Compare commits

...

No commits in common. "164379810d12c2ea66560b1c004601b96760a432" and "4f74522979de54748aa9dbb7868547db4ed407dc" have entirely different histories.

225 changed files with 27822 additions and 984 deletions

View file

@ -1,23 +1,28 @@
---
# Core
Language: Cpp
Standard: Latest
ColumnLimit: '100'
Standard: Cpp11
ColumnLimit: '0' # No limit
# Bin pack
BinPackArguments: 'false'
BinPackParameters: 'false'
### Bin pack ###
BinPackArguments: 'true'
BinPackParameters: 'true'
# Includes
SortIncludes: 'true'
IncludeBlocks: Regroup
IncludeCategories:
# Current Project
- Regex: '"'
Priority: 001
# Custom Project Categories...
# Normal includes
# Dependecies
- Regex: '<'
Priority: 500
# Custom include categories...
# Custom Deependencies Categories...
# C++ includes
- Regex: '[^.h .hpp]>'
@ -77,20 +82,20 @@ SpacesInContainerLiterals: 'false'
SpacesInParentheses: 'false'
SpacesInSquareBrackets: 'false'
# Alignment
PointerAlignment: Right
### Alignment ###
PointerAlignment: Left
DerivePointerAlignment: 'false'
AlignAfterOpenBracket: Align
AlignEscapedNewlines: Left
AlignAfterOpenBracket: BlockIndent
AlignConsecutiveDeclarations: 'false'
AlignConsecutiveAssignments: 'false'
AlignConsecutiveAssignments: 'true'
AlignConsecutiveMacros: 'true'
AlignOperands: 'true'
AlignTrailingComments: 'true'
# Single Line
### Single Line ###
AllowShortCaseLabelsOnASingleLine: 'true'
AllowShortFunctionsOnASingleLine: 'false'
AllowShortFunctionsOnASingleLine: Inline
AllowShortLambdasOnASingleLine: Inline
AllowAllArgumentsOnNextLine: 'false'
AllowShortLoopsOnASingleLine: 'false'
@ -98,32 +103,33 @@ AllowShortBlocksOnASingleLine: 'false'
AllowAllParametersOfDeclarationOnNextLine: 'false'
AllowShortIfStatementsOnASingleLine: Never
# Break
### Break ###
AlwaysBreakAfterReturnType: None
AlwaysBreakBeforeMultilineStrings: 'false'
AlwaysBreakTemplateDeclarations: 'Yes'
BreakBeforeBinaryOperators: All
BreakBeforeBinaryOperators: None
BreakBeforeTernaryOperators: 'false'
BreakInheritanceList: BeforeComma
BreakStringLiterals: 'true'
BreakStringLiterals: 'false'
# Penalties
PenaltyBreakAssignment: '99999'
PenaltyBreakAssignment: '0'
PenaltyBreakBeforeFirstCallParameter: '0'
PenaltyBreakComment: '0'
PenaltyBreakFirstLessLess: '0'
PenaltyBreakString: '0'
PenaltyBreakTemplateDeclaration: '0'
PenaltyExcessCharacter: '999999999'
PenaltyExcessCharacter: '0'
PenaltyReturnTypeOnItsOwnLine: '999999999' # Nope
# Constructor Initializers
ConstructorInitializerAllOnOneLineOrOnePerLine: 'true'
AllowAllConstructorInitializersOnNextLine: 'false'
AllowAllConstructorInitializersOnNextLine: 'true'
BreakConstructorInitializers: BeforeComma
# Comments
ReflowComments: 'true'
ReflowComments: 'false'
CommentPragmas: '^ TODO@:'
FixNamespaceComments: 'true'
# Misc
@ -131,5 +137,3 @@ Cpp11BracedListStyle: 'false'
SortUsingDeclarations: 'true'
KeepEmptyLinesAtTheStartOfBlocks: 'false'
MaxEmptyLinesToKeep: '2'
ExperimentalAutoDetectBinPacking: false

View file

@ -1,250 +0,0 @@
---
Checks: "-*,
performance-unnecessary-value-param,
performance-unnecessary-copy-initialization,
performance-type-promotion-in-math-fn,
performance-trivially-destructible,
performance-noexcept-swap,
performance-noexcept-move-constructor,
performance-noexcept-destructor,
performance-no-int-to-ptr,
performance-no-automatic-move,
performance-move-constructor-init,
performance-move-const-arg,
performance-inefficient-vector-operation,
performance-inefficient-string-concatenation,
performance-inefficient-algorithm,
performance-implicit-conversion-in-loop,
performance-for-range-copy,
performance-faster-string-find,
performance-enum-size,
performance-avoid-endl,
readability-avoid-const-params-in-decls,
readability-avoid-nested-conditional-operator,
readability-avoid-return-with-void-value,
readability-avoid-unconditional-preprocessor-if,
readability-const-return-type,
readability-container-contains,
readability-container-data-pointdr,
readability-container-size-empty,
readability-delete-null-pointer,
readability-duplicate-include,
readability-else-after-return,
readability-inconsistent-declaration-parameter-name,
readability-isolate-declaration,
readability-make-member-function-const,
readability-misleading-indentation,
readability-misplaced-array-index,
readability-named-parameter,
readability-non-const-parameter,
readability-qualified-auto,
readability-redundant-access-specifiers,
readability-redundant-casting,
readability-redundant-control-flow,
readability-redundant-declaration,
readability-redundant-function-ptr-dereference,
readability-redundant-inline-specifier,
readability-redundant-member-init,
readability-redundant-preprocessor,
readability-redundant-smartptr-get,
readability-redundant-string-cstr,
readability-reference-to-constructed-temporary,
readability-simplify-boolean-expr,
readability-simplify-subscript-expr,
readability-static-accessed-through-instance,
readability-static-definition-in-anonymous-namespace,
readability-string-compare,
readability-suspicious-call-argument,
readability-uniqueptr-delete-release,
readability-use-anyofallof
readability-use-std-min-max,
readability-function-cognitive-complexity
readability-function-size
readability-identifier-naming
readability-identifier-length
readability-magic-numbers
modernize-avoid-bind,
modernize-avoid-c-arrays,
modernize-concat-nested-namespaces,
modernize-deprecated-headers,
modernize-deprecated-ios-base-aliases,
modernize-loop-convert,
modernize-macro-to-enum,
modernize-make-shared,
modernize-make-unique,
modernize-pass-by-value,
modernize-raw-string-literal,
modernize-redundant-void-arg,
modernize-replace-auto-ptr,
modernize-replace-disallow-copy-and-assign-macro,
modernize-replace-random-shuffle,
modernize-return-braced-init-list,
modernize-shrink-to-fit,
modernize-type-traits,
modernize-unary-static-assert,
modernize-use-auto,
modernize-use-bool-literals,
modernize-use-constraints,
modernize-use-default-member-init,
modernize-use-designated-initializers,
modernize-use-emplace,
modernize-use-equals-default,
modernize-use-equals-delete,
modernize-use-nodiscard,
modernize-use-noexcept,
modernize-use-nullptr,
modernize-use-override,
modernize-use-starts-ends-with,
modernize-use-std-numbers,
modernize-use-std-print,
modernize-use-transparent-functors,
modernize-use-uncaught-exceptions,
modernize-use-using
modernize-min-max-use-initializer-list,
cppcoreguidelines-avoid-capturing-lambda-coroutines,
cppcoreguidelines-avoid-const-or-ref-data-members,
cppcoreguidelines-avoid-do-while,
cppcoreguidelines-avoid-goto,
cppcoreguidelines-avoid-non-const-global-variables,
cppcoreguidelines-avoid-reference-coroutine-parameters,
cppcoreguidelines-init-variables,
cppcoreguidelines-interfaces-global-init,
cppcoreguidelines-macro-usage,
cppcoreguidelines-misleading-capture-default-by-value,
cppcoreguidelines-missing-std-forward,
cppcoreguidelines-narrowing-conversions,
cppcoreguidelines-no-malloc,
cppcoreguidelines-no-suspend-with-lock,
cppcoreguidelines-owning-memory,
cppcoreguidelines-prefer-member-initializer,
cppcoreguidelines-pro-bounds-array-to-pointer-decay,
cppcoreguidelines-pro-bounds-pointer-arithmetic,
cppcoreguidelines-pro-type-const-cast,
cppcoreguidelines-pro-type-cstyle-cast,
cppcoreguidelines-pro-type-member-init,
cppcoreguidelines-pro-type-reinterpret-cast,
cppcoreguidelines-pro-type-static-cast-downcast,
cppcoreguidelines-pro-type-union-access,
cppcoreguidelines-pro-type-vararg,
cppcoreguidelines-rvalue-reference-param-not-moved,
cppcoreguidelines-slicing,
cppcoreguidelines-special-member-functions,
cppcoreguidelines-virtual-class-destructor,
bugprone-argument-comment,
bugprone-assert-side-effect,
bugprone-assignment-in-if-condition,
bugprone-bad-signal-to-kill-thread,
bugprone-bool-pointer-implicit-conversion,
bugprone-branch-clone,
bugprone-casting-through-void,
bugprone-chained-comparison,
bugprone-compare-pointer-to-member-virtual-function,
bugprone-copy-constructor-init,
bugprone-crtp-constructor-accessibility,
bugprone-dangling-handle,
bugprone-empty-catch,
bugprone-exception-escape,
bugprone-fold-init-type,
bugprone-forward-declaration-namespace,
bugprone-forwarding-reference-overload,
bugprone-implicit-widening-of-multiplication-result,
bugprone-inaccurate-erase,
bugprone-inc-dec-in-conditions,
bugprone-incorrect-enable-if,
bugprone-incorrect-roundings,
bugprone-infinite-loop,
bugprone-integer-division,
bugprone-lambda-function-name,
bugprone-macro-parentheses,
bugprone-macro-repeated-side-effects,
bugprone-misplaced-operator-in-strlen-in-alloc,
bugprone-misplaced-pointer-arithmetic-in-alloc,
bugprone-misplaced-widening-cast,
bugprone-move-forwarding-reference,
bugprone-multi-level-implicit-pointer-conversion,
bugprone-multiple-new-in-one-expression,
bugprone-multiple-statement-macro,
bugprone-no-escape,
bugprone-non-zero-enum-to-bool-conversion,
bugprone-not-null-terminated-result,
bugprone-optional-value-conversion,
bugprone-parent-virtual-call,
bugprone-posix-return,
bugprone-redundant-branch-condition,
bugprone-reserved-identifier,
bugprone-return-const-ref-from-parameter,
bugprone-shared-ptr-array-mismatch,
bugprone-signal-handler,
bugprone-signed-char-misuse,
bugprone-sizeof-container,
bugprone-sizeof-expression,
bugprone-spuriously-wake-up-functions,
bugprone-standalone-empty,
bugprone-string-constructor,
bugprone-string-integer-assignment,
bugprone-string-literal-with-embedded-nul,
bugprone-stringview-nullptr,
bugprone-suspicious-enum-usage,
bugprone-suspicious-include,
bugprone-suspicious-memory-comparison,
bugprone-suspicious-memset-usage,
bugprone-suspicious-missing-comma,
bugprone-suspicious-realloc-usage,
bugprone-suspicious-semicolon,
bugprone-suspicious-string-compare,
bugprone-suspicious-stringview-data-usage,
bugprone-swapped-arguments,
bugprone-switch-missing-default-case,
bugprone-terminating-continue,
bugprone-throw-keyword-missing,
bugprone-too-small-loop-variable,
bugprone-unchecked-optional-access,
bugprone-undefined-memory-manipulation,
bugprone-undelegated-constructor,
bugprone-unhandled-exception-at-new,
bugprone-unhandled-self-assignment,
bugprone-unique-ptr-array-mismatch,
bugprone-unsafe-functions,
bugprone-unused-local-non-trivial-variable,
bugprone-unused-raii,
bugprone-unused-return-value,
bugprone-use-after-move,
bugprone-virtual-near-miss,
concurrency-mt-unsafe,
concurrency-thread-canceltype-asynchronous,
misc-use-anonymous-namespace,
misc-unused-using-decls,
misc-unused-parameters,
misc-unused-alias-decls,
misc-uniqueptr-reset-release,
misc-unconventional-assign-operator,
misc-throw-by-value-catch-by-reference,
misc-static-assert,
misc-redundant-expression,
misc-non-private-member-variables-in-classes,
misc-non-copyable-objects,
misc-no-recursion,
misc-new-delete-overloads,
misc-misplaced-const,
misc-misleading-identifier,
misc-misleading-bidirectional,
misc-include-cleaner,
misc-header-include-cycle,
misc-definitions-in-headers,
misc-coroutine-hostile-raii,
misc-const-correctness,
misc-confusable-identifiers,
hicpp-signed-bitwise,
hicpp-no-assembler,
hicpp-multiway-paths-covered,
hicpp-ignored-remove-result,
hicpp-exception-baseclass,
"

View file

@ -1,7 +0,0 @@
dangle_parens: true
line_ending: unix
line_width: 120
max_pargs_hwrap: 3
separate_ctrl_name_with_space: true
separate_fn_name_with_space: false
tab_size: 4

View file

@ -1,13 +0,0 @@
kind: pipeline
type: docker
name: linux_amd64
platform:
os: linux
arch: amd64
steps:
- name: clang format
image: alpine_amd64__clang_format
pull: if-not-exists
commands: $(git rev-parse --show-toplevel)/tools/ci/alpine_amd64/script.sh

36
.github/ISSUE_TEMPLATE/bug_report.md vendored Normal file
View file

