Code Monkey home page Code Monkey logo

hazel's Introduction

Hazel License

Hazel

Hazel is primarily an early-stage interactive application and rendering engine for Windows. Currently not much is implemented, however (almost) everything inside this repository is being created within YouTube videos, found at thecherno.com/engine.


Getting Started

Visual Studio 2017 or 2019 is recommended, Hazel is officially untested on other development environments whilst we focus on a Windows build.

1. Downloading the repository:

Start by cloning the repository with git clone --recursive https://github.com/TheCherno/Hazel.

If the repository was cloned non-recursively previously, use git submodule update --init to clone the necessary submodules.

2. Configuring the dependencies:

  1. Run the Setup.bat file found in scripts folder. This will download the required prerequisites for the project if they are not present yet.
  2. One prerequisite is the Vulkan SDK. If it is not installed, the script will execute the VulkanSDK.exe file, and will prompt the user to install the SDK.
  3. After installation, run the Setup.bat file again. If the Vulkan SDK is installed properly, it will then download the Vulkan SDK Debug libraries. (This may take a longer amount of time)
  4. After downloading and unzipping the files, the Win-GenProjects.bat script file will get executed automatically, which will then generate a Visual Studio solution file for user's usage.

If changes are made, or if you want to regenerate project files, rerun the Win-GenProjects.bat script file found in scripts folder.


The Plan

The plan for Hazel is two-fold: to create a powerful 3D engine, but also to serve as an education tool for teaching game engine design and architecture. Because of this the development inside this repository is rather slow, since everything has to be taught and implemented on-camera. There is a much more advanced version of the engine in a private repository called Hazel-dev, accessible to supporters on Patreon. The plan for this project is to mostly take already implemented code from the Hazel-dev repository and integrate it into this one, done within videos and supported by explanations.

Main features to come:

  • Fast 2D rendering (UI, particles, sprites, etc.)
  • High-fidelity Physically-Based 3D rendering (this will be expanded later, 2D to come first)
  • Support for Mac, Linux, Android and iOS
    • Native rendering API support (DirectX, Vulkan, Metal)
  • Fully featured viewer and editor applications
  • Fully scripted interaction and behavior
  • Integrated 3rd party 2D and 3D physics engine
  • Procedural terrain and world generation
  • Artificial Intelligence
  • Audio system

Short term goals :

Note: this is subject to change at any time! Follow the roadmap over at hazelengine.com/roadmap.

By the end 2020, we want to make a game using the Hazel game engine. Not like the time I made a game in one hour using the engine, but this time by using the proper tools that would be required to make a game with Hazel. This means we need to add a full 2D workflow:

  • Design the game scene by using Hazelnut, the Hazel editor,
  • Test the game inside Hazelnut, including the ability to save/load the created game,
  • Load and play the game inside Sandbox.

We want everyone to be able to play the game on all desktop platforms (Windows, Mac and Linux). When this is implemented, another attempt at the "Creating a game in one hour using Hazel" will be made to see how far the engine has become.

Twitter Instagram Youtube Discord Patreon

hazel's People

Contributors

0xworks avatar 3x3y3z3t avatar 9y0 avatar advikkabra avatar ardarsha avatar cleversource avatar cybernethacker14 avatar d-tatianin avatar daveaxiom avatar dr01d3k4 avatar dragon9815 avatar herrdingenz avatar husamdababneh avatar ilikenoodles2 avatar isho312 avatar jack-punter avatar lewyischewy avatar lovelysanta avatar muthubroo avatar puddlestomper avatar ridhwandll avatar ryanbbernstein avatar seppahbaws avatar shaiavr avatar sidmostefaoui avatar stolkerve avatar szilard0605 avatar tatranskymedved avatar thecherno avatar tigercipher avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

hazel's Issues

glCreateBuffers and OpenGL 4.4

Hi,
We should make it clear what OpenGL copatability the project should have. The moment we changed glGenBuffers to glCreateBuffers things went south (for me) with the exception:

Exception thrown at 0x0000000000000000 in Sandbox.exe: 0xC0000005: Access violation executing location 0x0000000000000000.

