This commit is contained in:
2025-05-13 02:46:21 +03:00
parent 143e16692e
commit 86914b7fcc
610 changed files with 92343 additions and 2 deletions
+211
View File
@@ -0,0 +1,211 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="12.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{8BE9EDA5-A27E-48BF-BBA7-36139D47F5D9}</ProjectGuid>
<RootNamespace>LifeGame</RootNamespace>
<Keyword>Win32Proj</Keyword>
<SccProjectName>&lt;Project Location In Database&gt;</SccProjectName>
<SccAuxPath>&lt;Source Control Database&gt;</SccAuxPath>
<SccLocalPath>&lt;Local Binding Root of Project&gt;</SccLocalPath>
<SccProvider>Mercurial Source Control Package</SccProvider>
<VCTargetsPath Condition="'$(VCTargetsPath11)' != '' and '$(VSVersion)' == '' and $(VisualStudioVersion) == ''">$(VCTargetsPath11)</VCTargetsPath>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>StaticLibrary</ConfigurationType>
<CharacterSet>MultiByte</CharacterSet>
<WholeProgramOptimization>true</WholeProgramOptimization>
<PlatformToolset>v120</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>StaticLibrary</ConfigurationType>
<CharacterSet>MultiByte</CharacterSet>
<WholeProgramOptimization>true</WholeProgramOptimization>
<PlatformToolset>v120</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>StaticLibrary</ConfigurationType>
<CharacterSet>MultiByte</CharacterSet>
<PlatformToolset>v120</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>StaticLibrary</ConfigurationType>
<CharacterSet>MultiByte</CharacterSet>
<PlatformToolset>v120</PlatformToolset>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup>
<_ProjectFileVersion>10.0.30319.1</_ProjectFileVersion>
<OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)$(ProjectName)\lib\</OutDir>
<OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(SolutionDir)\lib\$(Configuration)\</OutDir>
<IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)$(ProjectName)\tmp\$(Configuration)\</IntDir>
<IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(Configuration)\$(ProjectName)</IntDir>
<OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)$(ProjectName)\lib\</OutDir>
<OutDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(SolutionDir)\lib\$(Configuration)\</OutDir>
<IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)$(ProjectName)\tmp\$(Configuration)\</IntDir>
<IntDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(Configuration)\</IntDir>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<TargetName>$(ProjectName)_d</TargetName>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<Optimization>Disabled</Optimization>
<AdditionalIncludeDirectories>$(REPO_DIR)/angelscript/include;$(REPO_DIR)\bullet-2.78\src;$(SolutionDir)\LifeGraphics\src;.\src;$(SolutionDir)\LifeCore\src;$(SolutionDir)\LifeGUI\src;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;_DEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<MinimalRebuild>false</MinimalRebuild>
<BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
<RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>EditAndContinue</DebugInformationFormat>
<MultiProcessorCompilation>true</MultiProcessorCompilation>
</ClCompile>
<Lib>
<AdditionalDependencies>LifeGUI_d.lib;angelscriptd.lib;LifeGraphics_d.lib;LifeCore_d.lib;%(AdditionalDependencies)</AdditionalDependencies>
<OutputFile>lib\LifeGame_d.lib</OutputFile>
<AdditionalLibraryDirectories>$(SolutionDir)\LifeGUI\lib;$(SolutionDir)\LifeGraphics\lib;$(REPO_DIR)/angelscript/lib;$(REPO_DIR)\bullet-2.78\bullet-2.78\lib;$(DXSDK_DIR)\Lib\x86;$(SolutionDir)\LifeCore\lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Lib>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<Optimization>Disabled</Optimization>
<AdditionalIncludeDirectories>$(REPO_DIR)/angelscript/include;$(REPO_DIR)\bullet-2.78\src;$(SolutionDir)\LifeEngine\include;.\include;$(SolutionDir)\LifeCore\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;_DEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<MinimalRebuild>false</MinimalRebuild>
<BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
<RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
<MultiProcessorCompilation>true</MultiProcessorCompilation>
</ClCompile>
<Lib>
<AdditionalDependencies>angelscriptd.lib;LifeEngine_d.lib;LifeCore_d.lib;%(AdditionalDependencies)</AdditionalDependencies>
<OutputFile>lib\LifeGame_d.lib</OutputFile>
<AdditionalLibraryDirectories>$(SolutionDir)\LifeEngine\lib;$(REPO_DIR)/angelscript/lib;$(REPO_DIR)\bullet-2.78\bullet-2.78\lib;$(DXSDK_DIR)\Lib\x86;$(SolutionDir)\LifeCore\lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Lib>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<Optimization>MaxSpeed</Optimization>
<IntrinsicFunctions>true</IntrinsicFunctions>
<AdditionalIncludeDirectories>$(REPO_DIR)/angelscript/include;$(REPO_DIR)\bullet-2.78\src;$(SolutionDir)\LifeGraphics\src;.\src;$(SolutionDir)\LifeCore\src;$(SolutionDir)\LifeGUI\src;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;NDEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
<FunctionLevelLinking>true</FunctionLevelLinking>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
<MultiProcessorCompilation>true</MultiProcessorCompilation>
</ClCompile>
<Lib>
<AdditionalDependencies>OIS_Static.lib;%(AdditionalDependencies)</AdditionalDependencies>
<OutputFile>lib\LifeGame.lib</OutputFile>
<AdditionalLibraryDirectories>$(SolutionDir)\LifeEngine\lib;$(REPO_DIR)\bullet-2.78\bullet-2.78\lib;$(REPO_DIR)\ois-v1-3\lib;$(DXSDK_DIR)\Lib\x86;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Lib>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<Optimization>MaxSpeed</Optimization>
<IntrinsicFunctions>true</IntrinsicFunctions>
<AdditionalIncludeDirectories>$(REPO_DIR)/angelscript/include;$(REPO_DIR)\bullet-2.78\src;$(REPO_DIR)\ois-v1-3\includes;$(SolutionDir)\LifeEngine\include;.\include;$(SolutionDir)\LifeCore\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;NDEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
<FunctionLevelLinking>true</FunctionLevelLinking>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
<MultiProcessorCompilation>true</MultiProcessorCompilation>
</ClCompile>
<Lib>
<AdditionalDependencies>OIS_Static.lib;%(AdditionalDependencies)</AdditionalDependencies>
<OutputFile>lib\LifeGame.lib</OutputFile>
<AdditionalLibraryDirectories>$(SolutionDir)\LifeEngine\lib;$(REPO_DIR)\bullet-2.78\bullet-2.78\lib;$(REPO_DIR)\ois-v1-3\lib;$(DXSDK_DIR)\Lib\x86;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Lib>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="src\Action.cpp" />
<ClCompile Include="src\ActionSystem.cpp" />
<ClCompile Include="src\CGUIDataManager.cpp" />
<ClCompile Include="src\CGUIRenderer.cpp" />
<ClCompile Include="src\CImage.cpp" />
<ClCompile Include="src\Entity.cpp" />
<ClCompile Include="src\Game.cpp" />
<ClCompile Include="src\GOCCameraFree.cpp" />
<ClCompile Include="src\IGraphicsEntity.cpp" />
<ClCompile Include="src\IPhysicsEntity.cpp" />
<ClCompile Include="src\InputActionProvider.cpp" />
<ClCompile Include="src\script\Script.cpp" />
<ClCompile Include="src\script\ScriptSystem.cpp" />
<ClCompile Include="src\World.cpp" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="src\Action.h" />
<ClInclude Include="src\ActionSystem.h" />
<ClInclude Include="src\BulletLibs.h" />
<ClInclude Include="src\CGUIDataManager.h" />
<ClInclude Include="src\CGUIRenderer.h" />
<ClInclude Include="src\CImage.h" />
<ClInclude Include="src\Entity.h" />
<ClInclude Include="src\EntityFactory.h" />
<ClInclude Include="src\Game.h" />
<ClInclude Include="src\GameCamera.h" />
<ClInclude Include="src\GameGlobals.h" />
<ClInclude Include="src\GOCCameraFree.h" />
<ClInclude Include="src\GOCLogic.h" />
<ClInclude Include="src\GOComponent.h" />
<ClInclude Include="src\Graphics.h" />
<ClInclude Include="src\GUIOutput.h" />
<ClInclude Include="src\IActionListener.h" />
<ClInclude Include="src\IActionProvider.h" />
<ClInclude Include="src\IGraphicsEntity.h" />
<ClInclude Include="src\InputActionProvider.h" />
<ClInclude Include="src\IPhysicsEntity.h" />
<ClInclude Include="src\IPhysicsWorld.h" />
<ClInclude Include="src\IScriptEntity.h" />
<ClInclude Include="src\script\Script.h" />
<ClInclude Include="src\script\ScriptSystem.h" />
<ClInclude Include="src\World.h" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>
+28
View File
@@ -0,0 +1,28 @@
#include "Action.h"
#include <assert.h>
#include "IActionListener.h"
namespace LifeGame
{
Action::Action(const ActionId& id)
:actionId(id){
}
void Action::AddListener(LifeGame::IActionListener* listener){
lock.lock();
listeners.push_back(listener);
lock.unlock();
}
void Action::RemoveListener(LifeGame::IActionListener* listener){
assert(false && "Not implemented yet");
}
void Action::Execute(const ActionParam& param){
lock.lock();
for(auto listener : listeners)
listener->OnAction(actionId, param);
lock.unlock();
}
const ActionId& Action::GetID(){
return actionId;
}
}
+37
View File
@@ -0,0 +1,37 @@
#ifndef Action_h__
#define Action_h__
#include <LString.h>
#include <vector>
#include <mutex>
namespace LifeGame
{
struct ActionParam{
union action_val{
int si32_val;
float f_val;
};
action_val val;
};
typedef String ActionId;
class IActionListener;
class Action final
{
public:
Action(const ActionId& id);
void AddListener(LifeGame::IActionListener* listener);
void RemoveListener(LifeGame::IActionListener* listener);
void Execute(const ActionParam& param);
const ActionId& GetID();
private:
typedef std::vector<LifeGame::IActionListener*> ActionListenerCollection;
typedef std::vector<LifeGame::IActionListener*>::iterator ActionListenerCollectionIt;
ActionListenerCollection listeners;
ActionId actionId;
std::mutex lock;
};
}
#endif // Action_h__
+33
View File
@@ -0,0 +1,33 @@
#include "ActionSystem.h"
#include <mutex>
namespace LifeGame
{
Action* ActionSystem::AddAction(const ActionId& id){
std::lock_guard<std::mutex> lg(action_mutex);
auto action = GetActionNoLock(id);
if(action == nullptr){
Action* act = new Action(id);
actions[id] = act;
return act;
}
return action;
}
Action* ActionSystem::GetAction(const ActionId& id){
std::lock_guard<std::mutex> lg(action_mutex);
return GetActionNoLock(id);
}
Action* ActionSystem::GetActionNoLock(const ActionId& id){
auto it = actions.find(id);
if(it != actions.end())
return it->second;
return nullptr;
}
void ActionSystem::DoAction(const ActionId& id, const ActionParam& param){
std::lock_guard<std::mutex> lg(action_mutex);
Action* act = GetActionNoLock(id);
if(act != nullptr){
act->Execute(param);
}
}
}
+28
View File
@@ -0,0 +1,28 @@
#ifndef EventSystem_h__
#define EventSystem_h__
#include <Singleton.h>
#include <mutex>
#include "Action.h"
#include <map>
namespace LifeGame
{
class ActionSystem : public Singleton<ActionSystem>
{
friend class Singleton<ActionSystem>;
public:
~ActionSystem(){};
Action* AddAction(const ActionId& id);
Action* GetAction(const ActionId& id);
void DoAction(const ActionId& id, const ActionParam& param);
private:
Action* GetActionNoLock(const ActionId& id);
ActionSystem(){};
typedef std::map<ActionId, Action*> ActionCollection;
typedef std::map<ActionId, Action*>::iterator ActionCollectionIt;
ActionCollection actions;
std::mutex action_mutex;
};
}
#endif // EventSystem_h__
+12
View File
@@ -0,0 +1,12 @@
#ifndef BulletLibs_h__
#define BulletLibs_h__
#pragma comment (lib, "BulletCollision.lib")
#pragma comment (lib, "BulletDynamics.lib")
#pragma comment (lib, "BulletSoftBody.lib")
#pragma comment (lib, "LinearMath.lib")
#pragma comment (lib, "ConvexDecomposition.lib")
#pragma comment (lib, "BulletMultiThreaded.lib")
#pragma comment (lib, "GIMPACTUtils.lib")
#endif // BulletLibs_h__
+21
View File
@@ -0,0 +1,21 @@
#include "CGUIDataManager.h"
#include <ResourceManager.h>
#include "CImage.h"
namespace LifeGame
{
LifeCore::IFileSystem* CGUIDataManager::getFileSystem(){
return LifeGraphics::ResourceManager::me()->getFileSystem();
}
LifeGUI::IImage* CGUIDataManager::getImage(const String& name){
LifeGraphics::ITexture2D* tex = LifeGraphics::ResourceManager::me()->GetTexture(AS_STRING("root/Data/GUI/") + name).ptr();
return CImage::FromTexture(tex);
}
const String CGUIDataManager::getGuiRootDir(){
return AS_STRING("root/Data/GUI/");
}
LifeGUI::IImage* CGUIDataManager::createImage(uint32 width, uint32 height){
LifeGraphics::ITexture2D* tex = LifeGraphics::CG::me()->GetRenderer()->CreateTexture2D(0, 1, width, height, FORMAT_R8G8B8A8_UNORM);
return CImage::FromTexture(tex);
}
}
+17
View File
@@ -0,0 +1,17 @@
#ifndef CGUIDataManager_h__
#define CGUIDataManager_h__
#include <IGUIDataManager.h>
namespace LifeGame
{
class CGUIDataManager : public LifeGUI::IGUIDataManager
{
public:
LifeCore::IFileSystem* getFileSystem();
LifeGUI::IImage* getImage(const String& name);
const String getGuiRootDir() override;
LifeGUI::IImage* createImage(uint32 width, uint32 height);
};
}
#endif // CGUIDataManager_h__
+121
View File
@@ -0,0 +1,121 @@
#include "CGUIRenderer.h"
#include "ResourceManager.h"
#include "CImage.h"
#include <GUIManager.h>
namespace LifeGame
{
CGUIRenderer::CGUIRenderer(LifeGraphics::IRenderer* renderer)
:scr_w(320), scr_h(240)
{
pRenderer = renderer;
blendState = pRenderer->CreateBlendState(true, false, BLEND_OP_ADD, BLEND_SRC_ALPHA, BLEND_INV_SRC_ALPHA, 1 | 2 | 4 | 8);
depthState = pRenderer->CreateDSState(false, false, COMPARISON_NEVER);
cb = pRenderer->CreateConstantBuffer(sizeof(LifeMath::float4));
LifeMath::float4 c((float)scr_w, (float)scr_h,0,0);
cb->Update(&c, sizeof(LifeMath::float4));
vsGui = LifeGraphics::ResourceManager::me()->CompileUserShaderVS(AS_STRING("GUI.vsh"));
psGui = LifeGraphics::ResourceManager::me()->CompileUserShaderPS(AS_STRING("GUI.psh"));
LifeGraphics::IInputElement elements[] =
{
LifeGraphics::IInputElement("POSITION", 0, 0, FORMAT_R32G32B32_FLOAT, 0, 0, 0),
LifeGraphics::IInputElement("WidgetColor", 0, 12, FORMAT_R32G32B32A32_FLOAT, 0, 0, 0),
LifeGraphics::IInputElement("TEXCOORD", 0, 28, FORMAT_R32G32B32A32_FLOAT, 0, 0, 0),
LifeGraphics::IInputElement("TileInfo", 0, 44, FORMAT_R32G32B32A32_FLOAT, 0, 0, 0),
};
ilGui = renderer->CreateInputLayout(elements, 4, vsGui);
//vb = renderer->CreateVertexBuffer(MAX_GUI_VERTEX_COUNT * sizeof(LifeGUI::GUIVertex), buffer->GetData(), sizeof(LifeGUI::GUIVertex));
vb = renderer->CreateVertexBufferDynamic(MAX_GUI_VERTEX_COUNT * sizeof(LifeGUI::GUIVertex), sizeof(LifeGUI::GUIVertex));
LifeGraphics::ISamplerDescription psDesc(LifeGraphics::Wrap, LifeGraphics::Wrap, LifeGraphics::Wrap, LifeGraphics::MinMagMipPoint);
pointSampler = renderer->CreateTextureSampler(&psDesc);
}
void CGUIRenderer::Render()
{
//printf("Batch ID: %i\n", batch_id);
if(buffer->Tell())
{
vb->Map(0, LifeGraphics::LF_Discard | LifeGraphics::LF_NoOverwrite)->Write(buffer->GetData(), buffer->Tell());
vb->Unmap();
//vb->Update(buffer->GetData(), buffer->Tell());
LifeMath::Rect2i vp(scr_w, scr_h);
pRenderer->SetViewport(vp);
pRenderer->SetScissorRectangle(vp);
pRenderer->SetVertexShader(vsGui);
pRenderer->SetPixelShader(psGui);
pRenderer->SetVertexBuffer(vb);
pRenderer->SetVSConstantBuffer(cb, 0);
pRenderer->SetInputLayout(ilGui);
pRenderer->SetPSTextureSampler(pointSampler, 0);
pRenderer->SetDepthStencilState(depthState);
pRenderer->SetBlendState(blendState);
pRenderer->SetPrimitiveTopology(PT_TRIANGLE_LIST);
int prev_topology = PT_TRIANGLE_LIST;
int tmp_topology;
size_t offset = 0;
for(size_t i = 0; i <= batch_id; i++)
{
LifeGUI::GUIBatch* b = &batch[i];
if(b->vertex_count > 0)
{
tmp_topology = b->lines ? PT_LINE_LIST : PT_TRIANGLE_LIST;
if(prev_topology != tmp_topology)
{
prev_topology = tmp_topology;
pRenderer->SetPrimitiveTopology((PRIMITIVE_TOPOLOGY)tmp_topology);
}
CImage* tex;
if(b->tex)
{
tex = reinterpret_cast<CImage*>(b->tex);
pRenderer->SetPSTexture(tex->GetTexture(), 0);
}
else{
pRenderer->SetPSTexture(reinterpret_cast<CImage*>(LifeGUI::GUIManager::me()->DIFF)->GetTexture(), 0);
}
if(b->font)
{
tex = reinterpret_cast<CImage*>(b->font);
pRenderer->SetPSTexture(tex->GetTexture(), 1);
}
pRenderer->Draw(b->vertex_count, offset);
offset += b->vertex_count;
}
}
}
}
void CGUIRenderer::SetScissor(const LifeMath::Rect2i& rect)
{
pRenderer->SetScissorRectangle(rect);
pRenderer->SetViewport(rect);
}
void CGUIRenderer::SetScreenSize(int w, int h)
{
scr_w = w;
scr_h = h;
LifeMath::float4 c((float)scr_w, (float)scr_h,0,0);
cb->Update(&c, sizeof(LifeMath::float4));
}
}
+31
View File
@@ -0,0 +1,31 @@
#ifndef CGUIRenderer_h__
#define CGUIRenderer_h__
#include <render/IRenderer.h>
#include <IGUIRenderer.h>
#include <IImage.h>
namespace LifeGame
{
class CGUIRenderer : public LifeGUI::IGUIRenderer
{
public:
CGUIRenderer(LifeGraphics::IRenderer* renderer);
void Render();
void SetScissor(const LifeMath::Rect2i& rect);
void SetScreenSize(int w, int h);
private:
LifeGraphics::IRenderer* pRenderer;
LifeGraphics::IShader* vsGui;
LifeGraphics::IShader* psGui;
LifeGraphics::IInputLayout* ilGui;
LifeGraphics::ITextureSampler* pointSampler;
LifeGraphics::IConstantBuffer* cb;
LifeGraphics::IVertexBuffer* vb;
LifeGraphics::IBlendState* blendState;
LifeGraphics::IDepthStencilState* depthState;
int scr_w, scr_h;
};
}
#endif // CGUIRenderer_h__
+64
View File
@@ -0,0 +1,64 @@
#include "CImage.h"
namespace LifeGame
{
CImage::CImage()
:pTex(0)
{
}
LifeCore::IDataRectangle* CImage::Map(uint32 level, bool read, bool write){
return pTex->Map(level, read, write);
}
void CImage::Unmap(uint32 level){
pTex->Unmap(level);
}
CImage* CImage::FromTexture(LifeGraphics::ITexture2D* src)
{
CImage* pic = new CImage();
pic->pTex = src;
return pic;
}
void CImage::Reset(LifeGraphics::ITexture2D* src)
{
pTex = src;
}
size_t CImage::GetID()
{
return pTex->GetID();
}
uint32 CImage::GetWidth()
{
return pTex->Width();
}
uint32 CImage::GetHeight()
{
return pTex->Height();
}
uint32 CImage::GetPixelSize()
{
return pTex->bpp;
}
void CImage::SetPixel(uint32 x, uint32 y, const void* data)
{
}
void CImage::GetPixel(uint32 x, uint32 y, void* data)
{
}
void CImage::SetData(const void* data, uint32 size)
{
}
void CImage::SetData(const void* data, const LifeMath::Rect2i& area)
{
}
void CImage::GetData(void* data, uint32 size)
{
}
void CImage::GetData(void* data, const LifeMath::Rect2i& area)
{
}
LifeGraphics::ITexture2D* CImage::GetTexture()
{
return pTex;
}
}
+34
View File
@@ -0,0 +1,34 @@
#ifndef CImage_h__
#define CImage_h__
#include "render/IRenderer.h"
#include "IImage.h"
namespace LifeGame
{
class CImage : public LifeGUI::IImage
{
public:
static CImage* FromTexture(LifeGraphics::ITexture2D* src);
size_t GetID();
uint32 GetWidth();
uint32 GetHeight();
uint32 GetPixelSize();
void SetPixel(uint32 x, uint32 y, const void* data);
void GetPixel(uint32 x, uint32 y, void* data);
void SetData(const void* data, uint32 size);
void SetData(const void* data, const LifeMath::Rect2i& area);
void GetData(void* data, uint32 size);
void GetData(void* data, const LifeMath::Rect2i& area);
void Reset(LifeGraphics::ITexture2D* src);
LifeGraphics::ITexture2D* GetTexture();
LifeCore::IDataRectangle* Map(uint32 level, bool read, bool write);
void Unmap(uint32 level);
private:
CImage();
LifeGraphics::ITexture2D* pTex;
};
}
#endif // CPicture_h__
+114
View File
@@ -0,0 +1,114 @@
#include "Entity.h"
namespace LifeGame
{
Entity::Entity()
:bEnabled(true)
{
physics = NULL;
graphics = NULL;
bPhysicalized = false;
name = "unnamed_entity";
}
Entity::~Entity()
{
}
void Entity::SetEnabled(bool state)
{
bEnabled = state;
}
bool Entity::IsEnabled()
{
return bEnabled;
}
const String& Entity::GetName() const
{
return name;
}
void Entity::SetName(const String& _name)
{
name = _name;
}
void Entity::Update(float timeElapsed){
for(auto logic : logic_components){
logic->Update(timeElapsed);
}
}
void Entity::Save()
{
pugi::xml_document doc;
pugi::xml_node root = doc.append_child("Entity");
root.append_attribute("Name") = this->name.c_str();
root.append_attribute("bGraphics") = (graphics != NULL);
root.append_attribute("bPhysics") = (physics != NULL);
if(graphics)
{
pugi::xml_node visual = root.append_child("Graphics");
//mesh block
visual.append_attribute("MeshFile") = (graphics->pMesh->Name).c_str();
//mesh->materials block
pugi::xml_node materials = visual.append_child("Materials");
for(int i = 0; i<graphics->pMesh->getSumbeshCount(); i++)
{
materials.append_attribute("ID") = i;
materials.append_attribute("Name") = graphics->pMesh->getMaterial(i)->GetBaseMaterial()->Name.c_str();
}
}
if(physics)
{
pugi::xml_node phys = root.append_child("Physics");
phys.append_attribute("fMass") = physics->GetMass();
phys.append_attribute("bStatic") = physics->IsStatic();
phys.append_attribute("fFriction") = 0.27f;
phys.append_attribute("sMeshName") = "Level2.ocf";
}
{
pugi::xml_node game = root.append_child("Game");
// game.append_attribute("bPlayer") = IsPlayer();
game.append_attribute("sScript") ="Actors/basic_player.lua";
}
LifeXMLWriter writer;
doc.print(writer);
LifeCore::IFile* file;
LifeGraphics::ResourceManager::me()->getFileSystem()->GetFile(AS_STRING("root/Data/Entities/") + name + AS_STRING(".xml"), &file);
LifeCore::IDataStreamPtr stm = file->OpenWrite(0);
stm->Write(writer.result.c_str(), writer.length);
stm.release();
}
void Entity::SetPhysicsEntity(IPhysicsEntity* _phys)
{
physics = _phys;
}
void Entity::SetGraphicalEntity(IGraphicsEntity* _graph)
{
graphics = _graph;
graphics->pMesh->SetTransform(&transform);
}
IPhysicsEntity* Entity::GetPhysicsEntity()
{
return physics;
}
IGraphicsEntity* Entity::GetGraphicalEntity()
{
return graphics;
}
void Entity::CallScriptEvent(String eventName)
{
}
LifeCore::ITransform* Entity::GetTransform()
{
return &transform;
}
void Entity::AddLogicEntity(GOCLogic* logic){
if(logic != nullptr){
logic_components.push_back(logic);
}
}
}
+93
View File
@@ -0,0 +1,93 @@
#ifndef Entity_h__
#define Entity_h__
#include "IGraphicsEntity.h"
#include "IPhysicsEntity.h"
#include <ITransform.h>
#include "LString.h"
#include "XML.h"
#include "Action.h"
#include "GOCLogic.h"
namespace LifeGame
{
enum ScriptEvent
{
ScriptEvent_Activate = 0x00000001,
ScriptEvent_Deactivate ,
ScriptEvent_FireModeChange ,
ScriptEvent_DropItem ,
ScriptEvent_Reset ,
ScriptEvent_Contact ,
ScriptEvent_Enter ,
ScriptEvent_Leave ,
ScriptEvent_Timer ,
ScriptEvent_StartAnimation ,
ScriptEvent_AnimationKey ,
ScriptEvent_EndAnimation ,
ScriptEvent_Respawn ,
ScriptEvent_ItemActivated ,
ScriptEvent_Hit ,
ScriptEvent_Fire ,
ScriptEvent_WeaponReady ,
ScriptEvent_StopFiring ,
ScriptEvent_Reload ,
ScriptEvent_Command ,
ScriptEvent_FireGrenade ,
ScriptEvent_Die ,
ScriptEvent_ZoomToggle ,
ScriptEvent_ZoomIn ,
ScriptEvent_ZoomOut ,
ScriptEvent_Land ,
ScriptEvent_FireCancel ,
ScriptEvent_GameDefinedEvent ,
ScriptEvent_ViewModeChange ,
ScriptEvent_SelectWeapon,
ScriptEvent_Deafened,
ScriptEvent_StanceChange,
ScriptEvent_CycleGrenade,
ScriptEvent_Use,
ScriptEvent_MeleeAttack,
ScriptEvent_PhysicalizeOnDemand,
ScriptEvent_PhysCollision,
ScriptEvent_FlashLightSwitch,
ScriptEvent_EnterWater,
ScriptEvent_CycleVehiclePos,
ScriptEvent_AllClear,
ScriptEvent_Expression,
ScriptEvent_InVehicleAnimation,
ScriptEvent_InVehicleAmmo,
ScriptEvent_ProcessCharacterEffects,
ScriptEvent_Jump,
};
class Entity
{
public:
Entity();
virtual ~Entity();
void SetEnabled(bool state);
bool IsEnabled();
const String& GetName() const;
void SetName(const String& _name);
virtual void Update(float timeElapsed);
void Save();
void SetPhysicsEntity(IPhysicsEntity* _phys);
void SetGraphicalEntity(IGraphicsEntity* _graph);
IPhysicsEntity* GetPhysicsEntity();
IGraphicsEntity* GetGraphicalEntity();
void CallScriptEvent(String eventName);
LifeCore::ITransform* GetTransform();
void AddLogicEntity(GOCLogic* logic);
private:
IPhysicsEntity* physics;
IGraphicsEntity* graphics;
bool bPhysicalized;
LifeCore::ITransform transform;
String name;
bool bEnabled;
std::vector<GOCLogic*> logic_components;
};
}
#endif // Entity_h__
+125
View File
@@ -0,0 +1,125 @@
#ifndef EntityFactory_h__
#define EntityFactory_h__
#include "Singleton.h"
#include "Globals.h"
#include "XML.h"
#include "Game.h"
namespace LifeGame
{
class EntityFactory;
class EntityFactory : public Singleton<EntityFactory>
{
public:
LifeGame::Entity* BuildEntity(const String& path, Game* engine)
{
pugi::xml_document doc;
//load file to memory
char* data;
LifeCore::IFile* file;
LifeGraphics::ResourceManager::me()->getFileSystem()->GetFile(path, &file);
LifeCore::IDataStreamPtr stm = file->OpenRead();
data = new char[stm->Length()];
stm->Read(data, stm->Length());
doc.load_buffer(data, stm->Length());
stm->Close();
delete[] data;
pugi::xml_node root = doc.child("Entity");
pugi::xml_node game = root.child("Game");
Entity* e;
e = new Entity();
e->SetName(root.attribute("Name").value());
//if entity have graphics - load it
if(root.attribute("bGraphics").as_bool())
{
pugi::xml_node g = root.child("Graphics");
IGraphicsEntity* visual = new IGraphicsEntity(engine->GetGraphics());
visual->Load(AS_STRING("root/Data/Objects/") + g.attribute("MeshFile").value());
pugi::xml_node mat = g.child("Materials");
//load materials
int curId =0;
for (pugi::xml_attribute_iterator ait = mat.attributes_begin(); ait != mat.attributes_end(); ++ait)
{
if(ait->name() == AS_STRING("ID"))
{
curId = ait->as_int();
}
else
{
if(ait->value() != AS_STRING(""))
{
// LifeGraphics::IMaterial* material = new LifeGraphics::IMaterial();
// material->load(AS_STRING("root/Data/Materials/") + AS_STRING(ait->value()) + AS_STRING(".xml"));
//visual->pMesh->setMaterial(material, curId);
}
}
}
e->SetGraphicalEntity(visual);
}
if(root.attribute("bPhysics").as_bool())
{
pugi::xml_node physx = root.child("Physics");
IPhysicsEntity* phys = new IPhysicsEntity(e);
//phys.append_attribute("sMeshName") = "Level2.ocf";
if(physx.attribute("sMeshName").value() != AS_STRING(""))
{
//if has collision mesh
//read data
LifeCore::IFile* file;
LifeGraphics::ResourceManager::me()->getFileSystem()->GetFile(AS_STRING("root/Data/Objects/") + physx.attribute("sMeshName").value(), &file);
LifeCore::IDataStreamPtr stm = file->OpenRead();
char* data = new char[stm->Length()];
stm->Read(data, stm->Length());
stm.release();
CollisionMeshData* meshData = new CollisionMeshData();
meshData->faceCount = (reinterpret_cast<int*>(data))[0];
meshData->vertexCount = meshData->faceCount * 3;
meshData->indexCount = meshData->vertexCount;
meshData->SixteenBit = false;
meshData->vertices = reinterpret_cast<LifeMath::float3*>(data + sizeof(int));
meshData->indices = reinterpret_cast<int*>(data + sizeof(int) + sizeof(LifeMath::float3)* meshData->vertexCount);
phys->CreateRigidBodyPhysics(LifeMath::float3(0.0f,0.0f,0.0f), NULL, physx.attribute("fMass").as_float(), meshData);
}
else
{
if(game.attribute("bPlayer").as_bool())
{
phys->CreateCharacterPhysics(LifeMath::float3(0.0f,0.0f,0.0f), physx.attribute("fMass").as_float(),0.6f,1.8f);
}
else
{
//no collision mesh specified! Just use bounding box
phys->CreateRigidBodyPhysics(LifeMath::float3(0.0f,220.0f,0.0f), e->GetGraphicalEntity()->pMesh->getBoundingBox(), physx.attribute("fMass").as_float(), NULL);
}
}
e->SetPhysicsEntity(phys);
}
return e;
}
Entity* CreatePlane(float width, float height, bool _physicalized, bool _static, Game* engine)
{
Entity* e = new Entity();
IGraphicsEntity* ge = new IGraphicsEntity(engine->GetGraphics());
return e;
}
};
}
#endif // EntityFactory_h__
+110
View File
@@ -0,0 +1,110 @@
#include "GOCCameraFree.h"
namespace LifeGame
{
GOCCameraFree::GOCCameraFree()
:camera(nullptr){
time_elapsed = 0.0f;
}
GOCCameraFree::~GOCCameraFree(){
}
void GOCCameraFree::SetCamera(GameCamera* cam){
camera = cam;
}
void GOCCameraFree::Update(float timeElapsed){
time_elapsed = timeElapsed;
if(!camera)
return;
}
void GOCCameraFree::OnAction(ActionId action, const ActionParam& param){
if(action == "MoveForward"){
if(camera){
auto cam_dir = camera->getCam()->getDirection();
auto dir = cam_dir * time_elapsed * 0.1f;
auto pos = camera->GetTransform()->GetPosition();
pos += dir;
camera->GetTransform()->SetPosition(pos);
camera->getCam()->setDirection(pos + cam_dir);
}
}else if(action == "MoveBackward"){
if(camera){
auto cam_dir = camera->getCam()->getDirection();
auto dir = cam_dir * -time_elapsed * 0.1f;
auto pos = camera->GetTransform()->GetPosition();
pos += dir;
camera->GetTransform()->SetPosition(pos);
camera->getCam()->setDirection(pos + cam_dir);
}
}else if(action == "MoveLeft"){
if(camera){
auto cam_dir = camera->getCam()->getDirection();
auto cam_right = camera->getCam()->getRight();
auto dir = cam_right * -time_elapsed * 0.1f;
auto pos = camera->GetTransform()->GetPosition();
pos += dir;
camera->GetTransform()->SetPosition(pos);
camera->getCam()->setDirection(pos + cam_dir);
}
}else if(action == "MoveRight"){
if(camera){
auto cam_dir = camera->getCam()->getDirection();
auto cam_right = camera->getCam()->getRight();
auto dir = cam_right * time_elapsed * 0.1f;
auto pos = camera->GetTransform()->GetPosition();
pos += dir;
camera->GetTransform()->SetPosition(pos);
camera->getCam()->setDirection(pos + cam_dir);
}
}else if(action == "RotateYaw"){
if(camera){
LifeMath::float3 cam_up = camera->getCam()->getUp();
LifeMath::float3 cam_dir = camera->getCam()->getDirection();
LifeMath::float3 cam_right = camera->getCam()->getRight();
LifeMath::float3 global_up(0,1,0);
LifeMath::Vec3Normalize(&cam_up);
LifeMath::Vec3Normalize(&cam_dir);
LifeMath::Vec3Normalize(&cam_right);
float angle = (float)param.val.si32_val / -10000.0f;
LifeMath::Quaternion rotation;
LifeMath::QuatSetAxisAngle(global_up, angle, rotation);
LifeMath::float4x4 rotation_mat;
LifeMath::Mat4x4RotationQuaternion(rotation, rotation_mat);
LifeMath::Vec3TransformCoordinate(cam_dir, rotation_mat);
LifeMath::Vec3TransformCoordinate(cam_right, rotation_mat);
LifeMath::Vec3TransformCoordinate(cam_up, rotation_mat);
camera->getCam()->SetupBasis(camera->GetTransform()->GetPosition(),
cam_dir, cam_up, cam_right);
}
}else if(action == "RotatePitch"){
if(camera){
/* LifeMath::float3 cam_up = camera->getCam()->getUp();
LifeMath::float3 cam_dir = camera->getCam()->getDirection();
LifeMath::float3 cam_right = camera->getCam()->getRight();
LifeMath::Vec3Normalize(&cam_up);
LifeMath::Vec3Normalize(&cam_dir);
LifeMath::Vec3Normalize(&cam_right);
float angle = (float)param.val.si32_val / -10000.0f;
LifeMath::Quaternion rotation;
LifeMath::QuatSetAxisAngle(cam_right, angle, rotation);
LifeMath::float4x4 rotation_mat;
LifeMath::Mat4x4RotationQuaternion(rotation, rotation_mat);
LifeMath::Vec3TransformCoordinate(cam_dir, rotation_mat);
LifeMath::Vec3TransformCoordinate(cam_up, rotation_mat);
camera->getCam()->SetupBasis(camera->GetTransform()->GetPosition(),
cam_dir, cam_up, cam_right);*/
}
}
}
}
+23
View File
@@ -0,0 +1,23 @@
#ifndef GOCCameraFree_h__
#define GOCCameraFree_h__
#include "GOCLogic.h"
#include "GameCamera.h"
#include "IActionListener.h"
namespace LifeGame
{
class GOCCameraFree : public GOCLogic, public IActionListener
{
public:
GOCCameraFree();
~GOCCameraFree();
void SetCamera(GameCamera* cam);
void Update(float timeElapsed);
void OnAction(ActionId action, const ActionParam& param) override;
private:
GameCamera* camera;
float time_elapsed;
};
}
#endif // GOCCameraFree_h__
+15
View File
@@ -0,0 +1,15 @@
#ifndef GOCLogic_h__
#define GOCLogic_h__
#include "GOComponent.h"
namespace LifeGame
{
class GOCLogic : public GOComponent
{
public:
GOCLogic(){}
virtual ~GOCLogic(){}
};
}
#endif // GOCLogic_h__
+14
View File
@@ -0,0 +1,14 @@
#ifndef GOComponent_h__
#define GOComponent_h__
namespace LifeGame
{
class GOComponent
{
public:
GOComponent(){}
virtual ~GOComponent(){}
virtual void Update(float timeElapsed){}
};
}
#endif // GOComponent_h__
+44
View File
@@ -0,0 +1,44 @@
#ifndef GUIOutput_h__
#define GUIOutput_h__
#include "IRenderOutput.h"
#include <GUIRenderWindow.h>
#include <CustomSwapChain.h>
#include <render/IRenderer.h>
#include "CImage.h"
namespace LifeGame
{
class GUIOutput : public LifeGraphics::IRenderOutput
{
public:
static GUIOutput* Create(LifeGUI::GUIRenderWindow* wnd, LifeGraphics::IRenderer* renderer){
LifeGraphics::CustomSwapChain* sc = new LifeGraphics::CustomSwapChain(wnd->GetWidth(), wnd->GetHeight(), 1, renderer, FORMAT_R8G8B8A8_UNORM);
return new GUIOutput(wnd, sc);
}
private:
GUIOutput(LifeGUI::GUIRenderWindow* wnd, LifeGraphics::CustomSwapChain* sc)
:LifeGraphics::IRenderOutput(wnd, sc)
{
out_wnd = wnd;
out_sc = sc;
img = CImage::FromTexture(sc->GetBackBuffer(0));
out_wnd->GetGUIWindow()->SetPicture(img);
wnd->GetGUIWindow()->Event_Resize += NewDelegate(this, &LifeGame::GUIOutput::OnResizeWND);
out_sc->Event_Resized += NewDelegate(this, &LifeGame::GUIOutput::OnResizeSC);
out_sc->Event_Presented += NewDelegate(this, &LifeGame::GUIOutput::OnResizeSC);
}
void OnResizeWND(LifeGUI::GUIWindow* wnd){
out_sc->Resize(out_wnd->GetWidth(), out_wnd->GetHeight());
}
void OnResizeSC(LifeGraphics::ISwapChain* sc){
delete img;
img = CImage::FromTexture(sc->GetBackBuffer(0));
out_wnd->GetGUIWindow()->SetPicture(img);
}
LifeGUI::GUIRenderWindow* out_wnd;
LifeGraphics::CustomSwapChain* out_sc;
CImage* img;
};
}
#endif // GUIOutput_h__
+39
View File
@@ -0,0 +1,39 @@
#include "Game.h"
#include <log/CLog.h>
namespace LifeGame
{
Game::Game()
:gameTime(0.0f), bRunning(false), fps(0), fcPos(0), frameCounter(0), customWindow(false)
{
SetResourcesPath(AS_STRING("D:\\development\\Programming\\Projects\\Data\\"));
pScriptSystem = new ScriptSystem(LifeGraphics::ResourceManager::me()->getFileSystem());
//register LOG
asIScriptEngine* engine = pScriptSystem->GetEngine();
engine->RegisterObjectType("CLog", 0, asOBJ_REF | asOBJ_NOHANDLE);
engine->RegisterObjectMethod("CLog", "void Write(const string &in)", asMETHODPR(LifeCore::CLog, Write, (const String&), void), asCALL_THISCALL);
engine->RegisterObjectMethod("CLog", "void LogToConsole(bool)", asMETHODPR(LifeCore::CLog, LogToConsole, (bool), void), asCALL_THISCALL);
engine->RegisterGlobalProperty("CLog LOG", LifeCore::CLog::me());
//engine->RegisterObjectType("Entity", 0, asOBJ_REF);
//engine->RegisterObjectType("Game", 0, asOBJ_REF | asOBJ_NOHANDLE);
//engine->RegisterObjectMethod("Game", "Entity@ GetPlayer()", asMETHODPR(Game, GetPlayer, (), Entity*), asCALL_THISCALL);
//engine->RegisterGlobalProperty("Game GameEngine", this);
//void CLog::LogToConsole(bool condition)
//register game engine in script system
//register graphics engine in script system
//register physics engine in script system
Script* config;
pScriptSystem->NewScript("root/Data/Scripts/Config.as", &config);
config->ExecuteGlobalFunction("void DoConfig()");
physicsWorld = new IPhysicsWorld();
}
}
+167
View File
@@ -0,0 +1,167 @@
#ifndef Game_h__
#define Game_h__
#include "Entity.h"
#include "IPhysicsWorld.h"
#include "World.h"
#include "InputSystemOIS.h"
#include "script/ScriptSystem.h"
#include <GUIManager.h>
#include <CGUIRenderer.h>
#include <IRenderWindow.h>
#include "CGUIDataManager.h"
namespace LifeGame
{
#define MAX_FPS_COUNTER 100
class Game
{
protected:
LifeCore::DisplayMode* modes;
IPhysicsWorld* physicsWorld;
LifeGraphics::LifeEngine* pGraphics;
LifeCore::IRenderWindow* output;
int mainWindow;
World* gameWorld;
float gameTime;
bool bRunning;
bool customWindow;
LifeCore::InputSystemOIS* input;
int frameCounter;
ScriptSystem* pScriptSystem;
CGUIRenderer* gui_renderer;
LifeGUI::GUIManager* gui_manager;
public:
Game();
LifeCore::IRenderWindow* GetWindow()
{
return output;
}
void DrawDebug()
{
physicsWorld->CompileDebug();
pGraphics->debugDrawer->Render();
pGraphics->debugDrawer->Flush();
}
LifeGraphics::LifeEngine* GetGraphics()
{
return pGraphics;
}
IPhysicsWorld* GetPhysics()
{
return physicsWorld;
}
void InitVideo(LifeGraphics::RENDERER_TYPE renderer, int width, int height)
{
pGraphics = new LifeGraphics::LifeEngine();
pGraphics->Init(renderer, LifeGraphics::RenderParams(false, false));
physicsWorld->SetDebugDrawer(pGraphics->debugDrawer);
LifeGUI::GUIManager::me()->Init(new CGUIRenderer(pGraphics->GetRenderer()), new CGUIDataManager());
}
void SetResourcesPath(const String& path)
{
LifeGraphics::ResourceManager::me()->SetCentralDirectory(path);
}
void SetWindow(RenderWindowWin* window)
{
output = window;
}
void SetWindow(int width, int height)
{
output = new RenderWindowWin();
output->SetSize(width, height);
}
void InitInput(int screenWidth, int screenHeight, LifeCore::IRenderWindow* wnd)
{
input = new LifeCore::InputSystemOIS();
input->Init(wnd->GetWidth(), wnd->GetHeight(), false, wnd->GetWindowHandle());
}
LifeCore::IInputSystem* GetInput()
{
return input;
}
int Run()
{
bRunning = true;
while(IsRunning())
{
process();
Sleep(0);
}
return 0;
}
bool IsRunning()
{
return bRunning;
}
void Exit()
{
bRunning = false;
}
virtual ~Game()
{
SAFE_DELETE(physicsWorld);
}
World* GetWorld()
{
return gameWorld;
}
void processWorld(World* world){
input->Capture();
world->Update(0.001f);
world->Render();
DrawDebug();
world->GetOutput()->GetSwapChain()->Present();
world->GetOutput()->GetWindow()->Update();
}
void process()
{
gameTime += pGraphics->GetTimeElapsed();
//pGraphics->GetRenderer()->ClearBuffers(CF_COLOR_TARGET | CF_DEPTH_BUFFER, 0xffff00, 1, 0);
//stateManager.Update(); //to world
// stateManager.Render();
frameCounter++;
avgFps[fcPos++] = 1.0f / GetGraphics()->GetTimeElapsed();
if(fcPos >= MAX_FPS_COUNTER)
{
fcPos = 0;
fps = 0.0f;
for(int i = 0; i<MAX_FPS_COUNTER; i++)
{
fps += avgFps[i];
}
fps /= (float)MAX_FPS_COUNTER;
printf("FPS: %f\n", fps);
}
}
private:
float fps;
float avgFps[MAX_FPS_COUNTER];
int fcPos;
};
}
#endif // LifeGame_h__
+37
View File
@@ -0,0 +1,37 @@
#ifndef EntityCamera_h__
#define EntityCamera_h__
#include "Entity.h"
#include "camera/Camera.h"
namespace LifeGame
{
class GameCamera : public Entity
{
private:
LifeGraphics::Camera cam;
void OnSetPosition()
{
cam.setPosition(GetTransform()->GetPosition());
}
void OnSetRotation()
{
}
public:
LifeGraphics::Camera* getCam()
{
return &cam;
}
GameCamera(float aspect)
{
cam.setAspect(aspect);
cam.setFov(3.1415f / 3.0f);
LifeCore::ITransform* t = GetTransform();
t->Event_SetPosition += NewDelegate(this, &GameCamera::OnSetPosition);
t->Event_SetPosition += NewDelegate(this, &GameCamera::OnSetRotation);
}
};
}
#endif // EntityCamera_h__
+4
View File
@@ -0,0 +1,4 @@
#ifndef GameGlobals_h__
#define GameGlobals_h__
#endif // GameGlobals_h__
+22
View File
@@ -0,0 +1,22 @@
#ifndef Graphics_h__
#define Graphics_h__
#include <LifeEngine.h>
#include <RenderWindow.h>
#include <ResourceManager.h>
#include <LString.h>
#include <log/CLog.h>
#include <vfs/IFolder.h>
#include <math/LifeMath.h>
#include "IObject.h"
#include <IObjectMesh.h>
#include <iostream>
#include <vector>
#include <sstream>
#include "vfs/pak/pak_io/PakFile.h"
#include "vfs/fs_win/IFSContentProvider.h"
#include "vfs/pak/IPakFileContentProvider.h"
#include "vfs/IFile.h"
#include "AnimationTrack.h"
#endif // Graphics_h__
+15
View File
@@ -0,0 +1,15 @@
#ifndef IActionListener_h__
#define IActionListener_h__
#include "Action.h"
namespace LifeGame
{
class IActionListener
{
public:
virtual ~IActionListener(){}
virtual void OnAction(ActionId action, const ActionParam& param) = 0;
};
}
#endif // IActionListener_h__
+13
View File
@@ -0,0 +1,13 @@
#ifndef IActionProvider_h__
#define IActionProvider_h__
namespace LifeGame
{
class IActionProvider
{
public:
virtual ~IActionProvider(){};
virtual void Update(){}
};
}
#endif // IActionProvider_h__
+36
View File
@@ -0,0 +1,36 @@
#include "IGraphicsEntity.h"
IGraphicsEntity::IGraphicsEntity(LifeGraphics::LifeEngine* engine)
{
pEngine = engine;
pMesh = (LifeGraphics::IObjectMesh*)0;
}
IGraphicsEntity::~IGraphicsEntity()
{
#ifdef _DEBUG
if(Unload())
LifeCore::CLog::me()->Write(AS_STRING("Graphics entity unloaded"));
#endif // _DEBUG
}
bool IGraphicsEntity::Load(String path)
{
pMesh = new LifeGraphics::IObjectMesh(path);
return true;
}
void IGraphicsEntity::SetBody(LifeGraphics::IObject* obj)
{
pMesh = static_cast<LifeGraphics::IObjectMesh*>(obj);
}
LifeGraphics::IObject* IGraphicsEntity::GetBody()
{
return pMesh;
}
bool IGraphicsEntity::Unload()
{
if(pMesh)
{
SAFE_DELETE(pMesh); // fixup for unloading from engine!!!
return true;
}
return false;
}
+19
View File
@@ -0,0 +1,19 @@
#ifndef IGraphicsEntity_h__
#define IGraphicsEntity_h__
#include "Graphics.h"
class IGraphicsEntity
{
public:
LifeGraphics::IObjectMesh* pMesh;
LifeGraphics::LifeEngine* pEngine;
IGraphicsEntity(LifeGraphics::LifeEngine* engine);
~IGraphicsEntity();
bool Load(String path);
bool Unload();
void SetBody(LifeGraphics::IObject* obj);
LifeGraphics::IObject* GetBody();
};
#endif // IGraphicsEntity_h__
+344
View File
@@ -0,0 +1,344 @@
#include "IPhysicsEntity.h"
#include "Entity.h"
#include <BulletCollision/CollisionDispatch/btGhostObject.h>
#include "IPhysicsWorld.h"
namespace LifeGame
{
static int ID = 0;
void LifeMotionState::buildMatrix()
{
bTransform.getOpenGLMatrix(reinterpret_cast<btScalar*>(&mTransform));
//setup new transform to owner
owner->GetTransform()->SetMatrix(mOffset1 * mTransform);
}
void LifeMotionState::getWorldTransform(btTransform& worldTrans ) const
{
LifeMath::float4x4 m2 = mOffset2 * owner->GetTransform()->GetMatrix();
worldTrans.setFromOpenGLMatrix(reinterpret_cast<btScalar*>(&m2));
}
void LifeMotionState::setWorldTransform(const LifeMath::float4x4& worldTrans)
{
mTransform = mOffset1 * worldTrans;
bTransform.setFromOpenGLMatrix(reinterpret_cast<btScalar*>(&mTransform));
}
IPhysicsEntity::IPhysicsEntity(Entity* _owner)
:data(0), collisionFlags(0), bGhost(false), prevPairCnt(0), curPairCnt(0)
{
owner = _owner;
id = ID++;
}
void IPhysicsEntity::EnableContactCallbacks(bool condition)
{
int flag = body->getCollisionFlags() & (~btCollisionObject::CF_CUSTOM_MATERIAL_CALLBACK);
body->setCollisionFlags(condition == true ? (flag | btCollisionObject::CF_CUSTOM_MATERIAL_CALLBACK) : flag);
// body->
}
void IPhysicsEntity::SetLinearVelocity(const LifeMath::float3& velocity)
{
if(body->getActivationState() == ISLAND_SLEEPING)
body->activate(true);
btVector3 vel;
vel.setX(velocity.X);
vel.setY(velocity.Y);
vel.setZ(velocity.Z);
(static_cast<btRigidBody*>(body))->setLinearVelocity(vel);
//(Body as RigidBody).LinearVelocity = new Vector3(vel.X, vel.Y, vel.Z);
}
bool FindCollider(int id, ContactPairInfo* pairs, int count)
{
for(int i = 0; i< count; i++)
{
if(pairs[i].id == id)
return true;
}
return false;
}
void IPhysicsEntity::Update(IPhysicsWorld* pWorld)
{
btOverlappingPairCache* worldPairCache = pWorld->GetBroadphaseInterface()->getOverlappingPairCache();
//find new collision pairs
if(bGhost)
{
//copy pairs to previous, find new pairs
if(curPairCnt)
{
memcpy(prevPairs, curPairs, curPairCnt * sizeof(ContactPairInfo));
prevPairCnt = curPairCnt;
curPairCnt = 0;
}
btPairCachingGhostObject* go = static_cast<btPairCachingGhostObject*>(body);
btBroadphasePairArray& pairArray = go->getOverlappingPairCache()->getOverlappingPairArray();
int numPairs = pairArray.size();
//btManifoldArray manifolds;
for(int i = 0; i < numPairs; i++)
{
//manifolds.clear();
const btBroadphasePair& pair = pairArray[i];
btBroadphasePair* p = worldPairCache->findPair(pair.m_pProxy0, pair.m_pProxy1);
if(!p)
continue;
btCollisionObject* obj1 = static_cast<btCollisionObject*>(p->m_pProxy0->m_clientObject);
btCollisionObject* obj2 = static_cast<btCollisionObject*>(p->m_pProxy1->m_clientObject);
IPhysicsEntity* e1 = reinterpret_cast<IPhysicsEntity*>(obj1->getUserPointer());
IPhysicsEntity* e2 = reinterpret_cast<IPhysicsEntity*>(obj2->getUserPointer());
if(!e1 || !e2)
continue;
IPhysicsEntity* other = 0;
if(e1->id == this->id)
other = e2;
else if(e2->id == this->id)
other = e1;
else
continue;
if(!FindCollider(other->id, curPairs, curPairCnt))
{
ContactPairInfo info;
info.id = other->id;
info.dataPtr = other;
curPairs[curPairCnt] = info;
curPairCnt++;
}
//p->m_pProxy0->
//pair.m_pProxy0->
}
//first 2 "if" cases is just optimization
if(curPairCnt == 0 && prevPairCnt > 0)
{
for(int i = 0; i < prevPairCnt; i++)
{
//do "on dispose contact"
this->Event_CollisionDispose.Invoke((IPhysicsEntity*)prevPairs[i].dataPtr);
}
}
else if(prevPairCnt == 0 && curPairCnt > 0) //new contacts
{
for(int i = 0; i < curPairCnt; i++)
{
//do "on create contact"
this->Event_CollisionCreate.Invoke((IPhysicsEntity*)curPairs[i].dataPtr);
}
}
else //partial changes
{
//find new contacts
for(int i = 0; i < curPairCnt; i++)
{
const ContactPairInfo& pair = curPairs[i];
if(!FindCollider(pair.id, prevPairs, prevPairCnt))
{
this->Event_CollisionCreate.Invoke((IPhysicsEntity*)pair.dataPtr);
}
}
//find disposed contacts
for(int i = 0; i < prevPairCnt; i++)
{
const ContactPairInfo& pair = prevPairs[i];
if(!FindCollider(pair.id, curPairs, curPairCnt))
{
this->Event_CollisionDispose.Invoke((IPhysicsEntity*)pair.dataPtr);
}
}
}
}
/*if(curPairCnt)
{
prev
}*/
}
void IPhysicsEntity::CreateTriggerPhysics(const LifeMath::float3& initialPos, float sx, float sy, float sz)
{
bGhost = true;
mass = 0;
data = 0;
LifeMath::float3 offset;
LifeMath::float3 size = LifeMath::float3(sx, sy, sz);
offset = LifeMath::float3(0,0,0);
Mat4x4Translation(offset, mOffset2);
Mat4x4Translation(offset * -1.0f, mOffset1);
//shape = new btPairCachingGhostObject();
shape = new btBoxShape(btVector3(sx / 2.0f, sy / 2.0f, sz / 2.0f));
btTransform transform;
transform.setIdentity();
transform.setOrigin(btVector3(0.0f, 0.8f, 0.0f));
btVector3 inertia(0.0f, 0.0f, 0.0f);
collisionFlags = COL_STATIC;
btTransform transform2;
transform2.setIdentity();
transform2.setOrigin(btVector3(initialPos.X + offset.X, initialPos.Y + offset.Y, initialPos.Z + offset.Z));
state = new LifeMotionState(transform2, owner, mOffset1, mOffset2);
//btRigidBody::btRigidBodyConstructionInfo ci(mass, state, shape, inertia);
body = new btPairCachingGhostObject();
body->setWorldTransform(transform2);
body->setCollisionShape(shape);
body->setUserPointer(this);
// body = new btRigidBody(ci);
}
void IPhysicsEntity::SetAngularFactor(const LifeMath::float3& velocity)
{
btVector3 vel;
vel.setX(velocity.X);
vel.setY(velocity.Y);
vel.setZ(velocity.Z);
(static_cast<btRigidBody*>(body))->setAngularFactor(vel);
}
void IPhysicsEntity::CreateCharacterPhysics(const LifeMath::float3& position, float _mass, float radius, float height)
{
Mat4x4Translation(LifeMath::float3(0.0f,0.0f,0.0f), mOffset2);
Mat4x4Translation(LifeMath::float3(0.0f,0.0f,0.0f), mOffset1);
mass = _mass;
float capsuleHeight = height - radius * 2;
btCompoundShape* characterShape = new btCompoundShape(true);
shape = characterShape;
//componentShapes.push_back(shape);
btCapsuleShape* capsule = new btCapsuleShape(radius,capsuleHeight);
componentShapes.push_back(capsule);
btTransform transform;
transform.setIdentity();
transform.setOrigin(btVector3(0.0f,height/2.0f, 0.0f));
characterShape->addChildShape(transform, capsule);
shape = characterShape;
transform.setIdentity();
transform.setOrigin(btVector3(0.0f, 0.0f, 0.0f));
btVector3 inertia(0.0f, 0.0f, 0.0f);
if(mass > 0.0f)
shape->calculateLocalInertia(mass, inertia);
collisionFlags = COL_PLAYER;
btTransform transform2;
transform2.setIdentity();
transform2.setOrigin(btVector3(position.X, position.Y, position.Z));
state = new LifeMotionState(transform2, owner, mOffset1, mOffset2);
btRigidBody::btRigidBodyConstructionInfo ci(mass, state, shape, inertia);
body = new btRigidBody(ci);
body->setUserPointer(this);
/*;
(Shell as CompoundShape).AddChildShape(Matrix.Translation(0,0.8f,0),new CapsuleShape(radius, capsuleHeight));
Vector3 inertia = new Vector3();
Shell.CalculateLocalInertia(mass, out inertia);
BulletSharp.MotionState state = new DefaultMotionState(Matrix.Identity);
RigidBodyConstructionInfo info = new RigidBodyConstructionInfo(mass, state, Shell, inertia);
Body = (CollisionObject) new RigidBody(info);
Body.UserObject = this.Owner;
PhysicsSystem.Instance.Scene.g_world.AddRigidBody((RigidBody) Body);*/
}
void IPhysicsEntity::PhysicsGetOwnerTransform()
{
m2 = mOffset2 * owner->GetTransform()->GetMatrix();
bTransform.setFromOpenGLMatrix(reinterpret_cast<btScalar*>(&m2));
//body->activate(true);
body->setWorldTransform(bTransform);
body->setInterpolationWorldTransform(bTransform);
}
//void IPhysicsEntity::CreateMeshPhysics(const LifeMath::float3& pos, float mass, )
void IPhysicsEntity::CreateRigidBodyPhysics(const LifeMath::float3& initialPos, const LifeCore::BoundingBox3D* bbox, float _mass, CollisionMeshData* _data)
{
mass = _mass;
data = _data;
LifeMath::float3 offset;
if(!data)
{
LifeMath::float3 size = bbox->maximum() - bbox->minimum();
offset = bbox->minimum() + size * 0.5f;
Mat4x4Translation(offset, mOffset2);
Mat4x4Translation(offset * -1.0f, mOffset1);
shape = new btBoxShape(btVector3(size.X / 2.0f, size.Y / 2.0f, size.Z / 2.0f));
}
else
{
offset = LifeMath::float3(0.0f,0.0f,0.0f);
Mat4x4Translation(LifeMath::float3(0.0f,0.0f,0.0f), mOffset2);
Mat4x4Translation(LifeMath::float3(0.0f,0.0f,0.0f), mOffset1);
btTriangleIndexVertexArray* arr = new btTriangleIndexVertexArray(data->faceCount,data->indices,sizeof(int) * 3,data->vertexCount, reinterpret_cast<btScalar*>(data->vertices), sizeof(LifeMath::float3));
shape = new btBvhTriangleMeshShape(arr, true, true);
}
btTransform transform;
transform.setIdentity();
transform.setOrigin(btVector3(0.0f, 0.8f, 0.0f));
btVector3 inertia(0.0f, 0.0f, 0.0f);
if(mass > 0.0f)
{
shape->calculateLocalInertia(mass, inertia);
collisionFlags = COL_DYNAMIC;
}
else
{
collisionFlags = COL_STATIC;
}
btTransform transform2;
transform2.setIdentity();
transform2.setOrigin(btVector3(initialPos.X + offset.X, initialPos.Y + offset.Y, initialPos.Z + offset.Z));
state = new LifeMotionState(transform2, owner, mOffset1, mOffset2);
btRigidBody::btRigidBodyConstructionInfo ci(mass, state, shape, inertia);
body = new btRigidBody(ci);
body->setUserPointer(this);
//body->setWorldTransform(transform2);
/*;
PhysicsSystem.Instance.Scene.g_world.AddRigidBody((RigidBody) Body);*/
}
}
+151
View File
@@ -0,0 +1,151 @@
#ifndef IPhysicsEntity_h__
#define IPhysicsEntity_h__
#include "Graphics.h"
#include <vector>
#include <BulletCollision/BroadphaseCollision/btAxisSweep3.h>
#include <BulletCollision/CollisionShapes/btBoxShape.h>
#include <BulletCollision/CollisionShapes/btCapsuleShape.h>
#include <BulletCollision/CollisionShapes/btHeightfieldTerrainShape.h>
#include <BulletCollision/CollisionShapes/btCompoundShape.h>
#include <btBulletDynamicsCommon.h>
#include "BulletLibs.h"
#include <delegate/Delegate.h>
#include <math/LifeMath.h>
namespace LifeGame
{
enum collisiontypes {
COL_NOTHING = 0,
COL_STATIC = 1 << 0,
COL_PLAYER = 1 << 1,
COL_DYNAMIC = 1 << 2,
COL_SENSOR = 1 <<3,
};
class Entity;
class CollisionMeshData
{
public:
char* dataPtr;
int vertexCount;
int faceCount;
int indexCount;
LifeMath::float3* vertices;
int* indices;
bool SixteenBit;
CollisionMeshData()
:dataPtr(0)
{
}
~CollisionMeshData()
{
if(dataPtr)
{
delete[] dataPtr;
}
}
};
struct ContactPairInfo
{
void* dataPtr;
int id;
};
class LifeMotionState : public btMotionState
{
private:
btTransform bTransform;
LifeMath::float4x4 mTransform;
Entity* owner;
void buildMatrix();
public:
LifeMath::float4x4 mOffset1;
LifeMath::float4x4 mOffset2;
LifeMotionState(btTransform& initialTransform, Entity* _owner, LifeMath::float4x4& offset1, LifeMath::float4x4& offset2)
{
owner = _owner;
bTransform = initialTransform;
mOffset1 = offset1;
mOffset2 = offset2;
buildMatrix();
}
~LifeMotionState()
{
}
void getWorldTransform(btTransform& worldTrans ) const;
void setWorldTransform(const btTransform& worldTrans)
{
bTransform = worldTrans;
buildMatrix();
}
void setWorldTransform(const LifeMath::float4x4& worldTrans);
};
class IPhysicsWorld;
class IPhysicsEntity
{
private:
int id;
float mass;
bool bGhost;
CollisionMeshData* data;
btCollisionShape* shape;
btCollisionObject* body;
std::vector<btCollisionShape*> componentShapes;
btTransform bTransform;
LifeMath::float4x4 m2;
EVENT1(PhysicsEvent, void*);
PhysicsEvent Event_CollisionCreate;
PhysicsEvent Event_CollisionDispose;
ContactPairInfo prevPairs[256];
ContactPairInfo curPairs[256];
int prevPairCnt;
int curPairCnt;
public:
short collisionFlags;
float GetMass()
{
return mass;
}
Entity* owner;
LifeMotionState* state;
LifeMath::float4x4 mOffset1;
LifeMath::float4x4 mOffset2;
void Update(IPhysicsWorld* pWorld);
bool IsStatic()
{
return mass <=0;
}
btCollisionObject* GetBody()
{
return body;
}
IPhysicsEntity(Entity* _owner);
void PhysicsGetOwnerTransform();
~IPhysicsEntity()
{
if(data)
delete data;
}
void EnableContactCallbacks(bool condition);
void SetLinearVelocity(const LifeMath::float3& velocity);
void SetAngularFactor(const LifeMath::float3& velocity);
void CreateTriggerPhysics(const LifeMath::float3& initialPos, float sx, float sy, float sz);
void CreateCharacterPhysics(const LifeMath::float3& position, float _mass, float radius, float height);
void CreateRigidBodyPhysics(const LifeMath::float3& initialPos, const LifeCore::BoundingBox3D* bbox, float _mass, CollisionMeshData* data);
};
}
#endif // IPhysicsEntity_h__
+228
View File
@@ -0,0 +1,228 @@
#ifndef IPhysicsWorld_h__
#define IPhysicsWorld_h__
#include <BulletCollision/BroadphaseCollision/btAxisSweep3.h>
#include "BulletLibs.h"
#include "IPhysicsEntity.h"
#include <BulletCollision/CollisionDispatch/btGhostObject.h>
#define MAX_DEBUG_LINE_CNT 1024
#include <vector>
#include "debug/IDebugDrawer.h"
namespace LifeGame
{
class DebugDrawer : public btIDebugDraw
{
public:
LifeGraphics::DebugVertex lines[MAX_DEBUG_LINE_CNT * 2];
int lineCount;
int dbgMode;
LifeGraphics::IDebugDrawer* debug;
DebugDrawer(LifeGraphics::IDebugDrawer* dd)
:lineCount(0), dbgMode(DBG_DrawWireframe | DBG_DrawConstraints)
{
debug = dd;
}
~DebugDrawer()
{
}
void drawLine(const btVector3& from,const btVector3& to,const btVector3& color)
{
LifeGraphics::DebugVertex v1;
v1.position = LifeMath::float3(from.x(), from.y(), from.z());
v1.color = LifeMath::float3(color.x(), color.y(), color.z());
LifeGraphics::DebugVertex v2;
v2.position = LifeMath::float3(to.x(), to.y(), to.z());
v2.color = LifeMath::float3(color.x(), color.y(), color.z());
debug->PushLine(v1,v2);
}
void drawContactPoint(const btVector3& PointOnB,const btVector3& normalOnB,btScalar distance,int lifeTime,const btVector3& color)
{
}
void reportErrorWarning(const char* warningString)
{
}
void draw3dText(const btVector3& location,const char* textString)
{
}
void setDebugMode(int debugMode)
{
dbgMode = debugMode;
}
int getDebugMode() const
{
return dbgMode;
}
};
class IPhysicsWorld
{
private:
btDiscreteDynamicsWorld* pWorld;
btBroadphaseInterface* pBroadphase;
btCollisionConfiguration* pCollisionConfiguration;
btConstraintSolver* pSolver;
btCollisionDispatcher* pDispatcher;
DebugDrawer* debugDraw;
std::vector<IPhysicsEntity*> entityCollection;
//SortedList<int, gocPhysical> g_components;
public:
float RayTest(const LifeMath::float3& from, const LifeMath::float3& to)
{
btVector3 f(from.X,from.Y, from.Z);
btVector3 t(to.X, to.Y, to.Z);
btCollisionWorld::ClosestRayResultCallback ray(f, t);
pWorld->rayTest(f, t, ray);
LifeMath::float3 pt(ray.m_hitPointWorld.getX(), ray.m_hitPointWorld.getY(), ray.m_hitPointWorld.getZ());
return Vec3Distance(from, pt);
}
void ApplyForce(const LifeMath::float3& from, const LifeMath::float3& to, float power)
{
btVector3 f(from.X,from.Y, from.Z);
btVector3 t(to.X, to.Y, to.Z);
btCollisionWorld::ClosestRayResultCallback ray(f, t);
pWorld->rayTest(f, t, ray);
LifeMath::float3 pt(ray.m_hitPointWorld.getX(), ray.m_hitPointWorld.getY(), ray.m_hitPointWorld.getZ());
if(!ray.m_collisionObject->isStaticObject())
{
LifeMath::float3 force = to - from;
Vec3Normalize(&force);
force = force * power;
btRigidBody* rb = static_cast<btRigidBody*>(ray.m_collisionObject);
rb->activate(true);
// rb->applyCentralForce(btVector3(force.X, force.Y, force.Z));
rb->applyForce(btVector3(force.X, force.Y, force.Z), ray.m_hitPointWorld);
}
}
float SphereTest(const LifeMath::float3& from, const LifeMath::float3& to, float radius)
{
btSphereShape CameraSphere(radius);
btTransform CameraFrom, CameraTo;
CameraFrom.setIdentity();
CameraFrom.setOrigin(btVector3(from.X, from.Y, from.Z));
CameraTo.setIdentity();
CameraTo.setOrigin(btVector3(to.X, to.Y, to.Z));
btCollisionWorld::ClosestConvexResultCallback cb(CameraFrom.getOrigin(), CameraTo.getOrigin() );
cb.m_collisionFilterMask = btBroadphaseProxy::StaticFilter;
cb.m_collisionFilterGroup = COL_SENSOR;
cb.m_collisionFilterMask = ~((int)COL_PLAYER);
pWorld->convexSweepTest(&CameraSphere,CameraFrom,CameraTo,cb);
if (cb.hasHit())
{
btScalar minFraction = cb.m_closestHitFraction;
float dist = Vec3Distance(from, to);
return dist * minFraction;
}
return 100500.0f;
}
btBroadphaseInterface* GetBroadphaseInterface()
{
return pBroadphase;
}
IPhysicsWorld()
:debugDraw(0)
{
LifeCore::CLog::me()->Write(AS_STRING("Loading physics engine..."));
pBroadphase = new btAxisSweep3(btVector3(-1000.0f,-1000.0f,-1000.0f), btVector3(1000.0f, 1000.0f, 1000.0f));
//pBroadphase = new btDbvtBroadphase();
pCollisionConfiguration = new btDefaultCollisionConfiguration();
pSolver = new btSequentialImpulseConstraintSolver();
pDispatcher = new btCollisionDispatcher(pCollisionConfiguration);
pWorld = new btDiscreteDynamicsWorld(pDispatcher, pBroadphase, pSolver, pCollisionConfiguration);
pWorld->setGravity(btVector3(0.0f, -9.8f, 0.0f));
LifeCore::CLog::me()->Write(AS_STRING("Physics engine loaded"));
//enable collisions for ghost objects
btGhostPairCallback* cb = new btGhostPairCallback();
pWorld->getPairCache()->setInternalGhostPairCallback(cb);
//test! create ground
btCollisionShape* groundShape = new btBoxShape(btVector3(100.0f,10.0f,100.0f));
btRigidBody* ground;
btTransform transform;
transform.setIdentity();
transform.setOrigin(btVector3(0.0f, -10.0f, 0.0f));
btVector3 inertia = btVector3(0.0f, 0.0f, 0.0f);
//groundShape->calculateLocalInertia(0, inertia);
btMotionState* state = new btDefaultMotionState();
btRigidBody::btRigidBodyConstructionInfo ci(0.0f, state, groundShape, inertia);
ground = new btRigidBody(ci);
ground->setWorldTransform(transform);
//pWorld->addRigidBody(ground);
}
void SetDebugDrawer(LifeGraphics::IDebugDrawer* _debug)
{
if(!debugDraw)
{
delete debugDraw;
}
debugDraw = new DebugDrawer(_debug);
pWorld->setDebugDrawer(debugDraw);
}
~IPhysicsWorld()
{
}
void CompileDebug()
{
if(debugDraw)
pWorld->debugDrawWorld();
}
void AddObject(IPhysicsEntity* ent)
{
short mask;
if(ent->collisionFlags == COL_STATIC)
{
mask = COL_DYNAMIC | COL_PLAYER | COL_SENSOR;
}
else
{
mask = COL_DYNAMIC | COL_PLAYER | COL_STATIC | COL_SENSOR;
}
pWorld->addRigidBody(static_cast<btRigidBody*>(ent->GetBody()),ent->collisionFlags, mask);
entityCollection.push_back(ent);
}
void Tick(float dt)
{
//update physics transform (in case when entity transform changed not by physics engine)
int cnt = entityCollection.size();
for(int i = 0; i< cnt; i++)
{
IPhysicsEntity* e = entityCollection[i];
e->PhysicsGetOwnerTransform();
e->state->setWorldTransform(e->mOffset2 * e->owner->GetTransform()->GetMatrix());
e->Update(this);
}
pWorld->stepSimulation(dt, 2);
}
protected:
private:
};
}
#endif // IPhysicsWorld_h__
+8
View File
@@ -0,0 +1,8 @@
#ifndef IScriptEntity_h__
#define IScriptEntity_h__
#include <SLB/SLB.hpp>
class IScriptEntity
{
};
#endif // IScriptEntity_h__
+75
View File
@@ -0,0 +1,75 @@
#include "InputActionProvider.h"
namespace LifeGame
{
InputActionProvider::InputActionProvider(){
}
void InputActionProvider::Map(LifeCore::Key key, LifeCore::KeyAction key_action, const ActionId& game_action){
bool found = false;
for(auto& map : key_mapping){
if((map.key == key) && (map.key_action == key_action) && (map.game_action == game_action)){
found = true;
break;
}
}
if(!found){
key_mapping.push_back(KeyMapInfo(key, key_action, game_action));
}
}
void InputActionProvider::Map(LifeCore::MouseAxis axis, const ActionId& action){
bool found = false;
for(auto& map : axis_mapping){
if(map.axis == axis && map.action == action){
found = true;
break;
}
}
if(!found){
axis_mapping.push_back(AxisMapInfo(axis,action));
}
}
void InputActionProvider::Unmap(LifeCore::Key key, LifeCore::KeyAction key_action, const ActionId& game_action){
}
void InputActionProvider::Update(){
//update keyboard mapping
for(auto& map : key_mapping){
if(map.key_action == LifeCore::KA_HOLD){
if(GetInputSystem() != nullptr && GetInputSystem()->KeyPressed(map.key)){
ActionParam param;
param.val.si32_val = decltype(param.val.si32_val)(map.key);
LifeGame::ActionSystem::me()->DoAction(map.game_action, param);
}
}
}
}
bool InputActionProvider::MouseMove( int absX, int relX, int absY, int relY){
ActionParam param;
if(relX == 0 && relY == 0){
return true;
}
//update mouse axis mapping
for(auto& map : axis_mapping){
if(map.axis == LifeCore::MOUSE_AXIS_X && relX != 0){
param.val.si32_val = relX;
char buf[256];
sprintf(buf, "%i\n", relX);
OutputDebugString(buf);
LifeGame::ActionSystem::me()->DoAction(map.action, param);
}else if(map.axis == LifeCore::MOUSE_AXIS_Y && relY != 0){
param.val.si32_val = relY;
LifeGame::ActionSystem::me()->DoAction(map.action, param);
}
}
return true;
}
bool InputActionProvider::KeyDown(LifeCore::Key key, unsigned int text, const std::string& str){
return true;
}
bool InputActionProvider::KeyUp(LifeCore::Key key, unsigned int text, const std::string& str){
return true;
}
}
+52
View File
@@ -0,0 +1,52 @@
#ifndef InputActionProvider_h__
#define InputActionProvider_h__
#include "IActionProvider.h"
#include <IInputSystem.h>
#include "Action.h"
#include "ActionSystem.h"
#include <vector>
#include <IInputListener.h>
namespace LifeGame
{
struct KeyMapInfo{
LifeCore::Key key;
LifeCore::KeyAction key_action;
ActionId game_action;
KeyMapInfo(LifeCore::Key _key, LifeCore::KeyAction _key_action, const ActionId& _game_action){
key = _key;
key_action = _key_action;
game_action = _game_action;
}
};
struct AxisMapInfo{
LifeCore::MouseAxis axis;
ActionId action;
AxisMapInfo(LifeCore::MouseAxis _axis, const ActionId& _game_action){
axis = _axis;
action = _game_action;
}
};
class InputActionProvider final : public IActionProvider, public LifeCore::IInputListener
{
public:
InputActionProvider();
void Map(LifeCore::Key key, LifeCore::KeyAction key_action, const ActionId& game_action);
void Map(LifeCore::MouseAxis axis, const ActionId& action);
void Unmap(LifeCore::Key key, LifeCore::KeyAction key_action, const ActionId& game_action);
void Update() override;
bool KeyDown(LifeCore::Key key, unsigned int text, const std::string& str) override;
bool KeyUp(LifeCore::Key key, unsigned int text, const std::string& str) override;
bool MouseMove( int absX, int relX, int absY, int relY) override;
private:
std::vector<KeyMapInfo> key_mapping;
std::vector<AxisMapInfo> axis_mapping;
};
}
#endif // KeyboardActionProvider_h__
+97
View File
@@ -0,0 +1,97 @@
#include "World.h"
#include "Game.h"
namespace LifeGame
{
World::World(Game* parent, IPhysicsWorld* _physScene, LifeGraphics::IRenderOutput* output)
:main_camera(nullptr)
{
visualScene = new LifeGraphics::IScene(output->GetWindow()->GetWidth(), output->GetWindow()->GetHeight());
physicsScene = _physScene;
render_out = output;
render_out->GetWindow()->Event_Resize += NewDelegate(this, &LifeGame::World::OnResize);
pGame = parent;
gui_manager = new LifeGUI::GUIOverlayManager();
gui_manager->SetSize(output->GetWindow()->GetWidth(), output->GetWindow()->GetHeight());
}
World::~World(){
}
void World::OnResize(LifeCore::IRenderWindow* sender){
printf("Resize world!\n");
GetGraphicsScene()->ResizeOutput(sender->GetWidth(), sender->GetHeight());
GetGUI()->SetSize(sender->GetWidth(), sender->GetHeight());
}
void World::Render(){
pGame->GetGraphics()->RenderScene(visualScene, render_out);
gui_manager->Render();
}
LifeGUI::GUIOverlayManager* World::GetGUI(){
return gui_manager;
}
LifeGraphics::IScene* World::GetGraphicsScene(){
return visualScene;
}
LifeGraphics::IRenderOutput* World::GetOutput(){
return render_out;
}
void World::SetMainCamera(GameCamera* cam){
for(auto s_cam : scene_cameras){
if(s_cam == cam){
main_camera = cam;
LOG_MESSAGE("Scene: Main camera selected!");
}
}
}
void World::AddEntity(Entity* e)
{
if(e)
{
objects.push_back(e);
if(e->GetGraphicalEntity())
{
visualScene->PushNode(e->GetGraphicalEntity()->pMesh);
}
if(e->GetPhysicsEntity())
{
physicsScene->AddObject(e->GetPhysicsEntity());
}
GameCamera* cam = dynamic_cast<GameCamera*>(e);
if(cam != nullptr){
scene_cameras.push_back(cam);
LOG_MESSAGE("Scene: Camera added!");
if(main_camera == nullptr){
SetMainCamera(cam);
}
}
}
}
void World::AddActionProvider(IActionProvider* provider){
action_providers.push_back(provider);
}
void World::Update(float timeElapsed)
{
if(main_camera != nullptr)
GetGraphicsScene()->SetMainCamera(main_camera->getCam());
for(EntityList::iterator it = objects.begin(); it != objects.end(); ++it)
{
Entity* e = (*it);
if(e->IsEnabled())
{
e->Update(timeElapsed);
}
}
for(auto provider : action_providers){
provider->Update();
}
visualScene->Update(timeElapsed);
}
}
+48
View File
@@ -0,0 +1,48 @@
#ifndef World_h__
#define World_h__
#include "Entity.h"
#include <GUIOverlayManager.h>
#include "IScene.h"
#include "IPhysicsWorld.h"
#include <IRenderOutput.h>
#include <vector>
#include "CGUIRenderer.h"
#include <IInputSystem.h>
#include <IInputListener.h>
#include "IActionProvider.h"
#include "GameCamera.h"
namespace LifeGame
{
class Game;
class World : public LifeCore::IInputListener
{
public:
World(Game* parent, IPhysicsWorld* _physScene, LifeGraphics::IRenderOutput* output);
~World();
void AddEntity(Entity* e);
void Update(float timeElapsed);
void Render();
LifeGUI::GUIOverlayManager* GetGUI();
LifeGraphics::IRenderOutput* GetOutput();
LifeGraphics::IScene* GetGraphicsScene();
void AddActionProvider(IActionProvider* provider);
void SetMainCamera(GameCamera* cam);
private:
void OnResize(LifeCore::IRenderWindow* sender);
typedef std::vector<Entity*> EntityList;
EntityList objects;
LifeGraphics::IScene* visualScene;
IPhysicsWorld* physicsScene;
Game* pGame;
LifeGUI::GUIOverlayManager* gui_manager;
LifeGraphics::IRenderOutput* render_out;
std::vector<IActionProvider*> action_providers;
std::vector<GameCamera*> scene_cameras;
GameCamera* main_camera;
};
}
#endif // World_h__
+64
View File
@@ -0,0 +1,64 @@
#include "script/Script.h"
#include <log/CLog.h>
#include <Error.h>
Script::Script()
{
LOG_ERROR("Can not create new instance of Script! Script objects must be created ONLY inside ScriptSystem class!", "Script", "Script");
throw std::bad_exception("Can not create Script instance outside of ScriptSystem class!");
}
Script::Script(asIScriptEngine* engine, const String& module)
:pObj(0), pEngine(0), pContext(0)
{
pEngine = engine;
name = module;
pContext = engine->CreateContext();
Rebuild();
}
void Script::ExecuteGlobalFunction(const String& decl)
{
int id = pModule->GetFunctionIdByDecl(decl.c_str());
if(id >= 0)
{
pContext->Prepare(id);
pContext->Execute();
}
}
int Script::Rebuild()
{
pModule = pEngine->GetModule(name.c_str());
if(pModule == 0 || pEngine == 0)
{
LOG_ERROR("Can not create script object! Module us undefined", "Script", "Script");
return SC_FAIL;
}
int id = pModule->GetTypeIdByDecl(name.c_str());
if(pObj)
{
pObj->Release();
}
pObj = (asIScriptObject*)pEngine->CreateScriptObject(id);
pObj->AddRef();
if(pContext == 0)
pContext = pEngine->CreateContext();
}
Script::~Script()
{
if(pContext)
{
pContext->Release();
}
if(pObj)
{
pObj->Release();
}
}
const String& Script::GetName()
{
return name;
}
+25
View File
@@ -0,0 +1,25 @@
#ifndef Script_h__
#define Script_h__
#include <angelscript.h>
#include <LString.h>
class Script
{
friend class ScriptSystem;
public:
Script();
~Script();
const String& GetName();
int Rebuild();
void ExecuteGlobalFunction(const String& decl);
//int GetObjectParam(const String& name);
private:
Script(asIScriptEngine* engine, const String& module);
String name;
asIScriptEngine* pEngine;
asIScriptContext* pContext;
asIScriptObject* pObj;
asIScriptModule* pModule;
};
#endif // Script_h__
+105
View File
@@ -0,0 +1,105 @@
#include "script/ScriptSystem.h"
#include <scriptstdstring.h>
#include <log/CLog.h>
ScriptSystem::ScriptSystem(LifeCore::IFileSystem* fileSystem)
{
pFs = fileSystem;
pEngine = asCreateScriptEngine(ANGELSCRIPT_VERSION);
RegisterStdString(pEngine);
int r;
//register ScriptSystem
r = pEngine->RegisterObjectType("ScriptSystem", 0, asOBJ_REF | asOBJ_NOHANDLE);
if(r < 0)
{
printf("FUCK!");
}
r = pEngine->RegisterObjectMethod("ScriptSystem", "int ReloadScript(const string &in)", asMETHODPR(ScriptSystem, ReloadScript, (const String&), int), asCALL_THISCALL);
if(r < 0)
{
printf("FUCK!");
}
r = pEngine->RegisterGlobalProperty("ScriptSystem ScriptEngine", this);
if(r < 0)
{
printf("FUCK!");
}
}
ScriptSystem::~ScriptSystem()
{
for(ScriptVectorIterator it = scripts.begin(); it != scripts.end(); ++it)
{
delete *it;
}
}
int ScriptSystem::ReloadScript(const String& path)
{
LifeCore::IFile* scriptFile;
if(pFs->GetFile(path, &scriptFile) != SC_OK)
{
LOG_ERROR("Can't load script! Invalid file specified.", "ScriptSystem", "LoadScript");
return SC_FAIL;
}
LifeCore::IDataStreamPtr stm = scriptFile->OpenRead();
String moduleName = GetFileNameWithoutExtention(path);
asIScriptModule* pModule;
pModule = pEngine->GetModule(moduleName.c_str());
CScriptBuilder builder;
int r = builder.StartNewModule(pEngine, moduleName.c_str());
//read script text from file
char* buffer = new char[stm->Length() + 1];
//+1 just to make sure that everything will go fine! Because file many not contain null terminating character!
buffer[stm->Length()] = '\0';
stm->Read(buffer, stm->Length());
stm.release();
//build new script module
r = builder.AddSectionFromMemory(buffer);
r = builder.BuildModule();
//if module is loaded not the first time - we have to rebuild all objects, created from this module
if(pModule != 0)
{
for(ScriptVectorIterator it = scripts.begin(); it != scripts.end(); ++it)
{
if((*it)->GetName() == moduleName)
{
(*it)->Rebuild();
}
}
}
return SC_OK;
}
int ScriptSystem::NewScript(const String& file, Script** output)
{
if(pEngine == 0 || file == "")
return SC_FAIL;
String module = GetFileNameWithoutExtention(file);
asIScriptModule* pModule;
pModule = pEngine->GetModule(module.c_str());
if(pModule == 0)
{
ReloadScript(file);
}
Script* script = new Script(pEngine, module);
scripts.push_back(script);
*output = script;
return SC_OK;
}
asIScriptEngine* ScriptSystem::GetEngine()
{
return pEngine;
}
+26
View File
@@ -0,0 +1,26 @@
#ifndef ScriptSystem_h__
#define ScriptSystem_h__
#include <LString.h>
#include <vfs/IFileSystem.h>
#include "script/Script.h"
#include <angelscript.h>
#include <scriptbuilder.h>
#include <vector>
class ScriptSystem
{
public:
ScriptSystem(LifeCore::IFileSystem* fileSystem);
~ScriptSystem();
asIScriptEngine* GetEngine();
int ReloadScript(const String& path);
int NewScript(const String& file, Script** output);
private:
LifeCore::IFileSystem* pFs;
asIScriptEngine* pEngine;
typedef std::vector<Script*> ScriptVector;
typedef std::vector<Script*>::iterator ScriptVectorIterator;
ScriptVector scripts;
};
#endif // ScriptSystem_h__