@ -0,0 +1,36 @@
---
name: Bug report
about: Create a report to help us improve
title: "[BUG]: "
labels: ''
assignees: Light3039
---
**Describe the bug**
A clear and concise description of what the bug is.
**Expected behavior**
A clear and concise description of what you expected to happen.
**To Reproduce**
Steps to reproduce the behavior:
1. Make projects "..."
2. Build projects "..."
3. Run project (Mirror/Sandbox) "..."
4. Do "..."
5. See bug "..."
**System (you can omit any of the fields except OS and Console's debug output):**
- OS: [e.g. Manjaro Linux v21.1.0]
- GPU: [e.g. NVIDIA GeForce GTX 1050 Ti Mobile]
- CPU: [e.g. Intel i7-7700HQ (8) @ 3.800GHz]
- Console's debug output (omit if bug occurs before running the program):
**Screenshots**
If applicable, add screenshots to help explain your problem.
If possible add screen shot of console's debug output and neofetch.
**Additional context**
Add any other context about the problem here.

30
.gitignore vendored
View file

@ -1,5 +1,33 @@
# Temp directories
.vs/
bin/
bin-obj/
build/
.cache/
compile_commands.json
# VS Files
**.vcxproj**
**.sln
.codelite/
.build-debug/
.vimspector.json
**.workspace
Makefile
**/**.mk
**/**.project
**/Engine.txt
**/GLAD.txt
**/Sandbox.txt
**/Logs/**
**.ini
!**/default_gui_layout.ini
CMake/
compile_commands.json

25
.gitmodules vendored Normal file
View file

@ -0,0 +1,25 @@
[submodule "Dependencies/spdlog"]
path = Dependencies/spdlog
url = https://github.com/gabime/spdlog
[submodule "Dependencies/GLFW"]
path = Dependencies/GLFW
url = https://github.com/glfw/glfw
[submodule "Dependencies/glm"]
path = Dependencies/glm
url = https://github.com/g-truc/glm
[submodule "Dependencies/imgui"]
path = Dependencies/imgui
url = https://github.com/ocornut/imgui
branch = docking
[submodule "Dependencies/entt"]
path = Dependencies/entt
url = https://github.com/skypjack/entt
[submodule "Dependencies/yaml-cpp"]
path = Dependencies/yaml-cpp
url = https://github.com/jbeder/yaml-cpp
[submodule "Dependencies/shaderc"]
path = Dependencies/shaderc
url = https://github.com/google/shaderc
[submodule "Dependencies/spirv-cross"]
path = Dependencies/spirv-cross
url = https://github.com/KhronosGroup/SPIRV-Cross

View file

@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

2020
Assets/Scenes/demo.scene Normal file

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,10 @@
#version 440 core
in vec4 vso_FragmentColor;
out vec4 fso_FragmentColor;
void main()
{
fso_FragmentColor = vso_FragmentColor;
}

View file

@ -0,0 +1,17 @@
#version 440 core
layout(location = 0) in vec4 a_Position;
layout(location = 1) in vec4 a_Color;
layout(std140, binding = 0) uniform ub_ViewProjection
{
mat4 viewProjection;
};
layout(location = 0) out vec4 vso_FragmentColor;
void main()
{
gl_Position = viewProjection * a_Position;
vso_FragmentColor = a_Color;
}

View file

@ -0,0 +1,12 @@
#version 450 core
in vec2 vso_TexCoord;
uniform sampler2D u_Texture;
out vec4 fso_FragmentColor;
void main()
{
fso_FragmentColor = texture(u_Texture, vso_TexCoord);
}

View file

@ -0,0 +1,19 @@
#version 450 core
layout(location = 0) in vec4 a_Position;
layout(location = 1) in vec2 a_TexCoord;
layout(std140, binding = 0) uniform ub_ViewProjection
{
mat4 u_ViewProjection;
};
layout(location = 0) out vec2 vso_TexCoord;
void main()
{
gl_Position = u_ViewProjection * a_Position;
vso_TexCoord = a_TexCoord;
}

View file

@ -0,0 +1,14 @@
#version 450 core
in vec4 vso_Tint;
in vec2 vso_TexCoord;
uniform sampler2D u_Texture;
out vec4 fso_FragmentColor;
void main()
{
fso_FragmentColor = texture(u_Texture, vso_TexCoord) * vso_Tint;
}

View file

@ -0,0 +1,22 @@
#version 450 core
layout(location = 0) in vec4 a_Position;
layout(location = 1) in vec4 a_Tint;
layout(location = 2) in vec2 a_TexCoord;
layout(std140, binding = 0) uniform ub_ViewProjection
{
mat4 u_ViewProjection;
};
out vec4 vso_Tint;
out vec2 vso_TexCoord;
void main()
{
gl_Position = u_ViewProjection * a_Position;
vso_Tint = a_Tint;
vso_TexCoord = a_TexCoord;
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 79 KiB

View file

@ -1,9 +1,74 @@
cmake_minimum_required(VERSION 3.16 FATAL_ERROR)
project("light" LANGUAGES CXX)
cmake_minimum_required(VERSION 4.0)
set(CMAKE_CXX_STANDARD 26)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
add_subdirectory(docs)
add_subdirectory(modules)
project(Light)
set(CMAKE_CXX_STANDARD 20)
# directories
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
set(MIRROR_DIR ${CMAKE_BINARY_DIR}/../Mirror/)
set(ENGINE_DIR ${CMAKE_BINARY_DIR}/../Engine/)
set(DEPENDENCIES_DIR ${CMAKE_BINARY_DIR}/../Dependencies/)
if(NOT MSV)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-error")
endif()
if(WIN32)
add_compile_definitions(LIGHT_PLATFORM_WINDOWS)
elseif(UNIX)
add_compile_definitions(LIGHT_PLATFORM_LINUX)
endif()
# Projects
add_subdirectory(${ENGINE_DIR}/)
add_subdirectory(${MIRROR_DIR}/)
# Dependencies
add_subdirectory(${DEPENDENCIES_DIR}GLAD/)
add_subdirectory(${DEPENDENCIES_DIR}GLFW/)
add_subdirectory(${DEPENDENCIES_DIR})
add_subdirectory(${DEPENDENCIES_DIR}spdlog/)
add_subdirectory(${DEPENDENCIES_DIR}glm/)
add_subdirectory(${DEPENDENCIES_DIR}entt/)
add_subdirectory(${DEPENDENCIES_DIR}stb_image/)
add_subdirectory(${DEPENDENCIES_DIR}yaml-cpp/)
add_subdirectory(${DEPENDENCIES_DIR}shaderc/)
# Link
target_link_libraries(
imgui
PUBLIC glad
PUBLIC glfw
)
target_link_libraries(
Engine
PRIVATE glad
PRIVATE glfw
PRIVATE spdlog
PRIVATE imgui
PRIVATE stb_image
PRIVATE yaml-cpp
PRIVATE shaderc
)
target_link_libraries(
Mirror
PRIVATE Engine
PRIVATE imgui
)
# Precompiled headers
target_precompile_headers(Engine PUBLIC ${ENGINE_DIR}src/Engine/ltpch.hpp)
if(MSVC)
set_property(DIRECTORY ${CMAE_CURRENT_SOURCE_DIR} PROPERTY VS_STARTUP_PROJECT Mirror)
endif()
set(CMAKE_BUILD_TYPE debug)
set(CMAKE_EXPORT_COMPILE_COMMANDS_ON)

View file

@ -1,9 +0,0 @@
{
"version": 4,
"vendor": {
"conan": {}
},
"include": [
"build/Debug/generators/CMakePresets.json"
]
}

128
CODE_OF_CONDUCT.md Normal file
View file

@ -0,0 +1,128 @@
# Contributor Covenant Code of Conduct
## Our Pledge
We as members, contributors, and leaders pledge to make participation in our
community a harassment-free experience for everyone, regardless of age, body
size, visible or invisible disability, ethnicity, sex characteristics, gender
identity and expression, level of experience, education, socio-economic status,
nationality, personal appearance, race, religion, or sexual identity
and orientation.
We pledge to act and interact in ways that contribute to an open, welcoming,
diverse, inclusive, and healthy community.
## Our Standards
Examples of behavior that contributes to a positive environment for our
community include:
* Demonstrating empathy and kindness toward other people
* Being respectful of differing opinions, viewpoints, and experiences
* Giving and gracefully accepting constructive feedback
* Accepting responsibility and apologizing to those affected by our mistakes,
and learning from the experience
* Focusing on what is best not just for us as individuals, but for the
overall community
Examples of unacceptable behavior include:
* The use of sexualized language or imagery, and sexual attention or
advances of any kind
* Trolling, insulting or derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or email
address, without their explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Enforcement Responsibilities
Community leaders are responsible for clarifying and enforcing our standards of
acceptable behavior and will take appropriate and fair corrective action in
response to any behavior that they deem inappropriate, threatening, offensive,
or harmful.
Community leaders have the right and responsibility to remove, edit, or reject
comments, commits, code, wiki edits, issues, and other contributions that are
not aligned to this Code of Conduct, and will communicate reasons for moderation
decisions when appropriate.
## Scope
This Code of Conduct applies within all community spaces, and also applies when
an individual is officially representing the community in public spaces.
Examples of representing our community include using an official e-mail address,
posting via an official social media account, or acting as an appointed
representative at an online or offline event.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported to the community leaders responsible for enforcement at
Discord: Light7734#4652.
All complaints will be reviewed and investigated promptly and fairly.
All community leaders are obligated to respect the privacy and security of the
reporter of any incident.
## Enforcement Guidelines
Community leaders will follow these Community Impact Guidelines in determining
the consequences for any action they deem in violation of this Code of Conduct:
### 1. Correction
**Community Impact**: Use of inappropriate language or other behavior deemed
unprofessional or unwelcome in the community.
**Consequence**: A private, written warning from community leaders, providing
clarity around the nature of the violation and an explanation of why the
behavior was inappropriate. A public apology may be requested.
### 2. Warning
**Community Impact**: A violation through a single incident or series
of actions.
**Consequence**: A warning with consequences for continued behavior. No
interaction with the people involved, including unsolicited interaction with
those enforcing the Code of Conduct, for a specified period of time. This
includes avoiding interactions in community spaces as well as external channels
like social media. Violating these terms may lead to a temporary or
permanent ban.
### 3. Temporary Ban
**Community Impact**: A serious violation of community standards, including
sustained inappropriate behavior.
**Consequence**: A temporary ban from any sort of interaction or public
communication with the community for a specified period of time. No public or
private interaction with the people involved, including unsolicited interaction
with those enforcing the Code of Conduct, is allowed during this period.
Violating these terms may lead to a permanent ban.
### 4. Permanent Ban
**Community Impact**: Demonstrating a pattern of violation of community
standards, including sustained inappropriate behavior, harassment of an
individual, or aggression toward or disparagement of classes of individuals.
**Consequence**: A permanent ban from any sort of public interaction within
the community.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
version 2.0, available at
https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
Community Impact Guidelines were inspired by [Mozilla's code of conduct
enforcement ladder](https://github.com/mozilla/diversity).
[homepage]: https://www.contributor-covenant.org
For answers to common questions about this code of conduct, see the FAQ at
https://www.contributor-covenant.org/faq. Translations are available at
https://www.contributor-covenant.org/translations.

14
CONTRIBUTING.md Normal file
View file

@ -0,0 +1,14 @@
# How to contribute to Light Engine
Thanks for putting in the time to contribute to this project <3
## Coding conventions
For the time being, don't worry too much about the conventions...
Try to read other parts of the code and you'll get the hang of it
I have to learn clang-format, then everyone contributing can use it to format their code
###### happy coding-

47
Dependencies/CMakeLists.txt vendored Normal file
View file

@ -0,0 +1,47 @@
cmake_minimum_required(VERSION 3.14)
if (CMAKE_COMPILER_IS_GNUCC)
add_compile_options(-w)
endif()
if(MSVC)
add_compile_options(/MP)
add_compile_options(/W0)
endif()
file(GLOB IMGUI_FILES true ABSOLUTE
${CMAKE_CURRENT_SOURCE_DIR}/imgui/imgui.cpp
${CMAKE_CURRENT_SOURCE_DIR}/imgui/imgui_tables.cpp
${CMAKE_CURRENT_SOURCE_DIR}/imgui/imgui_widgets.cpp
${CMAKE_CURRENT_SOURCE_DIR}/imgui/imgui_draw.cpp
${CMAKE_CURRENT_SOURCE_DIR}/imgui/imgui_demo.cpp
)
set(BACKENDS_DIR ${CMAKE_CURRENT_SOURCE_DIR}/imgui/backends/)
include_directories(${CMAKE_CURRENT_SOURCE_DIR}/imgui)
file(GLOB IMGUI_BACKEND_FILES true ABSOLUTE
${BACKENDS_DIR}imgui_impl_opengl3.cpp
${BACKENDS_DIR}imgui_impl_glfw.cpp
# ${BACKENDS_DIR}imgui_impl_vulkan.cpp ${BACKENDS_DIR}imgui_impl_vulkan.h
)
if(WIN32)
file(GLOB IMGUI_WINDOWS_BACKEND_FILES true ABSOLUTE ${CMAKE_CURRENT_SOURCE_DIR}/backends/
${BACKENDS_DIR}imgui_impl_dx11.cpp
${BACKENDS_DIR}imgui_impl_win32.cpp
)
list(APPEND IMGUI_BACKEND_FILES ${IMGUI_WINDOWS_BACKEND_FILES})
endif()
add_compile_definitions(IMGUI_IMPL_OPENGL_LOADER_GLAD)
include_directories(${DEPENDENCIES_DIR}GLAD/include)
include_directories(${DEPENDENCIES_DIR}GLFW/include)
include_directories(${DEPENDENCIES_DIR}glm/)
add_library(imgui STATIC ${IMGUI_FILES} ${IMGUI_BACKEND_FILES})
# Copy imconfig.h over
file(COPY ${CMAKE_CURRENT_SOURCE_DIR}/Configurations/imgui/imconfig.h
DESTINATION ${CMAKE_CURRENT_SOURCE_DIR}/imgui/)

View file

@ -0,0 +1,131 @@
//-----------------------------------------------------------------------------
// COMPILE-TIME OPTIONS FOR DEAR IMGUI
// Runtime options (clipboard callbacks, enabling various features, etc.) can generally be set via the ImGuiIO structure.
// You can use ImGui::SetAllocatorFunctions() before calling ImGui::CreateContext() to rewire memory allocation functions.
//-----------------------------------------------------------------------------
// A) You may edit imconfig.h (and not overwrite it when updating Dear ImGui, or maintain a patch/rebased branch with your modifications to it)
// B) or '#define IMGUI_USER_CONFIG "my_imgui_config.h"' in your project and then add directives in your own file without touching this template.
//-----------------------------------------------------------------------------
// You need to make sure that configuration settings are defined consistently _everywhere_ Dear ImGui is used, which include the imgui*.cpp
// files but also _any_ of your code that uses Dear ImGui. This is because some compile-time options have an affect on data structures.
// Defining those options in imconfig.h will ensure every compilation unit gets to see the same data structure layouts.
// Call IMGUI_CHECKVERSION() from your .cpp files to verify that the data structures your files are using are matching the ones imgui.cpp is using.
//-----------------------------------------------------------------------------
#pragma once
//---- Define assertion handler. Defaults to calling assert().
// If your macro uses multiple statements, make sure is enclosed in a 'do { .. } while (0)' block so it can be used as a single statement.
//#define IM_ASSERT(_EXPR) MyAssert(_EXPR)
//#define IM_ASSERT(_EXPR) ((void)(_EXPR)) // Disable asserts
//---- Define attributes of all API symbols declarations, e.g. for DLL under Windows
// Using Dear ImGui via a shared library is not recommended, because of function call overhead and because we don't guarantee backward nor forward ABI compatibility.
// DLL users: heaps and globals are not shared across DLL boundaries! You will need to call SetCurrentContext() + SetAllocatorFunctions()
// for each static/DLL boundary you are calling from. Read "Context and Memory Allocators" section of imgui.cpp for more details.
//#define IMGUI_API __declspec( dllexport )
//#define IMGUI_API __declspec( dllimport )
//---- Don't define obsolete functions/enums/behaviors. Consider enabling from time to time after updating to avoid using soon-to-be obsolete function/names.
//#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS
//#define IMGUI_DISABLE_OBSOLETE_KEYIO // 1.87: disable legacy io.KeyMap[]+io.KeysDown[] in favor io.AddKeyEvent(). This will be folded into IMGUI_DISABLE_OBSOLETE_FUNCTIONS in a few versions.
//---- Disable all of Dear ImGui or don't implement standard windows.
// It is very strongly recommended to NOT disable the demo windows during development. Please read comments in imgui_demo.cpp.
//#define IMGUI_DISABLE // Disable everything: all headers and source files will be empty.
//#define IMGUI_DISABLE_DEMO_WINDOWS // Disable demo windows: ShowDemoWindow()/ShowStyleEditor() will be empty. Not recommended.
//#define IMGUI_DISABLE_METRICS_WINDOW // Disable metrics/debugger and other debug tools: ShowMetricsWindow() and ShowStackToolWindow() will be empty.
//---- Don't implement some functions to reduce linkage requirements.
//#define IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS // [Win32] Don't implement default clipboard handler. Won't use and link with OpenClipboard/GetClipboardData/CloseClipboard etc. (user32.lib/.a, kernel32.lib/.a)
//#define IMGUI_ENABLE_WIN32_DEFAULT_IME_FUNCTIONS // [Win32] [Default with Visual Studio] Implement default IME handler (require imm32.lib/.a, auto-link for Visual Studio, -limm32 on command-line for MinGW)
//#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS // [Win32] [Default with non-Visual Studio compilers] Don't implement default IME handler (won't require imm32.lib/.a)
//#define IMGUI_DISABLE_WIN32_FUNCTIONS // [Win32] Won't use and link with any Win32 function (clipboard, ime).
//#define IMGUI_ENABLE_OSX_DEFAULT_CLIPBOARD_FUNCTIONS // [OSX] Implement default OSX clipboard handler (need to link with '-framework ApplicationServices', this is why this is not the default).
//#define IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS // Don't implement ImFormatString/ImFormatStringV so you can implement them yourself (e.g. if you don't want to link with vsnprintf)
//#define IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS // Don't implement ImFabs/ImSqrt/ImPow/ImFmod/ImCos/ImSin/ImAcos/ImAtan2 so you can implement them yourself.
//#define IMGUI_DISABLE_FILE_FUNCTIONS // Don't implement ImFileOpen/ImFileClose/ImFileRead/ImFileWrite and ImFileHandle at all (replace them with dummies)
//#define IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS // Don't implement ImFileOpen/ImFileClose/ImFileRead/ImFileWrite and ImFileHandle so you can implement them yourself if you don't want to link with fopen/fclose/fread/fwrite. This will also disable the LogToTTY() function.
//#define IMGUI_DISABLE_DEFAULT_ALLOCATORS // Don't implement default allocators calling malloc()/free() to avoid linking with them. You will need to call ImGui::SetAllocatorFunctions().
//#define IMGUI_DISABLE_SSE // Disable use of SSE intrinsics even if available
//---- Include imgui_user.h at the end of imgui.h as a convenience
//#define IMGUI_INCLUDE_IMGUI_USER_H
//---- Pack colors to BGRA8 instead of RGBA8 (to avoid converting from one to another)
//#define IMGUI_USE_BGRA_PACKED_COLOR
//---- Use 32-bit for ImWchar (default is 16-bit) to support unicode planes 1-16. (e.g. point beyond 0xFFFF like emoticons, dingbats, symbols, shapes, ancient languages, etc...)
//#define IMGUI_USE_WCHAR32
//---- Avoid multiple STB libraries implementations, or redefine path/filenames to prioritize another version
// By default the embedded implementations are declared static and not available outside of Dear ImGui sources files.
//#define IMGUI_STB_TRUETYPE_FILENAME "my_folder/stb_truetype.h"
//#define IMGUI_STB_RECT_PACK_FILENAME "my_folder/stb_rect_pack.h"
//#define IMGUI_DISABLE_STB_TRUETYPE_IMPLEMENTATION
//#define IMGUI_DISABLE_STB_RECT_PACK_IMPLEMENTATION
//---- Use stb_printf's faster implementation of vsnprintf instead of the one from libc (unless IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS is defined)
// Requires 'stb_sprintf.h' to be available in the include path. Compatibility checks of arguments and formats done by clang and GCC will be disabled in order to support the extra formats provided by STB sprintf.
// #define IMGUI_USE_STB_SPRINTF
//---- Use FreeType to build and rasterize the font atlas (instead of stb_truetype which is embedded by default in Dear ImGui)
// Requires FreeType headers to be available in the include path. Requires program to be compiled with 'misc/freetype/imgui_freetype.cpp' (in this repository) + the FreeType library (not provided).
// On Windows you may use vcpkg with 'vcpkg install freetype --triplet=x64-windows' + 'vcpkg integrate install'.
//#define IMGUI_ENABLE_FREETYPE
//---- Use stb_truetype to build and rasterize the font atlas (default)
// The only purpose of this define is if you want force compilation of the stb_truetype backend ALONG with the FreeType backend.
//#define IMGUI_ENABLE_STB_TRUETYPE
//---- Define constructor and implicit cast operators to convert back<>forth between your math types and ImVec2/ImVec4.
// This will be inlined as part of ImVec2 and ImVec4 class declarations.
#include <glm/glm.hpp>
#define IM_VEC2_CLASS_EXTRA \
bool operator==(glm::vec2 rhs) { return x == rhs.x && y == rhs.y; } \
bool operator!=(glm::vec2 rhs) { return (*this) == rhs; } \
bool operator==(ImVec2 rhs) { return x == rhs.x && y == rhs.y; } \
bool operator!=(ImVec2 rhs) { return (*this) == rhs; }
#define IM_VEC4_CLASS_EXTRA \
bool operator==(glm::vec4 rhs) { return x == rhs.x && y == rhs.y && z == rhs.z && w == rhs.w; } \
bool operator!=(glm::vec4 rhs) { return (*this) == rhs; } \
bool operator==(ImVec4 rhs) { return x == rhs.x && y == rhs.y && z == rhs.z && w == rhs.w; } \
bool operator!=(ImVec4 rhs) { return (*this) == rhs; }
//---- Use 32-bit vertex indices (default is 16-bit) is one way to allow large meshes with more than 64K vertices.
// Your renderer backend will need to support it (most example renderer backends support both 16/32-bit indices).
// Another way to allow large meshes while keeping 16-bit indices is to handle ImDrawCmd::VtxOffset in your renderer.
// Read about ImGuiBackendFlags_RendererHasVtxOffset for details.
//#define ImDrawIdx unsigned int
//---- Override ImDrawCallback signature (will need to modify renderer backends accordingly)
//struct ImDrawList;
//struct ImDrawCmd;
//typedef void (*MyImDrawCallback)(const ImDrawList* draw_list, const ImDrawCmd* cmd, void* my_renderer_user_data);
//#define ImDrawCallback MyImDrawCallback
//---- Debug Tools: Macro to break in Debugger
// (use 'Metrics->Tools->Item Picker' to pick widgets with the mouse and break into them for easy debugging.)
//#define IM_DEBUG_BREAK IM_ASSERT(0)
//#define IM_DEBUG_BREAK __debugbreak()
//---- Debug Tools: Have the Item Picker break in the ItemAdd() function instead of ItemHoverable(),
// (which comes earlier in the code, will catch a few extra items, allow picking items other than Hovered one.)
// This adds a small runtime cost which is why it is not enabled by default.
//#define IMGUI_DEBUG_TOOL_ITEM_PICKER_EX
//---- Debug Tools: Enable slower asserts
//#define IMGUI_DEBUG_PARANOID
//---- Tip: You can add extra functions within the ImGui:: namespace, here or in your own headers files.
/*
namespace ImGui
{
void MyFunction(const char* name, const MyMatrix44& v);
}
*/

18
Dependencies/GLAD/CMakeLists.txt vendored Normal file
View file

@ -0,0 +1,18 @@
cmake_minimum_required(VERSION 3.14)
if (CMAKE_COMPILER_IS_GNUCC)
add_compile_options(-w)
endif()
if(MSVC)
add_compile_options(/MP)
add_compile_options(/W0)
endif()
project(GLAD VERSION 0.1.34 LANGUAGES C)
file(GLOB_RECURSE GLAD_SOURCES true ABSOLUTE ${CMAKE_CURRENT_SOURCE_DIR}/src/*)
file(GLOB_RECURSE GLAD_HEADERS true ABSOLUTE ${CMAKE_CURRENT_SOURCE_DIR}/include/*)
include_directories(${CMAKE_CURRENT_SOURCE_DIR}/include/)
add_library(glad STATIC ${GLAD_SOURCES} ${GLAD_HEADERS})

View file

@ -0,0 +1,290 @@
#ifndef __khrplatform_h_
#define __khrplatform_h_
/*
** Copyright (c) 2008-2018 The Khronos Group Inc.
**
** Permission is hereby granted, free of charge, to any person obtaining a
** copy of this software and/or associated documentation files (the
** "Materials"), to deal in the Materials without restriction, including
** without limitation the rights to use, copy, modify, merge, publish,
** distribute, sublicense, and/or sell copies of the Materials, and to
** permit persons to whom the Materials are furnished to do so, subject to
** the following conditions:
**
** The above copyright notice and this permission notice shall be included
** in all copies or substantial portions of the Materials.
**
** THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
** IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
** CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
** TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
** MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS.
*/
/* Khronos platform-specific types and definitions.
*
* The master copy of khrplatform.h is maintained in the Khronos EGL
* Registry repository at https://github.com/KhronosGroup/EGL-Registry
* The last semantic modification to khrplatform.h was at commit ID:
* 67a3e0864c2d75ea5287b9f3d2eb74a745936692
*
* Adopters may modify this file to suit their platform. Adopters are
* encouraged to submit platform specific modifications to the Khronos
* group so that they can be included in future versions of this file.
* Please submit changes by filing pull requests or issues on
* the EGL Registry repository linked above.
*
*
* See the Implementer's Guidelines for information about where this file
* should be located on your system and for more details of its use:
* http://www.khronos.org/registry/implementers_guide.pdf
*
* This file should be included as
* #include <KHR/khrplatform.h>
* by Khronos client API header files that use its types and defines.
*
* The types in khrplatform.h should only be used to define API-specific types.
*
* Types defined in khrplatform.h:
* khronos_int8_t signed 8 bit
* khronos_uint8_t unsigned 8 bit
* khronos_int16_t signed 16 bit
* khronos_uint16_t unsigned 16 bit
* khronos_int32_t signed 32 bit
* khronos_uint32_t unsigned 32 bit
* khronos_int64_t signed 64 bit
* khronos_uint64_t unsigned 64 bit
* khronos_intptr_t signed same number of bits as a pointer
* khronos_uintptr_t unsigned same number of bits as a pointer
* khronos_ssize_t signed size
* khronos_usize_t unsigned size
* khronos_float_t signed 32 bit floating point
* khronos_time_ns_t unsigned 64 bit time in nanoseconds
* khronos_utime_nanoseconds_t unsigned time interval or absolute time in
* nanoseconds
* khronos_stime_nanoseconds_t signed time interval in nanoseconds
* khronos_boolean_enum_t enumerated boolean type. This should
* only be used as a base type when a client API's boolean type is
* an enum. Client APIs which use an integer or other type for
* booleans cannot use this as the base type for their boolean.
*
* Tokens defined in khrplatform.h:
*
* KHRONOS_FALSE, KHRONOS_TRUE Enumerated boolean false/true values.
*
* KHRONOS_SUPPORT_INT64 is 1 if 64 bit integers are supported; otherwise 0.
* KHRONOS_SUPPORT_FLOAT is 1 if floats are supported; otherwise 0.
*
* Calling convention macros defined in this file:
* KHRONOS_APICALL
* KHRONOS_APIENTRY
* KHRONOS_APIATTRIBUTES
*
* These may be used in function prototypes as:
*
* KHRONOS_APICALL void KHRONOS_APIENTRY funcname(
* int arg1,
* int arg2) KHRONOS_APIATTRIBUTES;
*/
#if defined(__SCITECH_SNAP__) && !defined(KHRONOS_STATIC)
# define KHRONOS_STATIC 1
#endif
/*-------------------------------------------------------------------------
* Definition of KHRONOS_APICALL
*-------------------------------------------------------------------------
* This precedes the return type of the function in the function prototype.
*/
#if defined(KHRONOS_STATIC)
/* If the preprocessor constant KHRONOS_STATIC is defined, make the
* header compatible with static linking. */
# define KHRONOS_APICALL
#elif defined(_WIN32)
# define KHRONOS_APICALL __declspec(dllimport)
#elif defined (__SYMBIAN32__)
# define KHRONOS_APICALL IMPORT_C
#elif defined(__ANDROID__)
# define KHRONOS_APICALL __attribute__((visibility("default")))
#else
# define KHRONOS_APICALL
#endif
/*-------------------------------------------------------------------------
* Definition of KHRONOS_APIENTRY
*-------------------------------------------------------------------------
* This follows the return type of the function and precedes the function
* name in the function prototype.
*/
#if defined(_WIN32) && !defined(_WIN32_WCE) && !defined(__SCITECH_SNAP__)
/* Win32 but not WinCE */
# define KHRONOS_APIENTRY __stdcall
#else
# define KHRONOS_APIENTRY
#endif
/*-------------------------------------------------------------------------
* Definition of KHRONOS_APIATTRIBUTES
*-------------------------------------------------------------------------
* This follows the closing parenthesis of the function prototype arguments.
*/
#if defined (__ARMCC_2__)
#define KHRONOS_APIATTRIBUTES __softfp
#else
#define KHRONOS_APIATTRIBUTES
#endif
/*-------------------------------------------------------------------------
* basic type definitions
*-----------------------------------------------------------------------*/
#if (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L) || defined(__GNUC__) || defined(__SCO__) || defined(__USLC__)
/*
* Using <stdint.h>
*/
#include <stdint.h>
typedef int32_t khronos_int32_t;
typedef uint32_t khronos_uint32_t;
typedef int64_t khronos_int64_t;
typedef uint64_t khronos_uint64_t;
#define KHRONOS_SUPPORT_INT64 1
#define KHRONOS_SUPPORT_FLOAT 1
#elif defined(__VMS ) || defined(__sgi)
/*
* Using <inttypes.h>
*/
#include <inttypes.h>
typedef int32_t khronos_int32_t;
typedef uint32_t khronos_uint32_t;
typedef int64_t khronos_int64_t;
typedef uint64_t khronos_uint64_t;
#define KHRONOS_SUPPORT_INT64 1
#define KHRONOS_SUPPORT_FLOAT 1
#elif defined(_WIN32) && !defined(__SCITECH_SNAP__)
/*
* Win32
*/
typedef __int32 khronos_int32_t;
typedef unsigned __int32 khronos_uint32_t;
typedef __int64 khronos_int64_t;
typedef unsigned __int64 khronos_uint64_t;
#define KHRONOS_SUPPORT_INT64 1
#define KHRONOS_SUPPORT_FLOAT 1
#elif defined(__sun__) || defined(__digital__)
/*
* Sun or Digital
*/
typedef int khronos_int32_t;
typedef unsigned int khronos_uint32_t;
#if defined(__arch64__) || defined(_LP64)
typedef long int khronos_int64_t;
typedef unsigned long int khronos_uint64_t;
#else
typedef long long int khronos_int64_t;
typedef unsigned long long int khronos_uint64_t;
#endif /* __arch64__ */
#define KHRONOS_SUPPORT_INT64 1
#define KHRONOS_SUPPORT_FLOAT 1
#elif 0
/*
* Hypothetical platform with no float or int64 support
*/
typedef int khronos_int32_t;
typedef unsigned int khronos_uint32_t;
#define KHRONOS_SUPPORT_INT64 0
#define KHRONOS_SUPPORT_FLOAT 0
#else
/*
* Generic fallback
*/
#include <stdint.h>
typedef int32_t khronos_int32_t;
typedef uint32_t khronos_uint32_t;
typedef int64_t khronos_int64_t;
typedef uint64_t khronos_uint64_t;
#define KHRONOS_SUPPORT_INT64 1
#define KHRONOS_SUPPORT_FLOAT 1
#endif
/*
* Types that are (so far) the same on all platforms
*/
typedef signed char khronos_int8_t;
typedef unsigned char khronos_uint8_t;
typedef signed short int khronos_int16_t;
typedef unsigned short int khronos_uint16_t;
/*
* Types that differ between LLP64 and LP64 architectures - in LLP64,
* pointers are 64 bits, but 'long' is still 32 bits. Win64 appears
* to be the only LLP64 architecture in current use.
*/
#ifdef _WIN64
typedef signed long long int khronos_intptr_t;
typedef unsigned long long int khronos_uintptr_t;
typedef signed long long int khronos_ssize_t;
typedef unsigned long long int khronos_usize_t;
#else
typedef signed long int khronos_intptr_t;
typedef unsigned long int khronos_uintptr_t;
typedef signed long int khronos_ssize_t;
typedef unsigned long int khronos_usize_t;
#endif
#if KHRONOS_SUPPORT_FLOAT
/*
* Float type
*/
typedef float khronos_float_t;
#endif
#if KHRONOS_SUPPORT_INT64
/* Time types
*
* These types can be used to represent a time interval in nanoseconds or
* an absolute Unadjusted System Time. Unadjusted System Time is the number
* of nanoseconds since some arbitrary system event (e.g. since the last
* time the system booted). The Unadjusted System Time is an unsigned
* 64 bit value that wraps back to 0 every 584 years. Time intervals
* may be either signed or unsigned.
*/
typedef khronos_uint64_t khronos_utime_nanoseconds_t;
typedef khronos_int64_t khronos_stime_nanoseconds_t;
#endif
/*
* Dummy value used to pad enum types to 32 bits.
*/
#ifndef KHRONOS_MAX_ENUM
#define KHRONOS_MAX_ENUM 0x7FFFFFFF
#endif
/*
* Enumerated boolean type
*
* Values other than zero should be considered to be true. Therefore
* comparisons should not be made against KHRONOS_TRUE.
*/
typedef enum {
KHRONOS_FALSE = 0,
KHRONOS_TRUE = 1,
KHRONOS_BOOLEAN_ENUM_FORCE_SIZE = KHRONOS_MAX_ENUM
} khronos_boolean_enum_t;
#endif /* __khrplatform_h_ */

3698
Dependencies/GLAD/include/glad/glad.h vendored Normal file

File diff suppressed because it is too large Load diff

1834
Dependencies/GLAD/src/glad.c vendored Normal file

File diff suppressed because it is too large Load diff

1
Dependencies/GLFW vendored Submodule

@ -0,0 +1 @@
Subproject commit 62e175ef9fae75335575964c845a302447c012c7

1
Dependencies/entt vendored Submodule

@ -0,0 +1 @@
Subproject commit ebc0c18534a33afcd49878cadea2620bac5cc6bf

1
Dependencies/glm vendored Submodule

@ -0,0 +1 @@
Subproject commit cc98465e3508535ba8c7f6208df934c156a018dc

1
Dependencies/imgui vendored Submodule

@ -0,0 +1 @@
Subproject commit 250333d895b1067533533dcfab137512745b9689

1
Dependencies/shaderc vendored Submodule

@ -0,0 +1 @@
Subproject commit 96b1dd72a827304817470274a470c4d3b2293451

1
Dependencies/spdlog vendored Submodule

@ -0,0 +1 @@
Subproject commit 6fa36017cfd5731d617e1a934f0e5ea9c4445b13

1
Dependencies/spirv-cross vendored Submodule

@ -0,0 +1 @@
Subproject commit b3ff97d0feafd2b7ca72aec7215cfc3d0998fb79

13
Dependencies/stb_image/CMakeLists.txt vendored Normal file
View file

@ -0,0 +1,13 @@
cmake_minimum_required(VERSION 3.14)
if (CMAKE_COMPILER_IS_GNUCC)
add_compile_options(-w)
endif()
if(MSVC)
add_compile_options(/MP)
add_compile_options(/W0)
endif()
file(GLOB STB_IMAGES_FILES true ABSOLUTE ${CMAKE_CURRENT_SOURCE_DIR}/*)
add_library(stb_image STATIC ${STB_IMAGES_FILES})

7126
Dependencies/stb_image/stb_image.c vendored Normal file

File diff suppressed because it is too large Load diff

541
Dependencies/stb_image/stb_image.h vendored Normal file
View file

@ -0,0 +1,541 @@
/* stb_image - v2.27 - public domain image loader - http://nothings.org/stb
no warranty implied; use at your own risk
Do this:
#define STB_IMAGE_IMPLEMENTATION
before you include this file in *one* C or C++ file to create the implementation.
// i.e. it should look like this:
#include ...
#include ...
#include ...
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
You can #define STBI_ASSERT(x) before the #include to avoid using assert.h.
And #define STBI_MALLOC, STBI_REALLOC, and STBI_FREE to avoid using malloc,realloc,free
QUICK NOTES:
Primarily of interest to game developers and other people who can
avoid problematic images and only need the trivial interface
JPEG baseline & progressive (12 bpc/arithmetic not supported, same as stock IJG lib)
PNG 1/2/4/8/16-bit-per-channel
TGA (not sure what subset, if a subset)
BMP non-1bpp, non-RLE
PSD (composited view only, no extra channels, 8/16 bit-per-channel)
GIF (*comp always reports as 4-channel)
HDR (radiance rgbE format)
PIC (Softimage PIC)
PNM (PPM and PGM binary only)
Animated GIF still needs a proper API, but here's one way to do it:
http://gist.github.com/urraka/685d9a6340b26b830d49
- decode from memory or through FILE (define STBI_NO_STDIO to remove code)
- decode from arbitrary I/O callbacks
- SIMD acceleration on x86/x64 (SSE2) and ARM (NEON)
Full documentation under "DOCUMENTATION" below.
LICENSE
See end of file for license information.
RECENT REVISION HISTORY:
2.27 (2021-07-11) document stbi_info better, 16-bit PNM support, bug fixes
2.26 (2020-07-13) many minor fixes
2.25 (2020-02-02) fix warnings
2.24 (2020-02-02) fix warnings; thread-local failure_reason and flip_vertically
2.23 (2019-08-11) fix clang static analysis warning
2.22 (2019-03-04) gif fixes, fix warnings
2.21 (2019-02-25) fix typo in comment
2.20 (2019-02-07) support utf8 filenames in Windows; fix warnings and platform ifdefs
2.19 (2018-02-11) fix warning
2.18 (2018-01-30) fix warnings
2.17 (2018-01-29) bugfix, 1-bit BMP, 16-bitness query, fix warnings
2.16 (2017-07-23) all functions have 16-bit variants; optimizations; bugfixes
2.15 (2017-03-18) fix png-1,2,4; all Imagenet JPGs; no runtime SSE detection on GCC
2.14 (2017-03-03) remove deprecated STBI_JPEG_OLD; fixes for Imagenet JPGs
2.13 (2016-12-04) experimental 16-bit API, only for PNG so far; fixes
2.12 (2016-04-02) fix typo in 2.11 PSD fix that caused crashes
2.11 (2016-04-02) 16-bit PNGS; enable SSE2 in non-gcc x64
RGB-format JPEG; remove white matting in PSD;
allocate large structures on the stack;
correct channel count for PNG & BMP
2.10 (2016-01-22) avoid warning introduced in 2.09
2.09 (2016-01-16) 16-bit TGA; comments in PNM files; STBI_REALLOC_SIZED
See end of file for full revision history.
============================ Contributors =========================
Image formats Extensions, features
Sean Barrett (jpeg, png, bmp) Jetro Lauha (stbi_info)
Nicolas Schulz (hdr, psd) Martin "SpartanJ" Golini (stbi_info)
Jonathan Dummer (tga) James "moose2000" Brown (iPhone PNG)
Jean-Marc Lienher (gif) Ben "Disch" Wenger (io callbacks)
Tom Seddon (pic) Omar Cornut (1/2/4-bit PNG)
Thatcher Ulrich (psd) Nicolas Guillemot (vertical flip)
Ken Miller (pgm, ppm) Richard Mitton (16-bit PSD)
github:urraka (animated gif) Junggon Kim (PNM comments)
Christopher Forseth (animated gif) Daniel Gibson (16-bit TGA)
socks-the-fox (16-bit PNG)
Jeremy Sawicki (handle all ImageNet JPGs)
Optimizations & bugfixes Mikhail Morozov (1-bit BMP)
Fabian "ryg" Giesen Anael Seghezzi (is-16-bit query)
Arseny Kapoulkine Simon Breuss (16-bit PNM)
John-Mark Allen
Carmelo J Fdez-Aguera
Bug & warning fixes
Marc LeBlanc David Woo Guillaume George Martins Mozeiko
Christpher Lloyd Jerry Jansson Joseph Thomson Blazej Dariusz Roszkowski
Phil Jordan Dave Moore Roy Eltham
Hayaki Saito Nathan Reed Won Chun
Luke Graham Johan Duparc Nick Verigakis the Horde3D community
Thomas Ruf Ronny Chevalier github:rlyeh
Janez Zemva John Bartholomew Michal Cichon github:romigrou
Jonathan Blow Ken Hamada Tero Hanninen github:svdijk
Eugene Golushkov Laurent Gomila Cort Stratton github:snagar
Aruelien Pocheville Sergio Gonzalez Thibault Reuille github:Zelex
Cass Everitt Ryamond Barbiero github:grim210
Paul Du Bois Engin Manap Aldo Culquicondor github:sammyhw
Philipp Wiesemann Dale Weiler Oriol Ferrer Mesia github:phprus
Josh Tobin Matthew Gregan github:poppolopoppo
Julian Raschke Gregory Mullen Christian Floisand github:darealshinji
Baldur Karlsson Kevin Schmidt JR Smith github:Michaelangel007
Brad Weinberger Matvey Cherevko github:mosra
Luca Sas Alexander Veselov Zack Middleton [reserved]
Ryan C. Gordon [reserved] [reserved]
DO NOT ADD YOUR NAME HERE
Jacko Dirks
To add your name to the credits, pick a random blank space in the middle and fill it.
80% of merge conflicts on stb PRs are due to people adding their name at the end
of the credits.
*/
#ifndef STBI_INCLUDE_STB_IMAGE_H
#define STBI_INCLUDE_STB_IMAGE_H
// DOCUMENTATION
//
// Limitations:
// - no 12-bit-per-channel JPEG
// - no JPEGs with arithmetic coding
// - GIF always returns *comp=4
//
// Basic usage (see HDR discussion below for HDR usage):
// int x,y,n;
// unsigned char *data = stbi_load(filename, &x, &y, &n, 0);
// // ... process data if not NULL ...
// // ... x = width, y = height, n = # 8-bit components per pixel ...
// // ... replace '0' with '1'..'4' to force that many components per pixel
// // ... but 'n' will always be the number that it would have been if you said 0
// stbi_image_free(data)
//
// Standard parameters:
// int *x -- outputs image width in pixels
// int *y -- outputs image height in pixels
// int *channels_in_file -- outputs # of image components in image file
// int desired_channels -- if non-zero, # of image components requested in result
//
// The return value from an image loader is an 'unsigned char *' which points
// to the pixel data, or NULL on an allocation failure or if the image is
// corrupt or invalid. The pixel data consists of *y scanlines of *x pixels,
// with each pixel consisting of N interleaved 8-bit components; the first
// pixel pointed to is top-left-most in the image. There is no padding between
// image scanlines or between pixels, regardless of format. The number of
// components N is 'desired_channels' if desired_channels is non-zero, or
// *channels_in_file otherwise. If desired_channels is non-zero,
// *channels_in_file has the number of components that _would_ have been
// output otherwise. E.g. if you set desired_channels to 4, you will always
// get RGBA output, but you can check *channels_in_file to see if it's trivially
// opaque because e.g. there were only 3 channels in the source image.
//
// An output image with N components has the following components interleaved
// in this order in each pixel:
//
// N=#comp components
// 1 grey
// 2 grey, alpha
// 3 red, green, blue
// 4 red, green, blue, alpha
//
// If image loading fails for any reason, the return value will be NULL,
// and *x, *y, *channels_in_file will be unchanged. The function
// stbi_failure_reason() can be queried for an extremely brief, end-user
// unfriendly explanation of why the load failed. Define STBI_NO_FAILURE_STRINGS
// to avoid compiling these strings at all, and STBI_FAILURE_USERMSG to get slightly
// more user-friendly ones.
//
// Paletted PNG, BMP, GIF, and PIC images are automatically depalettized.
//
// To query the width, height and component count of an image without having to
// decode the full file, you can use the stbi_info family of functions:
//
// int x,y,n,ok;
// ok = stbi_info(filename, &x, &y, &n);
// // returns ok=1 and sets x, y, n if image is a supported format,
// // 0 otherwise.
//
// Note that stb_image pervasively uses ints in its public API for sizes,
// including sizes of memory buffers. This is now part of the API and thus
// hard to change without causing breakage. As a result, the various image
// loaders all have certain limits on image size; these differ somewhat
// by format but generally boil down to either just under 2GB or just under
// 1GB. When the decoded image would be larger than this, stb_image decoding
// will fail.
//
// Additionally, stb_image will reject image files that have any of their
// dimensions set to a larger value than the configurable STBI_MAX_DIMENSIONS,
// which defaults to 2**24 = 16777216 pixels. Due to the above memory limit,
// the only way to have an image with such dimensions load correctly
// is for it to have a rather extreme aspect ratio. Either way, the
// assumption here is that such larger images are likely to be malformed
// or malicious. If you do need to load an image with individual dimensions
// larger than that, and it still fits in the overall size limit, you can
// #define STBI_MAX_DIMENSIONS on your own to be something larger.
//
// ===========================================================================
//
// UNICODE:
//
// If compiling for Windows and you wish to use Unicode filenames, compile
// with
// #define STBI_WINDOWS_UTF8
// and pass utf8-encoded filenames. Call stbi_convert_wchar_to_utf8 to convert
// Windows wchar_t filenames to utf8.
//
// ===========================================================================
//
// Philosophy
//
// stb libraries are designed with the following priorities:
//
// 1. easy to use
// 2. easy to maintain
// 3. good performance
//
// Sometimes I let "good performance" creep up in priority over "easy to maintain",
// and for best performance I may provide less-easy-to-use APIs that give higher
// performance, in addition to the easy-to-use ones. Nevertheless, it's important
// to keep in mind that from the standpoint of you, a client of this library,
// all you care about is #1 and #3, and stb libraries DO NOT emphasize #3 above all.
//
// Some secondary priorities arise directly from the first two, some of which
// provide more explicit reasons why performance can't be emphasized.
//
// - Portable ("ease of use")
// - Small source code footprint ("easy to maintain")
// - No dependencies ("ease of use")
//
// ===========================================================================
//
// I/O callbacks
//
// I/O callbacks allow you to read from arbitrary sources, like packaged
// files or some other source. Data read from callbacks are processed
// through a small internal buffer (currently 128 bytes) to try to reduce
// overhead.
//
// The three functions you must define are "read" (reads some bytes of data),
// "skip" (skips some bytes of data), "eof" (reports if the stream is at the end).
//
// ===========================================================================
//
// SIMD support
//
// The JPEG decoder will try to automatically use SIMD kernels on x86 when
// supported by the compiler. For ARM Neon support, you must explicitly
// request it.
//
// (The old do-it-yourself SIMD API is no longer supported in the current
// code.)
//
// On x86, SSE2 will automatically be used when available based on a run-time
// test; if not, the generic C versions are used as a fall-back. On ARM targets,
// the typical path is to have separate builds for NEON and non-NEON devices
// (at least this is true for iOS and Android). Therefore, the NEON support is
// toggled by a build flag: define STBI_NEON to get NEON loops.
//
// If for some reason you do not want to use any of SIMD code, or if
// you have issues compiling it, you can disable it entirely by
// defining STBI_NO_SIMD.
//
// ===========================================================================
//
// HDR image support (disable by defining STBI_NO_HDR)
//
// stb_image supports loading HDR images in general, and currently the Radiance
// .HDR file format specifically. You can still load any file through the existing
// interface; if you attempt to load an HDR file, it will be automatically remapped
// to LDR, assuming gamma 2.2 and an arbitrary scale factor defaulting to 1;
// both of these constants can be reconfigured through this interface:
//
// stbi_hdr_to_ldr_gamma(2.2f);
// stbi_hdr_to_ldr_scale(1.0f);
//
// (note, do not use _inverse_ constants; stbi_image will invert them
// appropriately).
//
// Additionally, there is a new, parallel interface for loading files as
// (linear) floats to preserve the full dynamic range:
//
// float *data = stbi_loadf(filename, &x, &y, &n, 0);
//
// If you load LDR images through this interface, those images will
// be promoted to floating point values, run through the inverse of
// constants corresponding to the above:
//
// stbi_ldr_to_hdr_scale(1.0f);
// stbi_ldr_to_hdr_gamma(2.2f);
//
// Finally, given a filename (or an open file or memory block--see header
// file for details) containing image data, you can query for the "most
// appropriate" interface to use (that is, whether the image is HDR or
// not), using:
//
// stbi_is_hdr(char *filename);
//
// ===========================================================================
//
// iPhone PNG support:
//
// We optionally support converting iPhone-formatted PNGs (which store
// premultiplied BGRA) back to RGB, even though they're internally encoded
// differently. To enable this conversion, call
// stbi_convert_iphone_png_to_rgb(1).
//
// Call stbi_set_unpremultiply_on_load(1) as well to force a divide per
// pixel to remove any premultiplied alpha *only* if the image file explicitly
// says there's premultiplied data (currently only happens in iPhone images,
// and only if iPhone convert-to-rgb processing is on).
//
// ===========================================================================
//
// ADDITIONAL CONFIGURATION
//
// - You can suppress implementation of any of the decoders to reduce
// your code footprint by #defining one or more of the following
// symbols before creating the implementation.
//
// STBI_NO_JPEG
// STBI_NO_PNG
// STBI_NO_BMP
// STBI_NO_PSD
// STBI_NO_TGA
// STBI_NO_GIF
// STBI_NO_HDR
// STBI_NO_PIC
// STBI_NO_PNM (.ppm and .pgm)
//
// - You can request *only* certain decoders and suppress all other ones
// (this will be more forward-compatible, as addition of new decoders
// doesn't require you to disable them explicitly):
//
// STBI_ONLY_JPEG
// STBI_ONLY_PNG
// STBI_ONLY_BMP
// STBI_ONLY_PSD
// STBI_ONLY_TGA
// STBI_ONLY_GIF
// STBI_ONLY_HDR
// STBI_ONLY_PIC
// STBI_ONLY_PNM (.ppm and .pgm)
//
// - If you use STBI_NO_PNG (or _ONLY_ without PNG), and you still
// want the zlib decoder to be available, #define STBI_SUPPORT_ZLIB
//
// - If you define STBI_MAX_DIMENSIONS, stb_image will reject images greater
// than that size (in either width or height) without further processing.
// This is to let programs in the wild set an upper bound to prevent
// denial-of-service attacks on untrusted data, as one could generate a
// valid image of gigantic dimensions and force stb_image to allocate a
// huge block of memory and spend disproportionate time decoding it. By
// default this is set to (1 << 24), which is 16777216, but that's still
// very big.
#ifndef STBI_NO_STDIO
#include <stdio.h>
#endif // STBI_NO_STDIO
#define STBI_VERSION 1
enum
{
STBI_default = 0, // only used for desired_channels
STBI_grey = 1,
STBI_grey_alpha = 2,
STBI_rgb = 3,
STBI_rgb_alpha = 4
};
#include <stdlib.h>
typedef unsigned char stbi_uc;
typedef unsigned short stbi_us;
#ifdef __cplusplus
extern "C"
{
#endif
#ifndef STBIDEF
#ifdef STB_IMAGE_STATIC
#define STBIDEF static
#else
#define STBIDEF extern
#endif
#endif
//////////////////////////////////////////////////////////////////////////////
//
// PRIMARY API - works on images of any type
//
//
// load image by filename, open file, or memory buffer
//
typedef struct
{
int (*read)(void* user, char* data, int size); // fill 'data' with 'size' bytes. return number of bytes actually read
void (*skip)(void* user, int n); // skip the next 'n' bytes, or 'unget' the last -n bytes if negative
int (*eof)(void* user); // returns nonzero if we are at end of file/data
} stbi_io_callbacks;
////////////////////////////////////
//
// 8-bits-per-channel interface
//
STBIDEF stbi_uc* stbi_load_from_memory(stbi_uc const* buffer, int len, int* x, int* y, int* channels_in_file, int desired_channels);
STBIDEF stbi_uc* stbi_load_from_callbacks(stbi_io_callbacks const* clbk, void* user, int* x, int* y, int* channels_in_file, int desired_channels);
#ifndef STBI_NO_STDIO
STBIDEF stbi_uc* stbi_load(char const* filename, int* x, int* y, int* channels_in_file, int desired_channels);
STBIDEF stbi_uc* stbi_load_from_file(FILE* f, int* x, int* y, int* channels_in_file, int desired_channels);
// for stbi_load_from_file, file pointer is left pointing immediately after image
#endif
#ifndef STBI_NO_GIF
STBIDEF stbi_uc* stbi_load_gif_from_memory(stbi_uc const* buffer, int len, int** delays, int* x, int* y, int* z, int* comp, int req_comp);
#endif
#ifdef STBI_WINDOWS_UTF8
STBIDEF int stbi_convert_wchar_to_utf8(char* buffer, size_t bufferlen, const wchar_t* input);
#endif
////////////////////////////////////
//
// 16-bits-per-channel interface
//
STBIDEF stbi_us* stbi_load_16_from_memory(stbi_uc const* buffer, int len, int* x, int* y, int* channels_in_file, int desired_channels);
STBIDEF stbi_us* stbi_load_16_from_callbacks(stbi_io_callbacks const* clbk, void* user, int* x, int* y, int* channels_in_file, int desired_channels);
#ifndef STBI_NO_STDIO
STBIDEF stbi_us* stbi_load_16(char const* filename, int* x, int* y, int* channels_in_file, int desired_channels);
STBIDEF stbi_us* stbi_load_from_file_16(FILE* f, int* x, int* y, int* channels_in_file, int desired_channels);
#endif
////////////////////////////////////
//
// float-per-channel interface
//
#ifndef STBI_NO_LINEAR
STBIDEF float* stbi_loadf_from_memory(stbi_uc const* buffer, int len, int* x, int* y, int* channels_in_file, int desired_channels);
STBIDEF float* stbi_loadf_from_callbacks(stbi_io_callbacks const* clbk, void* user, int* x, int* y, int* channels_in_file, int desired_channels);
#ifndef STBI_NO_STDIO
STBIDEF float* stbi_loadf(char const* filename, int* x, int* y, int* channels_in_file, int desired_channels);
STBIDEF float* stbi_loadf_from_file(FILE* f, int* x, int* y, int* channels_in_file, int desired_channels);
#endif
#endif
#ifndef STBI_NO_HDR
STBIDEF void stbi_hdr_to_ldr_gamma(float gamma);
STBIDEF void stbi_hdr_to_ldr_scale(float scale);
#endif // STBI_NO_HDR
#ifndef STBI_NO_LINEAR
STBIDEF void stbi_ldr_to_hdr_gamma(float gamma);
STBIDEF void stbi_ldr_to_hdr_scale(float scale);
#endif // STBI_NO_LINEAR
// stbi_is_hdr is always defined, but always returns false if STBI_NO_HDR
STBIDEF int stbi_is_hdr_from_callbacks(stbi_io_callbacks const* clbk, void* user);
STBIDEF int stbi_is_hdr_from_memory(stbi_uc const* buffer, int len);
#ifndef STBI_NO_STDIO
STBIDEF int stbi_is_hdr(char const* filename);
STBIDEF int stbi_is_hdr_from_file(FILE* f);
#endif // STBI_NO_STDIO
// get a VERY brief reason for failure
// on most compilers (and ALL modern mainstream compilers) this is threadsafe
STBIDEF const char* stbi_failure_reason(void);
// free the loaded image -- this is just free()
STBIDEF void stbi_image_free(void* retval_from_stbi_load);
// get image dimensions & components without fully decoding
STBIDEF int stbi_info_from_memory(stbi_uc const* buffer, int len, int* x, int* y, int* comp);
STBIDEF int stbi_info_from_callbacks(stbi_io_callbacks const* clbk, void* user, int* x, int* y, int* comp);
STBIDEF int stbi_is_16_bit_from_memory(stbi_uc const* buffer, int len);
STBIDEF int stbi_is_16_bit_from_callbacks(stbi_io_callbacks const* clbk, void* user);
#ifndef STBI_NO_STDIO
STBIDEF int stbi_info(char const* filename, int* x, int* y, int* comp);
STBIDEF int stbi_info_from_file(FILE* f, int* x, int* y, int* comp);
STBIDEF int stbi_is_16_bit(char const* filename);
STBIDEF int stbi_is_16_bit_from_file(FILE* f);
#endif
// for image formats that explicitly notate that they have premultiplied alpha,
// we just return the colors as stored in the file. set this flag to force
// unpremultiplication. results are undefined if the unpremultiply overflow.
STBIDEF void stbi_set_unpremultiply_on_load(int flag_true_if_should_unpremultiply);
// indicate whether we should process iphone images back to canonical format,
// or just pass them through "as-is"
STBIDEF void stbi_convert_iphone_png_to_rgb(int flag_true_if_should_convert);
// flip the image vertically, so the first pixel in the output array is the bottom left
STBIDEF void stbi_set_flip_vertically_on_load(int flag_true_if_should_flip);
// as above, but only applies to images loaded on the thread that calls the function
// this function is only available if your compiler supports thread-local variables;
// calling it will fail to link if your compiler doesn't
STBIDEF void stbi_set_unpremultiply_on_load_thread(int flag_true_if_should_unpremultiply);
STBIDEF void stbi_convert_iphone_png_to_rgb_thread(int flag_true_if_should_convert);
STBIDEF void stbi_set_flip_vertically_on_load_thread(int flag_true_if_should_flip);
// ZLIB client - used by PNG, available for other purposes
STBIDEF char* stbi_zlib_decode_malloc_guesssize(const char* buffer, int len, int initial_size, int* outlen);
STBIDEF char* stbi_zlib_decode_malloc_guesssize_headerflag(const char* buffer, int len, int initial_size, int* outlen, int parse_header);
STBIDEF char* stbi_zlib_decode_malloc(const char* buffer, int len, int* outlen);
STBIDEF int stbi_zlib_decode_buffer(char* obuffer, int olen, const char* ibuffer, int ilen);
STBIDEF char* stbi_zlib_decode_noheader_malloc(const char* buffer, int len, int* outlen);
STBIDEF int stbi_zlib_decode_noheader_buffer(char* obuffer, int olen, const char* ibuffer, int ilen);
#ifdef __cplusplus
}
#endif
//// end header file /////////////////////////////////////////////////////
#endif // STBI_INCLUDE_STB_IMAGE_H

1
Dependencies/volk vendored Submodule

@ -0,0 +1 @@
Subproject commit 760a782f295a66de7391d6ed573d65e3fb1c8450

1
Dependencies/yaml-cpp vendored Submodule

@ -0,0 +1 @@
Subproject commit 190ad502b5bc91b01fd2e73f5343cf7b40cfdc70

139
Engine/.clang-format Normal file
View file

@ -0,0 +1,139 @@
---
# Core
Language: Cpp
Standard: Cpp11
ColumnLimit: '0' # No limit
### Bin pack ###
BinPackArguments: 'true'
BinPackParameters: 'true'
# Includes
SortIncludes: 'true'
IncludeBlocks: Regroup
IncludeCategories:
# Current Project
- Regex: '"'
Priority: 001
# Custom Project Categories...
# Dependecies
- Regex: '<'
Priority: 500
# Custom Deependencies Categories...
# C++ includes
- Regex: '[^.h .hpp]>'
Priority: 998
# C includes
- Regex: '<[^/\n]+[.]h>'
Priority: 999
# Braces
BreakBeforeBraces: Custom
BraceWrapping:
AfterCaseLabel: true
AfterClass: true
AfterControlStatement: true
AfterEnum: true
AfterFunction: true
AfterNamespace: false
AfterObjCDeclaration: true
AfterStruct: true
AfterUnion: true
AfterExternBlock: true
BeforeCatch: true
BeforeElse: true
IndentBraces: false
SplitEmptyFunction: true
SplitEmptyRecord: true
SplitEmptyNamespace: true
# Indentation
UseTab: ForIndentation
TabWidth: '4'
IndentWidth: '4'
ContinuationIndentWidth: '4'
ConstructorInitializerIndentWidth: '4'
IndentCaseLabels: 'false'
IndentWrappedFunctionNames: 'true'
IndentPPDirectives: BeforeHash
NamespaceIndentation: None
AccessModifierOffset: '-4'
# Space
SpaceAfterCStyleCast: 'false'
SpaceAfterLogicalNot: 'false'
SpaceAfterTemplateKeyword: 'false'
SpaceBeforeAssignmentOperators: 'true'
SpaceBeforeCpp11BracedList: 'true'
SpaceBeforeCtorInitializerColon: 'false'
SpaceBeforeInheritanceColon: 'false'
SpaceBeforeParens: ControlStatements
SpaceBeforeRangeBasedForLoopColon: 'true'
SpaceInEmptyParentheses: 'false'
SpacesBeforeTrailingComments: '1'
SpacesInAngles: 'false'
SpacesInCStyleCastParentheses: 'false'
SpacesInContainerLiterals: 'false'
SpacesInParentheses: 'false'
SpacesInSquareBrackets: 'false'
### Alignment ###
PointerAlignment: Left
DerivePointerAlignment: 'false'
AlignAfterOpenBracket: Align
AlignEscapedNewlines: Left
AlignConsecutiveDeclarations: 'false'
AlignConsecutiveAssignments: 'true'
AlignConsecutiveMacros: 'true'
AlignOperands: 'true'
AlignTrailingComments: 'true'
### Single Line ###
AllowShortCaseLabelsOnASingleLine: 'true'
AllowShortFunctionsOnASingleLine: Inline
AllowShortLambdasOnASingleLine: Inline
AllowAllArgumentsOnNextLine: 'false'
AllowShortLoopsOnASingleLine: 'false'
AllowShortBlocksOnASingleLine: 'false'
AllowAllParametersOfDeclarationOnNextLine: 'false'
AllowShortIfStatementsOnASingleLine: Never
### Break ###
AlwaysBreakAfterReturnType: None
AlwaysBreakBeforeMultilineStrings: 'false'
AlwaysBreakTemplateDeclarations: 'Yes'
BreakBeforeBinaryOperators: None
BreakBeforeTernaryOperators: 'false'
BreakInheritanceList: BeforeComma
BreakStringLiterals: 'false'
# Penalties
PenaltyBreakAssignment: '0'
PenaltyBreakBeforeFirstCallParameter: '0'
PenaltyBreakComment: '0'
PenaltyBreakFirstLessLess: '0'
PenaltyBreakString: '0'
PenaltyBreakTemplateDeclaration: '0'
PenaltyExcessCharacter: '0'
PenaltyReturnTypeOnItsOwnLine: '999999999' # Nope
# Constructor Initializers
ConstructorInitializerAllOnOneLineOrOnePerLine: 'true'
AllowAllConstructorInitializersOnNextLine: 'true'
BreakConstructorInitializers: BeforeComma
# Comments
ReflowComments: 'false'
CommentPragmas: '^ TODO@:'
FixNamespaceComments: 'true'
# Misc
Cpp11BracedListStyle: 'false'
SortUsingDeclarations: 'true'
KeepEmptyLinesAtTheStartOfBlocks: 'false'
MaxEmptyLinesToKeep: '2'

57
Engine/CMakeLists.txt Normal file
View file

@ -0,0 +1,57 @@
cmake_minimum_required(VERSION 3.16)
if(CMAKE_COMPILER_IS_GNUCC)
add_compile_options(-w)
endif()
if(MSVC)
add_compile_options(/MP)
add_compile_options(/W0)
endif()
file(GLOB_RECURSE ENGINE_ALL_FILES true ABSOLUTE ${ENGINE_DIR}src/*)
file(GLOB_RECURSE ENGINE_RES_FILES true ABSOLUTE ${ENGINE_DIR}res/*)
list(LENGTH ENGINE_ALL_FILES ENGINE_ALL_FILES_COUNT)
if(NOT WIN32)
set(DX_DIR ${ENGINE_DIR}src/Platform/GraphicsAPI/DirectX/)
set(WIN_DIR ${ENGINE_DIR}src/Platform/OS/Windows/)
list(
REMOVE_ITEM ENGINE_ALL_FILES
${DX_DIR}dxBlender.cpp
${DX_DIR}dxBuffers.cpp
${DX_DIR}dxFramebuffer.cpp
${DX_DIR}dxGraphicsContext.cpp
${DX_DIR}dxRenderCommand.cpp
${DX_DIR}dxShader.cpp
${DX_DIR}dxSharedContext.cpp
${DX_DIR}dxTexture.cpp
${DX_DIR}dxUserInterface.cpp
${DX_DIR}dxVertexLayout.cpp
${WIN_DIR}wWindow.cpp
)
else()
file(GLOB_RECURSE HLSL_FILES true ABSOLUTE ${ENGINE_DIR}res/*.hlsl)
set_source_files_properties(${HLSL_FILES} PROPERTIES VS_TOOL_OVERRIDE "None")
endif()
list(LENGTH ENGINE_ALL_FILES ENGINE_ALL_FILES_COUNT)
include_directories(
${ENGINE_DIR}src/Engine/
${ENGINE_DIR}src/Platform/GraphicsAPI/
${ENGINE_DIR}src/Platform/OS/
${DEPENDENCIES_DIR}entt/src/
${DEPENDENCIES_DIR}GLAD/include/
${DEPENDENCIES_DIR}GLFW/include/
${DEPENDENCIES_DIR}glm/
${DEPENDENCIES_DIR}imgui/
${DEPENDENCIES_DIR}spdlog/include/
${DEPENDENCIES_DIR}stb_image/
${DEPENDENCIES_DIR}yaml-cpp/include/
${DEPENDENCIES_DIR}shaderc/libshaderc/include
)
source_group(TREE ${ENGINE_DIR} FILES ${ENGINE_ALL_FILES} ${ENGINE_RES_FILES})
add_library(Engine STATIC ${ENGINE_ALL_FILES} ${ENGINE_RES_FILES})

View file

@ -0,0 +1,111 @@
#pragma once
#include <memory>
namespace Light {
// Ref (Ref)
template<typename T>
using Ref = std::shared_ptr<T>;
template<typename T, typename... Args>
constexpr Ref<T> CreateRef(Args&&... args)
{
return std::make_shared<T>(std::forward<Args>(args)...);
}
template<typename T>
constexpr Ref<T> MakeRef(T* rawPointer)
{
return std::shared_ptr<T>(rawPointer);
}
// Scope (std::unique_ptr)
template<typename T>
using Scope = std::unique_ptr<T>;
template<typename T, typename... Args>
constexpr std::unique_ptr<T> CreateScope(Args&&... args)
{
return std::make_unique<T>(std::forward<Args>(args)...);
}
template<typename T>
constexpr std::unique_ptr<T> MakeScope(T* rawPointer)
{
return std::unique_ptr<T>(rawPointer);
}
} // namespace Light
//========== PLATFORM ==========//
#define LT_WIN(x) // windows
#define LT_LIN(x) // linux
#define LT_MAC(x) // mac
#if defined(LIGHT_PLATFORM_WINDOWS)
#define LT_BUILD_PLATFORM "Windows"
#define LT_WIN(x) x
#elif defined(LIGHT_PLATFORM_LINUX)
#define LT_BUILD_PLATFORM "Linux"
#define LT_LIN(x) x
#elif defined(LIGHT_PLATFORM_MAC)
#error "Unsupported platform: MAC"
#define LT_MAC(x) x
#else
#error "Unsupported platform: Unknown"
#endif
//========== PLATFORM ==========//
//====================================================================== OPERATIONS ======================================================================//
/* assertions */
#define ASSERT(x, ...) \
{ \
if (!(x)) \
{ \
LOG(critical, __VA_ARGS__); \
LT_DEBUG_TRAP(); \
throw ::Light::FailedAssertion(__FILE__, __LINE__); \
} \
}
/* bit-wise */
#define BIT(x) 1 << x
/* token */
#define LT_PAIR_TOKEN_VALUE_TO_NAME(token) \
{ \
token, #token \
}
#define LT_PAIR_TOKEN_NAME_TO_VALUE(token) \
{ \
#token, token \
}
#define LT_TOKEN_NAME(token) #token
//====================================================================== OPERATIONS ======================================================================//
//========== ESSENTIAL_HEADERS ==========//
/* config */
#ifndef LIGHT_CONFIG_H
#include "Base/Config.hpp"
#endif
/* debug */
#ifndef LIGHT_LOGGER_H
#include "Debug/Logger.hpp"
#endif
#include "Debug/Exceptions.hpp"
/* portables */
#ifndef LIGHT_DEBUG_TRAP_H
#include "Base/Portables/DebugTrap.hpp"
#endif
/* utility */
#ifndef LIGHT_STRINGIFIER_H
#include "Utility/Stringifier.hpp"
#endif
//========== ESSENTIAL_HEADERS ==========//

View file

@ -0,0 +1,16 @@
#pragma once
#ifndef LIGHT_CONFIG_H
#define LIGHT_CONFIG_H
//
// you can uncomment any of these definitions to config the project to your
// liking
//
// suppress undefined debug trap
#define LIGHT_IGNORE_UNDEFINED_DEBUG_TRAP
// log opengl shader compile info
// #define LIGHT_OPENGL_ENABLE_SHADER_INFO_LOG
#endif

View file

@ -0,0 +1,91 @@
#pragma once
#ifdef LIGHT_PLATFORM_WINDOWS
#include <LightEngine.hpp>
// to be defined in client project
extern Light::Application* Light::CreateApplication(std::string execName, std::vector<std::string> args);
// #todo: use windows specific stuff
int main(int argc, char* argv[])
{
Light::Application* application = nullptr;
int exitCode = 0;
std::vector<std::string> args;
if (argc > 1)
args.assign(argv + 1, argv + argc);
try
{
application = Light::CreateApplication(argv[0], args);
ASSERT(application, "Light::Application is not intialized");
for (int i = 0; i < argc; i++)
LOG(info, "argv[{}]: {}", i, argv[i]);
application->GameLoop();
}
// failed engine assertion
catch (Light::FailedAssertion)
{
LOG(critical, "Terminating due to unhandled 'FailedEngineAssertion'");
exitCode = -1;
}
// gl exception
catch (Light::glException)
{
LOG(critical, "Terminating due to unhandled 'glException'");
exitCode = -3;
}
// dx exception
catch (Light::dxException)
{
LOG(critical, "Terminating due to unhandled 'dxException'");
exitCode = -4;
}
delete application;
return exitCode;
}
#elif defined(LIGHT_PLATFORM_LINUX)
#include <LightEngine.hpp>
// to be defined in client project
extern Light::Application* Light::CreateApplication();
// #todo: use linux specific stuff
int main(int argc, char* argv[])
{
Light::Application* application = nullptr;
int exitCode = 0;
try
{
application = Light::CreateApplication();
ASSERT(application, "Light::Application is not intialized");
application->GameLoop();
}
// failed engine assertion
catch (Light::FailedAssertion)
{
LOG(critical, "Exitting due to unhandled 'FailedEngineAssertion'");
exitCode = -1;
}
// gl exception
catch (Light::glException)
{
LOG(critical, "main: exitting due to unhandled 'glException'");
exitCode = -3;
}
delete application;
return exitCode;
}
#endif

View file

@ -0,0 +1,149 @@
#pragma once
#ifndef LIGHT_DEBUG_TRAP_H
#define LIGHT_DEBUG_TRAP_H
#include "Base/Base.hpp"
// https://github.com/nemequ/portable-snippets/tree/master/debug-trap
#ifdef LIGHT_DIST
#ifdef _MSC_VER
#define LT_DEBUG_TRAP() \
LT_FILE_CRITICAL("DEBUG_TRAP REQUESTED AT: {}, FILE: {}, LINE: {}", \
__FUNCSIG__, __FILE__, __LINE__) // or __FUNCSIG__
#else
#define LT_DEBUG_TRAP() \
LT_FILE_CRITICAL("DEBUG_TRAP REQUESTED AT: {}", __PRETTY_FUNCTION__)
#endif
#endif
#if !defined(LT_DEBUG_TRAP) && defined(__has_builtin) && !defined(__ibmxl__)
#if __has_builtin(__builtin_debugtrap)
#define LT_DEBUG_TRAP() __builtin_debugtrap()
#elif __has_builtin(__debugbreak)
#define LT_DEBUG_TRAP() __debugbreak()
#endif
#endif
#if !defined(LT_DEBUG_TRAP)
#if defined(_MSC_VER) || defined(__INTEL_COMPILER)
#define LT_DEBUG_TRAP() __debugbreak()
#elif defined(__ARMCC_VERSION)
#define LT_DEBUG_TRAP() __breakpoint(42)
#elif defined(__ibmxl__) || defined(__xlC__)
#include <builtins.h>
#define LT_DEBUG_TRAP() __trap(42)
#elif defined(__DMC__) && defined(_M_IX86)
static inline void LT_DEBUG_TRAP(void)
{
__asm int 3h;
}
#elif defined(__i386__) || defined(__x86_64__)
static inline void LT_DEBUG_TRAP(void)
{
__asm__ __volatile__("int3");
}
#elif defined(__thumb__)
static inline void LT_DEBUG_TRAP(void)
{
__asm__ __volatile__(".inst 0xde01");
}
#elif defined(__aarch64__)
static inline void LT_DEBUG_TRAP(void)
{
__asm__ __volatile__(".inst 0xd4200000");
}
#elif defined(__arm__)
static inline void LT_DEBUG_TRAP(void)
{
__asm__ __volatile__(".inst 0xe7f001f0");
}
#elif defined(__alpha__) && !defined(__osf__)
static inline void LT_DEBUG_TRAP(void)
{
__asm__ __volatile__("bpt");
}
#elif defined(_54_)
static inline void LT_DEBUG_TRAP(void)
{
__asm__ __volatile__("ESTOP");
}
#elif defined(_55_)
static inline void LT_DEBUG_TRAP(void)
{
__asm__ __volatile__(
";\n .if (.MNEMONIC)\n ESTOP_1\n .else\n ESTOP_1()\n .endif\n NOP");
}
#elif defined(_64P_)
static inline void LT_DEBUG_TRAP(void)
{
__asm__ __volatile__("SWBP 0");
}
#elif defined(_6x_)
static inline void LT_DEBUG_TRAP(void)
{
__asm__ __volatile__("NOP\n .word 0x10000000");
}
#elif defined(__STDC_HOSTED__) && (__STDC_HOSTED__ == 0) && defined(__GNUC__)
#define LT_DEBUG_TRAP() __builtin_trap()
#else
#include <signal.h>
#if defined(SIGTRAP)
#define LT_DEBUG_TRAP() raise(SIGTRAP)
#else
#define LT_DEBUG_TRAP() raise(SIGABRT)
#endif
#endif
#endif
#if !defined(LT_DEBUG_TRAP)
#if !defined(LIGHT_IGNORE_UNDEFINED_DEBUG_TRAP)
#error \
"failed to define LT_BREAK, define LIGHT_IGNORE_UNDEFINED_DEBUG_TRAP in Config.h to disable this error"
#elif defined(LIGHT_DIST)
#ifdef _MSC_VER
#define LT_DEBUG_TRAP() \
LOG(critical, "DEBUG_TRAP REQUESTED AT: {}, FILE: {}, LINE: {}", \
__FUNCSIG__, __FILE__, __LINE__) // or __FUNCSIG__
#else
#define LT_DEBUG_TRAP() \
LOG(critical, "DEBUG_TRAP REQUESTED AT: {}", __PRETTY_FUNCTION__)
#endif
#else /* !defined(LIGHT_DIST) */
#ifdef _MSC_VER
#define LT_DEBUG_TRAP() \
LOG(critical, "DEBUG_TRAP REQUESTED AT: {}, FILE: {}, LINE: {}", \
__FUNCSIG__, __FILE__, __LINE__) // or __FUNCSIG__
#else
#define LT_DEBUG_TRAP() \
LOG(critical, "DEBUG_TRAP REQUESTED AT: {}", __PRETTY_FUNCTION__)
#endif
#endif
#endif
#endif

View file

@ -0,0 +1,6 @@
#include "Camera.hpp"
namespace Light {
}

View file

@ -0,0 +1,27 @@
#pragma once
#include "Base/Base.hpp"
#include <glm/glm.hpp>
namespace Light {
class Camera
{
private:
glm::vec4 m_BackgroundColor = glm::vec4(1.0f, 0.0f, 0.0f, 1.0f);
protected:
glm::mat4 m_Projection;
public:
Camera() = default;
inline const glm::mat4& GetProjection() const { return m_Projection; }
inline const glm::vec4& GetBackgroundColor() const { return m_BackgroundColor; }
inline void SetBackgroundColor(const glm::vec4& color) { m_BackgroundColor = color; }
};
} // namespace Light

View file

@ -0,0 +1,38 @@
#include "OrthographicCamera.hpp"
#include <glm/gtc/matrix_transform.hpp>
#include <glm/matrix.hpp>
namespace Light {
OrthographicCamera::OrthographicCamera(const glm::vec2& position, float aspectRatio, float zoomLevel, const glm::vec4& clearColor /* = glm::vec4(0.1f, 0.3f, 0.7f, 1.0f) */)
: m_Up(0.0f, 1.0f, 0.0f), m_Position(position), m_AspectRatio(aspectRatio), m_ZoomLevel(zoomLevel), m_ClearColor(clearColor)
{
}
void OrthographicCamera::CalculateView()
{
m_View = glm::lookAt(glm::vec3(m_Position, 100.0f), glm::vec3(m_Position, 0.0f), m_Up);
}
void OrthographicCamera::CalculateProjection()
{
m_Projection = glm::ortho(-m_ZoomLevel * m_AspectRatio,
+m_ZoomLevel * m_AspectRatio,
-m_ZoomLevel,
+m_ZoomLevel,
FLT_MAX, FLT_MIN);
}
void OrthographicCamera::OnResize(const glm::vec2& size)
{
m_AspectRatio = size.x / size.y;
CalculateProjection();
}
void OrthographicCamera::Move(const glm::vec2& position)
{
m_Position += position;
}
} // namespace Light

View file

@ -0,0 +1,41 @@
#pragma once
#include "Base/Base.hpp"
#include <glm/glm.hpp>
namespace Light {
class OrthographicCamera
{
private:
glm::vec2 m_Position;
float m_AspectRatio;
float m_ZoomLevel;
const glm::vec3 m_Up;
glm::mat4 m_Projection;
glm::mat4 m_View;
glm::vec4 m_ClearColor;
public:
OrthographicCamera(const glm::vec2& position, float aspectRatio, float zoomLevel, const glm::vec4& clearColor = glm::vec4(0.1f, 0.3f, 0.7f, 1.0f));
// CAMERA //
void CalculateView();
void CalculateProjection();
void OnResize(const glm::vec2& size);
inline const glm::mat4& GetView() const { return m_View; }
inline const glm::mat4& GetProjection() const { return m_Projection; }
inline const glm::vec4& GetClearColor() const { return m_ClearColor; }
// CAMERA_CONTROLLER //
void Move(const glm::vec2& position);
};
} // namespace Light

View file

@ -0,0 +1,81 @@
#include "SceneCamera.hpp"
#include <glm/gtc/matrix_transform.hpp>
namespace Light {
SceneCamera::SceneCamera()
: m_OrthographicSpecification { 1000.0f, -1.0f, 10000.0f }, m_PerspectiveSpecification { glm::radians(45.0f), 0.01f, 10000.0f }, m_AspectRatio(16.0f / 9.0f), m_ProjectionType(ProjectionType::Orthographic)
{
CalculateProjection();
}
void SceneCamera::SetViewportSize(unsigned int width, unsigned int height)
{
m_AspectRatio = width / (float)height;
CalculateProjection();
}
void SceneCamera::SetProjectionType(ProjectionType projectionType)
{
m_ProjectionType = projectionType;
CalculateProjection();
}
void SceneCamera::SetOrthographicSize(float size)
{
m_OrthographicSpecification.size = size;
CalculateProjection();
}
void SceneCamera::SetOrthographicFarPlane(float farPlane)
{
m_OrthographicSpecification.farPlane = farPlane;
CalculateProjection();
}
void SceneCamera::SetOrthographicNearPlane(float nearPlane)
{
m_OrthographicSpecification.nearPlane = nearPlane;
CalculateProjection();
}
void SceneCamera::SetPerspectiveVerticalFOV(float verticalFOV)
{
m_PerspectiveSpecification.verticalFOV = verticalFOV;
CalculateProjection();
}
void SceneCamera::SetPerspectiveFarPlane(float farPlane)
{
m_PerspectiveSpecification.farPlane = farPlane;
CalculateProjection();
}
void SceneCamera::SetPerspectiveNearPlane(float nearPlane)
{
m_PerspectiveSpecification.nearPlane = nearPlane;
CalculateProjection();
}
void SceneCamera::CalculateProjection()
{
if (m_ProjectionType == ProjectionType::Orthographic)
{
m_Projection = glm::ortho(-m_OrthographicSpecification.size * 0.5f * m_AspectRatio,
m_OrthographicSpecification.size * 0.5f * m_AspectRatio,
-m_OrthographicSpecification.size * 0.5f,
m_OrthographicSpecification.size * 0.5f,
m_OrthographicSpecification.farPlane,
m_OrthographicSpecification.nearPlane);
}
else // perspective
{
m_Projection = glm::perspective(m_PerspectiveSpecification.verticalFOV,
m_AspectRatio,
m_PerspectiveSpecification.nearPlane,
m_PerspectiveSpecification.farPlane);
}
}
} // namespace Light

View file

@ -0,0 +1,65 @@
#pragma once
#include "Base/Base.hpp"
#include "Camera.hpp"
namespace Light {
class SceneCamera: public Camera
{
public:
enum class ProjectionType
{
Orthographic = 0,
Perspetcive = 1
};
struct OrthographicSpecification // :#todo use this
{
float size;
float nearPlane, farPlane;
};
struct PerspectiveSpecification
{
float verticalFOV;
float nearPlane, farPlane;
};
private:
OrthographicSpecification m_OrthographicSpecification;
PerspectiveSpecification m_PerspectiveSpecification;
float m_AspectRatio;
ProjectionType m_ProjectionType;
public:
SceneCamera();
void SetViewportSize(unsigned int width, unsigned int height);
void SetProjectionType(ProjectionType projectionType);
void SetOrthographicSize(float size);
void SetOrthographicFarPlane(float farPlane);
void SetOrthographicNearPlane(float nearPlane);
void SetPerspectiveVerticalFOV(float verticalFov);
void SetPerspectiveFarPlane(float farPlane);
void SetPerspectiveNearPlane(float nearPlane);
inline float GetOrthographicSize() const { return m_OrthographicSpecification.size; }
inline float GetOrthographicFarPlane() const { return m_OrthographicSpecification.farPlane; }
inline float GetOrthographicNearPlane() const { return m_OrthographicSpecification.nearPlane; }
inline float GetPerspectiveVerticalFOV() const { return m_PerspectiveSpecification.verticalFOV; }
inline float GetPerspectiveFarPlane() const { return m_PerspectiveSpecification.farPlane; }
inline float GetPerspectiveNearPlane() const { return m_PerspectiveSpecification.nearPlane; }
inline ProjectionType GetProjectionType() const { return m_ProjectionType; }
private:
void CalculateProjection();
};
} // namespace Light

View file

@ -0,0 +1,148 @@
#include "Application.hpp"
#include "Debug/Instrumentor.hpp"
#include "Events/Event.hpp"
#include "Graphics/GraphicsContext.hpp"
#include "Graphics/RenderCommand.hpp"
#include "Graphics/Renderer.hpp"
#include "Layer/Layer.hpp"
#include "Time/Timer.hpp"
#include "UserInterface/UserInterface.hpp"
#include "Window.hpp"
namespace Light {
Application* Application::s_Context = nullptr;
Application::Application(std::string execName, std::vector<std::string> args)
: m_Instrumentor(nullptr), m_LayerStack(nullptr), m_Input(nullptr), m_Window(nullptr)
{
ASSERT(!s_Context, "Repeated singleton construction");
s_Context = this;
m_Logger = Logger::Create();
LogDebugData();
m_Instrumentor = Instrumentor::Create();
m_Instrumentor->BeginSession("Logs/ProfileResults_Startup.json");
m_LayerStack = LayerStack::Create();
m_Input = Input::Create();
m_ResourceManager = ResourceManager::Create();
m_Window = Window::Create(std::bind(&Application::OnEvent, this, std::placeholders::_1));
}
Application::~Application()
{
LOG(trace, "Application::~Application()");
m_Instrumentor->EndSession(); // ProfileResults_Termination //
}
void Application::GameLoop()
{
// check
ASSERT(!m_LayerStack->IsEmpty(), "LayerStack is empty");
// log debug data
m_Logger->LogDebugData();
m_Window->GetGfxContext()->LogDebugData();
m_Window->GetGfxContext()->GetUserInterface()->LogDebugData();
// reveal window
m_Window->SetVisibility(true);
m_Instrumentor->EndSession(); // ProfileResults_GameLoop //
m_Instrumentor->BeginSession("Logs/ProfileResults_GameLoop.json");
/* game loop */
DeltaTimer deltaTimer;
while (!m_Window->IsClosed())
{
{
// update layers
LT_PROFILE_SCOPE("GameLoop::Update");
for (auto it = m_LayerStack->begin(); it != m_LayerStack->end(); it++)
(*it)->OnUpdate(deltaTimer.GetDeltaTime());
}
{
// render layers
LT_PROFILE_SCOPE("GameLoop::Render");
m_Window->GetGfxContext()->GetRenderer()->BeginFrame();
for (auto it = m_LayerStack->begin(); it != m_LayerStack->end(); it++)
(*it)->OnRender();
m_Window->GetGfxContext()->GetRenderer()->EndFrame();
}
{
// render user interface
LT_PROFILE_SCOPE("GameLoop::UserInterface");
m_Window->GetGfxContext()->GetUserInterface()->Begin();
for (auto it = m_LayerStack->begin(); it != m_LayerStack->end(); it++)
(*it)->OnUserInterfaceUpdate();
m_Window->GetGfxContext()->GetUserInterface()->End();
}
{
// poll events
LT_PROFILE_SCOPE("GameLoop::Events");
m_Window->PollEvents();
}
/// update delta time
deltaTimer.Update();
}
m_Instrumentor->EndSession(); // ProfileResults_GameLoop //
m_Instrumentor->BeginSession("Logs/ProfileResults_Termination.json");
}
void Application::Quit()
{
s_Context->m_Window->Close();
}
void Application::OnEvent(const Event& event)
{
// window
if (event.HasCategory(WindowEventCategory))
{
m_Window->OnEvent(event);
if (event.GetEventType() == EventType::WindowResized)
m_Window->GetGfxContext()->GetRenderer()->OnWindowResize((const WindowResizedEvent&)event);
}
// input
if (event.HasCategory(InputEventCategory))
{
m_Input->OnEvent(event);
if (!m_Input->IsReceivingGameEvents()) // return if the event is an input event and 'Input' has disabled the game events
return;
}
/* layers */
for (auto it = m_LayerStack->rbegin(); it != m_LayerStack->rend(); it++)
if ((*it)->OnEvent(event))
return;
}
void Application::LogDebugData()
{
// #todo: log more information
LOG(info, "________________________________________");
LOG(info, "Platform::");
LOG(info, " OS: {}", LT_BUILD_PLATFORM);
LOG(info, " DIR: {}", std::filesystem::current_path().generic_string());
LOG(info, "________________________________________");
}
} // namespace Light

View file

@ -0,0 +1,54 @@
#pragma once
#include "Base/Base.hpp"
#include "Debug/Instrumentor.hpp"
#include "Input/Input.hpp"
#include "Layer/LayerStack.hpp"
#include "Utility/ResourceManager.hpp"
namespace Light {
class Window;
class Event;
class Instrumentor;
class Application /* singleton */
{
private:
static Application* s_Context;
private:
Scope<Logger> m_Logger;
Scope<Instrumentor> m_Instrumentor;
Scope<LayerStack> m_LayerStack;
Scope<Input> m_Input;
Scope<ResourceManager> m_ResourceManager;
protected:
Scope<Window> m_Window;
public:
Application(const Application&) = delete;
Application& operator=(const Application&) = delete;
virtual ~Application();
void GameLoop();
// To be defined in client project
static void Quit();
protected:
Application(std::string execName, std::vector<std::string> args);
private:
void OnEvent(const Event& event);
void LogDebugData();
};
extern Application* CreateApplication(std::string execName, std::vector<std::string> args);
} // namespace Light

View file

@ -0,0 +1,14 @@
#include "UUID.hpp"
#include "ltpch.hpp"
namespace Light {
std::mt19937_64 UUID::s_Engine = std::mt19937_64(std::random_device()());
std::uniform_int_distribution<uint64_t> UUID::s_UniformDistribution;
UUID::UUID(uint64_t uuid /* = -1 */)
: m_UUID(uuid == -1 ? s_UniformDistribution(s_Engine) : uuid)
{
}
} // namespace Light

View file

@ -0,0 +1,35 @@
#pragma once
#include <random>
namespace Light {
class UUID
{
private:
static std::mt19937_64 s_Engine;
static std::uniform_int_distribution<uint64_t> s_UniformDistribution;
private:
uint64_t m_UUID;
public:
UUID(uint64_t uuid = -1);
operator uint64_t() const { return m_UUID; }
};
}
namespace std {
template <>
struct hash<Light::UUID>
{
std::size_t operator()(const Light::UUID& uuid) const
{
return hash<uint64_t>()(static_cast<uint64_t>(uuid));
}
};
}

View file

@ -0,0 +1,73 @@
#pragma once
#include "Base/Base.hpp"
#include <glm/glm.hpp>
namespace Light {
class Event;
class GraphicsContext;
struct WindowProperties
{
std::string title;
glm::uvec2 size;
bool vsync, visible;
};
class Window
{
protected:
Scope<GraphicsContext> m_GraphicsContext;
WindowProperties m_Properties;
bool b_Closed;
public:
static Scope<Window> Create(std::function<void(Event&)> callback);
Window()
: m_GraphicsContext(nullptr), m_Properties {}, b_Closed(false)
{
}
Window(const Window&) = delete;
Window& operator=(const Window&) = delete;
virtual ~Window() = default;
/* events */
virtual void PollEvents() = 0;
virtual void OnEvent(const Event& event) = 0;
//======================================== SETTERS ========================================//
virtual void SetProperties(const WindowProperties& properties, bool affectVisibility = false) = 0;
virtual void SetTitle(const std::string& title) = 0;
virtual void SetSize(const glm::uvec2& size, bool additive = false) = 0; // pass 0 for width or height for single dimension resizing
inline void Close() { b_Closed = true; }
virtual void SetVSync(bool vsync, bool toggle = false) = 0;
virtual void SetVisibility(bool visible, bool toggle = false) = 0;
//======================================== SETTERS ========================================//
//============================== GETTERS ==============================//
inline GraphicsContext* GetGfxContext() const { return m_GraphicsContext.get(); }
inline const WindowProperties& GetProperties() const { return m_Properties; }
inline const std::string& GetTitle() const { return m_Properties.title; }
inline const glm::uvec2& GetSize() const { return m_Properties.size; }
inline bool IsClosed() const { return b_Closed; }
inline bool IsVSync() const { return m_Properties.vsync; }
inline bool IsVisible() const { return m_Properties.visible; }
//============================== GETTERS ==============================//
protected:
};
} // namespace Light

View file

@ -0,0 +1,55 @@
#include "Exceptions.hpp"
#include "Utility/Stringifier.hpp"
#include <glad/glad.h>
#ifdef LIGHT_PLATFORM_WINDOWS
#include <Windows.h>
#endif
namespace Light {
FailedAssertion::FailedAssertion(const char* file, int line)
{
LOG(critical, "Assertion failed in: {} (line {})", file, line);
}
glException::glException(unsigned int source, unsigned int type, unsigned int id, const char* msg)
{
// #todo: improve
LOG(critical, "________________________________________");
LOG(critical, "glException::glException::");
LOG(critical, " Severity: {}", Stringifier::glDebugMsgSeverity(GL_DEBUG_SEVERITY_HIGH));
LOG(critical, " Source : {}", Stringifier::glDebugMsgSource(source));
LOG(critical, " Type : {}", Stringifier::glDebugMsgType(type));
LOG(critical, " ID : {}", id);
// LOG(critical, " Vendor : {}", glGetString(GL_VENDOR));
// LOG(critical, " Renderer: {}", glGetString(GL_RENDERER));
// LOG(critical, " Version : {}", glGetString(GL_VERSION));
// LOG(critical, " critical, SVersion: {}", glGetString(GL_SHADING_LANGUAGE_VERSION));
LOG(critical, " {}", msg);
LOG(critical, "________________________________________");
}
#ifdef LIGHT_PLATFORM_WINDOWS
dxException::dxException(long hr, const char* file, int line)
{
char* message;
FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
nullptr, hr,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPSTR)(&message), NULL, nullptr);
// #todo: improve
LOG(critical, "________________________________________");
LOG(critical, "dxException::dxException::");
LOG(critical, " File: {}, Line: {}", file, line);
LOG(critical, " {}", message);
LOG(critical, "________________________________________");
LocalFree(message);
}
#endif
} // namespace Light

View file

@ -0,0 +1,33 @@
#pragma once
#define DXC(x) DXC_NO_REDIFINITION(x, __LINE__)
#define DXC_NO_REDIFINITION(x, line) DXC_NO_REDIFINITION2(x, line)
#define DXC_NO_REDIFINITION2(x, line) \
HRESULT hr##line; \
if (FAILED(hr##line = x)) \
throw dxException(hr##line, __FILE__, line)
namespace Light {
struct FailedAssertion: std::exception
{
FailedAssertion(const char* file, int line);
};
// OpenGL
struct glException: std::exception
{
glException(unsigned int source, unsigned int type, unsigned int id, const char* msg);
};
#ifdef LIGHT_PLATFORM_WINDOWS
// DirectX
struct dxException: std::exception
{
dxException(long hr, const char* file, int line);
};
#endif
} // namespace Light

View file

@ -0,0 +1,72 @@
#include "Instrumentor.hpp"
namespace Light {
Instrumentor* Instrumentor::s_Context = nullptr;
Scope<Instrumentor> Instrumentor::Create()
{
return MakeScope<Instrumentor>(new Instrumentor);
}
Instrumentor::Instrumentor()
: m_CurrentSessionCount(0u)
{
// #todo: maintenance
ASSERT(!s_Context, "An instance of 'Instrumentor' already exists, do not construct this class!");
s_Context = this;
}
void Instrumentor::BeginSessionImpl(const std::string& outputPath)
{
std::filesystem::create_directory(outputPath.substr(0, outputPath.find_last_of('/') + 1));
m_OutputFileStream.open(outputPath);
m_OutputFileStream << "{\"traceEvents\":[";
}
void Instrumentor::EndSessionImpl()
{
if (m_CurrentSessionCount == 0u)
LOG(warn, "0 profiling for the ended session");
m_CurrentSessionCount = 0u;
m_OutputFileStream << "]}";
m_OutputFileStream.flush();
m_OutputFileStream.close();
}
void Instrumentor::SubmitScopeProfileImpl(const ScopeProfileResult& profileResult)
{
if (m_CurrentSessionCount++ == 0u)
m_OutputFileStream << "{";
else
m_OutputFileStream << ",{";
m_OutputFileStream << "\"name\":\"" << profileResult.name << "\",";
m_OutputFileStream << "\"cat\": \"scope\",";
m_OutputFileStream << "\"ph\": \"X\",";
m_OutputFileStream << "\"ts\":" << profileResult.start << ",";
m_OutputFileStream << "\"dur\":" << profileResult.duration << ",";
m_OutputFileStream << "\"pid\":0,";
m_OutputFileStream << "\"tid\":" << profileResult.threadID << "";
m_OutputFileStream << "}";
}
InstrumentorTimer::InstrumentorTimer(const std::string& scopeName)
: m_Result({ scopeName, 0, 0, 0 }), m_Start(std::chrono::steady_clock::now())
{
}
InstrumentorTimer::~InstrumentorTimer()
{
auto end = std::chrono::steady_clock::now();
m_Result.start = std::chrono::time_point_cast<std::chrono::microseconds>(m_Start).time_since_epoch().count();
m_Result.duration = std::chrono::time_point_cast<std::chrono::microseconds>(end).time_since_epoch().count() - m_Result.start;
Instrumentor::SubmitScopeProfile(m_Result);
}
} // namespace Light

View file

@ -0,0 +1,70 @@
#pragma once
#include "Base/Base.hpp"
#include <chrono>
#include <fstream>
#include <ostream>
namespace Light {
struct ScopeProfileResult
{
std::string name;
long long start, duration;
uint32_t threadID;
};
// #todo: add event categories
// #todo: use ofstream in a separate thread
class Instrumentor /* singleton */
{
private:
static Instrumentor* s_Context;
private:
std::ofstream m_OutputFileStream;
unsigned int m_CurrentSessionCount;
public:
static Scope<Instrumentor> Create();
static inline void BeginSession(const std::string& outputPath) { s_Context->BeginSessionImpl(outputPath); }
static inline void EndSession() { s_Context->EndSessionImpl(); }
static inline void SubmitScopeProfile(const ScopeProfileResult& profileResult) { s_Context->SubmitScopeProfileImpl(profileResult); }
private:
Instrumentor();
void BeginSessionImpl(const std::string& outputPath);
void EndSessionImpl();
void SubmitScopeProfileImpl(const ScopeProfileResult& profileResult);
};
class InstrumentorTimer
{
private:
ScopeProfileResult m_Result;
std::chrono::time_point<std::chrono::steady_clock> m_Start;
public:
InstrumentorTimer(const std::string& scopeName);
~InstrumentorTimer();
};
} // namespace Light
/* scope */
#define LT_PROFILE_SCOPE(name) LT_PROFILE_SCOPE_NO_REDIFINITION(name, __LINE__)
#define LT_PROFILE_SCOPE_NO_REDIFINITION(name, line) LT_PROFILE_SCOPE_NO_REDIFINITION2(name, line)
#define LT_PROFILE_SCOPE_NO_REDIFINITION2(name, line) InstrumentorTimer timer##line(name)
/* function */
#define LT_PROFILE_FUNCTION LT_PROFILE_SCOPE(__FUNCSIG__)
/* session */
#define LT_PROFILE_BEGIN_SESSION(outputPath) ::Light::Instrumentor::BeginSession(outputPath)
#define LT_PROFILE_END_SESSION() ::Light::Instrumentor::EndSession()

View file

@ -0,0 +1,53 @@
#include "Logger.hpp"
#include <spdlog/sinks/basic_file_sink.h>
#include <spdlog/sinks/stdout_color_sinks.h>
namespace Light {
Logger* Logger::s_Context = nullptr;
Scope<Logger> Logger::Create()
{
return MakeScope<Logger>(new Logger());
}
Logger::Logger()
: m_EngineLogger(nullptr), m_FileLogger(nullptr), m_LogFilePath(LT_LOG_FILE_LOCATION)
{
ASSERT(!s_Context, "An instance of 'Logger' already exists, do not construct this class!");
s_Context = this;
// set spdlog pattern
// create loggers
spdlog::set_pattern("%^[%H:%M:%S]%g@%! ==> %v%$");
#ifndef LIGHT_DIST
spdlog::set_pattern("%^[%H:%M:%S]%! ==> %v%$");
m_EngineLogger = spdlog::stdout_color_mt("Engine");
#endif
m_FileLogger = spdlog::basic_logger_mt("File", m_LogFilePath);
m_FileLogger->set_pattern("%^[%M:%S:%e] <%l>: %v%$");
// set level
#if defined(LIGHT_DEBUG)
m_EngineLogger->set_level(spdlog::level::trace);
m_ClientLogger->set_level(spdlog::level::trace);
#elif defined(LIGHT_RELEASE)
s_EngineLogger->set_level(spdlog::level::info);
s_ClientLogger->set_level(spdlog::level::info);
#endif
}
void Logger::LogDebugData()
{
// #todo: improve
LOG(info, "________________________________________");
LOG(info, "Logger::");
LOG(info, " EngineLevel : {}", Stringifier::spdlogLevel(m_EngineLogger->level()));
LOG(info, " FileLevel : {}", Stringifier::spdlogLevel(m_FileLogger->level()));
LOG(info, " DefaultLevel: {}", Stringifier::spdlogLevel(spdlog::get_level()));
LOG(info, "________________________________________");
}
} // namespace Light

View file

@ -0,0 +1,43 @@
#pragma once
#ifndef LIGHT_LOGGER_H
#define LIGHT_LOGGER_H
#include "Base/Base.hpp"
#include <spdlog/spdlog.h>
#define LT_LOG_FILE_LOCATION "Logs/Logger.txt"
#ifndef LIGHT_DIST
#define LOG(logLevel, ...) SPDLOG_LOGGER_CALL(::Light::Logger::GetEngineLogger(), spdlog::level::logLevel, __VA_ARGS__)
#else
#define LOG(logLevel, ...) SPDLOG_LOGGER_CALL(::Light::Logger::GetFileLogger(), spdlog::level::logLevel, __VA_ARGS__)
#endif
namespace Light {
// #todo: extend
class Logger /* singleton */
{
private:
static Logger* s_Context;
private:
Ref<spdlog::logger> m_EngineLogger, m_FileLogger;
std::string m_LogFilePath;
public:
static Scope<Logger> Create();
static inline Ref<spdlog::logger> GetEngineLogger() { return s_Context->m_EngineLogger; }
static inline Ref<spdlog::logger> GetFileLogger() { return s_Context->m_FileLogger; }
void LogDebugData();
private:
Logger();
};
} // namespace Light
#endif

View file

@ -0,0 +1,33 @@
#pragma once
#include "Base/Base.hpp"
#include "Event.hpp"
#include <sstream>
namespace Light {
class SetCharEvent: public Event
{
private:
const unsigned int m_Character;
public:
SetCharEvent(unsigned int character)
: m_Character(character)
{
}
inline int GetCharacter() const { return m_Character; }
virtual std::string GetInfoLog() const override
{
std::stringstream ss;
ss << "CharSet: " << m_Character;
return ss.str();
}
EVENT_TYPE(SetChar)
EVENT_CATEGORY(InputEventCategory | KeyboardEventCategory)
};
} // namespace Light

View file

@ -0,0 +1,57 @@
#pragma once
#include "Base/Base.hpp"
namespace Light {
enum class EventType
{
None = 0,
// input
MouseMoved,
WheelScrolled,
ButtonPressed,
ButtonReleased,
KeyPressed,
KeyRepeated,
KeyReleased,
SetChar,
// window
WindowMoved,
WindowResized,
WindowClosed,
WindowLostFocus,
WindowGainFocus,
};
enum EventCategory
{
None = 0,
WindowEventCategory = BIT(0),
InputEventCategory = BIT(1),
KeyboardEventCategory = BIT(2),
MouseEventCategory = BIT(3),
};
#define EVENT_TYPE(type) \
EventType GetEventType() const override { return ::Light::EventType::type; }
#define EVENT_CATEGORY(eCategory) \
inline bool HasCategory(EventCategory category) const override { return (eCategory)&category; }
class Event
{
public:
virtual EventType GetEventType() const = 0;
virtual std::string GetInfoLog() const = 0;
virtual bool HasCategory(EventCategory category) const = 0;
friend std::ostream& operator<<(std::ostream& os, const Event& e)
{
return os << e.GetInfoLog();
}
};
} // namespace Light

View file

@ -0,0 +1,79 @@
#pragma once
#include "Base/Base.hpp"
#include "Event.hpp"
#include <sstream>
namespace Light {
class KeyPressedEvent: public Event
{
private:
const int m_Key;
public:
KeyPressedEvent(int key)
: m_Key(key)
{
}
inline int GetKey() const { return m_Key; }
virtual std::string GetInfoLog() const override
{
std::stringstream ss;
ss << "KeyPressed: " << m_Key;
return ss.str();
}
EVENT_TYPE(KeyPressed)
EVENT_CATEGORY(InputEventCategory | KeyboardEventCategory)
};
class KeyRepeatEvent: public Event
{
private:
const int m_Key;
public:
KeyRepeatEvent(int key)
: m_Key(key)
{
}
inline int GetKey() const { return m_Key; }
virtual std::string GetInfoLog() const override
{
std::stringstream ss;
ss << "KeyRepeated: " << m_Key;
return ss.str();
}
EVENT_TYPE(KeyRepeated)
EVENT_CATEGORY(InputEventCategory | KeyboardEventCategory)
};
class KeyReleasedEvent: public Event
{
private:
const int m_Key;
public:
KeyReleasedEvent(int key)
: m_Key(key)
{
}
inline int GetKey() const { return m_Key; }
virtual std::string GetInfoLog() const override
{
std::stringstream ss;
ss << "KeyReleased: " << m_Key;
return ss.str();
}
EVENT_TYPE(KeyReleased)
EVENT_CATEGORY(InputEventCategory | KeyboardEventCategory)
};
} // namespace Light

View file

@ -0,0 +1,106 @@
#pragma once
#include "Base/Base.hpp"
#include "Event.hpp"
#include <glm/glm.hpp>
#include <sstream>
namespace Light {
class MouseMovedEvent: public Event
{
private:
const glm::vec2 m_Position;
public:
MouseMovedEvent(float x, float y)
: m_Position(x, y)
{
}
inline const glm::vec2& GetPosition() const { return m_Position; }
inline float GetX() const { return m_Position.x; }
inline float GetY() const { return m_Position.y; }
virtual std::string GetInfoLog() const override
{
std::stringstream ss;
ss << "MouseMoved: " << m_Position.x << ", " << m_Position.y;
return ss.str();
}
EVENT_TYPE(MouseMoved)
EVENT_CATEGORY(InputEventCategory | MouseEventCategory)
};
class WheelScrolledEvent: public Event
{
private:
const float m_Offset;
public:
WheelScrolledEvent(float offset)
: m_Offset(offset)
{
}
inline float GetOffset() const { return m_Offset; }
virtual std::string GetInfoLog() const override
{
std::stringstream ss;
ss << "WheelScrolled: " << m_Offset;
return ss.str();
}
EVENT_TYPE(WheelScrolled)
EVENT_CATEGORY(InputEventCategory | MouseEventCategory)
};
class ButtonPressedEvent: public Event
{
private:
const int m_Button;
public:
ButtonPressedEvent(int button)
: m_Button(button)
{
}
inline int GetButton() const { return m_Button; }
virtual std::string GetInfoLog() const override
{
std::stringstream ss;
ss << "ButtonPressed: " << m_Button;
return ss.str();
}
EVENT_TYPE(ButtonPressed)
EVENT_CATEGORY(InputEventCategory | MouseEventCategory)
};
class ButtonReleasedEvent: public Event
{
private:
const int m_Button;
public:
ButtonReleasedEvent(int button)
: m_Button(button)
{
}
inline int GetButton() const { return m_Button; }
virtual std::string GetInfoLog() const override
{
std::stringstream ss;
ss << "ButtonReleased: " << m_Button;
return ss.str();
}
EVENT_TYPE(ButtonReleased)
EVENT_CATEGORY(InputEventCategory | MouseEventCategory)
};
} // namespace Light

View file

@ -0,0 +1,91 @@
#pragma once
#include "Base/Base.hpp"
#include "Event.hpp"
#include <glm/glm.hpp>
#include <sstream>
namespace Light {
class WindowClosedEvent: public Event
{
public:
virtual std::string GetInfoLog() const override
{
return "WindowClosedEvent";
}
EVENT_TYPE(WindowClosed)
EVENT_CATEGORY(WindowEventCategory)
};
class WindowMovedEvent: public Event
{
private:
const glm::ivec2 m_Position;
public:
WindowMovedEvent(int x, int y)
: m_Position(x, y)
{
}
const glm::ivec2& GetPosition() const { return m_Position; }
virtual std::string GetInfoLog() const override
{
std::stringstream ss;
ss << "WindwoMoved: " << m_Position.x << ", " << m_Position.y;
return ss.str();
;
}
EVENT_TYPE(WindowMoved)
EVENT_CATEGORY(WindowEventCategory)
};
class WindowResizedEvent: public Event
{
private:
const glm::uvec2 m_Size;
public:
WindowResizedEvent(unsigned int width, unsigned int height)
: m_Size(width, height)
{
}
const glm::uvec2& GetSize() const { return m_Size; }
virtual std::string GetInfoLog() const override
{
std::stringstream ss;
ss << "WindowResized: " << m_Size.x << ", " << m_Size.y;
return ss.str();
}
EVENT_TYPE(WindowResized)
EVENT_CATEGORY(WindowEventCategory)
};
class WindowLostFocusEvent: public Event
{
public:
virtual std::string GetInfoLog() const override
{
return "WindowLostFocus";
}
EVENT_TYPE(WindowLostFocus)
EVENT_CATEGORY(WindowEventCategory)
};
class WindowGainFocusEvent: public Event
{
public:
virtual std::string GetInfoLog() const override
{
return "WindowGainFocus";
}
EVENT_TYPE(WindowGainFocus)
EVENT_CATEGORY(WindowEventCategory)
};
} // namespace Light

View file

@ -0,0 +1,29 @@
#include "Blender.hpp"
#include "OpenGL/glBlender.hpp"
#ifdef LIGHT_PLATFORM_WINDOWS
#include "DirectX/dxBlender.hpp"
#include "DirectX/dxSharedContext.hpp"
#endif
#include "GraphicsContext.hpp"
namespace Light {
Scope<Blender> Blender::Create(Ref<SharedContext> sharedContext)
{
switch (GraphicsContext::GetGraphicsAPI())
{
case GraphicsAPI::OpenGL:
return CreateScope<glBlender>();
case GraphicsAPI::DirectX: LT_WIN(
return CreateScope<dxBlender>(std::static_pointer_cast<dxSharedContext>(sharedContext));)
default:
ASSERT(false, "Invalid/unsupported 'GraphicsAPI' {}", static_cast<uint32_t>(GraphicsContext::GetGraphicsAPI()));
}
}
} // namespace Light

View file

@ -0,0 +1,49 @@
#pragma once
#include "Base/Base.hpp"
namespace Light {
class SharedContext;
enum class BlendFactor : uint8_t
{
// constants
ZERO,
ONE,
// source
SRC_COLOR,
INVERSE_SRC_COLOR,
SRC_ALPHA,
INVERSE_SRC_ALPHA,
// destination
DST_COLOR,
INVERSE_DST_COLOR,
DST_ALPHA,
INVERSE_DST_ALPHA,
// source1
SRC1_COLOR,
INVERSE_SRC1_COLOR,
SRC1_ALPHA,
INVERSE_SRC1_ALPHA,
};
class Blender
{
public:
static Scope<Blender> Create(Ref<SharedContext> sharedContext);
virtual void Enable(BlendFactor srcFactor, BlendFactor dstFactor) = 0;
virtual void Disable() = 0;
protected:
Blender() = default;
};
} // namespace Light

View file

@ -0,0 +1,69 @@
#include "Buffers.hpp"
#include "OpenGL/glBuffers.hpp"
#include "SharedContext.hpp"
#ifdef LIGHT_PLATFORM_WINDOWS
#include "DirectX/dxBuffers.hpp"
#include "DirectX/dxSharedContext.hpp"
#endif
#include "GraphicsContext.hpp"
namespace Light {
//================================================== CONSTANT_BUFFER ==================================================//
Scope<ConstantBuffer> ConstantBuffer::Create(ConstantBufferIndex index, unsigned int size, Ref<SharedContext> sharedContext)
{
switch (GraphicsContext::GetGraphicsAPI())
{
case GraphicsAPI::OpenGL:
return CreateScope<glConstantBuffer>(index, size);
case GraphicsAPI::DirectX: LT_WIN(
return CreateScope<dxConstantBuffer>(index, size, std::static_pointer_cast<dxSharedContext>(sharedContext));)
default:
ASSERT(false, "Invalid/unsupported 'GraphicsAPI' {}", static_cast<uint32_t>(GraphicsContext::GetGraphicsAPI()));
return nullptr;
}
}
//================================================== CONSTANT_BUFFER ==================================================//
//================================================== VERTEX_BUFFER ==================================================//
Ref<VertexBuffer> VertexBuffer::Create(float* vertices, unsigned int stride, unsigned int count, Ref<SharedContext> sharedContext)
{
switch (GraphicsContext::GetGraphicsAPI())
{
case GraphicsAPI::OpenGL:
return CreateRef<glVertexBuffer>(vertices, stride, count);
case GraphicsAPI::DirectX: LT_WIN(
return CreateRef<dxVertexBuffer>(vertices, stride, count, std::static_pointer_cast<dxSharedContext>(sharedContext));)
default:
ASSERT(false, "Invalid/unsupported 'GraphicsAPI' {}", static_cast<uint32_t>(GraphicsContext::GetGraphicsAPI()));
return nullptr;
}
}
//================================================== VERTEX_BUFFER ==================================================//
//======================================== INDEX_BUFFER ========================================//
Ref<IndexBuffer> IndexBuffer::Create(unsigned int* indices, unsigned int count, Ref<SharedContext> sharedContext)
{
switch (GraphicsContext::GetGraphicsAPI())
{
case GraphicsAPI::OpenGL:
return CreateRef<glIndexBuffer>(indices, count);
case GraphicsAPI::DirectX: LT_WIN(
return CreateRef<dxIndexBuffer>(indices, count, std::dynamic_pointer_cast<dxSharedContext>(sharedContext));)
default:
ASSERT(false, "Invalid/unsupported 'GraphicsAPI' {}", static_cast<uint32_t>(GraphicsContext::GetGraphicsAPI()));
return nullptr;
}
}
//======================================== INDEX_BUFFER ========================================//
} // namespace Light

View file

@ -0,0 +1,62 @@
#pragma once
#include "Base/Base.hpp"
namespace Light {
class SharedContext;
enum class ConstantBufferIndex
{
ViewProjection = 0u
};
//========== CONSTANT_BUFFER ==========//
class ConstantBuffer
{
public:
static Scope<ConstantBuffer> Create(ConstantBufferIndex index, unsigned int size, Ref<SharedContext> sharedContext);
virtual void* Map() = 0;
virtual void UnMap() = 0;
virtual void Bind() = 0;
protected:
ConstantBuffer() = default;
};
//========== VERTEX_BUFFER ==========//
class VertexBuffer
{
public:
static Ref<VertexBuffer> Create(float* vertices, unsigned int stride, unsigned int count, Ref<SharedContext> sharedContext);
virtual ~VertexBuffer() = default;
virtual void* Map() = 0;
virtual void UnMap() = 0;
virtual void Bind() = 0;
virtual void UnBind() = 0;
protected:
VertexBuffer() = default;
};
//========== INDEX_BUFFER ==========//
class IndexBuffer
{
public:
static Ref<IndexBuffer> Create(unsigned int* indices, unsigned int count, Ref<SharedContext> sharedContext);
virtual ~IndexBuffer() = default;
virtual void Bind() = 0;
virtual void UnBind() = 0;
protected:
IndexBuffer() = default;
};
} // namespace Light

View file

@ -0,0 +1,30 @@
#include "Framebuffer.hpp"
#include "OpenGL/glFramebuffer.hpp"
#ifdef LIGHT_PLATFORM_WINDOWS
#include "DirectX/dxFramebuffer.hpp"
#include "DirectX/dxSharedContext.hpp"
#endif
#include "GraphicsContext.hpp"
namespace Light {
Ref<Framebuffer> Framebuffer::Create(const FramebufferSpecification& specification, Ref<SharedContext> sharedContext)
{
switch (GraphicsContext::GetGraphicsAPI())
{
case GraphicsAPI::OpenGL:
return CreateRef<glFramebuffer>(specification);
case GraphicsAPI::DirectX: LT_WIN(
return CreateRef<dxFramebuffer>(specification, std::static_pointer_cast<dxSharedContext>(sharedContext));)
default:
ASSERT(false, "Invalid/unsupported 'GraphicsAPI' {}", static_cast<uint32_t>(GraphicsContext::GetGraphicsAPI()));
return nullptr;
}
}
} // namespace Light

View file

@ -0,0 +1,33 @@
#pragma once
#include "Base/Base.hpp"
#include <glm/glm.hpp>
namespace Light {
class SharedContext;
struct FramebufferSpecification
{
unsigned int width, height;
unsigned int samples = 1;
};
class Framebuffer
{
public:
static Ref<Framebuffer> Create(const FramebufferSpecification& specification, Ref<SharedContext> sharedContext);
virtual void BindAsTarget(const glm::vec4& clearColor) = 0;
virtual void BindAsResource() = 0;
virtual void Resize(const glm::uvec2& size) = 0;
virtual void* GetColorAttachment() = 0;
protected:
Framebuffer() = default;
};
} // namespace Light

View file

@ -0,0 +1,79 @@
#include "GraphicsContext.hpp"
#include "OpenGL/glGraphicsContext.hpp"
#ifdef LIGHT_PLATFORM_WINDOWS
#include "DirectX/dxGraphicsContext.hpp"
#include "DirectX/dxSharedContext.hpp"
#endif
#include "Blender.hpp" // required for forward declaration
#include "Buffers.hpp" // required for forward declaration
#include "RenderCommand.hpp" // required for forward declaration
#include "Renderer.hpp" // required for forward declaration
#include "UserInterface/UserInterface.hpp" // required for forward declaration
#include "Utility/ResourceManager.hpp" // required for forward declaration
namespace Light {
GraphicsContext* GraphicsContext::s_Context = nullptr;
GraphicsContext::~GraphicsContext()
{
}
Scope<GraphicsContext> GraphicsContext::Create(GraphicsAPI api, GLFWwindow* windowHandle)
{
// terminate 'GraphicsContext' dependent classes
if (s_Context)
{
s_Context->m_Renderer.reset();
s_Context->m_UserInterface.reset();
delete s_Context;
}
// determine the default api
if (api == GraphicsAPI::Default)
{
#if defined(LIGHT_PLATFORM_WINDOWS)
api = GraphicsAPI::DirectX;
#elif defined(LIGHT_PLATFORM_LINUX)
api = GraphicsAPI::OpenGL;
#elif defined(LIGHT_PLATFORM_MAC)
api = GraphicsAPI::OpenGL;
#endif
}
// create gfx context
Scope<GraphicsContext> scopeGfx;
switch (api)
{
// opengl
case GraphicsAPI::OpenGL:
scopeGfx = CreateScope<glGraphicsContext>(windowHandle);
s_Context = scopeGfx.get();
break;
// directx
case GraphicsAPI::DirectX: LT_WIN(
scopeGfx = CreateScope<dxGraphicsContext>(windowHandle);
s_Context = scopeGfx.get();
break;)
default:
ASSERT(false, "Invalid/unsupported 'GraphicsAPI' {}", Stringifier::GraphicsAPIToString(api));
return nullptr;
}
// create 'GraphicsContext' dependent classes
s_Context->m_UserInterface = UserInterface::Create(windowHandle, s_Context->m_SharedContext);
s_Context->m_Renderer = Renderer::Create(windowHandle, s_Context->m_SharedContext);
// check
ASSERT(s_Context->m_UserInterface, "Failed to create UserInterface");
ASSERT(s_Context->m_Renderer, "Failed to create Renderer");
return std::move(scopeGfx);
}
} // namespace Light

View file

@ -0,0 +1,59 @@
#pragma once
#include "Base/Base.hpp"
struct GLFWwindow;
namespace Light {
class Renderer;
class ResourceManager;
class SharedContext;
class UserInterface;
class WindowResizedEvent;
enum class GraphicsAPI
{
Default = 0,
OpenGL,
DirectX,
Vulkan, // :#todo
Metal // :#todo
};
class GraphicsContext /* singleton */
{
private:
static GraphicsContext* s_Context;
private:
Scope<UserInterface> m_UserInterface;
Scope<Renderer> m_Renderer;
protected:
GraphicsAPI m_GraphicsAPI;
Ref<SharedContext> m_SharedContext = nullptr;
public:
static Scope<GraphicsContext> Create(GraphicsAPI api, GLFWwindow* windowHandle);
GraphicsContext(const GraphicsContext&) = delete;
GraphicsContext& operator=(const GraphicsContext&) = delete;
virtual ~GraphicsContext();
virtual void LogDebugData() = 0;
static inline GraphicsAPI GetGraphicsAPI() { return s_Context->m_GraphicsAPI; }
static inline Ref<SharedContext> GetSharedContext() { return s_Context->m_SharedContext; }
inline Renderer* GetRenderer() { return m_Renderer.get(); }
inline UserInterface* GetUserInterface() { return m_UserInterface.get(); }
protected:
GraphicsContext() = default;
};
} // namespace Light

View file

@ -0,0 +1,30 @@
#include "RenderCommand.hpp"
#include "OpenGL/glRenderCommand.hpp"
#ifdef LIGHT_PLATFORM_WINDOWS
#include "DirectX/dxRenderCommand.hpp"
#include "DirectX/dxSharedContext.hpp"
#endif
#include "GraphicsContext.hpp"
namespace Light {
Scope<RenderCommand> RenderCommand::Create(GLFWwindow* windowHandle, Ref<SharedContext> sharedContext)
{
switch (GraphicsContext::GetGraphicsAPI())
{
case GraphicsAPI::OpenGL:
return CreateScope<glRenderCommand>(windowHandle);
case GraphicsAPI::DirectX: LT_WIN(
return CreateScope<dxRenderCommand>((std::static_pointer_cast<dxSharedContext>)(sharedContext));)
default:
ASSERT(false, "Invalid/unsupported 'GraphicsAPI' {}", static_cast<uint32_t>(GraphicsContext::GetGraphicsAPI()));
return nullptr;
}
}
} // namespace Light

View file

@ -0,0 +1,37 @@
#pragma once
#include "Base/Base.hpp"
#include <glm/glm.hpp>
struct GLFWwindow;
namespace Light {
class SharedContext;
class RenderCommand
{
public:
static Scope<RenderCommand> Create(GLFWwindow* windowHandle, Ref<SharedContext> sharedContext);
RenderCommand(const RenderCommand&) = delete;
RenderCommand& operator=(const RenderCommand&) = delete;
virtual ~RenderCommand() = default;
virtual void SwapBuffers() = 0;
virtual void ClearBackBuffer(const glm::vec4& clearColor) = 0;
virtual void Draw(unsigned int count) = 0;
virtual void DrawIndexed(unsigned int count) = 0;
virtual void DefaultTargetFramebuffer() = 0;
virtual void SetViewport(unsigned int x, unsigned int y, unsigned int width, unsigned int height) = 0;
protected:
RenderCommand() = default;
};
} // namespace Light

View file

@ -0,0 +1,270 @@
#include "Renderer.hpp"
#include "Blender.hpp"
#include "Buffers.hpp"
#include "Camera/SceneCamera.hpp"
#include "Events/WindowEvents.hpp"
#include "Framebuffer.hpp"
#include "RenderCommand.hpp"
#include "Texture.hpp"
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/matrix.hpp>
namespace Light {
Renderer* Renderer::s_Context = nullptr;
Renderer::Renderer(GLFWwindow* windowHandle, Ref<SharedContext> sharedContext)
: m_QuadRenderer(LT_MAX_QUAD_RENDERER_VERTICES, sharedContext), m_TextureRenderer(LT_MAX_TEXTURE_RENDERER_VERTICES, sharedContext), m_TintedTextureRenderer(LT_MAX_TINTED_TEXTURE_RENDERER_VERTICES, sharedContext), m_ViewProjectionBuffer(nullptr), m_RenderCommand(nullptr), m_Blender(nullptr), m_DefaultFramebufferCamera(nullptr), m_TargetFramebuffer(nullptr), m_ShouldClearBackbuffer(false)
{
ASSERT(!s_Context, "An instance of 'Renderer' already exists, do not construct this class!");
s_Context = this;
m_ViewProjectionBuffer = ConstantBuffer::Create(ConstantBufferIndex::ViewProjection, sizeof(glm::mat4), sharedContext);
m_RenderCommand = RenderCommand::Create(windowHandle, sharedContext);
m_Blender = Blender::Create(sharedContext);
m_Blender->Enable(BlendFactor::SRC_ALPHA, BlendFactor::INVERSE_SRC_ALPHA);
}
Scope<Renderer> Renderer::Create(GLFWwindow* windowHandle, Ref<SharedContext> sharedContext)
{
return MakeScope<Renderer>(new Renderer(windowHandle, sharedContext));
}
void Renderer::OnWindowResize(const WindowResizedEvent& event)
{
m_RenderCommand->SetViewport(0u, 0u, event.GetSize().x, event.GetSize().y);
}
//======================================== DRAW_QUAD ========================================//
/* tinted textures */
void Renderer::DrawQuadImpl(const glm::vec3& position, const glm::vec2& size, const glm::vec4& tint, Ref<Texture> texture)
{
DrawQuad(glm::translate(glm::mat4(1.0f), position) * glm::scale(glm::mat4(1.0f), { size.x, size.y, 1.0f }),
tint, texture);
}
/* tint */
void Renderer::DrawQuadImpl(const glm::vec3& position, const glm::vec2& size, const glm::vec4& tint)
{
DrawQuad(glm::translate(glm::mat4(1.0f), position) * glm::scale(glm::mat4(1.0f), { size.x, size.y, 1.0f }),
tint);
}
/* texture */
void Renderer::DrawQuadImpl(const glm::vec3& position, const glm::vec2& size, Ref<Texture> texture)
{
DrawQuad(glm::translate(glm::mat4(1.0f), position) * glm::scale(glm::mat4(1.0f), { size.x, size.y, 1.0f }),
texture);
}
//======================================== DRAW_QUAD ========================================//
//==================== DRAW_QUAD_TINT ====================//
void Renderer::DrawQuadImpl(const glm::mat4& transform, const glm::vec4& tint)
{
// locals
QuadRendererProgram::QuadVertexData* bufferMap = m_QuadRenderer.GetMapCurrent();
// top left
bufferMap[0].position = transform * glm::vec4(-0.5f, -0.5f, 0.0f, 1.0f);
bufferMap[0].tint = tint;
// top right
bufferMap[1].position = transform * glm::vec4(0.5f, -0.5f, 0.0f, 1.0f);
bufferMap[1].tint = tint;
// bottom right
bufferMap[2].position = transform * glm::vec4(0.5f, 0.5f, 0.0f, 1.0f);
bufferMap[2].tint = tint;
// bottom left
bufferMap[3].position = transform * glm::vec4(-0.5f, 0.5f, 0.0f, 1.0f);
bufferMap[3].tint = tint;
// advance
if (!m_QuadRenderer.Advance())
{
LOG(warn, "Exceeded LT_MAX_QUAD_RENDERER_VERTICES: {}", LT_MAX_QUAD_RENDERER_VERTICES);
FlushScene();
}
}
//==================== DRAW_QUAD_TINT ====================//
//==================== DRAW_QUAD_TEXTURE ====================//
void Renderer::DrawQuadImpl(const glm::mat4& transform, Ref<Texture> texture)
{
// #todo: implement a proper binding
ASSERT(texture, "Texture passed to Renderer::DrawQuadImpl");
texture->Bind();
// locals
TextureRendererProgram::TextureVertexData* bufferMap = m_TextureRenderer.GetMapCurrent();
// top left
bufferMap[0].position = transform * glm::vec4(-0.5f, -0.5f, 0.0f, 1.0f);
bufferMap[0].texcoord = { 0.0f, 0.0f };
// top right
bufferMap[1].position = transform * glm::vec4(0.5f, -0.5f, 0.0f, 1.0f);
bufferMap[1].texcoord = { 1.0f, 0.0f };
// bottom right
bufferMap[2].position = transform * glm::vec4(0.5f, 0.5f, 0.0f, 1.0f);
bufferMap[2].texcoord = { 1.0f, 1.0f };
// bottom left
bufferMap[3].position = transform * glm::vec4(-0.5f, 0.5f, 0.0f, 1.0f);
bufferMap[3].texcoord = { 0.0f, 1.0f };
// advance
if (!m_TextureRenderer.Advance())
{
LOG(warn, "Exceeded LT_MAX_TEXTURE_RENDERER_VERTICES: {}", LT_MAX_TEXTURE_RENDERER_VERTICES);
FlushScene();
}
}
void Renderer::DrawQuadImpl(const glm::mat4& transform, const glm::vec4& tint, Ref<Texture> texture)
{
// #todo: implement a proper binding
ASSERT(texture, "Texture passed to Renderer::DrawQuadImpl");
texture->Bind();
// locals
TintedTextureRendererProgram::TintedTextureVertexData* bufferMap = m_TintedTextureRenderer.GetMapCurrent();
// top left
bufferMap[0].position = transform * glm::vec4(-0.5f, -0.5f, 0.0f, 1.0f);
bufferMap[0].tint = tint;
bufferMap[0].texcoord = { 0.0f, 0.0f };
// top right
bufferMap[1].position = transform * glm::vec4(0.5f, -0.5f, 0.0f, 1.0f);
bufferMap[1].tint = tint;
bufferMap[1].texcoord = { 1.0f, 0.0f };
// bottom right
bufferMap[2].position = transform * glm::vec4(0.5f, 0.5f, 0.0f, 1.0f);
bufferMap[2].tint = tint;
bufferMap[2].texcoord = { 1.0f, 1.0f };
// bottom left
bufferMap[3].position = transform * glm::vec4(-0.5f, 0.5f, 0.0f, 1.0f);
bufferMap[3].tint = tint;
bufferMap[3].texcoord = { 0.0f, 1.0f };
// advance
if (!m_TintedTextureRenderer.Advance())
{
LOG(warn, "Exceeded LT_MAX_TEXTURE_RENDERER_VERTICES: {}", LT_MAX_TEXTURE_RENDERER_VERTICES);
FlushScene();
}
}
//==================== DRAW_QUAD_TEXTURE ====================//
void Renderer::BeginFrame()
{
}
void Renderer::EndFrame()
{
m_RenderCommand->SwapBuffers();
m_RenderCommand->ClearBackBuffer(m_DefaultFramebufferCamera ? m_DefaultFramebufferCamera->GetBackgroundColor() : glm::vec4(0.0f));
m_DefaultFramebufferCamera = nullptr;
}
void Renderer::BeginSceneImpl(Camera* camera, const glm::mat4& cameraTransform, const Ref<Framebuffer>& targetFrameBuffer /* = nullptr */)
{
// determine the target frame buffer
m_TargetFramebuffer = targetFrameBuffer;
if (targetFrameBuffer)
targetFrameBuffer->BindAsTarget(camera->GetBackgroundColor());
else
{
m_DefaultFramebufferCamera = camera;
m_RenderCommand->DefaultTargetFramebuffer();
}
// update view projection buffer
glm::mat4* map = (glm::mat4*)m_ViewProjectionBuffer->Map();
map[0] = camera->GetProjection() * glm::inverse(cameraTransform);
m_ViewProjectionBuffer->UnMap();
// map renderers
m_QuadRenderer.Map();
m_TextureRenderer.Map();
m_TintedTextureRenderer.Map();
}
void Renderer::FlushScene()
{
/* tinted texture renderer */
m_TintedTextureRenderer.UnMap();
if (m_TintedTextureRenderer.GetQuadCount())
{
m_TintedTextureRenderer.Bind();
m_RenderCommand->DrawIndexed(m_TintedTextureRenderer.GetQuadCount() * 6u);
}
/* quad renderer */
m_QuadRenderer.UnMap();
if (m_QuadRenderer.GetQuadCount())
{
m_QuadRenderer.Bind();
m_RenderCommand->DrawIndexed(m_QuadRenderer.GetQuadCount() * 6u);
}
/* texture renderer */
m_TextureRenderer.UnMap();
if (m_TextureRenderer.GetQuadCount())
{
m_TextureRenderer.Bind();
m_RenderCommand->DrawIndexed(m_TextureRenderer.GetQuadCount() * 6u);
}
m_QuadRenderer.Map();
m_TextureRenderer.Map();
m_TintedTextureRenderer.Map();
}
void Renderer::EndSceneImpl()
{
/* tinted texture renderer */
m_TintedTextureRenderer.UnMap();
if (m_TintedTextureRenderer.GetQuadCount())
{
m_TintedTextureRenderer.Bind();
m_RenderCommand->DrawIndexed(m_TintedTextureRenderer.GetQuadCount() * 6u);
}
/* quad renderer */
m_QuadRenderer.UnMap();
if (m_QuadRenderer.GetQuadCount())
{
m_QuadRenderer.Bind();
m_RenderCommand->DrawIndexed(m_QuadRenderer.GetQuadCount() * 6u);
}
/* texture renderer */
m_TextureRenderer.UnMap();
if (m_TextureRenderer.GetQuadCount())
{
m_TextureRenderer.Bind();
m_RenderCommand->DrawIndexed(m_TextureRenderer.GetQuadCount() * 6u);
}
// reset frame buffer
if (m_TargetFramebuffer)
{
m_TargetFramebuffer = nullptr;
m_RenderCommand->DefaultTargetFramebuffer();
}
}
} // namespace Light

View file

@ -0,0 +1,84 @@
#pragma once
#include "Base/Base.hpp"
#include "RendererPrograms/QuadRendererProgram.hpp"
#include "RendererPrograms/TextureRendererProgram.hpp"
#include "RendererPrograms/TintedTextureRendererProgram.hpp"
#define LT_MAX_QUAD_RENDERER_VERTICES 1028u * 4u
#define LT_MAX_TEXTURE_RENDERER_VERTICES 1028u * 4u
#define LT_MAX_TINTED_TEXTURE_RENDERER_VERTICES 1028u * 4u
struct GLFWwindow;
namespace Light {
class Blender;
class ConstantBuffer;
class Framebuffer;
class RenderCommand;
class Texture;
class SharedContext;
class Camera;
class WindowResizedEvent;
class Renderer
{
private:
static Renderer* s_Context;
// renderer programs
QuadRendererProgram m_QuadRenderer;
TextureRendererProgram m_TextureRenderer;
TintedTextureRendererProgram m_TintedTextureRenderer;
// constant buffers
Scope<ConstantBuffer> m_ViewProjectionBuffer;
Scope<RenderCommand> m_RenderCommand;
Scope<Blender> m_Blender;
Camera* m_DefaultFramebufferCamera;
Ref<Framebuffer> m_TargetFramebuffer;
bool m_ShouldClearBackbuffer;
public:
static Scope<Renderer> Create(GLFWwindow* windowHandle, Ref<SharedContext> sharedContext);
static inline void DrawQuad(const glm::vec3& position, const glm::vec2& size, const glm::vec4& tint, Ref<Texture> texture) { s_Context->DrawQuadImpl(position, size, tint, texture); }
static inline void DrawQuad(const glm::vec3& position, const glm::vec2& size, const glm::vec4& tint) { s_Context->DrawQuadImpl(position, size, tint); }
static inline void DrawQuad(const glm::vec3& position, const glm::vec2& size, Ref<Texture> texture) { s_Context->DrawQuadImpl(position, size, texture); }
static void DrawQuad(const glm::mat4& transform, const glm::vec4& tint, Ref<Texture> texture) { s_Context->DrawQuadImpl(transform, tint, texture); }
static void DrawQuad(const glm::mat4& transform, const glm::vec4& tint) { s_Context->DrawQuadImpl(transform, tint); }
static void DrawQuad(const glm::mat4& transform, Ref<Texture> texture) { s_Context->DrawQuadImpl(transform, texture); }
static inline void BeginScene(Camera* camera, const glm::mat4& cameraTransform, const Ref<Framebuffer>& targetFrameBuffer = nullptr) { s_Context->BeginSceneImpl(camera, cameraTransform, targetFrameBuffer); }
static inline void EndScene() { s_Context->EndSceneImpl(); }
void OnWindowResize(const WindowResizedEvent& event);
void BeginFrame();
void EndFrame();
private:
Renderer(GLFWwindow* windowHandle, Ref<SharedContext> sharedContext);
void DrawQuadImpl(const glm::vec3& position, const glm::vec2& size, const glm::vec4& tint, Ref<Texture> texture);
void DrawQuadImpl(const glm::vec3& position, const glm::vec2& size, const glm::vec4& tint);
void DrawQuadImpl(const glm::vec3& position, const glm::vec2& size, Ref<Texture> texture);
void DrawQuadImpl(const glm::mat4& transform, const glm::vec4& tint, Ref<Texture> texture);
void DrawQuadImpl(const glm::mat4& transform, const glm::vec4& tint);
void DrawQuadImpl(const glm::mat4& transform, Ref<Texture> texture);
void BeginSceneImpl(Camera* camera, const glm::mat4& cameraTransform, const Ref<Framebuffer>& targetFrameBuffer = nullptr);
void FlushScene();
void EndSceneImpl();
};
} // namespace Light

View file

@ -0,0 +1,58 @@
#include "QuadRendererProgram.hpp"
#include "Camera/Camera.hpp"
#include "Graphics/Buffers.hpp"
#include "Graphics/Shader.hpp"
#include "Graphics/VertexLayout.hpp"
#include "Utility/ResourceManager.hpp"
namespace Light {
QuadRendererProgram::QuadRendererProgram(unsigned int maxVertices, Ref<SharedContext> sharedContext)
: m_Shader(nullptr), m_IndexBuffer(nullptr), m_VertexLayout(nullptr), m_MapCurrent(nullptr), m_MapEnd(nullptr), m_QuadCount(0u), m_MaxVertices(maxVertices)
{
// #todo: don't use relative path
ResourceManager::LoadShader("LT_ENGINE_RESOURCES_QUAD_SHADER", "Assets/Shaders/Quad/Quad_VS.glsl", "Assets/Shaders/Quad/Quad_PS.glsl");
m_Shader = ResourceManager::GetShader("LT_ENGINE_RESOURCES_QUAD_SHADER");
m_VertexBuffer = Ref<VertexBuffer>(VertexBuffer::Create(nullptr, sizeof(QuadVertexData), maxVertices, sharedContext));
m_IndexBuffer = Ref<IndexBuffer>(IndexBuffer::Create(nullptr, (maxVertices / 4) * 6, sharedContext));
m_VertexLayout = Ref<VertexLayout>(VertexLayout::Create(m_VertexBuffer, m_Shader, { { "POSITION", VertexElementType::Float4 }, { "COLOR", VertexElementType::Float4 } }, sharedContext));
}
bool QuadRendererProgram::Advance()
{
m_MapCurrent += 4;
if (m_MapCurrent >= m_MapEnd)
{
LOG(warn, "'VertexBuffer' map went beyond 'MaxVertices': {}", m_MaxVertices);
return false;
}
m_QuadCount++;
return true;
}
void QuadRendererProgram::Map()
{
m_QuadCount = 0u;
m_MapCurrent = (QuadRendererProgram::QuadVertexData*)m_VertexBuffer->Map();
m_MapEnd = m_MapCurrent + m_MaxVertices;
}
void QuadRendererProgram::UnMap()
{
m_VertexBuffer->UnMap();
}
void QuadRendererProgram::Bind()
{
m_Shader->Bind();
m_VertexLayout->Bind();
m_VertexBuffer->Bind();
m_IndexBuffer->Bind();
}
} // namespace Light

View file

@ -0,0 +1,55 @@
#pragma once
#include "Base/Base.hpp"
#include "RendererProgram.hpp"
#include <glm/glm.hpp>
namespace Light {
class Shader;
class VertexBuffer;
class IndexBuffer;
class VertexLayout;
class OrthographicCamera;
class SharedContext;
class QuadRendererProgram: RendererProgram
{
public:
struct QuadVertexData
{
glm::vec4 position;
glm::vec4 tint;
};
private:
Ref<Shader> m_Shader;
Ref<VertexBuffer> m_VertexBuffer;
Ref<IndexBuffer> m_IndexBuffer;
Ref<VertexLayout> m_VertexLayout;
QuadVertexData* m_MapCurrent = nullptr;
QuadVertexData* m_MapEnd = nullptr;
unsigned int m_QuadCount = 0u;
unsigned int m_MaxVertices = 0u;
public:
QuadRendererProgram(unsigned int maxVertices, Ref<SharedContext> sharedContext);
bool Advance();
void Map() override;
void UnMap() override;
void Bind() override;
inline QuadVertexData* GetMapCurrent() { return m_MapCurrent; }
inline unsigned int GetQuadCount() const { return m_QuadCount; }
inline constexpr unsigned int GetVertexSize() const { return sizeof(QuadVertexData); }
};
} // namespace Light

View file

@ -0,0 +1,17 @@
#pragma once
#include "Base/Base.hpp"
namespace Light {
class OrthographicCamera;
class RendererProgram
{
virtual void Map() = 0;
virtual void UnMap() = 0;
virtual void Bind() = 0;
};
} // namespace Light

View file

@ -0,0 +1,57 @@
#include "TextureRendererProgram.hpp"
#include "Camera/Camera.hpp"
#include "Graphics/Buffers.hpp"
#include "Graphics/Shader.hpp"
#include "Graphics/VertexLayout.hpp"
#include "Utility/ResourceManager.hpp"
namespace Light {
TextureRendererProgram::TextureRendererProgram(unsigned int maxVertices, Ref<SharedContext> sharedContext)
: m_Shader(nullptr), m_IndexBuffer(nullptr), m_VertexLayout(nullptr), m_MapCurrent(nullptr), m_MapEnd(nullptr), m_QuadCount(0u), m_MaxVertices(maxVertices)
{
// #todo: don't use relative path
ResourceManager::LoadShader("LT_ENGINE_RESOURCES_TEXTURE_SHADER", "Assets/Shaders/Texture/Texture_VS.glsl", "Assets/Shaders/Texture/Texture_PS.glsl");
m_Shader = ResourceManager::GetShader("LT_ENGINE_RESOURCES_TEXTURE_SHADER");
m_VertexBuffer = Ref<VertexBuffer>(VertexBuffer::Create(nullptr, sizeof(TextureVertexData), maxVertices, sharedContext));
m_IndexBuffer = Ref<IndexBuffer>(IndexBuffer::Create(nullptr, (maxVertices / 4) * 6, sharedContext));
m_VertexLayout = Ref<VertexLayout>(VertexLayout::Create(m_VertexBuffer, m_Shader, { { "POSITION", VertexElementType::Float4 }, { "TEXCOORD", VertexElementType::Float2 } }, sharedContext));
}
bool TextureRendererProgram::Advance()
{
if (m_MapCurrent + 4 >= m_MapEnd)
{
LOG(warn, "'VertexBuffer' map went beyond 'MaxVertices': {}", m_MaxVertices);
return false;
}
m_MapCurrent += 4;
m_QuadCount++;
return true;
}
void TextureRendererProgram::Map()
{
m_QuadCount = 0u;
m_MapCurrent = (TextureRendererProgram::TextureVertexData*)m_VertexBuffer->Map();
m_MapEnd = m_MapCurrent + m_MaxVertices;
}
void TextureRendererProgram::UnMap()
{
m_VertexBuffer->UnMap();
}
void TextureRendererProgram::Bind()
{
m_Shader->Bind();
m_VertexLayout->Bind();
m_VertexBuffer->Bind();
m_IndexBuffer->Bind();
}
} // namespace Light

View file

@ -0,0 +1,57 @@
#pragma once
#include "Base/Base.hpp"
#include "RendererProgram.hpp"
#include <glm/glm.hpp>
namespace Light {
class Shader;
class VertexBuffer;
class IndexBuffer;
class VertexLayout;
class OrthographicCamera;
class SharedContext;
class TextureRendererProgram: RendererProgram
{
public:
struct TextureVertexData
{
glm::vec4 position;
glm::vec2 texcoord;
};
private:
Ref<Shader> m_Shader;
Ref<VertexBuffer> m_VertexBuffer;
Ref<IndexBuffer> m_IndexBuffer;
Ref<VertexLayout> m_VertexLayout;
TextureVertexData* m_MapCurrent = nullptr;
TextureVertexData* m_MapEnd = nullptr;
unsigned int m_QuadCount;
unsigned int m_MaxVertices;
public:
TextureRendererProgram(unsigned int maxVertices, Ref<SharedContext> sharedContext);
bool Advance();
void Map() override;
void UnMap() override;
void Bind() override;
inline TextureVertexData* GetMapCurrent() { return m_MapCurrent; }
inline unsigned int GetQuadCount() const { return m_QuadCount; }
inline constexpr unsigned int GetVertexSize() const { return sizeof(TextureVertexData); }
};
} // namespace Light

View file

@ -0,0 +1,58 @@
#include "TintedTextureRendererProgram.hpp"
#include "Camera/Camera.hpp"
#include "Graphics/Buffers.hpp"
#include "Graphics/Shader.hpp"
#include "Graphics/VertexLayout.hpp"
#include "Utility/ResourceManager.hpp"
namespace Light {
TintedTextureRendererProgram::TintedTextureRendererProgram(unsigned int maxVertices, Ref<SharedContext> sharedContext)
: m_Shader(nullptr), m_IndexBuffer(nullptr), m_VertexLayout(nullptr), m_MapCurrent(nullptr), m_MapEnd(nullptr), m_QuadCount(0u), m_MaxVertices(maxVertices)
{
// #todo: don't use relative path
ResourceManager::LoadShader("LT_ENGINE_RESOURCES_TINTED_TEXTURE_SHADER", "Assets/Shaders/TintedTexture/TintedTexture_VS.glsl", "Assets/Shaders/TintedTexture/TintedTexture_PS.glsl");
m_Shader = ResourceManager::GetShader("LT_ENGINE_RESOURCES_TINTED_TEXTURE_SHADER");
m_VertexBuffer = Ref<VertexBuffer>(VertexBuffer::Create(nullptr, sizeof(TintedTextureVertexData), maxVertices, sharedContext));
m_IndexBuffer = Ref<IndexBuffer>(IndexBuffer::Create(nullptr, (maxVertices / 4) * 6, sharedContext));
m_VertexLayout = Ref<VertexLayout>(VertexLayout::Create(m_VertexBuffer, m_Shader, { { "POSITION", VertexElementType::Float4 }, { "TINT", VertexElementType::Float4 }, { "TEXCOORD", VertexElementType::Float2 } }, sharedContext));
}
bool TintedTextureRendererProgram::Advance()
{
m_MapCurrent += 4;
if (m_MapCurrent >= m_MapEnd)
{
LOG(warn, "'VertexBuffer' map went beyond 'MaxVertices': {}", m_MaxVertices);
return false;
}
m_QuadCount++;
return true;
}
void TintedTextureRendererProgram::Map()
{
m_QuadCount = 0u;
m_MapCurrent = (TintedTextureRendererProgram::TintedTextureVertexData*)m_VertexBuffer->Map();
m_MapEnd = m_MapCurrent + m_MaxVertices;
}
void TintedTextureRendererProgram::UnMap()
{
m_VertexBuffer->UnMap();
}
void TintedTextureRendererProgram::Bind()
{
m_Shader->Bind();
m_VertexLayout->Bind();
m_VertexBuffer->Bind();
m_IndexBuffer->Bind();
}
} // namespace Light

View file

@ -0,0 +1,58 @@
#pragma once
#include "Base/Base.hpp"
#include "RendererProgram.hpp"
#include <glm/glm.hpp>
namespace Light {
class Shader;
class VertexBuffer;
class IndexBuffer;
class VertexLayout;
class OrthographicCamera;
class SharedContext;
class TintedTextureRendererProgram: RendererProgram
{
public:
struct TintedTextureVertexData
{
glm::vec4 position;
glm::vec4 tint;
glm::vec2 texcoord;
};
private:
Ref<Shader> m_Shader;
Ref<VertexBuffer> m_VertexBuffer;
Ref<IndexBuffer> m_IndexBuffer;
Ref<VertexLayout> m_VertexLayout;
TintedTextureVertexData* m_MapCurrent = nullptr;
TintedTextureVertexData* m_MapEnd = nullptr;
unsigned int m_QuadCount;
unsigned int m_MaxVertices;
public:
TintedTextureRendererProgram(unsigned int maxVertices, Ref<SharedContext> sharedContext);
bool Advance();
void Map() override;
void UnMap() override;
void Bind() override;
inline TintedTextureVertexData* GetMapCurrent() { return m_MapCurrent; }
inline unsigned int GetQuadCount() const { return m_QuadCount; }
inline constexpr unsigned int GetVertexSize() const { return sizeof(TintedTextureVertexData); }
};
} // namespace Light

View file

@ -0,0 +1,31 @@
#include "Shader.hpp"
#include "OpenGL/glShader.hpp"
#ifdef LIGHT_PLATFORM_WINDOWS
#include "DirectX/dxShader.hpp"
#include "DirectX/dxSharedContext.hpp"
#endif
#include "GraphicsContext.hpp"
namespace Light {
Ref<Shader> Shader::Create(BasicFileHandle vertexFile, BasicFileHandle pixelFile, Ref<SharedContext> sharedContext)
{
// load shader source
switch (GraphicsContext::GetGraphicsAPI())
{
case GraphicsAPI::OpenGL:
return CreateRef<glShader>(vertexFile, pixelFile);
case GraphicsAPI::DirectX: LT_WIN(
return CreateRef<dxShader>(vertexFile, pixelFile, std::static_pointer_cast<dxSharedContext>(sharedContext));)
default:
ASSERT(false, "Invalid/unsupported 'GraphicsAPI' {}", static_cast<uint32_t>(GraphicsContext::GetGraphicsAPI()));
return nullptr;
}
}
} // namespace Light

View file

@ -0,0 +1,35 @@
#pragma once
#include "Base/Base.hpp"
#include "Utility/FileManager.hpp"
#include <glm/glm.hpp>
namespace Light {
class SharedContext;
class Shader
{
public:
enum Stage
{
NONE = 0,
VERTEX = 1,
PIXEL = 2,
GEOMETRY = 3
};
public:
static Ref<Shader> Create(BasicFileHandle vertexFile, BasicFileHandle pixelFile, Ref<SharedContext> sharedContext);
virtual ~Shader() = default;
virtual void Bind() = 0;
virtual void UnBind() = 0;
protected:
Shader() = default;
};
} // namespace Light

View file

@ -0,0 +1,13 @@
#pragma once
#include "Base/Base.hpp"
namespace Light {
class SharedContext
{
public:
virtual ~SharedContext() = default;
};
} // namespace Light

View file

@ -0,0 +1,35 @@
#include "Texture.hpp"
#include "OpenGL/glTexture.hpp"
#ifdef LIGHT_PLATFORM_WINDOWS
#include "DirectX/dxSharedContext.hpp"
#include "DirectX/dxTexture.hpp"
#endif
#include "GraphicsContext.hpp"
namespace Light {
Ref<Texture> Texture::Create(unsigned int width, unsigned int height, unsigned int components, unsigned char* pixels, Ref<SharedContext> sharedContext, const std::string& filePath)
{
switch (GraphicsContext::GetGraphicsAPI())
{
case GraphicsAPI::OpenGL:
return CreateRef<glTexture>(width, height, components, pixels, filePath);
case GraphicsAPI::DirectX: LT_WIN(
return CreateRef<dxTexture>(width, height, components, pixels, std::static_pointer_cast<dxSharedContext>(sharedContext), filePath);)
default:
ASSERT(false, "Invalid/unsupported 'GraphicsAPI' {}", static_cast<uint32_t>(GraphicsContext::GetGraphicsAPI()));
return nullptr;
}
}
Texture::Texture(const std::string& filePath)
: m_FilePath(filePath)
{
}
} // namespace Light

View file

@ -0,0 +1,33 @@
#pragma once
#include "Base/Base.hpp"
namespace Light {
class SharedContext;
// #todo: improve textures
class Texture
{
public:
static Ref<Texture> Create(unsigned int width, unsigned int height, unsigned int components, unsigned char* pixels, Ref<SharedContext> sharedContext, const std::string& filePath);
Texture(const Texture&) = delete;
Texture& operator=(const Texture&) = delete;
virtual ~Texture() = default;
virtual void Bind(unsigned int slot = 0) = 0;
virtual void* GetTexture() = 0;
inline const std::string& GetFilePath() const { return m_FilePath; }
protected:
Texture(const std::string& filePath);
protected:
std::string m_FilePath;
};
} // namespace Light

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