Compare commits

...

45 Commits

Author SHA1 Message Date
Martin Fouilleul 82e4d0e08b Moving repo to github 2023-10-09 17:23:54 +02:00
Martin Fouilleul ef79405805 Licensing changes 2023-10-08 18:29:58 +02:00
Martin Fouilleul a1b48b2b2f add github sponsor yml file 2023-10-08 18:27:43 +02:00
Ilia Demianenko 5e62a5d2e7 Make intensity FPS-independent 2023-10-03 21:31:22 -07:00
Ilia Demianenko c05223f91c Make the fluid sample do a splat on startup 2023-10-03 21:19:36 -07:00
Reuben Dunnington 6e4943c2fa
make scancode -> keycode conversion consistent with header definitions 2023-09-29 22:09:31 -04:00
Martin Fouilleul 90dd12a69f Aligned arena allocation 2023-09-29 10:53:48 +02:00
Martin Fouilleul 549e640102 making binding generator output explicit void for functions with no parameters. Fix oc_surface_canvas/oc_surface_gles to take explicit void 2023-09-28 21:29:03 +02:00
Martin Fouilleul d5bd7ea2bb fix order of file vs function in logging function arguments 2023-09-28 21:28:18 +02:00
Martin Fouilleul c4a1ad52a0 fix duplicate declarations in .clang-format 2023-09-28 10:04:32 +02:00
Reuben Dunnington 9448104f41
macos: separate building orca core from samples 2023-09-25 22:36:02 -04:00
Reuben Dunnington aac74b0533
win32: separate building orca core from samples 2023-09-25 22:28:01 -04:00
Ben Visness 4f0738fe64 Check for Xcode command-line tools 2023-09-25 11:28:52 +00:00
Ben Visness 1cc8778982 Do clang checks on Mac 2023-09-25 11:28:52 +00:00
Ben Visness 75c4f6f94d Revamp Clang checks for Windows; still need to do the same for Mac 2023-09-25 11:28:52 +00:00
Martin Fouilleul fb18d3240a Fix handling of wasm memory growing. Properly account for wasm3 header size, align on page boundary and return the previous size, asserting that there's enough memory for the requested chunk size. 2023-09-25 11:59:11 +02:00
Martin Fouilleul 388b059643 adding exp/expf 2023-09-24 18:44:32 +02:00
Martin Fouilleul b4aedb3ecc adding __math_xflowf 2023-09-24 11:15:08 +02:00
Ben Visness 34127134d5 Bypass dumb powershell execution policy problems 2023-09-21 06:54:13 +00:00
Ben Visness 24d61aaeab Detect MSVC version and architecture via preprocessor 2023-09-21 06:53:35 +00:00
Reuben Dunnington 37c00bd42f fix compile errors with pow/powf 2023-09-21 06:52:14 +00:00
Martin Fouilleul 94ce88e272 [macos] use libtool instead of ar when building wasm3 lib, and pass -no_warning_for_no_symbols because translation units in wasm3 don't have symbols 2023-09-19 11:48:42 +02:00
Martin Fouilleul 647565e285 Put offset curve sample check count in an enum to silence -Wgnu-folding-constant 2023-09-19 11:47:27 +02:00
Martin Fouilleul ecf89fa6b2 [macos build]
- Remove the need for -maes, silence warning about ignored option on ARM macs
- Set -mmacos-version-min when building wasm3 to match that of the platform layer and runtime
2023-09-19 09:56:46 +02:00
Martin Fouilleul 715ab0f6e3 put mtl renderer constants in an enum to silence -Wgnu-folding-constant warnings 2023-09-19 09:24:23 +02:00
Martin Fouilleul 370482a3e0 remove wrong alignment attribute of IM3Operation wasm3 2023-09-19 09:15:36 +02:00
Martin Fouilleul 827db17e14 update image atlas alloc functions to match image/font create functions 2023-09-19 09:10:06 +02:00
Martin Fouilleul 01565324c5 add extern C to libc-shim string.h in C++ mode 2023-09-19 08:57:23 +02:00
Reuben Dunnington ea74114693 windows: fix vsync logspam when window is minimized 2023-09-19 06:42:58 +00:00
Reuben Dunnington 4b30bd70d0 fix gl error spam when window is resized to 0 width/height 2023-09-19 06:37:46 +00:00
Ben Visness 43273cc170 Switch from `python3` to `python` on Windows
and just make other things nicer I dunno
2023-09-19 06:36:05 +00:00
Ben Visness ab3280ed4e Add extra checks for MSVC 2023-09-19 06:36:05 +00:00
Reuben Dunnington 0d839a9767
call oc_on_mouse_wheel() when getting a wheel event 2023-09-18 19:17:31 -07:00
Martin Fouilleul 762d2d9d10 small fixes in cheatsheets 2023-09-18 21:21:54 +02:00
Martin Fouilleul 34303edd4e expose malloc/free to apps through libc-shim stdlib.h 2023-09-18 21:13:06 +02:00
Reuben Dunnington e85d774245 Bring over more math functions from musl
* asin
* asinf
* acosf
* tan
* tanf
* atan
* atan2
* atan2f
* atanf
* cbrt
* cbrtf
* log
* logf
* log2
* log2f
2023-09-18 10:21:49 +00:00
Martin Fouilleul 116e614ab6 Keep log format as "function() in file:line: msg", but pass the arguments in consistent order between the host and guest app. 2023-09-18 10:19:13 +00:00
Reuben Dunnington 44477782d8 logging: move parens to be in front of function 2023-09-18 10:19:13 +00:00
Ben Visness d2e8430c49 Check if the runtime is up to date on dev install 2023-09-18 10:04:59 +00:00
Ben Visness 45c615bfa9 Add cool image to README 2023-09-18 10:02:42 +00:00
Ben Visness 17beaef0e0 Slightly improve MSVC documentation and error messages 2023-09-18 10:01:44 +00:00
Reuben Dunnington 37655abbf5 wrap some paths to handle spaces on windows 2023-09-18 10:01:11 +00:00
Ben Visness a77d6a07cd Use the HTTPS URL in the docs
SSH doesn't work unless you have a public key on your Gitea account. Obviously we don't even expect most of our users to even create a Gitea account.
2023-09-17 10:41:40 -05:00
Ben Visness 0b273f1e43 Fix links in quick start 2023-09-16 17:53:49 -05:00
Ben Visness bd780b20f3 Print help when running `orca source` 2023-09-16 15:46:00 -05:00
87 changed files with 4177 additions and 1436 deletions

View File

@ -24,7 +24,6 @@ BraceWrapping:
AfterEnum: true
AfterFunction: true
AfterNamespace: true
AfterObjCDeclaration: true
AfterStruct: true
AfterObjCDeclaration: true
AfterUnion: true

3
.gitignore vendored
View File

