Compare commits

..

No commits in common. "master" and "claude/issue-58" have entirely different histories.

185 changed files with 1371 additions and 8134 deletions

1
.gitignore vendored
View file

@ -1,3 +1,2 @@
build/
bin/
pipeline_cache.bin

176
LICENSE
View file

@ -1,165 +1,65 @@
GNU LESSER GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
GNU LESSER GENERAL PUBLIC LICENSE
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.
Version 3, 29 June 2007
Copyright © 2007 Free Software Foundation, Inc. <https://fsf.org/>
This version of the GNU Lesser General Public License incorporates
the terms and conditions of version 3 of the GNU General Public
License, supplemented by the additional permissions listed below.
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
0. Additional Definitions.
This version of the GNU Lesser General Public License incorporates the terms and conditions of version 3 of the GNU General Public License, supplemented by the additional permissions listed below.
0. Additional Definitions.
As used herein, "this License" refers to version 3 of the GNU Lesser
General Public License, and the "GNU GPL" refers to version 3 of the GNU
General Public License.
As used herein, “this License” refers to version 3 of the GNU Lesser General Public License, and the “GNU GPL” refers to version 3 of the GNU General Public License.
"The Library" refers to a covered work governed by this License,
other than an Application or a Combined Work as defined below.
“The Library” refers to a covered work governed by this License, other than an Application or a Combined Work as defined below.
An "Application" is any work that makes use of an interface provided
by the Library, but which is not otherwise based on the Library.
Defining a subclass of a class defined by the Library is deemed a mode
of using an interface provided by the Library.
An “Application” is any work that makes use of an interface provided by the Library, but which is not otherwise based on the Library. Defining a subclass of a class defined by the Library is deemed a mode of using an interface provided by the Library.
A "Combined Work" is a work produced by combining or linking an
Application with the Library. The particular version of the Library
with which the Combined Work was made is also called the "Linked
Version".
A “Combined Work” is a work produced by combining or linking an Application with the Library. The particular version of the Library with which the Combined Work was made is also called the “Linked Version”.
The "Minimal Corresponding Source" for a Combined Work means the
Corresponding Source for the Combined Work, excluding any source code
for portions of the Combined Work that, considered in isolation, are
based on the Application, and not on the Linked Version.
The “Minimal Corresponding Source” for a Combined Work means the Corresponding Source for the Combined Work, excluding any source code for portions of the Combined Work that, considered in isolation, are based on the Application, and not on the Linked Version.
The "Corresponding Application Code" for a Combined Work means the
object code and/or source code for the Application, including any data
and utility programs needed for reproducing the Combined Work from the
Application, but excluding the System Libraries of the Combined Work.
The “Corresponding Application Code” for a Combined Work means the object code and/or source code for the Application, including any data and utility programs needed for reproducing the Combined Work from the Application, but excluding the System Libraries of the Combined Work.
1. Exception to Section 3 of the GNU GPL.
1. Exception to Section 3 of the GNU GPL.
You may convey a covered work under sections 3 and 4 of this License without being bound by section 3 of the GNU GPL.
2. Conveying Modified Versions.
You may convey a covered work under sections 3 and 4 of this License
without being bound by section 3 of the GNU GPL.
If you modify a copy of the Library, and, in your modifications, a facility refers to a function or data to be supplied by an Application that uses the facility (other than as an argument passed when the facility is invoked), then you may convey a copy of the modified version:
2. Conveying Modified Versions.
a) under this License, provided that you make a good faith effort to ensure that, in the event an Application does not supply the function or data, the facility still operates, and performs whatever part of its purpose remains meaningful, or
b) under the GNU GPL, with none of the additional permissions of this License applicable to that copy.
If you modify a copy of the Library, and, in your modifications, a
facility refers to a function or data to be supplied by an Application
that uses the facility (other than as an argument passed when the
facility is invoked), then you may convey a copy of the modified
version:
3. Object Code Incorporating Material from Library Header Files.
a) under this License, provided that you make a good faith effort to
ensure that, in the event an Application does not supply the
function or data, the facility still operates, and performs
whatever part of its purpose remains meaningful, or
The object code form of an Application may incorporate material from a header file that is part of the Library. You may convey such object code under terms of your choice, provided that, if the incorporated material is not limited to numerical parameters, data structure layouts and accessors, or small macros, inline functions and templates (ten or fewer lines in length), you do both of the following:
b) under the GNU GPL, with none of the additional permissions of
this License applicable to that copy.
a) Give prominent notice with each copy of the object code that the Library is used in it and that the Library and its use are covered by this License.
b) Accompany the object code with a copy of the GNU GPL and this license document.
3. Object Code Incorporating Material from Library Header Files.
4. Combined Works.
The object code form of an Application may incorporate material from
a header file that is part of the Library. You may convey such object
code under terms of your choice, provided that, if the incorporated
material is not limited to numerical parameters, data structure
layouts and accessors, or small macros, inline functions and templates
(ten or fewer lines in length), you do both of the following:
a) Give prominent notice with each copy of the object code that the
Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the object code with a copy of the GNU GPL and this license
document.
4. Combined Works.
You may convey a Combined Work under terms of your choice that,
taken together, effectively do not restrict modification of the
portions of the Library contained in the Combined Work and reverse
engineering for debugging such modifications, if you also do each of
the following:
a) Give prominent notice with each copy of the Combined Work that
the Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the Combined Work with a copy of the GNU GPL and this license
document.
c) For a Combined Work that displays copyright notices during
execution, include the copyright notice for the Library among
these notices, as well as a reference directing the user to the
copies of the GNU GPL and this license document.
You may convey a Combined Work under terms of your choice that, taken together, effectively do not restrict modification of the portions of the Library contained in the Combined Work and reverse engineering for debugging such modifications, if you also do each of the following:
a) Give prominent notice with each copy of the Combined Work that the Library is used in it and that the Library and its use are covered by this License.
b) Accompany the Combined Work with a copy of the GNU GPL and this license document.
c) For a Combined Work that displays copyright notices during execution, include the copyright notice for the Library among these notices, as well as a reference directing the user to the copies of the GNU GPL and this license document.
d) Do one of the following:
0) Convey the Minimal Corresponding Source under the terms of this License, and the Corresponding Application Code in a form suitable for, and under terms that permit, the user to recombine or relink the Application with a modified version of the Linked Version to produce a modified Combined Work, in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.
1) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (a) uses at run time a copy of the Library already present on the user's computer system, and (b) will operate properly with a modified version of the Library that is interface-compatible with the Linked Version.
e) Provide Installation Information, but only if you would otherwise be required to provide such information under section 6 of the GNU GPL, and only to the extent that such information is necessary to install and execute a modified version of the Combined Work produced by recombining or relinking the Application with a modified version of the Linked Version. (If you use option 4d0, the Installation Information must accompany the Minimal Corresponding Source and Corresponding Application Code. If you use option 4d1, you must provide the Installation Information in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.)
0) Convey the Minimal Corresponding Source under the terms of this
License, and the Corresponding Application Code in a form
suitable for, and under terms that permit, the user to
recombine or relink the Application with a modified version of
the Linked Version to produce a modified Combined Work, in the
manner specified by section 6 of the GNU GPL for conveying
Corresponding Source.
5. Combined Libraries.
1) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (a) uses at run time
a copy of the Library already present on the user's computer
system, and (b) will operate properly with a modified version
of the Library that is interface-compatible with the Linked
Version.
You may place library facilities that are a work based on the Library side by side in a single library together with other library facilities that are not Applications and are not covered by this License, and convey such a combined library under terms of your choice, if you do both of the following:
e) Provide Installation Information, but only if you would otherwise
be required to provide such information under section 6 of the
GNU GPL, and only to the extent that such information is
necessary to install and execute a modified version of the
Combined Work produced by recombining or relinking the
Application with a modified version of the Linked Version. (If
you use option 4d0, the Installation Information must accompany
the Minimal Corresponding Source and Corresponding Application
Code. If you use option 4d1, you must provide the Installation
Information in the manner specified by section 6 of the GNU GPL
for conveying Corresponding Source.)
a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities, conveyed under the terms of this License.
b) Give prominent notice with the combined library that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work.
5. Combined Libraries.
6. Revised Versions of the GNU Lesser General Public License.
You may place library facilities that are a work based on the
Library side by side in a single library together with other library
facilities that are not Applications and are not covered by this
License, and convey such a combined library under terms of your
choice, if you do both of the following:
The Free Software Foundation may publish revised and/or new versions of the GNU Lesser 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.
a) Accompany the combined library with a copy of the same work based
on the Library, uncombined with any other library facilities,
conveyed under the terms of this License.
Each version is given a distinguishing version number. If the Library as you received it specifies that a certain numbered version of the GNU Lesser General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that published version or of any later version published by the Free Software Foundation. If the Library as you received it does not specify a version number of the GNU Lesser General Public License, you may choose any version of the GNU Lesser General Public License ever published by the Free Software Foundation.
b) Give prominent notice with the combined library that part of it
is a work based on the Library, and explaining where to find the
accompanying uncombined form of the same work.
6. Revised Versions of the GNU Lesser General Public License.
The Free Software Foundation may publish revised and/or new versions
of the GNU Lesser 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
Library as you received it specifies that a certain numbered version
of the GNU Lesser General Public License "or any later version"
applies to it, you have the option of following the terms and
conditions either of that published version or of any later version
published by the Free Software Foundation. If the Library as you
received it does not specify a version number of the GNU Lesser
General Public License, you may choose any version of the GNU Lesser
General Public License ever published by the Free Software Foundation.
If the Library as you received it specifies that a proxy can decide
whether future versions of the GNU Lesser General Public License shall
apply, that proxy's public statement of acceptance of any version is
permanent authorization for you to choose that version for the
Library.
If the Library as you received it specifies that a proxy can decide whether future versions of the GNU Lesser General Public License shall apply, that proxy's public statement of acceptance of any version is permanent authorization for you to choose that version for the Library.

View file

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

View file

@ -222,13 +222,4 @@ See [examples/](examples/). Quick map:
## License
This library is licensed under the GNU Lesser General Public License, version 3 only (LGPL-3.0-only). See [LICENSE](LICENSE) for the license text. The LGPL supplements the GNU General Public License version 3, a copy of which is included as [LICENSE.GPL](LICENSE.GPL).
The example code under [examples/](examples/) is licensed under the MIT license (see [examples/LICENSE](examples/LICENSE)), so it can be freely copied into your own projects.
The [lib/](lib/) directory contains vendored third-party code (stb, Wayland protocol bindings) that remains under its own permissive licenses; see the headers of those files.
## Copyright
Copyright (C) 2026 Catcrafts®
catcrafts.net
LGPL 3.0. See per-file headers and `LICENSE`.

View file

