# HG changeset patch # User bastiena # Date 1335530303 -7200 # Node ID 45c889eae324b4e07c25173e8c7059c4bbe98c28 # Parent fcf435874395f43e799d52162a08225566d6bf17 Front IDILL : Creation of the main parts of the 2 first Modes : MOSAIC : prezoom/preunzoom, zoom/unzoom. local mosaic developpement aborted and postponed for the late developpement parts. VIDEO : moving to a neighbour snapshot. diff -r fcf435874395 -r 45c889eae324 .hgignore --- a/.hgignore Thu Apr 19 11:53:06 2012 +0200 +++ b/.hgignore Fri Apr 27 14:38:23 2012 +0200 @@ -51,6 +51,8 @@ front_idill/extern/fajran-npTuioClient/TestClient/Release/ front_idill/extern/fajran-npTuioClient/TestClient/TestClient.vcxproj.user front_idill/extern/fajran-npTuioClient/TestClient/TestClient.vcxproj.filters +front_idill/src/snapshots-little/ +front_idill/src/snapshots/ syntax: regexp middleware/extern/.*/(bin|obj) middleware/src/bin/Debug/* diff -r fcf435874395 -r 45c889eae324 front_idill/extern/fajran-npTuioClient/.gitignore --- a/front_idill/extern/fajran-npTuioClient/.gitignore Thu Apr 19 11:53:06 2012 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,11 +0,0 @@ -*.o -*.swp -nptuio.so -Debug/ -Release/ -npTuioClient.ncb -npTuioClient.suo -npTuioClient.vcproj.* -npTuioClient.xcodeproj/*.mode1 -npTuioClient.xcodeproj/*.pbxuser -build/ diff -r fcf435874395 -r 45c889eae324 front_idill/extern/fajran-npTuioClient/English.lproj/InfoPlist.strings --- a/front_idill/extern/fajran-npTuioClient/English.lproj/InfoPlist.strings Thu Apr 19 11:53:06 2012 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,3 +0,0 @@ -/* Localized versions of Info.plist keys */ - -CFBundleName = "npTuioClient"; diff -r fcf435874395 -r 45c889eae324 front_idill/extern/fajran-npTuioClient/Info.plist --- a/front_idill/extern/fajran-npTuioClient/Info.plist Thu Apr 19 11:53:06 2012 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,42 +0,0 @@ - - - - - CFBundleDevelopmentRegion - English - CFBundleExecutable - npTuioClient - CFBundleIconFile - - CFBundleIdentifier - id.web.fajran.tuio - CFBundleInfoDictionaryVersion - 6.0 - CFBundlePackageType - BRPL - CFBundleShortVersionString - 1.0.1 - CFBundleSignature - ???? - CFBundleVersion - 0.2 - CSResourcesFileMapped - - WebPluginDescription - Tuio Client browser plugin - WebPluginMIMETypes - - application/x-tuio - - WebPluginExtensions - - tuio - - WebPluginTypeDescription - Tuio Client browser plugin - - - WebPluginName - npTuioClient - - diff -r fcf435874395 -r 45c889eae324 front_idill/extern/fajran-npTuioClient/LICENSE.txt --- a/front_idill/extern/fajran-npTuioClient/LICENSE.txt Thu Apr 19 11:53:06 2012 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,676 +0,0 @@ - - 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 fcf435874395 -r 45c889eae324 front_idill/extern/fajran-npTuioClient/Makefile --- a/front_idill/extern/fajran-npTuioClient/Makefile Thu Apr 19 11:53:06 2012 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,30 +0,0 @@ - -SRC= \ - ./TuioClient/oscpack/ip/IpEndpointName.cpp \ - ./TuioClient/oscpack/ip/posix/UdpSocket.cpp \ - ./TuioClient/oscpack/ip/posix/NetworkingUtils.cpp \ - ./TuioClient/oscpack/osc/OscPrintReceivedElements.cpp \ - ./TuioClient/oscpack/osc/OscReceivedElements.cpp \ - ./TuioClient/oscpack/osc/OscTypes.cpp \ - ./TuioClient/oscpack/osc/OscOutboundPacketStream.cpp \ - ./TuioClient/TuioClient.cpp \ - ./src/npn_gate.cpp \ - ./src/npp_gate.cpp \ - ./src/client.cpp \ - ./src/np_entry.cpp \ - ./src/plugin.cpp - -CC=g++ -BIN=npTuioClient.so - -CFLAGS=-Os -fPIC -I TuioClient/ -I TuioClient/oscpack/ -I npapi/ -I src/ -DOSC_HOST_LITTLE_ENDIAN -LDFLAGS=-lpthread - -all : ${BIN} - -clean : - rm ${BIN} - -${BIN} : ${SRC} - ${CC} -o $@ -shared ${CFLAGS} ${LDFLAGS} $+ - diff -r fcf435874395 -r 45c889eae324 front_idill/extern/fajran-npTuioClient/README.md --- a/front_idill/extern/fajran-npTuioClient/README.md Thu Apr 19 11:53:06 2012 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,98 +0,0 @@ -npTuioClient -============ - -npTuioClient is a TUIO Client implemented as an NPAPI-based browser -plugin. It uses [reacTIVision's](http://reactivision.sourceforge.net/) -TUIO Client as a base. - -The plugin constantly calls a javascript function `tuio_callback` -whenever a new touch event arrives. Having this function called, you -can start using javascript to manipulate HTML, Canvas, SVG, etc in -order to create a multi-touch application! - -Check the included examples to see how to use this plugin. Check also -[TUIOjs](http://github.com/fajran/tuiojs/tree/master) to see more -examples. - -The plugin has been tested and works on - -* Windows XP: Firefox 3.0.10, Google Chrome 2.0.172.33, and Safari 4.0. -* Linux (Ubuntu 8.04): Firefox 3.0.11 -* Mac OS X 10.4.11: Firefox 3.5rc3 and Safari 4.0 - -It doesn't work on Opera 9.64 on Windows XP nor Internet Explorer. - -To make the plugin works on Internet Explorer, the plugin has to be -ported (or wrapped) to an ActiveX-based plugin first. This is needed -since Internet Explorer doesn't support NPAPI-based plugin. - -Download --------- - -* [Windows](http://cloud.github.com/downloads/fajran/npTuioClient/npTuioClient-0.2-win.zip) -* [Linux](http://cloud.github.com/downloads/fajran/npTuioClient/npTuioClient-0.2-linux.tar.gz) (Ubuntu 8.04 i386) -* [Mac OS X](http://cloud.github.com/downloads/fajran/npTuioClient/npTuioClient-0.2-mac.zip) - -Compilation ------------ - -### Windows - -Open the Visual C++ project/solution file and build. I use Visual C++ -2008 Express Edition. - -### Linux - -Go to the project directory and type `make`. - -### Mac OS X - -Open the Xcode project and build. I use Xcode 2.5 under Mac OS X 10.4.11. - -Installation ------------- - -### Windows - -Put the plugin file `npTuioClient.dll` under Firefox'/Mozilla's -`plugin` directory. Mine is `C:\Program Files\Mozilla -Firefox\Plugins`. - -If you are using Google Chrome, put the plugin under -`C:\Users\\AppData\Local\Google\Chrome\Application\Plugins`. Create the -directory if necessary. - -### Linux - -Put the plugin file `npTuioClient.so` under `~/.mozilla/plugins`. - -### Mac OS X - -Put the plugin bundle `npTuioClient.plugin` under `~/Library/Internet Plug-Ins/`. - -Usage ------ - -Install the plugin, open one of the example files on your browser and -start using your multi-touch display! - -You can open multiple tabs or windows as long as they belong to the -same browser instance. The plugin can't be used from multiple browsers -at a time. This is because the TUIO Client library can only be started -once at a time. - -Issues ------- - -* Firefox on Mac OS X crashes when the plugin is unloaded (all pages - that use the plugin are closed). This doesn't happen on Safari 4.0. - - TODO: check plugin's shutfown and bundle unloading. - -* Firefox on Linux can't cleanly close the TUIO connection. So, the - browser has to be restarted if the plugin want to be loaded again. - - TODO: check TUIO Client's stop function. - - - diff -r fcf435874395 -r 45c889eae324 front_idill/extern/fajran-npTuioClient/TestClient/Test.cpp --- a/front_idill/extern/fajran-npTuioClient/TestClient/Test.cpp Thu Apr 19 11:53:06 2012 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,38 +0,0 @@ -/* - Modified by alexandre.bastien@iri.centrepompidou.fr to debug this project. -*/ - -#include -#include -#include -#include - -using namespace std; - -int main(int argc, char ** argv) -{ - /* get handle to dll */ - HINSTANCE hGetProcIDDLL = LoadLibrary((LPCWSTR)"npTuioClient.dll"); - - /* get pointer to the function in the dll*/ - FARPROC lpfnGetProcessID = GetProcAddress(HMODULE (hGetProcIDDLL),"tuio_start"); - FARPROC lpfnGetProcessID2 = GetProcAddress(HMODULE (hGetProcIDDLL),"tuio_stop"); - - /* - Define the Function in the DLL for reuse. This is just prototyping the dll's function. - A mock of it. Use "stdcall" for maximum compatibility. - */ - typedef int (__stdcall * pICFUNC)(void); - - pICFUNC t; - t = pICFUNC(lpfnGetProcessID); - - /* The actual call to the function contained in the dll */ - t(); - - /* Release the Dll */ - FreeLibrary(hGetProcIDDLL); - - system("PAUSE"); - return 0; -} \ No newline at end of file diff -r fcf435874395 -r 45c889eae324 front_idill/extern/fajran-npTuioClient/TestClient/TestClient.vcxproj --- a/front_idill/extern/fajran-npTuioClient/TestClient/TestClient.vcxproj Thu Apr 19 11:53:06 2012 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,82 +0,0 @@ - - - - - Debug - Win32 - - - Release - Win32 - - - - {FF6BDC4B-76DF-4C4F-8C83-FA442C38D5C2} - Win32Proj - TestClient - - - - Application - true - Unicode - - - Application - false - true - Unicode - - - - - - - - - - - - - true - - - false - - - - - - Level3 - Disabled - WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) - - - Console - true - - - - - Level3 - - - MaxSpeed - true - true - WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) - - - Console - true - true - true - - - - - - - - - \ No newline at end of file diff -r fcf435874395 -r 45c889eae324 front_idill/extern/fajran-npTuioClient/TuioClient/TuioClient.cpp --- a/front_idill/extern/fajran-npTuioClient/TuioClient/TuioClient.cpp Thu Apr 19 11:53:06 2012 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,643 +0,0 @@ -/* - TUIO C++ Library - part of the reacTIVision project - http://reactivision.sourceforge.net/ - - Copyright (c) 2005-2008 Martin Kaltenbrunner - - 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 2 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, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -/* - Modified by alexandre.bastien@iri.centrepompidou.fr to manage TUIO strings. -*/ - -#include "TuioClient.h" - -#ifndef WIN32 -static void* ThreadFunc( void* obj ) -#else -static DWORD WINAPI ThreadFunc( LPVOID obj ) -#endif -{ - static_cast(obj)->socket->Run(); - return 0; -}; - -using namespace std; - -TuioClient::TuioClient() { - TuioClient(3333); -} - -TuioClient::TuioClient(int port) { - try { - socket = new UdpListeningReceiveSocket(IpEndpointName( IpEndpointName::ANY_ADDRESS, port ), this ); - } catch (std::exception &e) { - std::cout << "could not bind to UDP port " << port << std::endl; - socket = NULL; - } - - if (socket!=NULL) { - if (!socket->IsBound()) { - delete socket; - socket = NULL; - } else std::cout << "listening to TUIO messages on UDP port " << port << std::endl; - } - - locked = false; - running = false; - currentFrame = lastFrame = maxFingerID = maxStringID = -1; -} - -TuioClient::~TuioClient() { - delete socket; -} - -void TuioClient::ProcessBundle( const ReceivedBundle& b, const IpEndpointName& remoteEndpoint) { - for( ReceivedBundle::const_iterator i = b.ElementsBegin(); i != b.ElementsEnd(); ++i ){ - if( i->IsBundle() ) - ProcessBundle( ReceivedBundle(*i), remoteEndpoint); - else - ProcessMessage( ReceivedMessage(*i), remoteEndpoint); - } -} - -void TuioClient::ProcessMessage( const ReceivedMessage& msg, const IpEndpointName& remoteEndpoint) -{ - try - { - ReceivedMessageArgumentStream args = msg.ArgumentStream(); - ReceivedMessage::const_iterator arg = msg.ArgumentsBegin(); - - if( strcmp( msg.AddressPattern(), "/tuio/2Dobj" ) == 0 ) - { - const char* cmd; - args >> cmd; - - if( strcmp( cmd, "set" ) == 0 ) - { - if ((currentFrame0)) return; - - int32 s_id, f_id; - float xpos, ypos, angle, xspeed, yspeed, rspeed, maccel, raccel; - - args >> s_id >> f_id >> xpos >> ypos >> angle >> xspeed >> yspeed >> rspeed >> maccel >> raccel >> EndMessage; - - std::list::iterator tobj; - for (tobj=objectList.begin(); tobj!= objectList.end(); tobj++) - if((*tobj)->getSessionID()==(long)s_id) break; - - if (tobj == objectList.end()) - { - - TuioObject *addObject = new TuioObject((long)s_id,(int)f_id,xpos,ypos,angle); - objectList.push_back(addObject); - - for (std::list::iterator listener=listenerList.begin(); listener != listenerList.end(); listener++) - (*listener)->addTuioObject(addObject); - - } - else if ( ((*tobj)->getX()!=xpos) || ((*tobj)->getY()!=ypos) || ((*tobj)->getAngle()!=angle) || ((*tobj)->getXSpeed()!=xspeed) || ((*tobj)->getYSpeed()!=yspeed) || ((*tobj)->getRotationSpeed()!=rspeed) || ((*tobj)->getMotionAccel()!=maccel) || ((*tobj)->getRotationAccel()!=raccel) ) - { - (*tobj)->update(xpos,ypos,angle,xspeed,yspeed,rspeed,maccel,raccel); - - for (std::list::iterator listener=listenerList.begin(); listener != listenerList.end(); listener++) - (*listener)->updateTuioObject((*tobj)); - } - } - else if( strcmp( cmd, "alive" ) == 0 ) - { - if ((currentFrame0)) return; - - int32 s_id; - while(!args.Eos()) - { - args >> s_id; - objectBuffer.push_back((long)s_id); - std::list::iterator iter; - iter = find(aliveObjectList.begin(), aliveObjectList.end(), (long)s_id); - if (iter != aliveObjectList.end()) aliveObjectList.erase(iter); - } - args >> EndMessage; - - std::list::iterator alive_iter; - for (alive_iter=aliveObjectList.begin(); alive_iter != aliveObjectList.end(); alive_iter++) - { - std::list::iterator tobj; - for (tobj=objectList.begin(); tobj!=objectList.end(); tobj++) - { - TuioObject *deleteObject = (*tobj); - if(deleteObject->getSessionID()==*alive_iter) - { - deleteObject->remove(); - for (std::list::iterator listener=listenerList.begin(); listener != listenerList.end(); listener++) - (*listener)->removeTuioObject(deleteObject); - objectList.erase(tobj); - delete deleteObject; - break; - } - } - } - aliveObjectList = objectBuffer; - objectBuffer.clear(); - } - else if( strcmp( cmd, "fseq" ) == 0 ) - { - if(currentFrame>0) lastFrame = currentFrame; - args >> currentFrame >> EndMessage; - - if ((currentFrame>=lastFrame) || (currentFrame<0)) - { - long currentTime = lastTime; - if (currentFrame>lastFrame) - { - currentTime = getCurrentTime()-startTime; - lastTime = currentTime; - } - - for (std::list::iterator refreshObject=objectList.begin(); refreshObject!=objectList.end(); refreshObject++) - if ((*refreshObject)->getUpdateTime()==TUIO_UNDEFINED) (*refreshObject)->setUpdateTime(currentTime); - - for (std::list::iterator listener=listenerList.begin(); listener!=listenerList.end(); listener++) - (*listener)->refresh(currentTime); - } - } - } - else if( strcmp( msg.AddressPattern(), "/tuio/3Dcur" ) == 0 ) - { - const char* cmd; - args >> cmd; - - if( strcmp( cmd, "set" ) == 0 ) - { - if ((currentFrame0)) return; - - int32 s_id; - float xpos, ypos, zpos, xspeed, yspeed, maccel; - //Modifié par alexandre.bastien@iri.centrepompidou.fr - args >> s_id >> xpos >> ypos >> zpos >> xspeed >> yspeed >> maccel >> EndMessage; - std::list::iterator tcur; - for (tcur=cursorList.begin(); tcur != cursorList.end(); tcur++) - if((*tcur)->getSessionID()==(long)s_id) break; - - if (tcur == cursorList.end()) - { - int f_id = (int)cursorList.size(); - if ((int)(cursorList.size())<=maxFingerID) - { - std::list::iterator closestCursor = freeCursorList.begin(); - //Modifié par alexandre.bastien@iri.centrepompidou.fr - for(std::list::iterator testCursor = freeCursorList.begin();testCursor!= freeCursorList.end(); testCursor++) - { - if((*testCursor)->getDistance(xpos,ypos,zpos)<(*closestCursor)->getDistance(xpos,ypos,zpos)) closestCursor = testCursor; - } - f_id = (*closestCursor)->getFingerID(); - freeCursorList.erase(closestCursor); - delete *closestCursor; - } - else maxFingerID = f_id; - //Modifié par alexandre.bastien@iri.centrepompidou.fr - TuioCursor *addCursor = new TuioCursor((long)s_id,f_id,xpos,ypos,zpos); - cursorList.push_back(addCursor); - - for (std::list::iterator listener=listenerList.begin(); listener != listenerList.end(); listener++) - (*listener)->addTuioCursor(addCursor); - - //Modifié par alexandre.bastien@iri.centrepompidou.fr - } - else if ( ((*tcur)->getX()!=xpos) || ((*tcur)->getY()!=ypos) || ((*tcur)->getZ()!=zpos) || ((*tcur)->getXSpeed()!=xspeed) || ((*tcur)->getYSpeed()!=yspeed) || ((*tcur)->getMotionAccel()!=maccel) ) - { - (*tcur)->update(xpos,ypos,zpos,xspeed,yspeed,maccel); - for (std::list::iterator listener=listenerList.begin(); listener != listenerList.end(); listener++) - (*listener)->updateTuioCursor((*tcur)); - } - } - else if( strcmp( cmd, "alive" ) == 0 ) - { - if ((currentFrame0)) return; - - int32 s_id; - while(!args.Eos()) - { - args >> s_id; - cursorBuffer.push_back((long)s_id); - std::list::iterator iter; - iter = find(aliveCursorList.begin(), aliveCursorList.end(), (long)s_id); - if (iter != aliveCursorList.end()) aliveCursorList.erase(iter); - } - args >> EndMessage; - std::list::iterator alive_iter; - for (alive_iter=aliveCursorList.begin(); alive_iter != aliveCursorList.end(); alive_iter++) - { - std::list::iterator tcur; - for (tcur=cursorList.begin(); tcur != cursorList.end(); tcur++) - { - TuioCursor *deleteCursor = (*tcur); - if(deleteCursor->getSessionID()==*alive_iter) - { - cursorList.erase(tcur); - deleteCursor->remove(); - for (std::list::iterator listener=listenerList.begin(); listener != listenerList.end(); listener++) - (*listener)->removeTuioCursor(deleteCursor); - - if (deleteCursor->getFingerID()==maxFingerID) - { - maxFingerID = -1; - delete deleteCursor; - - if (cursorList.size()>0) - { - std::list::iterator clist; - for (clist=cursorList.begin(); clist != cursorList.end(); clist++) - { - int f_id = (*clist)->getFingerID(); - if (f_id>maxFingerID) maxFingerID=f_id; - } - std::list::iterator flist; - for (flist=freeCursorList.begin(); flist != freeCursorList.end(); flist++) - { - TuioCursor *freeCursor = (*flist); - if (freeCursor->getFingerID()>maxFingerID) delete freeCursor; - else freeCursorBuffer.push_back(freeCursor); - } - freeCursorList = freeCursorBuffer; - freeCursorBuffer.clear(); - } - } - else if (deleteCursor->getFingerID()0) lastFrame = currentFrame; - args >> currentFrame >> EndMessage; - - if ((currentFrame>=lastFrame) || (currentFrame<0)) - { - long currentTime = lastTime; - if (currentFrame>lastFrame) - { - currentTime = getCurrentTime()-startTime; - lastTime = currentTime; - } - for (std::list::iterator refreshCursor=cursorList.begin(); refreshCursor!=cursorList.end(); refreshCursor++) - if ((*refreshCursor)->getUpdateTime()==TUIO_UNDEFINED) (*refreshCursor)->setUpdateTime(currentTime); - - for (std::list::iterator listener=listenerList.begin(); listener != listenerList.end(); listener++) - (*listener)->refresh(currentTime); - } - } - } - else if( strcmp( msg.AddressPattern(), "/tuio/_siP" ) == 0 ) - { - const char* cmd; - args >> cmd; - - if( strcmp( cmd, "set" ) == 0 ) - { - if ((currentFrame0)) return; - - int32 s_id; - const char* code; - args >> s_id >> code >> EndMessage; - std::list::iterator tstr; - for (tstr=stringList.begin(); tstr != stringList.end(); tstr++) - if((*tstr)->getSessionID()==(long)s_id) break; - - if (tstr == stringList.end()) - { - int s_id = (int)stringList.size();// - if ((int)(stringList.size())<=maxStringID)// - {// - std::list::iterator closestString = freeStringList.begin();// - //Modifié par alexandre.bastien@iri.centrepompidou.fr - - //for(std::list::iterator testString = freeStringList.begin();testString!= freeStringList.end(); testString++) - //{ - //if((*testString)->getDistance(xpos,ypos,zpos)<(*closestCursor)->getDistance(xpos,ypos,zpos)) closestCursor = testCursor; - //} - s_id = (*closestString)->getStringID();// - freeStringList.erase(closestString);// - delete *closestString;// - }// - else maxStringID = s_id;// - //Modifié par alexandre.bastien@iri.centrepompidou.fr - TuioString *addString = new TuioString((long)s_id,-1,code); - stringList.push_back(addString); - - for (std::list::iterator listener=listenerList.begin(); listener != listenerList.end(); listener++) - (*listener)->addTuioString(addString); - - //Modifié par alexandre.bastien@iri.centrepompidou.fr - } - else if ( ((*tstr)->getCode()!=code) ) - { - (*tstr)->update(code); - for (std::list::iterator listener=listenerList.begin(); listener != listenerList.end(); listener++) - (*listener)->updateTuioString((*tstr)); - } - } - else if( strcmp( cmd, "alive" ) == 0 ) - { - if ((currentFrame0)) return; - - int32 s_id; - while(!args.Eos()) - { - args >> s_id; - stringBuffer.push_back((long)s_id); - std::list::iterator iter; - iter = find(aliveStringList.begin(), aliveStringList.end(), (long)s_id); - if (iter != aliveStringList.end()) aliveStringList.erase(iter); - } - args >> EndMessage; - std::list::iterator alive_iter; - for (alive_iter=aliveStringList.begin(); alive_iter != aliveStringList.end(); alive_iter++) - { - std::list::iterator tstr; - for (tstr=stringList.begin(); tstr != stringList.end(); tstr++) - { - TuioString *deleteString = (*tstr); - if(deleteString->getSessionID()==*alive_iter) - { - stringList.erase(tstr); - deleteString->remove(); - for (std::list::iterator listener=listenerList.begin(); listener != listenerList.end(); listener++) - (*listener)->removeTuioString(deleteString); - - if (deleteString->getStringID()==maxStringID)// - {// - maxStringID = -1;// - delete deleteString; - - if (stringList.size()>0) - { - std::list::iterator clist;// - for (clist=stringList.begin(); clist != stringList.end(); clist++)// - {// - int s_id = (*clist)->getStringID();// - if (s_id>maxStringID) maxStringID=s_id;// - }// - std::list::iterator flist; - for (flist=freeStringList.begin(); flist != freeStringList.end(); flist++) - { - TuioString *freeString = (*flist); - if (freeString->getStringID()>maxStringID) delete freeString;// - else freeStringBuffer.push_back(freeString);// - freeStringBuffer.push_back(freeString); - } - freeStringList = freeStringBuffer; - freeStringBuffer.clear(); - } - }// - else if (deleteString->getStringID()0) lastFrame = currentFrame; - args >> currentFrame >> EndMessage; - - if ((currentFrame>=lastFrame) || (currentFrame<0)) - { - long currentTime = lastTime; - if (currentFrame>lastFrame) - { - currentTime = getCurrentTime()-startTime; - lastTime = currentTime; - } - for (std::list::iterator refreshString=stringList.begin(); refreshString!=stringList.end(); refreshString++) - if ((*refreshString)->getUpdateTime()==TUIO_UNDEFINED) (*refreshString)->setUpdateTime(currentTime); - - for (std::list::iterator listener=listenerList.begin(); listener != listenerList.end(); listener++) - (*listener)->refresh(currentTime); - } - } - } - //Ajouté par alexandre.bastien@iri.centrepompidou.fr - /*else if( strcmp( msg.AddressPattern(), "/tuio/_siP" ) == 0 ) - { - const char* cmd; - args >> cmd; - - if( strcmp( cmd, "set" ) == 0 ) - { - if ((currentFrame0)) return; - int32 s_id; - const char* code; - args >> s_id >> code >> EndMessage; - std::list::iterator tstr; - for (tstr=stringList.begin(); tstr != stringList.end(); tstr++) - if((*tstr)->getSessionID()==(long)s_id) break; - - if (tstr == stringList.end()) - { - TuioString *addString = new TuioString((long)s_id,code); - stringList.push_back(addString); - - for (std::list::iterator listener=listenerList.begin(); listener != listenerList.end(); listener++) - (*listener)->addTuioString(addString); - - - } - else if ( ((*tstr)->getCode()!=code) ) - { - (*tstr)->update(code); - for (std::list::iterator listener=listenerList.begin(); listener != listenerList.end(); listener++) - (*listener)->updateTuioString((*tstr)); - } - } - else if( strcmp( cmd, "alive" ) == 0 ) - { - if ((currentFrame0)) return; - - int32 s_id; - while(!args.Eos()) - { - args >> s_id; - stringBuffer.push_back((long)s_id); - std::list::iterator iter; - iter = find(aliveStringList.begin(), aliveStringList.end(), (long)s_id); - if (iter != aliveStringList.end()) aliveStringList.erase(iter); - } - args >> EndMessage; - - std::list::iterator alive_iter; - for (alive_iter=aliveStringList.begin(); alive_iter != aliveStringList.end(); alive_iter++) - { - std::list::iterator tstr; - for (tstr=stringList.begin(); tstr != stringList.end(); tstr++) - { - TuioString *deleteString = (*tstr); - if(deleteString->getSessionID()==*alive_iter) - { - stringList.erase(tstr); - deleteString->remove(); - for (std::list::iterator listener=listenerList.begin(); listener != listenerList.end(); listener++) - (*listener)->removeTuioString(deleteString); - - if (stringList.size()>0) - { - std::list::iterator flist; - for (flist=freeStringList.begin(); flist != freeStringList.end(); flist++) - { - TuioString *freeString = (*flist); - } - freeStringList = freeStringBuffer; - freeStringBuffer.clear(); - } - } - break; - } - } - aliveStringList = stringBuffer; - stringBuffer.clear(); - } - else if( strcmp( cmd, "fseq" ) == 0 ) - { - if(currentFrame>0) lastFrame = currentFrame; - args >> currentFrame >> EndMessage; - - if ((currentFrame>=lastFrame) || (currentFrame<0)) - { - long currentTime = lastTime; - if (currentFrame>lastFrame) - { - currentTime = getCurrentTime()-startTime; - lastTime = currentTime; - } - - for (std::list::iterator refreshString=stringList.begin(); refreshString!=stringList.end(); refreshString++) - if ((*refreshString)->getUpdateTime()==TUIO_UNDEFINED) (*refreshString)->setUpdateTime(currentTime); - - for (std::list::iterator listener=listenerList.begin(); listener != listenerList.end(); listener++) - (*listener)->refresh(currentTime); - } - } - }*/ - } - catch( Exception& e ) - { - std::cout << "error while parsing message: "<< msg.AddressPattern() << ": " << e.what() << "\n"; - } -} - -void TuioClient::ProcessPacket( const char *data, int size, const IpEndpointName& remoteEndpoint ) { - if (listenerList.size()==0) return; - ReceivedPacket p( data, size ); - if(p.IsBundle()) ProcessBundle( ReceivedBundle(p), remoteEndpoint); - else ProcessMessage( ReceivedMessage(p), remoteEndpoint); -} - -void TuioClient::start(bool lk) { - - if (socket==NULL) return; - - locked = lk; - if (!locked) { - #ifndef WIN32 - pthread_create(&thread , NULL, ThreadFunc, this); - #else - DWORD threadId; - thread = CreateThread( 0, 0, ThreadFunc, this, 0, &threadId ); - #endif - } else socket->Run(); - - startTime = getCurrentTime(); - lastTime = 0; - - running = true; -} - -void TuioClient::stop() { - - if (socket==NULL) return; - socket->Break(); - - if (!locked) { - #ifdef WIN32 - if( thread ) CloseHandle( thread ); - #endif - thread = 0; - locked = false; - } - running = false; -} - -void TuioClient::addTuioListener(TuioListener *listener) { - listenerList.push_back(listener); -} - -void TuioClient::removeTuioListener(TuioListener *listener) { - std::list::iterator result = find(listenerList.begin(),listenerList.end(),listener); - if (result!=listenerList.end()) listenerList.remove(listener); -} - -TuioObject* TuioClient::getTuioObject(long s_id) { - for (std::list::iterator iter=objectList.begin(); iter != objectList.end(); iter++) - if((*iter)->getSessionID()==s_id) return (*iter); - - return NULL; -} - -TuioCursor* TuioClient::getTuioCursor(long s_id) { - for (std::list::iterator iter=cursorList.begin(); iter != cursorList.end(); iter++) - if((*iter)->getSessionID()==s_id) return (*iter); - - return NULL; -} - -TuioString* TuioClient::getTuioString(long s_id) { - for (std::list::iterator iter=stringList.begin(); iter != stringList.end(); iter++) - if((*iter)->getSessionID()==s_id) return (*iter); - - return NULL; -} - -std::list TuioClient::getTuioObjects() { - return objectList; -} - -std::list TuioClient::getTuioCursors() { - return cursorList; -} - -std::list TuioClient::getTuioStrings() { - return stringList; -} - -long TuioClient::getCurrentTime() { - - #ifdef WIN32 - long timestamp = GetTickCount(); - #else - struct timeval tv; - struct timezone tz; - gettimeofday(&tv,&tz); - long timestamp = (tv.tv_sec*1000)+(tv.tv_usec/1000); - #endif - - return timestamp; -} diff -r fcf435874395 -r 45c889eae324 front_idill/extern/fajran-npTuioClient/TuioClient/TuioClient.h --- a/front_idill/extern/fajran-npTuioClient/TuioClient/TuioClient.h Thu Apr 19 11:53:06 2012 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,125 +0,0 @@ -/* - TUIO C++ Library - part of the reacTIVision project - http://reactivision.sourceforge.net/ - - Copyright (c) 2005-2008 Martin Kaltenbrunner - - 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 2 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, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -/* - Modified by alexandre.bastien@iri.centrepompidou.fr to manage TUIO strings. -*/ - -#ifndef INCLUDED_TUIOCLIENT_H -#define INCLUDED_TUIOCLIENT_H - -#ifndef WIN32 -#include -#include -#else -#include -#endif - -#include -#include -#include - -#include "osc/OscReceivedElements.h" -#include "osc/OscPrintReceivedElements.h" - -#include "ip/UdpSocket.h" -#include "ip/PacketListener.h" - -#include "TuioListener.h" -#include "TuioObject.h" -#include "TuioCursor.h" -#include "TuioString.h" - -using namespace osc; - -class TuioClient : public PacketListener { - - public: - TuioClient(); - TuioClient(int p); - ~TuioClient(); - - void start(bool lk=false); - void stop(); - bool isRunning() { return running; } - - - TuioObject* getTuioObject(long s_id); - TuioCursor* getTuioCursor(long s_id); - /* - * Ajouté par alexandre.bastien@iri.centrepompidou.fr - */ - TuioString* getTuioString(long s_id); - std::list getTuioObjects(); - std::list getTuioCursors(); - /* - * Ajouté par alexandre.bastien@iri.centrepompidou.fr - */ - std::list getTuioStrings(); - - void addTuioListener(TuioListener *listener); - void removeTuioListener(TuioListener *listener); - - void ProcessPacket( const char *data, int size, const IpEndpointName& remoteEndpoint ); - - UdpListeningReceiveSocket *socket; - - protected: - void ProcessBundle( const ReceivedBundle& b, const IpEndpointName& remoteEndpoint); - void ProcessMessage( const ReceivedMessage& m, const IpEndpointName& remoteEndpoint); - - private: - std::list listenerList; - - std::list objectList; - std::list aliveObjectList, objectBuffer; - std::list cursorList; - std::list aliveCursorList, cursorBuffer; - /* - * Ajouté par alexandre.bastien@iri.centrepompidou.fr - */ - std::list stringList; - std::list aliveStringList, stringBuffer; - - int32 currentFrame, lastFrame; - - long startTime; - long lastTime; - long getCurrentTime(); - - std::list freeCursorList, freeCursorBuffer; - /* - * Ajouté par alexandre.bastien@iri.centrepompidou.fr - */ - std::list freeStringList, freeStringBuffer; - int maxFingerID, maxStringID; - - #ifndef WIN32 - pthread_t thread; - #else - HANDLE thread; - #endif - - bool locked; - bool running; -}; - -#endif /* INCLUDED_TUIOCLIENT_H */ diff -r fcf435874395 -r 45c889eae324 front_idill/extern/fajran-npTuioClient/TuioClient/TuioContainer.h --- a/front_idill/extern/fajran-npTuioClient/TuioClient/TuioContainer.h Thu Apr 19 11:53:06 2012 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,169 +0,0 @@ -/* - TUIO C++ Library - part of the reacTIVision project - http://reactivision.sourceforge.net/ - - Copyright (c) 2005-2008 Martin Kaltenbrunner - - 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 2 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, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -/* - Modified by alexandre.bastien@iri.centrepompidou.fr to manage TUIO strings. -*/ - -#ifndef INCLUDED_TUIOCONTAINER_H -#define INCLUDED_TUIOCONTAINER_H - -#include -#include -#include "TuioPoint.h" -#include - -#define TUIO_ADDED 0 -#define TUIO_UPDATED 1 -#define TUIO_REMOVED 2 - -class TuioContainer: public TuioPoint { - - protected: - long session_id; - float xpos, ypos, zpos; - float x_speed, y_speed; - float motion_speed, motion_accel; - std::list path; - - int state; - - public: - TuioContainer (long s_id, float xpos, float ypos):TuioPoint(xpos,ypos) { - this->session_id = s_id; - this->x_speed = 0.0f; - this->y_speed = 0.0f; - this->motion_speed = 0.0f; - this->motion_accel = 0.0f; - TuioPoint p(xpos,ypos); - path.push_back(p); - - state = TUIO_ADDED; - }; - - /* - * Surchargé par alexandre.bastien@iri.centrepompidou.fr - */ - TuioContainer (long s_id, float xpos, float ypos, float zpos):TuioPoint(xpos,ypos,zpos) { - this->session_id = s_id; - this->x_speed = 0.0f; - this->y_speed = 0.0f; - this->motion_speed = 0.0f; - this->motion_accel = 0.0f; - TuioPoint p(xpos,ypos,zpos); - path.push_back(p); - - state = TUIO_ADDED; - }; - - /* - * Modifié par alexandre.bastien@iri.centrepompidou.fr - */ - TuioContainer (TuioContainer *tuioContainer):TuioPoint(tuioContainer) { - this->session_id = tuioContainer->getSessionID(); - this->x_speed = 0.0f; - this->y_speed = 0.0f; - this->motion_speed = 0.0f; - this->motion_accel = 0.0f; - TuioPoint p(xpos,ypos,zpos); - path.push_back(p); - - state = TUIO_ADDED; - }; - - virtual ~TuioContainer(){}; - - virtual void update (float xpos, float ypos,float xspeed, float yspeed,float maccel) { - TuioPoint::update(xpos, ypos); - this->x_speed = xspeed; - this->y_speed = yspeed; - this->motion_speed = (float)sqrt(xspeed*xspeed+yspeed*yspeed); - this->motion_accel = maccel; - TuioPoint p(xpos,ypos); - path.push_back(p); - - state = TUIO_UPDATED; - }; - - /* - * Surchargé par alexandre.bastien@iri.centrepompidou.fr - */ - virtual void update (float xpos, float ypos, float zpos, float xspeed, float yspeed,float maccel) { - TuioPoint::update(xpos, ypos, zpos); - this->x_speed = xspeed; - this->y_speed = yspeed; - this->motion_speed = (float)sqrt(xspeed*xspeed+yspeed*yspeed); - this->motion_accel = maccel; - TuioPoint p(xpos,ypos,zpos); - path.push_back(p); - - state = TUIO_UPDATED; - }; - - /* - * Modifié par alexandre.bastien@iri.centrepompidou.fr - */ - virtual void update (TuioContainer *tuioContainer) { - TuioPoint::update(tuioContainer); - this->x_speed = tuioContainer->getXSpeed(); - this->y_speed = tuioContainer->getYSpeed(); - this->motion_speed = tuioContainer->getMotionSpeed(); - this->motion_accel = tuioContainer->getMotionAccel(); - TuioPoint p(xpos,ypos,zpos); - path.push_back(p); - - state = TUIO_UPDATED; - }; - - virtual long getSessionID() { return session_id; }; - - /* - * Modifié par alexandre.bastien@iri.centrepompidou.fr - */ - virtual TuioPoint getPosition() { - TuioPoint p(xpos,ypos,zpos); - return p; - }; - - virtual std::list getPath() { - return path; - }; - - virtual void remove() { - state = TUIO_REMOVED; - timestamp = TUIO_UNDEFINED; - } - - virtual float getXSpeed() { return x_speed; }; - virtual float getYSpeed() { return y_speed; }; - virtual float getMotionSpeed() { return motion_speed; }; - virtual float getMotionAccel() { return motion_accel; }; - - virtual int getState() { return state; }; - virtual void setUpdateTime(long timestamp) { - this->timestamp = timestamp; - TuioPoint *lastPoint = &path.back(); - if (lastPoint!=NULL) lastPoint->setUpdateTime(timestamp); - }; - -}; - -#endif diff -r fcf435874395 -r 45c889eae324 front_idill/extern/fajran-npTuioClient/TuioClient/TuioCursor.h --- a/front_idill/extern/fajran-npTuioClient/TuioClient/TuioCursor.h Thu Apr 19 11:53:06 2012 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,60 +0,0 @@ -/* - TUIO C++ Library - part of the reacTIVision project - http://reactivision.sourceforge.net/ - - Copyright (c) 2005-2008 Martin Kaltenbrunner - - 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 2 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, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -/* - Modified by alexandre.bastien@iri.centrepompidou.fr to manage TUIO strings. -*/ - -#ifndef INCLUDED_TUIOCURSOR_H -#define INCLUDED_TUIOCURSOR_H - -#include -#include -#include "TuioContainer.h" - -class TuioCursor: public TuioContainer { - - protected: - int finger_id; - std::list path; - - public: - TuioCursor (long s_id, int f_id, float xpos, float ypos):TuioContainer(s_id,xpos,ypos) { - this->finger_id = f_id; - }; - - /* - * Surchargé par alexandre.bastien@iri.centrepompidou.fr - */ - TuioCursor (long s_id, int f_id, float xpos, float ypos, float zpos):TuioContainer(s_id,xpos,ypos,zpos) { - this->finger_id = f_id; - }; - - TuioCursor (TuioCursor *tuioCursor):TuioContainer(tuioCursor) { - this->finger_id = tuioCursor->getFingerID(); - }; - - ~TuioCursor(){}; - - int getFingerID() { return finger_id; }; -}; - -#endif diff -r fcf435874395 -r 45c889eae324 front_idill/extern/fajran-npTuioClient/TuioClient/TuioListener.h --- a/front_idill/extern/fajran-npTuioClient/TuioClient/TuioListener.h Thu Apr 19 11:53:06 2012 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,56 +0,0 @@ -/* - TUIO C++ Library - part of the reacTIVision project - http://reactivision.sourceforge.net/ - - Copyright (c) 2005-2008 Martin Kaltenbrunner - - 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 2 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, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -/* - Modified by alexandre.bastien@iri.centrepompidou.fr to manage TUIO strings. -*/ - -#ifndef INCLUDED_TUIOLISTENER_H -#define INCLUDED_TUIOLISTENER_H - -#include "TuioObject.h" -#include "TuioCursor.h" -#include "TuioString.h" - -class TuioListener { - - public: - virtual ~TuioListener(){}; - - virtual void addTuioObject(TuioObject *tuioObject)=0; - virtual void updateTuioObject(TuioObject *tuioObject)=0; - virtual void removeTuioObject(TuioObject *tuioObject)=0; - - virtual void addTuioCursor(TuioCursor *tuioCursor)=0; - virtual void updateTuioCursor(TuioCursor *tuioCursor)=0; - virtual void removeTuioCursor(TuioCursor *tuioCursor)=0; - - /* - * Ajouté par alexandre.bastien@iri.centrepompidou.fr - */ - virtual void addTuioString(TuioString *tuioString)=0; - virtual void updateTuioString(TuioString *tuioString)=0; - virtual void removeTuioString(TuioString *tuioString)=0; - - virtual void refresh(long timestamp)=0; -}; - -#endif /* INCLUDED_TUIOLISTENER_H */ diff -r fcf435874395 -r 45c889eae324 front_idill/extern/fajran-npTuioClient/TuioClient/TuioObject.h --- a/front_idill/extern/fajran-npTuioClient/TuioClient/TuioObject.h Thu Apr 19 11:53:06 2012 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,84 +0,0 @@ -/* - TUIO C++ Library - part of the reacTIVision project - http://reactivision.sourceforge.net/ - - Copyright (c) 2005-2008 Martin Kaltenbrunner - - 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 2 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, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -#ifndef INCLUDED_TUIOOBJECT_H -#define INCLUDED_TUIOOBJECT_H - -#ifndef M_PI -#define M_PI 3.14159265358979323846 -#endif - -#include -#include -#include "TuioContainer.h" - -class TuioObject: public TuioContainer { - - protected: - long session_id; - int fiducial_id; - float xpos, ypos, angle; - float x_speed, y_speed, motion_speed, motion_accel; - float rotation_speed, rotation_accel; - std::list path; - - public: - TuioObject (long s_id, int f_id, float xpos, float ypos, float angle):TuioContainer(s_id, xpos, ypos) { - this->fiducial_id = f_id; - this->angle = angle; - this->rotation_speed = 0.0f; - this->rotation_accel = 0.0f; - }; - - TuioObject (TuioObject *tuioObject):TuioContainer(tuioObject) { - this->fiducial_id = tuioObject->getFiducialID(); - this->angle = angle; - this->rotation_speed = 0.0f; - this->rotation_accel = 0.0f; - }; - - ~TuioObject() {}; - - void update (float xpos, float ypos, float angle, float xspeed, float yspeed, float rspeed, float maccel, float raccel) { - TuioContainer::update(xpos,ypos,xspeed,yspeed,maccel); - this->angle = angle; - this->rotation_speed = rspeed; - this->rotation_accel = raccel; - }; - - void update (TuioObject *tuioObject) { - TuioContainer::update(tuioObject); - this->angle = tuioObject->getAngle(); - this->rotation_speed = tuioObject->getRotationSpeed(); - this->rotation_accel = tuioObject->getRotationAccel(); - }; - - int getFiducialID() { return fiducial_id; }; - - float getAngle() { return angle; } - float getAngleDegrees() { return (float)(angle/M_PI*180); } - - float getRotationSpeed() { return rotation_speed; }; - float getRotationAccel() { return rotation_accel; }; - -}; - -#endif diff -r fcf435874395 -r 45c889eae324 front_idill/extern/fajran-npTuioClient/TuioClient/TuioPoint.h --- a/front_idill/extern/fajran-npTuioClient/TuioClient/TuioPoint.h Thu Apr 19 11:53:06 2012 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,155 +0,0 @@ -/* - TUIO C++ Library - part of the reacTIVision project - http://reactivision.sourceforge.net/ - - Copyright (c) 2005-2008 Martin Kaltenbrunner - - 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 2 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, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -#ifndef INCLUDED_TUIOPOINT_H -#define INCLUDED_TUIOPOINT_H - -#define TUIO_UNDEFINED -1 - -class TuioPoint { - - protected: - float xpos, ypos, zpos; - long timestamp; - - public: - TuioPoint (float xpos, float ypos) { - this->xpos = xpos; - this->ypos = ypos; - timestamp = TUIO_UNDEFINED; - }; - - /* - * Surchargé par alexandre.bastien@iri.centrepompidou.fr - */ - TuioPoint (float xpos, float ypos, float zpos) { - this->xpos = xpos; - this->ypos = ypos; - this->zpos = zpos; - timestamp = TUIO_UNDEFINED; - }; - - /* - * Modifié par alexandre.bastien@iri.centrepompidou.fr - */ - TuioPoint (TuioPoint *tuioPoint) { - this->xpos = tuioPoint->getX(); - this->ypos = tuioPoint->getY(); - this->zpos = tuioPoint->getZ(); - timestamp = TUIO_UNDEFINED; - }; - - ~TuioPoint(){}; - - /* - * Modifié par alexandre.bastien@iri.centrepompidou.fr - */ - void update (TuioPoint *tuioPoint) { - this->xpos = tuioPoint->getX(); - this->ypos = tuioPoint->getY(); - this->zpos = tuioPoint->getZ(); - timestamp = TUIO_UNDEFINED; - }; - - void update (float xpos, float ypos) { - this->xpos = xpos; - this->ypos = ypos; - timestamp = TUIO_UNDEFINED; - }; - - /* - * Surchargé par alexandre.bastien@iri.centrepompidou.fr - */ - void update (float xpos, float ypos, float zpos) { - this->xpos = xpos; - this->ypos = ypos; - this->zpos = zpos; - timestamp = TUIO_UNDEFINED; - }; - - float getX() { return xpos; }; - float getY() { return ypos; }; - /* - * Ajouté par alexandre.bastien@iri.centrepompidou.fr - */ - float getZ() { return zpos; }; - - float getDistance(float x, float y) { - float dx = xpos-x; - float dy = ypos-y; - return sqrtf(dx*dx+dy*dy); - } - - /* - * Surchargé par alexandre.bastien@iri.centrepompidou.fr - */ - float getDistance(float x, float y, float z) { - float dx = xpos-x; - float dy = ypos-y; - float dz = zpos-z; - return sqrtf(dx*dx+dy*dy+dz*dz); - } - - /* - * Modifié par alexandre.bastien@iri.centrepompidou.fr - */ - float getDistance(TuioPoint *tuioPoint) { - float dx = xpos-tuioPoint->getX(); - float dy = ypos-tuioPoint->getY(); - float dz = zpos-tuioPoint->getZ(); - return sqrtf(dx*dx+dy*dy+dz*dz); - } - - /* - * Modifié par alexandre.bastien@iri.centrepompidou.fr - */ - /*float getDistance3D(TuioPoint *tuioPoint) { - float dx = xpos-tuioPoint->getX(); - float dy = ypos-tuioPoint->getY(); - float dz = zpos-tuioPoint->getZ(); - return sqrtf(dx*dx+dy*dy+dz*dz); - }*/ - - float getAngle(TuioPoint *tuioPoint) { - - float side = tuioPoint->getX()-xpos; - float height = tuioPoint->getY()-ypos; - float distance = tuioPoint->getDistance(xpos,ypos); - - float angle = (float)(asin(side/distance)+M_PI/2); - if (height<0) angle = 2.0f*(float)M_PI-angle; - - return angle; - } - - float getAngleDegrees(TuioPoint *tuioPoint) { - return ((getAngle(tuioPoint)/(float)M_PI)*180.0f); - } - - float getScreenX(int w) { return xpos*w; }; - float getScreenY(int h) { return ypos*h; }; - - long getUpdateTime() { return timestamp; }; - void setUpdateTime(long timestamp) { this->timestamp = timestamp; }; - -}; - -#endif diff -r fcf435874395 -r 45c889eae324 front_idill/extern/fajran-npTuioClient/TuioClient/TuioString.h --- a/front_idill/extern/fajran-npTuioClient/TuioClient/TuioString.h Thu Apr 19 11:53:06 2012 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,57 +0,0 @@ -/* - Modified by alexandre.bastien@iri.centrepompidou.fr to manage TUIO strings. -*/ - -#ifndef INCLUDED_TUIOSTRING_H -#define INCLUDED_TUIOSTRING_H - -class TuioString { - - protected: - int session_id; - int string_id; - const char* code; - long timestamp; - int state; - - public: - TuioString (int s_id, int string_id, const char* _code) { - this->session_id = s_id; - this->string_id = string_id; - this->code = _code; - timestamp = TUIO_UNDEFINED; - state = TUIO_ADDED; - }; - - TuioString (TuioString *tuioString) { - this->session_id = tuioString->getSessionID(); - this->string_id = tuioString->getStringID(); - this->code = tuioString->getCode(); - timestamp = TUIO_UNDEFINED; - state = TUIO_ADDED; - }; - - ~TuioString(){}; - - int getSessionID() { return session_id; }; - int getStringID() { return string_id; }; - const char* getCode() { return code; }; - - - void update(const char* _code) - { - this->code = _code; - timestamp = TUIO_UNDEFINED; - state = TUIO_UPDATED; - } - - void remove() { - state = TUIO_REMOVED; - timestamp = TUIO_UNDEFINED; - } - - long getUpdateTime() { return timestamp; }; - void setUpdateTime(long timestamp) { this->timestamp = timestamp; }; -}; - -#endif diff -r fcf435874395 -r 45c889eae324 front_idill/extern/fajran-npTuioClient/TuioClient/oscpack/changes --- a/front_idill/extern/fajran-npTuioClient/TuioClient/oscpack/changes Thu Apr 19 11:53:06 2012 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,68 +0,0 @@ -September 28, 2005 ------------------- - -Compared to the previous official snapshot (November 2004) the -current version of oscpack includes a re-written set of network -classes and some changes to the syntax of the networking code. It no -longer uses threads, which means that you don't need to use sleep() -if you are writing a simple single-threaded server, or you need to -spawn your own threads in a more complex application. - -The list below summarises the changes if you are porting code from -the previous release. - - - there are no longer any threads in oscpack. if you need to - set up an asynchronous listener you can create your own thread - and call Run on an instance of SocketReceiveMultiplexer or - UdpListeningReceiveSocket (see ip/UdpSocket.h) yourself. - - - host byte order is now used for network (IP) addresses - - - functions which used to take two parameters - now take an instance of IpEndpointName (see - ip/IpEndpointName.h) this class has a number of convenient - constructors for converting numbers and strings to internet - addresses. For example there is one which takes a string and - another that take the dotted address components as separate - parameters. - - - The UdpTransmitPort class, formerly in UdpTransmitPort.h, is - now called UdpTransmitSocket, which is simply a convenience - class derived from UdpSocket (see ip/UdpSocket.h). Where you - used to use the constructor UdpTransmitPort( address, port) now - you can use UdpTransmitSocket( IpEndpointName( address, port ) - ) or you can any of the other possible ctors to IpEndpointName - () (see above). The Send() method is unchanged. - - - The packet listener base class is now located in - ip/PacketListener.h instead of PacketListenerPort.h. The - ProcessPacket method now has an additional parameter indicating - the remote endpoint - - - The preferred way to set up listeners is with - SocketReceiveMultiplexer (in ip/UdpSocket.h), this also allows - attaching periodic timers. For simple applications which only - listen to a single socket with no timers you can use - UdpListeningReceiveSocket (also in UdpSocket.h) See - osc/OscReceiveTest.cpp or osc/OscDump.cpp for examples of this. - This is more or less equivalent to the UdpPacketListenerPort - object in the old oscpack versions except that you need to - explicitly call Run() before it will start receiving packets - and it runs in the same thread, not a separate thread so Run() - won't usually return. - - - Explicit calls to InitializeNetworking() and - TerminateNetworking() are no longer required for simple - applications (more complex windows applications should - instantiate NetworkInitializer in main() or WinMain (see - ip/NetworkingUtils.h/.cpp) - - - The OscPacketListener base class (OscPacketListener.h) was - added to make traversing OSC packets easier, it handles bundle - traversal automatically so you only need to process messages in - your derived classes. - - - On Windows be sure to link with ws2_32.lib or you will see - a linker error about WSAEventSelect not being found. Also you - will need to link with winmm.lib for timeGetTime() - diff -r fcf435874395 -r 45c889eae324 front_idill/extern/fajran-npTuioClient/TuioClient/oscpack/ip/IpEndpointName.cpp --- a/front_idill/extern/fajran-npTuioClient/TuioClient/oscpack/ip/IpEndpointName.cpp Thu Apr 19 11:53:06 2012 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,81 +0,0 @@ -/* - oscpack -- Open Sound Control packet manipulation library - http://www.audiomulch.com/~rossb/oscpack - - Copyright (c) 2004-2005 Ross Bencina - - Permission is hereby granted, free of charge, to any person obtaining - a copy of this software and associated documentation files - (the "Software"), to deal in the Software without restriction, - including without limitation the rights to use, copy, modify, merge, - publish, distribute, sublicense, and/or sell copies of the Software, - and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be - included in all copies or substantial portions of the Software. - - Any person wishing to distribute modifications to the Software is - requested to send the modifications to the original developer so that - they can be incorporated into the canonical version. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR - ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF - CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -*/ -#include "IpEndpointName.h" - -#include - -#include "NetworkingUtils.h" - - -unsigned long IpEndpointName::GetHostByName( const char *s ) -{ - return ::GetHostByName(s); -} - - -void IpEndpointName::AddressAsString( char *s ) const -{ - if( address == ANY_ADDRESS ){ - sprintf( s, "" ); - }else{ - sprintf( s, "%d.%d.%d.%d", - (int)((address >> 24) & 0xFF), - (int)((address >> 16) & 0xFF), - (int)((address >> 8) & 0xFF), - (int)(address & 0xFF) ); - } -} - - -void IpEndpointName::AddressAndPortAsString( char *s ) const -{ - if( port == ANY_PORT ){ - if( address == ANY_ADDRESS ){ - sprintf( s, ":" ); - }else{ - sprintf( s, "%d.%d.%d.%d:", - (int)((address >> 24) & 0xFF), - (int)((address >> 16) & 0xFF), - (int)((address >> 8) & 0xFF), - (int)(address & 0xFF) ); - } - }else{ - if( address == ANY_ADDRESS ){ - sprintf( s, ":%d", port ); - }else{ - sprintf( s, "%d.%d.%d.%d:%d", - (int)((address >> 24) & 0xFF), - (int)((address >> 16) & 0xFF), - (int)((address >> 8) & 0xFF), - (int)(address & 0xFF), - (int)port ); - } - } -} diff -r fcf435874395 -r 45c889eae324 front_idill/extern/fajran-npTuioClient/TuioClient/oscpack/ip/IpEndpointName.h --- a/front_idill/extern/fajran-npTuioClient/TuioClient/oscpack/ip/IpEndpointName.h Thu Apr 19 11:53:06 2012 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,74 +0,0 @@ -/* - oscpack -- Open Sound Control packet manipulation library - http://www.audiomulch.com/~rossb/oscpack - - Copyright (c) 2004-2005 Ross Bencina - - Permission is hereby granted, free of charge, to any person obtaining - a copy of this software and associated documentation files - (the "Software"), to deal in the Software without restriction, - including without limitation the rights to use, copy, modify, merge, - publish, distribute, sublicense, and/or sell copies of the Software, - and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be - included in all copies or substantial portions of the Software. - - Any person wishing to distribute modifications to the Software is - requested to send the modifications to the original developer so that - they can be incorporated into the canonical version. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR - ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF - CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -*/ -#ifndef INCLUDED_IPENDPOINTNAME_H -#define INCLUDED_IPENDPOINTNAME_H - - -class IpEndpointName{ - static unsigned long GetHostByName( const char *s ); -public: - static const unsigned long ANY_ADDRESS = 0xFFFFFFFF; - static const int ANY_PORT = -1; - - IpEndpointName() - : address( ANY_ADDRESS ), port( ANY_PORT ) {} - IpEndpointName( int port_ ) - : address( ANY_ADDRESS ), port( port_ ) {} - IpEndpointName( unsigned long ipAddress_, int port_ ) - : address( ipAddress_ ), port( port_ ) {} - IpEndpointName( const char *addressName, int port_=ANY_PORT ) - : address( GetHostByName( addressName ) ) - , port( port_ ) {} - IpEndpointName( int addressA, int addressB, int addressC, int addressD, int port_=ANY_PORT ) - : address( ( (addressA << 24) | (addressB << 16) | (addressC << 8) | addressD ) ) - , port( port_ ) {} - - // address and port are maintained in host byte order here - unsigned long address; - int port; - - enum { ADDRESS_STRING_LENGTH=17 }; - void AddressAsString( char *s ) const; - - enum { ADDRESS_AND_PORT_STRING_LENGTH=23}; - void AddressAndPortAsString( char *s ) const; -}; - -inline bool operator==( const IpEndpointName& lhs, const IpEndpointName& rhs ) -{ - return (lhs.address == rhs.address && lhs.port == rhs.port ); -} - -inline bool operator!=( const IpEndpointName& lhs, const IpEndpointName& rhs ) -{ - return !(lhs == rhs); -} - -#endif /* INCLUDED_IPENDPOINTNAME_H */ diff -r fcf435874395 -r 45c889eae324 front_idill/extern/fajran-npTuioClient/TuioClient/oscpack/ip/NetworkingUtils.h --- a/front_idill/extern/fajran-npTuioClient/TuioClient/oscpack/ip/NetworkingUtils.h Thu Apr 19 11:53:06 2012 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,49 +0,0 @@ -/* - oscpack -- Open Sound Control packet manipulation library - http://www.audiomulch.com/~rossb/oscpack - - Copyright (c) 2004-2005 Ross Bencina - - Permission is hereby granted, free of charge, to any person obtaining - a copy of this software and associated documentation files - (the "Software"), to deal in the Software without restriction, - including without limitation the rights to use, copy, modify, merge, - publish, distribute, sublicense, and/or sell copies of the Software, - and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be - included in all copies or substantial portions of the Software. - - Any person wishing to distribute modifications to the Software is - requested to send the modifications to the original developer so that - they can be incorporated into the canonical version. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR - ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF - CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -*/ -#ifndef INCLUDED_NETWORKINGUTILS_H -#define INCLUDED_NETWORKINGUTILS_H - - -// in general NetworkInitializer is only used internally, but if you're -// application creates multiple sockets from different threads at runtime you -// should instantiate one of these in main just to make sure the networking -// layer is initialized. -class NetworkInitializer{ -public: - NetworkInitializer(); - ~NetworkInitializer(); -}; - - -// return ip address of host name in host byte order -unsigned long GetHostByName( const char *name ); - - -#endif /* INCLUDED_NETWORKINGUTILS_H */ diff -r fcf435874395 -r 45c889eae324 front_idill/extern/fajran-npTuioClient/TuioClient/oscpack/ip/PacketListener.h --- a/front_idill/extern/fajran-npTuioClient/TuioClient/oscpack/ip/PacketListener.h Thu Apr 19 11:53:06 2012 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,43 +0,0 @@ -/* - oscpack -- Open Sound Control packet manipulation library - http://www.audiomulch.com/~rossb/oscpack - - Copyright (c) 2004-2005 Ross Bencina - - Permission is hereby granted, free of charge, to any person obtaining - a copy of this software and associated documentation files - (the "Software"), to deal in the Software without restriction, - including without limitation the rights to use, copy, modify, merge, - publish, distribute, sublicense, and/or sell copies of the Software, - and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be - included in all copies or substantial portions of the Software. - - Any person wishing to distribute modifications to the Software is - requested to send the modifications to the original developer so that - they can be incorporated into the canonical version. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR - ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF - CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -*/ -#ifndef INCLUDED_PACKETLISTENER_H -#define INCLUDED_PACKETLISTENER_H - - -class IpEndpointName; - -class PacketListener{ -public: - virtual ~PacketListener() {} - virtual void ProcessPacket( const char *data, int size, - const IpEndpointName& remoteEndpoint ) = 0; -}; - -#endif /* INCLUDED_PACKETLISTENER_H */ diff -r fcf435874395 -r 45c889eae324 front_idill/extern/fajran-npTuioClient/TuioClient/oscpack/ip/TimerListener.h --- a/front_idill/extern/fajran-npTuioClient/TuioClient/oscpack/ip/TimerListener.h Thu Apr 19 11:53:06 2012 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,40 +0,0 @@ -/* - oscpack -- Open Sound Control packet manipulation library - http://www.audiomulch.com/~rossb/oscpack - - Copyright (c) 2004-2005 Ross Bencina - - Permission is hereby granted, free of charge, to any person obtaining - a copy of this software and associated documentation files - (the "Software"), to deal in the Software without restriction, - including without limitation the rights to use, copy, modify, merge, - publish, distribute, sublicense, and/or sell copies of the Software, - and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be - included in all copies or substantial portions of the Software. - - Any person wishing to distribute modifications to the Software is - requested to send the modifications to the original developer so that - they can be incorporated into the canonical version. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR - ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF - CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -*/ -#ifndef INCLUDED_TIMERLISTENER_H -#define INCLUDED_TIMERLISTENER_H - - -class TimerListener{ -public: - virtual ~TimerListener() {} - virtual void TimerExpired() = 0; -}; - -#endif /* INCLUDED_TIMERLISTENER_H */ diff -r fcf435874395 -r 45c889eae324 front_idill/extern/fajran-npTuioClient/TuioClient/oscpack/ip/UdpSocket.h --- a/front_idill/extern/fajran-npTuioClient/TuioClient/oscpack/ip/UdpSocket.h Thu Apr 19 11:53:06 2012 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,158 +0,0 @@ -/* - oscpack -- Open Sound Control packet manipulation library - http://www.audiomulch.com/~rossb/oscpack - - Copyright (c) 2004-2005 Ross Bencina - - Permission is hereby granted, free of charge, to any person obtaining - a copy of this software and associated documentation files - (the "Software"), to deal in the Software without restriction, - including without limitation the rights to use, copy, modify, merge, - publish, distribute, sublicense, and/or sell copies of the Software, - and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be - included in all copies or substantial portions of the Software. - - Any person wishing to distribute modifications to the Software is - requested to send the modifications to the original developer so that - they can be incorporated into the canonical version. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR - ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF - CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -*/ -#ifndef INCLUDED_UDPSOCKET_H -#define INCLUDED_UDPSOCKET_H - -#ifndef INCLUDED_NETWORKINGUTILITIES_H -#include "NetworkingUtils.h" -#endif /* INCLUDED_NETWORKINGUTILITIES_H */ - -#ifndef INCLUDED_IPENDPOINTNAME_H -#include "IpEndpointName.h" -#endif /* INCLUDED_IPENDPOINTNAME_H */ - - -class PacketListener; -class TimerListener; - -class UdpSocket; - -class SocketReceiveMultiplexer{ - class Implementation; - Implementation *impl_; - - friend class UdpSocket; - -public: - SocketReceiveMultiplexer(); - ~SocketReceiveMultiplexer(); - - // only call the attach/detach methods _before_ calling Run - - // only one listener per socket, each socket at most once - void AttachSocketListener( UdpSocket *socket, PacketListener *listener ); - void DetachSocketListener( UdpSocket *socket, PacketListener *listener ); - - void AttachPeriodicTimerListener( int periodMilliseconds, TimerListener *listener ); - void AttachPeriodicTimerListener( - int initialDelayMilliseconds, int periodMilliseconds, TimerListener *listener ); - void DetachPeriodicTimerListener( TimerListener *listener ); - - void Run(); // loop and block processing messages indefinitely - void RunUntilSigInt(); - void Break(); // call this from a listener to exit once the listener returns - void AsynchronousBreak(); // call this from another thread or signal handler to exit the Run() state -}; - - -class UdpSocket{ - class Implementation; - Implementation *impl_; - - friend class SocketReceiveMultiplexer::Implementation; - -public: - - // ctor throws std::runtime_error if there's a problem - // initializing the socket. - UdpSocket(); - virtual ~UdpSocket(); - - // the socket is created in an unbound, unconnected state - // such a socket can only be used to send to an arbitrary - // address using SendTo(). To use Send() you need to first - // connect to a remote endpoint using Connect(). To use - // ReceiveFrom you need to first bind to a local endpoint - // using Bind(). - - // retrieve the local endpoint name when sending to 'to' - IpEndpointName LocalEndpointFor( const IpEndpointName& remoteEndpoint ) const; - - // Connect to a remote endpoint which is used as the target - // for calls to Send() - void Connect( const IpEndpointName& remoteEndpoint ); - void Send( const char *data, int size ); - void SendTo( const IpEndpointName& remoteEndpoint, const char *data, int size ); - - - // Bind a local endpoint to receive incoming data. Endpoint - // can be 'any' for the system to choose an endpoint - void Bind( const IpEndpointName& localEndpoint ); - bool IsBound() const; - - int ReceiveFrom( IpEndpointName& remoteEndpoint, char *data, int size ); -}; - - -// convenience classes for transmitting and receiving -// they just call Connect and/or Bind in the ctor. -// note that you can still use a receive socket -// for transmitting etc - -class UdpTransmitSocket : public UdpSocket{ -public: - UdpTransmitSocket( const IpEndpointName& remoteEndpoint ) - { Connect( remoteEndpoint ); } -}; - - -class UdpReceiveSocket : public UdpSocket{ -public: - UdpReceiveSocket( const IpEndpointName& localEndpoint ) - { Bind( localEndpoint ); } -}; - - -// UdpListeningReceiveSocket provides a simple way to bind one listener -// to a single socket without having to manually set up a SocketReceiveMultiplexer - -class UdpListeningReceiveSocket : public UdpSocket{ - SocketReceiveMultiplexer mux_; - PacketListener *listener_; -public: - UdpListeningReceiveSocket( const IpEndpointName& localEndpoint, PacketListener *listener ) - : listener_( listener ) - { - Bind( localEndpoint ); - mux_.AttachSocketListener( this, listener_ ); - } - - ~UdpListeningReceiveSocket() - { mux_.DetachSocketListener( this, listener_ ); } - - // see SocketReceiveMultiplexer above for the behaviour of these methods... - void Run() { mux_.Run(); } - void RunUntilSigInt() { mux_.RunUntilSigInt(); } - void Break() { mux_.Break(); } - void AsynchronousBreak() { mux_.AsynchronousBreak(); } -}; - - -#endif /* INCLUDED_UDPSOCKET_H */ diff -r fcf435874395 -r 45c889eae324 front_idill/extern/fajran-npTuioClient/TuioClient/oscpack/ip/posix/NetworkingUtils.cpp --- a/front_idill/extern/fajran-npTuioClient/TuioClient/oscpack/ip/posix/NetworkingUtils.cpp Thu Apr 19 11:53:06 2012 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,57 +0,0 @@ -/* - oscpack -- Open Sound Control packet manipulation library - http://www.audiomulch.com/~rossb/oscpack - - Copyright (c) 2004-2005 Ross Bencina - - Permission is hereby granted, free of charge, to any person obtaining - a copy of this software and associated documentation files - (the "Software"), to deal in the Software without restriction, - including without limitation the rights to use, copy, modify, merge, - publish, distribute, sublicense, and/or sell copies of the Software, - and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be - included in all copies or substantial portions of the Software. - - Any person wishing to distribute modifications to the Software is - requested to send the modifications to the original developer so that - they can be incorporated into the canonical version. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR - ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF - CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -*/ -#include "ip/NetworkingUtils.h" - -#include -#include -#include -#include -#include - - - -NetworkInitializer::NetworkInitializer() {} - -NetworkInitializer::~NetworkInitializer() {} - - -unsigned long GetHostByName( const char *name ) -{ - unsigned long result = 0; - - struct hostent *h = gethostbyname( name ); - if( h ){ - struct in_addr a; - memcpy( &a, h->h_addr_list[0], h->h_length ); - result = ntohl(a.s_addr); - } - - return result; -} diff -r fcf435874395 -r 45c889eae324 front_idill/extern/fajran-npTuioClient/TuioClient/oscpack/ip/posix/UdpSocket.cpp --- a/front_idill/extern/fajran-npTuioClient/TuioClient/oscpack/ip/posix/UdpSocket.cpp Thu Apr 19 11:53:06 2012 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,549 +0,0 @@ -/* - oscpack -- Open Sound Control packet manipulation library - http://www.audiomulch.com/~rossb/oscpack - - Copyright (c) 2004-2005 Ross Bencina - - Permission is hereby granted, free of charge, to any person obtaining - a copy of this software and associated documentation files - (the "Software"), to deal in the Software without restriction, - including without limitation the rights to use, copy, modify, merge, - publish, distribute, sublicense, and/or sell copies of the Software, - and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be - included in all copies or substantial portions of the Software. - - Any person wishing to distribute modifications to the Software is - requested to send the modifications to the original developer so that - they can be incorporated into the canonical version. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR - ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF - CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -*/ -#include "ip/UdpSocket.h" - -#include -#include -#include -#include -#include -#include -#include -#include // for memset - -#include -#include -#include -#include -#include -#include -#include -#include -#include // for sockaddr_in - -#include "ip/PacketListener.h" -#include "ip/TimerListener.h" - - -#if defined(__APPLE__) && !defined(_SOCKLEN_T) -// pre system 10.3 didn have socklen_t -typedef ssize_t socklen_t; -#endif - - -static void SockaddrFromIpEndpointName( struct sockaddr_in& sockAddr, const IpEndpointName& endpoint ) -{ - memset( (char *)&sockAddr, 0, sizeof(sockAddr ) ); - sockAddr.sin_family = AF_INET; - - sockAddr.sin_addr.s_addr = - (endpoint.address == IpEndpointName::ANY_ADDRESS) - ? INADDR_ANY - : htonl( endpoint.address ); - - sockAddr.sin_port = - (endpoint.port == IpEndpointName::ANY_PORT) - ? 0 - : htons( endpoint.port ); -} - - -static IpEndpointName IpEndpointNameFromSockaddr( const struct sockaddr_in& sockAddr ) -{ - return IpEndpointName( - (sockAddr.sin_addr.s_addr == INADDR_ANY) - ? IpEndpointName::ANY_ADDRESS - : ntohl( sockAddr.sin_addr.s_addr ), - (sockAddr.sin_port == 0) - ? IpEndpointName::ANY_PORT - : ntohs( sockAddr.sin_port ) - ); -} - - -class UdpSocket::Implementation{ - bool isBound_; - bool isConnected_; - - int socket_; - struct sockaddr_in connectedAddr_; - struct sockaddr_in sendToAddr_; - -public: - - Implementation() - : isBound_( false ) - , isConnected_( false ) - , socket_( -1 ) - { - if( (socket_ = socket( AF_INET, SOCK_DGRAM, 0 )) == -1 ){ - throw std::runtime_error("unable to create udp socket\n"); - } - - memset( &sendToAddr_, 0, sizeof(sendToAddr_) ); - sendToAddr_.sin_family = AF_INET; - } - - ~Implementation() - { - if (socket_ != -1) close(socket_); - } - - IpEndpointName LocalEndpointFor( const IpEndpointName& remoteEndpoint ) const - { - assert( isBound_ ); - - // first connect the socket to the remote server - - struct sockaddr_in connectSockAddr; - SockaddrFromIpEndpointName( connectSockAddr, remoteEndpoint ); - - if (connect(socket_, (struct sockaddr *)&connectSockAddr, sizeof(connectSockAddr)) < 0) { - throw std::runtime_error("unable to connect udp socket\n"); - } - - // get the address - - struct sockaddr_in sockAddr; - memset( (char *)&sockAddr, 0, sizeof(sockAddr ) ); - socklen_t length = sizeof(sockAddr); - if (getsockname(socket_, (struct sockaddr *)&sockAddr, &length) < 0) { - throw std::runtime_error("unable to getsockname\n"); - } - - if( isConnected_ ){ - // reconnect to the connected address - - if (connect(socket_, (struct sockaddr *)&connectedAddr_, sizeof(connectedAddr_)) < 0) { - throw std::runtime_error("unable to connect udp socket\n"); - } - - }else{ - // unconnect from the remote address - - struct sockaddr_in unconnectSockAddr; - memset( (char *)&unconnectSockAddr, 0, sizeof(unconnectSockAddr ) ); - unconnectSockAddr.sin_family = AF_UNSPEC; - // address fields are zero - int connectResult = connect(socket_, (struct sockaddr *)&unconnectSockAddr, sizeof(unconnectSockAddr)); - if ( connectResult < 0 && errno != EAFNOSUPPORT ) { - throw std::runtime_error("unable to un-connect udp socket\n"); - } - } - - return IpEndpointNameFromSockaddr( sockAddr ); - } - - void Connect( const IpEndpointName& remoteEndpoint ) - { - SockaddrFromIpEndpointName( connectedAddr_, remoteEndpoint ); - - if (connect(socket_, (struct sockaddr *)&connectedAddr_, sizeof(connectedAddr_)) < 0) { - throw std::runtime_error("unable to connect udp socket\n"); - } - - isConnected_ = true; - } - - void Send( const char *data, int size ) - { - assert( isConnected_ ); - - send( socket_, data, size, 0 ); - } - - void SendTo( const IpEndpointName& remoteEndpoint, const char *data, int size ) - { - sendToAddr_.sin_addr.s_addr = htonl( remoteEndpoint.address ); - sendToAddr_.sin_port = htons( remoteEndpoint.port ); - - sendto( socket_, data, size, 0, (sockaddr*)&sendToAddr_, sizeof(sendToAddr_) ); - } - - void Bind( const IpEndpointName& localEndpoint ) - { - struct sockaddr_in bindSockAddr; - SockaddrFromIpEndpointName( bindSockAddr, localEndpoint ); - - if (bind(socket_, (struct sockaddr *)&bindSockAddr, sizeof(bindSockAddr)) < 0) { - throw std::runtime_error("unable to bind udp socket\n"); - } - - isBound_ = true; - } - - bool IsBound() const { return isBound_; } - - int ReceiveFrom( IpEndpointName& remoteEndpoint, char *data, int size ) - { - assert( isBound_ ); - - struct sockaddr_in fromAddr; - socklen_t fromAddrLen = sizeof(fromAddr); - - int result = recvfrom(socket_, data, size, 0, - (struct sockaddr *) &fromAddr, (socklen_t*)&fromAddrLen); - if( result < 0 ) - return 0; - - remoteEndpoint.address = ntohl(fromAddr.sin_addr.s_addr); - remoteEndpoint.port = ntohs(fromAddr.sin_port); - - return result; - } - - int Socket() { return socket_; } -}; - -UdpSocket::UdpSocket() -{ - impl_ = new Implementation(); -} - -UdpSocket::~UdpSocket() -{ - delete impl_; -} - -IpEndpointName UdpSocket::LocalEndpointFor( const IpEndpointName& remoteEndpoint ) const -{ - return impl_->LocalEndpointFor( remoteEndpoint ); -} - -void UdpSocket::Connect( const IpEndpointName& remoteEndpoint ) -{ - impl_->Connect( remoteEndpoint ); -} - -void UdpSocket::Send( const char *data, int size ) -{ - impl_->Send( data, size ); -} - -void UdpSocket::SendTo( const IpEndpointName& remoteEndpoint, const char *data, int size ) -{ - impl_->SendTo( remoteEndpoint, data, size ); -} - -void UdpSocket::Bind( const IpEndpointName& localEndpoint ) -{ - impl_->Bind( localEndpoint ); -} - -bool UdpSocket::IsBound() const -{ - return impl_->IsBound(); -} - -int UdpSocket::ReceiveFrom( IpEndpointName& remoteEndpoint, char *data, int size ) -{ - return impl_->ReceiveFrom( remoteEndpoint, data, size ); -} - - -struct AttachedTimerListener{ - AttachedTimerListener( int id, int p, TimerListener *tl ) - : initialDelayMs( id ) - , periodMs( p ) - , listener( tl ) {} - int initialDelayMs; - int periodMs; - TimerListener *listener; -}; - - -static bool CompareScheduledTimerCalls( - const std::pair< double, AttachedTimerListener > & lhs, const std::pair< double, AttachedTimerListener > & rhs ) -{ - return lhs.first < rhs.first; -} - - -SocketReceiveMultiplexer *multiplexerInstanceToAbortWithSigInt_ = 0; - -extern "C" /*static*/ void InterruptSignalHandler( int ); -/*static*/ void InterruptSignalHandler( int ) -{ - multiplexerInstanceToAbortWithSigInt_->AsynchronousBreak(); - signal( SIGINT, SIG_DFL ); -} - - -class SocketReceiveMultiplexer::Implementation{ - std::vector< std::pair< PacketListener*, UdpSocket* > > socketListeners_; - std::vector< AttachedTimerListener > timerListeners_; - - volatile bool break_; - int breakPipe_[2]; // [0] is the reader descriptor and [1] the writer - - double GetCurrentTimeMs() const - { - struct timeval t; - - gettimeofday( &t, 0 ); - - return ((double)t.tv_sec*1000.) + ((double)t.tv_usec / 1000.); - } - -public: - Implementation() - { - if( pipe(breakPipe_) != 0 ) - throw std::runtime_error( "creation of asynchronous break pipes failed\n" ); - } - - ~Implementation() - { - close( breakPipe_[0] ); - close( breakPipe_[1] ); - } - - void AttachSocketListener( UdpSocket *socket, PacketListener *listener ) - { - assert( std::find( socketListeners_.begin(), socketListeners_.end(), std::make_pair(listener, socket) ) == socketListeners_.end() ); - // we don't check that the same socket has been added multiple times, even though this is an error - socketListeners_.push_back( std::make_pair( listener, socket ) ); - } - - void DetachSocketListener( UdpSocket *socket, PacketListener *listener ) - { - std::vector< std::pair< PacketListener*, UdpSocket* > >::iterator i = - std::find( socketListeners_.begin(), socketListeners_.end(), std::make_pair(listener, socket) ); - assert( i != socketListeners_.end() ); - - socketListeners_.erase( i ); - } - - void AttachPeriodicTimerListener( int periodMilliseconds, TimerListener *listener ) - { - timerListeners_.push_back( AttachedTimerListener( periodMilliseconds, periodMilliseconds, listener ) ); - } - - void AttachPeriodicTimerListener( int initialDelayMilliseconds, int periodMilliseconds, TimerListener *listener ) - { - timerListeners_.push_back( AttachedTimerListener( initialDelayMilliseconds, periodMilliseconds, listener ) ); - } - - void DetachPeriodicTimerListener( TimerListener *listener ) - { - std::vector< AttachedTimerListener >::iterator i = timerListeners_.begin(); - while( i != timerListeners_.end() ){ - if( i->listener == listener ) - break; - ++i; - } - - assert( i != timerListeners_.end() ); - - timerListeners_.erase( i ); - } - - void Run() - { - break_ = false; - - // configure the master fd_set for select() - - fd_set masterfds, tempfds; - FD_ZERO( &masterfds ); - FD_ZERO( &tempfds ); - - // in addition to listening to the inbound sockets we - // also listen to the asynchronous break pipe, so that AsynchronousBreak() - // can break us out of select() from another thread. - FD_SET( breakPipe_[0], &masterfds ); - int fdmax = breakPipe_[0]; - - for( std::vector< std::pair< PacketListener*, UdpSocket* > >::iterator i = socketListeners_.begin(); - i != socketListeners_.end(); ++i ){ - - if( fdmax < i->second->impl_->Socket() ) - fdmax = i->second->impl_->Socket(); - FD_SET( i->second->impl_->Socket(), &masterfds ); - } - - - // configure the timer queue - double currentTimeMs = GetCurrentTimeMs(); - - // expiry time ms, listener - std::vector< std::pair< double, AttachedTimerListener > > timerQueue_; - for( std::vector< AttachedTimerListener >::iterator i = timerListeners_.begin(); - i != timerListeners_.end(); ++i ) - timerQueue_.push_back( std::make_pair( currentTimeMs + i->initialDelayMs, *i ) ); - std::sort( timerQueue_.begin(), timerQueue_.end(), CompareScheduledTimerCalls ); - - const int MAX_BUFFER_SIZE = 4098; - char *data = new char[ MAX_BUFFER_SIZE ]; - IpEndpointName remoteEndpoint; - - struct timeval timeout; - - while( !break_ ){ - tempfds = masterfds; - - struct timeval *timeoutPtr = 0; - if( !timerQueue_.empty() ){ - double timeoutMs = timerQueue_.front().first - GetCurrentTimeMs(); - if( timeoutMs < 0 ) - timeoutMs = 0; - - // 1000000 microseconds in a second - timeout.tv_sec = (long)(timeoutMs * .001); - timeout.tv_usec = (long)((timeoutMs - (timeout.tv_sec * 1000)) * 1000); - timeoutPtr = &timeout; - } - - if( select( fdmax + 1, &tempfds, 0, 0, timeoutPtr ) < 0 && errno != EINTR ){ - if (!break_) throw std::runtime_error("select failed\n"); - else break; - } - - if ( FD_ISSET( breakPipe_[0], &tempfds ) ){ - // clear pending data from the asynchronous break pipe - char c; - ssize_t ret; - ret = read( breakPipe_[0], &c, 1 ); - } - - if( break_ ) - break; - - for( std::vector< std::pair< PacketListener*, UdpSocket* > >::iterator i = socketListeners_.begin(); - i != socketListeners_.end(); ++i ){ - - if( FD_ISSET( i->second->impl_->Socket(), &tempfds ) ){ - - int size = i->second->ReceiveFrom( remoteEndpoint, data, MAX_BUFFER_SIZE ); - if( size > 0 ){ - i->first->ProcessPacket( data, size, remoteEndpoint ); - if( break_ ) - break; - } - } - } - - // execute any expired timers - currentTimeMs = GetCurrentTimeMs(); - bool resort = false; - for( std::vector< std::pair< double, AttachedTimerListener > >::iterator i = timerQueue_.begin(); - i != timerQueue_.end() && i->first <= currentTimeMs; ++i ){ - - i->second.listener->TimerExpired(); - if( break_ ) - break; - - i->first += i->second.periodMs; - resort = true; - } - if( resort ) - std::sort( timerQueue_.begin(), timerQueue_.end(), CompareScheduledTimerCalls ); - } - - delete [] data; - } - - void Break() - { - break_ = true; - } - - void AsynchronousBreak() - { - break_ = true; - - // Send a termination message to the asynchronous break pipe, so select() will return - ssize_t ret; - ret = write( breakPipe_[1], "!", 1 ); - } -}; - - - -SocketReceiveMultiplexer::SocketReceiveMultiplexer() -{ - impl_ = new Implementation(); -} - -SocketReceiveMultiplexer::~SocketReceiveMultiplexer() -{ - delete impl_; -} - -void SocketReceiveMultiplexer::AttachSocketListener( UdpSocket *socket, PacketListener *listener ) -{ - impl_->AttachSocketListener( socket, listener ); -} - -void SocketReceiveMultiplexer::DetachSocketListener( UdpSocket *socket, PacketListener *listener ) -{ - impl_->DetachSocketListener( socket, listener ); -} - -void SocketReceiveMultiplexer::AttachPeriodicTimerListener( int periodMilliseconds, TimerListener *listener ) -{ - impl_->AttachPeriodicTimerListener( periodMilliseconds, listener ); -} - -void SocketReceiveMultiplexer::AttachPeriodicTimerListener( int initialDelayMilliseconds, int periodMilliseconds, TimerListener *listener ) -{ - impl_->AttachPeriodicTimerListener( initialDelayMilliseconds, periodMilliseconds, listener ); -} - -void SocketReceiveMultiplexer::DetachPeriodicTimerListener( TimerListener *listener ) -{ - impl_->DetachPeriodicTimerListener( listener ); -} - -void SocketReceiveMultiplexer::Run() -{ - impl_->Run(); -} - -void SocketReceiveMultiplexer::RunUntilSigInt() -{ - assert( multiplexerInstanceToAbortWithSigInt_ == 0 ); /* at present we support only one multiplexer instance running until sig int */ - multiplexerInstanceToAbortWithSigInt_ = this; - signal( SIGINT, InterruptSignalHandler ); - impl_->Run(); - signal( SIGINT, SIG_DFL ); - multiplexerInstanceToAbortWithSigInt_ = 0; -} - -void SocketReceiveMultiplexer::Break() -{ - impl_->Break(); -} - -void SocketReceiveMultiplexer::AsynchronousBreak() -{ - impl_->AsynchronousBreak(); -} - diff -r fcf435874395 -r 45c889eae324 front_idill/extern/fajran-npTuioClient/TuioClient/oscpack/ip/win32/NetworkingUtils.cpp --- a/front_idill/extern/fajran-npTuioClient/TuioClient/oscpack/ip/win32/NetworkingUtils.cpp Thu Apr 19 11:53:06 2012 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,88 +0,0 @@ -/* - oscpack -- Open Sound Control packet manipulation library - http://www.audiomulch.com/~rossb/oscpack - - Copyright (c) 2004-2005 Ross Bencina - - Permission is hereby granted, free of charge, to any person obtaining - a copy of this software and associated documentation files - (the "Software"), to deal in the Software without restriction, - including without limitation the rights to use, copy, modify, merge, - publish, distribute, sublicense, and/or sell copies of the Software, - and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be - included in all copies or substantial portions of the Software. - - Any person wishing to distribute modifications to the Software is - requested to send the modifications to the original developer so that - they can be incorporated into the canonical version. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR - ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF - CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -*/ -#include "ip/NetworkingUtils.h" - -#include // this must come first to prevent errors with MSVC7 -#include -#include -#include - - -static LONG initCount_ = 0; -static bool winsockInitialized_ = false; - -NetworkInitializer::NetworkInitializer() -{ - if( InterlockedIncrement( &initCount_ ) == 1 ){ - // there is a race condition here if one thread tries to access - // the library while another is still initializing it. - // i can't think of an easy way to fix it so i'm telling you here - // incase you need to init the library from two threads at once. - // this is why the header file advises to instantiate one of these - // in main() so that the initialization happens globally - - // initialize winsock - WSAData wsaData; - int nCode = WSAStartup(MAKEWORD(1, 1), &wsaData); - if( nCode != 0 ){ - //std::cout << "WSAStartup() failed with error code " << nCode << "\n"; - }else{ - winsockInitialized_ = true; - } - } -} - - -NetworkInitializer::~NetworkInitializer() -{ - if( InterlockedDecrement( &initCount_ ) == 0 ){ - if( winsockInitialized_ ){ - WSACleanup(); - winsockInitialized_ = false; - } - } -} - - -unsigned long GetHostByName( const char *name ) -{ - NetworkInitializer networkInitializer; - - unsigned long result = 0; - - struct hostent *h = gethostbyname( name ); - if( h ){ - struct in_addr a; - memcpy( &a, h->h_addr_list[0], h->h_length ); - result = ntohl(a.s_addr); - } - - return result; -} diff -r fcf435874395 -r 45c889eae324 front_idill/extern/fajran-npTuioClient/TuioClient/oscpack/ip/win32/UdpSocket.cpp --- a/front_idill/extern/fajran-npTuioClient/TuioClient/oscpack/ip/win32/UdpSocket.cpp Thu Apr 19 11:53:06 2012 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,521 +0,0 @@ -/* - oscpack -- Open Sound Control packet manipulation library - http://www.audiomulch.com/~rossb/oscpack - - Copyright (c) 2004-2005 Ross Bencina - - Permission is hereby granted, free of charge, to any person obtaining - a copy of this software and associated documentation files - (the "Software"), to deal in the Software without restriction, - including without limitation the rights to use, copy, modify, merge, - publish, distribute, sublicense, and/or sell copies of the Software, - and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be - included in all copies or substantial portions of the Software. - - Any person wishing to distribute modifications to the Software is - requested to send the modifications to the original developer so that - they can be incorporated into the canonical version. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR - ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF - CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -*/ -#include "ip/UdpSocket.h" - -#include // this must come first to prevent errors with MSVC7 -#include -#include // for timeGetTime() - -#include -#include -#include -#include -#include - -#include "ip/NetworkingUtils.h" -#include "ip/PacketListener.h" -#include "ip/TimerListener.h" - - -typedef int socklen_t; - - -static void SockaddrFromIpEndpointName( struct sockaddr_in& sockAddr, const IpEndpointName& endpoint ) -{ - memset( (char *)&sockAddr, 0, sizeof(sockAddr ) ); - sockAddr.sin_family = AF_INET; - - sockAddr.sin_addr.s_addr = - (endpoint.address == IpEndpointName::ANY_ADDRESS) - ? INADDR_ANY - : htonl( endpoint.address ); - - sockAddr.sin_port = - (endpoint.port == IpEndpointName::ANY_PORT) - ? (short)0 - : htons( (short)endpoint.port ); -} - - -static IpEndpointName IpEndpointNameFromSockaddr( const struct sockaddr_in& sockAddr ) -{ - return IpEndpointName( - (sockAddr.sin_addr.s_addr == INADDR_ANY) - ? IpEndpointName::ANY_ADDRESS - : ntohl( sockAddr.sin_addr.s_addr ), - (sockAddr.sin_port == 0) - ? IpEndpointName::ANY_PORT - : ntohs( sockAddr.sin_port ) - ); -} - - -class UdpSocket::Implementation{ - NetworkInitializer networkInitializer_; - - bool isBound_; - bool isConnected_; - - SOCKET socket_; - struct sockaddr_in connectedAddr_; - struct sockaddr_in sendToAddr_; - -public: - - Implementation() - : isBound_( false ) - , isConnected_( false ) - , socket_( INVALID_SOCKET ) - { - if( (socket_ = socket( AF_INET, SOCK_DGRAM, 0 )) == INVALID_SOCKET ){ - throw std::runtime_error("unable to create udp socket\n"); - } - - memset( &sendToAddr_, 0, sizeof(sendToAddr_) ); - sendToAddr_.sin_family = AF_INET; - } - - ~Implementation() - { - if (socket_ != INVALID_SOCKET) closesocket(socket_); - } - - IpEndpointName LocalEndpointFor( const IpEndpointName& remoteEndpoint ) const - { - assert( isBound_ ); - - // first connect the socket to the remote server - - struct sockaddr_in connectSockAddr; - SockaddrFromIpEndpointName( connectSockAddr, remoteEndpoint ); - - if (connect(socket_, (struct sockaddr *)&connectSockAddr, sizeof(connectSockAddr)) < 0) { - throw std::runtime_error("unable to connect udp socket\n"); - } - - // get the address - - struct sockaddr_in sockAddr; - memset( (char *)&sockAddr, 0, sizeof(sockAddr ) ); - socklen_t length = sizeof(sockAddr); - if (getsockname(socket_, (struct sockaddr *)&sockAddr, &length) < 0) { - throw std::runtime_error("unable to getsockname\n"); - } - - if( isConnected_ ){ - // reconnect to the connected address - - if (connect(socket_, (struct sockaddr *)&connectedAddr_, sizeof(connectedAddr_)) < 0) { - throw std::runtime_error("unable to connect udp socket\n"); - } - - }else{ - // unconnect from the remote address - - struct sockaddr_in unconnectSockAddr; - SockaddrFromIpEndpointName( unconnectSockAddr, IpEndpointName() ); - - if( connect(socket_, (struct sockaddr *)&unconnectSockAddr, sizeof(unconnectSockAddr)) < 0 - && WSAGetLastError() != WSAEADDRNOTAVAIL ){ - throw std::runtime_error("unable to un-connect udp socket\n"); - } - } - - return IpEndpointNameFromSockaddr( sockAddr ); - } - - void Connect( const IpEndpointName& remoteEndpoint ) - { - SockaddrFromIpEndpointName( connectedAddr_, remoteEndpoint ); - - if (connect(socket_, (struct sockaddr *)&connectedAddr_, sizeof(connectedAddr_)) < 0) { - throw std::runtime_error("unable to connect udp socket\n"); - } - - isConnected_ = true; - } - - void Send( const char *data, int size ) - { - assert( isConnected_ ); - - send( socket_, data, size, 0 ); - } - - void SendTo( const IpEndpointName& remoteEndpoint, const char *data, int size ) - { - sendToAddr_.sin_addr.s_addr = htonl( remoteEndpoint.address ); - sendToAddr_.sin_port = htons( (short)remoteEndpoint.port ); - - sendto( socket_, data, size, 0, (sockaddr*)&sendToAddr_, sizeof(sendToAddr_) ); - } - - void Bind( const IpEndpointName& localEndpoint ) - { - struct sockaddr_in bindSockAddr; - SockaddrFromIpEndpointName( bindSockAddr, localEndpoint ); - - if (bind(socket_, (struct sockaddr *)&bindSockAddr, sizeof(bindSockAddr)) < 0) { - throw std::runtime_error("unable to bind udp socket\n"); - } - - isBound_ = true; - } - - bool IsBound() const { return isBound_; } - - int ReceiveFrom( IpEndpointName& remoteEndpoint, char *data, int size ) - { - assert( isBound_ ); - - struct sockaddr_in fromAddr; - socklen_t fromAddrLen = sizeof(fromAddr); - - int result = recvfrom(socket_, data, size, 0, - (struct sockaddr *) &fromAddr, (socklen_t*)&fromAddrLen); - if( result < 0 ) - return 0; - - remoteEndpoint.address = ntohl(fromAddr.sin_addr.s_addr); - remoteEndpoint.port = ntohs(fromAddr.sin_port); - - return result; - } - - SOCKET& Socket() { return socket_; } -}; - -UdpSocket::UdpSocket() -{ - impl_ = new Implementation(); -} - -UdpSocket::~UdpSocket() -{ - delete impl_; -} - -IpEndpointName UdpSocket::LocalEndpointFor( const IpEndpointName& remoteEndpoint ) const -{ - return impl_->LocalEndpointFor( remoteEndpoint ); -} - -void UdpSocket::Connect( const IpEndpointName& remoteEndpoint ) -{ - impl_->Connect( remoteEndpoint ); -} - -void UdpSocket::Send( const char *data, int size ) -{ - impl_->Send( data, size ); -} - -void UdpSocket::SendTo( const IpEndpointName& remoteEndpoint, const char *data, int size ) -{ - impl_->SendTo( remoteEndpoint, data, size ); -} - -void UdpSocket::Bind( const IpEndpointName& localEndpoint ) -{ - impl_->Bind( localEndpoint ); -} - -bool UdpSocket::IsBound() const -{ - return impl_->IsBound(); -} - -int UdpSocket::ReceiveFrom( IpEndpointName& remoteEndpoint, char *data, int size ) -{ - return impl_->ReceiveFrom( remoteEndpoint, data, size ); -} - - -struct AttachedTimerListener{ - AttachedTimerListener( int id, int p, TimerListener *tl ) - : initialDelayMs( id ) - , periodMs( p ) - , listener( tl ) {} - int initialDelayMs; - int periodMs; - TimerListener *listener; -}; - - -static bool CompareScheduledTimerCalls( - const std::pair< double, AttachedTimerListener > & lhs, const std::pair< double, AttachedTimerListener > & rhs ) -{ - return lhs.first < rhs.first; -} - - -SocketReceiveMultiplexer *multiplexerInstanceToAbortWithSigInt_ = 0; - -extern "C" /*static*/ void InterruptSignalHandler( int ); -/*static*/ void InterruptSignalHandler( int ) -{ - multiplexerInstanceToAbortWithSigInt_->AsynchronousBreak(); - signal( SIGINT, SIG_DFL ); -} - - -class SocketReceiveMultiplexer::Implementation{ - NetworkInitializer networkInitializer_; - - std::vector< std::pair< PacketListener*, UdpSocket* > > socketListeners_; - std::vector< AttachedTimerListener > timerListeners_; - - volatile bool break_; - HANDLE breakEvent_; - - double GetCurrentTimeMs() const - { - return timeGetTime(); // FIXME: bad choice if you want to run for more than 40 days - } - -public: - Implementation() - { - breakEvent_ = CreateEvent( NULL, FALSE, FALSE, NULL ); - } - - ~Implementation() - { - CloseHandle( breakEvent_ ); - } - - void AttachSocketListener( UdpSocket *socket, PacketListener *listener ) - { - assert( std::find( socketListeners_.begin(), socketListeners_.end(), std::make_pair(listener, socket) ) == socketListeners_.end() ); - // we don't check that the same socket has been added multiple times, even though this is an error - socketListeners_.push_back( std::make_pair( listener, socket ) ); - } - - void DetachSocketListener( UdpSocket *socket, PacketListener *listener ) - { - std::vector< std::pair< PacketListener*, UdpSocket* > >::iterator i = - std::find( socketListeners_.begin(), socketListeners_.end(), std::make_pair(listener, socket) ); - assert( i != socketListeners_.end() ); - - socketListeners_.erase( i ); - } - - void AttachPeriodicTimerListener( int periodMilliseconds, TimerListener *listener ) - { - timerListeners_.push_back( AttachedTimerListener( periodMilliseconds, periodMilliseconds, listener ) ); - } - - void AttachPeriodicTimerListener( int initialDelayMilliseconds, int periodMilliseconds, TimerListener *listener ) - { - timerListeners_.push_back( AttachedTimerListener( initialDelayMilliseconds, periodMilliseconds, listener ) ); - } - - void DetachPeriodicTimerListener( TimerListener *listener ) - { - std::vector< AttachedTimerListener >::iterator i = timerListeners_.begin(); - while( i != timerListeners_.end() ){ - if( i->listener == listener ) - break; - ++i; - } - - assert( i != timerListeners_.end() ); - - timerListeners_.erase( i ); - } - - void Run() - { - break_ = false; - - // prepare the window events which we use to wake up on incoming data - // we use this instead of select() primarily to support the AsyncBreak() - // mechanism. - - std::vector events( socketListeners_.size() + 1, 0 ); - int j=0; - for( std::vector< std::pair< PacketListener*, UdpSocket* > >::iterator i = socketListeners_.begin(); - i != socketListeners_.end(); ++i, ++j ){ - - HANDLE event = CreateEvent( NULL, FALSE, FALSE, NULL ); - WSAEventSelect( i->second->impl_->Socket(), event, FD_READ ); // note that this makes the socket non-blocking which is why we can safely call RecieveFrom() on all sockets below - events[j] = event; - } - - - events[ socketListeners_.size() ] = breakEvent_; // last event in the collection is the break event - - - // configure the timer queue - double currentTimeMs = GetCurrentTimeMs(); - - // expiry time ms, listener - std::vector< std::pair< double, AttachedTimerListener > > timerQueue_; - for( std::vector< AttachedTimerListener >::iterator i = timerListeners_.begin(); - i != timerListeners_.end(); ++i ) - timerQueue_.push_back( std::make_pair( currentTimeMs + i->initialDelayMs, *i ) ); - std::sort( timerQueue_.begin(), timerQueue_.end(), CompareScheduledTimerCalls ); - - const int MAX_BUFFER_SIZE = 4098; - char *data = new char[ MAX_BUFFER_SIZE ]; - IpEndpointName remoteEndpoint; - - while( !break_ ){ - - double currentTimeMs = GetCurrentTimeMs(); - - DWORD waitTime = INFINITE; - if( !timerQueue_.empty() ){ - - waitTime = (DWORD)( timerQueue_.front().first >= currentTimeMs - ? timerQueue_.front().first - currentTimeMs - : 0 ); - } - - DWORD waitResult = WaitForMultipleObjects( (DWORD)socketListeners_.size() + 1, &events[0], FALSE, waitTime ); - if( break_ ) - break; - - if( waitResult != WAIT_TIMEOUT ){ - for( int i = waitResult - WAIT_OBJECT_0; i < (int)socketListeners_.size(); ++i ){ - int size = socketListeners_[i].second->ReceiveFrom( remoteEndpoint, data, MAX_BUFFER_SIZE ); - if( size > 0 ){ - socketListeners_[i].first->ProcessPacket( data, size, remoteEndpoint ); - if( break_ ) - break; - } - } - } - - // execute any expired timers - currentTimeMs = GetCurrentTimeMs(); - bool resort = false; - for( std::vector< std::pair< double, AttachedTimerListener > >::iterator i = timerQueue_.begin(); - i != timerQueue_.end() && i->first <= currentTimeMs; ++i ){ - - i->second.listener->TimerExpired(); - if( break_ ) - break; - - i->first += i->second.periodMs; - resort = true; - } - if( resort ) - std::sort( timerQueue_.begin(), timerQueue_.end(), CompareScheduledTimerCalls ); - } - - delete [] data; - - // free events - j = 0; - for( std::vector< std::pair< PacketListener*, UdpSocket* > >::iterator i = socketListeners_.begin(); - i != socketListeners_.end(); ++i, ++j ){ - - WSAEventSelect( i->second->impl_->Socket(), events[j], 0 ); // remove association between socket and event - CloseHandle( events[j] ); - unsigned long enableNonblocking = 0; - ioctlsocket( i->second->impl_->Socket(), FIONBIO, &enableNonblocking ); // make the socket blocking again - } - } - - void Break() - { - break_ = true; - } - - void AsynchronousBreak() - { - break_ = true; - SetEvent( breakEvent_ ); - } -}; - - - -SocketReceiveMultiplexer::SocketReceiveMultiplexer() -{ - impl_ = new Implementation(); -} - -SocketReceiveMultiplexer::~SocketReceiveMultiplexer() -{ - delete impl_; -} - -void SocketReceiveMultiplexer::AttachSocketListener( UdpSocket *socket, PacketListener *listener ) -{ - impl_->AttachSocketListener( socket, listener ); -} - -void SocketReceiveMultiplexer::DetachSocketListener( UdpSocket *socket, PacketListener *listener ) -{ - impl_->DetachSocketListener( socket, listener ); -} - -void SocketReceiveMultiplexer::AttachPeriodicTimerListener( int periodMilliseconds, TimerListener *listener ) -{ - impl_->AttachPeriodicTimerListener( periodMilliseconds, listener ); -} - -void SocketReceiveMultiplexer::AttachPeriodicTimerListener( int initialDelayMilliseconds, int periodMilliseconds, TimerListener *listener ) -{ - impl_->AttachPeriodicTimerListener( initialDelayMilliseconds, periodMilliseconds, listener ); -} - -void SocketReceiveMultiplexer::DetachPeriodicTimerListener( TimerListener *listener ) -{ - impl_->DetachPeriodicTimerListener( listener ); -} - -void SocketReceiveMultiplexer::Run() -{ - impl_->Run(); -} - -void SocketReceiveMultiplexer::RunUntilSigInt() -{ - assert( multiplexerInstanceToAbortWithSigInt_ == 0 ); /* at present we support only one multiplexer instance running until sig int */ - multiplexerInstanceToAbortWithSigInt_ = this; - signal( SIGINT, InterruptSignalHandler ); - impl_->Run(); - signal( SIGINT, SIG_DFL ); - multiplexerInstanceToAbortWithSigInt_ = 0; -} - -void SocketReceiveMultiplexer::Break() -{ - impl_->Break(); -} - -void SocketReceiveMultiplexer::AsynchronousBreak() -{ - impl_->AsynchronousBreak(); -} - diff -r fcf435874395 -r 45c889eae324 front_idill/extern/fajran-npTuioClient/TuioClient/oscpack/license --- a/front_idill/extern/fajran-npTuioClient/TuioClient/oscpack/license Thu Apr 19 11:53:06 2012 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,28 +0,0 @@ -oscpack -- Open Sound Control packet manipulation library -http://www.audiomulch.com/~rossb/code/oscpack - -Copyright (c) 2004 Ross Bencina - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files -(the "Software"), to deal in the Software without restriction, -including without limitation the rights to use, copy, modify, merge, -publish, distribute, sublicense, and/or sell copies of the Software, -and to permit persons to whom the Software is furnished to do so, -subject to the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -Any person wishing to distribute modifications to the Software is -requested to send the modifications to the original developer so that -they can be incorporated into the canonical version. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR -ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF -CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - diff -r fcf435874395 -r 45c889eae324 front_idill/extern/fajran-npTuioClient/TuioClient/oscpack/osc/MessageMappingOscPacketListener.h --- a/front_idill/extern/fajran-npTuioClient/TuioClient/oscpack/osc/MessageMappingOscPacketListener.h Thu Apr 19 11:53:06 2012 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,73 +0,0 @@ -/* - oscpack -- Open Sound Control packet manipulation library - http://www.audiomulch.com/~rossb/oscpack - - Copyright (c) 2004-2005 Ross Bencina - - Permission is hereby granted, free of charge, to any person obtaining - a copy of this software and associated documentation files - (the "Software"), to deal in the Software without restriction, - including without limitation the rights to use, copy, modify, merge, - publish, distribute, sublicense, and/or sell copies of the Software, - and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be - included in all copies or substantial portions of the Software. - - Any person wishing to distribute modifications to the Software is - requested to send the modifications to the original developer so that - they can be incorporated into the canonical version. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR - ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF - CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -*/ -#ifndef INCLUDED_MESSAGEMAPPINGOSCPACKETLISTENER_H -#define INCLUDED_MESSAGEMAPPINGOSCPACKETLISTENER_H - -#include -#include - -#include "OscPacketListener.h" - - - -namespace osc{ - -template< class T > -class MessageMappingOscPacketListener : public OscPacketListener{ -public: - typedef void (T::*function_type)(const osc::ReceivedMessage&, const IpEndpointName&); - -protected: - void RegisterMessageFunction( const char *addressPattern, function_type f ) - { - functions_.insert( std::make_pair( addressPattern, f ) ); - } - - virtual void ProcessMessage( const osc::ReceivedMessage& m, - const IpEndpointName& remoteEndpoint ) - { - typename function_map_type::iterator i = functions_.find( m.AddressPattern() ); - if( i != functions_.end() ) - (dynamic_cast(this)->*(i->second))( m, remoteEndpoint ); - } - -private: - struct cstr_compare{ - bool operator()( const char *lhs, const char *rhs ) const - { return strcmp( lhs, rhs ) < 0; } - }; - - typedef std::map function_map_type; - function_map_type functions_; -}; - -} // namespace osc - -#endif /* INCLUDED_MESSAGEMAPPINGOSCPACKETLISTENER_H */ \ No newline at end of file diff -r fcf435874395 -r 45c889eae324 front_idill/extern/fajran-npTuioClient/TuioClient/oscpack/osc/OscException.h --- a/front_idill/extern/fajran-npTuioClient/TuioClient/oscpack/osc/OscException.h Thu Apr 19 11:53:06 2012 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,54 +0,0 @@ -/* - oscpack -- Open Sound Control packet manipulation library - http://www.audiomulch.com/~rossb/oscpack - - Copyright (c) 2004-2005 Ross Bencina - - Permission is hereby granted, free of charge, to any person obtaining - a copy of this software and associated documentation files - (the "Software"), to deal in the Software without restriction, - including without limitation the rights to use, copy, modify, merge, - publish, distribute, sublicense, and/or sell copies of the Software, - and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be - included in all copies or substantial portions of the Software. - - Any person wishing to distribute modifications to the Software is - requested to send the modifications to the original developer so that - they can be incorporated into the canonical version. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR - ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF - CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -*/ -#ifndef INCLUDED_OSC_EXCEPTION_H -#define INCLUDED_OSC_EXCEPTION_H - -#include - -namespace osc{ - -class Exception : public std::exception { - const char *what_; - -public: - Exception() throw() {} - Exception( const Exception& src ) throw() - : what_( src.what_ ) {} - Exception( const char *w ) throw() - : what_( w ) {} - Exception& operator=( const Exception& src ) throw() - { what_ = src.what_; return *this; } - virtual ~Exception() throw() {} - virtual const char* what() const throw() { return what_; } -}; - -} // namespace osc - -#endif /* INCLUDED_OSC_EXCEPTION_H */ diff -r fcf435874395 -r 45c889eae324 front_idill/extern/fajran-npTuioClient/TuioClient/oscpack/osc/OscHostEndianness.h --- a/front_idill/extern/fajran-npTuioClient/TuioClient/oscpack/osc/OscHostEndianness.h Thu Apr 19 11:53:06 2012 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,69 +0,0 @@ -/* - oscpack -- Open Sound Control packet manipulation library - http://www.audiomulch.com/~rossb/oscpack - - Copyright (c) 2004-2005 Ross Bencina - - Permission is hereby granted, free of charge, to any person obtaining - a copy of this software and associated documentation files - (the "Software"), to deal in the Software without restriction, - including without limitation the rights to use, copy, modify, merge, - publish, distribute, sublicense, and/or sell copies of the Software, - and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be - included in all copies or substantial portions of the Software. - - Any person wishing to distribute modifications to the Software is - requested to send the modifications to the original developer so that - they can be incorporated into the canonical version. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR - ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF - CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -*/ -#ifndef OSC_HOSTENDIANNESS_H -#define OSC_HOSTENDIANNESS_H - -/* - Make sure either OSC_HOST_LITTLE_ENDIAN or OSC_HOST_BIG_ENDIAN is defined - - If you know a way to enhance the detection below for Linux and/or MacOSX - please let me know! I've tried a few things which don't work. -*/ - -#if defined(OSC_HOST_LITTLE_ENDIAN) || defined(OSC_HOST_BIG_ENDIAN) - -// you can define one of the above symbols from the command line -// then you don't have to edit this file. - -#elif defined(__WIN32__) || defined(WIN32) - -// assume that __WIN32__ is only defined on little endian systems - -#define OSC_HOST_LITTLE_ENDIAN 1 -#undef OSC_HOST_BIG_ENDIAN - -#elif defined(__APPLE__) - -#if defined(__LITTLE_ENDIAN__) -#define OSC_HOST_LITTLE_ENDIAN 1 -#undef OSC_HOST_BIG_ENDIAN -#else -#define OSC_HOST_BIG_ENDIAN 1 -#undef OSC_HOST_LITTLE_ENDIAN -#endif - -#else - -#error please edit OSCHostEndianness.h to configure endianness - -#endif - -#endif /* OSC_HOSTENDIANNESS_H */ - diff -r fcf435874395 -r 45c889eae324 front_idill/extern/fajran-npTuioClient/TuioClient/oscpack/osc/OscOutboundPacketStream.cpp --- a/front_idill/extern/fajran-npTuioClient/TuioClient/oscpack/osc/OscOutboundPacketStream.cpp Thu Apr 19 11:53:06 2012 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,639 +0,0 @@ -/* - oscpack -- Open Sound Control packet manipulation library - http://www.audiomulch.com/~rossb/oscpack - - Copyright (c) 2004-2005 Ross Bencina - - Permission is hereby granted, free of charge, to any person obtaining - a copy of this software and associated documentation files - (the "Software"), to deal in the Software without restriction, - including without limitation the rights to use, copy, modify, merge, - publish, distribute, sublicense, and/or sell copies of the Software, - and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be - included in all copies or substantial portions of the Software. - - Any person wishing to distribute modifications to the Software is - requested to send the modifications to the original developer so that - they can be incorporated into the canonical version. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR - ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF - CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -*/ -#include "OscOutboundPacketStream.h" - -#include -#include -#include - -#if defined(__WIN32__) || defined(WIN32) -#include // for alloca -#endif - -#include "OscHostEndianness.h" - - -namespace osc{ - -static void FromInt32( char *p, int32 x ) -{ -#ifdef OSC_HOST_LITTLE_ENDIAN - union{ - osc::int32 i; - char c[4]; - } u; - - u.i = x; - - p[3] = u.c[0]; - p[2] = u.c[1]; - p[1] = u.c[2]; - p[0] = u.c[3]; -#else - *reinterpret_cast(p) = x; -#endif -} - - -static void FromUInt32( char *p, uint32 x ) -{ -#ifdef OSC_HOST_LITTLE_ENDIAN - union{ - osc::uint32 i; - char c[4]; - } u; - - u.i = x; - - p[3] = u.c[0]; - p[2] = u.c[1]; - p[1] = u.c[2]; - p[0] = u.c[3]; -#else - *reinterpret_cast(p) = x; -#endif -} - - -static void FromInt64( char *p, int64 x ) -{ -#ifdef OSC_HOST_LITTLE_ENDIAN - union{ - osc::int64 i; - char c[8]; - } u; - - u.i = x; - - p[7] = u.c[0]; - p[6] = u.c[1]; - p[5] = u.c[2]; - p[4] = u.c[3]; - p[3] = u.c[4]; - p[2] = u.c[5]; - p[1] = u.c[6]; - p[0] = u.c[7]; -#else - *reinterpret_cast(p) = x; -#endif -} - - -static void FromUInt64( char *p, uint64 x ) -{ -#ifdef OSC_HOST_LITTLE_ENDIAN - union{ - osc::uint64 i; - char c[8]; - } u; - - u.i = x; - - p[7] = u.c[0]; - p[6] = u.c[1]; - p[5] = u.c[2]; - p[4] = u.c[3]; - p[3] = u.c[4]; - p[2] = u.c[5]; - p[1] = u.c[6]; - p[0] = u.c[7]; -#else - *reinterpret_cast(p) = x; -#endif -} - - -static inline long RoundUp4( long x ) -{ - return ((x-1) & (~0x03L)) + 4; -} - - -OutboundPacketStream::OutboundPacketStream( char *buffer, unsigned long capacity ) - : data_( buffer ) - , end_( data_ + capacity ) - , typeTagsCurrent_( end_ ) - , messageCursor_( data_ ) - , argumentCurrent_( data_ ) - , elementSizePtr_( 0 ) - , messageIsInProgress_( false ) -{ - -} - - -OutboundPacketStream::~OutboundPacketStream() -{ - -} - - -char *OutboundPacketStream::BeginElement( char *beginPtr ) -{ - if( elementSizePtr_ == 0 ){ - - elementSizePtr_ = reinterpret_cast(data_); - - return beginPtr; - - }else{ - // store an offset to the old element size ptr in the element size slot - // we store an offset rather than the actual pointer to be 64 bit clean. - *reinterpret_cast(beginPtr) = - (uint32)(reinterpret_cast(elementSizePtr_) - data_); - - elementSizePtr_ = reinterpret_cast(beginPtr); - - return beginPtr + 4; - } -} - - -void OutboundPacketStream::EndElement( char *endPtr ) -{ - assert( elementSizePtr_ != 0 ); - - if( elementSizePtr_ == reinterpret_cast(data_) ){ - - elementSizePtr_ = 0; - - }else{ - // while building an element, an offset to the containing element's - // size slot is stored in the elements size slot (or a ptr to data_ - // if there is no containing element). We retrieve that here - uint32 *previousElementSizePtr = - (uint32*)(data_ + *reinterpret_cast(elementSizePtr_)); - - // then we store the element size in the slot, note that the element - // size does not include the size slot, hence the - 4 below. - uint32 elementSize = - (endPtr - reinterpret_cast(elementSizePtr_)) - 4; - FromUInt32( reinterpret_cast(elementSizePtr_), elementSize ); - - // finally, we reset the element size ptr to the containing element - elementSizePtr_ = previousElementSizePtr; - } -} - - -bool OutboundPacketStream::ElementSizeSlotRequired() const -{ - return (elementSizePtr_ != 0); -} - - -void OutboundPacketStream::CheckForAvailableBundleSpace() -{ - unsigned long required = Size() + ((ElementSizeSlotRequired())?4:0) + 16; - - if( required > Capacity() ) - throw OutOfBufferMemoryException(); -} - - -void OutboundPacketStream::CheckForAvailableMessageSpace( const char *addressPattern ) -{ - // plus 4 for at least four bytes of type tag - unsigned long required = Size() + ((ElementSizeSlotRequired())?4:0) - + RoundUp4(strlen(addressPattern) + 1) + 4; - - if( required > Capacity() ) - throw OutOfBufferMemoryException(); -} - - -void OutboundPacketStream::CheckForAvailableArgumentSpace( long argumentLength ) -{ - // plus three for extra type tag, comma and null terminator - unsigned long required = (argumentCurrent_ - data_) + argumentLength - + RoundUp4( (end_ - typeTagsCurrent_) + 3 ); - - if( required > Capacity() ) - throw OutOfBufferMemoryException(); -} - - -void OutboundPacketStream::Clear() -{ - typeTagsCurrent_ = end_; - messageCursor_ = data_; - argumentCurrent_ = data_; - elementSizePtr_ = 0; - messageIsInProgress_ = false; -} - - -unsigned int OutboundPacketStream::Capacity() const -{ - return end_ - data_; -} - - -unsigned int OutboundPacketStream::Size() const -{ - unsigned int result = argumentCurrent_ - data_; - if( IsMessageInProgress() ){ - // account for the length of the type tag string. the total type tag - // includes an initial comma, plus at least one terminating \0 - result += RoundUp4( (end_ - typeTagsCurrent_) + 2 ); - } - - return result; -} - - -const char *OutboundPacketStream::Data() const -{ - return data_; -} - - -bool OutboundPacketStream::IsReady() const -{ - return (!IsMessageInProgress() && !IsBundleInProgress()); -} - - -bool OutboundPacketStream::IsMessageInProgress() const -{ - return messageIsInProgress_; -} - - -bool OutboundPacketStream::IsBundleInProgress() const -{ - return (elementSizePtr_ != 0); -} - - -OutboundPacketStream& OutboundPacketStream::operator<<( const BundleInitiator& rhs ) -{ - if( IsMessageInProgress() ) - throw MessageInProgressException(); - - CheckForAvailableBundleSpace(); - - messageCursor_ = BeginElement( messageCursor_ ); - - memcpy( messageCursor_, "#bundle\0", 8 ); - FromUInt64( messageCursor_ + 8, rhs.timeTag ); - - messageCursor_ += 16; - argumentCurrent_ = messageCursor_; - - return *this; -} - - -OutboundPacketStream& OutboundPacketStream::operator<<( const BundleTerminator& rhs ) -{ - (void) rhs; - - if( !IsBundleInProgress() ) - throw BundleNotInProgressException(); - if( IsMessageInProgress() ) - throw MessageInProgressException(); - - EndElement( messageCursor_ ); - - return *this; -} - - -OutboundPacketStream& OutboundPacketStream::operator<<( const BeginMessage& rhs ) -{ - if( IsMessageInProgress() ) - throw MessageInProgressException(); - - CheckForAvailableMessageSpace( rhs.addressPattern ); - - messageCursor_ = BeginElement( messageCursor_ ); - - strcpy( messageCursor_, rhs.addressPattern ); - unsigned long rhsLength = strlen(rhs.addressPattern); - messageCursor_ += rhsLength + 1; - - // zero pad to 4-byte boundary - unsigned long i = rhsLength + 1; - while( i & 0x3 ){ - *messageCursor_++ = '\0'; - ++i; - } - - argumentCurrent_ = messageCursor_; - typeTagsCurrent_ = end_; - - messageIsInProgress_ = true; - - return *this; -} - - -OutboundPacketStream& OutboundPacketStream::operator<<( const MessageTerminator& rhs ) -{ - (void) rhs; - - if( !IsMessageInProgress() ) - throw MessageNotInProgressException(); - - int typeTagsCount = end_ - typeTagsCurrent_; - - if( typeTagsCount ){ - - char *tempTypeTags = (char*)alloca(typeTagsCount); - memcpy( tempTypeTags, typeTagsCurrent_, typeTagsCount ); - - // slot size includes comma and null terminator - int typeTagSlotSize = RoundUp4( typeTagsCount + 2 ); - - uint32 argumentsSize = argumentCurrent_ - messageCursor_; - - memmove( messageCursor_ + typeTagSlotSize, messageCursor_, argumentsSize ); - - messageCursor_[0] = ','; - // copy type tags in reverse (really forward) order - for( int i=0; i < typeTagsCount; ++i ) - messageCursor_[i+1] = tempTypeTags[ (typeTagsCount-1) - i ]; - - char *p = messageCursor_ + 1 + typeTagsCount; - for( int i=0; i < (typeTagSlotSize - (typeTagsCount + 1)); ++i ) - *p++ = '\0'; - - typeTagsCurrent_ = end_; - - // advance messageCursor_ for next message - messageCursor_ += typeTagSlotSize + argumentsSize; - - }else{ - // send an empty type tags string - memcpy( messageCursor_, ",\0\0\0", 4 ); - - // advance messageCursor_ for next message - messageCursor_ += 4; - } - - argumentCurrent_ = messageCursor_; - - EndElement( messageCursor_ ); - - messageIsInProgress_ = false; - - return *this; -} - - -OutboundPacketStream& OutboundPacketStream::operator<<( bool rhs ) -{ - CheckForAvailableArgumentSpace(0); - - *(--typeTagsCurrent_) = (char)((rhs) ? TRUE_TYPE_TAG : FALSE_TYPE_TAG); - - return *this; -} - - -OutboundPacketStream& OutboundPacketStream::operator<<( const NilType& rhs ) -{ - (void) rhs; - CheckForAvailableArgumentSpace(0); - - *(--typeTagsCurrent_) = NIL_TYPE_TAG; - - return *this; -} - - -OutboundPacketStream& OutboundPacketStream::operator<<( const InfinitumType& rhs ) -{ - (void) rhs; - CheckForAvailableArgumentSpace(0); - - *(--typeTagsCurrent_) = INFINITUM_TYPE_TAG; - - return *this; -} - - -OutboundPacketStream& OutboundPacketStream::operator<<( int32 rhs ) -{ - CheckForAvailableArgumentSpace(4); - - *(--typeTagsCurrent_) = INT32_TYPE_TAG; - FromInt32( argumentCurrent_, rhs ); - argumentCurrent_ += 4; - - return *this; -} - - -OutboundPacketStream& OutboundPacketStream::operator<<( float rhs ) -{ - CheckForAvailableArgumentSpace(4); - - *(--typeTagsCurrent_) = FLOAT_TYPE_TAG; - -#ifdef OSC_HOST_LITTLE_ENDIAN - union{ - float f; - char c[4]; - } u; - - u.f = rhs; - - argumentCurrent_[3] = u.c[0]; - argumentCurrent_[2] = u.c[1]; - argumentCurrent_[1] = u.c[2]; - argumentCurrent_[0] = u.c[3]; -#else - *reinterpret_cast(argumentCurrent_) = rhs; -#endif - - argumentCurrent_ += 4; - - return *this; -} - - -OutboundPacketStream& OutboundPacketStream::operator<<( char rhs ) -{ - CheckForAvailableArgumentSpace(4); - - *(--typeTagsCurrent_) = CHAR_TYPE_TAG; - FromInt32( argumentCurrent_, rhs ); - argumentCurrent_ += 4; - - return *this; -} - - -OutboundPacketStream& OutboundPacketStream::operator<<( const RgbaColor& rhs ) -{ - CheckForAvailableArgumentSpace(4); - - *(--typeTagsCurrent_) = RGBA_COLOR_TYPE_TAG; - FromUInt32( argumentCurrent_, rhs ); - argumentCurrent_ += 4; - - return *this; -} - - -OutboundPacketStream& OutboundPacketStream::operator<<( const MidiMessage& rhs ) -{ - CheckForAvailableArgumentSpace(4); - - *(--typeTagsCurrent_) = MIDI_MESSAGE_TYPE_TAG; - FromUInt32( argumentCurrent_, rhs ); - argumentCurrent_ += 4; - - return *this; -} - - -OutboundPacketStream& OutboundPacketStream::operator<<( int64 rhs ) -{ - CheckForAvailableArgumentSpace(8); - - *(--typeTagsCurrent_) = INT64_TYPE_TAG; - FromInt64( argumentCurrent_, rhs ); - argumentCurrent_ += 8; - - return *this; -} - - -OutboundPacketStream& OutboundPacketStream::operator<<( const TimeTag& rhs ) -{ - CheckForAvailableArgumentSpace(8); - - *(--typeTagsCurrent_) = TIME_TAG_TYPE_TAG; - FromUInt64( argumentCurrent_, rhs ); - argumentCurrent_ += 8; - - return *this; -} - - -OutboundPacketStream& OutboundPacketStream::operator<<( double rhs ) -{ - CheckForAvailableArgumentSpace(8); - - *(--typeTagsCurrent_) = DOUBLE_TYPE_TAG; - -#ifdef OSC_HOST_LITTLE_ENDIAN - union{ - double f; - char c[8]; - } u; - - u.f = rhs; - - argumentCurrent_[7] = u.c[0]; - argumentCurrent_[6] = u.c[1]; - argumentCurrent_[5] = u.c[2]; - argumentCurrent_[4] = u.c[3]; - argumentCurrent_[3] = u.c[4]; - argumentCurrent_[2] = u.c[5]; - argumentCurrent_[1] = u.c[6]; - argumentCurrent_[0] = u.c[7]; -#else - *reinterpret_cast(argumentCurrent_) = rhs; -#endif - - argumentCurrent_ += 8; - - return *this; -} - - -OutboundPacketStream& OutboundPacketStream::operator<<( const char *rhs ) -{ - CheckForAvailableArgumentSpace( RoundUp4(strlen(rhs) + 1) ); - - *(--typeTagsCurrent_) = STRING_TYPE_TAG; - strcpy( argumentCurrent_, rhs ); - unsigned long rhsLength = strlen(rhs); - argumentCurrent_ += rhsLength + 1; - - // zero pad to 4-byte boundary - unsigned long i = rhsLength + 1; - while( i & 0x3 ){ - *argumentCurrent_++ = '\0'; - ++i; - } - - return *this; -} - - -OutboundPacketStream& OutboundPacketStream::operator<<( const Symbol& rhs ) -{ - CheckForAvailableArgumentSpace( RoundUp4(strlen(rhs) + 1) ); - - *(--typeTagsCurrent_) = SYMBOL_TYPE_TAG; - strcpy( argumentCurrent_, rhs ); - unsigned long rhsLength = strlen(rhs); - argumentCurrent_ += rhsLength + 1; - - // zero pad to 4-byte boundary - unsigned long i = rhsLength + 1; - while( i & 0x3 ){ - *argumentCurrent_++ = '\0'; - ++i; - } - - return *this; -} - - -OutboundPacketStream& OutboundPacketStream::operator<<( const Blob& rhs ) -{ - CheckForAvailableArgumentSpace( 4 + RoundUp4(rhs.size) ); - - *(--typeTagsCurrent_) = BLOB_TYPE_TAG; - FromUInt32( argumentCurrent_, rhs.size ); - argumentCurrent_ += 4; - - memcpy( argumentCurrent_, rhs.data, rhs.size ); - argumentCurrent_ += rhs.size; - - // zero pad to 4-byte boundary - unsigned long i = rhs.size; - while( i & 0x3 ){ - *argumentCurrent_++ = '\0'; - ++i; - } - - return *this; -} - -} // namespace osc - - diff -r fcf435874395 -r 45c889eae324 front_idill/extern/fajran-npTuioClient/TuioClient/oscpack/osc/OscOutboundPacketStream.h --- a/front_idill/extern/fajran-npTuioClient/TuioClient/oscpack/osc/OscOutboundPacketStream.h Thu Apr 19 11:53:06 2012 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,142 +0,0 @@ -/* - oscpack -- Open Sound Control packet manipulation library - http://www.audiomulch.com/~rossb/oscpack - - Copyright (c) 2004-2005 Ross Bencina - - Permission is hereby granted, free of charge, to any person obtaining - a copy of this software and associated documentation files - (the "Software"), to deal in the Software without restriction, - including without limitation the rights to use, copy, modify, merge, - publish, distribute, sublicense, and/or sell copies of the Software, - and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be - included in all copies or substantial portions of the Software. - - Any person wishing to distribute modifications to the Software is - requested to send the modifications to the original developer so that - they can be incorporated into the canonical version. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR - ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF - CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -*/ -#ifndef INCLUDED_OSCOUTBOUNDPACKET_H -#define INCLUDED_OSCOUTBOUNDPACKET_H - -#include "OscTypes.h" -#include "OscException.h" - - -namespace osc{ - -class OutOfBufferMemoryException : public Exception{ -public: - OutOfBufferMemoryException( const char *w="out of buffer memory" ) - : Exception( w ) {} -}; - -class BundleNotInProgressException : public Exception{ -public: - BundleNotInProgressException( - const char *w="call to EndBundle when bundle is not in progress" ) - : Exception( w ) {} -}; - -class MessageInProgressException : public Exception{ -public: - MessageInProgressException( - const char *w="opening or closing bundle or message while message is in progress" ) - : Exception( w ) {} -}; - -class MessageNotInProgressException : public Exception{ -public: - MessageNotInProgressException( - const char *w="call to EndMessage when message is not in progress" ) - : Exception( w ) {} -}; - - -class OutboundPacketStream{ -public: - OutboundPacketStream( char *buffer, unsigned long capacity ); - ~OutboundPacketStream(); - - void Clear(); - - unsigned int Capacity() const; - - // invariant: size() is valid even while building a message. - unsigned int Size() const; - - const char *Data() const; - - // indicates that all messages have been closed with a matching EndMessage - // and all bundles have been closed with a matching EndBundle - bool IsReady() const; - - bool IsMessageInProgress() const; - bool IsBundleInProgress() const; - - OutboundPacketStream& operator<<( const BundleInitiator& rhs ); - OutboundPacketStream& operator<<( const BundleTerminator& rhs ); - - OutboundPacketStream& operator<<( const BeginMessage& rhs ); - OutboundPacketStream& operator<<( const MessageTerminator& rhs ); - - OutboundPacketStream& operator<<( bool rhs ); - OutboundPacketStream& operator<<( const NilType& rhs ); - OutboundPacketStream& operator<<( const InfinitumType& rhs ); - OutboundPacketStream& operator<<( int32 rhs ); - -#ifndef __x86_64__ - OutboundPacketStream& operator<<( int rhs ) - { *this << (int32)rhs; return *this; } -#endif - - OutboundPacketStream& operator<<( float rhs ); - OutboundPacketStream& operator<<( char rhs ); - OutboundPacketStream& operator<<( const RgbaColor& rhs ); - OutboundPacketStream& operator<<( const MidiMessage& rhs ); - OutboundPacketStream& operator<<( int64 rhs ); - OutboundPacketStream& operator<<( const TimeTag& rhs ); - OutboundPacketStream& operator<<( double rhs ); - OutboundPacketStream& operator<<( const char* rhs ); - OutboundPacketStream& operator<<( const Symbol& rhs ); - OutboundPacketStream& operator<<( const Blob& rhs ); - -private: - - char *BeginElement( char *beginPtr ); - void EndElement( char *endPtr ); - - bool ElementSizeSlotRequired() const; - void CheckForAvailableBundleSpace(); - void CheckForAvailableMessageSpace( const char *addressPattern ); - void CheckForAvailableArgumentSpace( long argumentLength ); - - char *data_; - char *end_; - - char *typeTagsCurrent_; // stored in reverse order - char *messageCursor_; - char *argumentCurrent_; - - // elementSizePtr_ has two special values: 0 indicates that a bundle - // isn't open, and elementSizePtr_==data_ indicates that a bundle is - // open but that it doesn't have a size slot (ie the outermost bundle) - uint32 *elementSizePtr_; - - bool messageIsInProgress_; -}; - -} // namespace osc - -#endif /* INCLUDED_OSC_OUTBOUND_PACKET_H */ diff -r fcf435874395 -r 45c889eae324 front_idill/extern/fajran-npTuioClient/TuioClient/oscpack/osc/OscPacketListener.h --- a/front_idill/extern/fajran-npTuioClient/TuioClient/oscpack/osc/OscPacketListener.h Thu Apr 19 11:53:06 2012 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,72 +0,0 @@ -/* - oscpack -- Open Sound Control packet manipulation library - http://www.audiomulch.com/~rossb/oscpack - - Copyright (c) 2004-2005 Ross Bencina - - Permission is hereby granted, free of charge, to any person obtaining - a copy of this software and associated documentation files - (the "Software"), to deal in the Software without restriction, - including without limitation the rights to use, copy, modify, merge, - publish, distribute, sublicense, and/or sell copies of the Software, - and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be - included in all copies or substantial portions of the Software. - - Any person wishing to distribute modifications to the Software is - requested to send the modifications to the original developer so that - they can be incorporated into the canonical version. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR - ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF - CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -*/ -#ifndef INCLUDED_OSCPACKETLISTENER_H -#define INCLUDED_OSCPACKETLISTENER_H - -#include "OscReceivedElements.h" -#include "../ip/PacketListener.h" - - -namespace osc{ - -class OscPacketListener : public PacketListener{ -protected: - virtual void ProcessBundle( const osc::ReceivedBundle& b, - const IpEndpointName& remoteEndpoint ) - { - // ignore bundle time tag for now - - for( ReceivedBundle::const_iterator i = b.ElementsBegin(); - i != b.ElementsEnd(); ++i ){ - if( i->IsBundle() ) - ProcessBundle( ReceivedBundle(*i), remoteEndpoint ); - else - ProcessMessage( ReceivedMessage(*i), remoteEndpoint ); - } - } - - virtual void ProcessMessage( const osc::ReceivedMessage& m, - const IpEndpointName& remoteEndpoint ) = 0; - -public: - virtual void ProcessPacket( const char *data, int size, - const IpEndpointName& remoteEndpoint ) - { - osc::ReceivedPacket p( data, size ); - if( p.IsBundle() ) - ProcessBundle( ReceivedBundle(p), remoteEndpoint ); - else - ProcessMessage( ReceivedMessage(p), remoteEndpoint ); - } -}; - -} // namespace osc - -#endif /* INCLUDED_OSCPACKETLISTENER_H */ diff -r fcf435874395 -r 45c889eae324 front_idill/extern/fajran-npTuioClient/TuioClient/oscpack/osc/OscPrintReceivedElements.cpp --- a/front_idill/extern/fajran-npTuioClient/TuioClient/oscpack/osc/OscPrintReceivedElements.cpp Thu Apr 19 11:53:06 2012 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,240 +0,0 @@ -/* - oscpack -- Open Sound Control packet manipulation library - http://www.audiomulch.com/~rossb/oscpack - - Copyright (c) 2004-2005 Ross Bencina - - Permission is hereby granted, free of charge, to any person obtaining - a copy of this software and associated documentation files - (the "Software"), to deal in the Software without restriction, - including without limitation the rights to use, copy, modify, merge, - publish, distribute, sublicense, and/or sell copies of the Software, - and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be - included in all copies or substantial portions of the Software. - - Any person wishing to distribute modifications to the Software is - requested to send the modifications to the original developer so that - they can be incorporated into the canonical version. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR - ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF - CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -*/ -#include "OscPrintReceivedElements.h" - -#include -#include -#include - - -namespace osc{ - - -std::ostream& operator<<( std::ostream & os, - const ReceivedMessageArgument& arg ) -{ - switch( arg.TypeTag() ){ - case TRUE_TYPE_TAG: - os << "bool:true"; - break; - - case FALSE_TYPE_TAG: - os << "bool:false"; - break; - - case NIL_TYPE_TAG: - os << "(Nil)"; - break; - - case INFINITUM_TYPE_TAG: - os << "(Infinitum)"; - break; - - case INT32_TYPE_TAG: - os << "int32:" << arg.AsInt32Unchecked(); - break; - - case FLOAT_TYPE_TAG: - os << "float32:" << arg.AsFloatUnchecked(); - break; - - case CHAR_TYPE_TAG: - { - char s[2] = {0}; - s[0] = arg.AsCharUnchecked(); - os << "char:'" << s << "'"; - } - break; - - case RGBA_COLOR_TYPE_TAG: - { - uint32 color = arg.AsRgbaColorUnchecked(); - - os << "RGBA:0x" - << std::hex << std::setfill('0') - << std::setw(2) << (int)((color>>24) & 0xFF) - << std::setw(2) << (int)((color>>16) & 0xFF) - << std::setw(2) << (int)((color>>8) & 0xFF) - << std::setw(2) << (int)(color & 0xFF) - << std::setfill(' '); - os.unsetf(std::ios::basefield); - } - break; - - case MIDI_MESSAGE_TYPE_TAG: - { - uint32 m = arg.AsMidiMessageUnchecked(); - os << "midi (port, status, data1, data2):<<" - << std::hex << std::setfill('0') - << "0x" << std::setw(2) << (int)((m>>24) & 0xFF) - << " 0x" << std::setw(2) << (int)((m>>16) & 0xFF) - << " 0x" << std::setw(2) << (int)((m>>8) & 0xFF) - << " 0x" << std::setw(2) << (int)(m & 0xFF) - << std::setfill(' ') << ">>"; - os.unsetf(std::ios::basefield); - } - break; - - case INT64_TYPE_TAG: - os << "int64:" << arg.AsInt64Unchecked(); - break; - - case TIME_TAG_TYPE_TAG: - { - os << "OSC-timetag:" << arg.AsTimeTagUnchecked(); - - std::time_t t = - (unsigned long)( arg.AsTimeTagUnchecked() >> 32 ); - - // strip trailing newline from string returned by ctime - const char *timeString = std::ctime( &t ); - size_t len = strlen( timeString ); - char *s = new char[ len + 1 ]; - strcpy( s, timeString ); - if( len ) - s[ len - 1 ] = '\0'; - - os << " " << s; - } - break; - - case DOUBLE_TYPE_TAG: - os << "double:" << arg.AsDoubleUnchecked(); - break; - - case STRING_TYPE_TAG: - os << "OSC-string:`" << arg.AsStringUnchecked() << "'"; - break; - - case SYMBOL_TYPE_TAG: - os << "OSC-string (symbol):`" << arg.AsSymbolUnchecked() << "'"; - break; - - case BLOB_TYPE_TAG: - { - unsigned long size; - const void *data; - arg.AsBlobUnchecked( data, size ); - os << "OSC-blob:<<" << std::hex << std::setfill('0'); - unsigned char *p = (unsigned char*)data; - for( unsigned long i = 0; i < size; ++i ){ - os << "0x" << std::setw(2) << int(p[i]); - if( i != size-1 ) - os << ' '; - } - os.unsetf(std::ios::basefield); - os << ">>" << std::setfill(' '); - } - break; - - default: - os << "unknown"; - } - - return os; -} - - -std::ostream& operator<<( std::ostream & os, const ReceivedMessage& m ) -{ - - os << "[" << m.AddressPattern(); - bool first = true; - - for( ReceivedMessage::const_iterator i = m.ArgumentsBegin(); - i != m.ArgumentsEnd(); ++i ){ - if( first ){ - os << " "; - first = false; - }else{ - os << ", "; - } - - os << *i; - } - - os << "]"; - - return os; -} - - -std::ostream& operator<<( std::ostream & os, const ReceivedBundle& b ) -{ - static int indent = 0; - - for( int j=0; j < indent; ++j ) - os << " "; - os << "{ ( "; - if( b.TimeTag() == 1 ) - os << "immediate"; - else - os << b.TimeTag(); - os << " )\n"; - - ++indent; - - for( ReceivedBundle::const_iterator i = b.ElementsBegin(); - i != b.ElementsEnd(); ++i ){ - if( i->IsBundle() ){ - ReceivedBundle b(*i); - os << b << "\n"; - }else{ - ReceivedMessage m(*i); - for( int j=0; j < indent; ++j ) - os << " "; - os << m << "\n"; - } - } - - --indent; - - for( int j=0; j < indent; ++j ) - os << " "; - os << "}"; - - return os; -} - - -std::ostream& operator<<( std::ostream & os, const ReceivedPacket& p ) -{ - if( p.IsBundle() ){ - ReceivedBundle b(p); - os << b << "\n"; - }else{ - ReceivedMessage m(p); - os << m << "\n"; - } - - return os; -} - -} // namespace osc diff -r fcf435874395 -r 45c889eae324 front_idill/extern/fajran-npTuioClient/TuioClient/oscpack/osc/OscPrintReceivedElements.h --- a/front_idill/extern/fajran-npTuioClient/TuioClient/oscpack/osc/OscPrintReceivedElements.h Thu Apr 19 11:53:06 2012 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,50 +0,0 @@ -/* - oscpack -- Open Sound Control packet manipulation library - http://www.audiomulch.com/~rossb/oscpack - - Copyright (c) 2004-2005 Ross Bencina - - Permission is hereby granted, free of charge, to any person obtaining - a copy of this software and associated documentation files - (the "Software"), to deal in the Software without restriction, - including without limitation the rights to use, copy, modify, merge, - publish, distribute, sublicense, and/or sell copies of the Software, - and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be - included in all copies or substantial portions of the Software. - - Any person wishing to distribute modifications to the Software is - requested to send the modifications to the original developer so that - they can be incorporated into the canonical version. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR - ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF - CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -*/ -#ifndef INCLUDED_OSCPRINTRECEIVEDELEMENTS_H -#define INCLUDED_OSCPRINTRECEIVEDELEMENTS_H - -#include -#include - -#ifndef INCLUDED_OSCRECEIVEDELEMENTS_H -#include "OscReceivedElements.h" -#endif /* INCLUDED_OSCRECEIVEDELEMENTS_H */ - - -namespace osc{ - -std::ostream& operator<<( std::ostream & os, const ReceivedPacket& p ); -std::ostream& operator<<( std::ostream & os, const ReceivedMessageArgument& arg ); -std::ostream& operator<<( std::ostream & os, const ReceivedMessage& m ); -std::ostream& operator<<( std::ostream & os, const ReceivedBundle& b ); - -} // namespace osc - -#endif /* INCLUDED_OSCPRINTRECEIVEDELEMENTS_H */ diff -r fcf435874395 -r 45c889eae324 front_idill/extern/fajran-npTuioClient/TuioClient/oscpack/osc/OscReceivedElements.cpp --- a/front_idill/extern/fajran-npTuioClient/TuioClient/oscpack/osc/OscReceivedElements.cpp Thu Apr 19 11:53:06 2012 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,722 +0,0 @@ -/* - oscpack -- Open Sound Control packet manipulation library - http://www.audiomulch.com/~rossb/oscpack - - Copyright (c) 2004-2005 Ross Bencina - - Permission is hereby granted, free of charge, to any person obtaining - a copy of this software and associated documentation files - (the "Software"), to deal in the Software without restriction, - including without limitation the rights to use, copy, modify, merge, - publish, distribute, sublicense, and/or sell copies of the Software, - and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be - included in all copies or substantial portions of the Software. - - Any person wishing to distribute modifications to the Software is - requested to send the modifications to the original developer so that - they can be incorporated into the canonical version. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR - ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF - CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -*/ -#include "OscReceivedElements.h" - -#include - -#include "OscHostEndianness.h" - - -namespace osc{ - - -// return the first 4 byte boundary after the end of a str4 -// be careful about calling this version if you don't know whether -// the string is terminated correctly. -static inline const char* FindStr4End( const char *p ) -{ - if( p[0] == '\0' ) // special case for SuperCollider integer address pattern - return p + 4; - - p += 3; - - while( *p ) - p += 4; - - return p + 1; -} - - -// return the first 4 byte boundary after the end of a str4 -// returns 0 if p == end or if the string is unterminated -static inline const char* FindStr4End( const char *p, const char *end ) -{ - if( p >= end ) - return 0; - - if( p[0] == '\0' ) // special case for SuperCollider integer address pattern - return p + 4; - - p += 3; - end -= 1; - - while( p < end && *p ) - p += 4; - - if( *p ) - return 0; - else - return p + 1; -} - - -static inline unsigned long RoundUp4( unsigned long x ) -{ - unsigned long remainder = x & 0x3UL; - if( remainder ) - return x + (4 - remainder); - else - return x; -} - - -static inline int32 ToInt32( const char *p ) -{ -#ifdef OSC_HOST_LITTLE_ENDIAN - union{ - osc::int32 i; - char c[4]; - } u; - - u.c[0] = p[3]; - u.c[1] = p[2]; - u.c[2] = p[1]; - u.c[3] = p[0]; - - return u.i; -#else - return *(int32*)p; -#endif -} - - -static inline uint32 ToUInt32( const char *p ) -{ -#ifdef OSC_HOST_LITTLE_ENDIAN - union{ - osc::uint32 i; - char c[4]; - } u; - - u.c[0] = p[3]; - u.c[1] = p[2]; - u.c[2] = p[1]; - u.c[3] = p[0]; - - return u.i; -#else - return *(uint32*)p; -#endif -} - - -int64 ToInt64( const char *p ) -{ -#ifdef OSC_HOST_LITTLE_ENDIAN - union{ - osc::int64 i; - char c[8]; - } u; - - u.c[0] = p[7]; - u.c[1] = p[6]; - u.c[2] = p[5]; - u.c[3] = p[4]; - u.c[4] = p[3]; - u.c[5] = p[2]; - u.c[6] = p[1]; - u.c[7] = p[0]; - - return u.i; -#else - return *(int64*)p; -#endif -} - - -uint64 ToUInt64( const char *p ) -{ -#ifdef OSC_HOST_LITTLE_ENDIAN - union{ - osc::uint64 i; - char c[8]; - } u; - - u.c[0] = p[7]; - u.c[1] = p[6]; - u.c[2] = p[5]; - u.c[3] = p[4]; - u.c[4] = p[3]; - u.c[5] = p[2]; - u.c[6] = p[1]; - u.c[7] = p[0]; - - return u.i; -#else - return *(uint64*)p; -#endif -} - -//------------------------------------------------------------------------------ - -bool ReceivedPacket::IsBundle() const -{ - return (Size() > 0 && Contents()[0] == '#'); -} - -//------------------------------------------------------------------------------ - -bool ReceivedBundleElement::IsBundle() const -{ - return (Size() > 0 && Contents()[0] == '#'); -} - - -int32 ReceivedBundleElement::Size() const -{ - return ToUInt32( size_ ); -} - -//------------------------------------------------------------------------------ - -bool ReceivedMessageArgument::AsBool() const -{ - if( !typeTag_ ) - throw MissingArgumentException(); - else if( *typeTag_ == TRUE_TYPE_TAG ) - return true; - else if( *typeTag_ == FALSE_TYPE_TAG ) - return false; - else - throw WrongArgumentTypeException(); -} - - -bool ReceivedMessageArgument::AsBoolUnchecked() const -{ - if( !typeTag_ ) - throw MissingArgumentException(); - else if( *typeTag_ == TRUE_TYPE_TAG ) - return true; - else - return false; -} - - -int32 ReceivedMessageArgument::AsInt32() const -{ - if( !typeTag_ ) - throw MissingArgumentException(); - else if( *typeTag_ == INT32_TYPE_TAG ) - return AsInt32Unchecked(); - else - throw WrongArgumentTypeException(); -} - - -int32 ReceivedMessageArgument::AsInt32Unchecked() const -{ -#ifdef OSC_HOST_LITTLE_ENDIAN - union{ - osc::int32 i; - char c[4]; - } u; - - u.c[0] = argument_[3]; - u.c[1] = argument_[2]; - u.c[2] = argument_[1]; - u.c[3] = argument_[0]; - - return u.i; -#else - return *(int32*)argument_; -#endif -} - - -float ReceivedMessageArgument::AsFloat() const -{ - if( !typeTag_ ) - throw MissingArgumentException(); - else if( *typeTag_ == FLOAT_TYPE_TAG ) - return AsFloatUnchecked(); - else - throw WrongArgumentTypeException(); -} - - -float ReceivedMessageArgument::AsFloatUnchecked() const -{ -#ifdef OSC_HOST_LITTLE_ENDIAN - union{ - float f; - char c[4]; - } u; - - u.c[0] = argument_[3]; - u.c[1] = argument_[2]; - u.c[2] = argument_[1]; - u.c[3] = argument_[0]; - - return u.f; -#else - return *(float*)argument_; -#endif -} - - -char ReceivedMessageArgument::AsChar() const -{ - if( !typeTag_ ) - throw MissingArgumentException(); - else if( *typeTag_ == CHAR_TYPE_TAG ) - return AsCharUnchecked(); - else - throw WrongArgumentTypeException(); -} - - -char ReceivedMessageArgument::AsCharUnchecked() const -{ - return (char)ToInt32( argument_ ); -} - - -uint32 ReceivedMessageArgument::AsRgbaColor() const -{ - if( !typeTag_ ) - throw MissingArgumentException(); - else if( *typeTag_ == RGBA_COLOR_TYPE_TAG ) - return AsRgbaColorUnchecked(); - else - throw WrongArgumentTypeException(); -} - - -uint32 ReceivedMessageArgument::AsRgbaColorUnchecked() const -{ - return ToUInt32( argument_ ); -} - - -uint32 ReceivedMessageArgument::AsMidiMessage() const -{ - if( !typeTag_ ) - throw MissingArgumentException(); - else if( *typeTag_ == MIDI_MESSAGE_TYPE_TAG ) - return AsMidiMessageUnchecked(); - else - throw WrongArgumentTypeException(); -} - - -uint32 ReceivedMessageArgument::AsMidiMessageUnchecked() const -{ - return ToUInt32( argument_ ); -} - - -int64 ReceivedMessageArgument::AsInt64() const -{ - if( !typeTag_ ) - throw MissingArgumentException(); - else if( *typeTag_ == INT64_TYPE_TAG ) - return AsInt64Unchecked(); - else - throw WrongArgumentTypeException(); -} - - -int64 ReceivedMessageArgument::AsInt64Unchecked() const -{ - return ToInt64( argument_ ); -} - - -uint64 ReceivedMessageArgument::AsTimeTag() const -{ - if( !typeTag_ ) - throw MissingArgumentException(); - else if( *typeTag_ == TIME_TAG_TYPE_TAG ) - return AsTimeTagUnchecked(); - else - throw WrongArgumentTypeException(); -} - - -uint64 ReceivedMessageArgument::AsTimeTagUnchecked() const -{ - return ToUInt64( argument_ ); -} - - -double ReceivedMessageArgument::AsDouble() const -{ - if( !typeTag_ ) - throw MissingArgumentException(); - else if( *typeTag_ == DOUBLE_TYPE_TAG ) - return AsDoubleUnchecked(); - else - throw WrongArgumentTypeException(); -} - - -double ReceivedMessageArgument::AsDoubleUnchecked() const -{ -#ifdef OSC_HOST_LITTLE_ENDIAN - union{ - double d; - char c[8]; - } u; - - u.c[0] = argument_[7]; - u.c[1] = argument_[6]; - u.c[2] = argument_[5]; - u.c[3] = argument_[4]; - u.c[4] = argument_[3]; - u.c[5] = argument_[2]; - u.c[6] = argument_[1]; - u.c[7] = argument_[0]; - - return u.d; -#else - return *(double*)argument_; -#endif -} - - -const char* ReceivedMessageArgument::AsString() const -{ - if( !typeTag_ ) - throw MissingArgumentException(); - else if( *typeTag_ == STRING_TYPE_TAG ) - return argument_; - else - throw WrongArgumentTypeException(); -} - - -const char* ReceivedMessageArgument::AsSymbol() const -{ - if( !typeTag_ ) - throw MissingArgumentException(); - else if( *typeTag_ == SYMBOL_TYPE_TAG ) - return argument_; - else - throw WrongArgumentTypeException(); -} - - -void ReceivedMessageArgument::AsBlob( const void*& data, unsigned long& size ) const -{ - if( !typeTag_ ) - throw MissingArgumentException(); - else if( *typeTag_ == BLOB_TYPE_TAG ) - AsBlobUnchecked( data, size ); - else - throw WrongArgumentTypeException(); -} - - -void ReceivedMessageArgument::AsBlobUnchecked( const void*& data, unsigned long& size ) const -{ - size = ToUInt32( argument_ ); - data = (void*)(argument_+4); -} - -//------------------------------------------------------------------------------ - -void ReceivedMessageArgumentIterator::Advance() -{ - if( !value_.typeTag_ ) - return; - - switch( *value_.typeTag_++ ){ - case '\0': - // don't advance past end - --value_.typeTag_; - break; - - case TRUE_TYPE_TAG: - case FALSE_TYPE_TAG: - case NIL_TYPE_TAG: - case INFINITUM_TYPE_TAG: - - // zero length - break; - - case INT32_TYPE_TAG: - case FLOAT_TYPE_TAG: - case CHAR_TYPE_TAG: - case RGBA_COLOR_TYPE_TAG: - case MIDI_MESSAGE_TYPE_TAG: - - value_.argument_ += 4; - break; - - case INT64_TYPE_TAG: - case TIME_TAG_TYPE_TAG: - case DOUBLE_TYPE_TAG: - - value_.argument_ += 8; - break; - - case STRING_TYPE_TAG: - case SYMBOL_TYPE_TAG: - - // we use the unsafe function FindStr4End(char*) here because all of - // the arguments have already been validated in - // ReceivedMessage::Init() below. - - value_.argument_ = FindStr4End( value_.argument_ ); - break; - - case BLOB_TYPE_TAG: - { - uint32 blobSize = ToUInt32( value_.argument_ ); - value_.argument_ = value_.argument_ + 4 + RoundUp4( blobSize ); - } - break; - - default: // unknown type tag - // don't advance - --value_.typeTag_; - break; - - - // not handled: - // [ Indicates the beginning of an array. The tags following are for - // data in the Array until a close brace tag is reached. - // ] Indicates the end of an array. - } -} - -//------------------------------------------------------------------------------ - -ReceivedMessage::ReceivedMessage( const ReceivedPacket& packet ) - : addressPattern_( packet.Contents() ) -{ - Init( packet.Contents(), packet.Size() ); -} - - -ReceivedMessage::ReceivedMessage( const ReceivedBundleElement& bundleElement ) - : addressPattern_( bundleElement.Contents() ) -{ - Init( bundleElement.Contents(), bundleElement.Size() ); -} - - -bool ReceivedMessage::AddressPatternIsUInt32() const -{ - return (addressPattern_[0] == '\0'); -} - - -uint32 ReceivedMessage::AddressPatternAsUInt32() const -{ - return ToUInt32( addressPattern_ ); -} - - -void ReceivedMessage::Init( const char *message, unsigned long size ) -{ - if( size == 0 ) - throw MalformedMessageException( "zero length messages not permitted" ); - - if( (size & 0x03L) != 0 ) - throw MalformedMessageException( "message size must be multiple of four" ); - - const char *end = message + size; - - typeTagsBegin_ = FindStr4End( addressPattern_, end ); - if( typeTagsBegin_ == 0 ){ - // address pattern was not terminated before end - throw MalformedMessageException( "unterminated address pattern" ); - } - - if( typeTagsBegin_ == end ){ - // message consists of only the address pattern - no arguments or type tags. - typeTagsBegin_ = 0; - typeTagsEnd_ = 0; - arguments_ = 0; - - }else{ - if( *typeTagsBegin_ != ',' ) - throw MalformedMessageException( "type tags not present" ); - - if( *(typeTagsBegin_ + 1) == '\0' ){ - // zero length type tags - typeTagsBegin_ = 0; - typeTagsEnd_ = 0; - arguments_ = 0; - - }else{ - // check that all arguments are present and well formed - - arguments_ = FindStr4End( typeTagsBegin_, end ); - if( arguments_ == 0 ){ - throw MalformedMessageException( "type tags were not terminated before end of message" ); - } - - ++typeTagsBegin_; // advance past initial ',' - - const char *typeTag = typeTagsBegin_; - const char *argument = arguments_; - - do{ - switch( *typeTag ){ - case TRUE_TYPE_TAG: - case FALSE_TYPE_TAG: - case NIL_TYPE_TAG: - case INFINITUM_TYPE_TAG: - - // zero length - break; - - case INT32_TYPE_TAG: - case FLOAT_TYPE_TAG: - case CHAR_TYPE_TAG: - case RGBA_COLOR_TYPE_TAG: - case MIDI_MESSAGE_TYPE_TAG: - - if( argument == end ) - throw MalformedMessageException( "arguments exceed message size" ); - argument += 4; - if( argument > end ) - throw MalformedMessageException( "arguments exceed message size" ); - break; - - case INT64_TYPE_TAG: - case TIME_TAG_TYPE_TAG: - case DOUBLE_TYPE_TAG: - - if( argument == end ) - throw MalformedMessageException( "arguments exceed message size" ); - argument += 8; - if( argument > end ) - throw MalformedMessageException( "arguments exceed message size" ); - break; - - case STRING_TYPE_TAG: - case SYMBOL_TYPE_TAG: - - if( argument == end ) - throw MalformedMessageException( "arguments exceed message size" ); - argument = FindStr4End( argument, end ); - if( argument == 0 ) - throw MalformedMessageException( "unterminated string argument" ); - break; - - case BLOB_TYPE_TAG: - { - if( argument + 4 > end ) - MalformedMessageException( "arguments exceed message size" ); - - uint32 blobSize = ToUInt32( argument ); - argument = argument + 4 + RoundUp4( blobSize ); - if( argument > end ) - MalformedMessageException( "arguments exceed message size" ); - } - break; - - default: - throw MalformedMessageException( "unknown type tag" ); - - // not handled: - // [ Indicates the beginning of an array. The tags following are for - // data in the Array until a close brace tag is reached. - // ] Indicates the end of an array. - } - - }while( *++typeTag != '\0' ); - typeTagsEnd_ = typeTag; - } - } -} - -//------------------------------------------------------------------------------ - -ReceivedBundle::ReceivedBundle( const ReceivedPacket& packet ) - : elementCount_( 0 ) -{ - Init( packet.Contents(), packet.Size() ); -} - - -ReceivedBundle::ReceivedBundle( const ReceivedBundleElement& bundleElement ) - : elementCount_( 0 ) -{ - Init( bundleElement.Contents(), bundleElement.Size() ); -} - - -void ReceivedBundle::Init( const char *bundle, unsigned long size ) -{ - if( size < 16 ) - throw MalformedBundleException( "packet too short for bundle" ); - - if( (size & 0x03L) != 0 ) - throw MalformedBundleException( "bundle size must be multiple of four" ); - - if( bundle[0] != '#' - || bundle[1] != 'b' - || bundle[2] != 'u' - || bundle[3] != 'n' - || bundle[4] != 'd' - || bundle[5] != 'l' - || bundle[6] != 'e' - || bundle[7] != '\0' ) - throw MalformedBundleException( "bad bundle address pattern" ); - - end_ = bundle + size; - - timeTag_ = bundle + 8; - - const char *p = timeTag_ + 8; - - while( p < end_ ){ - if( p + 4 > end_ ) - throw MalformedBundleException( "packet too short for elementSize" ); - - uint32 elementSize = ToUInt32( p ); - if( (elementSize & 0x03L) != 0 ) - throw MalformedBundleException( "bundle element size must be multiple of four" ); - - p += 4 + elementSize; - if( p > end_ ) - throw MalformedBundleException( "packet too short for bundle element" ); - - ++elementCount_; - } - - if( p != end_ ) - throw MalformedBundleException( "bundle contents " ); -} - - -uint64 ReceivedBundle::TimeTag() const -{ - return ToUInt64( timeTag_ ); -} - - -} // namespace osc - diff -r fcf435874395 -r 45c889eae324 front_idill/extern/fajran-npTuioClient/TuioClient/oscpack/osc/OscReceivedElements.h --- a/front_idill/extern/fajran-npTuioClient/TuioClient/oscpack/osc/OscReceivedElements.h Thu Apr 19 11:53:06 2012 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,486 +0,0 @@ -/* - oscpack -- Open Sound Control packet manipulation library - http://www.audiomulch.com/~rossb/oscpack - - Copyright (c) 2004-2005 Ross Bencina - - Permission is hereby granted, free of charge, to any person obtaining - a copy of this software and associated documentation files - (the "Software"), to deal in the Software without restriction, - including without limitation the rights to use, copy, modify, merge, - publish, distribute, sublicense, and/or sell copies of the Software, - and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be - included in all copies or substantial portions of the Software. - - Any person wishing to distribute modifications to the Software is - requested to send the modifications to the original developer so that - they can be incorporated into the canonical version. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR - ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF - CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -*/ -#ifndef INCLUDED_OSCRECEIVEDELEMENTS_H -#define INCLUDED_OSCRECEIVEDELEMENTS_H - -#include "OscTypes.h" -#include "OscException.h" - - -namespace osc{ - - -class MalformedMessageException : public Exception{ -public: - MalformedMessageException( const char *w="malformed message" ) - : Exception( w ) {} -}; - -class MalformedBundleException : public Exception{ -public: - MalformedBundleException( const char *w="malformed bundle" ) - : Exception( w ) {} -}; - -class WrongArgumentTypeException : public Exception{ -public: - WrongArgumentTypeException( const char *w="wrong argument type" ) - : Exception( w ) {} -}; - -class MissingArgumentException : public Exception{ -public: - MissingArgumentException( const char *w="missing argument" ) - : Exception( w ) {} -}; - -class ExcessArgumentException : public Exception{ -public: - ExcessArgumentException( const char *w="too many arguments" ) - : Exception( w ) {} -}; - - -class ReceivedPacket{ -public: - ReceivedPacket( const char *contents, int32 size ) - : contents_( contents ) - , size_( size ) {} - - bool IsMessage() const { return !IsBundle(); } - bool IsBundle() const; - - int32 Size() const { return size_; } - const char *Contents() const { return contents_; } - -private: - const char *contents_; - int32 size_; -}; - - -class ReceivedBundleElement{ -public: - ReceivedBundleElement( const char *size ) - : size_( size ) {} - - friend class ReceivedBundleElementIterator; - - bool IsMessage() const { return !IsBundle(); } - bool IsBundle() const; - - int32 Size() const; - const char *Contents() const { return size_ + 4; } - -private: - const char *size_; -}; - - -class ReceivedBundleElementIterator{ -public: - ReceivedBundleElementIterator( const char *sizePtr ) - : value_( sizePtr ) {} - - ReceivedBundleElementIterator operator++() - { - Advance(); - return *this; - } - - ReceivedBundleElementIterator operator++(int) - { - ReceivedBundleElementIterator old( *this ); - Advance(); - return old; - } - - const ReceivedBundleElement& operator*() const { return value_; } - - const ReceivedBundleElement* operator->() const { return &value_; } - - friend bool operator==(const ReceivedBundleElementIterator& lhs, - const ReceivedBundleElementIterator& rhs ); - -private: - ReceivedBundleElement value_; - - void Advance() { value_.size_ = value_.Contents() + value_.Size(); } - - bool IsEqualTo( const ReceivedBundleElementIterator& rhs ) const - { - return value_.size_ == rhs.value_.size_; - } -}; - -inline bool operator==(const ReceivedBundleElementIterator& lhs, - const ReceivedBundleElementIterator& rhs ) -{ - return lhs.IsEqualTo( rhs ); -} - -inline bool operator!=(const ReceivedBundleElementIterator& lhs, - const ReceivedBundleElementIterator& rhs ) -{ - return !( lhs == rhs ); -} - - -class ReceivedMessageArgument{ -public: - ReceivedMessageArgument( const char *typeTag, const char *argument ) - : typeTag_( typeTag ) - , argument_( argument ) {} - - friend class ReceivedMessageArgumentIterator; - - const char TypeTag() const { return *typeTag_; } - - // the unchecked methods below don't check whether the argument actually - // is of the specified type. they should only be used if you've already - // checked the type tag or the associated IsType() method. - - bool IsBool() const - { return *typeTag_ == TRUE_TYPE_TAG || *typeTag_ == FALSE_TYPE_TAG; } - bool AsBool() const; - bool AsBoolUnchecked() const; - - bool IsNil() const { return *typeTag_ == NIL_TYPE_TAG; } - bool IsInfinitum() const { return *typeTag_ == INFINITUM_TYPE_TAG; } - - bool IsInt32() const { return *typeTag_ == INT32_TYPE_TAG; } - int32 AsInt32() const; - int32 AsInt32Unchecked() const; - - bool IsFloat() const { return *typeTag_ == FLOAT_TYPE_TAG; } - float AsFloat() const; - float AsFloatUnchecked() const; - - bool IsChar() const { return *typeTag_ == CHAR_TYPE_TAG; } - char AsChar() const; - char AsCharUnchecked() const; - - bool IsRgbaColor() const { return *typeTag_ == RGBA_COLOR_TYPE_TAG; } - uint32 AsRgbaColor() const; - uint32 AsRgbaColorUnchecked() const; - - bool IsMidiMessage() const { return *typeTag_ == MIDI_MESSAGE_TYPE_TAG; } - uint32 AsMidiMessage() const; - uint32 AsMidiMessageUnchecked() const; - - bool IsInt64() const { return *typeTag_ == INT64_TYPE_TAG; } - int64 AsInt64() const; - int64 AsInt64Unchecked() const; - - bool IsTimeTag() const { return *typeTag_ == TIME_TAG_TYPE_TAG; } - uint64 AsTimeTag() const; - uint64 AsTimeTagUnchecked() const; - - bool IsDouble() const { return *typeTag_ == DOUBLE_TYPE_TAG; } - double AsDouble() const; - double AsDoubleUnchecked() const; - - bool IsString() const { return *typeTag_ == STRING_TYPE_TAG; } - const char* AsString() const; - const char* AsStringUnchecked() const { return argument_; } - - bool IsSymbol() const { return *typeTag_ == SYMBOL_TYPE_TAG; } - const char* AsSymbol() const; - const char* AsSymbolUnchecked() const { return argument_; } - - bool IsBlob() const { return *typeTag_ == BLOB_TYPE_TAG; } - void AsBlob( const void*& data, unsigned long& size ) const; - void AsBlobUnchecked( const void*& data, unsigned long& size ) const; - -private: - const char *typeTag_; - const char *argument_; -}; - - -class ReceivedMessageArgumentIterator{ -public: - ReceivedMessageArgumentIterator( const char *typeTags, const char *arguments ) - : value_( typeTags, arguments ) {} - - ReceivedMessageArgumentIterator operator++() - { - Advance(); - return *this; - } - - ReceivedMessageArgumentIterator operator++(int) - { - ReceivedMessageArgumentIterator old( *this ); - Advance(); - return old; - } - - const ReceivedMessageArgument& operator*() const { return value_; } - - const ReceivedMessageArgument* operator->() const { return &value_; } - - friend bool operator==(const ReceivedMessageArgumentIterator& lhs, - const ReceivedMessageArgumentIterator& rhs ); - -private: - ReceivedMessageArgument value_; - - void Advance(); - - bool IsEqualTo( const ReceivedMessageArgumentIterator& rhs ) const - { - return value_.typeTag_ == rhs.value_.typeTag_; - } -}; - -inline bool operator==(const ReceivedMessageArgumentIterator& lhs, - const ReceivedMessageArgumentIterator& rhs ) -{ - return lhs.IsEqualTo( rhs ); -} - -inline bool operator!=(const ReceivedMessageArgumentIterator& lhs, - const ReceivedMessageArgumentIterator& rhs ) -{ - return !( lhs == rhs ); -} - - -class ReceivedMessageArgumentStream{ - friend class ReceivedMessage; - ReceivedMessageArgumentStream( const ReceivedMessageArgumentIterator& begin, - const ReceivedMessageArgumentIterator& end ) - : p_( begin ) - , end_( end ) {} - - ReceivedMessageArgumentIterator p_, end_; - -public: - - // end of stream - bool Eos() const { return p_ == end_; } - - ReceivedMessageArgumentStream& operator>>( bool& rhs ) - { - if( Eos() ) - throw MissingArgumentException(); - - rhs = (*p_++).AsBool(); - return *this; - } - - // not sure if it would be useful to stream Nil and Infinitum - // for now it's not possible - - ReceivedMessageArgumentStream& operator>>( int32& rhs ) - { - if( Eos() ) - throw MissingArgumentException(); - - rhs = (*p_++).AsInt32(); - return *this; - } - - ReceivedMessageArgumentStream& operator>>( float& rhs ) - { - if( Eos() ) - throw MissingArgumentException(); - - rhs = (*p_++).AsFloat(); - return *this; - } - - ReceivedMessageArgumentStream& operator>>( char& rhs ) - { - if( Eos() ) - throw MissingArgumentException(); - - rhs = (*p_++).AsChar(); - return *this; - } - - ReceivedMessageArgumentStream& operator>>( RgbaColor& rhs ) - { - if( Eos() ) - throw MissingArgumentException(); - - rhs.value = (*p_++).AsRgbaColor(); - return *this; - } - - ReceivedMessageArgumentStream& operator>>( MidiMessage& rhs ) - { - if( Eos() ) - throw MissingArgumentException(); - - rhs.value = (*p_++).AsMidiMessage(); - return *this; - } - - ReceivedMessageArgumentStream& operator>>( int64& rhs ) - { - if( Eos() ) - throw MissingArgumentException(); - - rhs = (*p_++).AsInt64(); - return *this; - } - - ReceivedMessageArgumentStream& operator>>( TimeTag& rhs ) - { - if( Eos() ) - throw MissingArgumentException(); - - rhs.value = (*p_++).AsTimeTag(); - return *this; - } - - ReceivedMessageArgumentStream& operator>>( double& rhs ) - { - if( Eos() ) - throw MissingArgumentException(); - - rhs = (*p_++).AsDouble(); - return *this; - } - - ReceivedMessageArgumentStream& operator>>( Blob& rhs ) - { - if( Eos() ) - throw MissingArgumentException(); - - (*p_++).AsBlob( rhs.data, rhs.size ); - return *this; - } - - ReceivedMessageArgumentStream& operator>>( const char*& rhs ) - { - if( Eos() ) - throw MissingArgumentException(); - - rhs = (*p_++).AsString(); - return *this; - } - - ReceivedMessageArgumentStream& operator>>( Symbol& rhs ) - { - if( Eos() ) - throw MissingArgumentException(); - - rhs.value = (*p_++).AsSymbol(); - return *this; - } - - ReceivedMessageArgumentStream& operator>>( MessageTerminator& rhs ) - { - if( !Eos() ) - throw ExcessArgumentException(); - - return *this; - } -}; - - -class ReceivedMessage{ - void Init( const char *bundle, unsigned long size ); -public: - explicit ReceivedMessage( const ReceivedPacket& packet ); - explicit ReceivedMessage( const ReceivedBundleElement& bundleElement ); - - const char *AddressPattern() const { return addressPattern_; } - - // Support for non-standad SuperCollider integer address patterns: - bool AddressPatternIsUInt32() const; - uint32 AddressPatternAsUInt32() const; - - unsigned long ArgumentCount() const { return static_cast(typeTagsEnd_ - typeTagsBegin_); } - - const char *TypeTags() const { return typeTagsBegin_; } - - - typedef ReceivedMessageArgumentIterator const_iterator; - - ReceivedMessageArgumentIterator ArgumentsBegin() const - { - return ReceivedMessageArgumentIterator( typeTagsBegin_, arguments_ ); - } - - ReceivedMessageArgumentIterator ArgumentsEnd() const - { - return ReceivedMessageArgumentIterator( typeTagsEnd_, 0 ); - } - - ReceivedMessageArgumentStream ArgumentStream() const - { - return ReceivedMessageArgumentStream( ArgumentsBegin(), ArgumentsEnd() ); - } - -private: - const char *addressPattern_; - const char *typeTagsBegin_; - const char *typeTagsEnd_; - const char *arguments_; -}; - - -class ReceivedBundle{ - void Init( const char *message, unsigned long size ); -public: - explicit ReceivedBundle( const ReceivedPacket& packet ); - explicit ReceivedBundle( const ReceivedBundleElement& bundleElement ); - - uint64 TimeTag() const; - - unsigned long ElementCount() const { return elementCount_; } - - typedef ReceivedBundleElementIterator const_iterator; - - ReceivedBundleElementIterator ElementsBegin() const - { - return ReceivedBundleElementIterator( timeTag_ + 8 ); - } - - ReceivedBundleElementIterator ElementsEnd() const - { - return ReceivedBundleElementIterator( end_ ); - } - -private: - const char *timeTag_; - const char *end_; - unsigned long elementCount_; -}; - - -} // namespace osc - - -#endif /* INCLUDED_OSCRECEIVEDELEMENTS_H */ diff -r fcf435874395 -r 45c889eae324 front_idill/extern/fajran-npTuioClient/TuioClient/oscpack/osc/OscTypes.cpp --- a/front_idill/extern/fajran-npTuioClient/TuioClient/oscpack/osc/OscTypes.cpp Thu Apr 19 11:53:06 2012 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,40 +0,0 @@ -/* - oscpack -- Open Sound Control packet manipulation library - http://www.audiomulch.com/~rossb/oscpack - - Copyright (c) 2004-2005 Ross Bencina - - Permission is hereby granted, free of charge, to any person obtaining - a copy of this software and associated documentation files - (the "Software"), to deal in the Software without restriction, - including without limitation the rights to use, copy, modify, merge, - publish, distribute, sublicense, and/or sell copies of the Software, - and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be - included in all copies or substantial portions of the Software. - - Any person wishing to distribute modifications to the Software is - requested to send the modifications to the original developer so that - they can be incorporated into the canonical version. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR - ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF - CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -*/ -#include "OscTypes.h" - -namespace osc{ - -BundleInitiator BeginBundleImmediate(1); -BundleTerminator EndBundle; -MessageTerminator EndMessage; -NilType Nil; -InfinitumType Infinitum; - -} // namespace osc diff -r fcf435874395 -r 45c889eae324 front_idill/extern/fajran-npTuioClient/TuioClient/oscpack/osc/OscTypes.h --- a/front_idill/extern/fajran-npTuioClient/TuioClient/oscpack/osc/OscTypes.h Thu Apr 19 11:53:06 2012 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,178 +0,0 @@ -/* - oscpack -- Open Sound Control packet manipulation library - http://www.audiomulch.com/~rossb/oscpack - - Copyright (c) 2004-2005 Ross Bencina - - Permission is hereby granted, free of charge, to any person obtaining - a copy of this software and associated documentation files - (the "Software"), to deal in the Software without restriction, - including without limitation the rights to use, copy, modify, merge, - publish, distribute, sublicense, and/or sell copies of the Software, - and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be - included in all copies or substantial portions of the Software. - - Any person wishing to distribute modifications to the Software is - requested to send the modifications to the original developer so that - they can be incorporated into the canonical version. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR - ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF - CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -*/ -#ifndef INCLUDED_OSCTYPES_H -#define INCLUDED_OSCTYPES_H - - -namespace osc{ - -// basic types - -#if defined(__BORLANDC__) || defined(_MSC_VER) - -typedef __int64 int64; -typedef unsigned __int64 uint64; - -#else - -typedef long long int64; -typedef unsigned long long uint64; - -#endif - - - -#ifdef __x86_64__ - -typedef signed int int32; -typedef unsigned int uint32; - -#else - -typedef signed long int32; -typedef unsigned long uint32; - -#endif - - - -enum TypeTagValues { - TRUE_TYPE_TAG = 'T', - FALSE_TYPE_TAG = 'F', - NIL_TYPE_TAG = 'N', - INFINITUM_TYPE_TAG = 'I', - INT32_TYPE_TAG = 'i', - FLOAT_TYPE_TAG = 'f', - CHAR_TYPE_TAG = 'c', - RGBA_COLOR_TYPE_TAG = 'r', - MIDI_MESSAGE_TYPE_TAG = 'm', - INT64_TYPE_TAG = 'h', - TIME_TAG_TYPE_TAG = 't', - DOUBLE_TYPE_TAG = 'd', - STRING_TYPE_TAG = 's', - SYMBOL_TYPE_TAG = 'S', - BLOB_TYPE_TAG = 'b' -}; - - - -// i/o manipulators used for streaming interfaces - -struct BundleInitiator{ - explicit BundleInitiator( uint64 timeTag_ ) : timeTag( timeTag_ ) {} - uint64 timeTag; -}; - -extern BundleInitiator BeginBundleImmediate; - -inline BundleInitiator BeginBundle( uint64 timeTag=1 ) -{ - return BundleInitiator(timeTag); -} - - -struct BundleTerminator{ -}; - -extern BundleTerminator EndBundle; - -struct BeginMessage{ - explicit BeginMessage( const char *addressPattern_ ) : addressPattern( addressPattern_ ) {} - const char *addressPattern; -}; - -struct MessageTerminator{ -}; - -extern MessageTerminator EndMessage; - - -// osc specific types. they are defined as structs so they can be used -// as separately identifiable types with the streaming operators. - -struct NilType{ -}; - -extern NilType Nil; - - -struct InfinitumType{ -}; - -extern InfinitumType Infinitum; - -struct RgbaColor{ - RgbaColor() {} - explicit RgbaColor( uint32 value_ ) : value( value_ ) {} - uint32 value; - - operator uint32() const { return value; } -}; - - -struct MidiMessage{ - MidiMessage() {} - explicit MidiMessage( uint32 value_ ) : value( value_ ) {} - uint32 value; - - operator uint32() const { return value; } -}; - - -struct TimeTag{ - TimeTag() {} - explicit TimeTag( uint64 value_ ) : value( value_ ) {} - uint64 value; - - operator uint64() const { return value; } -}; - - -struct Symbol{ - Symbol() {} - explicit Symbol( const char* value_ ) : value( value_ ) {} - const char* value; - - operator const char *() const { return value; } -}; - - -struct Blob{ - Blob() {} - explicit Blob( const void* data_, unsigned long size_ ) - : data( data_ ), size( size_ ) {} - const void* data; - unsigned long size; -}; - -} // namespace osc - - -#endif /* INCLUDED_OSCTYPES_H */ diff -r fcf435874395 -r 45c889eae324 front_idill/extern/fajran-npTuioClient/TuioClient/oscpack/readme --- a/front_idill/extern/fajran-npTuioClient/TuioClient/oscpack/readme Thu Apr 19 11:53:06 2012 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,80 +0,0 @@ -oscpack -- Open Sound Control packet manipulation library -http://www.audiomulch.com/~rossb/code/oscpack - -Copyright (c) 2004-2005 Ross Bencina - -A simple C++ library for packing and unpacking OSC packets. - - -Oscpack is simply a set of C++ classes for packing and unpacking OSC packets. -Oscpack includes a minimal set of UDP networking classes for windows and posix -which are sufficient for writing many OSC applications and servers, but you are -encouraged to use another networking framework if it better suits your needs. -Oscpack is not an OSC application framework, it doesn't include infrastructure for -constructing or routing OSC namespaces, just classes for easily constructing, -sending, receiving and parsing OSC packets. The library should also be easy to use -for other transport methods (eg serial). - -The key goals of the oscpack library are: - - - to be a simple and complete implementation of OSC - - to be portable to a wide variety of platforms - - to allow easy development of robust OSC applications - (for example it should be impossible to crash a server - by sending it malformed packets, and difficult to - create malformed packets.) - -Here's a summary of the key files: - -osc/OscReceivedElements -- classes for parsing a packet -osc/OscPrintRecievedElements -- iostream << operators for printing packet elements -osc/OscOutboundPacket -- a class for packing messages into a packet -osc/OscPacketListener -- base class for listening to OSC packets on a UdpSocket -tests/OscUnitTests -- unit test program for the OSC modules -tests/OscSendTests -- examples of how to send messages -tests/OscReceiveTest -- example of how to receive the messages sent by OSCSendTests -examples/OscDump -- a program that prints received OSC packets - - - -Building --------- - -In general the idea is that you will embed this source code in your projects as you -see fit. The Makefile has an install rule for building a shared library and -installing headers in usr/local. - -The Makefile works for Linux and MaxOS X except that if you are on a big endian -machine such as PowerPC Macintosh you need to edit the line which sets the -endianness to OSC_HOST_BIG_ENDIAN (see the makefile comment for details) or it won't -work. If you want to build and install liboscpack as a library on OS X you also need -to edit the $(LIBFILENAME) rule by commenting out the Linux case and uncommenting -the OS X case since OS X uses different gcc flags for shared libraries. - -On Windows there is a batch file for doing a simple test build with MinGW gcc called -make.MinGW32.bat. This will build the test executables and oscdump in ./bin and run -the unit tests. - --- - - -If you fix anything or write a set of TCP send/recieve classes -please consider sending me a patch. Thanks :) - -For more information about Open Sound Control, see: -http://www.cnmat.berkeley.edu/OpenSoundControl/ - - -Thanks to Till Bovermann for helping with POSIX networking code and -Mac compatibility, and to Martin Kaltenbrunner and the rest of the -reacTable team for giving me a reason to finish this library. Thanks -to Merlijn Blaauw for reviewing the interfaces. Thanks to Xavier Oliver -for additional help with Linux builds and POSIX implementation details. - -Portions developed at the Music Technology Group, Audiovisual Institute, -University Pompeu Fabra, Barcelona, during my stay as a visiting -researcher, November 2004 - September 2005. - -See the file LICENSE for information about distributing and using this code. - - diff -r fcf435874395 -r 45c889eae324 front_idill/extern/fajran-npTuioClient/TuioClient/oscpack/todo --- a/front_idill/extern/fajran-npTuioClient/TuioClient/oscpack/todo Thu Apr 19 11:53:06 2012 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,55 +0,0 @@ -TODO: - - - consider adding the local endpoint name to PacketListener::PacketReceived() params - - - consider adding ListenerThread class to support old seperate thread listener functionality, something like: - - class UdpSocketListenerThread{ - public: - UdpSocketListenerThread( UdpSocket& socket, Listener *listener ); - UdpSocketListenerThread( UdpSocketReceiveMultiplexer *mux ); - ~UdpSocketListenerThread(); - - void Run(); - void Stop(); - }; - - - provide some kind of automatic endianness configuration (hopefully there - are gcc symbols for this) - - - work out a way to make the parsing classes totally safe. at a minimum this - means adding functions to test for invalid float/doublevalues, - making sure the iterators never pass the end of the message, ... - (passing end of message can happen if: - - too many args in type tags - a. typetags overflow message size - b. args fulfilling typetags overflow message size - - strings too long or not terminated correctly - - blobs too long or not terminated correctly - - if the message was fully checked during construction, the end() iterator - could be moved back until only arguments which fit withing size() may - be interated (this could be none). A flag could be set to indicate that - something was wrong. - - - other packet badness could include: - - time tags too far into the future (the scheduler should deal with - that i guess). - - message address patterns which aren't correctly terminated - - - improve the ability to parse messages without tags (SC uses methods which - get the data and advance the iterator in one step.) - - Check* could be modified to do this - ie if typetags are not present - it could check that reading the field won't escape the message size - and return the data, or return false if some consistency - constraint is violated. - (or alternately drop support for messages without type tags) - - - - add a method to discard an inprogress message if it gets half - constructed and the buffer is full in OutboundPacket - - - write a stress testing app which can send garbage packets to try to flush out other bugs in the parsing code. - - - diff -r fcf435874395 -r 45c889eae324 front_idill/extern/fajran-npTuioClient/example/events.html --- a/front_idill/extern/fajran-npTuioClient/example/events.html Thu Apr 19 11:53:06 2012 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,48 +0,0 @@ - - -TUIO Client plugin test - - - - - - -Plugin FAILED to load - -

-
-
-
diff -r fcf435874395 -r 45c889eae324 front_idill/extern/fajran-npTuioClient/example/paint.html
--- a/front_idill/extern/fajran-npTuioClient/example/paint.html	Thu Apr 19 11:53:06 2012 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,73 +0,0 @@
-
-
-TUIO Client plugin test
-
-
-
-
-    
-
-Plugin FAILED to load
-
-
-
diff -r fcf435874395 -r 45c889eae324 front_idill/extern/fajran-npTuioClient/example/tracker.html
--- a/front_idill/extern/fajran-npTuioClient/example/tracker.html	Thu Apr 19 11:53:06 2012 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,73 +0,0 @@
-
-
-TUIO Client plugin test
-
-
-
-
-
-    
-
-Plugin FAILED to load
-
-
-
diff -r fcf435874395 -r 45c889eae324 front_idill/extern/fajran-npTuioClient/example/tuio.js
--- a/front_idill/extern/fajran-npTuioClient/example/tuio.js	Thu Apr 19 11:53:06 2012 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,89 +0,0 @@
-
-var tuio = {
-    cursors: [],
-    objects: [],
-
-    _data: {},
-
-    _cb_object_add:    function(obj) { },
-    _cb_object_update: function(obj) { },
-    _cb_object_remove: function(obj) { },
-    _cb_cursor_add:    function(cur) { },
-    _cb_cursor_update: function(cur) { },
-    _cb_cursor_remove: function(cur) { },
-
-    // Callback from the main event handler
-
-    callback: function(type, sid, fid, x, y, angle) {
-        var data;
-        
-        if ((type != 0) && (type != 3)) {
-            data = this._data[sid];
-        }
-        else {
-            data = {
-                sid: sid,
-                fid: fid
-            }
-            this._data[sid] = data;
-        }
-
-        data.x = x;
-        data.y = y;
-        
-        if (type < 3) {
-            data.angle = angle;
-        }
-
-        switch (type) {
-            case 0: 
-                this.objects.push(data);
-                this._cb_object_add(data);
-                break;
-
-            case 1: 
-                this._cb_object_update(data);
-                break;
-
-            case 2: 
-                this.objects.splice(this.objects.indexOf(data), 1);
-                this._cb_object_remove(data);
-                break;
-
-            case 3: 
-                this.cursors.push(data);
-                this._cb_cursor_add(data);
-                break;
-
-            case 4: 
-                this._cb_cursor_update(data);
-                break;
-
-            case 5: 
-                this.cursors.splice(this.cursors.indexOf(data), 1);
-                this._cb_cursor_remove(data);
-                break;
-
-            default:
-                break;
-        }
-
-        if ((type == 2) || (type == 5)) {
-            delete this._data[sid];
-        }
-    },
-
-    // Callback for the developer
-
-    object_add:    function(f) { this._cb_object_add    = f; },
-    object_update: function(f) { this._cb_object_update = f; },
-    object_remove: function(f) { this._cb_object_remove = f; },
-    cursor_add:    function(f) { this._cb_cursor_add    = f; },
-    cursor_update: function(f) { this._cb_cursor_update = f; },
-    cursor_remove: function(f) { this._cb_cursor_remove = f; },
-}
-
-function tuio_callback(type, sid, fid, x, y, angle)    {
-    tuio.callback(type, sid, fid, x, y, angle);
-}
-
diff -r fcf435874395 -r 45c889eae324 front_idill/extern/fajran-npTuioClient/npTuioClient.aps
Binary file front_idill/extern/fajran-npTuioClient/npTuioClient.aps has changed
diff -r fcf435874395 -r 45c889eae324 front_idill/extern/fajran-npTuioClient/npTuioClient.def
--- a/front_idill/extern/fajran-npTuioClient/npTuioClient.def	Thu Apr 19 11:53:06 2012 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,6 +0,0 @@
-LIBRARY   npTuioClient
-
-EXPORTS
-	NP_GetEntryPoints   @1
-	NP_Initialize       @2
-	NP_Shutdown         @3
diff -r fcf435874395 -r 45c889eae324 front_idill/extern/fajran-npTuioClient/npTuioClient.rc
--- a/front_idill/extern/fajran-npTuioClient/npTuioClient.rc	Thu Apr 19 11:53:06 2012 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,112 +0,0 @@
-//Microsoft Developer Studio generated resource script.
-//
-#include "resource.h"
-
-#define APSTUDIO_READONLY_SYMBOLS
-/////////////////////////////////////////////////////////////////////////////
-//
-// Generated from the TEXTINCLUDE 2 resource.
-//
-#include "afxres.h"
-
-/////////////////////////////////////////////////////////////////////////////
-#undef APSTUDIO_READONLY_SYMBOLS
-
-/////////////////////////////////////////////////////////////////////////////
-// English (U.S.) resources
-
-#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)
-#ifdef _WIN32
-LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US
-#pragma code_page(1252)
-#endif //_WIN32
-
-#ifndef _MAC
-/////////////////////////////////////////////////////////////////////////////
-//
-// Version
-//
-
-VS_VERSION_INFO VERSIONINFO
- FILEVERSION 0,2,0,0
- PRODUCTVERSION 0,2,0,0
- FILEFLAGSMASK 0x3fL
-#ifdef _DEBUG
- FILEFLAGS 0x1L
-#else
- FILEFLAGS 0x0L
-#endif
- FILEOS 0x40004L
- FILETYPE 0x2L
- FILESUBTYPE 0x0L
-BEGIN
-    BLOCK "StringFileInfo"
-    BEGIN
-        BLOCK "040904e4"
-        BEGIN
-            VALUE "Comments", "\0"
-            VALUE "CompanyName", " \0"
-            VALUE "FileDescription", "Tuio Client browser plugin\0"
-            VALUE "FileExtents", "\0"
-            VALUE "FileOpenName", "\0"
-            VALUE "FileVersion", "0, 2, 0, 0\0"
-            VALUE "InternalName", "npTuioClient\0"
-            VALUE "LegalCopyright", "Copyright © 2009\0"
-            VALUE "LegalTrademarks", "\0"
-            VALUE "MIMEType", "application/x-tuio\0"
-            VALUE "OriginalFilename", "npTuioClient.dll\0"
-            VALUE "PrivateBuild", "\0"
-            VALUE "ProductName", "Tuio Client browser plugin\0"
-            VALUE "ProductVersion", "0, 2, 0, 0\0"
-            VALUE "SpecialBuild", "\0"
-        END
-    END
-    BLOCK "VarFileInfo"
-    BEGIN
-        VALUE "Translation", 0x409, 1252
-    END
-END
-
-#endif    // !_MAC
-
-
-#ifdef APSTUDIO_INVOKED
-/////////////////////////////////////////////////////////////////////////////
-//
-// TEXTINCLUDE
-//
-
-1 TEXTINCLUDE DISCARDABLE 
-BEGIN
-    "resource.h\0"
-END
-
-2 TEXTINCLUDE DISCARDABLE 
-BEGIN
-    "#include ""afxres.h""\r\n"
-    "\0"
-END
-
-3 TEXTINCLUDE DISCARDABLE 
-BEGIN
-    "\r\n"
-    "\0"
-END
-
-#endif    // APSTUDIO_INVOKED
-
-#endif    // English (U.S.) resources
-/////////////////////////////////////////////////////////////////////////////
-
-
-
-#ifndef APSTUDIO_INVOKED
-/////////////////////////////////////////////////////////////////////////////
-//
-// Generated from the TEXTINCLUDE 3 resource.
-//
-
-
-/////////////////////////////////////////////////////////////////////////////
-#endif    // not APSTUDIO_INVOKED
-
diff -r fcf435874395 -r 45c889eae324 front_idill/extern/fajran-npTuioClient/npTuioClient.sln
--- a/front_idill/extern/fajran-npTuioClient/npTuioClient.sln	Thu Apr 19 11:53:06 2012 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,45 +0,0 @@
-
-Microsoft Visual Studio Solution File, Format Version 11.00
-# Visual Studio 2010
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "npTuioClient", "npTuioClient.vcxproj", "{E2668B4E-318C-4021-ADC8-A85D70234E63}"
-EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TestClient", "TestClient\TestClient.vcxproj", "{FF6BDC4B-76DF-4C4F-8C83-FA442C38D5C2}"
-	ProjectSection(ProjectDependencies) = postProject
-		{E2668B4E-318C-4021-ADC8-A85D70234E63} = {E2668B4E-318C-4021-ADC8-A85D70234E63}
-	EndProjectSection
-EndProject
-Global
-	GlobalSection(SolutionConfigurationPlatforms) = preSolution
-		Debug|Mixed Platforms = Debug|Mixed Platforms
-		Debug|Win32 = Debug|Win32
-		Debug|x86 = Debug|x86
-		Release|Mixed Platforms = Release|Mixed Platforms
-		Release|Win32 = Release|Win32
-		Release|x86 = Release|x86
-	EndGlobalSection
-	GlobalSection(ProjectConfigurationPlatforms) = postSolution
-		{E2668B4E-318C-4021-ADC8-A85D70234E63}.Debug|Mixed Platforms.ActiveCfg = Debug|Win32
-		{E2668B4E-318C-4021-ADC8-A85D70234E63}.Debug|Mixed Platforms.Build.0 = Debug|Win32
-		{E2668B4E-318C-4021-ADC8-A85D70234E63}.Debug|Win32.ActiveCfg = Debug|Win32
-		{E2668B4E-318C-4021-ADC8-A85D70234E63}.Debug|Win32.Build.0 = Debug|Win32
-		{E2668B4E-318C-4021-ADC8-A85D70234E63}.Debug|x86.ActiveCfg = Debug|Win32
-		{E2668B4E-318C-4021-ADC8-A85D70234E63}.Release|Mixed Platforms.ActiveCfg = Release|Win32
-		{E2668B4E-318C-4021-ADC8-A85D70234E63}.Release|Mixed Platforms.Build.0 = Release|Win32
-		{E2668B4E-318C-4021-ADC8-A85D70234E63}.Release|Win32.ActiveCfg = Release|Win32
-		{E2668B4E-318C-4021-ADC8-A85D70234E63}.Release|Win32.Build.0 = Release|Win32
-		{E2668B4E-318C-4021-ADC8-A85D70234E63}.Release|x86.ActiveCfg = Release|Win32
-		{FF6BDC4B-76DF-4C4F-8C83-FA442C38D5C2}.Debug|Mixed Platforms.ActiveCfg = Debug|Win32
-		{FF6BDC4B-76DF-4C4F-8C83-FA442C38D5C2}.Debug|Mixed Platforms.Build.0 = Debug|Win32
-		{FF6BDC4B-76DF-4C4F-8C83-FA442C38D5C2}.Debug|Win32.ActiveCfg = Debug|Win32
-		{FF6BDC4B-76DF-4C4F-8C83-FA442C38D5C2}.Debug|Win32.Build.0 = Debug|Win32
-		{FF6BDC4B-76DF-4C4F-8C83-FA442C38D5C2}.Debug|x86.ActiveCfg = Debug|Win32
-		{FF6BDC4B-76DF-4C4F-8C83-FA442C38D5C2}.Release|Mixed Platforms.ActiveCfg = Release|Win32
-		{FF6BDC4B-76DF-4C4F-8C83-FA442C38D5C2}.Release|Mixed Platforms.Build.0 = Release|Win32
-		{FF6BDC4B-76DF-4C4F-8C83-FA442C38D5C2}.Release|Win32.ActiveCfg = Release|Win32
-		{FF6BDC4B-76DF-4C4F-8C83-FA442C38D5C2}.Release|Win32.Build.0 = Release|Win32
-		{FF6BDC4B-76DF-4C4F-8C83-FA442C38D5C2}.Release|x86.ActiveCfg = Release|Win32
-	EndGlobalSection
-	GlobalSection(SolutionProperties) = preSolution
-		HideSolutionNode = FALSE
-	EndGlobalSection
-EndGlobal
diff -r fcf435874395 -r 45c889eae324 front_idill/extern/fajran-npTuioClient/npTuioClient.vcproj
--- a/front_idill/extern/fajran-npTuioClient/npTuioClient.vcproj	Thu Apr 19 11:53:06 2012 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,371 +0,0 @@
-
-
-	
-		
-	
-	
-	
-	
-		
-			
-			
-			
-			
-			
-			
-			
-			
-			
-			
-			
-			
-			
-			
-			
-			
-			
-		
-		
-			
-			
-			
-			
-			
-			
-			
-			
-			
-			
-			
-			
-			
-			
-			
-			
-			
-		
-	
-	
-	
-	
-		
-			
-			
-			
-			
-			
-			
-			
-			
-			
-			
-		
-		
-			
-			
-			
-			
-			
-			
-			
-			
-			
-			
-		
-		
-			
-			
-			
-			
-		
-		
-			
-			
-			
-			
-			
-			
-			
-			
-			
-			
-			
-			
-			
-			
-			
-				
-					
-					
-					
-					
-					
-					
-					
-					
-					
-					
-					
-					
-					
-					
-					
-					
-					
-					
-					
-					
-					
-					
-					
-					
-				
-				
-					
-					
-					
-					
-					
-					
-					
-					
-					
-					
-					
-					
-					
-						
-						
-						
-						
-					
-				
-			
-		
-	
-	
-	
-
diff -r fcf435874395 -r 45c889eae324 front_idill/extern/fajran-npTuioClient/npTuioClient.vcxproj
--- a/front_idill/extern/fajran-npTuioClient/npTuioClient.vcxproj	Thu Apr 19 11:53:06 2012 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,148 +0,0 @@
-
-
-  
-    
-      Debug
-      Win32
-    
-    
-      Release
-      Win32
-    
-  
-  
-    {E2668B4E-318C-4021-ADC8-A85D70234E63}
-    npTuioClient
-    Win32Proj
-  
-  
-  
-    DynamicLibrary
-    Unicode
-    true
-  
-  
-    DynamicLibrary
-    Unicode
-  
-  
-  
-  
-  
-    
-  
-  
-    
-  
-  
-  
-    <_ProjectFileVersion>10.0.30319.1
-    $(SolutionDir)$(Configuration)\
-    $(Configuration)\
-    true
-    $(SolutionDir)$(Configuration)\
-    $(Configuration)\
-    false
-    AllRules.ruleset
-    
-    
-    AllRules.ruleset
-    
-    
-  
-  
-    
-      Disabled
-      npapi;TuioClient;TuioClient\oscpack;%(AdditionalIncludeDirectories)
-      WIN32;_WINDOWS;XP_WIN32;MOZILLA_STRICT_API;XPCOM_GLUE;XP_WIN;_X86_;OSC_HOST_LITTLE_ENDIAN;%(PreprocessorDefinitions)
-      true
-      EnableFastChecks
-      MultiThreadedDebugDLL
-      
-      
-      Level3
-      EditAndContinue
-    
-    
-      ws2_32.lib;winmm.lib;%(AdditionalDependencies)
-      npTuioClient.def
-      true
-      Windows
-      MachineX86
-    
-  
-  
-    
-      MaxSpeed
-      true
-      npapi;TuioClient;TuioClient\oscpack;%(AdditionalIncludeDirectories)
-      WIN32;_WINDOWS;XP_WIN32;MOZILLA_STRICT_API;XPCOM_GLUE;XP_WIN;_X86_;OSC_HOST_LITTLE_ENDIAN;%(PreprocessorDefinitions)
-      MultiThreadedDLL
-      true
-      
-      
-      Level3
-      ProgramDatabase
-    
-    
-      ws2_32.lib;winmm.lib;%(AdditionalDependencies)
-      npTuioClient.def
-      true
-      Windows
-      true
-      true
-      MachineX86
-    
-  
-  
-    
-    
-    
-    
-    
-    
-    
-    
-    
-    
-    
-    
-    
-  
-  
-    
-    
-    
-    
-    
-    
-    
-    
-    
-    
-    
-    
-    
-    
-    
-    
-    
-    
-    
-    
-    
-    
-    
-    
-    
-  
-  
-    
-  
-  
-    
-  
-  
-  
-  
-
\ No newline at end of file
diff -r fcf435874395 -r 45c889eae324 front_idill/extern/fajran-npTuioClient/npTuioClient.vcxproj.filters
--- a/front_idill/extern/fajran-npTuioClient/npTuioClient.vcxproj.filters	Thu Apr 19 11:53:06 2012 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,160 +0,0 @@
-
-
-  
-    
-      {4FC737F1-C7A5-4376-A066-2A32D752A2FF}
-      cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx
-    
-    
-      {93995380-89BD-4b04-88EB-625FBE52EBFB}
-      h;hpp;hxx;hm;inl;inc;xsd
-    
-    
-      {67DA6AB6-F800-4c08-8B7A-83BB121AAD01}
-      rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav
-    
-    
-      {8f3f3524-d6ea-49ee-8987-e5cdd6811b2e}
-    
-    
-      {671f0f49-ca32-46b6-b6bf-d06ae95889fa}
-    
-    
-      {4dacaf2c-6883-439c-a93c-16a56737952e}
-    
-    
-      {19970ac0-1c1e-46ad-a7c3-64d94501de32}
-    
-    
-      {2990b422-02cd-4167-b7b2-62f1ed2e963e}
-    
-  
-  
-    
-      Source Files
-    
-    
-      Source Files
-    
-    
-      Source Files
-    
-    
-      Source Files
-    
-    
-      Source Files
-    
-    
-      TuioClient
-    
-    
-      TuioClient\oscpack\osc
-    
-    
-      TuioClient\oscpack\osc
-    
-    
-      TuioClient\oscpack\osc
-    
-    
-      TuioClient\oscpack\osc
-    
-    
-      TuioClient\oscpack\ip
-    
-    
-      TuioClient\oscpack\ip\win32
-    
-    
-      TuioClient\oscpack\ip\win32
-    
-  
-  
-    
-      Header Files
-    
-    
-      Header Files
-    
-    
-      Header Files
-    
-    
-      Header Files
-    
-    
-      Header Files
-    
-    
-      TuioClient
-    
-    
-      TuioClient
-    
-    
-      TuioClient
-    
-    
-      TuioClient
-    
-    
-      TuioClient
-    
-    
-      TuioClient
-    
-    
-      TuioClient\oscpack\osc
-    
-    
-      TuioClient\oscpack\osc
-    
-    
-      TuioClient\oscpack\osc
-    
-    
-      TuioClient\oscpack\osc
-    
-    
-      TuioClient\oscpack\osc
-    
-    
-      TuioClient\oscpack\osc
-    
-    
-      TuioClient\oscpack\osc
-    
-    
-      TuioClient\oscpack\osc
-    
-    
-      TuioClient\oscpack\ip
-    
-    
-      TuioClient\oscpack\ip
-    
-    
-      TuioClient\oscpack\ip
-    
-    
-      TuioClient\oscpack\ip
-    
-    
-      TuioClient\oscpack\ip
-    
-    
-      TuioClient
-    
-  
-  
-    
-      Resource Files
-    
-  
-  
-    
-      Resource Files
-    
-  
-
\ No newline at end of file
diff -r fcf435874395 -r 45c889eae324 front_idill/extern/fajran-npTuioClient/npTuioClient.xcodeproj/project.pbxproj
--- a/front_idill/extern/fajran-npTuioClient/npTuioClient.xcodeproj/project.pbxproj	Thu Apr 19 11:53:06 2012 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,385 +0,0 @@
-// !$*UTF8*$!
-{
-	archiveVersion = 1;
-	classes = {
-	};
-	objectVersion = 42;
-	objects = {
-
-/* Begin PBXBuildFile section */
-		3F79C6440FF778D800293A4E /* client.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 3F79C6130FF778D800293A4E /* client.cpp */; };
-		3F79C6450FF778D800293A4E /* np_entry.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 3F79C6150FF778D800293A4E /* np_entry.cpp */; };
-		3F79C6460FF778D800293A4E /* npn_gate.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 3F79C6160FF778D800293A4E /* npn_gate.cpp */; };
-		3F79C6470FF778D800293A4E /* npp_gate.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 3F79C6170FF778D800293A4E /* npp_gate.cpp */; };
-		3F79C6480FF778D800293A4E /* plugin.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 3F79C6190FF778D800293A4E /* plugin.cpp */; };
-		3F79C64A0FF778D800293A4E /* IpEndpointName.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 3F79C6200FF778D800293A4E /* IpEndpointName.cpp */; };
-		3F79C64B0FF778D800293A4E /* NetworkingUtils.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 3F79C6250FF778D800293A4E /* NetworkingUtils.cpp */; };
-		3F79C64C0FF778D800293A4E /* UdpSocket.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 3F79C6260FF778D800293A4E /* UdpSocket.cpp */; };
-		3F79C6500FF778D800293A4E /* OscOutboundPacketStream.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 3F79C6310FF778D800293A4E /* OscOutboundPacketStream.cpp */; };
-		3F79C6510FF778D800293A4E /* OscPrintReceivedElements.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 3F79C6340FF778D800293A4E /* OscPrintReceivedElements.cpp */; };
-		3F79C6520FF778D800293A4E /* OscReceivedElements.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 3F79C6360FF778D800293A4E /* OscReceivedElements.cpp */; };
-		3F79C6530FF778D800293A4E /* OscTypes.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 3F79C6380FF778D800293A4E /* OscTypes.cpp */; };
-		3F79C6560FF778D800293A4E /* TuioClient.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 3F79C63C0FF778D800293A4E /* TuioClient.cpp */; };
-		8D01CCCA0486CAD60068D4B7 /* InfoPlist.strings in Resources */ = {isa = PBXBuildFile; fileRef = 089C167DFE841241C02AAC07 /* InfoPlist.strings */; };
-/* End PBXBuildFile section */
-
-/* Begin PBXFileReference section */
-		089C167EFE841241C02AAC07 /* English */ = {isa = PBXFileReference; fileEncoding = 10; lastKnownFileType = text.plist.strings; name = English; path = English.lproj/InfoPlist.strings; sourceTree = ""; };
-		3F79C6130FF778D800293A4E /* client.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = client.cpp; sourceTree = ""; };
-		3F79C6140FF778D800293A4E /* client.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = client.h; sourceTree = ""; };
-		3F79C6150FF778D800293A4E /* np_entry.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = np_entry.cpp; sourceTree = ""; };
-		3F79C6160FF778D800293A4E /* npn_gate.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = npn_gate.cpp; sourceTree = ""; };
-		3F79C6170FF778D800293A4E /* npp_gate.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = npp_gate.cpp; sourceTree = ""; };
-		3F79C6180FF778D800293A4E /* npplat.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = npplat.h; sourceTree = ""; };
-		3F79C6190FF778D800293A4E /* plugin.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = plugin.cpp; sourceTree = ""; };
-		3F79C61A0FF778D800293A4E /* plugin.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = plugin.h; sourceTree = ""; };
-		3F79C61B0FF778D800293A4E /* pluginbase.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = pluginbase.h; sourceTree = ""; };
-		3F79C6200FF778D800293A4E /* IpEndpointName.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = IpEndpointName.cpp; sourceTree = ""; };
-		3F79C6210FF778D800293A4E /* IpEndpointName.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = IpEndpointName.h; sourceTree = ""; };
-		3F79C6220FF778D800293A4E /* NetworkingUtils.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = NetworkingUtils.h; sourceTree = ""; };
-		3F79C6230FF778D800293A4E /* PacketListener.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = PacketListener.h; sourceTree = ""; };
-		3F79C6250FF778D800293A4E /* NetworkingUtils.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = NetworkingUtils.cpp; sourceTree = ""; };
-		3F79C6260FF778D800293A4E /* UdpSocket.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = UdpSocket.cpp; sourceTree = ""; };
-		3F79C6270FF778D800293A4E /* TimerListener.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = TimerListener.h; sourceTree = ""; };
-		3F79C6280FF778D800293A4E /* UdpSocket.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = UdpSocket.h; sourceTree = ""; };
-		3F79C62E0FF778D800293A4E /* MessageMappingOscPacketListener.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = MessageMappingOscPacketListener.h; sourceTree = ""; };
-		3F79C62F0FF778D800293A4E /* OscException.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = OscException.h; sourceTree = ""; };
-		3F79C6300FF778D800293A4E /* OscHostEndianness.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = OscHostEndianness.h; sourceTree = ""; };
-		3F79C6310FF778D800293A4E /* OscOutboundPacketStream.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = OscOutboundPacketStream.cpp; sourceTree = ""; };
-		3F79C6320FF778D800293A4E /* OscOutboundPacketStream.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = OscOutboundPacketStream.h; sourceTree = ""; };
-		3F79C6330FF778D800293A4E /* OscPacketListener.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = OscPacketListener.h; sourceTree = ""; };
-		3F79C6340FF778D800293A4E /* OscPrintReceivedElements.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = OscPrintReceivedElements.cpp; sourceTree = ""; };
-		3F79C6350FF778D800293A4E /* OscPrintReceivedElements.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = OscPrintReceivedElements.h; sourceTree = ""; };
-		3F79C6360FF778D800293A4E /* OscReceivedElements.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = OscReceivedElements.cpp; sourceTree = ""; };
-		3F79C6370FF778D800293A4E /* OscReceivedElements.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = OscReceivedElements.h; sourceTree = ""; };
-		3F79C6380FF778D800293A4E /* OscTypes.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = OscTypes.cpp; sourceTree = ""; };
-		3F79C6390FF778D800293A4E /* OscTypes.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = OscTypes.h; sourceTree = ""; };
-		3F79C63C0FF778D800293A4E /* TuioClient.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; path = TuioClient.cpp; sourceTree = ""; };
-		3F79C63D0FF778D800293A4E /* TuioClient.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = TuioClient.h; sourceTree = ""; };
-		3F79C63E0FF778D800293A4E /* TuioContainer.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = TuioContainer.h; sourceTree = ""; };
-		3F79C63F0FF778D800293A4E /* TuioCursor.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = TuioCursor.h; sourceTree = ""; };
-		3F79C6400FF778D800293A4E /* TuioListener.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = TuioListener.h; sourceTree = ""; };
-		3F79C6410FF778D800293A4E /* TuioObject.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = TuioObject.h; sourceTree = ""; };
-		3F79C6420FF778D800293A4E /* TuioPoint.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = TuioPoint.h; sourceTree = ""; };
-		8D01CCD10486CAD60068D4B7 /* Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist; path = Info.plist; sourceTree = ""; };
-		8D01CCD20486CAD60068D4B7 /* npTuioClient.plugin */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = npTuioClient.plugin; sourceTree = BUILT_PRODUCTS_DIR; };
-/* End PBXFileReference section */
-
-/* Begin PBXFrameworksBuildPhase section */
-		8D01CCCD0486CAD60068D4B7 /* Frameworks */ = {
-			isa = PBXFrameworksBuildPhase;
-			buildActionMask = 2147483647;
-			files = (
-			);
-			runOnlyForDeploymentPostprocessing = 0;
-		};
-/* End PBXFrameworksBuildPhase section */
-
-/* Begin PBXGroup section */
-		089C166AFE841209C02AAC07 /* npTuioClient */ = {
-			isa = PBXGroup;
-			children = (
-				08FB77ADFE841716C02AAC07 /* Source */,
-				089C167CFE841241C02AAC07 /* Resources */,
-				089C1671FE841209C02AAC07 /* External Frameworks and Libraries */,
-				19C28FB4FE9D528D11CA2CBB /* Products */,
-			);
-			name = npTuioClient;
-			sourceTree = "";
-		};
-		089C1671FE841209C02AAC07 /* External Frameworks and Libraries */ = {
-			isa = PBXGroup;
-			children = (
-			);
-			name = "External Frameworks and Libraries";
-			sourceTree = "";
-		};
-		089C167CFE841241C02AAC07 /* Resources */ = {
-			isa = PBXGroup;
-			children = (
-				8D01CCD10486CAD60068D4B7 /* Info.plist */,
-				089C167DFE841241C02AAC07 /* InfoPlist.strings */,
-			);
-			name = Resources;
-			sourceTree = "";
-		};
-		08FB77ADFE841716C02AAC07 /* Source */ = {
-			isa = PBXGroup;
-			children = (
-				3F79C6110FF778D800293A4E /* src */,
-				3F79C61C0FF778D800293A4E /* TuioClient */,
-			);
-			name = Source;
-			sourceTree = "";
-		};
-		19C28FB4FE9D528D11CA2CBB /* Products */ = {
-			isa = PBXGroup;
-			children = (
-				8D01CCD20486CAD60068D4B7 /* npTuioClient.plugin */,
-			);
-			name = Products;
-			sourceTree = "";
-		};
-		3F79C6110FF778D800293A4E /* src */ = {
-			isa = PBXGroup;
-			children = (
-				3F79C6130FF778D800293A4E /* client.cpp */,
-				3F79C6140FF778D800293A4E /* client.h */,
-				3F79C6150FF778D800293A4E /* np_entry.cpp */,
-				3F79C6160FF778D800293A4E /* npn_gate.cpp */,
-				3F79C6170FF778D800293A4E /* npp_gate.cpp */,
-				3F79C6180FF778D800293A4E /* npplat.h */,
-				3F79C6190FF778D800293A4E /* plugin.cpp */,
-				3F79C61A0FF778D800293A4E /* plugin.h */,
-				3F79C61B0FF778D800293A4E /* pluginbase.h */,
-			);
-			path = src;
-			sourceTree = "";
-		};
-		3F79C61C0FF778D800293A4E /* TuioClient */ = {
-			isa = PBXGroup;
-			children = (
-				3F79C61D0FF778D800293A4E /* oscpack */,
-				3F79C63C0FF778D800293A4E /* TuioClient.cpp */,
-				3F79C63D0FF778D800293A4E /* TuioClient.h */,
-				3F79C63E0FF778D800293A4E /* TuioContainer.h */,
-				3F79C63F0FF778D800293A4E /* TuioCursor.h */,
-				3F79C6400FF778D800293A4E /* TuioListener.h */,
-				3F79C6410FF778D800293A4E /* TuioObject.h */,
-				3F79C6420FF778D800293A4E /* TuioPoint.h */,
-			);
-			path = TuioClient;
-			sourceTree = "";
-		};
-		3F79C61D0FF778D800293A4E /* oscpack */ = {
-			isa = PBXGroup;
-			children = (
-				3F79C61F0FF778D800293A4E /* ip */,
-				3F79C62D0FF778D800293A4E /* osc */,
-			);
-			path = oscpack;
-			sourceTree = "";
-		};
-		3F79C61F0FF778D800293A4E /* ip */ = {
-			isa = PBXGroup;
-			children = (
-				3F79C6200FF778D800293A4E /* IpEndpointName.cpp */,
-				3F79C6210FF778D800293A4E /* IpEndpointName.h */,
-				3F79C6220FF778D800293A4E /* NetworkingUtils.h */,
-				3F79C6230FF778D800293A4E /* PacketListener.h */,
-				3F79C6240FF778D800293A4E /* posix */,
-				3F79C6270FF778D800293A4E /* TimerListener.h */,
-				3F79C6280FF778D800293A4E /* UdpSocket.h */,
-			);
-			path = ip;
-			sourceTree = "";
-		};
-		3F79C6240FF778D800293A4E /* posix */ = {
-			isa = PBXGroup;
-			children = (
-				3F79C6250FF778D800293A4E /* NetworkingUtils.cpp */,
-				3F79C6260FF778D800293A4E /* UdpSocket.cpp */,
-			);
-			path = posix;
-			sourceTree = "";
-		};
-		3F79C62D0FF778D800293A4E /* osc */ = {
-			isa = PBXGroup;
-			children = (
-				3F79C62E0FF778D800293A4E /* MessageMappingOscPacketListener.h */,
-				3F79C62F0FF778D800293A4E /* OscException.h */,
-				3F79C6300FF778D800293A4E /* OscHostEndianness.h */,
-				3F79C6310FF778D800293A4E /* OscOutboundPacketStream.cpp */,
-				3F79C6320FF778D800293A4E /* OscOutboundPacketStream.h */,
-				3F79C6330FF778D800293A4E /* OscPacketListener.h */,
-				3F79C6340FF778D800293A4E /* OscPrintReceivedElements.cpp */,
-				3F79C6350FF778D800293A4E /* OscPrintReceivedElements.h */,
-				3F79C6360FF778D800293A4E /* OscReceivedElements.cpp */,
-				3F79C6370FF778D800293A4E /* OscReceivedElements.h */,
-				3F79C6380FF778D800293A4E /* OscTypes.cpp */,
-				3F79C6390FF778D800293A4E /* OscTypes.h */,
-			);
-			path = osc;
-			sourceTree = "";
-		};
-/* End PBXGroup section */
-
-/* Begin PBXNativeTarget section */
-		8D01CCC60486CAD60068D4B7 /* npTuioClient */ = {
-			isa = PBXNativeTarget;
-			buildConfigurationList = 4FADC23308B4156C00ABE55E /* Build configuration list for PBXNativeTarget "npTuioClient" */;
-			buildPhases = (
-				8D01CCC90486CAD60068D4B7 /* Resources */,
-				8D01CCCB0486CAD60068D4B7 /* Sources */,
-				8D01CCCD0486CAD60068D4B7 /* Frameworks */,
-			);
-			buildRules = (
-			);
-			dependencies = (
-			);
-			name = npTuioClient;
-			productInstallPath = "$(HOME)/Library/Bundles";
-			productName = npTuioClient;
-			productReference = 8D01CCD20486CAD60068D4B7 /* npTuioClient.plugin */;
-			productType = "com.apple.product-type.bundle";
-		};
-/* End PBXNativeTarget section */
-
-/* Begin PBXProject section */
-		089C1669FE841209C02AAC07 /* Project object */ = {
-			isa = PBXProject;
-			buildConfigurationList = 4FADC23708B4156C00ABE55E /* Build configuration list for PBXProject "npTuioClient" */;
-			hasScannedForEncodings = 1;
-			mainGroup = 089C166AFE841209C02AAC07 /* npTuioClient */;
-			projectDirPath = "";
-			targets = (
-				8D01CCC60486CAD60068D4B7 /* npTuioClient */,
-			);
-		};
-/* End PBXProject section */
-
-/* Begin PBXResourcesBuildPhase section */
-		8D01CCC90486CAD60068D4B7 /* Resources */ = {
-			isa = PBXResourcesBuildPhase;
-			buildActionMask = 2147483647;
-			files = (
-				8D01CCCA0486CAD60068D4B7 /* InfoPlist.strings in Resources */,
-			);
-			runOnlyForDeploymentPostprocessing = 0;
-		};
-/* End PBXResourcesBuildPhase section */
-
-/* Begin PBXSourcesBuildPhase section */
-		8D01CCCB0486CAD60068D4B7 /* Sources */ = {
-			isa = PBXSourcesBuildPhase;
-			buildActionMask = 2147483647;
-			files = (
-				3F79C6440FF778D800293A4E /* client.cpp in Sources */,
-				3F79C6450FF778D800293A4E /* np_entry.cpp in Sources */,
-				3F79C6460FF778D800293A4E /* npn_gate.cpp in Sources */,
-				3F79C6470FF778D800293A4E /* npp_gate.cpp in Sources */,
-				3F79C6480FF778D800293A4E /* plugin.cpp in Sources */,
-				3F79C64A0FF778D800293A4E /* IpEndpointName.cpp in Sources */,
-				3F79C64B0FF778D800293A4E /* NetworkingUtils.cpp in Sources */,
-				3F79C64C0FF778D800293A4E /* UdpSocket.cpp in Sources */,
-				3F79C6500FF778D800293A4E /* OscOutboundPacketStream.cpp in Sources */,
-				3F79C6510FF778D800293A4E /* OscPrintReceivedElements.cpp in Sources */,
-				3F79C6520FF778D800293A4E /* OscReceivedElements.cpp in Sources */,
-				3F79C6530FF778D800293A4E /* OscTypes.cpp in Sources */,
-				3F79C6560FF778D800293A4E /* TuioClient.cpp in Sources */,
-			);
-			runOnlyForDeploymentPostprocessing = 0;
-		};
-/* End PBXSourcesBuildPhase section */
-
-/* Begin PBXVariantGroup section */
-		089C167DFE841241C02AAC07 /* InfoPlist.strings */ = {
-			isa = PBXVariantGroup;
-			children = (
-				089C167EFE841241C02AAC07 /* English */,
-			);
-			name = InfoPlist.strings;
-			sourceTree = "";
-		};
-/* End PBXVariantGroup section */
-
-/* Begin XCBuildConfiguration section */
-		4FADC23408B4156C00ABE55E /* Debug */ = {
-			isa = XCBuildConfiguration;
-			buildSettings = {
-				ARCHS = i386;
-				COPY_PHASE_STRIP = NO;
-				GCC_DYNAMIC_NO_PIC = NO;
-				GCC_ENABLE_FIX_AND_CONTINUE = YES;
-				GCC_MODEL_TUNING = G5;
-				GCC_OPTIMIZATION_LEVEL = 0;
-				GCC_PRECOMPILE_PREFIX_HEADER = NO;
-				GCC_PREFIX_HEADER = "";
-				INFOPLIST_FILE = Info.plist;
-				INSTALL_PATH = "$(HOME)/Library/Bundles";
-				PRODUCT_NAME = npTuioClient;
-				WRAPPER_EXTENSION = plugin;
-				ZERO_LINK = YES;
-			};
-			name = Debug;
-		};
-		4FADC23508B4156C00ABE55E /* Release */ = {
-			isa = XCBuildConfiguration;
-			buildSettings = {
-				ARCHS = i386;
-				GCC_GENERATE_DEBUGGING_SYMBOLS = NO;
-				GCC_MODEL_TUNING = G5;
-				GCC_PRECOMPILE_PREFIX_HEADER = NO;
-				GCC_PREFIX_HEADER = "";
-				INFOPLIST_FILE = Info.plist;
-				INSTALL_PATH = "$(HOME)/Library/Bundles";
-				PRODUCT_NAME = npTuioClient;
-				WRAPPER_EXTENSION = plugin;
-			};
-			name = Release;
-		};
-		4FADC23808B4156C00ABE55E /* Debug */ = {
-			isa = XCBuildConfiguration;
-			buildSettings = {
-				GCC_PREPROCESSOR_DEFINITIONS = (
-					OSC_HOST_LITTLE_ENDIAN,
-					XP_MAC,
-					XP_MACOSX,
-				);
-				GCC_WARN_ABOUT_RETURN_TYPE = YES;
-				GCC_WARN_UNUSED_VARIABLE = YES;
-				HEADER_SEARCH_PATHS = (
-					npapi,
-					TuioClient,
-					TuioClient/oscpack,
-				);
-				PREBINDING = NO;
-				SDKROOT = /Developer/SDKs/MacOSX10.4u.sdk;
-			};
-			name = Debug;
-		};
-		4FADC23908B4156C00ABE55E /* Release */ = {
-			isa = XCBuildConfiguration;
-			buildSettings = {
-				GCC_PREPROCESSOR_DEFINITIONS = (
-					OSC_HOST_LITTLE_ENDIAN,
-					XP_MAC,
-					XP_MACOSX,
-				);
-				GCC_WARN_ABOUT_RETURN_TYPE = YES;
-				GCC_WARN_UNUSED_VARIABLE = YES;
-				HEADER_SEARCH_PATHS = (
-					npapi,
-					TuioClient,
-					TuioClient/oscpack,
-				);
-				PREBINDING = NO;
-				SDKROOT = /Developer/SDKs/MacOSX10.4u.sdk;
-			};
-			name = Release;
-		};
-/* End XCBuildConfiguration section */
-
-/* Begin XCConfigurationList section */
-		4FADC23308B4156C00ABE55E /* Build configuration list for PBXNativeTarget "npTuioClient" */ = {
-			isa = XCConfigurationList;
-			buildConfigurations = (
-				4FADC23408B4156C00ABE55E /* Debug */,
-				4FADC23508B4156C00ABE55E /* Release */,
-			);
-			defaultConfigurationIsVisible = 0;
-			defaultConfigurationName = Release;
-		};
-		4FADC23708B4156C00ABE55E /* Build configuration list for PBXProject "npTuioClient" */ = {
-			isa = XCConfigurationList;
-			buildConfigurations = (
-				4FADC23808B4156C00ABE55E /* Debug */,
-				4FADC23908B4156C00ABE55E /* Release */,
-			);
-			defaultConfigurationIsVisible = 0;
-			defaultConfigurationName = Release;
-		};
-/* End XCConfigurationList section */
-	};
-	rootObject = 089C1669FE841209C02AAC07 /* Project object */;
-}
diff -r fcf435874395 -r 45c889eae324 front_idill/extern/fajran-npTuioClient/npapi/jni.h
--- a/front_idill/extern/fajran-npTuioClient/npapi/jni.h	Thu Apr 19 11:53:06 2012 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,1973 +0,0 @@
-/* ***** BEGIN LICENSE BLOCK *****
- * Version: MPL 1.1/GPL 2.0/LGPL 2.1
- *
- * The contents of this file are subject to the Mozilla Public License Version
- * 1.1 (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- * http://www.mozilla.org/MPL/
- *
- * Software distributed under the License is distributed on an "AS IS" basis,
- * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
- * for the specific language governing rights and limitations under the
- * License.
- *
- * The Original Code is the Java Runtime Interface.
- *
- * The Initial Developer of the Original Code is
- * Netscape Communications Corporation and Sun Microsystems, Inc.
- * Portions created by the Initial Developer are Copyright (C) 1993-1996
- * the Initial Developer. All Rights Reserved.
- *
- * Contributor(s):
- *
- * Alternatively, the contents of this file may be used under the terms of
- * either the GNU General Public License Version 2 or later (the "GPL"), or
- * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
- * in which case the provisions of the GPL or the LGPL are applicable instead
- * of those above. If you wish to allow use of your version of this file only
- * under the terms of either the GPL or the LGPL, and not to allow others to
- * use your version of this file under the terms of the MPL, indicate your
- * decision by deleting the provisions above and replace them with the notice
- * and other provisions required by the GPL or the LGPL. If you do not delete
- * the provisions above, a recipient may use your version of this file under
- * the terms of any one of the MPL, the GPL or the LGPL.
- *
- * ***** END LICENSE BLOCK ***** */
-
-#ifndef JNI_H
-#define JNI_H
-
-#include 
-#include 
-
-/* jni_md.h contains the machine-dependent typedefs for jbyte, jint 
-   and jlong */ 
-
-#include "jni_md.h"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/*
- * JNI Types
- */
-
-typedef unsigned char	jboolean;
-typedef unsigned short	jchar;
-typedef short		jshort;
-typedef float		jfloat;
-typedef double		jdouble;
-
-typedef jint            jsize;
-
-#ifdef __cplusplus
-
-class _jobject {};
-class _jclass : public _jobject {};
-class _jthrowable : public _jobject {};
-class _jstring : public _jobject {};
-class _jarray : public _jobject {};
-class _jbooleanArray : public _jarray {};
-class _jbyteArray : public _jarray {};
-class _jcharArray : public _jarray {};
-class _jshortArray : public _jarray {};
-class _jintArray : public _jarray {};
-class _jlongArray : public _jarray {};
-class _jfloatArray : public _jarray {};
-class _jdoubleArray : public _jarray {};
-class _jobjectArray : public _jarray {};
-
-typedef _jobject *jobject;
-typedef _jclass *jclass;
-typedef _jthrowable *jthrowable;
-typedef _jstring *jstring;
-typedef _jarray *jarray;
-typedef _jbooleanArray *jbooleanArray;
-typedef _jbyteArray *jbyteArray;
-typedef _jcharArray *jcharArray;
-typedef _jshortArray *jshortArray;
-typedef _jintArray *jintArray;
-typedef _jlongArray *jlongArray;
-typedef _jfloatArray *jfloatArray;
-typedef _jdoubleArray *jdoubleArray;
-typedef _jobjectArray *jobjectArray;
-
-#else
-
-struct _jobject;
-
-typedef struct _jobject *jobject;
-typedef jobject jclass;
-typedef jobject jthrowable;
-typedef jobject jstring;
-typedef jobject jarray;
-typedef jarray jbooleanArray;
-typedef jarray jbyteArray;
-typedef jarray jcharArray;
-typedef jarray jshortArray;
-typedef jarray jintArray;
-typedef jarray jlongArray;
-typedef jarray jfloatArray;
-typedef jarray jdoubleArray;
-typedef jarray jobjectArray;
-
-#endif
-
-typedef jobject jweak;
-
-#if 0	/* moved to jri_md.h */
-typedef jobject jref; /* For transition---not meant to be part of public 
-			 API anymore.*/
-#endif
-
-typedef union jvalue {
-    jboolean z;
-    jbyte    b;
-    jchar    c;
-    jshort   s;
-    jint     i;
-    jlong    j;
-    jfloat   f;
-    jdouble  d;
-    jobject  l;
-} jvalue;
-
-struct _jfieldID;
-typedef struct _jfieldID *jfieldID;
-
-struct _jmethodID;
-typedef struct _jmethodID *jmethodID;
-
-/*
- * jboolean constants
- */
-
-#define JNI_FALSE 0
-#define JNI_TRUE 1
-
-/*
- * possible return values for JNI functions.
- */
-
-#define JNI_OK           0                 /* success */
-#define JNI_ERR          (-1)              /* unknown error */
-#define JNI_EDETACHED    (-2)              /* thread detached from the VM */
-#define JNI_EVERSION     (-3)              /* JNI version error */
-#define JNI_ENOMEM       (-4)              /* not enough memory */
-#define JNI_EEXIST       (-5)              /* VM already created */
-#define JNI_EINVAL       (-6)              /* invalid arguments */
-
-/*
- * used in ReleaseScalarArrayElements
- */
-  
-#define JNI_COMMIT 1
-#define JNI_ABORT 2
-
-/*
- * used in RegisterNatives to describe native method name, signature,
- * and function pointer.
- */
-
-typedef struct {
-    char *name;
-    char *signature;
-    void *fnPtr;
-} JNINativeMethod;
-
-/*
- * JNI Native Method Interface.
- */
-
-struct JNINativeInterface_;
-
-struct JNIEnv_;
-
-#ifdef __cplusplus
-typedef JNIEnv_ JNIEnv;
-#else
-typedef const struct JNINativeInterface_ *JNIEnv;
-#endif
-
-/*
- * JNI Invocation Interface.
- */
-
-struct JNIInvokeInterface_;
-
-struct JavaVM_;
-
-#ifdef __cplusplus
-typedef JavaVM_ JavaVM;
-#else
-typedef const struct JNIInvokeInterface_ *JavaVM;
-#endif
-
-struct JNINativeInterface_ {
-    void *reserved0;
-    void *reserved1;
-    void *reserved2;
-
-    void *reserved3;
-    jint (JNICALL *GetVersion)(JNIEnv *env);
-
-    jclass (JNICALL *DefineClass)
-      (JNIEnv *env, const char *name, jobject loader, const jbyte *buf, 
-       jsize len);
-    jclass (JNICALL *FindClass)
-      (JNIEnv *env, const char *name);
-
-    jmethodID (JNICALL *FromReflectedMethod)
-      (JNIEnv *env, jobject method);
-    jfieldID (JNICALL *FromReflectedField)
-      (JNIEnv *env, jobject field);
-
-    jobject (JNICALL *ToReflectedMethod)
-      (JNIEnv *env, jclass cls, jmethodID methodID, jboolean isStatic);
-
-    jclass (JNICALL *GetSuperclass)
-      (JNIEnv *env, jclass sub);
-    jboolean (JNICALL *IsAssignableFrom)
-      (JNIEnv *env, jclass sub, jclass sup);
-
-    jobject (JNICALL *ToReflectedField)
-      (JNIEnv *env, jclass cls, jfieldID fieldID, jboolean isStatic);
-
-    jint (JNICALL *Throw)
-      (JNIEnv *env, jthrowable obj);
-    jint (JNICALL *ThrowNew)
-      (JNIEnv *env, jclass clazz, const char *msg);
-    jthrowable (JNICALL *ExceptionOccurred)
-      (JNIEnv *env);
-    void (JNICALL *ExceptionDescribe)
-      (JNIEnv *env);
-    void (JNICALL *ExceptionClear)
-      (JNIEnv *env);
-    void (JNICALL *FatalError)
-      (JNIEnv *env, const char *msg);
-
-    jint (JNICALL *PushLocalFrame)
-      (JNIEnv *env, jint capacity);
-    jobject (JNICALL *PopLocalFrame)
-      (JNIEnv *env, jobject result);
-
-    jobject (JNICALL *NewGlobalRef)
-      (JNIEnv *env, jobject lobj);
-    void (JNICALL *DeleteGlobalRef)
-      (JNIEnv *env, jobject gref);
-    void (JNICALL *DeleteLocalRef)
-      (JNIEnv *env, jobject obj);
-    jboolean (JNICALL *IsSameObject)
-      (JNIEnv *env, jobject obj1, jobject obj2);
-    jobject (JNICALL *NewLocalRef)
-      (JNIEnv *env, jobject ref);
-    jint (JNICALL *EnsureLocalCapacity)
-      (JNIEnv *env, jint capacity);
-
-    jobject (JNICALL *AllocObject)
-      (JNIEnv *env, jclass clazz);
-    jobject (JNICALL *NewObject)
-      (JNIEnv *env, jclass clazz, jmethodID methodID, ...);
-    jobject (JNICALL *NewObjectV)
-      (JNIEnv *env, jclass clazz, jmethodID methodID, va_list args);
-    jobject (JNICALL *NewObjectA)
-      (JNIEnv *env, jclass clazz, jmethodID methodID, jvalue *args);
-
-    jclass (JNICALL *GetObjectClass)
-      (JNIEnv *env, jobject obj);
-    jboolean (JNICALL *IsInstanceOf)
-      (JNIEnv *env, jobject obj, jclass clazz);
-
-    jmethodID (JNICALL *GetMethodID)
-      (JNIEnv *env, jclass clazz, const char *name, const char *sig);
-
-    jobject (JNICALL *CallObjectMethod)
-      (JNIEnv *env, jobject obj, jmethodID methodID, ...);
-    jobject (JNICALL *CallObjectMethodV)
-      (JNIEnv *env, jobject obj, jmethodID methodID, va_list args);
-    jobject (JNICALL *CallObjectMethodA)
-      (JNIEnv *env, jobject obj, jmethodID methodID, jvalue * args);
-
-    jboolean (JNICALL *CallBooleanMethod)
-      (JNIEnv *env, jobject obj, jmethodID methodID, ...);
-    jboolean (JNICALL *CallBooleanMethodV)
-      (JNIEnv *env, jobject obj, jmethodID methodID, va_list args);
-    jboolean (JNICALL *CallBooleanMethodA)
-      (JNIEnv *env, jobject obj, jmethodID methodID, jvalue * args);
-
-    jbyte (JNICALL *CallByteMethod)
-      (JNIEnv *env, jobject obj, jmethodID methodID, ...);
-    jbyte (JNICALL *CallByteMethodV)
-      (JNIEnv *env, jobject obj, jmethodID methodID, va_list args);
-    jbyte (JNICALL *CallByteMethodA)
-      (JNIEnv *env, jobject obj, jmethodID methodID, jvalue *args);
-
-    jchar (JNICALL *CallCharMethod)
-      (JNIEnv *env, jobject obj, jmethodID methodID, ...);
-    jchar (JNICALL *CallCharMethodV)
-      (JNIEnv *env, jobject obj, jmethodID methodID, va_list args);
-    jchar (JNICALL *CallCharMethodA)
-      (JNIEnv *env, jobject obj, jmethodID methodID, jvalue *args);
-
-    jshort (JNICALL *CallShortMethod)
-      (JNIEnv *env, jobject obj, jmethodID methodID, ...);
-    jshort (JNICALL *CallShortMethodV)
-      (JNIEnv *env, jobject obj, jmethodID methodID, va_list args);
-    jshort (JNICALL *CallShortMethodA)
-      (JNIEnv *env, jobject obj, jmethodID methodID, jvalue *args);
-
-    jint (JNICALL *CallIntMethod)
-      (JNIEnv *env, jobject obj, jmethodID methodID, ...);
-    jint (JNICALL *CallIntMethodV)
-      (JNIEnv *env, jobject obj, jmethodID methodID, va_list args);
-    jint (JNICALL *CallIntMethodA)
-      (JNIEnv *env, jobject obj, jmethodID methodID, jvalue *args);
-
-    jlong (JNICALL *CallLongMethod)
-      (JNIEnv *env, jobject obj, jmethodID methodID, ...);
-    jlong (JNICALL *CallLongMethodV)
-      (JNIEnv *env, jobject obj, jmethodID methodID, va_list args);
-    jlong (JNICALL *CallLongMethodA)
-      (JNIEnv *env, jobject obj, jmethodID methodID, jvalue *args);
-
-    jfloat (JNICALL *CallFloatMethod)
-      (JNIEnv *env, jobject obj, jmethodID methodID, ...);
-    jfloat (JNICALL *CallFloatMethodV)
-      (JNIEnv *env, jobject obj, jmethodID methodID, va_list args);
-    jfloat (JNICALL *CallFloatMethodA)
-      (JNIEnv *env, jobject obj, jmethodID methodID, jvalue *args);
-
-    jdouble (JNICALL *CallDoubleMethod)
-      (JNIEnv *env, jobject obj, jmethodID methodID, ...);
-    jdouble (JNICALL *CallDoubleMethodV)
-      (JNIEnv *env, jobject obj, jmethodID methodID, va_list args);
-    jdouble (JNICALL *CallDoubleMethodA)
-      (JNIEnv *env, jobject obj, jmethodID methodID, jvalue *args);
-
-    void (JNICALL *CallVoidMethod)
-      (JNIEnv *env, jobject obj, jmethodID methodID, ...);
-    void (JNICALL *CallVoidMethodV)
-      (JNIEnv *env, jobject obj, jmethodID methodID, va_list args);
-    void (JNICALL *CallVoidMethodA)
-      (JNIEnv *env, jobject obj, jmethodID methodID, jvalue * args);
-
-    jobject (JNICALL *CallNonvirtualObjectMethod)
-      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID, ...);
-    jobject (JNICALL *CallNonvirtualObjectMethodV)
-      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID, 
-       va_list args);
-    jobject (JNICALL *CallNonvirtualObjectMethodA)
-      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID, 
-       jvalue * args);
-
-    jboolean (JNICALL *CallNonvirtualBooleanMethod)
-      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID, ...);
-    jboolean (JNICALL *CallNonvirtualBooleanMethodV)
-      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,
-       va_list args);
-    jboolean (JNICALL *CallNonvirtualBooleanMethodA)
-      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,
-       jvalue * args);
-
-    jbyte (JNICALL *CallNonvirtualByteMethod)
-      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID, ...);
-    jbyte (JNICALL *CallNonvirtualByteMethodV)
-      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,
-       va_list args);
-    jbyte (JNICALL *CallNonvirtualByteMethodA)
-      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID, 
-       jvalue *args);
-
-    jchar (JNICALL *CallNonvirtualCharMethod)
-      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID, ...);
-    jchar (JNICALL *CallNonvirtualCharMethodV)
-      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,
-       va_list args);
-    jchar (JNICALL *CallNonvirtualCharMethodA)
-      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,
-       jvalue *args);
-
-    jshort (JNICALL *CallNonvirtualShortMethod)
-      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID, ...);
-    jshort (JNICALL *CallNonvirtualShortMethodV)
-      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,
-       va_list args);
-    jshort (JNICALL *CallNonvirtualShortMethodA)
-      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,
-       jvalue *args);
-
-    jint (JNICALL *CallNonvirtualIntMethod)
-      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID, ...);
-    jint (JNICALL *CallNonvirtualIntMethodV)
-      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,
-       va_list args);
-    jint (JNICALL *CallNonvirtualIntMethodA)
-      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,
-       jvalue *args);
-
-    jlong (JNICALL *CallNonvirtualLongMethod)
-      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID, ...);
-    jlong (JNICALL *CallNonvirtualLongMethodV)
-      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,
-       va_list args);
-    jlong (JNICALL *CallNonvirtualLongMethodA)
-      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID, 
-       jvalue *args);
-
-    jfloat (JNICALL *CallNonvirtualFloatMethod)
-      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID, ...);
-    jfloat (JNICALL *CallNonvirtualFloatMethodV)
-      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,
-       va_list args);
-    jfloat (JNICALL *CallNonvirtualFloatMethodA)
-      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,
-       jvalue *args);
-
-    jdouble (JNICALL *CallNonvirtualDoubleMethod)
-      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID, ...);
-    jdouble (JNICALL *CallNonvirtualDoubleMethodV)
-      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,
-       va_list args);
-    jdouble (JNICALL *CallNonvirtualDoubleMethodA)
-      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,
-       jvalue *args);
-
-    void (JNICALL *CallNonvirtualVoidMethod)
-      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID, ...);
-    void (JNICALL *CallNonvirtualVoidMethodV)
-      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,
-       va_list args);
-    void (JNICALL *CallNonvirtualVoidMethodA)
-      (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,
-       jvalue * args);
-
-    jfieldID (JNICALL *GetFieldID)
-      (JNIEnv *env, jclass clazz, const char *name, const char *sig);
-
-    jobject (JNICALL *GetObjectField)
-      (JNIEnv *env, jobject obj, jfieldID fieldID);
-    jboolean (JNICALL *GetBooleanField)
-      (JNIEnv *env, jobject obj, jfieldID fieldID);
-    jbyte (JNICALL *GetByteField)
-      (JNIEnv *env, jobject obj, jfieldID fieldID);
-    jchar (JNICALL *GetCharField)
-      (JNIEnv *env, jobject obj, jfieldID fieldID);
-    jshort (JNICALL *GetShortField)
-      (JNIEnv *env, jobject obj, jfieldID fieldID);
-    jint (JNICALL *GetIntField)
-      (JNIEnv *env, jobject obj, jfieldID fieldID);
-    jlong (JNICALL *GetLongField)
-      (JNIEnv *env, jobject obj, jfieldID fieldID);
-    jfloat (JNICALL *GetFloatField)
-      (JNIEnv *env, jobject obj, jfieldID fieldID);
-    jdouble (JNICALL *GetDoubleField)
-      (JNIEnv *env, jobject obj, jfieldID fieldID);
-
-    void (JNICALL *SetObjectField)
-      (JNIEnv *env, jobject obj, jfieldID fieldID, jobject val);
-    void (JNICALL *SetBooleanField)
-      (JNIEnv *env, jobject obj, jfieldID fieldID, jboolean val);
-    void (JNICALL *SetByteField)
-      (JNIEnv *env, jobject obj, jfieldID fieldID, jbyte val);
-    void (JNICALL *SetCharField)
-      (JNIEnv *env, jobject obj, jfieldID fieldID, jchar val);
-    void (JNICALL *SetShortField)
-      (JNIEnv *env, jobject obj, jfieldID fieldID, jshort val);
-    void (JNICALL *SetIntField)
-      (JNIEnv *env, jobject obj, jfieldID fieldID, jint val);
-    void (JNICALL *SetLongField)
-      (JNIEnv *env, jobject obj, jfieldID fieldID, jlong val);
-    void (JNICALL *SetFloatField)
-      (JNIEnv *env, jobject obj, jfieldID fieldID, jfloat val);
-    void (JNICALL *SetDoubleField)
-      (JNIEnv *env, jobject obj, jfieldID fieldID, jdouble val);
-
-    jmethodID (JNICALL *GetStaticMethodID)
-      (JNIEnv *env, jclass clazz, const char *name, const char *sig);
-
-    jobject (JNICALL *CallStaticObjectMethod)
-      (JNIEnv *env, jclass clazz, jmethodID methodID, ...);
-    jobject (JNICALL *CallStaticObjectMethodV)
-      (JNIEnv *env, jclass clazz, jmethodID methodID, va_list args);
-    jobject (JNICALL *CallStaticObjectMethodA)
-      (JNIEnv *env, jclass clazz, jmethodID methodID, jvalue *args);
-
-    jboolean (JNICALL *CallStaticBooleanMethod)
-      (JNIEnv *env, jclass clazz, jmethodID methodID, ...);
-    jboolean (JNICALL *CallStaticBooleanMethodV)
-      (JNIEnv *env, jclass clazz, jmethodID methodID, va_list args);
-    jboolean (JNICALL *CallStaticBooleanMethodA)
-      (JNIEnv *env, jclass clazz, jmethodID methodID, jvalue *args);
-
-    jbyte (JNICALL *CallStaticByteMethod)
-      (JNIEnv *env, jclass clazz, jmethodID methodID, ...);
-    jbyte (JNICALL *CallStaticByteMethodV)
-      (JNIEnv *env, jclass clazz, jmethodID methodID, va_list args);
-    jbyte (JNICALL *CallStaticByteMethodA)
-      (JNIEnv *env, jclass clazz, jmethodID methodID, jvalue *args);
-
-    jchar (JNICALL *CallStaticCharMethod)
-      (JNIEnv *env, jclass clazz, jmethodID methodID, ...);
-    jchar (JNICALL *CallStaticCharMethodV)
-      (JNIEnv *env, jclass clazz, jmethodID methodID, va_list args);
-    jchar (JNICALL *CallStaticCharMethodA)
-      (JNIEnv *env, jclass clazz, jmethodID methodID, jvalue *args);
-
-    jshort (JNICALL *CallStaticShortMethod)
-      (JNIEnv *env, jclass clazz, jmethodID methodID, ...);
-    jshort (JNICALL *CallStaticShortMethodV)
-      (JNIEnv *env, jclass clazz, jmethodID methodID, va_list args);
-    jshort (JNICALL *CallStaticShortMethodA)
-      (JNIEnv *env, jclass clazz, jmethodID methodID, jvalue *args);
-
-    jint (JNICALL *CallStaticIntMethod)
-      (JNIEnv *env, jclass clazz, jmethodID methodID, ...);
-    jint (JNICALL *CallStaticIntMethodV)
-      (JNIEnv *env, jclass clazz, jmethodID methodID, va_list args);
-    jint (JNICALL *CallStaticIntMethodA)
-      (JNIEnv *env, jclass clazz, jmethodID methodID, jvalue *args);
-
-    jlong (JNICALL *CallStaticLongMethod)
-      (JNIEnv *env, jclass clazz, jmethodID methodID, ...);
-    jlong (JNICALL *CallStaticLongMethodV)
-      (JNIEnv *env, jclass clazz, jmethodID methodID, va_list args);
-    jlong (JNICALL *CallStaticLongMethodA)
-      (JNIEnv *env, jclass clazz, jmethodID methodID, jvalue *args);
-
-    jfloat (JNICALL *CallStaticFloatMethod)
-      (JNIEnv *env, jclass clazz, jmethodID methodID, ...);
-    jfloat (JNICALL *CallStaticFloatMethodV)
-      (JNIEnv *env, jclass clazz, jmethodID methodID, va_list args);
-    jfloat (JNICALL *CallStaticFloatMethodA)
-      (JNIEnv *env, jclass clazz, jmethodID methodID, jvalue *args);
-
-    jdouble (JNICALL *CallStaticDoubleMethod)
-      (JNIEnv *env, jclass clazz, jmethodID methodID, ...);
-    jdouble (JNICALL *CallStaticDoubleMethodV)
-      (JNIEnv *env, jclass clazz, jmethodID methodID, va_list args);
-    jdouble (JNICALL *CallStaticDoubleMethodA)       
-      (JNIEnv *env, jclass clazz, jmethodID methodID, jvalue *args);
-
-    void (JNICALL *CallStaticVoidMethod)
-      (JNIEnv *env, jclass cls, jmethodID methodID, ...);
-    void (JNICALL *CallStaticVoidMethodV)
-      (JNIEnv *env, jclass cls, jmethodID methodID, va_list args);
-    void (JNICALL *CallStaticVoidMethodA)
-      (JNIEnv *env, jclass cls, jmethodID methodID, jvalue * args);
-
-    jfieldID (JNICALL *GetStaticFieldID)
-      (JNIEnv *env, jclass clazz, const char *name, const char *sig);
-    jobject (JNICALL *GetStaticObjectField)
-      (JNIEnv *env, jclass clazz, jfieldID fieldID);
-    jboolean (JNICALL *GetStaticBooleanField)
-      (JNIEnv *env, jclass clazz, jfieldID fieldID);
-    jbyte (JNICALL *GetStaticByteField)
-      (JNIEnv *env, jclass clazz, jfieldID fieldID);
-    jchar (JNICALL *GetStaticCharField)
-      (JNIEnv *env, jclass clazz, jfieldID fieldID);
-    jshort (JNICALL *GetStaticShortField)
-      (JNIEnv *env, jclass clazz, jfieldID fieldID);
-    jint (JNICALL *GetStaticIntField)
-      (JNIEnv *env, jclass clazz, jfieldID fieldID);
-    jlong (JNICALL *GetStaticLongField)
-      (JNIEnv *env, jclass clazz, jfieldID fieldID);
-    jfloat (JNICALL *GetStaticFloatField)
-      (JNIEnv *env, jclass clazz, jfieldID fieldID);
-    jdouble (JNICALL *GetStaticDoubleField)
-      (JNIEnv *env, jclass clazz, jfieldID fieldID);
-
-    void (JNICALL *SetStaticObjectField)
-      (JNIEnv *env, jclass clazz, jfieldID fieldID, jobject value);
-    void (JNICALL *SetStaticBooleanField)
-      (JNIEnv *env, jclass clazz, jfieldID fieldID, jboolean value);
-    void (JNICALL *SetStaticByteField)
-      (JNIEnv *env, jclass clazz, jfieldID fieldID, jbyte value);
-    void (JNICALL *SetStaticCharField)
-      (JNIEnv *env, jclass clazz, jfieldID fieldID, jchar value);
-    void (JNICALL *SetStaticShortField)
-      (JNIEnv *env, jclass clazz, jfieldID fieldID, jshort value);
-    void (JNICALL *SetStaticIntField)
-      (JNIEnv *env, jclass clazz, jfieldID fieldID, jint value);
-    void (JNICALL *SetStaticLongField)
-      (JNIEnv *env, jclass clazz, jfieldID fieldID, jlong value);
-    void (JNICALL *SetStaticFloatField)
-      (JNIEnv *env, jclass clazz, jfieldID fieldID, jfloat value);
-    void (JNICALL *SetStaticDoubleField)
-      (JNIEnv *env, jclass clazz, jfieldID fieldID, jdouble value);
-
-    jstring (JNICALL *NewString)
-      (JNIEnv *env, const jchar *unicode, jsize len);
-    jsize (JNICALL *GetStringLength)
-      (JNIEnv *env, jstring str);
-    const jchar *(JNICALL *GetStringChars)
-      (JNIEnv *env, jstring str, jboolean *isCopy);
-    void (JNICALL *ReleaseStringChars)
-      (JNIEnv *env, jstring str, const jchar *chars);
-  
-    jstring (JNICALL *NewStringUTF)
-      (JNIEnv *env, const char *utf);
-    jsize (JNICALL *GetStringUTFLength)
-      (JNIEnv *env, jstring str);
-    const char* (JNICALL *GetStringUTFChars)
-      (JNIEnv *env, jstring str, jboolean *isCopy);
-    void (JNICALL *ReleaseStringUTFChars)
-      (JNIEnv *env, jstring str, const char* chars);
-  
-
-    jsize (JNICALL *GetArrayLength)
-      (JNIEnv *env, jarray array);
-
-    jobjectArray (JNICALL *NewObjectArray)
-      (JNIEnv *env, jsize len, jclass clazz, jobject init);
-    jobject (JNICALL *GetObjectArrayElement)
-      (JNIEnv *env, jobjectArray array, jsize index);
-    void (JNICALL *SetObjectArrayElement)
-      (JNIEnv *env, jobjectArray array, jsize index, jobject val);
-
-    jbooleanArray (JNICALL *NewBooleanArray)
-      (JNIEnv *env, jsize len);
-    jbyteArray (JNICALL *NewByteArray)
-      (JNIEnv *env, jsize len);
-    jcharArray (JNICALL *NewCharArray)
-      (JNIEnv *env, jsize len);
-    jshortArray (JNICALL *NewShortArray)
-      (JNIEnv *env, jsize len);
-    jintArray (JNICALL *NewIntArray)
-      (JNIEnv *env, jsize len);
-    jlongArray (JNICALL *NewLongArray)
-      (JNIEnv *env, jsize len);
-    jfloatArray (JNICALL *NewFloatArray)
-      (JNIEnv *env, jsize len);
-    jdoubleArray (JNICALL *NewDoubleArray)
-      (JNIEnv *env, jsize len);
-
-    jboolean * (JNICALL *GetBooleanArrayElements)
-      (JNIEnv *env, jbooleanArray array, jboolean *isCopy);
-    jbyte * (JNICALL *GetByteArrayElements)
-      (JNIEnv *env, jbyteArray array, jboolean *isCopy);
-    jchar * (JNICALL *GetCharArrayElements)
-      (JNIEnv *env, jcharArray array, jboolean *isCopy);
-    jshort * (JNICALL *GetShortArrayElements)
-      (JNIEnv *env, jshortArray array, jboolean *isCopy);
-    jint * (JNICALL *GetIntArrayElements)
-      (JNIEnv *env, jintArray array, jboolean *isCopy);
-    jlong * (JNICALL *GetLongArrayElements)
-      (JNIEnv *env, jlongArray array, jboolean *isCopy);
-    jfloat * (JNICALL *GetFloatArrayElements)
-      (JNIEnv *env, jfloatArray array, jboolean *isCopy);
-    jdouble * (JNICALL *GetDoubleArrayElements)
-      (JNIEnv *env, jdoubleArray array, jboolean *isCopy);
-
-    void (JNICALL *ReleaseBooleanArrayElements)
-      (JNIEnv *env, jbooleanArray array, jboolean *elems, jint mode);
-    void (JNICALL *ReleaseByteArrayElements)
-      (JNIEnv *env, jbyteArray array, jbyte *elems, jint mode);
-    void (JNICALL *ReleaseCharArrayElements)
-      (JNIEnv *env, jcharArray array, jchar *elems, jint mode);
-    void (JNICALL *ReleaseShortArrayElements)
-      (JNIEnv *env, jshortArray array, jshort *elems, jint mode);
-    void (JNICALL *ReleaseIntArrayElements)
-      (JNIEnv *env, jintArray array, jint *elems, jint mode);
-    void (JNICALL *ReleaseLongArrayElements)
-      (JNIEnv *env, jlongArray array, jlong *elems, jint mode);
-    void (JNICALL *ReleaseFloatArrayElements)
-      (JNIEnv *env, jfloatArray array, jfloat *elems, jint mode);
-    void (JNICALL *ReleaseDoubleArrayElements)
-      (JNIEnv *env, jdoubleArray array, jdouble *elems, jint mode);
-
-    void (JNICALL *GetBooleanArrayRegion)
-      (JNIEnv *env, jbooleanArray array, jsize start, jsize l, jboolean *buf);
-    void (JNICALL *GetByteArrayRegion)
-      (JNIEnv *env, jbyteArray array, jsize start, jsize len, jbyte *buf);
-    void (JNICALL *GetCharArrayRegion)
-      (JNIEnv *env, jcharArray array, jsize start, jsize len, jchar *buf);
-    void (JNICALL *GetShortArrayRegion)
-      (JNIEnv *env, jshortArray array, jsize start, jsize len, jshort *buf);
-    void (JNICALL *GetIntArrayRegion)
-      (JNIEnv *env, jintArray array, jsize start, jsize len, jint *buf);
-    void (JNICALL *GetLongArrayRegion)
-      (JNIEnv *env, jlongArray array, jsize start, jsize len, jlong *buf);
-    void (JNICALL *GetFloatArrayRegion)
-      (JNIEnv *env, jfloatArray array, jsize start, jsize len, jfloat *buf);
-    void (JNICALL *GetDoubleArrayRegion)
-      (JNIEnv *env, jdoubleArray array, jsize start, jsize len, jdouble *buf);
-
-    void (JNICALL *SetBooleanArrayRegion)
-      (JNIEnv *env, jbooleanArray array, jsize start, jsize l, jboolean *buf);
-    void (JNICALL *SetByteArrayRegion)
-      (JNIEnv *env, jbyteArray array, jsize start, jsize len, jbyte *buf);
-    void (JNICALL *SetCharArrayRegion)
-      (JNIEnv *env, jcharArray array, jsize start, jsize len, jchar *buf);
-    void (JNICALL *SetShortArrayRegion)
-      (JNIEnv *env, jshortArray array, jsize start, jsize len, jshort *buf);
-    void (JNICALL *SetIntArrayRegion)
-      (JNIEnv *env, jintArray array, jsize start, jsize len, jint *buf);
-    void (JNICALL *SetLongArrayRegion)
-      (JNIEnv *env, jlongArray array, jsize start, jsize len, jlong *buf);
-    void (JNICALL *SetFloatArrayRegion)
-      (JNIEnv *env, jfloatArray array, jsize start, jsize len, jfloat *buf);
-    void (JNICALL *SetDoubleArrayRegion)
-      (JNIEnv *env, jdoubleArray array, jsize start, jsize len, jdouble *buf);
-
-    jint (JNICALL *RegisterNatives)
-      (JNIEnv *env, jclass clazz, const JNINativeMethod *methods, 
-       jint nMethods);
-    jint (JNICALL *UnregisterNatives)
-      (JNIEnv *env, jclass clazz);
-
-    jint (JNICALL *MonitorEnter)
-      (JNIEnv *env, jobject obj);
-    jint (JNICALL *MonitorExit)
-      (JNIEnv *env, jobject obj);
- 
-    jint (JNICALL *GetJavaVM)
-      (JNIEnv *env, JavaVM **vm);
-
-    void (JNICALL *GetStringRegion)
-      (JNIEnv *env, jstring str, jsize start, jsize len, jchar *buf);
-    void (JNICALL *GetStringUTFRegion)
-      (JNIEnv *env, jstring str, jsize start, jsize len, char *buf);
-
-    void * (JNICALL *GetPrimitiveArrayCritical)
-      (JNIEnv *env, jarray array, jboolean *isCopy);
-    void (JNICALL *ReleasePrimitiveArrayCritical)
-      (JNIEnv *env, jarray array, void *carray, jint mode);
-
-    const jchar * (JNICALL *GetStringCritical)
-      (JNIEnv *env, jstring string, jboolean *isCopy);
-    void (JNICALL *ReleaseStringCritical)
-      (JNIEnv *env, jstring string, const jchar *cstring);
-
-    jweak (JNICALL *NewWeakGlobalRef)
-       (JNIEnv *env, jobject obj);
-    void (JNICALL *DeleteWeakGlobalRef)
-       (JNIEnv *env, jweak ref);
-
-    jboolean (JNICALL *ExceptionCheck)
-       (JNIEnv *env);
-
-    jobject (JNICALL *NewDirectByteBuffer)
-       (JNIEnv* env, void* address, jlong capacity);
-    void* (JNICALL *GetDirectBufferAddress)
-       (JNIEnv* env, jobject buf);
-    jlong (JNICALL *GetDirectBufferCapacity)
-       (JNIEnv* env, jobject buf);
-};
-
-/*
- * We use inlined functions for C++ so that programmers can write:
- * 
- *    env->FindClass("java/lang/String")
- *
- * in C++ rather than:
- *
- *    (*env)->FindClass(env, "java/lang/String")
- *
- * in C.
- */
-
-struct JNIEnv_ {
-    const struct JNINativeInterface_ *functions;
-#ifdef __cplusplus
-
-    jint GetVersion() {
-        return functions->GetVersion(this);
-    }
-    jclass DefineClass(const char *name, jobject loader, const jbyte *buf,
-		       jsize len) {
-        return functions->DefineClass(this, name, loader, buf, len);
-    }
-    jclass FindClass(const char *name) {
-        return functions->FindClass(this, name);
-    }
-    jmethodID FromReflectedMethod(jobject method) {
-        return functions->FromReflectedMethod(this,method);
-    }
-    jfieldID FromReflectedField(jobject field) {
-        return functions->FromReflectedField(this,field);
-    }
-
-    jobject ToReflectedMethod(jclass cls, jmethodID methodID, jboolean isStatic) {
-        return functions->ToReflectedMethod(this, cls, methodID, isStatic);
-    }
-
-    jclass GetSuperclass(jclass sub) {
-        return functions->GetSuperclass(this, sub);
-    }
-    jboolean IsAssignableFrom(jclass sub, jclass sup) {
-        return functions->IsAssignableFrom(this, sub, sup);
-    }
-
-    jobject ToReflectedField(jclass cls, jfieldID fieldID, jboolean isStatic) {
-        return functions->ToReflectedField(this,cls,fieldID,isStatic);
-    }
-
-    jint Throw(jthrowable obj) {
-        return functions->Throw(this, obj);
-    }    
-    jint ThrowNew(jclass clazz, const char *msg) {
-        return functions->ThrowNew(this, clazz, msg);
-    }
-    jthrowable ExceptionOccurred() {
-        return functions->ExceptionOccurred(this);
-    }
-    void ExceptionDescribe() {
-        functions->ExceptionDescribe(this);
-    }
-    void ExceptionClear() {
-        functions->ExceptionClear(this);
-    }
-    void FatalError(const char *msg) {
-        functions->FatalError(this, msg);
-    }
-
-    jint PushLocalFrame(jint capacity) {
-        return functions->PushLocalFrame(this,capacity);
-    }
-    jobject PopLocalFrame(jobject result) {
-        return functions->PopLocalFrame(this,result);
-    }
-
-    jobject NewGlobalRef(jobject lobj) {
-        return functions->NewGlobalRef(this,lobj);
-    }
-    void DeleteGlobalRef(jobject gref) {
-        functions->DeleteGlobalRef(this,gref);
-    }
-    void DeleteLocalRef(jobject obj) {
-        functions->DeleteLocalRef(this, obj);
-    }
-
-    jboolean IsSameObject(jobject obj1, jobject obj2) {
-        return functions->IsSameObject(this,obj1,obj2);
-    }
-
-    jobject NewLocalRef(jobject ref) {
-        return functions->NewLocalRef(this,ref);
-    }
-    jint EnsureLocalCapacity(jint capacity) {
-        return functions->EnsureLocalCapacity(this,capacity);
-    }
-
-    jobject AllocObject(jclass clazz) {
-        return functions->AllocObject(this,clazz);
-    }
-    jobject NewObject(jclass clazz, jmethodID methodID, ...) {
-        va_list args;
-	jobject result;
-	va_start(args, methodID);
-        result = functions->NewObjectV(this,clazz,methodID,args);
-	va_end(args);
-	return result;
-    }
-    jobject NewObjectV(jclass clazz, jmethodID methodID, 
-		       va_list args) {
-        return functions->NewObjectV(this,clazz,methodID,args);
-    }
-    jobject NewObjectA(jclass clazz, jmethodID methodID, 
-		       jvalue *args) {
-        return functions->NewObjectA(this,clazz,methodID,args);
-    }
-
-    jclass GetObjectClass(jobject obj) {
-        return functions->GetObjectClass(this,obj);
-    }
-    jboolean IsInstanceOf(jobject obj, jclass clazz) {
-        return functions->IsInstanceOf(this,obj,clazz);
-    }
-
-    jmethodID GetMethodID(jclass clazz, const char *name, 
-			  const char *sig) {
-        return functions->GetMethodID(this,clazz,name,sig);
-    }
-
-    jobject CallObjectMethod(jobject obj, jmethodID methodID, ...) {
-        va_list args;
-	jobject result;
-	va_start(args,methodID);
-	result = functions->CallObjectMethodV(this,obj,methodID,args);
-	va_end(args);
-	return result;
-    }
-    jobject CallObjectMethodV(jobject obj, jmethodID methodID, 
-			va_list args) {
-        return functions->CallObjectMethodV(this,obj,methodID,args);
-    }
-    jobject CallObjectMethodA(jobject obj, jmethodID methodID, 
-			jvalue * args) {
-        return functions->CallObjectMethodA(this,obj,methodID,args);
-    }
-
-    jboolean CallBooleanMethod(jobject obj, 
-			       jmethodID methodID, ...) {
-        va_list args;
-	jboolean result;
-	va_start(args,methodID);
-	result = functions->CallBooleanMethodV(this,obj,methodID,args);
-	va_end(args);
-	return result;
-    }
-    jboolean CallBooleanMethodV(jobject obj, jmethodID methodID, 
-				va_list args) {
-        return functions->CallBooleanMethodV(this,obj,methodID,args);
-    }
-    jboolean CallBooleanMethodA(jobject obj, jmethodID methodID, 
-				jvalue * args) {
-        return functions->CallBooleanMethodA(this,obj,methodID, args);
-    }
-
-    jbyte CallByteMethod(jobject obj, jmethodID methodID, ...) {
-        va_list args;
-	jbyte result;
-	va_start(args,methodID);
-	result = functions->CallByteMethodV(this,obj,methodID,args);
-	va_end(args);
-	return result;
-    }
-    jbyte CallByteMethodV(jobject obj, jmethodID methodID, 
-			  va_list args) {
-        return functions->CallByteMethodV(this,obj,methodID,args);
-    }
-    jbyte CallByteMethodA(jobject obj, jmethodID methodID, 
-			  jvalue * args) {
-        return functions->CallByteMethodA(this,obj,methodID,args);
-    }
-
-    jchar CallCharMethod(jobject obj, jmethodID methodID, ...) {
-        va_list args;
-	jchar result;
-	va_start(args,methodID);
-	result = functions->CallCharMethodV(this,obj,methodID,args);
-	va_end(args);
-	return result;
-    }
-    jchar CallCharMethodV(jobject obj, jmethodID methodID, 
-			  va_list args) {
-        return functions->CallCharMethodV(this,obj,methodID,args);
-    }
-    jchar CallCharMethodA(jobject obj, jmethodID methodID, 
-			  jvalue * args) {
-        return functions->CallCharMethodA(this,obj,methodID,args);
-    }
-
-    jshort CallShortMethod(jobject obj, jmethodID methodID, ...) {
-        va_list args;
-	jshort result;
-	va_start(args,methodID);
-	result = functions->CallShortMethodV(this,obj,methodID,args);
-	va_end(args);
-	return result;
-    }
-    jshort CallShortMethodV(jobject obj, jmethodID methodID, 
-			    va_list args) {
-        return functions->CallShortMethodV(this,obj,methodID,args);
-    }
-    jshort CallShortMethodA(jobject obj, jmethodID methodID, 
-			    jvalue * args) {
-        return functions->CallShortMethodA(this,obj,methodID,args);
-    }
-
-    jint CallIntMethod(jobject obj, jmethodID methodID, ...) {
-        va_list args;
-	jint result;
-	va_start(args,methodID);
-	result = functions->CallIntMethodV(this,obj,methodID,args);
-	va_end(args);
-	return result;
-    }
-    jint CallIntMethodV(jobject obj, jmethodID methodID, 
-			va_list args) {
-        return functions->CallIntMethodV(this,obj,methodID,args);
-    }
-    jint CallIntMethodA(jobject obj, jmethodID methodID, 
-			jvalue * args) {
-        return functions->CallIntMethodA(this,obj,methodID,args);
-    }
-
-    jlong CallLongMethod(jobject obj, jmethodID methodID, ...) {
-        va_list args;
-	jlong result;
-	va_start(args,methodID);
-	result = functions->CallLongMethodV(this,obj,methodID,args);
-	va_end(args);
-	return result;
-    }
-    jlong CallLongMethodV(jobject obj, jmethodID methodID, 
-			  va_list args) {
-        return functions->CallLongMethodV(this,obj,methodID,args);
-    }
-    jlong CallLongMethodA(jobject obj, jmethodID methodID, 
-			  jvalue * args) {
-        return functions->CallLongMethodA(this,obj,methodID,args);
-    }
-
-    jfloat CallFloatMethod(jobject obj, jmethodID methodID, ...) {
-        va_list args;
-	jfloat result;
-	va_start(args,methodID);
-	result = functions->CallFloatMethodV(this,obj,methodID,args);
-	va_end(args);
-	return result;
-    }
-    jfloat CallFloatMethodV(jobject obj, jmethodID methodID, 
-			    va_list args) {
-        return functions->CallFloatMethodV(this,obj,methodID,args);
-    }
-    jfloat CallFloatMethodA(jobject obj, jmethodID methodID, 
-			    jvalue * args) {
-        return functions->CallFloatMethodA(this,obj,methodID,args);
-    }
-
-    jdouble CallDoubleMethod(jobject obj, jmethodID methodID, ...) {
-        va_list args;
-	jdouble result;
-	va_start(args,methodID);
-	result = functions->CallDoubleMethodV(this,obj,methodID,args);
-	va_end(args);
-	return result;
-    }
-    jdouble CallDoubleMethodV(jobject obj, jmethodID methodID, 
-			va_list args) {
-        return functions->CallDoubleMethodV(this,obj,methodID,args);
-    }
-    jdouble CallDoubleMethodA(jobject obj, jmethodID methodID, 
-			jvalue * args) {
-        return functions->CallDoubleMethodA(this,obj,methodID,args);
-    }
-
-    void CallVoidMethod(jobject obj, jmethodID methodID, ...) {
-        va_list args;
-	va_start(args,methodID);
-	functions->CallVoidMethodV(this,obj,methodID,args);
-	va_end(args);
-    }
-    void CallVoidMethodV(jobject obj, jmethodID methodID, 
-			 va_list args) {
-        functions->CallVoidMethodV(this,obj,methodID,args);
-    }
-    void CallVoidMethodA(jobject obj, jmethodID methodID, 
-			 jvalue * args) {
-        functions->CallVoidMethodA(this,obj,methodID,args);
-    }
-
-    jobject CallNonvirtualObjectMethod(jobject obj, jclass clazz, 
-				       jmethodID methodID, ...) {
-        va_list args;
-	jobject result;
-	va_start(args,methodID);
-	result = functions->CallNonvirtualObjectMethodV(this,obj,clazz,
-							methodID,args);
-	va_end(args);
-	return result;
-    }
-    jobject CallNonvirtualObjectMethodV(jobject obj, jclass clazz, 
-					jmethodID methodID, va_list args) {
-        return functions->CallNonvirtualObjectMethodV(this,obj,clazz,
-						      methodID,args);
-    }
-    jobject CallNonvirtualObjectMethodA(jobject obj, jclass clazz, 
-					jmethodID methodID, jvalue * args) {
-        return functions->CallNonvirtualObjectMethodA(this,obj,clazz,
-						      methodID,args);
-    }
-
-    jboolean CallNonvirtualBooleanMethod(jobject obj, jclass clazz, 
-					 jmethodID methodID, ...) {
-        va_list args;
-	jboolean result;
-	va_start(args,methodID);
-	result = functions->CallNonvirtualBooleanMethodV(this,obj,clazz,
-							 methodID,args);
-	va_end(args);
-	return result;
-    }
-    jboolean CallNonvirtualBooleanMethodV(jobject obj, jclass clazz, 
-					  jmethodID methodID, va_list args) {
-        return functions->CallNonvirtualBooleanMethodV(this,obj,clazz,
-						       methodID,args);
-    }
-    jboolean CallNonvirtualBooleanMethodA(jobject obj, jclass clazz, 
-					  jmethodID methodID, jvalue * args) {
-        return functions->CallNonvirtualBooleanMethodA(this,obj,clazz,
-						       methodID, args);
-    }
-
-    jbyte CallNonvirtualByteMethod(jobject obj, jclass clazz, 
-				   jmethodID methodID, ...) {
-        va_list args;
-	jbyte result;
-	va_start(args,methodID);
-	result = functions->CallNonvirtualByteMethodV(this,obj,clazz,
-						      methodID,args);
-	va_end(args);
-	return result;
-    }
-    jbyte CallNonvirtualByteMethodV(jobject obj, jclass clazz, 
-				    jmethodID methodID, va_list args) {
-        return functions->CallNonvirtualByteMethodV(this,obj,clazz,
-						    methodID,args);
-    }
-    jbyte CallNonvirtualByteMethodA(jobject obj, jclass clazz, 
-				    jmethodID methodID, jvalue * args) {
-        return functions->CallNonvirtualByteMethodA(this,obj,clazz,
-						    methodID,args);
-    }
-
-    jchar CallNonvirtualCharMethod(jobject obj, jclass clazz, 
-				   jmethodID methodID, ...) {
-        va_list args;
-	jchar result;
-	va_start(args,methodID);
-	result = functions->CallNonvirtualCharMethodV(this,obj,clazz,
-						      methodID,args);
-	va_end(args);
-	return result;
-    }
-    jchar CallNonvirtualCharMethodV(jobject obj, jclass clazz, 
-				    jmethodID methodID, va_list args) {
-        return functions->CallNonvirtualCharMethodV(this,obj,clazz,
-						    methodID,args);
-    }
-    jchar CallNonvirtualCharMethodA(jobject obj, jclass clazz, 
-				    jmethodID methodID, jvalue * args) {
-        return functions->CallNonvirtualCharMethodA(this,obj,clazz,
-						    methodID,args);
-    }
-
-    jshort CallNonvirtualShortMethod(jobject obj, jclass clazz, 
-				     jmethodID methodID, ...) {
-        va_list args;
-	jshort result;
-	va_start(args,methodID);
-	result = functions->CallNonvirtualShortMethodV(this,obj,clazz,
-						       methodID,args);
-	va_end(args);
-	return result;
-    }
-    jshort CallNonvirtualShortMethodV(jobject obj, jclass clazz, 
-				      jmethodID methodID, va_list args) {
-        return functions->CallNonvirtualShortMethodV(this,obj,clazz,
-						     methodID,args);
-    }
-    jshort CallNonvirtualShortMethodA(jobject obj, jclass clazz,
-				      jmethodID methodID, jvalue * args) {
-        return functions->CallNonvirtualShortMethodA(this,obj,clazz,
-						     methodID,args);
-    }
-
-    jint CallNonvirtualIntMethod(jobject obj, jclass clazz, 
-				 jmethodID methodID, ...) {
-        va_list args;
-	jint result;
-	va_start(args,methodID);
-	result = functions->CallNonvirtualIntMethodV(this,obj,clazz,
-						     methodID,args);
-	va_end(args);
-	return result;
-    }
-    jint CallNonvirtualIntMethodV(jobject obj, jclass clazz, 
-				  jmethodID methodID, va_list args) {
-        return functions->CallNonvirtualIntMethodV(this,obj,clazz,
-						   methodID,args);
-    }
-    jint CallNonvirtualIntMethodA(jobject obj, jclass clazz, 
-				  jmethodID methodID, jvalue * args) {
-        return functions->CallNonvirtualIntMethodA(this,obj,clazz,
-						   methodID,args);
-    }
-
-    jlong CallNonvirtualLongMethod(jobject obj, jclass clazz,
-				   jmethodID methodID, ...) {
-        va_list args;
-	jlong result;
-	va_start(args,methodID);
-	result = functions->CallNonvirtualLongMethodV(this,obj,clazz,
-						      methodID,args);
-	va_end(args);
-	return result;
-    }
-    jlong CallNonvirtualLongMethodV(jobject obj, jclass clazz,
-				    jmethodID methodID, va_list args) {
-        return functions->CallNonvirtualLongMethodV(this,obj,clazz,
-						    methodID,args);
-    }
-    jlong CallNonvirtualLongMethodA(jobject obj, jclass clazz, 
-				    jmethodID methodID, jvalue * args) {
-        return functions->CallNonvirtualLongMethodA(this,obj,clazz,
-						    methodID,args);
-    }
-
-    jfloat CallNonvirtualFloatMethod(jobject obj, jclass clazz, 
-				     jmethodID methodID, ...) {
-        va_list args;
-	jfloat result;
-	va_start(args,methodID);
-	result = functions->CallNonvirtualFloatMethodV(this,obj,clazz,
-						       methodID,args);
-	va_end(args);
-	return result;
-    }
-    jfloat CallNonvirtualFloatMethodV(jobject obj, jclass clazz,
-				      jmethodID methodID, 
-				      va_list args) {
-        return functions->CallNonvirtualFloatMethodV(this,obj,clazz,
-						     methodID,args);
-    }
-    jfloat CallNonvirtualFloatMethodA(jobject obj, jclass clazz, 
-				      jmethodID methodID, 
-				      jvalue * args) {
-        return functions->CallNonvirtualFloatMethodA(this,obj,clazz,
-						     methodID,args);
-    }
-
-    jdouble CallNonvirtualDoubleMethod(jobject obj, jclass clazz,
-				       jmethodID methodID, ...) {
-        va_list args;
-	jdouble result;
-	va_start(args,methodID);
-	result = functions->CallNonvirtualDoubleMethodV(this,obj,clazz,
-							methodID,args);
-	va_end(args);
-	return result;
-    }
-    jdouble CallNonvirtualDoubleMethodV(jobject obj, jclass clazz,
-					jmethodID methodID, 
-					va_list args) {
-        return functions->CallNonvirtualDoubleMethodV(this,obj,clazz,
-						      methodID,args);
-    }
-    jdouble CallNonvirtualDoubleMethodA(jobject obj, jclass clazz, 
-					jmethodID methodID, 
-					jvalue * args) {
-        return functions->CallNonvirtualDoubleMethodA(this,obj,clazz,
-						      methodID,args);
-    }
-
-    void CallNonvirtualVoidMethod(jobject obj, jclass clazz,
-				  jmethodID methodID, ...) {
-        va_list args;
-	va_start(args,methodID);
-	functions->CallNonvirtualVoidMethodV(this,obj,clazz,methodID,args);
-	va_end(args);
-    }
-    void CallNonvirtualVoidMethodV(jobject obj, jclass clazz,
-				   jmethodID methodID, 
-				   va_list args) {
-        functions->CallNonvirtualVoidMethodV(this,obj,clazz,methodID,args);
-    }
-    void CallNonvirtualVoidMethodA(jobject obj, jclass clazz,
-				   jmethodID methodID, 
-				   jvalue * args) {
-        functions->CallNonvirtualVoidMethodA(this,obj,clazz,methodID,args);
-    }
-
-    jfieldID GetFieldID(jclass clazz, const char *name, 
-			const char *sig) {
-        return functions->GetFieldID(this,clazz,name,sig);
-    }
-
-    jobject GetObjectField(jobject obj, jfieldID fieldID) {
-        return functions->GetObjectField(this,obj,fieldID);
-    }
-    jboolean GetBooleanField(jobject obj, jfieldID fieldID) {
-        return functions->GetBooleanField(this,obj,fieldID);
-    }
-    jbyte GetByteField(jobject obj, jfieldID fieldID) {
-        return functions->GetByteField(this,obj,fieldID);
-    }
-    jchar GetCharField(jobject obj, jfieldID fieldID) {
-        return functions->GetCharField(this,obj,fieldID);
-    }
-    jshort GetShortField(jobject obj, jfieldID fieldID) {
-        return functions->GetShortField(this,obj,fieldID);
-    }
-    jint GetIntField(jobject obj, jfieldID fieldID) {
-        return functions->GetIntField(this,obj,fieldID);
-    }
-    jlong GetLongField(jobject obj, jfieldID fieldID) {
-        return functions->GetLongField(this,obj,fieldID);
-    }
-    jfloat GetFloatField(jobject obj, jfieldID fieldID) {
-        return functions->GetFloatField(this,obj,fieldID);
-    }
-    jdouble GetDoubleField(jobject obj, jfieldID fieldID) {
-        return functions->GetDoubleField(this,obj,fieldID);
-    }
-
-    void SetObjectField(jobject obj, jfieldID fieldID, jobject val) {
-        functions->SetObjectField(this,obj,fieldID,val);
-    }
-    void SetBooleanField(jobject obj, jfieldID fieldID, 
-			 jboolean val) {
-        functions->SetBooleanField(this,obj,fieldID,val);
-    }
-    void SetByteField(jobject obj, jfieldID fieldID, 
-		      jbyte val) {
-        functions->SetByteField(this,obj,fieldID,val);
-    }
-    void SetCharField(jobject obj, jfieldID fieldID, 
-		      jchar val) {
-        functions->SetCharField(this,obj,fieldID,val);
-    }
-    void SetShortField(jobject obj, jfieldID fieldID,
-		       jshort val) {
-        functions->SetShortField(this,obj,fieldID,val);
-    }
-    void SetIntField(jobject obj, jfieldID fieldID, 
-		     jint val) {
-        functions->SetIntField(this,obj,fieldID,val);
-    }
-    void SetLongField(jobject obj, jfieldID fieldID, 
-		      jlong val) {
-        functions->SetLongField(this,obj,fieldID,val);
-    }
-    void SetFloatField(jobject obj, jfieldID fieldID, 
-		       jfloat val) {
-        functions->SetFloatField(this,obj,fieldID,val);
-    }
-    void SetDoubleField(jobject obj, jfieldID fieldID, 
-			jdouble val) {
-        functions->SetDoubleField(this,obj,fieldID,val);
-    }
-
-    jmethodID GetStaticMethodID(jclass clazz, const char *name, 
-				const char *sig) {
-        return functions->GetStaticMethodID(this,clazz,name,sig);
-    }
-
-    jobject CallStaticObjectMethod(jclass clazz, jmethodID methodID, 
-			     ...) {
-        va_list args;
-	jobject result;
-	va_start(args,methodID);
-	result = functions->CallStaticObjectMethodV(this,clazz,methodID,args);
-	va_end(args);
-	return result;
-    }
-    jobject CallStaticObjectMethodV(jclass clazz, jmethodID methodID, 
-			      va_list args) {
-        return functions->CallStaticObjectMethodV(this,clazz,methodID,args);
-    }
-    jobject CallStaticObjectMethodA(jclass clazz, jmethodID methodID, 
-			      jvalue *args) {
-        return functions->CallStaticObjectMethodA(this,clazz,methodID,args);
-    }
-
-    jboolean CallStaticBooleanMethod(jclass clazz, 
-				     jmethodID methodID, ...) {
-        va_list args;
-	jboolean result;
-	va_start(args,methodID);
-	result = functions->CallStaticBooleanMethodV(this,clazz,methodID,args);
-	va_end(args);
-	return result;
-    }
-    jboolean CallStaticBooleanMethodV(jclass clazz,
-				      jmethodID methodID, va_list args) {
-        return functions->CallStaticBooleanMethodV(this,clazz,methodID,args);
-    }
-    jboolean CallStaticBooleanMethodA(jclass clazz,
-				      jmethodID methodID, jvalue *args) {
-        return functions->CallStaticBooleanMethodA(this,clazz,methodID,args);
-    }
-
-    jbyte CallStaticByteMethod(jclass clazz,
-			       jmethodID methodID, ...) {
-        va_list args;
-	jbyte result;
-	va_start(args,methodID);
-	result = functions->CallStaticByteMethodV(this,clazz,methodID,args);
-	va_end(args);
-	return result;
-    }
-    jbyte CallStaticByteMethodV(jclass clazz,
-				jmethodID methodID, va_list args) {
-        return functions->CallStaticByteMethodV(this,clazz,methodID,args);
-    }
-    jbyte CallStaticByteMethodA(jclass clazz, 
-				jmethodID methodID, jvalue *args) {
-        return functions->CallStaticByteMethodA(this,clazz,methodID,args);
-    }
-
-    jchar CallStaticCharMethod(jclass clazz,
-			       jmethodID methodID, ...) {
-        va_list args;
-	jchar result;
-	va_start(args,methodID);
-	result = functions->CallStaticCharMethodV(this,clazz,methodID,args);
-	va_end(args);
-	return result;
-    }
-    jchar CallStaticCharMethodV(jclass clazz,
-				jmethodID methodID, va_list args) {
-        return functions->CallStaticCharMethodV(this,clazz,methodID,args);
-    }
-    jchar CallStaticCharMethodA(jclass clazz,
-				jmethodID methodID, jvalue *args) {
-        return functions->CallStaticCharMethodA(this,clazz,methodID,args);
-    }
-
-    jshort CallStaticShortMethod(jclass clazz,
-				 jmethodID methodID, ...) {
-        va_list args;
-	jshort result;
-	va_start(args,methodID);
-	result = functions->CallStaticShortMethodV(this,clazz,methodID,args);
-	va_end(args);
-	return result;
-    }
-    jshort CallStaticShortMethodV(jclass clazz,
-				  jmethodID methodID, va_list args) {
-        return functions->CallStaticShortMethodV(this,clazz,methodID,args);
-    }
-    jshort CallStaticShortMethodA(jclass clazz,
-				  jmethodID methodID, jvalue *args) {
-        return functions->CallStaticShortMethodA(this,clazz,methodID,args);
-    }
-
-    jint CallStaticIntMethod(jclass clazz,
-			     jmethodID methodID, ...) {
-        va_list args;
-	jint result;
-	va_start(args,methodID);
-	result = functions->CallStaticIntMethodV(this,clazz,methodID,args);
-	va_end(args);
-	return result;
-    }
-    jint CallStaticIntMethodV(jclass clazz,
-			      jmethodID methodID, va_list args) {
-        return functions->CallStaticIntMethodV(this,clazz,methodID,args);
-    }
-    jint CallStaticIntMethodA(jclass clazz, 
-			      jmethodID methodID, jvalue *args) {
-        return functions->CallStaticIntMethodA(this,clazz,methodID,args);
-    }
-
-    jlong CallStaticLongMethod(jclass clazz,
-			       jmethodID methodID, ...) {
-        va_list args;
-	jlong result;
-	va_start(args,methodID);
-	result = functions->CallStaticLongMethodV(this,clazz,methodID,args);
-	va_end(args);
-	return result;
-    }
-    jlong CallStaticLongMethodV(jclass clazz, 
-				jmethodID methodID, va_list args) {
-        return functions->CallStaticLongMethodV(this,clazz,methodID,args);
-    }
-    jlong CallStaticLongMethodA(jclass clazz, 
-				jmethodID methodID, jvalue *args) {
-        return functions->CallStaticLongMethodA(this,clazz,methodID,args);
-    }
-
-    jfloat CallStaticFloatMethod(jclass clazz, 
-				 jmethodID methodID, ...) {
-        va_list args;
-	jfloat result;
-	va_start(args,methodID);
-	result = functions->CallStaticFloatMethodV(this,clazz,methodID,args);
-	va_end(args);
-	return result;
-    }
-    jfloat CallStaticFloatMethodV(jclass clazz, 
-				  jmethodID methodID, va_list args) {
-        return functions->CallStaticFloatMethodV(this,clazz,methodID,args);
-    }
-    jfloat CallStaticFloatMethodA(jclass clazz, 
-				  jmethodID methodID, jvalue *args) {
-        return functions->CallStaticFloatMethodA(this,clazz,methodID,args);
-    }
-
-    jdouble CallStaticDoubleMethod(jclass clazz, 
-				   jmethodID methodID, ...) {
-        va_list args;
-	jdouble result;
-	va_start(args,methodID);
-	result = functions->CallStaticDoubleMethodV(this,clazz,methodID,args);
-	va_end(args);
-	return result;
-    }
-    jdouble CallStaticDoubleMethodV(jclass clazz, 
-				    jmethodID methodID, va_list args) {
-        return functions->CallStaticDoubleMethodV(this,clazz,methodID,args);
-    }
-    jdouble CallStaticDoubleMethodA(jclass clazz, 
-				    jmethodID methodID, jvalue *args) {
-        return functions->CallStaticDoubleMethodA(this,clazz,methodID,args);
-    }
-
-    void CallStaticVoidMethod(jclass cls, jmethodID methodID, ...) {
-        va_list args;
-	va_start(args,methodID);
-	functions->CallStaticVoidMethodV(this,cls,methodID,args);
-	va_end(args);
-    }
-    void CallStaticVoidMethodV(jclass cls, jmethodID methodID, 
-			       va_list args) {
-        functions->CallStaticVoidMethodV(this,cls,methodID,args);
-    }
-    void CallStaticVoidMethodA(jclass cls, jmethodID methodID, 
-			       jvalue * args) {
-        functions->CallStaticVoidMethodA(this,cls,methodID,args);
-    }
-
-    jfieldID GetStaticFieldID(jclass clazz, const char *name, 
-			      const char *sig) {
-        return functions->GetStaticFieldID(this,clazz,name,sig);
-    }
-    jobject GetStaticObjectField(jclass clazz, jfieldID fieldID) {
-        return functions->GetStaticObjectField(this,clazz,fieldID);
-    }
-    jboolean GetStaticBooleanField(jclass clazz, jfieldID fieldID) {
-        return functions->GetStaticBooleanField(this,clazz,fieldID);
-    }
-    jbyte GetStaticByteField(jclass clazz, jfieldID fieldID) {
-        return functions->GetStaticByteField(this,clazz,fieldID);
-    }
-    jchar GetStaticCharField(jclass clazz, jfieldID fieldID) {
-        return functions->GetStaticCharField(this,clazz,fieldID);
-    }
-    jshort GetStaticShortField(jclass clazz, jfieldID fieldID) {
-        return functions->GetStaticShortField(this,clazz,fieldID);
-    }
-    jint GetStaticIntField(jclass clazz, jfieldID fieldID) {
-        return functions->GetStaticIntField(this,clazz,fieldID);
-    }
-    jlong GetStaticLongField(jclass clazz, jfieldID fieldID) {
-        return functions->GetStaticLongField(this,clazz,fieldID);
-    }
-    jfloat GetStaticFloatField(jclass clazz, jfieldID fieldID) {
-        return functions->GetStaticFloatField(this,clazz,fieldID);
-    }
-    jdouble GetStaticDoubleField(jclass clazz, jfieldID fieldID) {
-        return functions->GetStaticDoubleField(this,clazz,fieldID);
-    }
-
-    void SetStaticObjectField(jclass clazz, jfieldID fieldID,
-			jobject value) {
-      functions->SetStaticObjectField(this,clazz,fieldID,value);
-    }
-    void SetStaticBooleanField(jclass clazz, jfieldID fieldID,
-			jboolean value) {
-      functions->SetStaticBooleanField(this,clazz,fieldID,value);
-    }
-    void SetStaticByteField(jclass clazz, jfieldID fieldID,
-			jbyte value) {
-      functions->SetStaticByteField(this,clazz,fieldID,value);
-    }
-    void SetStaticCharField(jclass clazz, jfieldID fieldID,
-			jchar value) {
-      functions->SetStaticCharField(this,clazz,fieldID,value);
-    }
-    void SetStaticShortField(jclass clazz, jfieldID fieldID,
-			jshort value) {
-      functions->SetStaticShortField(this,clazz,fieldID,value);
-    }
-    void SetStaticIntField(jclass clazz, jfieldID fieldID,
-			jint value) {
-      functions->SetStaticIntField(this,clazz,fieldID,value);
-    }
-    void SetStaticLongField(jclass clazz, jfieldID fieldID,
-			jlong value) {
-      functions->SetStaticLongField(this,clazz,fieldID,value);
-    }
-    void SetStaticFloatField(jclass clazz, jfieldID fieldID,
-			jfloat value) {
-      functions->SetStaticFloatField(this,clazz,fieldID,value);
-    }
-    void SetStaticDoubleField(jclass clazz, jfieldID fieldID,
-			jdouble value) {
-      functions->SetStaticDoubleField(this,clazz,fieldID,value);
-    }
-
-    jstring NewString(const jchar *unicode, jsize len) {
-        return functions->NewString(this,unicode,len);
-    }
-    jsize GetStringLength(jstring str) {
-        return functions->GetStringLength(this,str);
-    }
-    const jchar *GetStringChars(jstring str, jboolean *isCopy) {
-        return functions->GetStringChars(this,str,isCopy);
-    }
-    void ReleaseStringChars(jstring str, const jchar *chars) {
-        functions->ReleaseStringChars(this,str,chars);
-    }
-  
-    jstring NewStringUTF(const char *utf) {
-        return functions->NewStringUTF(this,utf);
-    }
-    jsize GetStringUTFLength(jstring str) {
-        return functions->GetStringUTFLength(this,str);
-    }
-    const char* GetStringUTFChars(jstring str, jboolean *isCopy) {
-        return functions->GetStringUTFChars(this,str,isCopy);
-    }
-    void ReleaseStringUTFChars(jstring str, const char* chars) {
-        functions->ReleaseStringUTFChars(this,str,chars);
-    }
-
-    jsize GetArrayLength(jarray array) {
-        return functions->GetArrayLength(this,array);
-    }
-
-    jobjectArray NewObjectArray(jsize len, jclass clazz, 
-				jobject init) {
-        return functions->NewObjectArray(this,len,clazz,init);
-    }
-    jobject GetObjectArrayElement(jobjectArray array, jsize index) {
-        return functions->GetObjectArrayElement(this,array,index);
-    }
-    void SetObjectArrayElement(jobjectArray array, jsize index, 
-			       jobject val) {
-        functions->SetObjectArrayElement(this,array,index,val);
-    }
-
-    jbooleanArray NewBooleanArray(jsize len) {
-        return functions->NewBooleanArray(this,len);
-    }
-    jbyteArray NewByteArray(jsize len) {
-        return functions->NewByteArray(this,len);
-    }
-    jcharArray NewCharArray(jsize len) {
-        return functions->NewCharArray(this,len);
-    }
-    jshortArray NewShortArray(jsize len) {
-        return functions->NewShortArray(this,len);
-    }
-    jintArray NewIntArray(jsize len) {
-        return functions->NewIntArray(this,len);
-    }
-    jlongArray NewLongArray(jsize len) {
-        return functions->NewLongArray(this,len);
-    }
-    jfloatArray NewFloatArray(jsize len) {
-        return functions->NewFloatArray(this,len);
-    }
-    jdoubleArray NewDoubleArray(jsize len) {
-        return functions->NewDoubleArray(this,len);
-    }
-
-    jboolean * GetBooleanArrayElements(jbooleanArray array, jboolean *isCopy) {
-        return functions->GetBooleanArrayElements(this,array,isCopy);
-    }
-    jbyte * GetByteArrayElements(jbyteArray array, jboolean *isCopy) {
-        return functions->GetByteArrayElements(this,array,isCopy);
-    }
-    jchar * GetCharArrayElements(jcharArray array, jboolean *isCopy) {
-        return functions->GetCharArrayElements(this,array,isCopy);
-    }
-    jshort * GetShortArrayElements(jshortArray array, jboolean *isCopy) {
-        return functions->GetShortArrayElements(this,array,isCopy);
-    }
-    jint * GetIntArrayElements(jintArray array, jboolean *isCopy) {
-        return functions->GetIntArrayElements(this,array,isCopy);
-    }
-    jlong * GetLongArrayElements(jlongArray array, jboolean *isCopy) {
-        return functions->GetLongArrayElements(this,array,isCopy);
-    }
-    jfloat * GetFloatArrayElements(jfloatArray array, jboolean *isCopy) {
-        return functions->GetFloatArrayElements(this,array,isCopy);
-    }
-    jdouble * GetDoubleArrayElements(jdoubleArray array, jboolean *isCopy) {
-        return functions->GetDoubleArrayElements(this,array,isCopy);
-    }
-
-    void ReleaseBooleanArrayElements(jbooleanArray array, 
-				     jboolean *elems,
-				     jint mode) {
-        functions->ReleaseBooleanArrayElements(this,array,elems,mode);
-    }
-    void ReleaseByteArrayElements(jbyteArray array, 
-				  jbyte *elems,
-				  jint mode) {
-        functions->ReleaseByteArrayElements(this,array,elems,mode);
-    }
-    void ReleaseCharArrayElements(jcharArray array, 
-				  jchar *elems,
-				  jint mode) {
-        functions->ReleaseCharArrayElements(this,array,elems,mode);
-    }
-    void ReleaseShortArrayElements(jshortArray array, 
-				   jshort *elems,
-				   jint mode) {
-        functions->ReleaseShortArrayElements(this,array,elems,mode);
-    }
-    void ReleaseIntArrayElements(jintArray array, 
-				 jint *elems,
-				 jint mode) {
-        functions->ReleaseIntArrayElements(this,array,elems,mode);
-    }
-    void ReleaseLongArrayElements(jlongArray array, 
-				  jlong *elems,
-				  jint mode) {
-        functions->ReleaseLongArrayElements(this,array,elems,mode);
-    }
-    void ReleaseFloatArrayElements(jfloatArray array, 
-				   jfloat *elems,
-				   jint mode) {
-        functions->ReleaseFloatArrayElements(this,array,elems,mode);
-    }
-    void ReleaseDoubleArrayElements(jdoubleArray array, 
-				    jdouble *elems,
-				    jint mode) {
-        functions->ReleaseDoubleArrayElements(this,array,elems,mode);
-    }
-
-    void GetBooleanArrayRegion(jbooleanArray array, 
-			       jsize start, jsize len, jboolean *buf) {
-        functions->GetBooleanArrayRegion(this,array,start,len,buf);
-    }
-    void GetByteArrayRegion(jbyteArray array, 
-			    jsize start, jsize len, jbyte *buf) {
-        functions->GetByteArrayRegion(this,array,start,len,buf);
-    }
-    void GetCharArrayRegion(jcharArray array, 
-			    jsize start, jsize len, jchar *buf) {
-        functions->GetCharArrayRegion(this,array,start,len,buf);
-    }
-    void GetShortArrayRegion(jshortArray array, 
-			     jsize start, jsize len, jshort *buf) {
-        functions->GetShortArrayRegion(this,array,start,len,buf);
-    }
-    void GetIntArrayRegion(jintArray array, 
-			   jsize start, jsize len, jint *buf) {
-        functions->GetIntArrayRegion(this,array,start,len,buf);
-    }
-    void GetLongArrayRegion(jlongArray array, 
-			    jsize start, jsize len, jlong *buf) {
-        functions->GetLongArrayRegion(this,array,start,len,buf);
-    }
-    void GetFloatArrayRegion(jfloatArray array, 
-			     jsize start, jsize len, jfloat *buf) {
-        functions->GetFloatArrayRegion(this,array,start,len,buf);
-    }
-    void GetDoubleArrayRegion(jdoubleArray array, 
-			      jsize start, jsize len, jdouble *buf) {
-        functions->GetDoubleArrayRegion(this,array,start,len,buf);
-    }
-
-    void SetBooleanArrayRegion(jbooleanArray array, jsize start, jsize len, 
-			       jboolean *buf) {
-        functions->SetBooleanArrayRegion(this,array,start,len,buf);
-    }
-    void SetByteArrayRegion(jbyteArray array, jsize start, jsize len,
-			    jbyte *buf) {
-        functions->SetByteArrayRegion(this,array,start,len,buf);
-    }
-    void SetCharArrayRegion(jcharArray array, jsize start, jsize len, 
-			    jchar *buf) {
-        functions->SetCharArrayRegion(this,array,start,len,buf);
-    }
-    void SetShortArrayRegion(jshortArray array, jsize start, jsize len, 
-			     jshort *buf) {
-        functions->SetShortArrayRegion(this,array,start,len,buf);
-    }
-    void SetIntArrayRegion(jintArray array, jsize start, jsize len,
-			   jint *buf) {
-        functions->SetIntArrayRegion(this,array,start,len,buf);
-    }
-    void SetLongArrayRegion(jlongArray array, jsize start, jsize len,
-			    jlong *buf) {
-        functions->SetLongArrayRegion(this,array,start,len,buf);
-    }
-    void SetFloatArrayRegion(jfloatArray array, jsize start, jsize len, 
-			     jfloat *buf) {
-        functions->SetFloatArrayRegion(this,array,start,len,buf);
-    }
-    void SetDoubleArrayRegion(jdoubleArray array, jsize start, jsize len,
-			      jdouble *buf) {
-        functions->SetDoubleArrayRegion(this,array,start,len,buf);
-    }
-
-    jint RegisterNatives(jclass clazz, const JNINativeMethod *methods,
-			 jint nMethods) {
-        return functions->RegisterNatives(this,clazz,methods,nMethods);
-    }
-    jint UnregisterNatives(jclass clazz) {
-        return functions->UnregisterNatives(this,clazz);
-    }  
-   
-    jint MonitorEnter(jobject obj) {
-        return functions->MonitorEnter(this,obj);
-    }
-    jint MonitorExit(jobject obj) {
-        return functions->MonitorExit(this,obj);
-    }
-
-    jint GetJavaVM(JavaVM **vm) {
-        return functions->GetJavaVM(this,vm);
-    }
-  
-    void GetStringRegion(jstring str, jsize start, jsize len, jchar *buf) {
-        functions->GetStringRegion(this,str,start,len,buf);
-    }
-    void GetStringUTFRegion(jstring str, jsize start, jsize len, char *buf) {
-        functions->GetStringUTFRegion(this,str,start,len,buf);
-    }
-
-    void * GetPrimitiveArrayCritical(jarray array, jboolean *isCopy) {
-        return functions->GetPrimitiveArrayCritical(this,array,isCopy);
-    }
-    void ReleasePrimitiveArrayCritical(jarray array, void *carray, jint mode) {
-        functions->ReleasePrimitiveArrayCritical(this,array,carray,mode);
-    }
-
-    const jchar * GetStringCritical(jstring string, jboolean *isCopy) {
-        return functions->GetStringCritical(this,string,isCopy);
-    }
-    void ReleaseStringCritical(jstring string, const jchar *cstring) {
-        functions->ReleaseStringCritical(this,string,cstring);
-    }
-
-    jweak NewWeakGlobalRef(jobject obj) {
-        return functions->NewWeakGlobalRef(this,obj);
-    }
-    void DeleteWeakGlobalRef(jweak ref) {
-        functions->DeleteWeakGlobalRef(this,ref);
-    }
-
-    jboolean ExceptionCheck() {
-	return functions->ExceptionCheck(this);
-    }
-
-    jobject NewDirectByteBuffer(void* address, jlong capacity) {
-        return functions->NewDirectByteBuffer(this, address, capacity);
-    }
-    void* GetDirectBufferAddress(jobject buf) {
-        return functions->GetDirectBufferAddress(this, buf);
-    }
-    jlong GetDirectBufferCapacity(jobject buf) {
-        return functions->GetDirectBufferCapacity(this, buf);
-    }
-
-#endif /* __cplusplus */
-};
-
-typedef struct JavaVMOption {
-    char *optionString;
-    void *extraInfo;
-} JavaVMOption;
-
-typedef struct JavaVMInitArgs {
-    jint version;
-
-    jint nOptions;
-    JavaVMOption *options;
-    jboolean ignoreUnrecognized;
-} JavaVMInitArgs;
-
-typedef struct JavaVMAttachArgs {
-    jint version;
-
-    char *name;
-    jobject group;
-} JavaVMAttachArgs;
-
-/* These structures will be VM-specific. */
-
-typedef struct JDK1_1InitArgs {
-    jint version;
-
-    char **properties;
-    jint checkSource; 
-    jint nativeStackSize;
-    jint javaStackSize;
-    jint minHeapSize;
-    jint maxHeapSize;
-    jint verifyMode;
-    char *classpath;
-
-    jint (JNICALL *vfprintf)(FILE *fp, const char *format, va_list args);
-    void (JNICALL *exit)(jint code);
-    void (JNICALL *abort)(void);
-    
-    jint enableClassGC;
-    jint enableVerboseGC;
-    jint disableAsyncGC;
-    jint verbose;
-    jboolean debugging;
-    jint debugPort;
-} JDK1_1InitArgs;
-
-typedef struct JDK1_1AttachArgs {
-    void * __padding; /* C compilers don't allow empty structures. */
-} JDK1_1AttachArgs;
-
-#define JDK1_2
-#define JDK1_4
-
-/* End VM-specific. */
-
-struct JNIInvokeInterface_ {
-    void *reserved0;
-    void *reserved1;
-    void *reserved2;
-
-    jint (JNICALL *DestroyJavaVM)(JavaVM *vm);
-
-    jint (JNICALL *AttachCurrentThread)(JavaVM *vm, void **penv, void *args);
-
-    jint (JNICALL *DetachCurrentThread)(JavaVM *vm);
-
-    jint (JNICALL *GetEnv)(JavaVM *vm, void **penv, jint version);
-
-    jint (JNICALL *AttachCurrentThreadAsDaemon)(JavaVM *vm, void **penv, void *args);
-};
-
-struct JavaVM_ {
-    const struct JNIInvokeInterface_ *functions;
-#ifdef __cplusplus
-
-    jint DestroyJavaVM() {
-        return functions->DestroyJavaVM(this);
-    }
-    jint AttachCurrentThread(void **penv, void *args) {
-        return functions->AttachCurrentThread(this, penv, args);
-    }
-    jint DetachCurrentThread() {
-        return functions->DetachCurrentThread(this);
-    }
-
-    jint GetEnv(void **penv, jint version) {
-        return functions->GetEnv(this, penv, version);
-    }
-    jint AttachCurrentThreadAsDaemon(void **penv, void *args) {
-        return functions->AttachCurrentThreadAsDaemon(this, penv, args);
-    }
-#endif
-};
-
-#ifdef _JNI_IMPLEMENTATION_
-#define _JNI_IMPORT_OR_EXPORT_ JNIEXPORT
-#else
-#define _JNI_IMPORT_OR_EXPORT_ JNIIMPORT
-#endif
-_JNI_IMPORT_OR_EXPORT_ jint JNICALL
-JNI_GetDefaultJavaVMInitArgs(void *args);
-
-_JNI_IMPORT_OR_EXPORT_ jint JNICALL
-JNI_CreateJavaVM(JavaVM **pvm, void **penv, void *args);
-
-_JNI_IMPORT_OR_EXPORT_ jint JNICALL
-JNI_GetCreatedJavaVMs(JavaVM **, jsize, jsize *);
-
-/* Defined by native libraries. */
-JNIEXPORT jint JNICALL
-JNI_OnLoad(JavaVM *vm, void *reserved);
-
-JNIEXPORT void JNICALL
-JNI_OnUnload(JavaVM *vm, void *reserved);
-
-#define JNI_VERSION_1_1 0x00010001
-#define JNI_VERSION_1_2 0x00010002
-#define JNI_VERSION_1_4 0x00010004
-
-#ifdef __cplusplus
-} /* extern "C" */
-#endif /* __cplusplus */
-
-#endif /* JNI_H */
-
-
diff -r fcf435874395 -r 45c889eae324 front_idill/extern/fajran-npTuioClient/npapi/jni_md.h
--- a/front_idill/extern/fajran-npTuioClient/npapi/jni_md.h	Thu Apr 19 11:53:06 2012 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,215 +0,0 @@
-/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
- *
- * ***** BEGIN LICENSE BLOCK *****
- * Version: MPL 1.1/GPL 2.0/LGPL 2.1
- *
- * The contents of this file are subject to the Mozilla Public License Version
- * 1.1 (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- * http://www.mozilla.org/MPL/
- *
- * Software distributed under the License is distributed on an "AS IS" basis,
- * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
- * for the specific language governing rights and limitations under the
- * License.
- *
- * The Original Code is mozilla.org code.
- *
- * The Initial Developer of the Original Code is
- * Netscape Communications Corporation.
- * Portions created by the Initial Developer are Copyright (C) 1998
- * the Initial Developer. All Rights Reserved.
- *
- * Contributor(s):
- *
- * Alternatively, the contents of this file may be used under the terms of
- * either the GNU General Public License Version 2 or later (the "GPL"), or
- * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
- * in which case the provisions of the GPL or the LGPL are applicable instead
- * of those above. If you wish to allow use of your version of this file only
- * under the terms of either the GPL or the LGPL, and not to allow others to
- * use your version of this file under the terms of the MPL, indicate your
- * decision by deleting the provisions above and replace them with the notice
- * and other provisions required by the GPL or the LGPL. If you do not delete
- * the provisions above, a recipient may use your version of this file under
- * the terms of any one of the MPL, the GPL or the LGPL.
- *
- * ***** END LICENSE BLOCK *****
- *
- *
- * This Original Code has been modified by IBM Corporation.
- * Modifications made by IBM described herein are
- * Copyright (c) International Business Machines
- * Corporation, 2000
- *
- * Modifications to Mozilla code or documentation
- * identified per MPL Section 3.3
- *
- * Date         Modified by     Description of modification
- * 03/27/2000   IBM Corp.       Set JNICALL to Optlink for
- *                               use in OS2
- */
-
-/*******************************************************************************
- * Netscape version of jni_md.h -- depends on jri_md.h
- ******************************************************************************/
-
-#ifndef JNI_MD_H
-#define JNI_MD_H
-
-#include "prtypes.h" /* needed for _declspec */
-
-/*******************************************************************************
- * WHAT'S UP WITH THIS FILE?
- * 
- * This is where we define the mystical JNI_PUBLIC_API macro that works on all
- * platforms. If you're running with Visual C++, Symantec C, or Borland's 
- * development environment on the PC, you're all set. Or if you're on the Mac
- * with Metrowerks, Symantec or MPW with SC you're ok too. For UNIX it shouldn't
- * matter.
-
- * Changes by sailesh on 9/26 
-
- * There are two symbols used in the declaration of the JNI functions
- * and native code that uses the JNI:
- * JNICALL - specifies the calling convention 
- * JNIEXPORT - specifies export status of the function 
- * 
- * The syntax to specify calling conventions is different in Win16 and
- * Win32 - the brains at Micro$oft at work here. JavaSoft in their
- * infinite wisdom cares for no platform other than Win32, and so they
- * just define these two symbols as:
-
- #define JNIEXPORT __declspec(dllexport)
- #define JNICALL __stdcall
-
- * We deal with this, in the way JRI defines the JRI_PUBLIC_API, by
- * defining a macro called JNI_PUBLIC_API. Any of our developers who
- * wish to use code for Win16 and Win32, _must_ use JNI_PUBLIC_API to
- * be able to export functions properly.
-
- * Since we must also maintain compatibility with JavaSoft, we
- * continue to define the symbol JNIEXPORT. However, use of this
- * internally is deprecated, since it will cause a mess on Win16.
-
- * We _do not_ need a new symbol called JNICALL. Instead we
- * redefine JNICALL in the same way JRI_CALLBACK was defined.
-
- ******************************************************************************/
-
-/* DLL Entry modifiers... */
-/* Win32 */
-#if defined(XP_WIN) || defined(_WINDOWS) || defined(WIN32) || defined(_WIN32)
-#	include 
-#	if defined(_MSC_VER) || defined(__GNUC__)
-#		if defined(WIN32) || defined(_WIN32)
-#			define JNI_PUBLIC_API(ResultType)	_declspec(dllexport) ResultType __stdcall
-#			define JNI_PUBLIC_VAR(VarType)		VarType
-#			define JNI_NATIVE_STUB(ResultType)	_declspec(dllexport) ResultType
-#			define JNICALL                          __stdcall
-#		else /* !_WIN32 */
-#		    if defined(_WINDLL)
-#			define JNI_PUBLIC_API(ResultType)	ResultType __cdecl __export __loadds 
-#			define JNI_PUBLIC_VAR(VarType)		VarType
-#			define JNI_NATIVE_STUB(ResultType)	ResultType __cdecl __loadds
-#			define JNICALL			        __loadds
-#		    else /* !WINDLL */
-#			define JNI_PUBLIC_API(ResultType)	ResultType __cdecl __export
-#			define JNI_PUBLIC_VAR(VarType)		VarType
-#			define JNI_NATIVE_STUB(ResultType)	ResultType __cdecl __export
-#			define JNICALL			        __export
-#                   endif /* !WINDLL */
-#		endif /* !_WIN32 */
-#	elif defined(__BORLANDC__)
-#		if defined(WIN32) || defined(_WIN32)
-#			define JNI_PUBLIC_API(ResultType)	__export ResultType
-#			define JNI_PUBLIC_VAR(VarType)		VarType
-#			define JNI_NATIVE_STUB(ResultType)	 __export ResultType
-#			define JNICALL
-#		else /* !_WIN32 */
-#			define JNI_PUBLIC_API(ResultType)	ResultType _cdecl _export _loadds 
-#			define JNI_PUBLIC_VAR(VarType)		VarType
-#			define JNI_NATIVE_STUB(ResultType)	ResultType _cdecl _loadds
-#			define JNICALL			_loadds
-#		endif
-#	else
-#		error Unsupported PC development environment.	
-#	endif
-#	ifndef IS_LITTLE_ENDIAN
-#		define IS_LITTLE_ENDIAN
-#	endif
-	/*  This is the stuff inherited from JavaSoft .. */
-#	define JNIEXPORT __declspec(dllexport)
-#	define JNIIMPORT __declspec(dllimport)
-
-/* OS/2 */
-#elif defined(XP_OS2)
-#	ifdef XP_OS2_VACPP
-#		define JNI_PUBLIC_API(ResultType)	ResultType _System
-#		define JNI_PUBLIC_VAR(VarType)		VarType
-#		define JNICALL				_Optlink
-#		define JNIEXPORT
-#		define JNIIMPORT
-#	elif defined(__declspec)
-#		define JNI_PUBLIC_API(ResultType)	__declspec(dllexport) ResultType
-#		define JNI_PUBLIC_VAR(VarType)		VarType
-#		define JNI_NATIVE_STUB(ResultType)	__declspec(dllexport) ResultType
-#		define JNICALL
-#		define JNIEXPORT
-#		define JNIIMPORT
-#	else
-#		define JNI_PUBLIC_API(ResultType)	ResultType
-#		define JNI_PUBLIC_VAR(VarType)		VarType
-#		define JNICALL
-#		define JNIEXPORT
-#		define JNIIMPORT
-#	endif
-#	ifndef IS_LITTLE_ENDIAN
-#		define IS_LITTLE_ENDIAN
-#	endif
-
-/* Mac */
-#elif macintosh || Macintosh || THINK_C
-#	if defined(__MWERKS__)				/* Metrowerks */
-#		if !__option(enumsalwaysint)
-#			error You need to define 'Enums Always Int' for your project.
-#		endif
-#		if defined(TARGET_CPU_68K) && !TARGET_RT_MAC_CFM 
-#			if !__option(fourbyteints) 
-#				error You need to define 'Struct Alignment: 68k' for your project.
-#			endif
-#		endif /* !GENERATINGCFM */
-#		define JNI_PUBLIC_API(ResultType)	__declspec(export) ResultType 
-#		define JNI_PUBLIC_VAR(VarType)		JNI_PUBLIC_API(VarType)
-#		define JNI_NATIVE_STUB(ResultType)	JNI_PUBLIC_API(ResultType)
-#	elif defined(__SC__)				/* Symantec */
-#		error What are the Symantec defines? (warren@netscape.com)
-#	elif macintosh && applec			/* MPW */
-#		error Please upgrade to the latest MPW compiler (SC).
-#	else
-#		error Unsupported Mac development environment.
-#	endif
-#	define JNICALL
-	/*  This is the stuff inherited from JavaSoft .. */
-#	define JNIEXPORT
-#	define JNIIMPORT
-
-/* Unix or else */
-#else
-#	define JNI_PUBLIC_API(ResultType)		ResultType
-#       define JNI_PUBLIC_VAR(VarType)                  VarType
-#       define JNI_NATIVE_STUB(ResultType)              ResultType
-#	define JNICALL
-	/*  This is the stuff inherited from JavaSoft .. */
-#	define JNIEXPORT
-#	define JNIIMPORT
-#endif
-
-#ifndef FAR		/* for non-Win16 */
-#define FAR
-#endif
-
-/* Get the rest of the stuff from jri_md.h */
-#include "jri_md.h"
-
-#endif /* JNI_MD_H */
diff -r fcf435874395 -r 45c889eae324 front_idill/extern/fajran-npTuioClient/npapi/jri.h
--- a/front_idill/extern/fajran-npTuioClient/npapi/jri.h	Thu Apr 19 11:53:06 2012 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,689 +0,0 @@
-/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
-/* ***** BEGIN LICENSE BLOCK *****
- * Version: MPL 1.1/GPL 2.0/LGPL 2.1
- *
- * The contents of this file are subject to the Mozilla Public License Version
- * 1.1 (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- * http://www.mozilla.org/MPL/
- *
- * Software distributed under the License is distributed on an "AS IS" basis,
- * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
- * for the specific language governing rights and limitations under the
- * License.
- *
- * The Original Code is mozilla.org code.
- *
- * The Initial Developer of the Original Code is
- * Netscape Communications Corporation.
- * Portions created by the Initial Developer are Copyright (C) 1998
- * the Initial Developer. All Rights Reserved.
- *
- * Contributor(s):
- *
- * Alternatively, the contents of this file may be used under the terms of
- * either the GNU General Public License Version 2 or later (the "GPL"), or
- * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
- * in which case the provisions of the GPL or the LGPL are applicable instead
- * of those above. If you wish to allow use of your version of this file only
- * under the terms of either the GPL or the LGPL, and not to allow others to
- * use your version of this file under the terms of the MPL, indicate your
- * decision by deleting the provisions above and replace them with the notice
- * and other provisions required by the GPL or the LGPL. If you do not delete
- * the provisions above, a recipient may use your version of this file under
- * the terms of any one of the MPL, the GPL or the LGPL.
- *
- * ***** END LICENSE BLOCK ***** */
-
-/*******************************************************************************
- * Java Runtime Interface
- ******************************************************************************/
-
-#ifndef JRI_H
-#define JRI_H
-
-#include "jritypes.h"
-
-#ifdef __cplusplus
-extern "C" {
-#endif /* __cplusplus */
-
-/*******************************************************************************
- * JRIEnv
- ******************************************************************************/
-
-/* The type of the JRIEnv interface. */
-typedef struct JRIEnvInterface	JRIEnvInterface;
-
-/* The type of a JRIEnv instance. */
-typedef const JRIEnvInterface*	JRIEnv;
-
-/*******************************************************************************
- * JRIEnv Operations
- ******************************************************************************/
-
-#define JRI_DefineClass(env, classLoader, buf, bufLen)	\
-	(((*(env))->DefineClass)(env, JRI_DefineClass_op, classLoader, buf, bufLen))
-
-#define JRI_FindClass(env, name)	\
-	(((*(env))->FindClass)(env, JRI_FindClass_op, name))
-
-#define JRI_Throw(env, obj)	\
-	(((*(env))->Throw)(env, JRI_Throw_op, obj))
-
-#define JRI_ThrowNew(env, clazz, message)	\
-	(((*(env))->ThrowNew)(env, JRI_ThrowNew_op, clazz, message))
-
-#define JRI_ExceptionOccurred(env)	\
-	(((*(env))->ExceptionOccurred)(env, JRI_ExceptionOccurred_op))
-
-#define JRI_ExceptionDescribe(env)	\
-	(((*(env))->ExceptionDescribe)(env, JRI_ExceptionDescribe_op))
-
-#define JRI_ExceptionClear(env)	\
-	(((*(env))->ExceptionClear)(env, JRI_ExceptionClear_op))
-
-#define JRI_NewGlobalRef(env, ref)	\
-	(((*(env))->NewGlobalRef)(env, JRI_NewGlobalRef_op, ref))
-
-#define JRI_DisposeGlobalRef(env, gref)	\
-	(((*(env))->DisposeGlobalRef)(env, JRI_DisposeGlobalRef_op, gref))
-
-#define JRI_GetGlobalRef(env, gref)	\
-	(((*(env))->GetGlobalRef)(env, JRI_GetGlobalRef_op, gref))
-
-#define JRI_SetGlobalRef(env, gref, ref)	\
-	(((*(env))->SetGlobalRef)(env, JRI_SetGlobalRef_op, gref, ref))
-
-#define JRI_IsSameObject(env, a, b)	\
-	(((*(env))->IsSameObject)(env, JRI_IsSameObject_op, a, b))
-
-#define JRI_NewObject(env)	((*(env))->NewObject)
-#define JRI_NewObjectV(env, clazz, methodID, args)	\
-	(((*(env))->NewObjectV)(env, JRI_NewObject_op_va_list, clazz, methodID, args))
-#define JRI_NewObjectA(env, clazz, method, args)	\
-	(((*(env))->NewObjectA)(env, JRI_NewObject_op_array, clazz, methodID, args))
-
-#define JRI_GetObjectClass(env, obj)	\
-	(((*(env))->GetObjectClass)(env, JRI_GetObjectClass_op, obj))
-
-#define JRI_IsInstanceOf(env, obj, clazz)	\
-	(((*(env))->IsInstanceOf)(env, JRI_IsInstanceOf_op, obj, clazz))
-
-#define JRI_GetMethodID(env, clazz, name, sig)	\
-	(((*(env))->GetMethodID)(env, JRI_GetMethodID_op, clazz, name, sig))
-
-#define JRI_CallMethod(env)	((*(env))->CallMethod)
-#define JRI_CallMethodV(env, obj, methodID, args)	\
-	(((*(env))->CallMethodV)(env, JRI_CallMethod_op_va_list, obj, methodID, args))
-#define JRI_CallMethodA(env, obj, methodID, args)	\
-	(((*(env))->CallMethodA)(env, JRI_CallMethod_op_array, obj, methodID, args))
-
-#define JRI_CallMethodBoolean(env)	((*(env))->CallMethodBoolean)
-#define JRI_CallMethodBooleanV(env, obj, methodID, args)	\
-	(((*(env))->CallMethodBooleanV)(env, JRI_CallMethodBoolean_op_va_list, obj, methodID, args))
-#define JRI_CallMethodBooleanA(env, obj, methodID, args)	\
-	(((*(env))->CallMethodBooleanA)(env, JRI_CallMethodBoolean_op_array, obj, methodID, args))
-
-#define JRI_CallMethodByte(env)	((*(env))->CallMethodByte)
-#define JRI_CallMethodByteV(env, obj, methodID, args)	\
-	(((*(env))->CallMethodByteV)(env, JRI_CallMethodByte_op_va_list, obj, methodID, args))
-#define JRI_CallMethodByteA(env, obj, methodID, args)	\
-	(((*(env))->CallMethodByteA)(env, JRI_CallMethodByte_op_array, obj, methodID, args))
-
-#define JRI_CallMethodChar(env)	((*(env))->CallMethodChar)
-#define JRI_CallMethodCharV(env, obj, methodID, args)	\
-	(((*(env))->CallMethodCharV)(env, JRI_CallMethodChar_op_va_list, obj, methodID, args))
-#define JRI_CallMethodCharA(env, obj, methodID, args)	\
-	(((*(env))->CallMethodCharA)(env, JRI_CallMethodChar_op_array, obj, methodID, args))
-
-#define JRI_CallMethodShort(env)	((*(env))->CallMethodShort)
-#define JRI_CallMethodShortV(env, obj, methodID, args)	\
-	(((*(env))->CallMethodShortV)(env, JRI_CallMethodShort_op_va_list, obj, methodID, args))
-#define JRI_CallMethodShortA(env, obj, methodID, args)	\
-	(((*(env))->CallMethodShortA)(env, JRI_CallMethodShort_op_array, obj, methodID, args))
-
-#define JRI_CallMethodInt(env)	((*(env))->CallMethodInt)
-#define JRI_CallMethodIntV(env, obj, methodID, args)	\
-	(((*(env))->CallMethodIntV)(env, JRI_CallMethodInt_op_va_list, obj, methodID, args))
-#define JRI_CallMethodIntA(env, obj, methodID, args)	\
-	(((*(env))->CallMethodIntA)(env, JRI_CallMethodInt_op_array, obj, methodID, args))
-
-#define JRI_CallMethodLong(env)	((*(env))->CallMethodLong)
-#define JRI_CallMethodLongV(env, obj, methodID, args)	\
-	(((*(env))->CallMethodLongV)(env, JRI_CallMethodLong_op_va_list, obj, methodID, args))
-#define JRI_CallMethodLongA(env, obj, methodID, args)	\
-	(((*(env))->CallMethodLongA)(env, JRI_CallMethodLong_op_array, obj, methodID, args))
-
-#define JRI_CallMethodFloat(env)	((*(env))->CallMethodFloat)
-#define JRI_CallMethodFloatV(env, obj, methodID, args)	\
-	(((*(env))->CallMethodFloatV)(env, JRI_CallMethodFloat_op_va_list, obj, methodID, args))
-#define JRI_CallMethodFloatA(env, obj, methodID, args)	\
-	(((*(env))->CallMethodFloatA)(env, JRI_CallMethodFloat_op_array, obj, methodID, args))
-
-#define JRI_CallMethodDouble(env)	((*(env))->CallMethodDouble)
-#define JRI_CallMethodDoubleV(env, obj, methodID, args)	\
-	(((*(env))->CallMethodDoubleV)(env, JRI_CallMethodDouble_op_va_list, obj, methodID, args))
-#define JRI_CallMethodDoubleA(env, obj, methodID, args)	\
-	(((*(env))->CallMethodDoubleA)(env, JRI_CallMethodDouble_op_array, obj, methodID, args))
-
-#define JRI_GetFieldID(env, clazz, name, sig)	\
-	(((*(env))->GetFieldID)(env, JRI_GetFieldID_op, clazz, name, sig))
-
-#define JRI_GetField(env, obj, fieldID)	\
-	(((*(env))->GetField)(env, JRI_GetField_op, obj, fieldID))
-
-#define JRI_GetFieldBoolean(env, obj, fieldID)	\
-	(((*(env))->GetFieldBoolean)(env, JRI_GetFieldBoolean_op, obj, fieldID))
-
-#define JRI_GetFieldByte(env, obj, fieldID)	\
-	(((*(env))->GetFieldByte)(env, JRI_GetFieldByte_op, obj, fieldID))
-
-#define JRI_GetFieldChar(env, obj, fieldID)	\
-	(((*(env))->GetFieldChar)(env, JRI_GetFieldChar_op, obj, fieldID))
-
-#define JRI_GetFieldShort(env, obj, fieldID)	\
-	(((*(env))->GetFieldShort)(env, JRI_GetFieldShort_op, obj, fieldID))
-
-#define JRI_GetFieldInt(env, obj, fieldID)	\
-	(((*(env))->GetFieldInt)(env, JRI_GetFieldInt_op, obj, fieldID))
-
-#define JRI_GetFieldLong(env, obj, fieldID)	\
-	(((*(env))->GetFieldLong)(env, JRI_GetFieldLong_op, obj, fieldID))
-
-#define JRI_GetFieldFloat(env, obj, fieldID)	\
-	(((*(env))->GetFieldFloat)(env, JRI_GetFieldFloat_op, obj, fieldID))
-
-#define JRI_GetFieldDouble(env, obj, fieldID)	\
-	(((*(env))->GetFieldDouble)(env, JRI_GetFieldDouble_op, obj, fieldID))
-
-#define JRI_SetField(env, obj, fieldID, value)	\
-	(((*(env))->SetField)(env, JRI_SetField_op, obj, fieldID, value))
-
-#define JRI_SetFieldBoolean(env, obj, fieldID, value)	\
-	(((*(env))->SetFieldBoolean)(env, JRI_SetFieldBoolean_op, obj, fieldID, value))
-
-#define JRI_SetFieldByte(env, obj, fieldID, value)	\
-	(((*(env))->SetFieldByte)(env, JRI_SetFieldByte_op, obj, fieldID, value))
-
-#define JRI_SetFieldChar(env, obj, fieldID, value)	\
-	(((*(env))->SetFieldChar)(env, JRI_SetFieldChar_op, obj, fieldID, value))
-
-#define JRI_SetFieldShort(env, obj, fieldID, value)	\
-	(((*(env))->SetFieldShort)(env, JRI_SetFieldShort_op, obj, fieldID, value))
-
-#define JRI_SetFieldInt(env, obj, fieldID, value)	\
-	(((*(env))->SetFieldInt)(env, JRI_SetFieldInt_op, obj, fieldID, value))
-
-#define JRI_SetFieldLong(env, obj, fieldID, value)	\
-	(((*(env))->SetFieldLong)(env, JRI_SetFieldLong_op, obj, fieldID, value))
-
-#define JRI_SetFieldFloat(env, obj, fieldID, value)	\
-	(((*(env))->SetFieldFloat)(env, JRI_SetFieldFloat_op, obj, fieldID, value))
-
-#define JRI_SetFieldDouble(env, obj, fieldID, value)	\
-	(((*(env))->SetFieldDouble)(env, JRI_SetFieldDouble_op, obj, fieldID, value))
-
-#define JRI_IsSubclassOf(env, a, b)	\
-	(((*(env))->IsSubclassOf)(env, JRI_IsSubclassOf_op, a, b))
-
-#define JRI_GetStaticMethodID(env, clazz, name, sig)	\
-	(((*(env))->GetStaticMethodID)(env, JRI_GetStaticMethodID_op, clazz, name, sig))
-
-#define JRI_CallStaticMethod(env)	((*(env))->CallStaticMethod)
-#define JRI_CallStaticMethodV(env, clazz, methodID, args)	\
-	(((*(env))->CallStaticMethodV)(env, JRI_CallStaticMethod_op_va_list, clazz, methodID, args))
-#define JRI_CallStaticMethodA(env, clazz, methodID, args)	\
-	(((*(env))->CallStaticMethodA)(env, JRI_CallStaticMethod_op_array, clazz, methodID, args))
-
-#define JRI_CallStaticMethodBoolean(env)	((*(env))->CallStaticMethodBoolean)
-#define JRI_CallStaticMethodBooleanV(env, clazz, methodID, args)	\
-	(((*(env))->CallStaticMethodBooleanV)(env, JRI_CallStaticMethodBoolean_op_va_list, clazz, methodID, args))
-#define JRI_CallStaticMethodBooleanA(env, clazz, methodID, args)	\
-	(((*(env))->CallStaticMethodBooleanA)(env, JRI_CallStaticMethodBoolean_op_array, clazz, methodID, args))
-
-#define JRI_CallStaticMethodByte(env)	((*(env))->CallStaticMethodByte)
-#define JRI_CallStaticMethodByteV(env, clazz, methodID, args)	\
-	(((*(env))->CallStaticMethodByteV)(env, JRI_CallStaticMethodByte_op_va_list, clazz, methodID, args))
-#define JRI_CallStaticMethodByteA(env, clazz, methodID, args)	\
-	(((*(env))->CallStaticMethodByteA)(env, JRI_CallStaticMethodByte_op_array, clazz, methodID, args))
-
-#define JRI_CallStaticMethodChar(env)	((*(env))->CallStaticMethodChar)
-#define JRI_CallStaticMethodCharV(env, clazz, methodID, args)	\
-	(((*(env))->CallStaticMethodCharV)(env, JRI_CallStaticMethodChar_op_va_list, clazz, methodID, args))
-#define JRI_CallStaticMethodCharA(env, clazz, methodID, args)	\
-	(((*(env))->CallStaticMethodCharA)(env, JRI_CallStaticMethodChar_op_array, clazz, methodID, args))
-
-#define JRI_CallStaticMethodShort(env)	((*(env))->CallStaticMethodShort)
-#define JRI_CallStaticMethodShortV(env, clazz, methodID, args)	\
-	(((*(env))->CallStaticMethodShortV)(env, JRI_CallStaticMethodShort_op_va_list, clazz, methodID, args))
-#define JRI_CallStaticMethodShortA(env, clazz, methodID, args)	\
-	(((*(env))->CallStaticMethodShortA)(env, JRI_CallStaticMethodShort_op_array, clazz, methodID, args))
-
-#define JRI_CallStaticMethodInt(env)	((*(env))->CallStaticMethodInt)
-#define JRI_CallStaticMethodIntV(env, clazz, methodID, args)	\
-	(((*(env))->CallStaticMethodIntV)(env, JRI_CallStaticMethodInt_op_va_list, clazz, methodID, args))
-#define JRI_CallStaticMethodIntA(env, clazz, methodID, args)	\
-	(((*(env))->CallStaticMethodIntA)(env, JRI_CallStaticMethodInt_op_array, clazz, methodID, args))
-
-#define JRI_CallStaticMethodLong(env)	((*(env))->CallStaticMethodLong)
-#define JRI_CallStaticMethodLongV(env, clazz, methodID, args)	\
-	(((*(env))->CallStaticMethodLongV)(env, JRI_CallStaticMethodLong_op_va_list, clazz, methodID, args))
-#define JRI_CallStaticMethodLongA(env, clazz, methodID, args)	\
-	(((*(env))->CallStaticMethodLongA)(env, JRI_CallStaticMethodLong_op_array, clazz, methodID, args))
-
-#define JRI_CallStaticMethodFloat(env)	((*(env))->CallStaticMethodFloat)
-#define JRI_CallStaticMethodFloatV(env, clazz, methodID, args)	\
-	(((*(env))->CallStaticMethodFloatV)(env, JRI_CallStaticMethodFloat_op_va_list, clazz, methodID, args))
-#define JRI_CallStaticMethodFloatA(env, clazz, methodID, args)	\
-	(((*(env))->CallStaticMethodFloatA)(env, JRI_CallStaticMethodFloat_op_array, clazz, methodID, args))
-
-#define JRI_CallStaticMethodDouble(env)	((*(env))->CallStaticMethodDouble)
-#define JRI_CallStaticMethodDoubleV(env, clazz, methodID, args)	\
-	(((*(env))->CallStaticMethodDoubleV)(env, JRI_CallStaticMethodDouble_op_va_list, clazz, methodID, args))
-#define JRI_CallStaticMethodDoubleA(env, clazz, methodID, args)	\
-	(((*(env))->CallStaticMethodDoubleA)(env, JRI_CallStaticMethodDouble_op_array, clazz, methodID, args))
-
-#define JRI_GetStaticFieldID(env, clazz, name, sig)	\
-	(((*(env))->GetStaticFieldID)(env, JRI_GetStaticFieldID_op, clazz, name, sig))
-
-#define JRI_GetStaticField(env, clazz, fieldID)	\
-	(((*(env))->GetStaticField)(env, JRI_GetStaticField_op, clazz, fieldID))
-
-#define JRI_GetStaticFieldBoolean(env, clazz, fieldID)	\
-	(((*(env))->GetStaticFieldBoolean)(env, JRI_GetStaticFieldBoolean_op, clazz, fieldID))
-
-#define JRI_GetStaticFieldByte(env, clazz, fieldID)	\
-	(((*(env))->GetStaticFieldByte)(env, JRI_GetStaticFieldByte_op, clazz, fieldID))
-
-#define JRI_GetStaticFieldChar(env, clazz, fieldID)	\
-	(((*(env))->GetStaticFieldChar)(env, JRI_GetStaticFieldChar_op, clazz, fieldID))
-
-#define JRI_GetStaticFieldShort(env, clazz, fieldID)	\
-	(((*(env))->GetStaticFieldShort)(env, JRI_GetStaticFieldShort_op, clazz, fieldID))
-
-#define JRI_GetStaticFieldInt(env, clazz, fieldID)	\
-	(((*(env))->GetStaticFieldInt)(env, JRI_GetStaticFieldInt_op, clazz, fieldID))
-
-#define JRI_GetStaticFieldLong(env, clazz, fieldID)	\
-	(((*(env))->GetStaticFieldLong)(env, JRI_GetStaticFieldLong_op, clazz, fieldID))
-
-#define JRI_GetStaticFieldFloat(env, clazz, fieldID)	\
-	(((*(env))->GetStaticFieldFloat)(env, JRI_GetStaticFieldFloat_op, clazz, fieldID))
-
-#define JRI_GetStaticFieldDouble(env, clazz, fieldID)	\
-	(((*(env))->GetStaticFieldDouble)(env, JRI_GetStaticFieldDouble_op, clazz, fieldID))
-
-#define JRI_SetStaticField(env, clazz, fieldID, value)	\
-	(((*(env))->SetStaticField)(env, JRI_SetStaticField_op, clazz, fieldID, value))
-
-#define JRI_SetStaticFieldBoolean(env, clazz, fieldID, value)	\
-	(((*(env))->SetStaticFieldBoolean)(env, JRI_SetStaticFieldBoolean_op, clazz, fieldID, value))
-
-#define JRI_SetStaticFieldByte(env, clazz, fieldID, value)	\
-	(((*(env))->SetStaticFieldByte)(env, JRI_SetStaticFieldByte_op, clazz, fieldID, value))
-
-#define JRI_SetStaticFieldChar(env, clazz, fieldID, value)	\
-	(((*(env))->SetStaticFieldChar)(env, JRI_SetStaticFieldChar_op, clazz, fieldID, value))
-
-#define JRI_SetStaticFieldShort(env, clazz, fieldID, value)	\
-	(((*(env))->SetStaticFieldShort)(env, JRI_SetStaticFieldShort_op, clazz, fieldID, value))
-
-#define JRI_SetStaticFieldInt(env, clazz, fieldID, value)	\
-	(((*(env))->SetStaticFieldInt)(env, JRI_SetStaticFieldInt_op, clazz, fieldID, value))
-
-#define JRI_SetStaticFieldLong(env, clazz, fieldID, value)	\
-	(((*(env))->SetStaticFieldLong)(env, JRI_SetStaticFieldLong_op, clazz, fieldID, value))
-
-#define JRI_SetStaticFieldFloat(env, clazz, fieldID, value)	\
-	(((*(env))->SetStaticFieldFloat)(env, JRI_SetStaticFieldFloat_op, clazz, fieldID, value))
-
-#define JRI_SetStaticFieldDouble(env, clazz, fieldID, value)	\
-	(((*(env))->SetStaticFieldDouble)(env, JRI_SetStaticFieldDouble_op, clazz, fieldID, value))
-
-#define JRI_NewString(env, unicode, len)	\
-	(((*(env))->NewString)(env, JRI_NewString_op, unicode, len))
-
-#define JRI_GetStringLength(env, string)	\
-	(((*(env))->GetStringLength)(env, JRI_GetStringLength_op, string))
-
-#define JRI_GetStringChars(env, string)	\
-	(((*(env))->GetStringChars)(env, JRI_GetStringChars_op, string))
-
-#define JRI_NewStringUTF(env, utf, len)	\
-	(((*(env))->NewStringUTF)(env, JRI_NewStringUTF_op, utf, len))
-
-#define JRI_GetStringUTFLength(env, string)	\
-	(((*(env))->GetStringUTFLength)(env, JRI_GetStringUTFLength_op, string))
-
-#define JRI_GetStringUTFChars(env, string)	\
-	(((*(env))->GetStringUTFChars)(env, JRI_GetStringUTFChars_op, string))
-
-#define JRI_NewScalarArray(env, length, elementSig, initialElements)	\
-	(((*(env))->NewScalarArray)(env, JRI_NewScalarArray_op, length, elementSig, initialElements))
-
-#define JRI_GetScalarArrayLength(env, array)	\
-	(((*(env))->GetScalarArrayLength)(env, JRI_GetScalarArrayLength_op, array))
-
-#define JRI_GetScalarArrayElements(env, array)	\
-	(((*(env))->GetScalarArrayElements)(env, JRI_GetScalarArrayElements_op, array))
-
-#define JRI_NewObjectArray(env, length, elementClass, initialElement)	\
-	(((*(env))->NewObjectArray)(env, JRI_NewObjectArray_op, length, elementClass, initialElement))
-
-#define JRI_GetObjectArrayLength(env, array)	\
-	(((*(env))->GetObjectArrayLength)(env, JRI_GetObjectArrayLength_op, array))
-
-#define JRI_GetObjectArrayElement(env, array, index)	\
-	(((*(env))->GetObjectArrayElement)(env, JRI_GetObjectArrayElement_op, array, index))
-
-#define JRI_SetObjectArrayElement(env, array, index, value)	\
-	(((*(env))->SetObjectArrayElement)(env, JRI_SetObjectArrayElement_op, array, index, value))
-
-#define JRI_RegisterNatives(env, clazz, nameAndSigArray, nativeProcArray)	\
-	(((*(env))->RegisterNatives)(env, JRI_RegisterNatives_op, clazz, nameAndSigArray, nativeProcArray))
-
-#define JRI_UnregisterNatives(env, clazz)	\
-	(((*(env))->UnregisterNatives)(env, JRI_UnregisterNatives_op, clazz))
-
-#define JRI_NewStringPlatform(env, string, len, encoding, encodingLength)	\
-	(((*(env))->NewStringPlatform)(env, JRI_NewStringPlatform_op, string, len, encoding, encodingLength))
-
-#define JRI_GetStringPlatformChars(env, string, encoding, encodingLength)	\
-	(((*(env))->GetStringPlatformChars)(env, JRI_GetStringPlatformChars_op, string, encoding, encodingLength))
-
-
-/*******************************************************************************
- * JRIEnv Interface
- ******************************************************************************/
-
-struct java_lang_ClassLoader;
-struct java_lang_Class;
-struct java_lang_Throwable;
-struct java_lang_Object;
-struct java_lang_String;
-
-struct JRIEnvInterface {
-	void*	reserved0;
-	void*	reserved1;
-	void*	reserved2;
-	void*	reserved3;
-	struct java_lang_Class*	(*FindClass)(JRIEnv* env, jint op, const char* a);
-	void	(*Throw)(JRIEnv* env, jint op, struct java_lang_Throwable* a);
-	void	(*ThrowNew)(JRIEnv* env, jint op, struct java_lang_Class* a, const char* b);
-	struct java_lang_Throwable*	(*ExceptionOccurred)(JRIEnv* env, jint op);
-	void	(*ExceptionDescribe)(JRIEnv* env, jint op);
-	void	(*ExceptionClear)(JRIEnv* env, jint op);
-	jglobal	(*NewGlobalRef)(JRIEnv* env, jint op, void* a);
-	void	(*DisposeGlobalRef)(JRIEnv* env, jint op, jglobal a);
-	void*	(*GetGlobalRef)(JRIEnv* env, jint op, jglobal a);
-	void	(*SetGlobalRef)(JRIEnv* env, jint op, jglobal a, void* b);
-	jbool	(*IsSameObject)(JRIEnv* env, jint op, void* a, void* b);
-	void*	(*NewObject)(JRIEnv* env, jint op, struct java_lang_Class* a, jint b, ...);
-	void*	(*NewObjectV)(JRIEnv* env, jint op, struct java_lang_Class* a, jint b, va_list c);
-	void*	(*NewObjectA)(JRIEnv* env, jint op, struct java_lang_Class* a, jint b, JRIValue* c);
-	struct java_lang_Class*	(*GetObjectClass)(JRIEnv* env, jint op, void* a);
-	jbool	(*IsInstanceOf)(JRIEnv* env, jint op, void* a, struct java_lang_Class* b);
-	jint	(*GetMethodID)(JRIEnv* env, jint op, struct java_lang_Class* a, const char* b, const char* c);
-	void*	(*CallMethod)(JRIEnv* env, jint op, void* a, jint b, ...);
-	void*	(*CallMethodV)(JRIEnv* env, jint op, void* a, jint b, va_list c);
-	void*	(*CallMethodA)(JRIEnv* env, jint op, void* a, jint b, JRIValue* c);
-	jbool	(*CallMethodBoolean)(JRIEnv* env, jint op, void* a, jint b, ...);
-	jbool	(*CallMethodBooleanV)(JRIEnv* env, jint op, void* a, jint b, va_list c);
-	jbool	(*CallMethodBooleanA)(JRIEnv* env, jint op, void* a, jint b, JRIValue* c);
-	jbyte	(*CallMethodByte)(JRIEnv* env, jint op, void* a, jint b, ...);
-	jbyte	(*CallMethodByteV)(JRIEnv* env, jint op, void* a, jint b, va_list c);
-	jbyte	(*CallMethodByteA)(JRIEnv* env, jint op, void* a, jint b, JRIValue* c);
-	jchar	(*CallMethodChar)(JRIEnv* env, jint op, void* a, jint b, ...);
-	jchar	(*CallMethodCharV)(JRIEnv* env, jint op, void* a, jint b, va_list c);
-	jchar	(*CallMethodCharA)(JRIEnv* env, jint op, void* a, jint b, JRIValue* c);
-	jshort	(*CallMethodShort)(JRIEnv* env, jint op, void* a, jint b, ...);
-	jshort	(*CallMethodShortV)(JRIEnv* env, jint op, void* a, jint b, va_list c);
-	jshort	(*CallMethodShortA)(JRIEnv* env, jint op, void* a, jint b, JRIValue* c);
-	jint	(*CallMethodInt)(JRIEnv* env, jint op, void* a, jint b, ...);
-	jint	(*CallMethodIntV)(JRIEnv* env, jint op, void* a, jint b, va_list c);
-	jint	(*CallMethodIntA)(JRIEnv* env, jint op, void* a, jint b, JRIValue* c);
-	jlong	(*CallMethodLong)(JRIEnv* env, jint op, void* a, jint b, ...);
-	jlong	(*CallMethodLongV)(JRIEnv* env, jint op, void* a, jint b, va_list c);
-	jlong	(*CallMethodLongA)(JRIEnv* env, jint op, void* a, jint b, JRIValue* c);
-	jfloat	(*CallMethodFloat)(JRIEnv* env, jint op, void* a, jint b, ...);
-	jfloat	(*CallMethodFloatV)(JRIEnv* env, jint op, void* a, jint b, va_list c);
-	jfloat	(*CallMethodFloatA)(JRIEnv* env, jint op, void* a, jint b, JRIValue* c);
-	jdouble	(*CallMethodDouble)(JRIEnv* env, jint op, void* a, jint b, ...);
-	jdouble	(*CallMethodDoubleV)(JRIEnv* env, jint op, void* a, jint b, va_list c);
-	jdouble	(*CallMethodDoubleA)(JRIEnv* env, jint op, void* a, jint b, JRIValue* c);
-	jint	(*GetFieldID)(JRIEnv* env, jint op, struct java_lang_Class* a, const char* b, const char* c);
-	void*	(*GetField)(JRIEnv* env, jint op, void* a, jint b);
-	jbool	(*GetFieldBoolean)(JRIEnv* env, jint op, void* a, jint b);
-	jbyte	(*GetFieldByte)(JRIEnv* env, jint op, void* a, jint b);
-	jchar	(*GetFieldChar)(JRIEnv* env, jint op, void* a, jint b);
-	jshort	(*GetFieldShort)(JRIEnv* env, jint op, void* a, jint b);
-	jint	(*GetFieldInt)(JRIEnv* env, jint op, void* a, jint b);
-	jlong	(*GetFieldLong)(JRIEnv* env, jint op, void* a, jint b);
-	jfloat	(*GetFieldFloat)(JRIEnv* env, jint op, void* a, jint b);
-	jdouble	(*GetFieldDouble)(JRIEnv* env, jint op, void* a, jint b);
-	void	(*SetField)(JRIEnv* env, jint op, void* a, jint b, void* c);
-	void	(*SetFieldBoolean)(JRIEnv* env, jint op, void* a, jint b, jbool c);
-	void	(*SetFieldByte)(JRIEnv* env, jint op, void* a, jint b, jbyte c);
-	void	(*SetFieldChar)(JRIEnv* env, jint op, void* a, jint b, jchar c);
-	void	(*SetFieldShort)(JRIEnv* env, jint op, void* a, jint b, jshort c);
-	void	(*SetFieldInt)(JRIEnv* env, jint op, void* a, jint b, jint c);
-	void	(*SetFieldLong)(JRIEnv* env, jint op, void* a, jint b, jlong c);
-	void	(*SetFieldFloat)(JRIEnv* env, jint op, void* a, jint b, jfloat c);
-	void	(*SetFieldDouble)(JRIEnv* env, jint op, void* a, jint b, jdouble c);
-	jbool	(*IsSubclassOf)(JRIEnv* env, jint op, struct java_lang_Class* a, struct java_lang_Class* b);
-	jint	(*GetStaticMethodID)(JRIEnv* env, jint op, struct java_lang_Class* a, const char* b, const char* c);
-	void*	(*CallStaticMethod)(JRIEnv* env, jint op, struct java_lang_Class* a, jint b, ...);
-	void*	(*CallStaticMethodV)(JRIEnv* env, jint op, struct java_lang_Class* a, jint b, va_list c);
-	void*	(*CallStaticMethodA)(JRIEnv* env, jint op, struct java_lang_Class* a, jint b, JRIValue* c);
-	jbool	(*CallStaticMethodBoolean)(JRIEnv* env, jint op, struct java_lang_Class* a, jint b, ...);
-	jbool	(*CallStaticMethodBooleanV)(JRIEnv* env, jint op, struct java_lang_Class* a, jint b, va_list c);
-	jbool	(*CallStaticMethodBooleanA)(JRIEnv* env, jint op, struct java_lang_Class* a, jint b, JRIValue* c);
-	jbyte	(*CallStaticMethodByte)(JRIEnv* env, jint op, struct java_lang_Class* a, jint b, ...);
-	jbyte	(*CallStaticMethodByteV)(JRIEnv* env, jint op, struct java_lang_Class* a, jint b, va_list c);
-	jbyte	(*CallStaticMethodByteA)(JRIEnv* env, jint op, struct java_lang_Class* a, jint b, JRIValue* c);
-	jchar	(*CallStaticMethodChar)(JRIEnv* env, jint op, struct java_lang_Class* a, jint b, ...);
-	jchar	(*CallStaticMethodCharV)(JRIEnv* env, jint op, struct java_lang_Class* a, jint b, va_list c);
-	jchar	(*CallStaticMethodCharA)(JRIEnv* env, jint op, struct java_lang_Class* a, jint b, JRIValue* c);
-	jshort	(*CallStaticMethodShort)(JRIEnv* env, jint op, struct java_lang_Class* a, jint b, ...);
-	jshort	(*CallStaticMethodShortV)(JRIEnv* env, jint op, struct java_lang_Class* a, jint b, va_list c);
-	jshort	(*CallStaticMethodShortA)(JRIEnv* env, jint op, struct java_lang_Class* a, jint b, JRIValue* c);
-	jint	(*CallStaticMethodInt)(JRIEnv* env, jint op, struct java_lang_Class* a, jint b, ...);
-	jint	(*CallStaticMethodIntV)(JRIEnv* env, jint op, struct java_lang_Class* a, jint b, va_list c);
-	jint	(*CallStaticMethodIntA)(JRIEnv* env, jint op, struct java_lang_Class* a, jint b, JRIValue* c);
-	jlong	(*CallStaticMethodLong)(JRIEnv* env, jint op, struct java_lang_Class* a, jint b, ...);
-	jlong	(*CallStaticMethodLongV)(JRIEnv* env, jint op, struct java_lang_Class* a, jint b, va_list c);
-	jlong	(*CallStaticMethodLongA)(JRIEnv* env, jint op, struct java_lang_Class* a, jint b, JRIValue* c);
-	jfloat	(*CallStaticMethodFloat)(JRIEnv* env, jint op, struct java_lang_Class* a, jint b, ...);
-	jfloat	(*CallStaticMethodFloatV)(JRIEnv* env, jint op, struct java_lang_Class* a, jint b, va_list c);
-	jfloat	(*CallStaticMethodFloatA)(JRIEnv* env, jint op, struct java_lang_Class* a, jint b, JRIValue* c);
-	jdouble	(*CallStaticMethodDouble)(JRIEnv* env, jint op, struct java_lang_Class* a, jint b, ...);
-	jdouble	(*CallStaticMethodDoubleV)(JRIEnv* env, jint op, struct java_lang_Class* a, jint b, va_list c);
-	jdouble	(*CallStaticMethodDoubleA)(JRIEnv* env, jint op, struct java_lang_Class* a, jint b, JRIValue* c);
-	jint	(*GetStaticFieldID)(JRIEnv* env, jint op, struct java_lang_Class* a, const char* b, const char* c);
-	void*	(*GetStaticField)(JRIEnv* env, jint op, struct java_lang_Class* a, jint b);
-	jbool	(*GetStaticFieldBoolean)(JRIEnv* env, jint op, struct java_lang_Class* a, jint b);
-	jbyte	(*GetStaticFieldByte)(JRIEnv* env, jint op, struct java_lang_Class* a, jint b);
-	jchar	(*GetStaticFieldChar)(JRIEnv* env, jint op, struct java_lang_Class* a, jint b);
-	jshort	(*GetStaticFieldShort)(JRIEnv* env, jint op, struct java_lang_Class* a, jint b);
-	jint	(*GetStaticFieldInt)(JRIEnv* env, jint op, struct java_lang_Class* a, jint b);
-	jlong	(*GetStaticFieldLong)(JRIEnv* env, jint op, struct java_lang_Class* a, jint b);
-	jfloat	(*GetStaticFieldFloat)(JRIEnv* env, jint op, struct java_lang_Class* a, jint b);
-	jdouble	(*GetStaticFieldDouble)(JRIEnv* env, jint op, struct java_lang_Class* a, jint b);
-	void	(*SetStaticField)(JRIEnv* env, jint op, struct java_lang_Class* a, jint b, void* c);
-	void	(*SetStaticFieldBoolean)(JRIEnv* env, jint op, struct java_lang_Class* a, jint b, jbool c);
-	void	(*SetStaticFieldByte)(JRIEnv* env, jint op, struct java_lang_Class* a, jint b, jbyte c);
-	void	(*SetStaticFieldChar)(JRIEnv* env, jint op, struct java_lang_Class* a, jint b, jchar c);
-	void	(*SetStaticFieldShort)(JRIEnv* env, jint op, struct java_lang_Class* a, jint b, jshort c);
-	void	(*SetStaticFieldInt)(JRIEnv* env, jint op, struct java_lang_Class* a, jint b, jint c);
-	void	(*SetStaticFieldLong)(JRIEnv* env, jint op, struct java_lang_Class* a, jint b, jlong c);
-	void	(*SetStaticFieldFloat)(JRIEnv* env, jint op, struct java_lang_Class* a, jint b, jfloat c);
-	void	(*SetStaticFieldDouble)(JRIEnv* env, jint op, struct java_lang_Class* a, jint b, jdouble c);
-	struct java_lang_String*	(*NewString)(JRIEnv* env, jint op, const jchar* a, jint b);
-	jint	(*GetStringLength)(JRIEnv* env, jint op, struct java_lang_String* a);
-	const jchar*	(*GetStringChars)(JRIEnv* env, jint op, struct java_lang_String* a);
-	struct java_lang_String*	(*NewStringUTF)(JRIEnv* env, jint op, const jbyte* a, jint b);
-	jint	(*GetStringUTFLength)(JRIEnv* env, jint op, struct java_lang_String* a);
-	const jbyte*	(*GetStringUTFChars)(JRIEnv* env, jint op, struct java_lang_String* a);
-	void*	(*NewScalarArray)(JRIEnv* env, jint op, jint a, const char* b, const jbyte* c);
-	jint	(*GetScalarArrayLength)(JRIEnv* env, jint op, void* a);
-	jbyte*	(*GetScalarArrayElements)(JRIEnv* env, jint op, void* a);
-	void*	(*NewObjectArray)(JRIEnv* env, jint op, jint a, struct java_lang_Class* b, void* c);
-	jint	(*GetObjectArrayLength)(JRIEnv* env, jint op, void* a);
-	void*	(*GetObjectArrayElement)(JRIEnv* env, jint op, void* a, jint b);
-	void	(*SetObjectArrayElement)(JRIEnv* env, jint op, void* a, jint b, void* c);
-	void	(*RegisterNatives)(JRIEnv* env, jint op, struct java_lang_Class* a, char** b, void** c);
-	void	(*UnregisterNatives)(JRIEnv* env, jint op, struct java_lang_Class* a);
-	struct java_lang_Class*	(*DefineClass)(JRIEnv* env, jint op, struct java_lang_ClassLoader* a, jbyte* b, jsize bLen);
-	struct java_lang_String*	(*NewStringPlatform)(JRIEnv* env, jint op, const jbyte* a, jint b, const jbyte* c, jint d);
-	const jbyte*	(*GetStringPlatformChars)(JRIEnv* env, jint op, struct java_lang_String* a, const jbyte* b, jint c);
-};
-
-/*
-** ****************************************************************************
-** JRIEnv Operation IDs
-** ***************************************************************************
-*/
-
-typedef enum JRIEnvOperations {
-	JRI_Reserved0_op,
-	JRI_Reserved1_op,
-	JRI_Reserved2_op,
-	JRI_Reserved3_op,
-	JRI_FindClass_op,
-	JRI_Throw_op,
-	JRI_ThrowNew_op,
-	JRI_ExceptionOccurred_op,
-	JRI_ExceptionDescribe_op,
-	JRI_ExceptionClear_op,
-	JRI_NewGlobalRef_op,
-	JRI_DisposeGlobalRef_op,
-	JRI_GetGlobalRef_op,
-	JRI_SetGlobalRef_op,
-	JRI_IsSameObject_op,
-	JRI_NewObject_op,
-	JRI_NewObject_op_va_list,
-	JRI_NewObject_op_array,
-	JRI_GetObjectClass_op,
-	JRI_IsInstanceOf_op,
-	JRI_GetMethodID_op,
-	JRI_CallMethod_op,
-	JRI_CallMethod_op_va_list,
-	JRI_CallMethod_op_array,
-	JRI_CallMethodBoolean_op,
-	JRI_CallMethodBoolean_op_va_list,
-	JRI_CallMethodBoolean_op_array,
-	JRI_CallMethodByte_op,
-	JRI_CallMethodByte_op_va_list,
-	JRI_CallMethodByte_op_array,
-	JRI_CallMethodChar_op,
-	JRI_CallMethodChar_op_va_list,
-	JRI_CallMethodChar_op_array,
-	JRI_CallMethodShort_op,
-	JRI_CallMethodShort_op_va_list,
-	JRI_CallMethodShort_op_array,
-	JRI_CallMethodInt_op,
-	JRI_CallMethodInt_op_va_list,
-	JRI_CallMethodInt_op_array,
-	JRI_CallMethodLong_op,
-	JRI_CallMethodLong_op_va_list,
-	JRI_CallMethodLong_op_array,
-	JRI_CallMethodFloat_op,
-	JRI_CallMethodFloat_op_va_list,
-	JRI_CallMethodFloat_op_array,
-	JRI_CallMethodDouble_op,
-	JRI_CallMethodDouble_op_va_list,
-	JRI_CallMethodDouble_op_array,
-	JRI_GetFieldID_op,
-	JRI_GetField_op,
-	JRI_GetFieldBoolean_op,
-	JRI_GetFieldByte_op,
-	JRI_GetFieldChar_op,
-	JRI_GetFieldShort_op,
-	JRI_GetFieldInt_op,
-	JRI_GetFieldLong_op,
-	JRI_GetFieldFloat_op,
-	JRI_GetFieldDouble_op,
-	JRI_SetField_op,
-	JRI_SetFieldBoolean_op,
-	JRI_SetFieldByte_op,
-	JRI_SetFieldChar_op,
-	JRI_SetFieldShort_op,
-	JRI_SetFieldInt_op,
-	JRI_SetFieldLong_op,
-	JRI_SetFieldFloat_op,
-	JRI_SetFieldDouble_op,
-	JRI_IsSubclassOf_op,
-	JRI_GetStaticMethodID_op,
-	JRI_CallStaticMethod_op,
-	JRI_CallStaticMethod_op_va_list,
-	JRI_CallStaticMethod_op_array,
-	JRI_CallStaticMethodBoolean_op,
-	JRI_CallStaticMethodBoolean_op_va_list,
-	JRI_CallStaticMethodBoolean_op_array,
-	JRI_CallStaticMethodByte_op,
-	JRI_CallStaticMethodByte_op_va_list,
-	JRI_CallStaticMethodByte_op_array,
-	JRI_CallStaticMethodChar_op,
-	JRI_CallStaticMethodChar_op_va_list,
-	JRI_CallStaticMethodChar_op_array,
-	JRI_CallStaticMethodShort_op,
-	JRI_CallStaticMethodShort_op_va_list,
-	JRI_CallStaticMethodShort_op_array,
-	JRI_CallStaticMethodInt_op,
-	JRI_CallStaticMethodInt_op_va_list,
-	JRI_CallStaticMethodInt_op_array,
-	JRI_CallStaticMethodLong_op,
-	JRI_CallStaticMethodLong_op_va_list,
-	JRI_CallStaticMethodLong_op_array,
-	JRI_CallStaticMethodFloat_op,
-	JRI_CallStaticMethodFloat_op_va_list,
-	JRI_CallStaticMethodFloat_op_array,
-	JRI_CallStaticMethodDouble_op,
-	JRI_CallStaticMethodDouble_op_va_list,
-	JRI_CallStaticMethodDouble_op_array,
-	JRI_GetStaticFieldID_op,
-	JRI_GetStaticField_op,
-	JRI_GetStaticFieldBoolean_op,
-	JRI_GetStaticFieldByte_op,
-	JRI_GetStaticFieldChar_op,
-	JRI_GetStaticFieldShort_op,
-	JRI_GetStaticFieldInt_op,
-	JRI_GetStaticFieldLong_op,
-	JRI_GetStaticFieldFloat_op,
-	JRI_GetStaticFieldDouble_op,
-	JRI_SetStaticField_op,
-	JRI_SetStaticFieldBoolean_op,
-	JRI_SetStaticFieldByte_op,
-	JRI_SetStaticFieldChar_op,
-	JRI_SetStaticFieldShort_op,
-	JRI_SetStaticFieldInt_op,
-	JRI_SetStaticFieldLong_op,
-	JRI_SetStaticFieldFloat_op,
-	JRI_SetStaticFieldDouble_op,
-	JRI_NewString_op,
-	JRI_GetStringLength_op,
-	JRI_GetStringChars_op,
-	JRI_NewStringUTF_op,
-	JRI_GetStringUTFLength_op,
-	JRI_GetStringUTFChars_op,
-	JRI_NewScalarArray_op,
-	JRI_GetScalarArrayLength_op,
-	JRI_GetScalarArrayElements_op,
-	JRI_NewObjectArray_op,
-	JRI_GetObjectArrayLength_op,
-	JRI_GetObjectArrayElement_op,
-	JRI_SetObjectArrayElement_op,
-	JRI_RegisterNatives_op,
-	JRI_UnregisterNatives_op,
-	JRI_DefineClass_op,
-	JRI_NewStringPlatform_op,
-	JRI_GetStringPlatformChars_op
-} JRIEnvOperations;
-
-#ifdef __cplusplus
-} /* extern "C" */
-#endif /* __cplusplus */
-
-#endif /* JRI_H */
-/******************************************************************************/
diff -r fcf435874395 -r 45c889eae324 front_idill/extern/fajran-npTuioClient/npapi/jri_md.h
--- a/front_idill/extern/fajran-npTuioClient/npapi/jri_md.h	Thu Apr 19 11:53:06 2012 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,574 +0,0 @@
-/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
-/* ***** BEGIN LICENSE BLOCK *****
- * Version: MPL 1.1/GPL 2.0/LGPL 2.1
- *
- * The contents of this file are subject to the Mozilla Public License Version
- * 1.1 (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- * http://www.mozilla.org/MPL/
- *
- * Software distributed under the License is distributed on an "AS IS" basis,
- * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
- * for the specific language governing rights and limitations under the
- * License.
- *
- * The Original Code is mozilla.org code.
- *
- * The Initial Developer of the Original Code is
- * Netscape Communications Corporation.
- * Portions created by the Initial Developer are Copyright (C) 1998
- * the Initial Developer. All Rights Reserved.
- *
- * Contributor(s):
- *
- * Alternatively, the contents of this file may be used under the terms of
- * either the GNU General Public License Version 2 or later (the "GPL"), or
- * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
- * in which case the provisions of the GPL or the LGPL are applicable instead
- * of those above. If you wish to allow use of your version of this file only
- * under the terms of either the GPL or the LGPL, and not to allow others to
- * use your version of this file under the terms of the MPL, indicate your
- * decision by deleting the provisions above and replace them with the notice
- * and other provisions required by the GPL or the LGPL. If you do not delete
- * the provisions above, a recipient may use your version of this file under
- * the terms of any one of the MPL, the GPL or the LGPL.
- *
- * ***** END LICENSE BLOCK ***** */
-
-/*******************************************************************************
- * Java Runtime Interface - Machine Dependent Types
- ******************************************************************************/
- 
-#ifndef JRI_MD_H
-#define JRI_MD_H
-
-#include 
-#include "prtypes.h" /* Needed for HAS_LONG_LONG ifdefs */
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/*******************************************************************************
- * WHAT'S UP WITH THIS FILE?
- * 
- * This is where we define the mystical JRI_PUBLIC_API macro that works on all
- * platforms. If you're running with Visual C++, Symantec C, or Borland's 
- * development environment on the PC, you're all set. Or if you're on the Mac
- * with Metrowerks, Symantec or MPW with SC you're ok too. For UNIX it shouldn't
- * matter.
- *
- * On UNIX though you probably care about a couple of other symbols though:
- *	IS_LITTLE_ENDIAN must be defined for little-endian systems
- *	HAVE_LONG_LONG must be defined on systems that have 'long long' integers
- *	HAVE_ALIGNED_LONGLONGS must be defined if long-longs must be 8 byte aligned
- *	HAVE_ALIGNED_DOUBLES must be defined if doubles must be 8 byte aligned
- *	IS_64 must be defined on 64-bit machines (like Dec Alpha)
- ******************************************************************************/
-
-/* DLL Entry modifiers... */
-
-/* Windows */
-#if defined(XP_WIN) || defined(_WINDOWS) || defined(WIN32) || defined(_WIN32)
-#	include 
-#	if defined(_MSC_VER) || defined(__GNUC__)
-#		if defined(WIN32) || defined(_WIN32)
-#			define JRI_PUBLIC_API(ResultType)  __declspec(dllexport) ResultType
-#			define JRI_PUBLIC_VAR(VarType)	   VarType
-#			define JRI_PUBLIC_VAR_EXP(VarType) __declspec(dllexport) VarType
-#			define JRI_PUBLIC_VAR_IMP(VarType) __declspec(dllimport) VarType
-#			define JRI_NATIVE_STUB(ResultType) __declspec(dllexport) ResultType
-#			define JRI_CALLBACK
-#		else /* !_WIN32 */
-#		    if defined(_WINDLL)
-#			define JRI_PUBLIC_API(ResultType)	ResultType __cdecl __export __loadds 
-#			define JRI_PUBLIC_VAR(VarType)		VarType
-#			define JRI_PUBLIC_VAR_EXP(VarType)	JRI_PUBLIC_VAR(VarType)
-#			define JRI_PUBLIC_VAR_IMP(VarType)	JRI_PUBLIC_VAR(VarType)
-#			define JRI_NATIVE_STUB(ResultType)	ResultType __cdecl __loadds
-#			define JRI_CALLBACK			__loadds
-#		else /* !WINDLL */
-#			define JRI_PUBLIC_API(ResultType)	ResultType __cdecl __export
-#			define JRI_PUBLIC_VAR(VarType)		VarType
-#			define JRI_PUBLIC_VAR_EXP(VarType)	JRI_PUBLIC_VAR(VarType)
-#			define JRI_PUBLIC_VAR_IMP(VarType)	JRI_PUBLIC_VAR(VarType)
-#			define JRI_NATIVE_STUB(ResultType)	ResultType __cdecl __export
-#			define JRI_CALLBACK			__export
-#                   endif /* !WINDLL */
-#		endif /* !_WIN32 */
-#	elif defined(__BORLANDC__)
-#		if defined(WIN32) || defined(_WIN32)
-#			define JRI_PUBLIC_API(ResultType)	__export ResultType
-#			define JRI_PUBLIC_VAR(VarType)		VarType
-#			define JRI_PUBLIC_VAR_EXP(VarType)	__export VarType
-#			define JRI_PUBLIC_VAR_IMP(VarType)	__import VarType
-#			define JRI_NATIVE_STUB(ResultType)	 __export ResultType
-#			define JRI_CALLBACK
-#		else /* !_WIN32 */
-#			define JRI_PUBLIC_API(ResultType)	ResultType _cdecl _export _loadds 
-#			define JRI_PUBLIC_VAR(VarType)		VarType
-#			define JRI_PUBLIC_VAR_EXP(VarType)	__cdecl __export VarType
-#			define JRI_PUBLIC_VAR_IMP(VarType)	__cdecl __import VarType
-#			define JRI_NATIVE_STUB(ResultType)	ResultType _cdecl _loadds
-#			define JRI_CALLBACK			_loadds
-#		endif
-#	else
-#		error Unsupported PC development environment.	
-#	endif
-#	ifndef IS_LITTLE_ENDIAN
-#		define IS_LITTLE_ENDIAN
-#	endif
-
-/* OS/2 */
-#elif defined(XP_OS2)
-#	ifdef XP_OS2_VACPP
-#		define JRI_PUBLIC_API(ResultType)	ResultType _Optlink
-#		define JRI_PUBLIC_VAR(VarType)		VarType
-#     		define JRI_CALLBACK
-#	elif defined(__declspec)
-#		define JRI_PUBLIC_API(ResultType)  	__declspec(dllexport) ResultType
-#		define JRI_PUBLIC_VAR(VarType)	   	VarType
-#		define JRI_PUBLIC_VAR_EXP(VarType) 	__declspec(dllexport) VarType
-#		define JRI_PUBLIC_VAR_IMP(VarType) 	__declspec(dllimport) VarType
-#		define JRI_NATIVE_STUB(ResultType) 	__declspec(dllexport) ResultType
-#		define JRI_CALLBACK
-#	else
-#		define JRI_PUBLIC_API(ResultType)	ResultType
-#		define JRI_PUBLIC_VAR(VarType)		VarType
-#		define JRI_CALLBACK
-#	endif
-
-/* Mac */
-#elif defined (macintosh) || Macintosh || THINK_C
-#	if defined(__MWERKS__)				/* Metrowerks */
-#		if !__option(enumsalwaysint)
-#			error You need to define 'Enums Always Int' for your project.
-#		endif
-#		if defined(TARGET_CPU_68K) && !TARGET_RT_MAC_CFM 
-#			if !__option(fourbyteints) 
-#				error You need to define 'Struct Alignment: 68k' for your project.
-#			endif
-#		endif /* !GENERATINGCFM */
-#		define JRI_PUBLIC_API(ResultType)	__declspec(export) ResultType
-#		define JRI_PUBLIC_VAR(VarType)		JRI_PUBLIC_API(VarType)
-#		define JRI_PUBLIC_VAR_EXP(VarType)	JRI_PUBLIC_API(VarType)
-#		define JRI_PUBLIC_VAR_IMP(VarType)	JRI_PUBLIC_API(VarType)
-#		define JRI_NATIVE_STUB(ResultType)	JRI_PUBLIC_API(ResultType)
-#	elif defined(__SC__)				/* Symantec */
-#		error What are the Symantec defines? (warren@netscape.com)
-#	elif macintosh && applec			/* MPW */
-#		error Please upgrade to the latest MPW compiler (SC).
-#	else
-#		error Unsupported Mac development environment.
-#	endif
-#	define JRI_CALLBACK
-
-/* Unix or else */
-#else
-#	define JRI_PUBLIC_API(ResultType)		ResultType
-#   define JRI_PUBLIC_VAR(VarType)          VarType
-#   define JRI_PUBLIC_VAR_EXP(VarType)		JRI_PUBLIC_VAR(VarType)
-#   define JRI_PUBLIC_VAR_IMP(VarType)		JRI_PUBLIC_VAR(VarType)
-#   define JRI_NATIVE_STUB(ResultType)		ResultType
-#	define JRI_CALLBACK
-#endif
-
-#ifndef FAR		/* for non-Win16 */
-#define FAR
-#endif
-
-/******************************************************************************/
-
-/* Java Scalar Types */
-
-#if 0	/* now in jni.h */
-typedef short			jchar;
-typedef short			jshort;
-typedef float			jfloat;
-typedef double			jdouble;
-typedef juint			jsize;
-#endif
-
-/* moved from jni.h -- Sun's new jni.h doesn't have this anymore */
-#ifdef __cplusplus
-typedef class _jobject *jref;
-#else
-typedef struct _jobject *jref;
-#endif
-
-typedef unsigned char	jbool;
-typedef signed char	jbyte;
-#ifdef IS_64 /* XXX ok for alpha, but not right on all 64-bit architectures */
-typedef unsigned int	juint;
-typedef int				jint;
-#else
-typedef unsigned long	juint;
-typedef long			jint;
-#endif
-
-/*******************************************************************************
- * jlong : long long (64-bit signed integer type) support.
- ******************************************************************************/
-
-/*
-** Bit masking macros.  (n must be <= 31 to be portable)
-*/
-#define JRI_BIT(n)			((juint)1 << (n))
-#define JRI_BITMASK(n)		(JRI_BIT(n) - 1)
-
-#ifdef HAVE_LONG_LONG
-
-#ifdef OSF1
-
-/* long is default 64-bit on OSF1, -std1 does not allow long long */
-typedef long                  jlong;
-typedef unsigned long         julong;
-#define jlong_MAXINT          0x7fffffffffffffffL
-#define jlong_MININT          0x8000000000000000L
-#define jlong_ZERO            0x0L
-
-#elif (defined(WIN32) || defined(_WIN32))
-
-typedef LONGLONG              jlong;
-typedef DWORDLONG             julong;
-#define jlong_MAXINT          0x7fffffffffffffffi64
-#define jlong_MININT          0x8000000000000000i64
-#define jlong_ZERO            0x0i64
-
-#else
-
-typedef long long             jlong;
-typedef unsigned long long    julong;
-#define jlong_MAXINT          0x7fffffffffffffffLL
-#define jlong_MININT          0x8000000000000000LL
-#define jlong_ZERO            0x0LL
-
-#endif
-
-#define jlong_IS_ZERO(a)	((a) == 0)
-#define jlong_EQ(a, b)		((a) == (b))
-#define jlong_NE(a, b)		((a) != (b))
-#define jlong_GE_ZERO(a)	((a) >= 0)
-#define jlong_CMP(a, op, b)	((a) op (b))
-
-#define jlong_AND(r, a, b)	((r) = (a) & (b))
-#define jlong_OR(r, a, b)	((r) = (a) | (b))
-#define jlong_XOR(r, a, b)	((r) = (a) ^ (b))
-#define jlong_OR2(r, a)		((r) = (r) | (a))
-#define jlong_NOT(r, a)		((r) = ~(a))
-
-#define jlong_NEG(r, a)		((r) = -(a))
-#define jlong_ADD(r, a, b)	((r) = (a) + (b))
-#define jlong_SUB(r, a, b)	((r) = (a) - (b))
-
-#define jlong_MUL(r, a, b)	((r) = (a) * (b))
-#define jlong_DIV(r, a, b)	((r) = (a) / (b))
-#define jlong_MOD(r, a, b)	((r) = (a) % (b))
-
-#define jlong_SHL(r, a, b)	((r) = (a) << (b))
-#define jlong_SHR(r, a, b)	((r) = (a) >> (b))
-#define jlong_USHR(r, a, b)	((r) = (julong)(a) >> (b))
-#define jlong_ISHL(r, a, b)	((r) = ((jlong)(a)) << (b))
-
-#define jlong_L2I(i, l)		((i) = (int)(l))
-#define jlong_L2UI(ui, l)	((ui) =(unsigned int)(l))
-#define jlong_L2F(f, l)		((f) = (l))
-#define jlong_L2D(d, l)		((d) = (l))
-
-#define jlong_I2L(l, i)		((l) = (i))
-#define jlong_UI2L(l, ui)	((l) = (ui))
-#define jlong_F2L(l, f)		((l) = (f))
-#define jlong_D2L(l, d)		((l) = (d))
-
-#define jlong_UDIVMOD(qp, rp, a, b)  \
-    (*(qp) = ((julong)(a) / (b)), \
-     *(rp) = ((julong)(a) % (b)))
-
-#else  /* !HAVE_LONG_LONG */
-
-typedef struct {
-#ifdef IS_LITTLE_ENDIAN
-    juint lo, hi;
-#else
-    juint hi, lo;
-#endif
-} jlong;
-typedef jlong				julong;
-
-extern jlong jlong_MAXINT, jlong_MININT, jlong_ZERO;
-
-#define jlong_IS_ZERO(a)	(((a).hi == 0) && ((a).lo == 0))
-#define jlong_EQ(a, b)		(((a).hi == (b).hi) && ((a).lo == (b).lo))
-#define jlong_NE(a, b)		(((a).hi != (b).hi) || ((a).lo != (b).lo))
-#define jlong_GE_ZERO(a)	(((a).hi >> 31) == 0)
-
-/*
- * NB: jlong_CMP and jlong_UCMP work only for strict relationals (<, >).
- */
-#define jlong_CMP(a, op, b)	(((int32)(a).hi op (int32)(b).hi) ||          \
-				 (((a).hi == (b).hi) && ((a).lo op (b).lo)))
-#define jlong_UCMP(a, op, b)	(((a).hi op (b).hi) ||                    \
-				 (((a).hi == (b).hi) && ((a).lo op (b).lo)))
-
-#define jlong_AND(r, a, b)	((r).lo = (a).lo & (b).lo,                    \
-				 (r).hi = (a).hi & (b).hi)
-#define jlong_OR(r, a, b)	((r).lo = (a).lo | (b).lo,                    \
-				 (r).hi = (a).hi | (b).hi)
-#define jlong_XOR(r, a, b)	((r).lo = (a).lo ^ (b).lo,                    \
-				 (r).hi = (a).hi ^ (b).hi)
-#define jlong_OR2(r, a)		((r).lo = (r).lo | (a).lo,                    \
-				 (r).hi = (r).hi | (a).hi)
-#define jlong_NOT(r, a)		((r).lo = ~(a).lo,	                          \
-				 (r).hi = ~(a).hi)
-
-#define jlong_NEG(r, a)		((r).lo = -(int32)(a).lo,                     \
-				 (r).hi = -(int32)(a).hi - ((r).lo != 0))
-#define jlong_ADD(r, a, b) {                                              \
-    jlong _a, _b;                                                         \
-    _a = a; _b = b;                                                       \
-    (r).lo = _a.lo + _b.lo;                                               \
-    (r).hi = _a.hi + _b.hi + ((r).lo < _b.lo);                            \
-}
-
-#define jlong_SUB(r, a, b) {                                              \
-    jlong _a, _b;                                                         \
-    _a = a; _b = b;                                                       \
-    (r).lo = _a.lo - _b.lo;                                               \
-    (r).hi = _a.hi - _b.hi - (_a.lo < _b.lo);                             \
-}                                                                         \
-
-/*
- * Multiply 64-bit operands a and b to get 64-bit result r.
- * First multiply the low 32 bits of a and b to get a 64-bit result in r.
- * Then add the outer and inner products to r.hi.
- */
-#define jlong_MUL(r, a, b) {                                              \
-    jlong _a, _b;                                                         \
-    _a = a; _b = b;                                                       \
-    jlong_MUL32(r, _a.lo, _b.lo);                                         \
-    (r).hi += _a.hi * _b.lo + _a.lo * _b.hi;                              \
-}
-
-/* XXX _jlong_lo16(a) = ((a) << 16 >> 16) is better on some archs (not on mips) */
-#define _jlong_lo16(a)		((a) & JRI_BITMASK(16))
-#define _jlong_hi16(a)		((a) >> 16)
-
-/*
- * Multiply 32-bit operands a and b to get 64-bit result r.
- * Use polynomial expansion based on primitive field element (1 << 16).
- */
-#define jlong_MUL32(r, a, b) {                                            \
-     juint _a1, _a0, _b1, _b0, _y0, _y1, _y2, _y3;                        \
-     _a1 = _jlong_hi16(a), _a0 = _jlong_lo16(a);                          \
-     _b1 = _jlong_hi16(b), _b0 = _jlong_lo16(b);                          \
-     _y0 = _a0 * _b0;                                                     \
-     _y1 = _a0 * _b1;                                                     \
-     _y2 = _a1 * _b0;                                                     \
-     _y3 = _a1 * _b1;                                                     \
-     _y1 += _jlong_hi16(_y0);                   /* can't carry */         \
-     _y1 += _y2;                                /* might carry */         \
-     if (_y1 < _y2) _y3 += 1 << 16;             /* propagate */           \
-     (r).lo = (_jlong_lo16(_y1) << 16) + _jlong_lo16(_y0);                \
-     (r).hi = _y3 + _jlong_hi16(_y1);                                     \
-}
-
-/*
- * Divide 64-bit unsigned operand a by 64-bit unsigned operand b, setting *qp
- * to the 64-bit unsigned quotient, and *rp to the 64-bit unsigned remainder.
- * Minimize effort if one of qp and rp is null.
- */
-#define jlong_UDIVMOD(qp, rp, a, b)	jlong_udivmod(qp, rp, a, b)
-
-extern JRI_PUBLIC_API(void)
-jlong_udivmod(julong *qp, julong *rp, julong a, julong b);
-
-#define jlong_DIV(r, a, b) {                                              \
-    jlong _a, _b;                                                         \
-    juint _negative = (int32)(a).hi < 0;                                  \
-    if (_negative) {                                                      \
-	jlong_NEG(_a, a);                                                     \
-    } else {                                                              \
-	_a = a;                                                               \
-    }                                                                     \
-    if ((int32)(b).hi < 0) {                                              \
-	_negative ^= 1;                                                       \
-	jlong_NEG(_b, b);                                                     \
-    } else {                                                              \
-	_b = b;                                                               \
-    }                                                                     \
-    jlong_UDIVMOD(&(r), 0, _a, _b);                                       \
-    if (_negative)                                                        \
-	jlong_NEG(r, r);                                                      \
-}
-
-#define jlong_MOD(r, a, b) {                                              \
-    jlong _a, _b;                                                         \
-    juint _negative = (int32)(a).hi < 0;                                  \
-    if (_negative) {                                                      \
-	jlong_NEG(_a, a);                                                     \
-    } else {                                                              \
-	_a = a;                                                               \
-    }                                                                     \
-    if ((int32)(b).hi < 0) {                                              \
-	jlong_NEG(_b, b);                                                     \
-    } else {                                                              \
-	_b = b;                                                               \
-    }                                                                     \
-    jlong_UDIVMOD(0, &(r), _a, _b);                                       \
-    if (_negative)                                                        \
-	jlong_NEG(r, r);                                                      \
-}
-
-/*
- * NB: b is a juint, not jlong or julong, for the shift ops.
- */
-#define jlong_SHL(r, a, b) {                                              \
-    if (b) {                                                              \
-	jlong _a;                                                             \
-        _a = a;                                                           \
-        if ((b) < 32) {                                                   \
-	    (r).lo = _a.lo << (b);                                            \
-	    (r).hi = (_a.hi << (b)) | (_a.lo >> (32 - (b)));                  \
-	} else {                                                              \
-	    (r).lo = 0;                                                       \
-	    (r).hi = _a.lo << ((b) & 31);                                     \
-	}                                                                     \
-    } else {                                                              \
-	(r) = (a);                                                            \
-    }                                                                     \
-}
-
-/* a is an int32, b is int32, r is jlong */
-#define jlong_ISHL(r, a, b) {                                             \
-    if (b) {                                                              \
-	jlong _a;                                                             \
-	_a.lo = (a);                                                          \
-	_a.hi = 0;                                                            \
-        if ((b) < 32) {                                                   \
-	    (r).lo = (a) << (b);                                              \
-	    (r).hi = ((a) >> (32 - (b)));                                     \
-	} else {                                                              \
-	    (r).lo = 0;                                                       \
-	    (r).hi = (a) << ((b) & 31);                                       \
-	}                                                                     \
-    } else {                                                              \
-	(r).lo = (a);                                                         \
-	(r).hi = 0;                                                           \
-    }                                                                     \
-}
-
-#define jlong_SHR(r, a, b) {                                              \
-    if (b) {                                                              \
-	jlong _a;                                                             \
-        _a = a;                                                           \
-	if ((b) < 32) {                                                       \
-	    (r).lo = (_a.hi << (32 - (b))) | (_a.lo >> (b));                  \
-	    (r).hi = (int32)_a.hi >> (b);                                     \
-	} else {                                                              \
-	    (r).lo = (int32)_a.hi >> ((b) & 31);                              \
-	    (r).hi = (int32)_a.hi >> 31;                                      \
-	}                                                                     \
-    } else {                                                              \
-	(r) = (a);                                                            \
-    }                                                                     \
-}
-
-#define jlong_USHR(r, a, b) {                                             \
-    if (b) {                                                              \
-	jlong _a;                                                             \
-        _a = a;                                                           \
-	if ((b) < 32) {                                                       \
-	    (r).lo = (_a.hi << (32 - (b))) | (_a.lo >> (b));                  \
-	    (r).hi = _a.hi >> (b);                                            \
-	} else {                                                              \
-	    (r).lo = _a.hi >> ((b) & 31);                                     \
-	    (r).hi = 0;                                                       \
-	}                                                                     \
-    } else {                                                              \
-	(r) = (a);                                                            \
-    }                                                                     \
-}
-
-#define jlong_L2I(i, l)		((i) = (l).lo)
-#define jlong_L2UI(ui, l)	((ui) = (l).lo)
-#define jlong_L2F(f, l)		{ double _d; jlong_L2D(_d, l); (f) = (float) _d; }
-
-#define jlong_L2D(d, l) {                                                 \
-    int32 _negative;                                                      \
-    jlong _absval;                                                        \
-                                                                          \
-    _negative = (l).hi >> 31;                                             \
-    if (_negative) {                                                      \
-	jlong_NEG(_absval, l);                                                \
-    } else {                                                              \
-	_absval = l;                                                          \
-    }                                                                     \
-    (d) = (double)_absval.hi * 4.294967296e9 + _absval.lo;                \
-    if (_negative)                                                        \
-	(d) = -(d);                                                           \
-}
-
-#define jlong_I2L(l, i)		((l).hi = (i) >> 31, (l).lo = (i))
-#define jlong_UI2L(l, ui)	((l).hi = 0, (l).lo = (ui))
-#define jlong_F2L(l, f)		{ double _d = (double) f; jlong_D2L(l, _d); }
-
-#define jlong_D2L(l, d) {                                                 \
-    int _negative;                                                        \
-    double _absval, _d_hi;                                                \
-    jlong _lo_d;                                                          \
-                                                                          \
-    _negative = ((d) < 0);                                                \
-    _absval = _negative ? -(d) : (d);                                     \
-                                                                          \
-    (l).hi = (juint)(_absval / 4.294967296e9);                            \
-    (l).lo = 0;                                                           \
-    jlong_L2D(_d_hi, l);                                                  \
-    _absval -= _d_hi;                                                     \
-    _lo_d.hi = 0;                                                         \
-    if (_absval < 0) {                                                    \
-	_lo_d.lo = (juint) -_absval;                                          \
-	jlong_SUB(l, l, _lo_d);                                               \
-    } else {                                                              \
-	_lo_d.lo = (juint) _absval;                                           \
-	jlong_ADD(l, l, _lo_d);                                               \
-    }                                                                     \
-                                                                          \
-    if (_negative)                                                        \
-	jlong_NEG(l, l);                                                      \
-}
-
-#endif /* !HAVE_LONG_LONG */
-
-/******************************************************************************/
-
-#ifdef HAVE_ALIGNED_LONGLONGS
-#define JRI_GET_INT64(_t,_addr) ( ((_t).x[0] = ((jint*)(_addr))[0]), \
-                              ((_t).x[1] = ((jint*)(_addr))[1]),      \
-                              (_t).l )
-#define JRI_SET_INT64(_t, _addr, _v) ( (_t).l = (_v),                \
-                                   ((jint*)(_addr))[0] = (_t).x[0], \
-                                   ((jint*)(_addr))[1] = (_t).x[1] )
-#else
-#define JRI_GET_INT64(_t,_addr) (*(jlong*)(_addr))
-#define JRI_SET_INT64(_t, _addr, _v) (*(jlong*)(_addr) = (_v))
-#endif
-
-/* If double's must be aligned on doubleword boundaries then define this */
-#ifdef HAVE_ALIGNED_DOUBLES
-#define JRI_GET_DOUBLE(_t,_addr) ( ((_t).x[0] = ((jint*)(_addr))[0]), \
-                               ((_t).x[1] = ((jint*)(_addr))[1]),      \
-                               (_t).d )
-#define JRI_SET_DOUBLE(_t, _addr, _v) ( (_t).d = (_v),                \
-                                    ((jint*)(_addr))[0] = (_t).x[0], \
-                                    ((jint*)(_addr))[1] = (_t).x[1] )
-#else
-#define JRI_GET_DOUBLE(_t,_addr) (*(jdouble*)(_addr))
-#define JRI_SET_DOUBLE(_t, _addr, _v) (*(jdouble*)(_addr) = (_v))
-#endif
-
-/******************************************************************************/
-#ifdef __cplusplus
-}
-#endif
-#endif /* JRI_MD_H */
-/******************************************************************************/
diff -r fcf435874395 -r 45c889eae324 front_idill/extern/fajran-npTuioClient/npapi/jritypes.h
--- a/front_idill/extern/fajran-npTuioClient/npapi/jritypes.h	Thu Apr 19 11:53:06 2012 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,243 +0,0 @@
-/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
-/* ***** BEGIN LICENSE BLOCK *****
- * Version: MPL 1.1/GPL 2.0/LGPL 2.1
- *
- * The contents of this file are subject to the Mozilla Public License Version
- * 1.1 (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- * http://www.mozilla.org/MPL/
- *
- * Software distributed under the License is distributed on an "AS IS" basis,
- * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
- * for the specific language governing rights and limitations under the
- * License.
- *
- * The Original Code is mozilla.org code.
- *
- * The Initial Developer of the Original Code is
- * Netscape Communications Corporation.
- * Portions created by the Initial Developer are Copyright (C) 1998
- * the Initial Developer. All Rights Reserved.
- *
- * Contributor(s):
- *
- * Alternatively, the contents of this file may be used under the terms of
- * either the GNU General Public License Version 2 or later (the "GPL"), or
- * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
- * in which case the provisions of the GPL or the LGPL are applicable instead
- * of those above. If you wish to allow use of your version of this file only
- * under the terms of either the GPL or the LGPL, and not to allow others to
- * use your version of this file under the terms of the MPL, indicate your
- * decision by deleting the provisions above and replace them with the notice
- * and other provisions required by the GPL or the LGPL. If you do not delete
- * the provisions above, a recipient may use your version of this file under
- * the terms of any one of the MPL, the GPL or the LGPL.
- *
- * ***** END LICENSE BLOCK ***** */
-
-/*******************************************************************************
- * Java Runtime Interface
- ******************************************************************************/
-
-#ifndef JRITYPES_H
-#define JRITYPES_H
-
-#include "jri_md.h"
-#include "jni.h"
-#include 
-#include 
-#include 
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/*******************************************************************************
- * Types
- ******************************************************************************/
-
-struct JRIEnvInterface;
-
-typedef void*		JRIRef;
-typedef void*		JRIGlobalRef;
-
-typedef jint		JRIFieldID;
-typedef jint		JRIMethodID;
-
-/* synonyms: */
-typedef JRIGlobalRef	jglobal;
-
-typedef union JRIValue {
-	jbool			z;
-	jbyte			b;
-	jchar			c;
-	jshort			s;
-	jint			i;
-	jlong			l;
-	jfloat			f;
-	jdouble			d;
-	jref			r;
-} JRIValue;
-
-typedef enum JRIBoolean {
-    JRIFalse		= 0,
-    JRITrue			= 1
-} JRIBoolean;
-
-typedef enum JRIConstant {
-	JRIUninitialized	= -1
-} JRIConstant;
-
-/* convenience types (these must be distinct struct types for c++ overloading): */
-#if 0	/* now in jni.h */
-typedef struct jbooleanArrayStruct*		jbooleanArray;
-typedef struct jbyteArrayStruct*		jbyteArray;
-typedef struct jcharArrayStruct*		jcharArray;
-typedef struct jshortArrayStruct*		jshortArray;
-typedef struct jintArrayStruct*			jintArray;
-typedef struct jlongArrayStruct*		jlongArray;
-typedef struct jfloatArrayStruct*		jfloatArray;
-typedef struct jdoubleArrayStruct*		jdoubleArray;
-typedef struct jobjectArrayStruct*		jobjectArray;
-#endif
-typedef struct jstringArrayStruct*		jstringArray;
-typedef struct jarrayArrayStruct*		jarrayArray;
-
-#define JRIConstructorMethodName	""
-
-/*******************************************************************************
- * Signature Construction Macros
- ******************************************************************************/
-
-/*
-** These macros can be used to construct signature strings. Hopefully their names
-** are a little easier to remember than the single character they correspond to.
-** For example, to specify the signature of the method:
-**
-**	public int read(byte b[], int off, int len);
-**
-** you could write something like this in C:
-**
-**	char* readSig = JRISigMethod(JRISigArray(JRISigByte)
-**								 JRISigInt
-**								 JRISigInt) JRISigInt;
-**
-** Of course, don't put commas between the types.
-*/
-#define JRISigArray(T)		"[" T
-#define JRISigByte			"B"
-#define JRISigChar			"C"
-#define JRISigClass(name)	"L" name ";"
-#define JRISigFloat			"F"
-#define JRISigDouble		"D"
-#define JRISigMethod(args)	"(" args ")"
-#define JRISigNoArgs		""
-#define JRISigInt			"I"
-#define JRISigLong			"J"
-#define JRISigShort			"S"
-#define JRISigVoid			"V"
-#define JRISigBoolean		"Z"
-
-/*******************************************************************************
- * Environments
- ******************************************************************************/
-
-extern JRI_PUBLIC_API(const struct JRIEnvInterface**)
-JRI_GetCurrentEnv(void);
-
-/*******************************************************************************
- * Specific Scalar Array Types
- ******************************************************************************/
-
-/*
-** The JRI Native Method Interface does not support boolean arrays. This
-** is to allow Java runtime implementations to optimize boolean array
-** storage. Using the ScalarArray operations on boolean arrays is bound
-** to fail, so convert any boolean arrays to byte arrays in Java before
-** passing them to a native method.
-*/
-
-#define JRI_NewByteArray(env, length, initialValues)	\
-	JRI_NewScalarArray(env, length, JRISigByte, (jbyte*)(initialValues))
-#define JRI_GetByteArrayLength(env, array)	\
-	JRI_GetScalarArrayLength(env, array)
-#define JRI_GetByteArrayElements(env, array)	\
-	JRI_GetScalarArrayElements(env, array)
-
-#define JRI_NewCharArray(env, length, initialValues)	\
-	JRI_NewScalarArray(env, ((length) * sizeof(jchar)), JRISigChar, (jbyte*)(initialValues))
-#define JRI_GetCharArrayLength(env, array)	\
-	JRI_GetScalarArrayLength(env, array)
-#define JRI_GetCharArrayElements(env, array)		   \
-	((jchar*)JRI_GetScalarArrayElements(env, array))
-
-#define JRI_NewShortArray(env, length, initialValues)	\
-	JRI_NewScalarArray(env, ((length) * sizeof(jshort)), JRISigShort, (jbyte*)(initialValues))
-#define JRI_GetShortArrayLength(env, array)	\
-	JRI_GetScalarArrayLength(env, array)
-#define JRI_GetShortArrayElements(env, array)		   \
-	((jshort*)JRI_GetScalarArrayElements(env, array))
-
-#define JRI_NewIntArray(env, length, initialValues)	\
-	JRI_NewScalarArray(env, ((length) * sizeof(jint)), JRISigInt, (jbyte*)(initialValues))
-#define JRI_GetIntArrayLength(env, array)	\
-	JRI_GetScalarArrayLength(env, array)
-#define JRI_GetIntArrayElements(env, array)		   \
-	((jint*)JRI_GetScalarArrayElements(env, array))
-
-#define JRI_NewLongArray(env, length, initialValues)	\
-	JRI_NewScalarArray(env, ((length) * sizeof(jlong)), JRISigLong, (jbyte*)(initialValues))
-#define JRI_GetLongArrayLength(env, array)	\
-	JRI_GetScalarArrayLength(env, array)
-#define JRI_GetLongArrayElements(env, array)		   \
-	((jlong*)JRI_GetScalarArrayElements(env, array))
-
-#define JRI_NewFloatArray(env, length, initialValues)	\
-	JRI_NewScalarArray(env, ((length) * sizeof(jfloat)), JRISigFloat, (jbyte*)(initialValues))
-#define JRI_GetFloatArrayLength(env, array)	\
-	JRI_GetScalarArrayLength(env, array)
-#define JRI_GetFloatArrayElements(env, array)		   \
-	((jfloat*)JRI_GetScalarArrayElements(env, array))
-
-#define JRI_NewDoubleArray(env, length, initialValues)	\
-	JRI_NewScalarArray(env, ((length) * sizeof(jdouble)), JRISigDouble, (jbyte*)(initialValues))
-#define JRI_GetDoubleArrayLength(env, array)	\
-	JRI_GetScalarArrayLength(env, array)
-#define JRI_GetDoubleArrayElements(env, array)		   \
-	((jdouble*)JRI_GetScalarArrayElements(env, array))
-
-/******************************************************************************/
-/*
-** JDK Stuff -- This stuff is still needed while we're using the JDK
-** dynamic linking strategy to call native methods.
-*/
-
-typedef union JRI_JDK_stack_item {
-    /* Non pointer items */
-    jint           i;
-    jfloat         f;
-    jint           o;
-    /* Pointer items */
-    void          *h;
-    void          *p;
-    unsigned char *addr;
-#ifdef IS_64
-    double         d;
-    long           l;		/* == 64bits! */
-#endif
-} JRI_JDK_stack_item;
-
-typedef union JRI_JDK_Java8Str {
-    jint x[2];
-    jdouble d;
-    jlong l;
-    void *p;
-    float f;
-} JRI_JDK_Java8;
-
-/******************************************************************************/
-#ifdef __cplusplus
-}
-#endif
-#endif /* JRITYPES_H */
-/******************************************************************************/
diff -r fcf435874395 -r 45c889eae324 front_idill/extern/fajran-npTuioClient/npapi/npapi.h
--- a/front_idill/extern/fajran-npTuioClient/npapi/npapi.h	Thu Apr 19 11:53:06 2012 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,766 +0,0 @@
-/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* ***** BEGIN LICENSE BLOCK *****
- * Version: MPL 1.1/GPL 2.0/LGPL 2.1
- *
- * The contents of this file are subject to the Mozilla Public License Version
- * 1.1 (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- * http://www.mozilla.org/MPL/
- *
- * Software distributed under the License is distributed on an "AS IS" basis,
- * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
- * for the specific language governing rights and limitations under the
- * License.
- *
- * The Original Code is mozilla.org code.
- *
- * The Initial Developer of the Original Code is
- * Netscape Communications Corporation.
- * Portions created by the Initial Developer are Copyright (C) 1998
- * the Initial Developer. All Rights Reserved.
- *
- * Contributor(s):
- *
- * Alternatively, the contents of this file may be used under the terms of
- * either the GNU General Public License Version 2 or later (the "GPL"), or
- * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
- * in which case the provisions of the GPL or the LGPL are applicable instead
- * of those above. If you wish to allow use of your version of this file only
- * under the terms of either the GPL or the LGPL, and not to allow others to
- * use your version of this file under the terms of the MPL, indicate your
- * decision by deleting the provisions above and replace them with the notice
- * and other provisions required by the GPL or the LGPL. If you do not delete
- * the provisions above, a recipient may use your version of this file under
- * the terms of any one of the MPL, the GPL or the LGPL.
- *
- * ***** END LICENSE BLOCK ***** */
-
-
-/*
- *  npapi.h $Revision: 3.48 $
- *  Netscape client plug-in API spec
- */
-
-#ifndef _NPAPI_H_
-#define _NPAPI_H_
-
-#ifdef __OS2__
-#pragma pack(1)
-#endif
-
-#include "prtypes.h"
-/* Copied from xp_core.h */
-/* removed #ifdef for hpux defined in /usr/include/model.h */
-#ifndef _INT16
-#define _INT16
-#endif
-#ifndef _INT32
-#define _INT32
-#endif
-#ifndef _UINT16
-#define _UINT16
-#endif
-#ifndef _UINT32
-#define _UINT32
-#endif
-
-/* 
- * NO_NSPR_10_SUPPORT disables the inclusion 
- * of obsolete/protypes.h, whose int16, uint16, 
- * int32, and uint32 typedefs conflict with those 
- * in this file. 
- */ 
-#ifndef NO_NSPR_10_SUPPORT
-#define NO_NSPR_10_SUPPORT
-#endif
-#ifdef OJI
-#include "jri.h"                /* Java Runtime Interface */
-#endif
-
-#if defined (__OS2__ ) || defined (OS2)
-#	ifndef XP_OS2
-#		define XP_OS2 1
-#	endif /* XP_OS2 */
-#endif /* __OS2__ */
-
-#ifdef _WINDOWS
-#	include 
-#	ifndef XP_WIN
-#		define XP_WIN 1
-#	endif /* XP_WIN */
-#endif /* _WINDOWS */
-
-#ifdef __MWERKS__
-#	define _declspec __declspec
-#	ifdef __INTEL__
-#		undef NULL
-#		ifndef XP_WIN
-#			define XP_WIN 1
-#		endif /* XP_WIN */
-#	endif /* __INTEL__ */
-#endif /* __MWERKS__ */
-
-#ifdef XP_MACOSX
-#include 
-#ifdef __LP64__
-#define NP_NO_QUICKDRAW
-#endif
-#endif
-
-#if defined(XP_UNIX) 
-#	include 
-#	if defined(MOZ_X11)
-#		include 
-#		include 
-#	endif
-#endif
-
-/*----------------------------------------------------------------------*/
-/*                        Plugin Version Constants                      */
-/*----------------------------------------------------------------------*/
-
-#define NP_VERSION_MAJOR 0
-#define NP_VERSION_MINOR 19
-
-
-/* The OS/2 version of Netscape uses RC_DATA to define the
-   mime types, file extensions, etc that are required.
-   Use a vertical bar to separate types, end types with \0.
-   FileVersion and ProductVersion are 32bit ints, all other
-   entries are strings the MUST be terminated wwith a \0.
-
-AN EXAMPLE:
-
-RCDATA NP_INFO_ProductVersion { 1,0,0,1,}
-
-RCDATA NP_INFO_MIMEType    { "video/x-video|",
-                             "video/x-flick\0" }
-RCDATA NP_INFO_FileExtents { "avi|",
-                             "flc\0" }
-RCDATA NP_INFO_FileOpenName{ "MMOS2 video player(*.avi)|",
-                             "MMOS2 Flc/Fli player(*.flc)\0" }
-
-RCDATA NP_INFO_FileVersion       { 1,0,0,1 }
-RCDATA NP_INFO_CompanyName       { "Netscape Communications\0" }
-RCDATA NP_INFO_FileDescription   { "NPAVI32 Extension DLL\0"
-RCDATA NP_INFO_InternalName      { "NPAVI32\0" )
-RCDATA NP_INFO_LegalCopyright    { "Copyright Netscape Communications \251 1996\0"
-RCDATA NP_INFO_OriginalFilename  { "NVAPI32.DLL" }
-RCDATA NP_INFO_ProductName       { "NPAVI32 Dynamic Link Library\0" }
-
-*/
-
-
-/* RC_DATA types for version info - required */
-#define NP_INFO_ProductVersion      1
-#define NP_INFO_MIMEType            2
-#define NP_INFO_FileOpenName        3
-#define NP_INFO_FileExtents         4
-
-/* RC_DATA types for version info - used if found */
-#define NP_INFO_FileDescription     5
-#define NP_INFO_ProductName         6
-
-/* RC_DATA types for version info - optional */
-#define NP_INFO_CompanyName         7
-#define NP_INFO_FileVersion         8
-#define NP_INFO_InternalName        9
-#define NP_INFO_LegalCopyright      10
-#define NP_INFO_OriginalFilename    11
-
-#ifndef RC_INVOKED
-
-
-
-/*----------------------------------------------------------------------*/
-/*                       Definition of Basic Types                      */
-/*----------------------------------------------------------------------*/
-
-#ifndef _UINT16
-typedef unsigned short uint16;
-#endif
-
-#ifndef _UINT32
-#    if defined(__alpha) || defined(__amd64__) || defined(__x86_64__)
-typedef unsigned int uint32;
-#    else  /* __alpha */
-typedef unsigned long uint32;
-#    endif /* __alpha */
-#endif
-
-/*
- * AIX defines these in sys/inttypes.h included from sys/types.h
- */
-#ifndef AIX
-#ifndef _INT16
-typedef short int16;
-#endif
-
-#ifndef _INT32
-#    if defined(__alpha) || defined(__amd64__) || defined(__x86_64__)
-typedef int int32;
-#    else  /* __alpha */
-typedef long int32;
-#    endif /* __alpha */
-#endif
-#endif
-
-#ifndef FALSE
-#define FALSE (0)
-#endif
-#ifndef TRUE
-#define TRUE (1)
-#endif
-#ifndef NULL
-#define NULL (0L)
-#endif
-
-#ifdef XP_MACOSX
-typedef enum {
-#ifndef NP_NO_QUICKDRAW
-  NPDrawingModelQuickDraw = 0,
-#endif
-  NPDrawingModelCoreGraphics = 1
-} NPDrawingModel;
-#endif
-
-typedef unsigned char	NPBool;
-typedef int16			NPError;
-typedef int16			NPReason;
-typedef char*			NPMIMEType;
-
-
-
-/*----------------------------------------------------------------------*/
-/*                       Structures and definitions                     */
-/*----------------------------------------------------------------------*/
-
-/*
- *  NPP is a plug-in's opaque instance handle
- */
-typedef struct _NPP
-{
-  void*	pdata;      /* plug-in private data */
-  void*	ndata;      /* netscape private data */
-} NPP_t;
-
-typedef NPP_t*  NPP;
-
-
-typedef struct _NPStream
-{
-  void*  pdata; /* plug-in private data */
-  void*  ndata; /* netscape private data */
-  const  char* url;
-  uint32 end;
-  uint32 lastmodified;
-  void*  notifyData;
-  const  char* headers; /* Response headers from host.
-                         * Exists only for >= NPVERS_HAS_RESPONSE_HEADERS.
-                         * Used for HTTP only; NULL for non-HTTP.
-                         * Available from NPP_NewStream onwards.
-                         * Plugin should copy this data before storing it.
-                         * Includes HTTP status line and all headers,
-                         * preferably verbatim as received from server,
-                         * headers formatted as in HTTP ("Header: Value"),
-                         * and newlines (\n, NOT \r\n) separating lines.
-                         * Terminated by \n\0 (NOT \n\n\0). */
-} NPStream;
-
-
-typedef struct _NPByteRange
-{
-  int32  offset; /* negative offset means from the end */
-  uint32 length;
-  struct _NPByteRange* next;
-} NPByteRange;
-
-
-typedef struct _NPSavedData
-{
-  int32	len;
-  void*	buf;
-} NPSavedData;
-
-
-typedef struct _NPRect
-{
-  uint16 top;
-  uint16 left;
-  uint16 bottom;
-  uint16 right;
-} NPRect;
-
-typedef struct _NPSize 
-{ 
-  int32 width; 
-  int32 height; 
-} NPSize; 
-
-#ifdef XP_UNIX
-/*
- * Unix specific structures and definitions
- */
-
-/*
- * Callback Structures.
- *
- * These are used to pass additional platform specific information.
- */
-enum {
-  NP_SETWINDOW = 1,
-  NP_PRINT
-};
-
-typedef struct
-{
-  int32 type;
-} NPAnyCallbackStruct;
-
-typedef struct
-{
-  int32        type;
-#ifdef MOZ_X11
-  Display*     display;
-  Visual*      visual;
-  Colormap     colormap;
-  unsigned int depth;
-#endif
-} NPSetWindowCallbackStruct;
-
-typedef struct
-{
-  int32 type;
-  FILE* fp;
-} NPPrintCallbackStruct;
-
-#endif /* XP_UNIX */
-
-
-/*
- *   The following masks are applied on certain platforms to NPNV and 
- *   NPPV selectors that pass around pointers to COM interfaces. Newer 
- *   compilers on some platforms may generate vtables that are not 
- *   compatible with older compilers. To prevent older plugins from 
- *   not understanding a new browser's ABI, these masks change the 
- *   values of those selectors on those platforms. To remain backwards
- *   compatible with differenet versions of the browser, plugins can 
- *   use these masks to dynamically determine and use the correct C++
- *   ABI that the browser is expecting. This does not apply to Windows 
- *   as Microsoft's COM ABI will likely not change.
- */
-
-#define NP_ABI_GCC3_MASK  0x10000000
-/*
- *   gcc 3.x generated vtables on UNIX and OSX are incompatible with 
- *   previous compilers.
- */
-#if (defined (XP_UNIX) && defined(__GNUC__) && (__GNUC__ >= 3))
-#define _NP_ABI_MIXIN_FOR_GCC3 NP_ABI_GCC3_MASK
-#else
-#define _NP_ABI_MIXIN_FOR_GCC3 0
-#endif
-
-
-#define NP_ABI_MACHO_MASK 0x01000000
-/*
- *   On OSX, the Mach-O executable format is significantly
- *   different than CFM. In addition to having a different
- *   C++ ABI, it also has has different C calling convention.
- *   You must use glue code when calling between CFM and
- *   Mach-O C functions. 
- */
-#if (defined(TARGET_RT_MAC_MACHO))
-#define _NP_ABI_MIXIN_FOR_MACHO NP_ABI_MACHO_MASK
-#else
-#define _NP_ABI_MIXIN_FOR_MACHO 0
-#endif
-
-
-#define NP_ABI_MASK (_NP_ABI_MIXIN_FOR_GCC3 | _NP_ABI_MIXIN_FOR_MACHO)
-
-/*
- * List of variable names for which NPP_GetValue shall be implemented
- */
-typedef enum {
-  NPPVpluginNameString = 1,
-  NPPVpluginDescriptionString,
-  NPPVpluginWindowBool,
-  NPPVpluginTransparentBool,
-  NPPVjavaClass,                /* Not implemented in Mozilla 1.0 */
-  NPPVpluginWindowSize,
-  NPPVpluginTimerInterval,
-
-  NPPVpluginScriptableInstance = (10 | NP_ABI_MASK),
-  NPPVpluginScriptableIID = 11,
-
-  /* Introduced in Mozilla 0.9.9 */
-  NPPVjavascriptPushCallerBool = 12,
-
-  /* Introduced in Mozilla 1.0 */
-  NPPVpluginKeepLibraryInMemory = 13,
-  NPPVpluginNeedsXEmbed         = 14,
-
-  /* Get the NPObject for scripting the plugin. Introduced in Firefox
-   * 1.0 (NPAPI minor version 14).
-   */
-  NPPVpluginScriptableNPObject  = 15,
-
-  /* Get the plugin value (as \0-terminated UTF-8 string data) for
-   * form submission if the plugin is part of a form. Use
-   * NPN_MemAlloc() to allocate memory for the string data. Introduced
-   * in Mozilla 1.8b2 (NPAPI minor version 15).
-   */
-  NPPVformValue = 16
-#ifdef XP_MACOSX
-  /* Used for negotiating drawing models */
-  , NPPVpluginDrawingModel = 1000
-#endif
-} NPPVariable;
-
-/*
- * List of variable names for which NPN_GetValue is implemented by Mozilla
- */
-typedef enum {
-  NPNVxDisplay = 1,
-  NPNVxtAppContext,
-  NPNVnetscapeWindow,
-  NPNVjavascriptEnabledBool,
-  NPNVasdEnabledBool,
-  NPNVisOfflineBool,
-
-  /* 10 and over are available on Mozilla builds starting with 0.9.4 */
-  NPNVserviceManager = (10 | NP_ABI_MASK),
-  NPNVDOMElement     = (11 | NP_ABI_MASK),   /* available in Mozilla 1.2 */
-  NPNVDOMWindow      = (12 | NP_ABI_MASK),
-  NPNVToolkit        = (13 | NP_ABI_MASK),
-  NPNVSupportsXEmbedBool = 14,
-
-  /* Get the NPObject wrapper for the browser window. */
-  NPNVWindowNPObject = 15,
-
-  /* Get the NPObject wrapper for the plugins DOM element. */
-  NPNVPluginElementNPObject = 16,
-
-  NPNVSupportsWindowless = 17
-
-#ifdef XP_MACOSX
-  /* Used for negotiating drawing models */
-  , NPNVpluginDrawingModel = 1000
-#ifndef NP_NO_QUICKDRAW
-  , NPNVsupportsQuickDrawBool = 2000
-#endif
-  , NPNVsupportsCoreGraphicsBool = 2001
-#endif
-} NPNVariable;
-
-/*
- * The type of Tookkit the widgets use
- */
-typedef enum {
-  NPNVGtk12 = 1,
-  NPNVGtk2
-} NPNToolkitType;
-
-/*
- * The type of a NPWindow - it specifies the type of the data structure
- * returned in the window field.
- */
-typedef enum {
-  NPWindowTypeWindow = 1,
-  NPWindowTypeDrawable
-} NPWindowType;
-
-typedef struct _NPWindow
-{
-  void* window;  /* Platform specific window handle */
-                 /* OS/2: x - Position of bottom left corner  */
-                 /* OS/2: y - relative to visible netscape window */
-  int32 x;       /* Position of top left corner relative */
-  int32 y;       /* to a netscape page.					*/
-  uint32 width;  /* Maximum window size */
-  uint32 height;
-  NPRect clipRect; /* Clipping rectangle in port coordinates */
-                   /* Used by MAC only.			  */
-#if defined(XP_UNIX) && !defined(XP_MACOSX)
-  void * ws_info; /* Platform-dependent additonal data */
-#endif /* XP_UNIX */
-  NPWindowType type; /* Is this a window or a drawable? */
-} NPWindow;
-
-
-typedef struct _NPFullPrint
-{
-  NPBool pluginPrinted;/* Set TRUE if plugin handled fullscreen printing */
-  NPBool printOne;		 /* TRUE if plugin should print one copy to default printer */
-  void* platformPrint; /* Platform-specific printing info */
-} NPFullPrint;
-
-typedef struct _NPEmbedPrint
-{
-  NPWindow window;
-  void* platformPrint; /* Platform-specific printing info */
-} NPEmbedPrint;
-
-typedef struct _NPPrint
-{
-  uint16 mode;               /* NP_FULL or NP_EMBED */
-  union
-  {
-    NPFullPrint fullPrint;   /* if mode is NP_FULL */
-    NPEmbedPrint embedPrint; /* if mode is NP_EMBED */
-  } print;
-} NPPrint;
-
-#ifdef XP_MACOSX
-typedef EventRecord	NPEvent;
-#elif defined(XP_WIN)
-typedef struct _NPEvent
-{
-  uint16 event;
-  uint32 wParam;
-  uint32 lParam;
-} NPEvent;
-#elif defined(XP_OS2)
-typedef struct _NPEvent
-{
-  uint32 event;
-  uint32 wParam;
-  uint32 lParam;
-} NPEvent;
-#elif defined (XP_UNIX) && defined(MOZ_X11)
-typedef XEvent NPEvent;
-#else
-typedef void*			NPEvent;
-#endif /* XP_MACOSX */
-
-#ifdef XP_MACOSX
-typedef void* NPRegion;
-#ifndef NP_NO_QUICKDRAW
-typedef RgnHandle NPQDRegion;
-#endif
-typedef CGPathRef NPCGRegion;
-#elif defined(XP_WIN)
-typedef HRGN NPRegion;
-#elif defined(XP_UNIX) && defined(MOZ_X11)
-typedef Region NPRegion;
-#else
-typedef void *NPRegion;
-#endif /* XP_MACOSX */
-
-#ifdef XP_MACOSX
-/*
- *  Mac-specific structures and definitions.
- */
-
-typedef struct NP_Port
-{
-  CGrafPtr port; /* Grafport */
-  int32 portx;   /* position inside the topmost window */
-  int32 porty;
-} NP_Port;
-
-typedef struct NP_CGContext
-{
-  CGContextRef context;
-  WindowRef window;
-} NP_CGContext;
-
-/*
- *  Non-standard event types that can be passed to HandleEvent
- */
-
-enum NPEventType {
-  NPEventType_GetFocusEvent = (osEvt + 16),
-  NPEventType_LoseFocusEvent,
-  NPEventType_AdjustCursorEvent,
-  NPEventType_MenuCommandEvent,
-  NPEventType_ClippingChangedEvent,
-  NPEventType_ScrollingBeginsEvent = 1000,
-  NPEventType_ScrollingEndsEvent
-};
-
-#ifdef OBSOLETE
-#define getFocusEvent     (osEvt + 16)
-#define loseFocusEvent    (osEvt + 17)
-#define adjustCursorEvent (osEvt + 18)
-#endif
-#endif /* XP_MACOSX */
-
-/*
- * Values for mode passed to NPP_New:
- */
-#define NP_EMBED 1
-#define NP_FULL  2
-
-/*
- * Values for stream type passed to NPP_NewStream:
- */
-#define NP_NORMAL     1
-#define NP_SEEK       2
-#define NP_ASFILE     3
-#define NP_ASFILEONLY 4
-
-#define NP_MAXREADY	(((unsigned)(~0)<<1)>>1)
-
-
-/*----------------------------------------------------------------------*/
-/*		     Error and Reason Code definitions			*/
-/*----------------------------------------------------------------------*/
-
-/*
- * Values of type NPError:
- */
-#define NPERR_BASE                         0
-#define NPERR_NO_ERROR                    (NPERR_BASE + 0)
-#define NPERR_GENERIC_ERROR               (NPERR_BASE + 1)
-#define NPERR_INVALID_INSTANCE_ERROR      (NPERR_BASE + 2)
-#define NPERR_INVALID_FUNCTABLE_ERROR     (NPERR_BASE + 3)
-#define NPERR_MODULE_LOAD_FAILED_ERROR    (NPERR_BASE + 4)
-#define NPERR_OUT_OF_MEMORY_ERROR         (NPERR_BASE + 5)
-#define NPERR_INVALID_PLUGIN_ERROR        (NPERR_BASE + 6)
-#define NPERR_INVALID_PLUGIN_DIR_ERROR    (NPERR_BASE + 7)
-#define NPERR_INCOMPATIBLE_VERSION_ERROR  (NPERR_BASE + 8)
-#define NPERR_INVALID_PARAM               (NPERR_BASE + 9)
-#define NPERR_INVALID_URL                 (NPERR_BASE + 10)
-#define NPERR_FILE_NOT_FOUND              (NPERR_BASE + 11)
-#define NPERR_NO_DATA                     (NPERR_BASE + 12)
-#define NPERR_STREAM_NOT_SEEKABLE         (NPERR_BASE + 13)
-
-/*
- * Values of type NPReason:
- */
-#define NPRES_BASE          0
-#define NPRES_DONE         (NPRES_BASE + 0)
-#define NPRES_NETWORK_ERR  (NPRES_BASE + 1)
-#define NPRES_USER_BREAK   (NPRES_BASE + 2)
-
-/*
- * Don't use these obsolete error codes any more.
- */
-#define NP_NOERR  NP_NOERR_is_obsolete_use_NPERR_NO_ERROR
-#define NP_EINVAL NP_EINVAL_is_obsolete_use_NPERR_GENERIC_ERROR
-#define NP_EABORT NP_EABORT_is_obsolete_use_NPRES_USER_BREAK
-
-/*
- * Version feature information
- */
-#define NPVERS_HAS_STREAMOUTPUT             8
-#define NPVERS_HAS_NOTIFICATION             9
-#define NPVERS_HAS_LIVECONNECT              9
-#define NPVERS_WIN16_HAS_LIVECONNECT        9
-#define NPVERS_68K_HAS_LIVECONNECT          11
-#define NPVERS_HAS_WINDOWLESS               11
-#define NPVERS_HAS_XPCONNECT_SCRIPTING      13
-#define NPVERS_HAS_NPRUNTIME_SCRIPTING      14
-#define NPVERS_HAS_FORM_VALUES              15
-#define NPVERS_HAS_POPUPS_ENABLED_STATE     16
-#define NPVERS_HAS_RESPONSE_HEADERS         17
-#define NPVERS_HAS_NPOBJECT_ENUM            18
-#define NPVERS_HAS_PLUGIN_THREAD_ASYNC_CALL 19
-
-/*----------------------------------------------------------------------*/
-/*                        Function Prototypes                           */
-/*----------------------------------------------------------------------*/
-
-#if defined(_WINDOWS) && !defined(WIN32)
-#define NP_LOADDS  _loadds
-#else
-#if defined(__OS2__)
-#define NP_LOADDS _System
-#else
-#define NP_LOADDS
-#endif
-#endif
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/*
- * NPP_* functions are provided by the plugin and called by the navigator.
- */
-
-#ifdef XP_UNIX
-char* NPP_GetMIMEDescription(void);
-#endif /* XP_UNIX */
-
-NPError NP_LOADDS NPP_Initialize(void);
-void    NP_LOADDS NPP_Shutdown(void);
-NPError NP_LOADDS NPP_New(NPMIMEType pluginType, NPP instance,
-                          uint16 mode, int16 argc, char* argn[],
-                          char* argv[], NPSavedData* saved);
-NPError NP_LOADDS NPP_Destroy(NPP instance, NPSavedData** save);
-NPError NP_LOADDS NPP_SetWindow(NPP instance, NPWindow* window);
-NPError NP_LOADDS NPP_NewStream(NPP instance, NPMIMEType type,
-                                NPStream* stream, NPBool seekable,
-                                uint16* stype);
-NPError NP_LOADDS NPP_DestroyStream(NPP instance, NPStream* stream,
-                                    NPReason reason);
-int32   NP_LOADDS NPP_WriteReady(NPP instance, NPStream* stream);
-int32   NP_LOADDS NPP_Write(NPP instance, NPStream* stream, int32 offset,
-                            int32 len, void* buffer);
-void    NP_LOADDS NPP_StreamAsFile(NPP instance, NPStream* stream,
-                                   const char* fname);
-void    NP_LOADDS NPP_Print(NPP instance, NPPrint* platformPrint);
-int16   NP_LOADDS NPP_HandleEvent(NPP instance, void* event);
-void    NP_LOADDS NPP_URLNotify(NPP instance, const char* url,
-                                NPReason reason, void* notifyData);
-#ifdef OJI
-jref    NP_LOADDS NPP_GetJavaClass(void);
-#endif
-NPError NP_LOADDS NPP_GetValue(NPP instance, NPPVariable variable, void *value);
-NPError NP_LOADDS NPP_SetValue(NPP instance, NPNVariable variable, void *value);
-
-/*
- * NPN_* functions are provided by the navigator and called by the plugin.
- */
-void    NP_LOADDS NPN_Version(int* plugin_major, int* plugin_minor,
-                              int* netscape_major, int* netscape_minor);
-NPError NP_LOADDS NPN_GetURLNotify(NPP instance, const char* url,
-                                   const char* target, void* notifyData);
-NPError NP_LOADDS NPN_GetURL(NPP instance, const char* url,
-                             const char* target);
-NPError NP_LOADDS NPN_PostURLNotify(NPP instance, const char* url,
-                                    const char* target, uint32 len,
-                                    const char* buf, NPBool file,
-                                    void* notifyData);
-NPError NP_LOADDS NPN_PostURL(NPP instance, const char* url,
-                              const char* target, uint32 len,
-                              const char* buf, NPBool file);
-NPError NP_LOADDS NPN_RequestRead(NPStream* stream, NPByteRange* rangeList);
-NPError NP_LOADDS NPN_NewStream(NPP instance, NPMIMEType type,
-                                const char* target, NPStream** stream);
-int32   NP_LOADDS NPN_Write(NPP instance, NPStream* stream, int32 len, void* buffer);
-NPError NP_LOADDS NPN_DestroyStream(NPP instance, NPStream* stream, NPReason reason);
-void    NP_LOADDS NPN_Status(NPP instance, const char* message);
-const char* NP_LOADDS	NPN_UserAgent(NPP instance);
-void*   NP_LOADDS NPN_MemAlloc(uint32 size);
-void    NP_LOADDS NPN_MemFree(void* ptr);
-uint32  NP_LOADDS NPN_MemFlush(uint32 size);
-void    NP_LOADDS NPN_ReloadPlugins(NPBool reloadPages);
-#ifdef OJI
-JRIEnv* NP_LOADDS NPN_GetJavaEnv(void);
-jref    NP_LOADDS NPN_GetJavaPeer(NPP instance);
-#endif
-NPError NP_LOADDS NPN_GetValue(NPP instance, NPNVariable variable, void *value);
-NPError NP_LOADDS NPN_SetValue(NPP instance, NPPVariable variable, void *value);
-void    NP_LOADDS NPN_InvalidateRect(NPP instance, NPRect *invalidRect);
-void    NP_LOADDS NPN_InvalidateRegion(NPP instance, NPRegion invalidRegion);
-void    NP_LOADDS NPN_ForceRedraw(NPP instance);
-void    NP_LOADDS NPN_PushPopupsEnabledState(NPP instance, NPBool enabled);
-void    NP_LOADDS NPN_PopPopupsEnabledState(NPP instance);
-void    NP_LOADDS NPN_PluginThreadAsyncCall(NPP instance,
-                                            void (*func) (void *),
-                                            void *userData);
-
-#ifdef __cplusplus
-}  /* end extern "C" */
-#endif
-
-#endif /* RC_INVOKED */
-#ifdef __OS2__
-#pragma pack()
-#endif
-
-#endif /* _NPAPI_H_ */
diff -r fcf435874395 -r 45c889eae324 front_idill/extern/fajran-npTuioClient/npapi/npruntime.h
--- a/front_idill/extern/fajran-npTuioClient/npapi/npruntime.h	Thu Apr 19 11:53:06 2012 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,423 +0,0 @@
-/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
-/*
- * Copyright © 2004, Apple Computer, Inc. and The Mozilla Foundation. 
- * All rights reserved.
- * 
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- * 
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the names of Apple Computer, Inc. ("Apple") or The Mozilla
- * Foundation ("Mozilla") nor the names of their contributors may be used
- * to endorse or promote products derived from this software without
- * specific prior written permission.
- * 
- * THIS SOFTWARE IS PROVIDED BY APPLE, MOZILLA AND THEIR CONTRIBUTORS "AS
- * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
- * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
- * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE, MOZILLA OR
- * THEIR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
- * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
- * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * Revision 1 (March 4, 2004):
- * Initial proposal.
- *
- * Revision 2 (March 10, 2004):
- * All calls into script were made asynchronous.  Results are
- * provided via the NPScriptResultFunctionPtr callback.
- *
- * Revision 3 (March 10, 2004):
- * Corrected comments to not refer to class retain/release FunctionPtrs.
- *
- * Revision 4 (March 11, 2004):
- * Added additional convenience NPN_SetExceptionWithUTF8().
- * Changed NPHasPropertyFunctionPtr and NPHasMethodFunctionPtr to take NPClass
- * pointers instead of NPObject pointers.
- * Added NPIsValidIdentifier().
- *
- * Revision 5 (March 17, 2004):
- * Added context parameter to result callbacks from ScriptObject functions.
- *
- * Revision 6 (March 29, 2004):
- * Renamed functions implemented by user agent to NPN_*.  Removed _ from
- * type names.
- * Renamed "JavaScript" types to "Script".
- *
- * Revision 7 (April 21, 2004):
- * NPIdentifier becomes a void*, was int32_t
- * Remove NP_IsValidIdentifier, renamed NP_IdentifierFromUTF8 to NP_GetIdentifier
- * Added NPVariant and modified functions to use this new type.
- *
- * Revision 8 (July 9, 2004):
- * Updated to joint Apple-Mozilla license.
- *
- */
-#ifndef _NP_RUNTIME_H_
-#define _NP_RUNTIME_H_
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#include "nptypes.h"
-
-/*
-    This API is used to facilitate binding code written in C to script
-    objects.  The API in this header does not assume the presence of a
-    user agent.  That is, it can be used to bind C code to scripting
-    environments outside of the context of a user agent.
-    
-    However, the normal use of the this API is in the context of a
-    scripting environment running in a browser or other user agent.
-    In particular it is used to support the extended Netscape
-    script-ability API for plugins (NP-SAP).  NP-SAP is an extension
-    of the Netscape plugin API.  As such we have adopted the use of
-    the "NP" prefix for this API.
-
-    The following NP{N|P}Variables were added to the Netscape plugin
-    API (in npapi.h):
-
-    NPNVWindowNPObject
-    NPNVPluginElementNPObject
-    NPPVpluginScriptableNPObject
-
-    These variables are exposed through NPN_GetValue() and
-    NPP_GetValue() (respectively) and are used to establish the
-    initial binding between the user agent and native code.  The DOM
-    objects in the user agent can be examined and manipulated using
-    the NPN_ functions that operate on NPObjects described in this
-    header.
-
-    To the extent possible the assumptions about the scripting
-    language used by the scripting environment have been minimized.
-*/
-
-#define NP_BEGIN_MACRO  do {
-#define NP_END_MACRO    } while (0)
-
-/*
-    Objects (non-primitive data) passed between 'C' and script is
-    always wrapped in an NPObject.  The 'interface' of an NPObject is
-    described by an NPClass.
-*/
-typedef struct NPObject NPObject;
-typedef struct NPClass NPClass;
-
-typedef char NPUTF8;
-typedef struct _NPString {
-    const NPUTF8 *utf8characters;
-    uint32_t utf8length;
-} NPString;
-
-typedef enum {
-    NPVariantType_Void,
-    NPVariantType_Null,
-    NPVariantType_Bool,
-    NPVariantType_Int32,
-    NPVariantType_Double,
-    NPVariantType_String,
-    NPVariantType_Object
-} NPVariantType;
-
-typedef struct _NPVariant {
-    NPVariantType type;
-    union {
-        bool boolValue;
-        int32_t intValue;
-        double doubleValue;
-        NPString stringValue;
-        NPObject *objectValue;
-    } value;
-} NPVariant;
-
-/*
-    NPN_ReleaseVariantValue is called on all 'out' parameters
-    references.  Specifically it is to be called on variants that own
-    their value, as is the case with all non-const NPVariant*
-    arguments after a successful call to any methods (except this one)
-    in this API.
-
-    After calling NPN_ReleaseVariantValue, the type of the variant
-    will be NPVariantType_Void.
-*/
-void NPN_ReleaseVariantValue(NPVariant *variant);
-
-#define NPVARIANT_IS_VOID(_v)    ((_v).type == NPVariantType_Void)
-#define NPVARIANT_IS_NULL(_v)    ((_v).type == NPVariantType_Null)
-#define NPVARIANT_IS_BOOLEAN(_v) ((_v).type == NPVariantType_Bool)
-#define NPVARIANT_IS_INT32(_v)   ((_v).type == NPVariantType_Int32)
-#define NPVARIANT_IS_DOUBLE(_v)  ((_v).type == NPVariantType_Double)
-#define NPVARIANT_IS_STRING(_v)  ((_v).type == NPVariantType_String)
-#define NPVARIANT_IS_OBJECT(_v)  ((_v).type == NPVariantType_Object)
-
-#define NPVARIANT_TO_BOOLEAN(_v) ((_v).value.boolValue)
-#define NPVARIANT_TO_INT32(_v)   ((_v).value.intValue)
-#define NPVARIANT_TO_DOUBLE(_v)  ((_v).value.doubleValue)
-#define NPVARIANT_TO_STRING(_v)  ((_v).value.stringValue)
-#define NPVARIANT_TO_OBJECT(_v)  ((_v).value.objectValue)
-
-#define VOID_TO_NPVARIANT(_v)                                                 \
-NP_BEGIN_MACRO                                                                \
-    (_v).type = NPVariantType_Void;                                           \
-    (_v).value.objectValue = NULL;                                            \
-NP_END_MACRO
-
-#define NULL_TO_NPVARIANT(_v)                                                 \
-NP_BEGIN_MACRO                                                                \
-    (_v).type = NPVariantType_Null;                                           \
-    (_v).value.objectValue = NULL;                                            \
-NP_END_MACRO
-
-#define BOOLEAN_TO_NPVARIANT(_val, _v)                                        \
-NP_BEGIN_MACRO                                                                \
-    (_v).type = NPVariantType_Bool;                                           \
-    (_v).value.boolValue = !!(_val);                                          \
-NP_END_MACRO
-
-#define INT32_TO_NPVARIANT(_val, _v)                                          \
-NP_BEGIN_MACRO                                                                \
-    (_v).type = NPVariantType_Int32;                                          \
-    (_v).value.intValue = _val;                                               \
-NP_END_MACRO
-
-#define DOUBLE_TO_NPVARIANT(_val, _v)                                         \
-NP_BEGIN_MACRO                                                                \
-    (_v).type = NPVariantType_Double;                                         \
-    (_v).value.doubleValue = _val;                                            \
-NP_END_MACRO
-
-#define STRINGZ_TO_NPVARIANT(_val, _v)                                        \
-NP_BEGIN_MACRO                                                                \
-    (_v).type = NPVariantType_String;                                         \
-    NPString str = { _val, strlen(_val) };                                    \
-    (_v).value.stringValue = str;                                             \
-NP_END_MACRO
-
-#define STRINGN_TO_NPVARIANT(_val, _len, _v)                                  \
-NP_BEGIN_MACRO                                                                \
-    (_v).type = NPVariantType_String;                                         \
-    NPString str = { _val, _len };                                            \
-    (_v).value.stringValue = str;                                             \
-NP_END_MACRO
-
-#define OBJECT_TO_NPVARIANT(_val, _v)                                         \
-NP_BEGIN_MACRO                                                                \
-    (_v).type = NPVariantType_Object;                                         \
-    (_v).value.objectValue = _val;                                            \
-NP_END_MACRO
-
-
-/*
-	Type mappings (JavaScript types have been used for illustration
-    purposes):
-
-	JavaScript       to             C (NPVariant with type:)
-	undefined                       NPVariantType_Void
-	null                            NPVariantType_Null
-	Boolean                         NPVariantType_Bool
-	Number                          NPVariantType_Double or NPVariantType_Int32
-	String                          NPVariantType_String
-	Object                          NPVariantType_Object
-
-	C (NPVariant with type:)   to   JavaScript
-	NPVariantType_Void              undefined
-	NPVariantType_Null              null
-	NPVariantType_Bool              Boolean	
-	NPVariantType_Int32             Number
-	NPVariantType_Double            Number
-	NPVariantType_String            String
-	NPVariantType_Object            Object
-*/
-
-typedef void *NPIdentifier;
-
-/*
-    NPObjects have methods and properties.  Methods and properties are
-    identified with NPIdentifiers.  These identifiers may be reflected
-    in script.  NPIdentifiers can be either strings or integers, IOW,
-    methods and properties can be identified by either strings or
-    integers (i.e. foo["bar"] vs foo[1]). NPIdentifiers can be
-    compared using ==.  In case of any errors, the requested
-    NPIdentifier(s) will be NULL.
-*/
-NPIdentifier NPN_GetStringIdentifier(const NPUTF8 *name);
-void NPN_GetStringIdentifiers(const NPUTF8 **names, int32_t nameCount,
-                              NPIdentifier *identifiers);
-NPIdentifier NPN_GetIntIdentifier(int32_t intid);
-bool NPN_IdentifierIsString(NPIdentifier identifier);
-
-/*
-    The NPUTF8 returned from NPN_UTF8FromIdentifier SHOULD be freed.
-*/
-NPUTF8 *NPN_UTF8FromIdentifier(NPIdentifier identifier);
-
-/*
-    Get the integer represented by identifier. If identifier is not an
-    integer identifier, the behaviour is undefined.
-*/
-int32_t NPN_IntFromIdentifier(NPIdentifier identifier);
-
-/*
-    NPObject behavior is implemented using the following set of
-    callback functions.
-
-    The NPVariant *result argument of these functions (where
-    applicable) should be released using NPN_ReleaseVariantValue().
-*/
-typedef NPObject *(*NPAllocateFunctionPtr)(NPP npp, NPClass *aClass);
-typedef void (*NPDeallocateFunctionPtr)(NPObject *npobj);
-typedef void (*NPInvalidateFunctionPtr)(NPObject *npobj);
-typedef bool (*NPHasMethodFunctionPtr)(NPObject *npobj, NPIdentifier name);
-typedef bool (*NPInvokeFunctionPtr)(NPObject *npobj, NPIdentifier name,
-                                    const NPVariant *args, uint32_t argCount,
-                                    NPVariant *result);
-typedef bool (*NPInvokeDefaultFunctionPtr)(NPObject *npobj,
-                                           const NPVariant *args,
-                                           uint32_t argCount,
-                                           NPVariant *result);
-typedef bool (*NPHasPropertyFunctionPtr)(NPObject *npobj, NPIdentifier name);
-typedef bool (*NPGetPropertyFunctionPtr)(NPObject *npobj, NPIdentifier name,
-                                         NPVariant *result);
-typedef bool (*NPSetPropertyFunctionPtr)(NPObject *npobj, NPIdentifier name,
-                                         const NPVariant *value);
-typedef bool (*NPRemovePropertyFunctionPtr)(NPObject *npobj,
-                                            NPIdentifier name);
-typedef bool (*NPEnumerationFunctionPtr)(NPObject *npobj, NPIdentifier **value,
-                                         uint32_t *count);
-typedef bool (*NPConstructFunctionPtr)(NPObject *npobj,
-                                       const NPVariant *args,
-                                       uint32_t argCount,
-                                       NPVariant *result);
-
-/*
-    NPObjects returned by create, retain, invoke, and getProperty pass
-    a reference count to the caller.  That is, the callee adds a
-    reference count which passes to the caller.  It is the caller's
-    responsibility to release the returned object.
-
-    NPInvokeFunctionPtr function may return 0 to indicate a void
-    result.
-
-    NPInvalidateFunctionPtr is called by the scripting environment
-    when the native code is shutdown.  Any attempt to message a
-    NPObject instance after the invalidate callback has been
-    called will result in undefined behavior, even if the native code
-    is still retaining those NPObject instances.  (The runtime
-    will typically return immediately, with 0 or NULL, from an attempt
-    to dispatch to a NPObject, but this behavior should not be
-    depended upon.)
-
-    The NPEnumerationFunctionPtr function may pass an array of
-    NPIdentifiers back to the caller. The callee allocs the memory of
-    the array using NPN_MemAlloc(), and it's the caller's responsibility
-    to release it using NPN_MemFree().
-*/
-struct NPClass
-{
-    uint32_t structVersion;
-    NPAllocateFunctionPtr allocate;
-    NPDeallocateFunctionPtr deallocate;
-    NPInvalidateFunctionPtr invalidate;
-    NPHasMethodFunctionPtr hasMethod;
-    NPInvokeFunctionPtr invoke;
-    NPInvokeDefaultFunctionPtr invokeDefault;
-    NPHasPropertyFunctionPtr hasProperty;
-    NPGetPropertyFunctionPtr getProperty;
-    NPSetPropertyFunctionPtr setProperty;
-    NPRemovePropertyFunctionPtr removeProperty;
-    NPEnumerationFunctionPtr enumerate;
-    NPConstructFunctionPtr construct;
-};
-
-#define NP_CLASS_STRUCT_VERSION      3
-
-#define NP_CLASS_STRUCT_VERSION_ENUM 2
-#define NP_CLASS_STRUCT_VERSION_CTOR 3
-
-#define NP_CLASS_STRUCT_VERSION_HAS_ENUM(npclass)   \
-        ((npclass)->structVersion >= NP_CLASS_STRUCT_VERSION_ENUM)
-
-#define NP_CLASS_STRUCT_VERSION_HAS_CTOR(npclass)   \
-        ((npclass)->structVersion >= NP_CLASS_STRUCT_VERSION_CTOR)
-
-struct NPObject {
-    NPClass *_class;
-    uint32_t referenceCount;
-    /*
-     * Additional space may be allocated here by types of NPObjects
-     */
-};
-
-/*
-    If the class has an allocate function, NPN_CreateObject invokes
-    that function, otherwise a NPObject is allocated and
-    returned. This method will initialize the referenceCount member of
-    the NPObject to 1.
-*/
-NPObject *NPN_CreateObject(NPP npp, NPClass *aClass);
-
-/*
-    Increment the NPObject's reference count.
-*/
-NPObject *NPN_RetainObject(NPObject *npobj);
-
-/*
-    Decremented the NPObject's reference count.  If the reference
-    count goes to zero, the class's destroy function is invoke if
-    specified, otherwise the object is freed directly.
-*/
-void NPN_ReleaseObject(NPObject *npobj);
-
-/*
-    Functions to access script objects represented by NPObject.
-
-    Calls to script objects are synchronous.  If a function returns a
-    value, it will be supplied via the result NPVariant
-    argument. Successful calls will return true, false will be
-    returned in case of an error.
-    
-    Calls made from plugin code to script must be made from the thread
-    on which the plugin was initialized.
-*/
-
-bool NPN_Invoke(NPP npp, NPObject *npobj, NPIdentifier methodName,
-                const NPVariant *args, uint32_t argCount, NPVariant *result);
-bool NPN_InvokeDefault(NPP npp, NPObject *npobj, const NPVariant *args,
-                       uint32_t argCount, NPVariant *result);
-bool NPN_Evaluate(NPP npp, NPObject *npobj, NPString *script,
-                  NPVariant *result);
-bool NPN_GetProperty(NPP npp, NPObject *npobj, NPIdentifier propertyName,
-                     NPVariant *result);
-bool NPN_SetProperty(NPP npp, NPObject *npobj, NPIdentifier propertyName,
-                     const NPVariant *value);
-bool NPN_RemoveProperty(NPP npp, NPObject *npobj, NPIdentifier propertyName);
-bool NPN_HasProperty(NPP npp, NPObject *npobj, NPIdentifier propertyName);
-bool NPN_HasMethod(NPP npp, NPObject *npobj, NPIdentifier methodName);
-bool NPN_Enumerate(NPP npp, NPObject *npobj, NPIdentifier **identifier,
-                   uint32_t *count);
-bool NPN_Construct(NPP npp, NPObject *npobj, const NPVariant *args,
-                   uint32_t argCount, NPVariant *result);
-
-/*
-    NPN_SetException may be called to trigger a script exception upon
-    return from entry points into NPObjects.  Typical usage:
-
-    NPN_SetException (npobj, message);
-*/
-void NPN_SetException(NPObject *npobj, const NPUTF8 *message);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif
diff -r fcf435874395 -r 45c889eae324 front_idill/extern/fajran-npTuioClient/npapi/nptypes.h
--- a/front_idill/extern/fajran-npTuioClient/npapi/nptypes.h	Thu Apr 19 11:53:06 2012 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,105 +0,0 @@
-/* -*- Mode: C; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* ***** BEGIN LICENSE BLOCK *****
- * Version: MPL 1.1/GPL 2.0/LGPL 2.1
- *
- * The contents of this file are subject to the Mozilla Public License Version
- * 1.1 (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- * http://www.mozilla.org/MPL/
- *
- * Software distributed under the License is distributed on an "AS IS" basis,
- * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
- * for the specific language governing rights and limitations under the
- * License.
- *
- * The Original Code is mozilla.org code.
- *
- * The Initial Developer of the Original Code is
- * mozilla.org.
- * Portions created by the Initial Developer are Copyright (C) 2004
- * the Initial Developer. All Rights Reserved.
- *
- * Contributor(s):
- *   Johnny Stenback  (Original author)
- *
- * Alternatively, the contents of this file may be used under the terms of
- * either the GNU General Public License Version 2 or later (the "GPL"), or
- * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
- * in which case the provisions of the GPL or the LGPL are applicable instead
- * of those above. If you wish to allow use of your version of this file only
- * under the terms of either the GPL or the LGPL, and not to allow others to
- * use your version of this file under the terms of the MPL, indicate your
- * decision by deleting the provisions above and replace them with the notice
- * and other provisions required by the GPL or the LGPL. If you do not delete
- * the provisions above, a recipient may use your version of this file under
- * the terms of any one of the MPL, the GPL or the LGPL.
- *
- * ***** END LICENSE BLOCK ***** */
-
-/*
- * Header file for ensuring that C99 types ([u]int32_t and bool) are
- * available.
- */
-
-#if defined(WIN32) || defined(OS2)
-  /*
-   * Win32 and OS/2 don't know C99, so define [u]int_32 here. The bool
-   * is predefined tho, both in C and C++.
-   */
-  typedef int int32_t;
-  typedef unsigned int uint32_t;
-#elif defined(_AIX) || defined(__sun) || defined(__osf__) || defined(IRIX) || defined(HPUX)
-  /*
-   * AIX and SunOS ship a inttypes.h header that defines [u]int32_t,
-   * but not bool for C.
-   */
-  #include 
-
-  #ifndef __cplusplus
-    typedef int bool;
-  #endif
-#elif defined(bsdi) || defined(FREEBSD) || defined(OPENBSD)
-  /*
-   * BSD/OS, FreeBSD, and OpenBSD ship sys/types.h that define int32_t and 
-   * u_int32_t.
-   */
-  #include 
-
-  /*
-   * BSD/OS ships no header that defines uint32_t, nor bool (for C)
-   */
-  #if defined(bsdi)
-  typedef u_int32_t uint32_t;
-
-  #if !defined(__cplusplus)
-    typedef int bool;
-  #endif
-  #else
-  /*
-   * FreeBSD and OpenBSD define uint32_t and bool.
-   */
-    #include 
-    #include 
-  #endif
-#elif defined(BEOS)
-  #include 
-#else
-  /*
-   * For those that ship a standard C99 stdint.h header file, include
-   * it. Can't do the same for stdbool.h tho, since some systems ship
-   * with a stdbool.h file that doesn't compile!
-   */
-  #include 
-
-  #ifndef __cplusplus
-    #if !defined(__GNUC__) || (__GNUC__ > 2 || __GNUC_MINOR__ > 95)
-      #include 
-    #else
-      /*
-       * GCC 2.91 can't deal with a typedef for bool, but a #define
-       * works.
-       */
-      #define bool int
-    #endif
-  #endif
-#endif
diff -r fcf435874395 -r 45c889eae324 front_idill/extern/fajran-npTuioClient/npapi/npupp.h
--- a/front_idill/extern/fajran-npTuioClient/npapi/npupp.h	Thu Apr 19 11:53:06 2012 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,722 +0,0 @@
-/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
-/* ***** BEGIN LICENSE BLOCK *****
- * Version: MPL 1.1/GPL 2.0/LGPL 2.1
- *
- * The contents of this file are subject to the Mozilla Public License Version
- * 1.1 (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- * http://www.mozilla.org/MPL/
- *
- * Software distributed under the License is distributed on an "AS IS" basis,
- * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
- * for the specific language governing rights and limitations under the
- * License.
- *
- * The Original Code is mozilla.org code.
- *
- * The Initial Developer of the Original Code is
- * Netscape Communications Corporation.
- * Portions created by the Initial Developer are Copyright (C) 1998
- * the Initial Developer. All Rights Reserved.
- *
- * Contributor(s):
- *
- * Alternatively, the contents of this file may be used under the terms of
- * either the GNU General Public License Version 2 or later (the "GPL"), or
- * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
- * in which case the provisions of the GPL or the LGPL are applicable instead
- * of those above. If you wish to allow use of your version of this file only
- * under the terms of either the GPL or the LGPL, and not to allow others to
- * use your version of this file under the terms of the MPL, indicate your
- * decision by deleting the provisions above and replace them with the notice
- * and other provisions required by the GPL or the LGPL. If you do not delete
- * the provisions above, a recipient may use your version of this file under
- * the terms of any one of the MPL, the GPL or the LGPL.
- *
- * ***** END LICENSE BLOCK ***** */
-
-
-/*
- *  npupp.h $Revision: 3.26 $
- *  function call mecahnics needed by platform specific glue code.
- */
-
-
-#ifndef _NPUPP_H_
-#define _NPUPP_H_
-
-#if defined(__OS2__)
-#pragma pack(1)
-#endif
-
-#ifndef GENERATINGCFM
-#define GENERATINGCFM 0
-#endif
-
-#ifndef _NPAPI_H_
-#include "npapi.h"
-#endif
-
-#include "npruntime.h"
-
-#include "jri.h"
-
-
-/******************************************************************************************
-   plug-in function table macros
- 	        for each function in and out of the plugin API we define
-                    typedef NPP_FooUPP
-					#define NewNPP_FooProc
-					#define CallNPP_FooProc
- *******************************************************************************************/
-
-
-/* NPP_Initialize */
-typedef void (* NP_LOADDS NPP_InitializeUPP)(void);
-#define NewNPP_InitializeProc(FUNC)		\
-		((NPP_InitializeUPP) (FUNC))
-#define CallNPP_InitializeProc(FUNC)		\
-		(*(FUNC))()
-
-/* NPP_Shutdown */
-typedef void (* NP_LOADDS NPP_ShutdownUPP)(void);
-#define NewNPP_ShutdownProc(FUNC)		\
-		((NPP_ShutdownUPP) (FUNC))
-#define CallNPP_ShutdownProc(FUNC)		\
-		(*(FUNC))()
-
-/* NPP_New */
-typedef NPError	(* NP_LOADDS NPP_NewUPP)(NPMIMEType pluginType, NPP instance, uint16 mode, int16 argc, char* argn[], char* argv[], NPSavedData* saved);
-#define NewNPP_NewProc(FUNC)		\
-		((NPP_NewUPP) (FUNC))
-#define CallNPP_NewProc(FUNC, ARG1, ARG2, ARG3, ARG4, ARG5, ARG6, ARG7)		\
-		(*(FUNC))((ARG1), (ARG2), (ARG3), (ARG4), (ARG5), (ARG6), (ARG7))
-
-/* NPP_Destroy */
-typedef NPError	(* NP_LOADDS NPP_DestroyUPP)(NPP instance, NPSavedData** save);
-#define NewNPP_DestroyProc(FUNC)		\
-		((NPP_DestroyUPP) (FUNC))
-#define CallNPP_DestroyProc(FUNC, ARG1, ARG2)		\
-		(*(FUNC))((ARG1), (ARG2))
-
-/* NPP_SetWindow */
-typedef NPError	(* NP_LOADDS NPP_SetWindowUPP)(NPP instance, NPWindow* window);
-#define NewNPP_SetWindowProc(FUNC)		\
-		((NPP_SetWindowUPP) (FUNC))
-#define CallNPP_SetWindowProc(FUNC, ARG1, ARG2)		\
-		(*(FUNC))((ARG1), (ARG2))
-
-/* NPP_NewStream */
-typedef NPError	(* NP_LOADDS NPP_NewStreamUPP)(NPP instance, NPMIMEType type, NPStream* stream, NPBool seekable, uint16* stype);
-#define NewNPP_NewStreamProc(FUNC)		\
-		((NPP_NewStreamUPP) (FUNC))
-#define CallNPP_NewStreamProc(FUNC, ARG1, ARG2, ARG3, ARG4, ARG5) \
-		(*(FUNC))((ARG1), (ARG2), (ARG3), (ARG4), (ARG5))
-
-/* NPP_DestroyStream */
-typedef NPError	(* NP_LOADDS NPP_DestroyStreamUPP)(NPP instance, NPStream* stream, NPReason reason);
-#define NewNPP_DestroyStreamProc(FUNC)		\
-		((NPP_DestroyStreamUPP) (FUNC))
-#define CallNPP_DestroyStreamProc(FUNC,  NPParg, NPStreamPtr, NPReasonArg)		\
-		(*(FUNC))((NPParg), (NPStreamPtr), (NPReasonArg))
-
-/* NPP_WriteReady */
-typedef int32 (* NP_LOADDS NPP_WriteReadyUPP)(NPP instance, NPStream* stream);
-#define NewNPP_WriteReadyProc(FUNC)		\
-		((NPP_WriteReadyUPP) (FUNC))
-#define CallNPP_WriteReadyProc(FUNC,  NPParg, NPStreamPtr)		\
-		(*(FUNC))((NPParg), (NPStreamPtr))
-
-/* NPP_Write */
-typedef int32 (* NP_LOADDS NPP_WriteUPP)(NPP instance, NPStream* stream, int32 offset, int32 len, void* buffer);
-#define NewNPP_WriteProc(FUNC)		\
-		((NPP_WriteUPP) (FUNC))
-#define CallNPP_WriteProc(FUNC,  NPParg, NPStreamPtr, offsetArg, lenArg, bufferPtr)		\
-		(*(FUNC))((NPParg), (NPStreamPtr), (offsetArg), (lenArg), (bufferPtr))
-
-/* NPP_StreamAsFile */
-typedef void (* NP_LOADDS NPP_StreamAsFileUPP)(NPP instance, NPStream* stream, const char* fname);
-#define NewNPP_StreamAsFileProc(FUNC)		\
-		((NPP_StreamAsFileUPP) (FUNC))
-#define CallNPP_StreamAsFileProc(FUNC,  ARG1, ARG2, ARG3)		\
-		(*(FUNC))((ARG1), (ARG2), (ARG3))
-
-/* NPP_Print */
-typedef void (* NP_LOADDS NPP_PrintUPP)(NPP instance, NPPrint* platformPrint);
-#define NewNPP_PrintProc(FUNC)		\
-		((NPP_PrintUPP) (FUNC))
-#define CallNPP_PrintProc(FUNC,  NPParg, NPPrintArg)		\
-		(*(FUNC))((NPParg), (NPPrintArg))
-
-/* NPP_HandleEvent */
-typedef int16 (* NP_LOADDS NPP_HandleEventUPP)(NPP instance, void* event);
-#define NewNPP_HandleEventProc(FUNC)		\
-		((NPP_HandleEventUPP) (FUNC))
-#define CallNPP_HandleEventProc(FUNC,  NPParg, voidPtr)		\
-		(*(FUNC))((NPParg), (voidPtr))
-
-/* NPP_URLNotify */
-typedef void (* NP_LOADDS NPP_URLNotifyUPP)(NPP instance, const char* url, NPReason reason, void* notifyData);
-#define NewNPP_URLNotifyProc(FUNC)		\
-		((NPP_URLNotifyUPP) (FUNC))
-#define CallNPP_URLNotifyProc(FUNC,  ARG1, ARG2, ARG3, ARG4)		\
-		(*(FUNC))((ARG1), (ARG2), (ARG3), (ARG4))
-
-/* NPP_GetValue */
-typedef NPError	(* NP_LOADDS NPP_GetValueUPP)(NPP instance, NPPVariable variable, void *ret_alue);
-#define NewNPP_GetValueProc(FUNC)		\
-		((NPP_GetValueUPP) (FUNC))
-#define CallNPP_GetValueProc(FUNC, ARG1, ARG2, ARG3)		\
-		(*(FUNC))((ARG1), (ARG2), (ARG3))
-
-/* NPP_SetValue */
-typedef NPError	(* NP_LOADDS NPP_SetValueUPP)(NPP instance, NPNVariable variable, void *ret_alue);
-#define NewNPP_SetValueProc(FUNC)		\
-		((NPP_SetValueUPP) (FUNC))
-#define CallNPP_SetValueProc(FUNC, ARG1, ARG2, ARG3)		\
-		(*(FUNC))((ARG1), (ARG2), (ARG3))
-
-/*
- *  Netscape entry points
- */
-
-
-/* NPN_GetValue */
-typedef NPError	(* NP_LOADDS NPN_GetValueUPP)(NPP instance, NPNVariable variable, void *ret_alue);
-#define NewNPN_GetValueProc(FUNC)		\
-		((NPN_GetValueUPP) (FUNC))
-#define CallNPN_GetValueProc(FUNC, ARG1, ARG2, ARG3)		\
-		(*(FUNC))((ARG1), (ARG2), (ARG3))
-
-/* NPN_SetValue */
-typedef NPError	(* NP_LOADDS NPN_SetValueUPP)(NPP instance, NPPVariable variable, void *ret_alue);
-#define NewNPN_SetValueProc(FUNC)		\
-		((NPN_SetValueUPP) (FUNC))
-#define CallNPN_SetValueProc(FUNC, ARG1, ARG2, ARG3)		\
-		(*(FUNC))((ARG1), (ARG2), (ARG3))
-
-/* NPN_GetUrlNotify */
-typedef NPError	(* NP_LOADDS NPN_GetURLNotifyUPP)(NPP instance, const char* url, const char* window, void* notifyData);
-#define NewNPN_GetURLNotifyProc(FUNC)		\
-		((NPN_GetURLNotifyUPP) (FUNC))
-#define CallNPN_GetURLNotifyProc(FUNC, ARG1, ARG2, ARG3, ARG4)		\
-		(*(FUNC))((ARG1), (ARG2), (ARG3), (ARG4))
-
-/* NPN_PostUrlNotify */
-typedef NPError (* NP_LOADDS NPN_PostURLNotifyUPP)(NPP instance, const char* url, const char* window, uint32 len, const char* buf, NPBool file, void* notifyData);
-#define NewNPN_PostURLNotifyProc(FUNC)		\
-		((NPN_PostURLNotifyUPP) (FUNC))
-#define CallNPN_PostURLNotifyProc(FUNC, ARG1, ARG2, ARG3, ARG4, ARG5, ARG6, ARG7) \
-		(*(FUNC))((ARG1), (ARG2), (ARG3), (ARG4), (ARG5), (ARG6), (ARG7))
-
-/* NPN_GetUrl */
-typedef NPError	(* NP_LOADDS NPN_GetURLUPP)(NPP instance, const char* url, const char* window);
-#define NewNPN_GetURLProc(FUNC)		\
-		((NPN_GetURLUPP) (FUNC))
-#define CallNPN_GetURLProc(FUNC, ARG1, ARG2, ARG3)		\
-		(*(FUNC))((ARG1), (ARG2), (ARG3))
-
-/* NPN_PostUrl */
-typedef NPError (* NP_LOADDS NPN_PostURLUPP)(NPP instance, const char* url, const char* window, uint32 len, const char* buf, NPBool file);
-#define NewNPN_PostURLProc(FUNC)		\
-		((NPN_PostURLUPP) (FUNC))
-#define CallNPN_PostURLProc(FUNC, ARG1, ARG2, ARG3, ARG4, ARG5, ARG6) \
-		(*(FUNC))((ARG1), (ARG2), (ARG3), (ARG4), (ARG5), (ARG6))
-
-/* NPN_RequestRead */
-typedef NPError	(* NP_LOADDS NPN_RequestReadUPP)(NPStream* stream, NPByteRange* rangeList);
-#define NewNPN_RequestReadProc(FUNC)		\
-		((NPN_RequestReadUPP) (FUNC))
-#define CallNPN_RequestReadProc(FUNC, stream, range)		\
-		(*(FUNC))((stream), (range))
-
-/* NPN_NewStream */
-typedef NPError	(* NP_LOADDS NPN_NewStreamUPP)(NPP instance, NPMIMEType type, const char* window, NPStream** stream);
-#define NewNPN_NewStreamProc(FUNC)		\
-		((NPN_NewStreamUPP) (FUNC))
-#define CallNPN_NewStreamProc(FUNC, npp, type, window, stream)		\
-		(*(FUNC))((npp), (type), (window), (stream))
-
-/* NPN_Write */
-typedef int32 (* NP_LOADDS NPN_WriteUPP)(NPP instance, NPStream* stream, int32 len, void* buffer);
-#define NewNPN_WriteProc(FUNC)		\
-		((NPN_WriteUPP) (FUNC))
-#define CallNPN_WriteProc(FUNC, npp, stream, len, buffer)		\
-		(*(FUNC))((npp), (stream), (len), (buffer))
-
-/* NPN_DestroyStream */
-typedef NPError (* NP_LOADDS NPN_DestroyStreamUPP)(NPP instance, NPStream* stream, NPReason reason);
-#define NewNPN_DestroyStreamProc(FUNC)		\
-		((NPN_DestroyStreamUPP) (FUNC))
-#define CallNPN_DestroyStreamProc(FUNC, npp, stream, reason)		\
-		(*(FUNC))((npp), (stream), (reason))
-
-/* NPN_Status */
-typedef void (* NP_LOADDS NPN_StatusUPP)(NPP instance, const char* message);
-#define NewNPN_StatusProc(FUNC)		\
-		((NPN_StatusUPP) (FUNC))
-#define CallNPN_StatusProc(FUNC, npp, msg)		\
-		(*(FUNC))((npp), (msg))	
-
-/* NPN_UserAgent */
-typedef const char*	(* NP_LOADDS NPN_UserAgentUPP)(NPP instance);
-#define NewNPN_UserAgentProc(FUNC)              \
-                ((NPN_UserAgentUPP) (FUNC))
-#define CallNPN_UserAgentProc(FUNC, ARG1)               \
-                (*(FUNC))((ARG1))
-
-/* NPN_MemAlloc */
-typedef void* (* NP_LOADDS NPN_MemAllocUPP)(uint32 size);
-#define NewNPN_MemAllocProc(FUNC)		\
-		((NPN_MemAllocUPP) (FUNC))
-#define CallNPN_MemAllocProc(FUNC, ARG1)		\
-		(*(FUNC))((ARG1))	
-
-/* NPN__MemFree */
-typedef void (* NP_LOADDS NPN_MemFreeUPP)(void* ptr);
-#define NewNPN_MemFreeProc(FUNC)		\
-		((NPN_MemFreeUPP) (FUNC))
-#define CallNPN_MemFreeProc(FUNC, ARG1)		\
-		(*(FUNC))((ARG1))	
-
-/* NPN_MemFlush */
-typedef uint32 (* NP_LOADDS NPN_MemFlushUPP)(uint32 size);
-#define NewNPN_MemFlushProc(FUNC)		\
-		((NPN_MemFlushUPP) (FUNC))
-#define CallNPN_MemFlushProc(FUNC, ARG1)		\
-		(*(FUNC))((ARG1))	
-
-/* NPN_ReloadPlugins */
-typedef void (* NP_LOADDS NPN_ReloadPluginsUPP)(NPBool reloadPages);
-#define NewNPN_ReloadPluginsProc(FUNC)		\
-		((NPN_ReloadPluginsUPP) (FUNC))
-#define CallNPN_ReloadPluginsProc(FUNC, ARG1)		\
-		(*(FUNC))((ARG1))	
-
-/* NPN_GetJavaEnv */
-typedef JRIEnv* (* NP_LOADDS NPN_GetJavaEnvUPP)(void);
-#define NewNPN_GetJavaEnvProc(FUNC)		\
-		((NPN_GetJavaEnvUPP) (FUNC))
-#define CallNPN_GetJavaEnvProc(FUNC)		\
-		(*(FUNC))()	
-
-/* NPN_GetJavaPeer */
-typedef jref (* NP_LOADDS NPN_GetJavaPeerUPP)(NPP instance);
-#define NewNPN_GetJavaPeerProc(FUNC)		\
-		((NPN_GetJavaPeerUPP) (FUNC))
-#define CallNPN_GetJavaPeerProc(FUNC, ARG1)		\
-		(*(FUNC))((ARG1))	
-
-/* NPN_InvalidateRect */
-typedef void (* NP_LOADDS NPN_InvalidateRectUPP)(NPP instance, NPRect *rect);
-#define NewNPN_InvalidateRectProc(FUNC)		\
-		((NPN_InvalidateRectUPP) (FUNC))
-#define CallNPN_InvalidateRectProc(FUNC, ARG1, ARG2)		\
-		(*(FUNC))((ARG1), (ARG2))	
-
-/* NPN_InvalidateRegion */
-typedef void (* NP_LOADDS NPN_InvalidateRegionUPP)(NPP instance, NPRegion region);
-#define NewNPN_InvalidateRegionProc(FUNC)		\
-		((NPN_InvalidateRegionUPP) (FUNC))
-#define CallNPN_InvalidateRegionProc(FUNC, ARG1, ARG2)		\
-		(*(FUNC))((ARG1), (ARG2))	
-
-/* NPN_ForceRedraw */
-typedef void (* NP_LOADDS NPN_ForceRedrawUPP)(NPP instance);
-#define NewNPN_ForceRedrawProc(FUNC)		\
-		((NPN_ForceRedrawUPP) (FUNC))
-#define CallNPN_ForceRedrawProc(FUNC, ARG1)		\
-		(*(FUNC))((ARG1))	
-
-/* NPN_GetStringIdentifier */
-typedef NPIdentifier (* NP_LOADDS NPN_GetStringIdentifierUPP)(const NPUTF8* name);
-#define NewNPN_GetStringIdentifierProc(FUNC)		\
-		((NPN_GetStringIdentifierUPP) (FUNC))
-#define CallNPN_GetStringIdentifierProc(FUNC, ARG1)		\
-		(*(FUNC))((ARG1))
-
-/* NPN_GetStringIdentifiers */
-typedef void (* NP_LOADDS NPN_GetStringIdentifiersUPP)(const NPUTF8** names,
-                                                 int32_t nameCount,
-                                                 NPIdentifier* identifiers);
-#define NewNPN_GetStringIdentifiersProc(FUNC)		\
-		((NPN_GetStringIdentifiersUPP) (FUNC))
-#define CallNPN_GetStringIdentifiersProc(FUNC, ARG1, ARG2, ARG3)		\
-		(*(FUNC))((ARG1), (ARG2), (ARG3))
-
-/* NPN_GetIntIdentifier */
-typedef NPIdentifier (* NP_LOADDS NPN_GetIntIdentifierUPP)(int32_t intid);
-#define NewNPN_GetIntIdentifierProc(FUNC)		\
-		((NPN_GetIntIdentifierUPP) (FUNC))
-#define CallNPN_GetIntIdentifierProc(FUNC, ARG1)		\
-		(*(FUNC))((ARG1))
-
-/* NPN_IdentifierIsString */
-typedef bool (* NP_LOADDS NPN_IdentifierIsStringUPP)(NPIdentifier identifier);
-#define NewNPN_IdentifierIsStringProc(FUNC)		\
-		((NPN_IdentifierIsStringUPP) (FUNC))
-#define CallNPN_IdentifierIsStringProc(FUNC, ARG1)		\
-		(*(FUNC))((ARG1))
-
-/* NPN_UTF8FromIdentifier */
-typedef NPUTF8* (* NP_LOADDS NPN_UTF8FromIdentifierUPP)(NPIdentifier identifier);
-#define NewNPN_UTF8FromIdentifierProc(FUNC)		\
-		((NPN_UTF8FromIdentifierUPP) (FUNC))
-#define CallNPN_UTF8FromIdentifierProc(FUNC, ARG1)		\
-		(*(FUNC))((ARG1))
-
-/* NPN_IntFromIdentifier */
-typedef int32_t (* NP_LOADDS NPN_IntFromIdentifierUPP)(NPIdentifier identifier);
-#define NewNPN_IntFromIdentifierProc(FUNC)		\
-		((NPN_IntFromIdentifierUPP) (FUNC))
-#define CallNPN_IntFromIdentifierProc(FUNC, ARG1)		\
-		(*(FUNC))((ARG1))
-
-/* NPN_CreateObject */
-typedef NPObject* (* NP_LOADDS NPN_CreateObjectUPP)(NPP npp, NPClass *aClass);
-#define NewNPN_CreateObjectProc(FUNC)		\
-		((NPN_CreateObjectUPP) (FUNC))
-#define CallNPN_CreateObjectProc(FUNC, ARG1, ARG2)		\
-		(*(FUNC))((ARG1), (ARG2))
-
-/* NPN_RetainObject */
-typedef NPObject* (* NP_LOADDS NPN_RetainObjectUPP)(NPObject *obj);
-#define NewNPN_RetainObjectProc(FUNC)		\
-		((NPN_RetainObjectUPP) (FUNC))
-#define CallNPN_RetainObjectProc(FUNC, ARG1)		\
-		(*(FUNC))((ARG1))
-
-/* NPN_ReleaseObject */
-typedef void (* NP_LOADDS NPN_ReleaseObjectUPP)(NPObject *obj);
-#define NewNPN_ReleaseObjectProc(FUNC)		\
-		((NPN_ReleaseObjectUPP) (FUNC))
-#define CallNPN_ReleaseObjectProc(FUNC, ARG1)		\
-		(*(FUNC))((ARG1))
-
-/* NPN_Invoke */
-typedef bool (* NP_LOADDS NPN_InvokeUPP)(NPP npp, NPObject* obj, NPIdentifier methodName, const NPVariant *args, uint32_t argCount, NPVariant *result);
-#define NewNPN_InvokeProc(FUNC)		\
-		((NPN_InvokeUPP) (FUNC))
-#define CallNPN_InvokeProc(FUNC, ARG1, ARG2, ARG3, ARG4, ARG5, ARG6)		\
-		(*(FUNC))((ARG1), (ARG2), (ARG3), (ARG4), (ARG5), (ARG6))
-
-/* NPN_InvokeDefault */
-typedef bool (* NP_LOADDS NPN_InvokeDefaultUPP)(NPP npp, NPObject* obj, const NPVariant *args, uint32_t argCount, NPVariant *result);
-#define NewNPN_InvokeDefaultProc(FUNC)		\
-		((NPN_InvokeDefaultUPP) (FUNC))
-#define CallNPN_InvokeDefaultProc(FUNC, ARG1, ARG2, ARG3, ARG4, ARG5)		\
-		(*(FUNC))((ARG1), (ARG2), (ARG3), (ARG4), (ARG5))
-
-/* NPN_Evaluate */
-typedef bool (* NP_LOADDS NPN_EvaluateUPP)(NPP npp, NPObject *obj, NPString *script, NPVariant *result);
-#define NewNPN_EvaluateProc(FUNC)		\
-		((NPN_EvaluateUPP) (FUNC))
-#define CallNPN_EvaluateProc(FUNC, ARG1, ARG2, ARG3, ARG4)		\
-		(*(FUNC))((ARG1), (ARG2), (ARG3), (ARG4))
-
-/* NPN_GetProperty */
-typedef bool (* NP_LOADDS NPN_GetPropertyUPP)(NPP npp, NPObject *obj, NPIdentifier propertyName, NPVariant *result);
-#define NewNPN_GetPropertyProc(FUNC)		\
-		((NPN_GetPropertyUPP) (FUNC))
-#define CallNPN_GetPropertyProc(FUNC, ARG1, ARG2, ARG3, ARG4)		\
-		(*(FUNC))((ARG1), (ARG2), (ARG3), (ARG4))
-
-/* NPN_SetProperty */
-typedef bool (* NP_LOADDS NPN_SetPropertyUPP)(NPP npp, NPObject *obj, NPIdentifier propertyName, const NPVariant *value);
-#define NewNPN_SetPropertyProc(FUNC)		\
-		((NPN_SetPropertyUPP) (FUNC))
-#define CallNPN_SetPropertyProc(FUNC, ARG1, ARG2, ARG3, ARG4)		\
-		(*(FUNC))((ARG1), (ARG2), (ARG3), (ARG4))
-
-/* NPN_RemoveProperty */
-typedef bool (* NP_LOADDS NPN_RemovePropertyUPP)(NPP npp, NPObject *obj, NPIdentifier propertyName);
-#define NewNPN_RemovePropertyProc(FUNC)		\
-		((NPN_RemovePropertyUPP) (FUNC))
-#define CallNPN_RemovePropertyProc(FUNC, ARG1, ARG2, ARG3)		\
-		(*(FUNC))((ARG1), (ARG2), (ARG3))
-
-/* NPN_HasProperty */
-typedef bool (* NP_LOADDS NPN_HasPropertyUPP)(NPP npp, NPObject *obj, NPIdentifier propertyName);
-#define NewNPN_HasPropertyProc(FUNC)		\
-		((NPN_HasPropertyUPP) (FUNC))
-#define CallNPN_HasPropertyProc(FUNC, ARG1, ARG2, ARG3)		\
-		(*(FUNC))((ARG1), (ARG2), (ARG3))
-
-/* NPN_HasMethod */
-typedef bool (* NP_LOADDS NPN_HasMethodUPP)(NPP npp, NPObject *obj, NPIdentifier propertyName);
-#define NewNPN_HasMethodProc(FUNC)		\
-		((NPN_HasMethodUPP) (FUNC))
-#define CallNPN_HasMethodProc(FUNC, ARG1, ARG2, ARG3)		\
-		(*(FUNC))((ARG1), (ARG2), (ARG3))
-
-/* NPN_ReleaseVariantValue */
-typedef void (* NP_LOADDS NPN_ReleaseVariantValueUPP)(NPVariant *variant);
-#define NewNPN_ReleaseVariantValueProc(FUNC)		\
-		((NPN_ReleaseVariantValueUPP) (FUNC))
-#define CallNPN_ReleaseVariantValueProc(FUNC, ARG1)		\
-		(*(FUNC))((ARG1))
-
-/* NPN_SetException */
-typedef void (* NP_LOADDS NPN_SetExceptionUPP)(NPObject *obj, const NPUTF8 *message);
-#define NewNPN_SetExceptionProc(FUNC)		\
-		((NPN_SetExceptionUPP) (FUNC))
-#define CallNPN_SetExceptionProc(FUNC, ARG1, ARG2)		\
-		(*(FUNC))((ARG1), (ARG2))	
-
-/* NPN_PushPopupsEnabledStateUPP */
-typedef bool (* NP_LOADDS NPN_PushPopupsEnabledStateUPP)(NPP npp, NPBool enabled);
-#define NewNPN_PushPopupsEnabledStateProc(FUNC)		\
-		((NPN_PushPopupsEnabledStateUPP) (FUNC))
-#define CallNPN_PushPopupsEnabledStateProc(FUNC, ARG1, ARG2)		\
-		(*(FUNC))((ARG1), (ARG2))
-
-/* NPN_PopPopupsEnabledState */
-typedef bool (* NP_LOADDS NPN_PopPopupsEnabledStateUPP)(NPP npp);
-#define NewNPN_PopPopupsEnabledStateProc(FUNC)		\
-		((NPN_PopPopupsEnabledStateUPP) (FUNC))
-#define CallNPN_PopPopupsEnabledStateProc(FUNC, ARG1)		\
-		(*(FUNC))((ARG1))
-
-/* NPN_Enumerate */
-typedef bool (* NP_LOADDS NPN_EnumerateUPP)(NPP npp, NPObject *obj, NPIdentifier **identifier, uint32_t *count);
-#define NewNPN_EnumerateProc(FUNC)		\
-		((NPN_EnumerateUPP) (FUNC))
-#define CallNPN_EnumerateProc(FUNC, ARG1, ARG2, ARG3, ARG4)		\
-		(*(FUNC))((ARG1), (ARG2), (ARG3), (ARG4))
-
-/* NPN_PluginThreadAsyncCall */
-typedef void (* NP_LOADDS NPN_PluginThreadAsyncCallUPP)(NPP instance, void (*func)(void *), void *userData);
-#define NewNPN_PluginThreadAsyncCallProc(FUNC) \
-		((NPN_PluginThreadAsyncCallUPP) (FUNC))
-#define CallNPN_PluginThreadAsyncCallProc(FUNC, ARG1, ARG2, ARG3) \
-		(*(FUNC))((ARG1), (ARG2), (ARG3))
-
-/* NPN_Construct */
-typedef bool (* NP_LOADDS NPN_ConstructUPP)(NPP npp, NPObject* obj, const NPVariant *args, uint32_t argCount, NPVariant *result);
-#define NewNPN_ConstructProc(FUNC)		\
-		((NPN_ConstructUPP) (FUNC))
-#define CallNPN_ConstructProc(FUNC, ARG1, ARG2, ARG3, ARG4, ARG5)      \
-		(*(FUNC))((ARG1), (ARG2), (ARG3), (ARG4), (ARG5))
-
-
-
-/******************************************************************************************
- * The actual plugin function table definitions
- *******************************************************************************************/
-
-typedef struct _NPPluginFuncs {
-    uint16 size;
-    uint16 version;
-    NPP_NewUPP newp;
-    NPP_DestroyUPP destroy;
-    NPP_SetWindowUPP setwindow;
-    NPP_NewStreamUPP newstream;
-    NPP_DestroyStreamUPP destroystream;
-    NPP_StreamAsFileUPP asfile;
-    NPP_WriteReadyUPP writeready;
-    NPP_WriteUPP write;
-    NPP_PrintUPP print;
-    NPP_HandleEventUPP event;
-    NPP_URLNotifyUPP urlnotify;
-    JRIGlobalRef javaClass;
-    NPP_GetValueUPP getvalue;
-    NPP_SetValueUPP setvalue;
-} NPPluginFuncs;
-
-typedef struct _NPNetscapeFuncs {
-    uint16 size;
-    uint16 version;
-    NPN_GetURLUPP geturl;
-    NPN_PostURLUPP posturl;
-    NPN_RequestReadUPP requestread;
-    NPN_NewStreamUPP newstream;
-    NPN_WriteUPP write;
-    NPN_DestroyStreamUPP destroystream;
-    NPN_StatusUPP status;
-    NPN_UserAgentUPP uagent;
-    NPN_MemAllocUPP memalloc;
-    NPN_MemFreeUPP memfree;
-    NPN_MemFlushUPP memflush;
-    NPN_ReloadPluginsUPP reloadplugins;
-    NPN_GetJavaEnvUPP getJavaEnv;
-    NPN_GetJavaPeerUPP getJavaPeer;
-    NPN_GetURLNotifyUPP geturlnotify;
-    NPN_PostURLNotifyUPP posturlnotify;
-    NPN_GetValueUPP getvalue;
-    NPN_SetValueUPP setvalue;
-    NPN_InvalidateRectUPP invalidaterect;
-    NPN_InvalidateRegionUPP invalidateregion;
-    NPN_ForceRedrawUPP forceredraw;
-    NPN_GetStringIdentifierUPP getstringidentifier;
-    NPN_GetStringIdentifiersUPP getstringidentifiers;
-    NPN_GetIntIdentifierUPP getintidentifier;
-    NPN_IdentifierIsStringUPP identifierisstring;
-    NPN_UTF8FromIdentifierUPP utf8fromidentifier;
-    NPN_IntFromIdentifierUPP intfromidentifier;
-    NPN_CreateObjectUPP createobject;
-    NPN_RetainObjectUPP retainobject;
-    NPN_ReleaseObjectUPP releaseobject;
-    NPN_InvokeUPP invoke;
-    NPN_InvokeDefaultUPP invokeDefault;
-    NPN_EvaluateUPP evaluate;
-    NPN_GetPropertyUPP getproperty;
-    NPN_SetPropertyUPP setproperty;
-    NPN_RemovePropertyUPP removeproperty;
-    NPN_HasPropertyUPP hasproperty;
-    NPN_HasMethodUPP hasmethod;
-    NPN_ReleaseVariantValueUPP releasevariantvalue;
-    NPN_SetExceptionUPP setexception;
-    NPN_PushPopupsEnabledStateUPP pushpopupsenabledstate;
-    NPN_PopPopupsEnabledStateUPP poppopupsenabledstate;
-    NPN_EnumerateUPP enumerate;
-    NPN_PluginThreadAsyncCallUPP pluginthreadasynccall;
-    NPN_ConstructUPP construct;
-} NPNetscapeFuncs;
-
-
-#ifdef XP_MACOSX
-/******************************************************************************************
- * Mac platform-specific plugin glue stuff
- *******************************************************************************************/
-
-/*
- * Main entry point of the plugin.
- * This routine will be called when the plugin is loaded. The function
- * tables are passed in and the plugin fills in the NPPluginFuncs table
- * and NPPShutdownUPP for Netscape's use.
- */
-typedef NPError (* NP_LOADDS NPP_MainEntryUPP)(NPNetscapeFuncs*, NPPluginFuncs*, NPP_ShutdownUPP*);
-#define NewNPP_MainEntryProc(FUNC)		\
-		((NPP_MainEntryUPP) (FUNC))
-#define CallNPP_MainEntryProc(FUNC,  netscapeFunc, pluginFunc, shutdownUPP)		\
-		(*(FUNC))((netscapeFunc), (pluginFunc), (shutdownUPP))
-
-/*
- * Mac OS X version(s) of NP_GetMIMEDescription(const char *)
- * These can be called to retreive MIME information from the plugin dynamically
- *
- * Note: For compatibility with Quicktime, BPSupportedMIMEtypes is another way
- *       to get mime info from the plugin only on OSX and may not be supported 
- *       in furture version -- use NP_GetMIMEDescription instead
- */
-
-enum
-{
- kBPSupportedMIMETypesStructVers_1    = 1
-};
-
-typedef struct _BPSupportedMIMETypes
-{
- SInt32    structVersion;      /* struct version */
- Handle    typeStrings;        /* STR# formated handle, allocated by plug-in */
- Handle    infoStrings;        /* STR# formated handle, allocated by plug-in */
-} BPSupportedMIMETypes;
-OSErr BP_GetSupportedMIMETypes(BPSupportedMIMETypes *mimeInfo, UInt32 flags);
-
- /* NP_GetMIMEDescription */
-#define NP_GETMIMEDESCRIPTION_NAME "NP_GetMIMEDescription"
-typedef const char* (* NP_LOADDS NP_GetMIMEDescriptionUPP)();
-#define NewNP_GetMIMEDescEntryProc(FUNC)		\
-		((NP_GetMIMEDescriptionUPP) (FUNC))
-#define CallNP_GetMIMEDescEntryProc(FUNC)		\
-		(*(FUNC))()
-
-/* BP_GetSupportedMIMETypes */
-typedef OSErr (* NP_LOADDS BP_GetSupportedMIMETypesUPP)(BPSupportedMIMETypes*, UInt32);
-#define NewBP_GetSupportedMIMETypesEntryProc(FUNC)		\
-		((BP_GetSupportedMIMETypesUPP) (FUNC))
-#define CallBP_GetMIMEDescEntryProc(FUNC,  mimeInfo, flags)		\
-		(*(FUNC))((mimeInfo), (flags))
-
-#endif /* XP_MACOSX */
-
-#if defined(_WINDOWS)
-#define OSCALL WINAPI
-#else
-#if defined(__OS2__)
-#define OSCALL _System
-#else
-#define OSCALL
-#endif
-#endif
-
-#if defined(XP_UNIX)
-/* GCC 3.3 and later support the visibility attribute. */
-#if defined(__GNUC__) && \
-    ((__GNUC__ >= 4) || (__GNUC__ == 3 && __GNUC_MINOR__ >= 3))
-#define NP_VISIBILITY_DEFAULT __attribute__((visibility("default")))
-#else
-#define NP_VISIBILITY_DEFAULT
-#endif
-
-#define NP_EXPORT(__type) NP_VISIBILITY_DEFAULT __type
-#endif
-
-#if defined( _WINDOWS ) || defined (__OS2__)
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/* plugin meta member functions */
-#if defined(__OS2__)
-
-typedef struct _NPPluginData {   /* Alternate OS2 Plugin interface */
-    char *pMimeTypes;
-    char *pFileExtents;
-    char *pFileOpenTemplate;
-    char *pProductName;
-    char *pProductDescription;
-    unsigned long dwProductVersionMS;
-    unsigned long dwProductVersionLS;
-} NPPluginData;
-
-NPError OSCALL NP_GetPluginData(NPPluginData * pPluginData);
-
-#endif
-
-NPError OSCALL NP_GetEntryPoints(NPPluginFuncs* pFuncs);
-
-NPError OSCALL NP_Initialize(NPNetscapeFuncs* pFuncs);
-
-NPError OSCALL NP_Shutdown();
-
-char*	NP_GetMIMEDescription();
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* _WINDOWS || __OS2__ */
-
-#if defined(__OS2__)
-#pragma pack()
-#endif
-
-#ifdef XP_UNIX
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/* plugin meta member functions */
-
-#ifdef XP_MAC
-NPError NP_Initialize(NPNetscapeFuncs *browserFuncs);
-NPError NP_GetEntryPoints(NPPluginFuncs *pluginFuncs);
-void NP_Shutdown(void);
-#else
-NP_EXPORT(char*)   NP_GetMIMEDescription(void);
-NP_EXPORT(NPError) NP_Initialize(NPNetscapeFuncs*, NPPluginFuncs*);
-NP_EXPORT(NPError) NP_Shutdown(void);
-#endif
-
-NP_EXPORT(NPError) NP_GetValue(void *future, NPPVariable aVariable, void *aValue);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* XP_UNIX */
-
-#endif /* _NPUPP_H_ */
diff -r fcf435874395 -r 45c889eae324 front_idill/extern/fajran-npTuioClient/npapi/obsolete/protypes.h
--- a/front_idill/extern/fajran-npTuioClient/npapi/obsolete/protypes.h	Thu Apr 19 11:53:06 2012 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,252 +0,0 @@
-/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* ***** BEGIN LICENSE BLOCK *****
- * Version: MPL 1.1/GPL 2.0/LGPL 2.1
- *
- * The contents of this file are subject to the Mozilla Public License Version
- * 1.1 (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- * http://www.mozilla.org/MPL/
- *
- * Software distributed under the License is distributed on an "AS IS" basis,
- * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
- * for the specific language governing rights and limitations under the
- * License.
- *
- * The Original Code is the Netscape Portable Runtime (NSPR).
- *
- * The Initial Developer of the Original Code is
- * Netscape Communications Corporation.
- * Portions created by the Initial Developer are Copyright (C) 1998-2000
- * the Initial Developer. All Rights Reserved.
- *
- * Contributor(s):
- *
- * Alternatively, the contents of this file may be used under the terms of
- * either the GNU General Public License Version 2 or later (the "GPL"), or
- * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
- * in which case the provisions of the GPL or the LGPL are applicable instead
- * of those above. If you wish to allow use of your version of this file only
- * under the terms of either the GPL or the LGPL, and not to allow others to
- * use your version of this file under the terms of the MPL, indicate your
- * decision by deleting the provisions above and replace them with the notice
- * and other provisions required by the GPL or the LGPL. If you do not delete
- * the provisions above, a recipient may use your version of this file under
- * the terms of any one of the MPL, the GPL or the LGPL.
- *
- * ***** END LICENSE BLOCK ***** */
-
-/*
- * This header typedefs the old 'native' types to the new PRs.
- * These definitions are scheduled to be eliminated at the earliest
- * possible time. The NSPR API is implemented and documented using
- * the new definitions.
- */
-
-#if !defined(PROTYPES_H)
-#define PROTYPES_H
-
-typedef PRUintn uintn;
-#ifndef _XP_Core_
-typedef PRIntn intn;
-#endif
-
-/*
- * It is trickier to define uint, int8, uint8, int16, uint16,
- * int32, uint32, int64, and uint64 because some of these int
- * types are defined by standard header files on some platforms.
- * Our strategy here is to include all such standard headers
- * first, and then define these int types only if they are not
- * defined by those standard headers.
- */
-
-/*
- * BeOS defines all the int types below in its standard header
- * file SupportDefs.h.
- */
-#ifdef XP_BEOS
-#include 
-#endif
-
-/*
- * OpenVMS defines all the int types below in its standard
- * header files ints.h and types.h.
- */
-#ifdef VMS
-#include 
-#include 
-#endif
-
-/*
- * SVR4 typedef of uint is commonly found on UNIX machines.
- *
- * On AIX 4.3, sys/inttypes.h (which is included by sys/types.h)
- * defines the types int8, int16, int32, and int64.
- */
-#ifdef XP_UNIX
-#include 
-#endif
-
-/* model.h on HP-UX defines int8, int16, and int32. */
-#ifdef HPUX
-#include 
-#endif
-
-/*
- * uint
- */
-
-#if !defined(XP_BEOS) && !defined(VMS) \
-    && !defined(XP_UNIX) || defined(NTO)
-typedef PRUintn uint;
-#endif
-
-/*
- * uint64
- */
-
-#if !defined(XP_BEOS) && !defined(VMS)
-typedef PRUint64 uint64;
-#endif
-
-/*
- * uint32
- */
-
-#if !defined(XP_BEOS) && !defined(VMS)
-#if !defined(XP_MAC) && !defined(_WIN32) && !defined(XP_OS2) && !defined(NTO)
-typedef PRUint32 uint32;
-#else
-typedef unsigned long uint32;
-#endif
-#endif
-
-/*
- * uint16
- */
-
-#if !defined(XP_BEOS) && !defined(VMS)
-typedef PRUint16 uint16;
-#endif
-
-/*
- * uint8
- */
-
-#if !defined(XP_BEOS) && !defined(VMS)
-typedef PRUint8 uint8;
-#endif
-
-/*
- * int64
- */
-
-#if !defined(XP_BEOS) && !defined(VMS) \
-    && !defined(_PR_AIX_HAVE_BSD_INT_TYPES)
-typedef PRInt64 int64;
-#endif
-
-/*
- * int32
- */
-
-#if !defined(XP_BEOS) && !defined(VMS) \
-    && !defined(_PR_AIX_HAVE_BSD_INT_TYPES) \
-    && !defined(HPUX)
-#if !defined(XP_MAC) && !defined(_WIN32) && !defined(XP_OS2) && !defined(NTO)
-typedef PRInt32 int32;
-#else
-typedef long int32;
-#endif
-#endif
-
-/*
- * int16
- */
-
-#if !defined(XP_BEOS) && !defined(VMS) \
-    && !defined(_PR_AIX_HAVE_BSD_INT_TYPES) \
-    && !defined(HPUX)
-typedef PRInt16 int16;
-#endif
-
-/*
- * int8
- */
-
-#if !defined(XP_BEOS) && !defined(VMS) \
-    && !defined(_PR_AIX_HAVE_BSD_INT_TYPES) \
-    && !defined(HPUX)
-typedef PRInt8 int8;
-#endif
-
-typedef PRFloat64 float64;
-typedef PRUptrdiff uptrdiff_t;
-typedef PRUword uprword_t;
-typedef PRWord prword_t;
-
-
-/* Re: prbit.h */
-#define TEST_BIT	PR_TEST_BIT
-#define SET_BIT		PR_SET_BIT
-#define CLEAR_BIT	PR_CLEAR_BIT
-
-/* Re: prarena.h->plarena.h */
-#define PRArena PLArena
-#define PRArenaPool PLArenaPool
-#define PRArenaStats PLArenaStats
-#define PR_ARENA_ALIGN PL_ARENA_ALIGN
-#define PR_INIT_ARENA_POOL PL_INIT_ARENA_POOL
-#define PR_ARENA_ALLOCATE PL_ARENA_ALLOCATE
-#define PR_ARENA_GROW PL_ARENA_GROW
-#define PR_ARENA_MARK PL_ARENA_MARK
-#define PR_CLEAR_UNUSED PL_CLEAR_UNUSED
-#define PR_CLEAR_ARENA PL_CLEAR_ARENA
-#define PR_ARENA_RELEASE PL_ARENA_RELEASE
-#define PR_COUNT_ARENA PL_COUNT_ARENA
-#define PR_ARENA_DESTROY PL_ARENA_DESTROY
-#define PR_InitArenaPool PL_InitArenaPool
-#define PR_FreeArenaPool PL_FreeArenaPool
-#define PR_FinishArenaPool PL_FinishArenaPool
-#define PR_CompactArenaPool PL_CompactArenaPool
-#define PR_ArenaFinish PL_ArenaFinish
-#define PR_ArenaAllocate PL_ArenaAllocate
-#define PR_ArenaGrow PL_ArenaGrow
-#define PR_ArenaRelease PL_ArenaRelease
-#define PR_ArenaCountAllocation PL_ArenaCountAllocation
-#define PR_ArenaCountInplaceGrowth PL_ArenaCountInplaceGrowth
-#define PR_ArenaCountGrowth PL_ArenaCountGrowth
-#define PR_ArenaCountRelease PL_ArenaCountRelease
-#define PR_ArenaCountRetract PL_ArenaCountRetract
-
-/* Re: prhash.h->plhash.h */
-#define PRHashEntry PLHashEntry
-#define PRHashTable PLHashTable
-#define PRHashNumber PLHashNumber
-#define PRHashFunction PLHashFunction
-#define PRHashComparator PLHashComparator
-#define PRHashEnumerator PLHashEnumerator
-#define PRHashAllocOps PLHashAllocOps
-#define PR_NewHashTable PL_NewHashTable
-#define PR_HashTableDestroy PL_HashTableDestroy
-#define PR_HashTableRawLookup PL_HashTableRawLookup
-#define PR_HashTableRawAdd PL_HashTableRawAdd
-#define PR_HashTableRawRemove PL_HashTableRawRemove
-#define PR_HashTableAdd PL_HashTableAdd
-#define PR_HashTableRemove PL_HashTableRemove
-#define PR_HashTableEnumerateEntries PL_HashTableEnumerateEntries
-#define PR_HashTableLookup PL_HashTableLookup
-#define PR_HashTableDump PL_HashTableDump
-#define PR_HashString PL_HashString
-#define PR_CompareStrings PL_CompareStrings
-#define PR_CompareValues PL_CompareValues
-
-#if defined(XP_MAC)
-#ifndef TRUE				/* Mac standard is lower case true */
-	#define TRUE 1
-#endif
-#ifndef FALSE				/* Mac standard is lower case false */
-	#define FALSE 0
-#endif
-#endif
-
-#endif /* !defined(PROTYPES_H) */
diff -r fcf435874395 -r 45c889eae324 front_idill/extern/fajran-npTuioClient/npapi/prcpucfg-glibc.h
--- a/front_idill/extern/fajran-npTuioClient/npapi/prcpucfg-glibc.h	Thu Apr 19 11:53:06 2012 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,764 +0,0 @@
-/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* ***** BEGIN LICENSE BLOCK *****
- * Version: MPL 1.1/GPL 2.0/LGPL 2.1
- *
- * The contents of this file are subject to the Mozilla Public License Version
- * 1.1 (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- * http://www.mozilla.org/MPL/
- *
- * Software distributed under the License is distributed on an "AS IS" basis,
- * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
- * for the specific language governing rights and limitations under the
- * License.
- *
- * The Original Code is the Netscape Portable Runtime (NSPR).
- *
- * The Initial Developer of the Original Code is
- * Netscape Communications Corporation.
- * Portions created by the Initial Developer are Copyright (C) 1998-2000
- * the Initial Developer. All Rights Reserved.
- *
- * Contributor(s):
- *
- * Alternatively, the contents of this file may be used under the terms of
- * either the GNU General Public License Version 2 or later (the "GPL"), or
- * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
- * in which case the provisions of the GPL or the LGPL are applicable instead
- * of those above. If you wish to allow use of your version of this file only
- * under the terms of either the GPL or the LGPL, and not to allow others to
- * use your version of this file under the terms of the MPL, indicate your
- * decision by deleting the provisions above and replace them with the notice
- * and other provisions required by the GPL or the LGPL. If you do not delete
- * the provisions above, a recipient may use your version of this file under
- * the terms of any one of the MPL, the GPL or the LGPL.
- *
- * ***** END LICENSE BLOCK ***** */
-
-/*
- * This file is used by not only Linux but also other glibc systems
- * such as GNU/Hurd and GNU/k*BSD.
- */
-
-#ifndef nspr_cpucfg___
-#define nspr_cpucfg___
-
-#ifndef XP_UNIX
-#define XP_UNIX
-#endif
-
-#if !defined(LINUX) && defined(__linux__)
-#define LINUX
-#endif
-
-#ifdef __FreeBSD_kernel__
-#define PR_AF_INET6 28  /* same as AF_INET6 */
-#else
-#define PR_AF_INET6 10  /* same as AF_INET6 */
-#endif
-
-#ifdef __powerpc64__
-
-#undef  IS_LITTLE_ENDIAN
-#define IS_BIG_ENDIAN    1
-#define IS_64
-
-#define PR_BYTES_PER_BYTE   1
-#define PR_BYTES_PER_SHORT  2
-#define PR_BYTES_PER_INT    4
-#define PR_BYTES_PER_INT64  8
-#define PR_BYTES_PER_LONG   8
-#define PR_BYTES_PER_FLOAT  4
-#define PR_BYTES_PER_DOUBLE 8
-#define PR_BYTES_PER_WORD   8
-#define PR_BYTES_PER_DWORD  8
-
-#define PR_BITS_PER_BYTE    8
-#define PR_BITS_PER_SHORT   16
-#define PR_BITS_PER_INT     32
-#define PR_BITS_PER_INT64   64
-#define PR_BITS_PER_LONG    64
-#define PR_BITS_PER_FLOAT   32
-#define PR_BITS_PER_DOUBLE  64
-#define PR_BITS_PER_WORD    64
-
-#define PR_BITS_PER_BYTE_LOG2   3
-#define PR_BITS_PER_SHORT_LOG2  4
-#define PR_BITS_PER_INT_LOG2    5
-#define PR_BITS_PER_INT64_LOG2  6
-#define PR_BITS_PER_LONG_LOG2   6
-#define PR_BITS_PER_FLOAT_LOG2  5
-#define PR_BITS_PER_DOUBLE_LOG2 6
-#define PR_BITS_PER_WORD_LOG2   6
-
-#define PR_ALIGN_OF_SHORT   2
-#define PR_ALIGN_OF_INT     4
-#define PR_ALIGN_OF_LONG    8
-#define PR_ALIGN_OF_INT64   8
-#define PR_ALIGN_OF_FLOAT   4
-#define PR_ALIGN_OF_DOUBLE  8
-#define PR_ALIGN_OF_POINTER 8
-#define PR_ALIGN_OF_WORD    8
-
-#define PR_BYTES_PER_WORD_LOG2   3
-#define PR_BYTES_PER_DWORD_LOG2  3
-
-#elif defined(__powerpc__)
-
-#undef  IS_LITTLE_ENDIAN
-#define IS_BIG_ENDIAN    1
-
-#define PR_BYTES_PER_BYTE   1
-#define PR_BYTES_PER_SHORT  2
-#define PR_BYTES_PER_INT    4
-#define PR_BYTES_PER_INT64  8
-#define PR_BYTES_PER_LONG   4
-#define PR_BYTES_PER_FLOAT  4
-#define PR_BYTES_PER_DOUBLE 8
-#define PR_BYTES_PER_WORD   4
-#define PR_BYTES_PER_DWORD  8
-
-#define PR_BITS_PER_BYTE    8
-#define PR_BITS_PER_SHORT   16
-#define PR_BITS_PER_INT     32
-#define PR_BITS_PER_INT64   64
-#define PR_BITS_PER_LONG    32
-#define PR_BITS_PER_FLOAT   32
-#define PR_BITS_PER_DOUBLE  64
-#define PR_BITS_PER_WORD    32
-
-#define PR_BITS_PER_BYTE_LOG2   3
-#define PR_BITS_PER_SHORT_LOG2  4
-#define PR_BITS_PER_INT_LOG2    5
-#define PR_BITS_PER_INT64_LOG2  6
-#define PR_BITS_PER_LONG_LOG2   5
-#define PR_BITS_PER_FLOAT_LOG2  5
-#define PR_BITS_PER_DOUBLE_LOG2 6
-#define PR_BITS_PER_WORD_LOG2   5
-
-#define PR_ALIGN_OF_SHORT   2
-#define PR_ALIGN_OF_INT     4
-#define PR_ALIGN_OF_LONG    4
-#define PR_ALIGN_OF_INT64   8
-#define PR_ALIGN_OF_FLOAT   4
-#define PR_ALIGN_OF_DOUBLE  8
-#define PR_ALIGN_OF_POINTER 4
-#define PR_ALIGN_OF_WORD    4
-
-#define PR_BYTES_PER_WORD_LOG2   2
-#define PR_BYTES_PER_DWORD_LOG2  3
-
-#elif defined(__alpha)
-
-#define IS_LITTLE_ENDIAN 1
-#undef  IS_BIG_ENDIAN
-#define IS_64
-
-#define PR_BYTES_PER_BYTE   1
-#define PR_BYTES_PER_SHORT  2
-#define PR_BYTES_PER_INT    4
-#define PR_BYTES_PER_INT64  8
-#define PR_BYTES_PER_LONG   8
-#define PR_BYTES_PER_FLOAT  4
-#define PR_BYTES_PER_DOUBLE 8
-#define PR_BYTES_PER_WORD   8
-#define PR_BYTES_PER_DWORD  8
-
-#define PR_BITS_PER_BYTE    8
-#define PR_BITS_PER_SHORT   16
-#define PR_BITS_PER_INT     32
-#define PR_BITS_PER_INT64   64
-#define PR_BITS_PER_LONG    64
-#define PR_BITS_PER_FLOAT   32
-#define PR_BITS_PER_DOUBLE  64
-#define PR_BITS_PER_WORD    64
-
-#define PR_BITS_PER_BYTE_LOG2   3
-#define PR_BITS_PER_SHORT_LOG2  4
-#define PR_BITS_PER_INT_LOG2    5
-#define PR_BITS_PER_INT64_LOG2  6
-#define PR_BITS_PER_LONG_LOG2   6
-#define PR_BITS_PER_FLOAT_LOG2  5
-#define PR_BITS_PER_DOUBLE_LOG2 6
-#define PR_BITS_PER_WORD_LOG2   6
-
-#define PR_ALIGN_OF_SHORT   2
-#define PR_ALIGN_OF_INT     4
-#define PR_ALIGN_OF_LONG    8
-#define PR_ALIGN_OF_INT64   8
-#define PR_ALIGN_OF_FLOAT   4
-#define PR_ALIGN_OF_DOUBLE  8
-#define PR_ALIGN_OF_POINTER 8
-#define PR_ALIGN_OF_WORD    8
-
-#define PR_BYTES_PER_WORD_LOG2  3
-#define PR_BYTES_PER_DWORD_LOG2 3
-
-#elif defined(__ia64__)
-
-#define IS_LITTLE_ENDIAN 1
-#undef  IS_BIG_ENDIAN
-#define IS_64
-
-#define PR_BYTES_PER_BYTE   1
-#define PR_BYTES_PER_SHORT  2
-#define PR_BYTES_PER_INT    4
-#define PR_BYTES_PER_INT64  8
-#define PR_BYTES_PER_LONG   8
-#define PR_BYTES_PER_FLOAT  4
-#define PR_BYTES_PER_DOUBLE 8
-#define PR_BYTES_PER_WORD   8
-#define PR_BYTES_PER_DWORD  8
-
-#define PR_BITS_PER_BYTE    8
-#define PR_BITS_PER_SHORT   16
-#define PR_BITS_PER_INT     32
-#define PR_BITS_PER_INT64   64
-#define PR_BITS_PER_LONG    64
-#define PR_BITS_PER_FLOAT   32
-#define PR_BITS_PER_DOUBLE  64
-#define PR_BITS_PER_WORD    64
-
-#define PR_BITS_PER_BYTE_LOG2   3
-#define PR_BITS_PER_SHORT_LOG2  4
-#define PR_BITS_PER_INT_LOG2    5
-#define PR_BITS_PER_INT64_LOG2  6
-#define PR_BITS_PER_LONG_LOG2   6
-#define PR_BITS_PER_FLOAT_LOG2  5
-#define PR_BITS_PER_DOUBLE_LOG2 6
-#define PR_BITS_PER_WORD_LOG2   6
-
-#define PR_ALIGN_OF_SHORT   2
-#define PR_ALIGN_OF_INT     4
-#define PR_ALIGN_OF_LONG    8
-#define PR_ALIGN_OF_INT64   8
-#define PR_ALIGN_OF_FLOAT   4
-#define PR_ALIGN_OF_DOUBLE  8
-#define PR_ALIGN_OF_POINTER 8
-#define PR_ALIGN_OF_WORD    8
-
-#define PR_BYTES_PER_WORD_LOG2  3
-#define PR_BYTES_PER_DWORD_LOG2 3
-
-#elif defined(__x86_64__)
-
-#define IS_LITTLE_ENDIAN 1
-#undef  IS_BIG_ENDIAN
-#define IS_64
-
-#define PR_BYTES_PER_BYTE   1
-#define PR_BYTES_PER_SHORT  2
-#define PR_BYTES_PER_INT    4
-#define PR_BYTES_PER_INT64  8
-#define PR_BYTES_PER_LONG   8
-#define PR_BYTES_PER_FLOAT  4
-#define PR_BYTES_PER_DOUBLE 8
-#define PR_BYTES_PER_WORD   8
-#define PR_BYTES_PER_DWORD  8
-
-#define PR_BITS_PER_BYTE    8
-#define PR_BITS_PER_SHORT   16
-#define PR_BITS_PER_INT     32
-#define PR_BITS_PER_INT64   64
-#define PR_BITS_PER_LONG    64
-#define PR_BITS_PER_FLOAT   32
-#define PR_BITS_PER_DOUBLE  64
-#define PR_BITS_PER_WORD    64
-
-#define PR_BITS_PER_BYTE_LOG2   3
-#define PR_BITS_PER_SHORT_LOG2  4
-#define PR_BITS_PER_INT_LOG2    5
-#define PR_BITS_PER_INT64_LOG2  6
-#define PR_BITS_PER_LONG_LOG2   6
-#define PR_BITS_PER_FLOAT_LOG2  5
-#define PR_BITS_PER_DOUBLE_LOG2 6
-#define PR_BITS_PER_WORD_LOG2   6
-
-#define PR_ALIGN_OF_SHORT   2
-#define PR_ALIGN_OF_INT     4
-#define PR_ALIGN_OF_LONG    8
-#define PR_ALIGN_OF_INT64   8
-#define PR_ALIGN_OF_FLOAT   4
-#define PR_ALIGN_OF_DOUBLE  8
-#define PR_ALIGN_OF_POINTER 8
-#define PR_ALIGN_OF_WORD    8
-
-#define PR_BYTES_PER_WORD_LOG2  3
-#define PR_BYTES_PER_DWORD_LOG2 3
-
-#elif defined(__mc68000__)
-
-#undef  IS_LITTLE_ENDIAN
-#define IS_BIG_ENDIAN 1
-
-#define PR_BYTES_PER_BYTE   1
-#define PR_BYTES_PER_SHORT  2
-#define PR_BYTES_PER_INT    4
-#define PR_BYTES_PER_INT64  8
-#define PR_BYTES_PER_LONG   4
-#define PR_BYTES_PER_FLOAT  4
-#define PR_BYTES_PER_DOUBLE 8
-#define PR_BYTES_PER_WORD   4
-#define PR_BYTES_PER_DWORD  8
-
-#define PR_BITS_PER_BYTE    8
-#define PR_BITS_PER_SHORT   16
-#define PR_BITS_PER_INT     32
-#define PR_BITS_PER_INT64   64
-#define PR_BITS_PER_LONG    32
-#define PR_BITS_PER_FLOAT   32
-#define PR_BITS_PER_DOUBLE  64
-#define PR_BITS_PER_WORD    32
-
-#define PR_BITS_PER_BYTE_LOG2   3
-#define PR_BITS_PER_SHORT_LOG2  4
-#define PR_BITS_PER_INT_LOG2    5
-#define PR_BITS_PER_INT64_LOG2  6
-#define PR_BITS_PER_LONG_LOG2   5
-#define PR_BITS_PER_FLOAT_LOG2  5
-#define PR_BITS_PER_DOUBLE_LOG2 6
-#define PR_BITS_PER_WORD_LOG2   5
-
-#define PR_ALIGN_OF_SHORT   2
-#define PR_ALIGN_OF_INT     2
-#define PR_ALIGN_OF_LONG    2
-#define PR_ALIGN_OF_INT64   2
-#define PR_ALIGN_OF_FLOAT   2
-#define PR_ALIGN_OF_DOUBLE  2
-#define PR_ALIGN_OF_POINTER 2
-#define PR_ALIGN_OF_WORD    2
-
-#define PR_BYTES_PER_WORD_LOG2   2
-#define PR_BYTES_PER_DWORD_LOG2  3
-
-#elif defined(__sparc__) && defined (__arch64__)
-
-#undef	IS_LITTLE_ENDIAN
-#define	IS_BIG_ENDIAN 1
-#define IS_64
-
-#define PR_BYTES_PER_BYTE   1
-#define PR_BYTES_PER_SHORT  2
-#define PR_BYTES_PER_INT    4
-#define PR_BYTES_PER_INT64  8
-#define PR_BYTES_PER_LONG   8
-#define PR_BYTES_PER_FLOAT  4
-#define PR_BYTES_PER_DOUBLE 8
-#define PR_BYTES_PER_WORD   8
-#define PR_BYTES_PER_DWORD  8
-
-#define PR_BITS_PER_BYTE    8
-#define PR_BITS_PER_SHORT   16
-#define PR_BITS_PER_INT     32
-#define PR_BITS_PER_INT64   64
-#define PR_BITS_PER_LONG    64
-#define PR_BITS_PER_FLOAT   32
-#define PR_BITS_PER_DOUBLE  64
-#define PR_BITS_PER_WORD    64
-
-#define PR_BITS_PER_BYTE_LOG2   3
-#define PR_BITS_PER_SHORT_LOG2  4
-#define PR_BITS_PER_INT_LOG2    5
-#define PR_BITS_PER_INT64_LOG2  6
-#define PR_BITS_PER_LONG_LOG2   6
-#define PR_BITS_PER_FLOAT_LOG2  5
-#define PR_BITS_PER_DOUBLE_LOG2 6
-#define PR_BITS_PER_WORD_LOG2   6
-
-#define PR_ALIGN_OF_SHORT   2
-#define PR_ALIGN_OF_INT     4
-#define PR_ALIGN_OF_INT64   8
-#define PR_ALIGN_OF_LONG    8
-#define PR_ALIGN_OF_FLOAT   4
-#define PR_ALIGN_OF_DOUBLE  8
-#define PR_ALIGN_OF_POINTER 8
-#define PR_ALIGN_OF_WORD    8
-
-#define PR_BYTES_PER_WORD_LOG2   3
-#define PR_BYTES_PER_DWORD_LOG2  3
-
-#elif defined(__sparc__)
-
-#undef	IS_LITTLE_ENDIAN
-#define	IS_BIG_ENDIAN 1
-
-#define PR_BYTES_PER_BYTE   1
-#define PR_BYTES_PER_SHORT  2
-#define PR_BYTES_PER_INT    4
-#define PR_BYTES_PER_INT64  8
-#define PR_BYTES_PER_LONG   4
-#define PR_BYTES_PER_FLOAT  4
-#define PR_BYTES_PER_DOUBLE 8
-#define PR_BYTES_PER_WORD   4
-#define PR_BYTES_PER_DWORD  8
-
-#define PR_BITS_PER_BYTE    8
-#define PR_BITS_PER_SHORT   16
-#define PR_BITS_PER_INT     32
-#define PR_BITS_PER_INT64   64
-#define PR_BITS_PER_LONG    32
-#define PR_BITS_PER_FLOAT   32
-#define PR_BITS_PER_DOUBLE  64
-#define PR_BITS_PER_WORD    32
-
-#define PR_BITS_PER_BYTE_LOG2   3
-#define PR_BITS_PER_SHORT_LOG2  4
-#define PR_BITS_PER_INT_LOG2    5
-#define PR_BITS_PER_INT64_LOG2  6
-#define PR_BITS_PER_LONG_LOG2   5
-#define PR_BITS_PER_FLOAT_LOG2  5
-#define PR_BITS_PER_DOUBLE_LOG2 6
-#define PR_BITS_PER_WORD_LOG2   5
-
-#define PR_ALIGN_OF_SHORT   2
-#define PR_ALIGN_OF_INT     4
-#define PR_ALIGN_OF_LONG    4
-#define PR_ALIGN_OF_INT64   8
-#define PR_ALIGN_OF_FLOAT   4
-#define PR_ALIGN_OF_DOUBLE  8
-#define PR_ALIGN_OF_POINTER 4
-#define PR_ALIGN_OF_WORD    4
-
-#define PR_BYTES_PER_WORD_LOG2   2
-#define PR_BYTES_PER_DWORD_LOG2  3
-
-#elif defined(__i386__)
-
-#define IS_LITTLE_ENDIAN 1
-#undef  IS_BIG_ENDIAN
-
-#define PR_BYTES_PER_BYTE   1
-#define PR_BYTES_PER_SHORT  2
-#define PR_BYTES_PER_INT    4
-#define PR_BYTES_PER_INT64  8
-#define PR_BYTES_PER_LONG   4
-#define PR_BYTES_PER_FLOAT  4
-#define PR_BYTES_PER_DOUBLE 8
-#define PR_BYTES_PER_WORD   4
-#define PR_BYTES_PER_DWORD  8
-
-#define PR_BITS_PER_BYTE    8
-#define PR_BITS_PER_SHORT   16
-#define PR_BITS_PER_INT     32
-#define PR_BITS_PER_INT64   64
-#define PR_BITS_PER_LONG    32
-#define PR_BITS_PER_FLOAT   32
-#define PR_BITS_PER_DOUBLE  64
-#define PR_BITS_PER_WORD    32
-
-#define PR_BITS_PER_BYTE_LOG2   3
-#define PR_BITS_PER_SHORT_LOG2  4
-#define PR_BITS_PER_INT_LOG2    5
-#define PR_BITS_PER_INT64_LOG2  6
-#define PR_BITS_PER_LONG_LOG2   5
-#define PR_BITS_PER_FLOAT_LOG2  5
-#define PR_BITS_PER_DOUBLE_LOG2 6
-#define PR_BITS_PER_WORD_LOG2   5
-
-#define PR_ALIGN_OF_SHORT   2
-#define PR_ALIGN_OF_INT     4
-#define PR_ALIGN_OF_LONG    4
-#define PR_ALIGN_OF_INT64   4
-#define PR_ALIGN_OF_FLOAT   4
-#define PR_ALIGN_OF_DOUBLE  4
-#define PR_ALIGN_OF_POINTER 4
-#define PR_ALIGN_OF_WORD    4
-
-#define PR_BYTES_PER_WORD_LOG2   2
-#define PR_BYTES_PER_DWORD_LOG2  3
-
-#elif defined(__mips__)
-
-#ifdef __MIPSEB__
-#define IS_BIG_ENDIAN 1
-#undef  IS_LITTLE_ENDIAN
-#elif defined(__MIPSEL__)
-#define IS_LITTLE_ENDIAN 1
-#undef  IS_BIG_ENDIAN
-#else
-#error "Unknown MIPS endianness."
-#endif
-
-#define PR_BYTES_PER_BYTE   1
-#define PR_BYTES_PER_SHORT  2
-#define PR_BYTES_PER_INT    4
-#define PR_BYTES_PER_INT64  8
-#define PR_BYTES_PER_LONG   4
-#define PR_BYTES_PER_FLOAT  4
-#define PR_BYTES_PER_DOUBLE 8
-#define PR_BYTES_PER_WORD   4
-#define PR_BYTES_PER_DWORD  8
-
-#define PR_BITS_PER_BYTE    8
-#define PR_BITS_PER_SHORT   16
-#define PR_BITS_PER_INT     32
-#define PR_BITS_PER_INT64   64
-#define PR_BITS_PER_LONG    32
-#define PR_BITS_PER_FLOAT   32
-#define PR_BITS_PER_DOUBLE  64
-#define PR_BITS_PER_WORD    32
-
-#define PR_BITS_PER_BYTE_LOG2   3
-#define PR_BITS_PER_SHORT_LOG2  4
-#define PR_BITS_PER_INT_LOG2    5
-#define PR_BITS_PER_INT64_LOG2  6
-#define PR_BITS_PER_LONG_LOG2   5
-#define PR_BITS_PER_FLOAT_LOG2  5
-#define PR_BITS_PER_DOUBLE_LOG2 6
-#define PR_BITS_PER_WORD_LOG2   5
-
-#define PR_ALIGN_OF_SHORT   2
-#define PR_ALIGN_OF_INT     4
-#define PR_ALIGN_OF_LONG    4
-#define PR_ALIGN_OF_INT64   8
-#define PR_ALIGN_OF_FLOAT   4
-#define PR_ALIGN_OF_DOUBLE  8
-#define PR_ALIGN_OF_POINTER 4
-#define PR_ALIGN_OF_WORD    4
-
-#define PR_BYTES_PER_WORD_LOG2   2
-#define PR_BYTES_PER_DWORD_LOG2  3
-
-#elif defined(__arm__)
-
-#define IS_LITTLE_ENDIAN 1
-#undef  IS_BIG_ENDIAN
-
-#define PR_BYTES_PER_BYTE   1
-#define PR_BYTES_PER_SHORT  2
-#define PR_BYTES_PER_INT    4
-#define PR_BYTES_PER_INT64  8
-#define PR_BYTES_PER_LONG   4
-#define PR_BYTES_PER_FLOAT  4
-#define PR_BYTES_PER_DOUBLE 8
-#define PR_BYTES_PER_WORD   4
-#define PR_BYTES_PER_DWORD  8
-
-#define PR_BITS_PER_BYTE    8
-#define PR_BITS_PER_SHORT   16
-#define PR_BITS_PER_INT     32
-#define PR_BITS_PER_INT64   64
-#define PR_BITS_PER_LONG    32
-#define PR_BITS_PER_FLOAT   32
-#define PR_BITS_PER_DOUBLE  64
-#define PR_BITS_PER_WORD    32
-
-#define PR_BITS_PER_BYTE_LOG2   3
-#define PR_BITS_PER_SHORT_LOG2  4
-#define PR_BITS_PER_INT_LOG2    5
-#define PR_BITS_PER_INT64_LOG2  6
-#define PR_BITS_PER_LONG_LOG2   5
-#define PR_BITS_PER_FLOAT_LOG2  5
-#define PR_BITS_PER_DOUBLE_LOG2 6
-#define PR_BITS_PER_WORD_LOG2   5
-
-#define PR_ALIGN_OF_SHORT   2
-#define PR_ALIGN_OF_INT     4
-#define PR_ALIGN_OF_LONG    4
-#define PR_ALIGN_OF_INT64   4
-#define PR_ALIGN_OF_FLOAT   4
-#define PR_ALIGN_OF_DOUBLE  4
-#define PR_ALIGN_OF_POINTER 4
-#define PR_ALIGN_OF_WORD    4
-
-#define PR_BYTES_PER_WORD_LOG2   2
-#define PR_BYTES_PER_DWORD_LOG2  3
-
-#elif defined(__hppa__)
-
-#undef  IS_LITTLE_ENDIAN
-#define IS_BIG_ENDIAN    1
-
-#define PR_BYTES_PER_BYTE   1
-#define PR_BYTES_PER_SHORT  2
-#define PR_BYTES_PER_INT    4
-#define PR_BYTES_PER_INT64  8
-#define PR_BYTES_PER_LONG   4
-#define PR_BYTES_PER_FLOAT  4
-#define PR_BYTES_PER_DOUBLE 8
-#define PR_BYTES_PER_WORD   4
-#define PR_BYTES_PER_DWORD  8
-
-#define PR_BITS_PER_BYTE    8
-#define PR_BITS_PER_SHORT   16
-#define PR_BITS_PER_INT     32
-#define PR_BITS_PER_INT64   64
-#define PR_BITS_PER_LONG    32
-#define PR_BITS_PER_FLOAT   32
-#define PR_BITS_PER_DOUBLE  64
-#define PR_BITS_PER_WORD    32
-
-#define PR_BITS_PER_BYTE_LOG2   3
-#define PR_BITS_PER_SHORT_LOG2  4
-#define PR_BITS_PER_INT_LOG2    5
-#define PR_BITS_PER_INT64_LOG2  6
-#define PR_BITS_PER_LONG_LOG2   5
-#define PR_BITS_PER_FLOAT_LOG2  5
-#define PR_BITS_PER_DOUBLE_LOG2 6
-#define PR_BITS_PER_WORD_LOG2   5
-
-#define PR_ALIGN_OF_SHORT   2
-#define PR_ALIGN_OF_INT     4
-#define PR_ALIGN_OF_LONG    4
-#define PR_ALIGN_OF_INT64   8
-#define PR_ALIGN_OF_FLOAT   4
-#define PR_ALIGN_OF_DOUBLE  8
-#define PR_ALIGN_OF_POINTER 4
-#define PR_ALIGN_OF_WORD    4
-
-#define PR_BYTES_PER_WORD_LOG2   2
-#define PR_BYTES_PER_DWORD_LOG2  3
-
-#elif defined(__s390x__)
-
-#define IS_BIG_ENDIAN 1
-#undef  IS_LITTLE_ENDIAN
-#define IS_64
-
-#define PR_BYTES_PER_BYTE   1
-#define PR_BYTES_PER_SHORT  2
-#define PR_BYTES_PER_INT    4
-#define PR_BYTES_PER_INT64  8
-#define PR_BYTES_PER_LONG   8
-#define PR_BYTES_PER_FLOAT  4
-#define PR_BYTES_PER_DOUBLE 8
-#define PR_BYTES_PER_WORD   8
-#define PR_BYTES_PER_DWORD  8
-
-#define PR_BITS_PER_BYTE    8
-#define PR_BITS_PER_SHORT   16
-#define PR_BITS_PER_INT     32
-#define PR_BITS_PER_INT64   64
-#define PR_BITS_PER_LONG    64
-#define PR_BITS_PER_FLOAT   32
-#define PR_BITS_PER_DOUBLE  64
-#define PR_BITS_PER_WORD    64
-
-#define PR_BITS_PER_BYTE_LOG2   3
-#define PR_BITS_PER_SHORT_LOG2  4
-#define PR_BITS_PER_INT_LOG2    5
-#define PR_BITS_PER_INT64_LOG2  6
-#define PR_BITS_PER_LONG_LOG2   6
-#define PR_BITS_PER_FLOAT_LOG2  5
-#define PR_BITS_PER_DOUBLE_LOG2 6
-#define PR_BITS_PER_WORD_LOG2   6
-
-#define PR_ALIGN_OF_SHORT   2
-#define PR_ALIGN_OF_INT     4
-#define PR_ALIGN_OF_LONG    8
-#define PR_ALIGN_OF_INT64   8
-#define PR_ALIGN_OF_FLOAT   4
-#define PR_ALIGN_OF_DOUBLE  8
-#define PR_ALIGN_OF_POINTER 8
-#define PR_ALIGN_OF_WORD    8
-
-#define PR_BYTES_PER_WORD_LOG2   3
-#define PR_BYTES_PER_DWORD_LOG2  3
-
-#elif defined(__s390__)
-
-#define IS_BIG_ENDIAN 1
-#undef  IS_LITTLE_ENDIAN
-
-#define PR_BYTES_PER_BYTE   1
-#define PR_BYTES_PER_SHORT  2
-#define PR_BYTES_PER_INT    4
-#define PR_BYTES_PER_INT64  8
-#define PR_BYTES_PER_LONG   4
-#define PR_BYTES_PER_FLOAT  4
-#define PR_BYTES_PER_DOUBLE 8
-#define PR_BYTES_PER_WORD   4
-#define PR_BYTES_PER_DWORD  8
-
-#define PR_BITS_PER_BYTE    8
-#define PR_BITS_PER_SHORT   16
-#define PR_BITS_PER_INT     32
-#define PR_BITS_PER_INT64   64
-#define PR_BITS_PER_LONG    32
-#define PR_BITS_PER_FLOAT   32
-#define PR_BITS_PER_DOUBLE  64
-#define PR_BITS_PER_WORD    32
-
-#define PR_BITS_PER_BYTE_LOG2   3
-#define PR_BITS_PER_SHORT_LOG2  4
-#define PR_BITS_PER_INT_LOG2    5
-#define PR_BITS_PER_INT64_LOG2  6
-#define PR_BITS_PER_LONG_LOG2   5
-#define PR_BITS_PER_FLOAT_LOG2  5
-#define PR_BITS_PER_DOUBLE_LOG2 6
-#define PR_BITS_PER_WORD_LOG2   5
-
-#define PR_ALIGN_OF_SHORT   2
-#define PR_ALIGN_OF_INT     4
-#define PR_ALIGN_OF_LONG    4
-#define PR_ALIGN_OF_INT64   4
-#define PR_ALIGN_OF_FLOAT   4
-#define PR_ALIGN_OF_DOUBLE  4
-#define PR_ALIGN_OF_POINTER 4
-#define PR_ALIGN_OF_WORD    4
-
-#define PR_BYTES_PER_WORD_LOG2   2
-#define PR_BYTES_PER_DWORD_LOG2  3
-
-#else
-
-#error "Unknown CPU architecture"
-
-#endif
-
-#ifndef HAVE_LONG_LONG
-#define	HAVE_LONG_LONG
-#endif
-#if PR_ALIGN_OF_DOUBLE == 8
-#define HAVE_ALIGNED_DOUBLES
-#endif
-#if PR_ALIGN_OF_INT64 == 8
-#define HAVE_ALIGNED_LONGLONGS
-#endif
-
-#ifndef NO_NSPR_10_SUPPORT
-
-#define BYTES_PER_BYTE		PR_BYTES_PER_BYTE
-#define BYTES_PER_SHORT 	PR_BYTES_PER_SHORT
-#define BYTES_PER_INT 		PR_BYTES_PER_INT
-#define BYTES_PER_INT64		PR_BYTES_PER_INT64
-#define BYTES_PER_LONG		PR_BYTES_PER_LONG
-#define BYTES_PER_FLOAT		PR_BYTES_PER_FLOAT
-#define BYTES_PER_DOUBLE	PR_BYTES_PER_DOUBLE
-#define BYTES_PER_WORD		PR_BYTES_PER_WORD
-#define BYTES_PER_DWORD		PR_BYTES_PER_DWORD
-
-#define BITS_PER_BYTE		PR_BITS_PER_BYTE
-#define BITS_PER_SHORT		PR_BITS_PER_SHORT
-#define BITS_PER_INT		PR_BITS_PER_INT
-#define BITS_PER_INT64		PR_BITS_PER_INT64
-#define BITS_PER_LONG		PR_BITS_PER_LONG
-#define BITS_PER_FLOAT		PR_BITS_PER_FLOAT
-#define BITS_PER_DOUBLE		PR_BITS_PER_DOUBLE
-#define BITS_PER_WORD		PR_BITS_PER_WORD
-
-#define BITS_PER_BYTE_LOG2	PR_BITS_PER_BYTE_LOG2
-#define BITS_PER_SHORT_LOG2	PR_BITS_PER_SHORT_LOG2
-#define BITS_PER_INT_LOG2	PR_BITS_PER_INT_LOG2
-#define BITS_PER_INT64_LOG2	PR_BITS_PER_INT64_LOG2
-#define BITS_PER_LONG_LOG2	PR_BITS_PER_LONG_LOG2
-#define BITS_PER_FLOAT_LOG2	PR_BITS_PER_FLOAT_LOG2
-#define BITS_PER_DOUBLE_LOG2 	PR_BITS_PER_DOUBLE_LOG2
-#define BITS_PER_WORD_LOG2	PR_BITS_PER_WORD_LOG2
-
-#define ALIGN_OF_SHORT		PR_ALIGN_OF_SHORT
-#define ALIGN_OF_INT		PR_ALIGN_OF_INT
-#define ALIGN_OF_LONG		PR_ALIGN_OF_LONG
-#define ALIGN_OF_INT64		PR_ALIGN_OF_INT64
-#define ALIGN_OF_FLOAT		PR_ALIGN_OF_FLOAT
-#define ALIGN_OF_DOUBLE		PR_ALIGN_OF_DOUBLE
-#define ALIGN_OF_POINTER	PR_ALIGN_OF_POINTER
-#define ALIGN_OF_WORD		PR_ALIGN_OF_WORD
-
-#define BYTES_PER_WORD_LOG2	PR_BYTES_PER_WORD_LOG2
-#define BYTES_PER_DWORD_LOG2	PR_BYTES_PER_DWORD_LOG2
-#define WORDS_PER_DWORD_LOG2	PR_WORDS_PER_DWORD_LOG2
-
-#endif /* NO_NSPR_10_SUPPORT */
-
-#endif /* nspr_cpucfg___ */
diff -r fcf435874395 -r 45c889eae324 front_idill/extern/fajran-npTuioClient/npapi/prcpucfg-win32.h
--- a/front_idill/extern/fajran-npTuioClient/npapi/prcpucfg-win32.h	Thu Apr 19 11:53:06 2012 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,300 +0,0 @@
-/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* ***** BEGIN LICENSE BLOCK *****
- * Version: MPL 1.1/GPL 2.0/LGPL 2.1
- *
- * The contents of this file are subject to the Mozilla Public License Version
- * 1.1 (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- * http://www.mozilla.org/MPL/
- *
- * Software distributed under the License is distributed on an "AS IS" basis,
- * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
- * for the specific language governing rights and limitations under the
- * License.
- *
- * The Original Code is the Netscape Portable Runtime (NSPR).
- *
- * The Initial Developer of the Original Code is
- * Netscape Communications Corporation.
- * Portions created by the Initial Developer are Copyright (C) 1998-2000
- * the Initial Developer. All Rights Reserved.
- *
- * Contributor(s):
- *
- * Alternatively, the contents of this file may be used under the terms of
- * either the GNU General Public License Version 2 or later (the "GPL"), or
- * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
- * in which case the provisions of the GPL or the LGPL are applicable instead
- * of those above. If you wish to allow use of your version of this file only
- * under the terms of either the GPL or the LGPL, and not to allow others to
- * use your version of this file under the terms of the MPL, indicate your
- * decision by deleting the provisions above and replace them with the notice
- * and other provisions required by the GPL or the LGPL. If you do not delete
- * the provisions above, a recipient may use your version of this file under
- * the terms of any one of the MPL, the GPL or the LGPL.
- *
- * ***** END LICENSE BLOCK ***** */
-
-#ifndef nspr_cpucfg___
-#define nspr_cpucfg___
-
-#ifndef XP_PC
-#define XP_PC
-#endif
-
-#ifndef WIN32
-#define WIN32
-#endif
-
-#ifndef WIN95
-#define WIN95
-#endif
-
-#define PR_AF_INET6 23  /* same as AF_INET6 */
-
-#if defined(_M_IX86) || defined(_X86_)
-
-#define IS_LITTLE_ENDIAN 1
-#undef  IS_BIG_ENDIAN
-
-#define PR_BYTES_PER_BYTE   1
-#define PR_BYTES_PER_SHORT  2
-#define PR_BYTES_PER_INT    4
-#define PR_BYTES_PER_INT64  8
-#define PR_BYTES_PER_LONG   4
-#define PR_BYTES_PER_FLOAT  4
-#define PR_BYTES_PER_WORD	4
-#define PR_BYTES_PER_DWORD	8
-#define PR_BYTES_PER_DOUBLE 8
-
-#define PR_BITS_PER_BYTE    8
-#define PR_BITS_PER_SHORT   16
-#define PR_BITS_PER_INT     32
-#define PR_BITS_PER_INT64   64
-#define PR_BITS_PER_LONG    32
-#define PR_BITS_PER_FLOAT   32
-#define PR_BITS_PER_WORD	32
-#define PR_BITS_PER_DWORD	64
-#define PR_BITS_PER_DOUBLE  64
-
-#define PR_BITS_PER_BYTE_LOG2   3
-#define PR_BITS_PER_SHORT_LOG2  4
-#define PR_BITS_PER_INT_LOG2    5
-#define PR_BITS_PER_INT64_LOG2  6
-#define PR_BITS_PER_LONG_LOG2   5
-#define PR_BITS_PER_FLOAT_LOG2  5
-#define PR_BITS_PER_WORD_LOG2	5
-#define PR_BITS_PER_DWORD_LOG2	6
-#define PR_BITS_PER_DOUBLE_LOG2 6
-
-#define PR_ALIGN_OF_SHORT   2
-#define PR_ALIGN_OF_INT     4
-#define PR_ALIGN_OF_LONG    4
-#define PR_ALIGN_OF_INT64   8
-#define PR_ALIGN_OF_FLOAT   4
-#define PR_ALIGN_OF_WORD	4
-#define PR_ALIGN_OF_DWORD	8
-#define PR_ALIGN_OF_DOUBLE  4
-#define PR_ALIGN_OF_POINTER 4
-
-#define PR_BYTES_PER_WORD_LOG2	2
-#define PR_BYTES_PER_DWORD_LOG2	2
-
-#elif defined(_ALPHA_)
-
-#define IS_LITTLE_ENDIAN 1
-#undef  IS_BIG_ENDIAN
-
-#define PR_BYTES_PER_BYTE   1
-#define PR_BYTES_PER_SHORT  2
-#define PR_BYTES_PER_INT    4
-#define PR_BYTES_PER_INT64  8
-#define PR_BYTES_PER_LONG   4
-#define PR_BYTES_PER_FLOAT  4
-#define PR_BYTES_PER_DOUBLE 8
-#define PR_BYTES_PER_WORD   4
-#define PR_BYTES_PER_DWORD  8
-
-#define PR_BITS_PER_BYTE    8
-#define PR_BITS_PER_SHORT   16
-#define PR_BITS_PER_INT     32
-#define PR_BITS_PER_INT64   64
-#define PR_BITS_PER_LONG    32
-#define PR_BITS_PER_FLOAT   32
-#define PR_BITS_PER_DOUBLE  64
-#define PR_BITS_PER_WORD    32
-
-#define PR_BITS_PER_BYTE_LOG2   3
-#define PR_BITS_PER_SHORT_LOG2  4
-#define PR_BITS_PER_INT_LOG2    5
-#define PR_BITS_PER_INT64_LOG2  6
-#define PR_BITS_PER_LONG_LOG2   5
-#define PR_BITS_PER_FLOAT_LOG2  5
-#define PR_BITS_PER_DOUBLE_LOG2 6
-#define PR_BITS_PER_WORD_LOG2   5
-
-#define PR_BYTES_PER_WORD_LOG2  2
-#define PR_BYTES_PER_DWORD_LOG2 3
-
-#define PR_ALIGN_OF_SHORT   2
-#define PR_ALIGN_OF_INT     4
-#define PR_ALIGN_OF_LONG    4
-#define PR_ALIGN_OF_INT64   8
-#define PR_ALIGN_OF_FLOAT   4
-#define PR_ALIGN_OF_DOUBLE  8
-#define PR_ALIGN_OF_POINTER 4
-
-#elif defined(_AMD64_)
-
-#define IS_LITTLE_ENDIAN 1
-#undef  IS_BIG_ENDIAN
-#define IS_64
-
-#define PR_BYTES_PER_BYTE   1
-#define PR_BYTES_PER_SHORT  2
-#define PR_BYTES_PER_INT    4
-#define PR_BYTES_PER_INT64  8
-#define PR_BYTES_PER_LONG   4
-#define PR_BYTES_PER_FLOAT  4
-#define PR_BYTES_PER_WORD	8
-#define PR_BYTES_PER_DWORD	8
-#define PR_BYTES_PER_DOUBLE 8
-
-#define PR_BITS_PER_BYTE    8
-#define PR_BITS_PER_SHORT   16
-#define PR_BITS_PER_INT     32
-#define PR_BITS_PER_INT64   64
-#define PR_BITS_PER_LONG    32
-#define PR_BITS_PER_FLOAT   32
-#define PR_BITS_PER_WORD	64
-#define PR_BITS_PER_DWORD	64
-#define PR_BITS_PER_DOUBLE  64
-
-#define PR_BITS_PER_BYTE_LOG2   3
-#define PR_BITS_PER_SHORT_LOG2  4
-#define PR_BITS_PER_INT_LOG2    5
-#define PR_BITS_PER_INT64_LOG2  6
-#define PR_BITS_PER_LONG_LOG2   5
-#define PR_BITS_PER_FLOAT_LOG2  5
-#define PR_BITS_PER_WORD_LOG2	6
-#define PR_BITS_PER_DWORD_LOG2	6
-#define PR_BITS_PER_DOUBLE_LOG2 6
-
-#define PR_ALIGN_OF_SHORT   2
-#define PR_ALIGN_OF_INT     4
-#define PR_ALIGN_OF_LONG    4
-#define PR_ALIGN_OF_INT64   8
-#define PR_ALIGN_OF_FLOAT   4
-#define PR_ALIGN_OF_WORD	8
-#define PR_ALIGN_OF_DWORD	8
-#define PR_ALIGN_OF_DOUBLE  8
-#define PR_ALIGN_OF_POINTER 8
-
-#define PR_BYTES_PER_WORD_LOG2	3
-#define PR_BYTES_PER_DWORD_LOG2	3
-
-#elif defined(_IA64_)
-
-#define IS_LITTLE_ENDIAN 1
-#undef  IS_BIG_ENDIAN
-#define IS_64
-
-#define PR_BYTES_PER_BYTE   1
-#define PR_BYTES_PER_SHORT  2
-#define PR_BYTES_PER_INT    4
-#define PR_BYTES_PER_INT64  8
-#define PR_BYTES_PER_LONG   4
-#define PR_BYTES_PER_FLOAT  4
-#define PR_BYTES_PER_WORD	8
-#define PR_BYTES_PER_DWORD	8
-#define PR_BYTES_PER_DOUBLE 8
-
-#define PR_BITS_PER_BYTE    8
-#define PR_BITS_PER_SHORT   16
-#define PR_BITS_PER_INT     32
-#define PR_BITS_PER_INT64   64
-#define PR_BITS_PER_LONG    32
-#define PR_BITS_PER_FLOAT   32
-#define PR_BITS_PER_WORD	64
-#define PR_BITS_PER_DWORD	64
-#define PR_BITS_PER_DOUBLE  64
-
-#define PR_BITS_PER_BYTE_LOG2   3
-#define PR_BITS_PER_SHORT_LOG2  4
-#define PR_BITS_PER_INT_LOG2    5
-#define PR_BITS_PER_INT64_LOG2  6
-#define PR_BITS_PER_LONG_LOG2   5
-#define PR_BITS_PER_FLOAT_LOG2  5
-#define PR_BITS_PER_WORD_LOG2	6
-#define PR_BITS_PER_DWORD_LOG2	6
-#define PR_BITS_PER_DOUBLE_LOG2 6
-
-#define PR_ALIGN_OF_SHORT   2
-#define PR_ALIGN_OF_INT     4
-#define PR_ALIGN_OF_LONG    4
-#define PR_ALIGN_OF_INT64   8
-#define PR_ALIGN_OF_FLOAT   4
-#define PR_ALIGN_OF_WORD	8
-#define PR_ALIGN_OF_DWORD	8
-#define PR_ALIGN_OF_DOUBLE  8
-#define PR_ALIGN_OF_POINTER 8
-
-#define PR_BYTES_PER_WORD_LOG2	3
-#define PR_BYTES_PER_DWORD_LOG2	3
-
-#else /* defined(_M_IX86) || defined(_X86_) */
-
-#error unknown processor architecture
-
-#endif /* defined(_M_IX86) || defined(_X86_) */
-
-#ifndef HAVE_LONG_LONG
-#define HAVE_LONG_LONG
-#endif
-
-#ifndef NO_NSPR_10_SUPPORT
-
-#define BYTES_PER_BYTE      PR_BYTES_PER_BYTE
-#define BYTES_PER_SHORT     PR_BYTES_PER_SHORT
-#define BYTES_PER_INT       PR_BYTES_PER_INT
-#define BYTES_PER_INT64     PR_BYTES_PER_INT64
-#define BYTES_PER_LONG      PR_BYTES_PER_LONG
-#define BYTES_PER_FLOAT     PR_BYTES_PER_FLOAT
-#define BYTES_PER_DOUBLE    PR_BYTES_PER_DOUBLE
-#define BYTES_PER_WORD      PR_BYTES_PER_WORD
-#define BYTES_PER_DWORD     PR_BYTES_PER_DWORD
-
-#define BITS_PER_BYTE       PR_BITS_PER_BYTE
-#define BITS_PER_SHORT      PR_BITS_PER_SHORT
-#define BITS_PER_INT        PR_BITS_PER_INT
-#define BITS_PER_INT64      PR_BITS_PER_INT64
-#define BITS_PER_LONG       PR_BITS_PER_LONG
-#define BITS_PER_FLOAT      PR_BITS_PER_FLOAT
-#define BITS_PER_DOUBLE     PR_BITS_PER_DOUBLE
-#define BITS_PER_WORD       PR_BITS_PER_WORD
-
-#define BITS_PER_BYTE_LOG2  PR_BITS_PER_BYTE_LOG2
-#define BITS_PER_SHORT_LOG2 PR_BITS_PER_SHORT_LOG2
-#define BITS_PER_INT_LOG2   PR_BITS_PER_INT_LOG2
-#define BITS_PER_INT64_LOG2 PR_BITS_PER_INT64_LOG2
-#define BITS_PER_LONG_LOG2  PR_BITS_PER_LONG_LOG2
-#define BITS_PER_FLOAT_LOG2 PR_BITS_PER_FLOAT_LOG2
-#define BITS_PER_DOUBLE_LOG2    PR_BITS_PER_DOUBLE_LOG2
-#define BITS_PER_WORD_LOG2  PR_BITS_PER_WORD_LOG2
-
-#define ALIGN_OF_SHORT      PR_ALIGN_OF_SHORT
-#define ALIGN_OF_INT        PR_ALIGN_OF_INT
-#define ALIGN_OF_LONG       PR_ALIGN_OF_LONG
-#define ALIGN_OF_INT64      PR_ALIGN_OF_INT64
-#define ALIGN_OF_FLOAT      PR_ALIGN_OF_FLOAT
-#define ALIGN_OF_DOUBLE     PR_ALIGN_OF_DOUBLE
-#define ALIGN_OF_POINTER    PR_ALIGN_OF_POINTER
-#define ALIGN_OF_WORD       PR_ALIGN_OF_WORD
-
-#define BYTES_PER_WORD_LOG2		PR_BYTES_PER_WORD_LOG2
-#define BYTES_PER_DWORD_LOG2    PR_BYTES_PER_DWORD_LOG2
-#define WORDS_PER_DWORD_LOG2    PR_WORDS_PER_DWORD_LOG2
-
-#endif /* NO_NSPR_10_SUPPORT */
-
-#endif /* nspr_cpucfg___ */
diff -r fcf435874395 -r 45c889eae324 front_idill/extern/fajran-npTuioClient/npapi/prcpucfg.h
--- a/front_idill/extern/fajran-npTuioClient/npapi/prcpucfg.h	Thu Apr 19 11:53:06 2012 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,23 +0,0 @@
-// 
-//   Copyright (C) 2005, 2006, 2007, 2008, 2009 Free Software Foundation, Inc.
-// 
-// 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, write to the Free Software
-// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
-//
-
-#ifdef _WIN32
-#include "prcpucfg-win32.h"
-#else
-#include "prcpucfg-glibc.h"
-#endif
diff -r fcf435874395 -r 45c889eae324 front_idill/extern/fajran-npTuioClient/npapi/protypes.h
--- a/front_idill/extern/fajran-npTuioClient/npapi/protypes.h	Thu Apr 19 11:53:06 2012 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,252 +0,0 @@
-/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* ***** BEGIN LICENSE BLOCK *****
- * Version: MPL 1.1/GPL 2.0/LGPL 2.1
- *
- * The contents of this file are subject to the Mozilla Public License Version
- * 1.1 (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- * http://www.mozilla.org/MPL/
- *
- * Software distributed under the License is distributed on an "AS IS" basis,
- * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
- * for the specific language governing rights and limitations under the
- * License.
- *
- * The Original Code is the Netscape Portable Runtime (NSPR).
- *
- * The Initial Developer of the Original Code is
- * Netscape Communications Corporation.
- * Portions created by the Initial Developer are Copyright (C) 1998-2000
- * the Initial Developer. All Rights Reserved.
- *
- * Contributor(s):
- *
- * Alternatively, the contents of this file may be used under the terms of
- * either the GNU General Public License Version 2 or later (the "GPL"), or
- * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
- * in which case the provisions of the GPL or the LGPL are applicable instead
- * of those above. If you wish to allow use of your version of this file only
- * under the terms of either the GPL or the LGPL, and not to allow others to
- * use your version of this file under the terms of the MPL, indicate your
- * decision by deleting the provisions above and replace them with the notice
- * and other provisions required by the GPL or the LGPL. If you do not delete
- * the provisions above, a recipient may use your version of this file under
- * the terms of any one of the MPL, the GPL or the LGPL.
- *
- * ***** END LICENSE BLOCK ***** */
-
-/*
- * This header typedefs the old 'native' types to the new PRs.
- * These definitions are scheduled to be eliminated at the earliest
- * possible time. The NSPR API is implemented and documented using
- * the new definitions.
- */
-
-#if !defined(PROTYPES_H)
-#define PROTYPES_H
-
-typedef PRUintn uintn;
-#ifndef _XP_Core_
-typedef PRIntn intn;
-#endif
-
-/*
- * It is trickier to define uint, int8, uint8, int16, uint16,
- * int32, uint32, int64, and uint64 because some of these int
- * types are defined by standard header files on some platforms.
- * Our strategy here is to include all such standard headers
- * first, and then define these int types only if they are not
- * defined by those standard headers.
- */
-
-/*
- * BeOS defines all the int types below in its standard header
- * file SupportDefs.h.
- */
-#ifdef XP_BEOS
-#include 
-#endif
-
-/*
- * OpenVMS defines all the int types below in its standard
- * header files ints.h and types.h.
- */
-#ifdef VMS
-#include 
-#include 
-#endif
-
-/*
- * SVR4 typedef of uint is commonly found on UNIX machines.
- *
- * On AIX 4.3, sys/inttypes.h (which is included by sys/types.h)
- * defines the types int8, int16, int32, and int64.
- */
-#ifdef XP_UNIX
-#include 
-#endif
-
-/* model.h on HP-UX defines int8, int16, and int32. */
-#ifdef HPUX
-#include 
-#endif
-
-/*
- * uint
- */
-
-#if !defined(XP_BEOS) && !defined(VMS) \
-    && !defined(XP_UNIX) || defined(NTO)
-typedef PRUintn uint;
-#endif
-
-/*
- * uint64
- */
-
-#if !defined(XP_BEOS) && !defined(VMS)
-typedef PRUint64 uint64;
-#endif
-
-/*
- * uint32
- */
-
-#if !defined(XP_BEOS) && !defined(VMS)
-#if !defined(XP_MAC) && !defined(_WIN32) && !defined(XP_OS2) && !defined(NTO)
-typedef PRUint32 uint32;
-#else
-typedef unsigned long uint32;
-#endif
-#endif
-
-/*
- * uint16
- */
-
-#if !defined(XP_BEOS) && !defined(VMS)
-typedef PRUint16 uint16;
-#endif
-
-/*
- * uint8
- */
-
-#if !defined(XP_BEOS) && !defined(VMS)
-typedef PRUint8 uint8;
-#endif
-
-/*
- * int64
- */
-
-#if !defined(XP_BEOS) && !defined(VMS) \
-    && !defined(_PR_AIX_HAVE_BSD_INT_TYPES)
-typedef PRInt64 int64;
-#endif
-
-/*
- * int32
- */
-
-#if !defined(XP_BEOS) && !defined(VMS) \
-    && !defined(_PR_AIX_HAVE_BSD_INT_TYPES) \
-    && !defined(HPUX)
-#if !defined(XP_MAC) && !defined(_WIN32) && !defined(XP_OS2) && !defined(NTO)
-typedef PRInt32 int32;
-#else
-typedef long int32;
-#endif
-#endif
-
-/*
- * int16
- */
-
-#if !defined(XP_BEOS) && !defined(VMS) \
-    && !defined(_PR_AIX_HAVE_BSD_INT_TYPES) \
-    && !defined(HPUX)
-typedef PRInt16 int16;
-#endif
-
-/*
- * int8
- */
-
-#if !defined(XP_BEOS) && !defined(VMS) \
-    && !defined(_PR_AIX_HAVE_BSD_INT_TYPES) \
-    && !defined(HPUX)
-typedef PRInt8 int8;
-#endif
-
-typedef PRFloat64 float64;
-typedef PRUptrdiff uptrdiff_t;
-typedef PRUword uprword_t;
-typedef PRWord prword_t;
-
-
-/* Re: prbit.h */
-#define TEST_BIT	PR_TEST_BIT
-#define SET_BIT		PR_SET_BIT
-#define CLEAR_BIT	PR_CLEAR_BIT
-
-/* Re: prarena.h->plarena.h */
-#define PRArena PLArena
-#define PRArenaPool PLArenaPool
-#define PRArenaStats PLArenaStats
-#define PR_ARENA_ALIGN PL_ARENA_ALIGN
-#define PR_INIT_ARENA_POOL PL_INIT_ARENA_POOL
-#define PR_ARENA_ALLOCATE PL_ARENA_ALLOCATE
-#define PR_ARENA_GROW PL_ARENA_GROW
-#define PR_ARENA_MARK PL_ARENA_MARK
-#define PR_CLEAR_UNUSED PL_CLEAR_UNUSED
-#define PR_CLEAR_ARENA PL_CLEAR_ARENA
-#define PR_ARENA_RELEASE PL_ARENA_RELEASE
-#define PR_COUNT_ARENA PL_COUNT_ARENA
-#define PR_ARENA_DESTROY PL_ARENA_DESTROY
-#define PR_InitArenaPool PL_InitArenaPool
-#define PR_FreeArenaPool PL_FreeArenaPool
-#define PR_FinishArenaPool PL_FinishArenaPool
-#define PR_CompactArenaPool PL_CompactArenaPool
-#define PR_ArenaFinish PL_ArenaFinish
-#define PR_ArenaAllocate PL_ArenaAllocate
-#define PR_ArenaGrow PL_ArenaGrow
-#define PR_ArenaRelease PL_ArenaRelease
-#define PR_ArenaCountAllocation PL_ArenaCountAllocation
-#define PR_ArenaCountInplaceGrowth PL_ArenaCountInplaceGrowth
-#define PR_ArenaCountGrowth PL_ArenaCountGrowth
-#define PR_ArenaCountRelease PL_ArenaCountRelease
-#define PR_ArenaCountRetract PL_ArenaCountRetract
-
-/* Re: prhash.h->plhash.h */
-#define PRHashEntry PLHashEntry
-#define PRHashTable PLHashTable
-#define PRHashNumber PLHashNumber
-#define PRHashFunction PLHashFunction
-#define PRHashComparator PLHashComparator
-#define PRHashEnumerator PLHashEnumerator
-#define PRHashAllocOps PLHashAllocOps
-#define PR_NewHashTable PL_NewHashTable
-#define PR_HashTableDestroy PL_HashTableDestroy
-#define PR_HashTableRawLookup PL_HashTableRawLookup
-#define PR_HashTableRawAdd PL_HashTableRawAdd
-#define PR_HashTableRawRemove PL_HashTableRawRemove
-#define PR_HashTableAdd PL_HashTableAdd
-#define PR_HashTableRemove PL_HashTableRemove
-#define PR_HashTableEnumerateEntries PL_HashTableEnumerateEntries
-#define PR_HashTableLookup PL_HashTableLookup
-#define PR_HashTableDump PL_HashTableDump
-#define PR_HashString PL_HashString
-#define PR_CompareStrings PL_CompareStrings
-#define PR_CompareValues PL_CompareValues
-
-#if defined(XP_MAC)
-#ifndef TRUE				/* Mac standard is lower case true */
-	#define TRUE 1
-#endif
-#ifndef FALSE				/* Mac standard is lower case false */
-	#define FALSE 0
-#endif
-#endif
-
-#endif /* !defined(PROTYPES_H) */
diff -r fcf435874395 -r 45c889eae324 front_idill/extern/fajran-npTuioClient/npapi/prtypes.h
--- a/front_idill/extern/fajran-npTuioClient/npapi/prtypes.h	Thu Apr 19 11:53:06 2012 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,575 +0,0 @@
-/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* ***** BEGIN LICENSE BLOCK *****
- * Version: MPL 1.1/GPL 2.0/LGPL 2.1
- *
- * The contents of this file are subject to the Mozilla Public License Version
- * 1.1 (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- * http://www.mozilla.org/MPL/
- *
- * Software distributed under the License is distributed on an "AS IS" basis,
- * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
- * for the specific language governing rights and limitations under the
- * License.
- *
- * The Original Code is the Netscape Portable Runtime (NSPR).
- *
- * The Initial Developer of the Original Code is
- * Netscape Communications Corporation.
- * Portions created by the Initial Developer are Copyright (C) 1998-2000
- * the Initial Developer. All Rights Reserved.
- *
- * Contributor(s):
- *
- * Alternatively, the contents of this file may be used under the terms of
- * either the GNU General Public License Version 2 or later (the "GPL"), or
- * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
- * in which case the provisions of the GPL or the LGPL are applicable instead
- * of those above. If you wish to allow use of your version of this file only
- * under the terms of either the GPL or the LGPL, and not to allow others to
- * use your version of this file under the terms of the MPL, indicate your
- * decision by deleting the provisions above and replace them with the notice
- * and other provisions required by the GPL or the LGPL. If you do not delete
- * the provisions above, a recipient may use your version of this file under
- * the terms of any one of the MPL, the GPL or the LGPL.
- *
- * ***** END LICENSE BLOCK ***** */
-
-/*
-** File:                prtypes.h
-** Description: Definitions of NSPR's basic types
-**
-** Prototypes and macros used to make up for deficiencies that we have found
-** in ANSI environments.
-**
-** Since we do not wrap  and all the other standard headers, authors
-** of portable code will not know in general that they need these definitions.
-** Instead of requiring these authors to find the dependent uses in their code
-** and take the following steps only in those C files, we take steps once here
-** for all C files.
-**/
-
-#ifndef prtypes_h___
-#define prtypes_h___
-
-#ifdef MDCPUCFG
-#include MDCPUCFG
-#else
-#include "prcpucfg.h"
-#endif
-
-#include 
-
-/***********************************************************************
-** MACROS:      PR_EXTERN
-**              PR_IMPLEMENT
-** DESCRIPTION:
-**      These are only for externally visible routines and globals.  For
-**      internal routines, just use "extern" for type checking and that
-**      will not export internal cross-file or forward-declared symbols.
-**      Define a macro for declaring procedures return types. We use this to
-**      deal with windoze specific type hackery for DLL definitions. Use
-**      PR_EXTERN when the prototype for the method is declared. Use
-**      PR_IMPLEMENT for the implementation of the method.
-**
-** Example:
-**   in dowhim.h
-**     PR_EXTERN( void ) DoWhatIMean( void );
-**   in dowhim.c
-**     PR_IMPLEMENT( void ) DoWhatIMean( void ) { return; }
-**
-**
-***********************************************************************/
-#if defined(WIN32)
-
-#define PR_EXPORT(__type) extern __declspec(dllexport) __type
-#define PR_EXPORT_DATA(__type) extern __declspec(dllexport) __type
-#define PR_IMPORT(__type) __declspec(dllimport) __type
-#define PR_IMPORT_DATA(__type) __declspec(dllimport) __type
-
-#define PR_EXTERN(__type) extern __declspec(dllexport) __type
-#define PR_IMPLEMENT(__type) __declspec(dllexport) __type
-#define PR_EXTERN_DATA(__type) extern __declspec(dllexport) __type
-#define PR_IMPLEMENT_DATA(__type) __declspec(dllexport) __type
-
-#define PR_CALLBACK
-#define PR_CALLBACK_DECL
-#define PR_STATIC_CALLBACK(__x) static __x
-
-#elif defined(XP_BEOS)
-
-#define PR_EXPORT(__type) extern __declspec(dllexport) __type
-#define PR_EXPORT_DATA(__type) extern __declspec(dllexport) __type
-#define PR_IMPORT(__type) extern __declspec(dllexport) __type
-#define PR_IMPORT_DATA(__type) extern __declspec(dllexport) __type
-
-#define PR_EXTERN(__type) extern __declspec(dllexport) __type
-#define PR_IMPLEMENT(__type) __declspec(dllexport) __type
-#define PR_EXTERN_DATA(__type) extern __declspec(dllexport) __type
-#define PR_IMPLEMENT_DATA(__type) __declspec(dllexport) __type
-
-#define PR_CALLBACK
-#define PR_CALLBACK_DECL
-#define PR_STATIC_CALLBACK(__x) static __x
-
-#elif defined(WIN16)
-
-#define PR_CALLBACK_DECL        __cdecl
-
-#if defined(_WINDLL)
-#define PR_EXPORT(__type) extern __type _cdecl _export _loadds
-#define PR_IMPORT(__type) extern __type _cdecl _export _loadds
-#define PR_EXPORT_DATA(__type) extern __type _export
-#define PR_IMPORT_DATA(__type) extern __type _export
-
-#define PR_EXTERN(__type) extern __type _cdecl _export _loadds
-#define PR_IMPLEMENT(__type) __type _cdecl _export _loadds
-#define PR_EXTERN_DATA(__type) extern __type _export
-#define PR_IMPLEMENT_DATA(__type) __type _export
-
-#define PR_CALLBACK             __cdecl __loadds
-#define PR_STATIC_CALLBACK(__x) static __x PR_CALLBACK
-
-#else /* this must be .EXE */
-#define PR_EXPORT(__type) extern __type _cdecl _export
-#define PR_IMPORT(__type) extern __type _cdecl _export
-#define PR_EXPORT_DATA(__type) extern __type _export
-#define PR_IMPORT_DATA(__type) extern __type _export
-
-#define PR_EXTERN(__type) extern __type _cdecl _export
-#define PR_IMPLEMENT(__type) __type _cdecl _export
-#define PR_EXTERN_DATA(__type) extern __type _export
-#define PR_IMPLEMENT_DATA(__type) __type _export
-
-#define PR_CALLBACK             __cdecl __loadds
-#define PR_STATIC_CALLBACK(__x) __x PR_CALLBACK
-#endif /* _WINDLL */
-
-#elif defined(XP_MAC)
-
-#define PR_EXPORT(__type) extern __declspec(export) __type
-#define PR_EXPORT_DATA(__type) extern __declspec(export) __type
-#define PR_IMPORT(__type) extern __declspec(export) __type
-#define PR_IMPORT_DATA(__type) extern __declspec(export) __type
-
-#define PR_EXTERN(__type) extern __declspec(export) __type
-#define PR_IMPLEMENT(__type) __declspec(export) __type
-#define PR_EXTERN_DATA(__type) extern __declspec(export) __type
-#define PR_IMPLEMENT_DATA(__type) __declspec(export) __type
-
-#define PR_CALLBACK
-#define PR_CALLBACK_DECL
-#define PR_STATIC_CALLBACK(__x) static __x
-
-#elif defined(XP_OS2) && defined(__declspec)
-
-#define PR_EXPORT(__type) extern __declspec(dllexport) __type
-#define PR_EXPORT_DATA(__type) extern __declspec(dllexport) __type
-#define PR_IMPORT(__type) extern  __declspec(dllimport) __type
-#define PR_IMPORT_DATA(__type) extern __declspec(dllimport) __type
-
-#define PR_EXTERN(__type) extern __declspec(dllexport) __type
-#define PR_IMPLEMENT(__type) __declspec(dllexport) __type
-#define PR_EXTERN_DATA(__type) extern __declspec(dllexport) __type
-#define PR_IMPLEMENT_DATA(__type) __declspec(dllexport) __type
-
-#define PR_CALLBACK
-#define PR_CALLBACK_DECL
-#define PR_STATIC_CALLBACK(__x) static __x
-
-#elif defined(SYMBIAN)
-
-#define PR_EXPORT(__type) extern __declspec(dllexport) __type
-#define PR_EXPORT_DATA(__type) extern __declspec(dllexport) __type
-#ifdef __WINS__
-#define PR_IMPORT(__type) extern __declspec(dllexport) __type
-#define PR_IMPORT_DATA(__type) extern __declspec(dllexport) __type
-#else
-#define PR_IMPORT(__type) extern __declspec(dllimport) __type
-#define PR_IMPORT_DATA(__type) extern __declspec(dllimport) __type
-#endif
-
-#define PR_EXTERN(__type) extern __type
-#define PR_IMPLEMENT(__type) __type
-#define PR_EXTERN_DATA(__type) extern __type
-#define PR_IMPLEMENT_DATA(__type) __type
-
-#define PR_CALLBACK
-#define PR_CALLBACK_DECL
-#define PR_STATIC_CALLBACK(__x) static __x
-
-#else /* Unix */
-
-/* GCC 3.3 and later support the visibility attribute. */
-#if (__GNUC__ >= 4) || \
-    (__GNUC__ == 3 && __GNUC_MINOR__ >= 3)
-#define PR_VISIBILITY_DEFAULT __attribute__((visibility("default")))
-#else
-#define PR_VISIBILITY_DEFAULT
-#endif
-
-#define PR_EXPORT(__type) extern PR_VISIBILITY_DEFAULT __type
-#define PR_EXPORT_DATA(__type) extern PR_VISIBILITY_DEFAULT __type
-#define PR_IMPORT(__type) extern PR_VISIBILITY_DEFAULT __type
-#define PR_IMPORT_DATA(__type) extern PR_VISIBILITY_DEFAULT __type
-
-#define PR_EXTERN(__type) extern PR_VISIBILITY_DEFAULT __type
-#define PR_IMPLEMENT(__type) PR_VISIBILITY_DEFAULT __type
-#define PR_EXTERN_DATA(__type) extern PR_VISIBILITY_DEFAULT __type
-#define PR_IMPLEMENT_DATA(__type) PR_VISIBILITY_DEFAULT __type
-#define PR_CALLBACK
-#define PR_CALLBACK_DECL
-#define PR_STATIC_CALLBACK(__x) static __x
-
-#endif
-
-#if defined(_NSPR_BUILD_)
-#define NSPR_API(__type) PR_EXPORT(__type)
-#define NSPR_DATA_API(__type) PR_EXPORT_DATA(__type)
-#else
-#define NSPR_API(__type) PR_IMPORT(__type)
-#define NSPR_DATA_API(__type) PR_IMPORT_DATA(__type)
-#endif
-
-/***********************************************************************
-** MACROS:      PR_BEGIN_MACRO
-**              PR_END_MACRO
-** DESCRIPTION:
-**      Macro body brackets so that macros with compound statement definitions
-**      behave syntactically more like functions when called.
-***********************************************************************/
-#define PR_BEGIN_MACRO  do {
-#define PR_END_MACRO    } while (0)
-
-/***********************************************************************
-** MACROS:      PR_BEGIN_EXTERN_C
-**              PR_END_EXTERN_C
-** DESCRIPTION:
-**      Macro shorthands for conditional C++ extern block delimiters.
-***********************************************************************/
-#ifdef __cplusplus
-#define PR_BEGIN_EXTERN_C       extern "C" {
-#define PR_END_EXTERN_C         }
-#else
-#define PR_BEGIN_EXTERN_C
-#define PR_END_EXTERN_C
-#endif
-
-/***********************************************************************
-** MACROS:      PR_BIT
-**              PR_BITMASK
-** DESCRIPTION:
-** Bit masking macros.  XXX n must be <= 31 to be portable
-***********************************************************************/
-#define PR_BIT(n)       ((PRUint32)1 << (n))
-#define PR_BITMASK(n)   (PR_BIT(n) - 1)
-
-/***********************************************************************
-** MACROS:      PR_ROUNDUP
-**              PR_MIN
-**              PR_MAX
-**              PR_ABS
-** DESCRIPTION:
-**      Commonly used macros for operations on compatible types.
-***********************************************************************/
-#define PR_ROUNDUP(x,y) ((((x)+((y)-1))/(y))*(y))
-#define PR_MIN(x,y)     ((x)<(y)?(x):(y))
-#define PR_MAX(x,y)     ((x)>(y)?(x):(y))
-#define PR_ABS(x)       ((x)<0?-(x):(x))
-
-PR_BEGIN_EXTERN_C
-
-/************************************************************************
-** TYPES:       PRUint8
-**              PRInt8
-** DESCRIPTION:
-**  The int8 types are known to be 8 bits each. There is no type that
-**      is equivalent to a plain "char". 
-************************************************************************/
-#if PR_BYTES_PER_BYTE == 1
-typedef unsigned char PRUint8;
-/*
-** Some cfront-based C++ compilers do not like 'signed char' and
-** issue the warning message:
-**     warning: "signed" not implemented (ignored)
-** For these compilers, we have to define PRInt8 as plain 'char'.
-** Make sure that plain 'char' is indeed signed under these compilers.
-*/
-#if (defined(HPUX) && defined(__cplusplus) \
-        && !defined(__GNUC__) && __cplusplus < 199707L) \
-    || (defined(SCO) && defined(__cplusplus) \
-        && !defined(__GNUC__) && __cplusplus == 1L)
-typedef char PRInt8;
-#else
-typedef signed char PRInt8;
-#endif
-#else
-#error No suitable type for PRInt8/PRUint8
-#endif
-
-/************************************************************************
- * MACROS:      PR_INT8_MAX
- *              PR_INT8_MIN
- *              PR_UINT8_MAX
- * DESCRIPTION:
- *  The maximum and minimum values of a PRInt8 or PRUint8.
-************************************************************************/
-
-#define PR_INT8_MAX 127
-#define PR_INT8_MIN (-128)
-#define PR_UINT8_MAX 255U
-
-/************************************************************************
-** TYPES:       PRUint16
-**              PRInt16
-** DESCRIPTION:
-**  The int16 types are known to be 16 bits each. 
-************************************************************************/
-#if PR_BYTES_PER_SHORT == 2
-typedef unsigned short PRUint16;
-typedef short PRInt16;
-#else
-#error No suitable type for PRInt16/PRUint16
-#endif
-
-/************************************************************************
- * MACROS:      PR_INT16_MAX
- *              PR_INT16_MIN
- *              PR_UINT16_MAX
- * DESCRIPTION:
- *  The maximum and minimum values of a PRInt16 or PRUint16.
-************************************************************************/
-
-#define PR_INT16_MAX 32767
-#define PR_INT16_MIN (-32768)
-#define PR_UINT16_MAX 65535U
-
-/************************************************************************
-** TYPES:       PRUint32
-**              PRInt32
-** DESCRIPTION:
-**  The int32 types are known to be 32 bits each. 
-************************************************************************/
-#if PR_BYTES_PER_INT == 4
-typedef unsigned int PRUint32;
-typedef int PRInt32;
-#define PR_INT32(x)  x
-#define PR_UINT32(x) x ## U
-#elif PR_BYTES_PER_LONG == 4
-typedef unsigned long PRUint32;
-typedef long PRInt32;
-#define PR_INT32(x)  x ## L
-#define PR_UINT32(x) x ## UL
-#else
-#error No suitable type for PRInt32/PRUint32
-#endif
-
-/************************************************************************
- * MACROS:      PR_INT32_MAX
- *              PR_INT32_MIN
- *              PR_UINT32_MAX
- * DESCRIPTION:
- *  The maximum and minimum values of a PRInt32 or PRUint32.
-************************************************************************/
-
-#define PR_INT32_MAX PR_INT32(2147483647)
-#define PR_INT32_MIN (-PR_INT32_MAX - 1)
-#define PR_UINT32_MAX PR_UINT32(4294967295)
-
-/************************************************************************
-** TYPES:       PRUint64
-**              PRInt64
-** DESCRIPTION:
-**  The int64 types are known to be 64 bits each. Care must be used when
-**      declaring variables of type PRUint64 or PRInt64. Different hardware
-**      architectures and even different compilers have varying support for
-**      64 bit values. The only guaranteed portability requires the use of
-**      the LL_ macros (see prlong.h).
-************************************************************************/
-#ifdef HAVE_LONG_LONG
-#if PR_BYTES_PER_LONG == 8
-typedef long PRInt64;
-typedef unsigned long PRUint64;
-#elif defined(WIN16)
-typedef __int64 PRInt64;
-typedef unsigned __int64 PRUint64;
-#elif defined(WIN32) && !defined(__GNUC__)
-typedef __int64  PRInt64;
-typedef unsigned __int64 PRUint64;
-#else
-typedef long long PRInt64;
-typedef unsigned long long PRUint64;
-#endif /* PR_BYTES_PER_LONG == 8 */
-#else  /* !HAVE_LONG_LONG */
-typedef struct {
-#ifdef IS_LITTLE_ENDIAN
-    PRUint32 lo, hi;
-#else
-    PRUint32 hi, lo;
-#endif
-} PRInt64;
-typedef PRInt64 PRUint64;
-#endif /* !HAVE_LONG_LONG */
-
-/************************************************************************
-** TYPES:       PRUintn
-**              PRIntn
-** DESCRIPTION:
-**  The PRIntn types are most appropriate for automatic variables. They are
-**      guaranteed to be at least 16 bits, though various architectures may
-**      define them to be wider (e.g., 32 or even 64 bits). These types are
-**      never valid for fields of a structure. 
-************************************************************************/
-#if PR_BYTES_PER_INT >= 2
-typedef int PRIntn;
-typedef unsigned int PRUintn;
-#else
-#error 'sizeof(int)' not sufficient for platform use
-#endif
-
-/************************************************************************
-** TYPES:       PRFloat64
-** DESCRIPTION:
-**  NSPR's floating point type is always 64 bits. 
-************************************************************************/
-typedef double          PRFloat64;
-
-/************************************************************************
-** TYPES:       PRSize
-** DESCRIPTION:
-**  A type for representing the size of objects. 
-************************************************************************/
-typedef size_t PRSize;
-
-
-/************************************************************************
-** TYPES:       PROffset32, PROffset64
-** DESCRIPTION:
-**  A type for representing byte offsets from some location. 
-************************************************************************/
-typedef PRInt32 PROffset32;
-typedef PRInt64 PROffset64;
-
-/************************************************************************
-** TYPES:       PRPtrDiff
-** DESCRIPTION:
-**  A type for pointer difference. Variables of this type are suitable
-**      for storing a pointer or pointer subtraction. 
-************************************************************************/
-typedef ptrdiff_t PRPtrdiff;
-
-/************************************************************************
-** TYPES:       PRUptrdiff
-** DESCRIPTION:
-**  A type for pointer difference. Variables of this type are suitable
-**      for storing a pointer or pointer sutraction. 
-************************************************************************/
-#ifdef _WIN64
-typedef unsigned __int64 PRUptrdiff;
-#else
-typedef unsigned long PRUptrdiff;
-#endif
-
-/************************************************************************
-** TYPES:       PRBool
-** DESCRIPTION:
-**  Use PRBool for variables and parameter types. Use PR_FALSE and PR_TRUE
-**      for clarity of target type in assignments and actual arguments. Use
-**      'if (bool)', 'while (!bool)', '(bool) ? x : y' etc., to test booleans
-**      just as you would C int-valued conditions. 
-************************************************************************/
-typedef PRIntn PRBool;
-#define PR_TRUE 1
-#define PR_FALSE 0
-
-/************************************************************************
-** TYPES:       PRPackedBool
-** DESCRIPTION:
-**  Use PRPackedBool within structs where bitfields are not desirable
-**      but minimum and consistant overhead matters.
-************************************************************************/
-typedef PRUint8 PRPackedBool;
-
-/*
-** Status code used by some routines that have a single point of failure or 
-** special status return.
-*/
-typedef enum { PR_FAILURE = -1, PR_SUCCESS = 0 } PRStatus;
-
-#ifndef __PRUNICHAR__
-#define __PRUNICHAR__
-#if defined(WIN32) || defined(XP_MAC)
-typedef wchar_t PRUnichar;
-#else
-typedef PRUint16 PRUnichar;
-#endif
-#endif
-
-/*
-** WARNING: The undocumented data types PRWord and PRUword are
-** only used in the garbage collection and arena code.  Do not
-** use PRWord and PRUword in new code.
-**
-** A PRWord is an integer that is the same size as a void*.
-** It implements the notion of a "word" in the Java Virtual
-** Machine.  (See Sec. 3.4 "Words", The Java Virtual Machine
-** Specification, Addison-Wesley, September 1996.
-** http://java.sun.com/docs/books/vmspec/index.html.)
-*/
-#ifdef _WIN64
-typedef __int64 PRWord;
-typedef unsigned __int64 PRUword;
-#else
-typedef long PRWord;
-typedef unsigned long PRUword;
-#endif
-
-#if defined(NO_NSPR_10_SUPPORT)
-#else
-/********* ???????????????? FIX ME       ??????????????????????????? *****/
-/********************** Some old definitions until pr=>ds transition is done ***/
-/********************** Also, we are still using NSPR 1.0. GC ******************/
-/*
-** Fundamental NSPR macros, used nearly everywhere.
-*/
-
-#define PR_PUBLIC_API		PR_IMPLEMENT
-
-/*
-** Macro body brackets so that macros with compound statement definitions
-** behave syntactically more like functions when called.
-*/
-#define NSPR_BEGIN_MACRO        do {
-#define NSPR_END_MACRO          } while (0)
-
-/*
-** Macro shorthands for conditional C++ extern block delimiters.
-*/
-#ifdef NSPR_BEGIN_EXTERN_C
-#undef NSPR_BEGIN_EXTERN_C
-#endif
-#ifdef NSPR_END_EXTERN_C
-#undef NSPR_END_EXTERN_C
-#endif
-
-#ifdef __cplusplus
-#define NSPR_BEGIN_EXTERN_C     extern "C" {
-#define NSPR_END_EXTERN_C       }
-#else
-#define NSPR_BEGIN_EXTERN_C
-#define NSPR_END_EXTERN_C
-#endif
-
-#ifdef XP_MAC
-#include "protypes.h"
-#else
-#include "obsolete/protypes.h"
-#endif
-
-/********* ????????????? End Fix me ?????????????????????????????? *****/
-#endif /* NO_NSPR_10_SUPPORT */
-
-PR_END_EXTERN_C
-
-#endif /* prtypes_h___ */
-
diff -r fcf435874395 -r 45c889eae324 front_idill/extern/fajran-npTuioClient/resource.h
--- a/front_idill/extern/fajran-npTuioClient/resource.h	Thu Apr 19 11:53:06 2012 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,20 +0,0 @@
-//{{NO_DEPENDENCIES}}
-// Microsoft Developer Studio generated include file.
-// Used by np4xscr.rc
-//
-#define IDD_MAIN                        101
-#define IDC_BUTTON_GO                   1002
-#define IDC_STATIC_UA                   1003
-#define IDC_BUTTON1                     1005
-#define IDC_BUTTON_DONT                 1005
-
-// Next default values for new objects
-// 
-#ifdef APSTUDIO_INVOKED
-#ifndef APSTUDIO_READONLY_SYMBOLS
-#define _APS_NEXT_RESOURCE_VALUE        102
-#define _APS_NEXT_COMMAND_VALUE         40001
-#define _APS_NEXT_CONTROL_VALUE         1006
-#define _APS_NEXT_SYMED_VALUE           101
-#endif
-#endif
diff -r fcf435874395 -r 45c889eae324 front_idill/extern/fajran-npTuioClient/src/client.cpp
--- a/front_idill/extern/fajran-npTuioClient/src/client.cpp	Thu Apr 19 11:53:06 2012 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,183 +0,0 @@
-//   
-// Copyright (C) 2009  Fajran Iman Rusadi
-//
-// 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 .
-//
-
-/*
-    Modified by alexandre.bastien@iri.centrepompidou.fr to manage TUIO strings.
-*/
-
-#include "client.h"
-
-#include 
-#include 
-#include 
-#include 
-
-static inline void call(TuioEvent type, long sid, int fid, float x, float y, float a)
-{
-    TuioEventData data;
-    data.type = type;
-    data.sid = sid;
-    data.fid = fid;
-    data.x = x;
-    data.y = y;
-    data.a = a;
-    tuio_callback(data);
-}
-
-/*
-* Surchargé par alexandre.bastien@iri.centrepompidou.fr
-*/
-static inline void call(TuioEvent type, long sid, int fid, float x, float y, float z, float a)
-{
-    TuioEventData data;
-    data.type = type;
-    data.sid = sid;
-    data.fid = fid;
-    data.x = x;
-    data.y = y;
-    data.z = z;
-    data.a = a;
-    data.code = "";
-    tuio_callback(data);
-}
-
-/*
-* Ajouté par alexandre.bastien@iri.centrepompidou.fr
-*/
-static inline void call(TuioEvent type, long sid, const char* code)
-{
-    TuioEventData data;
-    data.type = type;
-    data.sid = sid;
-    data.code = code;
-    tuio_callback(data);
-}
-
-class Listener : public TuioListener
-{
-public:
-    Listener() { };
-    ~Listener() { };
-
-    void addTuioObject(TuioObject *object)
-    {
-        call(TE_OBJECT_ADD,
-            object->getSessionID(), object->getFiducialID(),
-            object->getX(), object->getY(), object->getAngle());
-    }
-
-    void updateTuioObject(TuioObject *object)
-    {
-        call(TE_OBJECT_UPDATE,
-            object->getSessionID(), object->getFiducialID(),
-            object->getX(), object->getY(), object->getAngle());
-    }
-
-    void removeTuioObject(TuioObject *object)
-    {
-        call(TE_OBJECT_REMOVE,
-            object->getSessionID(), object->getFiducialID(),
-            object->getX(), object->getY(), object->getAngle());
-    }
-    
-    /*
-    * Modifié par alexandre.bastien@iri.centrepompidou.fr
-    */
-    void addTuioCursor(TuioCursor *cursor)
-    {
-        call(TE_CURSOR_ADD,
-            cursor->getSessionID(), cursor->getFingerID(),
-            cursor->getX(), cursor->getY(), cursor->getZ(), 0);
-    }
-
-    /*
-    * Modifié par alexandre.bastien@iri.centrepompidou.fr
-    */
-    void updateTuioCursor(TuioCursor *cursor)
-    {
-        call(TE_CURSOR_UPDATE,
-            cursor->getSessionID(), cursor->getFingerID(),
-            cursor->getX(), cursor->getY(), cursor->getZ(), 0);
-    }
-
-    /*
-    * Modifié par alexandre.bastien@iri.centrepompidou.fr
-    */
-    void removeTuioCursor(TuioCursor *cursor)
-    {
-        call(TE_CURSOR_REMOVE,
-            cursor->getSessionID(), cursor->getFingerID(),
-            cursor->getX(), cursor->getY(), cursor->getZ(), 0);
-    }
-
-    /*
-    * Ajouté par alexandre.bastien@iri.centrepompidou.fr
-    */
-    void addTuioString(TuioString *string)
-    {
-        call(TE_STRING_ADD, string->getSessionID(), string->getCode());
-    }
-
-    /*
-    * Ajouté par alexandre.bastien@iri.centrepompidou.fr
-    */
-    void updateTuioString(TuioString *string)
-    {
-        call(TE_STRING_UPDATE, string->getSessionID(), string->getCode());
-    }
-
-    /*
-    * Ajouté par alexandre.bastien@iri.centrepompidou.fr
-    */
-    void removeTuioString(TuioString *string)
-    {
-        call(TE_STRING_REMOVE, string->getSessionID(), string->getCode());
-    }
-    
-    void refresh(long timestamp) 
-    {
-    }
-};
-
-static TuioClient* client = 0;
-static Listener* listener = 0;
-
-void tuio_start(int port)
-{
-    if (!client) {
-        listener = new Listener();
-
-        client = new TuioClient(port);
-        client->addTuioListener(listener);
-        client->start();
-    }
-}
-
-void tuio_stop()
-{
-    client->stop();
-    delete listener;
-    delete client;
-
-    client = 0;
-    listener = 0;
-}
-
-void t()
-{
-    std::cout << "t" << std::endl;
-}
\ No newline at end of file
diff -r fcf435874395 -r 45c889eae324 front_idill/extern/fajran-npTuioClient/src/client.h
--- a/front_idill/extern/fajran-npTuioClient/src/client.h	Thu Apr 19 11:53:06 2012 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,67 +0,0 @@
-//   
-// Copyright (C) 2009  Fajran Iman Rusadi
-//
-// 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 .
-//
-
-/*
-    Modified by alexandre.bastien@iri.centrepompidou.fr to manage TUIO strings.
-*/
-
-#ifndef CLIENT_H_
-#define CLIENT_H_
-
-#include 
-
-enum TuioEvent {
-    TE_OBJECT_ADD    = 0,
-    TE_OBJECT_UPDATE = 1,
-    TE_OBJECT_REMOVE = 2,
-    TE_CURSOR_ADD    = 3,
-    TE_CURSOR_UPDATE = 4,
-    TE_CURSOR_REMOVE = 5,
-    /*
-    * Ajouté par alexandre.bastien@iri.centrepompidou.fr
-    */
-    TE_STRING_ADD    = 6,
-    TE_STRING_UPDATE = 7,
-    TE_STRING_REMOVE = 8,
-};
-
-typedef struct {
-    TuioEvent type;
-    long      fid;
-    int       sid;
-    float     x;
-    float     y;
-    float     z;
-    float     a;
-    //Ajouté par alexandre.bastien@iri.centrepompidou.fr
-    const char* code;
-} TuioEventData;
-
-/*void tuio_start(int);
-void tuio_stop();*/
-
-extern void tuio_callback(TuioEventData);
-
-extern "C"
-{
-__declspec(dllexport) void tuio_start(int);
-__declspec(dllexport) void tuio_stop(void);
-__declspec(dllexport) void t(void);
-}
-
-#endif
-
diff -r fcf435874395 -r 45c889eae324 front_idill/extern/fajran-npTuioClient/src/np_entry.cpp
--- a/front_idill/extern/fajran-npTuioClient/src/np_entry.cpp	Thu Apr 19 11:53:06 2012 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,265 +0,0 @@
-// 
-//   Copyright (C) 2005, 2006, 2007, 2008, 2009 Free Software Foundation, Inc.
-// 
-// 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, write to the Free Software
-// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
-//
-
-//////////////////////////////////////////////////////////////
-//
-// Main plugin entry point implementation -- exports from the 
-// plugin library
-//
-#include "npplat.h"
-#include "pluginbase.h"
-
-NPNetscapeFuncs NPNFuncs;
-
-#ifdef XP_MAC
-void OSCALL NP_Shutdown()
-{
-  NS_PluginShutdown();
-}
-#else
-NPError OSCALL NP_Shutdown()
-{
-  NS_PluginShutdown();
-  return NPERR_NO_ERROR;
-}
-#endif
-
-static NPError fillPluginFunctionTable(NPPluginFuncs* aNPPFuncs)
-{
-  if(aNPPFuncs == NULL)
-    return NPERR_INVALID_FUNCTABLE_ERROR;
-
-  // Set up the plugin function table that Netscape will use to
-  // call us. Netscape needs to know about our version and size   
-  // and have a UniversalProcPointer for every function we implement.
-
-  aNPPFuncs->version       = (NP_VERSION_MAJOR << 8) | NP_VERSION_MINOR;
-#ifdef XP_MAC
-  aNPPFuncs->newp          = NewNPP_NewProc(Private_New);
-  aNPPFuncs->destroy       = NewNPP_DestroyProc(Private_Destroy);
-  aNPPFuncs->setwindow     = NewNPP_SetWindowProc(Private_SetWindow);
-  aNPPFuncs->newstream     = NewNPP_NewStreamProc(Private_NewStream);
-  aNPPFuncs->destroystream = NewNPP_DestroyStreamProc(Private_DestroyStream);
-  aNPPFuncs->asfile        = NewNPP_StreamAsFileProc(Private_StreamAsFile);
-  aNPPFuncs->writeready    = NewNPP_WriteReadyProc(Private_WriteReady);
-  aNPPFuncs->write         = NewNPP_WriteProc(Private_Write);
-  aNPPFuncs->print         = NewNPP_PrintProc(Private_Print);
-  aNPPFuncs->event         = NewNPP_HandleEventProc(Private_HandleEvent);    
-  aNPPFuncs->urlnotify     = NewNPP_URLNotifyProc(Private_URLNotify);            
-  aNPPFuncs->getvalue      = NewNPP_GetValueProc(Private_GetValue);
-  aNPPFuncs->setvalue      = NewNPP_SetValueProc(Private_SetValue);
-#else
-  aNPPFuncs->newp          = NPP_New;
-  aNPPFuncs->destroy       = NPP_Destroy;
-  aNPPFuncs->setwindow     = NPP_SetWindow;
-  aNPPFuncs->newstream     = NPP_NewStream;
-  aNPPFuncs->destroystream = NPP_DestroyStream;
-  aNPPFuncs->asfile        = NPP_StreamAsFile;
-  aNPPFuncs->writeready    = NPP_WriteReady;
-  aNPPFuncs->write         = NPP_Write;
-  aNPPFuncs->print         = NPP_Print;
-  aNPPFuncs->event         = NPP_HandleEvent;
-  aNPPFuncs->urlnotify     = NPP_URLNotify;
-  aNPPFuncs->getvalue      = NPP_GetValue;
-  aNPPFuncs->setvalue      = NPP_SetValue;
-#endif
-#ifdef OJI
-  aNPPFuncs->javaClass     = NULL;
-#endif
-
-  return NPERR_NO_ERROR;
-}
-
-static NPError fillNetscapeFunctionTable(NPNetscapeFuncs* aNPNFuncs)
-{
-  int i = 0, n;
-
-  if(aNPNFuncs == NULL)
-    return NPERR_INVALID_FUNCTABLE_ERROR;
-
-  if(HIBYTE(aNPNFuncs->version) > NP_VERSION_MAJOR)
-    return NPERR_INCOMPATIBLE_VERSION_ERROR;
-
-#if 0
-  if(aNPNFuncs->size < sizeof(NPNetscapeFuncs))
-    return NPERR_INVALID_FUNCTABLE_ERROR;
-#endif
-
-  // Number of function pointers in aNPNFuncs.
-  n = (aNPNFuncs->size - (2 * sizeof(uint16))) / sizeof(void *);
-
-  NPNFuncs.size             = aNPNFuncs->size;
-  NPNFuncs.version          = aNPNFuncs->version;
-
-  /*
-   * BEWARE!  The following is order-sensitive and needs to be in the
-   * same order as the structure definition from npupp.h.
-   */
-
-  if (++i <= n) NPNFuncs.geturl = aNPNFuncs->geturl;
-  if (++i <= n) NPNFuncs.posturl = aNPNFuncs->posturl;
-  if (++i <= n) NPNFuncs.requestread = aNPNFuncs->requestread;
-  if (++i <= n) NPNFuncs.newstream = aNPNFuncs->newstream;
-  if (++i <= n) NPNFuncs.write = aNPNFuncs->write;
-  if (++i <= n) NPNFuncs.destroystream = aNPNFuncs->destroystream;
-  if (++i <= n) NPNFuncs.status = aNPNFuncs->status;
-  if (++i <= n) NPNFuncs.uagent = aNPNFuncs->uagent;
-  if (++i <= n) NPNFuncs.memalloc = aNPNFuncs->memalloc;
-  if (++i <= n) NPNFuncs.memfree = aNPNFuncs->memfree;
-  if (++i <= n) NPNFuncs.memflush = aNPNFuncs->memflush;
-  if (++i <= n) NPNFuncs.reloadplugins = aNPNFuncs->reloadplugins;
-  if (++i <= n) NPNFuncs.getJavaEnv = aNPNFuncs->getJavaEnv;
-  if (++i <= n) NPNFuncs.getJavaPeer = aNPNFuncs->getJavaPeer;
-  if (++i <= n) NPNFuncs.geturlnotify = aNPNFuncs->geturlnotify;
-  if (++i <= n) NPNFuncs.posturlnotify = aNPNFuncs->posturlnotify;
-  if (++i <= n) NPNFuncs.getvalue = aNPNFuncs->getvalue;
-  if (++i <= n) NPNFuncs.setvalue = aNPNFuncs->setvalue;
-  if (++i <= n) NPNFuncs.invalidaterect = aNPNFuncs->invalidaterect;
-  if (++i <= n) NPNFuncs.invalidateregion = aNPNFuncs->invalidateregion;
-  if (++i <= n) NPNFuncs.forceredraw = aNPNFuncs->forceredraw;
-  if (++i <= n) NPNFuncs.getstringidentifier = aNPNFuncs->getstringidentifier;
-  if (++i <= n) NPNFuncs.getstringidentifiers = aNPNFuncs->getstringidentifiers;
-  if (++i <= n) NPNFuncs.getintidentifier = aNPNFuncs->getintidentifier;
-  if (++i <= n) NPNFuncs.identifierisstring = aNPNFuncs->identifierisstring;
-  if (++i <= n) NPNFuncs.utf8fromidentifier = aNPNFuncs->utf8fromidentifier;
-  if (++i <= n) NPNFuncs.intfromidentifier = aNPNFuncs->intfromidentifier;
-  if (++i <= n) NPNFuncs.createobject = aNPNFuncs->createobject;
-  if (++i <= n) NPNFuncs.retainobject = aNPNFuncs->retainobject;
-  if (++i <= n) NPNFuncs.releaseobject = aNPNFuncs->releaseobject;
-  if (++i <= n) NPNFuncs.invoke = aNPNFuncs->invoke;
-  if (++i <= n) NPNFuncs.invokeDefault = aNPNFuncs->invokeDefault;
-  if (++i <= n) NPNFuncs.evaluate = aNPNFuncs->evaluate;
-  if (++i <= n) NPNFuncs.getproperty = aNPNFuncs->getproperty;
-  if (++i <= n) NPNFuncs.setproperty = aNPNFuncs->setproperty;
-  if (++i <= n) NPNFuncs.removeproperty = aNPNFuncs->removeproperty;
-  if (++i <= n) NPNFuncs.hasproperty = aNPNFuncs->hasproperty;
-  if (++i <= n) NPNFuncs.hasmethod = aNPNFuncs->hasmethod;
-  if (++i <= n) NPNFuncs.releasevariantvalue = aNPNFuncs->releasevariantvalue;
-  if (++i <= n) NPNFuncs.setexception = aNPNFuncs->setexception;
-  if (++i <= n) NPNFuncs.pushpopupsenabledstate = aNPNFuncs->pushpopupsenabledstate;
-  if (++i <= n) NPNFuncs.poppopupsenabledstate = aNPNFuncs->poppopupsenabledstate;
-  if (++i <= n) NPNFuncs.enumerate = aNPNFuncs->enumerate;
-  if (++i <= n) NPNFuncs.pluginthreadasynccall = aNPNFuncs->pluginthreadasynccall;
-  if (++i <= n) NPNFuncs.construct = aNPNFuncs->construct;
-
-  return NPERR_NO_ERROR;
-}
-
-//
-// Some exports are different on different platforms
-//
-
-/**************************************************/
-/*                                                */
-/*                   Windows                      */
-/*                                                */
-/**************************************************/
-#ifdef XP_WIN
-
-NPError OSCALL NP_Initialize(NPNetscapeFuncs* aNPNFuncs)
-{
-  /*
-   * N.B.  On Firefox 2.0.0.12/WinXP, aNPNFuncs->size is 172 while
-   * sizeof(NPNetscapeFuncs) is 184.  However, npgnash.dll continues to
-   * work fine even though NPNFuncs isn't populated (!), and as a matter
-   * of fact, Firefox seems to ignore the NPERR_INVALID_FUNCTABLE_ERROR
-   * return from NP_Initialize and continues to load and execute
-   * npgnash.dll, anyway.  Therefore, we should continue and execute
-   * NS_PluginInitialize anyway, too.
-   */
-
-  NPError rv = fillNetscapeFunctionTable(aNPNFuncs);
-#if 0
-  if(rv != NPERR_NO_ERROR)
-    return rv;
-#endif
-  NPError rv2 = NS_PluginInitialize();
-
-  return rv2 != NPERR_NO_ERROR ? rv2 : rv;
-}
-
-NPError OSCALL NP_GetEntryPoints(NPPluginFuncs* aNPPFuncs)
-{
-  return fillPluginFunctionTable(aNPPFuncs);
-}
-
-#endif //XP_WIN
-
-/**************************************************/
-/*                                                */
-/*                    Unix                        */
-/*                                                */
-/**************************************************/
-#ifdef XP_UNIX
-
-#ifdef XP_MAC
-NPError NP_Initialize(NPNetscapeFuncs* aNPNFuncs)
-#else
-NPError NP_Initialize(NPNetscapeFuncs* aNPNFuncs, NPPluginFuncs* aNPPFuncs)
-#endif
-{
-  NPError rv = fillNetscapeFunctionTable(aNPNFuncs);
-  if(rv != NPERR_NO_ERROR)
-    return rv;
-
-#ifndef XP_MAC
-  rv = fillPluginFunctionTable(aNPPFuncs);
-  if(rv != NPERR_NO_ERROR)
-    return rv;
-#endif
-
-  return NS_PluginInitialize();
-}
-
-char * NP_GetMIMEDescription(void)
-{
-  return NPP_GetMIMEDescription();
-}
-
-NPError NP_GetValue(void* /*future*/, NPPVariable aVariable, void *aValue)
-{
-  return NS_PluginGetValue(aVariable, aValue);
-}
-
-#endif //XP_UNIX
-
-/**************************************************/
-/*                                                */
-/*                     Mac                        */
-/*                                                */
-/**************************************************/
-#ifdef XP_MAC
-
-NPError OSCALL NP_GetEntryPoints(NPPluginFuncs* aNPPFuncs)
-{
-  return fillPluginFunctionTable(aNPPFuncs);
-}
-
-NPError Private_Initialize(void)
-{
-  NPError rv = NS_PluginInitialize();
-  return rv;
-}
-
-void Private_Shutdown(void)
-{
-  NS_PluginShutdown();
-//  __destroy_global_chain();
-}
-
-#endif //XP_MAC
diff -r fcf435874395 -r 45c889eae324 front_idill/extern/fajran-npTuioClient/src/npn_gate.cpp
--- a/front_idill/extern/fajran-npTuioClient/src/npn_gate.cpp	Thu Apr 19 11:53:06 2012 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,204 +0,0 @@
-// 
-//   Copyright (C) 2005, 2006, 2007, 2008, 2009 Free Software Foundation, Inc.
-//
-// 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, write to the Free Software
-// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
-//
-
-////////////////////////////////////////////////////////////
-//
-// Implementation of Netscape entry points (NPN_*)
-//
-
-#include "pluginbase.h"
-
-extern NPNetscapeFuncs NPNFuncs;
-
-void NPN_Version(int* plugin_major, int* plugin_minor, int* netscape_major, int* netscape_minor)
-{
-  *plugin_major   = NP_VERSION_MAJOR;
-  *plugin_minor   = NP_VERSION_MINOR;
-  *netscape_major = HIBYTE(NPNFuncs.version);
-  *netscape_minor = LOBYTE(NPNFuncs.version);
-}
-
-NPError NPN_GetURLNotify(NPP instance, const char *url, const char *target, void* notifyData)
-{
-    int navMinorVers = NPNFuncs.version & 0xFF;
-    NPError rv = NPERR_NO_ERROR;
-
-    if( navMinorVers >= NPVERS_HAS_NOTIFICATION )
-        rv = CallNPN_GetURLNotifyProc(NPNFuncs.geturlnotify, instance, url, target, notifyData);
-    else
-        rv = NPERR_INCOMPATIBLE_VERSION_ERROR;
-    
-    return rv;
-}
-
-NPError NPN_GetURL(NPP instance, const char *url, const char *target)
-{
-    NPError rv = CallNPN_GetURLProc(NPNFuncs.geturl, instance, url, target);
-    return rv;
-}
-
-NPError NPN_PostURLNotify(NPP instance, const char* url, const char* window, uint32 len, const char* buf, NPBool file, void* notifyData)
-{
-    int navMinorVers = NPNFuncs.version & 0xFF;
-  NPError rv = NPERR_NO_ERROR;
-
-    if( navMinorVers >= NPVERS_HAS_NOTIFICATION )
-        rv = CallNPN_PostURLNotifyProc(NPNFuncs.posturlnotify, instance, url, window, len, buf, file, notifyData);
-    else
-        rv = NPERR_INCOMPATIBLE_VERSION_ERROR;
-
-  return rv;
-}
-
-NPError NPN_PostURL(NPP instance, const char* url, const char* window, uint32 len, const char* buf, NPBool file)
-{
-  NPError rv = CallNPN_PostURLProc(NPNFuncs.posturl, instance, url, window, len, buf, file);
-  return rv;
-} 
-
-NPError NPN_RequestRead(NPStream* stream, NPByteRange* rangeList)
-{
-  NPError rv = CallNPN_RequestReadProc(NPNFuncs.requestread, stream, rangeList);
-  return rv;
-}
-
-NPError NPN_NewStream(NPP instance, NPMIMEType type, const char* target, NPStream** stream)
-{
-    int navMinorVersion = NPNFuncs.version & 0xFF;
-
-  NPError rv = NPERR_NO_ERROR;
-
-    if( navMinorVersion >= NPVERS_HAS_STREAMOUTPUT )
-        rv = CallNPN_NewStreamProc(NPNFuncs.newstream, instance, type, target, stream);
-    else
-        rv = NPERR_INCOMPATIBLE_VERSION_ERROR;
-
-  return rv;
-}
-
-int32 NPN_Write(NPP instance, NPStream *stream, int32 len, void *buffer)
-{
-    int navMinorVersion = NPNFuncs.version & 0xFF;
-  int32 rv = 0;
-
-  if( navMinorVersion >= NPVERS_HAS_STREAMOUTPUT )
-        rv = CallNPN_WriteProc(NPNFuncs.write, instance, stream, len, buffer);
-    else
-        rv = -1;
-
-  return rv;
-}
-
-NPError NPN_DestroyStream(NPP instance, NPStream* stream, NPError reason)
-{
-    int navMinorVersion = NPNFuncs.version & 0xFF;
-  NPError rv = NPERR_NO_ERROR;
-
-  if( navMinorVersion >= NPVERS_HAS_STREAMOUTPUT )
-        rv = CallNPN_DestroyStreamProc(NPNFuncs.destroystream, instance, stream, reason);
-    else
-        rv = NPERR_INCOMPATIBLE_VERSION_ERROR;
-
-  return rv;
-}
-
-void NPN_Status(NPP instance, const char *message)
-{
-  CallNPN_StatusProc(NPNFuncs.status, instance, message);
-}
-
-const char* NPN_UserAgent(NPP instance)
-{
-  const char * rv = NULL;
-  rv = CallNPN_UserAgentProc(NPNFuncs.uagent, instance);
-  return rv;
-}
-
-void* NPN_MemAlloc(uint32 size)
-{
-  void * rv = NULL;
-  rv = CallNPN_MemAllocProc(NPNFuncs.memalloc, size);
-  return rv;
-}
-
-void NPN_MemFree(void* ptr)
-{
-  CallNPN_MemFreeProc(NPNFuncs.memfree, ptr);
-}
-
-uint32 NPN_MemFlush(uint32 size)
-{
-  uint32 rv = CallNPN_MemFlushProc(NPNFuncs.memflush, size);
-  return rv;
-}
-
-void NPN_ReloadPlugins(NPBool reloadPages)
-{
-  CallNPN_ReloadPluginsProc(NPNFuncs.reloadplugins, reloadPages);
-}
-
-NPError NPN_GetValue(NPP instance, NPNVariable variable, void *value)
-{
-  NPError rv = CallNPN_GetValueProc(NPNFuncs.getvalue, instance, variable, value);
-  return rv;
-}
-
-NPError NPN_SetValue(NPP instance, NPPVariable variable, void *value)
-{
-  NPError rv = CallNPN_SetValueProc(NPNFuncs.setvalue, instance, variable, value);
-  return rv;
-}
-
-void NPN_InvalidateRect(NPP instance, NPRect *invalidRect)
-{
-  CallNPN_InvalidateRectProc(NPNFuncs.invalidaterect, instance, invalidRect);
-}
-
-void NPN_InvalidateRegion(NPP instance, NPRegion invalidRegion)
-{
-  CallNPN_InvalidateRegionProc(NPNFuncs.invalidateregion, instance, invalidRegion);
-}
-
-void NPN_ForceRedraw(NPP instance)
-{
-  CallNPN_ForceRedrawProc(NPNFuncs.forceredraw, instance);
-}
-
-// The following has been copied from a newer version of npn_gate.cpp
-
-NPIdentifier NPN_GetStringIdentifier(const NPUTF8 *name)
-{
-  return NPNFuncs.getstringidentifier(name);
-}
-
-bool NPN_GetProperty(NPP npp, NPObject* obj, NPIdentifier propertyName,
-                     NPVariant *result)
-{
-  return NPNFuncs.getproperty(npp, obj, propertyName, result);
-}
-
-void NPN_ReleaseObject(NPObject *obj)
-{
-  return NPNFuncs.releaseobject(obj);
-}
-
-void NPN_PluginThreadAsyncCall (NPP instance, void (*func)(void *), void  *userData)
-{
-    CallNPN_PluginThreadAsyncCallProc(NPNFuncs.pluginthreadasynccall,
-        instance, func,    userData);
-}
diff -r fcf435874395 -r 45c889eae324 front_idill/extern/fajran-npTuioClient/src/npp_gate.cpp
--- a/front_idill/extern/fajran-npTuioClient/src/npp_gate.cpp	Thu Apr 19 11:53:06 2012 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,331 +0,0 @@
-// 
-//   Copyright (C) 2005, 2006, 2007, 2008, 2009 Free Software Foundation, Inc.
-//
-// 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, write to the Free Software
-// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
-//
-
-////////////////////////////////////////////////////////////
-//
-// Implementation of plugin entry points (NPP_*)
-//
-#include "pluginbase.h"
-
-// here the plugin creates a plugin instance object which 
-// will be associated with this newly created NPP instance and 
-// will do all the necessary job
-NPError NPP_New(NPMIMEType pluginType, NPP instance, uint16 mode, int16 argc, char* argn[], char* argv[], NPSavedData* saved)
-{   
-  if(instance == NULL)
-    return NPERR_INVALID_INSTANCE_ERROR;
-
-  NPError rv = NPERR_NO_ERROR;
-
-  // create a new plugin instance object
-  // initialization will be done when the associated window is ready
-  nsPluginCreateData ds;
-  
-  ds.instance = instance;
-  ds.type     = pluginType; 
-  ds.mode     = mode; 
-  ds.argc     = argc; 
-  ds.argn     = argn; 
-  ds.argv     = argv; 
-  ds.saved    = saved;
-
-  nsPluginInstanceBase * plugin = NS_NewPluginInstance(&ds);
-  if(plugin == NULL)
-    return NPERR_OUT_OF_MEMORY_ERROR;
-
-  // associate the plugin instance object with NPP instance
-  instance->pdata = (void *)plugin;
-  return rv;
-}
-
-// here is the place to clean up and destroy the nsPluginInstance object
-NPError NPP_Destroy (NPP instance, NPSavedData** /*save*/)
-{
-  if(instance == NULL)
-    return NPERR_INVALID_INSTANCE_ERROR;
-
-  NPError rv = NPERR_NO_ERROR;
-
-  nsPluginInstanceBase * plugin = (nsPluginInstanceBase *)instance->pdata;
-  if(plugin != NULL) {
-    plugin->shut();
-    NS_DestroyPluginInstance(plugin);
-  }
-  return rv;
-}
-
-// during this call we know when the plugin window is ready or
-// is about to be destroyed so we can do some gui specific
-// initialization and shutdown
-NPError NPP_SetWindow (NPP instance, NPWindow* pNPWindow)
-{    
-  if(instance == NULL)
-    return NPERR_INVALID_INSTANCE_ERROR;
-
-  NPError rv = NPERR_NO_ERROR;
-
-  if(pNPWindow == NULL)
-    return NPERR_GENERIC_ERROR;
-
-  nsPluginInstanceBase * plugin = (nsPluginInstanceBase *)instance->pdata;
-
-  if(plugin == NULL) 
-    return NPERR_GENERIC_ERROR;
-
-  // window just created
-  if(!plugin->isInitialized() && (pNPWindow->window != NULL)) { 
-    if(!plugin->init(pNPWindow)) {
-      NS_DestroyPluginInstance(plugin);
-      return NPERR_MODULE_LOAD_FAILED_ERROR;
-    }
-  }
-
-  // window goes away
-  if((pNPWindow->window == NULL) && plugin->isInitialized())
-    return plugin->SetWindow(pNPWindow);
-
-  // window resized?
-  if(plugin->isInitialized() && (pNPWindow->window != NULL))
-    return plugin->SetWindow(pNPWindow);
-
-  // this should not happen, nothing to do
-  if((pNPWindow->window == NULL) && !plugin->isInitialized())
-    return plugin->SetWindow(pNPWindow);
-
-  return rv;
-}
-
-NPError NPP_NewStream(NPP instance, NPMIMEType type, NPStream* stream, NPBool seekable, uint16* stype)
-{
-  if(instance == NULL)
-    return NPERR_INVALID_INSTANCE_ERROR;
-
-  nsPluginInstanceBase * plugin = (nsPluginInstanceBase *)instance->pdata;
-  if(plugin == NULL) 
-    return NPERR_GENERIC_ERROR;
-
-  NPError rv = plugin->NewStream(type, stream, seekable, stype);
-  return rv;
-}
-
-int32 NPP_WriteReady (NPP instance, NPStream *stream)
-{
-  if(instance == NULL)
-    return 0x0fffffff;
-
-  nsPluginInstanceBase * plugin = (nsPluginInstanceBase *)instance->pdata;
-  if(plugin == NULL) 
-    return 0x0fffffff;
-
-  int32 rv = plugin->WriteReady(stream);
-  return rv;
-}
-
-int32 NPP_Write (NPP instance, NPStream *stream, int32 offset, int32 len, void *buffer)
-{   
-  if(instance == NULL)
-    return len;
-
-  nsPluginInstanceBase * plugin = (nsPluginInstanceBase *)instance->pdata;
-  if(plugin == NULL) 
-    return len;
-
-  int32 rv = plugin->Write(stream, offset, len, buffer);
-  return rv;
-}
-
-NPError NPP_DestroyStream (NPP instance, NPStream *stream, NPError reason)
-{
-  if(instance == NULL)
-    return NPERR_INVALID_INSTANCE_ERROR;
-
-  nsPluginInstanceBase * plugin = (nsPluginInstanceBase *)instance->pdata;
-  if(plugin == NULL) 
-    return NPERR_GENERIC_ERROR;
-
-  NPError rv = plugin->DestroyStream(stream, reason);
-  return rv;
-}
-
-void NPP_StreamAsFile (NPP instance, NPStream* stream, const char* fname)
-{
-  if(instance == NULL)
-    return;
-
-  nsPluginInstanceBase * plugin = (nsPluginInstanceBase *)instance->pdata;
-  if(plugin == NULL) 
-    return;
-
-  plugin->StreamAsFile(stream, fname);
-}
-
-void NPP_Print (NPP instance, NPPrint* printInfo)
-{
-  if(instance == NULL)
-    return;
-
-  nsPluginInstanceBase * plugin = (nsPluginInstanceBase *)instance->pdata;
-  if(plugin == NULL) 
-    return;
-
-  plugin->Print(printInfo);
-}
-
-void NPP_URLNotify(NPP instance, const char* url, NPReason reason, void* notifyData)
-{
-  if(instance == NULL)
-    return;
-
-  nsPluginInstanceBase * plugin = (nsPluginInstanceBase *)instance->pdata;
-  if(plugin == NULL) 
-    return;
-
-  plugin->URLNotify(url, reason, notifyData);
-}
-
-NPError    NPP_GetValue(NPP instance, NPPVariable variable, void *value)
-{
-  if(instance == NULL)
-    return NPERR_INVALID_INSTANCE_ERROR;
-
-  nsPluginInstanceBase * plugin = (nsPluginInstanceBase *)instance->pdata;
-  if(plugin == NULL) 
-    return NPERR_GENERIC_ERROR;
-
-  NPError rv = plugin->GetValue(variable, value);
-  return rv;
-}
-
-NPError NPP_SetValue(NPP instance, NPNVariable variable, void *value)
-{
-  if(instance == NULL)
-    return NPERR_INVALID_INSTANCE_ERROR;
-
-  nsPluginInstanceBase * plugin = (nsPluginInstanceBase *)instance->pdata;
-  if(plugin == NULL) 
-    return NPERR_GENERIC_ERROR;
-
-  NPError rv = plugin->SetValue(variable, value);
-  return rv;
-}
-
-int16    NPP_HandleEvent(NPP instance, void* event)
-{
-  if(instance == NULL)
-    return 0;
-
-  nsPluginInstanceBase * plugin = (nsPluginInstanceBase *)instance->pdata;
-  if(plugin == NULL) 
-    return 0;
-
-  uint16 rv = plugin->HandleEvent(event);
-  return rv;
-}
-
-/**************************************************/
-/*                                                */
-/*                     Mac                        */
-/*                                                */
-/**************************************************/
-
-// Mac needs these wrappers, see npplat.h for more info
-
-#ifdef XP_MAC
-
-NPError    Private_New(NPMIMEType pluginType, NPP instance, uint16 mode, int16 argc, char* argn[], char* argv[], NPSavedData* saved)
-{
-  NPError rv = NPP_New(pluginType, instance, mode, argc, argn, argv, saved);
-  return rv;    
-}
-
-NPError Private_Destroy(NPP instance, NPSavedData** save)
-{
-  NPError rv = NPP_Destroy(instance, save);
-  return rv;
-}
-
-NPError Private_SetWindow(NPP instance, NPWindow* window)
-{
-  NPError rv = NPP_SetWindow(instance, window);
-  return rv;
-}
-
-NPError Private_NewStream(NPP instance, NPMIMEType type, NPStream* stream, NPBool seekable, uint16* stype)
-{
-  NPError rv = NPP_NewStream(instance, type, stream, seekable, stype);
-  return rv;
-}
-
-int32 Private_WriteReady(NPP instance, NPStream* stream)
-{
-  int32 rv = NPP_WriteReady(instance, stream);
-  return rv;
-}
-
-int32 Private_Write(NPP instance, NPStream* stream, int32 offset, int32 len, void* buffer)
-{
-  int32 rv = NPP_Write(instance, stream, offset, len, buffer);
-  return rv;
-}
-
-void Private_StreamAsFile(NPP instance, NPStream* stream, const char* fname)
-{
-  NPP_StreamAsFile(instance, stream, fname);
-}
-
-
-NPError Private_DestroyStream(NPP instance, NPStream* stream, NPError reason)
-{
-  NPError rv = NPP_DestroyStream(instance, stream, reason);
-  return rv;
-}
-
-int16 Private_HandleEvent(NPP instance, void* event)
-{
-  int16 rv = NPP_HandleEvent(instance, event);
-  return rv;
-}
-
-void Private_Print(NPP instance, NPPrint* platformPrint)
-{
-  NPP_Print(instance, platformPrint);
-}
-
-void Private_URLNotify(NPP instance, const char* url, NPReason reason, void* notifyData)
-{
-  NPP_URLNotify(instance, url, reason, notifyData);
-}
-
-jref Private_GetJavaClass(void)
-{
-  return NULL;
-}
-
-NPError Private_GetValue(NPP instance, NPPVariable variable, void *result)
-{
-  NPError rv = NPP_GetValue(instance, variable, result);
-  return rv;
-}
-
-NPError Private_SetValue(NPP instance, NPNVariable variable, void *value)
-{
-  NPError rv = NPP_SetValue(instance, variable, value);
-  return rv;
-}
-
-#endif //XP_MAC
diff -r fcf435874395 -r 45c889eae324 front_idill/extern/fajran-npTuioClient/src/npplat.h
--- a/front_idill/extern/fajran-npTuioClient/src/npplat.h	Thu Apr 19 11:53:06 2012 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,101 +0,0 @@
-/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* ***** BEGIN LICENSE BLOCK *****
- * Version: MPL 1.1/GPL 2.0/LGPL 2.1
- *
- * The contents of this file are subject to the Mozilla Public License Version
- * 1.1 (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- * http://www.mozilla.org/MPL/
- *
- * Software distributed under the License is distributed on an "AS IS" basis,
- * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
- * for the specific language governing rights and limitations under the
- * License.
- *
- * The Original Code is mozilla.org code.
- *
- * The Initial Developer of the Original Code is
- * Netscape Communications Corporation.
- * Portions created by the Initial Developer are Copyright (C) 1998
- * the Initial Developer. All Rights Reserved.
- *
- * Contributor(s):
- *
- * Alternatively, the contents of this file may be used under the terms of
- * either the GNU General Public License Version 2 or later (the "GPL"), or
- * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
- * in which case the provisions of the GPL or the LGPL are applicable instead
- * of those above. If you wish to allow use of your version of this file only
- * under the terms of either the GPL or the LGPL, and not to allow others to
- * use your version of this file under the terms of the MPL, indicate your
- * decision by deleting the provisions above and replace them with the notice
- * and other provisions required by the GPL or the LGPL. If you do not delete
- * the provisions above, a recipient may use your version of this file under
- * the terms of any one of the MPL, the GPL or the LGPL.
- *
- * ***** END LICENSE BLOCK ***** */
-
-#ifndef _NPPLAT_H_
-#define _NPPLAT_H_
-
-#include "npapi.h"
-#include "npupp.h"
-
-/**************************************************/
-/*                                                */
-/*                   Windows                      */
-/*                                                */
-/**************************************************/
-#ifdef XP_WIN
-#include "windows.h"
-#endif //XP_WIN
-
-/**************************************************/
-/*                                                */
-/*                    Unix                        */
-/*                                                */
-/**************************************************/
-#ifdef XP_UNIX
-#include 
-#endif //XP_UNIX
-
-/**************************************************/
-/*                                                */
-/*                     Mac                        */
-/*                                                */
-/**************************************************/
-#ifdef XP_MAC
-
-// Wrapper functions for all calls from Netscape to the plugin.
-// These functions let the plugin developer just create the APIs
-// as documented and defined in npapi.h, without needing to 
-// install those functions in the function table or worry about
-// setting up globals for 68K plugins.
-NPError Private_Initialize(void);
-void    Private_Shutdown(void);
-NPError Private_New(NPMIMEType pluginType, NPP instance, uint16 mode, int16 argc, char* argn[], char* argv[], NPSavedData* saved);
-NPError Private_Destroy(NPP instance, NPSavedData** save);
-NPError Private_SetWindow(NPP instance, NPWindow* window);
-NPError Private_NewStream(NPP instance, NPMIMEType type, NPStream* stream, NPBool seekable, uint16* stype);
-NPError Private_DestroyStream(NPP instance, NPStream* stream, NPError reason);
-int32   Private_WriteReady(NPP instance, NPStream* stream);
-int32   Private_Write(NPP instance, NPStream* stream, int32 offset, int32 len, void* buffer);
-void    Private_StreamAsFile(NPP instance, NPStream* stream, const char* fname);
-void    Private_Print(NPP instance, NPPrint* platformPrint);
-int16   Private_HandleEvent(NPP instance, void* event);
-void    Private_URLNotify(NPP instance, const char* url, NPReason reason, void* notifyData);
-jref    Private_GetJavaClass(void);
-NPError Private_GetValue(NPP instance, NPPVariable variable, void *result);
-NPError Private_SetValue(NPP instance, NPNVariable variable, void *value);
-
-#endif //XP_MAC
-
-#ifndef HIBYTE
-#define HIBYTE(i) (i >> 8)
-#endif
-
-#ifndef LOBYTE
-#define LOBYTE(i) (i & 0xff)
-#endif
-
-#endif //_NPPLAT_H_
diff -r fcf435874395 -r 45c889eae324 front_idill/extern/fajran-npTuioClient/src/plugin.cpp
--- a/front_idill/extern/fajran-npTuioClient/src/plugin.cpp	Thu Apr 19 11:53:06 2012 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,363 +0,0 @@
-// 
-//   Copyright (C) 2005, 2006, 2007, 2008, 2009 Free Software Foundation, Inc.
-// 
-// 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, write to the Free Software
-// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
-
-/*
-    Modified by alexandre.bastien@iri.centrepompidou.fr to manage TUIO strings.
-*/
-
-#include "plugin.h"
-
-#include 
-#include 
-#include 
-#define D(s) /*std::cerr << s << std::endl;*/
-
-#include 
-
-#define MIME_TYPES_HANDLED  "application/x-tuio"
-// The name must be this value to get flash movies that check the
-// plugin version to load.
-#define PLUGIN_NAME    "TUIO Client"
-#define MIME_TYPES_DESCRIPTION  MIME_TYPES_HANDLED":tuio:"PLUGIN_NAME
-
-#define PLUGIN_DESCRIPTION "TUIO Client plugin"
-
-extern NPNetscapeFuncs NPNFuncs;
-
-NPBool plugInitialized = FALSE;
-
-static std::set instances;
-
-void tuio_callback(TuioEventData data)
-{
-    std::set::iterator iter;
-    for (iter = instances.begin(); iter != instances.end(); iter++) {
-        (*iter)->event(data);
-    }
-}
-
-void
-PR_CALLBACK Destructor(void * /* data */)
-{
-#if 0
-    /*
-     * We don't actually free the storage since it's actually allocated
-     * on the stack. Normally, this would not be the case and this is
-     * the opportunity to free whatever.
-     */
-    PR_Free(data);
-#endif
-}
-
-/// \brief Return the MIME Type description for this plugin.
-char*
-NPP_GetMIMEDescription(void)
-{
-    return const_cast(MIME_TYPES_DESCRIPTION);
-}
-
-//
-// general initialization and shutdown
-//
-
-/// \brief Initialize the plugin
-///
-/// This C++ function gets called once when the plugin is loaded,
-/// regardless of how many instantiations there is actually playing
-/// movies. So this is where all the one time only initialization
-/// stuff goes.
-NPError
-NS_PluginInitialize()
-{
-    if ( plugInitialized )
-    {
-        return NPERR_NO_ERROR;
-    }
-
-    plugInitialized = TRUE;
-
-    tuio_start(80);
-
-    return NPERR_NO_ERROR;
-}
-
-/// \brief Shutdown the plugin
-///
-/// This C++ function gets called once when the plugin is being
-/// shutdown, regardless of how many instantiations actually are
-/// playing movies. So this is where all the one time only
-/// shutdown stuff goes.
-void
-NS_PluginShutdown()
-{
-#if 0
-    if (!plugInitialized)
-    {
-#if GNASH_PLUGIN_DEBUG > 1
-        std::cout << "Plugin already shut down" << std::endl;
-#endif
-        return;
-    }
-
-    plugInitialized = FALSE;
-#endif
-
-    tuio_stop();
-}
-
-
-
-/// \brief Retrieve values from the plugin for the Browser
-///
-/// This C++ function is called by the browser to get certain
-/// information is needs from the plugin. This information is the
-/// plugin name, a description, etc...
-NPError
-NS_PluginGetValue(NPPVariable aVariable, void *aValue)
-{
-    NPError err = NPERR_NO_ERROR;
-
-    switch (aVariable)
-    {
-        case NPPVpluginNameString:
-            *static_cast (aValue) = PLUGIN_NAME;
-            break;
-
-        // This becomes the description field you see below the opening
-        // text when you type about:plugins and in
-        // navigator.plugins["Shockwave Flash"].description, used in
-        // many flash version detection scripts.
-        case NPPVpluginDescriptionString:
-            *static_cast(aValue) = PLUGIN_DESCRIPTION;
-            break;
-
-        case NPPVpluginNeedsXEmbed:
-            *(int*)aValue = PR_TRUE;
-            break;
-
-        case NPPVpluginTimerInterval:
-
-        case NPPVpluginKeepLibraryInMemory:
-
-        default:
-            err = NPERR_INVALID_PARAM;
-            break;
-    }
-    return err;
-}
-
-/// \brief construct our plugin instance object
-///
-/// This instantiates a new object via a C++ function used by the
-/// browser.
-nsPluginInstanceBase *
-NS_NewPluginInstance(nsPluginCreateData * aCreateDataStruct)
-{
-    if(!aCreateDataStruct) return NULL;
-
-    return new nsPluginInstance(aCreateDataStruct);
-}
-
-/// \brief destroy our plugin instance object
-///
-/// This destroys our instantiated object via a C++ function used by the
-/// browser.
-void
-NS_DestroyPluginInstance(nsPluginInstanceBase* aPlugin)
-{
-    delete static_cast (aPlugin);
-}
-
-//
-// nsPluginInstance class implementation
-//
-
-/// \brief Constructor
-nsPluginInstance::nsPluginInstance(nsPluginCreateData* data)
-    :
-    nsPluginInstanceBase(),
-    _instance(data->instance),
-    _port(3333),
-    _callback("tuio_callback")
-{
-    for (size_t i=0, n=data->argc; iargn[i])
-        {
-            name = data->argn[i];
-        }
-
-        if (data->argv[i])
-        {
-            val = data->argv[i];
-        }
-
-        else if ( ! strstr(name.c_str(), "callback") )
-        {
-            _callback = val;
-        }
-
-        else if ( ! strstr(name.c_str(), "port") )
-        {
-            _port = atoi(val.c_str());
-        }
-    }
-
-    instances.insert(this);
-}
-
-/// \brief Destructor
-nsPluginInstance::~nsPluginInstance()
-{
-    instances.erase(this);
-}
-
-/// \brief Initialize an instance of the plugin object
-/// 
-/// This methods initializes the plugin object, and is called for
-/// every movie that gets played. This is where the movie playing
-/// specific initialization goes.
-NPBool
-nsPluginInstance::init(NPWindow* aWindow)
-{
-    D("[ns] init");
-    return TRUE;
-}
-
-/// \brief Shutdown an instantiated object
-///
-/// This shuts down an object, and is called for every movie that gets
-/// played. This is where the movie playing specific shutdown code
-/// goes.
-void
-nsPluginInstance::shut()
-{
-    D("[ns] shut");
-}
-
-NPError
-nsPluginInstance::SetWindow(NPWindow* aWindow)
-{
-    D("[ns] SetWindow");
-
-    if(!aWindow)
-    {
-        return NPERR_INVALID_PARAM;
-    }
-
-    return NPERR_NO_ERROR;
-}
-
-NPError
-nsPluginInstance::GetValue(NPPVariable aVariable, void *aValue)
-{
-    return NS_PluginGetValue(aVariable, aValue);
-}
-
-/// \brief Write a status message
-///
-/// This writes a status message to the status line at the bottom of
-/// the browser window and the console firefox was started from.
-NPError
-nsPluginInstance::WriteStatus(const char *msg) const
-{
-    NPN_Status(_instance, msg);
-    std::cout << msg << std::endl;
-
-    return NPERR_NO_ERROR;
-}
-
-NPError
-nsPluginInstance::NewStream(NPMIMEType /*type*/, NPStream* stream,
-                            NPBool /*seekable*/, uint16* /*stype*/)
-{
-    D("[ns] NewStream");
-    return NPERR_NO_ERROR;
-}
-
-NPError
-nsPluginInstance::DestroyStream(NPStream* /*stream*/, NPError /*reason*/)
-{
-    D("[ns] DestroyStream");
-    return NPERR_NO_ERROR;
-}
-
-int32_t
-nsPluginInstance::WriteReady(NPStream* /* stream */ )
-{
-    D("[ns] WriteReady");
-    return 0x0fffffff;
-}
-
-int32_t
-nsPluginInstance::Write(NPStream* /*stream*/, int32_t /*offset*/, int32_t len,
-        void* buffer)
-{
-    D("[ns] Write: len=" << len);
-    return len;
-}
-
-typedef struct {
-    NPP instance;
-    TuioEventData data;
-} Event;
-
-void test(void* ev)
-{
-    D("ev=" << ev);
-    Event* event = (Event*)ev;
-    D("event=" << event);
-    std::stringstream ss;
-    ss << "javascript:tuio_callback(";
-    ss << event->data.type << ", ";
-    ss << event->data.sid << ", ";
-    ss << event->data.fid << ", ";
-    ss << event->data.x << ", ";
-    ss << event->data.y << ", ";
-    ss << event->data.z << ", ";
-    ss << event->data.a << ", ";
-    if(event->data.code == NULL || event->data.code == "")
-        ss << "\"\");";
-    else
-        ss << "\"" << event->data.code << "\"" << ");";
-    
-    NPN_GetURL(event->instance, ss.str().c_str(), "_self");
-
-    delete event;
-}
-
-void nsPluginInstance::event(TuioEventData data)
-{
-    D("[event] callback: type=" << data.type
-    << ", sid=" << data.sid << ", fid=" << data.fid
-    << ", x=" << data.x << ", y=" << data.y
-    << ", z=" << data.z << ", a=" << data.a
-    << ", code=" << "\"" << data.code << "\"");
-    
-    Event* ev = new Event();
-    ev->instance = _instance;
-    ev->data = data;
-
-    NPN_PluginThreadAsyncCall(_instance, test, ev);
-}
-
-// Local Variables:
-// mode: C++
-// indent-tabs-mode: t
-// End:
diff -r fcf435874395 -r 45c889eae324 front_idill/extern/fajran-npTuioClient/src/plugin.h
--- a/front_idill/extern/fajran-npTuioClient/src/plugin.h	Thu Apr 19 11:53:06 2012 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,71 +0,0 @@
-// 
-//   Copyright (C) 2005, 2006, 2007, 2008, 2009 Free Software Foundation, Inc.
-// 
-// 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, write to the Free Software
-// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
-
-/*
-    Modified by alexandre.bastien@iri.centrepompidou.fr to manage TUIO strings.
-*/
-
-#ifndef PLUGIN_H
-#define PLUGIN_H
-
-#include "pluginbase.h"
-#include "client.h"
-
-#include 
-#include 
-
-extern NPBool      plugInitialized;
-
-class nsPluginInstance : public nsPluginInstanceBase
-{
-public:
-    nsPluginInstance(nsPluginCreateData* );
-    virtual ~nsPluginInstance();
-
-    // We are required to implement these three methods.
-    NPBool init(NPWindow *aWindow);
-    NPBool isInitialized() { return plugInitialized; }
-    void shut();
-
-    NPError GetValue(NPPVariable variable, void *value);
-    NPError SetWindow(NPWindow *aWindow);
-
-    NPError NewStream(NPMIMEType type, NPStream *stream, NPBool seekable,
-                      uint16 *stype);
-    NPError DestroyStream(NPStream * stream, NPError reason);
-
-    int32_t WriteReady(NPStream *stream);
-    int32_t Write(NPStream *stream, int32_t offset, int32_t len, void *buffer);
-
-    NPError WriteStatus(const char *msg) const;
-
-    void event(TuioEventData);
-
-
-private:
-    NPP         _instance;
-
-    int         _port;
-    std::string _callback;
-};
-
-// end of __PLUGIN_H__
-#endif
-
-// Local Variables:
-// mode: C++
-// End:
diff -r fcf435874395 -r 45c889eae324 front_idill/extern/fajran-npTuioClient/src/pluginbase.h
--- a/front_idill/extern/fajran-npTuioClient/src/pluginbase.h	Thu Apr 19 11:53:06 2012 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,90 +0,0 @@
-// 
-//   Copyright (C) 2005, 2006, 2007, 2008, 2009 Free Software Foundation, Inc.
-//
-// 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, write to the Free Software
-// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
-//
-
-#ifndef PLUGINBASE_H_
-#define PLUGINBASE_H_
-
-#include 
-#include 
-#include 
-
-#ifndef HIBYTE
-#define HIBYTE(i) (i >> 8)
-#endif
-
-#ifndef LOBYTE
-#define LOBYTE(i) (i & 0xff)
-#endif
-
-struct nsPluginCreateData
-{
-  NPP instance;
-  NPMIMEType type; 
-  uint16 mode; 
-  int16 argc; 
-  char** argn; 
-  char** argv; 
-  NPSavedData* saved;
-};
-
-class nsPluginInstanceBase
-{
- public:
-  virtual ~nsPluginInstanceBase() { return; }
- 
-  // these three methods must be implemented in the derived
-  // class platform specific way
-  virtual NPBool init(NPWindow* aWindow) = 0;
-  virtual void shut() = 0;
-  virtual NPBool isInitialized() = 0;
-
-  // implement all or part of those methods in the derived 
-  // class as needed
-  virtual NPError SetWindow(NPWindow* /*pNPWindow*/)                    { return NPERR_NO_ERROR; }
-  virtual NPError WriteStatus(const char* /*msg*/) const                     { return NPERR_NO_ERROR; }
-  virtual NPError NewStream(NPMIMEType /*type*/, NPStream* /*stream*/, 
-                            NPBool /*seekable*/, uint16* /*stype*/)         { return NPERR_NO_ERROR; }
-  virtual NPError DestroyStream(NPStream* /*stream*/, NPError /*reason*/)   { return NPERR_NO_ERROR; }
-  virtual void    StreamAsFile(NPStream* /*stream*/, const char* /*fname*/) { return; }
-  virtual int32_t WriteReady(NPStream* /*stream*/)                      { return 0x0fffffff; }
-  virtual int32   Write(NPStream* /*stream*/, int32 /*offset*/, 
-                        int32 len, void* /*buffer*/)                    { return len; }
-  virtual void    Print(NPPrint* /*printInfo*/)                         { return; }
-  virtual uint16  HandleEvent(void* /*event*/)                          { return 0; }
-  virtual void    URLNotify(const char* /*url*/, NPReason /*reason*/, 
-                            void* /*notifyData*/)                       { return; }
-  virtual NPError GetValue(NPPVariable /*variable*/, void* /*value*/)       { return NPERR_NO_ERROR; }
-  virtual NPError SetValue(NPNVariable /*variable*/, void* /*value*/)       { return NPERR_NO_ERROR; }
-};
-
-// functions that should be implemented for each specific plugin
-
-// creation and destruction of the object of the derived class
-nsPluginInstanceBase * NS_NewPluginInstance(nsPluginCreateData * aCreateDataStruct);
-void NS_DestroyPluginInstance(nsPluginInstanceBase * aPlugin);
-
-// global plugin initialization and shutdown
-NPError NS_PluginInitialize();
-void NS_PluginShutdown();
-
-// FIXME #ifdef XP_UNIX
-// global to get plugins name & description 
-NPError NS_PluginGetValue(NPPVariable aVariable, void *aValue);
-// FIXME #endif
-
-#endif // __PLUGININSTANCEBASE_H__
diff -r fcf435874395 -r 45c889eae324 front_idill/extern/fajran-tuiojs/.gitignore
--- a/front_idill/extern/fajran-tuiojs/.gitignore	Thu Apr 19 11:53:06 2012 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,3 +0,0 @@
-*.swp
-*.pyc
-
diff -r fcf435874395 -r 45c889eae324 front_idill/extern/fajran-tuiojs/LICENSE.txt
--- a/front_idill/extern/fajran-tuiojs/LICENSE.txt	Thu Apr 19 11:53:06 2012 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,19 +0,0 @@
-Copyright (c) 2009 Fajran Iman Rusadi 
-
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in
-all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-THE SOFTWARE.
diff -r fcf435874395 -r 45c889eae324 front_idill/extern/fajran-tuiojs/README.md
--- a/front_idill/extern/fajran-tuiojs/README.md	Thu Apr 19 11:53:06 2012 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,15 +0,0 @@
-TUIOjs
-======
-
-Javascript TUIO client library.
-
-This library uses a connector to receive the TUIO data. Currently,
-there are two connectors available:
-
-* [npTuioClient](http://github.com/fajran/npTuioClient) based
-  connector. Check it's project page to see how it works.
-
-* Stomp based connector. This connector uses XHR to get events from a
-  [Stomp](http://stomp.codehaus.org/) server.
-
-
diff -r fcf435874395 -r 45c889eae324 front_idill/extern/fajran-tuiojs/connector/npTuioClient/tuiojs.npTuioClient.js
--- a/front_idill/extern/fajran-tuiojs/connector/npTuioClient/tuiojs.npTuioClient.js	Thu Apr 19 11:53:06 2012 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,38 +0,0 @@
-/*
-    Modified by alexandre.bastien@iri.centrepompidou.fr to manage TUIO strings.
-*/
-
-tuio.setConnector({
-    _failmsg: "Unable to initialize npTuioClient plugin.",
-    _id: "__tuiojs_connector_npTuioClient",
-
-    start: function() {
-        var el = document.getElementById(this._id);
-        if (el == undefined) {
-            var el = document.createElement('object');
-            el.setAttribute('id', this._id);
-            el.setAttribute('type', 'application/x-tuio');
-            el.appendChild(document.createTextNode(this._failmsg));
-            document.body.appendChild(el);
-        }
-
-        // TODO: check if the plugin can be loaded. 
-        //       if so, hide the plugin (display:none).
-    },
-
-    stop: function() {
-        var el = document.getElementById(this._id);
-        if (el != undefined) {
-            document.body.removeChild(el);
-        }
-    }
-});
-
-function tuio_callback(type, sid, fid, x, y, z, angle, code)  {
-
-    if(type < 6)
-        tuio.cursorCallback(type, sid, fid, x, y, z, angle);
-    else
-        tuio.stringCallback(type, sid, code);
-}
-
diff -r fcf435874395 -r 45c889eae324 front_idill/extern/fajran-tuiojs/connector/stomp/README.md
--- a/front_idill/extern/fajran-tuiojs/connector/stomp/README.md	Thu Apr 19 11:53:06 2012 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,27 +0,0 @@
-TUIOjs
-======
-
-A TUIO gateway for javascript.
-
-Data flow
----------
-
-The data flow can be illustrated more or less like the following.
-
-    Tracker =[tuio]=> gateway => message queue =[stomp/http]=> browser.
-
-Requirements
-------------
-
-- [orbited](http://orbited.org/)
-- [pytuio](http://code.google.com/p/pytuio/)
-- [stompy](http://code.google.com/p/stomppy/)
-- [jquery](http://jquery.org)
-- a fast browser. Tested with safari 4 on mac os x tiger.
-
-Screencast
-----------
-
-
-
-
diff -r fcf435874395 -r 45c889eae324 front_idill/extern/fajran-tuiojs/connector/stomp/index.html
--- a/front_idill/extern/fajran-tuiojs/connector/stomp/index.html	Thu Apr 19 11:53:06 2012 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,80 +0,0 @@
-
-
-
-
-
-
-
-
-
-
- diff -r fcf435874395 -r 45c889eae324 front_idill/extern/fajran-tuiojs/connector/stomp/orbited.cfg --- a/front_idill/extern/fajran-tuiojs/connector/stomp/orbited.cfg Thu Apr 19 11:53:06 2012 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,12 +0,0 @@ -[listen] -http://:9000 -stomp://:61613 - -[access] -* -> localhost:61613 - -[static] -graph=index.html - -[global] -session.ping_interval = 300 diff -r fcf435874395 -r 45c889eae324 front_idill/extern/fajran-tuiojs/connector/stomp/tuio-gateway.py --- a/front_idill/extern/fajran-tuiojs/connector/stomp/tuio-gateway.py Thu Apr 19 11:53:06 2012 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,58 +0,0 @@ -import tuio -import stomp - -s = stomp.Connection() -s.start() -s.connect() - -cnt = 0 - -current = [] -ld = {} - -t = tuio.Tracking() -try: - while True: - t.update() - - active = [] - for c in t.cursors(): - active.append(c.sessionid) - - tbr = [] - for c in current: - if c not in active: - tbr.append(c) - - tba = [] - for c in active: - if c not in current: - tba.append(c) - - current = active - - for c in tbr: - d = ld[c] - # cursor removed = 5 - s.send("5 %d %d %f %f 0" % (c, c, d[1], d[2]), destination="/topic/home") - ld.pop(c) - - # for c in tba: - # s.send("C N %d" % c, destination="/topic/home") - - for c in t.cursors(): - data = (c.sessionid, c.sessionid, c.xpos, c.ypos) - if not ld.get(c.sessionid, None) == data: - if c.sessionid in tba: - # cursor new = 3 - msg = "3 %d %d %f %f 0" % data - else: - # cursor update = 4 - msg = "4 %d %d %f %f 0" % data - s.send(msg, destination="/topic/home") - ld[c.sessionid] = data - cnt += 1 - -except KeyboardInterrupt: - t.stop() - diff -r fcf435874395 -r 45c889eae324 front_idill/extern/fajran-tuiojs/connector/stomp/tuio.stomp.js --- a/front_idill/extern/fajran-tuiojs/connector/stomp/tuio.stomp.js Thu Apr 19 11:53:06 2012 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,49 +0,0 @@ - -tuio.setConnector({ - _host: 'localhost', - _port: 61613, - _user: 'guest', - _pass: 'guest', - _topic: '/topic/home', - - _client: undefined, - - start: function() { - var self = this; - var sc = new STOMPClient(); - self._client = sc; - - sc.onopen = function() { - } - sc.onclose = function(code) { - } - sc.onerror = function(err) { - } - sc.onerrorframe = function(frame) { - } - sc.onconnectedframe = function() { - sc.subscribe(self._topic, {exchange:''}); - } - sc.onmessageframe = function(frame) { - self._process(frame.body.split(" ")); - } - setTimeout(function() { - sc.connect(self._host, self._port, self._user, self._pass); - }, 10); - }, - - stop: function() { - this._client.reset(); - }, - - _process: function(data) { - var type = parseInt(data[0]); - var sid = parseInt(data[1]); - var fid = parseInt(data[2]); - var x = parseFloat(data[3]); - var y = parseFloat(data[4]); - var angle = parseFloat(data[5]); - - tuio.callback(type, sid, fid, x, y, angle); - } -}); diff -r fcf435874395 -r 45c889eae324 front_idill/extern/fajran-tuiojs/examples/dump.html --- a/front_idill/extern/fajran-tuiojs/examples/dump.html Thu Apr 19 11:53:06 2012 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,48 +0,0 @@ - - - - - - - - - - diff -r fcf435874395 -r 45c889eae324 front_idill/extern/fajran-tuiojs/examples/fire.html --- a/front_idill/extern/fajran-tuiojs/examples/fire.html Thu Apr 19 11:53:06 2012 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,74 +0,0 @@ - - -TUIO Client plugin test - - - - - - - - - - - diff -r fcf435874395 -r 45c889eae324 front_idill/extern/fajran-tuiojs/examples/log.js --- a/front_idill/extern/fajran-tuiojs/examples/log.js Thu Apr 19 11:53:06 2012 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,23 +0,0 @@ - -var logs = []; -var max = 20; - -function updateLog() { - if (logs.length > max) { - logs = logs.splice(logs.length - max); - } - - var text = logs.join("\n"); - document.getElementById('log').innerHTML = text; -} - -function log(msg) { - if (console.log) { - console.log(msg); - } - else { - logs.push(msg); - updateLog(); - } -} - diff -r fcf435874395 -r 45c889eae324 front_idill/extern/fajran-tuiojs/examples/paint.html --- a/front_idill/extern/fajran-tuiojs/examples/paint.html Thu Apr 19 11:53:06 2012 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,54 +0,0 @@ - - -TUIO Client plugin test - - - - - - - - - - - diff -r fcf435874395 -r 45c889eae324 front_idill/extern/fajran-tuiojs/examples/processingjs/README.txt --- a/front_idill/extern/fajran-tuiojs/examples/processingjs/README.txt Thu Apr 19 11:53:06 2012 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,6 +0,0 @@ -Before you can start using the examples, download the processingjs and -its initialization script first. Put them inside this directory. - -- http://github.com/jeresig/processing-js/raw/master/processing.js -- http://github.com/jeresig/processing-js/raw/master/examples/init.js - diff -r fcf435874395 -r 45c889eae324 front_idill/extern/fajran-tuiojs/examples/processingjs/hand_pointing.html --- a/front_idill/extern/fajran-tuiojs/examples/processingjs/hand_pointing.html Thu Apr 19 11:53:06 2012 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,152 +0,0 @@ - - - - - - - - - - - -
- - -
- diff -r fcf435874395 -r 45c889eae324 front_idill/extern/fajran-tuiojs/examples/processingjs/init.js --- a/front_idill/extern/fajran-tuiojs/examples/processingjs/init.js Thu Apr 19 11:53:06 2012 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,37 +0,0 @@ -/* -* This code searches for all the - - - - - - - - - - diff -r fcf435874395 -r 45c889eae324 front_idill/extern/fajran-tuiojs/examples/processingjs/processing.js --- a/front_idill/extern/fajran-tuiojs/examples/processingjs/processing.js Thu Apr 19 11:53:06 2012 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,19812 +0,0 @@ - -(function(window, document, Math, undef) { - - var nop = function(){}; - - var debug = (function() { - if ("console" in window) { - return function(msg) { - window.console.log('Processing.js: ' + msg); - }; - } - return nop(); - }()); - - var ajax = function(url) { - var xhr = new XMLHttpRequest(); - xhr.open("GET", url, false); - if (xhr.overrideMimeType) { - xhr.overrideMimeType("text/plain"); - } - xhr.setRequestHeader("If-Modified-Since", "Fri, 01 Jan 1960 00:00:00 GMT"); - xhr.send(null); - // failed request? - if (xhr.status !== 200 && xhr.status !== 0) { throw ("XMLHttpRequest failed, status code " + xhr.status); } - return xhr.responseText; - }; - - var isDOMPresent = ("document" in this) && !("fake" in this.document); - - // document.head polyfill for the benefit of Firefox 3.6 - document.head = document.head || document.getElementsByTagName('head')[0]; - - // Typed Arrays: fallback to WebGL arrays or Native JS arrays if unavailable - function setupTypedArray(name, fallback) { - // Check if TypedArray exists, and use if so. - if (name in window) { - return window[name]; - } - - // Check if WebGLArray exists - if (typeof window[fallback] === "function") { - return window[fallback]; - } - - // Use Native JS array - return function(obj) { - if (obj instanceof Array) { - return obj; - } - if (typeof obj === "number") { - var arr = []; - arr.length = obj; - return arr; - } - }; - } - - var Float32Array = setupTypedArray("Float32Array", "WebGLFloatArray"), - Int32Array = setupTypedArray("Int32Array", "WebGLIntArray"), - Uint16Array = setupTypedArray("Uint16Array", "WebGLUnsignedShortArray"), - Uint8Array = setupTypedArray("Uint8Array", "WebGLUnsignedByteArray"); - - /* Browsers fixes end */ - - /** - * NOTE: in releases we replace symbolic PConstants.* names with their values. - * Using PConstants.* in code below is fine. See tools/rewrite-pconstants.js. - */ - var PConstants = { - X: 0, - Y: 1, - Z: 2, - - R: 3, - G: 4, - B: 5, - A: 6, - - U: 7, - V: 8, - - NX: 9, - NY: 10, - NZ: 11, - - EDGE: 12, - - // Stroke - SR: 13, - SG: 14, - SB: 15, - SA: 16, - - SW: 17, - - // Transformations (2D and 3D) - TX: 18, - TY: 19, - TZ: 20, - - VX: 21, - VY: 22, - VZ: 23, - VW: 24, - - // Material properties - AR: 25, - AG: 26, - AB: 27, - - DR: 3, - DG: 4, - DB: 5, - DA: 6, - - SPR: 28, - SPG: 29, - SPB: 30, - - SHINE: 31, - - ER: 32, - EG: 33, - EB: 34, - - BEEN_LIT: 35, - - VERTEX_FIELD_COUNT: 36, - - // Renderers - P2D: 1, - JAVA2D: 1, - WEBGL: 2, - P3D: 2, - OPENGL: 2, - PDF: 0, - DXF: 0, - - // Platform IDs - OTHER: 0, - WINDOWS: 1, - MAXOSX: 2, - LINUX: 3, - - EPSILON: 0.0001, - - MAX_FLOAT: 3.4028235e+38, - MIN_FLOAT: -3.4028235e+38, - MAX_INT: 2147483647, - MIN_INT: -2147483648, - - PI: Math.PI, - TWO_PI: 2 * Math.PI, - HALF_PI: Math.PI / 2, - THIRD_PI: Math.PI / 3, - QUARTER_PI: Math.PI / 4, - - DEG_TO_RAD: Math.PI / 180, - RAD_TO_DEG: 180 / Math.PI, - - WHITESPACE: " \t\n\r\f\u00A0", - - // Color modes - RGB: 1, - ARGB: 2, - HSB: 3, - ALPHA: 4, - CMYK: 5, - - // Image file types - TIFF: 0, - TARGA: 1, - JPEG: 2, - GIF: 3, - - // Filter/convert types - BLUR: 11, - GRAY: 12, - INVERT: 13, - OPAQUE: 14, - POSTERIZE: 15, - THRESHOLD: 16, - ERODE: 17, - DILATE: 18, - - // Blend modes - REPLACE: 0, - BLEND: 1 << 0, - ADD: 1 << 1, - SUBTRACT: 1 << 2, - LIGHTEST: 1 << 3, - DARKEST: 1 << 4, - DIFFERENCE: 1 << 5, - EXCLUSION: 1 << 6, - MULTIPLY: 1 << 7, - SCREEN: 1 << 8, - OVERLAY: 1 << 9, - HARD_LIGHT: 1 << 10, - SOFT_LIGHT: 1 << 11, - DODGE: 1 << 12, - BURN: 1 << 13, - - // Color component bit masks - ALPHA_MASK: 0xff000000, - RED_MASK: 0x00ff0000, - GREEN_MASK: 0x0000ff00, - BLUE_MASK: 0x000000ff, - - // Projection matrices - CUSTOM: 0, - ORTHOGRAPHIC: 2, - PERSPECTIVE: 3, - - // Shapes - POINT: 2, - POINTS: 2, - LINE: 4, - LINES: 4, - TRIANGLE: 8, - TRIANGLES: 9, - TRIANGLE_STRIP: 10, - TRIANGLE_FAN: 11, - QUAD: 16, - QUADS: 16, - QUAD_STRIP: 17, - POLYGON: 20, - PATH: 21, - RECT: 30, - ELLIPSE: 31, - ARC: 32, - SPHERE: 40, - BOX: 41, - - GROUP: 0, - PRIMITIVE: 1, - //PATH: 21, // shared with Shape PATH - GEOMETRY: 3, - - // Shape Vertex - VERTEX: 0, - BEZIER_VERTEX: 1, - CURVE_VERTEX: 2, - BREAK: 3, - CLOSESHAPE: 4, - - // Shape closing modes - OPEN: 1, - CLOSE: 2, - - // Shape drawing modes - CORNER: 0, // Draw mode convention to use (x, y) to (width, height) - CORNERS: 1, // Draw mode convention to use (x1, y1) to (x2, y2) coordinates - RADIUS: 2, // Draw mode from the center, and using the radius - CENTER_RADIUS: 2, // Deprecated! Use RADIUS instead - CENTER: 3, // Draw from the center, using second pair of values as the diameter - DIAMETER: 3, // Synonym for the CENTER constant. Draw from the center - CENTER_DIAMETER: 3, // Deprecated! Use DIAMETER instead - - // Text vertical alignment modes - BASELINE: 0, // Default vertical alignment for text placement - TOP: 101, // Align text to the top - BOTTOM: 102, // Align text from the bottom, using the baseline - - // UV Texture coordinate modes - NORMAL: 1, - NORMALIZED: 1, - IMAGE: 2, - - // Text placement modes - MODEL: 4, - SHAPE: 5, - - // Stroke modes - SQUARE: 'butt', - ROUND: 'round', - PROJECT: 'square', - MITER: 'miter', - BEVEL: 'bevel', - - // Lighting modes - AMBIENT: 0, - DIRECTIONAL: 1, - //POINT: 2, Shared with Shape constant - SPOT: 3, - - // Key constants - - // Both key and keyCode will be equal to these values - BACKSPACE: 8, - TAB: 9, - ENTER: 10, - RETURN: 13, - ESC: 27, - DELETE: 127, - CODED: 0xffff, - - // p.key will be CODED and p.keyCode will be this value - SHIFT: 16, - CONTROL: 17, - ALT: 18, - CAPSLK: 20, - PGUP: 33, - PGDN: 34, - END: 35, - HOME: 36, - LEFT: 37, - UP: 38, - RIGHT: 39, - DOWN: 40, - F1: 112, - F2: 113, - F3: 114, - F4: 115, - F5: 116, - F6: 117, - F7: 118, - F8: 119, - F9: 120, - F10: 121, - F11: 122, - F12: 123, - NUMLK: 144, - META: 157, - INSERT: 155, - - // Cursor types - ARROW: 'default', - CROSS: 'crosshair', - HAND: 'pointer', - MOVE: 'move', - TEXT: 'text', - WAIT: 'wait', - NOCURSOR: "url('data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw=='), auto", - - // Hints - DISABLE_OPENGL_2X_SMOOTH: 1, - ENABLE_OPENGL_2X_SMOOTH: -1, - ENABLE_OPENGL_4X_SMOOTH: 2, - ENABLE_NATIVE_FONTS: 3, - DISABLE_DEPTH_TEST: 4, - ENABLE_DEPTH_TEST: -4, - ENABLE_DEPTH_SORT: 5, - DISABLE_DEPTH_SORT: -5, - DISABLE_OPENGL_ERROR_REPORT: 6, - ENABLE_OPENGL_ERROR_REPORT: -6, - ENABLE_ACCURATE_TEXTURES: 7, - DISABLE_ACCURATE_TEXTURES: -7, - HINT_COUNT: 10, - - // PJS defined constants - SINCOS_LENGTH: 720, // every half degree - PRECISIONB: 15, // fixed point precision is limited to 15 bits!! - PRECISIONF: 1 << 15, - PREC_MAXVAL: (1 << 15) - 1, - PREC_ALPHA_SHIFT: 24 - 15, - PREC_RED_SHIFT: 16 - 15, - NORMAL_MODE_AUTO: 0, - NORMAL_MODE_SHAPE: 1, - NORMAL_MODE_VERTEX: 2, - MAX_LIGHTS: 8 - }; - - /** - * Returns Java hashCode() result for the object. If the object has the "hashCode" function, - * it preforms the call of this function. Otherwise it uses/creates the "$id" property, - * which is used as the hashCode. - * - * @param {Object} obj The object. - * @returns {int} The object's hash code. - */ - function virtHashCode(obj) { - if (typeof(obj) === "string") { - var hash = 0; - for (var i = 0; i < obj.length; ++i) { - hash = (hash * 31 + obj.charCodeAt(i)) & 0xFFFFFFFF; - } - return hash; - } - if (typeof(obj) !== "object") { - return obj & 0xFFFFFFFF; - } - if (obj.hashCode instanceof Function) { - return obj.hashCode(); - } - if (obj.$id === undef) { - obj.$id = ((Math.floor(Math.random() * 0x10000) - 0x8000) << 16) | Math.floor(Math.random() * 0x10000); - } - return obj.$id; - } - - /** - * Returns Java equals() result for two objects. If the first object - * has the "equals" function, it preforms the call of this function. - * Otherwise the method uses the JavaScript === operator. - * - * @param {Object} obj The first object. - * @param {Object} other The second object. - * - * @returns {boolean} true if the objects are equal. - */ - function virtEquals(obj, other) { - if (obj === null || other === null) { - return (obj === null) && (other === null); - } - if (typeof (obj) === "string") { - return obj === other; - } - if (typeof(obj) !== "object") { - return obj === other; - } - if (obj.equals instanceof Function) { - return obj.equals(other); - } - return obj === other; - } - - /** - * A ObjectIterator is an iterator wrapper for objects. If passed object contains - * the iterator method, the object instance will be replaced by the result returned by - * this method call. If passed object is an array, the ObjectIterator instance iterates - * through its items. - * - * @param {Object} obj The object to be iterated. - */ - var ObjectIterator = function(obj) { - if (obj.iterator instanceof Function) { - return obj.iterator(); - } - if (obj instanceof Array) { - // iterate through array items - var index = -1; - this.hasNext = function() { - return ++index < obj.length; - }; - this.next = function() { - return obj[index]; - }; - } else { - throw "Unable to iterate: " + obj; - } - }; - - /** - * An ArrayList stores a variable number of objects. - * - * @param {int} initialCapacity optional defines the initial capacity of the list, it's empty by default - * - * @returns {ArrayList} new ArrayList object - */ - var ArrayList = (function() { - function Iterator(array) { - var index = 0; - this.hasNext = function() { - return index < array.length; - }; - - this.next = function() { - return array[index++]; - }; - - this.remove = function() { - array.splice(index, 1); - }; - } - - function ArrayList() { - var array; - if (arguments.length === 0) { - array = []; - } else if (arguments.length > 0 && typeof arguments[0] !== 'number') { - array = arguments[0].toArray(); - } else { - array = []; - array.length = 0 | arguments[0]; - } - - /** - * @member ArrayList - * ArrayList.get() Returns the element at the specified position in this list. - * - * @param {int} i index of element to return - * - * @returns {Object} the element at the specified position in this list. - */ - this.get = function(i) { - return array[i]; - }; - /** - * @member ArrayList - * ArrayList.contains() Returns true if this list contains the specified element. - * - * @param {Object} item element whose presence in this List is to be tested. - * - * @returns {boolean} true if the specified element is present; false otherwise. - */ - this.contains = function(item) { - return this.indexOf(item)>-1; - }; - /** - * @member ArrayList - * ArrayList.indexOf() Returns the position this element takes in the list, or -1 if the element is not found. - * - * @param {Object} item element whose position in this List is to be tested. - * - * @returns {int} the list position that the first match for this element holds in the list, or -1 if it is not in the list. - */ - this.indexOf = function(item) { - for (var i = 0, len = array.length; i < len; ++i) { - if (virtEquals(item, array[i])) { - return i; - } - } - return -1; - }; - /** - * @member ArrayList - * ArrayList.add() Adds the specified element to this list. - * - * @param {int} index optional index at which the specified element is to be inserted - * @param {Object} object element to be added to the list - */ - this.add = function() { - if (arguments.length === 1) { - array.push(arguments[0]); // for add(Object) - } else if (arguments.length === 2) { - var arg0 = arguments[0]; - if (typeof arg0 === 'number') { - if (arg0 >= 0 && arg0 <= array.length) { - array.splice(arg0, 0, arguments[1]); // for add(i, Object) - } else { - throw(arg0 + " is not a valid index"); - } - } else { - throw(typeof arg0 + " is not a number"); - } - } else { - throw("Please use the proper number of parameters."); - } - }; - /** - * @member ArrayList - * ArrayList.addAll(collection) appends all of the elements in the specified - * Collection to the end of this list, in the order that they are returned by - * the specified Collection's Iterator. - * - * When called as addAll(index, collection) the elements are inserted into - * this list at the position indicated by index. - * - * @param {index} Optional; specifies the position the colletion should be inserted at - * @param {collection} Any iterable object (ArrayList, HashMap.keySet(), etc.) - * @throws out of bounds error for negative index, or index greater than list size. - */ - this.addAll = function(arg1, arg2) { - // addAll(int, Collection) - var it; - if (typeof arg1 === "number") { - if (arg1 < 0 || arg1 > array.length) { - throw("Index out of bounds for addAll: " + arg1 + " greater or equal than " + array.length); - } - it = new ObjectIterator(arg2); - while (it.hasNext()) { - array.splice(arg1++, 0, it.next()); - } - } - // addAll(Collection) - else { - it = new ObjectIterator(arg1); - while (it.hasNext()) { - array.push(it.next()); - } - } - }; - /** - * @member ArrayList - * ArrayList.set() Replaces the element at the specified position in this list with the specified element. - * - * @param {int} index index of element to replace - * @param {Object} object element to be stored at the specified position - */ - this.set = function() { - if (arguments.length === 2) { - var arg0 = arguments[0]; - if (typeof arg0 === 'number') { - if (arg0 >= 0 && arg0 < array.length) { - array.splice(arg0, 1, arguments[1]); - } else { - throw(arg0 + " is not a valid index."); - } - } else { - throw(typeof arg0 + " is not a number"); - } - } else { - throw("Please use the proper number of parameters."); - } - }; - - /** - * @member ArrayList - * ArrayList.size() Returns the number of elements in this list. - * - * @returns {int} the number of elements in this list - */ - this.size = function() { - return array.length; - }; - - /** - * @member ArrayList - * ArrayList.clear() Removes all of the elements from this list. The list will be empty after this call returns. - */ - this.clear = function() { - array.length = 0; - }; - - /** - * @member ArrayList - * ArrayList.remove() Removes an element either based on index, if the argument is a number, or - * by equality check, if the argument is an object. - * - * @param {int|Object} item either the index of the element to be removed, or the element itself. - * - * @returns {Object|boolean} If removal is by index, the element that was removed, or null if nothing was removed. If removal is by object, true if removal occurred, otherwise false. - */ - this.remove = function(item) { - if (typeof item === 'number') { - return array.splice(item, 1)[0]; - } - item = this.indexOf(item); - if (item > -1) { - array.splice(item, 1); - return true; - } - return false; - }; - - /** - * @member ArrayList - * ArrayList.isEmpty() Tests if this list has no elements. - * - * @returns {boolean} true if this list has no elements; false otherwise - */ - this.isEmpty = function() { - return !array.length; - }; - - /** - * @member ArrayList - * ArrayList.clone() Returns a shallow copy of this ArrayList instance. (The elements themselves are not copied.) - * - * @returns {ArrayList} a clone of this ArrayList instance - */ - this.clone = function() { - return new ArrayList(this); - }; - - /** - * @member ArrayList - * ArrayList.toArray() Returns an array containing all of the elements in this list in the correct order. - * - * @returns {Object[]} Returns an array containing all of the elements in this list in the correct order - */ - this.toArray = function() { - return array.slice(0); - }; - - this.iterator = function() { - return new Iterator(array); - }; - } - - return ArrayList; - }()); - - /** - * A HashMap stores a collection of objects, each referenced by a key. This is similar to an Array, only - * instead of accessing elements with a numeric index, a String is used. (If you are familiar with - * associative arrays from other languages, this is the same idea.) - * - * @param {int} initialCapacity defines the initial capacity of the map, it's 16 by default - * @param {float} loadFactor the load factor for the map, the default is 0.75 - * @param {Map} m gives the new HashMap the same mappings as this Map - */ - var HashMap = (function() { - /** - * @member HashMap - * A HashMap stores a collection of objects, each referenced by a key. This is similar to an Array, only - * instead of accessing elements with a numeric index, a String is used. (If you are familiar with - * associative arrays from other languages, this is the same idea.) - * - * @param {int} initialCapacity defines the initial capacity of the map, it's 16 by default - * @param {float} loadFactor the load factor for the map, the default is 0.75 - * @param {Map} m gives the new HashMap the same mappings as this Map - */ - function HashMap() { - if (arguments.length === 1 && arguments[0] instanceof HashMap) { - return arguments[0].clone(); - } - - var initialCapacity = arguments.length > 0 ? arguments[0] : 16; - var loadFactor = arguments.length > 1 ? arguments[1] : 0.75; - var buckets = []; - buckets.length = initialCapacity; - var count = 0; - var hashMap = this; - - function getBucketIndex(key) { - var index = virtHashCode(key) % buckets.length; - return index < 0 ? buckets.length + index : index; - } - function ensureLoad() { - if (count <= loadFactor * buckets.length) { - return; - } - var allEntries = []; - for (var i = 0; i < buckets.length; ++i) { - if (buckets[i] !== undef) { - allEntries = allEntries.concat(buckets[i]); - } - } - var newBucketsLength = buckets.length * 2; - buckets = []; - buckets.length = newBucketsLength; - for (var j = 0; j < allEntries.length; ++j) { - var index = getBucketIndex(allEntries[j].key); - var bucket = buckets[index]; - if (bucket === undef) { - buckets[index] = bucket = []; - } - bucket.push(allEntries[j]); - } - } - - function Iterator(conversion, removeItem) { - var bucketIndex = 0; - var itemIndex = -1; - var endOfBuckets = false; - - function findNext() { - while (!endOfBuckets) { - ++itemIndex; - if (bucketIndex >= buckets.length) { - endOfBuckets = true; - } else if (buckets[bucketIndex] === undef || itemIndex >= buckets[bucketIndex].length) { - itemIndex = -1; - ++bucketIndex; - } else { - return; - } - } - } - - /* - * @member Iterator - * Checks if the Iterator has more items - */ - this.hasNext = function() { - return !endOfBuckets; - }; - - /* - * @member Iterator - * Return the next Item - */ - this.next = function() { - var result = conversion(buckets[bucketIndex][itemIndex]); - findNext(); - return result; - }; - - /* - * @member Iterator - * Remove the current item - */ - this.remove = function() { - removeItem(this.next()); - --itemIndex; - }; - - findNext(); - } - - function Set(conversion, isIn, removeItem) { - this.clear = function() { - hashMap.clear(); - }; - - this.contains = function(o) { - return isIn(o); - }; - - this.containsAll = function(o) { - var it = o.iterator(); - while (it.hasNext()) { - if (!this.contains(it.next())) { - return false; - } - } - return true; - }; - - this.isEmpty = function() { - return hashMap.isEmpty(); - }; - - this.iterator = function() { - return new Iterator(conversion, removeItem); - }; - - this.remove = function(o) { - if (this.contains(o)) { - removeItem(o); - return true; - } - return false; - }; - - this.removeAll = function(c) { - var it = c.iterator(); - var changed = false; - while (it.hasNext()) { - var item = it.next(); - if (this.contains(item)) { - removeItem(item); - changed = true; - } - } - return true; - }; - - this.retainAll = function(c) { - var it = this.iterator(); - var toRemove = []; - while (it.hasNext()) { - var entry = it.next(); - if (!c.contains(entry)) { - toRemove.push(entry); - } - } - for (var i = 0; i < toRemove.length; ++i) { - removeItem(toRemove[i]); - } - return toRemove.length > 0; - }; - - this.size = function() { - return hashMap.size(); - }; - - this.toArray = function() { - var result = []; - var it = this.iterator(); - while (it.hasNext()) { - result.push(it.next()); - } - return result; - }; - } - - function Entry(pair) { - this._isIn = function(map) { - return map === hashMap && (pair.removed === undef); - }; - - this.equals = function(o) { - return virtEquals(pair.key, o.getKey()); - }; - - this.getKey = function() { - return pair.key; - }; - - this.getValue = function() { - return pair.value; - }; - - this.hashCode = function(o) { - return virtHashCode(pair.key); - }; - - this.setValue = function(value) { - var old = pair.value; - pair.value = value; - return old; - }; - } - - this.clear = function() { - count = 0; - buckets = []; - buckets.length = initialCapacity; - }; - - this.clone = function() { - var map = new HashMap(); - map.putAll(this); - return map; - }; - - this.containsKey = function(key) { - var index = getBucketIndex(key); - var bucket = buckets[index]; - if (bucket === undef) { - return false; - } - for (var i = 0; i < bucket.length; ++i) { - if (virtEquals(bucket[i].key, key)) { - return true; - } - } - return false; - }; - - this.containsValue = function(value) { - for (var i = 0; i < buckets.length; ++i) { - var bucket = buckets[i]; - if (bucket === undef) { - continue; - } - for (var j = 0; j < bucket.length; ++j) { - if (virtEquals(bucket[j].value, value)) { - return true; - } - } - } - return false; - }; - - this.entrySet = function() { - return new Set( - - function(pair) { - return new Entry(pair); - }, - - function(pair) { - return (pair instanceof Entry) && pair._isIn(hashMap); - }, - - function(pair) { - return hashMap.remove(pair.getKey()); - }); - }; - - this.get = function(key) { - var index = getBucketIndex(key); - var bucket = buckets[index]; - if (bucket === undef) { - return null; - } - for (var i = 0; i < bucket.length; ++i) { - if (virtEquals(bucket[i].key, key)) { - return bucket[i].value; - } - } - return null; - }; - - this.isEmpty = function() { - return count === 0; - }; - - this.keySet = function() { - return new Set( - // get key from pair - function(pair) { - return pair.key; - }, - // is-in test - function(key) { - return hashMap.containsKey(key); - }, - // remove from hashmap by key - function(key) { - return hashMap.remove(key); - } - ); - }; - - this.values = function() { - return new Set( - // get value from pair - function(pair) { - return pair.value; - }, - // is-in test - function(value) { - return hashMap.containsValue(value); - }, - // remove from hashmap by value - function(value) { - return hashMap.removeByValue(value); - } - ); - }; - - this.put = function(key, value) { - var index = getBucketIndex(key); - var bucket = buckets[index]; - if (bucket === undef) { - ++count; - buckets[index] = [{ - key: key, - value: value - }]; - ensureLoad(); - return null; - } - for (var i = 0; i < bucket.length; ++i) { - if (virtEquals(bucket[i].key, key)) { - var previous = bucket[i].value; - bucket[i].value = value; - return previous; - } - } - ++count; - bucket.push({ - key: key, - value: value - }); - ensureLoad(); - return null; - }; - - this.putAll = function(m) { - var it = m.entrySet().iterator(); - while (it.hasNext()) { - var entry = it.next(); - this.put(entry.getKey(), entry.getValue()); - } - }; - - this.remove = function(key) { - var index = getBucketIndex(key); - var bucket = buckets[index]; - if (bucket === undef) { - return null; - } - for (var i = 0; i < bucket.length; ++i) { - if (virtEquals(bucket[i].key, key)) { - --count; - var previous = bucket[i].value; - bucket[i].removed = true; - if (bucket.length > 1) { - bucket.splice(i, 1); - } else { - buckets[index] = undef; - } - return previous; - } - } - return null; - }; - - this.removeByValue = function(value) { - var bucket, i, ilen, pair; - for (bucket in buckets) { - if (buckets.hasOwnProperty(bucket)) { - for (i = 0, ilen = buckets[bucket].length; i < ilen; i++) { - pair = buckets[bucket][i]; - // removal on values is based on identity, not equality - if (pair.value === value) { - buckets[bucket].splice(i, 1); - return true; - } - } - } - } - return false; - }; - - this.size = function() { - return count; - }; - } - - return HashMap; - }()); - - var PVector = (function() { - function PVector(x, y, z) { - this.x = x || 0; - this.y = y || 0; - this.z = z || 0; - } - - PVector.dist = function(v1, v2) { - return v1.dist(v2); - }; - - PVector.dot = function(v1, v2) { - return v1.dot(v2); - }; - - PVector.cross = function(v1, v2) { - return v1.cross(v2); - }; - - PVector.angleBetween = function(v1, v2) { - return Math.acos(v1.dot(v2) / (v1.mag() * v2.mag())); - }; - - // Common vector operations for PVector - PVector.prototype = { - set: function(v, y, z) { - if (arguments.length === 1) { - this.set(v.x || v[0] || 0, - v.y || v[1] || 0, - v.z || v[2] || 0); - } else { - this.x = v; - this.y = y; - this.z = z; - } - }, - get: function() { - return new PVector(this.x, this.y, this.z); - }, - mag: function() { - var x = this.x, - y = this.y, - z = this.z; - return Math.sqrt(x * x + y * y + z * z); - }, - add: function(v, y, z) { - if (arguments.length === 1) { - this.x += v.x; - this.y += v.y; - this.z += v.z; - } else { - this.x += v; - this.y += y; - this.z += z; - } - }, - sub: function(v, y, z) { - if (arguments.length === 1) { - this.x -= v.x; - this.y -= v.y; - this.z -= v.z; - } else { - this.x -= v; - this.y -= y; - this.z -= z; - } - }, - mult: function(v) { - if (typeof v === 'number') { - this.x *= v; - this.y *= v; - this.z *= v; - } else { - this.x *= v.x; - this.y *= v.y; - this.z *= v.z; - } - }, - div: function(v) { - if (typeof v === 'number') { - this.x /= v; - this.y /= v; - this.z /= v; - } else { - this.x /= v.x; - this.y /= v.y; - this.z /= v.z; - } - }, - dist: function(v) { - var dx = this.x - v.x, - dy = this.y - v.y, - dz = this.z - v.z; - return Math.sqrt(dx * dx + dy * dy + dz * dz); - }, - dot: function(v, y, z) { - if (arguments.length === 1) { - return (this.x * v.x + this.y * v.y + this.z * v.z); - } - return (this.x * v + this.y * y + this.z * z); - }, - cross: function(v) { - var x = this.x, - y = this.y, - z = this.z; - return new PVector(y * v.z - v.y * z, - z * v.x - v.z * x, - x * v.y - v.x * y); - }, - normalize: function() { - var m = this.mag(); - if (m > 0) { - this.div(m); - } - }, - limit: function(high) { - if (this.mag() > high) { - this.normalize(); - this.mult(high); - } - }, - heading2D: function() { - return (-Math.atan2(-this.y, this.x)); - }, - toString: function() { - return "[" + this.x + ", " + this.y + ", " + this.z + "]"; - }, - array: function() { - return [this.x, this.y, this.z]; - } - }; - - function createPVectorMethod(method) { - return function(v1, v2) { - var v = v1.get(); - v[method](v2); - return v; - }; - } - - for (var method in PVector.prototype) { - if (PVector.prototype.hasOwnProperty(method) && !PVector.hasOwnProperty(method)) { - PVector[method] = createPVectorMethod(method); - } - } - - return PVector; - }()); - - // Building defaultScope. Changing of the prototype protects - // internal Processing code from the changes in defaultScope - function DefaultScope() {} - DefaultScope.prototype = PConstants; - - var defaultScope = new DefaultScope(); - defaultScope.ArrayList = ArrayList; - defaultScope.HashMap = HashMap; - defaultScope.PVector = PVector; - defaultScope.ObjectIterator = ObjectIterator; - defaultScope.PConstants = PConstants; - //defaultScope.PImage = PImage; // TODO - //defaultScope.PShape = PShape; // TODO - //defaultScope.PShapeSVG = PShapeSVG; // TODO - - //////////////////////////////////////////////////////////////////////////// - // Class inheritance helper methods - //////////////////////////////////////////////////////////////////////////// - - defaultScope.defineProperty = function(obj, name, desc) { - if("defineProperty" in Object) { - Object.defineProperty(obj, name, desc); - } else { - if (desc.hasOwnProperty("get")) { - obj.__defineGetter__(name, desc.get); - } - if (desc.hasOwnProperty("set")) { - obj.__defineSetter__(name, desc.set); - } - } - }; - - function extendClass(subClass, baseClass) { - function extendGetterSetter(propertyName) { - defaultScope.defineProperty(subClass, propertyName, { - get: function() { - return baseClass[propertyName]; - }, - set: function(v) { - baseClass[propertyName]=v; - }, - enumerable: true - }); - } - - var properties = []; - for (var propertyName in baseClass) { - if (typeof baseClass[propertyName] === 'function') { - // Overriding all non-overriden functions - if (!subClass.hasOwnProperty(propertyName)) { - subClass[propertyName] = baseClass[propertyName]; - } - } else if(propertyName.charAt(0) !== "$" && !(propertyName in subClass)) { - // Delaying the properties extension due to the IE9 bug (see #918). - properties.push(propertyName); - } - } - while (properties.length > 0) { - extendGetterSetter(properties.shift()); - } - } - - defaultScope.extendClassChain = function(base) { - var path = [base]; - for (var self = base.$upcast; self; self = self.$upcast) { - extendClass(self, base); - path.push(self); - base = self; - } - while (path.length > 0) { - path.pop().$self=base; - } - }; - - defaultScope.extendStaticMembers = function(derived, base) { - extendClass(derived, base); - }; - - defaultScope.extendInterfaceMembers = function(derived, base) { - extendClass(derived, base); - }; - - defaultScope.addMethod = function(object, name, fn, superAccessor) { - if (object[name]) { - var args = fn.length, - oldfn = object[name]; - - object[name] = function() { - if (arguments.length === args) { - return fn.apply(this, arguments); - } - return oldfn.apply(this, arguments); - }; - } else { - object[name] = fn; - } - }; - - defaultScope.createJavaArray = function(type, bounds) { - var result = null; - if (typeof bounds[0] === 'number') { - var itemsCount = 0 | bounds[0]; - if (bounds.length <= 1) { - result = []; - result.length = itemsCount; - for (var i = 0; i < itemsCount; ++i) { - result[i] = 0; - } - } else { - result = []; - var newBounds = bounds.slice(1); - for (var j = 0; j < itemsCount; ++j) { - result.push(defaultScope.createJavaArray(type, newBounds)); - } - } - } - return result; - }; - - var colors = { - aliceblue: "#f0f8ff", - antiquewhite: "#faebd7", - aqua: "#00ffff", - aquamarine: "#7fffd4", - azure: "#f0ffff", - beige: "#f5f5dc", - bisque: "#ffe4c4", - black: "#000000", - blanchedalmond: "#ffebcd", - blue: "#0000ff", - blueviolet: "#8a2be2", - brown: "#a52a2a", - burlywood: "#deb887", - cadetblue: "#5f9ea0", - chartreuse: "#7fff00", - chocolate: "#d2691e", - coral: "#ff7f50", - cornflowerblue: "#6495ed", - cornsilk: "#fff8dc", - crimson: "#dc143c", - cyan: "#00ffff", - darkblue: "#00008b", - darkcyan: "#008b8b", - darkgoldenrod: "#b8860b", - darkgray: "#a9a9a9", - darkgreen: "#006400", - darkkhaki: "#bdb76b", - darkmagenta: "#8b008b", - darkolivegreen: "#556b2f", - darkorange: "#ff8c00", - darkorchid: "#9932cc", - darkred: "#8b0000", - darksalmon: "#e9967a", - darkseagreen: "#8fbc8f", - darkslateblue: "#483d8b", - darkslategray: "#2f4f4f", - darkturquoise: "#00ced1", - darkviolet: "#9400d3", - deeppink: "#ff1493", - deepskyblue: "#00bfff", - dimgray: "#696969", - dodgerblue: "#1e90ff", - firebrick: "#b22222", - floralwhite: "#fffaf0", - forestgreen: "#228b22", - fuchsia: "#ff00ff", - gainsboro: "#dcdcdc", - ghostwhite: "#f8f8ff", - gold: "#ffd700", - goldenrod: "#daa520", - gray: "#808080", - green: "#008000", - greenyellow: "#adff2f", - honeydew: "#f0fff0", - hotpink: "#ff69b4", - indianred: "#cd5c5c", - indigo: "#4b0082", - ivory: "#fffff0", - khaki: "#f0e68c", - lavender: "#e6e6fa", - lavenderblush: "#fff0f5", - lawngreen: "#7cfc00", - lemonchiffon: "#fffacd", - lightblue: "#add8e6", - lightcoral: "#f08080", - lightcyan: "#e0ffff", - lightgoldenrodyellow: "#fafad2", - lightgrey: "#d3d3d3", - lightgreen: "#90ee90", - lightpink: "#ffb6c1", - lightsalmon: "#ffa07a", - lightseagreen: "#20b2aa", - lightskyblue: "#87cefa", - lightslategray: "#778899", - lightsteelblue: "#b0c4de", - lightyellow: "#ffffe0", - lime: "#00ff00", - limegreen: "#32cd32", - linen: "#faf0e6", - magenta: "#ff00ff", - maroon: "#800000", - mediumaquamarine: "#66cdaa", - mediumblue: "#0000cd", - mediumorchid: "#ba55d3", - mediumpurple: "#9370d8", - mediumseagreen: "#3cb371", - mediumslateblue: "#7b68ee", - mediumspringgreen: "#00fa9a", - mediumturquoise: "#48d1cc", - mediumvioletred: "#c71585", - midnightblue: "#191970", - mintcream: "#f5fffa", - mistyrose: "#ffe4e1", - moccasin: "#ffe4b5", - navajowhite: "#ffdead", - navy: "#000080", - oldlace: "#fdf5e6", - olive: "#808000", - olivedrab: "#6b8e23", - orange: "#ffa500", - orangered: "#ff4500", - orchid: "#da70d6", - palegoldenrod: "#eee8aa", - palegreen: "#98fb98", - paleturquoise: "#afeeee", - palevioletred: "#d87093", - papayawhip: "#ffefd5", - peachpuff: "#ffdab9", - peru: "#cd853f", - pink: "#ffc0cb", - plum: "#dda0dd", - powderblue: "#b0e0e6", - purple: "#800080", - red: "#ff0000", - rosybrown: "#bc8f8f", - royalblue: "#4169e1", - saddlebrown: "#8b4513", - salmon: "#fa8072", - sandybrown: "#f4a460", - seagreen: "#2e8b57", - seashell: "#fff5ee", - sienna: "#a0522d", - silver: "#c0c0c0", - skyblue: "#87ceeb", - slateblue: "#6a5acd", - slategray: "#708090", - snow: "#fffafa", - springgreen: "#00ff7f", - steelblue: "#4682b4", - tan: "#d2b48c", - teal: "#008080", - thistle: "#d8bfd8", - tomato: "#ff6347", - turquoise: "#40e0d0", - violet: "#ee82ee", - wheat: "#f5deb3", - white: "#ffffff", - whitesmoke: "#f5f5f5", - yellow: "#ffff00", - yellowgreen: "#9acd32" - }; - - // Unsupported Processing File and I/O operations. - (function(Processing) { - var unsupportedP5 = ("open() createOutput() createInput() BufferedReader selectFolder() " + - "dataPath() createWriter() selectOutput() beginRecord() " + - "saveStream() endRecord() selectInput() saveBytes() createReader() " + - "beginRaw() endRaw() PrintWriter delay()").split(" "), - count = unsupportedP5.length, - prettyName, - p5Name; - - function createUnsupportedFunc(n) { - return function() { - throw "Processing.js does not support " + n + "."; - }; - } - - while (count--) { - prettyName = unsupportedP5[count]; - p5Name = prettyName.replace("()", ""); - - Processing[p5Name] = createUnsupportedFunc(prettyName); - } - }(defaultScope)); - - // screenWidth and screenHeight are shared by all instances. - // and return the width/height of the browser's viewport. - defaultScope.defineProperty(defaultScope, 'screenWidth', - { get: function() { return window.innerWidth; } }); - - defaultScope.defineProperty(defaultScope, 'screenHeight', - { get: function() { return window.innerHeight; } }); - - // Manage multiple Processing instances - var processingInstances = []; - var processingInstanceIds = {}; - - var removeInstance = function(id) { - processingInstances.splice(processingInstanceIds[id], 1); - delete processingInstanceIds[id]; - }; - - var addInstance = function(processing) { - if (processing.externals.canvas.id === undef || !processing.externals.canvas.id.length) { - processing.externals.canvas.id = "__processing" + processingInstances.length; - } - processingInstanceIds[processing.externals.canvas.id] = processingInstances.length; - processingInstances.push(processing); - }; - - - //////////////////////////////////////////////////////////////////////////// - // PFONT.JS START - //////////////////////////////////////////////////////////////////////////// - - /** - * [internal function] computeFontMetrics() calculates various metrics for text - * placement. Currently this function computes the ascent, descent and leading - * (from "lead", used for vertical space) values for the currently active font. - */ - function computeFontMetrics(pfont) { - var emQuad = 250, - correctionFactor = pfont.size / emQuad, - canvas = document.createElement("canvas"); - canvas.width = 2*emQuad; - canvas.height = 2*emQuad; - canvas.style.opacity = 0; - var cfmFont = pfont.getCSSDefinition(emQuad+"px", "normal"), - ctx = canvas.getContext("2d"); - ctx.font = cfmFont; - pfont.context2d = ctx; - - // Size the canvas using a string with common max-ascent and max-descent letters. - // Changing the canvas dimensions resets the context, so we must reset the font. - var protrusions = "dbflkhyjqpg"; - canvas.width = ctx.measureText(protrusions).width; - ctx.font = cfmFont; - - // for text lead values, we meaure a multiline text container. - var leadDiv = document.createElement("div"); - leadDiv.style.position = "absolute"; - leadDiv.style.opacity = 0; - leadDiv.style.fontFamily = '"' + pfont.name + '"'; - leadDiv.style.fontSize = emQuad + "px"; - leadDiv.innerHTML = protrusions + "
" + protrusions; - document.body.appendChild(leadDiv); - - var w = canvas.width, - h = canvas.height, - baseline = h/2; - - // Set all canvas pixeldata values to 255, with all the content - // data being 0. This lets us scan for data[i] != 255. - ctx.fillStyle = "white"; - ctx.fillRect(0, 0, w, h); - ctx.fillStyle = "black"; - ctx.fillText(protrusions, 0, baseline); - var pixelData = ctx.getImageData(0, 0, w, h).data; - - // canvas pixel data is w*4 by h*4, because R, G, B and A are separate, - // consecutive values in the array, rather than stored as 32 bit ints. - var i = 0, - w4 = w * 4, - len = pixelData.length; - - // Finding the ascent uses a normal, forward scanline - while (++i < len && pixelData[i] === 255) { - nop(); - } - var ascent = Math.round(i / w4); - - // Finding the descent uses a reverse scanline - i = len - 1; - while (--i > 0 && pixelData[i] === 255) { - nop(); - } - var descent = Math.round(i / w4); - - // set font metrics - pfont.ascent = correctionFactor * (baseline - ascent); - pfont.descent = correctionFactor * (descent - baseline); - - // Then we try to get the real value from the browser - if (document.defaultView.getComputedStyle) { - var leadDivHeight = document.defaultView.getComputedStyle(leadDiv,null).getPropertyValue("height"); - leadDivHeight = correctionFactor * leadDivHeight.replace("px",""); - if (leadDivHeight >= pfont.size * 2) { - pfont.leading = Math.round(leadDivHeight/2); - } - } - document.body.removeChild(leadDiv); - } - - // Defines system (non-SVG) font. - function PFont(name, size) { - // according to the P5 API, new PFont() is legal (albeit completely useless) - if (name === undef) { - name = ""; - } - this.name = name; - if (size === undef) { - size = 0; - } - this.size = size; - this.glyph = false; - this.ascent = 0; - this.descent = 0; - // For leading, the "safe" value uses the standard TEX ratio - this.leading = 1.2 * size; - - // Note that an italic, bold font must used "... Bold Italic" - // in P5. "... Italic Bold" is treated as normal/normal. - var illegalIndicator = name.indexOf(" Italic Bold"); - if (illegalIndicator !== -1) { - name = name.substring(0, illegalIndicator); - } - - // determine font style - this.style = "normal"; - var italicsIndicator = name.indexOf(" Italic"); - if (italicsIndicator !== -1) { - name = name.substring(0, italicsIndicator); - this.style = "italic"; - } - - // determine font weight - this.weight = "normal"; - var boldIndicator = name.indexOf(" Bold"); - if (boldIndicator !== -1) { - name = name.substring(0, boldIndicator); - this.weight = "bold"; - } - - // determine font-family name - this.family = "sans-serif"; - if (name !== undef) { - switch(name) { - case "sans-serif": - case "serif": - case "monospace": - case "fantasy": - case "cursive": - this.family = name; - break; - default: - this.family = '"' + name + '", sans-serif'; - break; - } - } - // Calculate the ascent/descent/leading value based on - // how the browser renders this font. - this.context2d = null; - computeFontMetrics(this); - this.css = this.getCSSDefinition(); - this.context2d.font = this.css; - } - - /** - * This function generates the CSS "font" string for this PFont - */ - PFont.prototype.getCSSDefinition = function(fontSize, lineHeight) { - if(fontSize===undef) { - fontSize = this.size + "px"; - } - if(lineHeight===undef) { - lineHeight = this.leading + "px"; - } - // CSS "font" definition: font-style font-variant font-weight font-size/line-height font-family - var components = [this.style, "normal", this.weight, fontSize + "/" + lineHeight, this.family]; - return components.join(" "); - }; - - /** - * We cannot rely on there being a 2d context available, - * because we support OPENGL sketches, and canvas3d has - * no "measureText" function in the API. - */ - PFont.prototype.measureTextWidth = function(string) { - return this.context2d.measureText(string).width; - }; - - /** - * Global "loaded fonts" list, internal to PFont - */ - PFont.PFontCache = {}; - - /** - * This function acts as single access point for getting and caching - * fonts across all sketches handled by an instance of Processing.js - */ - PFont.get = function(fontName, fontSize) { - var cache = PFont.PFontCache; - var idx = fontName+"/"+fontSize; - if (!cache[idx]) { - cache[idx] = new PFont(fontName, fontSize); - } - return cache[idx]; - }; - - /** - * Lists all standard fonts. Due to browser limitations, this list is - * not the system font list, like in P5, but the CSS "genre" list. - */ - PFont.list = function() { - return ["sans-serif", "serif", "monospace", "fantasy", "cursive"]; - }; - - /** - * Loading external fonts through @font-face rules is handled by PFont, - * to ensure fonts loaded in this way are globally available. - */ - PFont.preloading = { - // template element used to compare font sizes - template: {}, - // indicates whether or not the reference tiny font has been loaded - initialized: false, - // load the reference tiny font via a css @font-face rule - initialize: function() { - var generateTinyFont = function() { - var encoded = "#E3KAI2wAgT1MvMg7Eo3VmNtYX7ABi3CxnbHlm" + - "7Abw3kaGVhZ7ACs3OGhoZWE7A53CRobXR47AY3" + - "AGbG9jYQ7G03Bm1heH7ABC3CBuYW1l7Ae3AgcG" + - "9zd7AI3AE#B3AQ2kgTY18PPPUACwAg3ALSRoo3" + - "#yld0xg32QAB77#E777773B#E3C#I#Q77773E#" + - "Q7777777772CMAIw7AB77732B#M#Q3wAB#g3B#" + - "E#E2BB//82BB////w#B7#gAEg3E77x2B32B#E#" + - "Q#MTcBAQ32gAe#M#QQJ#E32M#QQJ#I#g32Q77#"; - var expand = function(input) { - return "AAAAAAAA".substr(~~input ? 7-input : 6); - }; - return encoded.replace(/[#237]/g, expand); - }; - var fontface = document.createElement("style"); - fontface.setAttribute("type","text/css"); - fontface.innerHTML = "@font-face {\n" + - ' font-family: "PjsEmptyFont";' + "\n" + - " src: url('data:application/x-font-ttf;base64,"+generateTinyFont()+"')\n" + - " format('truetype');\n" + - "}"; - document.head.appendChild(fontface); - - // set up the template element - var element = document.createElement("span"); - element.style.cssText = 'position: absolute; top: 0; left: 0; opacity: 0; font-family: "PjsEmptyFont", fantasy;'; - element.innerHTML = "AAAAAAAA"; - document.body.appendChild(element); - this.template = element; - - this.initialized = true; - }, - // Shorthand function to get the computed width for an element. - getElementWidth: function(element) { - return document.defaultView.getComputedStyle(element,"").getPropertyValue("width"); - }, - // time taken so far in attempting to load a font - timeAttempted: 0, - // returns false if no fonts are pending load, or true otherwise. - pending: function(intervallength) { - if (!this.initialized) { - this.initialize(); - } - var element, - computedWidthFont, - computedWidthRef = this.getElementWidth(this.template); - for (var i = 0; i < this.fontList.length; i++) { - // compares size of text in pixels. if equal, custom font is not yet loaded - element = this.fontList[i]; - computedWidthFont = this.getElementWidth(element); - if (this.timeAttempted < 4000 && computedWidthFont === computedWidthRef) { - this.timeAttempted += intervallength; - return true; - } else { - document.body.removeChild(element); - this.fontList.splice(i--, 1); - this.timeAttempted = 0; - } - } - // if there are no more fonts to load, pending is false - if (this.fontList.length === 0) { - return false; - } - // We should have already returned before getting here. - // But, if we do get here, length!=0 so fonts are pending. - return true; - }, - // fontList contains elements to compare font sizes against a template - fontList: [], - // addedList contains the fontnames of all the fonts loaded via @font-face - addedList: {}, - // adds a font to the font cache - // creates an element using the font, to start loading the font, - // and compare against a default font to see if the custom font is loaded - add: function(fontSrc) { - if (!this.initialized) { - this.initialize(); - } - // fontSrc can be a string or a javascript object - // acceptable fonts are .ttf, .otf, and data uri - var fontName = (typeof fontSrc === 'object' ? fontSrc.fontFace : fontSrc), - fontUrl = (typeof fontSrc === 'object' ? fontSrc.url : fontSrc); - - // check whether we already created the @font-face rule for this font - if (this.addedList[fontName]) { - return; - } - - // if we didn't, create the @font-face rule - var style = document.createElement("style"); - style.setAttribute("type","text/css"); - style.innerHTML = "@font-face{\n font-family: '" + fontName + "';\n src: url('" + fontUrl + "');\n}\n"; - document.head.appendChild(style); - this.addedList[fontName] = true; - - // also create the element to load and compare the new font - var element = document.createElement("span"); - element.style.cssText = "position: absolute; top: 0; left: 0; opacity: 0;"; - element.style.fontFamily = '"' + fontName + '", "PjsEmptyFont", fantasy'; - element.innerHTML = "AAAAAAAA"; - document.body.appendChild(element); - this.fontList.push(element); - } - }; - - - // add to the default scope - defaultScope.PFont = PFont; - - - //////////////////////////////////////////////////////////////////////////// - // PFONT.JS END - //////////////////////////////////////////////////////////////////////////// - - - var Processing = this.Processing = function(aCanvas, aCode) { - // Previously we allowed calling Processing as a func instead of ctor, but no longer. - if (!(this instanceof Processing)) { - throw("called Processing constructor as if it were a function: missing 'new'."); - } - - var curElement, - pgraphicsMode = (aCanvas === undef && aCode === undef); - - if (pgraphicsMode) { - curElement = document.createElement("canvas"); - } else { - // We'll take a canvas element or a string for a canvas element's id - curElement = typeof aCanvas === "string" ? document.getElementById(aCanvas) : aCanvas; - } - - if (!(curElement instanceof HTMLCanvasElement)) { - throw("called Processing constructor without passing canvas element reference or id."); - } - - function unimplemented(s) { - Processing.debug('Unimplemented - ' + s); - } - - // When something new is added to "p." it must also be added to the "names" array. - // The names array contains the names of everything that is inside "p." - var p = this; - - // PJS specific (non-p5) methods and properties to externalize - p.externals = { - canvas: curElement, - context: undef, - sketch: undef - }; - - p.name = 'Processing.js Instance'; // Set Processing defaults / environment variables - p.use3DContext = false; // default '2d' canvas context - - /** - * Confirms if a Processing program is "focused", meaning that it is - * active and will accept input from mouse or keyboard. This variable - * is "true" if it is focused and "false" if not. This variable is - * often used when you want to warn people they need to click on the - * browser before it will work. - */ - p.focused = false; - p.breakShape = false; - - // Glyph path storage for textFonts - p.glyphTable = {}; - - // Global vars for tracking mouse position - p.pmouseX = 0; - p.pmouseY = 0; - p.mouseX = 0; - p.mouseY = 0; - p.mouseButton = 0; - p.mouseScroll = 0; - - // Undefined event handlers to be replaced by user when needed - p.mouseClicked = undef; - p.mouseDragged = undef; - p.mouseMoved = undef; - p.mousePressed = undef; - p.mouseReleased = undef; - p.mouseScrolled = undef; - p.mouseOver = undef; - p.mouseOut = undef; - p.touchStart = undef; - p.touchEnd = undef; - p.touchMove = undef; - p.touchCancel = undef; - p.key = undef; - p.keyCode = undef; - p.keyPressed = nop; // needed to remove function checks - p.keyReleased = nop; - p.keyTyped = nop; - p.draw = undef; - p.setup = undef; - - // Remapped vars - p.__mousePressed = false; - p.__keyPressed = false; - p.__frameRate = 60; - - // The current animation frame - p.frameCount = 0; - - // The height/width of the canvas - p.width = 100; - p.height = 100; - - // "Private" variables used to maintain state - var curContext, - curSketch, - drawing, // hold a Drawing2D or Drawing3D object - online = true, - doFill = true, - fillStyle = [1.0, 1.0, 1.0, 1.0], - currentFillColor = 0xFFFFFFFF, - isFillDirty = true, - doStroke = true, - strokeStyle = [0.0, 0.0, 0.0, 1.0], - currentStrokeColor = 0xFF000000, - isStrokeDirty = true, - lineWidth = 1, - loopStarted = false, - renderSmooth = false, - doLoop = true, - looping = 0, - curRectMode = PConstants.CORNER, - curEllipseMode = PConstants.CENTER, - normalX = 0, - normalY = 0, - normalZ = 0, - normalMode = PConstants.NORMAL_MODE_AUTO, - curFrameRate = 60, - curMsPerFrame = 1000/curFrameRate, - curCursor = PConstants.ARROW, - oldCursor = curElement.style.cursor, - curShape = PConstants.POLYGON, - curShapeCount = 0, - curvePoints = [], - curTightness = 0, - curveDet = 20, - curveInited = false, - backgroundObj = -3355444, // rgb(204, 204, 204) is the default gray background colour - bezDetail = 20, - colorModeA = 255, - colorModeX = 255, - colorModeY = 255, - colorModeZ = 255, - pathOpen = false, - mouseDragging = false, - pmouseXLastFrame = 0, - pmouseYLastFrame = 0, - curColorMode = PConstants.RGB, - curTint = null, - curTint3d = null, - getLoaded = false, - start = Date.now(), - timeSinceLastFPS = start, - framesSinceLastFPS = 0, - textcanvas, - curveBasisMatrix, - curveToBezierMatrix, - curveDrawMatrix, - bezierDrawMatrix, - bezierBasisInverse, - bezierBasisMatrix, - curContextCache = { attributes: {}, locations: {} }, - // Shaders - programObject3D, - programObject2D, - programObjectUnlitShape, - boxBuffer, - boxNormBuffer, - boxOutlineBuffer, - rectBuffer, - rectNormBuffer, - sphereBuffer, - lineBuffer, - fillBuffer, - fillColorBuffer, - strokeColorBuffer, - pointBuffer, - shapeTexVBO, - canTex, // texture for createGraphics - textTex, // texture for 3d tex - curTexture = {width:0,height:0}, - curTextureMode = PConstants.IMAGE, - usingTexture = false, - textBuffer, - textureBuffer, - indexBuffer, - // Text alignment - horizontalTextAlignment = PConstants.LEFT, - verticalTextAlignment = PConstants.BASELINE, - textMode = PConstants.MODEL, - // Font state - curFontName = "Arial", - curTextSize = 12, - curTextAscent = 9, - curTextDescent = 2, - curTextLeading = 14, - curTextFont = PFont.get(curFontName, curTextSize), - // Pixels cache - originalContext, - proxyContext = null, - isContextReplaced = false, - setPixelsCached, - maxPixelsCached = 1000, - pressedKeysMap = [], - lastPressedKeyCode = null, - codedKeys = [ PConstants.SHIFT, PConstants.CONTROL, PConstants.ALT, PConstants.CAPSLK, PConstants.PGUP, PConstants.PGDN, - PConstants.END, PConstants.HOME, PConstants.LEFT, PConstants.UP, PConstants.RIGHT, PConstants.DOWN, PConstants.NUMLK, - PConstants.INSERT, PConstants.F1, PConstants.F2, PConstants.F3, PConstants.F4, PConstants.F5, PConstants.F6, PConstants.F7, - PConstants.F8, PConstants.F9, PConstants.F10, PConstants.F11, PConstants.F12, PConstants.META ]; - - // Get padding and border style widths for mouse offsets - var stylePaddingLeft, stylePaddingTop, styleBorderLeft, styleBorderTop; - - if (document.defaultView && document.defaultView.getComputedStyle) { - stylePaddingLeft = parseInt(document.defaultView.getComputedStyle(curElement, null)['paddingLeft'], 10) || 0; - stylePaddingTop = parseInt(document.defaultView.getComputedStyle(curElement, null)['paddingTop'], 10) || 0; - styleBorderLeft = parseInt(document.defaultView.getComputedStyle(curElement, null)['borderLeftWidth'], 10) || 0; - styleBorderTop = parseInt(document.defaultView.getComputedStyle(curElement, null)['borderTopWidth'], 10) || 0; - } - - // User can only have MAX_LIGHTS lights - var lightCount = 0; - - //sphere stuff - var sphereDetailV = 0, - sphereDetailU = 0, - sphereX = [], - sphereY = [], - sphereZ = [], - sinLUT = new Float32Array(PConstants.SINCOS_LENGTH), - cosLUT = new Float32Array(PConstants.SINCOS_LENGTH), - sphereVerts, - sphereNorms; - - // Camera defaults and settings - var cam, - cameraInv, - modelView, - modelViewInv, - userMatrixStack, - userReverseMatrixStack, - inverseCopy, - projection, - manipulatingCamera = false, - frustumMode = false, - cameraFOV = 60 * (Math.PI / 180), - cameraX = p.width / 2, - cameraY = p.height / 2, - cameraZ = cameraY / Math.tan(cameraFOV / 2), - cameraNear = cameraZ / 10, - cameraFar = cameraZ * 10, - cameraAspect = p.width / p.height; - - var vertArray = [], - curveVertArray = [], - curveVertCount = 0, - isCurve = false, - isBezier = false, - firstVert = true; - - //PShape stuff - var curShapeMode = PConstants.CORNER; - - // Stores states for pushStyle() and popStyle(). - var styleArray = []; - - // Vertices are specified in a counter-clockwise order - // triangles are in this order: back, front, right, bottom, left, top - var boxVerts = new Float32Array([ - 0.5, 0.5, -0.5, 0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5, 0.5, -0.5, 0.5, 0.5, -0.5, - 0.5, 0.5, 0.5, -0.5, 0.5, 0.5, -0.5, -0.5, 0.5, -0.5, -0.5, 0.5, 0.5, -0.5, 0.5, 0.5, 0.5, 0.5, - 0.5, 0.5, -0.5, 0.5, 0.5, 0.5, 0.5, -0.5, 0.5, 0.5, -0.5, 0.5, 0.5, -0.5, -0.5, 0.5, 0.5, -0.5, - 0.5, -0.5, -0.5, 0.5, -0.5, 0.5, -0.5, -0.5, 0.5, -0.5, -0.5, 0.5, -0.5, -0.5, -0.5, 0.5, -0.5, -0.5, - -0.5, -0.5, -0.5, -0.5, -0.5, 0.5, -0.5, 0.5, 0.5, -0.5, 0.5, 0.5, -0.5, 0.5, -0.5, -0.5, -0.5, -0.5, - 0.5, 0.5, 0.5, 0.5, 0.5, -0.5, -0.5, 0.5, -0.5, -0.5, 0.5, -0.5, -0.5, 0.5, 0.5, 0.5, 0.5, 0.5]); - - var boxOutlineVerts = new Float32Array([ - 0.5, 0.5, 0.5, 0.5, -0.5, 0.5, 0.5, 0.5, -0.5, 0.5, -0.5, -0.5, - -0.5, 0.5, -0.5, -0.5, -0.5, -0.5, -0.5, 0.5, 0.5, -0.5, -0.5, 0.5, - 0.5, 0.5, 0.5, 0.5, 0.5, -0.5, 0.5, 0.5, -0.5, -0.5, 0.5, -0.5, - -0.5, 0.5, -0.5, -0.5, 0.5, 0.5, -0.5, 0.5, 0.5, 0.5, 0.5, 0.5, - 0.5, -0.5, 0.5, 0.5, -0.5, -0.5, 0.5, -0.5, -0.5, -0.5, -0.5, -0.5, - -0.5, -0.5, -0.5, -0.5, -0.5, 0.5, -0.5, -0.5, 0.5, 0.5, -0.5, 0.5]); - - var boxNorms = new Float32Array([ - 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, - 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, - 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, - 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, - -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, - 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0]); - - // These verts are used for the fill and stroke using TRIANGLE_FAN and LINE_LOOP - var rectVerts = new Float32Array([0,0,0, 0,1,0, 1,1,0, 1,0,0]); - - var rectNorms = new Float32Array([0,0,1, 0,0,1, 0,0,1, 0,0,1]); - - - // Shader for points and lines in begin/endShape - var vShaderSrcUnlitShape = - "varying vec4 frontColor;" + - - "attribute vec3 aVertex;" + - "attribute vec4 aColor;" + - - "uniform mat4 uView;" + - "uniform mat4 uProjection;" + - "uniform float pointSize;" + - - "void main(void) {" + - " frontColor = aColor;" + - " gl_PointSize = pointSize;" + - " gl_Position = uProjection * uView * vec4(aVertex, 1.0);" + - "}"; - - var fShaderSrcUnlitShape = - "#ifdef GL_ES\n" + - "precision highp float;\n" + - "#endif\n" + - - "varying vec4 frontColor;" + - - "void main(void){" + - " gl_FragColor = frontColor;" + - "}"; - - // Shader for rect, text, box outlines, sphere outlines, point() and line() - var vertexShaderSource2D = - "varying vec4 frontColor;" + - - "attribute vec3 Vertex;" + - "attribute vec2 aTextureCoord;" + - "uniform vec4 color;" + - - "uniform mat4 model;" + - "uniform mat4 view;" + - "uniform mat4 projection;" + - "uniform float pointSize;" + - "varying vec2 vTextureCoord;"+ - - "void main(void) {" + - " gl_PointSize = pointSize;" + - " frontColor = color;" + - " gl_Position = projection * view * model * vec4(Vertex, 1.0);" + - " vTextureCoord = aTextureCoord;" + - "}"; - - var fragmentShaderSource2D = - "#ifdef GL_ES\n" + - "precision highp float;\n" + - "#endif\n" + - - "varying vec4 frontColor;" + - "varying vec2 vTextureCoord;"+ - - "uniform sampler2D uSampler;"+ - "uniform int picktype;"+ - - "void main(void){" + - " if(picktype == 0){"+ - " gl_FragColor = frontColor;" + - " }" + - " else if(picktype == 1){"+ - " float alpha = texture2D(uSampler, vTextureCoord).a;"+ - " gl_FragColor = vec4(frontColor.rgb*alpha, alpha);\n"+ - " }"+ - "}"; - - var webglMaxTempsWorkaround = /Windows/.test(navigator.userAgent); - - // Vertex shader for boxes and spheres - var vertexShaderSource3D = - "varying vec4 frontColor;" + - - "attribute vec3 Vertex;" + - "attribute vec3 Normal;" + - "attribute vec4 aColor;" + - "attribute vec2 aTexture;" + - "varying vec2 vTexture;" + - - "uniform vec4 color;" + - - "uniform bool usingMat;" + - "uniform vec3 specular;" + - "uniform vec3 mat_emissive;" + - "uniform vec3 mat_ambient;" + - "uniform vec3 mat_specular;" + - "uniform float shininess;" + - - "uniform mat4 model;" + - "uniform mat4 view;" + - "uniform mat4 projection;" + - "uniform mat4 normalTransform;" + - - "uniform int lightCount;" + - "uniform vec3 falloff;" + - - // careful changing the order of these fields. Some cards - // have issues with memory alignment - "struct Light {" + - " int type;" + - " vec3 color;" + - " vec3 position;" + - " vec3 direction;" + - " float angle;" + - " vec3 halfVector;" + - " float concentration;" + - "};" + - - // nVidia cards have issues with arrays of structures - // so instead we create 8 instances of Light - "uniform Light lights0;" + - "uniform Light lights1;" + - "uniform Light lights2;" + - "uniform Light lights3;" + - "uniform Light lights4;" + - "uniform Light lights5;" + - "uniform Light lights6;" + - "uniform Light lights7;" + - - // GLSL does not support switch - "Light getLight(int index){" + - " if(index == 0) return lights0;" + - " if(index == 1) return lights1;" + - " if(index == 2) return lights2;" + - " if(index == 3) return lights3;" + - " if(index == 4) return lights4;" + - " if(index == 5) return lights5;" + - " if(index == 6) return lights6;" + - // Do not use a conditional for the last return statement - // because some video cards will fail and complain that - // "not all paths return" - " return lights7;" + - "}" + - - "void AmbientLight( inout vec3 totalAmbient, in vec3 ecPos, in Light light ) {" + - // Get the vector from the light to the vertex - // Get the distance from the current vector to the light position - " float d = length( light.position - ecPos );" + - " float attenuation = 1.0 / ( falloff[0] + ( falloff[1] * d ) + ( falloff[2] * d * d ));" + - " totalAmbient += light.color * attenuation;" + - "}" + - - "void DirectionalLight( inout vec3 col, inout vec3 spec, in vec3 vertNormal, in vec3 ecPos, in Light light ) {" + - " float powerfactor = 0.0;" + - " float nDotVP = max(0.0, dot( vertNormal, normalize(-light.position) ));" + - " float nDotVH = max(0.0, dot( vertNormal, normalize(-light.position-normalize(ecPos) )));" + - - " if( nDotVP != 0.0 ){" + - " powerfactor = pow( nDotVH, shininess );" + - " }" + - - " col += light.color * nDotVP;" + - " spec += specular * powerfactor;" + - "}" + - - "void PointLight( inout vec3 col, inout vec3 spec, in vec3 vertNormal, in vec3 ecPos, in Light light ) {" + - " float powerfactor;" + - - // Get the vector from the light to the vertex - " vec3 VP = light.position - ecPos;" + - - // Get the distance from the current vector to the light position - " float d = length( VP ); " + - - // Normalize the light ray so it can be used in the dot product operation. - " VP = normalize( VP );" + - - " float attenuation = 1.0 / ( falloff[0] + ( falloff[1] * d ) + ( falloff[2] * d * d ));" + - - " float nDotVP = max( 0.0, dot( vertNormal, VP ));" + - " vec3 halfVector = normalize( VP - normalize(ecPos) );" + - " float nDotHV = max( 0.0, dot( vertNormal, halfVector ));" + - - " if( nDotVP == 0.0) {" + - " powerfactor = 0.0;" + - " }" + - " else{" + - " powerfactor = pow( nDotHV, shininess );" + - " }" + - - " spec += specular * powerfactor * attenuation;" + - " col += light.color * nDotVP * attenuation;" + - "}" + - - /* - */ - "void SpotLight( inout vec3 col, inout vec3 spec, in vec3 vertNormal, in vec3 ecPos, in Light light ) {" + - " float spotAttenuation;" + - " float powerfactor;" + - - // calculate the vector from the current vertex to the light. - " vec3 VP = light.position - ecPos; " + - " vec3 ldir = normalize( -light.direction );" + - - // get the distance from the spotlight and the vertex - " float d = length( VP );" + - " VP = normalize( VP );" + - - " float attenuation = 1.0 / ( falloff[0] + ( falloff[1] * d ) + ( falloff[2] * d * d ) );" + - - // dot product of the vector from vertex to light and light direction. - " float spotDot = dot( VP, ldir );" + - - // if the vertex falls inside the cone - (webglMaxTempsWorkaround ? // Windows reports max temps error if light.angle is used - " spotAttenuation = 1.0; " : - " if( spotDot > cos( light.angle ) ) {" + - " spotAttenuation = pow( spotDot, light.concentration );" + - " }" + - " else{" + - " spotAttenuation = 0.0;" + - " }" + - " attenuation *= spotAttenuation;" + - "") + - - " float nDotVP = max( 0.0, dot( vertNormal, VP ));" + - " vec3 halfVector = normalize( VP - normalize(ecPos) );" + - " float nDotHV = max( 0.0, dot( vertNormal, halfVector ));" + - - " if( nDotVP == 0.0 ) {" + - " powerfactor = 0.0;" + - " }" + - " else {" + - " powerfactor = pow( nDotHV, shininess );" + - " }" + - - " spec += specular * powerfactor * attenuation;" + - " col += light.color * nDotVP * attenuation;" + - "}" + - - "void main(void) {" + - " vec3 finalAmbient = vec3( 0.0, 0.0, 0.0 );" + - " vec3 finalDiffuse = vec3( 0.0, 0.0, 0.0 );" + - " vec3 finalSpecular = vec3( 0.0, 0.0, 0.0 );" + - - " vec4 col = color;" + - - " if(color[0] == -1.0){" + - " col = aColor;" + - " }" + - - // We use the sphere vertices as the normals when we create the sphere buffer. - // But this only works if the sphere vertices are unit length, so we - // have to normalize the normals here. Since this is only required for spheres - // we could consider placing this in a conditional later on. - " vec3 norm = normalize(vec3( normalTransform * vec4( Normal, 0.0 ) ));" + - - " vec4 ecPos4 = view * model * vec4(Vertex,1.0);" + - " vec3 ecPos = (vec3(ecPos4))/ecPos4.w;" + - - // If there were no lights this draw call, just use the - // assigned fill color of the shape and the specular value - " if( lightCount == 0 ) {" + - " frontColor = col + vec4(mat_specular,1.0);" + - " }" + - " else {" + - // WebGL forces us to iterate over a constant value - // so we can't iterate using lightCount - " for( int i = 0; i < 8; i++ ) {" + - " Light l = getLight(i);" + - - // We can stop iterating if we know we have gone past - // the number of lights which are on - " if( i >= lightCount ){" + - " break;" + - " }" + - - " if( l.type == 0 ) {" + - " AmbientLight( finalAmbient, ecPos, l );" + - " }" + - " else if( l.type == 1 ) {" + - " DirectionalLight( finalDiffuse, finalSpecular, norm, ecPos, l );" + - " }" + - " else if( l.type == 2 ) {" + - " PointLight( finalDiffuse, finalSpecular, norm, ecPos, l );" + - " }" + - " else {" + - " SpotLight( finalDiffuse, finalSpecular, norm, ecPos, l );" + - " }" + - " }" + - - " if( usingMat == false ) {" + - " frontColor = vec4(" + - " vec3(col) * finalAmbient +" + - " vec3(col) * finalDiffuse +" + - " vec3(col) * finalSpecular," + - " col[3] );" + - " }" + - " else{" + - " frontColor = vec4( " + - " mat_emissive + " + - " (vec3(col) * mat_ambient * finalAmbient) + " + - " (vec3(col) * finalDiffuse) + " + - " (mat_specular * finalSpecular), " + - " col[3] );" + - " }" + - " }" + - - " vTexture.xy = aTexture.xy;" + - " gl_Position = projection * view * model * vec4( Vertex, 1.0 );" + - "}"; - - var fragmentShaderSource3D = - "#ifdef GL_ES\n" + - "precision highp float;\n" + - "#endif\n" + - - "varying vec4 frontColor;" + - - "uniform sampler2D sampler;" + - "uniform bool usingTexture;" + - "varying vec2 vTexture;" + - - // In Processing, when a texture is used, the fill color is ignored - // vec4(1.0,1.0,1.0,0.5) - "void main(void){" + - " if(usingTexture){" + - " gl_FragColor = vec4(texture2D(sampler, vTexture.xy)) * frontColor;" + - " }"+ - " else{" + - " gl_FragColor = frontColor;" + - " }" + - "}"; - - //////////////////////////////////////////////////////////////////////////// - // 3D Functions - //////////////////////////////////////////////////////////////////////////// - - /* - * Sets a uniform variable in a program object to a particular - * value. Before calling this function, ensure the correct - * program object has been installed as part of the current - * rendering state by calling useProgram. - * - * On some systems, if the variable exists in the shader but isn't used, - * the compiler will optimize it out and this function will fail. - * - * @param {WebGLProgram} programObj program object returned from - * createProgramObject - * @param {String} varName the name of the variable in the shader - * @param {float | Array} varValue either a scalar value or an Array - * - * @returns none - * - * @see uniformi - * @see uniformMatrix - */ - function uniformf(cacheId, programObj, varName, varValue) { - var varLocation = curContextCache.locations[cacheId]; - if(varLocation === undef) { - varLocation = curContext.getUniformLocation(programObj, varName); - curContextCache.locations[cacheId] = varLocation; - } - // the variable won't be found if it was optimized out. - if (varLocation !== null) { - if (varValue.length === 4) { - curContext.uniform4fv(varLocation, varValue); - } else if (varValue.length === 3) { - curContext.uniform3fv(varLocation, varValue); - } else if (varValue.length === 2) { - curContext.uniform2fv(varLocation, varValue); - } else { - curContext.uniform1f(varLocation, varValue); - } - } - } - - /** - * Sets a uniform int or int array in a program object to a particular - * value. Before calling this function, ensure the correct - * program object has been installed as part of the current - * rendering state. - * - * On some systems, if the variable exists in the shader but isn't used, - * the compiler will optimize it out and this function will fail. - * - * @param {WebGLProgram} programObj program object returned from - * createProgramObject - * @param {String} varName the name of the variable in the shader - * @param {int | Array} varValue either a scalar value or an Array - * - * @returns none - * - * @see uniformf - * @see uniformMatrix - */ - function uniformi(cacheId, programObj, varName, varValue) { - var varLocation = curContextCache.locations[cacheId]; - if(varLocation === undef) { - varLocation = curContext.getUniformLocation(programObj, varName); - curContextCache.locations[cacheId] = varLocation; - } - // the variable won't be found if it was optimized out. - if (varLocation !== null) { - if (varValue.length === 4) { - curContext.uniform4iv(varLocation, varValue); - } else if (varValue.length === 3) { - curContext.uniform3iv(varLocation, varValue); - } else if (varValue.length === 2) { - curContext.uniform2iv(varLocation, varValue); - } else { - curContext.uniform1i(varLocation, varValue); - } - } - } - - /** - * Sets the value of a uniform matrix variable in a program - * object. Before calling this function, ensure the correct - * program object has been installed as part of the current - * rendering state. - * - * On some systems, if the variable exists in the shader but - * isn't used, the compiler will optimize it out and this - * function will fail. - * - * @param {WebGLProgram} programObj program object returned from - * createProgramObject - * @param {String} varName the name of the variable in the shader - * @param {boolean} transpose must be false - * @param {Array} matrix an array of 4, 9 or 16 values - * - * @returns none - * - * @see uniformi - * @see uniformf - */ - function uniformMatrix(cacheId, programObj, varName, transpose, matrix) { - var varLocation = curContextCache.locations[cacheId]; - if(varLocation === undef) { - varLocation = curContext.getUniformLocation(programObj, varName); - curContextCache.locations[cacheId] = varLocation; - } - // the variable won't be found if it was optimized out. - if (varLocation !== -1) { - if (matrix.length === 16) { - curContext.uniformMatrix4fv(varLocation, transpose, matrix); - } else if (matrix.length === 9) { - curContext.uniformMatrix3fv(varLocation, transpose, matrix); - } else { - curContext.uniformMatrix2fv(varLocation, transpose, matrix); - } - } - } - - /** - * Binds the VBO, sets the vertex attribute data for the program - * object and enables the attribute. - * - * On some systems, if the attribute exists in the shader but - * isn't used, the compiler will optimize it out and this - * function will fail. - * - * @param {WebGLProgram} programObj program object returned from - * createProgramObject - * @param {String} varName the name of the variable in the shader - * @param {int} size the number of components per vertex attribute - * @param {WebGLBuffer} VBO Vertex Buffer Object - * - * @returns none - * - * @see disableVertexAttribPointer - */ - function vertexAttribPointer(cacheId, programObj, varName, size, VBO) { - var varLocation = curContextCache.attributes[cacheId]; - if(varLocation === undef) { - varLocation = curContext.getAttribLocation(programObj, varName); - curContextCache.attributes[cacheId] = varLocation; - } - if (varLocation !== -1) { - curContext.bindBuffer(curContext.ARRAY_BUFFER, VBO); - curContext.vertexAttribPointer(varLocation, size, curContext.FLOAT, false, 0, 0); - curContext.enableVertexAttribArray(varLocation); - } - } - - /** - * Disables a program object attribute from being sent to WebGL. - * - * @param {WebGLProgram} programObj program object returned from - * createProgramObject - * @param {String} varName name of the attribute - * - * @returns none - * - * @see vertexAttribPointer - */ - function disableVertexAttribPointer(cacheId, programObj, varName){ - var varLocation = curContextCache.attributes[cacheId]; - if(varLocation === undef) { - varLocation = curContext.getAttribLocation(programObj, varName); - curContextCache.attributes[cacheId] = varLocation; - } - if (varLocation !== -1) { - curContext.disableVertexAttribArray(varLocation); - } - } - - /** - * Creates a WebGL program object. - * - * @param {String} vetexShaderSource - * @param {String} fragmentShaderSource - * - * @returns {WebGLProgram} A program object - */ - var createProgramObject = function(curContext, vetexShaderSource, fragmentShaderSource) { - var vertexShaderObject = curContext.createShader(curContext.VERTEX_SHADER); - curContext.shaderSource(vertexShaderObject, vetexShaderSource); - curContext.compileShader(vertexShaderObject); - if (!curContext.getShaderParameter(vertexShaderObject, curContext.COMPILE_STATUS)) { - throw curContext.getShaderInfoLog(vertexShaderObject); - } - - var fragmentShaderObject = curContext.createShader(curContext.FRAGMENT_SHADER); - curContext.shaderSource(fragmentShaderObject, fragmentShaderSource); - curContext.compileShader(fragmentShaderObject); - if (!curContext.getShaderParameter(fragmentShaderObject, curContext.COMPILE_STATUS)) { - throw curContext.getShaderInfoLog(fragmentShaderObject); - } - - var programObject = curContext.createProgram(); - curContext.attachShader(programObject, vertexShaderObject); - curContext.attachShader(programObject, fragmentShaderObject); - curContext.linkProgram(programObject); - if (!curContext.getProgramParameter(programObject, curContext.LINK_STATUS)) { - throw "Error linking shaders."; - } - - return programObject; - }; - - //////////////////////////////////////////////////////////////////////////// - // 2D/3D drawing handling - //////////////////////////////////////////////////////////////////////////// - var imageModeCorner = function(x, y, w, h, whAreSizes) { - return { - x: x, - y: y, - w: w, - h: h - }; - }; - var imageModeConvert = imageModeCorner; - - var imageModeCorners = function(x, y, w, h, whAreSizes) { - return { - x: x, - y: y, - w: whAreSizes ? w : w - x, - h: whAreSizes ? h : h - y - }; - }; - - var imageModeCenter = function(x, y, w, h, whAreSizes) { - return { - x: x - w / 2, - y: y - h / 2, - w: w, - h: h - }; - }; - - // Objects for shared, 2D and 3D contexts - var DrawingShared = function(){}; - var Drawing2D = function(){}; - var Drawing3D = function(){}; - var DrawingPre = function(){}; - - // Setup the prototype chain - Drawing2D.prototype = new DrawingShared(); - Drawing2D.prototype.constructor = Drawing2D; - Drawing3D.prototype = new DrawingShared(); - Drawing3D.prototype.constructor = Drawing3D; - DrawingPre.prototype = new DrawingShared(); - DrawingPre.prototype.constructor = DrawingPre; - - // A no-op function for when the user calls 3D functions from a 2D sketch - // We can change this to a throw or console.error() later if we want - DrawingShared.prototype.a3DOnlyFunction = nop; - - //////////////////////////////////////////////////////////////////////////// - // Char handling - //////////////////////////////////////////////////////////////////////////// - var charMap = {}; - - var Char = p.Character = function(chr) { - if (typeof chr === 'string' && chr.length === 1) { - this.code = chr.charCodeAt(0); - } else if (typeof chr === 'number') { - this.code = chr; - } else if (chr instanceof Char) { - this.code = chr; - } else { - this.code = NaN; - } - - return (charMap[this.code] === undef) ? charMap[this.code] = this : charMap[this.code]; - }; - - Char.prototype.toString = function() { - return String.fromCharCode(this.code); - }; - - Char.prototype.valueOf = function() { - return this.code; - }; - - /** - * Datatype for storing shapes. Processing can currently load and display SVG (Scalable Vector Graphics) shapes. - * Before a shape is used, it must be loaded with the loadShape() function. The shape() function is used to draw the shape to the display window. - * The PShape object contain a group of methods, linked below, that can operate on the shape data. - *

The loadShape() method supports SVG files created with Inkscape and Adobe Illustrator. - * It is not a full SVG implementation, but offers some straightforward support for handling vector data. - * - * @param {int} family the shape type, one of GROUP, PRIMITIVE, PATH, or GEOMETRY - * - * @see #shape() - * @see #loadShape() - * @see #shapeMode() - */ - var PShape = p.PShape = function(family) { - this.family = family || PConstants.GROUP; - this.visible = true; - this.style = true; - this.children = []; - this.nameTable = []; - this.params = []; - this.name = ""; - this.image = null; //type PImage - this.matrix = null; - this.kind = null; - this.close = null; - this.width = null; - this.height = null; - this.parent = null; - }; - /** - * PShape methods - * missing: findChild(), apply(), contains(), findChild(), getPrimitive(), getParams(), getVertex() , getVertexCount(), - * getVertexCode() , getVertexCodes() , getVertexCodeCount(), getVertexX(), getVertexY(), getVertexZ() - */ - PShape.prototype = { - /** - * @member PShape - * The isVisible() function returns a boolean value "true" if the image is set to be visible, "false" if not. This is modified with the setVisible() parameter. - *

The visibility of a shape is usually controlled by whatever program created the SVG file. - * For instance, this parameter is controlled by showing or hiding the shape in the layers palette in Adobe Illustrator. - * - * @return {boolean} returns "true" if the image is set to be visible, "false" if not - */ - isVisible: function(){ - return this.visible; - }, - /** - * @member PShape - * The setVisible() function sets the shape to be visible or invisible. This is determined by the value of the visible parameter. - *

The visibility of a shape is usually controlled by whatever program created the SVG file. - * For instance, this parameter is controlled by showing or hiding the shape in the layers palette in Adobe Illustrator. - * - * @param {boolean} visible "false" makes the shape invisible and "true" makes it visible - */ - setVisible: function (visible){ - this.visible = visible; - }, - /** - * @member PShape - * The disableStyle() function disables the shape's style data and uses Processing's current styles. Styles include attributes such as colors, stroke weight, and stroke joints. - * Overrides this shape's style information and uses PGraphics styles and colors. Identical to ignoreStyles(true). Also disables styles for all child shapes. - */ - disableStyle: function(){ - this.style = false; - for(var i = 0, j=this.children.length; i part of the SVG document. - */ - drawPath: function(){ - var i, j; - if (this.vertices.length === 0) { return; } - p.beginShape(); - if (this.vertexCodes.length === 0) { // each point is a simple vertex - if (this.vertices[0].length === 2) { // drawing 2D vertices - for (i = 0, j = this.vertices.length; i < j; i++) { - p.vertex(this.vertices[i][0], this.vertices[i][1]); - } - } else { // drawing 3D vertices - for (i = 0, j = this.vertices.length; i < j; i++) { - p.vertex(this.vertices[i][0], - this.vertices[i][1], - this.vertices[i][2]); - } - } - } else { // coded set of vertices - var index = 0; - if (this.vertices[0].length === 2) { // drawing a 2D path - for (i = 0, j = this.vertexCodes.length; i < j; i++) { - if (this.vertexCodes[i] === PConstants.VERTEX) { - p.vertex(this.vertices[index][0], this.vertices[index][1]); - if ( this.vertices[index]["moveTo"] === true) { - vertArray[vertArray.length-1]["moveTo"] = true; - } else if ( this.vertices[index]["moveTo"] === false) { - vertArray[vertArray.length-1]["moveTo"] = false; - } - p.breakShape = false; - index++; - } else if (this.vertexCodes[i] === PConstants.BEZIER_VERTEX) { - p.bezierVertex(this.vertices[index+0][0], - this.vertices[index+0][1], - this.vertices[index+1][0], - this.vertices[index+1][1], - this.vertices[index+2][0], - this.vertices[index+2][1]); - index += 3; - } else if (this.vertexCodes[i] === PConstants.CURVE_VERTEX) { - p.curveVertex(this.vertices[index][0], - this.vertices[index][1]); - index++; - } else if (this.vertexCodes[i] === PConstants.BREAK) { - p.breakShape = true; - } - } - } else { // drawing a 3D path - for (i = 0, j = this.vertexCodes.length; i < j; i++) { - if (this.vertexCodes[i] === PConstants.VERTEX) { - p.vertex(this.vertices[index][0], - this.vertices[index][1], - this.vertices[index][2]); - if (this.vertices[index]["moveTo"] === true) { - vertArray[vertArray.length-1]["moveTo"] = true; - } else if (this.vertices[index]["moveTo"] === false) { - vertArray[vertArray.length-1]["moveTo"] = false; - } - p.breakShape = false; - } else if (this.vertexCodes[i] === PConstants.BEZIER_VERTEX) { - p.bezierVertex(this.vertices[index+0][0], - this.vertices[index+0][1], - this.vertices[index+0][2], - this.vertices[index+1][0], - this.vertices[index+1][1], - this.vertices[index+1][2], - this.vertices[index+2][0], - this.vertices[index+2][1], - this.vertices[index+2][2]); - index += 3; - } else if (this.vertexCodes[i] === PConstants.CURVE_VERTEX) { - p.curveVertex(this.vertices[index][0], - this.vertices[index][1], - this.vertices[index][2]); - index++; - } else if (this.vertexCodes[i] === PConstants.BREAK) { - p.breakShape = true; - } - } - } - } - p.endShape(this.close ? PConstants.CLOSE : PConstants.OPEN); - }, - /** - * @member PShape - * The drawGeometry() function draws the geometry part of the SVG document. - */ - drawGeometry: function() { - var i, j; - p.beginShape(this.kind); - if (this.style) { - for (i = 0, j = this.vertices.length; i < j; i++) { - p.vertex(this.vertices[i]); - } - } else { - for (i = 0, j = this.vertices.length; i < j; i++) { - var vert = this.vertices[i]; - if (vert[2] === 0) { - p.vertex(vert[0], vert[1]); - } else { - p.vertex(vert[0], vert[1], vert[2]); - } - } - } - p.endShape(); - }, - /** - * @member PShape - * The drawGroup() function draws the part of the SVG document. - */ - drawGroup: function() { - for (var i = 0, j = this.children.length; i < j; i++) { - this.children[i].draw(); - } - }, - /** - * @member PShape - * The drawPrimitive() function draws SVG document shape elements. These can be point, line, triangle, quad, rect, ellipse, arc, box, or sphere. - */ - drawPrimitive: function() { - if (this.kind === PConstants.POINT) { - p.point(this.params[0], this.params[1]); - } else if (this.kind === PConstants.LINE) { - if (this.params.length === 4) { // 2D - p.line(this.params[0], this.params[1], - this.params[2], this.params[3]); - } else { // 3D - p.line(this.params[0], this.params[1], this.params[2], - this.params[3], this.params[4], this.params[5]); - } - } else if (this.kind === PConstants.TRIANGLE) { - p.triangle(this.params[0], this.params[1], - this.params[2], this.params[3], - this.params[4], this.params[5]); - } else if (this.kind === PConstants.QUAD) { - p.quad(this.params[0], this.params[1], - this.params[2], this.params[3], - this.params[4], this.params[5], - this.params[6], this.params[7]); - } else if (this.kind === PConstants.RECT) { - if (this.image !== null) { - p.imageMode(PConstants.CORNER); - p.image(this.image, - this.params[0], - this.params[1], - this.params[2], - this.params[3]); - } else { - p.rectMode(PConstants.CORNER); - p.rect(this.params[0], - this.params[1], - this.params[2], - this.params[3]); - } - } else if (this.kind === PConstants.ELLIPSE) { - p.ellipseMode(PConstants.CORNER); - p.ellipse(this.params[0], - this.params[1], - this.params[2], - this.params[3]); - } else if (this.kind === PConstants.ARC) { - p.ellipseMode(PConstants.CORNER); - p.arc(this.params[0], - this.params[1], - this.params[2], - this.params[3], - this.params[4], - this.params[5]); - } else if (this.kind === PConstants.BOX) { - if (this.params.length === 1) { - p.box(this.params[0]); - } else { - p.box(this.params[0], this.params[1], this.params[2]); - } - } else if (this.kind === PConstants.SPHERE) { - p.sphere(this.params[0]); - } - }, - /** - * @member PShape - * The pre() function performs the preparations before the SVG is drawn. This includes doing transformations and storing previous styles. - */ - pre: function() { - if (this.matrix) { - p.pushMatrix(); - curContext.transform(this.matrix.elements[0], - this.matrix.elements[3], - this.matrix.elements[1], - this.matrix.elements[4], - this.matrix.elements[2], - this.matrix.elements[5]); - //p.applyMatrix(this.matrix.elements[0],this.matrix.elements[0]); - } - if (this.style) { - p.pushStyle(); - this.styles(); - } - }, - /** - * @member PShape - * The post() function performs the necessary actions after the SVG is drawn. This includes removing transformations and removing added styles. - */ - post: function() { - if (this.matrix) { - p.popMatrix(); - } - if (this.style) { - p.popStyle(); - } - }, - /** - * @member PShape - * The styles() function changes the Processing's current styles - */ - styles: function() { - if (this.stroke) { - p.stroke(this.strokeColor); - p.strokeWeight(this.strokeWeight); - p.strokeCap(this.strokeCap); - p.strokeJoin(this.strokeJoin); - } else { - p.noStroke(); - } - - if (this.fill) { - p.fill(this.fillColor); - - } else { - p.noFill(); - } - }, - /** - * @member PShape - * The getChild() function extracts a child shape from a parent shape. Specify the name of the shape with the target parameter or the - * layer position of the shape to get with the index parameter. - * The shape is returned as a PShape object, or null is returned if there is an error. - * - * @param {String} target the name of the shape to get - * @param {int} index the layer position of the shape to get - * - * @return {PShape} returns a child element of a shape as a PShape object or null if there is an error - */ - getChild: function(child) { - var i, j; - if (typeof child === 'number') { - return this.children[child]; - } - var found; - if(child === "" || this.name === child){ - return this; - } - if(this.nameTable.length > 0) { - for(i = 0, j = this.nameTable.length; i < j || found; i++) { - if(this.nameTable[i].getName === child) { - found = this.nameTable[i]; - break; - } - } - if (found) { return found; } - } - for(i = 0, j = this.children.length; i < j; i++) { - found = this.children[i].getChild(child); - if(found) { return found; } - } - return null; - }, - /** - * @member PShape - * The getChildCount() returns the number of children - * - * @return {int} returns a count of children - */ - getChildCount: function () { - return this.children.length; - }, - /** - * @member PShape - * The addChild() adds a child to the PShape. - * - * @param {PShape} child the child to add - */ - addChild: function( child ) { - this.children.push(child); - child.parent = this; - if (child.getName() !== null) { - this.addName(child.getName(), child); - } - }, - /** - * @member PShape - * The addName() functions adds a shape to the name lookup table. - * - * @param {String} name the name to be added - * @param {PShape} shape the shape - */ - addName: function(name, shape) { - if (this.parent !== null) { - this.parent.addName( name, shape ); - } else { - this.nameTable.push( [name, shape] ); - } - }, - /** - * @member PShape - * The translate() function specifies an amount to displace the shape. The x parameter specifies left/right translation, the y parameter specifies up/down translation, and the z parameter specifies translations toward/away from the screen. - * Subsequent calls to the method accumulates the effect. For example, calling translate(50, 0) and then translate(20, 0) is the same as translate(70, 0). - * This transformation is applied directly to the shape, it's not refreshed each time draw() is run. - *

Using this method with the z parameter requires using the P3D or OPENGL parameter in combination with size. - * - * @param {int|float} x left/right translation - * @param {int|float} y up/down translation - * @param {int|float} z forward/back translation - * - * @see PMatrix2D#translate - * @see PMatrix3D#translate - */ - translate: function() { - if(arguments.length === 2) - { - this.checkMatrix(2); - this.matrix.translate(arguments[0], arguments[1]); - } else { - this.checkMatrix(3); - this.matrix.translate(arguments[0], arguments[1], 0); - } - }, - /** - * @member PShape - * The checkMatrix() function makes sure that the shape's matrix is 1) not null, and 2) has a matrix - * that can handle at least the specified number of dimensions. - * - * @param {int} dimensions the specified number of dimensions - */ - checkMatrix: function(dimensions) { - if(this.matrix === null) { - if(dimensions === 2) { - this.matrix = new p.PMatrix2D(); - } else { - this.matrix = new p.PMatrix3D(); - } - }else if(dimensions === 3 && this.matrix instanceof p.PMatrix2D) { - this.matrix = new p.PMatrix3D(); - } - }, - /** - * @member PShape - * The rotateX() function rotates a shape around the x-axis the amount specified by the angle parameter. Angles should be specified in radians (values from 0 to TWO_PI) or converted to radians with the radians() method. - *

Shapes are always rotated around the upper-left corner of their bounding box. Positive numbers rotate objects in a clockwise direction. - * Subsequent calls to the method accumulates the effect. For example, calling rotateX(HALF_PI) and then rotateX(HALF_PI) is the same as rotateX(PI). - * This transformation is applied directly to the shape, it's not refreshed each time draw() is run. - *

This method requires a 3D renderer. You need to pass P3D or OPENGL as a third parameter into the size() method as shown in the example above. - * - * @param {float}angle angle of rotation specified in radians - * - * @see PMatrix3D#rotateX - */ - rotateX: function(angle) { - this.rotate(angle, 1, 0, 0); - }, - /** - * @member PShape - * The rotateY() function rotates a shape around the y-axis the amount specified by the angle parameter. Angles should be specified in radians (values from 0 to TWO_PI) or converted to radians with the radians() method. - *

Shapes are always rotated around the upper-left corner of their bounding box. Positive numbers rotate objects in a clockwise direction. - * Subsequent calls to the method accumulates the effect. For example, calling rotateY(HALF_PI) and then rotateY(HALF_PI) is the same as rotateY(PI). - * This transformation is applied directly to the shape, it's not refreshed each time draw() is run. - *

This method requires a 3D renderer. You need to pass P3D or OPENGL as a third parameter into the size() method as shown in the example above. - * - * @param {float}angle angle of rotation specified in radians - * - * @see PMatrix3D#rotateY - */ - rotateY: function(angle) { - this.rotate(angle, 0, 1, 0); - }, - /** - * @member PShape - * The rotateZ() function rotates a shape around the z-axis the amount specified by the angle parameter. Angles should be specified in radians (values from 0 to TWO_PI) or converted to radians with the radians() method. - *

Shapes are always rotated around the upper-left corner of their bounding box. Positive numbers rotate objects in a clockwise direction. - * Subsequent calls to the method accumulates the effect. For example, calling rotateZ(HALF_PI) and then rotateZ(HALF_PI) is the same as rotateZ(PI). - * This transformation is applied directly to the shape, it's not refreshed each time draw() is run. - *

This method requires a 3D renderer. You need to pass P3D or OPENGL as a third parameter into the size() method as shown in the example above. - * - * @param {float}angle angle of rotation specified in radians - * - * @see PMatrix3D#rotateZ - */ - rotateZ: function(angle) { - this.rotate(angle, 0, 0, 1); - }, - /** - * @member PShape - * The rotate() function rotates a shape the amount specified by the angle parameter. Angles should be specified in radians (values from 0 to TWO_PI) or converted to radians with the radians() method. - *

Shapes are always rotated around the upper-left corner of their bounding box. Positive numbers rotate objects in a clockwise direction. - * Transformations apply to everything that happens after and subsequent calls to the method accumulates the effect. - * For example, calling rotate(HALF_PI) and then rotate(HALF_PI) is the same as rotate(PI). - * This transformation is applied directly to the shape, it's not refreshed each time draw() is run. - * If optional parameters x,y,z are supplied, the rotate is about the point (x, y, z). - * - * @param {float}angle angle of rotation specified in radians - * @param {float}x x-coordinate of the point - * @param {float}y y-coordinate of the point - * @param {float}z z-coordinate of the point - * @see PMatrix2D#rotate - * @see PMatrix3D#rotate - */ - rotate: function() { - if(arguments.length === 1){ - this.checkMatrix(2); - this.matrix.rotate(arguments[0]); - } else { - this.checkMatrix(3); - this.matrix.rotate(arguments[0], - arguments[1], - arguments[2], - arguments[3]); - } - }, - /** - * @member PShape - * The scale() function increases or decreases the size of a shape by expanding and contracting vertices. Shapes always scale from the relative origin of their bounding box. - * Scale values are specified as decimal percentages. For example, the method call scale(2.0) increases the dimension of a shape by 200%. - * Subsequent calls to the method multiply the effect. For example, calling scale(2.0) and then scale(1.5) is the same as scale(3.0). - * This transformation is applied directly to the shape, it's not refreshed each time draw() is run. - *

Using this fuction with the z parameter requires passing P3D or OPENGL into the size() parameter. - * - * @param {float}s percentage to scale the object - * @param {float}x percentage to scale the object in the x-axis - * @param {float}y percentage to scale the object in the y-axis - * @param {float}z percentage to scale the object in the z-axis - * - * @see PMatrix2D#scale - * @see PMatrix3D#scale - */ - scale: function() { - if(arguments.length === 2) { - this.checkMatrix(2); - this.matrix.scale(arguments[0], arguments[1]); - } else if (arguments.length === 3) { - this.checkMatrix(2); - this.matrix.scale(arguments[0], arguments[1], arguments[2]); - } else { - this.checkMatrix(2); - this.matrix.scale(arguments[0]); - } - }, - /** - * @member PShape - * The resetMatrix() function resets the matrix - * - * @see PMatrix2D#reset - * @see PMatrix3D#reset - */ - resetMatrix: function() { - this.checkMatrix(2); - this.matrix.reset(); - }, - /** - * @member PShape - * The applyMatrix() function multiplies this matrix by another matrix of type PMatrix3D or PMatrix2D. - * Individual elements can also be provided - * - * @param {PMatrix3D|PMatrix2D} matrix the matrix to multiply by - * - * @see PMatrix2D#apply - * @see PMatrix3D#apply - */ - applyMatrix: function(matrix) { - if (arguments.length === 1) { - this.applyMatrix(matrix.elements[0], - matrix.elements[1], 0, - matrix.elements[2], - matrix.elements[3], - matrix.elements[4], 0, - matrix.elements[5], - 0, 0, 1, 0, - 0, 0, 0, 1); - } else if (arguments.length === 6) { - this.checkMatrix(2); - this.matrix.apply(arguments[0], arguments[1], arguments[2], 0, - arguments[3], arguments[4], arguments[5], 0, - 0, 0, 1, 0, - 0, 0, 0, 1); - - } else if (arguments.length === 16) { - this.checkMatrix(3); - this.matrix.apply(arguments[0], - arguments[1], - arguments[2], - arguments[3], - arguments[4], - arguments[5], - arguments[6], - arguments[7], - arguments[8], - arguments[9], - arguments[10], - arguments[11], - arguments[12], - arguments[13], - arguments[14], - arguments[15]); - } - } - }; - - /** - * SVG stands for Scalable Vector Graphics, a portable graphics format. It is - * a vector format so it allows for infinite resolution and relatively small - * file sizes. Most modern media software can view SVG files, including Adobe - * products, Firefox, etc. Illustrator and Inkscape can edit SVG files. - * - * @param {PApplet} parent typically use "this" - * @param {String} filename name of the SVG file to load - * @param {XMLElement} xml an XMLElement element - * @param {PShapeSVG} parent the parent PShapeSVG - * - * @see PShape - */ - var PShapeSVG = p.PShapeSVG = function() { - p.PShape.call( this ); // PShape is the base class. - if (arguments.length === 1) { //xml element coming in - this.element = arguments[0] ;//new p.XMLElement(null, arguments[0]); - // set values to their defaults according to the SVG spec - this.vertexCodes = []; - this.vertices = []; - this.opacity = 1; - - this.stroke = false; - this.strokeColor = PConstants.ALPHA_MASK; - this.strokeWeight = 1; - this.strokeCap = PConstants.SQUARE; // BUTT in svg spec - this.strokeJoin = PConstants.MITER; - this.strokeGradient = null; - this.strokeGradientPaint = null; - this.strokeName = null; - this.strokeOpacity = 1; - - this.fill = true; - this.fillColor = PConstants.ALPHA_MASK; - this.fillGradient = null; - this.fillGradientPaint = null; - this.fillName = null; - this.fillOpacity = 1; - - if (this.element.getName() !== "svg") { - throw("root is not , it's <" + this.element.getName() + ">"); - } - } - else if (arguments.length === 2) { - if (typeof arguments[1] === 'string') { - if (arguments[1].indexOf(".svg") > -1) { //its a filename - this.element = new p.XMLElement(null, arguments[1]); - // set values to their defaults according to the SVG spec - this.vertexCodes = []; - this.vertices = []; - this.opacity = 1; - - this.stroke = false; - this.strokeColor = PConstants.ALPHA_MASK; - this.strokeWeight = 1; - this.strokeCap = PConstants.SQUARE; // BUTT in svg spec - this.strokeJoin = PConstants.MITER; - this.strokeGradient = ""; - this.strokeGradientPaint = ""; - this.strokeName = ""; - this.strokeOpacity = 1; - - this.fill = true; - this.fillColor = PConstants.ALPHA_MASK; - this.fillGradient = null; - this.fillGradientPaint = null; - this.fillOpacity = 1; - - } - } else { // XMLElement - if (arguments[0]) { // PShapeSVG - this.element = arguments[1]; - this.vertexCodes = arguments[0].vertexCodes.slice(); - this.vertices = arguments[0].vertices.slice(); - - this.stroke = arguments[0].stroke; - this.strokeColor = arguments[0].strokeColor; - this.strokeWeight = arguments[0].strokeWeight; - this.strokeCap = arguments[0].strokeCap; - this.strokeJoin = arguments[0].strokeJoin; - this.strokeGradient = arguments[0].strokeGradient; - this.strokeGradientPaint = arguments[0].strokeGradientPaint; - this.strokeName = arguments[0].strokeName; - - this.fill = arguments[0].fill; - this.fillColor = arguments[0].fillColor; - this.fillGradient = arguments[0].fillGradient; - this.fillGradientPaint = arguments[0].fillGradientPaint; - this.fillName = arguments[0].fillName; - this.strokeOpacity = arguments[0].strokeOpacity; - this.fillOpacity = arguments[0].fillOpacity; - this.opacity = arguments[0].opacity; - } - } - } - - this.name = this.element.getStringAttribute("id"); - var displayStr = this.element.getStringAttribute("display", "inline"); - this.visible = displayStr !== "none"; - var str = this.element.getAttribute("transform"); - if (str) { - this.matrix = this.parseMatrix(str); - } - // not proper parsing of the viewBox, but will cover us for cases where - // the width and height of the object is not specified - var viewBoxStr = this.element.getStringAttribute("viewBox"); - if ( viewBoxStr !== null ) { - var viewBox = viewBoxStr.split(" "); - this.width = viewBox[2]; - this.height = viewBox[3]; - } - - // TODO if viewbox is not same as width/height, then use it to scale - // the original objects. for now, viewbox only used when width/height - // are empty values (which by the spec means w/h of "100%" - var unitWidth = this.element.getStringAttribute("width"); - var unitHeight = this.element.getStringAttribute("height"); - if (unitWidth !== null) { - this.width = this.parseUnitSize(unitWidth); - this.height = this.parseUnitSize(unitHeight); - } else { - if ((this.width === 0) || (this.height === 0)) { - // For the spec, the default is 100% and 100%. For purposes - // here, insert a dummy value because this is prolly just a - // font or something for which the w/h doesn't matter. - this.width = 1; - this.height = 1; - - //show warning - throw("The width and/or height is not " + - "readable in the tag of this file."); - } - } - this.parseColors(this.element); - this.parseChildren(this.element); - - }; - /** - * PShapeSVG methods - * missing: getChild(), print(), parseStyleAttributes(), styles() - deals with strokeGradient and fillGradient - */ - PShapeSVG.prototype = new PShape(); - /** - * @member PShapeSVG - * The parseMatrix() function parses the specified SVG matrix into a PMatrix2D. Note that PMatrix2D - * is rotated relative to the SVG definition, so parameters are rearranged - * here. More about the transformation matrices in - * this section - * of the SVG documentation. - * - * @param {String} str text of the matrix param. - * - * @return {PMatrix2D} a PMatrix2D - */ - PShapeSVG.prototype.parseMatrix = (function() { - function getCoords(s) { - var m = []; - s.replace(/\((.*?)\)/, (function() { - return function(all, params) { - // get the coordinates that can be separated by spaces or a comma - m = params.replace(/,+/g, " ").split(/\s+/); - }; - }())); - return m; - } - - return function(str) { - this.checkMatrix(2); - var pieces = []; - str.replace(/\s*(\w+)\((.*?)\)/g, function(all) { - // get a list of transform definitions - pieces.push(p.trim(all)); - }); - if (pieces.length === 0) { - return null; - } - - for (var i = 0, j = pieces.length; i < j; i++) { - var m = getCoords(pieces[i]); - - if (pieces[i].indexOf("matrix") !== -1) { - this.matrix.set(m[0], m[2], m[4], m[1], m[3], m[5]); - } else if (pieces[i].indexOf("translate") !== -1) { - var tx = m[0]; - var ty = (m.length === 2) ? m[1] : 0; - this.matrix.translate(tx,ty); - } else if (pieces[i].indexOf("scale") !== -1) { - var sx = m[0]; - var sy = (m.length === 2) ? m[1] : m[0]; - this.matrix.scale(sx,sy); - } else if (pieces[i].indexOf("rotate") !== -1) { - var angle = m[0]; - if (m.length === 1) { - this.matrix.rotate(p.radians(angle)); - } else if (m.length === 3) { - this.matrix.translate(m[1], m[2]); - this.matrix.rotate(p.radians(m[0])); - this.matrix.translate(-m[1], -m[2]); - } - } else if (pieces[i].indexOf("skewX") !== -1) { - this.matrix.skewX(parseFloat(m[0])); - } else if (pieces[i].indexOf("skewY") !== -1) { - this.matrix.skewY(m[0]); - } - } - return this.matrix; - }; - }()); - - /** - * @member PShapeSVG - * The parseChildren() function parses the specified XMLElement - * - * @param {XMLElement}element the XMLElement to parse - */ - PShapeSVG.prototype.parseChildren = function(element) { - var newelement = element.getChildren(); - var children = new p.PShape(); - for (var i = 0, j = newelement.length; i < j; i++) { - var kid = this.parseChild(newelement[i]); - if (kid) { - children.addChild(kid); - } - } - this.children.push(children); - }; - /** - * @member PShapeSVG - * The getName() function returns the name - * - * @return {String} the name - */ - PShapeSVG.prototype.getName = function() { - return this.name; - }; - /** - * @member PShapeSVG - * The parseChild() function parses a child XML element. - * - * @param {XMLElement} elem the element to parse - * - * @return {PShape} the newly created PShape - */ - PShapeSVG.prototype.parseChild = function( elem ) { - var name = elem.getName(); - var shape; - if (name === "g") { - shape = new PShapeSVG(this, elem); - } else if (name === "defs") { - // generally this will contain gradient info, so may - // as well just throw it into a group element for parsing - shape = new PShapeSVG(this, elem); - } else if (name === "line") { - shape = new PShapeSVG(this, elem); - shape.parseLine(); - } else if (name === "circle") { - shape = new PShapeSVG(this, elem); - shape.parseEllipse(true); - } else if (name === "ellipse") { - shape = new PShapeSVG(this, elem); - shape.parseEllipse(false); - } else if (name === "rect") { - shape = new PShapeSVG(this, elem); - shape.parseRect(); - } else if (name === "polygon") { - shape = new PShapeSVG(this, elem); - shape.parsePoly(true); - } else if (name === "polyline") { - shape = new PShapeSVG(this, elem); - shape.parsePoly(false); - } else if (name === "path") { - shape = new PShapeSVG(this, elem); - shape.parsePath(); - } else if (name === "radialGradient") { - //return new RadialGradient(this, elem); - unimplemented('PShapeSVG.prototype.parseChild, name = radialGradient'); - } else if (name === "linearGradient") { - //return new LinearGradient(this, elem); - unimplemented('PShapeSVG.prototype.parseChild, name = linearGradient'); - } else if (name === "text") { - unimplemented('PShapeSVG.prototype.parseChild, name = text'); - } else if (name === "filter") { - unimplemented('PShapeSVG.prototype.parseChild, name = filter'); - } else if (name === "mask") { - unimplemented('PShapeSVG.prototype.parseChild, name = mask'); - } else { - // ignoring - nop(); - } - return shape; - }; - /** - * @member PShapeSVG - * The parsePath() function parses the element of the svg file - * A path is defined by including a path element which contains a d="(path data)" attribute, where the d attribute contains - * the moveto, line, curve (both cubic and quadratic Beziers), arc and closepath instructions. - **/ - PShapeSVG.prototype.parsePath = function() { - this.family = PConstants.PATH; - this.kind = 0; - var pathDataChars = []; - var c; - //change multiple spaces and commas to single space - var pathData = p.trim(this.element.getStringAttribute("d") - .replace(/[\s,]+/g,' ')); - if (pathData === null) { - return; - } - pathData = p.__toCharArray(pathData); - var cx = 0, - cy = 0, - ctrlX = 0, - ctrlY = 0, - ctrlX1 = 0, - ctrlX2 = 0, - ctrlY1 = 0, - ctrlY2 = 0, - endX = 0, - endY = 0, - ppx = 0, - ppy = 0, - px = 0, - py = 0, - i = 0, - valOf = 0; - var str = ""; - var tmpArray =[]; - var flag = false; - var lastInstruction; - var command; - var j, k; - while (i< pathData.length) { - valOf = pathData[i].valueOf(); - if ((valOf >= 65 && valOf <= 90) || (valOf >= 97 && valOf <= 122)) { - // if it's a letter - // populate the tmpArray with coordinates - j = i; - i++; - if (i < pathData.length) { // don't go over boundary of array - tmpArray = []; - valOf = pathData[i].valueOf(); - while (!((valOf >= 65 && valOf <= 90) || - (valOf >= 97 && valOf <= 100) || - (valOf >= 102 && valOf <= 122)) - && flag === false) { // if its NOT a letter - if (valOf === 32) { //if its a space and the str isn't empty - // sometimes you get a space after the letter - if (str !== "") { - tmpArray.push(parseFloat(str)); - str = ""; - } - i++; - } else if (valOf === 45) { //if it's a - - // allow for 'e' notation in numbers, e.g. 2.10e-9 - if (pathData[i-1].valueOf() === 101) { - str += pathData[i].toString(); - i++; - } else { - // sometimes no space separator after (ex: 104.535-16.322) - if (str !== "") { - tmpArray.push(parseFloat(str)); - } - str = pathData[i].toString(); - i++; - } - } else { - str += pathData[i].toString(); - i++; - } - if (i === pathData.length) { // don't go over boundary of array - flag = true; - } else { - valOf = pathData[i].valueOf(); - } - } - } - if (str !== "") { - tmpArray.push(parseFloat(str)); - str = ""; - } - command = pathData[j]; - valOf = command.valueOf(); - if (valOf === 77) { // M - move to (absolute) - if (tmpArray.length >= 2 && tmpArray.length % 2 ===0) { - // need one+ pairs of co-ordinates - cx = tmpArray[0]; - cy = tmpArray[1]; - this.parsePathMoveto(cx, cy); - if (tmpArray.length > 2) { - for (j = 2, k = tmpArray.length; j < k; j+=2) { - // absolute line to - cx = tmpArray[j]; - cy = tmpArray[j+1]; - this.parsePathLineto(cx,cy); - } - } - } - } else if (valOf === 109) { // m - move to (relative) - if (tmpArray.length >= 2 && tmpArray.length % 2 === 0) { - // need one+ pairs of co-ordinates - cx += tmpArray[0]; - cy += tmpArray[1]; - this.parsePathMoveto(cx,cy); - if (tmpArray.length > 2) { - for (j = 2, k = tmpArray.length; j < k; j+=2) { - // relative line to - cx += tmpArray[j]; - cy += tmpArray[j + 1]; - this.parsePathLineto(cx,cy); - } - } - } - } else if (valOf === 76) { // L - lineto (absolute) - if (tmpArray.length >= 2 && tmpArray.length % 2 === 0) { - // need one+ pairs of co-ordinates - for (j = 0, k = tmpArray.length; j < k; j+=2) { - cx = tmpArray[j]; - cy = tmpArray[j + 1]; - this.parsePathLineto(cx,cy); - } - } - } else if (valOf === 108) { // l - lineto (relative) - if (tmpArray.length >= 2 && tmpArray.length % 2 === 0) { - // need one+ pairs of co-ordinates - for (j = 0, k = tmpArray.length; j < k; j+=2) { - cx += tmpArray[j]; - cy += tmpArray[j+1]; - this.parsePathLineto(cx,cy); - } - } - } else if (valOf === 72) { // H - horizontal lineto (absolute) - for (j = 0, k = tmpArray.length; j < k; j++) { - // multiple x co-ordinates can be provided - cx = tmpArray[j]; - this.parsePathLineto(cx, cy); - } - } else if (valOf === 104) { // h - horizontal lineto (relative) - for (j = 0, k = tmpArray.length; j < k; j++) { - // multiple x co-ordinates can be provided - cx += tmpArray[j]; - this.parsePathLineto(cx, cy); - } - } else if (valOf === 86) { // V - vertical lineto (absolute) - for (j = 0, k = tmpArray.length; j < k; j++) { - // multiple y co-ordinates can be provided - cy = tmpArray[j]; - this.parsePathLineto(cx, cy); - } - } else if (valOf === 118) { // v - vertical lineto (relative) - for (j = 0, k = tmpArray.length; j < k; j++) { - // multiple y co-ordinates can be provided - cy += tmpArray[j]; - this.parsePathLineto(cx, cy); - } - } else if (valOf === 67) { // C - curve to (absolute) - if (tmpArray.length >= 6 && tmpArray.length % 6 === 0) { - // need one+ multiples of 6 co-ordinates - for (j = 0, k = tmpArray.length; j < k; j+=6) { - ctrlX1 = tmpArray[j]; - ctrlY1 = tmpArray[j + 1]; - ctrlX2 = tmpArray[j + 2]; - ctrlY2 = tmpArray[j + 3]; - endX = tmpArray[j + 4]; - endY = tmpArray[j + 5]; - this.parsePathCurveto(ctrlX1, - ctrlY1, - ctrlX2, - ctrlY2, - endX, - endY); - cx = endX; - cy = endY; - } - } - } else if (valOf === 99) { // c - curve to (relative) - if (tmpArray.length >= 6 && tmpArray.length % 6 === 0) { - // need one+ multiples of 6 co-ordinates - for (j = 0, k = tmpArray.length; j < k; j+=6) { - ctrlX1 = cx + tmpArray[j]; - ctrlY1 = cy + tmpArray[j + 1]; - ctrlX2 = cx + tmpArray[j + 2]; - ctrlY2 = cy + tmpArray[j + 3]; - endX = cx + tmpArray[j + 4]; - endY = cy + tmpArray[j + 5]; - this.parsePathCurveto(ctrlX1, - ctrlY1, - ctrlX2, - ctrlY2, - endX, - endY); - cx = endX; - cy = endY; - } - } - } else if (valOf === 83) { // S - curve to shorthand (absolute) - if (tmpArray.length >= 4 && tmpArray.length % 4 === 0) { - // need one+ multiples of 4 co-ordinates - for (j = 0, k = tmpArray.length; j < k; j+=4) { - if (lastInstruction.toLowerCase() === "c" || - lastInstruction.toLowerCase() === "s") { - ppx = this.vertices[ this.vertices.length-2 ][0]; - ppy = this.vertices[ this.vertices.length-2 ][1]; - px = this.vertices[ this.vertices.length-1 ][0]; - py = this.vertices[ this.vertices.length-1 ][1]; - ctrlX1 = px + (px - ppx); - ctrlY1 = py + (py - ppy); - } else { - //If there is no previous curve, - //the current point will be used as the first control point. - ctrlX1 = this.vertices[this.vertices.length-1][0]; - ctrlY1 = this.vertices[this.vertices.length-1][1]; - } - ctrlX2 = tmpArray[j]; - ctrlY2 = tmpArray[j + 1]; - endX = tmpArray[j + 2]; - endY = tmpArray[j + 3]; - this.parsePathCurveto(ctrlX1, - ctrlY1, - ctrlX2, - ctrlY2, - endX, - endY); - cx = endX; - cy = endY; - } - } - } else if (valOf === 115) { // s - curve to shorthand (relative) - if (tmpArray.length >= 4 && tmpArray.length % 4 === 0) { - // need one+ multiples of 4 co-ordinates - for (j = 0, k = tmpArray.length; j < k; j+=4) { - if (lastInstruction.toLowerCase() === "c" || - lastInstruction.toLowerCase() === "s") { - ppx = this.vertices[this.vertices.length-2][0]; - ppy = this.vertices[this.vertices.length-2][1]; - px = this.vertices[this.vertices.length-1][0]; - py = this.vertices[this.vertices.length-1][1]; - ctrlX1 = px + (px - ppx); - ctrlY1 = py + (py - ppy); - } else { - //If there is no previous curve, - //the current point will be used as the first control point. - ctrlX1 = this.vertices[this.vertices.length-1][0]; - ctrlY1 = this.vertices[this.vertices.length-1][1]; - } - ctrlX2 = cx + tmpArray[j]; - ctrlY2 = cy + tmpArray[j + 1]; - endX = cx + tmpArray[j + 2]; - endY = cy + tmpArray[j + 3]; - this.parsePathCurveto(ctrlX1, - ctrlY1, - ctrlX2, - ctrlY2, - endX, - endY); - cx = endX; - cy = endY; - } - } - } else if (valOf === 81) { // Q - quadratic curve to (absolute) - if (tmpArray.length >= 4 && tmpArray.length % 4 === 0) { - // need one+ multiples of 4 co-ordinates - for (j = 0, k = tmpArray.length; j < k; j+=4) { - ctrlX = tmpArray[j]; - ctrlY = tmpArray[j + 1]; - endX = tmpArray[j + 2]; - endY = tmpArray[j + 3]; - this.parsePathQuadto(cx, cy, ctrlX, ctrlY, endX, endY); - cx = endX; - cy = endY; - } - } - } else if (valOf === 113) { // q - quadratic curve to (relative) - if (tmpArray.length >= 4 && tmpArray.length % 4 === 0) { - // need one+ multiples of 4 co-ordinates - for (j = 0, k = tmpArray.length; j < k; j+=4) { - ctrlX = cx + tmpArray[j]; - ctrlY = cy + tmpArray[j + 1]; - endX = cx + tmpArray[j + 2]; - endY = cy + tmpArray[j + 3]; - this.parsePathQuadto(cx, cy, ctrlX, ctrlY, endX, endY); - cx = endX; - cy = endY; - } - } - } else if (valOf === 84) { - // T - quadratic curve to shorthand (absolute) - if (tmpArray.length >= 2 && tmpArray.length % 2 === 0) { - // need one+ pairs of co-ordinates - for (j = 0, k = tmpArray.length; j < k; j+=2) { - if (lastInstruction.toLowerCase() === "q" || - lastInstruction.toLowerCase() === "t") { - ppx = this.vertices[this.vertices.length-2][0]; - ppy = this.vertices[this.vertices.length-2][1]; - px = this.vertices[this.vertices.length-1][0]; - py = this.vertices[this.vertices.length-1][1]; - ctrlX = px + (px - ppx); - ctrlY = py + (py - ppy); - } else { - // If there is no previous command or if the previous command - // was not a Q, q, T or t, assume the control point is - // coincident with the current point. - ctrlX = cx; - ctrlY = cy; - } - endX = tmpArray[j]; - endY = tmpArray[j + 1]; - this.parsePathQuadto(cx, cy, ctrlX, ctrlY, endX, endY); - cx = endX; - cy = endY; - } - } - } else if (valOf === 116) { - // t - quadratic curve to shorthand (relative) - if (tmpArray.length >= 2 && tmpArray.length % 2 === 0) { - // need one+ pairs of co-ordinates - for (j = 0, k = tmpArray.length; j < k; j+=2) { - if (lastInstruction.toLowerCase() === "q" || - lastInstruction.toLowerCase() === "t") { - ppx = this.vertices[this.vertices.length-2][0]; - ppy = this.vertices[this.vertices.length-2][1]; - px = this.vertices[this.vertices.length-1][0]; - py = this.vertices[this.vertices.length-1][1]; - ctrlX = px + (px - ppx); - ctrlY = py + (py - ppy); - } else { - // If there is no previous command or if the previous command - // was not a Q, q, T or t, assume the control point is - // coincident with the current point. - ctrlX = cx; - ctrlY = cy; - } - endX = cx + tmpArray[j]; - endY = cy + tmpArray[j + 1]; - this.parsePathQuadto(cx, cy, ctrlX, ctrlY, endX, endY); - cx = endX; - cy = endY; - } - } - } else if (valOf === 90 || valOf === 122) { // Z or z (these do the same thing) - this.close = true; - } - lastInstruction = command.toString(); - } else { i++;} - } - }; - /** - * @member PShapeSVG - * PShapeSVG.parsePath() helper function - * - * @see PShapeSVG#parsePath - */ - PShapeSVG.prototype.parsePathQuadto = function(x1, y1, cx, cy, x2, y2) { - if (this.vertices.length > 0) { - this.parsePathCode(PConstants.BEZIER_VERTEX); - // x1/y1 already covered by last moveto, lineto, or curveto - this.parsePathVertex(x1 + ((cx-x1)*2/3), y1 + ((cy-y1)*2/3)); - this.parsePathVertex(x2 + ((cx-x2)*2/3), y2 + ((cy-y2)*2/3)); - this.parsePathVertex(x2, y2); - } else { - throw ("Path must start with M/m"); - } - }; - /** - * @member PShapeSVG - * PShapeSVG.parsePath() helper function - * - * @see PShapeSVG#parsePath - */ - PShapeSVG.prototype.parsePathCurveto = function(x1, y1, x2, y2, x3, y3) { - if (this.vertices.length > 0) { - this.parsePathCode(PConstants.BEZIER_VERTEX ); - this.parsePathVertex(x1, y1); - this.parsePathVertex(x2, y2); - this.parsePathVertex(x3, y3); - } else { - throw ("Path must start with M/m"); - } - }; - /** - * @member PShapeSVG - * PShapeSVG.parsePath() helper function - * - * @see PShapeSVG#parsePath - */ - PShapeSVG.prototype.parsePathLineto = function(px, py) { - if (this.vertices.length > 0) { - this.parsePathCode(PConstants.VERTEX); - this.parsePathVertex(px, py); - // add property to distinguish between curContext.moveTo - // or curContext.lineTo - this.vertices[this.vertices.length-1]["moveTo"] = false; - } else { - throw ("Path must start with M/m"); - } - }; - - PShapeSVG.prototype.parsePathMoveto = function(px, py) { - if (this.vertices.length > 0) { - this.parsePathCode(PConstants.BREAK); - } - this.parsePathCode(PConstants.VERTEX); - this.parsePathVertex(px, py); - // add property to distinguish between curContext.moveTo - // or curContext.lineTo - this.vertices[this.vertices.length-1]["moveTo"] = true; - }; - /** - * @member PShapeSVG - * PShapeSVG.parsePath() helper function - * - * @see PShapeSVG#parsePath - */ - PShapeSVG.prototype.parsePathVertex = function(x, y) { - var verts = []; - verts[0] = x; - verts[1] = y; - this.vertices.push(verts); - }; - /** - * @member PShapeSVG - * PShapeSVG.parsePath() helper function - * - * @see PShapeSVG#parsePath - */ - PShapeSVG.prototype.parsePathCode = function(what) { - this.vertexCodes.push(what); - }; - /** - * @member PShapeSVG - * The parsePoly() function parses a polyline or polygon from an SVG file. - * - * @param {boolean}val true if shape is closed (polygon), false if not (polyline) - */ - PShapeSVG.prototype.parsePoly = function(val) { - this.family = PConstants.PATH; - this.close = val; - var pointsAttr = p.trim(this.element.getStringAttribute("points") - .replace(/[,\s]+/g,' ')); - if (pointsAttr !== null) { - //split into array - var pointsBuffer = pointsAttr.split(" "); - if (pointsBuffer.length % 2 === 0) { - for (var i = 0, j = pointsBuffer.length; i < j; i++) { - var verts = []; - verts[0] = pointsBuffer[i]; - verts[1] = pointsBuffer[++i]; - this.vertices.push(verts); - } - } else { - throw("Error parsing polygon points: odd number of coordinates provided"); - } - } - }; - /** - * @member PShapeSVG - * The parseRect() function parses a rect from an SVG file. - */ - PShapeSVG.prototype.parseRect = function() { - this.kind = PConstants.RECT; - this.family = PConstants.PRIMITIVE; - this.params = []; - this.params[0] = this.element.getFloatAttribute("x"); - this.params[1] = this.element.getFloatAttribute("y"); - this.params[2] = this.element.getFloatAttribute("width"); - this.params[3] = this.element.getFloatAttribute("height"); - if (this.params[2] < 0 || this.params[3] < 0) { - throw("svg error: negative width or height found while parsing "); - } - }; - /** - * @member PShapeSVG - * The parseEllipse() function handles parsing ellipse and circle tags. - * - * @param {boolean}val true if this is a circle and not an ellipse - */ - PShapeSVG.prototype.parseEllipse = function(val) { - this.kind = PConstants.ELLIPSE; - this.family = PConstants.PRIMITIVE; - this.params = []; - - this.params[0] = this.element.getFloatAttribute("cx") | 0 ; - this.params[1] = this.element.getFloatAttribute("cy") | 0; - - var rx, ry; - if (val) { - rx = ry = this.element.getFloatAttribute("r"); - if (rx < 0) { - throw("svg error: negative radius found while parsing "); - } - } else { - rx = this.element.getFloatAttribute("rx"); - ry = this.element.getFloatAttribute("ry"); - if (rx < 0 || ry < 0) { - throw("svg error: negative x-axis radius or y-axis radius found while parsing "); - } - } - this.params[0] -= rx; - this.params[1] -= ry; - - this.params[2] = rx*2; - this.params[3] = ry*2; - }; - /** - * @member PShapeSVG - * The parseLine() function handles parsing line tags. - * - * @param {boolean}val true if this is a circle and not an ellipse - */ - PShapeSVG.prototype.parseLine = function() { - this.kind = PConstants.LINE; - this.family = PConstants.PRIMITIVE; - this.params = []; - this.params[0] = this.element.getFloatAttribute("x1"); - this.params[1] = this.element.getFloatAttribute("y1"); - this.params[2] = this.element.getFloatAttribute("x2"); - this.params[3] = this.element.getFloatAttribute("y2"); - }; - /** - * @member PShapeSVG - * The parseColors() function handles parsing the opacity, strijem stroke-width, stroke-linejoin,stroke-linecap, fill, and style attributes - * - * @param {XMLElement}element the element of which attributes to parse - */ - PShapeSVG.prototype.parseColors = function(element) { - if (element.hasAttribute("opacity")) { - this.setOpacity(element.getAttribute("opacity")); - } - if (element.hasAttribute("stroke")) { - this.setStroke(element.getAttribute("stroke")); - } - if (element.hasAttribute("stroke-width")) { - // if NaN (i.e. if it's 'inherit') then default - // back to the inherit setting - this.setStrokeWeight(element.getAttribute("stroke-width")); - } - if (element.hasAttribute("stroke-linejoin") ) { - this.setStrokeJoin(element.getAttribute("stroke-linejoin")); - } - if (element.hasAttribute("stroke-linecap")) { - this.setStrokeCap(element.getStringAttribute("stroke-linecap")); - } - // fill defaults to black (though stroke defaults to "none") - // http://www.w3.org/TR/SVG/painting.html#FillProperties - if (element.hasAttribute("fill")) { - this.setFill(element.getStringAttribute("fill")); - } - if (element.hasAttribute("style")) { - var styleText = element.getStringAttribute("style"); - var styleTokens = styleText.toString().split( ";" ); - - for (var i = 0, j = styleTokens.length; i < j; i++) { - var tokens = p.trim(styleTokens[i].split( ":" )); - if (tokens[0] === "fill") { - this.setFill(tokens[1]); - } else if (tokens[0] === "fill-opacity") { - this.setFillOpacity(tokens[1]); - } else if (tokens[0] === "stroke") { - this.setStroke(tokens[1]); - } else if (tokens[0] === "stroke-width") { - this.setStrokeWeight(tokens[1]); - } else if (tokens[0] === "stroke-linecap") { - this.setStrokeCap(tokens[1]); - } else if (tokens[0] === "stroke-linejoin") { - this.setStrokeJoin(tokens[1]); - } else if (tokens[0] === "stroke-opacity") { - this.setStrokeOpacity(tokens[1]); - } else if (tokens[0] === "opacity") { - this.setOpacity(tokens[1]); - } // Other attributes are not yet implemented - } - } - }; - /** - * @member PShapeSVG - * PShapeSVG.parseColors() helper function - * - * @param {String} opacityText the value of fillOpacity - * - * @see PShapeSVG#parseColors - */ - PShapeSVG.prototype.setFillOpacity = function(opacityText) { - this.fillOpacity = parseFloat(opacityText); - this.fillColor = this.fillOpacity * 255 << 24 | - this.fillColor & 0xFFFFFF; - }; - /** - * @member PShapeSVG - * PShapeSVG.parseColors() helper function - * - * @param {String} fillText the value of fill - * - * @see PShapeSVG#parseColors - */ - PShapeSVG.prototype.setFill = function (fillText) { - var opacityMask = this.fillColor & 0xFF000000; - if (fillText === "none") { - this.fill = false; - } else if (fillText.indexOf("#") === 0) { - this.fill = true; - if (fillText.length === 4) { - // convert #00F to #0000FF - fillText = fillText.replace(/#(.)(.)(.)/,"#$1$1$2$2$3$3"); - } - this.fillColor = opacityMask | - (parseInt(fillText.substring(1), 16 )) & - 0xFFFFFF; - } else if (fillText.indexOf("rgb") === 0) { - this.fill = true; - this.fillColor = opacityMask | this.parseRGB(fillText); - } else if (fillText.indexOf("url(#") === 0) { - this.fillName = fillText.substring(5, fillText.length - 1 ); - } else if (colors[fillText]) { - this.fill = true; - this.fillColor = opacityMask | - (parseInt(colors[fillText].substring(1), 16)) & - 0xFFFFFF; - } - }; - /** - * @member PShapeSVG - * PShapeSVG.parseColors() helper function - * - * @param {String} opacity the value of opacity - * - * @see PShapeSVG#parseColors - */ - PShapeSVG.prototype.setOpacity = function(opacity) { - this.strokeColor = parseFloat(opacity) * 255 << 24 | - this.strokeColor & 0xFFFFFF; - this.fillColor = parseFloat(opacity) * 255 << 24 | - this.fillColor & 0xFFFFFF; - }; - /** - * @member PShapeSVG - * PShapeSVG.parseColors() helper function - * - * @param {String} strokeText the value to set stroke to - * - * @see PShapeSVG#parseColors - */ - PShapeSVG.prototype.setStroke = function(strokeText) { - var opacityMask = this.strokeColor & 0xFF000000; - if (strokeText === "none") { - this.stroke = false; - } else if (strokeText.charAt( 0 ) === "#") { - this.stroke = true; - if (strokeText.length === 4) { - // convert #00F to #0000FF - strokeText = strokeText.replace(/#(.)(.)(.)/,"#$1$1$2$2$3$3"); - } - this.strokeColor = opacityMask | - (parseInt( strokeText.substring( 1 ), 16 )) & - 0xFFFFFF; - } else if (strokeText.indexOf( "rgb" ) === 0 ) { - this.stroke = true; - this.strokeColor = opacityMask | this.parseRGB(strokeText); - } else if (strokeText.indexOf( "url(#" ) === 0) { - this.strokeName = strokeText.substring(5, strokeText.length - 1); - } else if (colors[strokeText]) { - this.stroke = true; - this.strokeColor = opacityMask | - (parseInt(colors[strokeText].substring(1), 16)) & - 0xFFFFFF; - } - }; - /** - * @member PShapeSVG - * PShapeSVG.parseColors() helper function - * - * @param {String} weight the value to set strokeWeight to - * - * @see PShapeSVG#parseColors - */ - PShapeSVG.prototype.setStrokeWeight = function(weight) { - this.strokeWeight = this.parseUnitSize(weight); - }; - /** - * @member PShapeSVG - * PShapeSVG.parseColors() helper function - * - * @param {String} linejoin the value to set strokeJoin to - * - * @see PShapeSVG#parseColors - */ - PShapeSVG.prototype.setStrokeJoin = function(linejoin) { - if (linejoin === "miter") { - this.strokeJoin = PConstants.MITER; - - } else if (linejoin === "round") { - this.strokeJoin = PConstants.ROUND; - - } else if (linejoin === "bevel") { - this.strokeJoin = PConstants.BEVEL; - } - }; - /** - * @member PShapeSVG - * PShapeSVG.parseColors() helper function - * - * @param {String} linecap the value to set strokeCap to - * - * @see PShapeSVG#parseColors - */ - PShapeSVG.prototype.setStrokeCap = function (linecap) { - if (linecap === "butt") { - this.strokeCap = PConstants.SQUARE; - - } else if (linecap === "round") { - this.strokeCap = PConstants.ROUND; - - } else if (linecap === "square") { - this.strokeCap = PConstants.PROJECT; - } - }; - /** - * @member PShapeSVG - * PShapeSVG.parseColors() helper function - * - * @param {String} opacityText the value to set stroke opacity to - * - * @see PShapeSVG#parseColors - */ - PShapeSVG.prototype.setStrokeOpacity = function (opacityText) { - this.strokeOpacity = parseFloat(opacityText); - this.strokeColor = this.strokeOpacity * 255 << 24 | - this.strokeColor & - 0xFFFFFF; - }; - /** - * @member PShapeSVG - * The parseRGB() function parses an rbg() color string and returns a color int - * - * @param {String} color the color to parse in rbg() format - * - * @return {int} the equivalent color int - */ - PShapeSVG.prototype.parseRGB = function(color) { - var sub = color.substring(color.indexOf('(') + 1, color.indexOf(')')); - var values = sub.split(", "); - return (values[0] << 16) | (values[1] << 8) | (values[2]); - }; - /** - * @member PShapeSVG - * The parseUnitSize() function parse a size that may have a suffix for its units. - * Ignoring cases where this could also be a percentage. - * The units spec: - *
    - *
  • "1pt" equals "1.25px" (and therefore 1.25 user units) - *
  • "1pc" equals "15px" (and therefore 15 user units) - *
  • "1mm" would be "3.543307px" (3.543307 user units) - *
  • "1cm" equals "35.43307px" (and therefore 35.43307 user units) - *
  • "1in" equals "90px" (and therefore 90 user units) - *
- */ - PShapeSVG.prototype.parseUnitSize = function (text) { - var len = text.length - 2; - if (len < 0) { return text; } - if (text.indexOf("pt") === len) { - return parseFloat(text.substring(0, len)) * 1.25; - } - if (text.indexOf("pc") === len) { - return parseFloat( text.substring( 0, len)) * 15; - } - if (text.indexOf("mm") === len) { - return parseFloat( text.substring(0, len)) * 3.543307; - } - if (text.indexOf("cm") === len) { - return parseFloat(text.substring(0, len)) * 35.43307; - } - if (text.indexOf("in") === len) { - return parseFloat(text.substring(0, len)) * 90; - } - if (text.indexOf("px") === len) { - return parseFloat(text.substring(0, len)); - } - return parseFloat(text); - }; - /** - * The shape() function displays shapes to the screen. - * Processing currently works with SVG shapes only. - * The shape parameter specifies the shape to display and the x - * and y parameters define the location of the shape from its - * upper-left corner. - * The shape is displayed at its original size unless the width - * and height parameters specify a different size. - * The shapeMode() function changes the way the parameters work. - * A call to shapeMode(CORNERS), for example, will change the width - * and height parameters to define the x and y values of the opposite corner - * of the shape. - *

- * Note complex shapes may draw awkwardly with P2D, P3D, and OPENGL. Those - * renderers do not yet support shapes that have holes or complicated breaks. - * - * @param {PShape} shape the shape to display - * @param {int|float} x x-coordinate of the shape - * @param {int|float} y y-coordinate of the shape - * @param {int|float} width width to display the shape - * @param {int|float} height height to display the shape - * - * @see PShape - * @see loadShape() - * @see shapeMode() - */ - p.shape = function(shape, x, y, width, height) { - if (arguments.length >= 1 && arguments[0] !== null) { - if (shape.isVisible()) { - p.pushMatrix(); - if (curShapeMode === PConstants.CENTER) { - if (arguments.length === 5) { - p.translate(x - width/2, y - height/2); - p.scale(width / shape.getWidth(), height / shape.getHeight()); - } else if (arguments.length === 3) { - p.translate(x - shape.getWidth()/2, - shape.getHeight()/2); - } else { - p.translate(-shape.getWidth()/2, -shape.getHeight()/2); - } - } else if (curShapeMode === PConstants.CORNER) { - if (arguments.length === 5) { - p.translate(x, y); - p.scale(width / shape.getWidth(), height / shape.getHeight()); - } else if (arguments.length === 3) { - p.translate(x, y); - } - } else if (curShapeMode === PConstants.CORNERS) { - if (arguments.length === 5) { - width -= x; - height -= y; - p.translate(x, y); - p.scale(width / shape.getWidth(), height / shape.getHeight()); - } else if (arguments.length === 3) { - p.translate(x, y); - } - } - shape.draw(); - if ((arguments.length === 1 && curShapeMode === PConstants.CENTER ) || arguments.length > 1) { - p.popMatrix(); - } - } - } - }; - - /** - * The shapeMode() function modifies the location from which shapes draw. - * The default mode is shapeMode(CORNER), which specifies the - * location to be the upper left corner of the shape and uses the third - * and fourth parameters of shape() to specify the width and height. - * The syntax shapeMode(CORNERS) uses the first and second parameters - * of shape() to set the location of one corner and uses the third - * and fourth parameters to set the opposite corner. - * The syntax shapeMode(CENTER) draws the shape from its center point - * and uses the third and forth parameters of shape() to specify the - * width and height. - * The parameter must be written in "ALL CAPS" because Processing syntax - * is case sensitive. - * - * @param {int} mode One of CORNER, CORNERS, CENTER - * - * @see shape() - * @see rectMode() - */ - p.shapeMode = function (mode) { - curShapeMode = mode; - }; - - /** - * The loadShape() function loads vector shapes into a variable of type PShape. Currently, only SVG files may be loaded. - * In most cases, loadShape() should be used inside setup() because loading shapes inside draw() will reduce the speed of a sketch. - * - * @param {String} filename an SVG file - * - * @return {PShape} a object of type PShape or null - * @see PShape - * @see PApplet#shape() - * @see PApplet#shapeMode() - */ - p.loadShape = function (filename) { - if (arguments.length === 1) { - if (filename.indexOf(".svg") > -1) { - return new PShapeSVG(null, filename); - } - } - return null; - }; - - /** - * XMLAttribute is an attribute of a XML element. This is an internal class - * - * @param {String} fname the full name of the attribute - * @param {String} n the short name of the attribute - * @param {String} namespace the namespace URI of the attribute - * @param {String} v the value of the attribute - * @param {String }t the type of the attribute - * - * @see XMLElement - */ - var XMLAttribute = function(fname, n, nameSpace, v, t){ - this.fullName = fname || ""; - this.name = n || ""; - this.namespace = nameSpace || ""; - this.value = v; - this.type = t; - }; - /** - * XMLAttribute methods - */ - XMLAttribute.prototype = { - /** - * @member XMLAttribute - * The getName() function returns the short name of the attribute - * - * @return {String} the short name of the attribute - */ - getName: function() { - return this.name; - }, - /** - * @member XMLAttribute - * The getFullName() function returns the full name of the attribute - * - * @return {String} the full name of the attribute - */ - getFullName: function() { - return this.fullName; - }, - /** - * @member XMLAttribute - * The getNamespace() function returns the namespace of the attribute - * - * @return {String} the namespace of the attribute - */ - getNamespace: function() { - return this.namespace; - }, - /** - * @member XMLAttribute - * The getValue() function returns the value of the attribute - * - * @return {String} the value of the attribute - */ - getValue: function() { - return this.value; - }, - /** - * @member XMLAttribute - * The getValue() function returns the type of the attribute - * - * @return {String} the type of the attribute - */ - getType: function() { - return this.type; - }, - /** - * @member XMLAttribute - * The setValue() function sets the value of the attribute - * - * @param {String} newval the new value - */ - setValue: function(newval) { - this.value = newval; - } - }; - - /** - * XMLElement is a representation of an XML object. The object is able to parse XML code - * - * @param {PApplet} parent typically use "this" - * @param {String} filename name of the XML/SVG file to load - * @param {String} xml the xml/svg string - * @param {String} fullname the full name of the element - * @param {String} namespace the namespace of the URI - * @param {String} systemID the system ID of the XML data where the element starts - * @param {Integer }lineNr the line in the XML data where the element starts - */ - var XMLElement = p.XMLElement = function() { - this.attributes = []; - this.children = []; - this.fullName = null; - this.name = null; - this.namespace = ""; - this.content = null; - this.parent = null; - this.lineNr = ""; - this.systemID = ""; - this.type = "ELEMENT"; - - if (arguments.length === 4) { - this.fullName = arguments[0] || ""; - if (arguments[1]) { - this.name = arguments[1]; - } else { - var index = this.fullName.indexOf(':'); - if (index >= 0) { - this.name = this.fullName.substring(index + 1); - } else { - this.name = this.fullName; - } - } - this.namespace = arguments[1]; - this.lineNr = arguments[3]; - this.systemID = arguments[2]; - } - else if ((arguments.length === 2 && arguments[1].indexOf(".") > -1) ) { - // filename or svg xml element - this.parse(arguments[arguments.length -1]); - } else if (arguments.length === 1 && typeof arguments[0] === "string"){ - this.parse(arguments[0]); - } - }; - /** - * XMLElement methods - * missing: enumerateAttributeNames(), enumerateChildren(), - * NOTE: parse does not work when a url is passed in - */ - XMLElement.prototype = { - /** - * @member XMLElement - * The parse() function retrieves the file via ajax() and uses DOMParser() - * parseFromString method to make an XML document - * @addon - * - * @param {String} filename name of the XML/SVG file to load - * - * @throws ExceptionType Error loading document - * - * @see XMLElement#parseChildrenRecursive - */ - parse: function(textstring) { - var xmlDoc; - try { - var extension = textstring.substring(textstring.length-4); - if (extension === ".xml" || extension === ".svg") { - textstring = ajax(textstring); - } - xmlDoc = new DOMParser().parseFromString(textstring, "text/xml"); - var elements = xmlDoc.documentElement; - if (elements) { - this.parseChildrenRecursive(null, elements); - } else { - throw ("Error loading document"); - } - return this; - } catch(e) { - throw(e); - } - }, - /** - * @member XMLElement - * Internal helper function for parse(). - * Loops through the - * @addon - * - * @param {XMLElement} parent the parent node - * @param {XML document childNodes} elementpath the remaining nodes that need parsing - * - * @return {XMLElement} the new element and its children elements - */ - parseChildrenRecursive: function (parent , elementpath){ - var xmlelement, - xmlattribute, - tmpattrib, - l, m, - child; - if (!parent) { // this element is the root element - this.fullName = elementpath.localName; - this.name = elementpath.nodeName; - xmlelement = this; - } else { // this element has a parent - xmlelement = new XMLElement(elementpath.localName, elementpath.nodeName, "", ""); - xmlelement.parent = parent; - } - - // if this is a text node, return a PCData element, instead of an XML element. - if(elementpath.nodeType === 3 && elementpath.textContent !== "") { - return this.createPCDataElement(elementpath.textContent); - } - - // bind all attributes - for (l = 0, m = elementpath.attributes.length; l < m; l++) { - tmpattrib = elementpath.attributes[l]; - xmlattribute = new XMLAttribute(tmpattrib.getname, - tmpattrib.nodeName, - tmpattrib.namespaceURI, - tmpattrib.nodeValue, - tmpattrib.nodeType); - xmlelement.attributes.push(xmlattribute); - } - - // bind all children - for (l = 0, m = elementpath.childNodes.length; l < m; l++) { - var node = elementpath.childNodes[l]; - if (node.nodeType === 1 || node.nodeType === 3) { // ELEMENT_NODE or TEXT_NODE - child = xmlelement.parseChildrenRecursive(xmlelement, node); - if (child !== null) { - xmlelement.children.push(child); - } - } - } - - return xmlelement; - }, - /** - * @member XMLElement - * The createElement() function Creates an empty element - * - * @param {String} fullName the full name of the element - * @param {String} namespace the namespace URI - * @param {String} systemID the system ID of the XML data where the element starts - * @param {int} lineNr the line in the XML data where the element starts - */ - createElement: function () { - if (arguments.length === 2) { - return new XMLElement(arguments[0], arguments[1], null, null); - } - return new XMLElement(arguments[0], arguments[1], arguments[2], arguments[3]); - }, - /** - * @member XMLElement - * The createPCDataElement() function creates an element to be used for #PCDATA content. - * Because Processing discards whitespace TEXT nodes, this method will not build an element - * if the passed content is empty after trimming for whitespace. - * - * @return {XMLElement} new "test" XMLElement, or null if content consists only of whitespace - */ - createPCDataElement: function (content) { - if(content.replace(/^\s+$/g,"") === "") { - return null; - } - var pcdata = new XMLElement(); - pcdata.content = content; - pcdata.type = "TEXT"; - return pcdata; - }, - /** - * @member XMLElement - * The hasAttribute() function returns whether an attribute exists - * - * @param {String} name name of the attribute - * @param {String} namespace the namespace URI of the attribute - * - * @return {boolean} true if the attribute exists - */ - hasAttribute: function () { - if (arguments.length === 1) { - return this.getAttribute(arguments[0]) !== null; - } - if (arguments.length === 2) { - return this.getAttribute(arguments[0],arguments[1]) !== null; - } - }, - /** - * @member XMLElement - * The equals() function checks to see if the XMLElement being passed in equals another XMLElement - * - * @param {XMLElement} rawElement the element to compare to - * - * @return {boolean} true if the element equals another element - */ - equals: function(other) { - if (!(other instanceof XMLElement)) { - return false; - } - var i, j; - if (this.name !== other.getLocalName()) { return false; } - if (this.attributes.length !== other.getAttributeCount()) { return false; } - // attributes may be ordered differently - if (this.attributes.length !== other.attributes.length) { return false; } - var attr_name, attr_ns, attr_value, attr_type, attr_other; - for (i = 0, j = this.attributes.length; i < j; i++) { - attr_name = this.attributes[i].getName(); - attr_ns = this.attributes[i].getNamespace(); - attr_other = other.findAttribute(attr_name, attr_ns); - if (attr_other === null) { return false; } - if (this.attributes[i].getValue() !== attr_other.getValue()) { return false; } - if (this.attributes[i].getType() !== attr_other.getType()) { return false; } - } - // children must be ordered identically - if (this.children.length !== other.getChildCount()) { return false; } - if (this.children.length>0) { - var child1, child2; - for (i = 0, j = this.children.length; i < j; i++) { - child1 = this.getChild(i); - child2 = other.getChild(i); - if (!child1.equals(child2)) { return false; } - } - return true; - } - return (this.content === other.content); - }, - /** - * @member XMLElement - * The getContent() function returns the content of an element. If there is no such content, null is returned - * - * @return {String} the (possibly null) content - */ - getContent: function(){ - if (this.type === "TEXT") { - return this.content; - } - var children = this.children; - if (children.length === 1 && children[0].type === "TEXT") { - return children[0].content; - } - return null; - }, - /** - * @member XMLElement - * The getAttribute() function returns the value of an attribute - * - * @param {String} name the non-null full name of the attribute - * @param {String} namespace the namespace URI, which may be null - * @param {String} defaultValue the default value of the attribute - * - * @return {String} the value, or defaultValue if the attribute does not exist - */ - getAttribute: function (){ - var attribute; - if( arguments.length === 2 ){ - attribute = this.findAttribute(arguments[0]); - if (attribute) { - return attribute.getValue(); - } - return arguments[1]; - } else if (arguments.length === 1) { - attribute = this.findAttribute(arguments[0]); - if (attribute) { - return attribute.getValue(); - } - return null; - } else if (arguments.length === 3) { - attribute = this.findAttribute(arguments[0],arguments[1]); - if (attribute) { - return attribute.getValue(); - } - return arguments[2]; - } - }, - /** - * @member XMLElement - * The getStringAttribute() function returns the string attribute of the element - * If the defaultValue parameter is used and the attribute doesn't exist, the defaultValue value is returned. - * When calling the function without the defaultValue parameter, if the attribute doesn't exist, the value 0 is returned. - * - * @param name the name of the attribute - * @param defaultValue value returned if the attribute is not found - * - * @return {String} the value, or defaultValue if the attribute does not exist - */ - getStringAttribute: function() { - if (arguments.length === 1) { - return this.getAttribute(arguments[0]); - } - if (arguments.length === 2){ - return this.getAttribute(arguments[0], arguments[1]); - } - return this.getAttribute(arguments[0], arguments[1],arguments[2]); - }, - /** - * Processing 1.5 XML API wrapper for the generic String - * attribute getter. This may only take one argument. - */ - getString: function(attributeName) { - return this.getStringAttribute(attributeName); - }, - /** - * @member XMLElement - * The getFloatAttribute() function returns the float attribute of the element. - * If the defaultValue parameter is used and the attribute doesn't exist, the defaultValue value is returned. - * When calling the function without the defaultValue parameter, if the attribute doesn't exist, the value 0 is returned. - * - * @param name the name of the attribute - * @param defaultValue value returned if the attribute is not found - * - * @return {float} the value, or defaultValue if the attribute does not exist - */ - getFloatAttribute: function() { - if (arguments.length === 1 ) { - return parseFloat(this.getAttribute(arguments[0], 0)); - } - if (arguments.length === 2 ){ - return this.getAttribute(arguments[0], arguments[1]); - } - return this.getAttribute(arguments[0], arguments[1],arguments[2]); - }, - /** - * Processing 1.5 XML API wrapper for the generic float - * attribute getter. This may only take one argument. - */ - getFloat: function(attributeName) { - return this.getFloatAttribute(attributeName); - }, - /** - * @member XMLElement - * The getIntAttribute() function returns the integer attribute of the element. - * If the defaultValue parameter is used and the attribute doesn't exist, the defaultValue value is returned. - * When calling the function without the defaultValue parameter, if the attribute doesn't exist, the value 0 is returned. - * - * @param name the name of the attribute - * @param defaultValue value returned if the attribute is not found - * - * @return {int} the value, or defaultValue if the attribute does not exist - */ - getIntAttribute: function () { - if (arguments.length === 1) { - return this.getAttribute( arguments[0], 0 ); - } - if (arguments.length === 2) { - return this.getAttribute(arguments[0], arguments[1]); - } - return this.getAttribute(arguments[0], arguments[1],arguments[2]); - }, - /** - * Processing 1.5 XML API wrapper for the generic int - * attribute getter. This may only take one argument. - */ - getInt: function(attributeName) { - return this.getIntAttribute(attributeName); - }, - /** - * @member XMLElement - * The hasChildren() function returns whether the element has children. - * - * @return {boolean} true if the element has children. - */ - hasChildren: function () { - return this.children.length > 0 ; - }, - /** - * @member XMLElement - * The addChild() function adds a child element - * - * @param {XMLElement} child the non-null child to add. - */ - addChild: function (child) { - if (child !== null) { - child.parent = this; - this.children.push(child); - } - }, - /** - * @member XMLElement - * The insertChild() function inserts a child element at the index provided - * - * @param {XMLElement} child the non-null child to add. - * @param {int} index where to put the child. - */ - insertChild: function (child, index) { - if (child) { - if ((child.getLocalName() === null) && (! this.hasChildren())) { - var lastChild = this.children[this.children.length -1]; - if (lastChild.getLocalName() === null) { - lastChild.setContent(lastChild.getContent() + child.getContent()); - return; - } - } - child.parent = this; - this.children.splice(index,0,child); - } - }, - /** - * @member XMLElement - * The getChild() returns the child XMLElement as specified by the index parameter. - * The value of the index parameter must be less than the total number of children to avoid going out of the array storing the child elements. - * When the path parameter is specified, then it will return all children that match that path. The path is a series of elements and sub-elements, separated by slashes. - * - * @param {int} index where to put the child. - * @param {String} path path to a particular element - * - * @return {XMLElement} the element - */ - getChild: function (){ - if (typeof arguments[0] === "number") { - return this.children[arguments[0]]; - } - if (arguments[0].indexOf('/') !== -1) { // path was given - this.getChildRecursive(arguments[0].split("/"), 0); - return null; - } - var kid, kidName; - for (var i = 0, j = this.getChildCount(); i < j; i++) { - kid = this.getChild(i); - kidName = kid.getName(); - if (kidName !== null && kidName === arguments[0]) { - return kid; - } - } - return null; - }, - /** - * @member XMLElement - * The getChildren() returns all of the children as an XMLElement array. - * When the path parameter is specified, then it will return all children that match that path. - * The path is a series of elements and sub-elements, separated by slashes. - * - * @param {String} path element name or path/to/element - * - * @return {XMLElement} array of child elements that match - * - * @see XMLElement#getChildCount() - * @see XMLElement#getChild() - */ - getChildren: function(){ - if (arguments.length === 1) { - if (typeof arguments[0] === "number") { - return this.getChild( arguments[0]); - } - if (arguments[0].indexOf('/') !== -1) { // path was given - return this.getChildrenRecursive( arguments[0].split("/"), 0); - } - var matches = []; - var kid, kidName; - for (var i = 0, j = this.getChildCount(); i < j; i++) { - kid = this.getChild(i); - kidName = kid.getName(); - if (kidName !== null && kidName === arguments[0]) { - matches.push(kid); - } - } - return matches; - } - return this.children; - }, - /** - * @member XMLElement - * The getChildCount() returns the number of children for the element. - * - * @return {int} the count - * - * @see XMLElement#getChild() - * @see XMLElement#getChildren() - */ - getChildCount: function(){ - return this.children.length; - }, - /** - * @member XMLElement - * Internal helper function for getChild(). - * - * @param {String[]} items result of splitting the query on slashes - * @param {int} offset where in the items[] array we're currently looking - * - * @return {XMLElement} matching element or null if no match - */ - getChildRecursive: function (items, offset) { - var kid, kidName; - for(var i = 0, j = this.getChildCount(); i < j; i++) { - kid = this.getChild(i); - kidName = kid.getName(); - if (kidName !== null && kidName === items[offset]) { - if (offset === items.length-1) { - return kid; - } - offset += 1; - return kid.getChildRecursive(items, offset); - } - } - return null; - }, - /** - * @member XMLElement - * Internal helper function for getChildren(). - * - * @param {String[]} items result of splitting the query on slashes - * @param {int} offset where in the items[] array we're currently looking - * - * @return {XMLElement[]} matching elements or empty array if no match - */ - getChildrenRecursive: function (items, offset) { - if (offset === items.length-1) { - return this.getChildren(items[offset]); - } - var matches = this.getChildren(items[offset]); - var kidMatches = []; - for (var i = 0; i < matches.length; i++) { - kidMatches = kidMatches.concat(matches[i].getChildrenRecursive(items, offset+1)); - } - return kidMatches; - }, - /** - * @member XMLElement - * The isLeaf() function returns whether the element is a leaf element. - * - * @return {boolean} true if the element has no children. - */ - isLeaf: function(){ - return !this.hasChildren(); - }, - /** - * @member XMLElement - * The listChildren() function put the names of all children into an array. Same as looping through - * each child and calling getName() on each XMLElement. - * - * @return {String[]} a list of element names. - */ - listChildren: function() { - var arr = []; - for (var i = 0, j = this.children.length; i < j; i++) { - arr.push( this.getChild(i).getName()); - } - return arr; - }, - /** - * @member XMLElement - * The removeAttribute() function removes an attribute - * - * @param {String} name the non-null name of the attribute. - * @param {String} namespace the namespace URI of the attribute, which may be null. - */ - removeAttribute: function (name , namespace) { - this.namespace = namespace || ""; - for (var i = 0, j = this.attributes.length; i < j; i++) { - if (this.attributes[i].getName() === name && this.attributes[i].getNamespace() === this.namespace) { - this.attributes.splice(i, 1); - break; - } - } - }, - /** - * @member XMLElement - * The removeChild() removes a child element. - * - * @param {XMLElement} child the the non-null child to be renoved - */ - removeChild: function(child) { - if (child) { - for (var i = 0, j = this.children.length; i < j; i++) { - if (this.children[i].equals(child)) { - this.children.splice(i, 1); - break; - } - } - } - }, - /** - * @member XMLElement - * The removeChildAtIndex() removes the child located at a certain index - * - * @param {int} index the index of the child, where the first child has index 0 - */ - removeChildAtIndex: function(index) { - if (this.children.length > index) { //make sure its not outofbounds - this.children.splice(index, 1); - } - }, - /** - * @member XMLElement - * The findAttribute() function searches an attribute - * - * @param {String} name fullName the non-null full name of the attribute - * @param {String} namespace the name space, which may be null - * - * @return {XMLAttribute} the attribute, or null if the attribute does not exist. - */ - findAttribute: function (name, namespace) { - this.namespace = namespace || ""; - for (var i = 0, j = this.attributes.length; i < j; i++) { - if (this.attributes[i].getName() === name && this.attributes[i].getNamespace() === this.namespace) { - return this.attributes[i]; - } - } - return null; - }, - /** - * @member XMLElement - * The setAttribute() function sets an attribute. - * - * @param {String} name the non-null full name of the attribute - * @param {String} namespace the non-null value of the attribute - */ - setAttribute: function() { - var attr; - if (arguments.length === 3) { - var index = arguments[0].indexOf(':'); - var name = arguments[0].substring(index + 1); - attr = this.findAttribute(name, arguments[1]); - if (attr) { - attr.setValue(arguments[2]); - } else { - attr = new XMLAttribute(arguments[0], name, arguments[1], arguments[2], "CDATA"); - this.attributes.push(attr); - } - } else { - attr = this.findAttribute(arguments[0]); - if (attr) { - attr.setValue(arguments[1]); - } else { - attr = new XMLAttribute(arguments[0], arguments[0], null, arguments[1], "CDATA"); - this.attributes.push(attr); - } - } - }, - /** - * Processing 1.5 XML API wrapper for the generic String - * attribute setter. This must take two arguments. - */ - setString: function(attribute, value) { - this.setAttribute(attribute, value); - }, - /** - * Processing 1.5 XML API wrapper for the generic int - * attribute setter. This must take two arguments. - */ - setInt: function(attribute, value) { - this.setAttribute(attribute, value); - }, - /** - * Processing 1.5 XML API wrapper for the generic float - * attribute setter. This must take two arguments. - */ - setFloat: function(attribute, value) { - this.setAttribute(attribute, value); - }, - /** - * @member XMLElement - * The setContent() function sets the #PCDATA content. It is an error to call this method with a - * non-null value if there are child objects. - * - * @param {String} content the (possibly null) content - */ - setContent: function(content) { - if (this.children.length>0) { - Processing.debug("Tried to set content for XMLElement with children"); } - this.content = content; - }, - /** - * @member XMLElement - * The setName() function sets the full name. This method also sets the short name and clears the - * namespace URI. - * - * @param {String} name the non-null name - * @param {String} namespace the namespace URI, which may be null. - */ - setName: function() { - if (arguments.length === 1) { - this.name = arguments[0]; - this.fullName = arguments[0]; - this.namespace = null; - } else { - var index = arguments[0].indexOf(':'); - if ((arguments[1] === null) || (index < 0)) { - this.name = arguments[0]; - } else { - this.name = arguments[0].substring(index + 1); - } - this.fullName = arguments[0]; - this.namespace = arguments[1]; - } - }, - /** - * @member XMLElement - * The getName() function returns the full name (i.e. the name including an eventual namespace - * prefix) of the element. - * - * @return {String} the name, or null if the element only contains #PCDATA. - */ - getName: function() { - return this.fullName; - }, - /** - * @member XMLElement - * The getLocalName() function returns the local name (i.e. the name excluding an eventual namespace - * prefix) of the element. - * - * @return {String} the name, or null if the element only contains #PCDATA. - */ - getLocalName: function() { - return this.name; - }, - /** - * @member XMLElement - * The getAttributeCount() function returns the number of attributes for the node - * that this XMLElement represents. - * - * @return {int} the number of attributes in this XMLElement - */ - getAttributeCount: function() { - return this.attributes.length; - }, - /** - * @member XMLElement - * The toString() function returns the XML definition of an XMLElement. - * - * @return {String} the XML definition of this XMLElement - */ - toString: function() { - // shortcut for text nodes - if(this.type==="TEXT") { return this.content; } - - // real XMLElements - var tagstring = (this.namespace !== "" && this.namespace !== this.name ? this.namespace + ":" : "") + this.name; - var xmlstring = "<" + tagstring; - var a,c; - - // serialize the attributes to XML string - for (a = 0; a"; - } - } else { - xmlstring += ">"; - for (c = 0; c"; - } - return xmlstring; - } - }; - - /** - * static Processing 1.5 XML API wrapper for the - * parse method. This may only take one argument. - */ - XMLElement.parse = function(xmlstring) { - var element = new XMLElement(); - element.parse(xmlstring); - return element; - }; - - //////////////////////////////////////////////////////////////////////////// - // 2D Matrix - //////////////////////////////////////////////////////////////////////////// - /** - * Helper function for printMatrix(). Finds the largest scalar - * in the matrix, then number of digits left of the decimal. - * Call from PMatrix2D and PMatrix3D's print() function. - */ - var printMatrixHelper = function(elements) { - var big = 0; - for (var i = 0; i < elements.length; i++) { - if (i !== 0) { - big = Math.max(big, Math.abs(elements[i])); - } else { - big = Math.abs(elements[i]); - } - } - - var digits = (big + "").indexOf("."); - if (digits === 0) { - digits = 1; - } else if (digits === -1) { - digits = (big + "").length; - } - - return digits; - }; - /** - * PMatrix2D is a 3x2 affine matrix implementation. The constructor accepts another PMatrix2D or a list of six float elements. - * If no parameters are provided the matrix is set to the identity matrix. - * - * @param {PMatrix2D} matrix the initial matrix to set to - * @param {float} m00 the first element of the matrix - * @param {float} m01 the second element of the matrix - * @param {float} m02 the third element of the matrix - * @param {float} m10 the fourth element of the matrix - * @param {float} m11 the fifth element of the matrix - * @param {float} m12 the sixth element of the matrix - */ - var PMatrix2D = p.PMatrix2D = function() { - if (arguments.length === 0) { - this.reset(); - } else if (arguments.length === 1 && arguments[0] instanceof PMatrix2D) { - this.set(arguments[0].array()); - } else if (arguments.length === 6) { - this.set(arguments[0], arguments[1], arguments[2], arguments[3], arguments[4], arguments[5]); - } - }; - /** - * PMatrix2D methods - */ - PMatrix2D.prototype = { - /** - * @member PMatrix2D - * The set() function sets the matrix elements. The function accepts either another PMatrix2D, an array of elements, or a list of six floats. - * - * @param {PMatrix2D} matrix the matrix to set this matrix to - * @param {float[]} elements an array of elements to set this matrix to - * @param {float} m00 the first element of the matrix - * @param {float} m01 the third element of the matrix - * @param {float} m10 the fourth element of the matrix - * @param {float} m11 the fith element of the matrix - * @param {float} m12 the sixth element of the matrix - */ - set: function() { - if (arguments.length === 6) { - var a = arguments; - this.set([a[0], a[1], a[2], - a[3], a[4], a[5]]); - } else if (arguments.length === 1 && arguments[0] instanceof PMatrix2D) { - this.elements = arguments[0].array(); - } else if (arguments.length === 1 && arguments[0] instanceof Array) { - this.elements = arguments[0].slice(); - } - }, - /** - * @member PMatrix2D - * The get() function returns a copy of this PMatrix2D. - * - * @return {PMatrix2D} a copy of this PMatrix2D - */ - get: function() { - var outgoing = new PMatrix2D(); - outgoing.set(this.elements); - return outgoing; - }, - /** - * @member PMatrix2D - * The reset() function sets this PMatrix2D to the identity matrix. - */ - reset: function() { - this.set([1, 0, 0, 0, 1, 0]); - }, - /** - * @member PMatrix2D - * The array() function returns a copy of the element values. - * @addon - * - * @return {float[]} returns a copy of the element values - */ - array: function array() { - return this.elements.slice(); - }, - /** - * @member PMatrix2D - * The translate() function translates this matrix by moving the current coordinates to the location specified by tx and ty. - * - * @param {float} tx the x-axis coordinate to move to - * @param {float} ty the y-axis coordinate to move to - */ - translate: function(tx, ty) { - this.elements[2] = tx * this.elements[0] + ty * this.elements[1] + this.elements[2]; - this.elements[5] = tx * this.elements[3] + ty * this.elements[4] + this.elements[5]; - }, - /** - * @member PMatrix2D - * The invTranslate() function translates this matrix by moving the current coordinates to the negative location specified by tx and ty. - * - * @param {float} tx the x-axis coordinate to move to - * @param {float} ty the y-axis coordinate to move to - */ - invTranslate: function(tx, ty) { - this.translate(-tx, -ty); - }, - /** - * @member PMatrix2D - * The transpose() function is not used in processingjs. - */ - transpose: function() { - // Does nothing in Processing. - }, - /** - * @member PMatrix2D - * The mult() function multiplied this matrix. - * If two array elements are passed in the function will multiply a two element vector against this matrix. - * If target is null or not length four, a new float array will be returned. - * The values for vec and target can be the same (though that's less efficient). - * If two PVectors are passed in the function multiply the x and y coordinates of a PVector against this matrix. - * - * @param {PVector} source, target the PVectors used to multiply this matrix - * @param {float[]} source, target the arrays used to multiply this matrix - * - * @return {PVector|float[]} returns a PVector or an array representing the new matrix - */ - mult: function(source, target) { - var x, y; - if (source instanceof PVector) { - x = source.x; - y = source.y; - if (!target) { - target = new PVector(); - } - } else if (source instanceof Array) { - x = source[0]; - y = source[1]; - if (!target) { - target = []; - } - } - if (target instanceof Array) { - target[0] = this.elements[0] * x + this.elements[1] * y + this.elements[2]; - target[1] = this.elements[3] * x + this.elements[4] * y + this.elements[5]; - } else if (target instanceof PVector) { - target.x = this.elements[0] * x + this.elements[1] * y + this.elements[2]; - target.y = this.elements[3] * x + this.elements[4] * y + this.elements[5]; - target.z = 0; - } - return target; - }, - /** - * @member PMatrix2D - * The multX() function calculates the x component of a vector from a transformation. - * - * @param {float} x the x component of the vector being transformed - * @param {float} y the y component of the vector being transformed - * - * @return {float} returnes the result of the calculation - */ - multX: function(x, y) { - return (x * this.elements[0] + y * this.elements[1] + this.elements[2]); - }, - /** - * @member PMatrix2D - * The multY() function calculates the y component of a vector from a transformation. - * - * @param {float} x the x component of the vector being transformed - * @param {float} y the y component of the vector being transformed - * - * @return {float} returnes the result of the calculation - */ - multY: function(x, y) { - return (x * this.elements[3] + y * this.elements[4] + this.elements[5]); - }, - /** - * @member PMatrix2D - * The skewX() function skews the matrix along the x-axis the amount specified by the angle parameter. - * Angles should be specified in radians (values from 0 to PI*2) or converted to radians with the radians() function. - * - * @param {float} angle angle of skew specified in radians - */ - skewX: function(angle) { - this.apply(1, 0, 1, angle, 0, 0); - }, - /** - * @member PMatrix2D - * The skewY() function skews the matrix along the y-axis the amount specified by the angle parameter. - * Angles should be specified in radians (values from 0 to PI*2) or converted to radians with the radians() function. - * - * @param {float} angle angle of skew specified in radians - */ - skewY: function(angle) { - this.apply(1, 0, 1, 0, angle, 0); - }, - /** - * @member PMatrix2D - * The determinant() function calvculates the determinant of this matrix. - * - * @return {float} the determinant of the matrix - */ - determinant: function() { - return (this.elements[0] * this.elements[4] - this.elements[1] * this.elements[3]); - }, - /** - * @member PMatrix2D - * The invert() function inverts this matrix - * - * @return {boolean} true if successful - */ - invert: function() { - var d = this.determinant(); - if (Math.abs( d ) > PConstants.MIN_INT) { - var old00 = this.elements[0]; - var old01 = this.elements[1]; - var old02 = this.elements[2]; - var old10 = this.elements[3]; - var old11 = this.elements[4]; - var old12 = this.elements[5]; - this.elements[0] = old11 / d; - this.elements[3] = -old10 / d; - this.elements[1] = -old01 / d; - this.elements[4] = old00 / d; - this.elements[2] = (old01 * old12 - old11 * old02) / d; - this.elements[5] = (old10 * old02 - old00 * old12) / d; - return true; - } - return false; - }, - /** - * @member PMatrix2D - * The scale() function increases or decreases the size of a shape by expanding and contracting vertices. When only one parameter is specified scale will occur in all dimensions. - * This is equivalent to a two parameter call. - * - * @param {float} sx the amount to scale on the x-axis - * @param {float} sy the amount to scale on the y-axis - */ - scale: function(sx, sy) { - if (sx && !sy) { - sy = sx; - } - if (sx && sy) { - this.elements[0] *= sx; - this.elements[1] *= sy; - this.elements[3] *= sx; - this.elements[4] *= sy; - } - }, - /** - * @member PMatrix2D - * The invScale() function decreases or increases the size of a shape by contracting and expanding vertices. When only one parameter is specified scale will occur in all dimensions. - * This is equivalent to a two parameter call. - * - * @param {float} sx the amount to scale on the x-axis - * @param {float} sy the amount to scale on the y-axis - */ - invScale: function(sx, sy) { - if (sx && !sy) { - sy = sx; - } - this.scale(1 / sx, 1 / sy); - }, - /** - * @member PMatrix2D - * The apply() function multiplies the current matrix by the one specified through the parameters. Note that either a PMatrix2D or a list of floats can be passed in. - * - * @param {PMatrix2D} matrix the matrix to apply this matrix to - * @param {float} m00 the first element of the matrix - * @param {float} m01 the third element of the matrix - * @param {float} m10 the fourth element of the matrix - * @param {float} m11 the fith element of the matrix - * @param {float} m12 the sixth element of the matrix - */ - apply: function() { - var source; - if (arguments.length === 1 && arguments[0] instanceof PMatrix2D) { - source = arguments[0].array(); - } else if (arguments.length === 6) { - source = Array.prototype.slice.call(arguments); - } else if (arguments.length === 1 && arguments[0] instanceof Array) { - source = arguments[0]; - } - - var result = [0, 0, this.elements[2], - 0, 0, this.elements[5]]; - var e = 0; - for (var row = 0; row < 2; row++) { - for (var col = 0; col < 3; col++, e++) { - result[e] += this.elements[row * 3 + 0] * source[col + 0] + - this.elements[row * 3 + 1] * source[col + 3]; - } - } - this.elements = result.slice(); - }, - /** - * @member PMatrix2D - * The preApply() function applies another matrix to the left of this one. Note that either a PMatrix2D or elements of a matrix can be passed in. - * - * @param {PMatrix2D} matrix the matrix to apply this matrix to - * @param {float} m00 the first element of the matrix - * @param {float} m01 the third element of the matrix - * @param {float} m10 the fourth element of the matrix - * @param {float} m11 the fith element of the matrix - * @param {float} m12 the sixth element of the matrix - */ - preApply: function() { - var source; - if (arguments.length === 1 && arguments[0] instanceof PMatrix2D) { - source = arguments[0].array(); - } else if (arguments.length === 6) { - source = Array.prototype.slice.call(arguments); - } else if (arguments.length === 1 && arguments[0] instanceof Array) { - source = arguments[0]; - } - var result = [0, 0, source[2], - 0, 0, source[5]]; - result[2] = source[2] + this.elements[2] * source[0] + this.elements[5] * source[1]; - result[5] = source[5] + this.elements[2] * source[3] + this.elements[5] * source[4]; - result[0] = this.elements[0] * source[0] + this.elements[3] * source[1]; - result[3] = this.elements[0] * source[3] + this.elements[3] * source[4]; - result[1] = this.elements[1] * source[0] + this.elements[4] * source[1]; - result[4] = this.elements[1] * source[3] + this.elements[4] * source[4]; - this.elements = result.slice(); - }, - /** - * @member PMatrix2D - * The rotate() function rotates the matrix. - * - * @param {float} angle the angle of rotation in radiants - */ - rotate: function(angle) { - var c = Math.cos(angle); - var s = Math.sin(angle); - var temp1 = this.elements[0]; - var temp2 = this.elements[1]; - this.elements[0] = c * temp1 + s * temp2; - this.elements[1] = -s * temp1 + c * temp2; - temp1 = this.elements[3]; - temp2 = this.elements[4]; - this.elements[3] = c * temp1 + s * temp2; - this.elements[4] = -s * temp1 + c * temp2; - }, - /** - * @member PMatrix2D - * The rotateZ() function rotates the matrix. - * - * @param {float} angle the angle of rotation in radiants - */ - rotateZ: function(angle) { - this.rotate(angle); - }, - /** - * @member PMatrix2D - * The invRotateZ() function rotates the matrix in opposite direction. - * - * @param {float} angle the angle of rotation in radiants - */ - invRotateZ: function(angle) { - this.rotateZ(angle - Math.PI); - }, - /** - * @member PMatrix2D - * The print() function prints out the elements of this matrix - */ - print: function() { - var digits = printMatrixHelper(this.elements); - var output = "" + p.nfs(this.elements[0], digits, 4) + " " + - p.nfs(this.elements[1], digits, 4) + " " + - p.nfs(this.elements[2], digits, 4) + "\n" + - p.nfs(this.elements[3], digits, 4) + " " + - p.nfs(this.elements[4], digits, 4) + " " + - p.nfs(this.elements[5], digits, 4) + "\n\n"; - p.println(output); - } - }; - - /** - * PMatrix3D is a 4x4 matrix implementation. The constructor accepts another PMatrix3D or a list of six or sixteen float elements. - * If no parameters are provided the matrix is set to the identity matrix. - */ - var PMatrix3D = p.PMatrix3D = function() { - // When a matrix is created, it is set to an identity matrix - this.reset(); - }; - /** - * PMatrix3D methods - */ - PMatrix3D.prototype = { - /** - * @member PMatrix2D - * The set() function sets the matrix elements. The function accepts either another PMatrix3D, an array of elements, or a list of six or sixteen floats. - * - * @param {PMatrix3D} matrix the initial matrix to set to - * @param {float[]} elements an array of elements to set this matrix to - * @param {float} m00 the first element of the matrix - * @param {float} m01 the second element of the matrix - * @param {float} m02 the third element of the matrix - * @param {float} m03 the fourth element of the matrix - * @param {float} m10 the fifth element of the matrix - * @param {float} m11 the sixth element of the matrix - * @param {float} m12 the seventh element of the matrix - * @param {float} m13 the eight element of the matrix - * @param {float} m20 the nineth element of the matrix - * @param {float} m21 the tenth element of the matrix - * @param {float} m22 the eleventh element of the matrix - * @param {float} m23 the twelveth element of the matrix - * @param {float} m30 the thirteenth element of the matrix - * @param {float} m31 the fourtheenth element of the matrix - * @param {float} m32 the fivetheenth element of the matrix - * @param {float} m33 the sixteenth element of the matrix - */ - set: function() { - if (arguments.length === 16) { - this.elements = Array.prototype.slice.call(arguments); - } else if (arguments.length === 1 && arguments[0] instanceof PMatrix3D) { - this.elements = arguments[0].array(); - } else if (arguments.length === 1 && arguments[0] instanceof Array) { - this.elements = arguments[0].slice(); - } - }, - /** - * @member PMatrix3D - * The get() function returns a copy of this PMatrix3D. - * - * @return {PMatrix3D} a copy of this PMatrix3D - */ - get: function() { - var outgoing = new PMatrix3D(); - outgoing.set(this.elements); - return outgoing; - }, - /** - * @member PMatrix3D - * The reset() function sets this PMatrix3D to the identity matrix. - */ - reset: function() { - this.elements = [1,0,0,0, - 0,1,0,0, - 0,0,1,0, - 0,0,0,1]; - }, - /** - * @member PMatrix3D - * The array() function returns a copy of the element values. - * @addon - * - * @return {float[]} returns a copy of the element values - */ - array: function array() { - return this.elements.slice(); - }, - /** - * @member PMatrix3D - * The translate() function translates this matrix by moving the current coordinates to the location specified by tx, ty, and tz. - * - * @param {float} tx the x-axis coordinate to move to - * @param {float} ty the y-axis coordinate to move to - * @param {float} tz the z-axis coordinate to move to - */ - translate: function(tx, ty, tz) { - if (tz === undef) { - tz = 0; - } - - this.elements[3] += tx * this.elements[0] + ty * this.elements[1] + tz * this.elements[2]; - this.elements[7] += tx * this.elements[4] + ty * this.elements[5] + tz * this.elements[6]; - this.elements[11] += tx * this.elements[8] + ty * this.elements[9] + tz * this.elements[10]; - this.elements[15] += tx * this.elements[12] + ty * this.elements[13] + tz * this.elements[14]; - }, - /** - * @member PMatrix3D - * The transpose() function transpose this matrix. - */ - transpose: function() { - var temp = this.elements[4]; - this.elements[4] = this.elements[1]; - this.elements[1] = temp; - - temp = this.elements[8]; - this.elements[8] = this.elements[2]; - this.elements[2] = temp; - - temp = this.elements[6]; - this.elements[6] = this.elements[9]; - this.elements[9] = temp; - - temp = this.elements[3]; - this.elements[3] = this.elements[12]; - this.elements[12] = temp; - - temp = this.elements[7]; - this.elements[7] = this.elements[13]; - this.elements[13] = temp; - - temp = this.elements[11]; - this.elements[11] = this.elements[14]; - this.elements[14] = temp; - }, - /** - * @member PMatrix3D - * The mult() function multiplied this matrix. - * If two array elements are passed in the function will multiply a two element vector against this matrix. - * If target is null or not length four, a new float array will be returned. - * The values for vec and target can be the same (though that's less efficient). - * If two PVectors are passed in the function multiply the x and y coordinates of a PVector against this matrix. - * - * @param {PVector} source, target the PVectors used to multiply this matrix - * @param {float[]} source, target the arrays used to multiply this matrix - * - * @return {PVector|float[]} returns a PVector or an array representing the new matrix - */ - mult: function(source, target) { - var x, y, z, w; - if (source instanceof PVector) { - x = source.x; - y = source.y; - z = source.z; - w = 1; - if (!target) { - target = new PVector(); - } - } else if (source instanceof Array) { - x = source[0]; - y = source[1]; - z = source[2]; - w = source[3] || 1; - - if ( !target || (target.length !== 3 && target.length !== 4) ) { - target = [0, 0, 0]; - } - } - - if (target instanceof Array) { - if (target.length === 3) { - target[0] = this.elements[0] * x + this.elements[1] * y + this.elements[2] * z + this.elements[3]; - target[1] = this.elements[4] * x + this.elements[5] * y + this.elements[6] * z + this.elements[7]; - target[2] = this.elements[8] * x + this.elements[9] * y + this.elements[10] * z + this.elements[11]; - } else if (target.length === 4) { - target[0] = this.elements[0] * x + this.elements[1] * y + this.elements[2] * z + this.elements[3] * w; - target[1] = this.elements[4] * x + this.elements[5] * y + this.elements[6] * z + this.elements[7] * w; - target[2] = this.elements[8] * x + this.elements[9] * y + this.elements[10] * z + this.elements[11] * w; - target[3] = this.elements[12] * x + this.elements[13] * y + this.elements[14] * z + this.elements[15] * w; - } - } - if (target instanceof PVector) { - target.x = this.elements[0] * x + this.elements[1] * y + this.elements[2] * z + this.elements[3]; - target.y = this.elements[4] * x + this.elements[5] * y + this.elements[6] * z + this.elements[7]; - target.z = this.elements[8] * x + this.elements[9] * y + this.elements[10] * z + this.elements[11]; - } - return target; - }, - /** - * @member PMatrix3D - * The preApply() function applies another matrix to the left of this one. Note that either a PMatrix3D or elements of a matrix can be passed in. - * - * @param {PMatrix3D} matrix the matrix to apply this matrix to - * @param {float} m00 the first element of the matrix - * @param {float} m01 the second element of the matrix - * @param {float} m02 the third element of the matrix - * @param {float} m03 the fourth element of the matrix - * @param {float} m10 the fifth element of the matrix - * @param {float} m11 the sixth element of the matrix - * @param {float} m12 the seventh element of the matrix - * @param {float} m13 the eight element of the matrix - * @param {float} m20 the nineth element of the matrix - * @param {float} m21 the tenth element of the matrix - * @param {float} m22 the eleventh element of the matrix - * @param {float} m23 the twelveth element of the matrix - * @param {float} m30 the thirteenth element of the matrix - * @param {float} m31 the fourtheenth element of the matrix - * @param {float} m32 the fivetheenth element of the matrix - * @param {float} m33 the sixteenth element of the matrix - */ - preApply: function() { - var source; - if (arguments.length === 1 && arguments[0] instanceof PMatrix3D) { - source = arguments[0].array(); - } else if (arguments.length === 16) { - source = Array.prototype.slice.call(arguments); - } else if (arguments.length === 1 && arguments[0] instanceof Array) { - source = arguments[0]; - } - - var result = [0, 0, 0, 0, - 0, 0, 0, 0, - 0, 0, 0, 0, - 0, 0, 0, 0]; - var e = 0; - for (var row = 0; row < 4; row++) { - for (var col = 0; col < 4; col++, e++) { - result[e] += this.elements[col + 0] * source[row * 4 + 0] + this.elements[col + 4] * - source[row * 4 + 1] + this.elements[col + 8] * source[row * 4 + 2] + - this.elements[col + 12] * source[row * 4 + 3]; - } - } - this.elements = result.slice(); - }, - /** - * @member PMatrix3D - * The apply() function multiplies the current matrix by the one specified through the parameters. Note that either a PMatrix3D or a list of floats can be passed in. - * - * @param {PMatrix3D} matrix the matrix to apply this matrix to - * @param {float} m00 the first element of the matrix - * @param {float} m01 the second element of the matrix - * @param {float} m02 the third element of the matrix - * @param {float} m03 the fourth element of the matrix - * @param {float} m10 the fifth element of the matrix - * @param {float} m11 the sixth element of the matrix - * @param {float} m12 the seventh element of the matrix - * @param {float} m13 the eight element of the matrix - * @param {float} m20 the nineth element of the matrix - * @param {float} m21 the tenth element of the matrix - * @param {float} m22 the eleventh element of the matrix - * @param {float} m23 the twelveth element of the matrix - * @param {float} m30 the thirteenth element of the matrix - * @param {float} m31 the fourtheenth element of the matrix - * @param {float} m32 the fivetheenth element of the matrix - * @param {float} m33 the sixteenth element of the matrix - */ - apply: function() { - var source; - if (arguments.length === 1 && arguments[0] instanceof PMatrix3D) { - source = arguments[0].array(); - } else if (arguments.length === 16) { - source = Array.prototype.slice.call(arguments); - } else if (arguments.length === 1 && arguments[0] instanceof Array) { - source = arguments[0]; - } - - var result = [0, 0, 0, 0, - 0, 0, 0, 0, - 0, 0, 0, 0, - 0, 0, 0, 0]; - var e = 0; - for (var row = 0; row < 4; row++) { - for (var col = 0; col < 4; col++, e++) { - result[e] += this.elements[row * 4 + 0] * source[col + 0] + this.elements[row * 4 + 1] * - source[col + 4] + this.elements[row * 4 + 2] * source[col + 8] + - this.elements[row * 4 + 3] * source[col + 12]; - } - } - this.elements = result.slice(); - }, - /** - * @member PMatrix3D - * The rotate() function rotates the matrix. - * - * @param {float} angle the angle of rotation in radiants - */ - rotate: function(angle, v0, v1, v2) { - if (!v1) { - this.rotateZ(angle); - } else { - // TODO should make sure this vector is normalized - var c = p.cos(angle); - var s = p.sin(angle); - var t = 1.0 - c; - - this.apply((t * v0 * v0) + c, - (t * v0 * v1) - (s * v2), - (t * v0 * v2) + (s * v1), - 0, - (t * v0 * v1) + (s * v2), - (t * v1 * v1) + c, - (t * v1 * v2) - (s * v0), - 0, - (t * v0 * v2) - (s * v1), - (t * v1 * v2) + (s * v0), - (t * v2 * v2) + c, - 0, - 0, 0, 0, 1); - } - }, - /** - * @member PMatrix3D - * The invApply() function applies the inverted matrix to this matrix. - * - * @param {float} m00 the first element of the matrix - * @param {float} m01 the second element of the matrix - * @param {float} m02 the third element of the matrix - * @param {float} m03 the fourth element of the matrix - * @param {float} m10 the fifth element of the matrix - * @param {float} m11 the sixth element of the matrix - * @param {float} m12 the seventh element of the matrix - * @param {float} m13 the eight element of the matrix - * @param {float} m20 the nineth element of the matrix - * @param {float} m21 the tenth element of the matrix - * @param {float} m22 the eleventh element of the matrix - * @param {float} m23 the twelveth element of the matrix - * @param {float} m30 the thirteenth element of the matrix - * @param {float} m31 the fourtheenth element of the matrix - * @param {float} m32 the fivetheenth element of the matrix - * @param {float} m33 the sixteenth element of the matrix - * - * @return {boolean} returns true if the operation was successful. - */ - invApply: function() { - if (inverseCopy === undef) { - inverseCopy = new PMatrix3D(); - } - var a = arguments; - inverseCopy.set(a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], - a[9], a[10], a[11], a[12], a[13], a[14], a[15]); - - if (!inverseCopy.invert()) { - return false; - } - this.preApply(inverseCopy); - return true; - }, - /** - * @member PMatrix3D - * The rotateZ() function rotates the matrix. - * - * @param {float} angle the angle of rotation in radiants - */ - rotateX: function(angle) { - var c = p.cos(angle); - var s = p.sin(angle); - this.apply([1, 0, 0, 0, 0, c, -s, 0, 0, s, c, 0, 0, 0, 0, 1]); - }, - /** - * @member PMatrix3D - * The rotateY() function rotates the matrix. - * - * @param {float} angle the angle of rotation in radiants - */ - rotateY: function(angle) { - var c = p.cos(angle); - var s = p.sin(angle); - this.apply([c, 0, s, 0, 0, 1, 0, 0, -s, 0, c, 0, 0, 0, 0, 1]); - }, - /** - * @member PMatrix3D - * The rotateZ() function rotates the matrix. - * - * @param {float} angle the angle of rotation in radiants - */ - rotateZ: function(angle) { - var c = Math.cos(angle); - var s = Math.sin(angle); - this.apply([c, -s, 0, 0, s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]); - }, - /** - * @member PMatrix3D - * The scale() function increases or decreases the size of a matrix by expanding and contracting vertices. When only one parameter is specified scale will occur in all dimensions. - * This is equivalent to a three parameter call. - * - * @param {float} sx the amount to scale on the x-axis - * @param {float} sy the amount to scale on the y-axis - * @param {float} sz the amount to scale on the z-axis - */ - scale: function(sx, sy, sz) { - if (sx && !sy && !sz) { - sy = sz = sx; - } else if (sx && sy && !sz) { - sz = 1; - } - - if (sx && sy && sz) { - this.elements[0] *= sx; - this.elements[1] *= sy; - this.elements[2] *= sz; - this.elements[4] *= sx; - this.elements[5] *= sy; - this.elements[6] *= sz; - this.elements[8] *= sx; - this.elements[9] *= sy; - this.elements[10] *= sz; - this.elements[12] *= sx; - this.elements[13] *= sy; - this.elements[14] *= sz; - } - }, - /** - * @member PMatrix3D - * The skewX() function skews the matrix along the x-axis the amount specified by the angle parameter. - * Angles should be specified in radians (values from 0 to PI*2) or converted to radians with the radians() function. - * - * @param {float} angle angle of skew specified in radians - */ - skewX: function(angle) { - var t = Math.tan(angle); - this.apply(1, t, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1); - }, - /** - * @member PMatrix3D - * The skewY() function skews the matrix along the y-axis the amount specified by the angle parameter. - * Angles should be specified in radians (values from 0 to PI*2) or converted to radians with the radians() function. - * - * @param {float} angle angle of skew specified in radians - */ - skewY: function(angle) { - var t = Math.tan(angle); - this.apply(1, 0, 0, 0, t, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1); - }, - multX: function(x, y, z, w) { - if (!z) { - return this.elements[0] * x + this.elements[1] * y + this.elements[3]; - } - if (!w) { - return this.elements[0] * x + this.elements[1] * y + this.elements[2] * z + this.elements[3]; - } - return this.elements[0] * x + this.elements[1] * y + this.elements[2] * z + this.elements[3] * w; - }, - multY: function(x, y, z, w) { - if (!z) { - return this.elements[4] * x + this.elements[5] * y + this.elements[7]; - } - if (!w) { - return this.elements[4] * x + this.elements[5] * y + this.elements[6] * z + this.elements[7]; - } - return this.elements[4] * x + this.elements[5] * y + this.elements[6] * z + this.elements[7] * w; - }, - multZ: function(x, y, z, w) { - if (!w) { - return this.elements[8] * x + this.elements[9] * y + this.elements[10] * z + this.elements[11]; - } - return this.elements[8] * x + this.elements[9] * y + this.elements[10] * z + this.elements[11] * w; - }, - multW: function(x, y, z, w) { - if (!w) { - return this.elements[12] * x + this.elements[13] * y + this.elements[14] * z + this.elements[15]; - } - return this.elements[12] * x + this.elements[13] * y + this.elements[14] * z + this.elements[15] * w; - }, - /** - * @member PMatrix3D - * The invert() function inverts this matrix - * - * @return {boolean} true if successful - */ - invert: function() { - var fA0 = this.elements[0] * this.elements[5] - this.elements[1] * this.elements[4]; - var fA1 = this.elements[0] * this.elements[6] - this.elements[2] * this.elements[4]; - var fA2 = this.elements[0] * this.elements[7] - this.elements[3] * this.elements[4]; - var fA3 = this.elements[1] * this.elements[6] - this.elements[2] * this.elements[5]; - var fA4 = this.elements[1] * this.elements[7] - this.elements[3] * this.elements[5]; - var fA5 = this.elements[2] * this.elements[7] - this.elements[3] * this.elements[6]; - var fB0 = this.elements[8] * this.elements[13] - this.elements[9] * this.elements[12]; - var fB1 = this.elements[8] * this.elements[14] - this.elements[10] * this.elements[12]; - var fB2 = this.elements[8] * this.elements[15] - this.elements[11] * this.elements[12]; - var fB3 = this.elements[9] * this.elements[14] - this.elements[10] * this.elements[13]; - var fB4 = this.elements[9] * this.elements[15] - this.elements[11] * this.elements[13]; - var fB5 = this.elements[10] * this.elements[15] - this.elements[11] * this.elements[14]; - - // Determinant - var fDet = fA0 * fB5 - fA1 * fB4 + fA2 * fB3 + fA3 * fB2 - fA4 * fB1 + fA5 * fB0; - - // Account for a very small value - // return false if not successful. - if (Math.abs(fDet) <= 1e-9) { - return false; - } - - var kInv = []; - kInv[0] = +this.elements[5] * fB5 - this.elements[6] * fB4 + this.elements[7] * fB3; - kInv[4] = -this.elements[4] * fB5 + this.elements[6] * fB2 - this.elements[7] * fB1; - kInv[8] = +this.elements[4] * fB4 - this.elements[5] * fB2 + this.elements[7] * fB0; - kInv[12] = -this.elements[4] * fB3 + this.elements[5] * fB1 - this.elements[6] * fB0; - kInv[1] = -this.elements[1] * fB5 + this.elements[2] * fB4 - this.elements[3] * fB3; - kInv[5] = +this.elements[0] * fB5 - this.elements[2] * fB2 + this.elements[3] * fB1; - kInv[9] = -this.elements[0] * fB4 + this.elements[1] * fB2 - this.elements[3] * fB0; - kInv[13] = +this.elements[0] * fB3 - this.elements[1] * fB1 + this.elements[2] * fB0; - kInv[2] = +this.elements[13] * fA5 - this.elements[14] * fA4 + this.elements[15] * fA3; - kInv[6] = -this.elements[12] * fA5 + this.elements[14] * fA2 - this.elements[15] * fA1; - kInv[10] = +this.elements[12] * fA4 - this.elements[13] * fA2 + this.elements[15] * fA0; - kInv[14] = -this.elements[12] * fA3 + this.elements[13] * fA1 - this.elements[14] * fA0; - kInv[3] = -this.elements[9] * fA5 + this.elements[10] * fA4 - this.elements[11] * fA3; - kInv[7] = +this.elements[8] * fA5 - this.elements[10] * fA2 + this.elements[11] * fA1; - kInv[11] = -this.elements[8] * fA4 + this.elements[9] * fA2 - this.elements[11] * fA0; - kInv[15] = +this.elements[8] * fA3 - this.elements[9] * fA1 + this.elements[10] * fA0; - - // Inverse using Determinant - var fInvDet = 1.0 / fDet; - kInv[0] *= fInvDet; - kInv[1] *= fInvDet; - kInv[2] *= fInvDet; - kInv[3] *= fInvDet; - kInv[4] *= fInvDet; - kInv[5] *= fInvDet; - kInv[6] *= fInvDet; - kInv[7] *= fInvDet; - kInv[8] *= fInvDet; - kInv[9] *= fInvDet; - kInv[10] *= fInvDet; - kInv[11] *= fInvDet; - kInv[12] *= fInvDet; - kInv[13] *= fInvDet; - kInv[14] *= fInvDet; - kInv[15] *= fInvDet; - - this.elements = kInv.slice(); - return true; - }, - toString: function() { - var str = ""; - for (var i = 0; i < 15; i++) { - str += this.elements[i] + ", "; - } - str += this.elements[15]; - return str; - }, - /** - * @member PMatrix3D - * The print() function prints out the elements of this matrix - */ - print: function() { - var digits = printMatrixHelper(this.elements); - - var output = "" + p.nfs(this.elements[0], digits, 4) + " " + p.nfs(this.elements[1], digits, 4) + - " " + p.nfs(this.elements[2], digits, 4) + " " + p.nfs(this.elements[3], digits, 4) + - "\n" + p.nfs(this.elements[4], digits, 4) + " " + p.nfs(this.elements[5], digits, 4) + - " " + p.nfs(this.elements[6], digits, 4) + " " + p.nfs(this.elements[7], digits, 4) + - "\n" + p.nfs(this.elements[8], digits, 4) + " " + p.nfs(this.elements[9], digits, 4) + - " " + p.nfs(this.elements[10], digits, 4) + " " + p.nfs(this.elements[11], digits, 4) + - "\n" + p.nfs(this.elements[12], digits, 4) + " " + p.nfs(this.elements[13], digits, 4) + - " " + p.nfs(this.elements[14], digits, 4) + " " + p.nfs(this.elements[15], digits, 4) + "\n\n"; - p.println(output); - }, - invTranslate: function(tx, ty, tz) { - this.preApply(1, 0, 0, -tx, 0, 1, 0, -ty, 0, 0, 1, -tz, 0, 0, 0, 1); - }, - invRotateX: function(angle) { - var c = Math.cos(-angle); - var s = Math.sin(-angle); - this.preApply([1, 0, 0, 0, 0, c, -s, 0, 0, s, c, 0, 0, 0, 0, 1]); - }, - invRotateY: function(angle) { - var c = Math.cos(-angle); - var s = Math.sin(-angle); - this.preApply([c, 0, s, 0, 0, 1, 0, 0, -s, 0, c, 0, 0, 0, 0, 1]); - }, - invRotateZ: function(angle) { - var c = Math.cos(-angle); - var s = Math.sin(-angle); - this.preApply([c, -s, 0, 0, s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]); - }, - invScale: function(x, y, z) { - this.preApply([1 / x, 0, 0, 0, 0, 1 / y, 0, 0, 0, 0, 1 / z, 0, 0, 0, 0, 1]); - } - }; - - /** - * @private - * The matrix stack stores the transformations and translations that occur within the space. - */ - var PMatrixStack = p.PMatrixStack = function() { - this.matrixStack = []; - }; - - /** - * @member PMatrixStack - * load pushes the matrix given in the function into the stack - * - * @param {Object | Array} matrix the matrix to be pushed into the stack - */ - PMatrixStack.prototype.load = function() { - var tmpMatrix = drawing.$newPMatrix(); - - if (arguments.length === 1) { - tmpMatrix.set(arguments[0]); - } else { - tmpMatrix.set(arguments); - } - this.matrixStack.push(tmpMatrix); - }; - - Drawing2D.prototype.$newPMatrix = function() { - return new PMatrix2D(); - }; - - Drawing3D.prototype.$newPMatrix = function() { - return new PMatrix3D(); - }; - - /** - * @member PMatrixStack - * push adds a duplicate of the top of the stack onto the stack - uses the peek function - */ - PMatrixStack.prototype.push = function() { - this.matrixStack.push(this.peek()); - }; - - /** - * @member PMatrixStack - * pop removes returns the matrix at the top of the stack - * - * @returns {Object} the matrix at the top of the stack - */ - PMatrixStack.prototype.pop = function() { - return this.matrixStack.pop(); - }; - - /** - * @member PMatrixStack - * peek returns but doesn't remove the matrix at the top of the stack - * - * @returns {Object} the matrix at the top of the stack - */ - PMatrixStack.prototype.peek = function() { - var tmpMatrix = drawing.$newPMatrix(); - - tmpMatrix.set(this.matrixStack[this.matrixStack.length - 1]); - return tmpMatrix; - }; - - /** - * @member PMatrixStack - * this function multiplies the matrix at the top of the stack with the matrix given as a parameter - * - * @param {Object | Array} matrix the matrix to be multiplied into the stack - */ - PMatrixStack.prototype.mult = function(matrix) { - this.matrixStack[this.matrixStack.length - 1].apply(matrix); - }; - - //////////////////////////////////////////////////////////////////////////// - // Array handling - //////////////////////////////////////////////////////////////////////////// - - /** - * The split() function breaks a string into pieces using a character or string - * as the divider. The delim parameter specifies the character or characters that - * mark the boundaries between each piece. A String[] array is returned that contains - * each of the pieces. - * If the result is a set of numbers, you can convert the String[] array to to a float[] - * or int[] array using the datatype conversion functions int() and float() (see example above). - * The splitTokens() function works in a similar fashion, except that it splits using a range - * of characters instead of a specific character or sequence. - * - * @param {String} str the String to be split - * @param {String} delim the character or String used to separate the data - * - * @returns {string[]} The new string array - * - * @see splitTokens - * @see join - * @see trim - */ - p.split = function(str, delim) { - return str.split(delim); - }; - - /** - * The splitTokens() function splits a String at one or many character "tokens." The tokens - * parameter specifies the character or characters to be used as a boundary. - * If no tokens character is specified, any whitespace character is used to split. - * Whitespace characters include tab (\t), line feed (\n), carriage return (\r), form - * feed (\f), and space. To convert a String to an array of integers or floats, use the - * datatype conversion functions int() and float() to convert the array of Strings. - * - * @param {String} str the String to be split - * @param {Char[]} tokens list of individual characters that will be used as separators - * - * @returns {string[]} The new string array - * - * @see split - * @see join - * @see trim - */ - p.splitTokens = function(str, tokens) { - if (arguments.length === 1) { - tokens = "\n\t\r\f "; - } - - tokens = "[" + tokens + "]"; - - var ary = []; - var index = 0; - var pos = str.search(tokens); - - while (pos >= 0) { - if (pos === 0) { - str = str.substring(1); - } else { - ary[index] = str.substring(0, pos); - index++; - str = str.substring(pos); - } - pos = str.search(tokens); - } - - if (str.length > 0) { - ary[index] = str; - } - - if (ary.length === 0) { - ary = undef; - } - - return ary; - }; - - /** - * Expands an array by one element and adds data to the new position. The datatype of - * the element parameter must be the same as the datatype of the array. - * When using an array of objects, the data returned from the function must be cast to - * the object array's data type. For example: SomeClass[] items = (SomeClass[]) - * append(originalArray, element). - * - * @param {boolean[]|byte[]|char[]|int[]|float[]|String[]|array of objects} array boolean[], - * byte[], char[], int[], float[], or String[], or an array of objects - * @param {boolean[]|byte[]|char[]|int[]|float[]|String[]|array of objects} element new data for the array - * - * @returns Array (the same datatype as the input) - * - * @see shorten - * @see expand - */ - p.append = function(array, element) { - array[array.length] = element; - return array; - }; - - /** - * Concatenates two arrays. For example, concatenating the array { 1, 2, 3 } and the - * array { 4, 5, 6 } yields { 1, 2, 3, 4, 5, 6 }. Both parameters must be arrays of the - * same datatype. - * When using an array of objects, the data returned from the function must be cast to the - * object array's data type. For example: SomeClass[] items = (SomeClass[]) concat(array1, array2). - * - * @param {boolean[]|byte[]|char[]|int[]|float[]|String[]|array of objects} array1 boolean[], - * byte[], char[], int[], float[], String[], or an array of objects - * @param {boolean[]|byte[]|char[]|int[]|float[]|String[]|array of objects} array2 boolean[], - * byte[], char[], int[], float[], String[], or an array of objects - * - * @returns Array (the same datatype as the input) - * - * @see splice - */ - p.concat = function(array1, array2) { - return array1.concat(array2); - }; - - /** - * Sorts an array of numbers from smallest to largest and puts an array of - * words in alphabetical order. The original array is not modified, a - * re-ordered array is returned. The count parameter states the number of - * elements to sort. For example if there are 12 elements in an array and - * if count is the value 5, only the first five elements on the array will - * be sorted. Alphabetical ordering is case insensitive. - * - * @param {String[] | int[] | float[]} array Array of elements to sort - * @param {int} numElem Number of elements to sort - * - * @returns {String[] | int[] | float[]} Array (same datatype as the input) - * - * @see reverse - */ - p.sort = function(array, numElem) { - var ret = []; - - // depending on the type used (int, float) or string - // we'll need to use a different compare function - if (array.length > 0) { - // copy since we need to return another array - var elemsToCopy = numElem > 0 ? numElem : array.length; - for (var i = 0; i < elemsToCopy; i++) { - ret.push(array[i]); - } - if (typeof array[0] === "string") { - ret.sort(); - } - // int or float - else { - ret.sort(function(a, b) { - return a - b; - }); - } - - // copy on the rest of the elements that were not sorted in case the user - // only wanted a subset of an array to be sorted. - if (numElem > 0) { - for (var j = ret.length; j < array.length; j++) { - ret.push(array[j]); - } - } - } - return ret; - }; - - /** - * Inserts a value or array of values into an existing array. The first two parameters must - * be of the same datatype. The array parameter defines the array which will be modified - * and the second parameter defines the data which will be inserted. When using an array - * of objects, the data returned from the function must be cast to the object array's data - * type. For example: SomeClass[] items = (SomeClass[]) splice(array1, array2, index). - * - * @param {boolean[]|byte[]|char[]|int[]|float[]|String[]|array of objects} array boolean[], - * byte[], char[], int[], float[], String[], or an array of objects - * @param {boolean|byte|char|int|float|String|boolean[]|byte[]|char[]|int[]|float[]|String[]|array of objects} - * value boolean, byte, char, int, float, String, boolean[], byte[], char[], int[], - * float[], String[], or other Object: value or an array of objects to be spliced in - * @param {int} index position in the array from which to insert data - * - * @returns Array (the same datatype as the input) - * - * @see contract - * @see subset - */ - p.splice = function(array, value, index) { - - // Trying to splice an empty array into "array" in P5 won't do - // anything, just return the original. - if(value.length === 0) - { - return array; - } - - // If the second argument was an array, we'll need to iterate over all - // the "value" elements and add one by one because - // array.splice(index, 0, value); - // would create a multi-dimensional array which isn't what we want. - if(value instanceof Array) { - for(var i = 0, j = index; i < value.length; j++,i++) { - array.splice(j, 0, value[i]); - } - } else { - array.splice(index, 0, value); - } - - return array; - }; - - /** - * Extracts an array of elements from an existing array. The array parameter defines the - * array from which the elements will be copied and the offset and length parameters determine - * which elements to extract. If no length is given, elements will be extracted from the offset - * to the end of the array. When specifying the offset remember the first array element is 0. - * This function does not change the source array. - * When using an array of objects, the data returned from the function must be cast to the - * object array's data type. - * - * @param {boolean[]|byte[]|char[]|int[]|float[]|String[]|array of objects} array boolean[], - * byte[], char[], int[], float[], String[], or an array of objects - * @param {int} offset position to begin - * @param {int} length number of values to extract - * - * @returns Array (the same datatype as the input) - * - * @see splice - */ - p.subset = function(array, offset, length) { - var end = (length !== undef) ? offset + length : array.length; - return array.slice(offset, end); - }; - - /** - * Combines an array of Strings into one String, each separated by the character(s) used for - * the separator parameter. To join arrays of ints or floats, it's necessary to first convert - * them to strings using nf() or nfs(). - * - * @param {Array} array array of Strings - * @param {char|String} separator char or String to be placed between each item - * - * @returns {String} The combined string - * - * @see split - * @see trim - * @see nf - * @see nfs - */ - p.join = function(array, seperator) { - return array.join(seperator); - }; - - /** - * Decreases an array by one element and returns the shortened array. When using an - * array of objects, the data returned from the function must be cast to the object array's - * data type. For example: SomeClass[] items = (SomeClass[]) shorten(originalArray). - * - * @param {boolean[]|byte[]|char[]|int[]|float[]|String[]|array of objects} array - * boolean[], byte[], char[], int[], float[], or String[], or an array of objects - * - * @returns Array (the same datatype as the input) - * - * @see append - * @see expand - */ - p.shorten = function(ary) { - var newary = []; - - // copy array into new array - var len = ary.length; - for (var i = 0; i < len; i++) { - newary[i] = ary[i]; - } - newary.pop(); - - return newary; - }; - - /** - * Increases the size of an array. By default, this function doubles the size of the array, - * but the optional newSize parameter provides precise control over the increase in size. - * When using an array of objects, the data returned from the function must be cast to the - * object array's data type. For example: SomeClass[] items = (SomeClass[]) expand(originalArray). - * - * @param {boolean[]|byte[]|char[]|int[]|float[]|String[]|array of objects} ary - * boolean[], byte[], char[], int[], float[], String[], or an array of objects - * @param {int} newSize positive int: new size for the array - * - * @returns Array (the same datatype as the input) - * - * @see contract - */ - p.expand = function(ary, targetSize) { - var temp = ary.slice(0), - newSize = targetSize || ary.length * 2; - temp.length = newSize; - return temp; - }; - - /** - * Copies an array (or part of an array) to another array. The src array is copied to the - * dst array, beginning at the position specified by srcPos and into the position specified - * by dstPos. The number of elements to copy is determined by length. The simplified version - * with two arguments copies an entire array to another of the same size. It is equivalent - * to "arrayCopy(src, 0, dst, 0, src.length)". This function is far more efficient for copying - * array data than iterating through a for and copying each element. - * - * @param {Array} src an array of any data type: the source array - * @param {Array} dest an array of any data type (as long as it's the same as src): the destination array - * @param {int} srcPos starting position in the source array - * @param {int} destPos starting position in the destination array - * @param {int} length number of array elements to be copied - * - * @returns none - */ - p.arrayCopy = function() { // src, srcPos, dest, destPos, length) { - var src, srcPos = 0, dest, destPos = 0, length; - - if (arguments.length === 2) { - // recall itself and copy src to dest from start index 0 to 0 of src.length - src = arguments[0]; - dest = arguments[1]; - length = src.length; - } else if (arguments.length === 3) { - // recall itself and copy src to dest from start index 0 to 0 of length - src = arguments[0]; - dest = arguments[1]; - length = arguments[2]; - } else if (arguments.length === 5) { - src = arguments[0]; - srcPos = arguments[1]; - dest = arguments[2]; - destPos = arguments[3]; - length = arguments[4]; - } - - // copy src to dest from index srcPos to index destPos of length recursivly on objects - for (var i = srcPos, j = destPos; i < length + srcPos; i++, j++) { - if (dest[j] !== undef) { - dest[j] = src[i]; - } else { - throw "array index out of bounds exception"; - } - } - }; - - /** - * Reverses the order of an array. - * - * @param {boolean[]|byte[]|char[]|int[]|float[]|String[]} array - * boolean[], byte[], char[], int[], float[], or String[] - * - * @returns Array (the same datatype as the input) - * - * @see sort - */ - p.reverse = function(array) { - return array.reverse(); - }; - - - //////////////////////////////////////////////////////////////////////////// - // Color functions - //////////////////////////////////////////////////////////////////////////// - - // helper functions for internal blending modes - p.mix = function(a, b, f) { - return a + (((b - a) * f) >> 8); - }; - - p.peg = function(n) { - return (n < 0) ? 0 : ((n > 255) ? 255 : n); - }; - - // blending modes - /** - * These are internal blending modes used for BlendColor() - * - * @param {Color} c1 First Color to blend - * @param {Color} c2 Second Color to blend - * - * @returns {Color} The blended Color - * - * @see BlendColor - * @see Blend - */ - p.modes = (function() { - var ALPHA_MASK = PConstants.ALPHA_MASK, - RED_MASK = PConstants.RED_MASK, - GREEN_MASK = PConstants.GREEN_MASK, - BLUE_MASK = PConstants.BLUE_MASK, - min = Math.min, - max = Math.max; - - function applyMode(c1, f, ar, ag, ab, br, bg, bb, cr, cg, cb) { - var a = min(((c1 & 0xff000000) >>> 24) + f, 0xff) << 24; - - var r = (ar + (((cr - ar) * f) >> 8)); - r = ((r < 0) ? 0 : ((r > 255) ? 255 : r)) << 16; - - var g = (ag + (((cg - ag) * f) >> 8)); - g = ((g < 0) ? 0 : ((g > 255) ? 255 : g)) << 8; - - var b = ab + (((cb - ab) * f) >> 8); - b = (b < 0) ? 0 : ((b > 255) ? 255 : b); - - return (a | r | g | b); - } - - return { - replace: function(c1, c2) { - return c2; - }, - blend: function(c1, c2) { - var f = (c2 & ALPHA_MASK) >>> 24, - ar = (c1 & RED_MASK), - ag = (c1 & GREEN_MASK), - ab = (c1 & BLUE_MASK), - br = (c2 & RED_MASK), - bg = (c2 & GREEN_MASK), - bb = (c2 & BLUE_MASK); - - return (min(((c1 & ALPHA_MASK) >>> 24) + f, 0xff) << 24 | - (ar + (((br - ar) * f) >> 8)) & RED_MASK | - (ag + (((bg - ag) * f) >> 8)) & GREEN_MASK | - (ab + (((bb - ab) * f) >> 8)) & BLUE_MASK); - }, - add: function(c1, c2) { - var f = (c2 & ALPHA_MASK) >>> 24; - return (min(((c1 & ALPHA_MASK) >>> 24) + f, 0xff) << 24 | - min(((c1 & RED_MASK) + ((c2 & RED_MASK) >> 8) * f), RED_MASK) & RED_MASK | - min(((c1 & GREEN_MASK) + ((c2 & GREEN_MASK) >> 8) * f), GREEN_MASK) & GREEN_MASK | - min((c1 & BLUE_MASK) + (((c2 & BLUE_MASK) * f) >> 8), BLUE_MASK)); - }, - subtract: function(c1, c2) { - var f = (c2 & ALPHA_MASK) >>> 24; - return (min(((c1 & ALPHA_MASK) >>> 24) + f, 0xff) << 24 | - max(((c1 & RED_MASK) - ((c2 & RED_MASK) >> 8) * f), GREEN_MASK) & RED_MASK | - max(((c1 & GREEN_MASK) - ((c2 & GREEN_MASK) >> 8) * f), BLUE_MASK) & GREEN_MASK | - max((c1 & BLUE_MASK) - (((c2 & BLUE_MASK) * f) >> 8), 0)); - }, - lightest: function(c1, c2) { - var f = (c2 & ALPHA_MASK) >>> 24; - return (min(((c1 & ALPHA_MASK) >>> 24) + f, 0xff) << 24 | - max(c1 & RED_MASK, ((c2 & RED_MASK) >> 8) * f) & RED_MASK | - max(c1 & GREEN_MASK, ((c2 & GREEN_MASK) >> 8) * f) & GREEN_MASK | - max(c1 & BLUE_MASK, ((c2 & BLUE_MASK) * f) >> 8)); - }, - darkest: function(c1, c2) { - var f = (c2 & ALPHA_MASK) >>> 24, - ar = (c1 & RED_MASK), - ag = (c1 & GREEN_MASK), - ab = (c1 & BLUE_MASK), - br = min(c1 & RED_MASK, ((c2 & RED_MASK) >> 8) * f), - bg = min(c1 & GREEN_MASK, ((c2 & GREEN_MASK) >> 8) * f), - bb = min(c1 & BLUE_MASK, ((c2 & BLUE_MASK) * f) >> 8); - - return (min(((c1 & ALPHA_MASK) >>> 24) + f, 0xff) << 24 | - (ar + (((br - ar) * f) >> 8)) & RED_MASK | - (ag + (((bg - ag) * f) >> 8)) & GREEN_MASK | - (ab + (((bb - ab) * f) >> 8)) & BLUE_MASK); - }, - difference: function(c1, c2) { - var f = (c2 & ALPHA_MASK) >>> 24, - ar = (c1 & RED_MASK) >> 16, - ag = (c1 & GREEN_MASK) >> 8, - ab = (c1 & BLUE_MASK), - br = (c2 & RED_MASK) >> 16, - bg = (c2 & GREEN_MASK) >> 8, - bb = (c2 & BLUE_MASK), - cr = (ar > br) ? (ar - br) : (br - ar), - cg = (ag > bg) ? (ag - bg) : (bg - ag), - cb = (ab > bb) ? (ab - bb) : (bb - ab); - - return applyMode(c1, f, ar, ag, ab, br, bg, bb, cr, cg, cb); - }, - exclusion: function(c1, c2) { - var f = (c2 & ALPHA_MASK) >>> 24, - ar = (c1 & RED_MASK) >> 16, - ag = (c1 & GREEN_MASK) >> 8, - ab = (c1 & BLUE_MASK), - br = (c2 & RED_MASK) >> 16, - bg = (c2 & GREEN_MASK) >> 8, - bb = (c2 & BLUE_MASK), - cr = ar + br - ((ar * br) >> 7), - cg = ag + bg - ((ag * bg) >> 7), - cb = ab + bb - ((ab * bb) >> 7); - - return applyMode(c1, f, ar, ag, ab, br, bg, bb, cr, cg, cb); - }, - multiply: function(c1, c2) { - var f = (c2 & ALPHA_MASK) >>> 24, - ar = (c1 & RED_MASK) >> 16, - ag = (c1 & GREEN_MASK) >> 8, - ab = (c1 & BLUE_MASK), - br = (c2 & RED_MASK) >> 16, - bg = (c2 & GREEN_MASK) >> 8, - bb = (c2 & BLUE_MASK), - cr = (ar * br) >> 8, - cg = (ag * bg) >> 8, - cb = (ab * bb) >> 8; - - return applyMode(c1, f, ar, ag, ab, br, bg, bb, cr, cg, cb); - }, - screen: function(c1, c2) { - var f = (c2 & ALPHA_MASK) >>> 24, - ar = (c1 & RED_MASK) >> 16, - ag = (c1 & GREEN_MASK) >> 8, - ab = (c1 & BLUE_MASK), - br = (c2 & RED_MASK) >> 16, - bg = (c2 & GREEN_MASK) >> 8, - bb = (c2 & BLUE_MASK), - cr = 255 - (((255 - ar) * (255 - br)) >> 8), - cg = 255 - (((255 - ag) * (255 - bg)) >> 8), - cb = 255 - (((255 - ab) * (255 - bb)) >> 8); - - return applyMode(c1, f, ar, ag, ab, br, bg, bb, cr, cg, cb); - }, - hard_light: function(c1, c2) { - var f = (c2 & ALPHA_MASK) >>> 24, - ar = (c1 & RED_MASK) >> 16, - ag = (c1 & GREEN_MASK) >> 8, - ab = (c1 & BLUE_MASK), - br = (c2 & RED_MASK) >> 16, - bg = (c2 & GREEN_MASK) >> 8, - bb = (c2 & BLUE_MASK), - cr = (br < 128) ? ((ar * br) >> 7) : (255 - (((255 - ar) * (255 - br)) >> 7)), - cg = (bg < 128) ? ((ag * bg) >> 7) : (255 - (((255 - ag) * (255 - bg)) >> 7)), - cb = (bb < 128) ? ((ab * bb) >> 7) : (255 - (((255 - ab) * (255 - bb)) >> 7)); - - return applyMode(c1, f, ar, ag, ab, br, bg, bb, cr, cg, cb); - }, - soft_light: function(c1, c2) { - var f = (c2 & ALPHA_MASK) >>> 24, - ar = (c1 & RED_MASK) >> 16, - ag = (c1 & GREEN_MASK) >> 8, - ab = (c1 & BLUE_MASK), - br = (c2 & RED_MASK) >> 16, - bg = (c2 & GREEN_MASK) >> 8, - bb = (c2 & BLUE_MASK), - cr = ((ar * br) >> 7) + ((ar * ar) >> 8) - ((ar * ar * br) >> 15), - cg = ((ag * bg) >> 7) + ((ag * ag) >> 8) - ((ag * ag * bg) >> 15), - cb = ((ab * bb) >> 7) + ((ab * ab) >> 8) - ((ab * ab * bb) >> 15); - - return applyMode(c1, f, ar, ag, ab, br, bg, bb, cr, cg, cb); - }, - overlay: function(c1, c2) { - var f = (c2 & ALPHA_MASK) >>> 24, - ar = (c1 & RED_MASK) >> 16, - ag = (c1 & GREEN_MASK) >> 8, - ab = (c1 & BLUE_MASK), - br = (c2 & RED_MASK) >> 16, - bg = (c2 & GREEN_MASK) >> 8, - bb = (c2 & BLUE_MASK), - cr = (ar < 128) ? ((ar * br) >> 7) : (255 - (((255 - ar) * (255 - br)) >> 7)), - cg = (ag < 128) ? ((ag * bg) >> 7) : (255 - (((255 - ag) * (255 - bg)) >> 7)), - cb = (ab < 128) ? ((ab * bb) >> 7) : (255 - (((255 - ab) * (255 - bb)) >> 7)); - - return applyMode(c1, f, ar, ag, ab, br, bg, bb, cr, cg, cb); - }, - dodge: function(c1, c2) { - var f = (c2 & ALPHA_MASK) >>> 24, - ar = (c1 & RED_MASK) >> 16, - ag = (c1 & GREEN_MASK) >> 8, - ab = (c1 & BLUE_MASK), - br = (c2 & RED_MASK) >> 16, - bg = (c2 & GREEN_MASK) >> 8, - bb = (c2 & BLUE_MASK); - - var cr = 255; - if (br !== 255) { - cr = (ar << 8) / (255 - br); - cr = (cr < 0) ? 0 : ((cr > 255) ? 255 : cr); - } - - var cg = 255; - if (bg !== 255) { - cg = (ag << 8) / (255 - bg); - cg = (cg < 0) ? 0 : ((cg > 255) ? 255 : cg); - } - - var cb = 255; - if (bb !== 255) { - cb = (ab << 8) / (255 - bb); - cb = (cb < 0) ? 0 : ((cb > 255) ? 255 : cb); - } - - return applyMode(c1, f, ar, ag, ab, br, bg, bb, cr, cg, cb); - }, - burn: function(c1, c2) { - var f = (c2 & ALPHA_MASK) >>> 24, - ar = (c1 & RED_MASK) >> 16, - ag = (c1 & GREEN_MASK) >> 8, - ab = (c1 & BLUE_MASK), - br = (c2 & RED_MASK) >> 16, - bg = (c2 & GREEN_MASK) >> 8, - bb = (c2 & BLUE_MASK); - - var cr = 0; - if (br !== 0) { - cr = ((255 - ar) << 8) / br; - cr = 255 - ((cr < 0) ? 0 : ((cr > 255) ? 255 : cr)); - } - - var cg = 0; - if (bg !== 0) { - cg = ((255 - ag) << 8) / bg; - cg = 255 - ((cg < 0) ? 0 : ((cg > 255) ? 255 : cg)); - } - - var cb = 0; - if (bb !== 0) { - cb = ((255 - ab) << 8) / bb; - cb = 255 - ((cb < 0) ? 0 : ((cb > 255) ? 255 : cb)); - } - - return applyMode(c1, f, ar, ag, ab, br, bg, bb, cr, cg, cb); - } - }; - }()); - - function color$4(aValue1, aValue2, aValue3, aValue4) { - var r, g, b, a; - - if (curColorMode === PConstants.HSB) { - var rgb = p.color.toRGB(aValue1, aValue2, aValue3); - r = rgb[0]; - g = rgb[1]; - b = rgb[2]; - } else { - r = Math.round(255 * (aValue1 / colorModeX)); - g = Math.round(255 * (aValue2 / colorModeY)); - b = Math.round(255 * (aValue3 / colorModeZ)); - } - - a = Math.round(255 * (aValue4 / colorModeA)); - - // Limit values less than 0 and greater than 255 - r = (r < 0) ? 0 : r; - g = (g < 0) ? 0 : g; - b = (b < 0) ? 0 : b; - a = (a < 0) ? 0 : a; - r = (r > 255) ? 255 : r; - g = (g > 255) ? 255 : g; - b = (b > 255) ? 255 : b; - a = (a > 255) ? 255 : a; - - // Create color int - return (a << 24) & PConstants.ALPHA_MASK | (r << 16) & PConstants.RED_MASK | (g << 8) & PConstants.GREEN_MASK | b & PConstants.BLUE_MASK; - } - - function color$2(aValue1, aValue2) { - var a; - - // Color int and alpha - if (aValue1 & PConstants.ALPHA_MASK) { - a = Math.round(255 * (aValue2 / colorModeA)); - // Limit values less than 0 and greater than 255 - a = (a > 255) ? 255 : a; - a = (a < 0) ? 0 : a; - - return aValue1 - (aValue1 & PConstants.ALPHA_MASK) + ((a << 24) & PConstants.ALPHA_MASK); - } - // Grayscale and alpha - if (curColorMode === PConstants.RGB) { - return color$4(aValue1, aValue1, aValue1, aValue2); - } - if (curColorMode === PConstants.HSB) { - return color$4(0, 0, (aValue1 / colorModeX) * colorModeZ, aValue2); - } - } - - function color$1(aValue1) { - // Grayscale - if (aValue1 <= colorModeX && aValue1 >= 0) { - if (curColorMode === PConstants.RGB) { - return color$4(aValue1, aValue1, aValue1, colorModeA); - } - if (curColorMode === PConstants.HSB) { - return color$4(0, 0, (aValue1 / colorModeX) * colorModeZ, colorModeA); - } - } - // Color int - if (aValue1) { - if (aValue1 > 2147483647) { - // Java Overflow - aValue1 -= 4294967296; - } - return aValue1; - } - } - - /** - * Creates colors for storing in variables of the color datatype. The parameters are - * interpreted as RGB or HSB values depending on the current colorMode(). The default - * mode is RGB values from 0 to 255 and therefore, the function call color(255, 204, 0) - * will return a bright yellow color. More about how colors are stored can be found in - * the reference for the color datatype. - * - * @param {int|float} aValue1 red or hue or grey values relative to the current color range. - * Also can be color value in hexadecimal notation (i.e. #FFCC00 or 0xFFFFCC00) - * @param {int|float} aValue2 green or saturation values relative to the current color range - * @param {int|float} aValue3 blue or brightness values relative to the current color range - * @param {int|float} aValue4 relative to current color range. Represents alpha - * - * @returns {color} the color - * - * @see colorMode - */ - p.color = function(aValue1, aValue2, aValue3, aValue4) { - - // 4 arguments: (R, G, B, A) or (H, S, B, A) - if (aValue1 !== undef && aValue2 !== undef && aValue3 !== undef && aValue4 !== undef) { - return color$4(aValue1, aValue2, aValue3, aValue4); - } - - // 3 arguments: (R, G, B) or (H, S, B) - if (aValue1 !== undef && aValue2 !== undef && aValue3 !== undef) { - return color$4(aValue1, aValue2, aValue3, colorModeA); - } - - // 2 arguments: (Color, A) or (Grayscale, A) - if (aValue1 !== undef && aValue2 !== undef) { - return color$2(aValue1, aValue2); - } - - // 1 argument: (Grayscale) or (Color) - if (typeof aValue1 === "number") { - return color$1(aValue1); - } - - // Default - return color$4(colorModeX, colorModeY, colorModeZ, colorModeA); - }; - - // Ease of use function to extract the colour bits into a string - p.color.toString = function(colorInt) { - return "rgba(" + ((colorInt & PConstants.RED_MASK) >>> 16) + "," + ((colorInt & PConstants.GREEN_MASK) >>> 8) + - "," + ((colorInt & PConstants.BLUE_MASK)) + "," + ((colorInt & PConstants.ALPHA_MASK) >>> 24) / 255 + ")"; - }; - - // Easy of use function to pack rgba values into a single bit-shifted color int. - p.color.toInt = function(r, g, b, a) { - return (a << 24) & PConstants.ALPHA_MASK | (r << 16) & PConstants.RED_MASK | (g << 8) & PConstants.GREEN_MASK | b & PConstants.BLUE_MASK; - }; - - // Creates a simple array in [R, G, B, A] format, [255, 255, 255, 255] - p.color.toArray = function(colorInt) { - return [(colorInt & PConstants.RED_MASK) >>> 16, (colorInt & PConstants.GREEN_MASK) >>> 8, - colorInt & PConstants.BLUE_MASK, (colorInt & PConstants.ALPHA_MASK) >>> 24]; - }; - - // Creates a WebGL color array in [R, G, B, A] format. WebGL wants the color ranges between 0 and 1, [1, 1, 1, 1] - p.color.toGLArray = function(colorInt) { - return [((colorInt & PConstants.RED_MASK) >>> 16) / 255, ((colorInt & PConstants.GREEN_MASK) >>> 8) / 255, - (colorInt & PConstants.BLUE_MASK) / 255, ((colorInt & PConstants.ALPHA_MASK) >>> 24) / 255]; - }; - - // HSB conversion function from Mootools, MIT Licensed - p.color.toRGB = function(h, s, b) { - // Limit values greater than range - h = (h > colorModeX) ? colorModeX : h; - s = (s > colorModeY) ? colorModeY : s; - b = (b > colorModeZ) ? colorModeZ : b; - - h = (h / colorModeX) * 360; - s = (s / colorModeY) * 100; - b = (b / colorModeZ) * 100; - - var br = Math.round(b / 100 * 255); - - if (s === 0) { // Grayscale - return [br, br, br]; - } - var hue = h % 360; - var f = hue % 60; - var p = Math.round((b * (100 - s)) / 10000 * 255); - var q = Math.round((b * (6000 - s * f)) / 600000 * 255); - var t = Math.round((b * (6000 - s * (60 - f))) / 600000 * 255); - switch (Math.floor(hue / 60)) { - case 0: - return [br, t, p]; - case 1: - return [q, br, p]; - case 2: - return [p, br, t]; - case 3: - return [p, q, br]; - case 4: - return [t, p, br]; - case 5: - return [br, p, q]; - } - }; - - function colorToHSB(colorInt) { - var red, green, blue; - - red = ((colorInt & PConstants.RED_MASK) >>> 16) / 255; - green = ((colorInt & PConstants.GREEN_MASK) >>> 8) / 255; - blue = (colorInt & PConstants.BLUE_MASK) / 255; - - var max = p.max(p.max(red,green), blue), - min = p.min(p.min(red,green), blue), - hue, saturation; - - if (min === max) { - return [0, 0, max*colorModeZ]; - } - saturation = (max - min) / max; - - if (red === max) { - hue = (green - blue) / (max - min); - } else if (green === max) { - hue = 2 + ((blue - red) / (max - min)); - } else { - hue = 4 + ((red - green) / (max - min)); - } - - hue /= 6; - - if (hue < 0) { - hue += 1; - } else if (hue > 1) { - hue -= 1; - } - return [hue*colorModeX, saturation*colorModeY, max*colorModeZ]; - } - - /** - * Extracts the brightness value from a color. - * - * @param {color} colInt any value of the color datatype - * - * @returns {float} The brightness color value. - * - * @see red - * @see green - * @see blue - * @see hue - * @see saturation - */ - p.brightness = function(colInt){ - return colorToHSB(colInt)[2]; - }; - - /** - * Extracts the saturation value from a color. - * - * @param {color} colInt any value of the color datatype - * - * @returns {float} The saturation color value. - * - * @see red - * @see green - * @see blue - * @see hue - * @see brightness - */ - p.saturation = function(colInt){ - return colorToHSB(colInt)[1]; - }; - - /** - * Extracts the hue value from a color. - * - * @param {color} colInt any value of the color datatype - * - * @returns {float} The hue color value. - * - * @see red - * @see green - * @see blue - * @see saturation - * @see brightness - */ - p.hue = function(colInt){ - return colorToHSB(colInt)[0]; - }; - - /** - * Extracts the red value from a color, scaled to match current colorMode(). - * This value is always returned as a float so be careful not to assign it to an int value. - * - * @param {color} aColor any value of the color datatype - * - * @returns {float} The red color value. - * - * @see green - * @see blue - * @see alpha - * @see >> right shift - * @see hue - * @see saturation - * @see brightness - */ - p.red = function(aColor) { - return ((aColor & PConstants.RED_MASK) >>> 16) / 255 * colorModeX; - }; - - /** - * Extracts the green value from a color, scaled to match current colorMode(). - * This value is always returned as a float so be careful not to assign it to an int value. - * - * @param {color} aColor any value of the color datatype - * - * @returns {float} The green color value. - * - * @see red - * @see blue - * @see alpha - * @see >> right shift - * @see hue - * @see saturation - * @see brightness - */ - p.green = function(aColor) { - return ((aColor & PConstants.GREEN_MASK) >>> 8) / 255 * colorModeY; - }; - - /** - * Extracts the blue value from a color, scaled to match current colorMode(). - * This value is always returned as a float so be careful not to assign it to an int value. - * - * @param {color} aColor any value of the color datatype - * - * @returns {float} The blue color value. - * - * @see red - * @see green - * @see alpha - * @see >> right shift - * @see hue - * @see saturation - * @see brightness - */ - p.blue = function(aColor) { - return (aColor & PConstants.BLUE_MASK) / 255 * colorModeZ; - }; - - /** - * Extracts the alpha value from a color, scaled to match current colorMode(). - * This value is always returned as a float so be careful not to assign it to an int value. - * - * @param {color} aColor any value of the color datatype - * - * @returns {float} The alpha color value. - * - * @see red - * @see green - * @see blue - * @see >> right shift - * @see hue - * @see saturation - * @see brightness - */ - p.alpha = function(aColor) { - return ((aColor & PConstants.ALPHA_MASK) >>> 24) / 255 * colorModeA; - }; - - /** - * Calculates a color or colors between two colors at a specific increment. - * The amt parameter is the amount to interpolate between the two values where 0.0 - * equal to the first point, 0.1 is very near the first point, 0.5 is half-way in between, etc. - * - * @param {color} c1 interpolate from this color - * @param {color} c2 interpolate to this color - * @param {float} amt between 0.0 and 1.0 - * - * @returns {float} The blended color. - * - * @see blendColor - * @see color - */ - p.lerpColor = function(c1, c2, amt) { - var r, g, b, a, r1, g1, b1, a1, r2, g2, b2, a2; - var hsb1, hsb2, rgb, h, s; - var colorBits1 = p.color(c1); - var colorBits2 = p.color(c2); - - if (curColorMode === PConstants.HSB) { - // Special processing for HSB mode. - // Get HSB and Alpha values for Color 1 and 2 - hsb1 = colorToHSB(colorBits1); - a1 = ((colorBits1 & PConstants.ALPHA_MASK) >>> 24) / colorModeA; - hsb2 = colorToHSB(colorBits2); - a2 = ((colorBits2 & PConstants.ALPHA_MASK) >>> 24) / colorModeA; - - // Return lerp value for each channel, for HSB components - h = p.lerp(hsb1[0], hsb2[0], amt); - s = p.lerp(hsb1[1], hsb2[1], amt); - b = p.lerp(hsb1[2], hsb2[2], amt); - rgb = p.color.toRGB(h, s, b); - // ... and for Alpha-range - a = p.lerp(a1, a2, amt) * colorModeA; - - return (a << 24) & PConstants.ALPHA_MASK | - (rgb[0] << 16) & PConstants.RED_MASK | - (rgb[1] << 8) & PConstants.GREEN_MASK | - rgb[2] & PConstants.BLUE_MASK; - } - - // Get RGBA values for Color 1 to floats - r1 = (colorBits1 & PConstants.RED_MASK) >>> 16; - g1 = (colorBits1 & PConstants.GREEN_MASK) >>> 8; - b1 = (colorBits1 & PConstants.BLUE_MASK); - a1 = ((colorBits1 & PConstants.ALPHA_MASK) >>> 24) / colorModeA; - - // Get RGBA values for Color 2 to floats - r2 = (colorBits2 & PConstants.RED_MASK) >>> 16; - g2 = (colorBits2 & PConstants.GREEN_MASK) >>> 8; - b2 = (colorBits2 & PConstants.BLUE_MASK); - a2 = ((colorBits2 & PConstants.ALPHA_MASK) >>> 24) / colorModeA; - - // Return lerp value for each channel, INT for color, Float for Alpha-range - r = p.lerp(r1, r2, amt) | 0; - g = p.lerp(g1, g2, amt) | 0; - b = p.lerp(b1, b2, amt) | 0; - a = p.lerp(a1, a2, amt) * colorModeA; - - return (a << 24) & PConstants.ALPHA_MASK | - (r << 16) & PConstants.RED_MASK | - (g << 8) & PConstants.GREEN_MASK | - b & PConstants.BLUE_MASK; - }; - - /** - * Changes the way Processing interprets color data. By default, fill(), stroke(), and background() - * colors are set by values between 0 and 255 using the RGB color model. It is possible to change the - * numerical range used for specifying colors and to switch color systems. For example, calling colorMode(RGB, 1.0) - * will specify that values are specified between 0 and 1. The limits for defining colors are altered by setting the - * parameters range1, range2, range3, and range 4. - * - * @param {MODE} mode Either RGB or HSB, corresponding to Red/Green/Blue and Hue/Saturation/Brightness - * @param {int|float} range range for all color elements - * @param {int|float} range1 range for the red or hue depending on the current color mode - * @param {int|float} range2 range for the green or saturation depending on the current color mode - * @param {int|float} range3 range for the blue or brightness depending on the current color mode - * @param {int|float} range4 range for the alpha - * - * @returns none - * - * @see background - * @see fill - * @see stroke - */ - p.colorMode = function() { // mode, range1, range2, range3, range4 - curColorMode = arguments[0]; - if (arguments.length > 1) { - colorModeX = arguments[1]; - colorModeY = arguments[2] || arguments[1]; - colorModeZ = arguments[3] || arguments[1]; - colorModeA = arguments[4] || arguments[1]; - } - }; - - /** - * Blends two color values together based on the blending mode given as the MODE parameter. - * The possible modes are described in the reference for the blend() function. - * - * @param {color} c1 color: the first color to blend - * @param {color} c2 color: the second color to blend - * @param {MODE} MODE Either BLEND, ADD, SUBTRACT, DARKEST, LIGHTEST, DIFFERENCE, EXCLUSION, MULTIPLY, - * SCREEN, OVERLAY, HARD_LIGHT, SOFT_LIGHT, DODGE, or BURN - * - * @returns {float} The blended color. - * - * @see blend - * @see color - */ - p.blendColor = function(c1, c2, mode) { - if (mode === PConstants.REPLACE) { - return p.modes.replace(c1, c2); - } else if (mode === PConstants.BLEND) { - return p.modes.blend(c1, c2); - } else if (mode === PConstants.ADD) { - return p.modes.add(c1, c2); - } else if (mode === PConstants.SUBTRACT) { - return p.modes.subtract(c1, c2); - } else if (mode === PConstants.LIGHTEST) { - return p.modes.lightest(c1, c2); - } else if (mode === PConstants.DARKEST) { - return p.modes.darkest(c1, c2); - } else if (mode === PConstants.DIFFERENCE) { - return p.modes.difference(c1, c2); - } else if (mode === PConstants.EXCLUSION) { - return p.modes.exclusion(c1, c2); - } else if (mode === PConstants.MULTIPLY) { - return p.modes.multiply(c1, c2); - } else if (mode === PConstants.SCREEN) { - return p.modes.screen(c1, c2); - } else if (mode === PConstants.HARD_LIGHT) { - return p.modes.hard_light(c1, c2); - } else if (mode === PConstants.SOFT_LIGHT) { - return p.modes.soft_light(c1, c2); - } else if (mode === PConstants.OVERLAY) { - return p.modes.overlay(c1, c2); - } else if (mode === PConstants.DODGE) { - return p.modes.dodge(c1, c2); - } else if (mode === PConstants.BURN) { - return p.modes.burn(c1, c2); - } - }; - - //////////////////////////////////////////////////////////////////////////// - // Canvas-Matrix manipulation - //////////////////////////////////////////////////////////////////////////// - - function saveContext() { - curContext.save(); - } - - function restoreContext() { - curContext.restore(); - isStrokeDirty = true; - isFillDirty = true; - } - - /** - * Prints the current matrix to the text window. - * - * @returns none - * - * @see pushMatrix - * @see popMatrix - * @see resetMatrix - * @see applyMatrix - */ - p.printMatrix = function() { - modelView.print(); - }; - - /** - * Specifies an amount to displace objects within the display window. The x parameter specifies left/right translation, - * the y parameter specifies up/down translation, and the z parameter specifies translations toward/away from the screen. - * Using this function with the z parameter requires using the P3D or OPENGL parameter in combination with size as shown - * in the above example. Transformations apply to everything that happens after and subsequent calls to the function - * accumulates the effect. For example, calling translate(50, 0) and then translate(20, 0) is the same as translate(70, 0). - * If translate() is called within draw(), the transformation is reset when the loop begins again. - * This function can be further controlled by the pushMatrix() and popMatrix(). - * - * @param {int|float} x left/right translation - * @param {int|float} y up/down translation - * @param {int|float} z forward/back translation - * - * @returns none - * - * @see pushMatrix - * @see popMatrix - * @see scale - * @see rotate - * @see rotateX - * @see rotateY - * @see rotateZ - */ - Drawing2D.prototype.translate = function(x, y) { - modelView.translate(x, y); - modelViewInv.invTranslate(x, y); - curContext.translate(x, y); - }; - - Drawing3D.prototype.translate = function(x, y, z) { - modelView.translate(x, y, z); - modelViewInv.invTranslate(x, y, z); - }; - - /** - * Increases or decreases the size of a shape by expanding and contracting vertices. Objects always scale from their - * relative origin to the coordinate system. Scale values are specified as decimal percentages. For example, the - * function call scale(2.0) increases the dimension of a shape by 200%. Transformations apply to everything that - * happens after and subsequent calls to the function multiply the effect. For example, calling scale(2.0) and - * then scale(1.5) is the same as scale(3.0). If scale() is called within draw(), the transformation is reset when - * the loop begins again. Using this fuction with the z parameter requires passing P3D or OPENGL into the size() - * parameter as shown in the example above. This function can be further controlled by pushMatrix() and popMatrix(). - * - * @param {int|float} size percentage to scale the object - * @param {int|float} x percentage to scale the object in the x-axis - * @param {int|float} y percentage to scale the object in the y-axis - * @param {int|float} z percentage to scale the object in the z-axis - * - * @returns none - * - * @see pushMatrix - * @see popMatrix - * @see translate - * @see rotate - * @see rotateX - * @see rotateY - * @see rotateZ - */ - Drawing2D.prototype.scale = function(x, y) { - modelView.scale(x, y); - modelViewInv.invScale(x, y); - curContext.scale(x, y || x); - }; - - Drawing3D.prototype.scale = function(x, y, z) { - modelView.scale(x, y, z); - modelViewInv.invScale(x, y, z); - }; - - /** - * Pushes the current transformation matrix onto the matrix stack. Understanding pushMatrix() and popMatrix() - * requires understanding the concept of a matrix stack. The pushMatrix() function saves the current coordinate - * system to the stack and popMatrix() restores the prior coordinate system. pushMatrix() and popMatrix() are - * used in conjuction with the other transformation methods and may be embedded to control the scope of - * the transformations. - * - * @returns none - * - * @see popMatrix - * @see translate - * @see rotate - * @see rotateX - * @see rotateY - * @see rotateZ - */ - Drawing2D.prototype.pushMatrix = function() { - userMatrixStack.load(modelView); - userReverseMatrixStack.load(modelViewInv); - saveContext(); - }; - - Drawing3D.prototype.pushMatrix = function() { - userMatrixStack.load(modelView); - userReverseMatrixStack.load(modelViewInv); - }; - - /** - * Pops the current transformation matrix off the matrix stack. Understanding pushing and popping requires - * understanding the concept of a matrix stack. The pushMatrix() function saves the current coordinate system to - * the stack and popMatrix() restores the prior coordinate system. pushMatrix() and popMatrix() are used in - * conjuction with the other transformation methods and may be embedded to control the scope of the transformations. - * - * @returns none - * - * @see popMatrix - * @see pushMatrix - */ - Drawing2D.prototype.popMatrix = function() { - modelView.set(userMatrixStack.pop()); - modelViewInv.set(userReverseMatrixStack.pop()); - restoreContext(); - }; - - Drawing3D.prototype.popMatrix = function() { - modelView.set(userMatrixStack.pop()); - modelViewInv.set(userReverseMatrixStack.pop()); - }; - - /** - * Replaces the current matrix with the identity matrix. The equivalent function in OpenGL is glLoadIdentity(). - * - * @returns none - * - * @see popMatrix - * @see pushMatrix - * @see applyMatrix - * @see printMatrix - */ - Drawing2D.prototype.resetMatrix = function() { - modelView.reset(); - modelViewInv.reset(); - curContext.setTransform(1,0,0,1,0,0); - }; - - Drawing3D.prototype.resetMatrix = function() { - modelView.reset(); - modelViewInv.reset(); - }; - - /** - * Multiplies the current matrix by the one specified through the parameters. This is very slow because it will - * try to calculate the inverse of the transform, so avoid it whenever possible. The equivalent function - * in OpenGL is glMultMatrix(). - * - * @param {int|float} n00-n15 numbers which define the 4x4 matrix to be multiplied - * - * @returns none - * - * @see popMatrix - * @see pushMatrix - * @see resetMatrix - * @see printMatrix - */ - DrawingShared.prototype.applyMatrix = function() { - var a = arguments; - modelView.apply(a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9], a[10], a[11], a[12], a[13], a[14], a[15]); - modelViewInv.invApply(a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9], a[10], a[11], a[12], a[13], a[14], a[15]); - }; - - Drawing2D.prototype.applyMatrix = function() { - var a = arguments; - for (var cnt = a.length; cnt < 16; cnt++) { - a[cnt] = 0; - } - a[10] = a[15] = 1; - DrawingShared.prototype.applyMatrix.apply(this, a); - }; - - /** - * Rotates a shape around the x-axis the amount specified by the angle parameter. Angles should be - * specified in radians (values from 0 to PI*2) or converted to radians with the radians() function. - * Objects are always rotated around their relative position to the origin and positive numbers - * rotate objects in a counterclockwise direction. Transformations apply to everything that happens - * after and subsequent calls to the function accumulates the effect. For example, calling rotateX(PI/2) - * and then rotateX(PI/2) is the same as rotateX(PI). If rotateX() is called within the draw(), the - * transformation is reset when the loop begins again. This function requires passing P3D or OPENGL - * into the size() parameter as shown in the example above. - * - * @param {int|float} angleInRadians angle of rotation specified in radians - * - * @returns none - * - * @see rotateY - * @see rotateZ - * @see rotate - * @see translate - * @see scale - * @see popMatrix - * @see pushMatrix - */ - p.rotateX = function(angleInRadians) { - modelView.rotateX(angleInRadians); - modelViewInv.invRotateX(angleInRadians); - }; - - /** - * Rotates a shape around the z-axis the amount specified by the angle parameter. Angles should be - * specified in radians (values from 0 to PI*2) or converted to radians with the radians() function. - * Objects are always rotated around their relative position to the origin and positive numbers - * rotate objects in a counterclockwise direction. Transformations apply to everything that happens - * after and subsequent calls to the function accumulates the effect. For example, calling rotateZ(PI/2) - * and then rotateZ(PI/2) is the same as rotateZ(PI). If rotateZ() is called within the draw(), the - * transformation is reset when the loop begins again. This function requires passing P3D or OPENGL - * into the size() parameter as shown in the example above. - * - * @param {int|float} angleInRadians angle of rotation specified in radians - * - * @returns none - * - * @see rotateX - * @see rotateY - * @see rotate - * @see translate - * @see scale - * @see popMatrix - * @see pushMatrix - */ - Drawing2D.prototype.rotateZ = function() { - throw "rotateZ() is not supported in 2D mode. Use rotate(float) instead."; - }; - - Drawing3D.prototype.rotateZ = function(angleInRadians) { - modelView.rotateZ(angleInRadians); - modelViewInv.invRotateZ(angleInRadians); - }; - - /** - * Rotates a shape around the y-axis the amount specified by the angle parameter. Angles should be - * specified in radians (values from 0 to PI*2) or converted to radians with the radians() function. - * Objects are always rotated around their relative position to the origin and positive numbers - * rotate objects in a counterclockwise direction. Transformations apply to everything that happens - * after and subsequent calls to the function accumulates the effect. For example, calling rotateY(PI/2) - * and then rotateY(PI/2) is the same as rotateY(PI). If rotateY() is called within the draw(), the - * transformation is reset when the loop begins again. This function requires passing P3D or OPENGL - * into the size() parameter as shown in the example above. - * - * @param {int|float} angleInRadians angle of rotation specified in radians - * - * @returns none - * - * @see rotateX - * @see rotateZ - * @see rotate - * @see translate - * @see scale - * @see popMatrix - * @see pushMatrix - */ - p.rotateY = function(angleInRadians) { - modelView.rotateY(angleInRadians); - modelViewInv.invRotateY(angleInRadians); - }; - - /** - * Rotates a shape the amount specified by the angle parameter. Angles should be specified in radians - * (values from 0 to TWO_PI) or converted to radians with the radians() function. Objects are always - * rotated around their relative position to the origin and positive numbers rotate objects in a - * clockwise direction. Transformations apply to everything that happens after and subsequent calls - * to the function accumulates the effect. For example, calling rotate(HALF_PI) and then rotate(HALF_PI) - * is the same as rotate(PI). All tranformations are reset when draw() begins again. Technically, - * rotate() multiplies the current transformation matrix by a rotation matrix. This function can be - * further controlled by the pushMatrix() and popMatrix(). - * - * @param {int|float} angleInRadians angle of rotation specified in radians - * - * @returns none - * - * @see rotateX - * @see rotateY - * @see rotateZ - * @see rotate - * @see translate - * @see scale - * @see popMatrix - * @see pushMatrix - */ - Drawing2D.prototype.rotate = function(angleInRadians) { - modelView.rotateZ(angleInRadians); - modelViewInv.invRotateZ(angleInRadians); - curContext.rotate(angleInRadians); - }; - - Drawing3D.prototype.rotate = function(angleInRadians) { - p.rotateZ(angleInRadians); - }; - - /** - * The pushStyle() function saves the current style settings and popStyle() restores the prior settings. - * Note that these functions are always used together. They allow you to change the style settings and later - * return to what you had. When a new style is started with pushStyle(), it builds on the current style information. - * The pushStyle() and popStyle() functions can be embedded to provide more control (see the second example - * above for a demonstration.) - * The style information controlled by the following functions are included in the style: fill(), stroke(), tint(), - * strokeWeight(), strokeCap(), strokeJoin(), imageMode(), rectMode(), ellipseMode(), shapeMode(), colorMode(), - * textAlign(), textFont(), textMode(), textSize(), textLeading(), emissive(), specular(), shininess(), ambient() - * - * @returns none - * - * @see popStyle - */ - p.pushStyle = function() { - // Save the canvas state. - saveContext(); - - p.pushMatrix(); - - var newState = { - 'doFill': doFill, - 'currentFillColor': currentFillColor, - 'doStroke': doStroke, - 'currentStrokeColor': currentStrokeColor, - 'curTint': curTint, - 'curRectMode': curRectMode, - 'curColorMode': curColorMode, - 'colorModeX': colorModeX, - 'colorModeZ': colorModeZ, - 'colorModeY': colorModeY, - 'colorModeA': colorModeA, - 'curTextFont': curTextFont, - 'horizontalTextAlignment': horizontalTextAlignment, - 'verticalTextAlignment': verticalTextAlignment, - 'textMode': textMode, - 'curFontName': curFontName, - 'curTextSize': curTextSize, - 'curTextAscent': curTextAscent, - 'curTextDescent': curTextDescent, - 'curTextLeading': curTextLeading - }; - - styleArray.push(newState); - }; - - /** - * The pushStyle() function saves the current style settings and popStyle() restores the prior settings; these - * functions are always used together. They allow you to change the style settings and later return to what you had. - * When a new style is started with pushStyle(), it builds on the current style information. The pushStyle() and - * popStyle() functions can be embedded to provide more control (see the second example above for a demonstration.) - * - * @returns none - * - * @see pushStyle - */ - p.popStyle = function() { - var oldState = styleArray.pop(); - - if (oldState) { - restoreContext(); - - p.popMatrix(); - - doFill = oldState.doFill; - currentFillColor = oldState.currentFillColor; - doStroke = oldState.doStroke; - currentStrokeColor = oldState.currentStrokeColor; - curTint = oldState.curTint; - curRectMode = oldState.curRectmode; - curColorMode = oldState.curColorMode; - colorModeX = oldState.colorModeX; - colorModeZ = oldState.colorModeZ; - colorModeY = oldState.colorModeY; - colorModeA = oldState.colorModeA; - curTextFont = oldState.curTextFont; - curFontName = oldState.curFontName; - curTextSize = oldState.curTextSize; - horizontalTextAlignment = oldState.horizontalTextAlignment; - verticalTextAlignment = oldState.verticalTextAlignment; - textMode = oldState.textMode; - curTextAscent = oldState.curTextAscent; - curTextDescent = oldState.curTextDescent; - curTextLeading = oldState.curTextLeading; - } else { - throw "Too many popStyle() without enough pushStyle()"; - } - }; - - //////////////////////////////////////////////////////////////////////////// - // Time based functions - //////////////////////////////////////////////////////////////////////////// - - /** - * Processing communicates with the clock on your computer. - * The year() function returns the current year as an integer (2003, 2004, 2005, etc). - * - * @returns {float} The current year. - * - * @see millis - * @see second - * @see minute - * @see hour - * @see day - * @see month - */ - p.year = function() { - return new Date().getFullYear(); - }; - /** - * Processing communicates with the clock on your computer. - * The month() function returns the current month as a value from 1 - 12. - * - * @returns {float} The current month. - * - * @see millis - * @see second - * @see minute - * @see hour - * @see day - * @see year - */ - p.month = function() { - return new Date().getMonth() + 1; - }; - /** - * Processing communicates with the clock on your computer. - * The day() function returns the current day as a value from 1 - 31. - * - * @returns {float} The current day. - * - * @see millis - * @see second - * @see minute - * @see hour - * @see month - * @see year - */ - p.day = function() { - return new Date().getDate(); - }; - /** - * Processing communicates with the clock on your computer. - * The hour() function returns the current hour as a value from 0 - 23. - * - * @returns {float} The current hour. - * - * @see millis - * @see second - * @see minute - * @see month - * @see day - * @see year - */ - p.hour = function() { - return new Date().getHours(); - }; - /** - * Processing communicates with the clock on your computer. - * The minute() function returns the current minute as a value from 0 - 59. - * - * @returns {float} The current minute. - * - * @see millis - * @see second - * @see month - * @see hour - * @see day - * @see year - */ - p.minute = function() { - return new Date().getMinutes(); - }; - /** - * Processing communicates with the clock on your computer. - * The second() function returns the current second as a value from 0 - 59. - * - * @returns {float} The current minute. - * - * @see millis - * @see month - * @see minute - * @see hour - * @see day - * @see year - */ - p.second = function() { - return new Date().getSeconds(); - }; - /** - * Returns the number of milliseconds (thousandths of a second) since starting a sketch. - * This information is often used for timing animation sequences. - * - * @returns {long} The number of milliseconds since starting the sketch. - * - * @see month - * @see second - * @see minute - * @see hour - * @see day - * @see year - */ - p.millis = function() { - return Date.now() - start; - }; - - /** - * Executes the code within draw() one time. This functions allows the program to update - * the display window only when necessary, for example when an event registered by - * mousePressed() or keyPressed() occurs. - * In structuring a program, it only makes sense to call redraw() within events such as - * mousePressed(). This is because redraw() does not run draw() immediately (it only sets - * a flag that indicates an update is needed). - * Calling redraw() within draw() has no effect because draw() is continuously called anyway. - * - * @returns none - * - * @see noLoop - * @see loop - */ - function redrawHelper() { - var sec = (Date.now() - timeSinceLastFPS) / 1000; - framesSinceLastFPS++; - var fps = framesSinceLastFPS / sec; - - // recalculate FPS every half second for better accuracy. - if (sec > 0.5) { - timeSinceLastFPS = Date.now(); - framesSinceLastFPS = 0; - p.__frameRate = fps; - } - - p.frameCount++; - } - - Drawing2D.prototype.redraw = function() { - redrawHelper(); - - curContext.lineWidth = lineWidth; - var pmouseXLastEvent = p.pmouseX, - pmouseYLastEvent = p.pmouseY; - p.pmouseX = pmouseXLastFrame; - p.pmouseY = pmouseYLastFrame; - - saveContext(); - p.draw(); - restoreContext(); - - pmouseXLastFrame = p.mouseX; - pmouseYLastFrame = p.mouseY; - p.pmouseX = pmouseXLastEvent; - p.pmouseY = pmouseYLastEvent; - }; - - Drawing3D.prototype.redraw = function() { - redrawHelper(); - - var pmouseXLastEvent = p.pmouseX, - pmouseYLastEvent = p.pmouseY; - p.pmouseX = pmouseXLastFrame; - p.pmouseY = pmouseYLastFrame; - // even if the color buffer isn't cleared with background(), - // the depth buffer needs to be cleared regardless. - curContext.clear(curContext.DEPTH_BUFFER_BIT); - curContextCache = { attributes: {}, locations: {} }; - // Delete all the lighting states and the materials the - // user set in the last draw() call. - p.noLights(); - p.lightFalloff(1, 0, 0); - p.shininess(1); - p.ambient(255, 255, 255); - p.specular(0, 0, 0); - p.emissive(0, 0, 0); - p.camera(); - p.draw(); - - pmouseXLastFrame = p.mouseX; - pmouseYLastFrame = p.mouseY; - p.pmouseX = pmouseXLastEvent; - p.pmouseY = pmouseYLastEvent; - }; - - /** - * Stops Processing from continuously executing the code within draw(). If loop() is - * called, the code in draw() begin to run continuously again. If using noLoop() in - * setup(), it should be the last line inside the block. - * When noLoop() is used, it's not possible to manipulate or access the screen inside event - * handling functions such as mousePressed() or keyPressed(). Instead, use those functions - * to call redraw() or loop(), which will run draw(), which can update the screen properly. - * This means that when noLoop() has been called, no drawing can happen, and functions like - * saveFrame() or loadPixels() may not be used. - * Note that if the sketch is resized, redraw() will be called to update the sketch, even - * after noLoop() has been specified. Otherwise, the sketch would enter an odd state until - * loop() was called. - * - * @returns none - * - * @see redraw - * @see draw - * @see loop - */ - p.noLoop = function() { - doLoop = false; - loopStarted = false; - clearInterval(looping); - curSketch.onPause(); - }; - - /** - * Causes Processing to continuously execute the code within draw(). If noLoop() is called, - * the code in draw() stops executing. - * - * @returns none - * - * @see noLoop - */ - p.loop = function() { - if (loopStarted) { - return; - } - - timeSinceLastFPS = Date.now(); - framesSinceLastFPS = 0; - - looping = window.setInterval(function() { - try { - curSketch.onFrameStart(); - p.redraw(); - curSketch.onFrameEnd(); - } catch(e_loop) { - window.clearInterval(looping); - throw e_loop; - } - }, curMsPerFrame); - doLoop = true; - loopStarted = true; - curSketch.onLoop(); - }; - - /** - * Specifies the number of frames to be displayed every second. If the processor is not - * fast enough to maintain the specified rate, it will not be achieved. For example, the - * function call frameRate(30) will attempt to refresh 30 times a second. It is recommended - * to set the frame rate within setup(). The default rate is 60 frames per second. - * - * @param {int} aRate number of frames per second. - * - * @returns none - * - * @see delay - */ - p.frameRate = function(aRate) { - curFrameRate = aRate; - curMsPerFrame = 1000 / curFrameRate; - - // clear and reset interval - if (doLoop) { - p.noLoop(); - p.loop(); - } - }; - - //////////////////////////////////////////////////////////////////////////// - // JavaScript event binding and releasing - //////////////////////////////////////////////////////////////////////////// - - var eventHandlers = []; - - function attachEventHandler(elem, type, fn) { - if (elem.addEventListener) { - elem.addEventListener(type, fn, false); - } else { - elem.attachEvent("on" + type, fn); - } - eventHandlers.push({elem: elem, type: type, fn: fn}); - } - - function detachEventHandler(eventHandler) { - var elem = eventHandler.elem, - type = eventHandler.type, - fn = eventHandler.fn; - if (elem.removeEventListener) { - elem.removeEventListener(type, fn, false); - } else if (elem.detachEvent) { - elem.detachEvent("on" + type, fn); - } - } - - /** - * Quits/stops/exits the program. Programs without a draw() function exit automatically - * after the last line has run, but programs with draw() run continuously until the - * program is manually stopped or exit() is run. - * Rather than terminating immediately, exit() will cause the sketch to exit after draw() - * has completed (or after setup() completes if called during the setup() method). - * - * @returns none - */ - p.exit = function() { - window.clearInterval(looping); - - removeInstance(p.externals.canvas.id); - - // Step through the libraries to detach them - for (var lib in Processing.lib) { - if (Processing.lib.hasOwnProperty(lib)) { - if (Processing.lib[lib].hasOwnProperty("detach")) { - Processing.lib[lib].detach(p); - } - } - } - - var i = eventHandlers.length; - while (i--) { - detachEventHandler(eventHandlers[i]); - } - curSketch.onExit(); - }; - - //////////////////////////////////////////////////////////////////////////// - // MISC functions - //////////////////////////////////////////////////////////////////////////// - - /** - * Sets the cursor to a predefined symbol, an image, or turns it on if already hidden. - * If you are trying to set an image as the cursor, it is recommended to make the size - * 16x16 or 32x32 pixels. It is not possible to load an image as the cursor if you are - * exporting your program for the Web. The values for parameters x and y must be less - * than the dimensions of the image. - * - * @param {MODE} MODE either ARROW, CROSS, HAND, MOVE, TEXT, WAIT - * @param {PImage} image any variable of type PImage - * @param {int} x the horizonal active spot of the cursor - * @param {int} y the vertical active spot of the cursor - * - * @returns none - * - * @see noCursor - */ - p.cursor = function() { - if (arguments.length > 1 || (arguments.length === 1 && arguments[0] instanceof p.PImage)) { - var image = arguments[0], - x, y; - if (arguments.length >= 3) { - x = arguments[1]; - y = arguments[2]; - if (x < 0 || y < 0 || y >= image.height || x >= image.width) { - throw "x and y must be non-negative and less than the dimensions of the image"; - } - } else { - x = image.width >>> 1; - y = image.height >>> 1; - } - - // see https://developer.mozilla.org/en/Using_URL_values_for_the_cursor_property - var imageDataURL = image.toDataURL(); - var style = "url(\"" + imageDataURL + "\") " + x + " " + y + ", default"; - curCursor = curElement.style.cursor = style; - } else if (arguments.length === 1) { - var mode = arguments[0]; - curCursor = curElement.style.cursor = mode; - } else { - curCursor = curElement.style.cursor = oldCursor; - } - }; - - /** - * Hides the cursor from view. - * - * @returns none - * - * @see cursor - */ - p.noCursor = function() { - curCursor = curElement.style.cursor = PConstants.NOCURSOR; - }; - - /** - * Links to a webpage either in the same window or in a new window. The complete URL - * must be specified. - * - * @param {String} href complete url as a String in quotes - * @param {String} target name of the window to load the URL as a string in quotes - * - * @returns none - */ - p.link = function(href, target) { - if (target !== undef) { - window.open(href, target); - } else { - window.location = href; - } - }; - - // PGraphics methods - // These functions exist only for compatibility with P5 - p.beginDraw = nop; - p.endDraw = nop; - - /** - * This function takes content from a canvas and turns it into an ImageData object to be used with a PImage - * - * @returns {ImageData} ImageData object to attach to a PImage (1D array of pixel data) - * - * @see PImage - */ - Drawing2D.prototype.toImageData = function(x, y, w, h) { - x = x !== undef ? x : 0; - y = y !== undef ? y : 0; - w = w !== undef ? w : p.width; - h = h !== undef ? h : p.height; - return curContext.getImageData(x, y, w, h); - }; - - Drawing3D.prototype.toImageData = function(x, y, w, h) { - x = x !== undef ? x : 0; - y = y !== undef ? y : 0; - w = w !== undef ? w : p.width; - h = h !== undef ? h : p.height; - var c = document.createElement("canvas"), - ctx = c.getContext("2d"), - obj = ctx.createImageData(w, h), - uBuff = new Uint8Array(w * h * 4); - curContext.readPixels(x, y, w, h, curContext.RGBA, curContext.UNSIGNED_BYTE, uBuff); - for (var i=0, ul=uBuff.length, obj_data=obj.data; i < ul; i++) { - obj_data[i] = uBuff[(h - 1 - Math.floor(i / 4 / w)) * w * 4 + (i % (w * 4))]; - } - return obj; - }; - - /** - * Displays message in the browser's status area. This is the text area in the lower - * left corner of the browser. The status() function will only work when the - * Processing program is running in a web browser. - * - * @param {String} text any valid String - * - * @returns none - */ - p.status = function(text) { - window.status = text; - }; - - //////////////////////////////////////////////////////////////////////////// - // Binary Functions - //////////////////////////////////////////////////////////////////////////// - - /** - * Converts a byte, char, int, or color to a String containing the equivalent binary - * notation. For example color(0, 102, 153, 255) will convert to the String - * "11111111000000000110011010011001". This function can help make your geeky debugging - * sessions much happier. - * - * @param {byte|char|int|color} num byte, char, int, color: value to convert - * @param {int} numBits number of digits to return - * - * @returns {String} - * - * @see unhex - * @see hex - * @see unbinary - */ - p.binary = function(num, numBits) { - var bit; - if (numBits > 0) { - bit = numBits; - } else if(num instanceof Char) { - bit = 16; - num |= 0; // making it int - } else { - // autodetect, skipping zeros - bit = 32; - while (bit > 1 && !((num >>> (bit - 1)) & 1)) { - bit--; - } - } - var result = ""; - while (bit > 0) { - result += ((num >>> (--bit)) & 1) ? "1" : "0"; - } - return result; - }; - - /** - * Converts a String representation of a binary number to its equivalent integer value. - * For example, unbinary("00001000") will return 8. - * - * @param {String} binaryString String - * - * @returns {Int} - * - * @see hex - * @see binary - * @see unbinary - */ - p.unbinary = function(binaryString) { - var i = binaryString.length - 1, mask = 1, result = 0; - while (i >= 0) { - var ch = binaryString[i--]; - if (ch !== '0' && ch !== '1') { - throw "the value passed into unbinary was not an 8 bit binary number"; - } - if (ch === '1') { - result += mask; - } - mask <<= 1; - } - return result; - }; - - /** - * Number-to-String formatting function. Prepends "plus" or "minus" depending - * on whether the value is positive or negative, respectively, after padding - * the value with zeroes on the left and right, the number of zeroes used dictated - * by the values 'leftDigits' and 'rightDigits'. 'value' cannot be an array. - * - * @param {int|float} value the number to format - * @param {String} plus the prefix for positive numbers - * @param {String} minus the prefix for negative numbers - * @param {int} left number of digits to the left of the decimal point - * @param {int} right number of digits to the right of the decimal point - * @param {String} group string delimited for groups, such as the comma in "1,000" - * - * @returns {String or String[]} - * - * @see nfCore - */ - function nfCoreScalar(value, plus, minus, leftDigits, rightDigits, group) { - var sign = (value < 0) ? minus : plus; - var autoDetectDecimals = rightDigits === 0; - var rightDigitsOfDefault = (rightDigits === undef || rightDigits < 0) ? 0 : rightDigits; - - var absValue = Math.abs(value); - if (autoDetectDecimals) { - rightDigitsOfDefault = 1; - absValue *= 10; - while (Math.abs(Math.round(absValue) - absValue) > 1e-6 && rightDigitsOfDefault < 7) { - ++rightDigitsOfDefault; - absValue *= 10; - } - } else if (rightDigitsOfDefault !== 0) { - absValue *= Math.pow(10, rightDigitsOfDefault); - } - - // Using Java's default rounding policy HALF_EVEN. This policy is based - // on the idea that 0.5 values round to the nearest even number, and - // everything else is rounded normally. - var number, doubled = absValue * 2; - if (Math.floor(absValue) === absValue) { - number = absValue; - } else if (Math.floor(doubled) === doubled) { - var floored = Math.floor(absValue); - number = floored + (floored % 2); - } else { - number = Math.round(absValue); - } - - var buffer = ""; - var totalDigits = leftDigits + rightDigitsOfDefault; - while (totalDigits > 0 || number > 0) { - totalDigits--; - buffer = "" + (number % 10) + buffer; - number = Math.floor(number / 10); - } - if (group !== undef) { - var i = buffer.length - 3 - rightDigitsOfDefault; - while(i > 0) { - buffer = buffer.substring(0,i) + group + buffer.substring(i); - i-=3; - } - } - if (rightDigitsOfDefault > 0) { - return sign + buffer.substring(0, buffer.length - rightDigitsOfDefault) + - "." + buffer.substring(buffer.length - rightDigitsOfDefault, buffer.length); - } - return sign + buffer; - } - - /** - * Number-to-String formatting function. Prepends "plus" or "minus" depending - * on whether the value is positive or negative, respectively, after padding - * the value with zeroes on the left and right, the number of zeroes used dictated - * by the values 'leftDigits' and 'rightDigits'. 'value' can be an array; - * if the input is an array, each value in it is formatted separately, and - * an array with formatted values is returned. - * - * @param {int|int[]|float|float[]} value the number(s) to format - * @param {String} plus the prefix for positive numbers - * @param {String} minus the prefix for negative numbers - * @param {int} left number of digits to the left of the decimal point - * @param {int} right number of digits to the right of the decimal point - * @param {String} group string delimited for groups, such as the comma in "1,000" - * - * @returns {String or String[]} - * - * @see nfCoreScalar - */ - function nfCore(value, plus, minus, leftDigits, rightDigits, group) { - if (value instanceof Array) { - var arr = []; - for (var i = 0, len = value.length; i < len; i++) { - arr.push(nfCoreScalar(value[i], plus, minus, leftDigits, rightDigits, group)); - } - return arr; - } - return nfCoreScalar(value, plus, minus, leftDigits, rightDigits, group); - } - - /** - * Utility function for formatting numbers into strings. There are two versions, one for - * formatting floats and one for formatting ints. The values for the digits, left, and - * right parameters should always be positive integers. - * As shown in the above example, nf() is used to add zeros to the left and/or right - * of a number. This is typically for aligning a list of numbers. To remove digits from - * a floating-point number, use the int(), ceil(), floor(), or round() functions. - * - * @param {int|int[]|float|float[]} value the number(s) to format - * @param {int} left number of digits to the left of the decimal point - * @param {int} right number of digits to the right of the decimal point - * - * @returns {String or String[]} - * - * @see nfs - * @see nfp - * @see nfc - */ - p.nf = function(value, leftDigits, rightDigits) { return nfCore(value, "", "-", leftDigits, rightDigits); }; - - /** - * Utility function for formatting numbers into strings. Similar to nf() but leaves a blank space in front - * of positive numbers so they align with negative numbers in spite of the minus symbol. There are two - * versions, one for formatting floats and one for formatting ints. The values for the digits, left, - * and right parameters should always be positive integers. - * - * @param {int|int[]|float|float[]} value the number(s) to format - * @param {int} left number of digits to the left of the decimal point - * @param {int} right number of digits to the right of the decimal point - * - * @returns {String or String[]} - * - * @see nf - * @see nfp - * @see nfc - */ - p.nfs = function(value, leftDigits, rightDigits) { return nfCore(value, " ", "-", leftDigits, rightDigits); }; - - /** - * Utility function for formatting numbers into strings. Similar to nf() but puts a "+" in front of - * positive numbers and a "-" in front of negative numbers. There are two versions, one for formatting - * floats and one for formatting ints. The values for the digits, left, and right parameters should - * always be positive integers. - * - * @param {int|int[]|float|float[]} value the number(s) to format - * @param {int} left number of digits to the left of the decimal point - * @param {int} right number of digits to the right of the decimal point - * - * @returns {String or String[]} - * - * @see nfs - * @see nf - * @see nfc - */ - p.nfp = function(value, leftDigits, rightDigits) { return nfCore(value, "+", "-", leftDigits, rightDigits); }; - - /** - * Utility function for formatting numbers into strings and placing appropriate commas to mark - * units of 1000. There are two versions, one for formatting ints and one for formatting an array - * of ints. The value for the digits parameter should always be a positive integer. - * - * @param {int|int[]|float|float[]} value the number(s) to format - * @param {int} left number of digits to the left of the decimal point - * @param {int} right number of digits to the right of the decimal point - * - * @returns {String or String[]} - * - * @see nf - * @see nfs - * @see nfp - */ - p.nfc = function(value, leftDigits, rightDigits) { return nfCore(value, "", "-", leftDigits, rightDigits, ","); }; - - var decimalToHex = function(d, padding) { - //if there is no padding value added, default padding to 8 else go into while statement. - padding = (padding === undef || padding === null) ? padding = 8 : padding; - if (d < 0) { - d = 0xFFFFFFFF + d + 1; - } - var hex = Number(d).toString(16).toUpperCase(); - while (hex.length < padding) { - hex = "0" + hex; - } - if (hex.length >= padding) { - hex = hex.substring(hex.length - padding, hex.length); - } - return hex; - }; - - // note: since we cannot keep track of byte, int types by default the returned string is 8 chars long - // if no 2nd argument is passed. closest compromise we can use to match java implementation Feb 5 2010 - // also the char parser has issues with chars that are not digits or letters IE: !@#$%^&* - /** - * Converts a byte, char, int, or color to a String containing the equivalent hexadecimal notation. - * For example color(0, 102, 153, 255) will convert to the String "FF006699". This function can help - * make your geeky debugging sessions much happier. - * - * @param {byte|char|int|Color} value the value to turn into a hex string - * @param {int} digits the number of digits to return - * - * @returns {String} - * - * @see unhex - * @see binary - * @see unbinary - */ - p.hex = function(value, len) { - if (arguments.length === 1) { - if (value instanceof Char) { - len = 4; - } else { // int or byte, indistinguishable at the moment, default to 8 - len = 8; - } - } - return decimalToHex(value, len); - }; - - function unhexScalar(hex) { - var value = parseInt("0x" + hex, 16); - - // correct for int overflow java expectation - if (value > 2147483647) { - value -= 4294967296; - } - return value; - } - - /** - * Converts a String representation of a hexadecimal number to its equivalent integer value. - * - * @param {String} hex the hex string to convert to an int - * - * @returns {int} - * - * @see hex - * @see binary - * @see unbinary - */ - p.unhex = function(hex) { - if (hex instanceof Array) { - var arr = []; - for (var i = 0; i < hex.length; i++) { - arr.push(unhexScalar(hex[i])); - } - return arr; - } - return unhexScalar(hex); - }; - - // Load a file or URL into strings - /** - * Reads the contents of a file or url and creates a String array of its individual lines. - * The filename parameter can also be a URL to a file found online. If the file is not available or an error occurs, - * null will be returned and an error message will be printed to the console. The error message does not halt - * the program. - * - * @param {String} filename name of the file or url to load - * - * @returns {String[]} - * - * @see loadBytes - * @see saveStrings - * @see saveBytes - */ - p.loadStrings = function(filename) { - if (localStorage[filename]) { - return localStorage[filename].split("\n"); - } - - var filecontent = ajax(filename); - if(typeof filecontent !== "string" || filecontent === "") { - return []; - } - - // deal with the fact that Windows uses \r\n, Unix uses \n, - // Mac uses \r, and we actually expect \n - filecontent = filecontent.replace(/(\r\n?)/g,"\n").replace(/\n$/,""); - - return filecontent.split("\n"); - }; - - // Writes an array of strings to a file, one line per string - /** - * Writes an array of strings to a file, one line per string. This file is saved to the localStorage. - * - * @param {String} filename name of the file to save to localStorage - * @param {String[]} strings string array to be written - * - * @see loadBytes - * @see loadStrings - * @see saveBytes - */ - p.saveStrings = function(filename, strings) { - localStorage[filename] = strings.join('\n'); - }; - - /** - * Reads the contents of a file or url and places it in a byte array. If a file is specified, it must be located in the localStorage. - * The filename parameter can also be a URL to a file found online. - * - * @param {String} filename name of a file in the localStorage or a URL. - * - * @returns {byte[]} - * - * @see loadStrings - * @see saveStrings - * @see saveBytes - */ - p.loadBytes = function(url) { - var string = ajax(url); - var ret = []; - - for (var i = 0; i < string.length; i++) { - ret.push(string.charCodeAt(i)); - } - - return ret; - }; - - /** - * Removes the first argument from the arguments set -- shifts. - * - * @param {Arguments} args The Arguments object. - * - * @return {Object[]} Returns an array of arguments except first one. - * - * @see #match - */ - function removeFirstArgument(args) { - return Array.prototype.slice.call(args, 1); - } - - //////////////////////////////////////////////////////////////////////////// - // String Functions - //////////////////////////////////////////////////////////////////////////// - /** - * The matchAll() function is identical to match(), except that it returns an array of all matches in - * the specified String, rather than just the first. - * - * @param {String} aString the String to search inside - * @param {String} aRegExp the regexp to be used for matching - * - * @return {String[]} returns an array of matches - * - * @see #match - */ - p.matchAll = function(aString, aRegExp) { - var results = [], - latest; - var regexp = new RegExp(aRegExp, "g"); - while ((latest = regexp.exec(aString)) !== null) { - results.push(latest); - if (latest[0].length === 0) { - ++regexp.lastIndex; - } - } - return results.length > 0 ? results : null; - }; - /** - * The contains(string) function returns true if the string passed in the parameter - * is a substring of this string. It returns false if the string passed - * in the parameter is not a substring of this string. - * - * @param {String} The string to look for in the current string - * - * @return {boolean} returns true if this string contains - * the string passed as parameter. returns false, otherwise. - * - */ - p.__contains = function (subject, subStr) { - if (typeof subject !== "string") { - return subject.contains.apply(subject, removeFirstArgument(arguments)); - } - //Parameter is not null AND - //The type of the parameter is the same as this object (string) - //The javascript function that finds a substring returns 0 or higher - return ( - (subject !== null) && - (subStr !== null) && - (typeof subStr === "string") && - (subject.indexOf(subStr) > -1) - ); - }; - /** - * The __replaceAll() function searches all matches between a substring (or regular expression) and a string, - * and replaces the matched substring with a new substring - * - * @param {String} subject a substring - * @param {String} regex a substring or a regular expression - * @param {String} replace the string to replace the found value - * - * @return {String} returns result - * - * @see #match - */ - p.__replaceAll = function(subject, regex, replacement) { - if (typeof subject !== "string") { - return subject.replaceAll.apply(subject, removeFirstArgument(arguments)); - } - - return subject.replace(new RegExp(regex, "g"), replacement); - }; - /** - * The __replaceFirst() function searches first matche between a substring (or regular expression) and a string, - * and replaces the matched substring with a new substring - * - * @param {String} subject a substring - * @param {String} regex a substring or a regular expression - * @param {String} replace the string to replace the found value - * - * @return {String} returns result - * - * @see #match - */ - p.__replaceFirst = function(subject, regex, replacement) { - if (typeof subject !== "string") { - return subject.replaceFirst.apply(subject, removeFirstArgument(arguments)); - } - - return subject.replace(new RegExp(regex, ""), replacement); - }; - /** - * The __replace() function searches all matches between a substring and a string, - * and replaces the matched substring with a new substring - * - * @param {String} subject a substring - * @param {String} what a substring to find - * @param {String} replacement the string to replace the found value - * - * @return {String} returns result - */ - p.__replace = function(subject, what, replacement) { - if (typeof subject !== "string") { - return subject.replace.apply(subject, removeFirstArgument(arguments)); - } - if (what instanceof RegExp) { - return subject.replace(what, replacement); - } - - if (typeof what !== "string") { - what = what.toString(); - } - if (what === "") { - return subject; - } - - var i = subject.indexOf(what); - if (i < 0) { - return subject; - } - - var j = 0, result = ""; - do { - result += subject.substring(j, i) + replacement; - j = i + what.length; - } while ( (i = subject.indexOf(what, j)) >= 0); - return result + subject.substring(j); - }; - /** - * The __equals() function compares two strings (or objects) to see if they are the same. - * This method is necessary because it's not possible to compare strings using the equality operator (==). - * Returns true if the strings are the same and false if they are not. - * - * @param {String} subject a string used for comparison - * @param {String} other a string used for comparison with - * - * @return {boolean} true is the strings are the same false otherwise - */ - p.__equals = function(subject, other) { - if (subject.equals instanceof Function) { - return subject.equals.apply(subject, removeFirstArgument(arguments)); - } - - // TODO use virtEquals for HashMap here - return subject.valueOf() === other.valueOf(); - }; - /** - * The __equalsIgnoreCase() function compares two strings to see if they are the same. - * Returns true if the strings are the same, either when forced to all lower case or - * all upper case. - * - * @param {String} subject a string used for comparison - * @param {String} other a string used for comparison with - * - * @return {boolean} true is the strings are the same, ignoring case. false otherwise - */ - p.__equalsIgnoreCase = function(subject, other) { - if (typeof subject !== "string") { - return subject.equalsIgnoreCase.apply(subject, removeFirstArgument(arguments)); - } - - return subject.toLowerCase() === other.toLowerCase(); - }; - /** - * The __toCharArray() function splits the string into a char array. - * - * @param {String} subject The string - * - * @return {Char[]} a char array - */ - p.__toCharArray = function(subject) { - if (typeof subject !== "string") { - return subject.toCharArray.apply(subject, removeFirstArgument(arguments)); - } - - var chars = []; - for (var i = 0, len = subject.length; i < len; ++i) { - chars[i] = new Char(subject.charAt(i)); - } - return chars; - }; - /** - * The __split() function splits a string using the regex delimiter - * specified. If limit is specified, the resultant array will have number - * of elements equal to or less than the limit. - * - * @param {String} subject string to be split - * @param {String} regexp regex string used to split the subject - * @param {int} limit max number of tokens to be returned - * - * @return {String[]} an array of tokens from the split string - */ - p.__split = function(subject, regex, limit) { - if (typeof subject !== "string") { - return subject.split.apply(subject, removeFirstArgument(arguments)); - } - - var pattern = new RegExp(regex); - - // If limit is not specified, use JavaScript's built-in String.split. - if ((limit === undef) || (limit < 1)) { - return subject.split(pattern); - } - - // If limit is specified, JavaScript's built-in String.split has a - // different behaviour than Java's. A Java-compatible implementation is - // provided here. - var result = [], currSubject = subject, pos; - while (((pos = currSubject.search(pattern)) !== -1) - && (result.length < (limit - 1))) { - var match = pattern.exec(currSubject).toString(); - result.push(currSubject.substring(0, pos)); - currSubject = currSubject.substring(pos + match.length); - } - if ((pos !== -1) || (currSubject !== "")) { - result.push(currSubject); - } - return result; - }; - /** - * The codePointAt() function returns the unicode value of the character at a given index of a string. - * - * @param {int} idx the index of the character - * - * @return {String} code the String containing the unicode value of the character - */ - p.__codePointAt = function(subject, idx) { - var code = subject.charCodeAt(idx), - hi, - low; - if (0xD800 <= code && code <= 0xDBFF) { - hi = code; - low = subject.charCodeAt(idx + 1); - return ((hi - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000; - } - return code; - }; - /** - * The match() function matches a string with a regular expression, and returns the match as an - * array. The first index is the matching expression, and array elements - * [1] and higher represent each of the groups (sequences found in parens). - * - * @param {String} str the String to be searched - * @param {String} regexp the regexp to be used for matching - * - * @return {String[]} an array of matching strings - */ - p.match = function(str, regexp) { - return str.match(regexp); - }; - /** - * The startsWith() function tests if a string starts with the specified prefix. If the prefix - * is the empty String or equal to the subject String, startsWith() will also return true. - * - * @param {String} prefix the String used to compare against the start of the subject String. - * @param {int} toffset (optional) an offset into the subject String where searching should begin. - * - * @return {boolean} true if the subject String starts with the prefix. - */ - p.__startsWith = function(subject, prefix, toffset) { - if (typeof subject !== "string") { - return subject.startsWith.apply(subject, removeFirstArgument(arguments)); - } - - toffset = toffset || 0; - if (toffset < 0 || toffset > subject.length) { - return false; - } - return (prefix === '' || prefix === subject) ? true : (subject.indexOf(prefix) === toffset); - }; - /** - * The endsWith() function tests if a string ends with the specified suffix. If the suffix - * is the empty String, endsWith() will also return true. - * - * @param {String} suffix the String used to compare against the end of the subject String. - * - * @return {boolean} true if the subject String starts with the prefix. - */ - p.__endsWith = function(subject, suffix) { - if (typeof subject !== "string") { - return subject.endsWith.apply(subject, removeFirstArgument(arguments)); - } - - var suffixLen = suffix ? suffix.length : 0; - return (suffix === '' || suffix === subject) ? true : - (subject.indexOf(suffix) === subject.length - suffixLen); - }; - - //////////////////////////////////////////////////////////////////////////// - // Other java specific functions - //////////////////////////////////////////////////////////////////////////// - - /** - * The returns hash code of the. - * - * @param {Object} subject The string - * - * @return {int} a hash code - */ - p.__hashCode = function(subject) { - if (subject.hashCode instanceof Function) { - return subject.hashCode.apply(subject, removeFirstArgument(arguments)); - } - return virtHashCode(subject); - }; - /** - * The __printStackTrace() prints stack trace to the console. - * - * @param {Exception} subject The error - */ - p.__printStackTrace = function(subject) { - p.println("Exception: " + subject.toString() ); - }; - - var logBuffer = []; - - /** - * The println() function writes to the console area of the Processing environment. - * Each call to this function creates a new line of output. Individual elements can be separated with quotes ("") and joined with the string concatenation operator (+). - * - * @param {String} message the string to write to the console - * - * @see #join - * @see #print - */ - p.println = function(message) { - var bufferLen = logBuffer.length; - if (bufferLen) { - Processing.logger.log(logBuffer.join("")); - logBuffer.length = 0; // clear log buffer - } - - if (arguments.length === 0 && bufferLen === 0) { - Processing.logger.log(""); - } else if (arguments.length !== 0) { - Processing.logger.log(message); - } - }; - /** - * The print() function writes to the console area of the Processing environment. - * - * @param {String} message the string to write to the console - * - * @see #join - */ - p.print = function(message) { - logBuffer.push(message); - }; - - // Alphanumeric chars arguments automatically converted to numbers when - // passed in, and will come out as numbers. - p.str = function(val) { - if (val instanceof Array) { - var arr = []; - for (var i = 0; i < val.length; i++) { - arr.push(val[i].toString() + ""); - } - return arr; - } - return (val.toString() + ""); - }; - /** - * Remove whitespace characters from the beginning and ending - * of a String or a String array. Works like String.trim() but includes the - * unicode nbsp character as well. If an array is passed in the function will return a new array not effecting the array passed in. - * - * @param {String} str the string to trim - * @param {String[]} str the string array to trim - * - * @return {String|String[]} retrurns a string or an array will removed whitespaces - */ - p.trim = function(str) { - if (str instanceof Array) { - var arr = []; - for (var i = 0; i < str.length; i++) { - arr.push(str[i].replace(/^\s*/, '').replace(/\s*$/, '').replace(/\r*$/, '')); - } - return arr; - } - return str.replace(/^\s*/, '').replace(/\s*$/, '').replace(/\r*$/, ''); - }; - - // Conversion - function booleanScalar(val) { - if (typeof val === 'number') { - return val !== 0; - } - if (typeof val === 'boolean') { - return val; - } - if (typeof val === 'string') { - return val.toLowerCase() === 'true'; - } - if (val instanceof Char) { - // 1, T or t - return val.code === 49 || val.code === 84 || val.code === 116; - } - } - - /** - * Converts the passed parameter to the function to its boolean value. - * It will return an array of booleans if an array is passed in. - * - * @param {int, byte, string} val the parameter to be converted to boolean - * @param {int[], byte[], string[]} val the array to be converted to boolean[] - * - * @return {boolean|boolean[]} returns a boolean or an array of booleans - */ - p.parseBoolean = function (val) { - if (val instanceof Array) { - var ret = []; - for (var i = 0; i < val.length; i++) { - ret.push(booleanScalar(val[i])); - } - return ret; - } - return booleanScalar(val); - }; - - /** - * Converts the passed parameter to the function to its byte value. - * A byte is a number between -128 and 127. - * It will return an array of bytes if an array is passed in. - * - * @param {int, char} what the parameter to be conveted to byte - * @param {int[], char[]} what the array to be converted to byte[] - * - * @return {byte|byte[]} returns a byte or an array of bytes - */ - p.parseByte = function(what) { - if (what instanceof Array) { - var bytes = []; - for (var i = 0; i < what.length; i++) { - bytes.push((0 - (what[i] & 0x80)) | (what[i] & 0x7F)); - } - return bytes; - } - return (0 - (what & 0x80)) | (what & 0x7F); - }; - - /** - * Converts the passed parameter to the function to its char value. - * It will return an array of chars if an array is passed in. - * - * @param {int, byte} key the parameter to be conveted to char - * @param {int[], byte[]} key the array to be converted to char[] - * - * @return {char|char[]} returns a char or an array of chars - */ - p.parseChar = function(key) { - if (typeof key === "number") { - return new Char(String.fromCharCode(key & 0xFFFF)); - } - if (key instanceof Array) { - var ret = []; - for (var i = 0; i < key.length; i++) { - ret.push(new Char(String.fromCharCode(key[i] & 0xFFFF))); - } - return ret; - } - throw "char() may receive only one argument of type int, byte, int[], or byte[]."; - }; - - // Processing doc claims good argument types are: int, char, byte, boolean, - // String, int[], char[], byte[], boolean[], String[]. - // floats should not work. However, floats with only zeroes right of the - // decimal will work because JS converts those to int. - function floatScalar(val) { - if (typeof val === 'number') { - return val; - } - if (typeof val === 'boolean') { - return val ? 1 : 0; - } - if (typeof val === 'string') { - return parseFloat(val); - } - if (val instanceof Char) { - return val.code; - } - } - - /** - * Converts the passed parameter to the function to its float value. - * It will return an array of floats if an array is passed in. - * - * @param {int, char, boolean, string} val the parameter to be conveted to float - * @param {int[], char[], boolean[], string[]} val the array to be converted to float[] - * - * @return {float|float[]} returns a float or an array of floats - */ - p.parseFloat = function(val) { - if (val instanceof Array) { - var ret = []; - for (var i = 0; i < val.length; i++) { - ret.push(floatScalar(val[i])); - } - return ret; - } - return floatScalar(val); - }; - - function intScalar(val, radix) { - if (typeof val === 'number') { - return val & 0xFFFFFFFF; - } - if (typeof val === 'boolean') { - return val ? 1 : 0; - } - if (typeof val === 'string') { - var number = parseInt(val, radix || 10); // Default to decimal radix. - return number & 0xFFFFFFFF; - } - if (val instanceof Char) { - return val.code; - } - } - - /** - * Converts the passed parameter to the function to its int value. - * It will return an array of ints if an array is passed in. - * - * @param {string, char, boolean, float} val the parameter to be conveted to int - * @param {string[], char[], boolean[], float[]} val the array to be converted to int[] - * @param {int} radix optional the radix of the number (for js compatibility) - * - * @return {int|int[]} returns a int or an array of ints - */ - p.parseInt = function(val, radix) { - if (val instanceof Array) { - var ret = []; - for (var i = 0; i < val.length; i++) { - if (typeof val[i] === 'string' && !/^\s*[+\-]?\d+\s*$/.test(val[i])) { - ret.push(0); - } else { - ret.push(intScalar(val[i], radix)); - } - } - return ret; - } - return intScalar(val, radix); - }; - - p.__int_cast = function(val) { - return 0|val; - }; - - p.__instanceof = function(obj, type) { - if (typeof type !== "function") { - throw "Function is expected as type argument for instanceof operator"; - } - - if (typeof obj === "string") { - // special case for strings - return type === Object || type === String; - } - - if (obj instanceof type) { - // fast check if obj is already of type instance - return true; - } - - if (typeof obj !== "object" || obj === null) { - return false; // not an object or null - } - - var objType = obj.constructor; - if (type.$isInterface) { - // expecting the interface - // queueing interfaces from type and its base classes - var interfaces = []; - while (objType) { - if (objType.$interfaces) { - interfaces = interfaces.concat(objType.$interfaces); - } - objType = objType.$base; - } - while (interfaces.length > 0) { - var i = interfaces.shift(); - if (i === type) { - return true; - } - // wide search in base interfaces - if (i.$interfaces) { - interfaces = interfaces.concat(i.$interfaces); - } - } - return false; - } - - while (objType.hasOwnProperty("$base")) { - objType = objType.$base; - if (objType === type) { - return true; // object was found - } - } - - return false; - }; - - //////////////////////////////////////////////////////////////////////////// - // Math functions - //////////////////////////////////////////////////////////////////////////// - - // Calculation - /** - * Calculates the absolute value (magnitude) of a number. The absolute value of a number is always positive. - * - * @param {int|float} value int or float - * - * @returns {int|float} - */ - p.abs = Math.abs; - - /** - * Calculates the closest int value that is greater than or equal to the value of the parameter. - * For example, ceil(9.03) returns the value 10. - * - * @param {float} value float - * - * @returns {int} - * - * @see floor - * @see round - */ - p.ceil = Math.ceil; - - /** - * Constrains a value to not exceed a maximum and minimum value. - * - * @param {int|float} value the value to constrain - * @param {int|float} value minimum limit - * @param {int|float} value maximum limit - * - * @returns {int|float} - * - * @see max - * @see min - */ - p.constrain = function(aNumber, aMin, aMax) { - return aNumber > aMax ? aMax : aNumber < aMin ? aMin : aNumber; - }; - - /** - * Calculates the distance between two points. - * - * @param {int|float} x1 int or float: x-coordinate of the first point - * @param {int|float} y1 int or float: y-coordinate of the first point - * @param {int|float} z1 int or float: z-coordinate of the first point - * @param {int|float} x2 int or float: x-coordinate of the second point - * @param {int|float} y2 int or float: y-coordinate of the second point - * @param {int|float} z2 int or float: z-coordinate of the second point - * - * @returns {float} - */ - p.dist = function() { - var dx, dy, dz; - if (arguments.length === 4) { - dx = arguments[0] - arguments[2]; - dy = arguments[1] - arguments[3]; - return Math.sqrt(dx * dx + dy * dy); - } - if (arguments.length === 6) { - dx = arguments[0] - arguments[3]; - dy = arguments[1] - arguments[4]; - dz = arguments[2] - arguments[5]; - return Math.sqrt(dx * dx + dy * dy + dz * dz); - } - }; - - /** - * Returns Euler's number e (2.71828...) raised to the power of the value parameter. - * - * @param {int|float} value int or float: the exponent to raise e to - * - * @returns {float} - */ - p.exp = Math.exp; - - /** - * Calculates the closest int value that is less than or equal to the value of the parameter. - * - * @param {int|float} value the value to floor - * - * @returns {int|float} - * - * @see ceil - * @see round - */ - p.floor = Math.floor; - - /** - * Calculates a number between two numbers at a specific increment. The amt parameter is the - * amount to interpolate between the two values where 0.0 equal to the first point, 0.1 is very - * near the first point, 0.5 is half-way in between, etc. The lerp function is convenient for - * creating motion along a straight path and for drawing dotted lines. - * - * @param {int|float} value1 float or int: first value - * @param {int|float} value2 float or int: second value - * @param {int|float} amt float: between 0.0 and 1.0 - * - * @returns {float} - * - * @see curvePoint - * @see bezierPoint - */ - p.lerp = function(value1, value2, amt) { - return ((value2 - value1) * amt) + value1; - }; - - /** - * Calculates the natural logarithm (the base-e logarithm) of a number. This function - * expects the values greater than 0.0. - * - * @param {int|float} value int or float: number must be greater then 0.0 - * - * @returns {float} - */ - p.log = Math.log; - - /** - * Calculates the magnitude (or length) of a vector. A vector is a direction in space commonly - * used in computer graphics and linear algebra. Because it has no "start" position, the magnitude - * of a vector can be thought of as the distance from coordinate (0,0) to its (x,y) value. - * Therefore, mag() is a shortcut for writing "dist(0, 0, x, y)". - * - * @param {int|float} a float or int: first value - * @param {int|float} b float or int: second value - * @param {int|float} c float or int: third value - * - * @returns {float} - * - * @see dist - */ - p.mag = function(a, b, c) { - if (c) { - return Math.sqrt(a * a + b * b + c * c); - } - - return Math.sqrt(a * a + b * b); - }; - - /** - * Re-maps a number from one range to another. In the example above, the number '25' is converted from - * a value in the range 0..100 into a value that ranges from the left edge (0) to the right edge (width) of the screen. - * Numbers outside the range are not clamped to 0 and 1, because out-of-range values are often intentional and useful. - * - * @param {float} value The incoming value to be converted - * @param {float} istart Lower bound of the value's current range - * @param {float} istop Upper bound of the value's current range - * @param {float} ostart Lower bound of the value's target range - * @param {float} ostop Upper bound of the value's target range - * - * @returns {float} - * - * @see norm - * @see lerp - */ - p.map = function(value, istart, istop, ostart, ostop) { - return ostart + (ostop - ostart) * ((value - istart) / (istop - istart)); - }; - - /** - * Determines the largest value in a sequence of numbers. - * - * @param {int|float} value1 int or float - * @param {int|float} value2 int or float - * @param {int|float} value3 int or float - * @param {int|float} array int or float array - * - * @returns {int|float} - * - * @see min - */ - p.max = function() { - if (arguments.length === 2) { - return arguments[0] < arguments[1] ? arguments[1] : arguments[0]; - } - var numbers = arguments.length === 1 ? arguments[0] : arguments; // if single argument, array is used - if (! ("length" in numbers && numbers.length > 0)) { - throw "Non-empty array is expected"; - } - var max = numbers[0], - count = numbers.length; - for (var i = 1; i < count; ++i) { - if (max < numbers[i]) { - max = numbers[i]; - } - } - return max; - }; - - /** - * Determines the smallest value in a sequence of numbers. - * - * @param {int|float} value1 int or float - * @param {int|float} value2 int or float - * @param {int|float} value3 int or float - * @param {int|float} array int or float array - * - * @returns {int|float} - * - * @see max - */ - p.min = function() { - if (arguments.length === 2) { - return arguments[0] < arguments[1] ? arguments[0] : arguments[1]; - } - var numbers = arguments.length === 1 ? arguments[0] : arguments; // if single argument, array is used - if (! ("length" in numbers && numbers.length > 0)) { - throw "Non-empty array is expected"; - } - var min = numbers[0], - count = numbers.length; - for (var i = 1; i < count; ++i) { - if (min > numbers[i]) { - min = numbers[i]; - } - } - return min; - }; - - /** - * Normalizes a number from another range into a value between 0 and 1. - * Identical to map(value, low, high, 0, 1); - * Numbers outside the range are not clamped to 0 and 1, because out-of-range - * values are often intentional and useful. - * - * @param {float} aNumber The incoming value to be converted - * @param {float} low Lower bound of the value's current range - * @param {float} high Upper bound of the value's current range - * - * @returns {float} - * - * @see map - * @see lerp - */ - p.norm = function(aNumber, low, high) { - return (aNumber - low) / (high - low); - }; - - /** - * Facilitates exponential expressions. The pow() function is an efficient way of - * multiplying numbers by themselves (or their reciprocal) in large quantities. - * For example, pow(3, 5) is equivalent to the expression 3*3*3*3*3 and pow(3, -5) - * is equivalent to 1 / 3*3*3*3*3. - * - * @param {int|float} num base of the exponential expression - * @param {int|float} exponent power of which to raise the base - * - * @returns {float} - * - * @see sqrt - */ - p.pow = Math.pow; - - /** - * Calculates the integer closest to the value parameter. For example, round(9.2) returns the value 9. - * - * @param {float} value number to round - * - * @returns {int} - * - * @see floor - * @see ceil - */ - p.round = Math.round; - - /** - * Squares a number (multiplies a number by itself). The result is always a positive number, - * as multiplying two negative numbers always yields a positive result. For example, -1 * -1 = 1. - * - * @param {float} value int or float - * - * @returns {float} - * - * @see sqrt - */ - p.sq = function(aNumber) { - return aNumber * aNumber; - }; - - /** - * Calculates the square root of a number. The square root of a number is always positive, - * even though there may be a valid negative root. The square root s of number a is such - * that s*s = a. It is the opposite of squaring. - * - * @param {float} value int or float, non negative - * - * @returns {float} - * - * @see pow - * @see sq - */ - p.sqrt = Math.sqrt; - - // Trigonometry - /** - * The inverse of cos(), returns the arc cosine of a value. This function expects the - * values in the range of -1 to 1 and values are returned in the range 0 to PI (3.1415927). - * - * @param {float} value the value whose arc cosine is to be returned - * - * @returns {float} - * - * @see cos - * @see asin - * @see atan - */ - p.acos = Math.acos; - - /** - * The inverse of sin(), returns the arc sine of a value. This function expects the values - * in the range of -1 to 1 and values are returned in the range -PI/2 to PI/2. - * - * @param {float} value the value whose arc sine is to be returned - * - * @returns {float} - * - * @see sin - * @see acos - * @see atan - */ - p.asin = Math.asin; - - /** - * The inverse of tan(), returns the arc tangent of a value. This function expects the values - * in the range of -Infinity to Infinity (exclusive) and values are returned in the range -PI/2 to PI/2 . - * - * @param {float} value -Infinity to Infinity (exclusive) - * - * @returns {float} - * - * @see tan - * @see asin - * @see acos - */ - p.atan = Math.atan; - - /** - * Calculates the angle (in radians) from a specified point to the coordinate origin as measured from - * the positive x-axis. Values are returned as a float in the range from PI to -PI. The atan2() function - * is most often used for orienting geometry to the position of the cursor. Note: The y-coordinate of the - * point is the first parameter and the x-coordinate is the second due the the structure of calculating the tangent. - * - * @param {float} y y-coordinate of the point - * @param {float} x x-coordinate of the point - * - * @returns {float} - * - * @see tan - */ - p.atan2 = Math.atan2; - - /** - * Calculates the cosine of an angle. This function expects the values of the angle parameter to be provided - * in radians (values from 0 to PI*2). Values are returned in the range -1 to 1. - * - * @param {float} value an angle in radians - * - * @returns {float} - * - * @see tan - * @see sin - */ - p.cos = Math.cos; - - /** - * Converts a radian measurement to its corresponding value in degrees. Radians and degrees are two ways of - * measuring the same thing. There are 360 degrees in a circle and 2*PI radians in a circle. For example, - * 90 degrees = PI/2 = 1.5707964. All trigonometric methods in Processing require their parameters to be specified in radians. - * - * @param {int|float} value an angle in radians - * - * @returns {float} - * - * @see radians - */ - p.degrees = function(aAngle) { - return (aAngle * 180) / Math.PI; - }; - - /** - * Converts a degree measurement to its corresponding value in radians. Radians and degrees are two ways of - * measuring the same thing. There are 360 degrees in a circle and 2*PI radians in a circle. For example, - * 90 degrees = PI/2 = 1.5707964. All trigonometric methods in Processing require their parameters to be specified in radians. - * - * @param {int|float} value an angle in radians - * - * @returns {float} - * - * @see degrees - */ - p.radians = function(aAngle) { - return (aAngle / 180) * Math.PI; - }; - - /** - * Calculates the sine of an angle. This function expects the values of the angle parameter to be provided in - * radians (values from 0 to 6.28). Values are returned in the range -1 to 1. - * - * @param {float} value an angle in radians - * - * @returns {float} - * - * @see cos - * @see radians - */ - p.sin = Math.sin; - - /** - * Calculates the ratio of the sine and cosine of an angle. This function expects the values of the angle - * parameter to be provided in radians (values from 0 to PI*2). Values are returned in the range infinity to -infinity. - * - * @param {float} value an angle in radians - * - * @returns {float} - * - * @see cos - * @see sin - * @see radians - */ - p.tan = Math.tan; - - var currentRandom = Math.random; - - /** - * Generates random numbers. Each time the random() function is called, it returns an unexpected value within - * the specified range. If one parameter is passed to the function it will return a float between zero and the - * value of the high parameter. The function call random(5) returns values between 0 and 5 (starting at zero, - * up to but not including 5). If two parameters are passed, it will return a float with a value between the - * parameters. The function call random(-5, 10.2) returns values starting at -5 up to (but not including) 10.2. - * To convert a floating-point random number to an integer, use the int() function. - * - * @param {int|float} value1 if one parameter is used, the top end to random from, if two params the low end - * @param {int|float} value2 the top end of the random range - * - * @returns {float} - * - * @see randomSeed - * @see noise - */ - p.random = function() { - if(arguments.length === 0) { - return currentRandom(); - } - if(arguments.length === 1) { - return currentRandom() * arguments[0]; - } - var aMin = arguments[0], aMax = arguments[1]; - return currentRandom() * (aMax - aMin) + aMin; - }; - - // Pseudo-random generator - function Marsaglia(i1, i2) { - // from http://www.math.uni-bielefeld.de/~sillke/ALGORITHMS/random/marsaglia-c - var z=i1 || 362436069, w= i2 || 521288629; - var nextInt = function() { - z=(36969*(z&65535)+(z>>>16)) & 0xFFFFFFFF; - w=(18000*(w&65535)+(w>>>16)) & 0xFFFFFFFF; - return (((z&0xFFFF)<<16) | (w&0xFFFF)) & 0xFFFFFFFF; - }; - - this.nextDouble = function() { - var i = nextInt() / 4294967296; - return i < 0 ? 1 + i : i; - }; - this.nextInt = nextInt; - } - Marsaglia.createRandomized = function() { - var now = new Date(); - return new Marsaglia((now / 60000) & 0xFFFFFFFF, now & 0xFFFFFFFF); - }; - - /** - * Sets the seed value for random(). By default, random() produces different results each time the - * program is run. Set the value parameter to a constant to return the same pseudo-random numbers - * each time the software is run. - * - * @param {int|float} seed int - * - * @see random - * @see noise - * @see noiseSeed - */ - p.randomSeed = function(seed) { - currentRandom = (new Marsaglia(seed)).nextDouble; - }; - - // Random - // We have two random()'s in the code... what does this do ? and which one is current ? - p.Random = function(seed) { - var haveNextNextGaussian = false, nextNextGaussian, random; - - this.nextGaussian = function() { - if (haveNextNextGaussian) { - haveNextNextGaussian = false; - return nextNextGaussian; - } - var v1, v2, s; - do { - v1 = 2 * random() - 1; // between -1.0 and 1.0 - v2 = 2 * random() - 1; // between -1.0 and 1.0 - s = v1 * v1 + v2 * v2; - } - while (s >= 1 || s === 0); - - var multiplier = Math.sqrt(-2 * Math.log(s) / s); - nextNextGaussian = v2 * multiplier; - haveNextNextGaussian = true; - - return v1 * multiplier; - }; - - // by default use standard random, otherwise seeded - random = (seed === undef) ? Math.random : (new Marsaglia(seed)).nextDouble; - }; - - // Noise functions and helpers - function PerlinNoise(seed) { - var rnd = seed !== undef ? new Marsaglia(seed) : Marsaglia.createRandomized(); - var i, j; - // http://www.noisemachine.com/talk1/17b.html - // http://mrl.nyu.edu/~perlin/noise/ - // generate permutation - var perm = new Uint8Array(512); - for(i=0;i<256;++i) { perm[i] = i; } - for(i=0;i<256;++i) { var t = perm[j = rnd.nextInt() & 0xFF]; perm[j] = perm[i]; perm[i] = t; } - // copy to avoid taking mod in perm[0]; - for(i=0;i<256;++i) { perm[i + 256] = perm[i]; } - - function grad3d(i,x,y,z) { - var h = i & 15; // convert into 12 gradient directions - var u = h<8 ? x : y, - v = h<4 ? y : h===12||h===14 ? x : z; - return ((h&1) === 0 ? u : -u) + ((h&2) === 0 ? v : -v); - } - - function grad2d(i,x,y) { - var v = (i & 1) === 0 ? x : y; - return (i&2) === 0 ? -v : v; - } - - function grad1d(i,x) { - return (i&1) === 0 ? -x : x; - } - - function lerp(t,a,b) { return a + t * (b - a); } - - this.noise3d = function(x, y, z) { - var X = Math.floor(x)&255, Y = Math.floor(y)&255, Z = Math.floor(z)&255; - x -= Math.floor(x); y -= Math.floor(y); z -= Math.floor(z); - var fx = (3-2*x)*x*x, fy = (3-2*y)*y*y, fz = (3-2*z)*z*z; - var p0 = perm[X]+Y, p00 = perm[p0] + Z, p01 = perm[p0 + 1] + Z, - p1 = perm[X + 1] + Y, p10 = perm[p1] + Z, p11 = perm[p1 + 1] + Z; - return lerp(fz, - lerp(fy, lerp(fx, grad3d(perm[p00], x, y, z), grad3d(perm[p10], x-1, y, z)), - lerp(fx, grad3d(perm[p01], x, y-1, z), grad3d(perm[p11], x-1, y-1,z))), - lerp(fy, lerp(fx, grad3d(perm[p00 + 1], x, y, z-1), grad3d(perm[p10 + 1], x-1, y, z-1)), - lerp(fx, grad3d(perm[p01 + 1], x, y-1, z-1), grad3d(perm[p11 + 1], x-1, y-1,z-1)))); - }; - - this.noise2d = function(x, y) { - var X = Math.floor(x)&255, Y = Math.floor(y)&255; - x -= Math.floor(x); y -= Math.floor(y); - var fx = (3-2*x)*x*x, fy = (3-2*y)*y*y; - var p0 = perm[X]+Y, p1 = perm[X + 1] + Y; - return lerp(fy, - lerp(fx, grad2d(perm[p0], x, y), grad2d(perm[p1], x-1, y)), - lerp(fx, grad2d(perm[p0 + 1], x, y-1), grad2d(perm[p1 + 1], x-1, y-1))); - }; - - this.noise1d = function(x) { - var X = Math.floor(x)&255; - x -= Math.floor(x); - var fx = (3-2*x)*x*x; - return lerp(fx, grad1d(perm[X], x), grad1d(perm[X+1], x-1)); - }; - } - - // processing defaults - var noiseProfile = { generator: undef, octaves: 4, fallout: 0.5, seed: undef}; - - /** - * Returns the Perlin noise value at specified coordinates. Perlin noise is a random sequence - * generator producing a more natural ordered, harmonic succession of numbers compared to the - * standard random() function. It was invented by Ken Perlin in the 1980s and been used since - * in graphical applications to produce procedural textures, natural motion, shapes, terrains etc. - * The main difference to the random() function is that Perlin noise is defined in an infinite - * n-dimensional space where each pair of coordinates corresponds to a fixed semi-random value - * (fixed only for the lifespan of the program). The resulting value will always be between 0.0 - * and 1.0. Processing can compute 1D, 2D and 3D noise, depending on the number of coordinates - * given. The noise value can be animated by moving through the noise space as demonstrated in - * the example above. The 2nd and 3rd dimension can also be interpreted as time. - * The actual noise is structured similar to an audio signal, in respect to the function's use - * of frequencies. Similar to the concept of harmonics in physics, perlin noise is computed over - * several octaves which are added together for the final result. - * Another way to adjust the character of the resulting sequence is the scale of the input - * coordinates. As the function works within an infinite space the value of the coordinates - * doesn't matter as such, only the distance between successive coordinates does (eg. when using - * noise() within a loop). As a general rule the smaller the difference between coordinates, the - * smoother the resulting noise sequence will be. Steps of 0.005-0.03 work best for most applications, - * but this will differ depending on use. - * - * @param {float} x x coordinate in noise space - * @param {float} y y coordinate in noise space - * @param {float} z z coordinate in noise space - * - * @returns {float} - * - * @see random - * @see noiseDetail - */ - p.noise = function(x, y, z) { - if(noiseProfile.generator === undef) { - // caching - noiseProfile.generator = new PerlinNoise(noiseProfile.seed); - } - var generator = noiseProfile.generator; - var effect = 1, k = 1, sum = 0; - for(var i=0; i 0 ) { - curElement.style.removeProperty("width"); - curElement.style.removeProperty("height"); - } - - curElement.width = p.width = aWidth || 100; - curElement.height = p.height = aHeight || 100; - - for (var prop in savedProperties) { - if (savedProperties.hasOwnProperty(prop)) { - curContext[prop] = savedProperties[prop]; - } - } - - // make sure to set the default font the first time round. - p.textFont(curTextFont); - - // Set the background to whatever it was called last as if background() was called before size() - // If background() hasn't been called before, set background() to a light gray - p.background(); - - // set 5% for pixels to cache (or 1000) - maxPixelsCached = Math.max(1000, aWidth * aHeight * 0.05); - - // Externalize the context - p.externals.context = curContext; - - for (var i = 0; i < PConstants.SINCOS_LENGTH; i++) { - sinLUT[i] = p.sin(i * (PConstants.PI / 180) * 0.5); - cosLUT[i] = p.cos(i * (PConstants.PI / 180) * 0.5); - } - }; - - Drawing2D.prototype.size = function(aWidth, aHeight, aMode) { - if (curContext === undef) { - // size() was called without p.init() default context, i.e. p.createGraphics() - curContext = curElement.getContext("2d"); - userMatrixStack = new PMatrixStack(); - userReverseMatrixStack = new PMatrixStack(); - modelView = new PMatrix2D(); - modelViewInv = new PMatrix2D(); - } - - DrawingShared.prototype.size.apply(this, arguments); - }; - - Drawing3D.prototype.size = (function() { - var size3DCalled = false; - - return function size(aWidth, aHeight, aMode) { - if (size3DCalled) { - throw "Multiple calls to size() for 3D renders are not allowed."; - } - size3DCalled = true; - - function getGLContext(canvas) { - var ctxNames = ['experimental-webgl', 'webgl', 'webkit-3d'], - gl; - - for (var i=0, l=ctxNames.length; i dimensions differ from the - // dimensions specified in the size() call in the sketch, for - // 3D sketches, browsers will either not render or render the - // scene incorrectly. To fix this, we need to adjust the - // width and height attributes of the canvas. - curElement.width = p.width = aWidth || 100; - curElement.height = p.height = aHeight || 100; - curContext = getGLContext(curElement); - canTex = curContext.createTexture(); // texture - textTex = curContext.createTexture(); // texture - } catch(e_size) { - Processing.debug(e_size); - } - - if (!curContext) { - throw "WebGL context is not supported on this browser."; - } - - // Set defaults - curContext.viewport(0, 0, curElement.width, curElement.height); - curContext.enable(curContext.DEPTH_TEST); - curContext.enable(curContext.BLEND); - curContext.blendFunc(curContext.SRC_ALPHA, curContext.ONE_MINUS_SRC_ALPHA); - - // Create the program objects to render 2D (points, lines) and - // 3D (spheres, boxes) shapes. Because 2D shapes are not lit, - // lighting calculations could be ommitted from that program object. - programObject2D = createProgramObject(curContext, vertexShaderSource2D, fragmentShaderSource2D); - - programObjectUnlitShape = createProgramObject(curContext, vShaderSrcUnlitShape, fShaderSrcUnlitShape); - - // Set the default point and line width for the 2D and unlit shapes. - p.strokeWeight(1.0); - - // Now that the programs have been compiled, we can set the default - // states for the lights. - programObject3D = createProgramObject(curContext, vertexShaderSource3D, fragmentShaderSource3D); - curContext.useProgram(programObject3D); - - // assume we aren't using textures by default - uniformi("usingTexture3d", programObject3D, "usingTexture", usingTexture); - // assume that we arn't tinting by default - p.lightFalloff(1, 0, 0); - p.shininess(1); - p.ambient(255, 255, 255); - p.specular(0, 0, 0); - p.emissive(0, 0, 0); - - // Create buffers for 3D primitives - boxBuffer = curContext.createBuffer(); - curContext.bindBuffer(curContext.ARRAY_BUFFER, boxBuffer); - curContext.bufferData(curContext.ARRAY_BUFFER, boxVerts, curContext.STATIC_DRAW); - - boxNormBuffer = curContext.createBuffer(); - curContext.bindBuffer(curContext.ARRAY_BUFFER, boxNormBuffer); - curContext.bufferData(curContext.ARRAY_BUFFER, boxNorms, curContext.STATIC_DRAW); - - boxOutlineBuffer = curContext.createBuffer(); - curContext.bindBuffer(curContext.ARRAY_BUFFER, boxOutlineBuffer); - curContext.bufferData(curContext.ARRAY_BUFFER, boxOutlineVerts, curContext.STATIC_DRAW); - - // used to draw the rectangle and the outline - rectBuffer = curContext.createBuffer(); - curContext.bindBuffer(curContext.ARRAY_BUFFER, rectBuffer); - curContext.bufferData(curContext.ARRAY_BUFFER, rectVerts, curContext.STATIC_DRAW); - - rectNormBuffer = curContext.createBuffer(); - curContext.bindBuffer(curContext.ARRAY_BUFFER, rectNormBuffer); - curContext.bufferData(curContext.ARRAY_BUFFER, rectNorms, curContext.STATIC_DRAW); - - // The sphere vertices are specified dynamically since the user - // can change the level of detail. Everytime the user does that - // using sphereDetail(), the new vertices are calculated. - sphereBuffer = curContext.createBuffer(); - - lineBuffer = curContext.createBuffer(); - - // Shape buffers - fillBuffer = curContext.createBuffer(); - fillColorBuffer = curContext.createBuffer(); - strokeColorBuffer = curContext.createBuffer(); - shapeTexVBO = curContext.createBuffer(); - - pointBuffer = curContext.createBuffer(); - curContext.bindBuffer(curContext.ARRAY_BUFFER, pointBuffer); - curContext.bufferData(curContext.ARRAY_BUFFER, new Float32Array([0, 0, 0]), curContext.STATIC_DRAW); - - textBuffer = curContext.createBuffer(); - curContext.bindBuffer(curContext.ARRAY_BUFFER, textBuffer ); - curContext.bufferData(curContext.ARRAY_BUFFER, new Float32Array([1,1,0,-1,1,0,-1,-1,0,1,-1,0]), curContext.STATIC_DRAW); - - textureBuffer = curContext.createBuffer(); - curContext.bindBuffer(curContext.ARRAY_BUFFER, textureBuffer); - curContext.bufferData(curContext.ARRAY_BUFFER, new Float32Array([0,0,1,0,1,1,0,1]), curContext.STATIC_DRAW); - - indexBuffer = curContext.createBuffer(); - curContext.bindBuffer(curContext.ELEMENT_ARRAY_BUFFER, indexBuffer); - curContext.bufferData(curContext.ELEMENT_ARRAY_BUFFER, new Uint16Array([0,1,2,2,3,0]), curContext.STATIC_DRAW); - - cam = new PMatrix3D(); - cameraInv = new PMatrix3D(); - modelView = new PMatrix3D(); - modelViewInv = new PMatrix3D(); - projection = new PMatrix3D(); - p.camera(); - p.perspective(); - - userMatrixStack = new PMatrixStack(); - userReverseMatrixStack = new PMatrixStack(); - // used by both curve and bezier, so just init here - curveBasisMatrix = new PMatrix3D(); - curveToBezierMatrix = new PMatrix3D(); - curveDrawMatrix = new PMatrix3D(); - bezierDrawMatrix = new PMatrix3D(); - bezierBasisInverse = new PMatrix3D(); - bezierBasisMatrix = new PMatrix3D(); - bezierBasisMatrix.set(-1, 3, -3, 1, 3, -6, 3, 0, -3, 3, 0, 0, 1, 0, 0, 0); - - DrawingShared.prototype.size.apply(this, arguments); - }; - }()); - - //////////////////////////////////////////////////////////////////////////// - // Lights - //////////////////////////////////////////////////////////////////////////// - - /** - * Adds an ambient light. Ambient light doesn't come from a specific direction, - * the rays have light have bounced around so much that objects are evenly lit - * from all sides. Ambient lights are almost always used in combination with - * other types of lights. Lights need to be included in the draw() to - * remain persistent in a looping program. Placing them in the setup() - * of a looping program will cause them to only have an effect the first time - * through the loop. The effect of the parameters is determined by the current - * color mode. - * - * @param {int | float} r red or hue value - * @param {int | float} g green or hue value - * @param {int | float} b blue or hue value - * - * @param {int | float} x x position of light (used for falloff) - * @param {int | float} y y position of light (used for falloff) - * @param {int | float} z z position of light (used for falloff) - * - * @returns none - * - * @see lights - * @see directionalLight - * @see pointLight - * @see spotLight - */ - Drawing2D.prototype.ambientLight = DrawingShared.prototype.a3DOnlyFunction; - - Drawing3D.prototype.ambientLight = function(r, g, b, x, y, z) { - if (lightCount === PConstants.MAX_LIGHTS) { - throw "can only create " + PConstants.MAX_LIGHTS + " lights"; - } - - var pos = new PVector(x, y, z); - var view = new PMatrix3D(); - view.scale(1, -1, 1); - view.apply(modelView.array()); - view.mult(pos, pos); - - // Instead of calling p.color, we do the calculations ourselves to - // reduce property lookups. - var col = color$4(r, g, b, 0); - var normalizedCol = [ ((col & PConstants.RED_MASK) >>> 16) / 255, - ((col & PConstants.GREEN_MASK) >>> 8) / 255, - (col & PConstants.BLUE_MASK) / 255 ]; - - curContext.useProgram(programObject3D); - uniformf("lights.color.3d." + lightCount, programObject3D, "lights" + lightCount + ".color", normalizedCol); - uniformf("lights.position.3d." + lightCount, programObject3D, "lights" + lightCount + ".position", pos.array()); - uniformi("lights.type.3d." + lightCount, programObject3D, "lights" + lightCount + ".type", 0); - uniformi("lightCount3d", programObject3D, "lightCount", ++lightCount); - }; - - /** - * Adds a directional light. Directional light comes from one direction and - * is stronger when hitting a surface squarely and weaker if it hits at a - * gentle angle. After hitting a surface, a directional lights scatters in - * all directions. Lights need to be included in the draw() to remain - * persistent in a looping program. Placing them in the setup() of a - * looping program will cause them to only have an effect the first time - * through the loop. The affect of the
r,
g, and
b - * parameters is determined by the current color mode. The nx, - * ny, and nz parameters specify the direction the light is - * facing. For example, setting ny to -1 will cause the geometry to be - * lit from below (the light is facing directly upward). - * - * @param {int | float} r red or hue value - * @param {int | float} g green or hue value - * @param {int | float} b blue or hue value - * - * @param {int | float} nx direction along the x axis - * @param {int | float} ny direction along the y axis - * @param {int | float} nz direction along the z axis - * - * @returns none - * - * @see lights - * @see ambientLight - * @see pointLight - * @see spotLight - */ - Drawing2D.prototype.directionalLight = DrawingShared.prototype.a3DOnlyFunction; - - Drawing3D.prototype.directionalLight = function(r, g, b, nx, ny, nz) { - if (lightCount === PConstants.MAX_LIGHTS) { - throw "can only create " + PConstants.MAX_LIGHTS + " lights"; - } - - curContext.useProgram(programObject3D); - - var mvm = new PMatrix3D(); - mvm.scale(1, -1, 1); - mvm.apply(modelView.array()); - mvm = mvm.array(); - - // We need to multiply the direction by the model view matrix, but - // the mult function checks the w component of the vector, if it isn't - // present, it uses 1, so we manually multiply. - var dir = [ - mvm[0] * nx + mvm[4] * ny + mvm[8] * nz, - mvm[1] * nx + mvm[5] * ny + mvm[9] * nz, - mvm[2] * nx + mvm[6] * ny + mvm[10] * nz - ]; - - // Instead of calling p.color, we do the calculations ourselves to - // reduce property lookups. - var col = color$4(r, g, b, 0); - var normalizedCol = [ ((col & PConstants.RED_MASK) >>> 16) / 255, - ((col & PConstants.GREEN_MASK) >>> 8) / 255, - (col & PConstants.BLUE_MASK) / 255 ]; - - uniformf("lights.color.3d." + lightCount, programObject3D, "lights" + lightCount + ".color", normalizedCol); - uniformf("lights.position.3d." + lightCount, programObject3D, "lights" + lightCount + ".position", dir); - uniformi("lights.type.3d." + lightCount, programObject3D, "lights" + lightCount + ".type", 1); - uniformi("lightCount3d", programObject3D, "lightCount", ++lightCount); - }; - - /** - * Sets the falloff rates for point lights, spot lights, and ambient lights. - * The parameters are used to determine the falloff with the following equation: - * - * d = distance from light position to vertex position - * falloff = 1 / (CONSTANT + d * LINEAR + (d*d) * QUADRATIC) - * - * Like fill(), it affects only the elements which are created after it in the - * code. The default value if LightFalloff(1.0, 0.0, 0.0). Thinking about an - * ambient light with a falloff can be tricky. It is used, for example, if you - * wanted a region of your scene to be lit ambiently one color and another region - * to be lit ambiently by another color, you would use an ambient light with location - * and falloff. You can think of it as a point light that doesn't care which direction - * a surface is facing. - * - * @param {int | float} constant constant value for determining falloff - * @param {int | float} linear linear value for determining falloff - * @param {int | float} quadratic quadratic value for determining falloff - * - * @returns none - * - * @see lights - * @see ambientLight - * @see pointLight - * @see spotLight - * @see lightSpecular - */ - Drawing2D.prototype.lightFalloff = DrawingShared.prototype.a3DOnlyFunction; - - Drawing3D.prototype.lightFalloff = function(constant, linear, quadratic) { - curContext.useProgram(programObject3D); - uniformf("falloff3d", programObject3D, "falloff", [constant, linear, quadratic]); - }; - - /** - * Sets the specular color for lights. Like fill(), it affects only the - * elements which are created after it in the code. Specular refers to light - * which bounces off a surface in a perferred direction (rather than bouncing - * in all directions like a diffuse light) and is used for creating highlights. - * The specular quality of a light interacts with the specular material qualities - * set through the specular() and shininess() functions. - * - * @param {int | float} r red or hue value - * @param {int | float} g green or hue value - * @param {int | float} b blue or hue value - * - * @returns none - * - * @see lights - * @see ambientLight - * @see pointLight - * @see spotLight - */ - Drawing2D.prototype.lightSpecular = DrawingShared.prototype.a3DOnlyFunction; - - Drawing3D.prototype.lightSpecular = function(r, g, b) { - - // Instead of calling p.color, we do the calculations ourselves to - // reduce property lookups. - var col = color$4(r, g, b, 0); - var normalizedCol = [ ((col & PConstants.RED_MASK) >>> 16) / 255, - ((col & PConstants.GREEN_MASK) >>> 8) / 255, - (col & PConstants.BLUE_MASK) / 255 ]; - - curContext.useProgram(programObject3D); - uniformf("specular3d", programObject3D, "specular", normalizedCol); - }; - - /** - * Sets the default ambient light, directional light, falloff, and specular - * values. The defaults are ambientLight(128, 128, 128) and - * directionalLight(128, 128, 128, 0, 0, -1), lightFalloff(1, 0, 0), and - * lightSpecular(0, 0, 0). Lights need to be included in the draw() to remain - * persistent in a looping program. Placing them in the setup() of a looping - * program will cause them to only have an effect the first time through the - * loop. - * - * @returns none - * - * @see ambientLight - * @see directionalLight - * @see pointLight - * @see spotLight - * @see noLights - * - */ - p.lights = function() { - p.ambientLight(128, 128, 128); - p.directionalLight(128, 128, 128, 0, 0, -1); - p.lightFalloff(1, 0, 0); - p.lightSpecular(0, 0, 0); - }; - - /** - * Adds a point light. Lights need to be included in the draw() to remain - * persistent in a looping program. Placing them in the setup() of a - * looping program will cause them to only have an effect the first time through - * the loop. The affect of the r, g, and b parameters - * is determined by the current color mode. The x, y, and z - * parameters set the position of the light. - * - * @param {int | float} r red or hue value - * @param {int | float} g green or hue value - * @param {int | float} b blue or hue value - * @param {int | float} x x coordinate of the light - * @param {int | float} y y coordinate of the light - * @param {int | float} z z coordinate of the light - * - * @returns none - * - * @see lights - * @see directionalLight - * @see ambientLight - * @see spotLight - */ - Drawing2D.prototype.pointLight = DrawingShared.prototype.a3DOnlyFunction; - - Drawing3D.prototype.pointLight = function(r, g, b, x, y, z) { - if (lightCount === PConstants.MAX_LIGHTS) { - throw "can only create " + PConstants.MAX_LIGHTS + " lights"; - } - - // Place the point in view space once instead of once per vertex - // in the shader. - var pos = new PVector(x, y, z); - var view = new PMatrix3D(); - view.scale(1, -1, 1); - view.apply(modelView.array()); - view.mult(pos, pos); - - // Instead of calling p.color, we do the calculations ourselves to - // reduce property lookups. - var col = color$4(r, g, b, 0); - var normalizedCol = [ ((col & PConstants.RED_MASK) >>> 16) / 255, - ((col & PConstants.GREEN_MASK) >>> 8) / 255, - (col & PConstants.BLUE_MASK) / 255 ]; - - curContext.useProgram(programObject3D); - uniformf("lights.color.3d." + lightCount, programObject3D, "lights" + lightCount + ".color", normalizedCol); - uniformf("lights.position.3d." + lightCount, programObject3D, "lights" + lightCount + ".position", pos.array()); - uniformi("lights.type.3d." + lightCount, programObject3D, "lights" + lightCount + ".type", 2); - uniformi("lightCount3d", programObject3D, "lightCount", ++lightCount); - }; - - /** - * Disable all lighting. Lighting is turned off by default and enabled with - * the lights() method. This function can be used to disable lighting so - * that 2D geometry (which does not require lighting) can be drawn after a - * set of lighted 3D geometry. - * - * @returns none - * - * @see lights - */ - Drawing2D.prototype.noLights = DrawingShared.prototype.a3DOnlyFunction; - - Drawing3D.prototype.noLights = function() { - lightCount = 0; - curContext.useProgram(programObject3D); - uniformi("lightCount3d", programObject3D, "lightCount", lightCount); - }; - - /** - * Adds a spot light. Lights need to be included in the draw() to - * remain persistent in a looping program. Placing them in the setup() - * of a looping program will cause them to only have an effect the first time - * through the loop. The affect of the r, g, and b parameters - * is determined by the current color mode. The x, y, and z - * parameters specify the position of the light and nx, ny, nz - * specify the direction or light. The angle parameter affects angle of the - * spotlight cone. - * - * @param {int | float} r red or hue value - * @param {int | float} g green or hue value - * @param {int | float} b blue or hue value - * @param {int | float} x coordinate of the light - * @param {int | float} y coordinate of the light - * @param {int | float} z coordinate of the light - * @param {int | float} nx direction along the x axis - * @param {int | float} ny direction along the y axis - * @param {int | float} nz direction along the z axis - * @param {float} angle angle of the spotlight cone - * @param {float} concentration exponent determining the center bias of the cone - * - * @returns none - * - * @see lights - * @see directionalLight - * @see ambientLight - * @see pointLight - */ - Drawing2D.prototype.spotLight = DrawingShared.prototype.a3DOnlyFunction; - - Drawing3D.prototype.spotLight = function(r, g, b, x, y, z, nx, ny, nz, angle, concentration) { - if (lightCount === PConstants.MAX_LIGHTS) { - throw "can only create " + PConstants.MAX_LIGHTS + " lights"; - } - - curContext.useProgram(programObject3D); - - // multiply the position and direction by the model view matrix - // once per object rather than once per vertex. - var pos = new PVector(x, y, z); - var mvm = new PMatrix3D(); - mvm.scale(1, -1, 1); - mvm.apply(modelView.array()); - mvm.mult(pos, pos); - - // Convert to array since we need to directly access the elements. - mvm = mvm.array(); - - // We need to multiply the direction by the model view matrix, but - // the mult function checks the w component of the vector, if it isn't - // present, it uses 1, so we use a very small value as a work around. - var dir = [ - mvm[0] * nx + mvm[4] * ny + mvm[8] * nz, - mvm[1] * nx + mvm[5] * ny + mvm[9] * nz, - mvm[2] * nx + mvm[6] * ny + mvm[10] * nz - ]; - - // Instead of calling p.color, we do the calculations ourselves to - // reduce property lookups. - var col = color$4(r, g, b, 0); - var normalizedCol = [ ((col & PConstants.RED_MASK) >>> 16) / 255, - ((col & PConstants.GREEN_MASK) >>> 8) / 255, - (col & PConstants.BLUE_MASK) / 255 ]; - - uniformf("lights.color.3d." + lightCount, programObject3D, "lights" + lightCount + ".color", normalizedCol); - uniformf("lights.position.3d." + lightCount, programObject3D, "lights" + lightCount + ".position", pos.array()); - uniformf("lights.direction.3d." + lightCount, programObject3D, "lights" + lightCount + ".direction", dir); - uniformf("lights.concentration.3d." + lightCount, programObject3D, "lights" + lightCount + ".concentration", concentration); - uniformf("lights.angle.3d." + lightCount, programObject3D, "lights" + lightCount + ".angle", angle); - uniformi("lights.type.3d." + lightCount, programObject3D, "lights" + lightCount + ".type", 3); - uniformi("lightCount3d", programObject3D, "lightCount", ++lightCount); - }; - - //////////////////////////////////////////////////////////////////////////// - // Camera functions - //////////////////////////////////////////////////////////////////////////// - - /** - * The beginCamera() and endCamera() functions enable advanced customization of the camera space. - * The functions are useful if you want to more control over camera movement, however for most users, the camera() - * function will be sufficient.

The camera functions will replace any transformations (such as rotate() - * or translate()) that occur before them in draw(), but they will not automatically replace the camera - * transform itself. For this reason, camera functions should be placed at the beginning of draw() (so that - * transformations happen afterwards), and the camera() function can be used after beginCamera() if - * you want to reset the camera before applying transformations.

This function sets the matrix mode to the - * camera matrix so calls such as translate(), rotate(), applyMatrix() and resetMatrix() affect the camera. - * beginCamera() should always be used with a following endCamera() and pairs of beginCamera() and - * endCamera() cannot be nested. - * - * @see camera - * @see endCamera - * @see applyMatrix - * @see resetMatrix - * @see translate - * @see rotate - * @see scale - */ - Drawing2D.prototype.beginCamera = function() { - throw ("beginCamera() is not available in 2D mode"); - }; - - Drawing3D.prototype.beginCamera = function() { - if (manipulatingCamera) { - throw ("You cannot call beginCamera() again before calling endCamera()"); - } - manipulatingCamera = true; - modelView = cameraInv; - modelViewInv = cam; - }; - - /** - * The beginCamera() and endCamera() functions enable advanced customization of the camera space. - * Please see the reference for beginCamera() for a description of how the functions are used. - * - * @see beginCamera - */ - Drawing2D.prototype.endCamera = function() { - throw ("endCamera() is not available in 2D mode"); - }; - - Drawing3D.prototype.endCamera = function() { - if (!manipulatingCamera) { - throw ("You cannot call endCamera() before calling beginCamera()"); - } - modelView.set(cam); - modelViewInv.set(cameraInv); - manipulatingCamera = false; - }; - - /** - * Sets the position of the camera through setting the eye position, the center of the scene, and which axis is facing - * upward. Moving the eye position and the direction it is pointing (the center of the scene) allows the images to be - * seen from different angles. The version without any parameters sets the camera to the default position, pointing to - * the center of the display window with the Y axis as up. The default values are camera(width/2.0, height/2.0, - * (height/2.0) / tan(PI*60.0 / 360.0), width/2.0, height/2.0, 0, 0, 1, 0). This function is similar to gluLookAt() - * in OpenGL, but it first clears the current camera settings. - * - * @param {float} eyeX x-coordinate for the eye - * @param {float} eyeY y-coordinate for the eye - * @param {float} eyeZ z-coordinate for the eye - * @param {float} centerX x-coordinate for the center of the scene - * @param {float} centerY y-coordinate for the center of the scene - * @param {float} centerZ z-coordinate for the center of the scene - * @param {float} upX usually 0.0, 1.0, -1.0 - * @param {float} upY usually 0.0, 1.0, -1.0 - * @param {float} upZ usually 0.0, 1.0, -1.0 - * - * @see beginCamera - * @see endCamera - * @see frustum - */ - p.camera = function(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ) { - if (eyeX === undef) { - // Workaround if createGraphics is used. - cameraX = p.width / 2; - cameraY = p.height / 2; - cameraZ = cameraY / Math.tan(cameraFOV / 2); - eyeX = cameraX; - eyeY = cameraY; - eyeZ = cameraZ; - centerX = cameraX; - centerY = cameraY; - centerZ = 0; - upX = 0; - upY = 1; - upZ = 0; - } - - var z = new PVector(eyeX - centerX, eyeY - centerY, eyeZ - centerZ); - var y = new PVector(upX, upY, upZ); - z.normalize(); - var x = PVector.cross(y, z); - y = PVector.cross(z, x); - x.normalize(); - y.normalize(); - - var xX = x.x, - xY = x.y, - xZ = x.z; - - var yX = y.x, - yY = y.y, - yZ = y.z; - - var zX = z.x, - zY = z.y, - zZ = z.z; - - cam.set(xX, xY, xZ, 0, yX, yY, yZ, 0, zX, zY, zZ, 0, 0, 0, 0, 1); - - cam.translate(-eyeX, -eyeY, -eyeZ); - - cameraInv.reset(); - cameraInv.invApply(xX, xY, xZ, 0, yX, yY, yZ, 0, zX, zY, zZ, 0, 0, 0, 0, 1); - - cameraInv.translate(eyeX, eyeY, eyeZ); - - modelView.set(cam); - modelViewInv.set(cameraInv); - }; - - /** - * Sets a perspective projection applying foreshortening, making distant objects appear smaller than closer ones. The - * parameters define a viewing volume with the shape of truncated pyramid. Objects near to the front of the volume appear - * their actual size, while farther objects appear smaller. This projection simulates the perspective of the world more - * accurately than orthographic projection. The version of perspective without parameters sets the default perspective and - * the version with four parameters allows the programmer to set the area precisely. The default values are: - * perspective(PI/3.0, width/height, cameraZ/10.0, cameraZ*10.0) where cameraZ is ((height/2.0) / tan(PI*60.0/360.0)); - * - * @param {float} fov field-of-view angle (in radians) for vertical direction - * @param {float} aspect ratio of width to height - * @param {float} zNear z-position of nearest clipping plane - * @param {float} zFar z-positions of farthest clipping plane - */ - p.perspective = function(fov, aspect, near, far) { - if (arguments.length === 0) { - //in case canvas is resized - cameraY = curElement.height / 2; - cameraZ = cameraY / Math.tan(cameraFOV / 2); - cameraNear = cameraZ / 10; - cameraFar = cameraZ * 10; - cameraAspect = p.width / p.height; - fov = cameraFOV; - aspect = cameraAspect; - near = cameraNear; - far = cameraFar; - } - - var yMax, yMin, xMax, xMin; - yMax = near * Math.tan(fov / 2); - yMin = -yMax; - xMax = yMax * aspect; - xMin = yMin * aspect; - p.frustum(xMin, xMax, yMin, yMax, near, far); - }; - - /** - * Sets a perspective matrix defined through the parameters. Works like glFrustum, except it wipes out the current - * perspective matrix rather than muliplying itself with it. - * - * @param {float} left left coordinate of the clipping plane - * @param {float} right right coordinate of the clipping plane - * @param {float} bottom bottom coordinate of the clipping plane - * @param {float} top top coordinate of the clipping plane - * @param {float} near near coordinate of the clipping plane - * @param {float} far far coordinate of the clipping plane - * - * @see beginCamera - * @see camera - * @see endCamera - * @see perspective - */ - Drawing2D.prototype.frustum = function() { - throw("Processing.js: frustum() is not supported in 2D mode"); - }; - - Drawing3D.prototype.frustum = function(left, right, bottom, top, near, far) { - frustumMode = true; - projection = new PMatrix3D(); - projection.set((2 * near) / (right - left), 0, (right + left) / (right - left), - 0, 0, (2 * near) / (top - bottom), (top + bottom) / (top - bottom), - 0, 0, 0, -(far + near) / (far - near), -(2 * far * near) / (far - near), - 0, 0, -1, 0); - var proj = new PMatrix3D(); - proj.set(projection); - proj.transpose(); - curContext.useProgram(programObject2D); - uniformMatrix("projection2d", programObject2D, "projection", false, proj.array()); - curContext.useProgram(programObject3D); - uniformMatrix("projection3d", programObject3D, "projection", false, proj.array()); - curContext.useProgram(programObjectUnlitShape); - uniformMatrix("uProjectionUS", programObjectUnlitShape, "uProjection", false, proj.array()); - }; - - /** - * Sets an orthographic projection and defines a parallel clipping volume. All objects with the same dimension appear - * the same size, regardless of whether they are near or far from the camera. The parameters to this function specify - * the clipping volume where left and right are the minimum and maximum x values, top and bottom are the minimum and - * maximum y values, and near and far are the minimum and maximum z values. If no parameters are given, the default - * is used: ortho(0, width, 0, height, -10, 10). - * - * @param {float} left left plane of the clipping volume - * @param {float} right right plane of the clipping volume - * @param {float} bottom bottom plane of the clipping volume - * @param {float} top top plane of the clipping volume - * @param {float} near maximum distance from the origin to the viewer - * @param {float} far maximum distance from the origin away from the viewer - */ - p.ortho = function(left, right, bottom, top, near, far) { - if (arguments.length === 0) { - left = 0; - right = p.width; - bottom = 0; - top = p.height; - near = -10; - far = 10; - } - - var x = 2 / (right - left); - var y = 2 / (top - bottom); - var z = -2 / (far - near); - - var tx = -(right + left) / (right - left); - var ty = -(top + bottom) / (top - bottom); - var tz = -(far + near) / (far - near); - - projection = new PMatrix3D(); - projection.set(x, 0, 0, tx, 0, y, 0, ty, 0, 0, z, tz, 0, 0, 0, 1); - - var proj = new PMatrix3D(); - proj.set(projection); - proj.transpose(); - curContext.useProgram(programObject2D); - uniformMatrix("projection2d", programObject2D, "projection", false, proj.array()); - curContext.useProgram(programObject3D); - uniformMatrix("projection3d", programObject3D, "projection", false, proj.array()); - curContext.useProgram(programObjectUnlitShape); - uniformMatrix("uProjectionUS", programObjectUnlitShape, "uProjection", false, proj.array()); - frustumMode = false; - }; - /** - * The printProjection() prints the current projection matrix to the text window. - */ - p.printProjection = function() { - projection.print(); - }; - /** - * The printCamera() function prints the current camera matrix. - */ - p.printCamera = function() { - cam.print(); - }; - - //////////////////////////////////////////////////////////////////////////// - // Shapes - //////////////////////////////////////////////////////////////////////////// - /** - * The box() function renders a box. A box is an extruded rectangle. A box with equal dimension on all sides is a cube. - * Calling this function with only one parameter will create a cube. - * - * @param {int|float} w dimension of the box in the x-dimension - * @param {int|float} h dimension of the box in the y-dimension - * @param {int|float} d dimension of the box in the z-dimension - */ - Drawing2D.prototype.box = DrawingShared.prototype.a3DOnlyFunction; - - Drawing3D.prototype.box = function(w, h, d) { - // user can uniformly scale the box by - // passing in only one argument. - if (!h || !d) { - h = d = w; - } - - // Modeling transformation - var model = new PMatrix3D(); - model.scale(w, h, d); - - // viewing transformation needs to have Y flipped - // becuase that's what Processing does. - var view = new PMatrix3D(); - view.scale(1, -1, 1); - view.apply(modelView.array()); - view.transpose(); - - if (doFill) { - curContext.useProgram(programObject3D); - uniformMatrix("model3d", programObject3D, "model", false, model.array()); - uniformMatrix("view3d", programObject3D, "view", false, view.array()); - // fix stitching problems. (lines get occluded by triangles - // since they share the same depth values). This is not entirely - // working, but it's a start for drawing the outline. So - // developers can start playing around with styles. - curContext.enable(curContext.POLYGON_OFFSET_FILL); - curContext.polygonOffset(1, 1); - uniformf("color3d", programObject3D, "color", fillStyle); - - // Calculating the normal matrix can be expensive, so only - // do it if it's necessary - if(lightCount > 0){ - // Create the normal transformation matrix - var v = new PMatrix3D(); - v.set(view); - - var m = new PMatrix3D(); - m.set(model); - - v.mult(m); - - var normalMatrix = new PMatrix3D(); - normalMatrix.set(v); - normalMatrix.invert(); - normalMatrix.transpose(); - - uniformMatrix("normalTransform3d", programObject3D, "normalTransform", false, normalMatrix.array()); - vertexAttribPointer("normal3d", programObject3D, "Normal", 3, boxNormBuffer); - } - else{ - disableVertexAttribPointer("normal3d", programObject3D, "Normal"); - } - - vertexAttribPointer("vertex3d", programObject3D, "Vertex", 3, boxBuffer); - - // Turn off per vertex colors - disableVertexAttribPointer("aColor3d", programObject3D, "aColor"); - disableVertexAttribPointer("aTexture3d", programObject3D, "aTexture"); - - curContext.drawArrays(curContext.TRIANGLES, 0, boxVerts.length / 3); - curContext.disable(curContext.POLYGON_OFFSET_FILL); - } - - if (lineWidth > 0 && doStroke) { - curContext.useProgram(programObject2D); - uniformMatrix("model2d", programObject2D, "model", false, model.array()); - uniformMatrix("view2d", programObject2D, "view", false, view.array()); - uniformf("color2d", programObject2D, "color", strokeStyle); - uniformi("picktype2d", programObject2D, "picktype", 0); - vertexAttribPointer("vertex2d", programObject2D, "Vertex", 3, boxOutlineBuffer); - disableVertexAttribPointer("aTextureCoord2d", programObject2D, "aTextureCoord"); - curContext.drawArrays(curContext.LINES, 0, boxOutlineVerts.length / 3); - } - }; - - /** - * The initSphere() function is a helper function used by sphereDetail() - * This function creates and stores sphere vertices every time the user changes sphere detail. - * - * @see #sphereDetail - */ - var initSphere = function() { - var i; - sphereVerts = []; - - for (i = 0; i < sphereDetailU; i++) { - sphereVerts.push(0); - sphereVerts.push(-1); - sphereVerts.push(0); - sphereVerts.push(sphereX[i]); - sphereVerts.push(sphereY[i]); - sphereVerts.push(sphereZ[i]); - } - sphereVerts.push(0); - sphereVerts.push(-1); - sphereVerts.push(0); - sphereVerts.push(sphereX[0]); - sphereVerts.push(sphereY[0]); - sphereVerts.push(sphereZ[0]); - - var v1, v11, v2; - - // middle rings - var voff = 0; - for (i = 2; i < sphereDetailV; i++) { - v1 = v11 = voff; - voff += sphereDetailU; - v2 = voff; - for (var j = 0; j < sphereDetailU; j++) { - sphereVerts.push(sphereX[v1]); - sphereVerts.push(sphereY[v1]); - sphereVerts.push(sphereZ[v1++]); - sphereVerts.push(sphereX[v2]); - sphereVerts.push(sphereY[v2]); - sphereVerts.push(sphereZ[v2++]); - } - - // close each ring - v1 = v11; - v2 = voff; - - sphereVerts.push(sphereX[v1]); - sphereVerts.push(sphereY[v1]); - sphereVerts.push(sphereZ[v1]); - sphereVerts.push(sphereX[v2]); - sphereVerts.push(sphereY[v2]); - sphereVerts.push(sphereZ[v2]); - } - - // add the northern cap - for (i = 0; i < sphereDetailU; i++) { - v2 = voff + i; - - sphereVerts.push(sphereX[v2]); - sphereVerts.push(sphereY[v2]); - sphereVerts.push(sphereZ[v2]); - sphereVerts.push(0); - sphereVerts.push(1); - sphereVerts.push(0); - } - - sphereVerts.push(sphereX[voff]); - sphereVerts.push(sphereY[voff]); - sphereVerts.push(sphereZ[voff]); - sphereVerts.push(0); - sphereVerts.push(1); - sphereVerts.push(0); - - //set the buffer data - curContext.bindBuffer(curContext.ARRAY_BUFFER, sphereBuffer); - curContext.bufferData(curContext.ARRAY_BUFFER, new Float32Array(sphereVerts), curContext.STATIC_DRAW); - }; - - /** - * The sphereDetail() function controls the detail used to render a sphere by adjusting the number of - * vertices of the sphere mesh. The default resolution is 30, which creates - * a fairly detailed sphere definition with vertices every 360/30 = 12 - * degrees. If you're going to render a great number of spheres per frame, - * it is advised to reduce the level of detail using this function. - * The setting stays active until sphereDetail() is called again with - * a new parameter and so should not be called prior to every - * sphere() statement, unless you wish to render spheres with - * different settings, e.g. using less detail for smaller spheres or ones - * further away from the camera. To control the detail of the horizontal - * and vertical resolution independently, use the version of the functions - * with two parameters. Calling this function with one parameter sets the number of segments - *(minimum of 3) used per full circle revolution. This is equivalent to calling the function with - * two identical values. - * - * @param {int} ures number of segments used horizontally (longitudinally) per full circle revolution - * @param {int} vres number of segments used vertically (latitudinally) from top to bottom - * - * @see #sphere() - */ - p.sphereDetail = function(ures, vres) { - var i; - - if (arguments.length === 1) { - ures = vres = arguments[0]; - } - - if (ures < 3) { - ures = 3; - } // force a minimum res - if (vres < 2) { - vres = 2; - } // force a minimum res - // if it hasn't changed do nothing - if ((ures === sphereDetailU) && (vres === sphereDetailV)) { - return; - } - - var delta = PConstants.SINCOS_LENGTH / ures; - var cx = new Float32Array(ures); - var cz = new Float32Array(ures); - // calc unit circle in XZ plane - for (i = 0; i < ures; i++) { - cx[i] = cosLUT[((i * delta) % PConstants.SINCOS_LENGTH) | 0]; - cz[i] = sinLUT[((i * delta) % PConstants.SINCOS_LENGTH) | 0]; - } - - // computing vertexlist - // vertexlist starts at south pole - var vertCount = ures * (vres - 1) + 2; - var currVert = 0; - - // re-init arrays to store vertices - sphereX = new Float32Array(vertCount); - sphereY = new Float32Array(vertCount); - sphereZ = new Float32Array(vertCount); - - var angle_step = (PConstants.SINCOS_LENGTH * 0.5) / vres; - var angle = angle_step; - - // step along Y axis - for (i = 1; i < vres; i++) { - var curradius = sinLUT[(angle % PConstants.SINCOS_LENGTH) | 0]; - var currY = -cosLUT[(angle % PConstants.SINCOS_LENGTH) | 0]; - for (var j = 0; j < ures; j++) { - sphereX[currVert] = cx[j] * curradius; - sphereY[currVert] = currY; - sphereZ[currVert++] = cz[j] * curradius; - } - angle += angle_step; - } - sphereDetailU = ures; - sphereDetailV = vres; - - // make the sphere verts and norms - initSphere(); - }; - - /** - * The sphere() function draws a sphere with radius r centered at coordinate 0, 0, 0. - * A sphere is a hollow ball made from tessellated triangles. - * - * @param {int|float} r the radius of the sphere - */ - Drawing2D.prototype.sphere = DrawingShared.prototype.a3DOnlyFunction; - - Drawing3D.prototype.sphere = function() { - var sRad = arguments[0]; - - if ((sphereDetailU < 3) || (sphereDetailV < 2)) { - p.sphereDetail(30); - } - - // Modeling transformation - var model = new PMatrix3D(); - model.scale(sRad, sRad, sRad); - - // viewing transformation needs to have Y flipped - // becuase that's what Processing does. - var view = new PMatrix3D(); - view.scale(1, -1, 1); - view.apply(modelView.array()); - view.transpose(); - - if (doFill) { - // Calculating the normal matrix can be expensive, so only - // do it if it's necessary - if(lightCount > 0){ - // Create a normal transformation matrix - var v = new PMatrix3D(); - v.set(view); - - var m = new PMatrix3D(); - m.set(model); - - v.mult(m); - - var normalMatrix = new PMatrix3D(); - normalMatrix.set(v); - normalMatrix.invert(); - normalMatrix.transpose(); - - uniformMatrix("normalTransform3d", programObject3D, "normalTransform", false, normalMatrix.array()); - vertexAttribPointer("normal3d", programObject3D, "Normal", 3, sphereBuffer); - } - else{ - disableVertexAttribPointer("normal3d", programObject3D, "Normal"); - } - - curContext.useProgram(programObject3D); - disableVertexAttribPointer("aTexture3d", programObject3D, "aTexture"); - - uniformMatrix("model3d", programObject3D, "model", false, model.array()); - uniformMatrix("view3d", programObject3D, "view", false, view.array()); - vertexAttribPointer("vertex3d", programObject3D, "Vertex", 3, sphereBuffer); - - // Turn off per vertex colors - disableVertexAttribPointer("aColor3d", programObject3D, "aColor"); - - // fix stitching problems. (lines get occluded by triangles - // since they share the same depth values). This is not entirely - // working, but it's a start for drawing the outline. So - // developers can start playing around with styles. - curContext.enable(curContext.POLYGON_OFFSET_FILL); - curContext.polygonOffset(1, 1); - uniformf("color3d", programObject3D, "color", fillStyle); - curContext.drawArrays(curContext.TRIANGLE_STRIP, 0, sphereVerts.length / 3); - curContext.disable(curContext.POLYGON_OFFSET_FILL); - } - - if (lineWidth > 0 && doStroke) { - curContext.useProgram(programObject2D); - uniformMatrix("model2d", programObject2D, "model", false, model.array()); - uniformMatrix("view2d", programObject2D, "view", false, view.array()); - vertexAttribPointer("vertex2d", programObject2D, "Vertex", 3, sphereBuffer); - disableVertexAttribPointer("aTextureCoord2d", programObject2D, "aTextureCoord"); - uniformf("color2d", programObject2D, "color", strokeStyle); - uniformi("picktype2d", programObject2D, "picktype", 0); - curContext.drawArrays(curContext.LINE_STRIP, 0, sphereVerts.length / 3); - } - }; - - //////////////////////////////////////////////////////////////////////////// - // Coordinates - //////////////////////////////////////////////////////////////////////////// - - /** - * Returns the three-dimensional X, Y, Z position in model space. This returns - * the X value for a given coordinate based on the current set of transformations - * (scale, rotate, translate, etc.) The X value can be used to place an object - * in space relative to the location of the original point once the transformations - * are no longer in use.
- *
- * - * @param {int | float} x 3D x coordinate to be mapped - * @param {int | float} y 3D y coordinate to be mapped - * @param {int | float} z 3D z coordinate to be mapped - * - * @returns {float} - * - * @see modelY - * @see modelZ - */ - p.modelX = function(x, y, z) { - var mv = modelView.array(); - var ci = cameraInv.array(); - - var ax = mv[0] * x + mv[1] * y + mv[2] * z + mv[3]; - var ay = mv[4] * x + mv[5] * y + mv[6] * z + mv[7]; - var az = mv[8] * x + mv[9] * y + mv[10] * z + mv[11]; - var aw = mv[12] * x + mv[13] * y + mv[14] * z + mv[15]; - - var ox = ci[0] * ax + ci[1] * ay + ci[2] * az + ci[3] * aw; - var ow = ci[12] * ax + ci[13] * ay + ci[14] * az + ci[15] * aw; - - return (ow !== 0) ? ox / ow : ox; - }; - - /** - * Returns the three-dimensional X, Y, Z position in model space. This returns - * the Y value for a given coordinate based on the current set of transformations - * (scale, rotate, translate, etc.) The Y value can be used to place an object in - * space relative to the location of the original point once the transformations - * are no longer in use.
- *
- * - * @param {int | float} x 3D x coordinate to be mapped - * @param {int | float} y 3D y coordinate to be mapped - * @param {int | float} z 3D z coordinate to be mapped - * - * @returns {float} - * - * @see modelX - * @see modelZ - */ - p.modelY = function(x, y, z) { - var mv = modelView.array(); - var ci = cameraInv.array(); - - var ax = mv[0] * x + mv[1] * y + mv[2] * z + mv[3]; - var ay = mv[4] * x + mv[5] * y + mv[6] * z + mv[7]; - var az = mv[8] * x + mv[9] * y + mv[10] * z + mv[11]; - var aw = mv[12] * x + mv[13] * y + mv[14] * z + mv[15]; - - var oy = ci[4] * ax + ci[5] * ay + ci[6] * az + ci[7] * aw; - var ow = ci[12] * ax + ci[13] * ay + ci[14] * az + ci[15] * aw; - - return (ow !== 0) ? oy / ow : oy; - }; - - /** - * Returns the three-dimensional X, Y, Z position in model space. This returns - * the Z value for a given coordinate based on the current set of transformations - * (scale, rotate, translate, etc.) The Z value can be used to place an object in - * space relative to the location of the original point once the transformations - * are no longer in use. - * - * @param {int | float} x 3D x coordinate to be mapped - * @param {int | float} y 3D y coordinate to be mapped - * @param {int | float} z 3D z coordinate to be mapped - * - * @returns {float} - * - * @see modelX - * @see modelY - */ - p.modelZ = function(x, y, z) { - var mv = modelView.array(); - var ci = cameraInv.array(); - - var ax = mv[0] * x + mv[1] * y + mv[2] * z + mv[3]; - var ay = mv[4] * x + mv[5] * y + mv[6] * z + mv[7]; - var az = mv[8] * x + mv[9] * y + mv[10] * z + mv[11]; - var aw = mv[12] * x + mv[13] * y + mv[14] * z + mv[15]; - - var oz = ci[8] * ax + ci[9] * ay + ci[10] * az + ci[11] * aw; - var ow = ci[12] * ax + ci[13] * ay + ci[14] * az + ci[15] * aw; - - return (ow !== 0) ? oz / ow : oz; - }; - - //////////////////////////////////////////////////////////////////////////// - // Material Properties - //////////////////////////////////////////////////////////////////////////// - - /** - * Sets the ambient reflectance for shapes drawn to the screen. This is - * combined with the ambient light component of environment. The color - * components set through the parameters define the reflectance. For example in - * the default color mode, setting v1=255, v2=126, v3=0, would cause all the - * red light to reflect and half of the green light to reflect. Used in combination - * with emissive(), specular(), and shininess() in setting - * the materal properties of shapes. - * - * @param {int | float} gray - * - * @returns none - * - * @see emissive - * @see specular - * @see shininess - */ - Drawing2D.prototype.ambient = DrawingShared.prototype.a3DOnlyFunction; - - Drawing3D.prototype.ambient = function(v1, v2, v3) { - curContext.useProgram(programObject3D); - uniformi("usingMat3d", programObject3D, "usingMat", true); - var col = p.color(v1, v2, v3); - uniformf("mat_ambient3d", programObject3D, "mat_ambient", p.color.toGLArray(col).slice(0, 3)); - }; - - /** - * Sets the emissive color of the material used for drawing shapes - * drawn to the screen. Used in combination with ambient(), specular(), - * and shininess() in setting the material properties of shapes. - * - * Can be called in the following ways: - * - * emissive(gray) - * @param {int | float} gray number specifying value between white and black - * - * emissive(color) - * @param {color} color any value of the color datatype - * - * emissive(v1, v2, v3) - * @param {int | float} v1 red or hue value - * @param {int | float} v2 green or saturation value - * @param {int | float} v3 blue or brightness value - * - * @returns none - * - * @see ambient - * @see specular - * @see shininess - */ - Drawing2D.prototype.emissive = DrawingShared.prototype.a3DOnlyFunction; - - Drawing3D.prototype.emissive = function(v1, v2, v3) { - curContext.useProgram(programObject3D); - uniformi("usingMat3d", programObject3D, "usingMat", true); - var col = p.color(v1, v2, v3); - uniformf("mat_emissive3d", programObject3D, "mat_emissive", p.color.toGLArray(col).slice(0, 3)); - }; - - /** - * Sets the amount of gloss in the surface of shapes. Used in combination with - * ambient(), specular(), and emissive() in setting the - * material properties of shapes. - * - * @param {float} shine degree of shininess - * - * @returns none - */ - Drawing2D.prototype.shininess = DrawingShared.prototype.a3DOnlyFunction; - - Drawing3D.prototype.shininess = function(shine) { - curContext.useProgram(programObject3D); - uniformi("usingMat3d", programObject3D, "usingMat", true); - uniformf("shininess3d", programObject3D, "shininess", shine); - }; - - /** - * Sets the specular color of the materials used for shapes drawn to the screen, - * which sets the color of hightlights. Specular refers to light which bounces - * off a surface in a perferred direction (rather than bouncing in all directions - * like a diffuse light). Used in combination with emissive(), ambient(), and - * shininess() in setting the material properties of shapes. - * - * Can be called in the following ways: - * - * specular(gray) - * @param {int | float} gray number specifying value between white and black - * - * specular(gray, alpha) - * @param {int | float} gray number specifying value between white and black - * @param {int | float} alpha opacity - * - * specular(color) - * @param {color} color any value of the color datatype - * - * specular(v1, v2, v3) - * @param {int | float} v1 red or hue value - * @param {int | float} v2 green or saturation value - * @param {int | float} v3 blue or brightness value - * - * specular(v1, v2, v3, alpha) - * @param {int | float} v1 red or hue value - * @param {int | float} v2 green or saturation value - * @param {int | float} v3 blue or brightness value - * @param {int | float} alpha opacity - * - * @returns none - * - * @see ambient - * @see emissive - * @see shininess - */ - Drawing2D.prototype.specular = DrawingShared.prototype.a3DOnlyFunction; - - Drawing3D.prototype.specular = function(v1, v2, v3) { - curContext.useProgram(programObject3D); - uniformi("usingMat3d", programObject3D, "usingMat", true); - var col = p.color(v1, v2, v3); - uniformf("mat_specular3d", programObject3D, "mat_specular", p.color.toGLArray(col).slice(0, 3)); - }; - - //////////////////////////////////////////////////////////////////////////// - // Coordinates - //////////////////////////////////////////////////////////////////////////// - - /** - * Takes a three-dimensional X, Y, Z position and returns the X value for - * where it will appear on a (two-dimensional) screen. - * - * @param {int | float} x 3D x coordinate to be mapped - * @param {int | float} y 3D y coordinate to be mapped - * @param {int | float} z 3D z optional coordinate to be mapped - * - * @returns {float} - * - * @see screenY - * @see screenZ - */ - p.screenX = function( x, y, z ) { - var mv = modelView.array(); - if( mv.length === 16 ) - { - var ax = mv[ 0]*x + mv[ 1]*y + mv[ 2]*z + mv[ 3]; - var ay = mv[ 4]*x + mv[ 5]*y + mv[ 6]*z + mv[ 7]; - var az = mv[ 8]*x + mv[ 9]*y + mv[10]*z + mv[11]; - var aw = mv[12]*x + mv[13]*y + mv[14]*z + mv[15]; - - var pj = projection.array(); - - var ox = pj[ 0]*ax + pj[ 1]*ay + pj[ 2]*az + pj[ 3]*aw; - var ow = pj[12]*ax + pj[13]*ay + pj[14]*az + pj[15]*aw; - - if ( ow !== 0 ){ - ox /= ow; - } - return p.width * ( 1 + ox ) / 2.0; - } - // We assume that we're in 2D - return modelView.multX(x, y); - }; - - /** - * Takes a three-dimensional X, Y, Z position and returns the Y value for - * where it will appear on a (two-dimensional) screen. - * - * @param {int | float} x 3D x coordinate to be mapped - * @param {int | float} y 3D y coordinate to be mapped - * @param {int | float} z 3D z optional coordinate to be mapped - * - * @returns {float} - * - * @see screenX - * @see screenZ - */ - p.screenY = function screenY( x, y, z ) { - var mv = modelView.array(); - if( mv.length === 16 ) { - var ax = mv[ 0]*x + mv[ 1]*y + mv[ 2]*z + mv[ 3]; - var ay = mv[ 4]*x + mv[ 5]*y + mv[ 6]*z + mv[ 7]; - var az = mv[ 8]*x + mv[ 9]*y + mv[10]*z + mv[11]; - var aw = mv[12]*x + mv[13]*y + mv[14]*z + mv[15]; - - var pj = projection.array(); - - var oy = pj[ 4]*ax + pj[ 5]*ay + pj[ 6]*az + pj[ 7]*aw; - var ow = pj[12]*ax + pj[13]*ay + pj[14]*az + pj[15]*aw; - - if ( ow !== 0 ){ - oy /= ow; - } - return p.height * ( 1 + oy ) / 2.0; - } - // We assume that we're in 2D - return modelView.multY(x, y); - }; - - /** - * Takes a three-dimensional X, Y, Z position and returns the Z value for - * where it will appear on a (two-dimensional) screen. - * - * @param {int | float} x 3D x coordinate to be mapped - * @param {int | float} y 3D y coordinate to be mapped - * @param {int | float} z 3D z coordinate to be mapped - * - * @returns {float} - * - * @see screenX - * @see screenY - */ - p.screenZ = function screenZ( x, y, z ) { - var mv = modelView.array(); - if( mv.length !== 16 ) { - return 0; - } - - var pj = projection.array(); - - var ax = mv[ 0]*x + mv[ 1]*y + mv[ 2]*z + mv[ 3]; - var ay = mv[ 4]*x + mv[ 5]*y + mv[ 6]*z + mv[ 7]; - var az = mv[ 8]*x + mv[ 9]*y + mv[10]*z + mv[11]; - var aw = mv[12]*x + mv[13]*y + mv[14]*z + mv[15]; - - var oz = pj[ 8]*ax + pj[ 9]*ay + pj[10]*az + pj[11]*aw; - var ow = pj[12]*ax + pj[13]*ay + pj[14]*az + pj[15]*aw; - - if ( ow !== 0 ) { - oz /= ow; - } - return ( oz + 1 ) / 2.0; - }; - - //////////////////////////////////////////////////////////////////////////// - // Style functions - //////////////////////////////////////////////////////////////////////////// - /** - * The fill() function sets the color used to fill shapes. For example, if you run fill(204, 102, 0), all subsequent shapes will be filled with orange. - * This color is either specified in terms of the RGB or HSB color depending on the current colorMode() - *(the default color space is RGB, with each value in the range from 0 to 255). - *

When using hexadecimal notation to specify a color, use "#" or "0x" before the values (e.g. #CCFFAA, 0xFFCCFFAA). - * The # syntax uses six digits to specify a color (the way colors are specified in HTML and CSS). When using the hexadecimal notation starting with "0x", - * the hexadecimal value must be specified with eight characters; the first two characters define the alpha component and the remainder the red, green, and blue components. - *

The value for the parameter "gray" must be less than or equal to the current maximum value as specified by colorMode(). The default maximum value is 255. - *

To change the color of an image (or a texture), use tint(). - * - * @param {int|float} gray number specifying value between white and black - * @param {int|float} value1 red or hue value - * @param {int|float} value2 green or saturation value - * @param {int|float} value3 blue or brightness value - * @param {int|float} alpha opacity of the fill - * @param {Color} color any value of the color datatype - * @param {int} hex color value in hexadecimal notation (i.e. #FFCC00 or 0xFFFFCC00) - * - * @see #noFill() - * @see #stroke() - * @see #tint() - * @see #background() - * @see #colorMode() - */ - DrawingShared.prototype.fill = function() { - var color = p.color(arguments[0], arguments[1], arguments[2], arguments[3]); - if(color === currentFillColor && doFill) { - return; - } - doFill = true; - currentFillColor = color; - }; - - Drawing2D.prototype.fill = function() { - DrawingShared.prototype.fill.apply(this, arguments); - isFillDirty = true; - }; - - Drawing3D.prototype.fill = function() { - DrawingShared.prototype.fill.apply(this, arguments); - fillStyle = p.color.toGLArray(currentFillColor); - }; - - function executeContextFill() { - if(doFill) { - if(isFillDirty) { - curContext.fillStyle = p.color.toString(currentFillColor); - isFillDirty = false; - } - curContext.fill(); - } - } - - /** - * The noFill() function disables filling geometry. If both noStroke() and noFill() - * are called, no shapes will be drawn to the screen. - * - * @see #fill() - * - */ - p.noFill = function() { - doFill = false; - }; - - /** - * The stroke() function sets the color used to draw lines and borders around shapes. This color - * is either specified in terms of the RGB or HSB color depending on the - * current colorMode() (the default color space is RGB, with each - * value in the range from 0 to 255). - *

When using hexadecimal notation to specify a color, use "#" or - * "0x" before the values (e.g. #CCFFAA, 0xFFCCFFAA). The # syntax uses six - * digits to specify a color (the way colors are specified in HTML and CSS). - * When using the hexadecimal notation starting with "0x", the hexadecimal - * value must be specified with eight characters; the first two characters - * define the alpha component and the remainder the red, green, and blue - * components. - *

The value for the parameter "gray" must be less than or equal - * to the current maximum value as specified by colorMode(). - * The default maximum value is 255. - * - * @param {int|float} gray number specifying value between white and black - * @param {int|float} value1 red or hue value - * @param {int|float} value2 green or saturation value - * @param {int|float} value3 blue or brightness value - * @param {int|float} alpha opacity of the stroke - * @param {Color} color any value of the color datatype - * @param {int} hex color value in hexadecimal notation (i.e. #FFCC00 or 0xFFFFCC00) - * - * @see #fill() - * @see #noStroke() - * @see #tint() - * @see #background() - * @see #colorMode() - */ - DrawingShared.prototype.stroke = function() { - var color = p.color(arguments[0], arguments[1], arguments[2], arguments[3]); - if(color === currentStrokeColor && doStroke) { - return; - } - doStroke = true; - currentStrokeColor = color; - }; - - Drawing2D.prototype.stroke = function() { - DrawingShared.prototype.stroke.apply(this, arguments); - isStrokeDirty = true; - }; - - Drawing3D.prototype.stroke = function() { - DrawingShared.prototype.stroke.apply(this, arguments); - strokeStyle = p.color.toGLArray(currentStrokeColor); - }; - - function executeContextStroke() { - if(doStroke) { - if(isStrokeDirty) { - curContext.strokeStyle = p.color.toString(currentStrokeColor); - isStrokeDirty = false; - } - curContext.stroke(); - } - } - - /** - * The noStroke() function disables drawing the stroke (outline). If both noStroke() and - * noFill() are called, no shapes will be drawn to the screen. - * - * @see #stroke() - */ - p.noStroke = function() { - doStroke = false; - }; - - /** - * The strokeWeight() function sets the width of the stroke used for lines, points, and the border around shapes. - * All widths are set in units of pixels. - * - * @param {int|float} w the weight (in pixels) of the stroke - */ - DrawingShared.prototype.strokeWeight = function(w) { - lineWidth = w; - }; - - Drawing2D.prototype.strokeWeight = function(w) { - DrawingShared.prototype.strokeWeight.apply(this, arguments); - curContext.lineWidth = w; - }; - - Drawing3D.prototype.strokeWeight = function(w) { - DrawingShared.prototype.strokeWeight.apply(this, arguments); - - // Processing groups the weight of points and lines under this one function, - // but for WebGL, we need to set a uniform for points and call a function for line. - - curContext.useProgram(programObject2D); - uniformf("pointSize2d", programObject2D, "pointSize", w); - - curContext.useProgram(programObjectUnlitShape); - uniformf("pointSizeUnlitShape", programObjectUnlitShape, "pointSize", w); - - curContext.lineWidth(w); - }; - - /** - * The strokeCap() function sets the style for rendering line endings. These ends are either squared, extended, or rounded and - * specified with the corresponding parameters SQUARE, PROJECT, and ROUND. The default cap is ROUND. - * This function is not available with the P2D, P3D, or OPENGL renderers - * - * @param {int} value Either SQUARE, PROJECT, or ROUND - */ - p.strokeCap = function(value) { - drawing.$ensureContext().lineCap = value; - }; - - /** - * The strokeJoin() function sets the style of the joints which connect line segments. - * These joints are either mitered, beveled, or rounded and specified with the corresponding parameters MITER, BEVEL, and ROUND. The default joint is MITER. - * This function is not available with the P2D, P3D, or OPENGL renderers - * - * @param {int} value Either SQUARE, PROJECT, or ROUND - */ - p.strokeJoin = function(value) { - drawing.$ensureContext().lineJoin = value; - }; - - /** - * The smooth() function draws all geometry with smooth (anti-aliased) edges. This will slow down the frame rate of the application, - * but will enhance the visual refinement.

- * Note that smooth() will also improve image quality of resized images, and noSmooth() will disable image (and font) smoothing altogether. - * - * @see #noSmooth() - * @see #hint() - * @see #size() - */ - - Drawing2D.prototype.smooth = function() { - renderSmooth = true; - var style = curElement.style; - style.setProperty("image-rendering", "optimizeQuality", "important"); - style.setProperty("-ms-interpolation-mode", "bicubic", "important"); - if (curContext.hasOwnProperty("mozImageSmoothingEnabled")) { - curContext.mozImageSmoothingEnabled = true; - } - }; - - Drawing3D.prototype.smooth = nop; - - /** - * The noSmooth() function draws all geometry with jagged (aliased) edges. - * - * @see #smooth() - */ - - Drawing2D.prototype.noSmooth = function() { - renderSmooth = false; - var style = curElement.style; - style.setProperty("image-rendering", "optimizeSpeed", "important"); - style.setProperty("image-rendering", "-moz-crisp-edges", "important"); - style.setProperty("image-rendering", "-webkit-optimize-contrast", "important"); - style.setProperty("image-rendering", "optimize-contrast", "important"); - style.setProperty("-ms-interpolation-mode", "nearest-neighbor", "important"); - if (curContext.hasOwnProperty("mozImageSmoothingEnabled")) { - curContext.mozImageSmoothingEnabled = false; - } - }; - - Drawing3D.prototype.noSmooth = nop; - - //////////////////////////////////////////////////////////////////////////// - // Vector drawing functions - //////////////////////////////////////////////////////////////////////////// - /** - * The point() function draws a point, a coordinate in space at the dimension of one pixel. - * The first parameter is the horizontal value for the point, the second - * value is the vertical value for the point, and the optional third value - * is the depth value. Drawing this shape in 3D using the z - * parameter requires the P3D or OPENGL parameter in combination with - * size as shown in the above example. - * - * @param {int|float} x x-coordinate of the point - * @param {int|float} y y-coordinate of the point - * @param {int|float} z z-coordinate of the point - * - * @see #beginShape() - */ - Drawing2D.prototype.point = function(x, y) { - if (!doStroke) { - return; - } - - x = Math.round(x); - y = Math.round(y); - curContext.fillStyle = p.color.toString(currentStrokeColor); - isFillDirty = true; - // Draw a circle for any point larger than 1px - if (lineWidth > 1) { - curContext.beginPath(); - curContext.arc(x, y, lineWidth / 2, 0, PConstants.TWO_PI, false); - curContext.fill(); - } else { - curContext.fillRect(x, y, 1, 1); - } - }; - - Drawing3D.prototype.point = function(x, y, z) { - var model = new PMatrix3D(); - - // move point to position - model.translate(x, y, z || 0); - model.transpose(); - - var view = new PMatrix3D(); - view.scale(1, -1, 1); - view.apply(modelView.array()); - view.transpose(); - - curContext.useProgram(programObject2D); - uniformMatrix("model2d", programObject2D, "model", false, model.array()); - uniformMatrix("view2d", programObject2D, "view", false, view.array()); - - if (lineWidth > 0 && doStroke) { - // this will be replaced with the new bit shifting color code - uniformf("color2d", programObject2D, "color", strokeStyle); - uniformi("picktype2d", programObject2D, "picktype", 0); - vertexAttribPointer("vertex2d", programObject2D, "Vertex", 3, pointBuffer); - disableVertexAttribPointer("aTextureCoord2d", programObject2D, "aTextureCoord"); - curContext.drawArrays(curContext.POINTS, 0, 1); - } - }; - - /** - * Using the beginShape() and endShape() functions allow creating more complex forms. - * beginShape() begins recording vertices for a shape and endShape() stops recording. - * The value of the MODE parameter tells it which types of shapes to create from the provided vertices. - * With no mode specified, the shape can be any irregular polygon. After calling the beginShape() function, - * a series of vertex() commands must follow. To stop drawing the shape, call endShape(). - * The vertex() function with two parameters specifies a position in 2D and the vertex() - * function with three parameters specifies a position in 3D. Each shape will be outlined with the current - * stroke color and filled with the fill color. - * - * @param {int} MODE either POINTS, LINES, TRIANGLES, TRIANGLE_FAN, TRIANGLE_STRIP, QUADS, and QUAD_STRIP. - * - * @see endShape - * @see vertex - * @see curveVertex - * @see bezierVertex - */ - p.beginShape = function(type) { - curShape = type; - curvePoints = []; - vertArray = []; - }; - - /** - * All shapes are constructed by connecting a series of vertices. vertex() is used to specify the vertex - * coordinates for points, lines, triangles, quads, and polygons and is used exclusively within the beginShape() - * and endShape() function.

Drawing a vertex in 3D using the z parameter requires the P3D or - * OPENGL parameter in combination with size as shown in the above example.

This function is also used to map a - * texture onto the geometry. The texture() function declares the texture to apply to the geometry and the u - * and v coordinates set define the mapping of this texture to the form. By default, the coordinates used for - * u and v are specified in relation to the image's size in pixels, but this relation can be changed with - * textureMode(). - * - * @param {int | float} x x-coordinate of the vertex - * @param {int | float} y y-coordinate of the vertex - * @param {int | float} z z-coordinate of the vertex - * @param {int | float} u horizontal coordinate for the texture mapping - * @param {int | float} v vertical coordinate for the texture mapping - * - * @see beginShape - * @see endShape - * @see bezierVertex - * @see curveVertex - * @see texture - */ - - Drawing2D.prototype.vertex = function(x, y, u, v) { - var vert = []; - - if (firstVert) { firstVert = false; } - vert["isVert"] = true; - - vert[0] = x; - vert[1] = y; - vert[2] = 0; - vert[3] = u; - vert[4] = v; - - // fill and stroke color - vert[5] = currentFillColor; - vert[6] = currentStrokeColor; - - vertArray.push(vert); - }; - - Drawing3D.prototype.vertex = function(x, y, z, u, v) { - var vert = []; - - if (firstVert) { firstVert = false; } - vert["isVert"] = true; - - if (v === undef && usingTexture) { - v = u; - u = z; - z = 0; - } - - // Convert u and v to normalized coordinates - if (u !== undef && v !== undef) { - if (curTextureMode === PConstants.IMAGE) { - u /= curTexture.width; - v /= curTexture.height; - } - u = u > 1 ? 1 : u; - u = u < 0 ? 0 : u; - v = v > 1 ? 1 : v; - v = v < 0 ? 0 : v; - } - - vert[0] = x; - vert[1] = y; - vert[2] = z || 0; - vert[3] = u || 0; - vert[4] = v || 0; - - // fill rgba - vert[5] = fillStyle[0]; - vert[6] = fillStyle[1]; - vert[7] = fillStyle[2]; - vert[8] = fillStyle[3]; - // stroke rgba - vert[9] = strokeStyle[0]; - vert[10] = strokeStyle[1]; - vert[11] = strokeStyle[2]; - vert[12] = strokeStyle[3]; - //normals - vert[13] = normalX; - vert[14] = normalY; - vert[15] = normalZ; - - vertArray.push(vert); - }; - - /** - * @private - * Renders 3D points created from calls to vertex and beginShape/endShape - * - * @param {Array} vArray an array of vertex coordinate - * @param {Array} cArray an array of colours used for the vertices - * - * @see beginShape - * @see endShape - * @see vertex - */ - var point3D = function(vArray, cArray){ - var view = new PMatrix3D(); - view.scale(1, -1, 1); - view.apply(modelView.array()); - view.transpose(); - - curContext.useProgram(programObjectUnlitShape); - - uniformMatrix("uViewUS", programObjectUnlitShape, "uView", false, view.array()); - - vertexAttribPointer("aVertexUS", programObjectUnlitShape, "aVertex", 3, pointBuffer); - curContext.bufferData(curContext.ARRAY_BUFFER, new Float32Array(vArray), curContext.STREAM_DRAW); - - vertexAttribPointer("aColorUS", programObjectUnlitShape, "aColor", 4, fillColorBuffer); - curContext.bufferData(curContext.ARRAY_BUFFER, new Float32Array(cArray), curContext.STREAM_DRAW); - - curContext.drawArrays(curContext.POINTS, 0, vArray.length/3); - }; - - /** - * @private - * Renders 3D lines created from calls to beginShape/vertex/endShape - based on the mode specified LINES, LINE_LOOP, etc. - * - * @param {Array} vArray an array of vertex coordinate - * @param {String} mode either LINES, LINE_LOOP, or LINE_STRIP - * @param {Array} cArray an array of colours used for the vertices - * - * @see beginShape - * @see endShape - * @see vertex - */ - var line3D = function(vArray, mode, cArray){ - var ctxMode; - if (mode === "LINES"){ - ctxMode = curContext.LINES; - } - else if(mode === "LINE_LOOP"){ - ctxMode = curContext.LINE_LOOP; - } - else{ - ctxMode = curContext.LINE_STRIP; - } - - var view = new PMatrix3D(); - view.scale(1, -1, 1); - view.apply(modelView.array()); - view.transpose(); - - curContext.useProgram(programObjectUnlitShape); - uniformMatrix("uViewUS", programObjectUnlitShape, "uView", false, view.array()); - vertexAttribPointer("aVertexUS", programObjectUnlitShape, "aVertex", 3, lineBuffer); - curContext.bufferData(curContext.ARRAY_BUFFER, new Float32Array(vArray), curContext.STREAM_DRAW); - vertexAttribPointer("aColorUS", programObjectUnlitShape, "aColor", 4, strokeColorBuffer); - curContext.bufferData(curContext.ARRAY_BUFFER, new Float32Array(cArray), curContext.STREAM_DRAW); - curContext.drawArrays(ctxMode, 0, vArray.length/3); - }; - - /** - * @private - * Render filled shapes created from calls to beginShape/vertex/endShape - based on the mode specified TRIANGLES, etc. - * - * @param {Array} vArray an array of vertex coordinate - * @param {String} mode either LINES, LINE_LOOP, or LINE_STRIP - * @param {Array} cArray an array of colours used for the vertices - * @param {Array} tArray an array of u,v coordinates for textures - * - * @see beginShape - * @see endShape - * @see vertex - */ - var fill3D = function(vArray, mode, cArray, tArray){ - var ctxMode; - if (mode === "TRIANGLES") { - ctxMode = curContext.TRIANGLES; - } else if(mode === "TRIANGLE_FAN") { - ctxMode = curContext.TRIANGLE_FAN; - } else { - ctxMode = curContext.TRIANGLE_STRIP; - } - - var view = new PMatrix3D(); - view.scale(1, -1, 1); - view.apply(modelView.array()); - view.transpose(); - - curContext.useProgram( programObject3D ); - uniformMatrix("model3d", programObject3D, "model", false, [1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1] ); - uniformMatrix("view3d", programObject3D, "view", false, view.array() ); - curContext.enable( curContext.POLYGON_OFFSET_FILL ); - curContext.polygonOffset( 1, 1 ); - uniformf("color3d", programObject3D, "color", [-1,0,0,0]); - vertexAttribPointer("vertex3d", programObject3D, "Vertex", 3, fillBuffer); - curContext.bufferData(curContext.ARRAY_BUFFER, new Float32Array(vArray), curContext.STREAM_DRAW); - - // if we are using a texture and a tint, then overwrite the - // contents of the color buffer with the current tint - if (usingTexture && curTint !== null){ - curTint3d(cArray); - } - - vertexAttribPointer("aColor3d", programObject3D, "aColor", 4, fillColorBuffer); - curContext.bufferData(curContext.ARRAY_BUFFER, new Float32Array(cArray), curContext.STREAM_DRAW); - - // No support for lights....yet - disableVertexAttribPointer("normal3d", programObject3D, "Normal"); - - if (usingTexture) { - uniformi("usingTexture3d", programObject3D, "usingTexture", usingTexture); - vertexAttribPointer("aTexture3d", programObject3D, "aTexture", 2, shapeTexVBO); - curContext.bufferData(curContext.ARRAY_BUFFER, new Float32Array(tArray), curContext.STREAM_DRAW); - } - - curContext.drawArrays( ctxMode, 0, vArray.length/3 ); - curContext.disable( curContext.POLYGON_OFFSET_FILL ); - }; - - /** - * this series of three operations is used a lot in Drawing2D.prototype.endShape - * and has been split off as its own function, to tighten the code and allow for - * fewer bugs. - */ - function fillStrokeClose() { - executeContextFill(); - executeContextStroke(); - curContext.closePath(); - } - - /** - * The endShape() function is the companion to beginShape() and may only be called after beginShape(). - * When endshape() is called, all of image data defined since the previous call to beginShape() is written - * into the image buffer. - * - * @param {int} MODE Use CLOSE to close the shape - * - * @see beginShape - */ - Drawing2D.prototype.endShape = function(mode) { - // Duplicated in Drawing3D; too many variables used - if (vertArray.length === 0) { return; } - - var closeShape = mode === PConstants.CLOSE; - - // if the shape is closed, the first element is also the last element - if (closeShape) { - vertArray.push(vertArray[0]); - } - - var lineVertArray = []; - var fillVertArray = []; - var colorVertArray = []; - var strokeVertArray = []; - var texVertArray = []; - var cachedVertArray; - - firstVert = true; - var i, j, k; - var vertArrayLength = vertArray.length; - - for (i = 0; i < vertArrayLength; i++) { - cachedVertArray = vertArray[i]; - for (j = 0; j < 3; j++) { - fillVertArray.push(cachedVertArray[j]); - } - } - - // 5,6,7,8 - // R,G,B,A - fill colour - for (i = 0; i < vertArrayLength; i++) { - cachedVertArray = vertArray[i]; - for (j = 5; j < 9; j++) { - colorVertArray.push(cachedVertArray[j]); - } - } - - // 9,10,11,12 - // R, G, B, A - stroke colour - for (i = 0; i < vertArrayLength; i++) { - cachedVertArray = vertArray[i]; - for (j = 9; j < 13; j++) { - strokeVertArray.push(cachedVertArray[j]); - } - } - - // texture u,v - for (i = 0; i < vertArrayLength; i++) { - cachedVertArray = vertArray[i]; - texVertArray.push(cachedVertArray[3]); - texVertArray.push(cachedVertArray[4]); - } - - // curveVertex - if ( isCurve && (curShape === PConstants.POLYGON || curShape === undef) ) { - if (vertArrayLength > 3) { - var b = [], - s = 1 - curTightness; - curContext.beginPath(); - curContext.moveTo(vertArray[1][0], vertArray[1][1]); - /* - * Matrix to convert from Catmull-Rom to cubic Bezier - * where t = curTightness - * |0 1 0 0 | - * |(t-1)/6 1 (1-t)/6 0 | - * |0 (1-t)/6 1 (t-1)/6 | - * |0 0 0 0 | - */ - for (i = 1; (i+2) < vertArrayLength; i++) { - cachedVertArray = vertArray[i]; - b[0] = [cachedVertArray[0], cachedVertArray[1]]; - b[1] = [cachedVertArray[0] + (s * vertArray[i+1][0] - s * vertArray[i-1][0]) / 6, - cachedVertArray[1] + (s * vertArray[i+1][1] - s * vertArray[i-1][1]) / 6]; - b[2] = [vertArray[i+1][0] + (s * vertArray[i][0] - s * vertArray[i+2][0]) / 6, - vertArray[i+1][1] + (s * vertArray[i][1] - s * vertArray[i+2][1]) / 6]; - b[3] = [vertArray[i+1][0], vertArray[i+1][1]]; - curContext.bezierCurveTo(b[1][0], b[1][1], b[2][0], b[2][1], b[3][0], b[3][1]); - } - fillStrokeClose(); - } - } - - // bezierVertex - else if ( isBezier && (curShape === PConstants.POLYGON || curShape === undef) ) { - curContext.beginPath(); - for (i = 0; i < vertArrayLength; i++) { - cachedVertArray = vertArray[i]; - if (vertArray[i]["isVert"]) { //if it is a vertex move to the position - if (vertArray[i]["moveTo"]) { - curContext.moveTo(cachedVertArray[0], cachedVertArray[1]); - } else { - curContext.lineTo(cachedVertArray[0], cachedVertArray[1]); - } - } else { //otherwise continue drawing bezier - curContext.bezierCurveTo(vertArray[i][0], vertArray[i][1], vertArray[i][2], vertArray[i][3], vertArray[i][4], vertArray[i][5]); - } - } - fillStrokeClose(); - } - - // render the vertices provided - else { - if (curShape === PConstants.POINTS) { - for (i = 0; i < vertArrayLength; i++) { - cachedVertArray = vertArray[i]; - if (doStroke) { - p.stroke(cachedVertArray[6]); - } - p.point(cachedVertArray[0], cachedVertArray[1]); - } - } else if (curShape === PConstants.LINES) { - for (i = 0; (i + 1) < vertArrayLength; i+=2) { - cachedVertArray = vertArray[i]; - if (doStroke) { - p.stroke(vertArray[i+1][6]); - } - p.line(cachedVertArray[0], cachedVertArray[1], vertArray[i+1][0], vertArray[i+1][1]); - } - } else if (curShape === PConstants.TRIANGLES) { - for (i = 0; (i + 2) < vertArrayLength; i+=3) { - cachedVertArray = vertArray[i]; - curContext.beginPath(); - curContext.moveTo(cachedVertArray[0], cachedVertArray[1]); - curContext.lineTo(vertArray[i+1][0], vertArray[i+1][1]); - curContext.lineTo(vertArray[i+2][0], vertArray[i+2][1]); - curContext.lineTo(cachedVertArray[0], cachedVertArray[1]); - - if (doFill) { - p.fill(vertArray[i+2][5]); - executeContextFill(); - } - if (doStroke) { - p.stroke(vertArray[i+2][6]); - executeContextStroke(); - } - - curContext.closePath(); - } - } else if (curShape === PConstants.TRIANGLE_STRIP) { - for (i = 0; (i+1) < vertArrayLength; i++) { - cachedVertArray = vertArray[i]; - curContext.beginPath(); - curContext.moveTo(vertArray[i+1][0], vertArray[i+1][1]); - curContext.lineTo(cachedVertArray[0], cachedVertArray[1]); - - if (doStroke) { - p.stroke(vertArray[i+1][6]); - } - if (doFill) { - p.fill(vertArray[i+1][5]); - } - - if (i + 2 < vertArrayLength) { - curContext.lineTo(vertArray[i+2][0], vertArray[i+2][1]); - if (doStroke) { - p.stroke(vertArray[i+2][6]); - } - if (doFill) { - p.fill(vertArray[i+2][5]); - } - } - fillStrokeClose(); - } - } else if (curShape === PConstants.TRIANGLE_FAN) { - if (vertArrayLength > 2) { - curContext.beginPath(); - curContext.moveTo(vertArray[0][0], vertArray[0][1]); - curContext.lineTo(vertArray[1][0], vertArray[1][1]); - curContext.lineTo(vertArray[2][0], vertArray[2][1]); - - if (doFill) { - p.fill(vertArray[2][5]); - executeContextFill(); - } - if (doStroke) { - p.stroke(vertArray[2][6]); - executeContextStroke(); - } - - curContext.closePath(); - for (i = 3; i < vertArrayLength; i++) { - cachedVertArray = vertArray[i]; - curContext.beginPath(); - curContext.moveTo(vertArray[0][0], vertArray[0][1]); - curContext.lineTo(vertArray[i-1][0], vertArray[i-1][1]); - curContext.lineTo(cachedVertArray[0], cachedVertArray[1]); - - if (doFill) { - p.fill(cachedVertArray[5]); - executeContextFill(); - } - if (doStroke) { - p.stroke(cachedVertArray[6]); - executeContextStroke(); - } - - curContext.closePath(); - } - } - } else if (curShape === PConstants.QUADS) { - for (i = 0; (i + 3) < vertArrayLength; i+=4) { - cachedVertArray = vertArray[i]; - curContext.beginPath(); - curContext.moveTo(cachedVertArray[0], cachedVertArray[1]); - for (j = 1; j < 4; j++) { - curContext.lineTo(vertArray[i+j][0], vertArray[i+j][1]); - } - curContext.lineTo(cachedVertArray[0], cachedVertArray[1]); - - if (doFill) { - p.fill(vertArray[i+3][5]); - executeContextFill(); - } - if (doStroke) { - p.stroke(vertArray[i+3][6]); - executeContextStroke(); - } - - curContext.closePath(); - } - } else if (curShape === PConstants.QUAD_STRIP) { - if (vertArrayLength > 3) { - for (i = 0; (i+1) < vertArrayLength; i+=2) { - cachedVertArray = vertArray[i]; - curContext.beginPath(); - if (i+3 < vertArrayLength) { - curContext.moveTo(vertArray[i+2][0], vertArray[i+2][1]); - curContext.lineTo(cachedVertArray[0], cachedVertArray[1]); - curContext.lineTo(vertArray[i+1][0], vertArray[i+1][1]); - curContext.lineTo(vertArray[i+3][0], vertArray[i+3][1]); - - if (doFill) { - p.fill(vertArray[i+3][5]); - } - if (doStroke) { - p.stroke(vertArray[i+3][6]); - } - } else { - curContext.moveTo(cachedVertArray[0], cachedVertArray[1]); - curContext.lineTo(vertArray[i+1][0], vertArray[i+1][1]); - } - fillStrokeClose(); - } - } - } else { - curContext.beginPath(); - curContext.moveTo(vertArray[0][0], vertArray[0][1]); - for (i = 1; i < vertArrayLength; i++) { - cachedVertArray = vertArray[i]; - if (cachedVertArray["isVert"]) { //if it is a vertex move to the position - if (cachedVertArray["moveTo"]) { - curContext.moveTo(cachedVertArray[0], cachedVertArray[1]); - } else { - curContext.lineTo(cachedVertArray[0], cachedVertArray[1]); - } - } - } - fillStrokeClose(); - } - } - - // Reset some settings - isCurve = false; - isBezier = false; - curveVertArray = []; - curveVertCount = 0; - - // If the shape is closed, the first element was added as last element. - // We must remove it again to prevent the list of vertices from growing - // over successive calls to endShape(CLOSE) - if (closeShape) { - vertArray.pop(); - } - }; - - Drawing3D.prototype.endShape = function(mode) { - // Duplicated in Drawing3D; too many variables used - if (vertArray.length === 0) { return; } - - var closeShape = mode === PConstants.CLOSE; - var lineVertArray = []; - var fillVertArray = []; - var colorVertArray = []; - var strokeVertArray = []; - var texVertArray = []; - var cachedVertArray; - - firstVert = true; - var i, j, k; - var vertArrayLength = vertArray.length; - - for (i = 0; i < vertArrayLength; i++) { - cachedVertArray = vertArray[i]; - for (j = 0; j < 3; j++) { - fillVertArray.push(cachedVertArray[j]); - } - } - - // 5,6,7,8 - // R,G,B,A - fill colour - for (i = 0; i < vertArrayLength; i++) { - cachedVertArray = vertArray[i]; - for (j = 5; j < 9; j++) { - colorVertArray.push(cachedVertArray[j]); - } - } - - // 9,10,11,12 - // R, G, B, A - stroke colour - for (i = 0; i < vertArrayLength; i++) { - cachedVertArray = vertArray[i]; - for (j = 9; j < 13; j++) { - strokeVertArray.push(cachedVertArray[j]); - } - } - - // texture u,v - for (i = 0; i < vertArrayLength; i++) { - cachedVertArray = vertArray[i]; - texVertArray.push(cachedVertArray[3]); - texVertArray.push(cachedVertArray[4]); - } - - // if shape is closed, push the first point into the last point (including colours) - if (closeShape) { - fillVertArray.push(vertArray[0][0]); - fillVertArray.push(vertArray[0][1]); - fillVertArray.push(vertArray[0][2]); - - for (i = 5; i < 9; i++) { - colorVertArray.push(vertArray[0][i]); - } - - for (i = 9; i < 13; i++) { - strokeVertArray.push(vertArray[0][i]); - } - - texVertArray.push(vertArray[0][3]); - texVertArray.push(vertArray[0][4]); - } - // End duplication - - // curveVertex - if ( isCurve && (curShape === PConstants.POLYGON || curShape === undef) ) { - lineVertArray = fillVertArray; - if (doStroke) { - line3D(lineVertArray, null, strokeVertArray); - } - if (doFill) { - fill3D(fillVertArray, null, colorVertArray); - } - } - // bezierVertex - else if ( isBezier && (curShape === PConstants.POLYGON || curShape === undef) ) { - lineVertArray = fillVertArray; - lineVertArray.splice(lineVertArray.length - 3); - strokeVertArray.splice(strokeVertArray.length - 4); - if (doStroke) { - line3D(lineVertArray, null, strokeVertArray); - } - if (doFill) { - fill3D(fillVertArray, "TRIANGLES", colorVertArray); - } - } - - // render the vertices provided - else { - if (curShape === PConstants.POINTS) { // if POINTS was the specified parameter in beginShape - for (i = 0; i < vertArrayLength; i++) { // loop through and push the point location information to the array - cachedVertArray = vertArray[i]; - for (j = 0; j < 3; j++) { - lineVertArray.push(cachedVertArray[j]); - } - } - point3D(lineVertArray, strokeVertArray); // render function for points - } else if (curShape === PConstants.LINES) { // if LINES was the specified parameter in beginShape - for (i = 0; i < vertArrayLength; i++) { // loop through and push the point location information to the array - cachedVertArray = vertArray[i]; - for (j = 0; j < 3; j++) { - lineVertArray.push(cachedVertArray[j]); - } - } - for (i = 0; i < vertArrayLength; i++) { // loop through and push the color information to the array - cachedVertArray = vertArray[i]; - for (j = 5; j < 9; j++) { - colorVertArray.push(cachedVertArray[j]); - } - } - line3D(lineVertArray, "LINES", strokeVertArray); // render function for lines - } else if (curShape === PConstants.TRIANGLES) { // if TRIANGLES was the specified parameter in beginShape - if (vertArrayLength > 2) { - for (i = 0; (i+2) < vertArrayLength; i+=3) { // loop through the array per triangle - fillVertArray = []; - texVertArray = []; - lineVertArray = []; - colorVertArray = []; - strokeVertArray = []; - for (j = 0; j < 3; j++) { - for (k = 0; k < 3; k++) { // loop through and push - lineVertArray.push(vertArray[i+j][k]); // the line point location information - fillVertArray.push(vertArray[i+j][k]); // and fill point location information - } - } - for (j = 0; j < 3; j++) { // loop through and push the texture information - for (k = 3; k < 5; k++) { - texVertArray.push(vertArray[i+j][k]); - } - } - for (j = 0; j < 3; j++) { - for (k = 5; k < 9; k++) { // loop through and push - colorVertArray.push(vertArray[i+j][k]); // the colour information - strokeVertArray.push(vertArray[i+j][k+4]);// and the stroke information - } - } - if (doStroke) { - line3D(lineVertArray, "LINE_LOOP", strokeVertArray ); // line render function - } - if (doFill || usingTexture) { - fill3D(fillVertArray, "TRIANGLES", colorVertArray, texVertArray); // fill shape render function - } - } - } - } else if (curShape === PConstants.TRIANGLE_STRIP) { // if TRIANGLE_STRIP was the specified parameter in beginShape - if (vertArrayLength > 2) { - for (i = 0; (i+2) < vertArrayLength; i++) { - lineVertArray = []; - fillVertArray = []; - strokeVertArray = []; - colorVertArray = []; - texVertArray = []; - for (j = 0; j < 3; j++) { - for (k = 0; k < 3; k++) { - lineVertArray.push(vertArray[i+j][k]); - fillVertArray.push(vertArray[i+j][k]); - } - } - for (j = 0; j < 3; j++) { - for (k = 3; k < 5; k++) { - texVertArray.push(vertArray[i+j][k]); - } - } - for (j = 0; j < 3; j++) { - for (k = 5; k < 9; k++) { - strokeVertArray.push(vertArray[i+j][k+4]); - colorVertArray.push(vertArray[i+j][k]); - } - } - - if (doFill || usingTexture) { - fill3D(fillVertArray, "TRIANGLE_STRIP", colorVertArray, texVertArray); - } - if (doStroke) { - line3D(lineVertArray, "LINE_LOOP", strokeVertArray); - } - } - } - } else if (curShape === PConstants.TRIANGLE_FAN) { - if (vertArrayLength > 2) { - for (i = 0; i < 3; i++) { - cachedVertArray = vertArray[i]; - for (j = 0; j < 3; j++) { - lineVertArray.push(cachedVertArray[j]); - } - } - for (i = 0; i < 3; i++) { - cachedVertArray = vertArray[i]; - for (j = 9; j < 13; j++) { - strokeVertArray.push(cachedVertArray[j]); - } - } - if (doStroke) { - line3D(lineVertArray, "LINE_LOOP", strokeVertArray); - } - - for (i = 2; (i+1) < vertArrayLength; i++) { - lineVertArray = []; - strokeVertArray = []; - lineVertArray.push(vertArray[0][0]); - lineVertArray.push(vertArray[0][1]); - lineVertArray.push(vertArray[0][2]); - - strokeVertArray.push(vertArray[0][9]); - strokeVertArray.push(vertArray[0][10]); - strokeVertArray.push(vertArray[0][11]); - strokeVertArray.push(vertArray[0][12]); - - for (j = 0; j < 2; j++) { - for (k = 0; k < 3; k++) { - lineVertArray.push(vertArray[i+j][k]); - } - } - for (j = 0; j < 2; j++) { - for (k = 9; k < 13; k++) { - strokeVertArray.push(vertArray[i+j][k]); - } - } - if (doStroke) { - line3D(lineVertArray, "LINE_STRIP",strokeVertArray); - } - } - if (doFill || usingTexture) { - fill3D(fillVertArray, "TRIANGLE_FAN", colorVertArray, texVertArray); - } - } - } else if (curShape === PConstants.QUADS) { - for (i = 0; (i + 3) < vertArrayLength; i+=4) { - lineVertArray = []; - for (j = 0; j < 4; j++) { - cachedVertArray = vertArray[i+j]; - for (k = 0; k < 3; k++) { - lineVertArray.push(cachedVertArray[k]); - } - } - if (doStroke) { - line3D(lineVertArray, "LINE_LOOP",strokeVertArray); - } - - if (doFill) { - fillVertArray = []; - colorVertArray = []; - texVertArray = []; - for (j = 0; j < 3; j++) { - fillVertArray.push(vertArray[i][j]); - } - for (j = 5; j < 9; j++) { - colorVertArray.push(vertArray[i][j]); - } - - for (j = 0; j < 3; j++) { - fillVertArray.push(vertArray[i+1][j]); - } - for (j = 5; j < 9; j++) { - colorVertArray.push(vertArray[i+1][j]); - } - - for (j = 0; j < 3; j++) { - fillVertArray.push(vertArray[i+3][j]); - } - for (j = 5; j < 9; j++) { - colorVertArray.push(vertArray[i+3][j]); - } - - for (j = 0; j < 3; j++) { - fillVertArray.push(vertArray[i+2][j]); - } - for (j = 5; j < 9; j++) { - colorVertArray.push(vertArray[i+2][j]); - } - - if (usingTexture) { - texVertArray.push(vertArray[i+0][3]); - texVertArray.push(vertArray[i+0][4]); - texVertArray.push(vertArray[i+1][3]); - texVertArray.push(vertArray[i+1][4]); - texVertArray.push(vertArray[i+3][3]); - texVertArray.push(vertArray[i+3][4]); - texVertArray.push(vertArray[i+2][3]); - texVertArray.push(vertArray[i+2][4]); - } - - fill3D(fillVertArray, "TRIANGLE_STRIP", colorVertArray, texVertArray); - } - } - } else if (curShape === PConstants.QUAD_STRIP) { - var tempArray = []; - if (vertArrayLength > 3) { - for (i = 0; i < 2; i++) { - cachedVertArray = vertArray[i]; - for (j = 0; j < 3; j++) { - lineVertArray.push(cachedVertArray[j]); - } - } - - for (i = 0; i < 2; i++) { - cachedVertArray = vertArray[i]; - for (j = 9; j < 13; j++) { - strokeVertArray.push(cachedVertArray[j]); - } - } - - line3D(lineVertArray, "LINE_STRIP", strokeVertArray); - if (vertArrayLength > 4 && vertArrayLength % 2 > 0) { - tempArray = fillVertArray.splice(fillVertArray.length - 3); - vertArray.pop(); - } - for (i = 0; (i+3) < vertArrayLength; i+=2) { - lineVertArray = []; - strokeVertArray = []; - for (j = 0; j < 3; j++) { - lineVertArray.push(vertArray[i+1][j]); - } - for (j = 0; j < 3; j++) { - lineVertArray.push(vertArray[i+3][j]); - } - for (j = 0; j < 3; j++) { - lineVertArray.push(vertArray[i+2][j]); - } - for (j = 0; j < 3; j++) { - lineVertArray.push(vertArray[i+0][j]); - } - for (j = 9; j < 13; j++) { - strokeVertArray.push(vertArray[i+1][j]); - } - for (j = 9; j < 13; j++) { - strokeVertArray.push(vertArray[i+3][j]); - } - for (j = 9; j < 13; j++) { - strokeVertArray.push(vertArray[i+2][j]); - } - for (j = 9; j < 13; j++) { - strokeVertArray.push(vertArray[i+0][j]); - } - if (doStroke) { - line3D(lineVertArray, "LINE_STRIP", strokeVertArray); - } - } - - if (doFill || usingTexture) { - fill3D(fillVertArray, "TRIANGLE_LIST", colorVertArray, texVertArray); - } - } - } - // If the user didn't specify a type (LINES, TRIANGLES, etc) - else { - // If only one vertex was specified, it must be a point - if (vertArrayLength === 1) { - for (j = 0; j < 3; j++) { - lineVertArray.push(vertArray[0][j]); - } - for (j = 9; j < 13; j++) { - strokeVertArray.push(vertArray[0][j]); - } - point3D(lineVertArray,strokeVertArray); - } else { - for (i = 0; i < vertArrayLength; i++) { - cachedVertArray = vertArray[i]; - for (j = 0; j < 3; j++) { - lineVertArray.push(cachedVertArray[j]); - } - for (j = 5; j < 9; j++) { - strokeVertArray.push(cachedVertArray[j]); - } - } - if (doStroke && closeShape) { - line3D(lineVertArray, "LINE_LOOP", strokeVertArray); - } else if (doStroke && !closeShape) { - line3D(lineVertArray, "LINE_STRIP", strokeVertArray); - } - - // fill is ignored if textures are used - if (doFill || usingTexture) { - fill3D(fillVertArray, "TRIANGLE_FAN", colorVertArray, texVertArray); - } - } - } - // everytime beginShape is followed by a call to - // texture(), texturing it turned back on. We do this to - // figure out if the shape should be textured or filled - // with a color. - usingTexture = false; - curContext.useProgram(programObject3D); - uniformi("usingTexture3d", programObject3D, "usingTexture", usingTexture); - } - - // Reset some settings - isCurve = false; - isBezier = false; - curveVertArray = []; - curveVertCount = 0; - }; - - /** - * The function splineForward() setup forward-differencing matrix to be used for speedy - * curve rendering. It's based on using a specific number - * of curve segments and just doing incremental adds for each - * vertex of the segment, rather than running the mathematically - * expensive cubic equation. This function is used by both curveDetail and bezierDetail. - * - * @param {int} segments number of curve segments to use when drawing - * @param {PMatrix3D} matrix target object for the new matrix - */ - var splineForward = function(segments, matrix) { - var f = 1.0 / segments; - var ff = f * f; - var fff = ff * f; - - matrix.set(0, 0, 0, 1, fff, ff, f, 0, 6 * fff, 2 * ff, 0, 0, 6 * fff, 0, 0, 0); - }; - - /** - * The curveInit() function set the number of segments to use when drawing a Catmull-Rom - * curve, and setting the s parameter, which defines how tightly - * the curve fits to each vertex. Catmull-Rom curves are actually - * a subset of this curve type where the s is set to zero. - * This in an internal function used by curveDetail() and curveTightness(). - */ - var curveInit = function() { - // allocate only if/when used to save startup time - if (!curveDrawMatrix) { - curveBasisMatrix = new PMatrix3D(); - curveDrawMatrix = new PMatrix3D(); - curveInited = true; - } - - var s = curTightness; - curveBasisMatrix.set((s - 1) / 2, (s + 3) / 2, (-3 - s) / 2, (1 - s) / 2, - (1 - s), (-5 - s) / 2, (s + 2), (s - 1) / 2, - (s - 1) / 2, 0, (1 - s) / 2, 0, 0, 1, 0, 0); - - splineForward(curveDet, curveDrawMatrix); - - if (!bezierBasisInverse) { - //bezierBasisInverse = bezierBasisMatrix.get(); - //bezierBasisInverse.invert(); - curveToBezierMatrix = new PMatrix3D(); - } - - // TODO only needed for PGraphicsJava2D? if so, move it there - // actually, it's generally useful for other renderers, so keep it - // or hide the implementation elsewhere. - curveToBezierMatrix.set(curveBasisMatrix); - curveToBezierMatrix.preApply(bezierBasisInverse); - - // multiply the basis and forward diff matrices together - // saves much time since this needn't be done for each curve - curveDrawMatrix.apply(curveBasisMatrix); - }; - - /** - * Specifies vertex coordinates for Bezier curves. Each call to bezierVertex() defines the position of two control - * points and one anchor point of a Bezier curve, adding a new segment to a line or shape. The first time - * bezierVertex() is used within a beginShape() call, it must be prefaced with a call to vertex() - * to set the first anchor point. This function must be used between beginShape() and endShape() and only - * when there is no MODE parameter specified to beginShape(). Using the 3D version of requires rendering with P3D - * or OPENGL (see the Environment reference for more information).

NOTE: Fill does not work properly yet. - * - * @param {float | int} cx1 The x-coordinate of 1st control point - * @param {float | int} cy1 The y-coordinate of 1st control point - * @param {float | int} cz1 The z-coordinate of 1st control point - * @param {float | int} cx2 The x-coordinate of 2nd control point - * @param {float | int} cy2 The y-coordinate of 2nd control point - * @param {float | int} cz2 The z-coordinate of 2nd control point - * @param {float | int} x The x-coordinate of the anchor point - * @param {float | int} y The y-coordinate of the anchor point - * @param {float | int} z The z-coordinate of the anchor point - * - * @see curveVertex - * @see vertex - * @see bezier - */ - Drawing2D.prototype.bezierVertex = function() { - isBezier = true; - var vert = []; - if (firstVert) { - throw ("vertex() must be used at least once before calling bezierVertex()"); - } - - for (var i = 0; i < arguments.length; i++) { - vert[i] = arguments[i]; - } - vertArray.push(vert); - vertArray[vertArray.length -1]["isVert"] = false; - }; - - Drawing3D.prototype.bezierVertex = function() { - isBezier = true; - var vert = []; - if (firstVert) { - throw ("vertex() must be used at least once before calling bezierVertex()"); - } - - if (arguments.length === 9) { - if (bezierDrawMatrix === undef) { - bezierDrawMatrix = new PMatrix3D(); - } - // setup matrix for forward differencing to speed up drawing - var lastPoint = vertArray.length - 1; - splineForward( bezDetail, bezierDrawMatrix ); - bezierDrawMatrix.apply( bezierBasisMatrix ); - var draw = bezierDrawMatrix.array(); - var x1 = vertArray[lastPoint][0], - y1 = vertArray[lastPoint][1], - z1 = vertArray[lastPoint][2]; - var xplot1 = draw[4] * x1 + draw[5] * arguments[0] + draw[6] * arguments[3] + draw[7] * arguments[6]; - var xplot2 = draw[8] * x1 + draw[9] * arguments[0] + draw[10]* arguments[3] + draw[11]* arguments[6]; - var xplot3 = draw[12]* x1 + draw[13]* arguments[0] + draw[14]* arguments[3] + draw[15]* arguments[6]; - - var yplot1 = draw[4] * y1 + draw[5] * arguments[1] + draw[6] * arguments[4] + draw[7] * arguments[7]; - var yplot2 = draw[8] * y1 + draw[9] * arguments[1] + draw[10]* arguments[4] + draw[11]* arguments[7]; - var yplot3 = draw[12]* y1 + draw[13]* arguments[1] + draw[14]* arguments[4] + draw[15]* arguments[7]; - - var zplot1 = draw[4] * z1 + draw[5] * arguments[2] + draw[6] * arguments[5] + draw[7] * arguments[8]; - var zplot2 = draw[8] * z1 + draw[9] * arguments[2] + draw[10]* arguments[5] + draw[11]* arguments[8]; - var zplot3 = draw[12]* z1 + draw[13]* arguments[2] + draw[14]* arguments[5] + draw[15]* arguments[8]; - for (var j = 0; j < bezDetail; j++) { - x1 += xplot1; xplot1 += xplot2; xplot2 += xplot3; - y1 += yplot1; yplot1 += yplot2; yplot2 += yplot3; - z1 += zplot1; zplot1 += zplot2; zplot2 += zplot3; - p.vertex(x1, y1, z1); - } - p.vertex(arguments[6], arguments[7], arguments[8]); - } - }; - - /** - * Sets a texture to be applied to vertex points. The texture() function - * must be called between beginShape() and endShape() and before - * any calls to vertex(). - * - * When textures are in use, the fill color is ignored. Instead, use tint() to - * specify the color of the texture as it is applied to the shape. - * - * @param {PImage} pimage the texture to apply - * - * @returns none - * - * @see textureMode - * @see beginShape - * @see endShape - * @see vertex - */ - p.texture = function(pimage) { - var curContext = drawing.$ensureContext(); - - if (pimage.__texture) { - curContext.bindTexture(curContext.TEXTURE_2D, pimage.__texture); - } else if (pimage.localName === "canvas") { - curContext.bindTexture(curContext.TEXTURE_2D, canTex); - curContext.texImage2D(curContext.TEXTURE_2D, 0, curContext.RGBA, curContext.RGBA, curContext.UNSIGNED_BYTE, pimage); - curContext.texParameteri(curContext.TEXTURE_2D, curContext.TEXTURE_MAG_FILTER, curContext.LINEAR); - curContext.texParameteri(curContext.TEXTURE_2D, curContext.TEXTURE_MIN_FILTER, curContext.LINEAR); - curContext.generateMipmap(curContext.TEXTURE_2D); - curTexture.width = pimage.width; - curTexture.height = pimage.height; - } else { - var texture = curContext.createTexture(), - cvs = document.createElement('canvas'), - cvsTextureCtx = cvs.getContext('2d'), - pot; - - // WebGL requires power of two textures - if (pimage.width & (pimage.width-1) === 0) { - cvs.width = pimage.width; - } else { - pot = 1; - while (pot < pimage.width) { - pot *= 2; - } - cvs.width = pot; - } - - if (pimage.height & (pimage.height-1) === 0) { - cvs.height = pimage.height; - } else { - pot = 1; - while (pot < pimage.height) { - pot *= 2; - } - cvs.height = pot; - } - - cvsTextureCtx.drawImage(pimage.sourceImg, 0, 0, pimage.width, pimage.height, 0, 0, cvs.width, cvs.height); - - curContext.bindTexture(curContext.TEXTURE_2D, texture); - curContext.texParameteri(curContext.TEXTURE_2D, curContext.TEXTURE_MIN_FILTER, curContext.LINEAR_MIPMAP_LINEAR); - curContext.texParameteri(curContext.TEXTURE_2D, curContext.TEXTURE_MAG_FILTER, curContext.LINEAR); - curContext.texParameteri(curContext.TEXTURE_2D, curContext.TEXTURE_WRAP_T, curContext.CLAMP_TO_EDGE); - curContext.texParameteri(curContext.TEXTURE_2D, curContext.TEXTURE_WRAP_S, curContext.CLAMP_TO_EDGE); - curContext.texImage2D(curContext.TEXTURE_2D, 0, curContext.RGBA, curContext.RGBA, curContext.UNSIGNED_BYTE, cvs); - curContext.generateMipmap(curContext.TEXTURE_2D); - - pimage.__texture = texture; - curTexture.width = pimage.width; - curTexture.height = pimage.height; - } - - usingTexture = true; - curContext.useProgram(programObject3D); - uniformi("usingTexture3d", programObject3D, "usingTexture", usingTexture); - }; - - /** - * Sets the coordinate space for texture mapping. There are two options, IMAGE, - * which refers to the actual coordinates of the image, and NORMALIZED, which - * refers to a normalized space of values ranging from 0 to 1. The default mode - * is IMAGE. In IMAGE, if an image is 100 x 200 pixels, mapping the image onto - * the entire size of a quad would require the points (0,0) (0,100) (100,200) (0,200). - * The same mapping in NORMAL_SPACE is (0,0) (0,1) (1,1) (0,1). - * - * @param MODE either IMAGE or NORMALIZED - * - * @returns none - * - * @see texture - */ - p.textureMode = function(mode){ - curTextureMode = mode; - }; - /** - * The curveVertexSegment() function handle emitting a specific segment of Catmull-Rom curve. Internal helper function used by curveVertex(). - */ - var curveVertexSegment = function(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4) { - var x0 = x2; - var y0 = y2; - var z0 = z2; - - var draw = curveDrawMatrix.array(); - - var xplot1 = draw[4] * x1 + draw[5] * x2 + draw[6] * x3 + draw[7] * x4; - var xplot2 = draw[8] * x1 + draw[9] * x2 + draw[10] * x3 + draw[11] * x4; - var xplot3 = draw[12] * x1 + draw[13] * x2 + draw[14] * x3 + draw[15] * x4; - - var yplot1 = draw[4] * y1 + draw[5] * y2 + draw[6] * y3 + draw[7] * y4; - var yplot2 = draw[8] * y1 + draw[9] * y2 + draw[10] * y3 + draw[11] * y4; - var yplot3 = draw[12] * y1 + draw[13] * y2 + draw[14] * y3 + draw[15] * y4; - - var zplot1 = draw[4] * z1 + draw[5] * z2 + draw[6] * z3 + draw[7] * z4; - var zplot2 = draw[8] * z1 + draw[9] * z2 + draw[10] * z3 + draw[11] * z4; - var zplot3 = draw[12] * z1 + draw[13] * z2 + draw[14] * z3 + draw[15] * z4; - - p.vertex(x0, y0, z0); - for (var j = 0; j < curveDet; j++) { - x0 += xplot1; xplot1 += xplot2; xplot2 += xplot3; - y0 += yplot1; yplot1 += yplot2; yplot2 += yplot3; - z0 += zplot1; zplot1 += zplot2; zplot2 += zplot3; - p.vertex(x0, y0, z0); - } - }; - - /** - * Specifies vertex coordinates for curves. This function may only be used between beginShape() and - * endShape() and only when there is no MODE parameter specified to beginShape(). The first and last points - * in a series of curveVertex() lines will be used to guide the beginning and end of a the curve. A minimum of four - * points is required to draw a tiny curve between the second and third points. Adding a fifth point with - * curveVertex() will draw the curve between the second, third, and fourth points. The curveVertex() function - * is an implementation of Catmull-Rom splines. Using the 3D version of requires rendering with P3D or OPENGL (see the - * Environment reference for more information).

NOTE: Fill does not work properly yet. - * - * @param {float | int} x The x-coordinate of the vertex - * @param {float | int} y The y-coordinate of the vertex - * @param {float | int} z The z-coordinate of the vertex - * - * @see curve - * @see beginShape - * @see endShape - * @see vertex - * @see bezierVertex - */ - Drawing2D.prototype.curveVertex = function(x, y) { - isCurve = true; - - p.vertex(x, y); - }; - - Drawing3D.prototype.curveVertex = function(x, y, z) { - isCurve = true; - - if (!curveInited) { - curveInit(); - } - var vert = []; - vert[0] = x; - vert[1] = y; - vert[2] = z; - curveVertArray.push(vert); - curveVertCount++; - - if (curveVertCount > 3) { - curveVertexSegment( curveVertArray[curveVertCount-4][0], - curveVertArray[curveVertCount-4][1], - curveVertArray[curveVertCount-4][2], - curveVertArray[curveVertCount-3][0], - curveVertArray[curveVertCount-3][1], - curveVertArray[curveVertCount-3][2], - curveVertArray[curveVertCount-2][0], - curveVertArray[curveVertCount-2][1], - curveVertArray[curveVertCount-2][2], - curveVertArray[curveVertCount-1][0], - curveVertArray[curveVertCount-1][1], - curveVertArray[curveVertCount-1][2] ); - } - }; - - /** - * The curve() function draws a curved line on the screen. The first and second parameters - * specify the beginning control point and the last two parameters specify - * the ending control point. The middle parameters specify the start and - * stop of the curve. Longer curves can be created by putting a series of - * curve() functions together or using curveVertex(). - * An additional function called curveTightness() provides control - * for the visual quality of the curve. The curve() function is an - * implementation of Catmull-Rom splines. Using the 3D version of requires - * rendering with P3D or OPENGL (see the Environment reference for more - * information). - * - * @param {int|float} x1 coordinates for the beginning control point - * @param {int|float} y1 coordinates for the beginning control point - * @param {int|float} z1 coordinates for the beginning control point - * @param {int|float} x2 coordinates for the first point - * @param {int|float} y2 coordinates for the first point - * @param {int|float} z2 coordinates for the first point - * @param {int|float} x3 coordinates for the second point - * @param {int|float} y3 coordinates for the second point - * @param {int|float} z3 coordinates for the second point - * @param {int|float} x4 coordinates for the ending control point - * @param {int|float} y4 coordinates for the ending control point - * @param {int|float} z4 coordinates for the ending control point - * - * @see #curveVertex() - * @see #curveTightness() - * @see #bezier() - */ - Drawing2D.prototype.curve = function() { - if (arguments.length === 8) { // curve(x1, y1, x2, y2, x3, y3, x4, y4) - p.beginShape(); - p.curveVertex(arguments[0], arguments[1]); - p.curveVertex(arguments[2], arguments[3]); - p.curveVertex(arguments[4], arguments[5]); - p.curveVertex(arguments[6], arguments[7]); - p.endShape(); - } - }; - - Drawing3D.prototype.curve = function() { - if (arguments.length === 12) { // curve( x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4); - p.beginShape(); - p.curveVertex(arguments[0], arguments[1], arguments[2]); - p.curveVertex(arguments[3], arguments[4], arguments[5]); - p.curveVertex(arguments[6], arguments[7], arguments[8]); - p.curveVertex(arguments[9], arguments[10], arguments[11]); - p.endShape(); - } - }; - - /** - * The curveTightness() function modifies the quality of forms created with curve() and - * curveVertex(). The parameter squishy determines how the - * curve fits to the vertex points. The value 0.0 is the default value for - * squishy (this value defines the curves to be Catmull-Rom splines) - * and the value 1.0 connects all the points with straight lines. - * Values within the range -5.0 and 5.0 will deform the curves but - * will leave them recognizable and as values increase in magnitude, - * they will continue to deform. - * - * @param {float} tightness amount of deformation from the original vertices - * - * @see #curve() - * @see #curveVertex() - * - */ - p.curveTightness = function(tightness) { - curTightness = tightness; - }; - - /** - * The curveDetail() function sets the resolution at which curves display. The default value is 20. - * This function is only useful when using the P3D or OPENGL renderer. - * - * @param {int} detail resolution of the curves - * - * @see curve() - * @see curveVertex() - * @see curveTightness() - */ - p.curveDetail = function(detail) { - curveDet = detail; - curveInit(); - }; - - /** - * Modifies the location from which rectangles draw. The default mode is rectMode(CORNER), which - * specifies the location to be the upper left corner of the shape and uses the third and fourth - * parameters of rect() to specify the width and height. The syntax rectMode(CORNERS) uses the - * first and second parameters of rect() to set the location of one corner and uses the third and - * fourth parameters to set the opposite corner. The syntax rectMode(CENTER) draws the image from - * its center point and uses the third and forth parameters of rect() to specify the image's width - * and height. The syntax rectMode(RADIUS) draws the image from its center point and uses the third - * and forth parameters of rect() to specify half of the image's width and height. The parameter must - * be written in ALL CAPS because Processing is a case sensitive language. Note: In version 125, the - * mode named CENTER_RADIUS was shortened to RADIUS. - * - * @param {MODE} MODE Either CORNER, CORNERS, CENTER, or RADIUS - * - * @see rect - */ - p.rectMode = function(aRectMode) { - curRectMode = aRectMode; - }; - - /** - * Modifies the location from which images draw. The default mode is imageMode(CORNER), which specifies - * the location to be the upper left corner and uses the fourth and fifth parameters of image() to set - * the image's width and height. The syntax imageMode(CORNERS) uses the second and third parameters of - * image() to set the location of one corner of the image and uses the fourth and fifth parameters to - * set the opposite corner. Use imageMode(CENTER) to draw images centered at the given x and y position. - * The parameter to imageMode() must be written in ALL CAPS because Processing is a case sensitive language. - * - * @param {MODE} MODE Either CORNER, CORNERS, or CENTER - * - * @see loadImage - * @see PImage - * @see image - * @see background - */ - p.imageMode = function(mode) { - switch (mode) { - case PConstants.CORNER: - imageModeConvert = imageModeCorner; - break; - case PConstants.CORNERS: - imageModeConvert = imageModeCorners; - break; - case PConstants.CENTER: - imageModeConvert = imageModeCenter; - break; - default: - throw "Invalid imageMode"; - } - }; - - /** - * The origin of the ellipse is modified by the ellipseMode() function. The default configuration is - * ellipseMode(CENTER), which specifies the location of the ellipse as the center of the shape. The RADIUS - * mode is the same, but the width and height parameters to ellipse() specify the radius of the ellipse, - * rather than the diameter. The CORNER mode draws the shape from the upper-left corner of its bounding box. - * The CORNERS mode uses the four parameters to ellipse() to set two opposing corners of the ellipse's bounding - * box. The parameter must be written in "ALL CAPS" because Processing is a case sensitive language. - * - * @param {MODE} MODE Either CENTER, RADIUS, CORNER, or CORNERS. - * - * @see ellipse - */ - p.ellipseMode = function(aEllipseMode) { - curEllipseMode = aEllipseMode; - }; - - /** - * The arc() function draws an arc in the display window. - * Arcs are drawn along the outer edge of an ellipse defined by the - * x, y, width and height parameters. - * The origin or the arc's ellipse may be changed with the - * ellipseMode() function. - * The start and stop parameters specify the angles - * at which to draw the arc. - * - * @param {float} a x-coordinate of the arc's ellipse - * @param {float} b y-coordinate of the arc's ellipse - * @param {float} c width of the arc's ellipse - * @param {float} d height of the arc's ellipse - * @param {float} start angle to start the arc, specified in radians - * @param {float} stop angle to stop the arc, specified in radians - * - * @see #ellipseMode() - * @see #ellipse() - */ - p.arc = function(x, y, width, height, start, stop) { - if (width <= 0 || stop < start) { return; } - - if (curEllipseMode === PConstants.CORNERS) { - width = width - x; - height = height - y; - } else if (curEllipseMode === PConstants.RADIUS) { - x = x - width; - y = y - height; - width = width * 2; - height = height * 2; - } else if (curEllipseMode === PConstants.CENTER) { - x = x - width/2; - y = y - height/2; - } - // make sure that we're starting at a useful point - while (start < 0) { - start += PConstants.TWO_PI; - stop += PConstants.TWO_PI; - } - if (stop - start > PConstants.TWO_PI) { - start = 0; - stop = PConstants.TWO_PI; - } - var hr = width / 2; - var vr = height / 2; - var centerX = x + hr; - var centerY = y + vr; - var startLUT = 0 | (-0.5 + start * p.RAD_TO_DEG * 2); - var stopLUT = 0 | (0.5 + stop * p.RAD_TO_DEG * 2); - var i, j; - if (doFill) { - // shut off stroke for a minute - var savedStroke = doStroke; - doStroke = false; - p.beginShape(); - p.vertex(centerX, centerY); - for (i = startLUT; i <= stopLUT; i++) { - j = i % PConstants.SINCOS_LENGTH; - p.vertex(centerX + cosLUT[j] * hr, centerY + sinLUT[j] * vr); - } - p.endShape(PConstants.CLOSE); - doStroke = savedStroke; - } - - if (doStroke) { - // and doesn't include the first (center) vertex. - var savedFill = doFill; - doFill = false; - p.beginShape(); - for (i = startLUT; i <= stopLUT; i++) { - j = i % PConstants.SINCOS_LENGTH; - p.vertex(centerX + cosLUT[j] * hr, centerY + sinLUT[j] * vr); - } - p.endShape(); - doFill = savedFill; - } - }; - - /** - * Draws a line (a direct path between two points) to the screen. The version of line() with four parameters - * draws the line in 2D. To color a line, use the stroke() function. A line cannot be filled, therefore the - * fill() method will not affect the color of a line. 2D lines are drawn with a width of one pixel by default, - * but this can be changed with the strokeWeight() function. The version with six parameters allows the line - * to be placed anywhere within XYZ space. Drawing this shape in 3D using the z parameter requires the P3D or - * OPENGL parameter in combination with size. - * - * @param {int|float} x1 x-coordinate of the first point - * @param {int|float} y1 y-coordinate of the first point - * @param {int|float} z1 z-coordinate of the first point - * @param {int|float} x2 x-coordinate of the second point - * @param {int|float} y2 y-coordinate of the second point - * @param {int|float} z2 z-coordinate of the second point - * - * @see strokeWeight - * @see strokeJoin - * @see strokeCap - * @see beginShape - */ - Drawing2D.prototype.line = function(x1, y1, x2, y2) { - if (!doStroke) { - return; - } - x1 = Math.round(x1); - x2 = Math.round(x2); - y1 = Math.round(y1); - y2 = Math.round(y2); - // A line is only defined if it has different start and end coordinates. - // If they are the same, we call point instead. - if (x1 === x2 && y1 === y2) { - p.point(x1, y1); - return; - } - - var swap = undef, - lineCap = undef, - drawCrisp = true, - currentModelView = modelView.array(), - identityMatrix = [1, 0, 0, 0, 1, 0]; - // Test if any transformations have been applied to the sketch - for (var i = 0; i < 6 && drawCrisp; i++) { - drawCrisp = currentModelView[i] === identityMatrix[i]; - } - /* Draw crisp lines if the line is vertical or horizontal with the following method - * If any transformations have been applied to the sketch, don't make the line crisp - * If the line is directed up or to the left, reverse it by swapping x1/x2 or y1/y2 - * Make the line 1 pixel longer to work around cross-platform canvas implementations - * If the lineWidth is odd, translate the line by 0.5 in the perpendicular direction - * Even lineWidths do not need to be translated because the canvas will draw them on pixel boundaries - * Change the cap to butt-end to work around cross-platform canvas implementations - * Reverse the translate and lineCap canvas state changes after drawing the line - */ - if (drawCrisp) { - if (x1 === x2) { - if (y1 > y2) { - swap = y1; - y1 = y2; - y2 = swap; - } - y2++; - if (lineWidth % 2 === 1) { - curContext.translate(0.5, 0.0); - } - } else if (y1 === y2) { - if (x1 > x2) { - swap = x1; - x1 = x2; - x2 = swap; - } - x2++; - if (lineWidth % 2 === 1) { - curContext.translate(0.0, 0.5); - } - } - if (lineWidth === 1) { - lineCap = curContext.lineCap; - curContext.lineCap = 'butt'; - } - } - curContext.beginPath(); - curContext.moveTo(x1 || 0, y1 || 0); - curContext.lineTo(x2 || 0, y2 || 0); - executeContextStroke(); - if (drawCrisp) { - if (x1 === x2 && lineWidth % 2 === 1) { - curContext.translate(-0.5, 0.0); - } else if (y1 === y2 && lineWidth % 2 === 1) { - curContext.translate(0.0, -0.5); - } - if (lineWidth === 1) { - curContext.lineCap = lineCap; - } - } - }; - - Drawing3D.prototype.line = function(x1, y1, z1, x2, y2, z2) { - if (y2 === undef || z2 === undef) { // 2D line called in 3D context - z2 = 0; - y2 = x2; - x2 = z1; - z1 = 0; - } - - // a line is only defined if it has different start and end coordinates. - // If they are the same, we call point instead. - if (x1===x2 && y1===y2 && z1===z2) { - p.point(x1,y1,z1); - return; - } - - var lineVerts = [x1, y1, z1, x2, y2, z2]; - - var view = new PMatrix3D(); - view.scale(1, -1, 1); - view.apply(modelView.array()); - view.transpose(); - - if (lineWidth > 0 && doStroke) { - curContext.useProgram(programObject2D); - - uniformMatrix("model2d", programObject2D, "model", false, [1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1]); - uniformMatrix("view2d", programObject2D, "view", false, view.array()); - - uniformf("color2d", programObject2D, "color", strokeStyle); - uniformi("picktype2d", programObject2D, "picktype", 0); - - vertexAttribPointer("vertex2d", programObject2D, "Vertex", 3, lineBuffer); - disableVertexAttribPointer("aTextureCoord2d", programObject2D, "aTextureCoord"); - - curContext.bufferData(curContext.ARRAY_BUFFER, new Float32Array(lineVerts), curContext.STREAM_DRAW); - curContext.drawArrays(curContext.LINES, 0, 2); - } - }; - - /** - * Draws a Bezier curve on the screen. These curves are defined by a series of anchor and control points. The first - * two parameters specify the first anchor point and the last two parameters specify the other anchor point. The - * middle parameters specify the control points which define the shape of the curve. Bezier curves were developed - * by French engineer Pierre Bezier. Using the 3D version of requires rendering with P3D or OPENGL (see the - * Environment reference for more information). - * - * @param {int | float} x1,y1,z1 coordinates for the first anchor point - * @param {int | float} cx1,cy1,cz1 coordinates for the first control point - * @param {int | float} cx2,cy2,cz2 coordinates for the second control point - * @param {int | float} x2,y2,z2 coordinates for the second anchor point - * - * @see bezierVertex - * @see curve - */ - Drawing2D.prototype.bezier = function() { - if (arguments.length !== 8) { - throw("You must use 8 parameters for bezier() in 2D mode"); - } - - p.beginShape(); - p.vertex( arguments[0], arguments[1] ); - p.bezierVertex( arguments[2], arguments[3], - arguments[4], arguments[5], - arguments[6], arguments[7] ); - p.endShape(); - }; - - Drawing3D.prototype.bezier = function() { - if (arguments.length !== 12) { - throw("You must use 12 parameters for bezier() in 3D mode"); - } - - p.beginShape(); - p.vertex( arguments[0], arguments[1], arguments[2] ); - p.bezierVertex( arguments[3], arguments[4], arguments[5], - arguments[6], arguments[7], arguments[8], - arguments[9], arguments[10], arguments[11] ); - p.endShape(); - }; - - /** - * Sets the resolution at which Beziers display. The default value is 20. This function is only useful when using the P3D - * or OPENGL renderer as the default (JAVA2D) renderer does not use this information. - * - * @param {int} detail resolution of the curves - * - * @see curve - * @see curveVertex - * @see curveTightness - */ - p.bezierDetail = function( detail ){ - bezDetail = detail; - }; - - /** - * The bezierPoint() function evalutes quadratic bezier at point t for points a, b, c, d. - * The parameter t varies between 0 and 1. The a and d parameters are the - * on-curve points, b and c are the control points. To make a two-dimensional - * curve, call this function once with the x coordinates and a second time - * with the y coordinates to get the location of a bezier curve at t. - * - * @param {float} a coordinate of first point on the curve - * @param {float} b coordinate of first control point - * @param {float} c coordinate of second control point - * @param {float} d coordinate of second point on the curve - * @param {float} t value between 0 and 1 - * - * @see #bezier() - * @see #bezierVertex() - * @see #curvePoint() - */ - p.bezierPoint = function(a, b, c, d, t) { - return (1 - t) * (1 - t) * (1 - t) * a + 3 * (1 - t) * (1 - t) * t * b + 3 * (1 - t) * t * t * c + t * t * t * d; - }; - - /** - * The bezierTangent() function calculates the tangent of a point on a Bezier curve. There is a good - * definition of "tangent" at Wikipedia: http://en.wikipedia.org/wiki/Tangent - * - * @param {float} a coordinate of first point on the curve - * @param {float} b coordinate of first control point - * @param {float} c coordinate of second control point - * @param {float} d coordinate of second point on the curve - * @param {float} t value between 0 and 1 - * - * @see #bezier() - * @see #bezierVertex() - * @see #curvePoint() - */ - p.bezierTangent = function(a, b, c, d, t) { - return (3 * t * t * (-a + 3 * b - 3 * c + d) + 6 * t * (a - 2 * b + c) + 3 * (-a + b)); - }; - - /** - * The curvePoint() function evalutes the Catmull-Rom curve at point t for points a, b, c, d. The - * parameter t varies between 0 and 1, a and d are points on the curve, - * and b and c are the control points. This can be done once with the x - * coordinates and a second time with the y coordinates to get the - * location of a curve at t. - * - * @param {int|float} a coordinate of first point on the curve - * @param {int|float} b coordinate of second point on the curve - * @param {int|float} c coordinate of third point on the curve - * @param {int|float} d coordinate of fourth point on the curve - * @param {float} t value between 0 and 1 - * - * @see #curve() - * @see #curveVertex() - * @see #bezierPoint() - */ - p.curvePoint = function(a, b, c, d, t) { - return 0.5 * ((2 * b) + (-a + c) * t + (2 * a - 5 * b + 4 * c - d) * t * t + (-a + 3 * b - 3 * c + d) * t * t * t); - }; - - /** - * The curveTangent() function calculates the tangent of a point on a Catmull-Rom curve. - * There is a good definition of "tangent" at Wikipedia: http://en.wikipedia.org/wiki/Tangent. - * - * @param {int|float} a coordinate of first point on the curve - * @param {int|float} b coordinate of first control point - * @param {int|float} c coordinate of second control point - * @param {int|float} d coordinate of second point on the curve - * @param {float} t value between 0 and 1 - * - * @see #curve() - * @see #curveVertex() - * @see #curvePoint() - * @see #bezierTangent() - */ - p.curveTangent = function(a, b, c, d, t) { - return 0.5 * ((-a + c) + 2 * (2 * a - 5 * b + 4 * c - d) * t + 3 * (-a + 3 * b - 3 * c + d) * t * t); - }; - - /** - * A triangle is a plane created by connecting three points. The first two arguments specify the first point, - * the middle two arguments specify the second point, and the last two arguments specify the third point. - * - * @param {int | float} x1 x-coordinate of the first point - * @param {int | float} y1 y-coordinate of the first point - * @param {int | float} x2 x-coordinate of the second point - * @param {int | float} y2 y-coordinate of the second point - * @param {int | float} x3 x-coordinate of the third point - * @param {int | float} y3 y-coordinate of the third point - */ - p.triangle = function(x1, y1, x2, y2, x3, y3) { - p.beginShape(PConstants.TRIANGLES); - p.vertex(x1, y1, 0); - p.vertex(x2, y2, 0); - p.vertex(x3, y3, 0); - p.endShape(); - }; - - /** - * A quad is a quadrilateral, a four sided polygon. It is similar to a rectangle, but the angles between its - * edges are not constrained to ninety degrees. The first pair of parameters (x1,y1) sets the first vertex - * and the subsequent pairs should proceed clockwise or counter-clockwise around the defined shape. - * - * @param {float | int} x1 x-coordinate of the first corner - * @param {float | int} y1 y-coordinate of the first corner - * @param {float | int} x2 x-coordinate of the second corner - * @param {float | int} y2 y-coordinate of the second corner - * @param {float | int} x3 x-coordinate of the third corner - * @param {float | int} y3 y-coordinate of the third corner - * @param {float | int} x4 x-coordinate of the fourth corner - * @param {float | int} y4 y-coordinate of the fourth corner - */ - p.quad = function(x1, y1, x2, y2, x3, y3, x4, y4) { - p.beginShape(PConstants.QUADS); - p.vertex(x1, y1, 0); - p.vertex(x2, y2, 0); - p.vertex(x3, y3, 0); - p.vertex(x4, y4, 0); - p.endShape(); - }; - - var roundedRect$2d = function(x, y, width, height, tl, tr, br, bl) { - if (bl === undef) { - tr = tl; - br = tl; - bl = tl; - } - var halfWidth = width / 2, - halfHeight = height / 2; - if (tl > halfWidth || tl > halfHeight) { - tl = Math.min(halfWidth, halfHeight); - } - if (tr > halfWidth || tr > halfHeight) { - tr = Math.min(halfWidth, halfHeight); - } - if (br > halfWidth || br > halfHeight) { - br = Math.min(halfWidth, halfHeight); - } - if (bl > halfWidth || bl > halfHeight) { - bl = Math.min(halfWidth, halfHeight); - } - // Translate the stroke by (0.5, 0.5) to draw a crisp border - if (!doFill || doStroke) { - curContext.translate(0.5, 0.5); - } - curContext.beginPath(); - curContext.moveTo(x + tl, y); - curContext.lineTo(x + width - tr, y); - curContext.quadraticCurveTo(x + width, y, x + width, y + tr); - curContext.lineTo(x + width, y + height - br); - curContext.quadraticCurveTo(x + width, y + height, x + width - br, y + height); - curContext.lineTo(x + bl, y + height); - curContext.quadraticCurveTo(x, y + height, x, y + height - bl); - curContext.lineTo(x, y + tl); - curContext.quadraticCurveTo(x, y, x + tl, y); - if (!doFill || doStroke) { - curContext.translate(-0.5, -0.5); - } - executeContextFill(); - executeContextStroke(); - }; - - /** - * Draws a rectangle to the screen. A rectangle is a four-sided shape with every angle at ninety - * degrees. The first two parameters set the location, the third sets the width, and the fourth - * sets the height. The origin is changed with the rectMode() function. - * - * @param {int|float} x x-coordinate of the rectangle - * @param {int|float} y y-coordinate of the rectangle - * @param {int|float} width width of the rectangle - * @param {int|float} height height of the rectangle - * - * @see rectMode - * @see quad - */ - Drawing2D.prototype.rect = function(x, y, width, height, tl, tr, br, bl) { - if (!width && !height) { - return; - } - - if (curRectMode === PConstants.CORNERS) { - width -= x; - height -= y; - } else if (curRectMode === PConstants.RADIUS) { - width *= 2; - height *= 2; - x -= width / 2; - y -= height / 2; - } else if (curRectMode === PConstants.CENTER) { - x -= width / 2; - y -= height / 2; - } - - x = Math.round(x); - y = Math.round(y); - width = Math.round(width); - height = Math.round(height); - if (tl !== undef) { - roundedRect$2d(x, y, width, height, tl, tr, br, bl); - return; - } - - // Translate the line by (0.5, 0.5) to draw a crisp rectangle border - if (doStroke && lineWidth % 2 === 1) { - curContext.translate(0.5, 0.5); - } - curContext.beginPath(); - curContext.rect(x, y, width, height); - executeContextFill(); - executeContextStroke(); - if (doStroke && lineWidth % 2 === 1) { - curContext.translate(-0.5, -0.5); - } - }; - - Drawing3D.prototype.rect = function(x, y, width, height, tl, tr, br, bl) { - if (tl !== undef) { - throw "rect() with rounded corners is not supported in 3D mode"; - } - - if (curRectMode === PConstants.CORNERS) { - width -= x; - height -= y; - } else if (curRectMode === PConstants.RADIUS) { - width *= 2; - height *= 2; - x -= width / 2; - y -= height / 2; - } else if (curRectMode === PConstants.CENTER) { - x -= width / 2; - y -= height / 2; - } - - // Modeling transformation - var model = new PMatrix3D(); - model.translate(x, y, 0); - model.scale(width, height, 1); - model.transpose(); - - // viewing transformation needs to have Y flipped - // becuase that's what Processing does. - var view = new PMatrix3D(); - view.scale(1, -1, 1); - view.apply(modelView.array()); - view.transpose(); - - if (lineWidth > 0 && doStroke) { - curContext.useProgram(programObject2D); - uniformMatrix("model2d", programObject2D, "model", false, model.array()); - uniformMatrix("view2d", programObject2D, "view", false, view.array()); - uniformf("color2d", programObject2D, "color", strokeStyle); - uniformi("picktype2d", programObject2D, "picktype", 0); - vertexAttribPointer("vertex2d", programObject2D, "Vertex", 3, rectBuffer); - disableVertexAttribPointer("aTextureCoord2d", programObject2D, "aTextureCoord"); - curContext.drawArrays(curContext.LINE_LOOP, 0, rectVerts.length / 3); - } - - if (doFill) { - curContext.useProgram(programObject3D); - uniformMatrix("model3d", programObject3D, "model", false, model.array()); - uniformMatrix("view3d", programObject3D, "view", false, view.array()); - - // fix stitching problems. (lines get occluded by triangles - // since they share the same depth values). This is not entirely - // working, but it's a start for drawing the outline. So - // developers can start playing around with styles. - curContext.enable(curContext.POLYGON_OFFSET_FILL); - curContext.polygonOffset(1, 1); - - uniformf("color3d", programObject3D, "color", fillStyle); - - if(lightCount > 0){ - var v = new PMatrix3D(); - v.set(view); - - var m = new PMatrix3D(); - m.set(model); - - v.mult(m); - - var normalMatrix = new PMatrix3D(); - normalMatrix.set(v); - normalMatrix.invert(); - normalMatrix.transpose(); - - uniformMatrix("normalTransform3d", programObject3D, "normalTransform", false, normalMatrix.array()); - vertexAttribPointer("normal3d", programObject3D, "Normal", 3, rectNormBuffer); - } - else{ - disableVertexAttribPointer("normal3d", programObject3D, "Normal"); - } - - vertexAttribPointer("vertex3d", programObject3D, "Vertex", 3, rectBuffer); - - curContext.drawArrays(curContext.TRIANGLE_FAN, 0, rectVerts.length / 3); - curContext.disable(curContext.POLYGON_OFFSET_FILL); - } - }; - - /** - * Draws an ellipse (oval) in the display window. An ellipse with an equal width and height is a circle. - * The first two parameters set the location, the third sets the width, and the fourth sets the height. The origin may be - * changed with the ellipseMode() function. - * - * @param {float|int} x x-coordinate of the ellipse - * @param {float|int} y y-coordinate of the ellipse - * @param {float|int} width width of the ellipse - * @param {float|int} height height of the ellipse - * - * @see ellipseMode - */ - Drawing2D.prototype.ellipse = function(x, y, width, height) { - x = x || 0; - y = y || 0; - - if (width <= 0 && height <= 0) { - return; - } - - if (curEllipseMode === PConstants.RADIUS) { - width *= 2; - height *= 2; - } else if (curEllipseMode === PConstants.CORNERS) { - width = width - x; - height = height - y; - x += width / 2; - y += height / 2; - } else if (curEllipseMode === PConstants.CORNER) { - x += width / 2; - y += height / 2; - } - - // Shortcut for drawing a 2D circle - if (width === height) { - curContext.beginPath(); - curContext.arc(x, y, width / 2, 0, PConstants.TWO_PI, false); - executeContextFill(); - executeContextStroke(); - } else { - var w = width / 2, - h = height / 2, - C = 0.5522847498307933, - c_x = C * w, - c_y = C * h; - - p.beginShape(); - p.vertex(x + w, y); - p.bezierVertex(x + w, y - c_y, x + c_x, y - h, x, y - h); - p.bezierVertex(x - c_x, y - h, x - w, y - c_y, x - w, y); - p.bezierVertex(x - w, y + c_y, x - c_x, y + h, x, y + h); - p.bezierVertex(x + c_x, y + h, x + w, y + c_y, x + w, y); - p.endShape(); - } - }; - - Drawing3D.prototype.ellipse = function(x, y, width, height) { - x = x || 0; - y = y || 0; - - if (width <= 0 && height <= 0) { - return; - } - - if (curEllipseMode === PConstants.RADIUS) { - width *= 2; - height *= 2; - } else if (curEllipseMode === PConstants.CORNERS) { - width = width - x; - height = height - y; - x += width / 2; - y += height / 2; - } else if (curEllipseMode === PConstants.CORNER) { - x += width / 2; - y += height / 2; - } - - var w = width / 2, - h = height / 2, - C = 0.5522847498307933, - c_x = C * w, - c_y = C * h; - - p.beginShape(); - p.vertex(x + w, y); - p.bezierVertex(x + w, y - c_y, 0, x + c_x, y - h, 0, x, y - h, 0); - p.bezierVertex(x - c_x, y - h, 0, x - w, y - c_y, 0, x - w, y, 0); - p.bezierVertex(x - w, y + c_y, 0, x - c_x, y + h, 0, x, y + h, 0); - p.bezierVertex(x + c_x, y + h, 0, x + w, y + c_y, 0, x + w, y, 0); - p.endShape(); - - if (doFill) { - //temporary workaround to not working fills for bezier -- will fix later - var xAv = 0, yAv = 0, i, j; - for (i = 0; i < vertArray.length; i++) { - xAv += vertArray[i][0]; - yAv += vertArray[i][1]; - } - xAv /= vertArray.length; - yAv /= vertArray.length; - var vert = [], - fillVertArray = [], - colorVertArray = []; - vert[0] = xAv; - vert[1] = yAv; - vert[2] = 0; - vert[3] = 0; - vert[4] = 0; - vert[5] = fillStyle[0]; - vert[6] = fillStyle[1]; - vert[7] = fillStyle[2]; - vert[8] = fillStyle[3]; - vert[9] = strokeStyle[0]; - vert[10] = strokeStyle[1]; - vert[11] = strokeStyle[2]; - vert[12] = strokeStyle[3]; - vert[13] = normalX; - vert[14] = normalY; - vert[15] = normalZ; - vertArray.unshift(vert); - for (i = 0; i < vertArray.length; i++) { - for (j = 0; j < 3; j++) { - fillVertArray.push(vertArray[i][j]); - } - for (j = 5; j < 9; j++) { - colorVertArray.push(vertArray[i][j]); - } - } - fill3D(fillVertArray, "TRIANGLE_FAN", colorVertArray); - } - }; - - /** - * Sets the current normal vector. This is for drawing three dimensional shapes and surfaces and - * specifies a vector perpendicular to the surface of the shape which determines how lighting affects - * it. Processing attempts to automatically assign normals to shapes, but since that's imperfect, - * this is a better option when you want more control. This function is identical to glNormal3f() in OpenGL. - * - * @param {float} nx x direction - * @param {float} ny y direction - * @param {float} nz z direction - * - * @see beginShape - * @see endShape - * @see lights - */ - p.normal = function(nx, ny, nz) { - if (arguments.length !== 3 || !(typeof nx === "number" && typeof ny === "number" && typeof nz === "number")) { - throw "normal() requires three numeric arguments."; - } - - normalX = nx; - normalY = ny; - normalZ = nz; - - if (curShape !== 0) { - if (normalMode === PConstants.NORMAL_MODE_AUTO) { - normalMode = PConstants.NORMAL_MODE_SHAPE; - } else if (normalMode === PConstants.NORMAL_MODE_SHAPE) { - normalMode = PConstants.NORMAL_MODE_VERTEX; - } - } - }; - - //////////////////////////////////////////////////////////////////////////// - // Raster drawing functions - //////////////////////////////////////////////////////////////////////////// - - /** - * Saves an image from the display window. Images are saved in TIFF, TARGA, JPEG, and PNG format - * depending on the extension within the filename parameter. For example, "image.tif" will have - * a TIFF image and "image.png" will save a PNG image. If no extension is included in the filename, - * the image will save in TIFF format and .tif will be added to the name. These files are saved to - * the sketch's folder, which may be opened by selecting "Show sketch folder" from the "Sketch" menu. - * It is not possible to use save() while running the program in a web browser. All images saved - * from the main drawing window will be opaque. To save images without a background, use createGraphics(). - * - * @param {String} filename any sequence of letters and numbers - * - * @see saveFrame - * @see createGraphics - */ - p.save = function(file, img) { - // file is unused at the moment - // may implement this differently in later release - if (img !== undef) { - return window.open(img.toDataURL(),"_blank"); - } - return window.open(p.externals.canvas.toDataURL(),"_blank"); - }; - - var saveNumber = 0; - - p.saveFrame = function(file) { - if(file === undef) { - // use default name template if parameter is not specified - file = "screen-####.png"; - } - // Increment changeable part: screen-0000.png, screen-0001.png, ... - var frameFilename = file.replace(/#+/, function(all) { - var s = "" + (saveNumber++); - while(s.length < all.length) { - s = "0" + s; - } - return s; - }); - p.save(frameFilename); - }; - - var utilityContext2d = document.createElement("canvas").getContext("2d"); - - var canvasDataCache = [undef, undef, undef]; // we need three for now - - function getCanvasData(obj, w, h) { - var canvasData = canvasDataCache.shift(); - - if (canvasData === undef) { - canvasData = {}; - canvasData.canvas = document.createElement("canvas"); - canvasData.context = canvasData.canvas.getContext('2d'); - } - - canvasDataCache.push(canvasData); - - var canvas = canvasData.canvas, context = canvasData.context, - width = w || obj.width, height = h || obj.height; - - canvas.width = width; - canvas.height = height; - - if (!obj) { - context.clearRect(0, 0, width, height); - } else if ("data" in obj) { // ImageData - context.putImageData(obj, 0, 0); - } else { - context.clearRect(0, 0, width, height); - context.drawImage(obj, 0, 0, width, height); - } - return canvasData; - } - - /** - * Handle the sketch code for pixels[] and pixels.length - * parser code converts pixels[] to getPixels() - * or setPixels(), .length becomes getLength() - */ - function buildPixelsObject(pImage) { - return { - - getLength: (function(aImg) { - return function() { - if (aImg.isRemote) { - throw "Image is loaded remotely. Cannot get length."; - } else { - return aImg.imageData.data.length ? aImg.imageData.data.length/4 : 0; - } - }; - }(pImage)), - - getPixel: (function(aImg) { - return function(i) { - var offset = i*4, - data = aImg.imageData.data; - - if (aImg.isRemote) { - throw "Image is loaded remotely. Cannot get pixels."; - } - - return (data[offset+3] << 24) & PConstants.ALPHA_MASK | - (data[offset] << 16) & PConstants.RED_MASK | - (data[offset+1] << 8) & PConstants.GREEN_MASK | - data[offset+2] & PConstants.BLUE_MASK; - }; - }(pImage)), - - setPixel: (function(aImg) { - return function(i, c) { - var offset = i*4, - data = aImg.imageData.data; - - if (aImg.isRemote) { - throw "Image is loaded remotely. Cannot set pixel."; - } - - data[offset+0] = (c & PConstants.RED_MASK) >>> 16; - data[offset+1] = (c & PConstants.GREEN_MASK) >>> 8; - data[offset+2] = (c & PConstants.BLUE_MASK); - data[offset+3] = (c & PConstants.ALPHA_MASK) >>> 24; - aImg.__isDirty = true; - }; - }(pImage)), - - toArray: (function(aImg) { - return function() { - var arr = [], - data = aImg.imageData.data, - length = aImg.width * aImg.height; - - if (aImg.isRemote) { - throw "Image is loaded remotely. Cannot get pixels."; - } - - for (var i = 0, offset = 0; i < length; i++, offset += 4) { - arr.push( (data[offset+3] << 24) & PConstants.ALPHA_MASK | - (data[offset] << 16) & PConstants.RED_MASK | - (data[offset+1] << 8) & PConstants.GREEN_MASK | - data[offset+2] & PConstants.BLUE_MASK ); - } - return arr; - }; - }(pImage)), - - set: (function(aImg) { - return function(arr) { - var offset, - data, - c; - if (this.isRemote) { - throw "Image is loaded remotely. Cannot set pixels."; - } - - data = aImg.imageData.data; - for (var i = 0, aL = arr.length; i < aL; i++) { - c = arr[i]; - offset = i*4; - - data[offset+0] = (c & PConstants.RED_MASK) >>> 16; - data[offset+1] = (c & PConstants.GREEN_MASK) >>> 8; - data[offset+2] = (c & PConstants.BLUE_MASK); - data[offset+3] = (c & PConstants.ALPHA_MASK) >>> 24; - } - aImg.__isDirty = true; - }; - }(pImage)) - - }; - } - - /** - * Datatype for storing images. Processing can display .gif, .jpg, .tga, and .png images. Images may be - * displayed in 2D and 3D space. Before an image is used, it must be loaded with the loadImage() function. - * The PImage object contains fields for the width and height of the image, as well as an array called - * pixels[] which contains the values for every pixel in the image. A group of methods, described below, - * allow easy access to the image's pixels and alpha channel and simplify the process of compositing. - * Before using the pixels[] array, be sure to use the loadPixels() method on the image to make sure that the - * pixel data is properly loaded. To create a new image, use the createImage() function (do not use new PImage()). - * - * @param {int} width image width - * @param {int} height image height - * @param {MODE} format Either RGB, ARGB, ALPHA (grayscale alpha channel) - * - * @returns {PImage} - * - * @see loadImage - * @see imageMode - * @see createImage - */ - var PImage = function(aWidth, aHeight, aFormat) { - - // Keep track of whether or not the cached imageData has been touched. - this.__isDirty = false; - - if (aWidth instanceof HTMLImageElement) { - // convert an to a PImage - this.fromHTMLImageData(aWidth); - } else if (aHeight || aFormat) { - this.width = aWidth || 1; - this.height = aHeight || 1; - - // Stuff a canvas into sourceImg so image() calls can use drawImage like an - var canvas = this.sourceImg = document.createElement("canvas"); - canvas.width = this.width; - canvas.height = this.height; - - var imageData = this.imageData = canvas.getContext('2d').createImageData(this.width, this.height); - this.format = (aFormat === PConstants.ARGB || aFormat === PConstants.ALPHA) ? aFormat : PConstants.RGB; - if (this.format === PConstants.RGB) { - // Set the alpha channel of an RGB image to opaque. - for (var i = 3, data = this.imageData.data, len = data.length; i < len; i += 4) { - data[i] = 255; - } - } - - this.__isDirty = true; - this.updatePixels(); - } else { - this.width = 0; - this.height = 0; - this.imageData = utilityContext2d.createImageData(1, 1); - this.format = PConstants.ARGB; - } - - this.pixels = buildPixelsObject(this); - }; - PImage.prototype = { - - /** - * Temporary hack to deal with cross-Processing-instance created PImage. See - * tickets #1623 and #1644. - */ - __isPImage: true, - - /** - * @member PImage - * Updates the image with the data in its pixels[] array. Use in conjunction with loadPixels(). If - * you're only reading pixels from the array, there's no need to call updatePixels(). - * Certain renderers may or may not seem to require loadPixels() or updatePixels(). However, the rule - * is that any time you want to manipulate the pixels[] array, you must first call loadPixels(), and - * after changes have been made, call updatePixels(). Even if the renderer may not seem to use this - * function in the current Processing release, this will always be subject to change. - * Currently, none of the renderers use the additional parameters to updatePixels(). - */ - updatePixels: function() { - var canvas = this.sourceImg; - if (canvas && canvas instanceof HTMLCanvasElement && this.__isDirty) { - canvas.getContext('2d').putImageData(this.imageData, 0, 0); - } - this.__isDirty = false; - }, - - fromHTMLImageData: function(htmlImg) { - // convert an to a PImage - var canvasData = getCanvasData(htmlImg); - try { - var imageData = canvasData.context.getImageData(0, 0, htmlImg.width, htmlImg.height); - this.fromImageData(imageData); - } catch(e) { - if (htmlImg.width && htmlImg.height) { - this.isRemote = true; - this.width = htmlImg.width; - this.height = htmlImg.height; - } - } - this.sourceImg = htmlImg; - }, - - 'get': function(x, y, w, h) { - if (!arguments.length) { - return p.get(this); - } - if (arguments.length === 2) { - return p.get(x, y, this); - } - if (arguments.length === 4) { - return p.get(x, y, w, h, this); - } - }, - - /** - * @member PImage - * Changes the color of any pixel or writes an image directly into the image. The x and y parameter - * specify the pixel or the upper-left corner of the image. The color parameter specifies the color value. - * Setting the color of a single pixel with set(x, y) is easy, but not as fast as putting the data - * directly into pixels[]. The equivalent statement to "set(x, y, #000000)" using pixels[] is - * "pixels[y*width+x] = #000000". Processing requires calling loadPixels() to load the display window - * data into the pixels[] array before getting the values and calling updatePixels() to update the window. - * - * @param {int} x x-coordinate of the pixel or upper-left corner of the image - * @param {int} y y-coordinate of the pixel or upper-left corner of the image - * @param {color} color any value of the color datatype - * - * @see get - * @see pixels[] - * @see copy - */ - 'set': function(x, y, c) { - p.set(x, y, c, this); - this.__isDirty = true; - }, - - /** - * @member PImage - * Blends a region of pixels into the image specified by the img parameter. These copies utilize full - * alpha channel support and a choice of the following modes to blend the colors of source pixels (A) - * with the ones of pixels in the destination image (B): - * BLEND - linear interpolation of colours: C = A*factor + B - * ADD - additive blending with white clip: C = min(A*factor + B, 255) - * SUBTRACT - subtractive blending with black clip: C = max(B - A*factor, 0) - * DARKEST - only the darkest colour succeeds: C = min(A*factor, B) - * LIGHTEST - only the lightest colour succeeds: C = max(A*factor, B) - * DIFFERENCE - subtract colors from underlying image. - * EXCLUSION - similar to DIFFERENCE, but less extreme. - * MULTIPLY - Multiply the colors, result will always be darker. - * SCREEN - Opposite multiply, uses inverse values of the colors. - * OVERLAY - A mix of MULTIPLY and SCREEN. Multiplies dark values, and screens light values. - * HARD_LIGHT - SCREEN when greater than 50% gray, MULTIPLY when lower. - * SOFT_LIGHT - Mix of DARKEST and LIGHTEST. Works like OVERLAY, but not as harsh. - * DODGE - Lightens light tones and increases contrast, ignores darks. Called "Color Dodge" in Illustrator and Photoshop. - * BURN - Darker areas are applied, increasing contrast, ignores lights. Called "Color Burn" in Illustrator and Photoshop. - * All modes use the alpha information (highest byte) of source image pixels as the blending factor. - * If the source and destination regions are different sizes, the image will be automatically resized to - * match the destination size. If the srcImg parameter is not used, the display window is used as the source image. - * This function ignores imageMode(). - * - * @param {int} x X coordinate of the source's upper left corner - * @param {int} y Y coordinate of the source's upper left corner - * @param {int} width source image width - * @param {int} height source image height - * @param {int} dx X coordinate of the destinations's upper left corner - * @param {int} dy Y coordinate of the destinations's upper left corner - * @param {int} dwidth destination image width - * @param {int} dheight destination image height - * @param {PImage} srcImg an image variable referring to the source image - * @param {MODE} MODE Either BLEND, ADD, SUBTRACT, LIGHTEST, DARKEST, DIFFERENCE, EXCLUSION, - * MULTIPLY, SCREEN, OVERLAY, HARD_LIGHT, SOFT_LIGHT, DODGE, BURN - * - * @see alpha - * @see copy - */ - blend: function(srcImg, x, y, width, height, dx, dy, dwidth, dheight, MODE) { - if (arguments.length === 9) { - p.blend(this, srcImg, x, y, width, height, dx, dy, dwidth, dheight, this); - } else if (arguments.length === 10) { - p.blend(srcImg, x, y, width, height, dx, dy, dwidth, dheight, MODE, this); - } - delete this.sourceImg; - }, - - /** - * @member PImage - * Copies a region of pixels from one image into another. If the source and destination regions - * aren't the same size, it will automatically resize source pixels to fit the specified target region. - * No alpha information is used in the process, however if the source image has an alpha channel set, - * it will be copied as well. This function ignores imageMode(). - * - * @param {int} sx X coordinate of the source's upper left corner - * @param {int} sy Y coordinate of the source's upper left corner - * @param {int} swidth source image width - * @param {int} sheight source image height - * @param {int} dx X coordinate of the destinations's upper left corner - * @param {int} dy Y coordinate of the destinations's upper left corner - * @param {int} dwidth destination image width - * @param {int} dheight destination image height - * @param {PImage} srcImg an image variable referring to the source image - * - * @see alpha - * @see blend - */ - copy: function(srcImg, sx, sy, swidth, sheight, dx, dy, dwidth, dheight) { - if (arguments.length === 8) { - p.blend(this, srcImg, sx, sy, swidth, sheight, dx, dy, dwidth, PConstants.REPLACE, this); - } else if (arguments.length === 9) { - p.blend(srcImg, sx, sy, swidth, sheight, dx, dy, dwidth, dheight, PConstants.REPLACE, this); - } - delete this.sourceImg; - }, - - /** - * @member PImage - * Filters an image as defined by one of the following modes: - * THRESHOLD - converts the image to black and white pixels depending if they are above or below - * the threshold defined by the level parameter. The level must be between 0.0 (black) and 1.0(white). - * If no level is specified, 0.5 is used. - * GRAY - converts any colors in the image to grayscale equivalents - * INVERT - sets each pixel to its inverse value - * POSTERIZE - limits each channel of the image to the number of colors specified as the level parameter - * BLUR - executes a Guassian blur with the level parameter specifying the extent of the blurring. - * If no level parameter is used, the blur is equivalent to Guassian blur of radius 1. - * OPAQUE - sets the alpha channel to entirely opaque. - * ERODE - reduces the light areas with the amount defined by the level parameter. - * DILATE - increases the light areas with the amount defined by the level parameter - * - * @param {MODE} MODE Either THRESHOLD, GRAY, INVERT, POSTERIZE, BLUR, OPAQUE, ERODE, or DILATE - * @param {int|float} param in the range from 0 to 1 - */ - filter: function(mode, param) { - if (arguments.length === 2) { - p.filter(mode, param, this); - } else if (arguments.length === 1) { - // no param specified, send null to show its invalid - p.filter(mode, null, this); - } - delete this.sourceImg; - }, - - /** - * @member PImage - * Saves the image into a file. Images are saved in TIFF, TARGA, JPEG, and PNG format depending on - * the extension within the filename parameter. For example, "image.tif" will have a TIFF image and - * "image.png" will save a PNG image. If no extension is included in the filename, the image will save - * in TIFF format and .tif will be added to the name. These files are saved to the sketch's folder, - * which may be opened by selecting "Show sketch folder" from the "Sketch" menu. It is not possible to - * use save() while running the program in a web browser. - * To save an image created within the code, rather than through loading, it's necessary to make the - * image with the createImage() function so it is aware of the location of the program and can therefore - * save the file to the right place. See the createImage() reference for more information. - * - * @param {String} filename a sequence of letters and numbers - */ - save: function(file){ - p.save(file,this); - }, - - /** - * @member PImage - * Resize the image to a new width and height. To make the image scale proportionally, use 0 as the - * value for the wide or high parameter. - * - * @param {int} wide the resized image width - * @param {int} high the resized image height - * - * @see get - */ - resize: function(w, h) { - if (this.isRemote) { // Remote images cannot access imageData - throw "Image is loaded remotely. Cannot resize."; - } - if (this.width !== 0 || this.height !== 0) { - // make aspect ratio if w or h is 0 - if (w === 0 && h !== 0) { - w = Math.floor(this.width / this.height * h); - } else if (h === 0 && w !== 0) { - h = Math.floor(this.height / this.width * w); - } - // put 'this.imageData' into a new canvas - var canvas = getCanvasData(this.imageData).canvas; - // pull imageData object out of canvas into ImageData object - var imageData = getCanvasData(canvas, w, h).context.getImageData(0, 0, w, h); - // set this as new pimage - this.fromImageData(imageData); - } - }, - - /** - * @member PImage - * Masks part of an image from displaying by loading another image and using it as an alpha channel. - * This mask image should only contain grayscale data, but only the blue color channel is used. The - * mask image needs to be the same size as the image to which it is applied. - * In addition to using a mask image, an integer array containing the alpha channel data can be - * specified directly. This method is useful for creating dynamically generated alpha masks. This - * array must be of the same length as the target image's pixels array and should contain only grayscale - * data of values between 0-255. - * - * @param {PImage} maskImg any PImage object used as the alpha channel for "img", needs to be same - * size as "img" - * @param {int[]} maskArray any array of Integer numbers used as the alpha channel, needs to be same - * length as the image's pixel array - */ - mask: function(mask) { - var obj = this.toImageData(), - i, - size; - - if (mask instanceof PImage || mask.__isPImage) { - if (mask.width === this.width && mask.height === this.height) { - mask = mask.toImageData(); - - for (i = 2, size = this.width * this.height * 4; i < size; i += 4) { - // using it as an alpha channel - obj.data[i + 1] = mask.data[i]; - // but only the blue color channel - } - } else { - throw "mask must have the same dimensions as PImage."; - } - } else if (mask instanceof Array) { - if (this.width * this.height === mask.length) { - for (i = 0, size = mask.length; i < size; ++i) { - obj.data[i * 4 + 3] = mask[i]; - } - } else { - throw "mask array must be the same length as PImage pixels array."; - } - } - - this.fromImageData(obj); - }, - - // These are intentionally left blank for PImages, we work live with pixels and draw as necessary - /** - * @member PImage - * Loads the pixel data for the image into its pixels[] array. This function must always be called - * before reading from or writing to pixels[]. - * Certain renderers may or may not seem to require loadPixels() or updatePixels(). However, the - * rule is that any time you want to manipulate the pixels[] array, you must first call loadPixels(), - * and after changes have been made, call updatePixels(). Even if the renderer may not seem to use - * this function in the current Processing release, this will always be subject to change. - */ - loadPixels: nop, - - toImageData: function() { - if (this.isRemote) { - return this.sourceImg; - } - - if (!this.__isDirty) { - return this.imageData; - } - - var canvasData = getCanvasData(this.imageData); - return canvasData.context.getImageData(0, 0, this.width, this.height); - }, - - toDataURL: function() { - if (this.isRemote) { // Remote images cannot access imageData - throw "Image is loaded remotely. Cannot create dataURI."; - } - var canvasData = getCanvasData(this.imageData); - return canvasData.canvas.toDataURL(); - }, - - fromImageData: function(canvasImg) { - var w = canvasImg.width, - h = canvasImg.height, - canvas = document.createElement('canvas'), - ctx = canvas.getContext('2d'); - - this.width = canvas.width = w; - this.height = canvas.height = h; - - ctx.putImageData(canvasImg, 0, 0); - - // changed for 0.9 - this.format = PConstants.ARGB; - - this.imageData = canvasImg; - this.sourceImg = canvas; - } - }; - - p.PImage = PImage; - - /** - * Creates a new PImage (the datatype for storing images). This provides a fresh buffer of pixels to play - * with. Set the size of the buffer with the width and height parameters. The format parameter defines how - * the pixels are stored. See the PImage reference for more information. - * Be sure to include all three parameters, specifying only the width and height (but no format) will - * produce a strange error. - * Advanced users please note that createImage() should be used instead of the syntax new PImage(). - * - * @param {int} width image width - * @param {int} height image height - * @param {MODE} format Either RGB, ARGB, ALPHA (grayscale alpha channel) - * - * @returns {PImage} - * - * @see PImage - * @see PGraphics - */ - p.createImage = function(w, h, mode) { - return new PImage(w,h,mode); - }; - - // Loads an image for display. Type is an extension. Callback is fired on load. - /** - * Loads an image into a variable of type PImage. Four types of images ( .gif, .jpg, .tga, .png) images may - * be loaded. To load correctly, images must be located in the data directory of the current sketch. In most - * cases, load all images in setup() to preload them at the start of the program. Loading images inside draw() - * will reduce the speed of a program. - * The filename parameter can also be a URL to a file found online. For security reasons, a Processing sketch - * found online can only download files from the same server from which it came. Getting around this restriction - * requires a signed applet. - * The extension parameter is used to determine the image type in cases where the image filename does not end - * with a proper extension. Specify the extension as the second parameter to loadImage(), as shown in the - * third example on this page. - * If an image is not loaded successfully, the null value is returned and an error message will be printed to - * the console. The error message does not halt the program, however the null value may cause a NullPointerException - * if your code does not check whether the value returned from loadImage() is null. - * Depending on the type of error, a PImage object may still be returned, but the width and height of the image - * will be set to -1. This happens if bad image data is returned or cannot be decoded properly. Sometimes this happens - * with image URLs that produce a 403 error or that redirect to a password prompt, because loadImage() will attempt - * to interpret the HTML as image data. - * - * @param {String} filename name of file to load, can be .gif, .jpg, .tga, or a handful of other image - * types depending on your platform. - * @param {String} extension the type of image to load, for example "png", "gif", "jpg" - * - * @returns {PImage} - * - * @see PImage - * @see image - * @see imageMode - * @see background - */ - p.loadImage = function(file, type, callback) { - // if type is specified add it with a . to file to make the filename - if (type) { - file = file + "." + type; - } - var pimg; - // if image is in the preloader cache return a new PImage - if (curSketch.imageCache.images[file]) { - pimg = new PImage(curSketch.imageCache.images[file]); - pimg.loaded = true; - return pimg; - } - // else async load it - pimg = new PImage(); - var img = document.createElement('img'); - - pimg.sourceImg = img; - - img.onload = (function(aImage, aPImage, aCallback) { - var image = aImage; - var pimg = aPImage; - var callback = aCallback; - return function() { - // change the object into a PImage now that its loaded - pimg.fromHTMLImageData(image); - pimg.loaded = true; - if (callback) { - callback(); - } - }; - }(img, pimg, callback)); - - img.src = file; // needs to be called after the img.onload function is declared or it wont work in opera - return pimg; - }; - - // async loading of large images, same functionality as loadImage above - /** - * This function load images on a separate thread so that your sketch does not freeze while images load during - * setup(). While the image is loading, its width and height will be 0. If an error occurs while loading the image, - * its width and height will be set to -1. You'll know when the image has loaded properly because its width and - * height will be greater than 0. Asynchronous image loading (particularly when downloading from a server) can - * dramatically improve performance. - * The extension parameter is used to determine the image type in cases where the image filename does not end - * with a proper extension. Specify the extension as the second parameter to requestImage(). - * - * @param {String} filename name of file to load, can be .gif, .jpg, .tga, or a handful of other image - * types depending on your platform. - * @param {String} extension the type of image to load, for example "png", "gif", "jpg" - * - * @returns {PImage} - * - * @see PImage - * @see loadImage - */ - p.requestImage = p.loadImage; - - function get$2(x,y) { - var data; - // return the color at x,y (int) of curContext - if (x >= p.width || x < 0 || y < 0 || y >= p.height) { - // x,y is outside image return transparent black - return 0; - } - - // loadPixels() has been called - if (isContextReplaced) { - var offset = ((0|x) + p.width * (0|y)) * 4; - data = p.imageData.data; - return (data[offset + 3] << 24) & PConstants.ALPHA_MASK | - (data[offset] << 16) & PConstants.RED_MASK | - (data[offset + 1] << 8) & PConstants.GREEN_MASK | - data[offset + 2] & PConstants.BLUE_MASK; - } - - // x,y is inside canvas space - data = p.toImageData(0|x, 0|y, 1, 1).data; - return (data[3] << 24) & PConstants.ALPHA_MASK | - (data[0] << 16) & PConstants.RED_MASK | - (data[1] << 8) & PConstants.GREEN_MASK | - data[2] & PConstants.BLUE_MASK; - } - function get$3(x,y,img) { - if (img.isRemote) { // Remote images cannot access imageData - throw "Image is loaded remotely. Cannot get x,y."; - } - // PImage.get(x,y) was called, return the color (int) at x,y of img - var offset = y * img.width * 4 + (x * 4), - data = img.imageData.data; - return (data[offset + 3] << 24) & PConstants.ALPHA_MASK | - (data[offset] << 16) & PConstants.RED_MASK | - (data[offset + 1] << 8) & PConstants.GREEN_MASK | - data[offset + 2] & PConstants.BLUE_MASK; - } - function get$4(x, y, w, h) { - // return a PImage of w and h from cood x,y of curContext - var c = new PImage(w, h, PConstants.ARGB); - c.fromImageData(p.toImageData(x, y, w, h)); - return c; - } - function get$5(x, y, w, h, img) { - if (img.isRemote) { // Remote images cannot access imageData - throw "Image is loaded remotely. Cannot get x,y,w,h."; - } - // PImage.get(x,y,w,h) was called, return x,y,w,h PImage of img - // offset start point needs to be *4 - var c = new PImage(w, h, PConstants.ARGB), cData = c.imageData.data, - imgWidth = img.width, imgHeight = img.height, imgData = img.imageData.data; - // Don't need to copy pixels from the image outside ranges. - var startRow = Math.max(0, -y), startColumn = Math.max(0, -x), - stopRow = Math.min(h, imgHeight - y), stopColumn = Math.min(w, imgWidth - x); - for (var i = startRow; i < stopRow; ++i) { - var sourceOffset = ((y + i) * imgWidth + (x + startColumn)) * 4; - var targetOffset = (i * w + startColumn) * 4; - for (var j = startColumn; j < stopColumn; ++j) { - cData[targetOffset++] = imgData[sourceOffset++]; - cData[targetOffset++] = imgData[sourceOffset++]; - cData[targetOffset++] = imgData[sourceOffset++]; - cData[targetOffset++] = imgData[sourceOffset++]; - } - } - c.__isDirty = true; - return c; - } - - // Gets a single pixel or block of pixels from the current Canvas Context or a PImage - /** - * Reads the color of any pixel or grabs a section of an image. If no parameters are specified, the entire - * image is returned. Get the value of one pixel by specifying an x,y coordinate. Get a section of the display - * window by specifying an additional width and height parameter. If the pixel requested is outside of the image - * window, black is returned. The numbers returned are scaled according to the current color ranges, but only RGB - * values are returned by this function. For example, even though you may have drawn a shape with colorMode(HSB), - * the numbers returned will be in RGB. - * Getting the color of a single pixel with get(x, y) is easy, but not as fast as grabbing the data directly - * from pixels[]. The equivalent statement to "get(x, y)" using pixels[] is "pixels[y*width+x]". Processing - * requires calling loadPixels() to load the display window data into the pixels[] array before getting the values. - * This function ignores imageMode(). - * - * @param {int} x x-coordinate of the pixel - * @param {int} y y-coordinate of the pixel - * @param {int} width width of pixel rectangle to get - * @param {int} height height of pixel rectangle to get - * - * @returns {Color|PImage} - * - * @see set - * @see pixels[] - * @see imageMode - */ - p.get = function(x, y, w, h, img) { - // for 0 2 and 4 arguments use curContext, otherwise PImage.get was called - if (img !== undefined) { - return get$5(x, y, w, h, img); - } - if (h !== undefined) { - return get$4(x, y, w, h); - } - if (w !== undefined) { - return get$3(x, y, w); - } - if (y !== undefined) { - return get$2(x, y); - } - if (x !== undefined) { - // PImage.get() was called, return a new PImage - return get$5(0, 0, x.width, x.height, x); - } - - return get$4(0, 0, p.width, p.height); - }; - - /** - * Creates and returns a new PGraphics object of the types P2D, P3D, and JAVA2D. Use this class if you need to draw - * into an off-screen graphics buffer. It's not possible to use createGraphics() with OPENGL, because it doesn't - * allow offscreen use. The DXF and PDF renderers require the filename parameter.

It's important to call - * any drawing commands between beginDraw() and endDraw() statements. This is also true for any commands that affect - * drawing, such as smooth() or colorMode().

Unlike the main drawing surface which is completely opaque, - * surfaces created with createGraphics() can have transparency. This makes it possible to draw into a graphics and - * maintain the alpha channel. - * - * @param {int} width width in pixels - * @param {int} height height in pixels - * @param {int} renderer Either P2D, P3D, JAVA2D, PDF, DXF - * @param {String} filename the name of the file (not supported yet) - */ - p.createGraphics = function(w, h, render) { - var pg = new Processing(); - pg.size(w, h, render); - return pg; - }; - - // pixels caching - function resetContext() { - if(isContextReplaced) { - curContext = originalContext; - isContextReplaced = false; - - p.updatePixels(); - } - } - function SetPixelContextWrapper() { - function wrapFunction(newContext, name) { - function wrapper() { - resetContext(); - curContext[name].apply(curContext, arguments); - } - newContext[name] = wrapper; - } - function wrapProperty(newContext, name) { - function getter() { - resetContext(); - return curContext[name]; - } - function setter(value) { - resetContext(); - curContext[name] = value; - } - p.defineProperty(newContext, name, { get: getter, set: setter }); - } - for(var n in curContext) { - if(typeof curContext[n] === 'function') { - wrapFunction(this, n); - } else { - wrapProperty(this, n); - } - } - } - function replaceContext() { - if(isContextReplaced) { - return; - } - p.loadPixels(); - if(proxyContext === null) { - originalContext = curContext; - proxyContext = new SetPixelContextWrapper(); - } - isContextReplaced = true; - curContext = proxyContext; - setPixelsCached = 0; - } - - function set$3(x, y, c) { - if (x < p.width && x >= 0 && y >= 0 && y < p.height) { - replaceContext(); - p.pixels.setPixel((0|x)+p.width*(0|y), c); - if(++setPixelsCached > maxPixelsCached) { - resetContext(); - } - } - } - function set$4(x, y, obj, img) { - if (img.isRemote) { // Remote images cannot access imageData - throw "Image is loaded remotely. Cannot set x,y."; - } - var c = p.color.toArray(obj); - var offset = y * img.width * 4 + (x*4); - var data = img.imageData.data; - data[offset] = c[0]; - data[offset+1] = c[1]; - data[offset+2] = c[2]; - data[offset+3] = c[3]; - } - - // Paints a pixel array into the canvas - /** - * Changes the color of any pixel or writes an image directly into the display window. The x and y parameters - * specify the pixel to change and the color parameter specifies the color value. The color parameter is affected - * by the current color mode (the default is RGB values from 0 to 255). When setting an image, the x and y - * parameters define the coordinates for the upper-left corner of the image. - * Setting the color of a single pixel with set(x, y) is easy, but not as fast as putting the data directly - * into pixels[]. The equivalent statement to "set(x, y, #000000)" using pixels[] is "pixels[y*width+x] = #000000". - * You must call loadPixels() to load the display window data into the pixels[] array before setting the values - * and calling updatePixels() to update the window with any changes. This function ignores imageMode(). - * - * @param {int} x x-coordinate of the pixel - * @param {int} y y-coordinate of the pixel - * @param {Color} obj any value of the color datatype - * @param {PImage} img any valid variable of type PImage - * - * @see get - * @see pixels[] - * @see imageMode - */ - p.set = function(x, y, obj, img) { - var color, oldFill; - if (arguments.length === 3) { - // called p.set(), was it with a color or a img ? - if (typeof obj === "number") { - set$3(x, y, obj); - } else if (obj instanceof PImage || obj.__isPImage) { - p.image(obj, x, y); - } - } else if (arguments.length === 4) { - // PImage.set(x,y,c) was called, set coordinate x,y color to c of img - set$4(x, y, obj, img); - } - }; - p.imageData = {}; - - // handle the sketch code for pixels[] - // parser code converts pixels[] to getPixels() or setPixels(), - // .length becomes getLength() - /** - * Array containing the values for all the pixels in the display window. These values are of the color datatype. - * This array is the size of the display window. For example, if the image is 100x100 pixels, there will be 10000 - * values and if the window is 200x300 pixels, there will be 60000 values. The index value defines the position - * of a value within the array. For example, the statment color b = pixels[230] will set the variable b to be - * equal to the value at that location in the array. - * Before accessing this array, the data must loaded with the loadPixels() function. After the array data has - * been modified, the updatePixels() function must be run to update the changes. - * - * @param {int} index must not exceed the size of the array - * - * @see loadPixels - * @see updatePixels - * @see get - * @see set - * @see PImage - */ - p.pixels = { - getLength: function() { return p.imageData.data.length ? p.imageData.data.length/4 : 0; }, - getPixel: function(i) { - var offset = i*4, data = p.imageData.data; - return (data[offset+3] << 24) & 0xff000000 | - (data[offset+0] << 16) & 0x00ff0000 | - (data[offset+1] << 8) & 0x0000ff00 | - data[offset+2] & 0x000000ff; - }, - setPixel: function(i,c) { - var offset = i*4, data = p.imageData.data; - data[offset+0] = (c & 0x00ff0000) >>> 16; // RED_MASK - data[offset+1] = (c & 0x0000ff00) >>> 8; // GREEN_MASK - data[offset+2] = (c & 0x000000ff); // BLUE_MASK - data[offset+3] = (c & 0xff000000) >>> 24; // ALPHA_MASK - }, - toArray: function() { - var arr = [], length = p.imageData.width * p.imageData.height, data = p.imageData.data; - for (var i = 0, offset = 0; i < length; i++, offset += 4) { - arr.push((data[offset+3] << 24) & 0xff000000 | - (data[offset+0] << 16) & 0x00ff0000 | - (data[offset+1] << 8) & 0x0000ff00 | - data[offset+2] & 0x000000ff); - } - return arr; - }, - set: function(arr) { - for (var i = 0, aL = arr.length; i < aL; i++) { - this.setPixel(i, arr[i]); - } - } - }; - - // Gets a 1-Dimensional pixel array from Canvas - /** - * Loads the pixel data for the display window into the pixels[] array. This function must always be called - * before reading from or writing to pixels[]. - * Certain renderers may or may not seem to require loadPixels() or updatePixels(). However, the rule is that - * any time you want to manipulate the pixels[] array, you must first call loadPixels(), and after changes - * have been made, call updatePixels(). Even if the renderer may not seem to use this function in the current - * Processing release, this will always be subject to change. - * - * @see pixels[] - * @see updatePixels - */ - p.loadPixels = function() { - p.imageData = drawing.$ensureContext().getImageData(0, 0, p.width, p.height); - }; - - // Draws a 1-Dimensional pixel array to Canvas - /** - * Updates the display window with the data in the pixels[] array. Use in conjunction with loadPixels(). If - * you're only reading pixels from the array, there's no need to call updatePixels() unless there are changes. - * Certain renderers may or may not seem to require loadPixels() or updatePixels(). However, the rule is that - * any time you want to manipulate the pixels[] array, you must first call loadPixels(), and after changes - * have been made, call updatePixels(). Even if the renderer may not seem to use this function in the current - * Processing release, this will always be subject to change. - * Currently, none of the renderers use the additional parameters to updatePixels(), however this may be - * implemented in the future. - * - * @see loadPixels - * @see pixels[] - */ - p.updatePixels = function() { - if (p.imageData) { - drawing.$ensureContext().putImageData(p.imageData, 0, 0); - } - }; - - /** - * Set various hints and hacks for the renderer. This is used to handle obscure rendering features that cannot be - * implemented in a consistent manner across renderers. Many options will often graduate to standard features - * instead of hints over time. - * hint(ENABLE_OPENGL_4X_SMOOTH) - Enable 4x anti-aliasing for OpenGL. This can help force anti-aliasing if - * it has not been enabled by the user. On some graphics cards, this can also be set by the graphics driver's - * control panel, however not all cards make this available. This hint must be called immediately after the - * size() command because it resets the renderer, obliterating any settings and anything drawn (and like size(), - * re-running the code that came before it again). - * hint(DISABLE_OPENGL_2X_SMOOTH) - In Processing 1.0, Processing always enables 2x smoothing when the OpenGL - * renderer is used. This hint disables the default 2x smoothing and returns the smoothing behavior found in - * earlier releases, where smooth() and noSmooth() could be used to enable and disable smoothing, though the - * quality was inferior. - * hint(ENABLE_NATIVE_FONTS) - Use the native version fonts when they are installed, rather than the bitmapped - * version from a .vlw file. This is useful with the JAVA2D renderer setting, as it will improve font rendering - * speed. This is not enabled by default, because it can be misleading while testing because the type will look - * great on your machine (because you have the font installed) but lousy on others' machines if the identical - * font is unavailable. This option can only be set per-sketch, and must be called before any use of textFont(). - * hint(DISABLE_DEPTH_TEST) - Disable the zbuffer, allowing you to draw on top of everything at will. When depth - * testing is disabled, items will be drawn to the screen sequentially, like a painting. This hint is most often - * used to draw in 3D, then draw in 2D on top of it (for instance, to draw GUI controls in 2D on top of a 3D - * interface). Starting in release 0149, this will also clear the depth buffer. Restore the default with - * hint(ENABLE_DEPTH_TEST), but note that with the depth buffer cleared, any 3D drawing that happens later in - * draw() will ignore existing shapes on the screen. - * hint(ENABLE_DEPTH_SORT) - Enable primitive z-sorting of triangles and lines in P3D and OPENGL. This can slow - * performance considerably, and the algorithm is not yet perfect. Restore the default with hint(DISABLE_DEPTH_SORT). - * hint(DISABLE_OPENGL_ERROR_REPORT) - Speeds up the OPENGL renderer setting by not checking for errors while - * running. Undo with hint(ENABLE_OPENGL_ERROR_REPORT). - * As of release 0149, unhint() has been removed in favor of adding additional ENABLE/DISABLE constants to reset - * the default behavior. This prevents the double negatives, and also reinforces which hints can be enabled or disabled. - * - * @param {MODE} item constant: name of the hint to be enabled or disabled - * - * @see PGraphics - * @see createGraphics - * @see size - */ - p.hint = function(which) { - var curContext = drawing.$ensureContext(); - if (which === PConstants.DISABLE_DEPTH_TEST) { - curContext.disable(curContext.DEPTH_TEST); - curContext.depthMask(false); - curContext.clear(curContext.DEPTH_BUFFER_BIT); - } - else if (which === PConstants.ENABLE_DEPTH_TEST) { - curContext.enable(curContext.DEPTH_TEST); - curContext.depthMask(true); - } - }; - - /** - * The background() function sets the color used for the background of the Processing window. - * The default background is light gray. In the draw() function, the background color is used to clear the display window at the beginning of each frame. - * An image can also be used as the background for a sketch, however its width and height must be the same size as the sketch window. - * To resize an image 'b' to the size of the sketch window, use b.resize(width, height). - * Images used as background will ignore the current tint() setting. - * For the main drawing surface, the alpha value will be ignored. However, - * alpha can be used on PGraphics objects from createGraphics(). This is - * the only way to set all the pixels partially transparent, for instance. - * If the 'gray' parameter is passed in the function sets the background to a grayscale value, based on the - * current colorMode. - *

- * Note that background() should be called before any transformations occur, - * because some implementations may require the current transformation matrix - * to be identity before drawing. - * - * @param {int|float} gray specifies a value between white and black - * @param {int|float} value1 red or hue value (depending on the current color mode) - * @param {int|float} value2 green or saturation value (depending on the current color mode) - * @param {int|float} value3 blue or brightness value (depending on the current color mode) - * @param {int|float} alpha opacity of the background - * @param {Color} color any value of the color datatype - * @param {int} hex color value in hexadecimal notation (i.e. #FFCC00 or 0xFFFFCC00) - * @param {PImage} image an instance of a PImage to use as a background - * - * @see #stroke() - * @see #fill() - * @see #tint() - * @see #colorMode() - */ - var backgroundHelper = function(arg1, arg2, arg3, arg4) { - var obj; - - if (arg1 instanceof PImage || arg1.__isPImage) { - obj = arg1; - - if (!obj.loaded) { - throw "Error using image in background(): PImage not loaded."; - } - if(obj.width !== p.width || obj.height !== p.height){ - throw "Background image must be the same dimensions as the canvas."; - } - } else { - obj = p.color(arg1, arg2, arg3, arg4); - } - - backgroundObj = obj; - }; - - Drawing2D.prototype.background = function(arg1, arg2, arg3, arg4) { - if (arg1 !== undef) { - backgroundHelper(arg1, arg2, arg3, arg4); - } - - if (backgroundObj instanceof PImage || backgroundObj.__isPImage) { - saveContext(); - curContext.setTransform(1, 0, 0, 1, 0, 0); - p.image(backgroundObj, 0, 0); - restoreContext(); - } else { - saveContext(); - curContext.setTransform(1, 0, 0, 1, 0, 0); - - // If the background is transparent - if (p.alpha(backgroundObj) !== colorModeA) { - curContext.clearRect(0,0, p.width, p.height); - } - curContext.fillStyle = p.color.toString(backgroundObj); - curContext.fillRect(0, 0, p.width, p.height); - isFillDirty = true; - restoreContext(); - } - }; - - Drawing3D.prototype.background = function(arg1, arg2, arg3, arg4) { - if (arguments.length > 0) { - backgroundHelper(arg1, arg2, arg3, arg4); - } - - var c = p.color.toGLArray(backgroundObj); - curContext.clearColor(c[0], c[1], c[2], c[3]); - curContext.clear(curContext.COLOR_BUFFER_BIT | curContext.DEPTH_BUFFER_BIT); - - // An image as a background in 3D is not implemented yet - }; - - // Draws an image to the Canvas - /** - * Displays images to the screen. The images must be in the sketch's "data" directory to load correctly. Select "Add - * file..." from the "Sketch" menu to add the image. Processing currently works with GIF, JPEG, and Targa images. The - * color of an image may be modified with the tint() function and if a GIF has transparency, it will maintain its - * transparency. The img parameter specifies the image to display and the x and y parameters define the location of - * the image from its upper-left corner. The image is displayed at its original size unless the width and height - * parameters specify a different size. The imageMode() function changes the way the parameters work. A call to - * imageMode(CORNERS) will change the width and height parameters to define the x and y values of the opposite - * corner of the image. - * - * @param {PImage} img the image to display - * @param {int|float} x x-coordinate of the image - * @param {int|float} y y-coordinate of the image - * @param {int|float} width width to display the image - * @param {int|float} height height to display the image - * - * @see loadImage - * @see PImage - * @see imageMode - * @see tint - * @see background - * @see alpha - */ - Drawing2D.prototype.image = function(img, x, y, w, h) { - // Fix fractional positions - x = Math.round(x); - y = Math.round(y); - - if (img.width > 0) { - var wid = w || img.width; - var hgt = h || img.height; - - var bounds = imageModeConvert(x || 0, y || 0, w || img.width, h || img.height, arguments.length < 4); - var fastImage = !!img.sourceImg && curTint === null; - if (fastImage) { - var htmlElement = img.sourceImg; - if (img.__isDirty) { - img.updatePixels(); - } - // Using HTML element's width and height in case if the image was resized. - curContext.drawImage(htmlElement, 0, 0, - htmlElement.width, htmlElement.height, bounds.x, bounds.y, bounds.w, bounds.h); - } else { - var obj = img.toImageData(); - - // Tint the image - if (curTint !== null) { - curTint(obj); - img.__isDirty = true; - } - - curContext.drawImage(getCanvasData(obj).canvas, 0, 0, - img.width, img.height, bounds.x, bounds.y, bounds.w, bounds.h); - } - } - }; - - Drawing3D.prototype.image = function(img, x, y, w, h) { - if (img.width > 0) { - // Fix fractional positions - x = Math.round(x); - y = Math.round(y); - w = w || img.width; - h = h || img.height; - - p.beginShape(p.QUADS); - p.texture(img); - p.vertex(x, y, 0, 0, 0); - p.vertex(x, y+h, 0, 0, h); - p.vertex(x+w, y+h, 0, w, h); - p.vertex(x+w, y, 0, w, 0); - p.endShape(); - } - }; - - /** - * The tint() function sets the fill value for displaying images. Images can be tinted to - * specified colors or made transparent by setting the alpha. - *

To make an image transparent, but not change it's color, - * use white as the tint color and specify an alpha value. For instance, - * tint(255, 128) will make an image 50% transparent (unless - * colorMode() has been used). - * - *

When using hexadecimal notation to specify a color, use "#" or - * "0x" before the values (e.g. #CCFFAA, 0xFFCCFFAA). The # syntax uses six - * digits to specify a color (the way colors are specified in HTML and CSS). - * When using the hexadecimal notation starting with "0x", the hexadecimal - * value must be specified with eight characters; the first two characters - * define the alpha component and the remainder the red, green, and blue - * components. - *

The value for the parameter "gray" must be less than or equal - * to the current maximum value as specified by colorMode(). - * The default maximum value is 255. - *

The tint() method is also used to control the coloring of - * textures in 3D. - * - * @param {int|float} gray any valid number - * @param {int|float} alpha opacity of the image - * @param {int|float} value1 red or hue value - * @param {int|float} value2 green or saturation value - * @param {int|float} value3 blue or brightness value - * @param {int|float} color any value of the color datatype - * @param {int} hex color value in hexadecimal notation (i.e. #FFCC00 or 0xFFFFCC00) - * - * @see #noTint() - * @see #image() - */ - p.tint = function(a1, a2, a3, a4) { - var tintColor = p.color(a1, a2, a3, a4); - var r = p.red(tintColor) / colorModeX; - var g = p.green(tintColor) / colorModeY; - var b = p.blue(tintColor) / colorModeZ; - var a = p.alpha(tintColor) / colorModeA; - curTint = function(obj) { - var data = obj.data, - length = 4 * obj.width * obj.height; - for (var i = 0; i < length;) { - data[i++] *= r; - data[i++] *= g; - data[i++] *= b; - data[i++] *= a; - } - }; - // for overriding the color buffer when 3d rendering - curTint3d = function(data){ - for (var i = 0; i < data.length;) { - data[i++] = r; - data[i++] = g; - data[i++] = b; - data[i++] = a; - } - }; - }; - - /** - * The noTint() function removes the current fill value for displaying images and reverts to displaying images with their original hues. - * - * @see #tint() - * @see #image() - */ - p.noTint = function() { - curTint = null; - curTint3d = null; - }; - - /** - * Copies a region of pixels from the display window to another area of the display window and copies a region of pixels from an - * image used as the srcImg parameter into the display window. If the source and destination regions aren't the same size, it will - * automatically resize the source pixels to fit the specified target region. No alpha information is used in the process, however - * if the source image has an alpha channel set, it will be copied as well. This function ignores imageMode(). - * - * @param {int} x X coordinate of the source's upper left corner - * @param {int} y Y coordinate of the source's upper left corner - * @param {int} width source image width - * @param {int} height source image height - * @param {int} dx X coordinate of the destination's upper left corner - * @param {int} dy Y coordinate of the destination's upper left corner - * @param {int} dwidth destination image width - * @param {int} dheight destination image height - * @param {PImage} srcImg image variable referring to the source image - * - * @see blend - * @see get - */ - p.copy = function(src, sx, sy, sw, sh, dx, dy, dw, dh) { - if (dh === undef) { - // shift everything, and introduce p - dh = dw; - dw = dy; - dy = dx; - dx = sh; - sh = sw; - sw = sy; - sy = sx; - sx = src; - src = p; - } - p.blend(src, sx, sy, sw, sh, dx, dy, dw, dh, PConstants.REPLACE); - }; - - /** - * Blends a region of pixels from one image into another (or in itself again) with full alpha channel support. There - * is a choice of the following modes to blend the source pixels (A) with the ones of pixels in the destination image (B): - * BLEND - linear interpolation of colours: C = A*factor + B - * ADD - additive blending with white clip: C = min(A*factor + B, 255) - * SUBTRACT - subtractive blending with black clip: C = max(B - A*factor, 0) - * DARKEST - only the darkest colour succeeds: C = min(A*factor, B) - * LIGHTEST - only the lightest colour succeeds: C = max(A*factor, B) - * DIFFERENCE - subtract colors from underlying image. - * EXCLUSION - similar to DIFFERENCE, but less extreme. - * MULTIPLY - Multiply the colors, result will always be darker. - * SCREEN - Opposite multiply, uses inverse values of the colors. - * OVERLAY - A mix of MULTIPLY and SCREEN. Multiplies dark values, and screens light values. - * HARD_LIGHT - SCREEN when greater than 50% gray, MULTIPLY when lower. - * SOFT_LIGHT - Mix of DARKEST and LIGHTEST. Works like OVERLAY, but not as harsh. - * DODGE - Lightens light tones and increases contrast, ignores darks. Called "Color Dodge" in Illustrator and Photoshop. - * BURN - Darker areas are applied, increasing contrast, ignores lights. Called "Color Burn" in Illustrator and Photoshop. - * All modes use the alpha information (highest byte) of source image pixels as the blending factor. If the source and - * destination regions are different sizes, the image will be automatically resized to match the destination size. If the - * srcImg parameter is not used, the display window is used as the source image. This function ignores imageMode(). - * - * @param {int} x X coordinate of the source's upper left corner - * @param {int} y Y coordinate of the source's upper left corner - * @param {int} width source image width - * @param {int} height source image height - * @param {int} dx X coordinate of the destination's upper left corner - * @param {int} dy Y coordinate of the destination's upper left corner - * @param {int} dwidth destination image width - * @param {int} dheight destination image height - * @param {PImage} srcImg image variable referring to the source image - * @param {PImage} MODE Either BLEND, ADD, SUBTRACT, LIGHTEST, DARKEST, DIFFERENCE, EXCLUSION, MULTIPLY, SCREEN, - * OVERLAY, HARD_LIGHT, SOFT_LIGHT, DODGE, BURN - * @see filter - */ - p.blend = function(src, sx, sy, sw, sh, dx, dy, dw, dh, mode, pimgdest) { - if (src.isRemote) { - throw "Image is loaded remotely. Cannot blend image."; - } - - if (mode === undef) { - // shift everything, and introduce p - mode = dh; - dh = dw; - dw = dy; - dy = dx; - dx = sh; - sh = sw; - sw = sy; - sy = sx; - sx = src; - src = p; - } - - var sx2 = sx + sw, - sy2 = sy + sh, - dx2 = dx + dw, - dy2 = dy + dh, - dest = pimgdest || p; - - // check if pimgdest is there and pixels, if so this was a call from pimg.blend - if (pimgdest === undef || mode === undef) { - p.loadPixels(); - } - - src.loadPixels(); - - if (src === p && p.intersect(sx, sy, sx2, sy2, dx, dy, dx2, dy2)) { - p.blit_resize(p.get(sx, sy, sx2 - sx, sy2 - sy), 0, 0, sx2 - sx - 1, sy2 - sy - 1, - dest.imageData.data, dest.width, dest.height, dx, dy, dx2, dy2, mode); - } else { - p.blit_resize(src, sx, sy, sx2, sy2, dest.imageData.data, dest.width, dest.height, dx, dy, dx2, dy2, mode); - } - - if (pimgdest === undef) { - p.updatePixels(); - } - }; - - // helper function for filter() - var buildBlurKernel = function(r) { - var radius = p.floor(r * 3.5), i, radiusi; - radius = (radius < 1) ? 1 : ((radius < 248) ? radius : 248); - if (p.shared.blurRadius !== radius) { - p.shared.blurRadius = radius; - p.shared.blurKernelSize = 1 + (p.shared.blurRadius<<1); - p.shared.blurKernel = new Float32Array(p.shared.blurKernelSize); - var sharedBlurKernal = p.shared.blurKernel; - var sharedBlurKernelSize = p.shared.blurKernelSize; - var sharedBlurRadius = p.shared.blurRadius; - // init blurKernel - for (i = 0; i < sharedBlurKernelSize; i++) { - sharedBlurKernal[i] = 0; - } - var radiusiSquared = (radius - 1) * (radius - 1); - for (i = 1; i < radius; i++) { - sharedBlurKernal[radius + i] = sharedBlurKernal[radiusi] = radiusiSquared; - } - sharedBlurKernal[radius] = radius * radius; - } - }; - - var blurARGB = function(r, aImg) { - var sum, cr, cg, cb, ca, c, m; - var read, ri, ym, ymi, bk0; - var wh = aImg.pixels.getLength(); - var r2 = new Float32Array(wh); - var g2 = new Float32Array(wh); - var b2 = new Float32Array(wh); - var a2 = new Float32Array(wh); - var yi = 0; - var x, y, i, offset; - - buildBlurKernel(r); - - var aImgHeight = aImg.height; - var aImgWidth = aImg.width; - var sharedBlurKernelSize = p.shared.blurKernelSize; - var sharedBlurRadius = p.shared.blurRadius; - var sharedBlurKernal = p.shared.blurKernel; - var pix = aImg.imageData.data; - - for (y = 0; y < aImgHeight; y++) { - for (x = 0; x < aImgWidth; x++) { - cb = cg = cr = ca = sum = 0; - read = x - sharedBlurRadius; - if (read<0) { - bk0 = -read; - read = 0; - } else { - if (read >= aImgWidth) { - break; - } - bk0=0; - } - for (i = bk0; i < sharedBlurKernelSize; i++) { - if (read >= aImgWidth) { - break; - } - offset = (read + yi) *4; - m = sharedBlurKernal[i]; - ca += m * pix[offset + 3]; - cr += m * pix[offset]; - cg += m * pix[offset + 1]; - cb += m * pix[offset + 2]; - sum += m; - read++; - } - ri = yi + x; - a2[ri] = ca / sum; - r2[ri] = cr / sum; - g2[ri] = cg / sum; - b2[ri] = cb / sum; - } - yi += aImgWidth; - } - - yi = 0; - ym = -sharedBlurRadius; - ymi = ym*aImgWidth; - - for (y = 0; y < aImgHeight; y++) { - for (x = 0; x < aImgWidth; x++) { - cb = cg = cr = ca = sum = 0; - if (ym<0) { - bk0 = ri = -ym; - read = x; - } else { - if (ym >= aImgHeight) { - break; - } - bk0 = 0; - ri = ym; - read = x + ymi; - } - for (i = bk0; i < sharedBlurKernelSize; i++) { - if (ri >= aImgHeight) { - break; - } - m = sharedBlurKernal[i]; - ca += m * a2[read]; - cr += m * r2[read]; - cg += m * g2[read]; - cb += m * b2[read]; - sum += m; - ri++; - read += aImgWidth; - } - offset = (x + yi) *4; - pix[offset] = cr / sum; - pix[offset + 1] = cg / sum; - pix[offset + 2] = cb / sum; - pix[offset + 3] = ca / sum; - } - yi += aImgWidth; - ymi += aImgWidth; - ym++; - } - }; - - // helper funtion for ERODE and DILATE modes of filter() - var dilate = function(isInverted, aImg) { - var currIdx = 0; - var maxIdx = aImg.pixels.getLength(); - var out = new Int32Array(maxIdx); - var currRowIdx, maxRowIdx, colOrig, colOut, currLum; - var idxRight, idxLeft, idxUp, idxDown, - colRight, colLeft, colUp, colDown, - lumRight, lumLeft, lumUp, lumDown; - - if (!isInverted) { - // erosion (grow light areas) - while (currIdx= maxRowIdx) { - idxRight = currIdx; - } - if (idxUp < 0) { - idxUp = 0; - } - if (idxDown >= maxIdx) { - idxDown = currIdx; - } - colUp = aImg.pixels.getPixel(idxUp); - colLeft = aImg.pixels.getPixel(idxLeft); - colDown = aImg.pixels.getPixel(idxDown); - colRight = aImg.pixels.getPixel(idxRight); - - // compute luminance - currLum = 77*(colOrig>>16&0xff) + 151*(colOrig>>8&0xff) + 28*(colOrig&0xff); - lumLeft = 77*(colLeft>>16&0xff) + 151*(colLeft>>8&0xff) + 28*(colLeft&0xff); - lumRight = 77*(colRight>>16&0xff) + 151*(colRight>>8&0xff) + 28*(colRight&0xff); - lumUp = 77*(colUp>>16&0xff) + 151*(colUp>>8&0xff) + 28*(colUp&0xff); - lumDown = 77*(colDown>>16&0xff) + 151*(colDown>>8&0xff) + 28*(colDown&0xff); - - if (lumLeft > currLum) { - colOut = colLeft; - currLum = lumLeft; - } - if (lumRight > currLum) { - colOut = colRight; - currLum = lumRight; - } - if (lumUp > currLum) { - colOut = colUp; - currLum = lumUp; - } - if (lumDown > currLum) { - colOut = colDown; - currLum = lumDown; - } - out[currIdx++] = colOut; - } - } - } else { - // dilate (grow dark areas) - while (currIdx < maxIdx) { - currRowIdx = currIdx; - maxRowIdx = currIdx + aImg.width; - while (currIdx < maxRowIdx) { - colOrig = colOut = aImg.pixels.getPixel(currIdx); - idxLeft = currIdx - 1; - idxRight = currIdx + 1; - idxUp = currIdx - aImg.width; - idxDown = currIdx + aImg.width; - if (idxLeft < currRowIdx) { - idxLeft = currIdx; - } - if (idxRight >= maxRowIdx) { - idxRight = currIdx; - } - if (idxUp < 0) { - idxUp = 0; - } - if (idxDown >= maxIdx) { - idxDown = currIdx; - } - colUp = aImg.pixels.getPixel(idxUp); - colLeft = aImg.pixels.getPixel(idxLeft); - colDown = aImg.pixels.getPixel(idxDown); - colRight = aImg.pixels.getPixel(idxRight); - - // compute luminance - currLum = 77*(colOrig>>16&0xff) + 151*(colOrig>>8&0xff) + 28*(colOrig&0xff); - lumLeft = 77*(colLeft>>16&0xff) + 151*(colLeft>>8&0xff) + 28*(colLeft&0xff); - lumRight = 77*(colRight>>16&0xff) + 151*(colRight>>8&0xff) + 28*(colRight&0xff); - lumUp = 77*(colUp>>16&0xff) + 151*(colUp>>8&0xff) + 28*(colUp&0xff); - lumDown = 77*(colDown>>16&0xff) + 151*(colDown>>8&0xff) + 28*(colDown&0xff); - - if (lumLeft < currLum) { - colOut = colLeft; - currLum = lumLeft; - } - if (lumRight < currLum) { - colOut = colRight; - currLum = lumRight; - } - if (lumUp < currLum) { - colOut = colUp; - currLum = lumUp; - } - if (lumDown < currLum) { - colOut = colDown; - currLum = lumDown; - } - out[currIdx++]=colOut; - } - } - } - aImg.pixels.set(out); - //p.arraycopy(out,0,pixels,0,maxIdx); - }; - - /** - * Filters the display window as defined by one of the following modes: - * THRESHOLD - converts the image to black and white pixels depending if they are above or below the threshold - * defined by the level parameter. The level must be between 0.0 (black) and 1.0(white). If no level is specified, 0.5 is used. - * GRAY - converts any colors in the image to grayscale equivalents - * INVERT - sets each pixel to its inverse value - * POSTERIZE - limits each channel of the image to the number of colors specified as the level parameter - * BLUR - executes a Guassian blur with the level parameter specifying the extent of the blurring. If no level parameter is - * used, the blur is equivalent to Guassian blur of radius 1. - * OPAQUE - sets the alpha channel to entirely opaque. - * ERODE - reduces the light areas with the amount defined by the level parameter. - * DILATE - increases the light areas with the amount defined by the level parameter. - * - * @param {MODE} MODE Either THRESHOLD, GRAY, INVERT, POSTERIZE, BLUR, OPAQUE, ERODE, or DILATE - * @param {int|float} level defines the quality of the filter - * - * @see blend - */ - p.filter = function(kind, param, aImg){ - var img, col, lum, i; - - if (arguments.length === 3) { - aImg.loadPixels(); - img = aImg; - } else { - p.loadPixels(); - img = p; - } - - if (param === undef) { - param = null; - } - if (img.isRemote) { // Remote images cannot access imageData - throw "Image is loaded remotely. Cannot filter image."; - } - // begin filter process - var imglen = img.pixels.getLength(); - switch (kind) { - case PConstants.BLUR: - var radius = param || 1; // if no param specified, use 1 (default for p5) - blurARGB(radius, img); - break; - - case PConstants.GRAY: - if (img.format === PConstants.ALPHA) { //trouble - // for an alpha image, convert it to an opaque grayscale - for (i = 0; i < imglen; i++) { - col = 255 - img.pixels.getPixel(i); - img.pixels.setPixel(i,(0xff000000 | (col << 16) | (col << 8) | col)); - } - img.format = PConstants.RGB; //trouble - } else { - for (i = 0; i < imglen; i++) { - col = img.pixels.getPixel(i); - lum = (77*(col>>16&0xff) + 151*(col>>8&0xff) + 28*(col&0xff))>>8; - img.pixels.setPixel(i,((col & PConstants.ALPHA_MASK) | lum<<16 | lum<<8 | lum)); - } - } - break; - - case PConstants.INVERT: - for (i = 0; i < imglen; i++) { - img.pixels.setPixel(i, (img.pixels.getPixel(i) ^ 0xffffff)); - } - break; - - case PConstants.POSTERIZE: - if (param === null) { - throw "Use filter(POSTERIZE, int levels) instead of filter(POSTERIZE)"; - } - var levels = p.floor(param); - if ((levels < 2) || (levels > 255)) { - throw "Levels must be between 2 and 255 for filter(POSTERIZE, levels)"; - } - var levels1 = levels - 1; - for (i = 0; i < imglen; i++) { - var rlevel = (img.pixels.getPixel(i) >> 16) & 0xff; - var glevel = (img.pixels.getPixel(i) >> 8) & 0xff; - var blevel = img.pixels.getPixel(i) & 0xff; - rlevel = (((rlevel * levels) >> 8) * 255) / levels1; - glevel = (((glevel * levels) >> 8) * 255) / levels1; - blevel = (((blevel * levels) >> 8) * 255) / levels1; - img.pixels.setPixel(i, ((0xff000000 & img.pixels.getPixel(i)) | (rlevel << 16) | (glevel << 8) | blevel)); - } - break; - - case PConstants.OPAQUE: - for (i = 0; i < imglen; i++) { - img.pixels.setPixel(i, (img.pixels.getPixel(i) | 0xff000000)); - } - img.format = PConstants.RGB; //trouble - break; - - case PConstants.THRESHOLD: - if (param === null) { - param = 0.5; - } - if ((param < 0) || (param > 1)) { - throw "Level must be between 0 and 1 for filter(THRESHOLD, level)"; - } - var thresh = p.floor(param * 255); - for (i = 0; i < imglen; i++) { - var max = p.max((img.pixels.getPixel(i) & PConstants.RED_MASK) >> 16, p.max((img.pixels.getPixel(i) & PConstants.GREEN_MASK) >> 8, (img.pixels.getPixel(i) & PConstants.BLUE_MASK))); - img.pixels.setPixel(i, ((img.pixels.getPixel(i) & PConstants.ALPHA_MASK) | ((max < thresh) ? 0x000000 : 0xffffff))); - } - break; - - case PConstants.ERODE: - dilate(true, img); - break; - - case PConstants.DILATE: - dilate(false, img); - break; - } - img.updatePixels(); - }; - - - // shared variables for blit_resize(), filter_new_scanline(), filter_bilinear(), filter() - // change this in the future to not be exposed to p - p.shared = { - fracU: 0, - ifU: 0, - fracV: 0, - ifV: 0, - u1: 0, - u2: 0, - v1: 0, - v2: 0, - sX: 0, - sY: 0, - iw: 0, - iw1: 0, - ih1: 0, - ul: 0, - ll: 0, - ur: 0, - lr: 0, - cUL: 0, - cLL: 0, - cUR: 0, - cLR: 0, - srcXOffset: 0, - srcYOffset: 0, - r: 0, - g: 0, - b: 0, - a: 0, - srcBuffer: null, - blurRadius: 0, - blurKernelSize: 0, - blurKernel: null - }; - - p.intersect = function(sx1, sy1, sx2, sy2, dx1, dy1, dx2, dy2) { - var sw = sx2 - sx1 + 1; - var sh = sy2 - sy1 + 1; - var dw = dx2 - dx1 + 1; - var dh = dy2 - dy1 + 1; - if (dx1 < sx1) { - dw += dx1 - sx1; - if (dw > sw) { - dw = sw; - } - } else { - var w = sw + sx1 - dx1; - if (dw > w) { - dw = w; - } - } - if (dy1 < sy1) { - dh += dy1 - sy1; - if (dh > sh) { - dh = sh; - } - } else { - var h = sh + sy1 - dy1; - if (dh > h) { - dh = h; - } - } - return ! (dw <= 0 || dh <= 0); - }; - - var blendFuncs = {}; - blendFuncs[PConstants.BLEND] = p.modes.blend; - blendFuncs[PConstants.ADD] = p.modes.add; - blendFuncs[PConstants.SUBTRACT] = p.modes.subtract; - blendFuncs[PConstants.LIGHTEST] = p.modes.lightest; - blendFuncs[PConstants.DARKEST] = p.modes.darkest; - blendFuncs[PConstants.REPLACE] = p.modes.replace; - blendFuncs[PConstants.DIFFERENCE] = p.modes.difference; - blendFuncs[PConstants.EXCLUSION] = p.modes.exclusion; - blendFuncs[PConstants.MULTIPLY] = p.modes.multiply; - blendFuncs[PConstants.SCREEN] = p.modes.screen; - blendFuncs[PConstants.OVERLAY] = p.modes.overlay; - blendFuncs[PConstants.HARD_LIGHT] = p.modes.hard_light; - blendFuncs[PConstants.SOFT_LIGHT] = p.modes.soft_light; - blendFuncs[PConstants.DODGE] = p.modes.dodge; - blendFuncs[PConstants.BURN] = p.modes.burn; - - p.blit_resize = function(img, srcX1, srcY1, srcX2, srcY2, destPixels, - screenW, screenH, destX1, destY1, destX2, destY2, mode) { - var x, y; - if (srcX1 < 0) { - srcX1 = 0; - } - if (srcY1 < 0) { - srcY1 = 0; - } - if (srcX2 >= img.width) { - srcX2 = img.width - 1; - } - if (srcY2 >= img.height) { - srcY2 = img.height - 1; - } - var srcW = srcX2 - srcX1; - var srcH = srcY2 - srcY1; - var destW = destX2 - destX1; - var destH = destY2 - destY1; - - if (destW <= 0 || destH <= 0 || srcW <= 0 || srcH <= 0 || destX1 >= screenW || - destY1 >= screenH || srcX1 >= img.width || srcY1 >= img.height) { - return; - } - - var dx = Math.floor(srcW / destW * PConstants.PRECISIONF); - var dy = Math.floor(srcH / destH * PConstants.PRECISIONF); - - var pshared = p.shared; - - pshared.srcXOffset = Math.floor(destX1 < 0 ? -destX1 * dx : srcX1 * PConstants.PRECISIONF); - pshared.srcYOffset = Math.floor(destY1 < 0 ? -destY1 * dy : srcY1 * PConstants.PRECISIONF); - if (destX1 < 0) { - destW += destX1; - destX1 = 0; - } - if (destY1 < 0) { - destH += destY1; - destY1 = 0; - } - destW = Math.min(destW, screenW - destX1); - destH = Math.min(destH, screenH - destY1); - - var destOffset = destY1 * screenW + destX1; - var destColor; - - pshared.srcBuffer = img.imageData.data; - pshared.iw = img.width; - pshared.iw1 = img.width - 1; - pshared.ih1 = img.height - 1; - - // cache for speed - var filterBilinear = p.filter_bilinear, - filterNewScanline = p.filter_new_scanline, - blendFunc = blendFuncs[mode], - blendedColor, - idx, - cULoffset, - cURoffset, - cLLoffset, - cLRoffset, - ALPHA_MASK = PConstants.ALPHA_MASK, - RED_MASK = PConstants.RED_MASK, - GREEN_MASK = PConstants.GREEN_MASK, - BLUE_MASK = PConstants.BLUE_MASK, - PREC_MAXVAL = PConstants.PREC_MAXVAL, - PRECISIONB = PConstants.PRECISIONB, - PREC_RED_SHIFT = PConstants.PREC_RED_SHIFT, - PREC_ALPHA_SHIFT = PConstants.PREC_ALPHA_SHIFT, - srcBuffer = pshared.srcBuffer, - min = Math.min; - - for (y = 0; y < destH; y++) { - - pshared.sX = pshared.srcXOffset; - pshared.fracV = pshared.srcYOffset & PREC_MAXVAL; - pshared.ifV = PREC_MAXVAL - pshared.fracV; - pshared.v1 = (pshared.srcYOffset >> PRECISIONB) * pshared.iw; - pshared.v2 = min((pshared.srcYOffset >> PRECISIONB) + 1, pshared.ih1) * pshared.iw; - - for (x = 0; x < destW; x++) { - idx = (destOffset + x) * 4; - - destColor = (destPixels[idx + 3] << 24) & - ALPHA_MASK | (destPixels[idx] << 16) & - RED_MASK | (destPixels[idx + 1] << 8) & - GREEN_MASK | destPixels[idx + 2] & BLUE_MASK; - - pshared.fracU = pshared.sX & PREC_MAXVAL; - pshared.ifU = PREC_MAXVAL - pshared.fracU; - pshared.ul = (pshared.ifU * pshared.ifV) >> PRECISIONB; - pshared.ll = (pshared.ifU * pshared.fracV) >> PRECISIONB; - pshared.ur = (pshared.fracU * pshared.ifV) >> PRECISIONB; - pshared.lr = (pshared.fracU * pshared.fracV) >> PRECISIONB; - pshared.u1 = (pshared.sX >> PRECISIONB); - pshared.u2 = min(pshared.u1 + 1, pshared.iw1); - - cULoffset = (pshared.v1 + pshared.u1) * 4; - cURoffset = (pshared.v1 + pshared.u2) * 4; - cLLoffset = (pshared.v2 + pshared.u1) * 4; - cLRoffset = (pshared.v2 + pshared.u2) * 4; - - pshared.cUL = (srcBuffer[cULoffset + 3] << 24) & - ALPHA_MASK | (srcBuffer[cULoffset] << 16) & - RED_MASK | (srcBuffer[cULoffset + 1] << 8) & - GREEN_MASK | srcBuffer[cULoffset + 2] & BLUE_MASK; - - pshared.cUR = (srcBuffer[cURoffset + 3] << 24) & - ALPHA_MASK | (srcBuffer[cURoffset] << 16) & - RED_MASK | (srcBuffer[cURoffset + 1] << 8) & - GREEN_MASK | srcBuffer[cURoffset + 2] & BLUE_MASK; - - pshared.cLL = (srcBuffer[cLLoffset + 3] << 24) & - ALPHA_MASK | (srcBuffer[cLLoffset] << 16) & - RED_MASK | (srcBuffer[cLLoffset + 1] << 8) & - GREEN_MASK | srcBuffer[cLLoffset + 2] & BLUE_MASK; - - pshared.cLR = (srcBuffer[cLRoffset + 3] << 24) & - ALPHA_MASK | (srcBuffer[cLRoffset] << 16) & - RED_MASK | (srcBuffer[cLRoffset + 1] << 8) & - GREEN_MASK | srcBuffer[cLRoffset + 2] & BLUE_MASK; - - pshared.r = ((pshared.ul * ((pshared.cUL & RED_MASK) >> 16) + - pshared.ll * ((pshared.cLL & RED_MASK) >> 16) + - pshared.ur * ((pshared.cUR & RED_MASK) >> 16) + - pshared.lr * ((pshared.cLR & RED_MASK) >> 16)) << PREC_RED_SHIFT) & RED_MASK; - pshared.g = ((pshared.ul * (pshared.cUL & GREEN_MASK) + - pshared.ll * (pshared.cLL & GREEN_MASK) + - pshared.ur * (pshared.cUR & GREEN_MASK) + - pshared.lr * (pshared.cLR & GREEN_MASK)) >>> PRECISIONB) & GREEN_MASK; - pshared.b = (pshared.ul * (pshared.cUL & BLUE_MASK) + - pshared.ll * (pshared.cLL & BLUE_MASK) + - pshared.ur * (pshared.cUR & BLUE_MASK) + - pshared.lr * (pshared.cLR & BLUE_MASK)) >>> PRECISIONB; - pshared.a = ((pshared.ul * ((pshared.cUL & ALPHA_MASK) >>> 24) + - pshared.ll * ((pshared.cLL & ALPHA_MASK) >>> 24) + - pshared.ur * ((pshared.cUR & ALPHA_MASK) >>> 24) + - pshared.lr * ((pshared.cLR & ALPHA_MASK) >>> 24)) << PREC_ALPHA_SHIFT) & ALPHA_MASK; - - blendedColor = blendFunc(destColor, (pshared.a | pshared.r | pshared.g | pshared.b)); - - destPixels[idx] = (blendedColor & RED_MASK) >>> 16; - destPixels[idx + 1] = (blendedColor & GREEN_MASK) >>> 8; - destPixels[idx + 2] = (blendedColor & BLUE_MASK); - destPixels[idx + 3] = (blendedColor & ALPHA_MASK) >>> 24; - - pshared.sX += dx; - } - destOffset += screenW; - pshared.srcYOffset += dy; - } - }; - - //////////////////////////////////////////////////////////////////////////// - // Font handling - //////////////////////////////////////////////////////////////////////////// - - /** - * loadFont() Loads a font into a variable of type PFont. - * - * @param {String} name filename of the font to load - * @param {int|float} size option font size (used internally) - * - * @returns {PFont} new PFont object - * - * @see #PFont - * @see #textFont - * @see #text - * @see #createFont - */ - p.loadFont = function(name, size) { - if (name === undef) { - throw("font name required in loadFont."); - } - if (name.indexOf(".svg") === -1) { - if (size === undef) { - size = curTextFont.size; - } - return PFont.get(name, size); - } - // If the font is a glyph, calculate by SVG table - var font = p.loadGlyphs(name); - - return { - name: name, - css: '12px sans-serif', - glyph: true, - units_per_em: font.units_per_em, - horiz_adv_x: 1 / font.units_per_em * font.horiz_adv_x, - ascent: font.ascent, - descent: font.descent, - width: function(str) { - var width = 0; - var len = str.length; - for (var i = 0; i < len; i++) { - try { - width += parseFloat(p.glyphLook(p.glyphTable[name], str[i]).horiz_adv_x); - } - catch(e) { - Processing.debug(e); - } - } - return width / p.glyphTable[name].units_per_em; - } - }; - }; - - /** - * createFont() Loads a font into a variable of type PFont. - * Smooth and charset are ignored in Processing.js. - * - * @param {String} name filename of the font to load - * @param {int|float} size font size in pixels - * @param {boolean} smooth not used in Processing.js - * @param {char[]} charset not used in Processing.js - * - * @returns {PFont} new PFont object - * - * @see #PFont - * @see #textFont - * @see #text - * @see #loadFont - */ - p.createFont = function(name, size) { - // because Processing.js only deals with real fonts, - // createFont is simply a wrapper for loadFont/2 - return p.loadFont(name, size); - }; - - /** - * textFont() Sets the current font. - * - * @param {PFont} pfont the PFont to load as current text font - * @param {int|float} size optional font size in pixels - * - * @see #createFont - * @see #loadFont - * @see #PFont - * @see #text - */ - p.textFont = function(pfont, size) { - if (size !== undef) { - // If we're using an SVG glyph font, don't load from cache - if (!pfont.glyph) { - pfont = PFont.get(pfont.name, size); - } - curTextSize = size; - } - curTextFont = pfont; - curFontName = curTextFont.name; - curTextAscent = curTextFont.ascent; - curTextDescent = curTextFont.descent; - curTextLeading = curTextFont.leading; - var curContext = drawing.$ensureContext(); - curContext.font = curTextFont.css; - }; - - /** - * textSize() Sets the current font size in pixels. - * - * @param {int|float} size font size in pixels - * - * @see #textFont - * @see #loadFont - * @see #PFont - * @see #text - */ - p.textSize = function(size) { - if (size !== curTextSize) { - curTextFont = PFont.get(curFontName, size); - curTextSize = size; - // recache metrics - curTextAscent = curTextFont.ascent; - curTextDescent = curTextFont.descent; - curTextLeading = curTextFont.leading; - var curContext = drawing.$ensureContext(); - curContext.font = curTextFont.css; - } - }; - - /** - * textAscent() returns the maximum height a character extends above the baseline of the - * current font at its current size, in pixels. - * - * @returns {float} height of the current font above the baseline, at its current size, in pixels - * - * @see #textDescent - */ - p.textAscent = function() { - return curTextAscent; - }; - - /** - * textDescent() returns the maximum depth a character will protrude below the baseline of - * the current font at its current size, in pixels. - * - * @returns {float} depth of the current font below the baseline, at its current size, in pixels - * - * @see #textAscent - */ - p.textDescent = function() { - return curTextDescent; - }; - - /** - * textLeading() Sets the current font's leading, which is the distance - * from baseline to baseline over consecutive lines, with additional vertical - * spacing taking into account. Usually this value is 1.2 or 1.25 times the - * textsize, but this value can be changed to effect vertically compressed - * or stretched text. - * - * @param {int|float} the desired baseline-to-baseline size in pixels - */ - p.textLeading = function(leading) { - curTextLeading = leading; - }; - - /** - * textAlign() Sets the current alignment for drawing text. - * - * @param {int} ALIGN Horizontal alignment, either LEFT, CENTER, or RIGHT - * @param {int} YALIGN optional vertical alignment, either TOP, BOTTOM, CENTER, or BASELINE - * - * @see #loadFont - * @see #PFont - * @see #text - */ - p.textAlign = function(xalign, yalign) { - horizontalTextAlignment = xalign; - verticalTextAlignment = yalign || PConstants.BASELINE; - }; - - /** - * toP5String converts things with arbitrary data type into - * string values, for text rendering. - * - * @param {any} any object that can be converted into a string - * - * @return {String} the string representation of the input - */ - function toP5String(obj) { - if(obj instanceof String) { - return obj; - } - if(typeof obj === 'number') { - // check if an int - if(obj === (0 | obj)) { - return obj.toString(); - } - return p.nf(obj, 0, 3); - } - if(obj === null || obj === undef) { - return ""; - } - return obj.toString(); - } - - /** - * textWidth() Calculates and returns the width of any character or text string in pixels. - * - * @param {char|String} str char or String to be measured - * - * @return {float} width of char or String in pixels - * - * @see #loadFont - * @see #PFont - * @see #text - * @see #textFont - */ - Drawing2D.prototype.textWidth = function(str) { - var lines = toP5String(str).split(/\r?\n/g), width = 0; - var i, linesCount = lines.length; - - curContext.font = curTextFont.css; - for (i = 0; i < linesCount; ++i) { - width = Math.max(width, curTextFont.measureTextWidth(lines[i])); - } - return width | 0; - }; - - Drawing3D.prototype.textWidth = function(str) { - var lines = toP5String(str).split(/\r?\n/g), width = 0; - var i, linesCount = lines.length; - if (textcanvas === undef) { - textcanvas = document.createElement("canvas"); - } - - var textContext = textcanvas.getContext("2d"); - textContext.font = curTextFont.css; - - for (i = 0; i < linesCount; ++i) { - width = Math.max(width, textContext.measureText(lines[i]).width); - } - return width | 0; - }; - - // A lookup table for characters that can not be referenced by Object - p.glyphLook = function(font, chr) { - try { - switch (chr) { - case "1": - return font.one; - case "2": - return font.two; - case "3": - return font.three; - case "4": - return font.four; - case "5": - return font.five; - case "6": - return font.six; - case "7": - return font.seven; - case "8": - return font.eight; - case "9": - return font.nine; - case "0": - return font.zero; - case " ": - return font.space; - case "$": - return font.dollar; - case "!": - return font.exclam; - case '"': - return font.quotedbl; - case "#": - return font.numbersign; - case "%": - return font.percent; - case "&": - return font.ampersand; - case "'": - return font.quotesingle; - case "(": - return font.parenleft; - case ")": - return font.parenright; - case "*": - return font.asterisk; - case "+": - return font.plus; - case ",": - return font.comma; - case "-": - return font.hyphen; - case ".": - return font.period; - case "/": - return font.slash; - case "_": - return font.underscore; - case ":": - return font.colon; - case ";": - return font.semicolon; - case "<": - return font.less; - case "=": - return font.equal; - case ">": - return font.greater; - case "?": - return font.question; - case "@": - return font.at; - case "[": - return font.bracketleft; - case "\\": - return font.backslash; - case "]": - return font.bracketright; - case "^": - return font.asciicircum; - case "`": - return font.grave; - case "{": - return font.braceleft; - case "|": - return font.bar; - case "}": - return font.braceright; - case "~": - return font.asciitilde; - // If the character is not 'special', access it by object reference - default: - return font[chr]; - } - } catch(e) { - Processing.debug(e); - } - }; - - // Print some text to the Canvas - Drawing2D.prototype.text$line = function(str, x, y, z, align) { - var textWidth = 0, xOffset = 0; - // If the font is a standard Canvas font... - if (!curTextFont.glyph) { - if (str && ("fillText" in curContext)) { - if (isFillDirty) { - curContext.fillStyle = p.color.toString(currentFillColor); - isFillDirty = false; - } - - // horizontal offset/alignment - if(align === PConstants.RIGHT || align === PConstants.CENTER) { - textWidth = curTextFont.measureTextWidth(str); - - if(align === PConstants.RIGHT) { - xOffset = -textWidth; - } else { // if(align === PConstants.CENTER) - xOffset = -textWidth/2; - } - } - - curContext.fillText(str, x+xOffset, y); - } - } else { - // If the font is a Batik SVG font... - var font = p.glyphTable[curFontName]; - saveContext(); - curContext.translate(x, y + curTextSize); - - // horizontal offset/alignment - if(align === PConstants.RIGHT || align === PConstants.CENTER) { - textWidth = font.width(str); - - if(align === PConstants.RIGHT) { - xOffset = -textWidth; - } else { // if(align === PConstants.CENTER) - xOffset = -textWidth/2; - } - } - - var upem = font.units_per_em, - newScale = 1 / upem * curTextSize; - - curContext.scale(newScale, newScale); - - for (var i=0, len=str.length; i < len; i++) { - // Test character against glyph table - try { - p.glyphLook(font, str[i]).draw(); - } catch(e) { - Processing.debug(e); - } - } - restoreContext(); - } - }; - - Drawing3D.prototype.text$line = function(str, x, y, z, align) { - // handle case for 3d text - if (textcanvas === undef) { - textcanvas = document.createElement("canvas"); - } - var oldContext = curContext; - curContext = textcanvas.getContext("2d"); - curContext.font = curTextFont.css; - var textWidth = curTextFont.measureTextWidth(str); - textcanvas.width = textWidth; - textcanvas.height = curTextSize; - curContext = textcanvas.getContext("2d"); // refreshes curContext - curContext.font = curTextFont.css; - curContext.textBaseline="top"; - - // paint on 2D canvas - Drawing2D.prototype.text$line(str,0,0,0,PConstants.LEFT); - - // use it as a texture - var aspect = textcanvas.width/textcanvas.height; - curContext = oldContext; - - curContext.bindTexture(curContext.TEXTURE_2D, textTex); - curContext.texImage2D(curContext.TEXTURE_2D, 0, curContext.RGBA, curContext.RGBA, curContext.UNSIGNED_BYTE, textcanvas); - curContext.texParameteri(curContext.TEXTURE_2D, curContext.TEXTURE_MAG_FILTER, curContext.LINEAR); - curContext.texParameteri(curContext.TEXTURE_2D, curContext.TEXTURE_MIN_FILTER, curContext.LINEAR); - curContext.texParameteri(curContext.TEXTURE_2D, curContext.TEXTURE_WRAP_T, curContext.CLAMP_TO_EDGE); - curContext.texParameteri(curContext.TEXTURE_2D, curContext.TEXTURE_WRAP_S, curContext.CLAMP_TO_EDGE); - // If we don't have a power of two texture, we can't mipmap it. - // curContext.generateMipmap(curContext.TEXTURE_2D); - - // horizontal offset/alignment - var xOffset = 0; - if (align === PConstants.RIGHT) { - xOffset = -textWidth; - } else if(align === PConstants.CENTER) { - xOffset = -textWidth/2; - } - var model = new PMatrix3D(); - var scalefactor = curTextSize * 0.5; - model.translate(x+xOffset-scalefactor/2, y-scalefactor, z); - model.scale(-aspect*scalefactor, -scalefactor, scalefactor); - model.translate(-1, -1, -1); - model.transpose(); - - var view = new PMatrix3D(); - view.scale(1, -1, 1); - view.apply(modelView.array()); - view.transpose(); - - curContext.useProgram(programObject2D); - vertexAttribPointer("vertex2d", programObject2D, "Vertex", 3, textBuffer); - vertexAttribPointer("aTextureCoord2d", programObject2D, "aTextureCoord", 2, textureBuffer); - uniformi("uSampler2d", programObject2D, "uSampler", [0]); - uniformi("picktype2d", programObject2D, "picktype", 1); - uniformMatrix("model2d", programObject2D, "model", false, model.array()); - uniformMatrix("view2d", programObject2D, "view", false, view.array()); - uniformf("color2d", programObject2D, "color", fillStyle); - curContext.bindBuffer(curContext.ELEMENT_ARRAY_BUFFER, indexBuffer); - curContext.drawElements(curContext.TRIANGLES, 6, curContext.UNSIGNED_SHORT, 0); - }; - - - /** - * unbounded text function (z is an optional argument) - */ - function text$4(str, x, y, z) { - var lines, linesCount; - if(str.indexOf('\n') < 0) { - lines = [str]; - linesCount = 1; - } else { - lines = str.split(/\r?\n/g); - linesCount = lines.length; - } - // handle text line-by-line - - var yOffset = 0; - if(verticalTextAlignment === PConstants.TOP) { - yOffset = curTextAscent + curTextDescent; - } else if(verticalTextAlignment === PConstants.CENTER) { - yOffset = curTextAscent/2 - (linesCount-1)*curTextLeading/2; - } else if(verticalTextAlignment === PConstants.BOTTOM) { - yOffset = -(curTextDescent + (linesCount-1)*curTextLeading); - } - - for(var i=0;i height) { - return; - } - - var spaceMark = -1; - var start = 0; - var lineWidth = 0; - var drawCommands = []; - - // run through text, character-by-character - for (var charPos=0, len=str.length; charPos < len; charPos++) - { - var currentChar = str[charPos]; - var spaceChar = (currentChar === " "); - var letterWidth = curTextFont.measureTextWidth(currentChar); - - // if we aren't looking at a newline, and the text still fits, keep processing - if (currentChar !== "\n" && (lineWidth + letterWidth <= width)) { - if (spaceChar) { spaceMark = charPos; } - lineWidth += letterWidth; - } - - // if we're looking at a newline, or the text no longer fits, push the section that fit into the drawcommand list - else - { - if (spaceMark + 1 === start) { - if(charPos>0) { - // Whole line without spaces so far. - spaceMark = charPos; - } else { - // 'fail', because the line can't even fit the first character - return; - } - } - - if (currentChar === "\n") { - drawCommands.push({text:str.substring(start, charPos), width: lineWidth}); - start = charPos + 1; - } else { - // current is not a newline, which means the line doesn't fit in box. push text. - // In Processing 1.5.1, the space is also pushed, so we push up to spaceMark+1, - // rather than up to spaceMark, as was the case for Processing 1.5 and earlier. - drawCommands.push({text:str.substring(start, spaceMark+1), width: lineWidth}); - start = spaceMark + 1; - } - - // newline + return - lineWidth = 0; - charPos = start - 1; - } - } - - // push the remaining text - if (start < len) { - drawCommands.push({text:str.substring(start), width: lineWidth}); - } - - // resolve horizontal alignment - var xOffset = 1, - yOffset = curTextAscent; - if (horizontalTextAlignment === PConstants.CENTER) { - xOffset = width/2; - } else if (horizontalTextAlignment === PConstants.RIGHT) { - xOffset = width; - } - - // resolve vertical alignment - var linesCount = drawCommands.length, - visibleLines = Math.min(linesCount, Math.floor(height/curTextLeading)); - if(verticalTextAlignment === PConstants.TOP) { - yOffset = curTextAscent + curTextDescent; - } else if(verticalTextAlignment === PConstants.CENTER) { - yOffset = (height/2) - curTextLeading * (visibleLines/2 - 1); - } else if(verticalTextAlignment === PConstants.BOTTOM) { - yOffset = curTextDescent + curTextLeading; - } - - var command, - drawCommand, - leading; - for (command = 0; command < linesCount; command++) { - leading = command * curTextLeading; - // stop if not enough space for one more line draw - if (yOffset + leading > height - curTextDescent) { - break; - } - drawCommand = drawCommands[command]; - drawing.text$line(drawCommand.text, x + xOffset, y + yOffset + leading, z, horizontalTextAlignment); - } - } - - /** - * text() Draws text to the screen. - * - * @param {String|char|int|float} data the alphanumeric symbols to be displayed - * @param {int|float} x x-coordinate of text - * @param {int|float} y y-coordinate of text - * @param {int|float} z optional z-coordinate of text - * @param {String} stringdata optional letters to be displayed - * @param {int|float} width optional width of text box - * @param {int|float} height optional height of text box - * - * @see #textAlign - * @see #textMode - * @see #loadFont - * @see #PFont - * @see #textFont - */ - p.text = function() { - if (textMode === PConstants.SHAPE) { - // TODO: requires beginRaw function - return; - } - if (arguments.length === 3) { // for text( str, x, y) - text$4(toP5String(arguments[0]), arguments[1], arguments[2], 0); - } else if (arguments.length === 4) { // for text( str, x, y, z) - text$4(toP5String(arguments[0]), arguments[1], arguments[2], arguments[3]); - } else if (arguments.length === 5) { // for text( str, x, y , width, height) - text$6(toP5String(arguments[0]), arguments[1], arguments[2], arguments[3], arguments[4], 0); - } else if (arguments.length === 6) { // for text( stringdata, x, y , width, height, z) - text$6(toP5String(arguments[0]), arguments[1], arguments[2], arguments[3], arguments[4], arguments[5]); - } - }; - - /** - * Sets the way text draws to the screen. In the default configuration (the MODEL mode), it's possible to rotate, - * scale, and place letters in two and three dimensional space.

Changing to SCREEN mode draws letters - * directly to the front of the window and greatly increases rendering quality and speed when used with the P2D and - * P3D renderers. textMode(SCREEN) with OPENGL and JAVA2D (the default) renderers will generally be slower, though - * pixel accurate with P2D and P3D. With textMode(SCREEN), the letters draw at the actual size of the font (in pixels) - * and therefore calls to textSize() will not affect the size of the letters. To create a font at the size you - * desire, use the "Create font..." option in the Tools menu, or use the createFont() function. When using textMode(SCREEN), - * any z-coordinate passed to a text() command will be ignored, because your computer screen is...flat! - * - * @param {int} MODE Either MODEL, SCREEN or SHAPE (not yet supported) - * - * @see loadFont - * @see PFont - * @see text - * @see textFont - * @see createFont - */ - p.textMode = function(mode){ - textMode = mode; - }; - - // Load Batik SVG Fonts and parse to pre-def objects for quick rendering - p.loadGlyphs = function(url) { - var x, y, cx, cy, nx, ny, d, a, lastCom, lenC, horiz_adv_x, getXY = '[0-9\\-]+', path; - - // Return arrays of SVG commands and coords - // get this to use p.matchAll() - will need to work around the lack of null return - var regex = function(needle, hay) { - var i = 0, - results = [], - latest, regexp = new RegExp(needle, "g"); - latest = results[i] = regexp.exec(hay); - while (latest) { - i++; - latest = results[i] = regexp.exec(hay); - } - return results; - }; - - var buildPath = function(d) { - var c = regex("[A-Za-z][0-9\\- ]+|Z", d); - var beforePathDraw = function() { - saveContext(); - return drawing.$ensureContext(); - }; - var afterPathDraw = function() { - executeContextFill(); - executeContextStroke(); - restoreContext(); - }; - - // Begin storing path object - path = "return {draw:function(){var curContext=beforePathDraw();curContext.beginPath();"; - - x = 0; - y = 0; - cx = 0; - cy = 0; - nx = 0; - ny = 0; - d = 0; - a = 0; - lastCom = ""; - lenC = c.length - 1; - - // Loop through SVG commands translating to canvas eqivs functions in path object - for (var j = 0; j < lenC; j++) { - var com = c[j][0], xy = regex(getXY, com); - - switch (com[0]) { - case "M": - //curContext.moveTo(x,-y); - x = parseFloat(xy[0][0]); - y = parseFloat(xy[1][0]); - path += "curContext.moveTo(" + x + "," + (-y) + ");"; - break; - - case "L": - //curContext.lineTo(x,-y); - x = parseFloat(xy[0][0]); - y = parseFloat(xy[1][0]); - path += "curContext.lineTo(" + x + "," + (-y) + ");"; - break; - - case "H": - //curContext.lineTo(x,-y) - x = parseFloat(xy[0][0]); - path += "curContext.lineTo(" + x + "," + (-y) + ");"; - break; - - case "V": - //curContext.lineTo(x,-y); - y = parseFloat(xy[0][0]); - path += "curContext.lineTo(" + x + "," + (-y) + ");"; - break; - - case "T": - //curContext.quadraticCurveTo(cx,-cy,nx,-ny); - nx = parseFloat(xy[0][0]); - ny = parseFloat(xy[1][0]); - - if (lastCom === "Q" || lastCom === "T") { - d = Math.sqrt(Math.pow(x - cx, 2) + Math.pow(cy - y, 2)); - a = Math.PI + Math.atan2(cx - x, cy - y); - cx = x + (Math.sin(a) * (d)); - cy = y + (Math.cos(a) * (d)); - } else { - cx = x; - cy = y; - } - - path += "curContext.quadraticCurveTo(" + cx + "," + (-cy) + "," + nx + "," + (-ny) + ");"; - x = nx; - y = ny; - break; - - case "Q": - //curContext.quadraticCurveTo(cx,-cy,nx,-ny); - cx = parseFloat(xy[0][0]); - cy = parseFloat(xy[1][0]); - nx = parseFloat(xy[2][0]); - ny = parseFloat(xy[3][0]); - path += "curContext.quadraticCurveTo(" + cx + "," + (-cy) + "," + nx + "," + (-ny) + ");"; - x = nx; - y = ny; - break; - - case "Z": - //curContext.closePath(); - path += "curContext.closePath();"; - break; - } - lastCom = com[0]; - } - - path += "afterPathDraw();"; - path += "curContext.translate(" + horiz_adv_x + ",0);"; - path += "}}"; - - return ((new Function("beforePathDraw", "afterPathDraw", path))(beforePathDraw, afterPathDraw)); - }; - - // Parse SVG font-file into block of Canvas commands - var parseSVGFont = function(svg) { - // Store font attributes - var font = svg.getElementsByTagName("font"); - p.glyphTable[url].horiz_adv_x = font[0].getAttribute("horiz-adv-x"); - - var font_face = svg.getElementsByTagName("font-face")[0]; - p.glyphTable[url].units_per_em = parseFloat(font_face.getAttribute("units-per-em")); - p.glyphTable[url].ascent = parseFloat(font_face.getAttribute("ascent")); - p.glyphTable[url].descent = parseFloat(font_face.getAttribute("descent")); - - var glyph = svg.getElementsByTagName("glyph"), - len = glyph.length; - - // Loop through each glyph in the SVG - for (var i = 0; i < len; i++) { - // Store attributes for this glyph - var unicode = glyph[i].getAttribute("unicode"); - var name = glyph[i].getAttribute("glyph-name"); - horiz_adv_x = glyph[i].getAttribute("horiz-adv-x"); - if (horiz_adv_x === null) { - horiz_adv_x = p.glyphTable[url].horiz_adv_x; - } - d = glyph[i].getAttribute("d"); - // Split path commands in glpyh - if (d !== undef) { - path = buildPath(d); - // Store glyph data to table object - p.glyphTable[url][name] = { - name: name, - unicode: unicode, - horiz_adv_x: horiz_adv_x, - draw: path.draw - }; - } - } // finished adding glyphs to table - }; - - // Load and parse Batik SVG font as XML into a Processing Glyph object - var loadXML = function() { - var xmlDoc; - - try { - xmlDoc = document.implementation.createDocument("", "", null); - } - catch(e_fx_op) { - Processing.debug(e_fx_op.message); - return; - } - - try { - xmlDoc.async = false; - xmlDoc.load(url); - parseSVGFont(xmlDoc.getElementsByTagName("svg")[0]); - } - catch(e_sf_ch) { - // Google Chrome, Safari etc. - Processing.debug(e_sf_ch); - try { - var xmlhttp = new window.XMLHttpRequest(); - xmlhttp.open("GET", url, false); - xmlhttp.send(null); - parseSVGFont(xmlhttp.responseXML.documentElement); - } - catch(e) { - Processing.debug(e_sf_ch); - } - } - }; - - // Create a new object in glyphTable to store this font - p.glyphTable[url] = {}; - - // Begin loading the Batik SVG font... - loadXML(url); - - // Return the loaded font for attribute grabbing - return p.glyphTable[url]; - }; - - /** - * Gets the sketch parameter value. The parameter can be defined as the canvas attribute with - * the "data-processing-" prefix or provided in the pjs directive (e.g. param-test="52"). - * The function tries the canvas attributes, then the pjs directive content. - * - * @param {String} name The name of the param to read. - * - * @returns {String} The parameter value, or null if parameter is not defined. - */ - p.param = function(name) { - // trying attribute that was specified in CANVAS - var attributeName = "data-processing-" + name; - if (curElement.hasAttribute(attributeName)) { - return curElement.getAttribute(attributeName); - } - // trying child PARAM elements of the CANVAS - for (var i = 0, len = curElement.childNodes.length; i < len; ++i) { - var item = curElement.childNodes.item(i); - if (item.nodeType !== 1 || item.tagName.toLowerCase() !== "param") { - continue; - } - if (item.getAttribute("name") === name) { - return item.getAttribute("value"); - } - } - // fallback to default params - if (curSketch.params.hasOwnProperty(name)) { - return curSketch.params[name]; - } - return null; - }; - - //////////////////////////////////////////////////////////////////////////// - // 2D/3D methods wiring utils - //////////////////////////////////////////////////////////////////////////// - function wireDimensionalFunctions(mode) { - // Drawing2D/Drawing3D - if (mode === '3D') { - drawing = new Drawing3D(); - } else if (mode === '2D') { - drawing = new Drawing2D(); - } else { - drawing = new DrawingPre(); - } - - // Wire up functions (Use DrawingPre properties names) - for (var i in DrawingPre.prototype) { - if (DrawingPre.prototype.hasOwnProperty(i) && i.indexOf("$") < 0) { - p[i] = drawing[i]; - } - } - - // Run initialization - drawing.$init(); - } - - function createDrawingPreFunction(name) { - return function() { - wireDimensionalFunctions("2D"); - return drawing[name].apply(this, arguments); - }; - } - DrawingPre.prototype.translate = createDrawingPreFunction("translate"); - DrawingPre.prototype.scale = createDrawingPreFunction("scale"); - DrawingPre.prototype.pushMatrix = createDrawingPreFunction("pushMatrix"); - DrawingPre.prototype.popMatrix = createDrawingPreFunction("popMatrix"); - DrawingPre.prototype.resetMatrix = createDrawingPreFunction("resetMatrix"); - DrawingPre.prototype.applyMatrix = createDrawingPreFunction("applyMatrix"); - DrawingPre.prototype.rotate = createDrawingPreFunction("rotate"); - DrawingPre.prototype.rotateZ = createDrawingPreFunction("rotateZ"); - DrawingPre.prototype.redraw = createDrawingPreFunction("redraw"); - DrawingPre.prototype.toImageData = createDrawingPreFunction("toImageData"); - DrawingPre.prototype.ambientLight = createDrawingPreFunction("ambientLight"); - DrawingPre.prototype.directionalLight = createDrawingPreFunction("directionalLight"); - DrawingPre.prototype.lightFalloff = createDrawingPreFunction("lightFalloff"); - DrawingPre.prototype.lightSpecular = createDrawingPreFunction("lightSpecular"); - DrawingPre.prototype.pointLight = createDrawingPreFunction("pointLight"); - DrawingPre.prototype.noLights = createDrawingPreFunction("noLights"); - DrawingPre.prototype.spotLight = createDrawingPreFunction("spotLight"); - DrawingPre.prototype.beginCamera = createDrawingPreFunction("beginCamera"); - DrawingPre.prototype.endCamera = createDrawingPreFunction("endCamera"); - DrawingPre.prototype.frustum = createDrawingPreFunction("frustum"); - DrawingPre.prototype.box = createDrawingPreFunction("box"); - DrawingPre.prototype.sphere = createDrawingPreFunction("sphere"); - DrawingPre.prototype.ambient = createDrawingPreFunction("ambient"); - DrawingPre.prototype.emissive = createDrawingPreFunction("emissive"); - DrawingPre.prototype.shininess = createDrawingPreFunction("shininess"); - DrawingPre.prototype.specular = createDrawingPreFunction("specular"); - DrawingPre.prototype.fill = createDrawingPreFunction("fill"); - DrawingPre.prototype.stroke = createDrawingPreFunction("stroke"); - DrawingPre.prototype.strokeWeight = createDrawingPreFunction("strokeWeight"); - DrawingPre.prototype.smooth = createDrawingPreFunction("smooth"); - DrawingPre.prototype.noSmooth = createDrawingPreFunction("noSmooth"); - DrawingPre.prototype.point = createDrawingPreFunction("point"); - DrawingPre.prototype.vertex = createDrawingPreFunction("vertex"); - DrawingPre.prototype.endShape = createDrawingPreFunction("endShape"); - DrawingPre.prototype.bezierVertex = createDrawingPreFunction("bezierVertex"); - DrawingPre.prototype.curveVertex = createDrawingPreFunction("curveVertex"); - DrawingPre.prototype.curve = createDrawingPreFunction("curve"); - DrawingPre.prototype.line = createDrawingPreFunction("line"); - DrawingPre.prototype.bezier = createDrawingPreFunction("bezier"); - DrawingPre.prototype.rect = createDrawingPreFunction("rect"); - DrawingPre.prototype.ellipse = createDrawingPreFunction("ellipse"); - DrawingPre.prototype.background = createDrawingPreFunction("background"); - DrawingPre.prototype.image = createDrawingPreFunction("image"); - DrawingPre.prototype.textWidth = createDrawingPreFunction("textWidth"); - DrawingPre.prototype.text$line = createDrawingPreFunction("text$line"); - DrawingPre.prototype.$ensureContext = createDrawingPreFunction("$ensureContext"); - DrawingPre.prototype.$newPMatrix = createDrawingPreFunction("$newPMatrix"); - - DrawingPre.prototype.size = function(aWidth, aHeight, aMode) { - wireDimensionalFunctions(aMode === PConstants.WEBGL ? "3D" : "2D"); - p.size(aWidth, aHeight, aMode); - }; - - DrawingPre.prototype.$init = nop; - - Drawing2D.prototype.$init = function() { - // Setup default 2d canvas context. - // Moving this here removes the number of times we need to check the 3D variable - p.size(p.width, p.height); - - curContext.lineCap = 'round'; - - // Set default stroke and fill color - p.noSmooth(); - p.disableContextMenu(); - }; - Drawing3D.prototype.$init = function() { - // For ref/perf test compatibility until those are fixed - p.use3DContext = true; - }; - - DrawingShared.prototype.$ensureContext = function() { - return curContext; - }; - - ////////////////////////////////////////////////////////////////////////// - // Touch and Mouse event handling - ////////////////////////////////////////////////////////////////////////// - - function calculateOffset(curElement, event) { - var element = curElement, - offsetX = 0, - offsetY = 0; - - p.pmouseX = p.mouseX; - p.pmouseY = p.mouseY; - - // Find element offset - if (element.offsetParent) { - do { - offsetX += element.offsetLeft; - offsetY += element.offsetTop; - } while (!!(element = element.offsetParent)); - } - - // Find Scroll offset - element = curElement; - do { - offsetX -= element.scrollLeft || 0; - offsetY -= element.scrollTop || 0; - } while (!!(element = element.parentNode)); - - // Add padding and border style widths to offset - offsetX += stylePaddingLeft; - offsetY += stylePaddingTop; - - offsetX += styleBorderLeft; - offsetY += styleBorderTop; - - // Take into account any scrolling done - offsetX += window.pageXOffset; - offsetY += window.pageYOffset; - - return {'X':offsetX,'Y':offsetY}; - } - - function updateMousePosition(curElement, event) { - var offset = calculateOffset(curElement, event); - - // Dropping support for IE clientX and clientY, switching to pageX and pageY so we don't have to calculate scroll offset. - // Removed in ticket #184. See rev: 2f106d1c7017fed92d045ba918db47d28e5c16f4 - p.mouseX = event.pageX - offset.X; - p.mouseY = event.pageY - offset.Y; - } - - // Return a TouchEvent with canvas-specific x/y co-ordinates - function addTouchEventOffset(t) { - var offset = calculateOffset(t.changedTouches[0].target, t.changedTouches[0]), - i; - - for (i = 0; i < t.touches.length; i++) { - var touch = t.touches[i]; - touch.offsetX = touch.pageX - offset.X; - touch.offsetY = touch.pageY - offset.Y; - } - for (i = 0; i < t.targetTouches.length; i++) { - var targetTouch = t.targetTouches[i]; - targetTouch.offsetX = targetTouch.pageX - offset.X; - targetTouch.offsetY = targetTouch.pageY - offset.Y; - } - for (i = 0; i < t.changedTouches.length; i++) { - var changedTouch = t.changedTouches[i]; - changedTouch.offsetX = changedTouch.pageX - offset.X; - changedTouch.offsetY = changedTouch.pageY - offset.Y; - } - - return t; - } - - attachEventHandler(curElement, "touchstart", function (t) { - // Removes unwanted behaviour of the canvas when touching canvas - curElement.setAttribute("style","-webkit-user-select: none"); - curElement.setAttribute("onclick","void(0)"); - curElement.setAttribute("style","-webkit-tap-highlight-color:rgba(0,0,0,0)"); - // Loop though eventHandlers and remove mouse listeners - for (var i=0, ehl=eventHandlers.length; i 'while"B1""A2"' - // parentheses() = B, brackets[] = C and braces{} = A - function splitToAtoms(code) { - var atoms = []; - var items = code.split(/([\{\[\(\)\]\}])/); - var result = items[0]; - - var stack = []; - for(var i=1; i < items.length; i += 2) { - var item = items[i]; - if(item === '[' || item === '{' || item === '(') { - stack.push(result); result = item; - } else if(item === ']' || item === '}' || item === ')') { - var kind = item === '}' ? 'A' : item === ')' ? 'B' : 'C'; - var index = atoms.length; atoms.push(result + item); - result = stack.pop() + '"' + kind + (index + 1) + '"'; - } - result += items[i + 1]; - } - atoms.unshift(result); - return atoms; - } - - // replaces strings and regexs keyed by index with an array of strings - function injectStrings(code, strings) { - return code.replace(/'(\d+)'/g, function(all, index) { - var val = strings[index]; - if(val.charAt(0) === "/") { - return val; - } - return (/^'((?:[^'\\\n])|(?:\\.[0-9A-Fa-f]*))'$/).test(val) ? "(new $p.Character(" + val + "))" : val; - }); - } - - // trims off leading and trailing spaces - // returns an object. object.left, object.middle, object.right, object.untrim - function trimSpaces(string) { - var m1 = /^\s*/.exec(string), result; - if(m1[0].length === string.length) { - result = {left: m1[0], middle: "", right: ""}; - } else { - var m2 = /\s*$/.exec(string); - result = {left: m1[0], middle: string.substring(m1[0].length, m2.index), right: m2[0]}; - } - result.untrim = function(t) { return this.left + t + this.right; }; - return result; - } - - // simple trim of leading and trailing spaces - function trim(string) { - return string.replace(/^\s+/,'').replace(/\s+$/,''); - } - - function appendToLookupTable(table, array) { - for(var i=0,l=array.length;i([=]?)/g, replaceFunc); - } while (genericsWereRemoved); - - var atoms = splitToAtoms(codeWoGenerics); - var replaceContext; - var declaredClasses = {}, currentClassId, classIdSeed = 0; - - function addAtom(text, type) { - var lastIndex = atoms.length; - atoms.push(text); - return '"' + type + lastIndex + '"'; - } - - function generateClassId() { - return "class" + (++classIdSeed); - } - - function appendClass(class_, classId, scopeId) { - class_.classId = classId; - class_.scopeId = scopeId; - declaredClasses[classId] = class_; - } - - // functions defined below - var transformClassBody, transformInterfaceBody, transformStatementsBlock, transformStatements, transformMain, transformExpression; - - var classesRegex = /\b((?:(?:public|private|final|protected|static|abstract)\s+)*)(class|interface)\s+([A-Za-z_$][\w$]*\b)(\s+extends\s+[A-Za-z_$][\w$]*\b(?:\s*\.\s*[A-Za-z_$][\w$]*\b)*(?:\s*,\s*[A-Za-z_$][\w$]*\b(?:\s*\.\s*[A-Za-z_$][\w$]*\b)*\b)*)?(\s+implements\s+[A-Za-z_$][\w$]*\b(?:\s*\.\s*[A-Za-z_$][\w$]*\b)*(?:\s*,\s*[A-Za-z_$][\w$]*\b(?:\s*\.\s*[A-Za-z_$][\w$]*\b)*\b)*)?\s*("A\d+")/g; - var methodsRegex = /\b((?:(?:public|private|final|protected|static|abstract|synchronized)\s+)*)((?!(?:else|new|return|throw|function|public|private|protected)\b)[A-Za-z_$][\w$]*\b(?:\s*\.\s*[A-Za-z_$][\w$]*\b)*(?:\s*"C\d+")*)\s*([A-Za-z_$][\w$]*\b)\s*("B\d+")(\s*throws\s+[A-Za-z_$][\w$]*\b(?:\s*\.\s*[A-Za-z_$][\w$]*\b)*(?:\s*,\s*[A-Za-z_$][\w$]*\b(?:\s*\.\s*[A-Za-z_$][\w$]*\b)*)*)?\s*("A\d+"|;)/g; - var fieldTest = /^((?:(?:public|private|final|protected|static)\s+)*)((?!(?:else|new|return|throw)\b)[A-Za-z_$][\w$]*\b(?:\s*\.\s*[A-Za-z_$][\w$]*\b)*(?:\s*"C\d+")*)\s*([A-Za-z_$][\w$]*\b)\s*(?:"C\d+"\s*)*([=,]|$)/; - var cstrsRegex = /\b((?:(?:public|private|final|protected|static|abstract)\s+)*)((?!(?:new|return|throw)\b)[A-Za-z_$][\w$]*\b)\s*("B\d+")(\s*throws\s+[A-Za-z_$][\w$]*\b(?:\s*\.\s*[A-Za-z_$][\w$]*\b)*(?:\s*,\s*[A-Za-z_$][\w$]*\b(?:\s*\.\s*[A-Za-z_$][\w$]*\b)*)*)?\s*("A\d+")/g; - var attrAndTypeRegex = /^((?:(?:public|private|final|protected|static)\s+)*)((?!(?:new|return|throw)\b)[A-Za-z_$][\w$]*\b(?:\s*\.\s*[A-Za-z_$][\w$]*\b)*(?:\s*"C\d+")*)\s*/; - var functionsRegex = /\bfunction(?:\s+([A-Za-z_$][\w$]*))?\s*("B\d+")\s*("A\d+")/g; - - // This converts classes, methods and functions into atoms, and adds them to the atoms array. - // classes = E, methods = D and functions = H - function extractClassesAndMethods(code) { - var s = code; - s = s.replace(classesRegex, function(all) { - return addAtom(all, 'E'); - }); - s = s.replace(methodsRegex, function(all) { - return addAtom(all, 'D'); - }); - s = s.replace(functionsRegex, function(all) { - return addAtom(all, 'H'); - }); - return s; - } - - // This converts constructors into atoms, and adds them to the atoms array. - // constructors = G - function extractConstructors(code, className) { - var result = code.replace(cstrsRegex, function(all, attr, name, params, throws_, body) { - if(name !== className) { - return all; - } - return addAtom(all, 'G'); - }); - return result; - } - - // AstParam contains the name of a parameter inside a function declaration - function AstParam(name) { - this.name = name; - } - AstParam.prototype.toString = function() { - return this.name; - }; - // AstParams contains an array of AstParam objects - function AstParams(params) { - this.params = params; - } - AstParams.prototype.getNames = function() { - var names = []; - for(var i=0,l=this.params.length;i {...} - s = s.replace(/\bnew\s+([A-Za-z_$][\w$]*\b(?:\s*\.\s*[A-Za-z_$][\w$]*\b)*)(?:\s*"C\d+")+\s*("A\d+")/g, function(all, type, init) { - return init; - }); - // new Runnable() {...} --> "F???" - s = s.replace(/\bnew\s+([A-Za-z_$][\w$]*\b(?:\s*\.\s*[A-Za-z_$][\w$]*\b)*)(?:\s*"B\d+")\s*("A\d+")/g, function(all, type, init) { - return addAtom(all, 'F'); - }); - // function(...) { } --> "H???" - s = s.replace(functionsRegex, function(all) { - return addAtom(all, 'H'); - }); - // new type[?] --> createJavaArray('type', [?]) - s = s.replace(/\bnew\s+([A-Za-z_$][\w$]*\b(?:\s*\.\s*[A-Za-z_$][\w$]*\b)*)\s*("C\d+"(?:\s*"C\d+")*)/g, function(all, type, index) { - var args = index.replace(/"C(\d+)"/g, function(all, j) { return atoms[j]; }) - .replace(/\[\s*\]/g, "[null]").replace(/\s*\]\s*\[\s*/g, ", "); - var arrayInitializer = "{" + args.substring(1, args.length - 1) + "}"; - var createArrayArgs = "('" + type + "', " + addAtom(arrayInitializer, 'A') + ")"; - return '$p.createJavaArray' + addAtom(createArrayArgs, 'B'); - }); - // .length() --> .length - s = s.replace(/(\.\s*length)\s*"B\d+"/g, "$1"); - // #000000 --> 0x000000 - s = s.replace(/#([0-9A-Fa-f]{6})\b/g, function(all, digits) { - return "0xFF" + digits; - }); - // delete (type)???, except (int)??? - s = s.replace(/"B(\d+)"(\s*(?:[\w$']|"B))/g, function(all, index, next) { - var atom = atoms[index]; - if(!/^\(\s*[A-Za-z_$][\w$]*\b(?:\s*\.\s*[A-Za-z_$][\w$]*\b)*\s*(?:"C\d+"\s*)*\)$/.test(atom)) { - return all; - } - if(/^\(\s*int\s*\)$/.test(atom)) { - return "(int)" + next; - } - var indexParts = atom.split(/"C(\d+)"/g); - if(indexParts.length > 1) { - // even items contains atom numbers, can check only first - if(! /^\[\s*\]$/.test(atoms[indexParts[1]])) { - return all; // fallback - not a cast - } - } - return "" + next; - }); - // (int)??? -> __int_cast(???) - s = s.replace(/\(int\)([^,\]\)\}\?\:\*\+\-\/\^\|\%\&\~<\>\=]+)/g, function(all, arg) { - var trimmed = trimSpaces(arg); - return trimmed.untrim("__int_cast(" + trimmed.middle + ")"); - }); - // super() -> $superCstr(), super. -> $super.; - s = s.replace(/\bsuper(\s*"B\d+")/g, "$$superCstr$1").replace(/\bsuper(\s*\.)/g, "$$super$1"); - // 000.43->0.43 and 0010f->10, but not 0010 - s = s.replace(/\b0+((\d*)(?:\.[\d*])?(?:[eE][\-\+]?\d+)?[fF]?)\b/, function(all, numberWo0, intPart) { - if( numberWo0 === intPart) { - return all; - } - return intPart === "" ? "0" + numberWo0 : numberWo0; - }); - // 3.0f -> 3.0 - s = s.replace(/\b(\.?\d+\.?)[fF]\b/g, "$1"); - // Weird (?) parsing errors with % - s = s.replace(/([^\s])%([^=\s])/g, "$1 % $2"); - // Since frameRate() and frameRate are different things, - // we need to differentiate them somehow. So when we parse - // the Processing.js source, replace frameRate so it isn't - // confused with frameRate(), as well as keyPressed and mousePressed - s = s.replace(/\b(frameRate|keyPressed|mousePressed)\b(?!\s*"B)/g, "__$1"); - // "boolean", "byte", "int", etc. => "parseBoolean", "parseByte", "parseInt", etc. - s = s.replace(/\b(boolean|byte|char|float|int)\s*"B/g, function(all, name) { - return "parse" + name.substring(0, 1).toUpperCase() + name.substring(1) + "\"B"; - }); - // "pixels" replacements: - // pixels[i] = c => pixels.setPixel(i,c) | pixels[i] => pixels.getPixel(i) - // pixels.length => pixels.getLength() - // pixels = ar => pixels.set(ar) | pixels => pixels.toArray() - s = s.replace(/\bpixels\b\s*(("C(\d+)")|\.length)?(\s*=(?!=)([^,\]\)\}]+))?/g, - function(all, indexOrLength, index, atomIndex, equalsPart, rightSide) { - if(index) { - var atom = atoms[atomIndex]; - if(equalsPart) { - return "pixels.setPixel" + addAtom("(" +atom.substring(1, atom.length - 1) + - "," + rightSide + ")", 'B'); - } - return "pixels.getPixel" + addAtom("(" + atom.substring(1, atom.length - 1) + - ")", 'B'); - } - if(indexOrLength) { - // length - return "pixels.getLength" + addAtom("()", 'B'); - } - if(equalsPart) { - return "pixels.set" + addAtom("(" + rightSide + ")", 'B'); - } - return "pixels.toArray" + addAtom("()", 'B'); - }); - // Java method replacements for: replace, replaceAll, replaceFirst, equals, hashCode, etc. - // xxx.replace(yyy) -> __replace(xxx, yyy) - // "xx".replace(yyy) -> __replace("xx", yyy) - var repeatJavaReplacement; - function replacePrototypeMethods(all, subject, method, atomIndex) { - var atom = atoms[atomIndex]; - repeatJavaReplacement = true; - var trimmed = trimSpaces(atom.substring(1, atom.length - 1)); - return "__" + method + ( trimmed.middle === "" ? addAtom("(" + subject.replace(/\.\s*$/, "") + ")", 'B') : - addAtom("(" + subject.replace(/\.\s*$/, "") + "," + trimmed.middle + ")", 'B') ); - } - do { - repeatJavaReplacement = false; - s = s.replace(/((?:'\d+'|\b[A-Za-z_$][\w$]*\s*(?:"[BC]\d+")*)\s*\.\s*(?:[A-Za-z_$][\w$]*\s*(?:"[BC]\d+"\s*)*\.\s*)*)(replace|replaceAll|replaceFirst|contains|equals|equalsIgnoreCase|hashCode|toCharArray|printStackTrace|split|startsWith|endsWith|codePointAt)\s*"B(\d+)"/g, - replacePrototypeMethods); - } while (repeatJavaReplacement); - // xxx instanceof yyy -> __instanceof(xxx, yyy) - function replaceInstanceof(all, subject, type) { - repeatJavaReplacement = true; - return "__instanceof" + addAtom("(" + subject + ", " + type + ")", 'B'); - } - do { - repeatJavaReplacement = false; - s = s.replace(/((?:'\d+'|\b[A-Za-z_$][\w$]*\s*(?:"[BC]\d+")*)\s*(?:\.\s*[A-Za-z_$][\w$]*\s*(?:"[BC]\d+"\s*)*)*)instanceof\s+([A-Za-z_$][\w$]*\s*(?:\.\s*[A-Za-z_$][\w$]*)*)/g, - replaceInstanceof); - } while (repeatJavaReplacement); - // this() -> $constr() - s = s.replace(/\bthis(\s*"B\d+")/g, "$$constr$1"); - - return s; - } - - function AstInlineClass(baseInterfaceName, body) { - this.baseInterfaceName = baseInterfaceName; - this.body = body; - body.owner = this; - } - AstInlineClass.prototype.toString = function() { - return "new (" + this.body + ")"; - }; - - function transformInlineClass(class_) { - var m = new RegExp(/\bnew\s*([A-Za-z_$][\w$]*\s*(?:\.\s*[A-Za-z_$][\w$]*)*)\s*"B\d+"\s*"A(\d+)"/).exec(class_); - var oldClassId = currentClassId, newClassId = generateClassId(); - currentClassId = newClassId; - var uniqueClassName = m[1] + "$" + newClassId; - var inlineClass = new AstInlineClass(uniqueClassName, - transformClassBody(atoms[m[2]], uniqueClassName, "", "implements " + m[1])); - appendClass(inlineClass, newClassId, oldClassId); - currentClassId = oldClassId; - return inlineClass; - } - - function AstFunction(name, params, body) { - this.name = name; - this.params = params; - this.body = body; - } - AstFunction.prototype.toString = function() { - var oldContext = replaceContext; - // saving "this." and parameters - var names = appendToLookupTable({"this":null}, this.params.getNames()); - replaceContext = function (subject) { - return names.hasOwnProperty(subject.name) ? subject.name : oldContext(subject); - }; - var result = "function"; - if(this.name) { - result += " " + this.name; - } - result += this.params + " " + this.body; - replaceContext = oldContext; - return result; - }; - - function transformFunction(class_) { - var m = new RegExp(/\b([A-Za-z_$][\w$]*)\s*"B(\d+)"\s*"A(\d+)"/).exec(class_); - return new AstFunction( m[1] !== "function" ? m[1] : null, - transformParams(atoms[m[2]]), transformStatementsBlock(atoms[m[3]])); - } - - function AstInlineObject(members) { - this.members = members; - } - AstInlineObject.prototype.toString = function() { - var oldContext = replaceContext; - replaceContext = function (subject) { - return subject.name === "this" ? "this" : oldContext(subject); // saving "this." - }; - var result = ""; - for(var i=0,l=this.members.length;i= 0; - var definitions = statement.substring(attrAndType[0].length).split(/,\s*/g); - var defaultTypeValue = getDefaultValueForType(attrAndType[2]); - for(var i=0; i < definitions.length; ++i) { - definitions[i] = transformVarDefinition(definitions[i], defaultTypeValue); - } - return new AstClassField(definitions, attrAndType[2], isStatic); - } - - function AstConstructor(params, body) { - this.params = params; - this.body = body; - } - AstConstructor.prototype.toString = function() { - var paramNames = appendToLookupTable({}, this.params.getNames()); - var oldContext = replaceContext; - replaceContext = function (subject) { - return paramNames.hasOwnProperty(subject.name) ? subject.name : oldContext(subject); - }; - var prefix = "function $constr_" + this.params.params.length + this.params.toString(); - var body = this.body.toString(); - if(!/\$(superCstr|constr)\b/.test(body)) { - body = "{\n$superCstr();\n" + body.substring(1); - } - replaceContext = oldContext; - return prefix + body + "\n"; - }; - - function transformConstructor(cstr) { - var m = new RegExp(/"B(\d+)"\s*"A(\d+)"/).exec(cstr); - var params = transformParams(atoms[m[1]]); - - return new AstConstructor(params, transformStatementsBlock(atoms[m[2]])); - } - - function AstInterfaceBody(name, interfacesNames, methodsNames, fields, innerClasses, misc) { - var i,l; - this.name = name; - this.interfacesNames = interfacesNames; - this.methodsNames = methodsNames; - this.fields = fields; - this.innerClasses = innerClasses; - this.misc = misc; - for(i=0,l=fields.length; i 0) { - result += this.functions.join('\n') + '\n'; - } - - sortByWeight(this.innerClasses); - for (i = 0, l = this.innerClasses.length; i < l; ++i) { - var innerClass = this.innerClasses[i]; - if (innerClass.isStatic) { - staticDefinitions += className + "." + innerClass.name + " = " + innerClass + ";\n"; - result += selfId + "." + innerClass.name + " = " + className + "." + innerClass.name + ";\n"; - } else { - result += selfId + "." + innerClass.name + " = " + innerClass + ";\n"; - } - } - - for (i = 0, l = this.fields.length; i < l; ++i) { - var field = this.fields[i]; - if (field.isStatic) { - staticDefinitions += className + "." + field.definitions.join(";\n" + className + ".") + ";\n"; - for (j = 0, m = field.definitions.length; j < m; ++j) { - var fieldName = field.definitions[j].name, staticName = className + "." + fieldName; - result += "$p.defineProperty(" + selfId + ", '" + fieldName + "', {" + - "get: function(){return " + staticName + "}, " + - "set: function(val){" + staticName + " = val}});\n"; - } - } else { - result += selfId + "." + field.definitions.join(";\n" + selfId + ".") + ";\n"; - } - } - var methodOverloads = {}; - for (i = 0, l = this.methods.length; i < l; ++i) { - var method = this.methods[i]; - var overload = methodOverloads[method.name]; - var methodId = method.name + "$" + method.params.params.length; - if (overload) { - ++overload; - methodId += "_" + overload; - } else { - overload = 1; - } - method.methodId = methodId; - methodOverloads[method.name] = overload; - if (method.isStatic) { - staticDefinitions += method; - staticDefinitions += "$p.addMethod(" + className + ", '" + method.name + "', " + methodId + ");\n"; - result += "$p.addMethod(" + selfId + ", '" + method.name + "', " + methodId + ");\n"; - } else { - result += method; - result += "$p.addMethod(" + selfId + ", '" + method.name + "', " + methodId + ");\n"; - } - } - result += trim(this.misc.tail); - - if (this.cstrs.length > 0) { - result += this.cstrs.join('\n') + '\n'; - } - - result += "function $constr() {\n"; - var cstrsIfs = []; - for (i = 0, l = this.cstrs.length; i < l; ++i) { - var paramsLength = this.cstrs[i].params.params.length; - cstrsIfs.push("if(arguments.length === " + paramsLength + ") { " + - "$constr_" + paramsLength + ".apply(" + selfId + ", arguments); }"); - } - if(cstrsIfs.length > 0) { - result += cstrsIfs.join(" else ") + " else "; - } - // ??? add check if length is 0, otherwise fail - result += "$superCstr();\n}\n"; - result += "$constr.apply(null, arguments);\n"; - - replaceContext = oldContext; - return "(function() {\n" + - "function " + className + "() {\n" + result + "}\n" + - staticDefinitions + - metadata + - "return " + className + ";\n" + - "})()"; - }; - - transformClassBody = function(body, name, baseName, interfaces) { - var declarations = body.substring(1, body.length - 1); - declarations = extractClassesAndMethods(declarations); - declarations = extractConstructors(declarations, name); - var methods = [], classes = [], cstrs = [], functions = []; - declarations = declarations.replace(/"([DEGH])(\d+)"/g, function(all, type, index) { - if(type === 'D') { methods.push(index); } - else if(type === 'E') { classes.push(index); } - else if(type === 'H') { functions.push(index); } - else { cstrs.push(index); } - return ""; - }); - var fields = declarations.replace(/^(?:\s*;)+/, "").split(/;(?:\s*;)*/g); - var baseClassName, interfacesNames; - var i; - - if(baseName !== undef) { - baseClassName = baseName.replace(/^\s*extends\s+([A-Za-z_$][\w$]*\b(?:\s*\.\s*[A-Za-z_$][\w$]*\b)*)\s*$/g, "$1"); - } - - if(interfaces !== undef) { - interfacesNames = interfaces.replace(/^\s*implements\s+(.+?)\s*$/g, "$1").split(/\s*,\s*/g); - } - - for(i = 0; i < functions.length; ++i) { - functions[i] = transformFunction(atoms[functions[i]]); - } - for(i = 0; i < methods.length; ++i) { - methods[i] = transformClassMethod(atoms[methods[i]]); - } - for(i = 0; i < fields.length - 1; ++i) { - var field = trimSpaces(fields[i]); - fields[i] = transformClassField(field.middle); - } - var tail = fields.pop(); - for(i = 0; i < cstrs.length; ++i) { - cstrs[i] = transformConstructor(atoms[cstrs[i]]); - } - for(i = 0; i < classes.length; ++i) { - classes[i] = transformInnerClass(atoms[classes[i]]); - } - - return new AstClassBody(name, baseClassName, interfacesNames, functions, methods, fields, cstrs, - classes, { tail: tail }); - }; - - function AstInterface(name, body) { - this.name = name; - this.body = body; - body.owner = this; - } - AstInterface.prototype.toString = function() { - return "var " + this.name + " = " + this.body + ";\n" + - "$p." + this.name + " = " + this.name + ";\n"; - }; - function AstClass(name, body) { - this.name = name; - this.body = body; - body.owner = this; - } - AstClass.prototype.toString = function() { - return "var " + this.name + " = " + this.body + ";\n" + - "$p." + this.name + " = " + this.name + ";\n"; - }; - - function transformGlobalClass(class_) { - var m = classesRegex.exec(class_); // 1 - attr, 2 - class|int, 3 - name, 4 - extends, 5 - implements, 6 - body - classesRegex.lastIndex = 0; - var body = atoms[getAtomIndex(m[6])]; - var oldClassId = currentClassId, newClassId = generateClassId(); - currentClassId = newClassId; - var globalClass; - if(m[2] === "interface") { - globalClass = new AstInterface(m[3], transformInterfaceBody(body, m[3], m[4]) ); - } else { - globalClass = new AstClass(m[3], transformClassBody(body, m[3], m[4], m[5]) ); - } - appendClass(globalClass, newClassId, oldClassId); - currentClassId = oldClassId; - return globalClass; - } - - function AstMethod(name, params, body) { - this.name = name; - this.params = params; - this.body = body; - } - AstMethod.prototype.toString = function(){ - var paramNames = appendToLookupTable({}, this.params.getNames()); - var oldContext = replaceContext; - replaceContext = function (subject) { - return paramNames.hasOwnProperty(subject.name) ? subject.name : oldContext(subject); - }; - var result = "function " + this.name + this.params + " " + this.body + "\n" + - "$p." + this.name + " = " + this.name + ";"; - replaceContext = oldContext; - return result; - }; - - function transformGlobalMethod(method) { - var m = methodsRegex.exec(method); - var result = - methodsRegex.lastIndex = 0; - return new AstMethod(m[3], transformParams(atoms[getAtomIndex(m[4])]), - transformStatementsBlock(atoms[getAtomIndex(m[6])])); - } - - function preStatementsTransform(statements) { - var s = statements; - // turns multiple catch blocks into one, because we have no way to properly get into them anyway. - s = s.replace(/\b(catch\s*"B\d+"\s*"A\d+")(\s*catch\s*"B\d+"\s*"A\d+")+/g, "$1"); - return s; - } - - function AstForStatement(argument, misc) { - this.argument = argument; - this.misc = misc; - } - AstForStatement.prototype.toString = function() { - return this.misc.prefix + this.argument.toString(); - }; - function AstCatchStatement(argument, misc) { - this.argument = argument; - this.misc = misc; - } - AstCatchStatement.prototype.toString = function() { - return this.misc.prefix + this.argument.toString(); - }; - function AstPrefixStatement(name, argument, misc) { - this.name = name; - this.argument = argument; - this.misc = misc; - } - AstPrefixStatement.prototype.toString = function() { - var result = this.misc.prefix; - if(this.argument !== undef) { - result += this.argument.toString(); - } - return result; - }; - function AstSwitchCase(expr) { - this.expr = expr; - } - AstSwitchCase.prototype.toString = function() { - return "case " + this.expr + ":"; - }; - function AstLabel(label) { - this.label = label; - } - AstLabel.prototype.toString = function() { - return this.label; - }; - - transformStatements = function(statements, transformMethod, transformClass) { - var nextStatement = new RegExp(/\b(catch|for|if|switch|while|with)\s*"B(\d+)"|\b(do|else|finally|return|throw|try|break|continue)\b|("[ADEH](\d+)")|\b(case)\s+([^:]+):|\b([A-Za-z_$][\w$]*\s*:)|(;)/g); - var res = []; - statements = preStatementsTransform(statements); - var lastIndex = 0, m, space; - // m contains the matches from the nextStatement regexp, null if there are no matches. - // nextStatement.exec starts searching at nextStatement.lastIndex. - while((m = nextStatement.exec(statements)) !== null) { - if(m[1] !== undef) { // catch, for ... - var i = statements.lastIndexOf('"B', nextStatement.lastIndex); - var statementsPrefix = statements.substring(lastIndex, i); - if(m[1] === "for") { - res.push(new AstForStatement(transformForExpression(atoms[m[2]]), - { prefix: statementsPrefix }) ); - } else if(m[1] === "catch") { - res.push(new AstCatchStatement(transformParams(atoms[m[2]]), - { prefix: statementsPrefix }) ); - } else { - res.push(new AstPrefixStatement(m[1], transformExpression(atoms[m[2]]), - { prefix: statementsPrefix }) ); - } - } else if(m[3] !== undef) { // do, else, ... - res.push(new AstPrefixStatement(m[3], undef, - { prefix: statements.substring(lastIndex, nextStatement.lastIndex) }) ); - } else if(m[4] !== undef) { // block, class and methods - space = statements.substring(lastIndex, nextStatement.lastIndex - m[4].length); - if(trim(space).length !== 0) { continue; } // avoiding new type[] {} construct - res.push(space); - var kind = m[4].charAt(1), atomIndex = m[5]; - if(kind === 'D') { - res.push(transformMethod(atoms[atomIndex])); - } else if(kind === 'E') { - res.push(transformClass(atoms[atomIndex])); - } else if(kind === 'H') { - res.push(transformFunction(atoms[atomIndex])); - } else { - res.push(transformStatementsBlock(atoms[atomIndex])); - } - } else if(m[6] !== undef) { // switch case - res.push(new AstSwitchCase(transformExpression(trim(m[7])))); - } else if(m[8] !== undef) { // label - space = statements.substring(lastIndex, nextStatement.lastIndex - m[8].length); - if(trim(space).length !== 0) { continue; } // avoiding ?: construct - res.push(new AstLabel(statements.substring(lastIndex, nextStatement.lastIndex)) ); - } else { // semicolon - var statement = trimSpaces(statements.substring(lastIndex, nextStatement.lastIndex - 1)); - res.push(statement.left); - res.push(transformStatement(statement.middle)); - res.push(statement.right + ";"); - } - lastIndex = nextStatement.lastIndex; - } - var statementsTail = trimSpaces(statements.substring(lastIndex)); - res.push(statementsTail.left); - if(statementsTail.middle !== "") { - res.push(transformStatement(statementsTail.middle)); - res.push(";" + statementsTail.right); - } - return res; - }; - - function getLocalNames(statements) { - var localNames = []; - for(var i=0,l=statements.length;i 0) { - for (i = 0, l = interfacesNames.length; i < l; ++i) { - var interface_ = findInScopes(class_, interfacesNames[i]); - interfaces.push(interface_); - if (!interface_) { - continue; - } - if (!interface_.derived) { - interface_.derived = []; - } - interface_.derived.push(class_); - } - if (interfaces.length > 0) { - class_.interfaces = interfaces; - } - } - } - } - } - - function setWeight(ast) { - var queue = [], tocheck = {}; - var id, scopeId, class_; - // queue most inner and non-inherited - for (id in declaredClasses) { - if (declaredClasses.hasOwnProperty(id)) { - class_ = declaredClasses[id]; - if (!class_.inScope && !class_.derived) { - queue.push(id); - class_.weight = 0; - } else { - var dependsOn = []; - if (class_.inScope) { - for (scopeId in class_.inScope) { - if (class_.inScope.hasOwnProperty(scopeId)) { - dependsOn.push(class_.inScope[scopeId]); - } - } - } - if (class_.derived) { - dependsOn = dependsOn.concat(class_.derived); - } - tocheck[id] = dependsOn; - } - } - } - function removeDependentAndCheck(targetId, from) { - var dependsOn = tocheck[targetId]; - if (!dependsOn) { - return false; // no need to process - } - var i = dependsOn.indexOf(from); - if (i < 0) { - return false; - } - dependsOn.splice(i, 1); - if (dependsOn.length > 0) { - return false; - } - delete tocheck[targetId]; - return true; - } - while (queue.length > 0) { - id = queue.shift(); - class_ = declaredClasses[id]; - if (class_.scopeId && removeDependentAndCheck(class_.scopeId, class_)) { - queue.push(class_.scopeId); - declaredClasses[class_.scopeId].weight = class_.weight + 1; - } - if (class_.base && removeDependentAndCheck(class_.base.classId, class_)) { - queue.push(class_.base.classId); - class_.base.weight = class_.weight + 1; - } - if (class_.interfaces) { - var i, l; - for (i = 0, l = class_.interfaces.length; i < l; ++i) { - if (!class_.interfaces[i] || - !removeDependentAndCheck(class_.interfaces[i].classId, class_)) { - continue; - } - queue.push(class_.interfaces[i].classId); - class_.interfaces[i].weight = class_.weight + 1; - } - } - } - } - - var transformed = transformMain(); - generateMetadata(transformed); - setWeight(transformed); - - var redendered = transformed.toString(); - - // remove empty extra lines with space - redendered = redendered.replace(/\s*\n(?:[\t ]*\n)+/g, "\n\n"); - - return injectStrings(redendered, strings); - }// Parser ends - - function preprocessCode(aCode, sketch) { - // Parse out @pjs directive, if any. - var dm = new RegExp(/\/\*\s*@pjs\s+((?:[^\*]|\*+[^\*\/])*)\*\//g).exec(aCode); - if (dm && dm.length === 2) { - // masks contents of a JSON to be replaced later - // to protect the contents from further parsing - var jsonItems = [], - directives = dm.splice(1, 2)[0].replace(/\{([\s\S]*?)\}/g, (function() { - return function(all, item) { - jsonItems.push(item); - return "{" + (jsonItems.length-1) + "}"; - }; - }())).replace('\n', '').replace('\r', '').split(";"); - - // We'll L/RTrim, and also remove any surrounding double quotes (e.g., just take string contents) - var clean = function(s) { - return s.replace(/^\s*["']?/, '').replace(/["']?\s*$/, ''); - }; - - for (var i = 0, dl = directives.length; i < dl; i++) { - var pair = directives[i].split('='); - if (pair && pair.length === 2) { - var key = clean(pair[0]), - value = clean(pair[1]), - list = []; - // A few directives require work beyond storying key/value pairings - if (key === "preload") { - list = value.split(','); - // All pre-loaded images will get put in imageCache, keyed on filename - for (var j = 0, jl = list.length; j < jl; j++) { - var imageName = clean(list[j]); - sketch.imageCache.add(imageName); - } - // fonts can be declared as a string containing a url, - // or a JSON object, containing a font name, and a url - } else if (key === "font") { - list = value.split(","); - for (var x = 0, xl = list.length; x < xl; x++) { - var fontName = clean(list[x]), - index = /^\{(\d*?)\}$/.exec(fontName); - // if index is not null, send JSON, otherwise, send string - PFont.preloading.add(index ? JSON.parse("{" + jsonItems[index[1]] + "}") : fontName); - } - } else if (key === "pauseOnBlur") { - sketch.options.pauseOnBlur = value === "true"; - } else if (key === "globalKeyEvents") { - sketch.options.globalKeyEvents = value === "true"; - } else if (key.substring(0, 6) === "param-") { - sketch.params[key.substring(6)] = value; - } else { - sketch.options[key] = value; - } - } - } - } - return aCode; - } - - // Parse/compiles Processing (Java-like) syntax to JavaScript syntax - Processing.compile = function(pdeCode) { - var sketch = new Processing.Sketch(); - var code = preprocessCode(pdeCode, sketch); - var compiledPde = parseProcessing(code); - sketch.sourceCode = compiledPde; - return sketch; - }; -//#endif - - // tinylog lite JavaScript library - // http://purl.eligrey.com/tinylog/lite - /*global tinylog,print*/ - var tinylogLite = (function() { - "use strict"; - - var tinylogLite = {}, - undef = "undefined", - func = "function", - False = !1, - True = !0, - logLimit = 512, - log = "log"; - - if (typeof tinylog !== undef && typeof tinylog[log] === func) { - // pre-existing tinylog present - tinylogLite[log] = tinylog[log]; - } else if (typeof document !== undef && !document.fake) { - (function() { - // DOM document - var doc = document, - - $div = "div", - $style = "style", - $title = "title", - - containerStyles = { - zIndex: 10000, - position: "fixed", - bottom: "0px", - width: "100%", - height: "15%", - fontFamily: "sans-serif", - color: "#ccc", - backgroundColor: "black" - }, - outputStyles = { - position: "relative", - fontFamily: "monospace", - overflow: "auto", - height: "100%", - paddingTop: "5px" - }, - resizerStyles = { - height: "5px", - marginTop: "-5px", - cursor: "n-resize", - backgroundColor: "darkgrey" - }, - closeButtonStyles = { - position: "absolute", - top: "5px", - right: "20px", - color: "#111", - MozBorderRadius: "4px", - webkitBorderRadius: "4px", - borderRadius: "4px", - cursor: "pointer", - fontWeight: "normal", - textAlign: "center", - padding: "3px 5px", - backgroundColor: "#333", - fontSize: "12px" - }, - entryStyles = { - //borderBottom: "1px solid #d3d3d3", - minHeight: "16px" - }, - entryTextStyles = { - fontSize: "12px", - margin: "0 8px 0 8px", - maxWidth: "100%", - whiteSpace: "pre-wrap", - overflow: "auto" - }, - - view = doc.defaultView, - docElem = doc.documentElement, - docElemStyle = docElem[$style], - - setStyles = function() { - var i = arguments.length, - elemStyle, styles, style; - - while (i--) { - styles = arguments[i--]; - elemStyle = arguments[i][$style]; - - for (style in styles) { - if (styles.hasOwnProperty(style)) { - elemStyle[style] = styles[style]; - } - } - } - }, - - observer = function(obj, event, handler) { - if (obj.addEventListener) { - obj.addEventListener(event, handler, False); - } else if (obj.attachEvent) { - obj.attachEvent("on" + event, handler); - } - return [obj, event, handler]; - }, - unobserve = function(obj, event, handler) { - if (obj.removeEventListener) { - obj.removeEventListener(event, handler, False); - } else if (obj.detachEvent) { - obj.detachEvent("on" + event, handler); - } - }, - clearChildren = function(node) { - var children = node.childNodes, - child = children.length; - - while (child--) { - node.removeChild(children.item(0)); - } - }, - append = function(to, elem) { - return to.appendChild(elem); - }, - createElement = function(localName) { - return doc.createElement(localName); - }, - createTextNode = function(text) { - return doc.createTextNode(text); - }, - - createLog = tinylogLite[log] = function(message) { - // don't show output log until called once - var uninit, - originalPadding = docElemStyle.paddingBottom, - container = createElement($div), - containerStyle = container[$style], - resizer = append(container, createElement($div)), - output = append(container, createElement($div)), - closeButton = append(container, createElement($div)), - resizingLog = False, - previousHeight = False, - previousScrollTop = False, - messages = 0, - - updateSafetyMargin = function() { - // have a blank space large enough to fit the output box at the page bottom - docElemStyle.paddingBottom = container.clientHeight + "px"; - }, - setContainerHeight = function(height) { - var viewHeight = view.innerHeight, - resizerHeight = resizer.clientHeight; - - // constrain the container inside the viewport's dimensions - if (height < 0) { - height = 0; - } else if (height + resizerHeight > viewHeight) { - height = viewHeight - resizerHeight; - } - - containerStyle.height = height / viewHeight * 100 + "%"; - - updateSafetyMargin(); - }, - observers = [ - observer(doc, "mousemove", function(evt) { - if (resizingLog) { - setContainerHeight(view.innerHeight - evt.clientY); - output.scrollTop = previousScrollTop; - } - }), - - observer(doc, "mouseup", function() { - if (resizingLog) { - resizingLog = previousScrollTop = False; - } - }), - - observer(resizer, "dblclick", function(evt) { - evt.preventDefault(); - - if (previousHeight) { - setContainerHeight(previousHeight); - previousHeight = False; - } else { - previousHeight = container.clientHeight; - containerStyle.height = "0px"; - } - }), - - observer(resizer, "mousedown", function(evt) { - evt.preventDefault(); - resizingLog = True; - previousScrollTop = output.scrollTop; - }), - - observer(resizer, "contextmenu", function() { - resizingLog = False; - }), - - observer(closeButton, "click", function() { - uninit(); - }) - ]; - - uninit = function() { - // remove observers - var i = observers.length; - - while (i--) { - unobserve.apply(tinylogLite, observers[i]); - } - - // remove tinylog lite from the DOM - docElem.removeChild(container); - docElemStyle.paddingBottom = originalPadding; - - clearChildren(output); - clearChildren(container); - - tinylogLite[log] = createLog; - }; - - setStyles( - container, containerStyles, output, outputStyles, resizer, resizerStyles, closeButton, closeButtonStyles); - - closeButton[$title] = "Close Log"; - append(closeButton, createTextNode("\u2716")); - - resizer[$title] = "Double-click to toggle log minimization"; - - docElem.insertBefore(container, docElem.firstChild); - - tinylogLite[log] = function(message) { - if (messages === logLimit) { - output.removeChild(output.firstChild); - } else { - messages++; - } - - var entry = append(output, createElement($div)), - entryText = append(entry, createElement($div)); - - entry[$title] = (new Date()).toLocaleTimeString(); - - setStyles( - entry, entryStyles, entryText, entryTextStyles); - - append(entryText, createTextNode(message)); - output.scrollTop = output.scrollHeight; - }; - - tinylogLite[log](message); - updateSafetyMargin(); - }; - }()); - } else if (typeof print === func) { // JS shell - tinylogLite[log] = print; - } - - return tinylogLite; - }()); - // end of tinylog lite JavaScript library - - Processing.logger = tinylogLite; - - Processing.version = "@VERSION@"; - - // Share lib space - Processing.lib = {}; - - Processing.registerLibrary = function(name, desc) { - Processing.lib[name] = desc; - - if(desc.hasOwnProperty("init")) { - desc.init(defaultScope); - } - }; - - // Store Processing instances. Only Processing.instances, - // Processing.getInstanceById are exposed. - Processing.instances = processingInstances; - - Processing.getInstanceById = function(name) { - return processingInstances[processingInstanceIds[name]]; - }; - - Processing.Sketch = function(attachFunction) { - this.attachFunction = attachFunction; // can be optional - this.options = { - pauseOnBlur: false, - globalKeyEvents: false - }; - - /* Optional Sketch event hooks: - * onLoad - parsing/preloading is done, before sketch starts - * onSetup - setup() has been called, before first draw() - * onPause - noLoop() has been called, pausing draw loop - * onLoop - loop() has been called, resuming draw loop - * onFrameStart - draw() loop about to begin - * onFrameEnd - draw() loop finished - * onExit - exit() done being called - */ - this.onLoad = nop; - this.onSetup = nop; - this.onPause = nop; - this.onLoop = nop; - this.onFrameStart = nop; - this.onFrameEnd = nop; - this.onExit = nop; - - this.params = {}; - this.imageCache = { - pending: 0, - images: {}, - // Opera requires special administration for preloading - operaCache: {}, - // Specify an optional img arg if the image is already loaded in the DOM, - // otherwise href will get loaded. - add: function(href, img) { - // Prevent muliple loads for an image, in case it gets - // preloaded more than once, or is added via JS and then preloaded. - if (this.images[href]) { - return; - } - - if (!isDOMPresent) { - this.images[href] = null; - } - - // No image in the DOM, kick-off a background load - if (!img) { - img = new Image(); - img.onload = (function(owner) { - return function() { - owner.pending--; - }; - }(this)); - this.pending++; - img.src = href; - } - - this.images[href] = img; - - // Opera will not load images until they are inserted into the DOM. - if (window.opera) { - var div = document.createElement("div"); - div.appendChild(img); - // we can't use "display: none", since that makes it invisible, and thus not load - div.style.position = "absolute"; - div.style.opacity = 0; - div.style.width = "1px"; - div.style.height= "1px"; - if (!this.operaCache[href]) { - document.body.appendChild(div); - this.operaCache[href] = div; - } - } - } - }; - this.sourceCode = undefined; - this.attach = function(processing) { - // either attachFunction or sourceCode must be present on attach - if(typeof this.attachFunction === "function") { - this.attachFunction(processing); - } else if(this.sourceCode) { - var func = ((new Function("return (" + this.sourceCode + ");"))()); - func(processing); - this.attachFunction = func; - } else { - throw "Unable to attach sketch to the processing instance"; - } - }; -//#if PARSER - this.toString = function() { - var i; - var code = "((function(Sketch) {\n"; - code += "var sketch = new Sketch(\n" + this.sourceCode + ");\n"; - for(i in this.options) { - if(this.options.hasOwnProperty(i)) { - var value = this.options[i]; - code += "sketch.options." + i + " = " + - (typeof value === 'string' ? '\"' + value + '\"' : "" + value) + ";\n"; - } - } - for(i in this.imageCache) { - if(this.options.hasOwnProperty(i)) { - code += "sketch.imageCache.add(\"" + i + "\");\n"; - } - } - // TODO serialize fonts - code += "return sketch;\n})(Processing.Sketch))"; - return code; - }; -//#endif - }; - -//#if PARSER - /** - * aggregate all source code into a single file, then rewrite that - * source and bind to canvas via new Processing(canvas, sourcestring). - * @param {CANVAS} canvas The html canvas element to bind to - * @param {String[]} source The array of files that must be loaded - */ - var loadSketchFromSources = function(canvas, sources) { - var code = [], errors = [], sourcesCount = sources.length, loaded = 0; - - function ajaxAsync(url, callback) { - var xhr = new XMLHttpRequest(); - xhr.onreadystatechange = function() { - if (xhr.readyState === 4) { - var error; - if (xhr.status !== 200 && xhr.status !== 0) { - error = "Invalid XHR status " + xhr.status; - } else if (xhr.responseText === "") { - // Give a hint when loading fails due to same-origin issues on file:/// urls - if ( ("withCredentials" in new XMLHttpRequest()) && - (new XMLHttpRequest()).withCredentials === false && - window.location.protocol === "file:" ) { - error = "XMLHttpRequest failure, possibly due to a same-origin policy violation. You can try loading this page in another browser, or load it from http://localhost using a local webserver. See the Processing.js README for a more detailed explanation of this problem and solutions."; - } else { - error = "File is empty."; - } - } - - callback(xhr.responseText, error); - } - }; - xhr.open("GET", url, true); - if (xhr.overrideMimeType) { - xhr.overrideMimeType("application/json"); - } - xhr.setRequestHeader("If-Modified-Since", "Fri, 01 Jan 1960 00:00:00 GMT"); // no cache - xhr.send(null); - } - - function loadBlock(index, filename) { - function callback(block, error) { - code[index] = block; - ++loaded; - if (error) { - errors.push(filename + " ==> " + error); - } - if (loaded === sourcesCount) { - if (errors.length === 0) { - try { - return new Processing(canvas, code.join("\n")); - } catch(e) { - throw "Processing.js: Unable to execute pjs sketch: " + e; - } - } else { - throw "Processing.js: Unable to load pjs sketch files: " + errors.join("\n"); - } - } - } - if (filename.charAt(0) === '#') { - // trying to get script from the element - var scriptElement = document.getElementById(filename.substring(1)); - if (scriptElement) { - callback(scriptElement.text || scriptElement.textContent); - } else { - callback("", "Unable to load pjs sketch: element with id \'" + filename.substring(1) + "\' was not found"); - } - return; - } - - ajaxAsync(filename, callback); - } - - for (var i = 0; i < sourcesCount; ++i) { - loadBlock(i, sources[i]); - } - }; - - /** - * Automatic initialization function. - */ - var init = function() { - document.removeEventListener('DOMContentLoaded', init, false); - - var canvas = document.getElementsByTagName('canvas'), - filenames; - - for (var i = 0, l = canvas.length; i < l; i++) { - // datasrc and data-src are deprecated. - var processingSources = canvas[i].getAttribute('data-processing-sources'); - if (processingSources === null) { - // Temporary fallback for datasrc and data-src - processingSources = canvas[i].getAttribute('data-src'); - if (processingSources === null) { - processingSources = canvas[i].getAttribute('datasrc'); - } - } - if (processingSources) { - filenames = processingSources.split(' '); - for (var j = 0; j < filenames.length;) { - if (filenames[j]) { - j++; - } else { - filenames.splice(j, 1); - } - } - loadSketchFromSources(canvas[i], filenames); - } - } - - // also process all - - - - - - -

- - -
- diff -r fcf435874395 -r 45c889eae324 front_idill/extern/fajran-tuiojs/examples/processingjs/tuio.processing.js --- a/front_idill/extern/fajran-tuiojs/examples/processingjs/tuio.processing.js Thu Apr 19 11:53:06 2012 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,142 +0,0 @@ -/* - Modified by alexandre.bastien@iri.centrepompidou.fr to manage TUIO strings. -*/ - -// add hooks -(function(){ -this.Processing.addTuioObject = undefined; -this.Processing.updateTuioObject = undefined; -this.Processing.removeTuioObject = undefined; -this.Processing.addTuioCursor = undefined; -this.Processing.updateTuioCursor = undefined; -this.Processing.removeTuioCursor = undefined; -this.Processing.addTuioString = undefined; -this.Processing.updateTuioString = undefined; -this.Processing.removeTuioString = undefined; -})(); - -(function(){ - -var tuio = this.tuio; - -/* -* Modifié par alexandre.bastien@iri.centrepompidou.fr -*/ -function wrapPath(d) { - var i, len = d.path.length; - var res = []; - for (i=0; i - -TUIO Client plugin test - - - - - - - - - - - diff -r fcf435874395 -r 45c889eae324 front_idill/extern/fajran-tuiojs/src/tuio.js --- a/front_idill/extern/fajran-tuiojs/src/tuio.js Thu Apr 19 11:53:06 2012 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,219 +0,0 @@ -/* - Modified by alexandre.bastien@iri.centrepompidou.fr to manage TUIO strings. -*/ - -var test = 0; - -(function() { - var TUIO = function() { - // Listener class - - this.Listener = function(impl) { - if (impl != undefined) { - // override original method implementation - for (var key in impl) { - this[key] = impl[key]; - } - } - } - this.Listener.prototype = { - object_add: function(data) { }, - object_update: function(data) { }, - object_remove: function(data) { }, - cursor_add: function(data) { }, - cursor_update: function(data) { }, - cursor_remove: function(data) { }, - string_add: function(data) { }, - string_update: function(data) { }, - string_remove: function(data) { } - } - - // Instance variables - - this.objects = []; - this.cursors = []; - this.strings = []; - - this._data = {}; - - this._default_listener = new this.Listener(); - this._listeners = [this._default_listener]; - - this._connector = undefined; - - }; - TUIO.prototype = { - start: function(name) { - var c = this._connector; - if (c != undefined) { - if (c.start != undefined) { - c.start(); - } - } - }, - - stop: function() { - var c = this._connector; - if (c != undefined) { - if (c.stop != undefined) { - c.stop(); - } - } - }, - - setConnector: function(connector) { - this._connector = connector; - }, - - addListener: function(listener) { - this._listeners.push(listener); - }, - removeListener: function(listener) { - this._listeners.splice(this._listeners.indexOf(listener), 1); - }, - - _invoke: function(method, data) { - var i, len = this._listeners.length; - for (i=0; i= 6) - return; - - var data; - - if ((type != 0) && (type != 3)) { - data = this._data[sid]; - } - else { - data = { - sid: sid, - fid: fid, - path: [] - } - this._data[sid] = data; - } - - data.path.push([x, y, z]); - - data.x = x; - data.y = y; - data.z = z; - - if (type < 3) { - data.angle = angle; - } - - switch (type) { - case 0: - this.objects.push(data); - this._invoke('object_add', data); - break; - - case 1: - this._invoke('object_update', data); - break; - - case 2: - this.objects.splice(this.objects.indexOf(data), 1); - this._invoke('object_remove', data); - break; - - case 3: - this.cursors.push(data); - this._invoke('cursor_add', data); - break; - - case 4: - this._invoke('cursor_update', data); - break; - - case 5: - this.cursors.splice(this.cursors.indexOf(data), 1); - this._invoke('cursor_remove', data); - break; - - default: - break; - } - - if ((type == 2) || (type == 5)) { - delete this._data[sid]; - } - }, - - stringCallback: function(type, sid, code) { - if(type < 6) - return; - - var data; - - if ((type != 6)) { - data = this._data[sid]; - } - else { - data = { - sid: sid, - code: code - } - this._data[sid] = data; - } - - //data.code = code; - - switch (type) { - case 6: - if(this.strings != null && this.strings.length <= 0) - { - this.strings.push(data); - this._invoke('string_add', data); - test++; - //alert(test); - } - break; - - case 7: - this._invoke('string_update', data); - break; - - case 8: - //var str = ""; - //for(var j = 0 ; j < this.strings.length ; j++) - //str += "(" + this.strings[i].sid + ")" + this.strings[i].code + " "; - //alert(str); - //this.strings.splice(this.strings.indexOf(data), 1); - this.strings.length = 0; - this._invoke('string_remove', data); - test--; - alert(test); - break; - - default: - break; - } - - if ((type == 8)) { - delete this._data[sid]; - } - }, - - // Convenient callbacks set - - object_add: function(f) { this._default_listener.object_add = f; }, - object_update: function(f) { this._default_listener.object_update = f; }, - object_remove: function(f) { this._default_listener.object_remove = f; }, - cursor_add: function(f) { this._default_listener.cursor_add = f; }, - cursor_update: function(f) { this._default_listener.cursor_update = f; }, - cursor_remove: function(f) { this._default_listener.cursor_remove = f; }, - string_add: function(f) { this._default_listener.string_add = f; }, - string_update: function(f) { this._default_listener.string_update = f; }, - string_remove: function(f) { this._default_listener.string_remove = f; } - - }; - this.tuio = new TUIO(); -})(); - diff -r fcf435874395 -r 45c889eae324 front_idill/lib/less-1.3.0.min.js --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/front_idill/lib/less-1.3.0.min.js Fri Apr 27 14:38:23 2012 +0200 @@ -0,0 +1,9 @@ +// +// LESS - Leaner CSS v1.3.0 +// http://lesscss.org +// +// Copyright (c) 2009-2011, Alexis Sellier +// Licensed under the Apache 2.0 License. +// +(function(a,b){function c(b){return a.less[b.split("/")[1]]}function l(){var a=document.getElementsByTagName("style");for(var b=0;b0?d.firstChild.nodeValue!==a.nodeValue&&d.replaceChild(a,d.firstChild):d.appendChild(a)})(document.createTextNode(a));c&&g&&(t("saving "+e+" to cache."),g.setItem(e,a),g.setItem(e+":timestamp",c))}function q(a,b,c,e){function i(b,c,d){b.status>=200&&b.status<300?c(b.responseText,b.getResponseHeader("Last-Modified")):typeof d=="function"&&d(b.status,a)}var g=r(),h=f?!1:d.async;typeof g.overrideMimeType=="function"&&g.overrideMimeType("text/css"),g.open("GET",a,h),g.setRequestHeader("Accept",b||"text/x-less, text/css; q=0.9, */*; q=0.5"),g.send(null),f?g.status===0||g.status>=200&&g.status<300?c(g.responseText):e(g.status,a):h?g.onreadystatechange=function(){g.readyState==4&&i(g,c,e)}:i(g,c,e)}function r(){if(a.XMLHttpRequest)return new XMLHttpRequest;try{return new ActiveXObject("MSXML2.XMLHTTP.3.0")}catch(b){return t("browser doesn't support AJAX."),null}}function s(a){return a&&a.parentNode.removeChild(a)}function t(a){d.env=="development"&&typeof console!="undefined"&&console.log("less: "+a)}function u(a,b){var c="less-error-message:"+o(b),e='
  • {content}
  • ',f=document.createElement("div"),g,h,i=[],j=a.filename||b;f.id=c,f.className="less-error-message",h="

    "+(a.message||"There is an error in your .less file")+"

    "+'

    in '+j+" ";var k=function(a,b,c){a.extract[b]&&i.push(e.replace(/\{line\}/,parseInt(a.line)+(b-1)).replace(/\{class\}/,c).replace(/\{content\}/,a.extract[b]))};a.stack?h+="
    "+a.stack.split("\n").slice(1).join("
    "):a.extract&&(k(a,0,""),k(a,1,"line"),k(a,2,""),h+="on line "+a.line+", column "+(a.column+1)+":

    "+"
      "+i.join("")+"
    "),f.innerHTML=h,p([".less-error-message ul, .less-error-message li {","list-style-type: none;","margin-right: 15px;","padding: 4px 0;","margin: 0;","}",".less-error-message label {","font-size: 12px;","margin-right: 15px;","padding: 4px 0;","color: #cc7777;","}",".less-error-message pre {","color: #dd6666;","padding: 4px 0;","margin: 0;","display: inline-block;","}",".less-error-message pre.line {","color: #ff0000;","}",".less-error-message h3 {","font-size: 20px;","font-weight: bold;","padding: 15px 0 5px 0;","margin: 0;","}",".less-error-message a {","color: #10a","}",".less-error-message .error {","color: red;","font-weight: bold;","padding-bottom: 2px;","border-bottom: 1px dashed red;","}"].join("\n"),{title:"error-message"}),f.style.cssText=["font-family: Arial, sans-serif","border: 1px solid #e00","background-color: #eee","border-radius: 5px","-webkit-border-radius: 5px","-moz-border-radius: 5px","color: #e00","padding: 15px","margin-bottom: 15px"].join(";"),d.env=="development"&&(g=setInterval(function(){document.body&&(document.getElementById(c)?document.body.replaceChild(f,document.getElementById(c)):document.body.insertBefore(f,document.body.firstChild),clearInterval(g))},10))}typeof define=="function"&&define.amd&&define("less",[],function(){return d}),Array.isArray||(Array.isArray=function(a){return Object.prototype.toString.call(a)==="[object Array]"||a instanceof Array}),Array.prototype.forEach||(Array.prototype.forEach=function(a,b){var c=this.length>>>0;for(var d=0;d>>0,c=new Array(b),d=arguments[1];for(var e=0;e>>0,c=0;if(b===0&&arguments.length===1)throw new TypeError;if(arguments.length>=2)var d=arguments[1];else do{if(c in this){d=this[c++];break}if(++c>=b)throw new TypeError}while(!0);for(;c=b)return-1;c<0&&(c+=b);for(;cl&&(k[g]=k[g].slice(f-l),l=f)}function t(a){var c,d,e,h,i,j,n,o;if(a instanceof Function)return a.call(m.parsers);if(typeof a=="string")c=b.charAt(f)===a?a:null,e=1,s();else{s();if(c=a.exec(k[g]))e=c[0].length;else return null}if(c){o=f+=e,j=f+k[g].length-e;while(f=0&&b.charAt(c)!=="\n";c--)d++;return{line:typeof a=="number"?(b.slice(0,a).match(/\n/g)||"").length:null,column:d}}function A(a,b){var c=y(a,b),d=z(a.index,c),e=d.line,f=d.column,g=c.split("\n");this.type=a.type||"Syntax",this.message=a.message,this.filename=a.filename||b.filename,this.index=a.index,this.line=typeof e=="number"?e+1:null,this.callLine=a.call&&z(a.call,c).line+1,this.callExtract=g[z(a.call,c).line],this.stack=a.stack,this.column=f,this.extract=[g[e-1],g[e],g[e+1]]}var b,f,g,h,i,j,k,l,m,n=this,o=function(){},p=this.imports={paths:a&&a.paths||[],queue:[],files:{},contents:{},mime:a&&a.mime,error:null,push:function(b,c){var e=this;this.queue.push(b),d.Parser.importer(b,this.paths,function(a,d,f){e.queue.splice(e.queue.indexOf(b),1),e.files[b]=d,e.contents[b]=f,a&&!e.error&&(e.error=a),c(a,d),e.queue.length===0&&o()},a)}};return this.env=a=a||{},this.optimization="optimization"in this.env?this.env.optimization:1,this.env.filename=this.env.filename||null,m={imports:p,parse:function(h,i){var n,p,q,r,s,u,v=[],w,x=null;f=g=l=j=0,b=h.replace(/\r\n/g,"\n"),k=function(c){var d=0,e=/[^"'`\{\}\/\(\)\\]+/g,f=/\/\*(?:[^*]|\*+[^\/*])*\*+\/|\/\/.*/g,g=/"((?:[^"\\\r\n]|\\.)*)"|'((?:[^'\\\r\n]|\\.)*)'|`((?:[^`\\\r\n]|\\.)*)`/g,h=0,i,j=c[0],k;for(var l=0,m,n;l0&&(x=new A({index:l,type:"Parse",message:"missing closing `}`",filename:a.filename},a)),c.map(function(a){return a.join("")})}([[]]);if(x)return i(x);try{n=new e.Ruleset([],t(this.parsers.primary)),n.root=!0}catch(y){return i(new A(y,a))}n.toCSS=function(b){var f,g,h;return function(f,g){var h=[],i;f=f||{},typeof g=="object"&&!Array.isArray(g)&&(g=Object.keys(g).map(function(a){var b=g[a];return b instanceof e.Value||(b instanceof e.Expression||(b=new e.Expression([b])),b=new e.Value([b])),new e.Rule("@"+a,b,!1,0)}),h=[new e.Ruleset(null,g)]);try{var j=b.call(this,{frames:h}).toCSS([],{compress:f.compress||!1})}catch(k){throw new A(k,a)}if(i=m.imports.error)throw i instanceof A?i:new A(i,a);return f.yuicompress&&d.mode==="node"?c("./cssmin").compressor.cssmin(j):f.compress?j.replace(/(\s)+/g,"$1"):j}}(n.eval);if(f=0&&b.charAt(z)!=="\n";z--)B++;x={type:"Parse",message:"Syntax Error on line "+s,index:f,filename:a.filename,line:s,column:B,extract:[u[s-2],u[s-1],u[s]]}}this.imports.queue.length>0?o=function(){i(x,n)}:i(x,n)},parsers:{primary:function(){var a,b=[];while((a=t(this.mixin.definition)||t(this.rule)||t(this.ruleset)||t(this.mixin.call)||t(this.comment)||t(this.directive))||t(/^[\s\n]+/))a&&b.push(a);return b},comment:function(){var a;if(b.charAt(f)!=="/")return;if(b.charAt(f+1)==="/")return new e.Comment(t(/^\/\/.*/),!0);if(a=t(/^\/\*(?:[^*]|\*+[^\/*])*\*+\/\n?/))return new e.Comment(a)},entities:{quoted:function(){var a,c=f,d;b.charAt(c)==="~"&&(c++,d=!0);if(b.charAt(c)!=='"'&&b.charAt(c)!=="'")return;d&&t("~");if(a=t(/^"((?:[^"\\\r\n]|\\.)*)"|'((?:[^'\\\r\n]|\\.)*)'/))return new e.Quoted(a[0],a[1]||a[2],d)},keyword:function(){var a;if(a=t(/^[_A-Za-z-][_A-Za-z0-9-]*/))return e.colors.hasOwnProperty(a)?new e.Color(e.colors[a].slice(1)):new e.Keyword(a)},call:function(){var b,c,d=f;if(!(b=/^([\w-]+|%|progid:[\w\.]+)\(/.exec(k[g])))return;b=b[1].toLowerCase();if(b==="url")return null;f+=b.length;if(b==="alpha")return t(this.alpha);t("("),c=t(this.entities.arguments);if(!t(")"))return;if(b)return new e.Call(b,c,d,a.filename)},arguments:function(){var a=[],b;while(b=t(this.entities.assignment)||t(this.expression)){a.push(b);if(!t(","))break}return a},literal:function(){return t(this.entities.dimension)||t(this.entities.color)||t(this.entities.quoted)},assignment:function(){var a,b;if((a=t(/^\w+(?=\s?=)/i))&&t("=")&&(b=t(this.entity)))return new e.Assignment(a,b)},url:function(){var a;if(b.charAt(f)!=="u"||!t(/^url\(/))return;return a=t(this.entities.quoted)||t(this.entities.variable)||t(this.entities.dataURI)||t(/^[-\w%@$\/.&=:;#+?~]+/)||"",u(")"),new e.URL(a.value||a.data||a instanceof e.Variable?a:new e.Anonymous(a),p.paths)},dataURI:function(){var a;if(t(/^data:/)){a={},a.mime=t(/^[^\/]+\/[^,;)]+/)||"",a.charset=t(/^;\s*charset=[^,;)]+/)||"",a.base64=t(/^;\s*base64/)||"",a.data=t(/^,\s*[^)]+/);if(a.data)return a}},variable:function(){var c,d=f;if(b.charAt(f)==="@"&&(c=t(/^@@?[\w-]+/)))return new e.Variable(c,d,a.filename)},color:function(){var a;if(b.charAt(f)==="#"&&(a=t(/^#([a-fA-F0-9]{6}|[a-fA-F0-9]{3})/)))return new e.Color(a[1])},dimension:function(){var a,c=b.charCodeAt(f);if(c>57||c<45||c===47)return;if(a=t(/^(-?\d*\.?\d+)(px|%|em|rem|pc|ex|in|deg|s|ms|pt|cm|mm|rad|grad|turn)?/))return new e.Dimension(a[1],a[2])},javascript:function(){var a,c=f,d;b.charAt(c)==="~"&&(c++,d=!0);if(b.charAt(c)!=="`")return;d&&t("~");if(a=t(/^`([^`]*)`/))return new e.JavaScript(a[1],f,d)}},variable:function(){var a;if(b.charAt(f)==="@"&&(a=t(/^(@[\w-]+)\s*:/)))return a[1]},shorthand:function(){var a,b;if(!w(/^[@\w.%-]+\/[@\w.-]+/))return;if((a=t(this.entity))&&t("/")&&(b=t(this.entity)))return new e.Shorthand(a,b)},mixin:{call:function(){var c=[],d,g,h,i=f,j=b.charAt(f),k=!1;if(j!=="."&&j!=="#")return;while(d=t(/^[#.](?:[\w-]|\\(?:[a-fA-F0-9]{1,6} ?|[^a-fA-F0-9]))+/))c.push(new e.Element(g,d,f)),g=t(">");t("(")&&(h=t(this.entities.arguments))&&t(")"),t(this.important)&&(k=!0);if(c.length>0&&(t(";")||w("}")))return new e.mixin.Call(c,h||[],i,a.filename,k)},definition:function(){var a,c=[],d,g,h,i,j,k=!1;if(b.charAt(f)!=="."&&b.charAt(f)!=="#"||w(/^[^{]*(;|})/))return;q();if(d=t(/^([#.](?:[\w-]|\\(?:[a-fA-F0-9]{1,6} ?|[^a-fA-F0-9]))+)\s*\(/)){a=d[1];do{if(b.charAt(f)==="."&&t(/^\.{3}/)){k=!0;break}if(!(h=t(this.entities.variable)||t(this.entities.literal)||t(this.entities.keyword)))break;if(h instanceof e.Variable)if(t(":"))i=u(this.expression,"expected expression"),c.push({name:h.name,value:i});else{if(t(/^\.{3}/)){c.push({name:h.name,variadic:!0}),k=!0;break}c.push({name:h.name})}else c.push({value:h})}while(t(","));u(")"),t(/^when/)&&(j=u(this.conditions,"expected condition")),g=t(this.block);if(g)return new e.mixin.Definition(a,c,g,j,k);r()}}},entity:function(){return t(this.entities.literal)||t(this.entities.variable)||t(this.entities.url)||t(this.entities.call)||t(this.entities.keyword)||t(this.entities.javascript)||t(this.comment)},end:function(){return t(";")||w("}")},alpha:function(){var a;if(!t(/^\(opacity=/i))return;if(a=t(/^\d+/)||t(this.entities.variable))return u(")"),new e.Alpha(a)},element:function(){var a,b,c,d;c=t(this.combinator),a=t(/^(?:\d+\.\d+|\d+)%/)||t(/^(?:[.#]?|:*)(?:[\w-]|\\(?:[a-fA-F0-9]{1,6} ?|[^a-fA-F0-9]))+/)||t("*")||t(this.attribute)||t(/^\([^)@]+\)/),a||t("(")&&(d=t(this.entities.variable))&&t(")")&&(a=new e.Paren(d));if(a)return new e.Element(c,a,f);if(c.value&&c.value.charAt(0)==="&")return new e.Element(c,null,f)},combinator:function(){var a,c=b.charAt(f);if(c===">"||c==="+"||c==="~"){f++;while(b.charAt(f)===" ")f++;return new e.Combinator(c)}if(c==="&"){a="&",f++,b.charAt(f)===" "&&(a="& ");while(b.charAt(f)===" ")f++;return new e.Combinator(a)}return b.charAt(f-1)===" "?new e.Combinator(" "):new e.Combinator(null)},selector:function(){var a,c,d=[],g,h;if(t("("))return a=t(this.entity),u(")"),new e.Selector([new e.Element("",a,f)]);while(c=t(this.element)){g=b.charAt(f),d.push(c);if(g==="{"||g==="}"||g===";"||g===",")break}if(d.length>0)return new e.Selector(d)},tag:function(){return t(/^[a-zA-Z][a-zA-Z-]*[0-9]?/)||t("*")},attribute:function(){var a="",b,c,d;if(!t("["))return;if(b=t(/^[a-zA-Z-]+/)||t(this.entities.quoted))(d=t(/^[|~*$^]?=/))&&(c=t(this.entities.quoted)||t(/^[\w-]+/))?a=[b,d,c.toCSS?c.toCSS():c].join(""):a=b;if(!t("]"))return;if(a)return"["+a+"]"},block:function(){var a;if(t("{")&&(a=t(this.primary))&&t("}"))return a},ruleset:function(){var b=[],c,d,g;q();while(c=t(this.selector)){b.push(c),t(this.comment);if(!t(","))break;t(this.comment)}if(b.length>0&&(d=t(this.block)))return new e.Ruleset(b,d,a.strictImports);j=f,r()},rule:function(){var a,c,d=b.charAt(f),h,l;q();if(d==="."||d==="#"||d==="&")return;if(a=t(this.variable)||t(this.property)){a.charAt(0)!="@"&&(l=/^([^@+\/'"*`(;{}-]*);/.exec(k[g]))?(f+=l[0].length-1,c=new e.Anonymous(l[1])):a==="font"?c=t(this.font):c=t(this.value),h=t(this.important);if(c&&t(this.end))return new e.Rule(a,c,h,i);j=f,r()}},"import":function(){var a,b,c=f;if(t(/^@import\s+/)&&(a=t(this.entities.quoted)||t(this.entities.url))){b=t(this.mediaFeatures);if(t(";"))return new e.Import(a,p,b,c)}},mediaFeature:function(){var a,b,c=[];do if(a=t(this.entities.keyword))c.push(a);else if(t("(")){b=t(this.property),a=t(this.entity);if(!t(")"))return null;if(b&&a)c.push(new e.Paren(new e.Rule(b,a,null,f,!0)));else if(a)c.push(new e.Paren(a));else return null}while(a);if(c.length>0)return new e.Expression(c)},mediaFeatures:function(){var a,b=[];do if(a=t(this.mediaFeature)){b.push(a);if(!t(","))break}else if(a=t(this.entities.variable)){b.push(a);if(!t(","))break}while(a);return b.length>0?b:null},media:function(){var a,b;if(t(/^@media/)){a=t(this.mediaFeatures);if(b=t(this.block))return new e.Media(b,a)}},directive:function(){var a,c,d,g,h,i;if(b.charAt(f)!=="@")return;if(c=t(this["import"])||t(this.media))return c;if(a=t(/^@page|@keyframes/)||t(/^@(?:-webkit-|-moz-|-o-|-ms-)[a-z0-9-]+/)){g=(t(/^[^{]+/)||"").trim();if(d=t(this.block))return new e.Directive(a+" "+g,d)}else if(a=t(/^@[-a-z]+/))if(a==="@font-face"){if(d=t(this.block))return new e.Directive(a,d)}else if((c=t(this.entity))&&t(";"))return new e.Directive(a,c)},font:function(){var a=[],b=[],c,d,f,g;while(g=t(this.shorthand)||t(this.entity))b.push(g);a.push(new e.Expression(b));if(t(","))while(g=t(this.expression)){a.push(g);if(!t(","))break}return new e.Value(a)},value:function(){var a,b=[],c;while(a=t(this.expression)){b.push(a);if(!t(","))break}if(b.length>0)return new e.Value(b)},important:function(){if(b.charAt(f)==="!")return t(/^! *important/)},sub:function(){var a;if(t("(")&&(a=t(this.expression))&&t(")"))return a},multiplication:function(){var a,b,c,d;if(a=t(this.operand)){while(!w(/^\/\*/)&&(c=t("/")||t("*"))&&(b=t(this.operand)))d=new e.Operation(c,[d||a,b]);return d||a}},addition:function(){var a,c,d,g;if(a=t(this.multiplication)){while((d=t(/^[-+]\s+/)||b.charAt(f-1)!=" "&&(t("+")||t("-")))&&(c=t(this.multiplication)))g=new e.Operation(d,[g||a,c]);return g||a}},conditions:function(){var a,b,c=f,d;if(a=t(this.condition)){while(t(",")&&(b=t(this.condition)))d=new e.Condition("or",d||a,b,c);return d||a}},condition:function(){var a,b,c,d,g=f,h=!1;t(/^not/)&&(h=!0),u("(");if(a=t(this.addition)||t(this.entities.keyword)||t(this.entities.quoted))return(d=t(/^(?:>=|=<|[<=>])/))?(b=t(this.addition)||t(this.entities.keyword)||t(this.entities.quoted))?c=new e.Condition(d,a,b,g,h):v("expected expression"):c=new e.Condition("=",a,new e.Keyword("true"),g,h),u(")"),t(/^and/)?new e.Condition("and",c,t(this.condition)):c},operand:function(){var a,c=b.charAt(f+1);b.charAt(f)==="-"&&(c==="@"||c==="(")&&(a=t("-"));var d=t(this.sub)||t(this.entities.dimension)||t(this.entities.color)||t(this.entities.variable)||t(this.entities.call);return a?new e.Operation("*",[new e.Dimension(-1),d]):d},expression:function(){var a,b,c=[],d;while(a=t(this.addition)||t(this.entity))c.push(a);if(c.length>0)return new e.Expression(c)},property:function(){var a;if(a=t(/^(\*?-?[-a-z_0-9]+)\s*:/))return a[1]}}}};if(d.mode==="browser"||d.mode==="rhino")d.Parser.importer=function(a,b,c,d){!/^([a-z]+:)?\//.test(a)&&b.length>0&&(a=b[0]+a),n({href:a,title:a,type:d.mime},function(e){e&&typeof d.errback=="function"?d.errback.call(null,a,b,c,d):c.apply(null,arguments)},!0)};(function(a){function b(b){return a.functions.hsla(b.h,b.s,b.l,b.a)}function c(b){if(b instanceof a.Dimension)return parseFloat(b.unit=="%"?b.value/100:b.value);if(typeof b=="number")return b;throw{error:"RuntimeError",message:"color functions take numbers as parameters"}}function d(a){return Math.min(1,Math.max(0,a))}a.functions={rgb:function(a,b,c){return this.rgba(a,b,c,1)},rgba:function(b,d,e,f){var g=[b,d,e].map(function(a){return c(a)}),f=c(f);return new a.Color(g,f)},hsl:function(a,b,c){return this.hsla(a,b,c,1)},hsla:function(a,b,d,e){function h(a){return a=a<0?a+1:a>1?a-1:a,a*6<1?g+(f-g)*a*6:a*2<1?f:a*3<2?g+(f-g)*(2/3-a)*6:g}a=c(a)%360/360,b=c(b),d=c(d),e=c(e);var f=d<=.5?d*(b+1):d+b-d*b,g=d*2-f;return this.rgba(h(a+1/3)*255,h(a)*255,h(a-1/3)*255,e)},hue:function(b){return new a.Dimension(Math.round(b.toHSL().h))},saturation:function(b){return new a.Dimension(Math.round(b.toHSL().s*100),"%")},lightness:function(b){return new a.Dimension(Math.round(b.toHSL().l*100),"%")},alpha:function(b){return new a.Dimension(b.toHSL().a)},saturate:function(a,c){var e=a.toHSL();return e.s+=c.value/100,e.s=d(e.s),b(e)},desaturate:function(a,c){var e=a.toHSL();return e.s-=c.value/100,e.s=d(e.s),b(e)},lighten:function(a,c){var e=a.toHSL();return e.l+=c.value/100,e.l=d(e.l),b(e)},darken:function(a,c){var e=a.toHSL();return e.l-=c.value/100,e.l=d(e.l),b(e)},fadein:function(a,c){var e=a.toHSL();return e.a+=c.value/100,e.a=d(e.a),b(e)},fadeout:function(a,c){var e=a.toHSL();return e.a-=c.value/100,e.a=d(e.a),b(e)},fade:function(a,c){var e=a.toHSL();return e.a=c.value/100,e.a=d(e.a),b(e)},spin:function(a,c){var d=a.toHSL(),e=(d.h+c.value)%360;return d.h=e<0?360+e:e,b(d)},mix:function(b,c,d){var e=d.value/100,f=e*2-1,g=b.toHSL().a-c.toHSL().a,h=((f*g==-1?f:(f+g)/(1+f*g))+1)/2,i=1-h,j=[b.rgb[0]*h+c.rgb[0]*i,b.rgb[1]*h+c.rgb[1]*i,b.rgb[2]*h+c.rgb[2]*i],k=b.alpha*e+c.alpha*(1-e);return new a.Color(j,k)},greyscale:function(b){return this.desaturate(b,new a.Dimension(100))},e:function(b){return new a.Anonymous(b instanceof a.JavaScript?b.evaluated:b)},escape:function(b){return new a.Anonymous(encodeURI(b.value).replace(/=/g,"%3D").replace(/:/g,"%3A").replace(/#/g,"%23").replace(/;/g,"%3B").replace(/\(/g,"%28").replace(/\)/g,"%29"))},"%":function(b){var c=Array.prototype.slice.call(arguments,1),d=b.value;for(var e=0;e255?255:a<0?0:a).toString(16),a.length===1?"0"+a:a}).join("")},operate:function(b,c){var d=[];c instanceof a.Color||(c=c.toColor());for(var e=0;e<3;e++)d[e]=a.operate(b,this.rgb[e],c.rgb[e]);return new a.Color(d,this.alpha+c.alpha)},toHSL:function(){var a=this.rgb[0]/255,b=this.rgb[1]/255,c=this.rgb[2]/255,d=this.alpha,e=Math.max(a,b,c),f=Math.min(a,b,c),g,h,i=(e+f)/2,j=e-f;if(e===f)g=h=0;else{h=i>.5?j/(2-e-f):j/(e+f);switch(e){case a:g=(b-c)/j+(b255?255:a<0?0:a).toString(16),a.length===1?"0"+a:a}).join("")}}}(c("../tree")),function(a){a.Comment=function(a,b){this.value=a,this.silent=!!b},a.Comment.prototype={toCSS:function(a){return a.compress?"":this.value},eval:function(){return this}}}(c("../tree")),function(a){a.Condition=function(a,b,c,d,e){this.op=a.trim(),this.lvalue=b,this.rvalue=c,this.index=d,this.negate=e},a.Condition.prototype.eval=function(a){var b=this.lvalue.eval(a),c=this.rvalue.eval(a),d=this.index,e,e=function(a){switch(a){case"and":return b&&c;case"or":return b||c;default:if(b.compare)e=b.compare(c);else if(c.compare)e=c.compare(b);else throw{type:"Type",message:"Unable to perform comparison",index:d};switch(e){case-1:return a==="<"||a==="=<";case 0:return a==="="||a===">="||a==="=<";case 1:return a===">"||a===">="}}}(this.op);return this.negate?!e:e}}(c("../tree")),function(a){a.Dimension=function(a,b){this.value=parseFloat(a),this.unit=b||null},a.Dimension.prototype={eval:function(){return this},toColor:function(){return new a.Color([this.value,this.value,this.value])},toCSS:function(){var a=this.value+this.unit;return a},operate:function(b,c){return new a.Dimension(a.operate(b,this.value,c.value),this.unit||c.unit)},compare:function(b){return b instanceof a.Dimension?b.value>this.value?-1:b.value":a.compress?">":" > "}[this.value]}}(c("../tree")),function(a){a.Expression=function(a){this.value=a},a.Expression.prototype={eval:function(b){return this.value.length>1?new a.Expression(this.value.map(function(a){return a.eval(b)})):this.value.length===1?this.value[0].eval(b):this},toCSS:function(a){return this.value.map(function(b){return b.toCSS?b.toCSS(a):""}).join(" ")}}}(c("../tree")),function(a){a.Import=function(b,c,d,e){var f=this;this.index=e,this._path=b,this.features=d&&new a.Value(d),b instanceof a.Quoted?this.path=/\.(le?|c)ss(\?.*)?$/.test(b.value)?b.value:b.value+".less":this.path=b.value.value||b.value,this.css=/css(\?.*)?$/.test(this.path),this.css||c.push(this.path,function(b,c){b&&(b.index=e),f.root=c||new a.Ruleset([],[])})},a.Import.prototype={toCSS:function(a){var b=this.features?" "+this.features.toCSS(a):"";return this.css?"@import "+this._path.toCSS()+b+";\n":""},eval:function(b){var c,d=this.features&&this.features.eval(b);if(this.css)return this;c=new a.Ruleset([],this.root.rules.slice(0));for(var e=0;e1){var d=new a.Element("&",null,0),e=[new a.Selector([d])];c=new a.Ruleset(e,b.mediaBlocks),c.multiMedia=!0}return delete b.mediaBlocks,delete b.mediaPath,c},evalNested:function(b){var c,d,e=b.mediaPath.concat([this]);for(c=0;c0;c--)b.splice(c,0,new a.Anonymous("and"));return new a.Expression(b)})),new a.Ruleset([],[])},permute:function(a){if(a.length===0)return[];if(a.length===1)return a[0];var b=[],c=this.permute(a.slice(1));for(var d=0;d0){c=this.arguments&&this.arguments.map(function(b){return b.eval(a)});for(var g=0;gthis.params.length)return!1;if(this.required>0&&c>this.params.length)return!1}if(this.condition&&!this.condition.eval({frames:[this.evalParams(b,a)].concat(b.frames)}))return!1;d=Math.min(c,this.arity);for(var f=0;fe.selectors[g].elements.length?Array.prototype.push.apply(d,e.find(new a.Selector(b.elements.slice(1)),c)):d.push(e);break}}),this._lookups[g]=d)},toCSS:function(b,c){var d=[],e=[],f=[],g=[],h,i;this.root||(b.length===0?g=this.selectors.map(function(a){return[a]}):this.joinSelectors(g,b,this.selectors));for(var j=0;j0&&(h=g.map(function(a){return a.map(function(a){return a.toCSS(c)}).join("").trim()}).join(c.compress?",":",\n"),d.push(h,(c.compress?"{":" {\n ")+e.join(c.compress?"":"\n ")+(c.compress?"}":"\n}\n"))),d.push(f),d.join("")+(c.compress?"\n":"")},joinSelectors:function(a,b,c){for(var d=0;d0&&e.push(new a.Selector(g)),h.length>0&&f.push(new a.Selector(h));for(var l=0;l0&&(b.value=c[0]+(b.value.charAt(0)==="/"?b.value.slice(1):b.value)),this.value=b,this.paths=c)},b.URL.prototype={toCSS:function(){return"url("+(this.attrs?"data:"+this.attrs.mime+this.attrs.charset+this.attrs.base64+this.attrs.data:this.value.toCSS())+")"},eval:function(a){return this.attrs?this:new b.URL(this.value.eval(a),this.paths)}}}(c("../tree")),function(a){a.Value=function(a){this.value=a,this.is="value"},a.Value.prototype={eval:function(b){return this.value.length===1?this.value[0].eval(b):new a.Value(this.value.map(function(a){return a.eval(b)}))},toCSS:function(a){return this.value.map(function(b){return b.toCSS(a)}).join(a.compress?",":", ")}}}(c("../tree")),function(a){a.Variable=function(a,b,c){this.name=a,this.index=b,this.file=c},a.Variable.prototype={eval:function(b){var c,d,e=this.name;e.indexOf("@@")==0&&(e="@"+(new a.Variable(e.slice(1))).eval(b).value);if(c=a.find(b.frames,function(a){if(d=a.variable(e))return d.value.eval(b)}))return c;throw{type:"Name",message:"variable "+e+" is undefined",filename:this.file,index:this.index}}}}(c("../tree")),function(a){a.find=function(a,b){for(var c=0,d;c1?"["+a.value.map(function(a){return a.toCSS(!1)}).join(", ")+"]":a.toCSS(!1)}}(c("./tree"));var f=location.protocol==="file:"||location.protocol==="chrome:"||location.protocol==="chrome-extension:"||location.protocol==="resource:";d.env=d.env||(location.hostname=="127.0.0.1"||location.hostname=="0.0.0.0"||location.hostname=="localhost"||location.port.length>0||f?"development":"production"),d.async=!1,d.poll=d.poll||(f?1e3:1500),d.watch=function(){return this.watchMode=!0},d.unwatch=function(){return this.watchMode=!1},d.env==="development"?(d.optimization=0,/!watch/.test(location.hash)&&d.watch(),d.watchTimer=setInterval(function(){d.watchMode&&m(function(a,b,c,d,e){b&&p(b.toCSS(),d,e.lastModified)})},d.poll)):d.optimization=3;var g;try{g=typeof a.localStorage=="undefined"?null:a.localStorage}catch(h){g=null}var i=document.getElementsByTagName("link"),j=/^text\/(x-)?less$/;d.sheets=[];for(var k=0;k +* +* For the full copyright and license information, please view the LICENSE +* file that was distributed with this source code. +*/ + +/* + * Projet : TraKERS + * Module : Front IDILL + * Fichier : index.html + * + * Auteur : alexandre.bastien@iri.centrepompidou.fr + * + * Fonctionnalités : Centralise les différents éléments du Front IDILL, tels que les classes javascript, les fonctions jQuery, les css. + */ +--> + + + + + + IDILL + + + + + + + + + + + +
    +
    + + +
    + + + + + \ No newline at end of file diff -r fcf435874395 -r 45c889eae324 front_idill/src/mosaic/css/mosaic.less --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/front_idill/src/mosaic/css/mosaic.less Fri Apr 27 14:38:23 2012 +0200 @@ -0,0 +1,107 @@ +/* +* This file is part of the TraKERS\Front IDILL package. +* +* (c) IRI +* +* For the full copyright and license information, please view the LICENSE +* file that was distributed with this source code. +*/ + +/* + * Projet : TraKERS + * Module : Front IDILL + * Fichier : mosaic.less + * + * Auteur : alexandre.bastien@iri.centrepompidou.fr + * + * Fonctionnalités : Définit les propriétés d'apparence des éléments de base de la mosaïque (les snapshots, la mosaïque en elle-même). + * + * Avertissement : Afin que ce fichier puisse compiler, il est nécessaire de lancer index.html depuis un chemin ne commencant pas par file:///. + * C'est pourquoi j'utilise WAMP pour le lancer. + */ + +@mosaic-border-tickness: 1px; +@mosaic-background-color: #202020; +@mosaic-background-image-path: url("../../img/background.png"); +@selected-snapshot-background-image-path: url("../../img/selected_background.png"); +@snapshots-background-color: #8D8D8D; +@snapshots-margin-value: 5px; +@snapshots-margin: @snapshots-margin-value @snapshots-margin-value @snapshots-margin-value @snapshots-margin-value; +@black: #000000; + +body +{ + overflow: hidden; + background-color: @black; +} + +/* + * Il s'agit des propriétés de la mosaïque en elle même. + * On désactive les barres de défilement, on peut la placer à n'importe qu'elle position, elle doit être aussi large que la fenêtre du navigateur. + * Son fond se répète. + */ +#mainPanel +{ + overflow: hidden; + position: absolute; + width: 100%; + top: 0px; + left: 0px; + background-image: @mosaic-background-image-path; + background-repeat: repeat; +} + +/* + * Les divs contenant les snapshots (ou les "voisins" aussi en cas de zoom total). Ils se positionnent par défaut de gauche à droite, à l'horizontale et wrap dès + * qu'ils ont atteint la bordure de fenêtre de droite. + */ +.snapshotDivs, .neighbourDivs +{ + background-color: @black; + margin: @snapshots-margin; + float: left; +} + +/* + * Les snapshots sont des images, elles doivent remplir l'intégralité de leurs divs (snapshotDivs). + */ +.snapshots +{ + width: 100%; + height: 100%; +} + +/* + * Ce sont des divs créés spécialement lors d'un prézoom. Leur fonction est d'afficher un clone du snapshot, superposé au précédent et de grandir un peu de manière + * à faire ressortir visuellement le snapshot pointé. Leur bordure est d'une couleur différente au fond, ce qui permet de les discerner plus facilement dans la mosaïque. + * au départ, lors de sa création, il est caché, mais apparaît dès que l'image est chargée. + */ +.prezoomContainers +{ + position: absolute; + display: none; + background-image: @selected-snapshot-background-image-path; + background-repeat: repeat; +} + +/* + * Cette classe est attachée à des divs destinés à remplir les bordures d'une mosaïque locale. + */ +.blacks +{ + background-color: @black; + float: left; +} + +/* + * C'est une classe appliquée aux divs "voisins", afin de les colorer lorsque l'utilisateur intéragit avec eux. + * Ils se positionnent exactement sur le voisin qu'ils représentent, à la manière du clone de prézoom (prezoomContainer), bien que celui-là n'est qu'un div simple + * ne contenant pas d'image. + * Au départ, l'opacité est à 0, ce qui signifie que ce div est invisible. L'opacité change lors d'intéractions avec cet objet. Le div apparaît alors. + */ +.cyan +{ + position: absolute; + background-color: #94C6C5; + opacity: 0; +} \ No newline at end of file diff -r fcf435874395 -r 45c889eae324 front_idill/src/mosaic/css/reset.css --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/front_idill/src/mosaic/css/reset.css Fri Apr 27 14:38:23 2012 +0200 @@ -0,0 +1,48 @@ +/* http://meyerweb.com/eric/tools/css/reset/ + v2.0 | 20110126 + License: none (public domain) +*/ + +html, body, div, span, applet, object, iframe, +h1, h2, h3, h4, h5, h6, p, blockquote, pre, +a, abbr, acronym, address, big, cite, code, +del, dfn, em, img, ins, kbd, q, s, samp, +small, strike, strong, sub, sup, tt, var, +b, u, i, center, +dl, dt, dd, ol, ul, li, +fieldset, form, label, legend, +table, caption, tbody, tfoot, thead, tr, th, td, +article, aside, canvas, details, embed, +figure, figcaption, footer, header, hgroup, +menu, nav, output, ruby, section, summary, +time, mark, audio, video { + margin: 0; + padding: 0; + border: 0; + font-size: 100%; + font: inherit; + vertical-align: baseline; +} +/* HTML5 display-role reset for older browsers */ +article, aside, details, figcaption, figure, +footer, header, hgroup, menu, nav, section { + display: block; +} +body { + line-height: 1; +} +ol, ul { + list-style: none; +} +blockquote, q { + quotes: none; +} +blockquote:before, blockquote:after, +q:before, q:after { + content: ''; + content: none; +} +table { + border-collapse: collapse; + border-spacing: 0; +} \ No newline at end of file diff -r fcf435874395 -r 45c889eae324 front_idill/src/mosaic/js/localMosaic.js --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/front_idill/src/mosaic/js/localMosaic.js Fri Apr 27 14:38:23 2012 +0200 @@ -0,0 +1,106 @@ +/* +* This file is part of the TraKERS\Front IDILL package. +* +* (c) IRI +* +* For the full copyright and license information, please view the LICENSE +* file that was distributed with this source code. +*/ + +/* + * Projet : TraKERS + * Module : Front IDILL + * Fichier : localMosaic.js + * + * Auteur : alexandre.bastien@iri.centrepompidou.fr + * + * Fonctionnalités : Définit la "classe" mosaïque locale (lors d'un zoom sur une mosaïque) et définit des fonctions d'intéractions. + */ + +/* + * Classe définissant la mosaïque locale. + * Elle sera toujours de la forme 3x3, même si toutes les cases ne seront pas remplies par des snapshots (cas des bords et coins). +*/ +function localMosaic(len, imgToShow, marginWidth) +{ + if(imgToShow % len == 0) + { + this.length = len; + this.imagesToShow = imgToShow; + this.centerId; + this.urls = []; + this.imgs = []; + this.ids = []; + this.width; + this.height; + this.marginWidth = marginWidth; + this.zoomed; + this.snapshotTop; + this.snapshotLeft; + this.snapshotWidth; + this.snapshotHeight; + } + else + { + //Affiche un message d'erreur. + } +} + +/* + * Crée la mosaïque locale, qui est une partie de la mosaïque de mosaic.js. + * Il y a le snapshot sur lequel on a zoomé, et les 8 snapshots voisins. +*/ +localMosaic.prototype.createLocalMosaic = function() +{ + var str = ''; + + var t = this.coord1Dto2D(this.centerId); + var localId; + + for(var a = t[1] - 1 ; a < t[1] + 2 ; a++) + for(var b = t[0] - 1 ; b < t[0] + 2 ; b++) + if(a > -1 && a < this.imagesToShow / this.length && b > -1 && b < this.length) + { + localId = this.coord2Dto1D(a, b); + str += '
    '; + } + else + str += '
    '; + + return str; +} + +/* + * Permet de charger la mosaïque locale. +*/ +localMosaic.prototype.loadLocalMosaic = function(snTop, snLeft, snWidth, snHeight, imgsTab, id) +{ + //On affecte les chemins vers les images à la mosaïque. + this.imgs = imgsTab; + this.centerId = id; + this.snapshotTop = snTop;//*(newPreMPHeight/initMPHeight) - this.zoomedMargin/2 + (initMPHeight - initMPHeight * this.zoomPercentage)/2 + 'px'; + this.previousMPLeft = snLeft; + this.snapshotWidth = snWidth; + this.snapshotHeight = snHeight; + //On met à jour la mosaïque. + $('#mainPanel').html(this.createLocalMosaic(id)); + $('.snapshotDivs').css('width', snWidth).css('height', snHeight).css('margin', this.marginWidth/2); + // var lMosTop = , newZoomLeft = -this.previousZoomedSN.position().left*(newPreMPWidth/initMPWidth) - this.zoomedMargin/2 + (initMPWidth - initMPWidth * this.zoomPercentage)/2 + 'px'; + $('#mainPanel').css('top', 0).css('left', 0); +} + +/* + * Change de 1 à 2 dimensions pour les coordonnées des snapshots dans la mosaïque. +*/ +localMosaic.prototype.coord1Dto2D = function(i) +{ + return [i%length, Math.floor(i/this.length)]; +} + +/* + * Change de 2 à 1 dimension pour les coordonnées des snapshots dans la mosaïque. +*/ +localMosaic.prototype.coord2Dto1D = function(i, j) +{ + return j * this.length + i; +} \ No newline at end of file diff -r fcf435874395 -r 45c889eae324 front_idill/src/mosaic/js/mosaic.js --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/front_idill/src/mosaic/js/mosaic.js Fri Apr 27 14:38:23 2012 +0200 @@ -0,0 +1,596 @@ +/* +* This file is part of the TraKERS\Front IDILL package. +* +* (c) IRI +* +* For the full copyright and license information, please view the LICENSE +* file that was distributed with this source code. +*/ + +/* + * Projet : TraKERS + * Module : Front IDILL + * Fichier : mosaic.js + * + * Auteur : alexandre.bastien@iri.centrepompidou.fr + * + * Fonctionnalités : Définit la "classe" mosaïque et définit des fonctions d'intéractions. + */ + +/* + * Classe définissant la mosaïque. + * Elle contient sa longueur, le nombre d'images total, une liste d'urls pour les vidéos, leurs snapshots principaux et leur position. + * Contient également les dimensions en px de la mosaïque. + */ +function mosaic(len, imgToShow, zoomPercentage, prezoomPercentage, zoomedMargin) +{ + //S'il s'agit d'un rectangle. + if(imgToShow % len == 0) + { + //Longueur horizontale. + this.length = len; + //Nombre d'images dans la mosaïque. + this.imagesToShow = imgToShow; + //Tableaux des urls des vidéos, des snapshots et de leur position dans la mosaïque. + this.urls = []; + this.imgs = []; + this.ids = []; + //Dimensions de la mosaïque en pixels. + this.width; + this.height; + //Dimensions d'un snapshot en pixels. + this.snapshotWidth; + this.snapshotHeight; + //Espacement entre les snapshots en pixels. + this.marginWidth; + + //Temps d'intéractions/d'animations. + this.preZoomTime; + this.preUnzoomTime; + this.zoomTime; + this.unzoomTime; + this.timeNeighbourGlowing; + this.timeNeighbourUnglowing; + this.timeMovingToNeighbour; + + //Booléens permettant ou non certaines intéractions selon le contexte. + this.zoomed; + this.fullscreen; + this.canMoveToNeighbour; + + //Mode actuel. + this.currentMode; + //Snapshot sur lequel on a zoomé. + this.previousZoomedSN; + //Son ID. + this.previousId; + //Largeur de la marge pour le centrage vertical de la mosaïque. + this.MPTop_margin; + this.top_margin; + //Pourcentage d'agrandissement lors d'un prézoom et d'un zoom. + this.prezoomPercentage = prezoomPercentage; + this.zoomPercentage = zoomPercentage; + //Espacement des snapshots après un zoom. + this.zoomedMargin = zoomedMargin; + //Mosaïque locale. + this.localMos; + //Position des voisins lors d'un zoom. + this.neighboursIds = []; + //ID du snapshot du milieu lors d'un zoom. + this.centerId; + } + else + { + //Affiche un message d'erreur. + } +} + +/* + * Méthode d'affichage de la mosaïque. + * Génère une matrice de imgs. + */ +mosaic.prototype.createMosaic = function() +{ + this.previousZoomedSN = ''; + this.previousPrezoomDiv = ''; + this.fullscreen = false; + this.canMoveToNeighbour = false; + var str = ''; + + if(this.imgs.length >= this.imagesToShow) + { + for(var i = 0 ; i < this.imagesToShow ; i++) + { + //On charge les images de petite taille pour ne pas surcharger la mosaïque lors de l'affichage global. + str += '
    '; + } + } + + return str; +} + +/* + * Permet de raffraichir la mosaïque. + */ +mosaic.prototype.loadMosaic = function(imgsTab) +{ + //On affecte les chemins vers les images à la mosaïque. + this.imgs = imgsTab; + this.previousZoomedSN; + //this.width = + //On met à jour la mosaïque. + $('#mainPanel').html(this.createMosaic()); + //On récupère la taille des bordures. + this.marginWidth = $('.snapshotDivs').css('margin-bottom'); + this.marginWidth = parseFloat(mos.marginWidth)*2; + //On calcule la taille des divs contenant les snapshots. + this.width = $('#mainPanel').innerWidth(); + //On ne calculera pas tout de suite la hauteur de la mosaique étant donnée qu'elle est calculée par la suite dynamiquement. + this.snapshotWidth = this.width / this.length - this.marginWidth; + this.snapshotHeight = this.snapshotWidth*9/16; + $('.snapshotDivs').css('width', this.snapshotWidth).css('height', this.snapshotHeight).css('margin', this.marginWidth/2); + + this.height = $('#mainPanel').innerHeight(); + //On centre verticalement la mosaïque. + this.MPTop_margin = ($(document).height() - $('#mainPanel').height())/2; + $('#mainPanel').css('margin-top', this.MPTop_margin).css('margin-bottom', this.MPTop_margin); +} + +/* + * Zoom sur la position d'une image, 1ère partie. Durant le laps de temps de time ms, l'utilisateur a le choix de zoomer sur une autre image. + * Après ce laps de temps, l'image zoom complétement et il n'est plus possible de sélectionner une autre image par pointage. + */ +mosaic.prototype.preZoom = function(snapshot) +{ + if(this.fullscreen) + return; + //Mosaïque. + var mosaic = this; + //Dimensions de la mosaïque. + var h = this.height, w = this.width; + //Longueur en images, nombre d'images et taille de bordure de la mosaïque. + var len = this.length, imgs = this.imagesToShow, margin = this.marginWidth; + //Dimensions et position d'un snapshot dans la mosaïque. + var snHeight = this.snapshotHeight, snWidth = this.snapshotWidth; + var sTop = snapshot.position().top, sLeft = snapshot.position().left; + var prezoomPercentage = this.prezoomPercentage; + + //ID de l'image actuelle. + var currentId = $('img', snapshot).attr('id'); + + //Si un zoom est déjà en cours, on ne zoom sur rien d'autre en attendant que ce snapshot ai dézoomé en cas de mouseleave. + if(this.zoomed) + if($('#preZoomContainer-' + currentId) != $(this) && this.previousZoomedSN != '' && this.previousId != '') + this.preUnzoom(); + else + return; + + //On indique qu'on a zoomé et on spécifie le snapshot sur lequel on a zoomé. + this.zoomed = true; + this.previousZoomedSN = snapshot; + this.previousId = currentId; + + //On récupère les attributs de l'image. + var fakeImg = $('img', snapshot); + //On forme la balise de la fausse image et on passe son url pour les grands snapshots. + fakeImg = ''; + //On génère un faux snapshot identique au précédent et qu'on va coller dessus. + var fakeSnapshot = '
    ' + fakeImg + '
    '; + + //On l'ajoute à la mosaïque. + $('#mainPanel').append(fakeSnapshot); + //On modifie ses attributs. + $('#fake-' + currentId).load(function() + { + $('#prezoomContainer-' + currentId).css('display', 'block'); + $('#prezoomContainer-' + currentId).css('top', sTop).css('left', sLeft).css('width', (snWidth + margin)).css('height', (snHeight + margin)); + $('#prezoomSnapshot-' + currentId).css('width', (snWidth)).css('height', (snHeight)); + + //Dimensions et coordonnées initiales du div sur lequel on zoom. + var initialDivWidth = $('#prezoomContainer-' + currentId).width(), initialDivHeight = $('#prezoomContainer-' + currentId).height(); + var initialDivTop = $('#prezoomContainer-' + currentId).position().top, initialDivLeft = $('#prezoomContainer-' + currentId).position().left; + //Dimensions et coordonnées finales du div. + var finalDivWidth = initialDivWidth * (prezoomPercentage+1), diffWidth = finalDivWidth - initialDivWidth, finalDivHeight = initialDivHeight + diffWidth; + var finalDivTop = (initialDivTop - (finalDivHeight - snHeight)/2), finalDivLeft = (initialDivLeft - (finalDivWidth - snWidth)/2); + + //CAS PARTICULIER pour la position du snapshot zoomé : les bordures. + if(finalDivTop < 0) + finalDivTop = -margin; + if(finalDivTop + finalDivHeight > h) + finalDivTop = h - finalDivHeight; + if(finalDivLeft < 0) + finalDivLeft = 0; + if(finalDivLeft + finalDivWidth + margin*2 > w) + finalDivLeft = w - finalDivWidth - margin*2; + + ////Code de debug. + ////CAUTION//// + /*var red = '
    '; + if($('#red') != null || $('#red') != undefined) + $('body').append(red); + $('#red').css('background-color', '#FF0000').css('position', 'absolute').css('top', '0px').css('left', '0px').css('width', '100px').css('height', '100px'); + $('#red').css('top', finalDivTop).css('left', finalDivLeft).css('width', finalDivWidth).css('height', finalDivHeight);*/ + //alert("initial : " + initialDivWidth + " " + initialDivHeight + " ; final : " + finalDivWidth + " " + finalDivHeight); + ////CAUTION//// + + //On prézoom le div en le centrant sur le milieu du snapshot pointé. + $('#prezoomSnapshot-' + currentId).animate( + { + width: finalDivWidth + margin, + height: finalDivHeight - margin*2, + top: finalDivTop + margin, + left: finalDivLeft + margin + }, this.preZoomTime); + $('#prezoomContainer-' + currentId).animate( + { + width: finalDivWidth + margin*2, + height: finalDivHeight - margin, + top: finalDivTop + margin, + left: finalDivLeft + }, this.preZoomTime); + }); + + //Si on clique sur le snapshot prézoomé, on enclenche un zoom total sur ce snapshot. + $('#prezoomContainer-' + currentId).click(function () + { + if(this.previousZoomedSN != '') + mosaic.zoom(); + }); +} + +/* + * Dézoome sur la position de l'image. Il est à noter que ce dézoome diffère du dézoom global dans la mesure où celui-ci ne concerne que l'image sur laquelle on a zoomé. + */ +mosaic.prototype.preUnzoom = function() +{ + //Si on n'a pas zoomé, on quitte la fonction. + if(!this.zoomed) + return; + + //On spécifie la marge afin de centrer le prédézoom. + var margin = this.marginWidth; + //ID du snapshot précédemment pointé. + var id = this.previousId; + //On ne zoom plus. + this.zoomed = false; + //On rétrécit le snapshot de prézoom, puis on le supprime en donnant l'illusion qu'il s'agissait du véritable snapshot, alors qu'en fait c'était un clone. + $('#prezoomSnapshot-' + id).animate( + { + width: this.snapshotWidth, + height: this.snapshotHeight, + top: this.previousZoomedSN.position().top, + left: this.previousZoomedSN.position().left + }, this.preUnzoomTime); + $('#prezoomContainer-' + id).animate( + { + width: this.snapshotWidth + margin, + height: this.snapshotHeight + margin, + top: this.previousZoomedSN.position().top, + left: this.previousZoomedSN.position().left + }, this.preUnzoomTime, function(){ $(this).remove(); this.zoomed = false; }); +} + + +/* + * Zoom d'un snapshot en plein écran. + */ +mosaic.prototype.zoom = function() +{ + var mos = this; + + //Si la mosaïque est en pleine écran, pas la peine de zoomer. + if(this.fullscreen) + return; + + //On prend les attributs nécessaires au calculs. + var margin = this.marginWidth, len = this.length, imgs = this.imagesToShow; + var initMPWidth = this.previousZoomedSN.width() * len + margin*len, initMPHeight = this.previousZoomedSN.height() * (imgs / len) + margin*(imgs / len); + var newMPWidth = initMPWidth * len + this.zoomedMargin * (len), newMPHeight = initMPHeight * (imgs / len) + this.zoomedMargin * ((imgs / len)); + var newPreMPWidth = initMPWidth * len * this.zoomPercentage + this.zoomedMargin * (len), newPreMPHeight = initMPHeight * (imgs / len) * this.zoomPercentage + this.zoomedMargin * ((imgs / len)); + + //Dimensions et coordonnées initiales du div sur lequel on zoom. + var initialDivWidth = this.previousZoomedSN.width(), initialDivHeight = this.previousZoomedSN.height(); + var initialDivTop = this.previousZoomedSN.position().top, initialDivLeft = this.previousZoomedSN.position().left; + //Dimensions et coordonnées finales du div. + var finalDivWidth = initialDivWidth * (this.zoomPercentage+1), finalDivHeight = initialDivHeight * (this.zoomPercentage+1); + var newZoomTop = -this.previousZoomedSN.position().top*(newPreMPHeight/initMPHeight) - this.zoomedMargin/2 + (initMPHeight - initMPHeight * this.zoomPercentage)/2 + 'px', newZoomLeft = -this.previousZoomedSN.position().left*(newPreMPWidth/initMPWidth) - this.zoomedMargin/2 + (initMPWidth - initMPWidth * this.zoomPercentage)/2 + 'px'; + var newSnWidth = initMPWidth * this.zoomPercentage, newSnHeight = initMPHeight * this.zoomPercentage; + + this.preUnzoom(this); + /*SINGULARITE*/ + this.fullscreen = true; + + //On passe l'image du snapshot pointé en HD. + var zoomedImg = $('img', this.previousZoomedSN); + var src = zoomedImg.attr('src'); + zoomedImg.attr('src', src.replace('-little/', '/')); + + //On récupère son ID. + var tab, zoomedImgId; + tab = mos.previousId.split('-'); + zoomedImgId = tab[1]; + + //Les snapshots baissent alors en opacité, donnant l'impression qu'ils sont grisés. + $('.snapshotDivs').animate( + { + width: newSnWidth, + height: newSnHeight, + margin: this.zoomedMargin/2 + 'px', + opacity: '0.4' + }, this.zoomTime); + //Le snapshot du milieu revient à une opacité optimale, ce qui attire l'attention de l'utilisateur. + $(this.previousZoomedSN).animate( + { + opacity: '1' + }, this.zoomTime); + //On zoome sur la mosaïque. + $('#mainPanel').animate( + { + width: newPreMPWidth, + height: newPreMPHeight, + top: newZoomTop, + left: newZoomLeft + }, this.zoomTime, function() + { + //On charge les interactions avec les voisins. + mos.centerId = zoomedImgId; + mos.listenToNeighbours(); + mos.currentMode = 'VIDEO'; + /*mos.unload(); + mos.localMos.loadLocalMosaic(newZoomTop, newZoomLeft, newSnWidth, newSnHeight, mos.imgs, tab[1]);*/ + }); +} + +/* + * Retour à la taille normale de la mosaïque. + */ +mosaic.prototype.unzoom = function() +{ + //Si on n'est pas en plein écran, on quitte. + if(!this.fullscreen) + return; + + //On charge les attributs nécessaires aux calculs. + var sWidth = this.snapshotWidth, sHeight = this.snapshotHeight; + var mpWidth = this.width, mpHeight = this.height; + var mos = this; + + //On passe le snapshot sur lequel on a zoomé en LD. + var zoomedImg = $('img', this.previousZoomedSN); + var src = zoomedImg.attr('src'); + zoomedImg.attr('src', src.replace('snapshots/', 'snapshots-little/')); + + //On rend leur opacité aux snapshots. Qui ne sont alors plus grisés. + $('.snapshotDivs').animate( + { + width: sWidth, + height: sHeight, + margin: this.marginWidth/2 + 'px', + opacity: '1' + }, this.unzoomTime); + //On dézoom sur la mosaïque. + $('#mainPanel').animate( + { + width: mpWidth, + height: mpHeight, + top: '0px', + left: '0px' + }, this.unzoomTime, function() + { + //On n'est plus en plein écran, et on ne peut plus se déplacer vers le prochain voisin. + mos.fullscreen = false; + mos.canMoveToNeighbour = false; + //On revient en mode MOSAIC. + mos.currentMode = 'MOSAIC'; + //On ne permet plus le déplacement vers les voisins. + $('.snapshotDivs').unbind('mouseenter', mos.changeNeighbourColor); + }); +} + +/* + * Affecte les listeners mouseenter aux voisins lors d'une vue en plein écran. + */ +mosaic.prototype.listenToNeighbours = function() +{ + ////TEST + //$('.test').empty(); + this.canMoveToNeighbour = false; + var currentLine = Math.floor(this.centerId / this.length), currentColumn = this.centerId % this.length; + var zoomedImg = $('img', this.previousZoomedSN); + var mos = this; + + //On cherche l'ID des voisins. + //Si le voisin de gauche est sur la même ligne, on n'est pas sur la bordure de gauche. + this.neighboursIds[0] = (currentColumn > 0) ? (this.centerId - 1) : -1; + //Si le voisin de droite est sur la même ligne, on n'est pas sur la bordure de droite. + this.neighboursIds[1] = (currentColumn < this.length) ? (+this.centerId + 1) : -1; + //Si le voisin du haut est sur la même colonne, on n'est pas sur la bordure du haut. + this.neighboursIds[2] = (currentLine > 0) ? (this.centerId - this.length) : -1; + //Si le voisin du bas est sur la même colonne, on n'est pas sur la bordure du bas. + this.neighboursIds[3] = (currentLine < (this.imagesToShow / this.length)) ? (+this.centerId + this.length) : -1; + + for(var i = 0 ; i < this.neighboursIds.length ; i++) + { + if(this.neighboursIds[i] != -1) + { + //On permet le déplacement vers les voisins. + $('#snapshotDiv-' + this.neighboursIds[i]).mouseenter(mos.changeNeighbourColor); + } + } +} + +/* + * Change la coloration d'une bordure où on se positionne lors d'une vue en plein écran. + */ +mosaic.prototype.changeNeighbourColor = function() +{ + ////TEST + //$('.test').append(mos.currentMode + " " + $(this).attr('id') + " " + 'snapshotDiv-' + mos.centerId + ','); + + //Si on est en mode VIDEO (plein écran) ET si le snapshot pointé est un voisin. + if((mos.currentMode == 'VIDEO') && ($(this).attr('id') != 'snapshotDiv-' + mos.centerId)) + { + //On crée le div cyan qui va être superposé au voisin. + var cyanDiv = '
    '; + //On le colle au voisin. + $('#mainPanel').append(cyanDiv); + $('#cyan-' + $(this).attr('id')).css('top', $(this).position().top).css('left', $(this).position().left).css('width', $(this).width()).css('height', $(this).height()).css('margin', $(this).css('margin')).animate( + { + //On le fait apparaître. + opacity: '0.4' + }, timeNeighbourUnglowing, function() + { + //On peut désormais se déplacer vers ce voisin. + mos.canMoveToNeighbour = true; + }).mouseleave(mos.unchangeNeighbourColor).click(mos.moveToNeighbour); + } +} + +/* + * Change la coloration d'une bordure quittée lors d'une vue en plein écran. + */ +mosaic.prototype.unchangeNeighbourColor = function() +{ + ////TEST + //$('.test').append('un,'); + + //On ne peut plus se déplacer vers les voisins. + mos.canMoveToNeighbour = false; + + //Si on est en mode VIDEO. + if(mos.currentMode == 'VIDEO') + { + //On obtient le div de coloration superposé au voisin. + var cyanDiv = $(this); + + //On le fait disparaître progressivement. + $(this).animate( + { + opacity: '0' + }, timeNeighbourGlowing, function() + { + //Une fois invisible, on le supprime. + cyanDiv.remove(); + }); + } +} + +/* + * Lors d'une vue en plein écran, on se déplace vers le voisin dont l'id a été spécifié dans la fonction appelante. + */ +mosaic.prototype.moveToNeighbour = function() +{ + //Si on ne peut pas se déplacer vers les voisins, on quitte. + if(!mos.canMoveToNeighbour) + return; + + //On obtient l'ID de destination. + var tab = $(this).attr('id').split('-'); + var destinationId = tab[2]; + + //On charge les attributs nécessaires aux calculs. + var MPCurrentTop = $('#mainPanel').position().top, MPCurrentLeft = $('#mainPanel').position().left; + var divideCoeffTop = Math.floor(destinationId / mos.length) == 0 ? 1 : Math.floor(destinationId / mos.length); + var divideCoeffLeft = destinationId % mos.length == 0 ? 1 : destinationId % mos.length; + var cyanTop = $(this).position().top, cyanLeft = $(this).position().left; + + //On définit pour le déplacement vertical s'il est nécessaire de se déplacer en haut ou en bas. + if(mos.previousZoomedSN.position().top > cyanTop) + MPCurrentTop += Math.abs(cyanTop - mos.previousZoomedSN.position().top); + else if(mos.previousZoomedSN.position().top < cyanTop) + MPCurrentTop -= Math.abs(cyanTop - mos.previousZoomedSN.position().top); + //On définit pour le déplacement horizontal s'il est nécessaire de se déplacer à gauche ou à droite. + if(mos.previousZoomedSN.position().left > cyanLeft) + MPCurrentLeft += Math.abs(cyanLeft - mos.previousZoomedSN.position().left); + else if(mos.previousZoomedSN.position().left < cyanLeft) + MPCurrentLeft -= Math.abs(cyanLeft - mos.previousZoomedSN.position().left); + + //On passe le snapshot de destination en HD. + var destinationImg = $('#snapshot-' + destinationId); + var destinationImgSrc = destinationImg.attr('src'); + destinationImg.attr('src', destinationImgSrc.replace('snapshots-little/', 'snapshots/')); + + //On passe l'ancien snapshot en LD. + var currentImgSrc = $('img', mos.previousZoomedSN).attr('src'); + $('img', mos.previousZoomedSN).attr('src', currentImgSrc.replace('snapshots/', 'snapshots-little/')); + + //On obtient l'ID du div de coloration du snapshot vers lequel on se déplace afin de le supprimer. + var cyan = $(this); + var tab = cyan.attr('id').split('-'); + mos.centerId = tab[2]; + $(this).css('opacity', '0'); + cyan.remove(); + + //On grise le snapshot qu'on vient de quitter. + mos.previousZoomedSN.animate( + { + opacity: '0.4' + }); + + //On se déplace. + $('#mainPanel').animate( + { + top: MPCurrentTop, + left: MPCurrentLeft + }, timeMovingToNeighbour, function() + { + //On fait apparaître le snapshot vers lequel on s'est déplacé. + $('#snapshotDiv-' + destinationId).animate( + { + opacity: '1' + }, mos.zoomTime, function() + { + //On recharge les voisins. + $('.snapshotDivs').unbind('mouseenter', mos.changeNeighbourColor); + mos.previousZoomedSN = $('#snapshotDiv-' + mos.centerId); + mos.listenToNeighbours(); + }); + }); +} + +/* + * Déchargement du contenu de la mosaïque pour le chargement de la mosaïque locale. + */ +mosaic.prototype.unload = function() +{ + //On supprime les event listeners des objets de la mosaïque. + $('.snapshotDivs').unbind(); + $('.snapshots').unbind(); + $('.prezoomContainers').unbind(); + //On supprime physiquement les objets. + $('#mainPanel').empty(); +} + +/* + * Centre verticalement un snapshot. + */ +/*function verticalCenterImg(mosaic, img) +{ + //On récupère sa hauteur. + var image_height = img.height(); + //Calcule la marge du haut de chaque div pour le centrage. + if(mosaic.top_margin == undefined) + mosaic.top_margin = (mosaic.snapshotHeight > image_height) ? (mosaic.snapshotHeight - image_height)/2 : (image_height - mosaic.snapshotHeight)/2; + //On centre le snapshot. + img.css('margin-top', mosaic.top_margin).css('margin-bottom', mosaic.top_margin); +}*/ + +/* + * Permet de tester l'égalité des éléments de deux objets. + * Pour ce faire on compare les éléments définissant ces objets. + */ +$.fn.equals = function(compareTo) +{ + if (!compareTo || !compareTo.length || this.length!=compareTo.length) + { + return false; + } + for (var i=0; i