@ -14,6 +14,7 @@ build
*.wasm
*.app
*.dylib
*.a
Debug/*
@ -39,4 +40,4 @@ scripts/files
/ext
src/ext/angle
sketches/*/bin
sketches/*/bin

2
FUNDING.yml Normal file
View File

@ -0,0 +1,2 @@
github: orca-app
custom: "https://orca-app.dev/sponsor.html"

View File

@ -1,678 +1,207 @@
Orca
Orca
Copyright (C) 2023 Martin Fouilleul and the Orca project contributors
Copyright (C) 2023 Martin Fouilleul
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation version 3, with additional
terms under section 7 of the GNU Affero General Public License version
3, as published at the end of this document.
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 Affero General Public License for more details.
Orca is distributed under the MIT license or the Apache License version 2.0,
at your option.
-------------------------------------------------------------------------------
AGPLv3 LICENSE
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
-------------------------------------------------------------------------------
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are 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.
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.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
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 Affero 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. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
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 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 work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero 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 Affero 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 Affero 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 Affero 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
--------------------------------------------------------------------------------
ADDITIONAL TERMS
--------------------------------------------------------------------------------
1. Pursuant to section 7(b) of the AGPLv3, we require the preservation of the legal
notices, copyright notices and author attributions in the program and in its
documentation and in the Appropriate Legal Notices displayed by works containing
it.
2. Pursuant to Section 7(c) of the AGPLv3, we require that modified versions of the
material should be marked in a reasonable way as different from the official
version.
Any modified material being redistributed must include a prominent and conveniently
accessible feature for the display of a Modified Material Notice including the statement
"This program is using a modified version of the Orca Runtime version VERSION_NUMBER
released on RELEASE_DATE.
The string VERSION_NUMBER should be replaced with the exact version number of
the Program on which the modified material is based.
The string RELEASE_DATE should be replaced with the full date of the release of
the version VERSION_NUMBER of the Program on which the
modified material is based.
The Modified Material Notice must be clearly visible with size of the fonts
and icons proportionate to the user interface being used.
The Modified Material Notice must be in the same language of the user interface.
3. Additional permission for WebAssembly modules used by the Program.
The Program works by loading and running WebAssembly modules written by third parties.
To make this work, portions of the Program must be compiled into these WebAssembly modules,
making them covered work under the terms of this license.
As an additional permission, WebAssembly modules including unmodified portions of
the Program to the sole purpose of being bundled with and run by an unmodified version
of the Program can be distributed under the terms of their author's choice, without being
bound by the requirements of this license. This permission does not extend to modifications
of the Program itself or its development libraries.
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS

134
Readme.md
View File

@ -1,134 +1,2 @@
------
**DISCLAIMER: This project is very much a Work In Progress. We are making it accessible in this very early state so that participants in the [2023 Wheel Reinvention Jam](https://handmade.network/jam/2023) can try it out and possibly use it as their jamming platform. Expect bugs, missing and/or incomplete features, unstable APIs, and sparse documentation. Some current issues might be a show stopper for you, so make sure you can build and run the sample apps before jumping in.**
**This repository is not used anymore. Development of Orca was moved here: [https://github.com/orca-app/orca](https://github.com/orca-app/orca)**
**If you do choose to try out Orca anyway, thank you! We'll do our best to answer your questions, and we'd really appreciate your feedback!**
------
# Orca
Orca is a development platform and runtime environment for cross-platform, sandboxed graphical WebAssembly applications. In this early MVP you can:
- Receive mouse and keyboard input.
- Draw paths, images and text using a 2D vector graphics API.
- Draw 2D/3D graphics using OpenGL ES 3.1 (minus a few features)
- Build user interfaces using our UI API and default widgets.
- Read and write files using a capability-based API.
To learn more about the project and its goals, read the [announcement post](https://orca-app.dev/posts/230607/orca_announcement.html).
## Installing
The Orca command-line tools must be installed to your system in order to use them in your own projects.
**At this early stage, you must build Orca yourself - in the future, this installation process will be streamlined.**
### Requirements
- Windows or Mac (Linux is not yet supported)
- [Python 3](https://www.python.org/) (for command line tools)
- Clang
- **Windows users:** `clang` can be installed via the Visual Studio installer. Search for "C++ Clang Compiler".
- **Mac users:** Apple's built-in `clang` does not support WebAssembly. We recommend installing `clang` via [Homebrew](https://brew.sh/) with `brew install clang`.
- MSVC (Visual Studio 2022 17.5 or newer) (Windows only)
- This can be installed through the [Visual Studio Community](https://visualstudio.microsoft.com/) installer.
- Please note the version requirement! Orca requires C11 atomics, which were only added to MSVC in late 2022.
### Installation instructions
Clone the repo, then `cd` into the `orca` directory:
```
git clone git@git.handmade.network:hmn/orca.git
cd orca
```
Build the Orca runtime:
```
./orca dev build-runtime
```
Install the Orca dev tools. If on Windows, the tool can automatically add `orca` to your PATH. Otherwise, you must manually add the Orca install directory to your PATH, e.g. by updating `.zshrc` or `.bashrc`.
```
./orca dev install
```
Finally, verify that Orca is successfully installed by running the `orca version` command. Note the lack of `./`!
```
orca version
```
If you encounter any errors, see the FAQ below.
Once the `orca` tools are installed and on your PATH, you can use them from anywhere.
### Building the sample Orca apps
The `samples` directory contains several sample apps that demonstrate various Orca features. To build one, `cd` to a sample project's directory and run its build script. For example, for the `breakout` sample:
```
cd samples/breakout
# Windows
build.bat
# Mac
./build.sh
```
On Windows this creates a `Breakout` directory in `samples/breakout`. You can launch the app by running `Breakout/bin/Breakout.exe`. On macOS this creates a `Breakout.app` bundle in `samples/breakout` that you can double-click to run.
## Writing an Orca app
Orca apps are WebAssembly modules that use the Orca APIs. The process for creating an Orca application is:
1. Compile a WebAssembly module using your language and toolchain of choice.
2. Bundle the WebAssembly module into a native executable using the Orca command-line tools.
For a more thorough overview, please read the [Quick Start Guide](./doc/QuickStart.md), which will walk you through building a simple application.
The following additional resources may also help you familiarize yourself with Orca and its APIs:
- The [samples folder](./samples) contains sample applications that show various aspects of the Orca API and core library:
- [`breakout`](./samples/breakout) is a small breakout game making use of the vector graphics API.
- [`clock`](./samples/clock) is a simple clock showcasing vector graphics and the time API.
- [`triangle`](./samples/triangle) shows how to draw a spinning triangle using the GLES API.
- [`fluid`](./samples/fluid) is a fluid simulation using a more complex GLES setup.
- [`ui`](./samples/ui) showcases the UI API and Orca's default UI widgets.
- The [API Cheatsheets](./doc/cheatsheets) provide a list of Orca API functions, grouped by topic.
## FAQ
**What platforms does Orca support?**
We currently support Windows 10 and up, and macOS 10.15 and up. We plan to expand to more platforms in the future.
**What languages can I use with Orca?**
In principle, you can use any language and toolchain that can produce a WebAssembly module and bind to the Orca APIs. However, several important parts of Orca, such as the UI, are provided as part of the core library, which must be compiled to WebAssembly with your app, and is written in C. Therefore, at this early stage, it may be difficult to use any language other than C.
C-style C++ is possible but requires compiling the core library in C as a separate object file, and then adding that object to your compile command when building your app.
We're currently working with contributors to add support for Odin and Zig, and we look forward to expanding the number of officially-supported languages in the future.
**Which WebAssembly features does Orca support?**
We currently use [wasm3](https://github.com/wasm3/wasm3) for our interpreter. We therefore support whatever features wasm3 supports. In practice this means all WebAssembly 1.0 features, bulk memory operations, and a couple other small features.
**I am getting errors about atomics when building the runtime on Windows.**
Please ensure that you have the latest version of Visual Studio and MSVC installed. The Orca runtime requires the use of C11 atomics, which were not added to MSVC until late 2022.
**I am getting errors saying that `orca` is not found.**
Please ensure that you have installed Orca to your system per the installation instructions above. Please also ensure that the Orca install directory is on your PATH. The installation path is printed when running `./orca dev install`.
## License
Orca is distributed under the terms of the GNU Affero General Public License version 3, with additional terms in accordance with section 7 of AGPLv3. These additional terms ensure that:
- Modified versions of Orca must reasonably inform users that they are modified.
- You can distribute your application's WebAssembly modules under the terms of your choice, and are not required to license them under the terms of the AGPLv3.
Copyright and License details can be found in [LICENSE.txt](./LICENSE.txt)

View File

@ -207,10 +207,10 @@ You can unconditionally abort the application with a message box using `OC_ABORT
For more examples of how to use Orca APIs, you can look at the other [sample apps](../samples):
- [breakout](./samples/breakout) is a mini breakout game making use of the vector graphics API. It demonstrates using input and drawing images.
- [triangle](./samples/triangle) shows how to draw a spining triangle using the GLES API.
- [fluid](./samples/fluid) is a fluid simulation using a more complex GLES setup.
- [ui](./samples/ui) showcases the UI API and Orca's default UI widgets.
- [breakout](../samples/breakout) is a mini breakout game making use of the vector graphics API. It demonstrates using input and drawing images.
- [triangle](../samples/triangle) shows how to draw a spining triangle using the GLES API.
- [fluid](../samples/fluid) is a fluid simulation using a more complex GLES setup.
- [ui](../samples/ui) showcases the UI API and Orca's default UI widgets.
For a list of Orca APIs, you can look at the [API cheatsheets](../doc/cheatsheets).

View File

@ -16,8 +16,8 @@ void oc_on_mouse_enter(void);
void oc_on_mouse_leave(void);
void oc_on_mouse_move(f32 x, f32 y, f32 deltaX, f32 deltaY);
void oc_on_mouse_wheel(f32 deltaX, f32 deltaY);
void oc_on_key_down(oc_key_code key);
void oc_on_key_up(oc_key_code key);
void oc_on_key_down(oc_scan_code scan, oc_key_code key);
void oc_on_key_up(oc_scan_code scan, oc_key_code key);
void oc_on_frame_refresh(void);
void oc_on_resize(f32 width, f32 height);
void oc_on_raw_event(oc_event* event);

View File

@ -117,21 +117,21 @@ oc_font oc_font_nil(void);
bool oc_font_is_nil(oc_font font);
oc_font oc_font_create_from_memory(oc_str8 mem, u32 rangeCount, oc_unicode_range* ranges);
oc_font oc_font_create_from_file(oc_file file, u32 rangeCount, oc_unicode_range* ranges);
oc_font oc_font_create_from_path(oc_str8 path, u32 rangeCount, oc_unicode_range* ranges);
void oc_font_destroy(oc_font font);
oc_font_extents oc_font_get_extents(oc_font font);
oc_font_extents oc_font_get_scaled_extents(oc_font font, f32 emSize);
oc_str32 oc_font_get_glyph_indices(oc_font font, oc_str32 codePoints, oc_str32 backing);
oc_str32 oc_font_push_glyph_indices(oc_arena* arena, oc_font font, oc_str32 codePoints);
u32 oc_font_get_glyph_index(oc_font font, oc_utf32 codePoint);
oc_font_metrics oc_font_get_metrics(oc_font font, f32 emSize);
oc_font_metrics oc_font_get_metrics_unscaled(oc_font font);
f32 oc_font_get_scale_for_em_pixels(oc_font font, f32 emSize);
u32 oc_font_get_glyph_index(oc_font font, oc_utf32 codePoint);
oc_str32 oc_font_get_glyph_indices(oc_font font, oc_str32 codePoints, oc_str32 backing);
oc_str32 oc_font_push_glyph_indices(oc_font font, oc_arena* arena, oc_str32 codePoints);
int oc_font_get_codepoint_extents(oc_font font, oc_utf32 codePoint, oc_text_extents* outExtents);
int oc_font_get_glyph_extents(oc_font font, oc_str32 glyphIndices, oc_text_extents* outExtents);
oc_rect oc_text_bounding_box_utf32(oc_font font, f32 fontSize, oc_str32 text);
oc_rect oc_text_bounding_box(oc_font font, f32 fontSize, oc_str8 text);
oc_text_metrics oc_font_text_metrics_utf32(oc_font font, f32 fontSize, oc_str32 codepoints);
oc_text_metrics oc_font_text_metrics(oc_font font, f32 fontSize, oc_str8 text);
//------------------------------------------------------------------------------------------
// images
@ -142,7 +142,8 @@ bool oc_image_is_nil(oc_image a);
oc_image oc_image_create(oc_surface surface, u32 width, u32 height);
oc_image oc_image_create_from_rgba8(oc_surface surface, u32 width, u32 height, u8* pixels);
oc_image oc_image_create_from_memory(oc_surface surface, oc_str8 mem, bool flip);
oc_image oc_image_create_from_file(oc_surface surface, oc_str8 path, bool flip);
oc_image oc_image_create_from_file(oc_surface surface, oc_file file, bool flip);
oc_image oc_image_create_from_path(oc_surface surface, oc_str8 path, bool flip);
void oc_image_destroy(oc_image image);
@ -158,6 +159,8 @@ oc_rect oc_rect_atlas_alloc(oc_rect_atlas* atlas, i32 width, i32 height);
void oc_rect_atlas_recycle(oc_rect_atlas* atlas, oc_rect rect);
oc_image_region oc_image_atlas_alloc_from_rgba8(oc_rect_atlas* atlas, oc_image backingImage, u32 width, u32 height, u8* pixels);
oc_image_region oc_image_atlas_alloc_from_data(oc_rect_atlas* atlas, oc_image backingImage, oc_str8 data, bool flip);
oc_image_region oc_image_atlas_alloc_from_file(oc_rect_atlas* atlas, oc_image backingImage, oc_str8 path, bool flip);
oc_image_region oc_image_atlas_alloc_from_memory(oc_rect_atlas* atlas, oc_image backingImage, oc_str8 mem, bool flip);
oc_image_region oc_image_atlas_alloc_from_file(oc_rect_atlas* atlas, oc_image backingImage, oc_file file, bool flip);
oc_image_region oc_image_atlas_alloc_from_path(oc_rect_atlas* atlas, oc_image backingImage, oc_str8 path, bool flip);
void oc_image_atlas_recycle(oc_rect_atlas* atlas, oc_image_region imageRgn);

Binary file not shown.

After

Width:  |  Height:  |  Size: 184 KiB

7
orca
View File

@ -7,10 +7,17 @@ import os
import sys
MAJOR, MINOR = 3, 8
if __name__ != "__main__":
print("why are you importing the orca command-line tool as a Python module, you absolute goofball")
exit(1)
if sys.version_info.major < MAJOR or sys.version_info.minor < MINOR:
print("Your Python version is too old.")
print("Orca requires version {}.{}, but you have version {}.{}.".format(MAJOR, MINOR, sys.version_info.major, sys.version_info.minor))
exit(1)
# If you modify this, be sure to modify the version in scripts/dev.py as well.
def check_if_source():

View File

@ -3,5 +3,5 @@
rem Get the directory of this batch script
set "script_dir=%~dp0"
python3 "%script_dir%orca" %*
python "%script_dir%orca" %*
exit /b %errorlevel%

View File

@ -1,9 +1,21 @@
@echo off
setlocal enabledelayedexpansion
:: The following code checks if you have the necessary programs to compile the samples.
:: This code exists to improve the experience of first-time Orca users and can
:: be safely deleted in your own projects if you wish.
if exist "..\..\scripts\sample_build_check.py" (
python ..\..\scripts\sample_build_check.py
if !ERRORLEVEL! neq 0 exit /b 1
) else (
echo Could not check if you have the necessary tools to build the Orca samples.
echo If you have copied this script to your own project, you can delete this code.
)
set ORCA_DIR=..\..
set STDLIB_DIR=%ORCA_DIR%\src\libc-shim
:: compile wasm module
:: common flags to build wasm modules
set wasmFlags=--target=wasm32^
--no-standard-libraries ^
-mbulk-memory ^
@ -15,7 +27,13 @@ set wasmFlags=--target=wasm32^
-I%ORCA_DIR%\src ^
-I%ORCA_DIR%\src\ext
clang %wasmFlags% -o .\module.wasm %ORCA_DIR%\src\orca.c %STDLIB_DIR%\src\*.c src\main.c
:: build orca core as wasm module
clang %wasmFlags% -Wl,--relocatable -o .\liborca.a %ORCA_DIR%\src\orca.c %ORCA_DIR%\src\libc-shim\src\*.c
IF %ERRORLEVEL% NEQ 0 EXIT /B %ERRORLEVEL%
:: build sample as wasm module and link it with the orca module
clang %wasmFlags% -L . -lorca -o module.wasm src/main.c
IF %ERRORLEVEL% NEQ 0 EXIT /B %ERRORLEVEL%
:: create app directory and copy files into it
orca bundle --orca-dir %ORCA_DIR% --name Breakout --icon icon.png --resource-dir data module.wasm

View File

@ -2,18 +2,20 @@
set -euo pipefail
if [[ -x /usr/local/opt/llvm/bin/clang ]]; then
CLANG=/usr/local/opt/llvm/bin/clang
elif [[ -x /opt/homebrew/opt/llvm/bin/clang ]]; then
CLANG=/opt/homebrew/opt/llvm/bin/clang
# The following code checks if you have the necessary programs to compile the samples.
# This code exists to improve the experience of first-time Orca users and can
# be safely deleted in your own projects if you wish.
if [ -f ../../scripts/sample_build_check.py ]; then
python3 ../../scripts/sample_build_check.py
else
echo "Could not find Homebrew clang; this script will probably not work."
CLANG=clang
echo "Could not check if you have the necessary tools to build the Orca samples."
echo "If you have copied this script to your own project, you can delete this code."
fi
ORCA_DIR=../..
STDLIB_DIR=$ORCA_DIR/src/libc-shim
# common flags to build wasm modules
wasmFlags="--target=wasm32 \
--no-standard-libraries \
-mbulk-memory \
@ -25,6 +27,11 @@ wasmFlags="--target=wasm32 \
-I $ORCA_DIR/src \
-I $ORCA_DIR/src/ext"
$CLANG $wasmFlags -o ./module.wasm $ORCA_DIR/src/orca.c $STDLIB_DIR/src/*.c src/main.c
# build orca core as wasm module
clang $wasmFlags -Wl,--relocatable -o ./liborca.a $ORCA_DIR/src/orca.c $STDLIB_DIR/src/*.c
# build sample as wasm module and link it with the orca module
clang $wasmFlags -L . -lorca -o module.wasm src/main.c
# create app directory and copy files into it
orca bundle --orca-dir $ORCA_DIR --name Breakout --icon icon.png --resource-dir data module.wasm

View File

@ -1,9 +1,21 @@
@echo off
setlocal enabledelayedexpansion
:: The following code checks if you have the necessary programs to compile the samples.
:: This code exists to improve the experience of first-time Orca users and can
:: be safely deleted in your own projects if you wish.
if exist "..\..\scripts\sample_build_check.py" (
python ..\..\scripts\sample_build_check.py
if !ERRORLEVEL! neq 0 exit /b 1
) else (
echo Could not check if you have the necessary tools to build the Orca samples.
echo If you have copied this script to your own project, you can delete this code.
)
set ORCA_DIR=..\..
set STDLIB_DIR=%ORCA_DIR%\src\libc-shim
:: compile wasm module
:: common flags to build wasm modules
set wasmFlags=--target=wasm32^
--no-standard-libraries ^
-mbulk-memory ^
@ -15,7 +27,13 @@ set wasmFlags=--target=wasm32^
-I%ORCA_DIR%\src ^
-I%ORCA_DIR%\src\ext
clang %wasmFlags% -o .\module.wasm %ORCA_DIR%\src\orca.c %STDLIB_DIR%\src\*.c src\main.c
:: build orca core as wasm module
clang %wasmFlags% -Wl,--relocatable -o .\liborca.a %ORCA_DIR%\src\orca.c %ORCA_DIR%\src\libc-shim\src\*.c
IF %ERRORLEVEL% NEQ 0 EXIT /B %ERRORLEVEL%
:: build sample as wasm module and link it with the orca module
clang %wasmFlags% -L . -lorca -o module.wasm src/main.c
IF %ERRORLEVEL% NEQ 0 EXIT /B %ERRORLEVEL%
:: create app directory and copy files into it
orca bundle --orca-dir %ORCA_DIR% --name Clock --icon icon.png --resource-dir data module.wasm

View File

@ -2,18 +2,20 @@
set -euo pipefail
if [[ -x /usr/local/opt/llvm/bin/clang ]]; then
CLANG=/usr/local/opt/llvm/bin/clang
elif [[ -x /opt/homebrew/opt/llvm/bin/clang ]]; then
CLANG=/opt/homebrew/opt/llvm/bin/clang
# The following code checks if you have the necessary programs to compile the samples.
# This code exists to improve the experience of first-time Orca users and can
# be safely deleted in your own projects if you wish.
if [ -f ../../scripts/sample_build_check.py ]; then
python3 ../../scripts/sample_build_check.py
else
echo "Could not find Homebrew clang; this script will probably not work."
CLANG=clang
echo "Could not check if you have the necessary tools to build the Orca samples."
echo "If you have copied this script to your own project, you can delete this code."
fi
ORCA_DIR=../..
STDLIB_DIR=$ORCA_DIR/src/libc-shim
# common flags to build wasm modules
wasmFlags="--target=wasm32 \
--no-standard-libraries \
-mbulk-memory \
@ -25,6 +27,11 @@ wasmFlags="--target=wasm32 \
-I $ORCA_DIR/src \
-I $ORCA_DIR/src/ext"
$CLANG $wasmFlags -o ./module.wasm $ORCA_DIR/src/orca.c $STDLIB_DIR/src/*.c src/main.c
# build orca core as wasm module
clang $wasmFlags -Wl,--relocatable -o ./liborca.a $ORCA_DIR/src/orca.c $STDLIB_DIR/src/*.c
# build sample as wasm module and link it with the orca module
clang $wasmFlags -L . -lorca -o module.wasm src/main.c
# create app directory and copy files into it
orca bundle --orca-dir $ORCA_DIR --name Clock --icon icon.png --resource-dir data module.wasm

View File

@ -1,9 +1,21 @@
@echo off
setlocal enabledelayedexpansion
:: The following code checks if you have the necessary programs to compile the samples.
:: This code exists to improve the experience of first-time Orca users and can
:: be safely deleted in your own projects if you wish.
if exist "..\..\scripts\sample_build_check.py" (
python ..\..\scripts\sample_build_check.py
if !ERRORLEVEL! neq 0 exit /b 1
) else (
echo Could not check if you have the necessary tools to build the Orca samples.
echo If you have copied this script to your own project, you can delete this code.
)
set ORCA_DIR=..\..
set STDLIB_DIR=%ORCA_DIR%\src\libc-shim
:: compile wasm module
:: common flags to build wasm modules
set wasmFlags=--target=wasm32^
--no-standard-libraries ^
-mbulk-memory ^
@ -15,6 +27,10 @@ set wasmFlags=--target=wasm32^
-I%ORCA_DIR%\src ^
-I%ORCA_DIR%\src\ext
:: build orca core as wasm module
clang %wasmFlags% -Wl,--relocatable -o .\liborca.a %ORCA_DIR%\src\orca.c %ORCA_DIR%\src\libc-shim\src\*.c
IF %ERRORLEVEL% NEQ 0 EXIT /B %ERRORLEVEL%
set shaders=src/shaders/advect.glsl^
src/shaders/blit_div_fragment.glsl^
src/shaders/blit_div_vertex.glsl^
@ -30,10 +46,12 @@ set shaders=src/shaders/advect.glsl^
src/shaders/subtract_pressure.glsl
call python3 ../../scripts/embed_text_files.py --prefix=glsl_ --output src/glsl_shaders.h %shaders%
call python ../../scripts/embed_text_files.py --prefix=glsl_ --output src/glsl_shaders.h %shaders%
if !ERRORLEVEL! neq 0 exit /b !ERRORLEVEL!
:: build sample as wasm module and link it with the orca module
clang %wasmFlags% -L . -lorca -o .\module.wasm src\main.c
IF %ERRORLEVEL% NEQ 0 EXIT /B %ERRORLEVEL%
clang %wasmFlags% -o .\module.wasm %ORCA_DIR%\src\orca.c %STDLIB_DIR%\src\*.c src\main.c
IF %ERRORLEVEL% NEQ 0 EXIT /B %ERRORLEVEL%
orca bundle --orca-dir %ORCA_DIR% --name Fluid --icon icon.png module.wasm
:: create app directory and copy files into it
orca bundle --orca-dir %ORCA_DIR% --name Fluid --icon icon.png module.wasm

View File

@ -2,13 +2,14 @@
set -euo pipefail
if [[ -x /usr/local/opt/llvm/bin/clang ]]; then
CLANG=/usr/local/opt/llvm/bin/clang
elif [[ -x /opt/homebrew/opt/llvm/bin/clang ]]; then
CLANG=/opt/homebrew/opt/llvm/bin/clang
# The following code checks if you have the necessary programs to compile the samples.
# This code exists to improve the experience of first-time Orca users and can
# be safely deleted in your own projects if you wish.
if [ -f ../../scripts/sample_build_check.py ]; then
python3 ../../scripts/sample_build_check.py
else
echo "Could not find Homebrew clang; this script will probably not work."
CLANG=clang
echo "Could not check if you have the necessary tools to build the Orca samples."
echo "If you have copied this script to your own project, you can delete this code."
fi
ORCA_DIR=../..
@ -16,6 +17,7 @@ STDLIB_DIR=$ORCA_DIR/src/libc-shim
python3 ../../scripts/embed_text_files.py --prefix=glsl_ --output src/glsl_shaders.h src/shaders/*.glsl
# common flags to build wasm modules
wasmFlags="--target=wasm32 \
--no-standard-libraries \
-mbulk-memory \
@ -27,6 +29,11 @@ wasmFlags="--target=wasm32 \
-I $ORCA_DIR/src \
-I $ORCA_DIR/src/ext"
$CLANG $wasmFlags -o ./module.wasm $ORCA_DIR/src/orca.c $STDLIB_DIR/src/*.c src/main.c
# build orca core as wasm module
clang $wasmFlags -Wl,--relocatable -o ./liborca.a $ORCA_DIR/src/orca.c $STDLIB_DIR/src/*.c
# build sample as wasm module and link it with the orca module
clang $wasmFlags -L . -lorca -o module.wasm src/main.c
# create app directory and copy files into it
orca bundle --orca-dir $ORCA_DIR --name Fluid --icon icon.png module.wasm

View File

@ -140,6 +140,7 @@ frame_buffer divBuffer[4];
GLuint vertexBuffer;
oc_surface surface;
f64 startTime;
//----------------------------------------------------------------
//NOTE(martin): initialization
@ -403,6 +404,7 @@ typedef struct mouse_input
} mouse_input;
mouse_input mouseInput = { 0 };
bool mouseWasDown = false;
int frameWidth = 800;
int frameHeight = 600;
@ -410,6 +412,7 @@ int frameHeight = 600;
ORCA_EXPORT void oc_on_mouse_down(int button)
{
mouseInput.down = true;
mouseWasDown = true;
}
ORCA_EXPORT void oc_on_mouse_up(int button)
@ -577,23 +580,56 @@ void multigrid_clear(frame_buffer* error)
void input_splat(float t)
{
//NOTE: apply force and dye
if(mouseInput.down && (mouseInput.deltaX || mouseInput.deltaY))
bool applySplat = false;
float x, y, deltaX, deltaY;
static f64 lastFrameTime = 0;
if (lastFrameTime == 0)
{
lastFrameTime = startTime;
}
f64 now = oc_clock_time(OC_CLOCK_MONOTONIC);
float frameDuration = now - lastFrameTime;
lastFrameTime = now;
if (mouseInput.down && (mouseInput.deltaX || mouseInput.deltaY))
{
oc_vec2 scaling = oc_surface_contents_scaling(surface);
applySplat = true;
x = mouseInput.x * scaling.x / frameWidth;
y = mouseInput.y * scaling.y / frameHeight;
deltaX = 1. / 60 / frameDuration * mouseInput.deltaX * scaling.x / frameWidth;
deltaY = 1. / 60 / frameDuration * mouseInput.deltaY * scaling.y / frameHeight;
mouseInput.deltaX = 0;
mouseInput.deltaY = 0;
}
f64 timeSinceStart = now - startTime;
if (!mouseWasDown && timeSinceStart < 1)
{
applySplat = true;
float totalDeltaX = 0.5;
x = 0.1 + totalDeltaX * timeSinceStart;
y = 0.5;
deltaX = totalDeltaX / 180;
deltaY = 0;
}
//NOTE: apply force and dye
if(applySplat)
{
// account for margin
float margin = 32;
float offset = margin / texWidth;
float ratio = 1 - 2 * margin / texWidth;
float splatPosX = (mouseInput.x * scaling.x / frameWidth) * ratio + offset;
float splatPosY = (1 - mouseInput.y * scaling.y / frameHeight) * ratio + offset;
float splatPosX = x * ratio + offset;
float splatPosY = (1 - y) * ratio + offset;
float splatVelX = (10000. * DELTA * mouseInput.deltaX * scaling.x / frameWidth) * ratio;
float splatVelY = (-10000. * DELTA * mouseInput.deltaY * scaling.y / frameWidth) * ratio;
float splatVelX = (10000. * DELTA * deltaX) * ratio;
float splatVelY = (-10000. * DELTA * deltaY) * ratio;
float intensity = 100 * sqrtf(square(ratio * mouseInput.deltaX * scaling.x / frameWidth) + square(ratio * mouseInput.deltaY * scaling.y / frameHeight));
float intensity = 100 * sqrtf(square(ratio * deltaX) + square(ratio * deltaY));
float r = intensity * (sinf(2 * M_PI * 0.1 * t) + 1);
float g = 0.5 * intensity * (cosf(2 * M_PI * 0.1 / M_E * t + 654) + 1);
@ -602,9 +638,6 @@ void input_splat(float t)
float radius = 0.005;
apply_splat(splatPosX, splatPosY, radius, splatVelX, splatVelY, r, g, b, false);
mouseInput.deltaX = 0;
mouseInput.deltaY = 0;
}
}
@ -677,6 +710,8 @@ ORCA_EXPORT void oc_on_init()
testDiv[i][j][0] = 0.5 + 0.5 * cosf(j / 100. * 3.14159 + i / 100. * 1.2139);
}
}
startTime = oc_clock_time(OC_CLOCK_MONOTONIC);
}
ORCA_EXPORT void oc_on_resize(u32 width, u32 height)

View File

@ -1,9 +1,21 @@
@echo off
setlocal enabledelayedexpansion
:: The following code checks if you have the necessary programs to compile the samples.
:: This code exists to improve the experience of first-time Orca users and can
:: be safely deleted in your own projects if you wish.
if exist "..\..\scripts\sample_build_check.py" (
python ..\..\scripts\sample_build_check.py
if !ERRORLEVEL! neq 0 exit /b 1
) else (
echo Could not check if you have the necessary tools to build the Orca samples.
echo If you have copied this script to your own project, you can delete this code.
)
set ORCA_DIR=..\..
set STDLIB_DIR=%ORCA_DIR%\src\libc-shim
:: compile wasm module
:: common flags to build wasm modules
set wasmFlags=--target=wasm32^
--no-standard-libraries ^
-mbulk-memory ^
@ -15,7 +27,13 @@ set wasmFlags=--target=wasm32^
-I%ORCA_DIR%\src ^
-I%ORCA_DIR%\src\ext
clang %wasmFlags% -o .\module.wasm %ORCA_DIR%\src\orca.c %STDLIB_DIR%\src\*.c src\main.c
:: build orca core as wasm module
clang %wasmFlags% -Wl,--relocatable -o .\liborca.a %ORCA_DIR%\src\orca.c %ORCA_DIR%\src\libc-shim\src\*.c
IF %ERRORLEVEL% NEQ 0 EXIT /B %ERRORLEVEL%
orca bundle --orca-dir %ORCA_DIR% --name Triangle module.wasm
:: build sample as wasm module and link it with the orca module
clang %wasmFlags% -L . -lorca -o module.wasm src/main.c
IF %ERRORLEVEL% NEQ 0 EXIT /B %ERRORLEVEL%
:: create app directory and copy files into it
orca bundle --orca-dir %ORCA_DIR% --name Triangle --icon icon.png module.wasm

View File

@ -2,18 +2,20 @@
set -euo pipefail
if [[ -x /usr/local/opt/llvm/bin/clang ]]; then
CLANG=/usr/local/opt/llvm/bin/clang
elif [[ -x /opt/homebrew/opt/llvm/bin/clang ]]; then
CLANG=/opt/homebrew/opt/llvm/bin/clang
# The following code checks if you have the necessary programs to compile the samples.
# This code exists to improve the experience of first-time Orca users and can
# be safely deleted in your own projects if you wish.
if [ -f ../../scripts/sample_build_check.py ]; then
python3 ../../scripts/sample_build_check.py
else
echo "Could not find Homebrew clang; this script will probably not work."
CLANG=clang
echo "Could not check if you have the necessary tools to build the Orca samples."
echo "If you have copied this script to your own project, you can delete this code."
fi
ORCA_DIR=../..
STDLIB_DIR=$ORCA_DIR/src/libc-shim
# common flags to build wasm modules
wasmFlags="--target=wasm32 \
--no-standard-libraries \
-mbulk-memory \
@ -25,6 +27,11 @@ wasmFlags="--target=wasm32 \
-I $ORCA_DIR/src \
-I $ORCA_DIR/src/ext"
$CLANG $wasmFlags -o ./module.wasm $ORCA_DIR/src/orca.c $STDLIB_DIR/src/*.c src/main.c
# build orca core as wasm module
clang $wasmFlags -Wl,--relocatable -o ./liborca.a $ORCA_DIR/src/orca.c $STDLIB_DIR/src/*.c
# build sample as wasm module and link it with the orca module
clang $wasmFlags -L . -lorca -o module.wasm src/main.c
# create app directory and copy files into it
orca bundle --orca-dir $ORCA_DIR --name Triangle module.wasm

View File

@ -1,9 +1,21 @@
@echo off
setlocal enabledelayedexpansion
:: The following code checks if you have the necessary programs to compile the samples.
:: This code exists to improve the experience of first-time Orca users and can
:: be safely deleted in your own projects if you wish.
if exist "..\..\scripts\sample_build_check.py" (
python ..\..\scripts\sample_build_check.py
if !ERRORLEVEL! neq 0 exit /b 1
) else (
echo Could not check if you have the necessary tools to build the Orca samples.
echo If you have copied this script to your own project, you can delete this code.
)
set ORCA_DIR=..\..
set STDLIB_DIR=%ORCA_DIR%\src\libc-shim
:: compile wasm module
:: common flags to build wasm modules
set wasmFlags=--target=wasm32^
--no-standard-libraries ^
-mbulk-memory ^
@ -15,7 +27,13 @@ set wasmFlags=--target=wasm32^
-I%ORCA_DIR%\src ^
-I%ORCA_DIR%\src\ext
clang %wasmFlags% -o .\module.wasm %ORCA_DIR%\src\orca.c %STDLIB_DIR%\src\*.c src\main.c
:: build orca core as wasm module
clang %wasmFlags% -Wl,--relocatable -o .\liborca.a %ORCA_DIR%\src\orca.c %ORCA_DIR%\src\libc-shim\src\*.c
IF %ERRORLEVEL% NEQ 0 EXIT /B %ERRORLEVEL%
:: build sample as wasm module and link it with the orca module
clang %wasmFlags% -L . -lorca -o .\module.wasm src\main.c
IF %ERRORLEVEL% NEQ 0 EXIT /B %ERRORLEVEL%
:: create app directory and copy files into it
orca bundle --orca-dir %ORCA_DIR% --name UI --resource-dir data module.wasm

View File

@ -2,18 +2,20 @@
set -euo pipefail
if [[ -x /usr/local/opt/llvm/bin/clang ]]; then
CLANG=/usr/local/opt/llvm/bin/clang
elif [[ -x /opt/homebrew/opt/llvm/bin/clang ]]; then
CLANG=/opt/homebrew/opt/llvm/bin/clang
# The following code checks if you have the necessary programs to compile the samples.
# This code exists to improve the experience of first-time Orca users and can
# be safely deleted in your own projects if you wish.
if [ -f ../../scripts/sample_build_check.py ]; then
python3 ../../scripts/sample_build_check.py
else
echo "Could not find Homebrew clang; this script will probably not work."
CLANG=clang
echo "Could not check if you have the necessary tools to build the Orca samples."
echo "If you have copied this script to your own project, you can delete this code."
fi
ORCA_DIR=../..
STDLIB_DIR=$ORCA_DIR/src/libc-shim
# common flags to build wasm modules
wasmFlags="--target=wasm32 \
--no-standard-libraries \
-mbulk-memory \
@ -25,6 +27,11 @@ wasmFlags="--target=wasm32 \
-I $ORCA_DIR/src \
-I $ORCA_DIR/src/ext"
$CLANG $wasmFlags -o ./module.wasm $ORCA_DIR/src/orca.c $STDLIB_DIR/src/*.c src/main.c
# build orca core as wasm module
clang $wasmFlags -Wl,--relocatable -o ./liborca.a $ORCA_DIR/src/orca.c $STDLIB_DIR/src/*.c
# build sample as wasm module and link it with the orca module
clang $wasmFlags -L . -lorca -o module.wasm src/main.c
# create app directory and copy files into it
orca bundle --orca-dir $ORCA_DIR --name UI --resource-dir data module.wasm

View File

@ -5,292 +5,298 @@ import json
def needs_arg_ptr_stub(decl):
res = (decl['ret']['tag'] == 'S')
for arg in decl['args']:
if arg['type']['tag'] == 'S':
res = True
return(res)
res = (decl['ret']['tag'] == 'S')
for arg in decl['args']:
if arg['type']['tag'] == 'S':
res = True
return(res)
def printError(str):
# This prints a string with a red foreground color.
# See this link for an explanation of console escape codes: https://stackabuse.com/how-to-print-colored-text-in-python/
print("\x1b[38;5;196m" + "error: " + str + "\033[0;0m")
# This prints a string with a red foreground color.
# See this link for an explanation of console escape codes: https://stackabuse.com/how-to-print-colored-text-in-python/
print("\x1b[38;5;196m" + "error: " + str + "\033[0;0m")
def bindgen(apiName, spec, **kwargs):
guest_stubs_path = kwargs.get("guest_stubs")
guest_include = kwargs.get("guest_include")
wasm3_bindings_path = kwargs.get("wasm3_bindings")
guest_stubs_path = kwargs.get("guest_stubs")
guest_include = kwargs.get("guest_include")
wasm3_bindings_path = kwargs.get("wasm3_bindings")
if guest_stubs_path == None:
guest_stubs_path = 'bindgen_' + apiName + '_guest_stubs.c'
if wasm3_bindings_path == None:
wasm3_bindings_path = 'bindgen_' + apiName + '_wasm3_bindings.c'
if guest_stubs_path == None:
guest_stubs_path = 'bindgen_' + apiName + '_guest_stubs.c'
if wasm3_bindings_path == None:
wasm3_bindings_path = 'bindgen_' + apiName + '_wasm3_bindings.c'
host_bindings = open(wasm3_bindings_path, 'w')
guest_bindings = None
host_bindings = open(wasm3_bindings_path, 'w')
guest_bindings = None
specFile = open(spec, 'r')
data = json.load(specFile)
specFile = open(spec, 'r')
data = json.load(specFile)
for decl in data:
if needs_arg_ptr_stub(decl):
guest_bindings = open(guest_stubs_path, 'w')
if guest_include != None:
s = '#include"' + guest_include + '"\n\n'
print(s, file=guest_bindings)
break
for decl in data:
if needs_arg_ptr_stub(decl):
guest_bindings = open(guest_stubs_path, 'w')
if guest_include != None:
s = '#include"' + guest_include + '"\n\n'
print(s, file=guest_bindings)
break
for decl in data:
for decl in data:
name = decl['name']
cname = decl.get('cname', name)
name = decl['name']
cname = decl.get('cname', name)
if needs_arg_ptr_stub(decl):
argPtrStubName = name + '_argptr_stub'
# pointer arg stub declaration
s = ''
if decl['ret']['tag'] == 'S':
s += 'void'
else:
s += decl['ret']['name']
if needs_arg_ptr_stub(decl):
argPtrStubName = name + '_argptr_stub'
# pointer arg stub declaration
s = ''
if decl['ret']['tag'] == 'S':
s += 'void'
else:
s += decl['ret']['name']
s += ' ORCA_IMPORT(' + argPtrStubName + ') ('
s += ' ORCA_IMPORT(' + argPtrStubName + ') ('
if decl['ret']['tag'] == 'S':
s += decl['ret']['name'] + '* __retArg'
if len(decl['args']) > 0:
s += ', '
if decl['ret']['tag'] == 'S':
s += decl['ret']['name'] + '* __retArg'
if len(decl['args']) > 0:
s += ', '
elif len(decl['args']) == 0:
s += 'void'
for i, arg in enumerate(decl['args']):
s += arg['type']['name']
if arg['type']['tag'] == 'S':
s += '*'
s += ' ' + arg['name']
if i+1 < len(decl['args']):
s += ', '
s += ');\n\n'
for i, arg in enumerate(decl['args']):
s += arg['type']['name']
if arg['type']['tag'] == 'S':
s += '*'
s += ' ' + arg['name']
if i+1 < len(decl['args']):
s += ', '
s += ');\n\n'
# forward function to pointer arg stub declaration
s += decl['ret']['name'] + ' ' + name + '('
for i, arg in enumerate(decl['args']):
s += arg['type']['name'] + ' ' + arg['name']
if i+1 < len(decl['args']):
s += ', '
s += ')\n'
s += '{\n'
s += '\t'
if decl['ret']['tag'] == 'S':
s += decl['ret']['name'] + ' __ret;\n\t'
elif decl['ret']['tag'] != 'v':
s += decl['ret']['name']
s += ' __ret = '
s += argPtrStubName + '('
# forward function to pointer arg stub declaration
s += decl['ret']['name'] + ' ' + name + '('
if decl['ret']['tag'] == 'S':
s += '&__ret'
if len(decl['args']) > 0:
s += ', '
if len(decl['args']) == 0:
s += 'void'
for i, arg in enumerate(decl['args']):
if arg['type']['tag'] == 'S':
s += '&'
for i, arg in enumerate(decl['args']):
s += arg['type']['name'] + ' ' + arg['name']
if i+1 < len(decl['args']):
s += ', '
s += ')\n'
s += '{\n'
s += '\t'
if decl['ret']['tag'] == 'S':
s += decl['ret']['name'] + ' __ret;\n\t'
elif decl['ret']['tag'] != 'v':
s += decl['ret']['name']
s += ' __ret = '
s += argPtrStubName + '('
s += arg['name']
if i+1 < len(decl['args']):
s += ', '
s += ');\n'
if decl['ret']['tag'] != 'v':
s += '\treturn(__ret);\n'
s += '}\n\n'
if decl['ret']['tag'] == 'S':
s += '&__ret'
if len(decl['args']) > 0:
s += ', '
print(s, file=guest_bindings)
for i, arg in enumerate(decl['args']):
if arg['type']['tag'] == 'S':
s += '&'
# host-side stub
s = 'const void* ' + cname + '_stub(IM3Runtime runtime, IM3ImportContext _ctx, uint64_t* _sp, void* _mem)'
s += arg['name']
if i+1 < len(decl['args']):
s += ', '
s += ');\n'
if decl['ret']['tag'] != 'v':
s += '\treturn(__ret);\n'
s += '}\n\n'
gen_stub = decl.get('gen_stub', True)
if gen_stub == False:
s += ';\n\n'
else:
s += '\n{\n'
print(s, file=guest_bindings)
# host-side stub
s = 'const void* ' + cname + '_stub(IM3Runtime runtime, IM3ImportContext _ctx, uint64_t* _sp, void* _mem)'
gen_stub = decl.get('gen_stub', True)
if gen_stub == False:
s += ';\n\n'
else:
s += '\n{\n'
# NOTE: check and cast arguments
retTag = decl['ret']['tag']
# NOTE: check and cast arguments
retTag = decl['ret']['tag']
firstArgIndex = 0
if retTag != 'v':
firstArgIndex = 1
firstArgIndex = 0
if retTag != 'v':
firstArgIndex = 1
if retTag == 'S':
retTypeName = decl['ret']['name']
retTypeCName = decl['ret'].get('cname', retTypeName)
s += retTypeCName + '* __retPtr = (' + retTypeCName + '*)((char*)_mem + *(i32*)&_sp[0]);\n'
if retTag == 'S':
retTypeName = decl['ret']['name']
retTypeCName = decl['ret'].get('cname', retTypeName)
s += retTypeCName + '* __retPtr = (' + retTypeCName + '*)((char*)_mem + *(i32*)&_sp[0]);\n'
s += '\t{\n'
s += '\t\tOC_ASSERT(((char*)__retPtr >= (char*)_mem) && (((char*)__retPtr - (char*)_mem) < m3_GetMemorySize(runtime)), "return pointer is out of bounds");\n'
s += '\t\tOC_ASSERT((char*)__retPtr + sizeof(' + retTypeCName + ') <= ((char*)_mem + m3_GetMemorySize(runtime)), "return pointer is out of bounds");\n'
s += '\t}\n'
s += '\t{\n'
s += '\t\tOC_ASSERT(((char*)__retPtr >= (char*)_mem) && (((char*)__retPtr - (char*)_mem) < m3_GetMemorySize(runtime)), "return pointer is out of bounds");\n'
s += '\t\tOC_ASSERT((char*)__retPtr + sizeof(' + retTypeCName + ') <= ((char*)_mem + m3_GetMemorySize(runtime)), "return pointer is out of bounds");\n'
s += '\t}\n'
for argIndex, arg in enumerate(decl['args']):
for argIndex, arg in enumerate(decl['args']):
argName = arg['name']
typeName = arg['type']['name']
typeCName = arg['type'].get('cname', typeName)
argTag = arg['type']['tag']
argName = arg['name']
typeName = arg['type']['name']
typeCName = arg['type'].get('cname', typeName)
argTag = arg['type']['tag']
s += '\t'
s += '\t'
if argTag == 'i':
s += typeCName + ' ' + argName + ' = ('+typeCName+')*(i32*)&_sp[' + str(firstArgIndex + argIndex) + '];\n'
elif argTag == 'I':
s += typeCName + ' ' + argName + ' = ('+typeCName+')*(i64*)&_sp[' + str(firstArgIndex + argIndex) + '];\n'
elif argTag == 'f':
s += typeCName + ' ' + argName + ' = ('+typeCName+')*(f32*)&_sp[' + str(firstArgIndex + argIndex) + '];\n'
elif argTag == 'F':
s += typeCName + ' ' + argName + ' = ('+typeCName+')*(f64*)&_sp[' + str(firstArgIndex + argIndex) + '];\n'
elif argTag == 'p':
s += typeCName + ' ' + argName + ' = ('+ typeCName +')((char*)_mem + *(u32*)&_sp[' + str(firstArgIndex + argIndex) + ']);\n'
elif argTag == 'S':
s += typeCName + ' ' + argName + ' = *('+ typeCName +'*)((char*)_mem + *(u32*)&_sp[' + str(firstArgIndex + argIndex) + ']);\n'
else:
print('unrecognized type ' + c + ' in procedure signature\n')
break
if argTag == 'i':
s += typeCName + ' ' + argName + ' = ('+typeCName+')*(i32*)&_sp[' + str(firstArgIndex + argIndex) + '];\n'
elif argTag == 'I':
s += typeCName + ' ' + argName + ' = ('+typeCName+')*(i64*)&_sp[' + str(firstArgIndex + argIndex) + '];\n'
elif argTag == 'f':
s += typeCName + ' ' + argName + ' = ('+typeCName+')*(f32*)&_sp[' + str(firstArgIndex + argIndex) + '];\n'
elif argTag == 'F':
s += typeCName + ' ' + argName + ' = ('+typeCName+')*(f64*)&_sp[' + str(firstArgIndex + argIndex) + '];\n'
elif argTag == 'p':
s += typeCName + ' ' + argName + ' = ('+ typeCName +')((char*)_mem + *(u32*)&_sp[' + str(firstArgIndex + argIndex) + ']);\n'
elif argTag == 'S':
s += typeCName + ' ' + argName + ' = *('+ typeCName +'*)((char*)_mem + *(u32*)&_sp[' + str(firstArgIndex + argIndex) + ']);\n'
else:
print('unrecognized type ' + c + ' in procedure signature\n')
break
# check pointer arg length
for arg in decl['args']:
# check pointer arg length
for arg in decl['args']:
argName = arg['name']
typeName = arg['type']['name']
typeCName = arg['type'].get('cname', typeName)
argTag = arg['type']['tag']
argLen = arg.get('len')
argName = arg['name']
typeName = arg['type']['name']
typeCName = arg['type'].get('cname', typeName)
argTag = arg['type']['tag']
argLen = arg.get('len')
if argTag == 'p':
if argLen == None:
printError("binding '" + name + "' missing pointer length decoration for param '" + argName + "'")
else:
s += '\t{\n'
s += '\t\tOC_ASSERT(((char*)'+ argName + ' >= (char*)_mem) && (((char*)'+ argName +' - (char*)_mem) < m3_GetMemorySize(runtime)), "parameter \''+argName+'\' is out of bounds");\n'
s += '\t\tOC_ASSERT((char*)' + argName + ' + '
if argTag == 'p':
if argLen == None:
printError("binding '" + name + "' missing pointer length decoration for param '" + argName + "'")
else:
s += '\t{\n'
s += '\t\tOC_ASSERT(((char*)'+ argName + ' >= (char*)_mem) && (((char*)'+ argName +' - (char*)_mem) < m3_GetMemorySize(runtime)), "parameter \''+argName+'\' is out of bounds");\n'
s += '\t\tOC_ASSERT((char*)' + argName + ' + '
proc = argLen.get('proc')
if proc != None:
s += proc + '(runtime, '
lenProcArgs = argLen['args']
for i, lenProcArg in enumerate(lenProcArgs):
s += lenProcArg
if i < len(lenProcArgs)-1:
s += ', '
s += ')'
else:
components = argLen.get('components')
countArg = argLen.get('count')
proc = argLen.get('proc')
if proc != None:
s += proc + '(runtime, '
lenProcArgs = argLen['args']
for i, lenProcArg in enumerate(lenProcArgs):
s += lenProcArg
if i < len(lenProcArgs)-1:
s += ', '
s += ')'
else:
components = argLen.get('components')
countArg = argLen.get('count')
if components != None:
s += str(components)
if countArg != None:
s += '*'
if countArg != None:
s += countArg
if components != None:
s += str(components)
if countArg != None:
s += '*'
if countArg != None:
s += countArg
if typeCName.endswith('**') or (typeCName.startswith('void') == False and typeCName.startswith('const void') == False):
s += '*sizeof('+typeCName[:-1]+')'
if typeCName.endswith('**') or (typeCName.startswith('void') == False and typeCName.startswith('const void') == False):
s += '*sizeof('+typeCName[:-1]+')'
s += ' <= ((char*)_mem + m3_GetMemorySize(runtime)), "parameter \''+argName+'\' is out of bounds");\n'
s += '\t}\n'
s += ' <= ((char*)_mem + m3_GetMemorySize(runtime)), "parameter \''+argName+'\' is out of bounds");\n'
s += '\t}\n'
s += '\t'
s += '\t'
if retTag == 'i':
s += '*((i32*)&_sp[0]) = (i32)'
elif retTag == 'I':
s += '*((i64*)&_sp[0]) = (i64)'
elif retTag == 'f':
s += '*((f32*)&_sp[0]) = (f32)'
elif retTag == 'F':
s += '*((f64*)&_sp[0]) = (f64)'
elif retTag == 'S':
s += '*__retPtr = '
elif retTag == 'p':
print("Warning: " + name + ": pointer return type not supported yet")
if retTag == 'i':
s += '*((i32*)&_sp[0]) = (i32)'
elif retTag == 'I':
s += '*((i64*)&_sp[0]) = (i64)'
elif retTag == 'f':
s += '*((f32*)&_sp[0]) = (f32)'
elif retTag == 'F':
s += '*((f64*)&_sp[0]) = (f64)'
elif retTag == 'S':
s += '*__retPtr = '
elif retTag == 'p':
print("Warning: " + name + ": pointer return type not supported yet")
s += cname + '('
s += cname + '('
for i, arg in enumerate(decl['args']):
s += arg['name']
for i, arg in enumerate(decl['args']):
s += arg['name']
if i+1 < len(decl['args']):
s += ', '
if i+1 < len(decl['args']):
s += ', '
s += ');\n\treturn(0);\n}\n\n'
s += ');\n\treturn(0);\n}\n\n'
print(s, file=host_bindings)
print(s, file=host_bindings)
# link function
s = 'int bindgen_link_' + apiName + '_api(IM3Module module)\n{\n'
s += ' M3Result res;\n'
s += ' int ret = 0;\n'
# link function
s = 'int bindgen_link_' + apiName + '_api(IM3Module module)\n{\n'
s += ' M3Result res;\n'
s += ' int ret = 0;\n'
for decl in data:
name = decl['name']
cname = decl.get('cname', name)
for decl in data:
name = decl['name']
cname = decl.get('cname', name)
if needs_arg_ptr_stub(decl):
name = name + '_argptr_stub'
if needs_arg_ptr_stub(decl):
name = name + '_argptr_stub'
m3Sig = ''
if decl['ret']['tag'] == 'S':
m3Sig += 'v'
else:
m3Sig += decl['ret']['tag']
m3Sig = ''
if decl['ret']['tag'] == 'S':
m3Sig += 'v'
else:
m3Sig += decl['ret']['tag']
m3Sig += '('
if decl['ret']['tag'] == 'S':
m3Sig += 'i'
for arg in decl['args']:
tag = arg['type']['tag']
if tag == 'p' or tag == 'S':
tag = 'i'
m3Sig += tag
m3Sig += ')'
m3Sig += '('
if decl['ret']['tag'] == 'S':
m3Sig += 'i'
for arg in decl['args']:
tag = arg['type']['tag']
if tag == 'p' or tag == 'S':
tag = 'i'
m3Sig += tag
m3Sig += ')'
s += ' res = m3_LinkRawFunction(module, "*", "' + name + '", "' + m3Sig + '", ' + cname + '_stub);\n'
s += ' if(res != m3Err_none && res != m3Err_functionLookupFailed)\n'
s += ' {\n'
s += ' oc_log_error("Couldn\'t link function ' + name + ' (%s)\\n", res);\n'
s += ' ret = -1;\n'
s += ' }\n\n'
s += ' res = m3_LinkRawFunction(module, "*", "' + name + '", "' + m3Sig + '", ' + cname + '_stub);\n'
s += ' if(res != m3Err_none && res != m3Err_functionLookupFailed)\n'
s += ' {\n'
s += ' oc_log_error("Couldn\'t link function ' + name + ' (%s)\\n", res);\n'
s += ' ret = -1;\n'
s += ' }\n\n'
s += '\treturn(ret);\n}\n'
s += '\treturn(ret);\n}\n'
print(s, file=host_bindings)
print(s, file=host_bindings)
if __name__ == "__main__":
parser = ArgumentParser(prog='bindgen.py')
parser.add_argument('api')
parser.add_argument('spec')
parser.add_argument('-g', '--guest-stubs')
parser.add_argument('--guest-include')
parser.add_argument('--wasm3-bindings')
parser = ArgumentParser(prog='bindgen.py')
parser.add_argument('api')
parser.add_argument('spec')
parser.add_argument('-g', '--guest-stubs')
parser.add_argument('--guest-include')
parser.add_argument('--wasm3-bindings')
args = parser.parse_args()
args = parser.parse_args()
apiName = args.api
spec = args.spec
guest_stubs_path = args.guest_stubs
if guest_stubs_path == None:
guest_stubs_path = 'bindgen_' + apiName + '_guest_stubs.c'
apiName = args.api
spec = args.spec
guest_stubs_path = args.guest_stubs
if guest_stubs_path == None:
guest_stubs_path = 'bindgen_' + apiName + '_guest_stubs.c'
wasm3_bindings_path = args.wasm3_bindings
if wasm3_bindings_path == None:
wasm3_bindings_path = 'bindgen_' + apiName + '_wasm3_bindings.c'
wasm3_bindings_path = args.wasm3_bindings
if wasm3_bindings_path == None:
wasm3_bindings_path = 'bindgen_' + apiName + '_wasm3_bindings.c'
bindgen(apiName, spec,
guest_stubs=guest_stubs_path,
guest_include=args.guest_include,
wasm3_bindings=wasm3_bindings_path,
)
bindgen(apiName, spec,
guest_stubs=guest_stubs_path,
guest_include=args.guest_include,
wasm3_bindings=wasm3_bindings_path,
)

View File

@ -1,5 +1,6 @@
import hashlib
import json
import os
from .log import *
@ -28,3 +29,80 @@ def checkfile(filepath):
def filesum(filepath):
with open(filepath, "rb") as file:
return hashlib.sha256(file.read()).hexdigest()
# -----------------------------------------------------------------------------
# Directory-hashing implementation pulled from the checksumdir package on pypi.
# Licensed under the MIT license.
# -----------------------------------------------------------------------------
def dirsum(
dirname,
hash_func=hashlib.sha1,
excluded_files=None,
ignore_hidden=False,
followlinks=False,
excluded_extensions=None,
include_paths=False
):
if not excluded_files:
excluded_files = []
if not excluded_extensions:
excluded_extensions = []
if not os.path.isdir(dirname):
raise TypeError("{} is not a directory.".format(dirname))
hashvalues = []
for root, dirs, files in os.walk(dirname, topdown=True, followlinks=followlinks):
if ignore_hidden and re.search(r"/\.", root):
continue
dirs.sort()
files.sort()
for fname in files:
if ignore_hidden and fname.startswith("."):
continue
if fname.split(".")[-1:][0] in excluded_extensions:
continue
if fname in excluded_files:
continue
hashvalues.append(_filehash(os.path.join(root, fname), hash_func))
if include_paths:
hasher = hash_func()
# get the resulting relative path into array of elements
path_list = os.path.relpath(os.path.join(root, fname)).split(os.sep)
# compute the hash on joined list, removes all os specific separators
hasher.update(''.join(path_list).encode('utf-8'))
hashvalues.append(hasher.hexdigest())
return _reduce_hash(hashvalues, hash_func)
def _filehash(filepath, hashfunc):
hasher = hashfunc()
blocksize = 64 * 1024
if not os.path.exists(filepath):
return hasher.hexdigest()
with open(filepath, "rb") as fp:
while True:
data = fp.read(blocksize)
if not data:
break
hasher.update(data)
return hasher.hexdigest()
def _reduce_hash(hashlist, hashfunc):
hasher = hashfunc()
for hashvalue in sorted(hashlist):
hasher.update(hashvalue.encode("utf-8"))
return hasher.hexdigest()

View File

@ -1,6 +1,7 @@
import glob
import os
import platform
import re
import urllib.request
import shutil
import subprocess
@ -8,6 +9,7 @@ from zipfile import ZipFile
from . import checksum
from .bindgen import bindgen
from .checksum import dirsum
from .gles_gen import gles_gen
from .log import *
from .utils import pushd, removeall, yeetdir, yeetfile
@ -15,7 +17,7 @@ from .embed_text_files import *
from .version import check_if_source, is_orca_source, orca_version
ANGLE_VERSION = "2023-07-05"
MAC_SDK_DIR = "/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk"
def attach_dev_commands(subparsers):
dev_cmd = subparsers.add_parser("dev", help="Commands for building Orca itself. Must be run from within an Orca source checkout.")
@ -65,6 +67,21 @@ def build_runtime(args):
build_wasm3(args.release)
build_orca(args.release)
with open("build/orcaruntime.sum", "w") as f:
f.write(runtime_checksum())
def runtime_checksum_last():
try:
with open("build/orcaruntime.sum", "r") as f:
return f.read()
except FileNotFoundError:
return None
def runtime_checksum():
return dirsum("src")
def clean(args):
yeetdir("build")
@ -151,12 +168,10 @@ def build_platform_layer_lib_win(release):
], check=True)
def build_platform_layer_lib_mac(release):
sdk_dir = "/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk"
flags = ["-mmacos-version-min=10.15.4", "-maes"]
flags = ["-mmacos-version-min=10.15.4"]
cflags = ["-std=c11"]
debug_flags = ["-O3"] if release else ["-g", "-DOC_DEBUG", "-DOC_LOG_COMPILE_DEBUG"]
ldflags = [f"-L{sdk_dir}/usr/lib", f"-F{sdk_dir}/System/Library/Frameworks/"]
ldflags = [f"-L{MAC_SDK_DIR}/usr/lib", f"-F{MAC_SDK_DIR}/System/Library/Frameworks/"]
includes = ["-Isrc", "-Isrc/util", "-Isrc/platform", "-Isrc/ext", "-Isrc/ext/angle/include"]
# compile metal shader
@ -263,6 +278,7 @@ def build_wasm3_lib_mac(release):
"-foptimize-sibling-calls",
"-Wno-extern-initializer",
"-Dd_m3VerboseErrorMessages",
"-mmacos-version-min=10.15.4"
]
for f in glob.iglob("src/ext/wasm3/source/*.c"):
@ -272,7 +288,7 @@ def build_wasm3_lib_mac(release):
"-o", f"build/obj/{name}",
f,
], check=True)
subprocess.run(["ar", "-rcs", "build/lib/libwasm3.a", *glob.glob("build/obj/*.o")], check=True)
subprocess.run(["libtool", "-static", "-o", "build/lib/libwasm3.a", "-no_warning_for_no_symbols", *glob.glob("build/obj/*.o")], check=True)
subprocess.run(["rm", "-rf", "build/obj"], check=True)
@ -331,9 +347,7 @@ def build_orca_mac(release):
debug_flags = ["-O2"] if release else ["-g", "-DOC_DEBUG -DOC_LOG_COMPILE_DEBUG"]
flags = [
*debug_flags,
"-mmacos-version-min=10.15.4",
"-maes",
]
"-mmacos-version-min=10.15.4"]
gen_all_bindings()
@ -390,28 +404,61 @@ def gen_all_bindings():
def ensure_programs():
if platform.system() == "Windows":
MSVC_MAJOR, MSVC_MINOR = 19, 35
try:
subprocess.run(["cl"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
cl_only = subprocess.run(["cl"], capture_output=True, text=True)
desc = cl_only.stderr.splitlines()[0]
detect = subprocess.run(["cl", "/EP", "scripts\\msvc_version.txt"], capture_output=True, text=True)
parts = [x for x in detect.stdout.splitlines() if x]
version, arch = int(parts[0]), parts[1]
major, minor = int(version / 100), version % 100
if arch != "x64":
msg = log_error("MSVC is not running in 64-bit mode. Make sure you are running in")
msg.more("an x64 Visual Studio command prompt, such as the \"x64 Native Tools")
msg.more("Command Prompt\" from your Start Menu.")
msg.more()
msg.more("MSVC reported itself as:")
msg.more(desc)
exit(1)
if major < MSVC_MAJOR or minor < MSVC_MINOR:
msg = log_error(f"Your version of MSVC is too old. You have version {major}.{minor},")
msg.more(f"but version {MSVC_MAJOR}.{MSVC_MINOR} or greater is required.")
msg.more()
msg.more("MSVC reported itself as:")
msg.more(desc)
msg.more()
msg.more("Please update Visual Studio to the latest version and try again.")
exit(1)
except FileNotFoundError:
msg = log_error("MSVC was not found on your system.")
msg.more("If you have already installed Visual Studio, make sure you are running in a")
msg.more("Visual Studio command prompt or you have run vcvarsall.bat. Otherwise, download")
msg.more("and install Visual Studio: https://visualstudio.microsoft.com/")
msg.more("If you have already installed Visual Studio, make sure you are running in an")
msg.more("x64 Visual Studio command prompt, such as the \"x64 Native Tools Command")
msg.more("Prompt\" from your Start Menu. Otherwise, download and install Visual Studio,")
msg.more("and ensure that your installation includes \"Desktop development with C++\"")
msg.more("and \"C++ Clang Compiler\": https://visualstudio.microsoft.com/")
exit(1)
try:
subprocess.run(["clang", "-v"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
except FileNotFoundError:
msg = log_error("clang was not found on your system.")
if platform.system() == "Windows":
msg.more("We recommend installing clang via the Visual Studio installer.")
elif platform.system() == "Darwin":
if platform.system() == "Darwin":
try:
subprocess.run(["clang", "-v"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
except FileNotFoundError:
msg = log_error("clang was not found on your system.")
msg.more("Run the following to install it:")
msg.more()
msg.more(" brew install llvm")
msg.more()
exit(1)
# TODO(ben): Check for xcode command line tools
exit(1)
if not os.path.exists(MAC_SDK_DIR):
msg = log_error("The Xcode command-line tools are not installed.")
msg.more("Run the following to install them:")
msg.more()
msg.more(" xcode-select --install")
msg.more()
exit(1)
def ensure_angle():
@ -501,6 +548,20 @@ def install_dir():
def install(args):
if runtime_checksum_last() is None:
print("You must build the Orca runtime before you can install it to your")
print("system. Please run the following command first:")
print()
print("orca dev build-runtime")
exit(1)
if runtime_checksum() != runtime_checksum_last():
print("Your build of the Orca runtime is out of date. We recommend that you")
print("rebuild the runtime first with `orca dev build-runtime`.")
if not prompt("Do you wish to install the runtime anyway?"):
return
print()
dest = install_dir()
bin_dir = os.path.join(dest, "bin")
src_dir = os.path.join(dest, "src")
@ -558,8 +619,13 @@ def install(args):
print()
print("The tools will need to be on your PATH in order to actually use them.")
if prompt("Would you like to automatically add Orca to your PATH?"):
subprocess.run(["powershell", "scripts\\updatepath.ps1", bin_dir], check=True)
print("Orca has been added to your PATH. Restart any open terminals to use it.")
try:
subprocess.run(["powershell", "-ExecutionPolicy", "Bypass", "scripts\\updatepath.ps1", f'"{bin_dir}"'], check=True)
print("Orca has been added to your PATH. Restart any open terminals to use it.")
except subprocess.CalledProcessError:
msg = log_warning(f"Failed to automatically add Orca to your PATH.")
msg.more("Please manually add the following directory to your PATH:")
msg.more(bin_dir)
else:
print("No worries. You can manually add Orca to your PATH in the Windows settings")
print("by searching for \"environment variables\".")
@ -600,7 +666,12 @@ def uninstall(args):
print("Orca has been uninstalled from your system.")
print()
if prompt("Would you like to automatically remove Orca from your PATH?"):
subprocess.run(["powershell", "scripts\\updatepath.ps1", bin_dir, "-remove"], check=True)
print("Orca has been removed from your PATH.")
try:
subprocess.run(["powershell", "-ExecutionPolicy", "Bypass", "scripts\\updatepath.ps1", f'"{bin_dir}"', "-remove"], check=True)
print("Orca has been removed from your PATH.")
except subprocess.CalledProcessError:
msg = log_warning(f"Failed to automatically remove Orca from your PATH.")
msg.more("Please manually remove the following directory from your PATH:")
msg.more(bin_dir)
else:
print("Orca has been uninstalled from your system. You may wish to remove it from your PATH.")

9
scripts/msvc_version.txt Normal file
View File

@ -0,0 +1,9 @@
_MSC_VER
#if defined(__x86_64__) || defined(_M_X64)
x64
#elif defined(i386) || defined(__i386__) || defined(__i386) || defined(_M_IX86)
x86
#else
unknown
#endif

View File

@ -0,0 +1,61 @@
import platform
import re
import shutil
import subprocess
import textwrap
CLANG_MAJOR, CLANG_MINOR = 11, 0
def printw(str=""):
print(textwrap.fill(str))
def print_clang_install_info(upgrade):
if platform.system() == "Windows":
printw(f"Please install Clang {CLANG_MAJOR}.{CLANG_MINOR} or newer. We recommend installing Clang via the Visual Studio installer. In the installer, search for \"C++ Clang Compiler\".")
elif platform.system() == "Darwin":
printw(f"Please install Clang {CLANG_MAJOR}.{CLANG_MINOR} or newer. We recommend installing Clang via Homebrew (https://brew.sh/):")
printw()
if upgrade:
printw(" brew upgrade llvm")
else:
printw(" brew install llvm")
printw()
else:
printw(f"Please install Clang {CLANG_MAJOR}.{CLANG_MINOR} or newer.")
try:
out = subprocess.run(["clang", "--version"], capture_output=True, text=True, check=True)
m = re.search(r"clang version (\d+)\.(\d+)\.(\d+)", out.stdout)
major, minor, patch = int(m.group(1)), int(m.group(2)), int(m.group(3))
if major < CLANG_MAJOR or minor < CLANG_MINOR:
printw(f"ERROR: Your version of Clang is too old. You have version {major}.{minor}.{patch}, but version {CLANG_MAJOR}.{CLANG_MINOR} or greater is required.")
printw()
printw("This script is currently running the clang located at:")
printw(shutil.which("clang"))
printw()
print_clang_install_info(True)
exit(1)
except FileNotFoundError:
printw("ERROR: clang is not installed. The Orca samples require Clang in order to compile C programs to WebAssembly.")
printw()
print_clang_install_info(False)
exit(1)
except subprocess.CalledProcessError:
printw("WARNING: Could not check Clang version. You may encounter build errors.")
try:
subprocess.run(["wasm-ld", "--version"], capture_output=True, check=True)
except FileNotFoundError:
printw("ERROR: wasm-ld was not found on your system. This is a component of Clang that is required in order to produce WebAssembly modules. This likely means that an old or otherwise incompatible version of Clang is being used, such as Apple's version of Clang.")
printw()
print_clang_install_info(False)
exit(1)
try:
subprocess.run(["orca", "version"], capture_output=True, shell=True, check=True)
except subprocess.CalledProcessError:
printw("ERROR: The Orca tooling has not been installed to your system or is not on your PATH. From the root of the Orca source code, please run the following commands:")
printw()
printw(" python orca dev build-runtime")
printw(" python orca dev install")
exit(1)

View File

@ -4,6 +4,7 @@ import os
import re
import shutil
from .checksum import dirsum
from .log import *
from .utils import yeetdir
from .version import src_dir, orca_version
@ -11,7 +12,7 @@ from .version import src_dir, orca_version
def attach_source_commands(subparsers):
source_cmd = subparsers.add_parser("source", help="Commands for helping compile the Orca source code into your project.")
source_sub = source_cmd.add_subparsers(title="commands")
source_sub = source_cmd.add_subparsers(required=True, title="commands")
cflags_cmd = source_sub.add_parser("cflags", help="Get help setting up a C or C++ compiler to compile the Orca source.")
cflags_cmd.add_argument("srcdir", nargs="?", default=src_dir(), help="the directory containing the Orca source code (defaults to system installation)")
@ -54,7 +55,7 @@ def vendor_file_path(vendor_dir):
def vendor_checksum(dir):
return dirhash(dir, excluded_extensions=["orcavendor"])
return dirsum(dir, excluded_extensions=["orcavendor"])
def cflags(args):
@ -104,86 +105,9 @@ def cflags(args):
print()
print("Complete clang example:")
print()
print(f"clang --target=wasm32 --no-standard-libraries -mbulk-memory -g -O2 -D__ORCA__ -Wl,--no-entry -Wl,--export-dynamic -isystem {sysinclude} -I {include} -I {extinclude} {orcac} {libcsource} your-main.c")
print(f"clang --target=wasm32 --no-standard-libraries -mbulk-memory -g -O2 -D__ORCA__ -Wl,--no-entry -Wl,--export-dynamic -isystem \"{sysinclude}\" -I \"{include}\" -I \"{extinclude}\" \"{orcac}\" \"{libcsource}\" your-main.c")
print()
if not path_contains(os.getcwd(), args.srcdir):
print("If these paths look crazy to you, consider vendoring the source code into your")
print("project using `orca source vendor`.")
print()
# -----------------------------------------------------------------------------
# Directory-hashing implementation pulled from the checksumdir package on pypi.
# Licensed under the MIT license.
# -----------------------------------------------------------------------------
def dirhash(
dirname,
hash_func=hashlib.sha1,
excluded_files=None,
ignore_hidden=False,
followlinks=False,
excluded_extensions=None,
include_paths=False
):
if not excluded_files:
excluded_files = []
if not excluded_extensions:
excluded_extensions = []
if not os.path.isdir(dirname):
raise TypeError("{} is not a directory.".format(dirname))
hashvalues = []
for root, dirs, files in os.walk(dirname, topdown=True, followlinks=followlinks):
if ignore_hidden and re.search(r"/\.", root):
continue
dirs.sort()
files.sort()
for fname in files:
if ignore_hidden and fname.startswith("."):
continue
if fname.split(".")[-1:][0] in excluded_extensions:
continue
if fname in excluded_files:
continue
hashvalues.append(_filehash(os.path.join(root, fname), hash_func))
if include_paths:
hasher = hash_func()
# get the resulting relative path into array of elements
path_list = os.path.relpath(os.path.join(root, fname)).split(os.sep)
# compute the hash on joined list, removes all os specific separators
hasher.update(''.join(path_list).encode('utf-8'))
hashvalues.append(hasher.hexdigest())
return _reduce_hash(hashvalues, hash_func)
def _filehash(filepath, hashfunc):
hasher = hashfunc()
blocksize = 64 * 1024
if not os.path.exists(filepath):
return hasher.hexdigest()
with open(filepath, "rb") as fp:
while True:
data = fp.read(blocksize)
if not data:
break
hasher.update(data)
return hasher.hexdigest()
def _reduce_hash(hashlist, hashfunc):
hasher = hashfunc()
for hashvalue in sorted(hashlist):
hasher.update(hashvalue.encode("utf-8"))
return hasher.hexdigest()

View File

@ -188,7 +188,7 @@ oc_key_code oc_scancode_to_keycode(oc_scan_code scanCode)
return (oc_appData.keyMap[scanCode]);
}
#define OC_DEFAULT_KEYMAP_ENTRY(sc, sv, ...) [(int) sc] = (oc_key_code)sc,
#define OC_DEFAULT_KEYMAP_ENTRY(sc, sv, kc, ...) [(int) sc] = OC_VA_NOPT(sv, ##__VA_ARGS__) __VA_ARGS__,
oc_key_code oc_defaultKeyMap[OC_SCANCODE_COUNT] = {
OC_KEY_TABLE(OC_DEFAULT_KEYMAP_ENTRY)

View File

@ -121,7 +121,7 @@ typedef int8_t i8;
# if defined (M3_COMPILER_MSVC)
# define vectorcall // For MSVC, better not to specify any call convention
# elif defined(__x86_64__)
# define vectorcall __attribute__((aligned(32)))
# define vectorcall
//# elif defined(__riscv) && (__riscv_xlen == 64)
//# define vectorcall __attribute__((aligned(16)))
# elif defined(__MINGW32__)

View File

@ -110,8 +110,8 @@ ORCA_API void oc_surface_set_hidden(oc_surface surface, bool hidden);
#else
ORCA_API oc_surface oc_surface_canvas(); //DOC: creates a surface for use with the canvas API
ORCA_API oc_surface oc_surface_gles(); //DOC: create a surface for use with GLES API
ORCA_API oc_surface oc_surface_canvas(void); //DOC: creates a surface for use with the canvas API
ORCA_API oc_surface oc_surface_gles(void); //DOC: create a surface for use with GLES API
#endif
@ -281,8 +281,9 @@ typedef struct oc_image_region
} oc_image_region;
ORCA_API oc_image_region oc_image_atlas_alloc_from_rgba8(oc_rect_atlas* atlas, oc_image backingImage, u32 width, u32 height, u8* pixels);
ORCA_API oc_image_region oc_image_atlas_alloc_from_data(oc_rect_atlas* atlas, oc_image backingImage, oc_str8 data, bool flip);
ORCA_API oc_image_region oc_image_atlas_alloc_from_file(oc_rect_atlas* atlas, oc_image backingImage, oc_str8 path, bool flip);
ORCA_API oc_image_region oc_image_atlas_alloc_from_memory(oc_rect_atlas* atlas, oc_image backingImage, oc_str8 mem, bool flip);
ORCA_API oc_image_region oc_image_atlas_alloc_from_file(oc_rect_atlas* atlas, oc_image backingImage, oc_file file, bool flip);
ORCA_API oc_image_region oc_image_atlas_alloc_from_path(oc_rect_atlas* atlas, oc_image backingImage, oc_str8 path, bool flip);
ORCA_API void oc_image_atlas_recycle(oc_rect_atlas* atlas, oc_image_region imageRgn);
//------------------------------------------------------------------------------------------

View File

@ -1887,16 +1887,14 @@ oc_image_region oc_image_atlas_alloc_from_rgba8(oc_rect_atlas* atlas, oc_image b
return (imageRgn);
}
#if !OC_PLATFORM_ORCA
oc_image_region oc_image_atlas_alloc_from_data(oc_rect_atlas* atlas, oc_image backingImage, oc_str8 data, bool flip)
oc_image_region oc_image_atlas_alloc_from_memory(oc_rect_atlas* atlas, oc_image backingImage, oc_str8 mem, bool flip)
{
oc_image_region imageRgn = { 0 };
stbi_set_flip_vertically_on_load(flip ? 1 : 0);
int width, height, channels;
u8* pixels = stbi_load_from_memory((u8*)data.ptr, data.len, &width, &height, &channels, 4);
stbi_set_flip_vertically_on_load(flip ? 1 : 0);
u8* pixels = stbi_load_from_memory((u8*)mem.ptr, mem.len, &width, &height, &channels, 4);
if(pixels)
{
imageRgn = oc_image_atlas_alloc_from_rgba8(atlas, backingImage, width, height, pixels);
@ -1905,27 +1903,45 @@ oc_image_region oc_image_atlas_alloc_from_data(oc_rect_atlas* atlas, oc_image ba
return (imageRgn);
}
oc_image_region oc_image_atlas_alloc_from_file(oc_rect_atlas* atlas, oc_image backingImage, oc_str8 path, bool flip)
oc_image_region oc_image_atlas_alloc_from_file(oc_rect_atlas* atlas, oc_image backingImage, oc_file file, bool flip)
{
oc_image_region imageRgn = { 0 };
stbi_set_flip_vertically_on_load(flip ? 1 : 0);
oc_arena_scope scratch = oc_scratch_begin();
const char* cpath = oc_str8_to_cstring(scratch.arena, path);
int width, height, channels;
u8* pixels = stbi_load(cpath, &width, &height, &channels, 4);
oc_scratch_end(scratch);
u64 size = oc_file_size(file);
char* buffer = oc_arena_push(scratch.arena, size);
u64 read = oc_file_read(file, size, buffer);
if(pixels)
if(read != size)
{
imageRgn = oc_image_atlas_alloc_from_rgba8(atlas, backingImage, width, height, pixels);
free(pixels);
oc_log_error("Couldn't read image data\n");
}
else
{
imageRgn = oc_image_atlas_alloc_from_memory(atlas, backingImage, oc_str8_from_buffer(size, buffer), flip);
}
oc_scratch_end(scratch);
return (imageRgn);
}
oc_image_region oc_image_atlas_alloc_from_path(oc_rect_atlas* atlas, oc_image backingImage, oc_str8 path, bool flip)
{
oc_image_region imageRgn = { 0 };
oc_file file = oc_file_open(path, OC_FILE_ACCESS_READ, OC_FILE_OPEN_NONE);
if(oc_file_last_error(file) != OC_IO_OK)
{
oc_log_error("Could not open file %*.s\n", oc_str8_ip(path));
}
else
{
imageRgn = oc_image_atlas_alloc_from_file(atlas, backingImage, file, flip);
}
oc_file_close(file);
return (imageRgn);
}
#endif // !OC_PLATFORM_ORCA
void oc_image_atlas_recycle(oc_rect_atlas* atlas, oc_image_region imageRgn)
{

View File

@ -15,9 +15,13 @@
#include "mtl_renderer.h"
const int OC_MTL_INPUT_BUFFERS_COUNT = 3,
OC_MTL_TILE_SIZE = 16,
OC_MTL_MSAA_COUNT = 8;
enum
{
OC_MTL_INPUT_BUFFERS_COUNT = 3,
OC_MTL_TILE_SIZE = 16,
OC_MTL_MSAA_COUNT = 8,
OC_MTL_OFFSET_CURVE_SAMPLE_COUNT = 5,
};
typedef struct oc_mtl_canvas_backend
{
@ -511,8 +515,7 @@ void oc_mtl_render_stroke_quadratic(oc_mtl_canvas_backend* backend, oc_vec2* p)
}
else
{
const int CHECK_SAMPLE_COUNT = 5;
f32 checkSamples[CHECK_SAMPLE_COUNT] = { 1. / 6, 2. / 6, 3. / 6, 4. / 6, 5. / 6 };
f32 checkSamples[OC_MTL_OFFSET_CURVE_SAMPLE_COUNT] = { 1. / 6, 2. / 6, 3. / 6, 4. / 6, 5. / 6 };
f32 d2LowBound = oc_square(0.5 * width - tolerance);
f32 d2HighBound = oc_square(0.5 * width + tolerance);
@ -520,7 +523,7 @@ void oc_mtl_render_stroke_quadratic(oc_mtl_canvas_backend* backend, oc_vec2* p)
f32 maxOvershoot = 0;
f32 maxOvershootParameter = 0;
for(int i = 0; i < CHECK_SAMPLE_COUNT; i++)
for(int i = 0; i < OC_MTL_OFFSET_CURVE_SAMPLE_COUNT; i++)
{
f32 t = checkSamples[i];
@ -613,8 +616,7 @@ void oc_mtl_render_stroke_cubic(oc_mtl_canvas_backend* backend, oc_vec2* p)
}
else
{
const int CHECK_SAMPLE_COUNT = 5;
f32 checkSamples[CHECK_SAMPLE_COUNT] = { 1. / 6, 2. / 6, 3. / 6, 4. / 6, 5. / 6 };
f32 checkSamples[OC_MTL_OFFSET_CURVE_SAMPLE_COUNT] = { 1. / 6, 2. / 6, 3. / 6, 4. / 6, 5. / 6 };
f32 d2LowBound = oc_square(0.5 * width - tolerance);
f32 d2HighBound = oc_square(0.5 * width + tolerance);
@ -622,7 +624,7 @@ void oc_mtl_render_stroke_cubic(oc_mtl_canvas_backend* backend, oc_vec2* p)
f32 maxOvershoot = 0;
f32 maxOvershootParameter = 0;
for(int i = 0; i < CHECK_SAMPLE_COUNT; i++)
for(int i = 0; i < OC_MTL_OFFSET_CURVE_SAMPLE_COUNT; i++)
{
f32 t = checkSamples[i];

View File

@ -67,7 +67,7 @@ void oc_vsync_init(void)
adapter = adapterFallback;
if(adapter)
{
oc_log_info("Couldn't find a dedicated hardware DXGI adapater, using software fallback.");
oc_log_info("Couldn't find a dedicated hardware DXGI adapater, using software fallback.\n");
}
}
@ -80,7 +80,7 @@ void oc_vsync_init(void)
}
else
{
oc_log_info("Couldn't find any DXGI adapters - vsync will be unavailable.");
oc_log_info("Couldn't find any DXGI adapters - vsync will be unavailable.\n");
IDXGIFactory_Release(factory);
}
}
@ -92,14 +92,14 @@ void oc_vsync_wait(oc_window window)
oc_window_data* windowData = oc_window_ptr_from_handle(window);
if(!windowData)
{
oc_log_error("Failed to get window ptr - assuming window was closed.");
oc_log_error("Failed to get window ptr - assuming window was closed.\n");
return;
}
RECT windowRect = { 0 };
if(GetWindowRect(windowData->win32.hWnd, &windowRect) == FALSE)
{
oc_log_error("Failed to get window rect with error: %d.", GetLastError());
oc_log_error("Failed to get window rect with error: %d.\n", GetLastError());
return;
}
@ -127,7 +127,7 @@ void oc_vsync_wait(oc_window window)
}
else
{
oc_log_error("Failed to get IDXGIOutput desc with error: %d", hr);
oc_log_error("Failed to get IDXGIOutput desc with error: %d\n", hr);
}
if(selectedOutput != output)
@ -143,14 +143,15 @@ void oc_vsync_wait(oc_window window)
if(FAILED(hr))
{
// TODO(reuben) - fall back to software timer
oc_log_warning("Failed to wait for vblank with error: %d", hr);
oc_log_warning("Failed to wait for vblank with error: %d\n", hr);
}
IDXGIOutput_Release(selectedOutput);
}
else
else if(output)
{
oc_log_warning("No outputs found. Were all monitors unplugged?");
// just use the last output found as a fallback - the window may be minimized or not otherwise visible on any monitor
IDXGIOutput_WaitForVBlank(output);
}
}
}

View File

@ -2,13 +2,12 @@
#define _MATH_H
#ifdef __cplusplus
extern "C"
{
extern "C" {
#endif
// NOTE(orca): not doing anything fancy for float_t and double_t
typedef float float_t;
typedef double double_t;
// NOTE(orca): not doing anything fancy for float_t and double_t
typedef float float_t;
typedef double double_t;
#define NAN __builtin_nanf("")
#define INFINITY __builtin_inff()
@ -19,33 +18,33 @@ extern "C"
#define FP_SUBNORMAL 3
#define FP_NORMAL 4
int __fpclassify(double);
int __fpclassifyf(float);
int __fpclassifyl(long double);
int __fpclassify(double);
int __fpclassifyf(float);
int __fpclassifyl(long double);
static __inline unsigned __FLOAT_BITS(float __f)
static __inline unsigned __FLOAT_BITS(float __f)
{
union
{
union
{
float __f;
unsigned __i;
} __u;
float __f;
unsigned __i;
} __u;
__u.__f = __f;
return __u.__i;
}
__u.__f = __f;
return __u.__i;
}
static __inline unsigned long long __DOUBLE_BITS(double __f)
static __inline unsigned long long __DOUBLE_BITS(double __f)
{
union
{
union
{
double __f;
unsigned long long __i;
} __u;
double __f;
unsigned long long __i;
} __u;
__u.__f = __f;
return __u.__i;
}
__u.__f = __f;
return __u.__i;
}
#define fpclassify(x) ( \
sizeof(x) == sizeof(float) ? __fpclassifyf(x) : sizeof(x) == sizeof(double) ? __fpclassify(x) \
@ -59,29 +58,53 @@ extern "C"
sizeof(x) == sizeof(float) ? (__FLOAT_BITS(x) & 0x7fffffff) > 0x7f800000 : sizeof(x) == sizeof(double) ? (__DOUBLE_BITS(x) & -1ULL >> 1) > 0x7ffULL << 52 \
: __fpclassifyl(x) == FP_NAN)
double acos(double);
double fabs(double);
float fabsf(float);
double ceil(double);
double acos(double);
float acosf(float);
double cos(double);
float cosf(float);
double cbrt(double);
float cbrtf(float);
double fabs(double);
float fabsf(float);
double ceil(double);
double floor(double);
double cos(double);
float cosf(float);
double fmod(double, double);
double floor(double);
double pow(double, double);
double fmod(double, double);
double scalbn(double, int);
double log(double);
float logf(float);
double log2(double);
float log2f(float);
double sin(double);
float sinf(float);
double pow(double, double);
float powf(float, float);
double sqrt(double);
float sqrtf(float);
double exp(double);
float expf(float);
double scalbn(double, int);
double sin(double);
float sinf(float);
double asin(double);
float asinf(float);
double tan(double);
float tanf(float);
double atan(double);
float atanf(float);
double atan2(double, double);
float atan2f(float, float);
double sqrt(double);
float sqrtf(float);
#define M_E 2.7182818284590452354 /* e */
#define M_LOG2E 1.4426950408889634074 /* log_2 e */
@ -97,6 +120,11 @@ extern "C"
#define M_SQRT2 1.41421356237309504880 /* sqrt(2) */
#define M_SQRT1_2 0.70710678118654752440 /* 1/sqrt(2) */
//NOTE(orca) - implementation details
typedef unsigned uint32_t;
double __math_divzero(uint32_t sign);
float __math_divzerof(uint32_t sign);
#ifdef __cplusplus
}
#endif