@ -1,5 +1,21 @@
//SPDX-License-Identifier: LGPL-3.0-only
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
/*
Crafter®.Graphics
Copyright (C) 2026 Catcrafts®
catcrafts.net
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License version 3.0 as published by the Free Software Foundation;
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
// JS bridge for the CRAFTER_GRAPHICS_WINDOW_DOM build of Crafter.Graphics.
// Populates `window.crafter_webbuild_env` (same global as Crafter.CppDOM

View file

@ -1,6 +1,3 @@
//SPDX-License-Identifier: LGPL-3.0-only
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
/*
Crafter.Graphics WebGPU bridge DOM mode UI compute pipeline.
@ -57,7 +54,6 @@ function stub(name) {
"wgpuRegisterMeshBLAS", "wgpuRegisterMeshBLASDeviceAabbs", "wgpuRefitMeshBLASDeviceAabbs",
"wgpuLoadRTPipeline", "wgpuDispatchRT", "wgpuBuildTLAS",
"wgpuLoadComputePipeline", "wgpuDispatchCompute",
"wgpuSetCanvasMount",
]) {
// Read-write ints don't need a stub-throw; return 0 for the size queries.
e[n] = n.endsWith("Width") || n.endsWith("Height")
@ -89,11 +85,6 @@ canvas.style.cssText = "position:fixed;inset:0;width:100vw;height:100vh;display:
document.body.style.margin = "0";
document.body.appendChild(canvas);
// Optional mount target set via wgpuSetCanvasMount() (below). When null the
// canvas is a full-viewport fixed layer (the original, unchanged default);
// when set, the canvas is reparented into that element and sized to it.
let mountEl = null;
function syncCanvasSize() {
// Canvas pixel size = CSS size × devicePixelRatio so the GPU draws
// at physical pixel resolution on HiDPI displays — otherwise the
@ -107,18 +98,8 @@ function syncCanvasSize() {
// share the physical-pixel coordinate space with window.width/.height.
const dpr = window.devicePixelRatio || 1;
window.crafter_dpr = dpr;
// Mounted → track the host element's box; unmounted → the viewport.
let cssW, cssH;
if (mountEl) {
const r = mountEl.getBoundingClientRect();
cssW = r.width;
cssH = r.height;
} else {
cssW = window.innerWidth;
cssH = window.innerHeight;
}
const w = Math.max(1, Math.round(cssW * dpr));
const h = Math.max(1, Math.round(cssH * dpr));
const w = Math.max(1, Math.round(window.innerWidth * dpr));
const h = Math.max(1, Math.round(window.innerHeight * dpr));
if (canvas.width !== w) canvas.width = w;
if (canvas.height !== h) canvas.height = h;
return { w, h };
@ -275,17 +256,12 @@ struct UIDispatchHeader {
@group(1) @binding(0) var outTex : texture_storage_2d<rgba8unorm, write>;
@group(1) @binding(1) var prevTex : texture_2d<f32>;
// Renderer-reserved high flag bit (mirrors ui-shared.glsl::UI_FLAG_CLIP).
const UI_FLAG_CLIP : u32 = 0x80000000u;
fn uiResolvePixel(coord: vec2<u32>) -> bool {
if (coord.x >= hdr.surfaceW || coord.y >= hdr.surfaceH) { return false; }
if ((hdr.flags & UI_FLAG_CLIP) != 0u) {
let fx = f32(coord.x); let fy = f32(coord.y);
if (fx < hdr.clipX || fy < hdr.clipY) { return false; }
if (fx >= hdr.clipX + hdr.clipW) { return false; }
if (fy >= hdr.clipY + hdr.clipH) { return false; }
}
return true;
}
@ -585,40 +561,6 @@ const env = window.crafter_webbuild_env;
env.wgpuGetCanvasWidth = () => canvas.width;
env.wgpuGetCanvasHeight = () => canvas.height;
// Reparent the render canvas into a host DOM element so a Crafter.Graphics
// scene can render inline inside an app's own layout instead of as a
// full-page layer. `idPtr`/`idLen` is a UTF-8 wasm string:
// - non-empty id of an existing element → move the canvas into it,
// position it to fill it (absolute inset:0), and size the render
// surface to that element's box (syncCanvasSize picks it up per frame).
// - empty string → detach back to <body> and hide it (display:none), so
// the host page is a plain DOM document again.
// The element is made position:relative if it is otherwise static, so the
// absolutely-positioned canvas anchors to it. Pointer events pass through
// (the inline use cases are non-interactive display surfaces).
env.wgpuSetCanvasMount = (idPtr, idLen) => {
const id = idLen > 0
? new TextDecoder().decode(memU8().subarray(idPtr, idPtr + idLen))
: "";
if (!id) {
mountEl = null;
if (canvas.parentNode !== document.body) document.body.appendChild(canvas);
canvas.style.cssText = "position:fixed;inset:0;width:100vw;height:100vh;display:none;";
return;
}
const el = document.getElementById(id);
if (!el) {
console.warn(`[crafter-wgpu] wgpuSetCanvasMount: no element #${id}`);
return;
}
mountEl = el;
if (getComputedStyle(el).position === "static") el.style.position = "relative";
if (canvas.parentNode !== el) el.appendChild(canvas);
canvas.style.cssText =
"position:absolute;inset:0;width:100%;height:100%;display:block;pointer-events:none;";
ensureSized();
};
env.wgpuCreateBuffer = (byteSize) => {
const h = newHandle();
const buf = device.createBuffer({
@ -666,7 +608,7 @@ env.wgpuWriteBufferRange = (handle, dstByteOffset, srcPtr, byteSize) => {
const READBACK_IDLE = 0;
const READBACK_PENDING = 1;
const READBACK_READY = 2;
const readbacks = new Map(); // device-buffer handle → { staging, capacity, readBytes, state, pendingData }
const readbacks = new Map(); // device-buffer handle → { staging, size, state, pendingData }
// Readbacks scheduled this frame that still need their mapAsync kicked
// off — done after the frame's queue.submit so the map waits for the
// compute writes that wrote to `buf` to finish, not just the standalone
@ -676,30 +618,21 @@ const pendingReadbackMaps = [];
env.wgpuReadbackEnqueue = (handle, byteSize, resetBytes) => {
const buf = buffers.get(handle);
if (!buf) return;
const aligned = (byteSize + 3) & ~3;
const resetAligned = resetBytes > 0 ? ((resetBytes + 3) & ~3) : 0;
let rb = readbacks.get(handle);
if (!rb) {
// Size the staging buffer to the FULL device-buffer capacity, not
// this first call's byteSize: a prefix readback (byteCount < size)
// is allowed to vary call-to-call, so the staging must cover any
// later full-size drain without re-allocating.
const capacity = Math.max(16, (buf.size + 3) & ~3);
rb = {
staging: device.createBuffer({
size: capacity,
size: Math.max(16, aligned),
usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST,
}),
capacity,
readBytes: 0, // bytes copied/mapped by the in-flight enqueue
size: aligned,
state: READBACK_IDLE,
pendingData: null,
};
readbacks.set(handle, rb);
}
// Copy/map only the requested prefix — that's the whole point of the
// byteCount path: skip the over-provisioned tail GPU→staging→wasm.
const aligned = Math.min((byteSize + 3) & ~3, rb.capacity);
rb.readBytes = aligned;
if (rb.state !== READBACK_IDLE) {
// Previous map still in flight (or has data nobody polled yet);
// skip this enqueue AND the paired reset. Events written by the
@ -743,9 +676,8 @@ env.wgpuReadbackEnqueue = (handle, byteSize, resetBytes) => {
if (resetAligned > 0) enc.clearBuffer(buf, 0, resetAligned);
queue.submit([enc.finish()]);
rb.state = READBACK_PENDING;
const mapBytes = rb.readBytes;
rb.staging.mapAsync(GPUMapMode.READ, 0, mapBytes).then(() => {
rb.pendingData = new Uint8Array(rb.staging.getMappedRange(0, mapBytes)).slice();
rb.staging.mapAsync(GPUMapMode.READ).then(() => {
rb.pendingData = new Uint8Array(rb.staging.getMappedRange()).slice();
rb.staging.unmap();
rb.state = READBACK_READY;
}).catch(e => {
@ -1073,9 +1005,8 @@ env.wgpuFrameEnd = () => {
// writes (not pre-substep state).
while (pendingReadbackMaps.length > 0) {
const rb = pendingReadbackMaps.pop();
const mapBytes = rb.readBytes;
rb.staging.mapAsync(GPUMapMode.READ, 0, mapBytes).then(() => {
rb.pendingData = new Uint8Array(rb.staging.getMappedRange(0, mapBytes)).slice();
rb.staging.mapAsync(GPUMapMode.READ).then(() => {
rb.pendingData = new Uint8Array(rb.staging.getMappedRange()).slice();
rb.staging.unmap();
rb.state = READBACK_READY;
}).catch(e => {

View file

@ -1,6 +1,3 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// Custom UI compute shader. Demonstrates the Tier 1 dispatch path:
// the user defines their own item struct, writes their own GLSL alongside
// the standard shaders (sharing the same UIDispatchHeader contract via

View file

@ -1,6 +1,3 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// DOM-mode port of inverse-circle.comp.glsl. Inverts RGB inside each
// user-supplied circle; passes through every other pixel so the
// ping-pong carries the prior dispatch's scene forward.

View file

@ -1,6 +1,3 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// Tier 1 demo: a user-authored compute shader dispatched alongside the
// standard ones. The custom shader inverts RGB in the area covered by a
// list of circles. The mouse-tracking circle moves; two static ones sit

View file

@ -1,6 +1,3 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
import std;
import Crafter.Build;
namespace fs = std::filesystem;

View file

@ -1,6 +1,3 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// End-to-end demo of GPU asset decompression via VK_EXT_memory_decompression.
//
// Walks the full compressed-asset pipeline:

View file

@ -1,6 +1,3 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
import std;
import Crafter.Build;
namespace fs = std::filesystem;

View file

@ -1,6 +1,3 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// HDRBloom blur pass (PlainComputeShader). Box-blurs the thresholded bloom
// mip into a second rgba16float target demonstrating an N-target float
// chain: this pass SAMPLES the texture the threshold pass wrote (storage

View file

@ -1,6 +1,3 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// HDRBloom closest-hit (runs in SHADE). Half the cubes are "emitters" that
// accumulate a strongly super-1.0 radiance (the HDR signal a bloom pass
// extracts); the rest are dim Lambert-shaded fillers near/below 1.0 that the

View file

@ -1,6 +1,3 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// HDRBloom composite (UI custom shader, dispatched via UIRenderer). Runs
// inside the per-frame UI compute pass, so it owns the ping-pong `out`
// texture that gets blitted to the canvas the app's compositeswapchain

View file

@ -1,6 +1,3 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// HDRBloom — cross-backend-shaped HDR post-process on the WebGPU/DOM
// backend, exercising the primitives added for issue #27:
//

View file

@ -1,6 +1,3 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// HDRBloom miss (runs in SHADE). Dark, sub-threshold background so the
// bloom pass only picks up the bright cubes, not the sky.
fn miss_main(ray: RayDesc, payload: ptr<function, Payload>) {

View file

@ -1,6 +1,3 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
import std;
import Crafter.Build;
namespace fs = std::filesystem;

View file

@ -1,6 +1,3 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// HDRBloom raygen (runs in GENERATE). Host-driven pinhole camera at
// @group(3) (groups 0..2 are reserved by the wavefront pipeline:
// 0 = WfParams, 1 = data heaps, 2 = indirect args). Primary rays only

View file

@ -1,6 +1,3 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// HDRBloom threshold pass (PlainComputeShader). Reads the linear HDR scene
// (rgba16float, written by the RT RESOLVE stage), keeps only the radiance
// above 1.0, and writes it into the bloom mip (also rgba16float). This is

View file

@ -1,6 +1,3 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
/*
HelloDom exercises every public surface of the DOM partition that
absorbed Crafter.CppDOM:

View file

@ -1,6 +1,3 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
/*
HelloDom the minimum DOM-mode example. Build with:
crafter-build --local --target=wasm32-wasip1

View file

@ -1,6 +1,3 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// Smoke test for the Tier 1+2+3 UI architecture. Opens a window, draws a
// background, a button (Tier 3 component), a slider (Tier 3 component), a
// progress bar (Tier 3 component), and a circle that follows the mouse
@ -173,20 +170,14 @@ int main() {
0, 0, 0, 0,
};
// Flush the buffers the GPU is about to read, then composite all three
// categories — background quads, the mouse circle, and the button/label
// text — in ONE fused dispatch (issue #47). The frame runs these passes
// back-to-back with no custom shader interleaved, so DispatchFused loads
// and stores the swapchain image once instead of three times and skips
// the two inter-pass barriers DispatchQuads→Circles→Text would insert.
// Canonical order is quads → circles → images → text; here there are no
// images, so that category is a free no-op.
// Flush + dispatch. The library inserts the inter-dispatch barriers.
if (qc > 0) {
#ifndef CRAFTER_GRAPHICS_WINDOW_DOM
quadsBuf.FlushDevice(cmd, VK_ACCESS_SHADER_READ_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT);
#else
quadsBuf.FlushDevice();
#endif
ui.DispatchQuads(cmd, quadsSlot, qc);
}
if (cc > 0) {
#ifndef CRAFTER_GRAPHICS_WINDOW_DOM
@ -194,6 +185,7 @@ int main() {
#else
circlesBuf.FlushDevice();
#endif
ui.DispatchCircles(cmd, circlesSlot, cc);
}
if (gc > 0) {
#ifndef CRAFTER_GRAPHICS_WINDOW_DOM
@ -201,12 +193,8 @@ int main() {
#else
glyphsBuf.FlushDevice();
#endif
ui.DispatchText(cmd, glyphsSlot, gc);
}
ui.DispatchFused(cmd,
{quadsSlot, qc},
{circlesSlot, cc},
{}, // no images this frame
{glyphsSlot, gc});
});
window.FinishInit();

View file

@ -1,6 +1,3 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
import std;
import Crafter.Build;
namespace fs = std::filesystem;

View file

@ -1,6 +1,3 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
import Crafter.Graphics;
import std;
using namespace Crafter;

View file

@ -1,6 +1,3 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
import std;
import Crafter.Build;
namespace fs = std::filesystem;

View file

@ -1,6 +1,3 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// =====================================================================
// InputSystem — guided tour of Crafter::Input
// =====================================================================

View file

@ -1,6 +1,3 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
import std;
import Crafter.Build;
namespace fs = std::filesystem;

View file

@ -1,21 +0,0 @@
MIT License
Copyright (C) 2026 Catcrafts®
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.

View file

@ -1,6 +1,3 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// RTMultiShadow closest-hit (runs in SHADE). The multi-light counterpart
// of RTStress: EVERY light emits its own shadow ray from this single
// invocation, so several rays for the same pixel resolve in the next SHADE

View file

@ -1,6 +1,3 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// RTMultiShadow — multi-light shadowing through the wavefront RT pipeline
// (issue #30). Five pillars on a checkered ground, lit by four colored
// point lights; the closest-hit emits one shadow ray PER LIGHT from the

View file

@ -1,6 +1,3 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// RTMultiShadow miss (runs in SHADE). Shadow miss that light is visible
// from the surface, so add its pending contribution; up to LIGHT_COUNT of
// these resolve for the same pixel in one pass (atomic rtAccumulate, #30).

View file

@ -1,6 +1,3 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
import std;
import Crafter.Build;
namespace fs = std::filesystem;

View file

@ -1,6 +1,3 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// RTMultiShadow raygen (runs in GENERATE). Host-driven pinhole camera at
// @group(3) (groups 0..2 are reserved by the wavefront pipeline:
// 0 = WfParams, 1 = data heaps, 2 = indirect args).

View file

@ -1,6 +1,3 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// RTMultiShadow RESOLVE-stage tonemap: Reinhard + gamma 2.2 over the
// linear accumulator. Registered as a WebGPURTStage::Resolve shader.
fn resolve_main(coord: vec2<u32>, hdr: vec4<f32>) -> vec4<f32> {

View file

@ -1,6 +1,3 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// RTStress closest-hit (runs in SHADE). Computes flat-shaded Lambert from
// the hit triangle's geometric normal, accumulates ambient, and if the
// surface faces the sun emits a shadow ray toward the sun. The shadow

View file

@ -1,6 +1,3 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// RTStress — the standing many-instance wavefront RT benchmark. An
// N×N×N grid of a small cube mesh (one BLAS, many TLAS instances), shaded
// with primary + shadow rays through the wavefront pipeline. The grid edge

View file

@ -1,6 +1,3 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// RTStress miss (runs in SHADE). Primary miss sky gradient. Shadow miss
// the sun is unoccluded, so add the pending direct contribution.
fn miss_main(ray: RayDesc, payload: ptr<function, Payload>) {

View file

@ -1,6 +1,3 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
import std;
import Crafter.Build;
namespace fs = std::filesystem;

View file

@ -1,6 +1,3 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// RTStress raygen (runs in GENERATE). Host-driven pinhole camera at
// @group(3) (groups 0..2 are reserved by the wavefront pipeline:
// 0 = WfParams, 1 = data heaps, 2 = indirect args).

View file

@ -1,6 +1,3 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// RTStress RESOLVE-stage tonemap: Reinhard + gamma 2.2 over the linear
// accumulator. Registered as a WebGPURTStage::Resolve shader.
fn resolve_main(coord: vec2<u32>, hdr: vec4<f32>) -> vec4<f32> {

View file

@ -1,6 +1,3 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
#version 460
#extension GL_EXT_buffer_reference : enable
#extension GL_EXT_scalar_block_layout : enable

View file

@ -1,6 +1,3 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// Issue #37: GPU producer (WebGPU) for the procedural AABB build input.
// Writes the per-box bounding boxes straight into a device storage buffer
// that Mesh::BuildProcedural / RefitProcedural then consume by handle, with

View file

@ -1,6 +1,3 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
#version 460
#extension GL_EXT_ray_tracing : enable

View file

@ -1,6 +1,3 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// RTVolume any-hit shader (runs in TRACE on every candidate sphere hit,
// because the geometry is registered non-opaque). Punches a spherical
// checkerboard of holes: for half the cells it returns RT_ANYHIT_IGNORE,

View file

@ -1,6 +1,3 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
#version 460
#extension GL_EXT_ray_tracing : enable

View file

@ -1,6 +1,3 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// RTVolume closest-hit (runs in SHADE). Shades the procedural sphere by
// its surface normal with a fixed sun + ambient, tinted per instance.
//

View file

@ -1,6 +1,3 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
#version 460
#extension GL_EXT_ray_tracing : enable

View file

@ -1,6 +1,3 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// RTVolume intersection shader (runs in TRACE, per AABB the ray enters).
// Analytic ray-sphere test: the unit box [-1,1]^3 is treated as the
// bounding volume of a sphere of radius 1 centred at the box centre. The

View file

@ -1,6 +1,3 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// RTVolume — procedural (AABB) ray tracing on both backends. Demonstrates
// the two features this example was written to exercise:
//

View file

@ -1,6 +1,3 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
#version 460
#extension GL_EXT_ray_tracing : enable

View file

@ -1,6 +1,3 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// RTVolume miss (runs in SHADE). Vertical sky gradient also what shows
// through the any-hit cut-out cells.
fn miss_main(ray: RayDesc, payload: ptr<function, Payload>) {

View file

@ -1,6 +1,3 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
import std;
import Crafter.Build;
namespace fs = std::filesystem;

View file

@ -1,6 +1,3 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
#version 460
#extension GL_EXT_ray_tracing : enable
#extension GL_EXT_shader_image_load_formatted : enable

View file

@ -1,6 +1,3 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// RTVolume raygen (runs in GENERATE). Host-driven pinhole camera at
// @group(3) (groups 0..2 are reserved by the wavefront pipeline:
// 0 = WfParams, 1 = data heaps, 2 = indirect args).

View file

@ -1,6 +1,3 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// RTVolume RESOLVE-stage tonemap: Reinhard + gamma 2.2 over the linear
// accumulator.
fn resolve_main(coord: vec2<u32>, hdr: vec4<f32>) -> vec4<f32> {

View file

@ -1,6 +1,3 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// RTStress closest-hit (runs in SHADE). Computes flat-shaded Lambert from
// the hit triangle's geometric normal, accumulates ambient, and if the
// surface faces the sun emits a shadow ray toward the sun. The shadow

View file

@ -1,6 +1,3 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// RayQueryPick — regression test for the WebGPU software ray-query shim.
//
// Builds an 8³ = 512-instance TLAS (well below the 8193 threshold where a
@ -192,17 +189,8 @@ int main() {
push.origin[2] = origin0 + float(kHitZ) * kSpacing;
push.dir[0] = -1.0f; push.dir[1] = 0.0f; push.dir[2] = 0.0f;
// Drive byteCount-bounded prefix readback (issue #133) once the full read
// has verified the hit: re-read ONLY the first 8 bytes (hit +
// instanceCustomIndex) with byteCount=8 after poisoning the host mirror,
// and confirm the two prefix fields land while primitiveIndex (bytes 8..11)
// stays poisoned — i.e. the copy was actually bounded, not full-capacity.
constexpr std::uint32_t kPoison = 0xEEEEEEEEu;
constexpr std::uint32_t kPrefixLen = 2 * sizeof(std::uint32_t); // hit + customIndex
static int frame = 0;
static bool dispatched = false;
static bool prefixSent = false;
static bool reported = false;
EventListener<void> tick(&window.onBeforeUpdate, [&]() {
if (reported) return;
@ -211,7 +199,7 @@ int main() {
pickShader.Dispatch(&push, sizeof(push), pickHandles, 1, 1, 1);
pickBuf.EnqueueReadback();
dispatched = true;
} else if (dispatched && !prefixSent && pickBuf.PollReadback()) {
} else if (dispatched && pickBuf.PollReadback()) {
const PickResult& r = pickBuf.value[0];
const bool ok = (r.hit == 1u) && (r.instanceCustomIndex == kExpectedCustomIndex);
std::println("[RayQueryPick] result: hit={} customIndex={} prim={} t={}",
@ -222,20 +210,6 @@ int main() {
std::println("[RayQueryPick] FAIL — expected hit=1 customIndex={}, got hit={} customIndex={}",
kExpectedCustomIndex, r.hit, r.instanceCustomIndex);
}
// Now kick off the bounded prefix re-read. Poison the whole mirror
// first; the prefix poll must overwrite only bytes [0,8).
pickBuf.value[0] = { kPoison, kPoison, kPoison, 0.0f };
pickBuf.EnqueueReadback(/*resetBytes*/ 0, /*byteCount*/ kPrefixLen);
prefixSent = true;
} else if (prefixSent && pickBuf.PollReadback(/*byteCount*/ kPrefixLen)) {
const PickResult& r = pickBuf.value[0];
const bool prefixOk = (r.hit == 1u)
&& (r.instanceCustomIndex == kExpectedCustomIndex)
&& (r.primitiveIndex == kPoison); // tail untouched
std::println("[RayQueryPick] prefix readback (byteCount={}): hit={} customIndex={} prim=0x{:08X}",
kPrefixLen, r.hit, r.instanceCustomIndex, r.primitiveIndex);
std::println("[RayQueryPick] {} — byteCount-bounded readback copied only the live prefix",
prefixOk ? "PASS" : "FAIL");
// The render loop runs after main's _Exit, where stdio is never
// flushed implicitly — push the verdict out explicitly.
std::fflush(stdout);

View file

@ -1,6 +1,3 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// RTStress miss (runs in SHADE). Primary miss sky gradient. Shadow miss
// the sun is unoccluded, so add the pending direct contribution.
fn miss_main(ray: RayDesc, payload: ptr<function, Payload>) {

View file

@ -1,6 +1,3 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
import std;
import Crafter.Build;
namespace fs = std::filesystem;

View file

@ -1,6 +1,3 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// RTStress raygen (runs in GENERATE). Host-driven pinhole camera at
// @group(3) (groups 0..2 are reserved by the wavefront pipeline:
// 0 = WfParams, 1 = data heaps, 2 = indirect args).

View file

@ -1,6 +1,3 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// rayQuery picking smoke test (WebGPU/DOM software ray-query path).
//
// Shoots a single, fully-determined ray at a known TLAS instance through

View file

@ -1,6 +1,3 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// RTStress RESOLVE-stage tonemap: Reinhard + gamma 2.2 over the linear
// accumulator. Registered as a WebGPURTStage::Resolve shader.
fn resolve_main(coord: vec2<u32>, hdr: vec4<f32>) -> vec4<f32> {

View file

@ -1,6 +1,3 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
#version 460
#extension GL_EXT_ray_tracing : enable
#extension GL_EXT_shader_image_load_formatted : enable

View file

@ -1,6 +1,3 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// Sponza closest-hit (runs in SHADE). In the wavefront model the lighting
// + shadow trace that used to live in raygen happens here: gather surface
// data, accumulate ambient, and emit a shadow ray toward the sun carrying

View file

@ -1,6 +1,3 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// Sponza on Vulkan + WebGPU. Same example source, two backends — picked
// by CRAFTER_GRAPHICS_WINDOW_DOM. Both paths:
// 1. Load a Sponza .cmesh (positions + indices, optional per-vertex

View file

@ -1,6 +1,3 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
#version 460
#extension GL_EXT_ray_tracing : enable

View file

@ -1,6 +1,3 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// Sponza miss (runs in SHADE). Primary miss two-stop sky gradient.
// Shadow miss the sun is unoccluded, so add the pending direct term.
fn miss_main(ray: RayDesc, payload: ptr<function, Payload>) {

View file

@ -1,6 +1,3 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
import std;
import Crafter.Build;
namespace fs = std::filesystem;

View file

@ -1,6 +1,3 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
#version 460
#extension GL_EXT_ray_tracing : enable
#extension GL_EXT_shader_image_load_formatted : enable

View file

@ -1,6 +1,3 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// Sponza raygen (runs in GENERATE). Emits the pixel's primary ray; all
// shading + the shadow trace now happen in SHADE (closesthit/miss). Camera
// state comes from the host each frame via a storage buffer at

View file

@ -1,6 +1,3 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// Sponza RESOLVE-stage tonemap: Reinhard + gamma 2.2 over the linear
// accumulator matches the tonemap the megakernel raygen applied inline.
fn resolve_main(coord: vec2<u32>, hdr: vec4<f32>) -> vec4<f32> {

View file

@ -1,131 +0,0 @@
# SponzaBench — measuring the post-#40 performance work
This example exists to answer issue **#155**: *starting with #40 a lot of
performance-related issues were merged — what is the net performance gain,
measured in a representative scene (Sponza)?*
It is a headless benchmark harness built around the **native Vulkan**
Sponza ray-tracing scene. Same asset bundle and camera as
[`examples/Sponza`](../Sponza), but instead of opening an interactive
window it times the work and prints machine-readable `BENCH …` lines, then
exits.
## What it measures
* **setup** — process start through the first command submission: asset
decompression, BLAS build per mesh group, the multi-instance TLAS, the
RT pipeline, GPU memory placement and the descriptor writes. This is the
window most of the post-#40 *native* perf work acts on.
* **frames** — a warmup followed by a measured loop calling
`Window::Render()`, reporting per-frame wall-clock stats and throughput.
Unlike the interactive Sponza example — which is single-material on native
because of the hit-shader dynamic-`descriptor_heap`-index driver fault
(see `examples/Sponza/README.md`) — SponzaBench's closest-hit shades from
barycentric coordinates and samples **no** texture, so it can build the
**full multi-mesh atrium** (25 mesh groups, ~262 k triangles) as one
multi-instance TLAS. The albedo is still decompressed and uploaded during
setup (to keep that path in the measurement) but is not bound.
## Running
```bash
cd examples/SponzaBench
crafter-build # native Vulkan
# from the produced bin dir:
VK_LOADER_LAYERS_DISABLE='~all~' \
CRAFTER_PRESENT_IMMEDIATE=1 \
BENCH_WARMUP=200 BENCH_FRAMES=2000 BENCH_MESHES=25 ./SponzaBench
```
`run-bench.sh <bindir> <label> <meshes> <reps> [--cold]` runs it N times
and reports the median / min / max of each metric.
Environment knobs:
| var | effect |
|---|---|
| `CRAFTER_PRESENT_IMMEDIATE=1` | uncapped present mode — without it FIFO pins frame time to the compositor's vblank (~60 Hz) and steady-state throughput can't be seen. |
| `VK_LOADER_LAYERS_DISABLE='~all~'` | disable the validation layer. The engine enables Khronos validation **and GPU-assisted validation** unconditionally; that adds large, version-dependent overhead and must be off for a representative measurement. |
| `BENCH_WARMUP` / `BENCH_FRAMES` | warmup and measured frame counts (default 200 / 2000). |
| `BENCH_MESHES` | cap on mesh groups loaded (default: all 25). A small cap shrinks GPU work so per-frame **CPU** cost dominates; the full scene is GPU-traversal bound. |
| `BENCH_CLEAN_EXIT=1` | exit via `std::exit` (runs `atexit`, which writes the #69 pipeline cache) instead of the default hard `_Exit`. Used once to seed `pipeline_cache.bin` for a warm-cache measurement. |
## Results — #40 vs current master
Measured on this repo's CI box: **NVIDIA RTX 4090**, driver `610.43.02`,
1280×720, validation disabled, `IMMEDIATE` present, 200 warmup + 2000
measured frames, **median of 9 runs**. "#40" is commit `1451e3a` (the #40
merge); "HEAD" is current master. The *same* SponzaBench sources were
built against each library revision (a git worktree at #40).
### Full atrium — 25 meshes / ~262 k triangles (GPU-traversal bound)
| metric | #40 | HEAD | Δ |
|---|---:|---:|---:|
| setup (cold) ms | 322.7 | 316.6 | **1.9 %** |
| setup (warm pipeline cache, #69) ms | 322.7¹ | 313.9 | **2.7 %** |
| throughput fps | 7 560 | 7 637 | **+1.0 %** |
| frame time p50 ms | 0.1311 | 0.1298 | **1.0 %** |
| peak host RSS (cold) MB | 336.0 | 344.2 | +2.4 % |
| peak host RSS (warm cache) MB | 336.0¹ | 332.0 | **1.2 %** |
¹ #40 predates the disk pipeline cache (#69), so its setup is always the
cold-compile path.
### Light scene — 1 mesh (deliberately CPU-bound)
| metric | #40 | HEAD | Δ |
|---|---:|---:|---:|
| throughput fps | 15 022 | 15 237 | **+1.4 %** |
| frame time p50 ms | 0.0662 | 0.0650 | **1.8 %** |
## Interpretation
**The net measured gain in a static Sponza RT scene is small: ~12 %
faster frames, ~23 % faster setup, and roughly flat host memory.** That is
an honest result, and the reason is *what Sponza exercises*, not that the
perf work was ineffective:
* **Most post-#40 PRs don't touch this workload.** The largest block is UI
/ text rendering (shaped-run cache, font-atlas dirty uploads, the UI
compute-shader rewrites — #46#57, #61, #122#129, #132). Sponza has no
UI, so those contribute **zero**. A second block optimises **per-frame
dynamic uploads** (TLAS dirty-tracking #118, deforming-mesh refit #119,
the staging ring #120). A *static* scene builds its TLAS once and never
re-uploads, so these don't fire in steady state either. WebGPU-only
(#130/#131/#133) and Win32-only (#134) PRs don't apply to a native
Vulkan build at all.
* **The PRs that *do* apply act on setup and memory, not frame time.**
Device-local placement (#65/#72/#73/#75), staging release
(#66/#67/#114), the pipeline cache (#69) and the deferred-deletion queue
(#101/#116) move setup cost and peak memory — which is exactly where the
measured ~23 % setup change and the warm-cache RSS drop show up. The
pipeline cache itself saves ~3 ms here (one RT pipeline) and, more
visibly, ~12 MB of peak RSS by skipping the cold shader-compile
allocations.
* **Steady-state frame time is GPU-traversal bound.** With 262 k triangles
the per-frame CPU work (barrier scoping #48/#115, cached heap-bind
structs #42/#43) is hidden behind GPU traversal, so it can't move the
frame time. Shrinking the scene until it is CPU-bound (the light scene
above) surfaces the per-frame CPU savings — and even then they are only
~1.8 %, because that CPU path was already cheap.
**Takeaway:** the post-#40 work is real but concentrated in UI/text and
per-frame dynamic-upload paths; a static, UI-less RT scene is the wrong
workload to see most of it. To quantify the UI/text gains a separate
benchmark over a text-heavy `UIRenderer` scene (or an animated/deforming
scene for the dynamic-upload PRs) would be needed.
## Caveats / notes
* The stock `examples/Sponza` **native** path does not currently compile
against the (unpinned) Vulkan-Headers `main`: the
`VkResourceDescriptorDataEXT` union no longer has the
`pCombinedImageSampler` member the example uses. SponzaBench sidesteps
this by not binding a combined image+sampler. (Pre-existing, unrelated to
#155 — worth a follow-up to port Sponza to the split sampled-image +
sampler-heap model the engine's own UI renderer already uses.)
* Numbers are CPU/GPU specific. Re-run `run-bench.sh` locally for your
hardware; the *deltas* between revisions are the point, not the absolute
figures.

View file

@ -1,19 +0,0 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
#version 460
#extension GL_EXT_ray_tracing : enable
// Benchmark closest-hit: shade from the hit's barycentric coordinates.
// SponzaBench deliberately avoids the descriptor-heap texture sample the
// interactive Sponza example uses — the point here is to measure the
// ray-tracing traversal + frame-loop cost, not texturing, and a
// texture-free hit keeps the host setup portable across library
// revisions (issue #155).
hitAttributeEXT vec2 hitAttrs;
layout(location = 0) rayPayloadInEXT vec3 hitValue;
void main() {
vec3 bary = vec3(1.0 - hitAttrs.x - hitAttrs.y, hitAttrs.x, hitAttrs.y);
hitValue = bary;
}

View file

@ -1,309 +0,0 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// SponzaBench — headless benchmark around the native Sponza RT scene.
//
// Identical setup to examples/Sponza (native branch): load the Sponza
// .cmesh + albedo .ctex, build BLAS/TLAS, wire an RTPass. Instead of
// opening an interactive window and idling in StartSync(), it times two
// things and exits:
//
// * setup — process start through the first command submission
// (asset decompress + BLAS/TLAS build + pipeline + memory
// placement + descriptor writes), which the bulk of the
// post-#40 perf work targets (device-local placement,
// staging release, pipeline cache, decompress, ...).
// * frames — a warmup then a measured loop calling Window::Render(),
// reporting per-frame wall-clock stats. Run with
// CRAFTER_PRESENT_IMMEDIATE=1 to uncap from vblank.
//
// Tunables (env): BENCH_WARMUP (default 200), BENCH_FRAMES (default 2000).
// Output lines are prefixed "BENCH " for easy scraping.
#include "vulkan/vulkan.h"
import Crafter.Graphics;
import Crafter.Asset;
import Crafter.Math;
import Crafter.Event;
import std;
using namespace Crafter;
namespace fs = std::filesystem;
using Clock = std::chrono::steady_clock;
namespace {
struct RGBA8 { std::uint8_t r, g, b, a; };
void RequireAssets(const fs::path& mesh, const fs::path& tex) {
if (fs::exists(mesh) && fs::exists(tex)) return;
std::println(std::cerr, "[SponzaBench] missing asset(s): {} / {}",
mesh.string(), tex.string());
std::abort();
}
// Peak resident set size (high-water mark) in kB, from /proc/self/status.
long PeakRSSkB() {
std::ifstream st("/proc/self/status");
std::string line;
while (std::getline(st, line)) {
if (line.rfind("VmHWM:", 0) == 0) {
long kb = 0;
std::sscanf(line.c_str(), "VmHWM: %ld", &kb);
return kb;
}
}
return -1;
}
std::size_t EnvSize(const char* name, std::size_t fallback) {
if (const char* v = std::getenv(name)) {
char* end = nullptr;
unsigned long parsed = std::strtoul(v, &end, 10);
if (end != v) return static_cast<std::size_t>(parsed);
}
return fallback;
}
double Ms(std::chrono::nanoseconds ns) {
return std::chrono::duration<double, std::milli>(ns).count();
}
}
int main() {
const std::size_t warmup = EnvSize("BENCH_WARMUP", 200);
const std::size_t frames = EnvSize("BENCH_FRAMES", 2000);
const auto tProcStart = Clock::now();
const fs::path texPath = "tex_0.ctex";
RequireAssets("mesh_0.cmesh", texPath);
// scene.txt (from the asset bundle): line 1 albedoCount, line 2
// meshCount, then per-mesh albedo index. We render every mesh group —
// unlike the interactive Sponza example, which is single-material on
// native because of the hit-shader dynamic-heap-index driver fault.
// SponzaBench's hit shader samples no texture, so it can build the
// full multi-mesh atrium as one multi-instance TLAS.
std::uint32_t albedoCount = 0, meshCount = 0;
{
std::ifstream manifest("scene.txt");
if (!manifest) { std::println(std::cerr, "[SponzaBench] missing scene.txt"); std::abort(); }
manifest >> albedoCount >> meshCount;
}
// BENCH_MESHES caps the number of mesh groups loaded (default: all).
// A small cap (e.g. 1) shrinks GPU work so per-frame CPU cost dominates;
// the full scene is GPU (traversal) bound.
meshCount = std::min<std::uint32_t>(meshCount, EnvSize("BENCH_MESHES", meshCount));
CompressedTextureAsset loadedTex = LoadCompressedTexture(texPath);
std::println("[SponzaBench] scene: {} meshes, {} albedos, {}x{} probe albedo",
meshCount, albedoCount, loadedTex.sizeX, loadedTex.sizeY);
Device::Initialize();
Window window(1280, 720, "SponzaBench");
VkCommandBuffer cmd = window.StartInit();
DescriptorHeapVulkan descriptorHeap;
descriptorHeap.Initialize(/*images*/ 2, /*buffers*/ 1, /*samplers*/ 0);
VkSpecializationMapEntry raygenEntry = { .constantID = 0, .offset = 0, .size = sizeof(std::uint16_t) };
VkSpecializationInfo raygenSpec = {
.mapEntryCount = 1, .pMapEntries = &raygenEntry,
.dataSize = sizeof(std::uint16_t), .pData = &descriptorHeap.bufferStartElement,
};
auto imgSlots = descriptorHeap.AllocateImageSlots(1);
auto bufSlots = descriptorHeap.AllocateBufferSlots(1);
std::array<VulkanShader, 3> shaders {{
{ "raygen.spv", "main", VK_SHADER_STAGE_RAYGEN_BIT_KHR, &raygenSpec },
{ "miss.spv", "main", VK_SHADER_STAGE_MISS_BIT_KHR, nullptr },
{ "closesthit.spv", "main", VK_SHADER_STAGE_CLOSEST_HIT_BIT_KHR, nullptr },
}};
ShaderBindingTableVulkan shaderTable;
shaderTable.Init(shaders);
std::array<VkRayTracingShaderGroupCreateInfoKHR, 1> raygenGroups {{ {
.sType = VK_STRUCTURE_TYPE_RAY_TRACING_SHADER_GROUP_CREATE_INFO_KHR,
.type = VK_RAY_TRACING_SHADER_GROUP_TYPE_GENERAL_KHR,
.generalShader = 0, .closestHitShader = VK_SHADER_UNUSED_KHR,
.anyHitShader = VK_SHADER_UNUSED_KHR, .intersectionShader = VK_SHADER_UNUSED_KHR,
} }};
std::array<VkRayTracingShaderGroupCreateInfoKHR, 1> missGroups {{ {
.sType = VK_STRUCTURE_TYPE_RAY_TRACING_SHADER_GROUP_CREATE_INFO_KHR,
.type = VK_RAY_TRACING_SHADER_GROUP_TYPE_GENERAL_KHR,
.generalShader = 1, .closestHitShader = VK_SHADER_UNUSED_KHR,
.anyHitShader = VK_SHADER_UNUSED_KHR, .intersectionShader = VK_SHADER_UNUSED_KHR,
} }};
std::array<VkRayTracingShaderGroupCreateInfoKHR, 1> hitGroups {{ {
.sType = VK_STRUCTURE_TYPE_RAY_TRACING_SHADER_GROUP_CREATE_INFO_KHR,
.type = VK_RAY_TRACING_SHADER_GROUP_TYPE_TRIANGLES_HIT_GROUP_KHR,
.generalShader = VK_SHADER_UNUSED_KHR, .closestHitShader = 2,
.anyHitShader = VK_SHADER_UNUSED_KHR, .intersectionShader = VK_SHADER_UNUSED_KHR,
} }};
PipelineRTVulkan pipeline;
pipeline.Init(cmd, raygenGroups, missGroups, hitGroups, shaderTable);
// One Mesh + RenderingElement3D per mesh group → BLAS each, then a
// single multi-instance TLAS. Pointers handed to RenderingElement3D
// live in the static vectors, so reserve up-front: a reallocation
// would dangle every registered element.
static std::vector<Mesh> meshes;
static std::vector<RenderingElement3D> renderers;
meshes.reserve(meshCount);
renderers.reserve(meshCount);
std::uint64_t totalVerts = 0, totalIdx = 0;
for (std::uint32_t i = 0; i < meshCount; ++i) {
const fs::path mp = std::format("mesh_{}.cmesh", i);
if (!fs::exists(mp)) continue;
CompressedMeshAsset loaded = LoadCompressedMesh(mp);
totalVerts += loaded.vertexCount;
totalIdx += loaded.indexCount;
meshes.emplace_back();
meshes.back().Build(loaded, cmd);
renderers.emplace_back();
RenderingElement3D& r = renderers.back();
r.instance = {
.transform = {},
.instanceCustomIndex = 0,
.mask = 0xFF,
.instanceShaderBindingTableRecordOffset = 0,
.flags = VK_GEOMETRY_INSTANCE_FORCE_OPAQUE_BIT_KHR,
.accelerationStructureReference = meshes.back().blasAddr,
};
MatrixRowMajor<float, 4, 3, 1>::Identity()
.Store(reinterpret_cast<float*>(r.instance.transform.matrix));
RenderingElement3D::Add(&r);
}
std::println("[SponzaBench] built {} BLAS, {} verts, {} idx total",
renderers.size(), totalVerts, totalIdx);
Image2D<RGBA8> albedo;
albedo.Create(loadedTex.sizeX, loadedTex.sizeY, /*mipLevels*/ 1, cmd,
VK_FORMAT_R8G8B8A8_UNORM,
VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT,
VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
albedo.Update(loadedTex, cmd, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
// The albedo is uploaded to keep the texture-decompress + staging
// setup path in the measured "setup" window, but is not bound — the
// closest-hit shades from barycentrics, so only the TLAS + per-frame
// output image need descriptors.
for (std::uint32_t f = 0; f < Window::numFrames; ++f)
RenderingElement3D::BuildTLAS(cmd, f);
window.FinishInit();
VkDeviceAddressRangeKHR tlasRanges[Window::numFrames];
VkImageDescriptorInfoEXT outImgInfos[Window::numFrames];
for (std::uint32_t f = 0; f < Window::numFrames; ++f) {
tlasRanges[f] = { .address = RenderingElement3D::tlases[f].address };
outImgInfos[f] = {
.sType = VK_STRUCTURE_TYPE_IMAGE_DESCRIPTOR_INFO_EXT,
.pView = &window.imageViews[f],
.layout = VK_IMAGE_LAYOUT_GENERAL,
};
}
std::vector<VkResourceDescriptorInfoEXT> resources;
std::vector<VkHostAddressRangeEXT> destinations;
resources.reserve(Window::numFrames * 2);
destinations.reserve(Window::numFrames * 2);
for (std::uint32_t f = 0; f < Window::numFrames; ++f) {
resources.push_back({
.sType = VK_STRUCTURE_TYPE_RESOURCE_DESCRIPTOR_INFO_EXT,
.type = VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_KHR,
.data = { .pAddressRange = &tlasRanges[f] },
});
destinations.push_back({
.address = descriptorHeap.resourceHeap[f].value
+ descriptorHeap.BufferByteOffset(bufSlots.firstElement),
.size = Device::descriptorHeapProperties.bufferDescriptorSize,
});
resources.push_back({
.sType = VK_STRUCTURE_TYPE_RESOURCE_DESCRIPTOR_INFO_EXT,
.type = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE,
.data = { .pImage = &outImgInfos[f] },
});
destinations.push_back({
.address = descriptorHeap.resourceHeap[f].value
+ descriptorHeap.ImageByteOffset(imgSlots.firstElement),
.size = Device::descriptorHeapProperties.imageDescriptorSize,
});
}
Device::vkWriteResourceDescriptorsEXT(Device::device,
static_cast<std::uint32_t>(resources.size()),
resources.data(), destinations.data());
for (std::uint32_t f = 0; f < Window::numFrames; ++f) {
descriptorHeap.resourceHeap[f].FlushDevice();
}
window.descriptorHeap = &descriptorHeap;
RTPass rtPass(&pipeline);
window.passes.push_back(&rtPass);
// ── Setup complete. Everything above is the per-run, one-time cost. ──
const auto tSetupDone = Clock::now();
const double setupMs = Ms(tSetupDone - tProcStart);
// ── Warmup: let the pipeline fill (frames-in-flight), caches warm. ──
for (std::size_t i = 0; i < warmup; ++i) window.Render();
// ── Measured loop: per-frame wall-clock around Render(). ────────────
std::vector<double> frameMs;
frameMs.reserve(frames);
const auto tLoopStart = Clock::now();
for (std::size_t i = 0; i < frames; ++i) {
const auto a = Clock::now();
window.Render();
const auto b = Clock::now();
frameMs.push_back(Ms(b - a));
}
const auto tLoopEnd = Clock::now();
// Drain so the loop's wall-clock isn't charged the GPU tail of the
// last few in-flight frames inconsistently across runs.
vkQueueWaitIdle(Device::queue);
const long peakRSS = PeakRSSkB();
// ── Stats. throughput uses the loop wall-clock (steady-state FPS);
// per-frame percentiles use the sorted per-frame samples. ─────────
const double loopWallMs = Ms(tLoopEnd - tLoopStart);
std::sort(frameMs.begin(), frameMs.end());
auto pct = [&](double p) {
if (frameMs.empty()) return 0.0;
std::size_t idx = static_cast<std::size_t>(p * (frameMs.size() - 1));
return frameMs[idx];
};
double sum = 0.0; for (double v : frameMs) sum += v;
const double meanMs = frameMs.empty() ? 0.0 : sum / frameMs.size();
std::println("");
std::println("BENCH setup_ms {:.3f}", setupMs);
std::println("BENCH frames {}", frames);
std::println("BENCH loop_wall_ms {:.3f}", loopWallMs);
std::println("BENCH fps {:.1f}", frames / (loopWallMs / 1000.0));
std::println("BENCH frame_mean_ms {:.4f}", meanMs);
std::println("BENCH frame_min_ms {:.4f}", pct(0.0));
std::println("BENCH frame_p50_ms {:.4f}", pct(0.50));
std::println("BENCH frame_p99_ms {:.4f}", pct(0.99));
std::println("BENCH frame_max_ms {:.4f}", pct(1.0));
std::println("BENCH peak_rss_kb {}", peakRSS);
// The interactive Sponza example never tears Device/Window down (it
// loops in StartSync forever); doing so here races GPU-still-in-flight
// resources at static-destruction time. The measurement is already
// printed, so skip destructors entirely with a hard exit.
//
// BENCH_CLEAN_EXIT=1 instead exits via std::exit, which runs atexit
// handlers (on builds that have the disk pipeline cache, #69, this is
// where it is written) before the destructor teardown. Used once to
// seed pipeline_cache.bin for a warm-cache setup measurement; the
// subsequent destructor race is irrelevant since the data is flushed.
std::cout.flush();
if (std::getenv("BENCH_CLEAN_EXIT")) std::exit(0);
std::_Exit(0);
}

View file

@ -1,14 +0,0 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
#version 460
#extension GL_EXT_ray_tracing : enable
layout(location = 0) rayPayloadInEXT vec3 hitValue;
void main() {
// Soft sky gradient based on ray direction Y. The actual ray dir
// isn't accessible without an extra payload field; use a flat warm
// tone that matches Sponza's interior lighting.
hitValue = vec3(0.10, 0.08, 0.06);
}

View file

@ -1,63 +0,0 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
import std;
import Crafter.Build;
namespace fs = std::filesystem;
using namespace Crafter;
// SponzaBench — a headless benchmark harness around the native Sponza
// ray-tracing scene. Same asset bundle and shaders as examples/Sponza,
// but main.cpp times setup + a fixed measured frame loop instead of
// opening an interactive window. Native (Vulkan) only — the point is to
// measure the native renderer's per-frame and setup cost across library
// revisions (issue #155: net perf gain from #40 to now).
constexpr std::string_view kSponzaGitUrl = "https://github.com/jimmiebergmann/Sponza.git";
constexpr std::string_view kSponzaCommitSHA = "222338979d32f4f4818466291bdbc29f192b86ba";
constexpr std::uint16_t kAlbedoSize = 1024u;
extern "C" Configuration CrafterBuildProject(std::span<const std::string_view> args) {
std::vector<std::string> graphicsArgs(args.begin(), args.end());
Configuration* graphics = LocalProject({
.projectFile = "../../project.cpp",
.args = graphicsArgs,
});
Configuration cfg;
cfg.path = "./";
cfg.name = "SponzaBench";
cfg.outputName = "SponzaBench";
cfg.type = ConfigurationType::Executable;
ApplyStandardArgs(cfg, args);
cfg.dependencies = { graphics };
std::array<fs::path, 0> ifaces = {};
std::array<fs::path, 1> impls = { "main" };
cfg.GetInterfacesAndImplementations(ifaces, impls);
fs::path sponzaRoot = GitFetch({
.url = std::string(kSponzaGitUrl),
.commit = std::string(kSponzaCommitSHA),
});
std::string bundleKey = std::format("{}|{}", kSponzaCommitSHA, kAlbedoSize);
auto bundleHash = std::hash<std::string>{}(bundleKey);
fs::path bundleDir = fs::path("build") / std::format("sponza-bundle-{:016x}", bundleHash);
if (auto err = BuildOBJBundle(
sponzaRoot / "sponza.obj",
sponzaRoot / "sponza.mtl",
bundleDir,
kAlbedoSize); !err.empty()) {
std::println(std::cerr, "Sponza bundle error: {}", err);
std::exit(1);
}
for (const auto& entry : fs::directory_iterator(bundleDir)) {
if (entry.is_regular_file()) cfg.files.push_back(entry.path());
}
cfg.shaders.emplace_back(fs::path("raygen.glsl"), std::string("main"), ShaderType::RayGen);
cfg.shaders.emplace_back(fs::path("closesthit.glsl"), std::string("main"), ShaderType::ClosestHit);
cfg.shaders.emplace_back(fs::path("miss.glsl"), std::string("main"), ShaderType::Miss);
return cfg;
}

View file

@ -1,55 +0,0 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
#version 460
#extension GL_EXT_ray_tracing : enable
#extension GL_EXT_shader_image_load_formatted : enable
#extension GL_EXT_shader_explicit_arithmetic_types_int16 : enable
#extension GL_EXT_descriptor_heap : enable
#extension GL_EXT_nonuniform_qualifier : enable
// Specialization constant set from descriptorHeap.bufferStartElement —
// shared with closesthit.glsl. The TLAS lives at descriptor_heap slot
// `bufferStart` (it's an SSBO-typed entry), the per-frame output image
// at heap slot 0.
layout(constant_id = 0) const uint16_t bufferStart = 0us;
layout(descriptor_heap) uniform accelerationStructureEXT topLevelAS[];
layout(descriptor_heap) uniform writeonly image2D image[];
layout(location = 0) rayPayloadEXT vec3 hitValue;
void main() {
uvec2 pixel = gl_LaunchIDEXT.xy;
uvec2 resolution = gl_LaunchSizeEXT.xy;
vec2 uv = (vec2(pixel) + 0.5) / vec2(resolution);
vec2 ndc = uv * 2.0 - 1.0;
// Camera positioned to look down the Sponza atrium axis. Sponza-OBJ
// from McGuire's archive is roughly 30 units wide × 13 tall × 18 deep,
// axis-aligned, with the floor near y=0 and the atrium centered on
// origin. -X faces the long end, so we sit inside looking +X.
vec3 origin = vec3(-10.0, 5.0, 0.0);
float aspect = float(resolution.x) / float(resolution.y);
float fov = radians(70.0);
float tanHalf = tan(fov * 0.5);
vec3 direction = normalize(vec3(
ndc.x * aspect * tanHalf,
-ndc.y * tanHalf,
1.0));
// Rotate +Z forward → +X forward (90° about Y).
direction = vec3(direction.z, direction.y, -direction.x);
traceRayEXT(
topLevelAS[bufferStart],
gl_RayFlagsNoneEXT,
0xff,
0, 0, 0,
origin,
0.001,
direction,
10000.0,
0);
imageStore(image[0], ivec2(pixel), vec4(hitValue, 1.0));
}

View file

@ -1,43 +0,0 @@
#!/usr/bin/env bash
#SPDX-License-Identifier: MIT
#SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
# Repeated-measurement harness for SponzaBench. Runs the binary in $BINDIR
# REPS times for a given mesh cap and reports the median (and min/max) of
# each BENCH metric. Validation is force-disabled via the loader (it adds
# huge, version-dependent overhead) and present mode is uncapped so frame
# time reflects real work rather than the compositor's vblank.
#
# Usage: run-bench.sh <bindir> <label> <meshes> <reps> [--cold]
# --cold deletes pipeline_cache.bin before EACH run (cold-compile path).
set -u
BINDIR="$1"; LABEL="$2"; MESHES="$3"; REPS="$4"; COLD="${5:-}"
cd "$BINDIR" || exit 1
declare -A vals
metrics="setup_ms fps frame_mean_ms frame_p50_ms frame_p99_ms peak_rss_kb"
for m in $metrics; do vals[$m]=""; done
for ((i=0;i<REPS;i++)); do
[ "$COLD" = "--cold" ] && rm -f pipeline_cache.bin
out=$(VK_LOADER_LAYERS_DISABLE='~all~' CRAFTER_PRESENT_IMMEDIATE=1 \
BENCH_WARMUP=200 BENCH_FRAMES=2000 BENCH_MESHES="$MESHES" \
./SponzaBench 2>/dev/null)
for m in $metrics; do
v=$(echo "$out" | awk -v k="$m" '$1=="BENCH" && $2==k {print $3}')
vals[$m]="${vals[$m]} $v"
done
done
med() { tr ' ' '\n' | grep -v '^$' | sort -n | awk '{a[NR]=$1} END{print a[int((NR+1)/2)]}'; }
lo() { tr ' ' '\n' | grep -v '^$' | sort -n | head -1; }
hi() { tr ' ' '\n' | grep -v '^$' | sort -n | tail -1; }
echo "## $LABEL (meshes=$MESHES reps=$REPS ${COLD})"
printf "%-15s %12s %12s %12s\n" metric median min max
for m in $metrics; do
echo -n "$(printf '%-15s' "$m") "
printf "%12s %12s %12s\n" \
"$(echo "${vals[$m]}" | med)" "$(echo "${vals[$m]}" | lo)" "$(echo "${vals[$m]}" | hi)"
done
echo

View file

@ -1,6 +1,3 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
#version 460
#extension GL_EXT_ray_tracing : enable
#extension GL_EXT_nonuniform_qualifier : enable

View file

@ -1,6 +1,3 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// Payload declared here so the WGSL assembler sees it before the wfPayload
// binding, the SHADE dispatch, and the raygen source.
//

View file

@ -1,6 +1,3 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
#ifndef CRAFTER_GRAPHICS_WINDOW_DOM
#include "vulkan/vulkan.h"
#endif

View file

@ -1,6 +1,3 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
#version 460
#extension GL_EXT_ray_tracing : enable

View file

@ -1,6 +1,3 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// Wavefront miss: runs in SHADE for rays that hit nothing. Accumulate the
// white background directly.

View file

@ -1,6 +1,3 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
import std;
import Crafter.Build;
namespace fs = std::filesystem;

View file

@ -1,6 +1,3 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
#version 460
#extension GL_EXT_ray_tracing : enable
#extension GL_EXT_shader_image_load_formatted : enable

View file

@ -1,6 +1,3 @@
//SPDX-License-Identifier: MIT
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// WebGPU wavefront raygen. Runs in GENERATE: compute the pinhole camera
// ray and emit it as the pixel's primary ray. Shading happens later in
// SHADE (closesthit/miss). The Payload type is declared in closesthit.wgsl.

View file

@ -1,6 +1,22 @@
//SPDX-License-Identifier: LGPL-3.0-only
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
/*
Crafter®.Graphics
Copyright (C) 2026 Catcrafts®
Catcrafts.net
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 3.0 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
module;
#ifdef CRAFTER_GRAPHICS_WINDOW_WAYLAND
#include <wayland-client.h>

View file

@ -1,6 +1,21 @@
//SPDX-License-Identifier: LGPL-3.0-only
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
/*
Crafter®.Graphics
Copyright (C) 2026 Catcrafts®
catcrafts.net
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License version 3.0 as published by the Free Software Foundation;
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
module;
#include "vulkan/vulkan.h"
module Crafter.Graphics:ComputeShader_impl;
@ -67,7 +82,7 @@ void ComputeShader::Load(const std::filesystem::path& spvPath) {
.layout = VK_NULL_HANDLE,
};
Device::CheckVkResult(vkCreateComputePipelines(
Device::device, Device::pipelineCache, 1, &info, nullptr, &pipeline));
Device::device, VK_NULL_HANDLE, 1, &info, nullptr, &pipeline));
}
void ComputeShader::Dispatch(VkCommandBuffer cmd,

View file

@ -1,5 +1,22 @@
//SPDX-License-Identifier: LGPL-3.0-only
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
/*
Crafter®.Graphics
Copyright (C) 2026 Catcrafts®
catcrafts.net
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License version 3.0 as published by the Free Software Foundation;
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
module;
@ -119,97 +136,6 @@ void Device::CheckVkResult(VkResult result) {
}
}
bool Device::PipelineCacheDataCompatible(std::span<const std::byte> data) {
// VkPipelineCacheHeaderVersionOne is a fixed 32-byte little-endian header
// (Vulkan spec 16.5.2): u32 headerSize, u32 headerVersion, u32 vendorID,
// u32 deviceID, then VK_UUID_SIZE bytes of pipelineCacheUUID. Parse the
// fields by offset rather than reinterpret_cast'ing the struct so the
// check is independent of the C struct's alignment/padding.
constexpr std::size_t headerBytes = 16 + VK_UUID_SIZE;
if (data.size() < headerBytes) {
return false;
}
auto readU32 = [&](std::size_t offset) {
std::uint32_t value;
std::memcpy(&value, data.data() + offset, sizeof(value));
return value;
};
const std::uint32_t headerSize = readU32(0);
const std::uint32_t headerVersion = readU32(4);
const std::uint32_t vendorID = readU32(8);
const std::uint32_t deviceID = readU32(12);
if (headerSize < headerBytes) {
return false;
}
if (headerVersion != VK_PIPELINE_CACHE_HEADER_VERSION_ONE) {
return false;
}
if (vendorID != deviceProperties.vendorID || deviceID != deviceProperties.deviceID) {
return false;
}
return std::memcmp(data.data() + 16, deviceProperties.pipelineCacheUUID, VK_UUID_SIZE) == 0;
}
void Device::LoadPipelineCache() {
std::vector<std::byte> initialData;
std::error_code ec;
if (std::filesystem::exists(pipelineCachePath, ec)) {
std::ifstream file(pipelineCachePath, std::ios::binary | std::ios::ate);
if (file) {
const std::streamoff size = file.tellg();
if (size > 0) {
initialData.resize(static_cast<std::size_t>(size));
file.seekg(0);
file.read(reinterpret_cast<char*>(initialData.data()), size);
if (!file) {
initialData.clear(); // partial/short read — start cold
}
}
}
}
// Drop a blob the current driver/device wouldn't accept: a header from a
// different GPU (or a corrupt/empty file) would at best be ignored and at
// worst rejected. Starting empty just costs a one-time cold compile.
if (!PipelineCacheDataCompatible(initialData)) {
initialData.clear();
}
VkPipelineCacheCreateInfo info {
.sType = VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO,
.initialDataSize = initialData.size(),
.pInitialData = initialData.empty() ? nullptr : initialData.data(),
};
CheckVkResult(vkCreatePipelineCache(device, &info, nullptr, &pipelineCache));
}
void Device::SavePipelineCache() {
if (pipelineCache == VK_NULL_HANDLE) {
return;
}
// Two-call idiom: query size, then fetch. Best-effort — a failure here only
// forfeits the next run's warm start, so it must never throw out of an
// atexit handler.
std::size_t size = 0;
if (vkGetPipelineCacheData(device, pipelineCache, &size, nullptr) != VK_SUCCESS || size == 0) {
return;
}
std::vector<std::byte> data(size);
if (vkGetPipelineCacheData(device, pipelineCache, &size, data.data()) != VK_SUCCESS) {
return;
}
std::ofstream file(pipelineCachePath, std::ios::binary | std::ios::trunc);
if (file) {
file.write(reinterpret_cast<const char*>(data.data()), static_cast<std::streamsize>(size));
}
}
VkBool32 onError(VkDebugUtilsMessageSeverityFlagBitsEXT severity, VkDebugUtilsMessageTypeFlagsEXT type, const VkDebugUtilsMessengerCallbackDataEXT* callbackData, void* userData)
{
printf("Vulkan ");
@ -551,12 +477,6 @@ void Device::Initialize() {
// https://github.com/KhronosGroup/Vulkan-ValidationLayers/issues/12103
// Per spencer-lunarg (LunarG) that was fixed in the next SDK release.
// The validation layer is now 1.4.350 (> 1.4.341), so re-enable it.
// Validation (incl. GPU-Assisted Validation) is a DEVELOPER tool and is OFF
// by default: GPU-AV instruments shaders and has crashed vendor SPIR-V
// compilers (observed: NVIDIA libnvidia-glvkspirv segfault on the
// descriptor-heap compute pipelines). Opt in by setting the environment
// variable CRAFTER_GRAPHICS_VALIDATION.
bool enableValidation = std::getenv("CRAFTER_GRAPHICS_VALIDATION") != nullptr;
VkValidationFeatureEnableEXT enabledValidationFeatures[] = {
VK_VALIDATION_FEATURE_ENABLE_GPU_ASSISTED_EXT,
};
@ -568,7 +488,7 @@ void Device::Initialize() {
VkInstanceCreateInfo instanceCreateInfo = {};
instanceCreateInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
instanceCreateInfo.pNext = enableValidation ? (const void*)&validationFeatures : nullptr;
instanceCreateInfo.pNext = &validationFeatures;
instanceCreateInfo.pApplicationInfo = &app;
instanceCreateInfo.enabledExtensionCount = sizeof(instanceExtensionNames) / sizeof(const char*);
instanceCreateInfo.ppEnabledExtensionNames = instanceExtensionNames;
@ -592,7 +512,7 @@ void Device::Initialize() {
}
}
if (enableValidation && foundInstanceLayers >= sizeof(layerNames) / sizeof(const char*))
if (foundInstanceLayers >= sizeof(layerNames) / sizeof(const char*))
{
instanceCreateInfo.enabledLayerCount = sizeof(layerNames) / sizeof(const char*);
instanceCreateInfo.ppEnabledLayerNames = layerNames;
@ -683,13 +603,6 @@ void Device::Initialize() {
.pNext = &rayTracingProperties
};
vkGetPhysicalDeviceProperties2(physDevice, &properties2);
// Keep the core properties around for the pipeline-cache identity check
// (vendorID / deviceID / pipelineCacheUUID).
deviceProperties = properties2.properties;
// Cache the flush/invalidate alignment for ranged host-memory flushes
// (VulkanBuffer::FlushDevice(offset,bytes)).
nonCoherentAtomSize = properties2.properties.limits.nonCoherentAtomSize;
// NVIDIA's brand-new VK_EXT_descriptor_heap acceleration-structure read
// path faults (see #7); enable the SPIR-V rewrite workaround there. Other
@ -867,7 +780,6 @@ void Device::Initialize() {
CheckVkResult(vkCreateCommandPool(device, &commandPoolcreateInfo, NULL, &commandPool));
vkGetPhysicalDeviceMemoryProperties(physDevice, &memoryProperties);
CacheUploadStrategy();
vkGetAccelerationStructureBuildSizesKHR = reinterpret_cast<PFN_vkGetAccelerationStructureBuildSizesKHR>(vkGetInstanceProcAddr(instance, "vkGetAccelerationStructureBuildSizesKHR"));
vkCreateAccelerationStructureKHR = reinterpret_cast<PFN_vkCreateAccelerationStructureKHR>(vkGetInstanceProcAddr(instance, "vkCreateAccelerationStructureKHR"));
@ -897,14 +809,6 @@ void Device::Initialize() {
memoryDecompressionSupported = false;
}
}
// Create the shared pipeline cache (seeded from disk when a compatible
// blob exists) and arrange for it to be written back at process exit. The
// device handle is a never-destroyed static, so it is still valid when the
// atexit handler runs. Registered once — Initialize is the single device
// bring-up.
LoadPipelineCache();
std::atexit(SavePipelineCache);
}
std::uint32_t Device::GetMemoryType(uint32_t typeBits, VkMemoryPropertyFlags required, VkMemoryPropertyFlags preferred) {
@ -937,92 +841,3 @@ std::uint32_t Device::GetMemoryType(uint32_t typeBits, VkMemoryPropertyFlags req
throw std::runtime_error("Could not find a matching memory type");
}
void Device::CacheUploadStrategy() {
constexpr VkMemoryPropertyFlags directFlags =
VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT;
// 1. Find a DEVICE_LOCAL | HOST_VISIBLE type and remember its heap. Without
// one (no resizable BAR), direct writes are impossible -> must stage.
bool haveDirectType = false;
std::uint32_t barHeapIndex = 0;
for (std::uint32_t i = 0; i < memoryProperties.memoryTypeCount; ++i) {
if ((memoryProperties.memoryTypes[i].propertyFlags & directFlags) == directFlags) {
haveDirectType = true;
barHeapIndex = memoryProperties.memoryTypes[i].heapIndex;
break;
}
}
if (!haveDirectType) {
directWriteBudget = 0;
return;
}
// 2. Compare the host-visible device-local heap against the largest plain
// DEVICE_LOCAL heap (the true VRAM size).
VkDeviceSize barHeap = memoryProperties.memoryHeaps[barHeapIndex].size;
VkDeviceSize vram = 0;
for (std::uint32_t i = 0; i < memoryProperties.memoryHeapCount; ++i) {
if (memoryProperties.memoryHeaps[i].flags & VK_MEMORY_HEAP_DEVICE_LOCAL_BIT) {
vram = std::max(vram, memoryProperties.memoryHeaps[i].size);
}
}
// 3. ReBAR / UMA: the BAR heap covers (almost) all of VRAM -> map any size.
// barHeap >= 0.9 * vram, written to dodge floating point / overflow.
if (barHeap >= vram - vram / 10) {
directWriteBudget = std::numeric_limits<VkDeviceSize>::max();
return;
}
// 4. Small BAR window: direct only for buffers small enough that several
// still fit the window — large buffers stage so they don't exhaust it.
// The budget is tied to the actual window size rather than a magic
// constant so it adapts across devices (a fixed cap would be wrong for
// both a 256 MiB and a 4 GiB window). VK_EXT_memory_budget would refine
// this to the window's *remaining* space; see the header note.
constexpr VkDeviceSize barWindowFraction = 8;
directWriteBudget = barHeap / barWindowFraction;
}
bool Device::PreferDirectDeviceWrite(VkDeviceSize size) {
// directWriteBudget caches the size-independent decision (CacheUploadStrategy):
// 0 -> never direct, max -> ReBAR/UMA so any size, else the small-window cap.
return directWriteBudget != 0 && size <= directWriteBudget;
}
void Device::EnqueueDeletion(VkBuffer buffer, VkDeviceMemory memory) {
// Nothing to free for an already-null handle — avoids parking dead
// entries that ReclaimDeletions would have to skip over.
if (buffer == VK_NULL_HANDLE) return;
deletionQueue.push_back({ frameCounter, buffer, memory });
}
void Device::ReclaimDeletions() {
// Free every entry whose retire frame has been reached. An entry tagged at
// frame F retires at F + framesInFlight: by the time the CPU has begun that
// many later frames (each gated by a per-image fence wait), single-queue
// submission order guarantees all GPU work from frame F is complete.
//
// frameCounter is monotonic, so retireAfter is non-decreasing down the
// queue and the ready entries are a contiguous prefix: pop them off the
// front and stop at the first one still in flight (everything behind it is
// newer, hence also in flight). O(ready), not O(queue).
while (!deletionQueue.empty() &&
deletionQueue.front().retireAfter + framesInFlight <= frameCounter) {
const PendingDeletion& entry = deletionQueue.front();
vkDestroyBuffer(device, entry.buffer, nullptr);
vkFreeMemory(device, entry.memory, nullptr);
deletionQueue.pop_front();
}
}
void Device::DrainDeletions() {
// Unconditional: the caller has just wait-idled, so no in-flight GPU work
// can still reference any queued resource.
for (PendingDeletion& entry : deletionQueue) {
vkDestroyBuffer(device, entry.buffer, nullptr);
vkFreeMemory(device, entry.memory, nullptr);
}
deletionQueue.clear();
}

View file

@ -1,5 +1,21 @@
//SPDX-License-Identifier: LGPL-3.0-only
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
/*
Crafter®.Graphics
Copyright (C) 2026 Catcrafts®
catcrafts.net
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License version 3.0 as published by the Free Software Foundation;
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
// Implementation of the :Dom partition. Only ever built when
// CRAFTER_GRAPHICS_WINDOW_DOM is defined (project.cpp's DOM branch

View file

@ -1,5 +1,22 @@
//SPDX-License-Identifier: LGPL-3.0-only
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
/*
Crafter®.Graphics
Copyright (C) 2026 Catcrafts®
Catcrafts.net
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 3.0 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
module;
#define STB_TRUETYPE_IMPLEMENTATION
@ -39,23 +56,6 @@ Font::Font(const std::filesystem::path& fontFilePath) {
this->ascent = ascent;
this->descent = descent;
this->lineGap = lineGap;
asciiAdvance_.fill(-1);
}
std::int32_t Font::AdvanceUnits(std::uint32_t cp) {
if (cp < asciiAdvance_.size()) {
if (asciiAdvance_[cp] < 0) {
int advance = 0, lsb = 0;
stbtt_GetCodepointHMetrics(&font, static_cast<int>(cp), &advance, &lsb);
asciiAdvance_[cp] = advance;
}
return asciiAdvance_[cp];
}
if (auto it = advanceUnits_.find(cp); it != advanceUnits_.end()) return it->second;
int advance = 0, lsb = 0;
stbtt_GetCodepointHMetrics(&font, static_cast<int>(cp), &advance, &lsb);
return advanceUnits_.emplace(cp, advance).first->second;
}
std::uint32_t Font::GetLineWidth(const std::string_view text, float size) {
@ -65,7 +65,9 @@ std::uint32_t Font::GetLineWidth(const std::string_view text, float size) {
while (i < text.size()) {
std::uint32_t cp = DecodeUtf8(text, i);
if (cp == 0) break;
lineWidth += (int)(AdvanceUnits(cp) * scale);
int advance, lsb;
stbtt_GetCodepointHMetrics(&font, static_cast<int>(cp), &advance, &lsb);
lineWidth += (int)(advance * scale);
}
return lineWidth;
}
@ -80,7 +82,9 @@ std::size_t Font::NearestCursorByte(std::string_view text, float size, float tar
while (i < text.size()) {
std::uint32_t cp = DecodeUtf8(text, i); // i advances to the next boundary
if (cp == 0) break;
cumWidth += (int)(AdvanceUnits(cp) * scale); // match GetLineWidth's per-glyph rounding
int advance, lsb;
stbtt_GetCodepointHMetrics(&font, static_cast<int>(cp), &advance, &lsb);
cumWidth += (int)(advance * scale); // match GetLineWidth's per-glyph rounding
float d = std::abs(target - cumWidth);
if (d < bestDist) {
bestDist = d;

View file

@ -1,6 +1,3 @@
//SPDX-License-Identifier: LGPL-3.0-only
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
/*
Crafter®.Graphics
Copyright (C) 2026 Catcrafts®
@ -42,11 +39,7 @@ void FontAtlas::Initialize(GraphicsCommandBuffer cmd) {
VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
// The atlas is sampled by the UI text *compute* shader, not an RT
// pipeline — scope the upload barriers to the real consumer.
VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
// Streamed: glyphs are rasterized into buffer.value on the CPU and
// re-uploaded every frame via UpdateRegion, so the persistent staging
// map must outlive the first upload rather than being released (#114).
/*streamed*/ true
VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT
);
std::memset(image.buffer.value, 0, kAtlasSize * kAtlasSize);
#else
@ -62,13 +55,11 @@ void FontAtlas::Initialize(GraphicsCommandBuffer cmd) {
MarkDirty(0, 0, kAtlasSize, kAtlasSize);
}
bool FontAtlas::ShelfPlace(int w, int h, int& outX, int& outY, int& outShelf) {
for (std::size_t i = 0; i < shelves_.size(); ++i) {
Shelf& s = shelves_[i];
bool FontAtlas::ShelfPlace(int w, int h, int& outX, int& outY) {
for (Shelf& s : shelves_) {
if (h <= s.height && s.cursorX + w <= kAtlasSize) {
outX = s.cursorX;
outY = s.y;
outShelf = static_cast<int>(i);
s.cursorX += w;
return true;
}
@ -80,7 +71,6 @@ bool FontAtlas::ShelfPlace(int w, int h, int& outX, int& outY, int& outShelf) {
s.cursorX = w;
outX = 0;
outY = s.y;
outShelf = static_cast<int>(shelves_.size());
shelves_.push_back(s);
nextShelfY_ += h;
return true;
@ -112,8 +102,8 @@ const Glyph* FontAtlas::EnsureAndGet(Font& font, std::uint32_t codepoint) {
g.yoff = static_cast<float>(yoff);
if (sdf && sw > 0 && sh > 0) {
int px = 0, py = 0, shelf = 0;
if (!ShelfPlace(sw, sh, px, py, shelf)) {
int px = 0, py = 0;
if (!ShelfPlace(sw, sh, px, py)) {
stbtt_FreeSDF(sdf, nullptr);
return nullptr;
}
@ -133,10 +123,7 @@ const Glyph* FontAtlas::EnsureAndGet(Font& font, std::uint32_t codepoint) {
g.v0 = static_cast<float>(py) / kAtlasSize;
g.u1 = static_cast<float>(px + sw) / kAtlasSize;
g.v1 = static_cast<float>(py + sh) / kAtlasSize;
// Mark the *shelf's* span, not one global box — keeps each upload
// tight when glyphs land on different shelves the same frame (#129).
shelves_[shelf].dirty.Add(px, py, sw, sh);
dirty = true;
MarkDirty(px, py, sw, sh);
}
return &cache_.emplace(key, g).first->second;
@ -150,18 +137,18 @@ const Glyph* FontAtlas::Lookup(Font& font, std::uint32_t codepoint) const {
void FontAtlas::Update(GraphicsCommandBuffer cmd) {
if (!dirty) return;
// Issue one tight copy per dirty span and reset it. Clamping to the atlas
// keeps each extent provably valid even though Add() already works in
// in-bounds glyph coordinates; UploadBox skips spans that never armed.
// The spans are the whole-atlas zero-clear (dirtyRect, Initialize only)
// plus each shelf's accumulated glyph run — so scattered glyphs upload as
// several small rects, not one tall union covering the gaps between them.
auto upload = [&](DirtyRect& r) {
// Clamp the accumulated box to the atlas and convert to (origin,
// extent). Add() works in glyph coordinates that are always in-bounds,
// but clamping keeps the copy extent provably valid. The `dirty` guard
// above guarantees the rect is non-empty, so UploadBox always fills the
// outputs.
std::uint32_t x = 0, y = 0, w = 0, h = 0;
if (!r.UploadBox(kAtlasSize, x, y, w, h)) return;
dirtyRect.UploadBox(kAtlasSize, x, y, w, h);
#ifndef CRAFTER_GRAPHICS_WINDOW_DOM
image.UpdateRegion(cmd, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, x, y, w, h);
#else
(void)cmd;
// The staging buffer keeps the full atlas row stride, so srcBytesPerRow
// stays kAtlasSize and (dstX, dstY) index the sub-rect's first texel.
WebGPU::wgpuWriteAtlasRegion(
@ -171,14 +158,6 @@ void FontAtlas::Update(GraphicsCommandBuffer cmd) {
static_cast<std::int32_t>(w), static_cast<std::int32_t>(h)
);
#endif
r.Reset();
};
#ifdef CRAFTER_GRAPHICS_WINDOW_DOM
(void)cmd;
#endif
upload(dirtyRect);
for (Shelf& s : shelves_) upload(s.dirty);
dirty = false;
dirtyRect.Reset();
}

View file

@ -1,6 +1,22 @@
//SPDX-License-Identifier: LGPL-3.0-only
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
/*
Crafter®.Graphics
Copyright (C) 2026 Catcrafts®
Catcrafts.net
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 3.0 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
module;
#ifdef CRAFTER_GRAPHICS_WINDOW_WAYLAND
#include <libudev.h>

View file

@ -1,6 +1,22 @@
//SPDX-License-Identifier: LGPL-3.0-only
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
/*
Crafter®.Graphics
Copyright (C) 2026 Catcrafts®
Catcrafts.net
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 3.0 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
module;
module Crafter.Graphics;
import std;

View file

@ -1,6 +1,21 @@
//SPDX-License-Identifier: LGPL-3.0-only
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
/*
Crafter®.Graphics
Copyright (C) 2026 Catcrafts®
catcrafts.net
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License version 3.0 as published by the Free Software Foundation;
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
module;
module Crafter.Graphics:InputField_impl;
import :InputField;
@ -135,21 +150,7 @@ void Crafter::DrawInputField(UIBuffer& buf, const InputField& f, Rect rect,
if (f.focused && caretVisible && *buf.quadCount < buf.quadCap) {
std::string_view sub(f.value.data(), std::min(f.cursorPos, f.value.size()));
// Memoise the prefix width (issue #128): only the blink changes between
// frames, so re-walking the prefix every frame is wasted work. A byte
// compare of the cached prefix (plus fontSize) is far cheaper than the
// per-glyph UTF-8 decode + advance accumulation GetLineWidth does.
float width;
if (f.caretCacheFontSize_ == fontSize && f.caretCachePrefix_ == sub) {
width = f.caretCacheWidth_;
} else {
width = sub.empty() ? 0.0f
: static_cast<float>(font.GetLineWidth(sub, fontSize));
f.caretCachePrefix_.assign(sub);
f.caretCacheFontSize_ = fontSize;
f.caretCacheWidth_ = width;
}
float caretX = textX + width;
float caretX = textX + (sub.empty() ? 0.0f : static_cast<float>(font.GetLineWidth(sub, fontSize)));
float caretH = fontSize * 1.1f;
float caretY = rect.y + (rect.h - caretH) * 0.5f;
float caretW = std::max(1.0f, fontSize / 16.0f);

View file

@ -1,6 +1,3 @@
//SPDX-License-Identifier: LGPL-3.0-only
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
/*
Crafter®.Graphics
Copyright (C) 2026 Catcrafts®
@ -380,18 +377,6 @@ void Mesh::Refit(std::span<Vector<float, 3, 3>> vertices,
Build(vertices, indices, cmd);
}
void Mesh::Refit(std::span<Vector<float, 3, 3>> vertices,
std::span<std::uint32_t> indices,
std::uint32_t /*dirtyVertexOffset*/,
std::uint32_t /*dirtyVertexCount*/,
WebGPUCommandEncoderRef cmd) {
// No hardware AS, so there is no sub-range to update in place — the
// software path rebuilds the host BVH over the full geometry regardless.
// The dirty window only matters to the hardware backend's ranged upload
// (#119); here it is ignored and this is identical to the full-span Refit.
Build(vertices, indices, cmd);
}
void Mesh::RefitProcedural(std::span<const RTAabb> aabbs,
WebGPUCommandEncoderRef cmd) {
BuildProcedural(aabbs, opaque, cmd);

View file

@ -1,5 +1,21 @@
//SPDX-License-Identifier: LGPL-3.0-only
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
/*
Crafter®.Graphics
Copyright (C) 2026 Catcrafts®
catcrafts.net
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License version 3.0 as published by the Free Software Foundation;
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
module;
#include "vulkan/vulkan.h"
@ -16,16 +32,10 @@ using namespace Crafter;
namespace {
// Buffer-usage flag set shared by both Build paths. The compressed path
// appends VK_BUFFER_USAGE_2_MEMORY_DECOMPRESSION_BIT_EXT, and the staged
// upload path appends VK_BUFFER_USAGE_TRANSFER_DST_BIT. TRANSFER_SRC is in
// the base because the geometry is now device-local (#73): once it no longer
// lives in host-mappable memory, a transfer copy is the only way to read it
// back (debugging, GPU-driven workflows, decompression validation) — a free
// usage flag that keeps device-local geometry inspectable.
// appends VK_BUFFER_USAGE_2_MEMORY_DECOMPRESSION_BIT_EXT.
constexpr VkBufferUsageFlags2 kVertexUsageBase =
VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT
| VK_BUFFER_USAGE_2_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT_KHR
| VK_BUFFER_USAGE_TRANSFER_SRC_BIT;
| VK_BUFFER_USAGE_2_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT_KHR;
constexpr VkBufferUsageFlags2 kIndexUsageBase =
kVertexUsageBase | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT;
@ -142,23 +152,6 @@ namespace {
self.buildFlags = flags;
self.builtPrimitiveCount = primitiveCount;
// Static (!allowUpdate) meshes can never refit, so their per-mesh
// scratch is dead weight the moment this build's GPU work completes —
// release it instead of keeping a persistent DEVICE_LOCAL allocation
// per mesh (the waste that dominates many-mesh scenes, issue #66). The
// fresh build recorded above still reads scratchBuffer.address from
// this command buffer, so a plain Clear() would be a use-after-free;
// DeferredClear() retires the allocation only once the build's frame
// has passed its fence (the queue from #101/#102). A later Refit on a
// static mesh takes the rebuild fallback, whose Resize sees the nulled
// handle and re-Creates the scratch. Refit-capable meshes keep theirs:
// an in-place UPDATE reuses it every frame (build scratch ≥ update
// scratch, so no resize). Only applies to a fresh build — an UPDATE
// never reaches here for a static mesh.
if (!update && !self.allowUpdate) {
self.scratchBuffer.DeferredClear();
}
}
void RecordBLASBuild(Mesh& self, std::uint32_t vertexCount, std::uint32_t indexCount, VkBuildAccelerationStructureFlagsKHR flags, bool update, VkCommandBuffer cmd) {
@ -191,13 +184,14 @@ namespace {
}
void Mesh::Build(std::span<Vector<float, 3, 3>> verticies, std::span<std::uint32_t> indicies, VkCommandBuffer cmd, RTBuildOptions options) {
// Place both inputs in device-local memory (direct map on ReBAR/UMA,
// staged copy otherwise — UploadDeviceLocal decides) and barrier the
// upload before the BLAS build reads them. Replaces the previous
// HOST_VISIBLE allocation that the build (and any hit-shader fetch) would
// read over PCIe every frame (#73).
vertexBuffer.UploadDeviceLocal(kVertexUsageBase, verticies.data(), static_cast<std::uint32_t>(verticies.size()), cmd, VK_ACCESS_MEMORY_READ_BIT, VK_PIPELINE_STAGE_ACCELERATION_STRUCTURE_BUILD_BIT_KHR);
indexBuffer.UploadDeviceLocal(kIndexUsageBase, indicies.data(), static_cast<std::uint32_t>(indicies.size()), cmd, VK_ACCESS_MEMORY_READ_BIT, VK_PIPELINE_STAGE_ACCELERATION_STRUCTURE_BUILD_BIT_KHR);
vertexBuffer.Resize(kVertexUsageBase, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, verticies.size());
indexBuffer.Resize(kIndexUsageBase, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, indicies.size());
std::memcpy(vertexBuffer.value, verticies.data(), verticies.size() * sizeof(Vector<float, 3, 3>));
std::memcpy(indexBuffer.value, indicies.data(), indicies.size() * sizeof(std::uint32_t));
vertexBuffer.FlushDevice(cmd, VK_ACCESS_MEMORY_READ_BIT, VK_PIPELINE_STAGE_ACCELERATION_STRUCTURE_BUILD_BIT_KHR);
indexBuffer.FlushDevice(cmd, VK_ACCESS_MEMORY_READ_BIT, VK_PIPELINE_STAGE_ACCELERATION_STRUCTURE_BUILD_BIT_KHR);
allowUpdate = options.allowUpdate;
builtInputCount = static_cast<std::uint32_t>(verticies.size());
@ -224,17 +218,13 @@ void Mesh::Build(const CompressedMeshAsset& asset, VkCommandBuffer cmd, RTBuildO
return;
}
// The GPU decompressor writes vertex/index directly (the build input is
// never host-written on this path), so they want pure DEVICE_LOCAL — no
// host visibility, no map. This is where the BLAS build and any hit-shader
// fetch then read them from (#73).
vertexBuffer.Resize(
kVertexUsageBase | VK_BUFFER_USAGE_2_MEMORY_DECOMPRESSION_BIT_EXT,
VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT,
asset.vertexCount);
indexBuffer.Resize(
kIndexUsageBase | VK_BUFFER_USAGE_2_MEMORY_DECOMPRESSION_BIT_EXT,
VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT,
asset.indexCount);
compressedStaging.Resize(
@ -271,16 +261,6 @@ void Mesh::Build(const CompressedMeshAsset& asset, VkCommandBuffer cmd, RTBuildO
VK_PIPELINE_STAGE_2_ACCELERATION_STRUCTURE_BUILD_BIT_KHR,
VK_ACCESS_2_ACCELERATION_STRUCTURE_READ_BIT_KHR);
// The compressed staging is only read by the decompress recorded above; the
// subsequent BLAS build reads the decompressed vertex/index buffers, never
// this. So hand it to the fence-keyed deletion queue (#101/#102) now rather
// than pinning host-visible memory for the mesh's whole life. The recorded
// vkCmdDecompressMemoryEXT still references compressedStaging.address, so it
// must outlive this submit — which the queue guarantees: it retires the
// allocation only after framesInFlight frames have elapsed, by which point
// the decompress submit's fence has cleared.
compressedStaging.DeferredClear();
allowUpdate = options.allowUpdate;
builtInputCount = asset.vertexCount;
RecordBLASBuild(*this, asset.vertexCount, asset.indexCount, BlasFlags(options), /*update*/ false, cmd);
@ -320,13 +300,14 @@ namespace {
void RecordProceduralBuild(Mesh& self, std::span<const RTAabb> aabbs, VkBuildAccelerationStructureFlagsKHR flags, bool update, VkCommandBuffer cmd) {
// 24-byte-stride VkAabbPositionsKHR-compatible build input
// (static_assert'd in the interface). Same usage set as the triangle
// inputs: AS-build read-only + device address. UploadDeviceLocal places
// it in device-local memory (direct map on ReBAR/UMA, staged otherwise,
// #73) and barriers the upload before the build reads it. A refit
// re-uploads into the same same-sized buffer: Resize reuses the existing
// allocation (count unchanged), so the device address — and the geometry
// it feeds — stays stable for an in-place UPDATE.
self.aabbBuffer.UploadDeviceLocal(kVertexUsageBase, aabbs.data(), static_cast<std::uint32_t>(aabbs.size()), cmd, VK_ACCESS_MEMORY_READ_BIT, VK_PIPELINE_STAGE_ACCELERATION_STRUCTURE_BUILD_BIT_KHR);
// inputs: AS-build read-only + device address. A refit reuses the
// existing same-sized buffer (count is unchanged), so the device
// address — and the geometry it feeds — stays stable.
if (!update) {
self.aabbBuffer.Resize(kVertexUsageBase, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, static_cast<std::uint32_t>(aabbs.size()));
}
std::memcpy(self.aabbBuffer.value, aabbs.data(), aabbs.size() * sizeof(RTAabb));
self.aabbBuffer.FlushDevice(cmd, VK_ACCESS_MEMORY_READ_BIT, VK_PIPELINE_STAGE_ACCELERATION_STRUCTURE_BUILD_BIT_KHR);
RecordProceduralBuildFromAddress(self, self.aabbBuffer.address, static_cast<std::uint32_t>(aabbs.size()), sizeof(RTAabb), flags, update, cmd);
}
@ -355,11 +336,6 @@ void Mesh::BuildProcedural(VkDeviceAddress aabbAddress, std::uint32_t count, boo
}
void Mesh::Refit(std::span<Vector<float, 3, 3>> verticies, std::span<std::uint32_t> indicies, VkCommandBuffer cmd) {
// Whole-vertex-array refit: the entire array is the dirty range.
Refit(verticies, indicies, 0, static_cast<std::uint32_t>(verticies.size()), cmd);
}
void Mesh::Refit(std::span<Vector<float, 3, 3>> verticies, std::span<std::uint32_t> indicies, std::uint32_t dirtyVertexOffset, std::uint32_t dirtyVertexCount, VkCommandBuffer cmd) {
// A hardware in-place UPDATE is only valid when the original build asked
// for it, an AS already exists, and the topology is unchanged. Otherwise
// fall back to a full rebuild (mode BUILD) of the same buffers — still
@ -372,9 +348,7 @@ void Mesh::Refit(std::span<Vector<float, 3, 3>> verticies, std::span<std::uint32
if (!update) {
// Counts may have changed (or update wasn't permitted): take the
// resizing build path, preserving the caller's original flags. The
// dirty window is irrelevant here — a fresh build re-uploads the whole
// array, which is why the full arrays are passed even on this overload.
// resizing build path, preserving the caller's original flags.
Build(verticies, indicies, cmd, RTBuildOptions{
.preference = (buildFlags & VK_BUILD_ACCELERATION_STRUCTURE_PREFER_FAST_BUILD_BIT_KHR)
? RTBuildPreference::FastBuild : RTBuildPreference::FastTrace,
@ -383,29 +357,12 @@ void Mesh::Refit(std::span<Vector<float, 3, 3>> verticies, std::span<std::uint32
return;
}
// Same-sized buffers: overwrite the moved vertex positions in place so the
// device address (and thus the geometry the UPDATE reads) stays stable.
// The index buffer is deliberately left untouched: a hardware AS UPDATE
// cannot change topology, so the indices are immutable here — re-uploading
// them would be a wasted memcpy + flush + barrier of unchanged data every
// refit. This means a bitwise-different-but-topologically-equivalent index
// array passed on refit is ignored, consistent with the documented
// contract that a refit may only move vertex positions.
//
// Re-upload only the dirty sub-range [dirtyVertexOffset, +dirtyVertexCount):
// the rest of the vertex buffer already holds last refit's positions, so a
// ranged upload patches just the vertices that moved (#119). The window is
// clamped to the array — a caller window past the end would otherwise read
// out of bounds / overflow the copy. UploadDeviceLocalRange writes into the
// existing same-sized allocation (no Resize), so the address the UPDATE
// reads stays stable, then barriers just that sub-range before the build. On
// the staged path this re-stages only the dirty slice (the deforming-mesh
// fallback, #73).
std::uint32_t offset = std::min(dirtyVertexOffset, static_cast<std::uint32_t>(verticies.size()));
std::uint32_t count = std::min(dirtyVertexCount, static_cast<std::uint32_t>(verticies.size()) - offset);
if (count != 0) {
vertexBuffer.UploadDeviceLocalRange(verticies.data() + offset, offset, count, cmd, VK_ACCESS_MEMORY_READ_BIT, VK_PIPELINE_STAGE_ACCELERATION_STRUCTURE_BUILD_BIT_KHR);
}
// Same-sized buffers: overwrite in place so the device addresses (and
// thus the geometry the UPDATE reads) stay stable.
std::memcpy(vertexBuffer.value, verticies.data(), verticies.size() * sizeof(Vector<float, 3, 3>));
std::memcpy(indexBuffer.value, indicies.data(), indicies.size() * sizeof(std::uint32_t));
vertexBuffer.FlushDevice(cmd, VK_ACCESS_MEMORY_READ_BIT, VK_PIPELINE_STAGE_ACCELERATION_STRUCTURE_BUILD_BIT_KHR);
indexBuffer.FlushDevice(cmd, VK_ACCESS_MEMORY_READ_BIT, VK_PIPELINE_STAGE_ACCELERATION_STRUCTURE_BUILD_BIT_KHR);
RecordBLASBuild(*this, static_cast<std::uint32_t>(verticies.size()), static_cast<std::uint32_t>(indicies.size()), buildFlags, /*update*/ true, cmd);
}

View file

@ -1,6 +1,3 @@
//SPDX-License-Identifier: LGPL-3.0-only
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
/*
Crafter®.Graphics
Copyright (C) 2026 Catcrafts®

View file

@ -1,6 +1,3 @@
//SPDX-License-Identifier: LGPL-3.0-only
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
/*
Crafter®.Graphics
Copyright (C) 2026 Catcrafts®
@ -111,16 +108,9 @@ void RenderingElement3D::BuildTLASUpload(WebGPUCommandEncoderRef /*cmd*/, std::u
auto& dst = tlas.instanceBuffer.value[i];
const auto& src = elements[i]->instance;
if (elements[i]->transformOwnedByGpu) {
// GPU owns the transform: copy only the host-authored
// metadata fields and leave the host mirror's transform bytes
// alone (the application doesn't maintain them). The upload
// below pushes the whole struct, including these transform
// bytes, but the physics-tlas-transform compute pass — which
// runs after this Upload and before Build in the supported
// Upload -> compute -> Build flow — overwrites the transform
// on the GPU before the TLAS build reads it, so the host-side
// value is moot. (Nothing reads instanceBuffer between Upload
// and that compute pass.)
// Preserve whatever the GPU compute shader most recently
// wrote into dst.transform. Update only the non-transform
// fields.
dst.instanceCustomIndex = src.instanceCustomIndex;
dst.mask = src.mask;
dst.instanceShaderBindingTableRecordOffset = src.instanceShaderBindingTableRecordOffset;
@ -132,34 +122,44 @@ void RenderingElement3D::BuildTLASUpload(WebGPUCommandEncoderRef /*cmd*/, std::u
tlas.metadataBuffer.value[i] = elements[i]->userMetadata;
}
// Upload the active instance range in a single contiguous writeBuffer.
//
// An earlier version split this into per-run arms: contiguous runs of
// CPU-driven elements (transformOwnedByGpu=false) were pushed as one
// block, but GPU-driven runs pushed only the trailing 16 metadata
// bytes of each element — one FlushDeviceRange per element — to avoid
// clobbering the GPU-written transform. The metadata bytes are strided
// (one 16-byte chunk per 64-byte slot), so a GPU-driven run couldn't
// batch; each element paid a separate WebGPU validation / encode /
// JS-boundary cost.
//
// Pushing the whole struct for GPU-driven elements too is harmless:
// the only supported way to drive a transform from the GPU is the
// manual Upload -> physics compute pass -> Build sequence (see the
// file header), and that compute pass runs after this upload and
// rewrites the transform on the GPU before the TLAS build reads it.
// So the stale transform bytes this push carries for those slots are
// overwritten before they matter, and the whole run uploads in one
// call. (The combined BuildTLAS path runs no compute pass and is, as
// documented, only valid for CPU-driven transforms.)
// Upload the instance buffer with partial-write semantics: for runs
// of CPU-driven elements (transformOwnedByGpu=false) we push the
// whole 64-byte struct in one writeBuffer call; for GPU-driven runs
// we push only the trailing 16 metadata bytes per element, leaving
// the transform field intact for the physics-tlas-transform compute
// shader to update. The two arms below produce identical GPU state
// when every element is CPU-driven — this is a no-op refactor until
// 3DForts flips its physics elements to transformOwnedByGpu=true.
constexpr std::uint32_t kInstSize = sizeof(RTInstance); // 64
tlas.instanceBuffer.FlushDeviceRange(0, 0, primitiveCount * kInstSize);
constexpr std::uint32_t kTransformSize = sizeof(RTTransformMatrix); // 48
constexpr std::uint32_t kMetaSize = kInstSize - kTransformSize; // 16
// Only primitiveCount slots are live; the buffer is padded to kNPadded
// (65536). Flushing the whole thing wgpuWriteBuffers all 256 KB through
// the WASM->JS staging path every frame — ~100-250x waste for a
// few-hundred-instance scene. Range-flush just the live entries.
tlas.metadataBuffer.FlushDeviceRange(0, 0, primitiveCount * sizeof(std::uint32_t));
std::uint32_t runStart = 0;
bool runOwned = elements[0]->transformOwnedByGpu;
for (std::uint32_t i = 1; i <= primitiveCount; ++i) {
const bool atEnd = (i == primitiveCount);
const bool currOwned = atEnd ? !runOwned : elements[i]->transformOwnedByGpu;
if (currOwned == runOwned && !atEnd) continue;
if (runOwned) {
// GPU-driven run — metadata only, per element. Cannot batch
// because the metadata bytes are non-contiguous in the
// instance buffer (one 16-byte chunk per 64-byte slot).
for (std::uint32_t j = runStart; j < i; ++j) {
const std::uint32_t off = j * kInstSize + kTransformSize;
tlas.instanceBuffer.FlushDeviceRange(off, off, kMetaSize);
}
} else {
// CPU-driven run — one contiguous writeBuffer.
const std::uint32_t startOff = runStart * kInstSize;
const std::uint32_t bytes = (i - runStart) * kInstSize;
tlas.instanceBuffer.FlushDeviceRange(startOff, startOff, bytes);
}
runStart = i;
runOwned = currOwned;
}
tlas.metadataBuffer.FlushDevice();
}
void RenderingElement3D::BuildTLASBuild(WebGPUCommandEncoderRef /*cmd*/, std::uint32_t index) {

Some files were not shown because too many files have changed in this diff Show more