Merge pull request #338 from DigitalPulseSoftware/nazara-next

Move Nazara-Next to the master branch
This commit is contained in:
Jérôme Leclercq 2021-06-20 17:54:16 +02:00 committed by GitHub
commit d2892b47e7
2499 changed files with 139571 additions and 333870 deletions

83
.github/workflows/linux-build.yml vendored Normal file
View File

@ -0,0 +1,83 @@
name: Linux-Build
on:
pull_request:
push:
paths-ignore:
- '.github/workflows/windows-build.yml'
- '.gitignore'
- 'LICENSE'
- 'CHANGELOG.md'
- 'README.md'
- 'README_en.md'
- 'README_fr.md'
jobs:
build:
strategy:
matrix:
os: [ubuntu-20.04]
arch: [x64]
mode: [debug, releasedbg]
runs-on: ${{ matrix.os }}
if: "!contains(github.event.head_commit.message, 'ci skip')"
steps:
- uses: actions/checkout@v2
# Install Qt (required for shader nodes editor)
- name: Install Qt
uses: jurplel/install-qt-action@v2
# Install Nazara dependencies
- name: Update apt repositories
run: sudo apt-get update
# Install Nazara dependencies
- name: Install system dependencies
run: sudo apt-get install libsndfile1-dev libfreetype6-dev libsdl2-dev mesa-common-dev libxcb-ewmh-dev libxcb-randr0-dev libxcb-icccm4-dev libxcb-keysyms1-dev libgl1-mesa-dev -y
# Force xmake to a specific folder (for cache)
- name: Set xmake env
run: echo "XMAKE_GLOBALDIR=${{ runner.workspace }}/xmake-global" >> $GITHUB_ENV
# Install xmake
- name: Setup xmake
uses: xmake-io/github-action-setup-xmake@v1
with:
xmake-version: branch@dev
# Update xmake repository (in order to have the file that will be cached)
- name: Update xmake repository
run: xmake repo --update
# Fetch xmake dephash
- name: Retrieve dependencies hash
id: dep_hash
run: echo "::set-output name=hash::$(xmake l utils.ci.packageskey)"
# Cache xmake dependencies
- name: Retrieve cached xmake dependencies
uses: actions/cache@v2
with:
path: ${{ env.XMAKE_GLOBALDIR }}/.xmake/packages
key: ${{ runner.os }}-${{ matrix.arch }}-${{ matrix.mode }}-${{ steps.dep_hash.outputs.hash }}
# Setup compilation mode and install project dependencies
- name: Configure xmake and install dependencies
run: xmake config --arch=${{ matrix.arch }} --mode=${{ matrix.mode }} --yes --verbose
# Build the engine
- name: Build Nazara
run: xmake
# Install the result files
- name: Install Nazara
run: xmake install -vo package
# Upload artifacts
- uses: actions/upload-artifact@v2
with:
name: ${{ matrix.os }}-${{ matrix.arch }}-${{ matrix.mode }}
path: package

75
.github/workflows/windows-build.yml vendored Normal file
View File

@ -0,0 +1,75 @@
name: Windows-Build
on:
pull_request:
push:
paths-ignore:
- '.github/workflows/linux-build.yml'
- '.gitignore'
- 'LICENSE'
- 'CHANGELOG.md'
- 'README.md'
- 'README_en.md'
- 'README_fr.md'
jobs:
build:
strategy:
matrix:
os: [windows-latest]
arch: [x64]
mode: [debug, releasedbg]
runs-on: ${{ matrix.os }}
if: "!contains(github.event.head_commit.message, 'ci skip')"
steps:
- uses: actions/checkout@v2
# Install Qt (required for shader nodes editor)
- name: Install Qt
uses: jurplel/install-qt-action@v2
# Force xmake to a specific folder (for cache)
- name: Set xmake env
run: echo "XMAKE_GLOBALDIR=${{ runner.workspace }}/xmake-global" | Out-File -FilePath $env:GITHUB_ENV -Encoding utf8 -Append
# Install xmake
- name: Setup xmake
uses: xmake-io/github-action-setup-xmake@v1
with:
xmake-version: branch@dev
# Update xmake repository (in order to have the file that will be cached)
- name: Update xmake repository
run: xmake.exe repo --update
# Fetch xmake dephash
- name: Retrieve dependencies hash
id: dep_hash
run: echo "::set-output name=hash::$(xmake.exe l utils.ci.packageskey)"
# Cache xmake dependencies
- name: Retrieve cached xmake dependencies
uses: actions/cache@v2
with:
path: ${{ env.XMAKE_GLOBALDIR }}\.xmake\packages
key: ${{ runner.os }}-${{ matrix.arch }}-${{ matrix.mode }}-${{ steps.dep_hash.outputs.hash }}
# Setup compilation mode and install project dependencies
- name: Configure xmake and install dependencies
run: xmake.exe config --arch=${{ matrix.arch }} --mode=${{ matrix.mode }} --yes --verbose
# Build the engine
- name: Build Nazara
run: xmake.exe
# Install the result files
- name: Install Nazara
run: xmake.exe install -vo package
# Upload artifacts
- uses: actions/upload-artifact@v2
with:
name: ${{ matrix.os }}-${{ matrix.arch }}-${{ matrix.mode }}
path: package

20
.gitignore vendored
View File

@ -1,5 +1,19 @@
# Nazara build
build/config.lua
# xmake-related files
.xmake/*
.vs/*
.vscode/*
CMakeLists.txt
Makefile
vs/*
vsxmake*/*
# Nazara binaries
bin/*
!bin/resources
!bin/resources/*
# Build files
build/*
# Nazara libraries
lib/*
@ -166,5 +180,3 @@ DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
build/gmake/

View File

@ -1,26 +0,0 @@
language:
cpp
sudo:
required
notifications:
email: true
services:
- docker
before_install:
- docker build -t nazara .
script:
- docker run --name Nazara -v `pwd`:/NazaraEngine nazara
sh -c "
cd build &&
./premake5-linux64 --cc=clang gmake &&
cd gmake &&
make -j4 &&
cd ../../tests &&
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:../lib/gmake/x64/:../extlibs/lib/gmake/x64/ &&
./NazaraUnitTestsServer
"

View File

@ -1,6 +0,0 @@
FROM debian:buster
RUN apt-get update && apt-get install -y build-essential clang libopenal-dev libsndfile1-dev libfreetype6-dev libassimp-dev libsdl2-dev libxcb-keysyms1-dev libxcb-ewmh-dev libx11-dev libfreetype6-dev mesa-common-dev libgl1-mesa-dev
RUN mkdir /NazaraEngine
WORKDIR /NazaraEngine

View File

@ -1,15 +0,0 @@
MODULE.Name = "ModuleName"
MODULE.Libraries = {
"NazaraCore"
}
MODULE.OsFiles.Windows = {
"../src/Nazara/ModuleName/Win32/**.hpp",
"../src/Nazara/ModuleName/Win32/**.cpp"
}
MODULE.OsFiles.Posix = {
"../src/Nazara/ModuleName/Posix/**.hpp",
"../src/Nazara/ModuleName/Posix/**.cpp"
}

View File

@ -1,28 +0,0 @@
// Copyright (C) YEAR AUTHORS
// This file is part of the "Nazara Engine - Module name"
// For conditions of distribution and use, see copyright notice in Config.hpp
#pragma once
#ifndef NAZARA_CLASSNAME_HPP
#define NAZARA_CLASSNAME_HPP
#include <Nazara/ModuleName/Config.hpp>
namespace Nz
{
class NAZARA_MODULENAME_API ClassName
{
public:
ClassName();
int GetAttribute() const;
void SetAttribute(int attribute);
private:
int m_attribute;
};
}
#endif // NAZARA_CLASSNAME_HPP

View File

@ -1,33 +0,0 @@
// Copyright (C) YEAR AUTHORS
// This file is part of the "Nazara Engine - Module name"
// For conditions of distribution and use, see copyright notice in Config.hpp
#pragma once
#ifndef NAZARA_MODULENAME_HPP
#define NAZARA_MODULENAME_HPP
#include <Nazara/Prerequisites.hpp>
#include <Nazara/Core/Initializer.hpp>
#include <Nazara/ModuleName/Config.hpp>
namespace Nz
{
class NAZARA_MODULENAME_API ModuleName
{
public:
ModuleName() = delete;
~ModuleName() = delete;
static bool Initialize();
static bool IsInitialized();
static void Uninitialize();
private:
static unsigned int s_moduleReferenceCounter;
};
}
#endif // NAZARA_MODULENAME_HPP

View File

@ -1,25 +0,0 @@
// Copyright (C) YEAR AUTHORS
// This file is part of the "Nazara Engine - Module name"
// For conditions of distribution and use, see copyright notice in Config.hpp
#include <Nazara/ModuleName/ClassName.hpp>
#include <Nazara/ModuleName/Debug.hpp>
namespace Nz
{
ClassName::ClassName() :
m_attribute(42)
{
}
int ClassName::GetAttribute() const
{
return m_attribute;
}
void ClassName::SetAttribute(int attribute)
{
m_attribute = attribute;
}
}

View File

@ -1,70 +0,0 @@
// Copyright (C) YEAR AUTHORS
// This file is part of the "Nazara Engine - Module name"
// For conditions of distribution and use, see copyright notice in Config.hpp
#include <Nazara/ModuleName/ModuleName.hpp>
#include <Nazara/Core/CallOnExit.hpp>
#include <Nazara/Core/Core.hpp>
#include <Nazara/Core/Error.hpp>
#include <Nazara/Core/Log.hpp>
#include <Nazara/ModuleName/Config.hpp>
#include <Nazara/ModuleName/Debug.hpp>
namespace Nz
{
bool ModuleName::Initialize()
{
if (s_moduleReferenceCounter > 0)
{
s_moduleReferenceCounter++;
return true; // Already initialized
}
// Initialize module dependencies
if (!Core::Initialize())
{
NazaraError("Failed to initialize core module");
return false;
}
s_moduleReferenceCounter++;
CallOnExit onExit(ModuleName::Uninitialize);
// Initialize module here
onExit.Reset();
NazaraNotice("Initialized: ModuleName module");
return true;
}
bool ModuleName::IsInitialized()
{
return s_moduleReferenceCounter != 0;
}
void ModuleName::Uninitialize()
{
if (s_moduleReferenceCounter != 1)
{
// Either the module is not initialized, either it was initialized multiple times
if (s_moduleReferenceCounter > 1)
s_moduleReferenceCounter--;
return;
}
s_moduleReferenceCounter = 0;
// Uninitialize module here
NazaraNotice("Uninitialized: ModuleName module");
// Free module dependencies
Core::Uninitialize();
}
unsigned int ModuleName::s_moduleReferenceCounter = 0;
}

View File

@ -1,151 +0,0 @@
// Copyright (C) 2017 Jérôme Leclercq
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequisites.hpp
#pragma once
#ifndef NDK_APPLICATION_HPP
#define NDK_APPLICATION_HPP
#include <NDK/Prerequisites.hpp>
#include <NDK/World.hpp>
#include <Nazara/Core/Clock.hpp>
#include <map>
#include <list>
#include <set>
#ifndef NDK_SERVER
#include <NDK/Canvas.hpp>
#include <NDK/Console.hpp>
#include <Nazara/Core/Log.hpp>
#include <Nazara/Lua/LuaInstance.hpp>
#include <Nazara/Graphics/TextSprite.hpp>
#include <Nazara/Renderer/RenderTarget.hpp>
#include <Nazara/Platform/Window.hpp>
#endif
namespace Ndk
{
class NDK_API Application
{
public:
#ifndef NDK_SERVER
struct ConsoleOverlay;
struct FPSCounterOverlay;
#endif
inline Application();
Application(int argc, char* argv[]);
Application(const Application&) = delete;
Application(Application&&) = delete;
inline ~Application();
#ifndef NDK_SERVER
template<typename T, typename... Args> T& AddWindow(Args&&... args);
#endif
template<typename... Args> World& AddWorld(Args&&... args);
#ifndef NDK_SERVER
inline void EnableConsole(bool enable);
inline void EnableFPSCounter(bool enable);
inline ConsoleOverlay& GetConsoleOverlay(std::size_t windowIndex = 0U);
inline FPSCounterOverlay& GetFPSCounterOverlay(std::size_t windowIndex = 0U);
#endif
inline const std::set<Nz::String>& GetOptions() const;
inline const std::map<Nz::String, Nz::String>& GetParameters() const;
inline float GetUpdateTime() const;
inline bool HasOption(const Nz::String& option) const;
inline bool HasParameter(const Nz::String& key, Nz::String* value) const;
#ifndef NDK_SERVER
inline bool IsConsoleEnabled() const;
inline bool IsFPSCounterEnabled() const;
#endif
bool Run();
#ifndef NDK_SERVER
inline void MakeExitOnLastWindowClosed(bool exitOnClosedWindows);
#endif
inline void Quit();
Application& operator=(const Application&) = delete;
Application& operator=(Application&&) = delete;
inline static Application* Instance();
#ifndef NDK_SERVER
struct ConsoleOverlay
{
Console* console;
Nz::LuaInstance lua;
NazaraSlot(Nz::EventHandler, OnEvent, eventSlot);
NazaraSlot(Nz::EventHandler, OnKeyPressed, keyPressedSlot);
NazaraSlot(Nz::RenderTarget, OnRenderTargetSizeChange, resizedSlot);
NazaraSlot(Nz::Log, OnLogWrite, logSlot);
};
struct FPSCounterOverlay
{
Nz::TextSpriteRef sprite;
EntityOwner entity;
float elapsedTime = 0.f;
unsigned int frameCount = 0;
};
#endif
private:
#ifndef NDK_SERVER
enum OverlayFlags
{
OverlayFlags_Console = 0x1,
OverlayFlags_FPSCounter = 0x2
};
struct WindowInfo
{
inline WindowInfo(std::unique_ptr<Nz::Window>&& window);
Nz::RenderTarget* renderTarget;
std::unique_ptr<Nz::Window> window;
std::unique_ptr<ConsoleOverlay> console;
std::unique_ptr<Canvas> canvas;
std::unique_ptr<FPSCounterOverlay> fpsCounter;
std::unique_ptr<World> overlayWorld;
};
void SetupConsole(WindowInfo& info);
void SetupFPSCounter(WindowInfo& info);
void SetupOverlay(WindowInfo& info);
template<typename T> void SetupWindow(WindowInfo& info, T* renderTarget, std::true_type /*isRenderTarget*/);
template<typename T> void SetupWindow(WindowInfo& /*info*/, T* /*renderTarget*/, std::false_type /*isNotRenderTarget*/);
std::vector<WindowInfo> m_windows;
#endif
std::map<Nz::String, Nz::String> m_parameters;
std::set<Nz::String> m_options;
std::list<World> m_worlds;
Nz::Clock m_updateClock;
#ifndef NDK_SERVER
Nz::UInt32 m_overlayFlags;
bool m_exitOnClosedWindows;
#endif
bool m_shouldQuit;
float m_updateTime;
static Application* s_application;
};
}
#include <NDK/Application.inl>
#endif // NDK_APPLICATION_HPP

View File

@ -1,379 +0,0 @@
// Copyright (C) 2017 Jérôme Leclercq
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequisites.hpp
#include <Nazara/Core/ErrorFlags.hpp>
#include <NDK/Sdk.hpp>
namespace Ndk
{
/*!
* \brief Constructs an Application object without passing command-line arguments
*
* This calls Sdk::Initialize()
*
* \remark Only one Application instance can exist at a time
*/
inline Application::Application() :
#ifndef NDK_SERVER
m_overlayFlags(0U),
m_exitOnClosedWindows(true),
#endif
m_shouldQuit(false),
m_updateTime(0.f)
{
NazaraAssert(s_application == nullptr, "You can create only one application instance per program");
s_application = this;
Nz::ErrorFlags errFlags(Nz::ErrorFlag_ThrowException, true);
// Initialisation du SDK
Sdk::Initialize();
}
/*!
* \brief Destructs the application object
*
* This destroy all worlds and windows and then calls Sdk::Uninitialize
*/
inline Application::~Application()
{
m_worlds.clear();
#ifndef NDK_SERVER
m_windows.clear();
#endif
// Free of SDK
Sdk::Uninitialize();
// Automatic free of modules
s_application = nullptr;
}
/*!
* \brief Adds a window to the application
* \return A reference to the newly created windows
*
* \param args Arguments used to create the window
*/
#ifndef NDK_SERVER
template<typename T, typename... Args>
T& Application::AddWindow(Args&&... args)
{
static_assert(std::is_base_of<Nz::Window, T>::value, "Type must inherit Window");
m_windows.emplace_back(std::make_unique<T>(std::forward<Args>(args)...));
WindowInfo& info = m_windows.back();
T& window = static_cast<T&>(*info.window.get()); //< Warning: ugly
SetupWindow(info, &window, std::is_base_of<Nz::RenderTarget, T>());
return window;
}
#endif
/*!
* \brief Adds a world to the application
* \return A reference to the newly created world
*
* \param args Arguments used to create the world
*/
template<typename... Args>
World& Application::AddWorld(Args&&... args)
{
m_worlds.emplace_back(std::forward<Args>(args)...);
return m_worlds.back();
}
/*!
* \brief Enable/disable debug console
*
* \param enable Should the console overlay be enabled
*/
#ifndef NDK_SERVER
inline void Application::EnableConsole(bool enable)
{
if (enable != ((m_overlayFlags & OverlayFlags_Console) != 0))
{
if (enable)
{
if (m_overlayFlags == 0)
{
for (WindowInfo& info : m_windows)
SetupOverlay(info);
}
for (WindowInfo& info : m_windows)
{
if (info.renderTarget)
SetupConsole(info);
}
m_overlayFlags |= OverlayFlags_Console;
}
else
{
for (WindowInfo& info : m_windows)
info.console.reset();
m_overlayFlags &= ~OverlayFlags_Console;
if (m_overlayFlags == 0)
{
for (WindowInfo& info : m_windows)
info.overlayWorld.reset();
}
}
}
}
#endif
/*!
* \brief Enable/disable debug FPS counter
*
* \param enable Should the FPS counter be displayed
*/
#ifndef NDK_SERVER
inline void Application::EnableFPSCounter(bool enable)
{
if (enable != ((m_overlayFlags & OverlayFlags_FPSCounter) != 0))
{
if (enable)
{
if (m_overlayFlags == 0)
{
for (WindowInfo& info : m_windows)
SetupOverlay(info);
}
for (WindowInfo& info : m_windows)
{
if (info.renderTarget)
SetupFPSCounter(info);
}
m_overlayFlags |= OverlayFlags_FPSCounter;
}
else
{
for (WindowInfo& info : m_windows)
info.fpsCounter.reset();
m_overlayFlags &= ~OverlayFlags_FPSCounter;
if (m_overlayFlags == 0)
{
for (WindowInfo& info : m_windows)
info.overlayWorld.reset();
}
}
}
}
#endif
/*!
* \brief Gets the console overlay for a specific window
*
* \param windowIndex Index of the window to get
*
* \remark The console overlay must be enabled
*
* \return A reference to the console overlay of the window
*
* \see IsConsoleOverlayEnabled
*/
#ifndef NDK_SERVER
inline Application::ConsoleOverlay& Application::GetConsoleOverlay(std::size_t windowIndex)
{
NazaraAssert(m_overlayFlags & OverlayFlags_Console, "Console overlay is not enabled");
NazaraAssert(windowIndex <= m_windows.size(), "Window index is out of range");
return *m_windows[windowIndex].console;
}
#endif
/*!
* \brief Gets the console overlay for a specific window
*
* \param windowIndex Index of the window to get
*
* \remark The console overlay must be enabled
*
* \return A reference to the console overlay of the window
*
* \see IsFPSCounterEnabled
*/
#ifndef NDK_SERVER
inline Application::FPSCounterOverlay& Application::GetFPSCounterOverlay(std::size_t windowIndex)
{
NazaraAssert(m_overlayFlags & OverlayFlags_FPSCounter, "FPS counter overlay is not enabled");
NazaraAssert(windowIndex <= m_windows.size(), "Window index is out of range");
return *m_windows[windowIndex].fpsCounter;
}
#endif
/*!
* \brief Gets the options used to start the application
*
* Options are defined as "-optionName" in command-line and are always lower-case
*
* \return Command-line options
*/
inline const std::set<Nz::String>& Application::GetOptions() const
{
return m_options;
}
/*!
* \brief Gets the parameters used to start the application
*
* Parameters are defined as "-key=value" in command-line, their key is lower-case but value capitals are kept.
*
* \return Command-line parameters
*/
inline const std::map<Nz::String, Nz::String>& Application::GetParameters() const
{
return m_parameters;
}
/*!
* \brief Gets the update time of the application
* \return Update rate
*/
inline float Application::GetUpdateTime() const
{
return m_updateTime;
}
/*!
* \brief Query for a command-line option
*
* \param option Option name
*
* \remark option must be lower-case
*
* \return True if option is present
*
* \see GetOptions
*/
inline bool Application::HasOption(const Nz::String& option) const
{
return m_options.count(option) != 0;
}
/*!
* \brief Query for a command-line option
*
* \param key Parameter name
* \param value Optional string to receive the parameter value
*
* \remark key must be lower-case
*
* \return True if parameter is present
*
* \see GetParameters
*/
inline bool Application::HasParameter(const Nz::String& key, Nz::String* value) const
{
auto it = m_parameters.find(key);
if (it == m_parameters.end())
return false;
if (value)
*value = it->second;
return true;
}
/*!
* \brief Checks if the console overlay is enabled
*
* \remark This has nothing to do with the visibility state of the console
*
* \return True if the console overlay is enabled
*
* \see GetConsoleOverlay
*/
#ifndef NDK_SERVER
inline bool Application::IsConsoleEnabled() const
{
return (m_overlayFlags & OverlayFlags_Console) != 0;
}
#endif
/*!
* \brief Checks if the FPS counter overlay is enabled
* \return True if the FPS counter overlay is enabled
*
* \see GetFPSCounterOverlay
*/
#ifndef NDK_SERVER
inline bool Application::IsFPSCounterEnabled() const
{
return (m_overlayFlags & OverlayFlags_FPSCounter) != 0;
}
#endif
/*!
* \brief Makes the application exit when there's no more open window
*
* \param exitOnClosedWindows Should exit be called when no more window is open
*/
#ifndef NDK_SERVER
inline void Application::MakeExitOnLastWindowClosed(bool exitOnClosedWindows)
{
m_exitOnClosedWindows = exitOnClosedWindows;
}
#endif
/*!
* \brief Quits the application
*/
inline void Application::Quit()
{
m_shouldQuit = true;
}
/*!
* \brief Gets the singleton instance of the application
* \return Singleton application
*/
inline Application* Application::Instance()
{
return s_application;
}
#ifndef NDK_SERVER
template<typename T>
inline void Application::SetupWindow(WindowInfo& info, T* renderTarget, std::true_type)
{
info.renderTarget = renderTarget;
if (m_overlayFlags)
{
SetupOverlay(info);
if (m_overlayFlags & OverlayFlags_Console)
SetupConsole(info);
if (m_overlayFlags & OverlayFlags_FPSCounter)
SetupFPSCounter(info);
}
}
template<typename T>
inline void Application::SetupWindow(WindowInfo&, T*, std::false_type)
{
}
inline Application::WindowInfo::WindowInfo(std::unique_ptr<Nz::Window>&& windowPtr) :
renderTarget(nullptr),
window(std::move(windowPtr))
{
}
#endif
}

View File

@ -1,179 +0,0 @@
// Copyright (C) 2017 Jérôme Leclercq
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequisites.hpp
#pragma once
#ifndef NDK_BASEWIDGET_HPP
#define NDK_BASEWIDGET_HPP
#include <NDK/Prerequisites.hpp>
#include <NDK/Entity.hpp>
#include <NDK/EntityOwner.hpp>
#include <NDK/World.hpp>
#include <Nazara/Graphics/Sprite.hpp>
#include <Nazara/Platform/Event.hpp>
#include <Nazara/Platform/Mouse.hpp>
#include <Nazara/Utility/Node.hpp>
#include <limits>
namespace Ndk
{
class Canvas;
class NDK_API BaseWidget : public Nz::Node
{
friend Canvas;
public:
BaseWidget(BaseWidget* parent);
BaseWidget(const BaseWidget&) = delete;
BaseWidget(BaseWidget&&) = delete;
virtual ~BaseWidget();
template<typename T, typename... Args> T* Add(Args&&... args);
inline void AddChild(std::unique_ptr<BaseWidget>&& widget);
inline void Center();
inline void CenterHorizontal();
inline void CenterVertical();
void ClearFocus();
inline void ClearRenderingRect();
void Destroy();
void EnableBackground(bool enable);
template<typename F> void ForEachWidgetChild(F iterator);
template<typename F> void ForEachWidgetChild(F iterator) const;
//virtual BaseWidget* Clone() const = 0;
inline const Nz::Color& GetBackgroundColor() const;
inline Canvas* GetCanvas();
inline Nz::SystemCursor GetCursor() const;
inline float GetHeight() const;
inline float GetMaximumHeight() const;
inline Nz::Vector2f GetMaximumSize() const;
inline float GetMaximumWidth() const;
inline float GetMinimumHeight() const;
inline Nz::Vector2f GetMinimumSize() const;
inline float GetMinimumWidth() const;
inline float GetPreferredHeight() const;
inline Nz::Vector2f GetPreferredSize() const;
inline float GetPreferredWidth() const;
inline const Nz::Rectf& GetRenderingRect() const;
inline Nz::Vector2f GetSize() const;
inline float GetWidth() const;
inline std::size_t GetWidgetChildCount() const;
bool HasFocus() const;
inline void Hide();
inline bool IsVisible() const;
void Resize(const Nz::Vector2f& size);
void SetBackgroundColor(const Nz::Color& color);
void SetCursor(Nz::SystemCursor systemCursor);
void SetFocus();
void SetParent(BaseWidget* widget);
inline void SetFixedHeight(float fixedHeight);
inline void SetFixedSize(const Nz::Vector2f& fixedSize);
inline void SetFixedWidth(float fixedWidth);
inline void SetMaximumHeight(float maximumHeight);
inline void SetMaximumSize(const Nz::Vector2f& maximumSize);
inline void SetMaximumWidth(float maximumWidth);
inline void SetMinimumHeight(float minimumHeight);
inline void SetMinimumSize(const Nz::Vector2f& minimumSize);
inline void SetMinimumWidth(float minimumWidth);
virtual void SetRenderingRect(const Nz::Rectf& renderingRect);
void Show(bool show = true);
BaseWidget& operator=(const BaseWidget&) = delete;
BaseWidget& operator=(BaseWidget&&) = delete;
protected:
const EntityHandle& CreateEntity();
void DestroyEntity(Entity* entity);
virtual void Layout();
void InvalidateNode() override;
Nz::Rectf GetScissorRect() const;
virtual bool IsFocusable() const;
virtual void OnFocusLost();
virtual void OnFocusReceived();
virtual bool OnKeyPressed(const Nz::WindowEvent::KeyEvent& key);
virtual void OnKeyReleased(const Nz::WindowEvent::KeyEvent& key);
virtual void OnMouseEnter();
virtual void OnMouseMoved(int x, int y, int deltaX, int deltaY);
virtual void OnMouseButtonPress(int x, int y, Nz::Mouse::Button button);
virtual void OnMouseButtonRelease(int x, int y, Nz::Mouse::Button button);
virtual void OnMouseWheelMoved(int x, int y, float delta);
virtual void OnMouseExit();
virtual void OnParentResized(const Nz::Vector2f& newSize);
virtual void OnTextEntered(char32_t character, bool repeated);
virtual void OnTextEdited(const std::array<char, 32>& characters, int length);
inline void SetPreferredSize(const Nz::Vector2f& preferredSize);
virtual void ShowChildren(bool show);
private:
inline BaseWidget();
void DestroyChild(BaseWidget* widget);
void DestroyChildren();
inline bool IsRegisteredToCanvas() const;
inline void NotifyParentResized(const Nz::Vector2f& newSize);
void RegisterToCanvas();
inline void UpdateCanvasIndex(std::size_t index);
void UnregisterFromCanvas();
void UpdatePositionAndSize();
struct WidgetEntity
{
EntityOwner handle;
bool isEnabled = true;
NazaraSlot(Ndk::Entity, OnEntityDisabled, onDisabledSlot);
NazaraSlot(Ndk::Entity, OnEntityEnabled, onEnabledSlot);
};
static constexpr std::size_t InvalidCanvasIndex = std::numeric_limits<std::size_t>::max();
std::size_t m_canvasIndex;
std::vector<WidgetEntity> m_entities;
std::vector<std::unique_ptr<BaseWidget>> m_children;
Canvas* m_canvas;
EntityOwner m_backgroundEntity;
WorldHandle m_world;
Nz::Color m_backgroundColor;
Nz::Rectf m_renderingRect;
Nz::SpriteRef m_backgroundSprite;
Nz::SystemCursor m_cursor;
Nz::Vector2f m_maximumSize;
Nz::Vector2f m_minimumSize;
Nz::Vector2f m_preferredSize;
Nz::Vector2f m_size;
BaseWidget* m_widgetParent;
bool m_visible;
};
}
#include <NDK/BaseWidget.inl>
#endif // NDK_BASEWIDGET_HPP

View File

@ -1,275 +0,0 @@
// Copyright (C) 2017 Jérôme Leclercq
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequisites.hpp
#include <NDK/BaseWidget.hpp>
#include <Nazara/Core/Error.hpp>
#include <Nazara/Math/Algorithm.hpp>
#include <limits>
namespace Ndk
{
inline BaseWidget::BaseWidget() :
m_canvasIndex(InvalidCanvasIndex),
m_canvas(nullptr),
m_backgroundColor(Nz::Color(230, 230, 230, 255)),
m_renderingRect(-std::numeric_limits<float>::infinity(), -std::numeric_limits<float>::infinity(), std::numeric_limits<float>::infinity(), std::numeric_limits<float>::infinity()),
m_cursor(Nz::SystemCursor_Default),
m_maximumSize(std::numeric_limits<float>::infinity()),
m_minimumSize(0.f),
m_preferredSize(-1),
m_size(50.f, 50.f),
m_widgetParent(nullptr),
m_visible(true)
{
}
template<typename T, typename... Args>
inline T* BaseWidget::Add(Args&&... args)
{
std::unique_ptr<T> widget = std::make_unique<T>(this, std::forward<Args>(args)...);
T* widgetPtr = widget.get();
AddChild(std::move(widget));
return widgetPtr;
}
inline void BaseWidget::AddChild(std::unique_ptr<BaseWidget>&& widget)
{
widget->Show(m_visible);
widget->SetParent(this);
m_children.emplace_back(std::move(widget));
}
inline void BaseWidget::Center()
{
NazaraAssert(m_widgetParent, "Widget has no parent");
Nz::Vector2f parentSize = m_widgetParent->GetSize();
Nz::Vector2f mySize = GetSize();
SetPosition((parentSize.x - mySize.x) / 2.f, (parentSize.y - mySize.y) / 2.f);
}
inline void BaseWidget::CenterHorizontal()
{
NazaraAssert(m_widgetParent, "Widget has no parent");
Nz::Vector2f parentSize = m_widgetParent->GetSize();
Nz::Vector2f mySize = GetSize();
SetPosition((parentSize.x - mySize.x) / 2.f, GetPosition(Nz::CoordSys_Local).y);
}
inline void BaseWidget::CenterVertical()
{
NazaraAssert(m_widgetParent, "Widget has no parent");
Nz::Vector2f parentSize = m_widgetParent->GetSize();
Nz::Vector2f mySize = GetSize();
SetPosition(GetPosition(Nz::CoordSys_Local).x, (parentSize.y - mySize.y) / 2.f);
}
inline void BaseWidget::ClearRenderingRect()
{
SetRenderingRect(Nz::Rectf(-std::numeric_limits<float>::infinity(), -std::numeric_limits<float>::infinity(), std::numeric_limits<float>::infinity(), std::numeric_limits<float>::infinity()));
}
template<typename F>
inline void BaseWidget::ForEachWidgetChild(F iterator)
{
for (const auto& child : m_children)
iterator(child.get());
}
template<typename F>
inline void BaseWidget::ForEachWidgetChild(F iterator) const
{
for (const auto& child : m_children)
iterator(static_cast<const BaseWidget*>(child.get()));
}
inline const Nz::Color& BaseWidget::GetBackgroundColor() const
{
return m_backgroundColor;
}
inline Canvas* BaseWidget::GetCanvas()
{
return m_canvas;
}
inline Nz::SystemCursor BaseWidget::GetCursor() const
{
return m_cursor;
}
inline float BaseWidget::GetHeight() const
{
return m_size.y;
}
inline float BaseWidget::GetMaximumHeight() const
{
return m_maximumSize.y;
}
inline Nz::Vector2f BaseWidget::GetMaximumSize() const
{
return m_maximumSize;
}
inline float BaseWidget::GetMaximumWidth() const
{
return m_maximumSize.x;
}
inline float BaseWidget::GetMinimumHeight() const
{
return m_minimumSize.y;
}
inline Nz::Vector2f BaseWidget::GetMinimumSize() const
{
return m_minimumSize;
}
inline float BaseWidget::GetMinimumWidth() const
{
return m_minimumSize.x;
}
inline float BaseWidget::GetPreferredHeight() const
{
return m_preferredSize.y;
}
inline Nz::Vector2f BaseWidget::GetPreferredSize() const
{
return m_preferredSize;
}
inline float BaseWidget::GetPreferredWidth() const
{
return m_preferredSize.x;
}
inline const Nz::Rectf& BaseWidget::GetRenderingRect() const
{
return m_renderingRect;
}
inline Nz::Vector2f BaseWidget::GetSize() const
{
return Nz::Vector2f(GetWidth(), GetHeight());
}
inline float BaseWidget::GetWidth() const
{
return m_size.x;
}
inline std::size_t BaseWidget::GetWidgetChildCount() const
{
return m_children.size();
}
inline void BaseWidget::Hide()
{
return Show(false);
}
inline bool BaseWidget::IsVisible() const
{
return m_visible;
}
inline void BaseWidget::SetFixedHeight(float fixedHeight)
{
SetMaximumHeight(fixedHeight);
SetMinimumHeight(fixedHeight);
}
inline void BaseWidget::SetFixedSize(const Nz::Vector2f& fixedSize)
{
SetMaximumSize(fixedSize);
SetMinimumSize(fixedSize);
}
inline void BaseWidget::SetFixedWidth(float fixedWidth)
{
SetMaximumWidth(fixedWidth);
SetMinimumWidth(fixedWidth);
}
inline void BaseWidget::SetMaximumHeight(float maximumHeight)
{
Nz::Vector2f maximumSize = GetMaximumSize();
maximumSize.y = maximumHeight;
SetMaximumSize(maximumSize);
}
inline void BaseWidget::SetMaximumSize(const Nz::Vector2f& maximumSize)
{
m_maximumSize = maximumSize;
Nz::Vector2f size = GetSize();
if (size.x > m_maximumSize.x || size.y > m_maximumSize.y)
Resize(size); //< Will clamp automatically
}
inline void BaseWidget::SetMaximumWidth(float maximumWidth)
{
Nz::Vector2f maximumSize = GetMaximumSize();
maximumSize.x = maximumWidth;
SetMaximumSize(maximumSize);
}
inline void BaseWidget::SetMinimumHeight(float minimumHeight)
{
Nz::Vector2f minimumSize = GetMinimumSize();
minimumSize.y = minimumHeight;
SetMinimumSize(minimumSize);
}
inline void BaseWidget::SetMinimumSize(const Nz::Vector2f& minimumSize)
{
m_minimumSize = minimumSize;
Nz::Vector2f size = GetSize();
if (size.x < m_minimumSize.x || size.y < m_minimumSize.y)
Resize(size); //< Will clamp automatically
}
inline void BaseWidget::SetMinimumWidth(float minimumWidth)
{
Nz::Vector2f minimumSize = GetMinimumSize();
minimumSize.x = minimumWidth;
SetMinimumSize(minimumSize);
}
inline void BaseWidget::SetPreferredSize(const Nz::Vector2f& preferredSize)
{
m_preferredSize = preferredSize;
//Resize(m_preferredSize);
}
inline bool BaseWidget::IsRegisteredToCanvas() const
{
return m_canvas && m_canvasIndex != InvalidCanvasIndex;
}
inline void BaseWidget::NotifyParentResized(const Nz::Vector2f& newSize)
{
for (const auto& widgetPtr : m_children)
widgetPtr->OnParentResized(newSize);
}
inline void BaseWidget::UpdateCanvasIndex(std::size_t index)
{
m_canvasIndex = index;
}
}

View File

@ -1,89 +0,0 @@
// Copyright (C) 2017 Jérôme Leclercq
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequisites.hpp
#pragma once
#ifndef NDK_CANVAS_HPP
#define NDK_CANVAS_HPP
#include <NDK/Prerequisites.hpp>
#include <NDK/BaseWidget.hpp>
#include <Nazara/Platform/CursorController.hpp>
#include <Nazara/Platform/EventHandler.hpp>
namespace Ndk
{
class NDK_API Canvas : public BaseWidget
{
friend BaseWidget;
public:
struct Padding;
inline Canvas(WorldHandle world, Nz::EventHandler& eventHandler, Nz::CursorControllerHandle cursorController);
Canvas(const Canvas&) = delete;
Canvas(Canvas&&) = delete;
inline ~Canvas();
inline const WorldHandle& GetWorld() const;
Canvas& operator=(const Canvas&) = delete;
Canvas& operator=(Canvas&&) = delete;
NazaraSignal(OnUnhandledKeyPressed, const Nz::EventHandler* /*eventHandler*/, const Nz::WindowEvent::KeyEvent& /*event*/);
NazaraSignal(OnUnhandledKeyReleased, const Nz::EventHandler* /*eventHandler*/, const Nz::WindowEvent::KeyEvent& /*event*/);
protected:
inline void ClearKeyboardOwner(std::size_t canvasIndex);
inline bool IsKeyboardOwner(std::size_t canvasIndex) const;
inline void NotifyWidgetBoxUpdate(std::size_t index);
inline void NotifyWidgetCursorUpdate(std::size_t index);
std::size_t RegisterWidget(BaseWidget* widget);
inline void SetKeyboardOwner(std::size_t canvasIndex);
void UnregisterWidget(std::size_t index);
private:
void OnEventMouseButtonPressed(const Nz::EventHandler* eventHandler, const Nz::WindowEvent::MouseButtonEvent& event);
void OnEventMouseButtonRelease(const Nz::EventHandler* eventHandler, const Nz::WindowEvent::MouseButtonEvent& event);
void OnEventMouseLeft(const Nz::EventHandler* eventHandler);
void OnEventMouseMoved(const Nz::EventHandler* eventHandler, const Nz::WindowEvent::MouseMoveEvent& event);
void OnEventMouseWheelMoved(const Nz::EventHandler* eventHandler, const Nz::WindowEvent::MouseWheelEvent& event);
void OnEventKeyPressed(const Nz::EventHandler* eventHandler, const Nz::WindowEvent::KeyEvent& event);
void OnEventKeyReleased(const Nz::EventHandler* eventHandler, const Nz::WindowEvent::KeyEvent& event);
void OnEventTextEntered(const Nz::EventHandler* eventHandler, const Nz::WindowEvent::TextEvent& event);
void OnEventTextEdited(const Nz::EventHandler* eventHandler, const Nz::WindowEvent::EditEvent& event);
struct WidgetEntry
{
BaseWidget* widget;
Nz::Boxf box;
Nz::SystemCursor cursor;
};
NazaraSlot(Nz::EventHandler, OnKeyPressed, m_keyPressedSlot);
NazaraSlot(Nz::EventHandler, OnKeyReleased, m_keyReleasedSlot);
NazaraSlot(Nz::EventHandler, OnMouseButtonPressed, m_mouseButtonPressedSlot);
NazaraSlot(Nz::EventHandler, OnMouseButtonReleased, m_mouseButtonReleasedSlot);
NazaraSlot(Nz::EventHandler, OnMouseLeft, m_mouseLeftSlot);
NazaraSlot(Nz::EventHandler, OnMouseMoved, m_mouseMovedSlot);
NazaraSlot(Nz::EventHandler, OnMouseWheelMoved, m_mouseWheelMovedSlot);
NazaraSlot(Nz::EventHandler, OnTextEntered, m_textEnteredSlot);
NazaraSlot(Nz::EventHandler, OnTextEdited, m_textEditedSlot);
std::size_t m_keyboardOwner;
std::size_t m_hoveredWidget;
std::vector<WidgetEntry> m_widgetEntries;
Nz::CursorControllerHandle m_cursorController;
WorldHandle m_world;
};
}
#include <NDK/Canvas.inl>
#endif // NDK_CANVAS_HPP

View File

@ -1,91 +0,0 @@
// Copyright (C) 2017 Jérôme Leclercq
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequisites.hpp
#include <NDK/Canvas.hpp>
#include <Nazara/Platform/Cursor.hpp>
namespace Ndk
{
inline Canvas::Canvas(WorldHandle world, Nz::EventHandler& eventHandler, Nz::CursorControllerHandle cursorController) :
m_keyboardOwner(InvalidCanvasIndex),
m_hoveredWidget(InvalidCanvasIndex),
m_cursorController(cursorController),
m_world(std::move(world))
{
m_canvas = this;
m_widgetParent = nullptr;
// Register ourselves as a widget to handle cursor change
RegisterToCanvas();
// Connect to every meaningful event
m_keyPressedSlot.Connect(eventHandler.OnKeyPressed, this, &Canvas::OnEventKeyPressed);
m_keyReleasedSlot.Connect(eventHandler.OnKeyReleased, this, &Canvas::OnEventKeyReleased);
m_mouseButtonPressedSlot.Connect(eventHandler.OnMouseButtonPressed, this, &Canvas::OnEventMouseButtonPressed);
m_mouseButtonReleasedSlot.Connect(eventHandler.OnMouseButtonReleased, this, &Canvas::OnEventMouseButtonRelease);
m_mouseLeftSlot.Connect(eventHandler.OnMouseLeft, this, &Canvas::OnEventMouseLeft);
m_mouseMovedSlot.Connect(eventHandler.OnMouseMoved, this, &Canvas::OnEventMouseMoved);
m_mouseWheelMovedSlot.Connect(eventHandler.OnMouseWheelMoved, this, &Canvas::OnEventMouseWheelMoved);
m_textEnteredSlot.Connect(eventHandler.OnTextEntered, this, &Canvas::OnEventTextEntered);
m_textEditedSlot.Connect(eventHandler.OnTextEdited, this, &Canvas::OnEventTextEdited);
}
inline Canvas::~Canvas()
{
// Destroy children explicitly because they signal us when getting destroyed, and that can't happen after our own destruction
DestroyChildren();
// Prevent our parent from trying to call us
m_canvasIndex = InvalidCanvasIndex;
}
inline const WorldHandle& Canvas::GetWorld() const
{
return m_world;
}
inline void Canvas::ClearKeyboardOwner(std::size_t canvasIndex)
{
if (m_keyboardOwner == canvasIndex)
SetKeyboardOwner(InvalidCanvasIndex);
}
inline bool Canvas::IsKeyboardOwner(std::size_t canvasIndex) const
{
return m_keyboardOwner == canvasIndex;
}
inline void Canvas::NotifyWidgetBoxUpdate(std::size_t index)
{
WidgetEntry& entry = m_widgetEntries[index];
Nz::Vector3f pos = entry.widget->GetPosition(Nz::CoordSys_Global);
Nz::Vector2f size = entry.widget->GetSize();
entry.box.Set(pos.x, pos.y, pos.z, size.x, size.y, 1.f);
}
inline void Canvas::NotifyWidgetCursorUpdate(std::size_t index)
{
WidgetEntry& entry = m_widgetEntries[index];
entry.cursor = entry.widget->GetCursor();
if (m_cursorController && m_hoveredWidget == index)
m_cursorController->UpdateCursor(Nz::Cursor::Get(entry.cursor));
}
inline void Canvas::SetKeyboardOwner(std::size_t canvasIndex)
{
if (m_keyboardOwner != canvasIndex)
{
if (m_keyboardOwner != InvalidCanvasIndex)
m_widgetEntries[m_keyboardOwner].widget->OnFocusLost();
m_keyboardOwner = canvasIndex;
if (m_keyboardOwner != InvalidCanvasIndex)
m_widgetEntries[m_keyboardOwner].widget->OnFocusReceived();
}
}
}

View File

@ -1,24 +0,0 @@
// This file was automatically generated
#pragma once
#ifndef NDK_COMPONENTS_GLOBAL_HPP
#define NDK_COMPONENTS_GLOBAL_HPP
#include <NDK/Components/CameraComponent.hpp>
#include <NDK/Components/CollisionComponent2D.hpp>
#include <NDK/Components/CollisionComponent3D.hpp>
#include <NDK/Components/ConstraintComponent2D.hpp>
#include <NDK/Components/DebugComponent.hpp>
#include <NDK/Components/GraphicsComponent.hpp>
#include <NDK/Components/LifetimeComponent.hpp>
#include <NDK/Components/LightComponent.hpp>
#include <NDK/Components/ListenerComponent.hpp>
#include <NDK/Components/NodeComponent.hpp>
#include <NDK/Components/ParticleEmitterComponent.hpp>
#include <NDK/Components/ParticleGroupComponent.hpp>
#include <NDK/Components/PhysicsComponent2D.hpp>
#include <NDK/Components/PhysicsComponent3D.hpp>
#include <NDK/Components/VelocityComponent.hpp>
#endif // NDK_COMPONENTS_GLOBAL_HPP

View File

@ -1,120 +0,0 @@
// Copyright (C) 2017 Jérôme Leclercq
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequisites.hpp
#pragma once
#ifndef NDK_SERVER
#ifndef NDK_COMPONENTS_CAMERACOMPONENT_HPP
#define NDK_COMPONENTS_CAMERACOMPONENT_HPP
#include <Nazara/Math/Frustum.hpp>
#include <Nazara/Math/Matrix4.hpp>
#include <Nazara/Math/Vector3.hpp>
#include <Nazara/Graphics/AbstractViewer.hpp>
#include <Nazara/Renderer/RenderTarget.hpp>
#include <Nazara/Utility/Node.hpp>
#include <NDK/Component.hpp>
namespace Ndk
{
class CameraComponent;
using CameraComponentHandle = Nz::ObjectHandle<CameraComponent>;
class NDK_API CameraComponent : public Component<CameraComponent>, public Nz::AbstractViewer
{
public:
inline CameraComponent();
inline CameraComponent(const CameraComponent& camera);
~CameraComponent() = default;
void ApplyView() const override;
inline void EnsureFrustumUpdate() const;
inline void EnsureProjectionMatrixUpdate() const;
inline void EnsureViewMatrixUpdate() const;
inline void EnsureViewportUpdate() const;
float GetAspectRatio() const override;
Nz::Vector3f GetEyePosition() const override;
Nz::Vector3f GetForward() const override;
inline float GetFOV() const;
const Nz::Frustumf& GetFrustum() const override;
inline unsigned int GetLayer() const;
const Nz::Matrix4f& GetProjectionMatrix() const override;
inline const Nz::Vector3f& GetProjectionScale() const;
Nz::ProjectionType GetProjectionType() const override;
inline const Nz::Vector2f& GetSize() const;
const Nz::RenderTarget* GetTarget() const override;
inline const Nz::Rectf& GetTargetRegion() const;
const Nz::Matrix4f& GetViewMatrix() const override;
const Nz::Recti& GetViewport() const override;
float GetZFar() const override;
float GetZNear() const override;
inline void SetFOV(float fov);
void SetLayer(unsigned int layer);
inline void SetProjectionScale(const Nz::Vector3f& scale);
inline void SetProjectionType(Nz::ProjectionType projection);
inline void SetSize(const Nz::Vector2f& size);
inline void SetSize(float width, float height);
inline void SetTarget(const Nz::RenderTarget* renderTarget);
inline void SetTargetRegion(const Nz::Rectf& region);
inline void SetViewport(const Nz::Recti& viewport);
inline void SetZFar(float zFar);
inline void SetZNear(float zNear);
inline bool UpdateVisibility(std::size_t visibilityHash);
static ComponentIndex componentIndex;
private:
inline void InvalidateFrustum() const;
inline void InvalidateProjectionMatrix() const;
inline void InvalidateViewMatrix() const;
inline void InvalidateViewport() const;
void OnAttached() override;
void OnComponentAttached(BaseComponent& component) override;
void OnComponentDetached(BaseComponent& component) override;
void OnDetached() override;
void OnNodeInvalidated(const Nz::Node* node);
void OnRenderTargetRelease(const Nz::RenderTarget* renderTarget);
void OnRenderTargetSizeChange(const Nz::RenderTarget* renderTarget);
void UpdateFrustum() const;
void UpdateProjectionMatrix() const;
void UpdateViewMatrix() const;
void UpdateViewport() const;
NazaraSlot(Nz::Node, OnNodeInvalidation, m_nodeInvalidationSlot);
NazaraSlot(Nz::RenderTarget, OnRenderTargetRelease, m_targetReleaseSlot);
NazaraSlot(Nz::RenderTarget, OnRenderTargetSizeChange, m_targetResizeSlot);
std::size_t m_visibilityHash;
Nz::ProjectionType m_projectionType;
mutable Nz::Frustumf m_frustum;
mutable Nz::Matrix4f m_projectionMatrix;
mutable Nz::Matrix4f m_viewMatrix;
Nz::Rectf m_targetRegion;
mutable Nz::Recti m_viewport;
const Nz::RenderTarget* m_target;
Nz::Vector2f m_size;
Nz::Vector3f m_projectionScale;
mutable bool m_frustumUpdated;
mutable bool m_projectionMatrixUpdated;
mutable bool m_viewMatrixUpdated;
mutable bool m_viewportUpdated;
mutable float m_aspectRatio;
float m_fov;
float m_zFar;
float m_zNear;
unsigned int m_layer;
};
}
#include <NDK/Components/CameraComponent.inl>
#endif // NDK_COMPONENTS_CAMERACOMPONENT_HPP
#endif // NDK_SERVER

View File

@ -1,353 +0,0 @@
// Copyright (C) 2017 Jérôme Leclercq
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequisites.hpp
#include <Nazara/Core/Error.hpp>
#include <Nazara/Math/Algorithm.hpp>
namespace Ndk
{
/*!
* \brief Constructs an CameraComponent object by default
*/
inline CameraComponent::CameraComponent() :
m_visibilityHash(0U),
m_projectionType(Nz::ProjectionType_Perspective),
m_targetRegion(0.f, 0.f, 1.f, 1.f),
m_target(nullptr),
m_size(0.f),
m_projectionScale(1.f, 1.f, 1.f),
m_frustumUpdated(false),
m_projectionMatrixUpdated(false),
m_viewMatrixUpdated(false),
m_viewportUpdated(false),
m_aspectRatio(0.f),
m_fov(70.f),
m_zFar(100.f),
m_zNear(1.f),
m_layer(0)
{
}
/*!
* \brief Constructs a CameraComponent object by copy semantic
*
* \param camera CameraComponent to copy
*/
inline CameraComponent::CameraComponent(const CameraComponent& camera) :
Component(camera),
AbstractViewer(camera),
m_visibilityHash(camera.m_visibilityHash),
m_projectionType(camera.m_projectionType),
m_targetRegion(camera.m_targetRegion),
m_target(nullptr),
m_size(camera.m_size),
m_projectionScale(camera.m_projectionScale),
m_frustumUpdated(false),
m_projectionMatrixUpdated(false),
m_viewMatrixUpdated(false),
m_viewportUpdated(false),
m_aspectRatio(camera.m_aspectRatio),
m_fov(camera.m_fov),
m_zFar(camera.m_zFar),
m_zNear(camera.m_zNear),
m_layer(camera.m_layer)
{
SetTarget(camera.m_target);
}
/*!
* \brief Ensures the frustum is up to date
*/
inline void CameraComponent::EnsureFrustumUpdate() const
{
if (!m_frustumUpdated)
UpdateFrustum();
}
/*!
* \brief Ensures the projection matrix is up to date
*/
inline void CameraComponent::EnsureProjectionMatrixUpdate() const
{
if (!m_projectionMatrixUpdated)
UpdateProjectionMatrix();
}
/*!
* \brief Ensures the view matrix is up to date
*/
inline void CameraComponent::EnsureViewMatrixUpdate() const
{
if (!m_viewMatrixUpdated)
UpdateViewMatrix();
}
/*!
* \brief Ensures the view port is up to date
*/
inline void CameraComponent::EnsureViewportUpdate() const
{
if (!m_viewportUpdated)
UpdateViewport();
}
/*!
* \brief Gets the field of view of the camera
* \return Field of view of the camera
*/
inline float CameraComponent::GetFOV() const
{
return m_fov;
}
/*!
* \brief Gets the layer of the camera
* \return Layer of the camera
*/
inline unsigned int CameraComponent::GetLayer() const
{
return m_layer;
}
/*!
* \brief Gets the projection scale of the camera
* \return Projection scale
*/
const Nz::Vector3f& CameraComponent::GetProjectionScale() const
{
return m_projectionScale;
}
/*!
* \brief Gets the size of the camera
* \return Size of the camera
*/
inline const Nz::Vector2f & CameraComponent::GetSize() const
{
return m_size;
}
/*!
* \brief Gets the target region of the camera
* \return A constant reference to the target region of the camera
*/
inline const Nz::Rectf& CameraComponent::GetTargetRegion() const
{
return m_targetRegion;
}
/*!
* \brief Sets the field of view of the camera
*
* \param fov Field of view of the camera
*
* \remark Produces a NazaraAssert if angle is zero
*/
inline void CameraComponent::SetFOV(float fov)
{
NazaraAssert(!Nz::NumberEquals(fov, 0.f), "FOV must be different from zero");
m_fov = fov;
InvalidateProjectionMatrix();
}
/*!
* \brief Sets the camera projection scale
*
* \param scale New projection scale
*/
inline void CameraComponent::SetProjectionScale(const Nz::Vector3f& scale)
{
m_projectionScale = scale;
InvalidateProjectionMatrix();
}
/*!
* \brief Sets the projection type of the camera
*
* \param projectionType Projection type of the camera
*/
inline void CameraComponent::SetProjectionType(Nz::ProjectionType projectionType)
{
m_projectionType = projectionType;
InvalidateProjectionMatrix();
}
/*!
* \brief Sets the size of the camera
*
* \param size Size of the camera
*/
inline void CameraComponent::SetSize(const Nz::Vector2f& size)
{
m_size = size;
InvalidateProjectionMatrix();
}
/*!
* \brief Sets the size of the camera
*
* \param width Size in X of the camera
* \param height Size in Y of the camera
*/
inline void CameraComponent::SetSize(float width, float height)
{
SetSize({width, height});
}
/*!
* \brief Sets the target of the camera
*
* \param renderTarget A constant reference to the render target of the camera
*/
inline void CameraComponent::SetTarget(const Nz::RenderTarget* renderTarget)
{
m_target = renderTarget;
if (m_target)
{
m_targetResizeSlot.Connect(m_target->OnRenderTargetSizeChange, this, &CameraComponent::OnRenderTargetSizeChange);
m_targetReleaseSlot.Connect(m_target->OnRenderTargetRelease, this, &CameraComponent::OnRenderTargetRelease);
}
else
{
m_targetResizeSlot.Disconnect();
m_targetReleaseSlot.Disconnect();
}
}
/*!
* \brief Sets the target region of the camera
*
* \param region A constant reference to the target region of the camera
*/
inline void CameraComponent::SetTargetRegion(const Nz::Rectf& region)
{
m_targetRegion = region;
InvalidateViewport();
}
/*!
* \brief Sets the view port of the camera
*
* \param viewport A constant reference to the view port of the camera
*
* \remark Produces a NazaraAssert if the camera has no target
*/
inline void CameraComponent::SetViewport(const Nz::Recti& viewport)
{
NazaraAssert(m_target, "Component has no render target");
// We compute the region necessary to make this view port with the actual size of the target
Nz::Vector2f invSize = 1.f / Nz::Vector2f(m_target->GetSize());
SetTargetRegion(Nz::Rectf(invSize.x * viewport.x, invSize.y * viewport.y, invSize.x * viewport.width, invSize.y * viewport.height));
}
/*!
* \brief Sets the Z far distance of the camera
*
* \param zFar Z far distance of the camera
*/
inline void CameraComponent::SetZFar(float zFar)
{
m_zFar = zFar;
InvalidateProjectionMatrix();
}
/*!
* \brief Sets the Z near distance of the camera
*
* \param zNear Z near distance of the camera
*
* \remark Produces a NazaraAssert if zNear is zero
*/
inline void CameraComponent::SetZNear(float zNear)
{
NazaraAssert(!Nz::NumberEquals(zNear, 0.f), "zNear cannot be zero");
m_zNear = zNear;
InvalidateProjectionMatrix();
}
/*!
* \brief Update the camera component visibility hash
*
* This is used with CullingList (which produce a visibility hash)
*
* \param visibilityHash New visibility hash
*
* \return True if the visibility hash is not the same as before
*/
inline bool CameraComponent::UpdateVisibility(std::size_t visibilityHash)
{
if (m_visibilityHash != visibilityHash)
{
m_visibilityHash = visibilityHash;
return true;
}
return false;
}
/*!
* \brief Invalidates the frustum
*/
inline void CameraComponent::InvalidateFrustum() const
{
m_frustumUpdated = false;
}
/*!
* \brief Invalidates the projection matrix
*/
inline void CameraComponent::InvalidateProjectionMatrix() const
{
m_frustumUpdated = false;
m_projectionMatrixUpdated = false;
}
/*!
* \brief Invalidates the view matrix
*/
inline void CameraComponent::InvalidateViewMatrix() const
{
m_frustumUpdated = false;
m_viewMatrixUpdated = false;
}
/*!
* \brief Invalidates the view port
*/
inline void CameraComponent::InvalidateViewport() const
{
m_frustumUpdated = false;
m_projectionMatrixUpdated = false;
m_viewportUpdated = false;
}
}

View File

@ -1,91 +0,0 @@
// Copyright (C) 2017 Jérôme Leclercq
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequisites.hpp
#pragma once
#ifndef NDK_SERVER
#ifndef NDK_COMPONENTS_DEBUGCOMPONENT_HPP
#define NDK_COMPONENTS_DEBUGCOMPONENT_HPP
#include <Nazara/Core/Flags.hpp>
#include <Nazara/Graphics/InstancedRenderable.hpp>
#include <NDK/Component.hpp>
namespace Ndk
{
enum class DebugDraw
{
Collider2D,
Collider3D,
GraphicsAABB,
GraphicsOBB,
Max = GraphicsOBB
};
}
namespace Nz
{
template<>
struct EnumAsFlags<Ndk::DebugDraw>
{
static constexpr Ndk::DebugDraw max = Ndk::DebugDraw::GraphicsOBB;
};
}
namespace Ndk
{
using DebugDrawFlags = Nz::Flags<DebugDraw>;
constexpr DebugDrawFlags DebugDraw_None = 0;
class DebugComponent;
class GraphicsComponent;
using DebugComponentHandle = Nz::ObjectHandle<DebugComponent>;
class NDK_API DebugComponent : public Component<DebugComponent>
{
friend class DebugSystem;
public:
inline DebugComponent(DebugDrawFlags flags = DebugDraw_None);
inline DebugComponent(const DebugComponent& debug);
~DebugComponent() = default;
inline void Disable(DebugDrawFlags flags);
inline void Enable(DebugDrawFlags flags);
inline DebugDrawFlags GetFlags() const;
inline bool IsEnabled(DebugDrawFlags flags) const;
inline DebugComponent& operator=(const DebugComponent& debug);
static ComponentIndex componentIndex;
private:
void DetachDebugRenderables(GraphicsComponent& gfxComponent);
inline const Nz::InstancedRenderableRef& GetDebugRenderable(DebugDraw option) const;
inline DebugDrawFlags GetEnabledFlags() const;
void OnComponentDetached(BaseComponent& component) override;
void OnDetached() override;
inline void UpdateDebugRenderable(DebugDraw option, Nz::InstancedRenderableRef renderable);
inline void UpdateEnabledFlags(DebugDrawFlags flags);
static constexpr std::size_t DebugModeCount = static_cast<std::size_t>(DebugDraw::Max) + 1;
std::array<Nz::InstancedRenderableRef, DebugModeCount> m_debugRenderables;
DebugDrawFlags m_enabledFlags;
DebugDrawFlags m_flags;
};
}
#include <NDK/Components/DebugComponent.inl>
#endif // NDK_COMPONENTS_DEBUGCOMPONENT_HPP
#endif // NDK_SERVER

View File

@ -1,74 +0,0 @@
// Copyright (C) 2017 Jérôme Leclercq
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequisites.hpp
#include <NDK/Components/DebugComponent.hpp>
namespace Ndk
{
inline DebugComponent::DebugComponent(DebugDrawFlags flags) :
m_flags(flags)
{
}
inline DebugComponent::DebugComponent(const DebugComponent& debug) :
m_flags(debug.m_flags)
{
}
inline void DebugComponent::Disable(DebugDrawFlags flags)
{
m_flags &= ~flags;
if (m_entity)
m_entity->Invalidate();
}
inline void DebugComponent::Enable(DebugDrawFlags flags)
{
m_flags |= flags;
if (m_entity)
m_entity->Invalidate();
}
inline DebugDrawFlags DebugComponent::GetFlags() const
{
return m_flags;
}
inline bool DebugComponent::IsEnabled(DebugDrawFlags flags) const
{
return (m_flags & flags) == flags;
}
inline DebugComponent& DebugComponent::operator=(const DebugComponent& debug)
{
m_flags = debug.m_flags;
if (m_entity)
m_entity->Invalidate();
return *this;
}
inline const Nz::InstancedRenderableRef& DebugComponent::GetDebugRenderable(DebugDraw option) const
{
return m_debugRenderables[static_cast<std::size_t>(option)];
}
inline DebugDrawFlags DebugComponent::GetEnabledFlags() const
{
return m_enabledFlags;
}
inline void DebugComponent::UpdateDebugRenderable(DebugDraw option, Nz::InstancedRenderableRef renderable)
{
m_debugRenderables[static_cast<std::size_t>(option)] = std::move(renderable);
}
inline void DebugComponent::UpdateEnabledFlags(DebugDrawFlags flags)
{
m_enabledFlags = flags;
}
}

View File

@ -1,170 +0,0 @@
// Copyright (C) 2017 Jérôme Leclercq
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequisites.hpp
#pragma once
#ifndef NDK_SERVER
#ifndef NDK_COMPONENTS_GRAPHICSCOMPONENT_HPP
#define NDK_COMPONENTS_GRAPHICSCOMPONENT_HPP
#include <Nazara/Graphics/CullingList.hpp>
#include <Nazara/Graphics/InstancedRenderable.hpp>
#include <Nazara/Math/Frustum.hpp>
#include <Nazara/Utility/Node.hpp>
#include <NDK/Component.hpp>
#include <unordered_map>
namespace Ndk
{
class GraphicsComponent;
using GraphicsComponentCullingList = Nz::CullingList<GraphicsComponent>;
using GraphicsComponentHandle = Nz::ObjectHandle<GraphicsComponent>;
class NDK_API GraphicsComponent : public Component<GraphicsComponent>
{
friend class RenderSystem;
public:
using RenderableList = std::vector<Nz::InstancedRenderableRef>;
inline GraphicsComponent();
inline GraphicsComponent(const GraphicsComponent& graphicsComponent);
~GraphicsComponent() = default;
inline void AddToCullingList(GraphicsComponentCullingList* cullingList) const;
void AddToRenderQueue(Nz::AbstractRenderQueue* renderQueue) const;
void AddToRenderQueueByCulling(const Nz::Frustumf& frustum, Nz::AbstractRenderQueue* renderQueue) const;
inline void Attach(Nz::InstancedRenderableRef renderable, int renderOrder = 0);
void Attach(Nz::InstancedRenderableRef renderable, const Nz::Matrix4f& localMatrix, int renderOrder = 0);
inline void Clear();
inline void Detach(const Nz::InstancedRenderable* renderable);
inline bool DoesRequireRealTimeReflections() const;
inline void EnsureBoundingVolumesUpdate() const;
inline void EnsureTransformMatrixUpdate() const;
template<typename Func> void ForEachRenderable(const Func& func) const;
inline const Nz::Boxf& GetAABB() const;
inline void GetAttachedRenderables(RenderableList* renderables) const;
inline std::size_t GetAttachedRenderableCount() const;
inline const Nz::BoundingVolumef& GetBoundingVolume(std::size_t renderableIndex) const;
inline const Nz::Matrix4f& GetLocalMatrix(std::size_t renderableIndex) const;
inline const Nz::Matrix4f& GetTransformMatrix(std::size_t renderableIndex) const;
inline void RemoveFromCullingList(GraphicsComponentCullingList* cullingList) const;
inline void SetScissorRect(const Nz::Recti& scissorRect);
inline void UpdateLocalMatrix(const Nz::InstancedRenderable* instancedRenderable, const Nz::Matrix4f& localMatrix);
inline void UpdateRenderOrder(const Nz::InstancedRenderable* instancedRenderable, int renderOrder);
static ComponentIndex componentIndex;
private:
struct Renderable;
void ConnectInstancedRenderableSignals(Renderable& renderable);
inline void ForceCullingInvalidation();
inline void InvalidateAABB() const;
void InvalidateRenderableData(const Nz::InstancedRenderable* renderable, Nz::UInt32 flags, std::size_t index);
void InvalidateRenderableMaterial(const Nz::InstancedRenderable* renderable, std::size_t skinIndex, std::size_t matIndex, const Nz::MaterialRef& newMat);
inline void InvalidateRenderables();
void InvalidateReflectionMap();
inline void InvalidateTransformMatrix();
void RegisterMaterial(Nz::Material* material, std::size_t count = 1);
void OnAttached() override;
void OnComponentAttached(BaseComponent& component) override;
void OnComponentDetached(BaseComponent& component) override;
void OnDetached() override;
void OnInstancedRenderableResetMaterials(const Nz::InstancedRenderable* renderable, std::size_t newMaterialCount);
void OnInstancedRenderableSkinChange(const Nz::InstancedRenderable* renderable, std::size_t newSkinIndex);
void OnMaterialReflectionChange(const Nz::Material* material, Nz::ReflectionMode reflectionMode);
void OnNodeInvalidated(const Nz::Node* node);
void UnregisterMaterial(Nz::Material* material);
void UpdateBoundingVolumes() const;
void UpdateTransformMatrix() const;
NazaraSlot(Nz::Node, OnNodeInvalidation, m_nodeInvalidationSlot);
using CullingListBoxEntry = GraphicsComponentCullingList::BoxEntry;
struct CullingBoxEntry
{
CullingListBoxEntry listEntry;
NazaraSlot(GraphicsComponentCullingList, OnCullingListRelease, cullingListReleaseSlot);
};
struct MaterialEntry
{
NazaraSlot(Nz::Material, OnMaterialReflectionModeChange, reflectionModelChangeSlot);
std::size_t renderableCounter;
};
struct Renderable
{
Renderable(const Nz::Matrix4f& transformMatrix) :
data(transformMatrix),
dataUpdated(false)
{
}
Renderable(const Renderable&) = delete;
Renderable(Renderable&& rhs) noexcept = default;
~Renderable()
{
// Disconnect release slot before releasing instanced renderable reference
renderableReleaseSlot.Disconnect();
}
Renderable& operator=(const Renderable&) = delete;
Renderable& operator=(Renderable&& r) noexcept = default;
NazaraSlot(Nz::InstancedRenderable, OnInstancedRenderableInvalidateBoundingVolume, renderableBoundingVolumeInvalidationSlot);
NazaraSlot(Nz::InstancedRenderable, OnInstancedRenderableInvalidateData, renderableDataInvalidationSlot);
NazaraSlot(Nz::InstancedRenderable, OnInstancedRenderableInvalidateMaterial, renderableMaterialInvalidationSlot);
NazaraSlot(Nz::InstancedRenderable, OnInstancedRenderableRelease, renderableReleaseSlot);
NazaraSlot(Nz::InstancedRenderable, OnInstancedRenderableResetMaterials, renderableResetMaterialsSlot);
NazaraSlot(Nz::InstancedRenderable, OnInstancedRenderableSkinChange, renderableSkinChangeSlot);
mutable Nz::BoundingVolumef boundingVolume;
mutable Nz::InstancedRenderable::InstanceData data;
Nz::InstancedRenderableRef renderable;
mutable bool dataUpdated;
};
std::size_t m_reflectiveMaterialCount;
mutable std::vector<CullingBoxEntry> m_cullingBoxEntries;
std::vector<Renderable> m_renderables;
std::unordered_map<const Nz::Material*, MaterialEntry> m_materialEntries;
mutable Nz::Boxf m_aabb;
mutable Nz::Matrix4f m_transformMatrix;
Nz::Recti m_scissorRect;
Nz::TextureRef m_reflectionMap;
mutable bool m_boundingVolumesUpdated;
mutable bool m_transformMatrixUpdated;
unsigned int m_reflectionMapSize;
};
}
#include <NDK/Components/GraphicsComponent.inl>
#endif // NDK_COMPONENTS_GRAPHICSCOMPONENT_HPP
#endif // NDK_SERVER

View File

@ -1,291 +0,0 @@
// Copyright (C) 2017 Jérôme Leclercq
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequisites.hpp
#include <NDK/Components/GraphicsComponent.hpp>
#include <NDK/World.hpp>
#include <NDK/Systems/RenderSystem.hpp>
#include <algorithm>
namespace Ndk
{
inline GraphicsComponent::GraphicsComponent() :
m_reflectiveMaterialCount(0),
m_scissorRect(-1, -1)
{
}
/*!
* \brief Constructs a GraphicsComponent object by copy semantic
*
* \param graphicsComponent GraphicsComponent to copy
*/
inline GraphicsComponent::GraphicsComponent(const GraphicsComponent& graphicsComponent) :
Component(graphicsComponent),
m_reflectiveMaterialCount(0),
m_aabb(graphicsComponent.m_aabb),
m_transformMatrix(graphicsComponent.m_transformMatrix),
m_scissorRect(graphicsComponent.m_scissorRect),
m_boundingVolumesUpdated(graphicsComponent.m_boundingVolumesUpdated),
m_transformMatrixUpdated(graphicsComponent.m_transformMatrixUpdated)
{
m_renderables.reserve(graphicsComponent.m_renderables.size());
for (const Renderable& r : graphicsComponent.m_renderables)
Attach(r.renderable, r.data.localMatrix, r.data.renderOrder);
}
inline void GraphicsComponent::AddToCullingList(GraphicsComponentCullingList* cullingList) const
{
m_cullingBoxEntries.emplace_back();
CullingBoxEntry& entry = m_cullingBoxEntries.back();
entry.cullingListReleaseSlot.Connect(cullingList->OnCullingListRelease, this, &GraphicsComponent::RemoveFromCullingList);
entry.listEntry = cullingList->RegisterBoxTest(this);
InvalidateAABB();
}
/*!
* \brief Attaches a renderable to the entity
*
* \param renderable Reference to a renderable element
* \param renderOrder Render order of the element
*/
inline void GraphicsComponent::Attach(Nz::InstancedRenderableRef renderable, int renderOrder)
{
return Attach(std::move(renderable), Nz::Matrix4f::Identity(), renderOrder);
}
/*!
* \brief Clears every renderable elements
*/
inline void GraphicsComponent::Clear()
{
m_materialEntries.clear();
m_renderables.clear();
if (m_reflectiveMaterialCount > 0)
{
m_reflectiveMaterialCount = 0;
InvalidateReflectionMap();
}
InvalidateAABB();
}
/*!
* \brief Detaches a renderable to the entity
*
* \param renderable Reference to a renderable element
*/
inline void GraphicsComponent::Detach(const Nz::InstancedRenderable* renderable)
{
for (auto it = m_renderables.begin(); it != m_renderables.end(); ++it)
{
if (it->renderable == renderable)
{
InvalidateAABB();
std::size_t materialCount = renderable->GetMaterialCount();
for (std::size_t i = 0; i < materialCount; ++i)
UnregisterMaterial(renderable->GetMaterial(i));
m_renderables.erase(it);
ForceCullingInvalidation();
break;
}
}
}
/*!
* \brief Checks if this graphics component requires real-time reflections to be generated
*
* If any of the materials attached to a GraphicsComponent (via the attached instanced renderable) needs real-time reflections, this function will return true.
*
* \return True if real-time reflections needs to be generated or false
*/
inline bool GraphicsComponent::DoesRequireRealTimeReflections() const
{
return m_reflectiveMaterialCount != 0 && m_reflectionMap;
}
/*!
* \brief Ensures the bounding volume is up to date
*/
inline void GraphicsComponent::EnsureBoundingVolumesUpdate() const
{
if (!m_boundingVolumesUpdated)
UpdateBoundingVolumes();
}
/*!
* \brief Ensures the transformation matrix is up to date
*/
inline void GraphicsComponent::EnsureTransformMatrixUpdate() const
{
if (!m_transformMatrixUpdated)
UpdateTransformMatrix();
}
/*!
* \brief Gets the axis-aligned bounding box of the entity
* \return A constant reference to the AABB
*/
inline const Nz::Boxf& GraphicsComponent::GetAABB() const
{
EnsureBoundingVolumesUpdate();
return m_aabb;
}
/*!
* \brief Gets the set of renderable elements
*
* \param renderables Pointer to the list of renderables
*
* \remark Produces a NazaraAssert if renderables is invalid
*/
inline void GraphicsComponent::GetAttachedRenderables(RenderableList* renderables) const
{
NazaraAssert(renderables, "Invalid renderable list");
renderables->reserve(renderables->size() + m_renderables.size());
for (const Renderable& r : m_renderables)
renderables->push_back(r.renderable);
}
/*!
* \brief Gets the number of renderable elements attached to the entity
* \return Number of renderable elements
*/
inline std::size_t GraphicsComponent::GetAttachedRenderableCount() const
{
return m_renderables.size();
}
inline const Nz::BoundingVolumef& GraphicsComponent::GetBoundingVolume(std::size_t renderableIndex) const
{
EnsureBoundingVolumesUpdate();
assert(renderableIndex < m_renderables.size());
return m_renderables[renderableIndex].boundingVolume;
}
inline const Nz::Matrix4f& GraphicsComponent::GetLocalMatrix(std::size_t renderableIndex) const
{
assert(renderableIndex < m_renderables.size());
return m_renderables[renderableIndex].data.localMatrix;
}
inline const Nz::Matrix4f& GraphicsComponent::GetTransformMatrix(std::size_t renderableIndex) const
{
EnsureBoundingVolumesUpdate();
assert(renderableIndex < m_renderables.size());
return m_renderables[renderableIndex].data.transformMatrix;
}
/*!
* \brief Calls a function for every renderable attached to this component
*
* \param func Callback function which will be called with renderable data
*/
template<typename Func>
void GraphicsComponent::ForEachRenderable(const Func& func) const
{
for (const auto& renderableData : m_renderables)
func(renderableData.renderable, renderableData.data.localMatrix, renderableData.data.renderOrder);
}
inline void GraphicsComponent::RemoveFromCullingList(GraphicsComponentCullingList* cullingList) const
{
for (auto it = m_cullingBoxEntries.begin(); it != m_cullingBoxEntries.end(); ++it)
{
if (it->listEntry.GetParent() == cullingList)
{
if (m_cullingBoxEntries.size() > 1)
*it = std::move(m_cullingBoxEntries.back());
m_cullingBoxEntries.pop_back();
break;
}
}
}
inline void GraphicsComponent::SetScissorRect(const Nz::Recti& scissorRect)
{
m_scissorRect = scissorRect;
for (CullingBoxEntry& entry : m_cullingBoxEntries)
entry.listEntry.ForceInvalidation(); //< Invalidate render queues
}
inline void GraphicsComponent::UpdateLocalMatrix(const Nz::InstancedRenderable* instancedRenderable, const Nz::Matrix4f& localMatrix)
{
for (auto& renderable : m_renderables)
{
if (renderable.renderable == instancedRenderable)
{
renderable.data.localMatrix = localMatrix;
InvalidateAABB();
break;
}
}
}
inline void GraphicsComponent::UpdateRenderOrder(const Nz::InstancedRenderable* instancedRenderable, int renderOrder)
{
for (auto& renderable : m_renderables)
{
if (renderable.renderable == instancedRenderable)
{
renderable.data.renderOrder = renderOrder;
break;
}
}
}
/*!
* \brief Invalidates the bounding volume
*/
inline void GraphicsComponent::ForceCullingInvalidation()
{
for (CullingBoxEntry& entry : m_cullingBoxEntries)
entry.listEntry.ForceInvalidation(); //< Invalidate render queues
}
inline void GraphicsComponent::InvalidateAABB() const
{
m_boundingVolumesUpdated = false;
}
/*!
* \brief Invalidates every renderable elements
*/
inline void GraphicsComponent::InvalidateRenderables()
{
for (Renderable& r : m_renderables)
r.dataUpdated = false;
}
/*!
* \brief Invalidates the transformation matrix
*/
inline void GraphicsComponent::InvalidateTransformMatrix()
{
m_transformMatrixUpdated = false;
InvalidateAABB();
InvalidateRenderables();
}
}

View File

@ -1,34 +0,0 @@
// Copyright (C) 2017 Jérôme Leclercq
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequisites.hpp
#pragma once
#ifndef NDK_SERVER
#ifndef NDK_COMPONENTS_LIGHTCOMPONENT_HPP
#define NDK_COMPONENTS_LIGHTCOMPONENT_HPP
#include <Nazara/Graphics/Light.hpp>
#include <NDK/Component.hpp>
namespace Ndk
{
class LightComponent;
using LightComponentHandle = Nz::ObjectHandle<LightComponent>;
class NDK_API LightComponent : public Component<LightComponent>, public Nz::Light
{
public:
inline LightComponent(Nz::LightType lightType = Nz::LightType_Point);
LightComponent(const LightComponent& light) = default;
~LightComponent() = default;
static ComponentIndex componentIndex;
};
}
#include <NDK/Components/LightComponent.inl>
#endif // NDK_COMPONENTS_LIGHTCOMPONENT_HPP
#endif // NDK_SERVER

View File

@ -1,15 +0,0 @@
// Copyright (C) 2017 Jérôme Leclercq
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequisites.hpp
namespace Ndk
{
/*!
* \brief Constructs an LightComponent object with a light type
*/
inline LightComponent::LightComponent(Nz::LightType lightType) :
Nz::Light(lightType)
{
}
}

View File

@ -1,49 +0,0 @@
// Copyright (C) 2017 Jérôme Leclercq
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequisites.hpp
#pragma once
#ifndef NDK_SERVER
#ifndef NDK_COMPONENTS_PARTICLEEMITTERCOMPONENT_HPP
#define NDK_COMPONENTS_PARTICLEEMITTERCOMPONENT_HPP
#include <Nazara/Graphics/ParticleEmitter.hpp>
#include <NDK/Component.hpp>
namespace Ndk
{
class ParticleEmitterComponent;
using ParticleEmitterComponentHandle = Nz::ObjectHandle<ParticleEmitterComponent>;
class NDK_API ParticleEmitterComponent : public Component<ParticleEmitterComponent>, public Nz::ParticleEmitter
{
public:
using SetupFunc = std::function<void(const EntityHandle& /*entity*/, Nz::ParticleMapper& /*mapper*/, unsigned int /*count*/)>;
inline ParticleEmitterComponent();
ParticleEmitterComponent(const ParticleEmitterComponent& emitter) = default;
ParticleEmitterComponent(ParticleEmitterComponent&& emitter) = default;
~ParticleEmitterComponent() = default;
inline void Enable(bool active = true);
inline bool IsActive() const;
inline void SetSetupFunc(SetupFunc func);
static ComponentIndex componentIndex;
private:
void SetupParticles(Nz::ParticleMapper& mapper, unsigned int count) const override;
SetupFunc m_setupFunc;
bool m_isActive;
};
}
#include <NDK/Components/ParticleEmitterComponent.inl>
#endif // NDK_COMPONENTS_PARTICLEEMITTERCOMPONENT_HPP
#endif // NDK_SERVER

View File

@ -1,47 +0,0 @@
// Copyright (C) 2017 Jérôme Leclercq
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequisites.hpp
namespace Ndk
{
/*!
* \brief Constructs an ParticleEmitterComponent object by default
*/
inline ParticleEmitterComponent::ParticleEmitterComponent() :
m_isActive(true)
{
}
/*!
* \brief Enables the emission of particles
*
* \param active Should the emitter be active
*/
inline void Ndk::ParticleEmitterComponent::Enable(bool active)
{
m_isActive = active;
}
/*!
* \brief Checks whether the emission of particles is activated
* \param true If it is the case
*/
inline bool ParticleEmitterComponent::IsActive() const
{
return m_isActive;
}
/*!
* \brief Sets the function use for setting up particles
*
* \param func Function to set up particles
*/
inline void Ndk::ParticleEmitterComponent::SetSetupFunc(SetupFunc func)
{
m_setupFunc = std::move(func);
}
}

View File

@ -1,41 +0,0 @@
// Copyright (C) 2017 Jérôme Leclercq
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequisites.hpp
#pragma once
#ifndef NDK_SERVER
#ifndef NDK_COMPONENTS_PARTICLEGROUPCOMPONENT_HPP
#define NDK_COMPONENTS_PARTICLEGROUPCOMPONENT_HPP
#include <Nazara/Graphics/ParticleGroup.hpp>
#include <NDK/Component.hpp>
namespace Ndk
{
class ParticleGroupComponent;
using ParticleGroupComponentHandle = Nz::ObjectHandle<ParticleGroupComponent>;
class NDK_API ParticleGroupComponent : public Component<ParticleGroupComponent>, public Nz::ParticleGroup
{
public:
inline ParticleGroupComponent(unsigned int maxParticleCount, Nz::ParticleLayout layout);
inline ParticleGroupComponent(unsigned int maxParticleCount, Nz::ParticleDeclarationConstRef declaration);
ParticleGroupComponent(const ParticleGroupComponent&) = default;
~ParticleGroupComponent() = default;
void AddEmitter(Entity* emitter);
using ParticleGroup::AddEmitter;
void RemoveEmitter(Entity* emitter);
using ParticleGroup::RemoveEmitter;
static ComponentIndex componentIndex;
};
}
#include <NDK/Components/ParticleGroupComponent.inl>
#endif // NDK_COMPONENTS_PARTICLEGROUPCOMPONENT_HPP
#endif // NDK_SERVER

View File

@ -1,76 +0,0 @@
// Copyright (C) 2017 Jérôme Leclercq
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequisites.hpp
#include <NDK/Components/ParticleEmitterComponent.hpp>
#include <Nazara/Core/Error.hpp>
namespace Ndk
{
/*!
* \ingroup NDK
* \class Ndk::ParticleGroupComponent
* \brief NDK class that represents the component for a group of particles
*/
/*!
* \brief Constructs a ParticleGroupComponent object with a maximal number of particles and a layout
*
* \param maxParticleCount Maximum number of particles to generate
* \param layout Enumeration for the layout of data information for the particles
*/
inline ParticleGroupComponent::ParticleGroupComponent(unsigned int maxParticleCount, Nz::ParticleLayout layout) :
ParticleGroup(maxParticleCount, layout)
{
}
/*!
* \brief Constructs a ParticleGroupComponent object with a maximal number of particles and a particle declaration
*
* \param maxParticleCount Maximum number of particles to generate
* \param declaration Data information for the particles
*/
inline ParticleGroupComponent::ParticleGroupComponent(unsigned int maxParticleCount, Nz::ParticleDeclarationConstRef declaration) :
ParticleGroup(maxParticleCount, std::move(declaration))
{
}
/*!
* \brief Adds an emitter to the particles
*
* \param emitter Emitter for the particles
*
* \remark Produces a NazaraAssert if emitter is invalid
* \remark Produces a NazaraAssert if entity has no component of type ParticleEmitterComponent
*/
inline void ParticleGroupComponent::AddEmitter(Entity* emitter)
{
NazaraAssert(emitter && emitter->IsValid(), "Invalid entity");
NazaraAssert(emitter->HasComponent<ParticleEmitterComponent>(), "Entity must have a ParticleEmitterComponent");
auto& emitterComponent = emitter->GetComponent<ParticleEmitterComponent>();
ParticleGroup::AddEmitter(&emitterComponent);
}
/*!
* \brief Removes an emitter to the particles
*
* \param emitter Emitter for the particles to remove
*
* \remark Produces a NazaraAssert if emitter is invalid
* \remark Produces a NazaraAssert if entity has no component of type ParticleEmitterComponent
*/
inline void ParticleGroupComponent::RemoveEmitter(Entity* emitter)
{
NazaraAssert(emitter && emitter->IsValid(), "Invalid entity");
NazaraAssert(emitter->HasComponent<ParticleEmitterComponent>(), "Entity must have a ParticleEmitterComponent");
auto& emitterComponent = emitter->GetComponent<ParticleEmitterComponent>();
ParticleGroup::RemoveEmitter(&emitterComponent);
}
}

View File

@ -1,88 +0,0 @@
// Copyright (C) 2017 Jérôme Leclercq
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequisites.hpp
#pragma once
#ifndef NDK_SERVER
#ifndef NDK_CONSOLE_HPP
#define NDK_CONSOLE_HPP
#include <Nazara/Core/HandledObject.hpp>
#include <Nazara/Core/ObjectHandle.hpp>
#include <Nazara/Graphics/Sprite.hpp>
#include <Nazara/Graphics/TextSprite.hpp>
#include <Nazara/Utility/Node.hpp>
#include <Nazara/Utility/SimpleTextDrawer.hpp>
#include <NDK/BaseWidget.hpp>
#include <NDK/EntityOwner.hpp>
namespace Nz
{
struct WindowEvent;
}
namespace Ndk
{
class AbstractTextAreaWidget;
class Console;
class Entity;
class RichTextAreaWidget;
class ScrollAreaWidget;
class TextAreaWidget;
using ConsoleHandle = Nz::ObjectHandle<Console>;
class NDK_API Console : public BaseWidget, public Nz::HandledObject<Console>
{
public:
Console(BaseWidget* parent);
Console(const Console& console) = delete;
Console(Console&& console) = default;
~Console() = default;
void AddLine(const Nz::String& text, const Nz::Color& color = Nz::Color::White);
void Clear();
void ClearFocus();
inline unsigned int GetCharacterSize() const;
inline const RichTextAreaWidget* GetHistory() const;
inline const TextAreaWidget* GetInput() const;
inline const Nz::FontRef& GetTextFont() const;
void SetCharacterSize(unsigned int size);
void SetFocus();
void SetTextFont(Nz::FontRef font);
Console& operator=(const Console& console) = delete;
Console& operator=(Console&& console) = default;
NazaraSignal(OnCommand, Console* /*console*/, const Nz::String& /*command*/);
private:
void ExecuteInput(const AbstractTextAreaWidget* textArea, bool* ignoreDefaultAction);
void Layout() override;
struct Line
{
Nz::Color color;
Nz::String text;
};
std::size_t m_historyPosition;
std::vector<Nz::String> m_commandHistory;
std::vector<Line> m_historyLines;
ScrollAreaWidget* m_historyArea;
RichTextAreaWidget* m_history;
TextAreaWidget* m_input;
Nz::FontRef m_defaultFont;
unsigned int m_characterSize;
unsigned int m_maxHistoryLines;
};
}
#include <NDK/Console.inl>
#endif // NDK_CONSOLE_HPP
#endif // NDK_SERVER

View File

@ -1,46 +0,0 @@
// Copyright (C) 2017 Jérôme Leclercq
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequisites.hpp
namespace Ndk
{
/*!
* \brief Gets the character size
* \return Height of the character
*/
inline unsigned int Console::GetCharacterSize() const
{
return m_characterSize;
}
/*!
* \brief Gets the entity representing the history of the console
* \return History of the console
*/
inline const RichTextAreaWidget* Console::GetHistory() const
{
return m_history;
}
/*!
* \brief Gets the entity representing the input of the console
* \return Input of the console
*/
inline const TextAreaWidget* Console::GetInput() const
{
return m_input;
}
/*!
* \brief Gets the font used by the console
* \return A reference to the font currenty used
*/
inline const Nz::FontRef& Console::GetTextFont() const
{
return m_defaultFont;
}
}

View File

@ -1,68 +0,0 @@
// Copyright (C) 2017 Jérôme Leclercq
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequisites.hpp
#pragma once
#ifndef NDK_LUABINDING_HPP
#define NDK_LUABINDING_HPP
#include <NDK/Entity.hpp>
#include <NDK/Lua/LuaBinding_Base.hpp>
#include <memory>
namespace Ndk
{
class NDK_API LuaBinding
{
friend class LuaBinding_SDK;
public:
LuaBinding();
~LuaBinding() = default;
template<typename T> void BindComponent(const Nz::String& name);
void RegisterClasses(Nz::LuaState& state);
std::unique_ptr<LuaBinding_Base> core;
std::unique_ptr<LuaBinding_Base> math;
std::unique_ptr<LuaBinding_Base> network;
std::unique_ptr<LuaBinding_Base> sdk;
std::unique_ptr<LuaBinding_Base> utility;
#ifndef NDK_SERVER
std::unique_ptr<LuaBinding_Base> audio;
std::unique_ptr<LuaBinding_Base> graphics;
std::unique_ptr<LuaBinding_Base> renderer;
std::unique_ptr<LuaBinding_Base> platform;
#endif
private:
template<typename T>
static int AddComponentOfType(Nz::LuaState& lua, EntityHandle& handle);
template<typename T>
static int PushComponentOfType(Nz::LuaState& lua, BaseComponent& component);
using AddComponentFunc = int(*)(Nz::LuaState&, EntityHandle&);
using GetComponentFunc = int(*)(Nz::LuaState&, BaseComponent&);
struct ComponentBinding
{
AddComponentFunc adder;
ComponentIndex index;
GetComponentFunc getter;
Nz::String name;
};
ComponentBinding* QueryComponentIndex(Nz::LuaState& lua, int argIndex = 2);
std::vector<ComponentBinding> m_componentBinding;
std::unordered_map<Nz::String, ComponentIndex> m_componentBindingByName;
};
}
#include <NDK/Lua/LuaBinding.inl>
#endif // NDK_LUABINDING_HPP

View File

@ -1,70 +0,0 @@
// Copyright (C) 2017 Jérôme Leclercq
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequisites.hpp
namespace Ndk
{
namespace Detail
{
template<bool HasDefaultConstructor>
struct AddComponentIf;
template<>
struct AddComponentIf<true>
{
template<typename T>
static int AddComponent(Nz::LuaState& lua, EntityHandle& handle)
{
T& component = handle->AddComponent<T>();
lua.Push(component.CreateHandle());
return 1;
}
};
template<>
struct AddComponentIf<false>
{
template<typename T>
static int AddComponent(Nz::LuaState& lua, EntityHandle& /*handle*/)
{
lua.Error("Component has no default constructor and cannot be created from Lua yet");
return 0;
}
};
}
/*!
* \brief Binds a component to a name
*
* \param name Name used to retrieve the component
*
* \remark Produces a NazaraAssert if name is empty
*/
template<typename T>
void LuaBinding::BindComponent(const Nz::String& name)
{
NazaraAssert(!name.IsEmpty(), "Component name cannot be empty");
static_assert(std::is_base_of<BaseComponent, T>::value, "ComponentType must inherit BaseComponent");
ComponentBinding binding;
binding.adder = &Detail::AddComponentIf<std::is_default_constructible<T>::value>::template AddComponent<T>;
binding.getter = &PushComponentOfType<T>;
binding.index = T::componentIndex;
binding.name = name;
if (m_componentBinding.size() <= T::componentIndex)
m_componentBinding.resize(T::componentIndex + 1);
m_componentBinding[T::componentIndex] = std::move(binding);
m_componentBindingByName[name] = T::componentIndex;
}
template<typename T>
int LuaBinding::PushComponentOfType(Nz::LuaState& lua, BaseComponent& component)
{
T& rightComponent = static_cast<T&>(component);
lua.Push(rightComponent.CreateHandle());
return 1;
}
}

View File

@ -1,33 +0,0 @@
// Copyright (C) 2017 Jérôme Leclercq
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequisites.hpp
#pragma once
#ifndef NDK_LUABINDING_AUDIO_HPP
#define NDK_LUABINDING_AUDIO_HPP
#include <Nazara/Audio/Music.hpp>
#include <Nazara/Audio/Sound.hpp>
#include <Nazara/Audio/SoundBuffer.hpp>
#include <Nazara/Audio/SoundEmitter.hpp>
#include <NDK/Lua/LuaBinding_Base.hpp>
namespace Ndk
{
class NDK_API LuaBinding_Audio : public LuaBinding_Base
{
public:
LuaBinding_Audio(LuaBinding& binding);
~LuaBinding_Audio() = default;
void Register(Nz::LuaState& state) override;
Nz::LuaClass<Nz::Music> music;
Nz::LuaClass<Nz::Sound> sound;
Nz::LuaClass<Nz::SoundBufferRef> soundBuffer;
Nz::LuaClass<Nz::SoundEmitter> soundEmitter;
};
}
#endif // NDK_LUABINDING_CORE_HPP

View File

@ -1,55 +0,0 @@
// Copyright (C) 2017 Jérôme Leclercq
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequisites.hpp
#pragma once
#ifndef NDK_LUABINDING_BASE_HPP
#define NDK_LUABINDING_BASE_HPP
#include <Nazara/Lua/LuaClass.hpp>
#include <Nazara/Lua/LuaInstance.hpp>
#include <NDK/Prerequisites.hpp>
namespace Ndk
{
class LuaBinding;
class LuaBinding_Audio;
class LuaBinding_Core;
class LuaBinding_Graphics;
class LuaBinding_Math;
class LuaBinding_Network;
class LuaBinding_Renderer;
class LuaBinding_SDK;
class LuaBinding_Utility;
class LuaBinding_Platform;
class NDK_API LuaBinding_Base
{
public:
LuaBinding_Base(LuaBinding& binding);
virtual ~LuaBinding_Base();
virtual void Register(Nz::LuaState& state) = 0;
// Implementation lies in the respective .cpp files (still searching for a cleaner way..)
static std::unique_ptr<LuaBinding_Base> BindCore(LuaBinding& binding);
static std::unique_ptr<LuaBinding_Base> BindMath(LuaBinding& binding);
static std::unique_ptr<LuaBinding_Base> BindNetwork(LuaBinding& binding);
static std::unique_ptr<LuaBinding_Base> BindSDK(LuaBinding& binding);
static std::unique_ptr<LuaBinding_Base> BindUtility(LuaBinding& binding);
#ifndef NDK_SERVER
static std::unique_ptr<LuaBinding_Base> BindAudio(LuaBinding& binding);
static std::unique_ptr<LuaBinding_Base> BindGraphics(LuaBinding& binding);
static std::unique_ptr<LuaBinding_Base> BindRenderer(LuaBinding& binding);
static std::unique_ptr<LuaBinding_Base> BindPlatform(LuaBinding& binding);
#endif
protected:
LuaBinding& m_binding;
};
}
#endif // NDK_LUABINDING_BASE_HPP

View File

@ -1,33 +0,0 @@
// Copyright (C) 2017 Jérôme Leclercq
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequisites.hpp
#pragma once
#ifndef NDK_LUABINDING_CORE_HPP
#define NDK_LUABINDING_CORE_HPP
#include <Nazara/Core/Clock.hpp>
#include <Nazara/Core/Directory.hpp>
#include <Nazara/Core/File.hpp>
#include <Nazara/Core/Stream.hpp>
#include <NDK/Lua/LuaBinding_Base.hpp>
namespace Ndk
{
class NDK_API LuaBinding_Core : public LuaBinding_Base
{
public:
LuaBinding_Core(LuaBinding& binding);
~LuaBinding_Core() = default;
void Register(Nz::LuaState& state) override;
Nz::LuaClass<Nz::Clock> clock;
Nz::LuaClass<Nz::Directory> directory;
Nz::LuaClass<Nz::File> file;
Nz::LuaClass<Nz::Stream> stream;
};
}
#endif // NDK_LUABINDING_CORE_HPP

View File

@ -1,36 +0,0 @@
// Copyright (C) 2017 Jérôme Leclercq
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequisites.hpp
#pragma once
#ifndef NDK_LUABINDING_GRAPHICS_HPP
#define NDK_LUABINDING_GRAPHICS_HPP
#include <Nazara/Graphics/AbstractViewer.hpp>
#include <Nazara/Graphics/InstancedRenderable.hpp>
#include <Nazara/Graphics/Material.hpp>
#include <Nazara/Graphics/Model.hpp>
#include <Nazara/Graphics/Sprite.hpp>
#include <NDK/Lua/LuaBinding_Base.hpp>
namespace Ndk
{
class NDK_API LuaBinding_Graphics : public LuaBinding_Base
{
public:
LuaBinding_Graphics(LuaBinding& binding);
~LuaBinding_Graphics() = default;
void Register(Nz::LuaState& state) override;
Nz::LuaClass<Nz::AbstractViewer> abstractViewer;
Nz::LuaClass<Nz::InstancedRenderableRef> instancedRenderable;
Nz::LuaClass<Nz::MaterialRef> material;
Nz::LuaClass<Nz::ModelRef> model;
Nz::LuaClass<Nz::SpriteRef> sprite;
Nz::LuaClass<Nz::SpriteLibrary> spriteLibrary;
};
}
#endif // NDK_LUABINDING_GRAPHICS_HPP

View File

@ -1,37 +0,0 @@
// Copyright (C) 2017 Jérôme Leclercq
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequisites.hpp
#pragma once
#ifndef NDK_LUABINDING_MATH_HPP
#define NDK_LUABINDING_MATH_HPP
#include <Nazara/Math/EulerAngles.hpp>
#include <Nazara/Math/Matrix4.hpp>
#include <Nazara/Math/Quaternion.hpp>
#include <Nazara/Math/Rect.hpp>
#include <Nazara/Math/Vector2.hpp>
#include <Nazara/Math/Vector3.hpp>
#include <NDK/Lua/LuaBinding_Base.hpp>
namespace Ndk
{
class NDK_API LuaBinding_Math : public LuaBinding_Base
{
public:
LuaBinding_Math(LuaBinding& binding);
~LuaBinding_Math() = default;
void Register(Nz::LuaState& state) override;
Nz::LuaClass<Nz::EulerAnglesd> eulerAngles;
Nz::LuaClass<Nz::Matrix4d> matrix4d;
Nz::LuaClass<Nz::Quaterniond> quaternion;
Nz::LuaClass<Nz::Rectd> rect;
Nz::LuaClass<Nz::Vector2d> vector2d;
Nz::LuaClass<Nz::Vector3d> vector3d;
};
}
#endif // NDK_LUABINDING_MATH_HPP

View File

@ -1,31 +0,0 @@
// Copyright (C) 2017 Jérôme Leclercq
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequisites.hpp
#pragma once
#ifndef NDK_LUABINDING_NETWORK_HPP
#define NDK_LUABINDING_NETWORK_HPP
#include <Nazara/Network/AbstractSocket.hpp>
#include <Nazara/Network/IpAddress.hpp>
#include <Nazara/Network/UdpSocket.hpp>
#include <NDK/Lua/LuaBinding_Base.hpp>
namespace Ndk
{
class NDK_API LuaBinding_Network : public LuaBinding_Base
{
public:
LuaBinding_Network(LuaBinding& binding);
~LuaBinding_Network() = default;
void Register(Nz::LuaState& state) override;
Nz::LuaClass<Nz::AbstractSocket> abstractSocket;
Nz::LuaClass<Nz::IpAddress> ipAddress;
Nz::LuaClass<Nz::UdpSocket> udpSocket;
};
}
#endif // NDK_LUABINDING_NETWORK_HPP

View File

@ -1,28 +0,0 @@
// Copyright (C) 2017 Jérôme Leclercq
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequisites.hpp
#pragma once
#ifndef NDK_LUABINDING_SYSTEM_HPP
#define NDK_LUABINDING_SYSTEM_HPP
#include <Nazara/Platform/Keyboard.hpp>
#include <NDK/Lua/LuaBinding_Base.hpp>
namespace Ndk
{
class NDK_API LuaBinding_Platform : public LuaBinding_Base
{
public:
LuaBinding_Platform(LuaBinding& binding);
~LuaBinding_Platform() = default;
void Register(Nz::LuaState& state) override;
// Platform
Nz::LuaClass<Nz::Keyboard> keyboard;
};
}
#endif // NDK_LUABINDING_SYSTEM_HPP

View File

@ -1,29 +0,0 @@
// Copyright (C) 2017 Jérôme Leclercq
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequisites.hpp
#pragma once
#ifndef NDK_LUABINDING_RENDERER_HPP
#define NDK_LUABINDING_RENDERER_HPP
#include <Nazara/Renderer/Texture.hpp>
#include <NDK/Lua/LuaBinding_Base.hpp>
namespace Ndk
{
class NDK_API LuaBinding_Renderer : public LuaBinding_Base
{
public:
LuaBinding_Renderer(LuaBinding& binding);
~LuaBinding_Renderer() = default;
void Register(Nz::LuaState& state) override;
Nz::LuaClass<Nz::TextureRef> texture;
Nz::LuaClass<Nz::TextureLibrary> textureLibrary;
Nz::LuaClass<Nz::TextureManager> textureManager;
};
}
#endif // NDK_LUABINDING_RENDERER_HPP

View File

@ -1,43 +0,0 @@
// Copyright (C) 2017 Jérôme Leclercq
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequisites.hpp
#pragma once
#ifndef NDK_LUABINDING_SDK_HPP
#define NDK_LUABINDING_SDK_HPP
#include <NDK/Lua/LuaBinding_Base.hpp>
#include <NDK/Components.hpp>
#include <NDK/Console.hpp>
#include <NDK/Entity.hpp>
#include <NDK/World.hpp>
namespace Ndk
{
class Application;
class NDK_API LuaBinding_SDK : public LuaBinding_Base
{
public:
LuaBinding_SDK(LuaBinding& binding);
~LuaBinding_SDK() = default;
void Register(Nz::LuaState& state) override;
Nz::LuaClass<Application*> application;
Nz::LuaClass<EntityHandle> entity;
Nz::LuaClass<NodeComponentHandle> nodeComponent;
Nz::LuaClass<VelocityComponentHandle> velocityComponent;
Nz::LuaClass<WorldHandle> world;
#ifndef NDK_SERVER
Nz::LuaClass<CameraComponentHandle> cameraComponent;
Nz::LuaClass<ConsoleHandle> console;
Nz::LuaClass<GraphicsComponentHandle> graphicsComponent;
#endif
};
}
#endif // NDK_LUABINDING_SDK_HPP

View File

@ -1,32 +0,0 @@
// Copyright (C) 2017 Jérôme Leclercq
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequisites.hpp
#pragma once
#ifndef NDK_LUABINDING_UTILITY_HPP
#define NDK_LUABINDING_UTILITY_HPP
#include <Nazara/Utility/AbstractImage.hpp>
#include <Nazara/Utility/Font.hpp>
#include <Nazara/Utility/Node.hpp>
#include <NDK/Lua/LuaBinding_Base.hpp>
namespace Ndk
{
class NDK_API LuaBinding_Utility : public LuaBinding_Base
{
public:
LuaBinding_Utility(LuaBinding& binding);
~LuaBinding_Utility() = default;
void Register(Nz::LuaState& state) override;
// Utility
Nz::LuaClass<Nz::AbstractImageRef> abstractImage;
Nz::LuaClass<Nz::FontRef> font;
Nz::LuaClass<Nz::Node> node;
};
}
#endif // NDK_LUABINDING_UTILITY_HPP

View File

@ -1,42 +0,0 @@
// Copyright (C) 2017 Jérôme Leclercq
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequisites.hpp
#pragma once
#ifndef NDK_LUAINTERFACE_HPP
#define NDK_LUAINTERFACE_HPP
#include <NDK/Prerequisites.hpp>
namespace Nz
{
class LuaState;
}
namespace Ndk
{
class LuaBinding;
class NDK_API LuaAPI
{
public:
LuaAPI() = delete;
~LuaAPI() = delete;
static LuaBinding* GetBinding();
static bool Initialize();
static void RegisterClasses(Nz::LuaState& state);
static void Uninitialize();
private:
static LuaBinding* s_binding;
};
}
#include <NDK/LuaAPI.inl>
#endif // NDK_LUAINTERFACE_HPP

View File

@ -1,687 +0,0 @@
// Copyright (C) 2017 Jérôme Leclercq
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequisites.hpp
#include <Nazara/Core/Color.hpp>
#include <Nazara/Lua/LuaState.hpp>
#include <Nazara/Math/EulerAngles.hpp>
#include <Nazara/Math/Quaternion.hpp>
#include <Nazara/Math/Vector3.hpp>
#include <Nazara/Network/IpAddress.hpp>
#include <Nazara/Utility/Font.hpp>
#include <Nazara/Utility/Image.hpp>
#include <Nazara/Utility/Mesh.hpp>
#include <NDK/Application.hpp>
#include <NDK/Components.hpp>
#include <NDK/Entity.hpp>
#include <NDK/World.hpp>
#ifndef NDK_SERVER
#include <Nazara/Audio/Music.hpp>
#include <Nazara/Audio/SoundBuffer.hpp>
#include <Nazara/Graphics/Model.hpp>
#include <Nazara/Renderer/Texture.hpp>
#include <NDK/Console.hpp>
#endif
namespace Nz
{
inline unsigned int LuaImplQueryArg(const LuaState& state, int index, Color* color, TypeTag<Color>)
{
state.CheckType(index, Nz::LuaType_Table);
color->r = state.CheckField<UInt8>("r", index);
color->g = state.CheckField<UInt8>("g", index);
color->b = state.CheckField<UInt8>("b", index);
color->a = state.CheckField<UInt8>("a", 255, index);
return 1;
}
inline unsigned int LuaImplQueryArg(const LuaState& state, int index, EulerAnglesd* angles, TypeTag<EulerAnglesd>)
{
switch (state.GetType(index))
{
case Nz::LuaType_Table:
angles->Set(state.CheckField<double>("pitch", index), state.CheckField<double>("yaw", index), state.CheckField<double>("roll", index));
return 1;
default:
{
if (state.IsOfType(index, "EulerAngles"))
angles->Set(*static_cast<EulerAnglesd*>(state.ToUserdata(index)));
else
angles->Set(*static_cast<Quaterniond*>(state.CheckUserdata(index, "Quaternion")));
return 1;
}
}
}
inline unsigned int LuaImplQueryArg(const LuaState& state, int index, EulerAnglesf* angles, TypeTag<EulerAnglesf>)
{
EulerAnglesd anglesDouble;
unsigned int ret = LuaImplQueryArg(state, index, &anglesDouble, TypeTag<EulerAnglesd>());
angles->Set(anglesDouble);
return ret;
}
inline unsigned int LuaImplQueryArg(const LuaState& state, int index, FontRef* fontRef, TypeTag<FontRef>)
{
*fontRef = *static_cast<FontRef*>(state.CheckUserdata(index, "Font"));
return 1;
}
inline unsigned int LuaImplQueryArg(const LuaState& state, int index, FontParams* params, TypeTag<FontParams>)
{
NazaraUnused(params);
state.CheckType(index, Nz::LuaType_Table);
// Structure is empty for now
return 1;
}
inline unsigned int LuaImplQueryArg(const LuaState& state, int index, ImageParams* params, TypeTag<ImageParams>)
{
state.CheckType(index, Nz::LuaType_Table);
params->levelCount = state.CheckField<Nz::UInt8>("LevelCount");
params->loadFormat = state.CheckField<Nz::PixelFormatType>("LoadFormat");
return 1;
}
inline unsigned int LuaImplQueryArg(const LuaState& state, int index, IpAddress* address, TypeTag<IpAddress>)
{
switch (state.GetType(index))
{
case Nz::LuaType_String:
address->BuildFromAddress(state.CheckString(index));
return 1;
default:
*address = *static_cast<IpAddress*>(state.CheckUserdata(index, "IpAddress"));
return 1;
}
}
inline unsigned int LuaImplQueryArg(const LuaState& state, int index, Matrix4d* mat, TypeTag<Matrix4d>)
{
switch (state.GetType(index))
{
case Nz::LuaType_Table:
{
double values[16];
for (std::size_t i = 0; i < 16; ++i)
{
state.PushInteger(i + 1);
state.GetTable();
values[i] = state.CheckNumber(-1);
state.Pop();
}
*mat = Matrix4d(values);
return 1;
}
default:
{
if (state.IsOfType(index, "Matrix4"))
*mat = *static_cast<Matrix4d*>(state.ToUserdata(index));
return 1;
}
}
}
inline unsigned int LuaImplQueryArg(const LuaState& state, int index, Matrix4f* mat, TypeTag<Matrix4f>)
{
Matrix4d matDouble = Matrix4d::Identity();
unsigned int ret = LuaImplQueryArg(state, index, &matDouble, TypeTag<Matrix4d>());
mat->Set(matDouble);
return ret;
}
inline unsigned int LuaImplQueryArg(const LuaState& state, int index, MeshParams* params, TypeTag<MeshParams>)
{
state.CheckType(index, Nz::LuaType_Table);
params->animated = state.CheckField<bool>("Animated", params->animated);
params->center = state.CheckField<bool>("Center", params->center);
params->matrix = state.CheckField<Matrix4f>("Matrix", params->matrix);
params->optimizeIndexBuffers = state.CheckField<bool>("OptimizeIndexBuffers", params->optimizeIndexBuffers);
params->texCoordOffset = state.CheckField<Vector2f>("TexCoordOffset", params->texCoordOffset);
params->texCoordScale = state.CheckField<Vector2f>("TexCoordScale", params->texCoordScale);
return 1;
}
inline unsigned int LuaImplQueryArg(const LuaState& state, int index, Quaterniond* quat, TypeTag<Quaterniond>)
{
switch (state.GetType(index))
{
case Nz::LuaType_Table:
quat->Set(state.CheckField<double>("w", index), state.CheckField<double>("x", index), state.CheckField<double>("y", index), state.CheckField<double>("z", index));
return 1;
default:
{
if (state.IsOfType(index, "EulerAngles"))
quat->Set(*static_cast<EulerAnglesd*>(state.ToUserdata(index)));
else
quat->Set(*static_cast<Quaterniond*>(state.CheckUserdata(index, "Quaternion")));
return 1;
}
}
}
inline unsigned int LuaImplQueryArg(const LuaState& state, int index, Quaternionf* quat, TypeTag<Quaternionf>)
{
Quaterniond quatDouble;
unsigned int ret = LuaImplQueryArg(state, index, &quatDouble, TypeTag<Quaterniond>());
quat->Set(quatDouble);
return ret;
}
inline unsigned int LuaImplQueryArg(const LuaState& state, int index, Rectd* rect, TypeTag<Rectd>)
{
state.CheckType(index, LuaType_Table);
rect->x = state.CheckField<double>("x", index);
rect->y = state.CheckField<double>("y", index);
rect->width = state.CheckField<double>("width", index);
rect->height = state.CheckField<double>("height", index);
return 1;
}
inline unsigned int LuaImplQueryArg(const LuaState& state, int index, Rectf* rect, TypeTag<Rectf>)
{
Rectd rectDouble;
unsigned int ret = LuaImplQueryArg(state, index, &rectDouble, TypeTag<Rectd>());
rect->Set(rectDouble);
return ret;
}
inline unsigned int LuaImplQueryArg(const LuaState& state, int index, Recti* rect, TypeTag<Recti>)
{
Rectd rectDouble;
unsigned int ret = LuaImplQueryArg(state, index, &rectDouble, TypeTag<Rectd>());
rect->Set(rectDouble);
return ret;
}
inline unsigned int LuaImplQueryArg(const LuaState& state, int index, Rectui* rect, TypeTag<Rectui>)
{
Rectd rectDouble;
unsigned int ret = LuaImplQueryArg(state, index, &rectDouble, TypeTag<Rectd>());
rect->Set(rectDouble);
return ret;
}
inline unsigned int LuaImplQueryArg(const LuaState& state, int index, Vector2d* vec, TypeTag<Vector2d>)
{
switch (state.GetType(index))
{
case Nz::LuaType_Number:
if (index < 0 && index > -2)
state.Error("Vector2 expected, two numbers are required to convert it");
vec->Set(state.CheckNumber(index), state.CheckNumber(index + 1));
return 2;
case Nz::LuaType_Table:
vec->Set(state.CheckField<double>("x", index), state.CheckField<double>("y", index));
return 1;
default:
vec->Set(*static_cast<Vector2d*>(state.CheckUserdata(index, "Vector2")));
return 1;
}
}
inline unsigned int LuaImplQueryArg(const LuaState& state, int index, Vector2f* vec, TypeTag<Vector2f>)
{
Vector2d vecDouble;
unsigned int ret = LuaImplQueryArg(state, index, &vecDouble, TypeTag<Vector2d>());
vec->Set(vecDouble);
return ret;
}
inline unsigned int LuaImplQueryArg(const LuaState& state, int index, Vector2ui* vec, TypeTag<Vector2ui>)
{
Vector2d vecDouble;
unsigned int ret = LuaImplQueryArg(state, index, &vecDouble, TypeTag<Vector2d>());
vec->Set(vecDouble);
return ret;
}
inline unsigned int LuaImplQueryArg(const LuaState& state, int index, Vector2i* vec, TypeTag<Vector2i>)
{
Vector2d vecDouble;
unsigned int ret = LuaImplQueryArg(state, index, &vecDouble, TypeTag<Vector2d>());
vec->Set(vecDouble);
return ret;
}
inline unsigned int LuaImplQueryArg(const LuaState& state, int index, Vector3d* vec, TypeTag<Vector3d>)
{
switch (state.GetType(index))
{
case Nz::LuaType_Number:
if (index < 0 && index > -3)
state.Error("Vector3 expected, three numbers are required to convert it");
vec->Set(state.CheckNumber(index), state.CheckNumber(index + 1), state.CheckNumber(index + 2, 0.0));
return 3;
case Nz::LuaType_Table:
vec->Set(state.CheckField<double>("x", index), state.CheckField<double>("y", index), state.CheckField<double>("z", 0.0, index));
return 1;
default:
vec->Set(*static_cast<Vector3d*>(state.CheckUserdata(index, "Vector3")));
return 1;
}
}
inline unsigned int LuaImplQueryArg(const LuaState& state, int index, Vector3f* vec, TypeTag<Vector3f>)
{
Vector3d vecDouble;
unsigned int ret = LuaImplQueryArg(state, index, &vecDouble, TypeTag<Vector3d>());
vec->Set(vecDouble);
return ret;
}
inline unsigned int LuaImplQueryArg(const LuaState& state, int index, Vector3ui* vec, TypeTag<Vector3ui>)
{
Vector3d vecDouble;
unsigned int ret = LuaImplQueryArg(state, index, &vecDouble, TypeTag<Vector3d>());
vec->Set(vecDouble);
return ret;
}
inline unsigned int LuaImplQueryArg(const LuaState& state, int index, Vector3i* vec, TypeTag<Vector3i>)
{
Vector3d vecDouble;
unsigned int ret = LuaImplQueryArg(state, index, &vecDouble, TypeTag<Vector3d>());
vec->Set(vecDouble);
return ret;
}
inline unsigned int LuaImplQueryArg(const LuaState& state, int index, Ndk::Entity** handle, TypeTag<Ndk::Entity*>)
{
if (!state.IsOfType(index, LuaType_Nil))
*handle = *static_cast<Ndk::EntityHandle*>(state.CheckUserdata(index, "Entity"));
else
*handle = nullptr;
return 1;
}
inline unsigned int LuaImplQueryArg(const LuaState& state, int index, Ndk::EntityHandle* handle, TypeTag<Ndk::EntityHandle>)
{
if (!state.IsOfType(index, LuaType_Nil))
*handle = *static_cast<Ndk::EntityHandle*>(state.CheckUserdata(index, "Entity"));
else
handle->Reset();
return 1;
}
inline unsigned int LuaImplQueryArg(const LuaState& state, int index, Ndk::WorldHandle* handle, TypeTag<Ndk::WorldHandle>)
{
*handle = *static_cast<Ndk::WorldHandle*>(state.CheckUserdata(index, "World"));
return 1;
}
#ifndef NDK_SERVER
inline unsigned int LuaImplQueryArg(const LuaState& state, int index, InstancedRenderableRef* renderable, TypeTag<InstancedRenderableRef>)
{
if (state.IsOfType(index, "InstancedRenderable") ||
state.IsOfType(index, "Model") ||
state.IsOfType(index, "Sprite"))
{
*renderable = *static_cast<InstancedRenderableRef*>(state.ToUserdata(index));
}
else
state.ArgError(index, "is not a InstancedRenderable instance");
return 1;
}
inline unsigned int LuaImplQueryArg(const LuaState& state, int index, MaterialRef* materialRef, TypeTag<MaterialRef>)
{
*materialRef = *static_cast<MaterialRef*>(state.CheckUserdata(index, "Material"));
return 1;
}
inline unsigned int LuaImplQueryArg(const LuaState& state, int index, MaterialParams* params, TypeTag<MaterialParams>)
{
state.CheckType(index, Nz::LuaType_Table);
params->loadAlphaMap = state.CheckField<bool>("LoadAlphaMap", params->loadAlphaMap);
params->loadDiffuseMap = state.CheckField<bool>("LoadDiffuseMap", params->loadDiffuseMap);
params->loadEmissiveMap = state.CheckField<bool>("LoadEmissiveMap", params->loadEmissiveMap);
params->loadHeightMap = state.CheckField<bool>("LoadHeightMap", params->loadHeightMap);
params->loadNormalMap = state.CheckField<bool>("LoadNormalMap", params->loadNormalMap);
params->loadSpecularMap = state.CheckField<bool>("LoadSpecularMap", params->loadSpecularMap);
params->shaderName = state.CheckField<String>("ShaderName", params->shaderName);
return 1;
}
inline unsigned int LuaImplQueryArg(const LuaState& state, int index, ModelParameters* params, TypeTag<ModelParameters>)
{
state.CheckType(index, Nz::LuaType_Table);
params->loadMaterials = state.CheckField<bool>("LoadMaterials", params->loadMaterials);
LuaImplQueryArg(state, -1, &params->material, TypeTag<MaterialParams>());
LuaImplQueryArg(state, -1, &params->mesh, TypeTag<MeshParams>());
return 1;
}
inline unsigned int LuaImplQueryArg(const LuaState& state, int index, SoundBufferParams* params, TypeTag<SoundBufferParams>)
{
state.CheckType(index, Nz::LuaType_Table);
params->forceMono = state.CheckField<bool>("ForceMono", params->forceMono);
return 1;
}
inline unsigned int LuaImplQueryArg(const LuaState& state, int index, SoundStreamParams* params, TypeTag<SoundStreamParams>)
{
state.CheckType(index, Nz::LuaType_Table);
params->forceMono = state.CheckField<bool>("ForceMono", params->forceMono);
return 1;
}
inline unsigned int LuaImplQueryArg(const LuaState& state, int index, SpriteRef* spriteRef, TypeTag<SpriteRef>)
{
*spriteRef = *static_cast<SpriteRef*>(state.CheckUserdata(index, "Sprite"));
return 1;
}
inline unsigned int LuaImplQueryArg(const LuaState& state, int index, TextureRef* textureRef, TypeTag<TextureRef>)
{
*textureRef = *static_cast<TextureRef*>(state.CheckUserdata(index, "Texture"));
return 1;
}
#endif
inline int LuaImplReplyVal(const LuaState& state, Color&& val, TypeTag<Color>)
{
state.PushTable();
state.PushField("r", val.r);
state.PushField("g", val.g);
state.PushField("b", val.b);
state.PushField("a", val.a);
return 1;
}
inline int LuaImplReplyVal(const LuaState& state, EulerAnglesd&& val, TypeTag<EulerAnglesd>)
{
state.PushInstance<EulerAnglesd>("EulerAngles", val);
return 1;
}
inline int LuaImplReplyVal(const LuaState& state, EulerAnglesf&& val, TypeTag<EulerAnglesf>)
{
state.PushInstance<EulerAnglesd>("EulerAngles", val);
return 1;
}
inline int LuaImplReplyVal(const LuaState& state, FontRef&& val, TypeTag<FontRef>)
{
state.PushInstance<FontRef>("Font", val);
return 1;
}
inline int LuaImplReplyVal(const LuaState& state, Font::SizeInfo&& val, TypeTag<Font::SizeInfo>)
{
state.PushTable();
state.PushField("LineHeight", val.lineHeight);
state.PushField("SpaceAdvance", val.spaceAdvance);
state.PushField("UnderlinePosition", val.underlinePosition);
state.PushField("UnderlineThickness", val.underlineThickness);
return 1;
}
inline int LuaImplReplyVal(const LuaState& state, ImageParams&& val, TypeTag<ImageParams>)
{
state.PushTable(0, 2);
state.PushField("LevelCount", val.levelCount);
state.PushField("LoadFormat", val.loadFormat);
return 1;
}
inline int LuaImplReplyVal(const LuaState& state, IpAddress&& val, TypeTag<IpAddress>)
{
state.PushInstance<IpAddress>("IpAddress", val);
return 1;
}
inline int LuaImplReplyVal(const LuaState& state, Matrix4d&& val, TypeTag<Matrix4d>)
{
state.PushInstance<Matrix4d>("Matrix4", val);
return 1;
}
inline int LuaImplReplyVal(const LuaState& state, Matrix4f&& val, TypeTag<Matrix4f>)
{
state.PushInstance<Matrix4d>("Matrix4", val);
return 1;
}
inline int LuaImplReplyVal(const LuaState& state, Quaterniond&& val, TypeTag<Quaterniond>)
{
state.PushInstance<Quaterniond>("Quaternion", val);
return 1;
}
inline int LuaImplReplyVal(const LuaState& state, Quaternionf&& val, TypeTag<Quaternionf>)
{
state.PushInstance<Quaterniond>("Quaternion", val);
return 1;
}
inline int LuaImplReplyVal(const LuaState& state, Rectd&& val, TypeTag<Rectd>)
{
state.PushInstance<Rectd>("Rect", val);
return 1;
}
inline int LuaImplReplyVal(const LuaState& state, Rectf&& val, TypeTag<Rectf>)
{
state.PushInstance<Rectd>("Rect", val);
return 1;
}
inline int LuaImplReplyVal(const LuaState& state, Recti&& val, TypeTag<Recti>)
{
state.PushInstance<Rectd>("Rect", val);
return 1;
}
inline int LuaImplReplyVal(const LuaState& state, Rectui&& val, TypeTag<Rectui>)
{
state.PushInstance<Rectd>("Rect", val);
return 1;
}
inline int LuaImplReplyVal(const LuaState& state, Vector2d&& val, TypeTag<Vector2d>)
{
state.PushInstance<Vector2d>("Vector2", val);
return 1;
}
inline int LuaImplReplyVal(const LuaState& state, Vector2f&& val, TypeTag<Vector2f>)
{
state.PushInstance<Vector2d>("Vector2", val);
return 1;
}
inline int LuaImplReplyVal(const LuaState& state, Vector2ui&& val, TypeTag<Vector2ui>)
{
state.PushInstance<Vector2d>("Vector2", val);
return 1;
}
inline int LuaImplReplyVal(const LuaState& state, Vector2i&& val, TypeTag<Vector2i>)
{
state.PushInstance<Vector2d>("Vector2", val);
return 1;
}
inline int LuaImplReplyVal(const LuaState& state, Vector3d&& val, TypeTag<Vector3d>)
{
state.PushInstance<Vector3d>("Vector3", val);
return 1;
}
inline int LuaImplReplyVal(const LuaState& state, Vector3f&& val, TypeTag<Vector3f>)
{
state.PushInstance<Vector3d>("Vector3", val);
return 1;
}
inline int LuaImplReplyVal(const LuaState& state, Vector3ui&& val, TypeTag<Vector3ui>)
{
state.PushInstance<Vector3d>("Vector3", val);
return 1;
}
inline int LuaImplReplyVal(const LuaState& state, Vector3i&& val, TypeTag<Vector3i>)
{
state.PushInstance<Vector3d>("Vector3", val);
return 1;
}
inline int LuaImplReplyVal(const LuaState& state, Ndk::Entity* ptr, TypeTag<Ndk::Entity*>)
{
state.PushInstance<Ndk::EntityHandle>("Entity", ptr);
return 1;
}
inline int LuaImplReplyVal(const LuaState& state, Ndk::Application* ptr, TypeTag<Ndk::Application*>)
{
state.PushInstance<Ndk::Application*>("Application", ptr);
return 1;
}
inline int LuaImplReplyVal(const LuaState& state, Ndk::EntityHandle&& handle, TypeTag<Ndk::EntityHandle>)
{
state.PushInstance<Ndk::EntityHandle>("Entity", handle);
return 1;
}
inline int LuaImplReplyVal(const LuaState& state, Ndk::NodeComponentHandle&& handle, TypeTag<Ndk::NodeComponentHandle>)
{
state.PushInstance<Ndk::NodeComponentHandle>("NodeComponent", handle);
return 1;
}
inline int LuaImplReplyVal(const LuaState& state, Ndk::VelocityComponentHandle&& handle, TypeTag<Ndk::VelocityComponentHandle>)
{
state.PushInstance<Ndk::VelocityComponentHandle>("VelocityComponent", handle);
return 1;
}
inline int LuaImplReplyVal(const LuaState& state, Ndk::World* ptr, TypeTag<Ndk::World*>)
{
state.PushInstance<Ndk::WorldHandle>("World", ptr);
return 1;
}
inline int LuaImplReplyVal(const LuaState& state, Ndk::WorldHandle&& handle, TypeTag<Ndk::WorldHandle>)
{
state.PushInstance<Ndk::WorldHandle>("World", handle);
return 1;
}
#ifndef NDK_SERVER
inline int LuaImplReplyVal(const LuaState& state, MaterialRef&& handle, TypeTag<MaterialRef>)
{
state.PushInstance<MaterialRef>("Material", handle);
return 1;
}
inline int LuaImplReplyVal(const LuaState& state, ModelRef&& handle, TypeTag<ModelRef>)
{
state.PushInstance<ModelRef>("Model", handle);
return 1;
}
inline int LuaImplReplyVal(const LuaState& state, const SoundBuffer* val, TypeTag<const SoundBuffer*>)
{
state.PushInstance<SoundBufferConstRef>("SoundBuffer", val);
return 1;
}
inline int LuaImplReplyVal(const LuaState& state, SoundBufferRef&& handle, TypeTag<SoundBufferRef>)
{
state.PushInstance<SoundBufferRef>("SoundBuffer", handle);
return 1;
}
inline int LuaImplReplyVal(const LuaState& state, SpriteRef&& handle, TypeTag<SpriteRef>)
{
state.PushInstance<SpriteRef>("Sprite", handle);
return 1;
}
inline int LuaImplReplyVal(const LuaState& state, TextureRef&& handle, TypeTag<TextureRef>)
{
state.PushInstance<TextureRef>("Texture", handle);
return 1;
}
inline int LuaImplReplyVal(const LuaState& state, Ndk::CameraComponentHandle&& handle, TypeTag<Ndk::CameraComponentHandle>)
{
state.PushInstance<Ndk::CameraComponentHandle>("CameraComponent", handle);
return 1;
}
inline int LuaImplReplyVal(const LuaState& state, Ndk::ConsoleHandle&& handle, TypeTag<Ndk::ConsoleHandle>)
{
state.PushInstance<Ndk::ConsoleHandle>("Console", handle);
return 1;
}
inline int LuaImplReplyVal(const LuaState& state, Ndk::GraphicsComponentHandle&& handle, TypeTag<Ndk::GraphicsComponentHandle>)
{
state.PushInstance<Ndk::GraphicsComponentHandle>("GraphicsComponent", handle);
return 1;
}
#endif
}

View File

@ -1,31 +0,0 @@
// Copyright (C) 2017 Jérôme Leclercq
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequisites.hpp
#pragma once
#ifndef NDK_SDK_HPP
#define NDK_SDK_HPP
#include <NDK/Prerequisites.hpp>
namespace Ndk
{
class NDK_API Sdk
{
public:
Sdk() = delete;
~Sdk() = delete;
static bool Initialize();
static bool IsInitialized();
static void Uninitialize();
private:
static unsigned int s_referenceCounter;
};
}
#include <NDK/Sdk.inl>
#endif // NDK_SDK_HPP

View File

@ -1,16 +0,0 @@
// Copyright (C) 2017 Jérôme Leclercq
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequisites.hpp
namespace Ndk
{
/*!
* \brief Checks whether the module is initialized
* \return true if module is initialized
*/
inline bool Sdk::IsInitialized()
{
return s_referenceCounter != 0;
}
}

View File

@ -1,17 +0,0 @@
// This file was automatically generated
#pragma once
#ifndef NDK_SYSTEMS_GLOBAL_HPP
#define NDK_SYSTEMS_GLOBAL_HPP
#include <NDK/Systems/DebugSystem.hpp>
#include <NDK/Systems/LifetimeSystem.hpp>
#include <NDK/Systems/ListenerSystem.hpp>
#include <NDK/Systems/ParticleSystem.hpp>
#include <NDK/Systems/PhysicsSystem2D.hpp>
#include <NDK/Systems/PhysicsSystem3D.hpp>
#include <NDK/Systems/RenderSystem.hpp>
#include <NDK/Systems/VelocitySystem.hpp>
#endif // NDK_SYSTEMS_GLOBAL_HPP

View File

@ -1,58 +0,0 @@
// Copyright (C) 2017 Jérôme Leclercq
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequisites.hpp
#pragma once
#ifndef NDK_SERVER
#ifndef NDK_SYSTEMS_DEBUGSYSTEM_HPP
#define NDK_SYSTEMS_DEBUGSYSTEM_HPP
#include <Nazara/Graphics/InstancedRenderable.hpp>
#include <Nazara/Utility/IndexBuffer.hpp>
#include <Nazara/Utility/Mesh.hpp>
#include <Nazara/Utility/VertexBuffer.hpp>
#include <NDK/System.hpp>
namespace Ndk
{
class NDK_API DebugSystem : public System<DebugSystem>
{
public:
DebugSystem();
~DebugSystem() = default;
void EnableDepthBuffer(bool enable);
inline bool IsDepthBufferEnabled() const;
static SystemIndex systemIndex;
private:
Nz::InstancedRenderableRef GenerateBox(Nz::Boxf box);
Nz::InstancedRenderableRef GenerateCollision2DMesh(Entity* entity, Nz::Vector3f* offset);
Nz::InstancedRenderableRef GenerateCollision3DMesh(Entity* entity);
std::pair<Nz::IndexBufferRef, Nz::VertexBufferRef> GetBoxMesh();
Nz::MaterialRef GetCollisionMaterial();
Nz::MaterialRef GetGlobalAABBMaterial();
Nz::MaterialRef GetLocalAABBMaterial();
Nz::MaterialRef GetOBBMaterial();
void OnEntityValidation(Entity* entity, bool justAdded) override;
void OnUpdate(float elapsedTime) override;
Nz::MaterialRef m_globalAabbMaterial;
Nz::MaterialRef m_localAabbMaterial;
Nz::MaterialRef m_collisionMaterial;
Nz::MaterialRef m_obbMaterial;
Nz::IndexBufferRef m_boxMeshIndexBuffer;
Nz::VertexBufferRef m_boxMeshVertexBuffer;
bool m_isDepthBufferEnabled;
};
}
#include <NDK/Systems/DebugSystem.inl>
#endif // NDK_SYSTEMS_DEBUGSYSTEM_HPP
#endif // NDK_SERVER

View File

@ -1,13 +0,0 @@
// Copyright (C) 2017 Jérôme Leclercq
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequisites.hpp
#include <NDK/Systems/DebugSystem.hpp>
namespace Ndk
{
inline bool DebugSystem::IsDepthBufferEnabled() const
{
return m_isDepthBufferEnabled;
}
}

View File

@ -1,31 +0,0 @@
// Copyright (C) 2017 Jérôme Leclercq
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequisites.hpp
#pragma once
#ifndef NDK_SERVER
#ifndef NDK_SYSTEMS_PARTICLESYSTEM_HPP
#define NDK_SYSTEMS_PARTICLESYSTEM_HPP
#include <NDK/System.hpp>
namespace Ndk
{
class NDK_API ParticleSystem : public System<ParticleSystem>
{
public:
ParticleSystem();
~ParticleSystem() = default;
static SystemIndex systemIndex;
private:
void OnUpdate(float elapsedTime) override;
};
}
#include <NDK/Systems/ParticleSystem.inl>
#endif // NDK_SYSTEMS_PARTICLESYSTEM_HPP
#endif // NDK_SERVER

View File

@ -1,85 +0,0 @@
// Copyright (C) 2017 Jérôme Leclercq
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequisites.hpp
#pragma once
#ifndef NDK_SERVER
#ifndef NDK_SYSTEMS_RENDERSYSTEM_HPP
#define NDK_SYSTEMS_RENDERSYSTEM_HPP
#include <Nazara/Graphics/AbstractBackground.hpp>
#include <Nazara/Graphics/CullingList.hpp>
#include <Nazara/Graphics/DepthRenderTechnique.hpp>
#include <Nazara/Renderer/RenderTexture.hpp>
#include <NDK/EntityList.hpp>
#include <NDK/System.hpp>
#include <NDK/Components/GraphicsComponent.hpp>
#include <vector>
namespace Ndk
{
class AbstractViewer;
class NDK_API RenderSystem : public System<RenderSystem>
{
public:
RenderSystem();
~RenderSystem() = default;
template<typename T> T& ChangeRenderTechnique();
inline Nz::AbstractRenderTechnique& ChangeRenderTechnique(std::unique_ptr<Nz::AbstractRenderTechnique>&& renderTechnique);
inline void EnableCulling(bool enable);
inline const Nz::BackgroundRef& GetDefaultBackground() const;
inline const Nz::Matrix4f& GetCoordinateSystemMatrix() const;
inline Nz::Vector3f GetGlobalForward() const;
inline Nz::Vector3f GetGlobalRight() const;
inline Nz::Vector3f GetGlobalUp() const;
inline Nz::AbstractRenderTechnique& GetRenderTechnique() const;
inline bool IsCullingEnabled() const;
inline void SetDefaultBackground(Nz::BackgroundRef background);
inline void SetGlobalForward(const Nz::Vector3f& direction);
inline void SetGlobalRight(const Nz::Vector3f& direction);
inline void SetGlobalUp(const Nz::Vector3f& direction);
static SystemIndex systemIndex;
private:
inline void InvalidateCoordinateSystem();
void OnEntityRemoved(Entity* entity) override;
void OnEntityValidation(Entity* entity, bool justAdded) override;
void OnUpdate(float elapsedTime) override;
void UpdateDynamicReflections();
void UpdateDirectionalShadowMaps(const Nz::AbstractViewer& viewer);
void UpdatePointSpotShadowMaps();
std::unique_ptr<Nz::AbstractRenderTechnique> m_renderTechnique;
std::vector<GraphicsComponentCullingList::VolumeEntry> m_volumeEntries;
std::vector<EntityHandle> m_cameras;
EntityList m_drawables;
EntityList m_directionalLights;
EntityList m_lights;
EntityList m_pointSpotLights;
EntityList m_particleGroups;
EntityList m_realtimeReflected;
GraphicsComponentCullingList m_drawableCulling;
Nz::BackgroundRef m_background;
Nz::DepthRenderTechnique m_shadowTechnique;
Nz::Matrix4f m_coordinateSystemMatrix;
Nz::RenderTexture m_shadowRT;
bool m_coordinateSystemInvalidated;
bool m_forceRenderQueueInvalidation;
bool m_isCullingEnabled;
};
}
#include <NDK/Systems/RenderSystem.inl>
#endif // NDK_SYSTEMS_RENDERSYSTEM_HPP
#endif // NDK_SERVER

View File

@ -1,186 +0,0 @@
// Copyright (C) 2017 Jérôme Leclercq
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequisites.hpp
#include <NDK/Systems/RenderSystem.hpp>
namespace Ndk
{
/*!
* \brief Changes the render technique used for the system
* \return A reference to the render technique type
*/
template<typename T>
inline T& RenderSystem::ChangeRenderTechnique()
{
static_assert(std::is_base_of<Nz::AbstractRenderTechnique, T>::value, "RenderTechnique is not a subtype of AbstractRenderTechnique");
return static_cast<T&>(ChangeRenderTechnique(std::make_unique<T>()));
}
/*!
* \brief Changes the render technique used for the system
* \return A reference to the abstract render technique
*
* \param renderTechnique Render technique to use
*/
inline Nz::AbstractRenderTechnique& RenderSystem::ChangeRenderTechnique(std::unique_ptr<Nz::AbstractRenderTechnique>&& renderTechnique)
{
m_renderTechnique = std::move(renderTechnique);
return *m_renderTechnique;
}
/*!
* \brief Enables/disables object culling
*
* Object culling is an algorithm used by the render system to detect invisible objects (which will not appear on screen) before they are rendered.
* This includes Frustum Culling and potentially Occlusion Culling.
*
* Disabling this is not recommended, as the system will draw every object in the world which could induce a performance loss.
*
* \param enable Whether to enable or disable culling
*
* \see IsCullingEnabled
*/
inline void RenderSystem::EnableCulling(bool enable)
{
m_isCullingEnabled = enable;
}
/*!
* \brief Gets the background used for rendering
* \return A reference to the background
*/
inline const Nz::BackgroundRef& RenderSystem::GetDefaultBackground() const
{
return m_background;
}
/*!
* \brief Gets the coordinates matrix used for rendering
* \return A constant reference to the matrix of coordinates
*/
inline const Nz::Matrix4f& RenderSystem::GetCoordinateSystemMatrix() const
{
return m_coordinateSystemMatrix;
}
/*!
* \brief Gets the "forward" global direction
* \return The forward direction, by default, it's -UnitZ() (Right hand coordinates)
*/
inline Nz::Vector3f RenderSystem::GetGlobalForward() const
{
return Nz::Vector3f(-m_coordinateSystemMatrix.m13, -m_coordinateSystemMatrix.m23, -m_coordinateSystemMatrix.m33);
}
/*!
* \brief Gets the "right" global direction
* \return The right direction, by default, it's UnitX() (Right hand coordinates)
*/
inline Nz::Vector3f RenderSystem::GetGlobalRight() const
{
return Nz::Vector3f(m_coordinateSystemMatrix.m11, m_coordinateSystemMatrix.m21, m_coordinateSystemMatrix.m31);
}
/*!
* \brief Gets the "up" global direction
* \return The up direction, by default, it's UnitY() (Right hand coordinates)
*/
inline Nz::Vector3f RenderSystem::GetGlobalUp() const
{
return Nz::Vector3f(m_coordinateSystemMatrix.m12, m_coordinateSystemMatrix.m22, m_coordinateSystemMatrix.m32);
}
/*!
* \brief Gets the render technique used for rendering
* \return A reference to the abstract render technique being used
*/
inline Nz::AbstractRenderTechnique& RenderSystem::GetRenderTechnique() const
{
return *m_renderTechnique.get();
}
/*!
* \brief Query if culling is enabled (enabled by default)
* \return True if culling is enabled, false otherwise
*
* \see EnableCulling
*/
inline bool RenderSystem::IsCullingEnabled() const
{
return m_isCullingEnabled;
}
/*!
* \brief Sets the background used for rendering
*
* \param background A reference to the background
*/
inline void RenderSystem::SetDefaultBackground(Nz::BackgroundRef background)
{
m_background = std::move(background);
}
/*!
* \brief Sets the "forward" global direction
*
* \param direction The new forward direction
*/
inline void RenderSystem::SetGlobalForward(const Nz::Vector3f& direction)
{
m_coordinateSystemMatrix.m13 = -direction.x;
m_coordinateSystemMatrix.m23 = -direction.y;
m_coordinateSystemMatrix.m33 = -direction.z;
InvalidateCoordinateSystem();
}
/*!
* \brief Sets the "right" global direction
*
* \param direction The new right direction
*/
inline void RenderSystem::SetGlobalRight(const Nz::Vector3f& direction)
{
m_coordinateSystemMatrix.m11 = direction.x;
m_coordinateSystemMatrix.m21 = direction.y;
m_coordinateSystemMatrix.m31 = direction.z;
InvalidateCoordinateSystem();
}
/*!
* \brief Sets the "up" global direction
*
* \param direction The new up direction
*/
inline void RenderSystem::SetGlobalUp(const Nz::Vector3f& direction)
{
m_coordinateSystemMatrix.m12 = direction.x;
m_coordinateSystemMatrix.m22 = direction.y;
m_coordinateSystemMatrix.m32 = direction.z;
InvalidateCoordinateSystem();
}
/*!
* \brief Invalidates the matrix of coordinates for the system
*/
inline void RenderSystem::InvalidateCoordinateSystem()
{
m_coordinateSystemInvalidated = true;
}
}

View File

@ -1,20 +0,0 @@
// This file was automatically generated
#pragma once
#ifndef NDK_WIDGETS_GLOBAL_HPP
#define NDK_WIDGETS_GLOBAL_HPP
#include <NDK/Widgets/AbstractTextAreaWidget.hpp>
#include <NDK/Widgets/BoxLayout.hpp>
#include <NDK/Widgets/ButtonWidget.hpp>
#include <NDK/Widgets/CheckboxWidget.hpp>
#include <NDK/Widgets/Enums.hpp>
#include <NDK/Widgets/ImageWidget.hpp>
#include <NDK/Widgets/LabelWidget.hpp>
#include <NDK/Widgets/ProgressBarWidget.hpp>
#include <NDK/Widgets/RichTextAreaWidget.hpp>
#include <NDK/Widgets/ScrollAreaWidget.hpp>
#include <NDK/Widgets/TextAreaWidget.hpp>
#endif // NDK_WIDGETS_GLOBAL_HPP

View File

@ -1,135 +0,0 @@
// Copyright (C) 2017 Jérôme Leclercq
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequisites.hpp
#pragma once
#ifndef NDK_WIDGETS_ABSTRACTTEXTAREAWIDGET_HPP
#define NDK_WIDGETS_ABSTRACTTEXTAREAWIDGET_HPP
#include <Nazara/Graphics/TextSprite.hpp>
#include <Nazara/Utility/AbstractTextDrawer.hpp>
#include <NDK/BaseWidget.hpp>
#include <NDK/Widgets/Enums.hpp>
#include <functional>
#include <vector>
namespace Ndk
{
class NDK_API AbstractTextAreaWidget : public BaseWidget
{
public:
using CharacterFilter = std::function<bool(char32_t)>;
AbstractTextAreaWidget(BaseWidget* parent);
AbstractTextAreaWidget(const AbstractTextAreaWidget&) = delete;
AbstractTextAreaWidget(AbstractTextAreaWidget&&) = default;
~AbstractTextAreaWidget() = default;
virtual void Clear();
//virtual TextAreaWidget* Clone() const = 0;
void EnableLineWrap(bool enable = true);
inline void EnableMultiline(bool enable = true);
inline void EnableTabWriting(bool enable = true);
inline void Erase(std::size_t glyphPosition);
virtual void Erase(std::size_t firstGlyph, std::size_t lastGlyph) = 0;
inline void EraseSelection();
inline const CharacterFilter& GetCharacterFilter() const;
inline const Nz::Vector2ui& GetCursorPosition() const;
inline Nz::Vector2ui GetCursorPosition(std::size_t glyphIndex) const;
inline EchoMode GetEchoMode() const;
inline std::size_t GetGlyphIndex() const;
inline std::size_t GetGlyphIndex(const Nz::Vector2ui& cursorPosition) const;
inline const Nz::String& GetText() const;
Nz::Vector2ui GetHoveredGlyph(float x, float y) const;
inline bool HasSelection() const;
inline bool IsLineWrapEnabled() const;
inline bool IsMultilineEnabled() const;
inline bool IsReadOnly() const;
inline bool IsTabWritingEnabled() const;
inline void MoveCursor(int offset);
inline void MoveCursor(const Nz::Vector2i& offset);
inline Nz::Vector2ui NormalizeCursorPosition(Nz::Vector2ui cursorPosition) const;
inline void SetCharacterFilter(CharacterFilter filter);
inline void SetCursorPosition(std::size_t glyphIndex);
inline void SetCursorPosition(Nz::Vector2ui cursorPosition);
inline void SetEchoMode(EchoMode echoMode);
inline void SetReadOnly(bool readOnly = true);
inline void SetSelection(Nz::Vector2ui fromPosition, Nz::Vector2ui toPosition);
inline void Write(const Nz::String& text);
inline void Write(const Nz::String& text, const Nz::Vector2ui& glyphPosition);
virtual void Write(const Nz::String& text, std::size_t glyphPosition) = 0;
AbstractTextAreaWidget& operator=(const AbstractTextAreaWidget&) = delete;
AbstractTextAreaWidget& operator=(AbstractTextAreaWidget&&) = default;
NazaraSignal(OnTextAreaCursorMove, const AbstractTextAreaWidget* /*textArea*/, Nz::Vector2ui* /*newCursorPosition*/);
NazaraSignal(OnTextAreaKeyBackspace, const AbstractTextAreaWidget* /*textArea*/, bool* /*ignoreDefaultAction*/);
NazaraSignal(OnTextAreaKeyDown, const AbstractTextAreaWidget* /*textArea*/, bool* /*ignoreDefaultAction*/);
NazaraSignal(OnTextAreaKeyEnd, const AbstractTextAreaWidget* /*textArea*/, bool* /*ignoreDefaultAction*/);
NazaraSignal(OnTextAreaKeyHome, const AbstractTextAreaWidget* /*textArea*/, bool* /*ignoreDefaultAction*/);
NazaraSignal(OnTextAreaKeyLeft, const AbstractTextAreaWidget* /*textArea*/, bool* /*ignoreDefaultAction*/);
NazaraSignal(OnTextAreaKeyReturn, const AbstractTextAreaWidget* /*textArea*/, bool* /*ignoreDefaultAction*/);
NazaraSignal(OnTextAreaKeyRight, const AbstractTextAreaWidget* /*textArea*/, bool* /*ignoreDefaultAction*/);
NazaraSignal(OnTextAreaKeyUp, const AbstractTextAreaWidget* /*textArea*/, bool* /*ignoreDefaultAction*/);
NazaraSignal(OnTextAreaSelection, const AbstractTextAreaWidget* /*textArea*/, Nz::Vector2ui* /*start*/, Nz::Vector2ui* /*end*/);
protected:
virtual Nz::AbstractTextDrawer& GetTextDrawer() = 0;
virtual const Nz::AbstractTextDrawer& GetTextDrawer() const = 0;
void Layout() override;
virtual void HandleIndentation(bool add) = 0;
virtual void HandleSelectionIndentation(bool add) = 0;
virtual void HandleWordCursorMove(bool left) = 0;
bool IsFocusable() const override;
void OnFocusLost() override;
void OnFocusReceived() override;
bool OnKeyPressed(const Nz::WindowEvent::KeyEvent& key) override;
void OnKeyReleased(const Nz::WindowEvent::KeyEvent& key) override;
void OnMouseButtonPress(int /*x*/, int /*y*/, Nz::Mouse::Button button) override;
void OnMouseButtonRelease(int /*x*/, int /*y*/, Nz::Mouse::Button button) override;
void OnMouseEnter() override;
void OnMouseMoved(int x, int y, int deltaX, int deltaY) override;
void OnTextEntered(char32_t character, bool repeated) override;
inline void SetCursorPositionInternal(std::size_t glyphIndex);
inline void SetCursorPositionInternal(Nz::Vector2ui cursorPosition);
void RefreshCursor();
virtual void UpdateDisplayText() = 0;
void UpdateTextSprite();
CharacterFilter m_characterFilter;
EchoMode m_echoMode;
EntityHandle m_cursorEntity;
EntityHandle m_textEntity;
Nz::TextSpriteRef m_textSprite;
Nz::Vector2ui m_cursorPositionBegin;
Nz::Vector2ui m_cursorPositionEnd;
Nz::Vector2ui m_selectionCursor;
std::vector<Nz::SpriteRef> m_cursorSprites;
bool m_isLineWrapEnabled;
bool m_isMouseButtonDown;
bool m_multiLineEnabled;
bool m_readOnly;
bool m_tabEnabled; // writes (Shift+)Tab character if set to true
};
}
#include <NDK/Widgets/AbstractTextAreaWidget.inl>
#endif // NDK_WIDGETS_ABSTRACTTEXTAREAWIDGET_HPP

View File

@ -1,252 +0,0 @@
// Copyright (C) 2017 Jérôme Leclercq
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequisites.hpp
#include <NDK/Widgets/AbstractTextAreaWidget.hpp>
namespace Ndk
{
inline void AbstractTextAreaWidget::EnableMultiline(bool enable)
{
m_multiLineEnabled = enable;
}
inline void AbstractTextAreaWidget::EnableTabWriting(bool enable)
{
m_tabEnabled = enable;
}
inline void AbstractTextAreaWidget::Erase(std::size_t glyphPosition)
{
Erase(glyphPosition, glyphPosition + 1U);
}
inline void AbstractTextAreaWidget::EraseSelection()
{
if (!HasSelection())
return;
Erase(GetGlyphIndex(m_cursorPositionBegin), GetGlyphIndex(m_cursorPositionEnd));
}
inline const AbstractTextAreaWidget::CharacterFilter& AbstractTextAreaWidget::GetCharacterFilter() const
{
return m_characterFilter;
}
inline const Nz::Vector2ui& AbstractTextAreaWidget::GetCursorPosition() const
{
return m_cursorPositionBegin;
}
Nz::Vector2ui AbstractTextAreaWidget::GetCursorPosition(std::size_t glyphIndex) const
{
const Nz::AbstractTextDrawer& textDrawer = GetTextDrawer();
glyphIndex = std::min(glyphIndex, GetTextDrawer().GetGlyphCount());
std::size_t lineCount = textDrawer.GetLineCount();
std::size_t line = 0U;
for (std::size_t i = line + 1; i < lineCount; ++i)
{
if (textDrawer.GetLine(i).glyphIndex > glyphIndex)
break;
line = i;
}
const auto& lineInfo = textDrawer.GetLine(line);
Nz::Vector2ui cursorPos;
cursorPos.y = static_cast<unsigned int>(line);
cursorPos.x = static_cast<unsigned int>(glyphIndex - lineInfo.glyphIndex);
return cursorPos;
}
inline EchoMode AbstractTextAreaWidget::GetEchoMode() const
{
return m_echoMode;
}
inline std::size_t AbstractTextAreaWidget::GetGlyphIndex() const
{
return GetGlyphIndex(m_cursorPositionBegin);
}
inline std::size_t AbstractTextAreaWidget::GetGlyphIndex(const Nz::Vector2ui& cursorPosition) const
{
const Nz::AbstractTextDrawer& textDrawer = GetTextDrawer();
std::size_t glyphIndex = textDrawer.GetLine(cursorPosition.y).glyphIndex + cursorPosition.x;
if (textDrawer.GetLineCount() > cursorPosition.y + 1)
glyphIndex = std::min(glyphIndex, textDrawer.GetLine(cursorPosition.y + 1).glyphIndex - 1);
else
glyphIndex = std::min(glyphIndex, textDrawer.GetGlyphCount());
return glyphIndex;
}
inline bool AbstractTextAreaWidget::HasSelection() const
{
return m_cursorPositionBegin != m_cursorPositionEnd;
}
inline bool AbstractTextAreaWidget::IsLineWrapEnabled() const
{
return m_isLineWrapEnabled;
}
inline bool AbstractTextAreaWidget::IsMultilineEnabled() const
{
return m_multiLineEnabled;
}
inline bool AbstractTextAreaWidget::IsTabWritingEnabled() const
{
return m_tabEnabled;
}
inline bool AbstractTextAreaWidget::IsReadOnly() const
{
return m_readOnly;
}
inline void AbstractTextAreaWidget::MoveCursor(int offset)
{
std::size_t cursorGlyph = GetGlyphIndex(m_cursorPositionBegin);
if (offset >= 0)
SetCursorPosition(cursorGlyph + static_cast<std::size_t>(offset));
else
{
std::size_t nOffset = static_cast<std::size_t>(-offset);
if (nOffset >= cursorGlyph)
SetCursorPosition(0);
else
SetCursorPosition(cursorGlyph - nOffset);
}
}
inline void AbstractTextAreaWidget::MoveCursor(const Nz::Vector2i& offset)
{
auto ClampOffset = [] (unsigned int cursorPosition, int cursorOffset) -> unsigned int
{
if (cursorOffset >= 0)
return cursorPosition + cursorOffset;
else
{
unsigned int nOffset = static_cast<unsigned int>(-cursorOffset);
if (nOffset >= cursorPosition)
return 0;
else
return cursorPosition - nOffset;
}
};
Nz::Vector2ui cursorPosition = m_cursorPositionBegin;
cursorPosition.x = ClampOffset(static_cast<unsigned int>(cursorPosition.x), offset.x);
cursorPosition.y = ClampOffset(static_cast<unsigned int>(cursorPosition.y), offset.y);
SetCursorPosition(cursorPosition);
}
inline Nz::Vector2ui AbstractTextAreaWidget::NormalizeCursorPosition(Nz::Vector2ui cursorPosition) const
{
const Nz::AbstractTextDrawer& textDrawer = GetTextDrawer();
std::size_t lineCount = textDrawer.GetLineCount();
if (cursorPosition.y >= lineCount)
cursorPosition.y = static_cast<unsigned int>(lineCount - 1);
const auto& lineInfo = textDrawer.GetLine(cursorPosition.y);
if (cursorPosition.y + 1 < lineCount)
{
const auto& nextLineInfo = textDrawer.GetLine(cursorPosition.y + 1);
cursorPosition.x = std::min(cursorPosition.x, static_cast<unsigned int>(nextLineInfo.glyphIndex - lineInfo.glyphIndex - 1));
}
return cursorPosition;
}
inline void AbstractTextAreaWidget::SetCharacterFilter(CharacterFilter filter)
{
m_characterFilter = std::move(filter);
}
inline void AbstractTextAreaWidget::SetCursorPosition(std::size_t glyphIndex)
{
Nz::Vector2ui position = GetCursorPosition(glyphIndex);
Nz::Vector2ui newPosition = position;
OnTextAreaCursorMove(this, &newPosition);
if (position == newPosition)
SetCursorPositionInternal(position);
else
SetCursorPositionInternal(GetGlyphIndex(newPosition));
}
inline void AbstractTextAreaWidget::SetCursorPosition(Nz::Vector2ui cursorPosition)
{
OnTextAreaCursorMove(this, &cursorPosition);
return SetCursorPositionInternal(NormalizeCursorPosition(cursorPosition));
}
inline void AbstractTextAreaWidget::SetEchoMode(EchoMode echoMode)
{
m_echoMode = echoMode;
UpdateDisplayText();
}
inline void AbstractTextAreaWidget::SetReadOnly(bool readOnly)
{
m_readOnly = readOnly;
m_cursorEntity->Enable(!m_readOnly && HasFocus());
}
inline void AbstractTextAreaWidget::SetSelection(Nz::Vector2ui fromPosition, Nz::Vector2ui toPosition)
{
// Ensure begin is before end
if (toPosition.y < fromPosition.y || (toPosition.y == fromPosition.y && toPosition.x < fromPosition.x))
std::swap(fromPosition, toPosition);
if (m_cursorPositionBegin != fromPosition || m_cursorPositionEnd != toPosition)
{
OnTextAreaSelection(this, &fromPosition, &toPosition);
// Ensure begin is before end a second time (in case signal changed it)
if (toPosition.y < fromPosition.y || (toPosition.y == fromPosition.y && toPosition.x < fromPosition.x))
std::swap(fromPosition, toPosition);
m_cursorPositionBegin = NormalizeCursorPosition(fromPosition);
m_cursorPositionEnd = NormalizeCursorPosition(toPosition);
RefreshCursor();
}
}
inline void AbstractTextAreaWidget::Write(const Nz::String& text)
{
Write(text, GetGlyphIndex(m_cursorPositionBegin));
}
inline void AbstractTextAreaWidget::Write(const Nz::String& text, const Nz::Vector2ui& glyphPosition)
{
Write(text, GetGlyphIndex(glyphPosition));
}
void AbstractTextAreaWidget::SetCursorPositionInternal(std::size_t glyphIndex)
{
return SetCursorPositionInternal(GetCursorPosition(glyphIndex));
}
inline void AbstractTextAreaWidget::SetCursorPositionInternal(Nz::Vector2ui cursorPosition)
{
m_cursorPositionBegin = cursorPosition;
m_cursorPositionEnd = m_cursorPositionBegin;
RefreshCursor();
}
}

View File

@ -1,41 +0,0 @@
// Copyright (C) 2017 Jérôme Leclercq
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequisites.hpp
#pragma once
#ifndef NDK_WIDGETS_BOXLAYOUT_HPP
#define NDK_WIDGETS_BOXLAYOUT_HPP
#include <NDK/Prerequisites.hpp>
#include <NDK/BaseWidget.hpp>
#include <NDK/Widgets/Enums.hpp>
#include <memory>
namespace Ndk
{
class NDK_API BoxLayout : public BaseWidget
{
public:
BoxLayout(BaseWidget* parent, BoxLayoutOrientation orientation);
BoxLayout(const BoxLayout&) = delete;
BoxLayout(BoxLayout&&) = delete;
~BoxLayout();
void Layout() override;
BoxLayout& operator=(const BoxLayout&) = delete;
BoxLayout& operator=(BoxLayout&&) = delete;
private:
struct State;
std::unique_ptr<State> m_state;
BoxLayoutOrientation m_orientation;
float m_spacing;
};
}
#include <NDK/Widgets/BoxLayout.inl>
#endif // NDK_WIDGETS_BOXLAYOUT_HPP

View File

@ -1,99 +0,0 @@
// Copyright (C) 2017 Jérôme Leclercq
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequisites.hpp
#pragma once
#ifndef NDK_WIDGETS_BUTTONWIDGET_HPP
#define NDK_WIDGETS_BUTTONWIDGET_HPP
#include <NDK/Prerequisites.hpp>
#include <NDK/BaseWidget.hpp>
#include <Nazara/Core/Color.hpp>
#include <Nazara/Graphics/Sprite.hpp>
#include <Nazara/Graphics/TextSprite.hpp>
namespace Nz
{
class AbstractTextDrawer;
}
namespace Ndk
{
class NDK_API ButtonWidget : public BaseWidget
{
public:
ButtonWidget(BaseWidget* parent);
ButtonWidget(const ButtonWidget&) = delete;
ButtonWidget(ButtonWidget&&) = default;
~ButtonWidget() = default;
inline const Nz::Color& GetColor() const;
inline const Nz::Color& GetCornerColor() const;
inline const Nz::Color& GetHoverColor() const;
inline const Nz::Color& GetHoverCornerColor() const;
inline const Nz::Color& GetPressColor() const;
inline const Nz::Color& GetPressCornerColor() const;
inline const Nz::TextureRef& GetTexture() const;
inline const Nz::TextureRef& GetHoverTexture() const;
inline const Nz::TextureRef& GetPressTexture() const;
inline void SetColor(const Nz::Color& color, const Nz::Color& cornerColor);
inline void SetHoverColor(const Nz::Color& color, const Nz::Color& cornerColor);
inline void SetPressColor(const Nz::Color& color, const Nz::Color& cornerColor);
inline void SetTexture(const Nz::TextureRef& texture);
inline void SetHoverTexture(const Nz::TextureRef& texture);
inline void SetPressTexture(const Nz::TextureRef& texture);
inline void UpdateText(const Nz::AbstractTextDrawer& drawer);
ButtonWidget& operator=(const ButtonWidget&) = delete;
ButtonWidget& operator=(ButtonWidget&&) = default;
static const Nz::Color& GetDefaultColor();
static const Nz::Color& GetDefaultCornerColor();
static const Nz::Color& GetDefaultHoverColor();
static const Nz::Color& GetDefaultHoverCornerColor();
static const Nz::Color& GetDefaultPressColor();
static const Nz::Color& GetDefaultPressCornerColor();
NazaraSignal(OnButtonTrigger, const ButtonWidget* /*button*/);
private:
void Layout() override;
void OnMouseEnter() override;
void OnMouseButtonPress(int x, int y, Nz::Mouse::Button button) override;
void OnMouseButtonRelease(int x, int y, Nz::Mouse::Button button) override;
void OnMouseExit() override;
EntityHandle m_textEntity;
EntityHandle m_gradientEntity;
Nz::SpriteRef m_gradientSprite;
Nz::TextSpriteRef m_textSprite;
Nz::Color m_color;
Nz::Color m_cornerColor;
Nz::Color m_hoverColor;
Nz::Color m_hoverCornerColor;
Nz::Color m_pressColor;
Nz::Color m_pressCornerColor;
Nz::TextureRef m_texture;
Nz::TextureRef m_hoverTexture;
Nz::TextureRef m_pressTexture;
static Nz::Color s_color;
static Nz::Color s_cornerColor;
static Nz::Color s_hoverColor;
static Nz::Color s_hoverCornerColor;
static Nz::Color s_pressColor;
static Nz::Color s_pressCornerColor;
};
}
#include <NDK/Widgets/ButtonWidget.inl>
#endif // NDK_WIDGETS_BUTTONWIDGET_HPP

View File

@ -1,102 +0,0 @@
// Copyright (C) 2017 Jérôme Leclercq
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequisites.hpp
#include <NDK/Widgets/ButtonWidget.hpp>
namespace Ndk
{
inline const Nz::Color& ButtonWidget::GetColor() const
{
return m_color;
}
inline const Nz::Color& ButtonWidget::GetCornerColor() const
{
return m_cornerColor;
}
inline const Nz::Color& ButtonWidget::GetHoverColor() const
{
return m_hoverColor;
}
inline const Nz::Color& ButtonWidget::GetHoverCornerColor() const
{
return m_hoverCornerColor;
}
inline const Nz::Color& ButtonWidget::GetPressColor() const
{
return m_pressColor;
}
inline const Nz::Color& ButtonWidget::GetPressCornerColor() const
{
return m_pressCornerColor;
}
inline const Nz::TextureRef& ButtonWidget::GetTexture() const
{
return m_texture;
}
inline const Nz::TextureRef& ButtonWidget::GetHoverTexture() const
{
return m_hoverTexture;
}
inline const Nz::TextureRef& ButtonWidget::GetPressTexture() const
{
return m_pressTexture;
}
inline void ButtonWidget::SetColor(const Nz::Color& color, const Nz::Color& cornerColor)
{
m_color = color;
m_cornerColor = cornerColor;
m_gradientSprite->SetColor(m_color);
m_gradientSprite->SetCornerColor(Nz::RectCorner_LeftBottom, m_cornerColor);
m_gradientSprite->SetCornerColor(Nz::RectCorner_RightBottom, m_cornerColor);
}
inline void ButtonWidget::SetHoverColor(const Nz::Color& color, const Nz::Color& cornerColor)
{
m_hoverColor = color;
m_hoverCornerColor = cornerColor;
}
inline void ButtonWidget::SetPressColor(const Nz::Color& color, const Nz::Color& cornerColor)
{
m_pressColor = color;
m_pressCornerColor = cornerColor;
}
inline void ButtonWidget::SetTexture(const Nz::TextureRef& texture)
{
m_texture = texture;
m_gradientSprite->SetTexture(m_texture);
}
inline void ButtonWidget::SetHoverTexture(const Nz::TextureRef& texture)
{
m_hoverTexture = texture;
}
inline void ButtonWidget::SetPressTexture(const Nz::TextureRef& texture)
{
m_pressTexture = texture;
}
inline void ButtonWidget::UpdateText(const Nz::AbstractTextDrawer& drawer)
{
m_textSprite->Update(drawer);
Nz::Vector2f textSize = Nz::Vector2f(m_textSprite->GetBoundingVolume().obb.localBox.GetLengths());
SetMinimumSize(textSize);
SetPreferredSize(textSize + Nz::Vector2f(20.f, 10.f));
Layout();
}
}

View File

@ -1,105 +0,0 @@
// Copyright (C) 2017 Samy Bensaid
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequisites.hpp
#pragma once
#ifndef NDK_WIDGETS_CHECKBOXWIDGET_HPP
#define NDK_WIDGETS_CHECKBOXWIDGET_HPP
#include <NDK/Prerequisites.hpp>
#include <NDK/BaseWidget.hpp>
#include <NDK/Components/NodeComponent.hpp>
#include <NDK/Widgets/Enums.hpp>
#include <Nazara/Renderer/Texture.hpp>
#include <Nazara/Graphics/Sprite.hpp>
#include <Nazara/Graphics/TextSprite.hpp>
#include <Nazara/Math/Vector2.hpp>
namespace Nz
{
class AbstractTextDrawer;
}
namespace Ndk
{
class NDK_API CheckboxWidget : public BaseWidget
{
friend class Sdk;
public:
CheckboxWidget(BaseWidget* parent);
CheckboxWidget(const CheckboxWidget&) = delete;
CheckboxWidget(CheckboxWidget&&) = default;
~CheckboxWidget() = default;
//virtual CheckboxWidget* Clone() const = 0;
inline void EnableAdaptativeMargin(bool enable = true);
inline void EnableCheckbox(bool enable = true);
inline void EnableTristate(bool enable = true);
inline bool IsCheckboxEnabled() const;
inline bool IsMarginAdaptative() const;
inline bool IsTristateEnabled() const;
inline const Nz::Vector2f& GetCheckboxSize() const;
inline Nz::Vector2f GetCheckboxBorderSize() const;
inline CheckboxState GetState() const;
inline float GetTextMargin() const;
inline void SetCheckboxSize(const Nz::Vector2f& size);
CheckboxState SwitchToNextState();
void SetState(CheckboxState state);
inline void SetTextMargin(float margin);
inline void UpdateText(const Nz::AbstractTextDrawer& drawer);
CheckboxWidget& operator=(const CheckboxWidget&) = delete;
CheckboxWidget& operator=(CheckboxWidget&&) = default;
NazaraSignal(OnStateChanged, const CheckboxWidget* /*checkbox*/);
private:
static bool Initialize();
static void Uninitialize();
void Layout() override;
void UpdateCheckbox();
void UpdateSize();
void OnMouseButtonRelease(int x, int y, Nz::Mouse::Button button) override;
inline bool ContainsCheckbox(int x, int y) const;
EntityHandle m_checkboxBorderEntity;
EntityHandle m_checkboxBackgroundEntity;
EntityHandle m_checkboxContentEntity;
EntityHandle m_textEntity;
Nz::TextureRef m_checkMark;
Nz::SpriteRef m_checkboxContentSprite;
Nz::SpriteRef m_checkboxBorderSprite;
Nz::SpriteRef m_checkboxBackgroundSprite;
Nz::TextSpriteRef m_textSprite;
static Nz::Color s_backgroundColor;
static Nz::Color s_disabledBackgroundColor;
static Nz::Color s_disabledBorderColor;
static Nz::Color s_borderColor;
bool m_adaptativeMargin;
bool m_checkboxEnabled;
bool m_tristateEnabled;
static float s_borderScale;
float m_textMargin;
CheckboxState m_state;
};
}
#include <NDK/Widgets/CheckboxWidget.inl>
#endif // NDK_WIDGETS_CHECKBOXWIDGET_HPP

View File

@ -1,94 +0,0 @@
// Copyright (C) 2017 Samy Bensaid
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequisites.hpp
namespace Ndk
{
inline void CheckboxWidget::EnableAdaptativeMargin(bool enable)
{
m_adaptativeMargin = enable;
Layout();
}
inline void CheckboxWidget::EnableCheckbox(bool enable)
{
m_checkboxEnabled = enable;
UpdateCheckbox();
}
inline void CheckboxWidget::EnableTristate(bool enable)
{
m_tristateEnabled = enable;
if (m_tristateEnabled && GetState() == CheckboxState_Tristate)
SetState(CheckboxState_Unchecked);
}
inline bool CheckboxWidget::IsCheckboxEnabled() const
{
return m_checkboxEnabled;
}
inline bool CheckboxWidget::IsMarginAdaptative() const
{
return m_adaptativeMargin;
}
inline bool CheckboxWidget::IsTristateEnabled() const
{
return m_tristateEnabled;
}
inline const Nz::Vector2f& CheckboxWidget::GetCheckboxSize() const
{
return m_checkboxBorderSprite->GetSize();
}
inline Nz::Vector2f CheckboxWidget::GetCheckboxBorderSize() const
{
return GetCheckboxSize() / s_borderScale;
}
inline CheckboxState CheckboxWidget::GetState() const
{
return m_state;
}
inline float CheckboxWidget::GetTextMargin() const
{
return m_textMargin;
}
inline void CheckboxWidget::SetCheckboxSize(const Nz::Vector2f& size)
{
m_checkboxBorderSprite->SetSize(size);
m_checkboxBackgroundSprite->SetSize(size - GetCheckboxBorderSize() * 2.f);
m_checkboxContentSprite->SetSize(GetCheckboxSize() - GetCheckboxBorderSize() * 2.f - Nz::Vector2f { 4.f, 4.f });
UpdateSize();
Layout();
}
inline void CheckboxWidget::SetTextMargin(float margin)
{
m_textMargin = margin;
Layout();
}
inline void CheckboxWidget::UpdateText(const Nz::AbstractTextDrawer& drawer)
{
m_textSprite->Update(drawer);
UpdateSize();
Layout();
}
inline bool CheckboxWidget::ContainsCheckbox(int x, int y) const
{
Nz::Vector2f checkboxSize = GetCheckboxSize();
Nz::Vector3f pos = m_checkboxBorderEntity->GetComponent<NodeComponent>().GetPosition(Nz::CoordSys_Local);
return x > pos.x && x < pos.x + checkboxSize.x &&
y > pos.y && y < pos.y + checkboxSize.y;
}
}

View File

@ -1,37 +0,0 @@
// Copyright (C) 2017 Samy Bensaid
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequisites.hpp
#pragma once
#ifndef NAZARA_ENUMS_SDK_HPP
#define NAZARA_ENUMS_SDK_HPP
namespace Ndk
{
enum BoxLayoutOrientation
{
BoxLayoutOrientation_Horizontal,
BoxLayoutOrientation_Vertical
};
enum CheckboxState
{
CheckboxState_Checked,
CheckboxState_Tristate,
CheckboxState_Unchecked,
CheckboxState_Max = CheckboxState_Unchecked
};
enum EchoMode
{
EchoMode_Normal,
EchoMode_Password,
EchoMode_PasswordExceptLast,
EchoMode_Max = EchoMode_PasswordExceptLast
};
}
#endif // NAZARA_ENUMS_SDK_HPP

View File

@ -1,51 +0,0 @@
// Copyright (C) 2017 Samy Bensaid
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequisites.hpp
#pragma once
#ifndef NDK_WIDGETS_IMAGEWIDGET_HPP
#define NDK_WIDGETS_IMAGEWIDGET_HPP
#include <NDK/Prerequisites.hpp>
#include <NDK/BaseWidget.hpp>
#include <NDK/Entity.hpp>
#include <Nazara/Graphics/Sprite.hpp>
#include <Nazara/Renderer/Texture.hpp>
#include <Nazara/Math/Vector2.hpp>
namespace Ndk
{
class NDK_API ImageWidget : public BaseWidget
{
public:
ImageWidget(BaseWidget* parent);
ImageWidget(const ImageWidget&) = delete;
ImageWidget(ImageWidget&&) = default;
~ImageWidget() = default;
//virtual ImageWidget* Clone() const = 0;
inline const Nz::Color& GetColor() const;
inline const Nz::TextureRef& GetTexture() const;
inline const Nz::Rectf& GetTextureCoords() const;
inline void SetColor(const Nz::Color& color);
inline void SetTexture(const Nz::TextureRef& texture);
inline void SetTextureCoords(const Nz::Rectf& coords);
inline void SetTextureRect(const Nz::Rectui& rect);
ImageWidget& operator=(const ImageWidget&) = delete;
ImageWidget& operator=(ImageWidget&&) = default;
private:
void Layout() override;
Ndk::EntityHandle m_entity;
Nz::SpriteRef m_sprite;
};
}
#include <NDK/Widgets/ImageWidget.inl>
#endif // NDK_WIDGETS_IMAGEWIDGET_HPP

View File

@ -1,47 +0,0 @@
// Copyright (C) 2017 Samy Bensaid
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequisites.hpp
#include <NDK/Widgets/ImageWidget.hpp>
namespace Ndk
{
inline const Nz::Color& ImageWidget::GetColor() const
{
return m_sprite->GetColor();
}
inline const Nz::TextureRef& ImageWidget::GetTexture() const
{
return m_sprite->GetMaterial()->GetDiffuseMap();
}
inline const Nz::Rectf& ImageWidget::GetTextureCoords() const
{
return m_sprite->GetTextureCoords();
}
inline void ImageWidget::SetColor(const Nz::Color& color)
{
m_sprite->SetColor(color);
}
inline void ImageWidget::SetTexture(const Nz::TextureRef& texture)
{
m_sprite->SetTexture(texture, false);
Nz::Vector2f textureSize = Nz::Vector2f(Nz::Vector2ui(m_sprite->GetMaterial()->GetDiffuseMap()->GetSize()));
SetMinimumSize(textureSize);
SetPreferredSize(textureSize);
}
inline void ImageWidget::SetTextureCoords(const Nz::Rectf& coords)
{
m_sprite->SetTextureCoords(coords);
}
inline void ImageWidget::SetTextureRect(const Nz::Rectui& rect)
{
m_sprite->SetTextureRect(rect);
}
}

View File

@ -1,42 +0,0 @@
// Copyright (C) 2017 Jérôme Leclercq
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequisites.hpp
#pragma once
#ifndef NDK_WIDGETS_LABELWIDGET_HPP
#define NDK_WIDGETS_LABELWIDGET_HPP
#include <NDK/Prerequisites.hpp>
#include <NDK/BaseWidget.hpp>
#include <Nazara/Graphics/TextSprite.hpp>
namespace Nz
{
class AbstractTextDrawer;
}
namespace Ndk
{
class NDK_API LabelWidget : public BaseWidget
{
public:
LabelWidget(BaseWidget* parent);
LabelWidget(const LabelWidget&) = delete;
LabelWidget(LabelWidget&&) = default;
~LabelWidget() = default;
inline void UpdateText(const Nz::AbstractTextDrawer& drawer);
LabelWidget& operator=(const LabelWidget&) = delete;
LabelWidget& operator=(LabelWidget&&) = default;
private:
EntityHandle m_textEntity;
Nz::TextSpriteRef m_textSprite;
};
}
#include <NDK/Widgets/LabelWidget.inl>
#endif // NDK_WIDGETS_LABELWIDGET_HPP

View File

@ -1,17 +0,0 @@
// Copyright (C) 2017 Jérôme Leclercq
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequisites.hpp
#include <NDK/Widgets/LabelWidget.hpp>
namespace Ndk
{
inline void LabelWidget::UpdateText(const Nz::AbstractTextDrawer& drawer)
{
m_textSprite->Update(drawer);
Nz::Vector2f size = Nz::Vector2f(m_textSprite->GetBoundingVolume().obb.localBox.GetLengths());
SetMinimumSize(size);
SetPreferredSize(size);
}
}

View File

@ -1,101 +0,0 @@
// Copyright (C) 2017 Samy Bensaid
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequisites.hpp
#pragma once
#ifndef NDK_WIDGETS_PROGRESSBARWIDGET_HPP
#define NDK_WIDGETS_PROGRESSBARWIDGET_HPP
#include <NDK/Prerequisites.hpp>
#include <NDK/BaseWidget.hpp>
#include <Nazara/Core/Color.hpp>
#include <Nazara/Graphics/Sprite.hpp>
#include <Nazara/Graphics/TextSprite.hpp>
#include <Nazara/Math/Vector2.hpp>
#include <Nazara/Renderer/Texture.hpp>
#include <Nazara/Utility/SimpleTextDrawer.hpp>
namespace Ndk
{
class NDK_API ProgressBarWidget : public BaseWidget
{
friend class Sdk;
public:
ProgressBarWidget(BaseWidget* parent);
ProgressBarWidget(const ProgressBarWidget&) = delete;
ProgressBarWidget(ProgressBarWidget&&) = default;
~ProgressBarWidget() = default;
//virtual ProgressBarWidget* Clone() const = 0;
inline void EnableText(bool enable = true);
inline void EnableBorder(bool enable = true);
inline bool IsTextEnabled() const;
inline bool IsBorderEnabled() const;
inline unsigned GetPercentageValue() const;
inline Nz::Vector2f GetProgressBarSize() const;
inline Nz::Vector2f GetProgressBarBorderSize() const;
inline float GetTextMargin() const;
inline const Nz::Color& GetBarBackgroundColor() const;
inline const Nz::Color& GetBarBackgroundCornerColor() const;
inline const Nz::Color& GetBarColor() const;
inline const Nz::Color& GetBarCornerColor() const;
inline const Nz::TextureRef& GetBarBackgroundTexture() const;
inline const Nz::TextureRef& GetBarTexture() const;
static const Nz::Color& GetDefaultBarColor();
static const Nz::Color& GetDefaultBarCornerColor();
static const Nz::Color& GetDefaultBarBackgroundColor();
static const Nz::Color& GetDefaultBarBackgroundCornerColor();
inline void SetBarBackgroundColor(const Nz::Color& globalColor, const Nz::Color& cornerColor);
inline void SetBarBackgroundTexture(Nz::TextureRef texture, bool resetColors = true);
inline void SetBarColor(const Nz::Color& globalColor, const Nz::Color& cornerColor);
inline void SetBarTexture(Nz::TextureRef texture, bool resetColors = true);
inline void SetPercentageValue(unsigned percentage);
inline void SetTextMargin(float margin);
inline void SetTextColor(const Nz::Color& color);
NazaraSignal(OnValueChanged, const ProgressBarWidget* /*progressBar*/);
private:
void Layout() override;
inline void UpdateText();
EntityHandle m_borderEntity;
EntityHandle m_barEntity;
EntityHandle m_textEntity;
static Nz::Color s_borderColor;
static Nz::Color s_barBackgroundColor;
static Nz::Color s_barBackgroundCornerColor;
static Nz::Color s_barColor;
static Nz::Color s_barCornerColor;
Nz::Color m_textColor;
Nz::SpriteRef m_borderSprite;
Nz::SpriteRef m_barBackgroundSprite;
Nz::SpriteRef m_barSprite;
Nz::TextSpriteRef m_textSprite;
static float s_borderScale;
float m_textMargin;
unsigned m_value;
};
}
#include <NDK/Widgets/ProgressBarWidget.inl>
#endif // NDK_WIDGETS_PROGRESSBARWIDGET_HPP

View File

@ -1,155 +0,0 @@
// Copyright (C) 2017 Samy Bensaid
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequisites.hpp
namespace Ndk
{
inline void ProgressBarWidget::EnableText(bool enable)
{
m_textEntity->Enable(enable);
Layout();
}
inline void ProgressBarWidget::EnableBorder(bool enable)
{
m_borderEntity->Enable(enable);
}
inline bool ProgressBarWidget::IsTextEnabled() const
{
return m_textEntity->IsEnabled();
}
inline bool ProgressBarWidget::IsBorderEnabled() const
{
return m_borderEntity->IsEnabled();
}
inline unsigned ProgressBarWidget::GetPercentageValue() const
{
return m_value;
}
inline Nz::Vector2f ProgressBarWidget::GetProgressBarSize() const
{
Nz::Vector3f progressBarSize = m_borderSprite->GetBoundingVolume().obb.localBox.GetLengths();
if (IsTextEnabled())
{
Nz::Vector3f textSize = m_textSprite->GetBoundingVolume().obb.localBox.GetLengths();
progressBarSize -= { textSize.x + m_textMargin, 0.f, 0.f };
}
return { progressBarSize.x, progressBarSize.y };
}
inline Nz::Vector2f ProgressBarWidget::GetProgressBarBorderSize() const
{
Nz::Vector2f barSize = GetProgressBarSize();
return { barSize.y / s_borderScale, barSize.y / s_borderScale };
}
inline float ProgressBarWidget::GetTextMargin() const
{
return m_textMargin;
}
inline const Nz::Color& ProgressBarWidget::GetBarBackgroundColor() const
{
return m_barBackgroundSprite->GetColor();
}
inline const Nz::Color& ProgressBarWidget::GetBarBackgroundCornerColor() const
{
return m_barBackgroundSprite->GetCornerColor(Nz::RectCorner_LeftTop);
}
inline const Nz::Color& ProgressBarWidget::GetBarColor() const
{
return m_barSprite->GetColor();
}
inline const Nz::Color& ProgressBarWidget::GetBarCornerColor() const
{
return m_barSprite->GetCornerColor(Nz::RectCorner_LeftTop);
}
inline const Nz::TextureRef& ProgressBarWidget::GetBarBackgroundTexture() const
{
return m_barBackgroundSprite->GetMaterial()->GetDiffuseMap();
}
inline const Nz::TextureRef& ProgressBarWidget::GetBarTexture() const
{
return m_barSprite->GetMaterial()->GetDiffuseMap();
}
inline void ProgressBarWidget::SetBarBackgroundColor(const Nz::Color& globalColor, const Nz::Color& cornerColor)
{
m_barBackgroundSprite->SetColor(globalColor);
m_barBackgroundSprite->SetCornerColor(Nz::RectCorner_LeftTop, cornerColor);
m_barBackgroundSprite->SetCornerColor(Nz::RectCorner_RightTop, cornerColor);
m_barBackgroundSprite->SetCornerColor(Nz::RectCorner_LeftBottom, globalColor);
m_barBackgroundSprite->SetCornerColor(Nz::RectCorner_RightBottom, globalColor);
}
inline void ProgressBarWidget::SetBarBackgroundTexture(Nz::TextureRef texture, bool resetColors)
{
m_barBackgroundSprite->SetTexture(texture, false);
if (resetColors)
SetBarBackgroundColor(Nz::Color::White, Nz::Color::White);
}
inline void ProgressBarWidget::SetBarColor(const Nz::Color& globalColor, const Nz::Color& cornerColor)
{
m_barSprite->SetColor(globalColor);
m_barSprite->SetCornerColor(Nz::RectCorner_LeftTop, cornerColor);
m_barSprite->SetCornerColor(Nz::RectCorner_RightTop, cornerColor);
m_barSprite->SetCornerColor(Nz::RectCorner_LeftBottom, globalColor);
m_barSprite->SetCornerColor(Nz::RectCorner_RightBottom, globalColor);
}
inline void ProgressBarWidget::SetBarTexture(Nz::TextureRef texture, bool resetColors)
{
m_barSprite->SetTexture(texture, false);
if (resetColors)
SetBarColor(Nz::Color::White, Nz::Color::White);
}
inline void ProgressBarWidget::SetPercentageValue(unsigned percentage)
{
m_value = percentage;
OnValueChanged(this);
Layout();
}
inline void ProgressBarWidget::SetTextMargin(float margin)
{
m_textMargin = margin;
if (IsTextEnabled())
Layout();
}
inline void ProgressBarWidget::SetTextColor(const Nz::Color& color)
{
m_textColor = color;
UpdateText();
}
inline void ProgressBarWidget::UpdateText()
{
if (IsTextEnabled())
{
Nz::Vector2f size = GetSize();
m_textSprite->Update(Nz::SimpleTextDrawer::Draw(Nz::String::Number(m_value).Append('%'), static_cast<unsigned int>(std::min(size.x, size.y) / 2.f), 0u, m_textColor));
}
}
}

View File

@ -1,68 +0,0 @@
// Copyright (C) 2017 Jérôme Leclercq
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequisites.hpp
#pragma once
#ifndef NDK_WIDGETS_RICHTEXTAREAWIDGET_HPP
#define NDK_WIDGETS_RICHTEXTAREAWIDGET_HPP
#include <Nazara/Utility/RichTextDrawer.hpp>
#include <NDK/Widgets/AbstractTextAreaWidget.hpp>
namespace Ndk
{
class NDK_API RichTextAreaWidget : public AbstractTextAreaWidget
{
public:
RichTextAreaWidget(BaseWidget* parent);
RichTextAreaWidget(const RichTextAreaWidget&) = delete;
RichTextAreaWidget(RichTextAreaWidget&&) = default;
~RichTextAreaWidget() = default;
void AppendText(const Nz::String& text);
void Clear() override;
void Erase(std::size_t firstGlyph, std::size_t lastGlyph) override;
inline unsigned int GetCharacterSize() const;
inline float GetCharacterSpacingOffset() const;
inline float GetLineSpacingOffset() const;
inline const Nz::Color& GetTextColor() const;
inline Nz::Font* GetTextFont() const;
inline const Nz::Color& GetTextOutlineColor() const;
inline float GetTextOutlineThickness() const;
inline Nz::TextStyleFlags GetTextStyle() const;
inline void SetCharacterSize(unsigned int characterSize);
inline void SetCharacterSpacingOffset(float offset);
inline void SetLineSpacingOffset(float offset);
inline void SetTextColor(const Nz::Color& color);
inline void SetTextFont(Nz::FontRef font);
inline void SetTextOutlineColor(const Nz::Color& color);
inline void SetTextOutlineThickness(float thickness);
inline void SetTextStyle(Nz::TextStyleFlags style);
void Write(const Nz::String& text, std::size_t glyphPosition) override;
RichTextAreaWidget& operator=(const RichTextAreaWidget&) = delete;
RichTextAreaWidget& operator=(RichTextAreaWidget&&) = default;
private:
Nz::AbstractTextDrawer& GetTextDrawer() override;
const Nz::AbstractTextDrawer& GetTextDrawer() const override;
void HandleIndentation(bool add) override;
void HandleSelectionIndentation(bool add) override;
void HandleWordCursorMove(bool left) override;
void UpdateDisplayText() override;
Nz::RichTextDrawer m_drawer;
};
}
#include <NDK/Widgets/RichTextAreaWidget.inl>
#endif // NDK_WIDGETS_TEXTAREAWIDGET_HPP

View File

@ -1,88 +0,0 @@
// Copyright (C) 2017 Jérôme Leclercq
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequisites.hpp
#include <NDK/Widgets/RichTextAreaWidget.hpp>
namespace Ndk
{
inline unsigned int RichTextAreaWidget::GetCharacterSize() const
{
return m_drawer.GetDefaultCharacterSize();
}
inline float RichTextAreaWidget::GetCharacterSpacingOffset() const
{
return m_drawer.GetDefaultCharacterSpacingOffset();
}
inline float RichTextAreaWidget::GetLineSpacingOffset() const
{
return m_drawer.GetDefaultLineSpacingOffset();
}
inline const Nz::Color& RichTextAreaWidget::GetTextColor() const
{
return m_drawer.GetDefaultColor();
}
inline Nz::Font* RichTextAreaWidget::GetTextFont() const
{
return m_drawer.GetDefaultFont();
}
inline const Nz::Color& RichTextAreaWidget::GetTextOutlineColor() const
{
return m_drawer.GetDefaultOutlineColor();
}
inline float RichTextAreaWidget::GetTextOutlineThickness() const
{
return m_drawer.GetDefaultOutlineThickness();
}
inline Nz::TextStyleFlags RichTextAreaWidget::GetTextStyle() const
{
return m_drawer.GetDefaultStyle();
}
inline void RichTextAreaWidget::SetCharacterSize(unsigned int characterSize)
{
m_drawer.SetDefaultCharacterSize(characterSize);
}
inline void RichTextAreaWidget::SetCharacterSpacingOffset(float offset)
{
m_drawer.SetDefaultCharacterSpacingOffset(offset);
}
inline void RichTextAreaWidget::SetLineSpacingOffset(float offset)
{
m_drawer.SetDefaultLineSpacingOffset(offset);
}
inline void RichTextAreaWidget::SetTextColor(const Nz::Color& color)
{
m_drawer.SetDefaultColor(color);
}
inline void RichTextAreaWidget::SetTextFont(Nz::FontRef font)
{
m_drawer.SetDefaultFont(std::move(font));
}
inline void RichTextAreaWidget::SetTextOutlineColor(const Nz::Color& color)
{
m_drawer.SetDefaultOutlineColor(color);
}
inline void RichTextAreaWidget::SetTextOutlineThickness(float thickness)
{
m_drawer.SetDefaultOutlineThickness(thickness);
}
inline void RichTextAreaWidget::SetTextStyle(Nz::TextStyleFlags style)
{
m_drawer.SetDefaultStyle(style);
}
}

View File

@ -1,74 +0,0 @@
// Copyright (C) 2019 Jérôme Leclercq
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequisites.hpp
#pragma once
#ifndef NDK_WIDGETS_SCROLLAREAWIDGET_HPP
#define NDK_WIDGETS_SCROLLAREAWIDGET_HPP
#include <NDK/Prerequisites.hpp>
#include <NDK/BaseWidget.hpp>
#include <Nazara/Graphics/TextSprite.hpp>
namespace Ndk
{
class NDK_API ScrollAreaWidget : public BaseWidget
{
public:
ScrollAreaWidget(BaseWidget* parent, BaseWidget* content);
ScrollAreaWidget(const ScrollAreaWidget&) = delete;
ScrollAreaWidget(ScrollAreaWidget&&) = default;
~ScrollAreaWidget() = default;
void EnableScrollbar(bool enable);
inline float GetScrollHeight() const;
inline float GetScrollRatio() const;
inline bool HasScrollbar() const;
inline bool IsScrollbarEnabled() const;
inline bool IsScrollbarVisible() const;
inline void ScrollToHeight(float height);
void ScrollToRatio(float ratio);
ScrollAreaWidget& operator=(const ScrollAreaWidget&) = delete;
ScrollAreaWidget& operator=(ScrollAreaWidget&&) = default;
private:
enum class ScrollBarStatus
{
Grabbed,
Hovered,
None
};
Nz::Rectf GetScrollbarRect() const;
void Layout() override;
void OnMouseButtonPress(int x, int y, Nz::Mouse::Button button) override;
void OnMouseButtonRelease(int x, int y, Nz::Mouse::Button button) override;
void OnMouseExit() override;
void OnMouseMoved(int x, int y, int deltaX, int deltaY) override;
void OnMouseWheelMoved(int x, int y, float delta) override;
void UpdateScrollbarStatus(ScrollBarStatus status);
BaseWidget* m_content;
EntityHandle m_scrollbarBackgroundEntity;
EntityHandle m_scrollbarEntity;
Nz::SpriteRef m_scrollbarBackgroundSprite;
Nz::SpriteRef m_scrollbarSprite;
Nz::Vector2i m_grabbedDelta;
ScrollBarStatus m_scrollbarStatus;
bool m_isScrollbarEnabled;
bool m_hasScrollbar;
float m_scrollRatio;
};
}
#include <NDK/Widgets/ScrollAreaWidget.inl>
#endif // NDK_WIDGETS_SCROLLAREAWIDGET_HPP

View File

@ -1,39 +0,0 @@
// Copyright (C) 2019 Jérôme Leclercq
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequisites.hpp
#include <NDK/Widgets/ScrollAreaWidget.hpp>
namespace Ndk
{
inline float ScrollAreaWidget::GetScrollHeight() const
{
return m_scrollRatio * m_content->GetHeight();
}
inline float ScrollAreaWidget::GetScrollRatio() const
{
return m_scrollRatio;
}
inline bool ScrollAreaWidget::HasScrollbar() const
{
return m_hasScrollbar;
}
inline bool ScrollAreaWidget::IsScrollbarEnabled() const
{
return m_isScrollbarEnabled;
}
inline bool ScrollAreaWidget::IsScrollbarVisible() const
{
return HasScrollbar() && IsScrollbarEnabled();
}
inline void ScrollAreaWidget::ScrollToHeight(float height)
{
float contentHeight = m_content->GetHeight();
ScrollToRatio(height / contentHeight);
}
}

View File

@ -1,77 +0,0 @@
// Copyright (C) 2017 Jérôme Leclercq
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequisites.hpp
#pragma once
#ifndef NDK_WIDGETS_TEXTAREAWIDGET_HPP
#define NDK_WIDGETS_TEXTAREAWIDGET_HPP
#include <Nazara/Utility/SimpleTextDrawer.hpp>
#include <NDK/Widgets/AbstractTextAreaWidget.hpp>
namespace Ndk
{
class NDK_API TextAreaWidget : public AbstractTextAreaWidget
{
public:
TextAreaWidget(BaseWidget* parent);
TextAreaWidget(const TextAreaWidget&) = delete;
TextAreaWidget(TextAreaWidget&&) = default;
~TextAreaWidget() = default;
void AppendText(const Nz::String& text);
void Clear() override;
using AbstractTextAreaWidget::Erase;
void Erase(std::size_t firstGlyph, std::size_t lastGlyph) override;
inline unsigned int GetCharacterSize() const;
inline const Nz::String& GetDisplayText() const;
inline float GetCharacterSpacingOffset() const;
inline float GetLineSpacingOffset() const;
inline const Nz::String& GetText() const;
inline const Nz::Color& GetTextColor() const;
inline Nz::Font* GetTextFont() const;
inline const Nz::Color& GetTextOulineColor() const;
inline float GetTextOulineThickness() const;
inline Nz::TextStyleFlags GetTextStyle() const;
inline void SetCharacterSize(unsigned int characterSize);
inline void SetCharacterSpacingOffset(float offset);
inline void SetLineSpacingOffset(float offset);
inline void SetText(const Nz::String& text);
inline void SetTextColor(const Nz::Color& text);
inline void SetTextFont(Nz::FontRef font);
inline void SetTextOutlineColor(const Nz::Color& color);
inline void SetTextOutlineThickness(float thickness);
inline void SetTextStyle(Nz::TextStyleFlags style);
using AbstractTextAreaWidget::Write;
void Write(const Nz::String& text, std::size_t glyphPosition) override;
TextAreaWidget& operator=(const TextAreaWidget&) = delete;
TextAreaWidget& operator=(TextAreaWidget&&) = default;
NazaraSignal(OnTextChanged, const AbstractTextAreaWidget* /*textArea*/, const Nz::String& /*text*/);
private:
Nz::AbstractTextDrawer& GetTextDrawer() override;
const Nz::AbstractTextDrawer& GetTextDrawer() const override;
void HandleIndentation(bool add) override;
void HandleSelectionIndentation(bool add) override;
void HandleWordCursorMove(bool left) override;
void UpdateDisplayText() override;
void UpdateMinimumSize();
Nz::SimpleTextDrawer m_drawer;
Nz::String m_text;
};
}
#include <NDK/Widgets/TextAreaWidget.inl>
#endif // NDK_WIDGETS_TEXTAREAWIDGET_HPP

View File

@ -1,124 +0,0 @@
// Copyright (C) 2017 Jérôme Leclercq
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequisites.hpp
#include <NDK/Widgets/TextAreaWidget.hpp>
namespace Ndk
{
inline unsigned int TextAreaWidget::GetCharacterSize() const
{
return m_drawer.GetCharacterSize();
}
inline const Nz::String& TextAreaWidget::GetDisplayText() const
{
return m_drawer.GetText();
}
inline float TextAreaWidget::GetCharacterSpacingOffset() const
{
return m_drawer.GetCharacterSpacingOffset();
}
inline float TextAreaWidget::GetLineSpacingOffset() const
{
return m_drawer.GetLineSpacingOffset();
}
inline const Nz::String& TextAreaWidget::GetText() const
{
return m_text;
}
inline const Nz::Color& TextAreaWidget::GetTextColor() const
{
return m_drawer.GetColor();
}
inline Nz::Font* TextAreaWidget::GetTextFont() const
{
return m_drawer.GetFont();
}
inline const Nz::Color& TextAreaWidget::GetTextOulineColor() const
{
return m_drawer.GetOutlineColor();
}
inline float TextAreaWidget::GetTextOulineThickness() const
{
return m_drawer.GetOutlineThickness();
}
inline Nz::TextStyleFlags TextAreaWidget::GetTextStyle() const
{
return m_drawer.GetStyle();
}
inline void TextAreaWidget::SetCharacterSize(unsigned int characterSize)
{
m_drawer.SetCharacterSize(characterSize);
UpdateMinimumSize();
UpdateDisplayText();
}
inline void TextAreaWidget::SetCharacterSpacingOffset(float offset)
{
m_drawer.SetCharacterSpacingOffset(offset);
UpdateMinimumSize();
UpdateDisplayText();
}
inline void TextAreaWidget::SetLineSpacingOffset(float offset)
{
m_drawer.SetLineSpacingOffset(offset);
UpdateDisplayText();
}
inline void TextAreaWidget::SetText(const Nz::String& text)
{
m_text = text;
OnTextChanged(this, m_text);
UpdateDisplayText();
}
inline void TextAreaWidget::SetTextColor(const Nz::Color& text)
{
m_drawer.SetColor(text);
UpdateDisplayText();
}
inline void TextAreaWidget::SetTextFont(Nz::FontRef font)
{
m_drawer.SetFont(font);
UpdateDisplayText();
}
inline void TextAreaWidget::SetTextOutlineColor(const Nz::Color& color)
{
m_drawer.SetOutlineColor(color);
UpdateDisplayText();
}
inline void TextAreaWidget::SetTextOutlineThickness(float thickness)
{
m_drawer.SetOutlineThickness(thickness);
UpdateDisplayText();
}
inline void TextAreaWidget::SetTextStyle(Nz::TextStyleFlags style)
{
m_drawer.SetStyle(style);
UpdateDisplayText();
}
}

View File

@ -1,271 +0,0 @@
// Copyright (C) 2017 Jérôme Leclercq
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequisites.hpp
#include <NDK/Application.hpp>
#include <Nazara/Core/Log.hpp>
#include <regex>
#ifndef NDK_SERVER
#include <NDK/Components/CameraComponent.hpp>
#include <NDK/Components/GraphicsComponent.hpp>
#include <NDK/Components/NodeComponent.hpp>
#include <NDK/Systems/RenderSystem.hpp>
#include <NDK/LuaAPI.hpp>
#include <Nazara/Graphics/ForwardRenderTechnique.hpp>
#include <Nazara/Utility/SimpleTextDrawer.hpp>
#endif
namespace Ndk
{
/*!
* \ingroup NDK
* \class Ndk::Application
* \brief NDK class that represents the application, it offers a set of tools to ease the development
*/
/*!
* \brief Constructs an Application object with command-line arguments
*
* Pass the argc and argv arguments from the main function.
*
* Command-line arguments can be retrieved by application methods
*
* This calls Sdk::Initialize()
*
* \remark Only one Application instance can exist at a time
*/
Application::Application(int argc, char* argv[]) :
Application()
{
std::regex optionRegex(R"(-(\w+))");
std::regex valueRegex(R"(-(\w+)\s*=\s*(.+))");
std::smatch results;
for (int i = 1; i < argc; ++i)
{
std::string argument(argv[i]);
if (std::regex_match(argument, results, valueRegex))
{
Nz::String key(results[1].str());
Nz::String value(results[2].str());
m_parameters[key.ToLower()] = value;
NazaraDebug("Registred parameter from command-line: " + key.ToLower() + "=" + value);
}
else if (std::regex_match(argument, results, optionRegex))
{
Nz::String option(results[1].str());
m_options.insert(option);
NazaraDebug("Registred option from command-line: " + option);
}
else
NazaraWarning("Ignored command-line argument #" + Nz::String::Number(i) + " \"" + argument + '"');
}
#ifndef NDK_SERVER
if (HasOption("console"))
EnableConsole(true);
if (HasOption("fpscounter"))
EnableFPSCounter(true);
#endif
}
/*!
* \brief Runs the application by updating worlds, taking care about windows, ...
*/
bool Application::Run()
{
#ifndef NDK_SERVER
bool hasAtLeastOneActiveWindow = false;
auto it = m_windows.begin();
while (it != m_windows.end())
{
Nz::Window& window = *it->window;
window.ProcessEvents();
if (!window.IsOpen(true))
{
it = m_windows.erase(it);
continue;
}
hasAtLeastOneActiveWindow = true;
++it;
}
if (m_exitOnClosedWindows && !hasAtLeastOneActiveWindow)
return false;
#endif
if (m_shouldQuit)
return false;
m_updateTime = m_updateClock.Restart() / 1'000'000.f;
for (World& world : m_worlds)
world.Update(m_updateTime);
#ifndef NDK_SERVER
for (WindowInfo& info : m_windows)
{
if (!info.overlayWorld)
continue;
if (info.fpsCounter)
{
FPSCounterOverlay& fpsCounter = *info.fpsCounter;
fpsCounter.frameCount++;
fpsCounter.elapsedTime += m_updateTime;
if (fpsCounter.elapsedTime >= 1.f)
{
fpsCounter.sprite->Update(Nz::SimpleTextDrawer::Draw("FPS: " + Nz::String::Number(fpsCounter.frameCount), 36));
fpsCounter.frameCount = 0;
fpsCounter.elapsedTime = 0.f;
}
}
info.overlayWorld->Update(m_updateTime);
}
#endif
return true;
}
#ifndef NDK_SERVER
void Application::SetupConsole(WindowInfo& info)
{
std::unique_ptr<ConsoleOverlay> overlay = std::make_unique<ConsoleOverlay>();
Nz::Vector2ui windowDimensions;
if (info.window->IsValid())
windowDimensions = info.window->GetSize();
else
windowDimensions.MakeZero();
Nz::LuaInstance& lua = overlay->lua;
overlay->console = info.canvas->Add<Console>();
overlay->console->OnCommand.Connect([&lua](Ndk::Console* console, const Nz::String& command)
{
if (!lua.Execute(command))
console->AddLine(lua.GetLastError(), Nz::Color::Red);
});
Console& consoleRef = *overlay->console;
consoleRef.Resize({float(windowDimensions.x), windowDimensions.y / 4.f});
consoleRef.Show(false);
// Redirect logs toward the console
overlay->logSlot.Connect(Nz::Log::OnLogWrite, [&consoleRef] (const Nz::String& str)
{
consoleRef.AddLine(str);
});
lua.LoadLibraries();
LuaAPI::RegisterClasses(lua);
// Override "print" function to add a line in the console
lua.PushFunction([&consoleRef] (Nz::LuaState& state)
{
Nz::StringStream stream;
unsigned int argCount = state.GetStackTop();
state.GetGlobal("tostring");
for (unsigned int i = 1; i <= argCount; ++i)
{
state.PushValue(-1); // tostring function
state.PushValue(i); // argument
state.Call(1, 1);
std::size_t length;
const char* str = state.CheckString(-1, &length);
if (i > 1)
stream << '\t';
stream << Nz::String(str, length);
state.Pop(1);
}
consoleRef.AddLine(stream);
return 0;
});
lua.SetGlobal("print");
// Define a few base variables to allow our interface to interact with the application
lua.PushGlobal("Application", Ndk::Application::Instance());
lua.PushGlobal("Console", consoleRef.CreateHandle());
// Setup a few event callback to handle the console
Nz::EventHandler& eventHandler = info.window->GetEventHandler();
overlay->keyPressedSlot.Connect(eventHandler.OnKeyPressed, [&consoleRef] (const Nz::EventHandler*, const Nz::WindowEvent::KeyEvent& event)
{
if (event.virtualKey == Nz::Keyboard::VKey::F9)
{
// Toggle console visibility and focus
if (consoleRef.IsVisible())
{
consoleRef.ClearFocus();
consoleRef.Show(false);
}
else
{
consoleRef.Show(true);
consoleRef.SetFocus();
}
}
});
overlay->resizedSlot.Connect(info.renderTarget->OnRenderTargetSizeChange, [&consoleRef] (const Nz::RenderTarget* renderTarget)
{
Nz::Vector2ui size = renderTarget->GetSize();
consoleRef.Resize({float(size.x), size.y / 4.f});
});
info.console = std::move(overlay);
}
void Application::SetupFPSCounter(WindowInfo& info)
{
std::unique_ptr<FPSCounterOverlay> fpsCounter = std::make_unique<FPSCounterOverlay>();
fpsCounter->sprite = Nz::TextSprite::New();
fpsCounter->entity = info.overlayWorld->CreateEntity();
fpsCounter->entity->AddComponent<NodeComponent>();
fpsCounter->entity->AddComponent<GraphicsComponent>().Attach(fpsCounter->sprite);
info.fpsCounter = std::move(fpsCounter);
}
void Application::SetupOverlay(WindowInfo& info)
{
info.overlayWorld = std::make_unique<World>(false); //< No default system
if (info.window->IsValid())
info.canvas = std::make_unique<Canvas>(info.overlayWorld->CreateHandle(), info.window->GetEventHandler(), info.window->GetCursorController().CreateHandle());
RenderSystem& renderSystem = info.overlayWorld->AddSystem<RenderSystem>();
renderSystem.ChangeRenderTechnique<Nz::ForwardRenderTechnique>();
renderSystem.SetDefaultBackground(nullptr);
renderSystem.SetGlobalUp(Nz::Vector3f::Down());
EntityHandle viewer = info.overlayWorld->CreateEntity();
CameraComponent& camComponent = viewer->AddComponent<CameraComponent>();
viewer->AddComponent<NodeComponent>();
camComponent.SetProjectionType(Nz::ProjectionType_Orthogonal);
camComponent.SetTarget(info.renderTarget);
}
#endif
Application* Application::s_application = nullptr;
}

View File

@ -1,381 +0,0 @@
// Copyright (C) 2017 Jérôme Leclercq
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequisites.hpp
#include <NDK/BaseWidget.hpp>
#include <NDK/Canvas.hpp>
#include <NDK/Components/GraphicsComponent.hpp>
#include <NDK/Components/NodeComponent.hpp>
#include <NDK/World.hpp>
#include <algorithm>
namespace Ndk
{
/*!
* \ingroup NDK
* \class Ndk::BaseWidget
* \brief Abstract class serving as a base class for all widgets
*/
/*!
* \brief Constructs a BaseWidget object using another widget as its parent
*
* \param parent Parent widget, must be valid and attached to a canvas
*
* Constructs a BaseWidget object using another widget as a base.
* This will also register the widget to the canvas owning the top-most widget.
*/
BaseWidget::BaseWidget(BaseWidget* parent) :
BaseWidget()
{
NazaraAssert(parent, "Invalid parent");
NazaraAssert(parent->GetCanvas(), "Parent has no canvas");
m_canvas = parent->GetCanvas();
m_widgetParent = parent;
m_world = m_canvas->GetWorld();
RegisterToCanvas();
}
/*!
* \brief Frees the widget, unregistering it from its canvas
*/
BaseWidget::~BaseWidget()
{
UnregisterFromCanvas();
}
/*!
* \brief Clears keyboard focus if and only if this widget owns it.
*/
void BaseWidget::ClearFocus()
{
if (IsRegisteredToCanvas())
m_canvas->ClearKeyboardOwner(m_canvasIndex);
}
/*!
* \brief Destroy the widget, deleting it in the process.
*
* Calling this function immediately destroys the widget, freeing its memory.
*/
void BaseWidget::Destroy()
{
NazaraAssert(this != m_canvas, "Canvas cannot be destroyed by calling Destroy()");
m_widgetParent->DestroyChild(this); //< This does delete us
}
/*!
* \brief Enable or disables the widget background.
*/
void BaseWidget::EnableBackground(bool enable)
{
if (m_backgroundEntity.IsValid() == enable)
return;
if (enable)
{
m_backgroundSprite = Nz::Sprite::New();
m_backgroundSprite->SetColor(m_backgroundColor);
m_backgroundSprite->SetMaterial(Nz::Material::New((m_backgroundColor.IsOpaque()) ? "Basic2D" : "Translucent2D")); //< TODO: Use a shared material instead of creating one everytime
m_backgroundEntity = CreateEntity();
m_backgroundEntity->AddComponent<GraphicsComponent>().Attach(m_backgroundSprite, -1);
m_backgroundEntity->AddComponent<NodeComponent>().SetParent(this);
BaseWidget::Layout(); // Only layout background
}
else
{
DestroyEntity(m_backgroundEntity);
m_backgroundEntity.Reset();
m_backgroundSprite.Reset();
}
}
/*!
* \brief Checks if this widget has keyboard focus
* \return true if widget has keyboard focus, false otherwise
*/
bool BaseWidget::HasFocus() const
{
if (!IsRegisteredToCanvas())
return false;
return m_canvas->IsKeyboardOwner(m_canvasIndex);
}
void BaseWidget::Resize(const Nz::Vector2f& size)
{
// Adjust new size
Nz::Vector2f newSize = size;
newSize.Maximize(m_minimumSize);
newSize.Minimize(m_maximumSize);
NotifyParentResized(newSize);
m_size = newSize;
Layout();
}
void BaseWidget::SetBackgroundColor(const Nz::Color& color)
{
m_backgroundColor = color;
if (m_backgroundSprite)
{
m_backgroundSprite->SetColor(color);
m_backgroundSprite->GetMaterial()->Configure((color.IsOpaque()) ? "Basic2D" : "Translucent2D"); //< Our sprite has its own material (see EnableBackground)
}
}
void BaseWidget::SetCursor(Nz::SystemCursor systemCursor)
{
m_cursor = systemCursor;
if (IsRegisteredToCanvas())
m_canvas->NotifyWidgetCursorUpdate(m_canvasIndex);
}
void BaseWidget::SetFocus()
{
if (IsRegisteredToCanvas())
m_canvas->SetKeyboardOwner(m_canvasIndex);
}
void BaseWidget::SetParent(BaseWidget* widget)
{
Canvas* oldCanvas = m_canvas;
Canvas* newCanvas = widget->GetCanvas();
// Changing a widget canvas is a problem because of the canvas entities
NazaraAssert(oldCanvas == newCanvas, "Transferring a widget between canvas is not yet supported");
Node::SetParent(widget);
m_widgetParent = widget;
Layout();
}
void BaseWidget::SetRenderingRect(const Nz::Rectf& renderingRect)
{
m_renderingRect = renderingRect;
UpdatePositionAndSize();
for (const auto& widgetPtr : m_children)
widgetPtr->UpdatePositionAndSize();
}
void BaseWidget::Show(bool show)
{
if (m_visible != show)
{
m_visible = show;
if (m_visible)
RegisterToCanvas();
else
UnregisterFromCanvas();
for (WidgetEntity& entity : m_entities)
{
if (entity.isEnabled)
{
entity.handle->Enable(show); //< This will override isEnabled, so reset it next line
entity.isEnabled = true;
}
}
ShowChildren(show);
}
}
const EntityHandle& BaseWidget::CreateEntity()
{
const EntityHandle& newEntity = m_world->CreateEntity();
newEntity->Enable(m_visible);
m_entities.emplace_back();
WidgetEntity& newWidgetEntity = m_entities.back();
newWidgetEntity.handle = newEntity;
newWidgetEntity.onDisabledSlot.Connect(newEntity->OnEntityDisabled, [this](Entity* entity)
{
auto it = std::find_if(m_entities.begin(), m_entities.end(), [&](const WidgetEntity& widgetEntity) { return widgetEntity.handle == entity; });
NazaraAssert(it != m_entities.end(), "Entity does not belong to this widget");
it->isEnabled = false;
});
newWidgetEntity.onEnabledSlot.Connect(newEntity->OnEntityEnabled, [this](Entity* entity)
{
auto it = std::find_if(m_entities.begin(), m_entities.end(), [&](const WidgetEntity& widgetEntity) { return widgetEntity.handle == entity; });
NazaraAssert(it != m_entities.end(), "Entity does not belong to this widget");
if (!IsVisible())
entity->Disable(); // Next line will override isEnabled status
it->isEnabled = true;
});
return newEntity;
}
void BaseWidget::DestroyEntity(Entity* entity)
{
auto it = std::find_if(m_entities.begin(), m_entities.end(), [&](const WidgetEntity& widgetEntity) { return widgetEntity.handle == entity; });
NazaraAssert(it != m_entities.end(), "Entity does not belong to this widget");
m_entities.erase(it);
}
void BaseWidget::Layout()
{
if (m_backgroundSprite)
m_backgroundSprite->SetSize(m_size.x, m_size.y);
UpdatePositionAndSize();
}
void BaseWidget::InvalidateNode()
{
Node::InvalidateNode();
UpdatePositionAndSize();
}
Nz::Rectf BaseWidget::GetScissorRect() const
{
Nz::Vector2f widgetPos = Nz::Vector2f(GetPosition(Nz::CoordSys_Global));
Nz::Vector2f widgetSize = GetSize();
Nz::Rectf widgetRect(widgetPos.x, widgetPos.y, widgetSize.x, widgetSize.y);
Nz::Rectf widgetRenderingRect(widgetPos.x + m_renderingRect.x, widgetPos.y + m_renderingRect.y, m_renderingRect.width, m_renderingRect.height);
widgetRect.Intersect(widgetRenderingRect, &widgetRect);
return widgetRect;
}
bool BaseWidget::IsFocusable() const
{
return false;
}
void BaseWidget::OnFocusLost()
{
}
void BaseWidget::OnFocusReceived()
{
}
bool BaseWidget::OnKeyPressed(const Nz::WindowEvent::KeyEvent& key)
{
return false;
}
void BaseWidget::OnKeyReleased(const Nz::WindowEvent::KeyEvent& /*key*/)
{
}
void BaseWidget::OnMouseEnter()
{
}
void BaseWidget::OnMouseMoved(int /*x*/, int /*y*/, int /*deltaX*/, int /*deltaY*/)
{
}
void BaseWidget::OnMouseButtonPress(int /*x*/, int /*y*/, Nz::Mouse::Button /*button*/)
{
}
void BaseWidget::OnMouseButtonRelease(int /*x*/, int /*y*/, Nz::Mouse::Button /*button*/)
{
}
void BaseWidget::OnMouseWheelMoved(int /*x*/, int /*y*/, float /*delta*/)
{
}
void BaseWidget::OnMouseExit()
{
}
void BaseWidget::OnParentResized(const Nz::Vector2f& /*newSize*/)
{
}
void BaseWidget::OnTextEntered(char32_t /*character*/, bool /*repeated*/)
{
}
void BaseWidget::OnTextEdited(const std::array<char, 32>& /*characters*/, int /*length*/)
{
}
void BaseWidget::ShowChildren(bool show)
{
for (const auto& widgetPtr : m_children)
widgetPtr->Show(show);
}
void BaseWidget::DestroyChild(BaseWidget* widget)
{
auto it = std::find_if(m_children.begin(), m_children.end(), [widget] (const std::unique_ptr<BaseWidget>& widgetPtr) -> bool
{
return widgetPtr.get() == widget;
});
NazaraAssert(it != m_children.end(), "Child widget not found in parent");
m_children.erase(it);
}
void BaseWidget::DestroyChildren()
{
m_children.clear();
}
void BaseWidget::RegisterToCanvas()
{
NazaraAssert(!IsRegisteredToCanvas(), "Widget is already registered to canvas");
m_canvasIndex = m_canvas->RegisterWidget(this);
}
void BaseWidget::UnregisterFromCanvas()
{
if (IsRegisteredToCanvas())
{
m_canvas->UnregisterWidget(m_canvasIndex);
m_canvasIndex = InvalidCanvasIndex;
}
}
void BaseWidget::UpdatePositionAndSize()
{
if (IsRegisteredToCanvas())
m_canvas->NotifyWidgetBoxUpdate(m_canvasIndex);
Nz::Rectf scissorRect = GetScissorRect();
if (m_widgetParent)
{
Nz::Rectf parentScissorRect = m_widgetParent->GetScissorRect();
if (!scissorRect.Intersect(parentScissorRect, &scissorRect))
scissorRect = parentScissorRect;
}
Nz::Recti fullBounds(scissorRect);
for (WidgetEntity& widgetEntity : m_entities)
{
const Ndk::EntityHandle& entity = widgetEntity.handle;
if (entity->HasComponent<GraphicsComponent>())
entity->GetComponent<GraphicsComponent>().SetScissorRect(fullBounds);
}
}
}

View File

@ -1,230 +0,0 @@
// Copyright (C) 2017 Jérôme Leclercq
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequisites.hpp
#include <NDK/Canvas.hpp>
#include <limits>
namespace Ndk
{
std::size_t Canvas::RegisterWidget(BaseWidget* widget)
{
WidgetEntry box;
box.cursor = widget->GetCursor();
box.widget = widget;
std::size_t index = m_widgetEntries.size();
m_widgetEntries.emplace_back(box);
NotifyWidgetBoxUpdate(index);
return index;
}
void Canvas::UnregisterWidget(std::size_t index)
{
WidgetEntry& entry = m_widgetEntries[index];
if (m_hoveredWidget == index)
m_hoveredWidget = InvalidCanvasIndex;
if (m_keyboardOwner == index)
m_keyboardOwner = InvalidCanvasIndex;
if (m_widgetEntries.size() > 1U)
{
WidgetEntry& lastEntry = m_widgetEntries.back();
std::size_t lastEntryIndex = m_widgetEntries.size() - 1;
entry = std::move(lastEntry);
entry.widget->UpdateCanvasIndex(index);
if (m_hoveredWidget == lastEntryIndex)
m_hoveredWidget = index;
if (m_keyboardOwner == lastEntryIndex)
m_keyboardOwner = index;
}
m_widgetEntries.pop_back();
}
void Canvas::OnEventMouseButtonPressed(const Nz::EventHandler* /*eventHandler*/, const Nz::WindowEvent::MouseButtonEvent& event)
{
if (m_hoveredWidget != InvalidCanvasIndex)
{
WidgetEntry& hoveredWidget = m_widgetEntries[m_hoveredWidget];
int x = static_cast<int>(std::round(event.x - hoveredWidget.box.x));
int y = static_cast<int>(std::round(event.y - hoveredWidget.box.y));
hoveredWidget.widget->OnMouseButtonPress(x, y, event.button);
}
}
void Canvas::OnEventMouseButtonRelease(const Nz::EventHandler* /*eventHandler*/, const Nz::WindowEvent::MouseButtonEvent& event)
{
if (m_hoveredWidget != InvalidCanvasIndex)
{
WidgetEntry& hoveredWidget = m_widgetEntries[m_hoveredWidget];
int x = static_cast<int>(std::round(event.x - hoveredWidget.box.x));
int y = static_cast<int>(std::round(event.y - hoveredWidget.box.y));
hoveredWidget.widget->OnMouseButtonRelease(x, y, event.button);
}
}
void Canvas::OnEventMouseMoved(const Nz::EventHandler* /*eventHandler*/, const Nz::WindowEvent::MouseMoveEvent& event)
{
std::size_t bestEntry = InvalidCanvasIndex;
float bestEntryArea = std::numeric_limits<float>::infinity();
Nz::Vector3f mousePos(float(event.x), float(event.y), 0.f);
for (std::size_t i = 0; i < m_widgetEntries.size(); ++i)
{
const Nz::Boxf& box = m_widgetEntries[i].box;
if (box.Contains(mousePos))
{
float area = box.width * box.height;
if (area < bestEntryArea)
{
bestEntry = i;
bestEntryArea = area;
}
}
}
if (bestEntry != InvalidCanvasIndex)
{
if (m_hoveredWidget != bestEntry)
{
if (m_hoveredWidget != InvalidCanvasIndex)
{
WidgetEntry& previouslyHovered = m_widgetEntries[m_hoveredWidget];
previouslyHovered.widget->OnMouseExit();
}
m_hoveredWidget = bestEntry;
m_widgetEntries[m_hoveredWidget].widget->OnMouseEnter();
if (m_cursorController)
m_cursorController->UpdateCursor(Nz::Cursor::Get(m_widgetEntries[m_hoveredWidget].cursor));
}
WidgetEntry& hoveredWidget = m_widgetEntries[m_hoveredWidget];
int x = static_cast<int>(std::round(event.x - hoveredWidget.box.x));
int y = static_cast<int>(std::round(event.y - hoveredWidget.box.y));
hoveredWidget.widget->OnMouseMoved(x, y, event.deltaX, event.deltaY);
}
else if (m_hoveredWidget != InvalidCanvasIndex)
{
m_widgetEntries[m_hoveredWidget].widget->OnMouseExit();
m_hoveredWidget = InvalidCanvasIndex;
if (m_cursorController)
m_cursorController->UpdateCursor(Nz::Cursor::Get(Nz::SystemCursor_Default));
}
}
void Canvas::OnEventMouseWheelMoved(const Nz::EventHandler* /*eventHandler*/, const Nz::WindowEvent::MouseWheelEvent& event)
{
if (m_hoveredWidget != InvalidCanvasIndex)
{
WidgetEntry& hoveredWidget = m_widgetEntries[m_hoveredWidget];
int x = static_cast<int>(std::round(event.x - hoveredWidget.box.x));
int y = static_cast<int>(std::round(event.y - hoveredWidget.box.y));
hoveredWidget.widget->OnMouseWheelMoved(x, y, event.delta);
}
}
void Canvas::OnEventMouseLeft(const Nz::EventHandler* /*eventHandler*/)
{
if (m_hoveredWidget != InvalidCanvasIndex)
{
m_widgetEntries[m_hoveredWidget].widget->OnMouseExit();
m_hoveredWidget = InvalidCanvasIndex;
}
}
void Canvas::OnEventKeyPressed(const Nz::EventHandler* eventHandler, const Nz::WindowEvent::KeyEvent& event)
{
if (m_keyboardOwner != InvalidCanvasIndex)
{
if (m_widgetEntries[m_keyboardOwner].widget->OnKeyPressed(event))
return;
if (event.virtualKey == Nz::Keyboard::VKey::Tab)
{
if (!event.shift)
{
// Forward
for (std::size_t i = m_keyboardOwner + 1; i < m_widgetEntries.size(); ++i)
{
if (m_widgetEntries[i].widget->IsFocusable())
{
SetKeyboardOwner(i);
return;
}
}
for (std::size_t i = 0; i < m_keyboardOwner; ++i)
{
if (m_widgetEntries[i].widget->IsFocusable())
{
SetKeyboardOwner(i);
return;
}
}
}
else
{
// Backward
for (decltype(m_widgetEntries)::reverse_iterator rit{ m_widgetEntries.begin() + m_keyboardOwner }; rit != m_widgetEntries.rend(); ++rit)
{
if (rit->widget->IsFocusable())
{
SetKeyboardOwner(std::distance(m_widgetEntries.begin(), rit.base()) - 1);
return;
}
}
decltype(m_widgetEntries)::reverse_iterator rend { m_widgetEntries.begin() + m_keyboardOwner };
for (auto rit = m_widgetEntries.rbegin(); rit != rend; ++rit)
{
if (rit->widget->IsFocusable())
{
SetKeyboardOwner(std::distance(m_widgetEntries.begin(), rit.base()) - 1);
return;
}
}
}
}
}
OnUnhandledKeyPressed(eventHandler, event);
}
void Canvas::OnEventKeyReleased(const Nz::EventHandler* eventHandler, const Nz::WindowEvent::KeyEvent& event)
{
if (m_keyboardOwner != InvalidCanvasIndex)
m_widgetEntries[m_keyboardOwner].widget->OnKeyReleased(event);
OnUnhandledKeyReleased(eventHandler, event);
}
void Canvas::OnEventTextEntered(const Nz::EventHandler* /*eventHandler*/, const Nz::WindowEvent::TextEvent& event)
{
if (m_keyboardOwner != InvalidCanvasIndex)
m_widgetEntries[m_keyboardOwner].widget->OnTextEntered(event.character, event.repeated);
}
void Canvas::OnEventTextEdited(const Nz::EventHandler* /*eventHandler*/, const Nz::WindowEvent::EditEvent& event)
{
if (m_keyboardOwner != InvalidCanvasIndex)
m_widgetEntries[m_keyboardOwner].widget->OnTextEdited(event.text, event.length);
}
}

View File

@ -1,363 +0,0 @@
// Copyright (C) 2017 Jérôme Leclercq
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequisites.hpp
#include <NDK/Components/CameraComponent.hpp>
#include <Nazara/Renderer/Renderer.hpp>
#include <NDK/Algorithm.hpp>
#include <NDK/Components/NodeComponent.hpp>
namespace Ndk
{
/*!
* \ingroup NDK
* \class Ndk::CameraComponent
* \brief NDK class that represents the component for camera
*/
/*!
* \brief Applys the view of the camera
*
* \remark Produces a NazaraAssert if the camera has no target
*/
void CameraComponent::ApplyView() const
{
NazaraAssert(m_target, "CameraComponent has no target");
EnsureProjectionMatrixUpdate();
EnsureViewMatrixUpdate();
EnsureViewportUpdate();
Nz::Renderer::SetMatrix(Nz::MatrixType_Projection, m_projectionMatrix);
Nz::Renderer::SetMatrix(Nz::MatrixType_View, m_viewMatrix);
Nz::Renderer::SetTarget(m_target);
Nz::Renderer::SetViewport(m_viewport);
}
/*!
* \brief Gets the aspect ratio of the camera
* \return Aspect ratio of the camera
*/
float CameraComponent::GetAspectRatio() const
{
EnsureViewportUpdate();
return m_aspectRatio;
}
/*!
* \brief Gets the eye position of the camera
*
* \remark Produces a NazaraAssert if entity is invalid or has no NodeComponent
*/
Nz::Vector3f CameraComponent::GetEyePosition() const
{
NazaraAssert(m_entity && m_entity->HasComponent<NodeComponent>(), "CameraComponent requires NodeComponent");
return m_entity->GetComponent<NodeComponent>().GetPosition();
}
/*!
* \brief Gets the forward direction of the camera
*
* \remark Produces a NazaraAssert if entity is invalid or has no NodeComponent
*/
Nz::Vector3f CameraComponent::GetForward() const
{
NazaraAssert(m_entity && m_entity->HasComponent<NodeComponent>(), "CameraComponent requires NodeComponent");
return m_entity->GetComponent<NodeComponent>().GetForward();
}
/*!
* \brief Gets the frutum of the camera
* \return A constant reference to the frustum of the camera
*/
const Nz::Frustumf& CameraComponent::GetFrustum() const
{
EnsureFrustumUpdate();
return m_frustum;
}
/*!
* \brief Gets the projection matrix of the camera
* \return A constant reference to the projection matrix of the camera
*/
const Nz::Matrix4f& CameraComponent::GetProjectionMatrix() const
{
EnsureProjectionMatrixUpdate();
return m_projectionMatrix;
}
/*!
* \brief Gets the projection type of the camera
* \return Projection type of the camera
*/
Nz::ProjectionType CameraComponent::GetProjectionType() const
{
return m_projectionType;
}
/*!
* \brief Gets the target of the camera
* \return A constant reference to the render target of the camera
*/
const Nz::RenderTarget* CameraComponent::GetTarget() const
{
return m_target;
}
/*!
* \brief Gets the view matrix of the camera
* \return A constant reference to the view matrix of the camera
*/
const Nz::Matrix4f& CameraComponent::GetViewMatrix() const
{
EnsureViewMatrixUpdate();
return m_viewMatrix;
}
/*!
* \brief Gets the view port of the camera
* \return A constant reference to the view port of the camera
*/
const Nz::Recti& CameraComponent::GetViewport() const
{
EnsureViewportUpdate();
return m_viewport;
}
/*!
* \brief Gets the Z far distance of the camera
* \return Z far distance of the camera
*/
float CameraComponent::GetZFar() const
{
return m_zFar;
}
/*!
* \brief Gets the Z near distance of the camera
* \return Z near distance of the camera
*/
float CameraComponent::GetZNear() const
{
return m_zNear;
}
/*!
* \brief Sets the layer of the camera in case of multiples layers
*
* \param layer Layer of the camera
*/
void CameraComponent::SetLayer(unsigned int layer)
{
m_layer = layer;
m_entity->Invalidate(); // Invalidate the entity to make it passes through RenderSystem validation
}
/*!
* \brief Operation to perform when component is attached to an entity
*/
void CameraComponent::OnAttached()
{
if (m_entity->HasComponent<NodeComponent>())
m_nodeInvalidationSlot.Connect(m_entity->GetComponent<NodeComponent>().OnNodeInvalidation, this, &CameraComponent::OnNodeInvalidated);
InvalidateViewMatrix();
}
/*!
* \brief Operation to perform when component is attached to this component
*
* \param component Component being attached
*/
void CameraComponent::OnComponentAttached(BaseComponent& component)
{
if (IsComponent<NodeComponent>(component))
{
NodeComponent& nodeComponent = static_cast<NodeComponent&>(component);
m_nodeInvalidationSlot.Connect(nodeComponent.OnNodeInvalidation, this, &CameraComponent::OnNodeInvalidated);
InvalidateViewMatrix();
}
}
/*!
* \brief Operation to perform when component is detached from this component
*
* \param component Component being detached
*/
void CameraComponent::OnComponentDetached(BaseComponent& component)
{
if (IsComponent<NodeComponent>(component))
{
m_nodeInvalidationSlot.Disconnect();
InvalidateViewMatrix();
}
}
/*!
* \brief Operation to perform when component is detached from an entity
*/
void CameraComponent::OnDetached()
{
m_nodeInvalidationSlot.Disconnect();
InvalidateViewMatrix();
}
/*!
* \brief Operation to perform when the node is invalidated
*
* \param node Pointer to the node
*/
void CameraComponent::OnNodeInvalidated(const Nz::Node* node)
{
NazaraUnused(node);
// Our view matrix depends on NodeComponent position/rotation
InvalidateViewMatrix();
}
/*!
* \brief Operation to perform when the render target is released
*
* \param renderTarget Pointer to the RenderTarget
*/
void CameraComponent::OnRenderTargetRelease(const Nz::RenderTarget* renderTarget)
{
if (renderTarget == m_target)
m_target = nullptr;
else
NazaraInternalError("Not listening to " + Nz::String::Pointer(renderTarget));
}
/*!
* \brief Operation to perform when the render target has its size changed
*
* \param renderTarget Pointer to the RenderTarget
*/
void CameraComponent::OnRenderTargetSizeChange(const Nz::RenderTarget* renderTarget)
{
if (renderTarget == m_target)
InvalidateViewport();
else
NazaraInternalError("Not listening to " + Nz::String::Pointer(renderTarget));
}
/*!
* \brief Updates the frustum of the camera
*/
void CameraComponent::UpdateFrustum() const
{
EnsureProjectionMatrixUpdate();
EnsureViewMatrixUpdate();
// Extract the frustum from the view and projection matrices
m_frustum.Extract(m_viewMatrix, m_projectionMatrix);
m_frustumUpdated = true;
}
/*!
* \brief Updates the project matrix of the camera
*/
void CameraComponent::UpdateProjectionMatrix() const
{
switch (m_projectionType)
{
case Nz::ProjectionType_Orthogonal:
if (m_size.x <= 0.f || m_size.y <= 0.f)
{
EnsureViewportUpdate();
m_projectionMatrix.MakeOrtho(0.f, static_cast<float>(m_viewport.width), 0.f, static_cast<float>(m_viewport.height), m_zNear, m_zFar);
}
else
m_projectionMatrix.MakeOrtho(0.f, m_size.x, 0.f, m_size.y, m_zNear, m_zFar);
break;
case Nz::ProjectionType_Perspective:
EnsureViewportUpdate(); // Can affect aspect ratio
m_projectionMatrix.MakePerspective(m_fov, m_aspectRatio, m_zNear, m_zFar);
break;
}
m_projectionMatrix *= Nz::Matrix4f::Scale(m_projectionScale);
m_projectionMatrixUpdated = true;
}
/*!
* \brief Updates the view matrix of the camera
*
* \remark Produces a NazaraAssert if entity is invalid or has no NodeComponent
*/
void CameraComponent::UpdateViewMatrix() const
{
NazaraAssert(m_entity && m_entity->HasComponent<NodeComponent>(), "CameraComponent requires NodeComponent");
NodeComponent& nodeComponent = m_entity->GetComponent<NodeComponent>();
// Build the view matrix using the NodeComponent position/rotation
m_viewMatrix.MakeViewMatrix(nodeComponent.GetPosition(Nz::CoordSys_Global), nodeComponent.GetRotation(Nz::CoordSys_Global));
m_viewMatrixUpdated = true;
}
/*!
* \brief Updates the view port of the camera
*
* \remark Produces a NazaraAssert if entity has no target
*/
void CameraComponent::UpdateViewport() const
{
NazaraAssert(m_target, "CameraComponent has no target");
Nz::Vector2ui targetSize = m_target->GetSize();
targetSize.y = std::max(targetSize.y, 1U); // Let's make sure we won't divide by zero
// Our target region is expressed as % of the viewport dimensions, let's compute it in pixels
Nz::Rectf fViewport(m_targetRegion);
fViewport.x *= targetSize.x;
fViewport.y *= targetSize.y;
fViewport.width *= targetSize.x;
fViewport.height *= targetSize.y;
// Compute the new aspect ratio, if it's different we need to invalidate the projection matrix
float aspectRatio = fViewport.width/fViewport.height;
if (!Nz::NumberEquals(m_aspectRatio, aspectRatio, 0.001f))
{
m_aspectRatio = aspectRatio;
if (m_projectionType == Nz::ProjectionType_Perspective)
InvalidateProjectionMatrix();
}
// Convert it back to int
m_viewport.Set(fViewport);
m_viewportUpdated = true;
}
ComponentIndex CameraComponent::componentIndex;
}

View File

@ -1,35 +0,0 @@
// Copyright (C) 2017 Jérôme Leclercq
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequisites.hpp
#include <NDK/Components/DebugComponent.hpp>
#include <NDK/Components/GraphicsComponent.hpp>
namespace Ndk
{
void DebugComponent::DetachDebugRenderables(GraphicsComponent& gfxComponent)
{
for (auto& renderable : m_debugRenderables)
{
if (renderable)
{
gfxComponent.Detach(renderable);
renderable.Reset();
}
}
}
void DebugComponent::OnComponentDetached(BaseComponent& component)
{
if (IsComponent<GraphicsComponent>(component))
DetachDebugRenderables(static_cast<GraphicsComponent&>(component));
}
void DebugComponent::OnDetached()
{
if (m_entity->HasComponent<GraphicsComponent>())
DetachDebugRenderables(m_entity->GetComponent<GraphicsComponent>());
}
ComponentIndex DebugComponent::componentIndex;
}

View File

@ -1,348 +0,0 @@
// Copyright (C) 2017 Jérôme Leclercq
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequisites.hpp
#include <NDK/Components/GraphicsComponent.hpp>
#include <NDK/World.hpp>
#include <NDK/Systems/RenderSystem.hpp>
#include <NDK/Components/NodeComponent.hpp>
namespace Ndk
{
/*!
* \ingroup NDK
* \class Ndk::GraphicsComponent
* \brief NDK class that represents the component for graphics
*/
/*!
* \brief Adds the renderable elements to the render queue
*
* \param renderQueue Queue to be added
*/
void GraphicsComponent::AddToRenderQueue(Nz::AbstractRenderQueue* renderQueue) const
{
EnsureBoundingVolumesUpdate();
EnsureTransformMatrixUpdate();
RenderSystem& renderSystem = m_entity->GetWorld()->GetSystem<RenderSystem>();
for (const Renderable& object : m_renderables)
{
if (!object.dataUpdated)
{
object.renderable->UpdateData(&object.data);
object.dataUpdated = true;
}
object.renderable->AddToRenderQueue(renderQueue, object.data, m_scissorRect);
}
}
/*!
* \brief Adds the renderable elements to the render queue if their bounding volume intersects with the frustum
*
* \param frustum Queue to be added
* \param renderQueue Queue to be added
*/
void GraphicsComponent::AddToRenderQueueByCulling(const Nz::Frustumf& frustum, Nz::AbstractRenderQueue* renderQueue) const
{
EnsureBoundingVolumesUpdate();
EnsureTransformMatrixUpdate();
RenderSystem& renderSystem = m_entity->GetWorld()->GetSystem<RenderSystem>();
for (const Renderable& object : m_renderables)
{
if (frustum.Contains(object.boundingVolume))
{
if (!object.dataUpdated)
{
object.renderable->UpdateData(&object.data);
object.dataUpdated = true;
}
object.renderable->AddToRenderQueue(renderQueue, object.data, m_scissorRect);
}
}
}
/*!
* \brief Attaches a renderable to the entity with a specific matrix
*
* \param renderable Reference to a renderable element
* \param localMatrix Local matrix that will be applied to the instanced renderable
* \param renderOrder Render order of the element
*/
void GraphicsComponent::Attach(Nz::InstancedRenderableRef renderable, const Nz::Matrix4f& localMatrix, int renderOrder)
{
m_renderables.emplace_back(m_transformMatrix);
Renderable& entry = m_renderables.back();
entry.data.localMatrix = localMatrix;
entry.data.renderOrder = renderOrder;
entry.renderable = std::move(renderable);
ConnectInstancedRenderableSignals(entry);
std::size_t materialCount = entry.renderable->GetMaterialCount();
for (std::size_t i = 0; i < materialCount; ++i)
RegisterMaterial(entry.renderable->GetMaterial(i));
InvalidateAABB();
ForceCullingInvalidation();
}
void GraphicsComponent::ConnectInstancedRenderableSignals(Renderable& entry)
{
entry.renderableBoundingVolumeInvalidationSlot.Connect(entry.renderable->OnInstancedRenderableInvalidateBoundingVolume, [this](const Nz::InstancedRenderable*) { InvalidateAABB(); });
entry.renderableDataInvalidationSlot.Connect(entry.renderable->OnInstancedRenderableInvalidateData, std::bind(&GraphicsComponent::InvalidateRenderableData, this, std::placeholders::_1, std::placeholders::_2, m_renderables.size() - 1));
entry.renderableMaterialInvalidationSlot.Connect(entry.renderable->OnInstancedRenderableInvalidateMaterial, this, &GraphicsComponent::InvalidateRenderableMaterial);
entry.renderableReleaseSlot.Connect(entry.renderable->OnInstancedRenderableRelease, this, &GraphicsComponent::Detach);
entry.renderableResetMaterialsSlot.Connect(entry.renderable->OnInstancedRenderableResetMaterials, this, &GraphicsComponent::OnInstancedRenderableResetMaterials);
entry.renderableSkinChangeSlot.Connect(entry.renderable->OnInstancedRenderableSkinChange, this, &GraphicsComponent::OnInstancedRenderableSkinChange);
}
void GraphicsComponent::InvalidateRenderableData(const Nz::InstancedRenderable* renderable , Nz::UInt32 flags, std::size_t index)
{
NazaraAssert(index < m_renderables.size(), "Invalid renderable index");
NazaraUnused(renderable);
Renderable& r = m_renderables[index];
r.dataUpdated = false;
r.renderable->InvalidateData(&r.data, flags);
ForceCullingInvalidation();
}
void GraphicsComponent::InvalidateRenderableMaterial(const Nz::InstancedRenderable* renderable, std::size_t skinIndex, std::size_t matIndex, const Nz::MaterialRef& newMat)
{
// Don't listen to dormant materials
if (renderable->GetSkin() != skinIndex)
return;
RegisterMaterial(newMat);
const Nz::MaterialRef& oldMat = renderable->GetMaterial(skinIndex, matIndex);
UnregisterMaterial(oldMat);
ForceCullingInvalidation();
}
void GraphicsComponent::InvalidateReflectionMap()
{
m_entity->Invalidate();
if (m_reflectiveMaterialCount > 0)
{
if (!m_reflectionMap)
{
m_reflectionMap = Nz::Texture::New();
if (!m_reflectionMap->Create(Nz::ImageType_Cubemap, Nz::PixelFormatType_RGB8, m_reflectionMapSize, m_reflectionMapSize))
{
NazaraWarning("Failed to create reflection map, reflections will be disabled for this entity");
return;
}
}
}
else
m_reflectionMap.Reset();
}
void GraphicsComponent::RegisterMaterial(Nz::Material* material, std::size_t count)
{
auto it = m_materialEntries.find(material);
if (it == m_materialEntries.end())
{
MaterialEntry matEntry;
matEntry.reflectionModelChangeSlot.Connect(material->OnMaterialReflectionModeChange, this, &GraphicsComponent::OnMaterialReflectionChange);
matEntry.renderableCounter = count;
if (material->GetReflectionMode() == Nz::ReflectionMode_RealTime)
{
if (m_reflectiveMaterialCount++ == 0)
InvalidateReflectionMap();
}
m_materialEntries.emplace(material, std::move(matEntry));
}
else
it->second.renderableCounter += count;
}
/*!
* \brief Operation to perform when component is attached to an entity
*/
void GraphicsComponent::OnAttached()
{
if (m_entity->HasComponent<NodeComponent>())
m_nodeInvalidationSlot.Connect(m_entity->GetComponent<NodeComponent>().OnNodeInvalidation, this, &GraphicsComponent::OnNodeInvalidated);
InvalidateTransformMatrix();
}
/*!
* \brief Operation to perform when component is attached to this component
*
* \param component Component being attached
*/
void GraphicsComponent::OnComponentAttached(BaseComponent& component)
{
if (IsComponent<NodeComponent>(component))
{
NodeComponent& nodeComponent = static_cast<NodeComponent&>(component);
m_nodeInvalidationSlot.Connect(nodeComponent.OnNodeInvalidation, this, &GraphicsComponent::OnNodeInvalidated);
InvalidateTransformMatrix();
}
}
/*!
* \brief Operation to perform when component is detached from this component
*
* \param component Component being detached
*/
void GraphicsComponent::OnComponentDetached(BaseComponent& component)
{
if (IsComponent<NodeComponent>(component))
{
m_nodeInvalidationSlot.Disconnect();
InvalidateTransformMatrix();
}
}
/*!
* \brief Operation to perform when component is detached from an entity
*/
void GraphicsComponent::OnDetached()
{
m_nodeInvalidationSlot.Disconnect();
InvalidateTransformMatrix();
}
void GraphicsComponent::OnInstancedRenderableResetMaterials(const Nz::InstancedRenderable* renderable, std::size_t newMaterialCount)
{
RegisterMaterial(Nz::Material::GetDefault(), newMaterialCount);
std::size_t materialCount = renderable->GetMaterialCount();
for (std::size_t i = 0; i < materialCount; ++i)
UnregisterMaterial(renderable->GetMaterial(i));
ForceCullingInvalidation();
}
void GraphicsComponent::OnInstancedRenderableSkinChange(const Nz::InstancedRenderable* renderable, std::size_t newSkinIndex)
{
std::size_t materialCount = renderable->GetMaterialCount();
for (std::size_t i = 0; i < materialCount; ++i)
RegisterMaterial(renderable->GetMaterial(newSkinIndex, i));
for (std::size_t i = 0; i < materialCount; ++i)
UnregisterMaterial(renderable->GetMaterial(i));
ForceCullingInvalidation();
}
void GraphicsComponent::OnMaterialReflectionChange(const Nz::Material* material, Nz::ReflectionMode reflectionMode)
{
// Since this signal is only called when the new reflection mode is different from the current one, no need to compare both
if (material->GetReflectionMode() == Nz::ReflectionMode_RealTime)
{
if (--m_reflectiveMaterialCount == 0)
InvalidateReflectionMap();
}
else if (reflectionMode == Nz::ReflectionMode_RealTime)
{
if (m_reflectiveMaterialCount++ == 0)
InvalidateReflectionMap();
}
}
void GraphicsComponent::OnNodeInvalidated(const Nz::Node* node)
{
NazaraUnused(node);
// Our view matrix depends on NodeComponent position/rotation
InvalidateAABB();
InvalidateTransformMatrix();
ForceCullingInvalidation(); //< Force invalidation on movement for now (FIXME)
}
void GraphicsComponent::UnregisterMaterial(Nz::Material* material)
{
auto it = m_materialEntries.find(material);
NazaraAssert(it != m_materialEntries.end(), "Material not registered");
MaterialEntry& matEntry = it->second;
if (--matEntry.renderableCounter == 0)
{
if (material->GetReflectionMode() == Nz::ReflectionMode_RealTime)
{
if (--m_reflectiveMaterialCount == 0)
InvalidateReflectionMap();
}
m_materialEntries.erase(it);
}
}
/*!
* \brief Updates the bounding volume
*/
void GraphicsComponent::UpdateBoundingVolumes() const
{
EnsureTransformMatrixUpdate();
RenderSystem& renderSystem = m_entity->GetWorld()->GetSystem<RenderSystem>();
m_aabb.Set(-1.f, -1.f, -1.f);
bool isAabbSet = false;
for (const Renderable& r : m_renderables)
{
r.boundingVolume = r.renderable->GetBoundingVolume();
r.data.transformMatrix = Nz::Matrix4f::ConcatenateAffine(renderSystem.GetCoordinateSystemMatrix(), Nz::Matrix4f::ConcatenateAffine(r.data.localMatrix, m_transformMatrix));
if (r.boundingVolume.IsFinite())
{
r.boundingVolume.Update(r.data.transformMatrix);
if (isAabbSet)
m_aabb.ExtendTo(r.boundingVolume.aabb);
else
{
m_aabb.Set(r.boundingVolume.aabb);
isAabbSet = true;
}
}
}
m_boundingVolumesUpdated = true;
for (CullingBoxEntry& entry : m_cullingBoxEntries)
entry.listEntry.UpdateBox(m_aabb);
}
/*!
* \brief Updates the transform matrix of the renderable
*
* \remark Produces a NazaraAssert if entity is invalid or has no NodeComponent
*/
void GraphicsComponent::UpdateTransformMatrix() const
{
NazaraAssert(m_entity && m_entity->HasComponent<NodeComponent>(), "GraphicsComponent requires NodeComponent");
m_transformMatrix = m_entity->GetComponent<NodeComponent>().GetTransformMatrix();
m_transformMatrixUpdated = true;
}
ComponentIndex GraphicsComponent::componentIndex;
}

View File

@ -1,10 +0,0 @@
// Copyright (C) 2017 Jérôme Leclercq
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequisites.hpp
#include <NDK/Components/LightComponent.hpp>
namespace Ndk
{
ComponentIndex LightComponent::componentIndex;
}

View File

@ -1,30 +0,0 @@
// Copyright (C) 2017 Jérôme Leclercq
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequisites.hpp
#include <NDK/Components/ParticleEmitterComponent.hpp>
#include <Nazara/Graphics/ParticleGroup.hpp>
namespace Ndk
{
/*!
* \ingroup NDK
* \class Ndk::ParticleEmitterComponent
* \brief NDK class that represents the component emitter of particles
*/
/*!
* \brief Sets up the particles
*
* \param mapper Mapper containing layout information of each particle
* \param count Number of particles
*/
void ParticleEmitterComponent::SetupParticles(Nz::ParticleMapper& mapper, unsigned int count) const
{
if (m_isActive && m_setupFunc)
m_setupFunc(m_entity, mapper, count);
}
ComponentIndex ParticleEmitterComponent::componentIndex;
}

View File

@ -1,10 +0,0 @@
// Copyright (C) 2017 Jérôme Leclercq
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequisites.hpp
#include <NDK/Components/ParticleGroupComponent.hpp>
namespace Ndk
{
ComponentIndex ParticleGroupComponent::componentIndex;
}

View File

@ -1,232 +0,0 @@
// Copyright (C) 2017 Jérôme Leclercq
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequisites.hpp
#include <NDK/Console.hpp>
#include <Nazara/Core/Unicode.hpp>
#include <Nazara/Platform/Event.hpp>
#include <NDK/Components/GraphicsComponent.hpp>
#include <NDK/Components/NodeComponent.hpp>
#include <NDK/Widgets.hpp>
#include <NDK/World.hpp>
namespace Ndk
{
namespace
{
const char s_inputPrefix[] = "> ";
constexpr std::size_t s_inputPrefixSize = Nz::CountOf(s_inputPrefix) - 1;
}
/*!
* \ingroup NDK
* \class Ndk::Console
* \brief NDK class that represents a console to help development with Lua scripting
*/
/*!
* \brief Constructs a Console object with a world to interact with
*
* \param world World to interact with
* \param size (Width, Height) of the console
* \param instance Lua instance that will interact with the world
*/
Console::Console(BaseWidget* parent) :
BaseWidget(parent),
m_historyPosition(0),
m_defaultFont(Nz::Font::GetDefault()),
m_characterSize(24),
m_maxHistoryLines(200)
{
// History
m_history = Add<RichTextAreaWidget>();
m_history->EnableBackground(true);
m_history->EnableLineWrap(true);
m_history->SetReadOnly(true);
m_history->SetBackgroundColor(Nz::Color(80, 80, 160, 128));
m_historyArea = Add<ScrollAreaWidget>(m_history);
// Input
m_input = Add<TextAreaWidget>();
m_input->EnableBackground(true);
m_input->SetText(s_inputPrefix);
m_input->SetTextColor(Nz::Color::Black);
m_input->OnTextAreaKeyReturn.Connect(this, &Console::ExecuteInput);
// Protect input prefix from erasure/selection
m_input->SetCursorPosition(s_inputPrefixSize);
m_input->OnTextAreaCursorMove.Connect([](const AbstractTextAreaWidget* textArea, Nz::Vector2ui* newCursorPos)
{
newCursorPos->x = std::max(newCursorPos->x, static_cast<unsigned int>(s_inputPrefixSize));
});
m_input->OnTextAreaSelection.Connect([](const AbstractTextAreaWidget* textArea, Nz::Vector2ui* start, Nz::Vector2ui* end)
{
start->x = std::max(start->x, static_cast<unsigned int>(s_inputPrefixSize));
end->x = std::max(end->x, static_cast<unsigned int>(s_inputPrefixSize));
});
m_input->OnTextAreaKeyBackspace.Connect([](const AbstractTextAreaWidget* textArea, bool* ignoreDefaultAction)
{
if (textArea->GetGlyphIndex() < s_inputPrefixSize)
*ignoreDefaultAction = true;
});
// Handle history
m_input->OnTextAreaKeyUp.Connect([&] (const AbstractTextAreaWidget* textArea, bool* ignoreDefaultAction)
{
*ignoreDefaultAction = true;
if (m_commandHistory.empty())
return;
if (m_historyPosition > 0)
m_historyPosition--;
m_input->SetText(s_inputPrefix + m_commandHistory[m_historyPosition]);
});
m_input->OnTextAreaKeyDown.Connect([&] (const AbstractTextAreaWidget* textArea, bool* ignoreDefaultAction)
{
*ignoreDefaultAction = true;
if (m_commandHistory.empty())
return;
if (++m_historyPosition >= m_commandHistory.size())
m_historyPosition = 0;
m_input->SetText(s_inputPrefix + m_commandHistory[m_historyPosition]);
});
}
/*!
* \brief Adds a line to the console
*
* \param text New line of text
* \param color Color for the text
*/
void Console::AddLine(const Nz::String& text, const Nz::Color& color)
{
if (m_historyLines.size() >= m_maxHistoryLines)
m_historyLines.erase(m_historyLines.begin());
m_historyLines.emplace_back(Line{ color, text });
m_history->SetTextColor(color);
m_history->AppendText(text + '\n');
m_history->Resize(m_history->GetPreferredSize());
m_historyArea->Resize(m_historyArea->GetSize());
m_historyArea->ScrollToRatio(1.f);
}
/*!
* \brief Clears the console
*
* Clears the console history and input
*/
void Console::Clear()
{
m_historyLines.clear();
m_history->Clear();
m_history->Resize(m_history->GetPreferredSize());
m_historyArea->Resize(m_historyArea->GetSize());
m_input->SetText(s_inputPrefix);
}
/*!
* \brief Clears the console focus
*
* Clear console input widget focus (if owned)
*/
void Console::ClearFocus()
{
m_input->ClearFocus();
}
/*!
* \brief Sets the character size
*
* \param size Size of the font
*/
void Console::SetCharacterSize(unsigned int size)
{
m_characterSize = size;
m_history->SetCharacterSize(size);
m_input->SetCharacterSize(size);
Layout();
}
/*!
* \brief Give the console input focus
*
*/
void Console::SetFocus()
{
m_input->SetFocus();
}
/*!
* \brief Sets the text font
*
* \param font Reference to a valid font
*
* \remark Produces a NazaraAssert if font is invalid or null
*/
void Console::SetTextFont(Nz::FontRef font)
{
NazaraAssert(font && font->IsValid(), "Invalid font");
m_defaultFont = std::move(font);
m_history->SetTextFont(m_defaultFont);
m_input->SetTextFont(m_defaultFont);
Layout();
}
/*!
* \brief Performs this action when an input is added to the console
*/
void Console::ExecuteInput(const AbstractTextAreaWidget* textArea, bool* ignoreDefaultAction)
{
NazaraAssert(textArea == m_input, "Unexpected signal from an other text area");
*ignoreDefaultAction = true;
Nz::String input = m_input->GetText();
Nz::String inputCmd = input.SubString(s_inputPrefixSize);
m_input->SetText(s_inputPrefix);
if (m_commandHistory.empty() || m_commandHistory.back() != inputCmd)
m_commandHistory.push_back(inputCmd);
m_historyPosition = m_commandHistory.size();
AddLine(input); //< With the input prefix
OnCommand(this, inputCmd);
}
/*!
* \brief Places the console according to its layout
*/
void Console::Layout()
{
Nz::Vector2f origin = Nz::Vector2f(GetPosition());
const Nz::Vector2f& size = GetSize();
unsigned int lineHeight = m_defaultFont->GetSizeInfo(m_characterSize).lineHeight;
float historyHeight = size.y - lineHeight;
m_historyArea->SetPosition(origin.x, origin.y);
m_historyArea->Resize({ size.x, historyHeight - 4.f });
m_input->Resize({size.x, size.y - historyHeight});
m_input->SetPosition(origin.x, origin.y + historyHeight);
}
}

View File

@ -1,68 +0,0 @@
// This file was automatically generated on 26 May 2014 at 01:05:31
#include <NDK/Lua/LuaBinding.hpp>
namespace Ndk
{
/*!
* \ingroup NDK
* \class Ndk::LuaBinding
* \brief NDK class that represents the binding between the engine & the SDK with the Lua scripting
*/
/*!
* \brief Binds modules to Lua
*/
LuaBinding::LuaBinding()
{
core = LuaBinding_Base::BindCore(*this);
math = LuaBinding_Base::BindMath(*this);
network = LuaBinding_Base::BindNetwork(*this);
utility = LuaBinding_Base::BindUtility(*this);
#ifndef NDK_SERVER
audio = LuaBinding_Base::BindAudio(*this);
renderer = LuaBinding_Base::BindRenderer(*this);
graphics = LuaBinding_Base::BindGraphics(*this);
platform = LuaBinding_Base::BindPlatform(*this);
#endif
sdk = LuaBinding_Base::BindSDK(*this);
}
/*!
* \brief Registers the classes that will be used by the Lua instance
*
* \param instance Lua instance that will interact with the engine & SDK
*/
void LuaBinding::RegisterClasses(Nz::LuaState& state)
{
core->Register(state);
math->Register(state);
network->Register(state);
sdk->Register(state);
utility->Register(state);
#ifndef NDK_SERVER
audio->Register(state);
graphics->Register(state);
renderer->Register(state);
platform->Register(state);
#endif
// ComponentType (fake enumeration to expose component indexes)
state.PushTable(0, m_componentBinding.size());
{
for (const ComponentBinding& entry : m_componentBinding)
{
if (entry.name.IsEmpty())
continue;
state.PushField(entry.name, entry.index);
}
}
state.SetGlobal("ComponentType");
}
}

View File

@ -1,198 +0,0 @@
// This file was automatically generated on 26 May 2014 at 01:05:31
#include <NDK/Lua/LuaBinding_Audio.hpp>
#include <Nazara/Core/MemoryHelper.hpp>
#include <NDK/LuaAPI.hpp>
namespace Ndk
{
std::unique_ptr<LuaBinding_Base> LuaBinding_Base::BindAudio(LuaBinding& binding)
{
return std::make_unique<LuaBinding_Audio>(binding);
}
LuaBinding_Audio::LuaBinding_Audio(LuaBinding& binding) :
LuaBinding_Base(binding)
{
/*********************************** Nz::SoundEmitter **********************************/
soundEmitter.Reset("SoundEmitter");
{
soundEmitter.BindMethod("EnableLooping", &Nz::SoundEmitter::EnableLooping);
soundEmitter.BindMethod("EnableSpatialization", &Nz::SoundEmitter::EnableSpatialization);
soundEmitter.BindMethod("GetAttenuation", &Nz::SoundEmitter::GetAttenuation);
soundEmitter.BindMethod("GetDuration", &Nz::SoundEmitter::GetDuration);
soundEmitter.BindMethod("GetMinDistance", &Nz::SoundEmitter::GetMinDistance);
soundEmitter.BindMethod("GetPitch", &Nz::SoundEmitter::GetPitch);
soundEmitter.BindMethod("GetPlayingOffset", &Nz::SoundEmitter::GetPlayingOffset);
soundEmitter.BindMethod("GetPosition", &Nz::Sound::GetPosition);
soundEmitter.BindMethod("GetStatus", &Nz::SoundEmitter::GetStatus);
soundEmitter.BindMethod("GetVelocity", &Nz::Sound::GetVelocity);
soundEmitter.BindMethod("GetVolume", &Nz::SoundEmitter::GetVolume);
soundEmitter.BindMethod("IsLooping", &Nz::SoundEmitter::IsLooping);
soundEmitter.BindMethod("IsSpatialized", &Nz::SoundEmitter::IsSpatialized);
soundEmitter.BindMethod("Pause", &Nz::SoundEmitter::Pause);
soundEmitter.BindMethod("Play", &Nz::SoundEmitter::Play);
soundEmitter.BindMethod("SetAttenuation", &Nz::SoundEmitter::SetAttenuation);
soundEmitter.BindMethod("SetMinDistance", &Nz::SoundEmitter::SetMinDistance);
soundEmitter.BindMethod("SetPitch", &Nz::SoundEmitter::SetPitch);
soundEmitter.BindMethod("SetPosition", (void(Nz::SoundEmitter::*)(const Nz::Vector3f&)) &Nz::SoundEmitter::SetPosition);
soundEmitter.BindMethod("SetVelocity", (void(Nz::SoundEmitter::*)(const Nz::Vector3f&)) &Nz::SoundEmitter::SetVelocity);
soundEmitter.BindMethod("SetVolume", &Nz::SoundEmitter::SetVolume);
soundEmitter.BindMethod("Stop", &Nz::SoundEmitter::Stop);
}
/*********************************** Nz::Music **********************************/
music.Reset("Music");
{
music.Inherit(soundEmitter);
music.BindDefaultConstructor();
//musicClass.SetMethod("Create", &Nz::Music::Create);
//musicClass.SetMethod("Destroy", &Nz::Music::Destroy);
music.BindMethod("EnableLooping", &Nz::Music::EnableLooping);
music.BindMethod("GetDuration", &Nz::Music::GetDuration);
music.BindMethod("GetFormat", &Nz::Music::GetFormat);
music.BindMethod("GetPlayingOffset", &Nz::Music::GetPlayingOffset);
music.BindMethod("GetSampleCount", &Nz::Music::GetSampleCount);
music.BindMethod("GetSampleRate", &Nz::Music::GetSampleRate);
music.BindMethod("GetStatus", &Nz::Music::GetStatus);
music.BindMethod("IsLooping", &Nz::Music::IsLooping);
music.BindMethod("OpenFromFile", &Nz::Music::OpenFromFile, Nz::SoundStreamParams());
music.BindMethod("Pause", &Nz::Music::Pause);
music.BindMethod("Play", &Nz::Music::Play);
music.BindMethod("SetPlayingOffset", &Nz::Music::SetPlayingOffset);
music.BindMethod("Stop", &Nz::Music::Stop);
// Manual
music.BindMethod("__tostring", [] (Nz::LuaState& lua, Nz::Music& instance, std::size_t /*argumentCount*/) -> int
{
Nz::StringStream ss("Music(");
ss << instance.GetFilePath() << ')';
lua.PushString(ss);
return 1;
});
}
/*********************************** Nz::Sound **********************************/
sound.Reset("Sound");
{
sound.Inherit(soundEmitter);
sound.BindDefaultConstructor();
sound.BindMethod("GetBuffer", &Nz::Sound::GetBuffer);
sound.BindMethod("IsPlayable", &Nz::Sound::IsPlayable);
sound.BindMethod("IsPlaying", &Nz::Sound::IsPlaying);
sound.BindMethod("LoadFromFile", &Nz::Sound::LoadFromFile, Nz::SoundBufferParams());
sound.BindMethod("SetPlayingOffset", &Nz::Sound::SetPlayingOffset);
// Manual
sound.BindMethod("__tostring", [] (Nz::LuaState& lua, Nz::Sound& instance, std::size_t /*argumentCount*/) -> int
{
Nz::StringStream ss("Sound(");
if (const Nz::SoundBuffer* buffer = instance.GetBuffer())
ss << buffer;
ss << ')';
lua.PushString(ss);
return 1;
});
}
/*********************************** Nz::SoundBuffer **********************************/
soundBuffer.Reset("SoundBuffer");
{
soundBuffer.SetConstructor([] (Nz::LuaState& lua, Nz::SoundBufferRef* instance, std::size_t argumentCount)
{
NazaraUnused(lua);
NazaraUnused(argumentCount);
Nz::PlacementNew(instance, Nz::SoundBuffer::New());
return true;
});
soundBuffer.BindMethod("Destroy", &Nz::SoundBuffer::Destroy);
soundBuffer.BindMethod("GetDuration", &Nz::SoundBuffer::GetDuration);
soundBuffer.BindMethod("GetFormat", &Nz::SoundBuffer::GetFormat);
soundBuffer.BindMethod("GetSampleCount", &Nz::SoundBuffer::GetSampleCount);
soundBuffer.BindMethod("GetSampleRate", &Nz::SoundBuffer::GetSampleRate);
soundBuffer.BindMethod("IsValid", &Nz::SoundBuffer::IsValid);
soundBuffer.BindStaticMethod("LoadFromFile", &Nz::SoundBuffer::LoadFromFile, Nz::SoundBufferParams());
soundBuffer.BindStaticMethod("IsFormatSupported", &Nz::SoundBuffer::IsFormatSupported);
// Manual
soundBuffer.BindMethod("Create", [] (Nz::LuaState& lua, Nz::SoundBufferRef& instance, std::size_t /*argumentCount*/) -> int
{
int index = 2;
Nz::AudioFormat format = lua.Check<Nz::AudioFormat>(&index);
unsigned int sampleCount = lua.Check<unsigned int>(&index);
unsigned int sampleRate = lua.Check<unsigned int>(&index);
std::size_t bufferSize = 0;
const char* buffer = lua.CheckString(index, &bufferSize);
lua.ArgCheck(buffer && bufferSize >= sampleCount * sizeof(Nz::Int16), index, "Invalid buffer");
lua.PushBoolean(instance->Create(format, sampleCount, sampleRate, reinterpret_cast<const Nz::Int16*>(buffer)));
return 1;
});
soundBuffer.BindMethod("GetSamples", [] (Nz::LuaState& lua, Nz::SoundBufferRef& instance, std::size_t /*argumentCount*/) -> int
{
lua.PushString(reinterpret_cast<const char*>(instance->GetSamples()), instance->GetSampleCount() * sizeof(Nz::Int16));
return 1;
});
soundBuffer.BindMethod("__tostring", [] (Nz::LuaState& lua, Nz::SoundBufferRef& instance, std::size_t /*argumentCount*/) -> int
{
Nz::StringStream ss("SoundBuffer(");
if (instance->IsValid())
{
Nz::String filePath = instance->GetFilePath();
if (!filePath.IsEmpty())
ss << "File: " << filePath << ", ";
ss << "Duration: " << instance->GetDuration() / 1000.f << "s";
}
ss << ')';
lua.PushString(ss);
return 1;
});
}
}
/*!
* \brief Registers the classes that will be used by the Lua instance
*
* \param instance Lua instance that will interact with the Audio classes
*/
void LuaBinding_Audio::Register(Nz::LuaState& state)
{
music.Register(state);
sound.Register(state);
soundBuffer.Register(state);
soundEmitter.Register(state);
}
}

View File

@ -1,13 +0,0 @@
// This file was automatically generated on 26 May 2014 at 01:05:31
#include <NDK/Lua/LuaBinding_Base.hpp>
namespace Ndk
{
LuaBinding_Base::LuaBinding_Base(LuaBinding& binding) :
m_binding(binding)
{
}
LuaBinding_Base::~LuaBinding_Base() = default;
}

View File

@ -1,355 +0,0 @@
// This file was automatically generated on 26 May 2014 at 01:05:31
#include <NDK/Lua/LuaBinding_Core.hpp>
#include <Nazara/Core/MemoryHelper.hpp>
#include <NDK/LuaAPI.hpp>
namespace Ndk
{
std::unique_ptr<LuaBinding_Base> LuaBinding_Base::BindCore(LuaBinding& binding)
{
return std::make_unique<LuaBinding_Core>(binding);
}
LuaBinding_Core::LuaBinding_Core(LuaBinding& binding) :
LuaBinding_Base(binding)
{
/*********************************** Nz::Stream ***********************************/
stream.Reset("Stream");
{
stream.BindMethod("EnableTextMode", &Nz::Stream::EnableTextMode);
stream.BindMethod("Flush", &Nz::Stream::Flush);
stream.BindMethod("GetCursorPos", &Nz::Stream::GetCursorPos);
stream.BindMethod("GetDirectory", &Nz::Stream::GetDirectory);
stream.BindMethod("GetPath", &Nz::Stream::GetPath);
stream.BindMethod("GetOpenMode", &Nz::Stream::GetOpenMode);
stream.BindMethod("GetStreamOptions", &Nz::Stream::GetStreamOptions);
stream.BindMethod("GetSize", &Nz::Stream::GetSize);
stream.BindMethod("ReadLine", &Nz::Stream::ReadLine, 0U);
stream.BindMethod("IsReadable", &Nz::Stream::IsReadable);
stream.BindMethod("IsSequential", &Nz::Stream::IsSequential);
stream.BindMethod("IsTextModeEnabled", &Nz::Stream::IsTextModeEnabled);
stream.BindMethod("IsWritable", &Nz::Stream::IsWritable);
stream.BindMethod("SetCursorPos", &Nz::Stream::SetCursorPos);
stream.BindMethod("Read", [] (Nz::LuaState& lua, Nz::Stream& instance, std::size_t /*argumentCount*/) -> int {
int argIndex = 2;
std::size_t length = lua.Check<std::size_t>(&argIndex);
std::unique_ptr<char[]> buffer(new char[length]);
std::size_t readLength = instance.Read(buffer.get(), length);
lua.PushString(Nz::String(buffer.get(), readLength));
return 1;
});
stream.BindMethod("Write", [] (Nz::LuaState& lua, Nz::Stream& instance, std::size_t /*argumentCount*/) -> int {
int argIndex = 2;
std::size_t bufferSize = 0;
const char* buffer = lua.CheckString(argIndex, &bufferSize);
if (instance.IsTextModeEnabled())
lua.Push(instance.Write(Nz::String(buffer, bufferSize)));
else
lua.Push(instance.Write(buffer, bufferSize));
return 1;
});
}
/*********************************** Nz::Clock **********************************/
clock.Reset("Clock");
{
clock.SetConstructor([] (Nz::LuaState& lua, Nz::Clock* instance, std::size_t argumentCount)
{
std::size_t argCount = std::min<std::size_t>(argumentCount, 2U);
int argIndex = 2;
switch (argCount)
{
case 0:
Nz::PlacementNew(instance);
return true;
case 1:
{
Nz::Int64 startingValue = lua.Check<Nz::Int64>(&argIndex, 0);
Nz::PlacementNew(instance, startingValue);
return true;
}
case 2:
{
Nz::Int64 startingValue = lua.Check<Nz::Int64>(&argIndex, 0);
bool paused = lua.Check<bool>(&argIndex, false);
Nz::PlacementNew(instance, startingValue, paused);
return true;
}
}
lua.Error("No matching overload for Clock constructor");
return false;
});
clock.BindMethod("GetMicroseconds", &Nz::Clock::GetMicroseconds);
clock.BindMethod("GetMilliseconds", &Nz::Clock::GetMilliseconds);
clock.BindMethod("GetSeconds", &Nz::Clock::GetSeconds);
clock.BindMethod("IsPaused", &Nz::Clock::IsPaused);
clock.BindMethod("Pause", &Nz::Clock::Pause);
clock.BindMethod("Restart", &Nz::Clock::Restart);
clock.BindMethod("Unpause", &Nz::Clock::Unpause);
// Manual
clock.BindMethod("__tostring", [] (Nz::LuaState& lua, Nz::Clock& instance, std::size_t /*argumentCount*/) -> int {
Nz::StringStream ss("Clock(Elapsed: ");
ss << instance.GetSeconds();
ss << "s, Paused: ";
ss << instance.IsPaused();
ss << ')';
lua.PushString(ss);
return 1;
});
}
/********************************* Nz::Directory ********************************/
directory.Reset("Directory");
{
directory.SetConstructor([] (Nz::LuaState& lua, Nz::Directory* instance, std::size_t argumentCount)
{
std::size_t argCount = std::min<std::size_t>(argumentCount, 1U);
int argIndex = 2;
switch (argCount)
{
case 0:
Nz::PlacementNew(instance);
return true;
case 1:
Nz::PlacementNew(instance, lua.Check<Nz::String>(&argIndex));
return true;
}
return false;
});
directory.BindMethod("Close", &Nz::Directory::Close);
directory.BindMethod("Exists", &Nz::Directory::Exists);
directory.BindMethod("GetPath", &Nz::Directory::GetPath);
directory.BindMethod("GetPattern", &Nz::Directory::GetPattern);
directory.BindMethod("GetResultName", &Nz::Directory::GetResultName);
directory.BindMethod("GetResultPath", &Nz::Directory::GetResultPath);
directory.BindMethod("GetResultSize", &Nz::Directory::GetResultSize);
directory.BindMethod("IsOpen", &Nz::Directory::IsOpen);
directory.BindMethod("IsResultDirectory", &Nz::Directory::IsResultDirectory);
directory.BindMethod("NextResult", &Nz::Directory::NextResult, true);
directory.BindMethod("Open", &Nz::Directory::Open);
directory.BindMethod("SetPath", &Nz::Directory::SetPath);
directory.BindMethod("SetPattern", &Nz::Directory::SetPattern);
directory.BindStaticMethod("Copy", Nz::Directory::Copy);
directory.BindStaticMethod("Create", Nz::Directory::Create);
directory.BindStaticMethod("Exists", Nz::Directory::Exists);
directory.BindStaticMethod("GetCurrent", Nz::Directory::GetCurrent);
directory.BindStaticMethod("Remove", Nz::Directory::Remove);
directory.BindStaticMethod("SetCurrent", Nz::Directory::SetCurrent);
// Manual
directory.BindMethod("__tostring", [] (Nz::LuaState& lua, Nz::Directory& instance, std::size_t /*argumentCount*/) -> int {
Nz::StringStream ss("Directory(");
ss << instance.GetPath();
ss << ')';
lua.PushString(ss);
return 1;
});
}
/*********************************** Nz::File ***********************************/
file.Reset("File");
{
file.Inherit(stream);
file.SetConstructor([] (Nz::LuaState& lua, Nz::File* instance, std::size_t argumentCount)
{
std::size_t argCount = std::min<std::size_t>(argumentCount, 1U);
int argIndex = 2;
switch (argCount)
{
case 0:
Nz::PlacementNew(instance);
return true;
case 1:
{
Nz::String filePath = lua.Check<Nz::String>(&argIndex);
Nz::PlacementNew(instance, filePath);
return true;
}
case 2:
{
Nz::String filePath = lua.Check<Nz::String>(&argIndex);
Nz::UInt32 openMode = lua.Check<Nz::UInt32>(&argIndex);
Nz::PlacementNew(instance, filePath, openMode);
return true;
}
}
lua.Error("No matching overload for File constructor");
return false;
});
file.BindMethod("Close", &Nz::File::Close);
file.BindMethod("Copy", &Nz::File::Copy);
file.BindMethod("Delete", &Nz::File::Delete);
file.BindMethod("EndOfFile", &Nz::File::EndOfFile);
file.BindMethod("Exists", &Nz::File::Exists);
file.BindMethod("GetCreationTime", &Nz::File::GetCreationTime);
file.BindMethod("GetFileName", &Nz::File::GetFileName);
file.BindMethod("GetLastAccessTime", &Nz::File::GetLastAccessTime);
file.BindMethod("GetLastWriteTime", &Nz::File::GetLastWriteTime);
file.BindMethod("IsOpen", &Nz::File::IsOpen);
file.BindMethod("Rename", &Nz::File::GetLastWriteTime);
file.BindMethod("GetLastWriteTime", &Nz::File::GetLastWriteTime);
file.BindMethod("SetFile", &Nz::File::GetLastWriteTime);
file.BindStaticMethod("AbsolutePath", &Nz::File::AbsolutePath);
file.BindStaticMethod("ComputeHash", (Nz::ByteArray(*)(Nz::HashType, const Nz::String&)) &Nz::File::ComputeHash);
file.BindStaticMethod("Copy", &Nz::File::Copy);
file.BindStaticMethod("Delete", &Nz::File::Delete);
file.BindStaticMethod("Exists", &Nz::File::Exists);
//fileClass.SetStaticMethod("GetCreationTime", &Nz::File::GetCreationTime);
file.BindStaticMethod("GetDirectory", &Nz::File::GetDirectory);
//fileClass.SetStaticMethod("GetLastAccessTime", &Nz::File::GetLastAccessTime);
//fileClass.SetStaticMethod("GetLastWriteTime", &Nz::File::GetLastWriteTime);
file.BindStaticMethod("GetSize", &Nz::File::GetSize);
file.BindStaticMethod("IsAbsolute", &Nz::File::IsAbsolute);
file.BindStaticMethod("NormalizePath", &Nz::File::NormalizePath);
file.BindStaticMethod("NormalizeSeparators", &Nz::File::NormalizeSeparators);
file.BindStaticMethod("Rename", &Nz::File::Rename);
// Manual
file.BindMethod("Open", [] (Nz::LuaState& lua, Nz::File& instance, std::size_t argumentCount) -> int
{
std::size_t argCount = std::min<std::size_t>(argumentCount, 2U);
int argIndex = 2;
switch (argCount)
{
case 0:
case 1:
return lua.Push(instance.Open(lua.Check<Nz::UInt32>(&argIndex, Nz::OpenMode_NotOpen)));
case 2:
{
Nz::String filePath = lua.Check<Nz::String>(&argIndex);
Nz::UInt32 openMode = lua.Check<Nz::UInt32>(&argIndex, Nz::OpenMode_NotOpen);
return lua.Push(instance.Open(filePath, openMode));
}
}
lua.Error("No matching overload for method Open");
return 0;
});
file.BindMethod("SetCursorPos", [] (Nz::LuaState& lua, Nz::File& instance, std::size_t argumentCount) -> int
{
std::size_t argCount = std::min<std::size_t>(argumentCount, 2U);
int argIndex = 2;
switch (argCount)
{
case 1:
return lua.Push(instance.SetCursorPos(lua.Check<Nz::UInt64>(&argIndex)));
case 2:
{
Nz::CursorPosition curPos = lua.Check<Nz::CursorPosition>(&argIndex);
Nz::Int64 offset = lua.Check<Nz::Int64>(&argIndex);
return lua.Push(instance.SetCursorPos(curPos, offset));
}
}
lua.Error("No matching overload for method SetCursorPos");
return 0;
});
file.BindMethod("__tostring", [] (Nz::LuaState& lua, Nz::File& instance, std::size_t /*argumentCount*/) -> int {
Nz::StringStream ss("File(");
if (instance.IsOpen())
ss << "Path: " << instance.GetPath();
ss << ')';
lua.PushString(ss);
return 1;
});
}
}
/*!
* \brief Registers the classes that will be used by the Lua instance
*
* \param instance Lua instance that will interact with the Core classes
*/
void LuaBinding_Core::Register(Nz::LuaState& state)
{
// Classes
clock.Register(state);
directory.Register(state);
file.Register(state);
stream.Register(state);
// Enums
// Nz::CursorPosition
static_assert(Nz::CursorPosition_Max + 1 == 3, "Nz::CursorPosition has been updated but change was not reflected to Lua binding");
state.PushTable(0, 3);
{
state.PushField("AtBegin", Nz::CursorPosition_AtBegin);
state.PushField("AtCurrent", Nz::CursorPosition_AtCurrent);
state.PushField("AtEnd", Nz::CursorPosition_AtEnd);
}
state.SetGlobal("CursorPosition");
// Nz::HashType
static_assert(Nz::HashType_Max + 1 == 10, "Nz::HashType has been updated but change was not reflected to Lua binding");
state.PushTable(0, 10);
{
state.PushField("CRC32", Nz::HashType_CRC32);
state.PushField("CRC64", Nz::HashType_CRC64);
state.PushField("Fletcher16", Nz::HashType_Fletcher16);
state.PushField("MD5", Nz::HashType_MD5);
state.PushField("SHA1", Nz::HashType_SHA1);
state.PushField("SHA224", Nz::HashType_SHA224);
state.PushField("SHA256", Nz::HashType_SHA256);
state.PushField("SHA384", Nz::HashType_SHA384);
state.PushField("SHA512", Nz::HashType_SHA512);
state.PushField("Whirlpool", Nz::HashType_Whirlpool);
}
state.SetGlobal("HashType");
// Nz::OpenMode
static_assert(Nz::OpenMode_Max + 1 == 8, "Nz::OpenModeFlags has been updated but change was not reflected to Lua binding");
state.PushTable(0, Nz::OpenMode_Max + 1);
{
state.PushField("Append", Nz::OpenMode_Append);
state.PushField("NotOpen", Nz::OpenMode_NotOpen);
state.PushField("Lock", Nz::OpenMode_Lock);
state.PushField("ReadOnly", Nz::OpenMode_ReadOnly);
state.PushField("ReadWrite", Nz::OpenMode_ReadWrite);
state.PushField("Text", Nz::OpenMode_Text);
state.PushField("Truncate", Nz::OpenMode_Truncate);
state.PushField("WriteOnly", Nz::OpenMode_WriteOnly);
}
state.SetGlobal("OpenMode");
}
}

View File

@ -1,498 +0,0 @@
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequisites.hpp
#include <NDK/Lua/LuaBinding_Graphics.hpp>
#include <NDK/LuaAPI.hpp>
namespace Ndk
{
std::unique_ptr<LuaBinding_Base> LuaBinding_Base::BindGraphics(LuaBinding& binding)
{
return std::make_unique<LuaBinding_Graphics>(binding);
}
LuaBinding_Graphics::LuaBinding_Graphics(LuaBinding& binding) :
LuaBinding_Base(binding)
{
/*********************************** Nz::AbstractViewer ***********************************/
abstractViewer.Reset("AbstractViewer");
{
abstractViewer.BindMethod("GetAspectRatio", &Nz::AbstractViewer::GetAspectRatio);
abstractViewer.BindMethod("GetEyePosition", &Nz::AbstractViewer::GetEyePosition);
abstractViewer.BindMethod("GetForward", &Nz::AbstractViewer::GetForward);
//abstractViewer.BindMethod("GetFrustum", &Nz::AbstractViewer::GetFrustum);
abstractViewer.BindMethod("GetProjectionMatrix", &Nz::AbstractViewer::GetProjectionMatrix);
//abstractViewer.BindMethod("GetTarget", &Nz::AbstractViewer::GetTarget);
abstractViewer.BindMethod("GetViewMatrix", &Nz::AbstractViewer::GetViewMatrix);
abstractViewer.BindMethod("GetViewport", &Nz::AbstractViewer::GetViewport);
abstractViewer.BindMethod("GetZFar", &Nz::AbstractViewer::GetZFar);
abstractViewer.BindMethod("GetZNear", &Nz::AbstractViewer::GetZNear);
}
/*********************************** Nz::InstancedRenderable ***********************************/
instancedRenderable.Reset("InstancedRenderable");
{
instancedRenderable.BindMethod("GetMaterial", [] (Nz::LuaState& lua, Nz::InstancedRenderable* instance, std::size_t argumentCount) -> int
{
std::size_t argCount = std::min<std::size_t>(argumentCount, 2U);
switch (argCount)
{
case 0:
case 1:
{
int argIndex = 2;
std::size_t matIndex(lua.Check<std::size_t>(&argIndex, 0));
return lua.Push(instance->GetMaterial(matIndex));
}
case 2:
{
int argIndex = 2;
std::size_t skinIndex(lua.Check<std::size_t>(&argIndex));
std::size_t matIndex(lua.Check<std::size_t>(&argIndex));
return lua.Push(instance->GetMaterial(skinIndex, matIndex));
}
}
lua.Error("No matching overload for method GetMaterial");
return 0;
});
instancedRenderable.BindMethod("GetMaterialCount", &Nz::InstancedRenderable::GetMaterialCount);
instancedRenderable.BindMethod("GetSkin", &Nz::InstancedRenderable::GetSkin);
instancedRenderable.BindMethod("GetSkinCount", &Nz::InstancedRenderable::GetSkinCount);
instancedRenderable.BindMethod("SetSkin", &Nz::InstancedRenderable::SetSkin);
instancedRenderable.BindMethod("SetSkinCount", &Nz::InstancedRenderable::SetSkinCount);
}
/*********************************** Nz::Material ***********************************/
material.Reset("Material");
{
material.SetConstructor([] (Nz::LuaState& lua, Nz::MaterialRef* instance, std::size_t argumentCount)
{
switch (argumentCount)
{
case 0:
Nz::PlacementNew(instance, Nz::Material::New());
return true;
case 1:
{
int argIndex = 1;
if (lua.IsOfType(argIndex, "MaterialPipeline"))
{
Nz::PlacementNew(instance, Nz::Material::New(*static_cast<Nz::MaterialPipelineRef*>(lua.ToUserdata(argIndex))));
return true;
}
else if (lua.IsOfType(argIndex, "Material"))
{
Nz::PlacementNew(instance, Nz::Material::New(**static_cast<Nz::MaterialRef*>(lua.ToUserdata(argIndex))));
return true;
}
else
{
Nz::PlacementNew(instance, Nz::Material::New(lua.Check<Nz::String>(&argIndex)));
return true;
}
}
}
lua.Error("No matching overload for constructor");
return false;
});
material.BindMethod("Configure", [] (Nz::LuaState& lua, Nz::MaterialRef& instance, std::size_t /*argumentCount*/) -> int
{
int argIndex = 2;
if (lua.IsOfType(argIndex, "MaterialPipeline"))
{
instance->Configure(*static_cast<Nz::MaterialPipelineRef*>(lua.ToUserdata(argIndex)));
return 0;
}
else
{
lua.Push(instance->Configure(lua.Check<Nz::String>(&argIndex)));
return 1;
}
});
material.BindMethod("EnableAlphaTest", &Nz::Material::EnableAlphaTest);
material.BindMethod("EnableBlending", &Nz::Material::EnableBlending);
material.BindMethod("EnableColorWrite", &Nz::Material::EnableColorWrite);
material.BindMethod("EnableDepthBuffer", &Nz::Material::EnableDepthBuffer);
material.BindMethod("EnableDepthSorting", &Nz::Material::EnableDepthSorting);
material.BindMethod("EnableDepthWrite", &Nz::Material::EnableDepthWrite);
material.BindMethod("EnableFaceCulling", &Nz::Material::EnableFaceCulling);
material.BindMethod("EnableReflectionMapping", &Nz::Material::EnableReflectionMapping);
material.BindMethod("EnableScissorTest", &Nz::Material::EnableScissorTest);
material.BindMethod("EnableShadowCasting", &Nz::Material::EnableShadowCasting);
material.BindMethod("EnableShadowReceive", &Nz::Material::EnableShadowReceive);
material.BindMethod("EnableStencilTest", &Nz::Material::EnableStencilTest);
material.BindMethod("EnsurePipelineUpdate", &Nz::Material::EnsurePipelineUpdate);
material.BindMethod("GetAlphaMap", &Nz::Material::GetAlphaMap);
material.BindMethod("GetAlphaThreshold", &Nz::Material::GetAlphaThreshold);
material.BindMethod("GetAmbientColor", &Nz::Material::GetAmbientColor);
material.BindMethod("GetDepthFunc", &Nz::Material::GetDepthFunc);
material.BindMethod("GetDepthMaterial", &Nz::Material::GetDepthMaterial);
material.BindMethod("GetDiffuseColor", &Nz::Material::GetDiffuseColor);
material.BindMethod("GetDiffuseMap", &Nz::Material::GetDiffuseMap);
//material.BindMethod("GetDiffuseSampler", &Nz::Material::GetDiffuseSampler);
material.BindMethod("GetDstBlend", &Nz::Material::GetDstBlend);
material.BindMethod("GetEmissiveMap", &Nz::Material::GetEmissiveMap);
material.BindMethod("GetFaceCulling", &Nz::Material::GetFaceCulling);
material.BindMethod("GetFaceFilling", &Nz::Material::GetFaceFilling);
material.BindMethod("GetHeightMap", &Nz::Material::GetHeightMap);
material.BindMethod("GetLineWidth", &Nz::Material::GetLineWidth);
material.BindMethod("GetNormalMap", &Nz::Material::GetNormalMap);
//material.BindMethod("GetPipeline", &Nz::Material::GetPipeline);
//material.BindMethod("GetPipelineInfo", &Nz::Material::GetPipelineInfo);
material.BindMethod("GetPointSize", &Nz::Material::GetPointSize);
material.BindMethod("GetReflectionMode", &Nz::Material::GetReflectionMode);
//material.BindMethod("GetShader", &Nz::Material::GetShader);
material.BindMethod("GetShininess", &Nz::Material::GetShininess);
material.BindMethod("GetSpecularColor", &Nz::Material::GetSpecularColor);
material.BindMethod("GetSpecularMap", &Nz::Material::GetSpecularMap);
//material.BindMethod("GetSpecularSampler", &Nz::Material::GetSpecularSampler);
material.BindMethod("GetSrcBlend", &Nz::Material::GetSrcBlend);
material.BindMethod("HasAlphaMap", &Nz::Material::HasAlphaMap);
material.BindMethod("HasDepthMaterial", &Nz::Material::HasDepthMaterial);
material.BindMethod("HasDiffuseMap", &Nz::Material::HasDiffuseMap);
material.BindMethod("HasEmissiveMap", &Nz::Material::HasEmissiveMap);
material.BindMethod("HasHeightMap", &Nz::Material::HasHeightMap);
material.BindMethod("HasNormalMap", &Nz::Material::HasNormalMap);
material.BindMethod("HasSpecularMap", &Nz::Material::HasSpecularMap);
material.BindMethod("IsAlphaTestEnabled", &Nz::Material::IsAlphaTestEnabled);
material.BindMethod("IsBlendingEnabled", &Nz::Material::IsBlendingEnabled);
material.BindMethod("IsColorWriteEnabled", &Nz::Material::IsColorWriteEnabled);
material.BindMethod("IsDepthBufferEnabled", &Nz::Material::IsDepthBufferEnabled);
material.BindMethod("IsDepthSortingEnabled", &Nz::Material::IsDepthSortingEnabled);
material.BindMethod("IsDepthWriteEnabled", &Nz::Material::IsDepthWriteEnabled);
material.BindMethod("IsFaceCullingEnabled", &Nz::Material::IsFaceCullingEnabled);
material.BindMethod("IsReflectionMappingEnabled", &Nz::Material::IsReflectionMappingEnabled);
material.BindMethod("IsScissorTestEnabled", &Nz::Material::IsScissorTestEnabled);
material.BindMethod("IsStencilTestEnabled", &Nz::Material::IsStencilTestEnabled);
material.BindMethod("IsShadowCastingEnabled", &Nz::Material::IsShadowCastingEnabled);
material.BindMethod("IsShadowReceiveEnabled", &Nz::Material::IsShadowReceiveEnabled);
material.BindMethod("Reset", &Nz::Material::Reset);
material.BindMethod("SetAlphaThreshold", &Nz::Material::SetAlphaThreshold);
material.BindMethod("SetAmbientColor", &Nz::Material::SetAmbientColor);
material.BindMethod("SetDepthFunc", &Nz::Material::SetDepthFunc);
material.BindMethod("SetDepthFunc", &Nz::Material::SetDepthFunc);
material.BindMethod("SetDepthMaterial", &Nz::Material::SetDepthMaterial);
material.BindMethod("SetDiffuseColor", &Nz::Material::SetDiffuseColor);
//material.BindMethod("SetDiffuseSampler", &Nz::Material::SetDiffuseSampler);
material.BindMethod("SetDstBlend", &Nz::Material::SetDstBlend);
material.BindMethod("SetFaceCulling", &Nz::Material::SetFaceCulling);
material.BindMethod("SetFaceFilling", &Nz::Material::SetFaceFilling);
material.BindMethod("SetLineWidth", &Nz::Material::SetLineWidth);
material.BindMethod("SetPointSize", &Nz::Material::SetPointSize);
material.BindMethod("SetReflectionMode", &Nz::Material::SetReflectionMode);
material.BindMethod("SetShininess", &Nz::Material::SetShininess);
material.BindMethod("SetSpecularColor", &Nz::Material::SetSpecularColor);
material.BindMethod("SetSpecularColor", &Nz::Material::SetSpecularColor);
//material.BindMethod("SetSpecularSampler", &Nz::Material::SetSpecularSampler);
material.BindMethod("SetSrcBlend", &Nz::Material::SetSrcBlend);
material.BindStaticMethod("GetDefault", &Nz::Material::GetDefault);
material.BindStaticMethod("LoadFromFile", &Nz::Material::LoadFromFile, Nz::MaterialParams());
material.BindMethod("SetAlphaMap", [] (Nz::LuaState& lua, Nz::MaterialRef& instance, std::size_t /*argumentCount*/) -> int
{
int argIndex = 2;
if (lua.IsOfType(argIndex, "Texture"))
{
instance->SetAlphaMap(*static_cast<Nz::TextureRef*>(lua.ToUserdata(argIndex)));
return 0;
}
else
return lua.Push(instance->SetAlphaMap(lua.Check<Nz::String>(&argIndex)));
});
material.BindMethod("SetDiffuseMap", [] (Nz::LuaState& lua, Nz::MaterialRef& instance, std::size_t /*argumentCount*/) -> int
{
int argIndex = 2;
if (lua.IsOfType(argIndex, "Texture"))
{
instance->SetDiffuseMap(*static_cast<Nz::TextureRef*>(lua.ToUserdata(argIndex)));
return 0;
}
else
return lua.Push(instance->SetDiffuseMap(lua.Check<Nz::String>(&argIndex)));
});
material.BindMethod("SetEmissiveMap", [] (Nz::LuaState& lua, Nz::MaterialRef& instance, std::size_t /*argumentCount*/) -> int
{
int argIndex = 2;
if (lua.IsOfType(argIndex, "Texture"))
{
instance->SetEmissiveMap(*static_cast<Nz::TextureRef*>(lua.ToUserdata(argIndex)));
return 0;
}
else
return lua.Push(instance->SetEmissiveMap(lua.Check<Nz::String>(&argIndex)));
});
material.BindMethod("SetHeightMap", [] (Nz::LuaState& lua, Nz::MaterialRef& instance, std::size_t /*argumentCount*/) -> int
{
int argIndex = 2;
if (lua.IsOfType(argIndex, "Texture"))
{
instance->SetHeightMap(*static_cast<Nz::TextureRef*>(lua.ToUserdata(argIndex)));
return 0;
}
else
return lua.Push(instance->SetHeightMap(lua.Check<Nz::String>(&argIndex)));
});
material.BindMethod("SetNormalMap", [] (Nz::LuaState& lua, Nz::MaterialRef& instance, std::size_t /*argumentCount*/) -> int
{
int argIndex = 2;
if (lua.IsOfType(argIndex, "Texture"))
{
instance->SetNormalMap(*static_cast<Nz::TextureRef*>(lua.ToUserdata(argIndex)));
return 0;
}
else
return lua.Push(instance->SetNormalMap(lua.Check<Nz::String>(&argIndex)));
});
material.BindMethod("SetShader", [] (Nz::LuaState& lua, Nz::MaterialRef& instance, std::size_t /*argumentCount*/) -> int
{
int argIndex = 2;
if (lua.IsOfType(argIndex, "UberShader"))
{
instance->SetShader(*static_cast<Nz::UberShaderRef*>(lua.ToUserdata(argIndex)));
return 0;
}
else
return lua.Push(instance->SetShader(lua.Check<Nz::String>(&argIndex)));
});
material.BindMethod("SetSpecularMap", [] (Nz::LuaState& lua, Nz::MaterialRef& instance, std::size_t /*argumentCount*/) -> int
{
int argIndex = 2;
if (lua.IsOfType(argIndex, "Texture"))
{
instance->SetSpecularMap(*static_cast<Nz::TextureRef*>(lua.ToUserdata(argIndex)));
return 0;
}
else
return lua.Push(instance->SetSpecularMap(lua.Check<Nz::String>(&argIndex)));
});
}
/*********************************** Nz::Model ***********************************/
model.Reset("Model");
{
model.Inherit<Nz::InstancedRenderableRef>(instancedRenderable, [] (Nz::ModelRef* modelRef) -> Nz::InstancedRenderableRef*
{
return reinterpret_cast<Nz::InstancedRenderableRef*>(modelRef); //TODO: Make a ObjectRefCast
});
model.SetConstructor([] (Nz::LuaState& /*lua*/, Nz::ModelRef* instance, std::size_t /*argumentCount*/)
{
Nz::PlacementNew(instance, Nz::Model::New());
return true;
});
//modelClass.SetMethod("GetMesh", &Nz::Model::GetMesh);
model.BindMethod("IsAnimated", &Nz::Model::IsAnimated);
model.BindMethod("SetMaterial", [] (Nz::LuaState& lua, Nz::Model* instance, std::size_t argumentCount) -> int
{
std::size_t argCount = std::min<std::size_t>(argumentCount, 3U);
switch (argCount)
{
case 2:
{
int argIndex = 2;
if (lua.IsOfType(argIndex, Nz::LuaType_Number))
{
std::size_t matIndex(lua.Check<std::size_t>(&argIndex));
Nz::MaterialRef mat(lua.Check<Nz::MaterialRef>(&argIndex));
instance->SetMaterial(matIndex, std::move(mat));
return 0;
}
else if (lua.IsOfType(argIndex, Nz::LuaType_String))
{
Nz::String subMesh(lua.Check<Nz::String>(&argIndex));
Nz::MaterialRef mat(lua.Check<Nz::MaterialRef>(&argIndex));
instance->SetMaterial(subMesh, std::move(mat));
return 0;
}
break;
}
case 3:
{
int argIndex = 2;
if (lua.IsOfType(argIndex, Nz::LuaType_Number))
{
std::size_t skinIndex(lua.Check<std::size_t>(&argIndex));
std::size_t matIndex(lua.Check<std::size_t>(&argIndex));
Nz::MaterialRef mat(lua.Check<Nz::MaterialRef>(&argIndex));
instance->SetMaterial(skinIndex, matIndex, std::move(mat));
return 0;
}
else if (lua.IsOfType(argIndex, Nz::LuaType_String))
{
std::size_t skinIndex(lua.Check<std::size_t>(&argIndex));
Nz::String subMesh(lua.Check<Nz::String>(&argIndex));
Nz::MaterialRef materialRef(lua.Check<Nz::MaterialRef>(&argIndex));
instance->SetMaterial(skinIndex, subMesh, std::move(materialRef));
return 0;
}
break;
}
}
lua.Error("No matching overload for method SetMaterial");
return 0;
});
//modelClass.SetMethod("SetMesh", &Nz::Model::SetMesh);
//modelClass.SetMethod("SetSequence", &Nz::Model::SetSequence);
model.BindStaticMethod("LoadFromFile", &Nz::Model::LoadFromFile, Nz::ModelParameters());
}
/*********************************** Nz::Sprite ***********************************/
sprite.Reset("Sprite");
{
sprite.Inherit<Nz::InstancedRenderableRef>(instancedRenderable, [] (Nz::SpriteRef* spriteRef) -> Nz::InstancedRenderableRef*
{
return reinterpret_cast<Nz::InstancedRenderableRef*>(spriteRef); //TODO: Make a ObjectRefCast
});
sprite.SetConstructor([] (Nz::LuaState& /*lua*/, Nz::SpriteRef* instance, std::size_t /*argumentCount*/)
{
Nz::PlacementNew(instance, Nz::Sprite::New());
return true;
});
sprite.BindMethod("GetColor", &Nz::Sprite::GetColor);
sprite.BindMethod("GetCornerColor", &Nz::Sprite::GetCornerColor);
sprite.BindMethod("GetOrigin", &Nz::Sprite::GetOrigin);
sprite.BindMethod("GetSize", &Nz::Sprite::GetSize);
sprite.BindMethod("GetTextureCoords", &Nz::Sprite::GetTextureCoords);
sprite.BindMethod("SetColor", &Nz::Sprite::SetColor);
sprite.BindMethod("SetCornerColor", &Nz::Sprite::SetCornerColor);
sprite.BindMethod("SetDefaultMaterial", &Nz::Sprite::SetDefaultMaterial);
sprite.BindMethod("SetOrigin", &Nz::Sprite::SetOrigin);
sprite.BindMethod("SetSize", (void(Nz::Sprite::*)(const Nz::Vector2f&)) &Nz::Sprite::SetSize);
sprite.BindMethod("SetTextureCoords", &Nz::Sprite::SetTextureCoords);
sprite.BindMethod("SetTextureRect", &Nz::Sprite::SetTextureRect);
sprite.BindMethod("SetMaterial", [] (Nz::LuaState& lua, Nz::SpriteRef& instance, std::size_t /*argumentCount*/) -> int
{
int argIndex = 2;
if (lua.IsOfType(argIndex, "Material"))
{
bool resizeSprite = lua.CheckBoolean(argIndex + 1, true);
instance->SetMaterial(*static_cast<Nz::MaterialRef*>(lua.ToUserdata(argIndex)), resizeSprite);
}
else if (lua.IsOfType(argIndex, Nz::LuaType_String))
{
bool resizeSprite = lua.CheckBoolean(argIndex + 1, true);
instance->SetMaterial(lua.ToString(argIndex), resizeSprite);
}
else if (lua.IsOfType(argIndex, Nz::LuaType_Number))
{
std::size_t skinIndex(lua.Check<std::size_t>(&argIndex));
bool resizeSprite = lua.CheckBoolean(argIndex + 1, true);
if (lua.IsOfType(argIndex, "Material"))
instance->SetMaterial(skinIndex, *static_cast<Nz::MaterialRef*>(lua.ToUserdata(argIndex)), resizeSprite);
else
instance->SetMaterial(skinIndex, lua.Check<Nz::String>(&argIndex), resizeSprite);
}
return 0;
});
sprite.BindMethod("SetTexture", [] (Nz::LuaState& lua, Nz::SpriteRef& instance, std::size_t /*argumentCount*/) -> int
{
int argIndex = 2;
if (lua.IsOfType(argIndex, "Texture"))
{
bool resizeSprite = lua.CheckBoolean(argIndex + 1, true);
instance->SetTexture(*static_cast<Nz::TextureRef*>(lua.ToUserdata(argIndex)), resizeSprite);
}
else if (lua.IsOfType(argIndex, Nz::LuaType_String))
{
bool resizeSprite = lua.CheckBoolean(argIndex + 1, true);
instance->SetTexture(lua.ToString(argIndex), resizeSprite);
}
else if (lua.IsOfType(argIndex, Nz::LuaType_Number))
{
std::size_t skinIndex(lua.Check<std::size_t>(&argIndex));
bool resizeSprite = lua.CheckBoolean(argIndex + 1, true);
if (lua.IsOfType(argIndex, "Texture"))
instance->SetTexture(skinIndex, *static_cast<Nz::TextureRef*>(lua.ToUserdata(argIndex)), resizeSprite);
else
instance->SetTexture(skinIndex, lua.Check<Nz::String>(&argIndex), resizeSprite);
}
return 0;
});
}
/*********************************** Nz::SpriteLibrary ***********************************/
spriteLibrary.Reset("SpriteLibrary");
{
spriteLibrary.BindStaticMethod("Get", &Nz::SpriteLibrary::Get);
spriteLibrary.BindStaticMethod("Has", &Nz::SpriteLibrary::Has);
spriteLibrary.BindStaticMethod("Register", &Nz::SpriteLibrary::Register);
spriteLibrary.BindStaticMethod("Query", &Nz::SpriteLibrary::Query);
spriteLibrary.BindStaticMethod("Unregister", &Nz::SpriteLibrary::Unregister);
}
}
/*!
* \brief Registers the classes that will be used by the Lua instance
*
* \param instance Lua instance that will interact with the Graphics classes
*/
void LuaBinding_Graphics::Register(Nz::LuaState& state)
{
abstractViewer.Register(state);
instancedRenderable.Register(state);
material.Register(state);
model.Register(state);
sprite.Register(state);
spriteLibrary.Register(state);
// Nz::ReflectionMode
static_assert(Nz::ReflectionMode_Max + 1 == 3, "Nz::ReflectionMode has been updated but change was not reflected to Lua binding");
state.PushTable(0, 3);
{
state.PushField("Probe", Nz::ReflectionMode_Probe);
state.PushField("RealTime", Nz::ReflectionMode_RealTime);
state.PushField("Skybox", Nz::ReflectionMode_Skybox);
}
state.SetGlobal("ReflectionMode");
}
}

View File

@ -1,986 +0,0 @@
// This file was automatically generated on 26 May 2014 at 01:05:31
#include <NDK/Lua/LuaBinding_Math.hpp>
#include <Nazara/Core/MemoryHelper.hpp>
#include <NDK/LuaAPI.hpp>
#include <cstring>
namespace Ndk
{
std::unique_ptr<LuaBinding_Base> LuaBinding_Base::BindMath(LuaBinding& binding)
{
return std::make_unique<LuaBinding_Math>(binding);
}
LuaBinding_Math::LuaBinding_Math(LuaBinding& binding) :
LuaBinding_Base(binding)
{
/*********************************** Nz::EulerAngles **********************************/
eulerAngles.Reset("EulerAngles");
{
eulerAngles.SetConstructor([] (Nz::LuaState& lua, Nz::EulerAnglesd* instance, std::size_t argumentCount)
{
std::size_t argCount = std::min<std::size_t>(argumentCount, 3U);
switch (argCount)
{
case 0:
Nz::PlacementNew(instance, Nz::EulerAnglesd::Zero());
return true;
case 1:
Nz::PlacementNew(instance, *static_cast<Nz::EulerAnglesd*>(lua.CheckUserdata(1, "EulerAngles")));
return true;
case 3:
Nz::PlacementNew(instance, lua.CheckNumber(1), lua.CheckNumber(2), lua.CheckNumber(3));
return true;
}
lua.Error("No matching overload for EulerAngles constructor");
return false;
});
eulerAngles.BindMethod("Normalize", &Nz::EulerAnglesd::Normalize);
eulerAngles.BindMethod("ToQuaternion", &Nz::EulerAnglesd::ToQuaternion);
eulerAngles.BindMethod("__tostring", &Nz::EulerAnglesd::ToString);
eulerAngles.SetGetter([] (Nz::LuaState& lua, Nz::EulerAnglesd& instance)
{
std::size_t length;
const char* ypr = lua.CheckString(2, &length);
switch (length)
{
case 1:
{
switch (ypr[0])
{
case 'p':
lua.Push(instance.pitch);
return true;
case 'y':
lua.Push(instance.yaw);
return true;
case 'r':
lua.Push(instance.roll);
return true;
}
break;
}
case 3:
{
if (std::memcmp(ypr, "yaw", 3) != 0)
break;
lua.Push(instance.yaw);
return true;
}
case 4:
{
if (std::memcmp(ypr, "roll", 4) != 0)
break;
lua.Push(instance.roll);
return true;
}
case 5:
{
if (std::memcmp(ypr, "pitch", 5) != 0)
break;
lua.Push(instance.pitch);
return true;
}
}
return false;
});
eulerAngles.SetSetter([] (Nz::LuaState& lua, Nz::EulerAnglesd& instance)
{
std::size_t length;
const char* ypr = lua.CheckString(2, &length);
double value = lua.CheckNumber(3);
switch (length)
{
case 1:
{
switch (ypr[0])
{
case 'p':
instance.pitch = value;
return true;
case 'y':
instance.yaw = value;
return true;
case 'r':
instance.roll = value;
return true;
}
break;
}
case 3:
{
if (std::memcmp(ypr, "yaw", 3) != 0)
break;
instance.yaw = value;
return true;
}
case 4:
{
if (std::memcmp(ypr, "roll", 4) != 0)
break;
instance.roll = value;
return true;
}
case 5:
{
if (std::memcmp(ypr, "pitch", 5) != 0)
break;
instance.pitch = value;
return true;
}
}
return false;
});
}
/*********************************** Nz::Matrix4 **********************************/
matrix4d.Reset("Matrix4");
{
matrix4d.SetConstructor([] (Nz::LuaState& lua, Nz::Matrix4d* matrix, std::size_t argumentCount)
{
std::size_t argCount = std::min<std::size_t>(argumentCount, 3U);
switch (argCount)
{
case 0:
Nz::PlacementNew(matrix, Nz::Matrix4d::Zero());
return true;
case 1:
if (lua.IsOfType(1, "Matrix4"))
Nz::PlacementNew(matrix, *static_cast<Nz::Matrix4d*>(lua.ToUserdata(1)));
break;
case 16:
{
double values[16];
for (int i = 0; i < 16; ++i)
values[i] = lua.CheckNumber(i);
Nz::PlacementNew(matrix, values);
return true;
}
}
lua.Error("No matching overload for constructor");
return false;
});
matrix4d.BindMethod("ApplyRotation", &Nz::Matrix4d::ApplyRotation);
matrix4d.BindMethod("ApplyScale", &Nz::Matrix4d::ApplyScale);
matrix4d.BindMethod("ApplyTranslation", &Nz::Matrix4d::ApplyTranslation);
matrix4d.BindMethod("Concatenate", &Nz::Matrix4d::Concatenate);
matrix4d.BindMethod("ConcatenateAffine", &Nz::Matrix4d::ConcatenateAffine);
//matrix4d.BindMethod("GetColumn", &Nz::Matrix4d::GetColumn);
matrix4d.BindMethod("GetDeterminant", &Nz::Matrix4d::GetDeterminant);
matrix4d.BindMethod("GetDeterminantAffine", &Nz::Matrix4d::GetDeterminantAffine);
matrix4d.BindMethod("GetInverse", [] (Nz::LuaState& lua, Nz::Matrix4d& instance, std::size_t /*argumentCount*/) -> int
{
Nz::Matrix4d result;
if (instance.GetInverse(&result))
return lua.Push(true, result);
else
return lua.Push(false);
});
matrix4d.BindMethod("GetInverseAffine", [] (Nz::LuaState& lua, Nz::Matrix4d& instance, std::size_t /*argumentCount*/) -> int
{
Nz::Matrix4d result;
if (instance.GetInverseAffine(&result))
return lua.Push(true, result);
else
return lua.Push(false);
});
matrix4d.BindMethod("GetRotation", &Nz::Matrix4d::GetRotation);
//matrix4d.BindMethod("GetRow", &Nz::Matrix4d::GetRow);
matrix4d.BindMethod("GetScale", &Nz::Matrix4d::GetScale);
matrix4d.BindMethod("GetSquaredScale", &Nz::Matrix4d::GetSquaredScale);
matrix4d.BindMethod("GetTranslation", &Nz::Matrix4d::GetTranslation);
matrix4d.BindMethod("GetTransposed", [] (Nz::LuaState& lua, Nz::Matrix4d& instance, std::size_t /*argumentCount*/) -> int
{
Nz::Matrix4d result;
instance.GetTransposed(&result);
return lua.Push(result);
});
matrix4d.BindMethod("HasNegativeScale", &Nz::Matrix4d::HasNegativeScale);
matrix4d.BindMethod("HasScale", &Nz::Matrix4d::HasScale);
matrix4d.BindMethod("Inverse", [] (Nz::LuaState& lua, Nz::Matrix4d& instance, std::size_t /*argumentCount*/) -> int
{
bool succeeded;
instance.Inverse(&succeeded);
return lua.Push(succeeded);
});
matrix4d.BindMethod("InverseAffine", [] (Nz::LuaState& lua, Nz::Matrix4d& instance, std::size_t /*argumentCount*/) -> int
{
bool succeeded;
instance.InverseAffine(&succeeded);
return lua.Push(succeeded);
});
matrix4d.BindMethod("IsAffine", &Nz::Matrix4d::IsAffine);
matrix4d.BindMethod("IsIdentity", &Nz::Matrix4d::IsIdentity);
matrix4d.BindMethod("MakeIdentity", &Nz::Matrix4d::MakeIdentity);
matrix4d.BindMethod("MakeLookAt", &Nz::Matrix4d::MakeLookAt, Nz::Vector3d::Up());
matrix4d.BindMethod("MakeOrtho", &Nz::Matrix4d::MakeOrtho, -1.0, 1.0);
matrix4d.BindMethod("MakePerspective", &Nz::Matrix4d::MakePerspective);
matrix4d.BindMethod("MakeRotation", &Nz::Matrix4d::MakeRotation);
matrix4d.BindMethod("MakeScale", &Nz::Matrix4d::MakeScale);
matrix4d.BindMethod("MakeTranslation", &Nz::Matrix4d::MakeTranslation);
matrix4d.BindMethod("MakeTransform", (Nz::Matrix4d&(Nz::Matrix4d::*)(const Nz::Vector3d&, const Nz::Quaterniond&, const Nz::Vector3d&)) &Nz::Matrix4d::MakeTransform, Nz::Vector3d::Unit());
matrix4d.BindMethod("MakeViewMatrix", &Nz::Matrix4d::MakeViewMatrix);
matrix4d.BindMethod("MakeZero", &Nz::Matrix4d::MakeZero);
matrix4d.BindMethod("Set", [] (Nz::LuaState& lua, Nz::Matrix4d& instance, std::size_t argumentCount) -> int
{
std::size_t argCount = std::min<std::size_t>(argumentCount, 3U);
int argIndex = 2;
switch (argCount)
{
case 1:
if (lua.IsOfType(argIndex, "Matrix4"))
instance = *static_cast<Nz::Matrix4d*>(lua.ToUserdata(argIndex));
break;
case 16:
{
double values[16];
for (std::size_t i = 0; i < 16; ++i)
values[i] = lua.CheckNumber(argIndex++);
instance = Nz::Matrix4d(values);
return 0;
}
}
lua.Error("No matching overload for method Set");
return 0;
});
matrix4d.BindMethod("SetRotation", &Nz::Matrix4d::SetRotation);
matrix4d.BindMethod("SetScale", &Nz::Matrix4d::SetScale);
matrix4d.BindMethod("SetTranslation", &Nz::Matrix4d::SetTranslation);
matrix4d.BindMethod("Transform", [] (Nz::LuaState& lua, Nz::Matrix4d& instance, std::size_t /*argumentCount*/) -> int
{
int argIndex = 2;
if (lua.IsOfType(argIndex, "Vector2"))
{
double z(lua.CheckNumber(argIndex + 1, 0.0));
double w(lua.CheckNumber(argIndex + 2, 1.0));
return lua.Push(instance.Transform(*static_cast<Nz::Vector2d*>(lua.ToUserdata(argIndex)), z, w));
}
else if (lua.IsOfType(argIndex, "Vector3"))
{
double w(lua.CheckNumber(argIndex + 1, 1.0));
return lua.Push(instance.Transform(*static_cast<Nz::Vector3d*>(lua.ToUserdata(argIndex)), w));
}
//else if (lua.IsOfType(2, "Vector4"))
// return lua.Push(instance.Transform(*static_cast<Nz::Vector4d*>(lua.ToUserdata(1))));
lua.Error("No matching overload for method Transform");
return 0;
});
matrix4d.BindMethod("Transpose", &Nz::Matrix4d::Transpose);
matrix4d.BindMethod("__tostring", &Nz::Matrix4d::ToString);
matrix4d.BindStaticMethod("Concatenate", &Nz::Matrix4d::Concatenate);
matrix4d.BindStaticMethod("ConcatenateAffine", &Nz::Matrix4d::ConcatenateAffine);
matrix4d.BindStaticMethod("Identity", &Nz::Matrix4d::Identity);
matrix4d.BindStaticMethod("LookAt", &Nz::Matrix4d::LookAt, Nz::Vector3d::Up());
matrix4d.BindStaticMethod("Ortho", &Nz::Matrix4d::Ortho, -1.0, 1.0);
matrix4d.BindStaticMethod("Perspective", &Nz::Matrix4d::Perspective);
matrix4d.BindStaticMethod("Rotate", &Nz::Matrix4d::Rotate);
matrix4d.BindStaticMethod("Scale", &Nz::Matrix4d::Scale);
matrix4d.BindStaticMethod("Translate", &Nz::Matrix4d::Translate);
matrix4d.BindStaticMethod("Transform", (Nz::Matrix4d(*)(const Nz::Vector3d&, const Nz::Quaterniond&, const Nz::Vector3d&)) &Nz::Matrix4d::Transform, Nz::Vector3d::Unit());
matrix4d.BindStaticMethod("ViewMatrix", &Nz::Matrix4d::ViewMatrix);
matrix4d.BindStaticMethod("Zero", &Nz::Matrix4d::Zero);
matrix4d.SetGetter([] (Nz::LuaState& lua, Nz::Matrix4d& instance)
{
bool succeeded = false;
std::size_t index = static_cast<std::size_t>(lua.ToInteger(2, &succeeded));
if (!succeeded || index < 1 || index > 16)
return false;
lua.Push(instance[index - 1]);
return true;
});
matrix4d.SetSetter([] (Nz::LuaState& lua, Nz::Matrix4d& instance)
{
bool succeeded = false;
std::size_t index = static_cast<std::size_t>(lua.ToInteger(2, &succeeded));
if (!succeeded || index < 1 || index > 16)
return false;
instance[index - 1] = lua.CheckNumber(3);
return true;
});
}
/*********************************** Nz::Rect **********************************/
rect.Reset("Rect");
{
rect.SetConstructor([] (Nz::LuaState& lua, Nz::Rectd* instance, std::size_t argumentCount)
{
std::size_t argCount = std::min<std::size_t>(argumentCount, 4U);
switch (argCount)
{
case 0:
case 4:
PlacementNew(instance, lua.CheckNumber(1, 0.0), lua.CheckNumber(2, 0.0), lua.CheckNumber(3, 0.0), lua.CheckNumber(4, 0.0));
return true;
case 1:
{
if (lua.IsOfType(1, "Rect"))
PlacementNew(instance, *static_cast<Nz::Rectd*>(lua.ToUserdata(1)));
else if (lua.IsOfType(1, Nz::LuaType_Table))
{
// TODO => Faire sans avoir à mettre de nom dans la table et prendre les éléments un à un pour créer le Rectd
PlacementNew(instance, lua.CheckField<double>("x", 1),
lua.CheckField<double>("y", 1),
lua.CheckField<double>("width", 1),
lua.CheckField<double>("height", 1));
}
else if (lua.IsOfType(1, "Vector2"))
PlacementNew(instance, *static_cast<Nz::Vector2d*>(lua.ToUserdata(1)));
else
break;
return true;
}
case 2:
{
if (lua.IsOfType(1, Nz::LuaType_Number) && lua.IsOfType(2, Nz::LuaType_Number))
PlacementNew(instance, lua.CheckNumber(1), lua.CheckNumber(2));
else if (lua.IsOfType(1, "Vector2") && lua.IsOfType(2, "Vector2"))
PlacementNew(instance, *static_cast<Nz::Vector2d*>(lua.ToUserdata(1)), *static_cast<Nz::Vector2d*>(lua.ToUserdata(2)));
else
break;
return true;
}
}
lua.Error("No matching overload for Rect constructor");
return false;
});
rect.BindMethod("__tostring", &Nz::Rectd::ToString);
rect.SetGetter([] (Nz::LuaState& lua, Nz::Rectd& instance)
{
switch (lua.GetType(2))
{
case Nz::LuaType_Number:
{
auto index = lua.CheckBoundInteger<std::size_t>(2);
if (index < 1 || index > 4)
return false;
lua.Push(instance[index - 1]);
return true;
}
case Nz::LuaType_String:
{
std::size_t length;
const char* xywh = lua.CheckString(2, &length);
if (length != 1)
break;
switch (xywh[0])
{
case 'x':
lua.Push(instance.x);
return true;
case 'y':
lua.Push(instance.y);
return true;
case 'w':
lua.Push(instance.width);
return true;
case 'h':
lua.Push(instance.height);
return true;
default:
break;
}
break;
}
default:
break;
}
return false;
});
rect.SetSetter([] (Nz::LuaState& lua, Nz::Rectd& instance)
{
switch (lua.GetType(2))
{
case Nz::LuaType_Number:
{
auto index = lua.CheckBoundInteger<std::size_t>(2);
if (index < 1 || index > 4)
return false;
instance[index - 1] = lua.CheckNumber(2);
return true;
}
case Nz::LuaType_String:
{
std::size_t length;
const char* xywh = lua.CheckString(2, &length);
if (length != 1)
break;
double value = lua.CheckNumber(3);
switch (xywh[0])
{
case 'x':
instance.x = value;
return true;
case 'y':
instance.y = value;
return true;
case 'w':
instance.width = value;
return true;
case 'h':
instance.height = value;
return true;
}
break;
}
default:
break;
}
return false;
});
}
/*********************************** Nz::Quaternion **********************************/
quaternion.Reset("Quaternion");
{
quaternion.SetConstructor([] (Nz::LuaState& lua, Nz::Quaterniond* instance, std::size_t argumentCount)
{
std::size_t argCount = std::min<std::size_t>(argumentCount, 4U);
switch (argCount)
{
case 0:
Nz::PlacementNew(instance, Nz::Quaterniond::Zero());
return true;
case 1:
{
if (lua.IsOfType(1, "EulerAngles"))
Nz::PlacementNew(instance, *static_cast<Nz::EulerAnglesd*>(lua.ToUserdata(1)));
else if (lua.IsOfType(1, "Quaternion"))
Nz::PlacementNew(instance, *static_cast<Nz::Quaterniond*>(lua.ToUserdata(1)));
else
break;
return true;
}
case 2:
Nz::PlacementNew(instance, lua.CheckNumber(1), *static_cast<Nz::Vector3d*>(lua.CheckUserdata(2, "Vector3")));
return true;
case 4:
Nz::PlacementNew(instance, lua.CheckNumber(1), lua.CheckNumber(2), lua.CheckNumber(3), lua.CheckNumber(4));
return true;
default:
break;
}
lua.Error("No matching overload for Quaternion constructor");
return false;
});
quaternion.BindMethod("ComputeW", &Nz::Quaterniond::ComputeW);
quaternion.BindMethod("Conjugate", &Nz::Quaterniond::Conjugate);
quaternion.BindMethod("DotProduct", &Nz::Quaterniond::DotProduct);
quaternion.BindMethod("GetConjugate", &Nz::Quaterniond::GetConjugate);
quaternion.BindMethod("GetInverse", &Nz::Quaterniond::GetInverse);
quaternion.BindMethod("Inverse", &Nz::Quaterniond::Inverse);
quaternion.BindMethod("Magnitude", &Nz::Quaterniond::Magnitude);
quaternion.BindMethod("SquaredMagnitude", &Nz::Quaterniond::SquaredMagnitude);
quaternion.BindMethod("ToEulerAngles", &Nz::Quaterniond::ToEulerAngles);
quaternion.BindMethod("__tostring", &Nz::Quaterniond::ToString);
quaternion.BindStaticMethod("Lerp", &Nz::Quaterniond::Lerp);
quaternion.BindStaticMethod("RotationBetween", &Nz::Quaterniond::RotationBetween);
quaternion.BindStaticMethod("Slerp", &Nz::Quaterniond::Slerp);
quaternion.BindMethod("GetNormal", [] (Nz::LuaState& lua, Nz::Quaterniond& instance, std::size_t /*argumentCount*/) -> int
{
double length;
lua.Push(instance.GetNormal(&length));
lua.Push(length);
return 2;
});
quaternion.BindMethod("Normalize", [] (Nz::LuaState& lua, Nz::Quaterniond& instance, std::size_t /*argumentCount*/) -> int
{
double length;
instance.Normalize(&length);
lua.Push(1); //< instance
lua.Push(length);
return 2;
});
quaternion.BindStaticMethod("Normalize", [] (Nz::LuaState& state) -> int
{
int argIndex = 1;
Nz::Quaterniond quat = state.Check<Nz::Quaterniond>(&argIndex);
double length;
state.Push(Nz::Quaterniond::Normalize(quat, &length));
state.Push(length);
return 2;
});
quaternion.SetGetter([] (Nz::LuaState& lua, Nz::Quaterniond& instance)
{
std::size_t length;
const char* wxyz = lua.CheckString(2, &length);
if (length != 1)
return false;
switch (wxyz[0])
{
case 'w':
lua.Push(instance.w);
return true;
case 'x':
lua.Push(instance.x);
return true;
case 'y':
lua.Push(instance.y);
return true;
case 'z':
lua.Push(instance.z);
return true;
}
return false;
});
quaternion.SetSetter([] (Nz::LuaState& lua, Nz::Quaterniond& instance)
{
std::size_t length;
const char* wxyz = lua.CheckString(2, &length);
if (length != 1)
return false;
double value = lua.CheckNumber(3);
switch (wxyz[0])
{
case 'w':
instance.w = value;
return true;
case 'x':
instance.x = value;
return true;
case 'y':
instance.y = value;
return true;
case 'z':
instance.z = value;
return true;
default:
break;
}
return false;
});
}
/*********************************** Nz::Vector2 **********************************/
vector2d.Reset("Vector2");
{
vector2d.SetConstructor([] (Nz::LuaState& lua, Nz::Vector2d* vector, std::size_t argumentCount)
{
std::size_t argCount = std::min<std::size_t>(argumentCount, 2U);
switch (argCount)
{
case 0:
case 2:
Nz::PlacementNew(vector, lua.CheckNumber(1, 0.0), lua.CheckNumber(2, 0.0));
return true;
case 1:
{
if (lua.IsOfType(1, Nz::LuaType_Number))
Nz::PlacementNew(vector, lua.CheckNumber(1));
else if (lua.IsOfType(1, "Vector2"))
Nz::PlacementNew(vector, *static_cast<Nz::Vector2d*>(lua.ToUserdata(1)));
else
break;
return true;
}
}
lua.Error("No matching overload for Vector2 constructor");
return false;
});
vector2d.BindMethod("__tostring", &Nz::Vector2d::ToString);
vector2d.SetGetter([] (Nz::LuaState& lua, Nz::Vector2d& instance)
{
switch (lua.GetType(2))
{
case Nz::LuaType_Number:
{
long long index = lua.CheckInteger(2);
if (index < 1 || index > 2)
return false;
lua.Push(instance[index - 1]);
return true;
}
case Nz::LuaType_String:
{
std::size_t length;
const char* xy = lua.CheckString(2, &length);
if (length != 1)
break;
switch (xy[0])
{
case 'x':
lua.Push(instance.x);
return true;
case 'y':
lua.Push(instance.y);
return true;
default:
break;
}
break;
}
default:
break;
}
return false;
});
vector2d.SetSetter([] (Nz::LuaState& lua, Nz::Vector2d& instance)
{
switch (lua.GetType(2))
{
case Nz::LuaType_Number:
{
long long index = lua.CheckInteger(2);
if (index < 1 || index > 2)
return false;
instance[index - 1] = lua.CheckNumber(3);
return true;
}
case Nz::LuaType_String:
{
std::size_t length;
const char* xy = lua.CheckString(2, &length);
if (length != 1)
break;
double value = lua.CheckNumber(3);
switch (xy[0])
{
case 'x':
instance.x = value;
return true;
case 'y':
instance.y = value;
return true;
default:
break;
}
break;
}
default:
break;
}
return false;
});
}
/*********************************** Nz::Vector3 **********************************/
vector3d.Reset("Vector3");
{
vector3d.SetConstructor([] (Nz::LuaState& lua, Nz::Vector3d* vector, std::size_t argumentCount)
{
std::size_t argCount = std::min<std::size_t>(argumentCount, 3U);
switch (argCount)
{
case 0:
case 3:
Nz::PlacementNew(vector, lua.CheckNumber(1, 0.0), lua.CheckNumber(2, 0.0), lua.CheckNumber(3, 0.0));
return true;
case 1:
{
if (lua.IsOfType(1, Nz::LuaType_Number))
Nz::PlacementNew(vector, lua.CheckNumber(1));
else if (lua.IsOfType(1, "Vector2"))
Nz::PlacementNew(vector, *static_cast<Nz::Vector2d*>(lua.ToUserdata(1)));
else if (lua.IsOfType(1, "Vector3"))
Nz::PlacementNew(vector, *static_cast<Nz::Vector3d*>(lua.ToUserdata(1)));
else
break;
return true;
}
case 2:
{
if (lua.IsOfType(1, Nz::LuaType_Number))
Nz::PlacementNew(vector, lua.CheckNumber(1), *static_cast<Nz::Vector2d*>(lua.CheckUserdata(2, "Vector2")));
else if (lua.IsOfType(1, "Vector2"))
Nz::PlacementNew(vector, *static_cast<Nz::Vector2d*>(lua.ToUserdata(1)), lua.CheckNumber(2));
else
break;
return true;
}
}
lua.Error("No matching overload for constructor");
return false;
});
vector3d.BindMethod("__tostring", &Nz::Vector3d::ToString);
vector3d.SetGetter([] (Nz::LuaState& lua, Nz::Vector3d& instance)
{
switch (lua.GetType(2))
{
case Nz::LuaType_Number:
{
long long index = lua.CheckInteger(2);
if (index < 1 || index > 3)
return false;
lua.Push(instance[index - 1]);
return true;
}
case Nz::LuaType_String:
{
std::size_t length;
const char* xyz = lua.CheckString(2, &length);
if (length != 1)
break;
switch (xyz[0])
{
case 'x':
lua.Push(instance.x);
return true;
case 'y':
lua.Push(instance.y);
return true;
case 'z':
lua.Push(instance.z);
return true;
default:
break;
}
break;
}
default:
break;
}
return false;
});
vector3d.SetSetter([] (Nz::LuaState& lua, Nz::Vector3d& instance)
{
switch (lua.GetType(2))
{
case Nz::LuaType_Number:
{
long long index = lua.CheckInteger(2);
if (index < 1 || index > 3)
return false;
instance[index - 1] = lua.CheckNumber(3);
return true;
}
case Nz::LuaType_String:
{
std::size_t length;
const char* xyz = lua.CheckString(2, &length);
if (length != 1)
break;
double value = lua.CheckNumber(3);
switch (xyz[0])
{
case 'x':
instance.x = value;
return true;
case 'y':
instance.y = value;
return true;
case 'z':
instance.z = value;
return true;
default:
break;
}
break;
}
default:
break;
}
return false;
});
}
}
/*!
* \brief Registers the classes that will be used by the Lua instance
*
* \param instance Lua instance that will interact with the Math classes
*/
void LuaBinding_Math::Register(Nz::LuaState& state)
{
eulerAngles.Register(state);
matrix4d.Register(state);
quaternion.Register(state);
rect.Register(state);
vector2d.Register(state);
vector3d.Register(state);
quaternion.PushGlobalTable(state);
{
state.PushField("Identity", Nz::Quaterniond::Identity());
state.PushField("Zero", Nz::Quaterniond::Zero());
}
state.Pop();
}
}

View File

@ -1,314 +0,0 @@
// This file was automatically generated on 26 May 2014 at 01:05:31
#include <NDK/Lua/LuaBinding_Network.hpp>
#include <NDK/LuaAPI.hpp>
namespace Ndk
{
std::unique_ptr<LuaBinding_Base> LuaBinding_Base::BindNetwork(LuaBinding& binding)
{
return std::make_unique<LuaBinding_Network>(binding);
}
LuaBinding_Network::LuaBinding_Network(LuaBinding& binding) :
LuaBinding_Base(binding)
{
/*********************************** Nz::AbstractSocket **********************************/
abstractSocket.Reset("AbstractSocket");
{
abstractSocket.BindMethod("Close", &Nz::AbstractSocket::Close);
abstractSocket.BindMethod("EnableBlocking", &Nz::AbstractSocket::EnableBlocking);
abstractSocket.BindMethod("GetLastError", &Nz::AbstractSocket::GetLastError);
abstractSocket.BindMethod("GetState", &Nz::AbstractSocket::GetState);
abstractSocket.BindMethod("GetType", &Nz::AbstractSocket::GetType);
abstractSocket.BindMethod("IsBlockingEnabled", &Nz::AbstractSocket::IsBlockingEnabled);
abstractSocket.BindMethod("QueryAvailableBytes", &Nz::AbstractSocket::QueryAvailableBytes);
}
/*********************************** Nz::IpAddress **********************************/
ipAddress.Reset("IpAddress");
{
ipAddress.SetConstructor([] (Nz::LuaState& lua, Nz::IpAddress* instance, std::size_t argumentCount)
{
std::size_t argCount = std::min<std::size_t>(argumentCount, 9U);
int argIndex = 1;
switch (argCount)
{
case 0:
Nz::PlacementNew(instance);
return true;
case 1:
Nz::PlacementNew(instance, lua.CheckString(argIndex));
return true;
case 4:
case 5:
{
Nz::UInt8 a = lua.Check<Nz::UInt8>(&argIndex);
Nz::UInt8 b = lua.Check<Nz::UInt8>(&argIndex);
Nz::UInt8 c = lua.Check<Nz::UInt8>(&argIndex);
Nz::UInt8 d = lua.Check<Nz::UInt8>(&argIndex);
Nz::UInt16 port = lua.Check<Nz::UInt16>(&argIndex, 0);
Nz::PlacementNew(instance, a, b, c, d, port);
return true;
}
case 8:
case 9:
{
Nz::UInt16 a = lua.Check<Nz::UInt16>(&argIndex);
Nz::UInt16 b = lua.Check<Nz::UInt16>(&argIndex);
Nz::UInt16 c = lua.Check<Nz::UInt16>(&argIndex);
Nz::UInt16 d = lua.Check<Nz::UInt16>(&argIndex);
Nz::UInt16 e = lua.Check<Nz::UInt16>(&argIndex);
Nz::UInt16 f = lua.Check<Nz::UInt16>(&argIndex);
Nz::UInt16 g = lua.Check<Nz::UInt16>(&argIndex);
Nz::UInt16 h = lua.Check<Nz::UInt16>(&argIndex);
Nz::UInt16 port = lua.Check<Nz::UInt16>(&argIndex, 0);
Nz::PlacementNew(instance, a, b, c, d, e, f, g, h, port);
return true;
}
}
lua.Error("No matching overload for constructor");
return false;
});
ipAddress.BindMethod("GetPort", &Nz::IpAddress::GetPort);
ipAddress.BindMethod("GetProtocol", &Nz::IpAddress::GetProtocol);
ipAddress.BindMethod("IsLoopback", &Nz::IpAddress::IsLoopback);
ipAddress.BindMethod("IsValid", &Nz::IpAddress::IsValid);
ipAddress.BindMethod("ToUInt32", &Nz::IpAddress::ToUInt32);
ipAddress.BindMethod("__tostring", &Nz::IpAddress::ToString);
ipAddress.BindStaticMethod("ResolveAddress", [] (Nz::LuaState& state) -> int
{
Nz::String service;
Nz::ResolveError error = Nz::ResolveError_Unknown;
int argIndex = 2;
Nz::String hostName = Nz::IpAddress::ResolveAddress(state.Check<Nz::IpAddress>(&argIndex), &service, &error);
if (error == Nz::ResolveError_NoError)
{
state.Push(hostName);
state.Push(service);
return 2;
}
else
{
state.PushBoolean(false);
state.Push(error);
return 2;
}
});
ipAddress.BindStaticMethod("ResolveHostname", [] (Nz::LuaState& state) -> int
{
Nz::ResolveError error = Nz::ResolveError_Unknown;
int argIndex = 2;
Nz::NetProtocol protocol = state.Check<Nz::NetProtocol>(&argIndex);
Nz::String hostname = state.Check<Nz::String>(&argIndex);
Nz::String service = state.Check<Nz::String>(&argIndex, "http");
std::vector<Nz::HostnameInfo> addresses = Nz::IpAddress::ResolveHostname(protocol, hostname, service, &error);
if (error == Nz::ResolveError_NoError)
{
int index = 1;
state.PushTable(addresses.size());
for (Nz::HostnameInfo& info : addresses)
{
state.PushInteger(index++);
state.PushTable(0, 4);
state.PushField("Address", std::move(info.address));
state.PushField("CanonicalName", std::move(info.canonicalName));
state.PushField("Protocol", std::move(info.protocol));
state.PushField("SocketType", std::move(info.socketType));
state.SetTable();
}
return 1;
}
else
{
state.PushBoolean(false);
state.Push(error);
return 2;
}
});
}
udpSocket.Reset("UdpSocket");
{
udpSocket.Inherit<Nz::AbstractSocket>(abstractSocket);
udpSocket.BindDefaultConstructor();
udpSocket.BindMethod("Create", &Nz::UdpSocket::Create);
udpSocket.BindMethod("EnableBroadcasting", &Nz::UdpSocket::EnableBroadcasting);
udpSocket.BindMethod("GetBoundAddress", &Nz::UdpSocket::GetBoundAddress);
udpSocket.BindMethod("GetBoundPort", &Nz::UdpSocket::GetBoundPort);
udpSocket.BindMethod("IsBroadcastingEnabled", &Nz::UdpSocket::IsBroadcastingEnabled);
udpSocket.BindMethod("QueryMaxDatagramSize", &Nz::UdpSocket::QueryMaxDatagramSize);
udpSocket.BindMethod("Bind", [](Nz::LuaState& lua, Nz::UdpSocket& socket, std::size_t /*argumentCount*/) -> int
{
int argIndex = 2;
if (lua.IsOfType(argIndex, "IpAddress"))
return lua.Push(socket.Bind(*static_cast<Nz::IpAddress*>(lua.ToUserdata(argIndex))));
else
return lua.Push(socket.Bind(lua.Check<Nz::UInt16>(&argIndex)));
});
udpSocket.BindMethod("Receive", [](Nz::LuaState& lua, Nz::UdpSocket& socket, std::size_t /*argumentCount*/) -> int
{
Nz::IpAddress from;
std::array<char, 0xFFFF> buffer;
std::size_t received;
if (socket.Receive(buffer.data(), buffer.size(), &from, &received))
{
lua.PushBoolean(true);
lua.PushString(from.ToString());
lua.PushString(buffer.data(), received);
return 3;
}
lua.PushBoolean(false);
return 1;
});
udpSocket.BindMethod("Send", [](Nz::LuaState& lua, Nz::UdpSocket& socket, std::size_t /*argumentCount*/) -> int
{
int argIndex = 2;
Nz::String to = lua.Check<Nz::String>(&argIndex);
std::size_t bufferLength;
const char* buffer = lua.CheckString(argIndex, &bufferLength);
std::size_t sent;
bool ret;
if ((ret = socket.Send(Nz::IpAddress(to), buffer, bufferLength, &sent)) != true)
sent = 0;
return lua.Push(std::make_pair(ret, sent));
});
}
}
/*!
* \brief Registers the classes that will be used by the Lua instance
*
* \param instance Lua instance that will interact with the Network classes
*/
void LuaBinding_Network::Register(Nz::LuaState& state)
{
// Classes
abstractSocket.Register(state);
ipAddress.Register(state);
udpSocket.Register(state);
// Enums
// Nz::NetProtocol
static_assert(Nz::NetProtocol_Max + 1 == 4, "Nz::NetProtocol has been updated but change was not reflected to Lua binding");
state.PushTable(0, 4);
{
state.PushField("Any", Nz::NetProtocol_Any);
state.PushField("IPv4", Nz::NetProtocol_IPv4);
state.PushField("IPv6", Nz::NetProtocol_IPv6);
state.PushField("Unknown", Nz::NetProtocol_Unknown);
}
state.SetGlobal("NetProtocol");
// Nz::PacketPriority
static_assert(Nz::PacketPriority_Max + 1 == 4, "Nz::PacketPriority has been updated but change was not reflected to Lua binding");
state.PushTable(0, 6);
{
state.PushField("High", Nz::PacketPriority_High);
state.PushField("Highest", Nz::PacketPriority_Highest);
state.PushField("Immediate", Nz::PacketPriority_Immediate);
state.PushField("Medium", Nz::PacketPriority_Medium);
state.PushField("Low", Nz::PacketPriority_Low);
state.PushField("Lowest", Nz::PacketPriority_Lowest);
}
state.SetGlobal("PacketPriority");
// Nz::PacketReliability
static_assert(Nz::PacketReliability_Max + 1 == 3, "Nz::PacketReliability has been updated but change was not reflected to Lua binding");
state.PushTable(0, 3);
{
state.PushField("Reliable", Nz::PacketReliability_Reliable);
state.PushField("ReliableOrdered", Nz::PacketReliability_ReliableOrdered);
state.PushField("Unreliable", Nz::PacketReliability_Unreliable);
}
state.SetGlobal("PacketReliability");
// Nz::ResolveError
static_assert(Nz::ResolveError_Max + 1 == 9, "Nz::ResolveError has been updated but change was not reflected to Lua binding");
state.PushTable(0, 9);
{
state.PushField("Internal", Nz::ResolveError_Internal);
state.PushField("ResourceError", Nz::ResolveError_ResourceError);
state.PushField("NoError", Nz::ResolveError_NoError);
state.PushField("NonRecoverable", Nz::ResolveError_NonRecoverable);
state.PushField("NotFound", Nz::ResolveError_NotFound);
state.PushField("NotInitialized", Nz::ResolveError_NotInitialized);
state.PushField("ProtocolNotSupported", Nz::ResolveError_ProtocolNotSupported);
state.PushField("TemporaryFailure", Nz::ResolveError_TemporaryFailure);
state.PushField("Unknown", Nz::ResolveError_Unknown);
}
state.SetGlobal("ResolveError");
// Nz::SocketError
static_assert(Nz::SocketError_Max + 1 == 16, "Nz::SocketError has been updated but change was not reflected to Lua binding");
state.PushTable(0, 16);
{
state.PushField("AddressNotAvailable", Nz::SocketError_AddressNotAvailable);
state.PushField("ConnectionClosed", Nz::SocketError_ConnectionClosed);
state.PushField("ConnectionRefused", Nz::SocketError_ConnectionRefused);
state.PushField("DatagramSize", Nz::SocketError_DatagramSize);
state.PushField("Internal", Nz::SocketError_Internal);
state.PushField("Interrupted", Nz::SocketError_Interrupted);
state.PushField("Packet", Nz::SocketError_Packet);
state.PushField("NetworkError", Nz::SocketError_NetworkError);
state.PushField("NoError", Nz::SocketError_NoError);
state.PushField("NotInitialized", Nz::SocketError_NotInitialized);
state.PushField("NotSupported", Nz::SocketError_NotSupported);
state.PushField("ResolveError", Nz::SocketError_ResolveError);
state.PushField("ResourceError", Nz::SocketError_ResourceError);
state.PushField("TimedOut", Nz::SocketError_TimedOut);
state.PushField("Unknown", Nz::SocketError_Unknown);
state.PushField("UnreachableHost", Nz::SocketError_UnreachableHost);
}
state.SetGlobal("SocketError");
// Nz::SocketState
static_assert(Nz::SocketState_Max + 1 == 5, "Nz::SocketState has been updated but change was not reflected to Lua binding");
state.PushTable(0, 5);
{
state.PushField("Bound", Nz::SocketState_Bound);
state.PushField("Connecting", Nz::SocketState_Connecting);
state.PushField("Connected", Nz::SocketState_Connected);
state.PushField("NotConnected", Nz::SocketState_NotConnected);
state.PushField("Resolving", Nz::SocketState_Resolving);
}
state.SetGlobal("SocketState");
// Nz::SocketType
static_assert(Nz::SocketType_Max + 1 == 4, "Nz::SocketState has been updated but change was not reflected to Lua binding");
state.PushTable(0, 4);
{
state.PushField("Raw", Nz::SocketType_Raw);
state.PushField("TCP", Nz::SocketType_TCP);
state.PushField("UDP", Nz::SocketType_UDP);
state.PushField("Unknown", Nz::SocketType_Unknown);
}
state.SetGlobal("SocketType");
}
}

View File

@ -1,136 +0,0 @@
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequisites.hpp
#include <NDK/Lua/LuaBinding_Platform.hpp>
#include <NDK/LuaAPI.hpp>
namespace Ndk
{
std::unique_ptr<LuaBinding_Base> LuaBinding_Base::BindPlatform(LuaBinding& binding)
{
return std::make_unique<LuaBinding_Platform>(binding);
}
LuaBinding_Platform::LuaBinding_Platform(LuaBinding& binding) :
LuaBinding_Base(binding)
{
/*********************************** Nz::Keyboard **********************************/
keyboard.Reset("Keyboard");
{
//keyboard.BindStaticMethod("GetKeyName", &Nz::Keyboard::GetKeyName);
//keyboard.BindStaticMethod("IsKeyPressed", &Nz::Keyboard::IsKeyPressed);
}
}
/*!
* \brief Registers the classes that will be used by the Lua instance
*
* \param instance Lua instance that will interact with the Utility classes
*/
void LuaBinding_Platform::Register(Nz::LuaState& state)
{
keyboard.Register(state);
/*keyboard.PushGlobalTable(state);
{
static_assert(Nz::Keyboard::Max == 123, "Nz::Keyboard::Key has been updated but change was not reflected to Lua binding");
state.PushField("Undefined", Nz::Keyboard::Undefined);
// A-Z
for (std::size_t i = 0; i < 26; ++i)
state.PushField(Nz::String('A' + char(i)), Nz::Keyboard::A + i);
// Numerical
for (std::size_t i = 0; i < 10; ++i)
{
state.PushField("Num" + Nz::String::Number(i), Nz::Keyboard::Num0 + i);
state.PushField("Numpad" + Nz::String::Number(i), Nz::Keyboard::Numpad0 + i);
}
// F1-F15
for (std::size_t i = 0; i < 15; ++i)
state.PushField('F' + Nz::String::Number(i+1), Nz::Keyboard::F1 + i);
// And all the others...
state.PushField("Down", Nz::Keyboard::Down);
state.PushField("Left", Nz::Keyboard::Left);
state.PushField("Right", Nz::Keyboard::Right);
state.PushField("Up", Nz::Keyboard::Up);
state.PushField("Add", Nz::Keyboard::Add);
state.PushField("Decimal", Nz::Keyboard::Decimal);
state.PushField("Divide", Nz::Keyboard::Divide);
state.PushField("Multiply", Nz::Keyboard::Multiply);
state.PushField("Subtract", Nz::Keyboard::Subtract);
state.PushField("NumpadReturn", Nz::Keyboard::NumpadReturn);
state.PushField("Backslash", Nz::Keyboard::Backslash);
state.PushField("Backspace", Nz::Keyboard::Backspace);
state.PushField("Clear", Nz::Keyboard::Clear);
state.PushField("Comma", Nz::Keyboard::Comma);
state.PushField("Dash", Nz::Keyboard::Dash);
state.PushField("Delete", Nz::Keyboard::Delete);
state.PushField("End", Nz::Keyboard::End);
state.PushField("Equal", Nz::Keyboard::Equal);
state.PushField("Escape", Nz::Keyboard::Escape);
state.PushField("Home", Nz::Keyboard::Home);
state.PushField("Insert", Nz::Keyboard::Insert);
state.PushField("LAlt", Nz::Keyboard::LAlt);
state.PushField("LBracket", Nz::Keyboard::LBracket);
state.PushField("LControl", Nz::Keyboard::LControl);
state.PushField("LShift", Nz::Keyboard::LShift);
state.PushField("LSystem", Nz::Keyboard::LSystem);
state.PushField("PageDown", Nz::Keyboard::PageDown);
state.PushField("PageUp", Nz::Keyboard::PageUp);
state.PushField("Pause", Nz::Keyboard::Pause);
state.PushField("Period", Nz::Keyboard::Period);
state.PushField("Print", Nz::Keyboard::Print);
state.PushField("PrintScreen", Nz::Keyboard::PrintScreen);
state.PushField("Quote", Nz::Keyboard::Quote);
state.PushField("RAlt", Nz::Keyboard::RAlt);
state.PushField("RBracket", Nz::Keyboard::RBracket);
state.PushField("RControl", Nz::Keyboard::RControl);
state.PushField("Return", Nz::Keyboard::Return);
state.PushField("RShift", Nz::Keyboard::RShift);
state.PushField("RSystem", Nz::Keyboard::RSystem);
state.PushField("Semicolon", Nz::Keyboard::Semicolon);
state.PushField("Slash", Nz::Keyboard::Slash);
state.PushField("Space", Nz::Keyboard::Space);
state.PushField("Tab", Nz::Keyboard::Tab);
state.PushField("Tilde", Nz::Keyboard::Tilde);
state.PushField("Menu", Nz::Keyboard::Menu);
state.PushField("ISOBackslash102", Nz::Keyboard::ISOBackslash102);
state.PushField("Browser_Back", Nz::Keyboard::Browser_Back);
state.PushField("Browser_Favorites", Nz::Keyboard::Browser_Favorites);
state.PushField("Browser_Forward", Nz::Keyboard::Browser_Forward);
state.PushField("Browser_Home", Nz::Keyboard::Browser_Home);
state.PushField("Browser_Refresh", Nz::Keyboard::Browser_Refresh);
state.PushField("Browser_Search", Nz::Keyboard::Browser_Search);
state.PushField("Browser_Stop", Nz::Keyboard::Browser_Stop);
state.PushField("Media_Next", Nz::Keyboard::Media_Next);
state.PushField("Media_Play", Nz::Keyboard::Media_Play);
state.PushField("Media_Previous", Nz::Keyboard::Media_Previous);
state.PushField("Media_Stop", Nz::Keyboard::Media_Stop);
state.PushField("Volume_Down", Nz::Keyboard::Volume_Down);
state.PushField("Volume_Mute", Nz::Keyboard::Volume_Mute);
state.PushField("Volume_Up", Nz::Keyboard::Volume_Up);
state.PushField("CapsLock", Nz::Keyboard::CapsLock);
state.PushField("NumLock", Nz::Keyboard::NumLock);
state.PushField("ScrollLock", Nz::Keyboard::ScrollLock);
}
state.Pop();*/
static_assert(Nz::WindowStyle_Max + 1 == 6, "Nz::WindowStyle has been updated but change was not reflected to Lua binding");
state.PushTable(0, Nz::WindowStyle_Max + 1);
{
state.PushField("None", Nz::WindowStyle_None);
state.PushField("Fullscreen", Nz::WindowStyle_Fullscreen);
state.PushField("Closable", Nz::WindowStyle_Closable);
state.PushField("Resizable", Nz::WindowStyle_Resizable);
state.PushField("Titlebar", Nz::WindowStyle_Titlebar);
state.PushField("Threaded", Nz::WindowStyle_Threaded);
}
state.SetGlobal("WindowStyle");
}
}

View File

@ -1,110 +0,0 @@
// Copyright (C) 2017 Jérôme Leclercq, Arnaud Cadot
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequisites.hpp
#include <NDK/Lua/LuaBinding_Renderer.hpp>
#include <NDK/LuaAPI.hpp>
#include <NDK/Lua/LuaBinding.hpp>
#include <NDK/Lua/LuaBinding_Utility.hpp>
namespace Ndk
{
std::unique_ptr<LuaBinding_Base> LuaBinding_Base::BindRenderer(LuaBinding& binding)
{
return std::make_unique<LuaBinding_Renderer>(binding);
}
LuaBinding_Renderer::LuaBinding_Renderer(LuaBinding& binding) :
LuaBinding_Base(binding)
{
LuaBinding_Utility& utility = static_cast<LuaBinding_Utility&>(*m_binding.utility);
/*********************************** Nz::Texture ***********************************/
texture.Reset("Texture");
{
texture.Inherit<Nz::AbstractImageRef>(utility.abstractImage, [] (Nz::TextureRef* textureRef) -> Nz::AbstractImageRef*
{
return reinterpret_cast<Nz::AbstractImageRef*>(textureRef); //TODO: Make a ObjectRefCast
});
texture.SetConstructor([] (Nz::LuaState& /*lua*/, Nz::TextureRef* instance, std::size_t /*argumentCount*/)
{
Nz::PlacementNew(instance, Nz::Texture::New());
return true;
});
texture.BindMethod("Create", &Nz::Texture::Create, static_cast<Nz::UInt8>(1), 1U);
texture.BindMethod("Destroy", &Nz::Texture::Destroy);
//texture.BindMethod("Download", &Nz::Texture::Download);
texture.BindMethod("EnableMipmapping", &Nz::Texture::EnableMipmapping);
texture.BindMethod("EnsureMipmapsUpdate", &Nz::Texture::EnsureMipmapsUpdate);
texture.BindMethod("HasMipmaps", &Nz::Texture::HasMipmaps);
texture.BindMethod("InvalidateMipmaps", &Nz::Texture::InvalidateMipmaps);
texture.BindMethod("IsValid", &Nz::Texture::IsValid);
texture.BindMethod("LoadFaceFromFile", &Nz::Texture::LoadFaceFromFile, Nz::ImageParams());
//bool LoadFaceFromMemory(CubemapFace face, const void* data, std::size_t size, const ImageParams& params = ImageParams());
//bool LoadFaceFromStream(CubemapFace face, Stream& stream, const ImageParams& params = ImageParams());
texture.BindMethod("SaveToFile", &Nz::Texture::SaveToFile, Nz::ImageParams());
//bool SaveToStream(Stream& stream, const String& format, const ImageParams& params = ImageParams());
texture.BindMethod("SetMipmapRange", &Nz::Texture::SetMipmapRange);
texture.BindStaticMethod("IsFormatSupported", &Nz::Texture::IsFormatSupported);
texture.BindStaticMethod("IsMipmappingSupported", &Nz::Texture::IsMipmappingSupported);
texture.BindStaticMethod("IsTypeSupported", &Nz::Texture::IsTypeSupported);
texture.BindStaticMethod("LoadFromFile", &Nz::Texture::LoadFromFile, true, Nz::ImageParams());
//TextureRef LoadFromImage(const Image& image, bool generateMipmaps = true);
//TextureRef LoadFromMemory(const void* data, std::size_t size, const ImageParams& params = ImageParams(), bool generateMipmaps = true);
//TextureRef LoadFromStream(Stream& stream, const ImageParams& params = ImageParams(), bool generateMipmaps = true);
texture.BindStaticMethod("LoadArrayFromFile", &Nz::Texture::LoadArrayFromFile, Nz::Vector2ui(2, 2), true, Nz::ImageParams());
//TextureRef LoadArrayFromImage(const Image& image, bool generateMipmaps = true, const Vector2ui& atlasSize = Vector2ui(2, 2));
//TextureRef LoadArrayFromMemory(const void* data, std::size_t size, const ImageParams& imageParams = ImageParams(), bool generateMipmaps = true, const Vector2ui& atlasSize = Vector2ui(2, 2));
//TextureRef LoadArrayFromStream(Stream& stream, const ImageParams& imageParams = ImageParams(), bool generateMipmaps = true, const Vector2ui& atlasSize = Vector2ui(2, 2));
//TextureRef LoadCubemapFromFile(const String& filePath, const ImageParams& imageParams = ImageParams(), bool generateMipmaps = true, const CubemapParams& cubemapParams = CubemapParams());
//TextureRef LoadCubemapFromImage(const Image& image, bool generateMipmaps = true, const CubemapParams& params = CubemapParams());
//TextureRef LoadCubemapFromMemory(const void* data, std::size_t size, const ImageParams& imageParams = ImageParams(), bool generateMipmaps = true, const CubemapParams& cubemapParams = CubemapParams());
//TextureRef LoadCubemapFromStream(Stream& stream, const ImageParams& imageParams = ImageParams(), bool generateMipmaps = true, const CubemapParams& cubemapParams = CubemapParams());
}
/*********************************** Nz::TextureLibrary ***********************************/
textureLibrary.Reset("TextureLibrary");
{
textureLibrary.BindStaticMethod("Get", &Nz::TextureLibrary::Get);
textureLibrary.BindStaticMethod("Has", &Nz::TextureLibrary::Has);
textureLibrary.BindStaticMethod("Register", &Nz::TextureLibrary::Register);
textureLibrary.BindStaticMethod("Query", &Nz::TextureLibrary::Query);
textureLibrary.BindStaticMethod("Unregister", &Nz::TextureLibrary::Unregister);
}
/*********************************** Nz::TextureManager ***********************************/
textureManager.Reset("TextureManager");
{
textureManager.BindStaticMethod("Clear", &Nz::TextureManager::Clear);
textureManager.BindStaticMethod("Get", &Nz::TextureManager::Get);
textureManager.BindStaticMethod("GetDefaultParameters", &Nz::TextureManager::GetDefaultParameters);
textureManager.BindStaticMethod("Purge", &Nz::TextureManager::Purge);
textureManager.BindStaticMethod("Register", &Nz::TextureManager::Register);
textureManager.BindStaticMethod("SetDefaultParameters", &Nz::TextureManager::SetDefaultParameters);
textureManager.BindStaticMethod("Unregister", &Nz::TextureManager::Unregister);
}
}
/*!
* \brief Registers the classes that will be used by the Lua instance
*
* \param instance Lua instance that will interact with the Renderer classes
*/
void LuaBinding_Renderer::Register(Nz::LuaState& state)
{
texture.Register(state);
textureLibrary.Register(state);
textureManager.Register(state);
}
}

View File

@ -1,354 +0,0 @@
// Copyright (C) 2017 Jérôme Leclercq, Arnaud Cadot
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequisites.hpp
#include <NDK/Lua/LuaBinding_SDK.hpp>
#include <NDK/LuaAPI.hpp>
#include <NDK/Lua/LuaBinding.hpp>
#include <NDK/Lua/LuaBinding_Utility.hpp>
#ifndef NDK_SERVER
#include <NDK/Lua/LuaBinding_Graphics.hpp>
#endif
namespace Ndk
{
std::unique_ptr<LuaBinding_Base> LuaBinding_Base::BindSDK(LuaBinding& binding)
{
return std::make_unique<LuaBinding_SDK>(binding);
}
LuaBinding_SDK::LuaBinding_SDK(LuaBinding& binding) :
LuaBinding_Base(binding)
{
#ifndef NDK_SERVER
LuaBinding_Graphics& graphics = static_cast<LuaBinding_Graphics&>(*m_binding.graphics);
#endif
LuaBinding_Utility& utility = static_cast<LuaBinding_Utility&>(*m_binding.utility);
/*********************************** Ndk::Application **********************************/
application.Reset("Application");
{
#ifndef NDK_SERVER
//application.SetMethod("AddWindow", &Application::AddWindow);
application.BindMethod("EnableConsole", &Application::EnableConsole);
application.BindMethod("EnableFPSCounter", &Application::EnableFPSCounter);
application.BindMethod("IsConsoleEnabled", &Application::IsConsoleEnabled);
application.BindMethod("IsFPSCounterEnabled", &Application::IsFPSCounterEnabled);
#endif
application.BindMethod("AddWorld", [] (Nz::LuaState& lua, Application* instance, std::size_t /*argumentCount*/) -> int
{
lua.Push(instance->AddWorld().CreateHandle());
return 1;
});
application.BindMethod("GetUpdateTime", &Application::GetUpdateTime);
application.BindMethod("Quit", &Application::Quit);
}
/*********************************** Ndk::Console **********************************/
#ifndef NDK_SERVER
console.Reset("Console");
{
console.Inherit<Nz::Node>(utility.node, [] (ConsoleHandle* handle) -> Nz::Node*
{
return handle->GetObject();
});
console.BindMethod("AddLine", &Console::AddLine, Nz::Color::White);
console.BindMethod("Clear", &Console::Clear);
console.BindMethod("GetCharacterSize", &Console::GetCharacterSize);
//console.BindMethod("GetHistory", &Console::GetHistory);
//console.BindMethod("GetInput", &Console::GetInput);
console.BindMethod("GetTextFont", &Console::GetTextFont);
console.BindMethod("IsValidHandle", &ConsoleHandle::IsValid);
console.BindMethod("SetCharacterSize", &Console::SetCharacterSize);
console.BindMethod("SetTextFont", &Console::SetTextFont);
}
#endif
/*********************************** Ndk::Entity **********************************/
entity.Reset("Entity");
{
entity.BindMethod("Enable", &Entity::Enable, true);
entity.BindMethod("GetId", &Entity::GetId);
entity.BindMethod("GetWorld", &Entity::GetWorld);
entity.BindMethod("Kill", &Entity::Kill);
entity.BindMethod("IsEnabled", &Entity::IsEnabled);
entity.BindMethod("IsValid", &Entity::IsValid);
entity.BindMethod("IsValidHandle", &EntityHandle::IsValid);
entity.BindMethod("RemoveAllComponents", &Entity::RemoveAllComponents);
entity.BindMethod("__tostring", &EntityHandle::ToString);
entity.BindMethod("AddComponent", [this] (Nz::LuaState& state, EntityHandle& handle, std::size_t /*argumentCount*/) -> int
{
LuaBinding::ComponentBinding* bindingComponent = m_binding.QueryComponentIndex(state);
return bindingComponent->adder(state, handle);
});
entity.BindMethod("HasComponent", [this](Nz::LuaState& state, EntityHandle& handle, std::size_t /*argumentCount*/) -> int
{
LuaBinding::ComponentBinding* bindingComponent = m_binding.QueryComponentIndex(state);
state.PushBoolean(handle->HasComponent(bindingComponent->index));
return 1;
});
entity.BindMethod("GetComponent", [this] (Nz::LuaState& state, EntityHandle& handle, std::size_t /*argumentCount*/) -> int
{
LuaBinding::ComponentBinding* bindingComponent = m_binding.QueryComponentIndex(state);
return bindingComponent->getter(state, handle->GetComponent(bindingComponent->index));
});
entity.BindMethod("RemoveComponent", [this] (Nz::LuaState& state, EntityHandle& handle, std::size_t /*argumentCount*/) -> int
{
LuaBinding::ComponentBinding* bindingComponent = m_binding.QueryComponentIndex(state);
handle->RemoveComponent(bindingComponent->index);
return 0;
});
}
/*********************************** Ndk::NodeComponent **********************************/
nodeComponent.Reset("NodeComponent");
{
nodeComponent.BindMethod("IsValidHandle", &NodeComponentHandle::IsValid);
nodeComponent.Inherit<Nz::Node>(utility.node, [] (NodeComponentHandle* handle) -> Nz::Node*
{
return handle->GetObject();
});
}
/*********************************** Ndk::VelocityComponent **********************************/
velocityComponent.Reset("VelocityComponent");
{
velocityComponent.BindMethod("IsValidHandle", &VelocityComponentHandle::IsValid);
velocityComponent.SetGetter([] (Nz::LuaState& lua, VelocityComponentHandle& instance)
{
std::size_t length;
const char* member = lua.CheckString(2, &length);
if (std::strcmp(member, "Linear") == 0)
{
lua.Push(instance->linearVelocity);
return true;
}
return false;
});
velocityComponent.SetSetter([] (Nz::LuaState& lua, VelocityComponentHandle& instance)
{
std::size_t length;
const char* member = lua.CheckString(2, &length);
int argIndex = 3;
if (std::strcmp(member, "Linear") == 0)
{
instance->linearVelocity = lua.Check<Nz::Vector3f>(&argIndex);
return true;
}
return false;
});
}
/*********************************** Ndk::World **********************************/
world.Reset("World");
{
world.BindMethod("CreateEntity", &World::CreateEntity);
world.BindMethod("CreateEntities", &World::CreateEntities);
world.BindMethod("Clear", &World::Clear);
world.BindMethod("DisableProfiler", &World::DisableProfiler);
world.BindMethod("EnableProfiler", &World::EnableProfiler);
world.BindMethod("IsProfilerEnabled", &World::IsProfilerEnabled);
world.BindMethod("Refresh", &World::Refresh);
world.BindMethod("ResetProfiler", &World::ResetProfiler);
world.BindMethod("Update", &World::Update);
world.BindMethod("IsValidHandle", &WorldHandle::IsValid);
}
#ifndef NDK_SERVER
/*********************************** Ndk::CameraComponent **********************************/
cameraComponent.Reset("CameraComponent");
{
cameraComponent.Inherit<Nz::AbstractViewer>(graphics.abstractViewer, [] (CameraComponentHandle* handle) -> Nz::AbstractViewer*
{
return handle->GetObject();
});
cameraComponent.BindMethod("GetFOV", &CameraComponent::GetFOV);
cameraComponent.BindMethod("GetLayer", &CameraComponent::GetLayer);
cameraComponent.BindMethod("IsValidHandle", &CameraComponentHandle::IsValid);
cameraComponent.BindMethod("SetFOV", &CameraComponent::SetFOV);
cameraComponent.BindMethod("SetLayer", &CameraComponent::SetLayer);
cameraComponent.BindMethod("SetProjectionType", &CameraComponent::SetProjectionType);
cameraComponent.BindMethod("SetSize", (void(CameraComponent::*)(const Nz::Vector2f&)) &CameraComponent::SetSize);
//cameraComponent.BindMethod("SetTarget", &CameraComponent::SetTarget);
cameraComponent.BindMethod("SetTargetRegion", &CameraComponent::SetTargetRegion);
cameraComponent.BindMethod("SetViewport", &CameraComponent::SetViewport);
cameraComponent.BindMethod("SetZFar", &CameraComponent::SetZFar);
cameraComponent.BindMethod("SetZNear", &CameraComponent::SetZNear);
}
/*********************************** Ndk::GraphicsComponent **********************************/
graphicsComponent.Reset("GraphicsComponent");
{
graphicsComponent.BindMethod("Attach", [] (Nz::LuaState& lua, Ndk::GraphicsComponent* instance, std::size_t argumentCount) -> int
{
/*
void Attach(Nz::InstancedRenderableRef renderable, int renderOrder = 0);
void Attach(Nz::InstancedRenderableRef renderable, const Nz::Matrix4f& localMatrix, int renderOrder = 0);
*/
std::size_t argCount = std::min<std::size_t>(argumentCount, 3U);
switch (argCount)
{
case 1:
{
int argIndex = 2;
instance->Attach(lua.Check<Nz::InstancedRenderableRef>(&argIndex));
return 0;
}
case 2:
{
int argIndex = 2;
Nz::InstancedRenderableRef renderable = lua.Check<Nz::InstancedRenderableRef>(&argIndex);
if (lua.IsOfType(argIndex, Nz::LuaType_Number))
{
int renderOrder = lua.Check<int>(&argIndex);
instance->Attach(renderable, renderOrder);
}
else if (lua.IsOfType(argIndex, "Matrix4"))
{
Nz::Matrix4f localMatrix = lua.Check<Nz::Matrix4f>(&argIndex);
instance->Attach(renderable, localMatrix);
}
else
break;
return 0;
}
case 3:
{
int argIndex = 2;
Nz::InstancedRenderableRef renderable = lua.Check<Nz::InstancedRenderableRef>(&argIndex);
Nz::Matrix4f localMatrix = lua.Check<Nz::Matrix4f>(&argIndex);
int renderOrder = lua.Check<int>(&argIndex);
instance->Attach(renderable, localMatrix, renderOrder);
return 0;
}
}
lua.Error("No matching overload for method GetMemoryUsage");
return 0;
});
graphicsComponent.BindMethod("IsValidHandle", &GraphicsComponentHandle::IsValid);
}
#endif
// Components functions
m_binding.BindComponent<NodeComponent>("Node");
m_binding.BindComponent<VelocityComponent>("Velocity");
#ifndef NDK_SERVER
m_binding.BindComponent<CameraComponent>("Camera");
m_binding.BindComponent<GraphicsComponent>("Graphics");
#endif
}
/*!
* \brief Registers the classes that will be used by the Lua instance
*
* \param instance Lua instance that will interact with the SDK classes
*/
void LuaBinding_SDK::Register(Nz::LuaState& state)
{
// Classes
application.Register(state);
entity.Register(state);
nodeComponent.Register(state);
velocityComponent.Register(state);
world.Register(state);
#ifndef NDK_SERVER
cameraComponent.Register(state);
console.Register(state);
graphicsComponent.Register(state);
#endif
// Enums
}
/*!
* \brief Gets the index of the component
* \return A pointer to the binding linked to a component
*
* \param instance Lua instance that will interact with the component
* \param argIndex Index of the component
*/
LuaBinding::ComponentBinding* LuaBinding::QueryComponentIndex(Nz::LuaState& state, int argIndex)
{
switch (state.GetType(argIndex))
{
case Nz::LuaType_Number:
{
ComponentIndex componentIndex = state.Check<ComponentIndex>(&argIndex);
if (componentIndex > m_componentBinding.size())
{
state.Error("Invalid component index");
return nullptr;
}
ComponentBinding& binding = m_componentBinding[componentIndex];
if (binding.name.IsEmpty())
{
state.Error("Invalid component index");
return nullptr;
}
return &binding;
}
case Nz::LuaType_String:
{
const char* key = state.CheckString(argIndex);
auto it = m_componentBindingByName.find(key);
if (it == m_componentBindingByName.end())
{
state.Error("Invalid component name");
return nullptr;
}
return &m_componentBinding[it->second];
}
default:
break;
}
state.Error("Invalid component index at #" + Nz::String::Number(argIndex));
return nullptr;
}
}

View File

@ -1,338 +0,0 @@
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequisites.hpp
#include <NDK/Lua/LuaBinding_Utility.hpp>
#include <NDK/LuaAPI.hpp>
namespace Ndk
{
std::unique_ptr<LuaBinding_Base> LuaBinding_Base::BindUtility(LuaBinding& binding)
{
return std::make_unique<LuaBinding_Utility>(binding);
}
LuaBinding_Utility::LuaBinding_Utility(LuaBinding& binding) :
LuaBinding_Base(binding)
{
/*********************************** Nz::AbstractImage **********************************/
abstractImage.Reset("AbstractImage");
{
abstractImage.BindMethod("GetBytesPerPixel", &Nz::AbstractImage::GetBytesPerPixel);
abstractImage.BindMethod("GetDepth", &Nz::AbstractImage::GetDepth, static_cast<Nz::UInt8>(0));
abstractImage.BindMethod("GetFormat", &Nz::AbstractImage::GetFormat);
abstractImage.BindMethod("GetHeight", &Nz::AbstractImage::GetHeight, static_cast<Nz::UInt8>(0));
abstractImage.BindMethod("GetLevelCount", &Nz::AbstractImage::GetLevelCount);
abstractImage.BindMethod("GetMaxLevel", &Nz::AbstractImage::GetMaxLevel);
abstractImage.BindMethod("GetSize", &Nz::AbstractImage::GetSize, static_cast<Nz::UInt8>(0));
abstractImage.BindMethod("GetType", &Nz::AbstractImage::GetType);
abstractImage.BindMethod("GetWidth", &Nz::AbstractImage::GetWidth, static_cast<Nz::UInt8>(0));
abstractImage.BindMethod("IsCompressed", &Nz::AbstractImage::IsCompressed);
abstractImage.BindMethod("IsCubemap", &Nz::AbstractImage::IsCubemap);
abstractImage.BindMethod("GetMemoryUsage", [] (Nz::LuaState& lua, Nz::AbstractImage* instance, std::size_t argumentCount) -> int
{
std::size_t argCount = std::min<std::size_t>(argumentCount, 1U);
switch (argCount)
{
case 0:
return lua.Push(instance->GetMemoryUsage());
case 1:
{
int argIndex = 2;
Nz::UInt8 level(lua.Check<Nz::UInt8>(&argIndex));
return lua.Push(instance->GetMemoryUsage(level));
}
}
lua.Error("No matching overload for method GetMemoryUsage");
return 0;
});
abstractImage.BindMethod("Update", [] (Nz::LuaState& lua, Nz::AbstractImage* instance, std::size_t argumentCount) -> int
{
std::size_t argCount = std::min<std::size_t>(argumentCount, 6U);
int argIndex = 2;
std::size_t bufferSize = 0;
const Nz::UInt8* pixels = reinterpret_cast<const Nz::UInt8*>(lua.CheckString(argIndex++, &bufferSize));
if (argCount < 2 || lua.IsOfType(2, Nz::LuaType_Number))
{
// bool Update(const UInt8* pixels, unsigned int srcWidth = 0, unsigned int srcHeight = 0, UInt8 level = 0)
unsigned int srcWidth = lua.Check<unsigned int>(&argIndex, 0);
unsigned int srcHeight = lua.Check<unsigned int>(&argIndex, 0);
Nz::UInt8 level = lua.Check<Nz::UInt8>(&argIndex, 0);
///TODO: Buffer checks (Nz::ByteBufferView ?)
return lua.Push(instance->Update(pixels, srcWidth, srcHeight, level));
}
/* Disabled until Box and Rect have been ported
else if (lua.IsOfType(2, "Box"))
{
// bool Update(const UInt8* pixels, const Boxui& box, unsigned int srcWidth = 0, unsigned int srcHeight = 0, UInt8 level = 0)
Nz::Boxui box = lua.Check<Nz::Boxui>(&argIndex);
unsigned int srcWidth = lua.Check<unsigned int>(&argIndex, 0);
unsigned int srcHeight = lua.Check<unsigned int>(&argIndex, 0);
Nz::UInt8 level = lua.Check<Nz::UInt8>(&argIndex, 0);
///TODO: Buffer checks (Nz::ByteBufferView ?)
return lua.Push(abstractImage->Update(pixels, srcWidth, srcHeight, level));
}
else if (lua.IsOfType(2, "Rect"))
{
// bool Update(const UInt8* pixels, const Rectui& rect, unsigned int z = 0, unsigned int srcWidth = 0, unsigned int srcHeight = 0, UInt8 level = 0)
Nz::Rectui box = lua.Check<Nz::Rectui>(&argIndex);
unsigned int srcWidth = lua.Check<unsigned int>(&argIndex, 0);
unsigned int srcHeight = lua.Check<unsigned int>(&argIndex, 0);
Nz::UInt8 level = lua.Check<Nz::UInt8>(&argIndex, 0);
///TODO: Buffer checks (Nz::ByteBufferView ?)
return lua.Push(abstractImage->Update(pixels, srcWidth, srcHeight, level));
}*/
lua.Error("No matching overload for method Update");
return 0;
});
}
/*********************************** Nz::Font **********************************/
font.Reset("Font");
{
font.SetConstructor([] (Nz::LuaState& /*lua*/, Nz::FontRef* instance, std::size_t /*argumentCount*/)
{
Nz::PlacementNew(instance, Nz::Font::New());
return true;
});
font.BindMethod("ClearGlyphCache", &Nz::Font::ClearGlyphCache);
font.BindMethod("ClearKerningCache", &Nz::Font::ClearKerningCache);
font.BindMethod("ClearSizeInfoCache", &Nz::Font::ClearSizeInfoCache);
font.BindMethod("Destroy", &Nz::Font::Destroy);
font.BindMethod("GetCachedGlyphCount", [] (Nz::LuaState& lua, Nz::FontRef& instance, std::size_t argumentCount) -> int
{
std::size_t argCount = std::min<std::size_t>(argumentCount, 2U);
int argIndex = 2;
switch (argCount)
{
case 0:
lua.Push(instance->GetCachedGlyphCount());
return 1;
case 3:
{
unsigned int characterSize = lua.Check<unsigned int>(&argIndex);
Nz::TextStyleFlags style = lua.Check<Nz::TextStyleFlags>(&argIndex);
float outlineThickness = lua.Check<float>(&argIndex);
lua.Push(instance->GetCachedGlyphCount(characterSize, style, outlineThickness));
return 1;
}
}
lua.Error("No matching overload for method GetCachedGlyphCount");
return 0;
});
font.BindMethod("GetFamilyName", &Nz::Font::GetFamilyName);
font.BindMethod("GetKerning", &Nz::Font::GetKerning);
font.BindMethod("GetGlyphBorder", &Nz::Font::GetGlyphBorder);
font.BindMethod("GetMinimumStepSize", &Nz::Font::GetMinimumStepSize);
font.BindMethod("GetSizeInfo", &Nz::Font::GetSizeInfo);
font.BindMethod("GetStyleName", &Nz::Font::GetStyleName);
font.BindMethod("IsValid", &Nz::Font::IsValid);
font.BindMethod("Precache", (bool(Nz::Font::*)(unsigned int, Nz::TextStyleFlags, float, const Nz::String&) const) &Nz::Font::Precache);
font.BindMethod("SetGlyphBorder", &Nz::Font::SetGlyphBorder);
font.BindMethod("SetMinimumStepSize", &Nz::Font::SetMinimumStepSize);
font.BindStaticMethod("GetDefault", &Nz::Font::GetDefault);
font.BindStaticMethod("GetDefaultGlyphBorder", &Nz::Font::GetDefaultGlyphBorder);
font.BindStaticMethod("GetDefaultMinimumStepSize", &Nz::Font::GetDefaultMinimumStepSize);
font.BindStaticMethod("OpenFromFile", &Nz::Font::OpenFromFile, Nz::FontParams());
font.BindStaticMethod("SetDefaultGlyphBorder", &Nz::Font::SetDefaultGlyphBorder);
font.BindStaticMethod("SetDefaultMinimumStepSize", &Nz::Font::SetDefaultMinimumStepSize);
}
/*********************************** Nz::Node **********************************/
node.Reset("Node");
{
node.BindMethod("GetBackward", &Nz::Node::GetBackward);
//nodeClass.SetMethod("GetChilds", &Nz::Node::GetChilds);
node.BindMethod("GetDown", &Nz::Node::GetDown);
node.BindMethod("GetForward", &Nz::Node::GetForward);
node.BindMethod("GetInheritPosition", &Nz::Node::GetInheritPosition);
node.BindMethod("GetInheritRotation", &Nz::Node::GetInheritRotation);
node.BindMethod("GetInheritScale", &Nz::Node::GetInheritScale);
node.BindMethod("GetInitialPosition", &Nz::Node::GetInitialPosition);
//nodeClass.SetMethod("GetInitialRotation", &Nz::Node::GetInitialRotation);
node.BindMethod("GetInitialScale", &Nz::Node::GetInitialScale);
node.BindMethod("GetLeft", &Nz::Node::GetLeft);
node.BindMethod("GetNodeType", &Nz::Node::GetNodeType);
//nodeClass.SetMethod("GetParent", &Nz::Node::GetParent);
node.BindMethod("GetPosition", &Nz::Node::GetPosition, Nz::CoordSys_Global);
node.BindMethod("GetRight", &Nz::Node::GetRight);
//nodeClass.SetMethod("GetRotation", &Nz::Node::GetRotation, Nz::CoordSys_Global);
node.BindMethod("GetScale", &Nz::Node::GetScale, Nz::CoordSys_Global);
//nodeClass.SetMethod("GetTransformMatrix", &Nz::Node::GetTransformMatrix);
node.BindMethod("GetUp", &Nz::Node::GetUp);
node.BindMethod("HasChilds", &Nz::Node::HasChilds);
node.BindMethod("GetBackward", &Nz::Node::GetBackward);
node.BindMethod("GetDown", &Nz::Node::GetDown);
node.BindMethod("GetForward", &Nz::Node::GetForward);
node.BindMethod("GetInheritPosition", &Nz::Node::GetInheritPosition);
node.BindMethod("GetInheritRotation", &Nz::Node::GetInheritRotation);
node.BindMethod("GetInheritScale", &Nz::Node::GetInheritScale);
node.BindMethod("GetInitialPosition", &Nz::Node::GetInitialPosition);
node.BindMethod("GetInitialRotation", &Nz::Node::GetInitialRotation);
node.BindMethod("GetInitialScale", &Nz::Node::GetInitialScale);
node.BindMethod("GetLeft", &Nz::Node::GetLeft);
node.BindMethod("GetNodeType", &Nz::Node::GetNodeType);
node.BindMethod("GetPosition", &Nz::Node::GetPosition, Nz::CoordSys_Global);
node.BindMethod("GetRight", &Nz::Node::GetRight);
node.BindMethod("GetRotation", &Nz::Node::GetRotation, Nz::CoordSys_Global);
node.BindMethod("GetScale", &Nz::Node::GetScale, Nz::CoordSys_Global);
node.BindMethod("GetUp", &Nz::Node::GetUp);
node.BindMethod("SetInitialPosition", (void(Nz::Node::*)(const Nz::Vector3f&)) &Nz::Node::SetInitialPosition);
node.BindMethod("SetInitialRotation", (void(Nz::Node::*)(const Nz::Quaternionf&)) &Nz::Node::SetInitialRotation);
node.BindMethod("SetPosition", (void(Nz::Node::*)(const Nz::Vector3f&, Nz::CoordSys)) &Nz::Node::SetPosition, Nz::CoordSys_Local);
node.BindMethod("SetRotation", (void(Nz::Node::*)(const Nz::Quaternionf&, Nz::CoordSys)) &Nz::Node::SetRotation, Nz::CoordSys_Local);
node.BindMethod("Move", [] (Nz::LuaState& lua, Nz::Node& instance, std::size_t /*argumentCount*/) -> int
{
int argIndex = 2;
Nz::Vector3f offset = lua.Check<Nz::Vector3f>(&argIndex);
Nz::CoordSys coordSys = lua.Check<Nz::CoordSys>(&argIndex, Nz::CoordSys_Local);
instance.Move(offset, coordSys);
return 0;
});
node.BindMethod("Rotate", [] (Nz::LuaState& lua, Nz::Node& instance, std::size_t /*argumentCount*/) -> int
{
int argIndex = 2;
Nz::Quaternionf rotation = lua.Check<Nz::Quaternionf>(&argIndex);
Nz::CoordSys coordSys = lua.Check<Nz::CoordSys>(&argIndex, Nz::CoordSys_Local);
instance.Rotate(rotation, coordSys);
return 0;
});
node.BindMethod("Scale", [] (Nz::LuaState& lua, Nz::Node& instance, std::size_t argumentCount) -> int
{
std::size_t argCount = std::min<std::size_t>(argumentCount, 4U);
int argIndex = 2;
switch (argCount)
{
case 1:
{
if (lua.IsOfType(argIndex, Nz::LuaType_Number))
instance.Scale(lua.Check<float>(&argIndex));
else
instance.Scale(lua.Check<Nz::Vector3f>(&argIndex));
return 0;
}
case 3:
instance.Scale(lua.Check<Nz::Vector3f>(&argIndex));
return 0;
}
lua.Error("No matching overload for method Scale");
return 0;
});
node.BindMethod("SetScale", [] (Nz::LuaState& lua, Nz::Node& instance, std::size_t argumentCount) -> int
{
std::size_t argCount = std::min<std::size_t>(argumentCount, 4U);
int argIndex = 2;
switch (argCount)
{
case 1:
case 2:
{
if (lua.IsOfType(argIndex, Nz::LuaType_Number))
{
float scale = lua.Check<float>(&argIndex);
Nz::CoordSys coordSys = lua.Check<Nz::CoordSys>(&argIndex, Nz::CoordSys_Local);
instance.SetScale(scale, coordSys);
}
else
instance.SetScale(lua.Check<Nz::Vector3f>(&argIndex));
return 0;
}
case 3:
case 4:
{
Nz::Vector3f scale = lua.Check<Nz::Vector3f>(&argIndex);
Nz::CoordSys coordSys = lua.Check<Nz::CoordSys>(&argIndex, Nz::CoordSys_Local);
instance.SetScale(scale, coordSys);
return 0;
}
}
lua.Error("No matching overload for method SetScale");
return 0;
});
node.BindMethod("SetInitialScale", [] (Nz::LuaState& lua, Nz::Node& instance, std::size_t argumentCount) -> int
{
std::size_t argCount = std::min<std::size_t>(argumentCount, 4U);
int argIndex = 2;
switch (argCount)
{
case 1:
{
if (lua.IsOfType(argIndex, Nz::LuaType_Number))
instance.SetInitialScale(lua.Check<float>(&argIndex));
else
instance.SetInitialScale(lua.Check<Nz::Vector2f>(&argIndex));
return 0;
}
case 2:
case 3:
instance.SetInitialScale(lua.Check<Nz::Vector3f>(&argIndex));
return 0;
}
lua.Error("No matching overload for method SetInitialScale");
return 0;
});
}
}
/*!
* \brief Registers the classes that will be used by the Lua instance
*
* \param instance Lua instance that will interact with the Utility classes
*/
void LuaBinding_Utility::Register(Nz::LuaState& state)
{
abstractImage.Register(state);
font.Register(state);
node.Register(state);
}
}

View File

@ -1,63 +0,0 @@
// This file was automatically generated on 26 May 2014 at 01:05:31
#include <NDK/LuaAPI.hpp>
#include <Nazara/Core/ErrorFlags.hpp>
#include <NDK/Lua/LuaBinding.hpp>
namespace Ndk
{
/*!
* \ingroup NDK
* \class Ndk::LuaAPI
* \brief NDK class that represents the api used for Lua
*/
/*!
* \brief Gets the internal binding for Lua
* \return A pointer to the binding
*/
LuaBinding* LuaAPI::GetBinding()
{
if (!s_binding && !Initialize())
{
NazaraError("Failed to initialize binding");
return nullptr;
}
return s_binding;
}
/*!
* \brief Initializes the LuaAPI module
* \return true if initialization is successful
*/
bool LuaAPI::Initialize()
{
s_binding = new LuaBinding;
return true;
}
/*!
* \brief Registers the classes that will be used by the Lua instance
*
* \param instance Lua instance that will interact with the engine & SDK
*/
void LuaAPI::RegisterClasses(Nz::LuaState& state)
{
Nz::ErrorFlags errFlags(Nz::ErrorFlag_ThrowException, true);
GetBinding()->RegisterClasses(state);
}
/*!
* \brief Uninitializes the LuaAPI module
*/
void LuaAPI::Uninitialize()
{
delete s_binding;
}
LuaBinding* LuaAPI::s_binding = nullptr;
}

View File

@ -1,196 +0,0 @@
// Copyright (C) 2017 Jérôme Leclercq
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequisites.hpp
#include <NDK/Sdk.hpp>
#include <Nazara/Audio/Audio.hpp>
#include <Nazara/Core/ErrorFlags.hpp>
#include <Nazara/Core/Log.hpp>
#include <Nazara/Graphics/Graphics.hpp>
#include <Nazara/Lua/Lua.hpp>
#include <Nazara/Noise/Noise.hpp>
#include <Nazara/Physics2D/Physics2D.hpp>
#include <Nazara/Physics3D/Physics3D.hpp>
#include <Nazara/Platform/Platform.hpp>
#include <Nazara/Utility/Utility.hpp>
#include <NDK/Algorithm.hpp>
#include <NDK/BaseSystem.hpp>
#include <NDK/Components/CollisionComponent2D.hpp>
#include <NDK/Components/CollisionComponent3D.hpp>
#include <NDK/Components/LifetimeComponent.hpp>
#include <NDK/Components/NodeComponent.hpp>
#include <NDK/Components/PhysicsComponent2D.hpp>
#include <NDK/Components/PhysicsComponent3D.hpp>
#include <NDK/Components/VelocityComponent.hpp>
#include <NDK/Components/ConstraintComponent2D.hpp>
#include <NDK/Systems/LifetimeSystem.hpp>
#include <NDK/Systems/PhysicsSystem2D.hpp>
#include <NDK/Systems/PhysicsSystem3D.hpp>
#include <NDK/Systems/VelocitySystem.hpp>
#ifndef NDK_SERVER
#include <NDK/Components/CameraComponent.hpp>
#include <NDK/Components/DebugComponent.hpp>
#include <NDK/Components/LightComponent.hpp>
#include <NDK/Components/ListenerComponent.hpp>
#include <NDK/Components/GraphicsComponent.hpp>
#include <NDK/Components/ParticleEmitterComponent.hpp>
#include <NDK/Components/ParticleGroupComponent.hpp>
#include <NDK/Systems/DebugSystem.hpp>
#include <NDK/Systems/ParticleSystem.hpp>
#include <NDK/Systems/ListenerSystem.hpp>
#include <NDK/Systems/RenderSystem.hpp>
#include <NDK/Widgets/CheckboxWidget.hpp>
#endif
namespace Ndk
{
/*!
* \ingroup NDK
* \class Ndk::Sdk
* \brief NDK class that represents the software development kit, a set of tools made to ease the conception of application
*/
/*!
* \brief Initializes the Sdk module
* \return true if initialization is successful
*
* \remark Produces a NazaraNotice
*/
bool Sdk::Initialize()
{
if (s_referenceCounter++ > 0)
return true; // Already initialized
try
{
Nz::ErrorFlags errFlags(Nz::ErrorFlag_ThrowException, true);
// Initialize the engine first
// Shared modules
Nz::Lua::Initialize();
Nz::Noise::Initialize();
Nz::Physics2D::Initialize();
Nz::Physics3D::Initialize();
Nz::Utility::Initialize();
#ifndef NDK_SERVER
// Client modules
Nz::Audio::Initialize();
Nz::Graphics::Initialize();
#endif
// SDK Initialization
// Components
BaseComponent::Initialize();
// Shared components
InitializeComponent<CollisionComponent2D>("NdkColl2");
InitializeComponent<CollisionComponent3D>("NdkColl3");
InitializeComponent<LifetimeComponent>("NdkLiftm");
InitializeComponent<NodeComponent>("NdkNode");
InitializeComponent<PhysicsComponent2D>("NdkPhys2");
InitializeComponent<PhysicsComponent3D>("NdkPhys3");
InitializeComponent<VelocityComponent>("NdkVeloc");
InitializeComponent<VelocityComponent>("NdkCons2");
#ifndef NDK_SERVER
// Client components
InitializeComponent<CameraComponent>("NdkCam");
InitializeComponent<DebugComponent>("NdkDebug");
InitializeComponent<LightComponent>("NdkLight");
InitializeComponent<ListenerComponent>("NdkList");
InitializeComponent<GraphicsComponent>("NdkGfx");
InitializeComponent<ParticleEmitterComponent>("NdkPaEmi");
InitializeComponent<ParticleGroupComponent>("NdkPaGrp");
#endif
// Systems
BaseSystem::Initialize();
// Shared systems
InitializeSystem<LifetimeSystem>();
InitializeSystem<PhysicsSystem2D>();
InitializeSystem<PhysicsSystem3D>();
InitializeSystem<VelocitySystem>();
#ifndef NDK_SERVER
// Client systems
InitializeSystem<DebugSystem>();
InitializeSystem<ListenerSystem>();
InitializeSystem<ParticleSystem>();
InitializeSystem<RenderSystem>();
// Widgets
if (!CheckboxWidget::Initialize())
{
NazaraError("Failed to initialize Checkbox Widget");
return false;
}
#endif
NazaraNotice("Initialized: SDK");
return true;
}
catch (const std::exception& e)
{
NazaraError("Failed to initialize NDK: " + Nz::String(e.what()));
return false;
}
}
/*!
* \brief Uninitializes the Sdk module
*
* \remark Produces a NazaraNotice
*/
void Sdk::Uninitialize()
{
if (s_referenceCounter != 1)
{
// Either the module is not initialized, either it was initialized multiple times
if (s_referenceCounter > 1)
s_referenceCounter--;
return;
}
// Uninitialize the SDK
s_referenceCounter = 0;
// Components
BaseComponent::Uninitialize();
// Systems
BaseSystem::Uninitialize();
// Uninitialize the engine
#ifndef NDK_SERVER
// Client modules
Nz::Audio::Uninitialize();
Nz::Graphics::Uninitialize();
#endif
// Shared modules
Nz::Lua::Uninitialize();
Nz::Noise::Uninitialize();
Nz::Physics2D::Uninitialize();
Nz::Physics3D::Uninitialize();
Nz::Utility::Uninitialize();
#ifndef NDK_SERVER
// Widgets
CheckboxWidget::Uninitialize();
#endif
NazaraNotice("Uninitialized: SDK");
}
unsigned int Sdk::s_referenceCounter = 0;
}

View File

@ -1,526 +0,0 @@
// Copyright (C) 2017 Jérôme Leclercq
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequisites.hpp
#include <NDK/Systems/DebugSystem.hpp>
#include <Nazara/Core/Primitive.hpp>
#include <Nazara/Graphics/Model.hpp>
#include <Nazara/Utility/IndexIterator.hpp>
#include <Nazara/Utility/Mesh.hpp>
#include <Nazara/Utility/StaticMesh.hpp>
#include <NDK/Components/CollisionComponent2D.hpp>
#include <NDK/Components/CollisionComponent3D.hpp>
#include <NDK/Components/DebugComponent.hpp>
#include <NDK/Components/GraphicsComponent.hpp>
#include <NDK/Components/NodeComponent.hpp>
#include <NDK/Components/PhysicsComponent2D.hpp>
namespace Ndk
{
namespace
{
class DebugRenderable : public Nz::InstancedRenderable
{
public:
DebugRenderable(Ndk::Entity* owner, Nz::IndexBufferRef indexBuffer, Nz::VertexBufferRef vertexBuffer) :
m_entityOwner(owner),
m_indexBuffer(std::move(indexBuffer)),
m_vertexBuffer(std::move(vertexBuffer))
{
ResetMaterials(1);
m_meshData.indexBuffer = m_indexBuffer;
m_meshData.primitiveMode = Nz::PrimitiveMode_LineList;
m_meshData.vertexBuffer = m_vertexBuffer;
}
void UpdateBoundingVolume(InstanceData* /*instanceData*/) const override
{
}
void MakeBoundingVolume() const override
{
// We generate an infinite bounding volume so that we're always considered for rendering when culling does occurs
// (bounding volume culling happens only if GraphicsComponent AABB partially fail)
m_boundingVolume.MakeInfinite();
}
protected:
Ndk::EntityHandle m_entityOwner;
Nz::IndexBufferRef m_indexBuffer;
Nz::MeshData m_meshData;
Nz::VertexBufferRef m_vertexBuffer;
};
class AABBDebugRenderable : public DebugRenderable
{
public:
AABBDebugRenderable(Ndk::Entity* owner, Nz::MaterialRef globalMaterial, Nz::MaterialRef localMaterial, Nz::IndexBufferRef indexBuffer, Nz::VertexBufferRef vertexBuffer) :
DebugRenderable(owner, std::move(indexBuffer), std::move(vertexBuffer)),
m_globalMaterial(std::move(globalMaterial)),
m_localMaterial(std::move(localMaterial))
{
}
void AddToRenderQueue(Nz::AbstractRenderQueue* renderQueue, const InstanceData& instanceData, const Nz::Recti& scissorRect) const override
{
NazaraAssert(m_entityOwner, "DebugRenderable has no owner");
const DebugComponent& entityDebug = m_entityOwner->GetComponent<DebugComponent>();
const GraphicsComponent& entityGfx = m_entityOwner->GetComponent<GraphicsComponent>();
auto DrawBox = [&](const Nz::Boxf& box, const Nz::MaterialRef& mat)
{
Nz::Matrix4f transformMatrix = Nz::Matrix4f::Identity();
transformMatrix.SetScale(box.GetLengths());
transformMatrix.SetTranslation(box.GetCenter());
renderQueue->AddMesh(0, mat, m_meshData, Nz::Boxf::Zero(), transformMatrix, scissorRect);
};
DrawBox(entityGfx.GetAABB(), m_globalMaterial);
for (std::size_t i = 0; i < entityGfx.GetAttachedRenderableCount(); ++i)
{
const Nz::BoundingVolumef& boundingVolume = entityGfx.GetBoundingVolume(i);
if (boundingVolume.IsFinite())
DrawBox(boundingVolume.aabb, m_localMaterial);
}
}
std::unique_ptr<InstancedRenderable> Clone() const override
{
return nullptr;
}
private:
Nz::MaterialRef m_globalMaterial;
Nz::MaterialRef m_localMaterial;
};
class OBBDebugRenderable : public DebugRenderable
{
public:
OBBDebugRenderable(Ndk::Entity* owner, Nz::MaterialRef material, Nz::IndexBufferRef indexBuffer, Nz::VertexBufferRef vertexBuffer) :
DebugRenderable(owner, std::move(indexBuffer), std::move(vertexBuffer)),
m_material(std::move(material))
{
}
void AddToRenderQueue(Nz::AbstractRenderQueue* renderQueue, const InstanceData& instanceData, const Nz::Recti& scissorRect) const override
{
NazaraAssert(m_entityOwner, "DebugRenderable has no owner");
const DebugComponent& entityDebug = m_entityOwner->GetComponent<DebugComponent>();
const GraphicsComponent& entityGfx = m_entityOwner->GetComponent<GraphicsComponent>();
auto DrawBox = [&](const Nz::Boxf& box, const Nz::Matrix4f& transformMatrix)
{
Nz::Matrix4f boxMatrix = Nz::Matrix4f::Identity();
boxMatrix.SetScale(box.GetLengths());
boxMatrix.SetTranslation(box.GetCenter());
boxMatrix.ConcatenateAffine(transformMatrix);
renderQueue->AddMesh(0, m_material, m_meshData, Nz::Boxf::Zero(), boxMatrix, scissorRect);
};
for (std::size_t i = 0; i < entityGfx.GetAttachedRenderableCount(); ++i)
{
const Nz::BoundingVolumef& boundingVolume = entityGfx.GetBoundingVolume(i);
if (boundingVolume.IsFinite())
DrawBox(boundingVolume.obb.localBox, entityGfx.GetTransformMatrix(i));
}
}
std::unique_ptr<InstancedRenderable> Clone() const override
{
return nullptr;
}
private:
Nz::MaterialRef m_material;
};
}
/*!
* \ingroup NDK
* \class Ndk::DebugSystem
* \brief NDK class that represents the debug system
*
* \remark This system is enabled if the entity owns the trait: DebugComponent and GraphicsComponent
*/
/*!
* \brief Constructs an DebugSystem object by default
*/
DebugSystem::DebugSystem() :
m_isDepthBufferEnabled(true)
{
Requires<DebugComponent, GraphicsComponent, NodeComponent>();
SetUpdateOrder(1000); //< Update last
}
void DebugSystem::EnableDepthBuffer(bool enable)
{
m_isDepthBufferEnabled = enable;
if (m_collisionMaterial)
m_collisionMaterial->EnableDepthBuffer(enable);
if (m_globalAabbMaterial)
m_globalAabbMaterial->EnableDepthBuffer(enable);
if (m_localAabbMaterial)
m_localAabbMaterial->EnableDepthBuffer(enable);
if (m_obbMaterial)
m_obbMaterial->EnableDepthBuffer(enable);
}
Nz::InstancedRenderableRef DebugSystem::GenerateBox(Nz::Boxf box)
{
Nz::MeshRef mesh = Nz::Mesh::New();
mesh->CreateStatic();
mesh->BuildSubMesh(Nz::Primitive::Box(box.GetLengths()));
mesh->SetMaterialCount(1);
Nz::ModelRef model = Nz::Model::New();
model->SetMesh(mesh);
model->SetMaterial(0, GetOBBMaterial());
return model;
}
Nz::InstancedRenderableRef DebugSystem::GenerateCollision2DMesh(Entity* entity, Nz::Vector3f* offset)
{
if (entity->HasComponent<CollisionComponent2D>())
{
CollisionComponent2D& entityCollision = entity->GetComponent<CollisionComponent2D>();
const Nz::Collider2DRef& geom = entityCollision.GetGeom();
std::vector<Nz::Vector3f> vertices;
std::vector<std::size_t> indices;
geom->ForEachPolygon([&](const Nz::Vector2f* polygonVertices, std::size_t vertexCount)
{
std::size_t firstIndex = vertices.size();
// Don't reserve and let the vector handle its own capacity
for (std::size_t i = 0; i < vertexCount; ++i)
vertices.emplace_back(*polygonVertices++);
for (std::size_t i = 0; i < vertexCount - 1; ++i)
{
indices.push_back(firstIndex + i);
indices.push_back(firstIndex + i + 1);
}
indices.push_back(firstIndex + vertexCount - 1);
indices.push_back(firstIndex);
});
Nz::IndexBufferRef indexBuffer = Nz::IndexBuffer::New(vertices.size() > 0xFFFF, Nz::UInt32(indices.size()), Nz::DataStorage_Hardware, 0);
Nz::IndexMapper indexMapper(indexBuffer, Nz::BufferAccess_WriteOnly);
Nz::IndexIterator indexPtr = indexMapper.begin();
for (std::size_t index : indices)
*indexPtr++ = static_cast<Nz::UInt32>(index);
indexMapper.Unmap();
Nz::VertexBufferRef vertexBuffer = Nz::VertexBuffer::New(Nz::VertexDeclaration::Get(Nz::VertexLayout_XYZ), Nz::UInt32(vertices.size()), Nz::DataStorage_Hardware, 0);
vertexBuffer->Fill(vertices.data(), 0, Nz::UInt32(vertices.size()));
Nz::MeshRef mesh = Nz::Mesh::New();
mesh->CreateStatic();
Nz::StaticMeshRef subMesh = Nz::StaticMesh::New(vertexBuffer, indexBuffer);
subMesh->SetPrimitiveMode(Nz::PrimitiveMode_LineList);
subMesh->SetMaterialIndex(0);
subMesh->GenerateAABB();
mesh->SetMaterialCount(1);
mesh->AddSubMesh(subMesh);
Nz::ModelRef model = Nz::Model::New();
model->SetMesh(mesh);
model->SetMaterial(0, GetCollisionMaterial());
// Find center of mass
if (entity->HasComponent<PhysicsComponent2D>())
{
const PhysicsComponent2D& entityPhys = entity->GetComponent<PhysicsComponent2D>();
*offset = entityPhys.GetMassCenter(Nz::CoordSys_Local) + entityCollision.GetGeomOffset();
}
else
*offset = entityCollision.GetGeomOffset();
return model;
}
else
return nullptr;
}
Nz::InstancedRenderableRef DebugSystem::GenerateCollision3DMesh(Entity* entity)
{
if (entity->HasComponent<CollisionComponent3D>())
{
CollisionComponent3D& entityCollision = entity->GetComponent<CollisionComponent3D>();
const Nz::Collider3DRef& geom = entityCollision.GetGeom();
std::vector<Nz::Vector3f> vertices;
std::vector<std::size_t> indices;
geom->ForEachPolygon([&](const Nz::Vector3f* polygonVertices, std::size_t vertexCount)
{
std::size_t firstIndex = vertices.size();
vertices.resize(firstIndex + vertexCount);
std::copy(polygonVertices, polygonVertices + vertexCount, &vertices[firstIndex]);
for (std::size_t i = 0; i < vertexCount - 1; ++i)
{
indices.push_back(firstIndex + i);
indices.push_back(firstIndex + i + 1);
}
indices.push_back(firstIndex + vertexCount - 1);
indices.push_back(firstIndex);
});
Nz::IndexBufferRef indexBuffer = Nz::IndexBuffer::New(vertices.size() > 0xFFFF, Nz::UInt32(indices.size()), Nz::DataStorage_Hardware, 0);
Nz::IndexMapper indexMapper(indexBuffer, Nz::BufferAccess_WriteOnly);
Nz::IndexIterator indexPtr = indexMapper.begin();
for (std::size_t index : indices)
*indexPtr++ = static_cast<Nz::UInt32>(index);
indexMapper.Unmap();
Nz::VertexBufferRef vertexBuffer = Nz::VertexBuffer::New(Nz::VertexDeclaration::Get(Nz::VertexLayout_XYZ), Nz::UInt32(vertices.size()), Nz::DataStorage_Hardware, 0);
vertexBuffer->Fill(vertices.data(), 0, Nz::UInt32(vertices.size()));
Nz::MeshRef mesh = Nz::Mesh::New();
mesh->CreateStatic();
Nz::StaticMeshRef subMesh = Nz::StaticMesh::New(vertexBuffer, indexBuffer);
subMesh->SetPrimitiveMode(Nz::PrimitiveMode_LineList);
subMesh->SetMaterialIndex(0);
subMesh->GenerateAABB();
mesh->SetMaterialCount(1);
mesh->AddSubMesh(subMesh);
Nz::ModelRef model = Nz::Model::New();
model->SetMesh(mesh);
model->SetMaterial(0, GetCollisionMaterial());
return model;
}
else
return nullptr;
}
std::pair<Nz::IndexBufferRef, Nz::VertexBufferRef> DebugSystem::GetBoxMesh()
{
if (!m_boxMeshIndexBuffer)
{
std::array<Nz::UInt16, 24> indices = {
{
0, 1,
1, 2,
2, 3,
3, 0,
4, 5,
5, 6,
6, 7,
7, 4,
0, 4,
1, 5,
2, 6,
3, 7
}
};
m_boxMeshIndexBuffer = Nz::IndexBuffer::New(false, Nz::UInt32(indices.size()), Nz::DataStorage_Hardware, 0);
m_boxMeshIndexBuffer->Fill(indices.data(), 0, Nz::UInt32(indices.size()));
}
if (!m_boxMeshVertexBuffer)
{
Nz::Boxf box(-0.5f, -0.5f, -0.5f, 1.f, 1.f, 1.f);
std::array<Nz::Vector3f, 8> positions = {
{
box.GetCorner(Nz::BoxCorner_FarLeftBottom),
box.GetCorner(Nz::BoxCorner_NearLeftBottom),
box.GetCorner(Nz::BoxCorner_NearRightBottom),
box.GetCorner(Nz::BoxCorner_FarRightBottom),
box.GetCorner(Nz::BoxCorner_FarLeftTop),
box.GetCorner(Nz::BoxCorner_NearLeftTop),
box.GetCorner(Nz::BoxCorner_NearRightTop),
box.GetCorner(Nz::BoxCorner_FarRightTop)
}
};
m_boxMeshVertexBuffer = Nz::VertexBuffer::New(Nz::VertexDeclaration::Get(Nz::VertexLayout_XYZ), Nz::UInt32(positions.size()), Nz::DataStorage_Hardware, 0);
m_boxMeshVertexBuffer->Fill(positions.data(), 0, Nz::UInt32(positions.size()));
}
return { m_boxMeshIndexBuffer, m_boxMeshVertexBuffer };
}
Nz::MaterialRef DebugSystem::GetGlobalAABBMaterial()
{
if (!m_globalAabbMaterial)
{
m_globalAabbMaterial = Nz::Material::New();
m_globalAabbMaterial->EnableFaceCulling(false);
m_globalAabbMaterial->EnableDepthBuffer(true);
m_globalAabbMaterial->SetDiffuseColor(Nz::Color::Orange);
m_globalAabbMaterial->SetFaceFilling(Nz::FaceFilling_Line);
//m_globalAabbMaterial->SetLineWidth(2.f);
}
return m_globalAabbMaterial;
}
Nz::MaterialRef DebugSystem::GetLocalAABBMaterial()
{
if (!m_localAabbMaterial)
{
m_localAabbMaterial = Nz::Material::New();
m_localAabbMaterial->EnableFaceCulling(false);
m_localAabbMaterial->EnableDepthBuffer(true);
m_localAabbMaterial->SetDiffuseColor(Nz::Color::Red);
m_localAabbMaterial->SetFaceFilling(Nz::FaceFilling_Line);
//m_localAabbMaterial->SetLineWidth(2.f);
}
return m_localAabbMaterial;
}
Nz::MaterialRef DebugSystem::GetCollisionMaterial()
{
if (!m_collisionMaterial)
{
m_collisionMaterial = Nz::Material::New();
m_collisionMaterial->EnableFaceCulling(false);
m_collisionMaterial->EnableDepthBuffer(true);
m_collisionMaterial->SetDiffuseColor(Nz::Color::Blue);
m_collisionMaterial->SetFaceFilling(Nz::FaceFilling_Line);
//m_collisionMaterial->SetLineWidth(2.f);
}
return m_collisionMaterial;
}
Nz::MaterialRef DebugSystem::GetOBBMaterial()
{
if (!m_obbMaterial)
{
m_obbMaterial = Nz::Material::New();
m_obbMaterial->EnableFaceCulling(false);
m_obbMaterial->EnableDepthBuffer(true);
m_obbMaterial->SetDiffuseColor(Nz::Color::Green);
m_obbMaterial->SetFaceFilling(Nz::FaceFilling_Line);
//m_obbMaterial->SetLineWidth(2.f);
}
return m_obbMaterial;
}
void DebugSystem::OnEntityValidation(Entity* entity, bool /*justAdded*/)
{
static constexpr int DebugDrawOrder = 1'000;
DebugComponent& entityDebug = entity->GetComponent<DebugComponent>();
GraphicsComponent& entityGfx = entity->GetComponent<GraphicsComponent>();
NodeComponent& entityNode = entity->GetComponent<NodeComponent>();
DebugDrawFlags enabledFlags = entityDebug.GetEnabledFlags();
DebugDrawFlags flags = entityDebug.GetFlags();
DebugDrawFlags flagsToEnable = flags & ~enabledFlags;
for (std::size_t i = 0; i <= static_cast<std::size_t>(DebugDraw::Max); ++i)
{
DebugDraw option = static_cast<DebugDraw>(i);
if (flagsToEnable & option)
{
switch (option)
{
case DebugDraw::Collider2D:
{
Nz::Vector3f offset;
Nz::InstancedRenderableRef renderable = GenerateCollision2DMesh(entity, &offset);
if (renderable)
entityGfx.Attach(renderable, Nz::Matrix4f::Translate(offset), DebugDrawOrder);
entityDebug.UpdateDebugRenderable(option, std::move(renderable));
break;
}
case DebugDraw::Collider3D:
{
const Nz::Boxf& obb = entityGfx.GetAABB();
Nz::InstancedRenderableRef renderable = GenerateCollision3DMesh(entity);
if (renderable)
entityGfx.Attach(renderable, Nz::Matrix4f::Translate(obb.GetCenter() - entityNode.GetPosition()), DebugDrawOrder);
entityDebug.UpdateDebugRenderable(option, std::move(renderable));
break;
}
case DebugDraw::GraphicsAABB:
{
auto indexVertexBuffers = GetBoxMesh();
Nz::InstancedRenderableRef renderable = new AABBDebugRenderable(entity, GetGlobalAABBMaterial(), GetLocalAABBMaterial(), indexVertexBuffers.first, indexVertexBuffers.second);
renderable->SetPersistent(false);
entityGfx.Attach(renderable, Nz::Matrix4f::Identity(), DebugDrawOrder);
entityDebug.UpdateDebugRenderable(option, std::move(renderable));
break;
}
case DebugDraw::GraphicsOBB:
{
auto indexVertexBuffers = GetBoxMesh();
Nz::InstancedRenderableRef renderable = new OBBDebugRenderable(entity, GetOBBMaterial(), indexVertexBuffers.first, indexVertexBuffers.second);
renderable->SetPersistent(false);
entityGfx.Attach(renderable, Nz::Matrix4f::Identity(), DebugDrawOrder);
entityDebug.UpdateDebugRenderable(option, std::move(renderable));
break;
}
default:
break;
}
}
}
DebugDrawFlags flagsToDisable = enabledFlags & ~flags;
for (std::size_t i = 0; i <= static_cast<std::size_t>(DebugDraw::Max); ++i)
{
DebugDraw option = static_cast<DebugDraw>(i);
if (flagsToDisable & option)
entityGfx.Detach(entityDebug.GetDebugRenderable(option));
}
entityDebug.UpdateEnabledFlags(flags);
}
void DebugSystem::OnUpdate(float elapsedTime)
{
// Nothing to do
}
SystemIndex DebugSystem::systemIndex;
}

View File

@ -1,44 +0,0 @@
// Copyright (C) 2017 Jérôme Leclercq
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequisites.hpp
#include <NDK/Systems/ParticleSystem.hpp>
#include <NDK/Components/ParticleGroupComponent.hpp>
namespace Ndk
{
/*!
* \ingroup NDK
* \class Ndk::ParticleSystem
* \brief NDK class that represents the particle system
*
* \remark This system is enabled if the entity has the trait: NodeComponent and any of these two: ParticleGroupComponent
*/
/*!
* \brief Constructs an ParticleSystem object by default
*/
ParticleSystem::ParticleSystem()
{
Requires<ParticleGroupComponent>();
}
/*!
* \brief Operation to perform when system is updated
*
* \param elapsedTime Delta time used for the update
*/
void ParticleSystem::OnUpdate(float elapsedTime)
{
for (const Ndk::EntityHandle& entity : GetEntities())
{
ParticleGroupComponent& group = entity->GetComponent<ParticleGroupComponent>();
group.Update(elapsedTime);
}
}
SystemIndex ParticleSystem::systemIndex;
}

View File

@ -1,428 +0,0 @@
// Copyright (C) 2017 Jérôme Leclercq
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequisites.hpp
#include <NDK/Systems/RenderSystem.hpp>
#include <Nazara/Graphics/ColorBackground.hpp>
#include <Nazara/Graphics/ForwardRenderTechnique.hpp>
#include <Nazara/Graphics/SceneData.hpp>
#include <Nazara/Graphics/SkinningManager.hpp>
#include <Nazara/Graphics/SkyboxBackground.hpp>
#include <Nazara/Math/Rect.hpp>
#include <Nazara/Renderer/Renderer.hpp>
#include <NDK/Components/CameraComponent.hpp>
#include <NDK/Components/GraphicsComponent.hpp>
#include <NDK/Components/LightComponent.hpp>
#include <NDK/Components/NodeComponent.hpp>
#include <NDK/Components/ParticleGroupComponent.hpp>
namespace Ndk
{
/*!
* \ingroup NDK
* \class Ndk::RenderSystem
* \brief NDK class that represents the rendering system
*
* \remark This system is enabled if the entity is a 'camera' with the trait: CameraComponent and NodeComponent
* or a drawable element with trait: GraphicsComponent and NodeComponent
* or a light element with trait: LightComponent and NodeComponent
* or a set of particles with trait: ParticleGroupComponent
*/
/*!
* \brief Constructs an RenderSystem object by default
*/
RenderSystem::RenderSystem() :
m_coordinateSystemMatrix(Nz::Matrix4f::Identity()),
m_coordinateSystemInvalidated(true),
m_forceRenderQueueInvalidation(false),
m_isCullingEnabled(true)
{
ChangeRenderTechnique<Nz::ForwardRenderTechnique>();
SetDefaultBackground(Nz::ColorBackground::New());
SetUpdateOrder(100); //< Render last, after every movement is done
SetMaximumUpdateRate(0.f); //< We don't want any rate limit
}
/*!
* \brief Operation to perform when an entity is removed
*
* \param entity Pointer to the entity
*/
void RenderSystem::OnEntityRemoved(Entity* entity)
{
m_forceRenderQueueInvalidation = true; //< Hackfix until lights and particles are handled by culling list
for (auto it = m_cameras.begin(); it != m_cameras.end(); ++it)
{
if (it->GetObject() == entity)
{
m_cameras.erase(it);
break;
}
}
if (entity->HasComponent<GraphicsComponent>())
{
GraphicsComponent& gfxComponent = entity->GetComponent<GraphicsComponent>();
gfxComponent.RemoveFromCullingList(&m_drawableCulling);
}
}
/*!
* \brief Operation to perform when entity is validated for the system
*
* \param entity Pointer to the entity
* \param justAdded Is the entity newly added
*/
void RenderSystem::OnEntityValidation(Entity* entity, bool justAdded)
{
NazaraUnused(justAdded);
if (entity->HasComponent<CameraComponent>() && entity->HasComponent<NodeComponent>())
{
m_cameras.emplace_back(entity);
std::sort(m_cameras.begin(), m_cameras.end(), [](const EntityHandle& handle1, const EntityHandle& handle2)
{
return handle1->GetComponent<CameraComponent>().GetLayer() < handle2->GetComponent<CameraComponent>().GetLayer();
});
}
else
{
for (auto it = m_cameras.begin(); it != m_cameras.end(); ++it)
{
if (it->GetObject() == entity)
{
m_cameras.erase(it);
break;
}
}
}
if (entity->HasComponent<GraphicsComponent>() && entity->HasComponent<NodeComponent>())
{
m_drawables.Insert(entity);
GraphicsComponent& gfxComponent = entity->GetComponent<GraphicsComponent>();
if (justAdded)
gfxComponent.AddToCullingList(&m_drawableCulling);
if (gfxComponent.DoesRequireRealTimeReflections())
m_realtimeReflected.Insert(entity);
else
m_realtimeReflected.Remove(entity);
}
else
{
m_drawables.Remove(entity);
m_realtimeReflected.Remove(entity);
if (entity->HasComponent<GraphicsComponent>())
{
GraphicsComponent& gfxComponent = entity->GetComponent<GraphicsComponent>();
gfxComponent.RemoveFromCullingList(&m_drawableCulling);
}
}
if (entity->HasComponent<LightComponent>() && entity->HasComponent<NodeComponent>())
{
m_forceRenderQueueInvalidation = true; //< Hackfix until lights and particles are handled by culling list
LightComponent& lightComponent = entity->GetComponent<LightComponent>();
if (lightComponent.GetLightType() == Nz::LightType_Directional)
{
m_directionalLights.Insert(entity);
m_pointSpotLights.Remove(entity);
}
else
{
m_directionalLights.Remove(entity);
m_pointSpotLights.Insert(entity);
}
m_lights.Insert(entity);
}
else
{
m_forceRenderQueueInvalidation = true; //< Hackfix until lights and particles are handled by culling list
m_directionalLights.Remove(entity);
m_lights.Remove(entity);
m_pointSpotLights.Remove(entity);
}
if (entity->HasComponent<ParticleGroupComponent>())
{
m_forceRenderQueueInvalidation = true; //< Hackfix until lights and particles are handled by culling list
m_particleGroups.Insert(entity);
}
else
{
m_forceRenderQueueInvalidation = true; //< Hackfix until lights and particles are handled by culling list
m_particleGroups.Remove(entity);
}
}
/*!
* \brief Operation to perform when system is updated
*
* \param elapsedTime Delta time used for the update
*/
void RenderSystem::OnUpdate(float /*elapsedTime*/)
{
// Invalidate every renderable if the coordinate system changed
if (m_coordinateSystemInvalidated)
{
for (const Ndk::EntityHandle& drawable : m_drawables)
{
GraphicsComponent& graphicsComponent = drawable->GetComponent<GraphicsComponent>();
graphicsComponent.InvalidateTransformMatrix();
}
m_coordinateSystemInvalidated = false;
}
Nz::SkinningManager::Skin();
UpdateDynamicReflections();
UpdatePointSpotShadowMaps();
for (const Ndk::EntityHandle& camera : m_cameras)
{
CameraComponent& camComponent = camera->GetComponent<CameraComponent>();
//UpdateDirectionalShadowMaps(camComponent);
Nz::AbstractRenderQueue* renderQueue = m_renderTechnique->GetRenderQueue();
// To make sure the bounding volumes used by the culling list is updated
for (const Ndk::EntityHandle& drawable : m_drawables)
{
GraphicsComponent& graphicsComponent = drawable->GetComponent<GraphicsComponent>();
graphicsComponent.EnsureBoundingVolumesUpdate();
}
bool forceInvalidation = false;
const Nz::Frustumf& frustum = camComponent.GetFrustum();
std::size_t visibilityHash;
if (m_isCullingEnabled)
visibilityHash = m_drawableCulling.Cull(frustum, &forceInvalidation);
else
visibilityHash = m_drawableCulling.FillWithAllEntries(&forceInvalidation);
// Always regenerate renderqueue if particle groups are present for now (FIXME)
if (!m_lights.empty() || !m_particleGroups.empty())
forceInvalidation = true;
if (camComponent.UpdateVisibility(visibilityHash) || m_forceRenderQueueInvalidation || forceInvalidation)
{
renderQueue->Clear();
for (const GraphicsComponent* gfxComponent : m_drawableCulling.GetFullyVisibleResults())
gfxComponent->AddToRenderQueue(renderQueue);
for (const GraphicsComponent* gfxComponent : m_drawableCulling.GetPartiallyVisibleResults())
gfxComponent->AddToRenderQueueByCulling(frustum, renderQueue);
for (const Ndk::EntityHandle& light : m_lights)
{
LightComponent& lightComponent = light->GetComponent<LightComponent>();
NodeComponent& lightNode = light->GetComponent<NodeComponent>();
///TODO: Cache somehow?
lightComponent.AddToRenderQueue(renderQueue, Nz::Matrix4f::ConcatenateAffine(m_coordinateSystemMatrix, lightNode.GetTransformMatrix()));
}
for (const Ndk::EntityHandle& particleGroup : m_particleGroups)
{
ParticleGroupComponent& groupComponent = particleGroup->GetComponent<ParticleGroupComponent>();
groupComponent.AddToRenderQueue(renderQueue, Nz::Matrix4f::Identity()); //< ParticleGroup doesn't use any transform matrix (yet)
}
m_forceRenderQueueInvalidation = false;
}
camComponent.ApplyView();
Nz::SceneData sceneData;
sceneData.ambientColor = Nz::Color(25, 25, 25);
sceneData.background = m_background;
sceneData.globalReflectionTexture = nullptr;
sceneData.viewer = &camComponent;
if (m_background && m_background->GetBackgroundType() == Nz::BackgroundType_Skybox)
sceneData.globalReflectionTexture = static_cast<Nz::SkyboxBackground*>(m_background.Get())->GetTexture();
m_renderTechnique->Clear(sceneData);
m_renderTechnique->Draw(sceneData);
}
}
/*!
* \brief Updates the directional shadow maps according to the position of the viewer
*
* \param viewer Viewer of the scene
*/
void RenderSystem::UpdateDynamicReflections()
{
Nz::SceneData dummySceneData;
dummySceneData.ambientColor = Nz::Color(0, 0, 0);
dummySceneData.background = nullptr;
dummySceneData.viewer = nullptr; //< Depth technique doesn't require any viewer
for (const Ndk::EntityHandle& handle : m_realtimeReflected)
{
//NazaraWarning("Realtime reflected: #" + handle->ToString());
}
}
void RenderSystem::UpdateDirectionalShadowMaps(const Nz::AbstractViewer& /*viewer*/)
{
if (!m_shadowRT.IsValid())
m_shadowRT.Create();
Nz::SceneData dummySceneData;
dummySceneData.ambientColor = Nz::Color(0, 0, 0);
dummySceneData.background = nullptr;
dummySceneData.viewer = nullptr; //< Depth technique doesn't require any viewer
for (const Ndk::EntityHandle& light : m_directionalLights)
{
LightComponent& lightComponent = light->GetComponent<LightComponent>();
NodeComponent& lightNode = light->GetComponent<NodeComponent>();
if (!lightComponent.IsShadowCastingEnabled())
continue;
Nz::Vector2ui shadowMapSize(lightComponent.GetShadowMap()->GetSize());
m_shadowRT.AttachTexture(Nz::AttachmentPoint_Depth, 0, lightComponent.GetShadowMap());
Nz::Renderer::SetTarget(&m_shadowRT);
Nz::Renderer::SetViewport(Nz::Recti(0, 0, shadowMapSize.x, shadowMapSize.y));
Nz::AbstractRenderQueue* renderQueue = m_shadowTechnique.GetRenderQueue();
renderQueue->Clear();
///TODO: Culling
for (const Ndk::EntityHandle& drawable : m_drawables)
{
GraphicsComponent& graphicsComponent = drawable->GetComponent<GraphicsComponent>();
graphicsComponent.AddToRenderQueue(renderQueue);
}
///TODO: Cache the matrices in the light?
Nz::Renderer::SetMatrix(Nz::MatrixType_Projection, Nz::Matrix4f::Ortho(0.f, 100.f, 100.f, 0.f, 1.f, 100.f));
Nz::Renderer::SetMatrix(Nz::MatrixType_View, Nz::Matrix4f::ViewMatrix(lightNode.GetRotation() * Nz::Vector3f::Forward() * 100.f, lightNode.GetRotation()));
m_shadowTechnique.Clear(dummySceneData);
m_shadowTechnique.Draw(dummySceneData);
}
}
/*!
* \brief Updates the point spot shadow maps
*/
void RenderSystem::UpdatePointSpotShadowMaps()
{
if (!m_shadowRT.IsValid())
m_shadowRT.Create();
Nz::SceneData dummySceneData;
dummySceneData.ambientColor = Nz::Color(0, 0, 0);
dummySceneData.background = nullptr;
dummySceneData.viewer = nullptr; //< Depth technique doesn't require any viewer
for (const Ndk::EntityHandle& light : m_pointSpotLights)
{
LightComponent& lightComponent = light->GetComponent<LightComponent>();
NodeComponent& lightNode = light->GetComponent<NodeComponent>();
if (!lightComponent.IsShadowCastingEnabled())
continue;
Nz::Vector2ui shadowMapSize(lightComponent.GetShadowMap()->GetSize());
switch (lightComponent.GetLightType())
{
case Nz::LightType_Directional:
NazaraInternalError("Directional lights included in point/spot light list");
break;
case Nz::LightType_Point:
{
static Nz::Quaternionf rotations[6] =
{
Nz::Quaternionf::RotationBetween(Nz::Vector3f::Forward(), Nz::Vector3f::UnitX()), // CubemapFace_PositiveX
Nz::Quaternionf::RotationBetween(Nz::Vector3f::Forward(), -Nz::Vector3f::UnitX()), // CubemapFace_NegativeX
Nz::Quaternionf::RotationBetween(Nz::Vector3f::Forward(), -Nz::Vector3f::UnitY()), // CubemapFace_PositiveY
Nz::Quaternionf::RotationBetween(Nz::Vector3f::Forward(), Nz::Vector3f::UnitY()), // CubemapFace_NegativeY
Nz::Quaternionf::RotationBetween(Nz::Vector3f::Forward(), -Nz::Vector3f::UnitZ()), // CubemapFace_PositiveZ
Nz::Quaternionf::RotationBetween(Nz::Vector3f::Forward(), Nz::Vector3f::UnitZ()) // CubemapFace_NegativeZ
};
for (unsigned int face = 0; face < 6; ++face)
{
m_shadowRT.AttachTexture(Nz::AttachmentPoint_Depth, 0, lightComponent.GetShadowMap(), face);
Nz::Renderer::SetTarget(&m_shadowRT);
Nz::Renderer::SetViewport(Nz::Recti(0, 0, shadowMapSize.x, shadowMapSize.y));
///TODO: Cache the matrices in the light?
Nz::Renderer::SetMatrix(Nz::MatrixType_Projection, Nz::Matrix4f::Perspective(Nz::FromDegrees(90.f), 1.f, 0.1f, lightComponent.GetRadius()));
Nz::Renderer::SetMatrix(Nz::MatrixType_View, Nz::Matrix4f::ViewMatrix(lightNode.GetPosition(), rotations[face]));
Nz::AbstractRenderQueue* renderQueue = m_shadowTechnique.GetRenderQueue();
renderQueue->Clear();
///TODO: Culling
for (const Ndk::EntityHandle& drawable : m_drawables)
{
GraphicsComponent& graphicsComponent = drawable->GetComponent<GraphicsComponent>();
graphicsComponent.AddToRenderQueue(renderQueue);
}
m_shadowTechnique.Clear(dummySceneData);
m_shadowTechnique.Draw(dummySceneData);
}
break;
}
case Nz::LightType_Spot:
{
m_shadowRT.AttachTexture(Nz::AttachmentPoint_Depth, 0, lightComponent.GetShadowMap());
Nz::Renderer::SetTarget(&m_shadowRT);
Nz::Renderer::SetViewport(Nz::Recti(0, 0, shadowMapSize.x, shadowMapSize.y));
///TODO: Cache the matrices in the light?
Nz::Renderer::SetMatrix(Nz::MatrixType_Projection, Nz::Matrix4f::Perspective(lightComponent.GetOuterAngle()*2.f, 1.f, 0.1f, lightComponent.GetRadius()));
Nz::Renderer::SetMatrix(Nz::MatrixType_View, Nz::Matrix4f::ViewMatrix(lightNode.GetPosition(), lightNode.GetRotation()));
Nz::AbstractRenderQueue* renderQueue = m_shadowTechnique.GetRenderQueue();
renderQueue->Clear();
///TODO: Culling
for (const Ndk::EntityHandle& drawable : m_drawables)
{
GraphicsComponent& graphicsComponent = drawable->GetComponent<GraphicsComponent>();
graphicsComponent.AddToRenderQueue(renderQueue);
}
m_shadowTechnique.Clear(dummySceneData);
m_shadowTechnique.Draw(dummySceneData);
break;
}
}
}
}
SystemIndex RenderSystem::systemIndex;
}

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