View File

@ -1,14 +1,20 @@
#ifndef _STDLIB_H
#define _STDLIB_H
#include <stddef.h>
#ifdef __cplusplus
extern "C"
{
extern "C" {
#endif
#define abort(...) OC_ABORT(__VA_ARGS__)
int abs(int);
int abs(int);
void* malloc(size_t);
void* realloc(void*, size_t);
void* calloc(size_t count, size_t size);
void free(void*);
#ifdef __cplusplus
}

View File

@ -1,5 +1,9 @@
#include "stb/stb_sprintf.h"
#ifdef __cplusplus
extern "C" {
#endif
void* memset(void* b, int c, size_t n);
void* memcpy(void* __restrict dst, const void* __restrict src, size_t n);
void* memmove(void* dst, const void* src, size_t n);
@ -12,3 +16,7 @@ char* strcpy(char* __restrict s1, const char* __restrict s2);
#define snprintf stbsp_snprintf
#define vsnprintf stbsp_vsnprintf
#ifdef __cplusplus
} // extern "C"
#endif

View File

@ -0,0 +1,3 @@
---
DisableFormat: true
SortIncludes: Never

View File

@ -0,0 +1,7 @@
#include "libm.h"
double __math_divzero(uint32_t sign)
{
// NOTE(orca): no fp barriers
return (sign ? -1.0 : 1.0) / 0.0;
}

View File

@ -0,0 +1,7 @@
#include "libm.h"
float __math_divzerof(uint32_t sign)
{
// NOTE(orca): no fp barriers
return (sign ? -1.0f : 1.0f) / 0.0f;
}

View File

@ -0,0 +1,6 @@
#include "libm.h"
float __math_oflowf(uint32_t sign)
{
return __math_xflowf(sign, 0x1p97f);
}

View File

@ -0,0 +1,6 @@
#include "libm.h"
float __math_uflowf(uint32_t sign)
{
return __math_xflowf(sign, 0x1p-95f);
}

View File

@ -0,0 +1,8 @@
#include "libm.h"
float __math_xflowf(uint32_t sign, float y)
{
// NOTE(orca): no fp barriers
// return eval_as_double(fp_barrier(sign ? -y : y) * y);
return eval_as_float((sign ? -y : y) * y);
}

110
src/libc-shim/src/__tan.c Normal file
View File

@ -0,0 +1,110 @@
/* origin: FreeBSD /usr/src/lib/msun/src/k_tan.c */
/*
* ====================================================
* Copyright 2004 Sun Microsystems, Inc. All Rights Reserved.
*
* Permission to use, copy, modify, and distribute this
* software is freely granted, provided that this notice
* is preserved.
* ====================================================
*/
/* __tan( x, y, k )
* kernel tan function on ~[-pi/4, pi/4] (except on -0), pi/4 ~ 0.7854
* Input x is assumed to be bounded by ~pi/4 in magnitude.
* Input y is the tail of x.
* Input odd indicates whether tan (if odd = 0) or -1/tan (if odd = 1) is returned.
*
* Algorithm
* 1. Since tan(-x) = -tan(x), we need only to consider positive x.
* 2. Callers must return tan(-0) = -0 without calling here since our
* odd polynomial is not evaluated in a way that preserves -0.
* Callers may do the optimization tan(x) ~ x for tiny x.
* 3. tan(x) is approximated by a odd polynomial of degree 27 on
* [0,0.67434]
* 3 27
* tan(x) ~ x + T1*x + ... + T13*x
* where
*
* |tan(x) 2 4 26 | -59.2
* |----- - (1+T1*x +T2*x +.... +T13*x )| <= 2
* | x |
*
* Note: tan(x+y) = tan(x) + tan'(x)*y
* ~ tan(x) + (1+x*x)*y
* Therefore, for better accuracy in computing tan(x+y), let
* 3 2 2 2 2
* r = x *(T2+x *(T3+x *(...+x *(T12+x *T13))))
* then
* 3 2
* tan(x+y) = x + (T1*x + (x *(r+y)+y))
*
* 4. For x in [0.67434,pi/4], let y = pi/4 - x, then
* tan(x) = tan(pi/4-y) = (1-tan(y))/(1+tan(y))
* = 1 - 2*(tan(y) - (tan(y)^2)/(1+tan(y)))
*/
#include "libm.h"
static const double T[] = {
3.33333333333334091986e-01, /* 3FD55555, 55555563 */
1.33333333333201242699e-01, /* 3FC11111, 1110FE7A */
5.39682539762260521377e-02, /* 3FABA1BA, 1BB341FE */
2.18694882948595424599e-02, /* 3F9664F4, 8406D637 */
8.86323982359930005737e-03, /* 3F8226E3, E96E8493 */
3.59207910759131235356e-03, /* 3F6D6D22, C9560328 */
1.45620945432529025516e-03, /* 3F57DBC8, FEE08315 */
5.88041240820264096874e-04, /* 3F4344D8, F2F26501 */
2.46463134818469906812e-04, /* 3F3026F7, 1A8D1068 */
7.81794442939557092300e-05, /* 3F147E88, A03792A6 */
7.14072491382608190305e-05, /* 3F12B80F, 32F0A7E9 */
-1.85586374855275456654e-05, /* BEF375CB, DB605373 */
2.59073051863633712884e-05, /* 3EFB2A70, 74BF7AD4 */
},
pio4 = 7.85398163397448278999e-01, /* 3FE921FB, 54442D18 */
pio4lo = 3.06161699786838301793e-17; /* 3C81A626, 33145C07 */
double __tan(double x, double y, int odd)
{
double_t z, r, v, w, s, a;
double w0, a0;
uint32_t hx;
int big, sign;
GET_HIGH_WORD(hx,x);
big = (hx&0x7fffffff) >= 0x3FE59428; /* |x| >= 0.6744 */
if (big) {
sign = hx>>31;
if (sign) {
x = -x;
y = -y;
}
x = (pio4 - x) + (pio4lo - y);
y = 0.0;
}
z = x * x;
w = z * z;
/*
* Break x^5*(T[1]+x^2*T[2]+...) into
* x^5(T[1]+x^4*T[3]+...+x^20*T[11]) +
* x^5(x^2*(T[2]+x^4*T[4]+...+x^22*[T12]))
*/
r = T[1] + w*(T[3] + w*(T[5] + w*(T[7] + w*(T[9] + w*T[11]))));
v = z*(T[2] + w*(T[4] + w*(T[6] + w*(T[8] + w*(T[10] + w*T[12])))));
s = z * x;
r = y + z*(s*(r + v) + y) + s*T[0];
w = x + r;
if (big) {
s = 1 - 2*odd;
v = s - 2.0 * (x + (r - w*w/(w + s)));
return sign ? -v : v;
}
if (!odd)
return w;
/* -1.0/(x+r) has up to 2ulp error, so compute it accurately */
w0 = w;
SET_LOW_WORD(w0, 0);
v = r - (w0 - x); /* w0+v = r+x */
a0 = a = -1.0 / w;
SET_LOW_WORD(a0, 0);
return a0 + a*(1.0 + a0*w0 + a0*v);
}

View File

@ -0,0 +1,54 @@
/* origin: FreeBSD /usr/src/lib/msun/src/k_tanf.c */
/*
* Conversion to float by Ian Lance Taylor, Cygnus Support, ian@cygnus.com.
* Optimized by Bruce D. Evans.
*/
/*
* ====================================================
* Copyright 2004 Sun Microsystems, Inc. All Rights Reserved.
*
* Permission to use, copy, modify, and distribute this
* software is freely granted, provided that this notice
* is preserved.
* ====================================================
*/
#include "libm.h"
/* |tan(x)/x - t(x)| < 2**-25.5 (~[-2e-08, 2e-08]). */
static const double T[] = {
0x15554d3418c99f.0p-54, /* 0.333331395030791399758 */
0x1112fd38999f72.0p-55, /* 0.133392002712976742718 */
0x1b54c91d865afe.0p-57, /* 0.0533812378445670393523 */
0x191df3908c33ce.0p-58, /* 0.0245283181166547278873 */
0x185dadfcecf44e.0p-61, /* 0.00297435743359967304927 */
0x1362b9bf971bcd.0p-59, /* 0.00946564784943673166728 */
};
float __tandf(double x, int odd)
{
double_t z,r,w,s,t,u;
z = x*x;
/*
* Split up the polynomial into small independent terms to give
* opportunities for parallel evaluation. The chosen splitting is
* micro-optimized for Athlons (XP, X64). It costs 2 multiplications
* relative to Horner's method on sequential machines.
*
* We add the small terms from lowest degree up for efficiency on
* non-sequential machines (the lowest degree terms tend to be ready
* earlier). Apart from this, we don't care about order of
* operations, and don't need to to care since we have precision to
* spare. However, the chosen splitting is good for accuracy too,
* and would give results as accurate as Horner's method if the
* small terms were added from highest degree down.
*/
r = T[4] + z*T[5];
t = T[2] + z*T[3];
w = z*z;
s = z*x;
u = T[0] + z*T[1];
r = (x + s*u) + (s*w)*(t + w*r);
return odd ? -1.0/r : r;
}

71
src/libc-shim/src/acosf.c Normal file
View File

@ -0,0 +1,71 @@
/* origin: FreeBSD /usr/src/lib/msun/src/e_acosf.c */
/*
* Conversion to float by Ian Lance Taylor, Cygnus Support, ian@cygnus.com.
*/
/*
* ====================================================
* Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
*
* Developed at SunPro, a Sun Microsystems, Inc. business.
* Permission to use, copy, modify, and distribute this
* software is freely granted, provided that this notice
* is preserved.
* ====================================================
*/
#include "libm.h"
static const float
pio2_hi = 1.5707962513e+00, /* 0x3fc90fda */
pio2_lo = 7.5497894159e-08, /* 0x33a22168 */
pS0 = 1.6666586697e-01,
pS1 = -4.2743422091e-02,
pS2 = -8.6563630030e-03,
qS1 = -7.0662963390e-01;
static float R(float z)
{
float_t p, q;
p = z*(pS0+z*(pS1+z*pS2));
q = 1.0f+z*qS1;
return p/q;
}
float acosf(float x)
{
float z,w,s,c,df;
uint32_t hx,ix;
GET_FLOAT_WORD(hx, x);
ix = hx & 0x7fffffff;
/* |x| >= 1 or nan */
if (ix >= 0x3f800000) {
if (ix == 0x3f800000) {
if (hx >> 31)
return 2*pio2_hi + 0x1p-120f;
return 0;
}
return 0/(x-x);
}
/* |x| < 0.5 */
if (ix < 0x3f000000) {
if (ix <= 0x32800000) /* |x| < 2**-26 */
return pio2_hi + 0x1p-120f;
return pio2_hi - (x - (pio2_lo-x*R(x*x)));
}
/* x < -0.5 */
if (hx >> 31) {
z = (1+x)*0.5f;
s = sqrtf(z);
w = R(z)*s-pio2_lo;
return 2*(pio2_hi - (s+w));
}
/* x > 0.5 */
z = (1-x)*0.5f;
s = sqrtf(z);
GET_FLOAT_WORD(hx,s);
SET_FLOAT_WORD(df,hx&0xfffff000);
c = (z-df*df)/(s+df);
w = R(z)*s+c;
return 2*(df+w);
}

107
src/libc-shim/src/asin.c Normal file
View File

@ -0,0 +1,107 @@
/* origin: FreeBSD /usr/src/lib/msun/src/e_asin.c */
/*
* ====================================================
* Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
*
* Developed at SunSoft, a Sun Microsystems, Inc. business.
* Permission to use, copy, modify, and distribute this
* software is freely granted, provided that this notice
* is preserved.
* ====================================================
*/
/* asin(x)
* Method :
* Since asin(x) = x + x^3/6 + x^5*3/40 + x^7*15/336 + ...
* we approximate asin(x) on [0,0.5] by
* asin(x) = x + x*x^2*R(x^2)
* where
* R(x^2) is a rational approximation of (asin(x)-x)/x^3
* and its remez error is bounded by
* |(asin(x)-x)/x^3 - R(x^2)| < 2^(-58.75)
*
* For x in [0.5,1]
* asin(x) = pi/2-2*asin(sqrt((1-x)/2))
* Let y = (1-x), z = y/2, s := sqrt(z), and pio2_hi+pio2_lo=pi/2;
* then for x>0.98
* asin(x) = pi/2 - 2*(s+s*z*R(z))
* = pio2_hi - (2*(s+s*z*R(z)) - pio2_lo)
* For x<=0.98, let pio4_hi = pio2_hi/2, then
* f = hi part of s;
* c = sqrt(z) - f = (z-f*f)/(s+f) ...f+c=sqrt(z)
* and
* asin(x) = pi/2 - 2*(s+s*z*R(z))
* = pio4_hi+(pio4-2s)-(2s*z*R(z)-pio2_lo)
* = pio4_hi+(pio4-2f)-(2s*z*R(z)-(pio2_lo+2c))
*
* Special cases:
* if x is NaN, return x itself;
* if |x|>1, return NaN with invalid signal.
*
*/
#include "libm.h"
static const double
pio2_hi = 1.57079632679489655800e+00, /* 0x3FF921FB, 0x54442D18 */
pio2_lo = 6.12323399573676603587e-17, /* 0x3C91A626, 0x33145C07 */
/* coefficients for R(x^2) */
pS0 = 1.66666666666666657415e-01, /* 0x3FC55555, 0x55555555 */
pS1 = -3.25565818622400915405e-01, /* 0xBFD4D612, 0x03EB6F7D */
pS2 = 2.01212532134862925881e-01, /* 0x3FC9C155, 0x0E884455 */
pS3 = -4.00555345006794114027e-02, /* 0xBFA48228, 0xB5688F3B */
pS4 = 7.91534994289814532176e-04, /* 0x3F49EFE0, 0x7501B288 */
pS5 = 3.47933107596021167570e-05, /* 0x3F023DE1, 0x0DFDF709 */
qS1 = -2.40339491173441421878e+00, /* 0xC0033A27, 0x1C8A2D4B */
qS2 = 2.02094576023350569471e+00, /* 0x40002AE5, 0x9C598AC8 */
qS3 = -6.88283971605453293030e-01, /* 0xBFE6066C, 0x1B8D0159 */
qS4 = 7.70381505559019352791e-02; /* 0x3FB3B8C5, 0xB12E9282 */
static double R(double z)
{
double_t p, q;
p = z*(pS0+z*(pS1+z*(pS2+z*(pS3+z*(pS4+z*pS5)))));
q = 1.0+z*(qS1+z*(qS2+z*(qS3+z*qS4)));
return p/q;
}
double asin(double x)
{
double z,r,s;
uint32_t hx,ix;
GET_HIGH_WORD(hx, x);
ix = hx & 0x7fffffff;
/* |x| >= 1 or nan */
if (ix >= 0x3ff00000) {
uint32_t lx;
GET_LOW_WORD(lx, x);
if ((ix-0x3ff00000 | lx) == 0)
/* asin(1) = +-pi/2 with inexact */
return x*pio2_hi + 0x1p-120f;
return 0/(x-x);
}
/* |x| < 0.5 */
if (ix < 0x3fe00000) {
/* if 0x1p-1022 <= |x| < 0x1p-26, avoid raising underflow */
if (ix < 0x3e500000 && ix >= 0x00100000)
return x;
return x + x*R(x*x);
}
/* 1 > |x| >= 0.5 */
z = (1 - fabs(x))*0.5;
s = sqrt(z);
r = R(z);
if (ix >= 0x3fef3333) { /* if |x| > 0.975 */
x = pio2_hi-(2*(s+s*r)-pio2_lo);
} else {
double f,c;
/* f+c = sqrt(z) */
f = s;
SET_LOW_WORD(f,0);
c = (z-f*f)/(s+f);
x = 0.5*pio2_hi - (2*s*r - (pio2_lo-2*c) - (0.5*pio2_hi-2*f));
}
if (hx >> 31)
return -x;
return x;
}

61
src/libc-shim/src/asinf.c Normal file
View File

@ -0,0 +1,61 @@
/* origin: FreeBSD /usr/src/lib/msun/src/e_asinf.c */
/*
* Conversion to float by Ian Lance Taylor, Cygnus Support, ian@cygnus.com.
*/
/*
* ====================================================
* Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
*
* Developed at SunPro, a Sun Microsystems, Inc. business.
* Permission to use, copy, modify, and distribute this
* software is freely granted, provided that this notice
* is preserved.
* ====================================================
*/
#include "libm.h"
static const double
pio2 = 1.570796326794896558e+00;
static const float
/* coefficients for R(x^2) */
pS0 = 1.6666586697e-01,
pS1 = -4.2743422091e-02,
pS2 = -8.6563630030e-03,
qS1 = -7.0662963390e-01;
static float R(float z)
{
float_t p, q;
p = z*(pS0+z*(pS1+z*pS2));
q = 1.0f+z*qS1;
return p/q;
}
float asinf(float x)
{
double s;
float z;
uint32_t hx,ix;
GET_FLOAT_WORD(hx, x);
ix = hx & 0x7fffffff;
if (ix >= 0x3f800000) { /* |x| >= 1 */
if (ix == 0x3f800000) /* |x| == 1 */
return x*pio2 + 0x1p-120f; /* asin(+-1) = +-pi/2 with inexact */
return 0/(x-x); /* asin(|x|>1) is NaN */
}
if (ix < 0x3f000000) { /* |x| < 0.5 */
/* if 0x1p-126 <= |x| < 0x1p-12, avoid raising underflow */
if (ix < 0x39800000 && ix >= 0x00800000)
return x;
return x + x*R(x*x);
}
/* 1 > |x| >= 0.5 */
z = (1 - fabsf(x))*0.5f;
s = sqrt(z);
x = pio2 - 2*(s+s*R(z));
if (hx >> 31)
return -x;
return x;
}

116
src/libc-shim/src/atan.c Normal file
View File

@ -0,0 +1,116 @@
/* origin: FreeBSD /usr/src/lib/msun/src/s_atan.c */
/*
* ====================================================
* Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
*
* Developed at SunPro, a Sun Microsystems, Inc. business.
* Permission to use, copy, modify, and distribute this
* software is freely granted, provided that this notice
* is preserved.
* ====================================================
*/
/* atan(x)
* Method
* 1. Reduce x to positive by atan(x) = -atan(-x).
* 2. According to the integer k=4t+0.25 chopped, t=x, the argument
* is further reduced to one of the following intervals and the
* arctangent of t is evaluated by the corresponding formula:
*
* [0,7/16] atan(x) = t-t^3*(a1+t^2*(a2+...(a10+t^2*a11)...)
* [7/16,11/16] atan(x) = atan(1/2) + atan( (t-0.5)/(1+t/2) )
* [11/16.19/16] atan(x) = atan( 1 ) + atan( (t-1)/(1+t) )
* [19/16,39/16] atan(x) = atan(3/2) + atan( (t-1.5)/(1+1.5t) )
* [39/16,INF] atan(x) = atan(INF) + atan( -1/t )
*
* Constants:
* The hexadecimal values are the intended ones for the following
* constants. The decimal values may be used, provided that the
* compiler will convert from decimal to binary accurately enough
* to produce the hexadecimal values shown.
*/
#include "libm.h"
static const double atanhi[] = {
4.63647609000806093515e-01, /* atan(0.5)hi 0x3FDDAC67, 0x0561BB4F */
7.85398163397448278999e-01, /* atan(1.0)hi 0x3FE921FB, 0x54442D18 */
9.82793723247329054082e-01, /* atan(1.5)hi 0x3FEF730B, 0xD281F69B */
1.57079632679489655800e+00, /* atan(inf)hi 0x3FF921FB, 0x54442D18 */
};
static const double atanlo[] = {
2.26987774529616870924e-17, /* atan(0.5)lo 0x3C7A2B7F, 0x222F65E2 */
3.06161699786838301793e-17, /* atan(1.0)lo 0x3C81A626, 0x33145C07 */
1.39033110312309984516e-17, /* atan(1.5)lo 0x3C700788, 0x7AF0CBBD */
6.12323399573676603587e-17, /* atan(inf)lo 0x3C91A626, 0x33145C07 */
};
static const double aT[] = {
3.33333333333329318027e-01, /* 0x3FD55555, 0x5555550D */
-1.99999999998764832476e-01, /* 0xBFC99999, 0x9998EBC4 */
1.42857142725034663711e-01, /* 0x3FC24924, 0x920083FF */
-1.11111104054623557880e-01, /* 0xBFBC71C6, 0xFE231671 */
9.09088713343650656196e-02, /* 0x3FB745CD, 0xC54C206E */
-7.69187620504482999495e-02, /* 0xBFB3B0F2, 0xAF749A6D */
6.66107313738753120669e-02, /* 0x3FB10D66, 0xA0D03D51 */
-5.83357013379057348645e-02, /* 0xBFADDE2D, 0x52DEFD9A */
4.97687799461593236017e-02, /* 0x3FA97B4B, 0x24760DEB */
-3.65315727442169155270e-02, /* 0xBFA2B444, 0x2C6A6C2F */
1.62858201153657823623e-02, /* 0x3F90AD3A, 0xE322DA11 */
};
double atan(double x)
{
double_t w,s1,s2,z;
uint32_t ix,sign;
int id;
GET_HIGH_WORD(ix, x);
sign = ix >> 31;
ix &= 0x7fffffff;
if (ix >= 0x44100000) { /* if |x| >= 2^66 */
if (isnan(x))
return x;
z = atanhi[3] + 0x1p-120f;
return sign ? -z : z;
}
if (ix < 0x3fdc0000) { /* |x| < 0.4375 */
if (ix < 0x3e400000) { /* |x| < 2^-27 */
if (ix < 0x00100000)
/* raise underflow for subnormal x */
FORCE_EVAL((float)x);
return x;
}
id = -1;
} else {
x = fabs(x);
if (ix < 0x3ff30000) { /* |x| < 1.1875 */
if (ix < 0x3fe60000) { /* 7/16 <= |x| < 11/16 */
id = 0;
x = (2.0*x-1.0)/(2.0+x);
} else { /* 11/16 <= |x| < 19/16 */
id = 1;
x = (x-1.0)/(x+1.0);
}
} else {
if (ix < 0x40038000) { /* |x| < 2.4375 */
id = 2;
x = (x-1.5)/(1.0+1.5*x);
} else { /* 2.4375 <= |x| < 2^66 */
id = 3;
x = -1.0/x;
}
}
}
/* end of argument reduction */
z = x*x;
w = z*z;
/* break sum from i=0 to 10 aT[i]z**(i+1) into odd and even poly */
s1 = z*(aT[0]+w*(aT[2]+w*(aT[4]+w*(aT[6]+w*(aT[8]+w*aT[10])))));
s2 = w*(aT[1]+w*(aT[3]+w*(aT[5]+w*(aT[7]+w*aT[9]))));
if (id < 0)
return x - x*(s1+s2);
z = atanhi[id] - (x*(s1+s2) - atanlo[id] - x);
return sign ? -z : z;
}

107
src/libc-shim/src/atan2.c Normal file
View File

@ -0,0 +1,107 @@
/* origin: FreeBSD /usr/src/lib/msun/src/e_atan2.c */
/*
* ====================================================
* Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
*
* Developed at SunSoft, a Sun Microsystems, Inc. business.
* Permission to use, copy, modify, and distribute this
* software is freely granted, provided that this notice
* is preserved.
* ====================================================
*
*/
/* atan2(y,x)
* Method :
* 1. Reduce y to positive by atan2(y,x)=-atan2(-y,x).
* 2. Reduce x to positive by (if x and y are unexceptional):
* ARG (x+iy) = arctan(y/x) ... if x > 0,
* ARG (x+iy) = pi - arctan[y/(-x)] ... if x < 0,
*
* Special cases:
*
* ATAN2((anything), NaN ) is NaN;
* ATAN2(NAN , (anything) ) is NaN;
* ATAN2(+-0, +(anything but NaN)) is +-0 ;
* ATAN2(+-0, -(anything but NaN)) is +-pi ;
* ATAN2(+-(anything but 0 and NaN), 0) is +-pi/2;
* ATAN2(+-(anything but INF and NaN), +INF) is +-0 ;
* ATAN2(+-(anything but INF and NaN), -INF) is +-pi;
* ATAN2(+-INF,+INF ) is +-pi/4 ;
* ATAN2(+-INF,-INF ) is +-3pi/4;
* ATAN2(+-INF, (anything but,0,NaN, and INF)) is +-pi/2;
*
* Constants:
* The hexadecimal values are the intended ones for the following
* constants. The decimal values may be used, provided that the
* compiler will convert from decimal to binary accurately enough
* to produce the hexadecimal values shown.
*/
#include "libm.h"
static const double
pi = 3.1415926535897931160E+00, /* 0x400921FB, 0x54442D18 */
pi_lo = 1.2246467991473531772E-16; /* 0x3CA1A626, 0x33145C07 */
double atan2(double y, double x)
{
double z;
uint32_t m,lx,ly,ix,iy;
if (isnan(x) || isnan(y))
return x+y;
EXTRACT_WORDS(ix, lx, x);
EXTRACT_WORDS(iy, ly, y);
if ((ix-0x3ff00000 | lx) == 0) /* x = 1.0 */
return atan(y);
m = ((iy>>31)&1) | ((ix>>30)&2); /* 2*sign(x)+sign(y) */
ix = ix & 0x7fffffff;
iy = iy & 0x7fffffff;
/* when y = 0 */
if ((iy|ly) == 0) {
switch(m) {
case 0:
case 1: return y; /* atan(+-0,+anything)=+-0 */
case 2: return pi; /* atan(+0,-anything) = pi */
case 3: return -pi; /* atan(-0,-anything) =-pi */
}
}
/* when x = 0 */
if ((ix|lx) == 0)
return m&1 ? -pi/2 : pi/2;
/* when x is INF */
if (ix == 0x7ff00000) {
if (iy == 0x7ff00000) {
switch(m) {
case 0: return pi/4; /* atan(+INF,+INF) */
case 1: return -pi/4; /* atan(-INF,+INF) */
case 2: return 3*pi/4; /* atan(+INF,-INF) */
case 3: return -3*pi/4; /* atan(-INF,-INF) */
}
} else {
switch(m) {
case 0: return 0.0; /* atan(+...,+INF) */
case 1: return -0.0; /* atan(-...,+INF) */
case 2: return pi; /* atan(+...,-INF) */
case 3: return -pi; /* atan(-...,-INF) */
}
}
}
/* |y/x| > 0x1p64 */
if (ix+(64<<20) < iy || iy == 0x7ff00000)
return m&1 ? -pi/2 : pi/2;
/* z = atan(|y/x|) without spurious underflow */
if ((m&2) && iy+(64<<20) < ix) /* |y/x| < 0x1p-64, x<0 */
z = 0;
else
z = atan(fabs(y/x));
switch (m) {
case 0: return z; /* atan(+,+) */
case 1: return -z; /* atan(-,+) */
case 2: return pi - (z-pi_lo); /* atan(+,-) */
default: /* case 3 */
return (z-pi_lo) - pi; /* atan(-,-) */
}
}

View File

@ -0,0 +1,83 @@
/* origin: FreeBSD /usr/src/lib/msun/src/e_atan2f.c */
/*
* Conversion to float by Ian Lance Taylor, Cygnus Support, ian@cygnus.com.
*/
/*
* ====================================================
* Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
*
* Developed at SunPro, a Sun Microsystems, Inc. business.
* Permission to use, copy, modify, and distribute this
* software is freely granted, provided that this notice
* is preserved.
* ====================================================
*/
#include "libm.h"
static const float
pi = 3.1415927410e+00, /* 0x40490fdb */
pi_lo = -8.7422776573e-08; /* 0xb3bbbd2e */
float atan2f(float y, float x)
{
float z;
uint32_t m,ix,iy;
if (isnan(x) || isnan(y))
return x+y;
GET_FLOAT_WORD(ix, x);
GET_FLOAT_WORD(iy, y);
if (ix == 0x3f800000) /* x=1.0 */
return atanf(y);
m = ((iy>>31)&1) | ((ix>>30)&2); /* 2*sign(x)+sign(y) */
ix &= 0x7fffffff;
iy &= 0x7fffffff;
/* when y = 0 */
if (iy == 0) {
switch (m) {
case 0:
case 1: return y; /* atan(+-0,+anything)=+-0 */
case 2: return pi; /* atan(+0,-anything) = pi */
case 3: return -pi; /* atan(-0,-anything) =-pi */
}
}
/* when x = 0 */
if (ix == 0)
return m&1 ? -pi/2 : pi/2;
/* when x is INF */
if (ix == 0x7f800000) {
if (iy == 0x7f800000) {
switch (m) {
case 0: return pi/4; /* atan(+INF,+INF) */
case 1: return -pi/4; /* atan(-INF,+INF) */
case 2: return 3*pi/4; /*atan(+INF,-INF)*/
case 3: return -3*pi/4; /*atan(-INF,-INF)*/
}
} else {
switch (m) {
case 0: return 0.0f; /* atan(+...,+INF) */
case 1: return -0.0f; /* atan(-...,+INF) */
case 2: return pi; /* atan(+...,-INF) */
case 3: return -pi; /* atan(-...,-INF) */
}
}
}
/* |y/x| > 0x1p26 */
if (ix+(26<<23) < iy || iy == 0x7f800000)
return m&1 ? -pi/2 : pi/2;
/* z = atan(|y/x|) with correct underflow */
if ((m&2) && iy+(26<<23) < ix) /*|y/x| < 0x1p-26, x < 0 */
z = 0.0;
else
z = atanf(fabsf(y/x));
switch (m) {
case 0: return z; /* atan(+,+) */
case 1: return -z; /* atan(-,+) */
case 2: return pi - (z-pi_lo); /* atan(+,-) */
default: /* case 3 */
return (z-pi_lo) - pi; /* atan(-,-) */
}
}

94
src/libc-shim/src/atanf.c Normal file
View File

@ -0,0 +1,94 @@
/* origin: FreeBSD /usr/src/lib/msun/src/s_atanf.c */
/*
* Conversion to float by Ian Lance Taylor, Cygnus Support, ian@cygnus.com.
*/
/*
* ====================================================
* Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
*
* Developed at SunPro, a Sun Microsystems, Inc. business.
* Permission to use, copy, modify, and distribute this
* software is freely granted, provided that this notice
* is preserved.
* ====================================================
*/
#include "libm.h"
static const float atanhi[] = {
4.6364760399e-01, /* atan(0.5)hi 0x3eed6338 */
7.8539812565e-01, /* atan(1.0)hi 0x3f490fda */
9.8279368877e-01, /* atan(1.5)hi 0x3f7b985e */
1.5707962513e+00, /* atan(inf)hi 0x3fc90fda */
};
static const float atanlo[] = {
5.0121582440e-09, /* atan(0.5)lo 0x31ac3769 */
3.7748947079e-08, /* atan(1.0)lo 0x33222168 */
3.4473217170e-08, /* atan(1.5)lo 0x33140fb4 */
7.5497894159e-08, /* atan(inf)lo 0x33a22168 */
};
static const float aT[] = {
3.3333328366e-01,
-1.9999158382e-01,
1.4253635705e-01,
-1.0648017377e-01,
6.1687607318e-02,
};
float atanf(float x)
{
float_t w,s1,s2,z;
uint32_t ix,sign;
int id;
GET_FLOAT_WORD(ix, x);
sign = ix>>31;
ix &= 0x7fffffff;
if (ix >= 0x4c800000) { /* if |x| >= 2**26 */
if (isnan(x))
return x;
z = atanhi[3] + 0x1p-120f;
return sign ? -z : z;
}
if (ix < 0x3ee00000) { /* |x| < 0.4375 */
if (ix < 0x39800000) { /* |x| < 2**-12 */
if (ix < 0x00800000)
/* raise underflow for subnormal x */
FORCE_EVAL(x*x);
return x;
}
id = -1;
} else {
x = fabsf(x);
if (ix < 0x3f980000) { /* |x| < 1.1875 */
if (ix < 0x3f300000) { /* 7/16 <= |x| < 11/16 */
id = 0;
x = (2.0f*x - 1.0f)/(2.0f + x);
} else { /* 11/16 <= |x| < 19/16 */
id = 1;
x = (x - 1.0f)/(x + 1.0f);
}
} else {
if (ix < 0x401c0000) { /* |x| < 2.4375 */
id = 2;
x = (x - 1.5f)/(1.0f + 1.5f*x);
} else { /* 2.4375 <= |x| < 2**26 */
id = 3;
x = -1.0f/x;
}
}
}
/* end of argument reduction */
z = x*x;
w = z*z;
/* break sum from i=0 to 10 aT[i]z**(i+1) into odd and even poly */
s1 = z*(aT[0]+w*(aT[2]+w*aT[4]));
s2 = w*(aT[1]+w*aT[3]);
if (id < 0)
return x - x*(s1+s2);
z = atanhi[id] - ((x*(s1+s2) - atanlo[id]) - x);
return sign ? -z : z;
}

103
src/libc-shim/src/cbrt.c Normal file
View File

@ -0,0 +1,103 @@
/* origin: FreeBSD /usr/src/lib/msun/src/s_cbrt.c */
/*
* ====================================================
* Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
*
* Developed at SunPro, a Sun Microsystems, Inc. business.
* Permission to use, copy, modify, and distribute this
* software is freely granted, provided that this notice
* is preserved.
* ====================================================
*
* Optimized by Bruce D. Evans.
*/
/* cbrt(x)
* Return cube root of x
*/
#include <math.h>
#include <stdint.h>
static const uint32_t
B1 = 715094163, /* B1 = (1023-1023/3-0.03306235651)*2**20 */
B2 = 696219795; /* B2 = (1023-1023/3-54/3-0.03306235651)*2**20 */
/* |1/cbrt(x) - p(x)| < 2**-23.5 (~[-7.93e-8, 7.929e-8]). */
static const double
P0 = 1.87595182427177009643, /* 0x3ffe03e6, 0x0f61e692 */
P1 = -1.88497979543377169875, /* 0xbffe28e0, 0x92f02420 */
P2 = 1.621429720105354466140, /* 0x3ff9f160, 0x4a49d6c2 */
P3 = -0.758397934778766047437, /* 0xbfe844cb, 0xbee751d9 */
P4 = 0.145996192886612446982; /* 0x3fc2b000, 0xd4e4edd7 */
double cbrt(double x)
{
union {double f; uint64_t i;} u = {x};
double_t r,s,t,w;
uint32_t hx = u.i>>32 & 0x7fffffff;
if (hx >= 0x7ff00000) /* cbrt(NaN,INF) is itself */
return x+x;
/*
* Rough cbrt to 5 bits:
* cbrt(2**e*(1+m) ~= 2**(e/3)*(1+(e%3+m)/3)
* where e is integral and >= 0, m is real and in [0, 1), and "/" and
* "%" are integer division and modulus with rounding towards minus
* infinity. The RHS is always >= the LHS and has a maximum relative
* error of about 1 in 16. Adding a bias of -0.03306235651 to the
* (e%3+m)/3 term reduces the error to about 1 in 32. With the IEEE
* floating point representation, for finite positive normal values,
* ordinary integer divison of the value in bits magically gives
* almost exactly the RHS of the above provided we first subtract the
* exponent bias (1023 for doubles) and later add it back. We do the
* subtraction virtually to keep e >= 0 so that ordinary integer
* division rounds towards minus infinity; this is also efficient.
*/
if (hx < 0x00100000) { /* zero or subnormal? */
u.f = x*0x1p54;
hx = u.i>>32 & 0x7fffffff;
if (hx == 0)
return x; /* cbrt(0) is itself */
hx = hx/3 + B2;
} else
hx = hx/3 + B1;
u.i &= 1ULL<<63;
u.i |= (uint64_t)hx << 32;
t = u.f;
/*
* New cbrt to 23 bits:
* cbrt(x) = t*cbrt(x/t**3) ~= t*P(t**3/x)
* where P(r) is a polynomial of degree 4 that approximates 1/cbrt(r)
* to within 2**-23.5 when |r - 1| < 1/10. The rough approximation
* has produced t such than |t/cbrt(x) - 1| ~< 1/32, and cubing this
* gives us bounds for r = t**3/x.
*
* Try to optimize for parallel evaluation as in __tanf.c.
*/
r = (t*t)*(t/x);
t = t*((P0+r*(P1+r*P2))+((r*r)*r)*(P3+r*P4));
/*
* Round t away from zero to 23 bits (sloppily except for ensuring that
* the result is larger in magnitude than cbrt(x) but not much more than
* 2 23-bit ulps larger). With rounding towards zero, the error bound
* would be ~5/6 instead of ~4/6. With a maximum error of 2 23-bit ulps
* in the rounded t, the infinite-precision error in the Newton
* approximation barely affects third digit in the final error
* 0.667; the error in the rounded t can be up to about 3 23-bit ulps
* before the final error is larger than 0.667 ulps.
*/
u.f = t;
u.i = (u.i + 0x80000000) & 0xffffffffc0000000ULL;
t = u.f;
/* one step Newton iteration to 53 bits with error < 0.667 ulps */
s = t*t; /* t*t is exact */
r = x/s; /* error <= 0.5 ulps; |r| < |t| */
w = t+t; /* t+t is exact */
r = (r-t)/(w+r); /* r-t is exact; w+r ~= 3*t */
t = t+t*r; /* error <= 0.5 + 0.5/3 + epsilon */
return t;
}

66
src/libc-shim/src/cbrtf.c Normal file
View File

@ -0,0 +1,66 @@
/* origin: FreeBSD /usr/src/lib/msun/src/s_cbrtf.c */
/*
* Conversion to float by Ian Lance Taylor, Cygnus Support, ian@cygnus.com.
* Debugged and optimized by Bruce D. Evans.
*/
/*
* ====================================================
* Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
*
* Developed at SunPro, a Sun Microsystems, Inc. business.
* Permission to use, copy, modify, and distribute this
* software is freely granted, provided that this notice
* is preserved.
* ====================================================
*/
/* cbrtf(x)
* Return cube root of x
*/
#include <math.h>
#include <stdint.h>
static const unsigned
B1 = 709958130, /* B1 = (127-127.0/3-0.03306235651)*2**23 */
B2 = 642849266; /* B2 = (127-127.0/3-24/3-0.03306235651)*2**23 */
float cbrtf(float x)
{
double_t r,T;
union {float f; uint32_t i;} u = {x};
uint32_t hx = u.i & 0x7fffffff;
if (hx >= 0x7f800000) /* cbrt(NaN,INF) is itself */
return x + x;
/* rough cbrt to 5 bits */
if (hx < 0x00800000) { /* zero or subnormal? */
if (hx == 0)
return x; /* cbrt(+-0) is itself */
u.f = x*0x1p24f;
hx = u.i & 0x7fffffff;
hx = hx/3 + B2;
} else
hx = hx/3 + B1;
u.i &= 0x80000000;
u.i |= hx;
/*
* First step Newton iteration (solving t*t-x/t == 0) to 16 bits. In
* double precision so that its terms can be arranged for efficiency
* without causing overflow or underflow.
*/
T = u.f;
r = T*T*T;
T = T*((double_t)x+x+r)/(x+r+r);
/*
* Second step Newton iteration to 47 bits. In double precision for
* efficiency and accuracy.
*/
r = T*T*T;
T = T*((double_t)x+x+r)/(x+r+r);
/* rounding to 24 bits is perfect in round-to-nearest mode */
return T;
}

136
src/libc-shim/src/exp.c Normal file
View File

@ -0,0 +1,136 @@
/*
* Double-precision e^x function.
*
* Copyright (c) 2018, Arm Limited.
* SPDX-License-Identifier: MIT
*/
#include <math.h>
#include <stdint.h>
#include "libm.h"
#include "exp_data.h"
#define N (1 << EXP_TABLE_BITS)
#define InvLn2N __exp_data.invln2N
#define NegLn2hiN __exp_data.negln2hiN
#define NegLn2loN __exp_data.negln2loN
#define Shift __exp_data.shift
#define T __exp_data.tab
#define C2 __exp_data.poly[5 - EXP_POLY_ORDER]
#define C3 __exp_data.poly[6 - EXP_POLY_ORDER]
#define C4 __exp_data.poly[7 - EXP_POLY_ORDER]
#define C5 __exp_data.poly[8 - EXP_POLY_ORDER]
/* Handle cases that may overflow or underflow when computing the result that
is scale*(1+TMP) without intermediate rounding. The bit representation of
scale is in SBITS, however it has a computed exponent that may have
overflown into the sign bit so that needs to be adjusted before using it as
a double. (int32_t)KI is the k used in the argument reduction and exponent
adjustment of scale, positive k here means the result may overflow and
negative k means the result may underflow. */
static inline double specialcase(double_t tmp, uint64_t sbits, uint64_t ki)
{
double_t scale, y;
if ((ki & 0x80000000) == 0) {
/* k > 0, the exponent of scale might have overflowed by <= 460. */
sbits -= 1009ull << 52;
scale = asdouble(sbits);
y = 0x1p1009 * (scale + scale * tmp);
return eval_as_double(y);
}
/* k < 0, need special care in the subnormal range. */
sbits += 1022ull << 52;
scale = asdouble(sbits);
y = scale + scale * tmp;
if (y < 1.0) {
/* Round y to the right precision before scaling it into the subnormal
range to avoid double rounding that can cause 0.5+E/2 ulp error where
E is the worst-case ulp error outside the subnormal range. So this
is only useful if the goal is better than 1 ulp worst-case error. */
double_t hi, lo;
lo = scale - y + scale * tmp;
hi = 1.0 + y;
lo = 1.0 - hi + y + lo;
y = eval_as_double(hi + lo) - 1.0;
/* Avoid -0.0 with downward rounding. */
if (WANT_ROUNDING && y == 0.0)
y = 0.0;
/* The underflow exception needs to be signaled explicitly. */
//WARN(orca): we don't have fp_barrier in wasm
//fp_force_eval(fp_barrier(0x1p-1022) * 0x1p-1022);
fp_force_eval((0x1p-1022) * 0x1p-1022);
}
y = 0x1p-1022 * y;
return eval_as_double(y);
}
/* Top 12 bits of a double (sign and exponent bits). */
static inline uint32_t top12(double x)
{
return asuint64(x) >> 52;
}
double exp(double x)
{
uint32_t abstop;
uint64_t ki, idx, top, sbits;
double_t kd, z, r, r2, scale, tail, tmp;
abstop = top12(x) & 0x7ff;
if (predict_false(abstop - top12(0x1p-54) >= top12(512.0) - top12(0x1p-54))) {
if (abstop - top12(0x1p-54) >= 0x80000000)
/* Avoid spurious underflow for tiny x. */
/* Note: 0 is common input. */
return WANT_ROUNDING ? 1.0 + x : 1.0;
if (abstop >= top12(1024.0)) {
if (asuint64(x) == asuint64(-INFINITY))
return 0.0;
if (abstop >= top12(INFINITY))
return 1.0 + x;
if (asuint64(x) >> 63)
return __math_uflow(0);
else
return __math_oflow(0);
}
/* Large x is special cased below. */
abstop = 0;
}
/* exp(x) = 2^(k/N) * exp(r), with exp(r) in [2^(-1/2N),2^(1/2N)]. */
/* x = ln2/N*k + r, with int k and r in [-ln2/2N, ln2/2N]. */
z = InvLn2N * x;
#if TOINT_INTRINSICS
kd = roundtoint(z);
ki = converttoint(z);
#elif EXP_USE_TOINT_NARROW
/* z - kd is in [-0.5-2^-16, 0.5] in all rounding modes. */
kd = eval_as_double(z + Shift);
ki = asuint64(kd) >> 16;
kd = (double_t)(int32_t)ki;
#else
/* z - kd is in [-1, 1] in non-nearest rounding modes. */
kd = eval_as_double(z + Shift);
ki = asuint64(kd);
kd -= Shift;
#endif
r = x + kd * NegLn2hiN + kd * NegLn2loN;
/* 2^(k/N) ~= scale * (1 + tail). */
idx = 2 * (ki % N);
top = ki << (52 - EXP_TABLE_BITS);
tail = asdouble(T[idx]);
/* This is only a valid scale when -1023*N < k < 1024*N. */
sbits = T[idx + 1] + top;
/* exp(x) = 2^(k/N) * exp(r) ~= scale + scale * (tail + exp(r) - 1). */
/* Evaluation is optimized assuming superscalar pipelined execution. */
r2 = r * r;
/* Without fma the worst case error is 0.25/N ulp larger. */
/* Worst case error is less than 0.5+1.11/N+(abs poly error * 2^53) ulp. */
tmp = tail + r + r2 * (C2 + r * C3) + r2 * r2 * (C4 + r * C5);
if (predict_false(abstop == 0))
return specialcase(tmp, sbits, ki);
scale = asdouble(sbits);
/* Note: tmp == 0 or |tmp| > 2^-200 and scale > 2^-739, so there
is no spurious underflow here even without fma. */
return eval_as_double(scale + scale * tmp);
}

View File

@ -0,0 +1,35 @@
/*
* Shared data between expf, exp2f and powf.
*
* Copyright (c) 2017-2018, Arm Limited.
* SPDX-License-Identifier: MIT
*/
#include "exp2f_data.h"
#define N (1 << EXP2F_TABLE_BITS)
const struct exp2f_data __exp2f_data = {
/* tab[i] = uint(2^(i/N)) - (i << 52-BITS)
used for computing 2^(k/N) for an int |k| < 150 N as
double(tab[k%N] + (k << 52-BITS)) */
.tab = {
0x3ff0000000000000, 0x3fefd9b0d3158574, 0x3fefb5586cf9890f, 0x3fef9301d0125b51,
0x3fef72b83c7d517b, 0x3fef54873168b9aa, 0x3fef387a6e756238, 0x3fef1e9df51fdee1,
0x3fef06fe0a31b715, 0x3feef1a7373aa9cb, 0x3feedea64c123422, 0x3feece086061892d,
0x3feebfdad5362a27, 0x3feeb42b569d4f82, 0x3feeab07dd485429, 0x3feea47eb03a5585,
0x3feea09e667f3bcd, 0x3fee9f75e8ec5f74, 0x3feea11473eb0187, 0x3feea589994cce13,
0x3feeace5422aa0db, 0x3feeb737b0cdc5e5, 0x3feec49182a3f090, 0x3feed503b23e255d,
0x3feee89f995ad3ad, 0x3feeff76f2fb5e47, 0x3fef199bdd85529c, 0x3fef3720dcef9069,
0x3fef5818dcfba487, 0x3fef7c97337b9b5f, 0x3fefa4afa2a490da, 0x3fefd0765b6e4540,
},
.shift_scaled = 0x1.8p+52 / N,
.poly = {
0x1.c6af84b912394p-5, 0x1.ebfce50fac4f3p-3, 0x1.62e42ff0c52d6p-1,
},
.shift = 0x1.8p+52,
.invln2_scaled = 0x1.71547652b82fep+0 * N,
.poly_scaled = {
0x1.c6af84b912394p-5/N/N/N, 0x1.ebfce50fac4f3p-3/N/N, 0x1.62e42ff0c52d6p-1/N,
},
};

View File

@ -0,0 +1,23 @@
/*
* Copyright (c) 2017-2018, Arm Limited.
* SPDX-License-Identifier: MIT
*/
#ifndef _EXP2F_DATA_H
#define _EXP2F_DATA_H
#include <features.h>
#include <stdint.h>
/* Shared between expf, exp2f and powf. */
#define EXP2F_TABLE_BITS 5
#define EXP2F_POLY_ORDER 3
extern const struct exp2f_data {
uint64_t tab[1 << EXP2F_TABLE_BITS];
double shift_scaled;
double poly[EXP2F_POLY_ORDER];
double shift;
double invln2_scaled;
double poly_scaled[EXP2F_POLY_ORDER];
} __exp2f_data;
#endif

View File

@ -0,0 +1,182 @@
/*
* Shared data between exp, exp2 and pow.
*
* Copyright (c) 2018, Arm Limited.
* SPDX-License-Identifier: MIT
*/
#include "exp_data.h"
#define N (1 << EXP_TABLE_BITS)
const struct exp_data __exp_data = {
// N/ln2
.invln2N = 0x1.71547652b82fep0 * N,
// -ln2/N
.negln2hiN = -0x1.62e42fefa0000p-8,
.negln2loN = -0x1.cf79abc9e3b3ap-47,
// Used for rounding when !TOINT_INTRINSICS
#if EXP_USE_TOINT_NARROW
.shift = 0x1800000000.8p0,
#else
.shift = 0x1.8p52,
#endif
// exp polynomial coefficients.
.poly = {
// abs error: 1.555*2^-66
// ulp error: 0.509 (0.511 without fma)
// if |x| < ln2/256+eps
// abs error if |x| < ln2/256+0x1p-15: 1.09*2^-65
// abs error if |x| < ln2/128: 1.7145*2^-56
0x1.ffffffffffdbdp-2,
0x1.555555555543cp-3,
0x1.55555cf172b91p-5,
0x1.1111167a4d017p-7,
},
.exp2_shift = 0x1.8p52 / N,
// exp2 polynomial coefficients.
.exp2_poly = {
// abs error: 1.2195*2^-65
// ulp error: 0.507 (0.511 without fma)
// if |x| < 1/256
// abs error if |x| < 1/128: 1.9941*2^-56
0x1.62e42fefa39efp-1,
0x1.ebfbdff82c424p-3,
0x1.c6b08d70cf4b5p-5,
0x1.3b2abd24650ccp-7,
0x1.5d7e09b4e3a84p-10,
},
// 2^(k/N) ~= H[k]*(1 + T[k]) for int k in [0,N)
// tab[2*k] = asuint64(T[k])
// tab[2*k+1] = asuint64(H[k]) - (k << 52)/N
.tab = {
0x0, 0x3ff0000000000000,
0x3c9b3b4f1a88bf6e, 0x3feff63da9fb3335,
0xbc7160139cd8dc5d, 0x3fefec9a3e778061,
0xbc905e7a108766d1, 0x3fefe315e86e7f85,
0x3c8cd2523567f613, 0x3fefd9b0d3158574,
0xbc8bce8023f98efa, 0x3fefd06b29ddf6de,
0x3c60f74e61e6c861, 0x3fefc74518759bc8,
0x3c90a3e45b33d399, 0x3fefbe3ecac6f383,
0x3c979aa65d837b6d, 0x3fefb5586cf9890f,
0x3c8eb51a92fdeffc, 0x3fefac922b7247f7,
0x3c3ebe3d702f9cd1, 0x3fefa3ec32d3d1a2,
0xbc6a033489906e0b, 0x3fef9b66affed31b,
0xbc9556522a2fbd0e, 0x3fef9301d0125b51,
0xbc5080ef8c4eea55, 0x3fef8abdc06c31cc,
0xbc91c923b9d5f416, 0x3fef829aaea92de0,
0x3c80d3e3e95c55af, 0x3fef7a98c8a58e51,
0xbc801b15eaa59348, 0x3fef72b83c7d517b,
0xbc8f1ff055de323d, 0x3fef6af9388c8dea,
0x3c8b898c3f1353bf, 0x3fef635beb6fcb75,
0xbc96d99c7611eb26, 0x3fef5be084045cd4,
0x3c9aecf73e3a2f60, 0x3fef54873168b9aa,
0xbc8fe782cb86389d, 0x3fef4d5022fcd91d,
0x3c8a6f4144a6c38d, 0x3fef463b88628cd6,
0x3c807a05b0e4047d, 0x3fef3f49917ddc96,
0x3c968efde3a8a894, 0x3fef387a6e756238,
0x3c875e18f274487d, 0x3fef31ce4fb2a63f,
0x3c80472b981fe7f2, 0x3fef2b4565e27cdd,
0xbc96b87b3f71085e, 0x3fef24dfe1f56381,
0x3c82f7e16d09ab31, 0x3fef1e9df51fdee1,
0xbc3d219b1a6fbffa, 0x3fef187fd0dad990,
0x3c8b3782720c0ab4, 0x3fef1285a6e4030b,
0x3c6e149289cecb8f, 0x3fef0cafa93e2f56,
0x3c834d754db0abb6, 0x3fef06fe0a31b715,
0x3c864201e2ac744c, 0x3fef0170fc4cd831,
0x3c8fdd395dd3f84a, 0x3feefc08b26416ff,
0xbc86a3803b8e5b04, 0x3feef6c55f929ff1,
0xbc924aedcc4b5068, 0x3feef1a7373aa9cb,
0xbc9907f81b512d8e, 0x3feeecae6d05d866,
0xbc71d1e83e9436d2, 0x3feee7db34e59ff7,
0xbc991919b3ce1b15, 0x3feee32dc313a8e5,
0x3c859f48a72a4c6d, 0x3feedea64c123422,
0xbc9312607a28698a, 0x3feeda4504ac801c,
0xbc58a78f4817895b, 0x3feed60a21f72e2a,
0xbc7c2c9b67499a1b, 0x3feed1f5d950a897,
0x3c4363ed60c2ac11, 0x3feece086061892d,
0x3c9666093b0664ef, 0x3feeca41ed1d0057,
0x3c6ecce1daa10379, 0x3feec6a2b5c13cd0,
0x3c93ff8e3f0f1230, 0x3feec32af0d7d3de,
0x3c7690cebb7aafb0, 0x3feebfdad5362a27,
0x3c931dbdeb54e077, 0x3feebcb299fddd0d,
0xbc8f94340071a38e, 0x3feeb9b2769d2ca7,
0xbc87deccdc93a349, 0x3feeb6daa2cf6642,
0xbc78dec6bd0f385f, 0x3feeb42b569d4f82,
0xbc861246ec7b5cf6, 0x3feeb1a4ca5d920f,
0x3c93350518fdd78e, 0x3feeaf4736b527da,
0x3c7b98b72f8a9b05, 0x3feead12d497c7fd,
0x3c9063e1e21c5409, 0x3feeab07dd485429,
0x3c34c7855019c6ea, 0x3feea9268a5946b7,
0x3c9432e62b64c035, 0x3feea76f15ad2148,
0xbc8ce44a6199769f, 0x3feea5e1b976dc09,
0xbc8c33c53bef4da8, 0x3feea47eb03a5585,
0xbc845378892be9ae, 0x3feea34634ccc320,
0xbc93cedd78565858, 0x3feea23882552225,
0x3c5710aa807e1964, 0x3feea155d44ca973,
0xbc93b3efbf5e2228, 0x3feea09e667f3bcd,
0xbc6a12ad8734b982, 0x3feea012750bdabf,
0xbc6367efb86da9ee, 0x3fee9fb23c651a2f,
0xbc80dc3d54e08851, 0x3fee9f7df9519484,
0xbc781f647e5a3ecf, 0x3fee9f75e8ec5f74,
0xbc86ee4ac08b7db0, 0x3fee9f9a48a58174,
0xbc8619321e55e68a, 0x3fee9feb564267c9,
0x3c909ccb5e09d4d3, 0x3feea0694fde5d3f,
0xbc7b32dcb94da51d, 0x3feea11473eb0187,
0x3c94ecfd5467c06b, 0x3feea1ed0130c132,
0x3c65ebe1abd66c55, 0x3feea2f336cf4e62,
0xbc88a1c52fb3cf42, 0x3feea427543e1a12,
0xbc9369b6f13b3734, 0x3feea589994cce13,
0xbc805e843a19ff1e, 0x3feea71a4623c7ad,
0xbc94d450d872576e, 0x3feea8d99b4492ed,
0x3c90ad675b0e8a00, 0x3feeaac7d98a6699,
0x3c8db72fc1f0eab4, 0x3feeace5422aa0db,
0xbc65b6609cc5e7ff, 0x3feeaf3216b5448c,
0x3c7bf68359f35f44, 0x3feeb1ae99157736,
0xbc93091fa71e3d83, 0x3feeb45b0b91ffc6,
0xbc5da9b88b6c1e29, 0x3feeb737b0cdc5e5,
0xbc6c23f97c90b959, 0x3feeba44cbc8520f,
0xbc92434322f4f9aa, 0x3feebd829fde4e50,
0xbc85ca6cd7668e4b, 0x3feec0f170ca07ba,
0x3c71affc2b91ce27, 0x3feec49182a3f090,
0x3c6dd235e10a73bb, 0x3feec86319e32323,
0xbc87c50422622263, 0x3feecc667b5de565,
0x3c8b1c86e3e231d5, 0x3feed09bec4a2d33,
0xbc91bbd1d3bcbb15, 0x3feed503b23e255d,
0x3c90cc319cee31d2, 0x3feed99e1330b358,
0x3c8469846e735ab3, 0x3feede6b5579fdbf,
0xbc82dfcd978e9db4, 0x3feee36bbfd3f37a,
0x3c8c1a7792cb3387, 0x3feee89f995ad3ad,
0xbc907b8f4ad1d9fa, 0x3feeee07298db666,
0xbc55c3d956dcaeba, 0x3feef3a2b84f15fb,
0xbc90a40e3da6f640, 0x3feef9728de5593a,
0xbc68d6f438ad9334, 0x3feeff76f2fb5e47,
0xbc91eee26b588a35, 0x3fef05b030a1064a,
0x3c74ffd70a5fddcd, 0x3fef0c1e904bc1d2,
0xbc91bdfbfa9298ac, 0x3fef12c25bd71e09,
0x3c736eae30af0cb3, 0x3fef199bdd85529c,
0x3c8ee3325c9ffd94, 0x3fef20ab5fffd07a,
0x3c84e08fd10959ac, 0x3fef27f12e57d14b,
0x3c63cdaf384e1a67, 0x3fef2f6d9406e7b5,
0x3c676b2c6c921968, 0x3fef3720dcef9069,
0xbc808a1883ccb5d2, 0x3fef3f0b555dc3fa,
0xbc8fad5d3ffffa6f, 0x3fef472d4a07897c,
0xbc900dae3875a949, 0x3fef4f87080d89f2,
0x3c74a385a63d07a7, 0x3fef5818dcfba487,
0xbc82919e2040220f, 0x3fef60e316c98398,
0x3c8e5a50d5c192ac, 0x3fef69e603db3285,
0x3c843a59ac016b4b, 0x3fef7321f301b460,
0xbc82d52107b43e1f, 0x3fef7c97337b9b5f,
0xbc892ab93b470dc9, 0x3fef864614f5a129,
0x3c74b604603a88d3, 0x3fef902ee78b3ff6,
0x3c83c5ec519d7271, 0x3fef9a51fbc74c83,
0xbc8ff7128fd391f0, 0x3fefa4afa2a490da,
0xbc8dae98e223747d, 0x3fefaf482d8e67f1,
0x3c8ec3bc41aa2008, 0x3fefba1bee615a27,
0x3c842b94c3a9eb32, 0x3fefc52b376bba97,
0x3c8a64a931d185ee, 0x3fefd0765b6e4540,
0xbc8e37bae43be3ed, 0x3fefdbfdad9cbe14,
0x3c77893b4d91cd9d, 0x3fefe7c1819e90d8,
0x3c5305c14160cc89, 0x3feff3c22b8f71f1,
},
};

80
src/libc-shim/src/expf.c Normal file
View File

@ -0,0 +1,80 @@
/*
* Single-precision e^x function.
*
* Copyright (c) 2017-2018, Arm Limited.
* SPDX-License-Identifier: MIT
*/
#include <math.h>
#include <stdint.h>
#include "libm.h"
#include "exp2f_data.h"
/*
EXP2F_TABLE_BITS = 5
EXP2F_POLY_ORDER = 3
ULP error: 0.502 (nearest rounding.)
Relative error: 1.69 * 2^-34 in [-ln2/64, ln2/64] (before rounding.)
Wrong count: 170635 (all nearest rounding wrong results with fma.)
Non-nearest ULP error: 1 (rounded ULP error)
*/
#define N (1 << EXP2F_TABLE_BITS)
#define InvLn2N __exp2f_data.invln2_scaled
#define T __exp2f_data.tab
#define C __exp2f_data.poly_scaled
static inline uint32_t top12(float x)
{
return asuint(x) >> 20;
}
float expf(float x)
{
uint32_t abstop;
uint64_t ki, t;
double_t kd, xd, z, r, r2, y, s;
xd = (double_t)x;
abstop = top12(x) & 0x7ff;
if (predict_false(abstop >= top12(88.0f))) {
/* |x| >= 88 or x is nan. */
if (asuint(x) == asuint(-INFINITY))
return 0.0f;
if (abstop >= top12(INFINITY))
return x + x;
if (x > 0x1.62e42ep6f) /* x > log(0x1p128) ~= 88.72 */
return __math_oflowf(0);
if (x < -0x1.9fe368p6f) /* x < log(0x1p-150) ~= -103.97 */
return __math_uflowf(0);
}
/* x*N/Ln2 = k + r with r in [-1/2, 1/2] and int k. */
z = InvLn2N * xd;
/* Round and convert z to int, the result is in [-150*N, 128*N] and
ideally ties-to-even rule is used, otherwise the magnitude of r
can be bigger which gives larger approximation error. */
#if TOINT_INTRINSICS
kd = roundtoint(z);
ki = converttoint(z);
#else
# define SHIFT __exp2f_data.shift
kd = eval_as_double(z + SHIFT);
ki = asuint64(kd);
kd -= SHIFT;
#endif
r = z - kd;
/* exp(x) = 2^(k/N) * 2^(r/N) ~= s * (C0*r^3 + C1*r^2 + C2*r + 1) */
t = T[ki % N];
t += ki << (52 - EXP2F_TABLE_BITS);
s = asdouble(t);
z = C[0] * r + C[1];
r2 = r * r;
y = C[2] * r + 1;
y = z * r2 + y;
y = y * s;
return eval_as_float(y);
}

View File

@ -1,3 +1,6 @@
#ifndef _LIBM_H
#define _LIBM_H
#include <float.h>
#include <math.h>
#include <stdint.h>
@ -144,8 +147,13 @@ int __rem_pio2f(float, double*);
float __sindf(double);
float __cosdf(double);
float __math_xflowf(uint32_t, float);
float __math_uflowf(uint32_t);
float __math_oflowf(uint32_t);
float __math_invalidf(float);
double __math_xflow(uint32_t, double);
double __math_uflow(uint32_t);
double __math_oflow(uint32_t);
double __math_invalid(double);
#endif // _LIBM_H

112
src/libc-shim/src/log.c Normal file
View File

@ -0,0 +1,112 @@
/*
* Double-precision log(x) function.
*
* Copyright (c) 2018, Arm Limited.
* SPDX-License-Identifier: MIT
*/
#include <math.h>
#include <stdint.h>
#include "libm.h"
#include "log_data.h"
#define T __log_data.tab
#define T2 __log_data.tab2
#define B __log_data.poly1
#define A __log_data.poly
#define Ln2hi __log_data.ln2hi
#define Ln2lo __log_data.ln2lo
#define N (1 << LOG_TABLE_BITS)
#define OFF 0x3fe6000000000000
/* Top 16 bits of a double. */
static inline uint32_t top16(double x)
{
return asuint64(x) >> 48;
}
double log(double x)
{
double_t w, z, r, r2, r3, y, invc, logc, kd, hi, lo;
uint64_t ix, iz, tmp;
uint32_t top;
int k, i;
ix = asuint64(x);
top = top16(x);
#define LO asuint64(1.0 - 0x1p-4)
#define HI asuint64(1.0 + 0x1.09p-4)
if (predict_false(ix - LO < HI - LO)) {
/* Handle close to 1.0 inputs separately. */
/* Fix sign of zero with downward rounding when x==1. */
if (WANT_ROUNDING && predict_false(ix == asuint64(1.0)))
return 0;
r = x - 1.0;
r2 = r * r;
r3 = r * r2;
y = r3 *
(B[1] + r * B[2] + r2 * B[3] +
r3 * (B[4] + r * B[5] + r2 * B[6] +
r3 * (B[7] + r * B[8] + r2 * B[9] + r3 * B[10])));
/* Worst-case error is around 0.507 ULP. */
w = r * 0x1p27;
double_t rhi = r + w - w;
double_t rlo = r - rhi;
w = rhi * rhi * B[0]; /* B[0] == -0.5. */
hi = r + w;
lo = r - hi + w;
lo += B[0] * rlo * (rhi + r);
y += lo;
y += hi;
return eval_as_double(y);
}
if (predict_false(top - 0x0010 >= 0x7ff0 - 0x0010)) {
/* x < 0x1p-1022 or inf or nan. */
if (ix * 2 == 0)
return __math_divzero(1);
if (ix == asuint64(INFINITY)) /* log(inf) == inf. */
return x;
if ((top & 0x8000) || (top & 0x7ff0) == 0x7ff0)
return __math_invalid(x);
/* x is subnormal, normalize it. */
ix = asuint64(x * 0x1p52);
ix -= 52ULL << 52;
}
/* x = 2^k z; where z is in range [OFF,2*OFF) and exact.
The range is split into N subintervals.
The ith subinterval contains z and c is near its center. */
tmp = ix - OFF;
i = (tmp >> (52 - LOG_TABLE_BITS)) % N;
k = (int64_t)tmp >> 52; /* arithmetic shift */
iz = ix - (tmp & 0xfffULL << 52);
invc = T[i].invc;
logc = T[i].logc;
z = asdouble(iz);
/* log(x) = log1p(z/c-1) + log(c) + k*Ln2. */
/* r ~= z/c - 1, |r| < 1/(2*N). */
#if __FP_FAST_FMA
/* rounding error: 0x1p-55/N. */
r = __builtin_fma(z, invc, -1.0);
#else
/* rounding error: 0x1p-55/N + 0x1p-66. */
r = (z - T2[i].chi - T2[i].clo) * invc;
#endif
kd = (double_t)k;
/* hi + lo = r + log(c) + k*Ln2. */
w = kd * Ln2hi + logc;
hi = w + r;
lo = w - hi + r + kd * Ln2lo;
/* log(x) = lo + (log1p(r) - r) + hi. */
r2 = r * r; /* rounding error: 0x1p-54/N^2. */
/* Worst case error if |y| > 0x1p-5:
0.5 + 4.13/N + abs-poly-error*2^57 ULP (+ 0.002 ULP without fma)
Worst case error if |y| > 0x1p-4:
0.5 + 2.06/N + abs-poly-error*2^56 ULP (+ 0.001 ULP without fma). */
y = lo + r2 * A[0] +
r * r2 * (A[1] + r * A[2] + r2 * (A[3] + r * A[4])) + hi;
return eval_as_double(y);
}

122
src/libc-shim/src/log2.c Normal file
View File

@ -0,0 +1,122 @@
/*
* Double-precision log2(x) function.
*
* Copyright (c) 2018, Arm Limited.
* SPDX-License-Identifier: MIT
*/
#include <math.h>
#include <stdint.h>
#include "libm.h"
#include "log2_data.h"
#define T __log2_data.tab
#define T2 __log2_data.tab2
#define B __log2_data.poly1
#define A __log2_data.poly
#define InvLn2hi __log2_data.invln2hi
#define InvLn2lo __log2_data.invln2lo
#define N (1 << LOG2_TABLE_BITS)
#define OFF 0x3fe6000000000000
/* Top 16 bits of a double. */
static inline uint32_t top16(double x)
{
return asuint64(x) >> 48;
}
double log2(double x)
{
double_t z, r, r2, r4, y, invc, logc, kd, hi, lo, t1, t2, t3, p;
uint64_t ix, iz, tmp;
uint32_t top;
int k, i;
ix = asuint64(x);
top = top16(x);
#define LO asuint64(1.0 - 0x1.5b51p-5)
#define HI asuint64(1.0 + 0x1.6ab2p-5)
if (predict_false(ix - LO < HI - LO)) {
/* Handle close to 1.0 inputs separately. */
/* Fix sign of zero with downward rounding when x==1. */
if (WANT_ROUNDING && predict_false(ix == asuint64(1.0)))
return 0;
r = x - 1.0;
#if __FP_FAST_FMA
hi = r * InvLn2hi;
lo = r * InvLn2lo + __builtin_fma(r, InvLn2hi, -hi);
#else
double_t rhi, rlo;
rhi = asdouble(asuint64(r) & -1ULL << 32);
rlo = r - rhi;
hi = rhi * InvLn2hi;
lo = rlo * InvLn2hi + r * InvLn2lo;
#endif
r2 = r * r; /* rounding error: 0x1p-62. */
r4 = r2 * r2;
/* Worst-case error is less than 0.54 ULP (0.55 ULP without fma). */
p = r2 * (B[0] + r * B[1]);
y = hi + p;
lo += hi - y + p;
lo += r4 * (B[2] + r * B[3] + r2 * (B[4] + r * B[5]) +
r4 * (B[6] + r * B[7] + r2 * (B[8] + r * B[9])));
y += lo;
return eval_as_double(y);
}
if (predict_false(top - 0x0010 >= 0x7ff0 - 0x0010)) {
/* x < 0x1p-1022 or inf or nan. */
if (ix * 2 == 0)
return __math_divzero(1);
if (ix == asuint64(INFINITY)) /* log(inf) == inf. */
return x;
if ((top & 0x8000) || (top & 0x7ff0) == 0x7ff0)
return __math_invalid(x);
/* x is subnormal, normalize it. */
ix = asuint64(x * 0x1p52);
ix -= 52ULL << 52;
}
/* x = 2^k z; where z is in range [OFF,2*OFF) and exact.
The range is split into N subintervals.
The ith subinterval contains z and c is near its center. */
tmp = ix - OFF;
i = (tmp >> (52 - LOG2_TABLE_BITS)) % N;
k = (int64_t)tmp >> 52; /* arithmetic shift */
iz = ix - (tmp & 0xfffULL << 52);
invc = T[i].invc;
logc = T[i].logc;
z = asdouble(iz);
kd = (double_t)k;
/* log2(x) = log2(z/c) + log2(c) + k. */
/* r ~= z/c - 1, |r| < 1/(2*N). */
#if __FP_FAST_FMA
/* rounding error: 0x1p-55/N. */
r = __builtin_fma(z, invc, -1.0);
t1 = r * InvLn2hi;
t2 = r * InvLn2lo + __builtin_fma(r, InvLn2hi, -t1);
#else
double_t rhi, rlo;
/* rounding error: 0x1p-55/N + 0x1p-65. */
r = (z - T2[i].chi - T2[i].clo) * invc;
rhi = asdouble(asuint64(r) & -1ULL << 32);
rlo = r - rhi;
t1 = rhi * InvLn2hi;
t2 = rlo * InvLn2hi + r * InvLn2lo;
#endif
/* hi + lo = r/ln2 + log2(c) + k. */
t3 = kd + logc;
hi = t3 + t1;
lo = t3 - hi + t1 + t2;
/* log2(r+1) = r/ln2 + r^2*poly(r). */
/* Evaluation is optimized assuming superscalar pipelined execution. */
r2 = r * r; /* rounding error: 0x1p-54/N^2. */
r4 = r2 * r2;
/* Worst-case error if |y| > 0x1p-4: 0.547 ULP (0.550 ULP without fma).
~ 0.5 + 2/N/ln2 + abs-poly-error*0x1p56 ULP (+ 0.003 ULP without fma). */
p = A[0] + r * A[1] + r2 * (A[2] + r * A[3]) + r4 * (A[4] + r * A[5]);
y = lo + r2 * p + hi;
return eval_as_double(y);
}

View File

@ -0,0 +1,201 @@
/*
* Data for log2.
*
* Copyright (c) 2018, Arm Limited.
* SPDX-License-Identifier: MIT
*/
#include "log2_data.h"
#define N (1 << LOG2_TABLE_BITS)
const struct log2_data __log2_data = {
// First coefficient: 0x1.71547652b82fe1777d0ffda0d24p0
.invln2hi = 0x1.7154765200000p+0,
.invln2lo = 0x1.705fc2eefa200p-33,
.poly1 = {
// relative error: 0x1.2fad8188p-63
// in -0x1.5b51p-5 0x1.6ab2p-5
-0x1.71547652b82fep-1,
0x1.ec709dc3a03f7p-2,
-0x1.71547652b7c3fp-2,
0x1.2776c50f05be4p-2,
-0x1.ec709dd768fe5p-3,
0x1.a61761ec4e736p-3,
-0x1.7153fbc64a79bp-3,
0x1.484d154f01b4ap-3,
-0x1.289e4a72c383cp-3,
0x1.0b32f285aee66p-3,
},
.poly = {
// relative error: 0x1.a72c2bf8p-58
// abs error: 0x1.67a552c8p-66
// in -0x1.f45p-8 0x1.f45p-8
-0x1.71547652b8339p-1,
0x1.ec709dc3a04bep-2,
-0x1.7154764702ffbp-2,
0x1.2776c50034c48p-2,
-0x1.ec7b328ea92bcp-3,
0x1.a6225e117f92ep-3,
},
/* Algorithm:
x = 2^k z
log2(x) = k + log2(c) + log2(z/c)
log2(z/c) = poly(z/c - 1)
where z is in [1.6p-1; 1.6p0] which is split into N subintervals and z falls
into the ith one, then table entries are computed as
tab[i].invc = 1/c
tab[i].logc = (double)log2(c)
tab2[i].chi = (double)c
tab2[i].clo = (double)(c - (double)c)
where c is near the center of the subinterval and is chosen by trying +-2^29
floating point invc candidates around 1/center and selecting one for which
1) the rounding error in 0x1.8p10 + logc is 0,
2) the rounding error in z - chi - clo is < 0x1p-64 and
3) the rounding error in (double)log2(c) is minimized (< 0x1p-68).
Note: 1) ensures that k + logc can be computed without rounding error, 2)
ensures that z/c - 1 can be computed as (z - chi - clo)*invc with close to a
single rounding error when there is no fast fma for z*invc - 1, 3) ensures
that logc + poly(z/c - 1) has small error, however near x == 1 when
|log2(x)| < 0x1p-4, this is not enough so that is special cased. */
.tab = {
{0x1.724286bb1acf8p+0, -0x1.1095feecdb000p-1},
{0x1.6e1f766d2cca1p+0, -0x1.08494bd76d000p-1},
{0x1.6a13d0e30d48ap+0, -0x1.00143aee8f800p-1},
{0x1.661ec32d06c85p+0, -0x1.efec5360b4000p-2},
{0x1.623fa951198f8p+0, -0x1.dfdd91ab7e000p-2},
{0x1.5e75ba4cf026cp+0, -0x1.cffae0cc79000p-2},
{0x1.5ac055a214fb8p+0, -0x1.c043811fda000p-2},
{0x1.571ed0f166e1ep+0, -0x1.b0b67323ae000p-2},
{0x1.53909590bf835p+0, -0x1.a152f5a2db000p-2},
{0x1.5014fed61adddp+0, -0x1.9217f5af86000p-2},
{0x1.4cab88e487bd0p+0, -0x1.8304db0719000p-2},
{0x1.49539b4334feep+0, -0x1.74189f9a9e000p-2},
{0x1.460cbdfafd569p+0, -0x1.6552bb5199000p-2},
{0x1.42d664ee4b953p+0, -0x1.56b23a29b1000p-2},
{0x1.3fb01111dd8a6p+0, -0x1.483650f5fa000p-2},
{0x1.3c995b70c5836p+0, -0x1.39de937f6a000p-2},
{0x1.3991c4ab6fd4ap+0, -0x1.2baa1538d6000p-2},
{0x1.3698e0ce099b5p+0, -0x1.1d98340ca4000p-2},
{0x1.33ae48213e7b2p+0, -0x1.0fa853a40e000p-2},
{0x1.30d191985bdb1p+0, -0x1.01d9c32e73000p-2},
{0x1.2e025cab271d7p+0, -0x1.e857da2fa6000p-3},
{0x1.2b404cf13cd82p+0, -0x1.cd3c8633d8000p-3},
{0x1.288b02c7ccb50p+0, -0x1.b26034c14a000p-3},
{0x1.25e2263944de5p+0, -0x1.97c1c2f4fe000p-3},
{0x1.234563d8615b1p+0, -0x1.7d6023f800000p-3},
{0x1.20b46e33eaf38p+0, -0x1.633a71a05e000p-3},
{0x1.1e2eefdcda3ddp+0, -0x1.494f5e9570000p-3},
{0x1.1bb4a580b3930p+0, -0x1.2f9e424e0a000p-3},
{0x1.19453847f2200p+0, -0x1.162595afdc000p-3},
{0x1.16e06c0d5d73cp+0, -0x1.f9c9a75bd8000p-4},
{0x1.1485f47b7e4c2p+0, -0x1.c7b575bf9c000p-4},
{0x1.12358ad0085d1p+0, -0x1.960c60ff48000p-4},
{0x1.0fef00f532227p+0, -0x1.64ce247b60000p-4},
{0x1.0db2077d03a8fp+0, -0x1.33f78b2014000p-4},
{0x1.0b7e6d65980d9p+0, -0x1.0387d1a42c000p-4},
{0x1.0953efe7b408dp+0, -0x1.a6f9208b50000p-5},
{0x1.07325cac53b83p+0, -0x1.47a954f770000p-5},
{0x1.05197e40d1b5cp+0, -0x1.d23a8c50c0000p-6},
{0x1.03091c1208ea2p+0, -0x1.16a2629780000p-6},
{0x1.0101025b37e21p+0, -0x1.720f8d8e80000p-8},
{0x1.fc07ef9caa76bp-1, 0x1.6fe53b1500000p-7},
{0x1.f4465d3f6f184p-1, 0x1.11ccce10f8000p-5},
{0x1.ecc079f84107fp-1, 0x1.c4dfc8c8b8000p-5},
{0x1.e573a99975ae8p-1, 0x1.3aa321e574000p-4},
{0x1.de5d6f0bd3de6p-1, 0x1.918a0d08b8000p-4},
{0x1.d77b681ff38b3p-1, 0x1.e72e9da044000p-4},
{0x1.d0cb5724de943p-1, 0x1.1dcd2507f6000p-3},
{0x1.ca4b2dc0e7563p-1, 0x1.476ab03dea000p-3},
{0x1.c3f8ee8d6cb51p-1, 0x1.7074377e22000p-3},
{0x1.bdd2b4f020c4cp-1, 0x1.98ede8ba94000p-3},
{0x1.b7d6c006015cap-1, 0x1.c0db86ad2e000p-3},
{0x1.b20366e2e338fp-1, 0x1.e840aafcee000p-3},
{0x1.ac57026295039p-1, 0x1.0790ab4678000p-2},
{0x1.a6d01bc2731ddp-1, 0x1.1ac056801c000p-2},
{0x1.a16d3bc3ff18bp-1, 0x1.2db11d4fee000p-2},
{0x1.9c2d14967feadp-1, 0x1.406464ec58000p-2},
{0x1.970e4f47c9902p-1, 0x1.52dbe093af000p-2},
{0x1.920fb3982bcf2p-1, 0x1.651902050d000p-2},
{0x1.8d30187f759f1p-1, 0x1.771d2cdeaf000p-2},
{0x1.886e5ebb9f66dp-1, 0x1.88e9c857d9000p-2},
{0x1.83c97b658b994p-1, 0x1.9a80155e16000p-2},
{0x1.7f405ffc61022p-1, 0x1.abe186ed3d000p-2},
{0x1.7ad22181415cap-1, 0x1.bd0f2aea0e000p-2},
{0x1.767dcf99eff8cp-1, 0x1.ce0a43dbf4000p-2},
},
#if !__FP_FAST_FMA
.tab2 = {
{0x1.6200012b90a8ep-1, 0x1.904ab0644b605p-55},
{0x1.66000045734a6p-1, 0x1.1ff9bea62f7a9p-57},
{0x1.69fffc325f2c5p-1, 0x1.27ecfcb3c90bap-55},
{0x1.6e00038b95a04p-1, 0x1.8ff8856739326p-55},
{0x1.71fffe09994e3p-1, 0x1.afd40275f82b1p-55},
{0x1.7600015590e1p-1, -0x1.2fd75b4238341p-56},
{0x1.7a00012655bd5p-1, 0x1.808e67c242b76p-56},
{0x1.7e0003259e9a6p-1, -0x1.208e426f622b7p-57},
{0x1.81fffedb4b2d2p-1, -0x1.402461ea5c92fp-55},
{0x1.860002dfafcc3p-1, 0x1.df7f4a2f29a1fp-57},
{0x1.89ffff78c6b5p-1, -0x1.e0453094995fdp-55},
{0x1.8e00039671566p-1, -0x1.a04f3bec77b45p-55},
{0x1.91fffe2bf1745p-1, -0x1.7fa34400e203cp-56},
{0x1.95fffcc5c9fd1p-1, -0x1.6ff8005a0695dp-56},
{0x1.9a0003bba4767p-1, 0x1.0f8c4c4ec7e03p-56},
{0x1.9dfffe7b92da5p-1, 0x1.e7fd9478c4602p-55},
{0x1.a1fffd72efdafp-1, -0x1.a0c554dcdae7ep-57},
{0x1.a5fffde04ff95p-1, 0x1.67da98ce9b26bp-55},
{0x1.a9fffca5e8d2bp-1, -0x1.284c9b54c13dep-55},
{0x1.adfffddad03eap-1, 0x1.812c8ea602e3cp-58},
{0x1.b1ffff10d3d4dp-1, -0x1.efaddad27789cp-55},
{0x1.b5fffce21165ap-1, 0x1.3cb1719c61237p-58},
{0x1.b9fffd950e674p-1, 0x1.3f7d94194cep-56},
{0x1.be000139ca8afp-1, 0x1.50ac4215d9bcp-56},
{0x1.c20005b46df99p-1, 0x1.beea653e9c1c9p-57},
{0x1.c600040b9f7aep-1, -0x1.c079f274a70d6p-56},
{0x1.ca0006255fd8ap-1, -0x1.a0b4076e84c1fp-56},
{0x1.cdfffd94c095dp-1, 0x1.8f933f99ab5d7p-55},
{0x1.d1ffff975d6cfp-1, -0x1.82c08665fe1bep-58},
{0x1.d5fffa2561c93p-1, -0x1.b04289bd295f3p-56},
{0x1.d9fff9d228b0cp-1, 0x1.70251340fa236p-55},
{0x1.de00065bc7e16p-1, -0x1.5011e16a4d80cp-56},
{0x1.e200002f64791p-1, 0x1.9802f09ef62ep-55},
{0x1.e600057d7a6d8p-1, -0x1.e0b75580cf7fap-56},
{0x1.ea00027edc00cp-1, -0x1.c848309459811p-55},
{0x1.ee0006cf5cb7cp-1, -0x1.f8027951576f4p-55},
{0x1.f2000782b7dccp-1, -0x1.f81d97274538fp-55},
{0x1.f6000260c450ap-1, -0x1.071002727ffdcp-59},
{0x1.f9fffe88cd533p-1, -0x1.81bdce1fda8bp-58},
{0x1.fdfffd50f8689p-1, 0x1.7f91acb918e6ep-55},
{0x1.0200004292367p+0, 0x1.b7ff365324681p-54},
{0x1.05fffe3e3d668p+0, 0x1.6fa08ddae957bp-55},
{0x1.0a0000a85a757p+0, -0x1.7e2de80d3fb91p-58},
{0x1.0e0001a5f3fccp+0, -0x1.1823305c5f014p-54},
{0x1.11ffff8afbaf5p+0, -0x1.bfabb6680bac2p-55},
{0x1.15fffe54d91adp+0, -0x1.d7f121737e7efp-54},
{0x1.1a00011ac36e1p+0, 0x1.c000a0516f5ffp-54},
{0x1.1e00019c84248p+0, -0x1.082fbe4da5dap-54},
{0x1.220000ffe5e6ep+0, -0x1.8fdd04c9cfb43p-55},
{0x1.26000269fd891p+0, 0x1.cfe2a7994d182p-55},
{0x1.2a00029a6e6dap+0, -0x1.00273715e8bc5p-56},
{0x1.2dfffe0293e39p+0, 0x1.b7c39dab2a6f9p-54},
{0x1.31ffff7dcf082p+0, 0x1.df1336edc5254p-56},
{0x1.35ffff05a8b6p+0, -0x1.e03564ccd31ebp-54},
{0x1.3a0002e0eaeccp+0, 0x1.5f0e74bd3a477p-56},
{0x1.3e000043bb236p+0, 0x1.c7dcb149d8833p-54},
{0x1.4200002d187ffp+0, 0x1.e08afcf2d3d28p-56},
{0x1.460000d387cb1p+0, 0x1.20837856599a6p-55},
{0x1.4a00004569f89p+0, -0x1.9fa5c904fbcd2p-55},
{0x1.4e000043543f3p+0, -0x1.81125ed175329p-56},
{0x1.51fffcc027f0fp+0, 0x1.883d8847754dcp-54},
{0x1.55ffffd87b36fp+0, -0x1.709e731d02807p-55},
{0x1.59ffff21df7bap+0, 0x1.7f79f68727b02p-55},
{0x1.5dfffebfc3481p+0, -0x1.180902e30e93ep-54},
},
#endif
};

View File

@ -0,0 +1,28 @@
/*
* Copyright (c) 2018, Arm Limited.
* SPDX-License-Identifier: MIT
*/
#ifndef _LOG2_DATA_H
#define _LOG2_DATA_H
#include <features.h>
#define LOG2_TABLE_BITS 6
#define LOG2_POLY_ORDER 7
#define LOG2_POLY1_ORDER 11
extern const struct log2_data {
double invln2hi;
double invln2lo;
double poly[LOG2_POLY_ORDER - 1];
double poly1[LOG2_POLY1_ORDER - 1];
struct {
double invc, logc;
} tab[1 << LOG2_TABLE_BITS];
#if !__FP_FAST_FMA
struct {
double chi, clo;
} tab2[1 << LOG2_TABLE_BITS];
#endif
} __log2_data;
#endif

72
src/libc-shim/src/log2f.c Normal file
View File

@ -0,0 +1,72 @@
/*
* Single-precision log2 function.
*
* Copyright (c) 2017-2018, Arm Limited.
* SPDX-License-Identifier: MIT
*/
#include <math.h>
#include <stdint.h>
#include "libm.h"
#include "log2f_data.h"
/*
LOG2F_TABLE_BITS = 4
LOG2F_POLY_ORDER = 4
ULP error: 0.752 (nearest rounding.)
Relative error: 1.9 * 2^-26 (before rounding.)
*/
#define N (1 << LOG2F_TABLE_BITS)
#define T __log2f_data.tab
#define A __log2f_data.poly
#define OFF 0x3f330000
float log2f(float x)
{
double_t z, r, r2, p, y, y0, invc, logc;
uint32_t ix, iz, top, tmp;
int k, i;
ix = asuint(x);
/* Fix sign of zero with downward rounding when x==1. */
if (WANT_ROUNDING && predict_false(ix == 0x3f800000))
return 0;
if (predict_false(ix - 0x00800000 >= 0x7f800000 - 0x00800000)) {
/* x < 0x1p-126 or inf or nan. */
if (ix * 2 == 0)
return __math_divzerof(1);
if (ix == 0x7f800000) /* log2(inf) == inf. */
return x;
if ((ix & 0x80000000) || ix * 2 >= 0xff000000)
return __math_invalidf(x);
/* x is subnormal, normalize it. */
ix = asuint(x * 0x1p23f);
ix -= 23 << 23;
}
/* x = 2^k z; where z is in range [OFF,2*OFF] and exact.
The range is split into N subintervals.
The ith subinterval contains z and c is near its center. */
tmp = ix - OFF;
i = (tmp >> (23 - LOG2F_TABLE_BITS)) % N;
top = tmp & 0xff800000;
iz = ix - top;
k = (int32_t)tmp >> 23; /* arithmetic shift */
invc = T[i].invc;
logc = T[i].logc;
z = (double_t)asfloat(iz);
/* log2(x) = log1p(z/c-1)/ln2 + log2(c) + k */
r = z * invc - 1;
y0 = logc + (double_t)k;
/* Pipelined polynomial evaluation to approximate log1p(r)/ln2. */
r2 = r * r;
y = A[1] * r + A[2];
y = A[0] * r2 + y;
p = A[3] * r + y0;
y = y * r2 + p;
return eval_as_float(y);
}

View File

@ -0,0 +1,33 @@
/*
* Data definition for log2f.
*
* Copyright (c) 2017-2018, Arm Limited.
* SPDX-License-Identifier: MIT
*/
#include "log2f_data.h"
const struct log2f_data __log2f_data = {
.tab = {
{ 0x1.661ec79f8f3bep+0, -0x1.efec65b963019p-2 },
{ 0x1.571ed4aaf883dp+0, -0x1.b0b6832d4fca4p-2 },
{ 0x1.49539f0f010bp+0, -0x1.7418b0a1fb77bp-2 },
{ 0x1.3c995b0b80385p+0, -0x1.39de91a6dcf7bp-2 },
{ 0x1.30d190c8864a5p+0, -0x1.01d9bf3f2b631p-2 },
{ 0x1.25e227b0b8eap+0, -0x1.97c1d1b3b7afp-3 },
{ 0x1.1bb4a4a1a343fp+0, -0x1.2f9e393af3c9fp-3 },
{ 0x1.12358f08ae5bap+0, -0x1.960cbbf788d5cp-4 },
{ 0x1.0953f419900a7p+0, -0x1.a6f9db6475fcep-5 },
{ 0x1p+0, 0x0p+0 },
{ 0x1.e608cfd9a47acp-1, 0x1.338ca9f24f53dp-4 },
{ 0x1.ca4b31f026aap-1, 0x1.476a9543891bap-3 },
{ 0x1.b2036576afce6p-1, 0x1.e840b4ac4e4d2p-3 },
{ 0x1.9c2d163a1aa2dp-1, 0x1.40645f0c6651cp-2 },
{ 0x1.886e6037841edp-1, 0x1.88e9c2c1b9ff8p-2 },
{ 0x1.767dcf5534862p-1, 0x1.ce0a44eb17bccp-2 },
},
.poly = {
-0x1.712b6f70a7e4dp-2, 0x1.ecabf496832ep-2, -0x1.715479ffae3dep-1,
0x1.715475f35c8b8p0,
}
};

View File

@ -0,0 +1,19 @@
/*
* Copyright (c) 2017-2018, Arm Limited.
* SPDX-License-Identifier: MIT
*/
#ifndef _LOG2F_DATA_H
#define _LOG2F_DATA_H
#include <features.h>
#define LOG2F_TABLE_BITS 4
#define LOG2F_POLY_ORDER 4
extern const struct log2f_data {
struct {
double invc, logc;
} tab[1 << LOG2F_TABLE_BITS];
double poly[LOG2F_POLY_ORDER];
} __log2f_data;
#endif

View File

@ -0,0 +1,328 @@
/*
* Data for log.
*
* Copyright (c) 2018, Arm Limited.
* SPDX-License-Identifier: MIT
*/
#include "log_data.h"
#define N (1 << LOG_TABLE_BITS)
const struct log_data __log_data = {
.ln2hi = 0x1.62e42fefa3800p-1,
.ln2lo = 0x1.ef35793c76730p-45,
.poly1 = {
// relative error: 0x1.c04d76cp-63
// in -0x1p-4 0x1.09p-4 (|log(1+x)| > 0x1p-4 outside the interval)
-0x1p-1,
0x1.5555555555577p-2,
-0x1.ffffffffffdcbp-3,
0x1.999999995dd0cp-3,
-0x1.55555556745a7p-3,
0x1.24924a344de3p-3,
-0x1.fffffa4423d65p-4,
0x1.c7184282ad6cap-4,
-0x1.999eb43b068ffp-4,
0x1.78182f7afd085p-4,
-0x1.5521375d145cdp-4,
},
.poly = {
// relative error: 0x1.926199e8p-56
// abs error: 0x1.882ff33p-65
// in -0x1.fp-9 0x1.fp-9
-0x1.0000000000001p-1,
0x1.555555551305bp-2,
-0x1.fffffffeb459p-3,
0x1.999b324f10111p-3,
-0x1.55575e506c89fp-3,
},
/* Algorithm:
x = 2^k z
log(x) = k ln2 + log(c) + log(z/c)
log(z/c) = poly(z/c - 1)
where z is in [1.6p-1; 1.6p0] which is split into N subintervals and z falls
into the ith one, then table entries are computed as
tab[i].invc = 1/c
tab[i].logc = (double)log(c)
tab2[i].chi = (double)c
tab2[i].clo = (double)(c - (double)c)
where c is near the center of the subinterval and is chosen by trying +-2^29
floating point invc candidates around 1/center and selecting one for which
1) the rounding error in 0x1.8p9 + logc is 0,
2) the rounding error in z - chi - clo is < 0x1p-66 and
3) the rounding error in (double)log(c) is minimized (< 0x1p-66).
Note: 1) ensures that k*ln2hi + logc can be computed without rounding error,
2) ensures that z/c - 1 can be computed as (z - chi - clo)*invc with close to
a single rounding error when there is no fast fma for z*invc - 1, 3) ensures
that logc + poly(z/c - 1) has small error, however near x == 1 when
|log(x)| < 0x1p-4, this is not enough so that is special cased. */
.tab = {
{0x1.734f0c3e0de9fp+0, -0x1.7cc7f79e69000p-2},
{0x1.713786a2ce91fp+0, -0x1.76feec20d0000p-2},
{0x1.6f26008fab5a0p+0, -0x1.713e31351e000p-2},
{0x1.6d1a61f138c7dp+0, -0x1.6b85b38287800p-2},
{0x1.6b1490bc5b4d1p+0, -0x1.65d5590807800p-2},
{0x1.69147332f0cbap+0, -0x1.602d076180000p-2},
{0x1.6719f18224223p+0, -0x1.5a8ca86909000p-2},
{0x1.6524f99a51ed9p+0, -0x1.54f4356035000p-2},
{0x1.63356aa8f24c4p+0, -0x1.4f637c36b4000p-2},
{0x1.614b36b9ddc14p+0, -0x1.49da7fda85000p-2},
{0x1.5f66452c65c4cp+0, -0x1.445923989a800p-2},
{0x1.5d867b5912c4fp+0, -0x1.3edf439b0b800p-2},
{0x1.5babccb5b90dep+0, -0x1.396ce448f7000p-2},
{0x1.59d61f2d91a78p+0, -0x1.3401e17bda000p-2},
{0x1.5805612465687p+0, -0x1.2e9e2ef468000p-2},
{0x1.56397cee76bd3p+0, -0x1.2941b3830e000p-2},
{0x1.54725e2a77f93p+0, -0x1.23ec58cda8800p-2},
{0x1.52aff42064583p+0, -0x1.1e9e129279000p-2},
{0x1.50f22dbb2bddfp+0, -0x1.1956d2b48f800p-2},
{0x1.4f38f4734ded7p+0, -0x1.141679ab9f800p-2},
{0x1.4d843cfde2840p+0, -0x1.0edd094ef9800p-2},
{0x1.4bd3ec078a3c8p+0, -0x1.09aa518db1000p-2},
{0x1.4a27fc3e0258ap+0, -0x1.047e65263b800p-2},
{0x1.4880524d48434p+0, -0x1.feb224586f000p-3},
{0x1.46dce1b192d0bp+0, -0x1.f474a7517b000p-3},
{0x1.453d9d3391854p+0, -0x1.ea4443d103000p-3},
{0x1.43a2744b4845ap+0, -0x1.e020d44e9b000p-3},
{0x1.420b54115f8fbp+0, -0x1.d60a22977f000p-3},
{0x1.40782da3ef4b1p+0, -0x1.cc00104959000p-3},
{0x1.3ee8f5d57fe8fp+0, -0x1.c202956891000p-3},
{0x1.3d5d9a00b4ce9p+0, -0x1.b81178d811000p-3},
{0x1.3bd60c010c12bp+0, -0x1.ae2c9ccd3d000p-3},
{0x1.3a5242b75dab8p+0, -0x1.a45402e129000p-3},
{0x1.38d22cd9fd002p+0, -0x1.9a877681df000p-3},
{0x1.3755bc5847a1cp+0, -0x1.90c6d69483000p-3},
{0x1.35dce49ad36e2p+0, -0x1.87120a645c000p-3},
{0x1.34679984dd440p+0, -0x1.7d68fb4143000p-3},
{0x1.32f5cceffcb24p+0, -0x1.73cb83c627000p-3},
{0x1.3187775a10d49p+0, -0x1.6a39a9b376000p-3},
{0x1.301c8373e3990p+0, -0x1.60b3154b7a000p-3},
{0x1.2eb4ebb95f841p+0, -0x1.5737d76243000p-3},
{0x1.2d50a0219a9d1p+0, -0x1.4dc7b8fc23000p-3},
{0x1.2bef9a8b7fd2ap+0, -0x1.4462c51d20000p-3},
{0x1.2a91c7a0c1babp+0, -0x1.3b08abc830000p-3},
{0x1.293726014b530p+0, -0x1.31b996b490000p-3},
{0x1.27dfa5757a1f5p+0, -0x1.2875490a44000p-3},
{0x1.268b39b1d3bbfp+0, -0x1.1f3b9f879a000p-3},
{0x1.2539d838ff5bdp+0, -0x1.160c8252ca000p-3},
{0x1.23eb7aac9083bp+0, -0x1.0ce7f57f72000p-3},
{0x1.22a012ba940b6p+0, -0x1.03cdc49fea000p-3},
{0x1.2157996cc4132p+0, -0x1.f57bdbc4b8000p-4},
{0x1.201201dd2fc9bp+0, -0x1.e370896404000p-4},
{0x1.1ecf4494d480bp+0, -0x1.d17983ef94000p-4},
{0x1.1d8f5528f6569p+0, -0x1.bf9674ed8a000p-4},
{0x1.1c52311577e7cp+0, -0x1.adc79202f6000p-4},
{0x1.1b17c74cb26e9p+0, -0x1.9c0c3e7288000p-4},
{0x1.19e010c2c1ab6p+0, -0x1.8a646b372c000p-4},
{0x1.18ab07bb670bdp+0, -0x1.78d01b3ac0000p-4},
{0x1.1778a25efbcb6p+0, -0x1.674f145380000p-4},
{0x1.1648d354c31dap+0, -0x1.55e0e6d878000p-4},
{0x1.151b990275fddp+0, -0x1.4485cdea1e000p-4},
{0x1.13f0ea432d24cp+0, -0x1.333d94d6aa000p-4},
{0x1.12c8b7210f9dap+0, -0x1.22079f8c56000p-4},
{0x1.11a3028ecb531p+0, -0x1.10e4698622000p-4},
{0x1.107fbda8434afp+0, -0x1.ffa6c6ad20000p-5},
{0x1.0f5ee0f4e6bb3p+0, -0x1.dda8d4a774000p-5},
{0x1.0e4065d2a9fcep+0, -0x1.bbcece4850000p-5},
{0x1.0d244632ca521p+0, -0x1.9a1894012c000p-5},
{0x1.0c0a77ce2981ap+0, -0x1.788583302c000p-5},
{0x1.0af2f83c636d1p+0, -0x1.5715e67d68000p-5},
{0x1.09ddb98a01339p+0, -0x1.35c8a49658000p-5},
{0x1.08cabaf52e7dfp+0, -0x1.149e364154000p-5},
{0x1.07b9f2f4e28fbp+0, -0x1.e72c082eb8000p-6},
{0x1.06ab58c358f19p+0, -0x1.a55f152528000p-6},
{0x1.059eea5ecf92cp+0, -0x1.63d62cf818000p-6},
{0x1.04949cdd12c90p+0, -0x1.228fb8caa0000p-6},
{0x1.038c6c6f0ada9p+0, -0x1.c317b20f90000p-7},
{0x1.02865137932a9p+0, -0x1.419355daa0000p-7},
{0x1.0182427ea7348p+0, -0x1.81203c2ec0000p-8},
{0x1.008040614b195p+0, -0x1.0040979240000p-9},
{0x1.fe01ff726fa1ap-1, 0x1.feff384900000p-9},
{0x1.fa11cc261ea74p-1, 0x1.7dc41353d0000p-7},
{0x1.f6310b081992ep-1, 0x1.3cea3c4c28000p-6},
{0x1.f25f63ceeadcdp-1, 0x1.b9fc114890000p-6},
{0x1.ee9c8039113e7p-1, 0x1.1b0d8ce110000p-5},
{0x1.eae8078cbb1abp-1, 0x1.58a5bd001c000p-5},
{0x1.e741aa29d0c9bp-1, 0x1.95c8340d88000p-5},
{0x1.e3a91830a99b5p-1, 0x1.d276aef578000p-5},
{0x1.e01e009609a56p-1, 0x1.07598e598c000p-4},
{0x1.dca01e577bb98p-1, 0x1.253f5e30d2000p-4},
{0x1.d92f20b7c9103p-1, 0x1.42edd8b380000p-4},
{0x1.d5cac66fb5ccep-1, 0x1.606598757c000p-4},
{0x1.d272caa5ede9dp-1, 0x1.7da76356a0000p-4},
{0x1.cf26e3e6b2ccdp-1, 0x1.9ab434e1c6000p-4},
{0x1.cbe6da2a77902p-1, 0x1.b78c7bb0d6000p-4},
{0x1.c8b266d37086dp-1, 0x1.d431332e72000p-4},
{0x1.c5894bd5d5804p-1, 0x1.f0a3171de6000p-4},
{0x1.c26b533bb9f8cp-1, 0x1.067152b914000p-3},
{0x1.bf583eeece73fp-1, 0x1.147858292b000p-3},
{0x1.bc4fd75db96c1p-1, 0x1.2266ecdca3000p-3},
{0x1.b951e0c864a28p-1, 0x1.303d7a6c55000p-3},
{0x1.b65e2c5ef3e2cp-1, 0x1.3dfc33c331000p-3},
{0x1.b374867c9888bp-1, 0x1.4ba366b7a8000p-3},
{0x1.b094b211d304ap-1, 0x1.5933928d1f000p-3},
{0x1.adbe885f2ef7ep-1, 0x1.66acd2418f000p-3},
{0x1.aaf1d31603da2p-1, 0x1.740f8ec669000p-3},
{0x1.a82e63fd358a7p-1, 0x1.815c0f51af000p-3},
{0x1.a5740ef09738bp-1, 0x1.8e92954f68000p-3},
{0x1.a2c2a90ab4b27p-1, 0x1.9bb3602f84000p-3},
{0x1.a01a01393f2d1p-1, 0x1.a8bed1c2c0000p-3},
{0x1.9d79f24db3c1bp-1, 0x1.b5b515c01d000p-3},
{0x1.9ae2505c7b190p-1, 0x1.c2967ccbcc000p-3},
{0x1.9852ef297ce2fp-1, 0x1.cf635d5486000p-3},
{0x1.95cbaeea44b75p-1, 0x1.dc1bd3446c000p-3},
{0x1.934c69de74838p-1, 0x1.e8c01b8cfe000p-3},
{0x1.90d4f2f6752e6p-1, 0x1.f5509c0179000p-3},
{0x1.8e6528effd79dp-1, 0x1.00e6c121fb800p-2},
{0x1.8bfce9fcc007cp-1, 0x1.071b80e93d000p-2},
{0x1.899c0dabec30ep-1, 0x1.0d46b9e867000p-2},
{0x1.87427aa2317fbp-1, 0x1.13687334bd000p-2},
{0x1.84f00acb39a08p-1, 0x1.1980d67234800p-2},
{0x1.82a49e8653e55p-1, 0x1.1f8ffe0cc8000p-2},
{0x1.8060195f40260p-1, 0x1.2595fd7636800p-2},
{0x1.7e22563e0a329p-1, 0x1.2b9300914a800p-2},
{0x1.7beb377dcb5adp-1, 0x1.3187210436000p-2},
{0x1.79baa679725c2p-1, 0x1.377266dec1800p-2},
{0x1.77907f2170657p-1, 0x1.3d54ffbaf3000p-2},
{0x1.756cadbd6130cp-1, 0x1.432eee32fe000p-2},
},
#if !__FP_FAST_FMA
.tab2 = {
{0x1.61000014fb66bp-1, 0x1.e026c91425b3cp-56},
{0x1.63000034db495p-1, 0x1.dbfea48005d41p-55},
{0x1.650000d94d478p-1, 0x1.e7fa786d6a5b7p-55},
{0x1.67000074e6fadp-1, 0x1.1fcea6b54254cp-57},
{0x1.68ffffedf0faep-1, -0x1.c7e274c590efdp-56},
{0x1.6b0000763c5bcp-1, -0x1.ac16848dcda01p-55},
{0x1.6d0001e5cc1f6p-1, 0x1.33f1c9d499311p-55},
{0x1.6efffeb05f63ep-1, -0x1.e80041ae22d53p-56},
{0x1.710000e86978p-1, 0x1.bff6671097952p-56},
{0x1.72ffffc67e912p-1, 0x1.c00e226bd8724p-55},
{0x1.74fffdf81116ap-1, -0x1.e02916ef101d2p-57},
{0x1.770000f679c9p-1, -0x1.7fc71cd549c74p-57},
{0x1.78ffffa7ec835p-1, 0x1.1bec19ef50483p-55},
{0x1.7affffe20c2e6p-1, -0x1.07e1729cc6465p-56},
{0x1.7cfffed3fc9p-1, -0x1.08072087b8b1cp-55},
{0x1.7efffe9261a76p-1, 0x1.dc0286d9df9aep-55},
{0x1.81000049ca3e8p-1, 0x1.97fd251e54c33p-55},
{0x1.8300017932c8fp-1, -0x1.afee9b630f381p-55},
{0x1.850000633739cp-1, 0x1.9bfbf6b6535bcp-55},
{0x1.87000204289c6p-1, -0x1.bbf65f3117b75p-55},
{0x1.88fffebf57904p-1, -0x1.9006ea23dcb57p-55},
{0x1.8b00022bc04dfp-1, -0x1.d00df38e04b0ap-56},
{0x1.8cfffe50c1b8ap-1, -0x1.8007146ff9f05p-55},
{0x1.8effffc918e43p-1, 0x1.3817bd07a7038p-55},
{0x1.910001efa5fc7p-1, 0x1.93e9176dfb403p-55},
{0x1.9300013467bb9p-1, 0x1.f804e4b980276p-56},
{0x1.94fffe6ee076fp-1, -0x1.f7ef0d9ff622ep-55},
{0x1.96fffde3c12d1p-1, -0x1.082aa962638bap-56},
{0x1.98ffff4458a0dp-1, -0x1.7801b9164a8efp-55},
{0x1.9afffdd982e3ep-1, -0x1.740e08a5a9337p-55},
{0x1.9cfffed49fb66p-1, 0x1.fce08c19bep-60},
{0x1.9f00020f19c51p-1, -0x1.a3faa27885b0ap-55},
{0x1.a10001145b006p-1, 0x1.4ff489958da56p-56},
{0x1.a300007bbf6fap-1, 0x1.cbeab8a2b6d18p-55},
{0x1.a500010971d79p-1, 0x1.8fecadd78793p-55},
{0x1.a70001df52e48p-1, -0x1.f41763dd8abdbp-55},
{0x1.a90001c593352p-1, -0x1.ebf0284c27612p-55},
{0x1.ab0002a4f3e4bp-1, -0x1.9fd043cff3f5fp-57},
{0x1.acfffd7ae1ed1p-1, -0x1.23ee7129070b4p-55},
{0x1.aefffee510478p-1, 0x1.a063ee00edea3p-57},
{0x1.b0fffdb650d5bp-1, 0x1.a06c8381f0ab9p-58},
{0x1.b2ffffeaaca57p-1, -0x1.9011e74233c1dp-56},
{0x1.b4fffd995badcp-1, -0x1.9ff1068862a9fp-56},
{0x1.b7000249e659cp-1, 0x1.aff45d0864f3ep-55},
{0x1.b8ffff987164p-1, 0x1.cfe7796c2c3f9p-56},
{0x1.bafffd204cb4fp-1, -0x1.3ff27eef22bc4p-57},
{0x1.bcfffd2415c45p-1, -0x1.cffb7ee3bea21p-57},
{0x1.beffff86309dfp-1, -0x1.14103972e0b5cp-55},
{0x1.c0fffe1b57653p-1, 0x1.bc16494b76a19p-55},
{0x1.c2ffff1fa57e3p-1, -0x1.4feef8d30c6edp-57},
{0x1.c4fffdcbfe424p-1, -0x1.43f68bcec4775p-55},
{0x1.c6fffed54b9f7p-1, 0x1.47ea3f053e0ecp-55},
{0x1.c8fffeb998fd5p-1, 0x1.383068df992f1p-56},
{0x1.cb0002125219ap-1, -0x1.8fd8e64180e04p-57},
{0x1.ccfffdd94469cp-1, 0x1.e7ebe1cc7ea72p-55},
{0x1.cefffeafdc476p-1, 0x1.ebe39ad9f88fep-55},
{0x1.d1000169af82bp-1, 0x1.57d91a8b95a71p-56},
{0x1.d30000d0ff71dp-1, 0x1.9c1906970c7dap-55},
{0x1.d4fffea790fc4p-1, -0x1.80e37c558fe0cp-58},
{0x1.d70002edc87e5p-1, -0x1.f80d64dc10f44p-56},
{0x1.d900021dc82aap-1, -0x1.47c8f94fd5c5cp-56},
{0x1.dafffd86b0283p-1, 0x1.c7f1dc521617ep-55},
{0x1.dd000296c4739p-1, 0x1.8019eb2ffb153p-55},
{0x1.defffe54490f5p-1, 0x1.e00d2c652cc89p-57},
{0x1.e0fffcdabf694p-1, -0x1.f8340202d69d2p-56},
{0x1.e2fffdb52c8ddp-1, 0x1.b00c1ca1b0864p-56},
{0x1.e4ffff24216efp-1, 0x1.2ffa8b094ab51p-56},
{0x1.e6fffe88a5e11p-1, -0x1.7f673b1efbe59p-58},
{0x1.e9000119eff0dp-1, -0x1.4808d5e0bc801p-55},
{0x1.eafffdfa51744p-1, 0x1.80006d54320b5p-56},
{0x1.ed0001a127fa1p-1, -0x1.002f860565c92p-58},
{0x1.ef00007babcc4p-1, -0x1.540445d35e611p-55},
{0x1.f0ffff57a8d02p-1, -0x1.ffb3139ef9105p-59},
{0x1.f30001ee58ac7p-1, 0x1.a81acf2731155p-55},
{0x1.f4ffff5823494p-1, 0x1.a3f41d4d7c743p-55},
{0x1.f6ffffca94c6bp-1, -0x1.202f41c987875p-57},
{0x1.f8fffe1f9c441p-1, 0x1.77dd1f477e74bp-56},
{0x1.fafffd2e0e37ep-1, -0x1.f01199a7ca331p-57},
{0x1.fd0001c77e49ep-1, 0x1.181ee4bceacb1p-56},
{0x1.feffff7e0c331p-1, -0x1.e05370170875ap-57},
{0x1.00ffff465606ep+0, -0x1.a7ead491c0adap-55},
{0x1.02ffff3867a58p+0, -0x1.77f69c3fcb2ep-54},
{0x1.04ffffdfc0d17p+0, 0x1.7bffe34cb945bp-54},
{0x1.0700003cd4d82p+0, 0x1.20083c0e456cbp-55},
{0x1.08ffff9f2cbe8p+0, -0x1.dffdfbe37751ap-57},
{0x1.0b000010cda65p+0, -0x1.13f7faee626ebp-54},
{0x1.0d00001a4d338p+0, 0x1.07dfa79489ff7p-55},
{0x1.0effffadafdfdp+0, -0x1.7040570d66bcp-56},
{0x1.110000bbafd96p+0, 0x1.e80d4846d0b62p-55},
{0x1.12ffffae5f45dp+0, 0x1.dbffa64fd36efp-54},
{0x1.150000dd59ad9p+0, 0x1.a0077701250aep-54},
{0x1.170000f21559ap+0, 0x1.dfdf9e2e3deeep-55},
{0x1.18ffffc275426p+0, 0x1.10030dc3b7273p-54},
{0x1.1b000123d3c59p+0, 0x1.97f7980030188p-54},
{0x1.1cffff8299eb7p+0, -0x1.5f932ab9f8c67p-57},
{0x1.1effff48ad4p+0, 0x1.37fbf9da75bebp-54},
{0x1.210000c8b86a4p+0, 0x1.f806b91fd5b22p-54},
{0x1.2300003854303p+0, 0x1.3ffc2eb9fbf33p-54},
{0x1.24fffffbcf684p+0, 0x1.601e77e2e2e72p-56},
{0x1.26ffff52921d9p+0, 0x1.ffcbb767f0c61p-56},
{0x1.2900014933a3cp+0, -0x1.202ca3c02412bp-56},
{0x1.2b00014556313p+0, -0x1.2808233f21f02p-54},
{0x1.2cfffebfe523bp+0, -0x1.8ff7e384fdcf2p-55},
{0x1.2f0000bb8ad96p+0, -0x1.5ff51503041c5p-55},
{0x1.30ffffb7ae2afp+0, -0x1.10071885e289dp-55},
{0x1.32ffffeac5f7fp+0, -0x1.1ff5d3fb7b715p-54},
{0x1.350000ca66756p+0, 0x1.57f82228b82bdp-54},
{0x1.3700011fbf721p+0, 0x1.000bac40dd5ccp-55},
{0x1.38ffff9592fb9p+0, -0x1.43f9d2db2a751p-54},
{0x1.3b00004ddd242p+0, 0x1.57f6b707638e1p-55},
{0x1.3cffff5b2c957p+0, 0x1.a023a10bf1231p-56},
{0x1.3efffeab0b418p+0, 0x1.87f6d66b152bp-54},
{0x1.410001532aff4p+0, 0x1.7f8375f198524p-57},
{0x1.4300017478b29p+0, 0x1.301e672dc5143p-55},
{0x1.44fffe795b463p+0, 0x1.9ff69b8b2895ap-55},
{0x1.46fffe80475ep+0, -0x1.5c0b19bc2f254p-54},
{0x1.48fffef6fc1e7p+0, 0x1.b4009f23a2a72p-54},
{0x1.4afffe5bea704p+0, -0x1.4ffb7bf0d7d45p-54},
{0x1.4d000171027dep+0, -0x1.9c06471dc6a3dp-54},
{0x1.4f0000ff03ee2p+0, 0x1.77f890b85531cp-54},
{0x1.5100012dc4bd1p+0, 0x1.004657166a436p-57},
{0x1.530001605277ap+0, -0x1.6bfcece233209p-54},
{0x1.54fffecdb704cp+0, -0x1.902720505a1d7p-55},
{0x1.56fffef5f54a9p+0, 0x1.bbfe60ec96412p-54},
{0x1.5900017e61012p+0, 0x1.87ec581afef9p-55},
{0x1.5b00003c93e92p+0, -0x1.f41080abf0ccp-54},
{0x1.5d0001d4919bcp+0, -0x1.8812afb254729p-54},
{0x1.5efffe7b87a89p+0, -0x1.47eb780ed6904p-54},
},
#endif
};

View File

@ -0,0 +1,28 @@
/*
* Copyright (c) 2018, Arm Limited.
* SPDX-License-Identifier: MIT
*/
#ifndef _LOG_DATA_H
#define _LOG_DATA_H
#include <features.h>
#define LOG_TABLE_BITS 7
#define LOG_POLY_ORDER 6
#define LOG_POLY1_ORDER 12
extern const struct log_data {
double ln2hi;
double ln2lo;
double poly[LOG_POLY_ORDER - 1]; /* First coefficient is 1. */
double poly1[LOG_POLY1_ORDER - 1];
struct {
double invc, logc;
} tab[1 << LOG_TABLE_BITS];
#if !__FP_FAST_FMA
struct {
double chi, clo;
} tab2[1 << LOG_TABLE_BITS];
#endif
} __log_data;
#endif

71
src/libc-shim/src/logf.c Normal file
View File

@ -0,0 +1,71 @@
/*
* Single-precision log function.
*
* Copyright (c) 2017-2018, Arm Limited.
* SPDX-License-Identifier: MIT
*/
#include <math.h>
#include <stdint.h>
#include "libm.h"
#include "logf_data.h"
/*
LOGF_TABLE_BITS = 4
LOGF_POLY_ORDER = 4
ULP error: 0.818 (nearest rounding.)
Relative error: 1.957 * 2^-26 (before rounding.)
*/
#define T __logf_data.tab
#define A __logf_data.poly
#define Ln2 __logf_data.ln2
#define N (1 << LOGF_TABLE_BITS)
#define OFF 0x3f330000
float logf(float x)
{
double_t z, r, r2, y, y0, invc, logc;
uint32_t ix, iz, tmp;
int k, i;
ix = asuint(x);
/* Fix sign of zero with downward rounding when x==1. */
if (WANT_ROUNDING && predict_false(ix == 0x3f800000))
return 0;
if (predict_false(ix - 0x00800000 >= 0x7f800000 - 0x00800000)) {
/* x < 0x1p-126 or inf or nan. */
if (ix * 2 == 0)
return __math_divzerof(1);
if (ix == 0x7f800000) /* log(inf) == inf. */
return x;
if ((ix & 0x80000000) || ix * 2 >= 0xff000000)
return __math_invalidf(x);
/* x is subnormal, normalize it. */
ix = asuint(x * 0x1p23f);
ix -= 23 << 23;
}
/* x = 2^k z; where z is in range [OFF,2*OFF] and exact.
The range is split into N subintervals.
The ith subinterval contains z and c is near its center. */
tmp = ix - OFF;
i = (tmp >> (23 - LOGF_TABLE_BITS)) % N;
k = (int32_t)tmp >> 23; /* arithmetic shift */
iz = ix - (tmp & 0xff800000);
invc = T[i].invc;
logc = T[i].logc;
z = (double_t)asfloat(iz);
/* log(x) = log1p(z/c-1) + log(c) + k*Ln2 */
r = z * invc - 1;
y0 = logc + (double_t)k * Ln2;
/* Pipelined polynomial evaluation to approximate log1p(r). */
r2 = r * r;
y = A[1] * r + A[2];
y = A[0] * r2 + y;
y = y * r2 + (y0 + r);
return eval_as_float(y);
}

View File

@ -0,0 +1,33 @@
/*
* Data definition for logf.
*
* Copyright (c) 2017-2018, Arm Limited.
* SPDX-License-Identifier: MIT
*/
#include "logf_data.h"
const struct logf_data __logf_data = {
.tab = {
{ 0x1.661ec79f8f3bep+0, -0x1.57bf7808caadep-2 },
{ 0x1.571ed4aaf883dp+0, -0x1.2bef0a7c06ddbp-2 },
{ 0x1.49539f0f010bp+0, -0x1.01eae7f513a67p-2 },
{ 0x1.3c995b0b80385p+0, -0x1.b31d8a68224e9p-3 },
{ 0x1.30d190c8864a5p+0, -0x1.6574f0ac07758p-3 },
{ 0x1.25e227b0b8eap+0, -0x1.1aa2bc79c81p-3 },
{ 0x1.1bb4a4a1a343fp+0, -0x1.a4e76ce8c0e5ep-4 },
{ 0x1.12358f08ae5bap+0, -0x1.1973c5a611cccp-4 },
{ 0x1.0953f419900a7p+0, -0x1.252f438e10c1ep-5 },
{ 0x1p+0, 0x0p+0 },
{ 0x1.e608cfd9a47acp-1, 0x1.aa5aa5df25984p-5 },
{ 0x1.ca4b31f026aap-1, 0x1.c5e53aa362eb4p-4 },
{ 0x1.b2036576afce6p-1, 0x1.526e57720db08p-3 },
{ 0x1.9c2d163a1aa2dp-1, 0x1.bc2860d22477p-3 },
{ 0x1.886e6037841edp-1, 0x1.1058bc8a07ee1p-2 },
{ 0x1.767dcf5534862p-1, 0x1.4043057b6ee09p-2 },
},
.ln2 = 0x1.62e42fefa39efp-1,
.poly = {
-0x1.00ea348b88334p-2, 0x1.5575b0be00b6ap-2, -0x1.ffffef20a4123p-2,
}
};

View File

@ -0,0 +1,20 @@
/*
* Copyright (c) 2017-2018, Arm Limited.
* SPDX-License-Identifier: MIT
*/
#ifndef _LOGF_DATA_H
#define _LOGF_DATA_H
#include <features.h>
#define LOGF_TABLE_BITS 4
#define LOGF_POLY_ORDER 4
extern const struct logf_data {
struct {
double invc, logc;
} tab[1 << LOGF_TABLE_BITS];
double ln2;
double poly[LOGF_POLY_ORDER - 1]; /* First order coefficient is 1. */
} __logf_data;
#endif

187
src/libc-shim/src/powf.c Normal file
View File

@ -0,0 +1,187 @@
/*
* Copyright (c) 2017-2018, Arm Limited.
* SPDX-License-Identifier: MIT
*/
#include <math.h>
#include <stdint.h>
#include "libm.h"
#include "exp2f_data.h"
#include "powf_data.h"
/*
POWF_LOG2_POLY_ORDER = 5
EXP2F_TABLE_BITS = 5
ULP error: 0.82 (~ 0.5 + relerr*2^24)
relerr: 1.27 * 2^-26 (Relative error ~= 128*Ln2*relerr_log2 + relerr_exp2)
relerr_log2: 1.83 * 2^-33 (Relative error of logx.)
relerr_exp2: 1.69 * 2^-34 (Relative error of exp2(ylogx).)
*/
#define N (1 << POWF_LOG2_TABLE_BITS)
#define T __powf_log2_data.tab
#define A __powf_log2_data.poly
#define OFF 0x3f330000
/* Subnormal input is normalized so ix has negative biased exponent.
Output is multiplied by N (POWF_SCALE) if TOINT_INTRINICS is set. */
static inline double_t log2_inline(uint32_t ix)
{
double_t z, r, r2, r4, p, q, y, y0, invc, logc;
uint32_t iz, top, tmp;
int k, i;
/* x = 2^k z; where z is in range [OFF,2*OFF] and exact.
The range is split into N subintervals.
The ith subinterval contains z and c is near its center. */
tmp = ix - OFF;
i = (tmp >> (23 - POWF_LOG2_TABLE_BITS)) % N;
top = tmp & 0xff800000;
iz = ix - top;
k = (int32_t)top >> (23 - POWF_SCALE_BITS); /* arithmetic shift */
invc = T[i].invc;
logc = T[i].logc;
z = (double_t)asfloat(iz);
/* log2(x) = log1p(z/c-1)/ln2 + log2(c) + k */
r = z * invc - 1;
y0 = logc + (double_t)k;
/* Pipelined polynomial evaluation to approximate log1p(r)/ln2. */
r2 = r * r;
y = A[0] * r + A[1];
p = A[2] * r + A[3];
r4 = r2 * r2;
q = A[4] * r + y0;
q = p * r2 + q;
y = y * r4 + q;
return y;
}
#undef N
#undef T
#define N (1 << EXP2F_TABLE_BITS)
#define T __exp2f_data.tab
#define SIGN_BIAS (1 << (EXP2F_TABLE_BITS + 11))
/* The output of log2 and thus the input of exp2 is either scaled by N
(in case of fast toint intrinsics) or not. The unscaled xd must be
in [-1021,1023], sign_bias sets the sign of the result. */
static inline float exp2_inline(double_t xd, uint32_t sign_bias)
{
uint64_t ki, ski, t;
double_t kd, z, r, r2, y, s;
#if TOINT_INTRINSICS
#define C __exp2f_data.poly_scaled
/* N*x = k + r with r in [-1/2, 1/2] */
kd = roundtoint(xd); /* k */
ki = converttoint(xd);
#else
#define C __exp2f_data.poly
#define SHIFT __exp2f_data.shift_scaled
/* x = k/N + r with r in [-1/(2N), 1/(2N)] */
kd = eval_as_double(xd + SHIFT);
ki = asuint64(kd);
kd -= SHIFT; /* k/N */
#endif
r = xd - kd;
/* exp2(x) = 2^(k/N) * 2^r ~= s * (C0*r^3 + C1*r^2 + C2*r + 1) */
t = T[ki % N];
ski = ki + sign_bias;
t += ski << (52 - EXP2F_TABLE_BITS);
s = asdouble(t);
z = C[0] * r + C[1];
r2 = r * r;
y = C[2] * r + 1;
y = z * r2 + y;
y = y * s;
return eval_as_float(y);
}
/* Returns 0 if not int, 1 if odd int, 2 if even int. The argument is
the bit representation of a non-zero finite floating-point value. */
static inline int checkint(uint32_t iy)
{
int e = iy >> 23 & 0xff;
if (e < 0x7f)
return 0;
if (e > 0x7f + 23)
return 2;
if (iy & ((1 << (0x7f + 23 - e)) - 1))
return 0;
if (iy & (1 << (0x7f + 23 - e)))
return 1;
return 2;
}
static inline int zeroinfnan(uint32_t ix)
{
return 2 * ix - 1 >= 2u * 0x7f800000 - 1;
}
float powf(float x, float y)
{
uint32_t sign_bias = 0;
uint32_t ix, iy;
ix = asuint(x);
iy = asuint(y);
if (predict_false(ix - 0x00800000 >= 0x7f800000 - 0x00800000 ||
zeroinfnan(iy))) {
/* Either (x < 0x1p-126 or inf or nan) or (y is 0 or inf or nan). */
if (predict_false(zeroinfnan(iy))) {
if (2 * iy == 0)
return issignalingf_inline(x) ? x + y : 1.0f;
if (ix == 0x3f800000)
return issignalingf_inline(y) ? x + y : 1.0f;
if (2 * ix > 2u * 0x7f800000 ||
2 * iy > 2u * 0x7f800000)
return x + y;
if (2 * ix == 2 * 0x3f800000)
return 1.0f;
if ((2 * ix < 2 * 0x3f800000) == !(iy & 0x80000000))
return 0.0f; /* |x|<1 && y==inf or |x|>1 && y==-inf. */
return y * y;
}
if (predict_false(zeroinfnan(ix))) {
float_t x2 = x * x;
if (ix & 0x80000000 && checkint(iy) == 1)
x2 = -x2;
/* Without the barrier some versions of clang hoist the 1/x2 and
thus division by zero exception can be signaled spuriously. */
// NOTE(orca): no fp barriers
//return iy & 0x80000000 ? fp_barrierf(1 / x2) : x2;
return iy & 0x80000000 ? (1 / x2) : x2;
}
/* x and y are non-zero finite. */
if (ix & 0x80000000) {
/* Finite x < 0. */
int yint = checkint(iy);
if (yint == 0)
return __math_invalidf(x);
if (yint == 1)
sign_bias = SIGN_BIAS;
ix &= 0x7fffffff;
}
if (ix < 0x00800000) {
/* Normalize subnormal x so exponent becomes negative. */
ix = asuint(x * 0x1p23f);
ix &= 0x7fffffff;
ix -= 23 << 23;
}
}
double_t logx = log2_inline(ix);
double_t ylogx = y * logx; /* cannot overflow, y is single prec. */
if (predict_false((asuint64(ylogx) >> 47 & 0xffff) >=
asuint64(126.0 * POWF_SCALE) >> 47)) {
/* |y*log(x)| >= 126. */
if (ylogx > 0x1.fffffffd1d571p+6 * POWF_SCALE)
return __math_oflowf(sign_bias);
if (ylogx <= -150.0 * POWF_SCALE)
return __math_uflowf(sign_bias);
}
return exp2_inline(ylogx, sign_bias);
}

View File

@ -0,0 +1,34 @@
/*
* Data definition for powf.
*
* Copyright (c) 2017-2018, Arm Limited.
* SPDX-License-Identifier: MIT
*/
#include "powf_data.h"
const struct powf_log2_data __powf_log2_data = {
.tab = {
{ 0x1.661ec79f8f3bep+0, -0x1.efec65b963019p-2 * POWF_SCALE },
{ 0x1.571ed4aaf883dp+0, -0x1.b0b6832d4fca4p-2 * POWF_SCALE },
{ 0x1.49539f0f010bp+0, -0x1.7418b0a1fb77bp-2 * POWF_SCALE },
{ 0x1.3c995b0b80385p+0, -0x1.39de91a6dcf7bp-2 * POWF_SCALE },
{ 0x1.30d190c8864a5p+0, -0x1.01d9bf3f2b631p-2 * POWF_SCALE },
{ 0x1.25e227b0b8eap+0, -0x1.97c1d1b3b7afp-3 * POWF_SCALE },
{ 0x1.1bb4a4a1a343fp+0, -0x1.2f9e393af3c9fp-3 * POWF_SCALE },
{ 0x1.12358f08ae5bap+0, -0x1.960cbbf788d5cp-4 * POWF_SCALE },
{ 0x1.0953f419900a7p+0, -0x1.a6f9db6475fcep-5 * POWF_SCALE },
{ 0x1p+0, 0x0p+0 * POWF_SCALE },
{ 0x1.e608cfd9a47acp-1, 0x1.338ca9f24f53dp-4 * POWF_SCALE },
{ 0x1.ca4b31f026aap-1, 0x1.476a9543891bap-3 * POWF_SCALE },
{ 0x1.b2036576afce6p-1, 0x1.e840b4ac4e4d2p-3 * POWF_SCALE },
{ 0x1.9c2d163a1aa2dp-1, 0x1.40645f0c6651cp-2 * POWF_SCALE },
{ 0x1.886e6037841edp-1, 0x1.88e9c2c1b9ff8p-2 * POWF_SCALE },
{ 0x1.767dcf5534862p-1, 0x1.ce0a44eb17bccp-2 * POWF_SCALE },
},
.poly = {
0x1.27616c9496e0bp-2 * POWF_SCALE, -0x1.71969a075c67ap-2 * POWF_SCALE,
0x1.ec70a6ca7baddp-2 * POWF_SCALE, -0x1.7154748bef6c8p-1 * POWF_SCALE,
0x1.71547652ab82bp0 * POWF_SCALE,
}
};

View File

@ -0,0 +1,26 @@
/*
* Copyright (c) 2017-2018, Arm Limited.
* SPDX-License-Identifier: MIT
*/
#ifndef _POWF_DATA_H
#define _POWF_DATA_H
#include "libm.h"
#include "exp2f_data.h"
#define POWF_LOG2_TABLE_BITS 4
#define POWF_LOG2_POLY_ORDER 5
#if TOINT_INTRINSICS
#define POWF_SCALE_BITS EXP2F_TABLE_BITS
#else
#define POWF_SCALE_BITS 0
#endif
#define POWF_SCALE ((double)(1 << POWF_SCALE_BITS))
extern const struct powf_log2_data {
struct {
double invc, logc;
} tab[1 << POWF_LOG2_TABLE_BITS];
double poly[POWF_LOG2_POLY_ORDER];
} __powf_log2_data;
#endif

72
src/libc-shim/src/tan.c Normal file
View File

@ -0,0 +1,72 @@
/* origin: FreeBSD /usr/src/lib/msun/src/s_tan.c */
/*
* ====================================================
* Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
*
* Developed at SunPro, a Sun Microsystems, Inc. business.
* Permission to use, copy, modify, and distribute this
* software is freely granted, provided that this notice
* is preserved.
* ====================================================
*/
/* tan(x)
* Return tangent function of x.
*
* kernel function:
* __tan ... tangent function on [-pi/4,pi/4]
* __rem_pio2 ... argument reduction routine
*
* Method.
* Let S,C and T denote the sin, cos and tan respectively on
* [-PI/4, +PI/4]. Reduce the argument x to y1+y2 = x-k*pi/2
* in [-pi/4 , +pi/4], and let n = k mod 4.
* We have
*
* n sin(x) cos(x) tan(x)
* ----------------------------------------------------------
* 0 S C T
* 1 C -S -1/T
* 2 -S -C T
* 3 -C S -1/T
* ----------------------------------------------------------
*
* Special cases:
* Let trig be any of sin, cos, or tan.
* trig(+-INF) is NaN, with signals;
* trig(NaN) is that NaN;
*
* Accuracy:
* TRIG(x) returns trig(x) nearly rounded
*/
#include "libm.h"
double __tan(double x, double y, int odd);
double tan(double x)
{
double y[2];
uint32_t ix;
unsigned n;
GET_HIGH_WORD(ix, x);
ix &= 0x7fffffff;
/* |x| ~< pi/4 */
if (ix <= 0x3fe921fb) {
if (ix < 0x3e400000) { /* |x| < 2**-27 */
/* raise inexact if x!=0 and underflow if subnormal */
FORCE_EVAL(ix < 0x00100000 ? x/0x1p120f : x+0x1p120f);
return x;
}
return __tan(x, 0.0, 0);
}
/* tan(Inf or NaN) is NaN */
if (ix >= 0x7ff00000)
return x - x;
/* argument reduction */
n = __rem_pio2(x, y);
return __tan(y[0], y[1], n&1);
}

66
src/libc-shim/src/tanf.c Normal file
View File

@ -0,0 +1,66 @@
/* origin: FreeBSD /usr/src/lib/msun/src/s_tanf.c */
/*
* Conversion to float by Ian Lance Taylor, Cygnus Support, ian@cygnus.com.
* Optimized by Bruce D. Evans.
*/
/*
* ====================================================
* Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
*
* Developed at SunPro, a Sun Microsystems, Inc. business.
* Permission to use, copy, modify, and distribute this
* software is freely granted, provided that this notice
* is preserved.
* ====================================================
*/
#include "libm.h"
/* Small multiples of pi/2 rounded to double precision. */
static const double
t1pio2 = 1*M_PI_2, /* 0x3FF921FB, 0x54442D18 */
t2pio2 = 2*M_PI_2, /* 0x400921FB, 0x54442D18 */
t3pio2 = 3*M_PI_2, /* 0x4012D97C, 0x7F3321D2 */
t4pio2 = 4*M_PI_2; /* 0x401921FB, 0x54442D18 */
float __tandf(double x, int odd);
float tanf(float x)
{
double y;
uint32_t ix;
unsigned n, sign;
GET_FLOAT_WORD(ix, x);
sign = ix >> 31;
ix &= 0x7fffffff;
if (ix <= 0x3f490fda) { /* |x| ~<= pi/4 */
if (ix < 0x39800000) { /* |x| < 2**-12 */
/* raise inexact if x!=0 and underflow if subnormal */
FORCE_EVAL(ix < 0x00800000 ? x/0x1p120f : x+0x1p120f);
return x;
}
return __tandf(x, 0);
}
if (ix <= 0x407b53d1) { /* |x| ~<= 5*pi/4 */
if (ix <= 0x4016cbe3) /* |x| ~<= 3pi/4 */
return __tandf((sign ? x+t1pio2 : x-t1pio2), 1);
else
return __tandf((sign ? x+t2pio2 : x-t2pio2), 0);
}
if (ix <= 0x40e231d5) { /* |x| ~<= 9*pi/4 */
if (ix <= 0x40afeddf) /* |x| ~<= 7*pi/4 */
return __tandf((sign ? x+t3pio2 : x-t3pio2), 1);
else
return __tandf((sign ? x+t4pio2 : x-t4pio2), 0);
}
/* tan(Inf or NaN) is NaN */
if (ix >= 0x7f800000)
return x - x;
/* argument reduction */
n = __rem_pio2f(x, &y);
return __tandf(y, n&1);
}

View File

@ -45,8 +45,8 @@ oc_log_output* OC_LOG_DEFAULT_OUTPUT = &oc_logDefaultOutput;
void platform_log_push(oc_log_output* output,
oc_log_level level,
const char* file,
const char* function,
const char* file,
int line,
const char* fmt,
va_list ap)

View File

@ -50,18 +50,18 @@ static oc_log_output oc_logDefaultOutput = { .kind = ORCA_LOG_OUTPUT_CONSOLE };
oc_log_output* OC_LOG_DEFAULT_OUTPUT = &oc_logDefaultOutput;
void ORCA_IMPORT(oc_bridge_log)(oc_log_level level,
int fileLen,
const char* file,
int functionLen,
const char* function,
int fileLen,
const char* file,
int line,
int msgLen,
const char* msg);
void platform_log_push(oc_log_output* output,
oc_log_level level,
const char* file,
const char* function,
const char* file,
int line,
const char* fmt,
va_list ap)
@ -76,7 +76,7 @@ void platform_log_push(oc_log_output* output,
oc_str8 string = oc_str8_list_join(scratch.arena, ctx.list);
oc_bridge_log(level, strlen(file), file, strlen(function), function, line, oc_str8_ip(string));
oc_bridge_log(level, strlen(function), function, strlen(file), file, line, oc_str8_ip(string));
oc_scratch_end(scratch);
}

View File

@ -28,8 +28,8 @@ void oc_log_set_level(oc_log_level level)
void platform_log_push(oc_log_output* output,
oc_log_level level,
const char* file,
const char* function,
const char* file,
int line,
const char* fmt,
va_list ap);
@ -50,7 +50,7 @@ void oc_log_ext(oc_log_level level,
{
va_list ap;
va_start(ap, fmt);
platform_log_push(__logConfig.output, level, file, function, line, fmt, ap);
platform_log_push(__logConfig.output, level, function, file, line, fmt, ap);
va_end(ap);
}
}

View File

@ -134,10 +134,10 @@ void oc_bridge_clipboard_set_string(oc_wasm_str8 value)
}
void oc_bridge_log(oc_log_level level,
int fileLen,
char* file,
int functionLen,
char* function,
int fileLen,
char* file,
int line,
int msgLen,
char* msg)
@ -179,14 +179,14 @@ void oc_bridge_log(oc_log_level level,
}
char* payload = (char*)entry + sizeof(log_entry);
entry->file.len = fileLen;
entry->file.ptr = payload;
payload += entry->file.len;
entry->function.len = functionLen;
entry->function.ptr = payload;
payload += entry->function.len;
entry->file.len = fileLen;
entry->file.ptr = payload;
payload += entry->file.len;
entry->msg.len = msgLen;
entry->msg.ptr = payload;
payload += entry->msg.len;
@ -203,8 +203,8 @@ void oc_bridge_log(oc_log_level level,
oc_list_push_back(&debug->logEntries, &entry->listElt);
oc_log_ext(level,
file,
function,
file,
line,
"%.*s\n",
msgLen,
@ -279,10 +279,14 @@ void orca_surface_render_commands(oc_surface surface,
char* memBase = app->env.wasmMemory.ptr;
u32 memSize = app->env.wasmMemory.committed;
oc_rect window_content_rect = oc_window_get_content_rect(app->window);
if(((char*)primitives > memBase)
&& ((char*)primitives + primitiveCount * sizeof(oc_primitive) - memBase <= memSize)
&& ((char*)elements > memBase)
&& ((char*)elements + eltCount * sizeof(oc_path_elt) - memBase <= memSize)
&& window_content_rect.w > 0
&& window_content_rect.h > 0
&& oc_window_is_minimized(app->window) == false)
{
oc_surface_render_commands(surface,
@ -352,8 +356,8 @@ void log_entry_ui(oc_debug_overlay* overlay, log_entry* entry)
oc_str8 loc = oc_str8_pushf(scratch.arena,
"%.*s() in %.*s:%i:",
oc_str8_ip(entry->file),
oc_str8_ip(entry->function),
oc_str8_ip(entry->file),
entry->line);
oc_ui_label_str8(loc);
}
@ -680,6 +684,20 @@ i32 orca_runloop(void* user)
}
break;
case OC_EVENT_MOUSE_WHEEL:
{
if(exports[OC_EXPORT_MOUSE_WHEEL])
{
const void* args[2] = { &event->mouse.deltaX, &event->mouse.deltaY };
M3Result res = m3_Call(exports[OC_EXPORT_MOUSE_WHEEL], 2, args);
if(res)
{
ORCA_WASM3_ABORT(app->env.m3Runtime, res, "Runtime error");
}
}
}
break;
case OC_EVENT_MOUSE_MOVE:
{
if(exports[OC_EXPORT_MOUSE_MOVE])

View File

@ -5,25 +5,33 @@
* See LICENSE.txt for licensing information
*
**************************************************************************/
#include <limits.h>
#include "runtime.h"
#include "runtime_memory.h"
void* oc_wasm_memory_resize_callback(void* p, unsigned long size, void* userData)
void* oc_wasm_memory_resize_callback(void* p, unsigned long newSize, void* userData)
{
//NOTE: this is called by wasm3. The size passed includes wasm3 memory header.
// We first align it on 4K page size
newSize = oc_align_up_pow2(newSize, 4 << 10);
oc_wasm_memory* memory = (oc_wasm_memory*)userData;
if(memory->committed >= size)
if(memory->committed >= newSize)
{
return (memory->ptr);
}
else if(memory->committed < memory->reserved)
else if(newSize <= memory->reserved)
{
u32 commitSize = size - memory->committed;
u32 commitSize = newSize - memory->committed;
oc_base_allocator* allocator = oc_base_allocator_default();
oc_base_commit(allocator, memory->ptr + memory->committed, commitSize);
memory->committed += commitSize;
OC_DEBUG_ASSERT((memory->committed & 0xfff) == 0, "Committed pointer is not aligned on page size");
return (memory->ptr);
}
else
@ -47,16 +55,21 @@ extern u32 oc_mem_grow(u64 size)
oc_wasm_env* env = oc_runtime_get_env();
oc_wasm_memory* memory = &env->wasmMemory;
size = oc_align_up_pow2(size, d_m3MemPageSize);
u64 totalSize = size + m3_GetMemorySize(env->m3Runtime);
u32 oldMemSize = m3_GetMemorySize(env->m3Runtime);
u32 addr = memory->committed;
//NOTE: compute total size and align on wasm memory page size
OC_ASSERT(oldMemSize <= UINT_MAX - size, "Memory size overflow");
u64 newMemSize = size + oldMemSize;
newMemSize = oc_align_up_pow2(newMemSize, d_m3MemPageSize);
//NOTE: call resize memory, which will call our custom resize callback... this is a bit involved because
// wasm3 doesn't allow resizing the memory directly
M3Result res = ResizeMemory(env->m3Runtime, totalSize / d_m3MemPageSize);
M3Result res = ResizeMemory(env->m3Runtime, newMemSize / d_m3MemPageSize);
return (addr);
OC_DEBUG_ASSERT(oldMemSize + size <= m3_GetMemorySize(env->m3Runtime), "Memory returned by oc_mem_grow overflows wasm memory");
return (oldMemSize);
}
void* oc_wasm_address_to_ptr(oc_wasm_addr addr, oc_wasm_size size)

View File

@ -8,8 +8,84 @@
#include "hash.h"
#include "platform/platform.h"
#if OC_ARCH_X64
#include <immintrin.h>
//xxhash64, copy-pasted from https://github.com/demetri/scribbles/blob/master/hashing/hash_functions.c
// Thanks to Demetri Spanos
uint64_t xxh_64(const void* key, int len, uint64_t h)
{
// primes used in mul-rot updates
uint64_t p1 = 0x9e3779b185ebca87, p2 = 0xc2b2ae3d27d4eb4f,
p3 = 0x165667b19e3779f9, p4 = 0x85ebca77c2b2ae63, p5 = 0x27d4eb2f165667c5;
// inital 32-byte (4x8) wide hash state
uint64_t s[4] = { h + p1 + p2, h + p2, h, h - p1 };
// bulk work: process all 32 byte blocks
uint64_t* k32 = (uint64_t*)key;
for(int i = 0; i < (len / 32); i += 4)
{
uint64_t b[4] = { k32[i + 0], k32[i + 1], k32[i + 2], k32[i + 3] };
for(int j = 0; j < 4; j++)
b[j] = b[j] * p2 + s[j];
for(int j = 0; j < 4; j++)
s[j] = ((b[j] << 31) | (b[j] >> 33)) * p1;
}
// mix 32-byte state down to 8-byte state, initalize to value for short keys
uint64_t s64 = (s[2] + p5);
if(len > 32)
{
s64 = ((s[0] << 1) | (s[0] >> 63)) + ((s[1] << 7) | (s[1] >> 57)) + ((s[2] << 12) | (s[2] >> 52)) + ((s[3] << 18) | (s[3] >> 46));
for(int i = 0; i < 4; i++)
{
uint64_t ps = (((s[i] * p2) << 31) | ((s[i] * p2) >> 33)) * p1;
s64 = (s64 ^ ps) * p1 + p4;
}
}
s64 += len;
// up to 31 bytes remain, process 0-3 8 byte blocks
uint8_t* tail = (uint8_t*)(((char*)key) + (len / 32) * 32);
for(int i = 0; i < (len & 31) / 8; i++, tail += 8)
{
uint64_t b = (*((uint64_t*)tail)) * p2;
b = (((b << 31) | (b >> 33)) * p1) ^ s64;
s64 = ((b << 27) | (b >> 37)) * p1 + p4;
}
// up to 7 bytes remain, process 0-1 4 byte block
for(int i = 0; i < (len & 7) / 4; i++, tail += 4)
{
uint64_t b = s64 ^ (*(uint32_t*)tail) * p1;
s64 = ((b << 23) | (b >> 41)) * p2 + p3;
}
// up to 3 bytes remain, process 0-3 1 byte blocks
for(int i = 0; i < (len & 3); i++, tail++)
{
uint64_t b = s64 ^ (*tail) * p5;
s64 = ((b << 11) | (b >> 53)) * p1;
}
// finalization mix
s64 = (s64 ^ (s64 >> 33)) * p2;
s64 = (s64 ^ (s64 >> 29)) * p3;
return (s64 ^ (s64 >> 32));
}
u64 oc_hash_xx64_string_seed(oc_str8 string, u64 seed)
{
return (xxh_64(string.ptr, string.len, seed));
}
u64 oc_hash_xx64_string(oc_str8 string)
{
return (xxh_64(string.ptr, string.len, 0));
}
#if 0 //NOTE(martin): keep that here cause we could want to use them when aes is available, but we don't for now
#if OC_ARCH_X64
#include <immintrin.h>
u64 oc_hash_aes_u64(u64 x)
{
@ -127,79 +203,5 @@ u64 oc_hash_aes_string_seed(oc_str8 string, u64 seed)
u64 result = _mm_extract_epi64(hash, 0);
return (result);
}
#endif // OC_ARCH_X64
//xxhash64, copy-pasted from https://github.com/demetri/scribbles/blob/master/hashing/hash_functions.c
// Thanks to Demetri Spanos
uint64_t xxh_64(const void* key, int len, uint64_t h)
{
// primes used in mul-rot updates
uint64_t p1 = 0x9e3779b185ebca87, p2 = 0xc2b2ae3d27d4eb4f,
p3 = 0x165667b19e3779f9, p4 = 0x85ebca77c2b2ae63, p5 = 0x27d4eb2f165667c5;
// inital 32-byte (4x8) wide hash state
uint64_t s[4] = { h + p1 + p2, h + p2, h, h - p1 };
// bulk work: process all 32 byte blocks
uint64_t* k32 = (uint64_t*)key;
for(int i = 0; i < (len / 32); i += 4)
{
uint64_t b[4] = { k32[i + 0], k32[i + 1], k32[i + 2], k32[i + 3] };
for(int j = 0; j < 4; j++)
b[j] = b[j] * p2 + s[j];
for(int j = 0; j < 4; j++)
s[j] = ((b[j] << 31) | (b[j] >> 33)) * p1;
}
// mix 32-byte state down to 8-byte state, initalize to value for short keys
uint64_t s64 = (s[2] + p5);
if(len > 32)
{
s64 = ((s[0] << 1) | (s[0] >> 63)) + ((s[1] << 7) | (s[1] >> 57)) + ((s[2] << 12) | (s[2] >> 52)) + ((s[3] << 18) | (s[3] >> 46));
for(int i = 0; i < 4; i++)
{
uint64_t ps = (((s[i] * p2) << 31) | ((s[i] * p2) >> 33)) * p1;
s64 = (s64 ^ ps) * p1 + p4;
}
}
s64 += len;
// up to 31 bytes remain, process 0-3 8 byte blocks
uint8_t* tail = (uint8_t*)(((char*)key) + (len / 32) * 32);
for(int i = 0; i < (len & 31) / 8; i++, tail += 8)
{
uint64_t b = (*((uint64_t*)tail)) * p2;
b = (((b << 31) | (b >> 33)) * p1) ^ s64;
s64 = ((b << 27) | (b >> 37)) * p1 + p4;
}
// up to 7 bytes remain, process 0-1 4 byte block
for(int i = 0; i < (len & 7) / 4; i++, tail += 4)
{
uint64_t b = s64 ^ (*(uint32_t*)tail) * p1;
s64 = ((b << 23) | (b >> 41)) * p2 + p3;
}
// up to 3 bytes remain, process 0-3 1 byte blocks
for(int i = 0; i < (len & 3); i++, tail++)
{
uint64_t b = s64 ^ (*tail) * p5;
s64 = ((b << 11) | (b >> 53)) * p1;
}
// finalization mix
s64 = (s64 ^ (s64 >> 33)) * p2;
s64 = (s64 ^ (s64 >> 29)) * p3;
return (s64 ^ (s64 >> 32));
}
u64 oc_hash_xx64_string_seed(oc_str8 string, u64 seed)
{
return (xxh_64(string.ptr, string.len, seed));
}
u64 oc_hash_xx64_string(oc_str8 string)
{
return (xxh_64(string.ptr, string.len, 0));
}
#endif // OC_ARCH_X64
#endif // 0

View File

@ -12,17 +12,11 @@
#include "typedefs.h"
#ifdef __cplusplus
extern "C"
{
extern "C" {
#endif
ORCA_API u64 oc_hash_aes_u64(u64 x);
ORCA_API u64 oc_hash_aes_u64_x2(u64 x, u64 y);
ORCA_API u64 oc_hash_aes_string(oc_str8 string);
ORCA_API u64 oc_hash_aes_string_seed(oc_str8 string, u64 seed);
ORCA_API u64 oc_hash_xx64_string_seed(oc_str8 string, u64 seed);
ORCA_API u64 oc_hash_xx64_string(oc_str8 string);
ORCA_API u64 oc_hash_xx64_string_seed(oc_str8 string, u64 seed);
ORCA_API u64 oc_hash_xx64_string(oc_str8 string);
#ifdef __cplusplus
} // extern "C"

View File

@ -13,27 +13,27 @@
#if OC_PLATFORM_ORCA
enum
{
OC_ARENA_DEFAULT_RESERVE_SIZE = 1 << 20
OC_ARENA_DEFAULT_RESERVE_SIZE = 1 << 20,
};
#else
enum
{
OC_ARENA_DEFAULT_RESERVE_SIZE = 1 << 30
OC_ARENA_DEFAULT_RESERVE_SIZE = 1 << 30,
};
#endif
enum
{
OC_ARENA_COMMIT_ALIGNMENT = 4 << 10
OC_ARENA_COMMIT_ALIGNMENT = 4 << 10,
};
//--------------------------------------------------------------------------------
//NOTE(martin): memory arena
//--------------------------------------------------------------------------------
oc_arena_chunk* oc_arena_chunk_alloc(oc_arena* arena, u64 reserveSize)
oc_arena_chunk* oc_arena_chunk_alloc(oc_arena* arena, u64 chunkMinSize)
{
reserveSize = oc_align_up_pow2(reserveSize, OC_ARENA_COMMIT_ALIGNMENT);
u64 reserveSize = oc_align_up_pow2(chunkMinSize + sizeof(oc_arena_chunk), OC_ARENA_COMMIT_ALIGNMENT);
u64 commitSize = oc_align_up_pow2(sizeof(oc_arena_chunk), OC_ARENA_COMMIT_ALIGNMENT);
char* mem = oc_base_reserve(arena->base, reserveSize);
@ -77,18 +77,25 @@ void oc_arena_cleanup(oc_arena* arena)
}
void* oc_arena_push(oc_arena* arena, u64 size)
{
return oc_arena_push_aligned(arena, size, 1);
}
void* oc_arena_push_aligned(oc_arena* arena, u64 size, u32 alignment)
{
oc_arena_chunk* chunk = arena->currentChunk;
OC_ASSERT(chunk);
u64 nextOffset = chunk->offset + size;
u64 alignedOffset = oc_align_up_pow2(chunk->offset, alignment);
u64 nextOffset = alignedOffset + size;
u64 lastCap = chunk->cap;
while(nextOffset > chunk->cap)
{
chunk = oc_list_next_entry(arena->chunks, chunk, oc_arena_chunk, listElt);
if(chunk)
{
nextOffset = chunk->offset + size;
alignedOffset = oc_align_up_pow2(chunk->offset, alignment);
nextOffset = alignedOffset + size;
lastCap = chunk->cap;
}
else
@ -98,10 +105,11 @@ void* oc_arena_push(oc_arena* arena, u64 size)
}
if(!chunk)
{
u64 reserveSize = oc_max(lastCap * 1.5, size);
u64 chunkMinSize = oc_max(lastCap * 1.5, size + alignment);
chunk = oc_arena_chunk_alloc(arena, reserveSize);
nextOffset = chunk->offset + size;
chunk = oc_arena_chunk_alloc(arena, chunkMinSize);
alignedOffset = oc_align_up_pow2(chunk->offset, alignment);
nextOffset = alignedOffset + size;
}
OC_ASSERT(nextOffset <= chunk->cap);
@ -115,8 +123,8 @@ void* oc_arena_push(oc_arena* arena, u64 size)
oc_base_commit(arena->base, chunk->ptr + chunk->committed, commitSize);
chunk->committed = nextCommitted;
}
char* p = chunk->ptr + chunk->offset;
chunk->offset += size;
char* p = chunk->ptr + alignedOffset;
chunk->offset = nextOffset;
return (p);
}

View File

@ -55,13 +55,14 @@ ORCA_API void oc_arena_init_with_options(oc_arena* arena, oc_arena_options* opti
ORCA_API void oc_arena_cleanup(oc_arena* arena);
ORCA_API void* oc_arena_push(oc_arena* arena, u64 size);
ORCA_API void* oc_arena_push_aligned(oc_arena* arena, u64 size, u32 alignment);
ORCA_API void oc_arena_clear(oc_arena* arena);
ORCA_API oc_arena_scope oc_arena_scope_begin(oc_arena* arena);
ORCA_API void oc_arena_scope_end(oc_arena_scope scope);
#define oc_arena_push_type(arena, type) ((type*)oc_arena_push(arena, sizeof(type)))
#define oc_arena_push_array(arena, type, count) ((type*)oc_arena_push(arena, sizeof(type) * (count)))
#define oc_arena_push_type(arena, type) ((type*)oc_arena_push_aligned(arena, sizeof(type), _Alignof(type)))
#define oc_arena_push_array(arena, type, count) ((type*)oc_arena_push_aligned(arena, sizeof(type) * (count), _Alignof(type)))
//--------------------------------------------------------------------------------
//NOTE(martin): memory pool

View File

@ -5,16 +5,16 @@
"ret": {"name": "void", "tag": "v"},
"args": [ {"name": "level",
"type": {"name": "oc_log_level", "tag": "i"}},
{"name": "fileLen",
"type": {"name": "int", "tag": "i"}},
{"name": "file",
"type": {"name": "char*", "tag": "p"},
"len": {"count": "fileLen"}},
{"name": "functionLen",
"type": {"name": "int", "tag": "i"}},
{"name": "function",
"type": {"name": "char*", "tag": "p"},
"len": {"count": "functionLen"}},
{"name": "fileLen",
"type": {"name": "int", "tag": "i"}},
{"name": "file",
"type": {"name": "char*", "tag": "p"},
"len": {"count": "fileLen"}},
{"name": "line",
"type": {"name": "int", "tag": "i"}},
{"name": "msgLen",