Compare commits

..

No commits in common. "master" and "2025-07-21-claude-refactor" have entirely different histories.

140 changed files with 3783 additions and 9756 deletions

2
.gitattributes vendored
View file

@ -1,2 +0,0 @@
assets/models/* filter=lfs diff=lfs merge=lfs -text
assets/exr/* filter=lfs diff=lfs merge=lfs -text

4
.gitignore vendored
View file

@ -1,3 +1,3 @@
target/ /target
.aider*
*.patch *.patch
.idea/

View file

@ -1,11 +0,0 @@
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.6.0
hooks:
- id: trailing-whitespace
files: "\\.rs$"
- id: end-of-file-fixer
files: "\\.rs$"
- id: mixed-line-ending
args: [--fix=lf]
files: "\\.rs$"

2164
Cargo.lock generated

File diff suppressed because it is too large Load diff

View file

@ -1,11 +1,9 @@
[workspace] [workspace]
members = [ members = [
"core", "raidillon_core",
"glium_platform", "raidillon_ecs",
"platform", "raidillon_render",
"asset", "raidillon_ui",
"game", "raidillon_game",
"ecs", "raidillon_input",
"engine",
"physics", "app",
] ]

661
LICENSE
View file

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

View file

@ -1,3 +0,0 @@
# Raidillon rewrite number #23818491847214
Starting in 2025-08-03, 17:59 UTC+3

View file

@ -1,16 +0,0 @@
[package]
name = "raidillon_app"
version = "0.1.0"
edition = "2024"
[dependencies]
raidillon_engine = { path = "../engine" }
raidillon_platform = { path = "../platform" }
raidillon_assets = { path = "../asset" }
raidillon_ecs = { path = "../ecs" }
raidillon_physics = { path = "../physics" }
raidillon_glium = { path = "../glium_platform", optional = true }
raidillon_core = { path = "../core" }
[features]
glium = ["raidillon_glium"]

View file

@ -1,45 +0,0 @@
pub mod prelude;
pub use prelude::*;
pub struct App {
pub engine: Option<Engine>,
}
impl App {
pub fn new() -> Self {
let engine = Engine::new();
Self { engine: Some(engine) }
}
pub fn add_system<S: System + Default + 'static>(&mut self) -> &mut Self {
self.engine.as_mut().unwrap().system_manager.add::<S>();
self
}
pub fn add_scene(&mut self, id: SceneID, scene: Scene) -> &mut Self {
self.engine.as_mut().unwrap().scene_manager.add_scene(id, scene);
self
}
pub fn set_active_scene(&mut self, id: SceneID) -> &mut Self {
self.engine.as_mut().unwrap().scene_manager.set_active_scene(id);
self
}
pub fn run(&mut self, title: String, width: u32, height: u32) {
#[cfg(feature = "glium")]
{
let platform = GliumPlatform::initialize(
self.engine.take().unwrap(),
title,
width,
height,
);
platform.run();
}
#[cfg(not(any(feature = "glium")))]
compile_error!("No platform feature enabled.");
}
}

View file

@ -1,47 +0,0 @@
pub use raidillon_engine::{
Engine,
system::System,
EngineResources,
InputState,
system::SystemContext,
};
pub use raidillon_platform::{
Platform,
Camera,
PlatformContext,
TimeContext,
DebugWireframes,
DebugWireframesRef,
DebugWireframeVertex,
settings::{Settings, WindowMode},
};
pub use raidillon_assets::{
ModelManagerRef,
model_path,
};
pub use raidillon_ecs::{
components::{
CameraMode,
CharacterBodyComponent,
ModelHandle,
RigidBodyComponent,
Transform,
},
};
pub use raidillon_physics::Physics;
pub use raidillon_core::{
scene::{Scene, SceneID},
EguiQueue,
engine::EngineTrait,
};
#[cfg(feature = "glium")]
pub use raidillon_glium::{
GliumPlatform,
RenderingSystem,
};

View file

@ -1,4 +0,0 @@
[package]
name = "raidillon_assets"
version = "0.1.0"
edition = "2024"

View file

@ -1,22 +0,0 @@
pub mod model_manager;
use std::path::PathBuf;
pub use crate::model_manager::{ModelManager, ModelManagerRef};
pub use crate::model_manager::ModelID;
#[macro_export]
macro_rules! include_shader {
($path:expr) => {
include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/../assets/shaders/", $path))
};
}
pub fn model_path(path: &str) -> PathBuf {
let manifest_dir = env!("CARGO_MANIFEST_DIR");
PathBuf::from(manifest_dir)
.join("..")
.join("assets")
.join("models")
.join(path)
}

View file

@ -1,17 +0,0 @@
use std::any::Any;
use std::cell::RefCell;
use std::path::{Path, PathBuf};
use std::rc::Rc;
pub type ModelManagerRef = Rc<RefCell<Box<dyn ModelManager>>>;
pub type ModelID = &'static str;
/// The asset manager trait of Raidillon.
pub trait ModelManager: Any {
/// Loads a gltf model to VRAM.
fn load_gltf(&mut self, id: ModelID, path: &Path);
/// Unloads the loaded model from VRAM.
fn unload_model(&mut self, id: ModelID);
fn get_model(&self, id: &ModelID) -> Option<&dyn Any>;
}

Binary file not shown.

BIN
assets/exr/qwantani_sunset_puresky_2k.exr (Stored with Git LFS)

Binary file not shown.

BIN
assets/models/checkered-sphere.glb (Stored with Git LFS)

Binary file not shown.

BIN
assets/models/monkey.bin (Stored with Git LFS)

Binary file not shown.

BIN
assets/models/monkey.gltf (Stored with Git LFS)

Binary file not shown.

BIN
assets/models/pink-monkey.bin (Stored with Git LFS)

Binary file not shown.

BIN
assets/models/pink-monkey.gltf (Stored with Git LFS)

Binary file not shown.

BIN
assets/models/plane.glb (Stored with Git LFS)

Binary file not shown.

BIN
assets/models/sphere.glb (Stored with Git LFS)

Binary file not shown.

BIN
assets/models/tree.bin (Stored with Git LFS)

Binary file not shown.

BIN
assets/models/tree.gltf (Stored with Git LFS)

Binary file not shown.

BIN
assets/models/tree_texture.png (Stored with Git LFS)

Binary file not shown.

View file

@ -1,9 +0,0 @@
#version 330 core
in vec4 v_color;
out vec4 frag_color;
void main() {
frag_color = v_color;
}

View file

@ -1,14 +0,0 @@
#version 330 core
in vec3 position;
in vec4 color;
uniform mat4 view;
uniform mat4 projection;
out vec4 v_color;
void main() {
v_color = color;
gl_Position = projection * view * vec4(position, 1.0);
}

View file

@ -1,43 +0,0 @@
#version 330 core
in vec3 v_normal;
in vec2 v_tex;
in vec3 v_position;
out vec4 frag_color;
uniform vec3 u_light; // direction TO the light (normalized)
uniform sampler2D tex;
uniform vec3 color; // base colour factor (acts as solid colour when no texture)
void main() {
// Combine base texture (or constant white) with colour factor supplied by CPU.
vec3 base_col = texture(tex, v_tex).rgb * color;
vec3 N = normalize(v_normal);
vec3 L = normalize(u_light);
// Classic Blinn-Phong lighting
// Ambient: always present
vec3 ambient = base_col * 0.15;
// Diffuse: N dot L, clamped
float NdotL = max(dot(N, L), 0.0);
vec3 diffuse = base_col * NdotL * 0.7;
// Specular: only on surfaces facing the light (NdotL > 0)
float specular = 0.0;
if (NdotL > 0.0) {
vec3 V = normalize(-v_position); // view direction (camera at origin in view space)
vec3 H = normalize(L + V); // half-vector
float NdotH = max(dot(N, H), 0.0);
specular = pow(NdotH, 32.0) * 0.5; // tighter highlight, moderated intensity
}
vec3 result = ambient + diffuse + vec3(specular);
// Convert from linear to sRGB for display (approximate gamma correction)
result = pow(result, vec3(1.0 / 2.2));
frag_color = vec4(result, 1.0);
}

Binary file not shown.

120
core/Cargo.lock generated
View file

@ -1,120 +0,0 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "ahash"
version = "0.8.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75"
dependencies = [
"cfg-if",
"once_cell",
"version_check",
"zerocopy",
]
[[package]]
name = "cfg-if"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9555578bc9e57714c812a1f84e4fc5b4d21fcb063490c624de019f7464c91268"
[[package]]
name = "hashbrown"
version = "0.14.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1"
dependencies = [
"ahash",
]
[[package]]
name = "hecs"
version = "0.10.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e1cbc675ee8d97b4d206a985137f8ad59666538f56f906474f554467a63c776d"
dependencies = [
"hashbrown",
"spin",
]
[[package]]
name = "once_cell"
version = "1.21.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d"
[[package]]
name = "proc-macro2"
version = "1.0.95"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "02b3e5e68a3a1a02aad3ec490a98007cbc13c37cbe84a3cd7b8e406d76e7f778"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.40"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1885c039570dc00dcb4ff087a89e185fd56bae234ddc7f056a945bf36467248d"
dependencies = [
"proc-macro2",
]
[[package]]
name = "raidillon_core"
version = "0.1.0"
dependencies = [
"hecs",
]
[[package]]
name = "spin"
version = "0.9.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6980e8d7511241f8acf4aebddbb1ff938df5eebe98691418c4468d0b72a96a67"
[[package]]
name = "syn"
version = "2.0.104"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "17b6f705963418cdb9927482fa304bc562ece2fdd4f616084c50b7023b435a40"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "unicode-ident"
version = "1.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5a5f39404a5da50712a4c1eecf25e90dd62b613502b7e925fd4e4d19b5c96512"
[[package]]
name = "version_check"
version = "0.9.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
[[package]]
name = "zerocopy"
version = "0.8.26"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1039dd0d3c310cf05de012d8a39ff557cb0d23087fd44cad61df08fc31907a2f"
dependencies = [
"zerocopy-derive",
]
[[package]]
name = "zerocopy-derive"
version = "0.8.26"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9ecf5b4cc5364572d7f4c329661bcc82724222973f2cab6f050a4e5c22f75181"
dependencies = [
"proc-macro2",
"quote",
"syn",
]

View file

@ -1,11 +0,0 @@
[package]
name = "raidillon_core"
version = "0.1.0"
edition = "2024"
[dependencies]
hecs = "0.10.5"
indexmap = "2.10.0"
raidillon_assets = { path = "../asset" }
winit = "0.30.12"
egui = "0.33.2"

View file

@ -1,22 +0,0 @@
pub struct EguiQueue {
pub queue_vec: Vec<Box<dyn FnOnce(&egui::Context) + Send>>,
}
impl EguiQueue {
pub fn new() -> Self {
Self { queue_vec: Vec::new() }
}
pub fn queue(&mut self, func: impl FnOnce(&egui::Context) + Send + 'static) {
self.queue_vec.push(Box::new(func));
}
pub fn clear(&mut self) {
self.queue_vec.clear()
}
pub fn run(&mut self, ctx: &egui::Context) {
self.queue_vec.drain(..).for_each(|func| func(ctx));
self.clear();
}
}

View file

@ -1,12 +0,0 @@
use crate::scene::Scene;
pub trait EngineTrait {
type PlatformCtx: Clone;
fn new() -> Self;
fn initialize(&mut self, platform_context: Self::PlatformCtx);
fn frame_update(&mut self, platform_context: Self::PlatformCtx);
fn fixed_update(&mut self, platform_context: Self::PlatformCtx);
fn handle_event(&mut self, platform_context: Self::PlatformCtx);
fn current_scene_mut(&mut self) -> &mut Scene;
fn current_scene(&self) -> &Scene;
}

View file

@ -1,7 +0,0 @@
pub mod engine;
pub mod time;
pub mod utils;
pub mod scene;
mod egui_queue;
pub use egui_queue::EguiQueue;

View file

@ -1,85 +0,0 @@
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use crate::{define_typemap};
pub struct Scene {
pub title: String,
pub world: hecs::World,
pub skybox_texture_path: Option<PathBuf>,
pub resources: SceneResources,
}
define_typemap!(SceneResources,);
impl Scene {
pub fn new(title: String, skybox_texture_path: Option<PathBuf>) -> Self {
let mut s = Self {
title,
world: hecs::World::new(),
skybox_texture_path,
resources: SceneResources::new(),
};
s.load_default_resources();
s
}
pub fn load_default_resources(&mut self) {}
}
impl Scene {}
impl AsRef<Scene> for Scene {
fn as_ref(&self) -> &Scene {
&self
}
}
impl AsMut<Scene> for Scene {
fn as_mut(&mut self) -> &mut Scene {
self
}
}
pub type SceneID = &'static str;
pub struct SceneManager {
scenes: HashMap<SceneID, Scene>,
active_scene: Option<SceneID>,
}
impl SceneManager {
pub fn new() -> Self {
let scenes = HashMap::new();
Self {
scenes,
active_scene: None,
}
}
pub fn current(&self) -> &Scene {
match &self.active_scene {
Some(id) => self.scenes[id].as_ref(),
None => panic!("No active scene"),
}
}
pub fn current_mut(&mut self) -> &mut Scene {
match &mut self.active_scene {
Some(id) => self.scenes.get_mut(id).unwrap().as_mut(),
None => panic!("No active scene"),
}
}
pub fn set_active_scene(&mut self, scene: SceneID) {
self.active_scene = Some(scene);
}
pub fn add_scene(&mut self, id: SceneID, scene: Scene) {
self.scenes.insert(id, scene);
}
pub fn remove_scene(&mut self, id: SceneID) {
self.scenes.remove(&id);
}
}

View file

@ -1,144 +0,0 @@
use std::thread;
use std::time::{Duration, Instant};
#[derive(Clone, Debug)]
pub struct Config {
pub target_frame_hz: Option<f64>,
pub target_update_hz: f64,
pub max_updates_per_frame: u32,
pub max_accumulated_steps: u32,
pub sleep_tolerance: Duration,
}
impl Default for Config {
fn default() -> Self {
Self {
target_frame_hz: Some(144.0),
target_update_hz: 60.0,
max_updates_per_frame: 5,
max_accumulated_steps: 8,
sleep_tolerance: Duration::from_micros(500),
}
}
}
#[derive(Debug)]
pub struct Time {
cfg: Config,
last_instant: Instant,
next_frame_due: Instant,
frame_interval: Option<Duration>,
fixed_dt: Duration,
// tracking
frame_dt: Duration,
accumulator: Duration,
// counters
pub frame_count: u64,
pub update_count: u64,
}
pub struct TickPlan {
/// How many fixed updates to run this frame
pub updates: u32,
/// Interpolation factor for rendering between previous/next sim states
pub alpha: f32,
/// Measured last frame delta (seconds)
pub frame_dt: f32,
/// Fixed timestep (seconds)
pub fixed_dt: f32,
}
impl Time {
pub fn new(cfg: Config) -> Self {
let now = Instant::now();
let frame_interval = cfg.target_frame_hz.map(|hz| Duration::from_secs_f64(1.0 / hz));
let fixed_dt = Duration::from_secs_f64(1.0 / cfg.target_update_hz);
Self {
cfg,
last_instant: now,
next_frame_due: now,
frame_interval,
fixed_dt,
frame_dt: Duration::ZERO,
accumulator: Duration::ZERO,
frame_count: 0,
update_count: 0,
}
}
pub fn reconfigure(&mut self, cfg: Config) {
self.cfg = cfg.clone();
self.frame_interval = cfg.target_frame_hz.map(|hz| Duration::from_secs_f64(1.0 / hz));
self.fixed_dt = Duration::from_secs_f64(1.0 / cfg.target_update_hz);
}
pub fn begin_frame_blocking(&mut self) -> TickPlan {
// 1) If there's a frame cap, block until next frame deadline
if let Some(interval) = self.frame_interval {
let mut now = Instant::now();
if now < self.next_frame_due {
// Sleep most of the remainder, then spin the last tiny bit for precision
let total_remaining = self.next_frame_due - now;
if total_remaining > self.cfg.sleep_tolerance {
let sleep_for = total_remaining - self.cfg.sleep_tolerance;
thread::sleep(sleep_for);
}
// Short spin-wait for precision
while Instant::now() < self.next_frame_due {
std::hint::spin_loop();
}
now = self.next_frame_due;
}
self.next_frame_due = self.next_frame_due + interval;
// In case we fell far behind (e.g., debugger pause), resync.
if self.next_frame_due < now {
self.next_frame_due = now + interval;
}
}
// 2) Measure frame dt
let now = Instant::now();
self.frame_dt = now.saturating_duration_since(self.last_instant);
self.last_instant = now;
self.frame_count += 1;
// 3) Accumulate for fixed updates
self.accumulator += self.frame_dt;
// Clamp accumulator to avoid doing a huge number of updates after a stall
let max_accumulated = self.fixed_dt * self.cfg.max_accumulated_steps;
if self.accumulator > max_accumulated {
self.accumulator = max_accumulated;
}
// 4) Determine how many updates to run this frame
let mut updates = 0u32;
while self.accumulator >= self.fixed_dt && updates < self.cfg.max_updates_per_frame {
self.accumulator -= self.fixed_dt;
updates += 1;
self.update_count += 1;
}
// 5) Compute interpolation factor for rendering (0..1)
let alpha = if self.fixed_dt.is_zero() {
1.0
} else {
(self.accumulator.as_secs_f32() / self.fixed_dt.as_secs_f32()).clamp(0.0, 1.0)
};
TickPlan {
updates,
alpha,
frame_dt: self.frame_dt.as_secs_f32(),
fixed_dt: self.fixed_dt.as_secs_f32(),
}
}
pub fn frame_dt_seconds(&self) -> f32 { self.frame_dt.as_secs_f32() }
pub fn fixed_dt_seconds(&self) -> f32 { self.fixed_dt.as_secs_f32() }
pub fn alpha(&self) -> f32 {
if self.fixed_dt.is_zero() { 1.0 } else { (self.accumulator.as_secs_f32() / self.fixed_dt.as_secs_f32()).clamp(0.0, 1.0) }
}
}

View file

@ -1,44 +0,0 @@
/// Unused as of now.
#[macro_export]
macro_rules! create_manager {
($manager_name:ident, $trait_name:ident) => {
pub struct $manager_name {
systems: ::indexmap::IndexMap<::std::any::TypeId, Box<dyn $trait_name>>,
}
impl $manager_name {
pub fn new() -> Self {
Self {
systems: ::indexmap::IndexMap::default(),
}
}
pub fn add<S: $trait_name + Default + 'static>(&mut self) {
self.systems
.insert(::std::any::TypeId::of::<S>(), Box::new(S::default()));
}
pub fn remove<S: 'static>(&mut self) {
self.systems.shift_remove(&::std::any::TypeId::of::<S>());
}
pub fn for_each_value<F>(&self, mut f: F)
where
F: FnMut(&dyn $trait_name),
{
for value in self.systems.values() {
f(value.as_ref());
}
}
pub fn for_each_value_mut<F>(&mut self, mut f: F)
where
F: FnMut(&mut dyn $trait_name),
{
for value in self.systems.values_mut() {
f(value.as_mut());
}
}
}
};
}

View file

@ -1,2 +0,0 @@
pub mod typemap;
mod managers;

View file

@ -1,544 +0,0 @@
#[macro_export]
macro_rules! define_typemap {
($name:ident, $($trait_bound:tt)*) => {
pub struct $name {
map: std::collections::HashMap<std::any::TypeId, Box<dyn std::any::Any>>,
}
impl $name {
pub fn new() -> Self {
Self { map: std::collections::HashMap::new() }
}
pub fn insert<T>(&mut self, value: T) -> Option<Box<T>>
where
T: std::any::Any + 'static + $($trait_bound)*,
{
let type_id = std::any::TypeId::of::<T>();
self.map.insert(type_id, Box::new(value)).and_then(|b| b.downcast().ok())
}
pub fn get<T>(&self) -> Option<&T>
where
T: std::any::Any + 'static + $($trait_bound)*,
{
self.map.get(&std::any::TypeId::of::<T>())?.downcast_ref::<T>()
}
pub fn get_mut<T>(&mut self) -> Option<&mut T>
where
T: std::any::Any + 'static + $($trait_bound)*,
{
self.map.get_mut(&std::any::TypeId::of::<T>())?.downcast_mut::<T>()
}
pub fn remove<T>(&mut self) -> Option<Box<T>>
where
T: std::any::Any + 'static + $($trait_bound)*,
{
self.map.remove(&std::any::TypeId::of::<T>())?.downcast().ok()
}
pub fn len(&self) -> usize { self.map.len() }
pub fn is_empty(&self) -> bool { self.map.is_empty() }
pub fn clear(&mut self) { self.map.clear(); }
pub fn contains<T>(&self) -> bool
where
T: std::any::Any + 'static + $($trait_bound)*,
{
self.map.contains_key(&std::any::TypeId::of::<T>())
}
// --- tuple-based multi-get API ---
pub fn get_many<'a, T>(&'a self) -> Option<<T as __tm_get::GetTuple>::Output<'a>>
where
T: __tm_get::GetTuple,
{
<T as __tm_get::GetTuple>::get_from(&self.map)
}
pub fn get_many_mut<'a, T>(&'a mut self) -> Option<<T as __tm_get::GetTupleMut>::Output<'a>>
where
T: __tm_get::GetTupleMut,
{
<T as __tm_get::GetTupleMut>::get_from_mut(&mut self.map)
}
}
impl Default for $name { fn default() -> Self { Self::new() } }
// Put helper traits/impls in a private module to avoid name clashes.
mod __tm_get {
use std::any::{Any, TypeId};
use std::collections::HashMap;
pub trait GetTuple {
type Output<'a>;
fn get_from<'a>(map: &'a HashMap<TypeId, Box<dyn Any>>) -> Option<Self::Output<'a>>;
}
pub trait GetTupleMut {
type Output<'a>;
fn get_from_mut<'a>(map: &'a mut HashMap<TypeId, Box<dyn Any>>) -> Option<Self::Output<'a>>;
}
// Manual implementations for arities 1..=8.
impl<A> GetTuple for (A,)
where
A: Any + 'static,
{
type Output<'a> = (&'a A,);
fn get_from<'a>(map: &'a HashMap<TypeId, Box<dyn Any>>) -> Option<Self::Output<'a>> {
let a = map.get(&TypeId::of::<A>())?.downcast_ref::<A>()?;
Some((a,))
}
}
impl<A> GetTupleMut for (A,)
where
A: Any + 'static,
{
type Output<'a> = (&'a mut A,);
fn get_from_mut<'a>(map: &'a mut HashMap<TypeId, Box<dyn Any>>) -> Option<Self::Output<'a>> {
let ptr_a = { map.get_mut(&TypeId::of::<A>()).map(|v| v.as_mut() as *mut dyn Any) }?;
unsafe {
let a = (&mut *ptr_a).downcast_mut::<A>()?;
Some((a,))
}
}
}
impl<A, B> GetTuple for (A, B)
where
A: Any + 'static,
B: Any + 'static,
{
type Output<'a> = (&'a A, &'a B);
fn get_from<'a>(map: &'a HashMap<TypeId, Box<dyn Any>>) -> Option<Self::Output<'a>> {
let ids = [TypeId::of::<A>(), TypeId::of::<B>()];
if ids[0] == ids[1] { return None; }
let a = map.get(&TypeId::of::<A>())?.downcast_ref::<A>()?;
let b = map.get(&TypeId::of::<B>())?.downcast_ref::<B>()?;
Some((a, b))
}
}
impl<A, B> GetTupleMut for (A, B)
where
A: Any + 'static,
B: Any + 'static,
{
type Output<'a> = (&'a mut A, &'a mut B);
fn get_from_mut<'a>(map: &'a mut HashMap<TypeId, Box<dyn Any>>) -> Option<Self::Output<'a>> {
let ids = [TypeId::of::<A>(), TypeId::of::<B>()];
if ids[0] == ids[1] { return None; }
let ptr_a = { map.get_mut(&TypeId::of::<A>()).map(|v| v.as_mut() as *mut dyn Any) }?;
let ptr_b = { map.get_mut(&TypeId::of::<B>()).map(|v| v.as_mut() as *mut dyn Any) }?;
unsafe {
let a = (&mut *ptr_a).downcast_mut::<A>()?;
let b = (&mut *ptr_b).downcast_mut::<B>()?;
Some((a, b))
}
}
}
impl<A, B, C> GetTuple for (A, B, C)
where
A: Any + 'static,
B: Any + 'static,
C: Any + 'static,
{
type Output<'a> = (&'a A, &'a B, &'a C);
fn get_from<'a>(map: &'a HashMap<TypeId, Box<dyn Any>>) -> Option<Self::Output<'a>> {
let ids = [TypeId::of::<A>(), TypeId::of::<B>(), TypeId::of::<C>()];
if ids[0] == ids[1] || ids[0] == ids[2] || ids[1] == ids[2] { return None; }
let a = map.get(&TypeId::of::<A>())?.downcast_ref::<A>()?;
let b = map.get(&TypeId::of::<B>())?.downcast_ref::<B>()?;
let c = map.get(&TypeId::of::<C>())?.downcast_ref::<C>()?;
Some((a, b, c))
}
}
impl<A, B, C> GetTupleMut for (A, B, C)
where
A: Any + 'static,
B: Any + 'static,
C: Any + 'static,
{
type Output<'a> = (&'a mut A, &'a mut B, &'a mut C);
fn get_from_mut<'a>(map: &'a mut HashMap<TypeId, Box<dyn Any>>) -> Option<Self::Output<'a>> {
let ids = [TypeId::of::<A>(), TypeId::of::<B>(), TypeId::of::<C>()];
if ids[0] == ids[1] || ids[0] == ids[2] || ids[1] == ids[2] { return None; }
let ptr_a = { map.get_mut(&TypeId::of::<A>()).map(|v| v.as_mut() as *mut dyn Any) }?;
let ptr_b = { map.get_mut(&TypeId::of::<B>()).map(|v| v.as_mut() as *mut dyn Any) }?;
let ptr_c = { map.get_mut(&TypeId::of::<C>()).map(|v| v.as_mut() as *mut dyn Any) }?;
unsafe {
let a = (&mut *ptr_a).downcast_mut::<A>()?;
let b = (&mut *ptr_b).downcast_mut::<B>()?;
let c = (&mut *ptr_c).downcast_mut::<C>()?;
Some((a, b, c))
}
}
}
impl<A, B, C, D> GetTuple for (A, B, C, D)
where
A: Any + 'static,
B: Any + 'static,
C: Any + 'static,
D: Any + 'static,
{
type Output<'a> = (&'a A, &'a B, &'a C, &'a D);
fn get_from<'a>(map: &'a HashMap<TypeId, Box<dyn Any>>) -> Option<Self::Output<'a>> {
let ids = [TypeId::of::<A>(), TypeId::of::<B>(), TypeId::of::<C>(), TypeId::of::<D>()];
for i in 0..ids.len() { for j in (i+1)..ids.len() { if ids[i] == ids[j] { return None; } } }
let a = map.get(&TypeId::of::<A>())?.downcast_ref::<A>()?;
let b = map.get(&TypeId::of::<B>())?.downcast_ref::<B>()?;
let c = map.get(&TypeId::of::<C>())?.downcast_ref::<C>()?;
let d = map.get(&TypeId::of::<D>())?.downcast_ref::<D>()?;
Some((a, b, c, d))
}
}
impl<A, B, C, D> GetTupleMut for (A, B, C, D)
where
A: Any + 'static,
B: Any + 'static,
C: Any + 'static,
D: Any + 'static,
{
type Output<'a> = (&'a mut A, &'a mut B, &'a mut C, &'a mut D);
fn get_from_mut<'a>(map: &'a mut HashMap<TypeId, Box<dyn Any>>) -> Option<Self::Output<'a>> {
let ids = [TypeId::of::<A>(), TypeId::of::<B>(), TypeId::of::<C>(), TypeId::of::<D>()];
for i in 0..ids.len() { for j in (i+1)..ids.len() { if ids[i] == ids[j] { return None; } } }
let ptr_a = { map.get_mut(&TypeId::of::<A>()).map(|v| v.as_mut() as *mut dyn Any) }?;
let ptr_b = { map.get_mut(&TypeId::of::<B>()).map(|v| v.as_mut() as *mut dyn Any) }?;
let ptr_c = { map.get_mut(&TypeId::of::<C>()).map(|v| v.as_mut() as *mut dyn Any) }?;
let ptr_d = { map.get_mut(&TypeId::of::<D>()).map(|v| v.as_mut() as *mut dyn Any) }?;
unsafe {
let a = (&mut *ptr_a).downcast_mut::<A>()?;
let b = (&mut *ptr_b).downcast_mut::<B>()?;
let c = (&mut *ptr_c).downcast_mut::<C>()?;
let d = (&mut *ptr_d).downcast_mut::<D>()?;
Some((a, b, c, d))
}
}
}
impl<A, B, C, D, E> GetTuple for (A, B, C, D, E)
where
A: Any + 'static,
B: Any + 'static,
C: Any + 'static,
D: Any + 'static,
E: Any + 'static,
{
type Output<'a> = (&'a A, &'a B, &'a C, &'a D, &'a E);
fn get_from<'a>(map: &'a HashMap<TypeId, Box<dyn Any>>) -> Option<Self::Output<'a>> {
let ids = [TypeId::of::<A>(), TypeId::of::<B>(), TypeId::of::<C>(), TypeId::of::<D>(), TypeId::of::<E>()];
for i in 0..ids.len() { for j in (i+1)..ids.len() { if ids[i] == ids[j] { return None; } } }
let a = map.get(&TypeId::of::<A>())?.downcast_ref::<A>()?;
let b = map.get(&TypeId::of::<B>())?.downcast_ref::<B>()?;
let c = map.get(&TypeId::of::<C>())?.downcast_ref::<C>()?;
let d = map.get(&TypeId::of::<D>())?.downcast_ref::<D>()?;
let e = map.get(&TypeId::of::<E>())?.downcast_ref::<E>()?;
Some((a, b, c, d, e))
}
}
impl<A, B, C, D, E> GetTupleMut for (A, B, C, D, E)
where
A: Any + 'static,
B: Any + 'static,
C: Any + 'static,
D: Any + 'static,
E: Any + 'static,
{
type Output<'a> = (&'a mut A, &'a mut B, &'a mut C, &'a mut D, &'a mut E);
fn get_from_mut<'a>(map: &'a mut HashMap<TypeId, Box<dyn Any>>) -> Option<Self::Output<'a>> {
let ids = [TypeId::of::<A>(), TypeId::of::<B>(), TypeId::of::<C>(), TypeId::of::<D>(), TypeId::of::<E>()];
for i in 0..ids.len() { for j in (i+1)..ids.len() { if ids[i] == ids[j] { return None; } } }
let ptr_a = { map.get_mut(&TypeId::of::<A>()).map(|v| v.as_mut() as *mut dyn Any) }?;
let ptr_b = { map.get_mut(&TypeId::of::<B>()).map(|v| v.as_mut() as *mut dyn Any) }?;
let ptr_c = { map.get_mut(&TypeId::of::<C>()).map(|v| v.as_mut() as *mut dyn Any) }?;
let ptr_d = { map.get_mut(&TypeId::of::<D>()).map(|v| v.as_mut() as *mut dyn Any) }?;
let ptr_e = { map.get_mut(&TypeId::of::<E>()).map(|v| v.as_mut() as *mut dyn Any) }?;
unsafe {
let a = (&mut *ptr_a).downcast_mut::<A>()?;
let b = (&mut *ptr_b).downcast_mut::<B>()?;
let c = (&mut *ptr_c).downcast_mut::<C>()?;
let d = (&mut *ptr_d).downcast_mut::<D>()?;
let e = (&mut *ptr_e).downcast_mut::<E>()?;
Some((a, b, c, d, e))
}
}
}
impl<A, B, C, D, E, F> GetTuple for (A, B, C, D, E, F)
where
A: Any + 'static,
B: Any + 'static,
C: Any + 'static,
D: Any + 'static,
E: Any + 'static,
F: Any + 'static,
{
type Output<'a> = (&'a A, &'a B, &'a C, &'a D, &'a E, &'a F);
fn get_from<'a>(map: &'a HashMap<TypeId, Box<dyn Any>>) -> Option<Self::Output<'a>> {
let ids = [TypeId::of::<A>(), TypeId::of::<B>(), TypeId::of::<C>(), TypeId::of::<D>(), TypeId::of::<E>(), TypeId::of::<F>()];
for i in 0..ids.len() { for j in (i+1)..ids.len() { if ids[i] == ids[j] { return None; } } }
let a = map.get(&TypeId::of::<A>())?.downcast_ref::<A>()?;
let b = map.get(&TypeId::of::<B>())?.downcast_ref::<B>()?;
let c = map.get(&TypeId::of::<C>())?.downcast_ref::<C>()?;
let d = map.get(&TypeId::of::<D>())?.downcast_ref::<D>()?;
let e = map.get(&TypeId::of::<E>())?.downcast_ref::<E>()?;
let f = map.get(&TypeId::of::<F>())?.downcast_ref::<F>()?;
Some((a, b, c, d, e, f))
}
}
impl<A, B, C, D, E, F> GetTupleMut for (A, B, C, D, E, F)
where
A: Any + 'static,
B: Any + 'static,
C: Any + 'static,
D: Any + 'static,
E: Any + 'static,
F: Any + 'static,
{
type Output<'a> = (&'a mut A, &'a mut B, &'a mut C, &'a mut D, &'a mut E, &'a mut F);
fn get_from_mut<'a>(map: &'a mut HashMap<TypeId, Box<dyn Any>>) -> Option<Self::Output<'a>> {
let ids = [TypeId::of::<A>(), TypeId::of::<B>(), TypeId::of::<C>(), TypeId::of::<D>(), TypeId::of::<E>(), TypeId::of::<F>()];
for i in 0..ids.len() { for j in (i+1)..ids.len() { if ids[i] == ids[j] { return None; } } }
let ptr_a = { map.get_mut(&TypeId::of::<A>()).map(|v| v.as_mut() as *mut dyn Any) }?;
let ptr_b = { map.get_mut(&TypeId::of::<B>()).map(|v| v.as_mut() as *mut dyn Any) }?;
let ptr_c = { map.get_mut(&TypeId::of::<C>()).map(|v| v.as_mut() as *mut dyn Any) }?;
let ptr_d = { map.get_mut(&TypeId::of::<D>()).map(|v| v.as_mut() as *mut dyn Any) }?;
let ptr_e = { map.get_mut(&TypeId::of::<E>()).map(|v| v.as_mut() as *mut dyn Any) }?;
let ptr_f = { map.get_mut(&TypeId::of::<F>()).map(|v| v.as_mut() as *mut dyn Any) }?;
unsafe {
let a = (&mut *ptr_a).downcast_mut::<A>()?;
let b = (&mut *ptr_b).downcast_mut::<B>()?;
let c = (&mut *ptr_c).downcast_mut::<C>()?;
let d = (&mut *ptr_d).downcast_mut::<D>()?;
let e = (&mut *ptr_e).downcast_mut::<E>()?;
let f = (&mut *ptr_f).downcast_mut::<F>()?;
Some((a, b, c, d, e, f))
}
}
}
impl<A, B, C, D, E, F, G> GetTuple for (A, B, C, D, E, F, G)
where
A: Any + 'static,
B: Any + 'static,
C: Any + 'static,
D: Any + 'static,
E: Any + 'static,
F: Any + 'static,
G: Any + 'static,
{
type Output<'a> = (&'a A, &'a B, &'a C, &'a D, &'a E, &'a F, &'a G);
fn get_from<'a>(map: &'a HashMap<TypeId, Box<dyn Any>>) -> Option<Self::Output<'a>> {
let ids = [TypeId::of::<A>(), TypeId::of::<B>(), TypeId::of::<C>(), TypeId::of::<D>(), TypeId::of::<E>(), TypeId::of::<F>(), TypeId::of::<G>()];
for i in 0..ids.len() { for j in (i+1)..ids.len() { if ids[i] == ids[j] { return None; } } }
let a = map.get(&TypeId::of::<A>())?.downcast_ref::<A>()?;
let b = map.get(&TypeId::of::<B>())?.downcast_ref::<B>()?;
let c = map.get(&TypeId::of::<C>())?.downcast_ref::<C>()?;
let d = map.get(&TypeId::of::<D>())?.downcast_ref::<D>()?;
let e = map.get(&TypeId::of::<E>())?.downcast_ref::<E>()?;
let f = map.get(&TypeId::of::<F>())?.downcast_ref::<F>()?;
let g = map.get(&TypeId::of::<G>())?.downcast_ref::<G>()?;
Some((a, b, c, d, e, f, g))
}
}
impl<A, B, C, D, E, F, G> GetTupleMut for (A, B, C, D, E, F, G)
where
A: Any + 'static,
B: Any + 'static,
C: Any + 'static,
D: Any + 'static,
E: Any + 'static,
F: Any + 'static,
G: Any + 'static,
{
type Output<'a> = (&'a mut A, &'a mut B, &'a mut C, &'a mut D, &'a mut E, &'a mut F, &'a mut G);
fn get_from_mut<'a>(map: &'a mut HashMap<TypeId, Box<dyn Any>>) -> Option<Self::Output<'a>> {
let ids = [TypeId::of::<A>(), TypeId::of::<B>(), TypeId::of::<C>(), TypeId::of::<D>(), TypeId::of::<E>(), TypeId::of::<F>(), TypeId::of::<G>()];
for i in 0..ids.len() { for j in (i+1)..ids.len() { if ids[i] == ids[j] { return None; } } }
let ptr_a = { map.get_mut(&TypeId::of::<A>()).map(|v| v.as_mut() as *mut dyn Any) }?;
let ptr_b = { map.get_mut(&TypeId::of::<B>()).map(|v| v.as_mut() as *mut dyn Any) }?;
let ptr_c = { map.get_mut(&TypeId::of::<C>()).map(|v| v.as_mut() as *mut dyn Any) }?;
let ptr_d = { map.get_mut(&TypeId::of::<D>()).map(|v| v.as_mut() as *mut dyn Any) }?;
let ptr_e = { map.get_mut(&TypeId::of::<E>()).map(|v| v.as_mut() as *mut dyn Any) }?;
let ptr_f = { map.get_mut(&TypeId::of::<F>()).map(|v| v.as_mut() as *mut dyn Any) }?;
let ptr_g = { map.get_mut(&TypeId::of::<G>()).map(|v| v.as_mut() as *mut dyn Any) }?;
unsafe {
let a = (&mut *ptr_a).downcast_mut::<A>()?;
let b = (&mut *ptr_b).downcast_mut::<B>()?;
let c = (&mut *ptr_c).downcast_mut::<C>()?;
let d = (&mut *ptr_d).downcast_mut::<D>()?;
let e = (&mut *ptr_e).downcast_mut::<E>()?;
let f = (&mut *ptr_f).downcast_mut::<F>()?;
let g = (&mut *ptr_g).downcast_mut::<G>()?;
Some((a, b, c, d, e, f, g))
}
}
}
impl<A, B, C, D, E, F, G, H> GetTuple for (A, B, C, D, E, F, G, H)
where
A: Any + 'static,
B: Any + 'static,
C: Any + 'static,
D: Any + 'static,
E: Any + 'static,
F: Any + 'static,
G: Any + 'static,
H: Any + 'static,
{
type Output<'a> = (&'a A, &'a B, &'a C, &'a D, &'a E, &'a F, &'a G, &'a H);
fn get_from<'a>(map: &'a HashMap<TypeId, Box<dyn Any>>) -> Option<Self::Output<'a>> {
let ids = [TypeId::of::<A>(), TypeId::of::<B>(), TypeId::of::<C>(), TypeId::of::<D>(), TypeId::of::<E>(), TypeId::of::<F>(), TypeId::of::<G>(), TypeId::of::<H>()];
for i in 0..ids.len() { for j in (i+1)..ids.len() { if ids[i] == ids[j] { return None; } } }
let a = map.get(&TypeId::of::<A>())?.downcast_ref::<A>()?;
let b = map.get(&TypeId::of::<B>())?.downcast_ref::<B>()?;
let c = map.get(&TypeId::of::<C>())?.downcast_ref::<C>()?;
let d = map.get(&TypeId::of::<D>())?.downcast_ref::<D>()?;
let e = map.get(&TypeId::of::<E>())?.downcast_ref::<E>()?;
let f = map.get(&TypeId::of::<F>())?.downcast_ref::<F>()?;
let g = map.get(&TypeId::of::<G>())?.downcast_ref::<G>()?;
let h = map.get(&TypeId::of::<H>())?.downcast_ref::<H>()?;
Some((a, b, c, d, e, f, g, h))
}
}
impl<A, B, C, D, E, F, G, H> GetTupleMut for (A, B, C, D, E, F, G, H)
where
A: Any + 'static,
B: Any + 'static,
C: Any + 'static,
D: Any + 'static,
E: Any + 'static,
F: Any + 'static,
G: Any + 'static,
H: Any + 'static,
{
type Output<'a> = (&'a mut A, &'a mut B, &'a mut C, &'a mut D, &'a mut E, &'a mut F, &'a mut G, &'a mut H);
fn get_from_mut<'a>(map: &'a mut HashMap<TypeId, Box<dyn Any>>) -> Option<Self::Output<'a>> {
let ids = [TypeId::of::<A>(), TypeId::of::<B>(), TypeId::of::<C>(), TypeId::of::<D>(), TypeId::of::<E>(), TypeId::of::<F>(), TypeId::of::<G>(), TypeId::of::<H>()];
for i in 0..ids.len() { for j in (i+1)..ids.len() { if ids[i] == ids[j] { return None; } } }
let ptr_a = { map.get_mut(&TypeId::of::<A>()).map(|v| v.as_mut() as *mut dyn Any) }?;
let ptr_b = { map.get_mut(&TypeId::of::<B>()).map(|v| v.as_mut() as *mut dyn Any) }?;
let ptr_c = { map.get_mut(&TypeId::of::<C>()).map(|v| v.as_mut() as *mut dyn Any) }?;
let ptr_d = { map.get_mut(&TypeId::of::<D>()).map(|v| v.as_mut() as *mut dyn Any) }?;
let ptr_e = { map.get_mut(&TypeId::of::<E>()).map(|v| v.as_mut() as *mut dyn Any) }?;
let ptr_f = { map.get_mut(&TypeId::of::<F>()).map(|v| v.as_mut() as *mut dyn Any) }?;
let ptr_g = { map.get_mut(&TypeId::of::<G>()).map(|v| v.as_mut() as *mut dyn Any) }?;
let ptr_h = { map.get_mut(&TypeId::of::<H>()).map(|v| v.as_mut() as *mut dyn Any) }?;
unsafe {
let a = (&mut *ptr_a).downcast_mut::<A>()?;
let b = (&mut *ptr_b).downcast_mut::<B>()?;
let c = (&mut *ptr_c).downcast_mut::<C>()?;
let d = (&mut *ptr_d).downcast_mut::<D>()?;
let e = (&mut *ptr_e).downcast_mut::<E>()?;
let f = (&mut *ptr_f).downcast_mut::<F>()?;
let g = (&mut *ptr_g).downcast_mut::<G>()?;
let h = (&mut *ptr_h).downcast_mut::<H>()?;
Some((a, b, c, d, e, f, g, h))
}
}
}
}
};
}
// pub struct TypeMap {
// map: HashMap<TypeId, Box<dyn Any>>,
// }
//
// impl TypeMap {
// pub fn new() -> Self {
// Self {
// map: HashMap::new(),
// }
// }
//
// pub fn insert<T: Any + 'static>(&mut self, value: T) -> Option<Box<T>> {
// let type_id = TypeId::of::<T>();
// self.map
// .insert(type_id, Box::new(value))
// .and_then(|boxed| boxed.downcast().ok())
// }
//
// pub fn get<T>(&self) -> Option<&T>
// where
// T: Any + 'static,
// {
// self.map.get(&TypeId::of::<T>())
// .and_then(|any| any.downcast_ref::<T>())
// }
//
// pub fn get_mut<T>(&mut self) -> Option<&mut T>
// where
// T: Any + 'static,
// {
// self.map.get_mut(&TypeId::of::<T>()).and_then(|any| any.downcast_mut::<T>())
// }
//
// pub fn remove<T: Any>(&mut self) -> Option<Box<T>> {
// unimplemented!()
// }
// }
//
// impl Default for TypeMap {
// fn default() -> Self {
// Self::new()
// }
// }
#[cfg(test)]
mod tests {
use crate::define_typemap;
define_typemap!(TestMap,);
#[test]
fn get_test() {
let mut tm = TestMap::new();
tm.insert::<u32>(42);
let v = tm.get::<u32>().expect("value should be present");
assert_eq!(*v, 42);
}
#[test]
fn get_many_test() {
let mut tm = TestMap::new();
tm.insert::<u32>(1);
tm.insert::<i32>(-2);
tm.insert::<f32>(3.5);
let (a, b, c) = tm
.get_many::<(u32, i32, f32)>()
.expect("all values should be present");
assert_eq!((*a, *b, *c), (1, -2, 3.5));
}
#[test]
fn get_many_mut_test() {
let mut tm = TestMap::new();
tm.insert::<i32>(-2);
tm.insert::<u32>(1);
tm.insert::<f32>(3.5);
let (a, b, c) = tm
.get_many_mut::<(i32, u32, f32)>()
.expect("all values should be present");
*a = 4;
*b = 5;
*c = 6.5;
}
}

View file

@ -1,9 +0,0 @@
[package]
name = "raidillon_ecs"
version = "0.1.0"
edition = "2024"
[dependencies]
glam = "0.30.5"
raidillon_assets = { path = "../asset" }
rapier3d = "0.30.1"

View file

@ -1,30 +0,0 @@
use glam::{Vec3, Quat, Mat4};
pub use raidillon_assets::ModelID;
#[derive(Copy, Clone)]
pub struct Transform {
pub translation: Vec3,
pub rotation: Quat,
pub scale: Vec3,
}
impl Transform {
pub fn matrix(&self) -> Mat4 {
Mat4::from_scale_rotation_translation(self.scale, self.rotation, self.translation)
}
}
pub struct ModelHandle(pub ModelID);
#[derive(Copy, Clone)]
pub struct RigidBodyComponent(pub rapier3d::dynamics::RigidBodyHandle);
#[derive(Copy, Clone)]
pub struct CharacterBodyComponent(pub rapier3d::dynamics::RigidBodyHandle);
#[derive(Debug, Default, PartialEq, Eq, Clone, Copy)]
pub enum CameraMode {
#[default]
Kinematic,
Debug,
}

View file

@ -1,3 +0,0 @@
pub mod components;
pub use components::{Transform, ModelID};

View file

@ -1,15 +0,0 @@
[package]
name = "raidillon_engine"
version = "0.1.0"
edition = "2024"
[dependencies]
raidillon_assets = { path = "../asset" }
raidillon_core = { path = "../core" }
raidillon_platform = { path = "../platform" }
raidillon_ecs = { path = "../ecs" }
winit = "0.30.12"
hecs = "0.10.5"
indexmap = "2.10.0"
glam = "0.30.8"
egui = "0.33.2"

View file

@ -1,88 +0,0 @@
use std::cell::RefCell;
use std::rc::Rc;
use raidillon_core::scene::{Scene, SceneManager};
use crate::system::{SystemContext, SystemManager};
use raidillon_platform::PlatformContext;
use raidillon_core::{define_typemap};
use raidillon_core::engine::EngineTrait;
use crate::input::InputState;
use crate::resources::EngineResources;
pub struct Engine {
pub scene_manager: SceneManager,
pub system_manager: SystemManager,
pub resources: EngineResources,
}
impl Engine {
fn load_default_resources(&mut self) {
let input = InputState::default();
self.resources.insert(input);
}
}
impl EngineTrait for Engine {
type PlatformCtx = PlatformContext;
fn new() -> Self {
let scene_manager = SceneManager::new();
let system_manager = SystemManager::new();
let mut s = Self {
scene_manager,
system_manager,
resources: EngineResources::new(),
};
s.load_default_resources();
s
}
/// Initialize systems, load the world.
fn initialize(&mut self, platform_context: PlatformContext) {
// Engine Loading Stage 1: initialize systems
for system in self.system_manager.systems.values_mut() {
system.initialize();
}
self.resources.insert(platform_context);
// Engine Loading Stage 2: load world
for system in self.system_manager.systems.values_mut() {
system.load_world(&mut self.resources, &mut self.scene_manager.current_mut());
}
}
/// Update the engine
fn frame_update(&mut self, platform_context: PlatformContext) {
self.resources.insert(platform_context);
for system in self.system_manager.systems.values_mut() {
system.frame_update(&mut self.resources, &mut self.scene_manager.current_mut());
}
}
fn fixed_update(&mut self, platform_context: PlatformContext) {
self.resources.insert(platform_context);
for system in self.system_manager.systems.values_mut() {
system.fixed_update(&mut self.resources, &mut self.scene_manager.current_mut());
}
}
fn handle_event(&mut self, platform_context: PlatformContext) {
self.resources.get_mut::<InputState>().unwrap().handle_event(&platform_context.current_event);
self.resources.insert(platform_context);
for system in self.system_manager.systems.values_mut() {
system.handle_event(&mut self.resources, &mut self.scene_manager.current_mut());
}
}
// pub fn build_system_context(&mut self) -> SystemContext {
// SystemContext {
// scene: self.scene_manager.current_mut(),
// }
// }
fn current_scene_mut(&mut self) -> &mut Scene {
self.scene_manager.current_mut()
}
fn current_scene(&self) -> &Scene {
self.scene_manager.current()
}
}

View file

@ -1,69 +0,0 @@
use std::collections::HashSet;
use winit::event::{ElementState, Event, MouseButton, WindowEvent};
use winit::keyboard::{KeyCode, PhysicalKey};
/// A utility to help with buffering input.
/// Meant to be plugged into systems.
#[derive(Default, Clone, Debug)]
pub struct InputState {
held_keys: HashSet<KeyCode>,
held_mouse: HashSet<MouseButton>,
}
impl InputState {
fn new() -> Self {
Default::default()
}
pub fn handle_event(&mut self, event: &Event<()>) {
if let Event::WindowEvent { event, .. } = event {
match event {
// Keyboard
WindowEvent::KeyboardInput { event: key_event, .. } => {
if let PhysicalKey::Code(code) = key_event.physical_key {
match key_event.state {
ElementState::Pressed => {
self.held_keys.insert(code);
}
ElementState::Released => {
self.held_keys.remove(&code);
}
}
}
}
// Mouse
WindowEvent::MouseInput { state, button, .. } => {
match state {
ElementState::Pressed => {
self.held_mouse.insert(*button);
}
ElementState::Released => {
self.held_mouse.remove(button);
}
}
}
WindowEvent::Focused(focused) => {
if !*focused {
self.clear();
}
}
_ => {}
}
}
}
pub fn key_held(&self, code: KeyCode) -> bool {
self.held_keys.contains(&code)
}
pub fn mouse_held(&self, button: MouseButton) -> bool {
self.held_mouse.contains(&button)
}
pub fn clear(&mut self) {
self.held_keys.clear();
self.held_mouse.clear();
}
}

View file

@ -1,9 +0,0 @@
pub mod engine;
pub mod system;
mod input;
pub mod systems;
mod resources;
pub use crate::engine::Engine;
pub use crate::resources::EngineResources;
pub use input::InputState;

View file

@ -1,3 +0,0 @@
use raidillon_core::define_typemap;
define_typemap!(EngineResources,);

View file

@ -1,45 +0,0 @@
use indexmap::IndexMap;
use raidillon_core::scene::Scene;
use raidillon_platform::PlatformContext;
use std::any::TypeId;
use std::cell::RefCell;
use std::rc::Rc;
use crate::input::InputState;
use crate::resources::EngineResources;
pub struct SystemContext<'a> {
pub scene: &'a mut Scene,
pub platform_context: PlatformContext,
pub input_state: Rc<RefCell<InputState>>,
}
pub trait System {
/// Initialize the system.
fn initialize(&mut self) {}
/// Spawn the first entities of the world.
fn load_world(&mut self, res: &mut EngineResources, scene: &mut Scene) {}
fn handle_event(&mut self, res: &mut EngineResources, scene: &mut Scene) {}
fn fixed_update(&mut self, res: &mut EngineResources, scene: &mut Scene) {}
fn frame_update(&mut self, res: &mut EngineResources, scene: &mut Scene) {}
}
pub struct SystemManager {
pub systems: IndexMap<TypeId, Box<dyn System>>,
}
impl SystemManager {
pub fn new() -> Self {
Self {
systems: IndexMap::default(),
}
}
pub fn add<S: System + Default + 'static>(&mut self) {
self.systems
.insert(TypeId::of::<S>(), Box::new(S::default()));
}
pub fn remove<S: 'static>(&mut self) {
self.systems.shift_remove(&TypeId::of::<S>());
}
}

View file

@ -1,12 +0,0 @@
[package]
name = "raidillon_game"
version = "0.1.0"
edition = "2024"
[dependencies]
raidillon_app = { path = "../app", features = ["glium"] }
glam = "0.30.5"
winit = "0.30.12"
rapier3d = "0.30.1"
hecs = "0.10.5"
egui = "0.33.2"

View file

@ -1,140 +0,0 @@
use raidillon_app::prelude::*;
mod systems;
use glam::{Quat, Vec3};
use rapier3d::dynamics::{CoefficientCombineRule, RigidBodyType};
use rapier3d::prelude::ColliderBuilder;
use winit::event::{Event, WindowEvent};
use systems::debug_camera::FPSDebugCameraSystem;
use crate::systems::common::should_draw_menu;
use crate::systems::{
DisplaySettings, KeybindsSystem, KinematicCharacterController, MenuSystem, PhysicsSystem,
PhysicsDebugSystem,
};
const TEST_GLTF: &str = "checkered-sphere.glb";
const PLANE_GLTF: &str = "plane.glb";
const MAIN_SCENE_ID: &str = "main_scene";
#[derive(Default)]
struct UpdateAspectRatioSystem;
impl System for UpdateAspectRatioSystem {
fn handle_event(&mut self, res: &mut EngineResources, scene: &mut Scene) {
let pctx = res.get::<PlatformContext>().unwrap();
if let Event::WindowEvent { event: WindowEvent::Resized(sz), .. } =
pctx.current_event
{
scene.world
.query_mut::<&mut Camera>()
.into_iter()
.for_each(|(_, cam)| {
cam.aspect = sz.width as f32 / sz.height as f32;
});
}
}
}
#[derive(Default)]
struct MainSystem;
impl System for MainSystem {
fn load_world(&mut self, res: &mut EngineResources, scene: &mut Scene) {
let pctx = res.get::<PlatformContext>().expect("PlatformContext missing").clone();
let physics = scene.resources.get_mut::<Physics>().expect("Physics missing");
// Spawn Sphere
{
let tr = Transform {
translation: Vec3::new(0.0, 5.0, 0.0),
rotation: Quat::IDENTITY,
scale: Vec3::new(1.0, 1.0, 1.0),
};
let collider = ColliderBuilder::ball(1.0)
.restitution(0.7)
.restitution_combine_rule(CoefficientCombineRule::Max)
.build();
let rb_handle = physics.add_rigid_body(RigidBodyType::Dynamic, tr, collider);
pctx.asset_manager.borrow_mut().load_gltf(TEST_GLTF, &model_path(TEST_GLTF));
scene.world.spawn((
tr,
ModelHandle(TEST_GLTF),
RigidBodyComponent(rb_handle),
));
}
// Spawn Plane
{
let tr = Transform {
translation: Vec3::new(0.0, 0.0, 0.0),
rotation: Quat::IDENTITY,
scale: Vec3::new(10.0, 1.0, 10.0),
};
let collider = ColliderBuilder::cuboid(10.0, 0.01, 10.0).build();
let rb_handle = physics.add_rigid_body(RigidBodyType::Fixed, tr, collider);
pctx.asset_manager.borrow_mut().load_gltf(PLANE_GLTF, &model_path(PLANE_GLTF));
scene.world.spawn((
tr,
ModelHandle(PLANE_GLTF),
RigidBodyComponent(rb_handle),
));
}
scene.world.spawn((Camera {
eye: Vec3::new(0.0, 2.0, 3.0),
center: Vec3::ZERO,
up: Vec3::Y,
fovy: 60_f32.to_radians(),
aspect: pctx.frame_width / pctx.frame_height,
znear: 0.1,
zfar: 100.0},
CameraMode::default(),
));
}
fn frame_update(&mut self, res: &mut EngineResources, scene: &mut Scene) {
let (
pctx,
input,
) = res.get_many_mut::<(
PlatformContext,
InputState,
)>().unwrap();
let mut egui_queue = pctx.egui_queue.borrow_mut();
let time_ctx = pctx.time_ctx.clone();
let mut character_pos = Vec3::ZERO;
for (_ent, (tr, ch_component)) in scene.world.query::<(&Transform, &CharacterBodyComponent)>().iter() {
character_pos = tr.translation;
}
egui_queue.queue(move |egui_ctx| {
// disable text selection on all labels.
egui_ctx.style_mut(|style| {
style.interaction.selectable_labels = false;
});
egui::Window::new("Debug").show(egui_ctx, |ui| {
ui.label("Hello World!");
ui.label(format!("Frame Delta: {:.3}", time_ctx.frame_dt));
ui.label(format!("Fixed Delta: {:.3}", time_ctx.fixed_dt));
ui.label(format!("FPS: {:.3}", 1.0 / time_ctx.frame_dt));
ui.label(format!("Character POS: {character_pos:.3}"));
});
});
}
}
fn main() {
raidillon_app::App::new()
.add_system::<PhysicsSystem>()
.add_system::<PhysicsDebugSystem>()
.add_system::<KeybindsSystem>()
.add_system::<KinematicCharacterController>()
.add_system::<FPSDebugCameraSystem>()
.add_system::<MenuSystem>()
.add_system::<DisplaySettings>()
.add_system::<MainSystem>()
.add_system::<UpdateAspectRatioSystem>()
.add_scene(MAIN_SCENE_ID, Scene::new(MAIN_SCENE_ID.to_owned(), None))
.set_active_scene(MAIN_SCENE_ID)
.run("Raidillon".to_string(), 2560, 1080);
}

View file

@ -1,34 +0,0 @@
use glam::Vec3;
use raidillon_app::prelude::*;
use crate::systems::menu::MenuState;
pub fn is_camera_mode_valid(scene: &mut Scene, mode: CameraMode) -> bool {
let mut q = scene.world.query::<(&Camera, &CameraMode)>();
let (cam_ent, (cam, cam_mode)) = q
.iter()
.next()
.unwrap();
*cam_mode == mode
}
pub fn is_mouse_look_enabled(scene: &mut Scene) -> bool {
let mut q = scene.world.query::<(&MenuState)>();
let (_ent, mode) = q.iter().next().unwrap();
*mode == MenuState::Closed
}
pub fn camera_front(yaw: f32, pitch: f32) -> Vec3 {
let yaw_rad = yaw.to_radians();
let pitch_rad = pitch.to_radians();
Vec3::new(
yaw_rad.cos() * pitch_rad.cos(),
pitch_rad.sin(),
yaw_rad.sin() * pitch_rad.cos(),
).normalize()
}
pub fn should_draw_menu(scene: &mut Scene) -> bool {
let mut q = scene.world.query::<(&MenuState)>();
let (_ent, mode) = q.iter().next().unwrap();
*mode == MenuState::Open
}

View file

@ -1,89 +0,0 @@
use glam::{Quat, Vec3};
use winit::event::DeviceEvent::MouseMotion;
use winit::event::{ElementState, Event, MouseButton, WindowEvent};
use winit::keyboard::{KeyCode, PhysicalKey};
use winit::window::CursorGrabMode;
use raidillon_app::prelude::*;
use crate::systems::common::{camera_front, is_camera_mode_valid, is_mouse_look_enabled};
use crate::systems::menu::MenuState;
pub struct FPSDebugCameraSystem {
mouse_delta: (f64, f64),
position: Vec3,
yaw: f32,
pitch: f32,
speed: f32,
sensitivity: f32,
}
impl Default for FPSDebugCameraSystem {
fn default() -> Self {
Self {
mouse_delta: Default::default(),
position: Vec3::new(0.0, 0.0, 2.0),
yaw: -90.0,
pitch: 0.0,
speed: 8.0,
sensitivity: 0.1,
}
}
}
impl System for FPSDebugCameraSystem {
fn handle_event(&mut self, res: &mut EngineResources, scene: &mut Scene) {
if !(is_camera_mode_valid(scene, CameraMode::Debug) && is_mouse_look_enabled(scene)) {
return
}
let pctx = res.get::<PlatformContext>().unwrap();
let event2 = pctx.current_event.clone();
match event2 {
Event::DeviceEvent { device_id, event} => {
match event {
MouseMotion { delta } => {
self.mouse_delta.0 += delta.0;
self.mouse_delta.1 += delta.1;
},
_ => {}
}
},
_ => {},
}
}
fn frame_update(&mut self, res: &mut EngineResources, scene: &mut Scene) {
let (pctx, input) = res.get_many::<(PlatformContext, InputState)>().unwrap();
if is_mouse_look_enabled(scene) {
self.yaw += self.mouse_delta.0 as f32 * self.sensitivity;
self.pitch -= self.mouse_delta.1 as f32 * self.sensitivity;
self.pitch = self.pitch.clamp(-89.0, 89.0);
}
let front = camera_front(self.yaw, self.pitch);
let right_vec = front.cross(Vec3::Y).normalize();
if is_mouse_look_enabled(scene) {
if input.key_held(KeyCode::KeyW) {
self.position += front * pctx.time_ctx.frame_dt * self.speed;
}
if input.key_held(KeyCode::KeyS) {
self.position -= front * pctx.time_ctx.frame_dt * self.speed;
}
if input.key_held(KeyCode::KeyA) {
self.position -= right_vec * pctx.time_ctx.frame_dt * self.speed;
}
if input.key_held(KeyCode::KeyD) {
self.position += right_vec * pctx.time_ctx.frame_dt * self.speed;
}
}
if is_camera_mode_valid(scene, CameraMode::Debug) {
scene.world.query_mut::<&mut Camera>().into_iter().for_each(|(_, camera)| {
camera.eye = self.position;
camera.center = self.position + front;
});
}
self.mouse_delta = (0.0, 0.0);
}
}

View file

@ -1,94 +0,0 @@
use std::sync::{Arc, Mutex};
use raidillon_app::prelude::*;
use crate::systems::common::should_draw_menu;
#[derive(Clone, Copy, PartialEq, Eq)]
enum SettingsTab {
Display,
}
impl Default for SettingsTab {
fn default() -> Self {
SettingsTab::Display
}
}
#[derive(Clone, Default)]
struct DisplaySettingsUiState {
selected_fullscreen_mode: WindowMode,
active_tab: SettingsTab,
}
#[derive(Default)]
pub struct DisplaySettings {
ui_state: Arc<Mutex<DisplaySettingsUiState>>,
}
impl System for DisplaySettings {
fn load_world(&mut self, res: &mut EngineResources, scene: &mut Scene) {
let pctx = res.get_mut::<PlatformContext>().unwrap();
// sync the settings with UI state once
if let (Ok(settings_handle), Ok(mut state)) = (pctx.settings.read(), self.ui_state.lock()) {
state.selected_fullscreen_mode = settings_handle.display_settings.fullscreen_mode;
}
}
fn frame_update(&mut self, res: &mut EngineResources, scene: &mut Scene) {
if should_draw_menu(scene) {
let pctx = res.get_mut::<PlatformContext>().unwrap();
let settings = pctx.settings.clone();
let ui_state = self.ui_state.clone();
pctx.egui_queue.borrow_mut().queue(move |egui_ctx| {
egui::Window::new("Settings").default_open(false).show(egui_ctx, |ui| {
let mut state = ui_state.lock().unwrap();
ui.horizontal(|ui| {
ui.selectable_value(&mut state.active_tab, SettingsTab::Display, "Display Settings");
});
ui.separator();
match state.active_tab {
SettingsTab::Display => {
ui.label("Window Mode");
egui::ComboBox::from_id_salt("window_mode")
.selected_text(window_mode_label(state.selected_fullscreen_mode))
.show_ui(ui, |ui| {
for mode in [
WindowMode::Windowed,
WindowMode::BorderlessFullscreen,
WindowMode::ExclusiveFullscreen,
] {
ui.selectable_value(
&mut state.selected_fullscreen_mode,
mode,
window_mode_label(mode),
);
}
});
ui.add_space(8.0);
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
if ui.button("Apply").clicked() {
if let Ok(mut settings_handle) = settings.write() {
settings_handle.display_settings.fullscreen_mode = state.selected_fullscreen_mode;
settings_handle.display_settings.dirty = true;
}
}
});
}
}
});
});
}
}
}
fn window_mode_label(mode: WindowMode) -> &'static str {
match mode {
WindowMode::Windowed => "Windowed",
WindowMode::BorderlessFullscreen => "Borderless Fullscreen",
WindowMode::ExclusiveFullscreen => "Exclusive Fullscreen",
}
}

View file

@ -1,69 +0,0 @@
use winit::keyboard::KeyCode;
use raidillon_app::prelude::*;
use crate::systems::{common::should_draw_menu, menu::MenuState};
#[derive(Default)]
pub struct KeybindsSystem {
camera_toggle_held: bool,
}
impl System for KeybindsSystem {
fn fixed_update(&mut self, res: &mut EngineResources, scene: &mut Scene) {
let input = res.get::<InputState>().unwrap();
if input.key_held(KeyCode::F5) {
if self.camera_toggle_held { return }
self.toggle_camera_mode(scene);
self.camera_toggle_held = true;
} else {
self.camera_toggle_held = false;
}
}
fn frame_update(&mut self, res: &mut EngineResources, scene: &mut Scene) {
if should_draw_menu(scene) {
let pctx = res.get_mut::<PlatformContext>().unwrap();
let mut q = scene.world.query::<(&Camera, &CameraMode)>();
let (cam_ent, (cam, cam_mode)) = q
.iter()
.next()
.unwrap();
let cam_mode_str = format!("Camera Mode: {:?}", cam_mode);
let mut q = scene.world.query::<(&MenuState)>();
let (_ent, menu_state) = q
.iter()
.next()
.unwrap();
let menu_state_str = format!("Menu State: {:?}", menu_state);
pctx.egui_queue.borrow_mut().queue(move |egui_ctx| {
egui::Window::new("Camera").show(egui_ctx, |ui| {
ui.label("F5 to switch camera");
ui.label(cam_mode_str);
ui.label(menu_state_str)
});
});
}
}
}
impl KeybindsSystem {
fn toggle_camera_mode(&mut self, scene: &mut Scene) {
let q = scene.world.query_mut::<(&mut Camera, &mut CameraMode)>();
let (cam_ent, (cam, cam_mode)) = q
.into_iter()
.next()
.unwrap();
match *cam_mode {
CameraMode::Kinematic => {
*cam_mode = CameraMode::Debug;
}
CameraMode::Debug => {
*cam_mode = CameraMode::Kinematic;
}
}
}
}

View file

@ -1,187 +0,0 @@
use glam::{Quat, Vec3};
use rapier3d::prelude::{nalgebra, ColliderBuilder, QueryFilter, RigidBodyBuilder, RigidBodyType};
use rapier3d::prelude::vector;
use rapier3d::control::{CharacterCollision, KinematicCharacterController as RapierKinematicCharacterController};
use rapier3d::na::{Isometry3, Vector3};
use winit::event::DeviceEvent::MouseMotion;
use winit::event::Event;
use winit::keyboard::KeyCode;
use raidillon_app::prelude::*;
use crate::systems::common::{camera_front, is_camera_mode_valid, is_mouse_look_enabled};
use crate::systems::menu::MenuState;
#[derive(Default)]
pub struct KinematicCharacterController {
character_controller: RapierKinematicCharacterController,
character_collider: ColliderBuilder,
desired_movement: Vec3,
last_position: Vector3<f32>,
yaw: f32,
pitch: f32,
speed: f32,
sensitivity: f32,
mouse_delta: (f64, f64),
vertical_velocity: f32,
gravity: f32,
max_fall_speed: f32,
}
impl System for KinematicCharacterController {
fn load_world(&mut self, res: &mut EngineResources, scene: &mut Scene) {
// create the rigid body, add it to the body set
let p = scene.resources.get_mut::<Physics>().expect("Physics missing");
let rb = RigidBodyBuilder::kinematic_position_based().build();
let rb_handle = p.rigid_body_set.insert(rb);
self.character_collider = ColliderBuilder::capsule_y(1.0, 1.0);
p.collider_set.insert_with_parent(self.character_collider.build(), rb_handle, &mut p.rigid_body_set);
let tr = Transform {
translation: Vec3::new(0.0, 2.0, 3.0),
rotation: Quat::IDENTITY,
scale: Vec3::new(1.0, 1.0, 1.0),
};
self.last_position = vector![
tr.translation.x,
tr.translation.y,
tr.translation.z,
];
scene.world.spawn((
tr,
CharacterBodyComponent(rb_handle),
));
self.speed = 5.0;
self.sensitivity = 0.05;
self.gravity = -9.81;
self.max_fall_speed = -50.0;
self.vertical_velocity = 0.0;
}
fn handle_event(&mut self, res: &mut EngineResources, scene: &mut Scene) {
if !is_camera_mode_valid(scene, CameraMode::Kinematic) {
return
}
let pctx = res.get::<PlatformContext>().unwrap();
let event2 = pctx.current_event.clone();
match event2 {
Event::DeviceEvent { device_id, event } => {
match event {
MouseMotion { delta } => {
self.mouse_delta.0 += delta.0;
self.mouse_delta.1 += delta.1;
},
_ => {}
}
},
_ => {},
}
}
fn frame_update(&mut self, res: &mut EngineResources, scene: &mut Scene) {
let front = camera_front(self.yaw, self.pitch);
let right_vec = front.cross(Vec3::Y).normalize();
if is_camera_mode_valid(scene, CameraMode::Kinematic) && is_mouse_look_enabled(scene) {
let (pctx, input) = res.get_many::<(PlatformContext, InputState)>().unwrap();
self.yaw += (self.mouse_delta.0 as f32) * self.sensitivity;
self.pitch -= (self.mouse_delta.1 as f32) * self.sensitivity;
self.pitch = self.pitch.clamp(-89.0, 89.0);
if input.key_held(KeyCode::KeyW) {
self.desired_movement += front * pctx.time_ctx.frame_dt * self.speed;
}
if input.key_held(KeyCode::KeyS) {
self.desired_movement -= front * pctx.time_ctx.frame_dt * self.speed;
}
if input.key_held(KeyCode::KeyA) {
self.desired_movement -= right_vec * pctx.time_ctx.frame_dt * self.speed;
}
if input.key_held(KeyCode::KeyD) {
self.desired_movement += right_vec * pctx.time_ctx.frame_dt * self.speed;
}
}
if is_camera_mode_valid(scene, CameraMode::Kinematic) {
let pos = Physics::rapier_translation_to_glam(&self.last_position);
scene.world.query_mut::<&mut Camera>().into_iter().for_each(|(_, camera)| {
// INTERPOLATION NEEDED.
camera.eye = pos;
camera.center = pos + front;
});
}
self.mouse_delta = (0.0, 0.0);
}
fn fixed_update(&mut self, res: &mut EngineResources, scene: &mut Scene) {
let p = scene.resources.get_mut::<Physics>().unwrap();
let (pctx, input) = res.get_many::<(PlatformContext, InputState)>().unwrap();
let (ch_ent, (ch_tr, ch_component)) = scene
.world
.query_mut::<(&mut Transform, &mut CharacterBodyComponent)>()
.into_iter()
.next()
.expect("no character entity in world");
let query_pipeline = p.broad_phase.as_query_pipeline(
p.narrow_phase.query_dispatcher(),
&p.rigid_body_set,
&p.collider_set,
QueryFilter::default().exclude_rigid_body(ch_component.0),
);
self.vertical_velocity = (self.vertical_velocity + self.gravity * pctx.time_ctx.fixed_dt)
.max(self.max_fall_speed);
let mut total_displacement = self.desired_movement;
total_displacement.y += self.vertical_velocity * pctx.time_ctx.fixed_dt;
let mut collisions: Vec<CharacterCollision> = Vec::new();
let corrected_movement = self.character_controller.move_shape(
pctx.time_ctx.fixed_dt,
&query_pipeline,
&*self.character_collider.shape,
&Isometry3::from(self.last_position),
vector![total_displacement.x, total_displacement.y, total_displacement.z],
|collision| collisions.push(collision),
);
// update character rigid body with the new translation.
if let Some(body) = p.get_rigid_body_mut(ch_component.0) {
self.last_position = vector![
self.last_position.x + corrected_movement.translation.x,
self.last_position.y + corrected_movement.translation.y,
self.last_position.z + corrected_movement.translation.z,
];
body.set_next_kinematic_position(Isometry3::from(self.last_position));
ch_tr.translation = Physics::rapier_translation_to_glam(&self.last_position);
// reset vertical velocity if grounded
if corrected_movement.grounded {
self.vertical_velocity = 0.0;
}
}
// apply impulses to dynamic bodies the character collided with
let character_push_force = 50.0;
for collision in collisions {
if let Some(collider) = p.collider_set.get(collision.handle) {
if let Some(rb_handle) = collider.parent() {
if let Some(rb) = p.rigid_body_set.get_mut(rb_handle) {
if rb.body_type() == RigidBodyType::Dynamic {
let push_direction = -collision.hit.normal1.into_inner();
let impulse = push_direction * character_push_force * pctx.time_ctx.fixed_dt;
rb.apply_impulse(impulse, true);
}
}
}
}
}
self.desired_movement = Vec3::ZERO;
}
}

View file

@ -1,85 +0,0 @@
use egui::Id;
use raidillon_app::prelude::*;
use winit::{dpi::{LogicalPosition, Position}, keyboard::KeyCode, window::CursorGrabMode};
#[derive(Default)]
pub struct MenuSystem {
escape_key_held: bool,
/// Unoptimal solution to fix windows event delay
times_ran_initial_win_event: u32,
}
#[derive(Default, Eq, PartialEq, Debug)]
pub enum MenuState {
Open,
#[default]
Closed,
}
impl System for MenuSystem {
fn load_world(&mut self, res: &mut EngineResources, scene: &mut Scene) {
scene.world.spawn((MenuState::Closed,));
}
fn frame_update(&mut self, res: &mut EngineResources, scene: &mut Scene) {
// Windows won't register some events in the first miliseconds after initialization
if self.times_ran_initial_win_event < 20 {
let window = res.get::<PlatformContext>().unwrap().window.lock().unwrap();
window.set_cursor_grab(CursorGrabMode::Confined).or_else(|_| window.set_cursor_grab(CursorGrabMode::Locked));
window.set_cursor_visible(false);
self.times_ran_initial_win_event += 1
}
let mut egui_queue = res.get::<PlatformContext>().unwrap().egui_queue.borrow_mut();
egui_queue.queue(|egui_ctx| {
egui::Area::new(Id::new("esc to pause"))
.anchor(egui::Align2::RIGHT_TOP, [-10.0, 10.0])
.show(egui_ctx, |ui| {
ui.label(
egui::RichText::new("ESC to pause").size(24.0).color(egui::Color32::BLACK)
);
});
});
}
fn handle_event(&mut self, res: &mut EngineResources, scene: &mut Scene) {
// The menu is toggled by pressing the escape key
let input = res.get::<InputState>().unwrap();
if input.key_held(KeyCode::Escape) {
if self.escape_key_held { return }
self.toggle_menu(res, scene);
self.escape_key_held = true;
} else {
self.escape_key_held = false;
}
}
}
impl MenuSystem {
fn toggle_menu(&mut self, res: &mut EngineResources, scene: &mut Scene) {
let q = scene.world.query_mut::<(&mut MenuState)>();
let (menu_ent, menu_state) = q
.into_iter()
.next()
.unwrap();
let pctx = res.get::<PlatformContext>().unwrap();
let window = pctx.window.lock().unwrap();
match *menu_state {
MenuState::Open => {
*menu_state = MenuState::Closed;
window.set_cursor_grab(CursorGrabMode::Confined).or_else(|_| window.set_cursor_grab(CursorGrabMode::Locked));
window.set_cursor_visible(false);
pctx.should_egui_receive_input_events.set(false);
},
MenuState::Closed => {
*menu_state = MenuState::Open;
window.set_cursor_grab(CursorGrabMode::None);
window.set_cursor_visible(true);
pctx.should_egui_receive_input_events.set(true);
},
}
}
}

View file

@ -1,15 +0,0 @@
mod physics;
mod physics_debug;
mod kinematic_character_controller;
mod keybinds;
mod menu;
pub mod debug_camera;
pub mod common;
mod display_settings;
pub use physics::PhysicsSystem;
pub use physics_debug::PhysicsDebugSystem;
pub use kinematic_character_controller::KinematicCharacterController;
pub use keybinds::KeybindsSystem;
pub use menu::MenuSystem;
pub use display_settings::DisplaySettings;

View file

@ -1,30 +0,0 @@
use raidillon_app::prelude::*;
/// Do physics calculations and apply to world.
#[derive(Default)]
pub struct PhysicsSystem;
impl System for PhysicsSystem {
fn load_world(&mut self, res: &mut EngineResources, scene: &mut Scene) {
let p = Physics::default();
scene.resources.insert(p);
}
fn fixed_update(&mut self, res: &mut EngineResources, scene: &mut Scene) {
let pctx = res.get::<PlatformContext>().expect("PlatformContext missing").clone();
let physics = scene.resources.get_mut::<Physics>().expect("Physics missing");
physics.step(pctx.time_ctx.fixed_dt);
// apply calculations to dynamic bodies
let mut query = scene.world.query::<(&mut Transform, &RigidBodyComponent)>();
for (_ent, (tr, rb_component)) in query.iter() {
if let Some(body) = physics.get_rigid_body(rb_component.0) {
let pos = body.position();
let translation = Physics::rapier_translation_to_glam(&pos.translation.vector);
let rotation = Physics::rapier_rotation_to_glam(&pos.rotation);
tr.translation = translation;
tr.rotation = rotation;
}
}
}
}

View file

@ -1,35 +0,0 @@
use raidillon_app::prelude::*;
/// renders aabb wireframes for all physics colliders
#[derive(Default)]
pub struct PhysicsDebugSystem;
impl System for PhysicsDebugSystem {
fn frame_update(&mut self, res: &mut EngineResources, scene: &mut Scene) {
let pctx = res.get::<PlatformContext>().expect("PlatformContext missing").clone();
let mut debug_wireframes = pctx.debug_wireframes.borrow_mut();
if !debug_wireframes.enabled {
return;
}
let physics = match scene.resources.get::<Physics>() {
Some(p) => p,
None => return,
};
let color = [1.0, 0.0, 0.0, 1.0];
for (_, collider) in physics.collider_set.iter() {
let aabb = collider.compute_aabb();
let min = aabb.mins;
let max = aabb.maxs;
debug_wireframes.add_box(
[min.x, min.y, min.z],
[max.x, max.y, max.z],
color,
);
}
}
}

2242
glium_platform/Cargo.lock generated

File diff suppressed because it is too large Load diff

View file

@ -1,21 +0,0 @@
[package]
name = "raidillon_glium"
version = "0.1.0"
edition = "2024"
[dependencies]
anyhow = "1.0.98"
glam = "0.30.5"
glium = { version = "0.36.0", features = ["glutin_backend", "simple_window_builder"] }
gltf = { version = "1.4.1", features = ["import", "utils", "KHR_texture_transform"] }
raidillon_platform = { path = "../platform" }
raidillon_core = { path = "../core" }
raidillon_assets = { path = "../asset" }
raidillon_ecs = { path = "../ecs" }
raidillon_engine = { path = "../engine" }
winit = "0.30.12"
indexmap = "2.10.0"
exr = "1.73.0"
image = { version = "0.25.8", default-features = false, features = ["exr"] }
egui = "0.33.2"
egui_glium = { version = "0.31.1", git = "https://github.com/reo6/egui_glium.git" }

View file

@ -1,53 +0,0 @@
use std::any::Any;
use std::cell::RefCell;
use raidillon_assets::{ModelManagerRef, ModelManager};
use crate::model::Model;
use std::path::{Path, PathBuf};
use crate::gltf_loader::load_gltf;
use glium::backend::Facade;
use std::collections::HashMap;
use std::collections::hash_map::Entry;
use std::rc::Rc;
use raidillon_assets::model_manager::ModelID;
/// Glium platform asset manager implementation.
pub struct GliumAssetManager {
pub models: HashMap<ModelID, Vec<Model>>,
facade: Box<dyn Facade>,
}
impl GliumAssetManager {
pub fn new(facade: Box<dyn Facade>) -> Self {
let models = HashMap::new();
Self {
models,
facade,
}
}
}
impl ModelManager for GliumAssetManager {
fn load_gltf(&mut self, id: ModelID, path: &Path) {
let models = load_gltf(path, self.facade.as_ref()).unwrap();
self.models.insert(id, models);
}
fn unload_model(&mut self, id: ModelID) {
self.models.remove(&id);
}
// fn get_model(&mut self, path: &Path) -> &Self::Model {
// let path_buf = path.to_path_buf();
// match self.models.entry(path_buf) {
// Entry::Occupied(entry) => entry.into_mut(),
// Entry::Vacant(entry) => {
// let model = load_gltf(path, self.facade.as_ref()).unwrap();
// entry.insert(model)
// }
// }
// }
fn get_model(&self, id: &ModelID) -> Option<&dyn Any> {
self.models.get(id).map(|models| models as &dyn Any)
}
}

View file

@ -1,183 +0,0 @@
use anyhow::{bail, Context, Result};
use glium::{backend::Facade, IndexBuffer, VertexBuffer};
use glium::index::PrimitiveType;
use std::{fmt::Debug, path::Path};
use crate::model::{Vertex, Mesh, Material, Model};
use glium::texture::{RawImage2d, Texture2d, SrgbTexture2d};
use glium::uniforms::{SamplerWrapFunction, MinifySamplerFilter, MagnifySamplerFilter};
use gltf::image::Format as GltfFormat;
use glam::Vec2;
/// Load a glTF 2.0 file from disk and upload all primitives to the GPU.
///
/// Returns one [`Model`] per glTF primitive (across all meshes).
pub fn load_gltf<P>(path: P, facade: &dyn Facade) -> Result<Vec<Model>>
where
P: AsRef<Path> + Debug,
{
// -- parse the asset & bring buffer blobs into memory --
let (doc, buffers, images) = gltf::import(path.as_ref()).context("failed to import glTF file")?;
// Helper to update sampler settings from glTF sampler
fn update_sampler(mat: &mut Material, t: &gltf::texture::Texture<'_>) {
let sampler_info = t.sampler();
mat.sampler.wrap_function.0 = match sampler_info.wrap_s() {
gltf::texture::WrappingMode::ClampToEdge => SamplerWrapFunction::Clamp,
gltf::texture::WrappingMode::MirroredRepeat => SamplerWrapFunction::Mirror,
gltf::texture::WrappingMode::Repeat => SamplerWrapFunction::Repeat,
};
mat.sampler.wrap_function.1 = match sampler_info.wrap_t() {
gltf::texture::WrappingMode::ClampToEdge => SamplerWrapFunction::Clamp,
gltf::texture::WrappingMode::MirroredRepeat => SamplerWrapFunction::Mirror,
gltf::texture::WrappingMode::Repeat => SamplerWrapFunction::Repeat,
};
if let Some(f) = sampler_info.mag_filter() {
mat.sampler.magnify_filter = match f {
gltf::texture::MagFilter::Nearest => MagnifySamplerFilter::Nearest,
gltf::texture::MagFilter::Linear => MagnifySamplerFilter::Linear,
};
}
if let Some(f) = sampler_info.min_filter() {
mat.sampler.minify_filter = match f {
gltf::texture::MinFilter::Nearest => MinifySamplerFilter::Nearest,
gltf::texture::MinFilter::Linear => MinifySamplerFilter::Linear,
gltf::texture::MinFilter::NearestMipmapNearest => MinifySamplerFilter::NearestMipmapNearest,
gltf::texture::MinFilter::NearestMipmapLinear => MinifySamplerFilter::NearestMipmapLinear,
gltf::texture::MinFilter::LinearMipmapNearest => MinifySamplerFilter::LinearMipmapNearest,
gltf::texture::MinFilter::LinearMipmapLinear => MinifySamplerFilter::LinearMipmapLinear,
};
}
}
let mut out: Vec<Model> = Vec::new();
for mesh in doc.meshes() {
for primitive in mesh.primitives() {
// ---------- MATERIAL ----------
let mut mat = Material::default();
let material = primitive.material();
let pbr = material.pbr_metallic_roughness();
// Factors --------------------------------------------------
mat.base_color_factor = pbr.base_color_factor();
mat.metal_factor = pbr.metallic_factor();
mat.roughness_factor = pbr.roughness_factor();
mat.emissive_factor = material.emissive_factor();
// Base-color texture (sRGB)
if let Some(info) = pbr.base_color_texture() {
update_sampler(&mut mat, &info.texture());
let view = info.texture().source().index();
mat.base_color = Some(glium_srgb_texture(facade, &images[view])?);
}
// Metallic-Roughness (linear)
if let Some(info) = pbr.metallic_roughness_texture() {
update_sampler(&mut mat, &info.texture());
let view = info.texture().source().index();
mat.metallic_roughness = Some(glium_linear_texture(facade, &images[view])?);
}
// Normal map (linear)
if let Some(info) = material.normal_texture() {
update_sampler(&mut mat, &info.texture());
let view = info.texture().source().index();
mat.normal = Some(glium_linear_texture(facade, &images[view])?);
}
// Occlusion (linear)
if let Some(info) = material.occlusion_texture() {
update_sampler(&mut mat, &info.texture());
let view = info.texture().source().index();
mat.occlusion = Some(glium_linear_texture(facade, &images[view])?);
}
// Emissive (sRGB)
if let Some(info) = material.emissive_texture() {
update_sampler(&mut mat, &info.texture());
let view = info.texture().source().index();
mat.emissive = Some(glium_srgb_texture(facade, &images[view])?);
}
// KHR_texture_transform (base color only, for now)
if let Some(tex) = pbr.base_color_texture() {
if let Some(xform) = tex.texture_transform() {
mat.uv_offset = Vec2::new(xform.offset()[0], xform.offset()[1]);
mat.uv_scale = Vec2::new(xform.scale()[0], xform.scale()[1]);
}
}
// ---- Vertex/index data ----
let reader = primitive.reader(|buf| Some(&buffers[buf.index()].0));
let positions: Vec<[f32; 3]> = reader.read_positions().context("missing POSITION")?.collect();
let normals: Vec<[f32; 3]> = reader.read_normals().context("missing NORMAL")?.collect();
let tex_coords: Vec<[f32; 2]> = reader
.read_tex_coords(0)
.map(|tc| tc.into_f32().collect())
.unwrap_or_else(|| vec![[0.0, 0.0]; positions.len()]);
let indices: Vec<u32> = reader.read_indices().context("missing indices")?.into_u32().collect();
// Interleave
let vertices: Vec<Vertex> = (0..positions.len())
.map(|i| Vertex { position: positions[i], normal: normals[i], tex_coords: tex_coords[i] })
.collect();
let vbuf = VertexBuffer::immutable(facade, &vertices)?;
let ibuf = IndexBuffer::immutable(facade, PrimitiveType::TrianglesList, &indices)?;
out.push(Model { mesh: Mesh { vbuf, ibuf }, material: mat });
}
}
if out.is_empty() {
bail!("glTF has no mesh primitives");
}
Ok(out)
}
/// Linear-space texture (RGBA8) from glTF image data.
fn glium_linear_texture(facade: &dyn Facade, img: &gltf::image::Data) -> Result<Texture2d>
{
let rgba = to_rgba(img);
let raw = RawImage2d::from_raw_rgba(rgba, (img.width, img.height));
Ok(Texture2d::new(facade, raw)?)
}
/// sRGB texture from glTF image data.
fn glium_srgb_texture(facade: &dyn Facade, img: &gltf::image::Data) -> Result<SrgbTexture2d>
{
let rgba = to_rgba(img);
let raw = RawImage2d::from_raw_rgba(rgba, (img.width, img.height));
Ok(SrgbTexture2d::new(facade, raw)?)
}
/// Convert various glTF image formats to RGBA8 as expected by glium.
fn to_rgba(img: &gltf::image::Data) -> Vec<u8> {
match img.format {
GltfFormat::R8G8B8A8 => img.pixels.clone(),
GltfFormat::R8G8B8 => {
// Expand RGB to RGBA with alpha=255
img.pixels
.chunks(3)
.flat_map(|rgb| [rgb[0], rgb[1], rgb[2], 255u8])
.collect()
}
GltfFormat::R8G8 => {
// Treat RG as luminance+alpha? For simplicity, replicate first channel into RGB, second as alpha.
img.pixels
.chunks(2)
.flat_map(|rg| [rg[0], rg[0], rg[0], rg[1]])
.collect()
}
GltfFormat::R8 => {
// Grayscale: replicate into RGB, alpha=255
img.pixels
.iter()
.flat_map(|l| [*l, *l, *l, 255u8])
.collect()
}
_ => img.pixels.clone(),
}
}

View file

@ -1,10 +0,0 @@
pub mod platform;
pub mod assets;
pub mod model;
pub mod gltf_loader;
pub mod system;
mod render;
pub use assets::GliumAssetManager;
pub use platform::GliumPlatform;
pub use system::RenderingSystem;

View file

@ -1,201 +0,0 @@
use std::cell::{RefCell, Cell};
use std::rc::Rc;
use std::sync::{Arc, Mutex, RwLock};
use raidillon_platform::{Platform, PlatformContext, TimeContext, DebugWireframes, DebugWireframesRef};
use glium::backend::glutin::Display;
use glium::backend::glutin::SimpleWindowBuilder;
use glium::glutin::surface::WindowSurface;
use glium::winit::event_loop::EventLoop;
use glium::winit::window::Window;
use glium::Surface;
use crate::system::{RenderingContext, RenderingSystemManager};
use winit::event::{DeviceEvent, Event, WindowEvent};
use raidillon_assets::ModelManagerRef;
use raidillon_core::engine::EngineTrait;
use raidillon_core::time;
use raidillon_core::time::Time;
use crate::render::{BasicMeshRenderingSystem, DebugWireframeRenderingSystem, EguiRenderer, SkyboxRenderingSystem};
use crate::GliumAssetManager;
use glam::Vec3;
use winit::event::DeviceEvent::MouseMotion;
use raidillon_core::EguiQueue;
use raidillon_platform::settings::{Settings, default_config_path};
pub struct GliumPlatform<E: EngineTrait<PlatformCtx = PlatformContext>> {
event_loop: EventLoop<()>,
window: Arc<Mutex<Window>>,
display: Display<WindowSurface>,
rendering_system_manager: RenderingSystemManager,
asset_manager: ModelManagerRef,
engine: E,
time: time::Time,
egui_queue: Rc<RefCell<EguiQueue>>,
settings: Arc<RwLock<Settings>>,
debug_wireframes: DebugWireframesRef,
should_egui_receive_input_events: Rc<Cell<bool>>,
}
impl<E: EngineTrait<PlatformCtx = PlatformContext>> Platform<E> for GliumPlatform<E> {
fn initialize(mut engine: E, title: String, width: u32, height: u32) -> Self {
let event_loop = glium::winit::event_loop::EventLoop::builder()
.build()
.expect("create event-loop");
let (window, display) = SimpleWindowBuilder::new()
.with_title(title.as_str())
.with_inner_size(width, height)
.build(&event_loop);
let asset_manager: ModelManagerRef = Rc::new(RefCell::new(Box::new(GliumAssetManager::new(Box::new(display.clone())))));
let mut rendering_system_manager = RenderingSystemManager::new();
let time_cfg = time::Config::default();
let time = time::Time::new(time_cfg);
let window = Arc::new(Mutex::new(window));
// Install rendering systems in order
rendering_system_manager.add::<SkyboxRenderingSystem>(&display, window.clone(), &event_loop);
rendering_system_manager.add::<BasicMeshRenderingSystem>(&display, window.clone(), &event_loop);
rendering_system_manager.add::<DebugWireframeRenderingSystem>(&display, window.clone(), &event_loop);
rendering_system_manager.add::<EguiRenderer>(&display, window.clone(), &event_loop);
let egui_queue = Rc::new(RefCell::new(EguiQueue::new()));
let settings = Arc::new(
RwLock::new(
Settings::load_or_default(default_config_path()).unwrap()
)
);
let debug_wireframes = Rc::new(RefCell::new(DebugWireframes::new()));
let should_egui_receive_input_events = Rc::new(Cell::new(false));
Self {
event_loop,
window,
display,
rendering_system_manager,
asset_manager,
engine,
time,
egui_queue,
settings,
debug_wireframes,
should_egui_receive_input_events,
}
}
fn run(mut self) {
let (w, h): (u32, u32) = match self.window.lock() {
Ok(window) => window.inner_size().into(),
Err(_) => (0, 0), // fallback values
};
let ctx = PlatformContext {
current_event: Event::AboutToWait,
asset_manager: self.asset_manager.clone(),
frame_width: w as f32,
frame_height: h as f32,
time_ctx: self.construct_time_ctx(),
window: self.window.clone(),
egui_queue: self.egui_queue.clone(),
settings: self.settings.clone(),
debug_wireframes: self.debug_wireframes.clone(),
should_egui_receive_input_events: self.should_egui_receive_input_events.clone(),
};
self.engine.initialize(ctx.clone());
self.settings.read().unwrap().display_settings.apply(&*self.window.lock().unwrap());
let _ = &self.event_loop.run(move |event, el| {
let settings_handle = self.settings.read().unwrap();
if settings_handle.display_settings.dirty {
settings_handle.display_settings.apply(&*self.window.lock().unwrap());
}
drop(settings_handle);
self.rendering_system_manager
.systems
.values_mut()
.for_each(|system| system.handle_event(self.window.clone(), event.clone()));
let mut ctx2 = ctx.clone();
ctx2.current_event = event.clone();
self.engine.handle_event(ctx2);
match event {
Event::WindowEvent { event, .. } => match event {
WindowEvent::Resized(size) => {
if size.width > 0 && size.height > 0 {
self.display.resize((size.width, size.height));
}
},
WindowEvent::CloseRequested => {
// TODO: Run uninitialize on renderer and engine
self.settings.read().unwrap().save_to_file(default_config_path());
el.exit();
},
WindowEvent::RedrawRequested => {
let mut target = self.display.draw();
target.clear_color_and_depth((0.1, 0.1, 0.15, 1.0), 1.0);
let scene = self.engine.current_scene();
let mut context = RenderingContext {
scene,
target: &mut target,
display: &self.display,
asset_manager: self.asset_manager.clone(),
window: self.window.clone(),
egui_queue: self.egui_queue.clone(),
debug_wireframes: self.debug_wireframes.clone(),
env_light_dir: Vec3::new(0.0, -1.0, 0.0),
should_egui_receive_input_events: self.should_egui_receive_input_events.clone(),
};
self.rendering_system_manager
.systems
.values_mut()
.for_each(|system| system.render(&mut context));
// clear debug wireframes after rendering
self.debug_wireframes.borrow_mut().clear();
target.finish().unwrap();
}
_ => {},
},
Event::AboutToWait => {
let plan = self.time.begin_frame_blocking();
let mut ctx2 = ctx.clone();
ctx2.time_ctx = TimeContext {
frame_dt: self.time.frame_dt_seconds(),
fixed_dt: self.time.fixed_dt_seconds(),
alpha: self.time.alpha(),
};
ctx2.current_event = Event::AboutToWait;
for _ in 0..plan.updates {
self.engine.fixed_update(ctx2.clone());
}
self.engine.frame_update(ctx2.clone());
self.rendering_system_manager
.systems
.values_mut()
.for_each(|system| system.prepare_frame(self.window.clone()));
self.window.lock().unwrap().request_redraw();
}
_ => {},
}
});
}
}
impl<E: EngineTrait<PlatformCtx = PlatformContext>> GliumPlatform<E> {
fn construct_time_ctx(&self) -> TimeContext {
TimeContext {
frame_dt: self.time.frame_dt_seconds(),
fixed_dt: self.time.fixed_dt_seconds(),
alpha: self.time.alpha(),
}
}
}

View file

@ -1,115 +0,0 @@
use std::any::Any;
use std::sync::{Arc, Mutex};
use glium::{uniform, Display, Program, Surface};
use glium::glutin::surface::WindowSurface;
use glium::texture::{RawImage2d, SrgbTexture2d};
use crate::{GliumAssetManager, RenderingSystem};
use crate::system::RenderingContext;
use raidillon_assets::include_shader;
pub use raidillon_platform::Camera;
use glam::Vec3;
use glium::uniforms::{MagnifySamplerFilter, MinifySamplerFilter, SamplerWrapFunction};
use winit::event::Event;
use winit::event_loop::EventLoop;
use raidillon_ecs::{Transform, ModelID};
use raidillon_ecs::components::ModelHandle;
use crate::model::Model;
/// A basic renderer pipeline step.
pub struct BasicMeshRenderingSystem {
program: Program,
white_tex: SrgbTexture2d,
params: glium::DrawParameters<'static>,
}
impl RenderingSystem for BasicMeshRenderingSystem {
fn initialize(display: &Display<WindowSurface>, _window: Arc<Mutex<glium::winit::window::Window>>, event_loop: &EventLoop<()>) -> Self {
const VERT_SRC: &str = include_shader!("gl_textured.vert");
const FRAG_SRC: &str = include_shader!("gl_textured.frag");
let program = Program::from_source(display, VERT_SRC, FRAG_SRC, None).unwrap();
let white_tex = {
let data = vec![255u8, 255u8, 255u8, 255u8];
let raw = RawImage2d::from_raw_rgba(data, (1, 1));
SrgbTexture2d::new(display, raw).unwrap()
};
let params = glium::DrawParameters {
depth: glium::Depth {
test: glium::draw_parameters::DepthTest::IfLess,
write: true,
.. Default::default()
},
.. Default::default()
};
Self {
program, white_tex, params
}
}
fn render(&mut self, ctx: &mut RenderingContext) {
let cam = match ctx.scene.world.query::<&Camera>().iter().next() {
Some((_, cam)) => *cam,
None => {
eprintln!("[renderer] No camera component found. Skipping frame");
return;
}
};
// Use HDR-derived environment light direction if provided, otherwise default to downward
let light_dir_world: Vec3 = if ctx.env_light_dir.length_squared() > 0.0 { ctx.env_light_dir.normalize() } else { Vec3::new(0.0, -1.0, 0.0) };
// Transform light direction to view space (normals/positions are in view space)
let view_mat3 = glam::Mat3::from_mat4(cam.view());
let light_dir_view = (view_mat3 * light_dir_world).normalize();
let asset_manager = ctx.asset_manager.borrow();
for (_, (tr, mh)) in ctx.scene.world.query::<(&Transform, &ModelHandle)>().iter() {
let model = match asset_manager.get_model(&mh.0) {
Some(model) => model,
_ => continue,
};
let models = match model.downcast_ref::<Vec<Model>>() {
Some(models) => models,
None => continue,
};
for model in models {
let mesh = &model.mesh;
let mat = &model.material;
let tex_ref: &SrgbTexture2d = mat.base_color.as_ref().unwrap_or(&self.white_tex);
let mut sampler = tex_ref.sampled();
sampler = sampler.wrap_function(SamplerWrapFunction::Repeat);
sampler = sampler.minify_filter(MinifySamplerFilter::Linear);
sampler = sampler.magnify_filter(MagnifySamplerFilter::Linear);
let c = mat.base_color_factor;
let uniforms = uniform! {
model: tr.matrix().to_cols_array_2d(),
view: cam.view().to_cols_array_2d(),
projection: cam.projection().to_cols_array_2d(),
u_light: [light_dir_view.x, light_dir_view.y, light_dir_view.z],
tex: sampler,
color: [c[0], c[1], c[2]],
uv_offset: [mat.uv_offset.x, mat.uv_offset.y],
uv_scale: [mat.uv_scale.x, mat.uv_scale.y],
};
ctx.target.draw(
&mesh.vbuf,
&mesh.ibuf,
&self.program,
&uniforms,
&self.params,
).unwrap();
}
}
}
}

View file

@ -1,80 +0,0 @@
use std::sync::{Arc, Mutex};
use glium::{Display, Program, Surface, VertexBuffer, implement_vertex};
use glium::glutin::surface::WindowSurface;
use glium::index::PrimitiveType;
use glium::uniform;
use winit::event_loop::EventLoop;
use raidillon_assets::include_shader;
use crate::system::RenderingContext;
use crate::RenderingSystem;
pub use raidillon_platform::Camera;
#[derive(Copy, Clone)]
struct DebugVertex {
position: [f32; 3],
color: [f32; 4],
}
implement_vertex!(DebugVertex, position, color);
/// renders debug wireframes from the shared buffer
pub struct DebugWireframeRenderingSystem {
program: Program,
params: glium::DrawParameters<'static>,
}
impl RenderingSystem for DebugWireframeRenderingSystem {
fn initialize(display: &Display<WindowSurface>, _window: Arc<Mutex<glium::winit::window::Window>>, _event_loop: &EventLoop<()>) -> Self {
const VERT_SRC: &str = include_shader!("debug_wireframe.vert");
const FRAG_SRC: &str = include_shader!("debug_wireframe.frag");
let program = Program::from_source(display, VERT_SRC, FRAG_SRC, None).unwrap();
let params = glium::DrawParameters {
depth: glium::Depth {
test: glium::draw_parameters::DepthTest::IfLess,
write: false,
..Default::default()
},
line_width: Some(1.0),
..Default::default()
};
Self { program, params }
}
fn render(&mut self, ctx: &mut RenderingContext) {
let debug_wireframes = ctx.debug_wireframes.borrow();
if !debug_wireframes.enabled || debug_wireframes.vertices.is_empty() {
return;
}
let cam = match ctx.scene.world.query::<&Camera>().iter().next() {
Some((_, cam)) => *cam,
None => return,
};
let vertices: Vec<DebugVertex> = debug_wireframes.vertices.iter()
.map(|v| DebugVertex { position: v.position, color: v.color })
.collect();
let vbuf = match VertexBuffer::new(ctx.display, &vertices) {
Ok(vb) => vb,
Err(_) => return,
};
let uniforms = uniform! {
view: cam.view().to_cols_array_2d(),
projection: cam.projection().to_cols_array_2d(),
};
ctx.target.draw(
&vbuf,
glium::index::NoIndices(PrimitiveType::LinesList),
&self.program,
&uniforms,
&self.params,
).ok();
}
}

View file

@ -1,74 +0,0 @@
use std::sync::{Arc, Mutex};
use egui::ViewportId;
use glium::{Display, Frame};
use glium::glutin::surface::WindowSurface;
use winit::window::Window;
use crate::RenderingSystem;
use crate::system::RenderingContext;
use egui_glium::EguiGlium;
use winit::event::{Event, WindowEvent};
use winit::event_loop::EventLoop;
use std::cell::Cell;
use std::rc::Rc;
pub struct EguiRenderer {
egui_glium: EguiGlium,
should_egui_receive_input_events: Option<Rc<Cell<bool>>>,
}
impl RenderingSystem for EguiRenderer {
fn initialize(display: &Display<WindowSurface>, window: Arc<Mutex<Window>>, event_loop: &EventLoop<()>) -> Self
where
Self: Sized,
{
let window = window.lock().unwrap();
let egui_glium = EguiGlium::new(ViewportId::ROOT, &display, &window, &event_loop);
Self { egui_glium: egui_glium, should_egui_receive_input_events: None }
}
fn render(&mut self, ctx: &mut RenderingContext) {
if self.should_egui_receive_input_events.is_none() {
self.should_egui_receive_input_events = Some(ctx.should_egui_receive_input_events.clone());
}
let window = ctx.window.lock().unwrap();
self.egui_glium.run(&window, |egui_ctx| {
ctx.egui_queue.borrow_mut().run(egui_ctx);
});
self.egui_glium.paint(ctx.display, ctx.target);
}
fn handle_event(&mut self, window: Arc<Mutex<Window>>, event: Event<()>) {
let window = window.lock().unwrap();
match event {
Event::WindowEvent { event, .. } => {
let should_egui_receive_input_events = match self.should_egui_receive_input_events.as_ref() {
Some(v) => v.get(),
None => true,
};
let should_send_event = if should_egui_receive_input_events {
true
} else {
!matches!(event,
WindowEvent::KeyboardInput { .. } |
WindowEvent::ModifiersChanged(_) |
WindowEvent::CursorMoved { .. } |
WindowEvent::MouseInput { .. } |
WindowEvent::MouseWheel { .. } |
WindowEvent::Touch(_) |
WindowEvent::Ime(_)
)
};
if should_send_event {
let _ = self.egui_glium.on_event(&window, &event);
}
}
_ => {},
}
}
}

View file

@ -1,9 +0,0 @@
mod basic;
mod skybox;
mod egui;
mod debug_wireframe;
pub use basic::BasicMeshRenderingSystem;
pub use skybox::SkyboxRenderingSystem;
pub use egui::EguiRenderer;
pub use debug_wireframe::DebugWireframeRenderingSystem;

View file

@ -1,157 +0,0 @@
use std::path::PathBuf;
use std::rc::Rc;
use std::cell::RefCell;
use std::sync::{Arc, Mutex};
use glium::{Display, Program, Surface, VertexBuffer, IndexBuffer, implement_vertex};
use glium::glutin::surface::WindowSurface;
use glium::index::PrimitiveType;
use glium::texture::{RawImage2d, SrgbTexture2d, Texture2d};
use glium::uniform;
use glium::uniforms::{MagnifySamplerFilter, MinifySamplerFilter, SamplerWrapFunction};
use glam::{Mat4, Vec2, Vec3};
use winit::event_loop::EventLoop;
use raidillon_assets::include_shader;
use crate::system::RenderingContext;
use crate::RenderingSystem;
#[derive(Copy, Clone)]
struct SkyboxVertex { position: [f32; 3] }
implement_vertex!(SkyboxVertex, position);
pub struct SkyboxRenderingSystem {
program: Program,
quad_vb: VertexBuffer<SkyboxVertex>,
quad_ib: IndexBuffer<u16>,
/// Equirectangular HDR image, tonemapped to sRGB for skybox view
equirect_srgb: SrgbTexture2d,
/// Dominant light direction estimated from HDRI
light_dir: Vec3,
}
impl SkyboxRenderingSystem {
fn build_cube(display: &Display<WindowSurface>) -> (VertexBuffer<SkyboxVertex>, IndexBuffer<u16>) {
// Unit cube centered at origin
let p = &[
[-1.0, -1.0, -1.0], [ 1.0, -1.0, -1.0], [ 1.0, 1.0, -1.0], [-1.0, 1.0, -1.0], // back
[-1.0, -1.0, 1.0], [ 1.0, -1.0, 1.0], [ 1.0, 1.0, 1.0], [-1.0, 1.0, 1.0], // front
];
let verts = vec![
SkyboxVertex { position: p[0] }, SkyboxVertex { position: p[1] }, SkyboxVertex { position: p[2] }, SkyboxVertex { position: p[3] }, // back
SkyboxVertex { position: p[4] }, SkyboxVertex { position: p[5] }, SkyboxVertex { position: p[6] }, SkyboxVertex { position: p[7] }, // front
];
let idx: [u16; 36] = [
// back face
0,1,2, 2,3,0,
// front face
4,6,5, 6,4,7,
// left face
0,3,7, 7,4,0,
// right face
1,5,6, 6,2,1,
// bottom face
0,4,5, 5,1,0,
// top face
3,2,6, 6,7,3,
];
(
VertexBuffer::new(display, &verts).unwrap(),
IndexBuffer::new(display, PrimitiveType::TrianglesList, &idx).unwrap(),
)
}
fn load_hdr_equirect_and_analyze(display: &Display<WindowSurface>, path: &std::path::Path) -> (SrgbTexture2d, Vec3) {
// Use image crate to decode EXR as f32 RGB
let dyn_img = image::ImageReader::open(path).expect("open exr").with_guessed_format().expect("guess format").decode().expect("decode exr");
let hdr = dyn_img.to_rgb32f();
let (width, height) = hdr.dimensions();
let width = width as usize; let height = height as usize;
let mut dir_accum = Vec3::ZERO;
let mut weight_sum = 0.0f32;
for y in 0..height {
let v = (y as f32 + 0.5) / height as f32;
let theta = (v - 0.5) * std::f32::consts::PI;
let lat_weight = theta.cos().max(0.0);
for x in 0..width {
let u = (x as f32 + 0.5) / width as f32;
let phi = (u - 0.5) * 2.0 * std::f32::consts::PI;
let px = hdr.get_pixel(x as u32, y as u32).0;
let rgb = Vec3::new(px[0], px[1], px[2]);
let lum = 0.2126*rgb.x + 0.7152*rgb.y + 0.0722*rgb.z;
if lum > 0.0 {
let dir = Vec3::new(phi.cos()*theta.cos(), theta.sin(), phi.sin()*theta.cos());
let w = lum * lat_weight;
dir_accum += dir * w;
weight_sum += w;
}
}
}
let mut light_dir = if weight_sum > 0.0 { dir_accum / weight_sum } else { Vec3::new(0.0, -1.0, 0.0) };
if light_dir.length_squared() < 1e-6 { light_dir = Vec3::new(0.0,-1.0,0.0); }
light_dir = light_dir.normalize();
// Tonemap to sRGB
let mut srgb_bytes = Vec::with_capacity(width*height*4);
for y in 0..height {
for x in 0..width {
let px = hdr.get_pixel(x as u32, y as u32).0;
let mapped = Vec3::new(px[0], px[1], px[2]) / (Vec3::new(px[0], px[1], px[2]) + Vec3::ONE);
let srgb = mapped.powf(1.0/2.2);
srgb_bytes.extend_from_slice(&[
(srgb.x.clamp(0.0,1.0)*255.0) as u8,
(srgb.y.clamp(0.0,1.0)*255.0) as u8,
(srgb.z.clamp(0.0,1.0)*255.0) as u8,
255u8,
]);
}
}
let raw = RawImage2d::from_raw_rgba(srgb_bytes, (width as u32, height as u32));
let tex = SrgbTexture2d::new(display, raw).unwrap();
(tex, light_dir)
}
}
impl RenderingSystem for SkyboxRenderingSystem {
fn initialize(display: &Display<WindowSurface>, _window: Arc<Mutex<glium::winit::window::Window>>, event_loop: &EventLoop<()>) -> Self {
const VERT_SRC: &str = include_shader!("skybox.vert");
const FRAG_SRC: &str = include_shader!("skybox.frag");
let program = Program::from_source(display, VERT_SRC, FRAG_SRC, None).unwrap();
let (quad_vb, quad_ib) = Self::build_cube(display);
// Load EXR from assets/exr
let manifest_dir = env!("CARGO_MANIFEST_DIR");
let path = std::path::Path::new(manifest_dir).join("../assets/exr/citrus_orchard_road_puresky_4k.exr");
let (equirect_srgb, light_dir) = Self::load_hdr_equirect_and_analyze(display, &path);
Self { program, quad_vb, quad_ib, equirect_srgb, light_dir }
}
fn render(&mut self, ctx: &mut RenderingContext) {
// Provide view and projection without translation for skybox
let cam = match ctx.scene.world.query::<&raidillon_platform::Camera>().iter().next() {
Some((_, cam)) => *cam,
None => return,
};
let mut view = cam.view();
// remove translation from view matrix (only orientation)
view.col_mut(3).x = 0.0; view.col_mut(3).y = 0.0; view.col_mut(3).z = 0.0;
let mut sampler = self.equirect_srgb.sampled();
sampler = sampler.wrap_function(SamplerWrapFunction::Repeat);
sampler = sampler.minify_filter(MinifySamplerFilter::Linear);
sampler = sampler.magnify_filter(MagnifySamplerFilter::Linear);
let uniforms = uniform! {
view: view.to_cols_array_2d(),
projection: cam.projection().to_cols_array_2d(),
equirect: sampler,
};
let params = glium::DrawParameters { depth: glium::Depth { test: glium::draw_parameters::DepthTest::IfLessOrEqual, write: false, ..Default::default() }, ..Default::default() };
ctx.target.draw(&self.quad_vb, &self.quad_ib, &self.program, &uniforms, &params).ok();
// Share light direction with following passes
ctx.env_light_dir = self.light_dir;
}
}
// Provide a getter for light direction for other systems
impl SkyboxRenderingSystem {
pub fn light_direction(&self) -> Vec3 { self.light_dir }
}

View file

@ -1,68 +0,0 @@
use std::any::TypeId;
use std::cell::RefCell;
use std::rc::Rc;
use std::sync::{Arc, Mutex};
use indexmap::IndexMap;
use glium::{Display, Frame};
use glium::glutin::surface::WindowSurface;
use raidillon_assets::ModelManagerRef;
use raidillon_core::{define_typemap, EguiQueue};
use raidillon_core::scene::Scene;
use raidillon_platform::DebugWireframesRef;
use glam::Vec3;
use winit::event_loop::EventLoop;
use std::cell::Cell;
pub struct RenderingContext<'a> {
pub scene: &'a Scene,
pub target: &'a mut Frame,
pub window: Arc<Mutex<glium::winit::window::Window>>,
pub display: &'a Display<WindowSurface>,
pub asset_manager: ModelManagerRef,
pub egui_queue: Rc<RefCell<EguiQueue>>,
pub debug_wireframes: DebugWireframesRef,
pub env_light_dir: Vec3,
pub should_egui_receive_input_events: Rc<Cell<bool>>
}
/// The internal "rendering system" trait of glium_platform.
/// This is unrelated to the main System trait in core.
pub trait RenderingSystem {
fn handle_event(
&mut self,
_window: Arc<Mutex<glium::winit::window::Window>>,
_event: winit::event::Event<()>,
) {
}
fn prepare_frame(&mut self, _window: Arc<Mutex<glium::winit::window::Window>>) {}
fn render(&mut self, ctx: &mut RenderingContext);
fn initialize(display: &Display<WindowSurface>, window: Arc<Mutex<glium::winit::window::Window>>, event_loop: &EventLoop<()>) -> Self
where
Self: Sized;
}
// define_typemap!(RenderingSystemManager, RenderingSystem);
pub struct RenderingSystemManager {
pub systems: IndexMap<TypeId, Box<dyn RenderingSystem>>,
}
impl RenderingSystemManager {
pub fn new() -> Self {
Self {
systems: IndexMap::default(),
}
}
pub fn add<R>(&mut self, display: &Display<WindowSurface>, window: Arc<Mutex<glium::winit::window::Window>>, event_loop: &EventLoop<()>)
where
R: RenderingSystem + 'static,
{
let system = R::initialize(display, window, event_loop);
self.systems.insert(TypeId::of::<R>(), Box::new(system));
}
pub fn remove<R: 'static>(&mut self) {
self.systems.shift_remove(&TypeId::of::<R>());
}
}

8
justfile Normal file
View file

@ -0,0 +1,8 @@
default:
@just --list
run *ARGS:
cargo run {{ARGS}}
watch:
bacon

View file

@ -1,9 +0,0 @@
[package]
name = "raidillon_physics"
version = "0.1.0"
edition = "2024"
[dependencies]
rapier3d = "0.30.1"
raidillon_ecs = { path = "../ecs" }
glam = "0.30.8"

View file

@ -1,3 +0,0 @@
mod physics;
pub use crate::physics::Physics;

View file

@ -1,82 +0,0 @@
use glam::{Quat, Vec3};
use rapier3d::na::{Quaternion, UnitQuaternion};
use rapier3d::prelude::*;
use raidillon_ecs::Transform;
/// Tiny wrapper around rapier3d.
pub struct Physics {
pub rigid_body_set: RigidBodySet,
pub collider_set: ColliderSet,
physics_pipeline: PhysicsPipeline,
island_manager: IslandManager,
pub broad_phase: DefaultBroadPhase,
pub narrow_phase: NarrowPhase,
impulse_joint_set: ImpulseJointSet,
multibody_joint_set: MultibodyJointSet,
ccd_solver: CCDSolver,
gravity: Vector<f32>,
integration_parameters: IntegrationParameters,
}
impl Default for Physics {
fn default() -> Self {
Self {
gravity: vector![0.0, -9.81, 0.0],
rigid_body_set: Default::default(),
collider_set: Default::default(),
physics_pipeline: Default::default(),
island_manager: Default::default(),
broad_phase: Default::default(),
narrow_phase: Default::default(),
impulse_joint_set: Default::default(),
multibody_joint_set: Default::default(),
ccd_solver: Default::default(),
integration_parameters: Default::default(),
}
}
}
impl Physics {
pub fn step(&mut self, dt: f32) {
self.integration_parameters.dt = dt;
self.physics_pipeline.step(
&self.gravity,
&self.integration_parameters,
&mut self.island_manager,
&mut self.broad_phase,
&mut self.narrow_phase,
&mut self.rigid_body_set,
&mut self.collider_set,
&mut self.impulse_joint_set,
&mut self.multibody_joint_set,
&mut self.ccd_solver,
&(),
&(),
);
}
pub fn add_rigid_body(&mut self, kind: RigidBodyType, transform: Transform, collider: Collider) -> RigidBodyHandle {
let rb = RigidBodyBuilder::new(kind)
.translation(vector![transform.translation.x, transform.translation.y, transform.translation.z])
.build();
let rb_handle = self.rigid_body_set.insert(rb);
self.collider_set.insert_with_parent(collider, rb_handle, &mut self.rigid_body_set);
rb_handle
}
pub fn get_rigid_body(&self, handle: RigidBodyHandle) -> Option<&RigidBody> {
self.rigid_body_set.get(handle)
}
pub fn get_rigid_body_mut(&mut self, handle: RigidBodyHandle) -> Option<&mut RigidBody> {
self.rigid_body_set.get_mut(handle)
}
pub fn rapier_translation_to_glam(v: &Vector<f32>) -> Vec3 {
Vec3::new(v.x, v.y, v.z)
}
pub fn rapier_rotation_to_glam(r: &UnitQuaternion<f32>) -> Quat {
Quat::from_xyzw(r.i, r.j, r.k, r.w)
}
}

1779
platform/Cargo.lock generated

File diff suppressed because it is too large Load diff

View file

@ -1,12 +0,0 @@
[package]
name = "raidillon_platform"
version = "0.1.0"
edition = "2024"
[dependencies]
winit = "0.30.12"
raidillon_core = { path = "../core" }
raidillon_assets = { path = "../asset" }
glam = "0.30.5"
serde = { version = "1.0.228", features = ["derive"] }
toml = "0.9.8"

View file

@ -1,86 +0,0 @@
use std::cell::Cell;
use std::{cell::RefCell, rc::Rc};
use std::sync::{Arc, Mutex, RwLock};
use winit::event::Event;
use raidillon_assets::ModelManagerRef;
use raidillon_core::EguiQueue;
use crate::settings::Settings;
/// a single debug wireframe vertex with position and color
#[derive(Clone, Copy)]
pub struct DebugWireframeVertex {
pub position: [f32; 3],
pub color: [f32; 4],
}
/// shared buffer for debug wireframe rendering
#[derive(Clone, Default)]
pub struct DebugWireframes {
pub vertices: Vec<DebugWireframeVertex>,
pub enabled: bool,
}
impl DebugWireframes {
pub fn new() -> Self {
Self { vertices: Vec::new(), enabled: true }
}
pub fn clear(&mut self) {
self.vertices.clear();
}
/// add a single line segment
pub fn add_line(&mut self, start: [f32; 3], end: [f32; 3], color: [f32; 4]) {
self.vertices.push(DebugWireframeVertex { position: start, color });
self.vertices.push(DebugWireframeVertex { position: end, color });
}
/// add a wireframe box from min/max corners
pub fn add_box(&mut self, min: [f32; 3], max: [f32; 3], color: [f32; 4]) {
let [x0, y0, z0] = min;
let [x1, y1, z1] = max;
// bottom face edges
self.add_line([x0, y0, z0], [x1, y0, z0], color);
self.add_line([x1, y0, z0], [x1, y0, z1], color);
self.add_line([x1, y0, z1], [x0, y0, z1], color);
self.add_line([x0, y0, z1], [x0, y0, z0], color);
// top face edges
self.add_line([x0, y1, z0], [x1, y1, z0], color);
self.add_line([x1, y1, z0], [x1, y1, z1], color);
self.add_line([x1, y1, z1], [x0, y1, z1], color);
self.add_line([x0, y1, z1], [x0, y1, z0], color);
// vertical edges
self.add_line([x0, y0, z0], [x0, y1, z0], color);
self.add_line([x1, y0, z0], [x1, y1, z0], color);
self.add_line([x1, y0, z1], [x1, y1, z1], color);
self.add_line([x0, y0, z1], [x0, y1, z1], color);
}
}
pub type DebugWireframesRef = Rc<RefCell<DebugWireframes>>;
#[derive(Clone)]
pub struct PlatformContext {
pub current_event: Event<()>,
pub asset_manager: ModelManagerRef,
pub frame_width: f32,
pub frame_height: f32,
pub time_ctx: TimeContext,
pub window: Arc<Mutex<winit::window::Window>>,
pub egui_queue: Rc<RefCell<EguiQueue>>,
pub settings: Arc<RwLock<Settings>>,
/// shared debug wireframe buffer
pub debug_wireframes: DebugWireframesRef,
/// sets whether or not egui will receive input events
pub should_egui_receive_input_events: Rc<Cell<bool>>,
}
#[derive(Clone)]
pub struct TimeContext {
pub frame_dt: f32,
pub fixed_dt: f32,
pub alpha: f32,
}

View file

@ -1,11 +0,0 @@
pub enum PlatformEvent {
/// Emmited when the window should
RedrawRequested,
/// The platform has requested to close the app.
CloseRequested,
/// Platform event loop is about to block and wait for new
/// new events.
AboutToWait
}

View file

@ -1,9 +0,0 @@
pub mod platform;
mod camera;
mod event;
pub mod context;
pub mod settings;
pub use platform::Platform;
pub use camera::Camera;
pub use context::{PlatformContext, TimeContext, DebugWireframes, DebugWireframesRef, DebugWireframeVertex};

View file

@ -1,8 +0,0 @@
use crate::PlatformContext;
use raidillon_core::engine::EngineTrait;
pub trait Platform<E: EngineTrait<PlatformCtx = PlatformContext>> {
/// Initialize platform.
fn initialize(engine: E, title: String, width: u32, height: u32) -> Self;
fn run(self);
}

View file

@ -1,166 +0,0 @@
use winit::monitor::{MonitorHandle, VideoModeHandle};
use winit::window::{Fullscreen, Window};
use serde::{Serialize, Deserialize};
use std::error::Error;
use std::fs;
use std::io;
use std::path::{Path, PathBuf};
pub fn default_config_path() -> PathBuf {
let exe_path = std::env::current_exe().unwrap();
let exe_dir = exe_path
.parent()
.ok_or_else(|| std::io::Error::new(std::io::ErrorKind::Other, "executable has no parent")).unwrap();
exe_dir.join("settings.toml")
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum WindowMode {
BorderlessFullscreen,
ExclusiveFullscreen,
#[default]
Windowed,
}
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct Settings {
pub display_settings: DisplaySettings,
}
impl Settings {
pub fn load_from_file(path: impl AsRef<Path>) -> Result<Self, Box<dyn Error>> {
let path = path.as_ref();
let text = fs::read_to_string(path)?;
let settings: Settings = toml::from_str(&text)?;
Ok(settings)
}
pub fn save_to_file(&self, path: impl AsRef<Path>) -> Result<(), Box<dyn Error>> {
let path = path.as_ref();
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)?;
}
let toml_str = toml::to_string_pretty(self)?;
fs::write(path, toml_str)?;
Ok(())
}
pub fn load_or_default(path: impl AsRef<Path>) -> Result<Self, Box<dyn Error>> {
let path = path.as_ref();
match fs::read_to_string(path) {
Ok(text) => {
let settings: Settings = toml::from_str(&text)?;
Ok(settings)
}
Err(err) if err.kind() == io::ErrorKind::NotFound => {
let settings = Settings::default();
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)?;
}
let toml_str = toml::to_string_pretty(&settings)?;
fs::write(path, toml_str)?;
Ok(settings)
}
Err(err) => Err(Box::new(err)),
}
}
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(default)]
pub struct DisplaySettings {
pub fullscreen_mode: WindowMode,
#[serde(skip)]
pub dirty: bool,
}
impl Default for DisplaySettings {
fn default() -> Self {
Self {
fullscreen_mode: WindowMode::Windowed,
dirty: false,
}
}
}
impl DisplaySettings {
pub fn apply(&self, window: &Window) {
// apply fullscreen mode
match self.fullscreen_mode {
WindowMode::BorderlessFullscreen => {
let monitor = window.current_monitor().or_else(|| window.primary_monitor());
window.set_fullscreen(Some(Fullscreen::Borderless(monitor)));
}
WindowMode::ExclusiveFullscreen => {
let monitor = window.current_monitor().or_else(|| window.primary_monitor());
match monitor {
Some(monitor) => {
if let Some(video_mode) = pick_best_video_mode(&monitor) {
window.set_fullscreen(Some(Fullscreen::Exclusive(video_mode)));
} else {
// fallback to borderless
window.set_fullscreen(Some(Fullscreen::Borderless(Some(monitor))));
}
}
None => {
// no monitor info, fallback to windowed
window.set_fullscreen(None);
}
}
}
WindowMode::Windowed => {
window.set_fullscreen(None);
},
}
}
}
fn pick_best_video_mode(monitor: &MonitorHandle) -> Option<VideoModeHandle> {
let target_size = monitor.size();
let mut best_native: Option<VideoModeHandle> = None;
let mut best_any: Option<VideoModeHandle> = None;
for mode in monitor.video_modes() {
if mode.size() == target_size {
let replace = match best_native.as_ref() {
None => true,
Some(best) => {
(mode.refresh_rate_millihertz(), mode.bit_depth())
> (best.refresh_rate_millihertz(), best.bit_depth())
}
};
if replace {
best_native = Some(mode.clone());
}
}
let replace = match best_any.as_ref() {
None => true,
Some(best) => is_better_video_mode(&mode, best),
};
if replace {
best_any = Some(mode);
}
}
best_native.or(best_any)
}
fn is_better_video_mode(a: &VideoModeHandle, b: &VideoModeHandle) -> bool {
let a_size = a.size();
let b_size = b.size();
let a_area = u64::from(a_size.width) * u64::from(a_size.height);
let b_area = u64::from(b_size.width) * u64::from(b_size.height);
match a_area.cmp(&b_area) {
std::cmp::Ordering::Greater => true,
std::cmp::Ordering::Less => false,
std::cmp::Ordering::Equal => {
(a.refresh_rate_millihertz(), a.bit_depth()) > (b.refresh_rate_millihertz(), b.bit_depth())
}
}
}

View file

@ -0,0 +1,9 @@
[package]
name = "raidillon_core"
version = "0.1.0"
edition = "2021"
[dependencies]
anyhow = "1.0.98"
glam = "0.30.4"
hecs = "0.10.5"

View file

@ -0,0 +1,95 @@
use std::collections::HashMap;
// Forward declarations - these will be from other crates
pub trait Model {}
pub trait Material {}
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub struct ModelId(pub usize);
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub struct MaterialId(pub usize);
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub struct TextureHandle(pub usize);
pub struct AssetManager<M: Model + ?Sized, Mat: Material + ?Sized> {
models: Vec<Box<M>>,
materials: Vec<Box<Mat>>,
textures: HashMap<String, TextureHandle>,
model_cache: HashMap<String, ModelId>,
next_texture_id: usize,
}
impl<M: Model + ?Sized, Mat: Material + ?Sized> AssetManager<M, Mat> {
pub fn new() -> Self {
Self {
models: Vec::new(),
materials: Vec::new(),
textures: HashMap::new(),
model_cache: HashMap::new(),
next_texture_id: 0,
}
}
pub fn add_model(&mut self, model: Box<M>) -> ModelId {
let id = ModelId(self.models.len());
self.models.push(model);
id
}
pub fn cache_model(&mut self, path: String, model: Box<M>) -> ModelId {
if let Some(&cached_id) = self.model_cache.get(&path) {
return cached_id;
}
let model_id = self.add_model(model);
self.model_cache.insert(path, model_id);
model_id
}
pub fn get_model(&self, id: ModelId) -> Option<&M> {
self.models.get(id.0).map(|boxed| boxed.as_ref())
}
pub fn get_model_mut(&mut self, id: ModelId) -> Option<&mut M> {
self.models.get_mut(id.0).map(|boxed| boxed.as_mut())
}
pub fn add_material(&mut self, material: Box<Mat>) -> MaterialId {
let id = MaterialId(self.materials.len());
self.materials.push(material);
id
}
pub fn get_material(&self, id: MaterialId) -> Option<&Mat> {
self.materials.get(id.0).map(|boxed| boxed.as_ref())
}
pub fn add_texture(&mut self, name: String) -> TextureHandle {
if let Some(&handle) = self.textures.get(&name) {
return handle;
}
let handle = TextureHandle(self.next_texture_id);
self.next_texture_id += 1;
self.textures.insert(name, handle);
handle
}
pub fn get_texture_handle(&self, name: &str) -> Option<TextureHandle> {
self.textures.get(name).copied()
}
pub fn model_count(&self) -> usize {
self.models.len()
}
pub fn material_count(&self) -> usize {
self.materials.len()
}
pub fn clear_cache(&mut self) {
self.model_cache.clear();
}
}

View file

@ -0,0 +1,80 @@
use hecs::World;
use crate::{
Time, EventBus, GameEvent, SystemRegistry,
AssetManager, Model, Material, ModelId
};
pub struct Engine {
pub world: World,
pub systems: SystemRegistry,
pub assets: AssetManager<dyn Model, dyn Material>,
pub events: EventBus,
pub time: Time,
}
impl Engine {
pub fn new() -> Self {
let systems = SystemRegistry::new();
Self {
world: World::new(),
systems,
assets: AssetManager::new(),
events: EventBus::new(),
time: Time::new(),
}
}
pub fn add_system<S: crate::System + 'static>(&mut self, system: S) {
self.systems.add_system(system);
}
pub fn update(&mut self) {
self.time.tick();
let dt = self.time.delta_seconds();
// Update all systems
self.systems.update_all(&mut self.world, &self.assets, &mut self.events, dt);
// Process events
self.events.process();
}
pub fn handle_window_event(&mut self, event: &GameEvent) {
self.events.emit(event.clone());
self.systems.handle_event_for_all(event, &mut self.world);
}
pub fn load_model(&mut self, path: &str) -> anyhow::Result<ModelId> {
// This is a placeholder - in a real implementation, we'd need to
// coordinate with the render system to actually load the model
// For now, just return a dummy ID
Ok(ModelId(0))
}
pub fn spawn_entity_with_model(&mut self, model_id: ModelId) -> hecs::Entity {
// This would need proper Transform and ModelHandle types
// For now, return a placeholder entity
self.world.spawn(())
}
pub fn delta_time(&self) -> f32 {
self.time.delta_seconds()
}
pub fn emit_event(&mut self, event: GameEvent) {
self.events.emit(event);
}
pub fn world(&self) -> &World {
&self.world
}
pub fn world_mut(&mut self) -> &mut World {
&mut self.world
}
pub fn system_count(&self) -> usize {
self.systems.system_count()
}
}

View file

@ -0,0 +1,60 @@
use glam::Vec3;
use hecs::Entity;
#[derive(Debug, Clone)]
pub enum GameEvent {
InputAction(InputAction),
CameraMove { position: Vec3, front: Vec3 },
WindowResize { width: u32, height: u32 },
EntitySpawned(Entity),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum InputAction {
MoveForward,
MoveBackward,
MoveLeft,
MoveRight,
}
pub trait EventHandler {
fn handle(&mut self, event: &GameEvent);
}
pub struct EventBus {
events: Vec<GameEvent>,
handlers: Vec<Box<dyn EventHandler>>,
}
impl EventBus {
pub fn new() -> Self {
Self {
events: Vec::new(),
handlers: Vec::new(),
}
}
pub fn emit(&mut self, event: GameEvent) {
self.events.push(event);
}
pub fn subscribe<H: EventHandler + 'static>(&mut self, handler: H) {
self.handlers.push(Box::new(handler));
}
pub fn process(&mut self) {
for event in self.events.drain(..) {
for handler in &mut self.handlers {
handler.handle(&event);
}
}
}
pub fn has_events(&self) -> bool {
!self.events.is_empty()
}
pub fn events(&self) -> &[GameEvent] {
&self.events
}
}

11
raidillon_core/src/lib.rs Normal file
View file

@ -0,0 +1,11 @@
pub mod time;
pub mod events;
pub mod assets;
pub mod systems;
pub mod engine;
pub use time::Time;
pub use events::{GameEvent, InputAction, EventHandler, EventBus};
pub use assets::{AssetManager, ModelId, MaterialId, TextureHandle, Model, Material};
pub use systems::{System, SystemRegistry};
pub use engine::Engine;

View file

@ -0,0 +1,45 @@
use hecs::World;
use crate::assets::{AssetManager, Model, Material};
use crate::events::{EventBus, GameEvent};
pub trait System {
fn update(&mut self, world: &mut World, resources: &AssetManager<dyn Model, dyn Material>, events: &mut EventBus, dt: f32);
fn handle_event(&mut self, event: &GameEvent, world: &mut World);
fn name(&self) -> &'static str;
}
pub struct SystemRegistry {
systems: Vec<Box<dyn System>>,
}
impl SystemRegistry {
pub fn new() -> Self {
Self {
systems: Vec::new(),
}
}
pub fn add_system<S: System + 'static>(&mut self, system: S) {
self.systems.push(Box::new(system));
}
pub fn update_all(&mut self, world: &mut World, resources: &AssetManager<dyn Model, dyn Material>, events: &mut EventBus, dt: f32) {
for system in &mut self.systems {
system.update(world, resources, events, dt);
}
}
pub fn handle_event_for_all(&mut self, event: &GameEvent, world: &mut World) {
for system in &mut self.systems {
system.handle_event(event, world);
}
}
pub fn system_count(&self) -> usize {
self.systems.len()
}
pub fn clear(&mut self) {
self.systems.clear();
}
}

View file

@ -0,0 +1,34 @@
use std::time::{Duration, Instant};
#[derive(Clone, Debug)]
pub struct Time {
last: Instant,
delta: Duration,
total: Duration,
}
impl Time {
pub fn new() -> Self {
let now = Instant::now();
Self {
last: now,
delta: Duration::ZERO,
total: Duration::ZERO,
}
}
pub fn tick(&mut self) {
let now = Instant::now();
self.delta = now - self.last;
self.total += self.delta;
self.last = now;
}
pub fn delta_seconds(&self) -> f32 {
self.delta.as_secs_f32()
}
pub fn total_seconds(&self) -> f32 {
self.total.as_secs_f32()
}
}

8
raidillon_ecs/Cargo.toml Normal file
View file

@ -0,0 +1,8 @@
[package]
name = "raidillon_ecs"
version = "0.1.0"
edition = "2021"
[dependencies]
glam = "0.30.4"
hecs = "0.10.5"

17
raidillon_ecs/src/lib.rs Normal file
View file

@ -0,0 +1,17 @@
use glam::{Mat4, Quat, Vec3};
#[derive(Copy, Clone)]
pub struct Transform {
pub translation: Vec3,
pub rotation: Quat,
pub scale: Vec3,
}
impl Transform {
pub fn matrix(&self) -> Mat4 {
Mat4::from_scale_rotation_translation(self.scale, self.rotation, self.translation)
}
}
#[derive(Copy, Clone, Debug)]
pub struct ModelHandle(pub usize);

16
raidillon_game/Cargo.toml Normal file
View file

@ -0,0 +1,16 @@
[package]
name = "raidillon_game"
version = "0.1.0"
edition = "2021"
[dependencies]
anyhow = "1.0.98"
glam = "0.30.4"
winit = "0.30"
glium = { version = "0.35.0", features = ["glutin_backend", "simple_window_builder"] }
raidillon_render = { path = "../raidillon_render" }
raidillon_ecs = { path = "../raidillon_ecs" }
raidillon_ui = { path = "../raidillon_ui" }
raidillon_core = { path = "../raidillon_core" }
hecs = "0.10.5"
raidillon_input = { path = "../raidillon_input" }

View file

@ -0,0 +1,88 @@
use anyhow;
use glam::{Quat, Vec3};
use hecs::{Entity, World};
use raidillon_ecs::{Transform, ModelHandle};
use raidillon_render::{Camera, ModelId};
use raidillon_core::InputAction;
pub struct GameState {
pub world: World,
pub camera_entity: Entity,
pub object_entity: Entity,
pub ground_entity: Entity,
}
impl GameState {
pub fn new() -> Self {
let mut world = World::new();
// Create camera entity
let camera_entity = world.spawn((Camera {
eye: Vec3::new(0.0, 0.0, 2.0),
center: Vec3::ZERO,
up: Vec3::Y,
fovy: 60_f32.to_radians(),
aspect: 1280.0 / 720.0, // default aspect ratio
znear: 0.1,
zfar: 100.0,
},));
// Create placeholder entities for object and ground (will be properly loaded later)
let object_entity = world.spawn((
Transform {
translation: Vec3::new(0.0, -2.5, -5.0),
rotation: Quat::IDENTITY,
scale: Vec3::new(0.01, 0.01, 0.01),
},
ModelHandle(0),
));
let ground_entity = world.spawn((
Transform {
translation: Vec3::new(0.0, -1.5, 0.0),
rotation: Quat::IDENTITY,
scale: Vec3::new(1.0, 1.0, 1.0),
},
ModelHandle(1),
));
Self {
world,
camera_entity,
object_entity,
ground_entity,
}
}
pub fn update(&mut self, _dt: f32) {
// Game state update logic will go here
// Camera updates are now handled by CameraSystem
}
pub fn resize_camera(&mut self, width: u32, height: u32) {
if let Ok(cam) = self.world.query_one_mut::<&mut Camera>(self.camera_entity) {
cam.aspect = width as f32 / height as f32;
}
}
pub fn world(&self) -> &World {
&self.world
}
pub fn world_mut(&mut self) -> &mut World {
&mut self.world
}
pub fn spawn_model(&mut self, model_id: ModelId, transform: Transform) -> Entity {
self.world.spawn((transform, ModelHandle(model_id.0)))
}
pub fn update_entity_model(&mut self, entity: Entity, model_id: ModelId) -> anyhow::Result<()> {
if let Ok(model_handle) = self.world.query_one_mut::<&mut ModelHandle>(entity) {
model_handle.0 = model_id.0;
Ok(())
} else {
Err(anyhow::anyhow!("Entity does not have a ModelHandle component"))
}
}
}

View file

@ -0,0 +1,4 @@
pub mod game_state;
pub use game_state::GameState;
pub use raidillon_core::InputAction;

199
raidillon_game/src/main.rs Normal file
View file

@ -0,0 +1,199 @@
use anyhow::Result;
use glam::{Quat, Vec3, EulerRot};
use raidillon_core::{Time, EventBus, GameEvent, InputAction, System, SystemRegistry, AssetManager, Model, Material};
use raidillon_ecs::Transform;
use raidillon_render::{RenderSystem, init_render_window, DisplayHandle};
use raidillon_ui::Gui;
use raidillon_input::{InputSystem, CameraSystem};
use raidillon_game::GameState;
use winit::window::CursorGrabMode;
use winit::event::MouseButton;
use hecs::World;
// Wrapper to make RenderSystem implement the System trait
struct RenderSystemWrapper {
render_system: RenderSystem,
}
impl RenderSystemWrapper {
fn new(display: DisplayHandle) -> anyhow::Result<Self> {
Ok(Self {
render_system: RenderSystem::new(display)?,
})
}
fn load_model(&mut self, path: &str) -> anyhow::Result<raidillon_core::ModelId> {
self.render_system.load_model(path)
}
fn render(&mut self, world: &World, target: &mut impl glium::Surface) {
self.render_system.render(world, target)
}
fn display(&self) -> &glium::Display<glium::glutin::surface::WindowSurface> {
self.render_system.display()
}
}
impl System for RenderSystemWrapper {
fn update(&mut self, _world: &mut World, _resources: &AssetManager<dyn Model, dyn Material>, _events: &mut EventBus, _dt: f32) {
// Rendering is handled separately in the main loop
}
fn handle_event(&mut self, _event: &GameEvent, _world: &mut World) {
// RenderSystem doesn't need to respond to events currently
}
fn name(&self) -> &'static str {
"RenderSystem"
}
}
fn main() -> Result<()> {
let event_loop = winit::event_loop::EventLoop::builder()
.build()
.expect("create event-loop");
let (window, _display): (winit::window::Window, DisplayHandle) = init_render_window(&event_loop, "raidillon", (1280, 720))?;
// Create game state and systems
let mut game_state = GameState::new();
let mut render_system_wrapper = RenderSystemWrapper::new(_display.clone())?;
// Dear ImGui integration
let mut gui = Gui::new(&_display, &window)?;
// Create system registry and register systems
let mut system_registry = SystemRegistry::new();
let mut event_bus = EventBus::new();
let mut input_system = InputSystem::new(); // Keep this for direct access
let mut camera_system = CameraSystem::new(game_state.camera_entity); // Keep this for direct access
// Register systems later when we have proper asset manager integration
// For now, manage systems directly in main loop
let mut right_mouse_held = false;
let mut time = Time::new();
// Load models using the RenderSystem
let object_model_id = render_system_wrapper.load_model("resources/models/tree.gltf")?;
let ground_model_id = render_system_wrapper.load_model("resources/models/plane.gltf")?;
// Update the model handles in game state using the new method
game_state.update_entity_model(game_state.object_entity, object_model_id)?;
game_state.update_entity_model(game_state.ground_entity, ground_model_id)?;
// Set initial camera aspect ratio
let (w, h): (u32, u32) = window.inner_size().into();
game_state.resize_camera(w, h);
event_loop
.run(move |event, el| {
use winit::event::{Event, WindowEvent};
gui.handle_event(&window, &event);
input_system.handle_event(&event);
match event {
Event::WindowEvent { event, .. } => match event {
WindowEvent::CloseRequested => el.exit(),
WindowEvent::Resized(sz) => {
camera_system.resize_camera(game_state.world_mut(), sz.width, sz.height);
event_bus.emit(GameEvent::WindowResize { width: sz.width, height: sz.height });
}
WindowEvent::MouseInput { state, button, .. } => {
if button == MouseButton::Right {
match state {
winit::event::ElementState::Pressed => {
if window
.set_cursor_grab(CursorGrabMode::Confined)
.or_else(|_| window.set_cursor_grab(CursorGrabMode::Locked))
.is_ok()
{
window.set_cursor_visible(false);
right_mouse_held = true;
}
}
winit::event::ElementState::Released => {
let _ = window.set_cursor_grab(CursorGrabMode::None);
window.set_cursor_visible(true);
right_mouse_held = false;
}
}
}
}
WindowEvent::RedrawRequested => {
// First render the 3D world
let mut target = render_system_wrapper.display().draw();
render_system_wrapper.render(game_state.world(), &mut target);
// Then overlay ImGui on top
gui.render_with(&mut target, &window, |ui| {
let object_entity = game_state.object_entity;
if let Ok(tr) = game_state.world_mut().query_one_mut::<&mut Transform>(object_entity) {
ui.text("Hold right click to control the camera");
ui.text("WASD to move");
// Translation controls
let mut translation = [tr.translation.x, tr.translation.y, tr.translation.z];
if ui.input_float3("Translation", &mut translation).build() {
tr.translation = Vec3::from(translation);
}
// Scale controls
let mut scale = [tr.scale.x, tr.scale.y, tr.scale.z];
if ui.input_float3("Scale", &mut scale).build() {
tr.scale = Vec3::from(scale);
}
// Rotation controls
let (yaw, pitch, roll) = tr.rotation.to_euler(EulerRot::YXZ);
let mut rotation_deg = [yaw.to_degrees(), pitch.to_degrees(), roll.to_degrees()];
if ui.input_float3("Rotation (deg)", &mut rotation_deg).build() {
let yaw = rotation_deg[0].to_radians();
let pitch = rotation_deg[1].to_radians();
let roll = rotation_deg[2].to_radians();
tr.rotation = Quat::from_euler(EulerRot::YXZ, yaw, pitch, roll);
}
}
});
target.finish().expect("Failed to swap buffers");
}
_ => {}
},
Event::AboutToWait => {
time.tick();
let dt = time.delta_seconds();
// Update input system and generate events
input_system.update(&mut event_bus, right_mouse_held);
// Process input events for camera movement
let mouse_delta = input_system.mouse_delta();
// Handle camera input actions
for event in event_bus.events() {
if let GameEvent::InputAction(action) = event {
camera_system.handle_input_action(*action, dt);
}
}
// Update camera with mouse movement
camera_system.update(game_state.world_mut(), dt, mouse_delta);
// Update game state
game_state.update(dt);
// Process all events
event_bus.process();
input_system.end_frame();
gui.prepare_frame(&window);
window.request_redraw();
}
_ => {}
}
})
.map_err(Into::into)
}

View file

@ -0,0 +1,116 @@
use anyhow::Result;
use raidillon_core::{Engine, GameEvent};
use raidillon_render::{init_render_window, RenderSystem};
use raidillon_ui::Gui;
use raidillon_input::{InputSystem, CameraSystem};
use winit::event::{Event, WindowEvent};
use winit::window::CursorGrabMode;
use winit::event::MouseButton;
fn main() -> Result<()> {
let event_loop = winit::event_loop::EventLoop::builder()
.build()
.expect("create event-loop");
let (window, _display) = init_render_window(&event_loop, "raidillon", (1280, 720))?;
// Create the unified engine
let mut engine = Engine::new();
// Create render system separately (for now, until full integration)
let mut render_system = RenderSystem::new(_display.clone())?;
// Create GUI system
let mut gui = Gui::new(&_display, &window)?;
// Add systems to the engine
let input_system = InputSystem::new();
let camera_system = CameraSystem::new(engine.world().spawn(())); // placeholder camera entity
engine.add_system(input_system);
engine.add_system(camera_system);
// Load initial scene content
load_default_scene(&mut engine, &mut render_system)?;
let mut right_mouse_held = false;
event_loop
.run(move |event, el| {
gui.handle_event(&window, &event);
match event {
Event::WindowEvent { event, .. } => match event {
WindowEvent::CloseRequested => el.exit(),
WindowEvent::Resized(sz) => {
engine.handle_window_event(&GameEvent::WindowResize {
width: sz.width,
height: sz.height
});
}
WindowEvent::MouseInput { state, button, .. } => {
if button == MouseButton::Right {
match state {
winit::event::ElementState::Pressed => {
if window
.set_cursor_grab(CursorGrabMode::Confined)
.or_else(|_| window.set_cursor_grab(CursorGrabMode::Locked))
.is_ok()
{
window.set_cursor_visible(false);
right_mouse_held = true;
}
}
winit::event::ElementState::Released => {
let _ = window.set_cursor_grab(CursorGrabMode::None);
window.set_cursor_visible(true);
right_mouse_held = false;
}
}
}
}
WindowEvent::RedrawRequested => {
// Update engine
engine.update();
// Render
let mut target = render_system.display().draw();
render_system.render(engine.world(), &mut target);
// Render debug UI
gui.render_with(&mut target, &window, |ui| {
render_debug_ui(&engine, ui);
});
target.finish().expect("Failed to swap buffers");
}
_ => {}
},
Event::AboutToWait => {
gui.prepare_frame(&window);
window.request_redraw();
}
_ => {}
}
})
.map_err(Into::into)
}
fn load_default_scene(engine: &mut Engine, render_system: &mut RenderSystem) -> Result<()> {
// Load and setup default scene
let _tree_model = render_system.load_model("resources/models/tree.gltf")?;
let _ground_model = render_system.load_model("resources/models/plane.gltf")?;
// Note: Full integration would require coordinating between engine and render system
// For now, this demonstrates the clean architecture structure
println!("Loaded default scene with {} systems", engine.system_count());
Ok(())
}
fn render_debug_ui(engine: &Engine, ui: &imgui::Ui) {
ui.text(format!("Engine Systems: {}", engine.system_count()));
ui.text(format!("Delta Time: {:.3}ms", engine.delta_time() * 1000.0));
ui.text("Clean Architecture Demo");
ui.text("This shows the unified Engine approach");
}

View file

@ -0,0 +1,11 @@
[package]
name = "raidillon_input"
version = "0.1.0"
edition = "2021"
[dependencies]
winit = "0.30"
glam = "0.30.4"
hecs = "0.10.5"
raidillon_core = { path = "../raidillon_core" }
raidillon_render = { path = "../raidillon_render" }

View file

@ -0,0 +1,73 @@
use glam::Vec3;
use std::hash::Hash;
use super::Input;
#[derive(Debug, Clone)]
pub struct FPSCameraController {
pub position: Vec3,
yaw: f32,
pitch: f32,
pub speed: f32,
pub sensitivity: f32,
}
impl FPSCameraController {
pub fn new(position: Vec3) -> Self {
Self {
position,
yaw: -90.0,
pitch: 0.0,
speed: 3.0,
sensitivity: 0.1,
}
}
pub fn update<A>(&mut self,
input: &Input<A>,
dt: f32,
mouse_enabled: bool,
actions: (A, A, A, A))
where
A: Copy + Eq + Hash,
{
let (forward, backward, left, right) = actions;
// Mouse look
if mouse_enabled {
let (dx, dy) = input.mouse_delta();
self.yaw += dx as f32 * self.sensitivity;
self.pitch -= dy as f32 * self.sensitivity;
self.pitch = self.pitch.clamp(-89.0, 89.0);
}
// Movement
let front = self.front();
let right_vec = front.cross(Vec3::Y).normalize();
let frame_speed = self.speed * dt;
if input.action_held(forward) {
self.position += front * frame_speed;
}
if input.action_held(backward) {
self.position -= front * frame_speed;
}
if input.action_held(left) {
self.position -= right_vec * frame_speed;
}
if input.action_held(right) {
self.position += right_vec * frame_speed;
}
}
pub fn front(&self) -> Vec3 {
let yaw_rad = self.yaw.to_radians();
let pitch_rad = self.pitch.to_radians();
Vec3::new(
yaw_rad.cos() * pitch_rad.cos(),
pitch_rad.sin(),
yaw_rad.sin() * pitch_rad.cos(),
)
.normalize()
}
}

View file

@ -0,0 +1,109 @@
use hecs::{Entity, World};
use raidillon_core::{EventHandler, GameEvent, InputAction, System, AssetManager, Model, Material, EventBus};
use raidillon_render::Camera;
use crate::FPSCameraController;
use glam::Vec3;
pub struct CameraSystem {
controller: FPSCameraController,
camera_entity: Entity,
yaw: f32,
pitch: f32,
}
impl CameraSystem {
pub fn new(camera_entity: Entity) -> Self {
Self {
controller: FPSCameraController::new(Vec3::new(0.0, 0.0, 2.0)),
camera_entity,
yaw: -90.0,
pitch: 0.0,
}
}
pub fn update(&mut self, world: &mut World, dt: f32, mouse_delta: (f64, f64)) {
// Apply mouse movement if there's any
if mouse_delta.0 != 0.0 || mouse_delta.1 != 0.0 {
self.yaw += mouse_delta.0 as f32 * self.controller.sensitivity;
self.pitch -= mouse_delta.1 as f32 * self.controller.sensitivity;
self.pitch = self.pitch.clamp(-89.0, 89.0);
// Update front vector based on new yaw/pitch
let yaw_rad = self.yaw.to_radians();
let pitch_rad = self.pitch.to_radians();
let front = Vec3::new(
yaw_rad.cos() * pitch_rad.cos(),
pitch_rad.sin(),
yaw_rad.sin() * pitch_rad.cos(),
).normalize();
}
// Update camera component in the world
if let Ok(cam) = world.query_one_mut::<&mut Camera>(self.camera_entity) {
cam.eye = self.controller.position;
cam.center = self.controller.position + self.controller.front();
}
}
pub fn handle_input_action(&mut self, action: InputAction, dt: f32) {
let front = self.controller.front();
let right = front.cross(Vec3::Y).normalize();
let frame_speed = self.controller.speed * dt;
match action {
InputAction::MoveForward => {
self.controller.position += front * frame_speed;
}
InputAction::MoveBackward => {
self.controller.position -= front * frame_speed;
}
InputAction::MoveLeft => {
self.controller.position -= right * frame_speed;
}
InputAction::MoveRight => {
self.controller.position += right * frame_speed;
}
}
}
pub fn resize_camera(&mut self, world: &mut World, width: u32, height: u32) {
if let Ok(cam) = world.query_one_mut::<&mut Camera>(self.camera_entity) {
cam.aspect = width as f32 / height as f32;
}
}
}
impl EventHandler for CameraSystem {
fn handle(&mut self, event: &GameEvent) {
match event {
GameEvent::InputAction(_action) => {
// Movement will be handled separately with delta time
// This is just for event registration
}
GameEvent::WindowResize { width: _, height: _ } => {
// Window resize will be handled separately with world access
}
_ => {}
}
}
}
impl System for CameraSystem {
fn update(&mut self, world: &mut World, _resources: &AssetManager<dyn Model, dyn Material>, _events: &mut EventBus, _dt: f32) {
// Camera update logic is handled separately with mouse input
// This system mainly responds to events
}
fn handle_event(&mut self, event: &GameEvent, world: &mut World) {
match event {
GameEvent::WindowResize { width, height } => {
self.resize_camera(world, *width, *height);
}
_ => {}
}
}
fn name(&self) -> &'static str {
"CameraSystem"
}
}

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