Jelajahi Sumber

Version 1.0

Viktor Chlumský 9 tahun lalu
induk
melakukan
61d3929db0
99 mengubah file dengan 35698 tambahan dan 0 penghapusan
  1. 677 0
      LICENSE.txt
  2. 3 0
      Makefile
  3. TEMPAT SAMPAH
      Msdfgen.rc
  4. 28 0
      Msdfgen.sln
  5. 182 0
      Msdfgen.vcxproj
  6. 151 0
      Msdfgen.vcxproj.filters
  7. 176 0
      README.md
  8. 77 0
      core/Bitmap.cpp
  9. 40 0
      core/Bitmap.h
  10. 26 0
      core/Contour.cpp
  11. 28 0
      core/Contour.h
  12. 18 0
      core/EdgeColor.h
  13. 67 0
      core/EdgeHolder.cpp
  14. 38 0
      core/EdgeHolder.h
  15. 56 0
      core/Shape.cpp
  16. 35 0
      core/Shape.h
  17. 30 0
      core/SignedDistance.cpp
  18. 25 0
      core/SignedDistance.h
  19. 146 0
      core/Vector2.cpp
  20. 66 0
      core/Vector2.h
  21. 57 0
      core/arithmetics.hpp
  22. 75 0
      core/edge-coloring.cpp
  23. 15 0
      core/edge-coloring.h
  24. 334 0
      core/edge-segments.cpp
  25. 101 0
      core/edge-segments.h
  26. 69 0
      core/equation-solver.cpp
  27. 15 0
      core/equation-solver.h
  28. 166 0
      core/msdfgen.cpp
  29. 107 0
      core/render-sdf.cpp
  30. 19 0
      core/render-sdf.h
  31. 109 0
      core/save-bmp.cpp
  32. 12 0
      core/save-bmp.h
  33. 285 0
      core/shape-description.cpp
  34. 16 0
      core/shape-description.h
  35. 1 0
      example.bat
  36. 192 0
      ext/import-font.cpp
  37. 29 0
      ext/import-font.h
  38. 184 0
      ext/import-svg.cpp
  39. 12 0
      ext/import-svg.h
  40. 30 0
      ext/save-png.cpp
  41. 12 0
      ext/save-png.h
  42. TEMPAT SAMPAH
      freetype6.dll
  43. TEMPAT SAMPAH
      icon.ico
  44. 350 0
      include/freetype/config/ftconfig.h
  45. 729 0
      include/freetype/config/ftheader.h
  46. 22 0
      include/freetype/config/ftmodule.h
  47. 695 0
      include/freetype/config/ftoption.h
  48. 180 0
      include/freetype/config/ftstdlib.h
  49. 3434 0
      include/freetype/freetype.h
  50. 94 0
      include/freetype/ftbbox.h
  51. 200 0
      include/freetype/ftbdf.h
  52. 206 0
      include/freetype/ftbitmap.h
  53. 1110 0
      include/freetype/ftcache.h
  54. 100 0
      include/freetype/ftchapters.h
  55. 239 0
      include/freetype/fterrdef.h
  56. 206 0
      include/freetype/fterrors.h
  57. 113 0
      include/freetype/ftgasp.h
  58. 575 0
      include/freetype/ftglyph.h
  59. 358 0
      include/freetype/ftgxval.h
  60. 102 0
      include/freetype/ftgzip.h
  61. 1237 0
      include/freetype/ftimage.h
  62. 331 0
      include/freetype/ftincrem.h
  63. 166 0
      include/freetype/ftlcdfil.h
  64. 273 0
      include/freetype/ftlist.h
  65. 99 0
      include/freetype/ftlzw.h
  66. 272 0
      include/freetype/ftmac.h
  67. 378 0
      include/freetype/ftmm.h
  68. 406 0
      include/freetype/ftmodapi.h
  69. 155 0
      include/freetype/ftmoderr.h
  70. 198 0
      include/freetype/ftotval.h
  71. 526 0
      include/freetype/ftoutln.h
  72. 172 0
      include/freetype/ftpfr.h
  73. 229 0
      include/freetype/ftrender.h
  74. 159 0
      include/freetype/ftsizes.h
  75. 170 0
      include/freetype/ftsnames.h
  76. 716 0
      include/freetype/ftstroke.h
  77. 73 0
      include/freetype/ftsynth.h
  78. 346 0
      include/freetype/ftsystem.h
  79. 350 0
      include/freetype/fttrigon.h
  80. 583 0
      include/freetype/fttypes.h
  81. 263 0
      include/freetype/ftwinfnt.h
  82. 80 0
      include/freetype/ftxf86.h
  83. 450 0
      include/freetype/t1tables.h
  84. 1132 0
      include/freetype/ttnameid.h
  85. 756 0
      include/freetype/tttables.h
  86. 99 0
      include/freetype/tttags.h
  87. 59 0
      include/freetype/ttunpat.h
  88. 61 0
      include/ft2build.h
  89. 1759 0
      include/lodepng.h
  90. 2102 0
      include/tinyxml2.h
  91. 169 0
      lib/FTL.TXT
  92. TEMPAT SAMPAH
      lib/freetype.lib
  93. 6223 0
      lib/lodepng.cpp
  94. 2467 0
      lib/tinyxml2.cpp
  95. 754 0
      main.cpp
  96. 23 0
      msdfgen-ext.h
  97. TEMPAT SAMPAH
      msdfgen.exe
  98. 40 0
      msdfgen.h
  99. TEMPAT SAMPAH
      resource.h

+ 677 - 0
LICENSE.txt

@@ -0,0 +1,677 @@
+
+
+                    GNU GENERAL PUBLIC LICENSE
+                       Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+                            Preamble
+
+  The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+  The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works.  By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users.  We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors.  You can apply it to
+your programs, too.
+
+  When we speak of free software, we are referring to freedom, not
+price.  Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+  To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights.  Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+  For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received.  You must make sure that they, too, receive
+or can get the source code.  And you must show them these terms so they
+know their rights.
+
+  Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+  For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software.  For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+  Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so.  This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software.  The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable.  Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products.  If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+  Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary.  To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+  The precise terms and conditions for copying, distribution and
+modification follow.
+
+                       TERMS AND CONDITIONS
+
+  0. Definitions.
+
+  "This License" refers to version 3 of the GNU General Public License.
+
+  "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+  "The Program" refers to any copyrightable work licensed under this
+License.  Each licensee is addressed as "you".  "Licensees" and
+"recipients" may be individuals or organizations.
+
+  To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy.  The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+  A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+  To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy.  Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+  To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies.  Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+  An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License.  If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+  1. Source Code.
+
+  The "source code" for a work means the preferred form of the work
+for making modifications to it.  "Object code" means any non-source
+form of a work.
+
+  A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+  The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form.  A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+  The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities.  However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work.  For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+  The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+  The Corresponding Source for a work in source code form is that
+same work.
+
+  2. Basic Permissions.
+
+  All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met.  This License explicitly affirms your unlimited
+permission to run the unmodified Program.  The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work.  This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+  You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force.  You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright.  Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+  Conveying under any other circumstances is permitted solely under
+the conditions stated below.  Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+  3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+  No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+  When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+  4. Conveying Verbatim Copies.
+
+  You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+  You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+  5. Conveying Modified Source Versions.
+
+  You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+    a) The work must carry prominent notices stating that you modified
+    it, and giving a relevant date.
+
+    b) The work must carry prominent notices stating that it is
+    released under this License and any conditions added under section
+    7.  This requirement modifies the requirement in section 4 to
+    "keep intact all notices".
+
+    c) You must license the entire work, as a whole, under this
+    License to anyone who comes into possession of a copy.  This
+    License will therefore apply, along with any applicable section 7
+    additional terms, to the whole of the work, and all its parts,
+    regardless of how they are packaged.  This License gives no
+    permission to license the work in any other way, but it does not
+    invalidate such permission if you have separately received it.
+
+    d) If the work has interactive user interfaces, each must display
+    Appropriate Legal Notices; however, if the Program has interactive
+    interfaces that do not display Appropriate Legal Notices, your
+    work need not make them do so.
+
+  A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit.  Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+  6. Conveying Non-Source Forms.
+
+  You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+    a) Convey the object code in, or embodied in, a physical product
+    (including a physical distribution medium), accompanied by the
+    Corresponding Source fixed on a durable physical medium
+    customarily used for software interchange.
+
+    b) Convey the object code in, or embodied in, a physical product
+    (including a physical distribution medium), accompanied by a
+    written offer, valid for at least three years and valid for as
+    long as you offer spare parts or customer support for that product
+    model, to give anyone who possesses the object code either (1) a
+    copy of the Corresponding Source for all the software in the
+    product that is covered by this License, on a durable physical
+    medium customarily used for software interchange, for a price no
+    more than your reasonable cost of physically performing this
+    conveying of source, or (2) access to copy the
+    Corresponding Source from a network server at no charge.
+
+    c) Convey individual copies of the object code with a copy of the
+    written offer to provide the Corresponding Source.  This
+    alternative is allowed only occasionally and noncommercially, and
+    only if you received the object code with such an offer, in accord
+    with subsection 6b.
+
+    d) Convey the object code by offering access from a designated
+    place (gratis or for a charge), and offer equivalent access to the
+    Corresponding Source in the same way through the same place at no
+    further charge.  You need not require recipients to copy the
+    Corresponding Source along with the object code.  If the place to
+    copy the object code is a network server, the Corresponding Source
+    may be on a different server (operated by you or a third party)
+    that supports equivalent copying facilities, provided you maintain
+    clear directions next to the object code saying where to find the
+    Corresponding Source.  Regardless of what server hosts the
+    Corresponding Source, you remain obligated to ensure that it is
+    available for as long as needed to satisfy these requirements.
+
+    e) Convey the object code using peer-to-peer transmission, provided
+    you inform other peers where the object code and Corresponding
+    Source of the work are being offered to the general public at no
+    charge under subsection 6d.
+
+  A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+  A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling.  In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage.  For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product.  A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+  "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source.  The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+  If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information.  But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+  The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed.  Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+  Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+  7. Additional Terms.
+
+  "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law.  If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+  When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it.  (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.)  You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+  Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+    a) Disclaiming warranty or limiting liability differently from the
+    terms of sections 15 and 16 of this License; or
+
+    b) Requiring preservation of specified reasonable legal notices or
+    author attributions in that material or in the Appropriate Legal
+    Notices displayed by works containing it; or
+
+    c) Prohibiting misrepresentation of the origin of that material, or
+    requiring that modified versions of such material be marked in
+    reasonable ways as different from the original version; or
+
+    d) Limiting the use for publicity purposes of names of licensors or
+    authors of the material; or
+
+    e) Declining to grant rights under trademark law for use of some
+    trade names, trademarks, or service marks; or
+
+    f) Requiring indemnification of licensors and authors of that
+    material by anyone who conveys the material (or modified versions of
+    it) with contractual assumptions of liability to the recipient, for
+    any liability that these contractual assumptions directly impose on
+    those licensors and authors.
+
+  All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10.  If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term.  If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+  If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+  Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+  8. Termination.
+
+  You may not propagate or modify a covered work except as expressly
+provided under this License.  Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+  However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+  Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+  Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License.  If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+  9. Acceptance Not Required for Having Copies.
+
+  You are not required to accept this License in order to receive or
+run a copy of the Program.  Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance.  However,
+nothing other than this License grants you permission to propagate or
+modify any covered work.  These actions infringe copyright if you do
+not accept this License.  Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+  10. Automatic Licensing of Downstream Recipients.
+
+  Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License.  You are not responsible
+for enforcing compliance by third parties with this License.
+
+  An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations.  If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+  You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License.  For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+  11. Patents.
+
+  A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based.  The
+work thus licensed is called the contributor's "contributor version".
+
+  A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version.  For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+  Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+  In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement).  To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+  If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients.  "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+  If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+  A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License.  You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+  Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+  12. No Surrender of Others' Freedom.
+
+  If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License.  If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all.  For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+  13. Use with the GNU Affero General Public License.
+
+  Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work.  The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+  14. Revised Versions of this License.
+
+  The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time.  Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+  Each version is given a distinguishing version number.  If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation.  If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+  If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+  Later license versions may give you additional or different
+permissions.  However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+  15. Disclaimer of Warranty.
+
+  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+  16. Limitation of Liability.
+
+  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+  17. Interpretation of Sections 15 and 16.
+
+  If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+                     END OF TERMS AND CONDITIONS
+
+            How to Apply These Terms to Your New Programs
+
+  If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+  To do so, attach the following notices to the program.  It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+    {one line to give the program's name and a brief idea of what it does.}
+    Copyright (C) {year}  {name of author}
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation, either version 3 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+Also add information on how to contact you by electronic and paper mail.
+
+  If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+    {project}  Copyright (C) {year}  {fullname}
+    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
+<http://www.gnu.org/licenses/>.
+
+  The GNU General Public License does not permit incorporating your program
+into proprietary programs.  If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library.  If this is what you want to do, use the GNU Lesser General
+Public License instead of this License.  But first, please read
+<http://www.gnu.org/philosophy/why-not-lgpl.html>.
+

+ 3 - 0
Makefile

@@ -0,0 +1,3 @@
+
+all:
+	g++ -I include -D MSDFGEN_STANDALONE -O2 -o msdfgen core/*.cpp lib/*.cpp ext/*.cpp main.cpp -lfreetype

TEMPAT SAMPAH
Msdfgen.rc


+ 28 - 0
Msdfgen.sln

@@ -0,0 +1,28 @@
+
+Microsoft Visual Studio Solution File, Format Version 12.00
+# Visual Studio 14
+VisualStudioVersion = 14.0.24720.0
+MinimumVisualStudioVersion = 10.0.40219.1
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Msdfgen", "Msdfgen.vcxproj", "{84BE2D91-F071-4151-BE12-61460464C494}"
+EndProject
+Global
+	GlobalSection(SolutionConfigurationPlatforms) = preSolution
+		Debug|x64 = Debug|x64
+		Debug|x86 = Debug|x86
+		Release|x64 = Release|x64
+		Release|x86 = Release|x86
+	EndGlobalSection
+	GlobalSection(ProjectConfigurationPlatforms) = postSolution
+		{84BE2D91-F071-4151-BE12-61460464C494}.Debug|x64.ActiveCfg = Debug|x64
+		{84BE2D91-F071-4151-BE12-61460464C494}.Debug|x64.Build.0 = Debug|x64
+		{84BE2D91-F071-4151-BE12-61460464C494}.Debug|x86.ActiveCfg = Debug|Win32
+		{84BE2D91-F071-4151-BE12-61460464C494}.Debug|x86.Build.0 = Debug|Win32
+		{84BE2D91-F071-4151-BE12-61460464C494}.Release|x64.ActiveCfg = Release|x64
+		{84BE2D91-F071-4151-BE12-61460464C494}.Release|x64.Build.0 = Release|x64
+		{84BE2D91-F071-4151-BE12-61460464C494}.Release|x86.ActiveCfg = Release|Win32
+		{84BE2D91-F071-4151-BE12-61460464C494}.Release|x86.Build.0 = Release|Win32
+	EndGlobalSection
+	GlobalSection(SolutionProperties) = preSolution
+		HideSolutionNode = FALSE
+	EndGlobalSection
+EndGlobal

+ 182 - 0
Msdfgen.vcxproj

@@ -0,0 +1,182 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project DefaultTargets="Build" ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <ItemGroup Label="ProjectConfigurations">
+    <ProjectConfiguration Include="Debug|Win32">
+      <Configuration>Debug</Configuration>
+      <Platform>Win32</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Release|Win32">
+      <Configuration>Release</Configuration>
+      <Platform>Win32</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Debug|x64">
+      <Configuration>Debug</Configuration>
+      <Platform>x64</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Release|x64">
+      <Configuration>Release</Configuration>
+      <Platform>x64</Platform>
+    </ProjectConfiguration>
+  </ItemGroup>
+  <PropertyGroup Label="Globals">
+    <ProjectGuid>{84BE2D91-F071-4151-BE12-61460464C494}</ProjectGuid>
+    <RootNamespace>Msdfgen</RootNamespace>
+    <WindowsTargetPlatformVersion>8.1</WindowsTargetPlatformVersion>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
+    <ConfigurationType>Application</ConfigurationType>
+    <UseDebugLibraries>true</UseDebugLibraries>
+    <PlatformToolset>v140</PlatformToolset>
+    <CharacterSet>MultiByte</CharacterSet>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
+    <ConfigurationType>Application</ConfigurationType>
+    <UseDebugLibraries>false</UseDebugLibraries>
+    <PlatformToolset>v140</PlatformToolset>
+    <WholeProgramOptimization>true</WholeProgramOptimization>
+    <CharacterSet>MultiByte</CharacterSet>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
+    <ConfigurationType>Application</ConfigurationType>
+    <UseDebugLibraries>true</UseDebugLibraries>
+    <PlatformToolset>v140</PlatformToolset>
+    <CharacterSet>MultiByte</CharacterSet>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
+    <ConfigurationType>Application</ConfigurationType>
+    <UseDebugLibraries>false</UseDebugLibraries>
+    <PlatformToolset>v140</PlatformToolset>
+    <WholeProgramOptimization>true</WholeProgramOptimization>
+    <CharacterSet>MultiByte</CharacterSet>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
+  <ImportGroup Label="ExtensionSettings">
+  </ImportGroup>
+  <ImportGroup Label="Shared">
+  </ImportGroup>
+  <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <PropertyGroup Label="UserMacros" />
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+    <TargetName>msdfgen</TargetName>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+    <TargetName>msdfgen</TargetName>
+    <OutDir>$(SolutionDir)\</OutDir>
+  </PropertyGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+    <ClCompile>
+      <WarningLevel>Level3</WarningLevel>
+      <Optimization>Disabled</Optimization>
+      <SDLCheck>true</SDLCheck>
+      <PreprocessorDefinitions>MSDFGEN_STANDALONE;MSDFGEN_USE_CPP11;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
+      <AdditionalIncludeDirectories>include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+    </ClCompile>
+    <Link>
+      <SubSystem>Console</SubSystem>
+      <AdditionalLibraryDirectories>lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
+    </Link>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
+    <ClCompile>
+      <WarningLevel>Level3</WarningLevel>
+      <Optimization>Disabled</Optimization>
+      <SDLCheck>true</SDLCheck>
+    </ClCompile>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+    <ClCompile>
+      <WarningLevel>Level3</WarningLevel>
+      <Optimization>MaxSpeed</Optimization>
+      <FunctionLevelLinking>true</FunctionLevelLinking>
+      <IntrinsicFunctions>true</IntrinsicFunctions>
+      <SDLCheck>true</SDLCheck>
+      <PreprocessorDefinitions>MSDFGEN_STANDALONE;MSDFGEN_USE_CPP11;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
+      <AdditionalIncludeDirectories>include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+    </ClCompile>
+    <Link>
+      <EnableCOMDATFolding>true</EnableCOMDATFolding>
+      <OptimizeReferences>true</OptimizeReferences>
+      <SubSystem>Console</SubSystem>
+      <AdditionalLibraryDirectories>lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
+    </Link>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
+    <ClCompile>
+      <WarningLevel>Level3</WarningLevel>
+      <Optimization>MaxSpeed</Optimization>
+      <FunctionLevelLinking>true</FunctionLevelLinking>
+      <IntrinsicFunctions>true</IntrinsicFunctions>
+      <SDLCheck>true</SDLCheck>
+    </ClCompile>
+    <Link>
+      <EnableCOMDATFolding>true</EnableCOMDATFolding>
+      <OptimizeReferences>true</OptimizeReferences>
+    </Link>
+  </ItemDefinitionGroup>
+  <ItemGroup>
+    <ClInclude Include="core\arithmetics.hpp" />
+    <ClInclude Include="core\Bitmap.h" />
+    <ClInclude Include="core\Contour.h" />
+    <ClInclude Include="core\edge-coloring.h" />
+    <ClInclude Include="core\edge-segments.h" />
+    <ClInclude Include="core\EdgeColor.h" />
+    <ClInclude Include="core\EdgeHolder.h" />
+    <ClInclude Include="core\equation-solver.h" />
+    <ClInclude Include="core\render-sdf.h" />
+    <ClInclude Include="core\save-bmp.h" />
+    <ClInclude Include="core\shape-description.h" />
+    <ClInclude Include="core\Shape.h" />
+    <ClInclude Include="core\SignedDistance.h" />
+    <ClInclude Include="core\Vector2.h" />
+    <ClInclude Include="ext\import-font.h" />
+    <ClInclude Include="ext\import-svg.h" />
+    <ClInclude Include="ext\save-png.h" />
+    <ClInclude Include="msdfgen-ext.h" />
+    <ClInclude Include="msdfgen.h" />
+    <ClInclude Include="resource.h" />
+  </ItemGroup>
+  <ItemGroup>
+    <ClCompile Include="core\Bitmap.cpp" />
+    <ClCompile Include="core\Contour.cpp" />
+    <ClCompile Include="core\edge-coloring.cpp" />
+    <ClCompile Include="core\edge-segments.cpp" />
+    <ClCompile Include="core\EdgeHolder.cpp" />
+    <ClCompile Include="core\equation-solver.cpp" />
+    <ClCompile Include="core\render-sdf.cpp" />
+    <ClCompile Include="core\save-bmp.cpp" />
+    <ClCompile Include="core\shape-description.cpp" />
+    <ClCompile Include="core\Shape.cpp" />
+    <ClCompile Include="core\SignedDistance.cpp" />
+    <ClCompile Include="core\Vector2.cpp" />
+    <ClCompile Include="ext\import-font.cpp" />
+    <ClCompile Include="ext\import-svg.cpp" />
+    <ClCompile Include="ext\save-png.cpp" />
+    <ClCompile Include="lib\lodepng.cpp" />
+    <ClCompile Include="lib\tinyxml2.cpp" />
+    <ClCompile Include="main.cpp" />
+    <ClCompile Include="core\msdfgen.cpp" />
+  </ItemGroup>
+  <ItemGroup>
+    <ResourceCompile Include="Msdfgen.rc" />
+  </ItemGroup>
+  <ItemGroup>
+    <Image Include="icon.ico" />
+  </ItemGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
+  <ImportGroup Label="ExtensionTargets">
+  </ImportGroup>
+</Project>

+ 151 - 0
Msdfgen.vcxproj.filters

@@ -0,0 +1,151 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <ItemGroup>
+    <Filter Include="Resource Files">
+      <UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
+      <Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
+    </Filter>
+    <Filter Include="Core">
+      <UniqueIdentifier>{110bf5de-0605-40a4-92b4-68ca012d572f}</UniqueIdentifier>
+    </Filter>
+    <Filter Include="Extensions">
+      <UniqueIdentifier>{8abe3d60-6507-4ee1-8d4f-eab2c43a3220}</UniqueIdentifier>
+    </Filter>
+    <Filter Include="Standalone">
+      <UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
+      <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
+    </Filter>
+    <Filter Include="Source Dependencies">
+      <UniqueIdentifier>{42db228a-5d46-439c-ad30-7595a74d635f}</UniqueIdentifier>
+    </Filter>
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="core\arithmetics.hpp">
+      <Filter>Core</Filter>
+    </ClInclude>
+    <ClInclude Include="core\Bitmap.h">
+      <Filter>Core</Filter>
+    </ClInclude>
+    <ClInclude Include="core\Contour.h">
+      <Filter>Core</Filter>
+    </ClInclude>
+    <ClInclude Include="core\EdgeColor.h">
+      <Filter>Core</Filter>
+    </ClInclude>
+    <ClInclude Include="core\edge-coloring.h">
+      <Filter>Core</Filter>
+    </ClInclude>
+    <ClInclude Include="core\EdgeHolder.h">
+      <Filter>Core</Filter>
+    </ClInclude>
+    <ClInclude Include="core\edge-segments.h">
+      <Filter>Core</Filter>
+    </ClInclude>
+    <ClInclude Include="core\equation-solver.h">
+      <Filter>Core</Filter>
+    </ClInclude>
+    <ClInclude Include="msdfgen.h">
+      <Filter>Core</Filter>
+    </ClInclude>
+    <ClInclude Include="core\render-sdf.h">
+      <Filter>Core</Filter>
+    </ClInclude>
+    <ClInclude Include="core\save-bmp.h">
+      <Filter>Core</Filter>
+    </ClInclude>
+    <ClInclude Include="core\Shape.h">
+      <Filter>Core</Filter>
+    </ClInclude>
+    <ClInclude Include="core\shape-description.h">
+      <Filter>Core</Filter>
+    </ClInclude>
+    <ClInclude Include="core\Vector2.h">
+      <Filter>Core</Filter>
+    </ClInclude>
+    <ClInclude Include="core\SignedDistance.h">
+      <Filter>Core</Filter>
+    </ClInclude>
+    <ClInclude Include="msdfgen-ext.h">
+      <Filter>Extensions</Filter>
+    </ClInclude>
+    <ClInclude Include="ext\save-png.h">
+      <Filter>Extensions</Filter>
+    </ClInclude>
+    <ClInclude Include="ext\import-svg.h">
+      <Filter>Extensions</Filter>
+    </ClInclude>
+    <ClInclude Include="ext\import-font.h">
+      <Filter>Extensions</Filter>
+    </ClInclude>
+    <ClInclude Include="resource.h" />
+  </ItemGroup>
+  <ItemGroup>
+    <ClCompile Include="main.cpp">
+      <Filter>Standalone</Filter>
+    </ClCompile>
+    <ClCompile Include="core\Bitmap.cpp">
+      <Filter>Core</Filter>
+    </ClCompile>
+    <ClCompile Include="core\Contour.cpp">
+      <Filter>Core</Filter>
+    </ClCompile>
+    <ClCompile Include="core\edge-coloring.cpp">
+      <Filter>Core</Filter>
+    </ClCompile>
+    <ClCompile Include="core\EdgeHolder.cpp">
+      <Filter>Core</Filter>
+    </ClCompile>
+    <ClCompile Include="core\edge-segments.cpp">
+      <Filter>Core</Filter>
+    </ClCompile>
+    <ClCompile Include="core\equation-solver.cpp">
+      <Filter>Core</Filter>
+    </ClCompile>
+    <ClCompile Include="ext\import-font.cpp">
+      <Filter>Extensions</Filter>
+    </ClCompile>
+    <ClCompile Include="ext\import-svg.cpp">
+      <Filter>Extensions</Filter>
+    </ClCompile>
+    <ClCompile Include="core\render-sdf.cpp">
+      <Filter>Core</Filter>
+    </ClCompile>
+    <ClCompile Include="core\save-bmp.cpp">
+      <Filter>Core</Filter>
+    </ClCompile>
+    <ClCompile Include="ext\save-png.cpp">
+      <Filter>Extensions</Filter>
+    </ClCompile>
+    <ClCompile Include="core\Shape.cpp">
+      <Filter>Core</Filter>
+    </ClCompile>
+    <ClCompile Include="core\shape-description.cpp">
+      <Filter>Core</Filter>
+    </ClCompile>
+    <ClCompile Include="core\SignedDistance.cpp">
+      <Filter>Core</Filter>
+    </ClCompile>
+    <ClCompile Include="core\Vector2.cpp">
+      <Filter>Core</Filter>
+    </ClCompile>
+    <ClCompile Include="lib\lodepng.cpp">
+      <Filter>Source Dependencies</Filter>
+    </ClCompile>
+    <ClCompile Include="lib\tinyxml2.cpp">
+      <Filter>Source Dependencies</Filter>
+    </ClCompile>
+    <ClCompile Include="core\msdfgen.cpp">
+      <Filter>Core</Filter>
+    </ClCompile>
+  </ItemGroup>
+  <ItemGroup>
+    <ResourceCompile Include="Msdfgen.rc">
+      <Filter>Resource Files</Filter>
+    </ResourceCompile>
+  </ItemGroup>
+  <ItemGroup>
+    <Image Include="icon.ico">
+      <Filter>Resource Files</Filter>
+    </Image>
+  </ItemGroup>
+</Project>

+ 176 - 0
README.md

@@ -0,0 +1,176 @@
+# Multi-channel signed distance field generator
+
+This is a utility for generating signed distance fields from vector shapes and font glyphs,
+which serve as a texture representation that can be used in real-time graphics to efficiently reproduce said shapes.
+Although it can also be used to generate conventional signed distance fields best known from
+[this Valve paper](http://www.valvesoftware.com/publications/2007/SIGGRAPH2007_AlphaTestedMagnification.pdf)
+and pseudo-distance fields, its primary purpose is to generate multi-channel distance fields,
+using a method I have developed. Unlike monochrome distance fields, they have the ability
+to reproduce sharp corners almost perfectly by utilizing all three color channels.
+
+The following sequence of images demonstrates the improvement in image quality.
+
+![demo-msdf16](https://cloud.githubusercontent.com/assets/18639794/14770355/14cda9f8-0a70-11e6-8346-2bd14b5b832f.png)
+![demo-sdf16](https://cloud.githubusercontent.com/assets/18639794/14770360/20c51156-0a70-11e6-8f03-ed7632d07997.png)
+![demo-sdf32](https://cloud.githubusercontent.com/assets/18639794/14770361/251a4406-0a70-11e6-95a7-e30e235ac729.png)
+
+## Getting started
+
+The project can be used either as a library or as a console program. is divided into two parts, **[core](core)**
+and **[extensions](ext)**. The core module has no dependencies and only uses bare C++. It contains all
+key data structures and algorithms, which can be accessed through the [msdfgen.h](msdfgen.h) header.
+Extensions contain utilities for loading fonts and SVG files, as well as saving PNG images.
+Those are exposed by the [msdfgen-ext.h](msdfgen-ext.h) header. This module uses
+[FreeType](http://www.freetype.org/),
+[TinyXML2](http://www.grinninglizard.com/tinyxml2/),
+and [LodePNG](http://lodev.org/lodepng/).
+
+Additionaly, there is the [main.cpp](main.cpp), which wraps the functionality into
+a comprehensive standalone console program. To start using the program immediately,
+a Windows binary of this program, [msdfgen.exe](msdfgen.exe), is available in the root directory.
+
+## Console commands
+
+The standalone program is executed as
+```
+msdfgen.exe <mode> <input> <options>
+```
+where only the input specification is required.
+
+Mode can be one of:
+ - **sdf** &ndash; generates a conventional monochrome signed distance field.
+ - **psdf** &ndash; generates a monochrome signed pseudo-distance field.
+ - **msdf** (default) &ndash; generates a multi-channel signed distance field using my new method.
+
+The input can be specified as one of:
+ - **-font \<filename.ttf\> \<character code\>** &ndash; to load a glyph from a font file.
+   Character code can be expressed as either a decimal (63) or hexadecimal (0x3F) Unicode value, or an ASCII character
+   in single quotes ('?').
+ - **-svg \<filename.svg\>** &ndash; to load an SVG file. Note that only the first vector path in the file will be used.
+ - **-shapedesc \<filename.txt\>**, -defineshape \<definition\>, -stdin &ndash; to load a text description of the shape
+   from either a file, the next argument, or the standard input, respectively. Its syntax is documented further down.
+
+The complete list of available options can be printed with **-help**.
+Some of the important ones are:
+ - **-o \<filename\>** &ndash; specifies the output file name. The desired format will be deduced from the extension
+   (png, bmp, txt, bin). Otherwise, use -format.
+ - **-size \<width\> \<height\>** &ndash; specifies the dimensions of the output distance field (in pixels).
+ - **-range \<range\>**, **-pxrange \<range\>** &ndash; specifies the width of the range around the shape
+   between the minimum and maximum representable signed distance in shape units or distance field pixels, respectivelly.
+ - **-autoframe** &ndash; automatically frames the shape to fit the distance field. If the output must be precisely aligned,
+   you should manually position it using -translate and -scale instead.
+ - **-scale \<scale\>** &ndash; sets the scale used to convert shape units to distance field pixels.
+ - **-translate \<x\> \<y\>** &ndash; sets the translation of the shape in shape units. Otherwise the origin (0, 0)
+   lies in the bottom left corner.
+ - **-angle \<angle\>** &ndash; specifies the maximum angle to be considered a corner.
+   Can be expressed in radians (3.0) or degrees with D at the end (171.9D).
+ - **-testrender \<filename.png\> \<width\> \<height\>** - tests the generated distance field by using it to render an image
+   of the original shape into a PNG file with the specified dimensions. Alternatively, -testrendermulti renders
+   an image without combining the color channels, and may give you an insight in how the multi-channel distance field works.
+ - **-exportshape \<filename.txt\>** - saves the text description of the shape with edge coloring to the specified file.
+   This can be later edited and used as input through -shapedesc.
+ - **-printmetrics** &ndash; prints some useful information about the shape's layout.
+
+For example,
+```
+msdfgen.exe msdf -font C:\Windows\Fonts\arialbd.ttf 'M' -o msdf.png -size 32 32 -pxrange 4 -autoframe -testrender render.png 1024 1024
+```
+
+will take the glyph capital M from the Arial Bold typeface, generate a 32&times;32 multi-channel distance field
+with a 4 pixels wide distance range, store it into msdf.png, and create a test render of the glyph as render.png.
+
+## Library API
+
+If you choose to use this utility inside your own program, there are a few simple steps you need to perform
+in order to generate a distance field. Please note that all classes and functions are in the `msdfgen` namespace.
+
+ - Acquire a `Shape` object. You can either load it via `loadGlyph` or `loadSvgShape`, or construct it manually.
+   It consists of closed contours, which in turn consist of edges. An edge is represented by a `LinearEdge`, `QuadraticEdge`,
+   or `CubicEdge`. You can construct them from two endpoints and 0 to 2 Bézier control points.
+ - Normalize the shape using its `normalize` method and assign colors to edges if you need a multi-channel SDF.
+   This can be performed automatically using the `edgeColoringSimple` heuristic, or manually by setting each edge's
+   `color` member. Keep in mind that at least two color channels must be turned on in each edge, and the color should
+   only change at corners.
+ - Call `generateSDF`, `generatePseudoSDF`, or `generateMSDF` to generate a distance field into a floating point
+   `Bitmap` object. This can then be worked with further or saved to a file using `saveBmp` or `savePng`.
+ - You may also render an image from the distance field using `renderSDF`. Consider calling `simulate8bit`
+   on the distance field beforehand to simulate the standard 8 bits/pixel image format.
+
+Example:
+```c++
+#include "msdfgen.h"
+#include "msdfgen-ext.h"
+
+using namespace msdfgen;
+
+int main() {
+    FreetypeHandle *ft = initializeFreetype();
+    if (ft) {
+        FontHandle *font = loadFont(ft, "C:\\Windows\\Fonts\\arialbd.ttf");
+        if (font) {
+            Shape shape;
+            if (loadGlyph(shape, font, 'A')) {
+                shape.normalize();
+                //                      max. angle
+                edgeColoringSimple(shape, 3.0);
+                //           image width, height
+                Bitmap<FloatRGB> msdf(32, 32);
+                //                     range, scale, translation
+                generateMSDF(msdf, shape, 4.0, 1.0, Vector2(4.0, 4.0));
+                savePng(msdf, "output.png");
+            }
+            destroyFont(font);
+        }
+        deinitializeFreetype(ft);
+    }
+    return 0;
+}
+
+```
+
+## Using a multi-channel distance field
+
+Using a multi-channel distance field generated by this program is similarly simple to how a monochrome distance field is used.
+The only additional operation is computing the **median** of the three channels inside the fragment shader,
+right after sampling the distance field. This signed distance value can then be used the same way as usual.
+
+The following is an example GLSL fragment shader including anti-aliasing:
+
+```glsl
+in vec2 pos;
+out vec4 color;
+uniform sampler2D msdf;
+uniform vec4 bgColor;
+uniform vec4 fgColor;
+
+float median(float r, float g, float b) {
+    return max(min(r, g), min(max(r, g), b));
+}
+
+void main() {
+    vec3 sample = texture(msdf, pos).rgb;
+    float sigDist = median(sample.r, sample.g, sample.b) - 0.5;
+    float opacity = clamp(sigDist/fwidth(sigDist) + 0.5, 0.0, 1.0);
+    color = mix(bgColor, fgColor, opacity);
+}
+```
+
+## Shape description syntax
+
+The text shape description has the following syntax.
+ - Each closed contour is enclosed by braces: `{ <contour 1> } { <contour 2> }`
+ - Each point (and control point) is written as two real numbers separated by a comma.
+ - Points in a contour are separated with semicolons.
+ - The last point of each contour must be equal to the first, or the symbol `#` can be used, which represents the first point.
+ - There can be an edge segment specification between any two points, also separated by semicolons.
+   This can include the edge's color (`c`, `m`, or `y`) and/or one or two curve control points inside parentheses.
+   
+For example,
+```
+{ -1, -1; m; -1, +1; y; +1, +1; m; +1, -1; y; # }
+```
+would represent a square with magenta and yellow edges,
+```
+{ 0, 1; (+1.6, -0.8; -1.6, -0.8); # }
+```
+is a teardrop shape formed by a single cubic Bézier curve.

+ 77 - 0
core/Bitmap.cpp

@@ -0,0 +1,77 @@
+
+#include "Bitmap.h"
+
+#include <cstring>
+
+namespace msdfgen {
+
+template <typename T>
+Bitmap<T>::Bitmap() : content(NULL), w(0), h(0) { }
+
+template <typename T>
+Bitmap<T>::Bitmap(int width, int height) : w(width), h(height) {
+    content = new T[w*h];
+}
+
+template <typename T>
+Bitmap<T>::Bitmap(const Bitmap<T> &orig) : w(orig.w), h(orig.h) {
+    content = new T[w*h];
+    memcpy(content, orig.content, w*h*sizeof(T));
+}
+
+#ifdef MSDFGEN_USE_CPP11
+template <typename T>
+Bitmap<T>::Bitmap(Bitmap<T> &&orig) : content(orig.content), w(orig.w), h(orig.h) {
+    orig.content = NULL;
+}
+#endif
+
+template <typename T>
+Bitmap<T>::~Bitmap() {
+    delete [] content;
+}
+
+template <typename T>
+Bitmap<T> & Bitmap<T>::operator=(const Bitmap<T> &orig) {
+    delete [] content;
+    w = orig.w, h = orig.h;
+    content = new T[w*h];
+    memcpy(content, orig.content, w*h*sizeof(T));
+    return *this;
+}
+
+#ifdef MSDFGEN_USE_CPP11
+template <typename T>
+Bitmap<T> & Bitmap<T>::operator=(Bitmap<T> &&orig) {
+    delete [] content;
+    content = orig.content;
+    w = orig.w, h = orig.h;
+    orig.content = NULL;
+    return *this;
+}
+#endif
+
+template <typename T>
+int Bitmap<T>::width() const {
+    return w;
+}
+
+template <typename T>
+int Bitmap<T>::height() const {
+    return h;
+}
+
+template <typename T>
+T & Bitmap<T>::operator()(int x, int y) {
+    return content[y*w+x];
+}
+
+template <typename T>
+const T & Bitmap<T>::operator()(int x, int y) const {
+    return content[y*w+x];
+}
+
+template class Bitmap<float>;
+template class Bitmap<FloatRGB>;
+
+}

+ 40 - 0
core/Bitmap.h

@@ -0,0 +1,40 @@
+
+#pragma once
+
+namespace msdfgen {
+
+/// A floating-point RGB pixel.
+struct FloatRGB {
+    float r, g, b;
+};
+
+/// A 2D image bitmap.
+template <typename T>
+class Bitmap {
+
+public:
+    Bitmap();
+    Bitmap(int width, int height);
+    Bitmap(const Bitmap<T> &orig);
+#ifdef MSDFGEN_USE_CPP11
+    Bitmap(Bitmap<T> &&orig);
+#endif
+    ~Bitmap();
+    Bitmap<T> & operator=(const Bitmap<T> &orig);
+#ifdef MSDFGEN_USE_CPP11
+    Bitmap<T> & operator=(Bitmap<T> &&orig);
+#endif
+    /// Bitmap width in pixels.
+    int width() const;
+    /// Bitmap height in pixels.
+    int height() const;
+    T & operator()(int x, int y);
+    const T & operator()(int x, int y) const;
+
+private:
+    T *content;
+    int w, h;
+
+};
+
+}

+ 26 - 0
core/Contour.cpp

@@ -0,0 +1,26 @@
+
+#include "Contour.h"
+
+namespace msdfgen {
+
+void Contour::addEdge(const EdgeHolder &edge) {
+    edges.push_back(edge);
+}
+
+#ifdef MSDFGEN_USE_CPP11
+void Contour::addEdge(EdgeHolder &&edge) {
+    edges.push_back((EdgeHolder &&) edge);
+}
+#endif
+
+EdgeHolder & Contour::addEdge() {
+    edges.resize(edges.size()+1);
+    return edges[edges.size()-1];
+}
+
+void Contour::bounds(double &l, double &b, double &r, double &t) const {
+    for (std::vector<EdgeHolder>::const_iterator edge = edges.begin(); edge != edges.end(); ++edge)
+        (*edge)->bounds(l, b, r, t);
+}
+
+}

+ 28 - 0
core/Contour.h

@@ -0,0 +1,28 @@
+
+#pragma once
+
+#include <vector>
+#include "EdgeHolder.h"
+
+namespace msdfgen {
+
+/// A single closed contour of a shape.
+class Contour {
+
+public:
+    /// The sequence of edges that make up the contour.
+    std::vector<EdgeHolder> edges;
+
+    /// Adds an edge to the contour.
+    void addEdge(const EdgeHolder &edge);
+#ifdef MSDFGEN_USE_CPP11
+    void addEdge(EdgeHolder &&edge);
+#endif
+    /// Creates a new edge in the contour and returns its reference.
+    EdgeHolder & addEdge();
+    /// Computes the bounding box of the contour.
+    void bounds(double &l, double &b, double &r, double &t) const;
+
+};
+
+}

+ 18 - 0
core/EdgeColor.h

@@ -0,0 +1,18 @@
+
+#pragma once
+
+namespace msdfgen {
+
+/// Edge color specifies which color channels an edge belongs to.
+enum EdgeColor {
+    BLACK = 0,
+    RED = 1,
+    GREEN = 2,
+    YELLOW = 3,
+    BLUE = 4,
+    MAGENTA = 5,
+    CYAN = 6,
+    WHITE = 7
+};
+
+}

+ 67 - 0
core/EdgeHolder.cpp

@@ -0,0 +1,67 @@
+
+#include "EdgeHolder.h"
+
+namespace msdfgen {
+
+EdgeHolder::EdgeHolder() : edgeSegment(NULL) { }
+
+EdgeHolder::EdgeHolder(EdgeSegment *segment) : edgeSegment(segment) { }
+
+EdgeHolder::EdgeHolder(Point2 p0, Point2 p1, EdgeColor edgeColor) : edgeSegment(new LinearSegment(p0, p1, edgeColor)) { }
+
+EdgeHolder::EdgeHolder(Point2 p0, Point2 p1, Point2 p2, EdgeColor edgeColor) : edgeSegment(new QuadraticSegment(p0, p1, p2, edgeColor)) { }
+
+EdgeHolder::EdgeHolder(Point2 p0, Point2 p1, Point2 p2, Point2 p3, EdgeColor edgeColor) : edgeSegment(new CubicSegment(p0, p1, p2, p3, edgeColor)) { }
+
+EdgeHolder::EdgeHolder(const EdgeHolder &orig) : edgeSegment(orig.edgeSegment ? orig.edgeSegment->clone() : NULL) { }
+
+#ifdef MSDFGEN_USE_CPP11
+EdgeHolder::EdgeHolder(EdgeHolder &&orig) : edgeSegment(orig.edgeSegment) {
+    orig.edgeSegment = NULL;
+}
+#endif
+
+EdgeHolder::~EdgeHolder() {
+    delete edgeSegment;
+}
+
+EdgeHolder & EdgeHolder::operator=(const EdgeHolder &orig) {
+    delete edgeSegment;
+    edgeSegment = orig.edgeSegment ? orig.edgeSegment->clone() : NULL;
+    return *this;
+}
+
+#ifdef MSDFGEN_USE_CPP11
+EdgeHolder & EdgeHolder::operator=(EdgeHolder &&orig) {
+    delete edgeSegment;
+    edgeSegment = orig.edgeSegment;
+    orig.edgeSegment = NULL;
+    return *this;
+}
+#endif
+
+EdgeSegment & EdgeHolder::operator*() {
+    return *edgeSegment;
+}
+
+const EdgeSegment & EdgeHolder::operator*() const {
+    return *edgeSegment;
+}
+
+EdgeSegment * EdgeHolder::operator->() {
+    return edgeSegment;
+}
+
+const EdgeSegment * EdgeHolder::operator->() const {
+    return edgeSegment;
+}
+
+EdgeHolder::operator EdgeSegment *() {
+    return edgeSegment;
+}
+
+EdgeHolder::operator const EdgeSegment *() const {
+    return edgeSegment;
+}
+
+}

+ 38 - 0
core/EdgeHolder.h

@@ -0,0 +1,38 @@
+
+#pragma once
+
+#include "edge-segments.h"
+
+namespace msdfgen {
+
+/// Container for a single edge of dynamic type.
+class EdgeHolder {
+
+public:
+    EdgeHolder();
+    EdgeHolder(EdgeSegment *segment);
+    EdgeHolder(Point2 p0, Point2 p1, EdgeColor edgeColor = WHITE);
+    EdgeHolder(Point2 p0, Point2 p1, Point2 p2, EdgeColor edgeColor = WHITE);
+    EdgeHolder(Point2 p0, Point2 p1, Point2 p2, Point2 p3, EdgeColor edgeColor = WHITE);
+    EdgeHolder(const EdgeHolder &orig);
+#ifdef MSDFGEN_USE_CPP11
+    EdgeHolder(EdgeHolder &&orig);
+#endif
+    ~EdgeHolder();
+    EdgeHolder & operator=(const EdgeHolder &orig);
+#ifdef MSDFGEN_USE_CPP11
+    EdgeHolder & operator=(EdgeHolder &&orig);
+#endif
+    EdgeSegment & operator*();
+    const EdgeSegment & operator*() const;
+    EdgeSegment * operator->();
+    const EdgeSegment * operator->() const;
+    operator EdgeSegment *();
+    operator const EdgeSegment *() const;
+
+private:
+    EdgeSegment *edgeSegment;
+
+};
+
+}

+ 56 - 0
core/Shape.cpp

@@ -0,0 +1,56 @@
+
+#include "Shape.h"
+
+namespace msdfgen {
+
+Shape::Shape() : inverseYAxis(false) { }
+
+void Shape::addContour(const Contour &contour) {
+    contours.push_back(contour);
+}
+
+#ifdef MSDFGEN_USE_CPP11
+void Shape::addContour(Contour &&contour) {
+    contours.push_back((Contour &&) contour);
+}
+#endif
+
+Contour & Shape::addContour() {
+    contours.resize(contours.size()+1);
+    return contours[contours.size()-1];
+}
+
+bool Shape::validate() const {
+    for (std::vector<Contour>::const_iterator contour = contours.begin(); contour != contours.end(); ++contour) {
+        if (!contour->edges.empty()) {
+            Point2 corner = (*(contour->edges.end()-1))->point(1);
+            for (std::vector<EdgeHolder>::const_iterator edge = contour->edges.begin(); edge != contour->edges.end(); ++edge) {
+                if (!*edge)
+                    return false;
+                if ((*edge)->point(0) != corner)
+                    return false;
+                corner = (*edge)->point(1);
+            }
+        }
+    }
+    return true;
+}
+
+void Shape::normalize() {
+    for (std::vector<Contour>::iterator contour = contours.begin(); contour != contours.end(); ++contour)
+        if (contour->edges.size() == 1) {
+            EdgeSegment *parts[3] = { };
+            contour->edges[0]->splitInThirds(parts[0], parts[1], parts[2]);
+            contour->edges.clear();
+            contour->edges.push_back(EdgeHolder(parts[0]));
+            contour->edges.push_back(EdgeHolder(parts[1]));
+            contour->edges.push_back(EdgeHolder(parts[2]));
+        }
+}
+
+void Shape::bounds(double &l, double &b, double &r, double &t) const {
+    for (std::vector<Contour>::const_iterator contour = contours.begin(); contour != contours.end(); ++contour)
+        contour->bounds(l, b, r, t);
+}
+
+}

+ 35 - 0
core/Shape.h

@@ -0,0 +1,35 @@
+
+#pragma once
+
+#include <vector>
+#include "Contour.h"
+
+namespace msdfgen {
+
+/// Vector shape representation.
+class Shape {
+
+public:
+    /// The list of contours the shape consists of.
+    std::vector<Contour> contours;
+    /// Specifies whether the shape uses bottom-to-top (false) or top-to-bottom (true) Y coordinates.
+    bool inverseYAxis;
+
+    Shape();
+    /// Adds a contour.
+    void addContour(const Contour &contour);
+#ifdef MSDFGEN_USE_CPP11
+    void addContour(Contour &&contour);
+#endif
+    /// Adds a blank contour and returns its reference.
+    Contour & addContour();
+    /// Normalizes the shape geometry for distance field generation.
+    void normalize();
+    /// Performs basic checks to determine if the object represents a valid shape.
+    bool validate() const;
+    /// Computes the shape's bounding box.
+    void bounds(double &l, double &b, double &r, double &t) const;
+
+};
+
+}

+ 30 - 0
core/SignedDistance.cpp

@@ -0,0 +1,30 @@
+
+#include "SignedDistance.h"
+
+#include <cmath>
+
+namespace msdfgen {
+
+const SignedDistance SignedDistance::INFINITE(-1e240, 1);
+
+SignedDistance::SignedDistance() : distance(-1e240), dot(1) { }
+
+SignedDistance::SignedDistance(double dist, double d) : distance(dist), dot(d) { }
+
+bool operator<(SignedDistance a, SignedDistance b) {
+    return fabs(a.distance) < fabs(b.distance) || (fabs(a.distance) == fabs(b.distance) && a.dot < b.dot);
+}
+
+bool operator>(SignedDistance a, SignedDistance b) {
+    return fabs(a.distance) > fabs(b.distance) || (fabs(a.distance) == fabs(b.distance) && a.dot > b.dot);
+}
+
+bool operator<=(SignedDistance a, SignedDistance b) {
+    return fabs(a.distance) < fabs(b.distance) || (fabs(a.distance) == fabs(b.distance) && a.dot <= b.dot);
+}
+
+bool operator>=(SignedDistance a, SignedDistance b) {
+    return fabs(a.distance) > fabs(b.distance) || (fabs(a.distance) == fabs(b.distance) && a.dot >= b.dot);
+}
+
+}

+ 25 - 0
core/SignedDistance.h

@@ -0,0 +1,25 @@
+
+#pragma once
+
+namespace msdfgen {
+
+/// Represents a signed distance and alignment, which together can be compared to uniquely determine the closest edge segment.
+class SignedDistance {
+
+public:
+    static const SignedDistance INFINITE;
+
+    double distance;
+    double dot;
+
+    SignedDistance();
+    SignedDistance(double dist, double d);
+
+    friend bool operator<(SignedDistance a, SignedDistance b);
+    friend bool operator>(SignedDistance a, SignedDistance b);
+    friend bool operator<=(SignedDistance a, SignedDistance b);
+    friend bool operator>=(SignedDistance a, SignedDistance b);
+
+};
+
+}

+ 146 - 0
core/Vector2.cpp

@@ -0,0 +1,146 @@
+
+#include "Vector2.h"
+
+namespace msdfgen {
+
+Vector2::Vector2(double val) : x(val), y(val) { }
+
+Vector2::Vector2(double x, double y) : x(x), y(y) { }
+
+void Vector2::reset() {
+    x = 0, y = 0;
+}
+
+void Vector2::set(double x, double y) {
+    Vector2::x = x, Vector2::y = y;
+}
+
+double Vector2::length() const {
+    return sqrt(x*x+y*y);
+}
+
+double Vector2::direction() const {
+    return atan2(y, x);
+}
+
+Vector2 Vector2::normalize(bool allowZero) const {
+    double len = length();
+    if (len == 0)
+        return Vector2(0, !allowZero);
+    return Vector2(x/len, y/len);
+}
+
+Vector2 Vector2::getOrthogonal(bool polarity) const {
+    return polarity ? Vector2(-y, x) : Vector2(y, -x);
+}
+
+Vector2 Vector2::getOrthonormal(bool polarity, bool allowZero) const {
+    double len = length();
+    if (len == 0)
+        return polarity ? Vector2(0, !allowZero) : Vector2(0, -!allowZero);
+    return polarity ? Vector2(-y/len, x/len) : Vector2(y/len, -x/len);
+}
+
+Vector2 Vector2::project(const Vector2 &vector, bool positive) const {
+    Vector2 n = normalize(true);
+    double t = dotProduct(vector, n);
+    if (positive && t <= 0)
+        return Vector2();
+    return t*n;
+}
+
+Vector2::operator const void*() const {
+    return x || y ? this : NULL;
+}
+
+bool Vector2::operator!() const {
+    return !x && !y;
+}
+
+bool Vector2::operator==(const Vector2 &other) const {
+    return x == other.x && y == other.y;
+}
+
+bool Vector2::operator!=(const Vector2 &other) const {
+    return x != other.x || y != other.y;
+}
+
+Vector2 Vector2::operator+() const {
+    return *this;
+}
+
+Vector2 Vector2::operator-() const {
+    return Vector2(-x, -y);
+}
+
+Vector2 Vector2::operator+(const Vector2 &other) const {
+    return Vector2(x+other.x, y+other.y);
+}
+
+Vector2 Vector2::operator-(const Vector2 &other) const {
+    return Vector2(x-other.x, y-other.y);
+}
+
+Vector2 Vector2::operator*(const Vector2 &other) const {
+    return Vector2(x*other.x, y*other.y);
+}
+
+Vector2 Vector2::operator/(const Vector2 &other) const {
+    return Vector2(x/other.x, y/other.y);
+}
+
+Vector2 Vector2::operator*(double value) const {
+    return Vector2(x*value, y*value);
+}
+
+Vector2 Vector2::operator/(double value) const {
+    return Vector2(x/value, y/value);
+}
+
+Vector2 & Vector2::operator+=(const Vector2 &other) {
+    x += other.x, y += other.y;
+    return *this;
+}
+
+Vector2 & Vector2::operator-=(const Vector2 &other) {
+    x -= other.x, y -= other.y;
+    return *this;
+}
+
+Vector2 & Vector2::operator*=(const Vector2 &other) {
+    x *= other.x, y *= other.y;
+    return *this;
+}
+
+Vector2 & Vector2::operator/=(const Vector2 &other) {
+    x /= other.x, y /= other.y;
+    return *this;
+}
+
+Vector2 & Vector2::operator*=(double value) {
+    x *= value, y *= value;
+    return *this;
+}
+
+Vector2 & Vector2::operator/=(double value) {
+    x /= value, y /= value;
+    return *this;
+}
+
+double dotProduct(const Vector2 &a, const Vector2 &b) {
+    return a.x*b.x+a.y*b.y;
+}
+
+double crossProduct(const Vector2 &a, const Vector2 &b) {
+    return a.x*b.y-a.y*b.x;
+}
+
+Vector2 operator*(double value, const Vector2 &vector) {
+    return Vector2(value*vector.x, value*vector.y);
+}
+
+Vector2 operator/(double value, const Vector2 &vector) {
+    return Vector2(value/vector.x, value/vector.y);
+}
+
+}

+ 66 - 0
core/Vector2.h

@@ -0,0 +1,66 @@
+
+#pragma once
+
+#include <cstdlib>
+#include <cmath>
+
+namespace msdfgen {
+
+/**
+* A 2-dimensional euclidean vector with double precision.
+* Implementation based on the Vector2 template from Artery Engine.
+* @author Viktor Chlumsky
+*/
+struct Vector2 {
+
+    double x, y;
+
+    Vector2(double val = 0);
+    Vector2(double x, double y);
+    /// Sets the vector to zero.
+    void reset();
+    /// Sets individual elements of the vector.
+    void set(double x, double y);
+    /// Returns the vector's length.
+    double length() const;
+    /// Returns the angle of the vector in radians (atan2).
+    double direction() const;
+    /// Returns the normalized vector - one that has the same direction but unit length.
+    Vector2 normalize(bool allowZero = false) const;
+    /// Returns a vector with the same length that is orthogonal to this one.
+    Vector2 getOrthogonal(bool polarity = true) const;
+    /// Returns a vector with unit length that is orthogonal to this one.
+    Vector2 getOrthonormal(bool polarity = true, bool allowZero = false) const;
+    /// Returns a vector projected along this one.
+    Vector2 project(const Vector2 &vector, bool positive = false) const;
+    operator const void *() const;
+    bool operator!() const;
+    bool operator==(const Vector2 &other) const;
+    bool operator!=(const Vector2 &other) const;
+    Vector2 operator+() const;
+    Vector2 operator-() const;
+    Vector2 operator+(const Vector2 &other) const;
+    Vector2 operator-(const Vector2 &other) const;
+    Vector2 operator*(const Vector2 &other) const;
+    Vector2 operator/(const Vector2 &other) const;
+    Vector2 operator*(double value) const;
+    Vector2 operator/(double value) const;
+    Vector2 & operator+=(const Vector2 &other);
+    Vector2 & operator-=(const Vector2 &other);
+    Vector2 & operator*=(const Vector2 &other);
+    Vector2 & operator/=(const Vector2 &other);
+    Vector2 & operator*=(double value);
+    Vector2 & operator/=(double value);
+    /// Dot product of two vectors.
+    friend double dotProduct(const Vector2 &a, const Vector2 &b);
+    /// A special version of the cross product for 2D vectors (returns scalar value).
+    friend double crossProduct(const Vector2 &a, const Vector2 &b);
+    friend Vector2 operator*(double value, const Vector2 &vector);
+    friend Vector2 operator/(double value, const Vector2 &vector);
+
+};
+
+/// A vector may also represent a point, which shall be differentiated semantically using the alias Point2.
+typedef Vector2 Point2;
+
+}

+ 57 - 0
core/arithmetics.hpp

@@ -0,0 +1,57 @@
+
+#pragma once
+
+#include <cstdlib>
+#include <cmath>
+
+namespace msdfgen {
+
+/// Returns the smaller of the arguments.
+template <typename T>
+inline T min(T a, T b) {
+    return b < a ? b : a;
+}
+
+/// Returns the larger of the arguments.
+template <typename T>
+inline T max(T a, T b) {
+    return a < b ? b : a;
+}
+
+/// Returns the middle out of three values
+template <typename T>
+inline T median(T a, T b, T c) {
+    return max(min(a, b), min(max(a, b), c));
+}
+
+/// Returns the weighted average of a and b.
+template <typename T, typename S>
+inline T mix(T a, T b, S weight) {
+    return T((S(1)-weight)*a+weight*b);
+}
+
+/// Clamps the number to the interval from 0 to 1.
+template <typename T>
+inline T clamp(T n) {
+    return n >= T(0) && n <= T(1) ? n : T(n > T(0));
+}
+
+/// Clamps the number to the interval from 0 to b.
+template <typename T>
+inline T clamp(T n, T b) {
+    return n >= T(0) && n <= b ? n : T(n > T(0))*b;
+}
+
+/// Clamps the number to the interval from a to b.
+template <typename T>
+inline T clamp(T n, T a, T b) {
+    return n >= a && n <= b ? n : n < a ? a : b;
+}
+
+/// Returns 1 for non-negative values and -1 for negative values.
+template <typename T>
+inline int nonZeroSign(T n) {
+    return 2*(n > T(0))-1;
+}
+
+}

+ 75 - 0
core/edge-coloring.cpp

@@ -0,0 +1,75 @@
+
+#include "edge-coloring.h"
+
+namespace msdfgen {
+
+static bool isCorner(const Vector2 &aDir, const Vector2 &bDir, double crossThreshold) {
+    return dotProduct(aDir, bDir) <= 0 || fabs(crossProduct(aDir, bDir)) > crossThreshold;
+}
+
+void edgeColoringSimple(Shape &shape, double angleThreshold) {
+    double crossThreshold = sin(angleThreshold);
+    std::vector<int> corners;
+    for (std::vector<Contour>::iterator contour = shape.contours.begin(); contour != shape.contours.end(); ++contour) {
+        // Identify corners
+        corners.clear();
+        if (!contour->edges.empty()) {
+            Vector2 prevDirection = (*(contour->edges.end()-1))->direction(1);
+            int index = 0;
+            for (std::vector<EdgeHolder>::const_iterator edge = contour->edges.begin(); edge != contour->edges.end(); ++edge, ++index) {
+                if (isCorner(prevDirection.normalize(), (*edge)->direction(0).normalize(), crossThreshold))
+                    corners.push_back(index);
+                prevDirection = (*edge)->direction(1);
+            }
+        }
+
+        // Smooth contour
+        if (corners.empty())
+            for (std::vector<EdgeHolder>::iterator edge = contour->edges.begin(); edge != contour->edges.end(); ++edge)
+                (*edge)->color = WHITE;
+        // "Teardrop" case
+        else if (corners.size() == 1) {
+            const EdgeColor colors[] = { MAGENTA, WHITE, YELLOW };
+            int corner = corners[0];
+            if (contour->edges.size() >= 3) {
+                int m = contour->edges.size();
+                for (int i = 0; i < m; ++i)
+                    contour->edges[(corner+i)%m]->color = (colors+1)[int(3+2.875*i/(m-1)-1.4375+.5)-3];
+            } else if (contour->edges.size() >= 1) {
+                // Less than three edge segments for three colors => edges must be split
+                EdgeSegment *parts[7] = { };
+                contour->edges[0]->splitInThirds(parts[0+3*corner], parts[1+3*corner], parts[2+3*corner]);
+                if (contour->edges.size() >= 2) {
+                    contour->edges[1]->splitInThirds(parts[3-3*corner], parts[4-3*corner], parts[5-3*corner]);
+                    parts[0]->color = parts[1]->color = colors[0];
+                    parts[2]->color = parts[3]->color = colors[1];
+                    parts[4]->color = parts[5]->color = colors[2];
+                } else {
+                    parts[0]->color = colors[0];
+                    parts[1]->color = colors[1];
+                    parts[2]->color = colors[2];
+                }
+                contour->edges.clear();
+                for (int i = 0; parts[i]; ++i)
+                    contour->edges.push_back(EdgeHolder(parts[i]));
+            }
+        }
+        // Multiple corners
+        else {
+            int cornerCount = corners.size();
+            // CMYCMYCMYCMY / YMYCMYC if corner count % 3 == 1
+            EdgeColor colors[] = { cornerCount%3 == 1 ? YELLOW : CYAN, CYAN, MAGENTA, YELLOW };
+            int spline = 0;
+            int start = corners[0];
+            int m = contour->edges.size();
+            for (int i = 0; i < m; ++i) {
+                int index = (start+i)%m;
+                if (cornerCount > spline+1 && corners[spline+1] == index)
+                    ++spline;
+                contour->edges[index]->color = (colors+1)[spline%3-!spline];
+            }
+        }
+    }
+}
+
+}

+ 15 - 0
core/edge-coloring.h

@@ -0,0 +1,15 @@
+
+#pragma once
+
+#include "Shape.h"
+
+namespace msdfgen {
+
+/** Assigns colors to edges of the shape in accordance to the multi-channel distance field technique.
+ *  May split some edges if necessary.
+ *  angleThreshold specifies the maximum angle (in radians) to be considered a corner, for example 3 (~172 degrees).
+ *  Values below 1/2 PI will be treated as the external angle.
+ */
+void edgeColoringSimple(Shape &shape, double angleThreshold);
+
+}

+ 334 - 0
core/edge-segments.cpp

@@ -0,0 +1,334 @@
+
+#include "edge-segments.h"
+
+#include "arithmetics.hpp"
+#include "equation-solver.h"
+
+namespace msdfgen {
+
+void EdgeSegment::distanceToPseudoDistance(SignedDistance &distance, Point2 origin, double param) const {
+    if (param < 0) {
+        Vector2 dir = direction(0).normalize();
+        Vector2 aq = origin-point(0);
+        double ts = dotProduct(aq, dir);
+        if (ts < 0) {
+            double pseudoDistance = crossProduct(aq, dir);
+            if (fabs(pseudoDistance) <= fabs(distance.distance)) {
+                distance.distance = pseudoDistance;
+                distance.dot = 0;
+            }
+        }
+    } else if (param > 1) {
+        Vector2 dir = direction(1).normalize();
+        Vector2 bq = origin-point(1);
+        double ts = dotProduct(bq, dir);
+        if (ts > 0) {
+            double pseudoDistance = crossProduct(bq, dir);
+            if (fabs(pseudoDistance) <= fabs(distance.distance)) {
+                distance.distance = pseudoDistance;
+                distance.dot = 0;
+            }
+        }
+    }
+}
+
+LinearSegment::LinearSegment(Point2 p0, Point2 p1, EdgeColor edgeColor) : EdgeSegment(edgeColor) {
+    p[0] = p0;
+    p[1] = p1;
+}
+
+QuadraticSegment::QuadraticSegment(Point2 p0, Point2 p1, Point2 p2, EdgeColor edgeColor) : EdgeSegment(edgeColor) {
+    p[0] = p0;
+    p[1] = p1;
+    p[2] = p2;
+}
+
+CubicSegment::CubicSegment(Point2 p0, Point2 p1, Point2 p2, Point2 p3, EdgeColor edgeColor) : EdgeSegment(edgeColor) {
+    p[0] = p0;
+    p[1] = p1;
+    p[2] = p2;
+    p[3] = p3;
+}
+
+LinearSegment * LinearSegment::clone() const {
+    return new LinearSegment(p[0], p[1], color);
+}
+
+QuadraticSegment * QuadraticSegment::clone() const {
+    return new QuadraticSegment(p[0], p[1], p[2], color);
+}
+
+CubicSegment * CubicSegment::clone() const {
+    return new CubicSegment(p[0], p[1], p[2], p[3], color);
+}
+
+Point2 LinearSegment::point(double param) const {
+    return mix(p[0], p[1], param);
+}
+
+Point2 QuadraticSegment::point(double param) const {
+    return mix(mix(p[0], p[1], param), mix(p[1], p[2], param), param);
+}
+
+Point2 CubicSegment::point(double param) const {
+    Vector2 p12 = mix(p[1], p[2], param);
+    return mix(mix(mix(p[0], p[1], param), p12, param), mix(p12, mix(p[2], p[3], param), param), param);
+}
+
+Vector2 LinearSegment::direction(double param) const {
+    return p[1]-p[0];
+}
+
+Vector2 QuadraticSegment::direction(double param) const {
+    return mix(p[1]-p[0], p[2]-p[1], param);
+}
+
+Vector2 CubicSegment::direction(double param) const {
+    return mix(mix(p[1]-p[0], p[2]-p[1], param), mix(p[2]-p[1], p[3]-p[2], param), param);
+}
+
+SignedDistance LinearSegment::signedDistance(Point2 origin, double &param) const {
+    Vector2 aq = origin-p[0];
+    Vector2 ab = p[1]-p[0];
+    param = dotProduct(aq, ab)/dotProduct(ab, ab);
+    Vector2 eq = p[param > .5]-origin;
+    double endpointDistance = eq.length();
+    if (param > 0 && param < 1) {
+        double orthoDistance = dotProduct(ab.getOrthonormal(false), aq);
+        if (fabs(orthoDistance) < endpointDistance)
+            return SignedDistance(orthoDistance, 0);
+    }
+    return SignedDistance(nonZeroSign(crossProduct(aq, ab))*endpointDistance, fabs(dotProduct(ab.normalize(), eq.normalize())));
+}
+
+SignedDistance QuadraticSegment::signedDistance(Point2 origin, double &param) const {
+    Vector2 qa = p[0]-origin;
+    Vector2 ab = p[1]-p[0];
+    Vector2 br = p[0]+p[2]-p[1]-p[1];
+    double a = dotProduct(br, br);
+    double b = 3*dotProduct(ab, br);
+    double c = 2*dotProduct(ab, ab)+dotProduct(qa, br);
+    double d = dotProduct(qa, ab);
+    double t[3];
+    int solutions = solveCubic(t, a, b, c, d);
+
+    double minDistance = nonZeroSign(crossProduct(ab, qa))*qa.length(); // distance from A
+    param = -dotProduct(qa, ab)/dotProduct(ab, ab);
+    {
+        double distance = nonZeroSign(crossProduct(p[2]-p[1], p[2]-origin))*(p[2]-origin).length(); // distance from B
+        if (fabs(distance) < fabs(minDistance)) {
+            minDistance = distance;
+            param = dotProduct(origin-p[1], p[2]-p[1])/dotProduct(p[2]-p[1], p[2]-p[1]);
+        }
+    }
+    for (int i = 0; i < solutions; ++i) {
+        if (t[i] > 0 && t[i] < 1) {
+            Point2 endpoint = p[0]+2*t[i]*ab+t[i]*t[i]*br;
+            double distance = nonZeroSign(crossProduct(p[2]-p[0], endpoint-origin))*(endpoint-origin).length();
+            if (fabs(distance) <= fabs(minDistance)) {
+                minDistance = distance;
+                param = t[i];
+            }
+        }
+    }
+
+    if (param >= 0 && param <= 1)
+        return SignedDistance(minDistance, 0);
+    if (param < .5)
+        return SignedDistance(minDistance, fabs(dotProduct(ab.normalize(), qa.normalize())));
+    else
+        return SignedDistance(minDistance, fabs(dotProduct((p[2]-p[1]).normalize(), (p[2]-origin).normalize())));
+}
+
+SignedDistance CubicSegment::signedDistance(Point2 origin, double &param) const {
+    Vector2 qa = p[0]-origin;
+    Vector2 ab = p[1]-p[0];
+    Vector2 br = p[2]-p[1]-ab;
+    Vector2 as = (p[3]-p[2])-(p[2]-p[1])-br;
+
+    double minDistance = nonZeroSign(crossProduct(ab, qa))*qa.length(); // distance from A
+    param = -dotProduct(qa, ab)/dotProduct(ab, ab);
+    {
+        double distance = nonZeroSign(crossProduct(p[3]-p[2], p[3]-origin))*(p[3]-origin).length(); // distance from B
+        if (fabs(distance) < fabs(minDistance)) {
+            minDistance = distance;
+            param = dotProduct(origin-p[2], p[3]-p[2])/dotProduct(p[3]-p[2], p[3]-p[2]);
+        }
+    }
+    // Iterative minimum distance search
+    for (int i = 0; i <= MSDFGEN_CUBIC_SEARCH_STARTS; ++i) {
+        double t = (double) i/MSDFGEN_CUBIC_SEARCH_STARTS;
+        for (int step = 0;; ++step) {
+            Vector2 qpt = point(t)-origin;
+            double distance = nonZeroSign(crossProduct(direction(t), qpt))*qpt.length();
+            if (fabs(distance) < fabs(minDistance)) {
+                minDistance = distance;
+                param = t;
+            }
+            if (step == MSDFGEN_CUBIC_SEARCH_STEPS)
+                break;
+            // Improve t
+            Vector2 d1 = 3*as*t*t+6*br*t+3*ab;
+            Vector2 d2 = 6*as*t+6*br;
+            t -= dotProduct(qpt, d1)/(dotProduct(d1, d1)+dotProduct(qpt, d2));
+            if (t < 0 || t > 1)
+                break;
+        }
+    }
+
+    if (param >= 0 && param <= 1)
+        return SignedDistance(minDistance, 0);
+    if (param < .5)
+        return SignedDistance(minDistance, fabs(dotProduct(ab.normalize(), qa.normalize())));
+    else
+        return SignedDistance(minDistance, fabs(dotProduct((p[3]-p[2]).normalize(), (p[3]-origin).normalize())));
+}
+
+// Original method by solving a fifth order polynomial
+/*SignedDistance CubicSegment::signedDistance(Point2 origin, double &param) const {
+    Vector2 qa = p[0]-origin;
+    Vector2 ab = p[1]-p[0];
+    Vector2 br = p[2]-p[1]-ab;
+    Vector2 as = (p[3]-p[2])-(p[2]-p[1])-br;
+    double a = dotProduct(as, as);
+    double b = 5*dotProduct(br, as);
+    double c = 4*dotProduct(ab, as)+6*dotProduct(br, br);
+    double d = 9*dotProduct(ab, br)+dotProduct(qa, as);
+    double e = 3*dotProduct(ab, ab)+2*dotProduct(qa, br);
+    double f = dotProduct(qa, ab);
+    double t[5];
+    int solutions = solveQuintic(t, a, b, c, d, e, f);
+
+    double minDistance = nonZeroSign(crossProduct(ab, qa))*qa.length(); // distance from A
+    param = -dotProduct(qa, ab)/dotProduct(ab, ab);
+    {
+        double distance = nonZeroSign(crossProduct(p[3]-p[2], p[3]-origin))*(p[3]-origin).length(); // distance from B
+        if (fabs(distance) < fabs(minDistance)) {
+            minDistance = distance;
+            param = dotProduct(origin-p[2], p[3]-p[2])/dotProduct(p[3]-p[2], p[3]-p[2]);
+        }
+    }
+    for (int i = 0; i < solutions; ++i) {
+        if (t[i] > 0 && t[i] < 1) {
+            Point2 endpoint = p[0]+3*t[i]*ab+3*t[i]*t[i]*br+t[i]*t[i]*t[i]*as;
+            Vector2 dirVec = t[i]*t[i]*as+2*t[i]*br+ab;
+            double distance = nonZeroSign(crossProduct(dirVec, endpoint-origin))*(endpoint-origin).length();
+            if (fabs(distance) <= fabs(minDistance)) {
+                minDistance = distance;
+                param = t[i];
+            }
+        }
+    }
+
+    if (param >= 0 && param <= 1)
+        return SignedDistance(minDistance, 0);
+    if (param < .5)
+        return SignedDistance(minDistance, fabs(dotProduct(ab.normalize(), qa.normalize())));
+    else
+        return SignedDistance(minDistance, fabs(dotProduct((p[3]-p[2]).normalize(), (p[3]-origin).normalize())));
+}*/
+
+static void pointBounds(Point2 p, double &l, double &b, double &r, double &t) {
+    if (p.x < l) l = p.x;
+    if (p.y < b) b = p.y;
+    if (p.x > r) r = p.x;
+    if (p.y > t) t = p.y;
+}
+
+void LinearSegment::bounds(double &l, double &b, double &r, double &t) const {
+    pointBounds(p[0], l, b, r, t);
+    pointBounds(p[1], l, b, r, t);
+}
+
+void QuadraticSegment::bounds(double &l, double &b, double &r, double &t) const {
+    pointBounds(p[0], l, b, r, t);
+    pointBounds(p[2], l, b, r, t);
+    Vector2 bot = (p[1]-p[0])-(p[2]-p[1]);
+    if (bot.x) {
+        double param = (p[1].x-p[0].x)/bot.x;
+        if (param > 0 && param < 1)
+            pointBounds(point(param), l, b, r, t);
+    }
+    if (bot.y) {
+        double param = (p[1].y-p[0].y)/bot.y;
+        if (param > 0 && param < 1)
+            pointBounds(point(param), l, b, r, t);
+    }
+}
+
+void CubicSegment::bounds(double &l, double &b, double &r, double &t) const {
+    pointBounds(p[0], l, b, r, t);
+    pointBounds(p[3], l, b, r, t);
+    Vector2 a0 = p[1]-p[0];
+    Vector2 a1 = 2*(p[2]-p[1]-a0);
+    Vector2 a2 = p[3]-3*p[2]+3*p[1]-p[0];
+    double params[2];
+    int solutions;
+    solutions = solveQuadratic(params, a2.x, a1.x, a0.x);
+    for (int i = 0; i < solutions; ++i)
+        if (params[i] > 0 && params[i] < 1)
+            pointBounds(point(params[i]), l, b, r, t);
+    solutions = solveQuadratic(params, a2.y, a1.y, a0.y);
+    for (int i = 0; i < solutions; ++i)
+        if (params[i] > 0 && params[i] < 1)
+            pointBounds(point(params[i]), l, b, r, t);
+}
+
+void LinearSegment::moveStartPoint(Point2 to) {
+    p[0] = to;
+}
+
+void QuadraticSegment::moveStartPoint(Point2 to) {
+    Vector2 origSDir = p[0]-p[1];
+    Point2 origP1 = p[1];
+    p[1] += crossProduct(p[0]-p[1], to-p[0])/crossProduct(p[0]-p[1], p[2]-p[1])*(p[2]-p[1]);
+    p[0] = to;
+    if (dotProduct(origSDir, p[0]-p[1]) < 0)
+        p[1] = origP1;
+}
+
+void CubicSegment::moveStartPoint(Point2 to) {
+    p[1] += to-p[0];
+    p[0] = to;
+}
+
+void LinearSegment::moveEndPoint(Point2 to) {
+    p[1] = to;
+}
+
+void QuadraticSegment::moveEndPoint(Point2 to) {
+    Vector2 origEDir = p[2]-p[1];
+    Point2 origP1 = p[1];
+    p[1] += crossProduct(p[2]-p[1], to-p[2])/crossProduct(p[2]-p[1], p[0]-p[1])*(p[0]-p[1]);
+    p[2] = to;
+    if (dotProduct(origEDir, p[2]-p[1]) < 0)
+        p[1] = origP1;
+}
+
+void CubicSegment::moveEndPoint(Point2 to) {
+    p[2] += to-p[3];
+    p[3] = to;
+}
+
+void LinearSegment::splitInThirds(EdgeSegment *&part1, EdgeSegment *&part2, EdgeSegment *&part3) const {
+    part1 = new LinearSegment(p[0], point(1/3.), color);
+    part2 = new LinearSegment(point(1/3.), point(2/3.), color);
+    part3 = new LinearSegment(point(2/3.), p[1], color);
+}
+
+void QuadraticSegment::splitInThirds(EdgeSegment *&part1, EdgeSegment *&part2, EdgeSegment *&part3) const {
+    part1 = new QuadraticSegment(p[0], mix(p[0], p[1], 1/3.), point(1/3.), color);
+    part2 = new QuadraticSegment(point(1/3.), mix(mix(p[0], p[1], 5/9.), mix(p[1], p[2], 4/9.), .5), point(2/3.), color);
+    part3 = new QuadraticSegment(point(2/3.), mix(p[1], p[2], 2/3.), p[2], color);
+}
+
+void CubicSegment::splitInThirds(EdgeSegment *&part1, EdgeSegment *&part2, EdgeSegment *&part3) const {
+    part1 = new CubicSegment(p[0], mix(p[0], p[1], 1/3.), mix(mix(p[0], p[1], 1/3.), mix(p[1], p[2], 1/3.), 1/3.), point(1/3.), color);
+    part2 = new CubicSegment(point(1/3.),
+        mix(mix(mix(p[0], p[1], 1/3.), mix(p[1], p[2], 1/3.), 1/3.), mix(mix(p[1], p[2], 1/3.), mix(p[2], p[3], 1/3.), 1/3.), 2/3.),
+        mix(mix(mix(p[0], p[1], 2/3.), mix(p[1], p[2], 2/3.), 2/3.), mix(mix(p[1], p[2], 2/3.), mix(p[2], p[3], 2/3.), 2/3.), 1/3.),
+        point(2/3.), color);
+    part3 = new CubicSegment(point(2/3.), mix(mix(p[1], p[2], 2/3.), mix(p[2], p[3], 2/3.), 2/3.), mix(p[2], p[3], 2/3.), p[3], color);
+}
+
+}

+ 101 - 0
core/edge-segments.h

@@ -0,0 +1,101 @@
+
+#pragma once
+
+#include "Vector2.h"
+#include "SignedDistance.h"
+#include "EdgeColor.h"
+
+namespace msdfgen {
+
+// Parameters for iterative search of closest point on a cubic Bezier curve. Increase for higher precision.
+#define MSDFGEN_CUBIC_SEARCH_STARTS 4
+#define MSDFGEN_CUBIC_SEARCH_STEPS 4
+
+/// An abstract edge segment.
+class EdgeSegment {
+
+public:
+    EdgeColor color;
+
+    EdgeSegment(EdgeColor edgeColor = WHITE) : color(edgeColor) { }
+    virtual ~EdgeSegment() { }
+    /// Creates a copy of the edge segment.
+    virtual EdgeSegment * clone() const = 0;
+    /// Returns the point on the edge specified by the parameter (between 0 and 1).
+    virtual Point2 point(double param) const = 0;
+    /// Returns the direction the edge has at the point specified by the parameter.
+    virtual Vector2 direction(double param) const = 0;
+    /// Returns the minimum signed distance between origin and the edge.
+    virtual SignedDistance signedDistance(Point2 origin, double &param) const = 0;
+    /// Converts a previously retrieved signed distance from origin to pseudo-distance.
+    virtual void distanceToPseudoDistance(SignedDistance &distance, Point2 origin, double param) const;
+    /// Adjusts the bounding box to fit the edge segment.
+    virtual void bounds(double &l, double &b, double &r, double &t) const = 0;
+
+    /// Moves the start point of the edge segment.
+    virtual void moveStartPoint(Point2 to) = 0;
+    /// Moves the end point of the edge segment.
+    virtual void moveEndPoint(Point2 to) = 0;
+    /// Splits the edge segments into thirds which together represent the original edge.
+    virtual void splitInThirds(EdgeSegment *&part1, EdgeSegment *&part2, EdgeSegment *&part3) const = 0;
+
+};
+
+/// A line segment.
+class LinearSegment : public EdgeSegment {
+
+public:
+    Point2 p[2];
+
+    LinearSegment(Point2 p0, Point2 p1, EdgeColor edgeColor = WHITE);
+    LinearSegment * clone() const;
+    Point2 point(double param) const;
+    Vector2 direction(double param) const;
+    SignedDistance signedDistance(Point2 origin, double &param) const;
+    void bounds(double &l, double &b, double &r, double &t) const;
+
+    void moveStartPoint(Point2 to);
+    void moveEndPoint(Point2 to);
+    void splitInThirds(EdgeSegment *&part1, EdgeSegment *&part2, EdgeSegment *&part3) const;
+
+};
+
+/// A quadratic Bezier curve.
+class QuadraticSegment : public EdgeSegment {
+
+public:
+    Point2 p[3];
+
+    QuadraticSegment(Point2 p0, Point2 p1, Point2 p2, EdgeColor edgeColor = WHITE);
+    QuadraticSegment * clone() const;
+    Point2 point(double param) const;
+    Vector2 direction(double param) const;
+    SignedDistance signedDistance(Point2 origin, double &param) const;
+    void bounds(double &l, double &b, double &r, double &t) const;
+
+    void moveStartPoint(Point2 to);
+    void moveEndPoint(Point2 to);
+    void splitInThirds(EdgeSegment *&part1, EdgeSegment *&part2, EdgeSegment *&part3) const;
+
+};
+
+/// A cubic Bezier curve.
+class CubicSegment : public EdgeSegment {
+
+public:
+    Point2 p[4];
+
+    CubicSegment(Point2 p0, Point2 p1, Point2 p2, Point2 p3, EdgeColor edgeColor = WHITE);
+    CubicSegment * clone() const;
+    Point2 point(double param) const;
+    Vector2 direction(double param) const;
+    SignedDistance signedDistance(Point2 origin, double &param) const;
+    void bounds(double &l, double &b, double &r, double &t) const;
+
+    void moveStartPoint(Point2 to);
+    void moveEndPoint(Point2 to);
+    void splitInThirds(EdgeSegment *&part1, EdgeSegment *&part2, EdgeSegment *&part3) const;
+
+};
+
+}

+ 69 - 0
core/equation-solver.cpp

@@ -0,0 +1,69 @@
+
+#include "equation-solver.h"
+
+#define _USE_MATH_DEFINES
+#include <cmath>
+
+namespace msdfgen {
+
+int solveQuadratic(double x[2], double a, double b, double c) {
+    if (fabs(a) < 1e-14) {
+        if (fabs(b) < 1e-14) {
+            if (c == 0)
+                return -1;
+            return 0;
+        }
+        x[0] = -c/b;
+        return 1;
+    }
+    double dscr = b*b-4*a*c;
+    if (dscr > 0) {
+        dscr = sqrt(dscr);
+        x[0] = (-b+dscr)/(2*a);
+        x[1] = (-b-dscr)/(2*a);
+        return 2;
+    } else if (dscr == 0) {
+        x[0] = -b/(2*a);
+        return 1;
+    } else
+        return 0;
+}
+
+int solveCubicNormed(double *x, double a, double b, double c) {
+    double a2 = a*a;
+    double q  = (a2 - 3*b)/9; 
+    double r  = (a*(2*a2-9*b) + 27*c)/54;
+    double r2 = r*r;
+    double q3 = q*q*q;
+    double A, B;
+    if (r2 < q3) {
+        double t = r/sqrt(q3);
+        if (t < -1) t = -1;
+        if (t > 1) t = 1;
+        t = acos(t);
+        a /= 3; q = -2*sqrt(q);
+        x[0] = q*cos(t/3)-a;
+        x[1] = q*cos((t+2*M_PI)/3)-a;
+        x[2] = q*cos((t-2*M_PI)/3)-a;
+        return 3;
+    } else {
+        A = -pow(fabs(r)+sqrt(r2-q3), 1/3.); 
+        if (r < 0) A = -A;
+        B = A == 0 ? 0 : q/A;
+        a /= 3;
+        x[0] = (A+B)-a;
+        x[1] = -0.5*(A+B)-a;
+        x[2] = 0.5*sqrt(3.)*(A-B);
+        if (fabs(x[2]) < 1e-14)
+            return 2;
+        return 1;
+    }
+}
+
+int solveCubic(double x[3], double a, double b, double c, double d) {
+    if (fabs(a) < 1e-14)
+        return solveQuadratic(x, b, c, d);
+    return solveCubicNormed(x, b/a, c/a, d/a);
+}
+
+}

+ 15 - 0
core/equation-solver.h

@@ -0,0 +1,15 @@
+
+#pragma once
+
+namespace msdfgen {
+
+// ax^2 + bx + c = 0
+int solveQuadratic(double x[2], double a, double b, double c);
+
+// ax^3 + bx^2 + cx + d = 0
+int solveCubic(double x[3], double a, double b, double c, double d);
+
+// ax^5 + bx^4 + cx^3 + dx^2 + ex + f = 0
+//int solveQuintic(double x[5], double a, double b, double c, double d, double e, double f);
+
+}

+ 166 - 0
core/msdfgen.cpp

@@ -0,0 +1,166 @@
+
+#include "../msdfgen.h"
+
+#include "arithmetics.hpp"
+
+namespace msdfgen {
+
+void generateSDF(Bitmap<float> &output, const Shape &shape, double range, const Vector2 &scale, const Vector2 &translate) {
+    int w = output.width(), h = output.height();
+#ifdef MSDFGEN_USE_OPENMP
+    #pragma omp parallel for
+#endif
+    for (int y = 0; y < h; ++y) {
+        int row = shape.inverseYAxis ? h-y-1 : y;
+        for (int x = 0; x < w; ++x) {
+            double dummy;
+            Point2 p = Vector2(x+.5, y+.5)/scale-translate;
+            SignedDistance minDistance;
+            for (std::vector<Contour>::const_iterator contour = shape.contours.begin(); contour != shape.contours.end(); ++contour)
+                for (std::vector<EdgeHolder>::const_iterator edge = contour->edges.begin(); edge != contour->edges.end(); ++edge) {
+                    SignedDistance distance = (*edge)->signedDistance(p, dummy);
+                    if (distance < minDistance)
+                        minDistance = distance;
+                }
+            output(x, row) = float(minDistance.distance/range+.5);
+        }
+    }
+}
+
+void generatePseudoSDF(Bitmap<float> &output, const Shape &shape, double range, const Vector2 &scale, const Vector2 &translate) {
+    int w = output.width(), h = output.height();
+#ifdef MSDFGEN_USE_OPENMP
+    #pragma omp parallel for
+#endif
+    for (int y = 0; y < h; ++y) {
+        int row = shape.inverseYAxis ? h-y-1 : y;
+        for (int x = 0; x < w; ++x) {
+            Point2 p = Vector2(x+.5, y+.5)/scale-translate;
+            SignedDistance minDistance;
+            const EdgeHolder *nearEdge = NULL;
+            double nearParam = 0;
+            for (std::vector<Contour>::const_iterator contour = shape.contours.begin(); contour != shape.contours.end(); ++contour)
+                for (std::vector<EdgeHolder>::const_iterator edge = contour->edges.begin(); edge != contour->edges.end(); ++edge) {
+                    double param;
+                    SignedDistance distance = (*edge)->signedDistance(p, param);
+                    if (distance < minDistance) {
+                        minDistance = distance;
+                        nearEdge = &*edge;
+                        nearParam = param;
+                    }
+                }
+            if (nearEdge)
+                (*nearEdge)->distanceToPseudoDistance(minDistance, p, nearParam);
+            output(x, row) = float(minDistance.distance/range+.5);
+        }
+    }
+}
+
+static inline bool pixelClash(const FloatRGB &a, const FloatRGB &b, double threshold) {
+    // Only consider pair where both are on the inside or both are on the outside
+    bool aIn = (a.r > .5f)+(a.g > .5f)+(a.b > .5f) >= 2;
+    bool bIn = (b.r > .5f)+(b.g > .5f)+(b.b > .5f) >= 2;
+    if (aIn != bIn) return false;
+    // If the change is 0 <-> 1 or 2 <-> 3 channels and not 1 <-> 1 or 2 <-> 2, it is not a clash
+    if ((a.r > .5f && a.g > .5f && a.b > .5f) || (a.r < .5f && a.g < .5f && a.b < .5f)
+        || (b.r > .5f && b.g > .5f && b.b > .5f) || (b.r < .5f && b.g < .5f && b.b < .5f))
+        return false;
+    // Find which color is which: _a, _b = the changing channels, _c = the remaining one
+    float aa, ab, ba, bb, ac, bc;
+    if ((a.r > .5f) != (b.r > .5f) && (a.r < .5f) != (b.r < .5f)) {
+        aa = a.r, ba = b.r;
+        if ((a.g > .5f) != (b.g > .5f) && (a.g < .5f) != (b.g < .5f)) {
+            ab = a.g, bb = b.g;
+            ac = a.b, bc = b.b;
+        } else if ((a.b > .5f) != (b.b > .5f) && (a.b < .5f) != (b.b < .5f)) {
+            ab = a.b, bb = b.b;
+            ac = a.g, bc = b.g;
+        } else
+            return false; // this should never happen
+    } else if ((a.g > .5f) != (b.g > .5f) && (a.g < .5f) != (b.g < .5f)
+        && (a.b > .5f) != (b.b > .5f) && (a.b < .5f) != (b.b < .5f)) {
+        aa = a.g, ba = b.g;
+        ab = a.b, bb = b.b;
+        ac = a.r, bc = b.r;
+    } else
+        return false;
+    // Find if the channels are in fact discontinuous
+    return (fabsf(aa-ba) >= threshold)
+        && (fabsf(ab-bb) >= threshold)
+        && fabsf(ac-.5f) >= fabsf(bc-.5f); // Out of the pair, only flag the pixel farther from a shape edge
+}
+
+void msdfErrorCorrection(Bitmap<FloatRGB> &output, const Vector2 &threshold) {
+    std::vector<std::pair<int, int> > clashes;
+    int w = output.width(), h = output.height();
+    for (int y = 0; y < h; ++y)
+        for (int x = 0; x < w; ++x) {
+            if ((x > 0 && pixelClash(output(x, y), output(x-1, y), threshold.x))
+                || (x < w-1 && pixelClash(output(x, y), output(x+1, y), threshold.x))
+                || (y > 0 && pixelClash(output(x, y), output(x, y-1), threshold.y))
+                || (y < h-1 && pixelClash(output(x, y), output(x, y+1), threshold.y)))
+                clashes.push_back(std::make_pair(x, y));
+        }
+    for (std::vector<std::pair<int, int> >::const_iterator clash = clashes.begin(); clash != clashes.end(); ++clash) {
+        FloatRGB &pixel = output(clash->first, clash->second);
+        float med = median(pixel.r, pixel.g, pixel.b);
+        pixel.r = med, pixel.g = med, pixel.b = med;
+    }
+}
+
+void generateMSDF(Bitmap<FloatRGB> &output, const Shape &shape, double range, const Vector2 &scale, const Vector2 &translate, double edgeThreshold) {
+    int w = output.width(), h = output.height();
+#ifdef MSDFGEN_USE_OPENMP
+    #pragma omp parallel for
+#endif
+    for (int y = 0; y < h; ++y) {
+        int row = shape.inverseYAxis ? h-y-1 : y;
+        for (int x = 0; x < w; ++x) {
+            Point2 p = Vector2(x+.5, y+.5)/scale-translate;
+
+            struct {
+                SignedDistance minDistance;
+                const EdgeHolder *nearEdge;
+                double nearParam;
+            } r, g, b;
+            r.nearEdge = g.nearEdge = b.nearEdge = NULL;
+            r.nearParam = g.nearParam = b.nearParam = 0;
+
+            for (std::vector<Contour>::const_iterator contour = shape.contours.begin(); contour != shape.contours.end(); ++contour)
+                for (std::vector<EdgeHolder>::const_iterator edge = contour->edges.begin(); edge != contour->edges.end(); ++edge) {
+                    double param;
+                    SignedDistance distance = (*edge)->signedDistance(p, param);
+                    if ((*edge)->color&RED && distance < r.minDistance) {
+                        r.minDistance = distance;
+                        r.nearEdge = &*edge;
+                        r.nearParam = param;
+                    }
+                    if ((*edge)->color&GREEN && distance < g.minDistance) {
+                        g.minDistance = distance;
+                        g.nearEdge = &*edge;
+                        g.nearParam = param;
+                    }
+                    if ((*edge)->color&BLUE && distance < b.minDistance) {
+                        b.minDistance = distance;
+                        b.nearEdge = &*edge;
+                        b.nearParam = param;
+                    }
+                }
+
+            if (r.nearEdge)
+                (*r.nearEdge)->distanceToPseudoDistance(r.minDistance, p, r.nearParam);
+            if (g.nearEdge)
+                (*g.nearEdge)->distanceToPseudoDistance(g.minDistance, p, g.nearParam);
+            if (b.nearEdge)
+                (*b.nearEdge)->distanceToPseudoDistance(b.minDistance, p, b.nearParam);
+            output(x, row).r = float(r.minDistance.distance/range+.5);
+            output(x, row).g = float(g.minDistance.distance/range+.5);
+            output(x, row).b = float(b.minDistance.distance/range+.5);
+        }
+    }
+
+    if (edgeThreshold > 0)
+        msdfErrorCorrection(output, edgeThreshold/(scale*range));
+}
+
+}

+ 107 - 0
core/render-sdf.cpp

@@ -0,0 +1,107 @@
+
+#include "render-sdf.h"
+
+#include "arithmetics.hpp"
+
+namespace msdfgen {
+
+template <typename S>
+inline FloatRGB mix(FloatRGB a, FloatRGB b, S weight) {
+    FloatRGB output = {
+        mix(a.r, b.r, weight),
+        mix(a.g, b.g, weight),
+        mix(a.b, b.b, weight)
+    };
+    return output;
+}
+
+template <typename T>
+static T sample(const Bitmap<T> &bitmap, Point2 pos) {
+    int w = bitmap.width(), h = bitmap.height();
+    double x = pos.x*w-.5;
+    double y = pos.y*h-.5;
+    int l = (int) floor(x);
+    int b = (int) floor(y);
+    int r = l+1;
+    int t = b+1;
+    double lr = x-l;
+    double bt = y-b;
+    l = clamp(l, w-1), r = clamp(r, w-1);
+    b = clamp(b, h-1), t = clamp(t, h-1);
+    return mix(mix(bitmap(l, b), bitmap(r, b), lr), mix(bitmap(l, t), bitmap(r, t), lr), bt);
+}
+
+static float distVal(float dist, double pxRange) {
+    if (!pxRange)
+        return dist > .5;
+    return (float) clamp((dist-.5)*pxRange+.5);
+}
+
+void renderSDF(Bitmap<float> &output, const Bitmap<float> &sdf, double pxRange) {
+    int w = output.width(), h = output.height();
+    pxRange *= (w+h)/(sdf.width()+sdf.height());
+    for (int y = 0; y < h; ++y)
+        for (int x = 0; x < w; ++x) {
+            float s = sample(sdf, Point2((x+.5)/w, (y+.5)/h));
+            output(x, y) = distVal(s, pxRange);
+        }
+}
+
+void renderSDF(Bitmap<FloatRGB> &output, const Bitmap<float> &sdf, double pxRange) {
+    int w = output.width(), h = output.height();
+    pxRange *= (w+h)/(sdf.width()+sdf.height());
+    for (int y = 0; y < h; ++y)
+        for (int x = 0; x < w; ++x) {
+            float s = sample(sdf, Point2((x+.5)/w, (y+.5)/h));
+            float v = distVal(s, pxRange);
+            output(x, y).r = v;
+            output(x, y).g = v;
+            output(x, y).b = v;
+        }
+}
+
+void renderSDF(Bitmap<float> &output, const Bitmap<FloatRGB> &sdf, double pxRange) {
+    int w = output.width(), h = output.height();
+    pxRange *= (w+h)/(sdf.width()+sdf.height());
+    for (int y = 0; y < h; ++y)
+        for (int x = 0; x < w; ++x) {
+            FloatRGB s = sample(sdf, Point2((x+.5)/w, (y+.5)/h));
+            output(x, y) = distVal(median(s.r, s.g, s.b), pxRange);
+        }
+}
+
+void renderSDF(Bitmap<FloatRGB> &output, const Bitmap<FloatRGB> &sdf, double pxRange) {
+    int w = output.width(), h = output.height();
+    pxRange *= (w+h)/(sdf.width()+sdf.height());
+    for (int y = 0; y < h; ++y)
+        for (int x = 0; x < w; ++x) {
+            FloatRGB s = sample(sdf, Point2((x+.5)/w, (y+.5)/h));
+            output(x, y).r = distVal(s.r, pxRange);
+            output(x, y).g = distVal(s.g, pxRange);
+            output(x, y).b = distVal(s.b, pxRange);
+        }
+}
+
+void simulate8bit(Bitmap<float> &bitmap) {
+    int w = bitmap.width(), h = bitmap.height();
+    for (int y = 0; y < h; ++y)
+        for (int x = 0; x < w; ++x) {
+            unsigned char v = clamp(int(bitmap(x, y)*0x100), 0xff);
+            bitmap(x, y) = v/255.f;
+        }
+}
+
+void simulate8bit(Bitmap<FloatRGB> &bitmap) {
+    int w = bitmap.width(), h = bitmap.height();
+    for (int y = 0; y < h; ++y)
+        for (int x = 0; x < w; ++x) {
+            unsigned char r = clamp(int(bitmap(x, y).r*0x100), 0xff);
+            unsigned char g = clamp(int(bitmap(x, y).g*0x100), 0xff);
+            unsigned char b = clamp(int(bitmap(x, y).b*0x100), 0xff);
+            bitmap(x, y).r = r/255.f;
+            bitmap(x, y).g = g/255.f;
+            bitmap(x, y).b = b/255.f;
+        }
+}
+
+}

+ 19 - 0
core/render-sdf.h

@@ -0,0 +1,19 @@
+
+#pragma once
+
+#include "Vector2.h"
+#include "Bitmap.h"
+
+namespace msdfgen {
+
+/// Reconstructs the shape's appearance into output from the distance field sdf.
+void renderSDF(Bitmap<float> &output, const Bitmap<float> &sdf, double pxRange = 0);
+void renderSDF(Bitmap<FloatRGB> &output, const Bitmap<float> &sdf, double pxRange = 0);
+void renderSDF(Bitmap<float> &output, const Bitmap<FloatRGB> &sdf, double pxRange = 0);
+void renderSDF(Bitmap<FloatRGB> &output, const Bitmap<FloatRGB> &sdf, double pxRange = 0);
+
+/// Snaps the values of the floating-point bitmaps into one of the 256 values representable in a standard 8-bit bitmap.
+void simulate8bit(Bitmap<float> &bitmap);
+void simulate8bit(Bitmap<FloatRGB> &bitmap);
+
+}

+ 109 - 0
core/save-bmp.cpp

@@ -0,0 +1,109 @@
+
+#include "save-bmp.h"
+
+#define _CRT_SECURE_NO_WARNINGS
+
+#include <cstdio>
+
+#ifdef MSDFGEN_USE_CPP11
+    #include <cstdint>
+#else
+    typedef int int32_t;
+    typedef unsigned uint32_t;
+    typedef unsigned short uint16_t;
+    typedef unsigned char uint8_t;
+#endif
+
+#include "arithmetics.hpp"
+
+namespace msdfgen {
+
+template <typename T>
+static bool writeValue(FILE *file, T value) {
+    #ifdef __BIG_ENDIAN__
+        T reverse = 0;
+        for (int i = 0; i < sizeof(T); ++i) {
+            reverse <<= 8;
+            reverse |= value&T(0xff);
+            value >>= 8;
+        }
+        return fwrite(&reverse, sizeof(T), 1, file) == 1;
+    #else
+        return fwrite(&value, sizeof(T), 1, file) == 1;
+    #endif
+}
+
+static bool writeBmpHeader(FILE *file, int width, int height, int &paddedWidth) {
+    paddedWidth = 3*width+3&~3;
+    const uint32_t bitmapStart = 54;
+    const uint32_t bitmapSize = paddedWidth*height;
+    const uint32_t fileSize = bitmapStart+bitmapSize;
+
+    writeValue<uint16_t>(file, 0x4d42u);
+    writeValue<uint32_t>(file, fileSize);
+    writeValue<uint16_t>(file, 0);
+    writeValue<uint16_t>(file, 0);
+    writeValue<uint32_t>(file, bitmapStart);
+
+    writeValue<uint32_t>(file, 40);
+    writeValue<int32_t>(file, width);
+    writeValue<int32_t>(file, height);
+    writeValue<uint16_t>(file, 1);
+    writeValue<uint16_t>(file, 24);
+    writeValue<uint32_t>(file, 0);
+    writeValue<uint32_t>(file, bitmapSize);
+    writeValue<uint32_t>(file, 2835);
+    writeValue<uint32_t>(file, 2835);
+    writeValue<uint32_t>(file, 0);
+    writeValue<uint32_t>(file, 0);
+
+    return true;
+}
+
+bool saveBmp(const Bitmap<float> &bitmap, const char *filename) {
+    FILE *file = fopen(filename, "wb");
+    if (!file)
+        return false;
+
+    int paddedWidth;
+    writeBmpHeader(file, bitmap.width(), bitmap.height(), paddedWidth);
+
+    const uint8_t padding[4] = { };
+    for (int y = 0; y < bitmap.height(); ++y) {
+        for (int x = 0; x < bitmap.width(); ++x) {
+            uint8_t px = (uint8_t) clamp(int(bitmap(x, y)*0x100), 0xff);
+            fwrite(&px, sizeof(uint8_t), 1, file);
+            fwrite(&px, sizeof(uint8_t), 1, file);
+            fwrite(&px, sizeof(uint8_t), 1, file);
+        }
+        fwrite(padding, 1, paddedWidth-3*bitmap.width(), file);
+    }
+
+    return !fclose(file);
+}
+
+bool saveBmp(const Bitmap<FloatRGB> &bitmap, const char *filename) {
+    FILE *file = fopen(filename, "wb");
+    if (!file)
+        return false;
+
+    int paddedWidth;
+    writeBmpHeader(file, bitmap.width(), bitmap.height(), paddedWidth);
+
+    const uint8_t padding[4] = { };
+    for (int y = 0; y < bitmap.height(); ++y) {
+        for (int x = 0; x < bitmap.width(); ++x) {
+            uint8_t bgr[3] = {
+                (uint8_t) clamp(int(bitmap(x, y).b*0x100), 0xff),
+                (uint8_t) clamp(int(bitmap(x, y).g*0x100), 0xff),
+                (uint8_t) clamp(int(bitmap(x, y).r*0x100), 0xff)
+            };
+            fwrite(bgr, sizeof(uint8_t), 3, file);
+        }
+        fwrite(padding, 1, paddedWidth-3*bitmap.width(), file);
+    }
+
+    return !fclose(file);
+}
+
+}

+ 12 - 0
core/save-bmp.h

@@ -0,0 +1,12 @@
+
+#pragma once
+
+#include "Bitmap.h"
+
+namespace msdfgen {
+
+/// Saves the bitmap as a BMP file.
+bool saveBmp(const Bitmap<float> &bitmap, const char *filename);
+bool saveBmp(const Bitmap<FloatRGB> &bitmap, const char *filename);
+
+}

+ 285 - 0
core/shape-description.cpp

@@ -0,0 +1,285 @@
+
+#include "shape-description.h"
+
+namespace msdfgen {
+
+#ifdef _WIN32
+    #pragma warning(disable:4996)
+#endif
+
+int readCharF(FILE *input) {
+    int c = '\0';
+    do {
+        c = fgetc(input);
+    } while (c == ' ' || c == '\t' || c == '\r' || c == '\n');
+    return c;
+}
+
+int readCharS(const char **input) {
+    int c = '\0';
+    do {
+        c = *(*input)++;
+    } while (c == ' ' || c == '\t' || c == '\r' || c == '\n');
+    if (!c) {
+        --c;
+        return EOF;
+    }
+    return c;
+}
+
+int readCoordF(FILE *input, Point2 &coord) {
+    return fscanf(input, "%lf,%lf", &coord.x, &coord.y);
+}
+
+int readCoordS(const char **input, Point2 &coord) {
+    int read = 0;
+    int result = sscanf(*input, "%lf,%lf%n", &coord.x, &coord.y, &read);
+    *input += read;
+    return result;
+}
+
+static bool writeCoord(FILE *output, Point2 coord) {
+    fprintf(output, "%.12g, %.12g", coord.x, coord.y);
+    return true;
+}
+
+template <typename T, int (*readChar)(T *), int (*readCoord)(T *, Point2 &)>
+static int readControlPoints(T *input, Point2 *output) {
+    int result = readCoord(input, output[0]);
+    if (result == 2) {
+        switch (readChar(input)) {
+            case ')':
+                return 1;
+            case ';':
+                break;
+            default:
+                return -1;
+        }
+        result = readCoord(input, output[1]);
+        if (result == 2 && readChar(input) == ')')
+            return 2;
+    } else if (result != 1 && readChar(input) == ')')
+        return 0;
+    return -1;
+}
+
+template <typename T, int (*readChar)(T *), int (*readCoord)(T *, Point2 &)>
+static bool readContour(T *input, Contour &output, const Point2 *first, int terminator, bool &colorsSpecified) {
+    Point2 p[4], start;
+    if (first)
+        p[0] = *first;
+    else {
+        int result = readCoord(input, p[0]);
+        if (result != 2)
+            return result != 1 && readChar(input) == terminator;
+    }
+    start = p[0];
+    int c = '\0';
+    while ((c = readChar(input)) != terminator) {
+        if (c != ';')
+            return false;
+        bool parenthesis = false;
+        EdgeColor color = WHITE;
+        int result = readCoord(input, p[1]);
+        if (result == 2) {
+            output.addEdge(EdgeHolder(p[0], p[1], color));
+            p[0] = p[1];
+            continue;
+        } else if (result == 1)
+            return false;
+        else {
+            int controlPoints = 0;
+            switch ((c = readChar(input))) {
+                case '#':
+                    output.addEdge(EdgeHolder(p[0], start, color));
+                    p[0] = start;
+                    continue;
+                case ';':
+                    goto FINISH_EDGE;
+                case '(':
+                    goto READ_CONTROL_POINTS;
+                case 'C': case 'c':
+                    color = CYAN;
+                    colorsSpecified = true;
+                    break;
+                case 'M': case 'm':
+                    color = MAGENTA;
+                    colorsSpecified = true;
+                    break;
+                case 'Y': case 'y':
+                    color = YELLOW;
+                    colorsSpecified = true;
+                    break;
+                case 'W': case 'w':
+                    color = WHITE;
+                    colorsSpecified = true;
+                    break;
+                default:
+                    return c == terminator;
+            }
+            switch (readChar(input)) {
+                case ';':
+                    goto FINISH_EDGE;
+                case '(':
+                READ_CONTROL_POINTS:
+                    if ((controlPoints = readControlPoints<T, readChar, readCoord>(input, p+1)) < 0)
+                        return false;
+                    break;
+                default:
+                    return false;
+            }
+            if (readChar(input) != ';')
+                return false;
+        FINISH_EDGE:
+            result = readCoord(input, p[1+controlPoints]);
+            if (result != 2) {
+                if (result == 1)
+                    return false;
+                else {
+                    if (readChar(input) == '#')
+                        p[1+controlPoints] = start;
+                    else
+                        return false;
+                }
+            }
+            switch (controlPoints) {
+                case 0:
+                    output.addEdge(EdgeHolder(p[0], p[1], color));
+                    p[0] = p[1];
+                    continue;
+                case 1:
+                    output.addEdge(EdgeHolder(p[0], p[1], p[2], color));
+                    p[0] = p[2];
+                    continue;
+                case 2:
+                    output.addEdge(EdgeHolder(p[0], p[1], p[2], p[3], color));
+                    p[0] = p[3];
+                    continue;
+            }
+        }
+    }
+    return true;
+}
+
+bool readShapeDescription(FILE *input, Shape &output, bool *colorsSpecified) {
+    bool locColorsSpec = false;
+    output.contours.clear();
+    output.inverseYAxis = false;
+    Point2 p;
+    int result = readCoordF(input, p);
+    if (result == 2) {
+        return readContour<FILE, readCharF, readCoordF>(input, output.addContour(), &p, EOF, locColorsSpec);
+    } else if (result == 1)
+        return false;
+    else {
+        int c = readCharF(input);
+        if (c == '@') {
+            char after = '\0';
+            if (fscanf(input, "invert-y%c", &after) != 1)
+                return feof(input) != 0;
+            output.inverseYAxis = true;
+            c = after;
+            if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
+                c = readCharF(input);
+        }
+        for (; c == '{'; c = readCharF(input))
+            if (!readContour<FILE, readCharF, readCoordF>(input, output.addContour(), NULL, '}', locColorsSpec))
+                return false;
+        if (colorsSpecified)
+            *colorsSpecified = locColorsSpec;
+        return c == EOF && feof(input);
+    }
+}
+
+bool readShapeDescription(const char *input, Shape &output, bool *colorsSpecified) {
+    bool locColorsSpec = false;
+    output.contours.clear();
+    output.inverseYAxis = false;
+    Point2 p;
+    int result = readCoordS(&input, p);
+    if (result == 2) {
+        return readContour<const char *, readCharS, readCoordS>(&input, output.addContour(), &p, EOF, locColorsSpec);
+    } else if (result == 1)
+        return false;
+    else {
+        int c = readCharS(&input);
+        if (c == '@') {
+            for (int i = 0; i < sizeof("invert-y")-1; ++i)
+                if (input[i] != "invert-y"[i])
+                    return false;
+            output.inverseYAxis = true;
+            input += sizeof("invert-y")-1;
+            c = readCharS(&input);
+        }
+        for (; c == '{'; c = readCharS(&input))
+            if (!readContour<const char *, readCharS, readCoordS>(&input, output.addContour(), NULL, '}', locColorsSpec))
+                return false;
+        if (colorsSpecified)
+            *colorsSpecified = locColorsSpec;
+        return c == EOF;
+    }
+}
+
+bool writeShapeDescription(FILE *output, const Shape &shape) {
+    if (!shape.validate())
+        return false;
+    if (shape.inverseYAxis)
+        fprintf(output, "@invert-y\n");
+    for (std::vector<Contour>::const_iterator contour = shape.contours.begin(); contour != shape.contours.end(); ++contour) {
+        fprintf(output, "{\n");
+        if (!contour->edges.empty()) {
+            for (std::vector<EdgeHolder>::const_iterator edge = contour->edges.begin(); edge != contour->edges.end(); ++edge) {
+                char colorCode = '\0';
+                switch ((*edge)->color) {
+                    case YELLOW: colorCode = 'y'; break;
+                    case MAGENTA: colorCode = 'm'; break;
+                    case CYAN: colorCode = 'c'; break;
+                    case WHITE: colorCode = 'w'; break;
+                }
+                {
+                    const LinearSegment *e = dynamic_cast<const LinearSegment *>(&**edge);
+                    if (e) {
+                        fprintf(output, "\t");
+                        writeCoord(output, e->p[0]);
+                        fprintf(output, ";\n");
+                        if (colorCode)
+                            fprintf(output, "\t\t%c;\n", colorCode);
+                    }
+                }
+                {
+                    const QuadraticSegment *e = dynamic_cast<const QuadraticSegment *>(&**edge);
+                    if (e) {
+                        fprintf(output, "\t");
+                        writeCoord(output, e->p[0]);
+                        fprintf(output, ";\n\t\t");
+                        if (colorCode)
+                            fprintf(output, "%c", colorCode);
+                        fprintf(output, "(");
+                        writeCoord(output, e->p[1]);
+                        fprintf(output, ");\n");
+                    }
+                }
+                {
+                    const CubicSegment *e = dynamic_cast<const CubicSegment *>(&**edge);
+                    if (e) {
+                        fprintf(output, "\t");
+                        writeCoord(output, e->p[0]);
+                        fprintf(output, ";\n\t\t");
+                        if (colorCode)
+                            fprintf(output, "%c", colorCode);
+                        fprintf(output, "(");
+                        writeCoord(output, e->p[1]);
+                        fprintf(output, "; ");
+                        writeCoord(output, e->p[2]);
+                        fprintf(output, ");\n");
+                    }
+                }
+            }
+            fprintf(output, "\t#\n");
+        }
+        fprintf(output, "}\n");
+    }
+    return true;
+}
+
+}

+ 16 - 0
core/shape-description.h

@@ -0,0 +1,16 @@
+
+#pragma once
+
+#include <cstdlib>
+#include <cstdio>
+#include "Shape.h"
+
+namespace msdfgen {
+
+/// Deserializes a text description of a vector shape into output.
+bool readShapeDescription(FILE *input, Shape &output, bool *colorsSpecified = NULL);
+bool readShapeDescription(const char *input, Shape &output, bool *colorsSpecified = NULL);
+/// Serializes a shape object into a text description.
+bool writeShapeDescription(FILE *output, const Shape &shape);
+
+}

+ 1 - 0
example.bat

@@ -0,0 +1 @@
+msdfgen.exe -defineshape "{ 1471,0; 1149,0; 1021,333; 435,333; 314,0; 0,0; 571,1466; 884,1466; # }{ 926,580; 724,1124; 526,580; # }" -size 16 16 -autoframe -testrender render.png 1024 1024

+ 192 - 0
ext/import-font.cpp

@@ -0,0 +1,192 @@
+
+#include "import-font.h"
+
+#include <cstdlib>
+#include <queue>
+#include <ft2build.h>
+#include FT_FREETYPE_H
+
+#ifdef _WIN32
+    #pragma comment(lib, "freetype.lib")
+#endif
+
+namespace msdfgen {
+
+#define REQUIRE(cond) { if (!(cond)) return false; }
+
+class FreetypeHandle {
+    friend FreetypeHandle * initializeFreetype();
+    friend void deinitializeFreetype(FreetypeHandle *library);
+    friend FontHandle * loadFont(FreetypeHandle *library, const char *filename);
+
+    FT_Library library;
+
+};
+
+class FontHandle {
+    friend FontHandle * loadFont(FreetypeHandle *library, const char *filename);
+    friend void destroyFont(FontHandle *font);
+    friend bool getFontScale(double &output, FontHandle *font);
+    friend bool getFontWhitespaceWidth(double &spaceAdvance, double &tabAdvance, FontHandle *font);
+    friend bool loadGlyph(Shape &output, FontHandle *font, int unicode, double *advance);
+    friend bool getKerning(double &output, FontHandle *font, int unicode1, int unicode2);
+
+    FT_Face face;
+
+};
+
+FreetypeHandle * initializeFreetype() {
+    FreetypeHandle *handle = new FreetypeHandle;
+    FT_Error error = FT_Init_FreeType(&handle->library);
+    if (error) {
+        delete handle;
+        return NULL;
+    }
+    return handle;
+}
+
+void deinitializeFreetype(FreetypeHandle *library) {
+    FT_Done_FreeType(library->library);
+    delete library;
+}
+
+FontHandle * loadFont(FreetypeHandle *library, const char *filename) {
+    if (!library)
+        return NULL;
+    FontHandle *handle = new FontHandle;
+    FT_Error error = FT_New_Face(library->library, filename, 0, &handle->face);
+    if (error) {
+        delete handle;
+        return NULL;
+    }
+    return handle;
+}
+
+void destroyFont(FontHandle *font) {
+    FT_Done_Face(font->face);
+    delete font;
+}
+
+bool getFontScale(double &output, FontHandle *font) {
+    output = font->face->units_per_EM/64.;
+    return true;
+}
+
+bool getFontWhitespaceWidth(double &spaceAdvance, double &tabAdvance, FontHandle *font) {
+    FT_Error error = FT_Load_Char(font->face, ' ', FT_LOAD_NO_SCALE);
+    if (error)
+        return false;
+    spaceAdvance = font->face->glyph->advance.x/64.;
+    error = FT_Load_Char(font->face, '\t', FT_LOAD_NO_SCALE);
+    if (error)
+        return false;
+    tabAdvance = font->face->glyph->advance.x/64.;
+    return true;
+}
+
+bool loadGlyph(Shape &output, FontHandle *font, int unicode, double *advance) {
+    enum PointType {
+        NONE = 0,
+        PATH_POINT,
+        QUADRATIC_POINT,
+        CUBIC_POINT,
+        CUBIC_POINT2
+    };
+
+    if (!font)
+        return NULL;
+    FT_Error error = FT_Load_Char(font->face, unicode, FT_LOAD_NO_SCALE);
+    if (error)
+        return NULL;
+    output.contours.clear();
+    output.inverseYAxis = false;
+    if (advance)
+        *advance = font->face->glyph->advance.x/64.;
+
+    int last = -1;
+    // For each contour
+    for (int i = 0; i < font->face->glyph->outline.n_contours; ++i) {
+
+        Contour &contour = output.addContour();
+        int first = last+1;
+        last = font->face->glyph->outline.contours[i];
+
+        PointType state = NONE;
+        Point2 startPoint;
+        Point2 controlPoint[2];
+
+        // For each point on the contour
+        for (int round = 0, index = first; round == 0; ++index) {
+            // Close contour
+            if (index > last) {
+                index = first;
+                round++;
+            }
+
+            Point2 point(font->face->glyph->outline.points[index].x/64., font->face->glyph->outline.points[index].y/64.);
+            PointType pointType = font->face->glyph->outline.tags[index]&1 ? PATH_POINT : font->face->glyph->outline.tags[index]&2 ? CUBIC_POINT : QUADRATIC_POINT;
+
+            switch (state) {
+                case NONE:
+                    REQUIRE(pointType == PATH_POINT);
+                    startPoint = point;
+                    state = PATH_POINT;
+                    break;
+                case PATH_POINT:
+                    if (pointType == PATH_POINT) {
+                        contour.addEdge(new LinearSegment(startPoint, point));
+                        startPoint = point;
+                    } else {
+                        controlPoint[0] = point;
+                        state = pointType;
+                    }
+                    break;
+                case QUADRATIC_POINT:
+                    REQUIRE(pointType != CUBIC_POINT);
+                    if (pointType == PATH_POINT) {
+                        contour.addEdge(new QuadraticSegment(startPoint, controlPoint[0], point));
+                        startPoint = point;
+                        state = PATH_POINT;
+                    } else {
+                        Point2 midPoint = .5*controlPoint[0]+.5*point;
+                        contour.addEdge(new QuadraticSegment(startPoint, controlPoint[0], midPoint));
+                        startPoint = midPoint;
+                        controlPoint[0] = point;
+                    }
+                    break;
+                case CUBIC_POINT:
+                    REQUIRE(pointType == CUBIC_POINT);
+                    controlPoint[1] = point;
+                    state = CUBIC_POINT2;
+                    break;
+                case CUBIC_POINT2:
+                    REQUIRE(pointType != QUADRATIC_POINT);
+                    if (pointType == PATH_POINT) {
+                        contour.addEdge(new CubicSegment(startPoint, controlPoint[0], controlPoint[1], point));
+                        startPoint = point;
+                    } else {
+                        Point2 midPoint = .5*controlPoint[1]+.5*point;
+                        contour.addEdge(new CubicSegment(startPoint, controlPoint[0], controlPoint[1], midPoint));
+                        startPoint = midPoint;
+                        controlPoint[0] = point;
+                    }
+                    state = pointType;
+                    break;
+            }
+
+        }
+    }
+    return true;
+}
+
+bool getKerning(double &output, FontHandle *font, int unicode1, int unicode2) {
+    FT_Vector kerning;
+    if (FT_Get_Kerning(font->face, FT_Get_Char_Index(font->face, unicode1), FT_Get_Char_Index(font->face, unicode2), FT_KERNING_UNSCALED, &kerning)) {
+        output = 0;
+        return false;
+    }
+    output = kerning.x/64.;
+    return true;
+}
+
+}

+ 29 - 0
ext/import-font.h

@@ -0,0 +1,29 @@
+
+#pragma once
+
+#include <cstdlib>
+#include "../core/Shape.h"
+
+namespace msdfgen {
+
+class FreetypeHandle;
+class FontHandle;
+
+/// Initializes the FreeType library
+FreetypeHandle * initializeFreetype();
+/// Deinitializes the FreeType library
+void deinitializeFreetype(FreetypeHandle *library);
+/// Loads a font file and returns its handle
+FontHandle * loadFont(FreetypeHandle *library, const char *filename);
+/// Unloads a font file
+void destroyFont(FontHandle *font);
+/// Returns the size of one EM in the font's coordinate system
+bool getFontScale(double &output, FontHandle *font);
+/// Returns the width of space and tab
+bool getFontWhitespaceWidth(double &spaceAdvance, double &tabAdvance, FontHandle *font);
+/// Loads the shape prototype of a glyph from font file
+bool loadGlyph(Shape &output, FontHandle *font, int unicode, double *advance = NULL);
+/// Returns the kerning distance adjustment between two specific glyphs.
+bool getKerning(double &output, FontHandle *font, int unicode1, int unicode2);
+
+}

+ 184 - 0
ext/import-svg.cpp

@@ -0,0 +1,184 @@
+
+#include "import-svg.h"
+
+#include <cstdio>
+#include <tinyxml2.h>
+
+#ifdef _WIN32
+    #pragma warning(disable:4996)
+#endif
+
+namespace msdfgen {
+
+#define REQUIRE(cond) { if (!(cond)) return false; }
+
+static bool readNodeType(char &output, const char *&pathDef) {
+    int shift;
+    char nodeType;
+    if (sscanf(pathDef, " %c%n", &nodeType, &shift) == 1 && nodeType != '+' && nodeType != '-' && nodeType != '.' && nodeType != ',' && (nodeType < '0' || nodeType > '9')) {
+        pathDef += shift;
+        output = nodeType;
+        return true;
+    }
+    return false;
+}
+
+static bool readCoord(Point2 &output, const char *&pathDef) {
+    int shift;
+    double x, y;
+    if (sscanf(pathDef, "%lf%lf%n", &x, &y, &shift) == 2) {
+        output.x = x;
+        output.y = y;
+        pathDef += shift;
+        return true;
+    }
+    if (sscanf(pathDef, "%lf,%lf%n", &x, &y, &shift) == 2) {
+        output.x = x;
+        output.y = y;
+        pathDef += shift;
+        return true;
+    }
+    return false;
+}
+
+static bool readDouble(double &output, const char *&pathDef) {
+    int shift;
+    double v;
+    if (sscanf(pathDef, "%lf%n", &v, &shift) == 1) {
+        pathDef += shift;
+        output = v;
+        return true;
+    }
+    return false;
+}
+
+static bool buildFromPath(Shape &shape, const char *pathDef) {
+    char nodeType;
+    Point2 prevNode(0, 0);
+    while (readNodeType(nodeType, pathDef)) {
+        Contour &contour = shape.addContour();
+        bool contourStart = true;
+
+        Point2 startPoint;
+        Point2 controlPoint[2];
+        Point2 node;
+
+        while (true) {
+            switch (nodeType) {
+                case 'M':
+                    REQUIRE(contourStart);
+                    REQUIRE(readCoord(node, pathDef));
+                    startPoint = node;
+                    nodeType = 'L';
+                    break;
+                case 'm':
+                    REQUIRE(contourStart);
+                    REQUIRE(readCoord(node, pathDef));
+                    node += prevNode;
+                    startPoint = node;
+                    nodeType = 'l';
+                    break;
+                case 'Z':
+                case 'z':
+                    if (prevNode != startPoint)
+                        contour.addEdge(new LinearSegment(prevNode, startPoint));
+                    goto NEXT_CONTOUR;
+                case 'L':
+                    REQUIRE(readCoord(node, pathDef));
+                    contour.addEdge(new LinearSegment(prevNode, node));
+                    break;
+                case 'l':
+                    REQUIRE(readCoord(node, pathDef));
+                    node += prevNode;
+                    contour.addEdge(new LinearSegment(prevNode, node));
+                    break;
+                case 'H':
+                    REQUIRE(readDouble(node.x, pathDef));
+                    contour.addEdge(new LinearSegment(prevNode, node));
+                    break;
+                case 'h':
+                    REQUIRE(readDouble(node.x, pathDef));
+                    node.x += prevNode.x;
+                    contour.addEdge(new LinearSegment(prevNode, node));
+                    break;
+                case 'V':
+                    REQUIRE(readDouble(node.y, pathDef));
+                    contour.addEdge(new LinearSegment(prevNode, node));
+                    break;
+                case 'v':
+                    REQUIRE(readDouble(node.y, pathDef));
+                    node.y += prevNode.y;
+                    contour.addEdge(new LinearSegment(prevNode, node));
+                    break;
+                case 'Q':
+                    REQUIRE(readCoord(controlPoint[0], pathDef));
+                    REQUIRE(readCoord(node, pathDef));
+                    contour.addEdge(new QuadraticSegment(prevNode, controlPoint[0], node));
+                    break;
+                case 'q':
+                    REQUIRE(readCoord(controlPoint[0], pathDef));
+                    REQUIRE(readCoord(node, pathDef));
+                    controlPoint[0] += prevNode;
+                    node += prevNode;
+                    contour.addEdge(new QuadraticSegment(prevNode, controlPoint[0], node));
+                    break;
+                // TODO T, t
+                case 'C':
+                    REQUIRE(readCoord(controlPoint[0], pathDef));
+                    REQUIRE(readCoord(controlPoint[1], pathDef));
+                    REQUIRE(readCoord(node, pathDef));
+                    contour.addEdge(new CubicSegment(prevNode, controlPoint[0], controlPoint[1], node));
+                    break;
+                case 'c':
+                    REQUIRE(readCoord(controlPoint[0], pathDef));
+                    REQUIRE(readCoord(controlPoint[1], pathDef));
+                    REQUIRE(readCoord(node, pathDef));
+                    controlPoint[0] += prevNode;
+                    controlPoint[1] += prevNode;
+                    node += prevNode;
+                    contour.addEdge(new CubicSegment(prevNode, controlPoint[0], controlPoint[1], node));
+                    break;
+                // TODO S, s
+                // TODO A, a
+                default:
+                    REQUIRE(false);
+            }
+            contourStart &= nodeType == 'M' || nodeType == 'm';
+            prevNode = node;
+            readNodeType(nodeType, pathDef);
+        }
+    NEXT_CONTOUR:;
+    }
+    return true;
+}
+
+bool loadSvgShape(Shape &output, const char *filename, Vector2 *dimensions) {
+    tinyxml2::XMLDocument doc;
+    if (doc.LoadFile(filename))
+        return false;
+    tinyxml2::XMLElement *root = doc.FirstChildElement("svg");
+    if (!root)
+        return false;
+
+    tinyxml2::XMLElement *path = root->FirstChildElement("path");
+    if (!path) {
+        tinyxml2::XMLElement *g = root->FirstChildElement("g");
+        if (g)
+            path = g->FirstChildElement("path");
+    }
+    if (!path)
+        return false;
+    const char *pd = path->Attribute("d");
+    if (!pd)
+        return false;
+
+    output.contours.clear();
+    output.inverseYAxis = true;
+    if (dimensions) {
+        dimensions->x = root->DoubleAttribute("width");
+        dimensions->y = root->DoubleAttribute("height");
+    }
+    return buildFromPath(output, pd);
+}
+
+}

+ 12 - 0
ext/import-svg.h

@@ -0,0 +1,12 @@
+
+#pragma once
+
+#include <cstdlib>
+#include "../core/Shape.h"
+
+namespace msdfgen {
+
+/// Reads the first path found in the specified SVG file and stores it as a Shape in output.
+bool loadSvgShape(Shape &output, const char *filename, Vector2 *dimensions = NULL);
+
+}

+ 30 - 0
ext/save-png.cpp

@@ -0,0 +1,30 @@
+
+#include "save-png.h"
+
+#include "../core/arithmetics.hpp"
+#include <lodepng.h>
+
+namespace msdfgen {
+
+bool savePng(const Bitmap<float> &bitmap, const char *filename) {
+    std::vector<unsigned char> pixels(bitmap.width()*bitmap.height());
+    std::vector<unsigned char>::iterator it = pixels.begin();
+    for (int y = bitmap.height()-1; y >= 0; --y)
+        for (int x = 0; x < bitmap.width(); ++x)
+            *it++ = clamp(int(bitmap(x, y)*0x100), 0xff);
+    return !lodepng::encode(filename, pixels, bitmap.width(), bitmap.height(), LCT_GREY);
+}
+
+bool savePng(const Bitmap<FloatRGB> &bitmap, const char *filename) {
+    std::vector<unsigned char> pixels(3*bitmap.width()*bitmap.height());
+    std::vector<unsigned char>::iterator it = pixels.begin();
+    for (int y = bitmap.height()-1; y >= 0; --y)
+        for (int x = 0; x < bitmap.width(); ++x) {
+            *it++ = clamp(int(bitmap(x, y).r*0x100), 0xff);
+            *it++ = clamp(int(bitmap(x, y).g*0x100), 0xff);
+            *it++ = clamp(int(bitmap(x, y).b*0x100), 0xff);
+        }
+    return !lodepng::encode(filename, pixels, bitmap.width(), bitmap.height(), LCT_RGB);
+}
+
+}

+ 12 - 0
ext/save-png.h

@@ -0,0 +1,12 @@
+
+#pragma once
+
+#include "../core/Bitmap.h"
+
+namespace msdfgen {
+
+/// Saves the bitmap as a PNG file.
+bool savePng(const Bitmap<float> &bitmap, const char *filename);
+bool savePng(const Bitmap<FloatRGB> &bitmap, const char *filename);
+
+}

TEMPAT SAMPAH
freetype6.dll


TEMPAT SAMPAH
icon.ico


+ 350 - 0
include/freetype/config/ftconfig.h

@@ -0,0 +1,350 @@
+/* ftconfig.h.  Generated from ftconfig.in by configure.  */
+/***************************************************************************/
+/*                                                                         */
+/*  ftconfig.in                                                            */
+/*                                                                         */
+/*    UNIX-specific configuration file (specification only).               */
+/*                                                                         */
+/*  Copyright 1996-2001, 2002, 2003, 2004, 2006, 2007 by                   */
+/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */
+/*                                                                         */
+/*  This file is part of the FreeType project, and may only be used,       */
+/*  modified, and distributed under the terms of the FreeType project      */
+/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */
+/*  this file you indicate that you have read the license and              */
+/*  understand and accept it fully.                                        */
+/*                                                                         */
+/***************************************************************************/
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* This header file contains a number of macro definitions that are used */
+  /* by the rest of the engine.  Most of the macros here are automatically */
+  /* determined at compile time, and you should not need to change it to   */
+  /* port FreeType, except to compile the library with a non-ANSI          */
+  /* compiler.                                                             */
+  /*                                                                       */
+  /* Note however that if some specific modifications are needed, we       */
+  /* advise you to place a modified copy in your build directory.          */
+  /*                                                                       */
+  /* The build directory is usually `freetype/builds/<system>', and        */
+  /* contains system-specific files that are always included first when    */
+  /* building the library.                                                 */
+  /*                                                                       */
+  /*************************************************************************/
+
+
+#ifndef __FTCONFIG_H__
+#define __FTCONFIG_H__
+
+#include <ft2build.h>
+#include FT_CONFIG_OPTIONS_H
+#include FT_CONFIG_STANDARD_LIBRARY_H
+
+
+FT_BEGIN_HEADER
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /*               PLATFORM-SPECIFIC CONFIGURATION MACROS                  */
+  /*                                                                       */
+  /* These macros can be toggled to suit a specific system.  The current   */
+  /* ones are defaults used to compile FreeType in an ANSI C environment   */
+  /* (16bit compilers are also supported).  Copy this file to your own     */
+  /* `freetype/builds/<system>' directory, and edit it to port the engine. */
+  /*                                                                       */
+  /*************************************************************************/
+
+
+#define HAVE_UNISTD_H 1
+#define HAVE_FCNTL_H 1
+
+#define SIZEOF_INT 4
+#define SIZEOF_LONG 4
+
+
+#define FT_SIZEOF_INT   SIZEOF_INT
+#define FT_SIZEOF_LONG  SIZEOF_LONG
+
+#define FT_CHAR_BIT  CHAR_BIT
+
+  /* Preferred alignment of data */
+#define FT_ALIGNMENT  8
+
+
+  /* FT_UNUSED is a macro used to indicate that a given parameter is not  */
+  /* used -- this is only used to get rid of unpleasant compiler warnings */
+#ifndef FT_UNUSED
+#define FT_UNUSED( arg )  ( (arg) = (arg) )
+#endif
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /*                     AUTOMATIC CONFIGURATION MACROS                    */
+  /*                                                                       */
+  /* These macros are computed from the ones defined above.  Don't touch   */
+  /* their definition, unless you know precisely what you are doing.  No   */
+  /* porter should need to mess with them.                                 */
+  /*                                                                       */
+  /*************************************************************************/
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* Mac support                                                           */
+  /*                                                                       */
+  /*   This is the only necessary change, so it is defined here instead    */
+  /*   providing a new configuration file.                                 */
+  /*                                                                       */
+#if ( defined( __APPLE__ ) && !defined( DARWIN_NO_CARBON ) ) || \
+    ( defined( __MWERKS__ ) && defined( macintosh )        )
+  /* no Carbon frameworks for 64bit 10.4.x */
+#include "AvailabilityMacros.h"
+#if defined( __LP64__ ) && \
+    ( MAC_OS_X_VERSION_MIN_REQUIRED <= MAC_OS_X_VERSION_10_4 )
+#define DARWIN_NO_CARBON 1
+#else
+#define FT_MACINTOSH 1
+#endif
+#endif
+
+
+  /* Fix compiler warning with sgi compiler */
+#if defined( __sgi ) && !defined( __GNUC__ )
+#if defined( _COMPILER_VERSION ) && ( _COMPILER_VERSION >= 730 )
+#pragma set woff 3505
+#endif
+#endif
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* IntN types                                                            */
+  /*                                                                       */
+  /*   Used to guarantee the size of some specific integers.               */
+  /*                                                                       */
+  typedef signed short    FT_Int16;
+  typedef unsigned short  FT_UInt16;
+
+#if FT_SIZEOF_INT == 4
+
+  typedef signed int      FT_Int32;
+  typedef unsigned int    FT_UInt32;
+
+#elif FT_SIZEOF_LONG == 4
+
+  typedef signed long     FT_Int32;
+  typedef unsigned long   FT_UInt32;
+
+#else
+#error "no 32bit type found -- please check your configuration files"
+#endif
+
+
+  /* look up an integer type that is at least 32 bits */
+#if FT_SIZEOF_INT >= 4
+
+  typedef int            FT_Fast;
+  typedef unsigned int   FT_UFast;
+
+#elif FT_SIZEOF_LONG >= 4
+
+  typedef long           FT_Fast;
+  typedef unsigned long  FT_UFast;
+
+#endif
+
+
+  /* determine whether we have a 64-bit int type for platforms without */
+  /* Autoconf                                                          */
+#if FT_SIZEOF_LONG == 8
+
+  /* FT_LONG64 must be defined if a 64-bit type is available */
+#define FT_LONG64
+#define FT_INT64  long
+
+#elif defined( _MSC_VER ) && _MSC_VER >= 900  /* Visual C++ (and Intel C++) */
+
+  /* this compiler provides the __int64 type */
+#define FT_LONG64
+#define FT_INT64  __int64
+
+#elif defined( __BORLANDC__ )  /* Borland C++ */
+
+  /* XXXX: We should probably check the value of __BORLANDC__ in order */
+  /*       to test the compiler version.                               */
+
+  /* this compiler provides the __int64 type */
+#define FT_LONG64
+#define FT_INT64  __int64
+
+#elif defined( __WATCOMC__ )   /* Watcom C++ */
+
+  /* Watcom doesn't provide 64-bit data types */
+
+#elif defined( __MWERKS__ )    /* Metrowerks CodeWarrior */
+
+#define FT_LONG64
+#define FT_INT64  long long int
+
+#elif defined( __GNUC__ )
+
+  /* GCC provides the `long long' type */
+#define FT_LONG64
+#define FT_INT64  long long int
+
+#endif /* FT_SIZEOF_LONG == 8 */
+
+
+#define FT_BEGIN_STMNT  do {
+#define FT_END_STMNT    } while ( 0 )
+#define FT_DUMMY_STMNT  FT_BEGIN_STMNT FT_END_STMNT
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* A 64-bit data type will create compilation problems if you compile    */
+  /* in strict ANSI mode.  To avoid them, we disable their use if          */
+  /* __STDC__ is defined.  You can however ignore this rule by             */
+  /* defining the FT_CONFIG_OPTION_FORCE_INT64 configuration macro.        */
+  /*                                                                       */
+#if defined( FT_LONG64 ) && !defined( FT_CONFIG_OPTION_FORCE_INT64 )
+
+#ifdef __STDC__
+
+  /* Undefine the 64-bit macros in strict ANSI compilation mode.  */
+  /* Since `#undef' doesn't survive in configuration header files */
+  /* we use the postprocessing facility of AC_CONFIG_HEADERS to   */
+  /* replace the leading `/' with `#'.                            */
+#undef FT_LONG64
+#undef FT_INT64
+
+#endif /* __STDC__ */
+
+#endif /* FT_LONG64 && !FT_CONFIG_OPTION_FORCE_INT64 */
+
+
+#ifdef FT_MAKE_OPTION_SINGLE_OBJECT
+
+#define FT_LOCAL( x )      static  x
+#define FT_LOCAL_DEF( x )  static  x
+
+#else
+
+#ifdef __cplusplus
+#define FT_LOCAL( x )      extern "C"  x
+#define FT_LOCAL_DEF( x )  extern "C"  x
+#else
+#define FT_LOCAL( x )      extern  x
+#define FT_LOCAL_DEF( x )  x
+#endif
+
+#endif /* FT_MAKE_OPTION_SINGLE_OBJECT */
+
+
+#ifndef FT_BASE
+
+#ifdef __cplusplus
+#define FT_BASE( x )  extern "C"  x
+#else
+#define FT_BASE( x )  extern  x
+#endif
+
+#endif /* !FT_BASE */
+
+
+#ifndef FT_BASE_DEF
+
+#ifdef __cplusplus
+#define FT_BASE_DEF( x )  x
+#else
+#define FT_BASE_DEF( x )  x
+#endif
+
+#endif /* !FT_BASE_DEF */
+
+
+#ifndef FT_EXPORT
+
+#ifdef __cplusplus
+#define FT_EXPORT( x )  extern "C"  x
+#else
+#define FT_EXPORT( x )  extern  x
+#endif
+
+#endif /* !FT_EXPORT */
+
+
+#ifndef FT_EXPORT_DEF
+
+#ifdef __cplusplus
+#define FT_EXPORT_DEF( x )  extern "C"  x
+#else
+#define FT_EXPORT_DEF( x )  extern  x
+#endif
+
+#endif /* !FT_EXPORT_DEF */
+
+
+#ifndef FT_EXPORT_VAR
+
+#ifdef __cplusplus
+#define FT_EXPORT_VAR( x )  extern "C"  x
+#else
+#define FT_EXPORT_VAR( x )  extern  x
+#endif
+
+#endif /* !FT_EXPORT_VAR */
+
+  /* The following macros are needed to compile the library with a   */
+  /* C++ compiler and with 16bit compilers.                          */
+  /*                                                                 */
+
+  /* This is special.  Within C++, you must specify `extern "C"' for */
+  /* functions which are used via function pointers, and you also    */
+  /* must do that for structures which contain function pointers to  */
+  /* assure C linkage -- it's not possible to have (local) anonymous */
+  /* functions which are accessed by (global) function pointers.     */
+  /*                                                                 */
+  /*                                                                 */
+  /* FT_CALLBACK_DEF is used to _define_ a callback function.        */
+  /*                                                                 */
+  /* FT_CALLBACK_TABLE is used to _declare_ a constant variable that */
+  /* contains pointers to callback functions.                        */
+  /*                                                                 */
+  /* FT_CALLBACK_TABLE_DEF is used to _define_ a constant variable   */
+  /* that contains pointers to callback functions.                   */
+  /*                                                                 */
+  /*                                                                 */
+  /* Some 16bit compilers have to redefine these macros to insert    */
+  /* the infamous `_cdecl' or `__fastcall' declarations.             */
+  /*                                                                 */
+#ifndef FT_CALLBACK_DEF
+#ifdef __cplusplus
+#define FT_CALLBACK_DEF( x )  extern "C"  x
+#else
+#define FT_CALLBACK_DEF( x )  static  x
+#endif
+#endif /* FT_CALLBACK_DEF */
+
+#ifndef FT_CALLBACK_TABLE
+#ifdef __cplusplus
+#define FT_CALLBACK_TABLE      extern "C"
+#define FT_CALLBACK_TABLE_DEF  extern "C"
+#else
+#define FT_CALLBACK_TABLE      extern
+#define FT_CALLBACK_TABLE_DEF  /* nothing */
+#endif
+#endif /* FT_CALLBACK_TABLE */
+
+
+FT_END_HEADER
+
+
+#endif /* __FTCONFIG_H__ */
+
+
+/* END */

+ 729 - 0
include/freetype/config/ftheader.h

@@ -0,0 +1,729 @@
+/***************************************************************************/
+/*                                                                         */
+/*  ftheader.h                                                             */
+/*                                                                         */
+/*    Build macros of the FreeType 2 library.                              */
+/*                                                                         */
+/*  Copyright 1996-2001, 2002, 2003, 2004, 2005, 2006, 2007 by             */
+/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */
+/*                                                                         */
+/*  This file is part of the FreeType project, and may only be used,       */
+/*  modified, and distributed under the terms of the FreeType project      */
+/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */
+/*  this file you indicate that you have read the license and              */
+/*  understand and accept it fully.                                        */
+/*                                                                         */
+/***************************************************************************/
+
+#ifndef __FT_HEADER_H__
+#define __FT_HEADER_H__
+
+
+  /*@***********************************************************************/
+  /*                                                                       */
+  /* <Macro>                                                               */
+  /*    FT_BEGIN_HEADER                                                    */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    This macro is used in association with @FT_END_HEADER in header    */
+  /*    files to ensure that the declarations within are properly          */
+  /*    encapsulated in an `extern "C" { .. }' block when included from a  */
+  /*    C++ compiler.                                                      */
+  /*                                                                       */
+#ifdef __cplusplus
+#define FT_BEGIN_HEADER  extern "C" {
+#else
+#define FT_BEGIN_HEADER  /* nothing */
+#endif
+
+
+  /*@***********************************************************************/
+  /*                                                                       */
+  /* <Macro>                                                               */
+  /*    FT_END_HEADER                                                      */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    This macro is used in association with @FT_BEGIN_HEADER in header  */
+  /*    files to ensure that the declarations within are properly          */
+  /*    encapsulated in an `extern "C" { .. }' block when included from a  */
+  /*    C++ compiler.                                                      */
+  /*                                                                       */
+#ifdef __cplusplus
+#define FT_END_HEADER  }
+#else
+#define FT_END_HEADER  /* nothing */
+#endif
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* Aliases for the FreeType 2 public and configuration files.            */
+  /*                                                                       */
+  /*************************************************************************/
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Section>                                                             */
+  /*    header_file_macros                                                 */
+  /*                                                                       */
+  /* <Title>                                                               */
+  /*    Header File Macros                                                 */
+  /*                                                                       */
+  /* <Abstract>                                                            */
+  /*    Macro definitions used to #include specific header files.          */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    The following macros are defined to the name of specific           */
+  /*    FreeType 2 header files.  They can be used directly in #include    */
+  /*    statements as in:                                                  */
+  /*                                                                       */
+  /*    {                                                                  */
+  /*      #include FT_FREETYPE_H                                           */
+  /*      #include FT_MULTIPLE_MASTERS_H                                   */
+  /*      #include FT_GLYPH_H                                              */
+  /*    }                                                                  */
+  /*                                                                       */
+  /*    There are several reasons why we are now using macros to name      */
+  /*    public header files.  The first one is that such macros are not    */
+  /*    limited to the infamous 8.3 naming rule required by DOS (and       */
+  /*    `FT_MULTIPLE_MASTERS_H' is a lot more meaningful than `ftmm.h').   */
+  /*                                                                       */
+  /*    The second reason is that it allows for more flexibility in the    */
+  /*    way FreeType 2 is installed on a given system.                     */
+  /*                                                                       */
+  /*************************************************************************/
+
+
+  /* configuration files */
+
+  /*************************************************************************
+   *
+   * @macro:
+   *   FT_CONFIG_CONFIG_H
+   *
+   * @description:
+   *   A macro used in #include statements to name the file containing
+   *   FreeType 2 configuration data.
+   *
+   */
+#ifndef FT_CONFIG_CONFIG_H
+#define FT_CONFIG_CONFIG_H  <freetype/config/ftconfig.h>
+#endif
+
+
+  /*************************************************************************
+   *
+   * @macro:
+   *   FT_CONFIG_STANDARD_LIBRARY_H
+   *
+   * @description:
+   *   A macro used in #include statements to name the file containing
+   *   FreeType 2 interface to the standard C library functions.
+   *
+   */
+#ifndef FT_CONFIG_STANDARD_LIBRARY_H
+#define FT_CONFIG_STANDARD_LIBRARY_H  <freetype/config/ftstdlib.h>
+#endif
+
+
+  /*************************************************************************
+   *
+   * @macro:
+   *   FT_CONFIG_OPTIONS_H
+   *
+   * @description:
+   *   A macro used in #include statements to name the file containing
+   *   FreeType 2 project-specific configuration options.
+   *
+   */
+#ifndef FT_CONFIG_OPTIONS_H
+#define FT_CONFIG_OPTIONS_H  <freetype/config/ftoption.h>
+#endif
+
+
+  /*************************************************************************
+   *
+   * @macro:
+   *   FT_CONFIG_MODULES_H
+   *
+   * @description:
+   *   A macro used in #include statements to name the file containing the
+   *   list of FreeType 2 modules that are statically linked to new library
+   *   instances in @FT_Init_FreeType.
+   *
+   */
+#ifndef FT_CONFIG_MODULES_H
+#define FT_CONFIG_MODULES_H  <freetype/config/ftmodule.h>
+#endif
+
+
+  /* public headers */
+
+  /*************************************************************************
+   *
+   * @macro:
+   *   FT_FREETYPE_H
+   *
+   * @description:
+   *   A macro used in #include statements to name the file containing the
+   *   base FreeType 2 API.
+   *
+   */
+#define FT_FREETYPE_H  <freetype/freetype.h>
+
+
+  /*************************************************************************
+   *
+   * @macro:
+   *   FT_ERRORS_H
+   *
+   * @description:
+   *   A macro used in #include statements to name the file containing the
+   *   list of FreeType 2 error codes (and messages).
+   *
+   *   It is included by @FT_FREETYPE_H.
+   *
+   */
+#define FT_ERRORS_H  <freetype/fterrors.h>
+
+
+  /*************************************************************************
+   *
+   * @macro:
+   *   FT_MODULE_ERRORS_H
+   *
+   * @description:
+   *   A macro used in #include statements to name the file containing the
+   *   list of FreeType 2 module error offsets (and messages).
+   *
+   */
+#define FT_MODULE_ERRORS_H  <freetype/ftmoderr.h>
+
+
+  /*************************************************************************
+   *
+   * @macro:
+   *   FT_SYSTEM_H
+   *
+   * @description:
+   *   A macro used in #include statements to name the file containing the
+   *   FreeType 2 interface to low-level operations (i.e., memory management
+   *   and stream i/o).
+   *
+   *   It is included by @FT_FREETYPE_H.
+   *
+   */
+#define FT_SYSTEM_H  <freetype/ftsystem.h>
+
+
+  /*************************************************************************
+   *
+   * @macro:
+   *   FT_IMAGE_H
+   *
+   * @description:
+   *   A macro used in #include statements to name the file containing type
+   *   definitions related to glyph images (i.e., bitmaps, outlines,
+   *   scan-converter parameters).
+   *
+   *   It is included by @FT_FREETYPE_H.
+   *
+   */
+#define FT_IMAGE_H  <freetype/ftimage.h>
+
+
+  /*************************************************************************
+   *
+   * @macro:
+   *   FT_TYPES_H
+   *
+   * @description:
+   *   A macro used in #include statements to name the file containing the
+   *   basic data types defined by FreeType 2.
+   *
+   *   It is included by @FT_FREETYPE_H.
+   *
+   */
+#define FT_TYPES_H  <freetype/fttypes.h>
+
+
+  /*************************************************************************
+   *
+   * @macro:
+   *   FT_LIST_H
+   *
+   * @description:
+   *   A macro used in #include statements to name the file containing the
+   *   list management API of FreeType 2.
+   *
+   *   (Most applications will never need to include this file.)
+   *
+   */
+#define FT_LIST_H  <freetype/ftlist.h>
+
+
+  /*************************************************************************
+   *
+   * @macro:
+   *   FT_OUTLINE_H
+   *
+   * @description:
+   *   A macro used in #include statements to name the file containing the
+   *   scalable outline management API of FreeType 2.
+   *
+   */
+#define FT_OUTLINE_H  <freetype/ftoutln.h>
+
+
+  /*************************************************************************
+   *
+   * @macro:
+   *   FT_SIZES_H
+   *
+   * @description:
+   *   A macro used in #include statements to name the file containing the
+   *   API which manages multiple @FT_Size objects per face.
+   *
+   */
+#define FT_SIZES_H  <freetype/ftsizes.h>
+
+
+  /*************************************************************************
+   *
+   * @macro:
+   *   FT_MODULE_H
+   *
+   * @description:
+   *   A macro used in #include statements to name the file containing the
+   *   module management API of FreeType 2.
+   *
+   */
+#define FT_MODULE_H  <freetype/ftmodapi.h>
+
+
+  /*************************************************************************
+   *
+   * @macro:
+   *   FT_RENDER_H
+   *
+   * @description:
+   *   A macro used in #include statements to name the file containing the
+   *   renderer module management API of FreeType 2.
+   *
+   */
+#define FT_RENDER_H  <freetype/ftrender.h>
+
+
+  /*************************************************************************
+   *
+   * @macro:
+   *   FT_TYPE1_TABLES_H
+   *
+   * @description:
+   *   A macro used in #include statements to name the file containing the
+   *   types and API specific to the Type 1 format.
+   *
+   */
+#define FT_TYPE1_TABLES_H  <freetype/t1tables.h>
+
+
+  /*************************************************************************
+   *
+   * @macro:
+   *   FT_TRUETYPE_IDS_H
+   *
+   * @description:
+   *   A macro used in #include statements to name the file containing the
+   *   enumeration values which identify name strings, languages, encodings,
+   *   etc.  This file really contains a _large_ set of constant macro
+   *   definitions, taken from the TrueType and OpenType specifications.
+   *
+   */
+#define FT_TRUETYPE_IDS_H  <freetype/ttnameid.h>
+
+
+  /*************************************************************************
+   *
+   * @macro:
+   *   FT_TRUETYPE_TABLES_H
+   *
+   * @description:
+   *   A macro used in #include statements to name the file containing the
+   *   types and API specific to the TrueType (as well as OpenType) format.
+   *
+   */
+#define FT_TRUETYPE_TABLES_H  <freetype/tttables.h>
+
+
+  /*************************************************************************
+   *
+   * @macro:
+   *   FT_TRUETYPE_TAGS_H
+   *
+   * @description:
+   *   A macro used in #include statements to name the file containing the
+   *   definitions of TrueType four-byte `tags' which identify blocks in
+   *   SFNT-based font formats (i.e., TrueType and OpenType).
+   *
+   */
+#define FT_TRUETYPE_TAGS_H  <freetype/tttags.h>
+
+
+  /*************************************************************************
+   *
+   * @macro:
+   *   FT_BDF_H
+   *
+   * @description:
+   *   A macro used in #include statements to name the file containing the
+   *   definitions of an API which accesses BDF-specific strings from a
+   *   face.
+   *
+   */
+#define FT_BDF_H  <freetype/ftbdf.h>
+
+
+  /*************************************************************************
+   *
+   * @macro:
+   *   FT_GZIP_H
+   *
+   * @description:
+   *   A macro used in #include statements to name the file containing the
+   *   definitions of an API which supports gzip-compressed files.
+   *
+   */
+#define FT_GZIP_H  <freetype/ftgzip.h>
+
+
+  /*************************************************************************
+   *
+   * @macro:
+   *   FT_LZW_H
+   *
+   * @description:
+   *   A macro used in #include statements to name the file containing the
+   *   definitions of an API which supports LZW-compressed files.
+   *
+   */
+#define FT_LZW_H  <freetype/ftlzw.h>
+
+
+  /*************************************************************************
+   *
+   * @macro:
+   *   FT_WINFONTS_H
+   *
+   * @description:
+   *   A macro used in #include statements to name the file containing the
+   *   definitions of an API which supports Windows FNT files.
+   *
+   */
+#define FT_WINFONTS_H   <freetype/ftwinfnt.h>
+
+
+  /*************************************************************************
+   *
+   * @macro:
+   *   FT_GLYPH_H
+   *
+   * @description:
+   *   A macro used in #include statements to name the file containing the
+   *   API of the optional glyph management component.
+   *
+   */
+#define FT_GLYPH_H  <freetype/ftglyph.h>
+
+
+  /*************************************************************************
+   *
+   * @macro:
+   *   FT_BITMAP_H
+   *
+   * @description:
+   *   A macro used in #include statements to name the file containing the
+   *   API of the optional bitmap conversion component.
+   *
+   */
+#define FT_BITMAP_H  <freetype/ftbitmap.h>
+
+
+  /*************************************************************************
+   *
+   * @macro:
+   *   FT_BBOX_H
+   *
+   * @description:
+   *   A macro used in #include statements to name the file containing the
+   *   API of the optional exact bounding box computation routines.
+   *
+   */
+#define FT_BBOX_H  <freetype/ftbbox.h>
+
+
+  /*************************************************************************
+   *
+   * @macro:
+   *   FT_CACHE_H
+   *
+   * @description:
+   *   A macro used in #include statements to name the file containing the
+   *   API of the optional FreeType 2 cache sub-system.
+   *
+   */
+#define FT_CACHE_H  <freetype/ftcache.h>
+
+
+  /*************************************************************************
+   *
+   * @macro:
+   *   FT_CACHE_IMAGE_H
+   *
+   * @description:
+   *   A macro used in #include statements to name the file containing the
+   *   `glyph image' API of the FreeType 2 cache sub-system.
+   *
+   *   It is used to define a cache for @FT_Glyph elements.  You can also
+   *   use the API defined in @FT_CACHE_SMALL_BITMAPS_H if you only need to
+   *   store small glyph bitmaps, as it will use less memory.
+   *
+   *   This macro is deprecated.  Simply include @FT_CACHE_H to have all
+   *   glyph image-related cache declarations.
+   *
+   */
+#define FT_CACHE_IMAGE_H  FT_CACHE_H
+
+
+  /*************************************************************************
+   *
+   * @macro:
+   *   FT_CACHE_SMALL_BITMAPS_H
+   *
+   * @description:
+   *   A macro used in #include statements to name the file containing the
+   *   `small bitmaps' API of the FreeType 2 cache sub-system.
+   *
+   *   It is used to define a cache for small glyph bitmaps in a relatively
+   *   memory-efficient way.  You can also use the API defined in
+   *   @FT_CACHE_IMAGE_H if you want to cache arbitrary glyph images,
+   *   including scalable outlines.
+   *
+   *   This macro is deprecated.  Simply include @FT_CACHE_H to have all
+   *   small bitmaps-related cache declarations.
+   *
+   */
+#define FT_CACHE_SMALL_BITMAPS_H  FT_CACHE_H
+
+
+  /*************************************************************************
+   *
+   * @macro:
+   *   FT_CACHE_CHARMAP_H
+   *
+   * @description:
+   *   A macro used in #include statements to name the file containing the
+   *   `charmap' API of the FreeType 2 cache sub-system.
+   *
+   *   This macro is deprecated.  Simply include @FT_CACHE_H to have all
+   *   charmap-based cache declarations.
+   *
+   */
+#define FT_CACHE_CHARMAP_H  FT_CACHE_H
+
+
+  /*************************************************************************
+   *
+   * @macro:
+   *   FT_MAC_H
+   *
+   * @description:
+   *   A macro used in #include statements to name the file containing the
+   *   Macintosh-specific FreeType 2 API.  The latter is used to access
+   *   fonts embedded in resource forks.
+   *
+   *   This header file must be explicitly included by client applications
+   *   compiled on the Mac (note that the base API still works though).
+   *
+   */
+#define FT_MAC_H  <freetype/ftmac.h>
+
+
+  /*************************************************************************
+   *
+   * @macro:
+   *   FT_MULTIPLE_MASTERS_H
+   *
+   * @description:
+   *   A macro used in #include statements to name the file containing the
+   *   optional multiple-masters management API of FreeType 2.
+   *
+   */
+#define FT_MULTIPLE_MASTERS_H  <freetype/ftmm.h>
+
+
+  /*************************************************************************
+   *
+   * @macro:
+   *   FT_SFNT_NAMES_H
+   *
+   * @description:
+   *   A macro used in #include statements to name the file containing the
+   *   optional FreeType 2 API which accesses embedded `name' strings in
+   *   SFNT-based font formats (i.e., TrueType and OpenType).
+   *
+   */
+#define FT_SFNT_NAMES_H  <freetype/ftsnames.h>
+
+
+  /*************************************************************************
+   *
+   * @macro:
+   *   FT_OPENTYPE_VALIDATE_H
+   *
+   * @description:
+   *   A macro used in #include statements to name the file containing the
+   *   optional FreeType 2 API which validates OpenType tables (BASE, GDEF,
+   *   GPOS, GSUB, JSTF).
+   *
+   */
+#define FT_OPENTYPE_VALIDATE_H  <freetype/ftotval.h>
+
+
+  /*************************************************************************
+   *
+   * @macro:
+   *   FT_GX_VALIDATE_H
+   *
+   * @description:
+   *   A macro used in #include statements to name the file containing the
+   *   optional FreeType 2 API which validates TrueTypeGX/AAT tables (feat,
+   *   mort, morx, bsln, just, kern, opbd, trak, prop).
+   *
+   */
+#define FT_GX_VALIDATE_H  <freetype/ftgxval.h>
+
+
+  /*************************************************************************
+   *
+   * @macro:
+   *   FT_PFR_H
+   *
+   * @description:
+   *   A macro used in #include statements to name the file containing the
+   *   FreeType 2 API which accesses PFR-specific data.
+   *
+   */
+#define FT_PFR_H  <freetype/ftpfr.h>
+
+
+  /*************************************************************************
+   *
+   * @macro:
+   *   FT_STROKER_H
+   *
+   * @description:
+   *   A macro used in #include statements to name the file containing the
+   *   FreeType 2 API which provides functions to stroke outline paths.
+   */
+#define FT_STROKER_H  <freetype/ftstroke.h>
+
+
+  /*************************************************************************
+   *
+   * @macro:
+   *   FT_SYNTHESIS_H
+   *
+   * @description:
+   *   A macro used in #include statements to name the file containing the
+   *   FreeType 2 API which performs artificial obliquing and emboldening.
+   */
+#define FT_SYNTHESIS_H  <freetype/ftsynth.h>
+
+
+  /*************************************************************************
+   *
+   * @macro:
+   *   FT_XFREE86_H
+   *
+   * @description:
+   *   A macro used in #include statements to name the file containing the
+   *   FreeType 2 API which provides functions specific to the XFree86 and
+   *   X.Org X11 servers.
+   */
+#define FT_XFREE86_H  <freetype/ftxf86.h>
+
+
+  /*************************************************************************
+   *
+   * @macro:
+   *   FT_TRIGONOMETRY_H
+   *
+   * @description:
+   *   A macro used in #include statements to name the file containing the
+   *   FreeType 2 API which performs trigonometric computations (e.g.,
+   *   cosines and arc tangents).
+   */
+#define FT_TRIGONOMETRY_H  <freetype/fttrigon.h>
+
+
+  /*************************************************************************
+   *
+   * @macro:
+   *   FT_LCD_FILTER_H
+   *
+   * @description:
+   *   A macro used in #include statements to name the file containing the
+   *   FreeType 2 API which performs color filtering for subpixel rendering.
+   */
+#define FT_LCD_FILTER_H  <freetype/ftlcdfil.h>
+
+
+  /*************************************************************************
+   *
+   * @macro:
+   *   FT_GASP_H
+   *
+   * @description:
+   *   A macro used in #include statements to name the file containing the
+   *   FreeType 2 API which returns entries from the TrueType GASP table.
+   */
+#define FT_GASP_H  <freetype/ftgasp.h>
+
+
+  /* */
+
+#define FT_ERROR_DEFINITIONS_H  <freetype/fterrdef.h>
+
+
+  /* The internals of the cache sub-system are no longer exposed.  We */
+  /* default to FT_CACHE_H at the moment just in case, but we know of */
+  /* no rogue client that uses them.                                  */
+  /*                                                                  */
+#define FT_CACHE_MANAGER_H           <freetype/ftcache.h>
+#define FT_CACHE_INTERNAL_MRU_H      <freetype/ftcache.h>
+#define FT_CACHE_INTERNAL_MANAGER_H  <freetype/ftcache.h>
+#define FT_CACHE_INTERNAL_CACHE_H    <freetype/ftcache.h>
+#define FT_CACHE_INTERNAL_GLYPH_H    <freetype/ftcache.h>
+#define FT_CACHE_INTERNAL_IMAGE_H    <freetype/ftcache.h>
+#define FT_CACHE_INTERNAL_SBITS_H    <freetype/ftcache.h>
+
+
+#define FT_INCREMENTAL_H          <freetype/ftincrem.h>
+
+#define FT_TRUETYPE_UNPATENTED_H  <freetype/ttunpat.h>
+
+
+  /*
+   * Include internal headers definitions from <freetype/internal/...>
+   * only when building the library.
+   */
+#ifdef FT2_BUILD_LIBRARY
+#define  FT_INTERNAL_INTERNAL_H  <freetype/internal/internal.h>
+#include FT_INTERNAL_INTERNAL_H
+#endif /* FT2_BUILD_LIBRARY */
+
+
+#endif /* __FT2_BUILD_H__ */
+
+
+/* END */

+ 22 - 0
include/freetype/config/ftmodule.h

@@ -0,0 +1,22 @@
+/* This is a generated file. */
+FT_USE_MODULE(tt_driver_class)
+FT_USE_MODULE(t1_driver_class)
+FT_USE_MODULE(cff_driver_class)
+FT_USE_MODULE(t1cid_driver_class)
+FT_USE_MODULE(pfr_driver_class)
+FT_USE_MODULE(t42_driver_class)
+FT_USE_MODULE(winfnt_driver_class)
+FT_USE_MODULE(pcf_driver_class)
+FT_USE_MODULE(bdf_driver_class)
+FT_USE_MODULE(sfnt_module_class)
+FT_USE_MODULE(autofit_module_class)
+FT_USE_MODULE(pshinter_module_class)
+FT_USE_MODULE(ft_raster1_renderer_class)
+FT_USE_MODULE(ft_smooth_renderer_class)
+FT_USE_MODULE(ft_smooth_lcd_renderer_class)
+FT_USE_MODULE(ft_smooth_lcdv_renderer_class)
+FT_USE_MODULE(gxv_module_class)
+FT_USE_MODULE(otv_module_class)
+FT_USE_MODULE(psaux_module_class)
+FT_USE_MODULE(psnames_module_class)
+/* EOF */

+ 695 - 0
include/freetype/config/ftoption.h

@@ -0,0 +1,695 @@
+/***************************************************************************/
+/*                                                                         */
+/*  ftoption.h                                                             */
+/*                                                                         */
+/*    User-selectable configuration macros (specification only).           */
+/*                                                                         */
+/*  Copyright 1996-2001, 2002, 2003, 2004, 2005, 2006, 2007 by             */
+/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */
+/*                                                                         */
+/*  This file is part of the FreeType project, and may only be used,       */
+/*  modified, and distributed under the terms of the FreeType project      */
+/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */
+/*  this file you indicate that you have read the license and              */
+/*  understand and accept it fully.                                        */
+/*                                                                         */
+/***************************************************************************/
+
+
+#ifndef __FTOPTION_H__
+#define __FTOPTION_H__
+
+
+#include <ft2build.h>
+
+
+FT_BEGIN_HEADER
+
+  /*************************************************************************/
+  /*                                                                       */
+  /*                 USER-SELECTABLE CONFIGURATION MACROS                  */
+  /*                                                                       */
+  /* This file contains the default configuration macro definitions for    */
+  /* a standard build of the FreeType library.  There are three ways to    */
+  /* use this file to build project-specific versions of the library:      */
+  /*                                                                       */
+  /*  - You can modify this file by hand, but this is not recommended in   */
+  /*    cases where you would like to build several versions of the        */
+  /*    library from a single source directory.                            */
+  /*                                                                       */
+  /*  - You can put a copy of this file in your build directory, more      */
+  /*    precisely in `$BUILD/freetype/config/ftoption.h', where `$BUILD'   */
+  /*    is the name of a directory that is included _before_ the FreeType  */
+  /*    include path during compilation.                                   */
+  /*                                                                       */
+  /*    The default FreeType Makefiles and Jamfiles use the build          */
+  /*    directory `builds/<system>' by default, but you can easily change  */
+  /*    that for your own projects.                                        */
+  /*                                                                       */
+  /*  - Copy the file <ft2build.h> to `$BUILD/ft2build.h' and modify it    */
+  /*    slightly to pre-define the macro FT_CONFIG_OPTIONS_H used to       */
+  /*    locate this file during the build.  For example,                   */
+  /*                                                                       */
+  /*      #define FT_CONFIG_OPTIONS_H  <myftoptions.h>                     */
+  /*      #include <freetype/config/ftheader.h>                            */
+  /*                                                                       */
+  /*    will use `$BUILD/myftoptions.h' instead of this file for macro     */
+  /*    definitions.                                                       */
+  /*                                                                       */
+  /*    Note also that you can similarly pre-define the macro              */
+  /*    FT_CONFIG_MODULES_H used to locate the file listing of the modules */
+  /*    that are statically linked to the library at compile time.  By     */
+  /*    default, this file is <freetype/config/ftmodule.h>.                */
+  /*                                                                       */
+  /*  We highly recommend using the third method whenever possible.        */
+  /*                                                                       */
+  /*************************************************************************/
+
+
+  /*************************************************************************/
+  /*************************************************************************/
+  /****                                                                 ****/
+  /**** G E N E R A L   F R E E T Y P E   2   C O N F I G U R A T I O N ****/
+  /****                                                                 ****/
+  /*************************************************************************/
+  /*************************************************************************/
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* Uncomment the line below if you want to activate sub-pixel rendering  */
+  /* (a.k.a. LCD rendering, or ClearType) in this build of the library.    */
+  /*                                                                       */
+  /* Note that this feature is covered by several Microsoft patents        */
+  /* and should not be activated in any default build of the library.      */
+  /*                                                                       */
+  /* This macro has no impact on the FreeType API, only on its             */
+  /* _implementation_.  For example, using FT_RENDER_MODE_LCD when calling */
+  /* FT_Render_Glyph still generates a bitmap that is 3 times larger than  */
+  /* the original size; the difference will be that each triplet of        */
+  /* subpixels has R=G=B.                                                  */
+  /*                                                                       */
+  /* This is done to allow FreeType clients to run unmodified, forcing     */
+  /* them to display normal gray-level anti-aliased glyphs.                */
+  /*                                                                       */
+#define FT_CONFIG_OPTION_SUBPIXEL_RENDERING
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* Many compilers provide a non-ANSI 64-bit data type that can be used   */
+  /* by FreeType to speed up some computations.  However, this will create */
+  /* some problems when compiling the library in strict ANSI mode.         */
+  /*                                                                       */
+  /* For this reason, the use of 64-bit integers is normally disabled when */
+  /* the __STDC__ macro is defined.  You can however disable this by       */
+  /* defining the macro FT_CONFIG_OPTION_FORCE_INT64 here.                 */
+  /*                                                                       */
+  /* For most compilers, this will only create compilation warnings when   */
+  /* building the library.                                                 */
+  /*                                                                       */
+  /* ObNote: The compiler-specific 64-bit integers are detected in the     */
+  /*         file `ftconfig.h' either statically or through the            */
+  /*         `configure' script on supported platforms.                    */
+  /*                                                                       */
+#undef  FT_CONFIG_OPTION_FORCE_INT64
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* LZW-compressed file support.                                          */
+  /*                                                                       */
+  /*   FreeType now handles font files that have been compressed with the  */
+  /*   `compress' program.  This is mostly used to parse many of the PCF   */
+  /*   files that come with various X11 distributions.  The implementation */
+  /*   uses NetBSD's `zopen' to partially uncompress the file on the fly   */
+  /*   (see src/lzw/ftgzip.c).                                             */
+  /*                                                                       */
+  /*   Define this macro if you want to enable this `feature'.             */
+  /*                                                                       */
+#define FT_CONFIG_OPTION_USE_LZW
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* Gzip-compressed file support.                                         */
+  /*                                                                       */
+  /*   FreeType now handles font files that have been compressed with the  */
+  /*   `gzip' program.  This is mostly used to parse many of the PCF files */
+  /*   that come with XFree86.  The implementation uses `zlib' to          */
+  /*   partially uncompress the file on the fly (see src/gzip/ftgzip.c).   */
+  /*                                                                       */
+  /*   Define this macro if you want to enable this `feature'.  See also   */
+  /*   the macro FT_CONFIG_OPTION_SYSTEM_ZLIB below.                       */
+  /*                                                                       */
+#define FT_CONFIG_OPTION_USE_ZLIB
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* ZLib library selection                                                */
+  /*                                                                       */
+  /*   This macro is only used when FT_CONFIG_OPTION_USE_ZLIB is defined.  */
+  /*   It allows FreeType's `ftgzip' component to link to the system's     */
+  /*   installation of the ZLib library.  This is useful on systems like   */
+  /*   Unix or VMS where it generally is already available.                */
+  /*                                                                       */
+  /*   If you let it undefined, the component will use its own copy        */
+  /*   of the zlib sources instead.  These have been modified to be        */
+  /*   included directly within the component and *not* export external    */
+  /*   function names.  This allows you to link any program with FreeType  */
+  /*   _and_ ZLib without linking conflicts.                               */
+  /*                                                                       */
+  /*   Do not #undef this macro here since the build system might define   */
+  /*   it for certain configurations only.                                 */
+  /*                                                                       */
+/* #define  FT_CONFIG_OPTION_SYSTEM_ZLIB */
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* DLL export compilation                                                */
+  /*                                                                       */
+  /*   When compiling FreeType as a DLL, some systems/compilers need a     */
+  /*   special keyword in front OR after the return type of function       */
+  /*   declarations.                                                       */
+  /*                                                                       */
+  /*   Two macros are used within the FreeType source code to define       */
+  /*   exported library functions: FT_EXPORT and FT_EXPORT_DEF.            */
+  /*                                                                       */
+  /*     FT_EXPORT( return_type )                                          */
+  /*                                                                       */
+  /*       is used in a function declaration, as in                        */
+  /*                                                                       */
+  /*         FT_EXPORT( FT_Error )                                         */
+  /*         FT_Init_FreeType( FT_Library*  alibrary );                    */
+  /*                                                                       */
+  /*                                                                       */
+  /*     FT_EXPORT_DEF( return_type )                                      */
+  /*                                                                       */
+  /*       is used in a function definition, as in                         */
+  /*                                                                       */
+  /*         FT_EXPORT_DEF( FT_Error )                                     */
+  /*         FT_Init_FreeType( FT_Library*  alibrary )                     */
+  /*         {                                                             */
+  /*           ... some code ...                                           */
+  /*           return FT_Err_Ok;                                           */
+  /*         }                                                             */
+  /*                                                                       */
+  /*   You can provide your own implementation of FT_EXPORT and            */
+  /*   FT_EXPORT_DEF here if you want.  If you leave them undefined, they  */
+  /*   will be later automatically defined as `extern return_type' to      */
+  /*   allow normal compilation.                                           */
+  /*                                                                       */
+  /*   Do not #undef these macros here since the build system might define */
+  /*   them for certain configurations only.                               */
+  /*                                                                       */
+/* #define  FT_EXPORT(x)       extern x */
+/* #define  FT_EXPORT_DEF(x)   x */
+#ifndef __GNUC__
+# define __DLL_IMPORT__  __declspec(dllimport)
+# define __DLL_EXPORT__  __declspec(dllexport)
+#else
+# define __DLL_IMPORT__  __attribute__((dllimport)) extern
+# define __DLL_EXPORT__  __attribute__((dllexport)) extern
+#endif 
+
+#if (defined __WIN32__) || (defined _WIN32)
+# ifdef BUILD_FREETYPE2_DLL
+#  define FREETYPE2_DLL_IMPEXP     __DLL_EXPORT__
+# elif defined(FREETYPE2_STATIC)
+#  define FREETYPE2_DLL_IMPEXP      
+# elif defined (USE_FREETYPE2_DLL)
+#  define FREETYPE2_DLL_IMPEXP     __DLL_IMPORT__
+# elif defined (USE_FREETYPE2_STATIC)
+#  define FREETYPE2_DLL_IMPEXP      
+# else /* assume USE_FREETYPE2_DLL */
+#  define FREETYPE2_DLL_IMPEXP     __DLL_IMPORT__
+# endif
+#else /* __WIN32__ */
+# define FREETYPE2_DLL_IMPEXP  
+#endif
+ 
+#define FT_EXPORT(x)    FREETYPE2_DLL_IMPEXP x
+#define FT_BASE(x)      FREETYPE2_DLL_IMPEXP x
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* Glyph Postscript Names handling                                       */
+  /*                                                                       */
+  /*   By default, FreeType 2 is compiled with the `PSNames' module.  This */
+  /*   module is in charge of converting a glyph name string into a        */
+  /*   Unicode value, or return a Macintosh standard glyph name for the    */
+  /*   use with the TrueType `post' table.                                 */
+  /*                                                                       */
+  /*   Undefine this macro if you do not want `PSNames' compiled in your   */
+  /*   build of FreeType.  This has the following effects:                 */
+  /*                                                                       */
+  /*   - The TrueType driver will provide its own set of glyph names,      */
+  /*     if you build it to support postscript names in the TrueType       */
+  /*     `post' table.                                                     */
+  /*                                                                       */
+  /*   - The Type 1 driver will not be able to synthetize a Unicode        */
+  /*     charmap out of the glyphs found in the fonts.                     */
+  /*                                                                       */
+  /*   You would normally undefine this configuration macro when building  */
+  /*   a version of FreeType that doesn't contain a Type 1 or CFF driver.  */
+  /*                                                                       */
+#define FT_CONFIG_OPTION_POSTSCRIPT_NAMES
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* Postscript Names to Unicode Values support                            */
+  /*                                                                       */
+  /*   By default, FreeType 2 is built with the `PSNames' module compiled  */
+  /*   in.  Among other things, the module is used to convert a glyph name */
+  /*   into a Unicode value.  This is especially useful in order to        */
+  /*   synthetize on the fly a Unicode charmap from the CFF/Type 1 driver  */
+  /*   through a big table named the `Adobe Glyph List' (AGL).             */
+  /*                                                                       */
+  /*   Undefine this macro if you do not want the Adobe Glyph List         */
+  /*   compiled in your `PSNames' module.  The Type 1 driver will not be   */
+  /*   able to synthetize a Unicode charmap out of the glyphs found in the */
+  /*   fonts.                                                              */
+  /*                                                                       */
+#define FT_CONFIG_OPTION_ADOBE_GLYPH_LIST
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* Support for Mac fonts                                                 */
+  /*                                                                       */
+  /*   Define this macro if you want support for outline fonts in Mac      */
+  /*   format (mac dfont, mac resource, macbinary containing a mac         */
+  /*   resource) on non-Mac platforms.                                     */
+  /*                                                                       */
+  /*   Note that the `FOND' resource isn't checked.                        */
+  /*                                                                       */
+#define FT_CONFIG_OPTION_MAC_FONTS
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* Guessing methods to access embedded resource forks                    */
+  /*                                                                       */
+  /*   Enable extra Mac fonts support on non-Mac platforms (e.g.           */
+  /*   GNU/Linux).                                                         */
+  /*                                                                       */
+  /*   Resource forks which include fonts data are stored sometimes in     */
+  /*   locations which users or developers don't expected.  In some cases, */
+  /*   resource forks start with some offset from the head of a file.  In  */
+  /*   other cases, the actual resource fork is stored in file different   */
+  /*   from what the user specifies.  If this option is activated,         */
+  /*   FreeType tries to guess whether such offsets or different file      */
+  /*   names must be used.                                                 */
+  /*                                                                       */
+  /*   Note that normal, direct access of resource forks is controlled via */
+  /*   the FT_CONFIG_OPTION_MAC_FONTS option.                              */
+  /*                                                                       */
+#ifdef FT_CONFIG_OPTION_MAC_FONTS
+#define FT_CONFIG_OPTION_GUESSING_EMBEDDED_RFORK
+#endif
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* Allow the use of FT_Incremental_Interface to load typefaces that      */
+  /* contain no glyph data, but supply it via a callback function.         */
+  /* This allows FreeType to be used with the PostScript language, using   */
+  /* the GhostScript interpreter.                                          */
+  /*                                                                       */
+/* #define FT_CONFIG_OPTION_INCREMENTAL */
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* The size in bytes of the render pool used by the scan-line converter  */
+  /* to do all of its work.                                                */
+  /*                                                                       */
+  /* This must be greater than 4KByte if you use FreeType to rasterize     */
+  /* glyphs; otherwise, you may set it to zero to avoid unnecessary        */
+  /* allocation of the render pool.                                        */
+  /*                                                                       */
+#define FT_RENDER_POOL_SIZE  16384L
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* FT_MAX_MODULES                                                        */
+  /*                                                                       */
+  /*   The maximum number of modules that can be registered in a single    */
+  /*   FreeType library object.  32 is the default.                        */
+  /*                                                                       */
+#define FT_MAX_MODULES  32
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* Debug level                                                           */
+  /*                                                                       */
+  /*   FreeType can be compiled in debug or trace mode.  In debug mode,    */
+  /*   errors are reported through the `ftdebug' component.  In trace      */
+  /*   mode, additional messages are sent to the standard output during    */
+  /*   execution.                                                          */
+  /*                                                                       */
+  /*   Define FT_DEBUG_LEVEL_ERROR to build the library in debug mode.     */
+  /*   Define FT_DEBUG_LEVEL_TRACE to build it in trace mode.              */
+  /*                                                                       */
+  /*   Don't define any of these macros to compile in `release' mode!      */
+  /*                                                                       */
+  /*   Do not #undef these macros here since the build system might define */
+  /*   them for certain configurations only.                               */
+  /*                                                                       */
+/* #define FT_DEBUG_LEVEL_ERROR */
+/* #define FT_DEBUG_LEVEL_TRACE */
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* Memory Debugging                                                      */
+  /*                                                                       */
+  /*   FreeType now comes with an integrated memory debugger that is       */
+  /*   capable of detecting simple errors like memory leaks or double      */
+  /*   deletes.  To compile it within your build of the library, you       */
+  /*   should define FT_DEBUG_MEMORY here.                                 */
+  /*                                                                       */
+  /*   Note that the memory debugger is only activated at runtime when     */
+  /*   when the _environment_ variable `FT2_DEBUG_MEMORY' is defined also! */
+  /*                                                                       */
+  /*   Do not #undef this macro here since the build system might define   */
+  /*   it for certain configurations only.                                 */
+  /*                                                                       */
+/* #define FT_DEBUG_MEMORY */
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* Module errors                                                         */
+  /*                                                                       */
+  /*   If this macro is set (which is _not_ the default), the higher byte  */
+  /*   of an error code gives the module in which the error has occurred,  */
+  /*   while the lower byte is the real error code.                        */
+  /*                                                                       */
+  /*   Setting this macro makes sense for debugging purposes only, since   */
+  /*   it would break source compatibility of certain programs that use    */
+  /*   FreeType 2.                                                         */
+  /*                                                                       */
+  /*   More details can be found in the files ftmoderr.h and fterrors.h.   */
+  /*                                                                       */
+#undef FT_CONFIG_OPTION_USE_MODULE_ERRORS
+
+
+
+  /*************************************************************************/
+  /*************************************************************************/
+  /****                                                                 ****/
+  /****        S F N T   D R I V E R    C O N F I G U R A T I O N       ****/
+  /****                                                                 ****/
+  /*************************************************************************/
+  /*************************************************************************/
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* Define TT_CONFIG_OPTION_EMBEDDED_BITMAPS if you want to support       */
+  /* embedded bitmaps in all formats using the SFNT module (namely         */
+  /* TrueType & OpenType).                                                 */
+  /*                                                                       */
+#define TT_CONFIG_OPTION_EMBEDDED_BITMAPS
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* Define TT_CONFIG_OPTION_POSTSCRIPT_NAMES if you want to be able to    */
+  /* load and enumerate the glyph Postscript names in a TrueType or        */
+  /* OpenType file.                                                        */
+  /*                                                                       */
+  /* Note that when you do not compile the `PSNames' module by undefining  */
+  /* the above FT_CONFIG_OPTION_POSTSCRIPT_NAMES, the `sfnt' module will   */
+  /* contain additional code used to read the PS Names table from a font.  */
+  /*                                                                       */
+  /* (By default, the module uses `PSNames' to extract glyph names.)       */
+  /*                                                                       */
+#define TT_CONFIG_OPTION_POSTSCRIPT_NAMES
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* Define TT_CONFIG_OPTION_SFNT_NAMES if your applications need to       */
+  /* access the internal name table in a SFNT-based format like TrueType   */
+  /* or OpenType.  The name table contains various strings used to         */
+  /* describe the font, like family name, copyright, version, etc.  It     */
+  /* does not contain any glyph name though.                               */
+  /*                                                                       */
+  /* Accessing SFNT names is done through the functions declared in        */
+  /* `freetype/ftnames.h'.                                                 */
+  /*                                                                       */
+#define TT_CONFIG_OPTION_SFNT_NAMES
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* TrueType CMap support                                                 */
+  /*                                                                       */
+  /*   Here you can fine-tune which TrueType CMap table format shall be    */
+  /*   supported.                                                          */
+#define TT_CONFIG_CMAP_FORMAT_0
+#define TT_CONFIG_CMAP_FORMAT_2
+#define TT_CONFIG_CMAP_FORMAT_4
+#define TT_CONFIG_CMAP_FORMAT_6
+#define TT_CONFIG_CMAP_FORMAT_8
+#define TT_CONFIG_CMAP_FORMAT_10
+#define TT_CONFIG_CMAP_FORMAT_12
+
+
+  /*************************************************************************/
+  /*************************************************************************/
+  /****                                                                 ****/
+  /****    T R U E T Y P E   D R I V E R    C O N F I G U R A T I O N   ****/
+  /****                                                                 ****/
+  /*************************************************************************/
+  /*************************************************************************/
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* Define TT_CONFIG_OPTION_BYTECODE_INTERPRETER if you want to compile   */
+  /* a bytecode interpreter in the TrueType driver.  Note that there are   */
+  /* important patent issues related to the use of the interpreter.        */
+  /*                                                                       */
+  /* By undefining this, you will only compile the code necessary to load  */
+  /* TrueType glyphs without hinting.                                      */
+  /*                                                                       */
+  /*   Do not #undef this macro here, since the build system might         */
+  /*   define it for certain configurations only.                          */
+  /*                                                                       */
+/* #define TT_CONFIG_OPTION_BYTECODE_INTERPRETER */
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* If you define TT_CONFIG_OPTION_UNPATENTED_HINTING, a special version  */
+  /* of the TrueType bytecode interpreter is used that doesn't implement   */
+  /* any of the patented opcodes and algorithms.  Note that the            */
+  /* the TT_CONFIG_OPTION_UNPATENTED_HINTING macro is *ignored* if you     */
+  /* define TT_CONFIG_OPTION_BYTECODE_INTERPRETER; with other words,       */
+  /* either define TT_CONFIG_OPTION_BYTECODE_INTERPRETER or                */
+  /* TT_CONFIG_OPTION_UNPATENTED_HINTING but not both at the same time.    */
+  /*                                                                       */
+  /* This macro is only useful for a small number of font files (mostly    */
+  /* for Asian scripts) that require bytecode interpretation to properly   */
+  /* load glyphs.  For all other fonts, this produces unpleasant results,  */
+  /* thus the unpatented interpreter is never used to load glyphs from     */
+  /* TrueType fonts unless one of the following two options is used.       */
+  /*                                                                       */
+  /*   - The unpatented interpreter is explicitly activated by the user    */
+  /*     through the FT_PARAM_TAG_UNPATENTED_HINTING parameter tag         */
+  /*     when opening the FT_Face.                                         */
+  /*                                                                       */
+  /*   - FreeType detects that the FT_Face corresponds to one of the       */
+  /*     `trick' fonts (e.g., `Mingliu') it knows about.  The font engine  */
+  /*     contains a hard-coded list of font names and other matching       */
+  /*     parameters (see function `tt_face_init' in file                   */
+  /*     `src/truetype/ttobjs.c').                                         */
+  /*                                                                       */
+  /* Here a sample code snippet for using FT_PARAM_TAG_UNPATENTED_HINTING. */
+  /*                                                                       */
+  /*   {                                                                   */
+  /*     FT_Parameter  parameter;                                          */
+  /*     FT_Open_Args  open_args;                                          */
+  /*                                                                       */
+  /*                                                                       */
+  /*     parameter.tag = FT_PARAM_TAG_UNPATENTED_HINTING;                  */
+  /*                                                                       */
+  /*     open_args.flags      = FT_OPEN_PATHNAME | FT_OPEN_PARAMS;         */
+  /*     open_args.pathname   = my_font_pathname;                          */
+  /*     open_args.num_params = 1;                                         */
+  /*     open_args.params     = &parameter;                                */
+  /*                                                                       */
+  /*     error = FT_Open_Face( library, &open_args, index, &face );        */
+  /*     ...                                                               */
+  /*   }                                                                   */
+  /*                                                                       */
+#define TT_CONFIG_OPTION_UNPATENTED_HINTING
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* Define TT_CONFIG_OPTION_INTERPRETER_SWITCH to compile the TrueType    */
+  /* bytecode interpreter with a huge switch statement, rather than a call */
+  /* table.  This results in smaller and faster code for a number of       */
+  /* architectures.                                                        */
+  /*                                                                       */
+  /* Note however that on some compiler/processor combinations, undefining */
+  /* this macro will generate faster, though larger, code.                 */
+  /*                                                                       */
+#define TT_CONFIG_OPTION_INTERPRETER_SWITCH
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* Define TT_CONFIG_OPTION_COMPONENT_OFFSET_SCALED to compile the        */
+  /* TrueType glyph loader to use Apple's definition of how to handle      */
+  /* component offsets in composite glyphs.                                */
+  /*                                                                       */
+  /* Apple and MS disagree on the default behavior of component offsets    */
+  /* in composites.  Apple says that they should be scaled by the scaling  */
+  /* factors in the transformation matrix (roughly, it's more complex)     */
+  /* while MS says they should not.  OpenType defines two bits in the      */
+  /* composite flags array which can be used to disambiguate, but old      */
+  /* fonts will not have them.                                             */
+  /*                                                                       */
+  /*   http://partners.adobe.com/asn/developer/opentype/glyf.html          */
+  /*   http://fonts.apple.com/TTRefMan/RM06/Chap6glyf.html                 */
+  /*                                                                       */
+#undef TT_CONFIG_OPTION_COMPONENT_OFFSET_SCALED
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* Define TT_CONFIG_OPTION_GX_VAR_SUPPORT if you want to include         */
+  /* support for Apple's distortable font technology (fvar, gvar, cvar,    */
+  /* and avar tables).  This has many similarities to Type 1 Multiple      */
+  /* Masters support.                                                      */
+  /*                                                                       */
+#define TT_CONFIG_OPTION_GX_VAR_SUPPORT
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* Define TT_CONFIG_OPTION_BDF if you want to include support for        */
+  /* an embedded `BDF ' table within SFNT-based bitmap formats.            */
+  /*                                                                       */
+#define TT_CONFIG_OPTION_BDF
+
+
+  /*************************************************************************/
+  /*************************************************************************/
+  /****                                                                 ****/
+  /****      T Y P E 1   D R I V E R    C O N F I G U R A T I O N       ****/
+  /****                                                                 ****/
+  /*************************************************************************/
+  /*************************************************************************/
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* T1_MAX_DICT_DEPTH is the maximal depth of nest dictionaries and       */
+  /* arrays in the Type 1 stream (see t1load.c).  A minimum of 4 is        */
+  /* required.                                                             */
+  /*                                                                       */
+#define T1_MAX_DICT_DEPTH  5
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* T1_MAX_SUBRS_CALLS details the maximum number of nested sub-routine   */
+  /* calls during glyph loading.                                           */
+  /*                                                                       */
+#define T1_MAX_SUBRS_CALLS  16
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* T1_MAX_CHARSTRING_OPERANDS is the charstring stack's capacity.  A     */
+  /* minimum of 16 is required.                                            */
+  /*                                                                       */
+  /* The Chinese font MingTiEG-Medium (CNS 11643 character set) needs 256. */
+  /*                                                                       */
+#define T1_MAX_CHARSTRINGS_OPERANDS  256
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* Define this configuration macro if you want to prevent the            */
+  /* compilation of `t1afm', which is in charge of reading Type 1 AFM      */
+  /* files into an existing face.  Note that if set, the T1 driver will be */
+  /* unable to produce kerning distances.                                  */
+  /*                                                                       */
+#undef T1_CONFIG_OPTION_NO_AFM
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* Define this configuration macro if you want to prevent the            */
+  /* compilation of the Multiple Masters font support in the Type 1        */
+  /* driver.                                                               */
+  /*                                                                       */
+#undef T1_CONFIG_OPTION_NO_MM_SUPPORT
+
+
+  /*************************************************************************/
+  /*************************************************************************/
+  /****                                                                 ****/
+  /****    A U T O F I T   M O D U L E    C O N F I G U R A T I O N     ****/
+  /****                                                                 ****/
+  /*************************************************************************/
+  /*************************************************************************/
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* Compile autofit module with CJK script support.                       */
+  /*                                                                       */
+#define AF_CONFIG_OPTION_CJK
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* Compile autofit module with Indic script support.                     */
+  /*                                                                       */
+#define AF_CONFIG_OPTION_INDIC
+
+  /* */
+
+
+  /*
+   * Define this variable if you want to keep the layout of internal
+   * structures that was used prior to FreeType 2.2.  This also compiles in
+   * a few obsolete functions to avoid linking problems on typical Unix
+   * distributions.
+   *
+   * For embedded systems or building a new distribution from scratch, it
+   * is recommended to disable the macro since it reduces the library's code
+   * size and activates a few memory-saving optimizations as well.
+   */
+/* #define FT_CONFIG_OPTION_OLD_INTERNALS */
+
+
+  /*
+   * This variable is defined if either unpatented or native TrueType
+   * hinting is requested by the definitions above.
+   */
+#ifdef TT_CONFIG_OPTION_BYTECODE_INTERPRETER
+#define  TT_USE_BYTECODE_INTERPRETER
+#elif defined TT_CONFIG_OPTION_UNPATENTED_HINTING
+#define  TT_USE_BYTECODE_INTERPRETER
+#endif
+
+FT_END_HEADER
+
+
+#endif /* __FTOPTION_H__ */
+
+
+/* END */

+ 180 - 0
include/freetype/config/ftstdlib.h

@@ -0,0 +1,180 @@
+/***************************************************************************/
+/*                                                                         */
+/*  ftstdlib.h                                                             */
+/*                                                                         */
+/*    ANSI-specific library and header configuration file (specification   */
+/*    only).                                                               */
+/*                                                                         */
+/*  Copyright 2002, 2003, 2004, 2005, 2006, 2007 by                        */
+/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */
+/*                                                                         */
+/*  This file is part of the FreeType project, and may only be used,       */
+/*  modified, and distributed under the terms of the FreeType project      */
+/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */
+/*  this file you indicate that you have read the license and              */
+/*  understand and accept it fully.                                        */
+/*                                                                         */
+/***************************************************************************/
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* This file is used to group all #includes to the ANSI C library that   */
+  /* FreeType normally requires.  It also defines macros to rename the     */
+  /* standard functions within the FreeType source code.                   */
+  /*                                                                       */
+  /* Load a file which defines __FTSTDLIB_H__ before this one to override  */
+  /* it.                                                                   */
+  /*                                                                       */
+  /*************************************************************************/
+
+
+#ifndef __FTSTDLIB_H__
+#define __FTSTDLIB_H__
+
+
+#include <stddef.h>
+
+#define ft_ptrdiff_t  ptrdiff_t
+
+
+  /**********************************************************************/
+  /*                                                                    */
+  /*                           integer limits                           */
+  /*                                                                    */
+  /* UINT_MAX and ULONG_MAX are used to automatically compute the size  */
+  /* of `int' and `long' in bytes at compile-time.  So far, this works  */
+  /* for all platforms the library has been tested on.                  */
+  /*                                                                    */
+  /* Note that on the extremely rare platforms that do not provide      */
+  /* integer types that are _exactly_ 16 and 32 bits wide (e.g. some    */
+  /* old Crays where `int' is 36 bits), we do not make any guarantee    */
+  /* about the correct behaviour of FT2 with all fonts.                 */
+  /*                                                                    */
+  /* In these case, `ftconfig.h' will refuse to compile anyway with a   */
+  /* message like `couldn't find 32-bit type' or something similar.     */
+  /*                                                                    */
+  /* IMPORTANT NOTE: We do not define aliases for heap management and   */
+  /*                 i/o routines (i.e. malloc/free/fopen/fread/...)    */
+  /*                 since these functions should all be encapsulated   */
+  /*                 by platform-specific implementations of            */
+  /*                 `ftsystem.c'.                                      */
+  /*                                                                    */
+  /**********************************************************************/
+
+
+#include <limits.h>
+
+#define FT_CHAR_BIT   CHAR_BIT
+#define FT_INT_MAX    INT_MAX
+#define FT_UINT_MAX   UINT_MAX
+#define FT_ULONG_MAX  ULONG_MAX
+
+
+  /**********************************************************************/
+  /*                                                                    */
+  /*                 character and string processing                    */
+  /*                                                                    */
+  /**********************************************************************/
+
+
+#include <string.h>
+
+#define ft_memchr   memchr
+#define ft_memcmp   memcmp
+#define ft_memcpy   memcpy
+#define ft_memmove  memmove
+#define ft_memset   memset
+#define ft_strcat   strcat
+#define ft_strcmp   strcmp
+#define ft_strcpy   strcpy
+#define ft_strlen   strlen
+#define ft_strncmp  strncmp
+#define ft_strncpy  strncpy
+#define ft_strrchr  strrchr
+#define ft_strstr   strstr
+
+
+  /**********************************************************************/
+  /*                                                                    */
+  /*                           file handling                            */
+  /*                                                                    */
+  /**********************************************************************/
+
+
+#include <stdio.h>
+
+#define FT_FILE     FILE
+#define ft_fclose   fclose
+#define ft_fopen    fopen
+#define ft_fread    fread
+#define ft_fseek    fseek
+#define ft_ftell    ftell
+#define ft_sprintf  sprintf
+
+
+  /**********************************************************************/
+  /*                                                                    */
+  /*                             sorting                                */
+  /*                                                                    */
+  /**********************************************************************/
+
+
+#include <stdlib.h>
+
+#define ft_qsort  qsort
+
+#define ft_exit   exit    /* only used to exit from unhandled exceptions */
+
+
+  /**********************************************************************/
+  /*                                                                    */
+  /*                        memory allocation                           */
+  /*                                                                    */
+  /**********************************************************************/
+
+
+#define ft_scalloc   calloc
+#define ft_sfree     free
+#define ft_smalloc   malloc
+#define ft_srealloc  realloc
+
+
+  /**********************************************************************/
+  /*                                                                    */
+  /*                          miscellaneous                             */
+  /*                                                                    */
+  /**********************************************************************/
+
+
+#define ft_atol   atol
+#define ft_labs   labs
+
+
+  /**********************************************************************/
+  /*                                                                    */
+  /*                         execution control                          */
+  /*                                                                    */
+  /**********************************************************************/
+
+
+#include <setjmp.h>
+
+#define ft_jmp_buf     jmp_buf  /* note: this cannot be a typedef since */
+                                /*       jmp_buf is defined as a macro  */
+                                /*       on certain platforms           */
+
+#define ft_longjmp     longjmp
+#define ft_setjmp( b ) setjmp( *(jmp_buf*) &(b) )    /* same thing here */
+
+
+  /* the following is only used for debugging purposes, i.e., if */
+  /* FT_DEBUG_LEVEL_ERROR or FT_DEBUG_LEVEL_TRACE are defined    */
+
+#include <stdarg.h>
+
+
+#endif /* __FTSTDLIB_H__ */
+
+
+/* END */

+ 3434 - 0
include/freetype/freetype.h

@@ -0,0 +1,3434 @@
+/***************************************************************************/
+/*                                                                         */
+/*  freetype.h                                                             */
+/*                                                                         */
+/*    FreeType high-level API and common types (specification only).       */
+/*                                                                         */
+/*  Copyright 1996-2001, 2002, 2003, 2004, 2005, 2006, 2007 by             */
+/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */
+/*                                                                         */
+/*  This file is part of the FreeType project, and may only be used,       */
+/*  modified, and distributed under the terms of the FreeType project      */
+/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */
+/*  this file you indicate that you have read the license and              */
+/*  understand and accept it fully.                                        */
+/*                                                                         */
+/***************************************************************************/
+
+
+#ifndef FT_FREETYPE_H
+#error "`ft2build.h' hasn't been included yet!"
+#error "Please always use macros to include FreeType header files."
+#error "Example:"
+#error "  #include <ft2build.h>"
+#error "  #include FT_FREETYPE_H"
+#endif
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* The `raster' component duplicates some of the declarations in         */
+  /* freetype.h for stand-alone use if _FREETYPE_ isn't defined.           */
+  /*                                                                       */
+  /*************************************************************************/
+
+
+#ifndef __FREETYPE_H__
+#define __FREETYPE_H__
+
+
+#include <ft2build.h>
+#include FT_CONFIG_CONFIG_H
+#include FT_ERRORS_H
+#include FT_TYPES_H
+
+
+FT_BEGIN_HEADER
+
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Section>                                                             */
+  /*    user_allocation                                                    */
+  /*                                                                       */
+  /* <Title>                                                               */
+  /*    User allocation                                                    */
+  /*                                                                       */
+  /* <Abstract>                                                            */
+  /*    How client applications should allocate FreeType data structures.  */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    FreeType assumes that structures allocated by the user and passed  */
+  /*    as arguments are zeroed out except for the actual data.  With      */
+  /*    other words, it is recommended to use `calloc' (or variants of it) */
+  /*    instead of `malloc' for allocation.                                */
+  /*                                                                       */
+  /*************************************************************************/
+
+
+
+  /*************************************************************************/
+  /*************************************************************************/
+  /*                                                                       */
+  /*                        B A S I C   T Y P E S                          */
+  /*                                                                       */
+  /*************************************************************************/
+  /*************************************************************************/
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Section>                                                             */
+  /*    base_interface                                                     */
+  /*                                                                       */
+  /* <Title>                                                               */
+  /*    Base Interface                                                     */
+  /*                                                                       */
+  /* <Abstract>                                                            */
+  /*    The FreeType 2 base font interface.                                */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    This section describes the public high-level API of FreeType 2.    */
+  /*                                                                       */
+  /* <Order>                                                               */
+  /*    FT_Library                                                         */
+  /*    FT_Face                                                            */
+  /*    FT_Size                                                            */
+  /*    FT_GlyphSlot                                                       */
+  /*    FT_CharMap                                                         */
+  /*    FT_Encoding                                                        */
+  /*                                                                       */
+  /*    FT_FaceRec                                                         */
+  /*                                                                       */
+  /*    FT_FACE_FLAG_SCALABLE                                              */
+  /*    FT_FACE_FLAG_FIXED_SIZES                                           */
+  /*    FT_FACE_FLAG_FIXED_WIDTH                                           */
+  /*    FT_FACE_FLAG_HORIZONTAL                                            */
+  /*    FT_FACE_FLAG_VERTICAL                                              */
+  /*    FT_FACE_FLAG_SFNT                                                  */
+  /*    FT_FACE_FLAG_KERNING                                               */
+  /*    FT_FACE_FLAG_MULTIPLE_MASTERS                                      */
+  /*    FT_FACE_FLAG_GLYPH_NAMES                                           */
+  /*    FT_FACE_FLAG_EXTERNAL_STREAM                                       */
+  /*    FT_FACE_FLAG_FAST_GLYPHS                                           */
+  /*    FT_FACE_FLAG_HINTER                                                */
+  /*                                                                       */
+  /*    FT_STYLE_FLAG_BOLD                                                 */
+  /*    FT_STYLE_FLAG_ITALIC                                               */
+  /*                                                                       */
+  /*    FT_SizeRec                                                         */
+  /*    FT_Size_Metrics                                                    */
+  /*                                                                       */
+  /*    FT_GlyphSlotRec                                                    */
+  /*    FT_Glyph_Metrics                                                   */
+  /*    FT_SubGlyph                                                        */
+  /*                                                                       */
+  /*    FT_Bitmap_Size                                                     */
+  /*                                                                       */
+  /*    FT_Init_FreeType                                                   */
+  /*    FT_Done_FreeType                                                   */
+  /*                                                                       */
+  /*    FT_New_Face                                                        */
+  /*    FT_Done_Face                                                       */
+  /*    FT_New_Memory_Face                                                 */
+  /*    FT_Open_Face                                                       */
+  /*    FT_Open_Args                                                       */
+  /*    FT_Parameter                                                       */
+  /*    FT_Attach_File                                                     */
+  /*    FT_Attach_Stream                                                   */
+  /*                                                                       */
+  /*    FT_Set_Char_Size                                                   */
+  /*    FT_Set_Pixel_Sizes                                                 */
+  /*    FT_Request_Size                                                    */
+  /*    FT_Select_Size                                                     */
+  /*    FT_Size_Request_Type                                               */
+  /*    FT_Size_Request                                                    */
+  /*    FT_Set_Transform                                                   */
+  /*    FT_Load_Glyph                                                      */
+  /*    FT_Get_Char_Index                                                  */
+  /*    FT_Get_Name_Index                                                  */
+  /*    FT_Load_Char                                                       */
+  /*                                                                       */
+  /*    FT_OPEN_MEMORY                                                     */
+  /*    FT_OPEN_STREAM                                                     */
+  /*    FT_OPEN_PATHNAME                                                   */
+  /*    FT_OPEN_DRIVER                                                     */
+  /*    FT_OPEN_PARAMS                                                     */
+  /*                                                                       */
+  /*    FT_LOAD_DEFAULT                                                    */
+  /*    FT_LOAD_RENDER                                                     */
+  /*    FT_LOAD_MONOCHROME                                                 */
+  /*    FT_LOAD_LINEAR_DESIGN                                              */
+  /*    FT_LOAD_NO_SCALE                                                   */
+  /*    FT_LOAD_NO_HINTING                                                 */
+  /*    FT_LOAD_NO_BITMAP                                                  */
+  /*    FT_LOAD_CROP_BITMAP                                                */
+  /*                                                                       */
+  /*    FT_LOAD_VERTICAL_LAYOUT                                            */
+  /*    FT_LOAD_IGNORE_TRANSFORM                                           */
+  /*    FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH                                */
+  /*    FT_LOAD_FORCE_AUTOHINT                                             */
+  /*    FT_LOAD_NO_RECURSE                                                 */
+  /*    FT_LOAD_PEDANTIC                                                   */
+  /*                                                                       */
+  /*    FT_LOAD_TARGET_NORMAL                                              */
+  /*    FT_LOAD_TARGET_LIGHT                                               */
+  /*    FT_LOAD_TARGET_MONO                                                */
+  /*    FT_LOAD_TARGET_LCD                                                 */
+  /*    FT_LOAD_TARGET_LCD_V                                               */
+  /*                                                                       */
+  /*    FT_Render_Glyph                                                    */
+  /*    FT_Render_Mode                                                     */
+  /*    FT_Get_Kerning                                                     */
+  /*    FT_Kerning_Mode                                                    */
+  /*    FT_Get_Track_Kerning                                               */
+  /*    FT_Get_Glyph_Name                                                  */
+  /*    FT_Get_Postscript_Name                                             */
+  /*                                                                       */
+  /*    FT_CharMapRec                                                      */
+  /*    FT_Select_Charmap                                                  */
+  /*    FT_Set_Charmap                                                     */
+  /*    FT_Get_Charmap_Index                                               */
+  /*                                                                       */
+  /*************************************************************************/
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Struct>                                                              */
+  /*    FT_Glyph_Metrics                                                   */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    A structure used to model the metrics of a single glyph.  The      */
+  /*    values are expressed in 26.6 fractional pixel format; if the flag  */
+  /*    @FT_LOAD_NO_SCALE has been used while loading the glyph, values    */
+  /*    are expressed in font units instead.                               */
+  /*                                                                       */
+  /* <Fields>                                                              */
+  /*    width ::                                                           */
+  /*      The glyph's width.                                               */
+  /*                                                                       */
+  /*    height ::                                                          */
+  /*      The glyph's height.                                              */
+  /*                                                                       */
+  /*    horiBearingX ::                                                    */
+  /*      Left side bearing for horizontal layout.                         */
+  /*                                                                       */
+  /*    horiBearingY ::                                                    */
+  /*      Top side bearing for horizontal layout.                          */
+  /*                                                                       */
+  /*    horiAdvance ::                                                     */
+  /*      Advance width for horizontal layout.                             */
+  /*                                                                       */
+  /*    vertBearingX ::                                                    */
+  /*      Left side bearing for vertical layout.                           */
+  /*                                                                       */
+  /*    vertBearingY ::                                                    */
+  /*      Top side bearing for vertical layout.                            */
+  /*                                                                       */
+  /*    vertAdvance ::                                                     */
+  /*      Advance height for vertical layout.                              */
+  /*                                                                       */
+  typedef struct  FT_Glyph_Metrics_
+  {
+    FT_Pos  width;
+    FT_Pos  height;
+
+    FT_Pos  horiBearingX;
+    FT_Pos  horiBearingY;
+    FT_Pos  horiAdvance;
+
+    FT_Pos  vertBearingX;
+    FT_Pos  vertBearingY;
+    FT_Pos  vertAdvance;
+
+  } FT_Glyph_Metrics;
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Struct>                                                              */
+  /*    FT_Bitmap_Size                                                     */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    This structure models the metrics of a bitmap strike (i.e., a set  */
+  /*    of glyphs for a given point size and resolution) in a bitmap font. */
+  /*    It is used for the `available_sizes' field of @FT_Face.            */
+  /*                                                                       */
+  /* <Fields>                                                              */
+  /*    height :: The vertical distance, in pixels, between two            */
+  /*              consecutive baselines.  It is always positive.           */
+  /*                                                                       */
+  /*    width  :: The average width, in pixels, of all glyphs in the       */
+  /*              strike.                                                  */
+  /*                                                                       */
+  /*    size   :: The nominal size of the strike in 26.6 fractional        */
+  /*              points.  This field is not very useful.                  */
+  /*                                                                       */
+  /*    x_ppem :: The horizontal ppem (nominal width) in 26.6 fractional   */
+  /*              pixels.                                                  */
+  /*                                                                       */
+  /*    y_ppem :: The vertical ppem (nominal height) in 26.6 fractional    */
+  /*              pixels.                                                  */
+  /*                                                                       */
+  /* <Note>                                                                */
+  /*    Windows FNT:                                                       */
+  /*      The nominal size given in a FNT font is not reliable.  Thus when */
+  /*      the driver finds it incorrect, it sets `size' to some calculated */
+  /*      values and sets `x_ppem' and `y_ppem' to the pixel width and     */
+  /*      height given in the font, respectively.                          */
+  /*                                                                       */
+  /*    TrueType embedded bitmaps:                                         */
+  /*      `size', `width', and `height' values are not contained in the    */
+  /*      bitmap strike itself.  They are computed from the global font    */
+  /*      parameters.                                                      */
+  /*                                                                       */
+  typedef struct  FT_Bitmap_Size_
+  {
+    FT_Short  height;
+    FT_Short  width;
+
+    FT_Pos    size;
+
+    FT_Pos    x_ppem;
+    FT_Pos    y_ppem;
+
+  } FT_Bitmap_Size;
+
+
+  /*************************************************************************/
+  /*************************************************************************/
+  /*                                                                       */
+  /*                     O B J E C T   C L A S S E S                       */
+  /*                                                                       */
+  /*************************************************************************/
+  /*************************************************************************/
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Type>                                                                */
+  /*    FT_Library                                                         */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    A handle to a FreeType library instance.  Each `library' is        */
+  /*    completely independent from the others; it is the `root' of a set  */
+  /*    of objects like fonts, faces, sizes, etc.                          */
+  /*                                                                       */
+  /*    It also embeds a memory manager (see @FT_Memory), as well as a     */
+  /*    scan-line converter object (see @FT_Raster).                       */
+  /*                                                                       */
+  /*    For multi-threading applications each thread should have its own   */
+  /*    FT_Library object.                                                 */
+  /*                                                                       */
+  /* <Note>                                                                */
+  /*    Library objects are normally created by @FT_Init_FreeType, and     */
+  /*    destroyed with @FT_Done_FreeType.                                  */
+  /*                                                                       */
+  typedef struct FT_LibraryRec_  *FT_Library;
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Type>                                                                */
+  /*    FT_Module                                                          */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    A handle to a given FreeType module object.  Each module can be a  */
+  /*    font driver, a renderer, or anything else that provides services   */
+  /*    to the formers.                                                    */
+  /*                                                                       */
+  typedef struct FT_ModuleRec_*  FT_Module;
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Type>                                                                */
+  /*    FT_Driver                                                          */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    A handle to a given FreeType font driver object.  Each font driver */
+  /*    is a special module capable of creating faces from font files.     */
+  /*                                                                       */
+  typedef struct FT_DriverRec_*  FT_Driver;
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Type>                                                                */
+  /*    FT_Renderer                                                        */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    A handle to a given FreeType renderer.  A renderer is a special    */
+  /*    module in charge of converting a glyph image to a bitmap, when     */
+  /*    necessary.  Each renderer supports a given glyph image format, and */
+  /*    one or more target surface depths.                                 */
+  /*                                                                       */
+  typedef struct FT_RendererRec_*  FT_Renderer;
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Type>                                                                */
+  /*    FT_Face                                                            */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    A handle to a given typographic face object.  A face object models */
+  /*    a given typeface, in a given style.                                */
+  /*                                                                       */
+  /* <Note>                                                                */
+  /*    Each face object also owns a single @FT_GlyphSlot object, as well  */
+  /*    as one or more @FT_Size objects.                                   */
+  /*                                                                       */
+  /*    Use @FT_New_Face or @FT_Open_Face to create a new face object from */
+  /*    a given filepathname or a custom input stream.                     */
+  /*                                                                       */
+  /*    Use @FT_Done_Face to destroy it (along with its slot and sizes).   */
+  /*                                                                       */
+  /* <Also>                                                                */
+  /*    The @FT_FaceRec details the publicly accessible fields of a given  */
+  /*    face object.                                                       */
+  /*                                                                       */
+  typedef struct FT_FaceRec_*  FT_Face;
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Type>                                                                */
+  /*    FT_Size                                                            */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    A handle to an object used to model a face scaled to a given       */
+  /*    character size.                                                    */
+  /*                                                                       */
+  /* <Note>                                                                */
+  /*    Each @FT_Face has an _active_ @FT_Size object that is used by      */
+  /*    functions like @FT_Load_Glyph to determine the scaling             */
+  /*    transformation which is used to load and hint glyphs and metrics.  */
+  /*                                                                       */
+  /*    You can use @FT_Set_Char_Size, @FT_Set_Pixel_Sizes,                */
+  /*    @FT_Request_Size or even @FT_Select_Size to change the content     */
+  /*    (i.e., the scaling values) of the active @FT_Size.                 */
+  /*                                                                       */
+  /*    You can use @FT_New_Size to create additional size objects for a   */
+  /*    given @FT_Face, but they won't be used by other functions until    */
+  /*    you activate it through @FT_Activate_Size.  Only one size can be   */
+  /*    activated at any given time per face.                              */
+  /*                                                                       */
+  /* <Also>                                                                */
+  /*    The @FT_SizeRec structure details the publicly accessible fields   */
+  /*    of a given size object.                                            */
+  /*                                                                       */
+  typedef struct FT_SizeRec_*  FT_Size;
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Type>                                                                */
+  /*    FT_GlyphSlot                                                       */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    A handle to a given `glyph slot'.  A slot is a container where it  */
+  /*    is possible to load any one of the glyphs contained in its parent  */
+  /*    face.                                                              */
+  /*                                                                       */
+  /*    In other words, each time you call @FT_Load_Glyph or               */
+  /*    @FT_Load_Char, the slot's content is erased by the new glyph data, */
+  /*    i.e., the glyph's metrics, its image (bitmap or outline), and      */
+  /*    other control information.                                         */
+  /*                                                                       */
+  /* <Also>                                                                */
+  /*    @FT_GlyphSlotRec details the publicly accessible glyph fields.     */
+  /*                                                                       */
+  typedef struct FT_GlyphSlotRec_*  FT_GlyphSlot;
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Type>                                                                */
+  /*    FT_CharMap                                                         */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    A handle to a given character map.  A charmap is used to translate */
+  /*    character codes in a given encoding into glyph indexes for its     */
+  /*    parent's face.  Some font formats may provide several charmaps per */
+  /*    font.                                                              */
+  /*                                                                       */
+  /*    Each face object owns zero or more charmaps, but only one of them  */
+  /*    can be `active' and used by @FT_Get_Char_Index or @FT_Load_Char.   */
+  /*                                                                       */
+  /*    The list of available charmaps in a face is available through the  */
+  /*    `face->num_charmaps' and `face->charmaps' fields of @FT_FaceRec.   */
+  /*                                                                       */
+  /*    The currently active charmap is available as `face->charmap'.      */
+  /*    You should call @FT_Set_Charmap to change it.                      */
+  /*                                                                       */
+  /* <Note>                                                                */
+  /*    When a new face is created (either through @FT_New_Face or         */
+  /*    @FT_Open_Face), the library looks for a Unicode charmap within     */
+  /*    the list and automatically activates it.                           */
+  /*                                                                       */
+  /* <Also>                                                                */
+  /*    The @FT_CharMapRec details the publicly accessible fields of a     */
+  /*    given character map.                                               */
+  /*                                                                       */
+  typedef struct FT_CharMapRec_*  FT_CharMap;
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Macro>                                                               */
+  /*    FT_ENC_TAG                                                         */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    This macro converts four-letter tags into an unsigned long.  It is */
+  /*    used to define `encoding' identifiers (see @FT_Encoding).          */
+  /*                                                                       */
+  /* <Note>                                                                */
+  /*    Since many 16bit compilers don't like 32bit enumerations, you      */
+  /*    should redefine this macro in case of problems to something like   */
+  /*    this:                                                              */
+  /*                                                                       */
+  /*    {                                                                  */
+  /*      #define FT_ENC_TAG( value, a, b, c, d )  value                   */
+  /*    }                                                                  */
+  /*                                                                       */
+  /*    to get a simple enumeration without assigning special numbers.     */
+  /*                                                                       */
+
+#ifndef FT_ENC_TAG
+#define FT_ENC_TAG( value, a, b, c, d )         \
+          value = ( ( (FT_UInt32)(a) << 24 ) |  \
+                    ( (FT_UInt32)(b) << 16 ) |  \
+                    ( (FT_UInt32)(c) <<  8 ) |  \
+                      (FT_UInt32)(d)         )
+
+#endif /* FT_ENC_TAG */
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Enum>                                                                */
+  /*    FT_Encoding                                                        */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    An enumeration used to specify character sets supported by         */
+  /*    charmaps.  Used in the @FT_Select_Charmap API function.            */
+  /*                                                                       */
+  /* <Note>                                                                */
+  /*    Despite the name, this enumeration lists specific character        */
+  /*    repertories (i.e., charsets), and not text encoding methods (e.g., */
+  /*    UTF-8, UTF-16, GB2312_EUC, etc.).                                  */
+  /*                                                                       */
+  /*    Because of 32-bit charcodes defined in Unicode (i.e., surrogates), */
+  /*    all character codes must be expressed as FT_Longs.                 */
+  /*                                                                       */
+  /*    Other encodings might be defined in the future.                    */
+  /*                                                                       */
+  /* <Values>                                                              */
+  /*   FT_ENCODING_NONE ::                                                 */
+  /*     The encoding value 0 is reserved.                                 */
+  /*                                                                       */
+  /*   FT_ENCODING_UNICODE ::                                              */
+  /*     Corresponds to the Unicode character set.  This value covers      */
+  /*     all versions of the Unicode repertoire, including ASCII and       */
+  /*     Latin-1.  Most fonts include a Unicode charmap, but not all       */
+  /*     of them.                                                          */
+  /*                                                                       */
+  /*   FT_ENCODING_MS_SYMBOL ::                                            */
+  /*     Corresponds to the Microsoft Symbol encoding, used to encode      */
+  /*     mathematical symbols in the 32..255 character code range.  For    */
+  /*     more information, see `http://www.ceviz.net/symbol.htm'.          */
+  /*                                                                       */
+  /*   FT_ENCODING_SJIS ::                                                 */
+  /*     Corresponds to Japanese SJIS encoding.  More info at              */
+  /*     at `http://langsupport.japanreference.com/encoding.shtml'.        */
+  /*     See note on multi-byte encodings below.                           */
+  /*                                                                       */
+  /*   FT_ENCODING_GB2312 ::                                               */
+  /*     Corresponds to an encoding system for Simplified Chinese as used  */
+  /*     used in mainland China.                                           */
+  /*                                                                       */
+  /*   FT_ENCODING_BIG5 ::                                                 */
+  /*     Corresponds to an encoding system for Traditional Chinese as used */
+  /*     in Taiwan and Hong Kong.                                          */
+  /*                                                                       */
+  /*   FT_ENCODING_WANSUNG ::                                              */
+  /*     Corresponds to the Korean encoding system known as Wansung.       */
+  /*     For more information see                                          */
+  /*     `http://www.microsoft.com/typography/unicode/949.txt'.            */
+  /*                                                                       */
+  /*   FT_ENCODING_JOHAB ::                                                */
+  /*     The Korean standard character set (KS C-5601-1992), which         */
+  /*     corresponds to MS Windows code page 1361.  This character set     */
+  /*     includes all possible Hangeul character combinations.             */
+  /*                                                                       */
+  /*   FT_ENCODING_ADOBE_LATIN_1 ::                                        */
+  /*     Corresponds to a Latin-1 encoding as defined in a Type 1          */
+  /*     Postscript font.  It is limited to 256 character codes.           */
+  /*                                                                       */
+  /*   FT_ENCODING_ADOBE_STANDARD ::                                       */
+  /*     Corresponds to the Adobe Standard encoding, as found in Type 1,   */
+  /*     CFF, and OpenType/CFF fonts.  It is limited to 256 character      */
+  /*     codes.                                                            */
+  /*                                                                       */
+  /*   FT_ENCODING_ADOBE_EXPERT ::                                         */
+  /*     Corresponds to the Adobe Expert encoding, as found in Type 1,     */
+  /*     CFF, and OpenType/CFF fonts.  It is limited to 256 character      */
+  /*     codes.                                                            */
+  /*                                                                       */
+  /*   FT_ENCODING_ADOBE_CUSTOM ::                                         */
+  /*     Corresponds to a custom encoding, as found in Type 1, CFF, and    */
+  /*     OpenType/CFF fonts.  It is limited to 256 character codes.        */
+  /*                                                                       */
+  /*   FT_ENCODING_APPLE_ROMAN ::                                          */
+  /*     Corresponds to the 8-bit Apple roman encoding.  Many TrueType and */
+  /*     OpenType fonts contain a charmap for this encoding, since older   */
+  /*     versions of Mac OS are able to use it.                            */
+  /*                                                                       */
+  /*   FT_ENCODING_OLD_LATIN_2 ::                                          */
+  /*     This value is deprecated and was never used nor reported by       */
+  /*     FreeType.  Don't use or test for it.                              */
+  /*                                                                       */
+  /*   FT_ENCODING_MS_SJIS ::                                              */
+  /*     Same as FT_ENCODING_SJIS.  Deprecated.                            */
+  /*                                                                       */
+  /*   FT_ENCODING_MS_GB2312 ::                                            */
+  /*     Same as FT_ENCODING_GB2312.  Deprecated.                          */
+  /*                                                                       */
+  /*   FT_ENCODING_MS_BIG5 ::                                              */
+  /*     Same as FT_ENCODING_BIG5.  Deprecated.                            */
+  /*                                                                       */
+  /*   FT_ENCODING_MS_WANSUNG ::                                           */
+  /*     Same as FT_ENCODING_WANSUNG.  Deprecated.                         */
+  /*                                                                       */
+  /*   FT_ENCODING_MS_JOHAB ::                                             */
+  /*     Same as FT_ENCODING_JOHAB.  Deprecated.                           */
+  /*                                                                       */
+  /* <Note>                                                                */
+  /*   By default, FreeType automatically synthetizes a Unicode charmap    */
+  /*   for Postscript fonts, using their glyph names dictionaries.         */
+  /*   However, it also reports the encodings defined explicitly in the    */
+  /*   font file, for the cases when they are needed, with the Adobe       */
+  /*   values as well.                                                     */
+  /*                                                                       */
+  /*   FT_ENCODING_NONE is set by the BDF and PCF drivers if the charmap   */
+  /*   is neither Unicode nor ISO-8859-1 (otherwise it is set to           */
+  /*   FT_ENCODING_UNICODE).  Use @FT_Get_BDF_Charset_ID to find out which */
+  /*   encoding is really present.  If, for example, the `cs_registry'     */
+  /*   field is `KOI8' and the `cs_encoding' field is `R', the font is     */
+  /*   encoded in KOI8-R.                                                  */
+  /*                                                                       */
+  /*   FT_ENCODING_NONE is always set (with a single exception) by the     */
+  /*   winfonts driver.  Use @FT_Get_WinFNT_Header and examine the         */
+  /*   `charset' field of the @FT_WinFNT_HeaderRec structure to find out   */
+  /*   which encoding is really present.  For example,                     */
+  /*   @FT_WinFNT_ID_CP1251 (204) means Windows code page 1251 (for        */
+  /*   Russian).                                                           */
+  /*                                                                       */
+  /*   FT_ENCODING_NONE is set if `platform_id' is @TT_PLATFORM_MACINTOSH  */
+  /*   and `encoding_id' is not @TT_MAC_ID_ROMAN (otherwise it is set to   */
+  /*   FT_ENCODING_APPLE_ROMAN).                                           */
+  /*                                                                       */
+  /*   If `platform_id' is @TT_PLATFORM_MACINTOSH, use the function  c     */
+  /*   @FT_Get_CMap_Language_ID  to query the Mac language ID which may be */
+  /*   needed to be able to distinguish Apple encoding variants.  See      */
+  /*                                                                       */
+  /*     http://www.unicode.org/Public/MAPPINGS/VENDORS/APPLE/README.TXT   */
+  /*                                                                       */
+  /*   to get an idea how to do that.  Basically, if the language ID is 0, */
+  /*   don't use it, otherwise subtract 1 from the language ID.  Then      */
+  /*   examine `encoding_id'.  If, for example, `encoding_id' is           */
+  /*   @TT_MAC_ID_ROMAN and the language ID (minus 1) is                   */
+  /*   `TT_MAC_LANGID_GREEK', it is the Greek encoding, not Roman.         */
+  /*   @TT_MAC_ID_ARABIC with `TT_MAC_LANGID_FARSI' means the Farsi        */
+  /*   variant the Arabic encoding.                                        */
+  /*                                                                       */
+  typedef enum  FT_Encoding_
+  {
+    FT_ENC_TAG( FT_ENCODING_NONE, 0, 0, 0, 0 ),
+
+    FT_ENC_TAG( FT_ENCODING_MS_SYMBOL, 's', 'y', 'm', 'b' ),
+    FT_ENC_TAG( FT_ENCODING_UNICODE,   'u', 'n', 'i', 'c' ),
+
+    FT_ENC_TAG( FT_ENCODING_SJIS,    's', 'j', 'i', 's' ),
+    FT_ENC_TAG( FT_ENCODING_GB2312,  'g', 'b', ' ', ' ' ),
+    FT_ENC_TAG( FT_ENCODING_BIG5,    'b', 'i', 'g', '5' ),
+    FT_ENC_TAG( FT_ENCODING_WANSUNG, 'w', 'a', 'n', 's' ),
+    FT_ENC_TAG( FT_ENCODING_JOHAB,   'j', 'o', 'h', 'a' ),
+
+    /* for backwards compatibility */
+    FT_ENCODING_MS_SJIS    = FT_ENCODING_SJIS,
+    FT_ENCODING_MS_GB2312  = FT_ENCODING_GB2312,
+    FT_ENCODING_MS_BIG5    = FT_ENCODING_BIG5,
+    FT_ENCODING_MS_WANSUNG = FT_ENCODING_WANSUNG,
+    FT_ENCODING_MS_JOHAB   = FT_ENCODING_JOHAB,
+
+    FT_ENC_TAG( FT_ENCODING_ADOBE_STANDARD, 'A', 'D', 'O', 'B' ),
+    FT_ENC_TAG( FT_ENCODING_ADOBE_EXPERT,   'A', 'D', 'B', 'E' ),
+    FT_ENC_TAG( FT_ENCODING_ADOBE_CUSTOM,   'A', 'D', 'B', 'C' ),
+    FT_ENC_TAG( FT_ENCODING_ADOBE_LATIN_1,  'l', 'a', 't', '1' ),
+
+    FT_ENC_TAG( FT_ENCODING_OLD_LATIN_2, 'l', 'a', 't', '2' ),
+
+    FT_ENC_TAG( FT_ENCODING_APPLE_ROMAN, 'a', 'r', 'm', 'n' )
+
+  } FT_Encoding;
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Enum>                                                                */
+  /*    ft_encoding_xxx                                                    */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    These constants are deprecated; use the corresponding @FT_Encoding */
+  /*    values instead.                                                    */
+  /*                                                                       */
+#define ft_encoding_none            FT_ENCODING_NONE
+#define ft_encoding_unicode         FT_ENCODING_UNICODE
+#define ft_encoding_symbol          FT_ENCODING_MS_SYMBOL
+#define ft_encoding_latin_1         FT_ENCODING_ADOBE_LATIN_1
+#define ft_encoding_latin_2         FT_ENCODING_OLD_LATIN_2
+#define ft_encoding_sjis            FT_ENCODING_SJIS
+#define ft_encoding_gb2312          FT_ENCODING_GB2312
+#define ft_encoding_big5            FT_ENCODING_BIG5
+#define ft_encoding_wansung         FT_ENCODING_WANSUNG
+#define ft_encoding_johab           FT_ENCODING_JOHAB
+
+#define ft_encoding_adobe_standard  FT_ENCODING_ADOBE_STANDARD
+#define ft_encoding_adobe_expert    FT_ENCODING_ADOBE_EXPERT
+#define ft_encoding_adobe_custom    FT_ENCODING_ADOBE_CUSTOM
+#define ft_encoding_apple_roman     FT_ENCODING_APPLE_ROMAN
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Struct>                                                              */
+  /*    FT_CharMapRec                                                      */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    The base charmap structure.                                        */
+  /*                                                                       */
+  /* <Fields>                                                              */
+  /*    face        :: A handle to the parent face object.                 */
+  /*                                                                       */
+  /*    encoding    :: An @FT_Encoding tag identifying the charmap.  Use   */
+  /*                   this with @FT_Select_Charmap.                       */
+  /*                                                                       */
+  /*    platform_id :: An ID number describing the platform for the        */
+  /*                   following encoding ID.  This comes directly from    */
+  /*                   the TrueType specification and should be emulated   */
+  /*                   for other formats.                                  */
+  /*                                                                       */
+  /*    encoding_id :: A platform specific encoding number.  This also     */
+  /*                   comes from the TrueType specification and should be */
+  /*                   emulated similarly.                                 */
+  /*                                                                       */
+  typedef struct  FT_CharMapRec_
+  {
+    FT_Face      face;
+    FT_Encoding  encoding;
+    FT_UShort    platform_id;
+    FT_UShort    encoding_id;
+
+  } FT_CharMapRec;
+
+
+  /*************************************************************************/
+  /*************************************************************************/
+  /*                                                                       */
+  /*                 B A S E   O B J E C T   C L A S S E S                 */
+  /*                                                                       */
+  /*************************************************************************/
+  /*************************************************************************/
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Type>                                                                */
+  /*    FT_Face_Internal                                                   */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    An opaque handle to an `FT_Face_InternalRec' structure, used to    */
+  /*    model private data of a given @FT_Face object.                     */
+  /*                                                                       */
+  /*    This structure might change between releases of FreeType 2 and is  */
+  /*    not generally available to client applications.                    */
+  /*                                                                       */
+  typedef struct FT_Face_InternalRec_*  FT_Face_Internal;
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Struct>                                                              */
+  /*    FT_FaceRec                                                         */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    FreeType root face class structure.  A face object models a        */
+  /*    typeface in a font file.                                           */
+  /*                                                                       */
+  /* <Fields>                                                              */
+  /*    num_faces           :: The number of faces in the font file.  Some */
+  /*                           font formats can have multiple faces in     */
+  /*                           a font file.                                */
+  /*                                                                       */
+  /*    face_index          :: The index of the face in the font file.  It */
+  /*                           is set to 0 if there is only one face in    */
+  /*                           the font file.                              */
+  /*                                                                       */
+  /*    face_flags          :: A set of bit flags that give important      */
+  /*                           information about the face; see             */
+  /*                           @FT_FACE_FLAG_XXX for the details.          */
+  /*                                                                       */
+  /*    style_flags         :: A set of bit flags indicating the style of  */
+  /*                           the face; see @FT_STYLE_FLAG_XXX for the    */
+  /*                           details.                                    */
+  /*                                                                       */
+  /*    num_glyphs          :: The number of glyphs in the face.  If the   */
+  /*                           face is scalable and has sbits (see         */
+  /*                           `num_fixed_sizes'), it is set to the number */
+  /*                           of outline glyphs.                          */
+  /*                                                                       */
+  /*    family_name         :: The face's family name.  This is an ASCII   */
+  /*                           string, usually in English, which describes */
+  /*                           the typeface's family (like `Times New      */
+  /*                           Roman', `Bodoni', `Garamond', etc).  This   */
+  /*                           is a least common denominator used to list  */
+  /*                           fonts.  Some formats (TrueType & OpenType)  */
+  /*                           provide localized and Unicode versions of   */
+  /*                           this string.  Applications should use the   */
+  /*                           format specific interface to access them.   */
+  /*                                                                       */
+  /*    style_name          :: The face's style name.  This is an ASCII    */
+  /*                           string, usually in English, which describes */
+  /*                           the typeface's style (like `Italic',        */
+  /*                           `Bold', `Condensed', etc).  Not all font    */
+  /*                           formats provide a style name, so this field */
+  /*                           is optional, and can be set to NULL.  As    */
+  /*                           for `family_name', some formats provide     */
+  /*                           localized and Unicode versions of this      */
+  /*                           string.  Applications should use the format */
+  /*                           specific interface to access them.          */
+  /*                                                                       */
+  /*    num_fixed_sizes     :: The number of bitmap strikes in the face.   */
+  /*                           Even if the face is scalable, there might   */
+  /*                           still be bitmap strikes, which are called   */
+  /*                           `sbits' in that case.                       */
+  /*                                                                       */
+  /*    available_sizes     :: An array of @FT_Bitmap_Size for all bitmap  */
+  /*                           strikes in the face.  It is set to NULL if  */
+  /*                           there is no bitmap strike.                  */
+  /*                                                                       */
+  /*    num_charmaps        :: The number of charmaps in the face.         */
+  /*                                                                       */
+  /*    charmaps            :: An array of the charmaps of the face.       */
+  /*                                                                       */
+  /*    generic             :: A field reserved for client uses.  See the  */
+  /*                           @FT_Generic type description.               */
+  /*                                                                       */
+  /*    bbox                :: The font bounding box.  Coordinates are     */
+  /*                           expressed in font units (see                */
+  /*                           `units_per_EM').  The box is large enough   */
+  /*                           to contain any glyph from the font.  Thus,  */
+  /*                           `bbox.yMax' can be seen as the `maximal     */
+  /*                           ascender', and `bbox.yMin' as the `minimal  */
+  /*                           descender'.  Only relevant for scalable     */
+  /*                           formats.                                    */
+  /*                                                                       */
+  /*    units_per_EM        :: The number of font units per EM square for  */
+  /*                           this face.  This is typically 2048 for      */
+  /*                           TrueType fonts, and 1000 for Type 1 fonts.  */
+  /*                           Only relevant for scalable formats.         */
+  /*                                                                       */
+  /*    ascender            :: The typographic ascender of the face,       */
+  /*                           expressed in font units.  For font formats  */
+  /*                           not having this information, it is set to   */
+  /*                           `bbox.yMax'.  Only relevant for scalable    */
+  /*                           formats.                                    */
+  /*                                                                       */
+  /*    descender           :: The typographic descender of the face,      */
+  /*                           expressed in font units.  For font formats  */
+  /*                           not having this information, it is set to   */
+  /*                           `bbox.yMin'.  Note that this field is       */
+  /*                           usually negative.  Only relevant for        */
+  /*                           scalable formats.                           */
+  /*                                                                       */
+  /*    height              :: The height is the vertical distance         */
+  /*                           between two consecutive baselines,          */
+  /*                           expressed in font units.  It is always      */
+  /*                           positive.  Only relevant for scalable       */
+  /*                           formats.                                    */
+  /*                                                                       */
+  /*    max_advance_width   :: The maximal advance width, in font units,   */
+  /*                           for all glyphs in this face.  This can be   */
+  /*                           used to make word wrapping computations     */
+  /*                           faster.  Only relevant for scalable         */
+  /*                           formats.                                    */
+  /*                                                                       */
+  /*    max_advance_height  :: The maximal advance height, in font units,  */
+  /*                           for all glyphs in this face.  This is only  */
+  /*                           relevant for vertical layouts, and is set   */
+  /*                           to `height' for fonts that do not provide   */
+  /*                           vertical metrics.  Only relevant for        */
+  /*                           scalable formats.                           */
+  /*                                                                       */
+  /*    underline_position  :: The position, in font units, of the         */
+  /*                           underline line for this face.  It's the     */
+  /*                           center of the underlining stem.  Only       */
+  /*                           relevant for scalable formats.              */
+  /*                                                                       */
+  /*    underline_thickness :: The thickness, in font units, of the        */
+  /*                           underline for this face.  Only relevant for */
+  /*                           scalable formats.                           */
+  /*                                                                       */
+  /*    glyph               :: The face's associated glyph slot(s).        */
+  /*                                                                       */
+  /*    size                :: The current active size for this face.      */
+  /*                                                                       */
+  /*    charmap             :: The current active charmap for this face.   */
+  /*                                                                       */
+  /* <Note>                                                                */
+  /*   Fields may be changed after a call to @FT_Attach_File or            */
+  /*   @FT_Attach_Stream.                                                  */
+  /*                                                                       */
+  typedef struct  FT_FaceRec_
+  {
+    FT_Long           num_faces;
+    FT_Long           face_index;
+
+    FT_Long           face_flags;
+    FT_Long           style_flags;
+
+    FT_Long           num_glyphs;
+
+    FT_String*        family_name;
+    FT_String*        style_name;
+
+    FT_Int            num_fixed_sizes;
+    FT_Bitmap_Size*   available_sizes;
+
+    FT_Int            num_charmaps;
+    FT_CharMap*       charmaps;
+
+    FT_Generic        generic;
+
+    /*# The following member variables (down to `underline_thickness') */
+    /*# are only relevant to scalable outlines; cf. @FT_Bitmap_Size    */
+    /*# for bitmap fonts.                                              */
+    FT_BBox           bbox;
+
+    FT_UShort         units_per_EM;
+    FT_Short          ascender;
+    FT_Short          descender;
+    FT_Short          height;
+
+    FT_Short          max_advance_width;
+    FT_Short          max_advance_height;
+
+    FT_Short          underline_position;
+    FT_Short          underline_thickness;
+
+    FT_GlyphSlot      glyph;
+    FT_Size           size;
+    FT_CharMap        charmap;
+
+    /*@private begin */
+
+    FT_Driver         driver;
+    FT_Memory         memory;
+    FT_Stream         stream;
+
+    FT_ListRec        sizes_list;
+
+    FT_Generic        autohint;
+    void*             extensions;
+
+    FT_Face_Internal  internal;
+
+    /*@private end */
+
+  } FT_FaceRec;
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Enum>                                                                */
+  /*    FT_FACE_FLAG_XXX                                                   */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    A list of bit flags used in the `face_flags' field of the          */
+  /*    @FT_FaceRec structure.  They inform client applications of         */
+  /*    properties of the corresponding face.                              */
+  /*                                                                       */
+  /* <Values>                                                              */
+  /*    FT_FACE_FLAG_SCALABLE ::                                           */
+  /*      Indicates that the face contains outline glyphs.  This doesn't   */
+  /*      prevent bitmap strikes, i.e., a face can have both this and      */
+  /*      and @FT_FACE_FLAG_FIXED_SIZES set.                               */
+  /*                                                                       */
+  /*    FT_FACE_FLAG_FIXED_SIZES ::                                        */
+  /*      Indicates that the face contains bitmap strikes.  See also the   */
+  /*      `num_fixed_sizes' and `available_sizes' fields of @FT_FaceRec.   */
+  /*                                                                       */
+  /*    FT_FACE_FLAG_FIXED_WIDTH ::                                        */
+  /*      Indicates that the face contains fixed-width characters (like    */
+  /*      Courier, Lucido, MonoType, etc.).                                */
+  /*                                                                       */
+  /*    FT_FACE_FLAG_SFNT ::                                               */
+  /*      Indicates that the face uses the `sfnt' storage scheme.  For     */
+  /*      now, this means TrueType and OpenType.                           */
+  /*                                                                       */
+  /*    FT_FACE_FLAG_HORIZONTAL ::                                         */
+  /*      Indicates that the face contains horizontal glyph metrics.  This */
+  /*      should be set for all common formats.                            */
+  /*                                                                       */
+  /*    FT_FACE_FLAG_VERTICAL ::                                           */
+  /*      Indicates that the face contains vertical glyph metrics.  This   */
+  /*      is only available in some formats, not all of them.              */
+  /*                                                                       */
+  /*    FT_FACE_FLAG_KERNING ::                                            */
+  /*      Indicates that the face contains kerning information.  If set,   */
+  /*      the kerning distance can be retrieved through the function       */
+  /*      @FT_Get_Kerning.  Otherwise the function always return the       */
+  /*      vector (0,0).  Note that FreeType doesn't handle kerning data    */
+  /*      from the `GPOS' table (as present in some OpenType fonts).       */
+  /*                                                                       */
+  /*    FT_FACE_FLAG_FAST_GLYPHS ::                                        */
+  /*      THIS FLAG IS DEPRECATED.  DO NOT USE OR TEST IT.                 */
+  /*                                                                       */
+  /*    FT_FACE_FLAG_MULTIPLE_MASTERS ::                                   */
+  /*      Indicates that the font contains multiple masters and is capable */
+  /*      of interpolating between them.  See the multiple-masters         */
+  /*      specific API for details.                                        */
+  /*                                                                       */
+  /*    FT_FACE_FLAG_GLYPH_NAMES ::                                        */
+  /*      Indicates that the font contains glyph names that can be         */
+  /*      retrieved through @FT_Get_Glyph_Name.  Note that some TrueType   */
+  /*      fonts contain broken glyph name tables.  Use the function        */
+  /*      @FT_Has_PS_Glyph_Names when needed.                              */
+  /*                                                                       */
+  /*    FT_FACE_FLAG_EXTERNAL_STREAM ::                                    */
+  /*      Used internally by FreeType to indicate that a face's stream was */
+  /*      provided by the client application and should not be destroyed   */
+  /*      when @FT_Done_Face is called.  Don't read or test this flag.     */
+  /*                                                                       */
+  /*    FT_FACE_FLAG_HINTER ::                                             */
+  /*      Set if the font driver has a hinting machine of its own.  For    */
+  /*      example, with TrueType fonts, it makes sense to use data from    */
+  /*      the SFNT `gasp' table only if the native TrueType hinting engine */
+  /*      (with the bytecode interpreter) is available and active.         */
+  /*                                                                       */
+#define FT_FACE_FLAG_SCALABLE          ( 1L <<  0 )
+#define FT_FACE_FLAG_FIXED_SIZES       ( 1L <<  1 )
+#define FT_FACE_FLAG_FIXED_WIDTH       ( 1L <<  2 )
+#define FT_FACE_FLAG_SFNT              ( 1L <<  3 )
+#define FT_FACE_FLAG_HORIZONTAL        ( 1L <<  4 )
+#define FT_FACE_FLAG_VERTICAL          ( 1L <<  5 )
+#define FT_FACE_FLAG_KERNING           ( 1L <<  6 )
+#define FT_FACE_FLAG_FAST_GLYPHS       ( 1L <<  7 )
+#define FT_FACE_FLAG_MULTIPLE_MASTERS  ( 1L <<  8 )
+#define FT_FACE_FLAG_GLYPH_NAMES       ( 1L <<  9 )
+#define FT_FACE_FLAG_EXTERNAL_STREAM   ( 1L << 10 )
+#define FT_FACE_FLAG_HINTER            ( 1L << 11 )
+
+  /* */
+
+
+  /*************************************************************************
+   *
+   * @macro:
+   *   FT_HAS_HORIZONTAL( face )
+   *
+   * @description:
+   *   A macro that returns true whenever a face object contains
+   *   horizontal metrics (this is true for all font formats though).
+   *
+   * @also:
+   *   @FT_HAS_VERTICAL can be used to check for vertical metrics.
+   *
+   */
+#define FT_HAS_HORIZONTAL( face ) \
+          ( face->face_flags & FT_FACE_FLAG_HORIZONTAL )
+
+
+  /*************************************************************************
+   *
+   * @macro:
+   *   FT_HAS_VERTICAL( face )
+   *
+   * @description:
+   *   A macro that returns true whenever a face object contains vertical
+   *   metrics.
+   *
+   */
+#define FT_HAS_VERTICAL( face ) \
+          ( face->face_flags & FT_FACE_FLAG_VERTICAL )
+
+
+  /*************************************************************************
+   *
+   * @macro:
+   *   FT_HAS_KERNING( face )
+   *
+   * @description:
+   *   A macro that returns true whenever a face object contains kerning
+   *   data that can be accessed with @FT_Get_Kerning.
+   *
+   */
+#define FT_HAS_KERNING( face ) \
+          ( face->face_flags & FT_FACE_FLAG_KERNING )
+
+
+  /*************************************************************************
+   *
+   * @macro:
+   *   FT_IS_SCALABLE( face )
+   *
+   * @description:
+   *   A macro that returns true whenever a face object contains a scalable
+   *   font face (true for TrueType, Type 1, Type 42, CID, OpenType/CFF,
+   *   and PFR font formats.
+   *
+   */
+#define FT_IS_SCALABLE( face ) \
+          ( face->face_flags & FT_FACE_FLAG_SCALABLE )
+
+
+  /*************************************************************************
+   *
+   * @macro:
+   *   FT_IS_SFNT( face )
+   *
+   * @description:
+   *   A macro that returns true whenever a face object contains a font
+   *   whose format is based on the SFNT storage scheme.  This usually
+   *   means: TrueType fonts, OpenType fonts, as well as SFNT-based embedded
+   *   bitmap fonts.
+   *
+   *   If this macro is true, all functions defined in @FT_SFNT_NAMES_H and
+   *   @FT_TRUETYPE_TABLES_H are available.
+   *
+   */
+#define FT_IS_SFNT( face ) \
+          ( face->face_flags & FT_FACE_FLAG_SFNT )
+
+
+  /*************************************************************************
+   *
+   * @macro:
+   *   FT_IS_FIXED_WIDTH( face )
+   *
+   * @description:
+   *   A macro that returns true whenever a face object contains a font face
+   *   that contains fixed-width (or `monospace', `fixed-pitch', etc.)
+   *   glyphs.
+   *
+   */
+#define FT_IS_FIXED_WIDTH( face ) \
+          ( face->face_flags & FT_FACE_FLAG_FIXED_WIDTH )
+
+
+  /*************************************************************************
+   *
+   * @macro:
+   *   FT_HAS_FIXED_SIZES( face )
+   *
+   * @description:
+   *   A macro that returns true whenever a face object contains some
+   *   embedded bitmaps.  See the `available_sizes' field of the
+   *   @FT_FaceRec structure.
+   *
+   */
+#define FT_HAS_FIXED_SIZES( face ) \
+          ( face->face_flags & FT_FACE_FLAG_FIXED_SIZES )
+
+  /* */
+
+
+  /*************************************************************************
+   *
+   * @macro:
+   *   FT_HAS_FAST_GLYPHS( face )
+   *
+   * @description:
+   *   Deprecated.
+   *
+   */
+#define FT_HAS_FAST_GLYPHS( face )  0
+
+
+  /*************************************************************************
+   *
+   * @macro:
+   *   FT_HAS_GLYPH_NAMES( face )
+   *
+   * @description:
+   *   A macro that returns true whenever a face object contains some glyph
+   *   names that can be accessed through @FT_Get_Glyph_Name.
+   *
+   */
+#define FT_HAS_GLYPH_NAMES( face ) \
+          ( face->face_flags & FT_FACE_FLAG_GLYPH_NAMES )
+
+
+  /*************************************************************************
+   *
+   * @macro:
+   *   FT_HAS_MULTIPLE_MASTERS( face )
+   *
+   * @description:
+   *   A macro that returns true whenever a face object contains some
+   *   multiple masters.  The functions provided by @FT_MULTIPLE_MASTERS_H
+   *   are then available to choose the exact design you want.
+   *
+   */
+#define FT_HAS_MULTIPLE_MASTERS( face ) \
+          ( face->face_flags & FT_FACE_FLAG_MULTIPLE_MASTERS )
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Constant>                                                            */
+  /*    FT_STYLE_FLAG_XXX                                                  */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    A list of bit-flags used to indicate the style of a given face.    */
+  /*    These are used in the `style_flags' field of @FT_FaceRec.          */
+  /*                                                                       */
+  /* <Values>                                                              */
+  /*    FT_STYLE_FLAG_ITALIC ::                                            */
+  /*      Indicates that a given face is italicized.                       */
+  /*                                                                       */
+  /*    FT_STYLE_FLAG_BOLD ::                                              */
+  /*      Indicates that a given face is bold.                             */
+  /*                                                                       */
+#define FT_STYLE_FLAG_ITALIC  ( 1 << 0 )
+#define FT_STYLE_FLAG_BOLD    ( 1 << 1 )
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Type>                                                                */
+  /*    FT_Size_Internal                                                   */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    An opaque handle to an `FT_Size_InternalRec' structure, used to    */
+  /*    model private data of a given FT_Size object.                      */
+  /*                                                                       */
+  typedef struct FT_Size_InternalRec_*  FT_Size_Internal;
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Struct>                                                              */
+  /*    FT_Size_Metrics                                                    */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    The size metrics structure gives the metrics of a size object.     */
+  /*                                                                       */
+  /* <Fields>                                                              */
+  /*    x_ppem       :: The width of the scaled EM square in pixels, hence */
+  /*                    the term `ppem' (pixels per EM).  It is also       */
+  /*                    referred to as `nominal width'.                    */
+  /*                                                                       */
+  /*    y_ppem       :: The height of the scaled EM square in pixels,      */
+  /*                    hence the term `ppem' (pixels per EM).  It is also */
+  /*                    referred to as `nominal height'.                   */
+  /*                                                                       */
+  /*    x_scale      :: A 16.16 fractional scaling value used to convert   */
+  /*                    horizontal metrics from font units to 26.6         */
+  /*                    fractional pixels.  Only relevant for scalable     */
+  /*                    font formats.                                      */
+  /*                                                                       */
+  /*    y_scale      :: A 16.16 fractional scaling value used to convert   */
+  /*                    vertical metrics from font units to 26.6           */
+  /*                    fractional pixels.  Only relevant for scalable     */
+  /*                    font formats.                                      */
+  /*                                                                       */
+  /*    ascender     :: The ascender in 26.6 fractional pixels.  See       */
+  /*                    @FT_FaceRec for the details.                       */
+  /*                                                                       */
+  /*    descender    :: The descender in 26.6 fractional pixels.  See      */
+  /*                    @FT_FaceRec for the details.                       */
+  /*                                                                       */
+  /*    height       :: The height in 26.6 fractional pixels.  See         */
+  /*                    @FT_FaceRec for the details.                       */
+  /*                                                                       */
+  /*    max_advance  :: The maximal advance width in 26.6 fractional       */
+  /*                    pixels.  See @FT_FaceRec for the details.          */
+  /*                                                                       */
+  /* <Note>                                                                */
+  /*    The scaling values, if relevant, are determined first during a     */
+  /*    size changing operation.  The remaining fields are then set by the */
+  /*    driver.  For scalable formats, they are usually set to scaled      */
+  /*    values of the corresponding fields in @FT_FaceRec.                 */
+  /*                                                                       */
+  /*    Note that due to glyph hinting, these values might not be exact    */
+  /*    for certain fonts.  Thus they must be treated as unreliable        */
+  /*    with an error margin of at least one pixel!                        */
+  /*                                                                       */
+  /*    Indeed, the only way to get the exact metrics is to render _all_   */
+  /*    glyphs.  As this would be a definite performance hit, it is up to  */
+  /*    client applications to perform such computations.                  */
+  /*                                                                       */
+  /*    The FT_Size_Metrics structure is valid for bitmap fonts also.      */
+  /*                                                                       */
+  typedef struct  FT_Size_Metrics_
+  {
+    FT_UShort  x_ppem;      /* horizontal pixels per EM               */
+    FT_UShort  y_ppem;      /* vertical pixels per EM                 */
+
+    FT_Fixed   x_scale;     /* scaling values used to convert font    */
+    FT_Fixed   y_scale;     /* units to 26.6 fractional pixels        */
+
+    FT_Pos     ascender;    /* ascender in 26.6 frac. pixels          */
+    FT_Pos     descender;   /* descender in 26.6 frac. pixels         */
+    FT_Pos     height;      /* text height in 26.6 frac. pixels       */
+    FT_Pos     max_advance; /* max horizontal advance, in 26.6 pixels */
+
+  } FT_Size_Metrics;
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Struct>                                                              */
+  /*    FT_SizeRec                                                         */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    FreeType root size class structure.  A size object models a face   */
+  /*    object at a given size.                                            */
+  /*                                                                       */
+  /* <Fields>                                                              */
+  /*    face    :: Handle to the parent face object.                       */
+  /*                                                                       */
+  /*    generic :: A typeless pointer, which is unused by the FreeType     */
+  /*               library or any of its drivers.  It can be used by       */
+  /*               client applications to link their own data to each size */
+  /*               object.                                                 */
+  /*                                                                       */
+  /*    metrics :: Metrics for this size object.  This field is read-only. */
+  /*                                                                       */
+  typedef struct  FT_SizeRec_
+  {
+    FT_Face           face;      /* parent face object              */
+    FT_Generic        generic;   /* generic pointer for client uses */
+    FT_Size_Metrics   metrics;   /* size metrics                    */
+    FT_Size_Internal  internal;
+
+  } FT_SizeRec;
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Struct>                                                              */
+  /*    FT_SubGlyph                                                        */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    The subglyph structure is an internal object used to describe      */
+  /*    subglyphs (for example, in the case of composites).                */
+  /*                                                                       */
+  /* <Note>                                                                */
+  /*    The subglyph implementation is not part of the high-level API,     */
+  /*    hence the forward structure declaration.                           */
+  /*                                                                       */
+  /*    You can however retrieve subglyph information with                 */
+  /*    @FT_Get_SubGlyph_Info.                                             */
+  /*                                                                       */
+  typedef struct FT_SubGlyphRec_*  FT_SubGlyph;
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Type>                                                                */
+  /*    FT_Slot_Internal                                                   */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    An opaque handle to an `FT_Slot_InternalRec' structure, used to    */
+  /*    model private data of a given FT_GlyphSlot object.                 */
+  /*                                                                       */
+  typedef struct FT_Slot_InternalRec_*  FT_Slot_Internal;
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Struct>                                                              */
+  /*    FT_GlyphSlotRec                                                    */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    FreeType root glyph slot class structure.  A glyph slot is a       */
+  /*    container where individual glyphs can be loaded, be they in        */
+  /*    outline or bitmap format.                                          */
+  /*                                                                       */
+  /* <Fields>                                                              */
+  /*    library           :: A handle to the FreeType library instance     */
+  /*                         this slot belongs to.                         */
+  /*                                                                       */
+  /*    face              :: A handle to the parent face object.           */
+  /*                                                                       */
+  /*    next              :: In some cases (like some font tools), several */
+  /*                         glyph slots per face object can be a good     */
+  /*                         thing.  As this is rare, the glyph slots are  */
+  /*                         listed through a direct, single-linked list   */
+  /*                         using its `next' field.                       */
+  /*                                                                       */
+  /*    generic           :: A typeless pointer which is unused by the     */
+  /*                         FreeType library or any of its drivers.  It   */
+  /*                         can be used by client applications to link    */
+  /*                         their own data to each glyph slot object.     */
+  /*                                                                       */
+  /*    metrics           :: The metrics of the last loaded glyph in the   */
+  /*                         slot.  The returned values depend on the last */
+  /*                         load flags (see the @FT_Load_Glyph API        */
+  /*                         function) and can be expressed either in 26.6 */
+  /*                         fractional pixels or font units.              */
+  /*                                                                       */
+  /*                         Note that even when the glyph image is        */
+  /*                         transformed, the metrics are not.             */
+  /*                                                                       */
+  /*    linearHoriAdvance :: The advance width of the unhinted glyph.      */
+  /*                         Its value is expressed in 16.16 fractional    */
+  /*                         pixels, unless @FT_LOAD_LINEAR_DESIGN is set  */
+  /*                         when loading the glyph.  This field can be    */
+  /*                         important to perform correct WYSIWYG layout.  */
+  /*                         Only relevant for outline glyphs.             */
+  /*                                                                       */
+  /*    linearVertAdvance :: The advance height of the unhinted glyph.     */
+  /*                         Its value is expressed in 16.16 fractional    */
+  /*                         pixels, unless @FT_LOAD_LINEAR_DESIGN is set  */
+  /*                         when loading the glyph.  This field can be    */
+  /*                         important to perform correct WYSIWYG layout.  */
+  /*                         Only relevant for outline glyphs.             */
+  /*                                                                       */
+  /*    advance           :: This is the transformed advance width for the */
+  /*                         glyph.                                        */
+  /*                                                                       */
+  /*    format            :: This field indicates the format of the image  */
+  /*                         contained in the glyph slot.  Typically       */
+  /*                         @FT_GLYPH_FORMAT_BITMAP,                      */
+  /*                         @FT_GLYPH_FORMAT_OUTLINE, or                  */
+  /*                         @FT_GLYPH_FORMAT_COMPOSITE, but others are    */
+  /*                         possible.                                     */
+  /*                                                                       */
+  /*    bitmap            :: This field is used as a bitmap descriptor     */
+  /*                         when the slot format is                       */
+  /*                         @FT_GLYPH_FORMAT_BITMAP.  Note that the       */
+  /*                         address and content of the bitmap buffer can  */
+  /*                         change between calls of @FT_Load_Glyph and a  */
+  /*                         few other functions.                          */
+  /*                                                                       */
+  /*    bitmap_left       :: This is the bitmap's left bearing expressed   */
+  /*                         in integer pixels.  Of course, this is only   */
+  /*                         valid if the format is                        */
+  /*                         @FT_GLYPH_FORMAT_BITMAP.                      */
+  /*                                                                       */
+  /*    bitmap_top        :: This is the bitmap's top bearing expressed in */
+  /*                         integer pixels.  Remember that this is the    */
+  /*                         distance from the baseline to the top-most    */
+  /*                         glyph scanline, upwards y-coordinates being   */
+  /*                         *positive*.                                   */
+  /*                                                                       */
+  /*    outline           :: The outline descriptor for the current glyph  */
+  /*                         image if its format is                        */
+  /*                         @FT_GLYPH_FORMAT_OUTLINE.  Once a glyph is    */
+  /*                         loaded, `outline' can be transformed,         */
+  /*                         distorted, embolded, etc.  However, it must   */
+  /*                         not be freed.                                 */
+  /*                                                                       */
+  /*    num_subglyphs     :: The number of subglyphs in a composite glyph. */
+  /*                         This field is only valid for the composite    */
+  /*                         glyph format that should normally only be     */
+  /*                         loaded with the @FT_LOAD_NO_RECURSE flag.     */
+  /*                         For now this is internal to FreeType.         */
+  /*                                                                       */
+  /*    subglyphs         :: An array of subglyph descriptors for          */
+  /*                         composite glyphs.  There are `num_subglyphs'  */
+  /*                         elements in there.  Currently internal to     */
+  /*                         FreeType.                                     */
+  /*                                                                       */
+  /*    control_data      :: Certain font drivers can also return the      */
+  /*                         control data for a given glyph image (e.g.    */
+  /*                         TrueType bytecode, Type 1 charstrings, etc.). */
+  /*                         This field is a pointer to such data.         */
+  /*                                                                       */
+  /*    control_len       :: This is the length in bytes of the control    */
+  /*                         data.                                         */
+  /*                                                                       */
+  /*    other             :: Really wicked formats can use this pointer to */
+  /*                         present their own glyph image to client       */
+  /*                         applications.  Note that the application      */
+  /*                         needs to know about the image format.         */
+  /*                                                                       */
+  /*    lsb_delta         :: The difference between hinted and unhinted    */
+  /*                         left side bearing while autohinting is        */
+  /*                         active.  Zero otherwise.                      */
+  /*                                                                       */
+  /*    rsb_delta         :: The difference between hinted and unhinted    */
+  /*                         right side bearing while autohinting is       */
+  /*                         active.  Zero otherwise.                      */
+  /*                                                                       */
+  /* <Note>                                                                */
+  /*    If @FT_Load_Glyph is called with default flags (see                */
+  /*    @FT_LOAD_DEFAULT) the glyph image is loaded in the glyph slot in   */
+  /*    its native format (e.g., an outline glyph for TrueType and Type 1  */
+  /*    formats).                                                          */
+  /*                                                                       */
+  /*    This image can later be converted into a bitmap by calling         */
+  /*    @FT_Render_Glyph.  This function finds the current renderer for    */
+  /*    the native image's format then invokes it.                         */
+  /*                                                                       */
+  /*    The renderer is in charge of transforming the native image through */
+  /*    the slot's face transformation fields, then convert it into a      */
+  /*    bitmap that is returned in `slot->bitmap'.                         */
+  /*                                                                       */
+  /*    Note that `slot->bitmap_left' and `slot->bitmap_top' are also used */
+  /*    to specify the position of the bitmap relative to the current pen  */
+  /*    position (e.g., coordinates (0,0) on the baseline).  Of course,    */
+  /*    `slot->format' is also changed to @FT_GLYPH_FORMAT_BITMAP.         */
+  /*                                                                       */
+  /* <Note>                                                                */
+  /*    Here a small pseudo code fragment which shows how to use           */
+  /*    `lsb_delta' and `rsb_delta':                                       */
+  /*                                                                       */
+  /*    {                                                                  */
+  /*      FT_Pos  origin_x       = 0;                                      */
+  /*      FT_Pos  prev_rsb_delta = 0;                                      */
+  /*                                                                       */
+  /*                                                                       */
+  /*      for all glyphs do                                                */
+  /*        <compute kern between current and previous glyph and add it to */
+  /*         `origin_x'>                                                   */
+  /*                                                                       */
+  /*        <load glyph with `FT_Load_Glyph'>                              */
+  /*                                                                       */
+  /*        if ( prev_rsb_delta - face->glyph->lsb_delta >= 32 )           */
+  /*          origin_x -= 64;                                              */
+  /*        else if ( prev_rsb_delta - face->glyph->lsb_delta < -32 )      */
+  /*          origin_x += 64;                                              */
+  /*                                                                       */
+  /*        prev_rsb_delta = face->glyph->rsb_delta;                       */
+  /*                                                                       */
+  /*        <save glyph image, or render glyph, or ...>                    */
+  /*                                                                       */
+  /*        origin_x += face->glyph->advance.x;                            */
+  /*      endfor                                                           */
+  /*    }                                                                  */
+  /*                                                                       */
+  typedef struct  FT_GlyphSlotRec_
+  {
+    FT_Library        library;
+    FT_Face           face;
+    FT_GlyphSlot      next;
+    FT_UInt           reserved;       /* retained for binary compatibility */
+    FT_Generic        generic;
+
+    FT_Glyph_Metrics  metrics;
+    FT_Fixed          linearHoriAdvance;
+    FT_Fixed          linearVertAdvance;
+    FT_Vector         advance;
+
+    FT_Glyph_Format   format;
+
+    FT_Bitmap         bitmap;
+    FT_Int            bitmap_left;
+    FT_Int            bitmap_top;
+
+    FT_Outline        outline;
+
+    FT_UInt           num_subglyphs;
+    FT_SubGlyph       subglyphs;
+
+    void*             control_data;
+    long              control_len;
+
+    FT_Pos            lsb_delta;
+    FT_Pos            rsb_delta;
+
+    void*             other;
+
+    FT_Slot_Internal  internal;
+
+  } FT_GlyphSlotRec;
+
+
+  /*************************************************************************/
+  /*************************************************************************/
+  /*                                                                       */
+  /*                         F U N C T I O N S                             */
+  /*                                                                       */
+  /*************************************************************************/
+  /*************************************************************************/
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FT_Init_FreeType                                                   */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    Initialize a new FreeType library object.  The set of modules      */
+  /*    that are registered by this function is determined at build time.  */
+  /*                                                                       */
+  /* <Output>                                                              */
+  /*    alibrary :: A handle to a new library object.                      */
+  /*                                                                       */
+  /* <Return>                                                              */
+  /*    FreeType error code.  0 means success.                             */
+  /*                                                                       */
+  FT_EXPORT( FT_Error )
+  FT_Init_FreeType( FT_Library  *alibrary );
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FT_Done_FreeType                                                   */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    Destroy a given FreeType library object and all of its children,   */
+  /*    including resources, drivers, faces, sizes, etc.                   */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    library :: A handle to the target library object.                  */
+  /*                                                                       */
+  /* <Return>                                                              */
+  /*    FreeType error code.  0 means success.                             */
+  /*                                                                       */
+  FT_EXPORT( FT_Error )
+  FT_Done_FreeType( FT_Library  library );
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Enum>                                                                */
+  /*    FT_OPEN_XXX                                                        */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    A list of bit-field constants used within the `flags' field of the */
+  /*    @FT_Open_Args structure.                                           */
+  /*                                                                       */
+  /* <Values>                                                              */
+  /*    FT_OPEN_MEMORY      :: This is a memory-based stream.              */
+  /*                                                                       */
+  /*    FT_OPEN_STREAM      :: Copy the stream from the `stream' field.    */
+  /*                                                                       */
+  /*    FT_OPEN_PATHNAME    :: Create a new input stream from a C          */
+  /*                           path name.                                  */
+  /*                                                                       */
+  /*    FT_OPEN_DRIVER      :: Use the `driver' field.                     */
+  /*                                                                       */
+  /*    FT_OPEN_PARAMS      :: Use the `num_params' and `params' fields.   */
+  /*                                                                       */
+  /*    ft_open_memory      :: Deprecated; use @FT_OPEN_MEMORY instead.    */
+  /*                                                                       */
+  /*    ft_open_stream      :: Deprecated; use @FT_OPEN_STREAM instead.    */
+  /*                                                                       */
+  /*    ft_open_pathname    :: Deprecated; use @FT_OPEN_PATHNAME instead.  */
+  /*                                                                       */
+  /*    ft_open_driver      :: Deprecated; use @FT_OPEN_DRIVER instead.    */
+  /*                                                                       */
+  /*    ft_open_params      :: Deprecated; use @FT_OPEN_PARAMS instead.    */
+  /*                                                                       */
+  /* <Note>                                                                */
+  /*    The `FT_OPEN_MEMORY', `FT_OPEN_STREAM', and `FT_OPEN_PATHNAME'     */
+  /*    flags are mutually exclusive.                                      */
+  /*                                                                       */
+#define FT_OPEN_MEMORY    0x1
+#define FT_OPEN_STREAM    0x2
+#define FT_OPEN_PATHNAME  0x4
+#define FT_OPEN_DRIVER    0x8
+#define FT_OPEN_PARAMS    0x10
+
+#define ft_open_memory    FT_OPEN_MEMORY     /* deprecated */
+#define ft_open_stream    FT_OPEN_STREAM     /* deprecated */
+#define ft_open_pathname  FT_OPEN_PATHNAME   /* deprecated */
+#define ft_open_driver    FT_OPEN_DRIVER     /* deprecated */
+#define ft_open_params    FT_OPEN_PARAMS     /* deprecated */
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Struct>                                                              */
+  /*    FT_Parameter                                                       */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    A simple structure used to pass more or less generic parameters    */
+  /*    to @FT_Open_Face.                                                  */
+  /*                                                                       */
+  /* <Fields>                                                              */
+  /*    tag  :: A four-byte identification tag.                            */
+  /*                                                                       */
+  /*    data :: A pointer to the parameter data.                           */
+  /*                                                                       */
+  /* <Note>                                                                */
+  /*    The ID and function of parameters are driver-specific.             */
+  /*                                                                       */
+  typedef struct  FT_Parameter_
+  {
+    FT_ULong    tag;
+    FT_Pointer  data;
+
+  } FT_Parameter;
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Struct>                                                              */
+  /*    FT_Open_Args                                                       */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    A structure used to indicate how to open a new font file or        */
+  /*    stream.  A pointer to such a structure can be used as a parameter  */
+  /*    for the functions @FT_Open_Face and @FT_Attach_Stream.             */
+  /*                                                                       */
+  /* <Fields>                                                              */
+  /*    flags       :: A set of bit flags indicating how to use the        */
+  /*                   structure.                                          */
+  /*                                                                       */
+  /*    memory_base :: The first byte of the file in memory.               */
+  /*                                                                       */
+  /*    memory_size :: The size in bytes of the file in memory.            */
+  /*                                                                       */
+  /*    pathname    :: A pointer to an 8-bit file pathname.                */
+  /*                                                                       */
+  /*    stream      :: A handle to a source stream object.                 */
+  /*                                                                       */
+  /*    driver      :: This field is exclusively used by @FT_Open_Face;    */
+  /*                   it simply specifies the font driver to use to open  */
+  /*                   the face.  If set to 0, FreeType tries to load the  */
+  /*                   face with each one of the drivers in its list.      */
+  /*                                                                       */
+  /*    num_params  :: The number of extra parameters.                     */
+  /*                                                                       */
+  /*    params      :: Extra parameters passed to the font driver when     */
+  /*                   opening a new face.                                 */
+  /*                                                                       */
+  /* <Note>                                                                */
+  /*    The stream type is determined by the contents of `flags' which     */
+  /*    are tested in the following order by @FT_Open_Face:                */
+  /*                                                                       */
+  /*    If the `FT_OPEN_MEMORY' bit is set, assume that this is a          */
+  /*    memory file of `memory_size' bytes, located at `memory_address'.   */
+  /*    The data are are not copied, and the client is responsible for     */
+  /*    releasing and destroying them _after_ the corresponding call to    */
+  /*    @FT_Done_Face.                                                     */
+  /*                                                                       */
+  /*    Otherwise, if the `FT_OPEN_STREAM' bit is set, assume that a       */
+  /*    custom input stream `stream' is used.                              */
+  /*                                                                       */
+  /*    Otherwise, if the `FT_OPEN_PATHNAME' bit is set, assume that this  */
+  /*    is a normal file and use `pathname' to open it.                    */
+  /*                                                                       */
+  /*    If the `FT_OPEN_DRIVER' bit is set, @FT_Open_Face only tries to    */
+  /*    open the file with the driver whose handler is in `driver'.        */
+  /*                                                                       */
+  /*    If the `FT_OPEN_PARAMS' bit is set, the parameters given by        */
+  /*    `num_params' and `params' is used.  They are ignored otherwise.    */
+  /*                                                                       */
+  /*    Ideally, both the `pathname' and `params' fields should be tagged  */
+  /*    as `const'; this is missing for API backwards compatibility.  With */
+  /*    other words, applications should treat them as read-only.          */
+  /*                                                                       */
+  typedef struct  FT_Open_Args_
+  {
+    FT_UInt         flags;
+    const FT_Byte*  memory_base;
+    FT_Long         memory_size;
+    FT_String*      pathname;
+    FT_Stream       stream;
+    FT_Module       driver;
+    FT_Int          num_params;
+    FT_Parameter*   params;
+
+  } FT_Open_Args;
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FT_New_Face                                                        */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    This function calls @FT_Open_Face to open a font by its pathname.  */
+  /*                                                                       */
+  /* <InOut>                                                               */
+  /*    library    :: A handle to the library resource.                    */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    pathname   :: A path to the font file.                             */
+  /*                                                                       */
+  /*    face_index :: The index of the face within the font.  The first    */
+  /*                  face has index 0.                                    */
+  /*                                                                       */
+  /* <Output>                                                              */
+  /*    aface      :: A handle to a new face object.  If `face_index' is   */
+  /*                  greater than or equal to zero, it must be non-NULL.  */
+  /*                  See @FT_Open_Face for more details.                  */
+  /*                                                                       */
+  /* <Return>                                                              */
+  /*    FreeType error code.  0 means success.                             */
+  /*                                                                       */
+  FT_EXPORT( FT_Error )
+  FT_New_Face( FT_Library   library,
+               const char*  filepathname,
+               FT_Long      face_index,
+               FT_Face     *aface );
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FT_New_Memory_Face                                                 */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    This function calls @FT_Open_Face to open a font which has been    */
+  /*    loaded into memory.                                                */
+  /*                                                                       */
+  /* <InOut>                                                               */
+  /*    library    :: A handle to the library resource.                    */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    file_base  :: A pointer to the beginning of the font data.         */
+  /*                                                                       */
+  /*    file_size  :: The size of the memory chunk used by the font data.  */
+  /*                                                                       */
+  /*    face_index :: The index of the face within the font.  The first    */
+  /*                  face has index 0.                                    */
+  /*                                                                       */
+  /* <Output>                                                              */
+  /*    aface      :: A handle to a new face object.  If `face_index' is   */
+  /*                  greater than or equal to zero, it must be non-NULL.  */
+  /*                  See @FT_Open_Face for more details.                  */
+  /*                                                                       */
+  /* <Return>                                                              */
+  /*    FreeType error code.  0 means success.                             */
+  /*                                                                       */
+  /* <Note>                                                                */
+  /*    You must not deallocate the memory before calling @FT_Done_Face.   */
+  /*                                                                       */
+  FT_EXPORT( FT_Error )
+  FT_New_Memory_Face( FT_Library      library,
+                      const FT_Byte*  file_base,
+                      FT_Long         file_size,
+                      FT_Long         face_index,
+                      FT_Face        *aface );
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FT_Open_Face                                                       */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    Create a face object from a given resource described by            */
+  /*    @FT_Open_Args.                                                     */
+  /*                                                                       */
+  /* <InOut>                                                               */
+  /*    library    :: A handle to the library resource.                    */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    args       :: A pointer to an `FT_Open_Args' structure which must  */
+  /*                  be filled by the caller.                             */
+  /*                                                                       */
+  /*    face_index :: The index of the face within the font.  The first    */
+  /*                  face has index 0.                                    */
+  /*                                                                       */
+  /* <Output>                                                              */
+  /*    aface      :: A handle to a new face object.  If `face_index' is   */
+  /*                  greater than or equal to zero, it must be non-NULL.  */
+  /*                  See note below.                                      */
+  /*                                                                       */
+  /* <Return>                                                              */
+  /*    FreeType error code.  0 means success.                             */
+  /*                                                                       */
+  /* <Note>                                                                */
+  /*    Unlike FreeType 1.x, this function automatically creates a glyph   */
+  /*    slot for the face object which can be accessed directly through    */
+  /*    `face->glyph'.                                                     */
+  /*                                                                       */
+  /*    FT_Open_Face can be used to quickly check whether the font         */
+  /*    format of a given font resource is supported by FreeType.  If the  */
+  /*    `face_index' field is negative, the function's return value is 0   */
+  /*    if the font format is recognized, or non-zero otherwise;           */
+  /*    the function returns a more or less empty face handle in `*aface'  */
+  /*    (if `aface' isn't NULL).  The only useful field in this special    */
+  /*    case is `face->num_faces' which gives the number of faces within   */
+  /*    the font file.  After examination, the returned @FT_Face structure */
+  /*    should be deallocated with a call to @FT_Done_Face.                */
+  /*                                                                       */
+  /*    Each new face object created with this function also owns a        */
+  /*    default @FT_Size object, accessible as `face->size'.               */
+  /*                                                                       */
+  FT_EXPORT( FT_Error )
+  FT_Open_Face( FT_Library           library,
+                const FT_Open_Args*  args,
+                FT_Long              face_index,
+                FT_Face             *aface );
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FT_Attach_File                                                     */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    This function calls @FT_Attach_Stream to attach a file.            */
+  /*                                                                       */
+  /* <InOut>                                                               */
+  /*    face         :: The target face object.                            */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    filepathname :: The pathname.                                      */
+  /*                                                                       */
+  /* <Return>                                                              */
+  /*    FreeType error code.  0 means success.                             */
+  /*                                                                       */
+  FT_EXPORT( FT_Error )
+  FT_Attach_File( FT_Face      face,
+                  const char*  filepathname );
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FT_Attach_Stream                                                   */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    `Attach' data to a face object.  Normally, this is used to read    */
+  /*    additional information for the face object.  For example, you can  */
+  /*    attach an AFM file that comes with a Type 1 font to get the        */
+  /*    kerning values and other metrics.                                  */
+  /*                                                                       */
+  /* <InOut>                                                               */
+  /*    face       :: The target face object.                              */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    parameters :: A pointer to @FT_Open_Args which must be filled by   */
+  /*                  the caller.                                          */
+  /*                                                                       */
+  /* <Return>                                                              */
+  /*    FreeType error code.  0 means success.                             */
+  /*                                                                       */
+  /* <Note>                                                                */
+  /*    The meaning of the `attach' (i.e., what really happens when the    */
+  /*    new file is read) is not fixed by FreeType itself.  It really      */
+  /*    depends on the font format (and thus the font driver).             */
+  /*                                                                       */
+  /*    Client applications are expected to know what they are doing       */
+  /*    when invoking this function.  Most drivers simply do not implement */
+  /*    file attachments.                                                  */
+  /*                                                                       */
+  FT_EXPORT( FT_Error )
+  FT_Attach_Stream( FT_Face        face,
+                    FT_Open_Args*  parameters );
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FT_Done_Face                                                       */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    Discard a given face object, as well as all of its child slots and */
+  /*    sizes.                                                             */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    face :: A handle to a target face object.                          */
+  /*                                                                       */
+  /* <Return>                                                              */
+  /*    FreeType error code.  0 means success.                             */
+  /*                                                                       */
+  FT_EXPORT( FT_Error )
+  FT_Done_Face( FT_Face  face );
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FT_Select_Size                                                     */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    Select a bitmap strike.                                            */
+  /*                                                                       */
+  /* <InOut>                                                               */
+  /*    face         :: A handle to a target face object.                  */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    strike_index :: The index of the bitmap strike in the              */
+  /*                    `available_sizes' field of @FT_FaceRec structure.  */
+  /*                                                                       */
+  /* <Return>                                                              */
+  /*    FreeType error code.  0 means success.                             */
+  /*                                                                       */
+  FT_EXPORT( FT_Error )
+  FT_Select_Size( FT_Face  face,
+                  FT_Int   strike_index );
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Enum>                                                                */
+  /*    FT_Size_Request_Type                                               */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    An enumeration type that lists the supported size request types.   */
+  /*                                                                       */
+  /* <Values>                                                              */
+  /*    FT_SIZE_REQUEST_TYPE_NOMINAL ::                                    */
+  /*      The nominal size.  The `units_per_EM' field of @FT_FaceRec is    */
+  /*      used to determine both scaling values.                           */
+  /*                                                                       */
+  /*    FT_SIZE_REQUEST_TYPE_REAL_DIM ::                                   */
+  /*      The real dimension.  The sum of the the `Ascender' and (minus    */
+  /*      of) the `Descender' fields of @FT_FaceRec are used to determine  */
+  /*      both scaling values.                                             */
+  /*                                                                       */
+  /*    FT_SIZE_REQUEST_TYPE_BBOX ::                                       */
+  /*      The font bounding box.  The width and height of the `bbox' field */
+  /*      of @FT_FaceRec are used to determine the horizontal and vertical */
+  /*      scaling value, respectively.                                     */
+  /*                                                                       */
+  /*    FT_SIZE_REQUEST_TYPE_CELL ::                                       */
+  /*      The `max_advance_width' field of @FT_FaceRec is used to          */
+  /*      determine the horizontal scaling value; the vertical scaling     */
+  /*      value is determined the same way as                              */
+  /*      @FT_SIZE_REQUEST_TYPE_REAL_DIM does.  Finally, both scaling      */
+  /*      values are set to the smaller one.  This type is useful if you   */
+  /*      want to specify the font size for, say, a window of a given      */
+  /*      dimension and 80x24 cells.                                       */
+  /*                                                                       */
+  /*    FT_SIZE_REQUEST_TYPE_SCALES ::                                     */
+  /*      Specify the scaling values directly.                             */
+  /*                                                                       */
+  /* <Note>                                                                */
+  /*    The above descriptions only apply to scalable formats.  For bitmap */
+  /*    formats, the behaviour is up to the driver.                        */
+  /*                                                                       */
+  /*    See the note section of @FT_Size_Metrics if you wonder how size    */
+  /*    requesting relates to scaling values.                              */
+  /*                                                                       */
+  typedef enum  FT_Size_Request_Type_
+  {
+    FT_SIZE_REQUEST_TYPE_NOMINAL,
+    FT_SIZE_REQUEST_TYPE_REAL_DIM,
+    FT_SIZE_REQUEST_TYPE_BBOX,
+    FT_SIZE_REQUEST_TYPE_CELL,
+    FT_SIZE_REQUEST_TYPE_SCALES,
+
+    FT_SIZE_REQUEST_TYPE_MAX
+
+  } FT_Size_Request_Type;
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Struct>                                                              */
+  /*    FT_Size_RequestRec                                                 */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    A structure used to model a size request.                          */
+  /*                                                                       */
+  /* <Fields>                                                              */
+  /*    type           :: See @FT_Size_Request_Type.                       */
+  /*                                                                       */
+  /*    width          :: The desired width.                               */
+  /*                                                                       */
+  /*    height         :: The desired height.                              */
+  /*                                                                       */
+  /*    horiResolution :: The horizontal resolution.  If set to zero,      */
+  /*                      `width' is treated as a 26.6 fractional pixel    */
+  /*                      value.                                           */
+  /*                                                                       */
+  /*    vertResolution :: The vertical resolution.  If set to zero,        */
+  /*                      `height' is treated as a 26.6 fractional pixel   */
+  /*                      value.                                           */
+  /*                                                                       */
+  /* <Note>                                                                */
+  /*    If `width' is zero, then the horizontal scaling value is set      */
+  /*    equal to the vertical scaling value, and vice versa.               */
+  /*                                                                       */
+  typedef struct  FT_Size_RequestRec_
+  {
+    FT_Size_Request_Type  type;
+    FT_Long               width;
+    FT_Long               height;
+    FT_UInt               horiResolution;
+    FT_UInt               vertResolution;
+
+  } FT_Size_RequestRec, *FT_Size_Request;
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FT_Request_Size                                                    */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    Resize the scale of the active @FT_Size object in a face.          */
+  /*                                                                       */
+  /* <InOut>                                                               */
+  /*    face :: A handle to a target face object.                          */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    req  :: A pointer to a @FT_Size_RequestRec.                        */
+  /*                                                                       */
+  /* <Return>                                                              */
+  /*    FreeType error code.  0 means success.                             */
+  /*                                                                       */
+  /* <Note>                                                                */
+  /*    Although drivers may select the bitmap strike matching the         */
+  /*    request, you should not rely on this if you intend to select a     */
+  /*    particular bitmap strike.  Use @FT_Select_Size instead in that     */
+  /*    case.                                                              */
+  /*                                                                       */
+  FT_EXPORT( FT_Error )
+  FT_Request_Size( FT_Face          face,
+                   FT_Size_Request  req );
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FT_Set_Char_Size                                                   */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    This function calls @FT_Request_Size to request the nominal size   */
+  /*    (in points).                                                       */
+  /*                                                                       */
+  /* <InOut>                                                               */
+  /*    face            :: A handle to a target face object.               */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    char_width      :: The nominal width, in 26.6 fractional points.   */
+  /*                                                                       */
+  /*    char_height     :: The nominal height, in 26.6 fractional points.  */
+  /*                                                                       */
+  /*    horz_resolution :: The horizontal resolution in dpi.               */
+  /*                                                                       */
+  /*    vert_resolution :: The vertical resolution in dpi.                 */
+  /*                                                                       */
+  /* <Return>                                                              */
+  /*    FreeType error code.  0 means success.                             */
+  /*                                                                       */
+  /* <Note>                                                                */
+  /*    If either the character width or height is zero, it is set equal   */
+  /*    to the other value.                                                */
+  /*                                                                       */
+  /*    If either the horizontal or vertical resolution is zero, it is set */
+  /*    equal to the other value.                                          */
+  /*                                                                       */
+  /*    A character width or height smaller than 1pt is set to 1pt; if     */
+  /*    both resolution values are zero, they are set to 72dpi.            */
+  /*                                                                       */
+
+  FT_EXPORT( FT_Error )
+  FT_Set_Char_Size( FT_Face     face,
+                    FT_F26Dot6  char_width,
+                    FT_F26Dot6  char_height,
+                    FT_UInt     horz_resolution,
+                    FT_UInt     vert_resolution );
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FT_Set_Pixel_Sizes                                                 */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    This function calls @FT_Request_Size to request the nominal size   */
+  /*    (in pixels).                                                       */
+  /*                                                                       */
+  /* <InOut>                                                               */
+  /*    face         :: A handle to the target face object.                */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    pixel_width  :: The nominal width, in pixels.                      */
+  /*                                                                       */
+  /*    pixel_height :: The nominal height, in pixels.                     */
+  /*                                                                       */
+  /* <Return>                                                              */
+  /*    FreeType error code.  0 means success.                             */
+  /*                                                                       */
+  FT_EXPORT( FT_Error )
+  FT_Set_Pixel_Sizes( FT_Face  face,
+                      FT_UInt  pixel_width,
+                      FT_UInt  pixel_height );
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FT_Load_Glyph                                                      */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    A function used to load a single glyph into the glyph slot of a    */
+  /*    face object.                                                       */
+  /*                                                                       */
+  /* <InOut>                                                               */
+  /*    face        :: A handle to the target face object where the glyph  */
+  /*                   is loaded.                                          */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    glyph_index :: The index of the glyph in the font file.  For       */
+  /*                   CID-keyed fonts (either in PS or in CFF format)     */
+  /*                   this argument specifies the CID value.              */
+  /*                                                                       */
+  /*    load_flags  :: A flag indicating what to load for this glyph.  The */
+  /*                   @FT_LOAD_XXX constants can be used to control the   */
+  /*                   glyph loading process (e.g., whether the outline    */
+  /*                   should be scaled, whether to load bitmaps or not,   */
+  /*                   whether to hint the outline, etc).                  */
+  /*                                                                       */
+  /* <Return>                                                              */
+  /*    FreeType error code.  0 means success.                             */
+  /*                                                                       */
+  /* <Note>                                                                */
+  /*    The loaded glyph may be transformed.  See @FT_Set_Transform for    */
+  /*    the details.                                                       */
+  /*                                                                       */
+  FT_EXPORT( FT_Error )
+  FT_Load_Glyph( FT_Face   face,
+                 FT_UInt   glyph_index,
+                 FT_Int32  load_flags );
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FT_Load_Char                                                       */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    A function used to load a single glyph into the glyph slot of a    */
+  /*    face object, according to its character code.                      */
+  /*                                                                       */
+  /* <InOut>                                                               */
+  /*    face        :: A handle to a target face object where the glyph    */
+  /*                   is loaded.                                          */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    char_code   :: The glyph's character code, according to the        */
+  /*                   current charmap used in the face.                   */
+  /*                                                                       */
+  /*    load_flags  :: A flag indicating what to load for this glyph.  The */
+  /*                   @FT_LOAD_XXX constants can be used to control the   */
+  /*                   glyph loading process (e.g., whether the outline    */
+  /*                   should be scaled, whether to load bitmaps or not,   */
+  /*                   whether to hint the outline, etc).                  */
+  /*                                                                       */
+  /* <Return>                                                              */
+  /*    FreeType error code.  0 means success.                             */
+  /*                                                                       */
+  /* <Note>                                                                */
+  /*    This function simply calls @FT_Get_Char_Index and @FT_Load_Glyph.  */
+  /*                                                                       */
+  FT_EXPORT( FT_Error )
+  FT_Load_Char( FT_Face   face,
+                FT_ULong  char_code,
+                FT_Int32  load_flags );
+
+
+  /*************************************************************************
+   *
+   * @enum:
+   *   FT_LOAD_XXX
+   *
+   * @description:
+   *   A list of bit-field constants used with @FT_Load_Glyph to indicate
+   *   what kind of operations to perform during glyph loading.
+   *
+   * @values:
+   *   FT_LOAD_DEFAULT ::
+   *     Corresponding to 0, this value is used as the default glyph load
+   *     operation.  In this case, the following happens:
+   *
+   *     1. FreeType looks for a bitmap for the glyph corresponding to the
+   *        face's current size.  If one is found, the function returns.
+   *        The bitmap data can be accessed from the glyph slot (see note
+   *        below).
+   *
+   *     2. If no embedded bitmap is searched or found, FreeType looks for a
+   *        scalable outline.  If one is found, it is loaded from the font
+   *        file, scaled to device pixels, then `hinted' to the pixel grid
+   *        in order to optimize it.  The outline data can be accessed from
+   *        the glyph slot (see note below).
+   *
+   *     Note that by default, the glyph loader doesn't render outlines into
+   *     bitmaps.  The following flags are used to modify this default
+   *     behaviour to more specific and useful cases.
+   *
+   *   FT_LOAD_NO_SCALE ::
+   *     Don't scale the outline glyph loaded, but keep it in font units.
+   *
+   *     This flag implies @FT_LOAD_NO_HINTING and @FT_LOAD_NO_BITMAP, and
+   *     unsets @FT_LOAD_RENDER.
+   *
+   *   FT_LOAD_NO_HINTING ::
+   *     Disable hinting.  This generally generates `blurrier' bitmap glyph
+   *     when the glyph is rendered in any of the anti-aliased modes.  See
+   *     also the note below.
+   *
+   *     This flag is implied by @FT_LOAD_NO_SCALE.
+   *
+   *   FT_LOAD_RENDER ::
+   *     Call @FT_Render_Glyph after the glyph is loaded.  By default, the
+   *     glyph is rendered in @FT_RENDER_MODE_NORMAL mode.  This can be
+   *     overridden by @FT_LOAD_TARGET_XXX or @FT_LOAD_MONOCHROME.
+   *
+   *     This flag is unset by @FT_LOAD_NO_SCALE.
+   *
+   *   FT_LOAD_NO_BITMAP ::
+   *     Ignore bitmap strikes when loading.  Bitmap-only fonts ignore this
+   *     flag.
+   *
+   *     @FT_LOAD_NO_SCALE always sets this flag.
+   *
+   *   FT_LOAD_VERTICAL_LAYOUT ::
+   *     Load the glyph for vertical text layout.  _Don't_ use it as it is
+   *     problematic currently.
+   *
+   *   FT_LOAD_FORCE_AUTOHINT ::
+   *     Indicates that the auto-hinter is preferred over the font's native
+   *     hinter.  See also the note below.
+   *
+   *   FT_LOAD_CROP_BITMAP ::
+   *     Indicates that the font driver should crop the loaded bitmap glyph
+   *     (i.e., remove all space around its black bits).  Not all drivers
+   *     implement this.
+   *
+   *   FT_LOAD_PEDANTIC ::
+   *     Indicates that the font driver should perform pedantic verifications
+   *     during glyph loading.  This is mostly used to detect broken glyphs
+   *     in fonts.  By default, FreeType tries to handle broken fonts also.
+   *
+   *   FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH ::
+   *     Indicates that the font driver should ignore the global advance
+   *     width defined in the font.  By default, that value is used as the
+   *     advance width for all glyphs when the face has
+   *     @FT_FACE_FLAG_FIXED_WIDTH set.
+   *
+   *     This flag exists for historical reasons (to support buggy CJK
+   *     fonts).
+   *
+   *   FT_LOAD_NO_RECURSE ::
+   *     This flag is only used internally.  It merely indicates that the
+   *     font driver should not load composite glyphs recursively.  Instead,
+   *     it should set the `num_subglyph' and `subglyphs' values of the
+   *     glyph slot accordingly, and set `glyph->format' to
+   *     @FT_GLYPH_FORMAT_COMPOSITE.
+   *
+   *     The description of sub-glyphs is not available to client
+   *     applications for now.
+   *
+   *     This flag implies @FT_LOAD_NO_SCALE and @FT_LOAD_IGNORE_TRANSFORM.
+   *
+   *   FT_LOAD_IGNORE_TRANSFORM ::
+   *     Indicates that the transform matrix set by @FT_Set_Transform should
+   *     be ignored.
+   *
+   *   FT_LOAD_MONOCHROME ::
+   *     This flag is used with @FT_LOAD_RENDER to indicate that you want to
+   *     render an outline glyph to a 1-bit monochrome bitmap glyph, with
+   *     8 pixels packed into each byte of the bitmap data.
+   *
+   *     Note that this has no effect on the hinting algorithm used.  You
+   *     should use @FT_LOAD_TARGET_MONO instead so that the
+   *     monochrome-optimized hinting algorithm is used.
+   *
+   *   FT_LOAD_LINEAR_DESIGN ::
+   *     Indicates that the `linearHoriAdvance' and `linearVertAdvance'
+   *     fields of @FT_GlyphSlotRec should be kept in font units.  See
+   *     @FT_GlyphSlotRec for details.
+   *
+   *   FT_LOAD_NO_AUTOHINT ::
+   *     Disable auto-hinter.  See also the note below.
+   *
+   * @note:
+   *   By default, hinting is enabled and the font's native hinter (see
+   *   @FT_FACE_FLAG_HINTER) is preferred over the auto-hinter.  You can
+   *   disable hinting by setting @FT_LOAD_NO_HINTING or change the
+   *   precedence by setting @FT_LOAD_FORCE_AUTOHINT.  You can also set
+   *   @FT_LOAD_NO_AUTOHINT in case you don't want the auto-hinter to be
+   *   used at all.
+   *
+   *   Besides deciding which hinter to use, you can also decide which
+   *   hinting algorithm to use.  See @FT_LOAD_TARGET_XXX for details.
+   */
+#define FT_LOAD_DEFAULT                      0x0
+#define FT_LOAD_NO_SCALE                     0x1
+#define FT_LOAD_NO_HINTING                   0x2
+#define FT_LOAD_RENDER                       0x4
+#define FT_LOAD_NO_BITMAP                    0x8
+#define FT_LOAD_VERTICAL_LAYOUT              0x10
+#define FT_LOAD_FORCE_AUTOHINT               0x20
+#define FT_LOAD_CROP_BITMAP                  0x40
+#define FT_LOAD_PEDANTIC                     0x80
+#define FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH  0x200
+#define FT_LOAD_NO_RECURSE                   0x400
+#define FT_LOAD_IGNORE_TRANSFORM             0x800
+#define FT_LOAD_MONOCHROME                   0x1000
+#define FT_LOAD_LINEAR_DESIGN                0x2000
+
+  /* temporary hack! */
+#define FT_LOAD_SBITS_ONLY                   0x4000
+#define FT_LOAD_NO_AUTOHINT                  0x8000U
+
+  /* */
+
+
+  /**************************************************************************
+   *
+   * @enum:
+   *   FT_LOAD_TARGET_XXX
+   *
+   * @description:
+   *   A list of values that are used to select a specific hinting algorithm
+   *   to use by the hinter.  You should OR one of these values to your
+   *   `load_flags' when calling @FT_Load_Glyph.
+   *
+   *   Note that font's native hinters may ignore the hinting algorithm you
+   *   have specified (e.g., the TrueType bytecode interpreter).  You can set
+   *   @FT_LOAD_FORCE_AUTOHINT to ensure that the auto-hinter is used.
+   *
+   *   Also note that @FT_LOAD_TARGET_LIGHT is an exception, in that it
+   *   always implies @FT_LOAD_FORCE_AUTOHINT.
+   *
+   * @values:
+   *   FT_LOAD_TARGET_NORMAL ::
+   *     This corresponds to the default hinting algorithm, optimized for
+   *     standard gray-level rendering.  For monochrome output, use
+   *     @FT_LOAD_TARGET_MONO instead.
+   *
+   *   FT_LOAD_TARGET_LIGHT ::
+   *     A lighter hinting algorithm for non-monochrome modes.  Many
+   *     generated glyphs are more fuzzy but better resemble its original
+   *     shape.  A bit like rendering on Mac OS X.
+   *
+   *     As a special exception, this target implies @FT_LOAD_FORCE_AUTOHINT.
+   *
+   *   FT_LOAD_TARGET_MONO ::
+   *     Strong hinting algorithm that should only be used for monochrome
+   *     output.  The result is probably unpleasant if the glyph is rendered
+   *     in non-monochrome modes.
+   *
+   *   FT_LOAD_TARGET_LCD ::
+   *     A variant of @FT_LOAD_TARGET_NORMAL optimized for horizontally
+   *     decimated LCD displays.
+   *
+   *   FT_LOAD_TARGET_LCD_V ::
+   *     A variant of @FT_LOAD_TARGET_NORMAL optimized for vertically
+   *     decimated LCD displays.
+   *
+   * @note:
+   *   You should use only _one_ of the FT_LOAD_TARGET_XXX values in your
+   *   `load_flags'.  They can't be ORed.
+   *
+   *   If @FT_LOAD_RENDER is also set, the glyph is rendered in the
+   *   corresponding mode (i.e., the mode which matches the used algorithm
+   *   best) unless @FT_LOAD_MONOCHROME is set.
+   *
+   *   You can use a hinting algorithm that doesn't correspond to the same
+   *   rendering mode.  As an example, it is possible to use the `light'
+   *   hinting algorithm and have the results rendered in horizontal LCD
+   *   pixel mode, with code like
+   *
+   *     {
+   *       FT_Load_Glyph( face, glyph_index,
+   *                      load_flags | FT_LOAD_TARGET_LIGHT );
+   *
+   *       FT_Render_Glyph( face->glyph, FT_RENDER_MODE_LCD );
+   *     }
+   */
+
+#define FT_LOAD_TARGET_( x )      ( (FT_Int32)( (x) & 15 ) << 16 )
+
+#define FT_LOAD_TARGET_NORMAL     FT_LOAD_TARGET_( FT_RENDER_MODE_NORMAL )
+#define FT_LOAD_TARGET_LIGHT      FT_LOAD_TARGET_( FT_RENDER_MODE_LIGHT  )
+#define FT_LOAD_TARGET_MONO       FT_LOAD_TARGET_( FT_RENDER_MODE_MONO   )
+#define FT_LOAD_TARGET_LCD        FT_LOAD_TARGET_( FT_RENDER_MODE_LCD    )
+#define FT_LOAD_TARGET_LCD_V      FT_LOAD_TARGET_( FT_RENDER_MODE_LCD_V  )
+
+
+  /*
+   * @macro:
+   *   FT_LOAD_TARGET_MODE
+   *
+   * @description:
+   *   Return the @FT_Render_Mode corresponding to a given
+   *   @FT_LOAD_TARGET_XXX value.
+   */
+
+#define FT_LOAD_TARGET_MODE( x )  ( (FT_Render_Mode)( ( (x) >> 16 ) & 15 ) )
+
+  /* */
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FT_Set_Transform                                                   */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    A function used to set the transformation that is applied to glyph */
+  /*    images when they are loaded into a glyph slot through              */
+  /*    @FT_Load_Glyph.                                                    */
+  /*                                                                       */
+  /* <InOut>                                                               */
+  /*    face   :: A handle to the source face object.                      */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    matrix :: A pointer to the transformation's 2x2 matrix.  Use 0 for */
+  /*              the identity matrix.                                     */
+  /*    delta  :: A pointer to the translation vector.  Use 0 for the null */
+  /*              vector.                                                  */
+  /*                                                                       */
+  /* <Note>                                                                */
+  /*    The transformation is only applied to scalable image formats after */
+  /*    the glyph has been loaded.  It means that hinting is unaltered by  */
+  /*    the transformation and is performed on the character size given in */
+  /*    the last call to @FT_Set_Char_Size or @FT_Set_Pixel_Sizes.         */
+  /*                                                                       */
+  /*    Note that this also transforms the `face.glyph.advance' field, but */
+  /*    *not* the values in `face.glyph.metrics'.                          */
+  /*                                                                       */
+  FT_EXPORT( void )
+  FT_Set_Transform( FT_Face     face,
+                    FT_Matrix*  matrix,
+                    FT_Vector*  delta );
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Enum>                                                                */
+  /*    FT_Render_Mode                                                     */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    An enumeration type that lists the render modes supported by       */
+  /*    FreeType 2.  Each mode corresponds to a specific type of scanline  */
+  /*    conversion performed on the outline.                               */
+  /*                                                                       */
+  /*    For bitmap fonts the `bitmap->pixel_mode' field in the             */
+  /*    @FT_GlyphSlotRec structure gives the format of the returned        */
+  /*    bitmap.                                                            */
+  /*                                                                       */
+  /* <Values>                                                              */
+  /*    FT_RENDER_MODE_NORMAL ::                                           */
+  /*      This is the default render mode; it corresponds to 8-bit         */
+  /*      anti-aliased bitmaps, using 256 levels of opacity.               */
+  /*                                                                       */
+  /*    FT_RENDER_MODE_LIGHT ::                                            */
+  /*      This is equivalent to @FT_RENDER_MODE_NORMAL.  It is only        */
+  /*      defined as a separate value because render modes are also used   */
+  /*      indirectly to define hinting algorithm selectors.  See           */
+  /*      @FT_LOAD_TARGET_XXX for details.                                 */
+  /*                                                                       */
+  /*    FT_RENDER_MODE_MONO ::                                             */
+  /*      This mode corresponds to 1-bit bitmaps.                          */
+  /*                                                                       */
+  /*    FT_RENDER_MODE_LCD ::                                              */
+  /*      This mode corresponds to horizontal RGB and BGR sub-pixel        */
+  /*      displays, like LCD-screens.  It produces 8-bit bitmaps that are  */
+  /*      3 times the width of the original glyph outline in pixels, and   */
+  /*      which use the @FT_PIXEL_MODE_LCD mode.                           */
+  /*                                                                       */
+  /*    FT_RENDER_MODE_LCD_V ::                                            */
+  /*      This mode corresponds to vertical RGB and BGR sub-pixel displays */
+  /*      (like PDA screens, rotated LCD displays, etc.).  It produces     */
+  /*      8-bit bitmaps that are 3 times the height of the original        */
+  /*      glyph outline in pixels and use the @FT_PIXEL_MODE_LCD_V mode.   */
+  /*                                                                       */
+  /* <Note>                                                                */
+  /*   The LCD-optimized glyph bitmaps produced by FT_Render_Glyph are     */
+  /*   _not_ _filtered_ to reduce color-fringes.  It is up to the caller   */
+  /*   to perform this pass.                                               */
+  /*                                                                       */
+  typedef enum  FT_Render_Mode_
+  {
+    FT_RENDER_MODE_NORMAL = 0,
+    FT_RENDER_MODE_LIGHT,
+    FT_RENDER_MODE_MONO,
+    FT_RENDER_MODE_LCD,
+    FT_RENDER_MODE_LCD_V,
+
+    FT_RENDER_MODE_MAX
+
+  } FT_Render_Mode;
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Enum>                                                                */
+  /*    ft_render_mode_xxx                                                 */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    These constants are deprecated.  Use the corresponding             */
+  /*    @FT_Render_Mode values instead.                                    */
+  /*                                                                       */
+  /* <Values>                                                              */
+  /*   ft_render_mode_normal :: see @FT_RENDER_MODE_NORMAL                 */
+  /*   ft_render_mode_mono   :: see @FT_RENDER_MODE_MONO                   */
+  /*                                                                       */
+#define ft_render_mode_normal  FT_RENDER_MODE_NORMAL
+#define ft_render_mode_mono    FT_RENDER_MODE_MONO
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FT_Render_Glyph                                                    */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    Convert a given glyph image to a bitmap.  It does so by inspecting */
+  /*    the glyph image format, finding the relevant renderer, and         */
+  /*    invoking it.                                                       */
+  /*                                                                       */
+  /* <InOut>                                                               */
+  /*    slot        :: A handle to the glyph slot containing the image to  */
+  /*                   convert.                                            */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    render_mode :: This is the render mode used to render the glyph    */
+  /*                   image into a bitmap.  See @FT_Render_Mode for a     */
+  /*                   list of possible values.                            */
+  /*                                                                       */
+  /* <Return>                                                              */
+  /*    FreeType error code.  0 means success.                             */
+  /*                                                                       */
+  FT_EXPORT( FT_Error )
+  FT_Render_Glyph( FT_GlyphSlot    slot,
+                   FT_Render_Mode  render_mode );
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Enum>                                                                */
+  /*    FT_Kerning_Mode                                                    */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    An enumeration used to specify which kerning values to return in   */
+  /*    @FT_Get_Kerning.                                                   */
+  /*                                                                       */
+  /* <Values>                                                              */
+  /*    FT_KERNING_DEFAULT  :: Return scaled and grid-fitted kerning       */
+  /*                           distances (value is 0).                     */
+  /*                                                                       */
+  /*    FT_KERNING_UNFITTED :: Return scaled but un-grid-fitted kerning    */
+  /*                           distances.                                  */
+  /*                                                                       */
+  /*    FT_KERNING_UNSCALED :: Return the kerning vector in original font  */
+  /*                           units.                                      */
+  /*                                                                       */
+  typedef enum  FT_Kerning_Mode_
+  {
+    FT_KERNING_DEFAULT  = 0,
+    FT_KERNING_UNFITTED,
+    FT_KERNING_UNSCALED
+
+  } FT_Kerning_Mode;
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Const>                                                               */
+  /*    ft_kerning_default                                                 */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    This constant is deprecated.  Please use @FT_KERNING_DEFAULT       */
+  /*    instead.                                                           */
+  /*                                                                       */
+#define ft_kerning_default   FT_KERNING_DEFAULT
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Const>                                                               */
+  /*    ft_kerning_unfitted                                                */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    This constant is deprecated.  Please use @FT_KERNING_UNFITTED      */
+  /*    instead.                                                           */
+  /*                                                                       */
+#define ft_kerning_unfitted  FT_KERNING_UNFITTED
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Const>                                                               */
+  /*    ft_kerning_unscaled                                                */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    This constant is deprecated.  Please use @FT_KERNING_UNSCALED      */
+  /*    instead.                                                           */
+  /*                                                                       */
+#define ft_kerning_unscaled  FT_KERNING_UNSCALED
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FT_Get_Kerning                                                     */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    Return the kerning vector between two glyphs of a same face.       */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    face        :: A handle to a source face object.                   */
+  /*                                                                       */
+  /*    left_glyph  :: The index of the left glyph in the kern pair.       */
+  /*                                                                       */
+  /*    right_glyph :: The index of the right glyph in the kern pair.      */
+  /*                                                                       */
+  /*    kern_mode   :: See @FT_Kerning_Mode for more information.          */
+  /*                   Determines the scale and dimension of the returned  */
+  /*                   kerning vector.                                     */
+  /*                                                                       */
+  /* <Output>                                                              */
+  /*    akerning    :: The kerning vector.  This is either in font units   */
+  /*                   or in pixels (26.6 format) for scalable formats,    */
+  /*                   and in pixels for fixed-sizes formats.              */
+  /*                                                                       */
+  /* <Return>                                                              */
+  /*    FreeType error code.  0 means success.                             */
+  /*                                                                       */
+  /* <Note>                                                                */
+  /*    Only horizontal layouts (left-to-right & right-to-left) are        */
+  /*    supported by this method.  Other layouts, or more sophisticated    */
+  /*    kernings, are out of the scope of this API function -- they can be */
+  /*    implemented through format-specific interfaces.                    */
+  /*                                                                       */
+  FT_EXPORT( FT_Error )
+  FT_Get_Kerning( FT_Face     face,
+                  FT_UInt     left_glyph,
+                  FT_UInt     right_glyph,
+                  FT_UInt     kern_mode,
+                  FT_Vector  *akerning );
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FT_Get_Track_Kerning                                               */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    Return the track kerning for a given face object at a given size.  */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    face        :: A handle to a source face object.                   */
+  /*                                                                       */
+  /*    point_size  :: The point size in 16.16 fractional points.          */
+  /*                                                                       */
+  /*    degree      :: The degree of tightness.                            */
+  /*                                                                       */
+  /* <Output>                                                              */
+  /*    akerning    :: The kerning in 16.16 fractional points.             */
+  /*                                                                       */
+  /* <Return>                                                              */
+  /*    FreeType error code.  0 means success.                             */
+  /*                                                                       */
+  FT_EXPORT( FT_Error )
+  FT_Get_Track_Kerning( FT_Face    face,
+                        FT_Fixed   point_size,
+                        FT_Int     degree,
+                        FT_Fixed*  akerning );
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FT_Get_Glyph_Name                                                  */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    Retrieve the ASCII name of a given glyph in a face.  This only     */
+  /*    works for those faces where @FT_HAS_GLYPH_NAMES(face) returns 1.   */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    face        :: A handle to a source face object.                   */
+  /*                                                                       */
+  /*    glyph_index :: The glyph index.                                    */
+  /*                                                                       */
+  /*    buffer_max  :: The maximal number of bytes available in the        */
+  /*                   buffer.                                             */
+  /*                                                                       */
+  /* <Output>                                                              */
+  /*    buffer      :: A pointer to a target buffer where the name is      */
+  /*                   copied to.                                          */
+  /*                                                                       */
+  /* <Return>                                                              */
+  /*    FreeType error code.  0 means success.                             */
+  /*                                                                       */
+  /* <Note>                                                                */
+  /*    An error is returned if the face doesn't provide glyph names or if */
+  /*    the glyph index is invalid.  In all cases of failure, the first    */
+  /*    byte of `buffer' is set to 0 to indicate an empty name.            */
+  /*                                                                       */
+  /*    The glyph name is truncated to fit within the buffer if it is too  */
+  /*    long.  The returned string is always zero-terminated.              */
+  /*                                                                       */
+  /*    This function is not compiled within the library if the config     */
+  /*    macro `FT_CONFIG_OPTION_NO_GLYPH_NAMES' is defined in              */
+  /*    `include/freetype/config/ftoptions.h'.                             */
+  /*                                                                       */
+  FT_EXPORT( FT_Error )
+  FT_Get_Glyph_Name( FT_Face     face,
+                     FT_UInt     glyph_index,
+                     FT_Pointer  buffer,
+                     FT_UInt     buffer_max );
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FT_Get_Postscript_Name                                             */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    Retrieve the ASCII Postscript name of a given face, if available.  */
+  /*    This only works with Postscript and TrueType fonts.                */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    face :: A handle to the source face object.                        */
+  /*                                                                       */
+  /* <Return>                                                              */
+  /*    A pointer to the face's Postscript name.  NULL if unavailable.     */
+  /*                                                                       */
+  /* <Note>                                                                */
+  /*    The returned pointer is owned by the face and is destroyed with    */
+  /*    it.                                                                */
+  /*                                                                       */
+  FT_EXPORT( const char* )
+  FT_Get_Postscript_Name( FT_Face  face );
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FT_Select_Charmap                                                  */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    Select a given charmap by its encoding tag (as listed in           */
+  /*    `freetype.h').                                                     */
+  /*                                                                       */
+  /* <InOut>                                                               */
+  /*    face     :: A handle to the source face object.                    */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    encoding :: A handle to the selected encoding.                     */
+  /*                                                                       */
+  /* <Return>                                                              */
+  /*    FreeType error code.  0 means success.                             */
+  /*                                                                       */
+  /* <Note>                                                                */
+  /*    This function returns an error if no charmap in the face           */
+  /*    corresponds to the encoding queried here.                          */
+  /*                                                                       */
+  /*    Because many fonts contain more than a single cmap for Unicode     */
+  /*    encoding, this function has some special code to select the one    */
+  /*    which covers Unicode best.  It is thus preferable to               */
+  /*    @FT_Set_Charmap in this case.                                      */
+  /*                                                                       */
+  FT_EXPORT( FT_Error )
+  FT_Select_Charmap( FT_Face      face,
+                     FT_Encoding  encoding );
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FT_Set_Charmap                                                     */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    Select a given charmap for character code to glyph index mapping.  */
+  /*                                                                       */
+  /* <InOut>                                                               */
+  /*    face    :: A handle to the source face object.                     */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    charmap :: A handle to the selected charmap.                       */
+  /*                                                                       */
+  /* <Return>                                                              */
+  /*    FreeType error code.  0 means success.                             */
+  /*                                                                       */
+  /* <Note>                                                                */
+  /*    This function returns an error if the charmap is not part of       */
+  /*    the face (i.e., if it is not listed in the `face->charmaps'        */
+  /*    table).                                                            */
+  /*                                                                       */
+  FT_EXPORT( FT_Error )
+  FT_Set_Charmap( FT_Face     face,
+                  FT_CharMap  charmap );
+
+
+  /*************************************************************************
+   *
+   * @function:
+   *   FT_Get_Charmap_Index
+   *
+   * @description:
+   *   Retrieve index of a given charmap.
+   *
+   * @input:
+   *   charmap ::
+   *     A handle to a charmap.
+   *
+   * @return:
+   *   The index into the array of character maps within the face to which
+   *   `charmap' belongs.
+   *
+   */
+  FT_EXPORT( FT_Int )
+  FT_Get_Charmap_Index( FT_CharMap  charmap );
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FT_Get_Char_Index                                                  */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    Return the glyph index of a given character code.  This function   */
+  /*    uses a charmap object to do the mapping.                           */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    face     :: A handle to the source face object.                    */
+  /*                                                                       */
+  /*    charcode :: The character code.                                    */
+  /*                                                                       */
+  /* <Return>                                                              */
+  /*    The glyph index.  0 means `undefined character code'.              */
+  /*                                                                       */
+  /* <Note>                                                                */
+  /*    If you use FreeType to manipulate the contents of font files       */
+  /*    directly, be aware that the glyph index returned by this function  */
+  /*    doesn't always correspond to the internal indices used within      */
+  /*    the file.  This is done to ensure that value 0 always corresponds  */
+  /*    to the `missing glyph'.                                            */
+  /*                                                                       */
+  FT_EXPORT( FT_UInt )
+  FT_Get_Char_Index( FT_Face   face,
+                     FT_ULong  charcode );
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FT_Get_First_Char                                                  */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    This function is used to return the first character code in the    */
+  /*    current charmap of a given face.  It also returns the              */
+  /*    corresponding glyph index.                                         */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    face    :: A handle to the source face object.                     */
+  /*                                                                       */
+  /* <Output>                                                              */
+  /*    agindex :: Glyph index of first character code.  0 if charmap is   */
+  /*               empty.                                                  */
+  /*                                                                       */
+  /* <Return>                                                              */
+  /*    The charmap's first character code.                                */
+  /*                                                                       */
+  /* <Note>                                                                */
+  /*    You should use this function with @FT_Get_Next_Char to be able to  */
+  /*    parse all character codes available in a given charmap.  The code  */
+  /*    should look like this:                                             */
+  /*                                                                       */
+  /*    {                                                                  */
+  /*      FT_ULong  charcode;                                              */
+  /*      FT_UInt   gindex;                                                */
+  /*                                                                       */
+  /*                                                                       */
+  /*      charcode = FT_Get_First_Char( face, &gindex );                   */
+  /*      while ( gindex != 0 )                                            */
+  /*      {                                                                */
+  /*        ... do something with (charcode,gindex) pair ...               */
+  /*                                                                       */
+  /*        charcode = FT_Get_Next_Char( face, charcode, &gindex );        */
+  /*      }                                                                */
+  /*    }                                                                  */
+  /*                                                                       */
+  /*    Note that `*agindex' is set to 0 if the charmap is empty.  The     */
+  /*    result itself can be 0 in two cases: if the charmap is empty or    */
+  /*    when the value 0 is the first valid character code.                */
+  /*                                                                       */
+  FT_EXPORT( FT_ULong )
+  FT_Get_First_Char( FT_Face   face,
+                     FT_UInt  *agindex );
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FT_Get_Next_Char                                                   */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    This function is used to return the next character code in the     */
+  /*    current charmap of a given face following the value `char_code',   */
+  /*    as well as the corresponding glyph index.                          */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    face      :: A handle to the source face object.                   */
+  /*    char_code :: The starting character code.                          */
+  /*                                                                       */
+  /* <Output>                                                              */
+  /*    agindex   :: Glyph index of first character code.  0 if charmap    */
+  /*                 is empty.                                             */
+  /*                                                                       */
+  /* <Return>                                                              */
+  /*    The charmap's next character code.                                 */
+  /*                                                                       */
+  /* <Note>                                                                */
+  /*    You should use this function with @FT_Get_First_Char to walk       */
+  /*    over all character codes available in a given charmap.  See the    */
+  /*    note for this function for a simple code example.                  */
+  /*                                                                       */
+  /*    Note that `*agindex' is set to 0 when there are no more codes in   */
+  /*    the charmap.                                                       */
+  /*                                                                       */
+  FT_EXPORT( FT_ULong )
+  FT_Get_Next_Char( FT_Face    face,
+                    FT_ULong   char_code,
+                    FT_UInt   *agindex );
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FT_Get_Name_Index                                                  */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    Return the glyph index of a given glyph name.  This function uses  */
+  /*    driver specific objects to do the translation.                     */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    face       :: A handle to the source face object.                  */
+  /*                                                                       */
+  /*    glyph_name :: The glyph name.                                      */
+  /*                                                                       */
+  /* <Return>                                                              */
+  /*    The glyph index.  0 means `undefined character code'.              */
+  /*                                                                       */
+  FT_EXPORT( FT_UInt )
+  FT_Get_Name_Index( FT_Face     face,
+                     FT_String*  glyph_name );
+
+
+  /*************************************************************************
+   *
+   * @macro:
+   *   FT_SUBGLYPH_FLAG_XXX
+   *
+   * @description:
+   *   A list of constants used to describe subglyphs.  Please refer to the
+   *   TrueType specification for the meaning of the various flags.
+   *
+   * @values:
+   *   FT_SUBGLYPH_FLAG_ARGS_ARE_WORDS ::
+   *   FT_SUBGLYPH_FLAG_ARGS_ARE_XY_VALUES ::
+   *   FT_SUBGLYPH_FLAG_ROUND_XY_TO_GRID ::
+   *   FT_SUBGLYPH_FLAG_SCALE ::
+   *   FT_SUBGLYPH_FLAG_XY_SCALE ::
+   *   FT_SUBGLYPH_FLAG_2X2 ::
+   *   FT_SUBGLYPH_FLAG_USE_MY_METRICS ::
+   *
+   */
+#define FT_SUBGLYPH_FLAG_ARGS_ARE_WORDS          1
+#define FT_SUBGLYPH_FLAG_ARGS_ARE_XY_VALUES      2
+#define FT_SUBGLYPH_FLAG_ROUND_XY_TO_GRID        4
+#define FT_SUBGLYPH_FLAG_SCALE                   8
+#define FT_SUBGLYPH_FLAG_XY_SCALE             0x40
+#define FT_SUBGLYPH_FLAG_2X2                  0x80
+#define FT_SUBGLYPH_FLAG_USE_MY_METRICS      0x200
+
+
+  /*************************************************************************
+   *
+   * @func:
+   *   FT_Get_SubGlyph_Info
+   *
+   * @description:
+   *   Retrieve a description of a given subglyph.  Only use it if
+   *   `glyph->format' is @FT_GLYPH_FORMAT_COMPOSITE, or an error is
+   *   returned.
+   *
+   * @input:
+   *   glyph ::
+   *     The source glyph slot.
+   *
+   *   sub_index ::
+   *     The index of subglyph.  Must be less than `glyph->num_subglyphs'.
+   *
+   * @output:
+   *   p_index ::
+   *     The glyph index of the subglyph.
+   *
+   *   p_flags ::
+   *     The subglyph flags, see @FT_SUBGLYPH_FLAG_XXX.
+   *
+   *   p_arg1 ::
+   *     The subglyph's first argument (if any).
+   *
+   *   p_arg2 ::
+   *     The subglyph's second argument (if any).
+   *
+   *   p_transform ::
+   *     The subglyph transformation (if any).
+   *
+   * @return:
+   *   FreeType error code.  0 means success.
+   *
+   * @note:
+   *   The values of `*p_arg1', `*p_arg2', and `*p_transform' must be
+   *   interpreted depending on the flags returned in `*p_flags'.  See the
+   *   TrueType specification for details.
+   *
+   */
+  FT_EXPORT( FT_Error )
+  FT_Get_SubGlyph_Info( FT_GlyphSlot  glyph,
+                        FT_UInt       sub_index,
+                        FT_Int       *p_index,
+                        FT_UInt      *p_flags,
+                        FT_Int       *p_arg1,
+                        FT_Int       *p_arg2,
+                        FT_Matrix    *p_transform );
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Section>                                                             */
+  /*    computations                                                       */
+  /*                                                                       */
+  /* <Title>                                                               */
+  /*    Computations                                                       */
+  /*                                                                       */
+  /* <Abstract>                                                            */
+  /*    Crunching fixed numbers and vectors.                               */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    This section contains various functions used to perform            */
+  /*    computations on 16.16 fixed-float numbers or 2d vectors.           */
+  /*                                                                       */
+  /* <Order>                                                               */
+  /*    FT_MulDiv                                                          */
+  /*    FT_MulFix                                                          */
+  /*    FT_DivFix                                                          */
+  /*    FT_RoundFix                                                        */
+  /*    FT_CeilFix                                                         */
+  /*    FT_FloorFix                                                        */
+  /*    FT_Vector_Transform                                                */
+  /*    FT_Matrix_Multiply                                                 */
+  /*    FT_Matrix_Invert                                                   */
+  /*                                                                       */
+  /*************************************************************************/
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FT_MulDiv                                                          */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    A very simple function used to perform the computation `(a*b)/c'   */
+  /*    with maximal accuracy (it uses a 64-bit intermediate integer       */
+  /*    whenever necessary).                                               */
+  /*                                                                       */
+  /*    This function isn't necessarily as fast as some processor specific */
+  /*    operations, but is at least completely portable.                   */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    a :: The first multiplier.                                         */
+  /*    b :: The second multiplier.                                        */
+  /*    c :: The divisor.                                                  */
+  /*                                                                       */
+  /* <Return>                                                              */
+  /*    The result of `(a*b)/c'.  This function never traps when trying to */
+  /*    divide by zero; it simply returns `MaxInt' or `MinInt' depending   */
+  /*    on the signs of `a' and `b'.                                       */
+  /*                                                                       */
+  FT_EXPORT( FT_Long )
+  FT_MulDiv( FT_Long  a,
+             FT_Long  b,
+             FT_Long  c );
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FT_MulFix                                                          */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    A very simple function used to perform the computation             */
+  /*    `(a*b)/0x10000' with maximal accuracy.  Most of the time this is   */
+  /*    used to multiply a given value by a 16.16 fixed float factor.      */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    a :: The first multiplier.                                         */
+  /*    b :: The second multiplier.  Use a 16.16 factor here whenever      */
+  /*         possible (see note below).                                    */
+  /*                                                                       */
+  /* <Return>                                                              */
+  /*    The result of `(a*b)/0x10000'.                                     */
+  /*                                                                       */
+  /* <Note>                                                                */
+  /*    This function has been optimized for the case where the absolute   */
+  /*    value of `a' is less than 2048, and `b' is a 16.16 scaling factor. */
+  /*    As this happens mainly when scaling from notional units to         */
+  /*    fractional pixels in FreeType, it resulted in noticeable speed     */
+  /*    improvements between versions 2.x and 1.x.                         */
+  /*                                                                       */
+  /*    As a conclusion, always try to place a 16.16 factor as the         */
+  /*    _second_ argument of this function; this can make a great          */
+  /*    difference.                                                        */
+  /*                                                                       */
+  FT_EXPORT( FT_Long )
+  FT_MulFix( FT_Long  a,
+             FT_Long  b );
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FT_DivFix                                                          */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    A very simple function used to perform the computation             */
+  /*    `(a*0x10000)/b' with maximal accuracy.  Most of the time, this is  */
+  /*    used to divide a given value by a 16.16 fixed float factor.        */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    a :: The first multiplier.                                         */
+  /*    b :: The second multiplier.  Use a 16.16 factor here whenever      */
+  /*         possible (see note below).                                    */
+  /*                                                                       */
+  /* <Return>                                                              */
+  /*    The result of `(a*0x10000)/b'.                                     */
+  /*                                                                       */
+  /* <Note>                                                                */
+  /*    The optimization for FT_DivFix() is simple: If (a << 16) fits in   */
+  /*    32 bits, then the division is computed directly.  Otherwise, we    */
+  /*    use a specialized version of @FT_MulDiv.                           */
+  /*                                                                       */
+  FT_EXPORT( FT_Long )
+  FT_DivFix( FT_Long  a,
+             FT_Long  b );
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FT_RoundFix                                                        */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    A very simple function used to round a 16.16 fixed number.         */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    a :: The number to be rounded.                                     */
+  /*                                                                       */
+  /* <Return>                                                              */
+  /*    The result of `(a + 0x8000) & -0x10000'.                           */
+  /*                                                                       */
+  FT_EXPORT( FT_Fixed )
+  FT_RoundFix( FT_Fixed  a );
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FT_CeilFix                                                         */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    A very simple function used to compute the ceiling function of a   */
+  /*    16.16 fixed number.                                                */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    a :: The number for which the ceiling function is to be computed.  */
+  /*                                                                       */
+  /* <Return>                                                              */
+  /*    The result of `(a + 0x10000 - 1) & -0x10000'.                      */
+  /*                                                                       */
+  FT_EXPORT( FT_Fixed )
+  FT_CeilFix( FT_Fixed  a );
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FT_FloorFix                                                        */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    A very simple function used to compute the floor function of a     */
+  /*    16.16 fixed number.                                                */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    a :: The number for which the floor function is to be computed.    */
+  /*                                                                       */
+  /* <Return>                                                              */
+  /*    The result of `a & -0x10000'.                                      */
+  /*                                                                       */
+  FT_EXPORT( FT_Fixed )
+  FT_FloorFix( FT_Fixed  a );
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FT_Vector_Transform                                                */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    Transform a single vector through a 2x2 matrix.                    */
+  /*                                                                       */
+  /* <InOut>                                                               */
+  /*    vector :: The target vector to transform.                          */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    matrix :: A pointer to the source 2x2 matrix.                      */
+  /*                                                                       */
+  /* <Note>                                                                */
+  /*    The result is undefined if either `vector' or `matrix' is invalid. */
+  /*                                                                       */
+  FT_EXPORT( void )
+  FT_Vector_Transform( FT_Vector*        vec,
+                       const FT_Matrix*  matrix );
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Section>                                                             */
+  /*    version                                                            */
+  /*                                                                       */
+  /* <Title>                                                               */
+  /*    FreeType Version                                                   */
+  /*                                                                       */
+  /* <Abstract>                                                            */
+  /*    Functions and macros related to FreeType versions.                 */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    Note that those functions and macros are of limited use because    */
+  /*    even a new release of FreeType with only documentation changes     */
+  /*    increases the version number.                                      */
+  /*                                                                       */
+  /*************************************************************************/
+
+
+  /*************************************************************************
+   *
+   *  @enum:
+   *    FREETYPE_XXX
+   *
+   *  @description:
+   *    These three macros identify the FreeType source code version.
+   *    Use @FT_Library_Version to access them at runtime.
+   *
+   *  @values:
+   *    FREETYPE_MAJOR :: The major version number.
+   *    FREETYPE_MINOR :: The minor version number.
+   *    FREETYPE_PATCH :: The patch level.
+   *
+   *  @note:
+   *    The version number of FreeType if built as a dynamic link library
+   *    with the `libtool' package is _not_ controlled by these three
+   *    macros.
+   */
+#define FREETYPE_MAJOR  2
+#define FREETYPE_MINOR  3
+#define FREETYPE_PATCH  5
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FT_Library_Version                                                 */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    Return the version of the FreeType library being used.  This is    */
+  /*    useful when dynamically linking to the library, since one cannot   */
+  /*    use the macros @FREETYPE_MAJOR, @FREETYPE_MINOR, and               */
+  /*    @FREETYPE_PATCH.                                                   */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    library :: A source library handle.                                */
+  /*                                                                       */
+  /* <Output>                                                              */
+  /*    amajor  :: The major version number.                               */
+  /*                                                                       */
+  /*    aminor  :: The minor version number.                               */
+  /*                                                                       */
+  /*    apatch  :: The patch version number.                               */
+  /*                                                                       */
+  /* <Note>                                                                */
+  /*    The reason why this function takes a `library' argument is because */
+  /*    certain programs implement library initialization in a custom way  */
+  /*    that doesn't use @FT_Init_FreeType.                                */
+  /*                                                                       */
+  /*    In such cases, the library version might not be available before   */
+  /*    the library object has been created.                               */
+  /*                                                                       */
+  FT_EXPORT( void )
+  FT_Library_Version( FT_Library   library,
+                      FT_Int      *amajor,
+                      FT_Int      *aminor,
+                      FT_Int      *apatch );
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FT_Face_CheckTrueTypePatents                                       */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    Parse all bytecode instructions of a TrueType font file to check   */
+  /*    whether any of the patented opcodes are used.  This is only useful */
+  /*    if you want to be able to use the unpatented hinter with           */
+  /*    fonts that do *not* use these opcodes.                             */
+  /*                                                                       */
+  /*    Note that this function parses *all* glyph instructions in the     */
+  /*    font file, which may be slow.                                      */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    face :: A face handle.                                             */
+  /*                                                                       */
+  /* <Return>                                                              */
+  /*    1 if this is a TrueType font that uses one of the patented         */
+  /*    opcodes, 0 otherwise.                                              */
+  /*                                                                       */
+  /* <Since>                                                               */
+  /*    2.3.5                                                              */
+  /*                                                                       */
+  FT_EXPORT( FT_Bool )
+  FT_Face_CheckTrueTypePatents( FT_Face  face );
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FT_Face_SetUnpatentedHinting                                       */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    Enable or disable the unpatented hinter for a given face.          */
+  /*    Only enable it if you have determined that the face doesn't        */
+  /*    use any patented opcodes (see @FT_Face_CheckTrueTypePatents).      */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    face  :: A face handle.                                            */
+  /*                                                                       */
+  /*    value :: New boolean setting.                                      */
+  /*                                                                       */
+  /* <Return>                                                              */
+  /*    The old setting value.  This will always be false if this is not   */
+  /*    a SFNT font, or if the unpatented hinter is not compiled in this   */
+  /*    instance of the library.                                           */
+  /*                                                                       */
+  /* <Since>                                                               */
+  /*    2.3.5                                                              */
+  /*                                                                       */
+  FT_EXPORT( FT_Bool )
+  FT_Face_SetUnpatentedHinting( FT_Face  face,
+                                FT_Bool  value );
+
+  /* */
+
+
+FT_END_HEADER
+
+#endif /* __FREETYPE_H__ */
+
+
+/* END */

+ 94 - 0
include/freetype/ftbbox.h

@@ -0,0 +1,94 @@
+/***************************************************************************/
+/*                                                                         */
+/*  ftbbox.h                                                               */
+/*                                                                         */
+/*    FreeType exact bbox computation (specification).                     */
+/*                                                                         */
+/*  Copyright 1996-2001, 2003 by                                           */
+/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */
+/*                                                                         */
+/*  This file is part of the FreeType project, and may only be used,       */
+/*  modified, and distributed under the terms of the FreeType project      */
+/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */
+/*  this file you indicate that you have read the license and              */
+/*  understand and accept it fully.                                        */
+/*                                                                         */
+/***************************************************************************/
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* This component has a _single_ role: to compute exact outline bounding */
+  /* boxes.                                                                */
+  /*                                                                       */
+  /* It is separated from the rest of the engine for various technical     */
+  /* reasons.  It may well be integrated in `ftoutln' later.               */
+  /*                                                                       */
+  /*************************************************************************/
+
+
+#ifndef __FTBBOX_H__
+#define __FTBBOX_H__
+
+
+#include <ft2build.h>
+#include FT_FREETYPE_H
+
+#ifdef FREETYPE_H
+#error "freetype.h of FreeType 1 has been loaded!"
+#error "Please fix the directory search order for header files"
+#error "so that freetype.h of FreeType 2 is found first."
+#endif
+
+
+FT_BEGIN_HEADER
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Section>                                                             */
+  /*    outline_processing                                                 */
+  /*                                                                       */
+  /*************************************************************************/
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FT_Outline_Get_BBox                                                */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    Computes the exact bounding box of an outline.  This is slower     */
+  /*    than computing the control box.  However, it uses an advanced      */
+  /*    algorithm which returns _very_ quickly when the two boxes          */
+  /*    coincide.  Otherwise, the outline Bézier arcs are walked over to   */
+  /*    extract their extrema.                                             */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    outline :: A pointer to the source outline.                        */
+  /*                                                                       */
+  /* <Output>                                                              */
+  /*    abbox   :: The outline's exact bounding box.                       */
+  /*                                                                       */
+  /* <Return>                                                              */
+  /*    FreeType error code.  0 means success.                             */
+  /*                                                                       */
+  FT_EXPORT( FT_Error )
+  FT_Outline_Get_BBox( FT_Outline*  outline,
+                       FT_BBox     *abbox );
+
+
+  /* */
+
+
+FT_END_HEADER
+
+#endif /* __FTBBOX_H__ */
+
+
+/* END */
+
+
+/* Local Variables: */
+/* coding: utf-8    */
+/* End:             */

+ 200 - 0
include/freetype/ftbdf.h

@@ -0,0 +1,200 @@
+/***************************************************************************/
+/*                                                                         */
+/*  ftbdf.h                                                                */
+/*                                                                         */
+/*    FreeType API for accessing BDF-specific strings (specification).     */
+/*                                                                         */
+/*  Copyright 2002, 2003, 2004, 2006 by                                    */
+/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */
+/*                                                                         */
+/*  This file is part of the FreeType project, and may only be used,       */
+/*  modified, and distributed under the terms of the FreeType project      */
+/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */
+/*  this file you indicate that you have read the license and              */
+/*  understand and accept it fully.                                        */
+/*                                                                         */
+/***************************************************************************/
+
+
+#ifndef __FTBDF_H__
+#define __FTBDF_H__
+
+#include <ft2build.h>
+#include FT_FREETYPE_H
+
+#ifdef FREETYPE_H
+#error "freetype.h of FreeType 1 has been loaded!"
+#error "Please fix the directory search order for header files"
+#error "so that freetype.h of FreeType 2 is found first."
+#endif
+
+
+FT_BEGIN_HEADER
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Section>                                                             */
+  /*    bdf_fonts                                                          */
+  /*                                                                       */
+  /* <Title>                                                               */
+  /*    BDF Files                                                          */
+  /*                                                                       */
+  /* <Abstract>                                                            */
+  /*    BDF specific API.                                                  */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    This section contains the declaration of BDF specific functions.   */
+  /*                                                                       */
+  /*************************************************************************/
+
+
+ /**********************************************************************
+  *
+  * @enum:
+  *    FT_PropertyType
+  *
+  * @description:
+  *    A list of BDF property types.
+  *
+  * @values:
+  *    BDF_PROPERTY_TYPE_NONE ::
+  *      Value 0 is used to indicate a missing property.
+  *
+  *    BDF_PROPERTY_TYPE_ATOM ::
+  *      Property is a string atom.
+  *
+  *    BDF_PROPERTY_TYPE_INTEGER ::
+  *      Property is a 32-bit signed integer.
+  *
+  *    BDF_PROPERTY_TYPE_CARDINAL ::
+  *      Property is a 32-bit unsigned integer.
+  */
+  typedef enum  BDF_PropertyType_
+  {
+    BDF_PROPERTY_TYPE_NONE     = 0,
+    BDF_PROPERTY_TYPE_ATOM     = 1,
+    BDF_PROPERTY_TYPE_INTEGER  = 2,
+    BDF_PROPERTY_TYPE_CARDINAL = 3
+
+  } BDF_PropertyType;
+
+
+ /**********************************************************************
+  *
+  * @type:
+  *    BDF_Property
+  *
+  * @description:
+  *    A handle to a @BDF_PropertyRec structure to model a given
+  *    BDF/PCF property.
+  */
+  typedef struct BDF_PropertyRec_*  BDF_Property;
+
+
+ /**********************************************************************
+  *
+  * @struct:
+  *    BDF_PropertyRec
+  *
+  * @description:
+  *    This structure models a given BDF/PCF property.
+  *
+  * @fields:
+  *    type ::
+  *      The property type.
+  *
+  *    u.atom ::
+  *      The atom string, if type is @BDF_PROPERTY_TYPE_ATOM.
+  *
+  *    u.integer ::
+  *      A signed integer, if type is @BDF_PROPERTY_TYPE_INTEGER.
+  *
+  *    u.cardinal ::
+  *      An unsigned integer, if type is @BDF_PROPERTY_TYPE_CARDINAL.
+  */
+  typedef struct  BDF_PropertyRec_
+  {
+    BDF_PropertyType  type;
+    union {
+      const char*     atom;
+      FT_Int32        integer;
+      FT_UInt32       cardinal;
+
+    } u;
+
+  } BDF_PropertyRec;
+
+
+ /**********************************************************************
+  *
+  * @function:
+  *    FT_Get_BDF_Charset_ID
+  *
+  * @description:
+  *    Retrieves a BDF font character set identity, according to
+  *    the BDF specification.
+  *
+  * @input:
+  *    face ::
+  *       A handle to the input face.
+  *
+  * @output:
+  *    acharset_encoding ::
+  *       Charset encoding, as a C string, owned by the face.
+  *
+  *    acharset_registry ::
+  *       Charset registry, as a C string, owned by the face.
+  *
+  * @return:
+  *   FreeType error code.  0 means success.
+  *
+  * @note:
+  *   This function only works with BDF faces, returning an error otherwise.
+  */
+  FT_EXPORT( FT_Error )
+  FT_Get_BDF_Charset_ID( FT_Face       face,
+                         const char*  *acharset_encoding,
+                         const char*  *acharset_registry );
+
+
+ /**********************************************************************
+  *
+  * @function:
+  *    FT_Get_BDF_Property
+  *
+  * @description:
+  *    Retrieves a BDF property from a BDF or PCF font file.
+  *
+  * @input:
+  *    face :: A handle to the input face.
+  *
+  *    name :: The property name.
+  *
+  * @output:
+  *    aproperty :: The property.
+  *
+  * @return:
+  *   FreeType error code.  0 means success.
+  *
+  * @note:
+  *   This function works with BDF _and_ PCF fonts.  It returns an error
+  *   otherwise.  It also returns an error if the property is not in the
+  *   font.
+  *
+  *   In case of error, `aproperty->type' is always set to
+  *   @BDF_PROPERTY_TYPE_NONE.
+  */
+  FT_EXPORT( FT_Error )
+  FT_Get_BDF_Property( FT_Face           face,
+                       const char*       prop_name,
+                       BDF_PropertyRec  *aproperty );
+
+ /* */
+
+FT_END_HEADER
+
+#endif /* __FTBDF_H__ */
+
+
+/* END */

+ 206 - 0
include/freetype/ftbitmap.h

@@ -0,0 +1,206 @@
+/***************************************************************************/
+/*                                                                         */
+/*  ftbitmap.h                                                             */
+/*                                                                         */
+/*    FreeType utility functions for converting 1bpp, 2bpp, 4bpp, and 8bpp */
+/*    bitmaps into 8bpp format (specification).                            */
+/*                                                                         */
+/*  Copyright 2004, 2005, 2006 by                                          */
+/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */
+/*                                                                         */
+/*  This file is part of the FreeType project, and may only be used,       */
+/*  modified, and distributed under the terms of the FreeType project      */
+/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */
+/*  this file you indicate that you have read the license and              */
+/*  understand and accept it fully.                                        */
+/*                                                                         */
+/***************************************************************************/
+
+
+#ifndef __FTBITMAP_H__
+#define __FTBITMAP_H__
+
+
+#include <ft2build.h>
+#include FT_FREETYPE_H
+
+#ifdef FREETYPE_H
+#error "freetype.h of FreeType 1 has been loaded!"
+#error "Please fix the directory search order for header files"
+#error "so that freetype.h of FreeType 2 is found first."
+#endif
+
+
+FT_BEGIN_HEADER
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Section>                                                             */
+  /*    bitmap_handling                                                    */
+  /*                                                                       */
+  /* <Title>                                                               */
+  /*    Bitmap Handling                                                    */
+  /*                                                                       */
+  /* <Abstract>                                                            */
+  /*    Handling FT_Bitmap objects.                                        */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    This section contains functions for converting FT_Bitmap objects.  */
+  /*                                                                       */
+  /*************************************************************************/
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FT_Bitmap_New                                                      */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    Initialize a pointer to an @FT_Bitmap structure.                   */
+  /*                                                                       */
+  /* <InOut>                                                               */
+  /*    abitmap :: A pointer to the bitmap structure.                      */
+  /*                                                                       */
+  FT_EXPORT( void )
+  FT_Bitmap_New( FT_Bitmap  *abitmap );
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FT_Bitmap_Copy                                                     */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    Copies an bitmap into another one.                                 */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    library :: A handle to a library object.                           */
+  /*                                                                       */
+  /*    source  :: A handle to the source bitmap.                          */
+  /*                                                                       */
+  /* <Output>                                                              */
+  /*    target  :: A handle to the target bitmap.                          */
+  /*                                                                       */
+  /* <Return>                                                              */
+  /*    FreeType error code.  0 means success.                             */
+  /*                                                                       */
+  FT_EXPORT( FT_Error )
+  FT_Bitmap_Copy( FT_Library        library,
+                  const FT_Bitmap  *source,
+                  FT_Bitmap        *target);
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FT_Bitmap_Embolden                                                 */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    Embolden a bitmap.  The new bitmap will be about `xStrength'       */
+  /*    pixels wider and `yStrength' pixels higher.  The left and bottom   */
+  /*    borders are kept unchanged.                                        */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    library   :: A handle to a library object.                         */
+  /*                                                                       */
+  /*    xStrength :: How strong the glyph is emboldened horizontally.      */
+  /*                 Expressed in 26.6 pixel format.                       */
+  /*                                                                       */
+  /*    yStrength :: How strong the glyph is emboldened vertically.        */
+  /*                 Expressed in 26.6 pixel format.                       */
+  /*                                                                       */
+  /* <InOut>                                                               */
+  /*    bitmap    :: A handle to the target bitmap.                        */
+  /*                                                                       */
+  /* <Return>                                                              */
+  /*    FreeType error code.  0 means success.                             */
+  /*                                                                       */
+  /* <Note>                                                                */
+  /*    The current implementation restricts `xStrength' to be less than   */
+  /*    or equal to 8 if bitmap is of pixel_mode @FT_PIXEL_MODE_MONO.      */
+  /*                                                                       */
+  /*    If you want to embolden the bitmap owned by a @FT_GlyphSlotRec,    */
+  /*    you should call `FT_GlyphSlot_Own_Bitmap' on the slot first.       */
+  /*                                                                       */
+  FT_EXPORT( FT_Error )
+  FT_Bitmap_Embolden( FT_Library  library,
+                      FT_Bitmap*  bitmap,
+                      FT_Pos      xStrength,
+                      FT_Pos      yStrength );
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FT_Bitmap_Convert                                                  */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    Convert a bitmap object with depth 1bpp, 2bpp, 4bpp, or 8bpp to a  */
+  /*    bitmap object with depth 8bpp, making the number of used bytes per */
+  /*    line (a.k.a. the `pitch') a multiple of `alignment'.               */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    library   :: A handle to a library object.                         */
+  /*                                                                       */
+  /*    source    :: The source bitmap.                                    */
+  /*                                                                       */
+  /*    alignment :: The pitch of the bitmap is a multiple of this         */
+  /*                 parameter.  Common values are 1, 2, or 4.             */
+  /*                                                                       */
+  /* <Output>                                                              */
+  /*    target    :: The target bitmap.                                    */
+  /*                                                                       */
+  /* <Return>                                                              */
+  /*    FreeType error code.  0 means success.                             */
+  /*                                                                       */
+  /* <Note>                                                                */
+  /*    It is possible to call @FT_Bitmap_Convert multiple times without   */
+  /*    calling @FT_Bitmap_Done (the memory is simply reallocated).        */
+  /*                                                                       */
+  /*    Use @FT_Bitmap_Done to finally remove the bitmap object.           */
+  /*                                                                       */
+  /*    The `library' argument is taken to have access to FreeType's       */
+  /*    memory handling functions.                                         */
+  /*                                                                       */
+  FT_EXPORT( FT_Error )
+  FT_Bitmap_Convert( FT_Library        library,
+                     const FT_Bitmap  *source,
+                     FT_Bitmap        *target,
+                     FT_Int            alignment );
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FT_Bitmap_Done                                                     */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    Destroy a bitmap object created with @FT_Bitmap_New.               */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    library :: A handle to a library object.                           */
+  /*                                                                       */
+  /*    bitmap  :: The bitmap object to be freed.                          */
+  /*                                                                       */
+  /* <Return>                                                              */
+  /*    FreeType error code.  0 means success.                             */
+  /*                                                                       */
+  /* <Note>                                                                */
+  /*    The `library' argument is taken to have access to FreeType's       */
+  /*    memory handling functions.                                         */
+  /*                                                                       */
+  FT_EXPORT( FT_Error )
+  FT_Bitmap_Done( FT_Library  library,
+                  FT_Bitmap  *bitmap );
+
+
+  /* */
+
+
+FT_END_HEADER
+
+#endif /* __FTBITMAP_H__ */
+
+
+/* END */

+ 1110 - 0
include/freetype/ftcache.h

@@ -0,0 +1,1110 @@
+/***************************************************************************/
+/*                                                                         */
+/*  ftcache.h                                                              */
+/*                                                                         */
+/*    FreeType Cache subsystem (specification).                            */
+/*                                                                         */
+/*  Copyright 1996-2001, 2002, 2003, 2004, 2005, 2006, 2007 by             */
+/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */
+/*                                                                         */
+/*  This file is part of the FreeType project, and may only be used,       */
+/*  modified, and distributed under the terms of the FreeType project      */
+/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */
+/*  this file you indicate that you have read the license and              */
+/*  understand and accept it fully.                                        */
+/*                                                                         */
+/***************************************************************************/
+
+
+#ifndef __FTCACHE_H__
+#define __FTCACHE_H__
+
+
+#include <ft2build.h>
+#include FT_GLYPH_H
+
+
+FT_BEGIN_HEADER
+
+
+  /*************************************************************************
+   *
+   * <Section>
+   *    cache_subsystem
+   *
+   * <Title>
+   *    Cache Sub-System
+   *
+   * <Abstract>
+   *    How to cache face, size, and glyph data with FreeType 2.
+   *
+   * <Description>
+   *   This section describes the FreeType 2 cache sub-system, which is used
+   *   to limit the number of concurrently opened @FT_Face and @FT_Size
+   *   objects, as well as caching information like character maps and glyph
+   *   images while limiting their maximum memory usage.
+   *
+   *   Note that all types and functions begin with the `FTC_' prefix.
+   *
+   *   The cache is highly portable and thus doesn't know anything about the
+   *   fonts installed on your system, or how to access them.  This implies
+   *   the following scheme:
+   *
+   *   First, available or installed font faces are uniquely identified by
+   *   @FTC_FaceID values, provided to the cache by the client.  Note that
+   *   the cache only stores and compares these values, and doesn't try to
+   *   interpret them in any way.
+   *
+   *   Second, the cache calls, only when needed, a client-provided function
+   *   to convert a @FTC_FaceID into a new @FT_Face object.  The latter is
+   *   then completely managed by the cache, including its termination
+   *   through @FT_Done_Face.
+   *
+   *   Clients are free to map face IDs to anything else.  The most simple
+   *   usage is to associate them to a (pathname,face_index) pair that is
+   *   used to call @FT_New_Face.  However, more complex schemes are also
+   *   possible.
+   *
+   *   Note that for the cache to work correctly, the face ID values must be
+   *   *persistent*, which means that the contents they point to should not
+   *   change at runtime, or that their value should not become invalid.
+   *
+   *   If this is unavoidable (e.g., when a font is uninstalled at runtime),
+   *   you should call @FTC_Manager_RemoveFaceID as soon as possible, to let
+   *   the cache get rid of any references to the old @FTC_FaceID it may
+   *   keep internally.  Failure to do so will lead to incorrect behaviour
+   *   or even crashes.
+   *
+   *   To use the cache, start with calling @FTC_Manager_New to create a new
+   *   @FTC_Manager object, which models a single cache instance.  You can
+   *   then look up @FT_Face and @FT_Size objects with
+   *   @FTC_Manager_LookupFace and @FTC_Manager_LookupSize, respectively.
+   *
+   *   If you want to use the charmap caching, call @FTC_CMapCache_New, then
+   *   later use @FTC_CMapCache_Lookup to perform the equivalent of
+   *   @FT_Get_Char_Index, only much faster.
+   *
+   *   If you want to use the @FT_Glyph caching, call @FTC_ImageCache, then
+   *   later use @FTC_ImageCache_Lookup to retrieve the corresponding
+   *   @FT_Glyph objects from the cache.
+   *
+   *   If you need lots of small bitmaps, it is much more memory efficient
+   *   to call @FTC_SBitCache_New followed by @FTC_SBitCache_Lookup.  This
+   *   returns @FTC_SBitRec structures, which are used to store small
+   *   bitmaps directly.  (A small bitmap is one whose metrics and
+   *   dimensions all fit into 8-bit integers).
+   *
+   *   We hope to also provide a kerning cache in the near future.
+   *
+   *
+   * <Order>
+   *   FTC_Manager
+   *   FTC_FaceID
+   *   FTC_Face_Requester
+   *
+   *   FTC_Manager_New
+   *   FTC_Manager_Reset
+   *   FTC_Manager_Done
+   *   FTC_Manager_LookupFace
+   *   FTC_Manager_LookupSize
+   *   FTC_Manager_RemoveFaceID
+   *
+   *   FTC_Node
+   *   FTC_Node_Unref
+   *
+   *   FTC_ImageCache
+   *   FTC_ImageCache_New
+   *   FTC_ImageCache_Lookup
+   *
+   *   FTC_SBit
+   *   FTC_SBitCache
+   *   FTC_SBitCache_New
+   *   FTC_SBitCache_Lookup
+   *
+   *   FTC_CMapCache
+   *   FTC_CMapCache_New
+   *   FTC_CMapCache_Lookup
+   *
+   *************************************************************************/
+
+
+  /*************************************************************************/
+  /*************************************************************************/
+  /*************************************************************************/
+  /*****                                                               *****/
+  /*****                    BASIC TYPE DEFINITIONS                     *****/
+  /*****                                                               *****/
+  /*************************************************************************/
+  /*************************************************************************/
+  /*************************************************************************/
+
+
+  /*************************************************************************
+   *
+   * @type: FTC_FaceID
+   *
+   * @description:
+   *   An opaque pointer type that is used to identity face objects.  The
+   *   contents of such objects is application-dependent.
+   *
+   *   These pointers are typically used to point to a user-defined
+   *   structure containing a font file path, and face index.
+   *
+   * @note:
+   *   Never use NULL as a valid @FTC_FaceID.
+   *
+   *   Face IDs are passed by the client to the cache manager, which calls,
+   *   when needed, the @FTC_Face_Requester to translate them into new
+   *   @FT_Face objects.
+   *
+   *   If the content of a given face ID changes at runtime, or if the value
+   *   becomes invalid (e.g., when uninstalling a font), you should
+   *   immediately call @FTC_Manager_RemoveFaceID before any other cache
+   *   function.
+   *
+   *   Failure to do so will result in incorrect behaviour or even
+   *   memory leaks and crashes.
+   */
+  typedef struct FTC_FaceIDRec_*  FTC_FaceID;
+
+
+  /************************************************************************
+   *
+   * @functype:
+   *   FTC_Face_Requester
+   *
+   * @description:
+   *   A callback function provided by client applications.  It is used by
+   *   the cache manager to translate a given @FTC_FaceID into a new valid
+   *   @FT_Face object, on demand.
+   *
+   * <Input>
+   *   face_id ::
+   *     The face ID to resolve.
+   *
+   *   library ::
+   *     A handle to a FreeType library object.
+   *
+   *   req_data ::
+   *     Application-provided request data (see note below).
+   *
+   * <Output>
+   *   aface ::
+   *     A new @FT_Face handle.
+   *
+   * <Return>
+   *   FreeType error code.  0 means success.
+   *
+   * <Note>
+   *   The third parameter `req_data' is the same as the one passed by the
+   *   client when @FTC_Manager_New is called.
+   *
+   *   The face requester should not perform funny things on the returned
+   *   face object, like creating a new @FT_Size for it, or setting a
+   *   transformation through @FT_Set_Transform!
+   */
+  typedef FT_Error
+  (*FTC_Face_Requester)( FTC_FaceID  face_id,
+                         FT_Library  library,
+                         FT_Pointer  request_data,
+                         FT_Face*    aface );
+
+ /* */
+
+#define FT_POINTER_TO_ULONG( p )  ( (FT_ULong)(FT_Pointer)(p) )
+
+#define FTC_FACE_ID_HASH( i )                                \
+          ((FT_UInt32)(( FT_POINTER_TO_ULONG( i ) >> 3 ) ^   \
+                       ( FT_POINTER_TO_ULONG( i ) << 7 ) ) )
+
+
+  /*************************************************************************/
+  /*************************************************************************/
+  /*************************************************************************/
+  /*****                                                               *****/
+  /*****                      CACHE MANAGER OBJECT                     *****/
+  /*****                                                               *****/
+  /*************************************************************************/
+  /*************************************************************************/
+  /*************************************************************************/
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Type>                                                                */
+  /*    FTC_Manager                                                        */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    This object corresponds to one instance of the cache-subsystem.    */
+  /*    It is used to cache one or more @FT_Face objects, along with       */
+  /*    corresponding @FT_Size objects.                                    */
+  /*                                                                       */
+  /*    The manager intentionally limits the total number of opened        */
+  /*    @FT_Face and @FT_Size objects to control memory usage.  See the    */
+  /*    `max_faces' and `max_sizes' parameters of @FTC_Manager_New.        */
+  /*                                                                       */
+  /*    The manager is also used to cache `nodes' of various types while   */
+  /*    limiting their total memory usage.                                 */
+  /*                                                                       */
+  /*    All limitations are enforced by keeping lists of managed objects   */
+  /*    in most-recently-used order, and flushing old nodes to make room   */
+  /*    for new ones.                                                      */
+  /*                                                                       */
+  typedef struct FTC_ManagerRec_*  FTC_Manager;
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Type>                                                                */
+  /*    FTC_Node                                                           */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    An opaque handle to a cache node object.  Each cache node is       */
+  /*    reference-counted.  A node with a count of 0 might be flushed      */
+  /*    out of a full cache whenever a lookup request is performed.        */
+  /*                                                                       */
+  /*    If you lookup nodes, you have the ability to `acquire' them, i.e., */
+  /*    to increment their reference count.  This will prevent the node    */
+  /*    from being flushed out of the cache until you explicitly `release' */
+  /*    it (see @FTC_Node_Unref).                                          */
+  /*                                                                       */
+  /*    See also @FTC_SBitCache_Lookup and @FTC_ImageCache_Lookup.         */
+  /*                                                                       */
+  typedef struct FTC_NodeRec_*  FTC_Node;
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FTC_Manager_New                                                    */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    Creates a new cache manager.                                       */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    library   :: The parent FreeType library handle to use.            */
+  /*                                                                       */
+  /*    max_faces :: Maximum number of opened @FT_Face objects managed by  */
+  /*                 this cache instance.  Use 0 for defaults.             */
+  /*                                                                       */
+  /*    max_sizes :: Maximum number of opened @FT_Size objects managed by  */
+  /*                 this cache instance.  Use 0 for defaults.             */
+  /*                                                                       */
+  /*    max_bytes :: Maximum number of bytes to use for cached data nodes. */
+  /*                 Use 0 for defaults.  Note that this value does not    */
+  /*                 account for managed @FT_Face and @FT_Size objects.    */
+  /*                                                                       */
+  /*    requester :: An application-provided callback used to translate    */
+  /*                 face IDs into real @FT_Face objects.                  */
+  /*                                                                       */
+  /*    req_data  :: A generic pointer that is passed to the requester     */
+  /*                 each time it is called (see @FTC_Face_Requester).     */
+  /*                                                                       */
+  /* <Output>                                                              */
+  /*    amanager  :: A handle to a new manager object.  0 in case of       */
+  /*                 failure.                                              */
+  /*                                                                       */
+  /* <Return>                                                              */
+  /*    FreeType error code.  0 means success.                             */
+  /*                                                                       */
+  FT_EXPORT( FT_Error )
+  FTC_Manager_New( FT_Library          library,
+                   FT_UInt             max_faces,
+                   FT_UInt             max_sizes,
+                   FT_ULong            max_bytes,
+                   FTC_Face_Requester  requester,
+                   FT_Pointer          req_data,
+                   FTC_Manager        *amanager );
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FTC_Manager_Reset                                                  */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    Empties a given cache manager.  This simply gets rid of all the    */
+  /*    currently cached @FT_Face and @FT_Size objects within the manager. */
+  /*                                                                       */
+  /* <InOut>                                                               */
+  /*    manager :: A handle to the manager.                                */
+  /*                                                                       */
+  FT_EXPORT( void )
+  FTC_Manager_Reset( FTC_Manager  manager );
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FTC_Manager_Done                                                   */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    Destroys a given manager after emptying it.                        */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    manager :: A handle to the target cache manager object.            */
+  /*                                                                       */
+  FT_EXPORT( void )
+  FTC_Manager_Done( FTC_Manager  manager );
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FTC_Manager_LookupFace                                             */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    Retrieves the @FT_Face object that corresponds to a given face ID  */
+  /*    through a cache manager.                                           */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    manager :: A handle to the cache manager.                          */
+  /*                                                                       */
+  /*    face_id :: The ID of the face object.                              */
+  /*                                                                       */
+  /* <Output>                                                              */
+  /*    aface   :: A handle to the face object.                            */
+  /*                                                                       */
+  /* <Return>                                                              */
+  /*    FreeType error code.  0 means success.                             */
+  /*                                                                       */
+  /* <Note>                                                                */
+  /*    The returned @FT_Face object is always owned by the manager.  You  */
+  /*    should never try to discard it yourself.                           */
+  /*                                                                       */
+  /*    The @FT_Face object doesn't necessarily have a current size object */
+  /*    (i.e., face->size can be 0).  If you need a specific `font size',  */
+  /*    use @FTC_Manager_LookupSize instead.                               */
+  /*                                                                       */
+  /*    Never change the face's transformation matrix (i.e., never call    */
+  /*    the @FT_Set_Transform function) on a returned face!  If you need   */
+  /*    to transform glyphs, do it yourself after glyph loading.           */
+  /*                                                                       */
+  /*    When you perform a lookup, out-of-memory errors are detected       */
+  /*    _within_ the lookup and force incremental flushes of the cache     */
+  /*    until enough memory is released for the lookup to succeed.         */
+  /*                                                                       */
+  /*    If a lookup fails with `FT_Err_Out_Of_Memory' the cache has        */
+  /*    already been completely flushed, and still no memory was available */
+  /*    for the operation.                                                 */
+  /*                                                                       */
+  FT_EXPORT( FT_Error )
+  FTC_Manager_LookupFace( FTC_Manager  manager,
+                          FTC_FaceID   face_id,
+                          FT_Face     *aface );
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Struct>                                                              */
+  /*    FTC_ScalerRec                                                      */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    A structure used to describe a given character size in either      */
+  /*    pixels or points to the cache manager.  See                        */
+  /*    @FTC_Manager_LookupSize.                                           */
+  /*                                                                       */
+  /* <Fields>                                                              */
+  /*    face_id :: The source face ID.                                     */
+  /*                                                                       */
+  /*    width   :: The character width.                                    */
+  /*                                                                       */
+  /*    height  :: The character height.                                   */
+  /*                                                                       */
+  /*    pixel   :: A Boolean.  If 1, the `width' and `height' fields are   */
+  /*               interpreted as integer pixel character sizes.           */
+  /*               Otherwise, they are expressed as 1/64th of points.      */
+  /*                                                                       */
+  /*    x_res   :: Only used when `pixel' is value 0 to indicate the       */
+  /*               horizontal resolution in dpi.                           */
+  /*                                                                       */
+  /*    y_res   :: Only used when `pixel' is value 0 to indicate the       */
+  /*               vertical resolution in dpi.                             */
+  /*                                                                       */
+  /* <Note>                                                                */
+  /*    This type is mainly used to retrieve @FT_Size objects through the  */
+  /*    cache manager.                                                     */
+  /*                                                                       */
+  typedef struct  FTC_ScalerRec_
+  {
+    FTC_FaceID  face_id;
+    FT_UInt     width;
+    FT_UInt     height;
+    FT_Int      pixel;
+    FT_UInt     x_res;
+    FT_UInt     y_res;
+
+  } FTC_ScalerRec, *FTC_Scaler;
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FTC_Manager_LookupSize                                             */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    Retrieve the @FT_Size object that corresponds to a given           */
+  /*    @FTC_ScalerRec pointer through a cache manager.                    */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    manager :: A handle to the cache manager.                          */
+  /*                                                                       */
+  /*    scaler  :: A scaler handle.                                        */
+  /*                                                                       */
+  /* <Output>                                                              */
+  /*    asize   :: A handle to the size object.                            */
+  /*                                                                       */
+  /* <Return>                                                              */
+  /*    FreeType error code.  0 means success.                             */
+  /*                                                                       */
+  /* <Note>                                                                */
+  /*    The returned @FT_Size object is always owned by the manager.  You  */
+  /*    should never try to discard it by yourself.                        */
+  /*                                                                       */
+  /*    You can access the parent @FT_Face object simply as `size->face'   */
+  /*    if you need it.  Note that this object is also owned by the        */
+  /*    manager.                                                           */
+  /*                                                                       */
+  /* <Note>                                                                */
+  /*    When you perform a lookup, out-of-memory errors are detected       */
+  /*    _within_ the lookup and force incremental flushes of the cache     */
+  /*    until enough memory is released for the lookup to succeed.         */
+  /*                                                                       */
+  /*    If a lookup fails with `FT_Err_Out_Of_Memory' the cache has        */
+  /*    already been completely flushed, and still no memory is available  */
+  /*    for the operation.                                                 */
+  /*                                                                       */
+  FT_EXPORT( FT_Error )
+  FTC_Manager_LookupSize( FTC_Manager  manager,
+                          FTC_Scaler   scaler,
+                          FT_Size     *asize );
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FTC_Node_Unref                                                     */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    Decrement a cache node's internal reference count.  When the count */
+  /*    reaches 0, it is not destroyed but becomes eligible for subsequent */
+  /*    cache flushes.                                                     */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    node    :: The cache node handle.                                  */
+  /*                                                                       */
+  /*    manager :: The cache manager handle.                               */
+  /*                                                                       */
+  FT_EXPORT( void )
+  FTC_Node_Unref( FTC_Node     node,
+                  FTC_Manager  manager );
+
+
+  /*************************************************************************
+   *
+   * @function:
+   *   FTC_Manager_RemoveFaceID
+   *
+   * @description:
+   *   A special function used to indicate to the cache manager that
+   *   a given @FTC_FaceID is no longer valid, either because its
+   *   content changed, or because it was deallocated or uninstalled.
+   *
+   * @input:
+   *   manager ::
+   *     The cache manager handle.
+   *
+   *   face_id ::
+   *     The @FTC_FaceID to be removed.
+   *
+   * @note:
+   *   This function flushes all nodes from the cache corresponding to this
+   *   `face_id', with the exception of nodes with a non-null reference
+   *   count.
+   *
+   *   Such nodes are however modified internally so as to never appear
+   *   in later lookups with the same `face_id' value, and to be immediately
+   *   destroyed when released by all their users.
+   *
+   */
+  FT_EXPORT( void )
+  FTC_Manager_RemoveFaceID( FTC_Manager  manager,
+                            FTC_FaceID   face_id );
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Section>                                                             */
+  /*    cache_subsystem                                                    */
+  /*                                                                       */
+  /*************************************************************************/
+
+  /*************************************************************************
+   *
+   * @type:
+   *   FTC_CMapCache
+   *
+   * @description:
+   *   An opaque handle used to model a charmap cache.  This cache is to
+   *   hold character codes -> glyph indices mappings.
+   *
+   */
+  typedef struct FTC_CMapCacheRec_*  FTC_CMapCache;
+
+
+  /*************************************************************************
+   *
+   * @function:
+   *   FTC_CMapCache_New
+   *
+   * @description:
+   *   Create a new charmap cache.
+   *
+   * @input:
+   *   manager ::
+   *     A handle to the cache manager.
+   *
+   * @output:
+   *   acache ::
+   *     A new cache handle.  NULL in case of error.
+   *
+   * @return:
+   *   FreeType error code.  0 means success.
+   *
+   * @note:
+   *   Like all other caches, this one will be destroyed with the cache
+   *   manager.
+   *
+   */
+  FT_EXPORT( FT_Error )
+  FTC_CMapCache_New( FTC_Manager     manager,
+                     FTC_CMapCache  *acache );
+
+
+  /************************************************************************
+   *
+   * @function:
+   *   FTC_CMapCache_Lookup
+   *
+   * @description:
+   *   Translate a character code into a glyph index, using the charmap
+   *   cache.
+   *
+   * @input:
+   *   cache ::
+   *     A charmap cache handle.
+   *
+   *   face_id ::
+   *     The source face ID.
+   *
+   *   cmap_index ::
+   *     The index of the charmap in the source face.
+   *
+   *   char_code ::
+   *     The character code (in the corresponding charmap).
+   *
+   * @return:
+   *    Glyph index.  0 means `no glyph'.
+   *
+   */
+  FT_EXPORT( FT_UInt )
+  FTC_CMapCache_Lookup( FTC_CMapCache  cache,
+                        FTC_FaceID     face_id,
+                        FT_Int         cmap_index,
+                        FT_UInt32      char_code );
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Section>                                                             */
+  /*    cache_subsystem                                                    */
+  /*                                                                       */
+  /*************************************************************************/
+
+
+  /*************************************************************************/
+  /*************************************************************************/
+  /*************************************************************************/
+  /*****                                                               *****/
+  /*****                       IMAGE CACHE OBJECT                      *****/
+  /*****                                                               *****/
+  /*************************************************************************/
+  /*************************************************************************/
+  /*************************************************************************/
+
+
+  /*************************************************************************
+   *
+   * @struct:
+   *   FTC_ImageTypeRec
+   *
+   * @description:
+   *   A structure used to model the type of images in a glyph cache.
+   *
+   * @fields:
+   *   face_id ::
+   *     The face ID.
+   *
+   *   width ::
+   *     The width in pixels.
+   *
+   *   height ::
+   *     The height in pixels.
+   *
+   *   flags ::
+   *     The load flags, as in @FT_Load_Glyph.
+   *
+   */
+  typedef struct  FTC_ImageTypeRec_
+  {
+    FTC_FaceID  face_id;
+    FT_Int      width;
+    FT_Int      height;
+    FT_Int32    flags;
+
+  } FTC_ImageTypeRec;
+
+
+  /*************************************************************************
+   *
+   * @type:
+   *   FTC_ImageType
+   *
+   * @description:
+   *   A handle to an @FTC_ImageTypeRec structure.
+   *
+   */
+  typedef struct FTC_ImageTypeRec_*  FTC_ImageType;
+
+
+  /* */
+
+
+#define FTC_IMAGE_TYPE_COMPARE( d1, d2 )      \
+          ( (d1)->face_id == (d2)->face_id && \
+            (d1)->width   == (d2)->width   && \
+            (d1)->flags   == (d2)->flags   )
+
+#define FTC_IMAGE_TYPE_HASH( d )                          \
+          (FT_UFast)( FTC_FACE_ID_HASH( (d)->face_id )  ^ \
+                      ( (d)->width << 8 ) ^ (d)->height ^ \
+                      ( (d)->flags << 4 )               )
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Type>                                                                */
+  /*    FTC_ImageCache                                                     */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    A handle to an glyph image cache object.  They are designed to     */
+  /*    hold many distinct glyph images while not exceeding a certain      */
+  /*    memory threshold.                                                  */
+  /*                                                                       */
+  typedef struct FTC_ImageCacheRec_*  FTC_ImageCache;
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FTC_ImageCache_New                                                 */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    Creates a new glyph image cache.                                   */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    manager :: The parent manager for the image cache.                 */
+  /*                                                                       */
+  /* <Output>                                                              */
+  /*    acache  :: A handle to the new glyph image cache object.           */
+  /*                                                                       */
+  /* <Return>                                                              */
+  /*    FreeType error code.  0 means success.                             */
+  /*                                                                       */
+  FT_EXPORT( FT_Error )
+  FTC_ImageCache_New( FTC_Manager      manager,
+                      FTC_ImageCache  *acache );
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FTC_ImageCache_Lookup                                              */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    Retrieves a given glyph image from a glyph image cache.            */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    cache  :: A handle to the source glyph image cache.                */
+  /*                                                                       */
+  /*    type   :: A pointer to a glyph image type descriptor.              */
+  /*                                                                       */
+  /*    gindex :: The glyph index to retrieve.                             */
+  /*                                                                       */
+  /* <Output>                                                              */
+  /*    aglyph :: The corresponding @FT_Glyph object.  0 in case of        */
+  /*              failure.                                                 */
+  /*                                                                       */
+  /*    anode  :: Used to return the address of of the corresponding cache */
+  /*              node after incrementing its reference count (see note    */
+  /*              below).                                                  */
+  /*                                                                       */
+  /* <Return>                                                              */
+  /*    FreeType error code.  0 means success.                             */
+  /*                                                                       */
+  /* <Note>                                                                */
+  /*    The returned glyph is owned and managed by the glyph image cache.  */
+  /*    Never try to transform or discard it manually!  You can however    */
+  /*    create a copy with @FT_Glyph_Copy and modify the new one.          */
+  /*                                                                       */
+  /*    If `anode' is _not_ NULL, it receives the address of the cache     */
+  /*    node containing the glyph image, after increasing its reference    */
+  /*    count.  This ensures that the node (as well as the @FT_Glyph) will */
+  /*    always be kept in the cache until you call @FTC_Node_Unref to      */
+  /*    `release' it.                                                      */
+  /*                                                                       */
+  /*    If `anode' is NULL, the cache node is left unchanged, which means  */
+  /*    that the @FT_Glyph could be flushed out of the cache on the next   */
+  /*    call to one of the caching sub-system APIs.  Don't assume that it  */
+  /*    is persistent!                                                     */
+  /*                                                                       */
+  FT_EXPORT( FT_Error )
+  FTC_ImageCache_Lookup( FTC_ImageCache  cache,
+                         FTC_ImageType   type,
+                         FT_UInt         gindex,
+                         FT_Glyph       *aglyph,
+                         FTC_Node       *anode );
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FTC_ImageCache_LookupScaler                                        */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    A variant of @FTC_ImageCache_Lookup that uses an @FTC_ScalerRec    */
+  /*    to specify the face ID and its size.                               */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    cache      :: A handle to the source glyph image cache.            */
+  /*                                                                       */
+  /*    scaler     :: A pointer to a scaler descriptor.                    */
+  /*                                                                       */
+  /*    load_flags :: The corresponding load flags.                        */
+  /*                                                                       */
+  /*    gindex     :: The glyph index to retrieve.                         */
+  /*                                                                       */
+  /* <Output>                                                              */
+  /*    aglyph     :: The corresponding @FT_Glyph object.  0 in case of    */
+  /*                  failure.                                             */
+  /*                                                                       */
+  /*    anode      :: Used to return the address of of the corresponding   */
+  /*                  cache node after incrementing its reference count    */
+  /*                  (see note below).                                    */
+  /*                                                                       */
+  /* <Return>                                                              */
+  /*    FreeType error code.  0 means success.                             */
+  /*                                                                       */
+  /* <Note>                                                                */
+  /*    The returned glyph is owned and managed by the glyph image cache.  */
+  /*    Never try to transform or discard it manually!  You can however    */
+  /*    create a copy with @FT_Glyph_Copy and modify the new one.          */
+  /*                                                                       */
+  /*    If `anode' is _not_ NULL, it receives the address of the cache     */
+  /*    node containing the glyph image, after increasing its reference    */
+  /*    count.  This ensures that the node (as well as the @FT_Glyph) will */
+  /*    always be kept in the cache until you call @FTC_Node_Unref to      */
+  /*    `release' it.                                                      */
+  /*                                                                       */
+  /*    If `anode' is NULL, the cache node is left unchanged, which means  */
+  /*    that the @FT_Glyph could be flushed out of the cache on the next   */
+  /*    call to one of the caching sub-system APIs.  Don't assume that it  */
+  /*    is persistent!                                                     */
+  /*                                                                       */
+  FT_EXPORT( FT_Error )
+  FTC_ImageCache_LookupScaler( FTC_ImageCache  cache,
+                               FTC_Scaler      scaler,
+                               FT_ULong        load_flags,
+                               FT_UInt         gindex,
+                               FT_Glyph       *aglyph,
+                               FTC_Node       *anode );
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Type>                                                                */
+  /*    FTC_SBit                                                           */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    A handle to a small bitmap descriptor.  See the @FTC_SBitRec       */
+  /*    structure for details.                                             */
+  /*                                                                       */
+  typedef struct FTC_SBitRec_*  FTC_SBit;
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Struct>                                                              */
+  /*    FTC_SBitRec                                                        */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    A very compact structure used to describe a small glyph bitmap.    */
+  /*                                                                       */
+  /* <Fields>                                                              */
+  /*    width     :: The bitmap width in pixels.                           */
+  /*                                                                       */
+  /*    height    :: The bitmap height in pixels.                          */
+  /*                                                                       */
+  /*    left      :: The horizontal distance from the pen position to the  */
+  /*                 left bitmap border (a.k.a. `left side bearing', or    */
+  /*                 `lsb').                                               */
+  /*                                                                       */
+  /*    top       :: The vertical distance from the pen position (on the   */
+  /*                 baseline) to the upper bitmap border (a.k.a. `top     */
+  /*                 side bearing').  The distance is positive for upwards */
+  /*                 Y coordinates.                                        */
+  /*                                                                       */
+  /*    format    :: The format of the glyph bitmap (monochrome or gray).  */
+  /*                                                                       */
+  /*    max_grays :: Maximum gray level value (in the range 1 to 255).     */
+  /*                                                                       */
+  /*    pitch     :: The number of bytes per bitmap line.  May be positive */
+  /*                 or negative.                                          */
+  /*                                                                       */
+  /*    xadvance  :: The horizontal advance width in pixels.               */
+  /*                                                                       */
+  /*    yadvance  :: The vertical advance height in pixels.                */
+  /*                                                                       */
+  /*    buffer    :: A pointer to the bitmap pixels.                       */
+  /*                                                                       */
+  typedef struct  FTC_SBitRec_
+  {
+    FT_Byte   width;
+    FT_Byte   height;
+    FT_Char   left;
+    FT_Char   top;
+
+    FT_Byte   format;
+    FT_Byte   max_grays;
+    FT_Short  pitch;
+    FT_Char   xadvance;
+    FT_Char   yadvance;
+
+    FT_Byte*  buffer;
+
+  } FTC_SBitRec;
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Type>                                                                */
+  /*    FTC_SBitCache                                                      */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    A handle to a small bitmap cache.  These are special cache objects */
+  /*    used to store small glyph bitmaps (and anti-aliased pixmaps) in a  */
+  /*    much more efficient way than the traditional glyph image cache     */
+  /*    implemented by @FTC_ImageCache.                                    */
+  /*                                                                       */
+  typedef struct FTC_SBitCacheRec_*  FTC_SBitCache;
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FTC_SBitCache_New                                                  */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    Creates a new cache to store small glyph bitmaps.                  */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    manager :: A handle to the source cache manager.                   */
+  /*                                                                       */
+  /* <Output>                                                              */
+  /*    acache  :: A handle to the new sbit cache.  NULL in case of error. */
+  /*                                                                       */
+  /* <Return>                                                              */
+  /*    FreeType error code.  0 means success.                             */
+  /*                                                                       */
+  FT_EXPORT( FT_Error )
+  FTC_SBitCache_New( FTC_Manager     manager,
+                     FTC_SBitCache  *acache );
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FTC_SBitCache_Lookup                                               */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    Looks up a given small glyph bitmap in a given sbit cache and      */
+  /*    `lock' it to prevent its flushing from the cache until needed.     */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    cache  :: A handle to the source sbit cache.                       */
+  /*                                                                       */
+  /*    type   :: A pointer to the glyph image type descriptor.            */
+  /*                                                                       */
+  /*    gindex :: The glyph index.                                         */
+  /*                                                                       */
+  /* <Output>                                                              */
+  /*    sbit   :: A handle to a small bitmap descriptor.                   */
+  /*                                                                       */
+  /*    anode  :: Used to return the address of of the corresponding cache */
+  /*              node after incrementing its reference count (see note    */
+  /*              below).                                                  */
+  /*                                                                       */
+  /* <Return>                                                              */
+  /*    FreeType error code.  0 means success.                             */
+  /*                                                                       */
+  /* <Note>                                                                */
+  /*    The small bitmap descriptor and its bit buffer are owned by the    */
+  /*    cache and should never be freed by the application.  They might    */
+  /*    as well disappear from memory on the next cache lookup, so don't   */
+  /*    treat them as persistent data.                                     */
+  /*                                                                       */
+  /*    The descriptor's `buffer' field is set to 0 to indicate a missing  */
+  /*    glyph bitmap.                                                      */
+  /*                                                                       */
+  /*    If `anode' is _not_ NULL, it receives the address of the cache     */
+  /*    node containing the bitmap, after increasing its reference count.  */
+  /*    This ensures that the node (as well as the image) will always be   */
+  /*    kept in the cache until you call @FTC_Node_Unref to `release' it.  */
+  /*                                                                       */
+  /*    If `anode' is NULL, the cache node is left unchanged, which means  */
+  /*    that the bitmap could be flushed out of the cache on the next      */
+  /*    call to one of the caching sub-system APIs.  Don't assume that it  */
+  /*    is persistent!                                                     */
+  /*                                                                       */
+  FT_EXPORT( FT_Error )
+  FTC_SBitCache_Lookup( FTC_SBitCache    cache,
+                        FTC_ImageType    type,
+                        FT_UInt          gindex,
+                        FTC_SBit        *sbit,
+                        FTC_Node        *anode );
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FTC_SBitCache_LookupScaler                                         */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    A variant of @FTC_SBitCache_Lookup that uses an @FTC_ScalerRec     */
+  /*    to specify the face ID and its size.                               */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    cache      :: A handle to the source sbit cache.                   */
+  /*                                                                       */
+  /*    scaler     :: A pointer to the scaler descriptor.                  */
+  /*                                                                       */
+  /*    load_flags :: The corresponding load flags.                        */
+  /*                                                                       */
+  /*    gindex     :: The glyph index.                                     */
+  /*                                                                       */
+  /* <Output>                                                              */
+  /*    sbit       :: A handle to a small bitmap descriptor.               */
+  /*                                                                       */
+  /*    anode      :: Used to return the address of of the corresponding   */
+  /*                  cache node after incrementing its reference count    */
+  /*                  (see note below).                                    */
+  /*                                                                       */
+  /* <Return>                                                              */
+  /*    FreeType error code.  0 means success.                             */
+  /*                                                                       */
+  /* <Note>                                                                */
+  /*    The small bitmap descriptor and its bit buffer are owned by the    */
+  /*    cache and should never be freed by the application.  They might    */
+  /*    as well disappear from memory on the next cache lookup, so don't   */
+  /*    treat them as persistent data.                                     */
+  /*                                                                       */
+  /*    The descriptor's `buffer' field is set to 0 to indicate a missing  */
+  /*    glyph bitmap.                                                      */
+  /*                                                                       */
+  /*    If `anode' is _not_ NULL, it receives the address of the cache     */
+  /*    node containing the bitmap, after increasing its reference count.  */
+  /*    This ensures that the node (as well as the image) will always be   */
+  /*    kept in the cache until you call @FTC_Node_Unref to `release' it.  */
+  /*                                                                       */
+  /*    If `anode' is NULL, the cache node is left unchanged, which means  */
+  /*    that the bitmap could be flushed out of the cache on the next      */
+  /*    call to one of the caching sub-system APIs.  Don't assume that it  */
+  /*    is persistent!                                                     */
+  /*                                                                       */
+  FT_EXPORT( FT_Error )
+  FTC_SBitCache_LookupScaler( FTC_SBitCache  cache,
+                              FTC_Scaler     scaler,
+                              FT_ULong       load_flags,
+                              FT_UInt        gindex,
+                              FTC_SBit      *sbit,
+                              FTC_Node      *anode );
+
+
+ /* */
+
+#ifdef FT_CONFIG_OPTION_OLD_INTERNALS
+
+  /*@***********************************************************************/
+  /*                                                                       */
+  /* <Struct>                                                              */
+  /*    FTC_FontRec                                                        */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    A simple structure used to describe a given `font' to the cache    */
+  /*    manager.  Note that a `font' is the combination of a given face    */
+  /*    with a given character size.                                       */
+  /*                                                                       */
+  /* <Fields>                                                              */
+  /*    face_id    :: The ID of the face to use.                           */
+  /*                                                                       */
+  /*    pix_width  :: The character width in integer pixels.               */
+  /*                                                                       */
+  /*    pix_height :: The character height in integer pixels.              */
+  /*                                                                       */
+  typedef struct  FTC_FontRec_
+  {
+    FTC_FaceID  face_id;
+    FT_UShort   pix_width;
+    FT_UShort   pix_height;
+
+  } FTC_FontRec;
+
+
+  /* */
+
+
+#define FTC_FONT_COMPARE( f1, f2 )                  \
+          ( (f1)->face_id    == (f2)->face_id    && \
+            (f1)->pix_width  == (f2)->pix_width  && \
+            (f1)->pix_height == (f2)->pix_height )
+
+#define FTC_FONT_HASH( f )                              \
+          (FT_UInt32)( FTC_FACE_ID_HASH((f)->face_id) ^ \
+                       ((f)->pix_width << 8)          ^ \
+                       ((f)->pix_height)              )
+
+  typedef FTC_FontRec*  FTC_Font;
+
+
+  FT_EXPORT( FT_Error )
+  FTC_Manager_Lookup_Face( FTC_Manager  manager,
+                           FTC_FaceID   face_id,
+                           FT_Face     *aface );
+
+  FT_EXPORT( FT_Error )
+  FTC_Manager_Lookup_Size( FTC_Manager  manager,
+                           FTC_Font     font,
+                           FT_Face     *aface,
+                           FT_Size     *asize );
+
+#endif /* FT_CONFIG_OPTION_OLD_INTERNALS */
+
+
+ /* */
+
+FT_END_HEADER
+
+#endif /* __FTCACHE_H__ */
+
+
+/* END */

+ 100 - 0
include/freetype/ftchapters.h

@@ -0,0 +1,100 @@
+/***************************************************************************/
+/*                                                                         */
+/* This file defines the structure of the FreeType reference.              */
+/* It is used by the python script which generates the HTML files.         */
+/*                                                                         */
+/***************************************************************************/
+
+
+/***************************************************************************/
+/*                                                                         */
+/* <Chapter>                                                               */
+/*    general_remarks                                                      */
+/*                                                                         */
+/* <Title>                                                                 */
+/*    General Remarks                                                      */
+/*                                                                         */
+/* <Sections>                                                              */
+/*    user_allocation                                                      */
+/*                                                                         */
+/***************************************************************************/
+
+
+/***************************************************************************/
+/*                                                                         */
+/* <Chapter>                                                               */
+/*    core_api                                                             */
+/*                                                                         */
+/* <Title>                                                                 */
+/*    Core API                                                             */
+/*                                                                         */
+/* <Sections>                                                              */
+/*    version                                                              */
+/*    basic_types                                                          */
+/*    base_interface                                                       */
+/*    glyph_management                                                     */
+/*    mac_specific                                                         */
+/*    sizes_management                                                     */
+/*    header_file_macros                                                   */
+/*                                                                         */
+/***************************************************************************/
+
+
+/***************************************************************************/
+/*                                                                         */
+/* <Chapter>                                                               */
+/*    format_specific                                                      */
+/*                                                                         */
+/* <Title>                                                                 */
+/*    Format-Specific API                                                  */
+/*                                                                         */
+/* <Sections>                                                              */
+/*    multiple_masters                                                     */
+/*    truetype_tables                                                      */
+/*    type1_tables                                                         */
+/*    sfnt_names                                                           */
+/*    bdf_fonts                                                            */
+/*    pfr_fonts                                                            */
+/*    winfnt_fonts                                                         */
+/*    font_formats                                                         */
+/*    gasp_table                                                           */
+/*                                                                         */
+/***************************************************************************/
+
+
+/***************************************************************************/
+/*                                                                         */
+/* <Chapter>                                                               */
+/*    cache_subsystem                                                      */
+/*                                                                         */
+/* <Title>                                                                 */
+/*    Cache Sub-System                                                     */
+/*                                                                         */
+/* <Sections>                                                              */
+/*    cache_subsystem                                                      */
+/*                                                                         */
+/***************************************************************************/
+
+
+/***************************************************************************/
+/*                                                                         */
+/* <Chapter>                                                               */
+/*    support_api                                                          */
+/*                                                                         */
+/* <Title>                                                                 */
+/*    Support API                                                          */
+/*                                                                         */
+/* <Sections>                                                              */
+/*    computations                                                         */
+/*    list_processing                                                      */
+/*    outline_processing                                                   */
+/*    bitmap_handling                                                      */
+/*    raster                                                               */
+/*    glyph_stroker                                                        */
+/*    system_interface                                                     */
+/*    module_management                                                    */
+/*    gzip                                                                 */
+/*    lzw                                                                  */
+/*    lcd_filtering                                                        */
+/*                                                                         */
+/***************************************************************************/

+ 239 - 0
include/freetype/fterrdef.h

@@ -0,0 +1,239 @@
+/***************************************************************************/
+/*                                                                         */
+/*  fterrdef.h                                                             */
+/*                                                                         */
+/*    FreeType error codes (specification).                                */
+/*                                                                         */
+/*  Copyright 2002, 2004, 2006, 2007 by                                    */
+/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */
+/*                                                                         */
+/*  This file is part of the FreeType project, and may only be used,       */
+/*  modified, and distributed under the terms of the FreeType project      */
+/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */
+/*  this file you indicate that you have read the license and              */
+/*  understand and accept it fully.                                        */
+/*                                                                         */
+/***************************************************************************/
+
+
+  /*******************************************************************/
+  /*******************************************************************/
+  /*****                                                         *****/
+  /*****                LIST OF ERROR CODES/MESSAGES             *****/
+  /*****                                                         *****/
+  /*******************************************************************/
+  /*******************************************************************/
+
+
+  /* You need to define both FT_ERRORDEF_ and FT_NOERRORDEF_ before */
+  /* including this file.                                           */
+
+
+  /* generic errors */
+
+  FT_NOERRORDEF_( Ok,                                        0x00, \
+                  "no error" )
+
+  FT_ERRORDEF_( Cannot_Open_Resource,                        0x01, \
+                "cannot open resource" )
+  FT_ERRORDEF_( Unknown_File_Format,                         0x02, \
+                "unknown file format" )
+  FT_ERRORDEF_( Invalid_File_Format,                         0x03, \
+                "broken file" )
+  FT_ERRORDEF_( Invalid_Version,                             0x04, \
+                "invalid FreeType version" )
+  FT_ERRORDEF_( Lower_Module_Version,                        0x05, \
+                "module version is too low" )
+  FT_ERRORDEF_( Invalid_Argument,                            0x06, \
+                "invalid argument" )
+  FT_ERRORDEF_( Unimplemented_Feature,                       0x07, \
+                "unimplemented feature" )
+  FT_ERRORDEF_( Invalid_Table,                               0x08, \
+                "broken table" )
+  FT_ERRORDEF_( Invalid_Offset,                              0x09, \
+                "broken offset within table" )
+  FT_ERRORDEF_( Array_Too_Large,                             0x0A, \
+                "array allocation size too large" )
+
+  /* glyph/character errors */
+
+  FT_ERRORDEF_( Invalid_Glyph_Index,                         0x10, \
+                "invalid glyph index" )
+  FT_ERRORDEF_( Invalid_Character_Code,                      0x11, \
+                "invalid character code" )
+  FT_ERRORDEF_( Invalid_Glyph_Format,                        0x12, \
+                "unsupported glyph image format" )
+  FT_ERRORDEF_( Cannot_Render_Glyph,                         0x13, \
+                "cannot render this glyph format" )
+  FT_ERRORDEF_( Invalid_Outline,                             0x14, \
+                "invalid outline" )
+  FT_ERRORDEF_( Invalid_Composite,                           0x15, \
+                "invalid composite glyph" )
+  FT_ERRORDEF_( Too_Many_Hints,                              0x16, \
+                "too many hints" )
+  FT_ERRORDEF_( Invalid_Pixel_Size,                          0x17, \
+                "invalid pixel size" )
+
+  /* handle errors */
+
+  FT_ERRORDEF_( Invalid_Handle,                              0x20, \
+                "invalid object handle" )
+  FT_ERRORDEF_( Invalid_Library_Handle,                      0x21, \
+                "invalid library handle" )
+  FT_ERRORDEF_( Invalid_Driver_Handle,                       0x22, \
+                "invalid module handle" )
+  FT_ERRORDEF_( Invalid_Face_Handle,                         0x23, \
+                "invalid face handle" )
+  FT_ERRORDEF_( Invalid_Size_Handle,                         0x24, \
+                "invalid size handle" )
+  FT_ERRORDEF_( Invalid_Slot_Handle,                         0x25, \
+                "invalid glyph slot handle" )
+  FT_ERRORDEF_( Invalid_CharMap_Handle,                      0x26, \
+                "invalid charmap handle" )
+  FT_ERRORDEF_( Invalid_Cache_Handle,                        0x27, \
+                "invalid cache manager handle" )
+  FT_ERRORDEF_( Invalid_Stream_Handle,                       0x28, \
+                "invalid stream handle" )
+
+  /* driver errors */
+
+  FT_ERRORDEF_( Too_Many_Drivers,                            0x30, \
+                "too many modules" )
+  FT_ERRORDEF_( Too_Many_Extensions,                         0x31, \
+                "too many extensions" )
+
+  /* memory errors */
+
+  FT_ERRORDEF_( Out_Of_Memory,                               0x40, \
+                "out of memory" )
+  FT_ERRORDEF_( Unlisted_Object,                             0x41, \
+                "unlisted object" )
+
+  /* stream errors */
+
+  FT_ERRORDEF_( Cannot_Open_Stream,                          0x51, \
+                "cannot open stream" )
+  FT_ERRORDEF_( Invalid_Stream_Seek,                         0x52, \
+                "invalid stream seek" )
+  FT_ERRORDEF_( Invalid_Stream_Skip,                         0x53, \
+                "invalid stream skip" )
+  FT_ERRORDEF_( Invalid_Stream_Read,                         0x54, \
+                "invalid stream read" )
+  FT_ERRORDEF_( Invalid_Stream_Operation,                    0x55, \
+                "invalid stream operation" )
+  FT_ERRORDEF_( Invalid_Frame_Operation,                     0x56, \
+                "invalid frame operation" )
+  FT_ERRORDEF_( Nested_Frame_Access,                         0x57, \
+                "nested frame access" )
+  FT_ERRORDEF_( Invalid_Frame_Read,                          0x58, \
+                "invalid frame read" )
+
+  /* raster errors */
+
+  FT_ERRORDEF_( Raster_Uninitialized,                        0x60, \
+                "raster uninitialized" )
+  FT_ERRORDEF_( Raster_Corrupted,                            0x61, \
+                "raster corrupted" )
+  FT_ERRORDEF_( Raster_Overflow,                             0x62, \
+                "raster overflow" )
+  FT_ERRORDEF_( Raster_Negative_Height,                      0x63, \
+                "negative height while rastering" )
+
+  /* cache errors */
+
+  FT_ERRORDEF_( Too_Many_Caches,                             0x70, \
+                "too many registered caches" )
+
+  /* TrueType and SFNT errors */
+
+  FT_ERRORDEF_( Invalid_Opcode,                              0x80, \
+                "invalid opcode" )
+  FT_ERRORDEF_( Too_Few_Arguments,                           0x81, \
+                "too few arguments" )
+  FT_ERRORDEF_( Stack_Overflow,                              0x82, \
+                "stack overflow" )
+  FT_ERRORDEF_( Code_Overflow,                               0x83, \
+                "code overflow" )
+  FT_ERRORDEF_( Bad_Argument,                                0x84, \
+                "bad argument" )
+  FT_ERRORDEF_( Divide_By_Zero,                              0x85, \
+                "division by zero" )
+  FT_ERRORDEF_( Invalid_Reference,                           0x86, \
+                "invalid reference" )
+  FT_ERRORDEF_( Debug_OpCode,                                0x87, \
+                "found debug opcode" )
+  FT_ERRORDEF_( ENDF_In_Exec_Stream,                         0x88, \
+                "found ENDF opcode in execution stream" )
+  FT_ERRORDEF_( Nested_DEFS,                                 0x89, \
+                "nested DEFS" )
+  FT_ERRORDEF_( Invalid_CodeRange,                           0x8A, \
+                "invalid code range" )
+  FT_ERRORDEF_( Execution_Too_Long,                          0x8B, \
+                "execution context too long" )
+  FT_ERRORDEF_( Too_Many_Function_Defs,                      0x8C, \
+                "too many function definitions" )
+  FT_ERRORDEF_( Too_Many_Instruction_Defs,                   0x8D, \
+                "too many instruction definitions" )
+  FT_ERRORDEF_( Table_Missing,                               0x8E, \
+                "SFNT font table missing" )
+  FT_ERRORDEF_( Horiz_Header_Missing,                        0x8F, \
+                "horizontal header (hhea) table missing" )
+  FT_ERRORDEF_( Locations_Missing,                           0x90, \
+                "locations (loca) table missing" )
+  FT_ERRORDEF_( Name_Table_Missing,                          0x91, \
+                "name table missing" )
+  FT_ERRORDEF_( CMap_Table_Missing,                          0x92, \
+                "character map (cmap) table missing" )
+  FT_ERRORDEF_( Hmtx_Table_Missing,                          0x93, \
+                "horizontal metrics (hmtx) table missing" )
+  FT_ERRORDEF_( Post_Table_Missing,                          0x94, \
+                "PostScript (post) table missing" )
+  FT_ERRORDEF_( Invalid_Horiz_Metrics,                       0x95, \
+                "invalid horizontal metrics" )
+  FT_ERRORDEF_( Invalid_CharMap_Format,                      0x96, \
+                "invalid character map (cmap) format" )
+  FT_ERRORDEF_( Invalid_PPem,                                0x97, \
+                "invalid ppem value" )
+  FT_ERRORDEF_( Invalid_Vert_Metrics,                        0x98, \
+                "invalid vertical metrics" )
+  FT_ERRORDEF_( Could_Not_Find_Context,                      0x99, \
+                "could not find context" )
+  FT_ERRORDEF_( Invalid_Post_Table_Format,                   0x9A, \
+                "invalid PostScript (post) table format" )
+  FT_ERRORDEF_( Invalid_Post_Table,                          0x9B, \
+                "invalid PostScript (post) table" )
+
+  /* CFF, CID, and Type 1 errors */
+
+  FT_ERRORDEF_( Syntax_Error,                                0xA0, \
+                "opcode syntax error" )
+  FT_ERRORDEF_( Stack_Underflow,                             0xA1, \
+                "argument stack underflow" )
+  FT_ERRORDEF_( Ignore,                                      0xA2, \
+                "ignore" )
+
+  /* BDF errors */
+
+  FT_ERRORDEF_( Missing_Startfont_Field,                     0xB0, \
+                "`STARTFONT' field missing" )
+  FT_ERRORDEF_( Missing_Font_Field,                          0xB1, \
+                "`FONT' field missing" )
+  FT_ERRORDEF_( Missing_Size_Field,                          0xB2, \
+                "`SIZE' field missing" )
+  FT_ERRORDEF_( Missing_Chars_Field,                         0xB3, \
+                "`CHARS' field missing" )
+  FT_ERRORDEF_( Missing_Startchar_Field,                     0xB4, \
+                "`STARTCHAR' field missing" )
+  FT_ERRORDEF_( Missing_Encoding_Field,                      0xB5, \
+                "`ENCODING' field missing" )
+  FT_ERRORDEF_( Missing_Bbx_Field,                           0xB6, \
+                "`BBX' field missing" )
+  FT_ERRORDEF_( Bbx_Too_Big,                                 0xB7, \
+                "`BBX' too big" )
+  FT_ERRORDEF_( Corrupted_Font_Header,                       0xB8, \
+                "Font header corrupted or missing fields" )
+  FT_ERRORDEF_( Corrupted_Font_Glyphs,                       0xB9, \
+                "Font glyphs corrupted or missing fields" )
+
+
+/* END */

+ 206 - 0
include/freetype/fterrors.h

@@ -0,0 +1,206 @@
+/***************************************************************************/
+/*                                                                         */
+/*  fterrors.h                                                             */
+/*                                                                         */
+/*    FreeType error code handling (specification).                        */
+/*                                                                         */
+/*  Copyright 1996-2001, 2002, 2004, 2007 by                               */
+/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */
+/*                                                                         */
+/*  This file is part of the FreeType project, and may only be used,       */
+/*  modified, and distributed under the terms of the FreeType project      */
+/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */
+/*  this file you indicate that you have read the license and              */
+/*  understand and accept it fully.                                        */
+/*                                                                         */
+/***************************************************************************/
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* This special header file is used to define the handling of FT2        */
+  /* enumeration constants.  It can also be used to generate error message */
+  /* strings with a small macro trick explained below.                     */
+  /*                                                                       */
+  /* I - Error Formats                                                     */
+  /* -----------------                                                     */
+  /*                                                                       */
+  /*   The configuration macro FT_CONFIG_OPTION_USE_MODULE_ERRORS can be   */
+  /*   defined in ftoption.h in order to make the higher byte indicate     */
+  /*   the module where the error has happened (this is not compatible     */
+  /*   with standard builds of FreeType 2).  You can then use the macro    */
+  /*   FT_ERROR_BASE macro to extract the generic error code from an       */
+  /*   FT_Error value.                                                     */
+  /*                                                                       */
+  /*                                                                       */
+  /* II - Error Message strings                                            */
+  /* --------------------------                                            */
+  /*                                                                       */
+  /*   The error definitions below are made through special macros that    */
+  /*   allow client applications to build a table of error message strings */
+  /*   if they need it.  The strings are not included in a normal build of */
+  /*   FreeType 2 to save space (most client applications do not use       */
+  /*   them).                                                              */
+  /*                                                                       */
+  /*   To do so, you have to define the following macros before including  */
+  /*   this file:                                                          */
+  /*                                                                       */
+  /*   FT_ERROR_START_LIST ::                                              */
+  /*     This macro is called before anything else to define the start of  */
+  /*     the error list.  It is followed by several FT_ERROR_DEF calls     */
+  /*     (see below).                                                      */
+  /*                                                                       */
+  /*   FT_ERROR_DEF( e, v, s ) ::                                          */
+  /*     This macro is called to define one single error.                  */
+  /*     `e' is the error code identifier (e.g. FT_Err_Invalid_Argument).  */
+  /*     `v' is the error numerical value.                                 */
+  /*     `s' is the corresponding error string.                            */
+  /*                                                                       */
+  /*   FT_ERROR_END_LIST ::                                                */
+  /*     This macro ends the list.                                         */
+  /*                                                                       */
+  /*   Additionally, you have to undefine __FTERRORS_H__ before #including */
+  /*   this file.                                                          */
+  /*                                                                       */
+  /*   Here is a simple example:                                           */
+  /*                                                                       */
+  /*     {                                                                 */
+  /*       #undef __FTERRORS_H__                                           */
+  /*       #define FT_ERRORDEF( e, v, s )  { e, s },                       */
+  /*       #define FT_ERROR_START_LIST     {                               */
+  /*       #define FT_ERROR_END_LIST       { 0, 0 } };                     */
+  /*                                                                       */
+  /*       const struct                                                    */
+  /*       {                                                               */
+  /*         int          err_code;                                        */
+  /*         const char*  err_msg;                                         */
+  /*       } ft_errors[] =                                                 */
+  /*                                                                       */
+  /*       #include FT_ERRORS_H                                            */
+  /*     }                                                                 */
+  /*                                                                       */
+  /*************************************************************************/
+
+
+#ifndef __FTERRORS_H__
+#define __FTERRORS_H__
+
+
+  /* include module base error codes */
+#include FT_MODULE_ERRORS_H
+
+
+  /*******************************************************************/
+  /*******************************************************************/
+  /*****                                                         *****/
+  /*****                       SETUP MACROS                      *****/
+  /*****                                                         *****/
+  /*******************************************************************/
+  /*******************************************************************/
+
+
+#undef  FT_NEED_EXTERN_C
+
+#undef  FT_ERR_XCAT
+#undef  FT_ERR_CAT
+
+#define FT_ERR_XCAT( x, y )  x ## y
+#define FT_ERR_CAT( x, y )   FT_ERR_XCAT( x, y )
+
+
+  /* FT_ERR_PREFIX is used as a prefix for error identifiers. */
+  /* By default, we use `FT_Err_'.                            */
+  /*                                                          */
+#ifndef FT_ERR_PREFIX
+#define FT_ERR_PREFIX  FT_Err_
+#endif
+
+
+  /* FT_ERR_BASE is used as the base for module-specific errors. */
+  /*                                                             */
+#ifdef FT_CONFIG_OPTION_USE_MODULE_ERRORS
+
+#ifndef FT_ERR_BASE
+#define FT_ERR_BASE  FT_Mod_Err_Base
+#endif
+
+#else
+
+#undef FT_ERR_BASE
+#define FT_ERR_BASE  0
+
+#endif /* FT_CONFIG_OPTION_USE_MODULE_ERRORS */
+
+
+  /* If FT_ERRORDEF is not defined, we need to define a simple */
+  /* enumeration type.                                         */
+  /*                                                           */
+#ifndef FT_ERRORDEF
+
+#define FT_ERRORDEF( e, v, s )  e = v,
+#define FT_ERROR_START_LIST     enum {
+#define FT_ERROR_END_LIST       FT_ERR_CAT( FT_ERR_PREFIX, Max ) };
+
+#ifdef __cplusplus
+#define FT_NEED_EXTERN_C
+  extern "C" {
+#endif
+
+#endif /* !FT_ERRORDEF */
+
+
+  /* this macro is used to define an error */
+#define FT_ERRORDEF_( e, v, s )   \
+          FT_ERRORDEF( FT_ERR_CAT( FT_ERR_PREFIX, e ), v + FT_ERR_BASE, s )
+
+  /* this is only used for <module>_Err_Ok, which must be 0! */
+#define FT_NOERRORDEF_( e, v, s ) \
+          FT_ERRORDEF( FT_ERR_CAT( FT_ERR_PREFIX, e ), v, s )
+
+
+#ifdef FT_ERROR_START_LIST
+  FT_ERROR_START_LIST
+#endif
+
+
+  /* now include the error codes */
+#include FT_ERROR_DEFINITIONS_H
+
+
+#ifdef FT_ERROR_END_LIST
+  FT_ERROR_END_LIST
+#endif
+
+
+  /*******************************************************************/
+  /*******************************************************************/
+  /*****                                                         *****/
+  /*****                      SIMPLE CLEANUP                     *****/
+  /*****                                                         *****/
+  /*******************************************************************/
+  /*******************************************************************/
+
+#ifdef FT_NEED_EXTERN_C
+  }
+#endif
+
+#undef FT_ERROR_START_LIST
+#undef FT_ERROR_END_LIST
+
+#undef FT_ERRORDEF
+#undef FT_ERRORDEF_
+#undef FT_NOERRORDEF_
+
+#undef FT_NEED_EXTERN_C
+#undef FT_ERR_CONCAT
+#undef FT_ERR_BASE
+
+  /* FT_KEEP_ERR_PREFIX is needed for ftvalid.h */
+#ifndef FT_KEEP_ERR_PREFIX
+#undef FT_ERR_PREFIX
+#endif
+
+#endif /* __FTERRORS_H__ */
+
+
+/* END */

+ 113 - 0
include/freetype/ftgasp.h

@@ -0,0 +1,113 @@
+/***************************************************************************/
+/*                                                                         */
+/*  ftgasp.h                                                               */
+/*                                                                         */
+/*    Access of TrueType's `gasp' table (specification).                   */
+/*                                                                         */
+/*  Copyright 2007 by                                                      */
+/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */
+/*                                                                         */
+/*  This file is part of the FreeType project, and may only be used,       */
+/*  modified, and distributed under the terms of the FreeType project      */
+/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */
+/*  this file you indicate that you have read the license and              */
+/*  understand and accept it fully.                                        */
+/*                                                                         */
+/***************************************************************************/
+
+
+#ifndef _FT_GASP_H_
+#define _FT_GASP_H_
+
+#include <ft2build.h>
+#include FT_FREETYPE_H
+
+  /***************************************************************************
+   *
+   * @section:
+   *   gasp_table
+   *
+   * @title:
+   *   Gasp Table
+   *
+   * @abstract:
+   *   Retrieving TrueType `gasp' table entries
+   *
+   * @description:
+   *   The function @FT_Get_Gasp can be used to query a TrueType or OpenType
+   *   font for specific entries in their `gasp' table, if any.  This is
+   *   mainly useful when implementing native TrueType hinting with the
+   *   bytecode interpreter to duplicate the Windows text rendering results.
+   */
+
+  /*************************************************************************
+   *
+   * @enum:
+   *   FT_GASP_XXX
+   *
+   * @description:
+   *   A list of values and/or bit-flags returned by the @FT_Get_Gasp
+   *   function.
+   *
+   * @values:
+   *   FT_GASP_NO_TABLE ::
+   *     This special value means that there is no GASP table in this face.
+   *     It is up to the client to decide what to do.
+   *
+   *   FT_GASP_DO_GRIDFIT ::
+   *     Grid-fitting and hinting should be performed at the specified ppem.
+   *     This *really* means TrueType bytecode interpretation.
+   *
+   *   FT_GASP_DO_GRAY ::
+   *     Anti-aliased rendering should be performed at the specified ppem.
+   *
+   *   FT_GASP_SYMMETRIC_SMOOTHING ::
+   *     Smoothing along multiple axes must be used with ClearType.
+   *
+   *   FT_GASP_SYMMETRIC_GRIDFIT ::
+   *     Grid-fitting must be used with ClearType's symmetric smoothing.
+   *
+   * @note:
+   *   `ClearType' is Microsoft's implementation of LCD rendering, partly
+   *   protected by patents.
+   *
+   * @since:
+   *   2.3.0
+   */
+#define FT_GASP_NO_TABLE               -1
+#define FT_GASP_DO_GRIDFIT           0x01
+#define FT_GASP_DO_GRAY              0x02
+#define FT_GASP_SYMMETRIC_SMOOTHING  0x08
+#define FT_GASP_SYMMETRIC_GRIDFIT    0x10
+
+
+  /*************************************************************************
+   *
+   * @func:
+   *   FT_Get_Gasp
+   *
+   * @description:
+   *   Read the `gasp' table from a TrueType or OpenType font file and
+   *   return the entry corresponding to a given character pixel size.
+   *
+   * @input:
+   *   face :: The source face handle.
+   *   ppem :: The vertical character pixel size.
+   *
+   * @return:
+   *   Bit flags (see @FT_GASP_XXX), or @FT_GASP_NO_TABLE is there is no
+   *   `gasp' table in the face.
+   *
+   * @since:
+   *   2.3.0
+   */
+  FT_EXPORT( FT_Int )
+  FT_Get_Gasp( FT_Face  face,
+               FT_UInt  ppem );
+
+/* */
+
+#endif /* _FT_GASP_H_ */
+
+
+/* END */

+ 575 - 0
include/freetype/ftglyph.h

@@ -0,0 +1,575 @@
+/***************************************************************************/
+/*                                                                         */
+/*  ftglyph.h                                                              */
+/*                                                                         */
+/*    FreeType convenience functions to handle glyphs (specification).     */
+/*                                                                         */
+/*  Copyright 1996-2001, 2002, 2003, 2006 by                               */
+/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */
+/*                                                                         */
+/*  This file is part of the FreeType project, and may only be used,       */
+/*  modified, and distributed under the terms of the FreeType project      */
+/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */
+/*  this file you indicate that you have read the license and              */
+/*  understand and accept it fully.                                        */
+/*                                                                         */
+/***************************************************************************/
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* This file contains the definition of several convenience functions    */
+  /* that can be used by client applications to easily retrieve glyph      */
+  /* bitmaps and outlines from a given face.                               */
+  /*                                                                       */
+  /* These functions should be optional if you are writing a font server   */
+  /* or text layout engine on top of FreeType.  However, they are pretty   */
+  /* handy for many other simple uses of the library.                      */
+  /*                                                                       */
+  /*************************************************************************/
+
+
+#ifndef __FTGLYPH_H__
+#define __FTGLYPH_H__
+
+
+#include <ft2build.h>
+#include FT_FREETYPE_H
+
+#ifdef FREETYPE_H
+#error "freetype.h of FreeType 1 has been loaded!"
+#error "Please fix the directory search order for header files"
+#error "so that freetype.h of FreeType 2 is found first."
+#endif
+
+
+FT_BEGIN_HEADER
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Section>                                                             */
+  /*    glyph_management                                                   */
+  /*                                                                       */
+  /* <Title>                                                               */
+  /*    Glyph Management                                                   */
+  /*                                                                       */
+  /* <Abstract>                                                            */
+  /*    Generic interface to manage individual glyph data.                 */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    This section contains definitions used to manage glyph data        */
+  /*    through generic FT_Glyph objects.  Each of them can contain a      */
+  /*    bitmap, a vector outline, or even images in other formats.         */
+  /*                                                                       */
+  /*************************************************************************/
+
+
+  /* forward declaration to a private type */
+  typedef struct FT_Glyph_Class_  FT_Glyph_Class;
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Type>                                                                */
+  /*    FT_Glyph                                                           */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    Handle to an object used to model generic glyph images.  It is a   */
+  /*    pointer to the @FT_GlyphRec structure and can contain a glyph      */
+  /*    bitmap or pointer.                                                 */
+  /*                                                                       */
+  /* <Note>                                                                */
+  /*    Glyph objects are not owned by the library.  You must thus release */
+  /*    them manually (through @FT_Done_Glyph) _before_ calling            */
+  /*    @FT_Done_FreeType.                                                 */
+  /*                                                                       */
+  typedef struct FT_GlyphRec_*  FT_Glyph;
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Struct>                                                              */
+  /*    FT_GlyphRec                                                        */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    The root glyph structure contains a given glyph image plus its     */
+  /*    advance width in 16.16 fixed float format.                         */
+  /*                                                                       */
+  /* <Fields>                                                              */
+  /*    library :: A handle to the FreeType library object.                */
+  /*                                                                       */
+  /*    clazz   :: A pointer to the glyph's class.  Private.               */
+  /*                                                                       */
+  /*    format  :: The format of the glyph's image.                        */
+  /*                                                                       */
+  /*    advance :: A 16.16 vector that gives the glyph's advance width.    */
+  /*                                                                       */
+  typedef struct  FT_GlyphRec_
+  {
+    FT_Library             library;
+    const FT_Glyph_Class*  clazz;
+    FT_Glyph_Format        format;
+    FT_Vector              advance;
+
+  } FT_GlyphRec;
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Type>                                                                */
+  /*    FT_BitmapGlyph                                                     */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    A handle to an object used to model a bitmap glyph image.  This is */
+  /*    a sub-class of @FT_Glyph, and a pointer to @FT_BitmapGlyphRec.     */
+  /*                                                                       */
+  typedef struct FT_BitmapGlyphRec_*  FT_BitmapGlyph;
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Struct>                                                              */
+  /*    FT_BitmapGlyphRec                                                  */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    A structure used for bitmap glyph images.  This really is a        */
+  /*    `sub-class' of @FT_GlyphRec.                                       */
+  /*                                                                       */
+  /* <Fields>                                                              */
+  /*    root   :: The root @FT_Glyph fields.                               */
+  /*                                                                       */
+  /*    left   :: The left-side bearing, i.e., the horizontal distance     */
+  /*              from the current pen position to the left border of the  */
+  /*              glyph bitmap.                                            */
+  /*                                                                       */
+  /*    top    :: The top-side bearing, i.e., the vertical distance from   */
+  /*              the current pen position to the top border of the glyph  */
+  /*              bitmap.  This distance is positive for upwards-y!        */
+  /*                                                                       */
+  /*    bitmap :: A descriptor for the bitmap.                             */
+  /*                                                                       */
+  /* <Note>                                                                */
+  /*    You can typecast an @FT_Glyph to @FT_BitmapGlyph if you have       */
+  /*    `glyph->format == FT_GLYPH_FORMAT_BITMAP'.  This lets you access   */
+  /*    the bitmap's contents easily.                                      */
+  /*                                                                       */
+  /*    The corresponding pixel buffer is always owned by @FT_BitmapGlyph  */
+  /*    and is thus created and destroyed with it.                         */
+  /*                                                                       */
+  typedef struct  FT_BitmapGlyphRec_
+  {
+    FT_GlyphRec  root;
+    FT_Int       left;
+    FT_Int       top;
+    FT_Bitmap    bitmap;
+
+  } FT_BitmapGlyphRec;
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Type>                                                                */
+  /*    FT_OutlineGlyph                                                    */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    A handle to an object used to model an outline glyph image.  This  */
+  /*    is a sub-class of @FT_Glyph, and a pointer to @FT_OutlineGlyphRec. */
+  /*                                                                       */
+  typedef struct FT_OutlineGlyphRec_*  FT_OutlineGlyph;
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Struct>                                                              */
+  /*    FT_OutlineGlyphRec                                                 */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    A structure used for outline (vectorial) glyph images.  This       */
+  /*    really is a `sub-class' of @FT_GlyphRec.                           */
+  /*                                                                       */
+  /* <Fields>                                                              */
+  /*    root    :: The root @FT_Glyph fields.                              */
+  /*                                                                       */
+  /*    outline :: A descriptor for the outline.                           */
+  /*                                                                       */
+  /* <Note>                                                                */
+  /*    You can typecast a @FT_Glyph to @FT_OutlineGlyph if you have       */
+  /*    `glyph->format == FT_GLYPH_FORMAT_OUTLINE'.  This lets you access  */
+  /*    the outline's content easily.                                      */
+  /*                                                                       */
+  /*    As the outline is extracted from a glyph slot, its coordinates are */
+  /*    expressed normally in 26.6 pixels, unless the flag                 */
+  /*    @FT_LOAD_NO_SCALE was used in @FT_Load_Glyph() or @FT_Load_Char(). */
+  /*                                                                       */
+  /*    The outline's tables are always owned by the object and are        */
+  /*    destroyed with it.                                                 */
+  /*                                                                       */
+  typedef struct  FT_OutlineGlyphRec_
+  {
+    FT_GlyphRec  root;
+    FT_Outline   outline;
+
+  } FT_OutlineGlyphRec;
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FT_Get_Glyph                                                       */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    A function used to extract a glyph image from a slot.              */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    slot   :: A handle to the source glyph slot.                       */
+  /*                                                                       */
+  /* <Output>                                                              */
+  /*    aglyph :: A handle to the glyph object.                            */
+  /*                                                                       */
+  /* <Return>                                                              */
+  /*    FreeType error code.  0 means success.                             */
+  /*                                                                       */
+  FT_EXPORT( FT_Error )
+  FT_Get_Glyph( FT_GlyphSlot  slot,
+                FT_Glyph     *aglyph );
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FT_Glyph_Copy                                                      */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    A function used to copy a glyph image.  Note that the created      */
+  /*    @FT_Glyph object must be released with @FT_Done_Glyph.             */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    source :: A handle to the source glyph object.                     */
+  /*                                                                       */
+  /* <Output>                                                              */
+  /*    target :: A handle to the target glyph object.  0 in case of       */
+  /*              error.                                                   */
+  /*                                                                       */
+  /* <Return>                                                              */
+  /*    FreeType error code.  0 means success.                             */
+  /*                                                                       */
+  FT_EXPORT( FT_Error )
+  FT_Glyph_Copy( FT_Glyph   source,
+                 FT_Glyph  *target );
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FT_Glyph_Transform                                                 */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    Transforms a glyph image if its format is scalable.                */
+  /*                                                                       */
+  /* <InOut>                                                               */
+  /*    glyph  :: A handle to the target glyph object.                     */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    matrix :: A pointer to a 2x2 matrix to apply.                      */
+  /*                                                                       */
+  /*    delta  :: A pointer to a 2d vector to apply.  Coordinates are      */
+  /*              expressed in 1/64th of a pixel.                          */
+  /*                                                                       */
+  /* <Return>                                                              */
+  /*    FreeType error code (if not 0, the glyph format is not scalable).  */
+  /*                                                                       */
+  /* <Note>                                                                */
+  /*    The 2x2 transformation matrix is also applied to the glyph's       */
+  /*    advance vector.                                                    */
+  /*                                                                       */
+  FT_EXPORT( FT_Error )
+  FT_Glyph_Transform( FT_Glyph    glyph,
+                      FT_Matrix*  matrix,
+                      FT_Vector*  delta );
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Enum>                                                                */
+  /*    FT_Glyph_BBox_Mode                                                 */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    The mode how the values of @FT_Glyph_Get_CBox are returned.        */
+  /*                                                                       */
+  /* <Values>                                                              */
+  /*    FT_GLYPH_BBOX_UNSCALED ::                                          */
+  /*      Return unscaled font units.                                      */
+  /*                                                                       */
+  /*    FT_GLYPH_BBOX_SUBPIXELS ::                                         */
+  /*      Return unfitted 26.6 coordinates.                                */
+  /*                                                                       */
+  /*    FT_GLYPH_BBOX_GRIDFIT ::                                           */
+  /*      Return grid-fitted 26.6 coordinates.                             */
+  /*                                                                       */
+  /*    FT_GLYPH_BBOX_TRUNCATE ::                                          */
+  /*      Return coordinates in integer pixels.                            */
+  /*                                                                       */
+  /*    FT_GLYPH_BBOX_PIXELS ::                                            */
+  /*      Return grid-fitted pixel coordinates.                            */
+  /*                                                                       */
+  typedef enum  FT_Glyph_BBox_Mode_
+  {
+    FT_GLYPH_BBOX_UNSCALED  = 0,
+    FT_GLYPH_BBOX_SUBPIXELS = 0,
+    FT_GLYPH_BBOX_GRIDFIT   = 1,
+    FT_GLYPH_BBOX_TRUNCATE  = 2,
+    FT_GLYPH_BBOX_PIXELS    = 3
+
+  } FT_Glyph_BBox_Mode;
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Enum>                                                                */
+  /*    ft_glyph_bbox_xxx                                                  */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    These constants are deprecated.  Use the corresponding             */
+  /*    @FT_Glyph_BBox_Mode values instead.                                */
+  /*                                                                       */
+  /* <Values>                                                              */
+  /*   ft_glyph_bbox_unscaled  :: See @FT_GLYPH_BBOX_UNSCALED.             */
+  /*   ft_glyph_bbox_subpixels :: See @FT_GLYPH_BBOX_SUBPIXELS.            */
+  /*   ft_glyph_bbox_gridfit   :: See @FT_GLYPH_BBOX_GRIDFIT.              */
+  /*   ft_glyph_bbox_truncate  :: See @FT_GLYPH_BBOX_TRUNCATE.             */
+  /*   ft_glyph_bbox_pixels    :: See @FT_GLYPH_BBOX_PIXELS.               */
+  /*                                                                       */
+#define ft_glyph_bbox_unscaled   FT_GLYPH_BBOX_UNSCALED
+#define ft_glyph_bbox_subpixels  FT_GLYPH_BBOX_SUBPIXELS
+#define ft_glyph_bbox_gridfit    FT_GLYPH_BBOX_GRIDFIT
+#define ft_glyph_bbox_truncate   FT_GLYPH_BBOX_TRUNCATE
+#define ft_glyph_bbox_pixels     FT_GLYPH_BBOX_PIXELS
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FT_Glyph_Get_CBox                                                  */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    Return a glyph's `control box'.  The control box encloses all the  */
+  /*    outline's points, including Bézier control points.  Though it      */
+  /*    coincides with the exact bounding box for most glyphs, it can be   */
+  /*    slightly larger in some situations (like when rotating an outline  */
+  /*    which contains Bézier outside arcs).                               */
+  /*                                                                       */
+  /*    Computing the control box is very fast, while getting the bounding */
+  /*    box can take much more time as it needs to walk over all segments  */
+  /*    and arcs in the outline.  To get the latter, you can use the       */
+  /*    `ftbbox' component which is dedicated to this single task.         */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    glyph :: A handle to the source glyph object.                      */
+  /*                                                                       */
+  /*    mode  :: The mode which indicates how to interpret the returned    */
+  /*             bounding box values.                                      */
+  /*                                                                       */
+  /* <Output>                                                              */
+  /*    acbox :: The glyph coordinate bounding box.  Coordinates are       */
+  /*             expressed in 1/64th of pixels if it is grid-fitted.       */
+  /*                                                                       */
+  /* <Note>                                                                */
+  /*    Coordinates are relative to the glyph origin, using the Y-upwards  */
+  /*    convention.                                                        */
+  /*                                                                       */
+  /*    If the glyph has been loaded with @FT_LOAD_NO_SCALE, `bbox_mode'   */
+  /*    must be set to @FT_GLYPH_BBOX_UNSCALED to get unscaled font        */
+  /*    units in 26.6 pixel format.  The value @FT_GLYPH_BBOX_SUBPIXELS    */
+  /*    is another name for this constant.                                 */
+  /*                                                                       */
+  /*    Note that the maximum coordinates are exclusive, which means that  */
+  /*    one can compute the width and height of the glyph image (be it in  */
+  /*    integer or 26.6 pixels) as:                                        */
+  /*                                                                       */
+  /*    {                                                                  */
+  /*      width  = bbox.xMax - bbox.xMin;                                  */
+  /*      height = bbox.yMax - bbox.yMin;                                  */
+  /*    }                                                                  */
+  /*                                                                       */
+  /*    Note also that for 26.6 coordinates, if `bbox_mode' is set to      */
+  /*    @FT_GLYPH_BBOX_GRIDFIT, the coordinates will also be grid-fitted,  */
+  /*    which corresponds to:                                              */
+  /*                                                                       */
+  /*    {                                                                  */
+  /*      bbox.xMin = FLOOR(bbox.xMin);                                    */
+  /*      bbox.yMin = FLOOR(bbox.yMin);                                    */
+  /*      bbox.xMax = CEILING(bbox.xMax);                                  */
+  /*      bbox.yMax = CEILING(bbox.yMax);                                  */
+  /*    }                                                                  */
+  /*                                                                       */
+  /*    To get the bbox in pixel coordinates, set `bbox_mode' to           */
+  /*    @FT_GLYPH_BBOX_TRUNCATE.                                           */
+  /*                                                                       */
+  /*    To get the bbox in grid-fitted pixel coordinates, set `bbox_mode'  */
+  /*    to @FT_GLYPH_BBOX_PIXELS.                                          */
+  /*                                                                       */
+  FT_EXPORT( void )
+  FT_Glyph_Get_CBox( FT_Glyph  glyph,
+                     FT_UInt   bbox_mode,
+                     FT_BBox  *acbox );
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FT_Glyph_To_Bitmap                                                 */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    Converts a given glyph object to a bitmap glyph object.            */
+  /*                                                                       */
+  /* <InOut>                                                               */
+  /*    the_glyph   :: A pointer to a handle to the target glyph.          */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    render_mode :: An enumeration that describe how the data is        */
+  /*                   rendered.                                           */
+  /*                                                                       */
+  /*    origin      :: A pointer to a vector used to translate the glyph   */
+  /*                   image before rendering.  Can be 0 (if no            */
+  /*                   translation).  The origin is expressed in           */
+  /*                   26.6 pixels.                                        */
+  /*                                                                       */
+  /*    destroy     :: A boolean that indicates that the original glyph    */
+  /*                   image should be destroyed by this function.  It is  */
+  /*                   never destroyed in case of error.                   */
+  /*                                                                       */
+  /* <Return>                                                              */
+  /*    FreeType error code.  0 means success.                             */
+  /*                                                                       */
+  /* <Note>                                                                */
+  /*    The glyph image is translated with the `origin' vector before      */
+  /*    rendering.                                                         */
+  /*                                                                       */
+  /*    The first parameter is a pointer to an @FT_Glyph handle, that will */
+  /*    be replaced by this function.  Typically, you would use (omitting  */
+  /*    error handling):                                                   */
+  /*                                                                       */
+  /*                                                                       */
+  /*      {                                                                */
+  /*        FT_Glyph        glyph;                                         */
+  /*        FT_BitmapGlyph  glyph_bitmap;                                  */
+  /*                                                                       */
+  /*                                                                       */
+  /*        // load glyph                                                  */
+  /*        error = FT_Load_Char( face, glyph_index, FT_LOAD_DEFAUT );     */
+  /*                                                                       */
+  /*        // extract glyph image                                         */
+  /*        error = FT_Get_Glyph( face->glyph, &glyph );                   */
+  /*                                                                       */
+  /*        // convert to a bitmap (default render mode + destroy old)     */
+  /*        if ( glyph->format != FT_GLYPH_FORMAT_BITMAP )                 */
+  /*        {                                                              */
+  /*          error = FT_Glyph_To_Bitmap( &glyph, FT_RENDER_MODE_DEFAULT,  */
+  /*                                      0, 1 );                          */
+  /*          if ( error ) // glyph unchanged                              */
+  /*            ...                                                        */
+  /*        }                                                              */
+  /*                                                                       */
+  /*        // access bitmap content by typecasting                        */
+  /*        glyph_bitmap = (FT_BitmapGlyph)glyph;                          */
+  /*                                                                       */
+  /*        // do funny stuff with it, like blitting/drawing               */
+  /*        ...                                                            */
+  /*                                                                       */
+  /*        // discard glyph image (bitmap or not)                         */
+  /*        FT_Done_Glyph( glyph );                                        */
+  /*      }                                                                */
+  /*                                                                       */
+  /*                                                                       */
+  /*    This function does nothing if the glyph format isn't scalable.     */
+  /*                                                                       */
+  FT_EXPORT( FT_Error )
+  FT_Glyph_To_Bitmap( FT_Glyph*       the_glyph,
+                      FT_Render_Mode  render_mode,
+                      FT_Vector*      origin,
+                      FT_Bool         destroy );
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FT_Done_Glyph                                                      */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    Destroys a given glyph.                                            */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    glyph :: A handle to the target glyph object.                      */
+  /*                                                                       */
+  FT_EXPORT( void )
+  FT_Done_Glyph( FT_Glyph  glyph );
+
+  /* */
+
+
+  /* other helpful functions */
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Section>                                                             */
+  /*    computations                                                       */
+  /*                                                                       */
+  /*************************************************************************/
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FT_Matrix_Multiply                                                 */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    Performs the matrix operation `b = a*b'.                           */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    a :: A pointer to matrix `a'.                                      */
+  /*                                                                       */
+  /* <InOut>                                                               */
+  /*    b :: A pointer to matrix `b'.                                      */
+  /*                                                                       */
+  /* <Note>                                                                */
+  /*    The result is undefined if either `a' or `b' is zero.              */
+  /*                                                                       */
+  FT_EXPORT( void )
+  FT_Matrix_Multiply( const FT_Matrix*  a,
+                      FT_Matrix*  b );
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FT_Matrix_Invert                                                   */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    Inverts a 2x2 matrix.  Returns an error if it can't be inverted.   */
+  /*                                                                       */
+  /* <InOut>                                                               */
+  /*    matrix :: A pointer to the target matrix.  Remains untouched in    */
+  /*              case of error.                                           */
+  /*                                                                       */
+  /* <Return>                                                              */
+  /*    FreeType error code.  0 means success.                             */
+  /*                                                                       */
+  FT_EXPORT( FT_Error )
+  FT_Matrix_Invert( FT_Matrix*  matrix );
+
+
+  /* */
+
+
+FT_END_HEADER
+
+#endif /* __FTGLYPH_H__ */
+
+
+/* END */
+
+
+/* Local Variables: */
+/* coding: utf-8    */
+/* End:             */

+ 358 - 0
include/freetype/ftgxval.h

@@ -0,0 +1,358 @@
+/***************************************************************************/
+/*                                                                         */
+/*  ftgxval.h                                                              */
+/*                                                                         */
+/*    FreeType API for validating TrueTypeGX/AAT tables (specification).   */
+/*                                                                         */
+/*  Copyright 2004, 2005, 2006 by                                          */
+/*  Masatake YAMATO, Redhat K.K,                                           */
+/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */
+/*                                                                         */
+/*  This file is part of the FreeType project, and may only be used,       */
+/*  modified, and distributed under the terms of the FreeType project      */
+/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */
+/*  this file you indicate that you have read the license and              */
+/*  understand and accept it fully.                                        */
+/*                                                                         */
+/***************************************************************************/
+
+/***************************************************************************/
+/*                                                                         */
+/* gxvalid is derived from both gxlayout module and otvalid module.        */
+/* Development of gxlayout is supported by the Information-technology      */
+/* Promotion Agency(IPA), Japan.                                           */
+/*                                                                         */
+/***************************************************************************/
+
+
+#ifndef __FTGXVAL_H__
+#define __FTGXVAL_H__
+
+#include <ft2build.h>
+#include FT_FREETYPE_H
+
+#ifdef FREETYPE_H
+#error "freetype.h of FreeType 1 has been loaded!"
+#error "Please fix the directory search order for header files"
+#error "so that freetype.h of FreeType 2 is found first."
+#endif
+
+
+FT_BEGIN_HEADER
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Section>                                                             */
+  /*    gx_validation                                                      */
+  /*                                                                       */
+  /* <Title>                                                               */
+  /*    TrueTypeGX/AAT Validation                                          */
+  /*                                                                       */
+  /* <Abstract>                                                            */
+  /*    An API to validate TrueTypeGX/AAT tables.                          */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    This section contains the declaration of functions to validate     */
+  /*    some TrueTypeGX tables (feat, mort, morx, bsln, just, kern, opbd,  */
+  /*    trak, prop, lcar).                                                 */
+  /*                                                                       */
+  /*************************************************************************/
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /*                                                                       */
+  /* Warning: Use FT_VALIDATE_XXX to validate a table.                     */
+  /*          Following definitions are for gxvalid developers.            */
+  /*                                                                       */
+  /*                                                                       */
+  /*************************************************************************/
+
+#define FT_VALIDATE_feat_INDEX     0
+#define FT_VALIDATE_mort_INDEX     1
+#define FT_VALIDATE_morx_INDEX     2
+#define FT_VALIDATE_bsln_INDEX     3
+#define FT_VALIDATE_just_INDEX     4
+#define FT_VALIDATE_kern_INDEX     5
+#define FT_VALIDATE_opbd_INDEX     6
+#define FT_VALIDATE_trak_INDEX     7
+#define FT_VALIDATE_prop_INDEX     8
+#define FT_VALIDATE_lcar_INDEX     9
+#define FT_VALIDATE_GX_LAST_INDEX  FT_VALIDATE_lcar_INDEX
+
+
+  /*************************************************************************
+   *
+   * @macro:
+   *   FT_VALIDATE_GX_LENGTH
+   *
+   * @description:
+   *   The number of tables checked in this module.  Use it as a parameter
+   *   for the `table-length' argument of function @FT_TrueTypeGX_Validate.
+   */
+#define FT_VALIDATE_GX_LENGTH     (FT_VALIDATE_GX_LAST_INDEX + 1)
+
+  /* */
+
+  /* Up to 0x1000 is used by otvalid.
+     Ox2xxx is reserved for feature OT extension. */
+#define FT_VALIDATE_GX_START 0x4000
+#define FT_VALIDATE_GX_BITFIELD( tag )                  \
+  ( FT_VALIDATE_GX_START << FT_VALIDATE_##tag##_INDEX )
+
+
+ /**********************************************************************
+  *
+  * @enum:
+  *    FT_VALIDATE_GXXXX
+  *
+  * @description:
+  *    A list of bit-field constants used with @FT_TrueTypeGX_Validate to
+  *    indicate which TrueTypeGX/AAT Type tables should be validated.
+  *
+  * @values:
+  *    FT_VALIDATE_feat ::
+  *      Validate `feat' table.
+  *
+  *    FT_VALIDATE_mort ::
+  *      Validate `mort' table.
+  *
+  *    FT_VALIDATE_morx ::
+  *      Validate `morx' table.
+  *
+  *    FT_VALIDATE_bsln ::
+  *      Validate `bsln' table.
+  *
+  *    FT_VALIDATE_just ::
+  *      Validate `just' table.
+  *
+  *    FT_VALIDATE_kern ::
+  *      Validate `kern' table.
+  *
+  *    FT_VALIDATE_opbd ::
+  *      Validate `opbd' table.
+  *
+  *    FT_VALIDATE_trak ::
+  *      Validate `trak' table.
+  *
+  *    FT_VALIDATE_prop ::
+  *      Validate `prop' table.
+  *
+  *    FT_VALIDATE_lcar ::
+  *      Validate `lcar' table.
+  *
+  *    FT_VALIDATE_GX ::
+  *      Validate all TrueTypeGX tables (feat, mort, morx, bsln, just, kern,
+  *      opbd, trak, prop and lcar).
+  *
+  */
+
+#define FT_VALIDATE_feat  FT_VALIDATE_GX_BITFIELD( feat )
+#define FT_VALIDATE_mort  FT_VALIDATE_GX_BITFIELD( mort )
+#define FT_VALIDATE_morx  FT_VALIDATE_GX_BITFIELD( morx )
+#define FT_VALIDATE_bsln  FT_VALIDATE_GX_BITFIELD( bsln )
+#define FT_VALIDATE_just  FT_VALIDATE_GX_BITFIELD( just )
+#define FT_VALIDATE_kern  FT_VALIDATE_GX_BITFIELD( kern )
+#define FT_VALIDATE_opbd  FT_VALIDATE_GX_BITFIELD( opbd )
+#define FT_VALIDATE_trak  FT_VALIDATE_GX_BITFIELD( trak )
+#define FT_VALIDATE_prop  FT_VALIDATE_GX_BITFIELD( prop )
+#define FT_VALIDATE_lcar  FT_VALIDATE_GX_BITFIELD( lcar )
+
+#define FT_VALIDATE_GX  ( FT_VALIDATE_feat | \
+                          FT_VALIDATE_mort | \
+                          FT_VALIDATE_morx | \
+                          FT_VALIDATE_bsln | \
+                          FT_VALIDATE_just | \
+                          FT_VALIDATE_kern | \
+                          FT_VALIDATE_opbd | \
+                          FT_VALIDATE_trak | \
+                          FT_VALIDATE_prop | \
+                          FT_VALIDATE_lcar )
+
+
+  /* */
+
+ /**********************************************************************
+  *
+  * @function:
+  *    FT_TrueTypeGX_Validate
+  *
+  * @description:
+  *    Validate various TrueTypeGX tables to assure that all offsets and
+  *    indices are valid.  The idea is that a higher-level library which
+  *    actually does the text layout can access those tables without
+  *    error checking (which can be quite time consuming).
+  *
+  * @input:
+  *    face ::
+  *       A handle to the input face.
+  *
+  *    validation_flags ::
+  *       A bit field which specifies the tables to be validated.  See
+  *       @FT_VALIDATE_GXXXX for possible values.
+  *
+  *    table_length ::
+  *       The size of the `tables' array.  Normally, @FT_VALIDATE_GX_LENGTH
+  *       should be passed.
+  *
+  * @output:
+  *    tables ::
+  *       The array where all validated sfnt tables are stored.
+  *       The array itself must be allocated by a client.
+  *
+  * @return:
+  *   FreeType error code.  0 means success.
+  *
+  * @note:
+  *   This function only works with TrueTypeGX fonts, returning an error
+  *   otherwise.
+  *
+  *   After use, the application should deallocate the buffers pointed to by
+  *   each `tables' element, by calling @FT_TrueTypeGX_Free.  A NULL value
+  *   indicates that the table either doesn't exist in the font, the
+  *   application hasn't asked for validation, or the validator doesn't have
+  *   the ability to validate the sfnt table.
+  */
+  FT_EXPORT( FT_Error )
+  FT_TrueTypeGX_Validate( FT_Face   face,
+                          FT_UInt   validation_flags,
+                          FT_Bytes  tables[FT_VALIDATE_GX_LENGTH],
+                          FT_UInt   table_length );
+
+
+  /* */
+
+ /**********************************************************************
+  *
+  * @function:
+  *    FT_TrueTypeGX_Free
+  *
+  * @description:
+  *    Free the buffer allocated by TrueTypeGX validator.
+  *
+  * @input:
+  *    face ::
+  *       A handle to the input face.
+  *
+  *    table ::
+  *       The pointer to the buffer allocated by
+  *       @FT_TrueTypeGX_Validate.
+  *
+  * @note:
+  *   This function must be used to free the buffer allocated by
+  *   @FT_TrueTypeGX_Validate only.
+  */
+  FT_EXPORT( void )
+  FT_TrueTypeGX_Free( FT_Face   face,
+                      FT_Bytes  table );
+
+
+  /* */
+
+ /**********************************************************************
+  *
+  * @enum:
+  *    FT_VALIDATE_CKERNXXX
+  *
+  * @description:
+  *    A list of bit-field constants used with @FT_ClassicKern_Validate
+  *    to indicate the classic kern dialect or dialects.  If the selected
+  *    type doesn't fit, @FT_ClassicKern_Validate regards the table as
+  *    invalid.
+  *
+  * @values:
+  *    FT_VALIDATE_MS ::
+  *      Handle the `kern' table as a classic Microsoft kern table.
+  *
+  *    FT_VALIDATE_APPLE ::
+  *      Handle the `kern' table as a classic Apple kern table.
+  *
+  *    FT_VALIDATE_CKERN ::
+  *      Handle the `kern' as either classic Apple or Microsoft kern table.
+  */
+#define FT_VALIDATE_MS     ( FT_VALIDATE_GX_START << 0 )
+#define FT_VALIDATE_APPLE  ( FT_VALIDATE_GX_START << 1 )
+
+#define FT_VALIDATE_CKERN  ( FT_VALIDATE_MS | FT_VALIDATE_APPLE )
+
+
+  /* */
+
+ /**********************************************************************
+  *
+  * @function:
+  *    FT_ClassicKern_Validate
+  *
+  * @description:
+  *    Validate classic (16bit format) kern table to assure that the offsets
+  *    and indices are valid.  The idea is that a higher-level library which
+  *    actually does the text layout can access those tables without error
+  *    checking (which can be quite time consuming).
+  *
+  *    The `kern' table validator in @FT_TrueTypeGX_Validate deals with both
+  *    the new 32bit format and the classic 16bit format, while
+  *    FT_ClassicKern_Validate only supports the classic 16bit format.
+  *
+  * @input:
+  *    face ::
+  *       A handle to the input face.
+  *
+  *    validation_flags ::
+  *       A bit field which specifies the dialect to be validated.  See
+  *       @FT_VALIDATE_CKERNXXX for possible values.
+  *
+  * @output:
+  *    ckern_table ::
+  *       A pointer to the kern table.
+  *
+  * @return:
+  *   FreeType error code.  0 means success.
+  *
+  * @note:
+  *   After use, the application should deallocate the buffers pointed to by
+  *   `ckern_table', by calling @FT_ClassicKern_Free.  A NULL value
+  *   indicates that the table doesn't exist in the font.
+  */
+  FT_EXPORT( FT_Error )
+  FT_ClassicKern_Validate( FT_Face    face,
+                           FT_UInt    validation_flags,
+                           FT_Bytes  *ckern_table );
+
+
+  /* */
+
+ /**********************************************************************
+  *
+  * @function:
+  *    FT_ClassicKern_Free
+  *
+  * @description:
+  *    Free the buffer allocated by classic Kern validator.
+  *
+  * @input:
+  *    face ::
+  *       A handle to the input face.
+  *
+  *    table ::
+  *       The pointer to the buffer that is allocated by
+  *       @FT_ClassicKern_Validate.
+  *
+  * @note:
+  *   This function must be used to free the buffer allocated by
+  *   @FT_ClassicKern_Validate only.
+  */
+  FT_EXPORT( void )
+  FT_ClassicKern_Free( FT_Face   face,
+                       FT_Bytes  table );
+
+
+ /* */
+
+
+FT_END_HEADER
+
+#endif /* __FTGXVAL_H__ */
+
+
+/* END */

+ 102 - 0
include/freetype/ftgzip.h

@@ -0,0 +1,102 @@
+/***************************************************************************/
+/*                                                                         */
+/*  ftgzip.h                                                               */
+/*                                                                         */
+/*    Gzip-compressed stream support.                                      */
+/*                                                                         */
+/*  Copyright 2002, 2003, 2004, 2006 by                                    */
+/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */
+/*                                                                         */
+/*  This file is part of the FreeType project, and may only be used,       */
+/*  modified, and distributed under the terms of the FreeType project      */
+/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */
+/*  this file you indicate that you have read the license and              */
+/*  understand and accept it fully.                                        */
+/*                                                                         */
+/***************************************************************************/
+
+
+#ifndef __FTGZIP_H__
+#define __FTGZIP_H__
+
+#include <ft2build.h>
+#include FT_FREETYPE_H
+
+#ifdef FREETYPE_H
+#error "freetype.h of FreeType 1 has been loaded!"
+#error "Please fix the directory search order for header files"
+#error "so that freetype.h of FreeType 2 is found first."
+#endif
+
+
+FT_BEGIN_HEADER
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Section>                                                             */
+  /*    gzip                                                               */
+  /*                                                                       */
+  /* <Title>                                                               */
+  /*    GZIP Streams                                                       */
+  /*                                                                       */
+  /* <Abstract>                                                            */
+  /*    Using gzip-compressed font files.                                  */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    This section contains the declaration of Gzip-specific functions.  */
+  /*                                                                       */
+  /*************************************************************************/
+
+
+ /************************************************************************
+  *
+  * @function:
+  *   FT_Stream_OpenGzip
+  *
+  * @description:
+  *   Open a new stream to parse gzip-compressed font files.  This is
+  *   mainly used to support the compressed `*.pcf.gz' fonts that come
+  *   with XFree86.
+  *
+  * @input:
+  *   stream ::
+  *     The target embedding stream.
+  *
+  *   source ::
+  *     The source stream.
+  *
+  * @return:
+  *   FreeType error code.  0 means success.
+  *
+  * @note:
+  *   The source stream must be opened _before_ calling this function.
+  *
+  *   Calling the internal function `FT_Stream_Close' on the new stream will
+  *   *not* call `FT_Stream_Close' on the source stream.  None of the stream
+  *   objects will be released to the heap.
+  *
+  *   The stream implementation is very basic and resets the decompression
+  *   process each time seeking backwards is needed within the stream.
+  *
+  *   In certain builds of the library, gzip compression recognition is
+  *   automatically handled when calling @FT_New_Face or @FT_Open_Face.
+  *   This means that if no font driver is capable of handling the raw
+  *   compressed file, the library will try to open a gzipped stream from
+  *   it and re-open the face with it.
+  *
+  *   This function may return `FT_Err_Unimplemented_Feature' if your build
+  *   of FreeType was not compiled with zlib support.
+  */
+  FT_EXPORT( FT_Error )
+  FT_Stream_OpenGzip( FT_Stream  stream,
+                      FT_Stream  source );
+
+ /* */
+
+
+FT_END_HEADER
+
+#endif /* __FTGZIP_H__ */
+
+
+/* END */

+ 1237 - 0
include/freetype/ftimage.h

@@ -0,0 +1,1237 @@
+/***************************************************************************/
+/*                                                                         */
+/*  ftimage.h                                                              */
+/*                                                                         */
+/*    FreeType glyph image formats and default raster interface            */
+/*    (specification).                                                     */
+/*                                                                         */
+/*  Copyright 1996-2001, 2002, 2003, 2004, 2005, 2006, 2007 by             */
+/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */
+/*                                                                         */
+/*  This file is part of the FreeType project, and may only be used,       */
+/*  modified, and distributed under the terms of the FreeType project      */
+/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */
+/*  this file you indicate that you have read the license and              */
+/*  understand and accept it fully.                                        */
+/*                                                                         */
+/***************************************************************************/
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* Note: A `raster' is simply a scan-line converter, used to render      */
+  /*       FT_Outlines into FT_Bitmaps.                                    */
+  /*                                                                       */
+  /*************************************************************************/
+
+
+#ifndef __FTIMAGE_H__
+#define __FTIMAGE_H__
+
+
+/* _STANDALONE_ is from ftgrays.c */
+#ifndef _STANDALONE_
+#include <ft2build.h>
+#endif
+
+
+FT_BEGIN_HEADER
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Section>                                                             */
+  /*    basic_types                                                        */
+  /*                                                                       */
+  /*************************************************************************/
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Type>                                                                */
+  /*    FT_Pos                                                             */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    The type FT_Pos is a 32-bit integer used to store vectorial        */
+  /*    coordinates.  Depending on the context, these can represent        */
+  /*    distances in integer font units, or 16,16, or 26.6 fixed float     */
+  /*    pixel coordinates.                                                 */
+  /*                                                                       */
+  typedef signed long  FT_Pos;
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Struct>                                                              */
+  /*    FT_Vector                                                          */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    A simple structure used to store a 2D vector; coordinates are of   */
+  /*    the FT_Pos type.                                                   */
+  /*                                                                       */
+  /* <Fields>                                                              */
+  /*    x :: The horizontal coordinate.                                    */
+  /*    y :: The vertical coordinate.                                      */
+  /*                                                                       */
+  typedef struct  FT_Vector_
+  {
+    FT_Pos  x;
+    FT_Pos  y;
+
+  } FT_Vector;
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Struct>                                                              */
+  /*    FT_BBox                                                            */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    A structure used to hold an outline's bounding box, i.e., the      */
+  /*    coordinates of its extrema in the horizontal and vertical          */
+  /*    directions.                                                        */
+  /*                                                                       */
+  /* <Fields>                                                              */
+  /*    xMin :: The horizontal minimum (left-most).                        */
+  /*                                                                       */
+  /*    yMin :: The vertical minimum (bottom-most).                        */
+  /*                                                                       */
+  /*    xMax :: The horizontal maximum (right-most).                       */
+  /*                                                                       */
+  /*    yMax :: The vertical maximum (top-most).                           */
+  /*                                                                       */
+  typedef struct  FT_BBox_
+  {
+    FT_Pos  xMin, yMin;
+    FT_Pos  xMax, yMax;
+
+  } FT_BBox;
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Enum>                                                                */
+  /*    FT_Pixel_Mode                                                      */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    An enumeration type used to describe the format of pixels in a     */
+  /*    given bitmap.  Note that additional formats may be added in the    */
+  /*    future.                                                            */
+  /*                                                                       */
+  /* <Values>                                                              */
+  /*    FT_PIXEL_MODE_NONE ::                                              */
+  /*      Value 0 is reserved.                                             */
+  /*                                                                       */
+  /*    FT_PIXEL_MODE_MONO ::                                              */
+  /*      A monochrome bitmap, using 1 bit per pixel.  Note that pixels    */
+  /*      are stored in most-significant order (MSB), which means that     */
+  /*      the left-most pixel in a byte has value 128.                     */
+  /*                                                                       */
+  /*    FT_PIXEL_MODE_GRAY ::                                              */
+  /*      An 8-bit bitmap, generally used to represent anti-aliased glyph  */
+  /*      images.  Each pixel is stored in one byte.  Note that the number */
+  /*      of value `gray' levels is stored in the `num_bytes' field of     */
+  /*      the @FT_Bitmap structure (it generally is 256).                  */
+  /*                                                                       */
+  /*    FT_PIXEL_MODE_GRAY2 ::                                             */
+  /*      A 2-bit/pixel bitmap, used to represent embedded anti-aliased    */
+  /*      bitmaps in font files according to the OpenType specification.   */
+  /*      We haven't found a single font using this format, however.       */
+  /*                                                                       */
+  /*    FT_PIXEL_MODE_GRAY4 ::                                             */
+  /*      A 4-bit/pixel bitmap, used to represent embedded anti-aliased    */
+  /*      bitmaps in font files according to the OpenType specification.   */
+  /*      We haven't found a single font using this format, however.       */
+  /*                                                                       */
+  /*    FT_PIXEL_MODE_LCD ::                                               */
+  /*      An 8-bit bitmap, used to represent RGB or BGR decimated glyph    */
+  /*      images used for display on LCD displays; the bitmap is three     */
+  /*      times wider than the original glyph image.  See also             */
+  /*      @FT_RENDER_MODE_LCD.                                             */
+  /*                                                                       */
+  /*    FT_PIXEL_MODE_LCD_V ::                                             */
+  /*      An 8-bit bitmap, used to represent RGB or BGR decimated glyph    */
+  /*      images used for display on rotated LCD displays; the bitmap      */
+  /*      is three times taller than the original glyph image.  See also   */
+  /*      @FT_RENDER_MODE_LCD_V.                                           */
+  /*                                                                       */
+  typedef enum  FT_Pixel_Mode_
+  {
+    FT_PIXEL_MODE_NONE = 0,
+    FT_PIXEL_MODE_MONO,
+    FT_PIXEL_MODE_GRAY,
+    FT_PIXEL_MODE_GRAY2,
+    FT_PIXEL_MODE_GRAY4,
+    FT_PIXEL_MODE_LCD,
+    FT_PIXEL_MODE_LCD_V,
+
+    FT_PIXEL_MODE_MAX      /* do not remove */
+
+  } FT_Pixel_Mode;
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Enum>                                                                */
+  /*    ft_pixel_mode_xxx                                                  */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    A list of deprecated constants.  Use the corresponding             */
+  /*    @FT_Pixel_Mode values instead.                                     */
+  /*                                                                       */
+  /* <Values>                                                              */
+  /*    ft_pixel_mode_none  :: See @FT_PIXEL_MODE_NONE.                    */
+  /*    ft_pixel_mode_mono  :: See @FT_PIXEL_MODE_MONO.                    */
+  /*    ft_pixel_mode_grays :: See @FT_PIXEL_MODE_GRAY.                    */
+  /*    ft_pixel_mode_pal2  :: See @FT_PIXEL_MODE_GRAY2.                   */
+  /*    ft_pixel_mode_pal4  :: See @FT_PIXEL_MODE_GRAY4.                   */
+  /*                                                                       */
+#define ft_pixel_mode_none   FT_PIXEL_MODE_NONE
+#define ft_pixel_mode_mono   FT_PIXEL_MODE_MONO
+#define ft_pixel_mode_grays  FT_PIXEL_MODE_GRAY
+#define ft_pixel_mode_pal2   FT_PIXEL_MODE_GRAY2
+#define ft_pixel_mode_pal4   FT_PIXEL_MODE_GRAY4
+
+ /* */
+
+#if 0
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Enum>                                                                */
+  /*    FT_Palette_Mode                                                    */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    THIS TYPE IS DEPRECATED.  DO NOT USE IT!                           */
+  /*                                                                       */
+  /*    An enumeration type to describe the format of a bitmap palette,    */
+  /*    used with ft_pixel_mode_pal4 and ft_pixel_mode_pal8.               */
+  /*                                                                       */
+  /* <Fields>                                                              */
+  /*    ft_palette_mode_rgb  :: The palette is an array of 3-bytes RGB     */
+  /*                            records.                                   */
+  /*                                                                       */
+  /*    ft_palette_mode_rgba :: The palette is an array of 4-bytes RGBA    */
+  /*                            records.                                   */
+  /*                                                                       */
+  /* <Note>                                                                */
+  /*    As ft_pixel_mode_pal2, pal4 and pal8 are currently unused by       */
+  /*    FreeType, these types are not handled by the library itself.       */
+  /*                                                                       */
+  typedef enum  FT_Palette_Mode_
+  {
+    ft_palette_mode_rgb = 0,
+    ft_palette_mode_rgba,
+
+    ft_palettte_mode_max   /* do not remove */
+
+  } FT_Palette_Mode;
+
+  /* */
+
+#endif
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Struct>                                                              */
+  /*    FT_Bitmap                                                          */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    A structure used to describe a bitmap or pixmap to the raster.     */
+  /*    Note that we now manage pixmaps of various depths through the      */
+  /*    `pixel_mode' field.                                                */
+  /*                                                                       */
+  /* <Fields>                                                              */
+  /*    rows         :: The number of bitmap rows.                         */
+  /*                                                                       */
+  /*    width        :: The number of pixels in bitmap row.                */
+  /*                                                                       */
+  /*    pitch        :: The pitch's absolute value is the number of bytes  */
+  /*                    taken by one bitmap row, including padding.        */
+  /*                    However, the pitch is positive when the bitmap has */
+  /*                    a `down' flow, and negative when it has an `up'    */
+  /*                    flow.  In all cases, the pitch is an offset to add */
+  /*                    to a bitmap pointer in order to go down one row.   */
+  /*                                                                       */
+  /*    buffer       :: A typeless pointer to the bitmap buffer.  This     */
+  /*                    value should be aligned on 32-bit boundaries in    */
+  /*                    most cases.                                        */
+  /*                                                                       */
+  /*    num_grays    :: This field is only used with                       */
+  /*                    @FT_PIXEL_MODE_GRAY; it gives the number of gray   */
+  /*                    levels used in the bitmap.                         */
+  /*                                                                       */
+  /*    pixel_mode   :: The pixel mode, i.e., how pixel bits are stored.   */
+  /*                    See @FT_Pixel_Mode for possible values.            */
+  /*                                                                       */
+  /*    palette_mode :: This field is intended for paletted pixel modes;   */
+  /*                    it indicates how the palette is stored.  Not       */
+  /*                    used currently.                                    */
+  /*                                                                       */
+  /*    palette      :: A typeless pointer to the bitmap palette; this     */
+  /*                    field is intended for paletted pixel modes.  Not   */
+  /*                    used currently.                                    */
+  /*                                                                       */
+  /* <Note>                                                                */
+  /*   For now, the only pixel modes supported by FreeType are mono and    */
+  /*   grays.  However, drivers might be added in the future to support    */
+  /*   more `colorful' options.                                            */
+  /*                                                                       */
+  typedef struct  FT_Bitmap_
+  {
+    int             rows;
+    int             width;
+    int             pitch;
+    unsigned char*  buffer;
+    short           num_grays;
+    char            pixel_mode;
+    char            palette_mode;
+    void*           palette;
+
+  } FT_Bitmap;
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Section>                                                             */
+  /*    outline_processing                                                 */
+  /*                                                                       */
+  /*************************************************************************/
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Struct>                                                              */
+  /*    FT_Outline                                                         */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    This structure is used to describe an outline to the scan-line     */
+  /*    converter.                                                         */
+  /*                                                                       */
+  /* <Fields>                                                              */
+  /*    n_contours :: The number of contours in the outline.               */
+  /*                                                                       */
+  /*    n_points   :: The number of points in the outline.                 */
+  /*                                                                       */
+  /*    points     :: A pointer to an array of `n_points' @FT_Vector       */
+  /*                  elements, giving the outline's point coordinates.    */
+  /*                                                                       */
+  /*    tags       :: A pointer to an array of `n_points' chars, giving    */
+  /*                  each outline point's type.  If bit 0 is unset, the   */
+  /*                  point is `off' the curve, i.e., a Bézier control     */
+  /*                  point, while it is `on' when set.                    */
+  /*                                                                       */
+  /*                  Bit 1 is meaningful for `off' points only.  If set,  */
+  /*                  it indicates a third-order Bézier arc control point; */
+  /*                  and a second-order control point if unset.           */
+  /*                                                                       */
+  /*    contours   :: An array of `n_contours' shorts, giving the end      */
+  /*                  point of each contour within the outline.  For       */
+  /*                  example, the first contour is defined by the points  */
+  /*                  `0' to `contours[0]', the second one is defined by   */
+  /*                  the points `contours[0]+1' to `contours[1]', etc.    */
+  /*                                                                       */
+  /*    flags      :: A set of bit flags used to characterize the outline  */
+  /*                  and give hints to the scan-converter and hinter on   */
+  /*                  how to convert/grid-fit it.  See @FT_OUTLINE_FLAGS.  */
+  /*                                                                       */
+  typedef struct  FT_Outline_
+  {
+    short       n_contours;      /* number of contours in glyph        */
+    short       n_points;        /* number of points in the glyph      */
+
+    FT_Vector*  points;          /* the outline's points               */
+    char*       tags;            /* the points flags                   */
+    short*      contours;        /* the contour end points             */
+
+    int         flags;           /* outline masks                      */
+
+  } FT_Outline;
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Enum>                                                                */
+  /*   FT_OUTLINE_FLAGS                                                    */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    A list of bit-field constants use for the flags in an outline's    */
+  /*    `flags' field.                                                     */
+  /*                                                                       */
+  /* <Values>                                                              */
+  /*    FT_OUTLINE_NONE           :: Value 0 is reserved.                  */
+  /*                                                                       */
+  /*    FT_OUTLINE_OWNER          :: If set, this flag indicates that the  */
+  /*                                 outline's field arrays (i.e.,         */
+  /*                                 `points', `flags' & `contours') are   */
+  /*                                 `owned' by the outline object, and    */
+  /*                                 should thus be freed when it is       */
+  /*                                 destroyed.                            */
+  /*                                                                       */
+  /*   FT_OUTLINE_EVEN_ODD_FILL   :: By default, outlines are filled using */
+  /*                                 the non-zero winding rule.  If set to */
+  /*                                 1, the outline will be filled using   */
+  /*                                 the even-odd fill rule (only works    */
+  /*                                 with the smooth raster).              */
+  /*                                                                       */
+  /*   FT_OUTLINE_REVERSE_FILL    :: By default, outside contours of an    */
+  /*                                 outline are oriented in clock-wise    */
+  /*                                 direction, as defined in the TrueType */
+  /*                                 specification.  This flag is set if   */
+  /*                                 the outline uses the opposite         */
+  /*                                 direction (typically for Type 1       */
+  /*                                 fonts).  This flag is ignored by the  */
+  /*                                 scan-converter.                       */
+  /*                                                                       */
+  /*   FT_OUTLINE_IGNORE_DROPOUTS :: By default, the scan converter will   */
+  /*                                 try to detect drop-outs in an outline */
+  /*                                 and correct the glyph bitmap to       */
+  /*                                 ensure consistent shape continuity.   */
+  /*                                 If set, this flag hints the scan-line */
+  /*                                 converter to ignore such cases.       */
+  /*                                                                       */
+  /*   FT_OUTLINE_HIGH_PRECISION  :: This flag indicates that the          */
+  /*                                 scan-line converter should try to     */
+  /*                                 convert this outline to bitmaps with  */
+  /*                                 the highest possible quality.  It is  */
+  /*                                 typically set for small character     */
+  /*                                 sizes.  Note that this is only a      */
+  /*                                 hint, that might be completely        */
+  /*                                 ignored by a given scan-converter.    */
+  /*                                                                       */
+  /*   FT_OUTLINE_SINGLE_PASS     :: This flag is set to force a given     */
+  /*                                 scan-converter to only use a single   */
+  /*                                 pass over the outline to render a     */
+  /*                                 bitmap glyph image.  Normally, it is  */
+  /*                                 set for very large character sizes.   */
+  /*                                 It is only a hint, that might be      */
+  /*                                 completely ignored by a given         */
+  /*                                 scan-converter.                       */
+  /*                                                                       */
+#define FT_OUTLINE_NONE             0x0
+#define FT_OUTLINE_OWNER            0x1
+#define FT_OUTLINE_EVEN_ODD_FILL    0x2
+#define FT_OUTLINE_REVERSE_FILL     0x4
+#define FT_OUTLINE_IGNORE_DROPOUTS  0x8
+
+#define FT_OUTLINE_HIGH_PRECISION   0x100
+#define FT_OUTLINE_SINGLE_PASS      0x200
+
+
+ /*************************************************************************
+  *
+  * @enum:
+  *   ft_outline_flags
+  *
+  * @description:
+  *   These constants are deprecated.  Please use the corresponding
+  *   @FT_OUTLINE_FLAGS values.
+  *
+  * @values:
+  *   ft_outline_none            :: See @FT_OUTLINE_NONE.
+  *   ft_outline_owner           :: See @FT_OUTLINE_OWNER.
+  *   ft_outline_even_odd_fill   :: See @FT_OUTLINE_EVEN_ODD_FILL.
+  *   ft_outline_reverse_fill    :: See @FT_OUTLINE_REVERSE_FILL.
+  *   ft_outline_ignore_dropouts :: See @FT_OUTLINE_IGNORE_DROPOUTS.
+  *   ft_outline_high_precision  :: See @FT_OUTLINE_HIGH_PRECISION.
+  *   ft_outline_single_pass     :: See @FT_OUTLINE_SINGLE_PASS.
+  */
+#define ft_outline_none             FT_OUTLINE_NONE
+#define ft_outline_owner            FT_OUTLINE_OWNER
+#define ft_outline_even_odd_fill    FT_OUTLINE_EVEN_ODD_FILL
+#define ft_outline_reverse_fill     FT_OUTLINE_REVERSE_FILL
+#define ft_outline_ignore_dropouts  FT_OUTLINE_IGNORE_DROPOUTS
+#define ft_outline_high_precision   FT_OUTLINE_HIGH_PRECISION
+#define ft_outline_single_pass      FT_OUTLINE_SINGLE_PASS
+
+  /* */
+
+#define FT_CURVE_TAG( flag )  ( flag & 3 )
+
+#define FT_CURVE_TAG_ON           1
+#define FT_CURVE_TAG_CONIC        0
+#define FT_CURVE_TAG_CUBIC        2
+
+#define FT_CURVE_TAG_TOUCH_X      8  /* reserved for the TrueType hinter */
+#define FT_CURVE_TAG_TOUCH_Y     16  /* reserved for the TrueType hinter */
+
+#define FT_CURVE_TAG_TOUCH_BOTH  ( FT_CURVE_TAG_TOUCH_X | \
+                                   FT_CURVE_TAG_TOUCH_Y )
+
+#define  FT_Curve_Tag_On       FT_CURVE_TAG_ON
+#define  FT_Curve_Tag_Conic    FT_CURVE_TAG_CONIC
+#define  FT_Curve_Tag_Cubic    FT_CURVE_TAG_CUBIC
+#define  FT_Curve_Tag_Touch_X  FT_CURVE_TAG_TOUCH_X
+#define  FT_Curve_Tag_Touch_Y  FT_CURVE_TAG_TOUCH_Y
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <FuncType>                                                            */
+  /*    FT_Outline_MoveToFunc                                              */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    A function pointer type used to describe the signature of a `move  */
+  /*    to' function during outline walking/decomposition.                 */
+  /*                                                                       */
+  /*    A `move to' is emitted to start a new contour in an outline.       */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    to   :: A pointer to the target point of the `move to'.            */
+  /*                                                                       */
+  /*    user :: A typeless pointer which is passed from the caller of the  */
+  /*            decomposition function.                                    */
+  /*                                                                       */
+  /* <Return>                                                              */
+  /*    Error code.  0 means success.                                      */
+  /*                                                                       */
+  typedef int
+  (*FT_Outline_MoveToFunc)( const FT_Vector*  to,
+                            void*             user );
+
+#define FT_Outline_MoveTo_Func  FT_Outline_MoveToFunc
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <FuncType>                                                            */
+  /*    FT_Outline_LineToFunc                                              */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    A function pointer type used to describe the signature of a `line  */
+  /*    to' function during outline walking/decomposition.                 */
+  /*                                                                       */
+  /*    A `line to' is emitted to indicate a segment in the outline.       */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    to   :: A pointer to the target point of the `line to'.            */
+  /*                                                                       */
+  /*    user :: A typeless pointer which is passed from the caller of the  */
+  /*            decomposition function.                                    */
+  /*                                                                       */
+  /* <Return>                                                              */
+  /*    Error code.  0 means success.                                      */
+  /*                                                                       */
+  typedef int
+  (*FT_Outline_LineToFunc)( const FT_Vector*  to,
+                            void*             user );
+
+#define  FT_Outline_LineTo_Func  FT_Outline_LineToFunc
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <FuncType>                                                            */
+  /*    FT_Outline_ConicToFunc                                             */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    A function pointer type use to describe the signature of a `conic  */
+  /*    to' function during outline walking/decomposition.                 */
+  /*                                                                       */
+  /*    A `conic to' is emitted to indicate a second-order Bézier arc in   */
+  /*    the outline.                                                       */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    control :: An intermediate control point between the last position */
+  /*               and the new target in `to'.                             */
+  /*                                                                       */
+  /*    to      :: A pointer to the target end point of the conic arc.     */
+  /*                                                                       */
+  /*    user    :: A typeless pointer which is passed from the caller of   */
+  /*               the decomposition function.                             */
+  /*                                                                       */
+  /* <Return>                                                              */
+  /*    Error code.  0 means success.                                      */
+  /*                                                                       */
+  typedef int
+  (*FT_Outline_ConicToFunc)( const FT_Vector*  control,
+                             const FT_Vector*  to,
+                             void*             user );
+
+#define  FT_Outline_ConicTo_Func  FT_Outline_ConicToFunc
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <FuncType>                                                            */
+  /*    FT_Outline_CubicToFunc                                             */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    A function pointer type used to describe the signature of a `cubic */
+  /*    to' function during outline walking/decomposition.                 */
+  /*                                                                       */
+  /*    A `cubic to' is emitted to indicate a third-order Bézier arc.      */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    control1 :: A pointer to the first Bézier control point.           */
+  /*                                                                       */
+  /*    control2 :: A pointer to the second Bézier control point.          */
+  /*                                                                       */
+  /*    to       :: A pointer to the target end point.                     */
+  /*                                                                       */
+  /*    user     :: A typeless pointer which is passed from the caller of  */
+  /*                the decomposition function.                            */
+  /*                                                                       */
+  /* <Return>                                                              */
+  /*    Error code.  0 means success.                                      */
+  /*                                                                       */
+  typedef int
+  (*FT_Outline_CubicToFunc)( const FT_Vector*  control1,
+                             const FT_Vector*  control2,
+                             const FT_Vector*  to,
+                             void*             user );
+
+#define  FT_Outline_CubicTo_Func  FT_Outline_CubicToFunc
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Struct>                                                              */
+  /*    FT_Outline_Funcs                                                   */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    A structure to hold various function pointers used during outline  */
+  /*    decomposition in order to emit segments, conic, and cubic Béziers, */
+  /*    as well as `move to' and `close to' operations.                    */
+  /*                                                                       */
+  /* <Fields>                                                              */
+  /*    move_to  :: The `move to' emitter.                                 */
+  /*                                                                       */
+  /*    line_to  :: The segment emitter.                                   */
+  /*                                                                       */
+  /*    conic_to :: The second-order Bézier arc emitter.                   */
+  /*                                                                       */
+  /*    cubic_to :: The third-order Bézier arc emitter.                    */
+  /*                                                                       */
+  /*    shift    :: The shift that is applied to coordinates before they   */
+  /*                are sent to the emitter.                               */
+  /*                                                                       */
+  /*    delta    :: The delta that is applied to coordinates before they   */
+  /*                are sent to the emitter, but after the shift.          */
+  /*                                                                       */
+  /* <Note>                                                                */
+  /*    The point coordinates sent to the emitters are the transformed     */
+  /*    version of the original coordinates (this is important for high    */
+  /*    accuracy during scan-conversion).  The transformation is simple:   */
+  /*                                                                       */
+  /*    {                                                                  */
+  /*      x' = (x << shift) - delta                                        */
+  /*      y' = (x << shift) - delta                                        */
+  /*    }                                                                  */
+  /*                                                                       */
+  /*    Set the value of `shift' and `delta' to 0 to get the original      */
+  /*    point coordinates.                                                 */
+  /*                                                                       */
+  typedef struct  FT_Outline_Funcs_
+  {
+    FT_Outline_MoveToFunc   move_to;
+    FT_Outline_LineToFunc   line_to;
+    FT_Outline_ConicToFunc  conic_to;
+    FT_Outline_CubicToFunc  cubic_to;
+
+    int                     shift;
+    FT_Pos                  delta;
+
+  } FT_Outline_Funcs;
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Section>                                                             */
+  /*    basic_types                                                        */
+  /*                                                                       */
+  /*************************************************************************/
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Macro>                                                               */
+  /*    FT_IMAGE_TAG                                                       */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    This macro converts four-letter tags to an unsigned long type.     */
+  /*                                                                       */
+  /* <Note>                                                                */
+  /*    Since many 16bit compilers don't like 32bit enumerations, you      */
+  /*    should redefine this macro in case of problems to something like   */
+  /*    this:                                                              */
+  /*                                                                       */
+  /*    {                                                                  */
+  /*      #define FT_IMAGE_TAG( value, _x1, _x2, _x3, _x4 )  value         */
+  /*    }                                                                  */
+  /*                                                                       */
+  /*    to get a simple enumeration without assigning special numbers.     */
+  /*                                                                       */
+#ifndef FT_IMAGE_TAG
+#define FT_IMAGE_TAG( value, _x1, _x2, _x3, _x4 )  \
+          value = ( ( (unsigned long)_x1 << 24 ) | \
+                    ( (unsigned long)_x2 << 16 ) | \
+                    ( (unsigned long)_x3 << 8  ) | \
+                      (unsigned long)_x4         )
+#endif /* FT_IMAGE_TAG */
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Enum>                                                                */
+  /*    FT_Glyph_Format                                                    */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    An enumeration type used to describe the format of a given glyph   */
+  /*    image.  Note that this version of FreeType only supports two image */
+  /*    formats, even though future font drivers will be able to register  */
+  /*    their own format.                                                  */
+  /*                                                                       */
+  /* <Values>                                                              */
+  /*    FT_GLYPH_FORMAT_NONE ::                                            */
+  /*      The value 0 is reserved.                                         */
+  /*                                                                       */
+  /*    FT_GLYPH_FORMAT_COMPOSITE ::                                       */
+  /*      The glyph image is a composite of several other images.  This    */
+  /*      format is _only_ used with @FT_LOAD_NO_RECURSE, and is used to   */
+  /*      report compound glyphs (like accented characters).               */
+  /*                                                                       */
+  /*    FT_GLYPH_FORMAT_BITMAP ::                                          */
+  /*      The glyph image is a bitmap, and can be described as an          */
+  /*      @FT_Bitmap.  You generally need to access the `bitmap' field of  */
+  /*      the @FT_GlyphSlotRec structure to read it.                       */
+  /*                                                                       */
+  /*    FT_GLYPH_FORMAT_OUTLINE ::                                         */
+  /*      The glyph image is a vectorial outline made of line segments     */
+  /*      and Bézier arcs; it can be described as an @FT_Outline; you      */
+  /*      generally want to access the `outline' field of the              */
+  /*      @FT_GlyphSlotRec structure to read it.                           */
+  /*                                                                       */
+  /*    FT_GLYPH_FORMAT_PLOTTER ::                                         */
+  /*      The glyph image is a vectorial path with no inside and outside   */
+  /*      contours.  Some Type 1 fonts, like those in the Hershey family,  */
+  /*      contain glyphs in this format.  These are described as           */
+  /*      @FT_Outline, but FreeType isn't currently capable of rendering   */
+  /*      them correctly.                                                  */
+  /*                                                                       */
+  typedef enum  FT_Glyph_Format_
+  {
+    FT_IMAGE_TAG( FT_GLYPH_FORMAT_NONE, 0, 0, 0, 0 ),
+
+    FT_IMAGE_TAG( FT_GLYPH_FORMAT_COMPOSITE, 'c', 'o', 'm', 'p' ),
+    FT_IMAGE_TAG( FT_GLYPH_FORMAT_BITMAP,    'b', 'i', 't', 's' ),
+    FT_IMAGE_TAG( FT_GLYPH_FORMAT_OUTLINE,   'o', 'u', 't', 'l' ),
+    FT_IMAGE_TAG( FT_GLYPH_FORMAT_PLOTTER,   'p', 'l', 'o', 't' )
+
+  } FT_Glyph_Format;
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Enum>                                                                */
+  /*    ft_glyph_format_xxx                                                */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    A list of deprecated constants.  Use the corresponding             */
+  /*    @FT_Glyph_Format values instead.                                   */
+  /*                                                                       */
+  /* <Values>                                                              */
+  /*    ft_glyph_format_none      :: See @FT_GLYPH_FORMAT_NONE.            */
+  /*    ft_glyph_format_composite :: See @FT_GLYPH_FORMAT_COMPOSITE.       */
+  /*    ft_glyph_format_bitmap    :: See @FT_GLYPH_FORMAT_BITMAP.          */
+  /*    ft_glyph_format_outline   :: See @FT_GLYPH_FORMAT_OUTLINE.         */
+  /*    ft_glyph_format_plotter   :: See @FT_GLYPH_FORMAT_PLOTTER.         */
+  /*                                                                       */
+#define ft_glyph_format_none       FT_GLYPH_FORMAT_NONE
+#define ft_glyph_format_composite  FT_GLYPH_FORMAT_COMPOSITE
+#define ft_glyph_format_bitmap     FT_GLYPH_FORMAT_BITMAP
+#define ft_glyph_format_outline    FT_GLYPH_FORMAT_OUTLINE
+#define ft_glyph_format_plotter    FT_GLYPH_FORMAT_PLOTTER
+
+
+  /*************************************************************************/
+  /*************************************************************************/
+  /*************************************************************************/
+  /*****                                                               *****/
+  /*****            R A S T E R   D E F I N I T I O N S                *****/
+  /*****                                                               *****/
+  /*************************************************************************/
+  /*************************************************************************/
+  /*************************************************************************/
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* A raster is a scan converter, in charge of rendering an outline into  */
+  /* a a bitmap.  This section contains the public API for rasters.        */
+  /*                                                                       */
+  /* Note that in FreeType 2, all rasters are now encapsulated within      */
+  /* specific modules called `renderers'.  See `freetype/ftrender.h' for   */
+  /* more details on renderers.                                            */
+  /*                                                                       */
+  /*************************************************************************/
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Section>                                                             */
+  /*    raster                                                             */
+  /*                                                                       */
+  /* <Title>                                                               */
+  /*    Scanline Converter                                                 */
+  /*                                                                       */
+  /* <Abstract>                                                            */
+  /*    How vectorial outlines are converted into bitmaps and pixmaps.     */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    This section contains technical definitions.                       */
+  /*                                                                       */
+  /*************************************************************************/
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Type>                                                                */
+  /*    FT_Raster                                                          */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    A handle (pointer) to a raster object.  Each object can be used    */
+  /*    independently to convert an outline into a bitmap or pixmap.       */
+  /*                                                                       */
+  typedef struct FT_RasterRec_*  FT_Raster;
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Struct>                                                              */
+  /*    FT_Span                                                            */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    A structure used to model a single span of gray (or black) pixels  */
+  /*    when rendering a monochrome or anti-aliased bitmap.                */
+  /*                                                                       */
+  /* <Fields>                                                              */
+  /*    x        :: The span's horizontal start position.                  */
+  /*                                                                       */
+  /*    len      :: The span's length in pixels.                           */
+  /*                                                                       */
+  /*    coverage :: The span color/coverage, ranging from 0 (background)   */
+  /*                to 255 (foreground).  Only used for anti-aliased       */
+  /*                rendering.                                             */
+  /*                                                                       */
+  /* <Note>                                                                */
+  /*    This structure is used by the span drawing callback type named     */
+  /*    @FT_SpanFunc which takes the y-coordinate of the span as a         */
+  /*    a parameter.                                                       */
+  /*                                                                       */
+  /*    The coverage value is always between 0 and 255.                    */
+  /*                                                                       */
+  typedef struct  FT_Span_
+  {
+    short           x;
+    unsigned short  len;
+    unsigned char   coverage;
+
+  } FT_Span;
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <FuncType>                                                            */
+  /*    FT_SpanFunc                                                        */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    A function used as a call-back by the anti-aliased renderer in     */
+  /*    order to let client applications draw themselves the gray pixel    */
+  /*    spans on each scan line.                                           */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    y     :: The scanline's y-coordinate.                              */
+  /*                                                                       */
+  /*    count :: The number of spans to draw on this scanline.             */
+  /*                                                                       */
+  /*    spans :: A table of `count' spans to draw on the scanline.         */
+  /*                                                                       */
+  /*    user  :: User-supplied data that is passed to the callback.        */
+  /*                                                                       */
+  /* <Note>                                                                */
+  /*    This callback allows client applications to directly render the    */
+  /*    gray spans of the anti-aliased bitmap to any kind of surfaces.     */
+  /*                                                                       */
+  /*    This can be used to write anti-aliased outlines directly to a      */
+  /*    given background bitmap, and even perform translucency.            */
+  /*                                                                       */
+  /*    Note that the `count' field cannot be greater than a fixed value   */
+  /*    defined by the `FT_MAX_GRAY_SPANS' configuration macro in          */
+  /*    `ftoption.h'.  By default, this value is set to 32, which means    */
+  /*    that if there are more than 32 spans on a given scanline, the      */
+  /*    callback is called several times with the same `y' parameter in    */
+  /*    order to draw all callbacks.                                       */
+  /*                                                                       */
+  /*    Otherwise, the callback is only called once per scan-line, and     */
+  /*    only for those scanlines that do have `gray' pixels on them.       */
+  /*                                                                       */
+  typedef void
+  (*FT_SpanFunc)( int             y,
+                  int             count,
+                  const FT_Span*  spans,
+                  void*           user );
+
+#define FT_Raster_Span_Func   FT_SpanFunc
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <FuncType>                                                            */
+  /*    FT_Raster_BitTest_Func                                             */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    THIS TYPE IS DEPRECATED.  DO NOT USE IT.                           */
+  /*                                                                       */
+  /*    A function used as a call-back by the monochrome scan-converter    */
+  /*    to test whether a given target pixel is already set to the drawing */
+  /*    `color'.  These tests are crucial to implement drop-out control    */
+  /*    per-se the TrueType spec.                                          */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    y     :: The pixel's y-coordinate.                                 */
+  /*                                                                       */
+  /*    x     :: The pixel's x-coordinate.                                 */
+  /*                                                                       */
+  /*    user  :: User-supplied data that is passed to the callback.        */
+  /*                                                                       */
+  /* <Return>                                                              */
+  /*   1 if the pixel is `set', 0 otherwise.                               */
+  /*                                                                       */
+  typedef int
+  (*FT_Raster_BitTest_Func)( int    y,
+                             int    x,
+                             void*  user );
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <FuncType>                                                            */
+  /*    FT_Raster_BitSet_Func                                              */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    THIS TYPE IS DEPRECATED.  DO NOT USE IT.                           */
+  /*                                                                       */
+  /*    A function used as a call-back by the monochrome scan-converter    */
+  /*    to set an individual target pixel.  This is crucial to implement   */
+  /*    drop-out control according to the TrueType specification.          */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    y     :: The pixel's y-coordinate.                                 */
+  /*                                                                       */
+  /*    x     :: The pixel's x-coordinate.                                 */
+  /*                                                                       */
+  /*    user  :: User-supplied data that is passed to the callback.        */
+  /*                                                                       */
+  /* <Return>                                                              */
+  /*    1 if the pixel is `set', 0 otherwise.                              */
+  /*                                                                       */
+  typedef void
+  (*FT_Raster_BitSet_Func)( int    y,
+                            int    x,
+                            void*  user );
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Enum>                                                                */
+  /*    FT_RASTER_FLAG_XXX                                                 */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    A list of bit flag constants as used in the `flags' field of a     */
+  /*    @FT_Raster_Params structure.                                       */
+  /*                                                                       */
+  /* <Values>                                                              */
+  /*    FT_RASTER_FLAG_DEFAULT :: This value is 0.                         */
+  /*                                                                       */
+  /*    FT_RASTER_FLAG_AA      :: This flag is set to indicate that an     */
+  /*                              anti-aliased glyph image should be       */
+  /*                              generated.  Otherwise, it will be        */
+  /*                              monochrome (1-bit).                      */
+  /*                                                                       */
+  /*    FT_RASTER_FLAG_DIRECT  :: This flag is set to indicate direct      */
+  /*                              rendering.  In this mode, client         */
+  /*                              applications must provide their own span */
+  /*                              callback.  This lets them directly       */
+  /*                              draw or compose over an existing bitmap. */
+  /*                              If this bit is not set, the target       */
+  /*                              pixmap's buffer _must_ be zeroed before  */
+  /*                              rendering.                               */
+  /*                                                                       */
+  /*                              Note that for now, direct rendering is   */
+  /*                              only possible with anti-aliased glyphs.  */
+  /*                                                                       */
+  /*    FT_RASTER_FLAG_CLIP    :: This flag is only used in direct         */
+  /*                              rendering mode.  If set, the output will */
+  /*                              be clipped to a box specified in the     */
+  /*                              `clip_box' field of the                  */
+  /*                              @FT_Raster_Params structure.             */
+  /*                                                                       */
+  /*                              Note that by default, the glyph bitmap   */
+  /*                              is clipped to the target pixmap, except  */
+  /*                              in direct rendering mode where all spans */
+  /*                              are generated if no clipping box is set. */
+  /*                                                                       */
+#define FT_RASTER_FLAG_DEFAULT  0x0
+#define FT_RASTER_FLAG_AA       0x1
+#define FT_RASTER_FLAG_DIRECT   0x2
+#define FT_RASTER_FLAG_CLIP     0x4
+
+  /* deprecated */
+#define ft_raster_flag_default  FT_RASTER_FLAG_DEFAULT
+#define ft_raster_flag_aa       FT_RASTER_FLAG_AA
+#define ft_raster_flag_direct   FT_RASTER_FLAG_DIRECT
+#define ft_raster_flag_clip     FT_RASTER_FLAG_CLIP
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Struct>                                                              */
+  /*    FT_Raster_Params                                                   */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    A structure to hold the arguments used by a raster's render        */
+  /*    function.                                                          */
+  /*                                                                       */
+  /* <Fields>                                                              */
+  /*    target      :: The target bitmap.                                  */
+  /*                                                                       */
+  /*    source      :: A pointer to the source glyph image (e.g., an       */
+  /*                   @FT_Outline).                                       */
+  /*                                                                       */
+  /*    flags       :: The rendering flags.                                */
+  /*                                                                       */
+  /*    gray_spans  :: The gray span drawing callback.                     */
+  /*                                                                       */
+  /*    black_spans :: The black span drawing callback.                    */
+  /*                                                                       */
+  /*    bit_test    :: The bit test callback.  UNIMPLEMENTED!              */
+  /*                                                                       */
+  /*    bit_set     :: The bit set callback.  UNIMPLEMENTED!               */
+  /*                                                                       */
+  /*    user        :: User-supplied data that is passed to each drawing   */
+  /*                   callback.                                           */
+  /*                                                                       */
+  /*    clip_box    :: An optional clipping box.  It is only used in       */
+  /*                   direct rendering mode.  Note that coordinates here  */
+  /*                   should be expressed in _integer_ pixels (and not in */
+  /*                   26.6 fixed-point units).                            */
+  /*                                                                       */
+  /* <Note>                                                                */
+  /*    An anti-aliased glyph bitmap is drawn if the @FT_RASTER_FLAG_AA    */
+  /*    bit flag is set in the `flags' field, otherwise a monochrome       */
+  /*    bitmap is generated.                                               */
+  /*                                                                       */
+  /*    If the @FT_RASTER_FLAG_DIRECT bit flag is set in `flags', the      */
+  /*    raster will call the `gray_spans' callback to draw gray pixel      */
+  /*    spans, in the case of an aa glyph bitmap, it will call             */
+  /*    `black_spans', and `bit_test' and `bit_set' in the case of a       */
+  /*    monochrome bitmap.  This allows direct composition over a          */
+  /*    pre-existing bitmap through user-provided callbacks to perform the */
+  /*    span drawing/composition.                                          */
+  /*                                                                       */
+  /*    Note that the `bit_test' and `bit_set' callbacks are required when */
+  /*    rendering a monochrome bitmap, as they are crucial to implement    */
+  /*    correct drop-out control as defined in the TrueType specification. */
+  /*                                                                       */
+  typedef struct  FT_Raster_Params_
+  {
+    const FT_Bitmap*        target;
+    const void*             source;
+    int                     flags;
+    FT_SpanFunc             gray_spans;
+    FT_SpanFunc             black_spans;
+    FT_Raster_BitTest_Func  bit_test;     /* doesn't work! */
+    FT_Raster_BitSet_Func   bit_set;      /* doesn't work! */
+    void*                   user;
+    FT_BBox                 clip_box;
+
+  } FT_Raster_Params;
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <FuncType>                                                            */
+  /*    FT_Raster_NewFunc                                                  */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    A function used to create a new raster object.                     */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    memory :: A handle to the memory allocator.                        */
+  /*                                                                       */
+  /* <Output>                                                              */
+  /*    raster :: A handle to the new raster object.                       */
+  /*                                                                       */
+  /* <Return>                                                              */
+  /*    Error code.  0 means success.                                      */
+  /*                                                                       */
+  /* <Note>                                                                */
+  /*    The `memory' parameter is a typeless pointer in order to avoid     */
+  /*    un-wanted dependencies on the rest of the FreeType code.  In       */
+  /*    practice, it is an @FT_Memory object, i.e., a handle to the        */
+  /*    standard FreeType memory allocator.  However, this field can be    */
+  /*    completely ignored by a given raster implementation.               */
+  /*                                                                       */
+  typedef int
+  (*FT_Raster_NewFunc)( void*       memory,
+                        FT_Raster*  raster );
+
+#define  FT_Raster_New_Func    FT_Raster_NewFunc
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <FuncType>                                                            */
+  /*    FT_Raster_DoneFunc                                                 */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    A function used to destroy a given raster object.                  */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    raster :: A handle to the raster object.                           */
+  /*                                                                       */
+  typedef void
+  (*FT_Raster_DoneFunc)( FT_Raster  raster );
+
+#define  FT_Raster_Done_Func   FT_Raster_DoneFunc
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <FuncType>                                                            */
+  /*    FT_Raster_ResetFunc                                                */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    FreeType provides an area of memory called the `render pool',      */
+  /*    available to all registered rasters.  This pool can be freely used */
+  /*    during a given scan-conversion but is shared by all rasters.  Its  */
+  /*    content is thus transient.                                         */
+  /*                                                                       */
+  /*    This function is called each time the render pool changes, or just */
+  /*    after a new raster object is created.                              */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    raster    :: A handle to the new raster object.                    */
+  /*                                                                       */
+  /*    pool_base :: The address in memory of the render pool.             */
+  /*                                                                       */
+  /*    pool_size :: The size in bytes of the render pool.                 */
+  /*                                                                       */
+  /* <Note>                                                                */
+  /*    Rasters can ignore the render pool and rely on dynamic memory      */
+  /*    allocation if they want to (a handle to the memory allocator is    */
+  /*    passed to the raster constructor).  However, this is not           */
+  /*    recommended for efficiency purposes.                               */
+  /*                                                                       */
+  typedef void
+  (*FT_Raster_ResetFunc)( FT_Raster       raster,
+                          unsigned char*  pool_base,
+                          unsigned long   pool_size );
+
+#define  FT_Raster_Reset_Func   FT_Raster_ResetFunc
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <FuncType>                                                            */
+  /*    FT_Raster_SetModeFunc                                              */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    This function is a generic facility to change modes or attributes  */
+  /*    in a given raster.  This can be used for debugging purposes, or    */
+  /*    simply to allow implementation-specific `features' in a given      */
+  /*    raster module.                                                     */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    raster :: A handle to the new raster object.                       */
+  /*                                                                       */
+  /*    mode   :: A 4-byte tag used to name the mode or property.          */
+  /*                                                                       */
+  /*    args   :: A pointer to the new mode/property to use.               */
+  /*                                                                       */
+  typedef int
+  (*FT_Raster_SetModeFunc)( FT_Raster      raster,
+                            unsigned long  mode,
+                            void*          args );
+
+#define  FT_Raster_Set_Mode_Func  FT_Raster_SetModeFunc
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <FuncType>                                                            */
+  /*    FT_Raster_RenderFunc                                               */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*   Invokes a given raster to scan-convert a given glyph image into a   */
+  /*   target bitmap.                                                      */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    raster :: A handle to the raster object.                           */
+  /*                                                                       */
+  /*    params :: A pointer to an @FT_Raster_Params structure used to      */
+  /*              store the rendering parameters.                          */
+  /*                                                                       */
+  /* <Return>                                                              */
+  /*    Error code.  0 means success.                                      */
+  /*                                                                       */
+  /* <Note>                                                                */
+  /*    The exact format of the source image depends on the raster's glyph */
+  /*    format defined in its @FT_Raster_Funcs structure.  It can be an    */
+  /*    @FT_Outline or anything else in order to support a large array of  */
+  /*    glyph formats.                                                     */
+  /*                                                                       */
+  /*    Note also that the render function can fail and return a           */
+  /*    `FT_Err_Unimplemented_Feature' error code if the raster used does  */
+  /*    not support direct composition.                                    */
+  /*                                                                       */
+  /*    XXX: For now, the standard raster doesn't support direct           */
+  /*         composition but this should change for the final release (see */
+  /*         the files `demos/src/ftgrays.c' and `demos/src/ftgrays2.c'    */
+  /*         for examples of distinct implementations which support direct */
+  /*         composition).                                                 */
+  /*                                                                       */
+  typedef int
+  (*FT_Raster_RenderFunc)( FT_Raster                raster,
+                           const FT_Raster_Params*  params );
+
+#define  FT_Raster_Render_Func    FT_Raster_RenderFunc
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Struct>                                                              */
+  /*    FT_Raster_Funcs                                                    */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*   A structure used to describe a given raster class to the library.   */
+  /*                                                                       */
+  /* <Fields>                                                              */
+  /*    glyph_format  :: The supported glyph format for this raster.       */
+  /*                                                                       */
+  /*    raster_new    :: The raster constructor.                           */
+  /*                                                                       */
+  /*    raster_reset  :: Used to reset the render pool within the raster.  */
+  /*                                                                       */
+  /*    raster_render :: A function to render a glyph into a given bitmap. */
+  /*                                                                       */
+  /*    raster_done   :: The raster destructor.                            */
+  /*                                                                       */
+  typedef struct  FT_Raster_Funcs_
+  {
+    FT_Glyph_Format         glyph_format;
+    FT_Raster_NewFunc       raster_new;
+    FT_Raster_ResetFunc     raster_reset;
+    FT_Raster_SetModeFunc   raster_set_mode;
+    FT_Raster_RenderFunc    raster_render;
+    FT_Raster_DoneFunc      raster_done;
+
+  } FT_Raster_Funcs;
+
+
+  /* */
+
+
+FT_END_HEADER
+
+#endif /* __FTIMAGE_H__ */
+
+
+/* END */
+
+
+/* Local Variables: */
+/* coding: utf-8    */
+/* End:             */

+ 331 - 0
include/freetype/ftincrem.h

@@ -0,0 +1,331 @@
+/***************************************************************************/
+/*                                                                         */
+/*  ftincrem.h                                                             */
+/*                                                                         */
+/*    FreeType incremental loading (specification).                        */
+/*                                                                         */
+/*  Copyright 2002, 2003, 2006, 2007 by                                    */
+/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */
+/*                                                                         */
+/*  This file is part of the FreeType project, and may only be used,       */
+/*  modified, and distributed under the terms of the FreeType project      */
+/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */
+/*  this file you indicate that you have read the license and              */
+/*  understand and accept it fully.                                        */
+/*                                                                         */
+/***************************************************************************/
+
+
+#ifndef __FTINCREM_H__
+#define __FTINCREM_H__
+
+#include <ft2build.h>
+#include FT_FREETYPE_H
+
+#ifdef FREETYPE_H
+#error "freetype.h of FreeType 1 has been loaded!"
+#error "Please fix the directory search order for header files"
+#error "so that freetype.h of FreeType 2 is found first."
+#endif
+
+
+FT_BEGIN_HEADER
+
+ /***************************************************************************
+  *
+  * @section:
+  *    incremental
+  *
+  * @title:
+  *    Incremental Loading
+  *
+  * @abstract:
+  *    Custom Glyph Loading.
+  *
+  * @description:
+  *   This section contains various functions used to perform so-called
+  *   `incremental' glyph loading.  This is a mode where all glyphs loaded
+  *   from a given @FT_Face are provided by the client application,
+  *
+  *   Apart from that, all other tables are loaded normally from the font
+  *   file.  This mode is useful when FreeType is used within another
+  *   engine, e.g., a Postscript Imaging Processor.
+  *
+  *   To enable this mode, you must use @FT_Open_Face, passing an
+  *   @FT_Parameter with the @FT_PARAM_TAG_INCREMENTAL tag and an
+  *   @FT_Incremental_Interface value.  See the comments for
+  *   @FT_Incremental_InterfaceRec for an example.
+  *
+  */
+
+
+ /***************************************************************************
+  *
+  * @type:
+  *   FT_Incremental
+  *
+  * @description:
+  *   An opaque type describing a user-provided object used to implement
+  *   `incremental' glyph loading within FreeType.  This is used to support
+  *   embedded fonts in certain environments (e.g., Postscript interpreters),
+  *   where the glyph data isn't in the font file, or must be overridden by
+  *   different values.
+  *
+  * @note:
+  *   It is up to client applications to create and implement @FT_Incremental
+  *   objects, as long as they provide implementations for the methods
+  *   @FT_Incremental_GetGlyphDataFunc, @FT_Incremental_FreeGlyphDataFunc
+  *   and @FT_Incremental_GetGlyphMetricsFunc.
+  *
+  *   See the description of @FT_Incremental_InterfaceRec to understand how
+  *   to use incremental objects with FreeType.
+  */
+  typedef struct FT_IncrementalRec_*  FT_Incremental;
+
+
+ /***************************************************************************
+  *
+  * @struct:
+  *   FT_Incremental_Metrics
+  *
+  * @description:
+  *   A small structure used to contain the basic glyph metrics returned
+  *   by the @FT_Incremental_GetGlyphMetricsFunc method.
+  *
+  * @fields:
+  *   bearing_x ::
+  *     Left bearing, in font units.
+  *
+  *   bearing_y ::
+  *     Top bearing, in font units.
+  *
+  *   advance ::
+  *     Glyph advance, in font units.
+  *
+  * @note:
+  *   These correspond to horizontal or vertical metrics depending on the
+  *   value of the `vertical' argument to the function
+  *   @FT_Incremental_GetGlyphMetricsFunc.
+  */
+  typedef struct  FT_Incremental_MetricsRec_
+  {
+    FT_Long  bearing_x;
+    FT_Long  bearing_y;
+    FT_Long  advance;
+
+  } FT_Incremental_MetricsRec, *FT_Incremental_Metrics;
+
+
+ /***************************************************************************
+  *
+  * @type:
+  *   FT_Incremental_GetGlyphDataFunc
+  *
+  * @description:
+  *   A function called by FreeType to access a given glyph's data bytes
+  *   during @FT_Load_Glyph or @FT_Load_Char if incremental loading is
+  *   enabled.
+  *
+  *   Note that the format of the glyph's data bytes depends on the font
+  *   file format.  For TrueType, it must correspond to the raw bytes within
+  *   the `glyf' table.  For Postscript formats, it must correspond to the
+  *   *unencrypted* charstring bytes, without any `lenIV' header.  It is
+  *   undefined for any other format.
+  *
+  * @input:
+  *   incremental ::
+  *     Handle to an opaque @FT_Incremental handle provided by the client
+  *     application.
+  *
+  *   glyph_index ::
+  *     Index of relevant glyph.
+  *
+  * @output:
+  *   adata ::
+  *     A structure describing the returned glyph data bytes (which will be
+  *     accessed as a read-only byte block).
+  *
+  * @return:
+  *   FreeType error code.  0 means success.
+  *
+  * @note:
+  *   If this function returns successfully the method
+  *   @FT_Incremental_FreeGlyphDataFunc will be called later to release
+  *   the data bytes.
+  *
+  *   Nested calls to @FT_Incremental_GetGlyphDataFunc can happen for
+  *   compound glyphs.
+  */
+  typedef FT_Error
+  (*FT_Incremental_GetGlyphDataFunc)( FT_Incremental  incremental,
+                                      FT_UInt         glyph_index,
+                                      FT_Data*        adata );
+
+
+ /***************************************************************************
+  *
+  * @type:
+  *   FT_Incremental_FreeGlyphDataFunc
+  *
+  * @description:
+  *   A function used to release the glyph data bytes returned by a
+  *   successful call to @FT_Incremental_GetGlyphDataFunc.
+  *
+  * @input:
+  *   incremental ::
+  *     A handle to an opaque @FT_Incremental handle provided by the client
+  *     application.
+  *
+  *   data ::
+  *     A structure describing the glyph data bytes (which will be accessed
+  *     as a read-only byte block).
+  */
+  typedef void
+  (*FT_Incremental_FreeGlyphDataFunc)( FT_Incremental  incremental,
+                                       FT_Data*        data );
+
+
+ /***************************************************************************
+  *
+  * @type:
+  *   FT_Incremental_GetGlyphMetricsFunc
+  *
+  * @description:
+  *   A function used to retrieve the basic metrics of a given glyph index
+  *   before accessing its data.  This is necessary because, in certain
+  *   formats like TrueType, the metrics are stored in a different place from
+  *   the glyph images proper.
+  *
+  * @input:
+  *   incremental ::
+  *     A handle to an opaque @FT_Incremental handle provided by the client
+  *     application.
+  *
+  *   glyph_index ::
+  *     Index of relevant glyph.
+  *
+  *   vertical ::
+  *     If true, return vertical metrics.
+  *
+  *   ametrics ::
+  *     This parameter is used for both input and output.
+  *     The original glyph metrics, if any, in font units.  If metrics are
+  *     not available all the values must be set to zero.
+  *
+  * @output:
+  *   ametrics ::
+  *     The replacement glyph metrics in font units.
+  *
+  */
+  typedef FT_Error
+  (*FT_Incremental_GetGlyphMetricsFunc)
+                      ( FT_Incremental              incremental,
+                        FT_UInt                     glyph_index,
+                        FT_Bool                     vertical,
+                        FT_Incremental_MetricsRec  *ametrics );
+
+
+  /**************************************************************************
+   *
+   * @struct:
+   *   FT_Incremental_FuncsRec
+   *
+   * @description:
+   *   A table of functions for accessing fonts that load data
+   *   incrementally.  Used in @FT_Incremental_InterfaceRec.
+   *
+   * @fields:
+   *   get_glyph_data ::
+   *     The function to get glyph data.  Must not be null.
+   *
+   *   free_glyph_data ::
+   *     The function to release glyph data.  Must not be null.
+   *
+   *   get_glyph_metrics ::
+   *     The function to get glyph metrics.  May be null if the font does
+   *     not provide overriding glyph metrics.
+   */
+  typedef struct  FT_Incremental_FuncsRec_
+  {
+    FT_Incremental_GetGlyphDataFunc     get_glyph_data;
+    FT_Incremental_FreeGlyphDataFunc    free_glyph_data;
+    FT_Incremental_GetGlyphMetricsFunc  get_glyph_metrics;
+
+  } FT_Incremental_FuncsRec;
+
+
+ /***************************************************************************
+  *
+  * @struct:
+  *   FT_Incremental_InterfaceRec
+  *
+  * @description:
+  *   A structure to be used with @FT_Open_Face to indicate that the user
+  *   wants to support incremental glyph loading.  You should use it with
+  *   @FT_PARAM_TAG_INCREMENTAL as in the following example:
+  *
+  *     {
+  *       FT_Incremental_InterfaceRec  inc_int;
+  *       FT_Parameter                 parameter;
+  *       FT_Open_Args                 open_args;
+  *
+  *
+  *       // set up incremental descriptor
+  *       inc_int.funcs  = my_funcs;
+  *       inc_int.object = my_object;
+  *
+  *       // set up optional parameter
+  *       parameter.tag  = FT_PARAM_TAG_INCREMENTAL;
+  *       parameter.data = &inc_int;
+  *
+  *       // set up FT_Open_Args structure
+  *       open_args.flags      = FT_OPEN_PATHNAME | FT_OPEN_PARAMS;
+  *       open_args.pathname   = my_font_pathname;
+  *       open_args.num_params = 1;
+  *       open_args.params     = &parameter; // we use one optional argument
+  *
+  *       // open the font
+  *       error = FT_Open_Face( library, &open_args, index, &face );
+  *       ...
+  *     }
+  */
+  typedef struct  FT_Incremental_InterfaceRec_
+  {
+    const FT_Incremental_FuncsRec*  funcs;
+    FT_Incremental                  object;
+
+  } FT_Incremental_InterfaceRec;
+
+
+ /***************************************************************************
+  *
+  * @type:
+  *   FT_Incremental_Interface
+  *
+  * @description:
+  *   A pointer to an @FT_Incremental_InterfaceRec structure.
+  *
+  */
+  typedef FT_Incremental_InterfaceRec*   FT_Incremental_Interface;
+
+
+ /***************************************************************************
+  *
+  * @constant:
+  *   FT_PARAM_TAG_INCREMENTAL
+  *
+  * @description:
+  *   A constant used as the tag of @FT_Parameter structures to indicate
+  *   an incremental loading object to be used by FreeType.
+  *
+  */
+#define FT_PARAM_TAG_INCREMENTAL  FT_MAKE_TAG( 'i', 'n', 'c', 'r' )
+
+ /* */
+
+FT_END_HEADER
+
+#endif /* __FTINCREM_H__ */
+
+
+/* END */

+ 166 - 0
include/freetype/ftlcdfil.h

@@ -0,0 +1,166 @@
+/***************************************************************************/
+/*                                                                         */
+/*  ftlcdfil.h                                                             */
+/*                                                                         */
+/*    FreeType API for color filtering of subpixel bitmap glyphs           */
+/*    (specification).                                                     */
+/*                                                                         */
+/*  Copyright 2006, 2007 by                                                */
+/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */
+/*                                                                         */
+/*  This file is part of the FreeType project, and may only be used,       */
+/*  modified, and distributed under the terms of the FreeType project      */
+/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */
+/*  this file you indicate that you have read the license and              */
+/*  understand and accept it fully.                                        */
+/*                                                                         */
+/***************************************************************************/
+
+
+#ifndef __FT_LCD_FILTER_H__
+#define __FT_LCD_FILTER_H__
+
+#include <ft2build.h>
+#include FT_FREETYPE_H
+
+
+FT_BEGIN_HEADER
+
+  /***************************************************************************
+   *
+   * @section:
+   *   lcd_filtering
+   *
+   * @title:
+   *   LCD Filtering
+   *
+   * @abstract:
+   *   Reduce color fringes of LCD-optimized bitmaps.
+   *
+   * @description:
+   *   The @FT_Library_SetLcdFilter API can be used to specify a low-pass
+   *   filter which is then applied to LCD-optimized bitmaps generated
+   *   through @FT_Render_Glyph.  This is useful to reduce color fringes
+   *   which would occur with unfiltered rendering.
+   *
+   *   Note that no filter is active by default, and that this function is
+   *   *not* implemented in default builds of the library.  You need to
+   *   #define FT_CONFIG_OPTION_SUBPIXEL_RENDERING in your `ftoption.h' file
+   *   in order to activate it.
+   */
+
+
+  /****************************************************************************
+   *
+   * @func:
+   *   FT_LcdFilter
+   *
+   * @description:
+   *   A list of values to identify various types of LCD filters.
+   *
+   * @values:
+   *   FT_LCD_FILTER_NONE ::
+   *     Do not perform filtering.  When used with subpixel rendering, this
+   *     results in sometimes severe color fringes.
+   *
+   *   FT_LCD_FILTER_DEFAULT ::
+   *     The default filter reduces color fringes considerably, at the cost
+   *     of a slight blurriness in the output.
+   *
+   *   FT_LCD_FILTER_LIGHT ::
+   *     The light filter is a variant that produces less blurriness at the
+   *     cost of slightly more color fringes than the default one.  It might
+   *     be better, depending on taste, your monitor, or your personal vision.
+   *
+   *   FT_LCD_FILTER_LEGACY ::
+   *     This filter corresponds to the original libXft color filter.  It
+   *     provides high contrast output but can exhibit really bad color
+   *     fringes if glyphs are not extremely well hinted to the pixel grid.
+   *     In other words, it only works well if the TrueType bytecode
+   *     interpreter is enabled *and* high-quality hinted fonts are used.
+   *
+   *     This filter is only provided for comparison purposes, and might be
+   *     disabled or stay unsupported in the future.
+   *
+   * @since:
+   *   2.3.0
+   */
+  typedef enum
+  {
+    FT_LCD_FILTER_NONE    = 0,
+    FT_LCD_FILTER_DEFAULT = 1,
+    FT_LCD_FILTER_LIGHT   = 2,
+    FT_LCD_FILTER_LEGACY  = 16,
+
+    FT_LCD_FILTER_MAX   /* do not remove */
+
+  } FT_LcdFilter;
+
+
+  /**************************************************************************
+   *
+   * @func:
+   *   FT_Library_SetLcdFilter
+   *
+   * @description:
+   *   This function is used to apply color filtering to LCD decimated
+   *   bitmaps, like the ones used when calling @FT_Render_Glyph with
+   *   @FT_RENDER_MODE_LCD or @FT_RENDER_MODE_LCD_V.
+   *
+   * @input:
+   *   library ::
+   *     A handle to the target library instance.
+   *
+   *   filter ::
+   *     The filter type.
+   *
+   *     You can use @FT_LCD_FILTER_NONE here to disable this feature, or
+   *     @FT_LCD_FILTER_DEFAULT to use a default filter that should work
+   *     well on most LCD screens.
+   *
+   * @return:
+   *   FreeType error code.  0 means success.
+   *
+   * @note:
+   *   This feature is always disabled by default.  Clients must make an
+   *   explicit call to this function with a `filter' value other than
+   *   @FT_LCD_FILTER_NONE in order to enable it.
+   *
+   *   Due to *PATENTS* covering subpixel rendering, this function doesn't
+   *   do anything except returning `FT_Err_Unimplemented_Feature' if the
+   *   configuration macro FT_CONFIG_OPTION_SUBPIXEL_RENDERING is not
+   *   defined in your build of the library, which should correspond to all
+   *   default builds of FreeType.
+   *
+   *   The filter affects glyph bitmaps rendered through @FT_Render_Glyph,
+   *   @FT_Outline_Get_Bitmap, @FT_Load_Glyph, and @FT_Load_Char.
+   *
+   *   It does _not_ affect the output of @FT_Outline_Render and
+   *   @FT_Outline_Get_Bitmap.
+   *
+   *   If this feature is activated, the dimensions of LCD glyph bitmaps are
+   *   either larger or taller than the dimensions of the corresponding
+   *   outline with regards to the pixel grid.  For example, for
+   *   @FT_RENDER_MODE_LCD, the filter adds up to 3 pixels to the left, and
+   *   up to 3 pixels to the right.
+   *
+   *   The bitmap offset values are adjusted correctly, so clients shouldn't
+   *   need to modify their layout and glyph positioning code when enabling
+   *   the filter.
+   *
+   * @since:
+   *   2.3.0
+   */
+  FT_EXPORT( FT_Error )
+  FT_Library_SetLcdFilter( FT_Library    library,
+                           FT_LcdFilter  filter );
+
+  /* */
+
+
+FT_END_HEADER
+
+#endif /* __FT_LCD_FILTER_H__ */
+
+
+/* END */

+ 273 - 0
include/freetype/ftlist.h

@@ -0,0 +1,273 @@
+/***************************************************************************/
+/*                                                                         */
+/*  ftlist.h                                                               */
+/*                                                                         */
+/*    Generic list support for FreeType (specification).                   */
+/*                                                                         */
+/*  Copyright 1996-2001, 2003, 2007 by                                     */
+/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */
+/*                                                                         */
+/*  This file is part of the FreeType project, and may only be used,       */
+/*  modified, and distributed under the terms of the FreeType project      */
+/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */
+/*  this file you indicate that you have read the license and              */
+/*  understand and accept it fully.                                        */
+/*                                                                         */
+/***************************************************************************/
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /*  This file implements functions relative to list processing.  Its     */
+  /*  data structures are defined in `freetype.h'.                         */
+  /*                                                                       */
+  /*************************************************************************/
+
+
+#ifndef __FTLIST_H__
+#define __FTLIST_H__
+
+
+#include <ft2build.h>
+#include FT_FREETYPE_H
+
+#ifdef FREETYPE_H
+#error "freetype.h of FreeType 1 has been loaded!"
+#error "Please fix the directory search order for header files"
+#error "so that freetype.h of FreeType 2 is found first."
+#endif
+
+
+FT_BEGIN_HEADER
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Section>                                                             */
+  /*    list_processing                                                    */
+  /*                                                                       */
+  /* <Title>                                                               */
+  /*    List Processing                                                    */
+  /*                                                                       */
+  /* <Abstract>                                                            */
+  /*    Simple management of lists.                                        */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    This section contains various definitions related to list          */
+  /*    processing using doubly-linked nodes.                              */
+  /*                                                                       */
+  /* <Order>                                                               */
+  /*    FT_List                                                            */
+  /*    FT_ListNode                                                        */
+  /*    FT_ListRec                                                         */
+  /*    FT_ListNodeRec                                                     */
+  /*                                                                       */
+  /*    FT_List_Add                                                        */
+  /*    FT_List_Insert                                                     */
+  /*    FT_List_Find                                                       */
+  /*    FT_List_Remove                                                     */
+  /*    FT_List_Up                                                         */
+  /*    FT_List_Iterate                                                    */
+  /*    FT_List_Iterator                                                   */
+  /*    FT_List_Finalize                                                   */
+  /*    FT_List_Destructor                                                 */
+  /*                                                                       */
+  /*************************************************************************/
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FT_List_Find                                                       */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    Finds the list node for a given listed object.                     */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    list :: A pointer to the parent list.                              */
+  /*    data :: The address of the listed object.                          */
+  /*                                                                       */
+  /* <Return>                                                              */
+  /*    List node.  NULL if it wasn't found.                               */
+  /*                                                                       */
+  FT_EXPORT( FT_ListNode )
+  FT_List_Find( FT_List  list,
+                void*    data );
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FT_List_Add                                                        */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    Appends an element to the end of a list.                           */
+  /*                                                                       */
+  /* <InOut>                                                               */
+  /*    list :: A pointer to the parent list.                              */
+  /*    node :: The node to append.                                        */
+  /*                                                                       */
+  FT_EXPORT( void )
+  FT_List_Add( FT_List      list,
+               FT_ListNode  node );
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FT_List_Insert                                                     */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    Inserts an element at the head of a list.                          */
+  /*                                                                       */
+  /* <InOut>                                                               */
+  /*    list :: A pointer to parent list.                                  */
+  /*    node :: The node to insert.                                        */
+  /*                                                                       */
+  FT_EXPORT( void )
+  FT_List_Insert( FT_List      list,
+                  FT_ListNode  node );
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FT_List_Remove                                                     */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    Removes a node from a list.  This function doesn't check whether   */
+  /*    the node is in the list!                                           */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    node :: The node to remove.                                        */
+  /*                                                                       */
+  /* <InOut>                                                               */
+  /*    list :: A pointer to the parent list.                              */
+  /*                                                                       */
+  FT_EXPORT( void )
+  FT_List_Remove( FT_List      list,
+                  FT_ListNode  node );
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FT_List_Up                                                         */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    Moves a node to the head/top of a list.  Used to maintain LRU      */
+  /*    lists.                                                             */
+  /*                                                                       */
+  /* <InOut>                                                               */
+  /*    list :: A pointer to the parent list.                              */
+  /*    node :: The node to move.                                          */
+  /*                                                                       */
+  FT_EXPORT( void )
+  FT_List_Up( FT_List      list,
+              FT_ListNode  node );
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <FuncType>                                                            */
+  /*    FT_List_Iterator                                                   */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    An FT_List iterator function which is called during a list parse   */
+  /*    by @FT_List_Iterate.                                               */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    node :: The current iteration list node.                           */
+  /*                                                                       */
+  /*    user :: A typeless pointer passed to @FT_List_Iterate.             */
+  /*            Can be used to point to the iteration's state.             */
+  /*                                                                       */
+  typedef FT_Error
+  (*FT_List_Iterator)( FT_ListNode  node,
+                       void*        user );
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FT_List_Iterate                                                    */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    Parses a list and calls a given iterator function on each element. */
+  /*    Note that parsing is stopped as soon as one of the iterator calls  */
+  /*    returns a non-zero value.                                          */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    list     :: A handle to the list.                                  */
+  /*    iterator :: An iterator function, called on each node of the list. */
+  /*    user     :: A user-supplied field which is passed as the second    */
+  /*                argument to the iterator.                              */
+  /*                                                                       */
+  /* <Return>                                                              */
+  /*    The result (a FreeType error code) of the last iterator call.      */
+  /*                                                                       */
+  FT_EXPORT( FT_Error )
+  FT_List_Iterate( FT_List           list,
+                   FT_List_Iterator  iterator,
+                   void*             user );
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <FuncType>                                                            */
+  /*    FT_List_Destructor                                                 */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    An @FT_List iterator function which is called during a list        */
+  /*    finalization by @FT_List_Finalize to destroy all elements in a     */
+  /*    given list.                                                        */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    system :: The current system object.                               */
+  /*                                                                       */
+  /*    data   :: The current object to destroy.                           */
+  /*                                                                       */
+  /*    user   :: A typeless pointer passed to @FT_List_Iterate.  It can   */
+  /*              be used to point to the iteration's state.               */
+  /*                                                                       */
+  typedef void
+  (*FT_List_Destructor)( FT_Memory  memory,
+                         void*      data,
+                         void*      user );
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FT_List_Finalize                                                   */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    Destroys all elements in the list as well as the list itself.      */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    list    :: A handle to the list.                                   */
+  /*                                                                       */
+  /*    destroy :: A list destructor that will be applied to each element  */
+  /*               of the list.                                            */
+  /*                                                                       */
+  /*    memory  :: The current memory object which handles deallocation.   */
+  /*                                                                       */
+  /*    user    :: A user-supplied field which is passed as the last       */
+  /*               argument to the destructor.                             */
+  /*                                                                       */
+  FT_EXPORT( void )
+  FT_List_Finalize( FT_List             list,
+                    FT_List_Destructor  destroy,
+                    FT_Memory           memory,
+                    void*               user );
+
+
+  /* */
+
+
+FT_END_HEADER
+
+#endif /* __FTLIST_H__ */
+
+
+/* END */

+ 99 - 0
include/freetype/ftlzw.h

@@ -0,0 +1,99 @@
+/***************************************************************************/
+/*                                                                         */
+/*  ftlzw.h                                                                */
+/*                                                                         */
+/*    LZW-compressed stream support.                                       */
+/*                                                                         */
+/*  Copyright 2004, 2006 by                                                */
+/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */
+/*                                                                         */
+/*  This file is part of the FreeType project, and may only be used,       */
+/*  modified, and distributed under the terms of the FreeType project      */
+/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */
+/*  this file you indicate that you have read the license and              */
+/*  understand and accept it fully.                                        */
+/*                                                                         */
+/***************************************************************************/
+
+
+#ifndef __FTLZW_H__
+#define __FTLZW_H__
+
+#include <ft2build.h>
+#include FT_FREETYPE_H
+
+#ifdef FREETYPE_H
+#error "freetype.h of FreeType 1 has been loaded!"
+#error "Please fix the directory search order for header files"
+#error "so that freetype.h of FreeType 2 is found first."
+#endif
+
+
+FT_BEGIN_HEADER
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Section>                                                             */
+  /*    lzw                                                                */
+  /*                                                                       */
+  /* <Title>                                                               */
+  /*    LZW Streams                                                        */
+  /*                                                                       */
+  /* <Abstract>                                                            */
+  /*    Using LZW-compressed font files.                                   */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    This section contains the declaration of LZW-specific functions.   */
+  /*                                                                       */
+  /*************************************************************************/
+
+ /************************************************************************
+  *
+  * @function:
+  *   FT_Stream_OpenLZW
+  *
+  * @description:
+  *   Open a new stream to parse LZW-compressed font files.  This is
+  *   mainly used to support the compressed `*.pcf.Z' fonts that come
+  *   with XFree86.
+  *
+  * @input:
+  *   stream :: The target embedding stream.
+  *
+  *   source :: The source stream.
+  *
+  * @return:
+  *   FreeType error code.  0 means success.
+  *
+  * @note:
+  *   The source stream must be opened _before_ calling this function.
+  *
+  *   Calling the internal function `FT_Stream_Close' on the new stream will
+  *   *not* call `FT_Stream_Close' on the source stream.  None of the stream
+  *   objects will be released to the heap.
+  *
+  *   The stream implementation is very basic and resets the decompression
+  *   process each time seeking backwards is needed within the stream
+  *
+  *   In certain builds of the library, LZW compression recognition is
+  *   automatically handled when calling @FT_New_Face or @FT_Open_Face.
+  *   This means that if no font driver is capable of handling the raw
+  *   compressed file, the library will try to open a LZW stream from it
+  *   and re-open the face with it.
+  *
+  *   This function may return `FT_Err_Unimplemented_Feature' if your build
+  *   of FreeType was not compiled with LZW support.
+  */
+  FT_EXPORT( FT_Error )
+  FT_Stream_OpenLZW( FT_Stream  stream,
+                     FT_Stream  source );
+
+ /* */
+
+
+FT_END_HEADER
+
+#endif /* __FTLZW_H__ */
+
+
+/* END */

+ 272 - 0
include/freetype/ftmac.h

@@ -0,0 +1,272 @@
+/***************************************************************************/
+/*                                                                         */
+/*  ftmac.h                                                                */
+/*                                                                         */
+/*    Additional Mac-specific API.                                         */
+/*                                                                         */
+/*  Copyright 1996-2001, 2004, 2006, 2007 by                               */
+/*  Just van Rossum, David Turner, Robert Wilhelm, and Werner Lemberg.     */
+/*                                                                         */
+/*  This file is part of the FreeType project, and may only be used,       */
+/*  modified, and distributed under the terms of the FreeType project      */
+/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */
+/*  this file you indicate that you have read the license and              */
+/*  understand and accept it fully.                                        */
+/*                                                                         */
+/***************************************************************************/
+
+
+/***************************************************************************/
+/*                                                                         */
+/* NOTE: Include this file after <freetype/freetype.h> and after the       */
+/*       Mac-specific <Types.h> header (or any other Mac header that       */
+/*       includes <Types.h>); we use Handle type.                          */
+/*                                                                         */
+/***************************************************************************/
+
+
+#ifndef __FTMAC_H__
+#define __FTMAC_H__
+
+
+#include <ft2build.h>
+
+
+FT_BEGIN_HEADER
+
+
+/* gcc-3.4.1 and later can warn about functions tagged as deprecated */
+#ifndef FT_DEPRECATED_ATTRIBUTE
+#if defined(__GNUC__)                                               && \
+    ((__GNUC__ >= 4) || ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 1)))
+#define FT_DEPRECATED_ATTRIBUTE  __attribute__((deprecated))
+#else
+#define FT_DEPRECATED_ATTRIBUTE
+#endif
+#endif
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Section>                                                             */
+  /*    mac_specific                                                       */
+  /*                                                                       */
+  /* <Title>                                                               */
+  /*    Mac Specific Interface                                             */
+  /*                                                                       */
+  /* <Abstract>                                                            */
+  /*    Only available on the Macintosh.                                   */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    The following definitions are only available if FreeType is        */
+  /*    compiled on a Macintosh.                                           */
+  /*                                                                       */
+  /*************************************************************************/
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FT_New_Face_From_FOND                                              */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    Create a new face object from a FOND resource.                     */
+  /*                                                                       */
+  /* <InOut>                                                               */
+  /*    library    :: A handle to the library resource.                    */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    fond       :: A FOND resource.                                     */
+  /*                                                                       */
+  /*    face_index :: Only supported for the -1 `sanity check' special     */
+  /*                  case.                                                */
+  /*                                                                       */
+  /* <Output>                                                              */
+  /*    aface      :: A handle to a new face object.                       */
+  /*                                                                       */
+  /* <Return>                                                              */
+  /*    FreeType error code.  0 means success.                             */
+  /*                                                                       */
+  /* <Notes>                                                               */
+  /*    This function can be used to create @FT_Face objects from fonts    */
+  /*    that are installed in the system as follows.                       */
+  /*                                                                       */
+  /*    {                                                                  */
+  /*      fond = GetResource( 'FOND', fontName );                          */
+  /*      error = FT_New_Face_From_FOND( library, fond, 0, &face );        */
+  /*    }                                                                  */
+  /*                                                                       */
+  FT_EXPORT( FT_Error )
+  FT_New_Face_From_FOND( FT_Library  library,
+                         Handle      fond,
+                         FT_Long     face_index,
+                         FT_Face    *aface );
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FT_GetFile_From_Mac_Name                                           */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    Return an FSSpec for the disk file containing the named font.      */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    fontName   :: Mac OS name of the font (e.g., Times New Roman       */
+  /*                  Bold).                                               */
+  /*                                                                       */
+  /* <Output>                                                              */
+  /*    pathSpec   :: FSSpec to the file.  For passing to                  */
+  /*                  @FT_New_Face_From_FSSpec.                            */
+  /*                                                                       */
+  /*    face_index :: Index of the face.  For passing to                   */
+  /*                  @FT_New_Face_From_FSSpec.                            */
+  /*                                                                       */
+  /* <Return>                                                              */
+  /*    FreeType error code.  0 means success.                             */
+  /*                                                                       */
+  FT_EXPORT( FT_Error )
+  FT_GetFile_From_Mac_Name( const char*  fontName,
+                            FSSpec*      pathSpec,
+                            FT_Long*     face_index )
+                          FT_DEPRECATED_ATTRIBUTE;
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FT_GetFile_From_Mac_ATS_Name                                       */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    Return an FSSpec for the disk file containing the named font.      */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    fontName   :: Mac OS name of the font in ATS framework.            */
+  /*                                                                       */
+  /* <Output>                                                              */
+  /*    pathSpec   :: FSSpec to the file. For passing to                   */
+  /*                  @FT_New_Face_From_FSSpec.                            */
+  /*                                                                       */
+  /*    face_index :: Index of the face. For passing to                    */
+  /*                  @FT_New_Face_From_FSSpec.                            */
+  /*                                                                       */
+  /* <Return>                                                              */
+  /*    FreeType error code.  0 means success.                             */
+  /*                                                                       */
+  FT_EXPORT( FT_Error )
+  FT_GetFile_From_Mac_ATS_Name( const char*  fontName,
+                                FSSpec*      pathSpec,
+                                FT_Long*     face_index )
+                              FT_DEPRECATED_ATTRIBUTE;
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FT_GetFilePath_From_Mac_ATS_Name                                   */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    Return a pathname of the disk file and face index for given font   */
+  /*    name which is handled by ATS framework.                            */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    fontName    :: Mac OS name of the font in ATS framework.           */
+  /*                                                                       */
+  /* <Output>                                                              */
+  /*    path        :: Buffer to store pathname of the file.  For passing  */
+  /*                   to @FT_New_Face.  The client must allocate this     */
+  /*                   buffer before calling this function.                */
+  /*                                                                       */
+  /*    maxPathSize :: Lengths of the buffer `path' that client allocated. */
+  /*                                                                       */
+  /*    face_index  :: Index of the face.  For passing to @FT_New_Face.    */
+  /*                                                                       */
+  /* <Return>                                                              */
+  /*    FreeType error code.  0 means success.                             */
+  /*                                                                       */
+  FT_EXPORT( FT_Error )
+  FT_GetFilePath_From_Mac_ATS_Name( const char*  fontName,
+                                    UInt8*       path,
+                                    UInt32       maxPathSize,
+                                    FT_Long*     face_index );
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FT_New_Face_From_FSSpec                                            */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    Create a new face object from a given resource and typeface index  */
+  /*    using an FSSpec to the font file.                                  */
+  /*                                                                       */
+  /* <InOut>                                                               */
+  /*    library    :: A handle to the library resource.                    */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    spec       :: FSSpec to the font file.                             */
+  /*                                                                       */
+  /*    face_index :: The index of the face within the resource.  The      */
+  /*                  first face has index 0.                              */
+  /* <Output>                                                              */
+  /*    aface      :: A handle to a new face object.                       */
+  /*                                                                       */
+  /* <Return>                                                              */
+  /*    FreeType error code.  0 means success.                             */
+  /*                                                                       */
+  /* <Note>                                                                */
+  /*    @FT_New_Face_From_FSSpec is identical to @FT_New_Face except       */
+  /*    it accepts an FSSpec instead of a path.                            */
+  /*                                                                       */
+  FT_EXPORT( FT_Error )
+  FT_New_Face_From_FSSpec( FT_Library     library,
+                           const FSSpec  *spec,
+                           FT_Long        face_index,
+                           FT_Face       *aface )
+                         FT_DEPRECATED_ATTRIBUTE;
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FT_New_Face_From_FSRef                                             */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    Create a new face object from a given resource and typeface index  */
+  /*    using an FSRef to the font file.                                   */
+  /*                                                                       */
+  /* <InOut>                                                               */
+  /*    library    :: A handle to the library resource.                    */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    spec       :: FSRef to the font file.                              */
+  /*                                                                       */
+  /*    face_index :: The index of the face within the resource.  The      */
+  /*                  first face has index 0.                              */
+  /* <Output>                                                              */
+  /*    aface      :: A handle to a new face object.                       */
+  /*                                                                       */
+  /* <Return>                                                              */
+  /*    FreeType error code.  0 means success.                             */
+  /*                                                                       */
+  /* <Note>                                                                */
+  /*    @FT_New_Face_From_FSRef is identical to @FT_New_Face except        */
+  /*    it accepts an FSRef instead of a path.                             */
+  /*                                                                       */
+  FT_EXPORT( FT_Error )
+  FT_New_Face_From_FSRef( FT_Library    library,
+                          const FSRef  *ref,
+                          FT_Long       face_index,
+                          FT_Face      *aface )
+                        FT_DEPRECATED_ATTRIBUTE;
+
+  /* */
+
+
+FT_END_HEADER
+
+
+#endif /* __FTMAC_H__ */
+
+
+/* END */

+ 378 - 0
include/freetype/ftmm.h

@@ -0,0 +1,378 @@
+/***************************************************************************/
+/*                                                                         */
+/*  ftmm.h                                                                 */
+/*                                                                         */
+/*    FreeType Multiple Master font interface (specification).             */
+/*                                                                         */
+/*  Copyright 1996-2001, 2003, 2004, 2006 by                               */
+/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */
+/*                                                                         */
+/*  This file is part of the FreeType project, and may only be used,       */
+/*  modified, and distributed under the terms of the FreeType project      */
+/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */
+/*  this file you indicate that you have read the license and              */
+/*  understand and accept it fully.                                        */
+/*                                                                         */
+/***************************************************************************/
+
+
+#ifndef __FTMM_H__
+#define __FTMM_H__
+
+
+#include <ft2build.h>
+#include FT_TYPE1_TABLES_H
+
+
+FT_BEGIN_HEADER
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Section>                                                             */
+  /*    multiple_masters                                                   */
+  /*                                                                       */
+  /* <Title>                                                               */
+  /*    Multiple Masters                                                   */
+  /*                                                                       */
+  /* <Abstract>                                                            */
+  /*    How to manage Multiple Masters fonts.                              */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    The following types and functions are used to manage Multiple      */
+  /*    Master fonts, i.e., the selection of specific design instances by  */
+  /*    setting design axis coordinates.                                   */
+  /*                                                                       */
+  /*    George Williams has extended this interface to make it work with   */
+  /*    both Type 1 Multiple Masters fonts and GX distortable (var)        */
+  /*    fonts.  Some of these routines only work with MM fonts, others     */
+  /*    will work with both types.  They are similar enough that a         */
+  /*    consistent interface makes sense.                                  */
+  /*                                                                       */
+  /*************************************************************************/
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Struct>                                                              */
+  /*    FT_MM_Axis                                                         */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    A simple structure used to model a given axis in design space for  */
+  /*    Multiple Masters fonts.                                            */
+  /*                                                                       */
+  /*    This structure can't be used for GX var fonts.                     */
+  /*                                                                       */
+  /* <Fields>                                                              */
+  /*    name    :: The axis's name.                                        */
+  /*                                                                       */
+  /*    minimum :: The axis's minimum design coordinate.                   */
+  /*                                                                       */
+  /*    maximum :: The axis's maximum design coordinate.                   */
+  /*                                                                       */
+  typedef struct  FT_MM_Axis_
+  {
+    FT_String*  name;
+    FT_Long     minimum;
+    FT_Long     maximum;
+
+  } FT_MM_Axis;
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Struct>                                                              */
+  /*    FT_Multi_Master                                                    */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    A structure used to model the axes and space of a Multiple Masters */
+  /*    font.                                                              */
+  /*                                                                       */
+  /*    This structure can't be used for GX var fonts.                     */
+  /*                                                                       */
+  /* <Fields>                                                              */
+  /*    num_axis    :: Number of axes.  Cannot exceed 4.                   */
+  /*                                                                       */
+  /*    num_designs :: Number of designs; should be normally 2^num_axis    */
+  /*                   even though the Type 1 specification strangely      */
+  /*                   allows for intermediate designs to be present. This */
+  /*                   number cannot exceed 16.                            */
+  /*                                                                       */
+  /*    axis        :: A table of axis descriptors.                        */
+  /*                                                                       */
+  typedef struct  FT_Multi_Master_
+  {
+    FT_UInt     num_axis;
+    FT_UInt     num_designs;
+    FT_MM_Axis  axis[T1_MAX_MM_AXIS];
+
+  } FT_Multi_Master;
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Struct>                                                              */
+  /*    FT_Var_Axis                                                        */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    A simple structure used to model a given axis in design space for  */
+  /*    Multiple Masters and GX var fonts.                                 */
+  /*                                                                       */
+  /* <Fields>                                                              */
+  /*    name    :: The axis's name.                                        */
+  /*               Not always meaningful for GX.                           */
+  /*                                                                       */
+  /*    minimum :: The axis's minimum design coordinate.                   */
+  /*                                                                       */
+  /*    def     :: The axis's default design coordinate.                   */
+  /*               FreeType computes meaningful default values for MM; it  */
+  /*               is then an integer value, not in 16.16 format.          */
+  /*                                                                       */
+  /*    maximum :: The axis's maximum design coordinate.                   */
+  /*                                                                       */
+  /*    tag     :: The axis's tag (the GX equivalent to `name').           */
+  /*               FreeType provides default values for MM if possible.    */
+  /*                                                                       */
+  /*    strid   :: The entry in `name' table (another GX version of        */
+  /*               `name').                                                */
+  /*               Not meaningful for MM.                                  */
+  /*                                                                       */
+  typedef struct  FT_Var_Axis_
+  {
+    FT_String*  name;
+
+    FT_Fixed    minimum;
+    FT_Fixed    def;
+    FT_Fixed    maximum;
+
+    FT_ULong    tag;
+    FT_UInt     strid;
+
+  } FT_Var_Axis;
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Struct>                                                              */
+  /*    FT_Var_Named_Style                                                 */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    A simple structure used to model a named style in a GX var font.   */
+  /*                                                                       */
+  /*    This structure can't be used for MM fonts.                         */
+  /*                                                                       */
+  /* <Fields>                                                              */
+  /*    coords :: The design coordinates for this style.                   */
+  /*              This is an array with one entry for each axis.           */
+  /*                                                                       */
+  /*    strid  :: The entry in `name' table identifying this style.        */
+  /*                                                                       */
+  typedef struct  FT_Var_Named_Style_
+  {
+    FT_Fixed*  coords;
+    FT_UInt    strid;
+
+  } FT_Var_Named_Style;
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Struct>                                                              */
+  /*    FT_MM_Var                                                          */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    A structure used to model the axes and space of a Multiple Masters */
+  /*    or GX var distortable font.                                        */
+  /*                                                                       */
+  /*    Some fields are specific to one format and not to the other.       */
+  /*                                                                       */
+  /* <Fields>                                                              */
+  /*    num_axis        :: The number of axes.  The maximum value is 4 for */
+  /*                       MM; no limit in GX.                             */
+  /*                                                                       */
+  /*    num_designs     :: The number of designs; should be normally       */
+  /*                       2^num_axis for MM fonts.  Not meaningful for GX */
+  /*                       (where every glyph could have a different       */
+  /*                       number of designs).                             */
+  /*                                                                       */
+  /*    num_namedstyles :: The number of named styles; only meaningful for */
+  /*                       GX which allows certain design coordinates to   */
+  /*                       have a string ID (in the `name' table)          */
+  /*                       associated with them.  The font can tell the    */
+  /*                       user that, for example, Weight=1.5 is `Bold'.   */
+  /*                                                                       */
+  /*    axis            :: A table of axis descriptors.                    */
+  /*                       GX fonts contain slightly more data than MM.    */
+  /*                                                                       */
+  /*    namedstyles     :: A table of named styles.                        */
+  /*                       Only meaningful with GX.                        */
+  /*                                                                       */
+  typedef struct  FT_MM_Var_
+  {
+    FT_UInt              num_axis;
+    FT_UInt              num_designs;
+    FT_UInt              num_namedstyles;
+    FT_Var_Axis*         axis;
+    FT_Var_Named_Style*  namedstyle;
+
+  } FT_MM_Var;
+
+
+  /* */
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FT_Get_Multi_Master                                                */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    Retrieves the Multiple Master descriptor of a given font.          */
+  /*                                                                       */
+  /*    This function can't be used with GX fonts.                         */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    face    :: A handle to the source face.                            */
+  /*                                                                       */
+  /* <Output>                                                              */
+  /*    amaster :: The Multiple Masters descriptor.                        */
+  /*                                                                       */
+  /* <Return>                                                              */
+  /*    FreeType error code.  0 means success.                             */
+  /*                                                                       */
+  FT_EXPORT( FT_Error )
+  FT_Get_Multi_Master( FT_Face           face,
+                       FT_Multi_Master  *amaster );
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FT_Get_MM_Var                                                      */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    Retrieves the Multiple Master/GX var descriptor of a given font.   */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    face    :: A handle to the source face.                            */
+  /*                                                                       */
+  /* <Output>                                                              */
+  /*    amaster :: The Multiple Masters descriptor.                        */
+  /*               Allocates a data structure, which the user must free    */
+  /*               (a single call to FT_FREE will do it).                  */
+  /*                                                                       */
+  /* <Return>                                                              */
+  /*    FreeType error code.  0 means success.                             */
+  /*                                                                       */
+  FT_EXPORT( FT_Error )
+  FT_Get_MM_Var( FT_Face      face,
+                 FT_MM_Var*  *amaster );
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FT_Set_MM_Design_Coordinates                                       */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    For Multiple Masters fonts, choose an interpolated font design     */
+  /*    through design coordinates.                                        */
+  /*                                                                       */
+  /*    This function can't be used with GX fonts.                         */
+  /*                                                                       */
+  /* <InOut>                                                               */
+  /*    face       :: A handle to the source face.                         */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    num_coords :: The number of design coordinates (must be equal to   */
+  /*                  the number of axes in the font).                     */
+  /*                                                                       */
+  /*    coords     :: An array of design coordinates.                      */
+  /*                                                                       */
+  /* <Return>                                                              */
+  /*    FreeType error code.  0 means success.                             */
+  /*                                                                       */
+  FT_EXPORT( FT_Error )
+  FT_Set_MM_Design_Coordinates( FT_Face   face,
+                                FT_UInt   num_coords,
+                                FT_Long*  coords );
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FT_Set_Var_Design_Coordinates                                      */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    For Multiple Master or GX Var fonts, choose an interpolated font   */
+  /*    design through design coordinates.                                 */
+  /*                                                                       */
+  /* <InOut>                                                               */
+  /*    face       :: A handle to the source face.                         */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    num_coords :: The number of design coordinates (must be equal to   */
+  /*                  the number of axes in the font).                     */
+  /*                                                                       */
+  /*    coords     :: An array of design coordinates.                      */
+  /*                                                                       */
+  /* <Return>                                                              */
+  /*    FreeType error code.  0 means success.                             */
+  /*                                                                       */
+  FT_EXPORT( FT_Error )
+  FT_Set_Var_Design_Coordinates( FT_Face    face,
+                                 FT_UInt    num_coords,
+                                 FT_Fixed*  coords );
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FT_Set_MM_Blend_Coordinates                                        */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    For Multiple Masters and GX var fonts, choose an interpolated font */
+  /*    design through normalized blend coordinates.                       */
+  /*                                                                       */
+  /* <InOut>                                                               */
+  /*    face       :: A handle to the source face.                         */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    num_coords :: The number of design coordinates (must be equal to   */
+  /*                  the number of axes in the font).                     */
+  /*                                                                       */
+  /*    coords     :: The design coordinates array (each element must be   */
+  /*                  between 0 and 1.0).                                  */
+  /*                                                                       */
+  /* <Return>                                                              */
+  /*    FreeType error code.  0 means success.                             */
+  /*                                                                       */
+  FT_EXPORT( FT_Error )
+  FT_Set_MM_Blend_Coordinates( FT_Face    face,
+                               FT_UInt    num_coords,
+                               FT_Fixed*  coords );
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FT_Set_Var_Blend_Coordinates                                       */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    This is another name of @FT_Set_MM_Blend_Coordinates.              */
+  /*                                                                       */
+  FT_EXPORT( FT_Error )
+  FT_Set_Var_Blend_Coordinates( FT_Face    face,
+                                FT_UInt    num_coords,
+                                FT_Fixed*  coords );
+
+
+  /* */
+
+
+FT_END_HEADER
+
+#endif /* __FTMM_H__ */
+
+
+/* END */

+ 406 - 0
include/freetype/ftmodapi.h

@@ -0,0 +1,406 @@
+/***************************************************************************/
+/*                                                                         */
+/*  ftmodapi.h                                                             */
+/*                                                                         */
+/*    FreeType modules public interface (specification).                   */
+/*                                                                         */
+/*  Copyright 1996-2001, 2002, 2003, 2006 by                               */
+/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */
+/*                                                                         */
+/*  This file is part of the FreeType project, and may only be used,       */
+/*  modified, and distributed under the terms of the FreeType project      */
+/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */
+/*  this file you indicate that you have read the license and              */
+/*  understand and accept it fully.                                        */
+/*                                                                         */
+/***************************************************************************/
+
+
+#ifndef __FTMODAPI_H__
+#define __FTMODAPI_H__
+
+
+#include <ft2build.h>
+#include FT_FREETYPE_H
+
+#ifdef FREETYPE_H
+#error "freetype.h of FreeType 1 has been loaded!"
+#error "Please fix the directory search order for header files"
+#error "so that freetype.h of FreeType 2 is found first."
+#endif
+
+
+FT_BEGIN_HEADER
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Section>                                                             */
+  /*    module_management                                                  */
+  /*                                                                       */
+  /* <Title>                                                               */
+  /*    Module Management                                                  */
+  /*                                                                       */
+  /* <Abstract>                                                            */
+  /*    How to add, upgrade, and remove modules from FreeType.             */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    The definitions below are used to manage modules within FreeType.  */
+  /*    Modules can be added, upgraded, and removed at runtime.            */
+  /*                                                                       */
+  /*************************************************************************/
+
+
+  /* module bit flags */
+#define FT_MODULE_FONT_DRIVER         1  /* this module is a font driver  */
+#define FT_MODULE_RENDERER            2  /* this module is a renderer     */
+#define FT_MODULE_HINTER              4  /* this module is a glyph hinter */
+#define FT_MODULE_STYLER              8  /* this module is a styler       */
+
+#define FT_MODULE_DRIVER_SCALABLE     0x100   /* the driver supports      */
+                                              /* scalable fonts           */
+#define FT_MODULE_DRIVER_NO_OUTLINES  0x200   /* the driver does not      */
+                                              /* support vector outlines  */
+#define FT_MODULE_DRIVER_HAS_HINTER   0x400   /* the driver provides its  */
+                                              /* own hinter               */
+
+
+  /* deprecated values */
+#define ft_module_font_driver         FT_MODULE_FONT_DRIVER
+#define ft_module_renderer            FT_MODULE_RENDERER
+#define ft_module_hinter              FT_MODULE_HINTER
+#define ft_module_styler              FT_MODULE_STYLER
+
+#define ft_module_driver_scalable     FT_MODULE_DRIVER_SCALABLE
+#define ft_module_driver_no_outlines  FT_MODULE_DRIVER_NO_OUTLINES
+#define ft_module_driver_has_hinter   FT_MODULE_DRIVER_HAS_HINTER
+
+
+  typedef FT_Pointer  FT_Module_Interface;
+
+  typedef FT_Error
+  (*FT_Module_Constructor)( FT_Module  module );
+
+  typedef void
+  (*FT_Module_Destructor)( FT_Module  module );
+
+  typedef FT_Module_Interface
+  (*FT_Module_Requester)( FT_Module    module,
+                          const char*  name );
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Struct>                                                              */
+  /*    FT_Module_Class                                                    */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    The module class descriptor.                                       */
+  /*                                                                       */
+  /* <Fields>                                                              */
+  /*    module_flags    :: Bit flags describing the module.                */
+  /*                                                                       */
+  /*    module_size     :: The size of one module object/instance in       */
+  /*                       bytes.                                          */
+  /*                                                                       */
+  /*    module_name     :: The name of the module.                         */
+  /*                                                                       */
+  /*    module_version  :: The version, as a 16.16 fixed number            */
+  /*                       (major.minor).                                  */
+  /*                                                                       */
+  /*    module_requires :: The version of FreeType this module requires,   */
+  /*                       as a 16.16 fixed number (major.minor).  Starts  */
+  /*                       at version 2.0, i.e., 0x20000.                  */
+  /*                                                                       */
+  /*    module_init     :: A function used to initialize (not create) a    */
+  /*                       new module object.                              */
+  /*                                                                       */
+  /*    module_done     :: A function used to finalize (not destroy) a     */
+  /*                       given module object                             */
+  /*                                                                       */
+  /*    get_interface   :: Queries a given module for a specific           */
+  /*                       interface by name.                              */
+  /*                                                                       */
+  typedef struct  FT_Module_Class_
+  {
+    FT_ULong               module_flags;
+    FT_Long                module_size;
+    const FT_String*       module_name;
+    FT_Fixed               module_version;
+    FT_Fixed               module_requires;
+
+    const void*            module_interface;
+
+    FT_Module_Constructor  module_init;
+    FT_Module_Destructor   module_done;
+    FT_Module_Requester    get_interface;
+
+  } FT_Module_Class;
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FT_Add_Module                                                      */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    Adds a new module to a given library instance.                     */
+  /*                                                                       */
+  /* <InOut>                                                               */
+  /*    library :: A handle to the library object.                         */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    clazz   :: A pointer to class descriptor for the module.           */
+  /*                                                                       */
+  /* <Return>                                                              */
+  /*    FreeType error code.  0 means success.                             */
+  /*                                                                       */
+  /* <Note>                                                                */
+  /*    An error will be returned if a module already exists by that name, */
+  /*    or if the module requires a version of FreeType that is too great. */
+  /*                                                                       */
+  FT_EXPORT( FT_Error )
+  FT_Add_Module( FT_Library              library,
+                 const FT_Module_Class*  clazz );
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FT_Get_Module                                                      */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    Finds a module by its name.                                        */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    library     :: A handle to the library object.                     */
+  /*                                                                       */
+  /*    module_name :: The module's name (as an ASCII string).             */
+  /*                                                                       */
+  /* <Return>                                                              */
+  /*    A module handle.  0 if none was found.                             */
+  /*                                                                       */
+  /* <Note>                                                                */
+  /*    FreeType's internal modules aren't documented very well, and you   */
+  /*    should look up the source code for details.                        */
+  /*                                                                       */
+  FT_EXPORT( FT_Module )
+  FT_Get_Module( FT_Library   library,
+                 const char*  module_name );
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FT_Remove_Module                                                   */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    Removes a given module from a library instance.                    */
+  /*                                                                       */
+  /* <InOut>                                                               */
+  /*    library :: A handle to a library object.                           */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    module  :: A handle to a module object.                            */
+  /*                                                                       */
+  /* <Return>                                                              */
+  /*    FreeType error code.  0 means success.                             */
+  /*                                                                       */
+  /* <Note>                                                                */
+  /*    The module object is destroyed by the function in case of success. */
+  /*                                                                       */
+  FT_EXPORT( FT_Error )
+  FT_Remove_Module( FT_Library  library,
+                    FT_Module   module );
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FT_New_Library                                                     */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    This function is used to create a new FreeType library instance    */
+  /*    from a given memory object.  It is thus possible to use libraries  */
+  /*    with distinct memory allocators within the same program.           */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    memory   :: A handle to the original memory object.                */
+  /*                                                                       */
+  /* <Output>                                                              */
+  /*    alibrary :: A pointer to handle of a new library object.           */
+  /*                                                                       */
+  /* <Return>                                                              */
+  /*    FreeType error code.  0 means success.                             */
+  /*                                                                       */
+  FT_EXPORT( FT_Error )
+  FT_New_Library( FT_Memory    memory,
+                  FT_Library  *alibrary );
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FT_Done_Library                                                    */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    Discards a given library object.  This closes all drivers and      */
+  /*    discards all resource objects.                                     */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    library :: A handle to the target library.                         */
+  /*                                                                       */
+  /* <Return>                                                              */
+  /*    FreeType error code.  0 means success.                             */
+  /*                                                                       */
+  FT_EXPORT( FT_Error )
+  FT_Done_Library( FT_Library  library );
+
+/* */
+
+  typedef void
+  (*FT_DebugHook_Func)( void*  arg );
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FT_Set_Debug_Hook                                                  */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    Sets a debug hook function for debugging the interpreter of a font */
+  /*    format.                                                            */
+  /*                                                                       */
+  /* <InOut>                                                               */
+  /*    library    :: A handle to the library object.                      */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    hook_index :: The index of the debug hook.  You should use the     */
+  /*                  values defined in `ftobjs.h', e.g.,                  */
+  /*                  `FT_DEBUG_HOOK_TRUETYPE'.                            */
+  /*                                                                       */
+  /*    debug_hook :: The function used to debug the interpreter.          */
+  /*                                                                       */
+  /* <Note>                                                                */
+  /*    Currently, four debug hook slots are available, but only two (for  */
+  /*    the TrueType and the Type 1 interpreter) are defined.              */
+  /*                                                                       */
+  /*    Since the internal headers of FreeType are no longer installed,    */
+  /*    the symbol `FT_DEBUG_HOOK_TRUETYPE' isn't available publicly.      */
+  /*    This is a bug and will be fixed in a forthcoming release.          */
+  /*                                                                       */
+  FT_EXPORT( void )
+  FT_Set_Debug_Hook( FT_Library         library,
+                     FT_UInt            hook_index,
+                     FT_DebugHook_Func  debug_hook );
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FT_Add_Default_Modules                                             */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    Adds the set of default drivers to a given library object.         */
+  /*    This is only useful when you create a library object with          */
+  /*    @FT_New_Library (usually to plug a custom memory manager).         */
+  /*                                                                       */
+  /* <InOut>                                                               */
+  /*    library :: A handle to a new library object.                       */
+  /*                                                                       */
+  FT_EXPORT( void )
+  FT_Add_Default_Modules( FT_Library  library );
+
+
+
+  /**************************************************************************
+   *
+   * @section:
+   *   truetype_engine
+   *
+   * @title:
+   *   The TrueType Engine
+   *
+   * @abstract:
+   *   TrueType bytecode support.
+   *
+   * @description:
+   *   This section contains a function used to query the level of TrueType
+   *   bytecode support compiled in this version of the library.
+   *
+   */
+
+
+  /**************************************************************************
+   *
+   *  @enum:
+   *     FT_TrueTypeEngineType
+   *
+   *  @description:
+   *     A list of values describing which kind of TrueType bytecode
+   *     engine is implemented in a given FT_Library instance.  It is used
+   *     by the @FT_Get_TrueType_Engine_Type function.
+   *
+   *  @values:
+   *     FT_TRUETYPE_ENGINE_TYPE_NONE ::
+   *       The library doesn't implement any kind of bytecode interpreter.
+   *
+   *     FT_TRUETYPE_ENGINE_TYPE_UNPATENTED ::
+   *       The library implements a bytecode interpreter that doesn't
+   *       support the patented operations of the TrueType virtual machine.
+   *
+   *       Its main use is to load certain Asian fonts which position and
+   *       scale glyph components with bytecode instructions.  It produces
+   *       bad output for most other fonts.
+   *
+   *    FT_TRUETYPE_ENGINE_TYPE_PATENTED ::
+   *       The library implements a bytecode interpreter that covers
+   *       the full instruction set of the TrueType virtual machine.
+   *       See the file `docs/PATENTS' for legal aspects.
+   *
+   *  @since:
+   *       2.2
+   *
+   */
+  typedef enum
+  {
+    FT_TRUETYPE_ENGINE_TYPE_NONE = 0,
+    FT_TRUETYPE_ENGINE_TYPE_UNPATENTED,
+    FT_TRUETYPE_ENGINE_TYPE_PATENTED
+
+  } FT_TrueTypeEngineType;
+
+
+  /**************************************************************************
+   *
+   *  @func:
+   *     FT_Get_TrueType_Engine_Type
+   *
+   *  @description:
+   *     Return a @FT_TrueTypeEngineType value to indicate which level of
+   *     the TrueType virtual machine a given library instance supports.
+   *
+   *  @input:
+   *     library ::
+   *       A library instance.
+   *
+   *  @return:
+   *     A value indicating which level is supported.
+   *
+   *  @since:
+   *     2.2
+   *
+   */
+  FT_EXPORT( FT_TrueTypeEngineType )
+  FT_Get_TrueType_Engine_Type( FT_Library  library );
+
+
+  /* */
+
+
+FT_END_HEADER
+
+#endif /* __FTMODAPI_H__ */
+
+
+/* END */

+ 155 - 0
include/freetype/ftmoderr.h

@@ -0,0 +1,155 @@
+/***************************************************************************/
+/*                                                                         */
+/*  ftmoderr.h                                                             */
+/*                                                                         */
+/*    FreeType module error offsets (specification).                       */
+/*                                                                         */
+/*  Copyright 2001, 2002, 2003, 2004, 2005 by                              */
+/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */
+/*                                                                         */
+/*  This file is part of the FreeType project, and may only be used,       */
+/*  modified, and distributed under the terms of the FreeType project      */
+/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */
+/*  this file you indicate that you have read the license and              */
+/*  understand and accept it fully.                                        */
+/*                                                                         */
+/***************************************************************************/
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* This file is used to define the FreeType module error offsets.        */
+  /*                                                                       */
+  /* The lower byte gives the error code, the higher byte gives the        */
+  /* module.  The base module has error offset 0.  For example, the error  */
+  /* `FT_Err_Invalid_File_Format' has value 0x003, the error               */
+  /* `TT_Err_Invalid_File_Format' has value 0x1103, the error              */
+  /* `T1_Err_Invalid_File_Format' has value 0x1203, etc.                   */
+  /*                                                                       */
+  /* Undefine the macro FT_CONFIG_OPTION_USE_MODULE_ERRORS in ftoption.h   */
+  /* to make the higher byte always zero (disabling the module error       */
+  /* mechanism).                                                           */
+  /*                                                                       */
+  /* It can also be used to create a module error message table easily     */
+  /* with something like                                                   */
+  /*                                                                       */
+  /*   {                                                                   */
+  /*     #undef __FTMODERR_H__                                             */
+  /*     #define FT_MODERRDEF( e, v, s )  { FT_Mod_Err_ ## e, s },         */
+  /*     #define FT_MODERR_START_LIST     {                                */
+  /*     #define FT_MODERR_END_LIST       { 0, 0 } };                      */
+  /*                                                                       */
+  /*     const struct                                                      */
+  /*     {                                                                 */
+  /*       int          mod_err_offset;                                    */
+  /*       const char*  mod_err_msg                                        */
+  /*     } ft_mod_errors[] =                                               */
+  /*                                                                       */
+  /*     #include FT_MODULE_ERRORS_H                                       */
+  /*   }                                                                   */
+  /*                                                                       */
+  /* To use such a table, all errors must be ANDed with 0xFF00 to remove   */
+  /* the error code.                                                       */
+  /*                                                                       */
+  /*************************************************************************/
+
+
+#ifndef __FTMODERR_H__
+#define __FTMODERR_H__
+
+
+  /*******************************************************************/
+  /*******************************************************************/
+  /*****                                                         *****/
+  /*****                       SETUP MACROS                      *****/
+  /*****                                                         *****/
+  /*******************************************************************/
+  /*******************************************************************/
+
+
+#undef  FT_NEED_EXTERN_C
+
+#ifndef FT_MODERRDEF
+
+#ifdef FT_CONFIG_OPTION_USE_MODULE_ERRORS
+#define FT_MODERRDEF( e, v, s )  FT_Mod_Err_ ## e = v,
+#else
+#define FT_MODERRDEF( e, v, s )  FT_Mod_Err_ ## e = 0,
+#endif
+
+#define FT_MODERR_START_LIST  enum {
+#define FT_MODERR_END_LIST    FT_Mod_Err_Max };
+
+#ifdef __cplusplus
+#define FT_NEED_EXTERN_C
+  extern "C" {
+#endif
+
+#endif /* !FT_MODERRDEF */
+
+
+  /*******************************************************************/
+  /*******************************************************************/
+  /*****                                                         *****/
+  /*****               LIST MODULE ERROR BASES                   *****/
+  /*****                                                         *****/
+  /*******************************************************************/
+  /*******************************************************************/
+
+
+#ifdef FT_MODERR_START_LIST
+  FT_MODERR_START_LIST
+#endif
+
+
+  FT_MODERRDEF( Base,      0x000, "base module" )
+  FT_MODERRDEF( Autofit,   0x100, "autofitter module" )
+  FT_MODERRDEF( BDF,       0x200, "BDF module" )
+  FT_MODERRDEF( Cache,     0x300, "cache module" )
+  FT_MODERRDEF( CFF,       0x400, "CFF module" )
+  FT_MODERRDEF( CID,       0x500, "CID module" )
+  FT_MODERRDEF( Gzip,      0x600, "Gzip module" )
+  FT_MODERRDEF( LZW,       0x700, "LZW module" )
+  FT_MODERRDEF( OTvalid,   0x800, "OpenType validation module" )
+  FT_MODERRDEF( PCF,       0x900, "PCF module" )
+  FT_MODERRDEF( PFR,       0xA00, "PFR module" )
+  FT_MODERRDEF( PSaux,     0xB00, "PS auxiliary module" )
+  FT_MODERRDEF( PShinter,  0xC00, "PS hinter module" )
+  FT_MODERRDEF( PSnames,   0xD00, "PS names module" )
+  FT_MODERRDEF( Raster,    0xE00, "raster module" )
+  FT_MODERRDEF( SFNT,      0xF00, "SFNT module" )
+  FT_MODERRDEF( Smooth,   0x1000, "smooth raster module" )
+  FT_MODERRDEF( TrueType, 0x1100, "TrueType module" )
+  FT_MODERRDEF( Type1,    0x1200, "Type 1 module" )
+  FT_MODERRDEF( Type42,   0x1300, "Type 42 module" )
+  FT_MODERRDEF( Winfonts, 0x1400, "Windows FON/FNT module" )
+
+
+#ifdef FT_MODERR_END_LIST
+  FT_MODERR_END_LIST
+#endif
+
+
+  /*******************************************************************/
+  /*******************************************************************/
+  /*****                                                         *****/
+  /*****                      CLEANUP                            *****/
+  /*****                                                         *****/
+  /*******************************************************************/
+  /*******************************************************************/
+
+
+#ifdef FT_NEED_EXTERN_C
+  }
+#endif
+
+#undef FT_MODERR_START_LIST
+#undef FT_MODERR_END_LIST
+#undef FT_MODERRDEF
+#undef FT_NEED_EXTERN_C
+
+
+#endif /* __FTMODERR_H__ */
+
+
+/* END */

+ 198 - 0
include/freetype/ftotval.h

@@ -0,0 +1,198 @@
+/***************************************************************************/
+/*                                                                         */
+/*  ftotval.h                                                              */
+/*                                                                         */
+/*    FreeType API for validating OpenType tables (specification).         */
+/*                                                                         */
+/*  Copyright 2004, 2005, 2006 by                                          */
+/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */
+/*                                                                         */
+/*  This file is part of the FreeType project, and may only be used,       */
+/*  modified, and distributed under the terms of the FreeType project      */
+/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */
+/*  this file you indicate that you have read the license and              */
+/*  understand and accept it fully.                                        */
+/*                                                                         */
+/***************************************************************************/
+
+
+/***************************************************************************/
+/*                                                                         */
+/*                                                                         */
+/* Warning: This module might be moved to a different library in the       */
+/*          future to avoid a tight dependency between FreeType and the    */
+/*          OpenType specification.                                        */
+/*                                                                         */
+/*                                                                         */
+/***************************************************************************/
+
+
+#ifndef __FTOTVAL_H__
+#define __FTOTVAL_H__
+
+#include <ft2build.h>
+#include FT_FREETYPE_H
+
+#ifdef FREETYPE_H
+#error "freetype.h of FreeType 1 has been loaded!"
+#error "Please fix the directory search order for header files"
+#error "so that freetype.h of FreeType 2 is found first."
+#endif
+
+
+FT_BEGIN_HEADER
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Section>                                                             */
+  /*    ot_validation                                                      */
+  /*                                                                       */
+  /* <Title>                                                               */
+  /*    OpenType Validation                                                */
+  /*                                                                       */
+  /* <Abstract>                                                            */
+  /*    An API to validate OpenType tables.                                */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    This section contains the declaration of functions to validate     */
+  /*    some OpenType tables (BASE, GDEF, GPOS, GSUB, JSTF).               */
+  /*                                                                       */
+  /*************************************************************************/
+
+
+ /**********************************************************************
+  *
+  * @enum:
+  *    FT_VALIDATE_OTXXX
+  *
+  * @description:
+  *    A list of bit-field constants used with @FT_OpenType_Validate to
+  *    indicate which OpenType tables should be validated.
+  *
+  * @values:
+  *    FT_VALIDATE_BASE ::
+  *      Validate BASE table.
+  *
+  *    FT_VALIDATE_GDEF ::
+  *      Validate GDEF table.
+  *
+  *    FT_VALIDATE_GPOS ::
+  *      Validate GPOS table.
+  *
+  *    FT_VALIDATE_GSUB ::
+  *      Validate GSUB table.
+  *
+  *    FT_VALIDATE_JSTF ::
+  *      Validate JSTF table.
+  *
+  *    FT_VALIDATE_OT ::
+  *      Validate all OpenType tables (BASE, GDEF, GPOS, GSUB, JSTF).
+  *
+  */
+#define FT_VALIDATE_BASE  0x0100
+#define FT_VALIDATE_GDEF  0x0200
+#define FT_VALIDATE_GPOS  0x0400
+#define FT_VALIDATE_GSUB  0x0800
+#define FT_VALIDATE_JSTF  0x1000
+
+#define FT_VALIDATE_OT  FT_VALIDATE_BASE | \
+                        FT_VALIDATE_GDEF | \
+                        FT_VALIDATE_GPOS | \
+                        FT_VALIDATE_GSUB | \
+                        FT_VALIDATE_JSTF
+
+  /* */
+
+ /**********************************************************************
+  *
+  * @function:
+  *    FT_OpenType_Validate
+  *
+  * @description:
+  *    Validate various OpenType tables to assure that all offsets and
+  *    indices are valid.  The idea is that a higher-level library which
+  *    actually does the text layout can access those tables without
+  *    error checking (which can be quite time consuming).
+  *
+  * @input:
+  *    face ::
+  *       A handle to the input face.
+  *
+  *    validation_flags ::
+  *       A bit field which specifies the tables to be validated.  See
+  *       @FT_VALIDATE_OTXXX for possible values.
+  *
+  * @output:
+  *    BASE_table ::
+  *       A pointer to the BASE table.
+  *
+  *    GDEF_table ::
+  *       A pointer to the GDEF table.
+  *
+  *    GPOS_table ::
+  *       A pointer to the GPOS table.
+  *
+  *    GSUB_table ::
+  *       A pointer to the GSUB table.
+  *
+  *    JSTF_table ::
+  *       A pointer to the JSTF table.
+  *
+  * @return:
+  *   FreeType error code.  0 means success.
+  *
+  * @note:
+  *   This function only works with OpenType fonts, returning an error
+  *   otherwise.
+  *
+  *   After use, the application should deallocate the five tables with
+  *   @FT_OpenType_Free.  A NULL value indicates that the table either
+  *   doesn't exist in the font, or the application hasn't asked for
+  *   validation.
+  */
+  FT_EXPORT( FT_Error )
+  FT_OpenType_Validate( FT_Face    face,
+                        FT_UInt    validation_flags,
+                        FT_Bytes  *BASE_table,
+                        FT_Bytes  *GDEF_table,
+                        FT_Bytes  *GPOS_table,
+                        FT_Bytes  *GSUB_table,
+                        FT_Bytes  *JSTF_table );
+
+  /* */
+
+ /**********************************************************************
+  *
+  * @function:
+  *    FT_OpenType_Free
+  *
+  * @description:
+  *    Free the buffer allocated by OpenType validator.
+  *
+  * @input:
+  *    face ::
+  *       A handle to the input face.
+  *
+  *    table ::
+  *       The pointer to the buffer that is allocated by
+  *       @FT_OpenType_Validate.
+  *
+  * @note:
+  *   This function must be used to free the buffer allocated by
+  *   @FT_OpenType_Validate only.
+  */
+  FT_EXPORT( void )
+  FT_OpenType_Free( FT_Face   face,
+                    FT_Bytes  table );
+
+
+ /* */
+
+
+FT_END_HEADER
+
+#endif /* __FTOTVAL_H__ */
+
+
+/* END */

+ 526 - 0
include/freetype/ftoutln.h

@@ -0,0 +1,526 @@
+/***************************************************************************/
+/*                                                                         */
+/*  ftoutln.h                                                              */
+/*                                                                         */
+/*    Support for the FT_Outline type used to store glyph shapes of        */
+/*    most scalable font formats (specification).                          */
+/*                                                                         */
+/*  Copyright 1996-2001, 2002, 2003, 2005, 2006, 2007 by                   */
+/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */
+/*                                                                         */
+/*  This file is part of the FreeType project, and may only be used,       */
+/*  modified, and distributed under the terms of the FreeType project      */
+/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */
+/*  this file you indicate that you have read the license and              */
+/*  understand and accept it fully.                                        */
+/*                                                                         */
+/***************************************************************************/
+
+
+#ifndef __FTOUTLN_H__
+#define __FTOUTLN_H__
+
+
+#include <ft2build.h>
+#include FT_FREETYPE_H
+
+#ifdef FREETYPE_H
+#error "freetype.h of FreeType 1 has been loaded!"
+#error "Please fix the directory search order for header files"
+#error "so that freetype.h of FreeType 2 is found first."
+#endif
+
+
+FT_BEGIN_HEADER
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Section>                                                             */
+  /*    outline_processing                                                 */
+  /*                                                                       */
+  /* <Title>                                                               */
+  /*    Outline Processing                                                 */
+  /*                                                                       */
+  /* <Abstract>                                                            */
+  /*    Functions to create, transform, and render vectorial glyph images. */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    This section contains routines used to create and destroy scalable */
+  /*    glyph images known as `outlines'.  These can also be measured,     */
+  /*    transformed, and converted into bitmaps and pixmaps.               */
+  /*                                                                       */
+  /* <Order>                                                               */
+  /*    FT_Outline                                                         */
+  /*    FT_OUTLINE_FLAGS                                                   */
+  /*    FT_Outline_New                                                     */
+  /*    FT_Outline_Done                                                    */
+  /*    FT_Outline_Copy                                                    */
+  /*    FT_Outline_Translate                                               */
+  /*    FT_Outline_Transform                                               */
+  /*    FT_Outline_Embolden                                                */
+  /*    FT_Outline_Reverse                                                 */
+  /*    FT_Outline_Check                                                   */
+  /*                                                                       */
+  /*    FT_Outline_Get_CBox                                                */
+  /*    FT_Outline_Get_BBox                                                */
+  /*                                                                       */
+  /*    FT_Outline_Get_Bitmap                                              */
+  /*    FT_Outline_Render                                                  */
+  /*                                                                       */
+  /*    FT_Outline_Decompose                                               */
+  /*    FT_Outline_Funcs                                                   */
+  /*    FT_Outline_MoveTo_Func                                             */
+  /*    FT_Outline_LineTo_Func                                             */
+  /*    FT_Outline_ConicTo_Func                                            */
+  /*    FT_Outline_CubicTo_Func                                            */
+  /*                                                                       */
+  /*************************************************************************/
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FT_Outline_Decompose                                               */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    Walks over an outline's structure to decompose it into individual  */
+  /*    segments and Bézier arcs.  This function is also able to emit      */
+  /*    `move to' and `close to' operations to indicate the start and end  */
+  /*    of new contours in the outline.                                    */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    outline        :: A pointer to the source target.                  */
+  /*                                                                       */
+  /*    func_interface :: A table of `emitters', i.e,. function pointers   */
+  /*                      called during decomposition to indicate path     */
+  /*                      operations.                                      */
+  /*                                                                       */
+  /* <InOut>                                                               */
+  /*    user           :: A typeless pointer which is passed to each       */
+  /*                      emitter during the decomposition.  It can be     */
+  /*                      used to store the state during the               */
+  /*                      decomposition.                                   */
+  /*                                                                       */
+  /* <Return>                                                              */
+  /*    FreeType error code.  0 means success.                             */
+  /*                                                                       */
+  FT_EXPORT( FT_Error )
+  FT_Outline_Decompose( FT_Outline*              outline,
+                        const FT_Outline_Funcs*  func_interface,
+                        void*                    user );
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FT_Outline_New                                                     */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    Creates a new outline of a given size.                             */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    library     :: A handle to the library object from where the       */
+  /*                   outline is allocated.  Note however that the new    */
+  /*                   outline will *not* necessarily be *freed*, when     */
+  /*                   destroying the library, by @FT_Done_FreeType.       */
+  /*                                                                       */
+  /*    numPoints   :: The maximal number of points within the outline.    */
+  /*                                                                       */
+  /*    numContours :: The maximal number of contours within the outline.  */
+  /*                                                                       */
+  /* <Output>                                                              */
+  /*    anoutline   :: A handle to the new outline.  NULL in case of       */
+  /*                   error.                                              */
+  /*                                                                       */
+  /* <Return>                                                              */
+  /*    FreeType error code.  0 means success.                             */
+  /*                                                                       */
+  /* <Note>                                                                */
+  /*    The reason why this function takes a `library' parameter is simply */
+  /*    to use the library's memory allocator.                             */
+  /*                                                                       */
+  FT_EXPORT( FT_Error )
+  FT_Outline_New( FT_Library   library,
+                  FT_UInt      numPoints,
+                  FT_Int       numContours,
+                  FT_Outline  *anoutline );
+
+
+  FT_EXPORT( FT_Error )
+  FT_Outline_New_Internal( FT_Memory    memory,
+                           FT_UInt      numPoints,
+                           FT_Int       numContours,
+                           FT_Outline  *anoutline );
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FT_Outline_Done                                                    */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    Destroys an outline created with @FT_Outline_New.                  */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    library :: A handle of the library object used to allocate the     */
+  /*               outline.                                                */
+  /*                                                                       */
+  /*    outline :: A pointer to the outline object to be discarded.        */
+  /*                                                                       */
+  /* <Return>                                                              */
+  /*    FreeType error code.  0 means success.                             */
+  /*                                                                       */
+  /* <Note>                                                                */
+  /*    If the outline's `owner' field is not set, only the outline        */
+  /*    descriptor will be released.                                       */
+  /*                                                                       */
+  /*    The reason why this function takes an `library' parameter is       */
+  /*    simply to use ft_mem_free().                                       */
+  /*                                                                       */
+  FT_EXPORT( FT_Error )
+  FT_Outline_Done( FT_Library   library,
+                   FT_Outline*  outline );
+
+
+  FT_EXPORT( FT_Error )
+  FT_Outline_Done_Internal( FT_Memory    memory,
+                            FT_Outline*  outline );
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FT_Outline_Check                                                   */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    Check the contents of an outline descriptor.                       */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    outline :: A handle to a source outline.                           */
+  /*                                                                       */
+  /* <Return>                                                              */
+  /*    FreeType error code.  0 means success.                             */
+  /*                                                                       */
+  FT_EXPORT( FT_Error )
+  FT_Outline_Check( FT_Outline*  outline );
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FT_Outline_Get_CBox                                                */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    Returns an outline's `control box'.  The control box encloses all  */
+  /*    the outline's points, including Bézier control points.  Though it  */
+  /*    coincides with the exact bounding box for most glyphs, it can be   */
+  /*    slightly larger in some situations (like when rotating an outline  */
+  /*    which contains Bézier outside arcs).                               */
+  /*                                                                       */
+  /*    Computing the control box is very fast, while getting the bounding */
+  /*    box can take much more time as it needs to walk over all segments  */
+  /*    and arcs in the outline.  To get the latter, you can use the       */
+  /*    `ftbbox' component which is dedicated to this single task.         */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    outline :: A pointer to the source outline descriptor.             */
+  /*                                                                       */
+  /* <Output>                                                              */
+  /*    acbox   :: The outline's control box.                              */
+  /*                                                                       */
+  FT_EXPORT( void )
+  FT_Outline_Get_CBox( const FT_Outline*  outline,
+                       FT_BBox           *acbox );
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FT_Outline_Translate                                               */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    Applies a simple translation to the points of an outline.          */
+  /*                                                                       */
+  /* <InOut>                                                               */
+  /*    outline :: A pointer to the target outline descriptor.             */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    xOffset :: The horizontal offset.                                  */
+  /*                                                                       */
+  /*    yOffset :: The vertical offset.                                    */
+  /*                                                                       */
+  FT_EXPORT( void )
+  FT_Outline_Translate( const FT_Outline*  outline,
+                        FT_Pos             xOffset,
+                        FT_Pos             yOffset );
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FT_Outline_Copy                                                    */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    Copies an outline into another one.  Both objects must have the    */
+  /*    same sizes (number of points & number of contours) when this       */
+  /*    function is called.                                                */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    source :: A handle to the source outline.                          */
+  /*                                                                       */
+  /* <Output>                                                              */
+  /*    target :: A handle to the target outline.                          */
+  /*                                                                       */
+  /* <Return>                                                              */
+  /*    FreeType error code.  0 means success.                             */
+  /*                                                                       */
+  FT_EXPORT( FT_Error )
+  FT_Outline_Copy( const FT_Outline*  source,
+                   FT_Outline        *target );
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FT_Outline_Transform                                               */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    Applies a simple 2x2 matrix to all of an outline's points.  Useful */
+  /*    for applying rotations, slanting, flipping, etc.                   */
+  /*                                                                       */
+  /* <InOut>                                                               */
+  /*    outline :: A pointer to the target outline descriptor.             */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    matrix  :: A pointer to the transformation matrix.                 */
+  /*                                                                       */
+  /* <Note>                                                                */
+  /*    You can use @FT_Outline_Translate if you need to translate the     */
+  /*    outline's points.                                                  */
+  /*                                                                       */
+  FT_EXPORT( void )
+  FT_Outline_Transform( const FT_Outline*  outline,
+                        const FT_Matrix*   matrix );
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FT_Outline_Embolden                                                */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    Emboldens an outline.  The new outline will be at most 4 times     */
+  /*    `strength' pixels wider and higher.  You may think of the left and */
+  /*    bottom borders as unchanged.                                       */
+  /*                                                                       */
+  /*    Negative `strength' values to reduce the outline thickness are     */
+  /*    possible also.                                                     */
+  /*                                                                       */
+  /* <InOut>                                                               */
+  /*    outline  :: A handle to the target outline.                        */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    strength :: How strong the glyph is emboldened.  Expressed in      */
+  /*                26.6 pixel format.                                     */
+  /*                                                                       */
+  /* <Return>                                                              */
+  /*    FreeType error code.  0 means success.                             */
+  /*                                                                       */
+  /* <Note>                                                                */
+  /*    The used algorithm to increase or decrease the thickness of the    */
+  /*    glyph doesn't change the number of points; this means that certain */
+  /*    situations like acute angles or intersections are sometimes        */
+  /*    handled incorrectly.                                               */
+  /*                                                                       */
+  /*    Example call:                                                      */
+  /*                                                                       */
+  /*    {                                                                  */
+  /*      FT_Load_Glyph( face, index, FT_LOAD_DEFAULT );                   */
+  /*      if ( face->slot->format == FT_GLYPH_FORMAT_OUTLINE )             */
+  /*        FT_Outline_Embolden( &face->slot->outline, strength );         */
+  /*    }                                                                  */
+  /*                                                                       */
+  FT_EXPORT( FT_Error )
+  FT_Outline_Embolden( FT_Outline*  outline,
+                       FT_Pos       strength );
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FT_Outline_Reverse                                                 */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    Reverses the drawing direction of an outline.  This is used to     */
+  /*    ensure consistent fill conventions for mirrored glyphs.            */
+  /*                                                                       */
+  /* <InOut>                                                               */
+  /*    outline :: A pointer to the target outline descriptor.             */
+  /*                                                                       */
+  /* <Note>                                                                */
+  /*    This functions toggles the bit flag @FT_OUTLINE_REVERSE_FILL in    */
+  /*    the outline's `flags' field.                                       */
+  /*                                                                       */
+  /*    It shouldn't be used by a normal client application, unless it     */
+  /*    knows what it is doing.                                            */
+  /*                                                                       */
+  FT_EXPORT( void )
+  FT_Outline_Reverse( FT_Outline*  outline );
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FT_Outline_Get_Bitmap                                              */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    Renders an outline within a bitmap.  The outline's image is simply */
+  /*    OR-ed to the target bitmap.                                        */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    library :: A handle to a FreeType library object.                  */
+  /*                                                                       */
+  /*    outline :: A pointer to the source outline descriptor.             */
+  /*                                                                       */
+  /* <InOut>                                                               */
+  /*    abitmap :: A pointer to the target bitmap descriptor.              */
+  /*                                                                       */
+  /* <Return>                                                              */
+  /*    FreeType error code.  0 means success.                             */
+  /*                                                                       */
+  /* <Note>                                                                */
+  /*    This function does NOT CREATE the bitmap, it only renders an       */
+  /*    outline image within the one you pass to it!                       */
+  /*                                                                       */
+  /*    It will use the raster corresponding to the default glyph format.  */
+  /*                                                                       */
+  FT_EXPORT( FT_Error )
+  FT_Outline_Get_Bitmap( FT_Library        library,
+                         FT_Outline*       outline,
+                         const FT_Bitmap  *abitmap );
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FT_Outline_Render                                                  */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    Renders an outline within a bitmap using the current scan-convert. */
+  /*    This functions uses an @FT_Raster_Params structure as an argument, */
+  /*    allowing advanced features like direct composition, translucency,  */
+  /*    etc.                                                               */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    library :: A handle to a FreeType library object.                  */
+  /*                                                                       */
+  /*    outline :: A pointer to the source outline descriptor.             */
+  /*                                                                       */
+  /* <InOut>                                                               */
+  /*    params  :: A pointer to an @FT_Raster_Params structure used to     */
+  /*               describe the rendering operation.                       */
+  /*                                                                       */
+  /* <Return>                                                              */
+  /*    FreeType error code.  0 means success.                             */
+  /*                                                                       */
+  /* <Note>                                                                */
+  /*    You should know what you are doing and how @FT_Raster_Params works */
+  /*    to use this function.                                              */
+  /*                                                                       */
+  /*    The field `params.source' will be set to `outline' before the scan */
+  /*    converter is called, which means that the value you give to it is  */
+  /*    actually ignored.                                                  */
+  /*                                                                       */
+  FT_EXPORT( FT_Error )
+  FT_Outline_Render( FT_Library         library,
+                     FT_Outline*        outline,
+                     FT_Raster_Params*  params );
+
+
+ /**************************************************************************
+  *
+  * @enum:
+  *   FT_Orientation
+  *
+  * @description:
+  *   A list of values used to describe an outline's contour orientation.
+  *
+  *   The TrueType and Postscript specifications use different conventions
+  *   to determine whether outline contours should be filled or unfilled.
+  *
+  * @values:
+  *   FT_ORIENTATION_TRUETYPE ::
+  *     According to the TrueType specification, clockwise contours must
+  *     be filled, and counter-clockwise ones must be unfilled.
+  *
+  *   FT_ORIENTATION_POSTSCRIPT ::
+  *     According to the Postscript specification, counter-clockwise contours
+  *     must be filled, and clockwise ones must be unfilled.
+  *
+  *   FT_ORIENTATION_FILL_RIGHT ::
+  *     This is identical to @FT_ORIENTATION_TRUETYPE, but is used to
+  *     remember that in TrueType, everything that is to the right of
+  *     the drawing direction of a contour must be filled.
+  *
+  *   FT_ORIENTATION_FILL_LEFT ::
+  *     This is identical to @FT_ORIENTATION_POSTSCRIPT, but is used to
+  *     remember that in Postscript, everything that is to the left of
+  *     the drawing direction of a contour must be filled.
+  *
+  *   FT_ORIENTATION_NONE ::
+  *     The orientation cannot be determined.  That is, different parts of
+  *     the glyph have different orientation.
+  *
+  */
+  typedef enum
+  {
+    FT_ORIENTATION_TRUETYPE   = 0,
+    FT_ORIENTATION_POSTSCRIPT = 1,
+    FT_ORIENTATION_FILL_RIGHT = FT_ORIENTATION_TRUETYPE,
+    FT_ORIENTATION_FILL_LEFT  = FT_ORIENTATION_POSTSCRIPT,
+    FT_ORIENTATION_NONE
+
+  } FT_Orientation;
+
+
+ /**************************************************************************
+  *
+  * @function:
+  *   FT_Outline_Get_Orientation
+  *
+  * @description:
+  *   This function analyzes a glyph outline and tries to compute its
+  *   fill orientation (see @FT_Orientation).  This is done by computing
+  *   the direction of each global horizontal and/or vertical extrema
+  *   within the outline.
+  *
+  *   Note that this will return @FT_ORIENTATION_TRUETYPE for empty
+  *   outlines.
+  *
+  * @input:
+  *   outline ::
+  *     A handle to the source outline.
+  *
+  * @return:
+  *   The orientation.
+  *
+  */
+  FT_EXPORT( FT_Orientation )
+  FT_Outline_Get_Orientation( FT_Outline*  outline );
+
+
+  /* */
+
+
+FT_END_HEADER
+
+#endif /* __FTOUTLN_H__ */
+
+
+/* END */
+
+
+/* Local Variables: */
+/* coding: utf-8    */
+/* End:             */

+ 172 - 0
include/freetype/ftpfr.h

@@ -0,0 +1,172 @@
+/***************************************************************************/
+/*                                                                         */
+/*  ftpfr.h                                                                */
+/*                                                                         */
+/*    FreeType API for accessing PFR-specific data (specification only).   */
+/*                                                                         */
+/*  Copyright 2002, 2003, 2004, 2006 by                                    */
+/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */
+/*                                                                         */
+/*  This file is part of the FreeType project, and may only be used,       */
+/*  modified, and distributed under the terms of the FreeType project      */
+/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */
+/*  this file you indicate that you have read the license and              */
+/*  understand and accept it fully.                                        */
+/*                                                                         */
+/***************************************************************************/
+
+
+#ifndef __FTPFR_H__
+#define __FTPFR_H__
+
+#include <ft2build.h>
+#include FT_FREETYPE_H
+
+#ifdef FREETYPE_H
+#error "freetype.h of FreeType 1 has been loaded!"
+#error "Please fix the directory search order for header files"
+#error "so that freetype.h of FreeType 2 is found first."
+#endif
+
+
+FT_BEGIN_HEADER
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Section>                                                             */
+  /*    pfr_fonts                                                          */
+  /*                                                                       */
+  /* <Title>                                                               */
+  /*    PFR Fonts                                                          */
+  /*                                                                       */
+  /* <Abstract>                                                            */
+  /*    PFR/TrueDoc specific API.                                          */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    This section contains the declaration of PFR-specific functions.   */
+  /*                                                                       */
+  /*************************************************************************/
+
+
+ /**********************************************************************
+  *
+  * @function:
+  *    FT_Get_PFR_Metrics
+  *
+  * @description:
+  *    Return the outline and metrics resolutions of a given PFR face.
+  *
+  * @input:
+  *    face :: Handle to the input face.  It can be a non-PFR face.
+  *
+  * @output:
+  *    aoutline_resolution ::
+  *      Outline resolution.  This is equivalent to `face->units_per_EM'.
+  *      Optional (parameter can be NULL).
+  *
+  *    ametrics_resolution ::
+  *      Metrics resolution.  This is equivalent to `outline_resolution'
+  *      for non-PFR fonts.  Optional (parameter can be NULL).
+  *
+  *    ametrics_x_scale ::
+  *      A 16.16 fixed-point number used to scale distance expressed
+  *      in metrics units to device sub-pixels.  This is equivalent to
+  *      `face->size->x_scale', but for metrics only.  Optional (parameter
+  *      can be NULL)
+  *
+  *    ametrics_y_scale ::
+  *      Same as `ametrics_x_scale' but for the vertical direction.
+  *      optional (parameter can be NULL)
+  *
+  * @return:
+  *    FreeType error code.  0 means success.
+  *
+  * @note:
+  *   If the input face is not a PFR, this function will return an error.
+  *   However, in all cases, it will return valid values.
+  */
+  FT_EXPORT( FT_Error )
+  FT_Get_PFR_Metrics( FT_Face    face,
+                      FT_UInt   *aoutline_resolution,
+                      FT_UInt   *ametrics_resolution,
+                      FT_Fixed  *ametrics_x_scale,
+                      FT_Fixed  *ametrics_y_scale );
+
+
+ /**********************************************************************
+  *
+  * @function:
+  *    FT_Get_PFR_Kerning
+  *
+  * @description:
+  *    Return the kerning pair corresponding to two glyphs in a PFR face.
+  *    The distance is expressed in metrics units, unlike the result of
+  *    @FT_Get_Kerning.
+  *
+  * @input:
+  *    face  :: A handle to the input face.
+  *
+  *    left  :: Index of the left glyph.
+  *
+  *    right :: Index of the right glyph.
+  *
+  * @output:
+  *    avector :: A kerning vector.
+  *
+  * @return:
+  *    FreeType error code.  0 means success.
+  *
+  * @note:
+  *    This function always return distances in original PFR metrics
+  *    units.  This is unlike @FT_Get_Kerning with the @FT_KERNING_UNSCALED
+  *    mode, which always returns distances converted to outline units.
+  *
+  *    You can use the value of the `x_scale' and `y_scale' parameters
+  *    returned by @FT_Get_PFR_Metrics to scale these to device sub-pixels.
+  */
+  FT_EXPORT( FT_Error )
+  FT_Get_PFR_Kerning( FT_Face     face,
+                      FT_UInt     left,
+                      FT_UInt     right,
+                      FT_Vector  *avector );
+
+
+ /**********************************************************************
+  *
+  * @function:
+  *    FT_Get_PFR_Advance
+  *
+  * @description:
+  *    Return a given glyph advance, expressed in original metrics units,
+  *    from a PFR font.
+  *
+  * @input:
+  *    face   :: A handle to the input face.
+  *
+  *    gindex :: The glyph index.
+  *
+  * @output:
+  *    aadvance :: The glyph advance in metrics units.
+  *
+  * @return:
+  *    FreeType error code.  0 means success.
+  *
+  * @note:
+  *    You can use the `x_scale' or `y_scale' results of @FT_Get_PFR_Metrics
+  *    to convert the advance to device sub-pixels (i.e., 1/64th of pixels).
+  */
+  FT_EXPORT( FT_Error )
+  FT_Get_PFR_Advance( FT_Face   face,
+                      FT_UInt   gindex,
+                      FT_Pos   *aadvance );
+
+ /* */
+
+
+FT_END_HEADER
+
+#endif /* __FTPFR_H__ */
+
+
+/* END */

+ 229 - 0
include/freetype/ftrender.h

@@ -0,0 +1,229 @@
+/***************************************************************************/
+/*                                                                         */
+/*  ftrender.h                                                             */
+/*                                                                         */
+/*    FreeType renderer modules public interface (specification).          */
+/*                                                                         */
+/*  Copyright 1996-2001, 2005, 2006 by                                     */
+/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */
+/*                                                                         */
+/*  This file is part of the FreeType project, and may only be used,       */
+/*  modified, and distributed under the terms of the FreeType project      */
+/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */
+/*  this file you indicate that you have read the license and              */
+/*  understand and accept it fully.                                        */
+/*                                                                         */
+/***************************************************************************/
+
+
+#ifndef __FTRENDER_H__
+#define __FTRENDER_H__
+
+
+#include <ft2build.h>
+#include FT_MODULE_H
+#include FT_GLYPH_H
+
+
+FT_BEGIN_HEADER
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Section>                                                             */
+  /*    module_management                                                  */
+  /*                                                                       */
+  /*************************************************************************/
+
+
+  /* create a new glyph object */
+  typedef FT_Error
+  (*FT_Glyph_InitFunc)( FT_Glyph      glyph,
+                        FT_GlyphSlot  slot );
+
+  /* destroys a given glyph object */
+  typedef void
+  (*FT_Glyph_DoneFunc)( FT_Glyph  glyph );
+
+  typedef void
+  (*FT_Glyph_TransformFunc)( FT_Glyph          glyph,
+                             const FT_Matrix*  matrix,
+                             const FT_Vector*  delta );
+
+  typedef void
+  (*FT_Glyph_GetBBoxFunc)( FT_Glyph  glyph,
+                           FT_BBox*  abbox );
+
+  typedef FT_Error
+  (*FT_Glyph_CopyFunc)( FT_Glyph   source,
+                        FT_Glyph   target );
+
+  typedef FT_Error
+  (*FT_Glyph_PrepareFunc)( FT_Glyph      glyph,
+                           FT_GlyphSlot  slot );
+
+/* deprecated */
+#define FT_Glyph_Init_Func       FT_Glyph_InitFunc
+#define FT_Glyph_Done_Func       FT_Glyph_DoneFunc
+#define FT_Glyph_Transform_Func  FT_Glyph_TransformFunc
+#define FT_Glyph_BBox_Func       FT_Glyph_GetBBoxFunc
+#define FT_Glyph_Copy_Func       FT_Glyph_CopyFunc
+#define FT_Glyph_Prepare_Func    FT_Glyph_PrepareFunc
+
+
+  struct  FT_Glyph_Class_
+  {
+    FT_Long                 glyph_size;
+    FT_Glyph_Format         glyph_format;
+    FT_Glyph_InitFunc       glyph_init;
+    FT_Glyph_DoneFunc       glyph_done;
+    FT_Glyph_CopyFunc       glyph_copy;
+    FT_Glyph_TransformFunc  glyph_transform;
+    FT_Glyph_GetBBoxFunc    glyph_bbox;
+    FT_Glyph_PrepareFunc    glyph_prepare;
+  };
+
+
+  typedef FT_Error
+  (*FT_Renderer_RenderFunc)( FT_Renderer       renderer,
+                             FT_GlyphSlot      slot,
+                             FT_UInt           mode,
+                             const FT_Vector*  origin );
+
+  typedef FT_Error
+  (*FT_Renderer_TransformFunc)( FT_Renderer       renderer,
+                                FT_GlyphSlot      slot,
+                                const FT_Matrix*  matrix,
+                                const FT_Vector*  delta );
+
+
+  typedef void
+  (*FT_Renderer_GetCBoxFunc)( FT_Renderer   renderer,
+                              FT_GlyphSlot  slot,
+                              FT_BBox*      cbox );
+
+
+  typedef FT_Error
+  (*FT_Renderer_SetModeFunc)( FT_Renderer  renderer,
+                              FT_ULong     mode_tag,
+                              FT_Pointer   mode_ptr );
+
+/* deprecated identifiers */
+#define FTRenderer_render  FT_Renderer_RenderFunc
+#define FTRenderer_transform  FT_Renderer_TransformFunc
+#define FTRenderer_getCBox  FT_Renderer_GetCBoxFunc
+#define FTRenderer_setMode  FT_Renderer_SetModeFunc
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Struct>                                                              */
+  /*    FT_Renderer_Class                                                  */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    The renderer module class descriptor.                              */
+  /*                                                                       */
+  /* <Fields>                                                              */
+  /*    root         :: The root @FT_Module_Class fields.                  */
+  /*                                                                       */
+  /*    glyph_format :: The glyph image format this renderer handles.      */
+  /*                                                                       */
+  /*    render_glyph :: A method used to render the image that is in a     */
+  /*                    given glyph slot into a bitmap.                    */
+  /*                                                                       */
+  /*    set_mode     :: A method used to pass additional parameters.       */
+  /*                                                                       */
+  /*    raster_class :: For @FT_GLYPH_FORMAT_OUTLINE renderers only.  This */
+  /*                    is a pointer to its raster's class.                */
+  /*                                                                       */
+  /*    raster       :: For @FT_GLYPH_FORMAT_OUTLINE renderers only.  This */
+  /*                    is a pointer to the corresponding raster object,   */
+  /*                    if any.                                            */
+  /*                                                                       */
+  typedef struct  FT_Renderer_Class_
+  {
+    FT_Module_Class       root;
+
+    FT_Glyph_Format       glyph_format;
+
+    FT_Renderer_RenderFunc     render_glyph;
+    FT_Renderer_TransformFunc  transform_glyph;
+    FT_Renderer_GetCBoxFunc    get_glyph_cbox;
+    FT_Renderer_SetModeFunc    set_mode;
+
+    FT_Raster_Funcs*           raster_class;
+
+  } FT_Renderer_Class;
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FT_Get_Renderer                                                    */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    Retrieves the current renderer for a given glyph format.           */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    library :: A handle to the library object.                         */
+  /*                                                                       */
+  /*    format  :: The glyph format.                                       */
+  /*                                                                       */
+  /* <Return>                                                              */
+  /*    A renderer handle.  0 if none found.                               */
+  /*                                                                       */
+  /* <Note>                                                                */
+  /*    An error will be returned if a module already exists by that name, */
+  /*    or if the module requires a version of FreeType that is too great. */
+  /*                                                                       */
+  /*    To add a new renderer, simply use @FT_Add_Module.  To retrieve a   */
+  /*    renderer by its name, use @FT_Get_Module.                          */
+  /*                                                                       */
+  FT_EXPORT( FT_Renderer )
+  FT_Get_Renderer( FT_Library       library,
+                   FT_Glyph_Format  format );
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FT_Set_Renderer                                                    */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    Sets the current renderer to use, and set additional mode.         */
+  /*                                                                       */
+  /* <InOut>                                                               */
+  /*    library    :: A handle to the library object.                      */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    renderer   :: A handle to the renderer object.                     */
+  /*                                                                       */
+  /*    num_params :: The number of additional parameters.                 */
+  /*                                                                       */
+  /*    parameters :: Additional parameters.                               */
+  /*                                                                       */
+  /* <Return>                                                              */
+  /*    FreeType error code.  0 means success.                             */
+  /*                                                                       */
+  /* <Note>                                                                */
+  /*    In case of success, the renderer will be used to convert glyph     */
+  /*    images in the renderer's known format into bitmaps.                */
+  /*                                                                       */
+  /*    This doesn't change the current renderer for other formats.        */
+  /*                                                                       */
+  FT_EXPORT( FT_Error )
+  FT_Set_Renderer( FT_Library     library,
+                   FT_Renderer    renderer,
+                   FT_UInt        num_params,
+                   FT_Parameter*  parameters );
+
+
+  /* */
+
+
+FT_END_HEADER
+
+#endif /* __FTRENDER_H__ */
+
+
+/* END */

+ 159 - 0
include/freetype/ftsizes.h

@@ -0,0 +1,159 @@
+/***************************************************************************/
+/*                                                                         */
+/*  ftsizes.h                                                              */
+/*                                                                         */
+/*    FreeType size objects management (specification).                    */
+/*                                                                         */
+/*  Copyright 1996-2001, 2003, 2004, 2006 by                               */
+/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */
+/*                                                                         */
+/*  This file is part of the FreeType project, and may only be used,       */
+/*  modified, and distributed under the terms of the FreeType project      */
+/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */
+/*  this file you indicate that you have read the license and              */
+/*  understand and accept it fully.                                        */
+/*                                                                         */
+/***************************************************************************/
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* Typical application would normally not need to use these functions.   */
+  /* However, they have been placed in a public API for the rare cases     */
+  /* where they are needed.                                                */
+  /*                                                                       */
+  /*************************************************************************/
+
+
+#ifndef __FTSIZES_H__
+#define __FTSIZES_H__
+
+
+#include <ft2build.h>
+#include FT_FREETYPE_H
+
+#ifdef FREETYPE_H
+#error "freetype.h of FreeType 1 has been loaded!"
+#error "Please fix the directory search order for header files"
+#error "so that freetype.h of FreeType 2 is found first."
+#endif
+
+
+FT_BEGIN_HEADER
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Section>                                                             */
+  /*    sizes_management                                                   */
+  /*                                                                       */
+  /* <Title>                                                               */
+  /*    Size Management                                                    */
+  /*                                                                       */
+  /* <Abstract>                                                            */
+  /*    Managing multiple sizes per face.                                  */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    When creating a new face object (e.g., with @FT_New_Face), an      */
+  /*    @FT_Size object is automatically created and used to store all     */
+  /*    pixel-size dependent information, available in the `face->size'    */
+  /*    field.                                                             */
+  /*                                                                       */
+  /*    It is however possible to create more sizes for a given face,      */
+  /*    mostly in order to manage several character pixel sizes of the     */
+  /*    same font family and style.  See @FT_New_Size and @FT_Done_Size.   */
+  /*                                                                       */
+  /*    Note that @FT_Set_Pixel_Sizes and @FT_Set_Char_Size only           */
+  /*    modify the contents of the current `active' size; you thus need    */
+  /*    to use @FT_Activate_Size to change it.                             */
+  /*                                                                       */
+  /*    99% of applications won't need the functions provided here,        */
+  /*    especially if they use the caching sub-system, so be cautious      */
+  /*    when using these.                                                  */
+  /*                                                                       */
+  /*************************************************************************/
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FT_New_Size                                                        */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    Create a new size object from a given face object.                 */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    face :: A handle to a parent face object.                          */
+  /*                                                                       */
+  /* <Output>                                                              */
+  /*    asize :: A handle to a new size object.                            */
+  /*                                                                       */
+  /* <Return>                                                              */
+  /*    FreeType error code.  0 means success.                             */
+  /*                                                                       */
+  /* <Note>                                                                */
+  /*    You need to call @FT_Activate_Size in order to select the new size */
+  /*    for upcoming calls to @FT_Set_Pixel_Sizes, @FT_Set_Char_Size,      */
+  /*    @FT_Load_Glyph, @FT_Load_Char, etc.                                */
+  /*                                                                       */
+  FT_EXPORT( FT_Error )
+  FT_New_Size( FT_Face   face,
+               FT_Size*  size );
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FT_Done_Size                                                       */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    Discard a given size object.  Note that @FT_Done_Face              */
+  /*    automatically discards all size objects allocated with             */
+  /*    @FT_New_Size.                                                      */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    size :: A handle to a target size object.                          */
+  /*                                                                       */
+  /* <Return>                                                              */
+  /*    FreeType error code.  0 means success.                             */
+  /*                                                                       */
+  FT_EXPORT( FT_Error )
+  FT_Done_Size( FT_Size  size );
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FT_Activate_Size                                                   */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    Even though it is possible to create several size objects for a    */
+  /*    given face (see @FT_New_Size for details), functions like          */
+  /*    @FT_Load_Glyph or @FT_Load_Char only use the last-created one to   */
+  /*    determine the `current character pixel size'.                      */
+  /*                                                                       */
+  /*    This function can be used to `activate' a previously created size  */
+  /*    object.                                                            */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    size :: A handle to a target size object.                          */
+  /*                                                                       */
+  /* <Return>                                                              */
+  /*    FreeType error code.  0 means success.                             */
+  /*                                                                       */
+  /* <Note>                                                                */
+  /*    If `face' is the size's parent face object, this function changes  */
+  /*    the value of `face->size' to the input size handle.                */
+  /*                                                                       */
+  FT_EXPORT( FT_Error )
+  FT_Activate_Size( FT_Size  size );
+
+  /* */
+
+
+FT_END_HEADER
+
+#endif /* __FTSIZES_H__ */
+
+
+/* END */

+ 170 - 0
include/freetype/ftsnames.h

@@ -0,0 +1,170 @@
+/***************************************************************************/
+/*                                                                         */
+/*  ftsnames.h                                                             */
+/*                                                                         */
+/*    Simple interface to access SFNT name tables (which are used          */
+/*    to hold font names, copyright info, notices, etc.) (specification).  */
+/*                                                                         */
+/*    This is _not_ used to retrieve glyph names!                          */
+/*                                                                         */
+/*  Copyright 1996-2001, 2002, 2003, 2006 by                               */
+/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */
+/*                                                                         */
+/*  This file is part of the FreeType project, and may only be used,       */
+/*  modified, and distributed under the terms of the FreeType project      */
+/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */
+/*  this file you indicate that you have read the license and              */
+/*  understand and accept it fully.                                        */
+/*                                                                         */
+/***************************************************************************/
+
+
+#ifndef __FT_SFNT_NAMES_H__
+#define __FT_SFNT_NAMES_H__
+
+
+#include <ft2build.h>
+#include FT_FREETYPE_H
+
+#ifdef FREETYPE_H
+#error "freetype.h of FreeType 1 has been loaded!"
+#error "Please fix the directory search order for header files"
+#error "so that freetype.h of FreeType 2 is found first."
+#endif
+
+
+FT_BEGIN_HEADER
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Section>                                                             */
+  /*    sfnt_names                                                         */
+  /*                                                                       */
+  /* <Title>                                                               */
+  /*    SFNT Names                                                         */
+  /*                                                                       */
+  /* <Abstract>                                                            */
+  /*    Access the names embedded in TrueType and OpenType files.          */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    The TrueType and OpenType specification allow the inclusion of     */
+  /*    a special `names table' in font files.  This table contains        */
+  /*    textual (and internationalized) information regarding the font,    */
+  /*    like family name, copyright, version, etc.                         */
+  /*                                                                       */
+  /*    The definitions below are used to access them if available.        */
+  /*                                                                       */
+  /*    Note that this has nothing to do with glyph names!                 */
+  /*                                                                       */
+  /*************************************************************************/
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Struct>                                                              */
+  /*    FT_SfntName                                                        */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    A structure used to model an SFNT `name' table entry.              */
+  /*                                                                       */
+  /* <Fields>                                                              */
+  /*    platform_id :: The platform ID for `string'.                       */
+  /*                                                                       */
+  /*    encoding_id :: The encoding ID for `string'.                       */
+  /*                                                                       */
+  /*    language_id :: The language ID for `string'.                       */
+  /*                                                                       */
+  /*    name_id     :: An identifier for `string'.                         */
+  /*                                                                       */
+  /*    string      :: The `name' string.  Note that its format differs    */
+  /*                   depending on the (platform,encoding) pair.  It can  */
+  /*                   be a Pascal String, a UTF-16 one, etc.              */
+  /*                                                                       */
+  /*                   Generally speaking, the string is not               */
+  /*                   zero-terminated.  Please refer to the TrueType      */
+  /*                   specification for details.                          */
+  /*                                                                       */
+  /*    string_len  :: The length of `string' in bytes.                    */
+  /*                                                                       */
+  /* <Note>                                                                */
+  /*    Possible values for `platform_id', `encoding_id', `language_id',   */
+  /*    and `name_id' are given in the file `ttnameid.h'.  For details     */
+  /*    please refer to the TrueType or OpenType specification.            */
+  /*                                                                       */
+  /*    See also @TT_PLATFORM_XXX, @TT_APPLE_ID_XXX, @TT_MAC_ID_XXX,       */
+  /*    @TT_ISO_ID_XXX, and @TT_MS_ID_XXX.                                 */
+  /*                                                                       */
+  typedef struct  FT_SfntName_
+  {
+    FT_UShort  platform_id;
+    FT_UShort  encoding_id;
+    FT_UShort  language_id;
+    FT_UShort  name_id;
+
+    FT_Byte*   string;      /* this string is *not* null-terminated! */
+    FT_UInt    string_len;  /* in bytes */
+
+  } FT_SfntName;
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FT_Get_Sfnt_Name_Count                                             */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    Retrieves the number of name strings in the SFNT `name' table.     */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    face :: A handle to the source face.                               */
+  /*                                                                       */
+  /* <Return>                                                              */
+  /*    The number of strings in the `name' table.                         */
+  /*                                                                       */
+  FT_EXPORT( FT_UInt )
+  FT_Get_Sfnt_Name_Count( FT_Face  face );
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FT_Get_Sfnt_Name                                                   */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    Retrieves a string of the SFNT `name' table for a given index.     */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    face  :: A handle to the source face.                              */
+  /*                                                                       */
+  /*    idx   :: The index of the `name' string.                           */
+  /*                                                                       */
+  /* <Output>                                                              */
+  /*    aname :: The indexed @FT_SfntName structure.                       */
+  /*                                                                       */
+  /* <Return>                                                              */
+  /*    FreeType error code.  0 means success.                             */
+  /*                                                                       */
+  /* <Note>                                                                */
+  /*    The `string' array returned in the `aname' structure is not        */
+  /*    null-terminated.                                                   */
+  /*                                                                       */
+  /*    Use @FT_Get_Sfnt_Name_Count to get the total number of available   */
+  /*    `name' table entries, then do a loop until you get the right       */
+  /*    platform, encoding, and name ID.                                   */
+  /*                                                                       */
+  FT_EXPORT( FT_Error )
+  FT_Get_Sfnt_Name( FT_Face       face,
+                    FT_UInt       idx,
+                    FT_SfntName  *aname );
+
+
+  /* */
+
+
+FT_END_HEADER
+
+#endif /* __FT_SFNT_NAMES_H__ */
+
+
+/* END */

+ 716 - 0
include/freetype/ftstroke.h

@@ -0,0 +1,716 @@
+/***************************************************************************/
+/*                                                                         */
+/*  ftstroke.h                                                             */
+/*                                                                         */
+/*    FreeType path stroker (specification).                               */
+/*                                                                         */
+/*  Copyright 2002, 2003, 2004, 2005, 2006 by                              */
+/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */
+/*                                                                         */
+/*  This file is part of the FreeType project, and may only be used,       */
+/*  modified, and distributed under the terms of the FreeType project      */
+/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */
+/*  this file you indicate that you have read the license and              */
+/*  understand and accept it fully.                                        */
+/*                                                                         */
+/***************************************************************************/
+
+
+#ifndef __FT_STROKE_H__
+#define __FT_STROKE_H__
+
+#include <ft2build.h>
+#include FT_OUTLINE_H
+#include FT_GLYPH_H
+
+
+FT_BEGIN_HEADER
+
+
+ /************************************************************************
+  *
+  * @section:
+  *    glyph_stroker
+  *
+  * @title:
+  *    Glyph Stroker
+  *
+  * @abstract:
+  *    Generating bordered and stroked glyphs.
+  *
+  * @description:
+  *    This component generates stroked outlines of a given vectorial
+  *    glyph.  It also allows you to retrieve the `outside' and/or the
+  *    `inside' borders of the stroke.
+  *
+  *    This can be useful to generate `bordered' glyph, i.e., glyphs
+  *    displayed with a coloured (and anti-aliased) border around their
+  *    shape.
+  */
+
+
+ /**************************************************************
+  *
+  * @type:
+  *   FT_Stroker
+  *
+  * @description:
+  *   Opaque handler to a path stroker object.
+  */
+  typedef struct FT_StrokerRec_*  FT_Stroker;
+
+
+  /**************************************************************
+   *
+   * @enum:
+   *   FT_Stroker_LineJoin
+   *
+   * @description:
+   *   These values determine how two joining lines are rendered
+   *   in a stroker.
+   *
+   * @values:
+   *   FT_STROKER_LINEJOIN_ROUND ::
+   *     Used to render rounded line joins.  Circular arcs are used
+   *     to join two lines smoothly.
+   *
+   *   FT_STROKER_LINEJOIN_BEVEL ::
+   *     Used to render beveled line joins; i.e., the two joining lines
+   *     are extended until they intersect.
+   *
+   *   FT_STROKER_LINEJOIN_MITER ::
+   *     Same as beveled rendering, except that an additional line
+   *     break is added if the angle between the two joining lines
+   *     is too closed (this is useful to avoid unpleasant spikes
+   *     in beveled rendering).
+   */
+  typedef enum
+  {
+    FT_STROKER_LINEJOIN_ROUND = 0,
+    FT_STROKER_LINEJOIN_BEVEL,
+    FT_STROKER_LINEJOIN_MITER
+
+  } FT_Stroker_LineJoin;
+
+
+  /**************************************************************
+   *
+   * @enum:
+   *   FT_Stroker_LineCap
+   *
+   * @description:
+   *   These values determine how the end of opened sub-paths are
+   *   rendered in a stroke.
+   *
+   * @values:
+   *   FT_STROKER_LINECAP_BUTT ::
+   *     The end of lines is rendered as a full stop on the last
+   *     point itself.
+   *
+   *   FT_STROKER_LINECAP_ROUND ::
+   *     The end of lines is rendered as a half-circle around the
+   *     last point.
+   *
+   *   FT_STROKER_LINECAP_SQUARE ::
+   *     The end of lines is rendered as a square around the
+   *     last point.
+   */
+  typedef enum
+  {
+    FT_STROKER_LINECAP_BUTT = 0,
+    FT_STROKER_LINECAP_ROUND,
+    FT_STROKER_LINECAP_SQUARE
+
+  } FT_Stroker_LineCap;
+
+
+  /**************************************************************
+   *
+   * @enum:
+   *   FT_StrokerBorder
+   *
+   * @description:
+   *   These values are used to select a given stroke border
+   *   in @FT_Stroker_GetBorderCounts and @FT_Stroker_ExportBorder.
+   *
+   * @values:
+   *   FT_STROKER_BORDER_LEFT ::
+   *     Select the left border, relative to the drawing direction.
+   *
+   *   FT_STROKER_BORDER_RIGHT ::
+   *     Select the right border, relative to the drawing direction.
+   *
+   * @note:
+   *   Applications are generally interested in the `inside' and `outside'
+   *   borders.  However, there is no direct mapping between these and the
+   *   `left' and `right' ones, since this really depends on the glyph's
+   *   drawing orientation, which varies between font formats.
+   *
+   *   You can however use @FT_Outline_GetInsideBorder and
+   *   @FT_Outline_GetOutsideBorder to get these.
+   */
+  typedef enum
+  {
+    FT_STROKER_BORDER_LEFT = 0,
+    FT_STROKER_BORDER_RIGHT
+
+  } FT_StrokerBorder;
+
+
+  /**************************************************************
+   *
+   * @function:
+   *   FT_Outline_GetInsideBorder
+   *
+   * @description:
+   *   Retrieve the @FT_StrokerBorder value corresponding to the
+   *   `inside' borders of a given outline.
+   *
+   * @input:
+   *   outline ::
+   *     The source outline handle.
+   *
+   * @return:
+   *   The border index.  @FT_STROKER_BORDER_LEFT for empty or invalid
+   *   outlines.
+   */
+  FT_EXPORT( FT_StrokerBorder )
+  FT_Outline_GetInsideBorder( FT_Outline*  outline );
+
+
+  /**************************************************************
+   *
+   * @function:
+   *   FT_Outline_GetOutsideBorder
+   *
+   * @description:
+   *   Retrieve the @FT_StrokerBorder value corresponding to the
+   *   `outside' borders of a given outline.
+   *
+   * @input:
+   *   outline ::
+   *     The source outline handle.
+   *
+   * @return:
+   *   The border index.  @FT_STROKER_BORDER_LEFT for empty or invalid
+   *   outlines.
+   */
+  FT_EXPORT( FT_StrokerBorder )
+  FT_Outline_GetOutsideBorder( FT_Outline*  outline );
+
+
+  /**************************************************************
+   *
+   * @function:
+   *   FT_Stroker_New
+   *
+   * @description:
+   *   Create a new stroker object.
+   *
+   * @input:
+   *   library ::
+   *     FreeType library handle.
+   *
+   * @output:
+   *   astroker ::
+   *     A new stroker object handle.  NULL in case of error.
+   *
+   * @return:
+   *    FreeType error code.  0 means success.
+   */
+  FT_EXPORT( FT_Error )
+  FT_Stroker_New( FT_Library   library,
+                  FT_Stroker  *astroker );
+
+
+  /**************************************************************
+   *
+   * @function:
+   *   FT_Stroker_Set
+   *
+   * @description:
+   *   Reset a stroker object's attributes.
+   *
+   * @input:
+   *   stroker ::
+   *     The target stroker handle.
+   *
+   *   radius ::
+   *     The border radius.
+   *
+   *   line_cap ::
+   *     The line cap style.
+   *
+   *   line_join ::
+   *     The line join style.
+   *
+   *   miter_limit ::
+   *     The miter limit for the FT_STROKER_LINEJOIN_MITER style,
+   *     expressed as 16.16 fixed point value.
+   *
+   * @note:
+   *   The radius is expressed in the same units that the outline
+   *   coordinates.
+   */
+  FT_EXPORT( void )
+  FT_Stroker_Set( FT_Stroker           stroker,
+                  FT_Fixed             radius,
+                  FT_Stroker_LineCap   line_cap,
+                  FT_Stroker_LineJoin  line_join,
+                  FT_Fixed             miter_limit );
+
+
+  /**************************************************************
+   *
+   * @function:
+   *   FT_Stroker_Rewind
+   *
+   * @description:
+   *   Reset a stroker object without changing its attributes.
+   *   You should call this function before beginning a new
+   *   series of calls to @FT_Stroker_BeginSubPath or
+   *   @FT_Stroker_EndSubPath.
+   *
+   * @input:
+   *   stroker ::
+   *     The target stroker handle.
+   */
+  FT_EXPORT( void )
+  FT_Stroker_Rewind( FT_Stroker  stroker );
+
+
+  /**************************************************************
+   *
+   * @function:
+   *   FT_Stroker_ParseOutline
+   *
+   * @description:
+   *   A convenience function used to parse a whole outline with
+   *   the stroker.  The resulting outline(s) can be retrieved
+   *   later by functions like @FT_Stroker_GetCounts and @FT_Stroker_Export.
+   *
+   * @input:
+   *   stroker ::
+   *     The target stroker handle.
+   *
+   *   outline ::
+   *     The source outline.
+   *
+   *   opened ::
+   *     A boolean.  If 1, the outline is treated as an open path instead
+   *     of a closed one.
+   *
+   * @return:
+   *   FreeType error code.  0 means success.
+   *
+   * @note:
+   *   If `opened' is 0 (the default), the outline is treated as a closed
+   *   path, and the stroker will generate two distinct `border' outlines.
+   *
+   *   If `opened' is 1, the outline is processed as an open path, and the
+   *   stroker will generate a single `stroke' outline.
+   *
+   *   This function calls @FT_Stroker_Rewind automatically.
+   */
+  FT_EXPORT( FT_Error )
+  FT_Stroker_ParseOutline( FT_Stroker   stroker,
+                           FT_Outline*  outline,
+                           FT_Bool      opened );
+
+
+  /**************************************************************
+   *
+   * @function:
+   *   FT_Stroker_BeginSubPath
+   *
+   * @description:
+   *   Start a new sub-path in the stroker.
+   *
+   * @input:
+   *   stroker ::
+   *     The target stroker handle.
+   *
+   *   to ::
+   *     A pointer to the start vector.
+   *
+   *   open ::
+   *     A boolean.  If 1, the sub-path is treated as an open one.
+   *
+   * @return:
+   *   FreeType error code.  0 means success.
+   *
+   * @note:
+   *   This function is useful when you need to stroke a path that is
+   *   not stored as an @FT_Outline object.
+   */
+  FT_EXPORT( FT_Error )
+  FT_Stroker_BeginSubPath( FT_Stroker  stroker,
+                           FT_Vector*  to,
+                           FT_Bool     open );
+
+
+  /**************************************************************
+   *
+   * @function:
+   *   FT_Stroker_EndSubPath
+   *
+   * @description:
+   *   Close the current sub-path in the stroker.
+   *
+   * @input:
+   *   stroker ::
+   *     The target stroker handle.
+   *
+   * @return:
+   *   FreeType error code.  0 means success.
+   *
+   * @note:
+   *   You should call this function after @FT_Stroker_BeginSubPath.
+   *   If the subpath was not `opened', this function will `draw' a
+   *   single line segment to the start position when needed.
+   */
+  FT_EXPORT( FT_Error )
+  FT_Stroker_EndSubPath( FT_Stroker  stroker );
+
+
+  /**************************************************************
+   *
+   * @function:
+   *   FT_Stroker_LineTo
+   *
+   * @description:
+   *   `Draw' a single line segment in the stroker's current sub-path,
+   *   from the last position.
+   *
+   * @input:
+   *   stroker ::
+   *     The target stroker handle.
+   *
+   *   to ::
+   *     A pointer to the destination point.
+   *
+   * @return:
+   *   FreeType error code.  0 means success.
+   *
+   * @note:
+   *   You should call this function between @FT_Stroker_BeginSubPath and
+   *   @FT_Stroker_EndSubPath.
+   */
+  FT_EXPORT( FT_Error )
+  FT_Stroker_LineTo( FT_Stroker  stroker,
+                     FT_Vector*  to );
+
+
+  /**************************************************************
+   *
+   * @function:
+   *   FT_Stroker_ConicTo
+   *
+   * @description:
+   *   `Draw' a single quadratic Bézier in the stroker's current sub-path,
+   *   from the last position.
+   *
+   * @input:
+   *   stroker ::
+   *     The target stroker handle.
+   *
+   *   control ::
+   *     A pointer to a Bézier control point.
+   *
+   *   to ::
+   *     A pointer to the destination point.
+   *
+   * @return:
+   *   FreeType error code.  0 means success.
+   *
+   * @note:
+   *   You should call this function between @FT_Stroker_BeginSubPath and
+   *   @FT_Stroker_EndSubPath.
+   */
+  FT_EXPORT( FT_Error )
+  FT_Stroker_ConicTo( FT_Stroker  stroker,
+                      FT_Vector*  control,
+                      FT_Vector*  to );
+
+
+  /**************************************************************
+   *
+   * @function:
+   *   FT_Stroker_CubicTo
+   *
+   * @description:
+   *   `Draw' a single cubic Bézier in the stroker's current sub-path,
+   *   from the last position.
+   *
+   * @input:
+   *   stroker ::
+   *     The target stroker handle.
+   *
+   *   control1 ::
+   *     A pointer to the first Bézier control point.
+   *
+   *   control2 ::
+   *     A pointer to second Bézier control point.
+   *
+   *   to ::
+   *     A pointer to the destination point.
+   *
+   * @return:
+   *   FreeType error code.  0 means success.
+   *
+   * @note:
+   *   You should call this function between @FT_Stroker_BeginSubPath and
+   *   @FT_Stroker_EndSubPath.
+   */
+  FT_EXPORT( FT_Error )
+  FT_Stroker_CubicTo( FT_Stroker  stroker,
+                      FT_Vector*  control1,
+                      FT_Vector*  control2,
+                      FT_Vector*  to );
+
+
+  /**************************************************************
+   *
+   * @function:
+   *   FT_Stroker_GetBorderCounts
+   *
+   * @description:
+   *   Call this function once you have finished parsing your paths
+   *   with the stroker.  It will return the number of points and
+   *   contours necessary to export one of the `border' or `stroke'
+   *   outlines generated by the stroker.
+   *
+   * @input:
+   *   stroker ::
+   *     The target stroker handle.
+   *
+   *   border ::
+   *     The border index.
+   *
+   * @output:
+   *   anum_points ::
+   *     The number of points.
+   *
+   *   anum_contours ::
+   *     The number of contours.
+   *
+   * @return:
+   *   FreeType error code.  0 means success.
+   *
+   * @note:
+   *   When an outline, or a sub-path, is `closed', the stroker generates
+   *   two independent `border' outlines, named `left' and `right'.
+   *
+   *   When the outline, or a sub-path, is `opened', the stroker merges
+   *   the `border' outlines with caps.  The `left' border receives all
+   *   points, while the `right' border becomes empty.
+   *
+   *   Use the function @FT_Stroker_GetCounts instead if you want to
+   *   retrieve the counts associated to both borders.
+   */
+  FT_EXPORT( FT_Error )
+  FT_Stroker_GetBorderCounts( FT_Stroker        stroker,
+                              FT_StrokerBorder  border,
+                              FT_UInt          *anum_points,
+                              FT_UInt          *anum_contours );
+
+
+  /**************************************************************
+   *
+   * @function:
+   *   FT_Stroker_ExportBorder
+   *
+   * @description:
+   *   Call this function after @FT_Stroker_GetBorderCounts to
+   *   export the corresponding border to your own @FT_Outline
+   *   structure.
+   *
+   *   Note that this function will append the border points and
+   *   contours to your outline, but will not try to resize its
+   *   arrays.
+   *
+   * @input:
+   *   stroker ::
+   *     The target stroker handle.
+   *
+   *   border ::
+   *     The border index.
+   *
+   *   outline ::
+   *     The target outline handle.
+   *
+   * @note:
+   *   Always call this function after @FT_Stroker_GetBorderCounts to
+   *   get sure that there is enough room in your @FT_Outline object to
+   *   receive all new data.
+   *
+   *   When an outline, or a sub-path, is `closed', the stroker generates
+   *   two independent `border' outlines, named `left' and `right'
+   *
+   *   When the outline, or a sub-path, is `opened', the stroker merges
+   *   the `border' outlines with caps. The `left' border receives all
+   *   points, while the `right' border becomes empty.
+   *
+   *   Use the function @FT_Stroker_Export instead if you want to
+   *   retrieve all borders at once.
+   */
+  FT_EXPORT( void )
+  FT_Stroker_ExportBorder( FT_Stroker        stroker,
+                           FT_StrokerBorder  border,
+                           FT_Outline*       outline );
+
+
+  /**************************************************************
+   *
+   * @function:
+   *   FT_Stroker_GetCounts
+   *
+   * @description:
+   *   Call this function once you have finished parsing your paths
+   *   with the stroker.  It returns the number of points and
+   *   contours necessary to export all points/borders from the stroked
+   *   outline/path.
+   *
+   * @input:
+   *   stroker ::
+   *     The target stroker handle.
+   *
+   * @output:
+   *   anum_points ::
+   *     The number of points.
+   *
+   *   anum_contours ::
+   *     The number of contours.
+   *
+   * @return:
+   *   FreeType error code.  0 means success.
+   */
+  FT_EXPORT( FT_Error )
+  FT_Stroker_GetCounts( FT_Stroker  stroker,
+                        FT_UInt    *anum_points,
+                        FT_UInt    *anum_contours );
+
+
+  /**************************************************************
+   *
+   * @function:
+   *   FT_Stroker_Export
+   *
+   * @description:
+   *   Call this function after @FT_Stroker_GetBorderCounts to
+   *   export the all borders to your own @FT_Outline structure.
+   *
+   *   Note that this function will append the border points and
+   *   contours to your outline, but will not try to resize its
+   *   arrays.
+   *
+   * @input:
+   *   stroker ::
+   *     The target stroker handle.
+   *
+   *   outline ::
+   *     The target outline handle.
+   */
+  FT_EXPORT( void )
+  FT_Stroker_Export( FT_Stroker   stroker,
+                     FT_Outline*  outline );
+
+
+  /**************************************************************
+   *
+   * @function:
+   *   FT_Stroker_Done
+   *
+   * @description:
+   *   Destroy a stroker object.
+   *
+   * @input:
+   *   stroker ::
+   *     A stroker handle.  Can be NULL.
+   */
+  FT_EXPORT( void )
+  FT_Stroker_Done( FT_Stroker  stroker );
+
+
+  /**************************************************************
+   *
+   * @function:
+   *   FT_Glyph_Stroke
+   *
+   * @description:
+   *   Stroke a given outline glyph object with a given stroker.
+   *
+   * @inout:
+   *   pglyph ::
+   *     Source glyph handle on input, new glyph handle on output.
+   *
+   * @input:
+   *   stroker ::
+   *     A stroker handle.
+   *
+   *   destroy ::
+   *     A Boolean.  If 1, the source glyph object is destroyed
+   *     on success.
+   *
+   * @return:
+   *    FreeType error code.  0 means success.
+   *
+   * @note:
+   *   The source glyph is untouched in case of error.
+   */
+  FT_EXPORT( FT_Error )
+  FT_Glyph_Stroke( FT_Glyph    *pglyph,
+                   FT_Stroker   stroker,
+                   FT_Bool      destroy );
+
+
+  /**************************************************************
+   *
+   * @function:
+   *   FT_Glyph_StrokeBorder
+   *
+   * @description:
+   *   Stroke a given outline glyph object with a given stroker, but
+   *   only return either its inside or outside border.
+   *
+   * @inout:
+   *   pglyph ::
+   *     Source glyph handle on input, new glyph handle on output.
+   *
+   * @input:
+   *   stroker ::
+   *     A stroker handle.
+   *
+   *   inside ::
+   *     A Boolean.  If 1, return the inside border, otherwise
+   *     the outside border.
+   *
+   *   destroy ::
+   *     A Boolean.  If 1, the source glyph object is destroyed
+   *     on success.
+   *
+   * @return:
+   *    FreeType error code.  0 means success.
+   *
+   * @note:
+   *   The source glyph is untouched in case of error.
+   */
+  FT_EXPORT( FT_Error )
+  FT_Glyph_StrokeBorder( FT_Glyph    *pglyph,
+                         FT_Stroker   stroker,
+                         FT_Bool      inside,
+                         FT_Bool      destroy );
+
+ /* */
+
+FT_END_HEADER
+
+#endif /* __FT_STROKE_H__ */
+
+
+/* END */
+
+
+/* Local Variables: */
+/* coding: utf-8    */
+/* End:             */

+ 73 - 0
include/freetype/ftsynth.h

@@ -0,0 +1,73 @@
+/***************************************************************************/
+/*                                                                         */
+/*  ftsynth.h                                                              */
+/*                                                                         */
+/*    FreeType synthesizing code for emboldening and slanting              */
+/*    (specification).                                                     */
+/*                                                                         */
+/*  Copyright 2000-2001, 2003, 2006 by                                     */
+/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */
+/*                                                                         */
+/*  This file is part of the FreeType project, and may only be used,       */
+/*  modified, and distributed under the terms of the FreeType project      */
+/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */
+/*  this file you indicate that you have read the license and              */
+/*  understand and accept it fully.                                        */
+/*                                                                         */
+/***************************************************************************/
+
+
+  /*************************************************************************/
+  /*************************************************************************/
+  /*************************************************************************/
+  /*************************************************************************/
+  /*************************************************************************/
+  /*********                                                       *********/
+  /*********        WARNING, THIS IS ALPHA CODE, THIS API          *********/
+  /*********    IS DUE TO CHANGE UNTIL STRICTLY NOTIFIED BY THE    *********/
+  /*********            FREETYPE DEVELOPMENT TEAM                  *********/
+  /*********                                                       *********/
+  /*************************************************************************/
+  /*************************************************************************/
+  /*************************************************************************/
+  /*************************************************************************/
+  /*************************************************************************/
+
+
+#ifndef __FTSYNTH_H__
+#define __FTSYNTH_H__
+
+
+#include <ft2build.h>
+#include FT_FREETYPE_H
+
+#ifdef FREETYPE_H
+#error "freetype.h of FreeType 1 has been loaded!"
+#error "Please fix the directory search order for header files"
+#error "so that freetype.h of FreeType 2 is found first."
+#endif
+
+
+FT_BEGIN_HEADER
+
+  /* Make sure slot owns slot->bitmap. */
+  FT_EXPORT( FT_Error )
+  FT_GlyphSlot_Own_Bitmap( FT_GlyphSlot  slot );
+
+  /* Do not use this function directly!  Copy the code to */
+  /* your application and modify it to suit your need.    */
+  FT_EXPORT( void )
+  FT_GlyphSlot_Embolden( FT_GlyphSlot  slot );
+
+
+  FT_EXPORT( void )
+  FT_GlyphSlot_Oblique( FT_GlyphSlot  slot );
+
+ /* */
+
+FT_END_HEADER
+
+#endif /* __FTSYNTH_H__ */
+
+
+/* END */

+ 346 - 0
include/freetype/ftsystem.h

@@ -0,0 +1,346 @@
+/***************************************************************************/
+/*                                                                         */
+/*  ftsystem.h                                                             */
+/*                                                                         */
+/*    FreeType low-level system interface definition (specification).      */
+/*                                                                         */
+/*  Copyright 1996-2001, 2002, 2005 by                                     */
+/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */
+/*                                                                         */
+/*  This file is part of the FreeType project, and may only be used,       */
+/*  modified, and distributed under the terms of the FreeType project      */
+/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */
+/*  this file you indicate that you have read the license and              */
+/*  understand and accept it fully.                                        */
+/*                                                                         */
+/***************************************************************************/
+
+
+#ifndef __FTSYSTEM_H__
+#define __FTSYSTEM_H__
+
+
+#include <ft2build.h>
+
+
+FT_BEGIN_HEADER
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Section>                                                             */
+  /*   system_interface                                                    */
+  /*                                                                       */
+  /* <Title>                                                               */
+  /*   System Interface                                                    */
+  /*                                                                       */
+  /* <Abstract>                                                            */
+  /*   How FreeType manages memory and i/o.                                */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*   This section contains various definitions related to memory         */
+  /*   management and i/o access.  You need to understand this             */
+  /*   information if you want to use a custom memory manager or you own   */
+  /*   i/o streams.                                                        */
+  /*                                                                       */
+  /*************************************************************************/
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /*                  M E M O R Y   M A N A G E M E N T                    */
+  /*                                                                       */
+  /*************************************************************************/
+
+
+  /*************************************************************************
+   *
+   * @type:
+   *   FT_Memory
+   *
+   * @description:
+   *   A handle to a given memory manager object, defined with an
+   *   @FT_MemoryRec structure.
+   *
+   */
+  typedef struct FT_MemoryRec_*  FT_Memory;
+
+
+  /*************************************************************************
+   *
+   * @functype:
+   *   FT_Alloc_Func
+   *
+   * @description:
+   *   A function used to allocate `size' bytes from `memory'.
+   *
+   * @input:
+   *   memory ::
+   *     A handle to the source memory manager.
+   *
+   *   size ::
+   *     The size in bytes to allocate.
+   *
+   * @return:
+   *   Address of new memory block.  0 in case of failure.
+   *
+   */
+  typedef void*
+  (*FT_Alloc_Func)( FT_Memory  memory,
+                    long       size );
+
+
+  /*************************************************************************
+   *
+   * @functype:
+   *   FT_Free_Func
+   *
+   * @description:
+   *   A function used to release a given block of memory.
+   *
+   * @input:
+   *   memory ::
+   *     A handle to the source memory manager.
+   *
+   *   block ::
+   *     The address of the target memory block.
+   *
+   */
+  typedef void
+  (*FT_Free_Func)( FT_Memory  memory,
+                   void*      block );
+
+
+  /*************************************************************************
+   *
+   * @functype:
+   *   FT_Realloc_Func
+   *
+   * @description:
+   *   A function used to re-allocate a given block of memory.
+   *
+   * @input:
+   *   memory ::
+   *     A handle to the source memory manager.
+   *
+   *   cur_size ::
+   *     The block's current size in bytes.
+   *
+   *   new_size ::
+   *     The block's requested new size.
+   *
+   *   block ::
+   *     The block's current address.
+   *
+   * @return:
+   *   New block address.  0 in case of memory shortage.
+   *
+   * @note:
+   *   In case of error, the old block must still be available.
+   *
+   */
+  typedef void*
+  (*FT_Realloc_Func)( FT_Memory  memory,
+                      long       cur_size,
+                      long       new_size,
+                      void*      block );
+
+
+  /*************************************************************************
+   *
+   * @struct:
+   *   FT_MemoryRec
+   *
+   * @description:
+   *   A structure used to describe a given memory manager to FreeType 2.
+   *
+   * @fields:
+   *   user ::
+   *     A generic typeless pointer for user data.
+   *
+   *   alloc ::
+   *     A pointer type to an allocation function.
+   *
+   *   free ::
+   *     A pointer type to an memory freeing function.
+   *
+   *   realloc ::
+   *     A pointer type to a reallocation function.
+   *
+   */
+  struct  FT_MemoryRec_
+  {
+    void*            user;
+    FT_Alloc_Func    alloc;
+    FT_Free_Func     free;
+    FT_Realloc_Func  realloc;
+  };
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /*                       I / O   M A N A G E M E N T                     */
+  /*                                                                       */
+  /*************************************************************************/
+
+
+  /*************************************************************************
+   *
+   * @type:
+   *   FT_Stream
+   *
+   * @description:
+   *   A handle to an input stream.
+   *
+   */
+  typedef struct FT_StreamRec_*  FT_Stream;
+
+
+  /*************************************************************************
+   *
+   * @struct:
+   *   FT_StreamDesc
+   *
+   * @description:
+   *   A union type used to store either a long or a pointer.  This is used
+   *   to store a file descriptor or a `FILE*' in an input stream.
+   *
+   */
+  typedef union  FT_StreamDesc_
+  {
+    long   value;
+    void*  pointer;
+
+  } FT_StreamDesc;
+
+
+  /*************************************************************************
+   *
+   * @functype:
+   *   FT_Stream_IoFunc
+   *
+   * @description:
+   *   A function used to seek and read data from a given input stream.
+   *
+   * @input:
+   *   stream ::
+   *     A handle to the source stream.
+   *
+   *   offset ::
+   *     The offset of read in stream (always from start).
+   *
+   *   buffer ::
+   *     The address of the read buffer.
+   *
+   *   count ::
+   *     The number of bytes to read from the stream.
+   *
+   * @return:
+   *   The number of bytes effectively read by the stream.
+   *
+   * @note:
+   *   This function might be called to perform a seek or skip operation
+   *   with a `count' of 0.
+   *
+   */
+  typedef unsigned long
+  (*FT_Stream_IoFunc)( FT_Stream       stream,
+                       unsigned long   offset,
+                       unsigned char*  buffer,
+                       unsigned long   count );
+
+
+  /*************************************************************************
+   *
+   * @functype:
+   *   FT_Stream_CloseFunc
+   *
+   * @description:
+   *   A function used to close a given input stream.
+   *
+   * @input:
+   *  stream ::
+   *     A handle to the target stream.
+   *
+   */
+  typedef void
+  (*FT_Stream_CloseFunc)( FT_Stream  stream );
+
+
+  /*************************************************************************
+   *
+   * @struct:
+   *   FT_StreamRec
+   *
+   * @description:
+   *   A structure used to describe an input stream.
+   *
+   * @input:
+   *   base ::
+   *     For memory-based streams, this is the address of the first stream
+   *     byte in memory.  This field should always be set to NULL for
+   *     disk-based streams.
+   *
+   *   size ::
+   *     The stream size in bytes.
+   *
+   *   pos ::
+   *     The current position within the stream.
+   *
+   *   descriptor ::
+   *     This field is a union that can hold an integer or a pointer.  It is
+   *     used by stream implementations to store file descriptors or `FILE*'
+   *     pointers.
+   *
+   *   pathname ::
+   *     This field is completely ignored by FreeType.  However, it is often
+   *     useful during debugging to use it to store the stream's filename
+   *     (where available).
+   *
+   *   read ::
+   *     The stream's input function.
+   *
+   *   close ::
+   *     The stream;s close function.
+   *
+   *   memory ::
+   *     The memory manager to use to preload frames.  This is set
+   *     internally by FreeType and shouldn't be touched by stream
+   *     implementations.
+   *
+   *   cursor ::
+   *     This field is set and used internally by FreeType when parsing
+   *     frames.
+   *
+   *   limit ::
+   *     This field is set and used internally by FreeType when parsing
+   *     frames.
+   *
+   */
+  typedef struct  FT_StreamRec_
+  {
+    unsigned char*       base;
+    unsigned long        size;
+    unsigned long        pos;
+
+    FT_StreamDesc        descriptor;
+    FT_StreamDesc        pathname;
+    FT_Stream_IoFunc     read;
+    FT_Stream_CloseFunc  close;
+
+    FT_Memory            memory;
+    unsigned char*       cursor;
+    unsigned char*       limit;
+
+  } FT_StreamRec;
+
+
+  /* */
+
+
+FT_END_HEADER
+
+#endif /* __FTSYSTEM_H__ */
+
+
+/* END */

+ 350 - 0
include/freetype/fttrigon.h

@@ -0,0 +1,350 @@
+/***************************************************************************/
+/*                                                                         */
+/*  fttrigon.h                                                             */
+/*                                                                         */
+/*    FreeType trigonometric functions (specification).                    */
+/*                                                                         */
+/*  Copyright 2001, 2003, 2005, 2007 by                                    */
+/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */
+/*                                                                         */
+/*  This file is part of the FreeType project, and may only be used,       */
+/*  modified, and distributed under the terms of the FreeType project      */
+/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */
+/*  this file you indicate that you have read the license and              */
+/*  understand and accept it fully.                                        */
+/*                                                                         */
+/***************************************************************************/
+
+
+#ifndef __FTTRIGON_H__
+#define __FTTRIGON_H__
+
+#include FT_FREETYPE_H
+
+#ifdef FREETYPE_H
+#error "freetype.h of FreeType 1 has been loaded!"
+#error "Please fix the directory search order for header files"
+#error "so that freetype.h of FreeType 2 is found first."
+#endif
+
+
+FT_BEGIN_HEADER
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Section>                                                             */
+  /*   computations                                                        */
+  /*                                                                       */
+  /*************************************************************************/
+
+
+  /*************************************************************************
+   *
+   * @type:
+   *   FT_Angle
+   *
+   * @description:
+   *   This type is used to model angle values in FreeType.  Note that the
+   *   angle is a 16.16 fixed float value expressed in degrees.
+   *
+   */
+  typedef FT_Fixed  FT_Angle;
+
+
+  /*************************************************************************
+   *
+   * @macro:
+   *   FT_ANGLE_PI
+   *
+   * @description:
+   *   The angle pi expressed in @FT_Angle units.
+   *
+   */
+#define FT_ANGLE_PI  ( 180L << 16 )
+
+
+  /*************************************************************************
+   *
+   * @macro:
+   *   FT_ANGLE_2PI
+   *
+   * @description:
+   *   The angle 2*pi expressed in @FT_Angle units.
+   *
+   */
+#define FT_ANGLE_2PI  ( FT_ANGLE_PI * 2 )
+
+
+  /*************************************************************************
+   *
+   * @macro:
+   *   FT_ANGLE_PI2
+   *
+   * @description:
+   *   The angle pi/2 expressed in @FT_Angle units.
+   *
+   */
+#define FT_ANGLE_PI2  ( FT_ANGLE_PI / 2 )
+
+
+  /*************************************************************************
+   *
+   * @macro:
+   *   FT_ANGLE_PI4
+   *
+   * @description:
+   *   The angle pi/4 expressed in @FT_Angle units.
+   *
+   */
+#define FT_ANGLE_PI4  ( FT_ANGLE_PI / 4 )
+
+
+  /*************************************************************************
+   *
+   * @function:
+   *   FT_Sin
+   *
+   * @description:
+   *   Return the sinus of a given angle in fixed point format.
+   *
+   * @input:
+   *   angle ::
+   *     The input angle.
+   *
+   * @return:
+   *   The sinus value.
+   *
+   * @note:
+   *   If you need both the sinus and cosinus for a given angle, use the
+   *   function @FT_Vector_Unit.
+   *
+   */
+  FT_EXPORT( FT_Fixed )
+  FT_Sin( FT_Angle  angle );
+
+
+  /*************************************************************************
+   *
+   * @function:
+   *   FT_Cos
+   *
+   * @description:
+   *   Return the cosinus of a given angle in fixed point format.
+   *
+   * @input:
+   *   angle ::
+   *     The input angle.
+   *
+   * @return:
+   *   The cosinus value.
+   *
+   * @note:
+   *   If you need both the sinus and cosinus for a given angle, use the
+   *   function @FT_Vector_Unit.
+   *
+   */
+  FT_EXPORT( FT_Fixed )
+  FT_Cos( FT_Angle  angle );
+
+
+  /*************************************************************************
+   *
+   * @function:
+   *   FT_Tan
+   *
+   * @description:
+   *   Return the tangent of a given angle in fixed point format.
+   *
+   * @input:
+   *   angle ::
+   *     The input angle.
+   *
+   * @return:
+   *   The tangent value.
+   *
+   */
+  FT_EXPORT( FT_Fixed )
+  FT_Tan( FT_Angle  angle );
+
+
+  /*************************************************************************
+   *
+   * @function:
+   *   FT_Atan2
+   *
+   * @description:
+   *   Return the arc-tangent corresponding to a given vector (x,y) in
+   *   the 2d plane.
+   *
+   * @input:
+   *   x ::
+   *     The horizontal vector coordinate.
+   *
+   *   y ::
+   *     The vertical vector coordinate.
+   *
+   * @return:
+   *   The arc-tangent value (i.e. angle).
+   *
+   */
+  FT_EXPORT( FT_Angle )
+  FT_Atan2( FT_Fixed  x,
+            FT_Fixed  y );
+
+
+  /*************************************************************************
+   *
+   * @function:
+   *   FT_Angle_Diff
+   *
+   * @description:
+   *   Return the difference between two angles.  The result is always
+   *   constrained to the ]-PI..PI] interval.
+   *
+   * @input:
+   *   angle1 ::
+   *     First angle.
+   *
+   *   angle2 ::
+   *     Second angle.
+   *
+   * @return:
+   *   Constrained value of `value2-value1'.
+   *
+   */
+  FT_EXPORT( FT_Angle )
+  FT_Angle_Diff( FT_Angle  angle1,
+                 FT_Angle  angle2 );
+
+
+  /*************************************************************************
+   *
+   * @function:
+   *   FT_Vector_Unit
+   *
+   * @description:
+   *   Return the unit vector corresponding to a given angle.  After the
+   *   call, the value of `vec.x' will be `sin(angle)', and the value of
+   *   `vec.y' will be `cos(angle)'.
+   *
+   *   This function is useful to retrieve both the sinus and cosinus of a
+   *   given angle quickly.
+   *
+   * @output:
+   *   vec ::
+   *     The address of target vector.
+   *
+   * @input:
+   *   angle ::
+   *     The address of angle.
+   *
+   */
+  FT_EXPORT( void )
+  FT_Vector_Unit( FT_Vector*  vec,
+                  FT_Angle    angle );
+
+
+  /*************************************************************************
+   *
+   * @function:
+   *   FT_Vector_Rotate
+   *
+   * @description:
+   *   Rotate a vector by a given angle.
+   *
+   * @inout:
+   *   vec ::
+   *     The address of target vector.
+   *
+   * @input:
+   *   angle ::
+   *     The address of angle.
+   *
+   */
+  FT_EXPORT( void )
+  FT_Vector_Rotate( FT_Vector*  vec,
+                    FT_Angle    angle );
+
+
+  /*************************************************************************
+   *
+   * @function:
+   *   FT_Vector_Length
+   *
+   * @description:
+   *   Return the length of a given vector.
+   *
+   * @input:
+   *   vec ::
+   *     The address of target vector.
+   *
+   * @return:
+   *   The vector length, expressed in the same units that the original
+   *   vector coordinates.
+   *
+   */
+  FT_EXPORT( FT_Fixed )
+  FT_Vector_Length( FT_Vector*  vec );
+
+
+  /*************************************************************************
+   *
+   * @function:
+   *   FT_Vector_Polarize
+   *
+   * @description:
+   *   Compute both the length and angle of a given vector.
+   *
+   * @input:
+   *   vec ::
+   *     The address of source vector.
+   *
+   * @output:
+   *   length ::
+   *     The vector length.
+   *
+   *   angle ::
+   *     The vector angle.
+   *
+   */
+  FT_EXPORT( void )
+  FT_Vector_Polarize( FT_Vector*  vec,
+                      FT_Fixed   *length,
+                      FT_Angle   *angle );
+
+
+  /*************************************************************************
+   *
+   * @function:
+   *   FT_Vector_From_Polar
+   *
+   * @description:
+   *   Compute vector coordinates from a length and angle.
+   *
+   * @output:
+   *   vec ::
+   *     The address of source vector.
+   *
+   * @input:
+   *   length ::
+   *     The vector length.
+   *
+   *   angle ::
+   *     The vector angle.
+   *
+   */
+  FT_EXPORT( void )
+  FT_Vector_From_Polar( FT_Vector*  vec,
+                        FT_Fixed    length,
+                        FT_Angle    angle );
+
+  /* */
+
+
+FT_END_HEADER
+
+#endif /* __FTTRIGON_H__ */
+
+
+/* END */

+ 583 - 0
include/freetype/fttypes.h

@@ -0,0 +1,583 @@
+/***************************************************************************/
+/*                                                                         */
+/*  fttypes.h                                                              */
+/*                                                                         */
+/*    FreeType simple types definitions (specification only).              */
+/*                                                                         */
+/*  Copyright 1996-2001, 2002, 2004, 2006, 2007 by                         */
+/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */
+/*                                                                         */
+/*  This file is part of the FreeType project, and may only be used,       */
+/*  modified, and distributed under the terms of the FreeType project      */
+/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */
+/*  this file you indicate that you have read the license and              */
+/*  understand and accept it fully.                                        */
+/*                                                                         */
+/***************************************************************************/
+
+
+#ifndef __FTTYPES_H__
+#define __FTTYPES_H__
+
+
+#include <ft2build.h>
+#include FT_CONFIG_CONFIG_H
+#include FT_SYSTEM_H
+#include FT_IMAGE_H
+
+#include <stddef.h>
+
+
+FT_BEGIN_HEADER
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Section>                                                             */
+  /*    basic_types                                                        */
+  /*                                                                       */
+  /* <Title>                                                               */
+  /*    Basic Data Types                                                   */
+  /*                                                                       */
+  /* <Abstract>                                                            */
+  /*    The basic data types defined by the library.                       */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    This section contains the basic data types defined by FreeType 2,  */
+  /*    ranging from simple scalar types to bitmap descriptors.  More      */
+  /*    font-specific structures are defined in a different section.       */
+  /*                                                                       */
+  /* <Order>                                                               */
+  /*    FT_Byte                                                            */
+  /*    FT_Bytes                                                           */
+  /*    FT_Char                                                            */
+  /*    FT_Int                                                             */
+  /*    FT_UInt                                                            */
+  /*    FT_Short                                                           */
+  /*    FT_UShort                                                          */
+  /*    FT_Long                                                            */
+  /*    FT_ULong                                                           */
+  /*    FT_Bool                                                            */
+  /*    FT_Offset                                                          */
+  /*    FT_PtrDist                                                         */
+  /*    FT_String                                                          */
+  /*    FT_Tag                                                             */
+  /*    FT_Error                                                           */
+  /*    FT_Fixed                                                           */
+  /*    FT_Pointer                                                         */
+  /*    FT_Pos                                                             */
+  /*    FT_Vector                                                          */
+  /*    FT_BBox                                                            */
+  /*    FT_Matrix                                                          */
+  /*    FT_FWord                                                           */
+  /*    FT_UFWord                                                          */
+  /*    FT_F2Dot14                                                         */
+  /*    FT_UnitVector                                                      */
+  /*    FT_F26Dot6                                                         */
+  /*                                                                       */
+  /*                                                                       */
+  /*    FT_Generic                                                         */
+  /*    FT_Generic_Finalizer                                               */
+  /*                                                                       */
+  /*    FT_Bitmap                                                          */
+  /*    FT_Pixel_Mode                                                      */
+  /*    FT_Palette_Mode                                                    */
+  /*    FT_Glyph_Format                                                    */
+  /*    FT_IMAGE_TAG                                                       */
+  /*                                                                       */
+  /*************************************************************************/
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Type>                                                                */
+  /*    FT_Bool                                                            */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    A typedef of unsigned char, used for simple booleans.  As usual,   */
+  /*    values 1 and 0 represent true and false, respectively.             */
+  /*                                                                       */
+  typedef unsigned char  FT_Bool;
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Type>                                                                */
+  /*    FT_FWord                                                           */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    A signed 16-bit integer used to store a distance in original font  */
+  /*    units.                                                             */
+  /*                                                                       */
+  typedef signed short  FT_FWord;   /* distance in FUnits */
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Type>                                                                */
+  /*    FT_UFWord                                                          */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    An unsigned 16-bit integer used to store a distance in original    */
+  /*    font units.                                                        */
+  /*                                                                       */
+  typedef unsigned short  FT_UFWord;  /* unsigned distance */
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Type>                                                                */
+  /*    FT_Char                                                            */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    A simple typedef for the _signed_ char type.                       */
+  /*                                                                       */
+  typedef signed char  FT_Char;
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Type>                                                                */
+  /*    FT_Byte                                                            */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    A simple typedef for the _unsigned_ char type.                     */
+  /*                                                                       */
+  typedef unsigned char  FT_Byte;
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Type>                                                                */
+  /*    FT_Bytes                                                           */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    A typedef for constant memory areas.                               */
+  /*                                                                       */
+  typedef const FT_Byte*  FT_Bytes;
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Type>                                                                */
+  /*    FT_Tag                                                             */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    A typedef for 32bit tags (as used in the SFNT format).             */
+  /*                                                                       */
+  typedef FT_UInt32  FT_Tag;
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Type>                                                                */
+  /*    FT_String                                                          */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    A simple typedef for the char type, usually used for strings.      */
+  /*                                                                       */
+  typedef char  FT_String;
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Type>                                                                */
+  /*    FT_Short                                                           */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    A typedef for signed short.                                        */
+  /*                                                                       */
+  typedef signed short  FT_Short;
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Type>                                                                */
+  /*    FT_UShort                                                          */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    A typedef for unsigned short.                                      */
+  /*                                                                       */
+  typedef unsigned short  FT_UShort;
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Type>                                                                */
+  /*    FT_Int                                                             */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    A typedef for the int type.                                        */
+  /*                                                                       */
+  typedef signed int  FT_Int;
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Type>                                                                */
+  /*    FT_UInt                                                            */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    A typedef for the unsigned int type.                               */
+  /*                                                                       */
+  typedef unsigned int  FT_UInt;
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Type>                                                                */
+  /*    FT_Long                                                            */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    A typedef for signed long.                                         */
+  /*                                                                       */
+  typedef signed long  FT_Long;
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Type>                                                                */
+  /*    FT_ULong                                                           */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    A typedef for unsigned long.                                       */
+  /*                                                                       */
+  typedef unsigned long  FT_ULong;
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Type>                                                                */
+  /*    FT_F2Dot14                                                         */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    A signed 2.14 fixed float type used for unit vectors.              */
+  /*                                                                       */
+  typedef signed short  FT_F2Dot14;
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Type>                                                                */
+  /*    FT_F26Dot6                                                         */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    A signed 26.6 fixed float type used for vectorial pixel            */
+  /*    coordinates.                                                       */
+  /*                                                                       */
+  typedef signed long  FT_F26Dot6;
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Type>                                                                */
+  /*    FT_Fixed                                                           */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    This type is used to store 16.16 fixed float values, like scaling  */
+  /*    values or matrix coefficients.                                     */
+  /*                                                                       */
+  typedef signed long  FT_Fixed;
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Type>                                                                */
+  /*    FT_Error                                                           */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    The FreeType error code type.  A value of 0 is always interpreted  */
+  /*    as a successful operation.                                         */
+  /*                                                                       */
+  typedef int  FT_Error;
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Type>                                                                */
+  /*    FT_Pointer                                                         */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    A simple typedef for a typeless pointer.                           */
+  /*                                                                       */
+  typedef void*  FT_Pointer;
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Type>                                                                */
+  /*    FT_Offset                                                          */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    This is equivalent to the ANSI C `size_t' type, i.e., the largest  */
+  /*    _unsigned_ integer type used to express a file size or position,   */
+  /*    or a memory block size.                                            */
+  /*                                                                       */
+  typedef size_t  FT_Offset;
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Type>                                                                */
+  /*    FT_PtrDist                                                         */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    This is equivalent to the ANSI C `ptrdiff_t' type, i.e., the       */
+  /*    largest _signed_ integer type used to express the distance         */
+  /*    between two pointers.                                              */
+  /*                                                                       */
+  typedef ft_ptrdiff_t  FT_PtrDist;
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Struct>                                                              */
+  /*    FT_UnitVector                                                      */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    A simple structure used to store a 2D vector unit vector.  Uses    */
+  /*    FT_F2Dot14 types.                                                  */
+  /*                                                                       */
+  /* <Fields>                                                              */
+  /*    x :: Horizontal coordinate.                                        */
+  /*                                                                       */
+  /*    y :: Vertical coordinate.                                          */
+  /*                                                                       */
+  typedef struct  FT_UnitVector_
+  {
+    FT_F2Dot14  x;
+    FT_F2Dot14  y;
+
+  } FT_UnitVector;
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Struct>                                                              */
+  /*    FT_Matrix                                                          */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    A simple structure used to store a 2x2 matrix.  Coefficients are   */
+  /*    in 16.16 fixed float format.  The computation performed is:        */
+  /*                                                                       */
+  /*       {                                                               */
+  /*          x' = x*xx + y*xy                                             */
+  /*          y' = x*yx + y*yy                                             */
+  /*       }                                                               */
+  /*                                                                       */
+  /* <Fields>                                                              */
+  /*    xx :: Matrix coefficient.                                          */
+  /*                                                                       */
+  /*    xy :: Matrix coefficient.                                          */
+  /*                                                                       */
+  /*    yx :: Matrix coefficient.                                          */
+  /*                                                                       */
+  /*    yy :: Matrix coefficient.                                          */
+  /*                                                                       */
+  typedef struct  FT_Matrix_
+  {
+    FT_Fixed  xx, xy;
+    FT_Fixed  yx, yy;
+
+  } FT_Matrix;
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Struct>                                                              */
+  /*    FT_Data                                                            */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    Read-only binary data represented as a pointer and a length.       */
+  /*                                                                       */
+  /* <Fields>                                                              */
+  /*    pointer :: The data.                                               */
+  /*                                                                       */
+  /*    length  :: The length of the data in bytes.                        */
+  /*                                                                       */
+  typedef struct  FT_Data_
+  {
+    const FT_Byte*  pointer;
+    FT_Int          length;
+
+  } FT_Data;
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <FuncType>                                                            */
+  /*    FT_Generic_Finalizer                                               */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    Describes a function used to destroy the `client' data of any      */
+  /*    FreeType object.  See the description of the @FT_Generic type for  */
+  /*    details of usage.                                                  */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    The address of the FreeType object which is under finalization.    */
+  /*    Its client data is accessed through its `generic' field.           */
+  /*                                                                       */
+  typedef void  (*FT_Generic_Finalizer)(void*  object);
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Struct>                                                              */
+  /*    FT_Generic                                                         */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    Client applications often need to associate their own data to a    */
+  /*    variety of FreeType core objects.  For example, a text layout API  */
+  /*    might want to associate a glyph cache to a given size object.      */
+  /*                                                                       */
+  /*    Most FreeType object contains a `generic' field, of type           */
+  /*    FT_Generic, which usage is left to client applications and font    */
+  /*    servers.                                                           */
+  /*                                                                       */
+  /*    It can be used to store a pointer to client-specific data, as well */
+  /*    as the address of a `finalizer' function, which will be called by  */
+  /*    FreeType when the object is destroyed (for example, the previous   */
+  /*    client example would put the address of the glyph cache destructor */
+  /*    in the `finalizer' field).                                         */
+  /*                                                                       */
+  /* <Fields>                                                              */
+  /*    data      :: A typeless pointer to any client-specified data. This */
+  /*                 field is completely ignored by the FreeType library.  */
+  /*                                                                       */
+  /*    finalizer :: A pointer to a `generic finalizer' function, which    */
+  /*                 will be called when the object is destroyed.  If this */
+  /*                 field is set to NULL, no code will be called.         */
+  /*                                                                       */
+  typedef struct  FT_Generic_
+  {
+    void*                 data;
+    FT_Generic_Finalizer  finalizer;
+
+  } FT_Generic;
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Macro>                                                               */
+  /*    FT_MAKE_TAG                                                        */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    This macro converts four-letter tags which are used to label       */
+  /*    TrueType tables into an unsigned long to be used within FreeType.  */
+  /*                                                                       */
+  /* <Note>                                                                */
+  /*    The produced values *must* be 32bit integers.  Don't redefine this */
+  /*    macro.                                                             */
+  /*                                                                       */
+#define FT_MAKE_TAG( _x1, _x2, _x3, _x4 ) \
+          ( ( (FT_ULong)_x1 << 24 ) |     \
+            ( (FT_ULong)_x2 << 16 ) |     \
+            ( (FT_ULong)_x3 <<  8 ) |     \
+              (FT_ULong)_x4         )
+
+
+  /*************************************************************************/
+  /*************************************************************************/
+  /*                                                                       */
+  /*                    L I S T   M A N A G E M E N T                      */
+  /*                                                                       */
+  /*************************************************************************/
+  /*************************************************************************/
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Section>                                                             */
+  /*    list_processing                                                    */
+  /*                                                                       */
+  /*************************************************************************/
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Type>                                                                */
+  /*    FT_ListNode                                                        */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*     Many elements and objects in FreeType are listed through an       */
+  /*     @FT_List record (see @FT_ListRec).  As its name suggests, an      */
+  /*     FT_ListNode is a handle to a single list element.                 */
+  /*                                                                       */
+  typedef struct FT_ListNodeRec_*  FT_ListNode;
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Type>                                                                */
+  /*    FT_List                                                            */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    A handle to a list record (see @FT_ListRec).                       */
+  /*                                                                       */
+  typedef struct FT_ListRec_*  FT_List;
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Struct>                                                              */
+  /*    FT_ListNodeRec                                                     */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    A structure used to hold a single list element.                    */
+  /*                                                                       */
+  /* <Fields>                                                              */
+  /*    prev :: The previous element in the list.  NULL if first.          */
+  /*                                                                       */
+  /*    next :: The next element in the list.  NULL if last.               */
+  /*                                                                       */
+  /*    data :: A typeless pointer to the listed object.                   */
+  /*                                                                       */
+  typedef struct  FT_ListNodeRec_
+  {
+    FT_ListNode  prev;
+    FT_ListNode  next;
+    void*        data;
+
+  } FT_ListNodeRec;
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Struct>                                                              */
+  /*    FT_ListRec                                                         */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    A structure used to hold a simple doubly-linked list.  These are   */
+  /*    used in many parts of FreeType.                                    */
+  /*                                                                       */
+  /* <Fields>                                                              */
+  /*    head :: The head (first element) of doubly-linked list.            */
+  /*                                                                       */
+  /*    tail :: The tail (last element) of doubly-linked list.             */
+  /*                                                                       */
+  typedef struct  FT_ListRec_
+  {
+    FT_ListNode  head;
+    FT_ListNode  tail;
+
+  } FT_ListRec;
+
+
+  /* */
+
+#define FT_IS_EMPTY( list )  ( (list).head == 0 )
+
+  /* return base error code (without module-specific prefix) */
+#define FT_ERROR_BASE( x )    ( (x) & 0xFF )
+
+  /* return module error code */
+#define FT_ERROR_MODULE( x )  ( (x) & 0xFF00U )
+
+#define FT_BOOL( x )  ( (FT_Bool)( x ) )
+
+FT_END_HEADER
+
+#endif /* __FTTYPES_H__ */
+
+
+/* END */

+ 263 - 0
include/freetype/ftwinfnt.h

@@ -0,0 +1,263 @@
+/***************************************************************************/
+/*                                                                         */
+/*  ftwinfnt.h                                                             */
+/*                                                                         */
+/*    FreeType API for accessing Windows fnt-specific data.                */
+/*                                                                         */
+/*  Copyright 2003, 2004 by                                                */
+/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */
+/*                                                                         */
+/*  This file is part of the FreeType project, and may only be used,       */
+/*  modified, and distributed under the terms of the FreeType project      */
+/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */
+/*  this file you indicate that you have read the license and              */
+/*  understand and accept it fully.                                        */
+/*                                                                         */
+/***************************************************************************/
+
+
+#ifndef __FTWINFNT_H__
+#define __FTWINFNT_H__
+
+#include <ft2build.h>
+#include FT_FREETYPE_H
+
+#ifdef FREETYPE_H
+#error "freetype.h of FreeType 1 has been loaded!"
+#error "Please fix the directory search order for header files"
+#error "so that freetype.h of FreeType 2 is found first."
+#endif
+
+
+FT_BEGIN_HEADER
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Section>                                                             */
+  /*    winfnt_fonts                                                       */
+  /*                                                                       */
+  /* <Title>                                                               */
+  /*    Window FNT Files                                                   */
+  /*                                                                       */
+  /* <Abstract>                                                            */
+  /*    Windows FNT specific API.                                          */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    This section contains the declaration of Windows FNT specific      */
+  /*    functions.                                                         */
+  /*                                                                       */
+  /*************************************************************************/
+
+
+  /*************************************************************************
+   *
+   * @enum:
+   *   FT_WinFNT_ID_XXX
+   *
+   * @description:
+   *   A list of valid values for the `charset' byte in
+   *   @FT_WinFNT_HeaderRec.  Exact mapping tables for the various cpXXXX
+   *   encodings (except for cp1361) can be found at ftp://ftp.unicode.org
+   *   in the MAPPINGS/VENDORS/MICSFT/WINDOWS subdirectory.  cp1361 is
+   *   roughly a superset of MAPPINGS/OBSOLETE/EASTASIA/KSC/JOHAB.TXT.
+   *
+   * @values:
+   *   FT_WinFNT_ID_DEFAULT ::
+   *     This is used for font enumeration and font creation as a
+   *     `don't care' value.  Valid font files don't contain this value.
+   *     When querying for information about the character set of the font
+   *     that is currently selected into a specified device context, this
+   *     return value (of the related Windows API) simply denotes failure.
+   *
+   *   FT_WinFNT_ID_SYMBOL ::
+   *     There is no known mapping table available.
+   *
+   *   FT_WinFNT_ID_MAC ::
+   *     Mac Roman encoding.
+   *
+   *   FT_WinFNT_ID_OEM ::
+   *     From Michael Pöttgen <[email protected]>:
+   *
+   *       The `Windows Font Mapping' article says that FT_WinFNT_ID_OEM
+   *       is used for the charset of vector fonts, like `modern.fon',
+   *       `roman.fon', and `script.fon' on Windows.
+   *
+   *       The `CreateFont' documentation says: The FT_WinFNT_ID_OEM value
+   *       specifies a character set that is operating-system dependent.
+   *
+   *       The `IFIMETRICS' documentation from the `Windows Driver
+   *       Development Kit' says: This font supports an OEM-specific
+   *       character set.  The OEM character set is system dependent.
+   *
+   *       In general OEM, as opposed to ANSI (i.e., cp1252), denotes the
+   *       second default codepage that most international versions of
+   *       Windows have.  It is one of the OEM codepages from
+   *
+   *         http://www.microsoft.com/globaldev/reference/cphome.mspx,
+   *
+   *       and is used for the `DOS boxes', to support legacy applications.
+   *       A German Windows version for example usually uses ANSI codepage
+   *       1252 and OEM codepage 850.
+   *
+   *   FT_WinFNT_ID_CP874 ::
+   *     A superset of Thai TIS 620 and ISO 8859-11.
+   *
+   *   FT_WinFNT_ID_CP932 ::
+   *     A superset of Japanese Shift-JIS (with minor deviations).
+   *
+   *   FT_WinFNT_ID_CP936 ::
+   *     A superset of simplified Chinese GB 2312-1980 (with different
+   *     ordering and minor deviations).
+   *
+   *   FT_WinFNT_ID_CP949 ::
+   *     A superset of Korean Hangul KS C 5601-1987 (with different
+   *     ordering and minor deviations).
+   *
+   *   FT_WinFNT_ID_CP950 ::
+   *     A superset of traditional Chinese Big 5 ETen (with different
+   *     ordering and minor deviations).
+   *
+   *   FT_WinFNT_ID_CP1250 ::
+   *     A superset of East European ISO 8859-2 (with slightly different
+   *     ordering).
+   *
+   *   FT_WinFNT_ID_CP1251 ::
+   *     A superset of Russian ISO 8859-5 (with different ordering).
+   *
+   *   FT_WinFNT_ID_CP1252 ::
+   *     ANSI encoding.  A superset of ISO 8859-1.
+   *
+   *   FT_WinFNT_ID_CP1253 ::
+   *     A superset of Greek ISO 8859-7 (with minor modifications).
+   *
+   *   FT_WinFNT_ID_CP1254 ::
+   *     A superset of Turkish ISO 8859-9.
+   *
+   *   FT_WinFNT_ID_CP1255 ::
+   *     A superset of Hebrew ISO 8859-8 (with some modifications).
+   *
+   *   FT_WinFNT_ID_CP1256 ::
+   *     A superset of Arabic ISO 8859-6 (with different ordering).
+   *
+   *   FT_WinFNT_ID_CP1257 ::
+   *     A superset of Baltic ISO 8859-13 (with some deviations).
+   *
+   *   FT_WinFNT_ID_CP1258 ::
+   *     For Vietnamese.  This encoding doesn't cover all necessary
+   *     characters.
+   *
+   *   FT_WinFNT_ID_CP1361 ::
+   *     Korean (Johab).
+   */
+
+#define FT_WinFNT_ID_CP1252    0
+#define FT_WinFNT_ID_DEFAULT   1
+#define FT_WinFNT_ID_SYMBOL    2
+#define FT_WinFNT_ID_MAC      77
+#define FT_WinFNT_ID_CP932   128
+#define FT_WinFNT_ID_CP949   129
+#define FT_WinFNT_ID_CP1361  130
+#define FT_WinFNT_ID_CP936   134
+#define FT_WinFNT_ID_CP950   136
+#define FT_WinFNT_ID_CP1253  161
+#define FT_WinFNT_ID_CP1254  162
+#define FT_WinFNT_ID_CP1258  163
+#define FT_WinFNT_ID_CP1255  177
+#define FT_WinFNT_ID_CP1256  178
+#define FT_WinFNT_ID_CP1257  186
+#define FT_WinFNT_ID_CP1251  204
+#define FT_WinFNT_ID_CP874   222
+#define FT_WinFNT_ID_CP1250  238
+#define FT_WinFNT_ID_OEM     255
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Struct>                                                              */
+  /*    FT_WinFNT_HeaderRec                                                */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    Windows FNT Header info.                                           */
+  /*                                                                       */
+  typedef struct  FT_WinFNT_HeaderRec_
+  {
+    FT_UShort  version;
+    FT_ULong   file_size;
+    FT_Byte    copyright[60];
+    FT_UShort  file_type;
+    FT_UShort  nominal_point_size;
+    FT_UShort  vertical_resolution;
+    FT_UShort  horizontal_resolution;
+    FT_UShort  ascent;
+    FT_UShort  internal_leading;
+    FT_UShort  external_leading;
+    FT_Byte    italic;
+    FT_Byte    underline;
+    FT_Byte    strike_out;
+    FT_UShort  weight;
+    FT_Byte    charset;
+    FT_UShort  pixel_width;
+    FT_UShort  pixel_height;
+    FT_Byte    pitch_and_family;
+    FT_UShort  avg_width;
+    FT_UShort  max_width;
+    FT_Byte    first_char;
+    FT_Byte    last_char;
+    FT_Byte    default_char;
+    FT_Byte    break_char;
+    FT_UShort  bytes_per_row;
+    FT_ULong   device_offset;
+    FT_ULong   face_name_offset;
+    FT_ULong   bits_pointer;
+    FT_ULong   bits_offset;
+    FT_Byte    reserved;
+    FT_ULong   flags;
+    FT_UShort  A_space;
+    FT_UShort  B_space;
+    FT_UShort  C_space;
+    FT_UShort  color_table_offset;
+    FT_ULong   reserved1[4];
+
+  } FT_WinFNT_HeaderRec, *FT_WinFNT_Header;
+
+
+ /**********************************************************************
+  *
+  * @function:
+  *    FT_Get_WinFNT_Header
+  *
+  * @description:
+  *    Retrieve a Windows FNT font info header.
+  *
+  * @input:
+  *    face    :: A handle to the input face.
+  *
+  * @output:
+  *    aheader :: The WinFNT header.
+  *
+  * @return:
+  *   FreeType error code.  0 means success.
+  *
+  * @note:
+  *   This function only works with Windows FNT faces, returning an error
+  *   otherwise.
+  */
+  FT_EXPORT( FT_Error )
+  FT_Get_WinFNT_Header( FT_Face               face,
+                        FT_WinFNT_HeaderRec  *aheader );
+
+
+ /* */
+
+FT_END_HEADER
+
+#endif /* __FTWINFNT_H__ */
+
+
+/* END */
+
+
+/* Local Variables: */
+/* coding: utf-8    */
+/* End:             */

+ 80 - 0
include/freetype/ftxf86.h

@@ -0,0 +1,80 @@
+/***************************************************************************/
+/*                                                                         */
+/*  ftxf86.h                                                               */
+/*                                                                         */
+/*    Support functions for X11.                                           */
+/*                                                                         */
+/*  Copyright 2002, 2003, 2004, 2006, 2007 by                              */
+/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */
+/*                                                                         */
+/*  This file is part of the FreeType project, and may only be used,       */
+/*  modified, and distributed under the terms of the FreeType project      */
+/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */
+/*  this file you indicate that you have read the license and              */
+/*  understand and accept it fully.                                        */
+/*                                                                         */
+/***************************************************************************/
+
+
+#ifndef __FTXF86_H__
+#define __FTXF86_H__
+
+#include <ft2build.h>
+#include FT_FREETYPE_H
+
+#ifdef FREETYPE_H
+#error "freetype.h of FreeType 1 has been loaded!"
+#error "Please fix the directory search order for header files"
+#error "so that freetype.h of FreeType 2 is found first."
+#endif
+
+
+FT_BEGIN_HEADER
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Section>                                                             */
+  /*   font_formats                                                        */
+  /*                                                                       */
+  /* <Title>                                                               */
+  /*   Font Formats                                                        */
+  /*                                                                       */
+  /* <Abstract>                                                            */
+  /*   Getting the font format.                                            */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*   The single function in this section can be used to get the font     */
+  /*   format.  Note that this information is not needed normally;         */
+  /*   however, there are special cases (like in PDF devices) where it is  */
+  /*   important to differentiate, in spite of FreeType's uniform API.     */
+  /*                                                                       */
+  /*************************************************************************/
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*   FT_Get_X11_Font_Format                                              */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*   Return a string describing the format of a given face, using values */
+  /*   which can be used as an X11 FONT_PROPERTY.  Possible values are     */
+  /*   `TrueType', `Type 1', `BDF', `PCF', `Type 42', `CID Type 1', `CFF', */
+  /*   `PFR', and `Windows FNT'.                                           */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*   face ::                                                             */
+  /*     Input face handle.                                                */
+  /*                                                                       */
+  /* <Return>                                                              */
+  /*   Font format string.  NULL in case of error.                         */
+  /*                                                                       */
+  FT_EXPORT( const char* )
+  FT_Get_X11_Font_Format( FT_Face  face );
+
+ /* */
+
+FT_END_HEADER
+
+#endif /* __FTXF86_H__ */

+ 450 - 0
include/freetype/t1tables.h

@@ -0,0 +1,450 @@
+/***************************************************************************/
+/*                                                                         */
+/*  t1tables.h                                                             */
+/*                                                                         */
+/*    Basic Type 1/Type 2 tables definitions and interface (specification  */
+/*    only).                                                               */
+/*                                                                         */
+/*  Copyright 1996-2001, 2002, 2003, 2004, 2006 by                         */
+/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */
+/*                                                                         */
+/*  This file is part of the FreeType project, and may only be used,       */
+/*  modified, and distributed under the terms of the FreeType project      */
+/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */
+/*  this file you indicate that you have read the license and              */
+/*  understand and accept it fully.                                        */
+/*                                                                         */
+/***************************************************************************/
+
+
+#ifndef __T1TABLES_H__
+#define __T1TABLES_H__
+
+
+#include <ft2build.h>
+#include FT_FREETYPE_H
+
+#ifdef FREETYPE_H
+#error "freetype.h of FreeType 1 has been loaded!"
+#error "Please fix the directory search order for header files"
+#error "so that freetype.h of FreeType 2 is found first."
+#endif
+
+
+FT_BEGIN_HEADER
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Section>                                                             */
+  /*    type1_tables                                                       */
+  /*                                                                       */
+  /* <Title>                                                               */
+  /*    Type 1 Tables                                                      */
+  /*                                                                       */
+  /* <Abstract>                                                            */
+  /*    Type 1 (PostScript) specific font tables.                          */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    This section contains the definition of Type 1-specific tables,    */
+  /*    including structures related to other PostScript font formats.     */
+  /*                                                                       */
+  /*************************************************************************/
+
+
+  /* Note that we separate font data in PS_FontInfoRec and PS_PrivateRec */
+  /* structures in order to support Multiple Master fonts.               */
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Struct>                                                              */
+  /*    PS_FontInfoRec                                                     */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    A structure used to model a Type1/Type2 FontInfo dictionary.  Note */
+  /*    that for Multiple Master fonts, each instance has its own          */
+  /*    FontInfo dictionary.                                               */
+  /*                                                                       */
+  typedef struct  PS_FontInfoRec
+  {
+    FT_String*  version;
+    FT_String*  notice;
+    FT_String*  full_name;
+    FT_String*  family_name;
+    FT_String*  weight;
+    FT_Long     italic_angle;
+    FT_Bool     is_fixed_pitch;
+    FT_Short    underline_position;
+    FT_UShort   underline_thickness;
+
+  } PS_FontInfoRec, *PS_FontInfo;
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Struct>                                                              */
+  /*    T1_FontInfo                                                        */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    This type is equivalent to @PS_FontInfoRec.  It is deprecated but  */
+  /*    kept to maintain source compatibility between various versions of  */
+  /*    FreeType.                                                          */
+  /*                                                                       */
+  typedef PS_FontInfoRec  T1_FontInfo;
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Struct>                                                              */
+  /*    PS_PrivateRec                                                      */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    A structure used to model a Type1/Type2 private dictionary.  Note  */
+  /*    that for Multiple Master fonts, each instance has its own Private  */
+  /*    dictionary.                                                        */
+  /*                                                                       */
+  typedef struct  PS_PrivateRec_
+  {
+    FT_Int     unique_id;
+    FT_Int     lenIV;
+
+    FT_Byte    num_blue_values;
+    FT_Byte    num_other_blues;
+    FT_Byte    num_family_blues;
+    FT_Byte    num_family_other_blues;
+
+    FT_Short   blue_values[14];
+    FT_Short   other_blues[10];
+
+    FT_Short   family_blues      [14];
+    FT_Short   family_other_blues[10];
+
+    FT_Fixed   blue_scale;
+    FT_Int     blue_shift;
+    FT_Int     blue_fuzz;
+
+    FT_UShort  standard_width[1];
+    FT_UShort  standard_height[1];
+
+    FT_Byte    num_snap_widths;
+    FT_Byte    num_snap_heights;
+    FT_Bool    force_bold;
+    FT_Bool    round_stem_up;
+
+    FT_Short   snap_widths [13];  /* including std width  */
+    FT_Short   snap_heights[13];  /* including std height */
+
+    FT_Fixed   expansion_factor;
+
+    FT_Long    language_group;
+    FT_Long    password;
+
+    FT_Short   min_feature[2];
+
+  } PS_PrivateRec, *PS_Private;
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Struct>                                                              */
+  /*    T1_Private                                                         */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*   This type is equivalent to @PS_PrivateRec.  It is deprecated but    */
+  /*   kept to maintain source compatibility between various versions of   */
+  /*   FreeType.                                                           */
+  /*                                                                       */
+  typedef PS_PrivateRec  T1_Private;
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Enum>                                                                */
+  /*    T1_Blend_Flags                                                     */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    A set of flags used to indicate which fields are present in a      */
+  /*    given blend dictionary (font info or private).  Used to support    */
+  /*    Multiple Masters fonts.                                            */
+  /*                                                                       */
+  typedef enum
+  {
+    /*# required fields in a FontInfo blend dictionary */
+    T1_BLEND_UNDERLINE_POSITION = 0,
+    T1_BLEND_UNDERLINE_THICKNESS,
+    T1_BLEND_ITALIC_ANGLE,
+
+    /*# required fields in a Private blend dictionary */
+    T1_BLEND_BLUE_VALUES,
+    T1_BLEND_OTHER_BLUES,
+    T1_BLEND_STANDARD_WIDTH,
+    T1_BLEND_STANDARD_HEIGHT,
+    T1_BLEND_STEM_SNAP_WIDTHS,
+    T1_BLEND_STEM_SNAP_HEIGHTS,
+    T1_BLEND_BLUE_SCALE,
+    T1_BLEND_BLUE_SHIFT,
+    T1_BLEND_FAMILY_BLUES,
+    T1_BLEND_FAMILY_OTHER_BLUES,
+    T1_BLEND_FORCE_BOLD,
+
+    /*# never remove */
+    T1_BLEND_MAX
+
+  } T1_Blend_Flags;
+
+  /* */
+
+
+  /*# backwards compatible definitions */
+#define t1_blend_underline_position   T1_BLEND_UNDERLINE_POSITION
+#define t1_blend_underline_thickness  T1_BLEND_UNDERLINE_THICKNESS
+#define t1_blend_italic_angle         T1_BLEND_ITALIC_ANGLE
+#define t1_blend_blue_values          T1_BLEND_BLUE_VALUES
+#define t1_blend_other_blues          T1_BLEND_OTHER_BLUES
+#define t1_blend_standard_widths      T1_BLEND_STANDARD_WIDTH
+#define t1_blend_standard_height      T1_BLEND_STANDARD_HEIGHT
+#define t1_blend_stem_snap_widths     T1_BLEND_STEM_SNAP_WIDTHS
+#define t1_blend_stem_snap_heights    T1_BLEND_STEM_SNAP_HEIGHTS
+#define t1_blend_blue_scale           T1_BLEND_BLUE_SCALE
+#define t1_blend_blue_shift           T1_BLEND_BLUE_SHIFT
+#define t1_blend_family_blues         T1_BLEND_FAMILY_BLUES
+#define t1_blend_family_other_blues   T1_BLEND_FAMILY_OTHER_BLUES
+#define t1_blend_force_bold           T1_BLEND_FORCE_BOLD
+#define t1_blend_max                  T1_BLEND_MAX
+
+
+  /* maximum number of Multiple Masters designs, as defined in the spec */
+#define T1_MAX_MM_DESIGNS     16
+
+  /* maximum number of Multiple Masters axes, as defined in the spec */
+#define T1_MAX_MM_AXIS        4
+
+  /* maximum number of elements in a design map */
+#define T1_MAX_MM_MAP_POINTS  20
+
+
+  /* this structure is used to store the BlendDesignMap entry for an axis */
+  typedef struct  PS_DesignMap_
+  {
+    FT_Byte    num_points;
+    FT_Long*   design_points;
+    FT_Fixed*  blend_points;
+
+  } PS_DesignMapRec, *PS_DesignMap;
+
+  /* backwards-compatible definition */
+  typedef PS_DesignMapRec  T1_DesignMap;
+
+
+  typedef struct  PS_BlendRec_
+  {
+    FT_UInt          num_designs;
+    FT_UInt          num_axis;
+
+    FT_String*       axis_names[T1_MAX_MM_AXIS];
+    FT_Fixed*        design_pos[T1_MAX_MM_DESIGNS];
+    PS_DesignMapRec  design_map[T1_MAX_MM_AXIS];
+
+    FT_Fixed*        weight_vector;
+    FT_Fixed*        default_weight_vector;
+
+    PS_FontInfo      font_infos[T1_MAX_MM_DESIGNS + 1];
+    PS_Private       privates  [T1_MAX_MM_DESIGNS + 1];
+
+    FT_ULong         blend_bitflags;
+
+    FT_BBox*         bboxes    [T1_MAX_MM_DESIGNS + 1];
+
+    /* since 2.3.0 */
+
+    /* undocumented, optional: the default design instance;   */
+    /* corresponds to default_weight_vector --                */
+    /* num_default_design_vector == 0 means it is not present */
+    /* in the font and associated metrics files               */
+    FT_UInt          default_design_vector[T1_MAX_MM_DESIGNS];
+    FT_UInt          num_default_design_vector;
+
+  } PS_BlendRec, *PS_Blend;
+
+
+  /* backwards-compatible definition */
+  typedef PS_BlendRec  T1_Blend;
+
+
+  typedef struct  CID_FaceDictRec_
+  {
+    PS_PrivateRec  private_dict;
+
+    FT_UInt        len_buildchar;
+    FT_Fixed       forcebold_threshold;
+    FT_Pos         stroke_width;
+    FT_Fixed       expansion_factor;
+
+    FT_Byte        paint_type;
+    FT_Byte        font_type;
+    FT_Matrix      font_matrix;
+    FT_Vector      font_offset;
+
+    FT_UInt        num_subrs;
+    FT_ULong       subrmap_offset;
+    FT_Int         sd_bytes;
+
+  } CID_FaceDictRec, *CID_FaceDict;
+
+
+  /* backwards-compatible definition */
+  typedef CID_FaceDictRec  CID_FontDict;
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Struct>                                                              */
+  /*    CID_FaceInfoRec                                                    */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    A structure used to represent CID Face information.                */
+  /*                                                                       */
+  typedef struct  CID_FaceInfoRec_
+  {
+    FT_String*      cid_font_name;
+    FT_Fixed        cid_version;
+    FT_Int          cid_font_type;
+
+    FT_String*      registry;
+    FT_String*      ordering;
+    FT_Int          supplement;
+
+    PS_FontInfoRec  font_info;
+    FT_BBox         font_bbox;
+    FT_ULong        uid_base;
+
+    FT_Int          num_xuid;
+    FT_ULong        xuid[16];
+
+    FT_ULong        cidmap_offset;
+    FT_Int          fd_bytes;
+    FT_Int          gd_bytes;
+    FT_ULong        cid_count;
+
+    FT_Int          num_dicts;
+    CID_FaceDict    font_dicts;
+
+    FT_ULong        data_offset;
+
+  } CID_FaceInfoRec, *CID_FaceInfo;
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Struct>                                                              */
+  /*    CID_Info                                                           */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*   This type is equivalent to @CID_FaceInfoRec.  It is deprecated but  */
+  /*   kept to maintain source compatibility between various versions of   */
+  /*   FreeType.                                                           */
+  /*                                                                       */
+  typedef CID_FaceInfoRec  CID_Info;
+
+  /* */
+
+
+ /************************************************************************
+  *
+  * @function:
+  *    FT_Has_PS_Glyph_Names
+  *
+  * @description:
+  *    Return true if a given face provides reliable Postscript glyph
+  *    names.  This is similar to using the @FT_HAS_GLYPH_NAMES macro,
+  *    except that certain fonts (mostly TrueType) contain incorrect
+  *    glyph name tables.
+  *
+  *    When this function returns true, the caller is sure that the glyph
+  *    names returned by @FT_Get_Glyph_Name are reliable.
+  *
+  * @input:
+  *    face ::
+  *       face handle
+  *
+  * @return:
+  *    Boolean.  True if glyph names are reliable.
+  */
+  FT_EXPORT( FT_Int )
+  FT_Has_PS_Glyph_Names( FT_Face  face );
+
+
+ /************************************************************************
+  *
+  * @function:
+  *    FT_Get_PS_Font_Info
+  *
+  * @description:
+  *    Retrieve the @PS_FontInfoRec structure corresponding to a given
+  *    Postscript font.
+  *
+  * @input:
+  *    face ::
+  *       Postscript face handle.
+  *
+  * @output:
+  *    afont_info ::
+  *       Output font info structure pointer.
+  *
+  * @return:
+  *    FreeType error code.  0 means success.
+  *
+  * @note:
+  *    The string pointers within the font info structure are owned by
+  *    the face and don't need to be freed by the caller.
+  *
+  *    If the font's format is not Postscript-based, this function will
+  *    return the `FT_Err_Invalid_Argument' error code.
+  */
+  FT_EXPORT( FT_Error )
+  FT_Get_PS_Font_Info( FT_Face          face,
+                       PS_FontInfoRec  *afont_info );
+
+
+ /************************************************************************
+  *
+  * @function:
+  *    FT_Get_PS_Font_Private
+  *
+  * @description:
+  *    Retrieve the @PS_PrivateRec structure corresponding to a given
+  *    Postscript font.
+  *
+  * @input:
+  *    face ::
+  *       Postscript face handle.
+  *
+  * @output:
+  *    afont_private ::
+  *       Output private dictionary structure pointer.
+  *
+  * @return:
+  *    FreeType error code.  0 means success.
+  *
+  * @note:
+  *    The string pointers within the font info structure are owned by
+  *    the face and don't need to be freed by the caller.
+  *
+  *    If the font's format is not Postscript-based, this function will
+  *    return the `FT_Err_Invalid_Argument' error code.
+  */
+  FT_EXPORT( FT_Error )
+  FT_Get_PS_Font_Private( FT_Face         face,
+                          PS_PrivateRec  *afont_private );
+
+ /* */
+
+
+
+FT_END_HEADER
+
+#endif /* __T1TABLES_H__ */
+
+
+/* END */

+ 1132 - 0
include/freetype/ttnameid.h

@@ -0,0 +1,1132 @@
+/***************************************************************************/
+/*                                                                         */
+/*  ttnameid.h                                                             */
+/*                                                                         */
+/*    TrueType name ID definitions (specification only).                   */
+/*                                                                         */
+/*  Copyright 1996-2002, 2003, 2004, 2006, 2007 by                         */
+/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */
+/*                                                                         */
+/*  This file is part of the FreeType project, and may only be used,       */
+/*  modified, and distributed under the terms of the FreeType project      */
+/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */
+/*  this file you indicate that you have read the license and              */
+/*  understand and accept it fully.                                        */
+/*                                                                         */
+/***************************************************************************/
+
+
+#ifndef __TTNAMEID_H__
+#define __TTNAMEID_H__
+
+
+#include <ft2build.h>
+
+
+FT_BEGIN_HEADER
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* Possible values for the `platform' identifier code in the name        */
+  /* records of the TTF `name' table.                                      */
+  /*                                                                       */
+  /*************************************************************************/
+
+
+  /***********************************************************************
+   *
+   * @enum:
+   *   TT_PLATFORM_XXX
+   *
+   * @description:
+   *   A list of valid values for the `platform_id' identifier code in
+   *   @FT_CharMapRec and @FT_SfntName structures.
+   *
+   * @values:
+   *   TT_PLATFORM_APPLE_UNICODE ::
+   *     Used by Apple to indicate a Unicode character map and/or name entry.
+   *     See @TT_APPLE_ID_XXX for corresponding `encoding_id' values.  Note
+   *     that name entries in this format are coded as big-endian UCS-2
+   *     character codes _only_.
+   *
+   *   TT_PLATFORM_MACINTOSH ::
+   *     Used by Apple to indicate a MacOS-specific charmap and/or name entry.
+   *     See @TT_MAC_ID_XXX for corresponding `encoding_id' values.  Note that
+   *     most TrueType fonts contain an Apple roman charmap to be usable on
+   *     MacOS systems (even if they contain a Microsoft charmap as well).
+   *
+   *   TT_PLATFORM_ISO ::
+   *     This value was used to specify Unicode charmaps.  It is however
+   *     now deprecated.  See @TT_ISO_ID_XXX for a list of corresponding
+   *     `encoding_id' values.
+   *
+   *   TT_PLATFORM_MICROSOFT ::
+   *     Used by Microsoft to indicate Windows-specific charmaps.  See
+   *     @TT_MS_ID_XXX for a list of corresponding `encoding_id' values.
+   *     Note that most fonts contain a Unicode charmap using
+   *     (TT_PLATFORM_MICROSOFT, @TT_MS_ID_UNICODE_CS).
+   *
+   *   TT_PLATFORM_CUSTOM ::
+   *     Used to indicate application-specific charmaps.
+   *
+   *   TT_PLATFORM_ADOBE ::
+   *     This value isn't part of any font format specification, but is used
+   *     by FreeType to report Adobe-specific charmaps in an @FT_CharMapRec
+   *     structure.  See @TT_ADOBE_ID_XXX.
+   */
+
+#define TT_PLATFORM_APPLE_UNICODE  0
+#define TT_PLATFORM_MACINTOSH      1
+#define TT_PLATFORM_ISO            2 /* deprecated */
+#define TT_PLATFORM_MICROSOFT      3
+#define TT_PLATFORM_CUSTOM         4
+#define TT_PLATFORM_ADOBE          7 /* artificial */
+
+
+  /***********************************************************************
+   *
+   * @enum:
+   *   TT_APPLE_ID_XXX
+   *
+   * @description:
+   *   A list of valid values for the `encoding_id' for
+   *   @TT_PLATFORM_APPLE_UNICODE charmaps and name entries.
+   *
+   * @values:
+   *   TT_APPLE_ID_DEFAULT ::
+   *     Unicode version 1.0.
+   *
+   *   TT_APPLE_ID_UNICODE_1_1 ::
+   *     Unicode 1.1; specifies Hangul characters starting at U+34xx.
+   *
+   *   TT_APPLE_ID_ISO_10646 ::
+   *     Deprecated (identical to preceding).
+   *
+   *   TT_APPLE_ID_UNICODE_2_0 ::
+   *     Unicode 2.0 and beyond (UTF-16 BMP only).
+   *
+   *   TT_APPLE_ID_UNICODE_32 ::
+   *     Unicode 3.1 and beyond, using UTF-32.
+   */
+
+#define TT_APPLE_ID_DEFAULT      0 /* Unicode 1.0 */
+#define TT_APPLE_ID_UNICODE_1_1  1 /* specify Hangul at U+34xx */
+#define TT_APPLE_ID_ISO_10646    2 /* deprecated */
+#define TT_APPLE_ID_UNICODE_2_0  3 /* or later */
+#define TT_APPLE_ID_UNICODE_32   4 /* 2.0 or later, full repertoire */
+
+
+  /***********************************************************************
+   *
+   * @enum:
+   *   TT_MAC_ID_XXX
+   *
+   * @description:
+   *   A list of valid values for the `encoding_id' for
+   *   @TT_PLATFORM_MACINTOSH charmaps and name entries.
+   *
+   * @values:
+   *   TT_MAC_ID_ROMAN ::
+   *   TT_MAC_ID_JAPANESE ::
+   *   TT_MAC_ID_TRADITIONAL_CHINESE ::
+   *   TT_MAC_ID_KOREAN ::
+   *   TT_MAC_ID_ARABIC ::
+   *   TT_MAC_ID_HEBREW ::
+   *   TT_MAC_ID_GREEK ::
+   *   TT_MAC_ID_RUSSIAN ::
+   *   TT_MAC_ID_RSYMBOL ::
+   *   TT_MAC_ID_DEVANAGARI ::
+   *   TT_MAC_ID_GURMUKHI ::
+   *   TT_MAC_ID_GUJARATI ::
+   *   TT_MAC_ID_ORIYA ::
+   *   TT_MAC_ID_BENGALI ::
+   *   TT_MAC_ID_TAMIL ::
+   *   TT_MAC_ID_TELUGU ::
+   *   TT_MAC_ID_KANNADA ::
+   *   TT_MAC_ID_MALAYALAM ::
+   *   TT_MAC_ID_SINHALESE ::
+   *   TT_MAC_ID_BURMESE ::
+   *   TT_MAC_ID_KHMER ::
+   *   TT_MAC_ID_THAI ::
+   *   TT_MAC_ID_LAOTIAN ::
+   *   TT_MAC_ID_GEORGIAN ::
+   *   TT_MAC_ID_ARMENIAN ::
+   *   TT_MAC_ID_MALDIVIAN ::
+   *   TT_MAC_ID_SIMPLIFIED_CHINESE ::
+   *   TT_MAC_ID_TIBETAN ::
+   *   TT_MAC_ID_MONGOLIAN ::
+   *   TT_MAC_ID_GEEZ ::
+   *   TT_MAC_ID_SLAVIC ::
+   *   TT_MAC_ID_VIETNAMESE ::
+   *   TT_MAC_ID_SINDHI ::
+   *   TT_MAC_ID_UNINTERP ::
+   */
+
+#define TT_MAC_ID_ROMAN                 0
+#define TT_MAC_ID_JAPANESE              1
+#define TT_MAC_ID_TRADITIONAL_CHINESE   2
+#define TT_MAC_ID_KOREAN                3
+#define TT_MAC_ID_ARABIC                4
+#define TT_MAC_ID_HEBREW                5
+#define TT_MAC_ID_GREEK                 6
+#define TT_MAC_ID_RUSSIAN               7
+#define TT_MAC_ID_RSYMBOL               8
+#define TT_MAC_ID_DEVANAGARI            9
+#define TT_MAC_ID_GURMUKHI             10
+#define TT_MAC_ID_GUJARATI             11
+#define TT_MAC_ID_ORIYA                12
+#define TT_MAC_ID_BENGALI              13
+#define TT_MAC_ID_TAMIL                14
+#define TT_MAC_ID_TELUGU               15
+#define TT_MAC_ID_KANNADA              16
+#define TT_MAC_ID_MALAYALAM            17
+#define TT_MAC_ID_SINHALESE            18
+#define TT_MAC_ID_BURMESE              19
+#define TT_MAC_ID_KHMER                20
+#define TT_MAC_ID_THAI                 21
+#define TT_MAC_ID_LAOTIAN              22
+#define TT_MAC_ID_GEORGIAN             23
+#define TT_MAC_ID_ARMENIAN             24
+#define TT_MAC_ID_MALDIVIAN            25
+#define TT_MAC_ID_SIMPLIFIED_CHINESE   25
+#define TT_MAC_ID_TIBETAN              26
+#define TT_MAC_ID_MONGOLIAN            27
+#define TT_MAC_ID_GEEZ                 28
+#define TT_MAC_ID_SLAVIC               29
+#define TT_MAC_ID_VIETNAMESE           30
+#define TT_MAC_ID_SINDHI               31
+#define TT_MAC_ID_UNINTERP             32
+
+
+  /***********************************************************************
+   *
+   * @enum:
+   *   TT_ISO_ID_XXX
+   *
+   * @description:
+   *   A list of valid values for the `encoding_id' for
+   *   @TT_PLATFORM_ISO charmaps and name entries.
+   *
+   *   Their use is now deprecated.
+   *
+   * @values:
+   *   TT_ISO_ID_7BIT_ASCII ::
+   *     ASCII.
+   *   TT_ISO_ID_10646 ::
+   *     ISO/10646.
+   *   TT_ISO_ID_8859_1 ::
+   *     Also known as Latin-1.
+   */
+
+#define TT_ISO_ID_7BIT_ASCII  0
+#define TT_ISO_ID_10646       1
+#define TT_ISO_ID_8859_1      2
+
+
+  /***********************************************************************
+   *
+   * @enum:
+   *   TT_MS_ID_XXX
+   *
+   * @description:
+   *   A list of valid values for the `encoding_id' for
+   *   @TT_PLATFORM_MICROSOFT charmaps and name entries.
+   *
+   * @values:
+   *   TT_MS_ID_SYMBOL_CS ::
+   *     Corresponds to Microsoft symbol encoding. See
+   *     @FT_ENCODING_MS_SYMBOL.
+   *
+   *   TT_MS_ID_UNICODE_CS ::
+   *     Corresponds to a Microsoft WGL4 charmap, matching Unicode.  See
+   *     @FT_ENCODING_UNICODE.
+   *
+   *   TT_MS_ID_SJIS ::
+   *     Corresponds to SJIS Japanese encoding.  See @FT_ENCODING_SJIS.
+   *
+   *   TT_MS_ID_GB2312 ::
+   *     Corresponds to Simplified Chinese as used in Mainland China.  See
+   *     @FT_ENCODING_GB2312.
+   *
+   *   TT_MS_ID_BIG_5 ::
+   *     Corresponds to Traditional Chinese as used in Taiwan and Hong Kong.
+   *     See @FT_ENCODING_BIG5.
+   *
+   *   TT_MS_ID_WANSUNG ::
+   *     Corresponds to Korean Wansung encoding.  See @FT_ENCODING_WANSUNG.
+   *
+   *   TT_MS_ID_JOHAB ::
+   *     Corresponds to Johab encoding.  See @FT_ENCODING_JOHAB.
+   *
+   *   TT_MS_ID_UCS_4 ::
+   *     Corresponds to UCS-4 or UTF-32 charmaps.  This has been added to
+   *     the OpenType specification version 1.4 (mid-2001.)
+   */
+
+#define TT_MS_ID_SYMBOL_CS    0
+#define TT_MS_ID_UNICODE_CS   1
+#define TT_MS_ID_SJIS         2
+#define TT_MS_ID_GB2312       3
+#define TT_MS_ID_BIG_5        4
+#define TT_MS_ID_WANSUNG      5
+#define TT_MS_ID_JOHAB        6
+#define TT_MS_ID_UCS_4       10
+
+
+  /***********************************************************************
+   *
+   * @enum:
+   *   TT_ADOBE_ID_XXX
+   *
+   * @description:
+   *   A list of valid values for the `encoding_id' for
+   *   @TT_PLATFORM_ADOBE charmaps.  This is a FreeType-specific extension!
+   *
+   * @values:
+   *   TT_ADOBE_ID_STANDARD ::
+   *     Adobe standard encoding.
+   *   TT_ADOBE_ID_EXPERT ::
+   *     Adobe expert encoding.
+   *   TT_ADOBE_ID_CUSTOM ::
+   *     Adobe custom encoding.
+   */
+
+#define TT_ADOBE_ID_STANDARD  0
+#define TT_ADOBE_ID_EXPERT    1
+#define TT_ADOBE_ID_CUSTOM    2
+#define TT_ADOBE_ID_LATIN_1   3
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* Possible values of the language identifier field in the name records  */
+  /* of the TTF `name' table if the `platform' identifier code is          */
+  /* TT_PLATFORM_MACINTOSH.                                                */
+  /*                                                                       */
+  /* The canonical source for the Apple assigned Language ID's is at       */
+  /*                                                                       */
+  /*   http://fonts.apple.com/TTRefMan/RM06/Chap6name.html                 */
+  /*                                                                       */
+#define TT_MAC_LANGID_ENGLISH                       0
+#define TT_MAC_LANGID_FRENCH                        1
+#define TT_MAC_LANGID_GERMAN                        2
+#define TT_MAC_LANGID_ITALIAN                       3
+#define TT_MAC_LANGID_DUTCH                         4
+#define TT_MAC_LANGID_SWEDISH                       5
+#define TT_MAC_LANGID_SPANISH                       6
+#define TT_MAC_LANGID_DANISH                        7
+#define TT_MAC_LANGID_PORTUGUESE                    8
+#define TT_MAC_LANGID_NORWEGIAN                     9
+#define TT_MAC_LANGID_HEBREW                       10
+#define TT_MAC_LANGID_JAPANESE                     11
+#define TT_MAC_LANGID_ARABIC                       12
+#define TT_MAC_LANGID_FINNISH                      13
+#define TT_MAC_LANGID_GREEK                        14
+#define TT_MAC_LANGID_ICELANDIC                    15
+#define TT_MAC_LANGID_MALTESE                      16
+#define TT_MAC_LANGID_TURKISH                      17
+#define TT_MAC_LANGID_CROATIAN                     18
+#define TT_MAC_LANGID_CHINESE_TRADITIONAL          19
+#define TT_MAC_LANGID_URDU                         20
+#define TT_MAC_LANGID_HINDI                        21
+#define TT_MAC_LANGID_THAI                         22
+#define TT_MAC_LANGID_KOREAN                       23
+#define TT_MAC_LANGID_LITHUANIAN                   24
+#define TT_MAC_LANGID_POLISH                       25
+#define TT_MAC_LANGID_HUNGARIAN                    26
+#define TT_MAC_LANGID_ESTONIAN                     27
+#define TT_MAC_LANGID_LETTISH                      28
+#define TT_MAC_LANGID_SAAMISK                      29
+#define TT_MAC_LANGID_FAEROESE                     30
+#define TT_MAC_LANGID_FARSI                        31
+#define TT_MAC_LANGID_RUSSIAN                      32
+#define TT_MAC_LANGID_CHINESE_SIMPLIFIED           33
+#define TT_MAC_LANGID_FLEMISH                      34
+#define TT_MAC_LANGID_IRISH                        35
+#define TT_MAC_LANGID_ALBANIAN                     36
+#define TT_MAC_LANGID_ROMANIAN                     37
+#define TT_MAC_LANGID_CZECH                        38
+#define TT_MAC_LANGID_SLOVAK                       39
+#define TT_MAC_LANGID_SLOVENIAN                    40
+#define TT_MAC_LANGID_YIDDISH                      41
+#define TT_MAC_LANGID_SERBIAN                      42
+#define TT_MAC_LANGID_MACEDONIAN                   43
+#define TT_MAC_LANGID_BULGARIAN                    44
+#define TT_MAC_LANGID_UKRAINIAN                    45
+#define TT_MAC_LANGID_BYELORUSSIAN                 46
+#define TT_MAC_LANGID_UZBEK                        47
+#define TT_MAC_LANGID_KAZAKH                       48
+#define TT_MAC_LANGID_AZERBAIJANI                  49
+#define TT_MAC_LANGID_AZERBAIJANI_CYRILLIC_SCRIPT  49
+#define TT_MAC_LANGID_AZERBAIJANI_ARABIC_SCRIPT    50
+#define TT_MAC_LANGID_ARMENIAN                     51
+#define TT_MAC_LANGID_GEORGIAN                     52
+#define TT_MAC_LANGID_MOLDAVIAN                    53
+#define TT_MAC_LANGID_KIRGHIZ                      54
+#define TT_MAC_LANGID_TAJIKI                       55
+#define TT_MAC_LANGID_TURKMEN                      56
+#define TT_MAC_LANGID_MONGOLIAN                    57
+#define TT_MAC_LANGID_MONGOLIAN_MONGOLIAN_SCRIPT   57
+#define TT_MAC_LANGID_MONGOLIAN_CYRILLIC_SCRIPT    58
+#define TT_MAC_LANGID_PASHTO                       59
+#define TT_MAC_LANGID_KURDISH                      60
+#define TT_MAC_LANGID_KASHMIRI                     61
+#define TT_MAC_LANGID_SINDHI                       62
+#define TT_MAC_LANGID_TIBETAN                      63
+#define TT_MAC_LANGID_NEPALI                       64
+#define TT_MAC_LANGID_SANSKRIT                     65
+#define TT_MAC_LANGID_MARATHI                      66
+#define TT_MAC_LANGID_BENGALI                      67
+#define TT_MAC_LANGID_ASSAMESE                     68
+#define TT_MAC_LANGID_GUJARATI                     69
+#define TT_MAC_LANGID_PUNJABI                      70
+#define TT_MAC_LANGID_ORIYA                        71
+#define TT_MAC_LANGID_MALAYALAM                    72
+#define TT_MAC_LANGID_KANNADA                      73
+#define TT_MAC_LANGID_TAMIL                        74
+#define TT_MAC_LANGID_TELUGU                       75
+#define TT_MAC_LANGID_SINHALESE                    76
+#define TT_MAC_LANGID_BURMESE                      77
+#define TT_MAC_LANGID_KHMER                        78
+#define TT_MAC_LANGID_LAO                          79
+#define TT_MAC_LANGID_VIETNAMESE                   80
+#define TT_MAC_LANGID_INDONESIAN                   81
+#define TT_MAC_LANGID_TAGALOG                      82
+#define TT_MAC_LANGID_MALAY_ROMAN_SCRIPT           83
+#define TT_MAC_LANGID_MALAY_ARABIC_SCRIPT          84
+#define TT_MAC_LANGID_AMHARIC                      85
+#define TT_MAC_LANGID_TIGRINYA                     86
+#define TT_MAC_LANGID_GALLA                        87
+#define TT_MAC_LANGID_SOMALI                       88
+#define TT_MAC_LANGID_SWAHILI                      89
+#define TT_MAC_LANGID_RUANDA                       90
+#define TT_MAC_LANGID_RUNDI                        91
+#define TT_MAC_LANGID_CHEWA                        92
+#define TT_MAC_LANGID_MALAGASY                     93
+#define TT_MAC_LANGID_ESPERANTO                    94
+#define TT_MAC_LANGID_WELSH                       128
+#define TT_MAC_LANGID_BASQUE                      129
+#define TT_MAC_LANGID_CATALAN                     130
+#define TT_MAC_LANGID_LATIN                       131
+#define TT_MAC_LANGID_QUECHUA                     132
+#define TT_MAC_LANGID_GUARANI                     133
+#define TT_MAC_LANGID_AYMARA                      134
+#define TT_MAC_LANGID_TATAR                       135
+#define TT_MAC_LANGID_UIGHUR                      136
+#define TT_MAC_LANGID_DZONGKHA                    137
+#define TT_MAC_LANGID_JAVANESE                    138
+#define TT_MAC_LANGID_SUNDANESE                   139
+
+
+#if 0  /* these seem to be errors that have been dropped */
+
+#define TT_MAC_LANGID_SCOTTISH_GAELIC             140
+#define TT_MAC_LANGID_IRISH_GAELIC                141
+
+#endif
+
+
+  /* The following codes are new as of 2000-03-10 */
+#define TT_MAC_LANGID_GALICIAN                    140
+#define TT_MAC_LANGID_AFRIKAANS                   141
+#define TT_MAC_LANGID_BRETON                      142
+#define TT_MAC_LANGID_INUKTITUT                   143
+#define TT_MAC_LANGID_SCOTTISH_GAELIC             144
+#define TT_MAC_LANGID_MANX_GAELIC                 145
+#define TT_MAC_LANGID_IRISH_GAELIC                146
+#define TT_MAC_LANGID_TONGAN                      147
+#define TT_MAC_LANGID_GREEK_POLYTONIC             148
+#define TT_MAC_LANGID_GREELANDIC                  149
+#define TT_MAC_LANGID_AZERBAIJANI_ROMAN_SCRIPT    150
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* Possible values of the language identifier field in the name records  */
+  /* of the TTF `name' table if the `platform' identifier code is          */
+  /* TT_PLATFORM_MICROSOFT.                                                */
+  /*                                                                       */
+  /* The canonical source for the MS assigned LCID's (seems to) be at      */
+  /*                                                                       */
+  /*   http://www.microsoft.com/globaldev/reference/lcid-all.mspx          */
+  /*                                                                       */
+  /* It used to be at various places, among them                           */
+  /*                                                                       */
+  /*   http://www.microsoft.com/typography/OTSPEC/lcid-cp.txt              */
+  /*   http://www.microsoft.com/globaldev/reference/loclanghome.asp        */
+  /*   http://support.microsoft.com/support/kb/articles/Q224/8/04.ASP      */
+  /*   http://msdn.microsoft.com/library/en-us/passport25/                 */
+  /*           NET_Passport_VBScript_Documentation/Single_Sign_In/         */
+  /*           Advanced_Single_Sign_In/Localization_and_LCIDs.asp          */
+  /*                                                                       */
+  /* Hopefully, it seems now that the Globaldev site prevails...           */
+  /*                                   (updated by Antoine, 2004-02-17)    */
+
+#define TT_MS_LANGID_ARABIC_GENERAL                    0x0001
+#define TT_MS_LANGID_ARABIC_SAUDI_ARABIA               0x0401
+#define TT_MS_LANGID_ARABIC_IRAQ                       0x0801
+#define TT_MS_LANGID_ARABIC_EGYPT                      0x0c01
+#define TT_MS_LANGID_ARABIC_LIBYA                      0x1001
+#define TT_MS_LANGID_ARABIC_ALGERIA                    0x1401
+#define TT_MS_LANGID_ARABIC_MOROCCO                    0x1801
+#define TT_MS_LANGID_ARABIC_TUNISIA                    0x1c01
+#define TT_MS_LANGID_ARABIC_OMAN                       0x2001
+#define TT_MS_LANGID_ARABIC_YEMEN                      0x2401
+#define TT_MS_LANGID_ARABIC_SYRIA                      0x2801
+#define TT_MS_LANGID_ARABIC_JORDAN                     0x2c01
+#define TT_MS_LANGID_ARABIC_LEBANON                    0x3001
+#define TT_MS_LANGID_ARABIC_KUWAIT                     0x3401
+#define TT_MS_LANGID_ARABIC_UAE                        0x3801
+#define TT_MS_LANGID_ARABIC_BAHRAIN                    0x3c01
+#define TT_MS_LANGID_ARABIC_QATAR                      0x4001
+#define TT_MS_LANGID_BULGARIAN_BULGARIA                0x0402
+#define TT_MS_LANGID_CATALAN_SPAIN                     0x0403
+#define TT_MS_LANGID_CHINESE_GENERAL                   0x0004
+#define TT_MS_LANGID_CHINESE_TAIWAN                    0x0404
+#define TT_MS_LANGID_CHINESE_PRC                       0x0804
+#define TT_MS_LANGID_CHINESE_HONG_KONG                 0x0c04
+#define TT_MS_LANGID_CHINESE_SINGAPORE                 0x1004
+
+#if 1  /* this looks like the correct value */
+#define TT_MS_LANGID_CHINESE_MACAU                     0x1404
+#else  /* but beware, Microsoft may change its mind...
+          the most recent Word reference has the following: */
+#define TT_MS_LANGID_CHINESE_MACAU  TT_MS_LANGID_CHINESE_HONG_KONG
+#endif
+
+#if 0  /* used only with .NET `cultures'; commented out */
+#define TT_MS_LANGID_CHINESE_TRADITIONAL               0x7C04
+#endif
+
+#define TT_MS_LANGID_CZECH_CZECH_REPUBLIC              0x0405
+#define TT_MS_LANGID_DANISH_DENMARK                    0x0406
+#define TT_MS_LANGID_GERMAN_GERMANY                    0x0407
+#define TT_MS_LANGID_GERMAN_SWITZERLAND                0x0807
+#define TT_MS_LANGID_GERMAN_AUSTRIA                    0x0c07
+#define TT_MS_LANGID_GERMAN_LUXEMBOURG                 0x1007
+#define TT_MS_LANGID_GERMAN_LIECHTENSTEI               0x1407
+#define TT_MS_LANGID_GREEK_GREECE                      0x0408
+
+  /* don't ask what this one means... It is commented out currently. */
+#if 0
+#define TT_MS_LANGID_GREEK_GREECE2                     0x2008
+#endif
+
+#define TT_MS_LANGID_ENGLISH_GENERAL                   0x0009
+#define TT_MS_LANGID_ENGLISH_UNITED_STATES             0x0409
+#define TT_MS_LANGID_ENGLISH_UNITED_KINGDOM            0x0809
+#define TT_MS_LANGID_ENGLISH_AUSTRALIA                 0x0c09
+#define TT_MS_LANGID_ENGLISH_CANADA                    0x1009
+#define TT_MS_LANGID_ENGLISH_NEW_ZEALAND               0x1409
+#define TT_MS_LANGID_ENGLISH_IRELAND                   0x1809
+#define TT_MS_LANGID_ENGLISH_SOUTH_AFRICA              0x1c09
+#define TT_MS_LANGID_ENGLISH_JAMAICA                   0x2009
+#define TT_MS_LANGID_ENGLISH_CARIBBEAN                 0x2409
+#define TT_MS_LANGID_ENGLISH_BELIZE                    0x2809
+#define TT_MS_LANGID_ENGLISH_TRINIDAD                  0x2c09
+#define TT_MS_LANGID_ENGLISH_ZIMBABWE                  0x3009
+#define TT_MS_LANGID_ENGLISH_PHILIPPINES               0x3409
+#define TT_MS_LANGID_ENGLISH_INDONESIA                 0x3809
+#define TT_MS_LANGID_ENGLISH_HONG_KONG                 0x3c09
+#define TT_MS_LANGID_ENGLISH_INDIA                     0x4009
+#define TT_MS_LANGID_ENGLISH_MALAYSIA                  0x4409
+#define TT_MS_LANGID_ENGLISH_SINGAPORE                 0x4809
+#define TT_MS_LANGID_SPANISH_SPAIN_TRADITIONAL_SORT    0x040a
+#define TT_MS_LANGID_SPANISH_MEXICO                    0x080a
+#define TT_MS_LANGID_SPANISH_SPAIN_INTERNATIONAL_SORT  0x0c0a
+#define TT_MS_LANGID_SPANISH_GUATEMALA                 0x100a
+#define TT_MS_LANGID_SPANISH_COSTA_RICA                0x140a
+#define TT_MS_LANGID_SPANISH_PANAMA                    0x180a
+#define TT_MS_LANGID_SPANISH_DOMINICAN_REPUBLIC        0x1c0a
+#define TT_MS_LANGID_SPANISH_VENEZUELA                 0x200a
+#define TT_MS_LANGID_SPANISH_COLOMBIA                  0x240a
+#define TT_MS_LANGID_SPANISH_PERU                      0x280a
+#define TT_MS_LANGID_SPANISH_ARGENTINA                 0x2c0a
+#define TT_MS_LANGID_SPANISH_ECUADOR                   0x300a
+#define TT_MS_LANGID_SPANISH_CHILE                     0x340a
+#define TT_MS_LANGID_SPANISH_URUGUAY                   0x380a
+#define TT_MS_LANGID_SPANISH_PARAGUAY                  0x3c0a
+#define TT_MS_LANGID_SPANISH_BOLIVIA                   0x400a
+#define TT_MS_LANGID_SPANISH_EL_SALVADOR               0x440a
+#define TT_MS_LANGID_SPANISH_HONDURAS                  0x480a
+#define TT_MS_LANGID_SPANISH_NICARAGUA                 0x4c0a
+#define TT_MS_LANGID_SPANISH_PUERTO_RICO               0x500a
+#define TT_MS_LANGID_SPANISH_UNITED_STATES             0x540a
+  /* The following ID blatantly violate MS specs by using a */
+  /* sublanguage > 0x1F.                                    */
+#define TT_MS_LANGID_SPANISH_LATIN_AMERICA             0xE40aU
+#define TT_MS_LANGID_FINNISH_FINLAND                   0x040b
+#define TT_MS_LANGID_FRENCH_FRANCE                     0x040c
+#define TT_MS_LANGID_FRENCH_BELGIUM                    0x080c
+#define TT_MS_LANGID_FRENCH_CANADA                     0x0c0c
+#define TT_MS_LANGID_FRENCH_SWITZERLAND                0x100c
+#define TT_MS_LANGID_FRENCH_LUXEMBOURG                 0x140c
+#define TT_MS_LANGID_FRENCH_MONACO                     0x180c
+#define TT_MS_LANGID_FRENCH_WEST_INDIES                0x1c0c
+#define TT_MS_LANGID_FRENCH_REUNION                    0x200c
+#define TT_MS_LANGID_FRENCH_CONGO                      0x240c
+  /* which was formerly: */
+#define TT_MS_LANGID_FRENCH_ZAIRE  TT_MS_LANGID_FRENCH_CONGO
+#define TT_MS_LANGID_FRENCH_SENEGAL                    0x280c
+#define TT_MS_LANGID_FRENCH_CAMEROON                   0x2c0c
+#define TT_MS_LANGID_FRENCH_COTE_D_IVOIRE              0x300c
+#define TT_MS_LANGID_FRENCH_MALI                       0x340c
+#define TT_MS_LANGID_FRENCH_MOROCCO                    0x380c
+#define TT_MS_LANGID_FRENCH_HAITI                      0x3c0c
+  /* and another violation of the spec (see 0xE40aU) */
+#define TT_MS_LANGID_FRENCH_NORTH_AFRICA               0xE40cU
+#define TT_MS_LANGID_HEBREW_ISRAEL                     0x040d
+#define TT_MS_LANGID_HUNGARIAN_HUNGARY                 0x040e
+#define TT_MS_LANGID_ICELANDIC_ICELAND                 0x040f
+#define TT_MS_LANGID_ITALIAN_ITALY                     0x0410
+#define TT_MS_LANGID_ITALIAN_SWITZERLAND               0x0810
+#define TT_MS_LANGID_JAPANESE_JAPAN                    0x0411
+#define TT_MS_LANGID_KOREAN_EXTENDED_WANSUNG_KOREA     0x0412
+#define TT_MS_LANGID_KOREAN_JOHAB_KOREA                0x0812
+#define TT_MS_LANGID_DUTCH_NETHERLANDS                 0x0413
+#define TT_MS_LANGID_DUTCH_BELGIUM                     0x0813
+#define TT_MS_LANGID_NORWEGIAN_NORWAY_BOKMAL           0x0414
+#define TT_MS_LANGID_NORWEGIAN_NORWAY_NYNORSK          0x0814
+#define TT_MS_LANGID_POLISH_POLAND                     0x0415
+#define TT_MS_LANGID_PORTUGUESE_BRAZIL                 0x0416
+#define TT_MS_LANGID_PORTUGUESE_PORTUGAL               0x0816
+#define TT_MS_LANGID_RHAETO_ROMANIC_SWITZERLAND        0x0417
+#define TT_MS_LANGID_ROMANIAN_ROMANIA                  0x0418
+#define TT_MS_LANGID_MOLDAVIAN_MOLDAVIA                0x0818
+#define TT_MS_LANGID_RUSSIAN_RUSSIA                    0x0419
+#define TT_MS_LANGID_RUSSIAN_MOLDAVIA                  0x0819
+#define TT_MS_LANGID_CROATIAN_CROATIA                  0x041a
+#define TT_MS_LANGID_SERBIAN_SERBIA_LATIN              0x081a
+#define TT_MS_LANGID_SERBIAN_SERBIA_CYRILLIC           0x0c1a
+
+#if 0  /* this used to be this value, but it looks like we were wrong */
+#define TT_MS_LANGID_BOSNIAN_BOSNIA_HERZEGOVINA        0x101a
+#else  /* current sources say */
+#define TT_MS_LANGID_CROATIAN_BOSNIA_HERZEGOVINA       0x101a
+#define TT_MS_LANGID_BOSNIAN_BOSNIA_HERZEGOVINA        0x141a
+       /* and XPsp2 Platform SDK added (2004-07-26) */
+       /* Names are shortened to be significant within 40 chars. */
+#define TT_MS_LANGID_SERBIAN_BOSNIA_HERZ_LATIN         0x181a
+#define TT_MS_LANGID_SERBIAN_BOSNIA_HERZ_CYRILLIC      0x181a
+#endif
+
+#define TT_MS_LANGID_SLOVAK_SLOVAKIA                   0x041b
+#define TT_MS_LANGID_ALBANIAN_ALBANIA                  0x041c
+#define TT_MS_LANGID_SWEDISH_SWEDEN                    0x041d
+#define TT_MS_LANGID_SWEDISH_FINLAND                   0x081d
+#define TT_MS_LANGID_THAI_THAILAND                     0x041e
+#define TT_MS_LANGID_TURKISH_TURKEY                    0x041f
+#define TT_MS_LANGID_URDU_PAKISTAN                     0x0420
+#define TT_MS_LANGID_URDU_INDIA                        0x0820
+#define TT_MS_LANGID_INDONESIAN_INDONESIA              0x0421
+#define TT_MS_LANGID_UKRAINIAN_UKRAINE                 0x0422
+#define TT_MS_LANGID_BELARUSIAN_BELARUS                0x0423
+#define TT_MS_LANGID_SLOVENE_SLOVENIA                  0x0424
+#define TT_MS_LANGID_ESTONIAN_ESTONIA                  0x0425
+#define TT_MS_LANGID_LATVIAN_LATVIA                    0x0426
+#define TT_MS_LANGID_LITHUANIAN_LITHUANIA              0x0427
+#define TT_MS_LANGID_CLASSIC_LITHUANIAN_LITHUANIA      0x0827
+#define TT_MS_LANGID_TAJIK_TAJIKISTAN                  0x0428
+#define TT_MS_LANGID_FARSI_IRAN                        0x0429
+#define TT_MS_LANGID_VIETNAMESE_VIET_NAM               0x042a
+#define TT_MS_LANGID_ARMENIAN_ARMENIA                  0x042b
+#define TT_MS_LANGID_AZERI_AZERBAIJAN_LATIN            0x042c
+#define TT_MS_LANGID_AZERI_AZERBAIJAN_CYRILLIC         0x082c
+#define TT_MS_LANGID_BASQUE_SPAIN                      0x042d
+#define TT_MS_LANGID_SORBIAN_GERMANY                   0x042e
+#define TT_MS_LANGID_MACEDONIAN_MACEDONIA              0x042f
+#define TT_MS_LANGID_SUTU_SOUTH_AFRICA                 0x0430
+#define TT_MS_LANGID_TSONGA_SOUTH_AFRICA               0x0431
+#define TT_MS_LANGID_TSWANA_SOUTH_AFRICA               0x0432
+#define TT_MS_LANGID_VENDA_SOUTH_AFRICA                0x0433
+#define TT_MS_LANGID_XHOSA_SOUTH_AFRICA                0x0434
+#define TT_MS_LANGID_ZULU_SOUTH_AFRICA                 0x0435
+#define TT_MS_LANGID_AFRIKAANS_SOUTH_AFRICA            0x0436
+#define TT_MS_LANGID_GEORGIAN_GEORGIA                  0x0437
+#define TT_MS_LANGID_FAEROESE_FAEROE_ISLANDS           0x0438
+#define TT_MS_LANGID_HINDI_INDIA                       0x0439
+#define TT_MS_LANGID_MALTESE_MALTA                     0x043a
+  /* Added by XPsp2 Platform SDK (2004-07-26) */
+#define TT_MS_LANGID_SAMI_NORTHERN_NORWAY              0x043b
+#define TT_MS_LANGID_SAMI_NORTHERN_SWEDEN              0x083b
+#define TT_MS_LANGID_SAMI_NORTHERN_FINLAND             0x0C3b
+#define TT_MS_LANGID_SAMI_LULE_NORWAY                  0x103b
+#define TT_MS_LANGID_SAMI_LULE_SWEDEN                  0x143b
+#define TT_MS_LANGID_SAMI_SOUTHERN_NORWAY              0x183b
+#define TT_MS_LANGID_SAMI_SOUTHERN_SWEDEN              0x1C3b
+#define TT_MS_LANGID_SAMI_SKOLT_FINLAND                0x203b
+#define TT_MS_LANGID_SAMI_INARI_FINLAND                0x243b
+  /* ... and we also keep our old identifier... */
+#define TT_MS_LANGID_SAAMI_LAPONIA                     0x043b
+
+#if 0 /* this seems to be a previous inversion */
+#define TT_MS_LANGID_IRISH_GAELIC_IRELAND              0x043c
+#define TT_MS_LANGID_SCOTTISH_GAELIC_UNITED_KINGDOM    0x083c
+#else
+#define TT_MS_LANGID_SCOTTISH_GAELIC_UNITED_KINGDOM    0x083c
+#define TT_MS_LANGID_IRISH_GAELIC_IRELAND              0x043c
+#endif
+
+#define TT_MS_LANGID_YIDDISH_GERMANY                   0x043d
+#define TT_MS_LANGID_MALAY_MALAYSIA                    0x043e
+#define TT_MS_LANGID_MALAY_BRUNEI_DARUSSALAM           0x083e
+#define TT_MS_LANGID_KAZAK_KAZAKSTAN                   0x043f
+#define TT_MS_LANGID_KIRGHIZ_KIRGHIZSTAN /* Cyrillic*/ 0x0440
+  /* alias declared in Windows 2000 */
+#define TT_MS_LANGID_KIRGHIZ_KIRGHIZ_REPUBLIC \
+          TT_MS_LANGID_KIRGHIZ_KIRGHIZSTAN
+
+#define TT_MS_LANGID_SWAHILI_KENYA                     0x0441
+#define TT_MS_LANGID_TURKMEN_TURKMENISTAN              0x0442
+#define TT_MS_LANGID_UZBEK_UZBEKISTAN_LATIN            0x0443
+#define TT_MS_LANGID_UZBEK_UZBEKISTAN_CYRILLIC         0x0843
+#define TT_MS_LANGID_TATAR_TATARSTAN                   0x0444
+#define TT_MS_LANGID_BENGALI_INDIA                     0x0445
+#define TT_MS_LANGID_BENGALI_BANGLADESH                0x0845
+#define TT_MS_LANGID_PUNJABI_INDIA                     0x0446
+#define TT_MS_LANGID_PUNJABI_ARABIC_PAKISTAN           0x0846
+#define TT_MS_LANGID_GUJARATI_INDIA                    0x0447
+#define TT_MS_LANGID_ORIYA_INDIA                       0x0448
+#define TT_MS_LANGID_TAMIL_INDIA                       0x0449
+#define TT_MS_LANGID_TELUGU_INDIA                      0x044a
+#define TT_MS_LANGID_KANNADA_INDIA                     0x044b
+#define TT_MS_LANGID_MALAYALAM_INDIA                   0x044c
+#define TT_MS_LANGID_ASSAMESE_INDIA                    0x044d
+#define TT_MS_LANGID_MARATHI_INDIA                     0x044e
+#define TT_MS_LANGID_SANSKRIT_INDIA                    0x044f
+#define TT_MS_LANGID_MONGOLIAN_MONGOLIA /* Cyrillic */ 0x0450
+#define TT_MS_LANGID_MONGOLIAN_MONGOLIA_MONGOLIAN      0x0850
+#define TT_MS_LANGID_TIBETAN_CHINA                     0x0451
+  /* Don't use the next constant!  It has            */
+  /*   (1) the wrong spelling (Dzonghka)             */
+  /*   (2) Microsoft doesn't officially define it -- */
+  /*       at least it is not in the List of Local   */
+  /*       ID Values.                                */
+  /*   (3) Dzongkha is not the same language as      */
+  /*       Tibetan, so merging it is wrong anyway.   */
+  /*                                                 */
+  /* TT_MS_LANGID_TIBETAN_BHUTAN is correct, BTW.    */
+#define TT_MS_LANGID_DZONGHKA_BHUTAN                   0x0851
+
+#if 0
+  /* the following used to be defined */
+#define TT_MS_LANGID_TIBETAN_BHUTAN                    0x0451
+  /* ... but it was changed; */
+#else
+  /* So we will continue to #define it, but with the correct value */
+#define TT_MS_LANGID_TIBETAN_BHUTAN   TT_MS_LANGID_DZONGHKA_BHUTAN
+#endif
+
+#define TT_MS_LANGID_WELSH_WALES                       0x0452
+#define TT_MS_LANGID_KHMER_CAMBODIA                    0x0453
+#define TT_MS_LANGID_LAO_LAOS                          0x0454
+#define TT_MS_LANGID_BURMESE_MYANMAR                   0x0455
+#define TT_MS_LANGID_GALICIAN_SPAIN                    0x0456
+#define TT_MS_LANGID_KONKANI_INDIA                     0x0457
+#define TT_MS_LANGID_MANIPURI_INDIA  /* Bengali */     0x0458
+#define TT_MS_LANGID_SINDHI_INDIA /* Arabic */         0x0459
+#define TT_MS_LANGID_SINDHI_PAKISTAN                   0x0859
+  /* Missing a LCID for Sindhi in Devanagari script */
+#define TT_MS_LANGID_SYRIAC_SYRIA                      0x045a
+#define TT_MS_LANGID_SINHALESE_SRI_LANKA               0x045b
+#define TT_MS_LANGID_CHEROKEE_UNITED_STATES            0x045c
+#define TT_MS_LANGID_INUKTITUT_CANADA                  0x045d
+#define TT_MS_LANGID_AMHARIC_ETHIOPIA                  0x045e
+#define TT_MS_LANGID_TAMAZIGHT_MOROCCO /* Arabic */    0x045f
+#define TT_MS_LANGID_TAMAZIGHT_MOROCCO_LATIN           0x085f
+  /* Missing a LCID for Tifinagh script */
+#define TT_MS_LANGID_KASHMIRI_PAKISTAN /* Arabic */    0x0460
+  /* Spelled this way by XPsp2 Platform SDK (2004-07-26) */
+  /* script is yet unclear... might be Arabic, Nagari or Sharada */
+#define TT_MS_LANGID_KASHMIRI_SASIA                    0x0860
+  /* ... and aliased (by MS) for compatibility reasons. */
+#define TT_MS_LANGID_KASHMIRI_INDIA TT_MS_LANGID_KASHMIRI_SASIA
+#define TT_MS_LANGID_NEPALI_NEPAL                      0x0461
+#define TT_MS_LANGID_NEPALI_INDIA                      0x0861
+#define TT_MS_LANGID_FRISIAN_NETHERLANDS               0x0462
+#define TT_MS_LANGID_PASHTO_AFGHANISTAN                0x0463
+#define TT_MS_LANGID_FILIPINO_PHILIPPINES              0x0464
+#define TT_MS_LANGID_DHIVEHI_MALDIVES                  0x0465
+  /* alias declared in Windows 2000 */
+#define TT_MS_LANGID_DIVEHI_MALDIVES  TT_MS_LANGID_DHIVEHI_MALDIVES
+#define TT_MS_LANGID_EDO_NIGERIA                       0x0466
+#define TT_MS_LANGID_FULFULDE_NIGERIA                  0x0467
+#define TT_MS_LANGID_HAUSA_NIGERIA                     0x0468
+#define TT_MS_LANGID_IBIBIO_NIGERIA                    0x0469
+#define TT_MS_LANGID_YORUBA_NIGERIA                    0x046a
+#define TT_MS_LANGID_QUECHUA_BOLIVIA                   0x046b
+#define TT_MS_LANGID_QUECHUA_ECUADOR                   0x086b
+#define TT_MS_LANGID_QUECHUA_PERU                      0x0c6b
+#define TT_MS_LANGID_SEPEDI_SOUTH_AFRICA               0x046c
+  /* Also spelled by XPsp2 Platform SDK (2004-07-26) */
+#define TT_MS_LANGID_SOTHO_SOUTHERN_SOUTH_AFRICA \
+          TT_MS_LANGID_SEPEDI_SOUTH_AFRICA
+  /* language codes 0x046d, 0x046e and 0x046f are (still) unknown. */
+#define TT_MS_LANGID_IGBO_NIGERIA                      0x0470
+#define TT_MS_LANGID_KANURI_NIGERIA                    0x0471
+#define TT_MS_LANGID_OROMO_ETHIOPIA                    0x0472
+#define TT_MS_LANGID_TIGRIGNA_ETHIOPIA                 0x0473
+#define TT_MS_LANGID_TIGRIGNA_ERYTHREA                 0x0873
+  /* also spelled in the `Passport SDK' list as: */
+#define TT_MS_LANGID_TIGRIGNA_ERYTREA  TT_MS_LANGID_TIGRIGNA_ERYTHREA
+#define TT_MS_LANGID_GUARANI_PARAGUAY                  0x0474
+#define TT_MS_LANGID_HAWAIIAN_UNITED_STATES            0x0475
+#define TT_MS_LANGID_LATIN                             0x0476
+#define TT_MS_LANGID_SOMALI_SOMALIA                    0x0477
+  /* Note: Yi does not have a (proper) ISO 639-2 code, since it is mostly */
+  /*       not written (but OTOH the peculiar writing system is worth     */
+  /*       studying).                                                     */
+#define TT_MS_LANGID_YI_CHINA                          0x0478
+#define TT_MS_LANGID_PAPIAMENTU_NETHERLANDS_ANTILLES   0x0479
+  /* language codes from 0x047a to 0x047f are (still) unknown. */
+#define TT_MS_LANGID_UIGHUR_CHINA                      0x0480
+#define TT_MS_LANGID_MAORI_NEW_ZEALAND                 0x0481
+
+#if 0  /* not deemed useful for fonts */
+#define TT_MS_LANGID_HUMAN_INTERFACE_DEVICE            0x04ff
+#endif
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* Possible values of the `name' identifier field in the name records of */
+  /* the TTF `name' table.  These values are platform independent.         */
+  /*                                                                       */
+#define TT_NAME_ID_COPYRIGHT            0
+#define TT_NAME_ID_FONT_FAMILY          1
+#define TT_NAME_ID_FONT_SUBFAMILY       2
+#define TT_NAME_ID_UNIQUE_ID            3
+#define TT_NAME_ID_FULL_NAME            4
+#define TT_NAME_ID_VERSION_STRING       5
+#define TT_NAME_ID_PS_NAME              6
+#define TT_NAME_ID_TRADEMARK            7
+
+  /* the following values are from the OpenType spec */
+#define TT_NAME_ID_MANUFACTURER         8
+#define TT_NAME_ID_DESIGNER             9
+#define TT_NAME_ID_DESCRIPTION          10
+#define TT_NAME_ID_VENDOR_URL           11
+#define TT_NAME_ID_DESIGNER_URL         12
+#define TT_NAME_ID_LICENSE              13
+#define TT_NAME_ID_LICENSE_URL          14
+  /* number 15 is reserved */
+#define TT_NAME_ID_PREFERRED_FAMILY     16
+#define TT_NAME_ID_PREFERRED_SUBFAMILY  17
+#define TT_NAME_ID_MAC_FULL_NAME        18
+
+  /* The following code is new as of 2000-01-21 */
+#define TT_NAME_ID_SAMPLE_TEXT          19
+
+  /* This is new in OpenType 1.3 */
+#define TT_NAME_ID_CID_FINDFONT_NAME    20
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* Bit mask values for the Unicode Ranges from the TTF `OS2 ' table.     */
+  /*                                                                       */
+  /* Updated 02-Jul-2000.                                                  */
+  /*                                                                       */
+
+  /* General Scripts Area */
+
+  /* Bit  0   Basic Latin */
+#define TT_UCR_BASIC_LATIN                     (1L <<  0) /* U+0020-U+007E */
+  /* Bit  1   C1 Controls and Latin-1 Supplement */
+#define TT_UCR_LATIN1_SUPPLEMENT               (1L <<  1) /* U+0080-U+00FF */
+  /* Bit  2   Latin Extended-A */
+#define TT_UCR_LATIN_EXTENDED_A                (1L <<  2) /* U+0100-U+017F */
+  /* Bit  3   Latin Extended-B */
+#define TT_UCR_LATIN_EXTENDED_B                (1L <<  3) /* U+0180-U+024F */
+  /* Bit  4   IPA Extensions */
+#define TT_UCR_IPA_EXTENSIONS                  (1L <<  4) /* U+0250-U+02AF */
+  /* Bit  5   Spacing Modifier Letters */
+#define TT_UCR_SPACING_MODIFIER                (1L <<  5) /* U+02B0-U+02FF */
+  /* Bit  6   Combining Diacritical Marks */
+#define TT_UCR_COMBINING_DIACRITICS            (1L <<  6) /* U+0300-U+036F */
+  /* Bit  7   Greek and Coptic */
+#define TT_UCR_GREEK                           (1L <<  7) /* U+0370-U+03FF */
+  /* Bit  8 is reserved (was: Greek Symbols and Coptic) */
+  /* Bit  9   Cyrillic               + */
+  /*          Cyrillic Supplementary   */
+#define TT_UCR_CYRILLIC                        (1L <<  9) /* U+0400-U+04FF */
+                                                          /* U+0500-U+052F */
+  /* Bit 10   Armenian */
+#define TT_UCR_ARMENIAN                        (1L << 10) /* U+0530-U+058F */
+  /* Bit 11   Hebrew */
+#define TT_UCR_HEBREW                          (1L << 11) /* U+0590-U+05FF */
+  /* Bit 12 is reserved (was: Hebrew Extended) */
+  /* Bit 13   Arabic */
+#define TT_UCR_ARABIC                          (1L << 13) /* U+0600-U+06FF */
+  /* Bit 14 is reserved (was: Arabic Extended) */
+  /* Bit 15   Devanagari */
+#define TT_UCR_DEVANAGARI                      (1L << 15) /* U+0900-U+097F */
+  /* Bit 16   Bengali */
+#define TT_UCR_BENGALI                         (1L << 16) /* U+0980-U+09FF */
+  /* Bit 17   Gurmukhi */
+#define TT_UCR_GURMUKHI                        (1L << 17) /* U+0A00-U+0A7F */
+  /* Bit 18   Gujarati */
+#define TT_UCR_GUJARATI                        (1L << 18) /* U+0A80-U+0AFF */
+  /* Bit 19   Oriya */
+#define TT_UCR_ORIYA                           (1L << 19) /* U+0B00-U+0B7F */
+  /* Bit 20   Tamil */
+#define TT_UCR_TAMIL                           (1L << 20) /* U+0B80-U+0BFF */
+  /* Bit 21   Telugu */
+#define TT_UCR_TELUGU                          (1L << 21) /* U+0C00-U+0C7F */
+  /* Bit 22   Kannada */
+#define TT_UCR_KANNADA                         (1L << 22) /* U+0C80-U+0CFF */
+  /* Bit 23   Malayalam */
+#define TT_UCR_MALAYALAM                       (1L << 23) /* U+0D00-U+0D7F */
+  /* Bit 24   Thai */
+#define TT_UCR_THAI                            (1L << 24) /* U+0E00-U+0E7F */
+  /* Bit 25   Lao */
+#define TT_UCR_LAO                             (1L << 25) /* U+0E80-U+0EFF */
+  /* Bit 26   Georgian */
+#define TT_UCR_GEORGIAN                        (1L << 26) /* U+10A0-U+10FF */
+  /* Bit 27 is reserved (was Georgian Extended) */
+  /* Bit 28   Hangul Jamo */
+#define TT_UCR_HANGUL_JAMO                     (1L << 28) /* U+1100-U+11FF */
+  /* Bit 29   Latin Extended Additional */
+#define TT_UCR_LATIN_EXTENDED_ADDITIONAL       (1L << 29) /* U+1E00-U+1EFF */
+  /* Bit 30   Greek Extended */
+#define TT_UCR_GREEK_EXTENDED                  (1L << 30) /* U+1F00-U+1FFF */
+
+  /* Symbols Area */
+
+  /* Bit 31   General Punctuation */
+#define TT_UCR_GENERAL_PUNCTUATION             (1L << 31) /* U+2000-U+206F */
+  /* Bit 32   Superscripts And Subscripts */
+#define TT_UCR_SUPERSCRIPTS_SUBSCRIPTS         (1L <<  0) /* U+2070-U+209F */
+  /* Bit 33   Currency Symbols */
+#define TT_UCR_CURRENCY_SYMBOLS                (1L <<  1) /* U+20A0-U+20CF */
+  /* Bit 34   Combining Diacritical Marks For Symbols */
+#define TT_UCR_COMBINING_DIACRITICS_SYMB       (1L <<  2) /* U+20D0-U+20FF */
+  /* Bit 35   Letterlike Symbols */
+#define TT_UCR_LETTERLIKE_SYMBOLS              (1L <<  3) /* U+2100-U+214F */
+  /* Bit 36   Number Forms */
+#define TT_UCR_NUMBER_FORMS                    (1L <<  4) /* U+2150-U+218F */
+  /* Bit 37   Arrows                + */
+  /*          Supplemental Arrows-A + */
+  /*          Supplemental Arrows-B   */
+#define TT_UCR_ARROWS                          (1L <<  5) /* U+2190-U+21FF */
+                                                          /* U+27F0-U+27FF */
+                                                          /* U+2900-U+297F */
+  /* Bit 38   Mathematical Operators               + */
+  /*          Supplemental Mathematical Operators  + */
+  /*          Miscellaneous Mathematical Symbols-A + */
+  /*          Miscellaneous Mathematical Symbols-B   */
+#define TT_UCR_MATHEMATICAL_OPERATORS          (1L <<  6) /* U+2200-U+22FF */
+                                                          /* U+2A00-U+2AFF */
+                                                          /* U+27C0-U+27EF */
+                                                          /* U+2980-U+29FF */
+  /* Bit 39 Miscellaneous Technical */
+#define TT_UCR_MISCELLANEOUS_TECHNICAL         (1L <<  7) /* U+2300-U+23FF */
+  /* Bit 40   Control Pictures */
+#define TT_UCR_CONTROL_PICTURES                (1L <<  8) /* U+2400-U+243F */
+  /* Bit 41   Optical Character Recognition */
+#define TT_UCR_OCR                             (1L <<  9) /* U+2440-U+245F */
+  /* Bit 42   Enclosed Alphanumerics */
+#define TT_UCR_ENCLOSED_ALPHANUMERICS          (1L << 10) /* U+2460-U+24FF */
+  /* Bit 43   Box Drawing */
+#define TT_UCR_BOX_DRAWING                     (1L << 11) /* U+2500-U+257F */
+  /* Bit 44   Block Elements */
+#define TT_UCR_BLOCK_ELEMENTS                  (1L << 12) /* U+2580-U+259F */
+  /* Bit 45   Geometric Shapes */
+#define TT_UCR_GEOMETRIC_SHAPES                (1L << 13) /* U+25A0-U+25FF */
+  /* Bit 46   Miscellaneous Symbols */
+#define TT_UCR_MISCELLANEOUS_SYMBOLS           (1L << 14) /* U+2600-U+26FF */
+  /* Bit 47   Dingbats */
+#define TT_UCR_DINGBATS                        (1L << 15) /* U+2700-U+27BF */
+
+  /* CJK Phonetics and Symbols Area */
+
+  /* Bit 48   CJK Symbols and Punctuation */
+#define TT_UCR_CJK_SYMBOLS                     (1L << 16) /* U+3000-U+303F */
+  /* Bit 49   Hiragana */
+#define TT_UCR_HIRAGANA                        (1L << 17) /* U+3040-U+309F */
+  /* Bit 50   Katakana                     + */
+  /*          Katakana Phonetic Extensions   */
+#define TT_UCR_KATAKANA                        (1L << 18) /* U+30A0-U+30FF */
+                                                          /* U+31F0-U+31FF */
+  /* Bit 51   Bopomofo          + */
+  /*          Bopomofo Extended   */
+#define TT_UCR_BOPOMOFO                        (1L << 19) /* U+3100-U+312F */
+                                                          /* U+31A0-U+31BF */
+  /* Bit 52   Hangul Compatibility Jamo */
+#define TT_UCR_HANGUL_COMPATIBILITY_JAMO       (1L << 20) /* U+3130-U+318F */
+  /* Bit 53   Kanbun */
+#define TT_UCR_CJK_MISC                        (1L << 21) /* U+3190-U+319F */
+#define TT_UCR_KANBUN  TT_UCR_CJK_MISC
+  /* Bit 54   Enclosed CJK Letters and Months */
+#define TT_UCR_ENCLOSED_CJK_LETTERS_MONTHS     (1L << 22) /* U+3200-U+32FF */
+  /* Bit 55   CJK Compatibility */
+#define TT_UCR_CJK_COMPATIBILITY               (1L << 23) /* U+3300-U+33FF */
+
+  /* Hangul Syllables Area */
+
+  /* Bit 56   Hangul */
+#define TT_UCR_HANGUL                          (1L << 24) /* U+AC00-U+D7A3 */
+
+  /* Surrogates Area */
+
+  /* Bit 57   High Surrogates             + */
+  /*          High Private Use Surrogates + */
+  /*          Low Surrogates                */
+#define TT_UCR_SURROGATES                      (1L << 25) /* U+D800-U+DB7F */
+                                                          /* U+DB80-U+DBFF */
+                                                          /* U+DC00-U+DFFF */
+  /* According to OpenType specs v.1.3+, setting bit 57 implies that there */
+  /* is at least one codepoint beyond the Basic Multilingual Plane that is */
+  /* supported by this font.  So it really means:            >= U+10000    */
+
+  /* Bit 58 is reserved for Unicode SubRanges */
+
+  /* CJK Ideographs Area */
+
+  /* Bit 59   CJK Unified Ideographs             + */
+  /*          CJK Radicals Supplement            + */
+  /*          Kangxi Radicals                    + */
+  /*          Ideographic Description Characters + */
+  /*          CJK Unified Ideographs Extension A   */
+  /*          CJK Unified Ideographs Extension A + */
+  /*          CJK Unified Ideographs Extension B + */
+  /*          Kanbun                               */
+#define TT_UCR_CJK_UNIFIED_IDEOGRAPHS          (1L << 27) /* U+4E00-U+9FFF */
+                                                          /* U+2E80-U+2EFF */
+                                                          /* U+2F00-U+2FDF */
+                                                          /* U+2FF0-U+2FFF */
+                                                          /* U+3400-U+4DB5 */
+                                                          /*U+20000-U+2A6DF*/
+                                                          /* U+3190-U+319F */
+
+  /* Private Use Area */
+
+  /* Bit 60   Private Use */
+#define TT_UCR_PRIVATE_USE                     (1L << 28) /* U+E000-U+F8FF */
+
+  /* Compatibility Area and Specials */
+
+  /* Bit 61   CJK Compatibility Ideographs            + */
+  /*          CJK Compatibility Ideographs Supplement   */
+#define TT_UCR_CJK_COMPATIBILITY_IDEOGRAPHS    (1L << 29) /* U+F900-U+FAFF */
+                                                          /*U+2F800-U+2FA1F*/
+  /* Bit 62   Alphabetic Presentation Forms */
+#define TT_UCR_ALPHABETIC_PRESENTATION_FORMS   (1L << 30) /* U+FB00-U+FB4F */
+  /* Bit 63   Arabic Presentation Forms-A */
+#define TT_UCR_ARABIC_PRESENTATIONS_A          (1L << 31) /* U+FB50-U+FDFF */
+  /* Bit 64   Combining Half Marks */
+#define TT_UCR_COMBINING_HALF_MARKS            (1L <<  0) /* U+FE20-U+FE2F */
+  /* Bit 65   CJK Compatibility Forms */
+#define TT_UCR_CJK_COMPATIBILITY_FORMS         (1L <<  1) /* U+FE30-U+FE4F */
+  /* Bit 66   Small Form Variants */
+#define TT_UCR_SMALL_FORM_VARIANTS             (1L <<  2) /* U+FE50-U+FE6F */
+  /* Bit 67   Arabic Presentation Forms-B */
+#define TT_UCR_ARABIC_PRESENTATIONS_B          (1L <<  3) /* U+FE70-U+FEFE */
+  /* Bit 68   Halfwidth and Fullwidth Forms */
+#define TT_UCR_HALFWIDTH_FULLWIDTH_FORMS       (1L <<  4) /* U+FF00-U+FFEF */
+  /* Bit 69   Specials */
+#define TT_UCR_SPECIALS                        (1L <<  5) /* U+FFF0-U+FFFD */
+  /* Bit 70   Tibetan */
+#define TT_UCR_TIBETAN                         (1L <<  6) /* U+0F00-U+0FFF */
+  /* Bit 71   Syriac */
+#define TT_UCR_SYRIAC                          (1L <<  7) /* U+0700-U+074F */
+  /* Bit 72   Thaana */
+#define TT_UCR_THAANA                          (1L <<  8) /* U+0780-U+07BF */
+  /* Bit 73   Sinhala */
+#define TT_UCR_SINHALA                         (1L <<  9) /* U+0D80-U+0DFF */
+  /* Bit 74   Myanmar */
+#define TT_UCR_MYANMAR                         (1L << 10) /* U+1000-U+109F */
+  /* Bit 75   Ethiopic */
+#define TT_UCR_ETHIOPIC                        (1L << 11) /* U+1200-U+137F */
+  /* Bit 76   Cherokee */
+#define TT_UCR_CHEROKEE                        (1L << 12) /* U+13A0-U+13FF */
+  /* Bit 77   Unified Canadian Aboriginal Syllabics */
+#define TT_UCR_CANADIAN_ABORIGINAL_SYLLABICS   (1L << 13) /* U+1400-U+167F */
+  /* Bit 78   Ogham */
+#define TT_UCR_OGHAM                           (1L << 14) /* U+1680-U+169F */
+  /* Bit 79   Runic */
+#define TT_UCR_RUNIC                           (1L << 15) /* U+16A0-U+16FF */
+  /* Bit 80   Khmer */
+#define TT_UCR_KHMER                           (1L << 16) /* U+1780-U+17FF */
+  /* Bit 81   Mongolian */
+#define TT_UCR_MONGOLIAN                       (1L << 17) /* U+1800-U+18AF */
+  /* Bit 82   Braille Patterns */
+#define TT_UCR_BRAILLE                         (1L << 18) /* U+2800-U+28FF */
+  /* Bit 83   Yi Syllables + */
+  /*          Yi Radicals    */
+#define TT_UCR_YI                              (1L << 19) /* U+A000-U+A48F */
+                                                          /* U+A490-U+A4CF */
+  /* Bit 84   Tagalog  + */
+  /*          Hanunoo  + */
+  /*          Buhid    + */
+  /*          Tagbanwa   */
+#define TT_UCR_PHILIPPINE                      (1L << 20) /* U+1700-U+171F */
+                                                          /* U+1720-U+173F */
+                                                          /* U+1740-U+175F */
+                                                          /* U+1760-U+177F */
+  /* Bit 85   Old Italic */
+#define TT_UCR_OLD_ITALIC                      (1L << 21) /*U+10300-U+1032F*/
+  /* Bit 86   Gothic */
+#define TT_UCR_GOTHIC                          (1L << 22) /*U+10330-U+1034F*/
+  /* Bit 87   Deseret */
+#define TT_UCR_DESERET                         (1L << 23) /*U+10400-U+1044F*/
+  /* Bit 88   Byzantine Musical Symbols + */
+  /*          Musical Symbols             */
+#define TT_UCR_MUSICAL_SYMBOLS                 (1L << 24) /*U+1D000-U+1D0FF*/
+                                                          /*U+1D100-U+1D1FF*/
+  /* Bit 89   Mathematical Alphanumeric Symbols */
+#define TT_UCR_MATH_ALPHANUMERIC_SYMBOLS       (1L << 25) /*U+1D400-U+1D7FF*/
+  /* Bit 90   Private Use (plane 15) + */
+  /*          Private Use (plane 16)   */
+#define TT_UCR_PRIVATE_USE_SUPPLEMENTARY       (1L << 26) /*U+F0000-U+FFFFD*/
+                                                        /*U+100000-U+10FFFD*/
+  /* Bit 91   Variation Selectors */
+#define TT_UCR_VARIATION_SELECTORS             (1L << 27) /* U+FE00-U+FE0F */
+  /* Bit 92   Tags */
+#define TT_UCR_TAGS                            (1L << 28) /*U+E0000-U+E007F*/
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* Some compilers have a very limited length of identifiers.             */
+  /*                                                                       */
+#if defined( __TURBOC__ ) && __TURBOC__ < 0x0410 || defined( __PACIFIC__ )
+#define HAVE_LIMIT_ON_IDENTS
+#endif
+
+
+#ifndef HAVE_LIMIT_ON_IDENTS
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* Here some alias #defines in order to be clearer.                      */
+  /*                                                                       */
+  /* These are not always #defined to stay within the 31 character limit   */
+  /* which some compilers have.                                            */
+  /*                                                                       */
+  /* Credits go to Dave Hoo <[email protected]> for pointing out that modern  */
+  /* Borland compilers (read: from BC++ 3.1 on) can increase this limit.   */
+  /* If you get a warning with such a compiler, use the -i40 switch.       */
+  /*                                                                       */
+#define TT_UCR_ARABIC_PRESENTATION_FORMS_A      \
+         TT_UCR_ARABIC_PRESENTATIONS_A
+#define TT_UCR_ARABIC_PRESENTATION_FORMS_B      \
+         TT_UCR_ARABIC_PRESENTATIONS_B
+
+#define TT_UCR_COMBINING_DIACRITICAL_MARKS      \
+         TT_UCR_COMBINING_DIACRITICS
+#define TT_UCR_COMBINING_DIACRITICAL_MARKS_SYMB \
+         TT_UCR_COMBINING_DIACRITICS_SYMB
+
+
+#endif /* !HAVE_LIMIT_ON_IDENTS */
+
+
+FT_END_HEADER
+
+#endif /* __TTNAMEID_H__ */
+
+
+/* END */

+ 756 - 0
include/freetype/tttables.h

@@ -0,0 +1,756 @@
+/***************************************************************************/
+/*                                                                         */
+/*  tttables.h                                                             */
+/*                                                                         */
+/*    Basic SFNT/TrueType tables definitions and interface                 */
+/*    (specification only).                                                */
+/*                                                                         */
+/*  Copyright 1996-2001, 2002, 2003, 2004, 2005 by                         */
+/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */
+/*                                                                         */
+/*  This file is part of the FreeType project, and may only be used,       */
+/*  modified, and distributed under the terms of the FreeType project      */
+/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */
+/*  this file you indicate that you have read the license and              */
+/*  understand and accept it fully.                                        */
+/*                                                                         */
+/***************************************************************************/
+
+
+#ifndef __TTTABLES_H__
+#define __TTTABLES_H__
+
+
+#include <ft2build.h>
+#include FT_FREETYPE_H
+
+#ifdef FREETYPE_H
+#error "freetype.h of FreeType 1 has been loaded!"
+#error "Please fix the directory search order for header files"
+#error "so that freetype.h of FreeType 2 is found first."
+#endif
+
+
+FT_BEGIN_HEADER
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Section>                                                             */
+  /*    truetype_tables                                                    */
+  /*                                                                       */
+  /* <Title>                                                               */
+  /*    TrueType Tables                                                    */
+  /*                                                                       */
+  /* <Abstract>                                                            */
+  /*    TrueType specific table types and functions.                       */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    This section contains the definition of TrueType-specific tables   */
+  /*    as well as some routines used to access and process them.          */
+  /*                                                                       */
+  /*************************************************************************/
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Struct>                                                              */
+  /*    TT_Header                                                          */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    A structure used to model a TrueType font header table.  All       */
+  /*    fields follow the TrueType specification.                          */
+  /*                                                                       */
+  typedef struct  TT_Header_
+  {
+    FT_Fixed   Table_Version;
+    FT_Fixed   Font_Revision;
+
+    FT_Long    CheckSum_Adjust;
+    FT_Long    Magic_Number;
+
+    FT_UShort  Flags;
+    FT_UShort  Units_Per_EM;
+
+    FT_Long    Created [2];
+    FT_Long    Modified[2];
+
+    FT_Short   xMin;
+    FT_Short   yMin;
+    FT_Short   xMax;
+    FT_Short   yMax;
+
+    FT_UShort  Mac_Style;
+    FT_UShort  Lowest_Rec_PPEM;
+
+    FT_Short   Font_Direction;
+    FT_Short   Index_To_Loc_Format;
+    FT_Short   Glyph_Data_Format;
+
+  } TT_Header;
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Struct>                                                              */
+  /*    TT_HoriHeader                                                      */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    A structure used to model a TrueType horizontal header, the `hhea' */
+  /*    table, as well as the corresponding horizontal metrics table,      */
+  /*    i.e., the `hmtx' table.                                            */
+  /*                                                                       */
+  /* <Fields>                                                              */
+  /*    Version                :: The table version.                       */
+  /*                                                                       */
+  /*    Ascender               :: The font's ascender, i.e., the distance  */
+  /*                              from the baseline to the top-most of all */
+  /*                              glyph points found in the font.          */
+  /*                                                                       */
+  /*                              This value is invalid in many fonts, as  */
+  /*                              it is usually set by the font designer,  */
+  /*                              and often reflects only a portion of the */
+  /*                              glyphs found in the font (maybe ASCII).  */
+  /*                                                                       */
+  /*                              You should use the `sTypoAscender' field */
+  /*                              of the OS/2 table instead if you want    */
+  /*                              the correct one.                         */
+  /*                                                                       */
+  /*    Descender              :: The font's descender, i.e., the distance */
+  /*                              from the baseline to the bottom-most of  */
+  /*                              all glyph points found in the font.  It  */
+  /*                              is negative.                             */
+  /*                                                                       */
+  /*                              This value is invalid in many fonts, as  */
+  /*                              it is usually set by the font designer,  */
+  /*                              and often reflects only a portion of the */
+  /*                              glyphs found in the font (maybe ASCII).  */
+  /*                                                                       */
+  /*                              You should use the `sTypoDescender'      */
+  /*                              field of the OS/2 table instead if you   */
+  /*                              want the correct one.                    */
+  /*                                                                       */
+  /*    Line_Gap               :: The font's line gap, i.e., the distance  */
+  /*                              to add to the ascender and descender to  */
+  /*                              get the BTB, i.e., the                   */
+  /*                              baseline-to-baseline distance for the    */
+  /*                              font.                                    */
+  /*                                                                       */
+  /*    advance_Width_Max      :: This field is the maximum of all advance */
+  /*                              widths found in the font.  It can be     */
+  /*                              used to compute the maximum width of an  */
+  /*                              arbitrary string of text.                */
+  /*                                                                       */
+  /*    min_Left_Side_Bearing  :: The minimum left side bearing of all     */
+  /*                              glyphs within the font.                  */
+  /*                                                                       */
+  /*    min_Right_Side_Bearing :: The minimum right side bearing of all    */
+  /*                              glyphs within the font.                  */
+  /*                                                                       */
+  /*    xMax_Extent            :: The maximum horizontal extent (i.e., the */
+  /*                              `width' of a glyph's bounding box) for   */
+  /*                              all glyphs in the font.                  */
+  /*                                                                       */
+  /*    caret_Slope_Rise       :: The rise coefficient of the cursor's     */
+  /*                              slope of the cursor (slope=rise/run).    */
+  /*                                                                       */
+  /*    caret_Slope_Run        :: The run coefficient of the cursor's      */
+  /*                              slope.                                   */
+  /*                                                                       */
+  /*    Reserved               :: 10 reserved bytes.                       */
+  /*                                                                       */
+  /*    metric_Data_Format     :: Always 0.                                */
+  /*                                                                       */
+  /*    number_Of_HMetrics     :: Number of HMetrics entries in the `hmtx' */
+  /*                              table -- this value can be smaller than  */
+  /*                              the total number of glyphs in the font.  */
+  /*                                                                       */
+  /*    long_metrics           :: A pointer into the `hmtx' table.         */
+  /*                                                                       */
+  /*    short_metrics          :: A pointer into the `hmtx' table.         */
+  /*                                                                       */
+  /* <Note>                                                                */
+  /*    IMPORTANT: The TT_HoriHeader and TT_VertHeader structures should   */
+  /*               be identical except for the names of their fields which */
+  /*               are different.                                          */
+  /*                                                                       */
+  /*               This ensures that a single function in the `ttload'     */
+  /*               module is able to read both the horizontal and vertical */
+  /*               headers.                                                */
+  /*                                                                       */
+  typedef struct  TT_HoriHeader_
+  {
+    FT_Fixed   Version;
+    FT_Short   Ascender;
+    FT_Short   Descender;
+    FT_Short   Line_Gap;
+
+    FT_UShort  advance_Width_Max;      /* advance width maximum */
+
+    FT_Short   min_Left_Side_Bearing;  /* minimum left-sb       */
+    FT_Short   min_Right_Side_Bearing; /* minimum right-sb      */
+    FT_Short   xMax_Extent;            /* xmax extents          */
+    FT_Short   caret_Slope_Rise;
+    FT_Short   caret_Slope_Run;
+    FT_Short   caret_Offset;
+
+    FT_Short   Reserved[4];
+
+    FT_Short   metric_Data_Format;
+    FT_UShort  number_Of_HMetrics;
+
+    /* The following fields are not defined by the TrueType specification */
+    /* but they are used to connect the metrics header to the relevant    */
+    /* `HMTX' table.                                                      */
+
+    void*      long_metrics;
+    void*      short_metrics;
+
+  } TT_HoriHeader;
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Struct>                                                              */
+  /*    TT_VertHeader                                                      */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    A structure used to model a TrueType vertical header, the `vhea'   */
+  /*    table, as well as the corresponding vertical metrics table, i.e.,  */
+  /*    the `vmtx' table.                                                  */
+  /*                                                                       */
+  /* <Fields>                                                              */
+  /*    Version                 :: The table version.                      */
+  /*                                                                       */
+  /*    Ascender                :: The font's ascender, i.e., the distance */
+  /*                               from the baseline to the top-most of    */
+  /*                               all glyph points found in the font.     */
+  /*                                                                       */
+  /*                               This value is invalid in many fonts, as */
+  /*                               it is usually set by the font designer, */
+  /*                               and often reflects only a portion of    */
+  /*                               the glyphs found in the font (maybe     */
+  /*                               ASCII).                                 */
+  /*                                                                       */
+  /*                               You should use the `sTypoAscender'      */
+  /*                               field of the OS/2 table instead if you  */
+  /*                               want the correct one.                   */
+  /*                                                                       */
+  /*    Descender               :: The font's descender, i.e., the         */
+  /*                               distance from the baseline to the       */
+  /*                               bottom-most of all glyph points found   */
+  /*                               in the font.  It is negative.           */
+  /*                                                                       */
+  /*                               This value is invalid in many fonts, as */
+  /*                               it is usually set by the font designer, */
+  /*                               and often reflects only a portion of    */
+  /*                               the glyphs found in the font (maybe     */
+  /*                               ASCII).                                 */
+  /*                                                                       */
+  /*                               You should use the `sTypoDescender'     */
+  /*                               field of the OS/2 table instead if you  */
+  /*                               want the correct one.                   */
+  /*                                                                       */
+  /*    Line_Gap                :: The font's line gap, i.e., the distance */
+  /*                               to add to the ascender and descender to */
+  /*                               get the BTB, i.e., the                  */
+  /*                               baseline-to-baseline distance for the   */
+  /*                               font.                                   */
+  /*                                                                       */
+  /*    advance_Height_Max      :: This field is the maximum of all        */
+  /*                               advance heights found in the font.  It  */
+  /*                               can be used to compute the maximum      */
+  /*                               height of an arbitrary string of text.  */
+  /*                                                                       */
+  /*    min_Top_Side_Bearing    :: The minimum top side bearing of all     */
+  /*                               glyphs within the font.                 */
+  /*                                                                       */
+  /*    min_Bottom_Side_Bearing :: The minimum bottom side bearing of all  */
+  /*                               glyphs within the font.                 */
+  /*                                                                       */
+  /*    yMax_Extent             :: The maximum vertical extent (i.e., the  */
+  /*                               `height' of a glyph's bounding box) for */
+  /*                               all glyphs in the font.                 */
+  /*                                                                       */
+  /*    caret_Slope_Rise        :: The rise coefficient of the cursor's    */
+  /*                               slope of the cursor (slope=rise/run).   */
+  /*                                                                       */
+  /*    caret_Slope_Run         :: The run coefficient of the cursor's     */
+  /*                               slope.                                  */
+  /*                                                                       */
+  /*    caret_Offset            :: The cursor's offset for slanted fonts.  */
+  /*                               This value is `reserved' in vmtx        */
+  /*                               version 1.0.                            */
+  /*                                                                       */
+  /*    Reserved                :: 8 reserved bytes.                       */
+  /*                                                                       */
+  /*    metric_Data_Format      :: Always 0.                               */
+  /*                                                                       */
+  /*    number_Of_HMetrics      :: Number of VMetrics entries in the       */
+  /*                               `vmtx' table -- this value can be       */
+  /*                               smaller than the total number of glyphs */
+  /*                               in the font.                            */
+  /*                                                                       */
+  /*    long_metrics           :: A pointer into the `vmtx' table.         */
+  /*                                                                       */
+  /*    short_metrics          :: A pointer into the `vmtx' table.         */
+  /*                                                                       */
+  /* <Note>                                                                */
+  /*    IMPORTANT: The TT_HoriHeader and TT_VertHeader structures should   */
+  /*               be identical except for the names of their fields which */
+  /*               are different.                                          */
+  /*                                                                       */
+  /*               This ensures that a single function in the `ttload'     */
+  /*               module is able to read both the horizontal and vertical */
+  /*               headers.                                                */
+  /*                                                                       */
+  typedef struct  TT_VertHeader_
+  {
+    FT_Fixed   Version;
+    FT_Short   Ascender;
+    FT_Short   Descender;
+    FT_Short   Line_Gap;
+
+    FT_UShort  advance_Height_Max;      /* advance height maximum */
+
+    FT_Short   min_Top_Side_Bearing;    /* minimum left-sb or top-sb       */
+    FT_Short   min_Bottom_Side_Bearing; /* minimum right-sb or bottom-sb   */
+    FT_Short   yMax_Extent;             /* xmax or ymax extents            */
+    FT_Short   caret_Slope_Rise;
+    FT_Short   caret_Slope_Run;
+    FT_Short   caret_Offset;
+
+    FT_Short   Reserved[4];
+
+    FT_Short   metric_Data_Format;
+    FT_UShort  number_Of_VMetrics;
+
+    /* The following fields are not defined by the TrueType specification */
+    /* but they're used to connect the metrics header to the relevant     */
+    /* `HMTX' or `VMTX' table.                                            */
+
+    void*      long_metrics;
+    void*      short_metrics;
+
+  } TT_VertHeader;
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Struct>                                                              */
+  /*    TT_OS2                                                             */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    A structure used to model a TrueType OS/2 table. This is the long  */
+  /*    table version.  All fields comply to the TrueType specification.   */
+  /*                                                                       */
+  /*    Note that we now support old Mac fonts which do not include an     */
+  /*    OS/2 table.  In this case, the `version' field is always set to    */
+  /*    0xFFFF.                                                            */
+  /*                                                                       */
+  typedef struct  TT_OS2_
+  {
+    FT_UShort  version;                /* 0x0001 - more or 0xFFFF */
+    FT_Short   xAvgCharWidth;
+    FT_UShort  usWeightClass;
+    FT_UShort  usWidthClass;
+    FT_Short   fsType;
+    FT_Short   ySubscriptXSize;
+    FT_Short   ySubscriptYSize;
+    FT_Short   ySubscriptXOffset;
+    FT_Short   ySubscriptYOffset;
+    FT_Short   ySuperscriptXSize;
+    FT_Short   ySuperscriptYSize;
+    FT_Short   ySuperscriptXOffset;
+    FT_Short   ySuperscriptYOffset;
+    FT_Short   yStrikeoutSize;
+    FT_Short   yStrikeoutPosition;
+    FT_Short   sFamilyClass;
+
+    FT_Byte    panose[10];
+
+    FT_ULong   ulUnicodeRange1;        /* Bits 0-31   */
+    FT_ULong   ulUnicodeRange2;        /* Bits 32-63  */
+    FT_ULong   ulUnicodeRange3;        /* Bits 64-95  */
+    FT_ULong   ulUnicodeRange4;        /* Bits 96-127 */
+
+    FT_Char    achVendID[4];
+
+    FT_UShort  fsSelection;
+    FT_UShort  usFirstCharIndex;
+    FT_UShort  usLastCharIndex;
+    FT_Short   sTypoAscender;
+    FT_Short   sTypoDescender;
+    FT_Short   sTypoLineGap;
+    FT_UShort  usWinAscent;
+    FT_UShort  usWinDescent;
+
+    /* only version 1 tables: */
+
+    FT_ULong   ulCodePageRange1;       /* Bits 0-31   */
+    FT_ULong   ulCodePageRange2;       /* Bits 32-63  */
+
+    /* only version 2 tables: */
+
+    FT_Short   sxHeight;
+    FT_Short   sCapHeight;
+    FT_UShort  usDefaultChar;
+    FT_UShort  usBreakChar;
+    FT_UShort  usMaxContext;
+
+  } TT_OS2;
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Struct>                                                              */
+  /*    TT_Postscript                                                      */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    A structure used to model a TrueType Postscript table.  All fields */
+  /*    comply to the TrueType specification.  This structure does not     */
+  /*    reference the Postscript glyph names, which can be nevertheless    */
+  /*    accessed with the `ttpost' module.                                 */
+  /*                                                                       */
+  typedef struct  TT_Postscript_
+  {
+    FT_Fixed  FormatType;
+    FT_Fixed  italicAngle;
+    FT_Short  underlinePosition;
+    FT_Short  underlineThickness;
+    FT_ULong  isFixedPitch;
+    FT_ULong  minMemType42;
+    FT_ULong  maxMemType42;
+    FT_ULong  minMemType1;
+    FT_ULong  maxMemType1;
+
+    /* Glyph names follow in the file, but we don't   */
+    /* load them by default.  See the ttpost.c file.  */
+
+  } TT_Postscript;
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Struct>                                                              */
+  /*    TT_PCLT                                                            */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    A structure used to model a TrueType PCLT table.  All fields       */
+  /*    comply to the TrueType specification.                              */
+  /*                                                                       */
+  typedef struct  TT_PCLT_
+  {
+    FT_Fixed   Version;
+    FT_ULong   FontNumber;
+    FT_UShort  Pitch;
+    FT_UShort  xHeight;
+    FT_UShort  Style;
+    FT_UShort  TypeFamily;
+    FT_UShort  CapHeight;
+    FT_UShort  SymbolSet;
+    FT_Char    TypeFace[16];
+    FT_Char    CharacterComplement[8];
+    FT_Char    FileName[6];
+    FT_Char    StrokeWeight;
+    FT_Char    WidthType;
+    FT_Byte    SerifStyle;
+    FT_Byte    Reserved;
+
+  } TT_PCLT;
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Struct>                                                              */
+  /*    TT_MaxProfile                                                      */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    The maximum profile is a table containing many max values which    */
+  /*    can be used to pre-allocate arrays.  This ensures that no memory   */
+  /*    allocation occurs during a glyph load.                             */
+  /*                                                                       */
+  /* <Fields>                                                              */
+  /*    version               :: The version number.                       */
+  /*                                                                       */
+  /*    numGlyphs             :: The number of glyphs in this TrueType     */
+  /*                             font.                                     */
+  /*                                                                       */
+  /*    maxPoints             :: The maximum number of points in a         */
+  /*                             non-composite TrueType glyph.  See also   */
+  /*                             the structure element                     */
+  /*                             `maxCompositePoints'.                     */
+  /*                                                                       */
+  /*    maxContours           :: The maximum number of contours in a       */
+  /*                             non-composite TrueType glyph.  See also   */
+  /*                             the structure element                     */
+  /*                             `maxCompositeContours'.                   */
+  /*                                                                       */
+  /*    maxCompositePoints    :: The maximum number of points in a         */
+  /*                             composite TrueType glyph.  See also the   */
+  /*                             structure element `maxPoints'.            */
+  /*                                                                       */
+  /*    maxCompositeContours  :: The maximum number of contours in a       */
+  /*                             composite TrueType glyph.  See also the   */
+  /*                             structure element `maxContours'.          */
+  /*                                                                       */
+  /*    maxZones              :: The maximum number of zones used for      */
+  /*                             glyph hinting.                            */
+  /*                                                                       */
+  /*    maxTwilightPoints     :: The maximum number of points in the       */
+  /*                             twilight zone used for glyph hinting.     */
+  /*                                                                       */
+  /*    maxStorage            :: The maximum number of elements in the     */
+  /*                             storage area used for glyph hinting.      */
+  /*                                                                       */
+  /*    maxFunctionDefs       :: The maximum number of function            */
+  /*                             definitions in the TrueType bytecode for  */
+  /*                             this font.                                */
+  /*                                                                       */
+  /*    maxInstructionDefs    :: The maximum number of instruction         */
+  /*                             definitions in the TrueType bytecode for  */
+  /*                             this font.                                */
+  /*                                                                       */
+  /*    maxStackElements      :: The maximum number of stack elements used */
+  /*                             during bytecode interpretation.           */
+  /*                                                                       */
+  /*    maxSizeOfInstructions :: The maximum number of TrueType opcodes    */
+  /*                             used for glyph hinting.                   */
+  /*                                                                       */
+  /*    maxComponentElements  :: The maximum number of simple (i.e., non-  */
+  /*                             composite) glyphs in a composite glyph.   */
+  /*                                                                       */
+  /*    maxComponentDepth     :: The maximum nesting depth of composite    */
+  /*                             glyphs.                                   */
+  /*                                                                       */
+  /* <Note>                                                                */
+  /*    This structure is only used during font loading.                   */
+  /*                                                                       */
+  typedef struct  TT_MaxProfile_
+  {
+    FT_Fixed   version;
+    FT_UShort  numGlyphs;
+    FT_UShort  maxPoints;
+    FT_UShort  maxContours;
+    FT_UShort  maxCompositePoints;
+    FT_UShort  maxCompositeContours;
+    FT_UShort  maxZones;
+    FT_UShort  maxTwilightPoints;
+    FT_UShort  maxStorage;
+    FT_UShort  maxFunctionDefs;
+    FT_UShort  maxInstructionDefs;
+    FT_UShort  maxStackElements;
+    FT_UShort  maxSizeOfInstructions;
+    FT_UShort  maxComponentElements;
+    FT_UShort  maxComponentDepth;
+
+  } TT_MaxProfile;
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Enum>                                                                */
+  /*    FT_Sfnt_Tag                                                        */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    An enumeration used to specify the index of an SFNT table.         */
+  /*    Used in the @FT_Get_Sfnt_Table API function.                       */
+  /*                                                                       */
+  typedef enum
+  {
+    ft_sfnt_head = 0,
+    ft_sfnt_maxp = 1,
+    ft_sfnt_os2  = 2,
+    ft_sfnt_hhea = 3,
+    ft_sfnt_vhea = 4,
+    ft_sfnt_post = 5,
+    ft_sfnt_pclt = 6,
+
+    sfnt_max   /* internal end mark */
+
+  } FT_Sfnt_Tag;
+
+  /* */
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FT_Get_Sfnt_Table                                                  */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    Returns a pointer to a given SFNT table within a face.             */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    face :: A handle to the source.                                    */
+  /*                                                                       */
+  /*    tag  :: The index of the SFNT table.                               */
+  /*                                                                       */
+  /* <Return>                                                              */
+  /*    A type-less pointer to the table.  This will be 0 in case of       */
+  /*    error, or if the corresponding table was not found *OR* loaded     */
+  /*    from the file.                                                     */
+  /*                                                                       */
+  /* <Note>                                                                */
+  /*    The table is owned by the face object and disappears with it.      */
+  /*                                                                       */
+  /*    This function is only useful to access SFNT tables that are loaded */
+  /*    by the sfnt, truetype, and opentype drivers.  See @FT_Sfnt_Tag for */
+  /*    a list.                                                            */
+  /*                                                                       */
+  FT_EXPORT( void* )
+  FT_Get_Sfnt_Table( FT_Face      face,
+                     FT_Sfnt_Tag  tag );
+
+
+ /**************************************************************************
+  *
+  * @function:
+  *   FT_Load_Sfnt_Table
+  *
+  * @description:
+  *   Loads any font table into client memory.
+  *
+  * @input:
+  *   face ::
+  *     A handle to the source face.
+  *
+  *   tag ::
+  *     The four-byte tag of the table to load.  Use the value 0 if you want
+  *     to access the whole font file.  Otherwise, you can use one of the
+  *     definitions found in the @FT_TRUETYPE_TAGS_H file, or forge a new
+  *     one with @FT_MAKE_TAG.
+  *
+  *   offset ::
+  *     The starting offset in the table (or file if tag == 0).
+  *
+  * @output:
+  *   buffer ::
+  *     The target buffer address.  The client must ensure that the memory
+  *     array is big enough to hold the data.
+  *
+  * @inout:
+  *   length ::
+  *     If the `length' parameter is NULL, then try to load the whole table.
+  *     Return an error code if it fails.
+  *
+  *     Else, if `*length' is 0, exit immediately while returning the
+  *     table's (or file) full size in it.
+  *
+  *     Else the number of bytes to read from the table or file, from the
+  *     starting offset.
+  *
+  * @return:
+  *   FreeType error code.  0 means success.
+  *
+  * @note:
+  *   If you need to determine the table's length you should first call this
+  *   function with `*length' set to 0, as in the following example:
+  *
+  *     {
+  *       FT_ULong  length = 0;
+  *
+  *
+  *       error = FT_Load_Sfnt_Table( face, tag, 0, NULL, &length );
+  *       if ( error ) { ... table does not exist ... }
+  *
+  *       buffer = malloc( length );
+  *       if ( buffer == NULL ) { ... not enough memory ... }
+  *
+  *       error = FT_Load_Sfnt_Table( face, tag, 0, buffer, &length );
+  *       if ( error ) { ... could not load table ... }
+  *     }
+  */
+  FT_EXPORT( FT_Error )
+  FT_Load_Sfnt_Table( FT_Face    face,
+                      FT_ULong   tag,
+                      FT_Long    offset,
+                      FT_Byte*   buffer,
+                      FT_ULong*  length );
+
+
+ /**************************************************************************
+  *
+  * @function:
+  *   FT_Sfnt_Table_Info
+  *
+  * @description:
+  *   Returns information on an SFNT table.
+  *
+  * @input:
+  *   face ::
+  *     A handle to the source face.
+  *
+  *   table_index ::
+  *     The index of an SFNT table.  The function returns
+  *     FT_Err_Table_Missing for an invalid value.
+  *
+  * @output:
+  *   tag ::
+  *     The name tag of the SFNT table.
+  *
+  *   length ::
+  *     The length of the SFNT table.
+  *
+  * @return:
+  *   FreeType error code.  0 means success.
+  *
+  * @note:
+  *   SFNT tables with length zero are treated as missing by Windows.
+  *
+  */
+  FT_EXPORT( FT_Error )
+  FT_Sfnt_Table_Info( FT_Face    face,
+                      FT_UInt    table_index,
+                      FT_ULong  *tag,
+                      FT_ULong  *length );
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FT_Get_CMap_Language_ID                                            */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    Return TrueType/sfnt specific cmap language ID.  Definitions of    */
+  /*    language ID values are in `freetype/ttnameid.h'.                   */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    charmap ::                                                         */
+  /*      The target charmap.                                              */
+  /*                                                                       */
+  /* <Return>                                                              */
+  /*    The language ID of `charmap'.  If `charmap' doesn't belong to a    */
+  /*    TrueType/sfnt face, just return 0 as the default value.            */
+  /*                                                                       */
+  FT_EXPORT( FT_ULong )
+  FT_Get_CMap_Language_ID( FT_CharMap  charmap );
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* <Function>                                                            */
+  /*    FT_Get_CMap_Format                                                 */
+  /*                                                                       */
+  /* <Description>                                                         */
+  /*    Return TrueType/sfnt specific cmap format.                         */
+  /*                                                                       */
+  /* <Input>                                                               */
+  /*    charmap ::                                                         */
+  /*      The target charmap.                                              */
+  /*                                                                       */
+  /* <Return>                                                              */
+  /*    The format of `charmap'.  If `charmap' doesn't belong to a         */
+  /*    TrueType/sfnt face, return -1.                                     */
+  /*                                                                       */
+  FT_EXPORT( FT_Long )
+  FT_Get_CMap_Format( FT_CharMap  charmap );
+
+  /* */
+
+
+FT_END_HEADER
+
+#endif /* __TTTABLES_H__ */
+
+
+/* END */

+ 99 - 0
include/freetype/tttags.h

@@ -0,0 +1,99 @@
+/***************************************************************************/
+/*                                                                         */
+/*  tttags.h                                                               */
+/*                                                                         */
+/*    Tags for TrueType and OpenType tables (specification only).          */
+/*                                                                         */
+/*  Copyright 1996-2001, 2004, 2005 by                                     */
+/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */
+/*                                                                         */
+/*  This file is part of the FreeType project, and may only be used,       */
+/*  modified, and distributed under the terms of the FreeType project      */
+/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */
+/*  this file you indicate that you have read the license and              */
+/*  understand and accept it fully.                                        */
+/*                                                                         */
+/***************************************************************************/
+
+
+#ifndef __TTAGS_H__
+#define __TTAGS_H__
+
+
+#include <ft2build.h>
+#include FT_FREETYPE_H
+
+#ifdef FREETYPE_H
+#error "freetype.h of FreeType 1 has been loaded!"
+#error "Please fix the directory search order for header files"
+#error "so that freetype.h of FreeType 2 is found first."
+#endif
+
+
+FT_BEGIN_HEADER
+
+
+#define TTAG_avar  FT_MAKE_TAG( 'a', 'v', 'a', 'r' )
+#define TTAG_BASE  FT_MAKE_TAG( 'B', 'A', 'S', 'E' )
+#define TTAG_bdat  FT_MAKE_TAG( 'b', 'd', 'a', 't' )
+#define TTAG_BDF   FT_MAKE_TAG( 'B', 'D', 'F', ' ' )
+#define TTAG_bhed  FT_MAKE_TAG( 'b', 'h', 'e', 'd' )
+#define TTAG_bloc  FT_MAKE_TAG( 'b', 'l', 'o', 'c' )
+#define TTAG_bsln  FT_MAKE_TAG( 'b', 's', 'l', 'n' )
+#define TTAG_CFF   FT_MAKE_TAG( 'C', 'F', 'F', ' ' )
+#define TTAG_cmap  FT_MAKE_TAG( 'c', 'm', 'a', 'p' )
+#define TTAG_cvar  FT_MAKE_TAG( 'c', 'v', 'a', 'r' )
+#define TTAG_cvt   FT_MAKE_TAG( 'c', 'v', 't', ' ' )
+#define TTAG_DSIG  FT_MAKE_TAG( 'D', 'S', 'I', 'G' )
+#define TTAG_EBDT  FT_MAKE_TAG( 'E', 'B', 'D', 'T' )
+#define TTAG_EBLC  FT_MAKE_TAG( 'E', 'B', 'L', 'C' )
+#define TTAG_EBSC  FT_MAKE_TAG( 'E', 'B', 'S', 'C' )
+#define TTAG_feat  FT_MAKE_TAG( 'f', 'e', 'a', 't' )
+#define TTAG_fpgm  FT_MAKE_TAG( 'f', 'p', 'g', 'm' )
+#define TTAG_fvar  FT_MAKE_TAG( 'f', 'v', 'a', 'r' )
+#define TTAG_gasp  FT_MAKE_TAG( 'g', 'a', 's', 'p' )
+#define TTAG_GDEF  FT_MAKE_TAG( 'G', 'D', 'E', 'F' )
+#define TTAG_glyf  FT_MAKE_TAG( 'g', 'l', 'y', 'f' )
+#define TTAG_GPOS  FT_MAKE_TAG( 'G', 'P', 'O', 'S' )
+#define TTAG_GSUB  FT_MAKE_TAG( 'G', 'S', 'U', 'B' )
+#define TTAG_gvar  FT_MAKE_TAG( 'g', 'v', 'a', 'r' )
+#define TTAG_hdmx  FT_MAKE_TAG( 'h', 'd', 'm', 'x' )
+#define TTAG_head  FT_MAKE_TAG( 'h', 'e', 'a', 'd' )
+#define TTAG_hhea  FT_MAKE_TAG( 'h', 'h', 'e', 'a' )
+#define TTAG_hmtx  FT_MAKE_TAG( 'h', 'm', 't', 'x' )
+#define TTAG_JSTF  FT_MAKE_TAG( 'J', 'S', 'T', 'F' )
+#define TTAG_just  FT_MAKE_TAG( 'j', 'u', 's', 't' )
+#define TTAG_kern  FT_MAKE_TAG( 'k', 'e', 'r', 'n' )
+#define TTAG_lcar  FT_MAKE_TAG( 'l', 'c', 'a', 'r' )
+#define TTAG_loca  FT_MAKE_TAG( 'l', 'o', 'c', 'a' )
+#define TTAG_LTSH  FT_MAKE_TAG( 'L', 'T', 'S', 'H' )
+#define TTAG_maxp  FT_MAKE_TAG( 'm', 'a', 'x', 'p' )
+#define TTAG_META  FT_MAKE_TAG( 'M', 'E', 'T', 'A' )
+#define TTAG_MMFX  FT_MAKE_TAG( 'M', 'M', 'F', 'X' )
+#define TTAG_MMSD  FT_MAKE_TAG( 'M', 'M', 'S', 'D' )
+#define TTAG_mort  FT_MAKE_TAG( 'm', 'o', 'r', 't' )
+#define TTAG_morx  FT_MAKE_TAG( 'm', 'o', 'r', 'x' )
+#define TTAG_name  FT_MAKE_TAG( 'n', 'a', 'm', 'e' )
+#define TTAG_opbd  FT_MAKE_TAG( 'o', 'p', 'b', 'd' )
+#define TTAG_OS2   FT_MAKE_TAG( 'O', 'S', '/', '2' )
+#define TTAG_OTTO  FT_MAKE_TAG( 'O', 'T', 'T', 'O' )
+#define TTAG_PCLT  FT_MAKE_TAG( 'P', 'C', 'L', 'T' )
+#define TTAG_post  FT_MAKE_TAG( 'p', 'o', 's', 't' )
+#define TTAG_prep  FT_MAKE_TAG( 'p', 'r', 'e', 'p' )
+#define TTAG_prop  FT_MAKE_TAG( 'p', 'r', 'o', 'p' )
+#define TTAG_SING  FT_MAKE_TAG( 'S', 'I', 'N', 'G' )
+#define TTAG_trak  FT_MAKE_TAG( 't', 'r', 'a', 'k' )
+#define TTAG_true  FT_MAKE_TAG( 't', 'r', 'u', 'e' )
+#define TTAG_ttc   FT_MAKE_TAG( 't', 't', 'c', ' ' )
+#define TTAG_ttcf  FT_MAKE_TAG( 't', 't', 'c', 'f' )
+#define TTAG_VDMX  FT_MAKE_TAG( 'V', 'D', 'M', 'X' )
+#define TTAG_vhea  FT_MAKE_TAG( 'v', 'h', 'e', 'a' )
+#define TTAG_vmtx  FT_MAKE_TAG( 'v', 'm', 't', 'x' )
+
+
+FT_END_HEADER
+
+#endif /* __TTAGS_H__ */
+
+
+/* END */

+ 59 - 0
include/freetype/ttunpat.h

@@ -0,0 +1,59 @@
+/***************************************************************************/
+/*                                                                         */
+/*  ttunpat.h                                                              */
+/*                                                                         */
+/*    Definitions for the unpatented TrueType hinting system               */
+/*                                                                         */
+/*  Copyright 2003, 2006 by                                                */
+/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */
+/*                                                                         */
+/*  Written by Graham Asher <[email protected]>                  */
+/*                                                                         */
+/*  This file is part of the FreeType project, and may only be used,       */
+/*  modified, and distributed under the terms of the FreeType project      */
+/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */
+/*  this file you indicate that you have read the license and              */
+/*  understand and accept it fully.                                        */
+/*                                                                         */
+/***************************************************************************/
+
+
+#ifndef __TTUNPAT_H__
+#define __TTUNPAT_H__
+
+
+#include <ft2build.h>
+#include FT_FREETYPE_H
+
+#ifdef FREETYPE_H
+#error "freetype.h of FreeType 1 has been loaded!"
+#error "Please fix the directory search order for header files"
+#error "so that freetype.h of FreeType 2 is found first."
+#endif
+
+
+FT_BEGIN_HEADER
+
+
+ /***************************************************************************
+  *
+  * @constant:
+  *   FT_PARAM_TAG_UNPATENTED_HINTING
+  *
+  * @description:
+  *   A constant used as the tag of an @FT_Parameter structure to indicate
+  *   that unpatented methods only should be used by the TrueType bytecode
+  *   interpreter for a typeface opened by @FT_Open_Face.
+  *
+  */
+#define FT_PARAM_TAG_UNPATENTED_HINTING  FT_MAKE_TAG( 'u', 'n', 'p', 'a' )
+
+ /* */
+
+FT_END_HEADER
+
+
+#endif /* __TTUNPAT_H__ */
+
+
+/* END */

+ 61 - 0
include/ft2build.h

@@ -0,0 +1,61 @@
+/***************************************************************************/
+/*                                                                         */
+/*  ft2build.h                                                             */
+/*                                                                         */
+/*    Build macros of the FreeType 2 library.                              */
+/*                                                                         */
+/*  Copyright 1996-2001, 2003, 2006 by                                     */
+/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */
+/*                                                                         */
+/*  This file is part of the FreeType project, and may only be used,       */
+/*  modified, and distributed under the terms of the FreeType project      */
+/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */
+/*  this file you indicate that you have read the license and              */
+/*  understand and accept it fully.                                        */
+/*                                                                         */
+/***************************************************************************/
+
+
+  /*************************************************************************/
+  /*                                                                       */
+  /* This is a Unix-specific version of <ft2build.h> that should be used   */
+  /* exclusively *after* installation of the library.                      */
+  /*                                                                       */
+  /* It assumes that `/usr/local/include/freetype2' (or whatever is        */
+  /* returned by the `freetype-config --cflags' or `pkg-config --cflags'   */
+  /* command) is in your compilation include path.                         */
+  /*                                                                       */
+  /* We don't need to do anything special in this release.  However, for   */
+  /* a future FreeType 2 release, the following installation changes will  */
+  /* be performed:                                                         */
+  /*                                                                       */
+  /*   - The contents of `freetype-2.x/include/freetype' will be installed */
+  /*     to `/usr/local/include/freetype2' instead of                      */
+  /*     `/usr/local/include/freetype2/freetype'.                          */
+  /*                                                                       */
+  /*   - This file will #include <freetype2/config/ftheader.h>, instead    */
+  /*     of <freetype/config/ftheader.h>.                                  */
+  /*                                                                       */
+  /*   - The contents of `ftheader.h' will be processed with `sed' to      */
+  /*     replace all `<freetype/xxx>' with `<freetype2/xxx>'.              */
+  /*                                                                       */
+  /*   - Adding `/usr/local/include/freetype2' to your compilation include */
+  /*     path will not be necessary anymore.                               */
+  /*                                                                       */
+  /* These changes will be transparent to client applications which use    */
+  /* freetype-config (or pkg-config).  No modifications will be necessary  */
+  /* to compile with the new scheme.                                       */
+  /*                                                                       */
+  /*************************************************************************/
+
+
+#ifndef __FT2_BUILD_UNIX_H__
+#define __FT2_BUILD_UNIX_H__
+
+  /* `<prefix>/include/freetype2' must be in your current inclusion path */
+#include <freetype/config/ftheader.h>
+
+#endif /* __FT2_BUILD_UNIX_H__ */
+
+
+/* END */

+ 1759 - 0
include/lodepng.h

@@ -0,0 +1,1759 @@
+/*
+LodePNG version 20160418
+
+Copyright (c) 2005-2016 Lode Vandevenne
+
+This software is provided 'as-is', without any express or implied
+warranty. In no event will the authors be held liable for any damages
+arising from the use of this software.
+
+Permission is granted to anyone to use this software for any purpose,
+including commercial applications, and to alter it and redistribute it
+freely, subject to the following restrictions:
+
+    1. The origin of this software must not be misrepresented; you must not
+    claim that you wrote the original software. If you use this software
+    in a product, an acknowledgment in the product documentation would be
+    appreciated but is not required.
+
+    2. Altered source versions must be plainly marked as such, and must not be
+    misrepresented as being the original software.
+
+    3. This notice may not be removed or altered from any source
+    distribution.
+*/
+
+#ifndef LODEPNG_H
+#define LODEPNG_H
+
+#include <string.h> /*for size_t*/
+
+extern const char* LODEPNG_VERSION_STRING;
+
+/*
+The following #defines are used to create code sections. They can be disabled
+to disable code sections, which can give faster compile time and smaller binary.
+The "NO_COMPILE" defines are designed to be used to pass as defines to the
+compiler command to disable them without modifying this header, e.g.
+-DLODEPNG_NO_COMPILE_ZLIB for gcc.
+In addition to those below, you can also define LODEPNG_NO_COMPILE_CRC to
+allow implementing a custom lodepng_crc32.
+*/
+/*deflate & zlib. If disabled, you must specify alternative zlib functions in
+the custom_zlib field of the compress and decompress settings*/
+#ifndef LODEPNG_NO_COMPILE_ZLIB
+#define LODEPNG_COMPILE_ZLIB
+#endif
+/*png encoder and png decoder*/
+#ifndef LODEPNG_NO_COMPILE_PNG
+#define LODEPNG_COMPILE_PNG
+#endif
+/*deflate&zlib decoder and png decoder*/
+#ifndef LODEPNG_NO_COMPILE_DECODER
+#define LODEPNG_COMPILE_DECODER
+#endif
+/*deflate&zlib encoder and png encoder*/
+#ifndef LODEPNG_NO_COMPILE_ENCODER
+#define LODEPNG_COMPILE_ENCODER
+#endif
+/*the optional built in harddisk file loading and saving functions*/
+#ifndef LODEPNG_NO_COMPILE_DISK
+#define LODEPNG_COMPILE_DISK
+#endif
+/*support for chunks other than IHDR, IDAT, PLTE, tRNS, IEND: ancillary and unknown chunks*/
+#ifndef LODEPNG_NO_COMPILE_ANCILLARY_CHUNKS
+#define LODEPNG_COMPILE_ANCILLARY_CHUNKS
+#endif
+/*ability to convert error numerical codes to English text string*/
+#ifndef LODEPNG_NO_COMPILE_ERROR_TEXT
+#define LODEPNG_COMPILE_ERROR_TEXT
+#endif
+/*Compile the default allocators (C's free, malloc and realloc). If you disable this,
+you can define the functions lodepng_free, lodepng_malloc and lodepng_realloc in your
+source files with custom allocators.*/
+#ifndef LODEPNG_NO_COMPILE_ALLOCATORS
+#define LODEPNG_COMPILE_ALLOCATORS
+#endif
+/*compile the C++ version (you can disable the C++ wrapper here even when compiling for C++)*/
+#ifdef __cplusplus
+#ifndef LODEPNG_NO_COMPILE_CPP
+#define LODEPNG_COMPILE_CPP
+#endif
+#endif
+
+#ifdef LODEPNG_COMPILE_CPP
+#include <vector>
+#include <string>
+#endif /*LODEPNG_COMPILE_CPP*/
+
+#ifdef LODEPNG_COMPILE_PNG
+/*The PNG color types (also used for raw).*/
+typedef enum LodePNGColorType
+{
+  LCT_GREY = 0, /*greyscale: 1,2,4,8,16 bit*/
+  LCT_RGB = 2, /*RGB: 8,16 bit*/
+  LCT_PALETTE = 3, /*palette: 1,2,4,8 bit*/
+  LCT_GREY_ALPHA = 4, /*greyscale with alpha: 8,16 bit*/
+  LCT_RGBA = 6 /*RGB with alpha: 8,16 bit*/
+} LodePNGColorType;
+
+#ifdef LODEPNG_COMPILE_DECODER
+/*
+Converts PNG data in memory to raw pixel data.
+out: Output parameter. Pointer to buffer that will contain the raw pixel data.
+     After decoding, its size is w * h * (bytes per pixel) bytes larger than
+     initially. Bytes per pixel depends on colortype and bitdepth.
+     Must be freed after usage with free(*out).
+     Note: for 16-bit per channel colors, uses big endian format like PNG does.
+w: Output parameter. Pointer to width of pixel data.
+h: Output parameter. Pointer to height of pixel data.
+in: Memory buffer with the PNG file.
+insize: size of the in buffer.
+colortype: the desired color type for the raw output image. See explanation on PNG color types.
+bitdepth: the desired bit depth for the raw output image. See explanation on PNG color types.
+Return value: LodePNG error code (0 means no error).
+*/
+unsigned lodepng_decode_memory(unsigned char** out, unsigned* w, unsigned* h,
+                               const unsigned char* in, size_t insize,
+                               LodePNGColorType colortype, unsigned bitdepth);
+
+/*Same as lodepng_decode_memory, but always decodes to 32-bit RGBA raw image*/
+unsigned lodepng_decode32(unsigned char** out, unsigned* w, unsigned* h,
+                          const unsigned char* in, size_t insize);
+
+/*Same as lodepng_decode_memory, but always decodes to 24-bit RGB raw image*/
+unsigned lodepng_decode24(unsigned char** out, unsigned* w, unsigned* h,
+                          const unsigned char* in, size_t insize);
+
+#ifdef LODEPNG_COMPILE_DISK
+/*
+Load PNG from disk, from file with given name.
+Same as the other decode functions, but instead takes a filename as input.
+*/
+unsigned lodepng_decode_file(unsigned char** out, unsigned* w, unsigned* h,
+                             const char* filename,
+                             LodePNGColorType colortype, unsigned bitdepth);
+
+/*Same as lodepng_decode_file, but always decodes to 32-bit RGBA raw image.*/
+unsigned lodepng_decode32_file(unsigned char** out, unsigned* w, unsigned* h,
+                               const char* filename);
+
+/*Same as lodepng_decode_file, but always decodes to 24-bit RGB raw image.*/
+unsigned lodepng_decode24_file(unsigned char** out, unsigned* w, unsigned* h,
+                               const char* filename);
+#endif /*LODEPNG_COMPILE_DISK*/
+#endif /*LODEPNG_COMPILE_DECODER*/
+
+
+#ifdef LODEPNG_COMPILE_ENCODER
+/*
+Converts raw pixel data into a PNG image in memory. The colortype and bitdepth
+  of the output PNG image cannot be chosen, they are automatically determined
+  by the colortype, bitdepth and content of the input pixel data.
+  Note: for 16-bit per channel colors, needs big endian format like PNG does.
+out: Output parameter. Pointer to buffer that will contain the PNG image data.
+     Must be freed after usage with free(*out).
+outsize: Output parameter. Pointer to the size in bytes of the out buffer.
+image: The raw pixel data to encode. The size of this buffer should be
+       w * h * (bytes per pixel), bytes per pixel depends on colortype and bitdepth.
+w: width of the raw pixel data in pixels.
+h: height of the raw pixel data in pixels.
+colortype: the color type of the raw input image. See explanation on PNG color types.
+bitdepth: the bit depth of the raw input image. See explanation on PNG color types.
+Return value: LodePNG error code (0 means no error).
+*/
+unsigned lodepng_encode_memory(unsigned char** out, size_t* outsize,
+                               const unsigned char* image, unsigned w, unsigned h,
+                               LodePNGColorType colortype, unsigned bitdepth);
+
+/*Same as lodepng_encode_memory, but always encodes from 32-bit RGBA raw image.*/
+unsigned lodepng_encode32(unsigned char** out, size_t* outsize,
+                          const unsigned char* image, unsigned w, unsigned h);
+
+/*Same as lodepng_encode_memory, but always encodes from 24-bit RGB raw image.*/
+unsigned lodepng_encode24(unsigned char** out, size_t* outsize,
+                          const unsigned char* image, unsigned w, unsigned h);
+
+#ifdef LODEPNG_COMPILE_DISK
+/*
+Converts raw pixel data into a PNG file on disk.
+Same as the other encode functions, but instead takes a filename as output.
+NOTE: This overwrites existing files without warning!
+*/
+unsigned lodepng_encode_file(const char* filename,
+                             const unsigned char* image, unsigned w, unsigned h,
+                             LodePNGColorType colortype, unsigned bitdepth);
+
+/*Same as lodepng_encode_file, but always encodes from 32-bit RGBA raw image.*/
+unsigned lodepng_encode32_file(const char* filename,
+                               const unsigned char* image, unsigned w, unsigned h);
+
+/*Same as lodepng_encode_file, but always encodes from 24-bit RGB raw image.*/
+unsigned lodepng_encode24_file(const char* filename,
+                               const unsigned char* image, unsigned w, unsigned h);
+#endif /*LODEPNG_COMPILE_DISK*/
+#endif /*LODEPNG_COMPILE_ENCODER*/
+
+
+#ifdef LODEPNG_COMPILE_CPP
+namespace lodepng
+{
+#ifdef LODEPNG_COMPILE_DECODER
+/*Same as lodepng_decode_memory, but decodes to an std::vector. The colortype
+is the format to output the pixels to. Default is RGBA 8-bit per channel.*/
+unsigned decode(std::vector<unsigned char>& out, unsigned& w, unsigned& h,
+                const unsigned char* in, size_t insize,
+                LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8);
+unsigned decode(std::vector<unsigned char>& out, unsigned& w, unsigned& h,
+                const std::vector<unsigned char>& in,
+                LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8);
+#ifdef LODEPNG_COMPILE_DISK
+/*
+Converts PNG file from disk to raw pixel data in memory.
+Same as the other decode functions, but instead takes a filename as input.
+*/
+unsigned decode(std::vector<unsigned char>& out, unsigned& w, unsigned& h,
+                const std::string& filename,
+                LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8);
+#endif /* LODEPNG_COMPILE_DISK */
+#endif /* LODEPNG_COMPILE_DECODER */
+
+#ifdef LODEPNG_COMPILE_ENCODER
+/*Same as lodepng_encode_memory, but encodes to an std::vector. colortype
+is that of the raw input data. The output PNG color type will be auto chosen.*/
+unsigned encode(std::vector<unsigned char>& out,
+                const unsigned char* in, unsigned w, unsigned h,
+                LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8);
+unsigned encode(std::vector<unsigned char>& out,
+                const std::vector<unsigned char>& in, unsigned w, unsigned h,
+                LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8);
+#ifdef LODEPNG_COMPILE_DISK
+/*
+Converts 32-bit RGBA raw pixel data into a PNG file on disk.
+Same as the other encode functions, but instead takes a filename as output.
+NOTE: This overwrites existing files without warning!
+*/
+unsigned encode(const std::string& filename,
+                const unsigned char* in, unsigned w, unsigned h,
+                LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8);
+unsigned encode(const std::string& filename,
+                const std::vector<unsigned char>& in, unsigned w, unsigned h,
+                LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8);
+#endif /* LODEPNG_COMPILE_DISK */
+#endif /* LODEPNG_COMPILE_ENCODER */
+} /* namespace lodepng */
+#endif /*LODEPNG_COMPILE_CPP*/
+#endif /*LODEPNG_COMPILE_PNG*/
+
+#ifdef LODEPNG_COMPILE_ERROR_TEXT
+/*Returns an English description of the numerical error code.*/
+const char* lodepng_error_text(unsigned code);
+#endif /*LODEPNG_COMPILE_ERROR_TEXT*/
+
+#ifdef LODEPNG_COMPILE_DECODER
+/*Settings for zlib decompression*/
+typedef struct LodePNGDecompressSettings LodePNGDecompressSettings;
+struct LodePNGDecompressSettings
+{
+  unsigned ignore_adler32; /*if 1, continue and don't give an error message if the Adler32 checksum is corrupted*/
+
+  /*use custom zlib decoder instead of built in one (default: null)*/
+  unsigned (*custom_zlib)(unsigned char**, size_t*,
+                          const unsigned char*, size_t,
+                          const LodePNGDecompressSettings*);
+  /*use custom deflate decoder instead of built in one (default: null)
+  if custom_zlib is used, custom_deflate is ignored since only the built in
+  zlib function will call custom_deflate*/
+  unsigned (*custom_inflate)(unsigned char**, size_t*,
+                             const unsigned char*, size_t,
+                             const LodePNGDecompressSettings*);
+
+  const void* custom_context; /*optional custom settings for custom functions*/
+};
+
+extern const LodePNGDecompressSettings lodepng_default_decompress_settings;
+void lodepng_decompress_settings_init(LodePNGDecompressSettings* settings);
+#endif /*LODEPNG_COMPILE_DECODER*/
+
+#ifdef LODEPNG_COMPILE_ENCODER
+/*
+Settings for zlib compression. Tweaking these settings tweaks the balance
+between speed and compression ratio.
+*/
+typedef struct LodePNGCompressSettings LodePNGCompressSettings;
+struct LodePNGCompressSettings /*deflate = compress*/
+{
+  /*LZ77 related settings*/
+  unsigned btype; /*the block type for LZ (0, 1, 2 or 3, see zlib standard). Should be 2 for proper compression.*/
+  unsigned use_lz77; /*whether or not to use LZ77. Should be 1 for proper compression.*/
+  unsigned windowsize; /*must be a power of two <= 32768. higher compresses more but is slower. Default value: 2048.*/
+  unsigned minmatch; /*mininum lz77 length. 3 is normally best, 6 can be better for some PNGs. Default: 0*/
+  unsigned nicematch; /*stop searching if >= this length found. Set to 258 for best compression. Default: 128*/
+  unsigned lazymatching; /*use lazy matching: better compression but a bit slower. Default: true*/
+
+  /*use custom zlib encoder instead of built in one (default: null)*/
+  unsigned (*custom_zlib)(unsigned char**, size_t*,
+                          const unsigned char*, size_t,
+                          const LodePNGCompressSettings*);
+  /*use custom deflate encoder instead of built in one (default: null)
+  if custom_zlib is used, custom_deflate is ignored since only the built in
+  zlib function will call custom_deflate*/
+  unsigned (*custom_deflate)(unsigned char**, size_t*,
+                             const unsigned char*, size_t,
+                             const LodePNGCompressSettings*);
+
+  const void* custom_context; /*optional custom settings for custom functions*/
+};
+
+extern const LodePNGCompressSettings lodepng_default_compress_settings;
+void lodepng_compress_settings_init(LodePNGCompressSettings* settings);
+#endif /*LODEPNG_COMPILE_ENCODER*/
+
+#ifdef LODEPNG_COMPILE_PNG
+/*
+Color mode of an image. Contains all information required to decode the pixel
+bits to RGBA colors. This information is the same as used in the PNG file
+format, and is used both for PNG and raw image data in LodePNG.
+*/
+typedef struct LodePNGColorMode
+{
+  /*header (IHDR)*/
+  LodePNGColorType colortype; /*color type, see PNG standard or documentation further in this header file*/
+  unsigned bitdepth;  /*bits per sample, see PNG standard or documentation further in this header file*/
+
+  /*
+  palette (PLTE and tRNS)
+
+  Dynamically allocated with the colors of the palette, including alpha.
+  When encoding a PNG, to store your colors in the palette of the LodePNGColorMode, first use
+  lodepng_palette_clear, then for each color use lodepng_palette_add.
+  If you encode an image without alpha with palette, don't forget to put value 255 in each A byte of the palette.
+
+  When decoding, by default you can ignore this palette, since LodePNG already
+  fills the palette colors in the pixels of the raw RGBA output.
+
+  The palette is only supported for color type 3.
+  */
+  unsigned char* palette; /*palette in RGBARGBA... order. When allocated, must be either 0, or have size 1024*/
+  size_t palettesize; /*palette size in number of colors (amount of bytes is 4 * palettesize)*/
+
+  /*
+  transparent color key (tRNS)
+
+  This color uses the same bit depth as the bitdepth value in this struct, which can be 1-bit to 16-bit.
+  For greyscale PNGs, r, g and b will all 3 be set to the same.
+
+  When decoding, by default you can ignore this information, since LodePNG sets
+  pixels with this key to transparent already in the raw RGBA output.
+
+  The color key is only supported for color types 0 and 2.
+  */
+  unsigned key_defined; /*is a transparent color key given? 0 = false, 1 = true*/
+  unsigned key_r;       /*red/greyscale component of color key*/
+  unsigned key_g;       /*green component of color key*/
+  unsigned key_b;       /*blue component of color key*/
+} LodePNGColorMode;
+
+/*init, cleanup and copy functions to use with this struct*/
+void lodepng_color_mode_init(LodePNGColorMode* info);
+void lodepng_color_mode_cleanup(LodePNGColorMode* info);
+/*return value is error code (0 means no error)*/
+unsigned lodepng_color_mode_copy(LodePNGColorMode* dest, const LodePNGColorMode* source);
+
+void lodepng_palette_clear(LodePNGColorMode* info);
+/*add 1 color to the palette*/
+unsigned lodepng_palette_add(LodePNGColorMode* info,
+                             unsigned char r, unsigned char g, unsigned char b, unsigned char a);
+
+/*get the total amount of bits per pixel, based on colortype and bitdepth in the struct*/
+unsigned lodepng_get_bpp(const LodePNGColorMode* info);
+/*get the amount of color channels used, based on colortype in the struct.
+If a palette is used, it counts as 1 channel.*/
+unsigned lodepng_get_channels(const LodePNGColorMode* info);
+/*is it a greyscale type? (only colortype 0 or 4)*/
+unsigned lodepng_is_greyscale_type(const LodePNGColorMode* info);
+/*has it got an alpha channel? (only colortype 2 or 6)*/
+unsigned lodepng_is_alpha_type(const LodePNGColorMode* info);
+/*has it got a palette? (only colortype 3)*/
+unsigned lodepng_is_palette_type(const LodePNGColorMode* info);
+/*only returns true if there is a palette and there is a value in the palette with alpha < 255.
+Loops through the palette to check this.*/
+unsigned lodepng_has_palette_alpha(const LodePNGColorMode* info);
+/*
+Check if the given color info indicates the possibility of having non-opaque pixels in the PNG image.
+Returns true if the image can have translucent or invisible pixels (it still be opaque if it doesn't use such pixels).
+Returns false if the image can only have opaque pixels.
+In detail, it returns true only if it's a color type with alpha, or has a palette with non-opaque values,
+or if "key_defined" is true.
+*/
+unsigned lodepng_can_have_alpha(const LodePNGColorMode* info);
+/*Returns the byte size of a raw image buffer with given width, height and color mode*/
+size_t lodepng_get_raw_size(unsigned w, unsigned h, const LodePNGColorMode* color);
+
+#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
+/*The information of a Time chunk in PNG.*/
+typedef struct LodePNGTime
+{
+  unsigned year;    /*2 bytes used (0-65535)*/
+  unsigned month;   /*1-12*/
+  unsigned day;     /*1-31*/
+  unsigned hour;    /*0-23*/
+  unsigned minute;  /*0-59*/
+  unsigned second;  /*0-60 (to allow for leap seconds)*/
+} LodePNGTime;
+#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
+
+/*Information about the PNG image, except pixels, width and height.*/
+typedef struct LodePNGInfo
+{
+  /*header (IHDR), palette (PLTE) and transparency (tRNS) chunks*/
+  unsigned compression_method;/*compression method of the original file. Always 0.*/
+  unsigned filter_method;     /*filter method of the original file*/
+  unsigned interlace_method;  /*interlace method of the original file*/
+  LodePNGColorMode color;     /*color type and bits, palette and transparency of the PNG file*/
+
+#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
+  /*
+  suggested background color chunk (bKGD)
+  This color uses the same color mode as the PNG (except alpha channel), which can be 1-bit to 16-bit.
+
+  For greyscale PNGs, r, g and b will all 3 be set to the same. When encoding
+  the encoder writes the red one. For palette PNGs: When decoding, the RGB value
+  will be stored, not a palette index. But when encoding, specify the index of
+  the palette in background_r, the other two are then ignored.
+
+  The decoder does not use this background color to edit the color of pixels.
+  */
+  unsigned background_defined; /*is a suggested background color given?*/
+  unsigned background_r;       /*red component of suggested background color*/
+  unsigned background_g;       /*green component of suggested background color*/
+  unsigned background_b;       /*blue component of suggested background color*/
+
+  /*
+  non-international text chunks (tEXt and zTXt)
+
+  The char** arrays each contain num strings. The actual messages are in
+  text_strings, while text_keys are keywords that give a short description what
+  the actual text represents, e.g. Title, Author, Description, or anything else.
+
+  A keyword is minimum 1 character and maximum 79 characters long. It's
+  discouraged to use a single line length longer than 79 characters for texts.
+
+  Don't allocate these text buffers yourself. Use the init/cleanup functions
+  correctly and use lodepng_add_text and lodepng_clear_text.
+  */
+  size_t text_num; /*the amount of texts in these char** buffers (there may be more texts in itext)*/
+  char** text_keys; /*the keyword of a text chunk (e.g. "Comment")*/
+  char** text_strings; /*the actual text*/
+
+  /*
+  international text chunks (iTXt)
+  Similar to the non-international text chunks, but with additional strings
+  "langtags" and "transkeys".
+  */
+  size_t itext_num; /*the amount of international texts in this PNG*/
+  char** itext_keys; /*the English keyword of the text chunk (e.g. "Comment")*/
+  char** itext_langtags; /*language tag for this text's language, ISO/IEC 646 string, e.g. ISO 639 language tag*/
+  char** itext_transkeys; /*keyword translated to the international language - UTF-8 string*/
+  char** itext_strings; /*the actual international text - UTF-8 string*/
+
+  /*time chunk (tIME)*/
+  unsigned time_defined; /*set to 1 to make the encoder generate a tIME chunk*/
+  LodePNGTime time;
+
+  /*phys chunk (pHYs)*/
+  unsigned phys_defined; /*if 0, there is no pHYs chunk and the values below are undefined, if 1 else there is one*/
+  unsigned phys_x; /*pixels per unit in x direction*/
+  unsigned phys_y; /*pixels per unit in y direction*/
+  unsigned phys_unit; /*may be 0 (unknown unit) or 1 (metre)*/
+
+  /*
+  unknown chunks
+  There are 3 buffers, one for each position in the PNG where unknown chunks can appear
+  each buffer contains all unknown chunks for that position consecutively
+  The 3 buffers are the unknown chunks between certain critical chunks:
+  0: IHDR-PLTE, 1: PLTE-IDAT, 2: IDAT-IEND
+  Do not allocate or traverse this data yourself. Use the chunk traversing functions declared
+  later, such as lodepng_chunk_next and lodepng_chunk_append, to read/write this struct.
+  */
+  unsigned char* unknown_chunks_data[3];
+  size_t unknown_chunks_size[3]; /*size in bytes of the unknown chunks, given for protection*/
+#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
+} LodePNGInfo;
+
+/*init, cleanup and copy functions to use with this struct*/
+void lodepng_info_init(LodePNGInfo* info);
+void lodepng_info_cleanup(LodePNGInfo* info);
+/*return value is error code (0 means no error)*/
+unsigned lodepng_info_copy(LodePNGInfo* dest, const LodePNGInfo* source);
+
+#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
+void lodepng_clear_text(LodePNGInfo* info); /*use this to clear the texts again after you filled them in*/
+unsigned lodepng_add_text(LodePNGInfo* info, const char* key, const char* str); /*push back both texts at once*/
+
+void lodepng_clear_itext(LodePNGInfo* info); /*use this to clear the itexts again after you filled them in*/
+unsigned lodepng_add_itext(LodePNGInfo* info, const char* key, const char* langtag,
+                           const char* transkey, const char* str); /*push back the 4 texts of 1 chunk at once*/
+#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
+
+/*
+Converts raw buffer from one color type to another color type, based on
+LodePNGColorMode structs to describe the input and output color type.
+See the reference manual at the end of this header file to see which color conversions are supported.
+return value = LodePNG error code (0 if all went ok, an error if the conversion isn't supported)
+The out buffer must have size (w * h * bpp + 7) / 8, where bpp is the bits per pixel
+of the output color type (lodepng_get_bpp).
+For < 8 bpp images, there should not be padding bits at the end of scanlines.
+For 16-bit per channel colors, uses big endian format like PNG does.
+Return value is LodePNG error code
+*/
+unsigned lodepng_convert(unsigned char* out, const unsigned char* in,
+                         const LodePNGColorMode* mode_out, const LodePNGColorMode* mode_in,
+                         unsigned w, unsigned h);
+
+#ifdef LODEPNG_COMPILE_DECODER
+/*
+Settings for the decoder. This contains settings for the PNG and the Zlib
+decoder, but not the Info settings from the Info structs.
+*/
+typedef struct LodePNGDecoderSettings
+{
+  LodePNGDecompressSettings zlibsettings; /*in here is the setting to ignore Adler32 checksums*/
+
+  unsigned ignore_crc; /*ignore CRC checksums*/
+
+  unsigned color_convert; /*whether to convert the PNG to the color type you want. Default: yes*/
+
+#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
+  unsigned read_text_chunks; /*if false but remember_unknown_chunks is true, they're stored in the unknown chunks*/
+  /*store all bytes from unknown chunks in the LodePNGInfo (off by default, useful for a png editor)*/
+  unsigned remember_unknown_chunks;
+#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
+} LodePNGDecoderSettings;
+
+void lodepng_decoder_settings_init(LodePNGDecoderSettings* settings);
+#endif /*LODEPNG_COMPILE_DECODER*/
+
+#ifdef LODEPNG_COMPILE_ENCODER
+/*automatically use color type with less bits per pixel if losslessly possible. Default: AUTO*/
+typedef enum LodePNGFilterStrategy
+{
+  /*every filter at zero*/
+  LFS_ZERO,
+  /*Use filter that gives minimum sum, as described in the official PNG filter heuristic.*/
+  LFS_MINSUM,
+  /*Use the filter type that gives smallest Shannon entropy for this scanline. Depending
+  on the image, this is better or worse than minsum.*/
+  LFS_ENTROPY,
+  /*
+  Brute-force-search PNG filters by compressing each filter for each scanline.
+  Experimental, very slow, and only rarely gives better compression than MINSUM.
+  */
+  LFS_BRUTE_FORCE,
+  /*use predefined_filters buffer: you specify the filter type for each scanline*/
+  LFS_PREDEFINED
+} LodePNGFilterStrategy;
+
+/*Gives characteristics about the colors of the image, which helps decide which color model to use for encoding.
+Used internally by default if "auto_convert" is enabled. Public because it's useful for custom algorithms.*/
+typedef struct LodePNGColorProfile
+{
+  unsigned colored; /*not greyscale*/
+  unsigned key; /*if true, image is not opaque. Only if true and alpha is false, color key is possible.*/
+  unsigned short key_r; /*these values are always in 16-bit bitdepth in the profile*/
+  unsigned short key_g;
+  unsigned short key_b;
+  unsigned alpha; /*alpha channel or alpha palette required*/
+  unsigned numcolors; /*amount of colors, up to 257. Not valid if bits == 16.*/
+  unsigned char palette[1024]; /*Remembers up to the first 256 RGBA colors, in no particular order*/
+  unsigned bits; /*bits per channel (not for palette). 1,2 or 4 for greyscale only. 16 if 16-bit per channel required.*/
+} LodePNGColorProfile;
+
+void lodepng_color_profile_init(LodePNGColorProfile* profile);
+
+/*Get a LodePNGColorProfile of the image.*/
+unsigned lodepng_get_color_profile(LodePNGColorProfile* profile,
+                                   const unsigned char* image, unsigned w, unsigned h,
+                                   const LodePNGColorMode* mode_in);
+/*The function LodePNG uses internally to decide the PNG color with auto_convert.
+Chooses an optimal color model, e.g. grey if only grey pixels, palette if < 256 colors, ...*/
+unsigned lodepng_auto_choose_color(LodePNGColorMode* mode_out,
+                                   const unsigned char* image, unsigned w, unsigned h,
+                                   const LodePNGColorMode* mode_in);
+
+/*Settings for the encoder.*/
+typedef struct LodePNGEncoderSettings
+{
+  LodePNGCompressSettings zlibsettings; /*settings for the zlib encoder, such as window size, ...*/
+
+  unsigned auto_convert; /*automatically choose output PNG color type. Default: true*/
+
+  /*If true, follows the official PNG heuristic: if the PNG uses a palette or lower than
+  8 bit depth, set all filters to zero. Otherwise use the filter_strategy. Note that to
+  completely follow the official PNG heuristic, filter_palette_zero must be true and
+  filter_strategy must be LFS_MINSUM*/
+  unsigned filter_palette_zero;
+  /*Which filter strategy to use when not using zeroes due to filter_palette_zero.
+  Set filter_palette_zero to 0 to ensure always using your chosen strategy. Default: LFS_MINSUM*/
+  LodePNGFilterStrategy filter_strategy;
+  /*used if filter_strategy is LFS_PREDEFINED. In that case, this must point to a buffer with
+  the same length as the amount of scanlines in the image, and each value must <= 5. You
+  have to cleanup this buffer, LodePNG will never free it. Don't forget that filter_palette_zero
+  must be set to 0 to ensure this is also used on palette or low bitdepth images.*/
+  const unsigned char* predefined_filters;
+
+  /*force creating a PLTE chunk if colortype is 2 or 6 (= a suggested palette).
+  If colortype is 3, PLTE is _always_ created.*/
+  unsigned force_palette;
+#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
+  /*add LodePNG identifier and version as a text chunk, for debugging*/
+  unsigned add_id;
+  /*encode text chunks as zTXt chunks instead of tEXt chunks, and use compression in iTXt chunks*/
+  unsigned text_compression;
+#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
+} LodePNGEncoderSettings;
+
+void lodepng_encoder_settings_init(LodePNGEncoderSettings* settings);
+#endif /*LODEPNG_COMPILE_ENCODER*/
+
+
+#if defined(LODEPNG_COMPILE_DECODER) || defined(LODEPNG_COMPILE_ENCODER)
+/*The settings, state and information for extended encoding and decoding.*/
+typedef struct LodePNGState
+{
+#ifdef LODEPNG_COMPILE_DECODER
+  LodePNGDecoderSettings decoder; /*the decoding settings*/
+#endif /*LODEPNG_COMPILE_DECODER*/
+#ifdef LODEPNG_COMPILE_ENCODER
+  LodePNGEncoderSettings encoder; /*the encoding settings*/
+#endif /*LODEPNG_COMPILE_ENCODER*/
+  LodePNGColorMode info_raw; /*specifies the format in which you would like to get the raw pixel buffer*/
+  LodePNGInfo info_png; /*info of the PNG image obtained after decoding*/
+  unsigned error;
+#ifdef LODEPNG_COMPILE_CPP
+  /* For the lodepng::State subclass. */
+  virtual ~LodePNGState(){}
+#endif
+} LodePNGState;
+
+/*init, cleanup and copy functions to use with this struct*/
+void lodepng_state_init(LodePNGState* state);
+void lodepng_state_cleanup(LodePNGState* state);
+void lodepng_state_copy(LodePNGState* dest, const LodePNGState* source);
+#endif /* defined(LODEPNG_COMPILE_DECODER) || defined(LODEPNG_COMPILE_ENCODER) */
+
+#ifdef LODEPNG_COMPILE_DECODER
+/*
+Same as lodepng_decode_memory, but uses a LodePNGState to allow custom settings and
+getting much more information about the PNG image and color mode.
+*/
+unsigned lodepng_decode(unsigned char** out, unsigned* w, unsigned* h,
+                        LodePNGState* state,
+                        const unsigned char* in, size_t insize);
+
+/*
+Read the PNG header, but not the actual data. This returns only the information
+that is in the header chunk of the PNG, such as width, height and color type. The
+information is placed in the info_png field of the LodePNGState.
+*/
+unsigned lodepng_inspect(unsigned* w, unsigned* h,
+                         LodePNGState* state,
+                         const unsigned char* in, size_t insize);
+#endif /*LODEPNG_COMPILE_DECODER*/
+
+
+#ifdef LODEPNG_COMPILE_ENCODER
+/*This function allocates the out buffer with standard malloc and stores the size in *outsize.*/
+unsigned lodepng_encode(unsigned char** out, size_t* outsize,
+                        const unsigned char* image, unsigned w, unsigned h,
+                        LodePNGState* state);
+#endif /*LODEPNG_COMPILE_ENCODER*/
+
+/*
+The lodepng_chunk functions are normally not needed, except to traverse the
+unknown chunks stored in the LodePNGInfo struct, or add new ones to it.
+It also allows traversing the chunks of an encoded PNG file yourself.
+
+PNG standard chunk naming conventions:
+First byte: uppercase = critical, lowercase = ancillary
+Second byte: uppercase = public, lowercase = private
+Third byte: must be uppercase
+Fourth byte: uppercase = unsafe to copy, lowercase = safe to copy
+*/
+
+/*
+Gets the length of the data of the chunk. Total chunk length has 12 bytes more.
+There must be at least 4 bytes to read from. If the result value is too large,
+it may be corrupt data.
+*/
+unsigned lodepng_chunk_length(const unsigned char* chunk);
+
+/*puts the 4-byte type in null terminated string*/
+void lodepng_chunk_type(char type[5], const unsigned char* chunk);
+
+/*check if the type is the given type*/
+unsigned char lodepng_chunk_type_equals(const unsigned char* chunk, const char* type);
+
+/*0: it's one of the critical chunk types, 1: it's an ancillary chunk (see PNG standard)*/
+unsigned char lodepng_chunk_ancillary(const unsigned char* chunk);
+
+/*0: public, 1: private (see PNG standard)*/
+unsigned char lodepng_chunk_private(const unsigned char* chunk);
+
+/*0: the chunk is unsafe to copy, 1: the chunk is safe to copy (see PNG standard)*/
+unsigned char lodepng_chunk_safetocopy(const unsigned char* chunk);
+
+/*get pointer to the data of the chunk, where the input points to the header of the chunk*/
+unsigned char* lodepng_chunk_data(unsigned char* chunk);
+const unsigned char* lodepng_chunk_data_const(const unsigned char* chunk);
+
+/*returns 0 if the crc is correct, 1 if it's incorrect (0 for OK as usual!)*/
+unsigned lodepng_chunk_check_crc(const unsigned char* chunk);
+
+/*generates the correct CRC from the data and puts it in the last 4 bytes of the chunk*/
+void lodepng_chunk_generate_crc(unsigned char* chunk);
+
+/*iterate to next chunks. don't use on IEND chunk, as there is no next chunk then*/
+unsigned char* lodepng_chunk_next(unsigned char* chunk);
+const unsigned char* lodepng_chunk_next_const(const unsigned char* chunk);
+
+/*
+Appends chunk to the data in out. The given chunk should already have its chunk header.
+The out variable and outlength are updated to reflect the new reallocated buffer.
+Returns error code (0 if it went ok)
+*/
+unsigned lodepng_chunk_append(unsigned char** out, size_t* outlength, const unsigned char* chunk);
+
+/*
+Appends new chunk to out. The chunk to append is given by giving its length, type
+and data separately. The type is a 4-letter string.
+The out variable and outlength are updated to reflect the new reallocated buffer.
+Returne error code (0 if it went ok)
+*/
+unsigned lodepng_chunk_create(unsigned char** out, size_t* outlength, unsigned length,
+                              const char* type, const unsigned char* data);
+
+
+/*Calculate CRC32 of buffer*/
+unsigned lodepng_crc32(const unsigned char* buf, size_t len);
+#endif /*LODEPNG_COMPILE_PNG*/
+
+
+#ifdef LODEPNG_COMPILE_ZLIB
+/*
+This zlib part can be used independently to zlib compress and decompress a
+buffer. It cannot be used to create gzip files however, and it only supports the
+part of zlib that is required for PNG, it does not support dictionaries.
+*/
+
+#ifdef LODEPNG_COMPILE_DECODER
+/*Inflate a buffer. Inflate is the decompression step of deflate. Out buffer must be freed after use.*/
+unsigned lodepng_inflate(unsigned char** out, size_t* outsize,
+                         const unsigned char* in, size_t insize,
+                         const LodePNGDecompressSettings* settings);
+
+/*
+Decompresses Zlib data. Reallocates the out buffer and appends the data. The
+data must be according to the zlib specification.
+Either, *out must be NULL and *outsize must be 0, or, *out must be a valid
+buffer and *outsize its size in bytes. out must be freed by user after usage.
+*/
+unsigned lodepng_zlib_decompress(unsigned char** out, size_t* outsize,
+                                 const unsigned char* in, size_t insize,
+                                 const LodePNGDecompressSettings* settings);
+#endif /*LODEPNG_COMPILE_DECODER*/
+
+#ifdef LODEPNG_COMPILE_ENCODER
+/*
+Compresses data with Zlib. Reallocates the out buffer and appends the data.
+Zlib adds a small header and trailer around the deflate data.
+The data is output in the format of the zlib specification.
+Either, *out must be NULL and *outsize must be 0, or, *out must be a valid
+buffer and *outsize its size in bytes. out must be freed by user after usage.
+*/
+unsigned lodepng_zlib_compress(unsigned char** out, size_t* outsize,
+                               const unsigned char* in, size_t insize,
+                               const LodePNGCompressSettings* settings);
+
+/*
+Find length-limited Huffman code for given frequencies. This function is in the
+public interface only for tests, it's used internally by lodepng_deflate.
+*/
+unsigned lodepng_huffman_code_lengths(unsigned* lengths, const unsigned* frequencies,
+                                      size_t numcodes, unsigned maxbitlen);
+
+/*Compress a buffer with deflate. See RFC 1951. Out buffer must be freed after use.*/
+unsigned lodepng_deflate(unsigned char** out, size_t* outsize,
+                         const unsigned char* in, size_t insize,
+                         const LodePNGCompressSettings* settings);
+
+#endif /*LODEPNG_COMPILE_ENCODER*/
+#endif /*LODEPNG_COMPILE_ZLIB*/
+
+#ifdef LODEPNG_COMPILE_DISK
+/*
+Load a file from disk into buffer. The function allocates the out buffer, and
+after usage you should free it.
+out: output parameter, contains pointer to loaded buffer.
+outsize: output parameter, size of the allocated out buffer
+filename: the path to the file to load
+return value: error code (0 means ok)
+*/
+unsigned lodepng_load_file(unsigned char** out, size_t* outsize, const char* filename);
+
+/*
+Save a file from buffer to disk. Warning, if it exists, this function overwrites
+the file without warning!
+buffer: the buffer to write
+buffersize: size of the buffer to write
+filename: the path to the file to save to
+return value: error code (0 means ok)
+*/
+unsigned lodepng_save_file(const unsigned char* buffer, size_t buffersize, const char* filename);
+#endif /*LODEPNG_COMPILE_DISK*/
+
+#ifdef LODEPNG_COMPILE_CPP
+/* The LodePNG C++ wrapper uses std::vectors instead of manually allocated memory buffers. */
+namespace lodepng
+{
+#ifdef LODEPNG_COMPILE_PNG
+class State : public LodePNGState
+{
+  public:
+    State();
+    State(const State& other);
+    virtual ~State();
+    State& operator=(const State& other);
+};
+
+#ifdef LODEPNG_COMPILE_DECODER
+/* Same as other lodepng::decode, but using a State for more settings and information. */
+unsigned decode(std::vector<unsigned char>& out, unsigned& w, unsigned& h,
+                State& state,
+                const unsigned char* in, size_t insize);
+unsigned decode(std::vector<unsigned char>& out, unsigned& w, unsigned& h,
+                State& state,
+                const std::vector<unsigned char>& in);
+#endif /*LODEPNG_COMPILE_DECODER*/
+
+#ifdef LODEPNG_COMPILE_ENCODER
+/* Same as other lodepng::encode, but using a State for more settings and information. */
+unsigned encode(std::vector<unsigned char>& out,
+                const unsigned char* in, unsigned w, unsigned h,
+                State& state);
+unsigned encode(std::vector<unsigned char>& out,
+                const std::vector<unsigned char>& in, unsigned w, unsigned h,
+                State& state);
+#endif /*LODEPNG_COMPILE_ENCODER*/
+
+#ifdef LODEPNG_COMPILE_DISK
+/*
+Load a file from disk into an std::vector.
+return value: error code (0 means ok)
+*/
+unsigned load_file(std::vector<unsigned char>& buffer, const std::string& filename);
+
+/*
+Save the binary data in an std::vector to a file on disk. The file is overwritten
+without warning.
+*/
+unsigned save_file(const std::vector<unsigned char>& buffer, const std::string& filename);
+#endif /* LODEPNG_COMPILE_DISK */
+#endif /* LODEPNG_COMPILE_PNG */
+
+#ifdef LODEPNG_COMPILE_ZLIB
+#ifdef LODEPNG_COMPILE_DECODER
+/* Zlib-decompress an unsigned char buffer */
+unsigned decompress(std::vector<unsigned char>& out, const unsigned char* in, size_t insize,
+                    const LodePNGDecompressSettings& settings = lodepng_default_decompress_settings);
+
+/* Zlib-decompress an std::vector */
+unsigned decompress(std::vector<unsigned char>& out, const std::vector<unsigned char>& in,
+                    const LodePNGDecompressSettings& settings = lodepng_default_decompress_settings);
+#endif /* LODEPNG_COMPILE_DECODER */
+
+#ifdef LODEPNG_COMPILE_ENCODER
+/* Zlib-compress an unsigned char buffer */
+unsigned compress(std::vector<unsigned char>& out, const unsigned char* in, size_t insize,
+                  const LodePNGCompressSettings& settings = lodepng_default_compress_settings);
+
+/* Zlib-compress an std::vector */
+unsigned compress(std::vector<unsigned char>& out, const std::vector<unsigned char>& in,
+                  const LodePNGCompressSettings& settings = lodepng_default_compress_settings);
+#endif /* LODEPNG_COMPILE_ENCODER */
+#endif /* LODEPNG_COMPILE_ZLIB */
+} /* namespace lodepng */
+#endif /*LODEPNG_COMPILE_CPP*/
+
+/*
+TODO:
+[.] test if there are no memory leaks or security exploits - done a lot but needs to be checked often
+[.] check compatibility with various compilers  - done but needs to be redone for every newer version
+[X] converting color to 16-bit per channel types
+[ ] read all public PNG chunk types (but never let the color profile and gamma ones touch RGB values)
+[ ] make sure encoder generates no chunks with size > (2^31)-1
+[ ] partial decoding (stream processing)
+[X] let the "isFullyOpaque" function check color keys and transparent palettes too
+[X] better name for the variables "codes", "codesD", "codelengthcodes", "clcl" and "lldl"
+[ ] don't stop decoding on errors like 69, 57, 58 (make warnings)
+[ ] let the C++ wrapper catch exceptions coming from the standard library and return LodePNG error codes
+[ ] allow user to provide custom color conversion functions, e.g. for premultiplied alpha, padding bits or not, ...
+[ ] allow user to give data (void*) to custom allocator
+*/
+
+#endif /*LODEPNG_H inclusion guard*/
+
+/*
+LodePNG Documentation
+---------------------
+
+0. table of contents
+--------------------
+
+  1. about
+   1.1. supported features
+   1.2. features not supported
+  2. C and C++ version
+  3. security
+  4. decoding
+  5. encoding
+  6. color conversions
+    6.1. PNG color types
+    6.2. color conversions
+    6.3. padding bits
+    6.4. A note about 16-bits per channel and endianness
+  7. error values
+  8. chunks and PNG editing
+  9. compiler support
+  10. examples
+   10.1. decoder C++ example
+   10.2. decoder C example
+  11. state settings reference
+  12. changes
+  13. contact information
+
+
+1. about
+--------
+
+PNG is a file format to store raster images losslessly with good compression,
+supporting different color types and alpha channel.
+
+LodePNG is a PNG codec according to the Portable Network Graphics (PNG)
+Specification (Second Edition) - W3C Recommendation 10 November 2003.
+
+The specifications used are:
+
+*) Portable Network Graphics (PNG) Specification (Second Edition):
+     http://www.w3.org/TR/2003/REC-PNG-20031110
+*) RFC 1950 ZLIB Compressed Data Format version 3.3:
+     http://www.gzip.org/zlib/rfc-zlib.html
+*) RFC 1951 DEFLATE Compressed Data Format Specification ver 1.3:
+     http://www.gzip.org/zlib/rfc-deflate.html
+
+The most recent version of LodePNG can currently be found at
+http://lodev.org/lodepng/
+
+LodePNG works both in C (ISO C90) and C++, with a C++ wrapper that adds
+extra functionality.
+
+LodePNG exists out of two files:
+-lodepng.h: the header file for both C and C++
+-lodepng.c(pp): give it the name lodepng.c or lodepng.cpp (or .cc) depending on your usage
+
+If you want to start using LodePNG right away without reading this doc, get the
+examples from the LodePNG website to see how to use it in code, or check the
+smaller examples in chapter 13 here.
+
+LodePNG is simple but only supports the basic requirements. To achieve
+simplicity, the following design choices were made: There are no dependencies
+on any external library. There are functions to decode and encode a PNG with
+a single function call, and extended versions of these functions taking a
+LodePNGState struct allowing to specify or get more information. By default
+the colors of the raw image are always RGB or RGBA, no matter what color type
+the PNG file uses. To read and write files, there are simple functions to
+convert the files to/from buffers in memory.
+
+This all makes LodePNG suitable for loading textures in games, demos and small
+programs, ... It's less suitable for full fledged image editors, loading PNGs
+over network (it requires all the image data to be available before decoding can
+begin), life-critical systems, ...
+
+1.1. supported features
+-----------------------
+
+The following features are supported by the decoder:
+
+*) decoding of PNGs with any color type, bit depth and interlace mode, to a 24- or 32-bit color raw image,
+   or the same color type as the PNG
+*) encoding of PNGs, from any raw image to 24- or 32-bit color, or the same color type as the raw image
+*) Adam7 interlace and deinterlace for any color type
+*) loading the image from harddisk or decoding it from a buffer from other sources than harddisk
+*) support for alpha channels, including RGBA color model, translucent palettes and color keying
+*) zlib decompression (inflate)
+*) zlib compression (deflate)
+*) CRC32 and ADLER32 checksums
+*) handling of unknown chunks, allowing making a PNG editor that stores custom and unknown chunks.
+*) the following chunks are supported (generated/interpreted) by both encoder and decoder:
+    IHDR: header information
+    PLTE: color palette
+    IDAT: pixel data
+    IEND: the final chunk
+    tRNS: transparency for palettized images
+    tEXt: textual information
+    zTXt: compressed textual information
+    iTXt: international textual information
+    bKGD: suggested background color
+    pHYs: physical dimensions
+    tIME: modification time
+
+1.2. features not supported
+---------------------------
+
+The following features are _not_ supported:
+
+*) some features needed to make a conformant PNG-Editor might be still missing.
+*) partial loading/stream processing. All data must be available and is processed in one call.
+*) The following public chunks are not supported but treated as unknown chunks by LodePNG
+    cHRM, gAMA, iCCP, sRGB, sBIT, hIST, sPLT
+   Some of these are not supported on purpose: LodePNG wants to provide the RGB values
+   stored in the pixels, not values modified by system dependent gamma or color models.
+
+
+2. C and C++ version
+--------------------
+
+The C version uses buffers allocated with alloc that you need to free()
+yourself. You need to use init and cleanup functions for each struct whenever
+using a struct from the C version to avoid exploits and memory leaks.
+
+The C++ version has extra functions with std::vectors in the interface and the
+lodepng::State class which is a LodePNGState with constructor and destructor.
+
+These files work without modification for both C and C++ compilers because all
+the additional C++ code is in "#ifdef __cplusplus" blocks that make C-compilers
+ignore it, and the C code is made to compile both with strict ISO C90 and C++.
+
+To use the C++ version, you need to rename the source file to lodepng.cpp
+(instead of lodepng.c), and compile it with a C++ compiler.
+
+To use the C version, you need to rename the source file to lodepng.c (instead
+of lodepng.cpp), and compile it with a C compiler.
+
+
+3. Security
+-----------
+
+Even if carefully designed, it's always possible that LodePNG contains possible
+exploits. If you discover one, please let me know, and it will be fixed.
+
+When using LodePNG, care has to be taken with the C version of LodePNG, as well
+as the C-style structs when working with C++. The following conventions are used
+for all C-style structs:
+
+-if a struct has a corresponding init function, always call the init function when making a new one
+-if a struct has a corresponding cleanup function, call it before the struct disappears to avoid memory leaks
+-if a struct has a corresponding copy function, use the copy function instead of "=".
+ The destination must also be inited already.
+
+
+4. Decoding
+-----------
+
+Decoding converts a PNG compressed image to a raw pixel buffer.
+
+Most documentation on using the decoder is at its declarations in the header
+above. For C, simple decoding can be done with functions such as
+lodepng_decode32, and more advanced decoding can be done with the struct
+LodePNGState and lodepng_decode. For C++, all decoding can be done with the
+various lodepng::decode functions, and lodepng::State can be used for advanced
+features.
+
+When using the LodePNGState, it uses the following fields for decoding:
+*) LodePNGInfo info_png: it stores extra information about the PNG (the input) in here
+*) LodePNGColorMode info_raw: here you can say what color mode of the raw image (the output) you want to get
+*) LodePNGDecoderSettings decoder: you can specify a few extra settings for the decoder to use
+
+LodePNGInfo info_png
+--------------------
+
+After decoding, this contains extra information of the PNG image, except the actual
+pixels, width and height because these are already gotten directly from the decoder
+functions.
+
+It contains for example the original color type of the PNG image, text comments,
+suggested background color, etc... More details about the LodePNGInfo struct are
+at its declaration documentation.
+
+LodePNGColorMode info_raw
+-------------------------
+
+When decoding, here you can specify which color type you want
+the resulting raw image to be. If this is different from the colortype of the
+PNG, then the decoder will automatically convert the result. This conversion
+always works, except if you want it to convert a color PNG to greyscale or to
+a palette with missing colors.
+
+By default, 32-bit color is used for the result.
+
+LodePNGDecoderSettings decoder
+------------------------------
+
+The settings can be used to ignore the errors created by invalid CRC and Adler32
+chunks, and to disable the decoding of tEXt chunks.
+
+There's also a setting color_convert, true by default. If false, no conversion
+is done, the resulting data will be as it was in the PNG (after decompression)
+and you'll have to puzzle the colors of the pixels together yourself using the
+color type information in the LodePNGInfo.
+
+
+5. Encoding
+-----------
+
+Encoding converts a raw pixel buffer to a PNG compressed image.
+
+Most documentation on using the encoder is at its declarations in the header
+above. For C, simple encoding can be done with functions such as
+lodepng_encode32, and more advanced decoding can be done with the struct
+LodePNGState and lodepng_encode. For C++, all encoding can be done with the
+various lodepng::encode functions, and lodepng::State can be used for advanced
+features.
+
+Like the decoder, the encoder can also give errors. However it gives less errors
+since the encoder input is trusted, the decoder input (a PNG image that could
+be forged by anyone) is not trusted.
+
+When using the LodePNGState, it uses the following fields for encoding:
+*) LodePNGInfo info_png: here you specify how you want the PNG (the output) to be.
+*) LodePNGColorMode info_raw: here you say what color type of the raw image (the input) has
+*) LodePNGEncoderSettings encoder: you can specify a few settings for the encoder to use
+
+LodePNGInfo info_png
+--------------------
+
+When encoding, you use this the opposite way as when decoding: for encoding,
+you fill in the values you want the PNG to have before encoding. By default it's
+not needed to specify a color type for the PNG since it's automatically chosen,
+but it's possible to choose it yourself given the right settings.
+
+The encoder will not always exactly match the LodePNGInfo struct you give,
+it tries as close as possible. Some things are ignored by the encoder. The
+encoder uses, for example, the following settings from it when applicable:
+colortype and bitdepth, text chunks, time chunk, the color key, the palette, the
+background color, the interlace method, unknown chunks, ...
+
+When encoding to a PNG with colortype 3, the encoder will generate a PLTE chunk.
+If the palette contains any colors for which the alpha channel is not 255 (so
+there are translucent colors in the palette), it'll add a tRNS chunk.
+
+LodePNGColorMode info_raw
+-------------------------
+
+You specify the color type of the raw image that you give to the input here,
+including a possible transparent color key and palette you happen to be using in
+your raw image data.
+
+By default, 32-bit color is assumed, meaning your input has to be in RGBA
+format with 4 bytes (unsigned chars) per pixel.
+
+LodePNGEncoderSettings encoder
+------------------------------
+
+The following settings are supported (some are in sub-structs):
+*) auto_convert: when this option is enabled, the encoder will
+automatically choose the smallest possible color mode (including color key) that
+can encode the colors of all pixels without information loss.
+*) btype: the block type for LZ77. 0 = uncompressed, 1 = fixed huffman tree,
+   2 = dynamic huffman tree (best compression). Should be 2 for proper
+   compression.
+*) use_lz77: whether or not to use LZ77 for compressed block types. Should be
+   true for proper compression.
+*) windowsize: the window size used by the LZ77 encoder (1 - 32768). Has value
+   2048 by default, but can be set to 32768 for better, but slow, compression.
+*) force_palette: if colortype is 2 or 6, you can make the encoder write a PLTE
+   chunk if force_palette is true. This can used as suggested palette to convert
+   to by viewers that don't support more than 256 colors (if those still exist)
+*) add_id: add text chunk "Encoder: LodePNG <version>" to the image.
+*) text_compression: default 1. If 1, it'll store texts as zTXt instead of tEXt chunks.
+  zTXt chunks use zlib compression on the text. This gives a smaller result on
+  large texts but a larger result on small texts (such as a single program name).
+  It's all tEXt or all zTXt though, there's no separate setting per text yet.
+
+
+6. color conversions
+--------------------
+
+An important thing to note about LodePNG, is that the color type of the PNG, and
+the color type of the raw image, are completely independent. By default, when
+you decode a PNG, you get the result as a raw image in the color type you want,
+no matter whether the PNG was encoded with a palette, greyscale or RGBA color.
+And if you encode an image, by default LodePNG will automatically choose the PNG
+color type that gives good compression based on the values of colors and amount
+of colors in the image. It can be configured to let you control it instead as
+well, though.
+
+To be able to do this, LodePNG does conversions from one color mode to another.
+It can convert from almost any color type to any other color type, except the
+following conversions: RGB to greyscale is not supported, and converting to a
+palette when the palette doesn't have a required color is not supported. This is
+not supported on purpose: this is information loss which requires a color
+reduction algorithm that is beyong the scope of a PNG encoder (yes, RGB to grey
+is easy, but there are multiple ways if you want to give some channels more
+weight).
+
+By default, when decoding, you get the raw image in 32-bit RGBA or 24-bit RGB
+color, no matter what color type the PNG has. And by default when encoding,
+LodePNG automatically picks the best color model for the output PNG, and expects
+the input image to be 32-bit RGBA or 24-bit RGB. So, unless you want to control
+the color format of the images yourself, you can skip this chapter.
+
+6.1. PNG color types
+--------------------
+
+A PNG image can have many color types, ranging from 1-bit color to 64-bit color,
+as well as palettized color modes. After the zlib decompression and unfiltering
+in the PNG image is done, the raw pixel data will have that color type and thus
+a certain amount of bits per pixel. If you want the output raw image after
+decoding to have another color type, a conversion is done by LodePNG.
+
+The PNG specification gives the following color types:
+
+0: greyscale, bit depths 1, 2, 4, 8, 16
+2: RGB, bit depths 8 and 16
+3: palette, bit depths 1, 2, 4 and 8
+4: greyscale with alpha, bit depths 8 and 16
+6: RGBA, bit depths 8 and 16
+
+Bit depth is the amount of bits per pixel per color channel. So the total amount
+of bits per pixel is: amount of channels * bitdepth.
+
+6.2. color conversions
+----------------------
+
+As explained in the sections about the encoder and decoder, you can specify
+color types and bit depths in info_png and info_raw to change the default
+behaviour.
+
+If, when decoding, you want the raw image to be something else than the default,
+you need to set the color type and bit depth you want in the LodePNGColorMode,
+or the parameters colortype and bitdepth of the simple decoding function.
+
+If, when encoding, you use another color type than the default in the raw input
+image, you need to specify its color type and bit depth in the LodePNGColorMode
+of the raw image, or use the parameters colortype and bitdepth of the simple
+encoding function.
+
+If, when encoding, you don't want LodePNG to choose the output PNG color type
+but control it yourself, you need to set auto_convert in the encoder settings
+to false, and specify the color type you want in the LodePNGInfo of the
+encoder (including palette: it can generate a palette if auto_convert is true,
+otherwise not).
+
+If the input and output color type differ (whether user chosen or auto chosen),
+LodePNG will do a color conversion, which follows the rules below, and may
+sometimes result in an error.
+
+To avoid some confusion:
+-the decoder converts from PNG to raw image
+-the encoder converts from raw image to PNG
+-the colortype and bitdepth in LodePNGColorMode info_raw, are those of the raw image
+-the colortype and bitdepth in the color field of LodePNGInfo info_png, are those of the PNG
+-when encoding, the color type in LodePNGInfo is ignored if auto_convert
+ is enabled, it is automatically generated instead
+-when decoding, the color type in LodePNGInfo is set by the decoder to that of the original
+ PNG image, but it can be ignored since the raw image has the color type you requested instead
+-if the color type of the LodePNGColorMode and PNG image aren't the same, a conversion
+ between the color types is done if the color types are supported. If it is not
+ supported, an error is returned. If the types are the same, no conversion is done.
+-even though some conversions aren't supported, LodePNG supports loading PNGs from any
+ colortype and saving PNGs to any colortype, sometimes it just requires preparing
+ the raw image correctly before encoding.
+-both encoder and decoder use the same color converter.
+
+Non supported color conversions:
+-color to greyscale: no error is thrown, but the result will look ugly because
+only the red channel is taken
+-anything to palette when that palette does not have that color in it: in this
+case an error is thrown
+
+Supported color conversions:
+-anything to 8-bit RGB, 8-bit RGBA, 16-bit RGB, 16-bit RGBA
+-any grey or grey+alpha, to grey or grey+alpha
+-anything to a palette, as long as the palette has the requested colors in it
+-removing alpha channel
+-higher to smaller bitdepth, and vice versa
+
+If you want no color conversion to be done (e.g. for speed or control):
+-In the encoder, you can make it save a PNG with any color type by giving the
+raw color mode and LodePNGInfo the same color mode, and setting auto_convert to
+false.
+-In the decoder, you can make it store the pixel data in the same color type
+as the PNG has, by setting the color_convert setting to false. Settings in
+info_raw are then ignored.
+
+The function lodepng_convert does the color conversion. It is available in the
+interface but normally isn't needed since the encoder and decoder already call
+it.
+
+6.3. padding bits
+-----------------
+
+In the PNG file format, if a less than 8-bit per pixel color type is used and the scanlines
+have a bit amount that isn't a multiple of 8, then padding bits are used so that each
+scanline starts at a fresh byte. But that is NOT true for the LodePNG raw input and output.
+The raw input image you give to the encoder, and the raw output image you get from the decoder
+will NOT have these padding bits, e.g. in the case of a 1-bit image with a width
+of 7 pixels, the first pixel of the second scanline will the the 8th bit of the first byte,
+not the first bit of a new byte.
+
+6.4. A note about 16-bits per channel and endianness
+----------------------------------------------------
+
+LodePNG uses unsigned char arrays for 16-bit per channel colors too, just like
+for any other color format. The 16-bit values are stored in big endian (most
+significant byte first) in these arrays. This is the opposite order of the
+little endian used by x86 CPU's.
+
+LodePNG always uses big endian because the PNG file format does so internally.
+Conversions to other formats than PNG uses internally are not supported by
+LodePNG on purpose, there are myriads of formats, including endianness of 16-bit
+colors, the order in which you store R, G, B and A, and so on. Supporting and
+converting to/from all that is outside the scope of LodePNG.
+
+This may mean that, depending on your use case, you may want to convert the big
+endian output of LodePNG to little endian with a for loop. This is certainly not
+always needed, many applications and libraries support big endian 16-bit colors
+anyway, but it means you cannot simply cast the unsigned char* buffer to an
+unsigned short* buffer on x86 CPUs.
+
+
+7. error values
+---------------
+
+All functions in LodePNG that return an error code, return 0 if everything went
+OK, or a non-zero code if there was an error.
+
+The meaning of the LodePNG error values can be retrieved with the function
+lodepng_error_text: given the numerical error code, it returns a description
+of the error in English as a string.
+
+Check the implementation of lodepng_error_text to see the meaning of each code.
+
+
+8. chunks and PNG editing
+-------------------------
+
+If you want to add extra chunks to a PNG you encode, or use LodePNG for a PNG
+editor that should follow the rules about handling of unknown chunks, or if your
+program is able to read other types of chunks than the ones handled by LodePNG,
+then that's possible with the chunk functions of LodePNG.
+
+A PNG chunk has the following layout:
+
+4 bytes length
+4 bytes type name
+length bytes data
+4 bytes CRC
+
+8.1. iterating through chunks
+-----------------------------
+
+If you have a buffer containing the PNG image data, then the first chunk (the
+IHDR chunk) starts at byte number 8 of that buffer. The first 8 bytes are the
+signature of the PNG and are not part of a chunk. But if you start at byte 8
+then you have a chunk, and can check the following things of it.
+
+NOTE: none of these functions check for memory buffer boundaries. To avoid
+exploits, always make sure the buffer contains all the data of the chunks.
+When using lodepng_chunk_next, make sure the returned value is within the
+allocated memory.
+
+unsigned lodepng_chunk_length(const unsigned char* chunk):
+
+Get the length of the chunk's data. The total chunk length is this length + 12.
+
+void lodepng_chunk_type(char type[5], const unsigned char* chunk):
+unsigned char lodepng_chunk_type_equals(const unsigned char* chunk, const char* type):
+
+Get the type of the chunk or compare if it's a certain type
+
+unsigned char lodepng_chunk_critical(const unsigned char* chunk):
+unsigned char lodepng_chunk_private(const unsigned char* chunk):
+unsigned char lodepng_chunk_safetocopy(const unsigned char* chunk):
+
+Check if the chunk is critical in the PNG standard (only IHDR, PLTE, IDAT and IEND are).
+Check if the chunk is private (public chunks are part of the standard, private ones not).
+Check if the chunk is safe to copy. If it's not, then, when modifying data in a critical
+chunk, unsafe to copy chunks of the old image may NOT be saved in the new one if your
+program doesn't handle that type of unknown chunk.
+
+unsigned char* lodepng_chunk_data(unsigned char* chunk):
+const unsigned char* lodepng_chunk_data_const(const unsigned char* chunk):
+
+Get a pointer to the start of the data of the chunk.
+
+unsigned lodepng_chunk_check_crc(const unsigned char* chunk):
+void lodepng_chunk_generate_crc(unsigned char* chunk):
+
+Check if the crc is correct or generate a correct one.
+
+unsigned char* lodepng_chunk_next(unsigned char* chunk):
+const unsigned char* lodepng_chunk_next_const(const unsigned char* chunk):
+
+Iterate to the next chunk. This works if you have a buffer with consecutive chunks. Note that these
+functions do no boundary checking of the allocated data whatsoever, so make sure there is enough
+data available in the buffer to be able to go to the next chunk.
+
+unsigned lodepng_chunk_append(unsigned char** out, size_t* outlength, const unsigned char* chunk):
+unsigned lodepng_chunk_create(unsigned char** out, size_t* outlength, unsigned length,
+                              const char* type, const unsigned char* data):
+
+These functions are used to create new chunks that are appended to the data in *out that has
+length *outlength. The append function appends an existing chunk to the new data. The create
+function creates a new chunk with the given parameters and appends it. Type is the 4-letter
+name of the chunk.
+
+8.2. chunks in info_png
+-----------------------
+
+The LodePNGInfo struct contains fields with the unknown chunk in it. It has 3
+buffers (each with size) to contain 3 types of unknown chunks:
+the ones that come before the PLTE chunk, the ones that come between the PLTE
+and the IDAT chunks, and the ones that come after the IDAT chunks.
+It's necessary to make the distionction between these 3 cases because the PNG
+standard forces to keep the ordering of unknown chunks compared to the critical
+chunks, but does not force any other ordering rules.
+
+info_png.unknown_chunks_data[0] is the chunks before PLTE
+info_png.unknown_chunks_data[1] is the chunks after PLTE, before IDAT
+info_png.unknown_chunks_data[2] is the chunks after IDAT
+
+The chunks in these 3 buffers can be iterated through and read by using the same
+way described in the previous subchapter.
+
+When using the decoder to decode a PNG, you can make it store all unknown chunks
+if you set the option settings.remember_unknown_chunks to 1. By default, this
+option is off (0).
+
+The encoder will always encode unknown chunks that are stored in the info_png.
+If you need it to add a particular chunk that isn't known by LodePNG, you can
+use lodepng_chunk_append or lodepng_chunk_create to the chunk data in
+info_png.unknown_chunks_data[x].
+
+Chunks that are known by LodePNG should not be added in that way. E.g. to make
+LodePNG add a bKGD chunk, set background_defined to true and add the correct
+parameters there instead.
+
+
+9. compiler support
+-------------------
+
+No libraries other than the current standard C library are needed to compile
+LodePNG. For the C++ version, only the standard C++ library is needed on top.
+Add the files lodepng.c(pp) and lodepng.h to your project, include
+lodepng.h where needed, and your program can read/write PNG files.
+
+It is compatible with C90 and up, and C++03 and up.
+
+If performance is important, use optimization when compiling! For both the
+encoder and decoder, this makes a large difference.
+
+Make sure that LodePNG is compiled with the same compiler of the same version
+and with the same settings as the rest of the program, or the interfaces with
+std::vectors and std::strings in C++ can be incompatible.
+
+CHAR_BITS must be 8 or higher, because LodePNG uses unsigned chars for octets.
+
+*) gcc and g++
+
+LodePNG is developed in gcc so this compiler is natively supported. It gives no
+warnings with compiler options "-Wall -Wextra -pedantic -ansi", with gcc and g++
+version 4.7.1 on Linux, 32-bit and 64-bit.
+
+*) Clang
+
+Fully supported and warning-free.
+
+*) Mingw
+
+The Mingw compiler (a port of gcc for Windows) should be fully supported by
+LodePNG.
+
+*) Visual Studio and Visual C++ Express Edition
+
+LodePNG should be warning-free with warning level W4. Two warnings were disabled
+with pragmas though: warning 4244 about implicit conversions, and warning 4996
+where it wants to use a non-standard function fopen_s instead of the standard C
+fopen.
+
+Visual Studio may want "stdafx.h" files to be included in each source file and
+give an error "unexpected end of file while looking for precompiled header".
+This is not standard C++ and will not be added to the stock LodePNG. You can
+disable it for lodepng.cpp only by right clicking it, Properties, C/C++,
+Precompiled Headers, and set it to Not Using Precompiled Headers there.
+
+NOTE: Modern versions of VS should be fully supported, but old versions, e.g.
+VS6, are not guaranteed to work.
+
+*) Compilers on Macintosh
+
+LodePNG has been reported to work both with gcc and LLVM for Macintosh, both for
+C and C++.
+
+*) Other Compilers
+
+If you encounter problems on any compilers, feel free to let me know and I may
+try to fix it if the compiler is modern and standards complient.
+
+
+10. examples
+------------
+
+This decoder example shows the most basic usage of LodePNG. More complex
+examples can be found on the LodePNG website.
+
+10.1. decoder C++ example
+-------------------------
+
+#include "lodepng.h"
+#include <iostream>
+
+int main(int argc, char *argv[])
+{
+  const char* filename = argc > 1 ? argv[1] : "test.png";
+
+  //load and decode
+  std::vector<unsigned char> image;
+  unsigned width, height;
+  unsigned error = lodepng::decode(image, width, height, filename);
+
+  //if there's an error, display it
+  if(error) std::cout << "decoder error " << error << ": " << lodepng_error_text(error) << std::endl;
+
+  //the pixels are now in the vector "image", 4 bytes per pixel, ordered RGBARGBA..., use it as texture, draw it, ...
+}
+
+10.2. decoder C example
+-----------------------
+
+#include "lodepng.h"
+
+int main(int argc, char *argv[])
+{
+  unsigned error;
+  unsigned char* image;
+  size_t width, height;
+  const char* filename = argc > 1 ? argv[1] : "test.png";
+
+  error = lodepng_decode32_file(&image, &width, &height, filename);
+
+  if(error) printf("decoder error %u: %s\n", error, lodepng_error_text(error));
+
+  / * use image here * /
+
+  free(image);
+  return 0;
+}
+
+11. state settings reference
+----------------------------
+
+A quick reference of some settings to set on the LodePNGState
+
+For decoding:
+
+state.decoder.zlibsettings.ignore_adler32: ignore ADLER32 checksums
+state.decoder.zlibsettings.custom_...: use custom inflate function
+state.decoder.ignore_crc: ignore CRC checksums
+state.decoder.color_convert: convert internal PNG color to chosen one
+state.decoder.read_text_chunks: whether to read in text metadata chunks
+state.decoder.remember_unknown_chunks: whether to read in unknown chunks
+state.info_raw.colortype: desired color type for decoded image
+state.info_raw.bitdepth: desired bit depth for decoded image
+state.info_raw....: more color settings, see struct LodePNGColorMode
+state.info_png....: no settings for decoder but ouput, see struct LodePNGInfo
+
+For encoding:
+
+state.encoder.zlibsettings.btype: disable compression by setting it to 0
+state.encoder.zlibsettings.use_lz77: use LZ77 in compression
+state.encoder.zlibsettings.windowsize: tweak LZ77 windowsize
+state.encoder.zlibsettings.minmatch: tweak min LZ77 length to match
+state.encoder.zlibsettings.nicematch: tweak LZ77 match where to stop searching
+state.encoder.zlibsettings.lazymatching: try one more LZ77 matching
+state.encoder.zlibsettings.custom_...: use custom deflate function
+state.encoder.auto_convert: choose optimal PNG color type, if 0 uses info_png
+state.encoder.filter_palette_zero: PNG filter strategy for palette
+state.encoder.filter_strategy: PNG filter strategy to encode with
+state.encoder.force_palette: add palette even if not encoding to one
+state.encoder.add_id: add LodePNG identifier and version as a text chunk
+state.encoder.text_compression: use compressed text chunks for metadata
+state.info_raw.colortype: color type of raw input image you provide
+state.info_raw.bitdepth: bit depth of raw input image you provide
+state.info_raw: more color settings, see struct LodePNGColorMode
+state.info_png.color.colortype: desired color type if auto_convert is false
+state.info_png.color.bitdepth: desired bit depth if auto_convert is false
+state.info_png.color....: more color settings, see struct LodePNGColorMode
+state.info_png....: more PNG related settings, see struct LodePNGInfo
+
+
+12. changes
+-----------
+
+The version number of LodePNG is the date of the change given in the format
+yyyymmdd.
+
+Some changes aren't backwards compatible. Those are indicated with a (!)
+symbol.
+
+*) 18 apr 2016: Changed qsort to custom stable sort (for platforms w/o qsort).
+*) 09 apr 2016: Fixed colorkey usage detection, and better file loading (within
+   the limits of pure C90).
+*) 08 dec 2015: Made load_file function return error if file can't be opened.
+*) 24 okt 2015: Bugfix with decoding to palette output.
+*) 18 apr 2015: Boundary PM instead of just package-merge for faster encoding.
+*) 23 aug 2014: Reduced needless memory usage of decoder.
+*) 28 jun 2014: Removed fix_png setting, always support palette OOB for
+    simplicity. Made ColorProfile public.
+*) 09 jun 2014: Faster encoder by fixing hash bug and more zeros optimization.
+*) 22 dec 2013: Power of two windowsize required for optimization.
+*) 15 apr 2013: Fixed bug with LAC_ALPHA and color key.
+*) 25 mar 2013: Added an optional feature to ignore some PNG errors (fix_png).
+*) 11 mar 2013 (!): Bugfix with custom free. Changed from "my" to "lodepng_"
+    prefix for the custom allocators and made it possible with a new #define to
+    use custom ones in your project without needing to change lodepng's code.
+*) 28 jan 2013: Bugfix with color key.
+*) 27 okt 2012: Tweaks in text chunk keyword length error handling.
+*) 8 okt 2012 (!): Added new filter strategy (entropy) and new auto color mode.
+    (no palette). Better deflate tree encoding. New compression tweak settings.
+    Faster color conversions while decoding. Some internal cleanups.
+*) 23 sep 2012: Reduced warnings in Visual Studio a little bit.
+*) 1 sep 2012 (!): Removed #define's for giving custom (de)compression functions
+    and made it work with function pointers instead.
+*) 23 jun 2012: Added more filter strategies. Made it easier to use custom alloc
+    and free functions and toggle #defines from compiler flags. Small fixes.
+*) 6 may 2012 (!): Made plugging in custom zlib/deflate functions more flexible.
+*) 22 apr 2012 (!): Made interface more consistent, renaming a lot. Removed
+    redundant C++ codec classes. Reduced amount of structs. Everything changed,
+    but it is cleaner now imho and functionality remains the same. Also fixed
+    several bugs and shrunk the implementation code. Made new samples.
+*) 6 nov 2011 (!): By default, the encoder now automatically chooses the best
+    PNG color model and bit depth, based on the amount and type of colors of the
+    raw image. For this, autoLeaveOutAlphaChannel replaced by auto_choose_color.
+*) 9 okt 2011: simpler hash chain implementation for the encoder.
+*) 8 sep 2011: lz77 encoder lazy matching instead of greedy matching.
+*) 23 aug 2011: tweaked the zlib compression parameters after benchmarking.
+    A bug with the PNG filtertype heuristic was fixed, so that it chooses much
+    better ones (it's quite significant). A setting to do an experimental, slow,
+    brute force search for PNG filter types is added.
+*) 17 aug 2011 (!): changed some C zlib related function names.
+*) 16 aug 2011: made the code less wide (max 120 characters per line).
+*) 17 apr 2011: code cleanup. Bugfixes. Convert low to 16-bit per sample colors.
+*) 21 feb 2011: fixed compiling for C90. Fixed compiling with sections disabled.
+*) 11 dec 2010: encoding is made faster, based on suggestion by Peter Eastman
+    to optimize long sequences of zeros.
+*) 13 nov 2010: added LodePNG_InfoColor_hasPaletteAlpha and
+    LodePNG_InfoColor_canHaveAlpha functions for convenience.
+*) 7 nov 2010: added LodePNG_error_text function to get error code description.
+*) 30 okt 2010: made decoding slightly faster
+*) 26 okt 2010: (!) changed some C function and struct names (more consistent).
+     Reorganized the documentation and the declaration order in the header.
+*) 08 aug 2010: only changed some comments and external samples.
+*) 05 jul 2010: fixed bug thanks to warnings in the new gcc version.
+*) 14 mar 2010: fixed bug where too much memory was allocated for char buffers.
+*) 02 sep 2008: fixed bug where it could create empty tree that linux apps could
+    read by ignoring the problem but windows apps couldn't.
+*) 06 jun 2008: added more error checks for out of memory cases.
+*) 26 apr 2008: added a few more checks here and there to ensure more safety.
+*) 06 mar 2008: crash with encoding of strings fixed
+*) 02 feb 2008: support for international text chunks added (iTXt)
+*) 23 jan 2008: small cleanups, and #defines to divide code in sections
+*) 20 jan 2008: support for unknown chunks allowing using LodePNG for an editor.
+*) 18 jan 2008: support for tIME and pHYs chunks added to encoder and decoder.
+*) 17 jan 2008: ability to encode and decode compressed zTXt chunks added
+    Also various fixes, such as in the deflate and the padding bits code.
+*) 13 jan 2008: Added ability to encode Adam7-interlaced images. Improved
+    filtering code of encoder.
+*) 07 jan 2008: (!) changed LodePNG to use ISO C90 instead of C++. A
+    C++ wrapper around this provides an interface almost identical to before.
+    Having LodePNG be pure ISO C90 makes it more portable. The C and C++ code
+    are together in these files but it works both for C and C++ compilers.
+*) 29 dec 2007: (!) changed most integer types to unsigned int + other tweaks
+*) 30 aug 2007: bug fixed which makes this Borland C++ compatible
+*) 09 aug 2007: some VS2005 warnings removed again
+*) 21 jul 2007: deflate code placed in new namespace separate from zlib code
+*) 08 jun 2007: fixed bug with 2- and 4-bit color, and small interlaced images
+*) 04 jun 2007: improved support for Visual Studio 2005: crash with accessing
+    invalid std::vector element [0] fixed, and level 3 and 4 warnings removed
+*) 02 jun 2007: made the encoder add a tag with version by default
+*) 27 may 2007: zlib and png code separated (but still in the same file),
+    simple encoder/decoder functions added for more simple usage cases
+*) 19 may 2007: minor fixes, some code cleaning, new error added (error 69),
+    moved some examples from here to lodepng_examples.cpp
+*) 12 may 2007: palette decoding bug fixed
+*) 24 apr 2007: changed the license from BSD to the zlib license
+*) 11 mar 2007: very simple addition: ability to encode bKGD chunks.
+*) 04 mar 2007: (!) tEXt chunk related fixes, and support for encoding
+    palettized PNG images. Plus little interface change with palette and texts.
+*) 03 mar 2007: Made it encode dynamic Huffman shorter with repeat codes.
+    Fixed a bug where the end code of a block had length 0 in the Huffman tree.
+*) 26 feb 2007: Huffman compression with dynamic trees (BTYPE 2) now implemented
+    and supported by the encoder, resulting in smaller PNGs at the output.
+*) 27 jan 2007: Made the Adler-32 test faster so that a timewaste is gone.
+*) 24 jan 2007: gave encoder an error interface. Added color conversion from any
+    greyscale type to 8-bit greyscale with or without alpha.
+*) 21 jan 2007: (!) Totally changed the interface. It allows more color types
+    to convert to and is more uniform. See the manual for how it works now.
+*) 07 jan 2007: Some cleanup & fixes, and a few changes over the last days:
+    encode/decode custom tEXt chunks, separate classes for zlib & deflate, and
+    at last made the decoder give errors for incorrect Adler32 or Crc.
+*) 01 jan 2007: Fixed bug with encoding PNGs with less than 8 bits per channel.
+*) 29 dec 2006: Added support for encoding images without alpha channel, and
+    cleaned out code as well as making certain parts faster.
+*) 28 dec 2006: Added "Settings" to the encoder.
+*) 26 dec 2006: The encoder now does LZ77 encoding and produces much smaller files now.
+    Removed some code duplication in the decoder. Fixed little bug in an example.
+*) 09 dec 2006: (!) Placed output parameters of public functions as first parameter.
+    Fixed a bug of the decoder with 16-bit per color.
+*) 15 okt 2006: Changed documentation structure
+*) 09 okt 2006: Encoder class added. It encodes a valid PNG image from the
+    given image buffer, however for now it's not compressed.
+*) 08 sep 2006: (!) Changed to interface with a Decoder class
+*) 30 jul 2006: (!) LodePNG_InfoPng , width and height are now retrieved in different
+    way. Renamed decodePNG to decodePNGGeneric.
+*) 29 jul 2006: (!) Changed the interface: image info is now returned as a
+    struct of type LodePNG::LodePNG_Info, instead of a vector, which was a bit clumsy.
+*) 28 jul 2006: Cleaned the code and added new error checks.
+    Corrected terminology "deflate" into "inflate".
+*) 23 jun 2006: Added SDL example in the documentation in the header, this
+    example allows easy debugging by displaying the PNG and its transparency.
+*) 22 jun 2006: (!) Changed way to obtain error value. Added
+    loadFile function for convenience. Made decodePNG32 faster.
+*) 21 jun 2006: (!) Changed type of info vector to unsigned.
+    Changed position of palette in info vector. Fixed an important bug that
+    happened on PNGs with an uncompressed block.
+*) 16 jun 2006: Internally changed unsigned into unsigned where
+    needed, and performed some optimizations.
+*) 07 jun 2006: (!) Renamed functions to decodePNG and placed them
+    in LodePNG namespace. Changed the order of the parameters. Rewrote the
+    documentation in the header. Renamed files to lodepng.cpp and lodepng.h
+*) 22 apr 2006: Optimized and improved some code
+*) 07 sep 2005: (!) Changed to std::vector interface
+*) 12 aug 2005: Initial release (C++, decoder only)
+
+
+13. contact information
+-----------------------
+
+Feel free to contact me with suggestions, problems, comments, ... concerning
+LodePNG. If you encounter a PNG image that doesn't work properly with this
+decoder, feel free to send it and I'll use it to find and fix the problem.
+
+My email address is (puzzle the account and domain together with an @ symbol):
+Domain: gmail dot com.
+Account: lode dot vandevenne.
+
+
+Copyright (c) 2005-2016 Lode Vandevenne
+*/

+ 2102 - 0
include/tinyxml2.h

@@ -0,0 +1,2102 @@
+/*
+Original code by Lee Thomason (www.grinninglizard.com)
+
+This software is provided 'as-is', without any express or implied
+warranty. In no event will the authors be held liable for any
+damages arising from the use of this software.
+
+Permission is granted to anyone to use this software for any
+purpose, including commercial applications, and to alter it and
+redistribute it freely, subject to the following restrictions:
+
+1. The origin of this software must not be misrepresented; you must
+not claim that you wrote the original software. If you use this
+software in a product, an acknowledgment in the product documentation
+would be appreciated but is not required.
+
+2. Altered source versions must be plainly marked as such, and
+must not be misrepresented as being the original software.
+
+3. This notice may not be removed or altered from any source
+distribution.
+*/
+
+#ifndef TINYXML2_INCLUDED
+#define TINYXML2_INCLUDED
+
+#if defined(ANDROID_NDK) || defined(__BORLANDC__) || defined(__QNXNTO__)
+#   include <ctype.h>
+#   include <limits.h>
+#   include <stdio.h>
+#   include <stdlib.h>
+#   include <string.h>
+#else
+#   include <cctype>
+#   include <climits>
+#   include <cstdio>
+#   include <cstdlib>
+#   include <cstring>
+#endif
+
+/*
+   TODO: intern strings instead of allocation.
+*/
+/*
+	gcc:
+        g++ -Wall -DDEBUG tinyxml2.cpp xmltest.cpp -o gccxmltest.exe
+
+    Formatting, Artistic Style:
+        AStyle.exe --style=1tbs --indent-switches --break-closing-brackets --indent-preprocessor tinyxml2.cpp tinyxml2.h
+*/
+
+#if defined( _DEBUG ) || defined( DEBUG ) || defined (__DEBUG__)
+#   ifndef DEBUG
+#       define DEBUG
+#   endif
+#endif
+
+#ifdef _MSC_VER
+#   pragma warning(push)
+#   pragma warning(disable: 4251)
+#endif
+
+#ifdef _WIN32
+#   ifdef TINYXML2_EXPORT
+#       define TINYXML2_LIB __declspec(dllexport)
+#   elif defined(TINYXML2_IMPORT)
+#       define TINYXML2_LIB __declspec(dllimport)
+#   else
+#       define TINYXML2_LIB
+#   endif
+#else
+#   define TINYXML2_LIB
+#endif
+
+
+#if defined(DEBUG)
+#   if defined(_MSC_VER)
+#       // "(void)0," is for suppressing C4127 warning in "assert(false)", "assert(true)" and the like
+#       define TIXMLASSERT( x )           if ( !((void)0,(x))) { __debugbreak(); }
+#   elif defined (ANDROID_NDK)
+#       include <android/log.h>
+#       define TIXMLASSERT( x )           if ( !(x)) { __android_log_assert( "assert", "grinliz", "ASSERT in '%s' at %d.", __FILE__, __LINE__ ); }
+#   else
+#       include <assert.h>
+#       define TIXMLASSERT                assert
+#   endif
+#else
+#   define TIXMLASSERT( x )               {}
+#endif
+
+
+/* Versioning, past 1.0.14:
+	http://semver.org/
+*/
+static const int TIXML2_MAJOR_VERSION = 3;
+static const int TIXML2_MINOR_VERSION = 0;
+static const int TIXML2_PATCH_VERSION = 0;
+
+namespace tinyxml2
+{
+class XMLDocument;
+class XMLElement;
+class XMLAttribute;
+class XMLComment;
+class XMLText;
+class XMLDeclaration;
+class XMLUnknown;
+class XMLPrinter;
+
+/*
+	A class that wraps strings. Normally stores the start and end
+	pointers into the XML file itself, and will apply normalization
+	and entity translation if actually read. Can also store (and memory
+	manage) a traditional char[]
+*/
+class StrPair
+{
+public:
+    enum {
+        NEEDS_ENTITY_PROCESSING			= 0x01,
+        NEEDS_NEWLINE_NORMALIZATION		= 0x02,
+        NEEDS_WHITESPACE_COLLAPSING     = 0x04,
+
+        TEXT_ELEMENT		            	= NEEDS_ENTITY_PROCESSING | NEEDS_NEWLINE_NORMALIZATION,
+        TEXT_ELEMENT_LEAVE_ENTITIES		= NEEDS_NEWLINE_NORMALIZATION,
+        ATTRIBUTE_NAME		            	= 0,
+        ATTRIBUTE_VALUE		            	= NEEDS_ENTITY_PROCESSING | NEEDS_NEWLINE_NORMALIZATION,
+        ATTRIBUTE_VALUE_LEAVE_ENTITIES  	= NEEDS_NEWLINE_NORMALIZATION,
+        COMMENT				        = NEEDS_NEWLINE_NORMALIZATION
+    };
+
+    StrPair() : _flags( 0 ), _start( 0 ), _end( 0 ) {}
+    ~StrPair();
+
+    void Set( char* start, char* end, int flags ) {
+        Reset();
+        _start  = start;
+        _end    = end;
+        _flags  = flags | NEEDS_FLUSH;
+    }
+
+    const char* GetStr();
+
+    bool Empty() const {
+        return _start == _end;
+    }
+
+    void SetInternedStr( const char* str ) {
+        Reset();
+        _start = const_cast<char*>(str);
+    }
+
+    void SetStr( const char* str, int flags=0 );
+
+    char* ParseText( char* in, const char* endTag, int strFlags );
+    char* ParseName( char* in );
+
+    void TransferTo( StrPair* other );
+
+private:
+    void Reset();
+    void CollapseWhitespace();
+
+    enum {
+        NEEDS_FLUSH = 0x100,
+        NEEDS_DELETE = 0x200
+    };
+
+    int     _flags;
+    char*   _start;
+    char*   _end;
+
+    StrPair( const StrPair& other );	// not supported
+    void operator=( StrPair& other );	// not supported, use TransferTo()
+};
+
+
+/*
+	A dynamic array of Plain Old Data. Doesn't support constructors, etc.
+	Has a small initial memory pool, so that low or no usage will not
+	cause a call to new/delete
+*/
+template <class T, int INITIAL_SIZE>
+class DynArray
+{
+public:
+    DynArray() {
+        _mem = _pool;
+        _allocated = INITIAL_SIZE;
+        _size = 0;
+    }
+
+    ~DynArray() {
+        if ( _mem != _pool ) {
+            delete [] _mem;
+        }
+    }
+
+    void Clear() {
+        _size = 0;
+    }
+
+    void Push( T t ) {
+        TIXMLASSERT( _size < INT_MAX );
+        EnsureCapacity( _size+1 );
+        _mem[_size++] = t;
+    }
+
+    T* PushArr( int count ) {
+        TIXMLASSERT( count >= 0 );
+        TIXMLASSERT( _size <= INT_MAX - count );
+        EnsureCapacity( _size+count );
+        T* ret = &_mem[_size];
+        _size += count;
+        return ret;
+    }
+
+    T Pop() {
+        TIXMLASSERT( _size > 0 );
+        return _mem[--_size];
+    }
+
+    void PopArr( int count ) {
+        TIXMLASSERT( _size >= count );
+        _size -= count;
+    }
+
+    bool Empty() const					{
+        return _size == 0;
+    }
+
+    T& operator[](int i)				{
+        TIXMLASSERT( i>= 0 && i < _size );
+        return _mem[i];
+    }
+
+    const T& operator[](int i) const	{
+        TIXMLASSERT( i>= 0 && i < _size );
+        return _mem[i];
+    }
+
+    const T& PeekTop() const            {
+        TIXMLASSERT( _size > 0 );
+        return _mem[ _size - 1];
+    }
+
+    int Size() const					{
+        TIXMLASSERT( _size >= 0 );
+        return _size;
+    }
+
+    int Capacity() const				{
+        TIXMLASSERT( _allocated >= INITIAL_SIZE );
+        return _allocated;
+    }
+
+    const T* Mem() const				{
+        TIXMLASSERT( _mem );
+        return _mem;
+    }
+
+    T* Mem()							{
+        TIXMLASSERT( _mem );
+        return _mem;
+    }
+
+private:
+    DynArray( const DynArray& ); // not supported
+    void operator=( const DynArray& ); // not supported
+
+    void EnsureCapacity( int cap ) {
+        TIXMLASSERT( cap > 0 );
+        if ( cap > _allocated ) {
+            TIXMLASSERT( cap <= INT_MAX / 2 );
+            int newAllocated = cap * 2;
+            T* newMem = new T[newAllocated];
+            memcpy( newMem, _mem, sizeof(T)*_size );	// warning: not using constructors, only works for PODs
+            if ( _mem != _pool ) {
+                delete [] _mem;
+            }
+            _mem = newMem;
+            _allocated = newAllocated;
+        }
+    }
+
+    T*  _mem;
+    T   _pool[INITIAL_SIZE];
+    int _allocated;		// objects allocated
+    int _size;			// number objects in use
+};
+
+
+/*
+	Parent virtual class of a pool for fast allocation
+	and deallocation of objects.
+*/
+class MemPool
+{
+public:
+    MemPool() {}
+    virtual ~MemPool() {}
+
+    virtual int ItemSize() const = 0;
+    virtual void* Alloc() = 0;
+    virtual void Free( void* ) = 0;
+    virtual void SetTracked() = 0;
+    virtual void Clear() = 0;
+};
+
+
+/*
+	Template child class to create pools of the correct type.
+*/
+template< int SIZE >
+class MemPoolT : public MemPool
+{
+public:
+    MemPoolT() : _root(0), _currentAllocs(0), _nAllocs(0), _maxAllocs(0), _nUntracked(0)	{}
+    ~MemPoolT() {
+        Clear();
+    }
+    
+    void Clear() {
+        // Delete the blocks.
+        while( !_blockPtrs.Empty()) {
+            Block* b  = _blockPtrs.Pop();
+            delete b;
+        }
+        _root = 0;
+        _currentAllocs = 0;
+        _nAllocs = 0;
+        _maxAllocs = 0;
+        _nUntracked = 0;
+    }
+
+    virtual int ItemSize() const	{
+        return SIZE;
+    }
+    int CurrentAllocs() const		{
+        return _currentAllocs;
+    }
+
+    virtual void* Alloc() {
+        if ( !_root ) {
+            // Need a new block.
+            Block* block = new Block();
+            _blockPtrs.Push( block );
+
+            for( int i=0; i<COUNT-1; ++i ) {
+                block->chunk[i].next = &block->chunk[i+1];
+            }
+            block->chunk[COUNT-1].next = 0;
+            _root = block->chunk;
+        }
+        void* result = _root;
+        _root = _root->next;
+
+        ++_currentAllocs;
+        if ( _currentAllocs > _maxAllocs ) {
+            _maxAllocs = _currentAllocs;
+        }
+        _nAllocs++;
+        _nUntracked++;
+        return result;
+    }
+    
+    virtual void Free( void* mem ) {
+        if ( !mem ) {
+            return;
+        }
+        --_currentAllocs;
+        Chunk* chunk = static_cast<Chunk*>( mem );
+#ifdef DEBUG
+        memset( chunk, 0xfe, sizeof(Chunk) );
+#endif
+        chunk->next = _root;
+        _root = chunk;
+    }
+    void Trace( const char* name ) {
+        printf( "Mempool %s watermark=%d [%dk] current=%d size=%d nAlloc=%d blocks=%d\n",
+                name, _maxAllocs, _maxAllocs*SIZE/1024, _currentAllocs, SIZE, _nAllocs, _blockPtrs.Size() );
+    }
+
+    void SetTracked() {
+        _nUntracked--;
+    }
+
+    int Untracked() const {
+        return _nUntracked;
+    }
+
+	// This number is perf sensitive. 4k seems like a good tradeoff on my machine.
+	// The test file is large, 170k.
+	// Release:		VS2010 gcc(no opt)
+	//		1k:		4000
+	//		2k:		4000
+	//		4k:		3900	21000
+	//		16k:	5200
+	//		32k:	4300
+	//		64k:	4000	21000
+    enum { COUNT = (4*1024)/SIZE }; // Some compilers do not accept to use COUNT in private part if COUNT is private
+
+private:
+    MemPoolT( const MemPoolT& ); // not supported
+    void operator=( const MemPoolT& ); // not supported
+
+    union Chunk {
+        Chunk*  next;
+        char    mem[SIZE];
+    };
+    struct Block {
+        Chunk chunk[COUNT];
+    };
+    DynArray< Block*, 10 > _blockPtrs;
+    Chunk* _root;
+
+    int _currentAllocs;
+    int _nAllocs;
+    int _maxAllocs;
+    int _nUntracked;
+};
+
+
+
+/**
+	Implements the interface to the "Visitor pattern" (see the Accept() method.)
+	If you call the Accept() method, it requires being passed a XMLVisitor
+	class to handle callbacks. For nodes that contain other nodes (Document, Element)
+	you will get called with a VisitEnter/VisitExit pair. Nodes that are always leafs
+	are simply called with Visit().
+
+	If you return 'true' from a Visit method, recursive parsing will continue. If you return
+	false, <b>no children of this node or its siblings</b> will be visited.
+
+	All flavors of Visit methods have a default implementation that returns 'true' (continue
+	visiting). You need to only override methods that are interesting to you.
+
+	Generally Accept() is called on the XMLDocument, although all nodes support visiting.
+
+	You should never change the document from a callback.
+
+	@sa XMLNode::Accept()
+*/
+class TINYXML2_LIB XMLVisitor
+{
+public:
+    virtual ~XMLVisitor() {}
+
+    /// Visit a document.
+    virtual bool VisitEnter( const XMLDocument& /*doc*/ )			{
+        return true;
+    }
+    /// Visit a document.
+    virtual bool VisitExit( const XMLDocument& /*doc*/ )			{
+        return true;
+    }
+
+    /// Visit an element.
+    virtual bool VisitEnter( const XMLElement& /*element*/, const XMLAttribute* /*firstAttribute*/ )	{
+        return true;
+    }
+    /// Visit an element.
+    virtual bool VisitExit( const XMLElement& /*element*/ )			{
+        return true;
+    }
+
+    /// Visit a declaration.
+    virtual bool Visit( const XMLDeclaration& /*declaration*/ )		{
+        return true;
+    }
+    /// Visit a text node.
+    virtual bool Visit( const XMLText& /*text*/ )					{
+        return true;
+    }
+    /// Visit a comment node.
+    virtual bool Visit( const XMLComment& /*comment*/ )				{
+        return true;
+    }
+    /// Visit an unknown node.
+    virtual bool Visit( const XMLUnknown& /*unknown*/ )				{
+        return true;
+    }
+};
+
+// WARNING: must match XMLDocument::_errorNames[]
+enum XMLError {
+    XML_SUCCESS = 0,
+    XML_NO_ERROR = 0,
+    XML_NO_ATTRIBUTE,
+    XML_WRONG_ATTRIBUTE_TYPE,
+    XML_ERROR_FILE_NOT_FOUND,
+    XML_ERROR_FILE_COULD_NOT_BE_OPENED,
+    XML_ERROR_FILE_READ_ERROR,
+    XML_ERROR_ELEMENT_MISMATCH,
+    XML_ERROR_PARSING_ELEMENT,
+    XML_ERROR_PARSING_ATTRIBUTE,
+    XML_ERROR_IDENTIFYING_TAG,
+    XML_ERROR_PARSING_TEXT,
+    XML_ERROR_PARSING_CDATA,
+    XML_ERROR_PARSING_COMMENT,
+    XML_ERROR_PARSING_DECLARATION,
+    XML_ERROR_PARSING_UNKNOWN,
+    XML_ERROR_EMPTY_DOCUMENT,
+    XML_ERROR_MISMATCHED_ELEMENT,
+    XML_ERROR_PARSING,
+    XML_CAN_NOT_CONVERT_TEXT,
+    XML_NO_TEXT_NODE,
+
+	XML_ERROR_COUNT
+};
+
+
+/*
+	Utility functionality.
+*/
+class XMLUtil
+{
+public:
+    static const char* SkipWhiteSpace( const char* p )	{
+        TIXMLASSERT( p );
+        while( IsWhiteSpace(*p) ) {
+            ++p;
+        }
+        TIXMLASSERT( p );
+        return p;
+    }
+    static char* SkipWhiteSpace( char* p )				{
+        return const_cast<char*>( SkipWhiteSpace( const_cast<const char*>(p) ) );
+    }
+
+    // Anything in the high order range of UTF-8 is assumed to not be whitespace. This isn't
+    // correct, but simple, and usually works.
+    static bool IsWhiteSpace( char p )					{
+        return !IsUTF8Continuation(p) && isspace( static_cast<unsigned char>(p) );
+    }
+    
+    inline static bool IsNameStartChar( unsigned char ch ) {
+        if ( ch >= 128 ) {
+            // This is a heuristic guess in attempt to not implement Unicode-aware isalpha()
+            return true;
+        }
+        if ( isalpha( ch ) ) {
+            return true;
+        }
+        return ch == ':' || ch == '_';
+    }
+    
+    inline static bool IsNameChar( unsigned char ch ) {
+        return IsNameStartChar( ch )
+               || isdigit( ch )
+               || ch == '.'
+               || ch == '-';
+    }
+
+    inline static bool StringEqual( const char* p, const char* q, int nChar=INT_MAX )  {
+        if ( p == q ) {
+            return true;
+        }
+        return strncmp( p, q, nChar ) == 0;
+    }
+    
+    inline static bool IsUTF8Continuation( char p ) {
+        return ( p & 0x80 ) != 0;
+    }
+
+    static const char* ReadBOM( const char* p, bool* hasBOM );
+    // p is the starting location,
+    // the UTF-8 value of the entity will be placed in value, and length filled in.
+    static const char* GetCharacterRef( const char* p, char* value, int* length );
+    static void ConvertUTF32ToUTF8( unsigned long input, char* output, int* length );
+
+    // converts primitive types to strings
+    static void ToStr( int v, char* buffer, int bufferSize );
+    static void ToStr( unsigned v, char* buffer, int bufferSize );
+    static void ToStr( bool v, char* buffer, int bufferSize );
+    static void ToStr( float v, char* buffer, int bufferSize );
+    static void ToStr( double v, char* buffer, int bufferSize );
+
+    // converts strings to primitive types
+    static bool	ToInt( const char* str, int* value );
+    static bool ToUnsigned( const char* str, unsigned* value );
+    static bool	ToBool( const char* str, bool* value );
+    static bool	ToFloat( const char* str, float* value );
+    static bool ToDouble( const char* str, double* value );
+};
+
+
+/** XMLNode is a base class for every object that is in the
+	XML Document Object Model (DOM), except XMLAttributes.
+	Nodes have siblings, a parent, and children which can
+	be navigated. A node is always in a XMLDocument.
+	The type of a XMLNode can be queried, and it can
+	be cast to its more defined type.
+
+	A XMLDocument allocates memory for all its Nodes.
+	When the XMLDocument gets deleted, all its Nodes
+	will also be deleted.
+
+	@verbatim
+	A Document can contain:	Element	(container or leaf)
+							Comment (leaf)
+							Unknown (leaf)
+							Declaration( leaf )
+
+	An Element can contain:	Element (container or leaf)
+							Text	(leaf)
+							Attributes (not on tree)
+							Comment (leaf)
+							Unknown (leaf)
+
+	@endverbatim
+*/
+class TINYXML2_LIB XMLNode
+{
+    friend class XMLDocument;
+    friend class XMLElement;
+public:
+
+    /// Get the XMLDocument that owns this XMLNode.
+    const XMLDocument* GetDocument() const	{
+        TIXMLASSERT( _document );
+        return _document;
+    }
+    /// Get the XMLDocument that owns this XMLNode.
+    XMLDocument* GetDocument()				{
+        TIXMLASSERT( _document );
+        return _document;
+    }
+
+    /// Safely cast to an Element, or null.
+    virtual XMLElement*		ToElement()		{
+        return 0;
+    }
+    /// Safely cast to Text, or null.
+    virtual XMLText*		ToText()		{
+        return 0;
+    }
+    /// Safely cast to a Comment, or null.
+    virtual XMLComment*		ToComment()		{
+        return 0;
+    }
+    /// Safely cast to a Document, or null.
+    virtual XMLDocument*	ToDocument()	{
+        return 0;
+    }
+    /// Safely cast to a Declaration, or null.
+    virtual XMLDeclaration*	ToDeclaration()	{
+        return 0;
+    }
+    /// Safely cast to an Unknown, or null.
+    virtual XMLUnknown*		ToUnknown()		{
+        return 0;
+    }
+
+    virtual const XMLElement*		ToElement() const		{
+        return 0;
+    }
+    virtual const XMLText*			ToText() const			{
+        return 0;
+    }
+    virtual const XMLComment*		ToComment() const		{
+        return 0;
+    }
+    virtual const XMLDocument*		ToDocument() const		{
+        return 0;
+    }
+    virtual const XMLDeclaration*	ToDeclaration() const	{
+        return 0;
+    }
+    virtual const XMLUnknown*		ToUnknown() const		{
+        return 0;
+    }
+
+    /** The meaning of 'value' changes for the specific type.
+    	@verbatim
+    	Document:	empty (NULL is returned, not an empty string)
+    	Element:	name of the element
+    	Comment:	the comment text
+    	Unknown:	the tag contents
+    	Text:		the text string
+    	@endverbatim
+    */
+    const char* Value() const;
+
+    /** Set the Value of an XML node.
+    	@sa Value()
+    */
+    void SetValue( const char* val, bool staticMem=false );
+
+    /// Get the parent of this node on the DOM.
+    const XMLNode*	Parent() const			{
+        return _parent;
+    }
+
+    XMLNode* Parent()						{
+        return _parent;
+    }
+
+    /// Returns true if this node has no children.
+    bool NoChildren() const					{
+        return !_firstChild;
+    }
+
+    /// Get the first child node, or null if none exists.
+    const XMLNode*  FirstChild() const		{
+        return _firstChild;
+    }
+
+    XMLNode*		FirstChild()			{
+        return _firstChild;
+    }
+
+    /** Get the first child element, or optionally the first child
+        element with the specified name.
+    */
+    const XMLElement* FirstChildElement( const char* name = 0 ) const;
+
+    XMLElement* FirstChildElement( const char* name = 0 )	{
+        return const_cast<XMLElement*>(const_cast<const XMLNode*>(this)->FirstChildElement( name ));
+    }
+
+    /// Get the last child node, or null if none exists.
+    const XMLNode*	LastChild() const						{
+        return _lastChild;
+    }
+
+    XMLNode*		LastChild()								{
+        return _lastChild;
+    }
+
+    /** Get the last child element or optionally the last child
+        element with the specified name.
+    */
+    const XMLElement* LastChildElement( const char* name = 0 ) const;
+
+    XMLElement* LastChildElement( const char* name = 0 )	{
+        return const_cast<XMLElement*>(const_cast<const XMLNode*>(this)->LastChildElement(name) );
+    }
+
+    /// Get the previous (left) sibling node of this node.
+    const XMLNode*	PreviousSibling() const					{
+        return _prev;
+    }
+
+    XMLNode*	PreviousSibling()							{
+        return _prev;
+    }
+
+    /// Get the previous (left) sibling element of this node, with an optionally supplied name.
+    const XMLElement*	PreviousSiblingElement( const char* name = 0 ) const ;
+
+    XMLElement*	PreviousSiblingElement( const char* name = 0 ) {
+        return const_cast<XMLElement*>(const_cast<const XMLNode*>(this)->PreviousSiblingElement( name ) );
+    }
+
+    /// Get the next (right) sibling node of this node.
+    const XMLNode*	NextSibling() const						{
+        return _next;
+    }
+
+    XMLNode*	NextSibling()								{
+        return _next;
+    }
+
+    /// Get the next (right) sibling element of this node, with an optionally supplied name.
+    const XMLElement*	NextSiblingElement( const char* name = 0 ) const;
+
+    XMLElement*	NextSiblingElement( const char* name = 0 )	{
+        return const_cast<XMLElement*>(const_cast<const XMLNode*>(this)->NextSiblingElement( name ) );
+    }
+
+    /**
+    	Add a child node as the last (right) child.
+		If the child node is already part of the document,
+		it is moved from its old location to the new location.
+		Returns the addThis argument or 0 if the node does not
+		belong to the same document.
+    */
+    XMLNode* InsertEndChild( XMLNode* addThis );
+
+    XMLNode* LinkEndChild( XMLNode* addThis )	{
+        return InsertEndChild( addThis );
+    }
+    /**
+    	Add a child node as the first (left) child.
+		If the child node is already part of the document,
+		it is moved from its old location to the new location.
+		Returns the addThis argument or 0 if the node does not
+		belong to the same document.
+    */
+    XMLNode* InsertFirstChild( XMLNode* addThis );
+    /**
+    	Add a node after the specified child node.
+		If the child node is already part of the document,
+		it is moved from its old location to the new location.
+		Returns the addThis argument or 0 if the afterThis node
+		is not a child of this node, or if the node does not
+		belong to the same document.
+    */
+    XMLNode* InsertAfterChild( XMLNode* afterThis, XMLNode* addThis );
+
+    /**
+    	Delete all the children of this node.
+    */
+    void DeleteChildren();
+
+    /**
+    	Delete a child of this node.
+    */
+    void DeleteChild( XMLNode* node );
+
+    /**
+    	Make a copy of this node, but not its children.
+    	You may pass in a Document pointer that will be
+    	the owner of the new Node. If the 'document' is
+    	null, then the node returned will be allocated
+    	from the current Document. (this->GetDocument())
+
+    	Note: if called on a XMLDocument, this will return null.
+    */
+    virtual XMLNode* ShallowClone( XMLDocument* document ) const = 0;
+
+    /**
+    	Test if 2 nodes are the same, but don't test children.
+    	The 2 nodes do not need to be in the same Document.
+
+    	Note: if called on a XMLDocument, this will return false.
+    */
+    virtual bool ShallowEqual( const XMLNode* compare ) const = 0;
+
+    /** Accept a hierarchical visit of the nodes in the TinyXML-2 DOM. Every node in the
+    	XML tree will be conditionally visited and the host will be called back
+    	via the XMLVisitor interface.
+
+    	This is essentially a SAX interface for TinyXML-2. (Note however it doesn't re-parse
+    	the XML for the callbacks, so the performance of TinyXML-2 is unchanged by using this
+    	interface versus any other.)
+
+    	The interface has been based on ideas from:
+
+    	- http://www.saxproject.org/
+    	- http://c2.com/cgi/wiki?HierarchicalVisitorPattern
+
+    	Which are both good references for "visiting".
+
+    	An example of using Accept():
+    	@verbatim
+    	XMLPrinter printer;
+    	tinyxmlDoc.Accept( &printer );
+    	const char* xmlcstr = printer.CStr();
+    	@endverbatim
+    */
+    virtual bool Accept( XMLVisitor* visitor ) const = 0;
+
+protected:
+    XMLNode( XMLDocument* );
+    virtual ~XMLNode();
+
+    virtual char* ParseDeep( char*, StrPair* );
+
+    XMLDocument*	_document;
+    XMLNode*		_parent;
+    mutable StrPair	_value;
+
+    XMLNode*		_firstChild;
+    XMLNode*		_lastChild;
+
+    XMLNode*		_prev;
+    XMLNode*		_next;
+
+private:
+    MemPool*		_memPool;
+    void Unlink( XMLNode* child );
+    static void DeleteNode( XMLNode* node );
+    void InsertChildPreamble( XMLNode* insertThis ) const;
+
+    XMLNode( const XMLNode& );	// not supported
+    XMLNode& operator=( const XMLNode& );	// not supported
+};
+
+
+/** XML text.
+
+	Note that a text node can have child element nodes, for example:
+	@verbatim
+	<root>This is <b>bold</b></root>
+	@endverbatim
+
+	A text node can have 2 ways to output the next. "normal" output
+	and CDATA. It will default to the mode it was parsed from the XML file and
+	you generally want to leave it alone, but you can change the output mode with
+	SetCData() and query it with CData().
+*/
+class TINYXML2_LIB XMLText : public XMLNode
+{
+    friend class XMLBase;
+    friend class XMLDocument;
+public:
+    virtual bool Accept( XMLVisitor* visitor ) const;
+
+    virtual XMLText* ToText()			{
+        return this;
+    }
+    virtual const XMLText* ToText() const	{
+        return this;
+    }
+
+    /// Declare whether this should be CDATA or standard text.
+    void SetCData( bool isCData )			{
+        _isCData = isCData;
+    }
+    /// Returns true if this is a CDATA text element.
+    bool CData() const						{
+        return _isCData;
+    }
+
+    virtual XMLNode* ShallowClone( XMLDocument* document ) const;
+    virtual bool ShallowEqual( const XMLNode* compare ) const;
+
+protected:
+    XMLText( XMLDocument* doc )	: XMLNode( doc ), _isCData( false )	{}
+    virtual ~XMLText()												{}
+
+    char* ParseDeep( char*, StrPair* endTag );
+
+private:
+    bool _isCData;
+
+    XMLText( const XMLText& );	// not supported
+    XMLText& operator=( const XMLText& );	// not supported
+};
+
+
+/** An XML Comment. */
+class TINYXML2_LIB XMLComment : public XMLNode
+{
+    friend class XMLDocument;
+public:
+    virtual XMLComment*	ToComment()					{
+        return this;
+    }
+    virtual const XMLComment* ToComment() const		{
+        return this;
+    }
+
+    virtual bool Accept( XMLVisitor* visitor ) const;
+
+    virtual XMLNode* ShallowClone( XMLDocument* document ) const;
+    virtual bool ShallowEqual( const XMLNode* compare ) const;
+
+protected:
+    XMLComment( XMLDocument* doc );
+    virtual ~XMLComment();
+
+    char* ParseDeep( char*, StrPair* endTag );
+
+private:
+    XMLComment( const XMLComment& );	// not supported
+    XMLComment& operator=( const XMLComment& );	// not supported
+};
+
+
+/** In correct XML the declaration is the first entry in the file.
+	@verbatim
+		<?xml version="1.0" standalone="yes"?>
+	@endverbatim
+
+	TinyXML-2 will happily read or write files without a declaration,
+	however.
+
+	The text of the declaration isn't interpreted. It is parsed
+	and written as a string.
+*/
+class TINYXML2_LIB XMLDeclaration : public XMLNode
+{
+    friend class XMLDocument;
+public:
+    virtual XMLDeclaration*	ToDeclaration()					{
+        return this;
+    }
+    virtual const XMLDeclaration* ToDeclaration() const		{
+        return this;
+    }
+
+    virtual bool Accept( XMLVisitor* visitor ) const;
+
+    virtual XMLNode* ShallowClone( XMLDocument* document ) const;
+    virtual bool ShallowEqual( const XMLNode* compare ) const;
+
+protected:
+    XMLDeclaration( XMLDocument* doc );
+    virtual ~XMLDeclaration();
+
+    char* ParseDeep( char*, StrPair* endTag );
+
+private:
+    XMLDeclaration( const XMLDeclaration& );	// not supported
+    XMLDeclaration& operator=( const XMLDeclaration& );	// not supported
+};
+
+
+/** Any tag that TinyXML-2 doesn't recognize is saved as an
+	unknown. It is a tag of text, but should not be modified.
+	It will be written back to the XML, unchanged, when the file
+	is saved.
+
+	DTD tags get thrown into XMLUnknowns.
+*/
+class TINYXML2_LIB XMLUnknown : public XMLNode
+{
+    friend class XMLDocument;
+public:
+    virtual XMLUnknown*	ToUnknown()					{
+        return this;
+    }
+    virtual const XMLUnknown* ToUnknown() const		{
+        return this;
+    }
+
+    virtual bool Accept( XMLVisitor* visitor ) const;
+
+    virtual XMLNode* ShallowClone( XMLDocument* document ) const;
+    virtual bool ShallowEqual( const XMLNode* compare ) const;
+
+protected:
+    XMLUnknown( XMLDocument* doc );
+    virtual ~XMLUnknown();
+
+    char* ParseDeep( char*, StrPair* endTag );
+
+private:
+    XMLUnknown( const XMLUnknown& );	// not supported
+    XMLUnknown& operator=( const XMLUnknown& );	// not supported
+};
+
+
+
+/** An attribute is a name-value pair. Elements have an arbitrary
+	number of attributes, each with a unique name.
+
+	@note The attributes are not XMLNodes. You may only query the
+	Next() attribute in a list.
+*/
+class TINYXML2_LIB XMLAttribute
+{
+    friend class XMLElement;
+public:
+    /// The name of the attribute.
+    const char* Name() const;
+
+    /// The value of the attribute.
+    const char* Value() const;
+
+    /// The next attribute in the list.
+    const XMLAttribute* Next() const {
+        return _next;
+    }
+
+    /** IntValue interprets the attribute as an integer, and returns the value.
+        If the value isn't an integer, 0 will be returned. There is no error checking;
+    	use QueryIntValue() if you need error checking.
+    */
+    int		 IntValue() const				{
+        int i=0;
+        QueryIntValue( &i );
+        return i;
+    }
+    /// Query as an unsigned integer. See IntValue()
+    unsigned UnsignedValue() const			{
+        unsigned i=0;
+        QueryUnsignedValue( &i );
+        return i;
+    }
+    /// Query as a boolean. See IntValue()
+    bool	 BoolValue() const				{
+        bool b=false;
+        QueryBoolValue( &b );
+        return b;
+    }
+    /// Query as a double. See IntValue()
+    double 	 DoubleValue() const			{
+        double d=0;
+        QueryDoubleValue( &d );
+        return d;
+    }
+    /// Query as a float. See IntValue()
+    float	 FloatValue() const				{
+        float f=0;
+        QueryFloatValue( &f );
+        return f;
+    }
+
+    /** QueryIntValue interprets the attribute as an integer, and returns the value
+    	in the provided parameter. The function will return XML_NO_ERROR on success,
+    	and XML_WRONG_ATTRIBUTE_TYPE if the conversion is not successful.
+    */
+    XMLError QueryIntValue( int* value ) const;
+    /// See QueryIntValue
+    XMLError QueryUnsignedValue( unsigned int* value ) const;
+    /// See QueryIntValue
+    XMLError QueryBoolValue( bool* value ) const;
+    /// See QueryIntValue
+    XMLError QueryDoubleValue( double* value ) const;
+    /// See QueryIntValue
+    XMLError QueryFloatValue( float* value ) const;
+
+    /// Set the attribute to a string value.
+    void SetAttribute( const char* value );
+    /// Set the attribute to value.
+    void SetAttribute( int value );
+    /// Set the attribute to value.
+    void SetAttribute( unsigned value );
+    /// Set the attribute to value.
+    void SetAttribute( bool value );
+    /// Set the attribute to value.
+    void SetAttribute( double value );
+    /// Set the attribute to value.
+    void SetAttribute( float value );
+
+private:
+    enum { BUF_SIZE = 200 };
+
+    XMLAttribute() : _next( 0 ), _memPool( 0 ) {}
+    virtual ~XMLAttribute()	{}
+
+    XMLAttribute( const XMLAttribute& );	// not supported
+    void operator=( const XMLAttribute& );	// not supported
+    void SetName( const char* name );
+
+    char* ParseDeep( char* p, bool processEntities );
+
+    mutable StrPair _name;
+    mutable StrPair _value;
+    XMLAttribute*   _next;
+    MemPool*        _memPool;
+};
+
+
+/** The element is a container class. It has a value, the element name,
+	and can contain other elements, text, comments, and unknowns.
+	Elements also contain an arbitrary number of attributes.
+*/
+class TINYXML2_LIB XMLElement : public XMLNode
+{
+    friend class XMLBase;
+    friend class XMLDocument;
+public:
+    /// Get the name of an element (which is the Value() of the node.)
+    const char* Name() const		{
+        return Value();
+    }
+    /// Set the name of the element.
+    void SetName( const char* str, bool staticMem=false )	{
+        SetValue( str, staticMem );
+    }
+
+    virtual XMLElement* ToElement()				{
+        return this;
+    }
+    virtual const XMLElement* ToElement() const {
+        return this;
+    }
+    virtual bool Accept( XMLVisitor* visitor ) const;
+
+    /** Given an attribute name, Attribute() returns the value
+    	for the attribute of that name, or null if none
+    	exists. For example:
+
+    	@verbatim
+    	const char* value = ele->Attribute( "foo" );
+    	@endverbatim
+
+    	The 'value' parameter is normally null. However, if specified,
+    	the attribute will only be returned if the 'name' and 'value'
+    	match. This allow you to write code:
+
+    	@verbatim
+    	if ( ele->Attribute( "foo", "bar" ) ) callFooIsBar();
+    	@endverbatim
+
+    	rather than:
+    	@verbatim
+    	if ( ele->Attribute( "foo" ) ) {
+    		if ( strcmp( ele->Attribute( "foo" ), "bar" ) == 0 ) callFooIsBar();
+    	}
+    	@endverbatim
+    */
+    const char* Attribute( const char* name, const char* value=0 ) const;
+
+    /** Given an attribute name, IntAttribute() returns the value
+    	of the attribute interpreted as an integer. 0 will be
+    	returned if there is an error. For a method with error
+    	checking, see QueryIntAttribute()
+    */
+    int		 IntAttribute( const char* name ) const		{
+        int i=0;
+        QueryIntAttribute( name, &i );
+        return i;
+    }
+    /// See IntAttribute()
+    unsigned UnsignedAttribute( const char* name ) const {
+        unsigned i=0;
+        QueryUnsignedAttribute( name, &i );
+        return i;
+    }
+    /// See IntAttribute()
+    bool	 BoolAttribute( const char* name ) const	{
+        bool b=false;
+        QueryBoolAttribute( name, &b );
+        return b;
+    }
+    /// See IntAttribute()
+    double 	 DoubleAttribute( const char* name ) const	{
+        double d=0;
+        QueryDoubleAttribute( name, &d );
+        return d;
+    }
+    /// See IntAttribute()
+    float	 FloatAttribute( const char* name ) const	{
+        float f=0;
+        QueryFloatAttribute( name, &f );
+        return f;
+    }
+
+    /** Given an attribute name, QueryIntAttribute() returns
+    	XML_NO_ERROR, XML_WRONG_ATTRIBUTE_TYPE if the conversion
+    	can't be performed, or XML_NO_ATTRIBUTE if the attribute
+    	doesn't exist. If successful, the result of the conversion
+    	will be written to 'value'. If not successful, nothing will
+    	be written to 'value'. This allows you to provide default
+    	value:
+
+    	@verbatim
+    	int value = 10;
+    	QueryIntAttribute( "foo", &value );		// if "foo" isn't found, value will still be 10
+    	@endverbatim
+    */
+    XMLError QueryIntAttribute( const char* name, int* value ) const				{
+        const XMLAttribute* a = FindAttribute( name );
+        if ( !a ) {
+            return XML_NO_ATTRIBUTE;
+        }
+        return a->QueryIntValue( value );
+    }
+    /// See QueryIntAttribute()
+    XMLError QueryUnsignedAttribute( const char* name, unsigned int* value ) const	{
+        const XMLAttribute* a = FindAttribute( name );
+        if ( !a ) {
+            return XML_NO_ATTRIBUTE;
+        }
+        return a->QueryUnsignedValue( value );
+    }
+    /// See QueryIntAttribute()
+    XMLError QueryBoolAttribute( const char* name, bool* value ) const				{
+        const XMLAttribute* a = FindAttribute( name );
+        if ( !a ) {
+            return XML_NO_ATTRIBUTE;
+        }
+        return a->QueryBoolValue( value );
+    }
+    /// See QueryIntAttribute()
+    XMLError QueryDoubleAttribute( const char* name, double* value ) const			{
+        const XMLAttribute* a = FindAttribute( name );
+        if ( !a ) {
+            return XML_NO_ATTRIBUTE;
+        }
+        return a->QueryDoubleValue( value );
+    }
+    /// See QueryIntAttribute()
+    XMLError QueryFloatAttribute( const char* name, float* value ) const			{
+        const XMLAttribute* a = FindAttribute( name );
+        if ( !a ) {
+            return XML_NO_ATTRIBUTE;
+        }
+        return a->QueryFloatValue( value );
+    }
+
+	
+    /** Given an attribute name, QueryAttribute() returns
+    	XML_NO_ERROR, XML_WRONG_ATTRIBUTE_TYPE if the conversion
+    	can't be performed, or XML_NO_ATTRIBUTE if the attribute
+    	doesn't exist. It is overloaded for the primitive types,
+		and is a generally more convenient replacement of
+		QueryIntAttribute() and related functions.
+		
+		If successful, the result of the conversion
+    	will be written to 'value'. If not successful, nothing will
+    	be written to 'value'. This allows you to provide default
+    	value:
+
+    	@verbatim
+    	int value = 10;
+    	QueryAttribute( "foo", &value );		// if "foo" isn't found, value will still be 10
+    	@endverbatim
+    */
+	int QueryAttribute( const char* name, int* value ) const {
+		return QueryIntAttribute( name, value );
+	}
+
+	int QueryAttribute( const char* name, unsigned int* value ) const {
+		return QueryUnsignedAttribute( name, value );
+	}
+
+	int QueryAttribute( const char* name, bool* value ) const {
+		return QueryBoolAttribute( name, value );
+	}
+
+	int QueryAttribute( const char* name, double* value ) const {
+		return QueryDoubleAttribute( name, value );
+	}
+
+	int QueryAttribute( const char* name, float* value ) const {
+		return QueryFloatAttribute( name, value );
+	}
+
+	/// Sets the named attribute to value.
+    void SetAttribute( const char* name, const char* value )	{
+        XMLAttribute* a = FindOrCreateAttribute( name );
+        a->SetAttribute( value );
+    }
+    /// Sets the named attribute to value.
+    void SetAttribute( const char* name, int value )			{
+        XMLAttribute* a = FindOrCreateAttribute( name );
+        a->SetAttribute( value );
+    }
+    /// Sets the named attribute to value.
+    void SetAttribute( const char* name, unsigned value )		{
+        XMLAttribute* a = FindOrCreateAttribute( name );
+        a->SetAttribute( value );
+    }
+    /// Sets the named attribute to value.
+    void SetAttribute( const char* name, bool value )			{
+        XMLAttribute* a = FindOrCreateAttribute( name );
+        a->SetAttribute( value );
+    }
+    /// Sets the named attribute to value.
+    void SetAttribute( const char* name, double value )		{
+        XMLAttribute* a = FindOrCreateAttribute( name );
+        a->SetAttribute( value );
+    }
+    /// Sets the named attribute to value.
+    void SetAttribute( const char* name, float value )		{
+        XMLAttribute* a = FindOrCreateAttribute( name );
+        a->SetAttribute( value );
+    }
+
+    /**
+    	Delete an attribute.
+    */
+    void DeleteAttribute( const char* name );
+
+    /// Return the first attribute in the list.
+    const XMLAttribute* FirstAttribute() const {
+        return _rootAttribute;
+    }
+    /// Query a specific attribute in the list.
+    const XMLAttribute* FindAttribute( const char* name ) const;
+
+    /** Convenience function for easy access to the text inside an element. Although easy
+    	and concise, GetText() is limited compared to getting the XMLText child
+    	and accessing it directly.
+
+    	If the first child of 'this' is a XMLText, the GetText()
+    	returns the character string of the Text node, else null is returned.
+
+    	This is a convenient method for getting the text of simple contained text:
+    	@verbatim
+    	<foo>This is text</foo>
+    		const char* str = fooElement->GetText();
+    	@endverbatim
+
+    	'str' will be a pointer to "This is text".
+
+    	Note that this function can be misleading. If the element foo was created from
+    	this XML:
+    	@verbatim
+    		<foo><b>This is text</b></foo>
+    	@endverbatim
+
+    	then the value of str would be null. The first child node isn't a text node, it is
+    	another element. From this XML:
+    	@verbatim
+    		<foo>This is <b>text</b></foo>
+    	@endverbatim
+    	GetText() will return "This is ".
+    */
+    const char* GetText() const;
+
+    /** Convenience function for easy access to the text inside an element. Although easy
+    	and concise, SetText() is limited compared to creating an XMLText child
+    	and mutating it directly.
+
+    	If the first child of 'this' is a XMLText, SetText() sets its value to
+		the given string, otherwise it will create a first child that is an XMLText.
+
+    	This is a convenient method for setting the text of simple contained text:
+    	@verbatim
+    	<foo>This is text</foo>
+    		fooElement->SetText( "Hullaballoo!" );
+     	<foo>Hullaballoo!</foo>
+		@endverbatim
+
+    	Note that this function can be misleading. If the element foo was created from
+    	this XML:
+    	@verbatim
+    		<foo><b>This is text</b></foo>
+    	@endverbatim
+
+    	then it will not change "This is text", but rather prefix it with a text element:
+    	@verbatim
+    		<foo>Hullaballoo!<b>This is text</b></foo>
+    	@endverbatim
+		
+		For this XML:
+    	@verbatim
+    		<foo />
+    	@endverbatim
+    	SetText() will generate
+    	@verbatim
+    		<foo>Hullaballoo!</foo>
+    	@endverbatim
+    */
+	void SetText( const char* inText );
+    /// Convenience method for setting text inside an element. See SetText() for important limitations.
+    void SetText( int value );
+    /// Convenience method for setting text inside an element. See SetText() for important limitations.
+    void SetText( unsigned value );  
+    /// Convenience method for setting text inside an element. See SetText() for important limitations.
+    void SetText( bool value );  
+    /// Convenience method for setting text inside an element. See SetText() for important limitations.
+    void SetText( double value );  
+    /// Convenience method for setting text inside an element. See SetText() for important limitations.
+    void SetText( float value );  
+
+    /**
+    	Convenience method to query the value of a child text node. This is probably best
+    	shown by example. Given you have a document is this form:
+    	@verbatim
+    		<point>
+    			<x>1</x>
+    			<y>1.4</y>
+    		</point>
+    	@endverbatim
+
+    	The QueryIntText() and similar functions provide a safe and easier way to get to the
+    	"value" of x and y.
+
+    	@verbatim
+    		int x = 0;
+    		float y = 0;	// types of x and y are contrived for example
+    		const XMLElement* xElement = pointElement->FirstChildElement( "x" );
+    		const XMLElement* yElement = pointElement->FirstChildElement( "y" );
+    		xElement->QueryIntText( &x );
+    		yElement->QueryFloatText( &y );
+    	@endverbatim
+
+    	@returns XML_SUCCESS (0) on success, XML_CAN_NOT_CONVERT_TEXT if the text cannot be converted
+    			 to the requested type, and XML_NO_TEXT_NODE if there is no child text to query.
+
+    */
+    XMLError QueryIntText( int* ival ) const;
+    /// See QueryIntText()
+    XMLError QueryUnsignedText( unsigned* uval ) const;
+    /// See QueryIntText()
+    XMLError QueryBoolText( bool* bval ) const;
+    /// See QueryIntText()
+    XMLError QueryDoubleText( double* dval ) const;
+    /// See QueryIntText()
+    XMLError QueryFloatText( float* fval ) const;
+
+    // internal:
+    enum {
+        OPEN,		// <foo>
+        CLOSED,		// <foo/>
+        CLOSING		// </foo>
+    };
+    int ClosingType() const {
+        return _closingType;
+    }
+    virtual XMLNode* ShallowClone( XMLDocument* document ) const;
+    virtual bool ShallowEqual( const XMLNode* compare ) const;
+
+protected:
+    char* ParseDeep( char* p, StrPair* endTag );
+
+private:
+    XMLElement( XMLDocument* doc );
+    virtual ~XMLElement();
+    XMLElement( const XMLElement& );	// not supported
+    void operator=( const XMLElement& );	// not supported
+
+    XMLAttribute* FindAttribute( const char* name ) {
+        return const_cast<XMLAttribute*>(const_cast<const XMLElement*>(this)->FindAttribute( name ));
+    }
+    XMLAttribute* FindOrCreateAttribute( const char* name );
+    //void LinkAttribute( XMLAttribute* attrib );
+    char* ParseAttributes( char* p );
+    static void DeleteAttribute( XMLAttribute* attribute );
+
+    enum { BUF_SIZE = 200 };
+    int _closingType;
+    // The attribute list is ordered; there is no 'lastAttribute'
+    // because the list needs to be scanned for dupes before adding
+    // a new attribute.
+    XMLAttribute* _rootAttribute;
+};
+
+
+enum Whitespace {
+    PRESERVE_WHITESPACE,
+    COLLAPSE_WHITESPACE
+};
+
+
+/** A Document binds together all the functionality.
+	It can be saved, loaded, and printed to the screen.
+	All Nodes are connected and allocated to a Document.
+	If the Document is deleted, all its Nodes are also deleted.
+*/
+class TINYXML2_LIB XMLDocument : public XMLNode
+{
+    friend class XMLElement;
+public:
+    /// constructor
+    XMLDocument( bool processEntities = true, Whitespace = PRESERVE_WHITESPACE );
+    ~XMLDocument();
+
+    virtual XMLDocument* ToDocument()				{
+        TIXMLASSERT( this == _document );
+        return this;
+    }
+    virtual const XMLDocument* ToDocument() const	{
+        TIXMLASSERT( this == _document );
+        return this;
+    }
+
+    /**
+    	Parse an XML file from a character string.
+    	Returns XML_NO_ERROR (0) on success, or
+    	an errorID.
+
+    	You may optionally pass in the 'nBytes', which is
+    	the number of bytes which will be parsed. If not
+    	specified, TinyXML-2 will assume 'xml' points to a
+    	null terminated string.
+    */
+    XMLError Parse( const char* xml, size_t nBytes=(size_t)(-1) );
+
+    /**
+    	Load an XML file from disk.
+    	Returns XML_NO_ERROR (0) on success, or
+    	an errorID.
+    */
+    XMLError LoadFile( const char* filename );
+
+    /**
+    	Load an XML file from disk. You are responsible
+    	for providing and closing the FILE*. 
+     
+        NOTE: The file should be opened as binary ("rb")
+        not text in order for TinyXML-2 to correctly
+        do newline normalization.
+
+    	Returns XML_NO_ERROR (0) on success, or
+    	an errorID.
+    */
+    XMLError LoadFile( FILE* );
+
+    /**
+    	Save the XML file to disk.
+    	Returns XML_NO_ERROR (0) on success, or
+    	an errorID.
+    */
+    XMLError SaveFile( const char* filename, bool compact = false );
+
+    /**
+    	Save the XML file to disk. You are responsible
+    	for providing and closing the FILE*.
+
+    	Returns XML_NO_ERROR (0) on success, or
+    	an errorID.
+    */
+    XMLError SaveFile( FILE* fp, bool compact = false );
+
+    bool ProcessEntities() const		{
+        return _processEntities;
+    }
+    Whitespace WhitespaceMode() const	{
+        return _whitespace;
+    }
+
+    /**
+    	Returns true if this document has a leading Byte Order Mark of UTF8.
+    */
+    bool HasBOM() const {
+        return _writeBOM;
+    }
+    /** Sets whether to write the BOM when writing the file.
+    */
+    void SetBOM( bool useBOM ) {
+        _writeBOM = useBOM;
+    }
+
+    /** Return the root element of DOM. Equivalent to FirstChildElement().
+        To get the first node, use FirstChild().
+    */
+    XMLElement* RootElement()				{
+        return FirstChildElement();
+    }
+    const XMLElement* RootElement() const	{
+        return FirstChildElement();
+    }
+
+    /** Print the Document. If the Printer is not provided, it will
+        print to stdout. If you provide Printer, this can print to a file:
+    	@verbatim
+    	XMLPrinter printer( fp );
+    	doc.Print( &printer );
+    	@endverbatim
+
+    	Or you can use a printer to print to memory:
+    	@verbatim
+    	XMLPrinter printer;
+    	doc.Print( &printer );
+    	// printer.CStr() has a const char* to the XML
+    	@endverbatim
+    */
+    void Print( XMLPrinter* streamer=0 ) const;
+    virtual bool Accept( XMLVisitor* visitor ) const;
+
+    /**
+    	Create a new Element associated with
+    	this Document. The memory for the Element
+    	is managed by the Document.
+    */
+    XMLElement* NewElement( const char* name );
+    /**
+    	Create a new Comment associated with
+    	this Document. The memory for the Comment
+    	is managed by the Document.
+    */
+    XMLComment* NewComment( const char* comment );
+    /**
+    	Create a new Text associated with
+    	this Document. The memory for the Text
+    	is managed by the Document.
+    */
+    XMLText* NewText( const char* text );
+    /**
+    	Create a new Declaration associated with
+    	this Document. The memory for the object
+    	is managed by the Document.
+
+    	If the 'text' param is null, the standard
+    	declaration is used.:
+    	@verbatim
+    		<?xml version="1.0" encoding="UTF-8"?>
+    	@endverbatim
+    */
+    XMLDeclaration* NewDeclaration( const char* text=0 );
+    /**
+    	Create a new Unknown associated with
+    	this Document. The memory for the object
+    	is managed by the Document.
+    */
+    XMLUnknown* NewUnknown( const char* text );
+
+    /**
+    	Delete a node associated with this document.
+    	It will be unlinked from the DOM.
+    */
+    void DeleteNode( XMLNode* node );
+
+    void SetError( XMLError error, const char* str1, const char* str2 );
+
+    /// Return true if there was an error parsing the document.
+    bool Error() const {
+        return _errorID != XML_NO_ERROR;
+    }
+    /// Return the errorID.
+    XMLError  ErrorID() const {
+        return _errorID;
+    }
+	const char* ErrorName() const;
+
+    /// Return a possibly helpful diagnostic location or string.
+    const char* GetErrorStr1() const {
+        return _errorStr1;
+    }
+    /// Return a possibly helpful secondary diagnostic location or string.
+    const char* GetErrorStr2() const {
+        return _errorStr2;
+    }
+    /// If there is an error, print it to stdout.
+    void PrintError() const;
+    
+    /// Clear the document, resetting it to the initial state.
+    void Clear();
+
+    // internal
+    char* Identify( char* p, XMLNode** node );
+
+    virtual XMLNode* ShallowClone( XMLDocument* /*document*/ ) const	{
+        return 0;
+    }
+    virtual bool ShallowEqual( const XMLNode* /*compare*/ ) const	{
+        return false;
+    }
+
+private:
+    XMLDocument( const XMLDocument& );	// not supported
+    void operator=( const XMLDocument& );	// not supported
+
+    bool        _writeBOM;
+    bool        _processEntities;
+    XMLError    _errorID;
+    Whitespace  _whitespace;
+    const char* _errorStr1;
+    const char* _errorStr2;
+    char*       _charBuffer;
+
+    MemPoolT< sizeof(XMLElement) >	 _elementPool;
+    MemPoolT< sizeof(XMLAttribute) > _attributePool;
+    MemPoolT< sizeof(XMLText) >		 _textPool;
+    MemPoolT< sizeof(XMLComment) >	 _commentPool;
+
+	static const char* _errorNames[XML_ERROR_COUNT];
+
+    void Parse();
+};
+
+
+/**
+	A XMLHandle is a class that wraps a node pointer with null checks; this is
+	an incredibly useful thing. Note that XMLHandle is not part of the TinyXML-2
+	DOM structure. It is a separate utility class.
+
+	Take an example:
+	@verbatim
+	<Document>
+		<Element attributeA = "valueA">
+			<Child attributeB = "value1" />
+			<Child attributeB = "value2" />
+		</Element>
+	</Document>
+	@endverbatim
+
+	Assuming you want the value of "attributeB" in the 2nd "Child" element, it's very
+	easy to write a *lot* of code that looks like:
+
+	@verbatim
+	XMLElement* root = document.FirstChildElement( "Document" );
+	if ( root )
+	{
+		XMLElement* element = root->FirstChildElement( "Element" );
+		if ( element )
+		{
+			XMLElement* child = element->FirstChildElement( "Child" );
+			if ( child )
+			{
+				XMLElement* child2 = child->NextSiblingElement( "Child" );
+				if ( child2 )
+				{
+					// Finally do something useful.
+	@endverbatim
+
+	And that doesn't even cover "else" cases. XMLHandle addresses the verbosity
+	of such code. A XMLHandle checks for null pointers so it is perfectly safe
+	and correct to use:
+
+	@verbatim
+	XMLHandle docHandle( &document );
+	XMLElement* child2 = docHandle.FirstChildElement( "Document" ).FirstChildElement( "Element" ).FirstChildElement().NextSiblingElement();
+	if ( child2 )
+	{
+		// do something useful
+	@endverbatim
+
+	Which is MUCH more concise and useful.
+
+	It is also safe to copy handles - internally they are nothing more than node pointers.
+	@verbatim
+	XMLHandle handleCopy = handle;
+	@endverbatim
+
+	See also XMLConstHandle, which is the same as XMLHandle, but operates on const objects.
+*/
+class TINYXML2_LIB XMLHandle
+{
+public:
+    /// Create a handle from any node (at any depth of the tree.) This can be a null pointer.
+    XMLHandle( XMLNode* node )												{
+        _node = node;
+    }
+    /// Create a handle from a node.
+    XMLHandle( XMLNode& node )												{
+        _node = &node;
+    }
+    /// Copy constructor
+    XMLHandle( const XMLHandle& ref )										{
+        _node = ref._node;
+    }
+    /// Assignment
+    XMLHandle& operator=( const XMLHandle& ref )							{
+        _node = ref._node;
+        return *this;
+    }
+
+    /// Get the first child of this handle.
+    XMLHandle FirstChild() 													{
+        return XMLHandle( _node ? _node->FirstChild() : 0 );
+    }
+    /// Get the first child element of this handle.
+    XMLHandle FirstChildElement( const char* name = 0 )						{
+        return XMLHandle( _node ? _node->FirstChildElement( name ) : 0 );
+    }
+    /// Get the last child of this handle.
+    XMLHandle LastChild()													{
+        return XMLHandle( _node ? _node->LastChild() : 0 );
+    }
+    /// Get the last child element of this handle.
+    XMLHandle LastChildElement( const char* name = 0 )						{
+        return XMLHandle( _node ? _node->LastChildElement( name ) : 0 );
+    }
+    /// Get the previous sibling of this handle.
+    XMLHandle PreviousSibling()												{
+        return XMLHandle( _node ? _node->PreviousSibling() : 0 );
+    }
+    /// Get the previous sibling element of this handle.
+    XMLHandle PreviousSiblingElement( const char* name = 0 )				{
+        return XMLHandle( _node ? _node->PreviousSiblingElement( name ) : 0 );
+    }
+    /// Get the next sibling of this handle.
+    XMLHandle NextSibling()													{
+        return XMLHandle( _node ? _node->NextSibling() : 0 );
+    }
+    /// Get the next sibling element of this handle.
+    XMLHandle NextSiblingElement( const char* name = 0 )					{
+        return XMLHandle( _node ? _node->NextSiblingElement( name ) : 0 );
+    }
+
+    /// Safe cast to XMLNode. This can return null.
+    XMLNode* ToNode()							{
+        return _node;
+    }
+    /// Safe cast to XMLElement. This can return null.
+    XMLElement* ToElement() 					{
+        return ( ( _node == 0 ) ? 0 : _node->ToElement() );
+    }
+    /// Safe cast to XMLText. This can return null.
+    XMLText* ToText() 							{
+        return ( ( _node == 0 ) ? 0 : _node->ToText() );
+    }
+    /// Safe cast to XMLUnknown. This can return null.
+    XMLUnknown* ToUnknown() 					{
+        return ( ( _node == 0 ) ? 0 : _node->ToUnknown() );
+    }
+    /// Safe cast to XMLDeclaration. This can return null.
+    XMLDeclaration* ToDeclaration() 			{
+        return ( ( _node == 0 ) ? 0 : _node->ToDeclaration() );
+    }
+
+private:
+    XMLNode* _node;
+};
+
+
+/**
+	A variant of the XMLHandle class for working with const XMLNodes and Documents. It is the
+	same in all regards, except for the 'const' qualifiers. See XMLHandle for API.
+*/
+class TINYXML2_LIB XMLConstHandle
+{
+public:
+    XMLConstHandle( const XMLNode* node )											{
+        _node = node;
+    }
+    XMLConstHandle( const XMLNode& node )											{
+        _node = &node;
+    }
+    XMLConstHandle( const XMLConstHandle& ref )										{
+        _node = ref._node;
+    }
+
+    XMLConstHandle& operator=( const XMLConstHandle& ref )							{
+        _node = ref._node;
+        return *this;
+    }
+
+    const XMLConstHandle FirstChild() const											{
+        return XMLConstHandle( _node ? _node->FirstChild() : 0 );
+    }
+    const XMLConstHandle FirstChildElement( const char* name = 0 ) const				{
+        return XMLConstHandle( _node ? _node->FirstChildElement( name ) : 0 );
+    }
+    const XMLConstHandle LastChild()	const										{
+        return XMLConstHandle( _node ? _node->LastChild() : 0 );
+    }
+    const XMLConstHandle LastChildElement( const char* name = 0 ) const				{
+        return XMLConstHandle( _node ? _node->LastChildElement( name ) : 0 );
+    }
+    const XMLConstHandle PreviousSibling() const									{
+        return XMLConstHandle( _node ? _node->PreviousSibling() : 0 );
+    }
+    const XMLConstHandle PreviousSiblingElement( const char* name = 0 ) const		{
+        return XMLConstHandle( _node ? _node->PreviousSiblingElement( name ) : 0 );
+    }
+    const XMLConstHandle NextSibling() const										{
+        return XMLConstHandle( _node ? _node->NextSibling() : 0 );
+    }
+    const XMLConstHandle NextSiblingElement( const char* name = 0 ) const			{
+        return XMLConstHandle( _node ? _node->NextSiblingElement( name ) : 0 );
+    }
+
+
+    const XMLNode* ToNode() const				{
+        return _node;
+    }
+    const XMLElement* ToElement() const			{
+        return ( ( _node == 0 ) ? 0 : _node->ToElement() );
+    }
+    const XMLText* ToText() const				{
+        return ( ( _node == 0 ) ? 0 : _node->ToText() );
+    }
+    const XMLUnknown* ToUnknown() const			{
+        return ( ( _node == 0 ) ? 0 : _node->ToUnknown() );
+    }
+    const XMLDeclaration* ToDeclaration() const	{
+        return ( ( _node == 0 ) ? 0 : _node->ToDeclaration() );
+    }
+
+private:
+    const XMLNode* _node;
+};
+
+
+/**
+	Printing functionality. The XMLPrinter gives you more
+	options than the XMLDocument::Print() method.
+
+	It can:
+	-# Print to memory.
+	-# Print to a file you provide.
+	-# Print XML without a XMLDocument.
+
+	Print to Memory
+
+	@verbatim
+	XMLPrinter printer;
+	doc.Print( &printer );
+	SomeFunction( printer.CStr() );
+	@endverbatim
+
+	Print to a File
+
+	You provide the file pointer.
+	@verbatim
+	XMLPrinter printer( fp );
+	doc.Print( &printer );
+	@endverbatim
+
+	Print without a XMLDocument
+
+	When loading, an XML parser is very useful. However, sometimes
+	when saving, it just gets in the way. The code is often set up
+	for streaming, and constructing the DOM is just overhead.
+
+	The Printer supports the streaming case. The following code
+	prints out a trivially simple XML file without ever creating
+	an XML document.
+
+	@verbatim
+	XMLPrinter printer( fp );
+	printer.OpenElement( "foo" );
+	printer.PushAttribute( "foo", "bar" );
+	printer.CloseElement();
+	@endverbatim
+*/
+class TINYXML2_LIB XMLPrinter : public XMLVisitor
+{
+public:
+    /** Construct the printer. If the FILE* is specified,
+    	this will print to the FILE. Else it will print
+    	to memory, and the result is available in CStr().
+    	If 'compact' is set to true, then output is created
+    	with only required whitespace and newlines.
+    */
+    XMLPrinter( FILE* file=0, bool compact = false, int depth = 0 );
+    virtual ~XMLPrinter()	{}
+
+    /** If streaming, write the BOM and declaration. */
+    void PushHeader( bool writeBOM, bool writeDeclaration );
+    /** If streaming, start writing an element.
+        The element must be closed with CloseElement()
+    */
+    void OpenElement( const char* name, bool compactMode=false );
+    /// If streaming, add an attribute to an open element.
+    void PushAttribute( const char* name, const char* value );
+    void PushAttribute( const char* name, int value );
+    void PushAttribute( const char* name, unsigned value );
+    void PushAttribute( const char* name, bool value );
+    void PushAttribute( const char* name, double value );
+    /// If streaming, close the Element.
+    virtual void CloseElement( bool compactMode=false );
+
+    /// Add a text node.
+    void PushText( const char* text, bool cdata=false );
+    /// Add a text node from an integer.
+    void PushText( int value );
+    /// Add a text node from an unsigned.
+    void PushText( unsigned value );
+    /// Add a text node from a bool.
+    void PushText( bool value );
+    /// Add a text node from a float.
+    void PushText( float value );
+    /// Add a text node from a double.
+    void PushText( double value );
+
+    /// Add a comment
+    void PushComment( const char* comment );
+
+    void PushDeclaration( const char* value );
+    void PushUnknown( const char* value );
+
+    virtual bool VisitEnter( const XMLDocument& /*doc*/ );
+    virtual bool VisitExit( const XMLDocument& /*doc*/ )			{
+        return true;
+    }
+
+    virtual bool VisitEnter( const XMLElement& element, const XMLAttribute* attribute );
+    virtual bool VisitExit( const XMLElement& element );
+
+    virtual bool Visit( const XMLText& text );
+    virtual bool Visit( const XMLComment& comment );
+    virtual bool Visit( const XMLDeclaration& declaration );
+    virtual bool Visit( const XMLUnknown& unknown );
+
+    /**
+    	If in print to memory mode, return a pointer to
+    	the XML file in memory.
+    */
+    const char* CStr() const {
+        return _buffer.Mem();
+    }
+    /**
+    	If in print to memory mode, return the size
+    	of the XML file in memory. (Note the size returned
+    	includes the terminating null.)
+    */
+    int CStrSize() const {
+        return _buffer.Size();
+    }
+    /**
+    	If in print to memory mode, reset the buffer to the
+    	beginning.
+    */
+    void ClearBuffer() {
+        _buffer.Clear();
+        _buffer.Push(0);
+    }
+
+protected:
+	virtual bool CompactMode( const XMLElement& )	{ return _compactMode; }
+
+	/** Prints out the space before an element. You may override to change
+	    the space and tabs used. A PrintSpace() override should call Print().
+	*/
+    virtual void PrintSpace( int depth );
+    void Print( const char* format, ... );
+
+    void SealElementIfJustOpened();
+    bool _elementJustOpened;
+    DynArray< const char*, 10 > _stack;
+
+private:
+    void PrintString( const char*, bool restrictedEntitySet );	// prints out, after detecting entities.
+
+    bool _firstElement;
+    FILE* _fp;
+    int _depth;
+    int _textDepth;
+    bool _processEntities;
+	bool _compactMode;
+
+    enum {
+        ENTITY_RANGE = 64,
+        BUF_SIZE = 200
+    };
+    bool _entityFlag[ENTITY_RANGE];
+    bool _restrictedEntityFlag[ENTITY_RANGE];
+
+    DynArray< char, 20 > _buffer;
+};
+
+
+}	// tinyxml2
+
+#if defined(_MSC_VER)
+#   pragma warning(pop)
+#endif
+
+#endif // TINYXML2_INCLUDED

+ 169 - 0
lib/FTL.TXT

@@ -0,0 +1,169 @@
+                    The FreeType Project LICENSE
+                    ----------------------------
+
+                            2006-Jan-27
+
+                    Copyright 1996-2002, 2006 by
+          David Turner, Robert Wilhelm, and Werner Lemberg
+
+
+
+Introduction
+============
+
+  The FreeType  Project is distributed in  several archive packages;
+  some of them may contain, in addition to the FreeType font engine,
+  various tools and  contributions which rely on, or  relate to, the
+  FreeType Project.
+
+  This  license applies  to all  files found  in such  packages, and
+  which do not  fall under their own explicit  license.  The license
+  affects  thus  the  FreeType   font  engine,  the  test  programs,
+  documentation and makefiles, at the very least.
+
+  This  license   was  inspired  by  the  BSD,   Artistic,  and  IJG
+  (Independent JPEG  Group) licenses, which  all encourage inclusion
+  and  use of  free  software in  commercial  and freeware  products
+  alike.  As a consequence, its main points are that:
+
+    o We don't promise that this software works. However, we will be
+      interested in any kind of bug reports. (`as is' distribution)
+
+    o You can  use this software for whatever you  want, in parts or
+      full form, without having to pay us. (`royalty-free' usage)
+
+    o You may not pretend that  you wrote this software.  If you use
+      it, or  only parts of it,  in a program,  you must acknowledge
+      somewhere  in  your  documentation  that  you  have  used  the
+      FreeType code. (`credits')
+
+  We  specifically  permit  and  encourage  the  inclusion  of  this
+  software, with  or without modifications,  in commercial products.
+  We  disclaim  all warranties  covering  The  FreeType Project  and
+  assume no liability related to The FreeType Project.
+
+
+  Finally,  many  people  asked  us  for  a  preferred  form  for  a
+  credit/disclaimer to use in compliance with this license.  We thus
+  encourage you to use the following text:
+
+   """
+    Portions of this software are copyright © <year> The FreeType
+    Project (www.freetype.org).  All rights reserved.
+   """
+
+  Please replace <year> with the value from the FreeType version you
+  actually use.
+
+
+Legal Terms
+===========
+
+0. Definitions
+--------------
+
+  Throughout this license,  the terms `package', `FreeType Project',
+  and  `FreeType  archive' refer  to  the  set  of files  originally
+  distributed  by the  authors  (David Turner,  Robert Wilhelm,  and
+  Werner Lemberg) as the `FreeType Project', be they named as alpha,
+  beta or final release.
+
+  `You' refers to  the licensee, or person using  the project, where
+  `using' is a generic term including compiling the project's source
+  code as  well as linking it  to form a  `program' or `executable'.
+  This  program is  referred to  as  `a program  using the  FreeType
+  engine'.
+
+  This  license applies  to all  files distributed  in  the original
+  FreeType  Project,   including  all  source   code,  binaries  and
+  documentation,  unless  otherwise  stated   in  the  file  in  its
+  original, unmodified form as  distributed in the original archive.
+  If you are  unsure whether or not a particular  file is covered by
+  this license, you must contact us to verify this.
+
+  The FreeType  Project is copyright (C) 1996-2000  by David Turner,
+  Robert Wilhelm, and Werner Lemberg.  All rights reserved except as
+  specified below.
+
+1. No Warranty
+--------------
+
+  THE FREETYPE PROJECT  IS PROVIDED `AS IS' WITHOUT  WARRANTY OF ANY
+  KIND, EITHER  EXPRESS OR IMPLIED,  INCLUDING, BUT NOT  LIMITED TO,
+  WARRANTIES  OF  MERCHANTABILITY   AND  FITNESS  FOR  A  PARTICULAR
+  PURPOSE.  IN NO EVENT WILL ANY OF THE AUTHORS OR COPYRIGHT HOLDERS
+  BE LIABLE  FOR ANY DAMAGES CAUSED  BY THE USE OR  THE INABILITY TO
+  USE, OF THE FREETYPE PROJECT.
+
+2. Redistribution
+-----------------
+
+  This  license  grants  a  worldwide, royalty-free,  perpetual  and
+  irrevocable right  and license to use,  execute, perform, compile,
+  display,  copy,   create  derivative  works   of,  distribute  and
+  sublicense the  FreeType Project (in  both source and  object code
+  forms)  and  derivative works  thereof  for  any  purpose; and  to
+  authorize others  to exercise  some or all  of the  rights granted
+  herein, subject to the following conditions:
+
+    o Redistribution of  source code  must retain this  license file
+      (`FTL.TXT') unaltered; any  additions, deletions or changes to
+      the original  files must be clearly  indicated in accompanying
+      documentation.   The  copyright   notices  of  the  unaltered,
+      original  files must  be  preserved in  all  copies of  source
+      files.
+
+    o Redistribution in binary form must provide a  disclaimer  that
+      states  that  the software is based in part of the work of the
+      FreeType Team,  in  the  distribution  documentation.  We also
+      encourage you to put an URL to the FreeType web page  in  your
+      documentation, though this isn't mandatory.
+
+  These conditions  apply to any  software derived from or  based on
+  the FreeType Project,  not just the unmodified files.   If you use
+  our work, you  must acknowledge us.  However, no  fee need be paid
+  to us.
+
+3. Advertising
+--------------
+
+  Neither the  FreeType authors and  contributors nor you  shall use
+  the name of the  other for commercial, advertising, or promotional
+  purposes without specific prior written permission.
+
+  We suggest,  but do not require, that  you use one or  more of the
+  following phrases to refer  to this software in your documentation
+  or advertising  materials: `FreeType Project',  `FreeType Engine',
+  `FreeType library', or `FreeType Distribution'.
+
+  As  you have  not signed  this license,  you are  not  required to
+  accept  it.   However,  as  the FreeType  Project  is  copyrighted
+  material, only  this license, or  another one contracted  with the
+  authors, grants you  the right to use, distribute,  and modify it.
+  Therefore,  by  using,  distributing,  or modifying  the  FreeType
+  Project, you indicate that you understand and accept all the terms
+  of this license.
+
+4. Contacts
+-----------
+
+  There are two mailing lists related to FreeType:
+
+    o [email protected]
+
+      Discusses general use and applications of FreeType, as well as
+      future and  wanted additions to the  library and distribution.
+      If  you are looking  for support,  start in  this list  if you
+      haven't found anything to help you in the documentation.
+
+    o [email protected]
+
+      Discusses bugs,  as well  as engine internals,  design issues,
+      specific licenses, porting, etc.
+
+  Our home page can be found at
+
+    http://www.freetype.org
+
+
+--- end of FTL.TXT ---

TEMPAT SAMPAH
lib/freetype.lib


+ 6223 - 0
lib/lodepng.cpp

@@ -0,0 +1,6223 @@
+/*
+LodePNG version 20160418
+
+Copyright (c) 2005-2016 Lode Vandevenne
+
+This software is provided 'as-is', without any express or implied
+warranty. In no event will the authors be held liable for any damages
+arising from the use of this software.
+
+Permission is granted to anyone to use this software for any purpose,
+including commercial applications, and to alter it and redistribute it
+freely, subject to the following restrictions:
+
+    1. The origin of this software must not be misrepresented; you must not
+    claim that you wrote the original software. If you use this software
+    in a product, an acknowledgment in the product documentation would be
+    appreciated but is not required.
+
+    2. Altered source versions must be plainly marked as such, and must not be
+    misrepresented as being the original software.
+
+    3. This notice may not be removed or altered from any source
+    distribution.
+*/
+
+/*
+The manual and changelog are in the header file "lodepng.h"
+Rename this file to lodepng.cpp to use it for C++, or to lodepng.c to use it for C.
+*/
+
+#include "lodepng.h"
+
+#include <limits.h>
+#include <stdio.h>
+#include <stdlib.h>
+
+#if defined(_MSC_VER) && (_MSC_VER >= 1310) /*Visual Studio: A few warning types are not desired here.*/
+#pragma warning( disable : 4244 ) /*implicit conversions: not warned by gcc -Wall -Wextra and requires too much casts*/
+#pragma warning( disable : 4996 ) /*VS does not like fopen, but fopen_s is not standard C so unusable here*/
+#endif /*_MSC_VER */
+
+const char* LODEPNG_VERSION_STRING = "20160418";
+
+/*
+This source file is built up in the following large parts. The code sections
+with the "LODEPNG_COMPILE_" #defines divide this up further in an intermixed way.
+-Tools for C and common code for PNG and Zlib
+-C Code for Zlib (huffman, deflate, ...)
+-C Code for PNG (file format chunks, adam7, PNG filters, color conversions, ...)
+-The C++ wrapper around all of the above
+*/
+
+/*The malloc, realloc and free functions defined here with "lodepng_" in front
+of the name, so that you can easily change them to others related to your
+platform if needed. Everything else in the code calls these. Pass
+-DLODEPNG_NO_COMPILE_ALLOCATORS to the compiler, or comment out
+#define LODEPNG_COMPILE_ALLOCATORS in the header, to disable the ones here and
+define them in your own project's source files without needing to change
+lodepng source code. Don't forget to remove "static" if you copypaste them
+from here.*/
+
+#ifdef LODEPNG_COMPILE_ALLOCATORS
+static void* lodepng_malloc(size_t size)
+{
+  return malloc(size);
+}
+
+static void* lodepng_realloc(void* ptr, size_t new_size)
+{
+  return realloc(ptr, new_size);
+}
+
+static void lodepng_free(void* ptr)
+{
+  free(ptr);
+}
+#else /*LODEPNG_COMPILE_ALLOCATORS*/
+void* lodepng_malloc(size_t size);
+void* lodepng_realloc(void* ptr, size_t new_size);
+void lodepng_free(void* ptr);
+#endif /*LODEPNG_COMPILE_ALLOCATORS*/
+
+/* ////////////////////////////////////////////////////////////////////////// */
+/* ////////////////////////////////////////////////////////////////////////// */
+/* // Tools for C, and common code for PNG and Zlib.                       // */
+/* ////////////////////////////////////////////////////////////////////////// */
+/* ////////////////////////////////////////////////////////////////////////// */
+
+/*
+Often in case of an error a value is assigned to a variable and then it breaks
+out of a loop (to go to the cleanup phase of a function). This macro does that.
+It makes the error handling code shorter and more readable.
+
+Example: if(!uivector_resizev(&frequencies_ll, 286, 0)) ERROR_BREAK(83);
+*/
+#define CERROR_BREAK(errorvar, code)\
+{\
+  errorvar = code;\
+  break;\
+}
+
+/*version of CERROR_BREAK that assumes the common case where the error variable is named "error"*/
+#define ERROR_BREAK(code) CERROR_BREAK(error, code)
+
+/*Set error var to the error code, and return it.*/
+#define CERROR_RETURN_ERROR(errorvar, code)\
+{\
+  errorvar = code;\
+  return code;\
+}
+
+/*Try the code, if it returns error, also return the error.*/
+#define CERROR_TRY_RETURN(call)\
+{\
+  unsigned error = call;\
+  if(error) return error;\
+}
+
+/*Set error var to the error code, and return from the void function.*/
+#define CERROR_RETURN(errorvar, code)\
+{\
+  errorvar = code;\
+  return;\
+}
+
+/*
+About uivector, ucvector and string:
+-All of them wrap dynamic arrays or text strings in a similar way.
+-LodePNG was originally written in C++. The vectors replace the std::vectors that were used in the C++ version.
+-The string tools are made to avoid problems with compilers that declare things like strncat as deprecated.
+-They're not used in the interface, only internally in this file as static functions.
+-As with many other structs in this file, the init and cleanup functions serve as ctor and dtor.
+*/
+
+#ifdef LODEPNG_COMPILE_ZLIB
+/*dynamic vector of unsigned ints*/
+typedef struct uivector
+{
+  unsigned* data;
+  size_t size; /*size in number of unsigned longs*/
+  size_t allocsize; /*allocated size in bytes*/
+} uivector;
+
+static void uivector_cleanup(void* p)
+{
+  ((uivector*)p)->size = ((uivector*)p)->allocsize = 0;
+  lodepng_free(((uivector*)p)->data);
+  ((uivector*)p)->data = NULL;
+}
+
+/*returns 1 if success, 0 if failure ==> nothing done*/
+static unsigned uivector_reserve(uivector* p, size_t allocsize)
+{
+  if(allocsize > p->allocsize)
+  {
+    size_t newsize = (allocsize > p->allocsize * 2) ? allocsize : (allocsize * 3 / 2);
+    void* data = lodepng_realloc(p->data, newsize);
+    if(data)
+    {
+      p->allocsize = newsize;
+      p->data = (unsigned*)data;
+    }
+    else return 0; /*error: not enough memory*/
+  }
+  return 1;
+}
+
+/*returns 1 if success, 0 if failure ==> nothing done*/
+static unsigned uivector_resize(uivector* p, size_t size)
+{
+  if(!uivector_reserve(p, size * sizeof(unsigned))) return 0;
+  p->size = size;
+  return 1; /*success*/
+}
+
+/*resize and give all new elements the value*/
+static unsigned uivector_resizev(uivector* p, size_t size, unsigned value)
+{
+  size_t oldsize = p->size, i;
+  if(!uivector_resize(p, size)) return 0;
+  for(i = oldsize; i < size; ++i) p->data[i] = value;
+  return 1;
+}
+
+static void uivector_init(uivector* p)
+{
+  p->data = NULL;
+  p->size = p->allocsize = 0;
+}
+
+#ifdef LODEPNG_COMPILE_ENCODER
+/*returns 1 if success, 0 if failure ==> nothing done*/
+static unsigned uivector_push_back(uivector* p, unsigned c)
+{
+  if(!uivector_resize(p, p->size + 1)) return 0;
+  p->data[p->size - 1] = c;
+  return 1;
+}
+#endif /*LODEPNG_COMPILE_ENCODER*/
+#endif /*LODEPNG_COMPILE_ZLIB*/
+
+/* /////////////////////////////////////////////////////////////////////////// */
+
+/*dynamic vector of unsigned chars*/
+typedef struct ucvector
+{
+  unsigned char* data;
+  size_t size; /*used size*/
+  size_t allocsize; /*allocated size*/
+} ucvector;
+
+/*returns 1 if success, 0 if failure ==> nothing done*/
+static unsigned ucvector_reserve(ucvector* p, size_t allocsize)
+{
+  if(allocsize > p->allocsize)
+  {
+    size_t newsize = (allocsize > p->allocsize * 2) ? allocsize : (allocsize * 3 / 2);
+    void* data = lodepng_realloc(p->data, newsize);
+    if(data)
+    {
+      p->allocsize = newsize;
+      p->data = (unsigned char*)data;
+    }
+    else return 0; /*error: not enough memory*/
+  }
+  return 1;
+}
+
+/*returns 1 if success, 0 if failure ==> nothing done*/
+static unsigned ucvector_resize(ucvector* p, size_t size)
+{
+  if(!ucvector_reserve(p, size * sizeof(unsigned char))) return 0;
+  p->size = size;
+  return 1; /*success*/
+}
+
+#ifdef LODEPNG_COMPILE_PNG
+
+static void ucvector_cleanup(void* p)
+{
+  ((ucvector*)p)->size = ((ucvector*)p)->allocsize = 0;
+  lodepng_free(((ucvector*)p)->data);
+  ((ucvector*)p)->data = NULL;
+}
+
+static void ucvector_init(ucvector* p)
+{
+  p->data = NULL;
+  p->size = p->allocsize = 0;
+}
+#endif /*LODEPNG_COMPILE_PNG*/
+
+#ifdef LODEPNG_COMPILE_ZLIB
+/*you can both convert from vector to buffer&size and vica versa. If you use
+init_buffer to take over a buffer and size, it is not needed to use cleanup*/
+static void ucvector_init_buffer(ucvector* p, unsigned char* buffer, size_t size)
+{
+  p->data = buffer;
+  p->allocsize = p->size = size;
+}
+#endif /*LODEPNG_COMPILE_ZLIB*/
+
+#if (defined(LODEPNG_COMPILE_PNG) && defined(LODEPNG_COMPILE_ANCILLARY_CHUNKS)) || defined(LODEPNG_COMPILE_ENCODER)
+/*returns 1 if success, 0 if failure ==> nothing done*/
+static unsigned ucvector_push_back(ucvector* p, unsigned char c)
+{
+  if(!ucvector_resize(p, p->size + 1)) return 0;
+  p->data[p->size - 1] = c;
+  return 1;
+}
+#endif /*defined(LODEPNG_COMPILE_PNG) || defined(LODEPNG_COMPILE_ENCODER)*/
+
+
+/* ////////////////////////////////////////////////////////////////////////// */
+
+#ifdef LODEPNG_COMPILE_PNG
+#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
+/*returns 1 if success, 0 if failure ==> nothing done*/
+static unsigned string_resize(char** out, size_t size)
+{
+  char* data = (char*)lodepng_realloc(*out, size + 1);
+  if(data)
+  {
+    data[size] = 0; /*null termination char*/
+    *out = data;
+  }
+  return data != 0;
+}
+
+/*init a {char*, size_t} pair for use as string*/
+static void string_init(char** out)
+{
+  *out = NULL;
+  string_resize(out, 0);
+}
+
+/*free the above pair again*/
+static void string_cleanup(char** out)
+{
+  lodepng_free(*out);
+  *out = NULL;
+}
+
+static void string_set(char** out, const char* in)
+{
+  size_t insize = strlen(in), i;
+  if(string_resize(out, insize))
+  {
+    for(i = 0; i != insize; ++i)
+    {
+      (*out)[i] = in[i];
+    }
+  }
+}
+#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
+#endif /*LODEPNG_COMPILE_PNG*/
+
+/* ////////////////////////////////////////////////////////////////////////// */
+
+unsigned lodepng_read32bitInt(const unsigned char* buffer)
+{
+  return (unsigned)((buffer[0] << 24) | (buffer[1] << 16) | (buffer[2] << 8) | buffer[3]);
+}
+
+#if defined(LODEPNG_COMPILE_PNG) || defined(LODEPNG_COMPILE_ENCODER)
+/*buffer must have at least 4 allocated bytes available*/
+static void lodepng_set32bitInt(unsigned char* buffer, unsigned value)
+{
+  buffer[0] = (unsigned char)((value >> 24) & 0xff);
+  buffer[1] = (unsigned char)((value >> 16) & 0xff);
+  buffer[2] = (unsigned char)((value >>  8) & 0xff);
+  buffer[3] = (unsigned char)((value      ) & 0xff);
+}
+#endif /*defined(LODEPNG_COMPILE_PNG) || defined(LODEPNG_COMPILE_ENCODER)*/
+
+#ifdef LODEPNG_COMPILE_ENCODER
+static void lodepng_add32bitInt(ucvector* buffer, unsigned value)
+{
+  ucvector_resize(buffer, buffer->size + 4); /*todo: give error if resize failed*/
+  lodepng_set32bitInt(&buffer->data[buffer->size - 4], value);
+}
+#endif /*LODEPNG_COMPILE_ENCODER*/
+
+/* ////////////////////////////////////////////////////////////////////////// */
+/* / File IO                                                                / */
+/* ////////////////////////////////////////////////////////////////////////// */
+
+#ifdef LODEPNG_COMPILE_DISK
+
+/* returns negative value on error. This should be pure C compatible, so no fstat. */
+static long lodepng_filesize(const char* filename)
+{
+  FILE* file;
+  long size;
+  file = fopen(filename, "rb");
+  if(!file) return -1;
+
+  if(fseek(file, 0, SEEK_END) != 0)
+  {
+    fclose(file);
+    return -1;
+  }
+
+  size = ftell(file);
+  /* It may give LONG_MAX as directory size, this is invalid for us. */
+  if(size == LONG_MAX) size = -1;
+
+  fclose(file);
+  return size;
+}
+
+/* load file into buffer that already has the correct allocated size. Returns error code.*/
+static unsigned lodepng_buffer_file(unsigned char* out, size_t size, const char* filename)
+{
+  FILE* file;
+  size_t readsize;
+  file = fopen(filename, "rb");
+  if(!file) return 78;
+
+  readsize = fread(out, 1, size, file);
+  fclose(file);
+
+  if (readsize != size) return 78;
+  return 0;
+}
+
+unsigned lodepng_load_file(unsigned char** out, size_t* outsize, const char* filename)
+{
+  long size = lodepng_filesize(filename);
+  if (size < 0) return 78;
+  *outsize = (size_t)size;
+
+  *out = (unsigned char*)lodepng_malloc((size_t)size);
+  if(!(*out) && size > 0) return 83; /*the above malloc failed*/
+
+  return lodepng_buffer_file(*out, (size_t)size, filename);
+}
+
+/*write given buffer to the file, overwriting the file, it doesn't append to it.*/
+unsigned lodepng_save_file(const unsigned char* buffer, size_t buffersize, const char* filename)
+{
+  FILE* file;
+  file = fopen(filename, "wb" );
+  if(!file) return 79;
+  fwrite((char*)buffer , 1 , buffersize, file);
+  fclose(file);
+  return 0;
+}
+
+#endif /*LODEPNG_COMPILE_DISK*/
+
+/* ////////////////////////////////////////////////////////////////////////// */
+/* ////////////////////////////////////////////////////////////////////////// */
+/* // End of common code and tools. Begin of Zlib related code.            // */
+/* ////////////////////////////////////////////////////////////////////////// */
+/* ////////////////////////////////////////////////////////////////////////// */
+
+#ifdef LODEPNG_COMPILE_ZLIB
+#ifdef LODEPNG_COMPILE_ENCODER
+/*TODO: this ignores potential out of memory errors*/
+#define addBitToStream(/*size_t**/ bitpointer, /*ucvector**/ bitstream, /*unsigned char*/ bit)\
+{\
+  /*add a new byte at the end*/\
+  if(((*bitpointer) & 7) == 0) ucvector_push_back(bitstream, (unsigned char)0);\
+  /*earlier bit of huffman code is in a lesser significant bit of an earlier byte*/\
+  (bitstream->data[bitstream->size - 1]) |= (bit << ((*bitpointer) & 0x7));\
+  ++(*bitpointer);\
+}
+
+static void addBitsToStream(size_t* bitpointer, ucvector* bitstream, unsigned value, size_t nbits)
+{
+  size_t i;
+  for(i = 0; i != nbits; ++i) addBitToStream(bitpointer, bitstream, (unsigned char)((value >> i) & 1));
+}
+
+static void addBitsToStreamReversed(size_t* bitpointer, ucvector* bitstream, unsigned value, size_t nbits)
+{
+  size_t i;
+  for(i = 0; i != nbits; ++i) addBitToStream(bitpointer, bitstream, (unsigned char)((value >> (nbits - 1 - i)) & 1));
+}
+#endif /*LODEPNG_COMPILE_ENCODER*/
+
+#ifdef LODEPNG_COMPILE_DECODER
+
+#define READBIT(bitpointer, bitstream) ((bitstream[bitpointer >> 3] >> (bitpointer & 0x7)) & (unsigned char)1)
+
+static unsigned char readBitFromStream(size_t* bitpointer, const unsigned char* bitstream)
+{
+  unsigned char result = (unsigned char)(READBIT(*bitpointer, bitstream));
+  ++(*bitpointer);
+  return result;
+}
+
+static unsigned readBitsFromStream(size_t* bitpointer, const unsigned char* bitstream, size_t nbits)
+{
+  unsigned result = 0, i;
+  for(i = 0; i != nbits; ++i)
+  {
+    result += ((unsigned)READBIT(*bitpointer, bitstream)) << i;
+    ++(*bitpointer);
+  }
+  return result;
+}
+#endif /*LODEPNG_COMPILE_DECODER*/
+
+/* ////////////////////////////////////////////////////////////////////////// */
+/* / Deflate - Huffman                                                      / */
+/* ////////////////////////////////////////////////////////////////////////// */
+
+#define FIRST_LENGTH_CODE_INDEX 257
+#define LAST_LENGTH_CODE_INDEX 285
+/*256 literals, the end code, some length codes, and 2 unused codes*/
+#define NUM_DEFLATE_CODE_SYMBOLS 288
+/*the distance codes have their own symbols, 30 used, 2 unused*/
+#define NUM_DISTANCE_SYMBOLS 32
+/*the code length codes. 0-15: code lengths, 16: copy previous 3-6 times, 17: 3-10 zeros, 18: 11-138 zeros*/
+#define NUM_CODE_LENGTH_CODES 19
+
+/*the base lengths represented by codes 257-285*/
+static const unsigned LENGTHBASE[29]
+  = {3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59,
+     67, 83, 99, 115, 131, 163, 195, 227, 258};
+
+/*the extra bits used by codes 257-285 (added to base length)*/
+static const unsigned LENGTHEXTRA[29]
+  = {0, 0, 0, 0, 0, 0, 0,  0,  1,  1,  1,  1,  2,  2,  2,  2,  3,  3,  3,  3,
+      4,  4,  4,   4,   5,   5,   5,   5,   0};
+
+/*the base backwards distances (the bits of distance codes appear after length codes and use their own huffman tree)*/
+static const unsigned DISTANCEBASE[30]
+  = {1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513,
+     769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577};
+
+/*the extra bits of backwards distances (added to base)*/
+static const unsigned DISTANCEEXTRA[30]
+  = {0, 0, 0, 0, 1, 1, 2,  2,  3,  3,  4,  4,  5,  5,   6,   6,   7,   7,   8,
+       8,    9,    9,   10,   10,   11,   11,   12,    12,    13,    13};
+
+/*the order in which "code length alphabet code lengths" are stored, out of this
+the huffman tree of the dynamic huffman tree lengths is generated*/
+static const unsigned CLCL_ORDER[NUM_CODE_LENGTH_CODES]
+  = {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
+
+/* ////////////////////////////////////////////////////////////////////////// */
+
+/*
+Huffman tree struct, containing multiple representations of the tree
+*/
+typedef struct HuffmanTree
+{
+  unsigned* tree2d;
+  unsigned* tree1d;
+  unsigned* lengths; /*the lengths of the codes of the 1d-tree*/
+  unsigned maxbitlen; /*maximum number of bits a single code can get*/
+  unsigned numcodes; /*number of symbols in the alphabet = number of codes*/
+} HuffmanTree;
+
+/*function used for debug purposes to draw the tree in ascii art with C++*/
+/*
+static void HuffmanTree_draw(HuffmanTree* tree)
+{
+  std::cout << "tree. length: " << tree->numcodes << " maxbitlen: " << tree->maxbitlen << std::endl;
+  for(size_t i = 0; i != tree->tree1d.size; ++i)
+  {
+    if(tree->lengths.data[i])
+      std::cout << i << " " << tree->tree1d.data[i] << " " << tree->lengths.data[i] << std::endl;
+  }
+  std::cout << std::endl;
+}*/
+
+static void HuffmanTree_init(HuffmanTree* tree)
+{
+  tree->tree2d = 0;
+  tree->tree1d = 0;
+  tree->lengths = 0;
+}
+
+static void HuffmanTree_cleanup(HuffmanTree* tree)
+{
+  lodepng_free(tree->tree2d);
+  lodepng_free(tree->tree1d);
+  lodepng_free(tree->lengths);
+}
+
+/*the tree representation used by the decoder. return value is error*/
+static unsigned HuffmanTree_make2DTree(HuffmanTree* tree)
+{
+  unsigned nodefilled = 0; /*up to which node it is filled*/
+  unsigned treepos = 0; /*position in the tree (1 of the numcodes columns)*/
+  unsigned n, i;
+
+  tree->tree2d = (unsigned*)lodepng_malloc(tree->numcodes * 2 * sizeof(unsigned));
+  if(!tree->tree2d) return 83; /*alloc fail*/
+
+  /*
+  convert tree1d[] to tree2d[][]. In the 2D array, a value of 32767 means
+  uninited, a value >= numcodes is an address to another bit, a value < numcodes
+  is a code. The 2 rows are the 2 possible bit values (0 or 1), there are as
+  many columns as codes - 1.
+  A good huffman tree has N * 2 - 1 nodes, of which N - 1 are internal nodes.
+  Here, the internal nodes are stored (what their 0 and 1 option point to).
+  There is only memory for such good tree currently, if there are more nodes
+  (due to too long length codes), error 55 will happen
+  */
+  for(n = 0; n < tree->numcodes * 2; ++n)
+  {
+    tree->tree2d[n] = 32767; /*32767 here means the tree2d isn't filled there yet*/
+  }
+
+  for(n = 0; n < tree->numcodes; ++n) /*the codes*/
+  {
+    for(i = 0; i != tree->lengths[n]; ++i) /*the bits for this code*/
+    {
+      unsigned char bit = (unsigned char)((tree->tree1d[n] >> (tree->lengths[n] - i - 1)) & 1);
+      /*oversubscribed, see comment in lodepng_error_text*/
+      if(treepos > 2147483647 || treepos + 2 > tree->numcodes) return 55;
+      if(tree->tree2d[2 * treepos + bit] == 32767) /*not yet filled in*/
+      {
+        if(i + 1 == tree->lengths[n]) /*last bit*/
+        {
+          tree->tree2d[2 * treepos + bit] = n; /*put the current code in it*/
+          treepos = 0;
+        }
+        else
+        {
+          /*put address of the next step in here, first that address has to be found of course
+          (it's just nodefilled + 1)...*/
+          ++nodefilled;
+          /*addresses encoded with numcodes added to it*/
+          tree->tree2d[2 * treepos + bit] = nodefilled + tree->numcodes;
+          treepos = nodefilled;
+        }
+      }
+      else treepos = tree->tree2d[2 * treepos + bit] - tree->numcodes;
+    }
+  }
+
+  for(n = 0; n < tree->numcodes * 2; ++n)
+  {
+    if(tree->tree2d[n] == 32767) tree->tree2d[n] = 0; /*remove possible remaining 32767's*/
+  }
+
+  return 0;
+}
+
+/*
+Second step for the ...makeFromLengths and ...makeFromFrequencies functions.
+numcodes, lengths and maxbitlen must already be filled in correctly. return
+value is error.
+*/
+static unsigned HuffmanTree_makeFromLengths2(HuffmanTree* tree)
+{
+  uivector blcount;
+  uivector nextcode;
+  unsigned error = 0;
+  unsigned bits, n;
+
+  uivector_init(&blcount);
+  uivector_init(&nextcode);
+
+  tree->tree1d = (unsigned*)lodepng_malloc(tree->numcodes * sizeof(unsigned));
+  if(!tree->tree1d) error = 83; /*alloc fail*/
+
+  if(!uivector_resizev(&blcount, tree->maxbitlen + 1, 0)
+  || !uivector_resizev(&nextcode, tree->maxbitlen + 1, 0))
+    error = 83; /*alloc fail*/
+
+  if(!error)
+  {
+    /*step 1: count number of instances of each code length*/
+    for(bits = 0; bits != tree->numcodes; ++bits) ++blcount.data[tree->lengths[bits]];
+    /*step 2: generate the nextcode values*/
+    for(bits = 1; bits <= tree->maxbitlen; ++bits)
+    {
+      nextcode.data[bits] = (nextcode.data[bits - 1] + blcount.data[bits - 1]) << 1;
+    }
+    /*step 3: generate all the codes*/
+    for(n = 0; n != tree->numcodes; ++n)
+    {
+      if(tree->lengths[n] != 0) tree->tree1d[n] = nextcode.data[tree->lengths[n]]++;
+    }
+  }
+
+  uivector_cleanup(&blcount);
+  uivector_cleanup(&nextcode);
+
+  if(!error) return HuffmanTree_make2DTree(tree);
+  else return error;
+}
+
+/*
+given the code lengths (as stored in the PNG file), generate the tree as defined
+by Deflate. maxbitlen is the maximum bits that a code in the tree can have.
+return value is error.
+*/
+static unsigned HuffmanTree_makeFromLengths(HuffmanTree* tree, const unsigned* bitlen,
+                                            size_t numcodes, unsigned maxbitlen)
+{
+  unsigned i;
+  tree->lengths = (unsigned*)lodepng_malloc(numcodes * sizeof(unsigned));
+  if(!tree->lengths) return 83; /*alloc fail*/
+  for(i = 0; i != numcodes; ++i) tree->lengths[i] = bitlen[i];
+  tree->numcodes = (unsigned)numcodes; /*number of symbols*/
+  tree->maxbitlen = maxbitlen;
+  return HuffmanTree_makeFromLengths2(tree);
+}
+
+#ifdef LODEPNG_COMPILE_ENCODER
+
+/*BPM: Boundary Package Merge, see "A Fast and Space-Economical Algorithm for Length-Limited Coding",
+Jyrki Katajainen, Alistair Moffat, Andrew Turpin, 1995.*/
+
+/*chain node for boundary package merge*/
+typedef struct BPMNode
+{
+  int weight; /*the sum of all weights in this chain*/
+  unsigned index; /*index of this leaf node (called "count" in the paper)*/
+  struct BPMNode* tail; /*the next nodes in this chain (null if last)*/
+  int in_use;
+} BPMNode;
+
+/*lists of chains*/
+typedef struct BPMLists
+{
+  /*memory pool*/
+  unsigned memsize;
+  BPMNode* memory;
+  unsigned numfree;
+  unsigned nextfree;
+  BPMNode** freelist;
+  /*two heads of lookahead chains per list*/
+  unsigned listsize;
+  BPMNode** chains0;
+  BPMNode** chains1;
+} BPMLists;
+
+/*creates a new chain node with the given parameters, from the memory in the lists */
+static BPMNode* bpmnode_create(BPMLists* lists, int weight, unsigned index, BPMNode* tail)
+{
+  unsigned i;
+  BPMNode* result;
+
+  /*memory full, so garbage collect*/
+  if(lists->nextfree >= lists->numfree)
+  {
+    /*mark only those that are in use*/
+    for(i = 0; i != lists->memsize; ++i) lists->memory[i].in_use = 0;
+    for(i = 0; i != lists->listsize; ++i)
+    {
+      BPMNode* node;
+      for(node = lists->chains0[i]; node != 0; node = node->tail) node->in_use = 1;
+      for(node = lists->chains1[i]; node != 0; node = node->tail) node->in_use = 1;
+    }
+    /*collect those that are free*/
+    lists->numfree = 0;
+    for(i = 0; i != lists->memsize; ++i)
+    {
+      if(!lists->memory[i].in_use) lists->freelist[lists->numfree++] = &lists->memory[i];
+    }
+    lists->nextfree = 0;
+  }
+
+  result = lists->freelist[lists->nextfree++];
+  result->weight = weight;
+  result->index = index;
+  result->tail = tail;
+  return result;
+}
+
+/*sort the leaves with stable mergesort*/
+static void bpmnode_sort(BPMNode* leaves, size_t num)
+{
+  BPMNode* mem = (BPMNode*)lodepng_malloc(sizeof(*leaves) * num);
+  size_t width, counter = 0;
+  for(width = 1; width < num; width *= 2)
+  {
+    BPMNode* a = (counter & 1) ? mem : leaves;
+    BPMNode* b = (counter & 1) ? leaves : mem;
+    size_t p;
+    for(p = 0; p < num; p += 2 * width)
+    {
+      size_t q = (p + width > num) ? num : (p + width);
+      size_t r = (p + 2 * width > num) ? num : (p + 2 * width);
+      size_t i = p, j = q, k;
+      for(k = p; k < r; k++)
+      {
+        if(i < q && (j >= r || a[i].weight <= a[j].weight)) b[k] = a[i++];
+        else b[k] = a[j++];
+      }
+    }
+    counter++;
+  }
+  if(counter & 1) memcpy(leaves, mem, sizeof(*leaves) * num);
+  lodepng_free(mem);
+}
+
+/*Boundary Package Merge step, numpresent is the amount of leaves, and c is the current chain.*/
+static void boundaryPM(BPMLists* lists, BPMNode* leaves, size_t numpresent, int c, int num)
+{
+  unsigned lastindex = lists->chains1[c]->index;
+
+  if(c == 0)
+  {
+    if(lastindex >= numpresent) return;
+    lists->chains0[c] = lists->chains1[c];
+    lists->chains1[c] = bpmnode_create(lists, leaves[lastindex].weight, lastindex + 1, 0);
+  }
+  else
+  {
+    /*sum of the weights of the head nodes of the previous lookahead chains.*/
+    int sum = lists->chains0[c - 1]->weight + lists->chains1[c - 1]->weight;
+    lists->chains0[c] = lists->chains1[c];
+    if(lastindex < numpresent && sum > leaves[lastindex].weight)
+    {
+      lists->chains1[c] = bpmnode_create(lists, leaves[lastindex].weight, lastindex + 1, lists->chains1[c]->tail);
+      return;
+    }
+    lists->chains1[c] = bpmnode_create(lists, sum, lastindex, lists->chains1[c - 1]);
+    /*in the end we are only interested in the chain of the last list, so no
+    need to recurse if we're at the last one (this gives measurable speedup)*/
+    if(num + 1 < (int)(2 * numpresent - 2))
+    {
+      boundaryPM(lists, leaves, numpresent, c - 1, num);
+      boundaryPM(lists, leaves, numpresent, c - 1, num);
+    }
+  }
+}
+
+unsigned lodepng_huffman_code_lengths(unsigned* lengths, const unsigned* frequencies,
+                                      size_t numcodes, unsigned maxbitlen)
+{
+  unsigned error = 0;
+  unsigned i;
+  size_t numpresent = 0; /*number of symbols with non-zero frequency*/
+  BPMNode* leaves; /*the symbols, only those with > 0 frequency*/
+
+  if(numcodes == 0) return 80; /*error: a tree of 0 symbols is not supposed to be made*/
+  if((1u << maxbitlen) < numcodes) return 80; /*error: represent all symbols*/
+
+  leaves = (BPMNode*)lodepng_malloc(numcodes * sizeof(*leaves));
+  if(!leaves) return 83; /*alloc fail*/
+
+  for(i = 0; i != numcodes; ++i)
+  {
+    if(frequencies[i] > 0)
+    {
+      leaves[numpresent].weight = (int)frequencies[i];
+      leaves[numpresent].index = i;
+      ++numpresent;
+    }
+  }
+
+  for(i = 0; i != numcodes; ++i) lengths[i] = 0;
+
+  /*ensure at least two present symbols. There should be at least one symbol
+  according to RFC 1951 section 3.2.7. Some decoders incorrectly require two. To
+  make these work as well ensure there are at least two symbols. The
+  Package-Merge code below also doesn't work correctly if there's only one
+  symbol, it'd give it the theoritical 0 bits but in practice zlib wants 1 bit*/
+  if(numpresent == 0)
+  {
+    lengths[0] = lengths[1] = 1; /*note that for RFC 1951 section 3.2.7, only lengths[0] = 1 is needed*/
+  }
+  else if(numpresent == 1)
+  {
+    lengths[leaves[0].index] = 1;
+    lengths[leaves[0].index == 0 ? 1 : 0] = 1;
+  }
+  else
+  {
+    BPMLists lists;
+    BPMNode* node;
+
+    bpmnode_sort(leaves, numpresent);
+
+    lists.listsize = maxbitlen;
+    lists.memsize = 2 * maxbitlen * (maxbitlen + 1);
+    lists.nextfree = 0;
+    lists.numfree = lists.memsize;
+    lists.memory = (BPMNode*)lodepng_malloc(lists.memsize * sizeof(*lists.memory));
+    lists.freelist = (BPMNode**)lodepng_malloc(lists.memsize * sizeof(BPMNode*));
+    lists.chains0 = (BPMNode**)lodepng_malloc(lists.listsize * sizeof(BPMNode*));
+    lists.chains1 = (BPMNode**)lodepng_malloc(lists.listsize * sizeof(BPMNode*));
+    if(!lists.memory || !lists.freelist || !lists.chains0 || !lists.chains1) error = 83; /*alloc fail*/
+
+    if(!error)
+    {
+      for(i = 0; i != lists.memsize; ++i) lists.freelist[i] = &lists.memory[i];
+
+      bpmnode_create(&lists, leaves[0].weight, 1, 0);
+      bpmnode_create(&lists, leaves[1].weight, 2, 0);
+
+      for(i = 0; i != lists.listsize; ++i)
+      {
+        lists.chains0[i] = &lists.memory[0];
+        lists.chains1[i] = &lists.memory[1];
+      }
+
+      /*each boundaryPM call adds one chain to the last list, and we need 2 * numpresent - 2 chains.*/
+      for(i = 2; i != 2 * numpresent - 2; ++i) boundaryPM(&lists, leaves, numpresent, (int)maxbitlen - 1, (int)i);
+
+      for(node = lists.chains1[maxbitlen - 1]; node; node = node->tail)
+      {
+        for(i = 0; i != node->index; ++i) ++lengths[leaves[i].index];
+      }
+    }
+
+    lodepng_free(lists.memory);
+    lodepng_free(lists.freelist);
+    lodepng_free(lists.chains0);
+    lodepng_free(lists.chains1);
+  }
+
+  lodepng_free(leaves);
+  return error;
+}
+
+/*Create the Huffman tree given the symbol frequencies*/
+static unsigned HuffmanTree_makeFromFrequencies(HuffmanTree* tree, const unsigned* frequencies,
+                                                size_t mincodes, size_t numcodes, unsigned maxbitlen)
+{
+  unsigned error = 0;
+  while(!frequencies[numcodes - 1] && numcodes > mincodes) --numcodes; /*trim zeroes*/
+  tree->maxbitlen = maxbitlen;
+  tree->numcodes = (unsigned)numcodes; /*number of symbols*/
+  tree->lengths = (unsigned*)lodepng_realloc(tree->lengths, numcodes * sizeof(unsigned));
+  if(!tree->lengths) return 83; /*alloc fail*/
+  /*initialize all lengths to 0*/
+  memset(tree->lengths, 0, numcodes * sizeof(unsigned));
+
+  error = lodepng_huffman_code_lengths(tree->lengths, frequencies, numcodes, maxbitlen);
+  if(!error) error = HuffmanTree_makeFromLengths2(tree);
+  return error;
+}
+
+static unsigned HuffmanTree_getCode(const HuffmanTree* tree, unsigned index)
+{
+  return tree->tree1d[index];
+}
+
+static unsigned HuffmanTree_getLength(const HuffmanTree* tree, unsigned index)
+{
+  return tree->lengths[index];
+}
+#endif /*LODEPNG_COMPILE_ENCODER*/
+
+/*get the literal and length code tree of a deflated block with fixed tree, as per the deflate specification*/
+static unsigned generateFixedLitLenTree(HuffmanTree* tree)
+{
+  unsigned i, error = 0;
+  unsigned* bitlen = (unsigned*)lodepng_malloc(NUM_DEFLATE_CODE_SYMBOLS * sizeof(unsigned));
+  if(!bitlen) return 83; /*alloc fail*/
+
+  /*288 possible codes: 0-255=literals, 256=endcode, 257-285=lengthcodes, 286-287=unused*/
+  for(i =   0; i <= 143; ++i) bitlen[i] = 8;
+  for(i = 144; i <= 255; ++i) bitlen[i] = 9;
+  for(i = 256; i <= 279; ++i) bitlen[i] = 7;
+  for(i = 280; i <= 287; ++i) bitlen[i] = 8;
+
+  error = HuffmanTree_makeFromLengths(tree, bitlen, NUM_DEFLATE_CODE_SYMBOLS, 15);
+
+  lodepng_free(bitlen);
+  return error;
+}
+
+/*get the distance code tree of a deflated block with fixed tree, as specified in the deflate specification*/
+static unsigned generateFixedDistanceTree(HuffmanTree* tree)
+{
+  unsigned i, error = 0;
+  unsigned* bitlen = (unsigned*)lodepng_malloc(NUM_DISTANCE_SYMBOLS * sizeof(unsigned));
+  if(!bitlen) return 83; /*alloc fail*/
+
+  /*there are 32 distance codes, but 30-31 are unused*/
+  for(i = 0; i != NUM_DISTANCE_SYMBOLS; ++i) bitlen[i] = 5;
+  error = HuffmanTree_makeFromLengths(tree, bitlen, NUM_DISTANCE_SYMBOLS, 15);
+
+  lodepng_free(bitlen);
+  return error;
+}
+
+#ifdef LODEPNG_COMPILE_DECODER
+
+/*
+returns the code, or (unsigned)(-1) if error happened
+inbitlength is the length of the complete buffer, in bits (so its byte length times 8)
+*/
+static unsigned huffmanDecodeSymbol(const unsigned char* in, size_t* bp,
+                                    const HuffmanTree* codetree, size_t inbitlength)
+{
+  unsigned treepos = 0, ct;
+  for(;;)
+  {
+    if(*bp >= inbitlength) return (unsigned)(-1); /*error: end of input memory reached without endcode*/
+    /*
+    decode the symbol from the tree. The "readBitFromStream" code is inlined in
+    the expression below because this is the biggest bottleneck while decoding
+    */
+    ct = codetree->tree2d[(treepos << 1) + READBIT(*bp, in)];
+    ++(*bp);
+    if(ct < codetree->numcodes) return ct; /*the symbol is decoded, return it*/
+    else treepos = ct - codetree->numcodes; /*symbol not yet decoded, instead move tree position*/
+
+    if(treepos >= codetree->numcodes) return (unsigned)(-1); /*error: it appeared outside the codetree*/
+  }
+}
+#endif /*LODEPNG_COMPILE_DECODER*/
+
+#ifdef LODEPNG_COMPILE_DECODER
+
+/* ////////////////////////////////////////////////////////////////////////// */
+/* / Inflator (Decompressor)                                                / */
+/* ////////////////////////////////////////////////////////////////////////// */
+
+/*get the tree of a deflated block with fixed tree, as specified in the deflate specification*/
+static void getTreeInflateFixed(HuffmanTree* tree_ll, HuffmanTree* tree_d)
+{
+  /*TODO: check for out of memory errors*/
+  generateFixedLitLenTree(tree_ll);
+  generateFixedDistanceTree(tree_d);
+}
+
+/*get the tree of a deflated block with dynamic tree, the tree itself is also Huffman compressed with a known tree*/
+static unsigned getTreeInflateDynamic(HuffmanTree* tree_ll, HuffmanTree* tree_d,
+                                      const unsigned char* in, size_t* bp, size_t inlength)
+{
+  /*make sure that length values that aren't filled in will be 0, or a wrong tree will be generated*/
+  unsigned error = 0;
+  unsigned n, HLIT, HDIST, HCLEN, i;
+  size_t inbitlength = inlength * 8;
+
+  /*see comments in deflateDynamic for explanation of the context and these variables, it is analogous*/
+  unsigned* bitlen_ll = 0; /*lit,len code lengths*/
+  unsigned* bitlen_d = 0; /*dist code lengths*/
+  /*code length code lengths ("clcl"), the bit lengths of the huffman tree used to compress bitlen_ll and bitlen_d*/
+  unsigned* bitlen_cl = 0;
+  HuffmanTree tree_cl; /*the code tree for code length codes (the huffman tree for compressed huffman trees)*/
+
+  if((*bp) + 14 > (inlength << 3)) return 49; /*error: the bit pointer is or will go past the memory*/
+
+  /*number of literal/length codes + 257. Unlike the spec, the value 257 is added to it here already*/
+  HLIT =  readBitsFromStream(bp, in, 5) + 257;
+  /*number of distance codes. Unlike the spec, the value 1 is added to it here already*/
+  HDIST = readBitsFromStream(bp, in, 5) + 1;
+  /*number of code length codes. Unlike the spec, the value 4 is added to it here already*/
+  HCLEN = readBitsFromStream(bp, in, 4) + 4;
+
+  if((*bp) + HCLEN * 3 > (inlength << 3)) return 50; /*error: the bit pointer is or will go past the memory*/
+
+  HuffmanTree_init(&tree_cl);
+
+  while(!error)
+  {
+    /*read the code length codes out of 3 * (amount of code length codes) bits*/
+
+    bitlen_cl = (unsigned*)lodepng_malloc(NUM_CODE_LENGTH_CODES * sizeof(unsigned));
+    if(!bitlen_cl) ERROR_BREAK(83 /*alloc fail*/);
+
+    for(i = 0; i != NUM_CODE_LENGTH_CODES; ++i)
+    {
+      if(i < HCLEN) bitlen_cl[CLCL_ORDER[i]] = readBitsFromStream(bp, in, 3);
+      else bitlen_cl[CLCL_ORDER[i]] = 0; /*if not, it must stay 0*/
+    }
+
+    error = HuffmanTree_makeFromLengths(&tree_cl, bitlen_cl, NUM_CODE_LENGTH_CODES, 7);
+    if(error) break;
+
+    /*now we can use this tree to read the lengths for the tree that this function will return*/
+    bitlen_ll = (unsigned*)lodepng_malloc(NUM_DEFLATE_CODE_SYMBOLS * sizeof(unsigned));
+    bitlen_d = (unsigned*)lodepng_malloc(NUM_DISTANCE_SYMBOLS * sizeof(unsigned));
+    if(!bitlen_ll || !bitlen_d) ERROR_BREAK(83 /*alloc fail*/);
+    for(i = 0; i != NUM_DEFLATE_CODE_SYMBOLS; ++i) bitlen_ll[i] = 0;
+    for(i = 0; i != NUM_DISTANCE_SYMBOLS; ++i) bitlen_d[i] = 0;
+
+    /*i is the current symbol we're reading in the part that contains the code lengths of lit/len and dist codes*/
+    i = 0;
+    while(i < HLIT + HDIST)
+    {
+      unsigned code = huffmanDecodeSymbol(in, bp, &tree_cl, inbitlength);
+      if(code <= 15) /*a length code*/
+      {
+        if(i < HLIT) bitlen_ll[i] = code;
+        else bitlen_d[i - HLIT] = code;
+        ++i;
+      }
+      else if(code == 16) /*repeat previous*/
+      {
+        unsigned replength = 3; /*read in the 2 bits that indicate repeat length (3-6)*/
+        unsigned value; /*set value to the previous code*/
+
+        if(i == 0) ERROR_BREAK(54); /*can't repeat previous if i is 0*/
+
+        if((*bp + 2) > inbitlength) ERROR_BREAK(50); /*error, bit pointer jumps past memory*/
+        replength += readBitsFromStream(bp, in, 2);
+
+        if(i < HLIT + 1) value = bitlen_ll[i - 1];
+        else value = bitlen_d[i - HLIT - 1];
+        /*repeat this value in the next lengths*/
+        for(n = 0; n < replength; ++n)
+        {
+          if(i >= HLIT + HDIST) ERROR_BREAK(13); /*error: i is larger than the amount of codes*/
+          if(i < HLIT) bitlen_ll[i] = value;
+          else bitlen_d[i - HLIT] = value;
+          ++i;
+        }
+      }
+      else if(code == 17) /*repeat "0" 3-10 times*/
+      {
+        unsigned replength = 3; /*read in the bits that indicate repeat length*/
+        if((*bp + 3) > inbitlength) ERROR_BREAK(50); /*error, bit pointer jumps past memory*/
+        replength += readBitsFromStream(bp, in, 3);
+
+        /*repeat this value in the next lengths*/
+        for(n = 0; n < replength; ++n)
+        {
+          if(i >= HLIT + HDIST) ERROR_BREAK(14); /*error: i is larger than the amount of codes*/
+
+          if(i < HLIT) bitlen_ll[i] = 0;
+          else bitlen_d[i - HLIT] = 0;
+          ++i;
+        }
+      }
+      else if(code == 18) /*repeat "0" 11-138 times*/
+      {
+        unsigned replength = 11; /*read in the bits that indicate repeat length*/
+        if((*bp + 7) > inbitlength) ERROR_BREAK(50); /*error, bit pointer jumps past memory*/
+        replength += readBitsFromStream(bp, in, 7);
+
+        /*repeat this value in the next lengths*/
+        for(n = 0; n < replength; ++n)
+        {
+          if(i >= HLIT + HDIST) ERROR_BREAK(15); /*error: i is larger than the amount of codes*/
+
+          if(i < HLIT) bitlen_ll[i] = 0;
+          else bitlen_d[i - HLIT] = 0;
+          ++i;
+        }
+      }
+      else /*if(code == (unsigned)(-1))*/ /*huffmanDecodeSymbol returns (unsigned)(-1) in case of error*/
+      {
+        if(code == (unsigned)(-1))
+        {
+          /*return error code 10 or 11 depending on the situation that happened in huffmanDecodeSymbol
+          (10=no endcode, 11=wrong jump outside of tree)*/
+          error = (*bp) > inbitlength ? 10 : 11;
+        }
+        else error = 16; /*unexisting code, this can never happen*/
+        break;
+      }
+    }
+    if(error) break;
+
+    if(bitlen_ll[256] == 0) ERROR_BREAK(64); /*the length of the end code 256 must be larger than 0*/
+
+    /*now we've finally got HLIT and HDIST, so generate the code trees, and the function is done*/
+    error = HuffmanTree_makeFromLengths(tree_ll, bitlen_ll, NUM_DEFLATE_CODE_SYMBOLS, 15);
+    if(error) break;
+    error = HuffmanTree_makeFromLengths(tree_d, bitlen_d, NUM_DISTANCE_SYMBOLS, 15);
+
+    break; /*end of error-while*/
+  }
+
+  lodepng_free(bitlen_cl);
+  lodepng_free(bitlen_ll);
+  lodepng_free(bitlen_d);
+  HuffmanTree_cleanup(&tree_cl);
+
+  return error;
+}
+
+/*inflate a block with dynamic of fixed Huffman tree*/
+static unsigned inflateHuffmanBlock(ucvector* out, const unsigned char* in, size_t* bp,
+                                    size_t* pos, size_t inlength, unsigned btype)
+{
+  unsigned error = 0;
+  HuffmanTree tree_ll; /*the huffman tree for literal and length codes*/
+  HuffmanTree tree_d; /*the huffman tree for distance codes*/
+  size_t inbitlength = inlength * 8;
+
+  HuffmanTree_init(&tree_ll);
+  HuffmanTree_init(&tree_d);
+
+  if(btype == 1) getTreeInflateFixed(&tree_ll, &tree_d);
+  else if(btype == 2) error = getTreeInflateDynamic(&tree_ll, &tree_d, in, bp, inlength);
+
+  while(!error) /*decode all symbols until end reached, breaks at end code*/
+  {
+    /*code_ll is literal, length or end code*/
+    unsigned code_ll = huffmanDecodeSymbol(in, bp, &tree_ll, inbitlength);
+    if(code_ll <= 255) /*literal symbol*/
+    {
+      /*ucvector_push_back would do the same, but for some reason the two lines below run 10% faster*/
+      if(!ucvector_resize(out, (*pos) + 1)) ERROR_BREAK(83 /*alloc fail*/);
+      out->data[*pos] = (unsigned char)code_ll;
+      ++(*pos);
+    }
+    else if(code_ll >= FIRST_LENGTH_CODE_INDEX && code_ll <= LAST_LENGTH_CODE_INDEX) /*length code*/
+    {
+      unsigned code_d, distance;
+      unsigned numextrabits_l, numextrabits_d; /*extra bits for length and distance*/
+      size_t start, forward, backward, length;
+
+      /*part 1: get length base*/
+      length = LENGTHBASE[code_ll - FIRST_LENGTH_CODE_INDEX];
+
+      /*part 2: get extra bits and add the value of that to length*/
+      numextrabits_l = LENGTHEXTRA[code_ll - FIRST_LENGTH_CODE_INDEX];
+      if((*bp + numextrabits_l) > inbitlength) ERROR_BREAK(51); /*error, bit pointer will jump past memory*/
+      length += readBitsFromStream(bp, in, numextrabits_l);
+
+      /*part 3: get distance code*/
+      code_d = huffmanDecodeSymbol(in, bp, &tree_d, inbitlength);
+      if(code_d > 29)
+      {
+        if(code_ll == (unsigned)(-1)) /*huffmanDecodeSymbol returns (unsigned)(-1) in case of error*/
+        {
+          /*return error code 10 or 11 depending on the situation that happened in huffmanDecodeSymbol
+          (10=no endcode, 11=wrong jump outside of tree)*/
+          error = (*bp) > inlength * 8 ? 10 : 11;
+        }
+        else error = 18; /*error: invalid distance code (30-31 are never used)*/
+        break;
+      }
+      distance = DISTANCEBASE[code_d];
+
+      /*part 4: get extra bits from distance*/
+      numextrabits_d = DISTANCEEXTRA[code_d];
+      if((*bp + numextrabits_d) > inbitlength) ERROR_BREAK(51); /*error, bit pointer will jump past memory*/
+      distance += readBitsFromStream(bp, in, numextrabits_d);
+
+      /*part 5: fill in all the out[n] values based on the length and dist*/
+      start = (*pos);
+      if(distance > start) ERROR_BREAK(52); /*too long backward distance*/
+      backward = start - distance;
+
+      if(!ucvector_resize(out, (*pos) + length)) ERROR_BREAK(83 /*alloc fail*/);
+      if (distance < length) {
+        for(forward = 0; forward < length; ++forward)
+        {
+          out->data[(*pos)++] = out->data[backward++];
+        }
+      } else {
+        memcpy(out->data + *pos, out->data + backward, length);
+        *pos += length;
+      }
+    }
+    else if(code_ll == 256)
+    {
+      break; /*end code, break the loop*/
+    }
+    else /*if(code == (unsigned)(-1))*/ /*huffmanDecodeSymbol returns (unsigned)(-1) in case of error*/
+    {
+      /*return error code 10 or 11 depending on the situation that happened in huffmanDecodeSymbol
+      (10=no endcode, 11=wrong jump outside of tree)*/
+      error = ((*bp) > inlength * 8) ? 10 : 11;
+      break;
+    }
+  }
+
+  HuffmanTree_cleanup(&tree_ll);
+  HuffmanTree_cleanup(&tree_d);
+
+  return error;
+}
+
+static unsigned inflateNoCompression(ucvector* out, const unsigned char* in, size_t* bp, size_t* pos, size_t inlength)
+{
+  size_t p;
+  unsigned LEN, NLEN, n, error = 0;
+
+  /*go to first boundary of byte*/
+  while(((*bp) & 0x7) != 0) ++(*bp);
+  p = (*bp) / 8; /*byte position*/
+
+  /*read LEN (2 bytes) and NLEN (2 bytes)*/
+  if(p + 4 >= inlength) return 52; /*error, bit pointer will jump past memory*/
+  LEN = in[p] + 256u * in[p + 1]; p += 2;
+  NLEN = in[p] + 256u * in[p + 1]; p += 2;
+
+  /*check if 16-bit NLEN is really the one's complement of LEN*/
+  if(LEN + NLEN != 65535) return 21; /*error: NLEN is not one's complement of LEN*/
+
+  if(!ucvector_resize(out, (*pos) + LEN)) return 83; /*alloc fail*/
+
+  /*read the literal data: LEN bytes are now stored in the out buffer*/
+  if(p + LEN > inlength) return 23; /*error: reading outside of in buffer*/
+  for(n = 0; n < LEN; ++n) out->data[(*pos)++] = in[p++];
+
+  (*bp) = p * 8;
+
+  return error;
+}
+
+static unsigned lodepng_inflatev(ucvector* out,
+                                 const unsigned char* in, size_t insize,
+                                 const LodePNGDecompressSettings* settings)
+{
+  /*bit pointer in the "in" data, current byte is bp >> 3, current bit is bp & 0x7 (from lsb to msb of the byte)*/
+  size_t bp = 0;
+  unsigned BFINAL = 0;
+  size_t pos = 0; /*byte position in the out buffer*/
+  unsigned error = 0;
+
+  (void)settings;
+
+  while(!BFINAL)
+  {
+    unsigned BTYPE;
+    if(bp + 2 >= insize * 8) return 52; /*error, bit pointer will jump past memory*/
+    BFINAL = readBitFromStream(&bp, in);
+    BTYPE = 1u * readBitFromStream(&bp, in);
+    BTYPE += 2u * readBitFromStream(&bp, in);
+
+    if(BTYPE == 3) return 20; /*error: invalid BTYPE*/
+    else if(BTYPE == 0) error = inflateNoCompression(out, in, &bp, &pos, insize); /*no compression*/
+    else error = inflateHuffmanBlock(out, in, &bp, &pos, insize, BTYPE); /*compression, BTYPE 01 or 10*/
+
+    if(error) return error;
+  }
+
+  return error;
+}
+
+unsigned lodepng_inflate(unsigned char** out, size_t* outsize,
+                         const unsigned char* in, size_t insize,
+                         const LodePNGDecompressSettings* settings)
+{
+  unsigned error;
+  ucvector v;
+  ucvector_init_buffer(&v, *out, *outsize);
+  error = lodepng_inflatev(&v, in, insize, settings);
+  *out = v.data;
+  *outsize = v.size;
+  return error;
+}
+
+static unsigned inflate(unsigned char** out, size_t* outsize,
+                        const unsigned char* in, size_t insize,
+                        const LodePNGDecompressSettings* settings)
+{
+  if(settings->custom_inflate)
+  {
+    return settings->custom_inflate(out, outsize, in, insize, settings);
+  }
+  else
+  {
+    return lodepng_inflate(out, outsize, in, insize, settings);
+  }
+}
+
+#endif /*LODEPNG_COMPILE_DECODER*/
+
+#ifdef LODEPNG_COMPILE_ENCODER
+
+/* ////////////////////////////////////////////////////////////////////////// */
+/* / Deflator (Compressor)                                                  / */
+/* ////////////////////////////////////////////////////////////////////////// */
+
+static const size_t MAX_SUPPORTED_DEFLATE_LENGTH = 258;
+
+/*bitlen is the size in bits of the code*/
+static void addHuffmanSymbol(size_t* bp, ucvector* compressed, unsigned code, unsigned bitlen)
+{
+  addBitsToStreamReversed(bp, compressed, code, bitlen);
+}
+
+/*search the index in the array, that has the largest value smaller than or equal to the given value,
+given array must be sorted (if no value is smaller, it returns the size of the given array)*/
+static size_t searchCodeIndex(const unsigned* array, size_t array_size, size_t value)
+{
+  /*binary search (only small gain over linear). TODO: use CPU log2 instruction for getting symbols instead*/
+  size_t left = 1;
+  size_t right = array_size - 1;
+
+  while(left <= right) {
+    size_t mid = (left + right) >> 1;
+    if (array[mid] >= value) right = mid - 1;
+    else left = mid + 1;
+  }
+  if(left >= array_size || array[left] > value) left--;
+  return left;
+}
+
+static void addLengthDistance(uivector* values, size_t length, size_t distance)
+{
+  /*values in encoded vector are those used by deflate:
+  0-255: literal bytes
+  256: end
+  257-285: length/distance pair (length code, followed by extra length bits, distance code, extra distance bits)
+  286-287: invalid*/
+
+  unsigned length_code = (unsigned)searchCodeIndex(LENGTHBASE, 29, length);
+  unsigned extra_length = (unsigned)(length - LENGTHBASE[length_code]);
+  unsigned dist_code = (unsigned)searchCodeIndex(DISTANCEBASE, 30, distance);
+  unsigned extra_distance = (unsigned)(distance - DISTANCEBASE[dist_code]);
+
+  uivector_push_back(values, length_code + FIRST_LENGTH_CODE_INDEX);
+  uivector_push_back(values, extra_length);
+  uivector_push_back(values, dist_code);
+  uivector_push_back(values, extra_distance);
+}
+
+/*3 bytes of data get encoded into two bytes. The hash cannot use more than 3
+bytes as input because 3 is the minimum match length for deflate*/
+static const unsigned HASH_NUM_VALUES = 65536;
+static const unsigned HASH_BIT_MASK = 65535; /*HASH_NUM_VALUES - 1, but C90 does not like that as initializer*/
+
+typedef struct Hash
+{
+  int* head; /*hash value to head circular pos - can be outdated if went around window*/
+  /*circular pos to prev circular pos*/
+  unsigned short* chain;
+  int* val; /*circular pos to hash value*/
+
+  /*TODO: do this not only for zeros but for any repeated byte. However for PNG
+  it's always going to be the zeros that dominate, so not important for PNG*/
+  int* headz; /*similar to head, but for chainz*/
+  unsigned short* chainz; /*those with same amount of zeros*/
+  unsigned short* zeros; /*length of zeros streak, used as a second hash chain*/
+} Hash;
+
+static unsigned hash_init(Hash* hash, unsigned windowsize)
+{
+  unsigned i;
+  hash->head = (int*)lodepng_malloc(sizeof(int) * HASH_NUM_VALUES);
+  hash->val = (int*)lodepng_malloc(sizeof(int) * windowsize);
+  hash->chain = (unsigned short*)lodepng_malloc(sizeof(unsigned short) * windowsize);
+
+  hash->zeros = (unsigned short*)lodepng_malloc(sizeof(unsigned short) * windowsize);
+  hash->headz = (int*)lodepng_malloc(sizeof(int) * (MAX_SUPPORTED_DEFLATE_LENGTH + 1));
+  hash->chainz = (unsigned short*)lodepng_malloc(sizeof(unsigned short) * windowsize);
+
+  if(!hash->head || !hash->chain || !hash->val  || !hash->headz|| !hash->chainz || !hash->zeros)
+  {
+    return 83; /*alloc fail*/
+  }
+
+  /*initialize hash table*/
+  for(i = 0; i != HASH_NUM_VALUES; ++i) hash->head[i] = -1;
+  for(i = 0; i != windowsize; ++i) hash->val[i] = -1;
+  for(i = 0; i != windowsize; ++i) hash->chain[i] = i; /*same value as index indicates uninitialized*/
+
+  for(i = 0; i <= MAX_SUPPORTED_DEFLATE_LENGTH; ++i) hash->headz[i] = -1;
+  for(i = 0; i != windowsize; ++i) hash->chainz[i] = i; /*same value as index indicates uninitialized*/
+
+  return 0;
+}
+
+static void hash_cleanup(Hash* hash)
+{
+  lodepng_free(hash->head);
+  lodepng_free(hash->val);
+  lodepng_free(hash->chain);
+
+  lodepng_free(hash->zeros);
+  lodepng_free(hash->headz);
+  lodepng_free(hash->chainz);
+}
+
+
+
+static unsigned getHash(const unsigned char* data, size_t size, size_t pos)
+{
+  unsigned result = 0;
+  if(pos + 2 < size)
+  {
+    /*A simple shift and xor hash is used. Since the data of PNGs is dominated
+    by zeroes due to the filters, a better hash does not have a significant
+    effect on speed in traversing the chain, and causes more time spend on
+    calculating the hash.*/
+    result ^= (unsigned)(data[pos + 0] << 0u);
+    result ^= (unsigned)(data[pos + 1] << 4u);
+    result ^= (unsigned)(data[pos + 2] << 8u);
+  } else {
+    size_t amount, i;
+    if(pos >= size) return 0;
+    amount = size - pos;
+    for(i = 0; i != amount; ++i) result ^= (unsigned)(data[pos + i] << (i * 8u));
+  }
+  return result & HASH_BIT_MASK;
+}
+
+static unsigned countZeros(const unsigned char* data, size_t size, size_t pos)
+{
+  const unsigned char* start = data + pos;
+  const unsigned char* end = start + MAX_SUPPORTED_DEFLATE_LENGTH;
+  if(end > data + size) end = data + size;
+  data = start;
+  while(data != end && *data == 0) ++data;
+  /*subtracting two addresses returned as 32-bit number (max value is MAX_SUPPORTED_DEFLATE_LENGTH)*/
+  return (unsigned)(data - start);
+}
+
+/*wpos = pos & (windowsize - 1)*/
+static void updateHashChain(Hash* hash, size_t wpos, unsigned hashval, unsigned short numzeros)
+{
+  hash->val[wpos] = (int)hashval;
+  if(hash->head[hashval] != -1) hash->chain[wpos] = hash->head[hashval];
+  hash->head[hashval] = wpos;
+
+  hash->zeros[wpos] = numzeros;
+  if(hash->headz[numzeros] != -1) hash->chainz[wpos] = hash->headz[numzeros];
+  hash->headz[numzeros] = wpos;
+}
+
+/*
+LZ77-encode the data. Return value is error code. The input are raw bytes, the output
+is in the form of unsigned integers with codes representing for example literal bytes, or
+length/distance pairs.
+It uses a hash table technique to let it encode faster. When doing LZ77 encoding, a
+sliding window (of windowsize) is used, and all past bytes in that window can be used as
+the "dictionary". A brute force search through all possible distances would be slow, and
+this hash technique is one out of several ways to speed this up.
+*/
+static unsigned encodeLZ77(uivector* out, Hash* hash,
+                           const unsigned char* in, size_t inpos, size_t insize, unsigned windowsize,
+                           unsigned minmatch, unsigned nicematch, unsigned lazymatching)
+{
+  size_t pos;
+  unsigned i, error = 0;
+  /*for large window lengths, assume the user wants no compression loss. Otherwise, max hash chain length speedup.*/
+  unsigned maxchainlength = windowsize >= 8192 ? windowsize : windowsize / 8;
+  unsigned maxlazymatch = windowsize >= 8192 ? MAX_SUPPORTED_DEFLATE_LENGTH : 64;
+
+  unsigned usezeros = 1; /*not sure if setting it to false for windowsize < 8192 is better or worse*/
+  unsigned numzeros = 0;
+
+  unsigned offset; /*the offset represents the distance in LZ77 terminology*/
+  unsigned length;
+  unsigned lazy = 0;
+  unsigned lazylength = 0, lazyoffset = 0;
+  unsigned hashval;
+  unsigned current_offset, current_length;
+  unsigned prev_offset;
+  const unsigned char *lastptr, *foreptr, *backptr;
+  unsigned hashpos;
+
+  if(windowsize == 0 || windowsize > 32768) return 60; /*error: windowsize smaller/larger than allowed*/
+  if((windowsize & (windowsize - 1)) != 0) return 90; /*error: must be power of two*/
+
+  if(nicematch > MAX_SUPPORTED_DEFLATE_LENGTH) nicematch = MAX_SUPPORTED_DEFLATE_LENGTH;
+
+  for(pos = inpos; pos < insize; ++pos)
+  {
+    size_t wpos = pos & (windowsize - 1); /*position for in 'circular' hash buffers*/
+    unsigned chainlength = 0;
+
+    hashval = getHash(in, insize, pos);
+
+    if(usezeros && hashval == 0)
+    {
+      if(numzeros == 0) numzeros = countZeros(in, insize, pos);
+      else if(pos + numzeros > insize || in[pos + numzeros - 1] != 0) --numzeros;
+    }
+    else
+    {
+      numzeros = 0;
+    }
+
+    updateHashChain(hash, wpos, hashval, numzeros);
+
+    /*the length and offset found for the current position*/
+    length = 0;
+    offset = 0;
+
+    hashpos = hash->chain[wpos];
+
+    lastptr = &in[insize < pos + MAX_SUPPORTED_DEFLATE_LENGTH ? insize : pos + MAX_SUPPORTED_DEFLATE_LENGTH];
+
+    /*search for the longest string*/
+    prev_offset = 0;
+    for(;;)
+    {
+      if(chainlength++ >= maxchainlength) break;
+      current_offset = hashpos <= wpos ? wpos - hashpos : wpos - hashpos + windowsize;
+
+      if(current_offset < prev_offset) break; /*stop when went completely around the circular buffer*/
+      prev_offset = current_offset;
+      if(current_offset > 0)
+      {
+        /*test the next characters*/
+        foreptr = &in[pos];
+        backptr = &in[pos - current_offset];
+
+        /*common case in PNGs is lots of zeros. Quickly skip over them as a speedup*/
+        if(numzeros >= 3)
+        {
+          unsigned skip = hash->zeros[hashpos];
+          if(skip > numzeros) skip = numzeros;
+          backptr += skip;
+          foreptr += skip;
+        }
+
+        while(foreptr != lastptr && *backptr == *foreptr) /*maximum supported length by deflate is max length*/
+        {
+          ++backptr;
+          ++foreptr;
+        }
+        current_length = (unsigned)(foreptr - &in[pos]);
+
+        if(current_length > length)
+        {
+          length = current_length; /*the longest length*/
+          offset = current_offset; /*the offset that is related to this longest length*/
+          /*jump out once a length of max length is found (speed gain). This also jumps
+          out if length is MAX_SUPPORTED_DEFLATE_LENGTH*/
+          if(current_length >= nicematch) break;
+        }
+      }
+
+      if(hashpos == hash->chain[hashpos]) break;
+
+      if(numzeros >= 3 && length > numzeros)
+      {
+        hashpos = hash->chainz[hashpos];
+        if(hash->zeros[hashpos] != numzeros) break;
+      }
+      else
+      {
+        hashpos = hash->chain[hashpos];
+        /*outdated hash value, happens if particular value was not encountered in whole last window*/
+        if(hash->val[hashpos] != (int)hashval) break;
+      }
+    }
+
+    if(lazymatching)
+    {
+      if(!lazy && length >= 3 && length <= maxlazymatch && length < MAX_SUPPORTED_DEFLATE_LENGTH)
+      {
+        lazy = 1;
+        lazylength = length;
+        lazyoffset = offset;
+        continue; /*try the next byte*/
+      }
+      if(lazy)
+      {
+        lazy = 0;
+        if(pos == 0) ERROR_BREAK(81);
+        if(length > lazylength + 1)
+        {
+          /*push the previous character as literal*/
+          if(!uivector_push_back(out, in[pos - 1])) ERROR_BREAK(83 /*alloc fail*/);
+        }
+        else
+        {
+          length = lazylength;
+          offset = lazyoffset;
+          hash->head[hashval] = -1; /*the same hashchain update will be done, this ensures no wrong alteration*/
+          hash->headz[numzeros] = -1; /*idem*/
+          --pos;
+        }
+      }
+    }
+    if(length >= 3 && offset > windowsize) ERROR_BREAK(86 /*too big (or overflown negative) offset*/);
+
+    /*encode it as length/distance pair or literal value*/
+    if(length < 3) /*only lengths of 3 or higher are supported as length/distance pair*/
+    {
+      if(!uivector_push_back(out, in[pos])) ERROR_BREAK(83 /*alloc fail*/);
+    }
+    else if(length < minmatch || (length == 3 && offset > 4096))
+    {
+      /*compensate for the fact that longer offsets have more extra bits, a
+      length of only 3 may be not worth it then*/
+      if(!uivector_push_back(out, in[pos])) ERROR_BREAK(83 /*alloc fail*/);
+    }
+    else
+    {
+      addLengthDistance(out, length, offset);
+      for(i = 1; i < length; ++i)
+      {
+        ++pos;
+        wpos = pos & (windowsize - 1);
+        hashval = getHash(in, insize, pos);
+        if(usezeros && hashval == 0)
+        {
+          if(numzeros == 0) numzeros = countZeros(in, insize, pos);
+          else if(pos + numzeros > insize || in[pos + numzeros - 1] != 0) --numzeros;
+        }
+        else
+        {
+          numzeros = 0;
+        }
+        updateHashChain(hash, wpos, hashval, numzeros);
+      }
+    }
+  } /*end of the loop through each character of input*/
+
+  return error;
+}
+
+/* /////////////////////////////////////////////////////////////////////////// */
+
+static unsigned deflateNoCompression(ucvector* out, const unsigned char* data, size_t datasize)
+{
+  /*non compressed deflate block data: 1 bit BFINAL,2 bits BTYPE,(5 bits): it jumps to start of next byte,
+  2 bytes LEN, 2 bytes NLEN, LEN bytes literal DATA*/
+
+  size_t i, j, numdeflateblocks = (datasize + 65534) / 65535;
+  unsigned datapos = 0;
+  for(i = 0; i != numdeflateblocks; ++i)
+  {
+    unsigned BFINAL, BTYPE, LEN, NLEN;
+    unsigned char firstbyte;
+
+    BFINAL = (i == numdeflateblocks - 1);
+    BTYPE = 0;
+
+    firstbyte = (unsigned char)(BFINAL + ((BTYPE & 1) << 1) + ((BTYPE & 2) << 1));
+    ucvector_push_back(out, firstbyte);
+
+    LEN = 65535;
+    if(datasize - datapos < 65535) LEN = (unsigned)datasize - datapos;
+    NLEN = 65535 - LEN;
+
+    ucvector_push_back(out, (unsigned char)(LEN & 255));
+    ucvector_push_back(out, (unsigned char)(LEN >> 8));
+    ucvector_push_back(out, (unsigned char)(NLEN & 255));
+    ucvector_push_back(out, (unsigned char)(NLEN >> 8));
+
+    /*Decompressed data*/
+    for(j = 0; j < 65535 && datapos < datasize; ++j)
+    {
+      ucvector_push_back(out, data[datapos++]);
+    }
+  }
+
+  return 0;
+}
+
+/*
+write the lz77-encoded data, which has lit, len and dist codes, to compressed stream using huffman trees.
+tree_ll: the tree for lit and len codes.
+tree_d: the tree for distance codes.
+*/
+static void writeLZ77data(size_t* bp, ucvector* out, const uivector* lz77_encoded,
+                          const HuffmanTree* tree_ll, const HuffmanTree* tree_d)
+{
+  size_t i = 0;
+  for(i = 0; i != lz77_encoded->size; ++i)
+  {
+    unsigned val = lz77_encoded->data[i];
+    addHuffmanSymbol(bp, out, HuffmanTree_getCode(tree_ll, val), HuffmanTree_getLength(tree_ll, val));
+    if(val > 256) /*for a length code, 3 more things have to be added*/
+    {
+      unsigned length_index = val - FIRST_LENGTH_CODE_INDEX;
+      unsigned n_length_extra_bits = LENGTHEXTRA[length_index];
+      unsigned length_extra_bits = lz77_encoded->data[++i];
+
+      unsigned distance_code = lz77_encoded->data[++i];
+
+      unsigned distance_index = distance_code;
+      unsigned n_distance_extra_bits = DISTANCEEXTRA[distance_index];
+      unsigned distance_extra_bits = lz77_encoded->data[++i];
+
+      addBitsToStream(bp, out, length_extra_bits, n_length_extra_bits);
+      addHuffmanSymbol(bp, out, HuffmanTree_getCode(tree_d, distance_code),
+                       HuffmanTree_getLength(tree_d, distance_code));
+      addBitsToStream(bp, out, distance_extra_bits, n_distance_extra_bits);
+    }
+  }
+}
+
+/*Deflate for a block of type "dynamic", that is, with freely, optimally, created huffman trees*/
+static unsigned deflateDynamic(ucvector* out, size_t* bp, Hash* hash,
+                               const unsigned char* data, size_t datapos, size_t dataend,
+                               const LodePNGCompressSettings* settings, unsigned final)
+{
+  unsigned error = 0;
+
+  /*
+  A block is compressed as follows: The PNG data is lz77 encoded, resulting in
+  literal bytes and length/distance pairs. This is then huffman compressed with
+  two huffman trees. One huffman tree is used for the lit and len values ("ll"),
+  another huffman tree is used for the dist values ("d"). These two trees are
+  stored using their code lengths, and to compress even more these code lengths
+  are also run-length encoded and huffman compressed. This gives a huffman tree
+  of code lengths "cl". The code lenghts used to describe this third tree are
+  the code length code lengths ("clcl").
+  */
+
+  /*The lz77 encoded data, represented with integers since there will also be length and distance codes in it*/
+  uivector lz77_encoded;
+  HuffmanTree tree_ll; /*tree for lit,len values*/
+  HuffmanTree tree_d; /*tree for distance codes*/
+  HuffmanTree tree_cl; /*tree for encoding the code lengths representing tree_ll and tree_d*/
+  uivector frequencies_ll; /*frequency of lit,len codes*/
+  uivector frequencies_d; /*frequency of dist codes*/
+  uivector frequencies_cl; /*frequency of code length codes*/
+  uivector bitlen_lld; /*lit,len,dist code lenghts (int bits), literally (without repeat codes).*/
+  uivector bitlen_lld_e; /*bitlen_lld encoded with repeat codes (this is a rudemtary run length compression)*/
+  /*bitlen_cl is the code length code lengths ("clcl"). The bit lengths of codes to represent tree_cl
+  (these are written as is in the file, it would be crazy to compress these using yet another huffman
+  tree that needs to be represented by yet another set of code lengths)*/
+  uivector bitlen_cl;
+  size_t datasize = dataend - datapos;
+
+  /*
+  Due to the huffman compression of huffman tree representations ("two levels"), there are some anologies:
+  bitlen_lld is to tree_cl what data is to tree_ll and tree_d.
+  bitlen_lld_e is to bitlen_lld what lz77_encoded is to data.
+  bitlen_cl is to bitlen_lld_e what bitlen_lld is to lz77_encoded.
+  */
+
+  unsigned BFINAL = final;
+  size_t numcodes_ll, numcodes_d, i;
+  unsigned HLIT, HDIST, HCLEN;
+
+  uivector_init(&lz77_encoded);
+  HuffmanTree_init(&tree_ll);
+  HuffmanTree_init(&tree_d);
+  HuffmanTree_init(&tree_cl);
+  uivector_init(&frequencies_ll);
+  uivector_init(&frequencies_d);
+  uivector_init(&frequencies_cl);
+  uivector_init(&bitlen_lld);
+  uivector_init(&bitlen_lld_e);
+  uivector_init(&bitlen_cl);
+
+  /*This while loop never loops due to a break at the end, it is here to
+  allow breaking out of it to the cleanup phase on error conditions.*/
+  while(!error)
+  {
+    if(settings->use_lz77)
+    {
+      error = encodeLZ77(&lz77_encoded, hash, data, datapos, dataend, settings->windowsize,
+                         settings->minmatch, settings->nicematch, settings->lazymatching);
+      if(error) break;
+    }
+    else
+    {
+      if(!uivector_resize(&lz77_encoded, datasize)) ERROR_BREAK(83 /*alloc fail*/);
+      for(i = datapos; i < dataend; ++i) lz77_encoded.data[i - datapos] = data[i]; /*no LZ77, but still will be Huffman compressed*/
+    }
+
+    if(!uivector_resizev(&frequencies_ll, 286, 0)) ERROR_BREAK(83 /*alloc fail*/);
+    if(!uivector_resizev(&frequencies_d, 30, 0)) ERROR_BREAK(83 /*alloc fail*/);
+
+    /*Count the frequencies of lit, len and dist codes*/
+    for(i = 0; i != lz77_encoded.size; ++i)
+    {
+      unsigned symbol = lz77_encoded.data[i];
+      ++frequencies_ll.data[symbol];
+      if(symbol > 256)
+      {
+        unsigned dist = lz77_encoded.data[i + 2];
+        ++frequencies_d.data[dist];
+        i += 3;
+      }
+    }
+    frequencies_ll.data[256] = 1; /*there will be exactly 1 end code, at the end of the block*/
+
+    /*Make both huffman trees, one for the lit and len codes, one for the dist codes*/
+    error = HuffmanTree_makeFromFrequencies(&tree_ll, frequencies_ll.data, 257, frequencies_ll.size, 15);
+    if(error) break;
+    /*2, not 1, is chosen for mincodes: some buggy PNG decoders require at least 2 symbols in the dist tree*/
+    error = HuffmanTree_makeFromFrequencies(&tree_d, frequencies_d.data, 2, frequencies_d.size, 15);
+    if(error) break;
+
+    numcodes_ll = tree_ll.numcodes; if(numcodes_ll > 286) numcodes_ll = 286;
+    numcodes_d = tree_d.numcodes; if(numcodes_d > 30) numcodes_d = 30;
+    /*store the code lengths of both generated trees in bitlen_lld*/
+    for(i = 0; i != numcodes_ll; ++i) uivector_push_back(&bitlen_lld, HuffmanTree_getLength(&tree_ll, (unsigned)i));
+    for(i = 0; i != numcodes_d; ++i) uivector_push_back(&bitlen_lld, HuffmanTree_getLength(&tree_d, (unsigned)i));
+
+    /*run-length compress bitlen_ldd into bitlen_lld_e by using repeat codes 16 (copy length 3-6 times),
+    17 (3-10 zeroes), 18 (11-138 zeroes)*/
+    for(i = 0; i != (unsigned)bitlen_lld.size; ++i)
+    {
+      unsigned j = 0; /*amount of repititions*/
+      while(i + j + 1 < (unsigned)bitlen_lld.size && bitlen_lld.data[i + j + 1] == bitlen_lld.data[i]) ++j;
+
+      if(bitlen_lld.data[i] == 0 && j >= 2) /*repeat code for zeroes*/
+      {
+        ++j; /*include the first zero*/
+        if(j <= 10) /*repeat code 17 supports max 10 zeroes*/
+        {
+          uivector_push_back(&bitlen_lld_e, 17);
+          uivector_push_back(&bitlen_lld_e, j - 3);
+        }
+        else /*repeat code 18 supports max 138 zeroes*/
+        {
+          if(j > 138) j = 138;
+          uivector_push_back(&bitlen_lld_e, 18);
+          uivector_push_back(&bitlen_lld_e, j - 11);
+        }
+        i += (j - 1);
+      }
+      else if(j >= 3) /*repeat code for value other than zero*/
+      {
+        size_t k;
+        unsigned num = j / 6, rest = j % 6;
+        uivector_push_back(&bitlen_lld_e, bitlen_lld.data[i]);
+        for(k = 0; k < num; ++k)
+        {
+          uivector_push_back(&bitlen_lld_e, 16);
+          uivector_push_back(&bitlen_lld_e, 6 - 3);
+        }
+        if(rest >= 3)
+        {
+          uivector_push_back(&bitlen_lld_e, 16);
+          uivector_push_back(&bitlen_lld_e, rest - 3);
+        }
+        else j -= rest;
+        i += j;
+      }
+      else /*too short to benefit from repeat code*/
+      {
+        uivector_push_back(&bitlen_lld_e, bitlen_lld.data[i]);
+      }
+    }
+
+    /*generate tree_cl, the huffmantree of huffmantrees*/
+
+    if(!uivector_resizev(&frequencies_cl, NUM_CODE_LENGTH_CODES, 0)) ERROR_BREAK(83 /*alloc fail*/);
+    for(i = 0; i != bitlen_lld_e.size; ++i)
+    {
+      ++frequencies_cl.data[bitlen_lld_e.data[i]];
+      /*after a repeat code come the bits that specify the number of repetitions,
+      those don't need to be in the frequencies_cl calculation*/
+      if(bitlen_lld_e.data[i] >= 16) ++i;
+    }
+
+    error = HuffmanTree_makeFromFrequencies(&tree_cl, frequencies_cl.data,
+                                            frequencies_cl.size, frequencies_cl.size, 7);
+    if(error) break;
+
+    if(!uivector_resize(&bitlen_cl, tree_cl.numcodes)) ERROR_BREAK(83 /*alloc fail*/);
+    for(i = 0; i != tree_cl.numcodes; ++i)
+    {
+      /*lenghts of code length tree is in the order as specified by deflate*/
+      bitlen_cl.data[i] = HuffmanTree_getLength(&tree_cl, CLCL_ORDER[i]);
+    }
+    while(bitlen_cl.data[bitlen_cl.size - 1] == 0 && bitlen_cl.size > 4)
+    {
+      /*remove zeros at the end, but minimum size must be 4*/
+      if(!uivector_resize(&bitlen_cl, bitlen_cl.size - 1)) ERROR_BREAK(83 /*alloc fail*/);
+    }
+    if(error) break;
+
+    /*
+    Write everything into the output
+
+    After the BFINAL and BTYPE, the dynamic block consists out of the following:
+    - 5 bits HLIT, 5 bits HDIST, 4 bits HCLEN
+    - (HCLEN+4)*3 bits code lengths of code length alphabet
+    - HLIT + 257 code lenghts of lit/length alphabet (encoded using the code length
+      alphabet, + possible repetition codes 16, 17, 18)
+    - HDIST + 1 code lengths of distance alphabet (encoded using the code length
+      alphabet, + possible repetition codes 16, 17, 18)
+    - compressed data
+    - 256 (end code)
+    */
+
+    /*Write block type*/
+    addBitToStream(bp, out, BFINAL);
+    addBitToStream(bp, out, 0); /*first bit of BTYPE "dynamic"*/
+    addBitToStream(bp, out, 1); /*second bit of BTYPE "dynamic"*/
+
+    /*write the HLIT, HDIST and HCLEN values*/
+    HLIT = (unsigned)(numcodes_ll - 257);
+    HDIST = (unsigned)(numcodes_d - 1);
+    HCLEN = (unsigned)bitlen_cl.size - 4;
+    /*trim zeroes for HCLEN. HLIT and HDIST were already trimmed at tree creation*/
+    while(!bitlen_cl.data[HCLEN + 4 - 1] && HCLEN > 0) --HCLEN;
+    addBitsToStream(bp, out, HLIT, 5);
+    addBitsToStream(bp, out, HDIST, 5);
+    addBitsToStream(bp, out, HCLEN, 4);
+
+    /*write the code lenghts of the code length alphabet*/
+    for(i = 0; i != HCLEN + 4; ++i) addBitsToStream(bp, out, bitlen_cl.data[i], 3);
+
+    /*write the lenghts of the lit/len AND the dist alphabet*/
+    for(i = 0; i != bitlen_lld_e.size; ++i)
+    {
+      addHuffmanSymbol(bp, out, HuffmanTree_getCode(&tree_cl, bitlen_lld_e.data[i]),
+                       HuffmanTree_getLength(&tree_cl, bitlen_lld_e.data[i]));
+      /*extra bits of repeat codes*/
+      if(bitlen_lld_e.data[i] == 16) addBitsToStream(bp, out, bitlen_lld_e.data[++i], 2);
+      else if(bitlen_lld_e.data[i] == 17) addBitsToStream(bp, out, bitlen_lld_e.data[++i], 3);
+      else if(bitlen_lld_e.data[i] == 18) addBitsToStream(bp, out, bitlen_lld_e.data[++i], 7);
+    }
+
+    /*write the compressed data symbols*/
+    writeLZ77data(bp, out, &lz77_encoded, &tree_ll, &tree_d);
+    /*error: the length of the end code 256 must be larger than 0*/
+    if(HuffmanTree_getLength(&tree_ll, 256) == 0) ERROR_BREAK(64);
+
+    /*write the end code*/
+    addHuffmanSymbol(bp, out, HuffmanTree_getCode(&tree_ll, 256), HuffmanTree_getLength(&tree_ll, 256));
+
+    break; /*end of error-while*/
+  }
+
+  /*cleanup*/
+  uivector_cleanup(&lz77_encoded);
+  HuffmanTree_cleanup(&tree_ll);
+  HuffmanTree_cleanup(&tree_d);
+  HuffmanTree_cleanup(&tree_cl);
+  uivector_cleanup(&frequencies_ll);
+  uivector_cleanup(&frequencies_d);
+  uivector_cleanup(&frequencies_cl);
+  uivector_cleanup(&bitlen_lld_e);
+  uivector_cleanup(&bitlen_lld);
+  uivector_cleanup(&bitlen_cl);
+
+  return error;
+}
+
+static unsigned deflateFixed(ucvector* out, size_t* bp, Hash* hash,
+                             const unsigned char* data,
+                             size_t datapos, size_t dataend,
+                             const LodePNGCompressSettings* settings, unsigned final)
+{
+  HuffmanTree tree_ll; /*tree for literal values and length codes*/
+  HuffmanTree tree_d; /*tree for distance codes*/
+
+  unsigned BFINAL = final;
+  unsigned error = 0;
+  size_t i;
+
+  HuffmanTree_init(&tree_ll);
+  HuffmanTree_init(&tree_d);
+
+  generateFixedLitLenTree(&tree_ll);
+  generateFixedDistanceTree(&tree_d);
+
+  addBitToStream(bp, out, BFINAL);
+  addBitToStream(bp, out, 1); /*first bit of BTYPE*/
+  addBitToStream(bp, out, 0); /*second bit of BTYPE*/
+
+  if(settings->use_lz77) /*LZ77 encoded*/
+  {
+    uivector lz77_encoded;
+    uivector_init(&lz77_encoded);
+    error = encodeLZ77(&lz77_encoded, hash, data, datapos, dataend, settings->windowsize,
+                       settings->minmatch, settings->nicematch, settings->lazymatching);
+    if(!error) writeLZ77data(bp, out, &lz77_encoded, &tree_ll, &tree_d);
+    uivector_cleanup(&lz77_encoded);
+  }
+  else /*no LZ77, but still will be Huffman compressed*/
+  {
+    for(i = datapos; i < dataend; ++i)
+    {
+      addHuffmanSymbol(bp, out, HuffmanTree_getCode(&tree_ll, data[i]), HuffmanTree_getLength(&tree_ll, data[i]));
+    }
+  }
+  /*add END code*/
+  if(!error) addHuffmanSymbol(bp, out, HuffmanTree_getCode(&tree_ll, 256), HuffmanTree_getLength(&tree_ll, 256));
+
+  /*cleanup*/
+  HuffmanTree_cleanup(&tree_ll);
+  HuffmanTree_cleanup(&tree_d);
+
+  return error;
+}
+
+static unsigned lodepng_deflatev(ucvector* out, const unsigned char* in, size_t insize,
+                                 const LodePNGCompressSettings* settings)
+{
+  unsigned error = 0;
+  size_t i, blocksize, numdeflateblocks;
+  size_t bp = 0; /*the bit pointer*/
+  Hash hash;
+
+  if(settings->btype > 2) return 61;
+  else if(settings->btype == 0) return deflateNoCompression(out, in, insize);
+  else if(settings->btype == 1) blocksize = insize;
+  else /*if(settings->btype == 2)*/
+  {
+    /*on PNGs, deflate blocks of 65-262k seem to give most dense encoding*/
+    blocksize = insize / 8 + 8;
+    if(blocksize < 65536) blocksize = 65536;
+    if(blocksize > 262144) blocksize = 262144;
+  }
+
+  numdeflateblocks = (insize + blocksize - 1) / blocksize;
+  if(numdeflateblocks == 0) numdeflateblocks = 1;
+
+  error = hash_init(&hash, settings->windowsize);
+  if(error) return error;
+
+  for(i = 0; i != numdeflateblocks && !error; ++i)
+  {
+    unsigned final = (i == numdeflateblocks - 1);
+    size_t start = i * blocksize;
+    size_t end = start + blocksize;
+    if(end > insize) end = insize;
+
+    if(settings->btype == 1) error = deflateFixed(out, &bp, &hash, in, start, end, settings, final);
+    else if(settings->btype == 2) error = deflateDynamic(out, &bp, &hash, in, start, end, settings, final);
+  }
+
+  hash_cleanup(&hash);
+
+  return error;
+}
+
+unsigned lodepng_deflate(unsigned char** out, size_t* outsize,
+                         const unsigned char* in, size_t insize,
+                         const LodePNGCompressSettings* settings)
+{
+  unsigned error;
+  ucvector v;
+  ucvector_init_buffer(&v, *out, *outsize);
+  error = lodepng_deflatev(&v, in, insize, settings);
+  *out = v.data;
+  *outsize = v.size;
+  return error;
+}
+
+static unsigned deflate(unsigned char** out, size_t* outsize,
+                        const unsigned char* in, size_t insize,
+                        const LodePNGCompressSettings* settings)
+{
+  if(settings->custom_deflate)
+  {
+    return settings->custom_deflate(out, outsize, in, insize, settings);
+  }
+  else
+  {
+    return lodepng_deflate(out, outsize, in, insize, settings);
+  }
+}
+
+#endif /*LODEPNG_COMPILE_DECODER*/
+
+/* ////////////////////////////////////////////////////////////////////////// */
+/* / Adler32                                                                  */
+/* ////////////////////////////////////////////////////////////////////////// */
+
+static unsigned update_adler32(unsigned adler, const unsigned char* data, unsigned len)
+{
+   unsigned s1 = adler & 0xffff;
+   unsigned s2 = (adler >> 16) & 0xffff;
+
+  while(len > 0)
+  {
+    /*at least 5550 sums can be done before the sums overflow, saving a lot of module divisions*/
+    unsigned amount = len > 5550 ? 5550 : len;
+    len -= amount;
+    while(amount > 0)
+    {
+      s1 += (*data++);
+      s2 += s1;
+      --amount;
+    }
+    s1 %= 65521;
+    s2 %= 65521;
+  }
+
+  return (s2 << 16) | s1;
+}
+
+/*Return the adler32 of the bytes data[0..len-1]*/
+static unsigned adler32(const unsigned char* data, unsigned len)
+{
+  return update_adler32(1L, data, len);
+}
+
+/* ////////////////////////////////////////////////////////////////////////// */
+/* / Zlib                                                                   / */
+/* ////////////////////////////////////////////////////////////////////////// */
+
+#ifdef LODEPNG_COMPILE_DECODER
+
+unsigned lodepng_zlib_decompress(unsigned char** out, size_t* outsize, const unsigned char* in,
+                                 size_t insize, const LodePNGDecompressSettings* settings)
+{
+  unsigned error = 0;
+  unsigned CM, CINFO, FDICT;
+
+  if(insize < 2) return 53; /*error, size of zlib data too small*/
+  /*read information from zlib header*/
+  if((in[0] * 256 + in[1]) % 31 != 0)
+  {
+    /*error: 256 * in[0] + in[1] must be a multiple of 31, the FCHECK value is supposed to be made that way*/
+    return 24;
+  }
+
+  CM = in[0] & 15;
+  CINFO = (in[0] >> 4) & 15;
+  /*FCHECK = in[1] & 31;*/ /*FCHECK is already tested above*/
+  FDICT = (in[1] >> 5) & 1;
+  /*FLEVEL = (in[1] >> 6) & 3;*/ /*FLEVEL is not used here*/
+
+  if(CM != 8 || CINFO > 7)
+  {
+    /*error: only compression method 8: inflate with sliding window of 32k is supported by the PNG spec*/
+    return 25;
+  }
+  if(FDICT != 0)
+  {
+    /*error: the specification of PNG says about the zlib stream:
+      "The additional flags shall not specify a preset dictionary."*/
+    return 26;
+  }
+
+  error = inflate(out, outsize, in + 2, insize - 2, settings);
+  if(error) return error;
+
+  if(!settings->ignore_adler32)
+  {
+    unsigned ADLER32 = lodepng_read32bitInt(&in[insize - 4]);
+    unsigned checksum = adler32(*out, (unsigned)(*outsize));
+    if(checksum != ADLER32) return 58; /*error, adler checksum not correct, data must be corrupted*/
+  }
+
+  return 0; /*no error*/
+}
+
+static unsigned zlib_decompress(unsigned char** out, size_t* outsize, const unsigned char* in,
+                                size_t insize, const LodePNGDecompressSettings* settings)
+{
+  if(settings->custom_zlib)
+  {
+    return settings->custom_zlib(out, outsize, in, insize, settings);
+  }
+  else
+  {
+    return lodepng_zlib_decompress(out, outsize, in, insize, settings);
+  }
+}
+
+#endif /*LODEPNG_COMPILE_DECODER*/
+
+#ifdef LODEPNG_COMPILE_ENCODER
+
+unsigned lodepng_zlib_compress(unsigned char** out, size_t* outsize, const unsigned char* in,
+                               size_t insize, const LodePNGCompressSettings* settings)
+{
+  /*initially, *out must be NULL and outsize 0, if you just give some random *out
+  that's pointing to a non allocated buffer, this'll crash*/
+  ucvector outv;
+  size_t i;
+  unsigned error;
+  unsigned char* deflatedata = 0;
+  size_t deflatesize = 0;
+
+  /*zlib data: 1 byte CMF (CM+CINFO), 1 byte FLG, deflate data, 4 byte ADLER32 checksum of the Decompressed data*/
+  unsigned CMF = 120; /*0b01111000: CM 8, CINFO 7. With CINFO 7, any window size up to 32768 can be used.*/
+  unsigned FLEVEL = 0;
+  unsigned FDICT = 0;
+  unsigned CMFFLG = 256 * CMF + FDICT * 32 + FLEVEL * 64;
+  unsigned FCHECK = 31 - CMFFLG % 31;
+  CMFFLG += FCHECK;
+
+  /*ucvector-controlled version of the output buffer, for dynamic array*/
+  ucvector_init_buffer(&outv, *out, *outsize);
+
+  ucvector_push_back(&outv, (unsigned char)(CMFFLG >> 8));
+  ucvector_push_back(&outv, (unsigned char)(CMFFLG & 255));
+
+  error = deflate(&deflatedata, &deflatesize, in, insize, settings);
+
+  if(!error)
+  {
+    unsigned ADLER32 = adler32(in, (unsigned)insize);
+    for(i = 0; i != deflatesize; ++i) ucvector_push_back(&outv, deflatedata[i]);
+    lodepng_free(deflatedata);
+    lodepng_add32bitInt(&outv, ADLER32);
+  }
+
+  *out = outv.data;
+  *outsize = outv.size;
+
+  return error;
+}
+
+/* compress using the default or custom zlib function */
+static unsigned zlib_compress(unsigned char** out, size_t* outsize, const unsigned char* in,
+                              size_t insize, const LodePNGCompressSettings* settings)
+{
+  if(settings->custom_zlib)
+  {
+    return settings->custom_zlib(out, outsize, in, insize, settings);
+  }
+  else
+  {
+    return lodepng_zlib_compress(out, outsize, in, insize, settings);
+  }
+}
+
+#endif /*LODEPNG_COMPILE_ENCODER*/
+
+#else /*no LODEPNG_COMPILE_ZLIB*/
+
+#ifdef LODEPNG_COMPILE_DECODER
+static unsigned zlib_decompress(unsigned char** out, size_t* outsize, const unsigned char* in,
+                                size_t insize, const LodePNGDecompressSettings* settings)
+{
+  if(!settings->custom_zlib) return 87; /*no custom zlib function provided */
+  return settings->custom_zlib(out, outsize, in, insize, settings);
+}
+#endif /*LODEPNG_COMPILE_DECODER*/
+#ifdef LODEPNG_COMPILE_ENCODER
+static unsigned zlib_compress(unsigned char** out, size_t* outsize, const unsigned char* in,
+                              size_t insize, const LodePNGCompressSettings* settings)
+{
+  if(!settings->custom_zlib) return 87; /*no custom zlib function provided */
+  return settings->custom_zlib(out, outsize, in, insize, settings);
+}
+#endif /*LODEPNG_COMPILE_ENCODER*/
+
+#endif /*LODEPNG_COMPILE_ZLIB*/
+
+/* ////////////////////////////////////////////////////////////////////////// */
+
+#ifdef LODEPNG_COMPILE_ENCODER
+
+/*this is a good tradeoff between speed and compression ratio*/
+#define DEFAULT_WINDOWSIZE 2048
+
+void lodepng_compress_settings_init(LodePNGCompressSettings* settings)
+{
+  /*compress with dynamic huffman tree (not in the mathematical sense, just not the predefined one)*/
+  settings->btype = 2;
+  settings->use_lz77 = 1;
+  settings->windowsize = DEFAULT_WINDOWSIZE;
+  settings->minmatch = 3;
+  settings->nicematch = 128;
+  settings->lazymatching = 1;
+
+  settings->custom_zlib = 0;
+  settings->custom_deflate = 0;
+  settings->custom_context = 0;
+}
+
+const LodePNGCompressSettings lodepng_default_compress_settings = {2, 1, DEFAULT_WINDOWSIZE, 3, 128, 1, 0, 0, 0};
+
+
+#endif /*LODEPNG_COMPILE_ENCODER*/
+
+#ifdef LODEPNG_COMPILE_DECODER
+
+void lodepng_decompress_settings_init(LodePNGDecompressSettings* settings)
+{
+  settings->ignore_adler32 = 0;
+
+  settings->custom_zlib = 0;
+  settings->custom_inflate = 0;
+  settings->custom_context = 0;
+}
+
+const LodePNGDecompressSettings lodepng_default_decompress_settings = {0, 0, 0, 0};
+
+#endif /*LODEPNG_COMPILE_DECODER*/
+
+/* ////////////////////////////////////////////////////////////////////////// */
+/* ////////////////////////////////////////////////////////////////////////// */
+/* // End of Zlib related code. Begin of PNG related code.                 // */
+/* ////////////////////////////////////////////////////////////////////////// */
+/* ////////////////////////////////////////////////////////////////////////// */
+
+#ifdef LODEPNG_COMPILE_PNG
+
+/* ////////////////////////////////////////////////////////////////////////// */
+/* / CRC32                                                                  / */
+/* ////////////////////////////////////////////////////////////////////////// */
+
+
+#ifndef LODEPNG_NO_COMPILE_CRC
+/* CRC polynomial: 0xedb88320 */
+static unsigned lodepng_crc32_table[256] = {
+           0u, 1996959894u, 3993919788u, 2567524794u,  124634137u, 1886057615u, 3915621685u, 2657392035u,
+   249268274u, 2044508324u, 3772115230u, 2547177864u,  162941995u, 2125561021u, 3887607047u, 2428444049u,
+   498536548u, 1789927666u, 4089016648u, 2227061214u,  450548861u, 1843258603u, 4107580753u, 2211677639u,
+   325883990u, 1684777152u, 4251122042u, 2321926636u,  335633487u, 1661365465u, 4195302755u, 2366115317u,
+   997073096u, 1281953886u, 3579855332u, 2724688242u, 1006888145u, 1258607687u, 3524101629u, 2768942443u,
+   901097722u, 1119000684u, 3686517206u, 2898065728u,  853044451u, 1172266101u, 3705015759u, 2882616665u,
+   651767980u, 1373503546u, 3369554304u, 3218104598u,  565507253u, 1454621731u, 3485111705u, 3099436303u,
+   671266974u, 1594198024u, 3322730930u, 2970347812u,  795835527u, 1483230225u, 3244367275u, 3060149565u,
+  1994146192u,   31158534u, 2563907772u, 4023717930u, 1907459465u,  112637215u, 2680153253u, 3904427059u,
+  2013776290u,  251722036u, 2517215374u, 3775830040u, 2137656763u,  141376813u, 2439277719u, 3865271297u,
+  1802195444u,  476864866u, 2238001368u, 4066508878u, 1812370925u,  453092731u, 2181625025u, 4111451223u,
+  1706088902u,  314042704u, 2344532202u, 4240017532u, 1658658271u,  366619977u, 2362670323u, 4224994405u,
+  1303535960u,  984961486u, 2747007092u, 3569037538u, 1256170817u, 1037604311u, 2765210733u, 3554079995u,
+  1131014506u,  879679996u, 2909243462u, 3663771856u, 1141124467u,  855842277u, 2852801631u, 3708648649u,
+  1342533948u,  654459306u, 3188396048u, 3373015174u, 1466479909u,  544179635u, 3110523913u, 3462522015u,
+  1591671054u,  702138776u, 2966460450u, 3352799412u, 1504918807u,  783551873u, 3082640443u, 3233442989u,
+  3988292384u, 2596254646u,   62317068u, 1957810842u, 3939845945u, 2647816111u,   81470997u, 1943803523u,
+  3814918930u, 2489596804u,  225274430u, 2053790376u, 3826175755u, 2466906013u,  167816743u, 2097651377u,
+  4027552580u, 2265490386u,  503444072u, 1762050814u, 4150417245u, 2154129355u,  426522225u, 1852507879u,
+  4275313526u, 2312317920u,  282753626u, 1742555852u, 4189708143u, 2394877945u,  397917763u, 1622183637u,
+  3604390888u, 2714866558u,  953729732u, 1340076626u, 3518719985u, 2797360999u, 1068828381u, 1219638859u,
+  3624741850u, 2936675148u,  906185462u, 1090812512u, 3747672003u, 2825379669u,  829329135u, 1181335161u,
+  3412177804u, 3160834842u,  628085408u, 1382605366u, 3423369109u, 3138078467u,  570562233u, 1426400815u,
+  3317316542u, 2998733608u,  733239954u, 1555261956u, 3268935591u, 3050360625u,  752459403u, 1541320221u,
+  2607071920u, 3965973030u, 1969922972u,   40735498u, 2617837225u, 3943577151u, 1913087877u,   83908371u,
+  2512341634u, 3803740692u, 2075208622u,  213261112u, 2463272603u, 3855990285u, 2094854071u,  198958881u,
+  2262029012u, 4057260610u, 1759359992u,  534414190u, 2176718541u, 4139329115u, 1873836001u,  414664567u,
+  2282248934u, 4279200368u, 1711684554u,  285281116u, 2405801727u, 4167216745u, 1634467795u,  376229701u,
+  2685067896u, 3608007406u, 1308918612u,  956543938u, 2808555105u, 3495958263u, 1231636301u, 1047427035u,
+  2932959818u, 3654703836u, 1088359270u,  936918000u, 2847714899u, 3736837829u, 1202900863u,  817233897u,
+  3183342108u, 3401237130u, 1404277552u,  615818150u, 3134207493u, 3453421203u, 1423857449u,  601450431u,
+  3009837614u, 3294710456u, 1567103746u,  711928724u, 3020668471u, 3272380065u, 1510334235u,  755167117u
+};
+
+/*Return the CRC of the bytes buf[0..len-1].*/
+unsigned lodepng_crc32(const unsigned char* data, size_t length)
+{
+  unsigned r = 0xffffffffu;
+  size_t i;
+  for(i = 0; i < length; ++i)
+  {
+    r = lodepng_crc32_table[(r ^ data[i]) & 0xff] ^ (r >> 8);
+  }
+  return r ^ 0xffffffffu;
+}
+#else /* !LODEPNG_NO_COMPILE_CRC */
+unsigned lodepng_crc32(const unsigned char* data, size_t length);
+#endif /* !LODEPNG_NO_COMPILE_CRC */
+
+/* ////////////////////////////////////////////////////////////////////////// */
+/* / Reading and writing single bits and bytes from/to stream for LodePNG   / */
+/* ////////////////////////////////////////////////////////////////////////// */
+
+static unsigned char readBitFromReversedStream(size_t* bitpointer, const unsigned char* bitstream)
+{
+  unsigned char result = (unsigned char)((bitstream[(*bitpointer) >> 3] >> (7 - ((*bitpointer) & 0x7))) & 1);
+  ++(*bitpointer);
+  return result;
+}
+
+static unsigned readBitsFromReversedStream(size_t* bitpointer, const unsigned char* bitstream, size_t nbits)
+{
+  unsigned result = 0;
+  size_t i;
+  for(i = nbits - 1; i < nbits; --i)
+  {
+    result += (unsigned)readBitFromReversedStream(bitpointer, bitstream) << i;
+  }
+  return result;
+}
+
+#ifdef LODEPNG_COMPILE_DECODER
+static void setBitOfReversedStream0(size_t* bitpointer, unsigned char* bitstream, unsigned char bit)
+{
+  /*the current bit in bitstream must be 0 for this to work*/
+  if(bit)
+  {
+    /*earlier bit of huffman code is in a lesser significant bit of an earlier byte*/
+    bitstream[(*bitpointer) >> 3] |= (bit << (7 - ((*bitpointer) & 0x7)));
+  }
+  ++(*bitpointer);
+}
+#endif /*LODEPNG_COMPILE_DECODER*/
+
+static void setBitOfReversedStream(size_t* bitpointer, unsigned char* bitstream, unsigned char bit)
+{
+  /*the current bit in bitstream may be 0 or 1 for this to work*/
+  if(bit == 0) bitstream[(*bitpointer) >> 3] &=  (unsigned char)(~(1 << (7 - ((*bitpointer) & 0x7))));
+  else         bitstream[(*bitpointer) >> 3] |=  (1 << (7 - ((*bitpointer) & 0x7)));
+  ++(*bitpointer);
+}
+
+/* ////////////////////////////////////////////////////////////////////////// */
+/* / PNG chunks                                                             / */
+/* ////////////////////////////////////////////////////////////////////////// */
+
+unsigned lodepng_chunk_length(const unsigned char* chunk)
+{
+  return lodepng_read32bitInt(&chunk[0]);
+}
+
+void lodepng_chunk_type(char type[5], const unsigned char* chunk)
+{
+  unsigned i;
+  for(i = 0; i != 4; ++i) type[i] = (char)chunk[4 + i];
+  type[4] = 0; /*null termination char*/
+}
+
+unsigned char lodepng_chunk_type_equals(const unsigned char* chunk, const char* type)
+{
+  if(strlen(type) != 4) return 0;
+  return (chunk[4] == type[0] && chunk[5] == type[1] && chunk[6] == type[2] && chunk[7] == type[3]);
+}
+
+unsigned char lodepng_chunk_ancillary(const unsigned char* chunk)
+{
+  return((chunk[4] & 32) != 0);
+}
+
+unsigned char lodepng_chunk_private(const unsigned char* chunk)
+{
+  return((chunk[6] & 32) != 0);
+}
+
+unsigned char lodepng_chunk_safetocopy(const unsigned char* chunk)
+{
+  return((chunk[7] & 32) != 0);
+}
+
+unsigned char* lodepng_chunk_data(unsigned char* chunk)
+{
+  return &chunk[8];
+}
+
+const unsigned char* lodepng_chunk_data_const(const unsigned char* chunk)
+{
+  return &chunk[8];
+}
+
+unsigned lodepng_chunk_check_crc(const unsigned char* chunk)
+{
+  unsigned length = lodepng_chunk_length(chunk);
+  unsigned CRC = lodepng_read32bitInt(&chunk[length + 8]);
+  /*the CRC is taken of the data and the 4 chunk type letters, not the length*/
+  unsigned checksum = lodepng_crc32(&chunk[4], length + 4);
+  if(CRC != checksum) return 1;
+  else return 0;
+}
+
+void lodepng_chunk_generate_crc(unsigned char* chunk)
+{
+  unsigned length = lodepng_chunk_length(chunk);
+  unsigned CRC = lodepng_crc32(&chunk[4], length + 4);
+  lodepng_set32bitInt(chunk + 8 + length, CRC);
+}
+
+unsigned char* lodepng_chunk_next(unsigned char* chunk)
+{
+  unsigned total_chunk_length = lodepng_chunk_length(chunk) + 12;
+  return &chunk[total_chunk_length];
+}
+
+const unsigned char* lodepng_chunk_next_const(const unsigned char* chunk)
+{
+  unsigned total_chunk_length = lodepng_chunk_length(chunk) + 12;
+  return &chunk[total_chunk_length];
+}
+
+unsigned lodepng_chunk_append(unsigned char** out, size_t* outlength, const unsigned char* chunk)
+{
+  unsigned i;
+  unsigned total_chunk_length = lodepng_chunk_length(chunk) + 12;
+  unsigned char *chunk_start, *new_buffer;
+  size_t new_length = (*outlength) + total_chunk_length;
+  if(new_length < total_chunk_length || new_length < (*outlength)) return 77; /*integer overflow happened*/
+
+  new_buffer = (unsigned char*)lodepng_realloc(*out, new_length);
+  if(!new_buffer) return 83; /*alloc fail*/
+  (*out) = new_buffer;
+  (*outlength) = new_length;
+  chunk_start = &(*out)[new_length - total_chunk_length];
+
+  for(i = 0; i != total_chunk_length; ++i) chunk_start[i] = chunk[i];
+
+  return 0;
+}
+
+unsigned lodepng_chunk_create(unsigned char** out, size_t* outlength, unsigned length,
+                              const char* type, const unsigned char* data)
+{
+  unsigned i;
+  unsigned char *chunk, *new_buffer;
+  size_t new_length = (*outlength) + length + 12;
+  if(new_length < length + 12 || new_length < (*outlength)) return 77; /*integer overflow happened*/
+  new_buffer = (unsigned char*)lodepng_realloc(*out, new_length);
+  if(!new_buffer) return 83; /*alloc fail*/
+  (*out) = new_buffer;
+  (*outlength) = new_length;
+  chunk = &(*out)[(*outlength) - length - 12];
+
+  /*1: length*/
+  lodepng_set32bitInt(chunk, (unsigned)length);
+
+  /*2: chunk name (4 letters)*/
+  chunk[4] = (unsigned char)type[0];
+  chunk[5] = (unsigned char)type[1];
+  chunk[6] = (unsigned char)type[2];
+  chunk[7] = (unsigned char)type[3];
+
+  /*3: the data*/
+  for(i = 0; i != length; ++i) chunk[8 + i] = data[i];
+
+  /*4: CRC (of the chunkname characters and the data)*/
+  lodepng_chunk_generate_crc(chunk);
+
+  return 0;
+}
+
+/* ////////////////////////////////////////////////////////////////////////// */
+/* / Color types and such                                                   / */
+/* ////////////////////////////////////////////////////////////////////////// */
+
+/*return type is a LodePNG error code*/
+static unsigned checkColorValidity(LodePNGColorType colortype, unsigned bd) /*bd = bitdepth*/
+{
+  switch(colortype)
+  {
+    case 0: if(!(bd == 1 || bd == 2 || bd == 4 || bd == 8 || bd == 16)) return 37; break; /*grey*/
+    case 2: if(!(                                 bd == 8 || bd == 16)) return 37; break; /*RGB*/
+    case 3: if(!(bd == 1 || bd == 2 || bd == 4 || bd == 8            )) return 37; break; /*palette*/
+    case 4: if(!(                                 bd == 8 || bd == 16)) return 37; break; /*grey + alpha*/
+    case 6: if(!(                                 bd == 8 || bd == 16)) return 37; break; /*RGBA*/
+    default: return 31;
+  }
+  return 0; /*allowed color type / bits combination*/
+}
+
+static unsigned getNumColorChannels(LodePNGColorType colortype)
+{
+  switch(colortype)
+  {
+    case 0: return 1; /*grey*/
+    case 2: return 3; /*RGB*/
+    case 3: return 1; /*palette*/
+    case 4: return 2; /*grey + alpha*/
+    case 6: return 4; /*RGBA*/
+  }
+  return 0; /*unexisting color type*/
+}
+
+static unsigned lodepng_get_bpp_lct(LodePNGColorType colortype, unsigned bitdepth)
+{
+  /*bits per pixel is amount of channels * bits per channel*/
+  return getNumColorChannels(colortype) * bitdepth;
+}
+
+/* ////////////////////////////////////////////////////////////////////////// */
+
+void lodepng_color_mode_init(LodePNGColorMode* info)
+{
+  info->key_defined = 0;
+  info->key_r = info->key_g = info->key_b = 0;
+  info->colortype = LCT_RGBA;
+  info->bitdepth = 8;
+  info->palette = 0;
+  info->palettesize = 0;
+}
+
+void lodepng_color_mode_cleanup(LodePNGColorMode* info)
+{
+  lodepng_palette_clear(info);
+}
+
+unsigned lodepng_color_mode_copy(LodePNGColorMode* dest, const LodePNGColorMode* source)
+{
+  size_t i;
+  lodepng_color_mode_cleanup(dest);
+  *dest = *source;
+  if(source->palette)
+  {
+    dest->palette = (unsigned char*)lodepng_malloc(1024);
+    if(!dest->palette && source->palettesize) return 83; /*alloc fail*/
+    for(i = 0; i != source->palettesize * 4; ++i) dest->palette[i] = source->palette[i];
+  }
+  return 0;
+}
+
+static int lodepng_color_mode_equal(const LodePNGColorMode* a, const LodePNGColorMode* b)
+{
+  size_t i;
+  if(a->colortype != b->colortype) return 0;
+  if(a->bitdepth != b->bitdepth) return 0;
+  if(a->key_defined != b->key_defined) return 0;
+  if(a->key_defined)
+  {
+    if(a->key_r != b->key_r) return 0;
+    if(a->key_g != b->key_g) return 0;
+    if(a->key_b != b->key_b) return 0;
+  }
+  /*if one of the palette sizes is 0, then we consider it to be the same as the
+  other: it means that e.g. the palette was not given by the user and should be
+  considered the same as the palette inside the PNG.*/
+  if(1/*a->palettesize != 0 && b->palettesize != 0*/) {
+    if(a->palettesize != b->palettesize) return 0;
+    for(i = 0; i != a->palettesize * 4; ++i)
+    {
+      if(a->palette[i] != b->palette[i]) return 0;
+    }
+  }
+  return 1;
+}
+
+void lodepng_palette_clear(LodePNGColorMode* info)
+{
+  if(info->palette) lodepng_free(info->palette);
+  info->palette = 0;
+  info->palettesize = 0;
+}
+
+unsigned lodepng_palette_add(LodePNGColorMode* info,
+                             unsigned char r, unsigned char g, unsigned char b, unsigned char a)
+{
+  unsigned char* data;
+  /*the same resize technique as C++ std::vectors is used, and here it's made so that for a palette with
+  the max of 256 colors, it'll have the exact alloc size*/
+  if(!info->palette) /*allocate palette if empty*/
+  {
+    /*room for 256 colors with 4 bytes each*/
+    data = (unsigned char*)lodepng_realloc(info->palette, 1024);
+    if(!data) return 83; /*alloc fail*/
+    else info->palette = data;
+  }
+  info->palette[4 * info->palettesize + 0] = r;
+  info->palette[4 * info->palettesize + 1] = g;
+  info->palette[4 * info->palettesize + 2] = b;
+  info->palette[4 * info->palettesize + 3] = a;
+  ++info->palettesize;
+  return 0;
+}
+
+unsigned lodepng_get_bpp(const LodePNGColorMode* info)
+{
+  /*calculate bits per pixel out of colortype and bitdepth*/
+  return lodepng_get_bpp_lct(info->colortype, info->bitdepth);
+}
+
+unsigned lodepng_get_channels(const LodePNGColorMode* info)
+{
+  return getNumColorChannels(info->colortype);
+}
+
+unsigned lodepng_is_greyscale_type(const LodePNGColorMode* info)
+{
+  return info->colortype == LCT_GREY || info->colortype == LCT_GREY_ALPHA;
+}
+
+unsigned lodepng_is_alpha_type(const LodePNGColorMode* info)
+{
+  return (info->colortype & 4) != 0; /*4 or 6*/
+}
+
+unsigned lodepng_is_palette_type(const LodePNGColorMode* info)
+{
+  return info->colortype == LCT_PALETTE;
+}
+
+unsigned lodepng_has_palette_alpha(const LodePNGColorMode* info)
+{
+  size_t i;
+  for(i = 0; i != info->palettesize; ++i)
+  {
+    if(info->palette[i * 4 + 3] < 255) return 1;
+  }
+  return 0;
+}
+
+unsigned lodepng_can_have_alpha(const LodePNGColorMode* info)
+{
+  return info->key_defined
+      || lodepng_is_alpha_type(info)
+      || lodepng_has_palette_alpha(info);
+}
+
+size_t lodepng_get_raw_size(unsigned w, unsigned h, const LodePNGColorMode* color)
+{
+  /*will not overflow for any color type if roughly w * h < 268435455*/
+  size_t bpp = lodepng_get_bpp(color);
+  size_t n = w * h;
+  return ((n / 8) * bpp) + ((n & 7) * bpp + 7) / 8;
+}
+
+size_t lodepng_get_raw_size_lct(unsigned w, unsigned h, LodePNGColorType colortype, unsigned bitdepth)
+{
+  /*will not overflow for any color type if roughly w * h < 268435455*/
+  size_t bpp = lodepng_get_bpp_lct(colortype, bitdepth);
+  size_t n = w * h;
+  return ((n / 8) * bpp) + ((n & 7) * bpp + 7) / 8;
+}
+
+
+#ifdef LODEPNG_COMPILE_PNG
+#ifdef LODEPNG_COMPILE_DECODER
+/*in an idat chunk, each scanline is a multiple of 8 bits, unlike the lodepng output buffer*/
+static size_t lodepng_get_raw_size_idat(unsigned w, unsigned h, const LodePNGColorMode* color)
+{
+  /*will not overflow for any color type if roughly w * h < 268435455*/
+  size_t bpp = lodepng_get_bpp(color);
+  size_t line = ((w / 8) * bpp) + ((w & 7) * bpp + 7) / 8;
+  return h * line;
+}
+#endif /*LODEPNG_COMPILE_DECODER*/
+#endif /*LODEPNG_COMPILE_PNG*/
+
+#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
+
+static void LodePNGUnknownChunks_init(LodePNGInfo* info)
+{
+  unsigned i;
+  for(i = 0; i != 3; ++i) info->unknown_chunks_data[i] = 0;
+  for(i = 0; i != 3; ++i) info->unknown_chunks_size[i] = 0;
+}
+
+static void LodePNGUnknownChunks_cleanup(LodePNGInfo* info)
+{
+  unsigned i;
+  for(i = 0; i != 3; ++i) lodepng_free(info->unknown_chunks_data[i]);
+}
+
+static unsigned LodePNGUnknownChunks_copy(LodePNGInfo* dest, const LodePNGInfo* src)
+{
+  unsigned i;
+
+  LodePNGUnknownChunks_cleanup(dest);
+
+  for(i = 0; i != 3; ++i)
+  {
+    size_t j;
+    dest->unknown_chunks_size[i] = src->unknown_chunks_size[i];
+    dest->unknown_chunks_data[i] = (unsigned char*)lodepng_malloc(src->unknown_chunks_size[i]);
+    if(!dest->unknown_chunks_data[i] && dest->unknown_chunks_size[i]) return 83; /*alloc fail*/
+    for(j = 0; j < src->unknown_chunks_size[i]; ++j)
+    {
+      dest->unknown_chunks_data[i][j] = src->unknown_chunks_data[i][j];
+    }
+  }
+
+  return 0;
+}
+
+/******************************************************************************/
+
+static void LodePNGText_init(LodePNGInfo* info)
+{
+  info->text_num = 0;
+  info->text_keys = NULL;
+  info->text_strings = NULL;
+}
+
+static void LodePNGText_cleanup(LodePNGInfo* info)
+{
+  size_t i;
+  for(i = 0; i != info->text_num; ++i)
+  {
+    string_cleanup(&info->text_keys[i]);
+    string_cleanup(&info->text_strings[i]);
+  }
+  lodepng_free(info->text_keys);
+  lodepng_free(info->text_strings);
+}
+
+static unsigned LodePNGText_copy(LodePNGInfo* dest, const LodePNGInfo* source)
+{
+  size_t i = 0;
+  dest->text_keys = 0;
+  dest->text_strings = 0;
+  dest->text_num = 0;
+  for(i = 0; i != source->text_num; ++i)
+  {
+    CERROR_TRY_RETURN(lodepng_add_text(dest, source->text_keys[i], source->text_strings[i]));
+  }
+  return 0;
+}
+
+void lodepng_clear_text(LodePNGInfo* info)
+{
+  LodePNGText_cleanup(info);
+}
+
+unsigned lodepng_add_text(LodePNGInfo* info, const char* key, const char* str)
+{
+  char** new_keys = (char**)(lodepng_realloc(info->text_keys, sizeof(char*) * (info->text_num + 1)));
+  char** new_strings = (char**)(lodepng_realloc(info->text_strings, sizeof(char*) * (info->text_num + 1)));
+  if(!new_keys || !new_strings)
+  {
+    lodepng_free(new_keys);
+    lodepng_free(new_strings);
+    return 83; /*alloc fail*/
+  }
+
+  ++info->text_num;
+  info->text_keys = new_keys;
+  info->text_strings = new_strings;
+
+  string_init(&info->text_keys[info->text_num - 1]);
+  string_set(&info->text_keys[info->text_num - 1], key);
+
+  string_init(&info->text_strings[info->text_num - 1]);
+  string_set(&info->text_strings[info->text_num - 1], str);
+
+  return 0;
+}
+
+/******************************************************************************/
+
+static void LodePNGIText_init(LodePNGInfo* info)
+{
+  info->itext_num = 0;
+  info->itext_keys = NULL;
+  info->itext_langtags = NULL;
+  info->itext_transkeys = NULL;
+  info->itext_strings = NULL;
+}
+
+static void LodePNGIText_cleanup(LodePNGInfo* info)
+{
+  size_t i;
+  for(i = 0; i != info->itext_num; ++i)
+  {
+    string_cleanup(&info->itext_keys[i]);
+    string_cleanup(&info->itext_langtags[i]);
+    string_cleanup(&info->itext_transkeys[i]);
+    string_cleanup(&info->itext_strings[i]);
+  }
+  lodepng_free(info->itext_keys);
+  lodepng_free(info->itext_langtags);
+  lodepng_free(info->itext_transkeys);
+  lodepng_free(info->itext_strings);
+}
+
+static unsigned LodePNGIText_copy(LodePNGInfo* dest, const LodePNGInfo* source)
+{
+  size_t i = 0;
+  dest->itext_keys = 0;
+  dest->itext_langtags = 0;
+  dest->itext_transkeys = 0;
+  dest->itext_strings = 0;
+  dest->itext_num = 0;
+  for(i = 0; i != source->itext_num; ++i)
+  {
+    CERROR_TRY_RETURN(lodepng_add_itext(dest, source->itext_keys[i], source->itext_langtags[i],
+                                        source->itext_transkeys[i], source->itext_strings[i]));
+  }
+  return 0;
+}
+
+void lodepng_clear_itext(LodePNGInfo* info)
+{
+  LodePNGIText_cleanup(info);
+}
+
+unsigned lodepng_add_itext(LodePNGInfo* info, const char* key, const char* langtag,
+                           const char* transkey, const char* str)
+{
+  char** new_keys = (char**)(lodepng_realloc(info->itext_keys, sizeof(char*) * (info->itext_num + 1)));
+  char** new_langtags = (char**)(lodepng_realloc(info->itext_langtags, sizeof(char*) * (info->itext_num + 1)));
+  char** new_transkeys = (char**)(lodepng_realloc(info->itext_transkeys, sizeof(char*) * (info->itext_num + 1)));
+  char** new_strings = (char**)(lodepng_realloc(info->itext_strings, sizeof(char*) * (info->itext_num + 1)));
+  if(!new_keys || !new_langtags || !new_transkeys || !new_strings)
+  {
+    lodepng_free(new_keys);
+    lodepng_free(new_langtags);
+    lodepng_free(new_transkeys);
+    lodepng_free(new_strings);
+    return 83; /*alloc fail*/
+  }
+
+  ++info->itext_num;
+  info->itext_keys = new_keys;
+  info->itext_langtags = new_langtags;
+  info->itext_transkeys = new_transkeys;
+  info->itext_strings = new_strings;
+
+  string_init(&info->itext_keys[info->itext_num - 1]);
+  string_set(&info->itext_keys[info->itext_num - 1], key);
+
+  string_init(&info->itext_langtags[info->itext_num - 1]);
+  string_set(&info->itext_langtags[info->itext_num - 1], langtag);
+
+  string_init(&info->itext_transkeys[info->itext_num - 1]);
+  string_set(&info->itext_transkeys[info->itext_num - 1], transkey);
+
+  string_init(&info->itext_strings[info->itext_num - 1]);
+  string_set(&info->itext_strings[info->itext_num - 1], str);
+
+  return 0;
+}
+#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
+
+void lodepng_info_init(LodePNGInfo* info)
+{
+  lodepng_color_mode_init(&info->color);
+  info->interlace_method = 0;
+  info->compression_method = 0;
+  info->filter_method = 0;
+#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
+  info->background_defined = 0;
+  info->background_r = info->background_g = info->background_b = 0;
+
+  LodePNGText_init(info);
+  LodePNGIText_init(info);
+
+  info->time_defined = 0;
+  info->phys_defined = 0;
+
+  LodePNGUnknownChunks_init(info);
+#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
+}
+
+void lodepng_info_cleanup(LodePNGInfo* info)
+{
+  lodepng_color_mode_cleanup(&info->color);
+#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
+  LodePNGText_cleanup(info);
+  LodePNGIText_cleanup(info);
+
+  LodePNGUnknownChunks_cleanup(info);
+#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
+}
+
+unsigned lodepng_info_copy(LodePNGInfo* dest, const LodePNGInfo* source)
+{
+  lodepng_info_cleanup(dest);
+  *dest = *source;
+  lodepng_color_mode_init(&dest->color);
+  CERROR_TRY_RETURN(lodepng_color_mode_copy(&dest->color, &source->color));
+
+#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
+  CERROR_TRY_RETURN(LodePNGText_copy(dest, source));
+  CERROR_TRY_RETURN(LodePNGIText_copy(dest, source));
+
+  LodePNGUnknownChunks_init(dest);
+  CERROR_TRY_RETURN(LodePNGUnknownChunks_copy(dest, source));
+#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
+  return 0;
+}
+
+void lodepng_info_swap(LodePNGInfo* a, LodePNGInfo* b)
+{
+  LodePNGInfo temp = *a;
+  *a = *b;
+  *b = temp;
+}
+
+/* ////////////////////////////////////////////////////////////////////////// */
+
+/*index: bitgroup index, bits: bitgroup size(1, 2 or 4), in: bitgroup value, out: octet array to add bits to*/
+static void addColorBits(unsigned char* out, size_t index, unsigned bits, unsigned in)
+{
+  unsigned m = bits == 1 ? 7 : bits == 2 ? 3 : 1; /*8 / bits - 1*/
+  /*p = the partial index in the byte, e.g. with 4 palettebits it is 0 for first half or 1 for second half*/
+  unsigned p = index & m;
+  in &= (1u << bits) - 1u; /*filter out any other bits of the input value*/
+  in = in << (bits * (m - p));
+  if(p == 0) out[index * bits / 8] = in;
+  else out[index * bits / 8] |= in;
+}
+
+typedef struct ColorTree ColorTree;
+
+/*
+One node of a color tree
+This is the data structure used to count the number of unique colors and to get a palette
+index for a color. It's like an octree, but because the alpha channel is used too, each
+node has 16 instead of 8 children.
+*/
+struct ColorTree
+{
+  ColorTree* children[16]; /*up to 16 pointers to ColorTree of next level*/
+  int index; /*the payload. Only has a meaningful value if this is in the last level*/
+};
+
+static void color_tree_init(ColorTree* tree)
+{
+  int i;
+  for(i = 0; i != 16; ++i) tree->children[i] = 0;
+  tree->index = -1;
+}
+
+static void color_tree_cleanup(ColorTree* tree)
+{
+  int i;
+  for(i = 0; i != 16; ++i)
+  {
+    if(tree->children[i])
+    {
+      color_tree_cleanup(tree->children[i]);
+      lodepng_free(tree->children[i]);
+    }
+  }
+}
+
+/*returns -1 if color not present, its index otherwise*/
+static int color_tree_get(ColorTree* tree, unsigned char r, unsigned char g, unsigned char b, unsigned char a)
+{
+  int bit = 0;
+  for(bit = 0; bit < 8; ++bit)
+  {
+    int i = 8 * ((r >> bit) & 1) + 4 * ((g >> bit) & 1) + 2 * ((b >> bit) & 1) + 1 * ((a >> bit) & 1);
+    if(!tree->children[i]) return -1;
+    else tree = tree->children[i];
+  }
+  return tree ? tree->index : -1;
+}
+
+#ifdef LODEPNG_COMPILE_ENCODER
+static int color_tree_has(ColorTree* tree, unsigned char r, unsigned char g, unsigned char b, unsigned char a)
+{
+  return color_tree_get(tree, r, g, b, a) >= 0;
+}
+#endif /*LODEPNG_COMPILE_ENCODER*/
+
+/*color is not allowed to already exist.
+Index should be >= 0 (it's signed to be compatible with using -1 for "doesn't exist")*/
+static void color_tree_add(ColorTree* tree,
+                           unsigned char r, unsigned char g, unsigned char b, unsigned char a, unsigned index)
+{
+  int bit;
+  for(bit = 0; bit < 8; ++bit)
+  {
+    int i = 8 * ((r >> bit) & 1) + 4 * ((g >> bit) & 1) + 2 * ((b >> bit) & 1) + 1 * ((a >> bit) & 1);
+    if(!tree->children[i])
+    {
+      tree->children[i] = (ColorTree*)lodepng_malloc(sizeof(ColorTree));
+      color_tree_init(tree->children[i]);
+    }
+    tree = tree->children[i];
+  }
+  tree->index = (int)index;
+}
+
+/*put a pixel, given its RGBA color, into image of any color type*/
+static unsigned rgba8ToPixel(unsigned char* out, size_t i,
+                             const LodePNGColorMode* mode, ColorTree* tree /*for palette*/,
+                             unsigned char r, unsigned char g, unsigned char b, unsigned char a)
+{
+  if(mode->colortype == LCT_GREY)
+  {
+    unsigned char grey = r; /*((unsigned short)r + g + b) / 3*/;
+    if(mode->bitdepth == 8) out[i] = grey;
+    else if(mode->bitdepth == 16) out[i * 2 + 0] = out[i * 2 + 1] = grey;
+    else
+    {
+      /*take the most significant bits of grey*/
+      grey = (grey >> (8 - mode->bitdepth)) & ((1 << mode->bitdepth) - 1);
+      addColorBits(out, i, mode->bitdepth, grey);
+    }
+  }
+  else if(mode->colortype == LCT_RGB)
+  {
+    if(mode->bitdepth == 8)
+    {
+      out[i * 3 + 0] = r;
+      out[i * 3 + 1] = g;
+      out[i * 3 + 2] = b;
+    }
+    else
+    {
+      out[i * 6 + 0] = out[i * 6 + 1] = r;
+      out[i * 6 + 2] = out[i * 6 + 3] = g;
+      out[i * 6 + 4] = out[i * 6 + 5] = b;
+    }
+  }
+  else if(mode->colortype == LCT_PALETTE)
+  {
+    int index = color_tree_get(tree, r, g, b, a);
+    if(index < 0) return 82; /*color not in palette*/
+    if(mode->bitdepth == 8) out[i] = index;
+    else addColorBits(out, i, mode->bitdepth, (unsigned)index);
+  }
+  else if(mode->colortype == LCT_GREY_ALPHA)
+  {
+    unsigned char grey = r; /*((unsigned short)r + g + b) / 3*/;
+    if(mode->bitdepth == 8)
+    {
+      out[i * 2 + 0] = grey;
+      out[i * 2 + 1] = a;
+    }
+    else if(mode->bitdepth == 16)
+    {
+      out[i * 4 + 0] = out[i * 4 + 1] = grey;
+      out[i * 4 + 2] = out[i * 4 + 3] = a;
+    }
+  }
+  else if(mode->colortype == LCT_RGBA)
+  {
+    if(mode->bitdepth == 8)
+    {
+      out[i * 4 + 0] = r;
+      out[i * 4 + 1] = g;
+      out[i * 4 + 2] = b;
+      out[i * 4 + 3] = a;
+    }
+    else
+    {
+      out[i * 8 + 0] = out[i * 8 + 1] = r;
+      out[i * 8 + 2] = out[i * 8 + 3] = g;
+      out[i * 8 + 4] = out[i * 8 + 5] = b;
+      out[i * 8 + 6] = out[i * 8 + 7] = a;
+    }
+  }
+
+  return 0; /*no error*/
+}
+
+/*put a pixel, given its RGBA16 color, into image of any color 16-bitdepth type*/
+static void rgba16ToPixel(unsigned char* out, size_t i,
+                         const LodePNGColorMode* mode,
+                         unsigned short r, unsigned short g, unsigned short b, unsigned short a)
+{
+  if(mode->colortype == LCT_GREY)
+  {
+    unsigned short grey = r; /*((unsigned)r + g + b) / 3*/;
+    out[i * 2 + 0] = (grey >> 8) & 255;
+    out[i * 2 + 1] = grey & 255;
+  }
+  else if(mode->colortype == LCT_RGB)
+  {
+    out[i * 6 + 0] = (r >> 8) & 255;
+    out[i * 6 + 1] = r & 255;
+    out[i * 6 + 2] = (g >> 8) & 255;
+    out[i * 6 + 3] = g & 255;
+    out[i * 6 + 4] = (b >> 8) & 255;
+    out[i * 6 + 5] = b & 255;
+  }
+  else if(mode->colortype == LCT_GREY_ALPHA)
+  {
+    unsigned short grey = r; /*((unsigned)r + g + b) / 3*/;
+    out[i * 4 + 0] = (grey >> 8) & 255;
+    out[i * 4 + 1] = grey & 255;
+    out[i * 4 + 2] = (a >> 8) & 255;
+    out[i * 4 + 3] = a & 255;
+  }
+  else if(mode->colortype == LCT_RGBA)
+  {
+    out[i * 8 + 0] = (r >> 8) & 255;
+    out[i * 8 + 1] = r & 255;
+    out[i * 8 + 2] = (g >> 8) & 255;
+    out[i * 8 + 3] = g & 255;
+    out[i * 8 + 4] = (b >> 8) & 255;
+    out[i * 8 + 5] = b & 255;
+    out[i * 8 + 6] = (a >> 8) & 255;
+    out[i * 8 + 7] = a & 255;
+  }
+}
+
+/*Get RGBA8 color of pixel with index i (y * width + x) from the raw image with given color type.*/
+static void getPixelColorRGBA8(unsigned char* r, unsigned char* g,
+                               unsigned char* b, unsigned char* a,
+                               const unsigned char* in, size_t i,
+                               const LodePNGColorMode* mode)
+{
+  if(mode->colortype == LCT_GREY)
+  {
+    if(mode->bitdepth == 8)
+    {
+      *r = *g = *b = in[i];
+      if(mode->key_defined && *r == mode->key_r) *a = 0;
+      else *a = 255;
+    }
+    else if(mode->bitdepth == 16)
+    {
+      *r = *g = *b = in[i * 2 + 0];
+      if(mode->key_defined && 256U * in[i * 2 + 0] + in[i * 2 + 1] == mode->key_r) *a = 0;
+      else *a = 255;
+    }
+    else
+    {
+      unsigned highest = ((1U << mode->bitdepth) - 1U); /*highest possible value for this bit depth*/
+      size_t j = i * mode->bitdepth;
+      unsigned value = readBitsFromReversedStream(&j, in, mode->bitdepth);
+      *r = *g = *b = (value * 255) / highest;
+      if(mode->key_defined && value == mode->key_r) *a = 0;
+      else *a = 255;
+    }
+  }
+  else if(mode->colortype == LCT_RGB)
+  {
+    if(mode->bitdepth == 8)
+    {
+      *r = in[i * 3 + 0]; *g = in[i * 3 + 1]; *b = in[i * 3 + 2];
+      if(mode->key_defined && *r == mode->key_r && *g == mode->key_g && *b == mode->key_b) *a = 0;
+      else *a = 255;
+    }
+    else
+    {
+      *r = in[i * 6 + 0];
+      *g = in[i * 6 + 2];
+      *b = in[i * 6 + 4];
+      if(mode->key_defined && 256U * in[i * 6 + 0] + in[i * 6 + 1] == mode->key_r
+         && 256U * in[i * 6 + 2] + in[i * 6 + 3] == mode->key_g
+         && 256U * in[i * 6 + 4] + in[i * 6 + 5] == mode->key_b) *a = 0;
+      else *a = 255;
+    }
+  }
+  else if(mode->colortype == LCT_PALETTE)
+  {
+    unsigned index;
+    if(mode->bitdepth == 8) index = in[i];
+    else
+    {
+      size_t j = i * mode->bitdepth;
+      index = readBitsFromReversedStream(&j, in, mode->bitdepth);
+    }
+
+    if(index >= mode->palettesize)
+    {
+      /*This is an error according to the PNG spec, but common PNG decoders make it black instead.
+      Done here too, slightly faster due to no error handling needed.*/
+      *r = *g = *b = 0;
+      *a = 255;
+    }
+    else
+    {
+      *r = mode->palette[index * 4 + 0];
+      *g = mode->palette[index * 4 + 1];
+      *b = mode->palette[index * 4 + 2];
+      *a = mode->palette[index * 4 + 3];
+    }
+  }
+  else if(mode->colortype == LCT_GREY_ALPHA)
+  {
+    if(mode->bitdepth == 8)
+    {
+      *r = *g = *b = in[i * 2 + 0];
+      *a = in[i * 2 + 1];
+    }
+    else
+    {
+      *r = *g = *b = in[i * 4 + 0];
+      *a = in[i * 4 + 2];
+    }
+  }
+  else if(mode->colortype == LCT_RGBA)
+  {
+    if(mode->bitdepth == 8)
+    {
+      *r = in[i * 4 + 0];
+      *g = in[i * 4 + 1];
+      *b = in[i * 4 + 2];
+      *a = in[i * 4 + 3];
+    }
+    else
+    {
+      *r = in[i * 8 + 0];
+      *g = in[i * 8 + 2];
+      *b = in[i * 8 + 4];
+      *a = in[i * 8 + 6];
+    }
+  }
+}
+
+/*Similar to getPixelColorRGBA8, but with all the for loops inside of the color
+mode test cases, optimized to convert the colors much faster, when converting
+to RGBA or RGB with 8 bit per cannel. buffer must be RGBA or RGB output with
+enough memory, if has_alpha is true the output is RGBA. mode has the color mode
+of the input buffer.*/
+static void getPixelColorsRGBA8(unsigned char* buffer, size_t numpixels,
+                                unsigned has_alpha, const unsigned char* in,
+                                const LodePNGColorMode* mode)
+{
+  unsigned num_channels = has_alpha ? 4 : 3;
+  size_t i;
+  if(mode->colortype == LCT_GREY)
+  {
+    if(mode->bitdepth == 8)
+    {
+      for(i = 0; i != numpixels; ++i, buffer += num_channels)
+      {
+        buffer[0] = buffer[1] = buffer[2] = in[i];
+        if(has_alpha) buffer[3] = mode->key_defined && in[i] == mode->key_r ? 0 : 255;
+      }
+    }
+    else if(mode->bitdepth == 16)
+    {
+      for(i = 0; i != numpixels; ++i, buffer += num_channels)
+      {
+        buffer[0] = buffer[1] = buffer[2] = in[i * 2];
+        if(has_alpha) buffer[3] = mode->key_defined && 256U * in[i * 2 + 0] + in[i * 2 + 1] == mode->key_r ? 0 : 255;
+      }
+    }
+    else
+    {
+      unsigned highest = ((1U << mode->bitdepth) - 1U); /*highest possible value for this bit depth*/
+      size_t j = 0;
+      for(i = 0; i != numpixels; ++i, buffer += num_channels)
+      {
+        unsigned value = readBitsFromReversedStream(&j, in, mode->bitdepth);
+        buffer[0] = buffer[1] = buffer[2] = (value * 255) / highest;
+        if(has_alpha) buffer[3] = mode->key_defined && value == mode->key_r ? 0 : 255;
+      }
+    }
+  }
+  else if(mode->colortype == LCT_RGB)
+  {
+    if(mode->bitdepth == 8)
+    {
+      for(i = 0; i != numpixels; ++i, buffer += num_channels)
+      {
+        buffer[0] = in[i * 3 + 0];
+        buffer[1] = in[i * 3 + 1];
+        buffer[2] = in[i * 3 + 2];
+        if(has_alpha) buffer[3] = mode->key_defined && buffer[0] == mode->key_r
+           && buffer[1]== mode->key_g && buffer[2] == mode->key_b ? 0 : 255;
+      }
+    }
+    else
+    {
+      for(i = 0; i != numpixels; ++i, buffer += num_channels)
+      {
+        buffer[0] = in[i * 6 + 0];
+        buffer[1] = in[i * 6 + 2];
+        buffer[2] = in[i * 6 + 4];
+        if(has_alpha) buffer[3] = mode->key_defined
+           && 256U * in[i * 6 + 0] + in[i * 6 + 1] == mode->key_r
+           && 256U * in[i * 6 + 2] + in[i * 6 + 3] == mode->key_g
+           && 256U * in[i * 6 + 4] + in[i * 6 + 5] == mode->key_b ? 0 : 255;
+      }
+    }
+  }
+  else if(mode->colortype == LCT_PALETTE)
+  {
+    unsigned index;
+    size_t j = 0;
+    for(i = 0; i != numpixels; ++i, buffer += num_channels)
+    {
+      if(mode->bitdepth == 8) index = in[i];
+      else index = readBitsFromReversedStream(&j, in, mode->bitdepth);
+
+      if(index >= mode->palettesize)
+      {
+        /*This is an error according to the PNG spec, but most PNG decoders make it black instead.
+        Done here too, slightly faster due to no error handling needed.*/
+        buffer[0] = buffer[1] = buffer[2] = 0;
+        if(has_alpha) buffer[3] = 255;
+      }
+      else
+      {
+        buffer[0] = mode->palette[index * 4 + 0];
+        buffer[1] = mode->palette[index * 4 + 1];
+        buffer[2] = mode->palette[index * 4 + 2];
+        if(has_alpha) buffer[3] = mode->palette[index * 4 + 3];
+      }
+    }
+  }
+  else if(mode->colortype == LCT_GREY_ALPHA)
+  {
+    if(mode->bitdepth == 8)
+    {
+      for(i = 0; i != numpixels; ++i, buffer += num_channels)
+      {
+        buffer[0] = buffer[1] = buffer[2] = in[i * 2 + 0];
+        if(has_alpha) buffer[3] = in[i * 2 + 1];
+      }
+    }
+    else
+    {
+      for(i = 0; i != numpixels; ++i, buffer += num_channels)
+      {
+        buffer[0] = buffer[1] = buffer[2] = in[i * 4 + 0];
+        if(has_alpha) buffer[3] = in[i * 4 + 2];
+      }
+    }
+  }
+  else if(mode->colortype == LCT_RGBA)
+  {
+    if(mode->bitdepth == 8)
+    {
+      for(i = 0; i != numpixels; ++i, buffer += num_channels)
+      {
+        buffer[0] = in[i * 4 + 0];
+        buffer[1] = in[i * 4 + 1];
+        buffer[2] = in[i * 4 + 2];
+        if(has_alpha) buffer[3] = in[i * 4 + 3];
+      }
+    }
+    else
+    {
+      for(i = 0; i != numpixels; ++i, buffer += num_channels)
+      {
+        buffer[0] = in[i * 8 + 0];
+        buffer[1] = in[i * 8 + 2];
+        buffer[2] = in[i * 8 + 4];
+        if(has_alpha) buffer[3] = in[i * 8 + 6];
+      }
+    }
+  }
+}
+
+/*Get RGBA16 color of pixel with index i (y * width + x) from the raw image with
+given color type, but the given color type must be 16-bit itself.*/
+static void getPixelColorRGBA16(unsigned short* r, unsigned short* g, unsigned short* b, unsigned short* a,
+                                const unsigned char* in, size_t i, const LodePNGColorMode* mode)
+{
+  if(mode->colortype == LCT_GREY)
+  {
+    *r = *g = *b = 256 * in[i * 2 + 0] + in[i * 2 + 1];
+    if(mode->key_defined && 256U * in[i * 2 + 0] + in[i * 2 + 1] == mode->key_r) *a = 0;
+    else *a = 65535;
+  }
+  else if(mode->colortype == LCT_RGB)
+  {
+    *r = 256u * in[i * 6 + 0] + in[i * 6 + 1];
+    *g = 256u * in[i * 6 + 2] + in[i * 6 + 3];
+    *b = 256u * in[i * 6 + 4] + in[i * 6 + 5];
+    if(mode->key_defined
+       && 256u * in[i * 6 + 0] + in[i * 6 + 1] == mode->key_r
+       && 256u * in[i * 6 + 2] + in[i * 6 + 3] == mode->key_g
+       && 256u * in[i * 6 + 4] + in[i * 6 + 5] == mode->key_b) *a = 0;
+    else *a = 65535;
+  }
+  else if(mode->colortype == LCT_GREY_ALPHA)
+  {
+    *r = *g = *b = 256u * in[i * 4 + 0] + in[i * 4 + 1];
+    *a = 256u * in[i * 4 + 2] + in[i * 4 + 3];
+  }
+  else if(mode->colortype == LCT_RGBA)
+  {
+    *r = 256u * in[i * 8 + 0] + in[i * 8 + 1];
+    *g = 256u * in[i * 8 + 2] + in[i * 8 + 3];
+    *b = 256u * in[i * 8 + 4] + in[i * 8 + 5];
+    *a = 256u * in[i * 8 + 6] + in[i * 8 + 7];
+  }
+}
+
+unsigned lodepng_convert(unsigned char* out, const unsigned char* in,
+                         const LodePNGColorMode* mode_out, const LodePNGColorMode* mode_in,
+                         unsigned w, unsigned h)
+{
+  size_t i;
+  ColorTree tree;
+  size_t numpixels = w * h;
+
+  if(lodepng_color_mode_equal(mode_out, mode_in))
+  {
+    size_t numbytes = lodepng_get_raw_size(w, h, mode_in);
+    for(i = 0; i != numbytes; ++i) out[i] = in[i];
+    return 0;
+  }
+
+  if(mode_out->colortype == LCT_PALETTE)
+  {
+    size_t palettesize = mode_out->palettesize;
+    const unsigned char* palette = mode_out->palette;
+    size_t palsize = 1u << mode_out->bitdepth;
+    /*if the user specified output palette but did not give the values, assume
+    they want the values of the input color type (assuming that one is palette).
+    Note that we never create a new palette ourselves.*/
+    if(palettesize == 0)
+    {
+      palettesize = mode_in->palettesize;
+      palette = mode_in->palette;
+    }
+    if(palettesize < palsize) palsize = palettesize;
+    color_tree_init(&tree);
+    for(i = 0; i != palsize; ++i)
+    {
+      const unsigned char* p = &palette[i * 4];
+      color_tree_add(&tree, p[0], p[1], p[2], p[3], i);
+    }
+  }
+
+  if(mode_in->bitdepth == 16 && mode_out->bitdepth == 16)
+  {
+    for(i = 0; i != numpixels; ++i)
+    {
+      unsigned short r = 0, g = 0, b = 0, a = 0;
+      getPixelColorRGBA16(&r, &g, &b, &a, in, i, mode_in);
+      rgba16ToPixel(out, i, mode_out, r, g, b, a);
+    }
+  }
+  else if(mode_out->bitdepth == 8 && mode_out->colortype == LCT_RGBA)
+  {
+    getPixelColorsRGBA8(out, numpixels, 1, in, mode_in);
+  }
+  else if(mode_out->bitdepth == 8 && mode_out->colortype == LCT_RGB)
+  {
+    getPixelColorsRGBA8(out, numpixels, 0, in, mode_in);
+  }
+  else
+  {
+    unsigned char r = 0, g = 0, b = 0, a = 0;
+    for(i = 0; i != numpixels; ++i)
+    {
+      getPixelColorRGBA8(&r, &g, &b, &a, in, i, mode_in);
+      CERROR_TRY_RETURN(rgba8ToPixel(out, i, mode_out, &tree, r, g, b, a));
+    }
+  }
+
+  if(mode_out->colortype == LCT_PALETTE)
+  {
+    color_tree_cleanup(&tree);
+  }
+
+  return 0; /*no error*/
+}
+
+#ifdef LODEPNG_COMPILE_ENCODER
+
+void lodepng_color_profile_init(LodePNGColorProfile* profile)
+{
+  profile->colored = 0;
+  profile->key = 0;
+  profile->alpha = 0;
+  profile->key_r = profile->key_g = profile->key_b = 0;
+  profile->numcolors = 0;
+  profile->bits = 1;
+}
+
+/*function used for debug purposes with C++*/
+/*void printColorProfile(LodePNGColorProfile* p)
+{
+  std::cout << "colored: " << (int)p->colored << ", ";
+  std::cout << "key: " << (int)p->key << ", ";
+  std::cout << "key_r: " << (int)p->key_r << ", ";
+  std::cout << "key_g: " << (int)p->key_g << ", ";
+  std::cout << "key_b: " << (int)p->key_b << ", ";
+  std::cout << "alpha: " << (int)p->alpha << ", ";
+  std::cout << "numcolors: " << (int)p->numcolors << ", ";
+  std::cout << "bits: " << (int)p->bits << std::endl;
+}*/
+
+/*Returns how many bits needed to represent given value (max 8 bit)*/
+static unsigned getValueRequiredBits(unsigned char value)
+{
+  if(value == 0 || value == 255) return 1;
+  /*The scaling of 2-bit and 4-bit values uses multiples of 85 and 17*/
+  if(value % 17 == 0) return value % 85 == 0 ? 2 : 4;
+  return 8;
+}
+
+/*profile must already have been inited with mode.
+It's ok to set some parameters of profile to done already.*/
+unsigned lodepng_get_color_profile(LodePNGColorProfile* profile,
+                                   const unsigned char* in, unsigned w, unsigned h,
+                                   const LodePNGColorMode* mode)
+{
+  unsigned error = 0;
+  size_t i;
+  ColorTree tree;
+  size_t numpixels = w * h;
+
+  unsigned colored_done = lodepng_is_greyscale_type(mode) ? 1 : 0;
+  unsigned alpha_done = lodepng_can_have_alpha(mode) ? 0 : 1;
+  unsigned numcolors_done = 0;
+  unsigned bpp = lodepng_get_bpp(mode);
+  unsigned bits_done = bpp == 1 ? 1 : 0;
+  unsigned maxnumcolors = 257;
+  unsigned sixteen = 0;
+  if(bpp <= 8) maxnumcolors = bpp == 1 ? 2 : (bpp == 2 ? 4 : (bpp == 4 ? 16 : 256));
+
+  color_tree_init(&tree);
+
+  /*Check if the 16-bit input is truly 16-bit*/
+  if(mode->bitdepth == 16)
+  {
+    unsigned short r, g, b, a;
+    for(i = 0; i != numpixels; ++i)
+    {
+      getPixelColorRGBA16(&r, &g, &b, &a, in, i, mode);
+      if((r & 255) != ((r >> 8) & 255) || (g & 255) != ((g >> 8) & 255) ||
+         (b & 255) != ((b >> 8) & 255) || (a & 255) != ((a >> 8) & 255)) /*first and second byte differ*/
+      {
+        sixteen = 1;
+        break;
+      }
+    }
+  }
+
+  if(sixteen)
+  {
+    unsigned short r = 0, g = 0, b = 0, a = 0;
+    profile->bits = 16;
+    bits_done = numcolors_done = 1; /*counting colors no longer useful, palette doesn't support 16-bit*/
+
+    for(i = 0; i != numpixels; ++i)
+    {
+      getPixelColorRGBA16(&r, &g, &b, &a, in, i, mode);
+
+      if(!colored_done && (r != g || r != b))
+      {
+        profile->colored = 1;
+        colored_done = 1;
+      }
+
+      if(!alpha_done)
+      {
+        unsigned matchkey = (r == profile->key_r && g == profile->key_g && b == profile->key_b);
+        if(a != 65535 && (a != 0 || (profile->key && !matchkey)))
+        {
+          profile->alpha = 1;
+          alpha_done = 1;
+          if(profile->bits < 8) profile->bits = 8; /*PNG has no alphachannel modes with less than 8-bit per channel*/
+        }
+        else if(a == 0 && !profile->alpha && !profile->key)
+        {
+          profile->key = 1;
+          profile->key_r = r;
+          profile->key_g = g;
+          profile->key_b = b;
+        }
+        else if(a == 65535 && profile->key && matchkey)
+        {
+          /* Color key cannot be used if an opaque pixel also has that RGB color. */
+          profile->alpha = 1;
+          alpha_done = 1;
+        }
+      }
+      if(alpha_done && numcolors_done && colored_done && bits_done) break;
+    }
+
+    if(profile->key && !profile->alpha)
+    {
+      for(i = 0; i != numpixels; ++i)
+      {
+        getPixelColorRGBA16(&r, &g, &b, &a, in, i, mode);
+        if(a != 0 && r == profile->key_r && g == profile->key_g && b == profile->key_b)
+        {
+          /* Color key cannot be used if an opaque pixel also has that RGB color. */
+          profile->alpha = 1;
+          alpha_done = 1;
+        }
+      }
+    }
+  }
+  else /* < 16-bit */
+  {
+    unsigned char r = 0, g = 0, b = 0, a = 0;
+    for(i = 0; i != numpixels; ++i)
+    {
+      getPixelColorRGBA8(&r, &g, &b, &a, in, i, mode);
+
+      if(!bits_done && profile->bits < 8)
+      {
+        /*only r is checked, < 8 bits is only relevant for greyscale*/
+        unsigned bits = getValueRequiredBits(r);
+        if(bits > profile->bits) profile->bits = bits;
+      }
+      bits_done = (profile->bits >= bpp);
+
+      if(!colored_done && (r != g || r != b))
+      {
+        profile->colored = 1;
+        colored_done = 1;
+        if(profile->bits < 8) profile->bits = 8; /*PNG has no colored modes with less than 8-bit per channel*/
+      }
+
+      if(!alpha_done)
+      {
+        unsigned matchkey = (r == profile->key_r && g == profile->key_g && b == profile->key_b);
+        if(a != 255 && (a != 0 || (profile->key && !matchkey)))
+        {
+          profile->alpha = 1;
+          alpha_done = 1;
+          if(profile->bits < 8) profile->bits = 8; /*PNG has no alphachannel modes with less than 8-bit per channel*/
+        }
+        else if(a == 0 && !profile->alpha && !profile->key)
+        {
+          profile->key = 1;
+          profile->key_r = r;
+          profile->key_g = g;
+          profile->key_b = b;
+        }
+        else if(a == 255 && profile->key && matchkey)
+        {
+          /* Color key cannot be used if an opaque pixel also has that RGB color. */
+          profile->alpha = 1;
+          alpha_done = 1;
+          if(profile->bits < 8) profile->bits = 8; /*PNG has no alphachannel modes with less than 8-bit per channel*/
+        }
+      }
+
+      if(!numcolors_done)
+      {
+        if(!color_tree_has(&tree, r, g, b, a))
+        {
+          color_tree_add(&tree, r, g, b, a, profile->numcolors);
+          if(profile->numcolors < 256)
+          {
+            unsigned char* p = profile->palette;
+            unsigned n = profile->numcolors;
+            p[n * 4 + 0] = r;
+            p[n * 4 + 1] = g;
+            p[n * 4 + 2] = b;
+            p[n * 4 + 3] = a;
+          }
+          ++profile->numcolors;
+          numcolors_done = profile->numcolors >= maxnumcolors;
+        }
+      }
+
+      if(alpha_done && numcolors_done && colored_done && bits_done) break;
+    }
+
+    if(profile->key && !profile->alpha)
+    {
+      for(i = 0; i != numpixels; ++i)
+      {
+        getPixelColorRGBA8(&r, &g, &b, &a, in, i, mode);
+        if(a != 0 && r == profile->key_r && g == profile->key_g && b == profile->key_b)
+        {
+          /* Color key cannot be used if an opaque pixel also has that RGB color. */
+          profile->alpha = 1;
+          alpha_done = 1;
+        }
+      }
+    }
+
+    /*make the profile's key always 16-bit for consistency - repeat each byte twice*/
+    profile->key_r += (profile->key_r << 8);
+    profile->key_g += (profile->key_g << 8);
+    profile->key_b += (profile->key_b << 8);
+  }
+
+  color_tree_cleanup(&tree);
+  return error;
+}
+
+/*Automatically chooses color type that gives smallest amount of bits in the
+output image, e.g. grey if there are only greyscale pixels, palette if there
+are less than 256 colors, ...
+Updates values of mode with a potentially smaller color model. mode_out should
+contain the user chosen color model, but will be overwritten with the new chosen one.*/
+unsigned lodepng_auto_choose_color(LodePNGColorMode* mode_out,
+                                   const unsigned char* image, unsigned w, unsigned h,
+                                   const LodePNGColorMode* mode_in)
+{
+  LodePNGColorProfile prof;
+  unsigned error = 0;
+  unsigned i, n, palettebits, grey_ok, palette_ok;
+
+  lodepng_color_profile_init(&prof);
+  error = lodepng_get_color_profile(&prof, image, w, h, mode_in);
+  if(error) return error;
+  mode_out->key_defined = 0;
+
+  if(prof.key && w * h <= 16)
+  {
+    prof.alpha = 1; /*too few pixels to justify tRNS chunk overhead*/
+    if(prof.bits < 8) prof.bits = 8; /*PNG has no alphachannel modes with less than 8-bit per channel*/
+  }
+  grey_ok = !prof.colored && !prof.alpha; /*grey without alpha, with potentially low bits*/
+  n = prof.numcolors;
+  palettebits = n <= 2 ? 1 : (n <= 4 ? 2 : (n <= 16 ? 4 : 8));
+  palette_ok = n <= 256 && (n * 2 < w * h) && prof.bits <= 8;
+  if(w * h < n * 2) palette_ok = 0; /*don't add palette overhead if image has only a few pixels*/
+  if(grey_ok && prof.bits <= palettebits) palette_ok = 0; /*grey is less overhead*/
+
+  if(palette_ok)
+  {
+    unsigned char* p = prof.palette;
+    lodepng_palette_clear(mode_out); /*remove potential earlier palette*/
+    for(i = 0; i != prof.numcolors; ++i)
+    {
+      error = lodepng_palette_add(mode_out, p[i * 4 + 0], p[i * 4 + 1], p[i * 4 + 2], p[i * 4 + 3]);
+      if(error) break;
+    }
+
+    mode_out->colortype = LCT_PALETTE;
+    mode_out->bitdepth = palettebits;
+
+    if(mode_in->colortype == LCT_PALETTE && mode_in->palettesize >= mode_out->palettesize
+        && mode_in->bitdepth == mode_out->bitdepth)
+    {
+      /*If input should have same palette colors, keep original to preserve its order and prevent conversion*/
+      lodepng_color_mode_cleanup(mode_out);
+      lodepng_color_mode_copy(mode_out, mode_in);
+    }
+  }
+  else /*8-bit or 16-bit per channel*/
+  {
+    mode_out->bitdepth = prof.bits;
+    mode_out->colortype = prof.alpha ? (prof.colored ? LCT_RGBA : LCT_GREY_ALPHA)
+                                     : (prof.colored ? LCT_RGB : LCT_GREY);
+
+    if(prof.key && !prof.alpha)
+    {
+      unsigned mask = (1u << mode_out->bitdepth) - 1u; /*profile always uses 16-bit, mask converts it*/
+      mode_out->key_r = prof.key_r & mask;
+      mode_out->key_g = prof.key_g & mask;
+      mode_out->key_b = prof.key_b & mask;
+      mode_out->key_defined = 1;
+    }
+  }
+
+  return error;
+}
+
+#endif /* #ifdef LODEPNG_COMPILE_ENCODER */
+
+/*
+Paeth predicter, used by PNG filter type 4
+The parameters are of type short, but should come from unsigned chars, the shorts
+are only needed to make the paeth calculation correct.
+*/
+static unsigned char paethPredictor(short a, short b, short c)
+{
+  short pa = abs(b - c);
+  short pb = abs(a - c);
+  short pc = abs(a + b - c - c);
+
+  if(pc < pa && pc < pb) return (unsigned char)c;
+  else if(pb < pa) return (unsigned char)b;
+  else return (unsigned char)a;
+}
+
+/*shared values used by multiple Adam7 related functions*/
+
+static const unsigned ADAM7_IX[7] = { 0, 4, 0, 2, 0, 1, 0 }; /*x start values*/
+static const unsigned ADAM7_IY[7] = { 0, 0, 4, 0, 2, 0, 1 }; /*y start values*/
+static const unsigned ADAM7_DX[7] = { 8, 8, 4, 4, 2, 2, 1 }; /*x delta values*/
+static const unsigned ADAM7_DY[7] = { 8, 8, 8, 4, 4, 2, 2 }; /*y delta values*/
+
+/*
+Outputs various dimensions and positions in the image related to the Adam7 reduced images.
+passw: output containing the width of the 7 passes
+passh: output containing the height of the 7 passes
+filter_passstart: output containing the index of the start and end of each
+ reduced image with filter bytes
+padded_passstart output containing the index of the start and end of each
+ reduced image when without filter bytes but with padded scanlines
+passstart: output containing the index of the start and end of each reduced
+ image without padding between scanlines, but still padding between the images
+w, h: width and height of non-interlaced image
+bpp: bits per pixel
+"padded" is only relevant if bpp is less than 8 and a scanline or image does not
+ end at a full byte
+*/
+static void Adam7_getpassvalues(unsigned passw[7], unsigned passh[7], size_t filter_passstart[8],
+                                size_t padded_passstart[8], size_t passstart[8], unsigned w, unsigned h, unsigned bpp)
+{
+  /*the passstart values have 8 values: the 8th one indicates the byte after the end of the 7th (= last) pass*/
+  unsigned i;
+
+  /*calculate width and height in pixels of each pass*/
+  for(i = 0; i != 7; ++i)
+  {
+    passw[i] = (w + ADAM7_DX[i] - ADAM7_IX[i] - 1) / ADAM7_DX[i];
+    passh[i] = (h + ADAM7_DY[i] - ADAM7_IY[i] - 1) / ADAM7_DY[i];
+    if(passw[i] == 0) passh[i] = 0;
+    if(passh[i] == 0) passw[i] = 0;
+  }
+
+  filter_passstart[0] = padded_passstart[0] = passstart[0] = 0;
+  for(i = 0; i != 7; ++i)
+  {
+    /*if passw[i] is 0, it's 0 bytes, not 1 (no filtertype-byte)*/
+    filter_passstart[i + 1] = filter_passstart[i]
+                            + ((passw[i] && passh[i]) ? passh[i] * (1 + (passw[i] * bpp + 7) / 8) : 0);
+    /*bits padded if needed to fill full byte at end of each scanline*/
+    padded_passstart[i + 1] = padded_passstart[i] + passh[i] * ((passw[i] * bpp + 7) / 8);
+    /*only padded at end of reduced image*/
+    passstart[i + 1] = passstart[i] + (passh[i] * passw[i] * bpp + 7) / 8;
+  }
+}
+
+#ifdef LODEPNG_COMPILE_DECODER
+
+/* ////////////////////////////////////////////////////////////////////////// */
+/* / PNG Decoder                                                            / */
+/* ////////////////////////////////////////////////////////////////////////// */
+
+/*read the information from the header and store it in the LodePNGInfo. return value is error*/
+unsigned lodepng_inspect(unsigned* w, unsigned* h, LodePNGState* state,
+                         const unsigned char* in, size_t insize)
+{
+  LodePNGInfo* info = &state->info_png;
+  if(insize == 0 || in == 0)
+  {
+    CERROR_RETURN_ERROR(state->error, 48); /*error: the given data is empty*/
+  }
+  if(insize < 33)
+  {
+    CERROR_RETURN_ERROR(state->error, 27); /*error: the data length is smaller than the length of a PNG header*/
+  }
+
+  /*when decoding a new PNG image, make sure all parameters created after previous decoding are reset*/
+  lodepng_info_cleanup(info);
+  lodepng_info_init(info);
+
+  if(in[0] != 137 || in[1] != 80 || in[2] != 78 || in[3] != 71
+     || in[4] != 13 || in[5] != 10 || in[6] != 26 || in[7] != 10)
+  {
+    CERROR_RETURN_ERROR(state->error, 28); /*error: the first 8 bytes are not the correct PNG signature*/
+  }
+  if(lodepng_chunk_length(in + 8) != 13)
+  {
+    CERROR_RETURN_ERROR(state->error, 94); /*error: header size must be 13 bytes*/
+  }
+  if(!lodepng_chunk_type_equals(in + 8, "IHDR"))
+  {
+    CERROR_RETURN_ERROR(state->error, 29); /*error: it doesn't start with a IHDR chunk!*/
+  }
+
+  /*read the values given in the header*/
+  *w = lodepng_read32bitInt(&in[16]);
+  *h = lodepng_read32bitInt(&in[20]);
+  info->color.bitdepth = in[24];
+  info->color.colortype = (LodePNGColorType)in[25];
+  info->compression_method = in[26];
+  info->filter_method = in[27];
+  info->interlace_method = in[28];
+
+  if(*w == 0 || *h == 0)
+  {
+    CERROR_RETURN_ERROR(state->error, 93);
+  }
+
+  if(!state->decoder.ignore_crc)
+  {
+    unsigned CRC = lodepng_read32bitInt(&in[29]);
+    unsigned checksum = lodepng_crc32(&in[12], 17);
+    if(CRC != checksum)
+    {
+      CERROR_RETURN_ERROR(state->error, 57); /*invalid CRC*/
+    }
+  }
+
+  /*error: only compression method 0 is allowed in the specification*/
+  if(info->compression_method != 0) CERROR_RETURN_ERROR(state->error, 32);
+  /*error: only filter method 0 is allowed in the specification*/
+  if(info->filter_method != 0) CERROR_RETURN_ERROR(state->error, 33);
+  /*error: only interlace methods 0 and 1 exist in the specification*/
+  if(info->interlace_method > 1) CERROR_RETURN_ERROR(state->error, 34);
+
+  state->error = checkColorValidity(info->color.colortype, info->color.bitdepth);
+  return state->error;
+}
+
+static unsigned unfilterScanline(unsigned char* recon, const unsigned char* scanline, const unsigned char* precon,
+                                 size_t bytewidth, unsigned char filterType, size_t length)
+{
+  /*
+  For PNG filter method 0
+  unfilter a PNG image scanline by scanline. when the pixels are smaller than 1 byte,
+  the filter works byte per byte (bytewidth = 1)
+  precon is the previous unfiltered scanline, recon the result, scanline the current one
+  the incoming scanlines do NOT include the filtertype byte, that one is given in the parameter filterType instead
+  recon and scanline MAY be the same memory address! precon must be disjoint.
+  */
+
+  size_t i;
+  switch(filterType)
+  {
+    case 0:
+      for(i = 0; i != length; ++i) recon[i] = scanline[i];
+      break;
+    case 1:
+      for(i = 0; i != bytewidth; ++i) recon[i] = scanline[i];
+      for(i = bytewidth; i < length; ++i) recon[i] = scanline[i] + recon[i - bytewidth];
+      break;
+    case 2:
+      if(precon)
+      {
+        for(i = 0; i != length; ++i) recon[i] = scanline[i] + precon[i];
+      }
+      else
+      {
+        for(i = 0; i != length; ++i) recon[i] = scanline[i];
+      }
+      break;
+    case 3:
+      if(precon)
+      {
+        for(i = 0; i != bytewidth; ++i) recon[i] = scanline[i] + (precon[i] >> 1);
+        for(i = bytewidth; i < length; ++i) recon[i] = scanline[i] + ((recon[i - bytewidth] + precon[i]) >> 1);
+      }
+      else
+      {
+        for(i = 0; i != bytewidth; ++i) recon[i] = scanline[i];
+        for(i = bytewidth; i < length; ++i) recon[i] = scanline[i] + (recon[i - bytewidth] >> 1);
+      }
+      break;
+    case 4:
+      if(precon)
+      {
+        for(i = 0; i != bytewidth; ++i)
+        {
+          recon[i] = (scanline[i] + precon[i]); /*paethPredictor(0, precon[i], 0) is always precon[i]*/
+        }
+        for(i = bytewidth; i < length; ++i)
+        {
+          recon[i] = (scanline[i] + paethPredictor(recon[i - bytewidth], precon[i], precon[i - bytewidth]));
+        }
+      }
+      else
+      {
+        for(i = 0; i != bytewidth; ++i)
+        {
+          recon[i] = scanline[i];
+        }
+        for(i = bytewidth; i < length; ++i)
+        {
+          /*paethPredictor(recon[i - bytewidth], 0, 0) is always recon[i - bytewidth]*/
+          recon[i] = (scanline[i] + recon[i - bytewidth]);
+        }
+      }
+      break;
+    default: return 36; /*error: unexisting filter type given*/
+  }
+  return 0;
+}
+
+static unsigned unfilter(unsigned char* out, const unsigned char* in, unsigned w, unsigned h, unsigned bpp)
+{
+  /*
+  For PNG filter method 0
+  this function unfilters a single image (e.g. without interlacing this is called once, with Adam7 seven times)
+  out must have enough bytes allocated already, in must have the scanlines + 1 filtertype byte per scanline
+  w and h are image dimensions or dimensions of reduced image, bpp is bits per pixel
+  in and out are allowed to be the same memory address (but aren't the same size since in has the extra filter bytes)
+  */
+
+  unsigned y;
+  unsigned char* prevline = 0;
+
+  /*bytewidth is used for filtering, is 1 when bpp < 8, number of bytes per pixel otherwise*/
+  size_t bytewidth = (bpp + 7) / 8;
+  size_t linebytes = (w * bpp + 7) / 8;
+
+  for(y = 0; y < h; ++y)
+  {
+    size_t outindex = linebytes * y;
+    size_t inindex = (1 + linebytes) * y; /*the extra filterbyte added to each row*/
+    unsigned char filterType = in[inindex];
+
+    CERROR_TRY_RETURN(unfilterScanline(&out[outindex], &in[inindex + 1], prevline, bytewidth, filterType, linebytes));
+
+    prevline = &out[outindex];
+  }
+
+  return 0;
+}
+
+/*
+in: Adam7 interlaced image, with no padding bits between scanlines, but between
+ reduced images so that each reduced image starts at a byte.
+out: the same pixels, but re-ordered so that they're now a non-interlaced image with size w*h
+bpp: bits per pixel
+out has the following size in bits: w * h * bpp.
+in is possibly bigger due to padding bits between reduced images.
+out must be big enough AND must be 0 everywhere if bpp < 8 in the current implementation
+(because that's likely a little bit faster)
+NOTE: comments about padding bits are only relevant if bpp < 8
+*/
+static void Adam7_deinterlace(unsigned char* out, const unsigned char* in, unsigned w, unsigned h, unsigned bpp)
+{
+  unsigned passw[7], passh[7];
+  size_t filter_passstart[8], padded_passstart[8], passstart[8];
+  unsigned i;
+
+  Adam7_getpassvalues(passw, passh, filter_passstart, padded_passstart, passstart, w, h, bpp);
+
+  if(bpp >= 8)
+  {
+    for(i = 0; i != 7; ++i)
+    {
+      unsigned x, y, b;
+      size_t bytewidth = bpp / 8;
+      for(y = 0; y < passh[i]; ++y)
+      for(x = 0; x < passw[i]; ++x)
+      {
+        size_t pixelinstart = passstart[i] + (y * passw[i] + x) * bytewidth;
+        size_t pixeloutstart = ((ADAM7_IY[i] + y * ADAM7_DY[i]) * w + ADAM7_IX[i] + x * ADAM7_DX[i]) * bytewidth;
+        for(b = 0; b < bytewidth; ++b)
+        {
+          out[pixeloutstart + b] = in[pixelinstart + b];
+        }
+      }
+    }
+  }
+  else /*bpp < 8: Adam7 with pixels < 8 bit is a bit trickier: with bit pointers*/
+  {
+    for(i = 0; i != 7; ++i)
+    {
+      unsigned x, y, b;
+      unsigned ilinebits = bpp * passw[i];
+      unsigned olinebits = bpp * w;
+      size_t obp, ibp; /*bit pointers (for out and in buffer)*/
+      for(y = 0; y < passh[i]; ++y)
+      for(x = 0; x < passw[i]; ++x)
+      {
+        ibp = (8 * passstart[i]) + (y * ilinebits + x * bpp);
+        obp = (ADAM7_IY[i] + y * ADAM7_DY[i]) * olinebits + (ADAM7_IX[i] + x * ADAM7_DX[i]) * bpp;
+        for(b = 0; b < bpp; ++b)
+        {
+          unsigned char bit = readBitFromReversedStream(&ibp, in);
+          /*note that this function assumes the out buffer is completely 0, use setBitOfReversedStream otherwise*/
+          setBitOfReversedStream0(&obp, out, bit);
+        }
+      }
+    }
+  }
+}
+
+static void removePaddingBits(unsigned char* out, const unsigned char* in,
+                              size_t olinebits, size_t ilinebits, unsigned h)
+{
+  /*
+  After filtering there are still padding bits if scanlines have non multiple of 8 bit amounts. They need
+  to be removed (except at last scanline of (Adam7-reduced) image) before working with pure image buffers
+  for the Adam7 code, the color convert code and the output to the user.
+  in and out are allowed to be the same buffer, in may also be higher but still overlapping; in must
+  have >= ilinebits*h bits, out must have >= olinebits*h bits, olinebits must be <= ilinebits
+  also used to move bits after earlier such operations happened, e.g. in a sequence of reduced images from Adam7
+  only useful if (ilinebits - olinebits) is a value in the range 1..7
+  */
+  unsigned y;
+  size_t diff = ilinebits - olinebits;
+  size_t ibp = 0, obp = 0; /*input and output bit pointers*/
+  for(y = 0; y < h; ++y)
+  {
+    size_t x;
+    for(x = 0; x < olinebits; ++x)
+    {
+      unsigned char bit = readBitFromReversedStream(&ibp, in);
+      setBitOfReversedStream(&obp, out, bit);
+    }
+    ibp += diff;
+  }
+}
+
+/*out must be buffer big enough to contain full image, and in must contain the full decompressed data from
+the IDAT chunks (with filter index bytes and possible padding bits)
+return value is error*/
+static unsigned postProcessScanlines(unsigned char* out, unsigned char* in,
+                                     unsigned w, unsigned h, const LodePNGInfo* info_png)
+{
+  /*
+  This function converts the filtered-padded-interlaced data into pure 2D image buffer with the PNG's colortype.
+  Steps:
+  *) if no Adam7: 1) unfilter 2) remove padding bits (= posible extra bits per scanline if bpp < 8)
+  *) if adam7: 1) 7x unfilter 2) 7x remove padding bits 3) Adam7_deinterlace
+  NOTE: the in buffer will be overwritten with intermediate data!
+  */
+  unsigned bpp = lodepng_get_bpp(&info_png->color);
+  if(bpp == 0) return 31; /*error: invalid colortype*/
+
+  if(info_png->interlace_method == 0)
+  {
+    if(bpp < 8 && w * bpp != ((w * bpp + 7) / 8) * 8)
+    {
+      CERROR_TRY_RETURN(unfilter(in, in, w, h, bpp));
+      removePaddingBits(out, in, w * bpp, ((w * bpp + 7) / 8) * 8, h);
+    }
+    /*we can immediately filter into the out buffer, no other steps needed*/
+    else CERROR_TRY_RETURN(unfilter(out, in, w, h, bpp));
+  }
+  else /*interlace_method is 1 (Adam7)*/
+  {
+    unsigned passw[7], passh[7]; size_t filter_passstart[8], padded_passstart[8], passstart[8];
+    unsigned i;
+
+    Adam7_getpassvalues(passw, passh, filter_passstart, padded_passstart, passstart, w, h, bpp);
+
+    for(i = 0; i != 7; ++i)
+    {
+      CERROR_TRY_RETURN(unfilter(&in[padded_passstart[i]], &in[filter_passstart[i]], passw[i], passh[i], bpp));
+      /*TODO: possible efficiency improvement: if in this reduced image the bits fit nicely in 1 scanline,
+      move bytes instead of bits or move not at all*/
+      if(bpp < 8)
+      {
+        /*remove padding bits in scanlines; after this there still may be padding
+        bits between the different reduced images: each reduced image still starts nicely at a byte*/
+        removePaddingBits(&in[passstart[i]], &in[padded_passstart[i]], passw[i] * bpp,
+                          ((passw[i] * bpp + 7) / 8) * 8, passh[i]);
+      }
+    }
+
+    Adam7_deinterlace(out, in, w, h, bpp);
+  }
+
+  return 0;
+}
+
+static unsigned readChunk_PLTE(LodePNGColorMode* color, const unsigned char* data, size_t chunkLength)
+{
+  unsigned pos = 0, i;
+  if(color->palette) lodepng_free(color->palette);
+  color->palettesize = chunkLength / 3;
+  color->palette = (unsigned char*)lodepng_malloc(4 * color->palettesize);
+  if(!color->palette && color->palettesize)
+  {
+    color->palettesize = 0;
+    return 83; /*alloc fail*/
+  }
+  if(color->palettesize > 256) return 38; /*error: palette too big*/
+
+  for(i = 0; i != color->palettesize; ++i)
+  {
+    color->palette[4 * i + 0] = data[pos++]; /*R*/
+    color->palette[4 * i + 1] = data[pos++]; /*G*/
+    color->palette[4 * i + 2] = data[pos++]; /*B*/
+    color->palette[4 * i + 3] = 255; /*alpha*/
+  }
+
+  return 0; /* OK */
+}
+
+static unsigned readChunk_tRNS(LodePNGColorMode* color, const unsigned char* data, size_t chunkLength)
+{
+  unsigned i;
+  if(color->colortype == LCT_PALETTE)
+  {
+    /*error: more alpha values given than there are palette entries*/
+    if(chunkLength > color->palettesize) return 38;
+
+    for(i = 0; i != chunkLength; ++i) color->palette[4 * i + 3] = data[i];
+  }
+  else if(color->colortype == LCT_GREY)
+  {
+    /*error: this chunk must be 2 bytes for greyscale image*/
+    if(chunkLength != 2) return 30;
+
+    color->key_defined = 1;
+    color->key_r = color->key_g = color->key_b = 256u * data[0] + data[1];
+  }
+  else if(color->colortype == LCT_RGB)
+  {
+    /*error: this chunk must be 6 bytes for RGB image*/
+    if(chunkLength != 6) return 41;
+
+    color->key_defined = 1;
+    color->key_r = 256u * data[0] + data[1];
+    color->key_g = 256u * data[2] + data[3];
+    color->key_b = 256u * data[4] + data[5];
+  }
+  else return 42; /*error: tRNS chunk not allowed for other color models*/
+
+  return 0; /* OK */
+}
+
+
+#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
+/*background color chunk (bKGD)*/
+static unsigned readChunk_bKGD(LodePNGInfo* info, const unsigned char* data, size_t chunkLength)
+{
+  if(info->color.colortype == LCT_PALETTE)
+  {
+    /*error: this chunk must be 1 byte for indexed color image*/
+    if(chunkLength != 1) return 43;
+
+    info->background_defined = 1;
+    info->background_r = info->background_g = info->background_b = data[0];
+  }
+  else if(info->color.colortype == LCT_GREY || info->color.colortype == LCT_GREY_ALPHA)
+  {
+    /*error: this chunk must be 2 bytes for greyscale image*/
+    if(chunkLength != 2) return 44;
+
+    info->background_defined = 1;
+    info->background_r = info->background_g = info->background_b = 256u * data[0] + data[1];
+  }
+  else if(info->color.colortype == LCT_RGB || info->color.colortype == LCT_RGBA)
+  {
+    /*error: this chunk must be 6 bytes for greyscale image*/
+    if(chunkLength != 6) return 45;
+
+    info->background_defined = 1;
+    info->background_r = 256u * data[0] + data[1];
+    info->background_g = 256u * data[2] + data[3];
+    info->background_b = 256u * data[4] + data[5];
+  }
+
+  return 0; /* OK */
+}
+
+/*text chunk (tEXt)*/
+static unsigned readChunk_tEXt(LodePNGInfo* info, const unsigned char* data, size_t chunkLength)
+{
+  unsigned error = 0;
+  char *key = 0, *str = 0;
+  unsigned i;
+
+  while(!error) /*not really a while loop, only used to break on error*/
+  {
+    unsigned length, string2_begin;
+
+    length = 0;
+    while(length < chunkLength && data[length] != 0) ++length;
+    /*even though it's not allowed by the standard, no error is thrown if
+    there's no null termination char, if the text is empty*/
+    if(length < 1 || length > 79) CERROR_BREAK(error, 89); /*keyword too short or long*/
+
+    key = (char*)lodepng_malloc(length + 1);
+    if(!key) CERROR_BREAK(error, 83); /*alloc fail*/
+
+    key[length] = 0;
+    for(i = 0; i != length; ++i) key[i] = (char)data[i];
+
+    string2_begin = length + 1; /*skip keyword null terminator*/
+
+    length = chunkLength < string2_begin ? 0 : chunkLength - string2_begin;
+    str = (char*)lodepng_malloc(length + 1);
+    if(!str) CERROR_BREAK(error, 83); /*alloc fail*/
+
+    str[length] = 0;
+    for(i = 0; i != length; ++i) str[i] = (char)data[string2_begin + i];
+
+    error = lodepng_add_text(info, key, str);
+
+    break;
+  }
+
+  lodepng_free(key);
+  lodepng_free(str);
+
+  return error;
+}
+
+/*compressed text chunk (zTXt)*/
+static unsigned readChunk_zTXt(LodePNGInfo* info, const LodePNGDecompressSettings* zlibsettings,
+                               const unsigned char* data, size_t chunkLength)
+{
+  unsigned error = 0;
+  unsigned i;
+
+  unsigned length, string2_begin;
+  char *key = 0;
+  ucvector decoded;
+
+  ucvector_init(&decoded);
+
+  while(!error) /*not really a while loop, only used to break on error*/
+  {
+    for(length = 0; length < chunkLength && data[length] != 0; ++length) ;
+    if(length + 2 >= chunkLength) CERROR_BREAK(error, 75); /*no null termination, corrupt?*/
+    if(length < 1 || length > 79) CERROR_BREAK(error, 89); /*keyword too short or long*/
+
+    key = (char*)lodepng_malloc(length + 1);
+    if(!key) CERROR_BREAK(error, 83); /*alloc fail*/
+
+    key[length] = 0;
+    for(i = 0; i != length; ++i) key[i] = (char)data[i];
+
+    if(data[length + 1] != 0) CERROR_BREAK(error, 72); /*the 0 byte indicating compression must be 0*/
+
+    string2_begin = length + 2;
+    if(string2_begin > chunkLength) CERROR_BREAK(error, 75); /*no null termination, corrupt?*/
+
+    length = chunkLength - string2_begin;
+    /*will fail if zlib error, e.g. if length is too small*/
+    error = zlib_decompress(&decoded.data, &decoded.size,
+                            (unsigned char*)(&data[string2_begin]),
+                            length, zlibsettings);
+    if(error) break;
+    ucvector_push_back(&decoded, 0);
+
+    error = lodepng_add_text(info, key, (char*)decoded.data);
+
+    break;
+  }
+
+  lodepng_free(key);
+  ucvector_cleanup(&decoded);
+
+  return error;
+}
+
+/*international text chunk (iTXt)*/
+static unsigned readChunk_iTXt(LodePNGInfo* info, const LodePNGDecompressSettings* zlibsettings,
+                               const unsigned char* data, size_t chunkLength)
+{
+  unsigned error = 0;
+  unsigned i;
+
+  unsigned length, begin, compressed;
+  char *key = 0, *langtag = 0, *transkey = 0;
+  ucvector decoded;
+  ucvector_init(&decoded);
+
+  while(!error) /*not really a while loop, only used to break on error*/
+  {
+    /*Quick check if the chunk length isn't too small. Even without check
+    it'd still fail with other error checks below if it's too short. This just gives a different error code.*/
+    if(chunkLength < 5) CERROR_BREAK(error, 30); /*iTXt chunk too short*/
+
+    /*read the key*/
+    for(length = 0; length < chunkLength && data[length] != 0; ++length) ;
+    if(length + 3 >= chunkLength) CERROR_BREAK(error, 75); /*no null termination char, corrupt?*/
+    if(length < 1 || length > 79) CERROR_BREAK(error, 89); /*keyword too short or long*/
+
+    key = (char*)lodepng_malloc(length + 1);
+    if(!key) CERROR_BREAK(error, 83); /*alloc fail*/
+
+    key[length] = 0;
+    for(i = 0; i != length; ++i) key[i] = (char)data[i];
+
+    /*read the compression method*/
+    compressed = data[length + 1];
+    if(data[length + 2] != 0) CERROR_BREAK(error, 72); /*the 0 byte indicating compression must be 0*/
+
+    /*even though it's not allowed by the standard, no error is thrown if
+    there's no null termination char, if the text is empty for the next 3 texts*/
+
+    /*read the langtag*/
+    begin = length + 3;
+    length = 0;
+    for(i = begin; i < chunkLength && data[i] != 0; ++i) ++length;
+
+    langtag = (char*)lodepng_malloc(length + 1);
+    if(!langtag) CERROR_BREAK(error, 83); /*alloc fail*/
+
+    langtag[length] = 0;
+    for(i = 0; i != length; ++i) langtag[i] = (char)data[begin + i];
+
+    /*read the transkey*/
+    begin += length + 1;
+    length = 0;
+    for(i = begin; i < chunkLength && data[i] != 0; ++i) ++length;
+
+    transkey = (char*)lodepng_malloc(length + 1);
+    if(!transkey) CERROR_BREAK(error, 83); /*alloc fail*/
+
+    transkey[length] = 0;
+    for(i = 0; i != length; ++i) transkey[i] = (char)data[begin + i];
+
+    /*read the actual text*/
+    begin += length + 1;
+
+    length = chunkLength < begin ? 0 : chunkLength - begin;
+
+    if(compressed)
+    {
+      /*will fail if zlib error, e.g. if length is too small*/
+      error = zlib_decompress(&decoded.data, &decoded.size,
+                              (unsigned char*)(&data[begin]),
+                              length, zlibsettings);
+      if(error) break;
+      if(decoded.allocsize < decoded.size) decoded.allocsize = decoded.size;
+      ucvector_push_back(&decoded, 0);
+    }
+    else
+    {
+      if(!ucvector_resize(&decoded, length + 1)) CERROR_BREAK(error, 83 /*alloc fail*/);
+
+      decoded.data[length] = 0;
+      for(i = 0; i != length; ++i) decoded.data[i] = data[begin + i];
+    }
+
+    error = lodepng_add_itext(info, key, langtag, transkey, (char*)decoded.data);
+
+    break;
+  }
+
+  lodepng_free(key);
+  lodepng_free(langtag);
+  lodepng_free(transkey);
+  ucvector_cleanup(&decoded);
+
+  return error;
+}
+
+static unsigned readChunk_tIME(LodePNGInfo* info, const unsigned char* data, size_t chunkLength)
+{
+  if(chunkLength != 7) return 73; /*invalid tIME chunk size*/
+
+  info->time_defined = 1;
+  info->time.year = 256u * data[0] + data[1];
+  info->time.month = data[2];
+  info->time.day = data[3];
+  info->time.hour = data[4];
+  info->time.minute = data[5];
+  info->time.second = data[6];
+
+  return 0; /* OK */
+}
+
+static unsigned readChunk_pHYs(LodePNGInfo* info, const unsigned char* data, size_t chunkLength)
+{
+  if(chunkLength != 9) return 74; /*invalid pHYs chunk size*/
+
+  info->phys_defined = 1;
+  info->phys_x = 16777216u * data[0] + 65536u * data[1] + 256u * data[2] + data[3];
+  info->phys_y = 16777216u * data[4] + 65536u * data[5] + 256u * data[6] + data[7];
+  info->phys_unit = data[8];
+
+  return 0; /* OK */
+}
+#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
+
+/*read a PNG, the result will be in the same color type as the PNG (hence "generic")*/
+static void decodeGeneric(unsigned char** out, unsigned* w, unsigned* h,
+                          LodePNGState* state,
+                          const unsigned char* in, size_t insize)
+{
+  unsigned char IEND = 0;
+  const unsigned char* chunk;
+  size_t i;
+  ucvector idat; /*the data from idat chunks*/
+  ucvector scanlines;
+  size_t predict;
+  size_t numpixels;
+  size_t outsize = 0;
+
+  /*for unknown chunk order*/
+  unsigned unknown = 0;
+#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
+  unsigned critical_pos = 1; /*1 = after IHDR, 2 = after PLTE, 3 = after IDAT*/
+#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
+
+  /*provide some proper output values if error will happen*/
+  *out = 0;
+
+  state->error = lodepng_inspect(w, h, state, in, insize); /*reads header and resets other parameters in state->info_png*/
+  if(state->error) return;
+
+  numpixels = *w * *h;
+
+  /*multiplication overflow*/
+  if(*h != 0 && numpixels / *h != *w) CERROR_RETURN(state->error, 92);
+  /*multiplication overflow possible further below. Allows up to 2^31-1 pixel
+  bytes with 16-bit RGBA, the rest is room for filter bytes.*/
+  if(numpixels > 268435455) CERROR_RETURN(state->error, 92);
+
+  ucvector_init(&idat);
+  chunk = &in[33]; /*first byte of the first chunk after the header*/
+
+  /*loop through the chunks, ignoring unknown chunks and stopping at IEND chunk.
+  IDAT data is put at the start of the in buffer*/
+  while(!IEND && !state->error)
+  {
+    unsigned chunkLength;
+    const unsigned char* data; /*the data in the chunk*/
+
+    /*error: size of the in buffer too small to contain next chunk*/
+    if((size_t)((chunk - in) + 12) > insize || chunk < in) CERROR_BREAK(state->error, 30);
+
+    /*length of the data of the chunk, excluding the length bytes, chunk type and CRC bytes*/
+    chunkLength = lodepng_chunk_length(chunk);
+    /*error: chunk length larger than the max PNG chunk size*/
+    if(chunkLength > 2147483647) CERROR_BREAK(state->error, 63);
+
+    if((size_t)((chunk - in) + chunkLength + 12) > insize || (chunk + chunkLength + 12) < in)
+    {
+      CERROR_BREAK(state->error, 64); /*error: size of the in buffer too small to contain next chunk*/
+    }
+
+    data = lodepng_chunk_data_const(chunk);
+
+    /*IDAT chunk, containing compressed image data*/
+    if(lodepng_chunk_type_equals(chunk, "IDAT"))
+    {
+      size_t oldsize = idat.size;
+      if(!ucvector_resize(&idat, oldsize + chunkLength)) CERROR_BREAK(state->error, 83 /*alloc fail*/);
+      for(i = 0; i != chunkLength; ++i) idat.data[oldsize + i] = data[i];
+#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
+      critical_pos = 3;
+#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
+    }
+    /*IEND chunk*/
+    else if(lodepng_chunk_type_equals(chunk, "IEND"))
+    {
+      IEND = 1;
+    }
+    /*palette chunk (PLTE)*/
+    else if(lodepng_chunk_type_equals(chunk, "PLTE"))
+    {
+      state->error = readChunk_PLTE(&state->info_png.color, data, chunkLength);
+      if(state->error) break;
+#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
+      critical_pos = 2;
+#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
+    }
+    /*palette transparency chunk (tRNS)*/
+    else if(lodepng_chunk_type_equals(chunk, "tRNS"))
+    {
+      state->error = readChunk_tRNS(&state->info_png.color, data, chunkLength);
+      if(state->error) break;
+    }
+#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
+    /*background color chunk (bKGD)*/
+    else if(lodepng_chunk_type_equals(chunk, "bKGD"))
+    {
+      state->error = readChunk_bKGD(&state->info_png, data, chunkLength);
+      if(state->error) break;
+    }
+    /*text chunk (tEXt)*/
+    else if(lodepng_chunk_type_equals(chunk, "tEXt"))
+    {
+      if(state->decoder.read_text_chunks)
+      {
+        state->error = readChunk_tEXt(&state->info_png, data, chunkLength);
+        if(state->error) break;
+      }
+    }
+    /*compressed text chunk (zTXt)*/
+    else if(lodepng_chunk_type_equals(chunk, "zTXt"))
+    {
+      if(state->decoder.read_text_chunks)
+      {
+        state->error = readChunk_zTXt(&state->info_png, &state->decoder.zlibsettings, data, chunkLength);
+        if(state->error) break;
+      }
+    }
+    /*international text chunk (iTXt)*/
+    else if(lodepng_chunk_type_equals(chunk, "iTXt"))
+    {
+      if(state->decoder.read_text_chunks)
+      {
+        state->error = readChunk_iTXt(&state->info_png, &state->decoder.zlibsettings, data, chunkLength);
+        if(state->error) break;
+      }
+    }
+    else if(lodepng_chunk_type_equals(chunk, "tIME"))
+    {
+      state->error = readChunk_tIME(&state->info_png, data, chunkLength);
+      if(state->error) break;
+    }
+    else if(lodepng_chunk_type_equals(chunk, "pHYs"))
+    {
+      state->error = readChunk_pHYs(&state->info_png, data, chunkLength);
+      if(state->error) break;
+    }
+#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
+    else /*it's not an implemented chunk type, so ignore it: skip over the data*/
+    {
+      /*error: unknown critical chunk (5th bit of first byte of chunk type is 0)*/
+      if(!lodepng_chunk_ancillary(chunk)) CERROR_BREAK(state->error, 69);
+
+      unknown = 1;
+#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
+      if(state->decoder.remember_unknown_chunks)
+      {
+        state->error = lodepng_chunk_append(&state->info_png.unknown_chunks_data[critical_pos - 1],
+                                            &state->info_png.unknown_chunks_size[critical_pos - 1], chunk);
+        if(state->error) break;
+      }
+#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
+    }
+
+    if(!state->decoder.ignore_crc && !unknown) /*check CRC if wanted, only on known chunk types*/
+    {
+      if(lodepng_chunk_check_crc(chunk)) CERROR_BREAK(state->error, 57); /*invalid CRC*/
+    }
+
+    if(!IEND) chunk = lodepng_chunk_next_const(chunk);
+  }
+
+  ucvector_init(&scanlines);
+  /*predict output size, to allocate exact size for output buffer to avoid more dynamic allocation.
+  If the decompressed size does not match the prediction, the image must be corrupt.*/
+  if(state->info_png.interlace_method == 0)
+  {
+    /*The extra *h is added because this are the filter bytes every scanline starts with*/
+    predict = lodepng_get_raw_size_idat(*w, *h, &state->info_png.color) + *h;
+  }
+  else
+  {
+    /*Adam-7 interlaced: predicted size is the sum of the 7 sub-images sizes*/
+    const LodePNGColorMode* color = &state->info_png.color;
+    predict = 0;
+    predict += lodepng_get_raw_size_idat((*w + 7) >> 3, (*h + 7) >> 3, color) + ((*h + 7) >> 3);
+    if(*w > 4) predict += lodepng_get_raw_size_idat((*w + 3) >> 3, (*h + 7) >> 3, color) + ((*h + 7) >> 3);
+    predict += lodepng_get_raw_size_idat((*w + 3) >> 2, (*h + 3) >> 3, color) + ((*h + 3) >> 3);
+    if(*w > 2) predict += lodepng_get_raw_size_idat((*w + 1) >> 2, (*h + 3) >> 2, color) + ((*h + 3) >> 2);
+    predict += lodepng_get_raw_size_idat((*w + 1) >> 1, (*h + 1) >> 2, color) + ((*h + 1) >> 2);
+    if(*w > 1) predict += lodepng_get_raw_size_idat((*w + 0) >> 1, (*h + 1) >> 1, color) + ((*h + 1) >> 1);
+    predict += lodepng_get_raw_size_idat((*w + 0), (*h + 0) >> 1, color) + ((*h + 0) >> 1);
+  }
+  if(!state->error && !ucvector_reserve(&scanlines, predict)) state->error = 83; /*alloc fail*/
+  if(!state->error)
+  {
+    state->error = zlib_decompress(&scanlines.data, &scanlines.size, idat.data,
+                                   idat.size, &state->decoder.zlibsettings);
+    if(!state->error && scanlines.size != predict) state->error = 91; /*decompressed size doesn't match prediction*/
+  }
+  ucvector_cleanup(&idat);
+
+  if(!state->error)
+  {
+    outsize = lodepng_get_raw_size(*w, *h, &state->info_png.color);
+    *out = (unsigned char*)lodepng_malloc(outsize);
+    if(!*out) state->error = 83; /*alloc fail*/
+  }
+  if(!state->error)
+  {
+    for(i = 0; i < outsize; i++) (*out)[i] = 0;
+    state->error = postProcessScanlines(*out, scanlines.data, *w, *h, &state->info_png);
+  }
+  ucvector_cleanup(&scanlines);
+}
+
+unsigned lodepng_decode(unsigned char** out, unsigned* w, unsigned* h,
+                        LodePNGState* state,
+                        const unsigned char* in, size_t insize)
+{
+  *out = 0;
+  decodeGeneric(out, w, h, state, in, insize);
+  if(state->error) return state->error;
+  if(!state->decoder.color_convert || lodepng_color_mode_equal(&state->info_raw, &state->info_png.color))
+  {
+    /*same color type, no copying or converting of data needed*/
+    /*store the info_png color settings on the info_raw so that the info_raw still reflects what colortype
+    the raw image has to the end user*/
+    if(!state->decoder.color_convert)
+    {
+      state->error = lodepng_color_mode_copy(&state->info_raw, &state->info_png.color);
+      if(state->error) return state->error;
+    }
+  }
+  else
+  {
+    /*color conversion needed; sort of copy of the data*/
+    unsigned char* data = *out;
+    size_t outsize;
+
+    /*TODO: check if this works according to the statement in the documentation: "The converter can convert
+    from greyscale input color type, to 8-bit greyscale or greyscale with alpha"*/
+    if(!(state->info_raw.colortype == LCT_RGB || state->info_raw.colortype == LCT_RGBA)
+       && !(state->info_raw.bitdepth == 8))
+    {
+      return 56; /*unsupported color mode conversion*/
+    }
+
+    outsize = lodepng_get_raw_size(*w, *h, &state->info_raw);
+    *out = (unsigned char*)lodepng_malloc(outsize);
+    if(!(*out))
+    {
+      state->error = 83; /*alloc fail*/
+    }
+    else state->error = lodepng_convert(*out, data, &state->info_raw,
+                                        &state->info_png.color, *w, *h);
+    lodepng_free(data);
+  }
+  return state->error;
+}
+
+unsigned lodepng_decode_memory(unsigned char** out, unsigned* w, unsigned* h, const unsigned char* in,
+                               size_t insize, LodePNGColorType colortype, unsigned bitdepth)
+{
+  unsigned error;
+  LodePNGState state;
+  lodepng_state_init(&state);
+  state.info_raw.colortype = colortype;
+  state.info_raw.bitdepth = bitdepth;
+  error = lodepng_decode(out, w, h, &state, in, insize);
+  lodepng_state_cleanup(&state);
+  return error;
+}
+
+unsigned lodepng_decode32(unsigned char** out, unsigned* w, unsigned* h, const unsigned char* in, size_t insize)
+{
+  return lodepng_decode_memory(out, w, h, in, insize, LCT_RGBA, 8);
+}
+
+unsigned lodepng_decode24(unsigned char** out, unsigned* w, unsigned* h, const unsigned char* in, size_t insize)
+{
+  return lodepng_decode_memory(out, w, h, in, insize, LCT_RGB, 8);
+}
+
+#ifdef LODEPNG_COMPILE_DISK
+unsigned lodepng_decode_file(unsigned char** out, unsigned* w, unsigned* h, const char* filename,
+                             LodePNGColorType colortype, unsigned bitdepth)
+{
+  unsigned char* buffer = 0;
+  size_t buffersize;
+  unsigned error;
+  error = lodepng_load_file(&buffer, &buffersize, filename);
+  if(!error) error = lodepng_decode_memory(out, w, h, buffer, buffersize, colortype, bitdepth);
+  lodepng_free(buffer);
+  return error;
+}
+
+unsigned lodepng_decode32_file(unsigned char** out, unsigned* w, unsigned* h, const char* filename)
+{
+  return lodepng_decode_file(out, w, h, filename, LCT_RGBA, 8);
+}
+
+unsigned lodepng_decode24_file(unsigned char** out, unsigned* w, unsigned* h, const char* filename)
+{
+  return lodepng_decode_file(out, w, h, filename, LCT_RGB, 8);
+}
+#endif /*LODEPNG_COMPILE_DISK*/
+
+void lodepng_decoder_settings_init(LodePNGDecoderSettings* settings)
+{
+  settings->color_convert = 1;
+#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
+  settings->read_text_chunks = 1;
+  settings->remember_unknown_chunks = 0;
+#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
+  settings->ignore_crc = 0;
+  lodepng_decompress_settings_init(&settings->zlibsettings);
+}
+
+#endif /*LODEPNG_COMPILE_DECODER*/
+
+#if defined(LODEPNG_COMPILE_DECODER) || defined(LODEPNG_COMPILE_ENCODER)
+
+void lodepng_state_init(LodePNGState* state)
+{
+#ifdef LODEPNG_COMPILE_DECODER
+  lodepng_decoder_settings_init(&state->decoder);
+#endif /*LODEPNG_COMPILE_DECODER*/
+#ifdef LODEPNG_COMPILE_ENCODER
+  lodepng_encoder_settings_init(&state->encoder);
+#endif /*LODEPNG_COMPILE_ENCODER*/
+  lodepng_color_mode_init(&state->info_raw);
+  lodepng_info_init(&state->info_png);
+  state->error = 1;
+}
+
+void lodepng_state_cleanup(LodePNGState* state)
+{
+  lodepng_color_mode_cleanup(&state->info_raw);
+  lodepng_info_cleanup(&state->info_png);
+}
+
+void lodepng_state_copy(LodePNGState* dest, const LodePNGState* source)
+{
+  lodepng_state_cleanup(dest);
+  *dest = *source;
+  lodepng_color_mode_init(&dest->info_raw);
+  lodepng_info_init(&dest->info_png);
+  dest->error = lodepng_color_mode_copy(&dest->info_raw, &source->info_raw); if(dest->error) return;
+  dest->error = lodepng_info_copy(&dest->info_png, &source->info_png); if(dest->error) return;
+}
+
+#endif /* defined(LODEPNG_COMPILE_DECODER) || defined(LODEPNG_COMPILE_ENCODER) */
+
+#ifdef LODEPNG_COMPILE_ENCODER
+
+/* ////////////////////////////////////////////////////////////////////////// */
+/* / PNG Encoder                                                            / */
+/* ////////////////////////////////////////////////////////////////////////// */
+
+/*chunkName must be string of 4 characters*/
+static unsigned addChunk(ucvector* out, const char* chunkName, const unsigned char* data, size_t length)
+{
+  CERROR_TRY_RETURN(lodepng_chunk_create(&out->data, &out->size, (unsigned)length, chunkName, data));
+  out->allocsize = out->size; /*fix the allocsize again*/
+  return 0;
+}
+
+static void writeSignature(ucvector* out)
+{
+  /*8 bytes PNG signature, aka the magic bytes*/
+  ucvector_push_back(out, 137);
+  ucvector_push_back(out, 80);
+  ucvector_push_back(out, 78);
+  ucvector_push_back(out, 71);
+  ucvector_push_back(out, 13);
+  ucvector_push_back(out, 10);
+  ucvector_push_back(out, 26);
+  ucvector_push_back(out, 10);
+}
+
+static unsigned addChunk_IHDR(ucvector* out, unsigned w, unsigned h,
+                              LodePNGColorType colortype, unsigned bitdepth, unsigned interlace_method)
+{
+  unsigned error = 0;
+  ucvector header;
+  ucvector_init(&header);
+
+  lodepng_add32bitInt(&header, w); /*width*/
+  lodepng_add32bitInt(&header, h); /*height*/
+  ucvector_push_back(&header, (unsigned char)bitdepth); /*bit depth*/
+  ucvector_push_back(&header, (unsigned char)colortype); /*color type*/
+  ucvector_push_back(&header, 0); /*compression method*/
+  ucvector_push_back(&header, 0); /*filter method*/
+  ucvector_push_back(&header, interlace_method); /*interlace method*/
+
+  error = addChunk(out, "IHDR", header.data, header.size);
+  ucvector_cleanup(&header);
+
+  return error;
+}
+
+static unsigned addChunk_PLTE(ucvector* out, const LodePNGColorMode* info)
+{
+  unsigned error = 0;
+  size_t i;
+  ucvector PLTE;
+  ucvector_init(&PLTE);
+  for(i = 0; i != info->palettesize * 4; ++i)
+  {
+    /*add all channels except alpha channel*/
+    if(i % 4 != 3) ucvector_push_back(&PLTE, info->palette[i]);
+  }
+  error = addChunk(out, "PLTE", PLTE.data, PLTE.size);
+  ucvector_cleanup(&PLTE);
+
+  return error;
+}
+
+static unsigned addChunk_tRNS(ucvector* out, const LodePNGColorMode* info)
+{
+  unsigned error = 0;
+  size_t i;
+  ucvector tRNS;
+  ucvector_init(&tRNS);
+  if(info->colortype == LCT_PALETTE)
+  {
+    size_t amount = info->palettesize;
+    /*the tail of palette values that all have 255 as alpha, does not have to be encoded*/
+    for(i = info->palettesize; i != 0; --i)
+    {
+      if(info->palette[4 * (i - 1) + 3] == 255) --amount;
+      else break;
+    }
+    /*add only alpha channel*/
+    for(i = 0; i != amount; ++i) ucvector_push_back(&tRNS, info->palette[4 * i + 3]);
+  }
+  else if(info->colortype == LCT_GREY)
+  {
+    if(info->key_defined)
+    {
+      ucvector_push_back(&tRNS, (unsigned char)(info->key_r >> 8));
+      ucvector_push_back(&tRNS, (unsigned char)(info->key_r & 255));
+    }
+  }
+  else if(info->colortype == LCT_RGB)
+  {
+    if(info->key_defined)
+    {
+      ucvector_push_back(&tRNS, (unsigned char)(info->key_r >> 8));
+      ucvector_push_back(&tRNS, (unsigned char)(info->key_r & 255));
+      ucvector_push_back(&tRNS, (unsigned char)(info->key_g >> 8));
+      ucvector_push_back(&tRNS, (unsigned char)(info->key_g & 255));
+      ucvector_push_back(&tRNS, (unsigned char)(info->key_b >> 8));
+      ucvector_push_back(&tRNS, (unsigned char)(info->key_b & 255));
+    }
+  }
+
+  error = addChunk(out, "tRNS", tRNS.data, tRNS.size);
+  ucvector_cleanup(&tRNS);
+
+  return error;
+}
+
+static unsigned addChunk_IDAT(ucvector* out, const unsigned char* data, size_t datasize,
+                              LodePNGCompressSettings* zlibsettings)
+{
+  ucvector zlibdata;
+  unsigned error = 0;
+
+  /*compress with the Zlib compressor*/
+  ucvector_init(&zlibdata);
+  error = zlib_compress(&zlibdata.data, &zlibdata.size, data, datasize, zlibsettings);
+  if(!error) error = addChunk(out, "IDAT", zlibdata.data, zlibdata.size);
+  ucvector_cleanup(&zlibdata);
+
+  return error;
+}
+
+static unsigned addChunk_IEND(ucvector* out)
+{
+  unsigned error = 0;
+  error = addChunk(out, "IEND", 0, 0);
+  return error;
+}
+
+#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
+
+static unsigned addChunk_tEXt(ucvector* out, const char* keyword, const char* textstring)
+{
+  unsigned error = 0;
+  size_t i;
+  ucvector text;
+  ucvector_init(&text);
+  for(i = 0; keyword[i] != 0; ++i) ucvector_push_back(&text, (unsigned char)keyword[i]);
+  if(i < 1 || i > 79) return 89; /*error: invalid keyword size*/
+  ucvector_push_back(&text, 0); /*0 termination char*/
+  for(i = 0; textstring[i] != 0; ++i) ucvector_push_back(&text, (unsigned char)textstring[i]);
+  error = addChunk(out, "tEXt", text.data, text.size);
+  ucvector_cleanup(&text);
+
+  return error;
+}
+
+static unsigned addChunk_zTXt(ucvector* out, const char* keyword, const char* textstring,
+                              LodePNGCompressSettings* zlibsettings)
+{
+  unsigned error = 0;
+  ucvector data, compressed;
+  size_t i, textsize = strlen(textstring);
+
+  ucvector_init(&data);
+  ucvector_init(&compressed);
+  for(i = 0; keyword[i] != 0; ++i) ucvector_push_back(&data, (unsigned char)keyword[i]);
+  if(i < 1 || i > 79) return 89; /*error: invalid keyword size*/
+  ucvector_push_back(&data, 0); /*0 termination char*/
+  ucvector_push_back(&data, 0); /*compression method: 0*/
+
+  error = zlib_compress(&compressed.data, &compressed.size,
+                        (unsigned char*)textstring, textsize, zlibsettings);
+  if(!error)
+  {
+    for(i = 0; i != compressed.size; ++i) ucvector_push_back(&data, compressed.data[i]);
+    error = addChunk(out, "zTXt", data.data, data.size);
+  }
+
+  ucvector_cleanup(&compressed);
+  ucvector_cleanup(&data);
+  return error;
+}
+
+static unsigned addChunk_iTXt(ucvector* out, unsigned compressed, const char* keyword, const char* langtag,
+                              const char* transkey, const char* textstring, LodePNGCompressSettings* zlibsettings)
+{
+  unsigned error = 0;
+  ucvector data;
+  size_t i, textsize = strlen(textstring);
+
+  ucvector_init(&data);
+
+  for(i = 0; keyword[i] != 0; ++i) ucvector_push_back(&data, (unsigned char)keyword[i]);
+  if(i < 1 || i > 79) return 89; /*error: invalid keyword size*/
+  ucvector_push_back(&data, 0); /*null termination char*/
+  ucvector_push_back(&data, compressed ? 1 : 0); /*compression flag*/
+  ucvector_push_back(&data, 0); /*compression method*/
+  for(i = 0; langtag[i] != 0; ++i) ucvector_push_back(&data, (unsigned char)langtag[i]);
+  ucvector_push_back(&data, 0); /*null termination char*/
+  for(i = 0; transkey[i] != 0; ++i) ucvector_push_back(&data, (unsigned char)transkey[i]);
+  ucvector_push_back(&data, 0); /*null termination char*/
+
+  if(compressed)
+  {
+    ucvector compressed_data;
+    ucvector_init(&compressed_data);
+    error = zlib_compress(&compressed_data.data, &compressed_data.size,
+                          (unsigned char*)textstring, textsize, zlibsettings);
+    if(!error)
+    {
+      for(i = 0; i != compressed_data.size; ++i) ucvector_push_back(&data, compressed_data.data[i]);
+    }
+    ucvector_cleanup(&compressed_data);
+  }
+  else /*not compressed*/
+  {
+    for(i = 0; textstring[i] != 0; ++i) ucvector_push_back(&data, (unsigned char)textstring[i]);
+  }
+
+  if(!error) error = addChunk(out, "iTXt", data.data, data.size);
+  ucvector_cleanup(&data);
+  return error;
+}
+
+static unsigned addChunk_bKGD(ucvector* out, const LodePNGInfo* info)
+{
+  unsigned error = 0;
+  ucvector bKGD;
+  ucvector_init(&bKGD);
+  if(info->color.colortype == LCT_GREY || info->color.colortype == LCT_GREY_ALPHA)
+  {
+    ucvector_push_back(&bKGD, (unsigned char)(info->background_r >> 8));
+    ucvector_push_back(&bKGD, (unsigned char)(info->background_r & 255));
+  }
+  else if(info->color.colortype == LCT_RGB || info->color.colortype == LCT_RGBA)
+  {
+    ucvector_push_back(&bKGD, (unsigned char)(info->background_r >> 8));
+    ucvector_push_back(&bKGD, (unsigned char)(info->background_r & 255));
+    ucvector_push_back(&bKGD, (unsigned char)(info->background_g >> 8));
+    ucvector_push_back(&bKGD, (unsigned char)(info->background_g & 255));
+    ucvector_push_back(&bKGD, (unsigned char)(info->background_b >> 8));
+    ucvector_push_back(&bKGD, (unsigned char)(info->background_b & 255));
+  }
+  else if(info->color.colortype == LCT_PALETTE)
+  {
+    ucvector_push_back(&bKGD, (unsigned char)(info->background_r & 255)); /*palette index*/
+  }
+
+  error = addChunk(out, "bKGD", bKGD.data, bKGD.size);
+  ucvector_cleanup(&bKGD);
+
+  return error;
+}
+
+static unsigned addChunk_tIME(ucvector* out, const LodePNGTime* time)
+{
+  unsigned error = 0;
+  unsigned char* data = (unsigned char*)lodepng_malloc(7);
+  if(!data) return 83; /*alloc fail*/
+  data[0] = (unsigned char)(time->year >> 8);
+  data[1] = (unsigned char)(time->year & 255);
+  data[2] = (unsigned char)time->month;
+  data[3] = (unsigned char)time->day;
+  data[4] = (unsigned char)time->hour;
+  data[5] = (unsigned char)time->minute;
+  data[6] = (unsigned char)time->second;
+  error = addChunk(out, "tIME", data, 7);
+  lodepng_free(data);
+  return error;
+}
+
+static unsigned addChunk_pHYs(ucvector* out, const LodePNGInfo* info)
+{
+  unsigned error = 0;
+  ucvector data;
+  ucvector_init(&data);
+
+  lodepng_add32bitInt(&data, info->phys_x);
+  lodepng_add32bitInt(&data, info->phys_y);
+  ucvector_push_back(&data, info->phys_unit);
+
+  error = addChunk(out, "pHYs", data.data, data.size);
+  ucvector_cleanup(&data);
+
+  return error;
+}
+
+#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
+
+static void filterScanline(unsigned char* out, const unsigned char* scanline, const unsigned char* prevline,
+                           size_t length, size_t bytewidth, unsigned char filterType)
+{
+  size_t i;
+  switch(filterType)
+  {
+    case 0: /*None*/
+      for(i = 0; i != length; ++i) out[i] = scanline[i];
+      break;
+    case 1: /*Sub*/
+      for(i = 0; i != bytewidth; ++i) out[i] = scanline[i];
+      for(i = bytewidth; i < length; ++i) out[i] = scanline[i] - scanline[i - bytewidth];
+      break;
+    case 2: /*Up*/
+      if(prevline)
+      {
+        for(i = 0; i != length; ++i) out[i] = scanline[i] - prevline[i];
+      }
+      else
+      {
+        for(i = 0; i != length; ++i) out[i] = scanline[i];
+      }
+      break;
+    case 3: /*Average*/
+      if(prevline)
+      {
+        for(i = 0; i != bytewidth; ++i) out[i] = scanline[i] - (prevline[i] >> 1);
+        for(i = bytewidth; i < length; ++i) out[i] = scanline[i] - ((scanline[i - bytewidth] + prevline[i]) >> 1);
+      }
+      else
+      {
+        for(i = 0; i != bytewidth; ++i) out[i] = scanline[i];
+        for(i = bytewidth; i < length; ++i) out[i] = scanline[i] - (scanline[i - bytewidth] >> 1);
+      }
+      break;
+    case 4: /*Paeth*/
+      if(prevline)
+      {
+        /*paethPredictor(0, prevline[i], 0) is always prevline[i]*/
+        for(i = 0; i != bytewidth; ++i) out[i] = (scanline[i] - prevline[i]);
+        for(i = bytewidth; i < length; ++i)
+        {
+          out[i] = (scanline[i] - paethPredictor(scanline[i - bytewidth], prevline[i], prevline[i - bytewidth]));
+        }
+      }
+      else
+      {
+        for(i = 0; i != bytewidth; ++i) out[i] = scanline[i];
+        /*paethPredictor(scanline[i - bytewidth], 0, 0) is always scanline[i - bytewidth]*/
+        for(i = bytewidth; i < length; ++i) out[i] = (scanline[i] - scanline[i - bytewidth]);
+      }
+      break;
+    default: return; /*unexisting filter type given*/
+  }
+}
+
+/* log2 approximation. A slight bit faster than std::log. */
+static float flog2(float f)
+{
+  float result = 0;
+  while(f > 32) { result += 4; f /= 16; }
+  while(f > 2) { ++result; f /= 2; }
+  return result + 1.442695f * (f * f * f / 3 - 3 * f * f / 2 + 3 * f - 1.83333f);
+}
+
+static unsigned filter(unsigned char* out, const unsigned char* in, unsigned w, unsigned h,
+                       const LodePNGColorMode* info, const LodePNGEncoderSettings* settings)
+{
+  /*
+  For PNG filter method 0
+  out must be a buffer with as size: h + (w * h * bpp + 7) / 8, because there are
+  the scanlines with 1 extra byte per scanline
+  */
+
+  unsigned bpp = lodepng_get_bpp(info);
+  /*the width of a scanline in bytes, not including the filter type*/
+  size_t linebytes = (w * bpp + 7) / 8;
+  /*bytewidth is used for filtering, is 1 when bpp < 8, number of bytes per pixel otherwise*/
+  size_t bytewidth = (bpp + 7) / 8;
+  const unsigned char* prevline = 0;
+  unsigned x, y;
+  unsigned error = 0;
+  LodePNGFilterStrategy strategy = settings->filter_strategy;
+
+  /*
+  There is a heuristic called the minimum sum of absolute differences heuristic, suggested by the PNG standard:
+   *  If the image type is Palette, or the bit depth is smaller than 8, then do not filter the image (i.e.
+      use fixed filtering, with the filter None).
+   * (The other case) If the image type is Grayscale or RGB (with or without Alpha), and the bit depth is
+     not smaller than 8, then use adaptive filtering heuristic as follows: independently for each row, apply
+     all five filters and select the filter that produces the smallest sum of absolute values per row.
+  This heuristic is used if filter strategy is LFS_MINSUM and filter_palette_zero is true.
+
+  If filter_palette_zero is true and filter_strategy is not LFS_MINSUM, the above heuristic is followed,
+  but for "the other case", whatever strategy filter_strategy is set to instead of the minimum sum
+  heuristic is used.
+  */
+  if(settings->filter_palette_zero &&
+     (info->colortype == LCT_PALETTE || info->bitdepth < 8)) strategy = LFS_ZERO;
+
+  if(bpp == 0) return 31; /*error: invalid color type*/
+
+  if(strategy == LFS_ZERO)
+  {
+    for(y = 0; y != h; ++y)
+    {
+      size_t outindex = (1 + linebytes) * y; /*the extra filterbyte added to each row*/
+      size_t inindex = linebytes * y;
+      out[outindex] = 0; /*filter type byte*/
+      filterScanline(&out[outindex + 1], &in[inindex], prevline, linebytes, bytewidth, 0);
+      prevline = &in[inindex];
+    }
+  }
+  else if(strategy == LFS_MINSUM)
+  {
+    /*adaptive filtering*/
+    size_t sum[5];
+    unsigned char* attempt[5]; /*five filtering attempts, one for each filter type*/
+    size_t smallest = 0;
+    unsigned char type, bestType = 0;
+
+    for(type = 0; type != 5; ++type)
+    {
+      attempt[type] = (unsigned char*)lodepng_malloc(linebytes);
+      if(!attempt[type]) return 83; /*alloc fail*/
+    }
+
+    if(!error)
+    {
+      for(y = 0; y != h; ++y)
+      {
+        /*try the 5 filter types*/
+        for(type = 0; type != 5; ++type)
+        {
+          filterScanline(attempt[type], &in[y * linebytes], prevline, linebytes, bytewidth, type);
+
+          /*calculate the sum of the result*/
+          sum[type] = 0;
+          if(type == 0)
+          {
+            for(x = 0; x != linebytes; ++x) sum[type] += (unsigned char)(attempt[type][x]);
+          }
+          else
+          {
+            for(x = 0; x != linebytes; ++x)
+            {
+              /*For differences, each byte should be treated as signed, values above 127 are negative
+              (converted to signed char). Filtertype 0 isn't a difference though, so use unsigned there.
+              This means filtertype 0 is almost never chosen, but that is justified.*/
+              unsigned char s = attempt[type][x];
+              sum[type] += s < 128 ? s : (255U - s);
+            }
+          }
+
+          /*check if this is smallest sum (or if type == 0 it's the first case so always store the values)*/
+          if(type == 0 || sum[type] < smallest)
+          {
+            bestType = type;
+            smallest = sum[type];
+          }
+        }
+
+        prevline = &in[y * linebytes];
+
+        /*now fill the out values*/
+        out[y * (linebytes + 1)] = bestType; /*the first byte of a scanline will be the filter type*/
+        for(x = 0; x != linebytes; ++x) out[y * (linebytes + 1) + 1 + x] = attempt[bestType][x];
+      }
+    }
+
+    for(type = 0; type != 5; ++type) lodepng_free(attempt[type]);
+  }
+  else if(strategy == LFS_ENTROPY)
+  {
+    float sum[5];
+    unsigned char* attempt[5]; /*five filtering attempts, one for each filter type*/
+    float smallest = 0;
+    unsigned type, bestType = 0;
+    unsigned count[256];
+
+    for(type = 0; type != 5; ++type)
+    {
+      attempt[type] = (unsigned char*)lodepng_malloc(linebytes);
+      if(!attempt[type]) return 83; /*alloc fail*/
+    }
+
+    for(y = 0; y != h; ++y)
+    {
+      /*try the 5 filter types*/
+      for(type = 0; type != 5; ++type)
+      {
+        filterScanline(attempt[type], &in[y * linebytes], prevline, linebytes, bytewidth, type);
+        for(x = 0; x != 256; ++x) count[x] = 0;
+        for(x = 0; x != linebytes; ++x) ++count[attempt[type][x]];
+        ++count[type]; /*the filter type itself is part of the scanline*/
+        sum[type] = 0;
+        for(x = 0; x != 256; ++x)
+        {
+          float p = count[x] / (float)(linebytes + 1);
+          sum[type] += count[x] == 0 ? 0 : flog2(1 / p) * p;
+        }
+        /*check if this is smallest sum (or if type == 0 it's the first case so always store the values)*/
+        if(type == 0 || sum[type] < smallest)
+        {
+          bestType = type;
+          smallest = sum[type];
+        }
+      }
+
+      prevline = &in[y * linebytes];
+
+      /*now fill the out values*/
+      out[y * (linebytes + 1)] = bestType; /*the first byte of a scanline will be the filter type*/
+      for(x = 0; x != linebytes; ++x) out[y * (linebytes + 1) + 1 + x] = attempt[bestType][x];
+    }
+
+    for(type = 0; type != 5; ++type) lodepng_free(attempt[type]);
+  }
+  else if(strategy == LFS_PREDEFINED)
+  {
+    for(y = 0; y != h; ++y)
+    {
+      size_t outindex = (1 + linebytes) * y; /*the extra filterbyte added to each row*/
+      size_t inindex = linebytes * y;
+      unsigned char type = settings->predefined_filters[y];
+      out[outindex] = type; /*filter type byte*/
+      filterScanline(&out[outindex + 1], &in[inindex], prevline, linebytes, bytewidth, type);
+      prevline = &in[inindex];
+    }
+  }
+  else if(strategy == LFS_BRUTE_FORCE)
+  {
+    /*brute force filter chooser.
+    deflate the scanline after every filter attempt to see which one deflates best.
+    This is very slow and gives only slightly smaller, sometimes even larger, result*/
+    size_t size[5];
+    unsigned char* attempt[5]; /*five filtering attempts, one for each filter type*/
+    size_t smallest = 0;
+    unsigned type = 0, bestType = 0;
+    unsigned char* dummy;
+    LodePNGCompressSettings zlibsettings = settings->zlibsettings;
+    /*use fixed tree on the attempts so that the tree is not adapted to the filtertype on purpose,
+    to simulate the true case where the tree is the same for the whole image. Sometimes it gives
+    better result with dynamic tree anyway. Using the fixed tree sometimes gives worse, but in rare
+    cases better compression. It does make this a bit less slow, so it's worth doing this.*/
+    zlibsettings.btype = 1;
+    /*a custom encoder likely doesn't read the btype setting and is optimized for complete PNG
+    images only, so disable it*/
+    zlibsettings.custom_zlib = 0;
+    zlibsettings.custom_deflate = 0;
+    for(type = 0; type != 5; ++type)
+    {
+      attempt[type] = (unsigned char*)lodepng_malloc(linebytes);
+      if(!attempt[type]) return 83; /*alloc fail*/
+    }
+    for(y = 0; y != h; ++y) /*try the 5 filter types*/
+    {
+      for(type = 0; type != 5; ++type)
+      {
+        unsigned testsize = linebytes;
+        /*if(testsize > 8) testsize /= 8;*/ /*it already works good enough by testing a part of the row*/
+
+        filterScanline(attempt[type], &in[y * linebytes], prevline, linebytes, bytewidth, type);
+        size[type] = 0;
+        dummy = 0;
+        zlib_compress(&dummy, &size[type], attempt[type], testsize, &zlibsettings);
+        lodepng_free(dummy);
+        /*check if this is smallest size (or if type == 0 it's the first case so always store the values)*/
+        if(type == 0 || size[type] < smallest)
+        {
+          bestType = type;
+          smallest = size[type];
+        }
+      }
+      prevline = &in[y * linebytes];
+      out[y * (linebytes + 1)] = bestType; /*the first byte of a scanline will be the filter type*/
+      for(x = 0; x != linebytes; ++x) out[y * (linebytes + 1) + 1 + x] = attempt[bestType][x];
+    }
+    for(type = 0; type != 5; ++type) lodepng_free(attempt[type]);
+  }
+  else return 88; /* unknown filter strategy */
+
+  return error;
+}
+
+static void addPaddingBits(unsigned char* out, const unsigned char* in,
+                           size_t olinebits, size_t ilinebits, unsigned h)
+{
+  /*The opposite of the removePaddingBits function
+  olinebits must be >= ilinebits*/
+  unsigned y;
+  size_t diff = olinebits - ilinebits;
+  size_t obp = 0, ibp = 0; /*bit pointers*/
+  for(y = 0; y != h; ++y)
+  {
+    size_t x;
+    for(x = 0; x < ilinebits; ++x)
+    {
+      unsigned char bit = readBitFromReversedStream(&ibp, in);
+      setBitOfReversedStream(&obp, out, bit);
+    }
+    /*obp += diff; --> no, fill in some value in the padding bits too, to avoid
+    "Use of uninitialised value of size ###" warning from valgrind*/
+    for(x = 0; x != diff; ++x) setBitOfReversedStream(&obp, out, 0);
+  }
+}
+
+/*
+in: non-interlaced image with size w*h
+out: the same pixels, but re-ordered according to PNG's Adam7 interlacing, with
+ no padding bits between scanlines, but between reduced images so that each
+ reduced image starts at a byte.
+bpp: bits per pixel
+there are no padding bits, not between scanlines, not between reduced images
+in has the following size in bits: w * h * bpp.
+out is possibly bigger due to padding bits between reduced images
+NOTE: comments about padding bits are only relevant if bpp < 8
+*/
+static void Adam7_interlace(unsigned char* out, const unsigned char* in, unsigned w, unsigned h, unsigned bpp)
+{
+  unsigned passw[7], passh[7];
+  size_t filter_passstart[8], padded_passstart[8], passstart[8];
+  unsigned i;
+
+  Adam7_getpassvalues(passw, passh, filter_passstart, padded_passstart, passstart, w, h, bpp);
+
+  if(bpp >= 8)
+  {
+    for(i = 0; i != 7; ++i)
+    {
+      unsigned x, y, b;
+      size_t bytewidth = bpp / 8;
+      for(y = 0; y < passh[i]; ++y)
+      for(x = 0; x < passw[i]; ++x)
+      {
+        size_t pixelinstart = ((ADAM7_IY[i] + y * ADAM7_DY[i]) * w + ADAM7_IX[i] + x * ADAM7_DX[i]) * bytewidth;
+        size_t pixeloutstart = passstart[i] + (y * passw[i] + x) * bytewidth;
+        for(b = 0; b < bytewidth; ++b)
+        {
+          out[pixeloutstart + b] = in[pixelinstart + b];
+        }
+      }
+    }
+  }
+  else /*bpp < 8: Adam7 with pixels < 8 bit is a bit trickier: with bit pointers*/
+  {
+    for(i = 0; i != 7; ++i)
+    {
+      unsigned x, y, b;
+      unsigned ilinebits = bpp * passw[i];
+      unsigned olinebits = bpp * w;
+      size_t obp, ibp; /*bit pointers (for out and in buffer)*/
+      for(y = 0; y < passh[i]; ++y)
+      for(x = 0; x < passw[i]; ++x)
+      {
+        ibp = (ADAM7_IY[i] + y * ADAM7_DY[i]) * olinebits + (ADAM7_IX[i] + x * ADAM7_DX[i]) * bpp;
+        obp = (8 * passstart[i]) + (y * ilinebits + x * bpp);
+        for(b = 0; b < bpp; ++b)
+        {
+          unsigned char bit = readBitFromReversedStream(&ibp, in);
+          setBitOfReversedStream(&obp, out, bit);
+        }
+      }
+    }
+  }
+}
+
+/*out must be buffer big enough to contain uncompressed IDAT chunk data, and in must contain the full image.
+return value is error**/
+static unsigned preProcessScanlines(unsigned char** out, size_t* outsize, const unsigned char* in,
+                                    unsigned w, unsigned h,
+                                    const LodePNGInfo* info_png, const LodePNGEncoderSettings* settings)
+{
+  /*
+  This function converts the pure 2D image with the PNG's colortype, into filtered-padded-interlaced data. Steps:
+  *) if no Adam7: 1) add padding bits (= posible extra bits per scanline if bpp < 8) 2) filter
+  *) if adam7: 1) Adam7_interlace 2) 7x add padding bits 3) 7x filter
+  */
+  unsigned bpp = lodepng_get_bpp(&info_png->color);
+  unsigned error = 0;
+
+  if(info_png->interlace_method == 0)
+  {
+    *outsize = h + (h * ((w * bpp + 7) / 8)); /*image size plus an extra byte per scanline + possible padding bits*/
+    *out = (unsigned char*)lodepng_malloc(*outsize);
+    if(!(*out) && (*outsize)) error = 83; /*alloc fail*/
+
+    if(!error)
+    {
+      /*non multiple of 8 bits per scanline, padding bits needed per scanline*/
+      if(bpp < 8 && w * bpp != ((w * bpp + 7) / 8) * 8)
+      {
+        unsigned char* padded = (unsigned char*)lodepng_malloc(h * ((w * bpp + 7) / 8));
+        if(!padded) error = 83; /*alloc fail*/
+        if(!error)
+        {
+          addPaddingBits(padded, in, ((w * bpp + 7) / 8) * 8, w * bpp, h);
+          error = filter(*out, padded, w, h, &info_png->color, settings);
+        }
+        lodepng_free(padded);
+      }
+      else
+      {
+        /*we can immediately filter into the out buffer, no other steps needed*/
+        error = filter(*out, in, w, h, &info_png->color, settings);
+      }
+    }
+  }
+  else /*interlace_method is 1 (Adam7)*/
+  {
+    unsigned passw[7], passh[7];
+    size_t filter_passstart[8], padded_passstart[8], passstart[8];
+    unsigned char* adam7;
+
+    Adam7_getpassvalues(passw, passh, filter_passstart, padded_passstart, passstart, w, h, bpp);
+
+    *outsize = filter_passstart[7]; /*image size plus an extra byte per scanline + possible padding bits*/
+    *out = (unsigned char*)lodepng_malloc(*outsize);
+    if(!(*out)) error = 83; /*alloc fail*/
+
+    adam7 = (unsigned char*)lodepng_malloc(passstart[7]);
+    if(!adam7 && passstart[7]) error = 83; /*alloc fail*/
+
+    if(!error)
+    {
+      unsigned i;
+
+      Adam7_interlace(adam7, in, w, h, bpp);
+      for(i = 0; i != 7; ++i)
+      {
+        if(bpp < 8)
+        {
+          unsigned char* padded = (unsigned char*)lodepng_malloc(padded_passstart[i + 1] - padded_passstart[i]);
+          if(!padded) ERROR_BREAK(83); /*alloc fail*/
+          addPaddingBits(padded, &adam7[passstart[i]],
+                         ((passw[i] * bpp + 7) / 8) * 8, passw[i] * bpp, passh[i]);
+          error = filter(&(*out)[filter_passstart[i]], padded,
+                         passw[i], passh[i], &info_png->color, settings);
+          lodepng_free(padded);
+        }
+        else
+        {
+          error = filter(&(*out)[filter_passstart[i]], &adam7[padded_passstart[i]],
+                         passw[i], passh[i], &info_png->color, settings);
+        }
+
+        if(error) break;
+      }
+    }
+
+    lodepng_free(adam7);
+  }
+
+  return error;
+}
+
+/*
+palette must have 4 * palettesize bytes allocated, and given in format RGBARGBARGBARGBA...
+returns 0 if the palette is opaque,
+returns 1 if the palette has a single color with alpha 0 ==> color key
+returns 2 if the palette is semi-translucent.
+*/
+static unsigned getPaletteTranslucency(const unsigned char* palette, size_t palettesize)
+{
+  size_t i;
+  unsigned key = 0;
+  unsigned r = 0, g = 0, b = 0; /*the value of the color with alpha 0, so long as color keying is possible*/
+  for(i = 0; i != palettesize; ++i)
+  {
+    if(!key && palette[4 * i + 3] == 0)
+    {
+      r = palette[4 * i + 0]; g = palette[4 * i + 1]; b = palette[4 * i + 2];
+      key = 1;
+      i = (size_t)(-1); /*restart from beginning, to detect earlier opaque colors with key's value*/
+    }
+    else if(palette[4 * i + 3] != 255) return 2;
+    /*when key, no opaque RGB may have key's RGB*/
+    else if(key && r == palette[i * 4 + 0] && g == palette[i * 4 + 1] && b == palette[i * 4 + 2]) return 2;
+  }
+  return key;
+}
+
+#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
+static unsigned addUnknownChunks(ucvector* out, unsigned char* data, size_t datasize)
+{
+  unsigned char* inchunk = data;
+  while((size_t)(inchunk - data) < datasize)
+  {
+    CERROR_TRY_RETURN(lodepng_chunk_append(&out->data, &out->size, inchunk));
+    out->allocsize = out->size; /*fix the allocsize again*/
+    inchunk = lodepng_chunk_next(inchunk);
+  }
+  return 0;
+}
+#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
+
+unsigned lodepng_encode(unsigned char** out, size_t* outsize,
+                        const unsigned char* image, unsigned w, unsigned h,
+                        LodePNGState* state)
+{
+  LodePNGInfo info;
+  ucvector outv;
+  unsigned char* data = 0; /*uncompressed version of the IDAT chunk data*/
+  size_t datasize = 0;
+
+  /*provide some proper output values if error will happen*/
+  *out = 0;
+  *outsize = 0;
+  state->error = 0;
+
+  lodepng_info_init(&info);
+  lodepng_info_copy(&info, &state->info_png);
+
+  if((info.color.colortype == LCT_PALETTE || state->encoder.force_palette)
+      && (info.color.palettesize == 0 || info.color.palettesize > 256))
+  {
+    state->error = 68; /*invalid palette size, it is only allowed to be 1-256*/
+    return state->error;
+  }
+
+  if(state->encoder.auto_convert)
+  {
+    state->error = lodepng_auto_choose_color(&info.color, image, w, h, &state->info_raw);
+  }
+  if(state->error) return state->error;
+
+  if(state->encoder.zlibsettings.btype > 2)
+  {
+    CERROR_RETURN_ERROR(state->error, 61); /*error: unexisting btype*/
+  }
+  if(state->info_png.interlace_method > 1)
+  {
+    CERROR_RETURN_ERROR(state->error, 71); /*error: unexisting interlace mode*/
+  }
+
+  state->error = checkColorValidity(info.color.colortype, info.color.bitdepth);
+  if(state->error) return state->error; /*error: unexisting color type given*/
+  state->error = checkColorValidity(state->info_raw.colortype, state->info_raw.bitdepth);
+  if(state->error) return state->error; /*error: unexisting color type given*/
+
+  if(!lodepng_color_mode_equal(&state->info_raw, &info.color))
+  {
+    unsigned char* converted;
+    size_t size = (w * h * lodepng_get_bpp(&info.color) + 7) / 8;
+
+    converted = (unsigned char*)lodepng_malloc(size);
+    if(!converted && size) state->error = 83; /*alloc fail*/
+    if(!state->error)
+    {
+      state->error = lodepng_convert(converted, image, &info.color, &state->info_raw, w, h);
+    }
+    if(!state->error) preProcessScanlines(&data, &datasize, converted, w, h, &info, &state->encoder);
+    lodepng_free(converted);
+  }
+  else preProcessScanlines(&data, &datasize, image, w, h, &info, &state->encoder);
+
+  ucvector_init(&outv);
+  while(!state->error) /*while only executed once, to break on error*/
+  {
+#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
+    size_t i;
+#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
+    /*write signature and chunks*/
+    writeSignature(&outv);
+    /*IHDR*/
+    addChunk_IHDR(&outv, w, h, info.color.colortype, info.color.bitdepth, info.interlace_method);
+#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
+    /*unknown chunks between IHDR and PLTE*/
+    if(info.unknown_chunks_data[0])
+    {
+      state->error = addUnknownChunks(&outv, info.unknown_chunks_data[0], info.unknown_chunks_size[0]);
+      if(state->error) break;
+    }
+#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
+    /*PLTE*/
+    if(info.color.colortype == LCT_PALETTE)
+    {
+      addChunk_PLTE(&outv, &info.color);
+    }
+    if(state->encoder.force_palette && (info.color.colortype == LCT_RGB || info.color.colortype == LCT_RGBA))
+    {
+      addChunk_PLTE(&outv, &info.color);
+    }
+    /*tRNS*/
+    if(info.color.colortype == LCT_PALETTE && getPaletteTranslucency(info.color.palette, info.color.palettesize) != 0)
+    {
+      addChunk_tRNS(&outv, &info.color);
+    }
+    if((info.color.colortype == LCT_GREY || info.color.colortype == LCT_RGB) && info.color.key_defined)
+    {
+      addChunk_tRNS(&outv, &info.color);
+    }
+#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
+    /*bKGD (must come between PLTE and the IDAt chunks*/
+    if(info.background_defined) addChunk_bKGD(&outv, &info);
+    /*pHYs (must come before the IDAT chunks)*/
+    if(info.phys_defined) addChunk_pHYs(&outv, &info);
+
+    /*unknown chunks between PLTE and IDAT*/
+    if(info.unknown_chunks_data[1])
+    {
+      state->error = addUnknownChunks(&outv, info.unknown_chunks_data[1], info.unknown_chunks_size[1]);
+      if(state->error) break;
+    }
+#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
+    /*IDAT (multiple IDAT chunks must be consecutive)*/
+    state->error = addChunk_IDAT(&outv, data, datasize, &state->encoder.zlibsettings);
+    if(state->error) break;
+#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
+    /*tIME*/
+    if(info.time_defined) addChunk_tIME(&outv, &info.time);
+    /*tEXt and/or zTXt*/
+    for(i = 0; i != info.text_num; ++i)
+    {
+      if(strlen(info.text_keys[i]) > 79)
+      {
+        state->error = 66; /*text chunk too large*/
+        break;
+      }
+      if(strlen(info.text_keys[i]) < 1)
+      {
+        state->error = 67; /*text chunk too small*/
+        break;
+      }
+      if(state->encoder.text_compression)
+      {
+        addChunk_zTXt(&outv, info.text_keys[i], info.text_strings[i], &state->encoder.zlibsettings);
+      }
+      else
+      {
+        addChunk_tEXt(&outv, info.text_keys[i], info.text_strings[i]);
+      }
+    }
+    /*LodePNG version id in text chunk*/
+    if(state->encoder.add_id)
+    {
+      unsigned alread_added_id_text = 0;
+      for(i = 0; i != info.text_num; ++i)
+      {
+        if(!strcmp(info.text_keys[i], "LodePNG"))
+        {
+          alread_added_id_text = 1;
+          break;
+        }
+      }
+      if(alread_added_id_text == 0)
+      {
+        addChunk_tEXt(&outv, "LodePNG", LODEPNG_VERSION_STRING); /*it's shorter as tEXt than as zTXt chunk*/
+      }
+    }
+    /*iTXt*/
+    for(i = 0; i != info.itext_num; ++i)
+    {
+      if(strlen(info.itext_keys[i]) > 79)
+      {
+        state->error = 66; /*text chunk too large*/
+        break;
+      }
+      if(strlen(info.itext_keys[i]) < 1)
+      {
+        state->error = 67; /*text chunk too small*/
+        break;
+      }
+      addChunk_iTXt(&outv, state->encoder.text_compression,
+                    info.itext_keys[i], info.itext_langtags[i], info.itext_transkeys[i], info.itext_strings[i],
+                    &state->encoder.zlibsettings);
+    }
+
+    /*unknown chunks between IDAT and IEND*/
+    if(info.unknown_chunks_data[2])
+    {
+      state->error = addUnknownChunks(&outv, info.unknown_chunks_data[2], info.unknown_chunks_size[2]);
+      if(state->error) break;
+    }
+#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
+    addChunk_IEND(&outv);
+
+    break; /*this isn't really a while loop; no error happened so break out now!*/
+  }
+
+  lodepng_info_cleanup(&info);
+  lodepng_free(data);
+  /*instead of cleaning the vector up, give it to the output*/
+  *out = outv.data;
+  *outsize = outv.size;
+
+  return state->error;
+}
+
+unsigned lodepng_encode_memory(unsigned char** out, size_t* outsize, const unsigned char* image,
+                               unsigned w, unsigned h, LodePNGColorType colortype, unsigned bitdepth)
+{
+  unsigned error;
+  LodePNGState state;
+  lodepng_state_init(&state);
+  state.info_raw.colortype = colortype;
+  state.info_raw.bitdepth = bitdepth;
+  state.info_png.color.colortype = colortype;
+  state.info_png.color.bitdepth = bitdepth;
+  lodepng_encode(out, outsize, image, w, h, &state);
+  error = state.error;
+  lodepng_state_cleanup(&state);
+  return error;
+}
+
+unsigned lodepng_encode32(unsigned char** out, size_t* outsize, const unsigned char* image, unsigned w, unsigned h)
+{
+  return lodepng_encode_memory(out, outsize, image, w, h, LCT_RGBA, 8);
+}
+
+unsigned lodepng_encode24(unsigned char** out, size_t* outsize, const unsigned char* image, unsigned w, unsigned h)
+{
+  return lodepng_encode_memory(out, outsize, image, w, h, LCT_RGB, 8);
+}
+
+#ifdef LODEPNG_COMPILE_DISK
+unsigned lodepng_encode_file(const char* filename, const unsigned char* image, unsigned w, unsigned h,
+                             LodePNGColorType colortype, unsigned bitdepth)
+{
+  unsigned char* buffer;
+  size_t buffersize;
+  unsigned error = lodepng_encode_memory(&buffer, &buffersize, image, w, h, colortype, bitdepth);
+  if(!error) error = lodepng_save_file(buffer, buffersize, filename);
+  lodepng_free(buffer);
+  return error;
+}
+
+unsigned lodepng_encode32_file(const char* filename, const unsigned char* image, unsigned w, unsigned h)
+{
+  return lodepng_encode_file(filename, image, w, h, LCT_RGBA, 8);
+}
+
+unsigned lodepng_encode24_file(const char* filename, const unsigned char* image, unsigned w, unsigned h)
+{
+  return lodepng_encode_file(filename, image, w, h, LCT_RGB, 8);
+}
+#endif /*LODEPNG_COMPILE_DISK*/
+
+void lodepng_encoder_settings_init(LodePNGEncoderSettings* settings)
+{
+  lodepng_compress_settings_init(&settings->zlibsettings);
+  settings->filter_palette_zero = 1;
+  settings->filter_strategy = LFS_MINSUM;
+  settings->auto_convert = 1;
+  settings->force_palette = 0;
+  settings->predefined_filters = 0;
+#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
+  settings->add_id = 0;
+  settings->text_compression = 1;
+#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
+}
+
+#endif /*LODEPNG_COMPILE_ENCODER*/
+#endif /*LODEPNG_COMPILE_PNG*/
+
+#ifdef LODEPNG_COMPILE_ERROR_TEXT
+/*
+This returns the description of a numerical error code in English. This is also
+the documentation of all the error codes.
+*/
+const char* lodepng_error_text(unsigned code)
+{
+  switch(code)
+  {
+    case 0: return "no error, everything went ok";
+    case 1: return "nothing done yet"; /*the Encoder/Decoder has done nothing yet, error checking makes no sense yet*/
+    case 10: return "end of input memory reached without huffman end code"; /*while huffman decoding*/
+    case 11: return "error in code tree made it jump outside of huffman tree"; /*while huffman decoding*/
+    case 13: return "problem while processing dynamic deflate block";
+    case 14: return "problem while processing dynamic deflate block";
+    case 15: return "problem while processing dynamic deflate block";
+    case 16: return "unexisting code while processing dynamic deflate block";
+    case 17: return "end of out buffer memory reached while inflating";
+    case 18: return "invalid distance code while inflating";
+    case 19: return "end of out buffer memory reached while inflating";
+    case 20: return "invalid deflate block BTYPE encountered while decoding";
+    case 21: return "NLEN is not ones complement of LEN in a deflate block";
+     /*end of out buffer memory reached while inflating:
+     This can happen if the inflated deflate data is longer than the amount of bytes required to fill up
+     all the pixels of the image, given the color depth and image dimensions. Something that doesn't
+     happen in a normal, well encoded, PNG image.*/
+    case 22: return "end of out buffer memory reached while inflating";
+    case 23: return "end of in buffer memory reached while inflating";
+    case 24: return "invalid FCHECK in zlib header";
+    case 25: return "invalid compression method in zlib header";
+    case 26: return "FDICT encountered in zlib header while it's not used for PNG";
+    case 27: return "PNG file is smaller than a PNG header";
+    /*Checks the magic file header, the first 8 bytes of the PNG file*/
+    case 28: return "incorrect PNG signature, it's no PNG or corrupted";
+    case 29: return "first chunk is not the header chunk";
+    case 30: return "chunk length too large, chunk broken off at end of file";
+    case 31: return "illegal PNG color type or bpp";
+    case 32: return "illegal PNG compression method";
+    case 33: return "illegal PNG filter method";
+    case 34: return "illegal PNG interlace method";
+    case 35: return "chunk length of a chunk is too large or the chunk too small";
+    case 36: return "illegal PNG filter type encountered";
+    case 37: return "illegal bit depth for this color type given";
+    case 38: return "the palette is too big"; /*more than 256 colors*/
+    case 39: return "more palette alpha values given in tRNS chunk than there are colors in the palette";
+    case 40: return "tRNS chunk has wrong size for greyscale image";
+    case 41: return "tRNS chunk has wrong size for RGB image";
+    case 42: return "tRNS chunk appeared while it was not allowed for this color type";
+    case 43: return "bKGD chunk has wrong size for palette image";
+    case 44: return "bKGD chunk has wrong size for greyscale image";
+    case 45: return "bKGD chunk has wrong size for RGB image";
+    case 48: return "empty input buffer given to decoder. Maybe caused by non-existing file?";
+    case 49: return "jumped past memory while generating dynamic huffman tree";
+    case 50: return "jumped past memory while generating dynamic huffman tree";
+    case 51: return "jumped past memory while inflating huffman block";
+    case 52: return "jumped past memory while inflating";
+    case 53: return "size of zlib data too small";
+    case 54: return "repeat symbol in tree while there was no value symbol yet";
+    /*jumped past tree while generating huffman tree, this could be when the
+    tree will have more leaves than symbols after generating it out of the
+    given lenghts. They call this an oversubscribed dynamic bit lengths tree in zlib.*/
+    case 55: return "jumped past tree while generating huffman tree";
+    case 56: return "given output image colortype or bitdepth not supported for color conversion";
+    case 57: return "invalid CRC encountered (checking CRC can be disabled)";
+    case 58: return "invalid ADLER32 encountered (checking ADLER32 can be disabled)";
+    case 59: return "requested color conversion not supported";
+    case 60: return "invalid window size given in the settings of the encoder (must be 0-32768)";
+    case 61: return "invalid BTYPE given in the settings of the encoder (only 0, 1 and 2 are allowed)";
+    /*LodePNG leaves the choice of RGB to greyscale conversion formula to the user.*/
+    case 62: return "conversion from color to greyscale not supported";
+    case 63: return "length of a chunk too long, max allowed for PNG is 2147483647 bytes per chunk"; /*(2^31-1)*/
+    /*this would result in the inability of a deflated block to ever contain an end code. It must be at least 1.*/
+    case 64: return "the length of the END symbol 256 in the Huffman tree is 0";
+    case 66: return "the length of a text chunk keyword given to the encoder is longer than the maximum of 79 bytes";
+    case 67: return "the length of a text chunk keyword given to the encoder is smaller than the minimum of 1 byte";
+    case 68: return "tried to encode a PLTE chunk with a palette that has less than 1 or more than 256 colors";
+    case 69: return "unknown chunk type with 'critical' flag encountered by the decoder";
+    case 71: return "unexisting interlace mode given to encoder (must be 0 or 1)";
+    case 72: return "while decoding, unexisting compression method encountering in zTXt or iTXt chunk (it must be 0)";
+    case 73: return "invalid tIME chunk size";
+    case 74: return "invalid pHYs chunk size";
+    /*length could be wrong, or data chopped off*/
+    case 75: return "no null termination char found while decoding text chunk";
+    case 76: return "iTXt chunk too short to contain required bytes";
+    case 77: return "integer overflow in buffer size";
+    case 78: return "failed to open file for reading"; /*file doesn't exist or couldn't be opened for reading*/
+    case 79: return "failed to open file for writing";
+    case 80: return "tried creating a tree of 0 symbols";
+    case 81: return "lazy matching at pos 0 is impossible";
+    case 82: return "color conversion to palette requested while a color isn't in palette";
+    case 83: return "memory allocation failed";
+    case 84: return "given image too small to contain all pixels to be encoded";
+    case 86: return "impossible offset in lz77 encoding (internal bug)";
+    case 87: return "must provide custom zlib function pointer if LODEPNG_COMPILE_ZLIB is not defined";
+    case 88: return "invalid filter strategy given for LodePNGEncoderSettings.filter_strategy";
+    case 89: return "text chunk keyword too short or long: must have size 1-79";
+    /*the windowsize in the LodePNGCompressSettings. Requiring POT(==> & instead of %) makes encoding 12% faster.*/
+    case 90: return "windowsize must be a power of two";
+    case 91: return "invalid decompressed idat size";
+    case 92: return "too many pixels, not supported";
+    case 93: return "zero width or height is invalid";
+    case 94: return "header chunk must have a size of 13 bytes";
+  }
+  return "unknown error code";
+}
+#endif /*LODEPNG_COMPILE_ERROR_TEXT*/
+
+/* ////////////////////////////////////////////////////////////////////////// */
+/* ////////////////////////////////////////////////////////////////////////// */
+/* // C++ Wrapper                                                          // */
+/* ////////////////////////////////////////////////////////////////////////// */
+/* ////////////////////////////////////////////////////////////////////////// */
+
+#ifdef LODEPNG_COMPILE_CPP
+namespace lodepng
+{
+
+#ifdef LODEPNG_COMPILE_DISK
+unsigned load_file(std::vector<unsigned char>& buffer, const std::string& filename)
+{
+  long size = lodepng_filesize(filename.c_str());
+  if(size < 0) return 78;
+  buffer.resize((size_t)size);
+  return size == 0 ? 0 : lodepng_buffer_file(&buffer[0], (size_t)size, filename.c_str());
+}
+
+/*write given buffer to the file, overwriting the file, it doesn't append to it.*/
+unsigned save_file(const std::vector<unsigned char>& buffer, const std::string& filename)
+{
+  return lodepng_save_file(buffer.empty() ? 0 : &buffer[0], buffer.size(), filename.c_str());
+}
+#endif /* LODEPNG_COMPILE_DISK */
+
+#ifdef LODEPNG_COMPILE_ZLIB
+#ifdef LODEPNG_COMPILE_DECODER
+unsigned decompress(std::vector<unsigned char>& out, const unsigned char* in, size_t insize,
+                    const LodePNGDecompressSettings& settings)
+{
+  unsigned char* buffer = 0;
+  size_t buffersize = 0;
+  unsigned error = zlib_decompress(&buffer, &buffersize, in, insize, &settings);
+  if(buffer)
+  {
+    out.insert(out.end(), &buffer[0], &buffer[buffersize]);
+    lodepng_free(buffer);
+  }
+  return error;
+}
+
+unsigned decompress(std::vector<unsigned char>& out, const std::vector<unsigned char>& in,
+                    const LodePNGDecompressSettings& settings)
+{
+  return decompress(out, in.empty() ? 0 : &in[0], in.size(), settings);
+}
+#endif /* LODEPNG_COMPILE_DECODER */
+
+#ifdef LODEPNG_COMPILE_ENCODER
+unsigned compress(std::vector<unsigned char>& out, const unsigned char* in, size_t insize,
+                  const LodePNGCompressSettings& settings)
+{
+  unsigned char* buffer = 0;
+  size_t buffersize = 0;
+  unsigned error = zlib_compress(&buffer, &buffersize, in, insize, &settings);
+  if(buffer)
+  {
+    out.insert(out.end(), &buffer[0], &buffer[buffersize]);
+    lodepng_free(buffer);
+  }
+  return error;
+}
+
+unsigned compress(std::vector<unsigned char>& out, const std::vector<unsigned char>& in,
+                  const LodePNGCompressSettings& settings)
+{
+  return compress(out, in.empty() ? 0 : &in[0], in.size(), settings);
+}
+#endif /* LODEPNG_COMPILE_ENCODER */
+#endif /* LODEPNG_COMPILE_ZLIB */
+
+
+#ifdef LODEPNG_COMPILE_PNG
+
+State::State()
+{
+  lodepng_state_init(this);
+}
+
+State::State(const State& other)
+{
+  lodepng_state_init(this);
+  lodepng_state_copy(this, &other);
+}
+
+State::~State()
+{
+  lodepng_state_cleanup(this);
+}
+
+State& State::operator=(const State& other)
+{
+  lodepng_state_copy(this, &other);
+  return *this;
+}
+
+#ifdef LODEPNG_COMPILE_DECODER
+
+unsigned decode(std::vector<unsigned char>& out, unsigned& w, unsigned& h, const unsigned char* in,
+                size_t insize, LodePNGColorType colortype, unsigned bitdepth)
+{
+  unsigned char* buffer;
+  unsigned error = lodepng_decode_memory(&buffer, &w, &h, in, insize, colortype, bitdepth);
+  if(buffer && !error)
+  {
+    State state;
+    state.info_raw.colortype = colortype;
+    state.info_raw.bitdepth = bitdepth;
+    size_t buffersize = lodepng_get_raw_size(w, h, &state.info_raw);
+    out.insert(out.end(), &buffer[0], &buffer[buffersize]);
+    lodepng_free(buffer);
+  }
+  return error;
+}
+
+unsigned decode(std::vector<unsigned char>& out, unsigned& w, unsigned& h,
+                const std::vector<unsigned char>& in, LodePNGColorType colortype, unsigned bitdepth)
+{
+  return decode(out, w, h, in.empty() ? 0 : &in[0], (unsigned)in.size(), colortype, bitdepth);
+}
+
+unsigned decode(std::vector<unsigned char>& out, unsigned& w, unsigned& h,
+                State& state,
+                const unsigned char* in, size_t insize)
+{
+  unsigned char* buffer = NULL;
+  unsigned error = lodepng_decode(&buffer, &w, &h, &state, in, insize);
+  if(buffer && !error)
+  {
+    size_t buffersize = lodepng_get_raw_size(w, h, &state.info_raw);
+    out.insert(out.end(), &buffer[0], &buffer[buffersize]);
+  }
+  lodepng_free(buffer);
+  return error;
+}
+
+unsigned decode(std::vector<unsigned char>& out, unsigned& w, unsigned& h,
+                State& state,
+                const std::vector<unsigned char>& in)
+{
+  return decode(out, w, h, state, in.empty() ? 0 : &in[0], in.size());
+}
+
+#ifdef LODEPNG_COMPILE_DISK
+unsigned decode(std::vector<unsigned char>& out, unsigned& w, unsigned& h, const std::string& filename,
+                LodePNGColorType colortype, unsigned bitdepth)
+{
+  std::vector<unsigned char> buffer;
+  unsigned error = load_file(buffer, filename);
+  if(error) return error;
+  return decode(out, w, h, buffer, colortype, bitdepth);
+}
+#endif /* LODEPNG_COMPILE_DECODER */
+#endif /* LODEPNG_COMPILE_DISK */
+
+#ifdef LODEPNG_COMPILE_ENCODER
+unsigned encode(std::vector<unsigned char>& out, const unsigned char* in, unsigned w, unsigned h,
+                LodePNGColorType colortype, unsigned bitdepth)
+{
+  unsigned char* buffer;
+  size_t buffersize;
+  unsigned error = lodepng_encode_memory(&buffer, &buffersize, in, w, h, colortype, bitdepth);
+  if(buffer)
+  {
+    out.insert(out.end(), &buffer[0], &buffer[buffersize]);
+    lodepng_free(buffer);
+  }
+  return error;
+}
+
+unsigned encode(std::vector<unsigned char>& out,
+                const std::vector<unsigned char>& in, unsigned w, unsigned h,
+                LodePNGColorType colortype, unsigned bitdepth)
+{
+  if(lodepng_get_raw_size_lct(w, h, colortype, bitdepth) > in.size()) return 84;
+  return encode(out, in.empty() ? 0 : &in[0], w, h, colortype, bitdepth);
+}
+
+unsigned encode(std::vector<unsigned char>& out,
+                const unsigned char* in, unsigned w, unsigned h,
+                State& state)
+{
+  unsigned char* buffer;
+  size_t buffersize;
+  unsigned error = lodepng_encode(&buffer, &buffersize, in, w, h, &state);
+  if(buffer)
+  {
+    out.insert(out.end(), &buffer[0], &buffer[buffersize]);
+    lodepng_free(buffer);
+  }
+  return error;
+}
+
+unsigned encode(std::vector<unsigned char>& out,
+                const std::vector<unsigned char>& in, unsigned w, unsigned h,
+                State& state)
+{
+  if(lodepng_get_raw_size(w, h, &state.info_raw) > in.size()) return 84;
+  return encode(out, in.empty() ? 0 : &in[0], w, h, state);
+}
+
+#ifdef LODEPNG_COMPILE_DISK
+unsigned encode(const std::string& filename,
+                const unsigned char* in, unsigned w, unsigned h,
+                LodePNGColorType colortype, unsigned bitdepth)
+{
+  std::vector<unsigned char> buffer;
+  unsigned error = encode(buffer, in, w, h, colortype, bitdepth);
+  if(!error) error = save_file(buffer, filename);
+  return error;
+}
+
+unsigned encode(const std::string& filename,
+                const std::vector<unsigned char>& in, unsigned w, unsigned h,
+                LodePNGColorType colortype, unsigned bitdepth)
+{
+  if(lodepng_get_raw_size_lct(w, h, colortype, bitdepth) > in.size()) return 84;
+  return encode(filename, in.empty() ? 0 : &in[0], w, h, colortype, bitdepth);
+}
+#endif /* LODEPNG_COMPILE_DISK */
+#endif /* LODEPNG_COMPILE_ENCODER */
+#endif /* LODEPNG_COMPILE_PNG */
+} /* namespace lodepng */
+#endif /*LODEPNG_COMPILE_CPP*/

+ 2467 - 0
lib/tinyxml2.cpp

@@ -0,0 +1,2467 @@
+/*
+Original code by Lee Thomason (www.grinninglizard.com)
+
+This software is provided 'as-is', without any express or implied
+warranty. In no event will the authors be held liable for any
+damages arising from the use of this software.
+
+Permission is granted to anyone to use this software for any
+purpose, including commercial applications, and to alter it and
+redistribute it freely, subject to the following restrictions:
+
+1. The origin of this software must not be misrepresented; you must
+not claim that you wrote the original software. If you use this
+software in a product, an acknowledgment in the product documentation
+would be appreciated but is not required.
+
+2. Altered source versions must be plainly marked as such, and
+must not be misrepresented as being the original software.
+
+3. This notice may not be removed or altered from any source
+distribution.
+*/
+
+#include "tinyxml2.h"
+
+#include <new>		// yes, this one new style header, is in the Android SDK.
+#if defined(ANDROID_NDK) || defined(__BORLANDC__) || defined(__QNXNTO__)
+#   include <stddef.h>
+#   include <stdarg.h>
+#else
+#   include <cstddef>
+#   include <cstdarg>
+#endif
+
+#if defined(_MSC_VER) && (_MSC_VER >= 1400 ) && (!defined WINCE)
+	// Microsoft Visual Studio, version 2005 and higher. Not WinCE.
+	/*int _snprintf_s(
+	   char *buffer,
+	   size_t sizeOfBuffer,
+	   size_t count,
+	   const char *format [,
+		  argument] ...
+	);*/
+	static inline int TIXML_SNPRINTF( char* buffer, size_t size, const char* format, ... )
+	{
+		va_list va;
+		va_start( va, format );
+		int result = vsnprintf_s( buffer, size, _TRUNCATE, format, va );
+		va_end( va );
+		return result;
+	}
+
+	static inline int TIXML_VSNPRINTF( char* buffer, size_t size, const char* format, va_list va )
+	{
+		int result = vsnprintf_s( buffer, size, _TRUNCATE, format, va );
+		return result;
+	}
+
+	#define TIXML_VSCPRINTF	_vscprintf
+	#define TIXML_SSCANF	sscanf_s
+#elif defined _MSC_VER
+	// Microsoft Visual Studio 2003 and earlier or WinCE
+	#define TIXML_SNPRINTF	_snprintf
+	#define TIXML_VSNPRINTF _vsnprintf
+	#define TIXML_SSCANF	sscanf
+	#if (_MSC_VER < 1400 ) && (!defined WINCE)
+		// Microsoft Visual Studio 2003 and not WinCE.
+		#define TIXML_VSCPRINTF   _vscprintf // VS2003's C runtime has this, but VC6 C runtime or WinCE SDK doesn't have.
+	#else
+		// Microsoft Visual Studio 2003 and earlier or WinCE.
+		static inline int TIXML_VSCPRINTF( const char* format, va_list va )
+		{
+			int len = 512;
+			for (;;) {
+				len = len*2;
+				char* str = new char[len]();
+				const int required = _vsnprintf(str, len, format, va);
+				delete[] str;
+				if ( required != -1 ) {
+					TIXMLASSERT( required >= 0 );
+					len = required;
+					break;
+				}
+			}
+			TIXMLASSERT( len >= 0 );
+			return len;
+		}
+	#endif
+#else
+	// GCC version 3 and higher
+	//#warning( "Using sn* functions." )
+	#define TIXML_SNPRINTF	snprintf
+	#define TIXML_VSNPRINTF	vsnprintf
+	static inline int TIXML_VSCPRINTF( const char* format, va_list va )
+	{
+		int len = vsnprintf( 0, 0, format, va );
+		TIXMLASSERT( len >= 0 );
+		return len;
+	}
+	#define TIXML_SSCANF   sscanf
+#endif
+
+
+static const char LINE_FEED				= (char)0x0a;			// all line endings are normalized to LF
+static const char LF = LINE_FEED;
+static const char CARRIAGE_RETURN		= (char)0x0d;			// CR gets filtered out
+static const char CR = CARRIAGE_RETURN;
+static const char SINGLE_QUOTE			= '\'';
+static const char DOUBLE_QUOTE			= '\"';
+
+// Bunch of unicode info at:
+//		http://www.unicode.org/faq/utf_bom.html
+//	ef bb bf (Microsoft "lead bytes") - designates UTF-8
+
+static const unsigned char TIXML_UTF_LEAD_0 = 0xefU;
+static const unsigned char TIXML_UTF_LEAD_1 = 0xbbU;
+static const unsigned char TIXML_UTF_LEAD_2 = 0xbfU;
+
+namespace tinyxml2
+{
+
+struct Entity {
+    const char* pattern;
+    int length;
+    char value;
+};
+
+static const int NUM_ENTITIES = 5;
+static const Entity entities[NUM_ENTITIES] = {
+    { "quot", 4,	DOUBLE_QUOTE },
+    { "amp", 3,		'&'  },
+    { "apos", 4,	SINGLE_QUOTE },
+    { "lt",	2, 		'<'	 },
+    { "gt",	2,		'>'	 }
+};
+
+
+StrPair::~StrPair()
+{
+    Reset();
+}
+
+
+void StrPair::TransferTo( StrPair* other )
+{
+    if ( this == other ) {
+        return;
+    }
+    // This in effect implements the assignment operator by "moving"
+    // ownership (as in auto_ptr).
+
+    TIXMLASSERT( other->_flags == 0 );
+    TIXMLASSERT( other->_start == 0 );
+    TIXMLASSERT( other->_end == 0 );
+
+    other->Reset();
+
+    other->_flags = _flags;
+    other->_start = _start;
+    other->_end = _end;
+
+    _flags = 0;
+    _start = 0;
+    _end = 0;
+}
+
+void StrPair::Reset()
+{
+    if ( _flags & NEEDS_DELETE ) {
+        delete [] _start;
+    }
+    _flags = 0;
+    _start = 0;
+    _end = 0;
+}
+
+
+void StrPair::SetStr( const char* str, int flags )
+{
+    TIXMLASSERT( str );
+    Reset();
+    size_t len = strlen( str );
+    TIXMLASSERT( _start == 0 );
+    _start = new char[ len+1 ];
+    memcpy( _start, str, len+1 );
+    _end = _start + len;
+    _flags = flags | NEEDS_DELETE;
+}
+
+
+char* StrPair::ParseText( char* p, const char* endTag, int strFlags )
+{
+    TIXMLASSERT( endTag && *endTag );
+
+    char* start = p;
+    char  endChar = *endTag;
+    size_t length = strlen( endTag );
+
+    // Inner loop of text parsing.
+    while ( *p ) {
+        if ( *p == endChar && strncmp( p, endTag, length ) == 0 ) {
+            Set( start, p, strFlags );
+            return p + length;
+        }
+        ++p;
+    }
+    return 0;
+}
+
+
+char* StrPair::ParseName( char* p )
+{
+    if ( !p || !(*p) ) {
+        return 0;
+    }
+    if ( !XMLUtil::IsNameStartChar( *p ) ) {
+        return 0;
+    }
+
+    char* const start = p;
+    ++p;
+    while ( *p && XMLUtil::IsNameChar( *p ) ) {
+        ++p;
+    }
+
+    Set( start, p, 0 );
+    return p;
+}
+
+
+void StrPair::CollapseWhitespace()
+{
+    // Adjusting _start would cause undefined behavior on delete[]
+    TIXMLASSERT( ( _flags & NEEDS_DELETE ) == 0 );
+    // Trim leading space.
+    _start = XMLUtil::SkipWhiteSpace( _start );
+
+    if ( *_start ) {
+        char* p = _start;	// the read pointer
+        char* q = _start;	// the write pointer
+
+        while( *p ) {
+            if ( XMLUtil::IsWhiteSpace( *p )) {
+                p = XMLUtil::SkipWhiteSpace( p );
+                if ( *p == 0 ) {
+                    break;    // don't write to q; this trims the trailing space.
+                }
+                *q = ' ';
+                ++q;
+            }
+            *q = *p;
+            ++q;
+            ++p;
+        }
+        *q = 0;
+    }
+}
+
+
+const char* StrPair::GetStr()
+{
+    TIXMLASSERT( _start );
+    TIXMLASSERT( _end );
+    if ( _flags & NEEDS_FLUSH ) {
+        *_end = 0;
+        _flags ^= NEEDS_FLUSH;
+
+        if ( _flags ) {
+            char* p = _start;	// the read pointer
+            char* q = _start;	// the write pointer
+
+            while( p < _end ) {
+                if ( (_flags & NEEDS_NEWLINE_NORMALIZATION) && *p == CR ) {
+                    // CR-LF pair becomes LF
+                    // CR alone becomes LF
+                    // LF-CR becomes LF
+                    if ( *(p+1) == LF ) {
+                        p += 2;
+                    }
+                    else {
+                        ++p;
+                    }
+                    *q++ = LF;
+                }
+                else if ( (_flags & NEEDS_NEWLINE_NORMALIZATION) && *p == LF ) {
+                    if ( *(p+1) == CR ) {
+                        p += 2;
+                    }
+                    else {
+                        ++p;
+                    }
+                    *q++ = LF;
+                }
+                else if ( (_flags & NEEDS_ENTITY_PROCESSING) && *p == '&' ) {
+                    // Entities handled by tinyXML2:
+                    // - special entities in the entity table [in/out]
+                    // - numeric character reference [in]
+                    //   &#20013; or &#x4e2d;
+
+                    if ( *(p+1) == '#' ) {
+                        const int buflen = 10;
+                        char buf[buflen] = { 0 };
+                        int len = 0;
+                        char* adjusted = const_cast<char*>( XMLUtil::GetCharacterRef( p, buf, &len ) );
+                        if ( adjusted == 0 ) {
+                            *q = *p;
+                            ++p;
+                            ++q;
+                        }
+                        else {
+                            TIXMLASSERT( 0 <= len && len <= buflen );
+                            TIXMLASSERT( q + len <= adjusted );
+                            p = adjusted;
+                            memcpy( q, buf, len );
+                            q += len;
+                        }
+                    }
+                    else {
+                        bool entityFound = false;
+                        for( int i = 0; i < NUM_ENTITIES; ++i ) {
+                            const Entity& entity = entities[i];
+                            if ( strncmp( p + 1, entity.pattern, entity.length ) == 0
+                                    && *( p + entity.length + 1 ) == ';' ) {
+                                // Found an entity - convert.
+                                *q = entity.value;
+                                ++q;
+                                p += entity.length + 2;
+                                entityFound = true;
+                                break;
+                            }
+                        }
+                        if ( !entityFound ) {
+                            // fixme: treat as error?
+                            ++p;
+                            ++q;
+                        }
+                    }
+                }
+                else {
+                    *q = *p;
+                    ++p;
+                    ++q;
+                }
+            }
+            *q = 0;
+        }
+        // The loop below has plenty going on, and this
+        // is a less useful mode. Break it out.
+        if ( _flags & NEEDS_WHITESPACE_COLLAPSING ) {
+            CollapseWhitespace();
+        }
+        _flags = (_flags & NEEDS_DELETE);
+    }
+    TIXMLASSERT( _start );
+    return _start;
+}
+
+
+
+
+// --------- XMLUtil ----------- //
+
+const char* XMLUtil::ReadBOM( const char* p, bool* bom )
+{
+    TIXMLASSERT( p );
+    TIXMLASSERT( bom );
+    *bom = false;
+    const unsigned char* pu = reinterpret_cast<const unsigned char*>(p);
+    // Check for BOM:
+    if (    *(pu+0) == TIXML_UTF_LEAD_0
+            && *(pu+1) == TIXML_UTF_LEAD_1
+            && *(pu+2) == TIXML_UTF_LEAD_2 ) {
+        *bom = true;
+        p += 3;
+    }
+    TIXMLASSERT( p );
+    return p;
+}
+
+
+void XMLUtil::ConvertUTF32ToUTF8( unsigned long input, char* output, int* length )
+{
+    const unsigned long BYTE_MASK = 0xBF;
+    const unsigned long BYTE_MARK = 0x80;
+    const unsigned long FIRST_BYTE_MARK[7] = { 0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC };
+
+    if (input < 0x80) {
+        *length = 1;
+    }
+    else if ( input < 0x800 ) {
+        *length = 2;
+    }
+    else if ( input < 0x10000 ) {
+        *length = 3;
+    }
+    else if ( input < 0x200000 ) {
+        *length = 4;
+    }
+    else {
+        *length = 0;    // This code won't convert this correctly anyway.
+        return;
+    }
+
+    output += *length;
+
+    // Scary scary fall throughs.
+    switch (*length) {
+        case 4:
+            --output;
+            *output = (char)((input | BYTE_MARK) & BYTE_MASK);
+            input >>= 6;
+        case 3:
+            --output;
+            *output = (char)((input | BYTE_MARK) & BYTE_MASK);
+            input >>= 6;
+        case 2:
+            --output;
+            *output = (char)((input | BYTE_MARK) & BYTE_MASK);
+            input >>= 6;
+        case 1:
+            --output;
+            *output = (char)(input | FIRST_BYTE_MARK[*length]);
+            break;
+        default:
+            TIXMLASSERT( false );
+    }
+}
+
+
+const char* XMLUtil::GetCharacterRef( const char* p, char* value, int* length )
+{
+    // Presume an entity, and pull it out.
+    *length = 0;
+
+    if ( *(p+1) == '#' && *(p+2) ) {
+        unsigned long ucs = 0;
+        TIXMLASSERT( sizeof( ucs ) >= 4 );
+        ptrdiff_t delta = 0;
+        unsigned mult = 1;
+        static const char SEMICOLON = ';';
+
+        if ( *(p+2) == 'x' ) {
+            // Hexadecimal.
+            const char* q = p+3;
+            if ( !(*q) ) {
+                return 0;
+            }
+
+            q = strchr( q, SEMICOLON );
+
+            if ( !q ) {
+                return 0;
+            }
+            TIXMLASSERT( *q == SEMICOLON );
+
+            delta = q-p;
+            --q;
+
+            while ( *q != 'x' ) {
+                unsigned int digit = 0;
+
+                if ( *q >= '0' && *q <= '9' ) {
+                    digit = *q - '0';
+                }
+                else if ( *q >= 'a' && *q <= 'f' ) {
+                    digit = *q - 'a' + 10;
+                }
+                else if ( *q >= 'A' && *q <= 'F' ) {
+                    digit = *q - 'A' + 10;
+                }
+                else {
+                    return 0;
+                }
+                TIXMLASSERT( digit < 16 );
+                TIXMLASSERT( digit == 0 || mult <= UINT_MAX / digit );
+                const unsigned int digitScaled = mult * digit;
+                TIXMLASSERT( ucs <= ULONG_MAX - digitScaled );
+                ucs += digitScaled;
+                TIXMLASSERT( mult <= UINT_MAX / 16 );
+                mult *= 16;
+                --q;
+            }
+        }
+        else {
+            // Decimal.
+            const char* q = p+2;
+            if ( !(*q) ) {
+                return 0;
+            }
+
+            q = strchr( q, SEMICOLON );
+
+            if ( !q ) {
+                return 0;
+            }
+            TIXMLASSERT( *q == SEMICOLON );
+
+            delta = q-p;
+            --q;
+
+            while ( *q != '#' ) {
+                if ( *q >= '0' && *q <= '9' ) {
+                    const unsigned int digit = *q - '0';
+                    TIXMLASSERT( digit < 10 );
+                    TIXMLASSERT( digit == 0 || mult <= UINT_MAX / digit );
+                    const unsigned int digitScaled = mult * digit;
+                    TIXMLASSERT( ucs <= ULONG_MAX - digitScaled );
+                    ucs += digitScaled;
+                }
+                else {
+                    return 0;
+                }
+                TIXMLASSERT( mult <= UINT_MAX / 10 );
+                mult *= 10;
+                --q;
+            }
+        }
+        // convert the UCS to UTF-8
+        ConvertUTF32ToUTF8( ucs, value, length );
+        return p + delta + 1;
+    }
+    return p+1;
+}
+
+
+void XMLUtil::ToStr( int v, char* buffer, int bufferSize )
+{
+    TIXML_SNPRINTF( buffer, bufferSize, "%d", v );
+}
+
+
+void XMLUtil::ToStr( unsigned v, char* buffer, int bufferSize )
+{
+    TIXML_SNPRINTF( buffer, bufferSize, "%u", v );
+}
+
+
+void XMLUtil::ToStr( bool v, char* buffer, int bufferSize )
+{
+    TIXML_SNPRINTF( buffer, bufferSize, "%d", v ? 1 : 0 );
+}
+
+/*
+	ToStr() of a number is a very tricky topic.
+	https://github.com/leethomason/tinyxml2/issues/106
+*/
+void XMLUtil::ToStr( float v, char* buffer, int bufferSize )
+{
+    TIXML_SNPRINTF( buffer, bufferSize, "%.8g", v );
+}
+
+
+void XMLUtil::ToStr( double v, char* buffer, int bufferSize )
+{
+    TIXML_SNPRINTF( buffer, bufferSize, "%.17g", v );
+}
+
+
+bool XMLUtil::ToInt( const char* str, int* value )
+{
+    if ( TIXML_SSCANF( str, "%d", value ) == 1 ) {
+        return true;
+    }
+    return false;
+}
+
+bool XMLUtil::ToUnsigned( const char* str, unsigned *value )
+{
+    if ( TIXML_SSCANF( str, "%u", value ) == 1 ) {
+        return true;
+    }
+    return false;
+}
+
+bool XMLUtil::ToBool( const char* str, bool* value )
+{
+    int ival = 0;
+    if ( ToInt( str, &ival )) {
+        *value = (ival==0) ? false : true;
+        return true;
+    }
+    if ( StringEqual( str, "true" ) ) {
+        *value = true;
+        return true;
+    }
+    else if ( StringEqual( str, "false" ) ) {
+        *value = false;
+        return true;
+    }
+    return false;
+}
+
+
+bool XMLUtil::ToFloat( const char* str, float* value )
+{
+    if ( TIXML_SSCANF( str, "%f", value ) == 1 ) {
+        return true;
+    }
+    return false;
+}
+
+bool XMLUtil::ToDouble( const char* str, double* value )
+{
+    if ( TIXML_SSCANF( str, "%lf", value ) == 1 ) {
+        return true;
+    }
+    return false;
+}
+
+
+char* XMLDocument::Identify( char* p, XMLNode** node )
+{
+    TIXMLASSERT( node );
+    TIXMLASSERT( p );
+    char* const start = p;
+    p = XMLUtil::SkipWhiteSpace( p );
+    if( !*p ) {
+        *node = 0;
+        TIXMLASSERT( p );
+        return p;
+    }
+
+    // These strings define the matching patterns:
+    static const char* xmlHeader		= { "<?" };
+    static const char* commentHeader	= { "<!--" };
+    static const char* cdataHeader		= { "<![CDATA[" };
+    static const char* dtdHeader		= { "<!" };
+    static const char* elementHeader	= { "<" };	// and a header for everything else; check last.
+
+    static const int xmlHeaderLen		= 2;
+    static const int commentHeaderLen	= 4;
+    static const int cdataHeaderLen		= 9;
+    static const int dtdHeaderLen		= 2;
+    static const int elementHeaderLen	= 1;
+
+    TIXMLASSERT( sizeof( XMLComment ) == sizeof( XMLUnknown ) );		// use same memory pool
+    TIXMLASSERT( sizeof( XMLComment ) == sizeof( XMLDeclaration ) );	// use same memory pool
+    XMLNode* returnNode = 0;
+    if ( XMLUtil::StringEqual( p, xmlHeader, xmlHeaderLen ) ) {
+        TIXMLASSERT( sizeof( XMLDeclaration ) == _commentPool.ItemSize() );
+        returnNode = new (_commentPool.Alloc()) XMLDeclaration( this );
+        returnNode->_memPool = &_commentPool;
+        p += xmlHeaderLen;
+    }
+    else if ( XMLUtil::StringEqual( p, commentHeader, commentHeaderLen ) ) {
+        TIXMLASSERT( sizeof( XMLComment ) == _commentPool.ItemSize() );
+        returnNode = new (_commentPool.Alloc()) XMLComment( this );
+        returnNode->_memPool = &_commentPool;
+        p += commentHeaderLen;
+    }
+    else if ( XMLUtil::StringEqual( p, cdataHeader, cdataHeaderLen ) ) {
+        TIXMLASSERT( sizeof( XMLText ) == _textPool.ItemSize() );
+        XMLText* text = new (_textPool.Alloc()) XMLText( this );
+        returnNode = text;
+        returnNode->_memPool = &_textPool;
+        p += cdataHeaderLen;
+        text->SetCData( true );
+    }
+    else if ( XMLUtil::StringEqual( p, dtdHeader, dtdHeaderLen ) ) {
+        TIXMLASSERT( sizeof( XMLUnknown ) == _commentPool.ItemSize() );
+        returnNode = new (_commentPool.Alloc()) XMLUnknown( this );
+        returnNode->_memPool = &_commentPool;
+        p += dtdHeaderLen;
+    }
+    else if ( XMLUtil::StringEqual( p, elementHeader, elementHeaderLen ) ) {
+        TIXMLASSERT( sizeof( XMLElement ) == _elementPool.ItemSize() );
+        returnNode = new (_elementPool.Alloc()) XMLElement( this );
+        returnNode->_memPool = &_elementPool;
+        p += elementHeaderLen;
+    }
+    else {
+        TIXMLASSERT( sizeof( XMLText ) == _textPool.ItemSize() );
+        returnNode = new (_textPool.Alloc()) XMLText( this );
+        returnNode->_memPool = &_textPool;
+        p = start;	// Back it up, all the text counts.
+    }
+
+    TIXMLASSERT( returnNode );
+    TIXMLASSERT( p );
+    *node = returnNode;
+    return p;
+}
+
+
+bool XMLDocument::Accept( XMLVisitor* visitor ) const
+{
+    TIXMLASSERT( visitor );
+    if ( visitor->VisitEnter( *this ) ) {
+        for ( const XMLNode* node=FirstChild(); node; node=node->NextSibling() ) {
+            if ( !node->Accept( visitor ) ) {
+                break;
+            }
+        }
+    }
+    return visitor->VisitExit( *this );
+}
+
+
+// --------- XMLNode ----------- //
+
+XMLNode::XMLNode( XMLDocument* doc ) :
+    _document( doc ),
+    _parent( 0 ),
+    _firstChild( 0 ), _lastChild( 0 ),
+    _prev( 0 ), _next( 0 ),
+    _memPool( 0 )
+{
+}
+
+
+XMLNode::~XMLNode()
+{
+    DeleteChildren();
+    if ( _parent ) {
+        _parent->Unlink( this );
+    }
+}
+
+const char* XMLNode::Value() const 
+{
+    // Catch an edge case: XMLDocuments don't have a a Value. Carefully return nullptr.
+    if ( this->ToDocument() )
+        return 0;
+    return _value.GetStr();
+}
+
+void XMLNode::SetValue( const char* str, bool staticMem )
+{
+    if ( staticMem ) {
+        _value.SetInternedStr( str );
+    }
+    else {
+        _value.SetStr( str );
+    }
+}
+
+
+void XMLNode::DeleteChildren()
+{
+    while( _firstChild ) {
+        TIXMLASSERT( _lastChild );
+        TIXMLASSERT( _firstChild->_document == _document );
+        XMLNode* node = _firstChild;
+        Unlink( node );
+
+        DeleteNode( node );
+    }
+    _firstChild = _lastChild = 0;
+}
+
+
+void XMLNode::Unlink( XMLNode* child )
+{
+    TIXMLASSERT( child );
+    TIXMLASSERT( child->_document == _document );
+    TIXMLASSERT( child->_parent == this );
+    if ( child == _firstChild ) {
+        _firstChild = _firstChild->_next;
+    }
+    if ( child == _lastChild ) {
+        _lastChild = _lastChild->_prev;
+    }
+
+    if ( child->_prev ) {
+        child->_prev->_next = child->_next;
+    }
+    if ( child->_next ) {
+        child->_next->_prev = child->_prev;
+    }
+	child->_parent = 0;
+}
+
+
+void XMLNode::DeleteChild( XMLNode* node )
+{
+    TIXMLASSERT( node );
+    TIXMLASSERT( node->_document == _document );
+    TIXMLASSERT( node->_parent == this );
+    Unlink( node );
+    DeleteNode( node );
+}
+
+
+XMLNode* XMLNode::InsertEndChild( XMLNode* addThis )
+{
+    TIXMLASSERT( addThis );
+    if ( addThis->_document != _document ) {
+        TIXMLASSERT( false );
+        return 0;
+    }
+    InsertChildPreamble( addThis );
+
+    if ( _lastChild ) {
+        TIXMLASSERT( _firstChild );
+        TIXMLASSERT( _lastChild->_next == 0 );
+        _lastChild->_next = addThis;
+        addThis->_prev = _lastChild;
+        _lastChild = addThis;
+
+        addThis->_next = 0;
+    }
+    else {
+        TIXMLASSERT( _firstChild == 0 );
+        _firstChild = _lastChild = addThis;
+
+        addThis->_prev = 0;
+        addThis->_next = 0;
+    }
+    addThis->_parent = this;
+    return addThis;
+}
+
+
+XMLNode* XMLNode::InsertFirstChild( XMLNode* addThis )
+{
+    TIXMLASSERT( addThis );
+    if ( addThis->_document != _document ) {
+        TIXMLASSERT( false );
+        return 0;
+    }
+    InsertChildPreamble( addThis );
+
+    if ( _firstChild ) {
+        TIXMLASSERT( _lastChild );
+        TIXMLASSERT( _firstChild->_prev == 0 );
+
+        _firstChild->_prev = addThis;
+        addThis->_next = _firstChild;
+        _firstChild = addThis;
+
+        addThis->_prev = 0;
+    }
+    else {
+        TIXMLASSERT( _lastChild == 0 );
+        _firstChild = _lastChild = addThis;
+
+        addThis->_prev = 0;
+        addThis->_next = 0;
+    }
+    addThis->_parent = this;
+    return addThis;
+}
+
+
+XMLNode* XMLNode::InsertAfterChild( XMLNode* afterThis, XMLNode* addThis )
+{
+    TIXMLASSERT( addThis );
+    if ( addThis->_document != _document ) {
+        TIXMLASSERT( false );
+        return 0;
+    }
+
+    TIXMLASSERT( afterThis );
+
+    if ( afterThis->_parent != this ) {
+        TIXMLASSERT( false );
+        return 0;
+    }
+
+    if ( afterThis->_next == 0 ) {
+        // The last node or the only node.
+        return InsertEndChild( addThis );
+    }
+    InsertChildPreamble( addThis );
+    addThis->_prev = afterThis;
+    addThis->_next = afterThis->_next;
+    afterThis->_next->_prev = addThis;
+    afterThis->_next = addThis;
+    addThis->_parent = this;
+    return addThis;
+}
+
+
+
+
+const XMLElement* XMLNode::FirstChildElement( const char* name ) const
+{
+    for( const XMLNode* node = _firstChild; node; node = node->_next ) {
+        const XMLElement* element = node->ToElement();
+        if ( element ) {
+            if ( !name || XMLUtil::StringEqual( element->Name(), name ) ) {
+                return element;
+            }
+        }
+    }
+    return 0;
+}
+
+
+const XMLElement* XMLNode::LastChildElement( const char* name ) const
+{
+    for( const XMLNode* node = _lastChild; node; node = node->_prev ) {
+        const XMLElement* element = node->ToElement();
+        if ( element ) {
+            if ( !name || XMLUtil::StringEqual( element->Name(), name ) ) {
+                return element;
+            }
+        }
+    }
+    return 0;
+}
+
+
+const XMLElement* XMLNode::NextSiblingElement( const char* name ) const
+{
+    for( const XMLNode* node = _next; node; node = node->_next ) {
+        const XMLElement* element = node->ToElement();
+        if ( element
+                && (!name || XMLUtil::StringEqual( name, element->Name() ))) {
+            return element;
+        }
+    }
+    return 0;
+}
+
+
+const XMLElement* XMLNode::PreviousSiblingElement( const char* name ) const
+{
+    for( const XMLNode* node = _prev; node; node = node->_prev ) {
+        const XMLElement* element = node->ToElement();
+        if ( element
+                && (!name || XMLUtil::StringEqual( name, element->Name() ))) {
+            return element;
+        }
+    }
+    return 0;
+}
+
+
+char* XMLNode::ParseDeep( char* p, StrPair* parentEnd )
+{
+    // This is a recursive method, but thinking about it "at the current level"
+    // it is a pretty simple flat list:
+    //		<foo/>
+    //		<!-- comment -->
+    //
+    // With a special case:
+    //		<foo>
+    //		</foo>
+    //		<!-- comment -->
+    //
+    // Where the closing element (/foo) *must* be the next thing after the opening
+    // element, and the names must match. BUT the tricky bit is that the closing
+    // element will be read by the child.
+    //
+    // 'endTag' is the end tag for this node, it is returned by a call to a child.
+    // 'parentEnd' is the end tag for the parent, which is filled in and returned.
+
+    while( p && *p ) {
+        XMLNode* node = 0;
+
+        p = _document->Identify( p, &node );
+        if ( node == 0 ) {
+            break;
+        }
+
+        StrPair endTag;
+        p = node->ParseDeep( p, &endTag );
+        if ( !p ) {
+            DeleteNode( node );
+            if ( !_document->Error() ) {
+                _document->SetError( XML_ERROR_PARSING, 0, 0 );
+            }
+            break;
+        }
+
+        XMLDeclaration* decl = node->ToDeclaration();
+        if ( decl ) {
+                // A declaration can only be the first child of a document.
+                // Set error, if document already has children.
+                if ( !_document->NoChildren() ) {
+                        _document->SetError( XML_ERROR_PARSING_DECLARATION, decl->Value(), 0);
+                        DeleteNode( decl );
+                        break;
+                }
+        }
+
+        XMLElement* ele = node->ToElement();
+        if ( ele ) {
+            // We read the end tag. Return it to the parent.
+            if ( ele->ClosingType() == XMLElement::CLOSING ) {
+                if ( parentEnd ) {
+                    ele->_value.TransferTo( parentEnd );
+                }
+                node->_memPool->SetTracked();   // created and then immediately deleted.
+                DeleteNode( node );
+                return p;
+            }
+
+            // Handle an end tag returned to this level.
+            // And handle a bunch of annoying errors.
+            bool mismatch = false;
+            if ( endTag.Empty() ) {
+                if ( ele->ClosingType() == XMLElement::OPEN ) {
+                    mismatch = true;
+                }
+            }
+            else {
+                if ( ele->ClosingType() != XMLElement::OPEN ) {
+                    mismatch = true;
+                }
+                else if ( !XMLUtil::StringEqual( endTag.GetStr(), ele->Name() ) ) {
+                    mismatch = true;
+                }
+            }
+            if ( mismatch ) {
+                _document->SetError( XML_ERROR_MISMATCHED_ELEMENT, ele->Name(), 0 );
+                DeleteNode( node );
+                break;
+            }
+        }
+        InsertEndChild( node );
+    }
+    return 0;
+}
+
+void XMLNode::DeleteNode( XMLNode* node )
+{
+    if ( node == 0 ) {
+        return;
+    }
+    MemPool* pool = node->_memPool;
+    node->~XMLNode();
+    pool->Free( node );
+}
+
+void XMLNode::InsertChildPreamble( XMLNode* insertThis ) const
+{
+    TIXMLASSERT( insertThis );
+    TIXMLASSERT( insertThis->_document == _document );
+
+    if ( insertThis->_parent )
+        insertThis->_parent->Unlink( insertThis );
+    else
+        insertThis->_memPool->SetTracked();
+}
+
+// --------- XMLText ---------- //
+char* XMLText::ParseDeep( char* p, StrPair* )
+{
+    const char* start = p;
+    if ( this->CData() ) {
+        p = _value.ParseText( p, "]]>", StrPair::NEEDS_NEWLINE_NORMALIZATION );
+        if ( !p ) {
+            _document->SetError( XML_ERROR_PARSING_CDATA, start, 0 );
+        }
+        return p;
+    }
+    else {
+        int flags = _document->ProcessEntities() ? StrPair::TEXT_ELEMENT : StrPair::TEXT_ELEMENT_LEAVE_ENTITIES;
+        if ( _document->WhitespaceMode() == COLLAPSE_WHITESPACE ) {
+            flags |= StrPair::NEEDS_WHITESPACE_COLLAPSING;
+        }
+
+        p = _value.ParseText( p, "<", flags );
+        if ( p && *p ) {
+            return p-1;
+        }
+        if ( !p ) {
+            _document->SetError( XML_ERROR_PARSING_TEXT, start, 0 );
+        }
+    }
+    return 0;
+}
+
+
+XMLNode* XMLText::ShallowClone( XMLDocument* doc ) const
+{
+    if ( !doc ) {
+        doc = _document;
+    }
+    XMLText* text = doc->NewText( Value() );	// fixme: this will always allocate memory. Intern?
+    text->SetCData( this->CData() );
+    return text;
+}
+
+
+bool XMLText::ShallowEqual( const XMLNode* compare ) const
+{
+    const XMLText* text = compare->ToText();
+    return ( text && XMLUtil::StringEqual( text->Value(), Value() ) );
+}
+
+
+bool XMLText::Accept( XMLVisitor* visitor ) const
+{
+    TIXMLASSERT( visitor );
+    return visitor->Visit( *this );
+}
+
+
+// --------- XMLComment ---------- //
+
+XMLComment::XMLComment( XMLDocument* doc ) : XMLNode( doc )
+{
+}
+
+
+XMLComment::~XMLComment()
+{
+}
+
+
+char* XMLComment::ParseDeep( char* p, StrPair* )
+{
+    // Comment parses as text.
+    const char* start = p;
+    p = _value.ParseText( p, "-->", StrPair::COMMENT );
+    if ( p == 0 ) {
+        _document->SetError( XML_ERROR_PARSING_COMMENT, start, 0 );
+    }
+    return p;
+}
+
+
+XMLNode* XMLComment::ShallowClone( XMLDocument* doc ) const
+{
+    if ( !doc ) {
+        doc = _document;
+    }
+    XMLComment* comment = doc->NewComment( Value() );	// fixme: this will always allocate memory. Intern?
+    return comment;
+}
+
+
+bool XMLComment::ShallowEqual( const XMLNode* compare ) const
+{
+    TIXMLASSERT( compare );
+    const XMLComment* comment = compare->ToComment();
+    return ( comment && XMLUtil::StringEqual( comment->Value(), Value() ));
+}
+
+
+bool XMLComment::Accept( XMLVisitor* visitor ) const
+{
+    TIXMLASSERT( visitor );
+    return visitor->Visit( *this );
+}
+
+
+// --------- XMLDeclaration ---------- //
+
+XMLDeclaration::XMLDeclaration( XMLDocument* doc ) : XMLNode( doc )
+{
+}
+
+
+XMLDeclaration::~XMLDeclaration()
+{
+    //printf( "~XMLDeclaration\n" );
+}
+
+
+char* XMLDeclaration::ParseDeep( char* p, StrPair* )
+{
+    // Declaration parses as text.
+    const char* start = p;
+    p = _value.ParseText( p, "?>", StrPair::NEEDS_NEWLINE_NORMALIZATION );
+    if ( p == 0 ) {
+        _document->SetError( XML_ERROR_PARSING_DECLARATION, start, 0 );
+    }
+    return p;
+}
+
+
+XMLNode* XMLDeclaration::ShallowClone( XMLDocument* doc ) const
+{
+    if ( !doc ) {
+        doc = _document;
+    }
+    XMLDeclaration* dec = doc->NewDeclaration( Value() );	// fixme: this will always allocate memory. Intern?
+    return dec;
+}
+
+
+bool XMLDeclaration::ShallowEqual( const XMLNode* compare ) const
+{
+    TIXMLASSERT( compare );
+    const XMLDeclaration* declaration = compare->ToDeclaration();
+    return ( declaration && XMLUtil::StringEqual( declaration->Value(), Value() ));
+}
+
+
+
+bool XMLDeclaration::Accept( XMLVisitor* visitor ) const
+{
+    TIXMLASSERT( visitor );
+    return visitor->Visit( *this );
+}
+
+// --------- XMLUnknown ---------- //
+
+XMLUnknown::XMLUnknown( XMLDocument* doc ) : XMLNode( doc )
+{
+}
+
+
+XMLUnknown::~XMLUnknown()
+{
+}
+
+
+char* XMLUnknown::ParseDeep( char* p, StrPair* )
+{
+    // Unknown parses as text.
+    const char* start = p;
+
+    p = _value.ParseText( p, ">", StrPair::NEEDS_NEWLINE_NORMALIZATION );
+    if ( !p ) {
+        _document->SetError( XML_ERROR_PARSING_UNKNOWN, start, 0 );
+    }
+    return p;
+}
+
+
+XMLNode* XMLUnknown::ShallowClone( XMLDocument* doc ) const
+{
+    if ( !doc ) {
+        doc = _document;
+    }
+    XMLUnknown* text = doc->NewUnknown( Value() );	// fixme: this will always allocate memory. Intern?
+    return text;
+}
+
+
+bool XMLUnknown::ShallowEqual( const XMLNode* compare ) const
+{
+    TIXMLASSERT( compare );
+    const XMLUnknown* unknown = compare->ToUnknown();
+    return ( unknown && XMLUtil::StringEqual( unknown->Value(), Value() ));
+}
+
+
+bool XMLUnknown::Accept( XMLVisitor* visitor ) const
+{
+    TIXMLASSERT( visitor );
+    return visitor->Visit( *this );
+}
+
+// --------- XMLAttribute ---------- //
+
+const char* XMLAttribute::Name() const 
+{
+    return _name.GetStr();
+}
+
+const char* XMLAttribute::Value() const 
+{
+    return _value.GetStr();
+}
+
+char* XMLAttribute::ParseDeep( char* p, bool processEntities )
+{
+    // Parse using the name rules: bug fix, was using ParseText before
+    p = _name.ParseName( p );
+    if ( !p || !*p ) {
+        return 0;
+    }
+
+    // Skip white space before =
+    p = XMLUtil::SkipWhiteSpace( p );
+    if ( *p != '=' ) {
+        return 0;
+    }
+
+    ++p;	// move up to opening quote
+    p = XMLUtil::SkipWhiteSpace( p );
+    if ( *p != '\"' && *p != '\'' ) {
+        return 0;
+    }
+
+    char endTag[2] = { *p, 0 };
+    ++p;	// move past opening quote
+
+    p = _value.ParseText( p, endTag, processEntities ? StrPair::ATTRIBUTE_VALUE : StrPair::ATTRIBUTE_VALUE_LEAVE_ENTITIES );
+    return p;
+}
+
+
+void XMLAttribute::SetName( const char* n )
+{
+    _name.SetStr( n );
+}
+
+
+XMLError XMLAttribute::QueryIntValue( int* value ) const
+{
+    if ( XMLUtil::ToInt( Value(), value )) {
+        return XML_NO_ERROR;
+    }
+    return XML_WRONG_ATTRIBUTE_TYPE;
+}
+
+
+XMLError XMLAttribute::QueryUnsignedValue( unsigned int* value ) const
+{
+    if ( XMLUtil::ToUnsigned( Value(), value )) {
+        return XML_NO_ERROR;
+    }
+    return XML_WRONG_ATTRIBUTE_TYPE;
+}
+
+
+XMLError XMLAttribute::QueryBoolValue( bool* value ) const
+{
+    if ( XMLUtil::ToBool( Value(), value )) {
+        return XML_NO_ERROR;
+    }
+    return XML_WRONG_ATTRIBUTE_TYPE;
+}
+
+
+XMLError XMLAttribute::QueryFloatValue( float* value ) const
+{
+    if ( XMLUtil::ToFloat( Value(), value )) {
+        return XML_NO_ERROR;
+    }
+    return XML_WRONG_ATTRIBUTE_TYPE;
+}
+
+
+XMLError XMLAttribute::QueryDoubleValue( double* value ) const
+{
+    if ( XMLUtil::ToDouble( Value(), value )) {
+        return XML_NO_ERROR;
+    }
+    return XML_WRONG_ATTRIBUTE_TYPE;
+}
+
+
+void XMLAttribute::SetAttribute( const char* v )
+{
+    _value.SetStr( v );
+}
+
+
+void XMLAttribute::SetAttribute( int v )
+{
+    char buf[BUF_SIZE];
+    XMLUtil::ToStr( v, buf, BUF_SIZE );
+    _value.SetStr( buf );
+}
+
+
+void XMLAttribute::SetAttribute( unsigned v )
+{
+    char buf[BUF_SIZE];
+    XMLUtil::ToStr( v, buf, BUF_SIZE );
+    _value.SetStr( buf );
+}
+
+
+void XMLAttribute::SetAttribute( bool v )
+{
+    char buf[BUF_SIZE];
+    XMLUtil::ToStr( v, buf, BUF_SIZE );
+    _value.SetStr( buf );
+}
+
+void XMLAttribute::SetAttribute( double v )
+{
+    char buf[BUF_SIZE];
+    XMLUtil::ToStr( v, buf, BUF_SIZE );
+    _value.SetStr( buf );
+}
+
+void XMLAttribute::SetAttribute( float v )
+{
+    char buf[BUF_SIZE];
+    XMLUtil::ToStr( v, buf, BUF_SIZE );
+    _value.SetStr( buf );
+}
+
+
+// --------- XMLElement ---------- //
+XMLElement::XMLElement( XMLDocument* doc ) : XMLNode( doc ),
+    _closingType( 0 ),
+    _rootAttribute( 0 )
+{
+}
+
+
+XMLElement::~XMLElement()
+{
+    while( _rootAttribute ) {
+        XMLAttribute* next = _rootAttribute->_next;
+        DeleteAttribute( _rootAttribute );
+        _rootAttribute = next;
+    }
+}
+
+
+const XMLAttribute* XMLElement::FindAttribute( const char* name ) const
+{
+    for( XMLAttribute* a = _rootAttribute; a; a = a->_next ) {
+        if ( XMLUtil::StringEqual( a->Name(), name ) ) {
+            return a;
+        }
+    }
+    return 0;
+}
+
+
+const char* XMLElement::Attribute( const char* name, const char* value ) const
+{
+    const XMLAttribute* a = FindAttribute( name );
+    if ( !a ) {
+        return 0;
+    }
+    if ( !value || XMLUtil::StringEqual( a->Value(), value )) {
+        return a->Value();
+    }
+    return 0;
+}
+
+
+const char* XMLElement::GetText() const
+{
+    if ( FirstChild() && FirstChild()->ToText() ) {
+        return FirstChild()->Value();
+    }
+    return 0;
+}
+
+
+void	XMLElement::SetText( const char* inText )
+{
+	if ( FirstChild() && FirstChild()->ToText() )
+		FirstChild()->SetValue( inText );
+	else {
+		XMLText*	theText = GetDocument()->NewText( inText );
+		InsertFirstChild( theText );
+	}
+}
+
+
+void XMLElement::SetText( int v ) 
+{
+    char buf[BUF_SIZE];
+    XMLUtil::ToStr( v, buf, BUF_SIZE );
+    SetText( buf );
+}
+
+
+void XMLElement::SetText( unsigned v ) 
+{
+    char buf[BUF_SIZE];
+    XMLUtil::ToStr( v, buf, BUF_SIZE );
+    SetText( buf );
+}
+
+
+void XMLElement::SetText( bool v ) 
+{
+    char buf[BUF_SIZE];
+    XMLUtil::ToStr( v, buf, BUF_SIZE );
+    SetText( buf );
+}
+
+
+void XMLElement::SetText( float v ) 
+{
+    char buf[BUF_SIZE];
+    XMLUtil::ToStr( v, buf, BUF_SIZE );
+    SetText( buf );
+}
+
+
+void XMLElement::SetText( double v ) 
+{
+    char buf[BUF_SIZE];
+    XMLUtil::ToStr( v, buf, BUF_SIZE );
+    SetText( buf );
+}
+
+
+XMLError XMLElement::QueryIntText( int* ival ) const
+{
+    if ( FirstChild() && FirstChild()->ToText() ) {
+        const char* t = FirstChild()->Value();
+        if ( XMLUtil::ToInt( t, ival ) ) {
+            return XML_SUCCESS;
+        }
+        return XML_CAN_NOT_CONVERT_TEXT;
+    }
+    return XML_NO_TEXT_NODE;
+}
+
+
+XMLError XMLElement::QueryUnsignedText( unsigned* uval ) const
+{
+    if ( FirstChild() && FirstChild()->ToText() ) {
+        const char* t = FirstChild()->Value();
+        if ( XMLUtil::ToUnsigned( t, uval ) ) {
+            return XML_SUCCESS;
+        }
+        return XML_CAN_NOT_CONVERT_TEXT;
+    }
+    return XML_NO_TEXT_NODE;
+}
+
+
+XMLError XMLElement::QueryBoolText( bool* bval ) const
+{
+    if ( FirstChild() && FirstChild()->ToText() ) {
+        const char* t = FirstChild()->Value();
+        if ( XMLUtil::ToBool( t, bval ) ) {
+            return XML_SUCCESS;
+        }
+        return XML_CAN_NOT_CONVERT_TEXT;
+    }
+    return XML_NO_TEXT_NODE;
+}
+
+
+XMLError XMLElement::QueryDoubleText( double* dval ) const
+{
+    if ( FirstChild() && FirstChild()->ToText() ) {
+        const char* t = FirstChild()->Value();
+        if ( XMLUtil::ToDouble( t, dval ) ) {
+            return XML_SUCCESS;
+        }
+        return XML_CAN_NOT_CONVERT_TEXT;
+    }
+    return XML_NO_TEXT_NODE;
+}
+
+
+XMLError XMLElement::QueryFloatText( float* fval ) const
+{
+    if ( FirstChild() && FirstChild()->ToText() ) {
+        const char* t = FirstChild()->Value();
+        if ( XMLUtil::ToFloat( t, fval ) ) {
+            return XML_SUCCESS;
+        }
+        return XML_CAN_NOT_CONVERT_TEXT;
+    }
+    return XML_NO_TEXT_NODE;
+}
+
+
+
+XMLAttribute* XMLElement::FindOrCreateAttribute( const char* name )
+{
+    XMLAttribute* last = 0;
+    XMLAttribute* attrib = 0;
+    for( attrib = _rootAttribute;
+            attrib;
+            last = attrib, attrib = attrib->_next ) {
+        if ( XMLUtil::StringEqual( attrib->Name(), name ) ) {
+            break;
+        }
+    }
+    if ( !attrib ) {
+        TIXMLASSERT( sizeof( XMLAttribute ) == _document->_attributePool.ItemSize() );
+        attrib = new (_document->_attributePool.Alloc() ) XMLAttribute();
+        attrib->_memPool = &_document->_attributePool;
+        if ( last ) {
+            last->_next = attrib;
+        }
+        else {
+            _rootAttribute = attrib;
+        }
+        attrib->SetName( name );
+        attrib->_memPool->SetTracked(); // always created and linked.
+    }
+    return attrib;
+}
+
+
+void XMLElement::DeleteAttribute( const char* name )
+{
+    XMLAttribute* prev = 0;
+    for( XMLAttribute* a=_rootAttribute; a; a=a->_next ) {
+        if ( XMLUtil::StringEqual( name, a->Name() ) ) {
+            if ( prev ) {
+                prev->_next = a->_next;
+            }
+            else {
+                _rootAttribute = a->_next;
+            }
+            DeleteAttribute( a );
+            break;
+        }
+        prev = a;
+    }
+}
+
+
+char* XMLElement::ParseAttributes( char* p )
+{
+    const char* start = p;
+    XMLAttribute* prevAttribute = 0;
+
+    // Read the attributes.
+    while( p ) {
+        p = XMLUtil::SkipWhiteSpace( p );
+        if ( !(*p) ) {
+            _document->SetError( XML_ERROR_PARSING_ELEMENT, start, Name() );
+            return 0;
+        }
+
+        // attribute.
+        if (XMLUtil::IsNameStartChar( *p ) ) {
+            TIXMLASSERT( sizeof( XMLAttribute ) == _document->_attributePool.ItemSize() );
+            XMLAttribute* attrib = new (_document->_attributePool.Alloc() ) XMLAttribute();
+            attrib->_memPool = &_document->_attributePool;
+			attrib->_memPool->SetTracked();
+
+            p = attrib->ParseDeep( p, _document->ProcessEntities() );
+            if ( !p || Attribute( attrib->Name() ) ) {
+                DeleteAttribute( attrib );
+                _document->SetError( XML_ERROR_PARSING_ATTRIBUTE, start, p );
+                return 0;
+            }
+            // There is a minor bug here: if the attribute in the source xml
+            // document is duplicated, it will not be detected and the
+            // attribute will be doubly added. However, tracking the 'prevAttribute'
+            // avoids re-scanning the attribute list. Preferring performance for
+            // now, may reconsider in the future.
+            if ( prevAttribute ) {
+                prevAttribute->_next = attrib;
+            }
+            else {
+                _rootAttribute = attrib;
+            }
+            prevAttribute = attrib;
+        }
+        // end of the tag
+        else if ( *p == '>' ) {
+            ++p;
+            break;
+        }
+        // end of the tag
+        else if ( *p == '/' && *(p+1) == '>' ) {
+            _closingType = CLOSED;
+            return p+2;	// done; sealed element.
+        }
+        else {
+            _document->SetError( XML_ERROR_PARSING_ELEMENT, start, p );
+            return 0;
+        }
+    }
+    return p;
+}
+
+void XMLElement::DeleteAttribute( XMLAttribute* attribute )
+{
+    if ( attribute == 0 ) {
+        return;
+    }
+    MemPool* pool = attribute->_memPool;
+    attribute->~XMLAttribute();
+    pool->Free( attribute );
+}
+
+//
+//	<ele></ele>
+//	<ele>foo<b>bar</b></ele>
+//
+char* XMLElement::ParseDeep( char* p, StrPair* strPair )
+{
+    // Read the element name.
+    p = XMLUtil::SkipWhiteSpace( p );
+
+    // The closing element is the </element> form. It is
+    // parsed just like a regular element then deleted from
+    // the DOM.
+    if ( *p == '/' ) {
+        _closingType = CLOSING;
+        ++p;
+    }
+
+    p = _value.ParseName( p );
+    if ( _value.Empty() ) {
+        return 0;
+    }
+
+    p = ParseAttributes( p );
+    if ( !p || !*p || _closingType ) {
+        return p;
+    }
+
+    p = XMLNode::ParseDeep( p, strPair );
+    return p;
+}
+
+
+
+XMLNode* XMLElement::ShallowClone( XMLDocument* doc ) const
+{
+    if ( !doc ) {
+        doc = _document;
+    }
+    XMLElement* element = doc->NewElement( Value() );					// fixme: this will always allocate memory. Intern?
+    for( const XMLAttribute* a=FirstAttribute(); a; a=a->Next() ) {
+        element->SetAttribute( a->Name(), a->Value() );					// fixme: this will always allocate memory. Intern?
+    }
+    return element;
+}
+
+
+bool XMLElement::ShallowEqual( const XMLNode* compare ) const
+{
+    TIXMLASSERT( compare );
+    const XMLElement* other = compare->ToElement();
+    if ( other && XMLUtil::StringEqual( other->Name(), Name() )) {
+
+        const XMLAttribute* a=FirstAttribute();
+        const XMLAttribute* b=other->FirstAttribute();
+
+        while ( a && b ) {
+            if ( !XMLUtil::StringEqual( a->Value(), b->Value() ) ) {
+                return false;
+            }
+            a = a->Next();
+            b = b->Next();
+        }
+        if ( a || b ) {
+            // different count
+            return false;
+        }
+        return true;
+    }
+    return false;
+}
+
+
+bool XMLElement::Accept( XMLVisitor* visitor ) const
+{
+    TIXMLASSERT( visitor );
+    if ( visitor->VisitEnter( *this, _rootAttribute ) ) {
+        for ( const XMLNode* node=FirstChild(); node; node=node->NextSibling() ) {
+            if ( !node->Accept( visitor ) ) {
+                break;
+            }
+        }
+    }
+    return visitor->VisitExit( *this );
+}
+
+
+// --------- XMLDocument ----------- //
+
+// Warning: List must match 'enum XMLError'
+const char* XMLDocument::_errorNames[XML_ERROR_COUNT] = {
+    "XML_SUCCESS",
+    "XML_NO_ATTRIBUTE",
+    "XML_WRONG_ATTRIBUTE_TYPE",
+    "XML_ERROR_FILE_NOT_FOUND",
+    "XML_ERROR_FILE_COULD_NOT_BE_OPENED",
+    "XML_ERROR_FILE_READ_ERROR",
+    "XML_ERROR_ELEMENT_MISMATCH",
+    "XML_ERROR_PARSING_ELEMENT",
+    "XML_ERROR_PARSING_ATTRIBUTE",
+    "XML_ERROR_IDENTIFYING_TAG",
+    "XML_ERROR_PARSING_TEXT",
+    "XML_ERROR_PARSING_CDATA",
+    "XML_ERROR_PARSING_COMMENT",
+    "XML_ERROR_PARSING_DECLARATION",
+    "XML_ERROR_PARSING_UNKNOWN",
+    "XML_ERROR_EMPTY_DOCUMENT",
+    "XML_ERROR_MISMATCHED_ELEMENT",
+    "XML_ERROR_PARSING",
+    "XML_CAN_NOT_CONVERT_TEXT",
+    "XML_NO_TEXT_NODE"
+};
+
+
+XMLDocument::XMLDocument( bool processEntities, Whitespace whitespace ) :
+    XMLNode( 0 ),
+    _writeBOM( false ),
+    _processEntities( processEntities ),
+    _errorID( XML_NO_ERROR ),
+    _whitespace( whitespace ),
+    _errorStr1( 0 ),
+    _errorStr2( 0 ),
+    _charBuffer( 0 )
+{
+    // avoid VC++ C4355 warning about 'this' in initializer list (C4355 is off by default in VS2012+)
+    _document = this;
+}
+
+
+XMLDocument::~XMLDocument()
+{
+    Clear();
+}
+
+
+void XMLDocument::Clear()
+{
+    DeleteChildren();
+
+#ifdef DEBUG
+    const bool hadError = Error();
+#endif
+    _errorID = XML_NO_ERROR;
+    _errorStr1 = 0;
+    _errorStr2 = 0;
+
+    delete [] _charBuffer;
+    _charBuffer = 0;
+
+#if 0
+    _textPool.Trace( "text" );
+    _elementPool.Trace( "element" );
+    _commentPool.Trace( "comment" );
+    _attributePool.Trace( "attribute" );
+#endif
+    
+#ifdef DEBUG
+    if ( !hadError ) {
+        TIXMLASSERT( _elementPool.CurrentAllocs()   == _elementPool.Untracked() );
+        TIXMLASSERT( _attributePool.CurrentAllocs() == _attributePool.Untracked() );
+        TIXMLASSERT( _textPool.CurrentAllocs()      == _textPool.Untracked() );
+        TIXMLASSERT( _commentPool.CurrentAllocs()   == _commentPool.Untracked() );
+    }
+#endif
+}
+
+
+XMLElement* XMLDocument::NewElement( const char* name )
+{
+    TIXMLASSERT( sizeof( XMLElement ) == _elementPool.ItemSize() );
+    XMLElement* ele = new (_elementPool.Alloc()) XMLElement( this );
+    ele->_memPool = &_elementPool;
+    ele->SetName( name );
+    return ele;
+}
+
+
+XMLComment* XMLDocument::NewComment( const char* str )
+{
+    TIXMLASSERT( sizeof( XMLComment ) == _commentPool.ItemSize() );
+    XMLComment* comment = new (_commentPool.Alloc()) XMLComment( this );
+    comment->_memPool = &_commentPool;
+    comment->SetValue( str );
+    return comment;
+}
+
+
+XMLText* XMLDocument::NewText( const char* str )
+{
+    TIXMLASSERT( sizeof( XMLText ) == _textPool.ItemSize() );
+    XMLText* text = new (_textPool.Alloc()) XMLText( this );
+    text->_memPool = &_textPool;
+    text->SetValue( str );
+    return text;
+}
+
+
+XMLDeclaration* XMLDocument::NewDeclaration( const char* str )
+{
+    TIXMLASSERT( sizeof( XMLDeclaration ) == _commentPool.ItemSize() );
+    XMLDeclaration* dec = new (_commentPool.Alloc()) XMLDeclaration( this );
+    dec->_memPool = &_commentPool;
+    dec->SetValue( str ? str : "xml version=\"1.0\" encoding=\"UTF-8\"" );
+    return dec;
+}
+
+
+XMLUnknown* XMLDocument::NewUnknown( const char* str )
+{
+    TIXMLASSERT( sizeof( XMLUnknown ) == _commentPool.ItemSize() );
+    XMLUnknown* unk = new (_commentPool.Alloc()) XMLUnknown( this );
+    unk->_memPool = &_commentPool;
+    unk->SetValue( str );
+    return unk;
+}
+
+static FILE* callfopen( const char* filepath, const char* mode )
+{
+    TIXMLASSERT( filepath );
+    TIXMLASSERT( mode );
+#if defined(_MSC_VER) && (_MSC_VER >= 1400 ) && (!defined WINCE)
+    FILE* fp = 0;
+    errno_t err = fopen_s( &fp, filepath, mode );
+    if ( err ) {
+        return 0;
+    }
+#else
+    FILE* fp = fopen( filepath, mode );
+#endif
+    return fp;
+}
+    
+void XMLDocument::DeleteNode( XMLNode* node )	{
+    TIXMLASSERT( node );
+    TIXMLASSERT(node->_document == this );
+    if (node->_parent) {
+        node->_parent->DeleteChild( node );
+    }
+    else {
+        // Isn't in the tree.
+        // Use the parent delete.
+        // Also, we need to mark it tracked: we 'know'
+        // it was never used.
+        node->_memPool->SetTracked();
+        // Call the static XMLNode version:
+        XMLNode::DeleteNode(node);
+    }
+}
+
+
+XMLError XMLDocument::LoadFile( const char* filename )
+{
+    Clear();
+    FILE* fp = callfopen( filename, "rb" );
+    if ( !fp ) {
+        SetError( XML_ERROR_FILE_NOT_FOUND, filename, 0 );
+        return _errorID;
+    }
+    LoadFile( fp );
+    fclose( fp );
+    return _errorID;
+}
+
+// This is likely overengineered template art to have a check that unsigned long value incremented
+// by one still fits into size_t. If size_t type is larger than unsigned long type
+// (x86_64-w64-mingw32 target) then the check is redundant and gcc and clang emit
+// -Wtype-limits warning. This piece makes the compiler select code with a check when a check
+// is useful and code with no check when a check is redundant depending on how size_t and unsigned long
+// types sizes relate to each other.
+template
+<bool = (sizeof(unsigned long) >= sizeof(size_t))>
+struct LongFitsIntoSizeTMinusOne {
+    static bool Fits( unsigned long value )
+    {
+        return value < (size_t)-1;
+    }
+};
+
+template <>
+bool LongFitsIntoSizeTMinusOne<false>::Fits( unsigned long /*value*/ )
+{
+    return true;
+}
+
+XMLError XMLDocument::LoadFile( FILE* fp )
+{
+    Clear();
+
+    fseek( fp, 0, SEEK_SET );
+    if ( fgetc( fp ) == EOF && ferror( fp ) != 0 ) {
+        SetError( XML_ERROR_FILE_READ_ERROR, 0, 0 );
+        return _errorID;
+    }
+
+    fseek( fp, 0, SEEK_END );
+    const long filelength = ftell( fp );
+    fseek( fp, 0, SEEK_SET );
+    if ( filelength == -1L ) {
+        SetError( XML_ERROR_FILE_READ_ERROR, 0, 0 );
+        return _errorID;
+    }
+    TIXMLASSERT( filelength >= 0 );
+
+    if ( !LongFitsIntoSizeTMinusOne<>::Fits( filelength ) ) {
+        // Cannot handle files which won't fit in buffer together with null terminator
+        SetError( XML_ERROR_FILE_READ_ERROR, 0, 0 );
+        return _errorID;
+    }
+
+    if ( filelength == 0 ) {
+        SetError( XML_ERROR_EMPTY_DOCUMENT, 0, 0 );
+        return _errorID;
+    }
+
+    const size_t size = filelength;
+    TIXMLASSERT( _charBuffer == 0 );
+    _charBuffer = new char[size+1];
+    size_t read = fread( _charBuffer, 1, size, fp );
+    if ( read != size ) {
+        SetError( XML_ERROR_FILE_READ_ERROR, 0, 0 );
+        return _errorID;
+    }
+
+    _charBuffer[size] = 0;
+
+    Parse();
+    return _errorID;
+}
+
+
+XMLError XMLDocument::SaveFile( const char* filename, bool compact )
+{
+    FILE* fp = callfopen( filename, "w" );
+    if ( !fp ) {
+        SetError( XML_ERROR_FILE_COULD_NOT_BE_OPENED, filename, 0 );
+        return _errorID;
+    }
+    SaveFile(fp, compact);
+    fclose( fp );
+    return _errorID;
+}
+
+
+XMLError XMLDocument::SaveFile( FILE* fp, bool compact )
+{
+    // Clear any error from the last save, otherwise it will get reported
+    // for *this* call.
+    SetError( XML_NO_ERROR, 0, 0 );
+    XMLPrinter stream( fp, compact );
+    Print( &stream );
+    return _errorID;
+}
+
+
+XMLError XMLDocument::Parse( const char* p, size_t len )
+{
+    Clear();
+
+    if ( len == 0 || !p || !*p ) {
+        SetError( XML_ERROR_EMPTY_DOCUMENT, 0, 0 );
+        return _errorID;
+    }
+    if ( len == (size_t)(-1) ) {
+        len = strlen( p );
+    }
+    TIXMLASSERT( _charBuffer == 0 );
+    _charBuffer = new char[ len+1 ];
+    memcpy( _charBuffer, p, len );
+    _charBuffer[len] = 0;
+
+    Parse();
+    if ( Error() ) {
+        // clean up now essentially dangling memory.
+        // and the parse fail can put objects in the
+        // pools that are dead and inaccessible.
+        DeleteChildren();
+        _elementPool.Clear();
+        _attributePool.Clear();
+        _textPool.Clear();
+        _commentPool.Clear();
+    }
+    return _errorID;
+}
+
+
+void XMLDocument::Print( XMLPrinter* streamer ) const
+{
+    if ( streamer ) {
+        Accept( streamer );
+    }
+    else {
+        XMLPrinter stdoutStreamer( stdout );
+        Accept( &stdoutStreamer );
+    }
+}
+
+
+void XMLDocument::SetError( XMLError error, const char* str1, const char* str2 )
+{
+    TIXMLASSERT( error >= 0 && error < XML_ERROR_COUNT );
+    _errorID = error;
+    _errorStr1 = str1;
+    _errorStr2 = str2;
+}
+
+const char* XMLDocument::ErrorName() const
+{
+	TIXMLASSERT( _errorID >= 0 && _errorID < XML_ERROR_COUNT );
+    const char* errorName = _errorNames[_errorID];
+    TIXMLASSERT( errorName && errorName[0] );
+    return errorName;
+}
+
+void XMLDocument::PrintError() const
+{
+    if ( Error() ) {
+        static const int LEN = 20;
+        char buf1[LEN] = { 0 };
+        char buf2[LEN] = { 0 };
+
+        if ( _errorStr1 ) {
+            TIXML_SNPRINTF( buf1, LEN, "%s", _errorStr1 );
+        }
+        if ( _errorStr2 ) {
+            TIXML_SNPRINTF( buf2, LEN, "%s", _errorStr2 );
+        }
+
+        // Should check INT_MIN <= _errorID && _errorId <= INT_MAX, but that
+        // causes a clang "always true" -Wtautological-constant-out-of-range-compare warning
+        TIXMLASSERT( 0 <= _errorID && XML_ERROR_COUNT - 1 <= INT_MAX );
+        printf( "XMLDocument error id=%d '%s' str1=%s str2=%s\n",
+                static_cast<int>( _errorID ), ErrorName(), buf1, buf2 );
+    }
+}
+
+void XMLDocument::Parse()
+{
+    TIXMLASSERT( NoChildren() ); // Clear() must have been called previously
+    TIXMLASSERT( _charBuffer );
+    char* p = _charBuffer;
+    p = XMLUtil::SkipWhiteSpace( p );
+    p = const_cast<char*>( XMLUtil::ReadBOM( p, &_writeBOM ) );
+    if ( !*p ) {
+        SetError( XML_ERROR_EMPTY_DOCUMENT, 0, 0 );
+        return;
+    }
+    ParseDeep(p, 0 );
+}
+
+XMLPrinter::XMLPrinter( FILE* file, bool compact, int depth ) :
+    _elementJustOpened( false ),
+    _firstElement( true ),
+    _fp( file ),
+    _depth( depth ),
+    _textDepth( -1 ),
+    _processEntities( true ),
+    _compactMode( compact )
+{
+    for( int i=0; i<ENTITY_RANGE; ++i ) {
+        _entityFlag[i] = false;
+        _restrictedEntityFlag[i] = false;
+    }
+    for( int i=0; i<NUM_ENTITIES; ++i ) {
+        const char entityValue = entities[i].value;
+        TIXMLASSERT( 0 <= entityValue && entityValue < ENTITY_RANGE );
+        _entityFlag[ (unsigned char)entityValue ] = true;
+    }
+    _restrictedEntityFlag[(unsigned char)'&'] = true;
+    _restrictedEntityFlag[(unsigned char)'<'] = true;
+    _restrictedEntityFlag[(unsigned char)'>'] = true;	// not required, but consistency is nice
+    _buffer.Push( 0 );
+}
+
+
+void XMLPrinter::Print( const char* format, ... )
+{
+    va_list     va;
+    va_start( va, format );
+
+    if ( _fp ) {
+        vfprintf( _fp, format, va );
+    }
+    else {
+        const int len = TIXML_VSCPRINTF( format, va );
+        // Close out and re-start the va-args
+        va_end( va );
+        TIXMLASSERT( len >= 0 );
+        va_start( va, format );
+        TIXMLASSERT( _buffer.Size() > 0 && _buffer[_buffer.Size() - 1] == 0 );
+        char* p = _buffer.PushArr( len ) - 1;	// back up over the null terminator.
+		TIXML_VSNPRINTF( p, len+1, format, va );
+    }
+    va_end( va );
+}
+
+
+void XMLPrinter::PrintSpace( int depth )
+{
+    for( int i=0; i<depth; ++i ) {
+        Print( "    " );
+    }
+}
+
+
+void XMLPrinter::PrintString( const char* p, bool restricted )
+{
+    // Look for runs of bytes between entities to print.
+    const char* q = p;
+
+    if ( _processEntities ) {
+        const bool* flag = restricted ? _restrictedEntityFlag : _entityFlag;
+        while ( *q ) {
+            TIXMLASSERT( p <= q );
+            // Remember, char is sometimes signed. (How many times has that bitten me?)
+            if ( *q > 0 && *q < ENTITY_RANGE ) {
+                // Check for entities. If one is found, flush
+                // the stream up until the entity, write the
+                // entity, and keep looking.
+                if ( flag[(unsigned char)(*q)] ) {
+                    while ( p < q ) {
+                        const size_t delta = q - p;
+                        // %.*s accepts type int as "precision"
+                        const int toPrint = ( INT_MAX < delta ) ? INT_MAX : (int)delta;
+                        Print( "%.*s", toPrint, p );
+                        p += toPrint;
+                    }
+                    bool entityPatternPrinted = false;
+                    for( int i=0; i<NUM_ENTITIES; ++i ) {
+                        if ( entities[i].value == *q ) {
+                            Print( "&%s;", entities[i].pattern );
+                            entityPatternPrinted = true;
+                            break;
+                        }
+                    }
+                    if ( !entityPatternPrinted ) {
+                        // TIXMLASSERT( entityPatternPrinted ) causes gcc -Wunused-but-set-variable in release
+                        TIXMLASSERT( false );
+                    }
+                    ++p;
+                }
+            }
+            ++q;
+            TIXMLASSERT( p <= q );
+        }
+    }
+    // Flush the remaining string. This will be the entire
+    // string if an entity wasn't found.
+    TIXMLASSERT( p <= q );
+    if ( !_processEntities || ( p < q ) ) {
+        Print( "%s", p );
+    }
+}
+
+
+void XMLPrinter::PushHeader( bool writeBOM, bool writeDec )
+{
+    if ( writeBOM ) {
+        static const unsigned char bom[] = { TIXML_UTF_LEAD_0, TIXML_UTF_LEAD_1, TIXML_UTF_LEAD_2, 0 };
+        Print( "%s", bom );
+    }
+    if ( writeDec ) {
+        PushDeclaration( "xml version=\"1.0\"" );
+    }
+}
+
+
+void XMLPrinter::OpenElement( const char* name, bool compactMode )
+{
+    SealElementIfJustOpened();
+    _stack.Push( name );
+
+    if ( _textDepth < 0 && !_firstElement && !compactMode ) {
+        Print( "\n" );
+    }
+    if ( !compactMode ) {
+        PrintSpace( _depth );
+    }
+
+    Print( "<%s", name );
+    _elementJustOpened = true;
+    _firstElement = false;
+    ++_depth;
+}
+
+
+void XMLPrinter::PushAttribute( const char* name, const char* value )
+{
+    TIXMLASSERT( _elementJustOpened );
+    Print( " %s=\"", name );
+    PrintString( value, false );
+    Print( "\"" );
+}
+
+
+void XMLPrinter::PushAttribute( const char* name, int v )
+{
+    char buf[BUF_SIZE];
+    XMLUtil::ToStr( v, buf, BUF_SIZE );
+    PushAttribute( name, buf );
+}
+
+
+void XMLPrinter::PushAttribute( const char* name, unsigned v )
+{
+    char buf[BUF_SIZE];
+    XMLUtil::ToStr( v, buf, BUF_SIZE );
+    PushAttribute( name, buf );
+}
+
+
+void XMLPrinter::PushAttribute( const char* name, bool v )
+{
+    char buf[BUF_SIZE];
+    XMLUtil::ToStr( v, buf, BUF_SIZE );
+    PushAttribute( name, buf );
+}
+
+
+void XMLPrinter::PushAttribute( const char* name, double v )
+{
+    char buf[BUF_SIZE];
+    XMLUtil::ToStr( v, buf, BUF_SIZE );
+    PushAttribute( name, buf );
+}
+
+
+void XMLPrinter::CloseElement( bool compactMode )
+{
+    --_depth;
+    const char* name = _stack.Pop();
+
+    if ( _elementJustOpened ) {
+        Print( "/>" );
+    }
+    else {
+        if ( _textDepth < 0 && !compactMode) {
+            Print( "\n" );
+            PrintSpace( _depth );
+        }
+        Print( "</%s>", name );
+    }
+
+    if ( _textDepth == _depth ) {
+        _textDepth = -1;
+    }
+    if ( _depth == 0 && !compactMode) {
+        Print( "\n" );
+    }
+    _elementJustOpened = false;
+}
+
+
+void XMLPrinter::SealElementIfJustOpened()
+{
+    if ( !_elementJustOpened ) {
+        return;
+    }
+    _elementJustOpened = false;
+    Print( ">" );
+}
+
+
+void XMLPrinter::PushText( const char* text, bool cdata )
+{
+    _textDepth = _depth-1;
+
+    SealElementIfJustOpened();
+    if ( cdata ) {
+        Print( "<![CDATA[%s]]>", text );
+    }
+    else {
+        PrintString( text, true );
+    }
+}
+
+void XMLPrinter::PushText( int value )
+{
+    char buf[BUF_SIZE];
+    XMLUtil::ToStr( value, buf, BUF_SIZE );
+    PushText( buf, false );
+}
+
+
+void XMLPrinter::PushText( unsigned value )
+{
+    char buf[BUF_SIZE];
+    XMLUtil::ToStr( value, buf, BUF_SIZE );
+    PushText( buf, false );
+}
+
+
+void XMLPrinter::PushText( bool value )
+{
+    char buf[BUF_SIZE];
+    XMLUtil::ToStr( value, buf, BUF_SIZE );
+    PushText( buf, false );
+}
+
+
+void XMLPrinter::PushText( float value )
+{
+    char buf[BUF_SIZE];
+    XMLUtil::ToStr( value, buf, BUF_SIZE );
+    PushText( buf, false );
+}
+
+
+void XMLPrinter::PushText( double value )
+{
+    char buf[BUF_SIZE];
+    XMLUtil::ToStr( value, buf, BUF_SIZE );
+    PushText( buf, false );
+}
+
+
+void XMLPrinter::PushComment( const char* comment )
+{
+    SealElementIfJustOpened();
+    if ( _textDepth < 0 && !_firstElement && !_compactMode) {
+        Print( "\n" );
+        PrintSpace( _depth );
+    }
+    _firstElement = false;
+    Print( "<!--%s-->", comment );
+}
+
+
+void XMLPrinter::PushDeclaration( const char* value )
+{
+    SealElementIfJustOpened();
+    if ( _textDepth < 0 && !_firstElement && !_compactMode) {
+        Print( "\n" );
+        PrintSpace( _depth );
+    }
+    _firstElement = false;
+    Print( "<?%s?>", value );
+}
+
+
+void XMLPrinter::PushUnknown( const char* value )
+{
+    SealElementIfJustOpened();
+    if ( _textDepth < 0 && !_firstElement && !_compactMode) {
+        Print( "\n" );
+        PrintSpace( _depth );
+    }
+    _firstElement = false;
+    Print( "<!%s>", value );
+}
+
+
+bool XMLPrinter::VisitEnter( const XMLDocument& doc )
+{
+    _processEntities = doc.ProcessEntities();
+    if ( doc.HasBOM() ) {
+        PushHeader( true, false );
+    }
+    return true;
+}
+
+
+bool XMLPrinter::VisitEnter( const XMLElement& element, const XMLAttribute* attribute )
+{
+    const XMLElement* parentElem = 0;
+    if ( element.Parent() ) {
+        parentElem = element.Parent()->ToElement();
+    }
+    const bool compactMode = parentElem ? CompactMode( *parentElem ) : _compactMode;
+    OpenElement( element.Name(), compactMode );
+    while ( attribute ) {
+        PushAttribute( attribute->Name(), attribute->Value() );
+        attribute = attribute->Next();
+    }
+    return true;
+}
+
+
+bool XMLPrinter::VisitExit( const XMLElement& element )
+{
+    CloseElement( CompactMode(element) );
+    return true;
+}
+
+
+bool XMLPrinter::Visit( const XMLText& text )
+{
+    PushText( text.Value(), text.CData() );
+    return true;
+}
+
+
+bool XMLPrinter::Visit( const XMLComment& comment )
+{
+    PushComment( comment.Value() );
+    return true;
+}
+
+bool XMLPrinter::Visit( const XMLDeclaration& declaration )
+{
+    PushDeclaration( declaration.Value() );
+    return true;
+}
+
+
+bool XMLPrinter::Visit( const XMLUnknown& unknown )
+{
+    PushUnknown( unknown.Value() );
+    return true;
+}
+
+}   // namespace tinyxml2
+

+ 754 - 0
main.cpp

@@ -0,0 +1,754 @@
+
+/*
+ * MULTI-CHANNEL SIGNED DISTANCE FIELD GENERATOR v1.0 (2016-04-24) - standalone console program
+ * --------------------------------------------------------------------------------------------
+ * A utility by Viktor Chlumsky, (c) 2014 - 2016
+ *
+ */
+
+#ifdef MSDFGEN_STANDALONE
+
+#define _USE_MATH_DEFINES
+#include <cstdio>
+#include <cmath>
+#include <cstring>
+
+#include "msdfgen.h"
+#include "msdfgen-ext.h"
+
+#ifdef _WIN32
+    #pragma warning(disable:4996)
+#endif
+
+#define LARGE_VALUE 1e240
+
+using namespace msdfgen;
+
+enum Format {
+    AUTO,
+    PNG,
+    BMP,
+    TEXT,
+    TEXT_FLOAT,
+    BINARY,
+    BINARY_FLOAT,
+    BINART_FLOAT_BE
+};
+
+static char toupper(char c) {
+    return c >= 'a' && c <= 'z' ? c-'a'+'A' : c;
+}
+
+static bool parseUnsigned(unsigned &value, const char *arg) {
+    static char c;
+    return sscanf(arg, "%u%c", &value, &c) == 1;
+}
+
+static bool parseUnsignedHex(unsigned &value, const char *arg) {
+    static char c;
+    return sscanf(arg, "%x%c", &value, &c) == 1;
+}
+
+static bool parseDouble(double &value, const char *arg) {
+    static char c;
+    return sscanf(arg, "%lf%c", &value, &c) == 1;
+}
+
+static bool parseUnicode(int &unicode, const char *arg) {
+    unsigned uuc;
+    if (parseUnsigned(uuc, arg)) {
+        unicode = uuc;
+        return true;
+    }
+    if (arg[0] == '0' && (arg[1] == 'x' || arg[1] == 'X') && parseUnsignedHex(uuc, arg+2)) {
+        unicode = uuc;
+        return true;
+    }
+    if (arg[0] == '\'' && arg[1] && arg[2] == '\'' && !arg[3]) {
+        unicode = arg[1];
+        return true;
+    }
+    return false;
+}
+
+static bool parseAngle(double &value, const char *arg) {
+    char c1, c2;
+    int result = sscanf(arg, "%lf%c%c", &value, &c1, &c2);
+    if (result == 1)
+        return true;
+    if (result == 2 && (c1 == 'd' || c1 == 'D')) {
+        value = M_PI*value/180;
+    }
+    return false;
+}
+
+static void parseColoring(Shape &shape, const char *edgeAssignment) {
+    unsigned c = 0, e = 0;
+    if (shape.contours.size() < c) return;
+    Contour *contour = &shape.contours[c];
+    bool change = false;
+    bool clear = true;
+    for (const char *in = edgeAssignment; *in; ++in) {
+        switch (*in) {
+            case ',':
+                if (change)
+                    ++e;
+                if (clear)
+                    while (e < contour->edges.size()) {
+                        contour->edges[e]->color = WHITE;
+                        ++e;
+                    }
+                ++c, e = 0;
+                if (shape.contours.size() <= c) return;
+                contour = &shape.contours[c];
+                change = false;
+                clear = true;
+                break;
+            case '?':
+                clear = false;
+                break;
+            case 'C': case 'M': case 'W': case 'Y': case 'c': case 'm': case 'w': case 'y':
+                if (change) {
+                    ++e;
+                    change = false;
+                }
+                if (e < contour->edges.size()) {
+                    contour->edges[e]->color = EdgeColor(
+                        (*in == 'C' || *in == 'c')*CYAN|
+                        (*in == 'M' || *in == 'm')*MAGENTA|
+                        (*in == 'Y' || *in == 'y')*YELLOW|
+                        (*in == 'W' || *in == 'w')*WHITE);
+                    change = true;
+                }
+                break;
+        }
+    }
+}
+
+static bool writeTextBitmap(FILE *file, const float *values, int cols, int rows) {
+    for (int row = 0; row < rows; ++row) {
+        for (int col = 0; col < cols; ++col) {
+            int v = clamp(int((*values++)*0x100), 0xff);
+            fprintf(file, col ? " %02X" : "%02X", v);
+        }
+        fprintf(file, "\n");
+    }
+    return true;
+}
+
+static bool writeTextBitmapFloat(FILE *file, const float *values, int cols, int rows) {
+    for (int row = 0; row < rows; ++row) {
+        for (int col = 0; col < cols; ++col) {
+            fprintf(file, col ? " %g" : "%g", *values++);
+        }
+        fprintf(file, "\n");
+    }
+    return true;
+}
+
+static bool writeBinBitmap(FILE *file, const float *values, int count) {
+    for (int pos = 0; pos < count; ++pos) {
+        unsigned char v = clamp(int((*values++)*0x100), 0xff);
+        fwrite(&v, 1, 1, file);
+    }
+    return true;
+}
+
+#ifdef __BIG_ENDIAN__
+static bool writeBinBitmapFloatBE(FILE *file, const float *values, int count)
+#else
+static bool writeBinBitmapFloat(FILE *file, const float *values, int count)
+#endif
+{
+    return fwrite(values, sizeof(float), count, file) == count;
+}
+
+#ifdef __BIG_ENDIAN__
+static bool writeBinBitmapFloat(FILE *file, const float *values, int count)
+#else
+static bool writeBinBitmapFloatBE(FILE *file, const float *values, int count)
+#endif
+{
+    for (int pos = 0; pos < count; ++pos) {
+        const unsigned char *b = reinterpret_cast<const unsigned char *>(values++);
+        for (int i = sizeof(float)-1; i >= 0; --i)
+            fwrite(b+i, 1, 1, file);
+    }
+    return true;
+}
+
+static bool cmpExtension(const char *path, const char *ext) {
+    for (const char *a = path+strlen(path)-1, *b = ext+strlen(ext)-1; b >= ext; --a, --b)
+        if (a < path || toupper(*a) != toupper(*b))
+            return false;
+    return true;
+}
+
+template <typename T>
+static const char * writeOutput(const Bitmap<T> &bitmap, const char *filename, Format format) {
+    if (filename) {
+        if (format == AUTO) {
+            if (cmpExtension(filename, ".png")) format = PNG;
+            else if (cmpExtension(filename, ".bmp")) format = BMP;
+            else if (cmpExtension(filename, ".txt")) format = TEXT;
+            else if (cmpExtension(filename, ".bin")) format = BINARY;
+            else
+                return "Could not deduce format from output file name.";
+        }
+        switch (format) {
+            case PNG: return savePng(bitmap, filename) ? NULL : "Failed to write output PNG image.";
+            case BMP: return saveBmp(bitmap, filename) ? NULL : "Failed to write output BMP image.";
+            case TEXT: case TEXT_FLOAT: {
+                FILE *file = fopen(filename, "w");
+                if (!file) return "Failed to write output text file.";
+                if (format == TEXT)
+                    writeTextBitmap(file, reinterpret_cast<const float *>(&bitmap(0, 0)), sizeof(T)/sizeof(float)*bitmap.width(), bitmap.height());
+                else if (format == TEXT_FLOAT)
+                    writeTextBitmapFloat(file, reinterpret_cast<const float *>(&bitmap(0, 0)), sizeof(T)/sizeof(float)*bitmap.width(), bitmap.height());
+                fclose(file);
+                return NULL;
+            }
+            case BINARY: case BINARY_FLOAT: case BINART_FLOAT_BE: {
+                FILE *file = fopen(filename, "wb");
+                if (!file) return "Failed to write output binary file.";
+                if (format == BINARY)
+                    writeBinBitmap(file, reinterpret_cast<const float *>(&bitmap(0, 0)), sizeof(T)/sizeof(float)*bitmap.width()*bitmap.height());
+                else if (format == BINARY_FLOAT)
+                    writeBinBitmapFloat(file, reinterpret_cast<const float *>(&bitmap(0, 0)), sizeof(T)/sizeof(float)*bitmap.width()*bitmap.height());
+                else if (format == BINART_FLOAT_BE)
+                    writeBinBitmapFloatBE(file, reinterpret_cast<const float *>(&bitmap(0, 0)), sizeof(T)/sizeof(float)*bitmap.width()*bitmap.height());
+                fclose(file);
+                return NULL;
+            }
+        }
+    } else {
+        if (format == AUTO || format == TEXT)
+            writeTextBitmap(stdout, reinterpret_cast<const float *>(&bitmap(0, 0)), sizeof(T)/sizeof(float)*bitmap.width(), bitmap.height());
+        else if (format == TEXT_FLOAT)
+            writeTextBitmapFloat(stdout, reinterpret_cast<const float *>(&bitmap(0, 0)), sizeof(T)/sizeof(float)*bitmap.width(), bitmap.height());
+        else
+            return "Unsupported format for standard output.";
+    }
+    return NULL;
+}
+
+static const char *helpText =
+    "\n"
+    "Multi-channel signed distance field generator by Viktor Chlumsky v" MSDFGEN_VERSION "\n"
+    "---------------------------------------------------------------------\n"
+    "  Usage: msdfgen"
+    #ifdef _WIN32
+        ".exe"
+    #endif
+        " <mode> <input specification> <options>\n"
+    "\n"
+    "MODES\n"
+    "  sdf - Generate conventional monochrome signed distance field.\n"
+    "  psdf - Generate monochrome signed pseudo-distance field.\n"
+    "  msdf - Generate multi-channel signed distance field. This is used by default if no mode is specified.\n"
+    "  metrics - Report shape metrics only.\n"
+    "\n"
+    "INPUT SPECIFICATION\n"
+    "  -defineshape <definition>\n"
+        "\tDefines input shape using the ad-hoc text definition.\n"
+    "  -font <filename.ttf> <character code>\n"
+        "\tLoads a single glyph from the specified font file. Format of character code is '?', 63 or 0x3F.\n"
+    "  -shapedesc <filename.txt>\n"
+        "\tLoads text shape description from a file.\n"
+    "  -stdin\n"
+        "\tReads text shape description from the standard input.\n"
+    "  -svg <filename.svg>\n"
+        "\tLoads the first vector path encountered in the specified SVG file.\n"
+    "\n"
+    "OPTIONS\n"
+    "  -angle <angle>\n"
+        "\tSpecifies the minimum angle between adjacent edges to be considered a corner. Append D for degrees.\n"
+    "  -ascale <x scale> <y scale>\n"
+        "\tSets the scale used to convert shape units to pixels asymmetrically.\n"
+    "  -autoframe\n"
+        "\tAutomatically scales (unless specified) and translates the shape to fit.\n"
+    "  -edgecolors <sequence>\n"
+        "\tOverrides automatic edge coloring with the specified color sequence.\n"
+    "  -errorcorrection <threshold>\n"
+        "\tChanges the threshold used to detect and correct potential artifacts. 0 disables error correction.\n"
+    "  -exportshape <filename.txt>\n"
+        "\tSaves the shape description into a text file that can be edited and loaded using -shapedesc.\n"
+    "  -format <png / bmp / text / textfloat / bin / binfloat / binfloatbe>\n"
+        "\tSpecifies the output format of the distance field. Otherwise it is chosen based on output file extension.\n"
+    "  -help\n"
+        "\tDisplays this help.\n"
+    "  -o <filename>\n"
+        "\tSets the output file name. The default value is \"output.png\".\n"
+    "  -printmetrics\n"
+        "\tPrints relevant metrics of the shape to the standard output.\n"
+    "  -pxrange <range>\n"
+        "\tSets the width of the range between the lowest and highest signed distance in pixels.\n"
+    "  -range <range>\n"
+        "\tSets the width of the range between the lowest and highest signed distance in shape units.\n"
+    "  -scale <scale>\n"
+        "\tSets the scale used to convert shape units to pixels.\n"
+    "  -size <width> <height>\n"
+        "\tSets the dimensions of the output image.\n"
+    "  -stdout\n"
+        "\tPrints the output instead of storing it in a file. Only text formats are supported.\n"
+    "  -testrender <filename.png> <width> <height>\n"
+        "\tRenders an image preview using the generated distance field and saves it as a PNG file.\n"
+    "  -testrendermulti <filename.png> <width> <height>\n"
+        "\tRenders an image preview without flattening the color channels.\n"
+    "  -translate <x> <y>\n"
+        "\tSets the translation of the shape in shape units.\n"
+    "  -yflip\n"
+        "\tInverts the Y axis in the output distance field. The default order is bottom to top.\n"
+    "\n";
+
+int main(int argc, const char * const *argv) {
+    #define ABORT(msg) { puts(msg); return 0; }
+
+    // Parse command line arguments
+    enum {
+        NONE,
+        SVG,
+        FONT,
+        DESCRIPTION_ARG,
+        DESCRIPTION_STDIN,
+        DESCRIPTION_FILE
+    } inputType = NONE;
+    enum {
+        SINGLE,
+        PSEUDO,
+        MULTI,
+        METRICS
+    } mode = MULTI;
+    Format format = AUTO;
+    const char *input = NULL;
+    const char *output = "output.png";
+    const char *shapeExport = NULL;
+    const char *testRender = NULL;
+    const char *testRenderMulti = NULL;
+    bool outputSpecified = false;
+    int unicode = 0;
+
+    int width = 64, height = 64;
+    int testWidth = 0, testHeight = 0;
+    int testWidthM = 0, testHeightM = 0;
+    bool autoFrame = false;
+    enum {
+        RANGE_UNIT,
+        RANGE_PX
+    } rangeMode = RANGE_PX;
+    double range = 1;
+    double pxRange = 2;
+    Vector2 translate;
+    Vector2 scale = 1;
+    bool scaleSpecified = false;
+    double angleThreshold = 3;
+    double edgeThreshold = 1.00000001;
+    bool defEdgeAssignment = true;
+    const char *edgeAssignment = NULL;
+    bool yFlip = false;
+    bool printMetrics = false;
+    bool skipColoring = false;
+
+    int argPos = 1;
+    bool suggestHelp = false;
+    while (argPos < argc) {
+        const char *arg = argv[argPos];
+        #define ARG_CASE(s, p) if (!strcmp(arg, s) && argPos+(p) < argc)
+        #define ARG_MODE(s, m) if (!strcmp(arg, s)) { mode = m; ++argPos; continue; }
+        #define SETFORMAT(fmt, ext) do { format = fmt; if (!outputSpecified) output = "output." ext; } while (false)
+
+        ARG_MODE("sdf", SINGLE)
+        ARG_MODE("psdf", PSEUDO)
+        ARG_MODE("msdf", MULTI)
+        ARG_MODE("metrics", METRICS)
+
+        ARG_CASE("-svg", 1) {
+            inputType = SVG;
+            input = argv[argPos+1];
+            argPos += 2;
+            continue;
+        }
+        ARG_CASE("-font", 2) {
+            inputType = FONT;
+            input = argv[argPos+1];
+            parseUnicode(unicode, argv[argPos+2]);
+            argPos += 3;
+            continue;
+        }
+        ARG_CASE("-defineshape", 1) {
+            inputType = DESCRIPTION_ARG;
+            input = argv[argPos+1];
+            argPos += 2;
+            continue;
+        }
+        ARG_CASE("-stdin", 0) {
+            inputType = DESCRIPTION_STDIN;
+            input = "stdin";
+            argPos += 1;
+            continue;
+        }
+        ARG_CASE("-shapedesc", 1) {
+            inputType = DESCRIPTION_FILE;
+            input = argv[argPos+1];
+            argPos += 2;
+            continue;
+        }
+        ARG_CASE("-o", 1) {
+            output = argv[argPos+1];
+            outputSpecified = true;
+            argPos += 2;
+            continue;
+        }
+        ARG_CASE("-stdout", 0) {
+            output = NULL;
+            argPos += 1;
+            continue;
+        }
+        ARG_CASE("-format", 1) {
+            if (!strcmp(argv[argPos+1], "auto")) format = AUTO;
+            else if (!strcmp(argv[argPos+1], "png")) SETFORMAT(PNG, "png");
+            else if (!strcmp(argv[argPos+1], "bmp")) SETFORMAT(BMP, "bmp");
+            else if (!strcmp(argv[argPos+1], "text") || !strcmp(argv[argPos+1], "txt")) SETFORMAT(TEXT, "txt");
+            else if (!strcmp(argv[argPos+1], "textfloat") || !strcmp(argv[argPos+1], "txtfloat")) SETFORMAT(TEXT_FLOAT, "txt");
+            else if (!strcmp(argv[argPos+1], "bin") || !strcmp(argv[argPos+1], "binary")) SETFORMAT(BINARY, "bin");
+            else if (!strcmp(argv[argPos+1], "binfloat") || !strcmp(argv[argPos+1], "binfloatle")) SETFORMAT(BINARY_FLOAT, "bin");
+            else if (!strcmp(argv[argPos+1], "binfloatbe")) SETFORMAT(BINART_FLOAT_BE, "bin");
+            else
+                puts("Unknown format specified.");
+            argPos += 2;
+            continue;
+        }
+        ARG_CASE("-size", 2) {
+            unsigned w, h;
+            if (!parseUnsigned(w, argv[argPos+1]) || !parseUnsigned(h, argv[argPos+2]) || !w || !h)
+                ABORT("Invalid size arguments. Use -size <width> <height> with two positive integers.");
+            width = w, height = h;
+            argPos += 3;
+            continue;
+        }
+        ARG_CASE("-autoframe", 0) {
+            autoFrame = true;
+            argPos += 1;
+            continue;
+        }
+        ARG_CASE("-range", 1) {
+            double r;
+            if (!parseDouble(r, argv[argPos+1]) || r < 0)
+                ABORT("Invalid range argument. Use -range <range> with a positive real number.");
+            rangeMode = RANGE_UNIT;
+            range = r;
+            argPos += 2;
+            continue;
+        }
+        ARG_CASE("-pxrange", 1) {
+            double r;
+            if (!parseDouble(r, argv[argPos+1]) || r < 0)
+                ABORT("Invalid range argument. Use -pxrange <range> with a positive real number.");
+            rangeMode = RANGE_PX;
+            pxRange = r;
+            argPos += 2;
+            continue;
+        }
+        ARG_CASE("-scale", 1) {
+            double s;
+            if (!parseDouble(s, argv[argPos+1]) || s <= 0)
+                ABORT("Invalid scale argument. Use -scale <scale> with a positive real number.");
+            scale = s;
+            scaleSpecified = true;
+            argPos += 2;
+            continue;
+        }
+        ARG_CASE("-ascale", 2) {
+            double sx, sy;
+            if (!parseDouble(sx, argv[argPos+1]) || !parseDouble(sy, argv[argPos+2]) || sx <= 0 || sy <= 0)
+                ABORT("Invalid scale arguments. Use -ascale <x> <y> with two positive real numbers.");
+            scale.set(sx, sy);
+            scaleSpecified = true;
+            argPos += 3;
+            continue;
+        }
+        ARG_CASE("-translate", 2) {
+            double tx, ty;
+            if (!parseDouble(tx, argv[argPos+1]) || !parseDouble(ty, argv[argPos+2]))
+                ABORT("Invalid translate arguments. Use -translate <x> <y> with two real numbers.");
+            translate.set(tx, ty);
+            argPos += 3;
+            continue;
+        }
+        ARG_CASE("-angle", 1) {
+            double at;
+            if (!parseAngle(at, argv[argPos+1]))
+                ABORT("Invalid angle threshold. Use -angle <min angle> with a positive real number less than PI or a value in degrees followed by 'd' below 180d.");
+            angleThreshold = at;
+            argPos += 2;
+            continue;
+        }
+        ARG_CASE("-errorcorrection", 1) {
+            double et;
+            if (!parseDouble(et, argv[argPos+1]) || et < 0)
+                ABORT("Invalid error correction threshold. Use -errorcorrection <threshold> with a real number larger or equal to 1.");
+            edgeThreshold = et;
+            argPos += 2;
+            continue;
+        }
+        ARG_CASE("-edgecolors", 1) {
+            static const char *allowed = " ?,cmyCMY";
+            for (int i = 0; argv[argPos+1][i]; ++i) {
+                for (int j = 0; allowed[j]; ++j)
+                    if (argv[argPos+1][i] == allowed[j])
+                        goto ROLL_ARG;
+                ABORT("Invalid edge coloring sequence. Use -assign <color sequence> with only the colors C, M, and Y. Separate contours by commas and use ? to keep the default assigment for a contour.");
+            ROLL_ARG:;
+            }
+            edgeAssignment = argv[argPos+1];
+            argPos += 2;
+            continue;
+        }
+        ARG_CASE("-exportshape", 1) {
+            shapeExport = argv[argPos+1];
+            argPos += 2;
+            continue;
+        }
+        ARG_CASE("-testrender", 3) {
+            unsigned w, h;
+            if (!parseUnsigned(w, argv[argPos+2]) || !parseUnsigned(h, argv[argPos+3]) || !w || !h)
+                ABORT("Invalid arguments for test render. Use -testrender <output.png> <width> <height>.");
+            testRender = argv[argPos+1];
+            testWidth = w, testHeight = h;
+            argPos += 4;
+            continue;
+        }
+        ARG_CASE("-testrendermulti", 3) {
+            unsigned w, h;
+            if (!parseUnsigned(w, argv[argPos+2]) || !parseUnsigned(h, argv[argPos+3]) || !w || !h)
+                ABORT("Invalid arguments for test render. Use -testrendermulti <output.png> <width> <height>.");
+            testRenderMulti = argv[argPos+1];
+            testWidthM = w, testHeightM = h;
+            argPos += 4;
+            continue;
+        }
+        ARG_CASE("-yflip", 0) {
+            yFlip = true;
+            argPos += 1;
+            continue;
+        }
+        ARG_CASE("-printmetrics", 0) {
+            printMetrics = true;
+            argPos += 1;
+            continue;
+        }
+        ARG_CASE("-help", 0)
+            ABORT(helpText);
+        printf("Unknown setting or insufficient parameters: %s\n", arg);
+        suggestHelp = true;
+        ++argPos;
+    }
+    if (suggestHelp)
+        printf("Use -help for more information.\n");
+
+    // Load input
+    Vector2 svgDims;
+    double glyphAdvance = 0;
+    if (!inputType || !input)
+        ABORT("No input specified! Use either -svg <file.svg> or -font <file.ttf/otf> <character code>, or see -help.");
+    Shape shape;
+    switch (inputType) {
+        case SVG: {
+            if (!loadSvgShape(shape, input, &svgDims))
+                ABORT("Failed to load shape from SVG file.");
+            break;
+        }
+        case FONT: {
+            if (!unicode)
+                ABORT("No character specified! Use -font <file.ttf/otf> <character code>. Character code can be a number (65, 0x41), or a character in apostrophes ('A').");
+            FreetypeHandle *ft = initializeFreetype();
+            if (!ft) return -1;
+            FontHandle *font = loadFont(ft, input);
+            if (!font) {
+                deinitializeFreetype(ft);
+                ABORT("Failed to load font file.");
+            }
+            if (!loadGlyph(shape, font, unicode, &glyphAdvance)) {
+                destroyFont(font);
+                deinitializeFreetype(ft);
+                ABORT("Failed to load glyph from font file.");
+            }
+            destroyFont(font);
+            deinitializeFreetype(ft);
+            break;
+        }
+        case DESCRIPTION_ARG: {
+            if (!readShapeDescription(input, shape, &skipColoring))
+                ABORT("Parse error in shape description.");
+            break;
+        }
+        case DESCRIPTION_STDIN: {
+            if (!readShapeDescription(stdin, shape, &skipColoring))
+                ABORT("Parse error in shape description.");
+            break;
+        }
+        case DESCRIPTION_FILE: {
+            FILE *file = fopen(input, "r");
+            if (!file)
+                ABORT("Failed to load shape description file.");
+            if (!readShapeDescription(file, shape, &skipColoring))
+                ABORT("Parse error in shape description.");
+            fclose(file);
+            break;
+        }
+    }
+
+    // Validate and normalize shape
+    if (!shape.validate())
+        ABORT("The geometry of the loaded shape is invalid.");
+    shape.normalize();
+    if (yFlip)
+        shape.inverseYAxis = !shape.inverseYAxis;
+
+    double avgScale = .5*(scale.x+scale.y);
+    struct {
+        double l, b, r, t;
+    } bounds = {
+        LARGE_VALUE, LARGE_VALUE, -LARGE_VALUE, -LARGE_VALUE
+    };
+    if (autoFrame || mode == METRICS || printMetrics)
+        shape.bounds(bounds.l, bounds.b, bounds.r, bounds.t);
+
+    // Auto-frame
+    if (autoFrame) {
+        double l = bounds.l, b = bounds.b, r = bounds.r, t = bounds.t;
+        Vector2 frame(width, height);
+        if (rangeMode == RANGE_UNIT)
+            l -= range, b -= range, r += range, t += range;
+        else if (!scaleSpecified)
+            frame -= 2*pxRange;
+        if (l >= r || b >= t)
+            l = 0, b = 0, r = 1, t = 1;
+        if (frame.x <= 0 || frame.y <= 0)
+            ABORT("Cannot fit the specified pixel range.");
+        Vector2 dims(r-l, t-b);
+        if (scaleSpecified)
+            translate = .5*(frame/scale-dims)-Vector2(l, b);
+        else {
+            if (dims.x*frame.y < dims.y*frame.x) {
+                translate.set(.5*(frame.x/frame.y*dims.y-dims.x)-l, -b);
+                scale = avgScale = frame.y/dims.y;
+            } else {
+                translate.set(-l, .5*(frame.y/frame.x*dims.x-dims.y)-b);
+                scale = avgScale = frame.x/dims.x;
+            }
+        }
+        if (rangeMode == RANGE_PX && !scaleSpecified)
+            translate += pxRange/scale;
+    }
+
+    if (rangeMode == RANGE_PX)
+        range = pxRange/min(scale.x, scale.y);
+
+    // Print metrics
+    if (mode == METRICS || printMetrics) {
+        FILE *out = stdout;
+        if (mode == METRICS && outputSpecified)
+            out = fopen(output, "w");
+        if (!out)
+            ABORT("Failed to write output file.");
+        if (shape.inverseYAxis)
+            fprintf(out, "inverseY = true\n");
+        if (bounds.r >= bounds.l && bounds.t >= bounds.b)
+            fprintf(out, "bounds = %.12g, %.12g, %.12g, %.12g\n", bounds.l, bounds.b, bounds.r, bounds.t);
+        if (svgDims.x != 0 && svgDims.y != 0)
+            fprintf(out, "dimensions = %.12g, %.12g\n", svgDims.x, svgDims.y);
+        if (glyphAdvance != 0)
+            fprintf(out, "advance = %.12g\n", glyphAdvance);
+        if (autoFrame) {
+            if (!scaleSpecified)
+                fprintf(out, "scale = %.12g\n", avgScale);
+            fprintf(out, "translate = %.12g, %.12g\n", translate.x, translate.y);
+        }
+        if (rangeMode == RANGE_PX)
+            fprintf(out, "range = %.12g\n", range);
+        if (mode == METRICS && outputSpecified)
+            fclose(out);
+    }
+
+    // Compute output
+    Bitmap<float> sdf;
+    Bitmap<FloatRGB> msdf;
+    switch (mode) {
+        case SINGLE: {
+            sdf = Bitmap<float>(width, height);
+            generateSDF(sdf, shape, range, scale, translate);
+            break;
+        }
+        case PSEUDO: {
+            sdf = Bitmap<float>(width, height);
+            generatePseudoSDF(sdf, shape, range, scale, translate);
+            break;
+        }
+        case MULTI: {
+            if (!skipColoring)
+                edgeColoringSimple(shape, angleThreshold);
+            if (edgeAssignment)
+                parseColoring(shape, edgeAssignment);
+            msdf = Bitmap<FloatRGB>(width, height);
+            generateMSDF(msdf, shape, range, scale, translate, edgeThreshold);
+            break;
+        }
+    }
+
+    // Save output
+    if (shapeExport) {
+        FILE *file = fopen(shapeExport, "w");
+        if (file) {
+            writeShapeDescription(file, shape);
+            fclose(file);
+        } else
+            puts("Failed to write shape export file.");
+    }
+    const char *error = NULL;
+    switch (mode) {
+        case SINGLE:
+        case PSEUDO:
+            error = writeOutput(sdf, output, format);
+            if (error)
+                ABORT(error);
+            if (testRenderMulti || testRender)
+                simulate8bit(sdf);
+            if (testRenderMulti) {
+                Bitmap<FloatRGB> render(testWidthM, testHeightM);
+                renderSDF(render, sdf, avgScale*range);
+                if (!savePng(render, testRenderMulti))
+                    puts("Failed to write test render file.");
+            }
+            if (testRender) {
+                Bitmap<float> render(testWidth, testHeight);
+                renderSDF(render, sdf, avgScale*range);
+                if (!savePng(render, testRender))
+                    puts("Failed to write test render file.");
+            }
+            break;
+        case MULTI:
+            error = writeOutput(msdf, output, format);
+            if (error)
+                ABORT(error);
+            if (testRenderMulti || testRender)
+                simulate8bit(msdf);
+            if (testRenderMulti) {
+                Bitmap<FloatRGB> render(testWidthM, testHeightM);
+                renderSDF(render, msdf, avgScale*range);
+                if (!savePng(render, testRenderMulti))
+                    puts("Failed to write test render file.");
+            }
+            if (testRender) {
+                Bitmap<float> render(testWidth, testHeight);
+                renderSDF(render, msdf, avgScale*range);
+                if (!savePng(render, testRender))
+                    ABORT("Failed to write test render file.");
+            }
+            break;
+    }
+
+    return 0;
+}
+
+#endif

+ 23 - 0
msdfgen-ext.h

@@ -0,0 +1,23 @@
+
+#pragma once
+
+/*
+ * MULTI-CHANNEL SIGNED DISTANCE FIELD GENERATOR v1.0 (2016-04-24) - extensions
+ * ----------------------------------------------------------------------------
+ * A utility by Viktor Chlumsky, (c) 2014 - 2016
+ *
+ * The extension module provides ways to easily load input and save output using popular formats.
+ *
+ * Third party dependencies in extension module:
+ * - FreeType 2
+ *   (to load input font files)
+ * - TinyXML 2 by Lee Thomason
+ *   (to aid in parsing input SVG files)
+ * - LodePNG by Lode Vandevenne
+ *   (to save output PNG images)
+ *
+ */
+
+#include "ext/save-png.h"
+#include "ext/import-svg.h"
+#include "ext/import-font.h"

TEMPAT SAMPAH
msdfgen.exe


+ 40 - 0
msdfgen.h

@@ -0,0 +1,40 @@
+
+#pragma once
+
+/*
+ * MULTI-CHANNEL SIGNED DISTANCE FIELD GENERATOR v1.0 (2016-04-24)
+ * ---------------------------------------------------------------
+ * A utility by Viktor Chlumsky, (c) 2014 - 2016
+ *
+ * The technique used to generate multi-channel distance fields in this code
+ * has been developed by Viktor Chlumsky in 2014 for his master's thesis,
+ * "Shape Decomposition for Multi-Channel Distance Fields". It provides improved
+ * quality of sharp corners in glyphs and other 2D shapes in comparison to monochrome
+ * distance fields. To reconstruct an image of the shape, apply the median of three
+ * operation on the triplet of sampled distance field values.
+ *
+ */
+
+#include "core/arithmetics.hpp"
+#include "core/Vector2.h"
+#include "core/Shape.h"
+#include "core/Bitmap.h"
+#include "core/edge-coloring.h"
+#include "core/render-sdf.h"
+#include "core/save-bmp.h"
+#include "core/shape-description.h"
+
+#define MSDFGEN_VERSION "1.0"
+
+namespace msdfgen {
+
+/// Generates a conventional single-channel signed distance field.
+void generateSDF(Bitmap<float> &output, const Shape &shape, double range, const Vector2 &scale, const Vector2 &translate);
+
+/// Generates a single-channel signed pseudo-distance field.
+void generatePseudoSDF(Bitmap<float> &output, const Shape &shape, double range, const Vector2 &scale, const Vector2 &translate);
+
+/// Generates a multi-channel signed distance field. Edge colors must be assigned first! (see edgeColoringSimple)
+void generateMSDF(Bitmap<FloatRGB> &output, const Shape &shape, double range, const Vector2 &scale, const Vector2 &translate, double edgeThreshold = 1.00000001);
+
+}

TEMPAT SAMPAH
resource.h