Some quick research suggested that it's sue to me running OpenGL 4.4 on my laptop. This of course means that the solution does not run out-of-the-box in this case, and based on what I've read, it's due to GL_ARB_direct_state_access entering the core profile only as of 4.5. So:

  • Are there any reasons for not sticking with glGenBuffers ?
  • Might it be worth differentiating the implementation based on the GL version?
  • Should anything below 4.5 be unsupported all together?

Linkage problem in vs2015

If I generate solution by premake5 for visual studio 2015 I am getting this error:
LINK : fatal error LNK1104: cannot open file '~\Hazel\bin\Debug-windows-x86_64\Hazel\Hazel.lib'

push_back/emplace_back in LayerStack invalidates m_LayerInsert iterator

Currently when we push_back/emplace_back (in case of overlays), since memory is reallocated, m_LayerInsert iterator gets invalidated.
And afterwards when we're pushing a layer, since we're using the invalidated m_LayerInsert iterator, it'll throw an exception.
One solution is to use an index instead of m_LayerInsert iterator and generate an iterator by m_Layers.begin()+index whenever we needed one to use insert/emplace methods.

Application crash on windows default full-screen toggling

I assume windows is trying to force our application to fullscreen mode, but then something goes wrong. (See image below)

image

Steps:

  • Run the application
  • Press F12

Bug:
Application crashes

Expected:
Nothing should happen at least or full screen should be toggled.

Segmentation fault...

Hi,

I try to make a version of Hazel on my own step by step watching the videos. And I do that on linux (thanks again @cubedtear).

Since I implemented ImGui I get a Segmentation fault each time I try to run the application. I can't figure out what I'm doing wrong.

Here's my repo : https://github.com/NiGhMa/Hazelicious

If you could help me, I'll appreciate a lot.

Edit:

I found that the line 219 in imgui_impl_opengl3.cpp ( glBindSampler(0, 0); ) causes the problem!
Screenshot from 2019-07-01 13-32-46

And here's my glxinfo output (version)

server glx version string: 1.4
client glx version string: 1.4
GLX version: 1.4
    Max core profile version: 4.5
    Max compat profile version: 3.0
    Max GLES1 profile version: 1.1
    Max GLES[23] profile version: 3.1
OpenGL core profile version string: 4.5 (Core Profile) Mesa 18.2.8
OpenGL core profile shading language version string: 4.50
OpenGL version string: 3.0 Mesa 18.2.8
OpenGL shading language version string: 1.30
OpenGL ES profile version string: OpenGL ES 3.1 Mesa 18.2.8
OpenGL ES profile shading language version string: OpenGL ES GLSL ES 3.10

Thanks

Visual Studio Project Files

Hello everyone!

I was wondering whether the already generated Visual Studio project files need to be in the repository, now that Premake is supported and anyone can generate them by themselves.

"Fire" event

Just to verify, Is it possible that currently the events callback are only related to the the Window class. Therefore, there is no mechanism that enable to set callbacks to application events?

Can you please help how to propagate application events when using hazel engine?

Originally:
I didn't understand how to "fire" an application event using hazel engine.
Can someone please explain it?

10X in advance!

premake group for vendor projects

Hello.

Number of projects in vendor folder are incrising. How about separating projects in subfolders. Using premake group.

In general something like this:

-- premake5.lua
...
group "Vendor"
include "Hazel/vendor/GLFW"
include "Hazel/vendor/Glad"
include "Hazel/vendor/imgui"

group "Engine"
project "Hazel"
...

Exeption thrown by glCreateVertexArrays

Exception thrown at 0x0000000000000000 in Sandbox.exe: 0xC0000005: Access violation executing location 0x0000000000000000.
At line: 31, at: OpenGLVertexArray.cpp.

This error throws on Debug and Release Windows runs.

Imgui linking problems

I'm having some issues with linking Imgui to the "Sandbox" project lately;

I'm linking the IMGUI static library to the "Core" dynamic library (that gets linked into the sandbox project).

I have decommented the "IMGUI_API" preprocessor for dllexport() inside imgui_config.h, but i still get an unresolved external:

