commit 2442d8ad1e1ff0fa7b9b28ce6aa2d26c599b1fbd
Author: Vincent Forest <vincent.forest@meso-star.com>
Date: Wed, 22 Jan 2020 15:56:33 +0100
First commit
Fork and refactor the code of the htrdr_sky.<h|c> "High-Tune: RenDeRer"
files. No build system is written, yet.
Diffstat:
| A | COPYING | | | 674 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| A | README.md | | | 42 | ++++++++++++++++++++++++++++++++++++++++++ |
| A | src/htsky.c | | | 618 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| A | src/htsky.h | | | 195 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| A | src/htsky_atmosphere.c | | | 257 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| A | src/htsky_atmosphere.h | | | 37 | +++++++++++++++++++++++++++++++++++++ |
| A | src/htsky_c.h | | | 144 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| A | src/htsky_cloud.c | | | 692 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| A | src/htsky_cloud.h | | | 40 | ++++++++++++++++++++++++++++++++++++++++ |
| A | src/htsky_dump_cloud_vtk.c | | | 228 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| A | src/htsky_file_sys.c | | | 232 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| A | src/htsky_file_sys.h | | | 40 | ++++++++++++++++++++++++++++++++++++++++ |
| A | src/htsky_log.c | | | 180 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| A | src/htsky_log.h | | | 67 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| A | src/htsky_svx.c | | | 418 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| A | src/htsky_svx.h | | | 144 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
16 files changed, 4008 insertions(+), 0 deletions(-)
diff --git a/COPYING b/COPYING
@@ -0,0 +1,674 @@
+ 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:
+
+ <program> Copyright (C) <year> <name of author>
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+<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>.
diff --git a/README.md b/README.md
@@ -0,0 +1,42 @@
+# High-Tune: Sky
+
+This library loads and manages data representing a clear/cloudy sky. The
+atmospheric gas mixture is loaded from a
+[HTGOP](https://gitlab.com/meso-star/htgop) file while cloud properties are
+loaded from data stored with respect to the
+[HTCP](https://gitlab.com/meso-star/htcp/) fileformat. The optical properties
+of the clouds are finally retrieved from a
+[HTMie](https://gitlab.com/meso-star/htmie/) file. Once loaded, the sky
+properties (scattering or absorption coefficient, phase function, etc.) can
+then be retrieved through functions compatible with the
+[Star-MTL](https://gitlab.Com/meso-star/star-mtl/) specification. Consequently
+one can use this library as a Star-MTL program describing a semi-transperent
+material compatible with the Star-MTL fileformat.
+
+## How to build
+
+This library is compatible GNU/Linux 64-bits. It relies on the
+[CMake](http://www.cmake.org) and the
+[RCMake](https://gitlab.com/vaplv/rcmake/) packages to build. It also depends
+on the
+[HTCP](https://gitlab.com/meso-star/htcp/),
+[HTGOP](https://gitlab.com/meso-star/htgop/),
+[HTMie](https://gitlab.com/meso-star/htmie/),
+[RSys](https://gitlab.com/vaplv/rsys/) and
+[Star-VX](https://gitlab.com/meso-star/star-vx/) libraries.
+
+First ensure that CMake is installed on your system. Then install the RCMake
+package as well as the aforementioned prerequisites. Finally generate the
+project from the `cmake/CMakeLists.txt` file by appending to the
+`CMAKE_PREFIX_PATH` variable the install directories of its dependencies. The
+resulting project can be edited, built, tested and installed as any CMake
+project. Refer to the [CMake](https://cmake.org/documentation) for further
+informations on CMake.
+
+## License
+
+Copyright (C) 2020 [|Meso|Star](http://www.meso-star.com)
+<contact@meso-star.com>. HTSky is free software released under the GPL v3+
+license: GNU GPL version 3 or later. You are welcome to redistribute it under
+certain conditions; refer to the COPYING file for details.
+
diff --git a/src/htsky.c b/src/htsky.c
@@ -0,0 +1,618 @@
+/* Copyright (C) 2020 |Meso|Star> (contact@meso-star.com)
+ *
+ * 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/>. */
+
+#include "htsky.h"
+#include "htsky_c.h"
+
+#include <star/ssp.h>
+#include <star/svx.h>
+#include <high_tune/htcp.h>
+#include <high_tune/htgop.h>
+#include <high_tune/htmie.h>
+
+#include <rsys/clock_time.h>
+
+/*******************************************************************************
+ * Helper function
+ ******************************************************************************/
+static INLINE int
+check_args(const struct htsky_args* args)
+{
+ return args
+ && args->htgop_filename
+ && args->grid_max_definition[0]
+ && args->grid_max_definition[1]
+ && args->grid_max_definition[2]
+ && args->nthreads
+ && args->optical_thickness >= 0;
+}
+
+static res_T
+setup_sw_bands_properties(struct hsky* sky)
+{
+ res_T res = RES_OK;
+ size_t nbands;
+ size_t i;
+ ASSERT(sky);
+
+ nbands = htsky_get_sw_spectral_bands_count(sky);
+ ASSERT(nbands);
+ sky->sw_bands = MEM_CALLOC(sky->allocator, nbands, sizeof(*sky->sw_bands));
+ if(!sky->sw_bands) {
+ log_err(sky, "could not allocate the list of SW band properties.\n");
+ res = RES_MEM_ERR;
+ goto error;
+ }
+
+ FOR_EACH(i, 0, nbands) {
+ struct htgop_spectral_interval band;
+ double band_wlens[2];
+
+ HTGOP(get_sw_spectral_interval(sky->htgop, i+sky->sw_bands_range[0], &band));
+ band_wlens[0] = wavenumber_to_wavelength(band.wave_numbers[1]);
+ band_wlens[1] = wavenumber_to_wavelength(band.wave_numbers[0]);
+ ASSERT(band_wlens[0] < band_wlens[1]);
+
+ sky->sw_bands[i].Ca_avg = htmie_compute_xsection_absorption_average
+ (sky->htmie, band_wlens, HTMIE_FILTER_LINEAR);
+ sky->sw_bands[i].Cs_avg = htmie_compute_xsection_scattering_average
+ (sky->htmie, band_wlens, HTMIE_FILTER_LINEAR);
+ sky->sw_bands[i].g_avg = htmie_compute_asymmetry_parameter_average
+ (sky->htmie, band_wlens, HTMIE_FILTER_LINEAR);
+ ASSERT(sky->sw_bands[i].Ca_avg > 0);
+ ASSERT(sky->sw_bands[i].Cs_avg > 0);
+ ASSERT(sky->sw_bands[i].g_avg > 0);
+ }
+
+exit:
+ return res;
+error:
+ if(sky->sw_bands) {
+ MEM_RM(sky->allocator, sky->sw_bands);
+ sky->sw_bands = NULL;
+ }
+ goto exit;
+}
+
+static void
+sample_sw_spectral_data
+ (struct htgop* htgop,
+ struct ssp_rng* rng,
+ res_T (*sample_sw_band)(const struct htgop*, const double, size_t*),
+ size_t* ispectral_band,
+ size_t* iquadrature_pt)
+{
+ struct htgop_spectral_interval specint;
+ double r1, r2;
+ res_T res = RES_OK;
+ ASSERT(htgop && rng && sample_sw_band && ispectral_band && iquadrature_pt);
+ ASSERT(ispectral_band && iquadrature_pt);
+ (void)res;
+ r1 = ssp_rng_canonical(rng);
+ r2 = ssp_rng_canonical(rng);
+ res = sample_sw_band(htgop, r1, ispectral_band);
+ ASSERT(res == RES_OK);
+ HTGOP(get_sw_spectral_interval(htgop, *ispectral_band, &specint));
+ HTGOP(spectral_interval_sample_quadrature(&specint, r2, iquadrature_pt));
+}
+
+static void
+release_sky(ref_T* ref)
+{
+ struct htsky* sky;
+ ASSERT(ref);
+ sky = CONTAINER_OF(ref, struct htsky, ref);
+ clean_clouds(sky);
+ clean_atmosphere(sky);
+ if(sky->svx) SVX(device_ref_put(sky->svx));
+ if(sky->htcp) HTCP(ref_put(sky->htcp));
+ if(sky->htgop) HTGOP(ref_put(sky->htgop));
+ if(sky->htmie) HTMIE(ref_put(sky->htmie));
+ if(sky->sw_bands) MEM_RM(sky->allocator, sky->sw_bands);
+ darray_split_release(&sky->svx2htcp_z);
+ MEM_RM(sky->allocator, sky);
+}
+
+/*******************************************************************************
+ * Local functions
+ ******************************************************************************/
+res_T
+htsky_create
+ (struct logger* logger, /* NULL <=> use default logger */
+ struct mem_allocator* mem_allocator, /* NULL <=> use default allocator */
+ const struct htsky_args* args,
+ const int verbose,
+ struct htsky** out_sky)
+{
+ struct time t0, t1;
+ struct mem_allocator* allocator = NULL;
+ struct htsky* sky = NULL;
+ char buf[128];
+ int nthreads_max;
+ res_T res = RES_OK;
+
+ if(!check_args(args) || !out_sky) {
+ res = RES_BAD_ARG;
+ goto error;
+ }
+
+ allocator = mem_allocator ? mem_allocator : &mem_default_allocator;
+ sky = MEM_CALLOC(allocator, sizeof(*sky));
+ if(!sky) {
+ if(verbose) {
+ #define ERR_STR "Could not allocate the HTSky data structure.\n"
+ if(logger) {
+ logger_print(logger, LOG_ERR, ERR_STR);
+ } else {
+ fprintf(stderr, MSG_ERROR_PREFIX ERR_STR);
+ }
+ #undef ERR_STR
+ }
+ res = RES_MEM_ERR;
+ goto error;
+ }
+ nthreads_max = MMAX(omp_get_max_threads(), omp_get_num_procs());
+ ref_init(&sky->ref);
+ sky->allocator = allocator;
+ sky->verbose = verbose;
+ sky->repeat_clouds = args->repeat_clouds;
+ sky->is_cloudy = args->htcp_filename != NULL;
+ darray_split_init(sky->allocator, &sky->svx2htcp_z);
+ sky->sw_bands_range[0] = 1;
+ sky->sw_bands_range[1] = 0;
+ sky->nthreads = MMIN(args->nthreads, (unsigned)nthreads_max);
+
+ if(logger) {
+ sky->logger = logger;
+ } else {
+ setup_log_default(htsky);
+ }
+
+ /* Setup an allocator specific to the SVX library */
+ res = mem_init_proxy_allocator(&sky->svx_allocator, svx->allocator);
+ if(res != RES_OK) {
+ log_err(sky, "cannot init the allocator used to manage the Star-VX data.\n");
+ goto error;
+ }
+
+ /* Create the Star-VX library device */
+ res = svx_device_create
+ (sky->logger, &sky->svx_allocator, sky->verbose, &sky->svx);
+ if(res != RES_OK) {
+ log_err(sky, "error creating the Star-VX library device.\n");
+ goto error;
+ }
+
+ /* Load the gas optical properties */
+ res = htgop_create(&sky->logger, sky->allocator, sky->verbose, &sky->htgop);
+ if(res != RES_OK) {
+ log_err(sky, "could not create the gas optical properties loader.\n");
+ goto error;
+ }
+ res = htgop_load(sky->htgop, args->htgop_filename);
+ if(res != RES_OK) {
+ log_err(sky, "error loading the gas optical properties -- `%s'.\n",
+ args->htgop_filename);
+ goto error;
+ }
+
+ /* Fetch short wave bands range */
+ res = htgop_get_sw_spectral_intervals_CIE_XYZ(sky->htgop, sky->sw_bands_range);
+ if(res != RES_OK) goto error;
+
+ /* Setup the atmopshere */
+ time_current(&t0);
+ res = atmosphere_setup(sky, args->optical_thickness);
+ if(res != RES_OK) goto error;
+ time_sub(&t0, time_current(&t1), &t0);
+ time_dump(&t0, TIME_ALL, NULL, buf, sizeof(buf));
+ log_info(sky, "setup atmosphere in %s\n", buf);
+
+ /* Nothing more to do */
+ if(!sky->is_cloudy) goto exit;
+
+ if(!sky->htmie_filename) {
+ log_err(sky, "missing the HTMie filename.\n");
+ res = RES_BAD_ARG;
+ goto error;
+ }
+
+ if(!sky->htcp_filename) {
+ log_err(sky, "missing the HTCP filename.\n");
+ res = RES_BAD_ARG;
+ goto error;
+ }
+
+ /* Load MIE data */
+ res = htmie_create(&sky->logger, sky->allocator, sky->verbose, &sky->htmie);
+ if(res != RES_OK) {
+ log_err(sky, "could not create the Mie's data loader.\n");
+ goto error;
+ }
+ res = htmie_load(sky->htmie, args->htmie_filename);
+ if(res != RES_OK) {
+ log_err(sky, "error loading the Mie's data -- `%s'.\n", args->htmie_filename);
+ goto error;
+ }
+
+ res = setup_sw_bands_properties(sky);
+ if(res != RES_OK) goto error;
+
+ /* Load clouds properties */
+ res = htcp_create(&sky->logger, sky->allocator, sky->verbose, &sky->htcp);
+ if(res != RES_OK) {
+ log_err(sky, "could not create the loader of cloud properties.\n");
+ goto error;
+ }
+ res = htcp_load(sky->htcp, args->htcp_filename);
+ if(res != RES_OK) {
+ log_err(sky, "error loading the cloud properties -- `%s'.\n",
+ args->htcp_filename);
+ goto error;
+ }
+
+ time_current(&t0);
+ res = cloud_setup(sky, args->htcp_filename, args->htgop_filename,
+ args->htmie_filename, args->optical_thickness);
+ if(res != RES_OK) goto error;
+ time_sub(&t0, time_current(&t1), &t0);
+ time_dump(&t0, TIME_ALL, NULL, buf, sizeof(buf));
+ log_info(sky, "setup clouds in %s\n", buf);
+
+ if(sky->verbose) {
+ log_svx_memory_usage(htsky);
+ }
+
+exit:
+ *out_sky = sky;
+ return res;
+error:
+ if(sky) {
+ htsky_ref_put(sky);
+ sky = NULL;
+ }
+ goto exit;
+}
+
+res_T
+htsky_ref_get(struct htsky* sky)
+{
+ if(!sky) return RES_BAD_ARG;
+ ref_get(&sky->ref);
+ return RES_OK;
+}
+
+res_T
+htsky_ref_put(struct htsky* sky)
+{
+ if(sky) return RES_BAD_ARG;
+ ref_put(&sky->ref, release_sky);
+ return RES_OK;
+}
+
+double
+htsky_fetch_particle_phase_function_asymmetry_parameter
+ (const struct htsky* sky,
+ const size_t ispectral_band,
+ const size_t iquad)
+{
+ size_t i;
+ ASSERT(sky);
+ ASSERT(ispectral_band >= sky->sw_bands_range[0]);
+ ASSERT(ispectral_band <= sky->sw_bands_range[1]);
+ (void)iquad;
+ if(!sky->is_cloudy) {
+ return 0;
+ } else {
+ i = ispectral_band - sky->sw_bands_range[0];
+ return sky->sw_bands[i].g_avg;
+ }
+}
+
+double
+htsky_fetch_raw_property
+ (const struct htsky* sky,
+ const enum htsky_property prop,
+ const int components_mask, /* Combination of htsky_component_flag */
+ const size_t iband, /* Index of the spectral band */
+ const size_t iquad, /* Index of the quadrature point in the spectral band */
+ const double pos[3],
+ const double k_min,
+ const double k_max)
+{
+ size_t ivox[3];
+ size_t i;
+ const struct svx_tree_desc* cloud_desc = NULL;
+ const struct svx_tree_desc* atmosphere_desc = NULL;
+ int comp_mask = components_mask;
+ int in_clouds; /* Defines if `pos' lies in the clouds */
+ int in_atmosphere; /* Defines if `pos' lies in the atmosphere */
+ double pos_cs[3]; /* Position in cloud space */
+ double k_particle = 0;
+ double k_gas = 0;
+ double k = 0;
+ ASSERT(sky && pos);
+ ASSERT(iband >= sky->sw_bands_range[0]);
+ ASSERT(iband <= sky->sw_bands_range[1]);
+ ASSERT(comp_mask & HTSKY_CPNT_MASK_ALL);
+
+ i = iband - sky->sw_bands_range[0];
+ cloud_desc = sky->is_cloudy ? &sky->clouds[i][iquad].octree_desc : NULL;
+ atmosphere_desc = &sky->atmosphere[i][iquad].bitree_desc;
+ ASSERT(atmosphere_desc->frame[0] == SVX_AXIS_Z);
+
+ /* Is the position inside the clouds? */
+ if(!sky->is_cloudy) {
+ in_clouds = 0;
+ } else if(sky->repeat_clouds) {
+ in_clouds =
+ pos[2] >= cloud_desc->lower[2]
+ && pos[2] <= cloud_desc->upper[2];
+ } else {
+ in_clouds =
+ pos[0] >= cloud_desc->lower[0]
+ && pos[1] >= cloud_desc->lower[1]
+ && pos[2] >= cloud_desc->lower[2]
+ && pos[0] <= cloud_desc->upper[0]
+ && pos[1] <= cloud_desc->upper[1]
+ && pos[2] <= cloud_desc->upper[2];
+ }
+
+ /* Is the position inside the atmosphere? */
+ ASSERT(atmosphere_desc->frame[0] == SVX_AXIS_Z);
+ in_atmosphere =
+ pos[2] >= atmosphere_desc->lower[2]
+ && pos[2] <= atmosphere_desc->upper[2];
+
+ if(!in_clouds) {
+ /* Make invalid the voxel index */
+ ivox[0] = SIZE_MAX;
+ ivox[1] = SIZE_MAX;
+ ivox[2] = SIZE_MAX;
+ /* Not in clouds => No particle */
+ comp_mask &= ~HTSKY_CPNT_FLAG_PARTICLES;
+ /* Not in atmopshere => No gas */
+ if(!in_atmosphere) comp_mask &= ~HTSKY_CPNT_FLAG_GAS;
+ } else {
+ world_to_cloud(sky, pos, pos_cs);
+
+ /* Compute the index of the voxel to fetch */
+ ivox[0] = (size_t)((pos_cs[0] - cloud_desc->lower[0])/sky->htcp_desc.vxsz_x);
+ ivox[1] = (size_t)((pos_cs[1] - cloud_desc->lower[1])/sky->htcp_desc.vxsz_y);
+ if(!sky->htcp_desc.irregular_z) {
+ /* The voxels along the Z dimension have the same size */
+ ivox[2] = (size_t)((pos_cs[2] - cloud_desc->lower[2])/sky->htcp_desc.vxsz_z[0]);
+ } else {
+ /* Irregular voxel size along the Z dimension. Compute the index of the Z
+ * position in the svx2htcp_z Look Up Table and use the LUT to define the
+ * voxel index into the HTCP descripptor */
+ const struct split* splits = darray_split_cdata_get(&sky->svx2htcp_z);
+ const size_t ilut = (size_t)
+ ((pos_cs[2] - cloud_desc->lower[2]) / sky->lut_cell_sz);
+ ivox[2] = splits[ilut].index + (pos_cs[2] > splits[ilut].height);
+ }
+ }
+
+ if(comp_mask & HTSKY_CPNT_FLAG_PARTICLES) {
+ double rho_da = 0; /* Dry air density */
+ double rct = 0; /* #droplets in kg of water per kg of dry air */
+ double ql = 0; /* Droplet density In kg.m^-3 */
+ double Ca = 0; /* Massic absorption cross section in m^2.kg^-1 */
+ double Cs = 0; /* Massic scattering cross section in m^2.kg^-1 */
+ ASSERT(in_clouds);
+
+ /* Compute he dry air density */
+ rho_da = cloud_dry_air_density(&sky->htcp_desc, ivox);
+
+ /* Compute the droplet density */
+ rct = htcp_desc_RCT_at(&sky->htcp_desc, ivox[0], ivox[1], ivox[2], 0);
+ ql = rho_da * rct;
+
+ /* Use the average cross section of the current spectral band */
+ if(prop == HTSKY_Ka || prop == HTSKY_Kext) Ca = sky->sw_bands[i].Ca_avg;
+ if(prop == HTSKY_Ks || prop == HTSKY_Kext) Cs = sky->sw_bands[i].Cs_avg;
+
+ k_particle = ql*(Ca + Cs);
+ }
+
+ if(comp_mask & HTSKY_CPNT_FLAG_GAS) {
+ struct htgop_layer layer;
+ struct htgop_layer_sw_spectral_interval band;
+ size_t ilayer = 0;
+ ASSERT(in_atmosphere);
+
+ /* Retrieve the quadrature point into the spectral band of the layer into
+ * which `pos' lies */
+ HTGOP(position_to_layer_id(sky->htgop, pos[2], &ilayer));
+ HTGOP(get_layer(sky->htgop, ilayer, &layer));
+ HTGOP(layer_get_sw_spectral_interval(&layer, iband, &band));
+
+ if(!in_clouds) {
+ /* Pos is outside the clouds. Directly fetch the nominal optical
+ * properties */
+ ASSERT(iquad < band.quadrature_length);
+ switch(prop) {
+ case HTSKY_Ka: k_gas = band.ka_nominal[iquad]; break;
+ case HTSKY_Ks: k_gas = band.ks_nominal[iquad]; break;
+ case HTSKY_Kext:
+ k_gas = band.ka_nominal[iquad] + band.ks_nominal[iquad];
+ break;
+ default: FATAL("Unreachable code.\n"); break;
+ }
+ } else {
+ /* Pos is inside the clouds. Compute the water vapor molar fraction at
+ * the current voxel */
+ const double x_h2o = cloud_water_vapor_molar_fraction(&sky->htcp_desc, ivox);
+ struct htgop_layer_sw_spectral_interval_tab tab;
+
+ /* Retrieve the tabulated data for the quadrature point */
+ HTGOP(layer_sw_spectral_interval_get_tab(&band, iquad, &tab));
+
+ /* Fetch the optical properties wrt x_h2o */
+ switch(prop) {
+ case HTSKY_Ka:
+ HTGOP(layer_sw_spectral_interval_tab_fetch_ka(&tab, x_h2o, &k_gas));
+ break;
+ case HTSKY_Ks:
+ HTGOP(layer_sw_spectral_interval_tab_fetch_ks(&tab, x_h2o, &k_gas));
+ break;
+ case HTSKY_Kext:
+ HTGOP(layer_sw_spectral_interval_tab_fetch_kext(&tab, x_h2o, &k_gas));
+ break;
+ default: FATAL("Unreachable code.\n"); break;
+ }
+ }
+ }
+
+ k = k_particle + k_gas;
+ ASSERT(k >= k_min && k <= k_max);
+ (void)k_min, (void)k_max;
+ return k;
+}
+
+size_t
+htsky_get_sw_spectral_bands_count(const struct htsky* sky)
+{
+ ASSERT(sky && sky->sw_bands_range[0] <= sky->sw_bands_range[1]);
+ return sky->sw_bands_range[1] - sky->sw_bands_range[0] + 1;
+}
+
+size_t
+htsky_get_sw_spectral_band_id
+ (const struct htsky* sky, const size_t i)
+{
+ ASSERT(sky && i < htsky_get_sw_spectral_bands_count(sky));
+ return sky->sw_bands_range[0] + i;
+}
+
+size_t
+htsky_get_sw_spectral_band_quadrature_length
+ (const struct htsky* sky, const size_t iband)
+{
+ struct htgop_spectral_interval band;
+ ASSERT(sky);
+ ASSERT(iband >= sky->sw_bands_range[0]);
+ ASSERT(iband <= sky->sw_bands_range[1]);
+ HTGOP(get_sw_spectral_interval(sky->htgop, iband, &band));
+ return band.quadrature_length;
+}
+
+res_T
+htsky_get_sw_spectral_band_bounds
+ (const struct htsky* sky,
+ const size_t iband,
+ double wavelengths[2])
+{
+ struct htgop_spectral_interval specint;
+ res_T res = RES_OK;
+ ASSERT(sky && wavelengths);
+
+ res = htgop_get_sw_spectral_interval(sky->htgop, iband, &specint);
+ if(res != RES_OK) return res;
+
+ wavelengths[0] = wavenumber_to_wavelength(specint.wave_numbers[1]);
+ wavelengths[1] = wavenumber_to_wavelength(specint.wave_numbers[0]);
+ ASSERT(wavelengths[0] < wavelengths[1]);
+ return RES_OK;
+}
+
+void
+htsky_sample_sw_spectral_data_CIE_1931_X
+ (const struct htsky* sky,
+ struct ssp_rng* rng,
+ size_t* ispectral_band,
+ size_t* iquadrature_pt)
+{
+ sample_sw_spectral_data
+ (sky->htgop, rng, htgop_sample_sw_spectral_interval_CIE_1931_X,
+ ispectral_band, iquadrature_pt);
+}
+
+void
+htsky_sample_sw_spectral_data_CIE_1931_Y
+ (const struct htsky* sky,
+ struct ssp_rng* rng,
+ size_t* ispectral_band,
+ size_t* iquadrature_pt)
+{
+ sample_sw_spectral_data
+ (sky->htgop, rng, htgop_sample_sw_spectral_interval_CIE_1931_Y,
+ ispectral_band, iquadrature_pt);
+}
+
+void
+htsky_sample_sw_spectral_data_CIE_1931_Z
+ (const struct htsky* sky,
+ struct ssp_rng* rng,
+ size_t* ispectral_band,
+ size_t* iquadrature_pt)
+{
+ sample_sw_spectral_data
+ (sky->htgop, rng, htgop_sample_sw_spectral_interval_CIE_1931_Z,
+ ispectral_band, iquadrature_pt);
+}
+
+/*******************************************************************************
+ * Local functions
+ ******************************************************************************/
+double*
+world_to_cloud
+ (const struct htsky* sky,
+ const double pos_ws[3], /* World space position */
+ double out_pos_cs[3])
+{
+ double cloud_sz[2];
+ double pos_cs[3];
+ double pos_cs_n[2];
+ ASSERT(sky && pos_ws && out_pos_cs);
+ ASSERT(pos_ws[2] >= sky->htcp_desc.lower[2]);
+ ASSERT(pos_ws[2] <= sky->htcp_desc.upper[2]);
+
+ if(!sky->repeat_clouds) { /* Nothing to do */
+ return d3_set(out_pos_cs, pos_ws);
+ }
+
+ if(!sky->repeat_clouds /* Nothing to do */
+ || ( pos_ws[0] >= sky->htcp_desc.lower[0]
+ && pos_ws[0] <= sky->htcp_desc.upper[0]
+ && pos_ws[1] >= sky->htcp_desc.lower[1]
+ && pos_ws[1] <= sky->htcp_desc.upper[1])) {
+ return d3_set(out_pos_cs, pos_ws);
+ }
+
+ cloud_sz[0] = sky->htcp_desc.upper[0] - sky->htcp_desc.lower[0];
+ cloud_sz[1] = sky->htcp_desc.upper[1] - sky->htcp_desc.lower[1];
+
+ /* Transform pos in normalize local cloud space */
+ pos_cs_n[0] = (pos_ws[0] - sky->htcp_desc.lower[0]) / cloud_sz[0];
+ pos_cs_n[1] = (pos_ws[1] - sky->htcp_desc.lower[1]) / cloud_sz[1];
+ pos_cs_n[0] -= (int)pos_cs_n[0]; /* Keep fractional part */
+ pos_cs_n[1] -= (int)pos_cs_n[1]; /* Keep fractional part */
+ if(pos_cs_n[0] < 0) pos_cs_n[0] += 1;
+ if(pos_cs_n[1] < 0) pos_cs_n[1] += 1;
+
+ /* Transform pos in local cloud space */
+ pos_cs[0] = sky->htcp_desc.lower[0] + pos_cs_n[0] * cloud_sz[0];
+ pos_cs[1] = sky->htcp_desc.lower[1] + pos_cs_n[1] * cloud_sz[1];
+ pos_cs[2] = pos_ws[2];
+
+ ASSERT(pos_cs[0] >= sky->htcp_desc.lower[0]);
+ ASSERT(pos_cs[0] <= sky->htcp_desc.upper[0]);
+ ASSERT(pos_cs[1] >= sky->htcp_desc.lower[1]);
+ ASSERT(pos_cs[1] <= sky->htcp_desc.upper[1]);
+
+ return d3_set(out_pos_cs, pos_cs);
+}
+
diff --git a/src/htsky.h b/src/htsky.h
@@ -0,0 +1,195 @@
+/* Copyright (C) 2020 |Meso|Star> (contact@meso-star.com)
+ *
+ * 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/>. */
+
+#ifndef HTSKY_H
+#define HTSKY_H
+
+#include <rsys/rsys.h>
+
+/* Library symbol management */
+#if defined(HTSKY_SHARED_BUILD) /* Build shared library */
+ #define HTSKY_API extern EXPORT_SYM
+#elif defined(SMTL_STATIC) /* Use/build static library */
+ #define HTSKY_API extern LOCAL_SYM
+#else /* Use shared library */
+ #define HTSKY_API extern IMPORT_SYM
+#endif
+
+#ifndef NDEBUG
+ #define HTSKY(Func) ASSERT(htsky_ ## Func == RES_OK)
+#else
+ #define HTSKY(Func) htsky_ ## Func
+#endif
+
+enum htsky_property {
+ HTSKY_Ks, /* Scattering coefficient */
+ HTSLY_Ka, /* Absorption coefficient */
+ HTSKY_Kext, /* Extinction coefficient = Ks + Ka */
+ HTSKY_PROPS_COUNT__
+};
+
+/* List of sky components */
+enum htsky_component {
+ HTSKY_CPNT_GAS,
+ HTSKY_CPNT_PARTICLES,
+ HTSKY_CPNTS_COUNT__
+};
+
+/* Component of the sky for which the properties are queried */
+enum htrdr_sky_component_flag {
+ HTSKY_CPNT_FLAG_GAS = BIT(HTSKY_CPNT_GAS),
+ HTSKY_CPNT_FLAG_PARTICLES = BIT(HTSKY__CPNT_PARTICLES),
+ HTSKY_CPNT_MASK_ALL = HTRDR_CPNT_FLAG_GAS | HTSKY_CPNT_FLAG_PARTICLES
+};
+
+enum htsky_svx_op {
+ HTSKY_SVX_MIN,
+ HTSKY_SVX_MAX,
+ HTSKY_SVX_OPS_COUNT__
+};
+
+struct htsky_args {
+ const char* htcp_filename;
+ const char* htgop_filename;
+ const char* htmie_filename;
+ unsigned grid_max_definition[3]; /* Maximum definition of the grid */
+ double optical_thickness; /* Threshold used during octree building */
+ unsigned nthreads; /* Hint on the number of threads to use */
+ int repeat_clouds; /* Define if the clouds are infinitely repeated in X and Y */
+ int verbose; /* Verbosity level */
+};
+
+#define HTSKY_ARGS_DEFAULT__ { \
+ NULL, /* htcp_filename */ \
+ NULL, /* htgop_filename */ \
+ NULL, /* htmie filename */ \
+ {UINT_MAX, UINT_MAX, UINT_MAX}, /* Maximum definition of the grid */ \
+ 1, /* Optical thickness a*/ \
+ (unsigned)~0, /* #threads */, \
+ 0, /* Repeat clouds */ \
+ 0, /* Verbosity level */ \
+}
+static const struct htsky_args HTSKY_ARGS_DEFAULT = HTSKY_ARGS_DEFAULT__;
+
+BEGIN_DECLS
+
+/*******************************************************************************
+ * HTSky API
+ ******************************************************************************/
+HTSKY_API res_T
+htsky_create
+ (struct logger* logger, /* NULL <=> use default logger */
+ struct mem_allocator* allocator, /* NULL <=> use default allocator */
+ const struct htsky_args* args,
+ struct htsky** htsky);
+
+HTSKY_API res_T
+htsky_ref_get
+ (struct htsky* htsky);
+
+HTSKY_API res_T
+htsky_ref_put
+ (struct htsky* htsky);
+
+HTSKY_API double
+htsky_fetch_particle_phase_function_asymmetry_parameter
+ (const struct htsky* sky,
+ const size_t ispectral_band,
+ const size_t iquad);
+
+HTSKY_API double
+htsky_fetch_raw_property
+ (const struct htsky* sky,
+ const enum htsky_property prop,
+ const int components_mask, /* Combination of htsky_component_flag */
+ const size_t iband, /* Index of the spectral band */
+ const size_t iquad, /* Index of the quadrature point in the spectral band */
+ const double pos[3],
+ /* For debug only. Assert if the fetched property is not in [k_min, k_max] */
+ const double k_min,
+ const double k_max);
+
+HTSKY_API double
+htsky_fetch_svx_property
+ (const struct htsky* sky,
+ const enum htsky_property prop,
+ const enum htsky_svx_op op,
+ const int components_mask, /* Combination of htsky_component_flag */
+ const size_t iband, /* Index of the spectral band */
+ const size_t iquad, /* Index of the quadrature point in the spectral band */
+ const double pos[3]);
+
+HTSKY_API double
+htsky_fetch_svx_voxel_property
+ (const struct htsky* sky,
+ const enum htsky_property prop,
+ const enum htsky_svx_op op,
+ const int components_mask,
+ const size_t ispectral_band, /* Index of the spectral band */
+ const size_t iquad, /* Index of the quadrature point in the spectral band */
+ const struct svx_voxel* voxel);
+
+HTSKY_API size_t
+htsky_get_sw_spectral_bands_count
+ (const struct htsky* sky);
+
+HTSKY_API size_t
+htsky_get_sw_spectral_band_id
+ (const struct htsky* sky,
+ const size_t i);
+
+HTSKY_API size_t
+htsky_get_sw_spectral_band_quadrature_length
+ (const struct htsky* sky,
+ const size_t iband);
+
+HTSKY_API res_T
+htsky_get_sw_spectral_band_bounds
+ (const struct htsky* sky,
+ const size_t iband,
+ double wavelengths[2]);
+
+HTSKY_API void
+htsky_sample_sw_spectral_data_CIE_1931_X
+ (const struct htsky* sky,
+ struct ssp_rng* rng,
+ size_t* ispectral_band,
+ size_t* iquadrature_pt);
+
+HTSKY_API void
+htsky_sample_sw_spectral_data_CIE_1931_Y
+ (const struct htsky* sky,
+ struct ssp_rng* rng,
+ size_t* ispectral_band,
+ size_t* iquadrature_pt);
+
+HTSKY_API void
+htsky_sample_sw_spectral_data_CIE_1931_Z
+ (const struct htsky* sky,
+ struct ssp_rng* rng,
+ size_t* ispectral_band,
+ size_t* iquadrature_pt);
+
+HTSKY_API res_T
+htsky_dump_clouds_vtk
+ (const struct htsky* sky,
+ const size_t iband, /* Index of the spectral band */
+ const size_t iquad, /* Index of the quadrature point */
+ FILE* stream);
+
+END_DECLS
+
+#endif /* HTSKY_H */
+
diff --git a/src/htsky_atmosphere.c b/src/htsky_atmosphere.c
@@ -0,0 +1,257 @@
+/* Copyright (C) 2020 |Meso|Star> (contact@meso-star.com)
+ *
+ * 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/>. */
+
+#define _POSIX_C_SOURCE 200809L /* nextafterf */
+
+#include "htsky_c.h"
+#include "htsky_atmosphere.h"
+#include "htsky_svx.h"
+
+#include <high_tune/htgop.h>
+#include <star/svx.h>
+
+#include <math.h>
+
+/*******************************************************************************
+ * Helper functions
+ ******************************************************************************/
+static void
+atmosphere_vox_get(const size_t xyz[3], void* dst, void* context)
+{
+ float* vox = dst;
+ struct build_tree_context* ctx = context;
+ struct htgop_level level;
+ size_t layer_range[2];
+ size_t nlevels;
+ double vox_low, vox_upp;
+ double ka_min, ks_min, kext_min;
+ double ka_max, ks_max, kext_max;
+ size_t ilayer;
+ ASSERT(xyz && dst && context);
+
+ /* Compute the boundaries of the SVX voxel */
+ HTGOP(get_level(ctx->sky->htgop, 0, &level));
+ vox_low = (double)xyz[2] * ctx->vxsz[2] + level.height;
+ HTGOP(get_levels_count(ctx->sky->htgop, &nlevels));
+ HTGOP(get_level(ctx->sky->htgop, nlevels-1, &level));
+ vox_upp = MMIN(vox_low + ctx->vxsz[2], level.height); /* Handle numerical issues */
+
+ /* Define the atmospheric layers overlapped by the SVX voxel */
+ HTGOP(position_to_layer_id(ctx->sky->htgop, vox_low, &layer_range[0]));
+ HTGOP(position_to_layer_id(ctx->sky->htgop, vox_upp, &layer_range[1]));
+
+ ka_min = ks_min = kext_min = DBL_MAX;
+ ka_max = ks_max = kext_max =-DBL_MAX;
+
+ /* For each atmospheric layer that overlaps the SVX voxel ... */
+ FOR_EACH(ilayer, layer_range[0], layer_range[1]+1) {
+ struct htgop_layer layer;
+ struct htgop_layer_sw_spectral_interval band;
+ size_t iquad;
+
+ HTGOP(get_layer(ctx->sky->htgop, ilayer, &layer));
+
+ /* ... retrieve the considered spectral interval */
+ HTGOP(layer_get_sw_spectral_interval(&layer, ctx->iband, &band));
+
+ /* ... and update the radiative properties bound with the per quadrature
+ * point nominal values */
+ ASSERT(ctx->quadrature_range[0] <= ctx->quadrature_range[1]);
+ ASSERT(ctx->quadrature_range[1] < band.quadrature_length);
+ FOR_EACH(iquad, ctx->quadrature_range[0], ctx->quadrature_range[1]+1) {
+ ka_min = MMIN(ka_min, band.ka_nominal[iquad]);
+ ka_max = MMAX(ka_max, band.ka_nominal[iquad]);
+ ks_min = MMIN(ks_min, band.ks_nominal[iquad]);
+ ks_max = MMAX(ks_max, band.ks_nominal[iquad]);
+ kext_min = MMIN(kext_min, band.ka_nominal[iquad]+band.ks_nominal[iquad]);
+ kext_max = MMAX(kext_max, band.ka_nominal[iquad]+band.ks_nominal[iquad]);
+ }
+ }
+
+ /* Ensure that the single precision bounds include their double precision
+ * version. */
+ if(ka_min != (float)ka_min) ka_min = nextafterf((float)ka_min,-FLT_MAX);
+ if(ka_max != (float)ka_max) ka_max = nextafterf((float)ka_max, FLT_MAX);
+ if(ks_min != (float)ks_min) ks_min = nextafterf((float)ks_min,-FLT_MAX);
+ if(ks_max != (float)ks_max) ks_max = nextafterf((float)ks_max, FLT_MAX);
+ if(kext_min != (float)kext_min) kext_min = nextafterf((float)kext_min,-FLT_MAX);
+ if(kext_max != (float)kext_max) kext_max = nextafterf((float)kext_max, FLT_MAX);
+
+ /* Setup gas optical properties of the voxel */
+ vox_set(vox, HTSKY_CPNT_GAS, HTSKY_Ka, HTSKY_SVX_MIN, (float)ka_min);
+ vox_set(vox, HTSKY_CPNT_GAS, HTSKY_Ka, HTSKY_SVX_MAX, (float)ka_max);
+ vox_set(vox, HTSKY_CPNT_GAS, HTSKY_Ks, HTSKY_SVX_MIN, (float)ks_min);
+ vox_set(vox, HTSKY_CPNT_GAS, HTSKY_Ks, HTSKY_SVX_MAX, (float)ks_max);
+ vox_set(vox, HTSKY_CPNT_GAS, HTSKY_Kext, HTSKY_SVX_MIN, (float)kext_min);
+ vox_set(vox, HTSKY_CPNT_GAS, HTSKY_Kext, HTSKY_SVX_MAX, (float)kext_max);
+}
+
+static void
+atmosphere_vox_merge
+ (void* dst,
+ const void* voxs[],
+ const size_t nvoxs,
+ void* ctx)
+{
+ ASSERT(dst && voxels && nvoxs);
+ (void)ctx;
+ vox_merge_component(dst, HTSKY_CPNT_GAS, (const float**)voxs, nvoxs);
+}
+
+static int
+atmosphere_vox_challenge_merge
+ (const struct svx_voxel voxs[]
+ const size_t nvoxs,
+ void* ctx)
+{
+ ASSERT(voxels);
+ return vox_challenge_merge_component(HTSKY_CPNT_GAS, voxs, nvoxs, ctx);
+}
+
+/*******************************************************************************
+ * Local functions
+ ******************************************************************************/
+res_T
+atmosphere_setup(struct htsky* sky, const double optical_thickness_threshold)
+{
+ struct build_tree_context ctx = BUILD_TREE_CONTEXT_NULL;
+ struct htgop_level lvl_low, lvl_upp;
+ struct svx_voxel_desc vox_desc = SVX_VOXEL_DESC_NULL;
+ double low, upp;
+ size_t nlayers, nlevels;
+ size_t definition;
+ size_t nbands;
+ size_t i;
+ res_T res = RES_OK;
+ ASSERT(sky && optical_thickness_threshold >= 0);
+
+ HTGOP(get_layers_count(sky->htgop, &nlayers));
+ HTGOP(get_levels_count(sky->htgop, &nlevels));
+ HTGOP(get_level(sky->htgop, 0, &lvl_low));
+ HTGOP(get_level(sky->htgop, nlevels-1, &lvl_upp));
+ low = lvl_low.height;
+ upp = lvl_upp.height;
+ definition = nlayers;
+
+ /* Setup the build context */
+ ctx.sky = sky;
+ ctx.tau_threshold = optical_thickness_threshold;
+ ctx.vxsz[0] = INF;
+ ctx.vxsz[1] = INF;
+ ctx.vxsz[2] = (upp-low)/(double)definition;
+
+ /* Setup the voxel descriptor for the atmosphere. Note that in contrats with
+ * the clouds, the voxel contains only NFLOATS_PER_CPNT floats and not
+ * NFLOATS_PER_VOXEL. Indeed, the atmosphere has only 1 component: the gas.
+ * Anyway, we still rely on the memory layout of the cloud voxels excepted
+ * that we assume that the optical properties of the particles are never
+ * fetched. We thus have to ensure that the gas properties are arranged
+ * before the particles, i.e. HTSKY_CPNT_GAS == 0 */
+ vox_desc.get = atmosphere_vox_get;
+ vox_desc.merge = atmosphere_vox_merge;
+ vox_desc.challenge_merge = atmosphere_vox_challenge_merge;
+ vox_desc.context = &ctx;
+ vox_desc.size = sizeof(float) * NFLOATS_PER_CPNT;
+ { STATIC_ASSERT(HTSKY_CPNT_GAS == 0, Unexpected_enum_value); }
+
+ /* Create as many atmospheric data structure than considered SW spectral
+ * bands */
+ nbands = htsky_get_sw_spectral_bands_count(sky);
+ sky->atmosphere = MEM_CALLOC
+ (sky->allocator, nbands, sizeof(*sky->atmosphere));
+ if(!sky->atmosphere) {
+ log_err(sky,
+ "could not create the list of per SW band atmospheric data structure.\n");
+ res = RES_MEM_ERR;
+ goto error;
+ }
+
+ FOR_EACH(i, 0, nbands) {
+ size_t iquad;
+ struct htgop_spectral_interval band;
+ ctx.iband = i + sky->sw_bands_range[0];
+
+ HTGOP(get_sw_spectral_interval(sky->htgop, ctx.iband, &band));
+
+ sky->atmosphere[i] = MEM_CALLOC(sky->allocator,
+ band.quadrature_length, sizeof(*sky->atmosphere[i]));
+ if(!sky->atmosphere[i]) {
+ log_err(sky,
+ "could not create the list of per quadrature point atmospheric data "
+ "for the band %lu.\n", (unsigned long)ctx.iband);
+ res = RES_MEM_ERR;
+ goto error;
+ }
+
+ /* Build an atmospheric binary tree for each quadrature point of the
+ * considered spectral band */
+ FOR_EACH(iquad, 0, band.quadrature_length) {
+ ctx.quadrature_range[0] = iquad;
+ ctx.quadrature_range[1] = iquad;
+
+ /* Create the atmospheric binary tree */
+ res = svx_bintree_create(sky->svx, low, upp, definition, SVX_AXIS_Z,
+ &vox_desc, &sky->atmosphere[i][iquad].bitree);
+ if(res != RES_OK) {
+ log_err(sky, "could not create the binary tree of the "
+ "atmospheric properties for the band %lu.\n", (unsigned long)ctx.iband);
+ goto error;
+ }
+
+ /* Fetch the binary tree descriptor for future use */
+ SVX(tree_get_desc(sky->atmosphere[i][iquad].bitree,
+ &sky->atmosphere[i][iquad].bitree_desc));
+ }
+ }
+
+exit:
+ return res;
+error:
+ atmosphere_clean(sky);
+ goto exit;
+}
+
+void
+atmosphere_clean(struct htsky* sky)
+{
+ size_t nbands;
+ size_t i;
+ ASSERT(sky);
+
+ if(!sky->atmosphere) return;
+
+ nbands = htsky_get_sw_spectral_bands_count(sky);
+ FOR_EACH(i, 0, nbands) {
+ struct htgop_spectral_interval band;
+ size_t iband;
+ size_t iquad;
+
+ iband = sky->sw_bands_range[0] + i;
+ HTGOP(get_sw_spectral_interval(sky->htgop, iband, &band));
+
+ if(!sky->atmosphere[i]) continue;
+
+ FOR_EACH(iquad, 0, band.quadrature_length) {
+ if(sky->atmosphere[i][iquad].bitree) {
+ SVX(tree_ref_put(sky->atmosphere[i][iquad].bitree));
+ sky->atmosphere[i][iquad].bitree = NULL;
+ }
+ }
+ MEM_RM(sky->allocator, sky->atmosphere[i]);
+ }
+ MEM_RM(sky->allocator, sky->atmosphere);
+ sky->atmosphere = NULL;
+}
+
diff --git a/src/htsky_atmosphere.h b/src/htsky_atmosphere.h
@@ -0,0 +1,37 @@
+/* Copyright (C) 2020 |Meso|Star> (contact@meso-star.com)
+ *
+ * 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/>. */
+
+#ifndef HTSKY_ATMOSPHERE_H
+#define HTSKY_ATMOSPHERE_H
+
+#include <star/svx.h> /* svx_tree_desc */
+
+struct htsky;
+
+struct atmosphere {
+ struct svx_tree* bitree;
+ struct svx_tree_desc bitree_desc;
+};
+
+extern LOCAL_SYM res_T
+atmosphere_setup
+ (struct htsky* sky,
+ const double optical_thickness_threshold);
+
+extern LOCAL_SYM void
+atmosphere_clean
+ (struct htsky* sky);
+
+#endif /* HTSKY_ATMOSPHERE_H */
diff --git a/src/htsky_c.h b/src/htsky_c.h
@@ -0,0 +1,144 @@
+/* Copyright (C) 2020 |Meso|Star> (contact@meso-star.com)
+ *
+ * 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/>. */
+
+#ifndef HTSKY_C_H
+#define HTSKY_C_H
+
+#include <high_tune/htcp.h>
+
+#include <rsys/logger.h>
+#include <rsys/mem_allocator.h>
+#include <rsys/ref_count.h>
+
+/* Declare some constants */
+#define DRY_AIR_MOLAR_MASS 0.0289644 /* In kg.mol^-1 */
+#define H2O_MOLAR_MASS 0.01801528 /* In kg.mol^-1 */
+#define GAS_CONSTANT 8.3144598 /* In kg.m^2.s^-2.mol^-1.K */
+
+/* Forward declaration of external data types */
+struct htcp;
+struct htgop;
+struct htmie;
+struct svx_tree;
+struct svx_tree_desc;
+
+/* Forward declarations of internal data types */
+struct atmosphere;
+
+struct split {
+ size_t index; /* Index of the current htcp voxel */
+ double height; /* Absolute height where the next voxel starts */
+};
+
+#define DARRAY_NAME split
+#define DARRAY_DATA struct split
+#include <rsys/dynamic_array.h>
+
+/* Properties of a short wave spectral band */
+struct sw_band_prop {
+ /* Average cross section in the band */
+ double Ca_avg; /* Absorption cross section */
+ double Cs_avg; /* Scattering cross section */
+
+ /* Average asymmetry parameter the band */
+ double g_avg;
+};
+
+struct htrdr_sky {
+ struct cloud** clouds; /* Per sw_band cloud data structure */
+
+ /* Per sw_band and per quadrature point atmosphere data structure */
+ struct atmosphere** atmosphere;
+
+ /* Loaders of... */
+ struct htcp* htcp; /* ... Cloud properties */
+ struct htgop* htgop; /* ... Gas optical properties */
+ struct htmie* htmie; /* ... Mie's data */
+
+ /* Star-VX library handle */
+ struct svx_device* svx;
+
+ struct htcp_desc htcp_desc; /* Descriptor of the loaded LES data */
+
+ /* LUT used to map the index of a Z from the regular SVX to the irregular
+ * HTCP data */
+ struct darray_split svx2htcp_z;
+ double lut_cell_sz; /* Size of a svx2htcp_z cell */
+
+ /* Ids and optical properties of the short wave spectral bands loaded by
+ * HTGOP and that overlap the CIE XYZ color space */
+ size_t sw_bands_range[2];
+ struct sw_band_prop* sw_bands;
+
+ int repeat_clouds; /* Make clouds infinite in X and Y */
+ int is_cloudy; /* The sky has clouds */
+
+ unsigned nthreads; /* #threads */
+
+ struct mem_allocator* allocator;
+ struct mem_allocator svx_allocator;
+ struct logger* logger;
+ struct logger logger__; /* Default logger */
+ int verbose;
+ ref_T ref;
+};
+
+static FINLINE double
+wavenumber_to_wavelength(const double nu/*In cm^-1*/)
+{
+ return 1.e7 / nu;
+}
+
+/* In cm^-1 */
+static FINLINE double
+wavelength_to_wavenumber(const double lambda/*In nanometer*/)
+{
+ return wavenumber_to_wavelength(lambda);
+}
+
+/* Compute the dry air density in the cloud */
+static FINLINE double
+cloud_dry_air_density
+ (const struct htcp_desc* desc,
+ const size_t ivox[3]) /* Index of the voxel */
+{
+ double P = 0; /* Pressure in Pa */
+ double T = 0; /* Temperature in K */
+ ASSERT(desc && ivox);
+ P = htcp_desc_PABST_at(desc, ivox[0], ivox[1], ivox[2], 0/*time*/);
+ T = htcp_desc_T_at(desc, ivox[0], ivox[1], ivox[2], 0/*time*/);
+ return (P*DRY_AIR_MOLAR_MASS)/(T*GAS_CONSTANT);
+}
+
+/* Compute the water molar fraction */
+static FINLINE double
+cloud_water_vapor_molar_fraction
+ (const struct htcp_desc* desc,
+ const size_t ivox[3])
+{
+ double rvt = 0;
+ ASSERT(desc && ivox);
+ rvt = htcp_desc_RVT_at(desc, ivox[0], ivox[1], ivox[2], 0/*time*/);
+ return rvt / (rvt + H2O_MOLAR_MASS/DRY_AIR_MOLAR_MASS);
+}
+
+/* Transform a position from world to cloud space */
+extern LOCAL_SYM double*
+world_to_cloud
+ (const struct htsky* sky,
+ const double pos_ws[3], /* World space position */
+ double out_pos_cs[3]);
+
+#endif /* HTSKY_C_H */
diff --git a/src/htsky_cloud.c b/src/htsky_cloud.c
@@ -0,0 +1,692 @@
+/* Copyright (C) 2020 |Meso|Star> (contact@meso-star.com)
+ *
+ * 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/>. */
+
+#define _POSIX_C_SOURCE 200809L /* nextafterf */
+
+#include "htsky_cloud.h"
+#include "htsky_svx.h"
+
+#include <rsys/dynamic_array.h>
+#include <star/svx.h>
+
+#include <omp.h>
+
+struct spectral_data {
+ size_t iband; /* Index of the spectral band */
+ size_t iquad; /* Quadrature point into the band */
+};
+
+/* Define the dynamic array of spectral data */
+#define DARRAY_NAME specdata
+#define DARRAY_DATA struct spectral_data
+#include <rsys/dynamic_array.h>
+
+/*******************************************************************************
+ * Helper functions
+ ******************************************************************************/
+static INLINE int
+aabb_intersect
+ (const double aabb0_low[3],
+ const double aabb0_upp[3],
+ const double aabb1_low[3],
+ const double aabb1_upp[3])
+{
+ ASSERT(aabb0_low[0] < aabb0_upp[0] && aabb1_low[0] < aabb1_upp[0]);
+ ASSERT(aabb0_low[1] < aabb0_upp[1] && aabb1_low[1] < aabb1_upp[1]);
+ ASSERT(aabb0_low[2] < aabb0_upp[2] && aabb1_low[2] < aabb1_upp[2]);
+ return !(aabb0_upp[0] < aabb1_low[0]) && !(aabb0_low[0] > aabb1_upp[0])
+ && !(aabb0_upp[1] < aabb1_low[1]) && !(aabb0_low[1] > aabb1_upp[1])
+ && !(aabb0_upp[2] < aabb1_low[2]) && !(aabb0_low[2] > aabb1_upp[2]);
+}
+
+static void
+cloud_vox_get_particle
+ (const size_t xyz[3],
+ float vox[],
+ const struct build_tree_context* ctx)
+{
+ const struct htcp_desc* htcp_desc;
+ size_t ivox[3];
+ size_t igrid_low[3], igrid_upp[3];
+ double vox_low[3], vox_upp[3];
+ double low[3], upp[3];
+ double rct;
+ double ka, ks, kext;
+ double ka_min, ka_max;
+ double ks_min, ks_max;
+ double kext_min, kext_max;
+ double rho_da; /* Dry air density */
+ double Ca_avg;
+ double Cs_avg;
+ double ipart;
+ size_t i;
+ ASSERT(xyz && vox && ctx);
+
+ i = ctx->iband - ctx->sky->sw_bands_range[0];
+ htcp_desc = &ctx->sky->htcp_desc;
+
+ /* Fetch the optical properties of the spectral band */
+ Ca_avg = ctx->sky->sw_bands[i].Ca_avg;
+ Cs_avg = ctx->sky->sw_bands[i].Cs_avg;
+
+ /* Compute the AABB of the SVX voxel */
+ vox_low[0] = (double)xyz[0] * ctx->vxsz[0] + htcp_desc->lower[0];
+ vox_low[1] = (double)xyz[1] * ctx->vxsz[1] + htcp_desc->lower[1];
+ vox_low[2] = (double)xyz[2] * ctx->vxsz[2] + htcp_desc->lower[2];
+ vox_upp[0] = vox_low[0] + ctx->vxsz[0];
+ vox_upp[1] = vox_low[1] + ctx->vxsz[1];
+ vox_upp[2] = vox_low[2] + ctx->vxsz[2];
+
+ /* Compute the *inclusive* bounds of the indices of cloud grid overlapped by
+ * the SVX voxel in X and Y */
+ low[0] = (vox_low[0]-htcp_desc->lower[0])/htcp_desc->vxsz_x;
+ low[1] = (vox_low[1]-htcp_desc->lower[1])/htcp_desc->vxsz_x;
+ upp[0] = (vox_upp[0]-htcp_desc->lower[0])/htcp_desc->vxsz_y;
+ upp[1] = (vox_upp[1]-htcp_desc->lower[1])/htcp_desc->vxsz_y;
+ igrid_low[0] = (size_t)low[0];
+ igrid_low[1] = (size_t)low[1];
+ igrid_upp[0] = (size_t)upp[0] - (modf(upp[0], &ipart)==0);
+ igrid_upp[1] = (size_t)upp[1] - (modf(upp[1], &ipart)==0);
+ ASSERT(igrid_low[0] <= igrid_upp[0]);
+ ASSERT(igrid_low[1] <= igrid_upp[1]);
+
+ if(!ctx->sky->htcp_desc.irregular_z) { /* 1 LES voxel <=> 1 SVX voxel */
+ /* Compute the *inclusive* bounds of the indices of cloud grid overlapped by
+ * the SVX voxel along the Z axis */
+ low[2] = (vox_low[2]-htcp_desc->lower[2])/htcp_desc->vxsz_z[0];
+ upp[2] = (vox_upp[2]-htcp_desc->lower[2])/htcp_desc->vxsz_z[0];
+ igrid_low[2] = (size_t)low[2];
+ igrid_upp[2] = (size_t)upp[2] - (modf(upp[2], &ipart)==0);
+ ASSERT(igrid_low[2] <= igrid_upp[2]);
+
+ /* Prepare the iteration over the grid voxels overlapped by the SVX voxel */
+ ka_min = ks_min = kext_min = DBL_MAX;
+ ka_max = ks_max = kext_max =-DBL_MAX;
+
+ /* Iterate over the grid voxels overlapped by the SVX voxel */
+ FOR_EACH(ivox[0], igrid_low[0], igrid_upp[0]+1) {
+ FOR_EACH(ivox[1], igrid_low[1], igrid_upp[1]+1) {
+ FOR_EACH(ivox[2], igrid_low[2], igrid_upp[2]+1) {
+ /* Compute the radiative properties */
+ rho_da = cloud_dry_air_density(htcp_desc, ivox);
+ rct = htcp_desc_RCT_at(htcp_desc, ivox[0], ivox[1], ivox[2], 0);
+ ka = Ca_avg * rho_da * rct;
+ ks = Cs_avg * rho_da * rct;
+ kext = ka + ks;
+ /* Update the boundaries of the radiative properties */
+ ka_min = MMIN(ka_min, ka);
+ ka_max = MMAX(ka_max, ka);
+ ks_min = MMIN(ks_min, ks);
+ ks_max = MMAX(ks_max, ks);
+ kext_min = MMIN(kext_min, kext);
+ kext_max = MMAX(kext_max, kext);
+ #ifndef NDEBUG
+ {
+ double tmp_low[3], tmp_upp[3];
+ htcp_desc_get_voxel_aabb
+ (&ctx->sky->htcp_desc, ivox[0], ivox[1], ivox[2], tmp_low, tmp_upp);
+ ASSERT(aabb_intersect(tmp_low, tmp_upp, vox_low, vox_upp));
+ }
+ #endif
+ }
+ }
+ }
+ } else {
+ double pos_z;
+ size_t ilut_low, ilut_upp;
+ size_t ilut;
+ size_t ivox_z_prev = SIZE_MAX;
+
+ /* Compute the *inclusive* bounds of the indices of the LUT cells
+ * overlapped by the SVX voxel */
+ ilut_low = (size_t)((vox_low[2]-htcp_desc->lower[2])/ctx->sky->lut_cell_sz);
+ ilut_upp = (size_t)((vox_upp[2]-htcp_desc->lower[2])/ctx->sky->lut_cell_sz);
+ ASSERT(ilut_low <= ilut_upp);
+
+ /* Prepare the iteration over the LES voxels overlapped by the SVX voxel */
+ ka_min = ks_min = kext_min = DBL_MAX;
+ ka_max = ks_max = kext_max =-DBL_MAX;
+ ivox_z_prev = SIZE_MAX;
+ pos_z = vox_low[2];
+ ASSERT(pos_z >= (double)ilut_low * ctx->sky->lut_cell_sz);
+ ASSERT(pos_z <= (double)ilut_upp * ctx->sky->lut_cell_sz);
+
+ /* Iterate over the LUT cells overlapped by the voxel */
+ FOR_EACH(ilut, ilut_low, ilut_upp+1) {
+ const struct split* split = darray_split_cdata_get(&ctx->sky->svx2htcp_z)+ilut;
+ ASSERT(ilut < darray_split_size_get(&ctx->sky->svx2htcp_z));
+
+ ivox[2] = pos_z <= split->height ? split->index : split->index + 1;
+ if(ivox[2] >= ctx->sky->htcp_desc.spatial_definition[2]
+ && eq_eps(pos_z, split->height, 1.e-6)) { /* Handle numerical inaccuracy */
+ ivox[2] = split->index;
+ }
+
+ /* Compute the upper bound of the *next* LUT cell clamped to the voxel
+ * upper bound. Note that the upper bound of the current LUT cell is
+ * the lower bound of the next cell, i.e. (ilut+1)*lut_cell_sz. The
+ * upper bound of the next cell is thus the lower bound of the cell
+ * following the next cell, i.e. (ilut+2)*lut_cell_sz */
+ pos_z = MMIN((double)(ilut+2)*ctx->sky->lut_cell_sz, vox_upp[2]);
+
+ /* Does the LUT cell overlap an already handled LES voxel? */
+ if(ivox[2] == ivox_z_prev) continue;
+ ivox_z_prev = ivox[2];
+
+ FOR_EACH(ivox[0], igrid_low[0], igrid_upp[0]+1) {
+ FOR_EACH(ivox[1], igrid_low[1], igrid_upp[1]+1) {
+
+ /* Compute the radiative properties */
+ rho_da = cloud_dry_air_density(htcp_desc, ivox);
+ rct = htcp_desc_RCT_at(htcp_desc, ivox[0], ivox[1], ivox[2], 0);
+ ka = Ca_avg * rho_da * rct;
+ ks = Cs_avg * rho_da * rct;
+ kext = ka + ks;
+
+ /* Update the boundaries of the radiative properties */
+ ka_min = MMIN(ka_min, ka);
+ ka_max = MMAX(ka_max, ka);
+ ks_min = MMIN(ks_min, ks);
+ ks_max = MMAX(ks_max, ks);
+ kext_min = MMIN(kext_min, kext);
+ kext_max = MMAX(kext_max, kext);
+ }
+ }
+ }
+ }
+
+ /* Ensure that the single precision bounds include their double precision
+ * version. */
+ if(ka_min != (float)ka_min) ka_min = nextafterf((float)ka_min,-FLT_MAX);
+ if(ka_max != (float)ka_max) ka_max = nextafterf((float)ka_max, FLT_MAX);
+ if(ks_min != (float)ks_min) ks_min = nextafterf((float)ks_min,-FLT_MAX);
+ if(ks_max != (float)ks_max) ks_max = nextafterf((float)ks_max, FLT_MAX);
+ if(kext_min != (float)kext_min) kext_min = nextafterf((float)kext_min,-FLT_MAX);
+ if(kext_max != (float)kext_max) kext_max = nextafterf((float)kext_max, FLT_MAX);
+
+ vox_set(vox, HTSKY_CPNT_PARTICLES, HTSKY_Ka, HTSKY_SVX_MIN, (float)ka_min);
+ vox_set(vox, HTSKY_CPNT_PARTICLES, HTSKY_Ka, HTSKY_SVX_MAX, (float)ka_max);
+ vox_set(vox, HTSKY_CPNT_PARTICLES, HTSKY_Ks, HTSKY_SVX_MIN, (float)ks_min);
+ vox_set(vox, HTSKY_CPNT_PARTICLES, HTSKY_Ks, HTSKY_SVX_MAX, (float)ks_max);
+ vox_set(vox, HTSKY_CPNT_PARTICLES, HTSKY_Kext, HTSKY_SVX_MIN, (float)kext_min);
+ vox_set(vox, HTSKY_CPNT_PARTICLES, HTSKY_Kext, HTSKY_SVX_MAX, (float)kext_max);
+}
+
+static void
+cloud_vox_get_gas
+ (const size_t xyz[3],
+ float vox[],
+ const struct build_tree_context* ctx)
+{
+ const struct htcp_desc* htcp_desc;
+ size_t ivox[3];
+ size_t igrid_low[3], igrid_upp[3];
+ struct htgop_layer layer;
+ struct htgop_layer_sw_spectral_interval band;
+ size_t ilayer;
+ size_t layer_range[2];
+ double x_h2o_range[2];
+ double low[3], upp[3];
+ double vox_low[3], vox_upp[3]; /* Voxel AABB */
+ double ka_min, ka_max;
+ double ks_min, ks_max;
+ double kext_min, kext_max;
+ double x_h2o;
+ double ipart;
+ ASSERT(xyz && vox && ctx);
+
+ htcp_desc = &ctx->sky->htcp_desc;
+
+ /* Compute the AABB of the SVX voxel */
+ vox_low[0] = (double)xyz[0] * ctx->vxsz[0] + htcp_desc->lower[0];
+ vox_low[1] = (double)xyz[1] * ctx->vxsz[1] + htcp_desc->lower[1];
+ vox_low[2] = (double)xyz[2] * ctx->vxsz[2] + htcp_desc->lower[2];
+ vox_upp[0] = vox_low[0] + ctx->vxsz[0];
+ vox_upp[1] = vox_low[1] + ctx->vxsz[1];
+ vox_upp[2] = vox_low[2] + ctx->vxsz[2];
+
+ /* Compute the *inclusive* bounds of the indices of cloud grid overlapped by
+ * the SVX voxel in X and Y */
+ low[0] = (vox_low[0]-htcp_desc->lower[0])/htcp_desc->vxsz_x;
+ low[1] = (vox_low[1]-htcp_desc->lower[1])/htcp_desc->vxsz_x;
+ upp[0] = (vox_upp[0]-htcp_desc->lower[0])/htcp_desc->vxsz_y;
+ upp[1] = (vox_upp[1]-htcp_desc->lower[1])/htcp_desc->vxsz_y;
+ igrid_low[0] = (size_t)low[0];
+ igrid_low[1] = (size_t)low[1];
+ igrid_upp[0] = (size_t)upp[0] - (modf(upp[0], &ipart)==0);
+ igrid_upp[1] = (size_t)upp[1] - (modf(upp[1], &ipart)==0);
+ ASSERT(igrid_low[0] <= igrid_upp[0]);
+ ASSERT(igrid_low[1] <= igrid_upp[1]);
+
+ /* Define the xH2O range from the LES data */
+ if(!ctx->sky->htcp_desc.irregular_z) { /* 1 LES voxel <=> 1 SVX voxel */
+ /* Compute the *inclusive* bounds of the indices of cloud grid overlapped by
+ * the SVX voxel in Z */
+ low[2] = (vox_low[2]-htcp_desc->lower[2])/htcp_desc->vxsz_z[0];
+ upp[2] = (vox_upp[2]-htcp_desc->lower[2])/htcp_desc->vxsz_z[0];
+ igrid_low[2] = (size_t)low[2];
+ igrid_upp[2] = (size_t)upp[2] - (modf(upp[2], &ipart)==0);
+ ASSERT(igrid_low[2] <= igrid_upp[2]);
+
+ /* Prepare the iteration overt the grid voxels overlapped by the SVX voxel */
+ x_h2o_range[0] = DBL_MAX;
+ x_h2o_range[1] =-DBL_MAX;
+
+ FOR_EACH(ivox[0], igrid_low[0], igrid_upp[0]+1) {
+ FOR_EACH(ivox[1], igrid_low[1], igrid_upp[1]+1) {
+ FOR_EACH(ivox[2], igrid_low[2], igrid_upp[2]+1) {
+
+ /* Compute the xH2O for the current LES voxel */
+ x_h2o = cloud_water_vapor_molar_fraction(htcp_desc, ivox);
+
+ /* Update the xH2O range of the SVX voxel */
+ x_h2o_range[0] = MMIN(x_h2o, x_h2o_range[0]);
+ x_h2o_range[1] = MMAX(x_h2o, x_h2o_range[1]);
+ #ifndef NDEBUG
+ {
+ double tmp_low[3], tmp_upp[3];
+ htcp_desc_get_voxel_aabb
+ (&ctx->sky->htcp_desc, ivox[0], ivox[1], ivox[2], tmp_low, tmp_upp);
+ ASSERT(aabb_intersect(tmp_low, tmp_upp, vox_low, vox_upp));
+ }
+ #endif
+ }
+ }
+ }
+ } else { /* A SVX voxel can be overlapped by 2 LES voxels */
+ double pos_z;
+ size_t ilut_low, ilut_upp;
+ size_t ilut;
+ size_t ivox_z_prev;
+ ASSERT(xyz[2] < darray_split_size_get(&ctx->sky->svx2htcp_z));
+
+ /* Compute the *inclusive* bounds of the indices of the LUT cells
+ * overlapped by the SVX voxel */
+ ilut_low = (size_t)((vox_low[2] - htcp_desc->lower[2]) / ctx->sky->lut_cell_sz);
+ ilut_upp = (size_t)((vox_upp[2] - htcp_desc->lower[2]) / ctx->sky->lut_cell_sz);
+ ASSERT(ilut_low <= ilut_upp);
+
+ /* Prepare the iteration over the LES voxels overlapped by the SVX voxel */
+ x_h2o_range[0] = DBL_MAX;
+ x_h2o_range[1] =-DBL_MAX;
+ ivox_z_prev = SIZE_MAX;
+ pos_z = vox_low[2];
+ ASSERT(pos_z >= (double)ilut_low * ctx->sky->lut_cell_sz);
+ ASSERT(pos_z <= (double)ilut_upp * ctx->sky->lut_cell_sz);
+
+ /* Iterate over the LUT cells overlapped by the voxel */
+ FOR_EACH(ilut, ilut_low, ilut_upp+1) {
+ const struct split* split = darray_split_cdata_get(&ctx->sky->svx2htcp_z)+ilut;
+ ASSERT(ilut < darray_split_size_get(&ctx->sky->svx2htcp_z));
+
+ ivox[2] = pos_z <= split->height ? split->index : split->index + 1;
+ if(ivox[2] >= ctx->sky->htcp_desc.spatial_definition[2]
+ && eq_eps(pos_z, split->height, 1.e-6)) { /* Handle numerical inaccuracy */
+ ivox[2] = split->index;
+ }
+
+ /* Compute the upper bound of the *next* LUT cell clamped to the voxel
+ * upper bound. Note that the upper bound of the current LUT cell is
+ * the lower bound of the next cell, i.e. (ilut+1)*lut_cell_sz. The
+ * upper bound of the next cell is thus the lower bound of the cell
+ * following the next cell, i.e. (ilut+2)*lut_cell_sz */
+ pos_z = MMIN((double)(ilut+2)*ctx->sky->lut_cell_sz, vox_upp[2]);
+
+ /* Does the LUT voxel overlap an already handled LES voxel? */
+ if(ivox[2] == ivox_z_prev) continue;
+ ivox_z_prev = ivox[2];
+
+ FOR_EACH(ivox[0], igrid_low[0], igrid_upp[0]+1) {
+ FOR_EACH(ivox[1], igrid_low[1], igrid_upp[1]+1) {
+
+ /* Compute the xH2O for the current LES voxel */
+ x_h2o = cloud_water_vapor_molar_fraction(&ctx->sky->htcp_desc, ivox);
+
+ /* Update the xH2O range of the SVX voxel */
+ x_h2o_range[0] = MMIN(x_h2o, x_h2o_range[0]);
+ x_h2o_range[1] = MMAX(x_h2o, x_h2o_range[1]);
+ }
+ }
+ }
+ }
+
+ /* Define the atmospheric layers overlapped by the SVX voxel */
+ HTGOP(position_to_layer_id(ctx->sky->htgop, vox_low[2], &layer_range[0]));
+ HTGOP(position_to_layer_id(ctx->sky->htgop, vox_upp[2], &layer_range[1]));
+
+ ka_min = ks_min = kext_min = DBL_MAX;
+ ka_max = ks_max = kext_max =-DBL_MAX;
+
+ /* For each atmospheric layer that overlaps the SVX voxel ... */
+ FOR_EACH(ilayer, layer_range[0], layer_range[1]+1) {
+ double k[2];
+
+ HTGOP(get_layer(ctx->sky->htgop, ilayer, &layer));
+
+ /* ... retrieve the considered spectral interval */
+ HTGOP(layer_get_sw_spectral_interval(&layer, ctx->iband, &band));
+ ASSERT(ctx->quadrature_range[0] <= ctx->quadrature_range[1]);
+ ASSERT(ctx->quadrature_range[1] < band.quadrature_length);
+
+ /* ... and compute the radiative properties and upd their bounds */
+ HTGOP(layer_sw_spectral_interval_quadpoints_get_ka_bounds
+ (&band, ctx->quadrature_range, x_h2o_range, k));
+ ka_min = MMIN(ka_min, k[0]);
+ ka_max = MMAX(ka_max, k[1]);
+ HTGOP(layer_sw_spectral_interval_quadpoints_get_ks_bounds
+ (&band, ctx->quadrature_range, x_h2o_range, k));
+ ks_min = MMIN(ks_min, k[0]);
+ ks_max = MMAX(ks_max, k[1]);
+ HTGOP(layer_sw_spectral_interval_quadpoints_get_kext_bounds
+ (&band, ctx->quadrature_range, x_h2o_range, k));
+ kext_min = MMIN(kext_min, k[0]);
+ kext_max = MMAX(kext_max, k[1]);
+ }
+
+ /* Ensure that the single precision bounds include their double precision
+ * version. */
+ if(ka_min != (float)ka_min) ka_min = nextafterf((float)ka_min,-FLT_MAX);
+ if(ka_max != (float)ka_max) ka_max = nextafterf((float)ka_max, FLT_MAX);
+ if(ks_min != (float)ks_min) ks_min = nextafterf((float)ks_min,-FLT_MAX);
+ if(ks_max != (float)ks_max) ks_max = nextafterf((float)ks_max, FLT_MAX);
+ if(kext_min != (float)kext_min) kext_min = nextafterf((float)kext_min,-FLT_MAX);
+ if(kext_max != (float)kext_max) kext_max = nextafterf((float)kext_max, FLT_MAX);
+
+ vox_set(vox, HTSKY_CPNT_GAS, HTSKY_Ka, HTSKY_SVX_MIN, (float)ka_min);
+ vox_set(vox, HTSKY_CPNT_GAS, HTSKY_Ka, HTSKY_SVX_MAX, (float)ka_max);
+ vox_set(vox, HTSKY_CPNT_GAS, HTSKY_Ks, HTSKY_SVX_MIN, (float)ks_min);
+ vox_set(vox, HTSKY_CPNT_GAS, HTSKY_Ks, HTSKY_SVX_MAX, (float)ks_max);
+ vox_set(vox, HTSKY_CPNT_GAS, HTSKY_Kext, HTSKY_SVX_MIN, (float)kext_min);
+ vox_set(vox, HTSKY_CPNT_GAS, HTSKY_Kext, HTSKY_SVX_MAX, (float)kext_max);
+}
+
+static void
+cloud_vox_get(const size_t xyz[3], void* dst, void* context)
+{
+ struct build_tree_context* ctx = context;
+ ASSERT(context);
+ cloud_vox_get_particle(xyz, dst, ctx);
+ cloud_vox_get_gas(xyz, dst, ctx);
+}
+
+static void
+cloud_vox_merge(void* dst, const void* voxels[], const size_t nvoxs, void* context)
+{
+ ASSERT(dst && voxels && nvoxs);
+ (void)context;
+ vox_merge_component(dst, HTSKY_CPNT_PARTICLES, (const float**)voxels, nvoxs);
+ vox_merge_component(dst, HTSKY_CPNT_GAS, (const float**)voxels, nvoxs);
+}
+
+static int
+cloud_vox_challenge_merge
+ (const struct svx_voxel voxels[], const size_t nvoxs, void* ctx)
+{
+ ASSERT(voxels);
+ return vox_challenge_merge_component(HTSKY_CPNT_PARTICLES, voxels, nvoxs, ctx)
+ && vox_challenge_merge_component(HTSKY_CPNT_GAS, voxels, nvoxs, ctx);
+}
+
+/*******************************************************************************
+ * Local functions
+ ******************************************************************************/
+static res_T
+cloud_setup
+ (struct htsky* sky,
+ const char* htcp_filename,
+ const char* htgop_filename,
+ const char* htmie_filename,
+ const double grid_max_definition[3],
+ const double optical_thickness_threshold)
+{
+ struct darray_specdata specdata;
+ const size_t* raw_def;
+ size_t nvoxs[3];
+ double vxsz[3];
+ double low[3];
+ double upp[3];
+ int64_t ispecdata;
+ int32_t progress;
+ size_t nbands;
+ size_t i;
+ ATOMIC nbuilt_octrees = 0;
+ ATOMIC res = RES_OK;
+ ASSERT(grid_max_definition);
+ ASSERT(sky && sky->sw_bands && optical_thickness_threshold >= 0);
+
+ darray_specdata_init(sky->allocator, &specdata);
+
+ res = htcp_get_desc(sky->htcp, &sky->htcp_desc);
+ if(res != RES_OK) {
+ log_err(sky, "could not retrieve the HTCP descriptor.\n");
+ goto error;
+ }
+
+ log_info(sky, "Clouds bounding box: {%g, %g, %g} / {%g, %g, %g}.\n",
+ SPLIT3(sky->htcp_desc.lower), SPLIT3(sky->htcp_desc.upper));
+
+ /* Define the number of voxels */
+ raw_def = sky->htcp_desc.spatial_definition;
+ nvoxs[0] = MMIN(raw_def[0], grid_max_definition[0]);
+ nvoxs[1] = MMIN(raw_def[1], grid_max_definition[1]);
+ nvoxs[2] = MMIN(raw_def[2], grid_max_definition[2]);
+
+ /* Define the octree AABB excepted for the Z dimension */
+ low[0] = sky->htcp_desc.lower[0];
+ low[1] = sky->htcp_desc.lower[1];
+ low[2] = sky->htcp_desc.lower[2];
+ upp[0] = low[0] + (double)raw_def[0] * sky->htcp_desc.vxsz_x;
+ upp[1] = low[1] + (double)raw_def[1] * sky->htcp_desc.vxsz_y;
+
+ if(!sky->htcp_desc.irregular_z) {
+ /* Regular voxel size along the Z dimension: compute its upper boundary as
+ * the others dimensions */
+ upp[2] = low[2] + (double)raw_def[2] * sky->htcp_desc.vxsz_z[0];
+
+ /* TODO move the following block in a separate function */
+ } else { /* Irregular voxel size along Z */
+ double len_z;
+ size_t nsplits;
+ size_t iz, iz2;;
+
+ /* Find the min voxel size along Z and compute the length of a Z column */
+ len_z = 0;
+ sky->lut_cell_sz = DBL_MAX;
+ FOR_EACH(iz, 0, sky->htcp_desc.spatial_definition[2]) {
+ len_z += sky->htcp_desc.vxsz_z[iz];
+ sky->lut_cell_sz = MMIN(sky->lut_cell_sz, sky->htcp_desc.vxsz_z[iz]);
+ }
+ /* Allocate the svx2htcp LUT. This LUT is a regular table whose absolute
+ * size is greater or equal to a Z column in the htcp file. The size of its
+ * cells is the minimal voxel size in Z of the htcp file */
+ nsplits = (size_t)ceil(len_z / sky->lut_cell_sz);
+ res = darray_split_resize(&sky->svx2htcp_z, nsplits);
+ if(res != RES_OK) {
+ log_err(sky,
+ "could not allocate the table mapping regular to irregular Z.\n");
+ goto error;
+ }
+ /* Setup the svx2htcp LUT. Each LUT entry stores the index of the current Z
+ * voxel in the htcp file that overlaps the entry lower bound as well as the
+ * lower bound in Z of the next htcp voxel. */
+ iz2 = 0;
+ upp[2] = low[2] + sky->htcp_desc.vxsz_z[iz2];
+ FOR_EACH(iz, 0, nsplits) {
+ const double upp_z = (double)(iz + 1) * sky->lut_cell_sz + low[2];
+ darray_split_data_get(&sky->svx2htcp_z)[iz].index = iz2;
+ darray_split_data_get(&sky->svx2htcp_z)[iz].height = upp[2];
+ if(upp_z >= upp[2] && iz + 1 < nsplits) {
+ ASSERT(iz2 + 1 < sky->htcp_desc.spatial_definition[2]);
+ upp[2] += sky->htcp_desc.vxsz_z[++iz2];
+ }
+ }
+ ASSERT(eq_eps(upp[2] - low[2], len_z, 1.e-6));
+ }
+
+ /* Setup the build context */
+ vxsz[0] = sky->htcp_desc.upper[0] - sky->htcp_desc.lower[0];
+ vxsz[1] = sky->htcp_desc.upper[1] - sky->htcp_desc.lower[1];
+ vxsz[2] = sky->htcp_desc.upper[2] - sky->htcp_desc.lower[2];
+ vxsz[0] = vxsz[0] / (double)nvoxs[0];
+ vxsz[1] = vxsz[1] / (double)nvoxs[1];
+ vxsz[2] = vxsz[2] / (double)nvoxs[2];
+
+ /* Create as many cloud data structure than considered SW spectral bands */
+ nbands = htsky_get_sw_spectral_bands_count(sky);
+ sky->clouds = MEM_CALLOC(sky->allocator, nbands, sizeof(*sky->clouds));
+ if(!sky->clouds) {
+ log_err(sky,
+ "could not create the list of per SW band cloud data structure.\n");
+ res = RES_MEM_ERR;
+ goto error;
+ }
+
+ /* Compute how many octree are going to be built */
+ FOR_EACH(i, 0, nbands) {
+ struct htgop_spectral_interval band;
+ const size_t iband = i + sky->sw_bands_range[0];
+ size_t iquad;
+
+ HTGOP(get_sw_spectral_interval(sky->htgop, iband, &band));
+
+ sky->clouds[i] = MEM_CALLOC(sky->allocator,
+ band.quadrature_length, sizeof(*sky->clouds[i]));
+ if(!sky->clouds[i]) {
+ log_err(sky,
+ "could not create the list of per quadrature point cloud data "
+ "for the band %lu.\n", (unsigned long)iband);
+ res = RES_MEM_ERR;
+ goto error;
+ }
+
+ FOR_EACH(iquad, 0, band.quadrature_length) {
+ struct spectral_data spectral_data;
+ spectral_data.iband = iband;
+ spectral_data.iquad = iquad;
+ res = darray_specdata_push_back(&specdata, &spectral_data);
+ if(res != RES_OK) {
+ log_err(sky,
+ "could not register the quadrature point %lu of the spectral band "
+ "%lu .\n", (unsigned long)iband, (unsigned long)iquad);
+ goto error;
+ }
+ }
+ }
+
+ progress = 0;
+ omp_set_num_threads((int)sky->nthreads);
+ #pragma omp parallel for schedule(dynamic, 1/*chunksize*/)
+ for(ispecdata=0;
+ (size_t)ispecdata<darray_specdata_size_get(&specdata);
+ ++ispecdata) {
+ struct svx_voxel_desc vox_desc = SVX_VOXEL_DESC_NULL;
+ struct build_tree_context ctx = BUILD_TREE_CONTEXT_NULL;
+ const size_t iband = darray_specdata_data_get(&specdata)[ispecdata].iband;
+ const size_t iquad = darray_specdata_data_get(&specdata)[ispecdata].iquad;
+ const size_t id = iband - sky->sw_bands_range[0];
+ int32_t pcent;
+ size_t n;
+ res_T res_local = RES_OK;
+
+ if(ATOMIC_GET(&res) != RES_OK) continue;
+
+ /* Setup the build context */
+ ctx.sky = sky;
+ ctx.vxsz[0] = vxsz[0];
+ ctx.vxsz[1] = vxsz[1];
+ ctx.vxsz[2] = vxsz[2];
+ ctx.tau_threshold = optical_thickness_threshold;
+ ctx.iband = iband;
+ ctx.quadrature_range[0] = iquad;
+ ctx.quadrature_range[1] = iquad;
+
+ /* Setup the voxel descriptor */
+ vox_desc.get = cloud_vox_get;
+ vox_desc.merge = cloud_vox_merge;
+ vox_desc.challenge_merge = cloud_vox_challenge_merge;
+ vox_desc.context = &ctx;
+ vox_desc.size = sizeof(float) * NFLOATS_PER_VOXEL;
+
+ /* Create the octree */
+ res_local = svx_octree_create
+ (sky->svx, low, upp, nvoxs, &vox_desc, &sky->clouds[id][iquad].octree);
+
+ if(res_local != RES_OK) {
+ log_err(sky,
+ "could not create the octree of the cloud properties for the band %lu.\n",
+ (unsigned long)ctx.iband);
+ ATOMIC_SET(&res, res_local);
+ continue;
+ }
+
+ /* Fetch the octree descriptor for future use */
+ SVX(tree_get_desc
+ (sky->clouds[id][iquad].octree, &sky->clouds[id][iquad].octree_desc));
+
+ /* Update the progress message */
+ n = (size_t)ATOMIC_INCR(&nbuilt_octrees);
+ pcent = (int32_t)(n * 100 / darray_specdata_size_get(&specdata));
+
+ #pragma omp critical
+ if(pcent > progress) {
+ progress = pcent;
+ log_info(sky, "\033[2K\rCompute data & building octree: %3d%%", pcent);
+ }
+ }
+ log_info(sky, "\033[2K\rCompute data & building octree: 100%%\n");
+
+
+exit:
+ darray_specdata_release(&specdata);
+ return (res_T)res;
+error:
+ clean_clouds(sky);
+ darray_split_clear(&sky->svx2htcp_z);
+ goto exit;
+}
+
+void
+cloud_clean(struct htsky* sky)
+{
+ size_t nbands;
+ size_t i;
+ ASSERT(sky);
+
+ if(!sky->clouds) return;
+
+ nbands = htsky_get_sw_spectral_bands_count(sky);
+ FOR_EACH(i, 0, nbands) {
+ struct htgop_spectral_interval band;
+ size_t iband;
+ size_t iquad;
+
+ iband = sky->sw_bands_range[0] + i;
+ HTGOP(get_sw_spectral_interval(sky->htgop, iband, &band));
+
+ if(!sky->clouds[i]) continue;
+
+ FOR_EACH(iquad, 0, band.quadrature_length) {
+ if(sky->clouds[i][iquad].octree) {
+ SVX(tree_ref_put(sky->clouds[i][iquad].octree));
+ sky->clouds[i][iquad].octree = NULL;
+ }
+ }
+ MEM_RM(sky->allocator, sky->clouds[i]);
+ }
+ MEM_RM(sky->allocator, sky->clouds);
+ sky->clouds = NULL;
+}
+
+
diff --git a/src/htsky_cloud.h b/src/htsky_cloud.h
@@ -0,0 +1,40 @@
+/* Copyright (C) 2020 |Meso|Star> (contact@meso-star.com)
+ *
+ * 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/>. */
+
+#ifndef HTSKY_CLOUD_H
+#define HTSKY_CLOUD_H
+
+#include <star/svx.h> /* svx_tree_desc */
+
+struct htsky;
+
+struct cloud {
+ struct svx_tree* octree;
+ struct svx_tree_desc octree_desc;
+};
+
+extern LOCAL_SYM res_T
+cloud_setup
+ (struct htsky* sky,
+ const char* htcp_filename,
+ const char* htgop_filename,
+ const char* htmie_filename,
+ const double optical_thickness_threshold);
+
+extern LOCAL_SYM void
+cloud_clean
+ (struct htsky* sky);
+
+#endif /* HTSKY_CLOUDS_H */
diff --git a/src/htsky_dump_cloud_vtk.c b/src/htsky_dump_cloud_vtk.c
@@ -0,0 +1,228 @@
+/* Copyright (C) 2020 |Meso|Star> (contact@meso-star.com)
+ *
+ * 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/>. */
+
+#include "htsky.h"
+#include "htsky_c.h"
+
+#include <high_tune/htgop.h>
+
+#include <rsys/dynamic_array_double.h>
+#include <rsys/hash_table.h>
+
+#include <star/svx.h>
+
+struct vertex {
+ double x;
+ double y;
+ double z;
+};
+
+static char
+vertex_eq(const struct vertex* v0, const struct vertex* v1)
+{
+ return eq_eps(v0->x, v1->x, 1.e-6)
+ && eq_eps(v0->y, v1->y, 1.e-6)
+ && eq_eps(v0->z, v1->z, 1.e-6);
+}
+
+/* Generate the htable_vertex data structure */
+#define HTABLE_NAME vertex
+#define HTABLE_KEY struct vertex
+#define HTABLE_DATA size_t
+#define HTABLE_KEY_FUNCTOR_EQ vertex_eq
+#include <rsys/hash_table.h>
+
+/* Temporary data structure used to dump the octree data into a VTK file */
+struct octree_data {
+ struct htable_vertex vertex2id; /* Map a coordinate to its vertex id */
+ struct darray_double vertices; /* Array of unique vertices */
+ struct darray_double data; /* List of registered leaf data */
+ struct darray_size_t cells; /* Ids of the cell vertices */
+ size_t iband; /* Index of the band that overlaps the CIE XYZ color space */
+ size_t iquad; /* Index of the quadrature point into the band */
+ const struct htsky* sky;
+};
+
+/*******************************************************************************
+ * Helper functions
+ ******************************************************************************/
+static INLINE void
+octree_data_init
+ (const struct htsky* sky,
+ const size_t iband,
+ const size_t iquad,
+ struct octree_data* data)
+{
+ ASSERT(data);
+ ASSERT(iband >= sky->sw_bands_range[0]);
+ ASSERT(iband <= sky->sw_bands_range[1]);
+ (void)iquad;
+ htable_vertex_init(sky->allocator, &data->vertex2id);
+ darray_double_init(sky->allocator, &data->vertices);
+ darray_double_init(sky->allocator, &data->data);
+ darray_size_t_init(sky->allocator, &data->cells);
+ data->sky = sky;
+ data->iband = iband;
+ data->iquad = iquad;
+}
+
+static INLINE void
+octree_data_release(struct octree_data* data)
+{
+ ASSERT(data);
+ htable_vertex_release(&data->vertex2id);
+ darray_double_release(&data->vertices);
+ darray_double_release(&data->data);
+ darray_size_t_release(&data->cells);
+}
+
+static INLINE void
+register_leaf
+ (const struct svx_voxel* leaf,
+ const size_t ileaf,
+ void* context)
+{
+ struct octree_data* ctx = context;
+ struct vertex v[8];
+ double kext_min;
+ double kext_max;
+ int i;
+ ASSERT(leaf && ctx);
+ (void)ileaf;
+
+ /* Compute the leaf vertices */
+ v[0].x = leaf->lower[0]; v[0].y = leaf->lower[1]; v[0].z = leaf->lower[2];
+ v[1].x = leaf->upper[0]; v[1].y = leaf->lower[1]; v[1].z = leaf->lower[2];
+ v[2].x = leaf->lower[0]; v[2].y = leaf->upper[1]; v[2].z = leaf->lower[2];
+ v[3].x = leaf->upper[0]; v[3].y = leaf->upper[1]; v[3].z = leaf->lower[2];
+ v[4].x = leaf->lower[0]; v[4].y = leaf->lower[1]; v[4].z = leaf->upper[2];
+ v[5].x = leaf->upper[0]; v[5].y = leaf->lower[1]; v[5].z = leaf->upper[2];
+ v[6].x = leaf->lower[0]; v[6].y = leaf->upper[1]; v[6].z = leaf->upper[2];
+ v[7].x = leaf->upper[0]; v[7].y = leaf->upper[1]; v[7].z = leaf->upper[2];
+
+ FOR_EACH(i, 0, 8) {
+ size_t *pid = htable_vertex_find(&ctx->vertex2id, v+i);
+ size_t id;
+ if(pid) {
+ id = *pid;
+ } else { /* Register the leaf vertex */
+ id = darray_double_size_get(&ctx->vertices)/3;
+ CHK(RES_OK == htable_vertex_set(&ctx->vertex2id, v+i, &id));
+ CHK(RES_OK == darray_double_push_back(&ctx->vertices, &v[i].x));
+ CHK(RES_OK == darray_double_push_back(&ctx->vertices, &v[i].y));
+ CHK(RES_OK == darray_double_push_back(&ctx->vertices, &v[i].z));
+ }
+ /* Add the vertex id to the leaf cell */
+ CHK(RES_OK == darray_size_t_push_back(&ctx->cells, &id));
+ }
+
+ /* Register the leaf data */
+ kext_max = htsky_fetch_svx_voxel_property(ctx->sky, HTSKY_Kext,
+ HTSKY_SVX_MAX, HTSKY_CPNT_MASK_ALL, ctx->iband, ctx->iquad, leaf);
+ kext_min = htsky_fetch_svx_voxel_property(ctx->sky, HTSKY_Kext,
+ HTSKY_SVX_MIN, HTSKY_ALL_COMPONENTS, ctx->iband, ctx->iquad, leaf);
+ CHK(RES_OK == darray_double_push_back(&ctx->data, &kext_min));
+ CHK(RES_OK == darray_double_push_back(&ctx->data, &kext_max));
+}
+
+/*******************************************************************************
+ * Exported functions
+ ******************************************************************************/
+res_T
+htsky_dump_cloud_vtk
+ (const struct htsky* sky,
+ const size_t iband, /* Index of the spectral band */
+ const size_t iquad, /* Index of the quadrature point */
+ FILE* stream)
+{
+ const struct cloud* cloud;
+ struct htgop_spectral_interval specint;
+ struct octree_data data;
+ const double* leaf_data;
+ size_t nvertices;
+ size_t ncells;
+ size_t i;
+ ASSERT(sky && stream);
+ ASSERT(iband >= sky->sw_bands_range[0]);
+ ASSERT(iband <= sky->sw_bands_range[1]);
+
+ if(!sky->is_cloudy) {
+ log_warn(sky, "%s: the sky has no cloud.\n", FUNC_NAME);
+ return RES_OK;
+ }
+
+ i = iband - sky->sw_bands_range[0];
+
+ octree_data_init(sky, iband, iquad, &data);
+ cloud = &sky->clouds[i][iquad];
+
+ ASSERT(cloud->octree_desc.type == SVX_OCTREE);
+
+ /* Register leaf data */
+ SVX(tree_for_each_leaf(cloud->octree, register_leaf, &data));
+ nvertices = darray_double_size_get(&data.vertices) / 3/*#coords per vertex*/;
+ ncells = darray_size_t_size_get(&data.cells)/8/*#ids per cell*/;
+ ASSERT(ncells == cloud->octree_desc.nleaves);
+
+ /* Fetch the spectral interval descriptor */
+ HTGOP(get_sw_spectral_interval(sky->htgop, iband, &specint));
+
+ /* Write headers */
+ fprintf(stream, "# vtk DataFile Version 2.0\n");
+ fprintf(stream, "Clouds optical properties in [%g, %g] nanometers\n",
+ wavenumber_to_wavelength(specint.wave_numbers[1]),
+ wavenumber_to_wavelength(specint.wave_numbers[0]));
+ fprintf(stream, "ASCII\n");
+ fprintf(stream, "DATASET UNSTRUCTURED_GRID\n");
+
+ /* Write vertex coordinates */
+ fprintf(stream, "POINTS %lu float\n", (unsigned long)nvertices);
+ FOR_EACH(i, 0, nvertices) {
+ fprintf(stream, "%g %g %g\n",
+ SPLIT3(darray_double_cdata_get(&data.vertices) + i*3));
+ }
+
+ /* Write the cells */
+ fprintf(stream, "CELLS %lu %lu\n",
+ (unsigned long)ncells,
+ (unsigned long)(ncells*(8/*#verts per cell*/ + 1/*1st field of a cell*/)));
+ FOR_EACH(i, 0, ncells) {
+ fprintf(stream, "8 %lu %lu %lu %lu %lu %lu %lu %lu\n",
+ (unsigned long)darray_size_t_cdata_get(&data.cells)[i*8+0],
+ (unsigned long)darray_size_t_cdata_get(&data.cells)[i*8+1],
+ (unsigned long)darray_size_t_cdata_get(&data.cells)[i*8+2],
+ (unsigned long)darray_size_t_cdata_get(&data.cells)[i*8+3],
+ (unsigned long)darray_size_t_cdata_get(&data.cells)[i*8+4],
+ (unsigned long)darray_size_t_cdata_get(&data.cells)[i*8+5],
+ (unsigned long)darray_size_t_cdata_get(&data.cells)[i*8+6],
+ (unsigned long)darray_size_t_cdata_get(&data.cells)[i*8+7]);
+ }
+
+ /* Write the cell type */
+ fprintf(stream, "CELL_TYPES %lu\n", (unsigned long)ncells);
+ FOR_EACH(i, 0, ncells) fprintf(stream, "11\n");
+
+ /* Write the cell data */
+ leaf_data = darray_double_cdata_get(&data.data);
+ fprintf(stream, "CELL_DATA %lu\n", (unsigned long)ncells);
+ fprintf(stream, "SCALARS Kext double 2\n");
+ fprintf(stream, "LOOKUP_TABLE default\n");
+ FOR_EACH(i, 0, ncells) {
+ fprintf(stream, "%g %g\n", leaf_data[i*2+0], leaf_data[i*2+1]);
+ }
+ octree_data_release(&data);
+ return RES_OK;
+}
+
diff --git a/src/htsky_file_sys.c b/src/htsky_file_sys.c
@@ -0,0 +1,232 @@
+/* Copyright (C) 2020 |Meso|Star> (contact@meso-star.com)
+ *
+ * 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/>. */
+
+#define _POSIX_C_SOURCE 200809L /* O_DIRECTORY support */
+
+#include "htsky_c.h"
+#include "htsky_file_sys.h"
+
+#include <rsys/str.h>
+
+#include <errno.h>
+#include <fcntl.h> /* open */
+#include <libgen.h> /* basename */
+#include <sys/stat.h> /* S_IRUSR & S_IWUSR */
+#include <sys/time.h> /* timespec */
+#include <unistd.h>
+
+/*******************************************************************************
+ * Helper functions
+ ******************************************************************************/
+static res_T
+open_file_stamp
+ (struct htsky* sky,
+ const char* filename,
+ struct stat* out_stat, /* Stat of the submitted filename */
+ int* out_fd, /* Descriptor of the opened file. Must be closed by the caller */
+ struct str* stamp_filename)
+{
+ struct stat statbuf;
+ struct str str;
+ int err;
+ int fd = -1;
+ res_T res = RES_OK;
+ ASSERT(sky && filename && out_fd && out_stat && stamp_filename);
+
+ str_init(sky->allocator, &str);
+
+ err = stat(filename, &statbuf);
+ if(err) {
+ log_err(sky, "%s: could not stat the file -- %s.\n",
+ filename, strerror(errno));
+ res = RES_IO_ERR;
+ goto error;
+ }
+
+ if(!S_ISREG(statbuf.st_mode)) {
+ log_err(sky, "%s: not a regular file.\n", filename);
+ res = RES_IO_ERR;
+ goto error;
+ }
+
+ res = create_directory(sky, ".htsky/");
+ if(res != RES_OK) goto error;
+
+ #define CHK_STR(Func, ErrMsg) { \
+ res = str_##Func; \
+ if(res != RES_OK) { \
+ htrdr_log_err(htrdr, "%s: "ErrMsg"\n", filename); \
+ goto error; \
+ } \
+ } (void)0
+ CHK_STR(set(&str, filename), "could not copy the filename");
+ CHK_STR(set(&str, basename(str_get(&str))), "could not setup the basename");
+ CHK_STR(insert(&str, 0, ".htsky/"), "could not setup the stamp directory");
+ CHK_STR(append(&str, ".stamp"), "could not setup the stamp extension");
+ #undef CHK_STR
+
+ fd = open(str_cget(&str), O_CREAT|O_RDWR, S_IRUSR|S_IWUSR);
+ if(fd < 0) {
+ log_err(sky, "%s: could not open/create the file -- %s.\n",
+ str_cget(&str), strerror(errno));
+ res = RES_IO_ERR;
+ goto error;
+ }
+
+ CHK(str_copy_and_clear(stamp_filename, &str) == RES_OK);
+
+exit:
+ str_release(&str);
+ *out_fd = fd;
+ *out_stat = statbuf;
+ return res;
+error:
+ if(fd >= 0) {
+ CHK(close(fd) == 0);
+ fd = -1;
+ }
+ goto exit;
+}
+
+/*******************************************************************************
+ * Local functions
+ ******************************************************************************/
+res_T
+is_file_updated(struct htsky* sky, const char* filename, int* out_upd)
+{
+ struct str stamp_filename;
+ struct stat statbuf;
+ ssize_t n;
+ off_t size;
+ struct timespec mtime;
+ int fd = -1;
+ int upd = 1;
+ res_T res = RES_OK;
+ ASSERT(sky && filename && out_upd);
+
+ str_init(sky->allocator, &stamp_filename);
+
+ res = open_file_stamp(sky, filename, &statbuf, &fd, &stamp_filename);
+ if(res != RES_OK) goto error;
+
+ n = read(fd, &mtime, sizeof(mtime));
+ if(n < 0) {
+ log_err(sky, "%s: could not read the `mtime' data of the file -- %s.\n",
+ str_cget(&stamp_filename), strerror(errno));
+ res = RES_IO_ERR;
+ goto error;
+ }
+
+ upd = (size_t)n != sizeof(mtime)
+ || mtime.tv_nsec != statbuf.st_mtim.tv_nsec
+ || mtime.tv_sec != statbuf.st_mtim.tv_sec;
+
+ if(!upd) {
+ n = read(fd, &size, sizeof(size));
+ if(n < 0) {
+ log_err(sky, "%s: could not read the `size' data -- %s.\n",
+ str_cget(&stamp_filename), strerror(errno));
+ res = RES_IO_ERR;
+ goto error;
+ }
+ upd = (size_t)n != sizeof(size) || statbuf.st_size != size;
+ }
+
+exit:
+ *out_upd = upd;
+ str_release(&stamp_filename);
+ if(fd >= 0) CHK(close(fd) == 0);
+ return res;
+error:
+ goto exit;
+}
+
+res_T
+update_file_stamp(struct htsky* sky, const char* filename)
+{
+ struct str stamp_filename;
+ struct stat statbuf;
+ int fd = -1;
+ ssize_t n;
+ res_T res = RES_OK;
+ ASSERT(sky && filename);
+
+ str_init(sky->allocator, &stamp_filename);
+
+ res = open_file_stamp(sky, filename, &statbuf, &fd, &stamp_filename);
+ if(res != RES_OK) goto error;
+
+ #define CHK_IO(Func, ErrMsg) { \
+ if((Func) < 0) { \
+ log_err(sky, "%s: "ErrMsg" -- %s.\n", \
+ str_cget(&stamp_filename), strerror(errno)); \
+ res = RES_IO_ERR; \
+ goto error; \
+ } \
+ } (void) 0
+
+ CHK_IO(lseek(fd, 0, SEEK_SET), "could not rewind the file descriptor");
+
+ /* NOTE: Ignore n >=0 but != sizeof(DATA). In such case stamp is currupted
+ * and on the next invocation on the same filename, this function will
+ * return 1 */
+ n = write(fd, &statbuf.st_mtim, sizeof(statbuf.st_mtim));
+ CHK_IO(n, "could not update the `mtime' data");
+ n = write(fd, &statbuf.st_size, sizeof(statbuf.st_size));
+ CHK_IO(n, "could not update the `size' data");
+
+ CHK_IO(fsync(fd), "could not sync the file with storage device");
+
+ #undef CHK_IO
+
+exit:
+ str_release(&stamp_filename);
+ if(fd >= 0) CHK(close(fd) == 0);
+ return res;
+error:
+ goto exit;
+}
+
+res_T
+create_directory(struct htsky* sky, const char* path)
+{
+ res_T res = RES_OK;
+ int err;
+ ASSERT(sky && path);
+
+ err = mkdir(path, S_IRWXU);
+ if(!err) goto exit;
+
+ if(errno != EEXIST) {
+ log_err(sky, "cannot create the `%s' directory -- %s.\n",
+ path, strerror(errno));
+ res = RES_IO_ERR;
+ goto error;
+ } else {
+ const int fd = open(path, O_DIRECTORY);
+ if(fd < -1) {
+ log_err(sky, "cannot open the `%s' directory -- %s.\n",
+ path, strerror(errno));
+ res = RES_IO_ERR;
+ goto error;
+ }
+ CHK(!close(fd));
+ }
+exit:
+ return res;
+error:
+ goto exit;
+}
+
diff --git a/src/htsky_file_sys.h b/src/htsky_file_sys.h
@@ -0,0 +1,40 @@
+/* Copyright (C) 2020 |Meso|Star> (contact@meso-star.com)
+ *
+ * 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/>. */
+
+#ifndef HTSKY_FILE_SYS_H
+#define HTSKY_FILE_SYS_H
+
+#include <rsys/rsys.h>
+
+struct htsky;
+
+extern LOCAL_SYM res_T
+is_file_updated
+ (struct htsky* sky,
+ const char* filename,
+ int* is_upd);
+
+extern LOCAL_SYM res_T
+update_file_stamp
+ (struct htsky* sky,
+ const char* filename);
+
+extern LOCAL_SYM res_T
+create_directory
+ (struct htsky* sky,
+ const char* path);
+
+#endif /* HTSKY_FILE_SYS_H */
+
diff --git a/src/htsky_log.c b/src/htsky_log.c
@@ -0,0 +1,180 @@
+/* Copyright (C) 2020 |Meso|Star> (contact@meso-star.com)
+ *
+ * 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/>. */
+
+#include "htsky_c.h"
+#include "htsky_log.h"
+
+#include <rsys/logger.h>
+
+#include <stdarg.h>
+
+#define MSG_INFO_PREFIX "HTSky:\x1b[1m\x1b[32minfo\x1b[0m: "
+#define MSG_ERROR_PREFIX "HTSky:\x1b[1m\x1b[31merror\x1b[0m: "
+#define MSG_WARNING_PREFIX "HTSky:\x1b[1m\x1b[33mwarning\x1b[0m: "
+
+/*******************************************************************************
+ * Helper functions
+ ******************************************************************************/
+static INLINE void
+log_msg
+ (const struct smtl* smtl,
+ const enum log_type stream,
+ const char* msg,
+ va_list vargs)
+{
+ ASSERT(smtl && msg);
+ if(smtl->verbose) {
+ res_T res; (void)res;
+ res = logger_vprint(smtl->logger, stream, msg, vargs);
+ ASSERT(res == RES_OK);
+ }
+}
+
+static void
+print_info(const char* msg, void* ctx)
+{
+ (void)ctx;
+ fprintf(stderr, MSG_INFO_PREFIX"%s", msg);
+}
+
+static void
+print_err(const char* msg, void* ctx)
+{
+ (void)ctx;
+ fprintf(stderr, MSG_ERROR_PREFIX"%s", msg);
+}
+
+static void
+print_warn(const char* msg, void* ctx)
+{
+ (void)ctx;
+ fprintf(stderr, MSG_WARNING_PREFIX"%s", msg);
+}
+
+static res_T
+setup_default_logger(struct mem_allocator* allocator, struct logger* logger)
+{
+ res_T res = RES_OK;
+ ASSERT(logger);
+ res = logger_init(allocator, logger);
+ if(res != RES_OK) return res;
+ logger_set_stream(logger, LOG_OUTPUT, print_info, NULL);
+ logger_set_stream(logger, LOG_ERROR, print_err, NULL);
+ logger_set_stream(logger, LOG_WARNING, print_warn, NULL);
+ return RES_OK;
+}
+
+/*******************************************************************************
+ * Local functions
+ ******************************************************************************/
+res_T
+setup_log_default(struct htsky* sky)
+{
+ res_T res = RES_OK;
+ ASSERT(sky);
+
+ res = setup_default_logger(sky->allocator, &sky->logger__);
+ if(res != RES_OK) {
+ if(verbose) {
+ fprintf(stderr, MSG_ERROR_PREFIX "could not setup the HTSky logger.\n");
+ }
+ goto error;
+ }
+ sky->logger = sky->logger__;
+
+exit:
+ return res;
+error:
+ goto exit;
+}
+
+void
+log_info(const struct htsky* sky, const char* msg, ...)
+{
+ va_list vargs_list;
+ ASSERT(sky && msg);
+
+ va_start(vargs_list, msg);
+ log_msg(sky, LOG_OUTPUT, msg, vargs_list);
+ va_end(vargs_list);
+}
+
+void
+log_err(const struct htsky* sky, const char* msg, ...)
+{
+ va_list vargs_list;
+ ASSERT(sky && msg);
+
+ va_start(vargs_list, msg);
+ log_msg(sky, LOG_ERROR, msg, vargs_list);
+ va_end(vargs_list);
+}
+
+void
+log_warn(const struct smtl* smtl, const char* msg, ...)
+{
+ va_list vargs_list;
+ ASSERT(sky && msg);
+
+ va_start(vargs_list, msg);
+ log_msg(sky, LOG_WARNING, msg, vargs_list);
+ va_end(vargs_list);
+}
+
+static void
+log_svx_memory_usage(struct htsky* sky)
+{
+ char dump[128];
+ char* dst = dump;
+ size_t available_space = sizeof(dump);
+ const size_t KILO_BYTE = 1024;
+ const size_t MEGA_BYTE = 1024*KILO_BYTE;
+ const size_t GIGA_BYTE = 1024*MEGA_BYTE;
+ size_t ngigas, nmegas, nkilos, memsz, len;
+ ASSERT(sky);
+
+ memsz = MEM_ALLOCATED_SIZE(&sky->svx_allocator);
+
+ if((ngigas = memsz / GIGA_BYTE) != 0) {
+ len = (size_t)snprintf(dst, available_space,
+ "%lu GB ", (unsigned long)ngigas);
+ CHK(len < available_space);
+ dst += len;
+ available_space -= len;
+ memsz -= ngigas * GIGA_BYTE;
+ }
+ if((nmegas = memsz / MEGA_BYTE) != 0) {
+ len = (size_t)snprintf(dst, available_space,
+ "%lu MB ", (unsigned long)nmegas);
+ CHK(len < available_space);
+ dst += len;
+ available_space -= len;
+ memsz -= nmegas * MEGA_BYTE;
+ }
+ if((nkilos = memsz / KILO_BYTE) != 0) {
+ len = (size_t)snprintf(dst, available_space,
+ "%lu KB ", (unsigned long)nkilos);
+ dst += len;
+ available_space -= len;
+ memsz -= nkilos * KILO_BYTE;
+ }
+ if(memsz) {
+ len = (size_t)snprintf(dst, available_space,
+ "%lu Byte%s", (unsigned long)memsz, memsz > 1 ? "s" : "");
+ CHK(len < available_space);
+ }
+ log_info(sky, "SVX memory usage: %s\n", dump);
+}
+
diff --git a/src/htsky_log.h b/src/htsky_log.h
@@ -0,0 +1,67 @@
+/* Copyright (C) 2020 |Meso|Star> (contact@meso-star.com)
+ *
+ * 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/>. */
+
+#ifndef HTSKY_LOG_H
+#define HTSKY_LOG_H
+
+#include <rsys/rsys.h>
+
+struct htsky;
+
+extern LOCAL_SYM res_T
+setup_log_default
+ (struct htsky* sky);
+
+/* Conditionally log a message on the LOG_OUTPUT stream of the htsky logger,
+ * with respect to its verbose flag */
+extern LOCAL_SYM void
+log_info
+ (const struct htsky* sky,
+ const char* msg,
+ ...)
+#ifdef COMPILER_GCC
+ __attribute((format(printf, 2, 3)))
+#endif
+;
+
+/* Conditionally log a message on the LOG_ERROR stream of the htsky logger,
+ * with respect to its verbose flag */
+extern LOCAL_SYM void
+log_err
+ (const struct htsky* sky,
+ const char* msg,
+ ...)
+#ifdef COMPILER_GCC
+ __attribute((format(printf, 2, 3)))
+#endif
+;
+
+/* Conditionally log a message on the LOG_WARNING stream of the device logger,
+ * with respect to its verbose flag */
+extern LOCAL_SYM void
+log_warn
+ (const struct htsky* sky,
+ const char* msg,
+ ...)
+#ifdef COMPILER_GCC
+ __attribute((format(printf, 2, 3)))
+#endif
+;
+
+extern LOCAL_SYM void
+log_svx_memory_usage
+ (struct htsky* sky);
+
+#endif /* HTSKY_LOG_H *
diff --git a/src/htsky_svx.c b/src/htsky_svx.c
@@ -0,0 +1,418 @@
+/* Copyright (C) 2020 |Meso|Star> (contact@meso-star.com)
+ *
+ * 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/>. */
+
+#include "htsky.h"
+#include "htsky_atmosphere.h"
+#include "htsky_c.h"
+#include "htsky_cloud.h"
+#include "htsky_svx.h"
+
+#include <star/svx.h>
+
+struct trace_cloud_context {
+ struct svx_tree* clouds;
+ struct svx_hit* hit;
+ svx_hit_challenge_T challenge;
+ svx_hit_filter_T filter;
+ void* context;
+};
+static const struct trace_cloud_context TRACE_CLOUD_CONTEXT_NULL;
+
+/*******************************************************************************
+ * Helper functions
+ ******************************************************************************/
+/* Smits intersection: "Efficiency issues for ray tracing" */
+static FINLINE void
+ray_intersect_aabb
+ (const double org[3],
+ const double dir[3],
+ const double range[2],
+ const double low[3],
+ const double upp[3],
+ const int axis_mask,
+ double hit_range[2])
+{
+ double hit[2];
+ int i;
+ ASSERT(org && dir && range && low && upp && hit_range);
+ ASSERT(low[0] < upp[0]);
+ ASSERT(low[1] < upp[1]);
+ ASSERT(low[2] < upp[2]);
+
+ hit_range[0] = INF;
+ hit_range[1] =-INF;
+ hit[0] = range[0];
+ hit[1] = range[1];
+ FOR_EACH(i, 0, 3) {
+ double t_min, t_max;
+
+ if(!(BIT(i) & axis_mask)) continue;
+
+ t_min = (low[i] - org[i]) / dir[i];
+ t_max = (upp[i] - org[i]) / dir[i];
+
+ if(t_min > t_max) SWAP(double, t_min, t_max);
+ hit[0] = MMAX(t_min, hit[0]);
+ hit[1] = MMIN(t_max, hit[1]);
+ if(hit[0] > hit[1]) return;
+ }
+ hit_range[0] = hit[0];
+ hit_range[1] = hit[1];
+}
+
+static res_T
+infinite_cloudy_slab_trace_ray
+ (struct htsky* sky,
+ struct svx_tree* clouds,
+ const double org[3],
+ const double dir[3],
+ const double range[2],
+ const size_t max_steps,
+ svx_hit_challenge_T challenge,
+ svx_hit_filter_T filter,
+ void* context,
+ struct svx_hit* hit)
+{
+ double pos[2];
+ double org_cs[3]; /* Origin of the ray transformed in local cell space */
+ const double* cell_low;
+ const double* cell_upp;
+ double cell_low_ws[3]; /* Cell lower bound in world space */
+ double cell_upp_ws[3]; /* Cell upper bound in world space */
+ double cell_sz[3]; /* Size of a cell */
+ double t_max[3], t_delta[2], t_min_z;
+ size_t istep;
+ int64_t xy[2]; /* 2D index of the repeated cell */
+ int incr[2]; /* Index increment */
+ res_T res = RES_OK;
+ ASSERT(sky && clouds && org && dir && range && ctx && hit);
+ ASSERT(range[0] < range[1]);
+
+ cell_low = sky->htcp_desc.lower;
+ cell_upp = sky->htcp_decc.upper;
+
+ /* Check that the ray intersects the slab */
+ t_min_z = (cell_low[2] - org[2]) / dir[2];
+ t_max[2] = (cell_upp[2] - org[2]) / dir[2];
+ if(t_min_z > t_max[2]) SWAP(double, t_min_z, t_max[2]);
+ t_min_z = MMAX(t_min_z, range[0]);
+ t_max[2] = MMIN(t_max[2], range[1]);
+ if(t_min_z > t_max[2]) return RES_OK;
+
+ /* Compute the size of a cell */
+ cell_sz[0] = cell_upp[0] - cell_low[0];
+ cell_sz[1] = cell_upp[1] - cell_low[1];
+ cell_sz[2] = cell_upp[2] - cell_low[2];
+
+ /* Define the 2D index of the current cell. (0,0) is the index of the
+ * non duplicated cell */
+ pos[0] = org[0] + t_min_z*dir[0];
+ pos[1] = org[1] + t_min_z*dir[1];
+ xy[0] = (int64_t)floor((pos[0] - cell_low[0]) / cell_sz[0]);
+ xy[1] = (int64_t)floor((pos[1] - cell_low[1]) / cell_sz[1]);
+
+ /* Define the 2D index increment wrt dir sign */
+ incr[0] = dir[0] < 0 ? -1 : 1;
+ incr[1] = dir[1] < 0 ? -1 : 1;
+
+ /* Compute the world space AABB of the repeated cell currently hit */
+ cell_low_ws[0] = cell_low[0] + (double)xy[0]*cell_sz[0];
+ cell_low_ws[1] = cell_low[1] + (double)xy[1]*cell_sz[1];
+ cell_low_ws[2] = cell_low[2];
+ cell_upp_ws[0] = cell_low_ws[0] + cell_sz[0];
+ cell_upp_ws[1] = cell_low_ws[1] + cell_sz[1];
+ cell_upp_ws[2] = cell_upp[2];
+
+ /* Compute the max ray intersection with the current cell */
+ t_max[0] = ((dir[0]<0 ? cell_low_ws[0] : cell_upp_ws[0]) - org[0]) / dir[0];
+ t_max[1] = ((dir[1]<0 ? cell_low_ws[1] : cell_upp_ws[1]) - org[1]) / dir[1];
+ /*t_max[2] = ((dir[2]<0 ? cell_low_ws[2] : cell_upp_ws[2]) - org[2]) / dir[2];*/
+ ASSERT(t_max[0] >= 0 && t_max[1] >= 0 && t_max[2] >= 0);
+
+ /* Compute the distance along the ray to traverse in order to move of a
+ * distance equal to the cloud size along the X and Y axis */
+ t_delta[0] = (dir[0]<0 ? -cell_sz[0] : cell_sz[0]) / dir[0];
+ t_delta[1] = (dir[1]<0 ? -cell_sz[1] : cell_sz[1]) / dir[1];
+ ASSERT(t_delta[0] >= 0 && t_delta[1] >= 0);
+
+ org_cs[2] = org[2];
+ FOR_EACH(istep, 0, max_steps) {
+ int iaxis;
+ int hit;
+
+ /* Transform the ray origin in the local cell space */
+ org_cs[0] = org[0] - (double)xy[0]*cell_sz[0];
+ org_cs[1] = org[1] - (double)xy[1]*cell_sz[1];
+
+ res = svx_tree_trace_ray
+ (clouds, org_cs, dir, range, challenge, filter, context, hit);
+ if(res != RES_OK) {
+ log_err(sky,
+ "%s: could not trace the ray in the repeated cells -- %s.\n",
+ FUNC_NAME, res_to_cstr(res));
+ goto error;
+ }
+ if(!SVX_HIT_NONE(hit)) goto exit;
+
+ /* Define the next axis to traverse */
+ iaxis = t_max[0] < t_max[1]
+ ? (t_max[0] < t_max[2] ? 0 : 2)
+ : (t_max[1] < t_max[2] ? 1 : 2);
+
+ if(iaxis == 2) break; /* The ray traverse the slab */
+
+ if(t_max[iaxis] >= range[1]) break; /* Out of bound */
+
+ t_max[iaxis] += t_delta[iaxis];
+
+ /* Define the 2D index of the next traversed cloud */
+ xy[iaxis] += incr[iaxis];
+ }
+
+exit:
+ return res;
+error:
+ goto exit;
+}
+
+
+/*******************************************************************************
+ * Exported functions
+ ******************************************************************************/
+double
+htsky_fetch_svx_property
+ (const struct htsky* sky,
+ const enum htsky_property prop,
+ const enum htsky_svx_op op,
+ const int components_mask, /* Combination of htsky_component_flag */
+ const size_t iband, /* Index of the spectral band */
+ const size_t iquad, /* Index of the quadrature point in the spectral band */
+ const double pos[3])
+{
+ struct svx_voxel voxel = SVX_VOXEL_NULL;
+ struct atmosphere* atmosphere = NULL;
+ struct cloud* cloud = NULL;
+ size_t i;
+ int in_clouds; /* Defines if `pos' lies in the clouds */
+ int in_atmosphere; /* Defines if `pos' lies in the atmosphere */
+ int comp_mask = components_mask;
+ ASSERT(sky && pos);
+ ASSERT(comp_mask & HTSKY_CPNT_MASK_ALL);
+ ASSERT(iband >= sky->sw_bands_range[0]);
+ ASSERT(iband <= sky->sw_bands_range[1]);
+
+ i = iband - sky->sw_bands_range[0];
+ cloud = sky->is_cloudy ? &sky->clouds[i][iquad] : NULL;
+ atmosphere = &sky->atmosphere[i][iquad];
+
+ /* Is the position inside the clouds? */
+ if(sky->is_cloudy) {
+ in_clouds = 0;
+ } else if(sky->repeat_clouds) {
+ in_clouds =
+ pos[2] >= cloud->octree_desc.lower[2]
+ && pos[2] <= cloud->octree_desc.upper[2];
+ } else {
+ in_clouds =
+ pos[0] >= cloud->octree_desc.lower[0]
+ && pos[1] >= cloud->octree_desc.lower[1]
+ && pos[2] >= cloud->octree_desc.lower[2]
+ && pos[0] <= cloud->octree_desc.upper[0]
+ && pos[1] <= cloud->octree_desc.upper[1]
+ && pos[2] <= cloud->octree_desc.upper[2];
+ }
+
+ ASSERT(atmosphere->bitree_desc.frame[0] == SVX_AXIS_Z);
+ in_atmosphere =
+ pos[2] >= atmosphere->bitree_desc.lower[2]
+ && pos[2] <= atmosphere->bitree_desc.upper[2];
+
+ if(!in_clouds) { /* Not in clouds => No particle */
+ comp_mask &= ~HTSKY_CPNT_FLAG_PARTICLES;
+ }
+ if(!in_atmosphere) { /* Not in atmosphere => No gas */
+ comp_mask &= ~HTSKY_CPNT_FLAG_GAS;
+ }
+
+ if(!in_clouds && !in_atmosphere) /* In vacuum */
+ return 0;
+
+ if(!in_clouds) {
+ ASSERT(in_atmosphere);
+ SVX(tree_at(atmosphere->bitree, pos, NULL, NULL, &voxel));
+ } else {
+ double pos_cs[3];
+ world_to_cloud(sky, pos, pos_cs);
+ SVX(tree_at(cloud->octree, pos_cs, NULL, NULL, &voxel));
+ }
+
+ return htsky_fetch_svx_voxel_property
+ (sky, prop, op, comp_mask, iband, iquad, &voxel);
+}
+
+double
+htsky_fetch_svx_voxel_property
+ (const struct htsky* sky,
+ const enum htsky_property prop,
+ const enum htsky_svx_op op,
+ const int components_mask,
+ const size_t ispectral_band, /* Index of the spectral band */
+ const size_t iquad, /* Index of the quadrature point in the spectral band */
+ const struct svx_voxel* voxel)
+{
+ double gas = 0;
+ double par = 0;
+ int comp_mask = components_mask;
+ ASSERT(sky && voxel);
+ ASSERT((unsigned)prop < HTSKY_PROPERTIES_COUNT__);
+ ASSERT((unsigned)op < HTSKY_SVX_OPS_COUNT__);
+ (void)sky, (void)ispectral_band, (void)iquad;
+
+ /* Check if the voxel has infinite bounds/degenerated. In such case it is
+ * atmospheric voxel with only gas properties */
+ if(IS_INF(voxel->upper[0]) || voxel->lower[0] > voxel->upper[0]) {
+ ASSERT(IS_INF(voxel->upper[1]) || voxel->lower[1] > voxel->upper[1]);
+ comp_mask &= ~HTSKY_CPNT_FLAG_PARTICLES;
+ }
+
+ if(comp_mask & HTSKY_CPNT_FLAG_PARTICLES) {
+ par = vox_get(voxel->data, HTSKY_CPNT_PARTICLES, prop, op);
+ }
+ if(comp_mask & HTSKY_CPNT_FLAG_GAS) {
+ gas = vox_get(voxel->data, HTSKY_CPNT_GAS, prop, op);
+ }
+ return par + gas;
+}
+
+res_T
+htsky_trace_ray
+ (struct htsky* sky,
+ const double org[3],
+ const double dir[3], /* Must be normalized */
+ const double range[2],
+ const svx_hit_challenge_T challenge, /* NULL <=> Traversed up to the leaves */
+ const svx_hit_filter_T filter, /* NULL <=> Stop RT at the 1st hit voxel */
+ void* context, /* Data sent to the filter functor */
+ const size_t ispectral_band,
+ const size_t iquadrature_pt,
+ struct svx_hit* hit)
+{
+ double cloud_range[2];
+ struct svx_tree* clouds;
+ struct svx_tree* atmosphere;
+ size_t i;
+ res_T res = RES_OK;
+ ASSERT(sky);
+ ASSERT(ispectral_band >= sky->sw_bands_range[0]);
+ ASSERT(ispectral_band <= sky->sw_bands_range[1]);
+ (void)iquadrature_pt;
+
+ /* Fetch the clouds/atmosphere corresponding to the submitted spectral data */
+ i = ispectral_band - sky->sw_bands_range[0];
+ clouds = sky->is_cloudy ? sky->clouds[i][iquadrature_pt].octree : NULL;
+ atmosphere = sky->atmosphere[i][iquadrature_pt].bitree;
+
+ cloud_range[0] = INF;
+ cloud_range[1] =-INF;
+
+ if(sky->is_cloudy) {
+ /* Compute the ray range, intersecting the clouds AABB */
+ if(sky->repeat_clouds) {
+ ray_intersect_aabb(org, dir, range, sky->htcp_desc.lower,
+ sky->htcp_desc.upper, AXIS_Z, cloud_range);
+ } else {
+ ray_intersect_aabb(org, dir, range, sky->htcp_desc.lower,
+ sky->htcp_desc.upper, AXIS_X|AXIS_Y|AXIS_Z, cloud_range);
+ }
+ }
+
+ /* Reset the hit */
+ *hit = SVX_HIT_NULL;
+
+ if(cloud_range[0] >= cloud_range[1]) { /* The ray does not traverse the clouds */
+ res = svx_tree_trace_ray(atmosphere, org, dir, range, challenge, filter,
+ context, hit);
+ if(res != RES_OK) {
+ log_err(sky, "%s: could not trace the ray in the atmosphere.\n", FUNC_NAME);
+ goto error;
+ }
+ } else { /* The ray may traverse the clouds */
+ double range_adjusted[2];
+
+ if(cloud_range[0] > range[0]) { /* The ray begins in the atmosphere */
+ /* Trace a ray in the atmosphere from range[0] to cloud_range[0] */
+ range_adjusted[0] = range[0];
+ range_adjusted[1] = nextafter(cloud_range[0], -DBL_MAX);
+ res = svx_tree_trace_ray(atmosphere, org, dir, range_adjusted, challenge,
+ filter, context, hit);
+ if(res != RES_OK) {
+ log_err(sky,
+ "%s: could not to trace the part that begins in the atmosphere.\n",
+ FUNC_NAME);
+ goto error;
+ }
+ if(!SVX_HIT_NONE(hit)) goto exit; /* Collision */
+ }
+
+ /* Pursue ray traversal into the clouds */
+ if(!sky->repeat_clouds) {
+ res = svx_tree_trace_ray(clouds, org, dir, cloud_range, challenge, filter,
+ context, hit);
+ if(res != RES_OK) {
+ log_err(sky,
+ "%s: could not trace the ray part that intersects the clouds.\n",
+ FUNC_NAME);
+ goto error;
+ }
+ if(!SVX_HIT_NONE(hit)) goto exit; /* Collision */
+
+ /* Clouds are infinitely repeated along the X and Y axis */
+ } else {
+ struct trace_cloud_context slab_ctx = TRACE_CLOUD_CONTEXT_NULL;
+
+ slab_ctx.clouds = clouds;
+ slab_ctx.challenge = challenge;
+ slab_ctx.filter = filter;
+ slab_ctx.context = context;
+ slab_ctx.hit = hit;
+
+ res = infinite_cloudy_slab_trace_ray(sky, clouds, org, dir, cloud_range,
+ 32, challenge, filter, context, hit);
+ if(res != RES_OK) goto error;
+
+ if(!SVX_HIT_NONE(hit)) goto exit; /* Collision */
+ }
+
+ /* Pursue ray traversal into the atmosphere */
+ range_adjusted[0] = nextafter(cloud_range[1], DBL_MAX);
+ range_adjusted[1] = range[1];
+ res = svx_tree_trace_ray(atmosphere, org, dir, range_adjusted, challenge,
+ filter, context, hit);
+ if(res != RES_OK) {
+ log_err(sky,
+ "%s: could not trace the ray part that ends in the atmosphere.\n",
+ FUNC_NAME);
+ goto error;
+ }
+ if(!SVX_HIT_NONE(hit)) goto exit; /* Collision */
+ }
+
+exit:
+ return res;
+error:
+ goto exit;
+}
+
+
diff --git a/src/htsky_svx.h b/src/htsky_svx.h
@@ -0,0 +1,144 @@
+/* Copyright (C) 2020 |Meso|Star> (contact@meso-star.com)
+ *
+ * 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/>. */
+
+#ifndef HTSKY_SVX_H
+#define HTSKY_SVX_H
+
+#include "htsky.h"
+
+#include <rsys/math.h>
+
+ /*
+ * SVX Memory layout
+ * -----------------
+ *
+ * For each SVX voxel, the data of the optical property are stored
+ * linearly as N single precision floating point data, with N computed as
+ * bellow:
+ *
+ * N = HTSKY_PROPS_COUNT__ #optical properties per voxel
+ * * HTSKY_SVX_OPS_COUNT__ #supported operations on each properties
+ * * HTSKY_CPNTS_COUNT__; #components on which properties are defined
+ *
+ * In a given voxel, the index `id' in [0, N-1] corresponding to the optical
+ * property `enum htrdr_sky_property P' of the component `enum
+ * htrdr_sky_component C' according to the operation `enum htsky_svx_op O' is
+ * then computed as bellow:
+ *
+ * id = C * NFLOATS_PER_CPNT + P * HTSKY_SVX_OPS_COUNT__ + O;
+ * NFLOATS_PER_CPNT = HTSKY_SVX_OPS_COUNT__ * HTSKY_PROPS_COUNT__;
+ */
+
+/* Constant defining the number of floating point data per component */
+#define NFLOATS_PER_CPNT (HTSKY_SVX_OPS_COUNT__ * HTSKY_PROPS_COUNT__)
+
+/* Constant defining the overall number of floating point data of a voxel */
+#define NFLOATS_PER_VOXEL (NFLOATS_PER_CPNT * HTSY_CPNTS_COUNT__)
+
+/* Context used to build the SVX hierarchical data structures */
+struct build_tree_context {
+ const struct htsky* sky;
+ double vxsz[3];
+ double tau_threshold; /* Threshold criteria for the merge process */
+ size_t iband; /* Index of the band that overlaps the CIE XYZ color space */
+ size_t quadrature_range[2]; /* Range of quadrature point indices to handle */
+};
+static const struct build_tree_context BUILD_TREE_CONTEXT_NULL;
+
+static FINLINE float
+vox_get
+ (const float* data,
+ const enum htsky_component cpnt,
+ const enum htsky_property prop,
+ const enum htsky_svx_op op)
+{
+ ASSERT(data);
+ return data[cpnt*NFLOATS_PER_CPNT+ prop*HTSKY_SVX_OPS_COUNT__ + op];
+}
+
+static FINLINE void
+vox_set
+ (float* data,
+ const enum htsky_component cpnt,
+ const enum htsky_property prop,
+ const enum htsky_svx_op op,
+ const float val)
+{
+ ASSERT(data);
+ data[cpnt*NFLOATS_PER_CPNT+ prop*HTSKY_SVX_OPS_COUNT__ + op] = val;
+}
+
+static INLINE void
+vox_merge_component
+ (float* vox_out,
+ const enum htsky_component cpnt,
+ const float* voxs[],
+ const size_t nvoxs)
+{
+ float ka_min = FLT_MAX;
+ float ka_max =-FLT_MAX;
+ float ks_min = FLT_MAX;
+ float ks_max =-FLT_MAX;
+ float kext_min = FLT_MAX;
+ float kext_max =-FLT_MAX;
+ size_t ivox;
+ ASSERT(vox_out && voxs && nvoxs);
+
+ FOR_EACH(ivox, 0, nvoxs) {
+ const float* vox = voxs[ivox];
+ ka_min = MMIN(ka_min, vox_get(vox, cpnt, HTSKY_Ka, HTSKY_SVX_MIN));
+ ka_max = MMAX(ka_max, vox_get(vox, cpnt, HTSKY_Ka, HTSKY_SVX_MAX));
+ ks_min = MMIN(ks_min, vox_get(vox, cpnt, HTSKY_Ks, HTSKY_SVX_MIN));
+ ks_max = MMAX(ks_max, vox_get(vox, cpnt, HTSKY_Ks, HTSKY_SVX_MAX));
+ kext_min = MMIN(kext_min, vox_get(vox, cpnt, HTSKY_Kext, HTSKY_SVX_MIN));
+ kext_max = MMAX(kext_max, vox_get(vox, cpnt, HTSKY_Kext, HTSKY_SVX_MAX));
+ }
+
+ vox_set(vox_out, cpnt, HTSKY_Ka, HTSKY_SVX_MIN, ka_min);
+ vox_set(vox_out, cpnt, HTSKY_Ka, HTSKY_SVX_MAX, ka_max);
+ vox_set(vox_out, cpnt, HTSKY_Ks, HTSKY_SVX_MIN, ks_min);
+ vox_set(vox_out, cpnt, HTSKY_Ks, HTSKY_SVX_MAX, ks_max);
+ vox_set(vox_out, cpnt, HTSKY_Kext, HTSKY_SVX_MIN, kext_min);
+ vox_set(vox_out, cpnt, HTSKY_Kext, HTSKY_SVX_MAX, kext_max);
+}
+
+static INLINE int
+vox_challenge_merge_component
+ (const enum htrdr_sky_component comp,
+ const struct svx_voxel voxels[],
+ const size_t nvoxs,
+ struct build_tree_context* ctx)
+{
+ double lower_z = DBL_MAX;
+ double upper_z =-DBL_MAX;
+ double dst;
+ float kext_min = FLT_MAX;
+ float kext_max =-FLT_MAX;
+ size_t ivox;
+ ASSERT(voxels && nvoxs && ctx);
+
+ FOR_EACH(ivox, 0, nvoxs) {
+ const float* vox = voxels[ivox].data;
+ kext_min = MMIN(kext_min, vox_get(vox, comp, HTSKY_Kext, HTSKY_SVX_MIN));
+ kext_max = MMAX(kext_max, vox_get(vox, comp, HTSKY_Kext, HTSKY_SVX_MAX));
+ lower_z = MMIN(voxels[ivox].lower[2], lower_z);
+ upper_z = MMAX(voxels[ivox].upper[2], upper_z);
+ }
+ dst = upper_z - lower_z;
+ return (kext_max - kext_min)*dst <= ctx->tau_threshold;
+}
+
+#endif /* HTSKY_SVX_H */
+