geometry-4.0.0/0000755000000000000000000000000013615712371011542 5ustar0000000000000000geometry-4.0.0/COPYING0000644000000000000000000010451313615712371012601 0ustar0000000000000000 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 . geometry-4.0.0/DESCRIPTION0000644000000000000000000000071113615712371013247 0ustar0000000000000000Name: geometry Version: 4.0.0 Date: 03-02-2020 Author: Juan Pablo Carbajal , Philip Nienhuis , Simeon Simeonov , Maintainer: Juan Pablo Carbajal Title: Computational Geometry Description: Library for extending MatGeom functionality. Depends: octave (>= 4.2.0), matgeom (>= 1.0.0) Autoload: no License: GPLv3+, Boost v1.0 Url: https://octave.sourceforge.io/geometry/ geometry-4.0.0/INDEX0000644000000000000000000000125413615712371012336 0ustar0000000000000000geometry >> Computational Geometry 2D Polylines clipPolyline clipPolyline_clipper simplifyPolyline_geometry 2D Ellipses cov2ellipse ellipse2cov 2D Polygons clipPolygon clipPolygon_clipper clipPolygon_mrf drawFilledPolygon ispolycw ispolyccw isPolygonCCW isPolygonCW_Clipper joinPolygons orientPolygon polygon2patch polygon2shape poly2ccw poly2cw simplifyPolygon_geometry 2D Piecewise polynomial shapes curveval curve2polyline plotShape polygon2shape shape2polygon shapeCentroid transformShape 2D Others beltProblem Input [broken] @svg/svg @svg/plot @svg/getpath @svg/path2polygon @svg/normalize @svg/pathid @svg/height @svg/width Output data2geo geometry-4.0.0/NEWS0000644000000000000000000003623513615712371012252 0ustar0000000000000000Summary of important user-visible changes for releases of the geometry package =============================================================================== geometry-4.0.0 Release Date: 03-02-2020 Release Manager: Juan Pablo Carbajal =============================================================================== As of this version, geometry does not contain any matgeom functionality. It contains all the extra functions that we have been adding to geometry, in particular matlab compatible functionality for the mapping package. It might need that you do not need geometry anymore and instead you need to install matgeom to get the functionality you were using. Geometry was an attempt to port MatGeom (a geometry package developed for Matlab) to Octave, improving docstrings and updating to octave's special features when possible. Over time it became almost impossible to keep geometry in sync with the upstream developments of MatGeom. Hence I have decided to separate matgeom from geometry. My apologize for the troubles caused, this is the way I learn, by doing. Moreover, the @svg class is not working anymore. I leave it in the package but it should be considered broken. Will fix in future versions. ** Functions have been modified clipPolygon: - Accepts boolean operation as strings or as integer. - Accepts a box [xmin xmax ymin ymax] as clipping polygon. ** Added Functions drawFilledPolygon =============================================================================== geometry-3.0.0 Release Date: 27-03-2017 Release Manager: Juan Pablo Carbajal =============================================================================== This version of the package is not backward compatible for the following reasons: ** Functions have changed their name beltproblem --> beltProblem closed_path --> closedPath shapearea --> shapeArea shapecentroid --> shapeCentroid shapeplot --> plotShape shapetransform --> transformShape simplifypolygon --> simplifyPoligon simplifyPolyline --> simplifyPolyline ** Functions that are in GNU Octave core since 4.0.1 rad2deg deg2rad ** Added Functions isAxisHandle isPolygonCCW isPolygonCW_Clipper joinPolygons polygon2patch orientPolygon boundedVoronoi2d drawGraphEdges clipGraph grAdjacentEdges grAdjacentNodes grEdgeLengths centroidalVoronoi2d clipGraphPolygon cvtUpdate intersectEdgePolygon intersectLinePolygon isPointInPolygon polygonBounds polygonContains convexHull minimumCaliperDiameter grShortestPath drawNodeLabels nndist createRotation3dLineAngle drawPlane3d rotation3dAxisAndAngle boxToMesh checkMeshAdjacentFaces clipConvexPolyhedronHP clipMeshVertices createDodecahedron createDurerPolyhedron createIcosahedron createMengerSponge createOctahedron createRhombododecahedron createSoccerBall createTetrahedron createTetrakaidecahedron cylinderMesh drawFaceNormals drawPolyhedron ellipsoidMesh faceCentroids faceNormal intersectLineMesh3d intersectPlaneMesh mergeCoplanarFaces meshAdjacencyMatrix meshDihedralAngles meshEdgeFaces meshEdgeLength meshEdges meshFace meshFaceAdjacency meshFaceEdges meshFaceNumber meshFacePolygons meshSurfaceArea meshVolume minConvexHull polyhedra polyhedronCentroid polyhedronMeanBreadth polyhedronNormalAngle polyhedronSlice readMesh_off removeMeshVertices smoothMesh sphereMesh steinerPolytope subdivideMesh surfToMesh tetrahedronVolume torusMesh triangulateFaces trimMesh trimeshEdgeFaces trimeshMeanBreadth trimeshSurfaceArea vertexNormal distancePoints clipLine3d drawLine3d eulerAnglesToRotation3d intersectLineSphere linePosition3d recenterTransform3d transformLine3d transformVector3d intersectPolylines clipPolyline clipPolyline_clipper clipPolygon clipPolygon_clipper ** Improved Functions drawPolygon is more efficent when drawing polygons in cells and now it takes an axis handle as first argument (optional). Added demo and tests intersectEdges accepts tolerance as third argument polygon2patch demo fixed, missing third argument for patch. =============================================================================== geometry-2.1.1 Release Date: 2016-03-24 Release Manager: Juan Pablo Carbajal =============================================================================== ** Added Functions fillPolygon rectAsPolygon ** Improved Functions drawShape was not working due to missing functions. they have all been added now. ============================================================================== geometry-2.1.0 Release Date: 2016-02-04 Release Manager: Juan Pablo Carbajal =============================================================================== ** Added Functions projPointOnPolyline: the function is added for compatibility, but it is just a wrapper of distancePointPolyline. findClosestPoint ** Improved Functions distancePointPolyline is now updated with a spee dup of 100x. It also calculates the projections, so projPointOnPolyline is obsolete. =============================================================================== geometry-2.0.0 Release Date: 2015-04-27 Release Manager: Juan Pablo Carbajal =============================================================================== ** Geometry 2.0.0 is not compatible with versions of octave older than 4.0. Thi si due to inputParser being used in the functions curve2polyline, cov2ellipse and simplifypolyline. If you do not need this functions you should no problems using octave > 3.6.0 ** Removed functions oc_polybol is not part of geomtry anymore. This function is part of the octclip package. ** Added Functions planePoint ** Bug Fixes: - polynomialCurveSetFit had debug entries, now removed. ** Other changes: - closed_path demo code was improved. =============================================================================== geometry-1.7.0 Release Date: 2013-04-07 Release Manager: Juan Pablo Carbajal =============================================================================== ** Added Functions box3dVolume cart2cyl circle3dPoint cyl2cart drawCircle3d drawPoint3d createScaling3d drawCube createCube drawSphericalTriangle drawTorus revolutionSurface drawVector3d spheres drawPolyline drawPolynomialCurve polynomialCurveCentroid polynomialCurveDerivative polynomialCurveFit polynomialCurvePoint polynomialCurveSetFit polygonPoint polygonSubcurve ** Bug Fixes: - cov2ellipse scale and orientation of axis. =============================================================================== geometry-1.6.0 Release Date: 2012-10-12 Release Manager: Juan Pablo Carbajal =============================================================================== ** geometry doesn't autoloads anymore ** Added Functions anglePoints3d angles3d boxes3d geom3d_Contents lines3d planes3d points3d polygons3d vectors3d graphs_Contents meshes3d_Contents angleSort3d createPlane intersectLinePlane normalizePlane planeNormal planePosition projPointOnPlane sph2cart2 vectorAngle3d distancePointLine3d cart2sph2d createRotationOx createRotationOy createRotationOz createTranslation3d drawAxis3d drawCylinder drawSphere polygonArea3d transformPoint3d drawBox3d drawEdge3d drawMesh createCubeOctahedron boundingBox3d cart2sph2 circle3dOrigin circle3dPosition drawCircleArc3d drawPolygon3d drawSphericalEdge drawSphericalPolygon intersectPlaneSphere sph2cart2d ** Updated functions distancePoints ** Bug Fixes: - drawArrow was not working due to porting errors. =============================================================================== geometry-1.5.0 Release Date: 2012-06-05 Release Manager: Juan Pablo Carbajal =============================================================================== * Added functions: - cov2ellipse & ellipse2cov: transform between ellipses and covariances matrices. - beltproblem : Finds the four lines tangent to two circles with given centers and radii. This is the solution to the belt problem in 2D. - curveval : Evaluates a polynomial curve defined as a 2-by-N matrix. - curve2polyline : Converts a polynomial curve into a polyline by the adaptive sampling method. - simplifypolyline : Ramer-Douglas-Peucker algorithm to simplify polylines. - parametrize : Estimate a parametrization of a polygon/line based on the distance between the points. - curvature : Estimation of the curvature of a polygon/line based on polynomial approximation. - reversePolygon and reversePolyline : reverse the orders of the points in of polygon/line. - supportFunction : Compute support function of a polygon. - distancePointPolygon , distancePointPolyline , distancePolygons , expandPolygon , medialAxisConvex , polygonLoops , polygonSelfIntersections polylineSelfIntersections , splitPolygons - close_path : given a set of points in the plane calculate a piecewise linear simple path that passes through all points. * Changed functions: - distancePointEdge : Now the function computes the distance between all points and all edges. A third optional argument provides backward compatibility. * Solved bugs: - simplifypolygon returned empty polygons when points are repeated, i.e when the polygon is not correctly formed. - Removed installation warnings. =============================================================================== geometry-1.4.1 Release Date: 2012-03-24 Release Manager: Juan Pablo Carbajal =============================================================================== * Renamed functions - Contents renamed to geom2d_Contents to avoid clashes. * Deprecated functions - svgload, svgnormalize, svgpath2polygon: Use the methods in class svg. * Bug fixes - @svg/path2polygon - Fix addpath/rmpath installation warnings - Fix octclip/src/Makefile - Fix shapecentriod for piece-wise polynomial shapes. * Known issues - simplifypolygon returns empty polygons when points are repeated, i.e when the polygon is not correctly formed. =============================================================================== geometry-1.4.0 Release Date: 2012-01-25 Release Manager: Juan Pablo Carbajal =============================================================================== * Added basic geometric graphs creation and manipulation. =============================================================================== geometry-1.3.0 Release Date: 2011-11-24 Release Manager: Juan Pablo Carbajal =============================================================================== * Geometry merged with octCLIP. * Geometry autoloads. =============================================================================== geometry-1.2.2 Release Date: 2011-11-04 Release Manager: Juan Pablo Carbajal =============================================================================== * Improved SVG interface. Thanks to jwe and carandraug. * Adding files to manipulate and convert 2D shapes defined with smooth polynomials. shape2polygon shapearea shapecentroid shapeplot shapetransform * Inverted the order in the NEWS file. New entries are on top. =============================================================================== geometry-1.2.1 Release Date: 2011-11-02 Release Manager: Juan Pablo Carbajal =============================================================================== * Adding SVG object and demo for data2geom (converting SVG to msh format) =============================================================================== geometry-1.2.0 Release Date: 2011-10-21 Release Manager: Juan Pablo Carbajal =============================================================================== * All geom2d added createCircle createDirectedCircle createEdge medianLine Contents bisector cartesianLine drawArrow edges2d lines2d orthogonalLine parallelLine projPointOnLine drawCenteredEdge drawCircle drawCircleArc drawEllipse drawEllipseArc drawLabels drawOrientedBox drawParabola drawRect drawShape circles2d ellipses2d createVector inertiaEllipse changelog.txt readme.txt hexagonalGrid squareGrid triangleGrid intersectCircles intersectEdges intersectLineCircle isLeftOriented isPointInCircle isPointInEllipse isPointOnCircle isPointOnLine edgeLength edgePosition edgeToLine circleArcAsCurve circleAsPolygon crackPattern crackPattern2 distancePointEdge distancePointLine ellipseAsPolygon enclosingCircle radicalAxis reverseEdge reverseLine =============================================================================== geometry-1.1.3 Release Date: 2011-10-13 Release Manager: Juan Pablo Carbajal =============================================================================== * Continue to add geom2d from matGeom (transforms and points2d) createBasisTransform createHomothecy createLineReflection createRotation createScaling createTranslation transformPoint transforms2d fitAffineTransform2d transformEdge transformLine centroid distancePoints midPoint polarPoint drawPoint isCounterClockwise minDistancePoints pointOnLine points2d intersectLineEdge isPointOnEdge =============================================================================== geometry-1.1.2 Release Date: 2011-10-09 Release Manager: Juan Pablo Carbajal =============================================================================== * Continue to add geom2d from matGeom (rays and vectors) createRay drawEdge drawRay isParallel isPerpendicular isPointOnRay normalizeVector rays2d rotateVector transformVector vectorNorm vectors2d =============================================================================== geometry-1.1.1 Release Date: 2011-10-06 Release Manager: Juan Pablo Carbajal =============================================================================== * Continue to add geom2d from matGeom (boxes and clips) cbezier2poly boxes2d clipEdge clipLine clipPoints drawBezierCurve drawBox clipRay intersectBoxes intersectLines linePosition mergeBoxes randomPointInBox drawLine =============================================================================== geometry-1.1.0 Release Date: 2011-10-04 Release Manager: Juan Pablo Carbajal =============================================================================== * Starting to add geom2d from matGeom angle2Points angle3Points angleAbsDiff angleDiff angles2d angleSort createLine deg2rad edgeAngle lineAngle normalizeAngle rad2deg vectorAngle =============================================================================== geometry-1.0.1 Release Date: 2011-09-27 Release Manager: Juan Pablo Carbajal =============================================================================== Improvements to the docstrings of all functions. =============================================================================== geometry-1.0.0 Release Date: 2011-09-26 Release Manager: Juan Pablo Carbajal =============================================================================== ** First official release. =============================================================================== geometry-4.0.0/TODO0000644000000000000000000000017413615712371012234 0ustar0000000000000000* Bring back JuanPi's implementation of simplifyPolygon and simplifyPolyline ~ revision 522 or later * Make svg work again geometry-4.0.0/inst/0000755000000000000000000000000013615712371012517 5ustar0000000000000000geometry-4.0.0/inst/@svg/0000755000000000000000000000000013615712371013416 5ustar0000000000000000geometry-4.0.0/inst/@svg/display.m0000644000000000000000000000154313615712371015244 0ustar0000000000000000## Copyright (C) 2012 Juan Pablo Carbajal ## ## 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 . function display (obj) fields = fieldnames (obj); for i = 1 : numel(fields) printf ("#s\n", fields{i}); obj.(fields{i}) end endfunction geometry-4.0.0/inst/@svg/getpath.m0000644000000000000000000000405613615712371015235 0ustar0000000000000000## Copyright (C) 2012-2019 Juan Pablo Carbajal ## ## 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 . ## Author: Juan Pablo Carbajal ## Created: 2019-05-14 ## -*- texinfo -*- ## @deftypefn {Function File} {@var{paths} = } getpath (@var{ids}) ## Returns paths in @var{ids}. ## ## @end deftypefn function paths = getpath(obj, varargin) if !isempty(varargin) ids = varargin; if iscell (ids) && numel(ids) == 1 && iscell(ids{1}) # dealing with ids given as cell ids = ids{1}; if !all ( cellfun (@ischar, ids) ) print_usage end elseif !all ( cellfun (@ischar, ids) ) print_usage end else paths = obj.Path; return end tf = ismember (ids, fieldnames (obj.Path)); cellfun (@(s) printf("'#s' is not a valid path id.\n", s) , {ids{!tf}}); paths = []; if any (tf) stuff = {ids{tf}}; for i = 1: numel(stuff) paths{i} = obj.Path.(ids{i}).data; endfor # Variation # paths = cellfun(@(s) obj.Path.(s).data, stuff,'UniformOutput',false); # Another variation # paths = cellfun(@(s) getfield(obj,'Path').(s).data, stuff,'UniformOutput',false); # Yet another # paths = cellfun(@(s) getfield(obj.Path,s).data, stuff,'UniformOutput',false); # Yet yet another # dummy = @(s) obj.Path.(s).data; # paths = cellfun(dummy, stuff,'UniformOutput',false); if numel(paths) == 1 paths = paths{1}; end end endfunction geometry-4.0.0/inst/@svg/height.m0000644000000000000000000000155013615712371015045 0ustar0000000000000000## Copyright (C) 2012 Juan Pablo Carbajal ## ## 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 . ## -*- texinfo -*- ## @deftypefn {Function File} {} function_name () ## @end deftypefn function o = height(obj,varargin) o = obj.Data.height; endfunction geometry-4.0.0/inst/@svg/inkex.py0000644000000000000000000002004513615712371015107 0ustar0000000000000000#!/usr/bin/env python3 """ inkex.py A helper module for creating Inkscape extensions Copyright (C) 2005,2007 Aaron Spike, aaron@ekips.org 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 . """ import sys, copy, optparse, random, re import gettext from math import * _ = gettext.gettext #a dictionary of all of the xmlns prefixes in a standard inkscape doc NSS = { u'sodipodi' :u'http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd', u'cc' :u'http://creativecommons.org/ns#', u'ccOLD' :u'http://web.resource.org/cc/', u'svg' :u'http://www.w3.org/2000/svg', u'dc' :u'http://purl.org/dc/elements/1.1/', u'rdf' :u'http://www.w3.org/1999/02/22-rdf-syntax-ns#', u'inkscape' :u'http://www.inkscape.org/namespaces/inkscape', u'xlink' :u'http://www.w3.org/1999/xlink', u'xml' :u'http://www.w3.org/XML/1998/namespace' } #a dictionary of unit to user unit conversion factors uuconv = {'in':90.0, 'pt':1.25, 'px':1, 'mm':3.5433070866, 'cm':35.433070866, 'm':3543.3070866, 'km':3543307.0866, 'pc':15.0, 'yd':3240 , 'ft':1080} def unittouu(string): '''Returns userunits given a string representation of units in another system''' unit = re.compile('(%s)$' % '|'.join(uuconv.keys())) param = re.compile(r'(([-+]?[0-9]+(\.[0-9]*)?|[-+]?\.[0-9]+)([eE][-+]?[0-9]+)?)') p = param.match(string) u = unit.search(string) if p: retval = float(p.string[p.start():p.end()]) else: retval = 0.0 if u: try: return retval * uuconv[u.string[u.start():u.end()]] except KeyError: pass return retval def uutounit(val, unit): return val/uuconv[unit] try: from lxml import etree except: sys.exit(_('The fantastic lxml wrapper for libxml2 is required by inkex.py and therefore this extension. Please download and install the latest version from http://cheeseshop.python.org/pypi/lxml/, or install it through your package manager by a command like: sudo apt-get install python-lxml')) def debug(what): sys.stderr.write(str(what) + "\n") return what def errormsg(msg): """Intended for end-user-visible error messages. (Currently just writes to stderr with an appended newline, but could do something better in future: e.g. could add markup to distinguish error messages from status messages or debugging output.) Note that this should always be combined with translation: import gettext _ = gettext.gettext ... inkex.errormsg(_("This extension requires two selected paths.")) """ sys.stderr.write((unicode(msg) + "\n").encode("UTF-8")) def check_inkbool(option, opt, value): if str(value).capitalize() == 'True': return True elif str(value).capitalize() == 'False': return False else: raise optparse.OptionValueError("option %s: invalid inkbool value: %s" % (opt, value)) def addNS(tag, ns=None): val = tag if ns!=None and len(ns)>0 and NSS.has_key(ns) and len(tag)>0 and tag[0]!='{': val = "{%s}%s" % (NSS[ns], tag) return val class InkOption(optparse.Option): TYPES = optparse.Option.TYPES + ("inkbool",) TYPE_CHECKER = copy.copy(optparse.Option.TYPE_CHECKER) TYPE_CHECKER["inkbool"] = check_inkbool class Effect: """A class for creating Inkscape SVG Effects""" def __init__(self, *args, **kwargs): self.document=None self.ctx=None self.selected={} self.doc_ids={} self.options=None self.args=None self.OptionParser = optparse.OptionParser(usage="usage: %prog [options] SVGfile",option_class=InkOption) self.OptionParser.add_option("--id", action="append", type="string", dest="ids", default=[], help="id attribute of object to manipulate") def effect(self): pass def getoptions(self,args=sys.argv[1:]): """Collect command line arguments""" self.options, self.args = self.OptionParser.parse_args(args) def parse(self,file=None): """Parse document in specified file or on stdin""" try: try: stream = open(file,'r') except: stream = open(self.svg_file,'r') except: stream = sys.stdin self.document = etree.parse(stream) stream.close() def getposinlayer(self): #defaults self.current_layer = self.document.getroot() self.view_center = (0.0,0.0) layerattr = self.document.xpath('//sodipodi:namedview/@inkscape:current-layer', namespaces=NSS) if layerattr: layername = layerattr[0] layer = self.document.xpath('//svg:g[@id="%s"]' % layername, namespaces=NSS) if layer: self.current_layer = layer[0] xattr = self.document.xpath('//sodipodi:namedview/@inkscape:cx', namespaces=NSS) yattr = self.document.xpath('//sodipodi:namedview/@inkscape:cy', namespaces=NSS) doc_height = unittouu(self.document.getroot().get('height')) if xattr and yattr: x = xattr[0] y = yattr[0] if x and y: self.view_center = (float(x), doc_height - float(y)) # FIXME: y-coordinate flip, eliminate it when it's gone in Inkscape def getselected(self): """Collect selected nodes""" for i in self.options.ids: path = '//*[@id="%s"]' % i for node in self.document.xpath(path, namespaces=NSS): self.selected[i] = node def getElementById(self, id): path = '//*[@id="%s"]' % id el_list = self.document.xpath(path, namespaces=NSS) if el_list: return el_list[0] else: return None def getParentNode(self, node): for parent in self.document.getiterator(): if node in parent.getchildren(): return parent break def getdocids(self): docIdNodes = self.document.xpath('//@id', namespaces=NSS) for m in docIdNodes: self.doc_ids[m] = 1 def getNamedView(self): return self.document.xpath('//sodipodi:namedview', namespaces=NSS)[0] def createGuide(self, posX, posY, angle): atts = { 'position': str(posX)+','+str(posY), 'orientation': str(sin(radians(angle)))+','+str(-cos(radians(angle))) } guide = etree.SubElement( self.getNamedView(), addNS('guide','sodipodi'), atts ) return guide def output(self): """Serialize document into XML on stdout""" self.document.write(sys.stdout) def affect(self, args=sys.argv[1:], output=True): """Affect an SVG document with a callback effect""" self.svg_file = args[-1] self.getoptions(args) self.parse() self.getposinlayer() self.getselected() self.getdocids() self.effect() if output: self.output() def uniqueId(self, old_id, make_new_id = True): new_id = old_id if make_new_id: while new_id in self.doc_ids: new_id += random.choice('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ') self.doc_ids[new_id] = 1 return new_id def xpathSingle(self, path): try: retval = self.document.xpath(path, namespaces=NSS)[0] except: errormsg(_("No matching node for expression: %s") % path) retval = None return retval # vim: expandtab shiftwidth=4 tabstop=8 softtabstop=4 encoding=utf-8 textwidth=99 geometry-4.0.0/inst/@svg/loadpaths.m0000644000000000000000000000544113615712371015557 0ustar0000000000000000## Copyright (C) 2012-2019 Juan Pablo Carbajal ## ## 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 . ## Author: Juan Pablo Carbajal ## Updated: 2019-05-14 function Paths = loadpaths (obj, svg, varargin) here = which ("@svg/loadpaths"); here = fileparts (here); script = fullfile (here, 'parsePath.py'); ## Call python script if exist (svg,'file') # read from file [st str]=system (sprintf ('python3 %s %s', script, svg)); else # inline SVG [st str]=system (sprintf ('python3 %s < %s', script, svg)); end ## Parse ouput strpath = strsplit (str(1:end-1), '$', true); npaths = numel (strpath); ## Convert path data to polynoms for ip = 1:npaths eval (strpath{ip}); ## FIXME: intialize struct with cell field svgpath2.cmd = svgpath(1).cmd; svgpath2.data = {svgpath.data}; nD = length(svgpath2.cmd); pathdata = cell (nD-1,1); point_end=[]; ## If the path is closed, last command is Z and we set initial point == final if svgpath2.cmd(end) == 'Z' nD -= 1; point_end = svgpath2.data{1}; svgpath2.data(end) = []; end ## Initial point points(1,:) = svgpath2.data{1}; for jp = 2:nD switch svgpath2.cmd(jp) case 'L' ## Straigth segment to polygon points(2,:) = svgpath2.data{jp}; pp = [(points(2,:)-points(1,:))' points(1,:)']; clear points points(1,:) = [polyval(pp(1,:),1) polyval(pp(2,:),1)]; case 'C' ## Cubic bezier to polygon points(2:4,:) = reshape (svgpath2.data{jp}, 2, 3).'; pp = cubicBezierToPolyline (points); clear points points(1,:) = [polyval(pp(1,:),1) polyval(pp(2,:),1)]; end pathdata{jp-1} = pp; end if ~isempty(point_end) ## Straight segment to close the path points(2,:) = point_end; pp = [(points(2,:)-points(1,:))' points(1,:)']; if all ( abs(pp(:,1)) < sqrt(eps) ) # Final point of last segment is already initial point pathdata(end) = []; else pathdata{end} = pp; end end ## TODO # pathdata = transformShape(pathdata); Paths.(svgpathid).data = pathdata; end endfunction geometry-4.0.0/inst/@svg/loadsvgdata.m0000644000000000000000000000226013615712371016065 0ustar0000000000000000## Copyright (C) 2012 Juan Pablo Carbajal ## ## 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 . function data = loadsvgdata (obj, svg, varargin) here = which ("@svg/loadsvgdata"); here = fileparts (here); script = fullfile (here, 'parseSVGData.py'); ## Call python script if exist (svg,'file') # read from file [st str]=system (sprintf ('python3 %s %s', script, svg)); else # inline SVG [st str]=system (sprintf ('python3 %s < %s', script, svg)); end ## Parse ouput strdata = strsplit (str(1:end-1), '$', true); eval (strdata{1}); endfunction geometry-4.0.0/inst/@svg/normalize.m0000644000000000000000000000567113615712371015605 0ustar0000000000000000## Copyright (C) 2012 Juan Pablo Carbajal ## ## 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 . ## -*- texinfo -*- ## @deftypefn {Function File} @var{SVGn} = normalize (@var{SVG}) ## normalizes and SVG. ## @end deftypefn function [SVGn bb] = normalize (obj) SVGn = obj; bb = []; if ! obj.Data.normalized ids = fieldnames (obj.Path); npath = numel(ids); v = zeros(npath,2); bb = zeros(1,4); for ip = 1:npath v(ip,:) = shapeCentroid(obj.Path.(ids{ip}).data); p = shape2polygon(obj.Path.(ids{ip}).data); bb = mergeBoxes(bb, [min(p) max(p)]([1 3 2 4])); end if npath > 1 v = mean(v)(:); else v = v.'; end ## check whether document and bounding box agree. bbHeight = bb(2)-bb(1); bbWidth = bb(4)-bb(2); if obj.Data.height != bbHeight warning("svg:normalize:Sanitycheck",... ["Height of SVG #g and height boundingbox #g don't match.\n" ... "Using bounding box.\n"],obj.Data.height,bbHeight) end if obj.Data.width != bbWidth warning("svg:normalize:Sanitycheck",... ["Width of SVG #g and width boundingbox #g don't match.\n" ... "Using bounding box.\n"],obj.Data.width,bbWidth) end ## Move paths such that center of SVG is at 0,0 ## Put coordinates in the usual frame ## Scale such that diagonal of bounding box is 1 Dnorm = sqrt (bbWidth ^ 2 + bbHeight ^ 2); S = (1 / Dnorm) * eye (2); bb = zeros(1,4); for ip = 1:npath SVGn.Path.(ids{ip}).data = transformShape(obj.Path.(ids{ip}).data,-v); # Put to middle SVGn.Path.(ids{ip}).data = ... transformShape(SVGn.Path.(ids{ip}).data,[0; -bbHeight/2]); # Reflect y SVGn.Path.(ids{ip}).data = ... transformShape(SVGn.Path.(ids{ip}).data,[1 0;0 -1]); # Put to bottom SVGn.Path.(ids{ip}).data = ... transformShape(SVGn.Path.(ids{ip}).data,[0; bbHeight/2]); # Scale SVGn.Path.(ids{ip}).data = ... transformShape(SVGn.Path.(ids{ip}).data,S); p = shape2polygon(SVGn.Path.(ids{ip}).data); bb = mergeBoxes(bb, [min(p) max(p)]([1 3 2 4])); end bbHeight = bb(2)-bb(1); bbWidth = bb(4)-bb(2); SVGn.Data.height = bbHeight; SVGn.Data.width = bbWidth; SVGn.Data.normalized = true; end end geometry-4.0.0/inst/@svg/parsePath.py0000644000000000000000000000422013615712371015715 0ustar0000000000000000#!/usr/bin/env python3 ## Copyright (c) 2012 Juan Pablo Carbajal ## ## 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 ## 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 . import inkex, simplepath import sys #import getopt def parsePaths (filen=None): svg = inkex.Effect () svg.parse (filen) paths = svg.document.xpath ('//svg:path', namespaces=inkex.NSS) for path in paths: D = simplepath.parsePath (path.attrib['d']) cmdlst = []; parlst = []; for cmd,params in D: cmdlst.append(cmd) parlst.append(params) print ('svgpath = struct("cmd","{0}","data",{{{1}}});' .format(''.join(cmdlst),str(parlst).replace('[[','[').replace(']]',']'))) print ('svgpathid = "{0}"; $'.format(path.attrib['id'])) # ---------------------------- if __name__=="__main__": ''' try: optlist,args = getopt.getopt(sys.argv[1:],"thdp") except getopt.GetoptError: usage() sys.exit(2) doHelp = 0 c = Context() c.doPrint = 1 for opt in optlist: if opt[0] == "-d": c.debug = 1 if opt[0] == "-p": c.plot = 1 if opt[0] == "-t": c.triangulate = 1 if opt[0] == "-h": doHelp = 1 if not doHelp: pts = [] fp = sys.stdin if len(args) > 0: fp = open(args[0],'r') for line in fp: fld = line.split() x = float(fld[0]) y = float(fld[1]) pts.append(Site(x,y)) if len(args) > 0: fp.close() if doHelp or len(pts) == 0: usage() sys.exit(2) ''' svg = sys.argv[1] parsePaths(svg) geometry-4.0.0/inst/@svg/parseSVGData.py0000644000000000000000000000232613615712371016257 0ustar0000000000000000#!/usr/bin/env python3 ## Copyright (c) 2012 Juan Pablo Carbajal ## ## 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 ## 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 . import inkex import sys #import getopt def parseSVGData (filen=None): svg = inkex.Effect () svg.parse (filen) root = svg.document.xpath ('//svg:svg', namespaces=inkex.NSS) print ('data = struct("height",{0},"width",{1},"id","{2}");' .format(root[0].attrib['height'],root[0].attrib['width'], root[0].attrib['id'])) # ---------------------------- if __name__=="__main__": svg = sys.argv[1] parseSVGData(svg) geometry-4.0.0/inst/@svg/path2polygon.m0000644000000000000000000000300613615712371016221 0ustar0000000000000000## Copyright (C) 2012-2019 Juan Pablo Carbajal ## ## 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 . ## Author: Juan Pablo Carbajal ## Updated: 2019-05-14 ## -*- texinfo -*- ## @defun {@var{P} =} path2polygon (@var{id}) ## @defunx {@var{P} =} path2polygon (@var{id}, @var{n}) ## Converts the SVG path to an array of polygons. ## @end defun function P = path2polygon (obj, id) P = shape2polygon (getpath (obj, id)); endfunction #{ pd = obj.Path.(id).data; P = cellfun(@(x)convertpath(x,n),pd,'UniformOutput',false); P = cell2mat(P); end function p = convertpath(x,np) n = size(x,2); switch n case 2 p = zeros(2,2); # Straight segment p(:,1) = polyval (x(1,:), [0; 1]); p(:,2) = polyval (x(2,:), [0; 1]); case 4 p = zeros(np,2); # Cubic bezier t = linspace (0, 1, np).'; p(:,1) = polyval (x(1,:),t); p(:,2) = polyval (x(2,:),t); end end #} geometry-4.0.0/inst/@svg/pathid.m0000644000000000000000000000156213615712371015051 0ustar0000000000000000## Copyright (C) 2012 Juan Pablo Carbajal ## ## 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 . ## -*- texinfo -*- ## @deftypefn {Function File} {} function_name () ## @end deftypefn function ids = pathid(obj,varargin) ids = fieldnames (obj.Path); endfunction geometry-4.0.0/inst/@svg/plot.m0000644000000000000000000000260113615712371014551 0ustar0000000000000000## Copyright (C) 2012 Juan Pablo Carbajal ## ## 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 . ## -*- texinfo -*- ## @deftypefn {Function File} {@var{h} = } plot () ## Plots and SVG object. ## ## @end deftypefn function h = plot(obj, varargin) # Get path ids ids = fieldnames(obj.Path); npath = numel(ids); t = linspace (0, 1, 64); args={}; if !isempty (varargin) args = varargin; end holded = false; if ~ishold(gca) hold on; holded = true; end for i = 1:npath x = []; y = []; data = obj.Path.(ids{i}).data; for j = 1:numel(data) x = cat (2, x, polyval (data{j}(1,:),t)); y = cat (2, y, polyval (data{j}(2,:),t)); end h = plot(x,y,args{:}); end if holded hold off end axis tight axis equal endfunction geometry-4.0.0/inst/@svg/simplepath.py0000644000000000000000000001546713615712371016153 0ustar0000000000000000#!/usr/bin/env python3 """ simplepath.py functions for digesting paths into a simple list structure Copyright (C) 2005 Aaron Spike, aaron@ekips.org 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 . """ import re, math def lexPath(d): """ returns and iterator that breaks path data identifies command and parameter tokens """ offset = 0 length = len(d) delim = re.compile(r'[ \t\r\n,]+') command = re.compile(r'[MLHVCSQTAZmlhvcsqtaz]') parameter = re.compile(r'(([-+]?[0-9]+(\.[0-9]*)?|[-+]?\.[0-9]+)([eE][-+]?[0-9]+)?)') while 1: m = delim.match(d, offset) if m: offset = m.end() if offset >= length: break m = command.match(d, offset) if m: yield [d[offset:m.end()], True] offset = m.end() continue m = parameter.match(d, offset) if m: yield [d[offset:m.end()], False] offset = m.end() continue #TODO: create new exception raise Exception ('Invalid path data!') ''' pathdefs = {commandfamily: [ implicitnext, #params, [casts,cast,cast], [coord type,x,y,0] ]} ''' pathdefs = { 'M':['L', 2, [float, float], ['x','y']], 'L':['L', 2, [float, float], ['x','y']], 'H':['H', 1, [float], ['x']], 'V':['V', 1, [float], ['y']], 'C':['C', 6, [float, float, float, float, float, float], ['x','y','x','y','x','y']], 'S':['S', 4, [float, float, float, float], ['x','y','x','y']], 'Q':['Q', 4, [float, float, float, float], ['x','y','x','y']], 'T':['T', 2, [float, float], ['x','y']], 'A':['A', 7, [float, float, float, int, int, float, float], ['r','r','a',0,'s','x','y']], 'Z':['L', 0, [], []] } def parsePath(d): """ Parse SVG path and return an array of segments. Removes all shorthand notation. Converts coordinates to absolute. """ retval = [] lexer = lexPath(d) pen = (0.0,0.0) subPathStart = pen lastControl = pen lastCommand = '' while 1: try: token, isCommand = next (lexer) except StopIteration: break params = [] needParam = True if isCommand: if not lastCommand and token.upper() != 'M': raise Exception ('Invalid path, must begin with moveto.') else: command = token else: #command was omited #use last command's implicit next command needParam = False if lastCommand: if lastCommand.isupper(): command = pathdefs[lastCommand][0] else: command = pathdefs[lastCommand.upper()][0].lower() else: raise Exception ('Invalid path, no initial command.') numParams = pathdefs[command.upper()][1] while numParams > 0: if needParam: try: token, isCommand = next (lexer) if isCommand: raise Exception ('Invalid number of parameters') except StopIteration: raise Exception ('Unexpected end of path') cast = pathdefs[command.upper()][2][-numParams] param = cast(token) if command.islower(): if pathdefs[command.upper()][3][-numParams]=='x': param += pen[0] elif pathdefs[command.upper()][3][-numParams]=='y': param += pen[1] params.append(param) needParam = True numParams -= 1 #segment is now absolute so outputCommand = command.upper() #Flesh out shortcut notation if outputCommand in ('H','V'): if outputCommand == 'H': params.append(pen[1]) if outputCommand == 'V': params.insert(0,pen[0]) outputCommand = 'L' if outputCommand in ('S','T'): params.insert(0,pen[1]+(pen[1]-lastControl[1])) params.insert(0,pen[0]+(pen[0]-lastControl[0])) if outputCommand == 'S': outputCommand = 'C' if outputCommand == 'T': outputCommand = 'Q' #current values become "last" values if outputCommand == 'M': subPathStart = tuple(params[0:2]) pen = subPathStart if outputCommand == 'Z': pen = subPathStart else: pen = tuple(params[-2:]) if outputCommand in ('Q','C'): lastControl = tuple(params[-4:-2]) else: lastControl = pen lastCommand = command retval.append([outputCommand,params]) return retval def formatPath(a): """Format SVG path data from an array""" return "".join([cmd + " ".join([str(p) for p in params]) for cmd, params in a]) def translatePath(p, x, y): for cmd,params in p: defs = pathdefs[cmd] for i in range(defs[1]): if defs[3][i] == 'x': params[i] += x elif defs[3][i] == 'y': params[i] += y def scalePath(p, x, y): for cmd,params in p: defs = pathdefs[cmd] for i in range(defs[1]): if defs[3][i] == 'x': params[i] *= x elif defs[3][i] == 'y': params[i] *= y elif defs[3][i] == 'r': # radius parameter params[i] *= x elif defs[3][i] == 's': # sweep-flag parameter if x*y < 0: params[i] = 1 - params[i] elif defs[3][i] == 'a': # x-axis-rotation angle if y < 0: params[i] = - params[i] def rotatePath(p, a, cx = 0, cy = 0): if a == 0: return p for cmd,params in p: defs = pathdefs[cmd] for i in range(defs[1]): if defs[3][i] == 'x': x = params[i] - cx y = params[i + 1] - cy r = math.sqrt((x**2) + (y**2)) if r != 0: theta = math.atan2(y, x) + a params[i] = (r * math.cos(theta)) + cx params[i + 1] = (r * math.sin(theta)) + cy # vim: expandtab shiftwidth=4 tabstop=8 softtabstop=4 encoding=utf-8 textwidth=99 geometry-4.0.0/inst/@svg/subsref.m0000644000000000000000000000471713615712371015256 0ustar0000000000000000## Copyright (C) 2012 Juan Pablo Carbajal ## ## 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 . ## -*- texinfo -*- ## @deftypefn {Function File} {} function_name () ## @end deftypefn function varargout = subsref (obj, idx) persistent __method__ method4field typeNotImplemented if isempty(__method__) __method__ = struct(); __method__.plot = @(o,varargin) plot (o, varargin{:}); __method__.getpath = @(o,varargin) getpath (o, varargin{:}); __method__.pathid = @(o,varargin) pathid(o,varargin{:}); __method__.path2polygon = @(o,varargin) path2polygon (o, varargin{:}); __method__.normalize = @(o,varargin) normalize (o, varargin{:}); __method__.height = @(o,varargin) height(o, varargin{:}); __method__.width = @(o,varargin) width(o,varargin{:}); # Error strings method4field = "Class #s has no field #s. Use #s() for the method."; typeNotImplemented = "#s no implemented for class #s."; end if ( !strcmp (class (obj), 'svg') ) error ("Object must be of the svg class but '#s' was used", class (obj) ); elseif ( idx(1).type != '.' ) error ("Invalid index for class #s", class (obj) ); endif method = idx(1).subs; if ~isfield(__method__, method) error('Unknown method #s.',method); else fhandle = __method__.(method); end if strcmp(method,'normalize') warning("svg:Devel",["Not returning second output argument of #s" ... " use method(obj) API to get it"],method); end if numel (idx) == 1 # can't access properties, only methods error (method4field, class (obj), method, method); end if strcmp (idx(2).type, '()') args = idx(2).subs; if isempty(args) out = fhandle (obj); else out = fhandle (obj, args{:}); end varargout{1} = out; else error (typeNotImplemented,[method idx(2).type], class (obj)); end endfunction geometry-4.0.0/inst/@svg/svg.m0000644000000000000000000000505113615712371014374 0ustar0000000000000000## Copyright (C) 2012-2019 Juan Pablo Carbajal ## ## 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 . ## Author: Juan Pablo Carbajal ## Updated: 2019-05-14 ## -*- texinfo -*- ## @deftypefn {Function File} {@var{obj} =} svg () ## @deftypefnx {Function File} {@var{obj} =} svg (@var{str}) ## Create object of the svg class. ## ## If no input argument is provided the object is empty. @var{str} can be a filename ## or a string defining an inline SVG. ## ## @end deftypefn function svg = svg(name='') svg = struct; ## SVG data. All the attributes of the node. ## The field unparsed contains all the attributes that are not being parsed. svg.Data = struct('height',[],'width',[],'id','null','normalized',false); ## SVG metadata. All the attributes of the node. ## The field unparsed contains all the attributes that are not being parsed. svg.Metadata = struct('unparsed',' '); ## SVG paths. It is a vector of path structs. Maybe path can be a object too? ## Order of Path.Data is important so we store in a cell (could be a matrix padded with zeros). ## All the paths stored in polyval compatible format. Straigth segments are also stored as a polynomial. svg.Path = struct(); svg = class (svg, 'svg'); if !isempty (name) if exist(name,"file") == 2 name = file_in_path(path(), name); else error("svg:BadArguemnt", "File %s doesn't exist",name); end svg.Path = loadpaths(svg, name); svg.Data = loadsvgdata(svg, name); svg.Data.normalized = false; elseif !ischar(name) print_usage ; endif endfunction %!test %! dc = svg('drawing5.svg'); %! dc.getpath(); %! dc.pathid(); %! dc.getpath('path3756'); %! %! dc = svg('drawing.svg'); %! ids = dc.pathid(); %! dc.getpath({ids{[1 3]}}); %!test %! dc = svg('drawing6.svg'); %! ids = dc.pathid(); %! P = dc.path2polygon(ids{1}); %!test %! dc = svg('drawing6.svg'); %! dc.plot(); %! dc.plot('color','r','linewidth',2); ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������geometry-4.0.0/inst/@svg/width.m��������������������������������������������������������������������0000644�0000000�0000000�00000001546�13615712371�014721� 0����������������������������������������������������������������������������������������������������ustar�00����������������������������������������������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������## Copyright (C) 2012 Juan Pablo Carbajal ## ## 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 . ## -*- texinfo -*- ## @deftypefn {Function File} {} function_name () ## @end deftypefn function o = width(obj,varargin) o = obj.Data.width; endfunction ����������������������������������������������������������������������������������������������������������������������������������������������������������geometry-4.0.0/inst/beltProblem.m�������������������������������������������������������������������0000644�0000000�0000000�00000010405�13615712371�015144� 0����������������������������������������������������������������������������������������������������ustar�00����������������������������������������������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������## Copyright (C) 2012-2019 Juan Pablo Carbajal ## ## 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 . ## Author: Juan Pablo Carbajal ## Updated: 2019-05-14 ## -*- texinfo -*- ## @deftypefn {Function File} {[@var{tangent},@var{inner}] = } beltProblem (@var{c}, @var{r}) ## Finds the four lines tangent to two circles with given centers and radii. ## ## The function solves the belt problem in 2D for circles with center @var{c} and ## radii @var{r}. ## ## @strong{INPUT} ## @table @var ## @item c ## 2-by-2 matrix containig coordinates of the centers of the circles; one row per circle. ## @item r ## 2-by-1 vector with the radii of the circles. ##@end table ## ## @strong{OUPUT} ## @table @var ## @item tangent ## 4-by-4 matrix with the points of tangency. Each row describes a segment(edge). ## @item inner ## 4-by-2 vector with the point of intersection of the inner tangents (crossed belts) ## with the segment that joins the centers of the two circles. If ## the i-th edge is not an inner tangent then @code{inner(i,:)=[NaN,NaN]}. ## @end table ## ## Example: ## ## @example ## c = [0 0;1 3]; ## r = [1 0.5]; ## [T inner] = beltProblem(c,r) ## @result{} T = ## -0.68516 0.72839 1.34258 2.63581 ## 0.98516 0.17161 0.50742 2.91419 ## 0.98675 -0.16225 1.49338 2.91888 ## -0.88675 0.46225 0.55663 3.23112 ## ## @result{} inner = ## 0.66667 2.00000 ## 0.66667 2.00000 ## NaN NaN ## NaN NaN ## ## @end example ## ## @seealso{edges2d} ## @end deftypefn function [edgeTan inner] = beltProblem(c,r) x0 = [c(1,1) c(1,2) c(2,1) c(2,2)]; r0 = r([1 1 2 2]); middleEdge = createEdge(c(1,:),c(2,:)); ind0 = [1 0 1 0; 0 1 1 0; 1 1 1 0; -1 0 1 0; 0 -1 1 0; -1 -1 1 0;... 1 0 0 1; 0 1 0 1; 1 1 0 1; -1 0 0 1; 0 -1 0 1; -1 -1 0 1;... 1 0 1 1; 0 1 1 1; 1 1 1 1; -1 0 1 1; 0 -1 1 1; -1 -1 1 1;... 1 0 -1 0; 0 1 -1 0; 1 1 -1 0; -1 0 -1 0; 0 -1 -1 0; -1 -1 -1 0;... 1 0 0 -1; 0 1 0 -1; 1 1 0 -1; -1 0 0 -1; 0 -1 0 -1; -1 -1 0 -1;... 1 0 -1 -1; 0 1 -1 -1; 1 1 -1 -1; -1 0 -1 -1; 0 -1 -1 -1; -1 -1 -1 -1]; nInit = size(ind0,1); ir = randperm(nInit); edgeTan = zeros(4,4); inner = zeros(4,2); nSol = 0; i=1; ## Solve for 2 different lines while nSol<4 && i 1e-6); end if all(notequal) nSol = nSol+1; edgeTan(nSol,:) = createEdge(sol(1:2),sol(3:4)); # Find innerTangent inner(nSol,:) = intersectEdges(middleEdge,edgeTan(nSol,:)); end i = i+1; end # Sort to avoid random order of results [~, order] = sort (sumsq (inner, 2)); inner = inner(order,:); edgeTan = edgeTan(order,:); endfunction function res = belt(x,c,r) res = zeros(4,1); res(1,1) = (x(3:4) - c(2,1:2))*(x(3:4) - x(1:2))'; res(2,1) = (x(1:2) - c(1,1:2))*(x(3:4) - x(1:2))'; res(3,1) = sumsq(x(1:2) - c(1,1:2)) - r(1)^2; res(4,1) = sumsq(x(3:4) - c(2,1:2)) - r(2)^2; end %!demo %! c = [0 0;1 3]; %! r = [1 0.5]; %! [T inner] = beltProblem(c,r) %! %! figure(1) %! clf %! hold on %! h = drawEdge (T); %! set(h(find(~isnan(inner(:,1)))),'color','m'); %! set(h,'linewidth',2); %! hold on %! drawCircle([c(1,:) r(1); c(2,:) r(2)],'linewidth',2); %! axis tight %! axis equal %! %! # ------------------------------------------------------------------- %! # The circles with the tangents edges are plotted. The solution with %! # crossed belts (inner tangets) is shown in red. �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������geometry-4.0.0/inst/clipPolygon.m�������������������������������������������������������������������0000644�0000000�0000000�00000014460�13615712371�015201� 0����������������������������������������������������������������������������������������������������ustar�00����������������������������������������������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������## Copyright (C) 2017 - 2019 Philip Nienhuis ## Copyright (C) 2017 - 2019 Juan Pablo Carbajal ## Copyright (C) 2017 - 2019 Piyush Jain ## ## 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 . ## -*- texinfo -*- ## @deffn {} [@var{outpol}, @var{npol}] = clipPolygon (@var{inpol}, @var{clippol}, @var{op}) ## @deffnx {} [@var{outpol}, @var{npol}] = clipPolygon (@var{inpol}, @var{clippol}, @var{op}, @var{library}) ## @deffnx {} [@var{outpol}, @var{npol}] = clipPolygon (@dots{}, @var{args}) ## Perform boolean operation on polygon(s) using one of several algorithms. ## ## @var{inpol} = Nx2 matrix of (X, Y) coordinates constituting the polygons(s) ## to be clipped (subject polygons). Polygons are separated by [NaN NaN] rows. ## ## @var{clippol} = another Nx2 matrix of (X, Y) coordinates representing the ## clip polygon(s). @* ## @var{clippol} can also be a vector containing the bottom left and upper right ## coordinates of a clipping rectangle, or bounding box, in the format @* ## [xmin xmax ymin ymax]. ## ## The argument @var{op}, the boolean operation, can be either an integer or a ## string. In the case of integer it should be between 0 and 3, correspoding to: ## ## @itemize ## @item 0: difference @var{inpol} - @var{clippol} ## ## @item 1: intersection ('AND') of @var{inpol} and @var{clippol} (= default) ## ## @item 2: exclusiveOR ('XOR') of @var{inpol} and @var{clippol} ## ## @item 3: union ('OR') of @var{inpol} and @var{clippol} ## @end itemize ## ## If @var{op} is a string should be one of @asis{'diff', 'and', 'xor', 'or'}, ## the parsing of this option is case insensitive, i.e. @asis{'AND'} is the same ## as @asis{'and'}. ## ## The optional argument @var{library} specifies which library to use for clipping. ## Currently @asis{'clipper'} and @asis{'mrf'} are implemented. Option ## @asis{'clipper'} uses a MEX interface to the Clipper library, option ## @asis{'mrf'} uses the algorithm by Martinez, Rueda and Feito implemented ## with OCT files. @* ## Each library interprets polygons as holes differently, refer to the help ## of the specific function to learn how to pass polygons with holes. ## ## Output array @var{outpol} will be an Nx2 array of polygons resulting from ## the requested boolean operation, or in case of just one input argument an ## Nx1 array indicating winding direction of each subpolygon in input argument ## @var{inpol}. ## ## Optional output argument @var{npol} indicates the number of output polygons. ## ## @seealso{clipPolygon_clipper, clipPolygon_mrf, clipPolyline} ## @end deffn ## Author: Philip Nienhuis ## Created: 2017-03-21 function [opol, npol] = clipPolygon (inpol, clipol, op, library = 'clipper', varargin) # Check number of required input arguments if (nargin < 3) print_usage () endif if (any (size (clipol) == 1)) ## Bottom left - upper right corner of clip rectangle input. ## Check if clipol geometry is acceptable. if (clipol(1) >= clipol(2) || clipol(3) >= clipol(4)) error ('Octave:invalid-input-arg', ... ['clipPolygon: clip rectangle has zero or negative area - ' ... 'check coordinates']); endif clipol = reshape (clipol(:)', 2, []); clipol = [clipol(1, :); clipol(1, :); clipol(2, :); clipol(2, :)]; clipol = [clipol(:, 1) circshift(clipol(:, 2), -1)]; op = 1; endif ## Very basic input check. Other checks are in called functions. if (size (inpol, 1) < 3 || size (clipol, 1) < 3) error ('Octave:invalid-input-arg', ... 'clipPolygon: subject or clip polygons must have at least 3 vertices'); endif ## Parse operations given as strings if (ischar (op) ) [~, op_] = ismember (tolower (op), {'diff', 'and', 'xor', 'or'}); if (op_ == 0) # wrong operation string error ('Octave:invalid-input-arg', ... 'clipPolygon: operation "%s" unknown', op); endif op = op_ - 1; endif switch library case 'clipper' [opol, npol] = clipPolygon_clipper (inpol, clipol, op, varargin{:}); case 'mrf' [opol, npol] = clipPolygon_mrf (inpol, clipol, op, varargin{:}); otherwise error ('Octave:invalid-fun-call', ... 'clipPolygon: unimplemented polygon clipping library: "%s"', library); endswitch endfunction %!error clipPolygon([],[],[],'abracadabra') %!error clipPolygon([0 0; 0 1; 0.5 1],[-1 -1; -1 1; 0 1],'no-op') %!demo %! pol1 = [2 2; 6 2; 6 6; 2 6; 2 2; NaN NaN; 3 3; 3 5; 5 5; 5 3; 3 3]; %! pol2 = [1 2; 7 4; 4 7; 1 2; NaN NaN; 2.5 3; 5.5 4; 4 5.5; 2.5 3]; %! %! subplot (3, 3, 1) %! drawFilledPolygon (pol1, 'edgecolor', 'k', 'facecolor', 'c') %! axis image %! title ('1. Subject polygon') %! axis off %! %! subplot (3, 3, 2) %! drawFilledPolygon (pol1, 'linestyle', 'none', 'facecolor', 'c') %! drawFilledPolygon (pol2, 'edgecolor', 'b', 'facecolor', 'y') %! axis image %! title ('2. Clip polygon') %! axis off %! %! algo = {'clipper', 'mrf'}; %! for i = 1:numel (algo) %! subplot (3, 3, i+2); %! tic %! [opol, npol] = clipPolygon (pol1, pol2, 3, 'clipper'); %! printf('%s took: %f seconds (union)\n', algo{i}, toc); %! drawFilledPolygon (opol, 'edgecolor', 'r', 'facecolor', 'g') %! axis image %! title (sprintf('Union - %s', algo{i})); %! axis off %! %! subplot (3, 3, i+4); %! tic %! [opol, npol] = clipPolygon (pol1, pol2, 1, 'clipper'); %! printf('%s took: %f seconds (and)\n', algo{i}, toc); %! drawFilledPolygon (opol, 'edgecolor', 'r', 'facecolor', 'g') %! axis image %! title (sprintf('And - %s', algo{i})); %! axis off %! %! subplot (3, 3, i+6); %! tic %! [opol, npol] = clipPolygon (pol1, pol2, 2, 'clipper'); %! printf('%s took: %f seconds (xor)\n', algo{i}, toc); %! drawFilledPolygon (opol, 'edgecolor', 'r', 'facecolor', 'g') %! axis image %! title (sprintf('Xor - %s', algo{i})); %! axis off %! endfor ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������geometry-4.0.0/inst/clipPolygon_clipper.m�����������������������������������������������������������0000644�0000000�0000000�00000016161�13615712371�016717� 0����������������������������������������������������������������������������������������������������ustar�00����������������������������������������������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������## Copyright (C) 2015-2019 - Philip Nienhuis ## Copyright (C) 2017 - Juan Pablo Carbajal ## Copyright (C) 2017 - Piyush Jain ## ## 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 . ## -*- texinfo -*- ## @deffn {} [@var{outpol}, @var{npol}] = clipPolygon_clipper (@var{inpol}, @var{clippol}) ## @deffnx {} [@var{outpol}, @var{npol}] = clipPolygon_clipper (@var{inpol}, @var{clippol}, @var{op}) ## @deffnx {} [@var{outpol}, @var{npol}] = clipPolygon_clipper (@var{inpol}, @var{clippol}, @var{op}, @var{rules}, @var{rulec}) ## Perform boolean operation on polygon(s) using the Clipper library. ## ## @var{inpol} = Nx2 matrix of (X, Y) coordinates constituting the polygons(s) ## to be clipped. Polygons are separated by [NaN NaN] rows. @var{clippol} = ## another Nx2 matrix of (X, Y) coordinates representing the clip polygon(s). ## ## Optional argument @var{op}, the boolean operation, can be: ## ## @itemize ## @item 0: difference @var{inpol} - @var{clippol} ## ## @item 1: intersection ("AND") of @var{inpol} and @var{clippol} (= default) ## ## @item 2: exclusiveOR ("XOR") of @var{inpol} and @var{clippol} ## ## @item 3: union ("OR") of @var{inpol} and @var{clippol} ## @end itemize ## ## In addition a rule can be specified to instruct polyclip how to assess ## holes, or rather, how to assess polygon fill. This works as follows: start ## with a winding number of zero (0). From a point outside all polygons ## specified in @var{INPOL}, go to the center of the innermost polygon and note ## which polygons are crossed. For each polygon boundary crossing from right ## to left, increase the winding number, while for each polygon crossing from ## left to right, decrement it, and then assign it to the crossed polygon. ## @var{rules} and @var{rulec} can be set individually for subject and clip ## polygons, respectively, as follows: ## ## @itemize ## @item 0 Even-Odd, also called Alternate (= default): ## The first polygon crossed specifies the outer boundary of a filled polygon, ## the next polygon (if present) specifies the inner boundary of that filled ## polygon, and so on. Winding direction (clockwise or counterclockwise) is ## irrelevant here. ## ## @item 1 Non-Zero: ## All polygons with a non-zero winding number are filled. ## ## @item 2 Positive: ## All polygons with a winding number > 0 are filled. This is the usual setting ## for counterclockwise polygons to be the outer, and clockwise polygons to be ## the inner boundary ("holes") of complex polygons. ## ## @item 3 Negative: ## All polygons with a winding number < 0 are filled. ## @end itemize ## (for details see [1]) ## ## Output array @var{outpol} will be an Nx2 array of polygons resulting from ## the requested boolean operation, or in case of just one input argument an ## Nx1 array indicating winding direction of each subpolygon in input argument ## @var{inpol}. ## ## [1]: @uref{http://www.angusj.com/delphi/clipper/documentation/Docs/Units/ClipperLib/Types/PolyFillType.htm} ## ## @seealso{clipPolygon_mrf,clipPolygon} ## @end deffn ## Author: Philip Nienhuis ## Created: 2015-05-03 ## Based on Clipper library, polyclipping.sf.net, 3rd Party, Matlab function [outpoly, npol] = clipPolygon_clipper (inpoly, clippoly, method=1, rules=0, rulec=0) ## Input validation if (nargin < 3) print_usage (); endif if (! isnumeric (inpoly) || size (inpoly, 2) < 2) error ("Octave:invalid-input-arg", ... "clipPolygon: inpoly should be a numeric Nx2 array"); endif if (! isnumeric (clippoly) || size (clippoly, 2) < 2) error ("Octave:invalid-input-arg", ... "clipPolygon: clippoly should be a numeric Nx2 array"); elseif (! isnumeric (method) || method < 0 || method > 3) error ("Octave:invalid-input-arg", ... "clipPolygon: operation must be a number in the range [0..3]"); elseif (! isnumeric (rules) || ! isnumeric (rulec) || rules < 0 || rulec < 0) error ("Octave:invalid-input-arg", ... "clipPolygon: fill type rules must be nummbers in range [0..3]"); endif [inpol, xy_mean, xy_magn] = __dbl2int64__ (inpoly, clippoly); clpol = __dbl2int64__ (clippoly, [], xy_mean, xy_magn); ## Perform boolean operation outpol = clipper (inpol, clpol, method, rules, rulec); npol = numel (outpol); if (! isempty (outpol)) ## Morph struct output into [X,Y] array. Put NaNs between sub-polys. First X: [tmp(1:2:2*npol, 1)] = deal ({outpol.x}); [tmp(2:2:2*npol, 1)] = ... cellfun (@(x) [x(1); NaN], tmp(1:2:2*npol, 1), "uni", 0); ## Convert back from in64 into double, wipe trailing NaN X = double (cell2mat (tmp))(1:end-1); ## Y-coordinates: [tmp(1:2:2*npol, 1)] = deal ({outpol.y}); [tmp(2:2:2*npol, 1)] = ... cellfun (@(y) [y(1); NaN], tmp(1:2:2*npol, 1), "uni", 0); Y = double (cell2mat (tmp))(1:end-1); outpoly = ([X Y] / xy_magn) + xy_mean; else outpoly = zeros (0, 2); endif endfunction %!demo %! pol1 = [2 2; 6 2; 6 6; 2 6; 2 2; NaN NaN; 3 3; 3 5; 5 5; 5 3; 3 3]; %! pol2 = [1 2; 7 4; 4 7; 1 2; NaN NaN; 2.5 3; 5.5 4; 4 5.5; 2.5 3]; %! lw = 2; %! %! subplot (2, 7, [1 2]) %! pol1a = polygon2patch (pol1); %! patch (pol1a(:, 1), pol1a(:, 2), 'facecolor', 'c', 'edgecolor', 'k', 'linewidth', lw); %! axis image %! title ("1. Subject polygon") %! axis off %! %! subplot (2, 7, [3 4]) %! patch (pol1a(:, 1), pol1a(:, 2), 'facecolor', 'c', 'edgecolor', 'none'); %! hold on %! pol2a = polygon2patch (pol2); %! patch (pol2a(:, 1), pol2a(:, 2), 'facecolor', 'y', 'edgecolor', 'b', 'linewidth', lw); %! axis image %! title "2. Clip polygon" %! axis off %! %! op = {"Sub - clip", "AND / Intersection", "Exclusive OR", "OR / Union"}; %! for i=1:numel(op) %! subplot (6, 4, [12 16]+i); %! [opol, npol] = clipPolygon_clipper (pol1, pol2, i-1); %! opol = polygon2patch (opol); %! patch (pol1a(:, 1), pol1a(:, 2), 'facecolor', 'c', 'edgecolor', 'none'); %! hold on %! patch (pol2a(:, 1), pol2a(:, 2), 'facecolor', 'y', 'edgecolor', 'none'); %! patch (opol(:,1),opol(:,2), 'facecolor', 'g', 'edgecolor', 'r', ... %! 'linewidth', lw); %! axis image %! grid on %! title (sprintf("%d. %s", i+3, op{i})); %! axis off %! endfor %! %! subplot (2, 7, [6 7]); %! [opol, npol] = clipPolygon_clipper (pol2, pol1, 0); %! opol = polygon2patch (opol); %! patch (pol1a(:, 1), pol1a(:, 2), 'facecolor', 'c', 'edgecolor', 'none'); %! hold on %! patch (pol2a(:, 1), pol2a(:, 2), 'facecolor', 'y', 'edgecolor', 'none'); %! patch (opol(:,1),opol(:,2), 'facecolor', 'g', 'edgecolor', 'r', ... %! 'linewidth', lw); %! axis image %! grid on %! axis off %! title "3. Clip - sub"; ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������geometry-4.0.0/inst/clipPolygon_mrf.m���������������������������������������������������������������0000644�0000000�0000000�00000021146�13615712371�016044� 0����������������������������������������������������������������������������������������������������ustar�00����������������������������������������������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������## Copyright (C) 2017 - Piyush Jain ## Copyright (C) 2017 - Juan Pablo Carbajal ## ## 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 . ## -*- texinfo -*- ## @deffn {} [@var{outpol}, @var{npol}] = clipPolygon_mrf (@var{inpol}, @var{clippol}) ## @deffnx {} [@var{outpol}, @var{npol}] = clipPolygon_mrf (@var{inpol}, @var{clippol}, @var{op}) ## Perform boolean operation on polygon(s) using the algorithm by Martinez, Rueda and Feito. ## ## @var{inpol} = Nx2 matrix of (X, Y) coordinates constituting the polygons(s) ## to be clipped (subject polygon). ## @var{clippol} = Nx2 matrix of (X, Y) coordinates representing the clip polygon(s). ## ## Polygons may have multiple non-intersecting regions. The contours are separated by [Nan NaN] rows. ## Polygons may also contain holes. Holes are defined as the region enclosed within the boundaries of polygon which are not part of the polygon region. Here again, the inner and outer contours are separated by [Nan NaN] rows. Specifically, if a contour is lying inside another contour, it is automatically treated as a hole. ## ## The following features are allowed in input polygons: ## ## @itemize ## @item 0: Contours can be described in clockwise or counterclockwise order. ## ## @item 1: Holes. ## ## @item 2: A vertex of a polygon can touch (in a point) a vertex or edge of the same polygon. ## ## @item 3: Self-intersecting polygons. ## @end itemize ## ## The following features are not allowed in input polygons: ## ## @itemize ## The intersection of two edges of the same polygon can be a point, but cannot be a segment. ## @end itemize ## ## The argument @var{op}, the boolean operation, can be: ## ## @itemize ## @item 0: difference @var{inpol} - @var{clippol} ## ## @item 1: intersection ("AND") of @var{inpol} and @var{clippol} (= default) ## ## @item 2: exclusiveOR ("XOR") of @var{inpol} and @var{clippol} ## ## @item 3: union ("OR") of @var{inpol} and @var{clippol} ## @end itemize ## ## Output array @var{outpol} will be an Nx2 array of polygons resulting from ## the requested boolean operation ## ## Optional output argument @var{npol} indicates the number of output polygons. ## ## Know more about the algorithm by Martinez, Rueda and Feito[1]. ## ## [1]: @uref{http://www4.ujaen.es/~fmartin/bool_op.html} ## ## @seealso{clipPolygon_clipper,clipPolygon} ## @end deffn ## Created: 2017-06-09 function [outpol, npol] = clipPolygon_mrf (inpoly, clippoly=[], method=1) ## Input validation if (nargin < 2 || nargin > 3) print_usage (); endif if(isempty(inpoly) || isempty(clippoly)) error ('Octave:invalid-input-arg', ... "clipPolygon_mrf: Empty polygon"); endif if (! isnumeric (inpoly) || size (inpoly, 2) < 2) error ('Octave:invalid-input-arg', ... "clipPolygon_mrf: inpoly should be a numeric Nx2 array"); endif if (! isnumeric (clippoly) || size (clippoly, 2) < 2) error ('Octave:invalid-input-arg', ... "clipPolygon_mrf: clippoly should be a numeric Nx2 array"); elseif (! isnumeric (method) || method < 0 || method > 3) error ('Octave:invalid-input-arg', ... "clipPolygon_mrf: operation must be a number in the range [0..3]"); endif inpol = __polytostruct__ (inpoly); clpol = __polytostruct__ (clippoly); ## Perform boolean operation [X, Y, npol] = polybool_mrf(inpol, clpol, method); if(npol == 0) outpol = [ , ]; else outpol = [X Y]; endif endfunction %!test %! pol1 = [-0.15 -0.15; 0.45 -0.15; 0.15 0.45]; %! pol2 = [-0.05 -0.05; 0.15 0.35; 0.35 -0.05; NaN NaN; %! 0.05 0.05; 0.25 0.05; 0.15 0.25]; %! opol_0 = [0.15 0.25; 0.05 0.05; 0.25 0.05; NaN NaN; %! 0.15 0.35; -0.05 -0.05; 0.35 -0.05; NaN NaN; %! 0.15 0.45; -0.15 -0.15; 0.45 -0.15]; %! npol_0 = 3; %! opol_1= [0.15 0.25; 0.05 0.05; 0.25 0.05; NaN NaN; %! 0.15 0.35; -0.05 -0.05; 0.35 -0.05]; %! npol_1 = 2; %! opol_2 = [0.15 0.25; 0.05 0.05; 0.25 0.05; NaN NaN; %! 0.15 0.35; -0.05 -0.05; 0.35 -0.05; NaN NaN; %! 0.15 0.45; -0.15 -0.15; 0.45 -0.15]; %! npol_2 = 3; %! opol_3 = [0.15 0.45; -0.15 -0.15; 0.45 -0.15]; %! npol_3 = 1; %! [opol npol] = clipPolygon_mrf (pol1, pol2, 0); %! assert(opol, opol_0); %! assert(npol, npol_0); %! [opol npol] = clipPolygon_mrf (pol1, pol2, 1); %! assert(opol, opol_1); %! assert(npol, npol_1); %! [opol npol] = clipPolygon_mrf (pol1, pol2, 2); %! assert(opol, opol_2); %! assert(npol, npol_2); %! [opol npol] = clipPolygon_mrf (pol1, pol2, 3); %! assert(opol, opol_3); %! assert(npol, npol_3); %!error clipPolygon_mrf([], [], 0); %!error %! pol1 = [0.15 0.15; 0.55 0.45; 0.15 0.75]; %! pol2 = [0.35 0.45; 0.75 0.15; 0.75 0.75]; %! clipPolygon_mrf(pol1, pol2, 4); %!test ## Bug #56506 %! subpol = [0 0; 5 5; 2.5 4;0 0]; %! clppol2 = [10 1; 16 6; 13.5 5; 10 1]; %! [a, b] = clipPolygon_mrf (subpol, clppol2, 1); %! assert (a, []); %! assert (b, 0); %!demo %! pol1 = [0.15 0.15; 0.55 0.45; 0.15 0.75]; %! pol2 = [0.35 0.45; 0.75 0.15; 0.75 0.75]; %! pol1a = polygon2patch(pol1); %! pol2a = polygon2patch(pol2); %! lw = 2; %! subplot (2, 6, [2 3]) %! patch (pol1a(:, 1), pol1a(:, 2), 'facecolor', 'c', 'edgecolor', 'k', 'linewidth', lw); %! axis image %! grid on %! title ("1. Subject polygon") %! %! subplot (2, 6, [4 5]) %! patch (pol1a(:, 1), pol1a(:, 2), 'facecolor', 'c', 'edgecolor', 'none'); %! hold on %! patch (pol2a(:, 1), pol2a(:, 2), 'facecolor', 'y', 'edgecolor', 'b', 'linewidth', lw); %! axis image %! grid on %! title "2. Clip polygon" %! %! op = {"Sub -clip", "AND / Intersection", "Exclusive OR", "OR / Union"}; %! for i=1:numel(op) %! subplot (6, 4, [12 16]+i); %! [opol, npol] = clipPolygon_mrf (pol1, pol2, i-1); %! opol = polygon2patch (opol); %! patch (pol1a(:, 1), pol1a(:, 2), 'facecolor', 'c', 'edgecolor', 'none'); %! hold on %! patch (pol2a(:, 1), pol2a(:, 2), 'facecolor', 'y', 'edgecolor', 'none'); %! patch (opol(:,1),opol(:,2), 'facecolor', 'g', 'edgecolor', 'r', ... %! 'linewidth', lw); %! axis image %! grid on %! title (sprintf("%d. %s", i+2, op{i})); %! axis off %! endfor %! %! subplot (10, 4, 37); %! [opol, npol] = clipPolygon_mrf (pol2, pol1, 0); %! opol = polygon2patch (opol); %! patch (pol1a(:, 1), pol1a(:, 2), 'facecolor', 'c', 'edgecolor', 'none'); %! hold on %! patch (pol2a(:, 1), pol2a(:, 2), 'facecolor', 'y', 'edgecolor', 'none'); %! patch (opol(:,1),opol(:,2), 'facecolor', 'g', 'edgecolor', 'r', ... %! 'linewidth', lw); %! axis image %! grid on %! axis off %! title "7. Clip - sub"; %!demo %! pol1 = [1 1; 5 1; 3 7; NaN NaN; 2 2; 3 5; 4 2]; %! pol2 = [3 1; 5 6; 1 6]; %! pol1a = polygon2patch(pol1); %! pol2a = polygon2patch(pol2); %! lw = 2; %! subplot (2, 6, [2 3]) %! patch (pol1a(:, 1), pol1a(:, 2), 'facecolor', 'c', 'edgecolor', 'k', 'linewidth', lw); %! axis image %! grid on %! title ("1. Subject polygon") %! %! subplot (2, 6, [4 5]) %! patch (pol1a(:, 1), pol1a(:, 2), 'facecolor', 'c', 'edgecolor', 'none'); %! hold on %! patch (pol2a(:, 1), pol2a(:, 2), 'facecolor', 'y', 'edgecolor', 'b', 'linewidth', lw); %! axis image %! grid on %! title "2. Clip polygon" %! %! op = {"Sub -clip", "AND / Intersection", "Exclusive OR", "OR / Union"}; %! for i=1:numel(op) %! subplot (6, 4, [12 16]+i); %! [opol, npol] = clipPolygon_mrf (pol1, pol2, i-1); %! opol = polygon2patch (opol); %! patch (pol1a(:, 1), pol1a(:, 2), 'facecolor', 'c', 'edgecolor', 'none'); %! hold on %! patch (pol2a(:, 1), pol2a(:, 2), 'facecolor', 'y', 'edgecolor', 'none'); %! patch (opol(:,1),opol(:,2), 'facecolor', 'g', 'edgecolor', 'r', ... %! 'linewidth', lw); %! axis image %! grid on %! title (sprintf("%d. %s", i+2, op{i})); %! axis off %! endfor %! %! subplot (10, 4, 37); %! [opol, npol] = clipPolygon_mrf (pol2, pol1, 0); %! opol = polygon2patch (opol); %! patch (pol1a(:, 1), pol1a(:, 2), 'facecolor', 'c', 'edgecolor', 'none'); %! hold on %! patch (pol2a(:, 1), pol2a(:, 2), 'facecolor', 'y', 'edgecolor', 'none'); %! patch (opol(:,1),opol(:,2), 'facecolor', 'g', 'edgecolor', 'r', ... %! 'linewidth', lw); %! axis image %! grid on %! axis off %! title "7. Clip - sub";��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������geometry-4.0.0/inst/clipPolyline.m������������������������������������������������������������������0000644�0000000�0000000�00000005461�13615712371�015346� 0����������������������������������������������������������������������������������������������������ustar�00����������������������������������������������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������## Copyright (C) 2017-2019 Philip Nienhuis ## ## 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 . ## -*- texinfo -*- ## @deftypefn {} {@var{oline}} = clipPolyline (@var{inpol}, @var{clippol}, @var{op}) ## Clip (possibly composite) polylines with polygon(s) using one of boolean ## methods. ## ## @var{inpol} = Nx2 matrix of (X, Y) coordinates constituting the polylines(s) ## to be clipped. Polyline sections are separated by [NaN NaN] rows. ## @var{clippol} = another Nx2 matrix of (X, Y) coordinates representing the ## clip polygon(s). @var{clippol} may comprise separate and/or concentric ## polygons (the latter with holes). ## ## The argument @var{op}, the boolean operation, can be: ## ## @itemize ## @item 0: difference @var{inpol} - @var{clippol} ## ## @item 1: intersection ("AND") of @var{inpol} and @var{clippol} (= default) ## @end itemize ## ## Output array @var{oline} will be an Nx2 array of polyline sections ## resulting from the requested boolean operation. ## ## The optional argument @var{library} specifies which library to use for clipping. ## Currently only @asis{"clipper"} is implemented. ## ## @seealso{clipPolygon} ## @end deftypefn ## Author: Philip Nienhuis ## Created: 2017-03-21 function [olin, nlin] = clipPolyline (p1, p2, op, library = "clipper") if ~(ismember (tolower (library), {"clipper"})) error ('Octave:invalid-fun-call', "clipPolyline: unimplemented polygon clipping library: '%s'", library); endif [olin, nlin] = clipPolyline_clipper (p1, p2, op); endfunction %!demo %! sline = [0, 6.5; 1.25, 4; 1.25, 0; NaN, NaN; 0.25, 7; 1.75, 4; 1.75, 0]; %! for ii=1:10 %! sline = [sline; [NaN NaN]; [ii/2+0.25, 7; ii/2+1.75, 4; ii/2+1.75, 0]]; %! endfor %! pol2a = [1 2; 7 4; 4 7; 1 2; 2.5 3; 4 5.5; 5.5 4; 2.5 3; 1 2]; %! figure (); %! hold on %! patch (pol2a(:, 1), pol2a(:, 2), 'facecolor', 'y', 'edgecolor', 'b', 'linewidth', 2); %! [olin, nlin] = clipPolyline_clipper (sline, pol2a, 1); %! plot (olin(:, 1), olin(:, 2), 'r', 'linewidth', 3); %! [olin, nlin] = clipPolyline (sline, pol2a, 0); %! plot (olin(:, 1), olin(:, 2), 'g', 'linewidth', 3); %! grid on; %! box on; %! axis equal; %! legend ({"Clip polygon", "AND", "OR"}); %! title ("Demo: clipping polylines with polygons"); ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������geometry-4.0.0/inst/clipPolyline_clipper.m����������������������������������������������������������0000644�0000000�0000000�00000006103�13615712371�017056� 0����������������������������������������������������������������������������������������������������ustar�00����������������������������������������������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������## Copyright (C) 2017 Philip Nienhuis ## ## 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 . ## -*- texinfo -*- ## @deftypefn {Function File} [@var{olin}, @var{nlin}] = clipPolyline_clipper (@var{inlin}, @var{clippol}) ## @deftypefnx {Function File} [@var{olin}, @var{nlin}] = clipPolyline_clipper (@var{inlin}, @var{clippol}, @var{op}) ## Clip (possibly composite) polylines with polygon(s) using one of boolean ## methods. ## ## @var{inpol} = Nx2 matrix of (X, Y) coordinates constituting the polylines(s) ## to be clipped. Polyline sections are separated by [NaN NaN] rows. ## @var{clippol} = another Nx2 matrix of (X, Y) coordinates representing the ## clip polygon(s). @var{clippol} may comprise separate and/or concentric ## polygons (the latter with holes). ## ## Optional argument @var{op}, the boolean operation, can be: ## ## @itemize ## @item 0: difference @var{inpol} - @var{clippol} ## ## @item 1: intersection ("AND") of @var{inpol} and @var{clippol} (= default) ## @end itemize ## ## Output array @var{oline} will be an Nx2 array of polyline sections ## resulting from the requested boolean operation. ## @end deftypefn ## Author: Philip Nienhuis ## Created: 2017-03-21 ## Based on Clipper library, polyclipping.sf.net, 3rd Party, Matlab function [olin, nlin] = clipPolyline_clipper (inpoly, clippoly, method=1) ## Input validation if (nargin < 2) print_usage (); endif if (! isnumeric (inpoly) || size (inpoly, 2) < 2) error (" clipPolyline: inpoly should be a numeric Nx2 array"); endif if (! isnumeric (clippoly) || size (clippoly, 2) < 2) error (" clipPolyline: clippoly should be a numeric Nx2 array"); elseif (! isnumeric (method) || method < 0 || method > 3) error (" clipPolyline: operation must be a numeric 0 or 1"); endif [inpol, xy_mean, xy_magn] = __dbl2int64__ (inpoly, clippoly); clpol = __dbl2int64__ (clippoly, [], xy_mean, xy_magn); ## Perform boolean operation olin = clipper (inpol, clpol, method, -1); nlin = numel (olin); if (! isempty (olin)) ## Morph struct output into [X,Y] array. Put NaNs between sub-polys. First X: [tmp(1:2:2*nlin, 1)] = deal ({olin.x}); [tmp(2:2:2*nlin-1, 1)] = NaN; ## Convert back from in64 into double, wipe trailing NaN X = double (cell2mat (tmp)); ## Y-coordinates: [tmp(1:2:2*nlin, 1)] = deal ({olin.y}); [tmp(2:2:2*nlin-1, 1)] = NaN; Y = double (cell2mat (tmp)); olin = ([X Y] / xy_magn) + xy_mean; else olin = zeros (0, 2); endif endfunction �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������geometry-4.0.0/inst/cov2ellipse.m�������������������������������������������������������������������0000644�0000000�0000000�00000006146�13615712371�015133� 0����������������������������������������������������������������������������������������������������ustar�00����������������������������������������������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## 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. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND 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 THE AUTHOR OR 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. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{ellipse} = } cov2ellipse (@var{K}) ## @deftypefnx {Function File} {[@var{ra} @var{rb} @var{theta}] = } cov2ellipse (@var{K}) ## @deftypefnx {Function File} {@dots{} = } cov2ellipse (@dots{}, @samp{tol},@var{tol}) ## Calculates ellipse parameters from covariance matrix. ## ## @var{K} must be symmetric positive (semi)definite. The optional argument ## @samp{tol} sets the tolerance for the verification of the ## positive-(semi)definiteness of the matrix @var{K} (see @command{isdefinite}). ## ## If only one output argument is supplied a vector defining a ellipse is returned ## as defined in @command{ellipses2d}. Otherwise the angle @var{theta} is given ## in radians. ## ## Run @code{demo cov2ellipse} to see an example. ## ## @seealso{ellipses2d, cov2ellipse, drawEllipse} ## @end deftypefn function varargout = cov2ellipse (K, varargin); parser = inputParser (); parser.FunctionName = "cov2ellipse"; parser.addParamValue ('Tol', 100*eps*norm (K, "fro"), @(x)x>0); parser.parse(varargin{:}); if isdefinite (K,parser.Results.Tol) == -1 print_usage end [R S W] = svd (K); theta = atan2 (R(2,1), R(1,1)); v = sqrt (diag(S))'; if nargout == 1 varargout{1} = [0 0 v theta*180/pi]; elseif nargout == 3 varargout{1} = v(1); varargout{2} = v(2); varargout{3} = theta; end endfunction %!demo %! K = [2 1; 1 2]; %! L = chol(K,'lower'); %! u = randn(1e3,2)*L'; %! %! elli = cov2ellipse (K) %! %! figure(1) %! plot(u(:,1),u(:,2),'.r'); %! hold on; %! drawEllipse(elli,'linewidth',2); %! hold off %! axis tight ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������geometry-4.0.0/inst/curve2polyline.m����������������������������������������������������������������0000644�0000000�0000000�00000010403�13615712371�015655� 0����������������������������������������������������������������������������������������������������ustar�00����������������������������������������������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������## Copyright (C) 2012-2019 Juan Pablo Carbajal ## ## 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 . ## -*- texinfo -*- ## @defun {@var{polyline} = } curve2polyline (@var{curve}) ## @defunx {@var{polyline} = } curve2polyline (@dots{},@var{property},@var{value},@dots{}) ## Adaptive sampling of a parametric curve. ## ## The @var{curve} is described as a 2-by-N matrix. Rows correspond to the ## polynomial (compatible with @code{polyval}) describing the respective component ## of the curve. The curve must be parametrized in the interval [0,1]. ## The vertices of the polyline are accumulated in regions of the curve where ## the curvature is higher. ## ## @strong{Parameters} ## @table @samp ## @item 'Nmax' ## Maximum number of vertices. Not used. ## @item 'Tol' ## Tolerance for the error criteria. Default value @code{1e-4}. ## ## Currently the area of the smaller triangle formed by three consecutive points ## on the curve is considered. When this area is smaller than tolerance the ## points are colinear, and hence no more sampling between these points is ## needed. ## ## @item 'MaxIter' ## Maximum number of iterations. Default value @code{10}. ## @item 'Method' ## Not implemented. ## @end table ## ## This function is based on the algorithm described in ## L. H. de Figueiredo (1993). "Adaptive Sampling of Parametric Curves". Graphic Gems III. ## @seealso{shape2polygon, curveval} ## @end defun ## I had to remove the recursion so this version could be improved. ## Thursday, April 12 2012 -- JuanPi function [polyline t bump]= curve2polyline (curve, varargin) ## TODO make tolerance relative to the "diameter" of the curve. # --- Parse arguments --- # parser = inputParser (); parser.FunctionName = "curve2polyline"; parser.addParamValue ('Nmax', 32, @(x)x>0); parser.addParamValue ('Tol', 1e-4, @(x)x>0); parser.addParamValue ('MaxIter', 10, @(x)x>0); parser.parse(varargin{:}); Nmax = parser.Results.Nmax; tol = parser.Results.Tol; MaxIter = parser.Results.MaxIter; clear parser toldef # ------ # t = [0; 1]; tf = 1; points = 1; for iter = 1:MaxIter # Add parameter values where error is still bigger than tol. t = interleave(t, tf); nt = length (t); # Update error polyline = curveval (curve,t); bump = bumpyness (polyline); # Check which intervals must be subdivided idx = find (bump > tol); # The position of the bumps maps into intervals # 1 -> 1 2 # 2 -> 3 4 # 3 -> 5 6 # and so on idx = [2*(idx-1)+1; 2*idx](:); tf = false (nt-1,1); tf(idx) = true; if all (!tf) break; end end endfunction function f = bumpyness (p) ## Check for co-linearity ## TODO implement various method for this ## -- Area of the triangle close to zero (used currently). ## -- Angle close to pi. ## -- abs(p0-pt) + abs(pt-p1) - abs(p0-p1) almost zero. ## -- Curve's tange at 0,t,1 are almost parallel. ## -- pt is in chord p0 -> p1. ## Do this in isParallel.m and remove this function PL = p(1:2:end-2,:); PC = p(2:2:end-1,:); PR = p(3:2:end,:); a = PL - PC; b = PR - PC; f = (a(:,1).*b(:,2) - a(:,2).*b(:,1)).^2; endfunction function tt = interleave (t,varargin) nt = length (t); ntt = 2 * nt -1; tt = zeros (ntt,1); tt(1:2:ntt) = t; beta = 0.4 + 0.2 * rand (nt-1, 1); tt(2:2:ntt) = t(1:end-1) + beta .* (t(2:end)-t(1:end-1)); if nargin > 1 tf = true (ntt,1); tf(2:2:ntt) = varargin{1}; tt(!tf) = []; end endfunction %!demo %! curve = [0 0 1 0;1 -0.3-1 0.3 0]; %! polyline = curve2polyline(curve,'tol',1e-8); %! %! t = linspace(0,1,100)'; %! pc = curveval(curve,t); %! %! plot(polyline(:,1),polyline(:,2),'-o',pc(:,1),pc(:,2),'-r') �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������geometry-4.0.0/inst/curveval.m����������������������������������������������������������������������0000644�0000000�0000000�00000002003�13615712371�014517� 0����������������������������������������������������������������������������������������������������ustar�00����������������������������������������������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������## Copyright (C) 2012-2017 (C) Juan Pablo Carbajal ## ## 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 . ## -*- texinfo -*- ## @deftypefn {Function File} {@var{p} = } curveval (@var{curve}, @var{t}) ## Evaluates parametric @var{curve} at @var{t}. ## ## @end deftypefn function p = curveval (curve, t) dim = size (curve,1); p = zeros (length(t), dim); for i = 1:dim p(:,i) = polyval (curve(i,:), t); end endfunction �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������geometry-4.0.0/inst/data2geo.m����������������������������������������������������������������������0000644�0000000�0000000�00000007200�13615712371�014362� 0����������������������������������������������������������������������������������������������������ustar�00����������������������������������������������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������## Copyright (C) 2016-2019 Juan Pablo Carbajal ## ## 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 . ## Author: Juan Pablo Carbajal ## -*- texinfo -*- ## @deftypefn {Function File} {@var{fileStr} =} data2geo (@var{data}, @var{lc}) ## @deftypefnx {Function File} {@var{fileStr} =} data2geo (@dots{}, @var{param}, @var{value}) ## Uses data to build a file compatible with Gmsh. ## ## @var{data} is assumed to describe a polygon in @code{polygon2d} format. ## The argument @var{lc} specifies the edge size. ## ## The optional parameters can be 'output' followed with a string specifying a file ## to write, and 'spherical' followed by a real number @var{r} indicating that the ## polygon describes a spherical surface of radious @var{r}. ## ## @seealso{polygon2d} ## @end deftypefn function strFile = data2geo(data, lc, varargin) nl = @()sprintf('\n'); ## Parse options filegiven = []; spherical = []; if nargin > 2 filegiven = find(cellfun(@(x)strcmpi(x,'output'),varargin)); spherical = find(cellfun(@(x)strcmpi(x,'spherical'),varargin)); end [n dim] = size(data); if dim == 2 data(:,3) = zeros(n,1); end header = ' // File created with Octave'; strFile = [header nl()]; # Points strFile = [strFile '// Points' nl()]; for i=1:n strFile = [strFile pointGeo(i,data(i,:),lc)]; end # Lines strFile = [strFile '// Lines' nl()]; for i=1:n-1 strFile = [strFile lineGeo(i,i,i+1)]; end strFile = [strFile lineGeo(n,n,1)]; # Loop strFile = [strFile lineLoopGeo(n+1,n,1:n)]; # Surface if spherical sphr = varargin{spherical+1}; if dim ==2 sphr(1,3) = 0; end strFile = [strFile pointGeo(n+1,sphr,lc)]; strFile = [strFile ruledSurfGeo(n+3,1,n+1,n+1)]; else strFile = [strFile planeSurfGeo(n+2,1,n+1)]; end if filegiven outfile = varargin{filegiven+1}; fid = fopen(outfile,'w'); fprintf(fid,'%s',strFile); fclose(fid); disp(['DATA2GEO: Geometry file saved to ' outfile]) end endfunction %!demo %! points = [0 0 0; 0.1 0 0; 0.1 .3 0; 0 0.3 0]; %! strFile = data2geo(points,0.009); %! disp(strFile) # This demo doesn't work because the svg class is broken as of geometry 4.0.0 #%!demo #%! dc = svg('drawing6.svg'); #%! ids = dc.pathid(); #%! P = dc.path2polygon(ids{1},12)(1:end-1,:); #%! P = bsxfun(@minus, P, centroid(P)); #%! P = simplifyPolygon_geometry(P,'tol',5e-1); #%! filename = tmpnam (); #%! meshsize = sqrt(mean(sumsq(diff(P,1,1),2)))/2; #%! data2geo (P, meshsize, 'output', [filename '.geo']); #%! #%! pkg load msh fpl #%! T = msh2m_gmsh(filename); #%! pdemesh(T.p,T.e,T.t) #%! view(2) #%! axis tight #%! # -------------------------------------------------------------------------- #%! # We load the drawing6.svg file into Octave and transform it into a polygon. #%! # Then we create a temporary file where the .geo mesh will be written. #%! # If the packages msh and fpl are available, a mesh is created from the .geo #%! # file. ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������geometry-4.0.0/inst/drawFilledPolygon.m�������������������������������������������������������������0000644�0000000�0000000�00000012261�13615712371�016324� 0����������������������������������������������������������������������������������������������������ustar�00����������������������������������������������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������## Copyright (C) 2019 Juan Pablo Carbajal ## ## 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 . ## -*- texinfo -*- ## @defun {} drawFilledPolygon (@var{p}) ## @defunx {} drawFilledPolygon (@var{hax}, @var{p}) ## @defunx {} clipPolygon (@dots{}, @var{prop}, @var{value}, @dots{}) ## @defunx {@var{h} =} drawFilledPolygon (@dots{}) ## Draw a filled polygon. ## ## Add a patch representing the polygon(s) @var{p} in the current axes. ## ## Multiple property-value pairs may be specified, but they must ## appear in pairs. These arguments are passed to the function @code{patch}. ## ## If the first argument @var{hax} is an axes handle, then plot into this ## axes, rather than the current axes returned by @code{gca}. ## ## If @var{p} is a cell, each element of the cell is processed in sequence. ## ## The optional return value @var{h} is a vector of graphics handles to the ## created patch objects. ## ## For example: ## ## Draw a polygon with default filling color and red edges. ## ## @example ## @group ## pol = [1 2; 7 4; 4 7; 1 2; NaN NaN; 2.5 3; 5.5 4; 4 5.5; 2.5 3]; ## h = drawFilledPolygon (pol, 'edgecolor', 'r'); ## @end group ## @end example ## ## @seealso{drawPolygon, polygon2patch, patch} ## @end defun ## Author: Juan Pablo Carbajal ## Created: 2019-12-15 function h = drawFilledPolygon (px, varargin) # Check input if (nargin < 1) print_usage (); endif # Check for empty polygons if (isempty (px)) return endif # Store hold state state = ishold (gca); hold on; # Extract handle of axis to draw on ax = gca; if (isAxisHandle (px)) ax = px; px = varargin{1}; varargin(1) = []; end ## Manage cell arrays of polygons # Case of a set of polygons stored in a cell array if (iscell (px)) np = numel (px); h_ = zeros(1, np); for i = 1:np h_(np - i + 1) = drawFilledPolygon (px{i}, varargin{:}); endfor else # Check size vs number of arguments if (size (px, 2) == 1) # Case of polygon specified as two N-by-1 arrays with same length if (nargin < 2 || nargin == 2 && ~isnumeric (varargin{1})) error('Octave:invalid-input-arg', ... ['drawFilledPolygon: Should specify either a N-by-2 array,' ... ' or 2 N-by-1 vectors']); endif # Merge coordinates of polygon vertices py = varargin{1}; varargin(1) = []; if (length (py) ~= length (px)) error('Octave:invalid-input-arg', ... ['drawFilledPolygon: X and Y coordinate arrays should have' ... ' same lengths (%d,%d)'], length (px), length (py)) endif px = [px py]; elseif (size (px, 2) > 2 || size (px, 2) < 1) error ('Octave:invalid-input-arg', ... 'drawFilledPolygon: Should specify a N-by-2 array'); endif # Set default format fmtdef = {'facecolor', [0.7 0.7 0.7], ... 'edgecolor', 'k', ... 'linewidth', 2}; varargin = {fmtdef{:}, varargin{:}}; # if (isempty (varargin)) # varargin = formatdef; # else # set missing with defaults # [tfdef, idxarg] = ismember (formatdef(1:2:end), ... # tolower (varargin(1:2:end))); # if (any (tfdef)) # idxdef = find (tfdef); # idxarg = idxarg(idxarg > 0); # varargin(2 * idxarg) = formatdef(2 * idxdef); # endif # endif pxpatch = polygon2patch (px); h_ = patch (ax, pxpatch(:,1), pxpatch(:,2), varargin{:}); endif # whether input arg was a cell if (~state) hold off endif # Avoid returning argument if not required if (nargout > 0) h = h_; endif endfunction %!demo %! figure (1) %! clf; %! pol = [1 2; 7 4; 4 7; 1 2; NaN NaN; 2.5 3; 5.5 4; 4 5.5; 2.5 3]; %! subplot(131) %! drawFilledPolygon(pol) %! axis tight equal off %! subplot(132) %! drawFilledPolygon(pol, 'facecolor', 'c', 'linestyle', '--', 'edgecolor', 'r') %! axis tight equal off %! subplot(133) %! R = createRotation (polygonCentroid (splitPolygons(pol){1}), pi/6); %! pol2 = transformPoint (pol, R); %! drawFilledPolygon(pol, 'linestyle', 'none') %! drawFilledPolygon(gca, pol2, 'facealpha', 0.5) %! axis tight equal off %!demo %! pol = [2 2; 6 2; 6 6; 2 6; 2 2; NaN NaN; 3 3; 3 5; 5 5; 5 3; 3 3]; %! n = 5; %! alpha = linspace(0.1, 1, n); %! theta = linspace(pi / 3, 0, n); %! %! cpol = cell(n, 1); %! for i = 1:n %! cpol{i} = transformPoint (pol, createRotation (theta(i))); %! endfor %! h = drawFilledPolygon(cpol, 'linestyle', 'none'); %! for i = 1:n-1 %! set(h(i), 'facealpha', alpha(i)) %! endfor %! axis tight equal off �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������geometry-4.0.0/inst/drawing.svg���������������������������������������������������������������������0000644�0000000�0000000�00000003401�13615712371�014671� 0����������������������������������������������������������������������������������������������������ustar�00����������������������������������������������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������ image/svg+xml ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������geometry-4.0.0/inst/drawing2.svg��������������������������������������������������������������������0000644�0000000�0000000�00000003717�13615712371�014765� 0����������������������������������������������������������������������������������������������������ustar�00����������������������������������������������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������ image/svg+xml �������������������������������������������������geometry-4.0.0/inst/drawing3.svg��������������������������������������������������������������������0000644�0000000�0000000�00000002052�13615712371�014755� 0����������������������������������������������������������������������������������������������������ustar�00����������������������������������������������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������ image/svg+xml ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������geometry-4.0.0/inst/drawing4.svg��������������������������������������������������������������������0000644�0000000�0000000�00000004070�13615712371�014760� 0����������������������������������������������������������������������������������������������������ustar�00����������������������������������������������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������ image/svg+xml ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������geometry-4.0.0/inst/drawing5.svg��������������������������������������������������������������������0000644�0000000�0000000�00000003746�13615712371�014772� 0����������������������������������������������������������������������������������������������������ustar�00����������������������������������������������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������ image/svg+xml ��������������������������geometry-4.0.0/inst/drawing6.svg��������������������������������������������������������������������0000644�0000000�0000000�00000002604�13615712371�014763� 0����������������������������������������������������������������������������������������������������ustar�00����������������������������������������������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������ image/svg+xml ����������������������������������������������������������������������������������������������������������������������������geometry-4.0.0/inst/ellipse2cov.m�������������������������������������������������������������������0000644�0000000�0000000�00000006527�13615712371�015136� 0����������������������������������������������������������������������������������������������������ustar�00����������������������������������������������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������## Copyright (C) 2004-2011 David Legland ## Copyright (C) 2004-2011 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas) ## Copyright (C) 2012 Adapted to Octave by Juan Pablo Carbajal ## 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. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND 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 THE AUTHOR OR 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. ## -*- texinfo -*- ## @deftypefn {Function File} {@var{K} = } ellipse2cov (@var{elli}) ## @deftypefnx {Function File} {@var{K} = } ellipse2cov (@var{ra}, @var{rb}) ## @deftypefnx {Function File} {@var{K} = } ellipse2cov (@dots{}, @var{theta}) ## Calculates covariance matrix from ellipse. ## ## If only one input is given, @var{elli} must define an ellipse as described in ## @command{ellipses2d}. ## If two inputs are given, @var{ra} and @var{rb} define the half-lenght of the ## axes. ## If a third input is given, @var{theta} must be the angle of rotation of the ## ellipse in radians, and in counter-clockwise direction. ## ## The output @var{K} contains the covariance matrix define by the ellipse. ## ## Run @code{demo ellipse2cov} to see an example. ## ## @seealso{ellipses2d, cov2ellipse, drawEllipse} ## @end deftypefn function K = ellipse2cov (elli, varargin); ra = 1; rb = 1; theta = 0; switch numel (varargin) case 0 ## ellipse format if numel (elli) != 5 print_usage (); end ra = elli(1,3); rb = elli(1,4); theta = elli(1,5)*pi/180; case 1 ## ra,rb if numel (elli) != 1 print_usage (); end ra = elli; rb = varargin{1}; case 2 ## ra,rb, theta if numel (elli) != 1 print_usage (); end ra = elli; rb = varargin{1}; theta = varargin{2}; otherwise print_usage (); end T = createRotation (theta)(1:2,1:2); K = T*diag([ra rb])*T'; endfunction %!demo %! elli = [0 0 1 3 -45]; %! %! # Create 2D normal random variables with covarinace defined by elli. %! K = ellipse2cov (elli) %! L = chol(K,'lower'); %! u = randn(1e3,2)*L'; %! %! Kn = cov (u) %! %! figure(1) %! plot(u(:,1),u(:,2),'.r'); %! hold on; %! drawEllipse(elli,'linewidth',2); %! hold off %! axis tight �������������������������������������������������������������������������������������������������������������������������������������������������������������������������geometry-4.0.0/inst/isPolygonCCW.m������������������������������������������������������������������0000644�0000000�0000000�00000010206�13615712371�015214� 0����������������������������������������������������������������������������������������������������ustar�00����������������������������������������������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������## Copyright (C) 2016-2017 Juan Pablo Carbajal ## ## 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 . ## -*- texinfo -*- ## @deftypefn {} {@var{ccw} =} isPolygonCCW (@var{p}) ## @deftypefnx {} {@var{ccw} =} isPolygonCCW (@var{px}, @var{py}) ## Returns true if the polygon @var{p} are oriented Counter-Clockwise. ## ## @var{p} is a N-by-2 array containing coordinates of vertices. The coordinates ## of the vertices of the polygon can also be given as two N-by-1 arrays ## @var{px}, @var{py}. ## ## Optional third argument @var{library} can be one of "geometry" or ## "clipper". In the latter case the potentially faster Clipper polygon ## library will be invoked to assess winding directions. The default is ## "geometry". ## ## If any polygon is self-crossing, the result is undefined. ## ## If @var{p} is a cell, each element is considered a polygon, the ## resulting @var{cww} is a cell of the same size. ## ## @seealso{polygonArea} ## @end deftypefn ## Author: Juan Pablo Carbajal function ccw = isPolygonCCW (px, py=[], lib="geometry") ## case of wrong number of input arguments if (nargin > 3 || nargin < 1) print_usage (); endif if (ischar (py)) py = lower (py); if (ismember (py, {"geometry", "clipper"})) lib = py; py = []; else error ('Octave:invalid-fun-call', "use of '%s' not implemented", lib); endif endif if (! isempty (py)) if (! strcmp (typeinfo (px), typeinfo (py))) error ('Octave:invalid-input-arg', 'X and Y should be of the same type'); endif if (any (size (px) != size (py)) ) error ('Octave:invalid-input-arg', 'X and Y should be of the same size'); endif endif if (iscell (px)) ## Cell Array Format ## Call this function on each cell if (isempty (py)) py = cell (size (px)); endif ccw = cellfun (@(u,v) isPolygonCCW (u,v,lib), px, py, "unif", 0); else ## Input are matrices ## merge them to one px = [px py]; if (isempty (px)) error ("isPolygonCW: empty input polygon encountered"); elseif (strcmpi (lib, "clipper")) ## Clipper can do all of them in one call ccw = logical (isPolygonCW_Clipper (px)); return endif if (any (isnan (px(:)))) ## Inputs are many polygons separated with NaN ## Split them and call this function on each of them px = splitPolygons (px); ccw = cellfun (@(u) isPolygonCCW (u,[],lib), px); else ## Here do the actual work ccw = polygonArea (px) > 0; endif endif endfunction %!shared pccw, pcw, pxccw, pyccw, pxnan, pynan, pnan %! pccw = [0 0; 1 0; 1 1; 0 1]; %! pcw = reversePolygon (pccw); %! pxccw = pccw(:,1); %! pyccw = pccw(:,2); %! pxnan = [2; 2; 0; 0; NaN; 0; 0; 2]; %! pynan = [0; 2; 2; 0; NaN; 0; 3; 0]; %! pnan = [pxnan pynan]; ## Native testing %!assert (isPolygonCCW (pccw)); %!assert (isPolygonCCW (pxccw, pyccw)); %!assert (isPolygonCCW ({pxccw, pxccw}, {pyccw, pyccw}), {true, true}); %!assert (~isPolygonCCW (pcw)); %!assert (isPolygonCCW ({pccw;pcw}), {true;false}); %!assert (isPolygonCCW(pnan), [true; false]); %!assert (isPolygonCCW({pnan,pcw}),{[true;false], false}); ## Clipper testing %!assert (isPolygonCCW (pccw,[],"clipper")); %!assert (isPolygonCCW (pxccw, pyccw,"clipper")); %!assert (isPolygonCCW ({pxccw, pxccw}, {pyccw, pyccw},"clipper"), {true, true}); %!assert (~isPolygonCCW (pcw,[],"clipper")); %!assert (isPolygonCCW ({pccw;pcw},[],"clipper"), {true;false}); %!xtest assert (isPolygonCCW(pnan,[],"clipper"), [true; false]); %!xtest assert (isPolygonCCW({pnan,pcw},[],"clipper"),{[true; false], false}); ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������geometry-4.0.0/inst/isPolygonCW_Clipper.m�����������������������������������������������������������0000644�0000000�0000000�00000003250�13615712371�016570� 0����������������������������������������������������������������������������������������������������ustar�00����������������������������������������������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������## Copyright (C) 2015-2017 Philip Nienhuis ## ## 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 . ## -*- texinfo -*- ## @deftypefn {Function File} [@var{orientation}] = isPolygonCW_Clipper (@var{inpol}) ## Inspect winding direction of polygon(s). ## ## Based on Clipper library (polyclipping.sf.net / 3rd Party / Matlab) ## ## @var{inpol} = Nx2 matrix of (X, Y) coordinates constituting the polygons(s) ## whose winding direction should be assessed. Subpolygons are separated by ## [NaN NaN] rows. ## ## Output argument @var{orientation} contains the winding direction(s) of ## each subpolygon: 0 for clockwise, 1 for counterclockwise. ## ## @end deftypefn ## Author: Philip Nienhuis ## Created: 2015-05-03 function [orientation] = isPolygonCW_Clipper (inpoly) ## Input validation if (nargin < 1) print_usage (); endif if (! isnumeric (inpoly) || size (inpoly, 2) < 2) error ("ispolycw: inpoly should be a numeric Nx2 array"); endif inpol = __dbl2int64__ (inpoly); ## Just find out orientation of polygons orientation = clipper (inpol); endfunction ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������geometry-4.0.0/inst/ispolyccw.m���������������������������������������������������������������������0000644�0000000�0000000�00000004506�13615712371�014716� 0����������������������������������������������������������������������������������������������������ustar�00����������������������������������������������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������## Copyright (C) 2016 - Juan Pablo Carbajal ## Copyright (C) 2017 - Piyush Jain ## ## 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 . ## Author: Juan Pablo Carbajal ## -*- texinfo -*- ## @deftypefn {} {@var{ccw} =} ispolyccw (@var{p}) ## @deftypefnx {} {@var{ccw} =} ispolyccw (@var{px}, @var{py}) ## Returns true if the polygon @var{p} are oriented Counter-Clockwise. ## ## @var{p} is a N-by-2 array containing coordinates of vertices. The coordinates ## of the vertices of the polygon can also be given as two N-by-1 arrways ## @var{px}, @var{py}. ## ## If polygon is self-crossing, the result is undefined. ## ## If x and y contain multiple contours, either in NaN-separated vector form or in cell array form, ispolyccw returns a logical array containing one true or false value per contour. ## ## If @var{points} is a cell, each element is considered a polygon, the ## resulting @var{cww} array has the same shape as the cell. ## ## @seealso{polygonArea} ## @end deftypefn function ccw = ispolyccw (px, py) if (nargin > 3 || nargin < 1) print_usage (); endif if(nargin == 1) px = reshape(px, numel(px)/2, 2); else px = reshape(px, numel(px), 1); py = reshape(py, numel(py), 1); px = [px py]; endif ccw = isPolygonCCW(px); end %!shared pccw, pcw, ph %! pccw = pcw = [0 0; 1 0; 1 1; 0 1]; %! pcw([2 4],:) = pcw([4 2], :); %! ph = [pccw; nan(1,2); 0.5*pcw+[0.25 0.25]]; %!assert (ispolyccw (pccw)); %!assert (~ispolyccw (pcw)); %!assert (ispolyccw ({pccw;pcw}), {true false}); %!assert (ispolyccw(ph),[true;false]); %!test %! phcw = [pcw; nan(1,2); 0.5*pccw+[0.25 0.25]]; %! assert (ispolyccw(phcw),[false;true]); %!test %! x=[0 0 2 2 NaN 0 2 0]; y=[0 2 2 0 NaN 0 0 3]; %! assert(ispolyccw(x,y),[false;true]); ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������geometry-4.0.0/inst/ispolycw.m����������������������������������������������������������������������0000644�0000000�0000000�00000005023�13615712371�014546� 0����������������������������������������������������������������������������������������������������ustar�00����������������������������������������������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������## Copyright (C) 2016 - Juan Pablo Carbajal ## Copyright (C) 2017 - Piyush Jain ## ## 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 . ## -*- texinfo -*- ## @deftypefn {} {@var{ccw} =} ispolycw (@var{p}) ## @deftypefnx {} {@var{ccw} =} ispolycw (@var{px}, @var{py}) ## Returns true if the polygon @var{p} are oriented Clockwise. ## ## @var{p} is a N-by-2 array containing coordinates of vertices. The coordinates ## of the vertices of the polygon can also be given as two N-by-1 arrways ## @var{px}, @var{py}. ## ## If polygon is self-crossing, the result is undefined. ## ## If x and y contain multiple contours, either in NaN-separated vector form or in cell array form, ispolycw returns a logical array containing one true or false value per contour. ## ## If a contour contains two or fewer vertices, ispolycw returns true. ## ## If @var{points} is a cell, each element is considered a polygon, the ## resulting @var{cw} array has the same shape as the cell. ## ## @seealso{polygonArea} ## @end deftypefn function cw = ispolycw (px, py) if iscell (px) cw = cellfun (@ispolycw, px); else if nargin == 2; px = [px py]; end px = reshape(px, numel(px)/2, 2); px = splitPolygons (px); for i=1:size(px)(1) pol = px{i}; ## if contour contains two or fewer vertices if size(pol)(1) < 3 cw(i,1) = true; else cw(i,1) = polygonArea (pol) < 0; endif endfor end end %!shared pccw, pcw, ph %! pccw = pcw = [0 0; 1 0; 1 1; 0 1]; %! pcw([2 4],:) = pcw([4 2], :); %! ph = [pccw; nan(1,2); 0.5*pcw+[0.25 0.25]]; %!assert (~ispolycw (pccw)); %!assert (ispolycw (pcw)); %!assert (ispolycw ({pccw;pcw}), [false;true]); %!assert (ispolycw ({pccw,pcw}), [false,true]); %!assert (ispolycw(ph),[false;true]); %!test %! phcw = [pcw; nan(1,2); 0.5*pccw+[0.25 0.25]]; %! assert (ispolycw(phcw),[true;false]); %!test %! x=[0 0 2 2 NaN 0 2 0]; y=[0 2 2 0 NaN 0 0 3]; %! assert(ispolycw(x,y),[true;false]); �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������geometry-4.0.0/inst/joinPolygons.m������������������������������������������������������������������0000644�0000000�0000000�00000004153�13615712371�015372� 0����������������������������������������������������������������������������������������������������ustar�00����������������������������������������������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������## Copyright (C) 2016 Philip Nienhuis ## ## 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 . ## -*- texinfo -*- ## @deftypefn {} {@var{outpol} =} joinPolygons (@var{inpol}) ## Convert a cell style set of polygons into an array of subpolygons ## separated by NaN rows. ## ## @var{inpol} is expected to be an Nx1 (column) cell array with each cell ## containing either a matrix of Mx1 (X), Mx2 (X,Y), or Mx3 (X,Y,Z) coordinates. ## ## @var{outpol} is a numeric Px1, Px2 or Px3 array os subpolygons each ## separated by a row of NaN values. ## ## @seealso{splitPolygons} ## @end deftypefn ## Author: Philip Nienhuis ## Created: 2016-05-10 function [polys] = joinPolygons (poly) if (! iscell (poly)) error ('Octave:invalid-input-arg', 'joinPolygons: cell array expected'); elseif (isempty (poly)) polys = []; return elseif (isvector (poly) && any (cellfun (@(p)isrow(p) && numel(p) != 1, poly))) error ('Octave:invalid-input-arg', 'joinPolygons: column vectors expected'); endif XY(1:2:2*size (poly, 1), :) = [{poly{:}}']; XY(2:2:2*size (poly, 1) - 1, :) = NaN (1, size (poly{1}, 2)); polys = cell2mat (XY); endfunction %!test %! assert (joinPolygons ({1,2}), [1 2]); %!test %! assert (joinPolygons ({}), []); %!test %! XY = joinPolygons ({[1 6; 2 5; 3 4]; [4 3; 5 2; 6 1]}); %! assert (XY, [1 6; 2 5; 3 4; NaN NaN; 4 3; 5 2; 6 1]); %!error joinPolygons ([1 2 NaN 3 4], [56 NaN 78]) %!error joinPolygons ({[1,0], [0,2]}); ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������geometry-4.0.0/inst/orientPolygon.m�����������������������������������������������������������������0000644�0000000�0000000�00000010100�13615712371�015535� 0����������������������������������������������������������������������������������������������������ustar�00����������������������������������������������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������## Copyright (C) 2016 - Juan Pablo Carbajal ## ## 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 . ## Author: Juan Pablo Carbajal ## -*- texinfo -*- ## @deftypefn {} {@var{q} =} orientPolygon (@var{p}) ## @deftypefnx {} {@dots{} =} orientPolygon (@var{p}, [], @var{dir}) ## @deftypefnx {} {[@var{qx} @var{qy}] =} orientPolygon (@var{px}, @var{py}) ## @deftypefnx {} {@dots{} =} orientPolygon (@var{px}, @var{py}, @var{dir}) ## Orient polygon counterclockwise or clockwise. ## ## @var{p} is a N-by-2 array containing coordinates of vertices. The coordinates ## of the vertices of the polygon can also be given as two N-by-1 arrways ## @var{px}, @var{py}. It can also be cells of polygons or NaN separated polygons. ## The output has the same format as the input. ## ## The optional argument @var{dir} can be @asis{"ccw"} or @asis{"cw"}. ## By default it orients polygon counterclockwise (@code{@var{dir} == "ccw"}). ## To orient the polygon clockwise, use @code{@var{dir} == "cw"}. ## ## Holes are treated as independet polygons, that is a cw polygon with a cw hole ## will be seen as two cw polygons. ## ## If polygon is self-crossing, the result is undefined. ## ## @seealso{isPolygonCCW} ## @end deftypefn function [x y] = orientPolygon (x, y=[], d = "ccw"); #case of wrong number of input arguments if (nargin > 3 || nargin < 1) print_usage (); endif if (!isempty (y)) if (!strcmp (typeinfo (x), typeinfo (y))) error ('Octave:invalid-input-arg', 'X and Y should be of the same type'); endif if(any (size (x) != size (y)) ) error ('Octave:invalid-input-arg', 'X and Y should be of the same size'); endif endif # define orientation mode mode_ccw = strcmpi (d, "ccw"); if (iscell (x)) # Cell Array Format # Call this function on each cell if (isempty (y)) y = cell (size (x)); endif [x y] = cellfun (@(u,v) orientPolygon (u,v,d), x, y, "unif", 0); else # Input are matrices # merge them to one x = [x y]; if any (isnan (x(:))) # Inputs are many polygons separated with NaN # Split them and call this function on each of them x = splitPolygons (x); x = cellfun (@(u) orientPolygon (u,[],d), x, "unif", 0); x = joinPolygons (x); else ## Here do the actual work #Check the orientation of the polygons if ( (!isPolygonCCW (x) && mode_ccw) || (isPolygonCCW (x) && !mode_ccw) ); x = reversePolygon (x); endif endif if (!isempty (y)) y = x(:,2); x = x(:,1); endif endif endfunction %!shared pccw, pcw, pxccw, pyccw, pxnan, pynan, pnan %! pccw = [0 0; 1 0; 1 1; 0 1]; %! pcw = reversePolygon (pccw); %! pxccw = pccw(:,1); %! pyccw = pccw(:,2); %! pxnan = [2; 2; 0; 0; NaN; 0; 0; 2]; %! pynan = [0; 2; 2; 0; NaN; 0; 3; 0]; %! pnan = [pxnan pynan]; %!test %! x = orientPolygon (pccw,[],"ccw"); %! assert (x, pccw); %!test %! x = orientPolygon (pccw,[],"cw"); %! assert (x, pcw); %!test %! x = orientPolygon (pcw,[],"ccw"); %! assert (x, pccw); %!test %! x = orientPolygon (pcw,[],"cw"); %! assert (x, pcw); %!test %! x = orientPolygon (pnan,[],"cw"); %! y = splitPolygons (pnan); %! y = joinPolygons ({reversePolygon(y{1}); y{2}}); %! assert (x, y); %!test %! x = orientPolygon (pnan,[],"ccw"); %! y = splitPolygons (pnan); %! y = joinPolygons ({y{1}; reversePolygon(y{2})}); %! assert (x, y); %!test %! [x y] = orientPolygon (pxccw,pyccw,"ccw"); %! assert ([x y], pccw); %!test %! [x y] = orientPolygon (pxccw,pyccw,"cw"); %! assert ([x y], pcw); ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������geometry-4.0.0/inst/plotShape.m���������������������������������������������������������������������0000644�0000000�0000000�00000006247�13615712371�014645� 0����������������������������������������������������������������������������������������������������ustar�00����������������������������������������������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������## Copyright (C) 2012-2019 (C) Juan Pablo Carbajal ## ## 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 . ## Author: Juan Pablo Carbajal ## -*- texinfo -*- ## @defun {} {@var{h} = } plotShape (@var{shape}) ## @defunx {} {@var{h} = } plotShape (@dots{}, @asis{'tol'}, @var{value}) ## @defunx {} {@var{h} = } plotShape (@dots{}, @var{prop}, @var{value}) ## Plots a 2D shape defined by piecewise smooth polynomials in the current axis. ## ## @var{shape} is a cell where each elements is a 2-by-(poly_degree+1) matrix ## containing a pair of polynomials. ## ## The property @asis{'Tol'} sets the tolerance for the quality ## of the polygon as explained in @command{shape2polygon}. ## Additional property value pairs are passed to @code{drawPolygon}. ## ## @seealso{drawPolygon, shape2polygon, polygon2shape} ## @end defun function h = plotShape(shape, varargin) # Parse arguments # consume tolerance option # use last one given, erase all tol = 1e-4; if ~isempty (varargin) istol = cellfun (@(x)strcmp (tolower (x), 'tol'), varargin); if any (istol) idx = find (istol); # use last tol = varargin{idx(end) + 1}; # erase all varargin([idx(:); idx(:)+1]) = []; endif endif # Estimate step for discretization using random samples to get area range pts = cell2mat (cellfun (@(x)curveval (x, rand (1, 11)), shape, 'unif', 0)); bb = boundingBox (pts); mxrange = ( (bb(2) - bb(1)) * (bb(4) - bb(3)) ) * 0.5; dr = tol * mxrange; p = shape2polygon (shape, 'tol', dr); h = drawPolygon (p, varargin{:}); endfunction %!demo %! # Taylor series of cos(pi*x),sin(pi*x) %! n = 5; N = 0:5; %! s{1}(1,2:2:2*n+2) = fliplr ( (-1).^N .* (pi).^(2*N) ./ factorial (2*N)); %! s{1}(2,1:2:2*n+1) = fliplr ( (-1).^N .* (pi).^(2*N+1) ./ factorial (2*N+1)); %! %! h(1) = plotShape (s, 'tol', 1e-1, 'color','b'); %! h(2) = plotShape (s, 'tol', 1e-3, 'color', 'm'); %! h(3) = plotShape (s, 'tol', 1e-9, 'color', 'g'); %! legend (h, {'1e-1','1e-3','1e-9'}) %! axis image %!shared s %! s = {[0.1 1; 1 0]}; %!test %! plotShape (s); close; %!test %! plotShape (s,'tol', 1e-4);close; %!test %! plotShape (s,'color', 'm', 'tol', 1e-4);close; %!test %! plotShape (s,'color', 'm', 'linewidth', 2, 'tol', 1e-4);close; %!test %! plotShape (s,'color', 'm', 'tol', 1e-4, 'linewidth', 2);close; %!test %! plotShape (s,'-om', 'tol', 1e-4, 'linewidth', 2);close; %! plotShape (s,'tol', 1e-4, '-om', 'linewidth', 2);close; %! plotShape (s,'-om', 'linewidth', 2, 'tol', 1e-4);close; %!test %! plotShape (s,'-om', 'tol', 1e-4, 'tol', 1e-2);close; ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������geometry-4.0.0/inst/poly2ccw.m����������������������������������������������������������������������0000644�0000000�0000000�00000004255�13615712371�014445� 0����������������������������������������������������������������������������������������������������ustar�00����������������������������������������������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������## Copyright (C) 2016 - Amr Mohamed ## Copyright (C) 2017 - Piyush Jain ## ## This file is part of Octave. ## ## Octave 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. ## ## Octave 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 Octave; see the file COPYING. If not, ## see . ## -*- texinfo -*- ## @deftypefn {Function File} [@var{xccw},@var{yccw}] = poly2ccw (@var{x},@var{y}) ## Convert Polygons to counterclockwise contours(polygons). ## ## @var{x}/@var{y} is a cell array or NaN delimited vector of polygons, representing the x/y coordinates of the points. If x1 and y1 can contain multiple contours, represented either as NaN-separated vectors or as cell arrays, then each contour is converted to counter-clockwise ordering. ## @var{xccw}/@var{yccw} has the same format of the input. ## ## @seealso{poly2cw,ispolycw} ## @end deftypefn ## Created: 2017-07-18 function [xccw, yccw]=poly2ccw(x,y); if (nargin != 2) #case of wrong number of input arguments print_usage(); endif if(isempty(x) || isempty(y)) error ('Octave:invalid-input-arg', ... "poly2ccw: Empty arguments"); endif x = reshape(x, numel(x), 1); y = reshape(y, numel(y), 1); [xccw, yccw] = orientPolygon(x,y,"ccw"); if(xccw(1) == xccw(2) && yccw(1) == yccw(2)) xccw = circshift(xccw,-1); yccw = circshift(yccw,-1); endif endfunction %!test %! x = [0 0 1 1 0]; y = [0 1 1 0 0]; %! [xccw,yccw] = poly2ccw(x,y); %! xexp = [0; 1; 1; 0; 0]; yexp = [0; 0; 1; 1; 0]; %! assert (xccw,xexp); %! assert (yccw,yexp); %!test %! x=[0 0 2 2 NaN 0 2 0]; y=[0 2 2 0 NaN 0 0 3]; %! [xccw,yccw]=poly2ccw(x,y); %! xexp=[0; 2; 2; 0; NaN; 0; 2; 0]; %! yexp=[0; 0; 2; 2; NaN; 0; 0; 3]; %! assert (xccw,xexp); %! assert (yccw,yexp); ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������geometry-4.0.0/inst/poly2cw.m�����������������������������������������������������������������������0000644�0000000�0000000�00000004226�13615712371�014300� 0����������������������������������������������������������������������������������������������������ustar�00����������������������������������������������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������## Copyright (C) 2016 - Amr Mohamed ## Copyright (C) 2017 - Piyush Jain ## ## This file is part of Octave. ## ## Octave 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. ## ## Octave 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 Octave; see the file COPYING. If not, ## see . ## -*- texinfo -*- ## @deftypefn {Function File} [@var{xcw},@var{ycw}] = poly2cw (@var{x},@var{y}) ## Convert Polygons to clockwise contours(polygons). ## ## @var{x}/@var{y} is a cell array or NaN delimited vector of polygons, representing the x/y coordinates of the points. If x1 and y1 can contain multiple contours, represented either as NaN-separated vectors or as cell arrays, then each contour is converted to counter-clockwise ordering. ## @var{xccw}/@var{yccw} has the same format of the input. ## ## @seealso{poly2ccw,ispolycw} ## @end deftypefn ## Created: 2017-07-18 function [xcw, ycw]=poly2cw(x,y); if (nargin != 2) #case of wrong number of input arguments print_usage(); endif if(isempty(x) || isempty(y)) error ('Octave:invalid-input-arg', ... "poly2ccw: Empty arguments"); endif x = reshape(x, numel(x), 1); y = reshape(y, numel(y), 1); [xcw, ycw] = orientPolygon(x,y,"cw"); if(xcw(1) == xcw(2) && ycw(1) == ycw(2)) xcw = circshift(xcw,-1); ycw = circshift(ycw,-1); endif endfunction %!test %! x = [0; 1; 1; 0; 0]; y = [0; 0; 1; 1; 0]; %! [xcw,ycw] = poly2cw(x,y); %! xexp = [0; 0; 1; 1; 0]; yexp = [0; 1; 1; 0; 0]; %! assert (xcw,xexp); %! assert (ycw,yexp); %!test %! x=[0 0 2 2 NaN 0 2 0]; y=[0 2 2 0 NaN 0 0 3]; %! [xcw,ycw]=poly2cw(x,y); %! xexp=[0; 0; 2; 2; NaN; 0; 0; 2]; %! yexp=[0; 2; 2; 0; NaN; 0; 3; 0]; %! assert (xcw,xexp); %! assert (ycw,yexp); ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������geometry-4.0.0/inst/polybool.m����������������������������������������������������������������������0000644�0000000�0000000�00000026754�13615712371�014552� 0����������������������������������������������������������������������������������������������������ustar�00����������������������������������������������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������## Copyright (C) 2017-2019 Philip Nienhuis ## ## 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 ## . ## -*- texinfo -*- ## @deftypefn {Function File} [@var{VXo}, @var{VYo}] = polybool (@var{op}, @var{VX1}, @var{VY1}, @var{VX2}, @var{VY2}) ## @deftypefnx {Function File} [@var{MXYZ}] = polybool (@var{op}, @var{MSP}, @var{MCP}) ## @deftypefnx {Function File} [@var{MXYZ}] = polybool (@dots{}, @var{library}) ## Perform boolean operation(s) on polygons. ## ## The subject and clip polygons can each be represented by two separate ## input vectors. The subject polygon X and Y coordinates would be @var{VX1} ## and @var{VY1}, resp., and the clip polygon(s) X and Y coordinates would be ## @var{VX2} and @var{VY2}. All these vectors can be row or column vectors, ## numeric or cell, and the output format will match that of @var{VX1} and ## @var{VY1}. ## ## Alternatively, the subject and clip polygons can be represented by 2D or ## 3D matrices (@var{MSP} and @var{MCP}, respectively) of X, Y, and ## -optionally- Z values, where each row constitues the coordinates of one ## vertex. The Z values of clip polygon(s) are ignored. Z-values of newly ## created vertices in the output polygon(s) are copied from the nearest ## vertex in the subject polygon(s). ## ## In any case the input polygons can be multipart, where subpolygons are ## separated by NaN values (or NaN rows in case of matrix input). By ## convention, in case of nested polygons the outer polygon should have a ## clockwise winding direction, inner polygons constituting "holes" should ## have a counterclockwise winding direction; polygons nested in holes ## should again be clockwise, and so on. ## ## Every polygon part should comprise at least different 3 vertices. As ## polygons are implicitly assumed to be closed, no need to repeat the first ## vertex as last closing vertex. ## ## Likewise, output polygons returned in @var{VXo} and @var{VYo} (in case ## of vector input) or @var{MXYZ} (in case of matrix input) can be multipart ## and if so also have NaNs or NaN row(s) separating subpolygons. ## ## @var{op} is the requested operation and can be one of the following (for ## character values only the first letter is required, case-independent): ## ## @table @asis ## @item 0 (numeric) ## @itemx "subtraction" ## @itemx "minus" @* ## Subtract the clip polygon(s) from the subject polygon(s). ## ## @item 1 (numeric) ## @itemx "intersection" ## @itemx "and" @* ## Return intersection(s) of subject and clip polygon(s). ## ## @item 2 (numeric) ## @itemx "exclusiveor" ## @itemx "xor" @* ## Return ExclusiveOr(s) of subject and clip polygon(s); this is the ## complement of the 'and' operation or the result of subtracting the output ## of 'and' from 'or' operations on both polygons. ## ## @item 3 (numeric) ## @itemx "union" ## @itemx "or" @* ## Return the union of both input polygons. ## @end table ## ## @seealso{ispolycw,isShapeMultiPart} ## @end deftypefn ## Author: Philip Nienhuis ## Created: 2017-11-12 function [xo, yo] = polybool (op, varargin) ## Input checks if (nargin < 3) ## For matrices we need at least 3 args. For vectors we'll check later. print_usage (); elseif (! ischar (op) && (isnumeric (op) && (op < 0 || op > 3))) error ("Octave:invalid-input-arg", ... "polybool: char value or numeric value [0-3] expected for arg. #1"); endif ## Check subject polygon class and type. ## itype = 1 (column vectors), 2 (row vectors), -1 (matrix), ## 3 (cell column vectors), 4 (cell row vectors) if (isnumeric (varargin{1}) && isnumeric (varargin{2})) sza1 = size (varargin{1}); if (isvector (varargin{1})) ## Separate numeric vector input (ML compatible). Make it a Nx2 matrix itype = 1; X1 = varargin{1}; Y1 = varargin{2}; elseif (numel (sza1) == 2 && prod (sza1) > max (sza1) && ... sza1(1) >= 3 && sza1(1) >= sza1(2)) ## Matrix input (makes Z-values possible), X,Y{,Z] in columns itype = -1; inpol = varargin{1}; else error ("Octave:invalid-input-arg", ... "polybool: Nx2 or Nx3 (with N > 2) numeric input expected for arg #2"); endif elseif (iscell (varargin{1}) && iscell (varargin{2})) ## Always assume (ML-compatible) vector input itype = 3; [X1, Y1] = polyjoin (varargin{1}, varargin{2}); else error ("Octave:invalid-input-arg", ... "polybool: X1, Y1 input vectors must be same class"); endif if (itype != -1) ## X1 and X2 are assumed numeric vectors now if (numel (X1) != numel (Y1)) error ("Octave:invalid-input-arg", ... "polybool: X1, Y1 input vectors must be same length"); endif if (isrow (X1) != isrow (Y1)) error ("Octave:invalid-input-arg", ... "polybool: X1 and Y1 should have same dimension"); endif ## Convert vector input into a Nx2 matrix if (isrow (X1)) ++itype; inpol = [X1; Y1]'; else inpol = [X1 Y1]; endif endif if (size (inpol, 1) < 3) ## Not a polygon error ("Octave:invalid-input-arg", ..., "polybool: input 'polygon' has less than 3 vertices"); endif ## Check clip polygon class and type. ## ctype = 1 (column vectors), 2 (row vectors), -1 (matrix), ## 3 (cell column vectors), 4 (cell row vectors) if (itype == -1) ## Matrix input sza2 = size (varargin{2}); if (numel (sza2) == 2 && prod (sza2) > max (sza2) && ... sza2(1) >= 3 && sza2(1) >= sza2(2)) ctype = -1; clpol = varargin{2}; else error ("Octave:invalid-input-arg", ..., "polybool: Nx3 matrix input (with N > 2) expected for arg #3"); endif elseif (nargin < 5) # For vector input we need at least 5 args print_usage (); else if (isnumeric (varargin{3}) && isnumeric (varargin{4})) ctype = 1; X2 = varargin{3}; Y2 = varargin{4}; elseif (iscell (varargin{3}) && iscell (varargin{4})) ctype = 3; [X2, Y2] = polyjoin (varargin{3}, varargin{4}); else error ("Octave:invalid-input-arg", ... "polybool: X2, Y2 input vectors must be same class"); endif if (isrow (X2) != isrow (Y2)) error ("Octave:invalid-input-arg", ... "polybool: X2 and Y2 should have same dimension"); endif if (numel (X2) != numel (Y2)) error ("Octave:invalid-input-arg", ... "polybool: X2, Y2 input vectors must be same length"); endif ## Turn clip poygon into matrix if (isrow (X2)) ++ctype; clpol = [X2; Y2]'; else clpol = [X2 Y2]; endif endif if (size (inpol, 1) < 3) ## Not a polygon error ("Octave:invalid-input-arg", ..., "polybool: clip 'polygon' has less than 3 vertices"); endif ## Boolean operation library ichar = 0; blib = "clipper"; ## Find out arg no. of library name if (itype == -1 && nargin > 3) ichar = 3; elseif (nargin > 5) ichar = 5; endif if (ichar) if (ischar (varargin{ichar})) blib = lower (varargin{ichar}); if (! ismember (blib, {"clipper", "mrf"})) error ("Octave:invalid-input-arg", ..., "polybool: unknown polygon library - %s", blib); endif elseif (! ischar (varargin{ichar})) print_usage (); endif endif if (ischar (op)) switch (lower (op(1))) case {"s", "m", "-"} ## Subtraction op = 0; case {"i", "a", "&"} ## Intersection / And op = 1; case {"e", "x"} ## ExclusiveOR op = 2; case {"u", "o", "|", "+", "p"} ## Union / Or op = 3; otherwise error ("Octave:invalid-input-arg", ... "polybool: unknown operation '%s'", op); endswitch endif ## Call clipPolygon (geometry pkg) to do the work try if (strcmp (blib, "clipper")) [outpol, npol] = clipPolygon_clipper (inpol, clpol, op); else [outpol, npol] = clipPolygon_mrf (inpol, clpol, op); endif catch error ("polybool: internal error, possibly invalid geometric input"); end_try_catch ## Postprocess output to match input formats switch itype case 1 ## Numeric column input xo = outpol(:, 1); yo = outpol(:, 2); case 2 ## Numeric row input xo = outpol(:, 1)'; yo = outpol(:, 2)'; case 3 ## cell column input xo = {outpol(:, 1)}; yo = {outpol(:, 2)}; case 4 ## Cell row input xo = {outpol(:, 1)'}; yo = {outpol(:, 2)'}; case -1 ## Matrix input xo = outpol; yo = []; otherwise endswitch endfunction %!shared ipol, cpol, ix, iy, cx, cy, xi, yi, xc, yc %! ipol = [0 0; 3 0; 3 3; 0 3; 0 0]; %! cpol = [2, 1; 5, 1; 5, 4; 2, 4; 2, 1]; %! ix = {ipol(:, 1)'}; %! iy = {ipol(:, 2)'}; %! cx = {cpol(:, 1)'}; %! cy = {cpol(:, 2)'}; %! xi = {ipol(:, 1)}; %! yi = {ipol(:, 2)}; %! xc = {cpol(:, 1)}; %! yc = {cpol(:, 2)}; %% Subtraction - matrix input %!test %! opol = polybool (0, ipol, cpol); %! assert (size (opol), [7, 2]); %! assert (polygonArea (opol), 7); %% Subtraction - row vector input input %!test %! [ox, oy] = polybool (0, ix, iy, cx, cy); %! opol = [ox{1}', oy{1}']; %! assert (size (opol), [7, 2]); %! assert (polygonArea (opol), 7); %% Subtraction - column vector input input %!test %! [ox, oy] = polybool (0, xi, yi, xc, yc); %! opol = [ox{1}, oy{1}]; %! assert (size (opol), [7, 2]); %! assert (polygonArea (opol), 7); %!test %! opol = polybool (1, cpol, ipol); %! assert (size (opol), [5, 2]); %! assert (polygonArea (opol), 2); %!test %! [ox, oy] = polybool (1, ix, iy, cx, cy); %! opol = [ox{1}', oy{1}']; %! assert (size (opol), [5, 2]); %! assert (polygonArea (opol), 2); %!test %! opol = polybool (2, cpol, ipol); %! assert (size (opol), [15, 2]); %! assert (polygonArea (opol), 14); %!test %! [ox, oy] = polybool (2, ix, iy, cx, cy); %! opol = [ox{1}', oy{1}']; %! assert (size (opol), [15, 2]); %! assert (polygonArea (opol), 14); %!test %! opol = polybool (3, cpol, ipol); %! assert (size (opol), [9, 2]); %! assert (polygonArea (opol), 16); %!test %! [ox, oy] = polybool (3, ix, iy, cx, cy); %! opol = [ox{1}', oy{1}']; %! assert (size (opol), [9, 2]); %! assert (polygonArea (opol), 16); %!error