Severity	Code	Description	Project	File	Line	Suppression State 
Error	LNK2019	unresolved external symbol "void __cdecl ImGui::ShowDemoWindow(bool *)" 
(?ShowDemoWindow@ImGui@@YAXPEA_N@Z) referenced in function "public: virtual void 
__cdecl Test::OnImguiRender(void)" (?OnImguiRender@Test@@UEAAXXZ)	Sandbox	 
C:\Users\gabri\Documents\GitHub\Liquid-Engine\Sandbox\main.obj	1	

Here is my main.cpp:

#include "Liquid.h"

#include "..\..\IMGUI\src\imgui.h"

class Test : public Liquid::Layer
{
public:

void OnImguiRender() override
{
	static bool show = true;
	ImGui::ShowDemoWindow(&show);
}
};

class Sandbox : public Liquid::Application
{
public:

Sandbox() : Liquid::Application("Game",960,540)
{
	PushLayer(new Test());
}

~Sandbox()
{	

}
};

Liquid::Application* Liquid::CreateApplication()
{
return new Sandbox();
}

Any kind of help is welcome, thanks a lot guys :)

CreateApplication is declared Twice!

Why is Application* CreateApplication() declared twice both in Application.h and EntryPoint.h. Shouldn't we just have it declared once then implemented by the Sandbox Application.

Issue with premake

//cmd begins here...
F:\C++\VS2019\Solutions\GameEngine>call Dependencies\premake5\premake5.exe --file=PreGameEngine.lua vs2019
Error: [string "src/base/_foundation.lua"]:127: attempt to concatenate a table value (local 'fname')

F:\C++\VS2019\Solutions\GameEngine>pause
Press any key to continue . . .
//cmd ends here...

Hi Cherno! How should I clear this error? I'm using vs 2019 and premake 5 alpha 14..
Thanks in advance!

