Compare commits

..

No commits in common. "main" and "vulkan_api_wrapper" have entirely different histories.

110 changed files with 4694 additions and 6056 deletions

View file

@ -2,8 +2,6 @@
kind: pipeline kind: pipeline
type: exec type: exec
name: amd64 — msvc name: amd64 — msvc
node:
environment: lina
trigger: trigger:
branch: branch:
- main - main
@ -15,14 +13,12 @@ steps:
- name: unit tests - name: unit tests
shell: powershell shell: powershell
commands: commands:
- pwsh ./tools/ci/amd64/msvc/unit_tests.ps1 - ./tools/ci/amd64/msvc/unit_tests.ps1
--- ---
kind: pipeline kind: pipeline
type: docker type: docker
name: amd64 — gcc name: amd64 — gcc
node:
environment: marci
trigger: trigger:
branch: branch:
- main - main
@ -44,8 +40,6 @@ steps:
kind: pipeline kind: pipeline
type: docker type: docker
name: amd64 — clang name: amd64 — clang
node:
environment: marci
trigger: trigger:
branch: branch:
- main - main
@ -76,8 +70,6 @@ steps:
kind: pipeline kind: pipeline
type: docker type: docker
name: static analysis name: static analysis
node:
environment: marci
trigger: trigger:
branch: branch:
- main - main

14
.gitignore vendored
View file

@ -1,9 +1,11 @@
# Temp directories
.vs/ .vs/
bin/ bin/
bin-obj/ bin-obj/
build/ build/
.cache/ .cache/
# VS Files
**.vcxproj** **.vcxproj**
**.sln **.sln
@ -15,9 +17,21 @@ build/
Makefile Makefile
**/**.mk **/**.mk
**/**.project **/**.project
**/Engine.txt
**/GLAD.txt
**/Sandbox.txt
**/Logs/**
**/logs/**
**.ini
!**/default_gui_layout.ini
CMake/
CMakeUserPresets.json CMakeUserPresets.json
compile_commands.json compile_commands.json

View file

@ -7,7 +7,7 @@ set(CMAKE_CXX_MODULE_STD 1)
cmake_minimum_required(VERSION 4.1) cmake_minimum_required(VERSION 4.1)
project(Light) project(Light)
include(${CMAKE_CURRENT_SOURCE_DIR}/tools/cmake/module.cmake) include(${CMAKE_CURRENT_SOURCE_DIR}/tools/cmake/functions.cmake)
include(${CMAKE_CURRENT_SOURCE_DIR}/tools/cmake/definitions.cmake) include(${CMAKE_CURRENT_SOURCE_DIR}/tools/cmake/definitions.cmake)
include(${CMAKE_CURRENT_SOURCE_DIR}/tools/cmake/options.cmake) include(${CMAKE_CURRENT_SOURCE_DIR}/tools/cmake/options.cmake)

859
LICENSE
View file

@ -1,674 +1,201 @@
GNU GENERAL PUBLIC LICENSE Apache License
Version 3, 29 June 2007 Version 2.0, January 2004
http://www.apache.org/licenses/
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
of this license document, but changing it is not allowed.
1. Definitions.
Preamble
"License" shall mean the terms and conditions for use, reproduction,
The GNU General Public License is a free, copyleft license for and distribution as defined by Sections 1 through 9 of this document.
software and other kinds of works.
"Licensor" shall mean the copyright owner or entity authorized by
The licenses for most software and other practical works are designed the copyright owner that is granting the License.
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 "Legal Entity" shall mean the union of the acting entity and all
share and change all versions of a program--to make sure it remains free other entities that control, are controlled by, or are under common
software for all its users. We, the Free Software Foundation, use the control with that entity. For the purposes of this definition,
GNU General Public License for most of our software; it applies also to "control" means (i) the power, direct or indirect, to cause the
any other work released this way by its authors. You can apply it to direction or management of such entity, whether by contract or
your programs, too. otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you "You" (or "Your") shall mean an individual or Legal Entity
have the freedom to distribute copies of free software (and charge for exercising permissions granted by this License.
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 "Source" form shall mean the preferred form for making modifications,
free programs, and that you know you can do these things. including but not limited to software source code, documentation
source, and configuration files.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have "Object" form shall mean any form resulting from mechanical
certain responsibilities if you distribute copies of the software, or if transformation or translation of a Source form, including but
you modify it: responsibilities to respect the freedom of others. not limited to compiled object code, generated documentation,
and conversions to other media types.
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 "Work" shall mean the work of authorship, whether in Source or
freedoms that you received. You must make sure that they, too, receive Object form, made available under the License, as indicated by a
or can get the source code. And you must show them these terms so they copyright notice that is included in or attached to the work
know their rights. (an example is provided in the Appendix below).
Developers that use the GNU GPL protect your rights with two steps: "Derivative Works" shall mean any work, whether in Source or Object
(1) assert copyright on the software, and (2) offer you this License form, that is based on (or derived from) the Work and for which the
giving you legal permission to copy, distribute and/or modify it. editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
For the developers' and authors' protection, the GPL clearly explains of this License, Derivative Works shall not include works that remain
that there is no warranty for this free software. For both users' and separable from, or merely link (or bind by name) to the interfaces of,
authors' sake, the GPL requires that modified versions be marked as the Work and Derivative Works thereof.
changed, so that their problems will not be attributed erroneously to
authors of previous versions. "Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
Some devices are designed to deny users access to install or run to that Work or Derivative Works thereof, that is intentionally
modified versions of the software inside them, although the manufacturer submitted to Licensor for inclusion in the Work by the copyright owner
can do so. This is fundamentally incompatible with the aim of or by an individual or Legal Entity authorized to submit on behalf of
protecting users' freedom to change the software. The systematic the copyright owner. For the purposes of this definition, "submitted"
pattern of such abuse occurs in the area of products for individuals to means any form of electronic, verbal, or written communication sent
use, which is precisely where it is most unacceptable. Therefore, we to the Licensor or its representatives, including but not limited to
have designed this version of the GPL to prohibit the practice for those communication on electronic mailing lists, source code control systems,
products. If such problems arise substantially in other domains, we and issue tracking systems that are managed by, or on behalf of, the
stand ready to extend this provision to those domains in future versions Licensor for the purpose of discussing and improving the Work, but
of the GPL, as needed to protect the freedom of users. excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of "Contributor" shall mean Licensor and any individual or Legal Entity
software on general-purpose computers, but in those that do, we wish to on behalf of whom a Contribution has been received by Licensor and
avoid the special danger that patents applied to a free program could subsequently incorporated within the Work.
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free. 2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
The precise terms and conditions for copying, distribution and worldwide, non-exclusive, no-charge, royalty-free, irrevocable
modification follow. copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
TERMS AND CONDITIONS Work and such Derivative Works in Source or Object form.
0. Definitions. 3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
"This License" refers to version 3 of the GNU General Public License. worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
"Copyright" also means copyright-like laws that apply to other kinds of use, offer to sell, sell, import, and otherwise transfer the Work,
works, such as semiconductor masks. where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
"The Program" refers to any copyrightable work licensed under this Contribution(s) alone or by combination of their Contribution(s)
License. Each licensee is addressed as "you". "Licensees" and with the Work to which such Contribution(s) was submitted. If You
"recipients" may be individuals or organizations. institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
To "modify" a work means to copy from or adapt all or part of the work or a Contribution incorporated within the Work constitutes direct
in a fashion requiring copyright permission, other than the making of an or contributory patent infringement, then any patent licenses
exact copy. The resulting work is called a "modified version" of the granted to You under this License for that Work shall terminate
earlier work or a work "based on" the earlier work. as of the date such litigation is filed.
A "covered work" means either the unmodified Program or a work based 4. Redistribution. You may reproduce and distribute copies of the
on the Program. Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
To "propagate" a work means to do anything with it that, without meet the following conditions:
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a (a) You must give any other recipients of the Work or
computer or modifying a private copy. Propagation includes copying, Derivative Works a copy of this License; and
distribution (with or without modification), making available to the
public, and in some countries other activities as well. (b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through (c) You must retain, in the Source form of any Derivative Works
a computer network, with no transfer of a copy, is not conveying. that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
An interactive user interface displays "Appropriate Legal Notices" excluding those notices that do not pertain to any part of
to the extent that it includes a convenient and prominently visible the Derivative Works; and
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the (d) If the Work includes a "NOTICE" text file as part of its
extent that warranties are provided), that licensees may convey the distribution, then any Derivative Works that You distribute must
work under this License, and how to view a copy of this License. If include a readable copy of the attribution notices contained
the interface presents a list of user commands or options, such as a within such NOTICE file, excluding those notices that do not
menu, a prominent item in the list meets this criterion. pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
1. Source Code. as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
The "source code" for a work means the preferred form of the work within a display generated by the Derivative Works, if and
for making modifications to it. "Object code" means any non-source wherever such third-party notices normally appear. The contents
form of a work. of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
A "Standard Interface" means an interface that either is an official notices within Derivative Works that You distribute, alongside
standard defined by a recognized standards body, or, in the case of or as an addendum to the NOTICE text from the Work, provided
interfaces specified for a particular programming language, one that that such additional attribution notices cannot be construed
is widely used among developers working in that language. as modifying the License.
The "System Libraries" of an executable work include anything, other You may add Your own copyright statement to Your modifications and
than the work as a whole, that (a) is included in the normal form of may provide additional or different license terms and conditions
packaging a Major Component, but which is not part of that Major for use, reproduction, or distribution of Your modifications, or
Component, and (b) serves only to enable use of the work with that for any such Derivative Works as a whole, provided Your use,
Major Component, or to implement a Standard Interface for which an reproduction, and distribution of the Work otherwise complies with
implementation is available to the public in source code form. A the conditions stated in this License.
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system 5. Submission of Contributions. Unless You explicitly state otherwise,
(if any) on which the executable work runs, or a compiler used to any Contribution intentionally submitted for inclusion in the Work
produce the work, or an object code interpreter used to run it. by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
The "Corresponding Source" for a work in object code form means all Notwithstanding the above, nothing herein shall supersede or modify
the source code needed to generate, install, and (for an executable the terms of any separate license agreement you may have executed
work) run the object code and to modify the work, including scripts to with Licensor regarding such Contributions.
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free 6. Trademarks. This License does not grant permission to use the trade
programs which are used unmodified in performing those activities but names, trademarks, service marks, or product names of the Licensor,
which are not part of the work. For example, Corresponding Source except as required for reasonable and customary use in describing the
includes interface definition files associated with source files for origin of the Work and reproducing the content of the NOTICE file.
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require, 7. Disclaimer of Warranty. Unless required by applicable law or
such as by intimate data communication or control flow between those agreed to in writing, Licensor provides the Work (and each
subprograms and other parts of the work. Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
The Corresponding Source need not include anything that users implied, including, without limitation, any warranties or conditions
can regenerate automatically from other parts of the Corresponding of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
Source. PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
The Corresponding Source for a work in source code form is that risks associated with Your exercise of permissions under this License.
same work.
8. Limitation of Liability. In no event and under no legal theory,
2. Basic Permissions. whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
All rights granted under this License are granted for the term of negligent acts) or agreed to in writing, shall any Contributor be
copyright on the Program, and are irrevocable provided the stated liable to You for damages, including any direct, indirect, special,
conditions are met. This License explicitly affirms your unlimited incidental, or consequential damages of any character arising as a
permission to run the unmodified Program. The output from running a result of this License or out of the use or inability to use the
covered work is covered by this License only if the output, given its Work (including but not limited to damages for loss of goodwill,
content, constitutes a covered work. This License acknowledges your work stoppage, computer failure or malfunction, or any and all
rights of fair use or other equivalent, as provided by copyright law. other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains 9. Accepting Warranty or Additional Liability. While redistributing
in force. You may convey covered works to others for the sole purpose the Work or Derivative Works thereof, You may choose to offer,
of having them make modifications exclusively for you, or provide you and charge a fee for, acceptance of support, warranty, indemnity,
with facilities for running those works, provided that you comply with or other liability obligations and/or rights consistent with this
the terms of this License in conveying all material for which you do License. However, in accepting such obligations, You may act only
not control copyright. Those thus making or running the covered works on Your own behalf and on Your sole responsibility, not on behalf
for you must do so exclusively on your behalf, under your direction of any other Contributor, and only if You agree to indemnify,
and control, on terms that prohibit them from making any copies of defend, and hold each Contributor harmless for any liability
your copyrighted material outside their relationship with you. incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
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 END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs APPENDIX: How to apply the Apache License to your work.
If you develop a new program, and you want it to be of the greatest To apply the Apache License to your work, attach the following
possible use to the public, the best way to achieve this is to make it boilerplate notice, with the fields enclosed by brackets "[]"
free software which everyone can redistribute and change under these terms. replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
To do so, attach the following notices to the program. It is safest Copyright [yyyy] [name of copyright owner]
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.> Licensed under the Apache License, Version 2.0 (the "License");
Copyright (C) <year> <name of author> you may not use this file except in compliance with the License.
You may obtain a copy of the License at
This program is free software: you can redistribute it and/or modify http://www.apache.org/licenses/LICENSE-2.0
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, Unless required by applicable law or agreed to in writing, software
but WITHOUT ANY WARRANTY; without even the implied warranty of distributed under the License is distributed on an "AS IS" BASIS,
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
GNU General Public License for more details. See the License for the specific language governing permissions and
limitations under the License.
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

@ -1,51 +1,47 @@
add_module(NAME preliminary INTERFACES module.cppm fundumental_types.cppm assertions.cppm build_constants.cppm) add_module(NAME logger INTERFACES logger.cppm TESTS logger.test.cpp)
add_module(NAME logger INTERFACES logger.cppm TESTS logger.test.cpp DEPENDENCIES preliminary) add_module(NAME bitwise INTERFACES operations.cppm)
add_module(NAME tracer INTERFACES tracer.cppm DEPENDENCIES preliminary logger) add_module(NAME env INTERFACES constants.cppm)
add_module(NAME memory INTERFACES null_on_move.cppm reference.cppm scope.cppm)
add_module(NAME bitwise INTERFACES operations.cppm DEPENDENCIES preliminary) add_module(NAME time INTERFACES timer.cppm TESTS timer.test.cpp)
add_module(NAME memory INTERFACES null_on_move.cppm reference.cppm scope.cppm
DEPENDENCIES
preliminary
logger
)
add_module(NAME time INTERFACES timer.cppm TESTS timer.test.cpp DEPENDENCIES preliminary)
add_module( add_module(
NAME NAME
test test
INTERFACES INTERFACES
module.cppm
test.cppm test.cppm
expects.cppm expects.cppm
registry.cppm registry.cppm
SOURCES SOURCES
entrypoint.cpp entrypoint.cpp
DEPENDENCIES DEPENDENCIES
preliminary
logger logger
TESTS TESTS
test.test.cpp test.test.cpp
) )
add_module(
NAME
lt_debug
ROOT_DIR
${CMAKE_CURRENT_SOURCE_DIR}/debug
INTERFACES
instrumentor.cppm
assertions.cppm
DEPENDENCIES
logger
)
add_module( add_module(
NAME NAME
math math
INTERFACES INTERFACES
algebra.cppm algebra.cppm
mat4.cppm
trig.cppm trig.cppm
vec2.cppm vec2.cppm
vec3.cppm vec3.cppm
vec4.cppm vec4.cppm
mat4.cppm
components.cppm components.cppm
DEPENDENCIES
preliminary
TESTS
trig.test.cpp
vec2.test.cpp
vec3.test.cpp
vec4.test.cpp
mat4.test.cpp
) )
add_module( add_module(
@ -55,8 +51,8 @@ add_module(
shader.cppm shader.cppm
metadata.cppm metadata.cppm
DEPENDENCIES DEPENDENCIES
preliminary
logger logger
lt_debug
TESTS TESTS
shader.test.cpp shader.test.cpp
) )
@ -71,15 +67,17 @@ add_module(
ENTRYPOINT ENTRYPOINT
entrypoint.cpp entrypoint.cpp
DEPENDENCIES DEPENDENCIES
preliminary
assets assets
logger logger
lt_debug
TESTS
bakers.test.cpp
) )
# add_executable(asset_baker entrypoint.cpp) target_link_libraries(asset_baker # add_executable(asset_baker entrypoint.cpp) target_link_libraries(asset_baker
# PRIVATE libasset_baker) # PRIVATE libasset_baker)
add_module(NAME camera INTERFACES components.cppm DEPENDENCIES preliminary math) add_module(NAME camera INTERFACES components.cppm DEPENDENCIES math)
add_module( add_module(
NAME NAME
@ -88,9 +86,9 @@ add_module(
application.cppm application.cppm
system.cppm system.cppm
DEPENDENCIES DEPENDENCIES
preliminary
memory memory
PRIVATE_DEPENDENCIES PRIVATE_DEPENDENCIES
lt_debug
) )
add_module( add_module(
@ -102,13 +100,14 @@ add_module(
entity.cppm entity.cppm
DEPENDENCIES DEPENDENCIES
logger logger
lt_debug
memory memory
TESTS TESTS
registry.test.cpp registry.test.cpp
sparse_set.test.cpp sparse_set.test.cpp
) )
add_module(NAME input_codes INTERFACES input_codes.cppm DEPENDENCIES preliminary) add_module(NAME input_codes INTERFACES input_codes.cppm)
if(WIN32) if(WIN32)
add_module( add_module(
@ -120,35 +119,21 @@ if(WIN32)
requests.cppm requests.cppm
events.cppm events.cppm
components.cppm components.cppm
SOURCES
platform_windows.cpp
DEPENDENCIES DEPENDENCIES
preliminary
ecs ecs
app app
math math
memory memory
input_codes input_codes
PRIVATE_DEPENDENCIES PRIVATE_DEPENDENCIES
user32
gdi32
kernel32
dwmapi
Shcore
logger logger
lt_debug
time time
TESTS
system.test.cpp
) )
elseif(UNIX) elseif(UNIX)
add_custom_command(
OUTPUT ${CMAKE_CURRENT_SOURCE_DIR}/surface/wayland-protocols/xdg-shell.h ${CMAKE_CURRENT_SOURCE_DIR}/surface/wayland-protocols/xdg-shell.c
COMMAND wayland-scanner client-header /usr/share/wayland-protocols/stable/xdg-shell/xdg-shell.xml ${CMAKE_CURRENT_SOURCE_DIR}/surface/wayland-protocols/xdg-shell.h
COMMAND wayland-scanner private-code /usr/share/wayland-protocols/stable/xdg-shell/xdg-shell.xml ${CMAKE_CURRENT_SOURCE_DIR}/surface/wayland-protocols/xdg-shell.c
DEPENDS /usr/share/wayland-protocols/stable/xdg-shell/xdg-shell.xml
)
add_custom_target(xdg-shell-gen DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/surface/wayland-protocols/xdg-shell.h ${CMAKE_CURRENT_SOURCE_DIR}/surface/wayland-protocols/xdg-shell.c)
add_module( add_module(
NAME NAME
surface surface
@ -159,24 +144,21 @@ add_module(
events.cppm events.cppm
components.cppm components.cppm
SOURCES SOURCES
wayland-protocols/xdg-shell.c platform_linux.cpp
DEPENDENCIES DEPENDENCIES
preliminary
ecs ecs
app app
math math
memory memory
input_codes input_codes
wayland-client
PRIVATE_DEPENDENCIES PRIVATE_DEPENDENCIES
X11 X11
logger logger
lt_debug
time time
TESTS TESTS
system.test.cpp system.test.cpp
) )
target_include_directories(surface PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/surface/wayland-protocols/)
add_dependencies(surface xdg-shell-gen)
else() else()
message(FATAL "Failed to generate cmake: unsupported platform") message(FATAL "Failed to generate cmake: unsupported platform")
@ -191,7 +173,6 @@ add_module(
components.cppm components.cppm
events.cppm events.cppm
DEPENDENCIES DEPENDENCIES
preliminary
input_codes input_codes
surface surface
math math
@ -222,7 +203,6 @@ add_module(
vk/renderer.cppm vk/renderer.cppm
vk/debugger.cppm vk/debugger.cppm
DEPENDENCIES DEPENDENCIES
preliminary
app app
ecs ecs
memory memory
@ -261,8 +241,21 @@ add_module(
surface surface
renderer renderer
camera camera
# TESTS system.test.cpp
) )
if(ENABLE_SANDBOX) add_executable(exectest ${CMAKE_CURRENT_SOURCE_DIR}/mirror/entrypoint.cpp)
add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/sandbox/)
endif() target_link_libraries(
exectest
PRIVATE mirror
app
time
input
surface
renderer
camera
)
# add_executable_module(mirror entrypoint/mirror.cpp)
# target_link_libraries(mirror PRIVATE libmirror input)

View file

@ -1,17 +1,16 @@
export module app; export module app;
import preliminary;
import app.system; import app.system;
import memory.reference; import memory.reference;
import memory.scope; import memory.scope;
import std;
export namespace lt::app { namespace lt::app {
/** The main application class. /** The main application class.
* Think of this like an aggregate of systems, you register systems through this interface. * Think of this like an aggregate of systems, you register systems through this interface.
* Then they'll tick every "application frame". * Then they'll tick every "application frame".
*/ */
class Application export class Application
{ {
public: public:
Application(const Application &) = delete; Application(const Application &) = delete;
@ -43,8 +42,7 @@ private:
} // namespace lt::app } // namespace lt::app
/** @todo(Light): unimplemented in gcc -- is it even right to use a private fragment? */ module :private;
// module :private;
namespace lt::app { namespace lt::app {
void Application::game_loop() void Application::game_loop()
@ -56,13 +54,11 @@ void Application::game_loop()
const auto &last_tick = system->get_last_tick_result(); const auto &last_tick = system->get_last_tick_result();
const auto now = std::chrono::steady_clock::now(); const auto now = std::chrono::steady_clock::now();
system->tick( system->tick(TickInfo {
TickInfo {
.delta_time = now - last_tick.end_time, .delta_time = now - last_tick.end_time,
.budget = std::chrono::milliseconds { 10 }, .budget = std::chrono::milliseconds { 10 },
.start_time = now, .start_time = now,
} });
);
} }
for (auto &system : m_systems_to_be_registered) for (auto &system : m_systems_to_be_registered)

View file

@ -1,18 +1,17 @@
export module app.system; export module app.system;
import preliminary;
import logger; import logger;
import std;
export namespace lt::app { namespace lt::app {
/** Information required to tick a system. /** Information required to tick a system.
* @note May be used across an entire application-frame (consisting of multiple systems ticking) * @note May be used across an entire application-frame (consisting of multiple systems ticking)
*/ */
struct TickInfo export struct TickInfo
{ {
using Timepoint_T = std::chrono::time_point<std::chrono::steady_clock>; using Timepoint_T = std::chrono::time_point<std::chrono::steady_clock>;
using Duration_T = std::chrono::duration<f64>; using Duration_T = std::chrono::duration<double>;
/** Duration since previous tick's end_time to current tick's start_time. */ /** Duration since previous tick's end_time to current tick's start_time. */
Duration_T delta_time {}; Duration_T delta_time {};
@ -31,11 +30,11 @@ struct TickInfo
}; };
/** Information about how a system's tick performed */ /** Information about how a system's tick performed */
struct TickResult export struct TickResult
{ {
using Timepoint_T = std::chrono::time_point<std::chrono::steady_clock>; using Timepoint_T = std::chrono::time_point<std::chrono::steady_clock>;
using Duration_T = std::chrono::duration<f64>; using Duration_T = std::chrono::duration<double>;
/** The info supplied to the system for ticking. */ /** The info supplied to the system for ticking. */
TickInfo info; TickInfo info;
@ -47,9 +46,9 @@ struct TickResult
Timepoint_T end_time; Timepoint_T end_time;
}; };
struct SystemDiagnosis export struct SystemDiagnosis
{ {
enum class Severity : u8 enum class Severity : std::uint8_t
{ {
verbose, verbose,
info, info,
@ -65,7 +64,7 @@ struct SystemDiagnosis
Severity severity; Severity severity;
}; };
class SystemStats export class SystemStats
{ {
public: public:
void push_diagnosis(SystemDiagnosis &&diagnosis) void push_diagnosis(SystemDiagnosis &&diagnosis)
@ -84,7 +83,7 @@ private:
std::vector<SystemDiagnosis> m_diagnosis; std::vector<SystemDiagnosis> m_diagnosis;
}; };
class ISystem export class ISystem
{ {
public: public:
ISystem() = default; ISystem() = default;

View file

@ -1,9 +1,10 @@
export module bakers; export module bakers;
import preliminary; import debug.assertions;
import assets.metadata; import assets.metadata;
import assets.shader; import assets.shader;
import logger; import logger;
import std;
export void bake_shader( export void bake_shader(
const std::filesystem::path &in_path, const std::filesystem::path &in_path,
@ -25,18 +26,16 @@ export void bake_shader(
// Don't bother linking to shaderc, just invoke the command with a system call. // Don't bother linking to shaderc, just invoke the command with a system call.
// NOLINTNEXTLINE(concurrency-mt-unsafe) // NOLINTNEXTLINE(concurrency-mt-unsafe)
std::system( std::system(std::format(
std::format(
"glslc --target-env=vulkan1.4 -std=450core -fshader-stage={} {} -o {}", "glslc --target-env=vulkan1.4 -std=450core -fshader-stage={} {} -o {}",
type == vertex ? "vert" : "frag", type == vertex ? "vert" : "frag",
glsl_path, glsl_path,
spv_path spv_path
) )
.c_str() .c_str());
);
auto stream = std::ifstream(spv_path, std::ios::binary); auto stream = std::ifstream(spv_path, std::ios::binary);
ensure( lt::debug::ensure(
stream.is_open(), stream.is_open(),
"Failed to open compiled {} shader at: {}", "Failed to open compiled {} shader at: {}",
type == vertex ? "vert" : "frag", type == vertex ? "vert" : "frag",
@ -46,9 +45,10 @@ export void bake_shader(
stream.seekg(0, std::ios::end); stream.seekg(0, std::ios::end);
const auto size = stream.tellg(); const auto size = stream.tellg();
auto bytes = std::vector<byte>(size); auto bytes = std::vector<std::byte>(size);
stream.seekg(0, std::ios::beg); stream.seekg(0, std::ios::beg);
stream.read((char *)bytes.data(), size); // NOLINT stream.read((char *)bytes.data(), size); // NOLINT
lt::log::debug("BYTES: {}", bytes.size());
stream.close(); stream.close();
std::filesystem::remove(spv_path); std::filesystem::remove(spv_path);

View file

View file

@ -1,9 +1,10 @@
import preliminary;
import assets.shader; import assets.shader;
import logger; import logger;
import bakers; import bakers;
import std;
auto main(i32 argc, char *argv[]) -> i32
auto main(int argc, char *argv[]) -> std::int32_t
try try
{ {
if (argc != 2) if (argc != 2)
@ -20,8 +21,7 @@ try
} }
const auto &in_path = directory_iterator.path(); const auto &in_path = directory_iterator.path();
const std::string in_path_str = in_path.generic_string(); const auto out_path = std::format("{}.asset", in_path.c_str());
const auto out_path = std::format("{}.asset", in_path_str);
if (in_path.extension() == ".vert") if (in_path.extension() == ".vert")
{ {

View file

@ -1,20 +1,19 @@
export module assets.metadata; export module assets.metadata;
import std;
import preliminary;
export namespace lt::assets { export namespace lt::assets {
using Type_T = std::array<const char, 16>; using Type_T = std::array<const char, 16>;
using Tag_T = u8; using Tag_T = std::uint8_t;
using Version = u8; using Version = std::uint8_t;
using Blob = std::vector<byte>; using Blob = std::vector<std::byte>;
constexpr auto current_version = Version { 1u }; constexpr auto current_version = Version { 1u };
enum class CompressionType : u8 enum class CompressionType : std::uint8_t
{ {
none, none,
lz4, lz4,
@ -32,13 +31,13 @@ struct BlobMetadata
{ {
Tag_T tag; Tag_T tag;
size_t offset; std::size_t offset;
CompressionType compression_type; CompressionType compression_type;
size_t compressed_size; std::size_t compressed_size;
size_t uncompressed_size; std::size_t uncompressed_size;
}; };
} // namespace lt::assets } // namespace lt::assets

View file

@ -1,8 +1,8 @@
export module assets.shader; export module assets.shader;
import preliminary;
import assets.metadata; import assets.metadata;
import logger; import debug.assertions;
import std;
export namespace lt::assets { export namespace lt::assets {
@ -16,7 +16,7 @@ public:
code, code,
}; };
enum class Type : u8 enum class Type : std::uint8_t
{ {
vertex, vertex,
fragment, fragment,
@ -38,7 +38,7 @@ public:
ShaderAsset(const std::filesystem::path &path); ShaderAsset(const std::filesystem::path &path);
void unpack_to(BlobTag tag, std::span<byte> destination) const; void unpack_to(BlobTag tag, std::span<std::byte> destination) const;
[[nodiscard]] auto unpack(BlobTag tag) const -> Blob; [[nodiscard]] auto unpack(BlobTag tag) const -> Blob;
@ -54,7 +54,7 @@ public:
[[nodiscard]] auto get_blob_metadata(BlobTag tag) const -> const BlobMetadata & [[nodiscard]] auto get_blob_metadata(BlobTag tag) const -> const BlobMetadata &
{ {
ensure( debug::ensure(
tag == BlobTag::code, tag == BlobTag::code,
"Invalid blob tag for shader asset: {}", "Invalid blob tag for shader asset: {}",
std::to_underlying(tag) std::to_underlying(tag)
@ -88,16 +88,16 @@ constexpr auto total_metadata_size = //
+ sizeof(BlobMetadata::compressed_size) // + sizeof(BlobMetadata::compressed_size) //
+ sizeof(BlobMetadata::uncompressed_size); + sizeof(BlobMetadata::uncompressed_size);
ShaderAsset::ShaderAsset(const std::filesystem::path &path): m_stream(path, std::ios::binary) ShaderAsset::ShaderAsset(const std::filesystem::path &path): m_stream(path)
{ {
ensure(m_stream.is_open(), "Failed to open shader asset at: {}", path.string()); debug::ensure(m_stream.is_open(), "Failed to open shader asset at: {}", path.string());
const auto read = [this](auto &field) { const auto read = [this](auto &field) {
m_stream.read(std::bit_cast<char *>(&field), sizeof(field)); m_stream.read(std::bit_cast<char *>(&field), sizeof(field));
}; };
m_stream.seekg(0, std::ifstream::end); m_stream.seekg(0, std::ifstream::end);
const auto file_size = static_cast<size_t>(m_stream.tellg()); const auto file_size = static_cast<std::size_t>(m_stream.tellg());
ensure( debug::ensure(
file_size > total_metadata_size, file_size > total_metadata_size,
"Failed to open shader asset at: {}, file smaller than metadata: {} < {}", "Failed to open shader asset at: {}, file smaller than metadata: {} < {}",
path.string(), path.string(),
@ -109,14 +109,13 @@ ShaderAsset::ShaderAsset(const std::filesystem::path &path): m_stream(path, std:
read(m_asset_metadata.type); read(m_asset_metadata.type);
read(m_asset_metadata.version); read(m_asset_metadata.version);
read(m_metadata.type); read(m_metadata.type);
read(m_code_blob_metadata.tag); read(m_code_blob_metadata.tag);
read(m_code_blob_metadata.offset); read(m_code_blob_metadata.offset);
read(m_code_blob_metadata.compression_type); read(m_code_blob_metadata.compression_type);
read(m_code_blob_metadata.compressed_size); read(m_code_blob_metadata.compressed_size);
read(m_code_blob_metadata.uncompressed_size); read(m_code_blob_metadata.uncompressed_size);
ensure( debug::ensure(
m_asset_metadata.type == asset_type_identifier, m_asset_metadata.type == asset_type_identifier,
"Failed to open shader asset at: {}, incorrect asset type: {} != {}", "Failed to open shader asset at: {}, incorrect asset type: {} != {}",
path.string(), path.string(),
@ -124,7 +123,7 @@ ShaderAsset::ShaderAsset(const std::filesystem::path &path): m_stream(path, std:
asset_type_identifier asset_type_identifier
); );
ensure( debug::ensure(
m_asset_metadata.version == current_version, m_asset_metadata.version == current_version,
"Failed to open shader asset at: {}, version mismatch: {} != {}", "Failed to open shader asset at: {}, version mismatch: {} != {}",
path.string(), path.string(),
@ -132,21 +131,21 @@ ShaderAsset::ShaderAsset(const std::filesystem::path &path): m_stream(path, std:
current_version current_version
); );
ensure( debug::ensure(
std::to_underlying(m_metadata.type) <= std::to_underlying(Type::compute), std::to_underlying(m_metadata.type) <= std::to_underlying(Type::compute),
"Failed to open shader asset at: {}, invalid shader type: {}", "Failed to open shader asset at: {}, invalid shader type: {}",
path.string(), path.string(),
std::to_underlying(m_metadata.type) std::to_underlying(m_metadata.type)
); );
ensure( debug::ensure(
m_code_blob_metadata.tag == std::to_underlying(BlobTag::code), m_code_blob_metadata.tag == std::to_underlying(BlobTag::code),
"Failed to open shader asset at: {}, invalid blob tag: {}", "Failed to open shader asset at: {}, invalid blob tag: {}",
path.string(), path.string(),
m_code_blob_metadata.tag m_code_blob_metadata.tag
); );
ensure( debug::ensure(
m_code_blob_metadata.offset + m_code_blob_metadata.compressed_size <= file_size, m_code_blob_metadata.offset + m_code_blob_metadata.compressed_size <= file_size,
"Failed to open shader asset at: {}, file smaller than blob: {} > {} + {}", "Failed to open shader asset at: {}, file smaller than blob: {} > {} + {}",
path.string(), path.string(),
@ -176,7 +175,7 @@ ShaderAsset::ShaderAsset(const std::filesystem::path &path): m_stream(path, std:
.uncompressed_size = code_blob.size(), .uncompressed_size = code_blob.size(),
}; };
ensure(stream.is_open(), "Failed to pack shader asset to {}", destination.string()); debug::ensure(stream.is_open(), "Failed to pack shader asset to {}", destination.string());
const auto write = [&stream](auto &field) { const auto write = [&stream](auto &field) {
stream.write(std::bit_cast<char *>(&field), sizeof(field)); stream.write(std::bit_cast<char *>(&field), sizeof(field));
}; };
@ -191,30 +190,38 @@ ShaderAsset::ShaderAsset(const std::filesystem::path &path): m_stream(path, std:
stream.write(std::bit_cast<char *>(code_blob.data()), static_cast<long long>(code_blob.size())); stream.write(std::bit_cast<char *>(code_blob.data()), static_cast<long long>(code_blob.size()));
} }
void ShaderAsset::unpack_to(BlobTag tag, std::span<byte> destination) const void ShaderAsset::unpack_to(BlobTag tag, std::span<std::byte> destination) const
{ {
ensure(tag == BlobTag::code, "Invalid blob tag for shader asset: {}", std::to_underlying(tag)); debug::ensure(
tag == BlobTag::code,
"Invalid blob tag for shader asset: {}",
std::to_underlying(tag)
);
ensure( debug::ensure(
destination.size() >= m_code_blob_metadata.uncompressed_size, destination.size() >= m_code_blob_metadata.uncompressed_size,
"Failed to unpack shader blob {} to destination ({}) of size {} since it's smaller " "Failed to unpack shader blob {} to destination ({}) of size {} since it's smaller "
"than the blobl's uncompressed size: {}", "than the blobl's uncompressed size: {}",
std::to_underlying(tag), std::to_underlying(tag),
std::bit_cast<size_t>(destination.data()), std::bit_cast<std::size_t>(destination.data()),
destination.size(), destination.size(),
m_code_blob_metadata.uncompressed_size m_code_blob_metadata.uncompressed_size
); );
m_stream.seekg(static_cast<long long>(m_code_blob_metadata.offset), std::ifstream::beg); m_stream.seekg(static_cast<long long>(m_code_blob_metadata.offset));
m_stream.read( m_stream.read(
std::bit_cast<char *>(destination.data()), std::bit_cast<char *>(destination.data()),
m_code_blob_metadata.uncompressed_size static_cast<long long>(m_code_blob_metadata.uncompressed_size)
); );
} }
[[nodiscard]] auto ShaderAsset::unpack(BlobTag tag) const -> Blob [[nodiscard]] auto ShaderAsset::unpack(BlobTag tag) const -> Blob
{ {
ensure(tag == BlobTag::code, "Invalid blob tag for shader asset: {}", std::to_underlying(tag)); debug::ensure(
tag == BlobTag::code,
"Invalid blob tag for shader asset: {}",
std::to_underlying(tag)
);
auto blob = Blob(m_code_blob_metadata.uncompressed_size); auto blob = Blob(m_code_blob_metadata.uncompressed_size);
unpack_to(tag, blob); unpack_to(tag, blob);

View file

@ -1,65 +1,47 @@
import test;
import assets.metadata; import assets.metadata;
import assets.shader; import assets.shader;
import test.test;
import test.expects;
import std;
using ::lt::assets::AssetMetadata; using ::lt::assets::AssetMetadata;
using ::lt::assets::Blob;
using ::lt::assets::BlobMetadata; using ::lt::assets::BlobMetadata;
using ::lt::assets::ShaderAsset; using ::lt::assets::ShaderAsset;
using ::lt::test::Case;
using ::lt::test::expect_eq;
using ::lt::test::expect_throw;
using ::lt::test::expect_true;
using ::lt::test::Suite;
using ::lt::test::operator""_suite;
const auto test_data_path = std::filesystem::path { "./data/test_assets" }; const auto test_data_path = std::filesystem::path { "./data/test_assets" };
const auto tmp_path = std::filesystem::path { "/tmp/lt_assets_tests/" }; const auto tmp_path = std::filesystem::path { "/tmp/lt_assets_tests/" };
[[nodiscard]] auto generate_blob(size_t size) -> Blob
{
auto blob = Blob {};
for (auto idx : std::views::iota(0u, size))
{
blob.emplace_back(static_cast<byte>(idx));
}
return blob;
}
Suite raii = "shader_raii"_suite = [] { Suite raii = "shader_raii"_suite = [] {
std::filesystem::current_path(test_data_path); std::filesystem::current_path(test_data_path);
std::filesystem::create_directories(tmp_path); std::filesystem::create_directories(tmp_path);
Case { "happy paths" } = [] { Case { "happy path won't throw" } = [] {
auto shader_asset = ShaderAsset { "triangle.frag.asset" };
}; };
Case { "unhappy paths" } = [] { Case { "many won't freeze/throw" } = [] {
// non-existent file
expect_throw([] { ShaderAsset { "path" }; });
// incompatible type
expect_throw([] { ShaderAsset { "dummytext" }; });
// some random stressing
expect_throw([] {
for (auto idx : std::views::iota(0u, 1'000u))
{
auto shader_asset = ShaderAsset { std::to_string(idx) };
}
});
}; };
Case { "many" } = [] { Case { "unhappy path throws" } = [] {
for (auto idx : std::views::iota(0u, 1'000u)) expect_throw([] { ShaderAsset { "random_path" }; });
{
ignore = idx;
auto shader_asset = ShaderAsset { "triangle.frag.asset" };
}
}; };
}; };
// NOLINTNEXTLINE(cppcoreguidelines-interfaces-global-init)
Suite packing = "shader_pack"_suite = [] { Suite packing = "shader_pack"_suite = [] {
Case { "Unpacking packed data returns the same data" } = [] { Case { "" } = [] {
const auto out_path = tmp_path / "shader_packing"; const auto out_path = tmp_path / "shader_packing";
constexpr auto blob_size = size_t { 255u }; auto dummy_blob = lt::assets::Blob {};
for (auto idx : std::views::iota(0, 255))
auto blob = generate_blob(blob_size); {
dummy_blob.emplace_back(static_cast<std::byte>(idx));
}
const auto expected_size = // const auto expected_size = //
sizeof(AssetMetadata::type) // sizeof(AssetMetadata::type) //
@ -70,7 +52,7 @@ Suite packing = "shader_pack"_suite = [] {
+ sizeof(BlobMetadata::compression_type) // + sizeof(BlobMetadata::compression_type) //
+ sizeof(BlobMetadata::compressed_size) // + sizeof(BlobMetadata::compressed_size) //
+ sizeof(BlobMetadata::uncompressed_size) // + sizeof(BlobMetadata::uncompressed_size) //
+ blob.size(); + dummy_blob.size();
ShaderAsset::pack( ShaderAsset::pack(
out_path, out_path,
@ -81,7 +63,7 @@ Suite packing = "shader_pack"_suite = [] {
ShaderAsset::Metadata { ShaderAsset::Metadata {
.type = ShaderAsset::Type::vertex, .type = ShaderAsset::Type::vertex,
}, },
std::move(blob) std::move(dummy_blob)
); );
auto stream = std::ifstream { auto stream = std::ifstream {
@ -90,8 +72,8 @@ Suite packing = "shader_pack"_suite = [] {
}; };
expect_true(stream.is_open()); expect_true(stream.is_open());
stream.seekg(0u, std::ios::end); stream.seekg(0, std::ios::end);
const auto file_size = static_cast<size_t>(stream.tellg()); const auto file_size = static_cast<std::size_t>(stream.tellg());
expect_eq(file_size, expected_size); expect_eq(file_size, expected_size);
stream.close(); stream.close();
@ -104,12 +86,12 @@ Suite packing = "shader_pack"_suite = [] {
const auto &metadata = shader_asset.get_metadata(); const auto &metadata = shader_asset.get_metadata();
expect_eq(metadata.type, ShaderAsset::Type::vertex); expect_eq(metadata.type, ShaderAsset::Type::vertex);
auto unpakced_blob = shader_asset.unpack(ShaderAsset::BlobTag::code); auto blob = shader_asset.unpack(ShaderAsset::BlobTag::code);
expect_eq(unpakced_blob.size(), blob_size); expect_eq(blob.size(), 255);
for (auto idx : std::views::iota(0u, blob_size)) for (auto idx : std::views::iota(0, 255))
{ {
expect_eq(unpakced_blob[idx], static_cast<byte>(idx)); expect_eq(blob[idx], static_cast<std::byte>(idx));
} }
}; };
}; };

View file

@ -1,12 +1,12 @@
export module bitwise; export module bitwise;
import preliminary; import std;
namespace lt::bitwise { namespace lt::bitwise {
/* bit-wise */ /* bit-wise */
export constexpr auto bit(u32 x) -> u32 export constexpr auto bit(std::uint32_t x) -> std::uint32_t
{ {
return u32 { 1u } << x; return 1u << x;
} }
} // namespace lt::bitwise } // namespace lt::bitwise

View file

@ -1,19 +1,17 @@
export module camera.components; export module camera.components;
import preliminary;
import math.vec4; import math.vec4;
export namespace lt::camera::components { namespace lt::camera::components {
struct PerspectiveCamera export struct PerspectiveCamera
{ {
f32 vertical_fov {}; float vertical_fov {};
f32 near_plane {}; float near_plane {};
f32 far_plane {}; float far_plane {};
f32 aspect_ratio {}; float aspect_ratio {};
math::vec4 background_color; math::vec4 background_color;

View file

@ -0,0 +1,47 @@
export module debug.assertions;
import std;
namespace lt::debug {
///////////////////////////////////////
// ----------* INTERFACE *--------- //
/////////////////////////////////////
export template<typename Expression_T, typename... Args_T>
struct ensure
{
ensure(
const Expression_T &expression,
std::format_string<Args_T...> fmt,
Args_T &&...args,
const std::source_location &location = std::source_location::current()
);
};
export template<typename Expression_T, typename... Args_T>
ensure(Expression_T, std::format_string<Args_T...>, Args_T &&...)
-> ensure<Expression_T, Args_T...>;
///////////////////////////////////////
// * IMPLEMENTATION -- TEMPLATES * //
/////////////////////////////////////
template<typename Expression_T, typename... Args_T>
ensure<Expression_T, Args_T...>::ensure(
const Expression_T &expression,
std::format_string<Args_T...> fmt,
Args_T &&...args,
const std::source_location &location
)
{
if (!static_cast<bool>(expression))
{
throw std::runtime_error { std::format(
"exception: {}\nlocation: {}:{}",
std::format(fmt, std::forward<Args_T>(args)...),
location.file_name(),
location.line()
) };
}
}
} // namespace lt::debug

View file

@ -1,25 +1,23 @@
// @todo(Light): Implement...
export module debug.instrumentor; export module debug.instrumentor;
import preliminary; import std;
import logger; import logger;
namespace lt::tracer { namespace lt::debug {
struct ScopeTraceResult struct ScopeProfileResult
{ {
std::string name; std::string name;
u64 start, duration; long long start, duration;
u32 threadID; std::uint32_t threadID;
}; };
class Tracer class Instrumentor
{ {
public: public:
static auto instance() -> Tracer & static auto instance() -> Instrumentor &
{ {
static auto instance = Tracer {}; static auto instance = Instrumentor {};
return instance; return instance;
} }
@ -32,7 +30,7 @@ public:
instance().end_session_impl(); instance().end_session_impl();
} }
static void submit_scope_profile(const ScopeTraceResult &profileResult) static void submit_scope_profile(const ScopeProfileResult &profileResult)
{ {
instance().submit_scope_profile_impl(profileResult); instance().submit_scope_profile_impl(profileResult);
} }
@ -42,47 +40,46 @@ private:
unsigned int m_current_session_count { 0u }; unsigned int m_current_session_count { 0u };
Tracer() = default; Instrumentor() = default;
void begin_session_impl(const std::string &outputPath); void begin_session_impl(const std::string &outputPath);
void end_session_impl(); void end_session_impl();
void submit_scope_profile_impl(const ScopeTraceResult &profileResult); void submit_scope_profile_impl(const ScopeProfileResult &profileResult);
}; };
class TracerTimer class InstrumentorTimer
{ {
public: public:
TracerTimer(const std::string &scopeName); InstrumentorTimer(const std::string &scopeName);
~TracerTimer(); ~InstrumentorTimer();
private: private:
ScopeTraceResult m_result; ScopeProfileResult m_result;
std::chrono::time_point<std::chrono::steady_clock> m_start; std::chrono::time_point<std::chrono::steady_clock> m_start;
}; };
} // namespace lt::tracer } // namespace lt::debug
/* scope */ /* scope */
#define lt_trace_scope(name) lt_profile_scope_no_redifinition(name, __LINE__) #define lt_profile_scope(name) lt_profile_scope_no_redifinition(name, __LINE__)
#define lt_trace_scope_no_redifinition(name, line) lt_profile_scope_no_redifinition2(name, line) #define lt_profile_scope_no_redifinition(name, line) lt_profile_scope_no_redifinition2(name, line)
#define lt_trace_scope_no_redifinition2(name, line) InstrumentorTimer timer##line(name) #define lt_profile_scope_no_redifinition2(name, line) InstrumentorTimer timer##line(name)
/* function */ /* function */
#define lt_trace_function lt_profile_scope(__FUNCSIG__) #define LT_PROFILE_FUNCTION lt_profile_scope(__FUNCSIG__)
/* session */ /* session */
#define lt_trace_begin_session(outputPath) ::lt::Instrumentor::begin_session(outputPath) #define lt_profile_begin_session(outputPath) ::lt::Instrumentor::begin_session(outputPath)
#define lt_trace_end_session() ::lt::Instrumentor::end_session() #define lt_profile_end_session() ::lt::Instrumentor::end_session()
/** @todo(Light): unimplemented in gcc -- is it even right to use a private fragment? */ module :private;
// module :private; namespace lt::debug {
namespace lt::tracer {
void Tracer::begin_session_impl(const std::string &outputPath) void Instrumentor::begin_session_impl(const std::string &outputPath)
{ {
std::filesystem::create_directory(outputPath.substr(0, outputPath.find_last_of('/') + 1)); std::filesystem::create_directory(outputPath.substr(0, outputPath.find_last_of('/') + 1));
@ -90,7 +87,7 @@ void Tracer::begin_session_impl(const std::string &outputPath)
m_output_file_stream << "{\"traceEvents\":["; m_output_file_stream << "{\"traceEvents\":[";
} }
void Tracer::end_session_impl() void Instrumentor::end_session_impl()
{ {
if (m_current_session_count == 0u) if (m_current_session_count == 0u)
{ {
@ -104,7 +101,7 @@ void Tracer::end_session_impl()
m_output_file_stream.close(); m_output_file_stream.close();
} }
void Tracer::submit_scope_profile_impl(const ScopeTraceResult &profileResult) void Instrumentor::submit_scope_profile_impl(const ScopeProfileResult &profileResult)
{ {
if (m_current_session_count++ == 0u) if (m_current_session_count++ == 0u)
{ {
@ -125,13 +122,13 @@ void Tracer::submit_scope_profile_impl(const ScopeTraceResult &profileResult)
m_output_file_stream << "}"; m_output_file_stream << "}";
} }
TracerTimer::TracerTimer(const std::string &scopeName) InstrumentorTimer::InstrumentorTimer(const std::string &scopeName)
: m_result({ .name = scopeName, .start = 0, .duration = 0, .threadID = 0 }) : m_result({ .name = scopeName, .start = 0, .duration = 0, .threadID = 0 })
, m_start(std::chrono::steady_clock::now()) , m_start(std::chrono::steady_clock::now())
{ {
} }
TracerTimer::~TracerTimer() InstrumentorTimer::~InstrumentorTimer()
{ {
auto end = std::chrono::steady_clock::now(); auto end = std::chrono::steady_clock::now();
@ -144,6 +141,6 @@ TracerTimer::~TracerTimer()
.count() .count()
- m_result.start; - m_result.start;
Tracer::submit_scope_profile(m_result); Instrumentor::submit_scope_profile(m_result);
} }
} // namespace lt::tracer } // namespace lt::debug

View file

@ -1,20 +1,20 @@
export module ecs.entity; export module ecs.entity;
import debug.assertions;
import preliminary;
import memory.reference; import memory.reference;
import ecs.registry; import ecs.registry;
import std;
export namespace lt::ecs { namespace lt::ecs {
/** High-level entity convenience wrapper */ /** High-level entity convenience wrapper */
class Entity export class Entity
{ {
public: public:
Entity(memory::Ref<Registry> registry, EntityId identifier) Entity(memory::Ref<Registry> registry, EntityId identifier)
: m_registry(std::move(registry)) : m_registry(std::move(registry))
, m_identifier(identifier) , m_identifier(identifier)
{ {
ensure(m_registry, "Failed to create Entity ({}): null registry", m_identifier); debug::ensure(m_registry, "Failed to create Entity ({}): null registry", m_identifier);
} }
template<typename Component_T> template<typename Component_T>
@ -51,4 +51,5 @@ private:
EntityId m_identifier; EntityId m_identifier;
}; };
} // namespace lt::ecs } // namespace lt::ecs

View file

@ -1,14 +1,14 @@
export module ecs.registry; export module ecs.registry;
import debug.assertions;
import preliminary;
import ecs.sparse_set; import ecs.sparse_set;
import memory.scope; import memory.scope;
import std;
export namespace lt::ecs { namespace lt::ecs {
using EntityId = u32; export using EntityId = std::uint32_t;
constexpr auto null_entity = std::numeric_limits<EntityId>::max(); export constexpr auto null_entity = std::numeric_limits<EntityId>::max();
/** A registry of components, the heart of an ECS architecture. /** A registry of components, the heart of an ECS architecture.
* *
@ -23,7 +23,7 @@ constexpr auto null_entity = std::numeric_limits<EntityId>::max();
* @ref https://github.com/skypjack/entt * @ref https://github.com/skypjack/entt
* @ref https://github.com/SanderMertens/flecs * @ref https://github.com/SanderMertens/flecs
*/ */
class Registry export class Registry
{ {
public: public:
using UnderlyingSparseSet_T = TypeErasedSparseSet<EntityId>; using UnderlyingSparseSet_T = TypeErasedSparseSet<EntityId>;
@ -190,25 +190,25 @@ public:
} }
}; };
[[nodiscard]] auto get_entity_count() const -> size_t [[nodiscard]] auto get_entity_count() const -> std::size_t
{ {
return static_cast<size_t>(m_entity_count); return static_cast<std::size_t>(m_entity_count);
} }
private: private:
using TypeId = size_t; using TypeId = std::size_t;
static consteval auto hash_cstr(const char *str) -> TypeId static consteval auto hash_cstr(const char *str) -> TypeId
{ {
constexpr auto fnv_offset_basis = size_t { 14695981039346656037ull }; constexpr auto fnv_offset_basis = std::size_t { 14695981039346656037ull };
constexpr auto fnv_prime = size_t { 1099511628211ull }; constexpr auto fnv_prime = std::size_t { 1099511628211ull };
auto hash = fnv_offset_basis; auto hash = fnv_offset_basis;
for (const auto &ch : std::string_view { str }) for (const auto &ch : std::string_view { str })
{ {
hash *= fnv_prime; hash *= fnv_prime;
hash ^= static_cast<u8>(ch); hash ^= static_cast<std::uint8_t>(ch);
} }
return hash; return hash;
@ -242,7 +242,7 @@ private:
auto *base_set = m_sparsed_sets[type_id].get(); auto *base_set = m_sparsed_sets[type_id].get();
auto *derived_set = dynamic_cast<SparseSet<T, EntityId> *>(base_set); auto *derived_set = dynamic_cast<SparseSet<T, EntityId> *>(base_set);
ensure(derived_set, "Failed to downcast to derived set"); debug::ensure(derived_set, "Failed to downcast to derived set");
return *derived_set; return *derived_set;
} }

View file

@ -1,12 +1,21 @@
import test;
import ecs.registry; import ecs.registry;
import test.test;
import test.expects;
import std;
using ::lt::ecs::EntityId; using ::lt::ecs::EntityId;
using ::lt::ecs::Registry; using ::lt::ecs::Registry;
using ::lt::test::Case;
using ::lt::test::expect_eq;
using ::lt::test::expect_false;
using ::lt::test::expect_true;
using ::lt::test::expect_unreachable;
using ::lt::test::Suite;
using ::lt::test::operator""_suite;
struct Component struct Component
{ {
i32 m_int {}; int m_int {};
std::string m_string; std::string m_string;
[[nodiscard]] friend auto operator==(const Component &lhs, const Component &rhs) -> bool [[nodiscard]] friend auto operator==(const Component &lhs, const Component &rhs) -> bool
@ -30,7 +39,7 @@ struct std::formatter<Component>
struct Component_B struct Component_B
{ {
f32 m_float {}; float m_float {};
[[nodiscard]] friend auto operator==(const Component_B lhs, const Component_B &rhs) -> bool [[nodiscard]] friend auto operator==(const Component_B lhs, const Component_B &rhs) -> bool
{ {
@ -52,21 +61,20 @@ struct std::formatter<Component_B>
}; };
Suite raii = "raii"_suite = [] { Suite raii = "raii"_suite = [] {
Case { "happy paths" } = [] { Case { "happy path won't throw" } = [] {
ignore = Registry {}; std::ignore = Registry {};
}; };
Case { "unhappy paths" } = [] { Case { "many won't freeze/throw" } = [] {
};
Case { "many" } = [] {
for (auto idx : std::views::iota(0, 100'000)) for (auto idx : std::views::iota(0, 100'000))
{ {
ignore = idx; std::ignore = Registry {};
ignore = Registry {};
} }
}; };
Case { "unhappy path throws" } = [] {
};
Case { "post construct has correct state" } = [] { Case { "post construct has correct state" } = [] {
auto registry = Registry {}; auto registry = Registry {};
expect_eq(registry.get_entity_count(), 0); expect_eq(registry.get_entity_count(), 0);
@ -150,7 +158,6 @@ Suite callbacks = "callbacks"_suite = [] {
Case { "on_construct/on_destruct won't get called on unrelated component" } = [] { Case { "on_construct/on_destruct won't get called on unrelated component" } = [] {
auto registry = Registry {}; auto registry = Registry {};
registry.connect_on_construct<Component>([&](Registry &, EntityId) { registry.connect_on_construct<Component>([&](Registry &, EntityId) {
expect_unreachable(); expect_unreachable();
}); });
@ -160,7 +167,6 @@ Suite callbacks = "callbacks"_suite = [] {
for (auto idx : std::views::iota(0, 100'000)) for (auto idx : std::views::iota(0, 100'000))
{ {
ignore = idx;
registry.add<Component_B>(registry.create_entity(), {}); registry.add<Component_B>(registry.create_entity(), {});
} }
}; };
@ -182,8 +188,6 @@ Suite callbacks = "callbacks"_suite = [] {
expect_true(on_destruct_called.empty()); expect_true(on_destruct_called.empty());
for (auto idx : std::views::iota(0, 100'000)) for (auto idx : std::views::iota(0, 100'000))
{ {
ignore = idx;
auto entity = all_entities.emplace_back(registry.create_entity()); auto entity = all_entities.emplace_back(registry.create_entity());
registry.add<Component>(entity, {}); registry.add<Component>(entity, {});
} }
@ -218,7 +222,7 @@ Suite each = "each"_suite = [] {
component_map_a[entity] = component; component_map_a[entity] = component;
} }
auto component_map_b = std::unordered_map<EntityId, Component_B> {}; auto component_map_b = std::unordered_map<lt::ecs::EntityId, Component_B> {};
for (auto idx : std::views::iota(0, 10'000)) for (auto idx : std::views::iota(0, 10'000))
{ {
auto entity = EntityId {}; auto entity = EntityId {};
@ -233,7 +237,7 @@ Suite each = "each"_suite = [] {
} }
auto &component = registry.add<Component_B>( auto &component = registry.add<Component_B>(
entity, entity,
{ .m_float = static_cast<f32>(idx) / 2.0f } { .m_float = static_cast<float>(idx) / 2.0f }
); );
component_map_b[entity] = component; component_map_b[entity] = component;
@ -304,7 +308,7 @@ Suite views = "views"_suite = [] {
} }
auto &component = registry.add<Component_B>( auto &component = registry.add<Component_B>(
entity, entity,
{ .m_float = static_cast<f32>(idx) / 2.0f } { .m_float = static_cast<float>(idx) / 2.0f }
); );
component_map_b[entity] = component; component_map_b[entity] = component;

View file

@ -1,13 +1,13 @@
export module ecs.sparse_set; export module ecs.sparse_set;
import debug.assertions;
import std;
import preliminary; namespace lt::ecs {
export namespace lt::ecs {
/** /**
* @ref https://programmingpraxis.com/2012/03/09/sparse-sets/ * @ref https://programmingpraxis.com/2012/03/09/sparse-sets/
*/ */
template<typename Identifier_T = u32> export template<typename Identifier_T = std::uint32_t>
class TypeErasedSparseSet class TypeErasedSparseSet
{ {
public: public:
@ -26,19 +26,19 @@ public:
virtual void remove(Identifier_T identifier) = 0; virtual void remove(Identifier_T identifier) = 0;
}; };
template<typename Value_T, typename Identifier_T = u32> export template<typename Value_T, typename Identifier_T = std::uint32_t>
class SparseSet: public TypeErasedSparseSet<Identifier_T> class SparseSet: public TypeErasedSparseSet<Identifier_T>
{ {
public: public:
using Dense_T = std::pair<Identifier_T, Value_T>; using Dense_T = std::pair<Identifier_T, Value_T>;
static constexpr auto max_capacity = size_t { 1'000'000 }; static constexpr auto max_capacity = std::size_t { 1'000'000 };
static constexpr auto null_identifier = std::numeric_limits<Identifier_T>().max(); static constexpr auto null_identifier = std::numeric_limits<Identifier_T>().max();
explicit SparseSet(size_t initial_capacity = 1) explicit SparseSet(std::size_t initial_capacity = 1)
{ {
ensure( debug::ensure(
initial_capacity <= max_capacity, initial_capacity <= max_capacity,
"Failed to create SparseSet: capacity too large ({} > {})", "Failed to create SparseSet: capacity too large ({} > {})",
initial_capacity, initial_capacity,
@ -51,18 +51,24 @@ public:
auto insert(Identifier_T identifier, Value_T value) -> Dense_T & auto insert(Identifier_T identifier, Value_T value) -> Dense_T &
{ {
ensure(identifier < max_capacity, "SparseSet::insert: identifier < max_capacity");
if (m_sparse.size() < identifier + 1) if (m_sparse.size() < identifier + 1)
{ {
auto new_capacity = std::max(static_cast<size_t>(identifier + 1), m_sparse.size() * 2); auto new_capacity = std::max(
static_cast<std::size_t>(identifier + 1),
m_sparse.size() * 2
);
new_capacity = std::min(new_capacity, max_capacity); new_capacity = std::min(new_capacity, max_capacity);
// log::debug("Increasing sparse vector size:", m_dead_count);
// log::debug("\tdead_count: {}", m_dead_count);
// log::debug("\talive_count: {}", m_alive_count);
// log::debug("\tsparse.size: {} -> {}", m_sparse.size(), new_capacity);
m_sparse.resize(new_capacity, null_identifier); m_sparse.resize(new_capacity, null_identifier);
} }
++m_alive_count; ++m_alive_count;
m_sparse[identifier] = static_cast<Identifier_T>(m_dense.size()); m_sparse[identifier] = m_dense.size();
return m_dense.emplace_back(identifier, std::move(value)); return m_dense.emplace_back(identifier, std::move(value));
} }
@ -72,27 +78,7 @@ public:
*/ */
void remove(Identifier_T identifier) override void remove(Identifier_T identifier) override
{ {
ensure(
identifier < m_sparse.size(),
"Failed to ensure: identifier < m_sparse.size() [{} < {}]",
identifier,
m_sparse.size()
);
auto &idx = m_sparse[identifier]; auto &idx = m_sparse[identifier];
ensure(
idx != null_identifier,
"Failed to ensure: idx != null_identifier [{} != {}]",
idx,
null_identifier
);
ensure(
idx < m_dense.size(),
"Failed to ensure: idx < m_dense.size() [{} < {}]",
idx,
m_dense.size()
);
auto &[entity, component] = m_dense[idx]; auto &[entity, component] = m_dense[idx];
auto &[last_entity, last_component] = m_dense.back(); auto &[last_entity, last_component] = m_dense.back();
@ -163,12 +149,12 @@ public:
return std::forward<Self_T>(self).m_dense[std::forward<Self_T>(self).m_sparse[identifier]]; return std::forward<Self_T>(self).m_dense[std::forward<Self_T>(self).m_sparse[identifier]];
} }
[[nodiscard]] auto get_size() const noexcept -> size_t [[nodiscard]] auto get_size() const noexcept -> std::size_t
{ {
return m_alive_count; return m_alive_count;
} }
[[nodiscard]] auto get_capacity() const noexcept -> size_t [[nodiscard]] auto get_capacity() const noexcept -> std::size_t
{ {
return m_sparse.capacity(); return m_sparse.capacity();
} }
@ -183,9 +169,9 @@ private:
std::vector<Identifier_T> m_sparse; std::vector<Identifier_T> m_sparse;
size_t m_alive_count {}; std::size_t m_alive_count {};
size_t m_dead_count {}; std::size_t m_dead_count {};
}; };
} // namespace lt::ecs } // namespace lt::ecs

View file

@ -1,26 +1,28 @@
import test;
import ecs.sparse_set; import ecs.sparse_set;
import test.test;
import test.expects;
import std;
using Value_T = i32; using ::lt::test::Case;
using Set = lt::ecs::SparseSet<Value_T>; using ::lt::test::expect_eq;
using ::lt::test::expect_false;
using ::lt::test::expect_ne;
using ::lt::test::expect_throw;
using ::lt::test::expect_true;
using ::lt::test::Suite;
using ::lt::test::operator""_suite;
using Set = lt::ecs::SparseSet<int>;
constexpr auto capacity = 100; constexpr auto capacity = 100;
Suite raii = "raii"_suite = [] { Suite raii = "raii"_suite = [] {
Case { "happy paths" } = [] { Case { "happy path won't throw" } = [] {
ignore = Set {}; std::ignore = Set {};
ignore = Set { Set::max_capacity }; std::ignore = Set { Set::max_capacity };
}; };
Case { "unhappy paths" } = [] { Case { "unhappy path throws" } = [] {
expect_throw([] { ignore = Set { Set::max_capacity + 1 }; }); expect_throw([] { std::ignore = Set { Set::max_capacity + 1 }; });
};
Case { "many" } = [] {
for (auto idx : std::views::iota(0, 1'000))
{
ignore = Set { static_cast<size_t>(idx) };
}
}; };
Case { "post construct has correct state" } = [&] { Case { "post construct has correct state" } = [&] {
@ -31,29 +33,7 @@ Suite raii = "raii"_suite = [] {
}; };
Suite element_raii = "element_raii"_suite = [] { Suite element_raii = "element_raii"_suite = [] {
Case { "happy paths" } = [] { Case { "many inserts/removes won't freeze/throw" } = [] {
auto set = Set { capacity };
set.insert(0, {});
set.remove(0);
};
Case { "unhappy paths" } = [] {
expect_throw([] {
auto set = Set { capacity };
set.insert(Set::max_capacity + 1, {});
});
expect_throw([] {
auto set = Set { capacity };
set.insert(0, {});
set.insert(1, {});
set.insert(2, {});
set.remove(3);
});
};
Case { "many" } = [] {
auto set = Set {}; auto set = Set {};
for (auto idx : std::views::iota(0, 10'000)) for (auto idx : std::views::iota(0, 10'000))
{ {
@ -97,7 +77,7 @@ Suite element_raii = "element_raii"_suite = [] {
expect_eq(set.get_size(), 10'000 - (idx + 1)); expect_eq(set.get_size(), 10'000 - (idx + 1));
expect_false(set.contains(idx)); expect_false(set.contains(idx));
expect_throw([&] { ignore = set.at(idx); }); expect_throw([&] { std::ignore = set.at(idx); });
} }
}; };
@ -117,7 +97,7 @@ Suite element_raii = "element_raii"_suite = [] {
for (auto &[identifier, value] : set) for (auto &[identifier, value] : set)
{ {
expect_eq(static_cast<Value_T>(identifier), value); expect_eq(identifier, value);
expect_ne(value, 0); expect_ne(value, 0);
expect_ne(value, 32); expect_ne(value, 32);
expect_ne(value, 69); expect_ne(value, 69);
@ -149,7 +129,7 @@ Suite getters = "getters"_suite = [] {
expect_eq(set.get_capacity(), 10'000); expect_eq(set.get_capacity(), 10'000);
set.insert(static_cast<Value_T>(set.get_size()), {}); set.insert(set.get_size(), {});
expect_ne(set.get_capacity(), 10'000); expect_ne(set.get_capacity(), 10'000);
}; };
@ -160,12 +140,12 @@ Suite getters = "getters"_suite = [] {
{ {
expect_throw([&] { expect_throw([&] {
set.insert(idx, {}); set.insert(idx, {});
ignore = set.at(50); std::ignore = set.at(50);
}); });
} }
set.insert(50, {}); set.insert(50, {});
ignore = set.at(50); // should not throw std::ignore = set.at(50); // should not throw
}; };
}; };
@ -179,10 +159,5 @@ Suite clear = "clear"_suite = [] {
set.clear(); set.clear();
expect_eq(set.get_size(), 0); expect_eq(set.get_size(), 0);
for (auto idx : std::views::iota(0, 10'000))
{
expect_throw([&] { ignore = set.at(idx); });
}
}; };
}; };

View file

@ -1,11 +1,10 @@
export module preliminary.build_constants; export module env;
import preliminary.fundumental_types;
import std; import std;
export namespace build_constants { namespace lt {
enum class Platform : u8 enum class Platform : std::uint8_t
{ {
/** The GNU/Linux platform. /** The GNU/Linux platform.
* Tested on the following distros: arch-x86_64 * Tested on the following distros: arch-x86_64
@ -27,7 +26,7 @@ enum class Platform : u8
}; };
/** The compiler that was used for compiling the project. */ /** The compiler that was used for compiling the project. */
enum class Compiler : u8 enum class Compiler : std::uint8_t
{ {
clang, clang,
gcc, gcc,
@ -35,51 +34,37 @@ enum class Compiler : u8
apple_clang, apple_clang,
}; };
enum class BuildType namespace constants {
{
debug,
release,
distribution
};
#if defined(LIGHT_PLATFORM_WINDOWS) #if defined(LIGHT_PLATFORM_WINDOWS)
#define lt_win(x) #define lt_win(x)
constexpr auto platform = Platform::windows; constexpr auto platform = Platform::windows;
constexpr auto platform_name = "windows"; constexpr auto platform_name = "windows";
constexpr auto platform_identifier = platform_name; // TODO(Light)
#undef LIGHT_PLATFORM_WINDOWS #undef LIGHT_PLATFORM_WINDOWS
#elif defined(LIGHT_PLATFORM_LINUX) #elif defined(LIGHT_PLATFORM_LINUX)
constexpr auto platform = Platform::gnu_linux; constexpr auto platform = Platform::gnu_linux;
constexpr auto platform_name = "gnu_linux"; constexpr auto platform_name = "gnu_linux";
constexpr auto platform_identifier = platform_name; // TODO(Light)
#elif defined(LIGHT_PLATFORM_MAC) #elif defined(LIGHT_PLATFORM_MAC)
#define lt_mac(x) x #define lt_mac(x) x
constexpr auto platform = Platform::mac; constexpr auto platform = Platform::mac;
constexpr auto platform_name = "mac"; constexpr auto platform_name = "mac";
constexpr auto platform_identifier = platform_name; // TODO(Light)
#else #else
#error "Unsupported platform: Unknown" #error "Unsupported platform: Unknown"
#endif #endif
/** @TODO(Light): Handle other compilers... */
#ifdef __clang__ #ifdef __clang__
constexpr auto compiler = Compiler::clang; constexpr auto compiler = Compiler::clang;
constexpr auto compiler_name = "clang"; constexpr auto compiler_name = "clang";
/** @TODO(Light): insert the full identifier, including version information and such */ /** @todo(Light): insert the full identifier, including version information and such */
constexpr auto compiler_identifier = "clang"; constexpr auto full_compiler_identifier = "clang";
#endif #endif
// @TODO(Light): inject build info through CMake using LIGHT_... constant macros } // namespace constants
#if defined(_DEBUG)
constexpr auto build_type = BuildType::debug;
#else
constexpr auto build_type = BuildType::release;
#endif
} // namespace build_constants } // namespace lt

View file

@ -1,18 +1,17 @@
export module input.system:components; export module input.system:components;
import preliminary;
import input.codes; import input.codes;
import std;
export namespace lt::input { namespace lt::input {
struct Trigger export struct Trigger
{ {
Key mapped_keycode; Key mapped_keycode;
}; };
struct InputAction export struct InputAction
{ {
enum class State : u8 enum class State : std::uint8_t
{ {
inactive, inactive,
active, active,
@ -27,18 +26,18 @@ struct InputAction
Trigger trigger; Trigger trigger;
}; };
class InputComponent export class InputComponent
{ {
public: public:
InputComponent() = default; InputComponent() = default;
auto add_action(InputAction action) -> size_t auto add_action(InputAction action) -> std::size_t
{ {
m_actions.emplace_back(std::move(action)); m_actions.emplace_back(std::move(action));
return m_actions.size() - 1; return m_actions.size() - 1;
} }
auto get_action(size_t idx) -> const InputAction & auto get_action(std::size_t idx) -> const InputAction &
{ {
return m_actions[idx]; return m_actions[idx];
} }

View file

@ -10,7 +10,7 @@ namespace lt::input {
export class AnalogEvent export class AnalogEvent
{ {
public: public:
AnalogEvent(Key key, math::vec2_u32 pointer_position) AnalogEvent(Key key, math::uvec2 pointer_position)
: m_key(key) : m_key(key)
, m_pointer_position(pointer_position) , m_pointer_position(pointer_position)
{ {
@ -21,7 +21,7 @@ public:
return m_key; return m_key;
}; };
[[nodiscard]] auto get_pointer_position() const -> math::vec2_u32 [[nodiscard]] auto get_pointer_position() const -> math::uvec2
{ {
return m_pointer_position; return m_pointer_position;
} }
@ -35,7 +35,7 @@ public:
private: private:
Key m_key; Key m_key;
math::vec2_u32 m_pointer_position; math::uvec2 m_pointer_position;
}; };
} // namespace lt::input } // namespace lt::input

View file

@ -2,6 +2,7 @@ export module input.system;
export import :components; export import :components;
import logger; import logger;
import app.system; import app.system;
import debug.assertions;
import ecs.registry; import ecs.registry;
import memory.reference; import memory.reference;
import surface.system; import surface.system;
@ -36,12 +37,18 @@ private:
void on_key_release(const lt::surface::KeyReleasedEvent &event); void on_key_release(const lt::surface::KeyReleasedEvent &event);
void on_pointer(const lt::surface::PointerEvent &event); void on_pointer_move(const lt::surface::MouseMovedEvent &event);
void on_button_press(const lt::surface::ButtonPressedEvent &event);
void on_button_release(const lt::surface::ButtonReleasedEvent &event);
memory::Ref<ecs::Registry> m_registry; memory::Ref<ecs::Registry> m_registry;
std::array<bool, 512> m_keys {}; std::array<bool, 512> m_keys {};
std::array<bool, 512> m_buttons {};
math::vec2 m_pointer_position; math::vec2 m_pointer_position;
app::TickResult m_last_tick_result {}; app::TickResult m_last_tick_result {};
@ -51,8 +58,7 @@ private:
} // namespace lt::input } // namespace lt::input
/** @todo(Light): unimplemented in gcc -- is it even right to use a private fragment? */ module :private;
// module :private;
namespace lt::input { namespace lt::input {
template<class... Ts> template<class... Ts>
@ -63,7 +69,7 @@ struct overloads: Ts...
System::System(memory::Ref<ecs::Registry> registry): m_registry(std::move(registry)) System::System(memory::Ref<ecs::Registry> registry): m_registry(std::move(registry))
{ {
ensure(m_registry, "Failed to initialize input system: null registry"); debug::ensure(m_registry, "Failed to initialize input system: null registry");
} }
void System::tick(app::TickInfo tick) void System::tick(app::TickInfo tick)
@ -126,7 +132,9 @@ void System::handle_event(const surface::SurfaceComponent::Event &event)
[this](const surface::LostFocusEvent &) { on_surface_lost_focus(); }, [this](const surface::LostFocusEvent &) { on_surface_lost_focus(); },
[this](const surface::KeyPressedEvent &event) { on_key_press(event); }, [this](const surface::KeyPressedEvent &event) { on_key_press(event); },
[this](const surface::KeyReleasedEvent &event) { on_key_release(event); }, [this](const surface::KeyReleasedEvent &event) { on_key_release(event); },
[this](const surface::PointerEvent &event) { on_pointer(event); }, [this](const surface::MouseMovedEvent &event) { on_pointer_move(event); },
[this](const surface::ButtonPressedEvent &event) { on_button_press(event); },
[this](const surface::ButtonReleasedEvent &event) { on_button_release(event); },
[this](auto) {}, [this](auto) {},
}; };
@ -139,16 +147,19 @@ void System::on_surface_lost_focus()
{ {
key = false; key = false;
} }
for (auto &button : m_buttons)
{
button = false;
}
} }
void System::on_key_press(const lt::surface::KeyPressedEvent &event) void System::on_key_press(const lt::surface::KeyPressedEvent &event)
{ {
if (std::to_underlying(event.get_key()) > m_keys.size()) if (std::to_underlying(event.get_key()) > m_keys.size())
{ {
log::warn( log::debug("Key code larger than key container size, implement platform-dependant "
"Key code larger than key container size, implement platform-dependant " "key-code-mapping!");
"key-code-mapping!"
);
return; return;
} }
@ -160,10 +171,8 @@ void System::on_key_release(const lt::surface::KeyReleasedEvent &event)
{ {
if (std::to_underlying(event.get_key()) > m_keys.size()) if (std::to_underlying(event.get_key()) > m_keys.size())
{ {
log::warn( log::debug("Key code larger than key container size, implement platform-dependant "
"Key code larger than key container size, implement platform-dependant " "key-code-mapping!");
"key-code-mapping!"
);
return; return;
} }
@ -171,9 +180,19 @@ void System::on_key_release(const lt::surface::KeyReleasedEvent &event)
m_keys[std::to_underlying(event.get_key())] = false; m_keys[std::to_underlying(event.get_key())] = false;
} }
void System::on_pointer(const lt::surface::PointerEvent &event) void System::on_pointer_move(const lt::surface::MouseMovedEvent &event)
{ {
m_pointer_position = event.get_position(); m_pointer_position = event.get_position();
} }
void System::on_button_press(const lt::surface::ButtonPressedEvent &event)
{
m_buttons[std::to_underlying(event.get_button())] = true;
}
void System::on_button_release(const lt::surface::ButtonReleasedEvent &event)
{
m_buttons[std::to_underlying(event.get_button())] = false;
}
} // namespace lt::input } // namespace lt::input

View file

@ -1,6 +1,9 @@
import test; import std;
import input.system; import input.system;
import input.codes; import input.codes;
import std;
import test.test;
import test.expects;
import surface.events; import surface.events;
import memory.scope; import memory.scope;
import memory.reference; import memory.reference;
@ -9,10 +12,23 @@ import ecs.entity;
import ecs.registry; import ecs.registry;
import surface.system; import surface.system;
using ::lt::input::InputComponent;
using ::lt::input::System;
[[nodiscard]] auto tick_info() -> lt::app::TickInfo // NOLINTBEGIN
using namespace lt;
using input::InputComponent;
using input::System;
using std::ignore;
using test::Case;
using test::expect_eq;
using test::expect_false;
using test::expect_ne;
using test::expect_not_nullptr;
using test::operator""_suite;
using test::expect_throw;
using test::Suite;
// NOLINTEND
[[nodiscard]] auto tick_info() -> app::TickInfo
{ {
return { return {
.delta_time = std::chrono::milliseconds { 16 }, .delta_time = std::chrono::milliseconds { 16 },
@ -24,12 +40,12 @@ using ::lt::input::System;
class Fixture class Fixture
{ {
public: public:
[[nodiscard]] auto registry() -> lt::memory::Ref<lt::ecs::Registry> [[nodiscard]] auto registry() -> memory::Ref<ecs::Registry>
{ {
return m_registry; return m_registry;
} }
auto add_input_component() -> lt::ecs::EntityId auto add_input_component() -> ecs::EntityId
{ {
auto entity = m_registry->create_entity(); auto entity = m_registry->create_entity();
m_registry->add<InputComponent>(entity, {}); m_registry->add<InputComponent>(entity, {});
@ -37,7 +53,7 @@ public:
return entity; return entity;
} }
auto add_surface_component() -> lt::ecs::EntityId auto add_surface_component() -> ecs::EntityId
{ {
auto entity = m_registry->create_entity(); auto entity = m_registry->create_entity();
m_surface_system.create_surface_component( m_surface_system.create_surface_component(
@ -49,28 +65,27 @@ public:
} }
private: private:
lt::memory::Ref<lt::ecs::Registry> m_registry = lt::memory::create_ref<lt::ecs::Registry>(); memory::Ref<ecs::Registry> m_registry = memory::create_ref<ecs::Registry>();
lt::surface::System m_surface_system = lt::surface::System { m_registry }; surface::System m_surface_system = surface::System { m_registry };
}; };
Suite raii = "raii"_suite = "raii"_suite = [] { Suite raii = "raii"_suite = "raii"_suite = [] {
Case { "happy paths" } = [&] { Case { "happy path won't throw" } = [&] {
System { Fixture {}.registry() }; System { Fixture {}.registry() };
}; };
Case { "unhappy paths" } = [] { Case { "many won't freeze/throw" } = [&] {
expect_throw([] { ignore = System { {} }; });
};
Case { "many" } = [&] {
auto fixture = Fixture {}; auto fixture = Fixture {};
for (auto idx : std::views::iota(0, 10'000)) for (auto idx : std::views::iota(0, 10'000))
{ {
ignore = idx;
ignore = System { fixture.registry() }; ignore = System { fixture.registry() };
} }
}; };
Case { "unhappy path throws" } = [] {
expect_throw([] { ignore = System { {} }; });
};
}; };
Suite system_events = "system_events"_suite = [] { Suite system_events = "system_events"_suite = [] {
@ -100,14 +115,14 @@ Suite registry_events = "registry_events"_suite = [] {
auto registry = fixture.registry(); auto registry = fixture.registry();
auto system = System { registry }; auto system = System { registry };
fixture.add_input_component(); const auto &entity = fixture.add_input_component();
expect_eq(registry->view<InputComponent>().get_size(), 1); expect_eq(registry->view<InputComponent>().get_size(), 1);
}; };
Case { "on_destrroy<InputComponent>" } = [] { Case { "on_destrroy<InputComponent>" } = [] {
auto fixture = Fixture {}; auto fixture = Fixture {};
auto registry = fixture.registry(); auto registry = fixture.registry();
auto system = lt::memory::create_scope<System>(registry); auto system = memory::create_scope<System>(registry);
auto entity_a = fixture.add_input_component(); auto entity_a = fixture.add_input_component();
auto entity_b = fixture.add_input_component(); auto entity_b = fixture.add_input_component();
@ -139,7 +154,7 @@ Suite tick = "tick"_suite = [] {
auto system = System { fixture.registry() }; auto system = System { fixture.registry() };
auto surface_entity = fixture.add_surface_component(); auto surface_entity = fixture.add_surface_component();
auto &surface = registry->get<lt::surface::SurfaceComponent>(surface_entity); auto &surface = registry->get<surface::SurfaceComponent>(surface_entity);
auto input_entity = fixture.add_input_component(); auto input_entity = fixture.add_input_component();
auto &input = registry->get<InputComponent>(input_entity); auto &input = registry->get<InputComponent>(input_entity);
@ -147,29 +162,48 @@ Suite tick = "tick"_suite = [] {
auto action_key = input.add_action( auto action_key = input.add_action(
{ {
.name { "test" }, .name { "test" },
.trigger = { .mapped_keycode = lt::Key::a }, .trigger = { .mapped_keycode = Key::A },
} }
); );
using enum ::lt::input::InputAction::State; expect_eq(input.get_action(action_key).state, input::InputAction::State::inactive);
expect_eq(input.get_action(action_key).state, inactive);
system.tick(tick_info()); system.tick(tick_info());
expect_eq(input.get_action(action_key).state, inactive); expect_eq(input.get_action(action_key).state, input::InputAction::State::inactive);
surface.push_event(lt::surface::KeyPressedEvent(lt::Key::a)); surface.push_event(surface::KeyPressedEvent(Key::A));
system.tick(tick_info()); system.tick(tick_info());
expect_eq(input.get_action(action_key).state, triggered); expect_eq(input.get_action(action_key).state, input::InputAction::State::triggered);
system.tick(tick_info()); system.tick(tick_info());
expect_eq(input.get_action(action_key).state, active); expect_eq(input.get_action(action_key).state, input::InputAction::State::active);
system.tick(tick_info()); system.tick(tick_info());
system.tick(tick_info()); system.tick(tick_info());
system.tick(tick_info()); system.tick(tick_info());
expect_eq(input.get_action(action_key).state, active); expect_eq(input.get_action(action_key).state, input::InputAction::State::active);
surface.push_event(lt::surface::KeyReleasedEvent(lt::Key::a)); surface.push_event(surface::KeyReleasedEvent(Key::A));
system.tick(tick_info()); system.tick(tick_info());
expect_eq(input.get_action(action_key).state, inactive); expect_eq(input.get_action(action_key).state, input::InputAction::State::inactive);
};
Case { "Tick triggers" } = [] {
auto fixture = Fixture {};
auto registry = fixture.registry();
auto system = System { fixture.registry() };
auto surface_entity = fixture.add_surface_component();
auto &surface = registry->get<surface::SurfaceComponent>(surface_entity);
auto input_entity = fixture.add_input_component();
auto &input = registry->get<InputComponent>(input_entity);
auto action_key = input.add_action(
{
.name { "test" },
.trigger = { .mapped_keycode = Key::A },
}
);
}; };
}; };

View file

@ -1,317 +1,173 @@
/**
* @note: The reason this is a separate module, rather than being in the `Input` module is that
* the input is received from the hardware through the `Surface` module, and it is further parsed
* inside the `Input` module, USING the `Surface` module's events.
*
* Hence, both `Surface` and `Input` needs to agree to the same input codes, while `Input` depends
* on `Surface`. The simplest solution is to keep the codes in a 3rd module and make both depend on
* it. (I did not want to give `Surface` the responsibility of defining input codes...)
*/
export module input.codes; export module input.codes;
import std;
import preliminary; export enum class Key: std::uint16_t {
/* digits */
D0 = 48,
D1 = 49,
D2 = 50,
D3 = 51,
D4 = 52,
D5 = 53,
D6 = 54,
D7 = 55,
D8 = 56,
D9 = 57,
Semicolon = 59, // ;
Equal = 61, // =
export namespace lt { /* letters */
A = 65,
B = 66,
C = 67,
D = 68,
E = 69,
F = 70,
G = 71,
H = 72,
I = 73,
J = 74,
K = 75,
L = 76,
M = 77,
N = 78,
O = 79,
P = 80,
Q = 81,
R = 82,
S = 83,
t = 84,
U = 85,
V = 86,
W = 87,
X = 88,
Y = 89,
Z = 90,
enum class Key : u16 /* brackets */
{ LeftBracket = 91, // [
none = 0, LBracket = LeftBracket, // [
RightBracket = 93, // ]
RBracket = RightBracket, // ]
left_button, /* arrow */
l_button = left_button, Right = 262,
RightArrow = Right,
RArrow = Right,
Left = 263,
LeftArrow = Left,
LArrow = Left,
Down = 264,
DownArrow = Down,
DArrow = Down,
Up = 265,
UpArrow = Up,
UArrow = Up,
right_button, /* page */
r_button = right_button, PageUp = 266,
PageDown = 267,
middle_button, /* home/end */
m_button = middle_button, Home = 268,
end = 269,
// the buttons on the sidse of some mouses /* toggles */
x_button_1, CapsLock = 280,
x_button_2, ScrollLock = 281,
NumLock = 282,
NumberLock = NumLock,
// Mouse-wheel movement is treated like a key, deal with it. /* function */
wheel_down, F1 = 290,
wheel_up, F2 = 291,
F3 = 292,
F4 = 293,
F5 = 294,
F6 = 295,
F7 = 296,
F8 = 297,
F9 = 298,
F10 = 299,
F11 = 300,
F12 = 301,
F13 = 302,
F14 = 303,
F15 = 304,
F16 = 305,
F17 = 306,
F18 = 307,
F19 = 308,
F20 = 309,
F21 = 310,
F22 = 311,
F23 = 312,
F24 = 313,
F25 = 314,
escape, /* keypad */
escp = escape, Kp0 = 320,
backspace, Kp1 = 321,
tab, Kp2 = 322,
capslock, Kp3 = 323,
enter, Kp4 = 324,
space, Kp5 = 325,
delete_, Kp6 = 326,
Kp7 = 327,
Kp8 = 328,
Kp9 = 329,
KpDecimal = 330,
KpDivide = 331,
KpMultiply = 332,
KpSubstract = 333,
KpAdd = 334,
KpEnter = 335,
KpEqual = 336,
shift, /* modifiers */
left_shit = shift, LeftShift = 340,
l_shift = shift, LShift = LeftShift,
LeftControl = 341,
LControl = LeftControl,
LeftAlt = 342,
LAlt = LeftAlt,
LeftSuper = 343,
LSuper = LeftSuper,
RightShift = 344,
RShift = 344,
RightControl = 345,
RControl = 345,
RightAlt = 346,
RAlt = 346,
RightSuper = 347,
RSuper = 347,
right_shift, /* misc */
r_shift = right_shift, Space = 32,
Apostrophe = 39, // '
Quote = Apostrophe,
control, Comma = 44, // ,
left_control = control, Minus = 45, // -
l_control = control, Period = 46, // .
ctrl = control, Slash = 47, // /
left_ctrl = control, ForwardSlash = Slash, // /
l_ctrl = control, BackSlash = 92, // \
right_control, GraveAccent = 96, // `
r_control = right_control, Console = GraveAccent,
right_ctrl = right_control, World1 = 161, // non-US #1
r_ctrl = right_control, World2 = 162, // non-US #2
Escape = 256,
Esc = Escape,
Enter = 257,
Tab = 258,
BackSpace = 259,
Insert = 260,
Delete = 261,
alt, PrintScreen = 283,
left_alt = alt, Pause = 284,
l_alt = alt,
right_alt, Menu = 348,
r_alt = right_alt,
pageup,
pagedown,
home,
end,
left_arrow,
l_arrow = left_arrow,
up_arrow,
u_arrow = up_arrow,
right_arrow,
r_arrow = right_arrow,
down_arrow,
d_arrow = down_arrow,
cancel,
pause,
select,
print,
snapshot, // aka. print-screen
insert,
help,
sleep,
eep = sleep,
digit_0,
digit_1,
digit_2,
digit_3,
digit_4,
digit_5,
digit_6,
digit_7,
digit_8,
digit_9,
a,
b,
c,
d,
e,
f,
g,
h,
i,
j,
k,
l,
m,
n,
o,
p,
q,
r,
s,
t,
u,
v,
w,
x,
y,
z,
super,
left_super = super,
l_super = super,
right_super,
r_super = right_super,
kp_0,
kp_1,
kp_2,
kp_3,
kp_4,
kp_5,
kp_6,
kp_7,
kp_8,
kp_9,
kp_decimal,
kp_divide,
kp_multiply,
kp_subtract,
kp_add,
kp_enter,
kp_equal,
f1,
f2,
f3,
f4,
f5,
f6,
f7,
f8,
f9,
f10,
f11,
f12,
/** Input was received but was none of the above. */
unknown,
};
[[nodiscard]] constexpr auto to_string(Key key) -> std::string
{
using enum Key;
switch (key)
{
case none: return "<none>";
case left_button: return "left_button";
case right_button: return "right_button";
case middle_button: return "middle_button";
case x_button_1: return "x_button_1";
case x_button_2: return "x_button_2";
case wheel_down: return "wheel_down";
case wheel_up: return "wheel_up";
case escape: return "escape";
case backspace: return "backspace";
case tab: return "tab";
case capslock: return "capslock";
case enter: return "enter";
case space: return "space";
case delete_: return "delete";
case shift: return "shift";
case control: return "control";
case right_control: return "right_control";
case alt: return "alt";
case right_alt: return "right_alt";
case pageup: return "pageup";
case pagedown: return "pagedown";
case home: return "home";
case end: return "end";
case left_arrow: return "left_arrow";
case up_arrow: return "up_arrow";
case right_arrow: return "right_arrow";
case down_arrow: return "down_arrow";
case cancel: return "cancel";
case pause: return "pause";
case select: return "select";
case print: return "print";
case snapshot: return "snapshot";
case insert: return "insert";
case help: return "help";
case sleep: return "sleep";
case digit_0: return "0";
case digit_1: return "1";
case digit_2: return "2";
case digit_3: return "3";
case digit_4: return "4";
case digit_5: return "5";
case digit_6: return "6";
case digit_7: return "7";
case digit_8: return "8";
case digit_9: return "9";
case a: return "a";
case b: return "b";
case c: return "c";
case d: return "d";
case e: return "e";
case f: return "f";
case g: return "g";
case h: return "h";
case i: return "i";
case j: return "j";
case k: return "k";
case l: return "l";
case m: return "m";
case n: return "n";
case o: return "o";
case p: return "p";
case q: return "q";
case r: return "r";
case s: return "s";
case t: return "t";
case u: return "u";
case v: return "v";
case w: return "w";
case x: return "x";
case y: return "y";
case z: return "z";
case super: return "super";
case right_super: return "right_super";
case kp_0: return "kp_0";
case kp_1: return "kp_1";
case kp_2: return "kp_2";
case kp_3: return "kp_3";
case kp_4: return "kp_4";
case kp_5: return "kp_5";
case kp_6: return "kp_6";
case kp_7: return "kp_7";
case kp_8: return "kp_8";
case kp_9: return "kp_9";
case kp_decimal: return "kp_decimal";
case kp_divide: return "kp_divide";
case kp_multiply: return "kp_multiply";
case kp_subtract: return "kp_subtract";
case kp_add: return "kp_add";
case kp_enter: return "kp_enter";
case kp_equal: return "kp_equal";
case f1: return "f1";
case f2: return "f2";
case f3: return "f3";
case f4: return "f4";
case f5: return "f5";
case f6: return "f6";
case f7: return "f7";
case f8: return "f8";
case f9: return "f9";
case f10: return "f10";
case f11: return "f11";
case f12: return "f12";
case unknown: return "<unknown>";
}
return "<invalid>";
}
} // namespace lt
template<>
struct std::formatter<lt::Key>: std::formatter<std::string_view>
{
template<typename FormatContext>
auto format(lt::Key key, FormatContext &ctx) const
{
return std::formatter<std::string_view>::format(lt::to_string(key), ctx);
}
}; };

View file

@ -1,11 +1,11 @@
export module logger; export module logger;
import preliminary; import std;
export namespace lt::log { namespace lt::log {
/** Severity of a log message. */ /** Severity of a log message. */
enum class Level : u8 enum class Level : std::uint8_t
{ {
/** Lowest and most vebose log level, for tracing execution paths and events */ /** Lowest and most vebose log level, for tracing execution paths and events */
trace = 0, trace = 0,
@ -25,25 +25,19 @@ enum class Level : u8
/** Unrecoverable errors */ /** Unrecoverable errors */
critical = 5, critical = 5,
/**
* Logs from the testing-framework.
* Highest so we still get them while turning off all logs from the code under test.
*
* @note: log::test does NOT include source_location
*/
test = 6,
/** No logging */ /** No logging */
off = 7, off = 6,
}; };
auto min_severity = Level::trace; namespace details {
auto set_min_severity(Level severity) inline auto thread_hash_id() noexcept -> std::uint64_t
{ {
min_severity = severity; return static_cast<std::uint64_t>(std::hash<std::thread::id> {}(std::this_thread::get_id()));
} }
} // namespace details
template<typename... Args> template<typename... Args>
struct [[maybe_unused]] print struct [[maybe_unused]] print
{ {
@ -54,12 +48,7 @@ struct [[maybe_unused]] print
Args &&...arguments Args &&...arguments
) noexcept ) noexcept
{ {
if (std::to_underlying(level) < std::to_underlying(min_severity)) constexpr auto to_string = [](Level level, auto location) {
{
return;
}
constexpr auto to_string = [](Level level) {
// clang-format off // clang-format off
switch (level) switch (level)
{ {
@ -70,7 +59,6 @@ struct [[maybe_unused]] print
case warn : return "\033[1;33m| wrn |\033[0m"; case warn : return "\033[1;33m| wrn |\033[0m";
case error : return "\033[1;31m| err |\033[0m"; case error : return "\033[1;31m| err |\033[0m";
case critical: return "\033[1;41m| crt |\033[0m"; case critical: return "\033[1;41m| crt |\033[0m";
case test: /* testing framework's logs will never have location */
case off: return "off"; case off: return "off";
} }
// clang-format on // clang-format on
@ -82,50 +70,18 @@ struct [[maybe_unused]] print
std::println( std::println(
"{} {} ==> {}", "{} {} ==> {}",
to_string(level), to_string(level, location),
std::format("{}:{}", path.filename().string(), location.line()), std::format("{}:{}", path.filename().string(), location.line()),
std::format(format, std::forward<Args>(arguments)...) std::format(format, std::forward<Args>(arguments)...)
); );
} }
[[maybe_unused]] print(
Level level,
std::format_string<Args...> format,
Args &&...arguments
) noexcept
{
constexpr auto to_string = [](Level level) {
// clang-format off
switch (level)
{
using enum ::lt::log::Level;
case trace : return "\033[1;37m| trc |\033[0m";
case debug : return "\033[1;36m| dbg |\033[0m";
case info : return "\033[1;32m| inf |\033[0m";
case warn : return "\033[1;33m| wrn |\033[0m";
case error : return "\033[1;31m| err |\033[0m";
case critical: return "\033[1;41m| crt |\033[0m";
case test : return "\033[1;33m| test |\033[0m";
case off : return "";
}
// clang-format on
std::unreachable();
};
std::println(
"{} {}",
to_string(level),
std::format(format, std::forward<Args>(arguments)...)
);
}
}; };
template<typename... Args> template<typename... Args>
print(Level, const std::source_location &, std::format_string<Args...>, Args &&...) noexcept print(Level, const std::source_location &, std::format_string<Args...>, Args &&...) noexcept
-> print<Args...>; -> print<Args...>;
template<typename... Args> export template<typename... Args>
struct [[maybe_unused]] trace struct [[maybe_unused]] trace
{ {
[[maybe_unused]] trace( [[maybe_unused]] trace(
@ -138,10 +94,10 @@ struct [[maybe_unused]] trace
} }
}; };
template<typename... Args> export template<typename... Args>
trace(std::format_string<Args...>, Args &&...) noexcept -> trace<Args...>; trace(std::format_string<Args...>, Args &&...) noexcept -> trace<Args...>;
template<typename... Args> export template<typename... Args>
struct [[maybe_unused]] debug struct [[maybe_unused]] debug
{ {
[[maybe_unused]] debug( [[maybe_unused]] debug(
@ -154,11 +110,10 @@ struct [[maybe_unused]] debug
} }
}; };
template<typename... Args> export template<typename... Args>
debug(std::format_string<Args...>, Args &&...) noexcept -> debug<Args...>; debug(std::format_string<Args...>, Args &&...) noexcept -> debug<Args...>;
export template<typename... Args>
template<typename... Args>
struct [[maybe_unused]] info struct [[maybe_unused]] info
{ {
[[maybe_unused]] info( [[maybe_unused]] info(
@ -171,10 +126,10 @@ struct [[maybe_unused]] info
} }
}; };
template<typename... Args> export template<typename... Args>
info(std::format_string<Args...>, Args &&...) noexcept -> info<Args...>; info(std::format_string<Args...>, Args &&...) noexcept -> info<Args...>;
template<typename... Args> export template<typename... Args>
struct [[maybe_unused]] warn struct [[maybe_unused]] warn
{ {
[[maybe_unused]] warn( [[maybe_unused]] warn(
@ -187,10 +142,10 @@ struct [[maybe_unused]] warn
} }
}; };
template<typename... Args> export template<typename... Args>
warn(std::format_string<Args...>, Args &&...) noexcept -> warn<Args...>; warn(std::format_string<Args...>, Args &&...) noexcept -> warn<Args...>;
template<typename... Args> export template<typename... Args>
struct [[maybe_unused]] error struct [[maybe_unused]] error
{ {
[[maybe_unused]] error( [[maybe_unused]] error(
@ -203,10 +158,10 @@ struct [[maybe_unused]] error
} }
}; };
template<typename... Args> export template<typename... Args>
error(std::format_string<Args...>, Args &&...) noexcept -> error<Args...>; error(std::format_string<Args...>, Args &&...) noexcept -> error<Args...>;
template<typename... Args> export template<typename... Args>
struct [[maybe_unused]] critical struct [[maybe_unused]] critical
{ {
[[maybe_unused]] critical( [[maybe_unused]] critical(
@ -219,13 +174,7 @@ struct [[maybe_unused]] critical
} }
}; };
template<typename... Args> export template<typename... Args>
critical(std::format_string<Args...>, Args &&...) noexcept -> critical<Args...>; critical(std::format_string<Args...>, Args &&...) noexcept -> critical<Args...>;
template<typename... Args>
void test(std::format_string<Args...> format, Args &&...arguments) noexcept
{
print(Level::test, format, std::forward<Args>(arguments)...);
}
} // namespace lt::log } // namespace lt::log

View file

@ -1,7 +1,11 @@
import test; import logger;
import test.test;
using ::lt::test::Case;
using ::lt::test::Suite;
Suite suite = [] { Suite suite = [] {
Case { "formatless" } = [] { Case { "no format" } = [] {
lt::log::trace("trace"); lt::log::trace("trace");
lt::log::debug("debug"); lt::log::debug("debug");
lt::log::info("info"); lt::log::info("info");

View file

@ -1,7 +1,6 @@
export module math.algebra; export module math.algebra;
import preliminary;
import math.mat4; import math.mat4;
import std;
export namespace lt::math { export namespace lt::math {
@ -32,12 +31,11 @@ export namespace lt::math {
* *
* the 1 at [z][3] is to save the Z axis into the resulting W for perspective division. * the 1 at [z][3] is to save the Z axis into the resulting W for perspective division.
* *
* @ref Thanks to @pikuma for explaining the math behind this: * @ref Thanks to pikuma for explaining the math behind this:
* https://www.youtube.com/watch?v=EqNcqBdrNyI * https://www.youtube.com/watch?v=EqNcqBdrNyI
*/ */
template<typename T> template<typename T>
requires(std::is_arithmetic_v<T>) constexpr auto perspective(T field_of_view, T aspect_ratio, T z_near, T z_far)
constexpr auto perspective(T field_of_view, T aspect_ratio, T z_near, T z_far) -> mat4_impl<T>
{ {
const T half_fov_tan = std::tan(field_of_view / static_cast<T>(2)); const T half_fov_tan = std::tan(field_of_view / static_cast<T>(2));

View file

@ -1,6 +1,5 @@
export module math.components; export module math.components;
import preliminary;
import math.vec3; import math.vec3;
namespace lt::math::components { namespace lt::math::components {

View file

@ -1,26 +1,16 @@
export module math.mat4; export module math.mat4;
import preliminary;
import math.vec2;
import math.vec3; import math.vec3;
import math.vec4; import math.vec4;
import std;
export namespace lt::math { namespace lt::math {
/** A 4 by 4 matrix, column major order export template<typename T = float>
*
* @todo(Light): Use std::simd when it's implemented. */
template<typename T = f32>
requires(std::is_arithmetic_v<T>)
struct mat4_impl struct mat4_impl
{ {
using Column_T = vec4_impl<T>; using Column_T = vec4_impl<T>;
using Underlying_T = Column_T::Underlying_T; constexpr explicit mat4_impl(T scalar = 0)
static constexpr auto num_elements = 4u * 4u;
constexpr explicit mat4_impl(T scalar = T {})
: values( : values(
{ {
Column_T { scalar }, Column_T { scalar },
@ -32,12 +22,13 @@ struct mat4_impl
{ {
} }
constexpr mat4_impl(
// clang-format off // clang-format off
const T& x0, const T& x1, const T& x2, const T& x3, constexpr mat4_impl(
const T& y0, const T& y1, const T& y2, const T& y3, const T& x0, const T& y0, const T& z0, const T& w0,
const T& z0, const T& z1, const T& z2, const T& z3, const T& x1, const T& y1, const T& z1, const T& w1,
const T& w0, const T& w1, const T& w2, const T& w3) const T& x2, const T& y2, const T& z2, const T& w2,
const T& x3, const T& y3, const T& z3, const T& w3
)
// clang-format on // clang-format on
: values({ { x0, x1, x2, x3 }, { y0, y1, y2, y3 }, { z0, z1, z2, z3 }, { w0, w1, w2, w3 } }) : values({ { x0, x1, x2, x3 }, { y0, y1, y2, y3 }, { z0, z1, z2, z3 }, { w0, w1, w2, w3 } })
{ {
@ -63,123 +54,57 @@ struct mat4_impl
}; };
} }
[[nodiscard]] constexpr auto operator[](std::size_t idx) -> Column_T &
{
return values[idx];
}
[[nodiscard]] constexpr auto operator[](std::size_t idx) const -> const Column_T &
{
return values[idx];
}
[[nodiscard]] constexpr auto operator*(const mat4_impl<T> &other) const -> mat4_impl<T> [[nodiscard]] constexpr auto operator*(const mat4_impl<T> &other) const -> mat4_impl<T>
{ {
const auto &[a_x, a_y, a_z, a_w] = values; return mat4_impl<T> {};
const auto &[b_x, b_y, b_z, b_w] = other.values;
return mat4_impl<T>(
// X column
a_x.x * b_x.x + a_y.x * b_x.y + a_z.x * b_x.z + a_w.x * b_x.w,
a_x.y * b_x.x + a_y.y * b_x.y + a_z.y * b_x.z + a_w.y * b_x.w,
a_x.z * b_x.x + a_y.z * b_x.y + a_z.z * b_x.z + a_w.z * b_x.w,
a_x.w * b_x.x + a_y.w * b_x.y + a_z.w * b_x.z + a_w.w * b_x.w,
// Y column
a_x.x * b_y.x + a_y.x * b_y.y + a_z.x * b_y.z + a_w.x * b_y.w,
a_x.y * b_y.x + a_y.y * b_y.y + a_z.y * b_y.z + a_w.y * b_y.w,
a_x.z * b_y.x + a_y.z * b_y.y + a_z.z * b_y.z + a_w.z * b_y.w,
a_x.w * b_y.x + a_y.w * b_y.y + a_z.w * b_y.z + a_w.w * b_y.w,
// Z column
a_x.x * b_z.x + a_y.x * b_z.y + a_z.x * b_z.z + a_w.x * b_z.w,
a_x.y * b_z.x + a_y.y * b_z.y + a_z.y * b_z.z + a_w.y * b_z.w,
a_x.z * b_z.x + a_y.z * b_z.y + a_z.z * b_z.z + a_w.z * b_z.w,
a_x.w * b_z.x + a_y.w * b_z.y + a_z.w * b_z.z + a_w.w * b_z.w,
// W column
a_x.x * b_w.x + a_y.x * b_w.y + a_z.x * b_w.z + a_w.x * b_w.w,
a_x.y * b_w.x + a_y.y * b_w.y + a_z.y * b_w.z + a_w.y * b_w.w,
a_x.z * b_w.x + a_y.z * b_w.y + a_z.z * b_w.z + a_w.z * b_w.w,
a_x.w * b_w.x + a_y.w * b_w.y + a_z.w * b_w.z + a_w.w * b_w.w
);
} }
[[nodiscard]] constexpr auto operator[](size_t idx) -> Column_T & [[nodiscard]] constexpr auto operator*(const vec4_impl<T> &other) const -> vec4_impl<T>
{ {
debug_check(idx < num_elements, "mat4 out of bound access: {}", idx); return vec4_impl<T> {};
return values[idx];
} }
[[nodiscard]] constexpr auto operator[](size_t idx) const -> const Column_T & std::array<Column_T, 4> values; // NOLINT
{
return values[idx];
}
[[nodiscard]] static constexpr auto transpose(const mat4_impl<T> &mat) -> mat4_impl<T>
{
const auto &[x, y, z, w] = mat.values;
return mat4_impl<T> {
x.x, y.x, z.x, w.x, x.y, y.y, z.y, w.y, x.z, y.z, z.z, w.z, x.w, y.w, z.w, w.w,
};
}
[[nodiscard]] static constexpr auto translate(const vec3_impl<T> &vec) -> mat4_impl<T>
{
return mat4_impl<T>(
T { 1 },
T { 0 },
T { 0 },
T { 0 },
T { 0 },
T { 1 },
T { 0 },
T { 0 },
T { 0 },
T { 0 },
T { 1 },
T { 0 },
vec.x,
vec.y,
vec.z,
T { 1 }
);
}
[[nodiscard]] static constexpr auto scale(const vec3_impl<T> &vec) -> mat4_impl<T>
{
return mat4_impl<T>(
vec.x,
T { 0 },
T { 0 },
T { 0 },
T { 0 },
vec.y,
T { 0 },
T { 0 },
T { 0 },
T { 0 },
vec.z,
T { 0 },
T { 0 },
T { 0 },
T { 0 },
T { 1 }
);
}
std::array<Column_T, 4u> values;
}; };
using mat4 = mat4_impl<f32>; export template<typename T>
[[nodiscard]] auto translate(const vec3_impl<T> &value) -> mat4_impl<T>
{
return mat4_impl<T> {};
}
using mat4_f32 = mat4; export template<typename T>
using mat4_f64 = mat4_impl<f64>; [[nodiscard]] auto rotate(float value, const vec3_impl<T> &xyz) -> mat4_impl<T>
{
return mat4_impl<T> {};
}
using mat4_i8 = mat4_impl<i8>; export template<typename T>
using mat4_i16 = mat4_impl<i16>; [[nodiscard]] auto scale(const vec3_impl<T> &value) -> mat4_impl<T>
using mat4_i32 = mat4_impl<i32>; {
using mat4_i64 = mat4_impl<i64>; return mat4_impl<T> {};
}
using mat4_u8 = mat4_impl<u8>; export template<typename T>
using mat4_u16 = mat4_impl<u16>; [[nodiscard]] auto inverse(const mat4_impl<T> &value) -> mat4_impl<T>
using mat4_u32 = mat4_impl<u32>; {
using mat4_u64 = mat4_impl<u64>; return mat4_impl<T> {};
}
export using mat4 = mat4_impl<float>;
export using imat4 = mat4_impl<std::int32_t>;
export using umat4 = mat4_impl<std::uint32_t>;
} // namespace lt::math } // namespace lt::math

View file

@ -1,413 +0,0 @@
import test;
import math.vec3;
import math.mat4;
using vec3 = ::lt::math::vec3;
using mat4 = ::lt::math::mat4;
Suite static_tests = "mat4_static_checks"_suite = [] {
constexpr auto num_elements = lt::math::mat4::num_elements;
static_assert(num_elements == 4u * 4u);
static_assert(std::is_same_v<lt::math::mat4, lt::math::mat4_f32>);
static_assert(sizeof(lt::math::mat4_f32) == sizeof(f32) * num_elements);
static_assert(sizeof(lt::math::mat4_f64) == sizeof(f64) * num_elements);
static_assert(sizeof(lt::math::mat4_i8) == sizeof(i8) * num_elements);
static_assert(sizeof(lt::math::mat4_i16) == sizeof(i16) * num_elements);
static_assert(sizeof(lt::math::mat4_i32) == sizeof(i32) * num_elements);
static_assert(sizeof(lt::math::mat4_i64) == sizeof(i64) * num_elements);
static_assert(sizeof(lt::math::mat4_u8) == sizeof(u8) * num_elements);
static_assert(sizeof(lt::math::mat4_u16) == sizeof(u16) * num_elements);
static_assert(sizeof(lt::math::mat4_u32) == sizeof(u32) * num_elements);
static_assert(sizeof(lt::math::mat4_u64) == sizeof(u64) * num_elements);
};
Suite raii = "mat4_raii"_suite = [] {
Case { "happy paths" } = [] {
ignore = mat4 {};
ignore = mat4 { 1.0 };
ignore = mat4 {
1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0,
};
ignore = mat4 {
mat4::Column_T { 1.0, 2.0, 3.0, 4.0 },
mat4::Column_T { 5.0, 6.0, 7.0, 8.0 },
mat4::Column_T { 9.0, 10.0, 11.0, 12.0 },
mat4::Column_T { 13.0, 14.0, 15.0, 16.0 },
};
};
Case { "unhappy paths" } = [] {
};
Case { "many" } = [] {
for (auto idx : std::views::iota(0, 1'000'000))
{
ignore = idx;
ignore = mat4 {};
ignore = mat4 { 1.0 };
ignore = mat4 {
1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0,
9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0,
};
ignore = mat4 {
mat4::Column_T { 1.0, 2.0, 3.0, 4.0 },
mat4::Column_T { 5.0, 6.0, 7.0, 8.0 },
mat4::Column_T { 9.0, 10.0, 11.0, 12.0 },
mat4::Column_T { 13.0, 14.0, 15.0, 16.0 },
};
}
};
Case { "post default construct has correct state" } = [] {
const auto [x, y, z, w] = mat4 {}.values;
expect_eq(x[0], mat4::Underlying_T {});
expect_eq(x[1], mat4::Underlying_T {});
expect_eq(x[2], mat4::Underlying_T {});
expect_eq(x[3], mat4::Underlying_T {});
expect_eq(y[0], mat4::Underlying_T {});
expect_eq(y[1], mat4::Underlying_T {});
expect_eq(y[2], mat4::Underlying_T {});
expect_eq(y[3], mat4::Underlying_T {});
expect_eq(z[0], mat4::Underlying_T {});
expect_eq(z[1], mat4::Underlying_T {});
expect_eq(z[2], mat4::Underlying_T {});
expect_eq(z[3], mat4::Underlying_T {});
expect_eq(w[0], mat4::Underlying_T {});
expect_eq(w[1], mat4::Underlying_T {});
expect_eq(w[2], mat4::Underlying_T {});
expect_eq(w[3], mat4::Underlying_T {});
};
Case { "post scalar construct has correct state" } = [] {
const auto [x, y, z, w] = mat4 { 69.0 }.values;
expect_eq(x[0], mat4::Underlying_T { 69.0 });
expect_eq(x[1], mat4::Underlying_T { 69.0 });
expect_eq(x[2], mat4::Underlying_T { 69.0 });
expect_eq(x[3], mat4::Underlying_T { 69.0 });
expect_eq(y[0], mat4::Underlying_T { 69.0 });
expect_eq(y[1], mat4::Underlying_T { 69.0 });
expect_eq(y[2], mat4::Underlying_T { 69.0 });
expect_eq(y[3], mat4::Underlying_T { 69.0 });
expect_eq(z[0], mat4::Underlying_T { 69.0 });
expect_eq(z[1], mat4::Underlying_T { 69.0 });
expect_eq(z[2], mat4::Underlying_T { 69.0 });
expect_eq(z[3], mat4::Underlying_T { 69.0 });
expect_eq(w[0], mat4::Underlying_T { 69.0 });
expect_eq(w[1], mat4::Underlying_T { 69.0 });
expect_eq(w[2], mat4::Underlying_T { 69.0 });
expect_eq(w[3], mat4::Underlying_T { 69.0 });
};
Case { "post construct with all values has correct state" } = [] {
const auto [x, y, z, w] = mat4 {
1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0,
}.values;
expect_eq(x[0], mat4::Underlying_T { 1.0 });
expect_eq(x[1], mat4::Underlying_T { 2.0 });
expect_eq(x[2], mat4::Underlying_T { 3.0 });
expect_eq(x[3], mat4::Underlying_T { 4.0 });
expect_eq(y[0], mat4::Underlying_T { 5.0 });
expect_eq(y[1], mat4::Underlying_T { 6.0 });
expect_eq(y[2], mat4::Underlying_T { 7.0 });
expect_eq(y[3], mat4::Underlying_T { 8.0 });
expect_eq(z[0], mat4::Underlying_T { 9.0 });
expect_eq(z[1], mat4::Underlying_T { 10.0 });
expect_eq(z[2], mat4::Underlying_T { 11.0 });
expect_eq(z[3], mat4::Underlying_T { 12.0 });
expect_eq(w[0], mat4::Underlying_T { 13.0 });
expect_eq(w[1], mat4::Underlying_T { 14.0 });
expect_eq(w[2], mat4::Underlying_T { 15.0 });
expect_eq(w[3], mat4::Underlying_T { 16.0 });
};
Case { "post construct with columns has correct state" } = [] {
const auto [x, y, z, w] = mat4 {
mat4::Column_T { 1.0, 2.0, 3.0, 4.0 },
mat4::Column_T { 5.0, 6.0, 7.0, 8.0 },
mat4::Column_T { 9.0, 10.0, 11.0, 12.0 },
mat4::Column_T { 13.0, 14.0, 15.0, 16.0 },
}.values;
expect_eq(x[0], mat4::Underlying_T { 1.0 });
expect_eq(x[1], mat4::Underlying_T { 2.0 });
expect_eq(x[2], mat4::Underlying_T { 3.0 });
expect_eq(x[3], mat4::Underlying_T { 4.0 });
expect_eq(y[0], mat4::Underlying_T { 5.0 });
expect_eq(y[1], mat4::Underlying_T { 6.0 });
expect_eq(y[2], mat4::Underlying_T { 7.0 });
expect_eq(y[3], mat4::Underlying_T { 8.0 });
expect_eq(z[0], mat4::Underlying_T { 9.0 });
expect_eq(z[1], mat4::Underlying_T { 10.0 });
expect_eq(z[2], mat4::Underlying_T { 11.0 });
expect_eq(z[3], mat4::Underlying_T { 12.0 });
expect_eq(w[0], mat4::Underlying_T { 13.0 });
expect_eq(w[1], mat4::Underlying_T { 14.0 });
expect_eq(w[2], mat4::Underlying_T { 15.0 });
expect_eq(w[3], mat4::Underlying_T { 16.0 });
};
Case { "post construct identity matrix has correct state" } = [] {
const auto [x, y, z, w] = mat4::identity().values;
expect_eq(x[0], mat4::Underlying_T { 1 });
expect_eq(x[1], mat4::Underlying_T {});
expect_eq(x[2], mat4::Underlying_T {});
expect_eq(x[3], mat4::Underlying_T {});
expect_eq(y[0], mat4::Underlying_T {});
expect_eq(y[1], mat4::Underlying_T { 1 });
expect_eq(y[2], mat4::Underlying_T {});
expect_eq(y[3], mat4::Underlying_T {});
expect_eq(z[0], mat4::Underlying_T {});
expect_eq(z[1], mat4::Underlying_T {});
expect_eq(z[2], mat4::Underlying_T { 1 });
expect_eq(z[3], mat4::Underlying_T {});
expect_eq(w[0], mat4::Underlying_T {});
expect_eq(w[1], mat4::Underlying_T {});
expect_eq(w[2], mat4::Underlying_T {});
expect_eq(w[3], mat4::Underlying_T { 1 });
};
};
Suite arithmetic_operators = "mat4_arithmetic_operators"_suite = [] {
Case { "operator *" } = [] {
const auto lhs = mat4 {
mat4::Column_T { 1.0, 2.0, 3.0, 4.0 },
mat4::Column_T { 5.0, 6.0, 7.0, 8.0 },
mat4::Column_T { 9.0, 10.0, 11.0, 12.0 },
mat4::Column_T { 13.0, 14.0, 15.0, 16.0 },
};
const auto rhs = mat4 {
mat4::Column_T { 17.0, 18.0, 19.0, 20.0 },
mat4::Column_T { 21.0, 22.0, 23.0, 24.0 },
mat4::Column_T { 25.0, 26.0, 27.0, 28.0 },
mat4::Column_T { 29.0, 30.0, 31.0, 32.0 },
};
const auto [x, y, z, w] = (lhs * rhs).values;
expect_eq(x[0], 538.0);
expect_eq(x[1], 612.0);
expect_eq(x[2], 686.0);
expect_eq(x[3], 760.0);
expect_eq(y[0], 650.0);
expect_eq(y[1], 740.0);
expect_eq(y[2], 830.0);
expect_eq(y[3], 920.0);
expect_eq(z[0], 762.0);
expect_eq(z[1], 868.0);
expect_eq(z[2], 974.0);
expect_eq(z[3], 1080.0);
expect_eq(w[0], 874.0);
expect_eq(w[1], 996.0);
expect_eq(w[2], 1118.0);
expect_eq(w[3], 1240.0);
};
};
Suite access_operators = "mat4_access_operators"_suite = [] {
Case { "operator []" } = [] {
auto mat = mat4 {
1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0,
};
expect_eq(mat[0][0], 1.0);
expect_eq(mat[0][1], 2.0);
expect_eq(mat[0][2], 3.0);
expect_eq(mat[0][3], 4.0);
expect_eq(mat[1][0], 5.0);
expect_eq(mat[1][1], 6.0);
expect_eq(mat[1][2], 7.0);
expect_eq(mat[1][3], 8.0);
expect_eq(mat[2][0], 9.0);
expect_eq(mat[2][1], 10.0);
expect_eq(mat[2][2], 11.0);
expect_eq(mat[2][3], 12.0);
expect_eq(mat[3][0], 13.0);
expect_eq(mat[3][1], 14.0);
expect_eq(mat[3][2], 15.0);
expect_eq(mat[3][3], 16.0);
};
Case { "operator [] const" } = [] {
const auto mat = mat4 {
1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0,
};
expect_eq(mat[0][0], 1.0);
expect_eq(mat[0][1], 2.0);
expect_eq(mat[0][2], 3.0);
expect_eq(mat[0][3], 4.0);
expect_eq(mat[1][0], 5.0);
expect_eq(mat[1][1], 6.0);
expect_eq(mat[1][2], 7.0);
expect_eq(mat[1][3], 8.0);
expect_eq(mat[2][0], 9.0);
expect_eq(mat[2][1], 10.0);
expect_eq(mat[2][2], 11.0);
expect_eq(mat[2][3], 12.0);
expect_eq(mat[3][0], 13.0);
expect_eq(mat[3][1], 14.0);
expect_eq(mat[3][2], 15.0);
expect_eq(mat[3][3], 16.0);
};
};
Suite transformations = "mat4_transformations"_suite = [] {
Case { "translate" } = [] {
const auto &[x, y, z, w] = mat4::translate(vec3 { 1, 2, 3 }).values;
// identity basis
expect_eq(x[0], 1);
expect_eq(x[1], 0);
expect_eq(x[2], 0);
expect_eq(x[3], 0);
expect_eq(y[0], 0);
expect_eq(y[1], 1);
expect_eq(y[2], 0);
expect_eq(y[3], 0);
expect_eq(z[0], 0);
expect_eq(z[1], 0);
expect_eq(z[2], 1);
expect_eq(z[3], 0);
// translation column
expect_eq(w[0], 1);
expect_eq(w[1], 2);
expect_eq(w[2], 3);
expect_eq(w[3], 1);
};
Case { "scale" } = [] {
const auto [x, y, z, w] = mat4::scale(vec3 { 2, 3, 4 }).values;
expect_eq(x[0], 2);
expect_eq(x[1], 0);
expect_eq(x[2], 0);
expect_eq(x[3], 0);
expect_eq(y[0], 0);
expect_eq(y[1], 3);
expect_eq(y[2], 0);
expect_eq(y[3], 0);
expect_eq(z[0], 0);
expect_eq(z[1], 0);
expect_eq(z[2], 4);
expect_eq(z[3], 0);
expect_eq(w[0], 0);
expect_eq(w[1], 0);
expect_eq(w[2], 0);
expect_eq(w[3], 1);
};
Case { "scale -> translate" } = [] {
const auto scale = mat4::scale(vec3 { 2, 2, 2 });
const auto translate = mat4::translate(vec3 { 1, 2, 3 });
const auto [x, y, z, w] = (scale * translate).values;
// scaled basis
expect_eq(x[0], 2);
expect_eq(x[1], 0);
expect_eq(x[2], 0);
expect_eq(x[3], 0);
expect_eq(y[0], 0);
expect_eq(y[1], 2);
expect_eq(y[2], 0);
expect_eq(y[3], 0);
expect_eq(z[0], 0);
expect_eq(z[1], 0);
expect_eq(z[2], 2);
expect_eq(z[3], 0);
// translation is scaled (local-space translation)
expect_eq(w[0], 2); // 1 * 2
expect_eq(w[1], 4); // 2 * 2
expect_eq(w[2], 6); // 3 * 2
expect_eq(w[3], 1);
};
Case { "transpose" } = [] {
const auto mat = mat4 {
mat4::Column_T { 1, 2, 3, 4 },
mat4::Column_T { 5, 6, 7, 8 },
mat4::Column_T { 9, 10, 11, 12 },
mat4::Column_T { 13, 14, 15, 16 },
};
const auto [x, y, z, w] = mat4::transpose(mat).values;
// rows become columns
expect_eq(x[0], 1);
expect_eq(x[1], 5);
expect_eq(x[2], 9);
expect_eq(x[3], 13);
expect_eq(y[0], 2);
expect_eq(y[1], 6);
expect_eq(y[2], 10);
expect_eq(y[3], 14);
expect_eq(z[0], 3);
expect_eq(z[1], 7);
expect_eq(z[2], 11);
expect_eq(z[3], 15);
expect_eq(w[0], 4);
expect_eq(w[1], 8);
expect_eq(w[2], 12);
expect_eq(w[3], 16);
};
Case { "transpose twice" } = [] {
const auto mat = mat4 {
mat4::Column_T { 1, 2, 3, 4 },
mat4::Column_T { 5, 6, 7, 8 },
mat4::Column_T { 9, 10, 11, 12 },
mat4::Column_T { 13, 14, 15, 16 },
};
const auto [x, y, z, w] = mat4::transpose(mat4::transpose(mat)).values;
expect_eq(x[0], 1);
expect_eq(x[1], 2);
expect_eq(x[2], 3);
expect_eq(x[3], 4);
expect_eq(y[0], 5);
expect_eq(y[1], 6);
expect_eq(y[2], 7);
expect_eq(y[3], 8);
expect_eq(z[0], 9);
expect_eq(z[1], 10);
expect_eq(z[2], 11);
expect_eq(z[3], 12);
expect_eq(w[0], 13);
expect_eq(w[1], 14);
expect_eq(w[2], 15);
expect_eq(w[3], 16);
};
};

View file

@ -1,27 +1,26 @@
export module math.trig; export module math.trig;
import preliminary;
export namespace lt::math { export namespace lt::math {
[[nodiscard]] constexpr auto to_radians(f32 degrees) -> f32 [[nodiscard]] constexpr auto radians(float degrees) -> float
{ {
return degrees * 0.01745329251994329576923690768489f; return degrees * 0.01745329251994329576923690768489f;
} }
[[nodiscard]] constexpr auto to_radians(f64 degrees) -> f64 [[nodiscard]] constexpr auto radians(double degrees) -> double
{ {
return degrees * 0.01745329251994329576923690768489; return degrees * 0.01745329251994329576923690768489;
} }
[[nodiscard]] constexpr auto to_degrees(f32 radians) -> f32 [[nodiscard]] constexpr auto degrees(float radians) -> float
{ {
return radians * 57.295779513082320876798154814105f; return radians * 57.295779513082320876798154814105f;
} }
[[nodiscard]] constexpr auto to_degrees(f64 radians) -> f64 [[nodiscard]] constexpr auto degrees(double radians) -> double
{ {
return radians * 57.295779513082320876798154814105; return radians * 57.295779513082320876798154814105;
} }
} // namespace lt::math } // namespace lt::math

View file

@ -1,43 +0,0 @@
import test;
import math.trig;
Suite conversions = "trig_conversions"_suite = [] {
using ::lt::math::to_degrees;
using ::lt::math::to_radians;
Case { "to_radians <f32>" } = [] {
expect_eq(to_radians(f32 { 0.0f }), f32 { 0.0f });
expect_eq(to_radians(f32 { 90.0f }), f32 { 1.5707963267948966f });
expect_eq(to_radians(f32 { 180.0f }), f32 { 3.1415926535897932f });
expect_eq(to_radians(f32 { 360.0f }), f32 { 6.2831853071795864f });
};
Case { "to_radians <f64>" } = [] {
expect_eq(to_radians(f64 { 0.0 }), f64 { 0.0 });
expect_eq(to_radians(f64 { 90.0 }), f64 { 1.5707963267948966 });
expect_eq(to_radians(f64 { 180.0 }), f64 { 3.1415926535897932 });
expect_eq(to_radians(f64 { 360.0 }), f64 { 6.2831853071795864 });
};
Case { "to_degrees <f32>" } = [] {
expect_eq(to_degrees(f32 { 0.0f }), f32 { 0.0f });
expect_eq(to_degrees(f32 { 1.5707963267948966f }), f32 { 90.0f });
expect_eq(to_degrees(f32 { 3.1415926535897932f }), f32 { 180.0f });
expect_eq(to_degrees(f32 { 6.2831853071795864f }), f32 { 360.0f });
};
Case { "to_degrees <f64>" } = [] {
expect_eq(to_degrees(f64 { 0.0 }), f64 { 0.0 });
expect_eq(to_degrees(f64 { 1.5707963267948966 }), f64 { 90.0 });
expect_eq(to_degrees(f64 { 3.1415926535897932 }), f64 { 180.0 });
expect_eq(to_degrees(f64 { 6.2831853071795864 }), f64 { 360.0 });
};
Case { "to_degrees -> to_radians -> to_degrees <f32>" } = [] {
expect_eq(to_degrees(to_radians(f32 { 45.0f })), f32 { 45.0f });
};
Case { "to_degrees -> to_radians -> to_degrees <f64>" } = [] {
expect_eq(to_degrees(to_radians(f64 { 45.0 })), f64 { 45.0 });
};
};

View file

@ -1,17 +1,12 @@
export module math.vec2; export module math.vec2;
import preliminary; import std;
export namespace lt::math { namespace lt::math {
template<typename T = f32> export template<typename T = float>
requires(std::is_arithmetic_v<T>)
struct vec2_impl struct vec2_impl
{ {
using Underlying_T = T;
static constexpr auto num_elements = 2u;
constexpr vec2_impl(): x(), y() constexpr vec2_impl(): x(), y()
{ {
} }
@ -34,23 +29,7 @@ struct vec2_impl
return !(*this == other); return !(*this == other);
} }
[[nodiscard]] constexpr auto operator+(const vec2_impl<T> &other) const -> vec2_impl [[nodiscard]] auto operator*(const vec2_impl<T> &other) const -> vec2_impl
{
return {
x + other.x,
y + other.y,
};
}
[[nodiscard]] constexpr auto operator-(const vec2_impl<T> &other) const -> vec2_impl
{
return {
x - other.x,
y - other.y,
};
}
[[nodiscard]] constexpr auto operator*(const vec2_impl<T> &other) const -> vec2_impl
{ {
return { return {
x * other.x, x * other.x,
@ -58,45 +37,33 @@ struct vec2_impl
}; };
} }
[[nodiscard]] constexpr auto operator/(const vec2_impl<T> &other) const -> vec2_impl [[nodiscard]] auto operator-(const vec2_impl<T> &other) const -> vec2_impl
{ {
return { return {
x / other.x, x - other.x,
y / other.y, y - other.y,
}; };
} }
[[nodiscard]] constexpr auto operator[](u8 idx) -> T & [[nodiscard]] auto operator*(float scalar) const -> vec2_impl
{ {
debug_check(idx < num_elements, "vec2 out of bound access: {}", idx); return {
return ((T *)this)[idx]; x * scalar,
y * scalar,
};
} }
[[nodiscard]] constexpr auto operator[](u8 idx) const -> const T & T x; // NOLINT
{
debug_check(idx < num_elements, "vec2 out of bound access: {}", idx);
return ((T *)this)[idx];
}
T x; T y; // NOLINT
T y;
}; };
using vec2 = vec2_impl<f32>;
using vec2_f32 = vec2; export using vec2 = vec2_impl<float>;
using vec2_f64 = vec2_impl<f64>;
using vec2_i8 = vec2_impl<i8>; export using ivec2 = vec2_impl<std::int32_t>;
using vec2_i16 = vec2_impl<i16>;
using vec2_i32 = vec2_impl<i32>;
using vec2_i64 = vec2_impl<i64>;
using vec2_u8 = vec2_impl<u8>; export using uvec2 = vec2_impl<std::uint32_t>;
using vec2_u16 = vec2_impl<u16>;
using vec2_u32 = vec2_impl<u32>;
using vec2_u64 = vec2_impl<u64>;
} // namespace lt::math } // namespace lt::math

View file

@ -1,130 +0,0 @@
import test;
import math.vec2;
using vec2 = ::lt::math::vec2;
using ivec2 = ::lt::math::vec2_i32;
Suite static_tests = "vec3_static_checks"_suite = [] {
constexpr auto num_elements = lt::math::vec2::num_elements;
static_assert(num_elements == 2u);
static_assert(std::is_same_v<lt::math::vec2, lt::math::vec2_f32>);
static_assert(sizeof(lt::math::vec2_f32) == sizeof(f32) * num_elements);
static_assert(sizeof(lt::math::vec2_f64) == sizeof(f64) * num_elements);
static_assert(sizeof(lt::math::vec2_i8) == sizeof(i8) * num_elements);
static_assert(sizeof(lt::math::vec2_i16) == sizeof(i16) * num_elements);
static_assert(sizeof(lt::math::vec2_i32) == sizeof(i32) * num_elements);
static_assert(sizeof(lt::math::vec2_i64) == sizeof(i64) * num_elements);
static_assert(sizeof(lt::math::vec2_u8) == sizeof(u8) * num_elements);
static_assert(sizeof(lt::math::vec2_u16) == sizeof(u16) * num_elements);
static_assert(sizeof(lt::math::vec2_u32) == sizeof(u32) * num_elements);
static_assert(sizeof(lt::math::vec2_u64) == sizeof(u64) * num_elements);
};
Suite raii = "vec2_raii"_suite = [] {
Case { "happy paths" } = [] {
ignore = vec2 {};
ignore = vec2 { 2.0 };
ignore = vec2 { 2.0, 4.0 };
};
Case { "unhappy paths" } = [] {
};
Case { "many" } = [] {
for (auto idx : std::views::iota(0, 1'000'000))
{
ignore = idx;
ignore = vec2 {};
ignore = vec2 { 2.0 };
ignore = vec2 { 2.0, 4.0 };
}
};
Case { "post default construct has correct state" } = [] {
const auto vec = vec2 {};
expect_eq(vec.x, 0.0);
expect_eq(vec.y, 0.0);
};
Case { "post scalar construct has correct state" } = [] {
const auto vec = vec2 { 2.0 };
expect_eq(vec.x, 2.0);
expect_eq(vec.y, 2.0);
};
Case { "post construct with x,y has correct state" } = [] {
const auto vec = vec2 { 2.0, 3.0 };
expect_eq(vec.x, 2.0);
expect_eq(vec.y, 3.0);
};
};
Suite arithmetic_operators = "vec2_operators"_suite = [] {
Case { "operator ==" } = [] {
const auto lhs = vec2 { 1.0, 2.0 };
expect_false(lhs == vec2 { {}, 2.0 });
expect_false(lhs == vec2 { 1.0, {} });
expect_true(lhs == vec2 { 1.0, 2.0 });
};
Case { "operator !=" } = [] {
const auto lhs = vec2 { 1.0, 2.0 };
expect_true(lhs != vec2 { {}, 2.0 });
expect_true(lhs != vec2 { 1.0, {} });
expect_false(lhs != vec2 { 1.0, 2.0 });
};
Case { "operator +" } = [] {
const auto lhs = vec2 { 2.0, 3.0 };
const auto rhs = vec2 { 4.0, 5.0 };
expect_eq(lhs + rhs, vec2 { 6.0, 8.0 });
};
Case { "operator -" } = [] {
const auto lhs = vec2 { 2.0, 3.0 };
const auto rhs = vec2 { 4.0, 6.0 };
expect_eq(lhs - rhs, vec2 { -2.0, -3.0 });
};
Case { "operator *" } = [] {
const auto lhs = vec2 { 2.0, 3.0 };
const auto rhs = vec2 { 10.0, 20.0 };
expect_eq(lhs * rhs, vec2 { 20.0, 60.0 });
};
Case { "operator /" } = [] {
const auto lhs = vec2 { 10.0, 20.0 };
const auto rhs = vec2 { 2.0, 20.0 };
expect_eq(lhs / rhs, vec2 { 5.0, 1.0 });
};
Case { "operator []" } = [] {
auto vec = vec2 { 0.0, 1.0 };
expect_eq(vec[0], 0.0);
expect_eq(vec[1], 1.0);
};
Case { "operator [] const" } = [] {
const auto vec = vec2 { 0.0, 1.0 };
expect_eq(vec[0], 0.0);
expect_eq(vec[1], 1.0);
};
};
Suite utilities = "vec2_utilities"_suite = [] {
Case { "std::format float" } = [] {
auto str = std::format("{}", vec2 { 10.0000f, 30.0005f });
expect_eq(str, "10, 30.0005");
};
Case { "std::format int" } = [] {
auto str = std::format("{}", ivec2 { 10, 30 });
expect_eq(str, "10, 30");
};
};

View file

@ -1,18 +1,13 @@
export module math.vec3; export module math.vec3;
import preliminary;
import math.vec2; import math.vec2;
import std;
export namespace lt::math { namespace lt::math {
template<typename T = f32> export template<typename T = float>
requires(std::is_arithmetic_v<T>)
struct vec3_impl struct vec3_impl
{ {
using Underlying_T = T;
static constexpr auto num_elements = 3u;
constexpr vec3_impl(): x(), y(), z() constexpr vec3_impl(): x(), y(), z()
{ {
} }
@ -25,14 +20,6 @@ struct vec3_impl
{ {
} }
constexpr vec3_impl(vec2_impl<T> xy, T z): x(xy.x), y(xy.y), z(z)
{
}
constexpr vec3_impl(T x, vec2_impl<T> yz): x(x), y(yz.x), z(yz.y)
{
}
[[nodiscard]] auto operator==(const vec3_impl<T> &other) const -> bool [[nodiscard]] auto operator==(const vec3_impl<T> &other) const -> bool
{ {
return x == other.x && y == other.y && z == other.z; return x == other.x && y == other.y && z == other.z;
@ -43,15 +30,6 @@ struct vec3_impl
return !(*this == other); return !(*this == other);
} }
[[nodiscard]] constexpr auto operator+(const vec3_impl<T> &other) const -> vec3_impl
{
return {
x + other.x,
y + other.y,
z + other.z,
};
}
[[nodiscard]] constexpr auto operator-(const vec3_impl<T> &other) const -> vec3_impl [[nodiscard]] constexpr auto operator-(const vec3_impl<T> &other) const -> vec3_impl
{ {
return { return {
@ -70,58 +48,28 @@ struct vec3_impl
}; };
} }
[[nodiscard]] constexpr auto operator/(const vec3_impl<T> &other) const -> vec3_impl
{
return {
x / other.x,
y / other.y,
z / other.z,
};
}
[[nodiscard]] constexpr auto operator[](u8 idx) -> T &
{
debug_check(idx < num_elements, "vec3 out of bound access: {}", idx);
return ((T *)this)[idx];
}
[[nodiscard]] constexpr auto operator[](u8 idx) const -> const T &
{
debug_check(idx < num_elements, "vec3 out of bound access: {}", idx);
return ((T *)this)[idx];
}
friend auto operator<<(std::ostream &stream, vec3_impl<T> value) -> std::ostream & friend auto operator<<(std::ostream &stream, vec3_impl<T> value) -> std::ostream &
{ {
stream << value.x << ", " << value.y << ", " << value.z; stream << value.x << ", " << value.y << ", " << value.z;
return stream; return stream;
} }
T x; T x; // NOLINT
T y; T y; // NOLINT
T z; T z; // NOLINT
}; };
using vec3 = vec3_impl<f32>; export using vec3 = vec3_impl<float>;
using vec3_f32 = vec3; export using ivec3 = vec3_impl<std::int32_t>;
using vec3_f64 = vec3_impl<f64>;
using vec3_i8 = vec3_impl<i8>; export using uvec3 = vec3_impl<std::uint32_t>;
using vec3_i16 = vec3_impl<i16>;
using vec3_i32 = vec3_impl<i32>;
using vec3_i64 = vec3_impl<i64>;
using vec3_u8 = vec3_impl<u8>;
using vec3_u16 = vec3_impl<u16>;
using vec3_u32 = vec3_impl<u32>;
using vec3_u64 = vec3_impl<u64>;
} // namespace lt::math } // namespace lt::math
export template<typename T> template<typename T>
struct std::formatter<lt::math::vec3_impl<T>> struct std::formatter<lt::math::vec3_impl<T>>
{ {
constexpr auto parse(std::format_parse_context &context) constexpr auto parse(std::format_parse_context &context)

View file

@ -1,157 +0,0 @@
import test;
import math.vec2;
import math.vec3;
using vec2 = ::lt::math::vec2;
using vec3 = ::lt::math::vec3;
using ivec3 = ::lt::math::vec3_i32;
Suite static_tests = "vec3_static_checks"_suite = [] {
constexpr auto num_elements = lt::math::vec3::num_elements;
static_assert(num_elements == 3u);
static_assert(std::is_same_v<lt::math::vec3, lt::math::vec3_f32>);
static_assert(sizeof(lt::math::vec3_f32) == sizeof(f32) * num_elements);
static_assert(sizeof(lt::math::vec3_f64) == sizeof(f64) * num_elements);
static_assert(sizeof(lt::math::vec3_i8) == sizeof(i8) * num_elements);
static_assert(sizeof(lt::math::vec3_i16) == sizeof(i16) * num_elements);
static_assert(sizeof(lt::math::vec3_i32) == sizeof(i32) * num_elements);
static_assert(sizeof(lt::math::vec3_i64) == sizeof(i64) * num_elements);
static_assert(sizeof(lt::math::vec3_u8) == sizeof(u8) * num_elements);
static_assert(sizeof(lt::math::vec3_u16) == sizeof(u16) * num_elements);
static_assert(sizeof(lt::math::vec3_u32) == sizeof(u32) * num_elements);
static_assert(sizeof(lt::math::vec3_u64) == sizeof(u64) * num_elements);
};
Suite raii = "vec3_raii"_suite = [] {
Case { "happy paths" } = [] {
ignore = vec3 {};
ignore = vec3 { 2.0 };
ignore = vec3 { 2.0, 4.0, 6.0 };
ignore = vec3 { vec2 { 2.0, 4.0 }, 6.0 };
ignore = vec3 { 2.0, vec2 { 4.0, 6.0 } };
};
Case { "unhappy paths" } = [] {
};
Case { "many" } = [] {
for (auto idx : std::views::iota(0, 1'000'000))
{
ignore = idx;
ignore = vec3 {};
ignore = vec3 { 2.0 };
ignore = vec3 { 2.0, 4.0, 6.0 };
ignore = vec3 { vec2 { 2.0, 4.0 }, 6.0 };
ignore = vec3 { 2.0, vec2 { 4.0, 6.0 } };
}
};
Case { "post default construct has correct state" } = [] {
const auto vec = vec3 {};
expect_eq(vec.x, 0.0);
expect_eq(vec.y, 0.0);
expect_eq(vec.z, 0.0);
};
Case { "post scalar construct has correct state" } = [] {
const auto vec = vec3 { 2.0 };
expect_eq(vec.x, 2.0);
expect_eq(vec.y, 2.0);
expect_eq(vec.z, 2.0);
};
Case { "post construct with x,y,z has correct state" } = [] {
const auto vec = vec3 { 1.0, 2.0, 3.0 };
expect_eq(vec.x, 1.0);
expect_eq(vec.y, 2.0);
expect_eq(vec.y, 3.0);
};
Case { "post construct with xy,z has correct state" } = [] {
const auto vec = vec3 { vec2 { 1.0, 2.0 }, 3.0 };
expect_eq(vec.x, 1.0);
expect_eq(vec.y, 2.0);
expect_eq(vec.z, 3.0);
};
Case { "post construct with x,yz has correct state" } = [] {
const auto vec = vec3 { 1.0, vec2 { 2.0, 3.0 } };
expect_eq(vec.x, 1.0);
expect_eq(vec.y, 2.0);
expect_eq(vec.z, 3.0);
};
};
Suite arithmetic_operators = "vec3_operators"_suite = [] {
Case { "operator ==" } = [] {
const auto lhs = vec3 { 1.0, 2.0, 3.0 };
expect_false(lhs == vec3 { {}, 2.0, 3.0 });
expect_false(lhs == vec3 { 1.0, {}, 3.0 });
expect_false(lhs == vec3 { 1.0, 2.0, {} });
expect_true(lhs == vec3 { 1.0, 2.0, 3.0 });
};
Case { "operator !=" } = [] {
const auto lhs = vec3 { 1.0, 2.0, 3.0 };
expect_true(lhs != vec3 { {}, 2.0, 3.0 });
expect_true(lhs != vec3 { 1.0, {}, 3.0 });
expect_true(lhs != vec3 { 1.0, 2.0, {} });
expect_false(lhs != vec3 { 1.0, 2.0, 3.0 });
};
Case { "operator +" } = [] {
const auto lhs = vec3 { 1.0, 2.0, 3.0 };
const auto rhs = vec3 { 4.0, 5.0, 6.0 };
expect_eq(lhs + rhs, vec3 { 5.0, 7.0, 9.0 });
};
Case { "operator -" } = [] {
const auto lhs = vec3 { 1.0, 2.0, 3.0 };
const auto rhs = vec3 { 4.0, 5.0, 7.0 };
expect_eq(lhs - rhs, vec3 { -2.0, -3.0, -4.0 });
};
Case { "operator *" } = [] {
const auto lhs = vec3 { 1.0, 2.0, 3.0 };
const auto rhs = vec3 { 4.0, 5.0, 6.0 };
expect_eq(lhs * rhs, vec3 { 4.0, 10.0, 18.0 });
};
Case { "operator /" } = [] {
const auto lhs = vec3 { 4.0, 10.0, 30.0 };
const auto rhs = vec3 { 1.0, 2.0, 5.0 };
expect_eq(lhs / rhs, vec3 { 4.0, 5.0, 6.0 });
};
Case { "operator []" } = [] {
auto vec = vec3 { 0.0, 1.0, 2.0 };
expect_eq(vec[0], 0.0);
expect_eq(vec[1], 1.0);
expect_eq(vec[2], 2.0);
};
Case { "operator [] const" } = [] {
const auto vec = vec3 { 0.0, 1.0, 2.0 };
expect_eq(vec[0], 0.0);
expect_eq(vec[1], 1.0);
expect_eq(vec[2], 2.0);
};
};
Suite utilities = "vec3_utilities"_suite = [] {
Case { "std::format float" } = [] {
auto str = std::format("{}", vec3 { 10.0000f, 30.0005f, 40.00005f });
expect_eq(str, "10, 30.0005, 40.00005");
};
Case { "std::format int" } = [] {
auto str = std::format("{}", ivec3 { 10, 30, 3'000'000 });
expect_eq(str, "10, 30, 3000000");
};
};

View file

@ -1,19 +1,13 @@
export module math.vec4; export module math.vec4;
import preliminary;
import math.vec2; import math.vec2;
import math.vec3; import math.vec3;
import std;
export namespace lt::math { namespace lt::math {
template<typename T = f32> export template<typename T = float>
requires(std::is_arithmetic_v<T>)
struct vec4_impl struct vec4_impl
{ {
using Underlying_T = T;
static constexpr auto num_elements = 4u;
constexpr vec4_impl(): x(), y(), z(), w() constexpr vec4_impl(): x(), y(), z(), w()
{ {
} }
@ -26,30 +20,6 @@ struct vec4_impl
{ {
} }
constexpr vec4_impl(vec2_impl<T> xy, T z, T w): x(xy.x), y(xy.y), z(z), w(w)
{
}
constexpr vec4_impl(T x, vec2_impl<T> yz, T w): x(x), y(yz.x), z(yz.y), w(w)
{
}
constexpr vec4_impl(T x, T y, vec2_impl<T> zw): x(x), y(y), z(zw.x), w(zw.y)
{
}
constexpr vec4_impl(vec2_impl<T> xy, vec2_impl<T> zw): x(xy.x), y(xy.y), z(zw.x), w(zw.y)
{
}
constexpr vec4_impl(vec3_impl<T> xyz, T w): x(xyz.x), y(xyz.y), z(xyz.z), w(w)
{
}
constexpr vec4_impl(T x, vec3_impl<T> yzw): x(x), y(yzw.x), z(yzw.y), w(yzw.z)
{
}
[[nodiscard]] auto operator==(const vec4_impl<T> &other) const -> bool [[nodiscard]] auto operator==(const vec4_impl<T> &other) const -> bool
{ {
return x == other.x && y == other.y && z == other.z && w == other.w; return x == other.x && y == other.y && z == other.z && w == other.w;
@ -60,16 +30,6 @@ struct vec4_impl
return !(*this == other); return !(*this == other);
} }
[[nodiscard]] constexpr auto operator+(const vec4_impl<T> &other) const -> vec4_impl
{
return {
x + other.x,
y + other.y,
z + other.z,
w + other.w,
};
}
[[nodiscard]] constexpr auto operator-(const vec4_impl<T> &other) const -> vec4_impl [[nodiscard]] constexpr auto operator-(const vec4_impl<T> &other) const -> vec4_impl
{ {
return { return {
@ -80,36 +40,14 @@ struct vec4_impl
}; };
} }
[[nodiscard]] constexpr auto operator*(const vec4_impl<T> &other) const -> vec4_impl [[nodiscard]] constexpr auto operator[](std::size_t idx) -> T &
{ {
return { return values[idx];
x * other.x,
y * other.y,
z * other.z,
w * other.w,
};
} }
[[nodiscard]] constexpr auto operator/(const vec4_impl<T> &other) const -> vec4_impl [[nodiscard]] constexpr auto operator[](std::size_t idx) const -> const T &
{ {
return { return values[idx];
x / other.x,
y / other.y,
z / other.z,
w / other.w,
};
}
[[nodiscard]] constexpr auto operator[](u8 idx) -> T &
{
debug_check(idx < num_elements, "vec4 out of bound access: {}", idx);
return ((T *)this)[idx];
}
[[nodiscard]] constexpr auto operator[](u8 idx) const -> const T &
{
debug_check(idx < num_elements, "vec4 out of bound access: {}", idx);
return ((T *)this)[idx];
} }
friend auto operator<<(std::ostream &stream, vec4_impl<T> value) -> std::ostream & friend auto operator<<(std::ostream &stream, vec4_impl<T> value) -> std::ostream &
@ -118,6 +56,11 @@ struct vec4_impl
return stream; return stream;
} }
// NOLINTNEXTLINE
union
{
struct
{
T x; T x;
T y; T y;
@ -126,21 +69,28 @@ struct vec4_impl
T w; T w;
}; };
struct
{
T r;
using vec4 = vec4_impl<f32>; T g;
using vec4_f32 = vec4; T b;
using vec4_f64 = vec4_impl<f64>;
using vec4_i8 = vec4_impl<i8>; T a;
using vec4_i16 = vec4_impl<i16>; };
using vec4_i32 = vec4_impl<i32>; struct
using vec4_i64 = vec4_impl<i64>; {
std::array<T, 4> values;
};
};
};
using vec4_u8 = vec4_impl<u8>; export using vec4 = vec4_impl<float>;
using vec4_u16 = vec4_impl<u16>;
using vec4_u32 = vec4_impl<u32>; export using ivec4 = vec4_impl<std::int32_t>;
using vec4_u64 = vec4_impl<u64>;
export using uvec4 = vec4_impl<std::uint32_t>;
} // namespace lt::math } // namespace lt::math

View file

@ -1,215 +0,0 @@
import test;
import math.vec2;
import math.vec3;
import math.vec4;
import logger;
using vec2 = ::lt::math::vec2;
using vec3 = ::lt::math::vec3;
using vec4 = ::lt::math::vec4;
using ivec4 = ::lt::math::vec4_i32;
Suite static_tests = "vec4_static_checks"_suite = [] {
constexpr auto num_elements = lt::math::vec4::num_elements;
static_assert(num_elements == 4u);
static_assert(std::is_same_v<lt::math::vec4, lt::math::vec4_f32>);
static_assert(sizeof(lt::math::vec4_f32) == sizeof(f32) * num_elements);
static_assert(sizeof(lt::math::vec4_f64) == sizeof(f64) * num_elements);
static_assert(sizeof(lt::math::vec4_i8) == sizeof(i8) * num_elements);
static_assert(sizeof(lt::math::vec4_i16) == sizeof(i16) * num_elements);
static_assert(sizeof(lt::math::vec4_i32) == sizeof(i32) * num_elements);
static_assert(sizeof(lt::math::vec4_i64) == sizeof(i64) * num_elements);
static_assert(sizeof(lt::math::vec4_u8) == sizeof(u8) * num_elements);
static_assert(sizeof(lt::math::vec4_u16) == sizeof(u16) * num_elements);
static_assert(sizeof(lt::math::vec4_u32) == sizeof(u32) * num_elements);
static_assert(sizeof(lt::math::vec4_u64) == sizeof(u64) * num_elements);
};
Suite raii = "vec4_raii"_suite = [] {
Case { "happy paths" } = [] {
ignore = vec4 {};
ignore = vec4 { 2.0 };
ignore = vec4 { 2.0, 4.0, 6.0, 8.0 };
ignore = vec4 { vec2 { 2.0, 4.0 }, 6.0, 8.0 };
ignore = vec4 { 2.0, 4.0, vec2 { 6.0, 8.0 } };
ignore = vec4 { vec2 { 2.0, 4.0 }, vec2 { 6.0, 8.0 } };
ignore = vec4 { vec3 { 2.0, 4.0, 6.0 }, 8.0 };
ignore = vec4 { 2.0, vec3 { 4.0, 6.0, 8.0 } };
};
Case { "unhappy paths" } = [] {
};
Case { "many" } = [] {
for (auto idx : std::views::iota(0, 1'000'000))
{
ignore = idx;
ignore = vec4 {};
ignore = vec4 { 2.0 };
ignore = vec4 { 2.0, 4.0, 6.0, 8.0 };
ignore = vec4 { vec2 { 2.0, 4.0 }, 6.0, 8.0 };
ignore = vec4 { 2.0, 4.0, vec2 { 6.0, 8.0 } };
ignore = vec4 { vec2 { 2.0, 4.0 }, vec2 { 6.0, 8.0 } };
ignore = vec4 { vec3 { 2.0, 4.0, 6.0 }, 8.0 };
ignore = vec4 { 2.0, vec3 { 4.0, 6.0, 8.0 } };
}
};
Case { "post default construct has correct state" } = [] {
const auto vec = vec4 {};
expect_eq(vec.x, 0.0);
expect_eq(vec.y, 0.0);
expect_eq(vec.z, 0.0);
expect_eq(vec.w, 0.0);
};
Case { "post scalar construct has correct state" } = [] {
const auto vec = vec4 { 2.0 };
expect_eq(vec.x, 2.0);
expect_eq(vec.y, 2.0);
expect_eq(vec.z, 2.0);
expect_eq(vec.w, 2.0);
};
Case { "post construct with x,y,z,w has correct state" } = [] {
const auto vec = vec4 { 1.0, 2.0, 3.0, 4.0 };
expect_eq(vec.x, 1.0);
expect_eq(vec.y, 2.0);
expect_eq(vec.y, 3.0);
expect_eq(vec.z, 4.0);
};
Case { "post construct with xy,z,w has correct state" } = [] {
const auto vec = vec4 { vec2 { 1.0, 2.0 }, 3.0, 4.0 };
expect_eq(vec.x, 1.0);
expect_eq(vec.y, 2.0);
expect_eq(vec.z, 3.0);
expect_eq(vec.w, 4.0);
};
Case { "post construct with x,y,zw has correct state" } = [] {
const auto vec = vec4 { 1.0, 2.0, vec2 { 3.0, 4.0 } };
expect_eq(vec.x, 1.0);
expect_eq(vec.y, 2.0);
expect_eq(vec.z, 3.0);
expect_eq(vec.w, 4.0);
};
Case { "post construct with x,yz,w has correct state" } = [] {
const auto vec = vec4 { 1.0, vec2 { 2.0, 3.0 }, 4.0 };
expect_eq(vec.x, 1.0);
expect_eq(vec.y, 2.0);
expect_eq(vec.z, 3.0);
expect_eq(vec.w, 4.0);
};
Case { "post construct with x,y,zw has correct state" } = [] {
const auto vec = vec4 { 1.0, 2.0, vec2 { 3.0, 4.0 } };
expect_eq(vec.x, 1.0);
expect_eq(vec.y, 2.0);
expect_eq(vec.z, 3.0);
expect_eq(vec.w, 4.0);
};
Case { "post construct with xy,zw has correct state" } = [] {
const auto vec = vec4 { vec2 { 1.0, 2.0 }, vec2 { 3.0, 4.0 } };
expect_eq(vec.x, 1.0);
expect_eq(vec.y, 2.0);
expect_eq(vec.z, 3.0);
expect_eq(vec.w, 4.0);
};
Case { "post construct with xyz,w has correct state" } = [] {
const auto vec = vec4 { vec3 { 1.0, 2.0, 3.0 }, 4.0 };
expect_eq(vec.x, 1.0);
expect_eq(vec.y, 2.0);
expect_eq(vec.z, 3.0);
expect_eq(vec.w, 4.0);
};
Case { "post construct with x,yzw has correct state" } = [] {
const auto vec = vec4 { 1.0, vec3 { 2.0, 3.0, 4.0 } };
expect_eq(vec.x, 1.0);
expect_eq(vec.y, 2.0);
expect_eq(vec.z, 3.0);
expect_eq(vec.w, 4.0);
};
};
Suite arithmetic_operators = "vec4_operators"_suite = [] {
Case { "operator ==" } = [] {
const auto lhs = vec4 { 1.0, 2.0, 3.0, 4.0 };
expect_false(lhs == vec4 { {}, 2.0, 3.0, 4.0 });
expect_false(lhs == vec4 { 1.0, {}, 3.0, 4.0 });
expect_false(lhs == vec4 { 1.0, 2.0, {}, 4.0 });
expect_false(lhs == vec4 { 1.0, 2.0, 3.0, {} });
expect_true(lhs == vec4 { 1.0, 2.0, 3.0, 4.0 });
};
Case { "operator !=" } = [] {
const auto lhs = vec4 { 1.0, 2.0, 3.0, 4.0 };
expect_true(lhs != vec4 { {}, 2.0, 3.0, 4.0 });
expect_true(lhs != vec4 { 1.0, {}, 3.0, 4.0 });
expect_true(lhs != vec4 { 1.0, 2.0, {}, 4.0 });
expect_true(lhs != vec4 { 1.0, 2.0, 3.0, {} });
expect_false(lhs != vec4 { 1.0, 2.0, 3.0, 4.0 });
};
Case { "operator +" } = [] {
const auto lhs = vec4 { 1.0, 2.0, 3.0, 4.0 };
const auto rhs = vec4 { 5.0, 6.0, 7.0, 8.0 };
expect_eq(lhs + rhs, vec4 { 6.0, 8.0, 10.0, 12.0 });
};
Case { "operator -" } = [] {
const auto lhs = vec4 { 1.0, 2.0, 3.0, 4.0 };
const auto rhs = vec4 { 5.0, 10.0, 15.0, 20.0 };
expect_eq(lhs - rhs, vec4 { -4.0, -8.0, -12.0, -16.0 });
};
Case { "operator *" } = [] {
const auto lhs = vec4 { 1.0, 2.0, 3.0, 4.0 };
const auto rhs = vec4 { 5.0, 6.0, 7.0, 8.0 };
expect_eq(lhs * rhs, vec4 { 5.0, 12.0, 21.0, 32.0 });
};
Case { "operator /" } = [] {
const auto lhs = vec4 { 5.0, 6.0, 30.0, 8.0 };
const auto rhs = vec4 { 1.0, 2.0, 3.0, 4.0 };
expect_eq(lhs / rhs, vec4 { 5.0, 3.0, 10.0, 2.0 });
};
Case { "operator []" } = [] {
auto vec = vec4 { 0.0, 1.0, 2.0, 3.0 };
expect_eq(vec[0], 0.0);
expect_eq(vec[1], 1.0);
expect_eq(vec[2], 2.0);
expect_eq(vec[3], 3.0);
};
Case { "operator [] const" } = [] {
const auto vec = vec4 { 0.0, 1.0, 2.0, 3.0 };
expect_eq(vec[0], 0.0);
expect_eq(vec[1], 1.0);
expect_eq(vec[2], 2.0);
expect_eq(vec[3], 3.0);
};
};
Suite utilities = "vec4_utilities"_suite = [] {
Case { "std::format float" } = [] {
auto str = std::format("{}", vec4 { 10.0000f, 30.0005f, 40.00005f, 0.0 });
expect_eq(str, "10, 30.0005, 40.00005, 0");
};
Case { "std::format int" } = [] {
auto str = std::format("{}", ivec4 { 10, 30, 3'000'000, 13 });
expect_eq(str, "10, 30, 3000000, 13");
};
};

View file

@ -1,15 +1,13 @@
export module memory.null_on_move; export module memory.null_on_move;
import logger; import std;
import preliminary;
namespace lt::memory { namespace lt::memory {
/** Holds an `Underlying_T`, assigns it to `null_value` when this object is moved. /** Holds an `Underlying_T`, assigns it to `null_value` when this object is moved.
* *
* @note For avoiding the need to explicitly implement the move constructor for objects that hold * @note For avoiding the need to explicitly implement the move constructor for objects that hold
* non-raii-handles (eg. Vulkan, Wayland). * Vulkan handles. But may serve other purposes, hence why I kept the implementation generic.
*/ */
export template<typename Underlying_T, Underlying_T null_value = nullptr> export template<typename Underlying_T, Underlying_T null_value = nullptr>
class NullOnMove class NullOnMove
@ -81,6 +79,11 @@ public:
return m_value; return m_value;
} }
operator std::uint64_t() const
{
return (std::uint64_t)m_value;
}
[[nodiscard]] auto get() -> Underlying_T & [[nodiscard]] auto get() -> Underlying_T &
{ {
return m_value; return m_value;

View file

@ -1,6 +1,6 @@
export module memory.reference; export module memory.reference;
import preliminary; import std;
namespace lt::memory { namespace lt::memory {

View file

@ -1,6 +1,6 @@
export module memory.scope; export module memory.scope;
import preliminary; import std;
namespace lt::memory { namespace lt::memory {

View file

@ -7,12 +7,12 @@ import mirror.system;
import renderer.factory; import renderer.factory;
/** The ultimate entrypoint. */ /** The ultimate entrypoint. */
auto main(i32 argc, char *argv[]) -> i32 auto main(int argc, char *argv[]) -> std::int32_t
{ {
try try
{ {
ignore = argc; std::ignore = argc;
ignore = argv; std::ignore = argv;
auto application = lt::memory::create_scope<lt::Mirror>(); auto application = lt::memory::create_scope<lt::Mirror>();
if (!application) if (!application)

View file

@ -0,0 +1,227 @@
#pragma once
#include <app/layer.hpp>
#include <imgui.h>
#include <math/vec2.hpp>
#include <memory/reference.hpp>
#include <mirror/panels/asset_browser.hpp>
#include <mirror/panels/properties.hpp>
#include <mirror/panels/scene_hierarchy.hpp>
#include <renderer/texture.hpp>
namespace lt {
class Scene;
class EditorLayer: public Layer
{
public:
EditorLayer(const std::string &name);
~EditorLayer() override;
EditorLayer(EditorLayer &&) = delete;
EditorLayer(const EditorLayer &) = delete;
auto operator=(EditorLayer &&) const -> EditorLayer & = delete;
auto operator=(const EditorLayer &) const -> EditorLayer & = delete;
void on_update(float delta_time) override;
void on_render() override;
void on_user_interface_update() override;
private:
std::string m_scene_dir;
math::vec2 m_direction;
float m_speed = 1000.0f;
memory::Ref<Scene> m_scene;
memory::Ref<SceneHierarchyPanel> m_sceneHierarchyPanel;
memory::Ref<PropertiesPanel> m_properties_panel;
memory::Ref<AssetBrowserPanel> m_content_browser_panel;
memory::Ref<Framebuffer> m_framebuffer;
Entity m_camera_entity;
ImVec2 m_available_content_region_prev;
};
} // namespace lt
#include <app/application.hpp>
#include <asset_manager/asset_manager.hpp>
#include <camera/component.hpp>
#include <ecs/components.hpp>
#include <ecs/registry.hpp>
#include <ecs/serializer.hpp>
#include <input/input.hpp>
#include <input/key_codes.hpp>
#include <math/vec4.hpp>
#include <memory/reference.hpp>
#include <mirror/layers/editor_layer.hpp>
#include <renderer/framebuffer.hpp>
#include <renderer/texture.hpp>
#include <ui/ui.hpp>
namespace lt {
EditorLayer::EditorLayer(const std::string &name)
: Layer(name)
, m_scene_dir("")
, m_direction { 0.0, 0.0 }
{
m_scene = memory::create_ref<Scene>();
m_properties_panel = memory::create_ref<PropertiesPanel>();
m_sceneHierarchyPanel = memory::create_ref<SceneHierarchyPanel>(m_scene, m_properties_panel);
m_content_browser_panel = memory::create_ref<AssetBrowserPanel>(m_scene);
m_framebuffer = Framebuffer::create(
{
.width = 1,
.height = 1,
.samples = 1,
},
GraphicsContext::get_shared_context()
);
if (m_scene_dir.empty())
{
m_camera_entity = m_scene->create_entity("Camera");
m_camera_entity.add_component<CameraComponent>(SceneCamera(), true);
AssetManager::load_texture("Awesomeface", "data/assets/textures/awesomeface.asset");
auto entity = Entity { m_scene->create_entity("Awesomeface", {}) };
entity.add_component<SpriteRendererComponent>(
AssetManager::get_texture("Awesomeface"),
math::vec4 { 0.0f, 1.0f, 1.0f, 1.0f }
);
}
else
{
auto serializer = SceneSerializer { m_scene };
ensure(serializer.deserialize(m_scene_dir), "Failed to de-serialize: {}", m_scene_dir);
// m_camera_entity = m_scene->GetEntityByTag("Game Camera");
}
}
EditorLayer::~EditorLayer()
{
if (!m_scene_dir.empty())
{
auto serializer = SceneSerializer { m_scene };
serializer.serialize(m_scene_dir);
}
}
void EditorLayer::on_update(float delta_time)
{
m_scene->on_update(delta_time);
if (Input::get_keyboard_key(Key::A))
{
m_direction.x = -1.0;
}
else if (Input::get_keyboard_key(Key::D))
{
m_direction.x = 1.0f;
}
else
{
m_direction.x = 0.0;
}
if (Input::get_keyboard_key(Key::S))
{
m_direction.y = -1.0;
}
else if (Input::get_keyboard_key(Key::W))
{
m_direction.y = 1.0f;
}
else
{
m_direction.y = 0.0;
}
auto &translation = m_camera_entity.get_component<TransformComponent>().translation;
auto velocity = m_direction * m_speed * delta_time;
translation = translation * math::vec3 { velocity.x, velocity.y, 0.0f };
if (Input::get_keyboard_key(Key::Escape))
{
Application::quit();
}
}
void EditorLayer::on_render()
{
m_scene->on_render(m_framebuffer);
}
void EditorLayer::on_user_interface_update()
{
UserInterface::dockspace_begin();
ImGui::ShowDemoWindow();
if (ImGui::Begin("Game"))
{
Input::receive_game_events(ImGui::IsWindowFocused());
auto available_region = ImGui::GetContentRegionAvail();
if (m_available_content_region_prev.x != available_region.x
|| m_available_content_region_prev.y != available_region.y)
{
m_framebuffer->resize(
math::uvec2 {
static_cast<uint32_t>(available_region.x),
static_cast<uint32_t>(available_region.y),
}
);
auto &camera = m_camera_entity.get_component<CameraComponent>().camera;
camera.set_viewport_size(
static_cast<uint32_t>(available_region.x),
static_cast<uint32_t>(available_region.y)
);
m_available_content_region_prev = available_region;
}
if (GraphicsContext::get_graphics_api() == GraphicsAPI::DirectX)
{
ImGui::Image(m_framebuffer->get_color_attachment(), available_region);
}
else
{
ImGui::Image(
m_framebuffer->get_color_attachment(),
available_region,
ImVec2(0, 1),
ImVec2(1, 0)
);
}
}
ImGui::End();
// Panels
m_sceneHierarchyPanel->on_user_interface_update();
m_properties_panel->on_user_interface_update();
m_content_browser_panel->on_user_interface_update();
UserInterface::dockspace_end();
}
} // namespace lt

View file

@ -0,0 +1,200 @@
#pragma once
#include <filesystem>
#include <memory/reference.hpp>
#include <mirror/panels/panel.hpp>
#include <renderer/texture.hpp>
namespace lt {
class Scene;
class AssetBrowserPanel: public Panel
{
public:
AssetBrowserPanel(memory::Ref<Scene> active_scene);
void on_user_interface_update();
private:
enum class AssetType
{
none = 0,
scene,
directory,
text,
image,
};
std::filesystem::path m_current_directory;
const std::filesystem::path m_assets_path;
float m_file_size = 128.0f;
float m_file_padding = 8.0f;
memory::Ref<Scene> m_active_scene;
memory::Ref<Texture> m_directory_texture;
memory::Ref<Texture> m_scene_texture;
memory::Ref<Texture> m_image_texture;
memory::Ref<Texture> m_text_texture;
};
} // namespace lt
#include <asset_manager/asset_manager.hpp>
#include <ecs/registry.hpp>
#include <ecs/serializer.hpp>
#include <imgui.h>
#include <memory/reference.hpp>
#include <mirror/panels/asset_browser.hpp>
#include <renderer/texture.hpp>
namespace lt {
AssetBrowserPanel::AssetBrowserPanel(memory::Ref<Scene> active_scene)
: m_current_directory("./data/assets")
, m_assets_path("./data/assets")
, m_active_scene(std::move(active_scene))
{
AssetManager::load_texture("_Assets_Directory", "data/engine/icons/asset/dir.asset");
AssetManager::load_texture("_Assets_Scene", "data/engine/icons/asset/scene.asset");
AssetManager::load_texture("_Assets_Image", "data/engine/icons/asset/img.asset");
AssetManager::load_texture("_Assets_Text", "data/engine/icons/asset/txt.asset");
m_directory_texture = AssetManager::get_texture("_Assets_Directory");
m_scene_texture = AssetManager::get_texture("_Assets_Scene");
m_image_texture = AssetManager::get_texture("_Assets_Image");
m_text_texture = AssetManager::get_texture("_Assets_Text");
}
void AssetBrowserPanel::on_user_interface_update()
{
ImGui::Begin("Content Browser");
// Parent directory button
if (m_current_directory != std::filesystem::path("data/assets"))
{
if (ImGui::Button(" <-- "))
{
m_current_directory = m_current_directory.parent_path();
}
}
const auto available_region = ImGui::GetContentRegionAvail();
const auto cell_size = m_file_size + m_file_padding;
const auto column_count = std::clamp(
static_cast<uint32_t>(std::floor(available_region.x / cell_size)),
1u,
64u
);
if (ImGui::BeginTable("ContentBrowser", static_cast<int>(column_count)))
{
m_directory_texture->bind(0u);
for (const auto &directory_entry : std::filesystem::directory_iterator(m_current_directory))
{
const auto &path = directory_entry.path();
auto extension = directory_entry.path().extension().string();
auto asset_type = AssetType {};
if (extension.empty())
{
asset_type = AssetType::directory;
}
else if (extension == ".txt" || extension == ".glsl")
{
asset_type = AssetType::text;
}
else if (extension == ".png")
{
asset_type = AssetType::image;
}
else if (extension == ".scene")
{
asset_type = AssetType::scene;
}
else
{
asset_type = AssetType::none;
}
// Extension not supported
if (asset_type == AssetType::none)
{
continue;
}
// Button
const auto path_str = path.string();
ImGui::TableNextColumn();
ImGui::PushID(path_str.c_str());
switch (asset_type)
{
// Directory
case AssetType::directory:
if (ImGui::ImageButton(
path_str.c_str(),
m_directory_texture->get_texture(),
ImVec2(m_file_size, m_file_size)
))
{
m_current_directory /= path.filename();
}
break;
// Scene
case AssetType::scene:
if (ImGui::ImageButton(
path_str.c_str(),
m_scene_texture->get_texture(),
ImVec2(m_file_size, m_file_size)
))
{
auto serializer = SceneSerializer { m_active_scene };
log::info("Attempting to deserialize: {}", path.string());
serializer.deserialize(path.string());
}
break;
// Image
case AssetType::image:
if (ImGui::ImageButton(
path_str.c_str(),
m_image_texture->get_texture(),
ImVec2(m_file_size, m_file_size)
))
{
}
break;
// Text
case AssetType::text:
if (ImGui::ImageButton(
path_str.c_str(),
m_text_texture->get_texture(),
ImVec2(m_file_size, m_file_size)
))
{
}
break;
default: break;
}
// Label
ImGui::TextUnformatted(std::format("{}", path.filename().string()).c_str());
ImGui::PopID();
}
ImGui::EndTable();
}
ImGui::End();
}
} // namespace lt

View file

@ -0,0 +1,13 @@
#pragma once
namespace lt {
class Panel
{
public:
Panel() = default;
virtual ~Panel() = default;
};
} // namespace lt

View file

@ -0,0 +1,345 @@
#pragma once
#include <ecs/entity.hpp>
#include <math/vec3.hpp>
#include <mirror/panels/panel.hpp>
namespace lt {
class PropertiesPanel: public Panel
{
public:
PropertiesPanel() = default;
void on_user_interface_update();
void set_entity_context(const Entity &entity);
private:
void draw_vec3_control(
const std::string &label,
math::vec3 &values,
float reset_value = 0.0f,
float column_width = 100.0f
);
template<typename ComponentType, typename UIFunction>
void draw_component(const std::string &name, Entity entity, UIFunction function);
Entity m_entity_context;
};
} // namespace lt
#include <asset_manager/asset_manager.hpp>
#include <camera/component.hpp>
#include <ecs/components.hpp>
#include <imgui.h>
#include <imgui_internal.h>
#include <math/trig.hpp>
#include <mirror/panels/properties.hpp>
namespace lt {
void PropertiesPanel::on_user_interface_update()
{
ImGui::Begin("Properties");
if (m_entity_context.is_valid())
{
if (m_entity_context.has_component<TagComponent>())
{
auto &tagComponent = m_entity_context.get_component<TagComponent>();
auto buffer = std::array<char, 256> {};
memset(buffer.data(), 0, buffer.size());
strncpy(buffer.data(), tagComponent.tag.c_str(), buffer.size());
if (ImGui::InputText("##Tag", buffer.data(), buffer.size()))
{
tagComponent.tag = buffer.data();
}
}
ImGui::SameLine();
ImGui::PushItemWidth(-1);
if (ImGui::Button("Add component"))
{
ImGui::OpenPopup("Components");
}
if (ImGui::BeginPopup("Components"))
{
if (ImGui::Selectable(
"SpriteRenderer",
false,
m_entity_context.has_component<SpriteRendererComponent>() ?
ImGuiSelectableFlags_Disabled :
ImGuiSelectableFlags {}
))
{
m_entity_context.add_component<SpriteRendererComponent>(
lt::AssetManager::get_texture("awesomeface")
);
}
if (ImGui::Selectable(
"Camera",
false,
m_entity_context.has_component<CameraComponent>() ?
ImGuiSelectableFlags_Disabled :
ImGuiSelectableFlags {}
))
{
m_entity_context.add_component<CameraComponent>();
}
ImGui::EndPopup();
}
ImGui::PopItemWidth();
draw_component<TransformComponent>(
"Transform Component",
m_entity_context,
[&](auto &transformComponent) {
draw_vec3_control("Translation", transformComponent.translation);
}
);
draw_component<SpriteRendererComponent>(
"SpriteRenderer Component",
m_entity_context,
[&](auto &spriteRendererComponent) {
ImGui::ColorEdit4("Color", &spriteRendererComponent.tint[0]);
}
);
draw_component<CameraComponent>(
"Camera Component",
m_entity_context,
[&](auto &cameraComponent) {
auto &camera = cameraComponent.camera;
auto projection_type = camera.get_projection_type();
auto projection_types_str = std::array<const char *, 2> {
"Orthographic",
"Perspective",
};
if (ImGui::BeginCombo("ProjectionType", projection_types_str[(int)projection_type]))
{
for (auto idx = 0; idx < 2; idx++)
{
const auto is_selected = static_cast<int>(projection_type) == idx;
if (ImGui::Selectable(projection_types_str[idx], is_selected))
{
projection_type = static_cast<SceneCamera::ProjectionType>(idx);
camera.set_projection_type(projection_type);
}
if (is_selected)
{
ImGui::SetItemDefaultFocus();
}
}
ImGui::EndCombo();
}
if (projection_type == SceneCamera::ProjectionType::Orthographic)
{
auto ortho_size = float {};
auto near_plane = float {};
auto far_plane = float {};
ortho_size = camera.get_orthographic_size();
near_plane = camera.get_orthographic_near_plane();
far_plane = camera.get_orthographic_far_plane();
if (ImGui::DragFloat("Orthographic Size", &ortho_size))
{
camera.set_orthographic_size(ortho_size);
}
if (ImGui::DragFloat("Near Plane", &near_plane))
{
camera.set_orthographic_near_plane(near_plane);
}
if (ImGui::DragFloat("Far Plane", &far_plane))
{
camera.set_orthographic_far_plane(far_plane);
}
}
else // perspective
{
auto vertical_fov = float {};
auto near_plane = float {};
auto far_plane = float {};
vertical_fov = math::degrees(camera.get_perspective_vertical_fov());
near_plane = camera.get_perspective_near_plane();
far_plane = camera.get_perspective_far_plane();
if (ImGui::DragFloat("Vertical FOV", &vertical_fov))
{
camera.set_perspective_vertical_fov(math::radians(vertical_fov));
}
if (ImGui::DragFloat("Near Plane", &near_plane))
{
camera.set_perspective_near_plane(near_plane);
}
if (ImGui::DragFloat("Far Plane", &far_plane))
{
camera.set_perspective_far_plane(far_plane);
}
}
ImGui::Separator();
}
);
}
ImGui::End();
}
void PropertiesPanel::set_entity_context(const Entity &entity)
{
m_entity_context = entity;
}
void PropertiesPanel::draw_vec3_control(
const std::string &label,
math::vec3 &values,
float reset_value,
float column_width
)
{
auto &io = ImGui::GetIO();
auto *bold_font = io.Fonts->Fonts[0];
ImGui::Columns(2);
ImGui::SetColumnWidth(0, column_width);
ImGui::TextUnformatted(label.c_str());
ImGui::NextColumn();
ImGui::PushMultiItemsWidths(3, ImGui::CalcItemWidth());
ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2 { 0, 0 });
auto line_height = GImGui->Font->LegacySize + GImGui->Style.FramePadding.y * 2.0f;
auto button_size = ImVec2 { line_height + 3.0f, line_height };
ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.8f, 0.1f, 0.15f, 1.0f));
ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(0.9f, 0.2f, 0.2f, 1.0f));
ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4(0.8f, 0.1f, 0.15f, 1.0f));
ImGui::PushFont(bold_font);
if (ImGui::Button("X", button_size))
{
values.x = reset_value;
}
ImGui::PopFont();
ImGui::PopStyleColor(3);
ImGui::SameLine();
ImGui::DragFloat("##X", &values.x, 0.1f);
ImGui::PopItemWidth();
ImGui::SameLine();
ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.2f, 0.7f, 0.2f, 1.0f));
ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(0.3f, 0.8f, 0.3f, 1.0f));
ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4(0.2f, 0.7f, 0.2f, 1.0f));
ImGui::PushFont(bold_font);
if (ImGui::Button("Y", button_size))
{
values.y = reset_value;
}
ImGui::PopFont();
ImGui::PopStyleColor(3);
ImGui::SameLine();
ImGui::DragFloat("##Y", &values.y, 0.1f);
ImGui::PopItemWidth();
ImGui::SameLine();
ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.1f, 0.25f, 0.8f, 1.0f));
ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(0.2f, 0.35f, 0.9f, 1.0f));
ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4(0.1f, 0.25f, 0.8f, 1.0f));
ImGui::PushFont(bold_font);
if (ImGui::Button("Z", button_size))
{
values.z = reset_value;
}
ImGui::PopFont();
ImGui::PopStyleColor(3);
ImGui::SameLine();
ImGui::DragFloat("##Z", &values.z, 0.1f);
ImGui::PopItemWidth();
ImGui::PopStyleVar();
ImGui::Columns(1);
}
template<typename ComponentType, typename UIFunction>
void PropertiesPanel::draw_component(
const std::string &name,
Entity entity,
UIFunction user_interface_function
)
{
if (!entity.has_component<ComponentType>())
{
return;
}
auto &component = entity.get_component<ComponentType>();
auto available_region = ImGui::GetContentRegionAvail();
// NOLINTNEXTLINE
auto flags = ImGuiTreeNodeFlags_DefaultOpen | ImGuiTreeNodeFlags_SpanAvailWidth
| ImGuiTreeNodeFlags_Framed | ImGuiTreeNodeFlags_AllowItemOverlap
| ImGuiTreeNodeFlags_FramePadding;
ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, { 4, 4 });
auto lineHeight = GImGui->Font->LegacySize + GImGui->Style.FramePadding.y * 2.0f;
ImGui::Separator();
// NOLINTNEXTLINE
if (ImGui::TreeNodeEx((void *)typeid(ComponentType).hash_code(), flags, name.c_str()))
{
ImGui::PopStyleVar();
ImGui::SameLine(available_region.x - lineHeight * .5f);
if (ImGui::Button("+", { lineHeight, lineHeight }))
{
ImGui::OpenPopup("ComponentSettings");
}
if (ImGui::BeginPopup("ComponentSettings"))
{
if (ImGui::Selectable("Remove component"))
{
entity.remove_component<ComponentType>();
}
ImGui::EndPopup();
}
user_interface_function(component);
ImGui::TreePop();
}
else
{
ImGui::PopStyleVar();
}
}
} // namespace lt

View file

@ -0,0 +1,124 @@
#pragma once
#include <ecs/entity.hpp>
#include <ecs/registry.hpp>
#include <memory/reference.hpp>
#include <mirror/panels/panel.hpp>
namespace lt {
class PropertiesPanel;
class SceneHierarchyPanel: public Panel
{
public:
SceneHierarchyPanel();
SceneHierarchyPanel(
memory::Ref<Scene> context,
memory::Ref<PropertiesPanel> properties_panel = nullptr
);
void on_user_interface_update();
void set_context(
memory::Ref<Scene> context,
memory::Ref<PropertiesPanel> properties_panel = nullptr
);
private:
void draw_node(Entity entity, const std::string &label);
memory::Ref<Scene> m_context;
memory::Ref<PropertiesPanel> m_properties_panel_context;
Entity m_selection_context;
};
} // namespace lt
#include <ecs/components.hpp>
#include <imgui.h>
#include <memory/reference.hpp>
#include <mirror/panels/properties.hpp>
#include <mirror/panels/scene_hierarchy.hpp>
namespace lt {
SceneHierarchyPanel::SceneHierarchyPanel(): m_context(nullptr), m_properties_panel_context(nullptr)
{
}
SceneHierarchyPanel::SceneHierarchyPanel(
memory::Ref<Scene> context,
memory::Ref<PropertiesPanel> properties_panel
)
: m_context(std::move(context))
, m_properties_panel_context(std::move(properties_panel))
{
}
void SceneHierarchyPanel::on_user_interface_update()
{
if (m_context)
{
ImGui::Begin("Hierarchy");
for (auto entityID : m_context->m_registry.view<TagComponent>())
{
auto entity = Entity {
static_cast<entt::entity>(entityID),
m_context.get(),
};
const auto &tag = entity.get_component<TagComponent>();
draw_node(entity, tag);
};
}
ImGui::End();
}
void SceneHierarchyPanel::set_context(
memory::Ref<Scene> context,
memory::Ref<PropertiesPanel> properties_panel
)
{
if (properties_panel)
{
m_properties_panel_context = std::move(properties_panel);
}
m_context = std::move(context);
}
void SceneHierarchyPanel::draw_node(Entity entity, const std::string &label)
{
auto flags = ImGuiTreeNodeFlags {
// NOLINTNEXTLINE
(m_selection_context == entity ? ImGuiTreeNodeFlags_Selected : ImGuiTreeNodeFlags {})
| ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_SpanFullWidth
};
// NOLINTNEXTLINE
const auto expanded = ImGui::TreeNodeEx(
std::bit_cast<void *>(static_cast<uint64_t>(entity)),
flags,
"%s",
label.c_str()
);
if (ImGui::IsItemClicked())
{
m_selection_context = entity;
m_properties_panel_context->set_entity_context(entity);
}
if (expanded)
{
ImGui::TextUnformatted("TEST_OPENED_TREE!");
ImGui::TreePop();
}
}
} // namespace lt

View file

@ -1,6 +1,4 @@
export module mirror.system; export module mirror.system;
import preliminary;
import math.vec3; import math.vec3;
import camera.components; import camera.components;
import surface.requests; import surface.requests;
@ -24,6 +22,7 @@ import app;
import app.system; import app.system;
import ecs.entity; import ecs.entity;
import ecs.registry; import ecs.registry;
import std;
namespace lt { namespace lt {
@ -34,11 +33,11 @@ void renderer_callback(
std::any &user_data std::any &user_data
) )
{ {
ignore = message_severity; std::ignore = message_severity;
ignore = message_type; std::ignore = message_type;
ignore = user_data; std::ignore = user_data;
log::trace("< Renderer > ==> {}", std::string { data.message }); log::debug("RENDERER CALLBACK: {}", std::string { data.message });
} }
class MirrorSystem: public lt::app::ISystem class MirrorSystem: public lt::app::ISystem
@ -46,8 +45,8 @@ class MirrorSystem: public lt::app::ISystem
public: public:
MirrorSystem( MirrorSystem(
memory::Ref<ecs::Registry> registry, memory::Ref<ecs::Registry> registry,
size_t quit_action_key, std::size_t quit_action_key,
std::array<size_t, 4ul> debug_action_keys std::array<std::size_t, 4ul> debug_action_keys
) )
: m_registry(std::move(registry)) : m_registry(std::move(registry))
, m_quit_action_key(quit_action_key) , m_quit_action_key(quit_action_key)
@ -85,7 +84,7 @@ public:
for (auto &[id, camera] : for (auto &[id, camera] :
m_registry->view<lt::camera::components::PerspectiveCamera>()) m_registry->view<lt::camera::components::PerspectiveCamera>())
{ {
camera.vertical_fov += (static_cast<f32>(tick.delta_time.count()) * 40.0f); camera.vertical_fov += (static_cast<float>(tick.delta_time.count()) * 40.0f);
} }
} }
@ -129,9 +128,9 @@ public:
private: private:
memory::Ref<ecs::Registry> m_registry; memory::Ref<ecs::Registry> m_registry;
size_t m_quit_action_key; std::size_t m_quit_action_key;
std::array<size_t, 4ul> m_debug_action_keys {}; std::array<std::size_t, 4ul> m_debug_action_keys {};
app::TickResult m_last_tick_result {}; app::TickResult m_last_tick_result {};
}; };
@ -177,41 +176,31 @@ public:
); );
auto &input = m_editor_registry->add<InputComponent>(m_window, {}); auto &input = m_editor_registry->add<InputComponent>(m_window, {});
auto quit_action_key = input.add_action( auto quit_action_key = input.add_action(input::InputAction {
input::InputAction {
.name = "quit", .name = "quit",
.trigger = input::Trigger { .mapped_keycode = Key::q }, .trigger = input::Trigger { .mapped_keycode = Key::Q },
} });
);
auto debug_action_keys = std::array<size_t, 4ul> {}; auto debug_action_keys = std::array<std::size_t, 4ul> {};
debug_action_keys[0] = input.add_action( debug_action_keys[0] = input.add_action(input::InputAction {
input::InputAction {
.name = "debug_1", .name = "debug_1",
.trigger = input::Trigger { .mapped_keycode = Key::digit_1 }, .trigger = input::Trigger { .mapped_keycode = Key::D1 },
} });
);
debug_action_keys[1] = input.add_action( debug_action_keys[1] = input.add_action(input::InputAction {
input::InputAction {
.name = "debug_2", .name = "debug_2",
.trigger = input::Trigger { .mapped_keycode = Key::digit_2 }, .trigger = input::Trigger { .mapped_keycode = Key::D2 },
} });
);
debug_action_keys[2] = input.add_action( debug_action_keys[2] = input.add_action(input::InputAction {
input::InputAction {
.name = "debug_3", .name = "debug_3",
.trigger = input::Trigger { .mapped_keycode = Key::digit_3 }, .trigger = input::Trigger { .mapped_keycode = Key::D3 },
} });
);
debug_action_keys[3] = input.add_action( debug_action_keys[3] = input.add_action(input::InputAction {
input::InputAction {
.name = "debug_4", .name = "debug_4",
.trigger = input::Trigger { .mapped_keycode = Key::digit_4 }, .trigger = input::Trigger { .mapped_keycode = Key::D4 },
} });
);
m_input_system = memory::create_ref<input::System>(m_editor_registry); m_input_system = memory::create_ref<input::System>(m_editor_registry);
m_mirror_system = memory::create_ref<MirrorSystem>( m_mirror_system = memory::create_ref<MirrorSystem>(
@ -255,7 +244,7 @@ public:
m_editor_registry->add( m_editor_registry->add(
m_camera_id, m_camera_id,
camera::components::PerspectiveCamera { camera::components::PerspectiveCamera {
.vertical_fov = math::to_radians(90.0f), .vertical_fov = math::radians(90.0f),
.near_plane = 0.1f, .near_plane = 0.1f,
.far_plane = 30.0, .far_plane = 30.0,
.aspect_ratio = 1.0f, .aspect_ratio = 1.0f,

View file

View file

@ -1,85 +0,0 @@
export module preliminary.assertions;
import preliminary.build_constants;
import std;
///////////////////////////////////////
// ----------* INTERFACE *--------- //
/////////////////////////////////////
/** To be used for ensuring a condition holds true, throws otherwise. */
export template<typename Expression_T, typename... Args_T>
struct ensure
{
ensure(
const Expression_T &expression,
std::format_string<Args_T...> fmt,
Args_T &&...args,
const std::source_location &location = std::source_location::current()
);
};
/** To be used for costly checks that should be stripped in release builds. */
export template<typename Expression_T, typename... Args_T>
struct debug_check
{
debug_check(
const Expression_T &expression,
std::format_string<Args_T...> fmt,
Args_T &&...args,
const std::source_location &location = std::source_location::current()
);
};
export template<typename Expression_T, typename... Args_T>
ensure(Expression_T, std::format_string<Args_T...>, Args_T &&...)
-> ensure<Expression_T, Args_T...>;
export template<typename Expression_T, typename... Args_T>
debug_check(Expression_T, std::format_string<Args_T...>, Args_T &&...)
-> debug_check<Expression_T, Args_T...>;
///////////////////////////////////////
// * IMPLEMENTATION -- TEMPLATES * //
/////////////////////////////////////
template<typename Expression_T, typename... Args_T>
ensure<Expression_T, Args_T...>::ensure(
const Expression_T &expression,
std::format_string<Args_T...> fmt,
Args_T &&...args,
const std::source_location &location
)
{
if (!static_cast<bool>(expression))
{
throw std::runtime_error { std::format(
"exception: {}\nlocation: {}:{}",
std::format(fmt, std::forward<Args_T>(args)...),
location.file_name(),
location.line()
) };
}
}
template<typename Expression_T, typename... Args_T>
debug_check<Expression_T, Args_T...>::debug_check(
const Expression_T &expression,
std::format_string<Args_T...> fmt,
Args_T &&...args,
const std::source_location &location
)
{
if constexpr (build_constants::build_type != build_constants::BuildType::debug)
{
return;
}
if (!static_cast<bool>(expression))
{
throw std::runtime_error { std::format(
"exception: {}\nlocation: {}:{}",
std::format(fmt, std::forward<Args_T>(args)...),
location.file_name(),
location.line()
) };
}
}

View file

@ -1,22 +0,0 @@
export module preliminary.fundumental_types;
import std;
export using byte = ::std::byte;
export using u8 = ::std::uint8_t;
export using u16 = ::std::uint16_t;
export using u32 = ::std::uint32_t;
export using u64 = ::std::uint64_t;
export using i8 = ::std::int8_t;
export using i16 = ::std::int16_t;
export using i32 = ::std::int32_t;
export using i64 = ::std::int64_t;
export using f32 = float;
export using f64 = double;
export using size_t = ::std::size_t;
export using ::std::ignore;

View file

@ -1,7 +0,0 @@
export module preliminary;
export import preliminary.fundumental_types;
export import preliminary.assertions;
export import preliminary.build_constants;
// std should always be available...
export import std;

View file

@ -3,22 +3,118 @@ import renderer.test_utils;
using enum ::lt::renderer::IDebugger::MessageSeverity; using enum ::lt::renderer::IDebugger::MessageSeverity;
using enum ::lt::renderer::IBuffer::Usage; using enum ::lt::renderer::IBuffer::Usage;
using ::std::this_thread::sleep_for;
// TODO(Light): finish these (and many other) tests...
Suite raii = "buffer_raii"_suite = [] { Suite raii = "buffer_raii"_suite = [] {
Case { "happy paths" } = [] { Case { "happy path won't throw" } = [] {
auto fixture = FixtureDeviceSwapchain {}; auto fixture = FixtureDeviceSwapchain {};
};
sleep_for(std::chrono::milliseconds { 500u });
Case { "unhappy paths" } = [] { for (auto idx = 0; idx <= std::to_underlying(staging); ++idx)
{
ignore = lt::renderer::create_buffer(
lt::renderer::Api::vulkan,
fixture.device(),
fixture.gpu(),
lt::renderer::IBuffer::CreateInfo {
.usage = static_cast<lt::renderer::IBuffer::Usage>(idx),
.size = 1000u,
.debug_name = "",
}
);
}
expect_false(fixture.has_any_messages_of(error));
expect_false(fixture.has_any_messages_of(warning));
};
Case { "unhappy path throws" } = [] {
auto fixture = FixtureDeviceSwapchain {}; auto fixture = FixtureDeviceSwapchain {};
};
sleep_for(std::chrono::milliseconds { 500u });
auto info = lt::renderer::IBuffer::CreateInfo {
.usage = vertex,
.size = 10000u,
.debug_name = "",
};
expect_throw([&] {
ignore = lt::renderer::create_buffer(
lt::renderer::Api::vulkan,
nullptr,
fixture.gpu(),
info
);
});
expect_throw([&] {
ignore = lt::renderer::create_buffer(lt::renderer::Api::vulkan, fixture.device(), nullptr, info);
});
expect_throw([&, info] mutable {
info.size = 0;
ignore = lt::renderer::create_buffer(
lt::renderer::Api::vulkan,
fixture.device(),
fixture.gpu(),
info
);
});
expect_throw([&] {
ignore = lt::renderer::create_buffer(
lt::renderer::Api::direct_x,
fixture.device(),
fixture.gpu(),
info
);
});
expect_throw([&] {
ignore = lt::renderer::create_buffer(
lt::renderer::Api::metal,
fixture.device(),
fixture.gpu(),
info
);
});
expect_throw([&] {
ignore = lt::renderer::create_buffer(
lt::renderer::Api::none,
fixture.device(),
fixture.gpu(),
info
);
});
/** Make sure the default-case was OK */
ignore = lt::renderer::create_buffer(lt::renderer::Api::vulkan, fixture.device(), fixture.gpu(), info);
expect_false(fixture.has_any_messages_of(error));
expect_false(fixture.has_any_messages_of(warning));
};
};
Suite mapping = "buffer_mapping"_suite = [] {
Case { "mapping" } = [] { Case { "mapping" } = [] {
auto fixture = FixtureDeviceSwapchain {}; auto fixture = FixtureDeviceSwapchain {};
constexpr auto size = 1000u;
auto buffer = lt::renderer::create_buffer(
lt::renderer::Api::vulkan,
fixture.device(),
fixture.gpu(),
lt::renderer::IBuffer::CreateInfo {
.usage = staging,
.size = size,
.debug_name = "",
}
);
auto map = buffer->map();
expect_eq(map.size(), size);
expect_not_nullptr(map.data());
expect_false(fixture.has_any_messages_of(error));
expect_false(fixture.has_any_messages_of(warning));
}; };
sleep_for(std::chrono::milliseconds { 500u });
}; };

View file

@ -1,9 +1,18 @@
import renderer.frontend; import renderer.frontend;
import renderer.test_utils; import renderer.test_utils;
void noop_callback(
lt::renderer::IDebugger::MessageSeverity message_severity,
lt::renderer::IDebugger::MessageType message_type,
const lt::renderer::IDebugger::MessageData &data,
std::any &user_data
)
{
}
Suite raii = "debugger_raii"_suite = [] { Suite raii = "debugger_raii"_suite = [] {
Case { "happy paths" } = [] { Case { "happy path won't throw" } = [] {
ignore = lt::renderer::create_debugger( std::ignore = lt::renderer::create_debugger(
lt::renderer::Api::vulkan, lt::renderer::Api::vulkan,
lt::renderer::get_instance(lt::renderer::Api::vulkan), lt::renderer::get_instance(lt::renderer::Api::vulkan),
lt::renderer::IDebugger::CreateInfo { lt::renderer::IDebugger::CreateInfo {
@ -14,9 +23,9 @@ Suite raii = "debugger_raii"_suite = [] {
); );
}; };
Case { "unhappy paths" } = [] { Case { "unhappy path throws" } = [] {
expect_throw([] { expect_throw([] {
ignore = lt::renderer::create_debugger( std::ignore = lt::renderer::create_debugger(
lt::renderer::Api::vulkan, lt::renderer::Api::vulkan,
lt::renderer::get_instance(lt::renderer::Api::vulkan), lt::renderer::get_instance(lt::renderer::Api::vulkan),
lt::renderer::IDebugger::CreateInfo { lt::renderer::IDebugger::CreateInfo {
@ -28,7 +37,7 @@ Suite raii = "debugger_raii"_suite = [] {
}); });
expect_throw([] { expect_throw([] {
ignore = lt::renderer::create_debugger( std::ignore = lt::renderer::create_debugger(
lt::renderer::Api::vulkan, lt::renderer::Api::vulkan,
lt::renderer::get_instance(lt::renderer::Api::vulkan), lt::renderer::get_instance(lt::renderer::Api::vulkan),
lt::renderer::IDebugger::CreateInfo { lt::renderer::IDebugger::CreateInfo {
@ -40,7 +49,7 @@ Suite raii = "debugger_raii"_suite = [] {
}); });
expect_throw([] { expect_throw([] {
ignore = lt::renderer::create_debugger( std::ignore = lt::renderer::create_debugger(
lt::renderer::Api::vulkan, lt::renderer::Api::vulkan,
lt::renderer::get_instance(lt::renderer::Api::vulkan), lt::renderer::get_instance(lt::renderer::Api::vulkan),
lt::renderer::IDebugger::CreateInfo { lt::renderer::IDebugger::CreateInfo {

View file

@ -2,12 +2,12 @@ import renderer.frontend;
import renderer.test_utils; import renderer.test_utils;
Suite raii = "device_raii"_suite = [] { Suite raii = "device_raii"_suite = [] {
Case { "happy paths" } = [] { Case { "happy path won't throw" } = [] {
auto fixture = Fixture_SurfaceGpu {}; auto fixture = Fixture_SurfaceGpu {};
ignore = lt::renderer::create_device(constants::api, fixture.gpu(), fixture.surface()); std::ignore = lt::renderer::create_device(constants::api, fixture.gpu(), fixture.surface());
}; };
Case { "unhappy paths" } = [] { Case { "unhappy path throws" } = [] {
auto fixture = Fixture_SurfaceGpu {}; auto fixture = Fixture_SurfaceGpu {};
expect_throw([&] { expect_throw([&] {

View file

@ -2,9 +2,9 @@ import renderer.frontend;
import renderer.test_utils; import renderer.test_utils;
Suite raii = "pass_raii"_suite = [] { Suite raii = "pass_raii"_suite = [] {
Case { "happy paths" } = [] { Case { "happy path won't throw" } = [] {
auto fixture = FixtureDeviceSwapchain {}; auto fixture = FixtureDeviceSwapchain {};
ignore = lt::renderer::create_pass( std::ignore = lt::renderer::create_pass(
constants::api, constants::api,
fixture.device(), fixture.device(),
lt::assets::ShaderAsset { "./data/test_assets/triangle.vert.asset" }, lt::assets::ShaderAsset { "./data/test_assets/triangle.vert.asset" },
@ -17,10 +17,10 @@ Suite raii = "pass_raii"_suite = [] {
); );
}; };
Case { "unhappy paths" } = [] { Case { "unhappy path throws" } = [] {
auto fixture = FixtureDeviceSwapchain {}; auto fixture = FixtureDeviceSwapchain {};
expect_throw([&] { expect_throw([&] {
ignore = lt::renderer::create_pass( std::ignore = lt::renderer::create_pass(
constants::api, constants::api,
nullptr, nullptr,
lt::assets::ShaderAsset { "./data/test_assets/triangle.vert.asset" }, lt::assets::ShaderAsset { "./data/test_assets/triangle.vert.asset" },
@ -29,7 +29,7 @@ Suite raii = "pass_raii"_suite = [] {
}); });
expect_throw([&] { expect_throw([&] {
ignore = lt::renderer::create_pass( std::ignore = lt::renderer::create_pass(
lt::renderer::Api::none, lt::renderer::Api::none,
fixture.device(), fixture.device(),
lt::assets::ShaderAsset { "./data/test_assets/triangle.vert.asset" }, lt::assets::ShaderAsset { "./data/test_assets/triangle.vert.asset" },
@ -38,7 +38,7 @@ Suite raii = "pass_raii"_suite = [] {
}); });
expect_throw([&] { expect_throw([&] {
ignore = lt::renderer::create_pass( std::ignore = lt::renderer::create_pass(
lt::renderer::Api::direct_x, lt::renderer::Api::direct_x,
fixture.device(), fixture.device(),
lt::assets::ShaderAsset { "./data/test_assets/triangle.vert.asset" }, lt::assets::ShaderAsset { "./data/test_assets/triangle.vert.asset" },
@ -47,7 +47,7 @@ Suite raii = "pass_raii"_suite = [] {
}); });
expect_throw([&] { expect_throw([&] {
ignore = lt::renderer::create_pass( std::ignore = lt::renderer::create_pass(
lt::renderer::Api::metal, lt::renderer::Api::metal,
fixture.device(), fixture.device(),
lt::assets::ShaderAsset { "./data/test_assets/triangle.vert.asset" }, lt::assets::ShaderAsset { "./data/test_assets/triangle.vert.asset" },

View file

@ -2,7 +2,7 @@ import renderer.frontend;
import renderer.test_utils; import renderer.test_utils;
Suite raii = "renderer_raii"_suite = [] { Suite raii = "renderer_raii"_suite = [] {
Case { "happy paths" } = [] { Case { "happy path won't throw" } = [] {
auto fixture = FixtureDeviceSwapchain {}; auto fixture = FixtureDeviceSwapchain {};
ignore = lt::renderer::create_renderer( ignore = lt::renderer::create_renderer(
constants::api, constants::api,
@ -18,7 +18,7 @@ Suite raii = "renderer_raii"_suite = [] {
); );
}; };
Case { "unhappy paths" } = [] { Case { "unhappy path throws" } = [] {
auto fixture = FixtureDeviceSwapchain {}; auto fixture = FixtureDeviceSwapchain {};
expect_throw([&] { expect_throw([&] {

View file

@ -2,7 +2,7 @@ import renderer.frontend;
import renderer.test_utils; import renderer.test_utils;
Suite raii = "surface"_suite = [] { Suite raii = "surface"_suite = [] {
Case { "happy paths" } = [&] { Case { "happy path won't throw" } = [&] {
auto fixture = Fixture_SurfaceSystem {}; auto fixture = Fixture_SurfaceSystem {};
const auto surface = lt::renderer::create_surface( const auto surface = lt::renderer::create_surface(
@ -16,13 +16,13 @@ Suite raii = "surface"_suite = [] {
expect_eq(y, constants::resolution.y); expect_eq(y, constants::resolution.y);
}; };
Case { "unhappy paths" } = [&] { Case { "unhappy path throws" } = [&] {
auto registry = lt::memory::create_ref<lt::ecs::Registry>(); auto registry = lt::memory::create_ref<lt::ecs::Registry>();
auto entity = lt::ecs::Entity { registry, registry->create_entity() }; auto entity = lt::ecs::Entity { registry, registry->create_entity() };
auto system = lt::surface::System(registry); auto system = lt::surface::System(registry);
expect_throw([&] { expect_throw([&] {
ignore = lt::renderer::create_surface( std::ignore = lt::renderer::create_surface(
constants::api, constants::api,
lt::renderer::get_instance(constants::api), lt::renderer::get_instance(constants::api),
entity entity
@ -38,11 +38,11 @@ Suite raii = "surface"_suite = [] {
); );
expect_throw([&] { expect_throw([&] {
ignore = lt::renderer::create_surface(constants::api, nullptr, entity); std::ignore = lt::renderer::create_surface(constants::api, nullptr, entity);
}); });
expect_throw([&] { expect_throw([&] {
ignore = lt::renderer::create_surface( std::ignore = lt::renderer::create_surface(
lt::renderer::Api::none, lt::renderer::Api::none,
lt::renderer::get_instance(constants::api), lt::renderer::get_instance(constants::api),
entity entity
@ -50,7 +50,7 @@ Suite raii = "surface"_suite = [] {
}); });
expect_throw([&] { expect_throw([&] {
ignore = lt::renderer::create_surface( std::ignore = lt::renderer::create_surface(
lt::renderer::Api::direct_x, lt::renderer::Api::direct_x,
lt::renderer::get_instance(constants::api), lt::renderer::get_instance(constants::api),
entity entity
@ -58,7 +58,7 @@ Suite raii = "surface"_suite = [] {
}); });
expect_throw([&] { expect_throw([&] {
ignore = lt::renderer::create_surface( std::ignore = lt::renderer::create_surface(
lt::renderer::Api::metal, lt::renderer::Api::metal,
lt::renderer::get_instance(constants::api), lt::renderer::get_instance(constants::api),
entity entity
@ -66,7 +66,7 @@ Suite raii = "surface"_suite = [] {
}); });
// Ensure base creation info is non-throwing // Ensure base creation info is non-throwing
ignore = lt::renderer::create_surface( std::ignore = lt::renderer::create_surface(
constants::api, constants::api,
lt::renderer::get_instance(constants::api), lt::renderer::get_instance(constants::api),
entity entity

View file

@ -1,24 +1,25 @@
import preliminary;
import time;
import renderer.frontend; import renderer.frontend;
import renderer.test_utils; import renderer.test_utils;
struct SurfaceContext struct SurfaceContext
{ {
lt::surface::System system; lt::surface::System system;
lt::ecs::Entity entity; lt::ecs::Entity entity;
}; };
struct RendererContext struct RendererContext
{ {
lt::memory::Ref<lt::ecs::Registry> registry; lt::memory::Ref<lt::ecs::Registry> registry;
lt::renderer::System system; lt::renderer::System system;
}; };
Suite raii = "system_raii"_suite = [] { Suite raii = "system_raii"_suite = [] {
Case { "happy paths" } = [] { Case { "happy path won't throw" } = [] {
ignore = Fixture_RendererSystem {};
};
Case { "happy path has no errors" } = [] {
auto fixture = Fixture_RendererSystem {}; auto fixture = Fixture_RendererSystem {};
expect_false(fixture.has_any_messages_of(lt::renderer::IDebugger::MessageSeverity::error)); expect_false(fixture.has_any_messages_of(lt::renderer::IDebugger::MessageSeverity::error));
expect_false( expect_false(
@ -26,7 +27,7 @@ Suite raii = "system_raii"_suite = [] {
); );
}; };
Case { "unhappy paths" } = [] { Case { "unhappy path throws" } = [] {
auto fixture = Fixture_SurfaceSystem {}; auto fixture = Fixture_SurfaceSystem {};
auto empty_entity = lt::ecs::Entity { fixture.registry(), auto empty_entity = lt::ecs::Entity { fixture.registry(),
fixture.registry()->create_entity() }; fixture.registry()->create_entity() };

View file

@ -1,9 +1,11 @@
export module renderer.test_utils; export module renderer.test_utils;
export import test; export import logger;
export import surface.system; export import surface.system;
export import ecs.registry; export import ecs.registry;
export import renderer.factory; export import renderer.factory;
export import test.test;
export import test.expects;
export import memory.reference; export import memory.reference;
export import renderer.frontend; export import renderer.frontend;
export import renderer.system; export import renderer.system;
@ -11,21 +13,32 @@ export import math.vec2;
export import math.vec3; export import math.vec3;
export import math.vec4; export import math.vec4;
export import math.mat4; export import math.mat4;
export import std;
export using ::lt::test::Case;
export using ::lt::test::expect_eq;
export using ::lt::test::expect_false;
export using ::lt::test::expect_not_nullptr;
export using ::lt::test::expect_throw;
export using ::lt::test::operator""_suite;
export using ::lt::test::expect_true;
export using ::lt::test::Suite;
export using ::std::ignore;
export namespace constants { export namespace constants {
constexpr auto api = lt::renderer::Api::vulkan; constexpr auto api = lt::renderer::Api::vulkan;
constexpr auto resolution = lt::math::vec2_u32 { 800u, 600u }; constexpr auto resolution = lt::math::uvec2 { 800u, 600u };
constexpr auto frames_in_flight = u32 { 3u }; constexpr auto frames_in_flight = std::uint32_t { 3u };
} // namespace constants } // namespace constants
export void noop_callback( void noop_messenger_callback(
lt::renderer::IDebugger::MessageSeverity, lt::renderer::IDebugger::MessageSeverity severity,
lt::renderer::IDebugger::MessageType, lt::renderer::IDebugger::MessageType type,
const lt::renderer::IDebugger::MessageData &, const lt::renderer::IDebugger::MessageData &data,
std::any & std::any &user_data
) )
{ {
} }
@ -56,7 +69,7 @@ public:
.debug_callback_info = { .debug_callback_info = {
.severities = lt::renderer::IDebugger::MessageSeverity::all, .severities = lt::renderer::IDebugger::MessageSeverity::all,
.types= lt::renderer::IDebugger::MessageType::all, .types= lt::renderer::IDebugger::MessageType::all,
.callback = noop_callback, .callback = noop_messenger_callback,
.user_data = {}, .user_data = {},
} }
} ; } ;
@ -144,7 +157,7 @@ public:
} }
[[nodiscard]] auto has_any_messages_of(lt::renderer::IDebugger ::MessageSeverity severity) const [[nodiscard]] auto has_any_messages_of(lt::renderer::IDebugger ::MessageSeverity severity) const
-> u32 -> std::uint32_t
{ {
return m_user_data->m_severity_counter.contains(severity); return m_user_data->m_severity_counter.contains(severity);
} }
@ -159,9 +172,9 @@ private:
{ {
// I know this makes the tests too verbose... // I know this makes the tests too verbose...
// but makes it easier to figure out what the problem is when things fail on ci // but makes it easier to figure out what the problem is when things fail on ci
lt::log::trace("vulkan: {}", std::string { data.message }); lt::log::debug("vulkan: {}", data.message);
ignore = data; std::ignore = data;
ignore = type; std::ignore = type;
auto *fixture = std::any_cast<UserData *>(user_data); auto *fixture = std::any_cast<UserData *>(user_data);
fixture->m_has_any_messages = true; fixture->m_has_any_messages = true;
@ -170,7 +183,8 @@ private:
struct UserData struct UserData
{ {
std::unordered_map<lt::renderer::IDebugger::MessageSeverity, u32> m_severity_counter; std::unordered_map<lt::renderer::IDebugger::MessageSeverity, std::uint32_t>
m_severity_counter;
bool m_has_any_messages {}; bool m_has_any_messages {};
}; };
@ -207,13 +221,17 @@ public:
return m_system; return m_system;
} }
auto device() -> lt::renderer::IDevice &
{
}
[[nodiscard]] auto has_any_messages() const -> bool [[nodiscard]] auto has_any_messages() const -> bool
{ {
return m_user_data->m_has_any_messages; return m_user_data->m_has_any_messages;
} }
[[nodiscard]] auto has_any_messages_of(lt::renderer::IDebugger ::MessageSeverity severity) const [[nodiscard]] auto has_any_messages_of(lt::renderer::IDebugger ::MessageSeverity severity) const
-> u32 -> std::uint32_t
{ {
return m_user_data->m_severity_counter.contains(severity); return m_user_data->m_severity_counter.contains(severity);
} }
@ -228,10 +246,10 @@ private:
{ {
// I know this makes the tests too verbose... // I know this makes the tests too verbose...
// but makes it easier to figure out what the problem is when things fail on ci // but makes it easier to figure out what the problem is when things fail on ci
lt::log::trace("vulkan: {}", std::string { data.message }); lt::log::trace("vulkan: {}", data.message);
ignore = data; std::ignore = data;
ignore = type; std::ignore = type;
auto *fixture = std::any_cast<UserData *>(user_data); auto *fixture = std::any_cast<UserData *>(user_data);
fixture->m_has_any_messages = true; fixture->m_has_any_messages = true;
@ -240,7 +258,8 @@ private:
struct UserData struct UserData
{ {
std::unordered_map<lt::renderer::IDebugger::MessageSeverity, u32> m_severity_counter; std::unordered_map<lt::renderer::IDebugger::MessageSeverity, std::uint32_t>
m_severity_counter;
bool m_has_any_messages {}; bool m_has_any_messages {};
}; };

View file

@ -1,20 +1,19 @@
export module renderer.components; export module renderer.components;
import preliminary;
import assets.shader; import assets.shader;
import math.vec3; import math.vec3;
import memory.reference; import memory.reference;
import std;
export namespace lt::renderer::components { export namespace lt::renderer::components {
enum class VertexFormat : u8 enum class VertexFormat : std::uint8_t
{ {
r32_g32_b32_sfloat, r32_g32_b32_sfloat,
r32_g32_sfloat, r32_g32_sfloat,
}; };
enum class VertexInputRate : u8 enum class VertexInputRate : std::uint8_t
{ {
per_vertex, per_vertex,
@ -23,20 +22,20 @@ enum class VertexInputRate : u8
struct VertexInputAttributeDescriptipn struct VertexInputAttributeDescriptipn
{ {
u32 location; std::uint32_t location;
u32 binding; std::uint32_t binding;
u32 offset; std::uint32_t offset;
VertexFormat format; VertexFormat format;
}; };
struct VertexInputBindingDescription struct VertexInputBindingDescription
{ {
u32 binding; std::uint32_t binding;
u32 stride; std::uint32_t stride;
}; };
/** Requires a math::components::Transform component on the same entity to be functional. */ /** Requires a math::components::Transform component on the same entity to be functional. */

View file

@ -2,9 +2,10 @@ export module renderer.data;
import math.mat4; import math.mat4;
export namespace lt::renderer {
struct FrameConstants namespace lt::renderer {
export struct FrameConstants
{ {
math::mat4 view_projection; math::mat4 view_projection;
}; };

View file

@ -11,9 +11,9 @@ export import renderer.vk.gpu;
export import renderer.vk.debugger; export import renderer.vk.debugger;
export import renderer.vk.surface; export import renderer.vk.surface;
export import memory.scope; export import memory.scope;
export import debug.assertions;
export import ecs.entity; export import ecs.entity;
export import std;
import preliminary;
export namespace lt::renderer { export namespace lt::renderer {
@ -48,7 +48,7 @@ export namespace lt::renderer {
IGpu *gpu, IGpu *gpu,
IDevice *device, IDevice *device,
ISwapchain *swapchain, ISwapchain *swapchain,
u32 max_frames_in_flight std::uint32_t max_frames_in_flight
) -> memory::Scope<IRenderer>; ) -> memory::Scope<IRenderer>;
[[nodiscard]] auto create_buffer( [[nodiscard]] auto create_buffer(
@ -60,8 +60,7 @@ export namespace lt::renderer {
} // namespace lt::renderer } // namespace lt::renderer
/** @todo(Light): unimplemented in gcc -- is it even right to use a private fragment? */ module :private;
// module :private;
namespace lt::renderer { namespace lt::renderer {
[[nodiscard]] auto get_instance(Api target_api) -> IInstance * [[nodiscard]] auto get_instance(Api target_api) -> IInstance *
@ -83,7 +82,7 @@ namespace lt::renderer {
const lt::ecs::Entity &surface_entity const lt::ecs::Entity &surface_entity
) -> memory::Scope<ISurface> ) -> memory::Scope<ISurface>
{ {
ensure(instance, "Failed to create renderer::ISurface: null instance"); debug::ensure(instance, "Failed to create renderer::ISurface: null instance");
switch (target_api) switch (target_api)
{ {
@ -112,8 +111,8 @@ namespace lt::renderer {
[[nodiscard]] auto create_device(Api target_api, IGpu *gpu, ISurface *surface) [[nodiscard]] auto create_device(Api target_api, IGpu *gpu, ISurface *surface)
-> memory::Scope<IDevice> -> memory::Scope<IDevice>
{ {
ensure(gpu, "Failed to create renderer::IDevice: null gpu"); debug::ensure(gpu, "Failed to create renderer::IDevice: null gpu");
ensure(surface, "Failed to create renderer::IDevice: null surface"); debug::ensure(surface, "Failed to create renderer::IDevice: null surface");
switch (target_api) switch (target_api)
{ {
@ -147,9 +146,9 @@ namespace lt::renderer {
const IBuffer::CreateInfo &info const IBuffer::CreateInfo &info
) -> memory::Scope<IBuffer> ) -> memory::Scope<IBuffer>
{ {
ensure(device, "Failed to create renderer::IBuffer: null device"); debug::ensure(device, "Failed to create renderer::IBuffer: null device");
ensure(gpu, "Failed to create renderer::IBuffer: null gpu"); debug::ensure(gpu, "Failed to create renderer::IBuffer: null gpu");
ensure(info.size > 0, "Failed to create renderer::IBuffer: null size"); debug::ensure(info.size > 0, "Failed to create renderer::IBuffer: null size");
switch (target_api) switch (target_api)
{ {
@ -170,7 +169,7 @@ namespace lt::renderer {
const lt::assets::ShaderAsset &fragment_shader const lt::assets::ShaderAsset &fragment_shader
) -> memory::Scope<IPass> ) -> memory::Scope<IPass>
{ {
ensure(device, "Failed to create renderer::IPass: null device"); debug::ensure(device, "Failed to create renderer::IPass: null device");
switch (target_api) switch (target_api)
{ {
@ -189,13 +188,13 @@ namespace lt::renderer {
IGpu *gpu, IGpu *gpu,
IDevice *device, IDevice *device,
ISwapchain *swapchain, ISwapchain *swapchain,
u32 max_frames_in_flight std::uint32_t max_frames_in_flight
) -> memory::Scope<IRenderer> ) -> memory::Scope<IRenderer>
{ {
ensure(gpu, "Failed to create renderer::IRenderer: null gpu"); debug::ensure(gpu, "Failed to create renderer::IRenderer: null gpu");
ensure(device, "Failed to create renderer::IRenderer: null device"); debug::ensure(device, "Failed to create renderer::IRenderer: null device");
ensure(swapchain, "Failed to create renderer::IRenderer: null swapchain"); debug::ensure(swapchain, "Failed to create renderer::IRenderer: null swapchain");
ensure( debug::ensure(
std::clamp( std::clamp(
max_frames_in_flight, max_frames_in_flight,
IRenderer::frames_in_flight_lower_limit, IRenderer::frames_in_flight_lower_limit,
@ -224,17 +223,17 @@ namespace lt::renderer {
[[nodiscard]] auto create_debugger(Api target_api, IInstance *instance, IDebugger::CreateInfo info) [[nodiscard]] auto create_debugger(Api target_api, IInstance *instance, IDebugger::CreateInfo info)
-> memory::Scope<IDebugger> -> memory::Scope<IDebugger>
{ {
ensure( debug::ensure(
info.severities != IDebugger::MessageSeverity::none, info.severities != IDebugger::MessageSeverity::none,
"Failed to create renderer::IDebugger: severities == none" "Failed to create renderer::IDebugger: severities == none"
); );
ensure( debug::ensure(
info.types != IDebugger::MessageType::none, info.types != IDebugger::MessageType::none,
"Failed to create renderer::IDebugger: types == none" "Failed to create renderer::IDebugger: types == none"
); );
ensure(info.callback, "Failed to create vk::Messenger: null callback"); debug::ensure(info.callback, "Failed to create vk::Messenger: null callback");
switch (target_api) switch (target_api)
{ {

View file

@ -1,6 +1,4 @@
export module renderer.frontend; export module renderer.frontend;
import preliminary;
import renderer.data; import renderer.data;
import renderer.components; import renderer.components;
import bitwise; import bitwise;
@ -9,10 +7,11 @@ import assets.shader;
import ecs.entity; import ecs.entity;
import math.vec2; import math.vec2;
import memory.scope; import memory.scope;
import std;
export namespace lt::renderer { export namespace lt::renderer {
enum class Api : u8 enum class Api : std::uint8_t
{ {
none = 0u, none = 0u,
@ -52,7 +51,7 @@ public:
virtual ~ISurface() = default; virtual ~ISurface() = default;
[[nodiscard]] virtual auto get_framebuffer_size() const -> math::vec2_u32 = 0; [[nodiscard]] virtual auto get_framebuffer_size() const -> math::uvec2 = 0;
}; };
class ISwapchain class ISwapchain
@ -66,7 +65,7 @@ public:
class IBuffer class IBuffer
{ {
public: public:
enum class Usage : u8 enum class Usage : std::uint8_t
{ {
vertex, vertex,
@ -81,27 +80,27 @@ public:
{ {
Usage usage; Usage usage;
size_t size; std::size_t size;
std::string debug_name; std::string debug_name;
}; };
struct CopyInfo struct CopyInfo
{ {
size_t offset; std::size_t offset;
size_t size; std::size_t size;
}; };
IBuffer() = default; IBuffer() = default;
virtual ~IBuffer() = default; virtual ~IBuffer() = default;
[[nodiscard]] virtual auto map() -> std::span<byte> = 0; [[nodiscard]] virtual auto map() -> std::span<std::byte> = 0;
virtual void unmap() = 0; virtual void unmap() = 0;
[[nodiscard]] virtual auto get_size() const -> size_t = 0; [[nodiscard]] virtual auto get_size() const -> std::size_t = 0;
private: private:
}; };
@ -121,7 +120,7 @@ public:
static constexpr auto frames_in_flight_lower_limit = 1u; static constexpr auto frames_in_flight_lower_limit = 1u;
enum class Result : u8 enum class Result : std::uint8_t
{ {
success = 0, success = 0,
invalid_swapchain, invalid_swapchain,
@ -132,7 +131,7 @@ public:
virtual ~IRenderer() = default; virtual ~IRenderer() = default;
virtual auto frame(u32 frame_idx, std::function<void()> submit_scene) -> Result = 0; virtual auto frame(std::uint32_t frame_idx, std::function<void()> submit_scene) -> Result = 0;
virtual void replace_swapchain(class ISwapchain *swapchain) = 0; virtual void replace_swapchain(class ISwapchain *swapchain) = 0;
@ -147,7 +146,7 @@ public:
class IDebugger class IDebugger
{ {
public: public:
enum class MessageSeverity : u8 enum class MessageSeverity : std::uint8_t
{ {
none = 0u, none = 0u,
@ -159,7 +158,7 @@ public:
all = verbose | info | warning | error, all = verbose | info | warning | error,
}; };
enum class MessageType : u8 enum class MessageType : std::uint8_t
{ {
none = 0u, none = 0u,
general = bitwise::bit(0u), general = bitwise::bit(0u),

View file

@ -1,7 +1,6 @@
export module renderer.system; export module renderer.system;
import preliminary;
import logger; import logger;
import debug.assertions;
import math.mat4; import math.mat4;
import renderer.factory; import renderer.factory;
import app.system; import app.system;
@ -17,8 +16,9 @@ import renderer.components;
import math.components; import math.components;
import math.algebra; import math.algebra;
import math.trig; import math.trig;
import std;
export namespace lt::renderer { namespace lt::renderer {
/** The main rendering engine. /** The main rendering engine.
* *
@ -27,11 +27,9 @@ export namespace lt::renderer {
* - Connecting the context to the physical devices (select gpu, create surface, logical device) * - Connecting the context to the physical devices (select gpu, create surface, logical device)
* - Rendering the scene represented in registry via lt::renderer::components. * - Rendering the scene represented in registry via lt::renderer::components.
*/ */
class System: public app::ISystem export class System: public app::ISystem
{ {
public: public:
// TODO(Light): this is some horrible design... fix it :(
/** config.max_frames_in_flight should not be higher than this value. */ /** config.max_frames_in_flight should not be higher than this value. */
static constexpr auto frames_in_flight_upper_limit = 5u; static constexpr auto frames_in_flight_upper_limit = 5u;
@ -42,7 +40,7 @@ public:
{ {
Api target_api; Api target_api;
u32 max_frames_in_flight; std::uint32_t max_frames_in_flight;
}; };
struct CreateInfo struct CreateInfo
@ -58,7 +56,7 @@ public:
System(CreateInfo info); System(CreateInfo info);
~System() override = default; ~System() override;
System(System &&) = default; System(System &&) = default;
@ -108,15 +106,14 @@ private:
app::TickResult m_last_tick_result {}; app::TickResult m_last_tick_result {};
u32 m_frame_idx {}; std::uint32_t m_frame_idx {};
u32 m_max_frames_in_flight {}; std::uint32_t m_max_frames_in_flight {};
}; };
} // namespace lt::renderer } // namespace lt::renderer
/** @todo(Light): unimplemented in gcc -- is it even right to use a private fragment? */ module :private;
// module :private;
namespace lt::renderer { namespace lt::renderer {
System::System(CreateInfo info) System::System(CreateInfo info)
@ -126,8 +123,8 @@ System::System(CreateInfo info)
, m_instance(get_instance(m_api)) , m_instance(get_instance(m_api))
, m_max_frames_in_flight(info.config.max_frames_in_flight) , m_max_frames_in_flight(info.config.max_frames_in_flight)
{ {
ensure(m_registry, "Failed to initialize renderer::System: null registry"); debug::ensure(m_registry, "Failed to initialize renderer::System: null registry");
ensure( debug::ensure(
std::clamp( std::clamp(
info.config.max_frames_in_flight, info.config.max_frames_in_flight,
frames_in_flight_lower_limit, frames_in_flight_lower_limit,
@ -155,6 +152,8 @@ System::System(CreateInfo info)
) }; ) };
} }
System::~System() = default;
void System::on_register() void System::on_register()
{ {
} }
@ -165,7 +164,7 @@ void System::on_unregister()
void System::tick(app::TickInfo tick) void System::tick(app::TickInfo tick)
{ {
ignore = tick; std::ignore = tick;
handle_surface_resized_events(); handle_surface_resized_events();
auto frame_result = m_renderer->frame(m_frame_idx, [this] { submit_scene(); }); auto frame_result = m_renderer->frame(m_frame_idx, [this] { submit_scene(); });
@ -183,29 +182,9 @@ void System::handle_surface_resized_events()
{ {
if (std::holds_alternative<surface::ResizedEvent>(event)) if (std::holds_alternative<surface::ResizedEvent>(event))
{ {
const auto res = std::get<surface::ResizedEvent>(event).get_size();
log::debug("Resize event received from the renderer: {}", res);
// m_swapchain.reset();
// m_swapchain = create_swapchain(m_api, m_surface.get(), m_gpu.get(), m_device.get());
// m_renderer->replace_swapchain(m_swapchain.get());
m_renderer.reset();
m_swapchain.reset(); m_swapchain.reset();
m_device.reset();
m_gpu.reset();
m_surface.reset();
m_surface = create_surface(m_api, m_instance, m_surface_entity);
m_gpu = create_gpu(m_api, m_instance);
m_device = create_device(m_api, m_gpu.get(), m_surface.get());
m_swapchain = create_swapchain(m_api, m_surface.get(), m_gpu.get(), m_device.get()); m_swapchain = create_swapchain(m_api, m_surface.get(), m_gpu.get(), m_device.get());
m_renderer = { create_renderer( m_renderer->replace_swapchain(m_swapchain.get());
m_api,
m_gpu.get(),
m_device.get(),
m_swapchain.get(),
m_max_frames_in_flight
) };
// No need to process multiple resize events // No need to process multiple resize events
break; break;

File diff suppressed because it is too large Load diff

View file

@ -1,14 +1,13 @@
export module renderer.vk.buffer; export module renderer.vk.buffer;
import preliminary;
import renderer.vk.device; import renderer.vk.device;
import renderer.vk.gpu; import renderer.vk.gpu;
import renderer.vk.api_wrapper; import renderer.vk.api_wrapper;
import renderer.frontend; import renderer.frontend;
import std;
export namespace lt::renderer::vkb { namespace lt::renderer::vkb {
class Buffer: public IBuffer export class Buffer: public IBuffer
{ {
public: public:
Buffer(class IDevice *device, class IGpu *gpu, const CreateInfo &info); Buffer(class IDevice *device, class IGpu *gpu, const CreateInfo &info);
@ -17,7 +16,7 @@ public:
void unmap() override; void unmap() override;
[[nodiscard]] auto get_size() const -> size_t override [[nodiscard]] auto get_size() const -> std::size_t override
{ {
return m_size; return m_size;
} }
@ -35,11 +34,12 @@ private:
[[nodiscard]] auto to_native_memory_properties(Usage usage) const -> vk::Memory::PropertyFlags; [[nodiscard]] auto to_native_memory_properties(Usage usage) const -> vk::Memory::PropertyFlags;
[[nodiscard]] auto has_correct_memory_type_bit(u32 type_bits, u32 type_idx) const -> bool; [[nodiscard]] auto has_correct_memory_type_bit(std::uint32_t type_bits, std::uint32_t type_idx)
const -> bool;
[[nodiscard]] auto has_required_memory_properties( [[nodiscard]] auto has_required_memory_properties(
u32 required_properties, std::uint32_t required_properties,
u32 property_flags std::uint32_t property_flags
) const -> bool; ) const -> bool;
Device *m_device {}; Device *m_device {};
@ -51,14 +51,14 @@ private:
vk::Memory m_memory; vk::Memory m_memory;
// TODO(Light): should this reflect the allocation size instead? // TODO(Light): should this reflect the allocation size instead?
size_t m_size {}; std::size_t m_size {};
}; };
} // namespace lt::renderer::vkb } // namespace lt::renderer::vkb
/** @todo(Light): unimplemented in gcc -- is it even right to use a private fragment? */ module :private;
// module :private; using namespace ::lt::renderer;
namespace lt::renderer::vkb { using namespace ::lt::renderer::vkb;
Buffer::Buffer(IDevice *device, IGpu *gpu, const CreateInfo &info) Buffer::Buffer(IDevice *device, IGpu *gpu, const CreateInfo &info)
: m_device(static_cast<Device *>(device)) : m_device(static_cast<Device *>(device))
@ -145,17 +145,18 @@ void Buffer::unmap() /* override */
std::unreachable(); std::unreachable();
} }
[[nodiscard]] auto Buffer::has_correct_memory_type_bit(u32 type_bits, u32 type_idx) const -> bool [[nodiscard]] auto Buffer::has_correct_memory_type_bit(
std::uint32_t type_bits,
std::uint32_t type_idx
) const -> bool
{ {
return type_bits & (1 << type_idx); return type_bits & (1 << type_idx);
} }
[[nodiscard]] auto Buffer::has_required_memory_properties( [[nodiscard]] auto Buffer::has_required_memory_properties(
u32 required_properties, std::uint32_t required_properties,
u32 property_flags std::uint32_t property_flags
) const -> bool ) const -> bool
{ {
return (property_flags & required_properties) == required_properties; return (property_flags & required_properties) == required_properties;
} }
} // namespace lt::renderer::vkb

View file

@ -1,15 +1,15 @@
export module renderer.vk.debugger; export module renderer.vk.debugger;
import preliminary;
import renderer.vk.instance; import renderer.vk.instance;
import renderer.frontend; import renderer.frontend;
import renderer.vk.api_wrapper; import renderer.vk.api_wrapper;
import memory.null_on_move; import memory.null_on_move;
import debug.assertions;
import logger; import logger;
import std;
export namespace lt::renderer::vkb { namespace lt::renderer::vkb {
class Debugger: public IDebugger export class Debugger: public IDebugger
{ {
public: public:
Debugger(IInstance *instance, CreateInfo info); Debugger(IInstance *instance, CreateInfo info);
@ -35,8 +35,7 @@ private:
} // namespace lt::renderer::vkb } // namespace lt::renderer::vkb
/** @todo(Light): unimplemented in gcc -- is it even right to use a private fragment? */ module :private;
// module :private;
namespace lt::renderer::vkb { namespace lt::renderer::vkb {
[[nodiscard]] auto to_native_severity(IDebugger::MessageSeverity severity) -> vk::Flags [[nodiscard]] auto to_native_severity(IDebugger::MessageSeverity severity) -> vk::Flags
@ -156,7 +155,7 @@ void Debugger::native_callback(
{ {
try try
{ {
ensure(user_data, "Null vulkan_user_data received in messenger callback"); debug::ensure(user_data, "Null vulkan_user_data received in messenger callback");
auto *messenger = std::bit_cast<Debugger *>(user_data); auto *messenger = std::bit_cast<Debugger *>(user_data);
messenger->m_user_callback( messenger->m_user_callback(

View file

@ -0,0 +1,9 @@
#pragma once
namespace lt::renderer::vk {
class Descriptors
{
};
} // namespace lt::renderer::vk

View file

@ -1,17 +1,17 @@
export module renderer.vk.device; export module renderer.vk.device;
import preliminary;
import memory.null_on_move; import memory.null_on_move;
import logger; import logger;
import debug.assertions;
import renderer.vk.instance; import renderer.vk.instance;
import renderer.frontend; import renderer.frontend;
import renderer.vk.api_wrapper; import renderer.vk.api_wrapper;
import renderer.vk.gpu; import renderer.vk.gpu;
import renderer.vk.surface; import renderer.vk.surface;
import std;
export namespace lt::renderer::vkb { namespace lt::renderer::vkb {
class Device: public IDevice export class Device: public IDevice
{ {
public: public:
Device(IGpu *gpu, ISurface *surface); Device(IGpu *gpu, ISurface *surface);
@ -21,7 +21,7 @@ public:
return m_device; return m_device;
} }
[[nodiscard]] auto get_family_indices() const -> std::vector<u32> [[nodiscard]] auto get_family_indices() const -> std::vector<std::uint32_t>
{ {
return { m_graphics_queue_family_index, m_present_queue_family_index }; return { m_graphics_queue_family_index, m_present_queue_family_index };
} }
@ -43,7 +43,7 @@ private:
void initialize_queue_indices(); void initialize_queue_indices();
[[nodiscard]] auto find_suitable_queue_family() const -> u32; [[nodiscard]] auto find_suitable_queue_family() const -> std::uint32_t;
vkb::Gpu *m_gpu {}; vkb::Gpu *m_gpu {};
@ -55,23 +55,22 @@ private:
vk::Queue m_present_queue {}; vk::Queue m_present_queue {};
u32 m_graphics_queue_family_index = vk::constants::queue_family_ignored; std::uint32_t m_graphics_queue_family_index = vk::constants::queue_family_ignored;
u32 m_present_queue_family_index = vk::constants::queue_family_ignored; std::uint32_t m_present_queue_family_index = vk::constants::queue_family_ignored;
}; };
} // namespace lt::renderer::vkb } // namespace lt::renderer::vkb
/** @todo(Light): unimplemented in gcc -- is it even right to use a private fragment? */ module :private;
// module :private;
namespace lt::renderer::vkb { namespace lt::renderer::vkb {
Device::Device(IGpu *gpu, ISurface *surface) Device::Device(IGpu *gpu, ISurface *surface)
: m_gpu(static_cast<Gpu *>(gpu)) : m_gpu(static_cast<Gpu *>(gpu))
, m_surface(static_cast<Surface *>(surface)) , m_surface(static_cast<Surface *>(surface))
{ {
ensure(m_surface->vk(), "Failed to initialize vk::Device: null vulkan surface"); debug::ensure(m_surface->vk(), "Failed to initialize vk::Device: null vulkan surface");
initialize_queue_indices(); initialize_queue_indices();
initialize_logical_device(); initialize_logical_device();
@ -106,9 +105,9 @@ void Device::initialize_logical_device()
.features = { .features = {
.geometry_shader = true, .geometry_shader = true,
.sampler_anisotropy = true,
.multi_draw_indirect = true, .multi_draw_indirect = true,
.draw_indirect_first_instance = true, .draw_indirect_first_instance = true,
.sampler_anisotropy = true,
}, },
.dynamic_rendering_features = m_gpu->vk().get_supported_dynamic_rendering_features(), .dynamic_rendering_features = m_gpu->vk().get_supported_dynamic_rendering_features(),
@ -125,7 +124,7 @@ void Device::initialize_logical_device()
void Device::initialize_queue_indices() void Device::initialize_queue_indices()
{ {
auto properties = m_gpu->vk().get_queue_family_properties(); auto properties = m_gpu->vk().get_queue_family_properties();
for (auto idx = u32 { 0u }; const auto &property : properties) for (auto idx = std::uint32_t { 0u }; const auto &property : properties)
{ {
if (property.queue_flags & vk::QueueFlags::graphics_bit) if (property.queue_flags & vk::QueueFlags::graphics_bit)
{ {
@ -146,12 +145,12 @@ void Device::initialize_queue_indices()
++idx; ++idx;
} }
ensure( debug::ensure(
m_graphics_queue_family_index != vk::constants::queue_family_ignored, m_graphics_queue_family_index != vk::constants::queue_family_ignored,
"Failed to find graphics queue family" "Failed to find graphics queue family"
); );
ensure( debug::ensure(
m_present_queue_family_index != vk::constants::queue_family_ignored, m_present_queue_family_index != vk::constants::queue_family_ignored,
"Failed to find presentation queue family" "Failed to find presentation queue family"
); );

View file

@ -1,19 +1,51 @@
export module renderer.vk.gpu; export module renderer.vk.gpu;
import preliminary;
import renderer.vk.api_wrapper; import renderer.vk.api_wrapper;
import logger; import debug.assertions;
import renderer.frontend; import renderer.frontend;
import renderer.vk.instance; import renderer.vk.instance;
import memory.null_on_move; import memory.null_on_move;
import std;
export namespace lt::renderer::vkb { namespace lt::renderer::vkb {
class Gpu: public IGpu export class Gpu: public IGpu
{ {
public: public:
Gpu(IInstance *instance); Gpu(IInstance *instance);
// [[nodiscard]] auto queue_family_supports_presentation(
// VkSurfaceKHR surface,
// uint32_t queue_family_idx
// ) -> bool;
//
// [[nodiscard]] auto get_surface_capabilities(VkSurfaceKHR surface) const
// -> VkSurfaceCapabilitiesKHR;
//
// [[nodiscard]] auto get_surface_formats(VkSurfaceKHR surface) const
// -> std::vector<VkSurfaceFormatKHR>;
//
// [[nodiscard]] auto get_properties() const -> VkPhysicalDeviceProperties
// {
// return m_properties;
// }
//
// [[nodiscard]] auto get_descriptor_indexing_features() const
// -> VkPhysicalDeviceDescriptorIndexingFeatures
// {
// return m_descriptor_indexing_features;
// }
//
// [[nodiscard]] auto get_memory_properties() const -> VkPhysicalDeviceMemoryProperties
// {
// return m_memory_properties;
// }
//
// [[nodiscard]] auto get_queue_family_properties() const ->
// std::vector<VkQueueFamilyProperties>
// {
// return m_queue_family_properties;
// }
[[nodiscard]] auto vk() -> vk::Gpu &; [[nodiscard]] auto vk() -> vk::Gpu &;
private: private:
@ -21,6 +53,8 @@ private:
vk::Gpu::Properties m_properties {}; vk::Gpu::Properties m_properties {};
// VkPhysicalDeviceDescriptorIndexingFeatures m_descriptor_indexing_features;
vk::Gpu::MemoryProperties m_memory_properties {}; vk::Gpu::MemoryProperties m_memory_properties {};
std::vector<vk::Gpu::QueueFamilyProperties> m_queue_family_properties; std::vector<vk::Gpu::QueueFamilyProperties> m_queue_family_properties;
@ -29,8 +63,7 @@ private:
} // namespace lt::renderer::vkb } // namespace lt::renderer::vkb
/** @todo(Light): unimplemented in gcc -- is it even right to use a private fragment? */ module :private;
// module :private;
namespace lt::renderer::vkb { namespace lt::renderer::vkb {
Gpu::Gpu(IInstance *instance) Gpu::Gpu(IInstance *instance)
@ -42,31 +75,13 @@ Gpu::Gpu(IInstance *instance)
auto properties = gpu.get_properties(); auto properties = gpu.get_properties();
auto features = gpu.get_features(); auto features = gpu.get_features();
// GPU is dedicated, a great success!
if (properties.device_type == vk::Gpu::Type::discrete_gpu && features.geometry_shader) if (properties.device_type == vk::Gpu::Type::discrete_gpu && features.geometry_shader)
{ {
m_gpu = gpu; m_gpu = gpu;
} }
} }
if (!m_gpu) debug::ensure(m_gpu, "Failed to find any suitable Vulkan physical device");
{
for (auto &gpu : gpus)
{
auto properties = gpu.get_properties();
auto features = gpu.get_features();
// GPU is integrated, fall back to anything with geometry shader support...
if (features.geometry_shader)
{
m_gpu = gpu;
log::warn("Using integrated GPU");
}
}
}
// No suitable GPU is fonud...
ensure(m_gpu, "Failed to find any suitable Vulkan physical device");
m_memory_properties = m_gpu.get_memory_properties(); m_memory_properties = m_gpu.get_memory_properties();
m_queue_family_properties = m_gpu.get_queue_family_properties(); m_queue_family_properties = m_gpu.get_queue_family_properties();
@ -77,4 +92,42 @@ Gpu::Gpu(IInstance *instance)
return m_gpu; return m_gpu;
} }
// [[nodiscard]] auto Gpu::queue_family_supports_presentation(
// VkSurfaceKHR surface,
// uint32_t queue_family_idx
// ) -> bool
// {
// auto supported = VkBool32 { false };
// vkc(vk_get_physical_device_surface_support(m_gpu, queue_family_idx, surface, &supported));
//
// return supported;
// }
//
// [[nodiscard]] auto Gpu::get_surface_capabilities(VkSurfaceKHR surface) const
// -> VkSurfaceCapabilitiesKHR
// {
// auto capabilities = VkSurfaceCapabilitiesKHR {};
// vkc(vk_get_physical_device_surface_capabilities(m_gpu, surface, &capabilities));
// return capabilities;
// }
//
// [[nodiscard]] auto Gpu::get_surface_formats(VkSurfaceKHR surface) const
// -> std::vector<VkSurfaceFormatKHR>
// {
// auto count = uint32_t { 0u };
// vkc(vk_get_physical_device_surface_formats(m_gpu, surface, &count, nullptr));
//
// auto formats = std::vector<VkSurfaceFormatKHR>(count);
// vkc(vk_get_physical_device_surface_formats(m_gpu, surface, &count, formats.data()));
//
// return formats;
// }
// [[nodiscard]] auto Gpu::create_device(VkDeviceCreateInfo info) const -> VkDevice
// {
// auto *device = VkDevice {};
// vkc(vk_create_device(m_gpu, &info, nullptr, &device));
// return device;
// }
} // namespace lt::renderer::vkb } // namespace lt::renderer::vkb

View file

@ -1,10 +1,10 @@
export module renderer.vk.instance; export module renderer.vk.instance;
import debug.assertions;
import preliminary;
import renderer.frontend; import renderer.frontend;
import renderer.vk.api_wrapper; import renderer.vk.api_wrapper;
import std;
export namespace lt::renderer::vkb { namespace lt::renderer::vkb {
/** /**
* Responsible for dynamically loading Vulkan library/functions. * Responsible for dynamically loading Vulkan library/functions.
@ -15,7 +15,7 @@ export namespace lt::renderer::vkb {
* https://www.xfree86.org/4.7.0/DRI11.html * https://www.xfree86.org/4.7.0/DRI11.html
* https://github.com/KhronosGroup/Vulkan-LoaderAndValidationLayers/issues/1894 * https://github.com/KhronosGroup/Vulkan-LoaderAndValidationLayers/issues/1894
*/ */
class Instance: public IInstance export class Instance: public IInstance
{ {
public: public:
static auto get() -> IInstance * static auto get() -> IInstance *
@ -28,6 +28,20 @@ public:
return m_instance; return m_instance;
} }
// /* create functions */
// [[nodiscard]] auto create_xlib_surface(VkXlibSurfaceCreateInfoKHR info) const ->
// VkSurfaceKHR;
//
// [[nodiscard]] auto create_messenger(VkDebugUtilsMessengerCreateInfoEXT info) const
// -> VkDebugUtilsMessengerEXT;
//
// /* destroy functions */
// void destroy_surface(VkSurfaceKHR surface) const;
//
// void destroy_messenger(VkDebugUtilsMessengerEXT messenger) const;
//
// [[nodiscard]] auto enumerate_gpus() const -> std::vector<VkPhysicalDevice>;
private: private:
static auto instance() -> IInstance & static auto instance() -> IInstance &
{ {
@ -42,8 +56,7 @@ private:
} // namespace lt::renderer::vkb } // namespace lt::renderer::vkb
/** @todo(Light): unimplemented in gcc -- is it even right to use a private fragment? */ module :private;
// module :private;
namespace lt::renderer::vkb { namespace lt::renderer::vkb {
Instance::Instance() Instance::Instance()
@ -68,7 +81,7 @@ Instance::Instance()
Setting { .name = "enable_message_limit", .values = true }, Setting { .name = "enable_message_limit", .values = true },
Setting { Setting {
.name = "duplicate_message_limit", .name = "duplicate_message_limit",
.values = std::numeric_limits<u32>::max(), .values = std::numeric_limits<std::uint32_t>::max(),
}, },
Setting { Setting {
.name = "report_flags", .name = "report_flags",
@ -76,6 +89,7 @@ Instance::Instance()
}, },
}; };
using Layer = vk::Instance::Layer; using Layer = vk::Instance::Layer;
m_instance = vk::Instance( m_instance = vk::Instance(
vk::Instance::CreateInfo { vk::Instance::CreateInfo {
@ -96,4 +110,41 @@ Instance::Instance()
m_instance.load_functions(); m_instance.load_functions();
} }
// auto Instance::enumerate_gpus() const -> std::vector<VkPhysicalDevice>
// {
// auto count = 0u;
// vkc(vk_enumerate_physical_devices(m_instance, &count, nullptr));
// debug::ensure(count != 0u, "Failed to find any gpus with Vulkan support");
//
// auto gpus = std::vector<VkPhysicalDevice>(count);
// vkc(vk_enumerate_physical_devices(m_instance, &count, gpus.data()));
// return gpus;
// }
//
// auto Instance::create_xlib_surface(VkXlibSurfaceCreateInfoKHR info) const -> VkSurfaceKHR
// {
// auto *value = VkSurfaceKHR {};
// vk_create_xlib_surface_khr(m_instance, &info, m_allocator, &value);
//
// return value;
// }
//
// [[nodiscard]] auto Instance::create_messenger(VkDebugUtilsMessengerCreateInfoEXT info) const
// -> VkDebugUtilsMessengerEXT
// {
// auto *messenger = VkDebugUtilsMessengerEXT {};
// vkc(vk_create_debug_messenger(m_instance, &info, m_allocator, &messenger));
// return messenger;
// }
//
// void Instance::destroy_surface(VkSurfaceKHR surface) const
// {
// vk_destroy_surface_khr(m_instance, surface, m_allocator);
// }
//
// void Instance::destroy_messenger(VkDebugUtilsMessengerEXT messenger) const
// {
// vk_destroy_debug_messenger(m_instance, messenger, m_allocator);
// }
} // namespace lt::renderer::vkb } // namespace lt::renderer::vkb

View file

@ -1,6 +1,4 @@
export module renderer.vk.pass; export module renderer.vk.pass;
import preliminary;
import renderer.data; import renderer.data;
import renderer.vk.api_wrapper; import renderer.vk.api_wrapper;
import renderer.vk.device; import renderer.vk.device;
@ -9,10 +7,11 @@ import assets.shader;
import assets.metadata; import assets.metadata;
import memory.null_on_move; import memory.null_on_move;
import renderer.frontend; import renderer.frontend;
import std;
export namespace lt::renderer::vkb { namespace lt::renderer::vkb {
class Pass: public IPass export class Pass: public IPass
{ {
public: public:
Pass( Pass(
@ -52,9 +51,10 @@ private:
} // namespace lt::renderer::vkb } // namespace lt::renderer::vkb
/** @todo(Light): unimplemented in gcc -- is it even right to use a private fragment? */
// module :private; module :private;
namespace lt::renderer::vkb { using namespace ::lt::renderer::vkb;
using namespace ::lt::renderer;
using enum vk::DescriptorSetLayout::Binding::FlagBits; using enum vk::DescriptorSetLayout::Binding::FlagBits;
@ -80,6 +80,36 @@ Pass::Pass(
.push_constant_ranges = { { vk::ShaderStageFlags::vertex_bit, 0u, sizeof(FrameConstants) } } .push_constant_ranges = { { vk::ShaderStageFlags::vertex_bit, 0u, sizeof(FrameConstants) } }
})) }))
{ {
// auto pool_size = VkDescriptorPoolSize {
// .type = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER,
// .descriptorCount = descriptor_count,
// };
//
// m_descriptor_pool = m_device->create_desscriptor_pool(
// {
// .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO,
// .poolSizeCount = 1u,
// .pPoolSizes = &pool_size,
// }
// );
//
// auto descriptor_set_variable_descriptor_count_info
// = VkDescriptorSetVariableDescriptorCountAllocateInfo {
// .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_VARIABLE_DESCRIPTOR_COUNT_ALLOCATE_INFO,
// .descriptorSetCount = 1u,
// .pDescriptorCounts = &descriptor_count,
// };
//
// m_vertices_descriptor_set = m_device->allocate_descriptor_set(
// VkDescriptorSetAllocateInfo {
// .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO,
// .pNext = &descriptor_set_variable_descriptor_count_info,
// .descriptorPool = m_descriptor_pool,
// .descriptorSetCount = 1u,
// .pSetLayouts = &m_vertices_descriptor_set_layout,
// }
// );
auto shaders = std::vector<std::pair<vk::ShaderModule, vk::ShaderStageFlags::T>> {}; auto shaders = std::vector<std::pair<vk::ShaderModule, vk::ShaderStageFlags::T>> {};
shaders.emplace_back( shaders.emplace_back(
vk::ShaderModule( vk::ShaderModule(
@ -122,5 +152,3 @@ Pass::Pass(
} }
); );
} }
} // namespace lt::renderer::vkb

View file

@ -1,9 +1,7 @@
export module renderer.vk.renderer; export module renderer.vk.renderer;
import preliminary;
import time;
import logger; import logger;
import assets.shader; import assets.shader;
import debug.assertions;
import renderer.vk.api_wrapper; import renderer.vk.api_wrapper;
import memory.reference; import memory.reference;
import memory.null_on_move; import memory.null_on_move;
@ -16,17 +14,19 @@ import renderer.vk.buffer;
import renderer.vk.pass; import renderer.vk.pass;
import renderer.data; import renderer.data;
import renderer.frontend; import renderer.frontend;
import std;
export namespace lt::renderer::vkb { namespace lt::renderer::vkb {
class Renderer: public IRenderer // NOLINTNEXTLINE
export class Renderer: public IRenderer
{ {
public: public:
Renderer( Renderer(
class IGpu *gpu, class IGpu *gpu,
class IDevice *device, class IDevice *device,
class ISwapchain *swapchain, class ISwapchain *swapchain,
u32 max_frames_in_flight std::uint32_t max_frames_in_flight
); );
~Renderer() override ~Renderer() override
@ -35,14 +35,14 @@ public:
{ {
m_device->vk().wait_idle(); m_device->vk().wait_idle();
} }
catch (const std::exception &exp) catch (std::exception &exp)
{ {
log::error("Failed to wait idle on device in renderer destructor:"); log::error("Failed to wait idle on device in renderer destructor");
log::error("\twhat: {}", exp.what());
} }
} }
[[nodiscard]] auto frame(u32 frame_idx, std::function<void()> submit_scene) -> Result override; [[nodiscard]] auto frame(std::uint32_t frame_idx, std::function<void()> submit_scene)
-> Result override;
void replace_swapchain(ISwapchain *swapchain) override; void replace_swapchain(ISwapchain *swapchain) override;
@ -57,11 +57,11 @@ public:
) override; ) override;
private: private:
void record_cmd(vk::CommandBuffer &cmd, u32 image_idx); void record_cmd(vk::CommandBuffer &cmd, std::uint32_t image_idx);
void map_buffers(u32 frame_idx); void map_buffers(std::uint32_t frame_idx);
u32 m_max_frames_in_flight {}; std::uint32_t m_max_frames_in_flight {};
Device *m_device {}; Device *m_device {};
@ -79,7 +79,7 @@ private:
std::vector<vk::Semaphore> m_submit_semaphores; std::vector<vk::Semaphore> m_submit_semaphores;
math::vec2_u32 m_resolution; math::uvec2 m_resolution;
FrameConstants m_frame_constants; FrameConstants m_frame_constants;
@ -87,13 +87,13 @@ private:
Buffer m_staging_buffer; Buffer m_staging_buffer;
size_t m_staging_offset; std::size_t m_staging_offset;
std::span<byte> m_staging_map; std::span<std::byte> m_staging_map;
std::span<components::Sprite::Vertex> m_sprite_vertex_map; std::span<components::Sprite::Vertex> m_sprite_vertex_map;
size_t m_current_sprite_idx; std::size_t m_current_sprite_idx;
vk::DescriptorPool m_global_set_pool; vk::DescriptorPool m_global_set_pool;
@ -102,11 +102,15 @@ private:
} // namespace lt::renderer::vkb } // namespace lt::renderer::vkb
/** @todo(Light): unimplemented in gcc -- is it even right to use a private fragment? */ module :private;
// module :private;
namespace lt::renderer::vkb { namespace lt::renderer::vkb {
Renderer::Renderer(IGpu *gpu, IDevice *device, ISwapchain *swapchain, u32 max_frames_in_flight) Renderer::Renderer(
IGpu *gpu,
IDevice *device,
ISwapchain *swapchain,
std::uint32_t max_frames_in_flight
)
: m_device(static_cast<Device *>(device)) : m_device(static_cast<Device *>(device))
, m_swapchain(static_cast<Swapchain *>(swapchain)) , m_swapchain(static_cast<Swapchain *>(swapchain))
, m_resolution(m_swapchain->get_resolution()) , m_resolution(m_swapchain->get_resolution())
@ -170,9 +174,10 @@ Renderer::Renderer(IGpu *gpu, IDevice *device, ISwapchain *swapchain, u32 max_fr
} }
}; };
[[nodiscard]] auto Renderer::frame(u32 frame_idx, std::function<void()> submit_scene) -> Result [[nodiscard]] auto Renderer::frame(std::uint32_t frame_idx, std::function<void()> submit_scene)
-> Result
{ {
ensure( debug::ensure(
frame_idx < m_max_frames_in_flight, frame_idx < m_max_frames_in_flight,
"Failed to draw: frame_idx >= max_frames_in_flight ({} >= {})", "Failed to draw: frame_idx >= max_frames_in_flight ({} >= {})",
frame_idx, frame_idx,
@ -188,10 +193,7 @@ Renderer::Renderer(IGpu *gpu, IDevice *device, ISwapchain *swapchain, u32 max_fr
frame_fence.reset(); frame_fence.reset();
map_buffers(frame_idx); map_buffers(frame_idx);
submit_scene();
// WIP(Light): submit the scene!
ignore = submit_scene;
// submit_scene();
record_cmd(cmd, image_idx); record_cmd(cmd, image_idx);
auto &submit_semaphore = m_submit_semaphores[image_idx]; auto &submit_semaphore = m_submit_semaphores[image_idx];
@ -223,7 +225,7 @@ void Renderer::replace_swapchain(ISwapchain *swapchain)
m_resolution = m_swapchain->get_resolution(); m_resolution = m_swapchain->get_resolution();
} }
void Renderer::map_buffers(u32 frame_idx) void Renderer::map_buffers(std::uint32_t frame_idx)
{ {
using components::Sprite; using components::Sprite;
@ -240,7 +242,7 @@ void Renderer::map_buffers(u32 frame_idx)
); );
} }
void Renderer::record_cmd(vk::CommandBuffer &cmd, u32 image_idx) void Renderer::record_cmd(vk::CommandBuffer &cmd, std::uint32_t image_idx)
{ {
m_staging_map = {}; m_staging_map = {};
m_sprite_vertex_map = {}; m_sprite_vertex_map = {};
@ -248,35 +250,35 @@ void Renderer::record_cmd(vk::CommandBuffer &cmd, u32 image_idx)
m_staging_buffer.unmap(); m_staging_buffer.unmap();
// if (m_current_sprite_idx) if (m_current_sprite_idx)
// { {
// cmd.copy( cmd.copy(
// { {
// .src_buffer = &m_staging_buffer.vk(), .src_buffer = &m_staging_buffer.vk(),
// .dst_buffer = &m_vertex_buffer.vk(), .dst_buffer = &m_vertex_buffer.vk(),
// .src_offset = m_staging_offset, .src_offset = m_staging_offset,
// .dst_offset = m_staging_offset, .dst_offset = m_staging_offset,
// .size = m_current_sprite_idx * sizeof(components::Sprite::Vertex), .size = m_current_sprite_idx * sizeof(components::Sprite::Vertex),
// } }
// ); );
// } }
// cmd.push_constants( cmd.push_constants(
// { {
// .layout = &m_pass->get_pipeline_layout(), .layout = &m_pass->get_pipeline_layout(),
// .shader_stages = vk::ShaderStageFlags::vertex_bit, .shader_stages = vk::ShaderStageFlags::vertex_bit,
// .offset = 0u, .offset = 0u,
// .size = sizeof(FrameConstants), .size = sizeof(FrameConstants),
// .data = &m_frame_constants, .data = &m_frame_constants,
// } }
// ); );
//
// cmd.bind_descriptor_set( cmd.bind_descriptor_set(
// m_global_set, m_global_set,
// vk::Pipeline::BindPoint::graphics, vk::Pipeline::BindPoint::graphics,
// m_pass->get_pipeline_layout(), m_pass->get_pipeline_layout(),
// 0 0
// ); );
using AccessFlagBits = vk::CommandBuffer::ImageBarrierInfo::AccessFlagBits; using AccessFlagBits = vk::CommandBuffer::ImageBarrierInfo::AccessFlagBits;
cmd.image_barrier( cmd.image_barrier(
@ -292,10 +294,9 @@ void Renderer::record_cmd(vk::CommandBuffer &cmd, u32 image_idx)
} }
); );
static lt::time::Timer timer;
using Attachment = vk::CommandBuffer::RenderingInfo::AttachmentInfo; using Attachment = vk::CommandBuffer::RenderingInfo::AttachmentInfo;
cmd.begin_rendering({ cmd.begin_rendering(
{
.area_offset = {0u, 0u,}, .area_offset = {0u, 0u,},
.area_extent = m_resolution, .area_extent = m_resolution,
.color_attachments = std::vector<Attachment> { .color_attachments = std::vector<Attachment> {
@ -304,34 +305,30 @@ void Renderer::record_cmd(vk::CommandBuffer &cmd, u32 image_idx)
.layout = vk::Image::Layout::color_attachment_optimal, .layout = vk::Image::Layout::color_attachment_optimal,
.load_operation = Attachment::LoadOperation::clear, .load_operation = Attachment::LoadOperation::clear,
.store_operation = Attachment::StoreOperation::store, .store_operation = Attachment::StoreOperation::store,
.color_clear_values = { .color_clear_values = {.5f, .5f, .5f, 1.f}
static_cast<float>(std::sin(timer.elapsed_time().count())),
static_cast<float>(std::cos(timer.elapsed_time().count() * 2.0)),
static_cast<float>(std::sin(timer.elapsed_time().count() / 2.0)),
1.f
} }
} }
} }
}); );
// cmd.bind_pipeline(m_pass->get_pipeline(), vk::Pipeline::BindPoint::graphics); cmd.bind_pipeline(m_pass->get_pipeline(), vk::Pipeline::BindPoint::graphics);
// cmd.set_viewport( cmd.set_viewport(
// { {
// .origin = {}, .origin = {},
// .extent = { static_cast<f32>(m_resolution.x), static_cast<f32>(m_resolution.y) }, .extent = { static_cast<float>(m_resolution.x), static_cast<float>(m_resolution.y) },
// .min_depth = 0.0f, .min_depth = 0.0f,
// .max_depth = 1.0f, .max_depth = 1.0f,
// } }
// ); );
// cmd.set_scissor({ .offset = {}, .extent = m_resolution }); cmd.set_scissor({ .offset = {}, .extent = m_resolution });
// cmd.draw( cmd.draw(
// { {
// .vertex_count = static_cast<u32>(m_current_sprite_idx), .vertex_count = static_cast<std::uint32_t>(m_current_sprite_idx),
// .instance_count = 1u, .instance_count = 1u,
// .first_vertex = 0u, .first_vertex = 0u,
// .first_instance = 0u, .first_instance = 0u,
// } }
// ); );
//
cmd.end_rendering(); cmd.end_rendering();
cmd.image_barrier( cmd.image_barrier(
{ {

View file

@ -1,6 +1,5 @@
export module renderer.vk.surface; export module renderer.vk.surface;
import debug.assertions;
import preliminary;
import ecs.entity; import ecs.entity;
import ecs.registry; import ecs.registry;
import memory.null_on_move; import memory.null_on_move;
@ -10,9 +9,9 @@ import renderer.frontend;
import renderer.vk.instance; import renderer.vk.instance;
import renderer.vk.api_wrapper; import renderer.vk.api_wrapper;
export namespace lt::renderer::vkb { namespace lt::renderer::vkb {
class Surface: public ISurface export class Surface: public ISurface
{ {
public: public:
Surface(IInstance *instance, const ecs::Entity &surface_entity); Surface(IInstance *instance, const ecs::Entity &surface_entity);
@ -22,7 +21,7 @@ public:
return m_surface; return m_surface;
} }
[[nodiscard]] auto get_framebuffer_size() const -> math::vec2_u32 override; [[nodiscard]] auto get_framebuffer_size() const -> math::uvec2 override;
private: private:
vk::Surface m_surface; vk::Surface m_surface;
@ -32,8 +31,7 @@ private:
} // namespace lt::renderer::vkb } // namespace lt::renderer::vkb
/** @todo(Light): unimplemented in gcc -- is it even right to use a private fragment? */ module :private;
// module :private;
namespace lt::renderer::vkb { namespace lt::renderer::vkb {
Surface::Surface(IInstance *instance, const ecs::Entity &surface_entity) Surface::Surface(IInstance *instance, const ecs::Entity &surface_entity)
@ -43,25 +41,25 @@ Surface::Surface(IInstance *instance, const ecs::Entity &surface_entity)
#if defined(LIGHT_PLATFORM_LINUX) #if defined(LIGHT_PLATFORM_LINUX)
ensure( debug::ensure(
component.get_native_data().display, component.get_native_data().display,
"Failed to initialize vk::Surface: null Wayland display" "Failed to initialize vk::Surface: null x-display"
); );
ensure( debug::ensure(
component.get_native_data().surface, component.get_native_data().window,
"Failed to initialize vk::Surface: null Wayland surface" "Failed to initialize vk::Surface: null x-window"
); );
m_surface = vk::Surface( m_surface = vk::Surface(
static_cast<Instance *>(instance)->vk(), static_cast<Instance *>(instance)->vk(),
vk::Surface::CreateInfo { vk::Surface::CreateInfo {
.display = component.get_native_data().display, .display = component.get_native_data().display,
.surface = component.get_native_data().surface, .window = component.get_native_data().window,
} }
); );
#elif defined(LIGHT_PLATFORM_WINDOWS) #elif defined(LIGHT_PLATFORM_WINDOWS)
ensure( debug::ensure(
component.get_native_data().window, component.get_native_data().window,
"Failed to initialize vk::Surface: null win32 window handle" "Failed to initialize vk::Surface: null win32 window handle"
); );
@ -79,7 +77,7 @@ Surface::Surface(IInstance *instance, const ecs::Entity &surface_entity)
#endif #endif
} }
[[nodiscard]] auto Surface::get_framebuffer_size() const -> math::vec2_u32 [[nodiscard]] auto Surface::get_framebuffer_size() const -> math::uvec2
{ {
return m_surface_entity.get<surface::SurfaceComponent>().get_resolution(); return m_surface_entity.get<surface::SurfaceComponent>().get_resolution();
} }

View file

@ -1,6 +1,4 @@
export module renderer.vk.swapchain; export module renderer.vk.swapchain;
import preliminary;
import renderer.vk.api_wrapper; import renderer.vk.api_wrapper;
import renderer.vk.surface; import renderer.vk.surface;
import renderer.vk.device; import renderer.vk.device;
@ -10,10 +8,11 @@ import renderer.frontend;
import math.vec2; import math.vec2;
import memory.null_on_move; import memory.null_on_move;
import logger; import logger;
import std;
export namespace lt::renderer::vkb { namespace lt::renderer::vkb {
class Swapchain: public ISwapchain export class Swapchain: public ISwapchain
{ {
public: public:
Swapchain(ISurface *surface, IGpu *gpu, IDevice *device); Swapchain(ISurface *surface, IGpu *gpu, IDevice *device);
@ -23,7 +22,7 @@ public:
return m_swapchain; return m_swapchain;
} }
[[nodiscard]] auto get_resolution() const -> math::vec2_u32 [[nodiscard]] auto get_resolution() const -> math::uvec2
{ {
return m_resolution; return m_resolution;
} }
@ -33,17 +32,17 @@ public:
return m_format; return m_format;
} }
[[nodiscard]] auto get_image_count() const -> size_t [[nodiscard]] auto get_image_count() const -> std::size_t
{ {
return m_images.size(); return m_images.size();
} }
[[nodiscard]] auto get_image_view(u32 idx) -> vk::ImageView & [[nodiscard]] auto get_image_view(std::uint32_t idx) -> vk::ImageView &
{ {
return m_image_views[idx]; return m_image_views[idx];
} }
[[nodiscard]] auto get_image(u32 idx) -> vk::Image & [[nodiscard]] auto get_image(std::uint32_t idx) -> vk::Image &
{ {
return m_images[idx]; return m_images[idx];
} }
@ -51,8 +50,8 @@ public:
private: private:
[[nodiscard]] auto get_optimal_image_count( [[nodiscard]] auto get_optimal_image_count(
vk::Surface::Capabilities capabilities, vk::Surface::Capabilities capabilities,
u32 desired_image_count std::uint32_t desired_image_count
) const -> u32; ) const -> std::uint32_t;
Gpu *m_gpu; Gpu *m_gpu;
@ -66,15 +65,15 @@ private:
std::vector<vk::ImageView> m_image_views; std::vector<vk::ImageView> m_image_views;
math::vec2_u32 m_resolution {}; math::uvec2 m_resolution {};
vk::Format m_format {}; vk::Format m_format {};
}; };
} // namespace lt::renderer::vkb } // namespace lt::renderer::vkb
/** @todo(Light): unimplemented in gcc -- is it even right to use a private fragment? */
// module :private; module :private;
namespace lt::renderer::vkb { namespace lt::renderer::vkb {
Swapchain::Swapchain(ISurface *surface, IGpu *gpu, IDevice *device) Swapchain::Swapchain(ISurface *surface, IGpu *gpu, IDevice *device)
@ -82,28 +81,16 @@ Swapchain::Swapchain(ISurface *surface, IGpu *gpu, IDevice *device)
, m_gpu(static_cast<Gpu *>(gpu)) , m_gpu(static_cast<Gpu *>(gpu))
, m_device(static_cast<Device *>(device)) , m_device(static_cast<Device *>(device))
{ {
auto capabilities = m_gpu->vk().get_surface_capabilities(m_surface->vk()); static auto idx = 0u;
const auto capabilities = m_gpu->vk().get_surface_capabilities(m_surface->vk());
const auto formats = m_gpu->vk().get_surface_formats(m_surface->vk()); const auto formats = m_gpu->vk().get_surface_formats(m_surface->vk());
// TODO(Light): parameterize // TODO(Light): parameterize
constexpr auto desired_image_count = u32 { 3u }; constexpr auto desired_image_count = std::uint32_t { 3u };
const auto surface_format = formats.front(); const auto surface_format = formats.front();
m_format = surface_format.format; m_format = surface_format.format;
if (capabilities.current_extent.x == std::numeric_limits<u32>::max())
{
log::info(
"Vulkan surface capabilities current extent is uint32 max... This indicates that the "
"surface size will be determined by the extent of a swapchain targeting the surface."
);
// TODO(Light): Take surface extent as swapchain creation argument...
capabilities.current_extent.x = 800u;
capabilities.current_extent.y = 600u;
}
static auto swapchain_idx = 0u;
m_swapchain = vk::Swapchain( m_swapchain = vk::Swapchain(
m_device->vk(), m_device->vk(),
m_surface->vk(), m_surface->vk(),
@ -114,9 +101,9 @@ Swapchain::Swapchain(ISurface *surface, IGpu *gpu, IDevice *device)
.extent = capabilities.current_extent, .extent = capabilities.current_extent,
.min_image_count = get_optimal_image_count(capabilities, desired_image_count), .min_image_count = get_optimal_image_count(capabilities, desired_image_count),
.queue_family_indices = m_device->get_family_indices(), .queue_family_indices = m_device->get_family_indices(),
.present_mode = vk::Swapchain::PresentMode::mailbox, .present_mode = vk::Swapchain::PresentMode::immediate,
.pre_transform = capabilities.current_transform, .pre_transform = capabilities.current_transform,
.name = std::format("swapchain {}", swapchain_idx++), .name = std::format("swapchain {}", idx++),
} }
); );
m_resolution = capabilities.current_extent; m_resolution = capabilities.current_extent;
@ -156,8 +143,8 @@ Swapchain::Swapchain(ISurface *surface, IGpu *gpu, IDevice *device)
[[nodiscard]] auto Swapchain::get_optimal_image_count( [[nodiscard]] auto Swapchain::get_optimal_image_count(
vk::Surface::Capabilities capabilities, vk::Surface::Capabilities capabilities,
u32 desired_image_count std::uint32_t desired_image_count
) const -> u32 ) const -> std::uint32_t
{ {
const auto min_image_count = capabilities.min_image_count; const auto min_image_count = capabilities.min_image_count;
const auto max_image_count = capabilities.max_image_count; const auto max_image_count = capabilities.max_image_count;

View file

@ -1,3 +0,0 @@
add_executable(sandbox sandbox.cpp)
target_link_libraries(sandbox PRIVATE preliminary logger bitwise memory time test math assets app ecs surface renderer input mirror)

View file

@ -1,159 +0,0 @@
import preliminary;
import time;
import logger;
import renderer.system;
import renderer.frontend;
import surface.system;
import surface.events;
import surface.requests;
import ecs.entity;
import input.codes;
import ecs.registry;
import memory.scope;
import memory.reference;
import logger;
import math.vec2;
import app.system;
constexpr auto title = "TestWindow";
constexpr auto width = 800u;
constexpr auto height = 600u;
constexpr auto vsync = true;
constexpr auto visible = true;
template<class... Ts>
struct overloads: Ts...
{
using Ts::operator()...;
};
void renderer_debug_callback(
lt::renderer::IDebugger::MessageSeverity message_severity,
lt::renderer::IDebugger::MessageType message_type,
lt::renderer::IDebugger::MessageData data,
std::any &user_data
)
{
ignore = message_severity;
ignore = message_type;
ignore = user_data;
lt::log::trace("< Renderer > ==> {}", std::string { data.message });
}
auto main() -> i32
try
{
auto registry = lt::memory::create_ref<lt::ecs::Registry>();
auto surface_system = lt::surface::System { registry };
auto entity = registry->create_entity();
lt::log::trace("Creating surface component");
surface_system.create_surface_component(
entity,
lt::surface::SurfaceComponent::CreateInfo {
.title = title,
.position = { 500, 500 },
.resolution = { width, height },
.vsync = vsync,
.visible = visible,
}
);
auto &window = registry->get<lt::surface::SurfaceComponent>(entity);
const auto config = lt::renderer::System::Configuration {
.target_api = lt::renderer::Api::vulkan,
.max_frames_in_flight = 3u,
};
const auto debug_callback_info = lt::renderer::IDebugger::CreateInfo {
.severities = lt::renderer::IDebugger::MessageSeverity::all,
.types = lt::renderer::IDebugger::MessageType::all,
.callback = &renderer_debug_callback,
.user_data = nullptr,
};
const auto surface_entity = lt::ecs::Entity { registry, entity };
auto renderer_system = lt::renderer::System { lt::renderer::System::CreateInfo {
config,
registry,
surface_entity,
debug_callback_info,
} };
auto should_close = false;
const auto visitor = overloads {
[&](const lt::surface::ClosedEvent &) {
lt::log::info("Closing due to: Window X button pressed");
should_close = true;
},
[&](const lt::surface::MovedEvent &event) {
lt::log::info("Moved: {}", event.get_position());
},
[&](const lt::surface::ResizedEvent &event) {
lt::log::info("Resized: {}", event.get_size());
},
[&](const lt::surface::LostFocusEvent &) { lt::log::info("Lost focus"); },
[&](const lt::surface::GainFocusEvent &) { lt::log::info("Gain focus"); },
[&](const lt::surface::KeyPressedEvent &event) {
if (event.get_key() == lt::Key::escape)
{
lt::log::info("Closing due to: Escape key pressed");
should_close = true;
}
if (event.get_key() == lt::Key::q)
{
lt::log::info("Closing due to: Q key pressed");
should_close = true;
}
lt::log::info("Key pressed: {}", event.get_key());
},
[&](const lt::surface::KeyReleasedEvent &event) {
lt::log::info("Key released: {}", event.get_key());
},
[&](const lt::surface::PointerEvent &event) {
lt::log::info("Pointer: {}", event.get_position());
}
};
auto timer = lt::time::Timer {};
while (!should_close)
{
if (timer.elapsed_time() > std::chrono::milliseconds { 250 })
{
const auto [width, height] = window.get_resolution();
window.push_request(
lt::surface::ModifyResolutionRequest {
.resolution = { width + 50u, height + 50u },
}
);
lt::log::trace("mrrp");
timer.reset();
}
surface_system.tick({});
renderer_system.tick({});
for (const auto &event : window.peek_events())
{
std::visit(visitor, event);
}
}
}
catch (const std::exception &exp)
{
lt::log::critical("Aborting due to uncaught std::exception:");
lt::log::critical("\twhat: {}", exp.what());
}
catch (...)
{
lt::log::critical("Aborting due to uncaught non std::exception!");
}

View file

@ -1,27 +1,23 @@
module; module;
#if defined(LIGHT_PLATFORM_LINUX) #if defined(LIGHT_PLATFORM_LINUX)
struct wl_display; typedef struct _XDisplay Display;
struct wl_surface;
struct xdg_surface;
struct xdg_toplevel;
#else defined(LIGHT_PLATFORM_WINDOWS) #else defined(LIGHT_PLATFORM_WINDOWS)
#include <Windows.h> #include <Windows.h>
#endif #endif
export module surface.system:components; export module surface.system:components;
import std;
import preliminary;
import math.vec2; import math.vec2;
import surface.events; import surface.events;
import surface.requests; import surface.requests;
export namespace lt::surface { namespace lt::surface {
/** Represents a platform's surface (eg. a Window). /** Represents a platform's surface (eg. a Window).
* *
* @note This is a "system component" * @note This is a "system component"
*/ */
class SurfaceComponent export class SurfaceComponent
{ {
public: public:
friend class System; friend class System;
@ -34,7 +30,9 @@ public:
GainFocusEvent, GainFocusEvent,
KeyPressedEvent, KeyPressedEvent,
KeyReleasedEvent, KeyReleasedEvent,
PointerEvent>; MouseMovedEvent,
ButtonPressedEvent,
ButtonReleasedEvent>;
using Request = std::variant< using Request = std::variant<
ModifyTitleRequest, ModifyTitleRequest,
@ -45,13 +43,9 @@ public:
#if defined(LIGHT_PLATFORM_LINUX) #if defined(LIGHT_PLATFORM_LINUX)
struct NativeData struct NativeData
{ {
wl_display *display; Display *display;
std::uint32_t window;
wl_surface *surface; unsigned long wm_delete_message;
xdg_surface *shell_surface;
xdg_toplevel *shell_toplevel;
}; };
#elif defined(LIGHT_PLATFORM_WINDOWS) #elif defined(LIGHT_PLATFORM_WINDOWS)
struct NativeData struct NativeData
@ -64,32 +58,28 @@ public:
static constexpr auto max_title_length = 256; static constexpr auto max_title_length = 256;
// TODO(Light): add `center_to_screen` flag
// TODO(Light): add `screen_mode` flag (windowed/full_screen/windowed_full_screen)
struct CreateInfo struct CreateInfo
{ {
std::string title; std::string_view title;
math::vec2_i32 position; math::uvec2 resolution;
math::vec2_u32 resolution;
bool vsync; bool vsync;
bool visible; bool visible;
}; };
[[nodiscard]] auto get_title() const -> std::string // yes copy the title, whatever... [[nodiscard]] auto get_title() const -> std::string_view
{ {
return m_title; return m_title;
} }
[[nodiscard]] auto get_resolution() const -> const math::vec2_u32 & [[nodiscard]] auto get_resolution() const -> const math::uvec2 &
{ {
return m_resolution; return m_resolution;
} }
[[nodiscard]] auto get_position() const -> const math::vec2_i32 & [[nodiscard]] auto get_position() const -> const math::ivec2 &
{ {
return m_position; return m_position;
} }
@ -142,9 +132,9 @@ private:
std::string m_title; std::string m_title;
math::vec2_u32 m_resolution; math::uvec2 m_resolution;
math::vec2_i32 m_position; math::ivec2 m_position;
bool m_vsync; bool m_vsync;

View file

@ -1,8 +1,7 @@
export module surface.events; export module surface.events;
import preliminary;
import input.codes; import input.codes;
import math.vec2; import math.vec2;
import std;
export namespace lt::surface { export namespace lt::surface {
@ -27,6 +26,27 @@ private:
Key m_key; Key m_key;
}; };
class KeyRepeatEvent
{
public:
KeyRepeatEvent(Key key): m_key(key)
{
}
[[nodiscard]] auto get_key() const -> Key
{
return m_key;
}
[[nodiscard]] auto to_string() const -> std::string
{
return std::format("KeyRepeated: {}", std::to_underlying(m_key));
}
private:
Key m_key;
};
class KeyReleasedEvent class KeyReleasedEvent
{ {
public: public:
@ -69,14 +89,10 @@ private:
Key m_character; Key m_character;
}; };
class PointerEvent class MouseMovedEvent
{ {
public: public:
PointerEvent(math::vec2 position): m_position(position) MouseMovedEvent(float x, float y): m_position(x, y)
{
}
PointerEvent(f32 x, f32 y): m_position(x, y)
{ {
} }
@ -85,19 +101,19 @@ public:
return m_position; return m_position;
} }
[[nodiscard]] auto get_x() const -> f32 [[nodiscard]] auto get_x() const -> float
{ {
return m_position.x; return m_position.x;
} }
[[nodiscard]] auto get_y() const -> f32 [[nodiscard]] auto get_y() const -> float
{ {
return m_position.y; return m_position.y;
} }
[[nodiscard]] auto to_string() const -> std::string [[nodiscard]] auto to_string() const -> std::string
{ {
return std::format("Pointer: {}, {}", m_position.x, m_position.y); return std::format("MouseMoved: {}, {}", m_position.x, m_position.y);
} }
private: private:
@ -107,11 +123,11 @@ private:
class WheelScrolledEvent class WheelScrolledEvent
{ {
public: public:
WheelScrolledEvent(f32 offset): m_offset(offset) WheelScrolledEvent(float offset): m_offset(offset)
{ {
} }
[[nodiscard]] auto get_offset() const -> f32 [[nodiscard]] auto get_offset() const -> float
{ {
return m_offset; return m_offset;
} }
@ -124,7 +140,49 @@ public:
} }
private: private:
f32 m_offset; float m_offset;
};
class ButtonPressedEvent
{
public:
ButtonPressedEvent(Key button): m_button(button)
{
}
[[nodiscard]] auto get_button() const -> Key
{
return m_button;
}
[[nodiscard]] auto to_string() const -> std::string
{
return std::format("ButtonPressed: {}", std::to_underlying(m_button));
}
private:
Key m_button;
};
class ButtonReleasedEvent
{
public:
ButtonReleasedEvent(Key button): m_button(button)
{
}
[[nodiscard]] auto get_button() const -> Key
{
return m_button;
}
[[nodiscard]] auto to_string() const -> std::string
{
return std::format("ButtonReleased: {}", std::to_underlying(m_button));
}
private:
Key m_button;
}; };
class ClosedEvent class ClosedEvent
@ -139,15 +197,11 @@ public:
class MovedEvent class MovedEvent
{ {
public: public:
MovedEvent(math::vec2_i32 position): m_position(position) MovedEvent(std::int32_t x, std::int32_t y): m_position(x, y)
{ {
} }
MovedEvent(i32 x, i32 y): m_position(x, y) [[nodiscard]] auto get_position() const -> const math::ivec2 &
{
}
[[nodiscard]] auto get_position() const -> const math::vec2_i32 &
{ {
return m_position; return m_position;
} }
@ -158,21 +212,17 @@ public:
} }
private: private:
math::vec2_i32 m_position; math::ivec2 m_position;
}; };
class ResizedEvent class ResizedEvent
{ {
public: public:
ResizedEvent(math::vec2_u32 size): m_size(size) ResizedEvent(std::uint32_t width, std::uint32_t height): m_size(width, height)
{ {
} }
ResizedEvent(u32 width, u32 height): m_size(width, height) [[nodiscard]] auto get_size() const -> const math::uvec2 &
{
}
[[nodiscard]] auto get_size() const -> const math::vec2_u32 &
{ {
return m_size; return m_size;
} }
@ -183,7 +233,7 @@ public:
} }
private: private:
math::vec2_u32 m_size; math::uvec2 m_size;
}; };
class LostFocusEvent class LostFocusEvent

View file

@ -0,0 +1,506 @@
module;
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/keysym.h>
#include <X11/keysymdef.h>
module surface.system;
import debug.assertions;
import memory.reference;
import surface.requests;
import surface.events;
import logger;
import ecs.registry;
import time;
import std;
import input.codes;
namespace lt::surface {
template<int EventType>
auto XEventTypeEquals(Display *display, XEvent *event, char *winptr) -> int
{
std::ignore = display;
return (
event->type == EventType
&& *(std::bit_cast<const Window *>(winptr))
== std::bit_cast<const XAnyEvent *>(event)->window
);
}
template<class... Ts>
struct overloads: Ts...
{
using Ts::operator()...;
};
void ensure_component_sanity(const SurfaceComponent &component);
constexpr auto all_events_mask = KeyPressMask | //
KeyReleaseMask | //
ButtonPressMask | //
ButtonReleaseMask | //
EnterWindowMask | //
LeaveWindowMask | //
PointerMotionMask | //
KeymapStateMask | //
ExposureMask | //
VisibilityChangeMask | //
StructureNotifyMask | //
FocusChangeMask | //
ColormapChangeMask | //
OwnerGrabButtonMask;
System::System(memory::Ref<ecs::Registry> registry): m_registry(std::move(registry))
{
debug::ensure(m_registry, "Failed to initialize surface system: null registry");
debug::ensure(
m_registry->view<SurfaceComponent>().get_size() == 0,
"Failed to initialize surface system: registry has surface component(s)"
);
m_registry->connect_on_destruct<SurfaceComponent>(
[this](ecs::Registry &registry, ecs::EntityId entity) {
on_surface_destruct(registry, entity);
}
);
}
System::~System()
{
if (!m_registry)
{
return;
}
try
{
// TODO(Light): make registry.remove not invalidate iterators
auto entities_to_remove = std::vector<ecs::EntityId> {};
for (auto &[entity, surface] : m_registry->view<SurfaceComponent>())
{
entities_to_remove.emplace_back(entity);
}
for (auto entity : entities_to_remove)
{
m_registry->remove<SurfaceComponent>(entity);
}
m_registry->disconnect_on_construct<SurfaceComponent>();
m_registry->disconnect_on_destruct<SurfaceComponent>();
}
catch (const std::exception &exp)
{
log::error("Uncaught exception in surface::~System:");
log::error("\twhat: {}", exp.what());
}
}
void System::on_register()
{
}
void System::on_unregister()
{
}
void System::create_surface_component(ecs::EntityId entity, SurfaceComponent::CreateInfo info)
try
{
auto &component = m_registry->add<SurfaceComponent>(entity, info);
auto &surface = m_registry->get<SurfaceComponent>(entity);
const auto &resolution = surface.get_resolution();
const auto &position = surface.get_position();
ensure_component_sanity(surface);
// TODO(Light): refactor "environment" into standalone module
// NOLINTNEXTLINE(concurrency-mt-unsafe)
auto *display_env = std::getenv("DISPLAY");
debug::ensure(display_env != nullptr, "DISPLAY env var not found!");
auto *display = XOpenDisplay(display_env);
debug::ensure(display, "Failed to open XDisplay with DISPLAY: {}", display_env);
auto root_window = XDefaultRootWindow(display);
auto border_width = 0;
auto depth = std::int32_t { CopyFromParent };
auto window_class = CopyFromParent;
auto *visual = (Visual *)CopyFromParent;
auto attribute_value_mask = CWBackPixel | CWEventMask;
auto attributes = XSetWindowAttributes {
.background_pixel = 0xffafe9af,
.event_mask = all_events_mask,
};
typedef struct Hints
{
unsigned long flags;
unsigned long functions;
unsigned long decorations;
long inputMode;
unsigned long status;
} Hints;
auto main_window = XCreateWindow(
display,
root_window,
position.x,
position.y,
resolution.x,
resolution.y,
border_width,
depth,
window_class,
visual,
attribute_value_mask,
&attributes
);
surface.m_native_data.display = display;
surface.m_native_data.window = main_window;
surface.m_native_data.wm_delete_message = XInternAtom(display, "WM_DELETE_WINDOW", False);
XSetWMProtocols(display, main_window, &surface.m_native_data.wm_delete_message, 1);
// code to remove decoration
auto hints = std::array<const unsigned char, 5> { 2, 0, 0, 0, 0 };
const auto motif_hints = XInternAtom(display, "_MOTIF_WM_HINTS", False);
XChangeProperty(
display,
surface.m_native_data.window,
motif_hints,
motif_hints,
32,
PropModeReplace,
hints.data(),
5
);
XMapWindow(display, main_window);
XStoreName(display, main_window, surface.m_title.c_str());
XFlush(display);
if (!surface.is_visible())
{
XUnmapWindow(display, main_window);
}
}
catch (const std::exception &exp)
{
log::error("Exception thrown when on_constructing surface component");
log::error("\tentity: {}", entity);
log::error("\twhat: {}", exp.what());
m_registry->remove<SurfaceComponent>(entity);
}
void System::on_surface_destruct(ecs::Registry &registry, ecs::EntityId entity)
{
const auto &[display, window, _] = registry.get<SurfaceComponent>(entity).get_native_data();
if (!display)
{
log::warn("Surface component destroyed with null display");
return;
}
XDestroyWindow(display, window);
XCloseDisplay(display);
}
void System::handle_events(SurfaceComponent &surface)
{
auto &queue = surface.m_event_queue;
queue.clear();
auto event = XEvent {};
auto &[display, window, wm_delete_message] = surface.m_native_data;
XFlush(display);
while (XEventsQueued(display, QueuedAlready) != 0)
{
XNextEvent(surface.m_native_data.display, &event);
switch (event.type)
{
case KeyPress:
{
queue.emplace_back<KeyPressedEvent>(static_cast<Key>(XLookupKeysym(&event.xkey, 0)));
break;
}
case KeyRelease:
{
queue.emplace_back<KeyReleasedEvent>(static_cast<Key>(XLookupKeysym(&event.xkey, 0)));
break;
}
case ButtonPress:
{
queue.emplace_back<ButtonPressedEvent>(static_cast<Key>(event.xbutton.button));
break;
}
case ButtonRelease:
{
queue.emplace_back<ButtonReleasedEvent>(static_cast<Key>(event.xbutton.button));
break;
}
case FocusIn:
{
queue.emplace_back<GainFocusEvent>({});
break;
}
case FocusOut:
{
queue.emplace_back<LostFocusEvent>({});
break;
}
case ClientMessage:
{
if (event.xclient.data.l[0] == wm_delete_message)
{
queue.emplace_back<ClosedEvent>({});
}
break;
}
case MotionNotify:
{
queue.emplace_back<MouseMovedEvent>(MouseMovedEvent {
static_cast<float>(event.xmotion.x),
static_cast<float>(event.xmotion.y),
});
break;
}
case ConfigureNotify:
{
const auto [prev_width, prev_height] = surface.get_resolution();
const auto new_width = event.xconfigure.width;
const auto new_height = event.xconfigure.height;
if (prev_width != new_width || prev_height != new_height)
{
surface.m_resolution.x = new_width;
surface.m_resolution.y = new_height;
queue.emplace_back<ResizedEvent>(ResizedEvent {
static_cast<std::uint32_t>(new_width),
static_cast<std::uint32_t>(new_height),
});
}
const auto [prev_x, prev_y] = surface.get_position();
const auto new_x = event.xconfigure.x;
const auto new_y = event.xconfigure.y;
if (prev_x != new_x || prev_y != new_y)
{
surface.m_position.x = new_x;
surface.m_position.y = new_y;
queue.emplace_back<MovedEvent>(MovedEvent {
new_x,
new_y,
});
}
break;
}
default: break; /* pass */
}
}
}
void System::handle_requests(SurfaceComponent &surface)
{
const auto visitor = overloads {
[&](const ModifyTitleRequest &request) { modify_title(surface, request); },
[&](const ModifyResolutionRequest &request) { modify_resolution(surface, request); },
[&](const ModifyPositionRequest &request) { modify_position(surface, request); },
[&](const ModifyVisibilityRequest &request) { modify_visiblity(surface, request); },
[&](const auto &) { log::error("Unknown surface request"); },
};
for (const auto &request : surface.peek_requests())
{
std::visit(visitor, request);
}
surface.m_requests.clear();
}
void System::modify_title(SurfaceComponent &surface, const ModifyTitleRequest &request)
{
surface.m_title = request.title;
const auto &[display, window, _] = surface.get_native_data();
XStoreName(display, window, request.title.c_str());
}
void System::modify_resolution(SurfaceComponent &surface, const ModifyResolutionRequest &request)
{
// surface.m_resolution = request.resolution;
auto &[display, window, _] = surface.m_native_data;
const auto &[width, height] = request.resolution;
// XResizeWindow(display, window, width, height);
// get baseline serial number for X requests generated from XResizeWindow
auto serial = NextRequest(display);
// request a new window size from the X server
XResizeWindow(
display,
window,
static_cast<std::uint32_t>(width),
static_cast<std::uint32_t>(height)
);
// flush output queue and wait for X server to processes the request
XSync(display, False);
// The documentation for XResizeWindow includes this important note:
//
// If the override-redirect flag of the window is False and some
// other client has selected SubstructureRedirectMask on the parent,
// the X server generates a ConfigureRequest event, and no further
// processing is performed.
//
// What this means, essentially, is that if this window is a top-level
// window, then it's the window manager (the "other client") that is
// responsible for changing this window's size. So when we call
// XResizeWindow() on a top-level window, then instead of resizing
// the window immediately, the X server informs the window manager,
// and then the window manager sets our new size (usually it will be
// the size we asked for). We receive a ConfigureNotify event when
// our new size has been set.
constexpr auto lifespan = std::chrono::milliseconds { 10 };
auto timer = time::Timer {};
auto event = XEvent {};
while (!XCheckIfEvent(
display,
&event,
XEventTypeEquals<ConfigureNotify>,
reinterpret_cast<XPointer>(&window) // NOLINT
)
|| event.xconfigure.serial < serial)
{
std::this_thread::sleep_for(std::chrono::microseconds { 100 });
if (timer.elapsed_time() > lifespan)
{
log::error("Timed out waiting for XResizeWindow's event");
return;
}
}
// We don't need to update the component's state and handle the event in this funcion.
// Since handle_requests is called before handle_events.
// So we just put the event back into the queue and move on.
XPutBackEvent(display, &event);
XSync(display, False);
XFlush(display);
}
void System::modify_position(SurfaceComponent &surface, const ModifyPositionRequest &request)
{
// surface.m_position = request.position;
auto &[display, window, _] = surface.m_native_data;
const auto &[x, y] = request.position;
// get baseline serial number for X requests generated from XResizeWindow
auto serial = NextRequest(display);
XMoveWindow(display, window, static_cast<int>(x), static_cast<int>(y));
// flush output queue and wait for X server to processes the request
XSync(display, False);
constexpr auto lifespan = std::chrono::milliseconds { 10 };
auto timer = time::Timer {};
auto event = XEvent {};
while (!XCheckIfEvent(
display,
&event,
XEventTypeEquals<ConfigureNotify>,
reinterpret_cast<XPointer>(&window) // NOLINT
)
|| event.xconfigure.serial < serial)
{
std::this_thread::sleep_for(std::chrono::microseconds { 100 });
if (timer.elapsed_time() > lifespan)
{
log::error("Timed out waiting for XMoveWindow's event");
return;
}
}
// We don't need to update the component's state and handle the event in this funcion.
// Since handle_requests is called before handle_events.
// So we just put the event back into the queue and move on.
XPutBackEvent(display, &event);
XSync(display, False);
XFlush(display);
}
void System::modify_visiblity(SurfaceComponent &surface, const ModifyVisibilityRequest &request)
{
const auto &[display, window, _] = surface.get_native_data();
surface.m_visible = request.visible;
if (request.visible)
{
XMapWindow(display, window);
}
else
{
XUnmapWindow(display, window);
}
}
void System::tick(app::TickInfo tick)
{
for (auto &[id, surface] : m_registry->view<SurfaceComponent>())
{
handle_requests(surface);
handle_events(surface);
}
const auto now = std::chrono::steady_clock::now();
m_last_tick_result = app::TickResult {
.info = tick,
.duration = now - tick.start_time,
.end_time = now,
};
}
void ensure_component_sanity(const SurfaceComponent &component)
{
auto [width, height] = component.get_resolution();
debug::ensure(width != 0u, "Received bad values for surface component: width({}) == 0", width);
debug::ensure(
height != 0u,
"Received bad values for surface component: height({}) == 0",
height
);
debug::ensure(
width < SurfaceComponent::max_dimension,
"Received bad values for surface component: width({}) > max_dimension({})",
width,
SurfaceComponent::max_dimension
);
debug::ensure(
height < SurfaceComponent::max_dimension,
"Received bad values for surface component: height({}) > max_dimension({})",
height,
SurfaceComponent::max_dimension
);
debug::ensure(
component.get_title().size() < SurfaceComponent::max_title_length,
"Received bad values for surface component: title.size({}) > max_title_length({})",
component.get_title().size(),
SurfaceComponent::max_title_length
);
}
} // namespace lt::surface
namespace lt {
} // namespace lt

View file

@ -0,0 +1,527 @@
module;
#include <Windows.h>
module surface.system;
import surface.constants;
import debug.assertions;
import memory.reference;
import surface.requests;
import surface.events;
import logger;
import ecs.registry;
import ecs.entity;
import time;
import std;
namespace lt::surface {
template<class... Ts>
struct overloads: Ts...
{
using Ts::operator()...;
};
void ensure_component_sanity(const SurfaceComponent &component);
auto CALLBACK native_window_proc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) -> LRESULT;
System::System(memory::Ref<ecs::Registry> registry): m_registry(std::move(registry))
{
debug::ensure(m_registry, "Failed to initialize surface system: null registry");
debug::ensure(
m_registry->view<SurfaceComponent>().get_size() == 0,
"Failed to initialize surface system: registry has surface component(s)"
);
m_registry->connect_on_destruct<SurfaceComponent>(
[this](ecs::Registry &registry, ecs::EntityId entity) {
on_surface_destruct(registry, entity);
}
);
auto window_class = WNDCLASS {
.lpfnWndProc = native_window_proc,
.hInstance = GetModuleHandle(nullptr),
.lpszClassName = constants::class_name,
};
RegisterClass(&window_class);
}
System::~System()
{
if (!m_registry)
{
return;
}
try
{
// TODO(Light): make registry.remove not invalidate iterators
auto entities_to_remove = std::vector<ecs::EntityId> {};
for (auto &[entity, surface] : m_registry->view<SurfaceComponent>())
{
entities_to_remove.emplace_back(entity);
}
for (auto entity : entities_to_remove)
{
m_registry->remove<SurfaceComponent>(entity);
}
m_registry->disconnect_on_construct<SurfaceComponent>();
m_registry->disconnect_on_destruct<SurfaceComponent>();
}
catch (const std::exception &exp)
{
log::error("Uncaught exception in surface::~System:");
log::error("\twhat: {}", exp.what());
}
}
void System::on_register()
{
}
void System::on_unregister()
{
}
void System::create_surface_component(ecs::EntityId entity, SurfaceComponent::CreateInfo info)
try
{
auto &component = m_registry->add<SurfaceComponent>(entity, info);
auto &surface = m_registry->get<SurfaceComponent>(entity);
const auto &resolution = surface.get_resolution();
const auto &position = surface.get_position();
ensure_component_sanity(surface);
surface.m_native_data.window = CreateWindowEx(
0,
constants::class_name,
info.title.data(),
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT,
CW_USEDEFAULT,
CW_USEDEFAULT,
CW_USEDEFAULT,
nullptr,
nullptr,
GetModuleHandle(nullptr),
nullptr
);
debug::ensure(surface.m_native_data.window, "Failed to create Windows surface component");
ShowWindow(surface.m_native_data.window, SW_NORMAL);
// TODO(Light): refactor "environment" into standalone module
// NOLINTNEXTLINE(concurrency-mt-unsafe)
// auto *display_env = std::getenv("DISPLAY");
// debug::ensure(display_env != nullptr, "DISPLAY env var not found!");
//
// auto *display = XOpenDisplay(display_env);
// debug::ensure(display, "Failed to open XDisplay with DISPLAY: {}", display_env);
//
// auto root_window = XDefaultRootWindow(display);
//
// auto border_width = 0;
// auto depth = std::int32_t { CopyFromParent };
// auto window_class = CopyFromParent;
// auto *visual = (Visual *)CopyFromParent;
//
// auto attribute_value_mask = CWBackPixel | CWEventMask;
// auto attributes = XSetWindowAttributes {
// .background_pixel = 0xffafe9af,
// .event_mask = all_events_mask,
// };
//
// typedef struct Hints
// {
// unsigned long flags;
// unsigned long functions;
// unsigned long decorations;
// long inputMode;
// unsigned long status;
// } Hints;
//
// auto main_window = XCreateWindow(
// display,
// root_window,
// position.x,
// position.y,
// resolution.x,
// resolution.y,
// border_width,
// depth,
// window_class,
// visual,
// attribute_value_mask,
// &attributes
// );
// surface.m_native_data.display = display;
// surface.m_native_data.window = main_window;
//
// surface.m_native_data.wm_delete_message = XInternAtom(display, "WM_DELETE_WINDOW", False);
// XSetWMProtocols(display, main_window, &surface.m_native_data.wm_delete_message, 1);
//
// // code to remove decoration
// auto hints = std::array<const unsigned char, 5> { 2, 0, 0, 0, 0 };
// const auto motif_hints = XInternAtom(display, "_MOTIF_WM_HINTS", False);
//
// XChangeProperty(
// display,
// surface.m_native_data.window,
// motif_hints,
// motif_hints,
// 32,
// PropModeReplace,
// hints.data(),
// 5
// );
//
// XMapWindow(display, main_window);
// XStoreName(display, main_window, surface.m_title.c_str());
// XFlush(display);
//
// if (!surface.is_visible())
// {
// XUnmapWindow(display, main_window);
// }
}
catch (const std::exception &exp)
{
log::error("Exception thrown when on_constructing surface component");
log::error("\tentity: {}", std::uint32_t { entity });
log::error("\twhat: {}", exp.what());
m_registry->remove<SurfaceComponent>(entity);
}
void System::on_surface_destruct(ecs::Registry &registry, ecs::EntityId entity)
{
auto *window = registry.get<SurfaceComponent>(entity).get_native_data().window;
if (!window)
{
log::warn("Surface component destroyed with null window handle");
return;
}
DestroyWindow(window);
}
void System::handle_events(SurfaceComponent &surface)
{
auto &queue = surface.m_event_queue;
queue.clear();
auto message = MSG {};
while (PeekMessage(&message, 0, {}, {}, PM_REMOVE))
{
switch (message.message)
{
}
log::debug("Window message type: {}", std::uint32_t { message.message });
}
// auto event = XEvent {};
// auto &[display, window, wm_delete_message] = surface.m_native_data;
//
// XFlush(display);
// while (XEventsQueued(display, QueuedAlready) != 0)
// {
// XNextEvent(surface.m_native_data.display, &event);
//
// switch (event.type)
// {
// case KeyPress:
// {
// queue.emplace_back<KeyPressedEvent>(
// static_cast<std::uint32_t>(XLookupKeysym(&event.xkey, 0))
// );
// break;
// }
// case KeyRelease:
// {
// queue.emplace_back<KeyReleasedEvent>(
// static_cast<std::uint32_t>(XLookupKeysym(&event.xkey, 0))
// );
// break;
// }
// case ButtonPress:
// {
// queue.emplace_back<ButtonPressedEvent>(static_cast<int>(event.xbutton.button));
// break;
// }
// case ButtonRelease:
// {
// queue.emplace_back<ButtonReleasedEvent>(static_cast<int>(event.xbutton.button));
// break;
// }
// case FocusIn:
// {
// queue.emplace_back<GainFocusEvent>({});
// break;
// }
// case FocusOut:
// {
// queue.emplace_back<LostFocusEvent>({});
// break;
// }
// case ClientMessage:
// {
// if (event.xclient.data.l[0] == wm_delete_message)
// {
// queue.emplace_back<ClosedEvent>({});
// }
//
// break;
// }
// case MotionNotify:
// {
// queue.emplace_back<MouseMovedEvent>(MouseMovedEvent {
// static_cast<float>(event.xmotion.x),
// static_cast<float>(event.xmotion.y),
// });
// break;
// }
// case ConfigureNotify:
// {
// const auto [prev_width, prev_height] = surface.get_resolution();
// const auto new_width = event.xconfigure.width;
// const auto new_height = event.xconfigure.height;
// if (prev_width != new_width || prev_height != new_height)
// {
// surface.m_resolution.x = new_width;
// surface.m_resolution.y = new_height;
// queue.emplace_back<ResizedEvent>(ResizedEvent {
// static_cast<std::uint32_t>(new_width),
// static_cast<std::uint32_t>(new_height),
// });
// }
//
// const auto [prev_x, prev_y] = surface.get_position();
// const auto new_x = event.xconfigure.x;
// const auto new_y = event.xconfigure.y;
// if (prev_x != new_x || prev_y != new_y)
// {
// surface.m_position.x = new_x;
// surface.m_position.y = new_y;
// queue.emplace_back<MovedEvent>(MovedEvent {
// new_x,
// new_y,
// });
// }
// break;
// }
//
// default: break; /* pass */
// }
// }
}
void System::handle_requests(SurfaceComponent &surface)
{
const auto visitor = overloads {
[&](const ModifyTitleRequest &request) { modify_title(surface, request); },
[&](const ModifyResolutionRequest &request) { modify_resolution(surface, request); },
[&](const ModifyPositionRequest &request) { modify_position(surface, request); },
[&](const ModifyVisibilityRequest &request) { modify_visiblity(surface, request); },
[&](const auto &) { log::error("Unknown surface request"); },
};
for (const auto &request : surface.peek_requests())
{
std::visit(visitor, request);
}
surface.m_requests.clear();
}
void System::modify_title(SurfaceComponent &surface, const ModifyTitleRequest &request)
{
surface.m_title = request.title;
// const auto &[display, window, _] = surface.get_native_data();
// XStoreName(display, window, request.title.c_str());
}
void System::modify_resolution(SurfaceComponent &surface, const ModifyResolutionRequest &request)
{
// surface.m_resolution = request.resolution;
// auto &[display, window, _] = surface.m_native_data;
// const auto &[width, height] = request.resolution;
// // XResizeWindow(display, window, width, height);
//
// // get baseline serial number for X requests generated from XResizeWindow
// auto serial = NextRequest(display);
//
// // request a new window size from the X server
// XResizeWindow(
// display,
// window,
// static_cast<std::uint32_t>(width),
// static_cast<std::uint32_t>(height)
// );
//
// // flush output queue and wait for X server to processes the request
// XSync(display, False);
// // The documentation for XResizeWindow includes this important note:
// //
// // If the override-redirect flag of the window is False and some
// // other client has selected SubstructureRedirectMask on the parent,
// // the X server generates a ConfigureRequest event, and no further
// // processing is performed.
// //
// // What this means, essentially, is that if this window is a top-level
// // window, then it's the window manager (the "other client") that is
// // responsible for changing this window's size. So when we call
// // XResizeWindow() on a top-level window, then instead of resizing
// // the window immediately, the X server informs the window manager,
// // and then the window manager sets our new size (usually it will be
// // the size we asked for). We receive a ConfigureNotify event when
// // our new size has been set.
// constexpr auto lifespan = std::chrono::milliseconds { 10 };
// auto timer = time::Timer {};
// auto event = XEvent {};
// while (!XCheckIfEvent(
// display,
// &event,
// XEventTypeEquals<ConfigureNotify>,
// reinterpret_cast<XPointer>(&window) // NOLINT
// )
// || event.xconfigure.serial < serial)
// {
// std::this_thread::sleep_for(std::chrono::microseconds { 100 });
// if (timer.elapsed_time() > lifespan)
// {
// log::error("Timed out waiting for XResizeWindow's event");
// return;
// }
// }
// // We don't need to update the component's state and handle the event in this funcion.
// // Since handle_requests is called before handle_events.
// // So we just put the event back into the queue and move on.
// XPutBackEvent(display, &event);
// XSync(display, False);
// XFlush(display);
}
void System::modify_position(SurfaceComponent &surface, const ModifyPositionRequest &request)
{
// surface.m_position = request.position;
// auto &[display, window, _] = surface.m_native_data;
// const auto &[x, y] = request.position;
//
// // get baseline serial number for X requests generated from XResizeWindow
// auto serial = NextRequest(display);
// XMoveWindow(display, window, static_cast<int>(x), static_cast<int>(y));
//
// // flush output queue and wait for X server to processes the request
// XSync(display, False);
// constexpr auto lifespan = std::chrono::milliseconds { 10 };
// auto timer = time::Timer {};
// auto event = XEvent {};
// while (!XCheckIfEvent(
// display,
// &event,
// XEventTypeEquals<ConfigureNotify>,
// reinterpret_cast<XPointer>(&window) // NOLINT
// )
// || event.xconfigure.serial < serial)
// {
// std::this_thread::sleep_for(std::chrono::microseconds { 100 });
// if (timer.elapsed_time() > lifespan)
// {
// log::error("Timed out waiting for XMoveWindow's event");
// return;
// }
// }
// // We don't need to update the component's state and handle the event in this funcion.
// // Since handle_requests is called before handle_events.
// // So we just put the event back into the queue and move on.
// XPutBackEvent(display, &event);
// XSync(display, False);
// XFlush(display);
}
void System::modify_visiblity(SurfaceComponent &surface, const ModifyVisibilityRequest &request)
{
// const auto &[display, window, _] = surface.get_native_data();
// surface.m_visible = request.visible;
// if (request.visible)
// {
// XMapWindow(display, window);
// }
// else
// {
// XUnmapWindow(display, window);
// }
}
void System::tick(app::TickInfo tick)
{
for (auto &[id, surface] : m_registry->view<SurfaceComponent>())
{
handle_requests(surface);
handle_events(surface);
}
const auto now = std::chrono::steady_clock::now();
m_last_tick_result = app::TickResult {
.info = tick,
.duration = now - tick.start_time,
.end_time = now,
};
}
void ensure_component_sanity(const SurfaceComponent &component)
{
auto [width, height] = component.get_resolution();
debug::ensure(width != 0u, "Received bad values for surface component: width({}) == 0", width);
debug::ensure(
height != 0u,
"Received bad values for surface component: height({}) == 0",
height
);
debug::ensure(
width < SurfaceComponent::max_dimension,
"Received bad values for surface component: width({}) > max_dimension({})",
width,
SurfaceComponent::max_dimension
);
debug::ensure(
height < SurfaceComponent::max_dimension,
"Received bad values for surface component: height({}) > max_dimension({})",
height,
SurfaceComponent::max_dimension
);
debug::ensure(
component.get_title().size() < SurfaceComponent::max_title_length,
"Received bad values for surface component: title.size({}) > max_title_length({})",
component.get_title().size(),
SurfaceComponent::max_title_length
);
}
auto CALLBACK native_window_proc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) -> LRESULT
{
switch (uMsg)
{
case WM_DESTROY:
{
PostQuitMessage(0);
return 0;
}
}
return DefWindowProcA(hwnd, uMsg, wParam, lParam);
}
} // namespace lt::surface

View file

@ -1,7 +1,6 @@
export module surface.requests; export module surface.requests;
import preliminary;
import math.vec2; import math.vec2;
import std;
export namespace lt::surface { export namespace lt::surface {
@ -12,12 +11,12 @@ struct ModifyTitleRequest
struct ModifyResolutionRequest struct ModifyResolutionRequest
{ {
math::vec2_u32 resolution; math::uvec2 resolution;
}; };
struct ModifyPositionRequest struct ModifyPositionRequest
{ {
math::vec2_i32 position; math::ivec2 position;
}; };
struct ModifyVisibilityRequest struct ModifyVisibilityRequest

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,155 @@
#include <ecs/entity.hpp>
#include <ecs/registry.hpp>
#include <memory/reference.hpp>
#include <surface/components.hpp>
#include <surface/system.hpp>
#include <test/fuzz.hpp>
#include <test/test.hpp>
namespace lt::surface {
enum class FuzzAction : uint8_t
{
create_entity,
create_surface_component,
destroy_surface_component,
push_request,
push_event,
tick_system,
count,
};
enum class EventType : uint8_t
{
Closed,
Moved,
Resized,
LostFocus,
GainFocus,
};
void create_surface_component(test::FuzzDataProvider &provider, ecs::Registry &registry)
{
const auto length = std::min(provider.consume<uint32_t>().value_or(16), 255u);
const auto title = provider.consume_string(length).value_or("");
const auto resolution = math::uvec2 {
provider.consume<uint32_t>().value_or(32u),
provider.consume<uint32_t>().value_or(64u),
};
const auto visible = provider.consume<bool>().value_or(false);
const auto vsync = provider.consume<bool>().value_or(false);
try
{
auto entity = registry.create_entity();
registry.add<surface::SurfaceComponent>(
entity,
surface::SurfaceComponent::CreateInfo {
.title = std::move(title),
.resolution = resolution,
.vsync = vsync,
.visible = visible,
}
);
}
catch (const std::exception &exp)
{
std::ignore = exp;
}
}
void remove_surface_component(ecs::Registry &registry)
{
const auto view = registry.view<SurfaceComponent>();
if (!view.is_empty())
{
registry.remove<SurfaceComponent>(view[0].first);
}
}
void push_request(ecs::Registry &registry)
{
}
void push_event(ecs::Registry &registry)
{
}
void check_invariants()
{
}
test::FuzzHarness harness = [](const uint8_t *data, size_t size) {
auto provider = test::FuzzDataProvider { data, size };
auto registry = memory::create_ref<ecs::Registry>();
auto system = surface::System { registry };
while (auto action = provider.consume<uint8_t>())
{
if (*action > std::to_underlying(FuzzAction::count))
{
*action = *action % std::to_underlying(FuzzAction::count);
}
switch (static_cast<FuzzAction>(action.value()))
{
case FuzzAction::create_entity:
{
const auto length = std::min(provider.consume<uint32_t>().value_or(16), 255u);
registry->create_entity();
break;
}
case FuzzAction::create_surface_component:
{
create_surface_component(provider, *registry);
break;
}
case FuzzAction::destroy_surface_component:
{
remove_surface_component(*registry);
break;
}
case FuzzAction::push_event:
{
auto view = registry->view<SurfaceComponent>();
if (!view.is_empty())
{
for (auto &[entity, component] : view)
{
provider.consume<uint8_t>().value_or(0);
// @TODO(Light): push some event
}
}
break;
}
case FuzzAction::push_request:
{
break;
}
case FuzzAction::count:
case FuzzAction::tick_system:
{
system.tick();
break;
}
}
check_invariants();
}
return 0;
};
} // namespace lt::surface

View file

@ -1,30 +1,26 @@
/** @todo(Light): test pointer-invalidation of ecs using this system-> (?) */ import test.test;
import test.expects;
#if defined(LIGHT_PLATFORM_LINUX)
#elif defined(LIGHT_PLATFORM_WINDOWS)
#include <Windows.h>
#include <Winuser.h>
#else
#error "Unsupported platform"
#endif
import test;
import time;
import input.codes;
import logger;
import surface.system; import surface.system;
import surface.events; import surface.events;
import surface.requests; import surface.requests;
import ecs.registry; import ecs.registry;
import memory.scope; import memory.scope;
import memory.reference; import memory.reference;
import logger;
import math.vec2; import math.vec2;
import app.system; import app.system;
import std;
using ::lt::Key;
using ::lt::surface::SurfaceComponent; using ::lt::surface::SurfaceComponent;
using ::lt::surface::System; using ::lt::surface::System;
using ::lt::test::Case;
using ::lt::test::expect_eq;
using ::lt::test::expect_ne;
using ::lt::test::expect_not_nullptr;
using ::lt::test::expect_throw;
using ::lt::test::Suite;
using ::std::ignore;
using ::lt::test::operator""_suite;
[[nodiscard]] auto tick_info() -> lt::app::TickInfo [[nodiscard]] auto tick_info() -> lt::app::TickInfo
{ {
@ -38,8 +34,6 @@ using ::lt::surface::System;
constexpr auto title = "TestWindow"; constexpr auto title = "TestWindow";
constexpr auto width = 800u; constexpr auto width = 800u;
constexpr auto height = 600u; constexpr auto height = 600u;
constexpr auto position_x = 100;
constexpr auto position_y = 200;
constexpr auto vsync = true; constexpr auto vsync = true;
constexpr auto visible = false; constexpr auto visible = false;
@ -57,16 +51,9 @@ public:
return m_registry; return m_registry;
} }
[[nodiscard]] auto system() -> lt::memory::Ref<System>
{
return m_system;
}
auto create_component( auto create_component(
const SurfaceComponent::CreateInfo &info = SurfaceComponent::CreateInfo { SurfaceComponent::CreateInfo info = SurfaceComponent::CreateInfo {
.title = title, .title = title,
.position = { position_x, position_y },
.resolution = { width, height }, .resolution = { width, height },
.vsync = vsync, .vsync = vsync,
.visible = visible, .visible = visible,
@ -74,7 +61,7 @@ public:
) -> std::optional<SurfaceComponent *> ) -> std::optional<SurfaceComponent *>
{ {
auto entity = m_registry->create_entity(); auto entity = m_registry->create_entity();
m_system->create_surface_component(entity, info); m_system.create_surface_component(entity, info);
return &m_registry->get<SurfaceComponent>(entity); return &m_registry->get<SurfaceComponent>(entity);
} }
@ -83,7 +70,7 @@ public:
{ {
#ifdef LIGHT_PLATFORM_LINUX #ifdef LIGHT_PLATFORM_LINUX
expect_not_nullptr(component->get_native_data().display); expect_not_nullptr(component->get_native_data().display);
expect_not_nullptr(component->get_native_data().surface); expect_ne(component->get_native_data().window, 0);
#endif #endif
expect_eq(component->get_resolution().x, width); expect_eq(component->get_resolution().x, width);
@ -96,32 +83,31 @@ public:
private: private:
lt::memory::Ref<lt::ecs::Registry> m_registry = lt::memory::create_ref<lt::ecs::Registry>(); lt::memory::Ref<lt::ecs::Registry> m_registry = lt::memory::create_ref<lt::ecs::Registry>();
lt::memory::Ref<System> m_system = lt::memory::create_ref<System>(m_registry); System m_system { m_registry };
}; };
Suite raii = "raii"_suite = [] { Suite raii = "raii"_suite = [] {
Case { "happy paths" } = [] { Case { "happy path won't throw" } = [] {
auto fixture = Fixture {}; auto fixture = Fixture {};
auto system = fixture.system(); ignore = System { fixture.registry() };
}; };
Case { "unhappy paths" } = [] { Case { "many won't freeze/throw" } = [] {
expect_throw([] { ignore = System { {} }; });
};
Case { "many" } = [] {
auto fixture = Fixture {}; auto fixture = Fixture {};
for (auto idx : std::views::iota(0, 250)) for (auto idx : std::views::iota(0, 250))
{ {
ignore = idx; ignore = System { fixture.registry() };
ignore = fixture.system();
} }
}; };
Case { "unhappy path throws" } = [] {
expect_throw([] { ignore = System { {} }; });
};
Case { "post construct has correct state" } = [] { Case { "post construct has correct state" } = [] {
auto fixture = Fixture {}; auto fixture = Fixture {};
auto system = fixture.system(); auto system = System { fixture.registry() };
expect_eq(fixture.registry()->view<SurfaceComponent>().get_size(), 0); expect_eq(fixture.registry()->view<SurfaceComponent>().get_size(), 0);
}; };
@ -140,44 +126,34 @@ Suite raii = "raii"_suite = [] {
Suite system_events = "system_events"_suite = [] { Suite system_events = "system_events"_suite = [] {
Case { "on_register won't throw" } = [] { Case { "on_register won't throw" } = [] {
auto fixture = Fixture {}; auto fixture = Fixture {};
auto system = fixture.system(); auto system = System { fixture.registry() };
system->on_register(); system.on_register();
expect_eq(fixture.registry()->view<SurfaceComponent>().get_size(), 0); expect_eq(fixture.registry()->view<SurfaceComponent>().get_size(), 0);
}; };
Case { "on_unregister won't throw" } = [] { Case { "on_unregister won't throw" } = [] {
auto fixture = Fixture {}; auto fixture = Fixture {};
auto system = fixture.system(); auto system = System { fixture.registry() };
system->on_register(); system.on_register();
system->on_unregister(); system.on_unregister();
expect_eq(fixture.registry()->view<SurfaceComponent>().get_size(), 0); expect_eq(fixture.registry()->view<SurfaceComponent>().get_size(), 0);
}; };
}; };
Suite registry_events = "registry_events"_suite = [] { Suite registry_events = "registry_events"_suite = [] {
Case { "on_construct initializes component" } = [] { Case { "on_construct<SurfaceComponent> initializes component" } = [] {
auto fixture = Fixture {}; auto fixture = Fixture {};
auto system = fixture.system();
system->tick({});
system->tick({});
const auto &component = fixture.create_component(); const auto &component = fixture.create_component();
system->tick({});
system->tick({});
system->tick({});
expect_eq(fixture.registry()->view<SurfaceComponent>().get_size(), 1); expect_eq(fixture.registry()->view<SurfaceComponent>().get_size(), 1);
system->tick({});
system->tick({});
system->tick({});
fixture.check_values(*component); fixture.check_values(*component);
}; };
Case { "unhappy on_construct throws" } = [] { Case { "unhappy on_construct<SurfaceComponent> throws" } = [] {
auto fixture = Fixture {}; auto fixture = Fixture {};
auto system = fixture.system(); auto system = System { fixture.registry() };
expect_throw([&] { fixture.create_component({ .resolution = { width, 0 } }); }); expect_throw([&] { fixture.create_component({ .resolution = { width, 0 } }); });
@ -202,15 +178,15 @@ Suite registry_events = "registry_events"_suite = [] {
}); });
}; };
Case { "unhappy on_construct removes component" } = [] { Case { "unhappy on_construct<SurfaceComponent> removes component" } = [] {
auto fixture = Fixture {}; auto fixture = Fixture {};
auto system = fixture.system(); auto system = System { fixture.registry() };
expect_throw([&] { fixture.create_component({ .resolution = { width, 0 } }); }); expect_throw([&] { fixture.create_component({ .resolution = { width, 0 } }); });
expect_eq(fixture.registry()->view<SurfaceComponent>().get_size(), 0); expect_eq(fixture.registry()->view<SurfaceComponent>().get_size(), 0);
}; };
Case { "on_destroy cleans up component" } = [] { Case { "on_destrroy<SurfaceComponent> cleans up component" } = [] {
auto fixture = Fixture {}; auto fixture = Fixture {};
auto system = lt::memory::create_scope<System>(fixture.registry()); auto system = lt::memory::create_scope<System>(fixture.registry());
@ -223,60 +199,64 @@ Suite registry_events = "registry_events"_suite = [] {
}; };
}; };
Suite tick = "ticking"_suite = [] { Suite tick = "tick"_suite = [] {
Case { "on empty registry won't throw" } = [] { Case { "ticking on empty registry won't throw" } = [] {
auto fixture = Fixture {}; auto fixture = Fixture {};
fixture.system()->tick(tick_info()); System { fixture.registry() }.tick(tick_info());
}; };
Case { "on non-empty registry won't throw" } = [] { Case { "ticking on non-empty registry won't throw" } = [] {
auto fixture = Fixture {}; auto fixture = Fixture {};
auto system = fixture.system(); auto system = System { fixture.registry() };
fixture.create_component(); fixture.create_component();
system->tick(tick_info()); system.tick(tick_info());
};
}; };
Case { "clears previous tick's events" } = [] { Suite tick_handles_events = "tick_handles_events"_suite = [] {
Case { "ticking clears previous tick's events" } = [] {
auto fixture = Fixture {}; auto fixture = Fixture {};
auto system = fixture.system(); auto system = System { fixture.registry() };
auto &surface = **fixture.create_component(); auto &surface = **fixture.create_component();
// flush window-creation events // flush window-creation events
system->tick(tick_info()); system.tick(tick_info());
expect_eq(surface.peek_events().size(), 0); expect_eq(surface.peek_events().size(), 0);
surface.push_event(lt::surface::MovedEvent({}, {})); surface.push_event(lt::surface::MovedEvent({}, {}));
expect_eq(surface.peek_events().size(), 1); expect_eq(surface.peek_events().size(), 1);
surface.push_event(lt::surface::KeyPressedEvent({})); surface.push_event(lt::surface::ButtonPressedEvent({}));
expect_eq(surface.peek_events().size(), 2); expect_eq(surface.peek_events().size(), 2);
system->tick(tick_info()); system.tick(tick_info());
expect_eq(surface.peek_events().size(), 0); expect_eq(surface.peek_events().size(), 0);
}; };
};
Case { "clears requests" } = [] { Suite tick_handles_requests = "tick_handles_requests"_suite = [] {
Case { "ticking clears requests" } = [] {
auto fixture = Fixture {}; auto fixture = Fixture {};
auto system = fixture.system(); auto system = System { fixture.registry() };
auto &surface = **fixture.create_component(); auto &surface = **fixture.create_component();
const auto new_title = std::string { title } + std::string { "_" }; constexpr auto title = "ABC";
constexpr auto new_position = lt::math::vec2_i32 { position_x + 50, position_y + 50 }; constexpr auto position = lt::math::ivec2 { 50, 50 };
constexpr auto new_resolution = lt::math::vec2_u32 { width + 50, height + 50 }; constexpr auto resolution = lt::math::uvec2 { 50, 50 };
expect_eq(surface.peek_requests().size(), 0); expect_eq(surface.peek_requests().size(), 0);
surface.push_request(lt::surface::ModifyVisibilityRequest(true)); surface.push_request(lt::surface::ModifyVisibilityRequest(true));
expect_eq(surface.peek_requests().size(), 1); expect_eq(surface.peek_requests().size(), 1);
system->tick(tick_info()); system.tick(tick_info());
expect_eq(surface.peek_requests().size(), 0); expect_eq(surface.peek_requests().size(), 0);
surface.push_request(lt::surface::ModifyTitleRequest(new_title)); surface.push_request(lt::surface::ModifyTitleRequest(title));
expect_eq(surface.peek_requests().size(), 1); expect_eq(surface.peek_requests().size(), 1);
surface.push_request(lt::surface::ModifyResolutionRequest(new_resolution)); surface.push_request(lt::surface::ModifyResolutionRequest(resolution));
surface.push_request(lt::surface::ModifyPositionRequest(new_position)); surface.push_request(lt::surface::ModifyPositionRequest(position));
expect_eq(surface.peek_requests().size(), 1 + 2); expect_eq(surface.peek_requests().size(), 1 + 2);
surface.push_request(lt::surface::ModifyVisibilityRequest(false)); surface.push_request(lt::surface::ModifyVisibilityRequest(false));
@ -284,251 +264,21 @@ Suite tick = "ticking"_suite = [] {
surface.push_request(lt::surface::ModifyVisibilityRequest(false)); surface.push_request(lt::surface::ModifyVisibilityRequest(false));
expect_eq(surface.peek_requests().size(), 1 + 2 + 3); expect_eq(surface.peek_requests().size(), 1 + 2 + 3);
system->tick(tick_info()); system.tick(tick_info());
expect_eq(surface.peek_requests().size(), 0); expect_eq(surface.peek_requests().size(), 0);
};
expect_eq(surface.get_title(), title);
expect_eq(surface.get_position(), position);
expect_eq(surface.get_resolution(), resolution);
lt::log::debug("EVENT COUNT: {}", surface.peek_events().size());
for (const auto &event : surface.peek_events())
{
const auto visitor = overloads {
[&](auto event) { lt::log::debug("event: {}", event.to_string()); },
}; };
Suite requests = "requests"_suite = [] { std::visit(visitor, event);
using ::lt::surface::ModifyTitleRequest; }
using ::lt::surface::ModifyResolutionRequest;
using ::lt::surface::ModifyPositionRequest;
using ::lt::surface::ModifyVisibilityRequest;
auto fixture = Fixture {};
auto system = fixture.system();
auto &surface = **fixture.create_component();
Case { "ModifyTitleRequest" } = [&] {
const auto new_title = std::string { title } + std::string { "_" };
surface.push_request({ ModifyTitleRequest { new_title } });
system->tick({});
expect_eq(surface.get_title(), new_title);
};
// TODO(Light): modifying resolution on Wayland is done by the underlying Graphics API
// and not the windowing system iteslf...
Case { "ModifyResolutionRequest" } = [&] {
constexpr auto new_resolution = lt::math::vec2_u32 { width + 50, height + 50 };
surface.push_request({ ModifyResolutionRequest { new_resolution } });
system->tick({});
expect_eq(surface.get_resolution(), new_resolution);
};
// Case { "ModifyPositionRequest" } = [&] {
// constexpr auto new_position = lt::math::vec2_i32 { position_x + 50, position_y + 50 };
// surface.push_request({ ModifyPositionRequest { new_position } });
//
// system->tick({});
// expect_eq(surface.get_position(), new_position);
// };
//
// Case { "ModifyVisibilityRequest" } = [&] {
// surface.push_request({ ModifyVisibilityRequest { .visible = false } });
// system->tick({});
// expect_eq(surface.is_visible(), false);
//
// surface.push_request({ ModifyVisibilityRequest { .visible = true } });
// system->tick({});
// expect_eq(surface.is_visible(), true);
// };
};
#if defined(LIGHT_PLATFORM_WINDOWS)
Suite windows_window_proc = "windows_window_proc"_suite = [] {
auto fixture = Fixture {};
auto system = fixture.system();
auto &surface = **fixture.create_component();
auto [hwnd] = surface.get_native_data();
const auto &events = surface.peek_events();
system->tick({});
Case { "WM_SETFOCUS" } = [&] {
expect_eq(events.size(), 0u);
::SendMessage(hwnd, WM_SETFOCUS, {}, {});
expect_eq(events.size(), 1u);
auto event = std::get<lt::surface::GainFocusEvent>(events.front());
::lt::log::trace("{}", event.to_string()); // make sure it's not optimized away?
};
system->tick({});
Case { "WM_KILLFOCUS" } = [&] {
expect_eq(events.size(), 0u);
::SendMessage(hwnd, WM_KILLFOCUS, {}, {});
expect_eq(events.size(), 1u);
auto event = std::get<lt::surface::LostFocusEvent>(events.front());
::lt::log::trace("{}", event.to_string()); // make sure it's not optimized away?
};
system->tick({});
Case { "WM_SIZE" } = [&] {
const auto new_width = width + 50;
const auto new_height = height + 60;
expect_eq(events.size(), 0u);
::SendMessage(hwnd, WM_SIZE, {}, MAKELPARAM(new_width, new_height));
expect_eq(events.size(), 1u);
const auto &event = std::get<lt::surface::ResizedEvent>(events.front());
expect_eq(event.get_size().x, new_width);
expect_eq(event.get_size().y, new_height);
expect_eq(surface.get_resolution().x, new_width);
expect_eq(surface.get_resolution().y, new_height);
};
system->tick({});
Case { "WM_MOVE" } = [&] {
const auto new_x = position_x + 120;
const auto new_y = position_y + 150;
expect_eq(events.size(), 0u);
::SendMessage(hwnd, WM_MOVE, {}, MAKELPARAM(new_x, new_y));
expect_eq(events.size(), 1u);
const auto &event = std::get<lt::surface::MovedEvent>(events.front());
expect_eq(event.get_position().x, new_x);
expect_eq(event.get_position().y, new_y);
expect_eq(surface.get_position().x, new_x);
expect_eq(surface.get_position().y, new_y);
};
system->tick({});
Case { "WM_MOUSEWHEEL" } = [&] {
expect_eq(events.size(), 0u);
::SendMessage(hwnd, WM_MOUSEWHEEL, MAKEWPARAM(0, WHEEL_DELTA), {});
::SendMessage(hwnd, WM_MOUSEWHEEL, MAKEWPARAM(0, -WHEEL_DELTA), {});
// Mouse wheel is treated like key presses,
// but since there is no "release" action for it...
// Every movement causes two key press events together:
// Press + Release of wheel_up/down.
expect_eq(events.size(), 4u);
expect_eq(std::get<lt::surface::KeyPressedEvent>(events[0]).get_key(), Key::wheel_up);
expect_eq(std::get<lt::surface::KeyReleasedEvent>(events[1]).get_key(), Key::wheel_up);
expect_eq(std::get<lt::surface::KeyPressedEvent>(events[2]).get_key(), Key::wheel_down);
expect_eq(std::get<lt::surface::KeyReleasedEvent>(events[3]).get_key(), Key::wheel_down);
};
system->tick({});
Case { "WM_LBUTTONDOWN" } = [&] {
expect_eq(events.size(), 0u);
::SendMessage(hwnd, WM_LBUTTONDOWN, {}, {});
expect_eq(events.size(), 1u);
// Mouse buttons are treated like key presses.
expect_eq(std::get<lt::surface::KeyPressedEvent>(events[0]).get_key(), Key::left_button);
};
system->tick({});
Case { "WM_LBUTTONUP" } = [&] {
expect_eq(events.size(), 0u);
::SendMessage(hwnd, WM_LBUTTONUP, {}, {});
expect_eq(events.size(), 1u);
// Mouse buttons are treated like key presses.
expect_eq(std::get<lt::surface::KeyReleasedEvent>(events[0]).get_key(), Key::left_button);
};
system->tick({});
Case { "WM_RBUTTONDOWN" } = [&] {
expect_eq(events.size(), 0u);
::SendMessage(hwnd, WM_RBUTTONDOWN, {}, {});
expect_eq(events.size(), 1u);
// Mouse buttons are treated like key presses.
expect_eq(std::get<lt::surface::KeyPressedEvent>(events[0]).get_key(), Key::right_button);
};
system->tick({});
Case { "WM_RBUTTONUP" } = [&] {
expect_eq(events.size(), 0u);
::SendMessage(hwnd, WM_RBUTTONUP, {}, {});
expect_eq(events.size(), 1u);
// Mouse buttons are treated like key presses.
expect_eq(std::get<lt::surface::KeyReleasedEvent>(events[0]).get_key(), Key::right_button);
};
system->tick({});
Case { "WM_MBUTTONDOWN" } = [&] {
expect_eq(events.size(), 0u);
::SendMessage(hwnd, WM_MBUTTONDOWN, {}, {});
expect_eq(events.size(), 1u);
// Mouse buttons are treated like key presses.
expect_eq(std::get<lt::surface::KeyPressedEvent>(events[0]).get_key(), Key::middle_button);
};
system->tick({});
Case { "WM_MBUTTONUP" } = [&] {
expect_eq(events.size(), 0u);
::SendMessage(hwnd, WM_MBUTTONUP, {}, {});
expect_eq(events.size(), 1u);
// Mouse buttons are treated like key presses.
expect_eq(std::get<lt::surface::KeyReleasedEvent>(events[0]).get_key(), Key::middle_button);
};
system->tick({});
Case { "WM_XBUTTONDOWN" } = [&] {
expect_eq(events.size(), 0u);
::SendMessage(hwnd, WM_XBUTTONDOWN, MAKEWPARAM(0, XBUTTON1), {});
::SendMessage(hwnd, WM_XBUTTONDOWN, MAKEWPARAM(0, XBUTTON2), {});
expect_eq(events.size(), 2u);
// Mouse buttons are treated like key presses.
expect_eq(std::get<lt::surface::KeyPressedEvent>(events[0]).get_key(), Key::x_button_1);
expect_eq(std::get<lt::surface::KeyPressedEvent>(events[1]).get_key(), Key::x_button_2);
};
system->tick({});
Case { "WM_XBUTTONUP" } = [&] {
expect_eq(events.size(), 0u);
::SendMessage(hwnd, WM_XBUTTONUP, MAKEWPARAM(0, XBUTTON1), {});
::SendMessage(hwnd, WM_XBUTTONUP, MAKEWPARAM(0, XBUTTON2), {});
expect_eq(events.size(), 2u);
// Mouse buttons are treated like key presses.
expect_eq(std::get<lt::surface::KeyReleasedEvent>(events[0]).get_key(), Key::x_button_1);
expect_eq(std::get<lt::surface::KeyReleasedEvent>(events[1]).get_key(), Key::x_button_2);
};
system->tick({});
Case { "WM_KEYDOWN" } = [&] {
expect_eq(events.size(), 0u);
::SendMessage(hwnd, WM_KEYDOWN, System::to_native_key(Key::escape), {});
expect_eq(events.size(), 1u);
expect_eq(std::get<lt::surface::KeyPressedEvent>(events[0]).get_key(), Key::escape);
};
system->tick({});
Case { "WM_KEYUP" } = [&] {
expect_eq(events.size(), 0u);
::SendMessage(hwnd, WM_KEYUP, System::to_native_key(Key::escape), {});
expect_eq(events.size(), 1u);
expect_eq(std::get<lt::surface::KeyReleasedEvent>(events[0]).get_key(), Key::escape);
};
system->tick({});
Case { "WM_CLOSE" } = [&] {
expect_eq(events.size(), 0u);
::SendMessage(hwnd, WM_CLOSE, {}, {});
expect_eq(events.size(), 1u);
// would throw if type is incorrect
auto event = std::get<lt::surface::ClosedEvent>(events[0]);
::lt::log::trace("{}", event.to_string()); // make sure it's not optimized away?
}; };
}; };
#endif

View file

@ -1 +0,0 @@
*

View file

@ -1,7 +1,12 @@
import test; import logger;
import test.test;
import test.registry; import test.registry;
void parse_option(std::string_view argument, lt::test::Registry::Options &options) import std;
using namespace ::lt::test;
void parse_option(std::string_view argument, Registry::Options &options)
{ {
constexpr auto case_str = std::string_view { "--case=" }; constexpr auto case_str = std::string_view { "--case=" };
constexpr auto suite_str = std::string_view { "--suite=" }; constexpr auto suite_str = std::string_view { "--suite=" };
@ -14,7 +19,7 @@ void parse_option(std::string_view argument, lt::test::Registry::Options &option
if (argument.starts_with("--mode=") && argument.substr(7ul) == "stats") if (argument.starts_with("--mode=") && argument.substr(7ul) == "stats")
{ {
options.execution_policy = lt::test::Registry::ExecutionPolicy::stats; options.execution_policy = Registry::ExecutionPolicy::stats;
return; return;
} }
@ -46,13 +51,12 @@ void print_help()
std::println("--help | -h --> ~You just used it! :D"); std::println("--help | -h --> ~You just used it! :D");
} }
auto main(i32 argc, char **argv) -> i32 auto main(std::int32_t argc, char **argv) -> std::int32_t
try try
{ {
lt::log::set_min_severity(lt::log::Level::test);
auto raw_arguments = std::span<char *>(argv, argc); auto raw_arguments = std::span<char *>(argv, argc);
auto options = lt::test::Registry::Options {}; auto options = Registry::Options {};
for (auto idx = 0; auto &raw_argument : raw_arguments) for (auto idx = 0; auto &raw_argument : raw_arguments)
{ {
// First argument is the "cwd' // First argument is the "cwd'
@ -79,7 +83,7 @@ try
} }
} }
return static_cast<i32>(lt::test::Registry::run_all(options)); return static_cast<std::int32_t>(Registry::run_all(options));
} }
catch (const std::exception &exp) catch (const std::exception &exp)
{ {

View file

@ -1,7 +1,6 @@
export module test.expects; export module test.expects;
import std;
import preliminary;
namespace lt::test { namespace lt::test {
@ -24,14 +23,14 @@ export void expect_unreachable(
{ {
throw std::runtime_error { throw std::runtime_error {
std::format( std::format(
"unreachable reached: {}:{}", "Failed unreachable expectation:\n"
"\tlocation: {}:{}",
source_location.file_name(), source_location.file_name(),
source_location.line() source_location.line()
), ),
}; };
}; };
/** @todo(Light7734): Check exception type. */
export constexpr void expect_throw( export constexpr void expect_throw(
std::invocable auto invocable, std::invocable auto invocable,
std::source_location source_location = std::source_location::current() std::source_location source_location = std::source_location::current()
@ -41,13 +40,18 @@ export constexpr void expect_throw(
{ {
invocable(); invocable();
} }
catch (const std::exception &) catch (const std::exception &exp)
{ {
return; return;
} }
throw std::runtime_error { throw std::runtime_error {
std::format("did not throw: {}:{}", source_location.file_name(), source_location.line()), std::format(
"Failed throwing expectation:\n"
"\tlocation: {}:{}",
source_location.file_name(),
source_location.line()
),
}; };
} }
@ -63,7 +67,10 @@ export constexpr void expect_eq(
{ {
throw std::runtime_error { throw std::runtime_error {
std::format( std::format(
"expect_eq: {} == {} @ {}:{}", "Failed equality expectation:\n"
"\tactual: {}\n"
"\texpected: {}\n"
"\tlocation: {}:{}",
std::to_underlying<decltype(lhs)>(lhs), std::to_underlying<decltype(lhs)>(lhs),
std::to_underlying<decltype(rhs)>(rhs), std::to_underlying<decltype(rhs)>(rhs),
source_location.file_name(), source_location.file_name(),
@ -76,7 +83,10 @@ export constexpr void expect_eq(
{ {
throw std::runtime_error { throw std::runtime_error {
std::format( std::format(
"expect_eq: {} == {} @ {}:{}", "Failed equality expectation:\n"
"\tactual: {}\n"
"\texpected: {}\n"
"\tlocation: {}:{}",
lhs, lhs,
rhs, rhs,
source_location.file_name(), source_location.file_name(),
@ -96,47 +106,10 @@ export constexpr void expect_ne(
{ {
throw std::runtime_error { throw std::runtime_error {
std::format( std::format(
"expect_ne: {} != {} @ {}:{}", "Failed un-equality expectation:\n"
lhs, "\tactual: {}\n"
rhs, "\texpected: {}\n"
source_location.file_name(), "\tlocation: {}:{}",
source_location.line()
),
};
}
}
export constexpr void expect_le(
Testable auto lhs,
Testable auto rhs,
std::source_location source_location = std::source_location::current()
)
{
if (lhs > rhs)
{
throw std::runtime_error {
std::format(
"expect_le: {} <= {} @ {}:{}",
lhs,
rhs,
source_location.file_name(),
source_location.line()
),
};
}
}
export constexpr void expect_ge(
Testable auto lhs,
Testable auto rhs,
std::source_location source_location = std::source_location::current()
)
{
if (lhs < rhs)
{
throw std::runtime_error {
std::format(
"expect_ge: {} >= {} @ {}:{}",
lhs, lhs,
rhs, rhs,
source_location.file_name(), source_location.file_name(),
@ -155,7 +128,10 @@ export constexpr void expect_true(
{ {
throw std::runtime_error { throw std::runtime_error {
std::format( std::format(
"expect_true: {} @ {}:{}", "Failed true expectation:\n"
"\tactual: {}\n"
"\texpected: true\n"
"\tlocation: {}:{}",
expression, expression,
source_location.file_name(), source_location.file_name(),
source_location.line() source_location.line()
@ -173,7 +149,10 @@ export constexpr void expect_false(
{ {
throw std::runtime_error { throw std::runtime_error {
std::format( std::format(
"expect_false: {} @ {}:{}", "Failed false expectation:\n"
"\tactual: {}\n"
"\texpected: true\n"
"\tlocation: {}:{}",
expression, expression,
source_location.file_name(), source_location.file_name(),
source_location.line() source_location.line()
@ -191,7 +170,34 @@ export constexpr void expect_not_nullptr(
{ {
throw std::runtime_error { throw std::runtime_error {
std::format( std::format(
"expect_not_nullptr: @ {}:{}", "Failed true expectation:\n"
"\tactual: nullptr\n"
"\texpected: not nullptr\n"
"\tlocation: {}:{}",
source_location.file_name(),
source_location.line()
),
};
}
}
export constexpr void expect_le(
Testable auto lhs,
Testable auto rhs,
std::source_location source_location = std::source_location::current()
)
{
if (lhs > rhs)
{
throw std::runtime_error {
std::format(
"Failed false expectation:\n"
"\tactual: {}\n"
"\texpected: >= {}\n"
"\tlocation: {}:{}",
lhs,
rhs,
source_location.file_name(), source_location.file_name(),
source_location.line() source_location.line()
), ),

86
modules/test/fuzz.cppm Normal file
View file

@ -0,0 +1,86 @@
#include <cstring>
#include <test/test.hpp>
namespace lt::test {
class FuzzDataProvider
{
public:
FuzzDataProvider(const uint8_t *data, size_t size): m_data(data, size)
{
}
template<typename T>
requires(
std::is_trivially_constructible_v<T> //
&& std::is_trivially_copy_constructible_v<T> //
&& std::is_trivially_copy_assignable_v<T>
)
auto consume() -> std::optional<T>
{
if (m_data.size() < sizeof(T))
{
return std::nullopt;
}
T value;
std::memcpy(&value, m_data.data(), sizeof(T));
m_data = m_data.subspan(sizeof(T));
return value;
}
auto consume_string(size_t size) -> std::optional<std::string>
{
if (m_data.size() < size)
{
return std::nullopt;
}
// NOLINTNEXTLINE
auto value = std::string { (const char *)m_data.data(), size };
m_data = m_data.subspan(size);
return value;
}
auto consume_remaining_as_string() -> std::string
{
if (m_data.empty())
{
return std::string {};
}
return { m_data.begin(), m_data.end() };
};
private:
std::span<const uint8_t> m_data;
};
} // namespace lt::test
namespace lt::test {
auto process_fuzz_input(const uint8_t *data, size_t size) -> int32_t
try
{
return details::Registry::process_fuzz_input(data, size);
}
catch (const std::exception &exp)
{
std::println("Fuzz input resulted in uncaught exception:");
std::println("\twhat: {}", exp.what());
std::println("\tinput size: {}", size);
return EXIT_FAILURE;
}
}; // namespace lt::test
extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size)
{
return lt::test::process_fuzz_input(data, size);
}

View file

@ -1,23 +0,0 @@
export module test;
export import preliminary;
export import test.test;
export import test.expects;
export import test.expects;
export import logger;
export using ::lt::test::Suite;
export using ::lt::test::Case;
export using ::lt::test::expect_eq;
export using ::lt::test::expect_ne;
export using ::lt::test::expect_le;
export using ::lt::test::expect_true;
export using ::lt::test::expect_false;
export using ::lt::test::expect_throw;
export using ::lt::test::expect_not_nullptr;
export using ::lt::test::expect_unreachable;
export using ::lt::test::operator""_suite;

View file

@ -1,7 +1,6 @@
export module test.registry; export module test.registry;
import logger; import std;
import preliminary;
import test.expects; import test.expects;
/////////////////////////////////////// ///////////////////////////////////////
@ -12,7 +11,7 @@ namespace lt::test {
export class Registry export class Registry
{ {
public: public:
enum class ExecutionPolicy : u8 enum class ExecutionPolicy : std::uint8_t
{ {
normal, normal,
stats, stats,
@ -29,7 +28,7 @@ public:
std::string case_regex; std::string case_regex;
}; };
using FuzzFunction = i32 (*)(const u8 *, size_t); using FuzzFunction = std::int32_t (*)(const std::uint8_t *, std::size_t);
using SuiteFunction = void (*)(); using SuiteFunction = void (*)();
@ -37,9 +36,9 @@ public:
static void register_fuzz_harness(FuzzFunction suite); static void register_fuzz_harness(FuzzFunction suite);
static auto run_all(Options options) -> i32; static auto run_all(Options options) -> std::int32_t;
static auto process_fuzz_input(const u8 *data, size_t size) -> i32; static auto process_fuzz_input(const std::uint8_t *data, std::size_t size) -> std::int32_t;
static void set_last_suite_name(const char *name); static void set_last_suite_name(const char *name);
@ -74,7 +73,7 @@ private:
[[nodiscard]] static auto instance() -> Registry &; [[nodiscard]] static auto instance() -> Registry &;
auto run_all_impl() -> i32; auto run_all_impl() -> std::int32_t;
void print_options(); void print_options();
@ -84,25 +83,25 @@ private:
FuzzFunction m_fuzz_harness {}; FuzzFunction m_fuzz_harness {};
i32 m_total_case_count {}; std::int32_t m_total_case_count {};
i32 m_passed_case_count {}; std::int32_t m_passed_case_count {};
i32 m_failed_case_count {}; std::int32_t m_failed_case_count {};
i32 m_matched_case_count {}; std::int32_t m_matched_case_count {};
i32 m_skipped_case_count {}; std::int32_t m_skipped_case_count {};
i32 m_total_suite_count {}; std::int32_t m_total_suite_count {};
i32 m_passed_suite_count {}; std::int32_t m_passed_suite_count {};
i32 m_failed_suite_count {}; std::int32_t m_failed_suite_count {};
i32 m_matched_suite_count {}; std::int32_t m_matched_suite_count {};
i32 m_skipped_suite_count {}; std::int32_t m_skipped_suite_count {};
std::regex m_case_regex; std::regex m_case_regex;
}; };
@ -112,8 +111,7 @@ private:
////////////////////////////////////// //////////////////////////////////////
// -------* IMPLEMENTATION *------- // // -------* IMPLEMENTATION *------- //
///////////////////////////////////// /////////////////////////////////////
/** @todo(Light): unimplemented in gcc -- is it even right to use a private fragment? */ module :private;
// module :private;
namespace lt::test { namespace lt::test {
/* static */ void Registry::register_suite(SuiteFunction suite) /* static */ void Registry::register_suite(SuiteFunction suite)
@ -133,13 +131,14 @@ namespace lt::test {
instance().m_fuzz_harness = suite; instance().m_fuzz_harness = suite;
} }
/* static */ auto Registry::run_all(Options options) -> i32 /* static */ auto Registry::run_all(Options options) -> std::int32_t
{ {
instance().m_options = std::move(options); instance().m_options = std::move(options);
return instance().run_all_impl(); return instance().run_all_impl();
} }
/* static */ auto Registry::process_fuzz_input(const u8 *data, size_t size) -> i32 /* static */ auto Registry::process_fuzz_input(const std::uint8_t *data, std::size_t size)
-> std::int32_t
{ {
if (!instance().m_fuzz_harness) if (!instance().m_fuzz_harness)
{ {
@ -206,22 +205,22 @@ namespace lt::test {
++instance().m_failed_case_count; ++instance().m_failed_case_count;
} }
/* static */ [[nodiscard]] auto Registry::should_return_on_failure() -> bool [[nodiscard]] /* static */ auto Registry::should_return_on_failure() -> bool
{ {
return instance().m_options.stop_on_fail; return instance().m_options.stop_on_fail;
} }
/* static */ [[nodiscard]] auto Registry::get_options() -> const Options & [[nodiscard]] /* static */ auto Registry::get_options() -> const Options &
{ {
return instance().m_options; return instance().m_options;
} }
/* static */ [[nodiscard]] auto Registry::get_case_regex() -> const std::regex & [[nodiscard]] /* static */ auto Registry::get_case_regex() -> const std::regex &
{ {
return instance().m_case_regex; return instance().m_case_regex;
} }
auto Registry::run_all_impl() -> i32 auto Registry::run_all_impl() -> std::int32_t
{ {
print_options(); print_options();
m_case_regex = std::regex(m_options.case_regex); m_case_regex = std::regex(m_options.case_regex);
@ -233,30 +232,6 @@ auto Registry::run_all_impl() -> i32
{ {
if (std::regex_search(name, regex)) if (std::regex_search(name, regex))
{ {
auto padding_left = std::string {};
padding_left.resize((79 - std::strlen(name)) / 2u - 1u);
for (auto &ch : padding_left)
{
ch = '-';
}
auto padding_right = std::string {};
padding_right.resize((79 - std::strlen(name)) / 2u);
if (std::strlen(name) % 2 == 0)
{
padding_right.resize(padding_right.size() + 1);
}
for (auto &ch : padding_right)
{
ch = '-';
}
log::test(
"\033[1;33m*{}{}{}-*\033[0m",
std::string { padding_left },
std::string_view { name },
std::string { padding_right }
);
suite(); suite();
increment_matched_suite_count(); increment_matched_suite_count();
} }
@ -271,12 +246,12 @@ auto Registry::run_all_impl() -> i32
{ {
if (m_options.stop_on_fail) if (m_options.stop_on_fail)
{ {
log::info("Quitting due to options.stop_on_fail == true"); std::println("Quitting due to options.stop_on_fail == true");
break; break;
} }
log::test("Uncaught exception when running suite:"); std::println("Uncaught exception when running suite:");
log::test("\twhat: {}", exp.what()); std::println("\twhat: {}", exp.what());
break; break;
} }
} }
@ -285,32 +260,32 @@ auto Registry::run_all_impl() -> i32
{ {
case ExecutionPolicy::normal: case ExecutionPolicy::normal:
{ {
// log::test("[-------STATS------]"); std::println("[-------STATS------]");
//
// log::test("suites:");
// log::test("\ttotal: {}", (i32)m_total_suite_count);
// log::test("\tpassed: {}", (i32)m_passed_suite_count);
// log::test("\tfailed: {}", (i32)m_failed_suite_count);
// log::test("\tmatched: {}", (i32)m_matched_suite_count);
// log::test("\tskipped: {}", (i32)m_skipped_suite_count);
//
// log::test("tests:");
// log::test("\ttotal: {}", (i32)m_total_case_count);
// log::test("\tpassed: {}", (i32)m_passed_case_count);
// log::test("\tfailed: {}", (i32)m_failed_case_count);
// log::test("\tmatched: {}", (i32)m_matched_case_count);
// log::test("\tskipped: {}", (i32)m_skipped_case_count);
// log::test("________________________________________________________________"); std::println("suites:");
std::println("\ttotal: {}", m_total_suite_count);
std::println("\tpassed: {}", m_passed_suite_count);
std::println("\tfailed: {}", m_failed_suite_count);
std::println("\tmatched: {}", m_matched_suite_count);
std::println("\tskipped: {}", m_skipped_suite_count);
std::println("tests:");
std::println("\ttotal: {}", m_total_case_count);
std::println("\tpassed: {}", m_passed_case_count);
std::println("\tfailed: {}", m_failed_case_count);
std::println("\tmatched: {}", m_matched_case_count);
std::println("\tskipped: {}", m_skipped_case_count);
std::println("________________________________________________________________");
return m_failed_case_count; return m_failed_case_count;
} }
case ExecutionPolicy::stats: case ExecutionPolicy::stats:
{ {
log::test("[-------STATS------]"); std::println("[-------STATS------]");
log::test("Total suite count: {}", (i32)m_total_suite_count); std::println("Total suite count: {}", m_total_suite_count);
log::test("Total test count: {}", (i32)m_total_case_count); std::println("Total test count: {}", m_total_case_count);
log::test("________________________________________________________________"); std::println("________________________________________________________________");
return 0; return 0;
} }
@ -321,12 +296,12 @@ auto Registry::run_all_impl() -> i32
void Registry::print_options() void Registry::print_options()
{ {
// log::info("stop-on-failure: {}", static_cast<bool>(m_options.stop_on_fail)); std::println("stop-on-failure: {}", m_options.stop_on_fail);
} }
Registry::Registry() Registry::Registry()
{ {
// log::info("________________________________________________________________"); std::println("________________________________________________________________");
} }
[[nodiscard]] /* static */ auto Registry::instance() -> Registry & [[nodiscard]] /* static */ auto Registry::instance() -> Registry &

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