ImGUI layer (a question

Hi,

Why you have decided to include dear ImGUI layer inside your engine. It is a little weird to me since I believe that each game will have its on GUI.

BTW very nice series!

10x!
A.I.

Not hitting break points in Hazel code

Visual studio is not able to hit break points set in code in the Hazel project. It can hit breakpoints in the Sandbox app but not in the Engine.

This seems to be because the generated PDB file is not accessible to the running executable (Sandbox.exe) so it can not load the debugging symbols.

The simple solution is to add an additional post build command step to copy the file over. Something like:

("{COPY} ../bin/" .. outputdir .. "/Hazel/Hazel.pdb" .. " ../bin/" .. outputdir .. "/%{prj.name}")

to the premake5.lua file.

I would make a PR however in the repo's current state it will probably have the same issue as pointed out here. Both this new post command step and the original DLL copy should be moved to the Sandbox project section of the lua file. Because of this I'll just leave it as a suggestion for a future fix.

2d graphics

Would you create high quality 2d rendering like rounding quads, triangles, beziers with signed distance field or different technique with explanation?

FYI: Runtime Library Configuration

Hey,
you mentioned in your video Layers Game Engine series you'd like to know a way how to control the Runtime Library Configuration via Premake.

Premake has to functions for that, the first one (that you already set btw.) is staticruntime, by turning it on or off you configure either if visual studio should use the Multi-Threaded Static or DLL Runtime.
Second you have runtime that controls either the debug or non debug Runtime, if static or DLL is still determined by staticruntime.

Hope that helps,
Cheers

HZ_ENABLE_ASSERTS never enabled

Hello,

In the core you define the asserts:

#ifdef HZ_ENABLE_ASSERTS
#define HZ_ASSERT(x, ...) { if(!(x)) { HZ_ERROR("Assertion Failed: {0}", __VA_ARGS__); __debugbreak(); } }
#define HZ_CORE_ASSERT(x, ...) { if(!(x)) { HZ_CORE_ERROR("Assertion Failed: {0}", __VA_ARGS__); __debugbreak(); } }
#else
#define HZ_ASSERT(x, ...)
#define HZ_CORE_ASSERT(x, ...)
#endif

You never added those to the premake5.lua file, resulting in never asserting the statements in any mode (Debug/Release/Dist).

Kind regards
lovely_santa

ImGUI layer (a question)

Hi,

Why you have decided to include dear ImGUI layer inside your engine? (I believe that each game will have its on GUI).

BTW very nice series!

10x!
A.I.

One or more Projects in the solution were not loaded correctly

Hello peeps!
i tried running the .sln on Virtual Studio 19 and ended up with the error below.
i figured changing to VS17 would solve this (probably due to some linkage/version issues) but it wasnt the case.
Hazel folder was both manually extracted / git cloned / git submoduled and same for all the external vendor dependencies.
the GLFW / Imgui are the unloaded solutions and there is no .sln file inside their repositories
(cherno mentioned stuffs about Glad being added instead of forked and submodeled and its loading properly : maybe thats something there but im missing the hint)
anyhow heres the error message (Cmake?)

Severity Code Description Project File Line Suppression State
Error CMake Error: The following variables are used in this project, but they are set to NOTFOUND.
Please set them or make sure they are set and tested correctly in the CMake files:
VULKAN_LIBRARY (ADVANCED) C:\dev\Hazel-master\Hazel\vendor\imgui\examples\example_glfw_vulkan\Please set them or make sure they are set and tested correctly in the CMake files

How about CI?

I've used travis-ci.org with success, though I think Windows support is a no-go. I would be surprised, given the massive market share, that there isn't a solution... Google says AppVeyor, so there may yet be ppl who use continue to use Windows.

LayerStack::PopLayer is incorrect

In LayerStack::PopLayer, a comparison is made as

if (it != m_Layers.end())

this should, however, be:

if (it != m_Layers.begin() + m_LayerInsertIndex)

otherwise, if the function is passed an overlay layer, it will happily remove and shift the last non-overlay layer to be an overlay when it decrements m_LayerInsertIndex.

Incorrect cases in GetComponentCount

The OpenGL specification states that the size argument of the glVertexAttribPointer function must be 1, 2, 3, or 4. However:

uint32_t GetComponentCount() const
{
switch (Type)
{
case ShaderDataType::Float: return 1;
case ShaderDataType::Float2: return 2;
case ShaderDataType::Float3: return 3;
case ShaderDataType::Float4: return 4;
case ShaderDataType::Mat3: return 3 * 3;
case ShaderDataType::Mat4: return 4 * 4;
case ShaderDataType::Int: return 1;
case ShaderDataType::Int2: return 2;
case ShaderDataType::Int3: return 3;
case ShaderDataType::Int4: return 4;
case ShaderDataType::Bool: return 1;
}
HZ_CORE_ASSERT(false, "Unknown ShaderDataType!");
return 0;
}

There are cases in which 9 or 16 may be returned, and this method is used to generate the size argument as described above in:

glVertexAttribPointer(index,
element.GetComponentCount(),
ShaderDataTypeToOpenGLBaseType(element.Type),
element.Normalized ? GL_TRUE : GL_FALSE,
layout.GetStride(),
(const void*)element.Offset);

spdlog::logger does not contain a definition of "fatal"

Log.h contains macros called HZ_CORE_FATAL and HZ_FATAL.
The problem is that when one of these get's called somewhere in the code, a compiler error gets thrown saying that the class logger does not contain a definition for fatal (Visual Studio didn't complain since they are macros)

It's really not that much of a problem, but "prevention is better than cure" :P

sandbox not working while debugging in mvs

when i build the project it builds successfully but when i try to run it in the debugger it gives me this error while it doesn't give any error while running outside mvs
i tried to add the debugger and mvs to work on nividia card but nothing happened
this is the error message:

THE Engine
[21:47:53] HAZEL: Initialized Log!
[21:47:53] APP: Hello
[21:47:53] HAZEL: Creating Window Hazel Engine (1280,700)
ERROR: ImGui_ImplOpenGL3_CreateDeviceObjects: failed to compile vertex shader!
ERROR: 0:1: '' : Version number not supported by OGL driver
ERROR: 1:1: 'layout' : syntax error syntax error
ERROR: ImGui_ImplOpenGL3_CreateDeviceObjects: failed to compile fragment shader!
ERROR: 0:1: '' : Version number not supported by OGL driver
ERROR: 1:1: 'in' : supported in GLSL 1.30 or later
ERROR: 1:2: 'in' : supported in GLSL 1.30 or later
ERROR: 1:4: 'layout' : syntax error syntax error
ERROR: ImGui_ImplOpenGL3_CreateDeviceObjects: failed to link shader program! (wi
th GLSL '#version 410
')

A minor issue with extra warnings as errors

Just saying, if you setup high level of warnings like

# which I did
warnings "Extra"
flags { "FatalWarnings" }

# or something like
filter "toolset:msc*"
    buildoptions { "-W4", "-WX" }

Then you need also these:

Core.h

#ifdef HZ_PLATFORM_WINDOWS
	#ifdef HZ_BUILD_DLL
		#define HAZEL_API __declspec(dllexport)
		#define HAZEL_TEMPLATE
	#else
		#define HAZEL_API __declspec(dllimport)
		#define HAZEL_TEMPLATE extern
	#endif
#else
	#error Hazel only supports Windows!
#endif

Log.h

HAZEL_TEMPLATE template class HAZEL_API std::shared_ptr<spdlog::logger>;

Application.h

HAZEL_TEMPLATE template class HAZEL_API std::_Compressed_pair<std::default_delete<Window>, Window *, true>;
HAZEL_TEMPLATE template class HAZEL_API std::unique_ptr<Window>;

Which is mostly compiler nonsense, I would say.

Random search on the warning gives: https://jeffpar.github.io/kbarchive/kb/168/Q168958/

Mac OS X support

How can I use the code in Xcode on Mac? If there is a way of course

GLFW Compilation Error

I am aware support for Linux is not available as of yet, but I tried to build it anyways and got a GLFW compilation related error.

==== Building GLFW (debug) ====
context.c
In file included from src/context.c:28:
src/internal.h:193:3: error: #error "No supported window creation API selected"
  #error "No supported window creation API selected"
   ^~~~~
src/internal.h:356:5: error: expected specifier-qualifier-list before ‘_GLFW_PLATFORM_CONTEXT_STATE’
     _GLFW_PLATFORM_CONTEXT_STATE;
     ^~~~~~~~~~~~~~~~~~~~~~~~~~~~
src/internal.h:417:5: error: expected specifier-qualifier-list before ‘_GLFW_PLATFORM_WINDOW_STATE’
     _GLFW_PLATFORM_WINDOW_STATE;
     ^~~~~~~~~~~~~~~~~~~~~~~~~~~
src/internal.h:441:5: error: expected specifier-qualifier-list before ‘_GLFW_PLATFORM_MONITOR_STATE’
     _GLFW_PLATFORM_MONITOR_STATE;
     ^~~~~~~~~~~~~~~~~~~~~~~~~~~~
src/internal.h:451:5: error: expected specifier-qualifier-list before ‘_GLFW_PLATFORM_CURSOR_STATE’
     _GLFW_PLATFORM_CURSOR_STATE;
     ^~~~~~~~~~~~~~~~~~~~~~~~~~~
src/internal.h:491:5: error: expected specifier-qualifier-list before ‘_GLFW_PLATFORM_JOYSTICK_STATE’
     _GLFW_PLATFORM_JOYSTICK_STATE;
     ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~
src/internal.h:499:5: error: expected specifier-qualifier-list before ‘_GLFW_PLATFORM_TLS_STATE’
     _GLFW_PLATFORM_TLS_STATE;
     ^~~~~~~~~~~~~~~~~~~~~~~~
src/internal.h:507:5: error: expected specifier-qualifier-list before ‘_GLFW_PLATFORM_MUTEX_STATE’
     _GLFW_PLATFORM_MUTEX_STATE;
     ^~~~~~~~~~~~~~~~~~~~~~~~~~
src/internal.h:542:9: error: expected specifier-qualifier-list before ‘_GLFW_PLATFORM_LIBRARY_TIMER_STATE’
         _GLFW_PLATFORM_LIBRARY_TIMER_STATE;
         ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
src/internal.h:572:5: error: expected specifier-qualifier-list before ‘_GLFW_PLATFORM_LIBRARY_WINDOW_STATE’
     _GLFW_PLATFORM_LIBRARY_WINDOW_STATE;
     ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
make[1]: *** [Makefile:161: bin-int/Debug-linux-x86_64/GLFW/context.o] Error 1
make: *** [Makefile:44: GLFW] Error 2

Doing some research, I need to define the _GLFW_X11 macro for linux but I'm not sure where it should be placed in the premake.lua file.

OpenGL deprecated on macOS

I know I am writing this a little ahead, but I think I've heard in one of @TheCherno videos that he was going to use OpenGL for the game engine. Along with OpenGL he wanted the engine to have cross platform support. As of MacOS 10.14 OpenGL has been deprecated. They have frozen the state of OpenGL for now. All I recommend is using the Vulkan API or some other alternatives.

MacOS What's New

Edit 1: Changed Link to what's new

log the OpenGL errors

As mensioned in discord, currently we're not logging any openGL errors that could possible occur. To do this, I would recommend creating the same macro as Cherno did in his OpenGL series.

Step 1: Creating the macro

In src/Platform/OpenGL/ create a new file OpenGLMacro.h where the macro is defined. We do it in the OpenGL folder as it is OpenGL specific:

// OpenGLMacro.h
#pragma once
#include "Engine/Core.h"
#include "Engine/Log.h"

#include "glad/glad.h"

inline static void GLClearError() { while (glGetError() != GL_NO_ERROR); }

static bool GLLogCall(const char* function, const char* file, const int line)
{
    while (GLenum error = glGetError())
    {
        ENGINE_CORE_ERROR("[OpenGL] Error ({0}):", error);
        ENGINE_CORE_ERROR("[OpenGL]     in function {0}", function);
        ENGINE_CORE_ERROR("[OpenGL]     at {0} ({1})", file, line);
        return false;
    }
    return true;
}

#if defined ENGINE_DEBUG
    #define GLCall(x) GLClearError();\
                      x;\
                      ENGINE_CORE_ASSERT(GLLogCall(#x, __FILE__, __LINE__), "OpenGL Error!")
#else
    #define GLCall(x) x
#endif

As described in Cherno's video, the macro wraps two functions around the actual call:

  • GLClearError() before the function call to clear all previous errors
  • GLLogCall(...) after the function to log any errors.

NOTE: ENGINE_CORE_ASSERT currently does not call the function outside the debug configuration, which is here not an issue as the GLCall macro is only defined inside the debug configuration.

When ENGINE_DEBUG is not defined, GLCall will just call the function without any other fuctions wrapped around it.

Step 2: Using the macro

In every OpenGl cpp file (inside src/Platform/OpenGL/) we include the OpenGLMacro.h and add GLCall() around each raw OpenGL call.

For example in src/Platform/OpenGL/OpenGLBuffer.cpp line 1-15::

#include "hzpch.h"
#include "OpenGLBuffer.h"

#include <glad/glad.h>

namespace Hazel {

	/////////////////////////////////////////////////////////////////////////////
	// VertexBuffer /////////////////////////////////////////////////////////////
	/////////////////////////////////////////////////////////////////////////////

	OpenGLVertexBuffer::OpenGLVertexBuffer(float* vertices, uint32_t size)
	{
		glCreateBuffers(1, &m_RendererID);

becomes

#include "hzpch.h"
#include "OpenGLBuffer.h"
#include "OpenGLMacro.h"

#include <glad/glad.h>

namespace Hazel {

	/////////////////////////////////////////////////////////////////////////////
	// VertexBuffer /////////////////////////////////////////////////////////////
	/////////////////////////////////////////////////////////////////////////////

	OpenGLVertexBuffer::OpenGLVertexBuffer(float* vertices, uint32_t size)
	{
		GLCall(glCreateBuffers(1, &m_RendererID));

NOTE: This could also be added in the current shader class implementation, but I would leave that out until the Shader class is abstracted to an OpenGLShader

Bug closing the gui with WindowsWindow.h Events

If you implement the events in WindowsWindow.h like in the tutorial, I discovered that if you not click the standard close button but the minimize or maximize button the application gets shutdown as well. Same for resizing the window on the top side. Any idea why this happens?

Memory leak in layerstack

Found a huge memory leak which is cause by ImGui as we do not shut everything down.
Inside LayerStack destructor we need to make sure that OnDetach is called.

LayerStack::~LayerStack()
{
	for (Layer* layer : m_Layers)
	{
		layer->OnDetach();		// Just added this
		delete layer;
	}
}

Memory leak in Hazel?

This is what I had to say on the Discord:
image

I don't know what causes this and am still debugging it but I have managed to experience this memory leak 2 out of 10 runs in a row. This is a definite memory leak, just I can't find the root cause. I would love to discuss more of this with people and discover possible solutions, and I want to bring this to Cherno's attention.

Thanks.👍

Task list

  • Delete created shaders after created program (#126)
  • Delete created shaders after created program (#127)
  • Call GLFWterminate (#128)
  • Use scopes instead of raw pointers (#129)
  • Test if there are more leaks

EDIT by @LovelySanta: Added task list

Warnings from sub modules

When Cloning this repository and building, there are still some build warnings to do with some compiler options added in one of the submodules premake file. These warnings where removed in the static linking video when Cherno made a load of changes to all of the premake files. I think that the fix for this is Cherno simply pushing the changes he made to his forks of the libraries that we are using so that clean forks/clones contain the changes made to those premake files.
The Warnings in question are:

`3>------ Rebuild All started: Project: ImGui, Configuration: Release x64 ------
1>cl : Command line warning D9002 : ignoring unknown option '-std=c11'
1>cl : Command line warning D9002 : ignoring unknown option '-lgdi32'

Dependency Build Paths

At present the dependencies for the project (GLFW, GLAD and ImGui) are building into their own sub folders inside vendor.

I was unsure if this was intended or not, but in the case that it wasn't intended the following changes could be made to the dependencies premake5.lua files to fix the issue.

targetdir ("%{wks.basedir}/bin/" .. outputdir .. "/%{prj.name}")
objdir ("%{wks.basedir}/bin-int/" .. outputdir .. "/%{prj.name}")

A number of other changes could be made to their premake files as well to keep them in line with the main project's setup such as the staticruntime, runtime, symbols, systemversion "latest" and optimization options.

I can create pull requests for this change in the relevant repositories if anyone else thinks this is worth changing.

Avoid using std::function in event dispatcher for performance

Currently Hazel is using std::function as the parameter to event dispatchers.

template<typename T>
bool Dispatch(EventFn<T> func)
{
if (m_Event.GetEventType() == T::GetStaticType())
{
m_Event.Handled = func(*(T*)&m_Event);
return true;
}
return false;
}

But as we all know, std::function uses type erasure under the hood, which renders this approach inefficient for high performance needs:

  1. The size of a class (in this case std::function<R(Ts...)>) is fixed at compile time, but since any kind of functor with the corresponding signature might be used to construct the std::function object, dynamic allocations may happen. Furthermore, if the functor passed is big (e.g. a lambda with several captures by value), it also needs to copy a large chunk of memory. But all these aren't necessary.

  2. Modern compilers can be really good at inlining trivial function calls, like when we pass a rather simple lambda to a consumer function which calls the lambda in some way, the call might be inlined thus done without overhead. But with the type erasure mechanism used by std::function, the compiler in most cases cannot make sense of all these weird things thus it cannot do inlining, which makes the case worse.

Therefore I propose a simple solution to this problem, just template on the type of the functor.

template <typename T, typename F>
bool Dispatch(const F& func)
{
    if (m_Event.GetEventType() == T::GetStaticType())
    {
        // BTW you can just simply cast the event reference to T&, no need for the addressing and dereferencing
        m_Event.Handled = func(static_cast<T&>(m_Event));  
        return true;
    }
    return false;
}

The F parameter can be deduced by the compiler and the user passes in T anyways.

Plus, for a better user interface, even the parameter T can be automatically deduced using some tricks:

namespace detail
{
    // These thing can get the parameter type T out of the lambda type F
    // The following two functions don't need to be implemented since only the function signatures are used
    template <typename F, typename T>
    T dispatch_helper(bool (F::*)(T&));
    template <typename F, typename T>
    T dispatch_helper(bool (F::*)(T&) const);
    template <typename F>
    using DispatchEventType = decltype(dispatch_helper(&F::operator()));
}
...
// The second template parameter SFINAE's out lambdas that are not event handlers
// So if you pass in just a random functor it will be a compile error, which is neat
template <typename F, typename = decltype(detail::DispatchEventType<F>::GetStaticType())>
bool Dispatch(F&& func)
{
    using T = detail::DispatchEventType<F>;  // Use the helper to get the parameter type
    if (m_Event.GetEventType() == T::GetStaticType())
    {
        m_Event.Handled = std::forward<F>(func)(static_cast<T&>(m_Event));
        return true;
    }
    return false;
}

And now everything is solved!

DLL export/import

I wonder why you do not use Boost.DLL?
I think that this is a better solution since the engine is to be multi-platform.
It is a simple solution to implement.

Build errors after enabling precompiled headers

After enabling precompiled headers from following through the video, when I ran the rebuild/build all command on my own fork of the project, I got a ton of errors and the build failed.
The same thing happens when I try to build the latest clone of this project.

The detailed build log for Hazel can be found at:
hazel_build

I get the exact same errors when building my own fork of Hazel.

Removing ImGui

Hi,
I was trying to remove ImGui in replace of my own GUI library, however, when the file ImGuiBuild.cpp is removed it throws this error:
vsscanferror
Or, in text:
LNK2019
unresolved external symbol __imp___stdio_common_vsscanf referenced in function _vsscanf_s_l
Project: Sandbox
File: glad.lib(glad.c.obj)
Line: 1

And, the error is irreversible, in the sense that once it occurs, if you add the file back again, the error stays. There is no way (that I can tell) to get rid of the error once you get it, other than reverting to a backup. An interesting thing to note is that the error is occurring in the Sandbox project, and that Hazel itself builds completely fine.

Update Premake to compile alpha 14 frome source

The current Premake in this repo is the version 5.0.0-alpha13 that doesnt support VS2019 solutions, please update this to alpha 14. Btw in my fork of Hazel i updated this and everything works fine on VS2019 solutions.

Using default destructors over empty ones

You are using empty destructors for your interfaces. This is potentially performance bug since class which is not std::is_trivially_destructible<A>::value. This is usually not a problem, but IMHO it is better to explicitly use default instead of empty destructors. Example of it is Window class.

Vendor folder not present

I have noticed that the vendor folder, at the solution's root is missing. It's the folder supposed to contain premake5.exe, which gets called by the GenerateProjects.bat file, in order to create the Visual Studio project files. I was curious whether it's like this on purpose, or whether the .gitignore hides it, by accident, by specifying bin/ as an ignored directory.
Without the premake executable, you have to download it and then put it in the required folder, in order to be able to generate the project files.

Templates for Issues & Pull requests

Hi TheCherno,

In your last video "Pull Requests" you briefly talked about better-structured pull requests. I think Github's feature for Issue templates is the perfect solution. You probably know what I'm talking about, but for everyone else here is a link to the official documentation.

TLDR:
We need to create a file under $REPO/.github/ which will be a template for every new Issue opened. Quickstart can be found here

This example would be a great starting point for the Issue template. It's from a Golang project that I have worked on. We could drop some of the Prerequisites & adapt the Info section for the C++ environment.

Grettings,
Toby

forking issues

well im by no mean a git expert but forking the project from an updated repository gives me an outdated version of it (on my local repository) and i dont seem to figure out how to fix that.
anyone here who have been through the same issue can fix ?

Dedicated branch for Pull Requests

Hello.
There will be definitely more pull requests as the project grows. I think it looks cleaner just to have a dedicated branch for pull requests. Then, later on, it can be merged into master.

Maybe call it nightly or something.

Cheers.

linux support

hi @TheCherno !
was wondering if this project will also be suitable for linux.
i honestly just cant afford a decent windows laptop.

Best,
Andrew

gcc compile glfw makefile error "'cc' is not recognized as an internal or external command, operable program or batch file."

Hi,

I'm trying to set the project up with gcc, but when I try to compile the glfw makefile generated with the premake script in the forked repository, I get the error "'cc' is not recognized as an internal or external command, operable program or batch file.". However, it compiles fine if I generate visual studio files and compile with visual studio.

I'm on windows 10, using cygwin to compile with gcc version 7.4.0.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.