From 9f056b4cfe458f0d2bc15ab89bbb7656de8a72a8 Mon Sep 17 00:00:00 2001 From: turanszkij Date: Fri, 26 Oct 2018 18:35:11 +0100 Subject: [PATCH] updated engine initialization logic; fade manager is now time-based instead of frame-based; wiImage moved to namespace instead of static class; refactors; editor updates; contributing updates; --- CODE_OF_CONDUCT.md | 47 +- CONTRIBUTING.md | 6 +- Documentation/ScriptingAPI-Documentation.md | 2 +- Editor/Editor.cpp | 4 +- Editor/MeshWindow.cpp | 4 +- Tests/Tests.cpp | 3 +- Tests/test_script.lua | 7 +- WickedEngine/ConstantBufferMapping.h | 42 +- WickedEngine/MainComponent.cpp | 60 +- WickedEngine/MainComponent.h | 20 +- WickedEngine/MainComponent_BindLua.cpp | 20 +- WickedEngine/ShaderInterop_Font.h | 13 + WickedEngine/WickedEngine_SHARED.vcxitems | 3 + .../WickedEngine_SHARED.vcxitems.filters | 5 + WickedEngine/fontPS.hlsl | 3 +- WickedEngine/fontVS.hlsl | 7 +- WickedEngine/wiCube.cpp | 65 +- WickedEngine/wiCube.h | 11 +- WickedEngine/wiEmittedParticle.cpp | 119 +- WickedEngine/wiEmittedParticle.h | 23 +- WickedEngine/wiFFTGenerator.cpp | 13 +- WickedEngine/wiFFTGenerator.h | 4 - WickedEngine/wiFadeManager.cpp | 37 +- WickedEngine/wiFadeManager.h | 17 +- WickedEngine/wiFont.cpp | 309 ++-- WickedEngine/wiFont.h | 39 +- WickedEngine/wiGPUBVH.cpp | 6 +- WickedEngine/wiGPUSortLib.cpp | 20 +- WickedEngine/wiGraphicsDevice.h | 23 +- WickedEngine/wiGraphicsDevice_DX11.cpp | 2 +- WickedEngine/wiGraphicsDevice_DX12.cpp | 2 +- WickedEngine/wiGraphicsDevice_Vulkan.cpp | 2 +- WickedEngine/wiHairParticle.cpp | 425 +++--- WickedEngine/wiHairParticle.h | 19 +- WickedEngine/wiImage.cpp | 1302 +++++++++-------- WickedEngine/wiImage.h | 85 +- WickedEngine/wiInitializer.cpp | 48 +- WickedEngine/wiInitializer.h | 9 +- WickedEngine/wiLensFlare.cpp | 313 ++-- WickedEngine/wiLensFlare.h | 25 +- WickedEngine/wiRenderer.cpp | 64 +- WickedEngine/wiResourceManager.cpp | 12 +- WickedEngine/wiResourceManager.h | 1 - WickedEngine/wiSceneSystem.cpp | 14 +- WickedEngine/wiSceneSystem.h | 4 + WickedEngine/wiSprite.h | 2 +- WickedEngine/wiVersion.cpp | 2 +- scripts/camera_animation_clamped.lua | 10 +- scripts/camera_animation_repeat.lua | 10 +- 49 files changed, 1630 insertions(+), 1653 deletions(-) create mode 100644 WickedEngine/ShaderInterop_Font.h diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md index a97bc4194..b5eb9e199 100644 --- a/CODE_OF_CONDUCT.md +++ b/CODE_OF_CONDUCT.md @@ -1,46 +1,11 @@ -# Contributor Covenant Code of Conduct +# Code of Conduct -## Our Pledge +The home of Wicked Engine is GitHub for now: https://github.com/turanszkij/WickedEngine -In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. +There you can open issues, pull requests. You can take a look at contributions guidelines: https://github.com/turanszkij/WickedEngine/blob/master/CONTRIBUTING.md -## Our Standards +The primary hub for general conversations: https://gitter.im/WickedEngine/Lobby -Examples of behavior that contributes to creating a positive environment include: +Just be nice and everything should be fine. -* Using welcoming and inclusive language -* Being respectful of differing viewpoints and experiences -* Gracefully accepting constructive criticism -* Focusing on what is best for the community -* Showing empathy towards other community members - -Examples of unacceptable behavior by participants include: - -* The use of sexualized language or imagery and unwelcome sexual attention or advances -* Trolling, insulting/derogatory comments, and personal or political attacks -* Public or private harassment -* Publishing others' private information, such as a physical or electronic address, without explicit permission -* Other conduct which could reasonably be considered inappropriate in a professional setting - -## Our Responsibilities - -Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. - -Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. - -## Scope - -This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. - -## Enforcement - -Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at turanszkij@gmail.com. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. - -Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. - -## Attribution - -This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] - -[homepage]: http://contributor-covenant.org -[version]: http://contributor-covenant.org/version/1/4/ +Also, don't panic and thanks for all the fish! diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index bc02df632..89732efe2 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,16 +1,14 @@ # Contributions are welcome! You should be familiar with the following few guidelines before you contribute any code. These are not set in stone, if there is a good argument, I am very much open to change. You can submit a pull request with your changes, briefly describe them and I will review as soon as I can! -## First, let's get the boring code formatting guidelines out of the way: +## Some guidelines, which can be broken if you have a good reason: - use the default Visual Studio 2017 formatting - generally, function names start with Uppercase, variable names with lowercase - Very short, inline function names can start with lowercase - member and global variables usually use camelCase formatting: int myGlobalVariable; - temporary variables on stack sometimes use lowercase formatting like this: int tmp_variable_on_stack; - prefer having braces on their own line when writing loops, branches, functions or whatever - -## Now, on to some more interesting stuff: -- avoid using c++ stl containers if possible (std::vector is fine) (todo: there are still some offenders remaining in the code) +- avoid using c++ stl containers if possible (std::vector is acceptable, or unordered_map, but use them sparingly) - avoid new and malloc and generally allocating on heap wherever you can. Especially avoid it in frequently called code! Note that by default, c++ std:: lib will allocate on heap. - you can use auto keyword, but aim for as small scope as possible - using auto keyword for iterators is encouraged diff --git a/Documentation/ScriptingAPI-Documentation.md b/Documentation/ScriptingAPI-Documentation.md index 240e30129..765ecd80c 100644 --- a/Documentation/ScriptingAPI-Documentation.md +++ b/Documentation/ScriptingAPI-Documentation.md @@ -311,7 +311,7 @@ The main component which holds information and manages the running of the curren - [void-constructor]MainComponent() - GetContent() : Resource? result - GetActiveComponent() : RenderableComponent? result -- SetActiveComponent(RenderableComponent component, opt int fadeFrames,fadeColorR,fadeColorG,fadeColorB) +- SetActiveComponent(RenderableComponent component, opt float fadeSeconds,fadeColorR,fadeColorG,fadeColorB) - SetFrameSkip(bool enabled) - SetInfoDisplay(bool active) - SetWatermarkDisplay(bool active) diff --git a/Editor/Editor.cpp b/Editor/Editor.cpp index a5949e70a..b37e462b5 100644 --- a/Editor/Editor.cpp +++ b/Editor/Editor.cpp @@ -522,10 +522,10 @@ void EditorComponent::Load() } }); loader->onFinished([=] { - main->activateComponent(this, 10, wiColor::Black); + main->activateComponent(this, 0.2f, wiColor::Black); weatherWnd->UpdateFromRenderer(); }); - main->activateComponent(loader, 10, wiColor::Black); + main->activateComponent(loader, 0.2f, wiColor::Black); ResetHistory(); } }).detach(); diff --git a/Editor/MeshWindow.cpp b/Editor/MeshWindow.cpp index 1a924eceb..be8266092 100644 --- a/Editor/MeshWindow.cpp +++ b/Editor/MeshWindow.cpp @@ -266,12 +266,12 @@ void MeshWindow::SetEntity(Entity entity) } tessellationFactorSlider->SetValue(mesh->GetTessellationFactor()); - softbodyCheckBox->SetEnabled(false); + softbodyCheckBox->SetCheck(false); SoftBodyPhysicsComponent* physicscomponent = wiRenderer::GetScene().softbodies.GetComponent(entity); if (physicscomponent != nullptr) { - softbodyCheckBox->SetEnabled(true); + softbodyCheckBox->SetCheck(true); massSlider->SetValue(physicscomponent->mass); frictionSlider->SetValue(physicscomponent->friction); } diff --git a/Tests/Tests.cpp b/Tests/Tests.cpp index 11edac7a0..7694b7a82 100644 --- a/Tests/Tests.cpp +++ b/Tests/Tests.cpp @@ -69,6 +69,7 @@ TestsRenderer::TestsRenderer() testSelector->SetMaxVisibleItemCount(100); testSelector->OnSelect([=](wiEventArgs args) { + wiRenderer::SetToDrawGridHelper(false); wiRenderer::SetTemporalAAEnabled(false); wiRenderer::ClearWorld(); wiRenderer::GetScene().weather = WeatherComponent(); @@ -101,7 +102,7 @@ TestsRenderer::TestsRenderer() wiRenderer::LoadModel("../models/hairparticle_torus.wiscene", XMMatrixTranslation(0, 1, 0)); break; case 5: - wiRenderer::SetTemporalAAEnabled(true); + wiRenderer::SetToDrawGridHelper(true); wiLua::GetGlobal()->RunFile("test_script.lua"); break; case 6: diff --git a/Tests/test_script.lua b/Tests/test_script.lua index 1021f729f..54ce89f20 100644 --- a/Tests/test_script.lua +++ b/Tests/test_script.lua @@ -5,6 +5,11 @@ debugout("Begin script: test_script.lua"); -- Load a model: LoadModel("../models/teapot.wiscene"); +LoadModel("../models/cameras.wiscene"); + +-- Load camera sample script: +dofile("../scripts/camera_animation_repeat.lua"); +ToggleCameraAnimation(); -- Load an image: local sprite = Sprite("images/HelloWorld.png"); @@ -64,7 +69,7 @@ runProcess(function() -- Rotate teapot by parent transform: local transform = scene.Component_GetTransform(parent); - transform.Rotate(Vector(0, 0.01, 0)); + transform.Rotate(Vector(0, 0, 0.01)); fixedupdate(); -- wait for new frame diff --git a/WickedEngine/ConstantBufferMapping.h b/WickedEngine/ConstantBufferMapping.h index f928190b1..984174af6 100644 --- a/WickedEngine/ConstantBufferMapping.h +++ b/WickedEngine/ConstantBufferMapping.h @@ -13,31 +13,33 @@ #define CBSLOT_IMAGE_IMAGE 3 #define CBSLOT_IMAGE_POSTPROCESS 4 -#define CBSLOT_API 5 +#define CBSLOT_FONT 5 + +#define CBSLOT_API 6 // On demand buffers: // These are bound on demand and alive until another is bound at the same slot -#define CBSLOT_RENDERER_MATERIAL 6 -#define CBSLOT_RENDERER_CUBEMAPRENDER 7 -#define CBSLOT_RENDERER_VOLUMELIGHT 7 -#define CBSLOT_RENDERER_LENSFLARE 7 -#define CBSLOT_RENDERER_DECAL 7 -#define CBSLOT_RENDERER_TESSELLATION 7 -#define CBSLOT_RENDERER_DISPATCHPARAMS 7 -#define CBSLOT_RENDERER_VOXELIZER 7 -#define CBSLOT_RENDERER_TRACED 7 -#define CBSLOT_RENDERER_BVH 7 -#define CBSLOT_RENDERER_UTILITY 7 +#define CBSLOT_RENDERER_MATERIAL 7 +#define CBSLOT_RENDERER_CUBEMAPRENDER 8 +#define CBSLOT_RENDERER_VOLUMELIGHT 8 +#define CBSLOT_RENDERER_LENSFLARE 8 +#define CBSLOT_RENDERER_DECAL 8 +#define CBSLOT_RENDERER_TESSELLATION 8 +#define CBSLOT_RENDERER_DISPATCHPARAMS 8 +#define CBSLOT_RENDERER_VOXELIZER 8 +#define CBSLOT_RENDERER_TRACED 8 +#define CBSLOT_RENDERER_BVH 8 +#define CBSLOT_RENDERER_UTILITY 8 -#define CBSLOT_OTHER_EMITTEDPARTICLE 7 -#define CBSLOT_OTHER_HAIRPARTICLE 7 -#define CBSLOT_OTHER_FFTGENERATOR 7 -#define CBSLOT_OTHER_OCEAN_SIMULATION_IMMUTABLE 7 -#define CBSLOT_OTHER_OCEAN_SIMULATION_PERFRAME 8 -#define CBSLOT_OTHER_OCEAN_RENDER 7 -#define CBSLOT_OTHER_CLOUDGENERATOR 7 -#define CBSLOT_OTHER_GPUSORTLIB 8 +#define CBSLOT_OTHER_EMITTEDPARTICLE 8 +#define CBSLOT_OTHER_HAIRPARTICLE 8 +#define CBSLOT_OTHER_FFTGENERATOR 8 +#define CBSLOT_OTHER_OCEAN_SIMULATION_IMMUTABLE 8 +#define CBSLOT_OTHER_OCEAN_SIMULATION_PERFRAME 9 +#define CBSLOT_OTHER_OCEAN_RENDER 8 +#define CBSLOT_OTHER_CLOUDGENERATOR 8 +#define CBSLOT_OTHER_GPUSORTLIB 9 diff --git a/WickedEngine/MainComponent.cpp b/WickedEngine/MainComponent.cpp index 9752c8a65..383b747fe 100644 --- a/WickedEngine/MainComponent.cpp +++ b/WickedEngine/MainComponent.cpp @@ -28,19 +28,7 @@ MainComponent::MainComponent() // This call also saves the current working dir as the original one on this first call wiHelper::GetOriginalWorkingDirectory(); - screenW = 0; - screenH = 0; - fullscreen = false; - activeComponent = new RenderableComponent(); - - setFrameSkip(true); - setTargetFrameRate(60); - setApplicationControlLostThreshold(10); - - infoDisplay = InfoDisplayer(); - - fadeManager.Clear(); } @@ -83,43 +71,41 @@ void MainComponent::Initialize() } - wiInitializer::InitializeComponents(); + wiInitializer::InitializeComponentsAsync(); wiLua::GetGlobal()->RegisterObject(MainComponent_BindLua::className, "main", new MainComponent_BindLua(this)); } -void MainComponent::activateComponent(RenderableComponent* component, int fadeFrames, const wiColor& fadeColor) +void MainComponent::activateComponent(RenderableComponent* component, float fadeSeconds, const wiColor& fadeColor) { if (component == nullptr) { return; } - if (fadeFrames > 0) - { - // Fade - fadeManager.Clear(); - fadeManager.Start(fadeFrames, fadeColor, [this,component]() { - if (component == nullptr) - return; - activeComponent->Stop(); - component->Start(); - activeComponent = component; - }); - } - else - { - // No fade - fadeManager.Clear(); - + // Fade manager will activate on fadeout + fadeManager.Clear(); + fadeManager.Start(fadeSeconds, fadeColor, [this,component]() { + if (component == nullptr) + return; activeComponent->Stop(); component->Start(); activeComponent = component; - } + }); } void MainComponent::Run() { + if (!wiInitializer::IsInitializeFinished()) + { + // Until engine is not loaded, present initialization screen... + wiRenderer::GetDevice()->PresentBegin(); + wiFont::BindPersistentState(GRAPHICSTHREAD_IMMEDIATE); + wiFont("Initializing Wicked Engine, please wait...", wiFontProps(4, 4, infoDisplay.size)).Draw(GRAPHICSTHREAD_IMMEDIATE); + wiRenderer::GetDevice()->PresentEnd(); + return; + } + wiProfiler::GetInstance().BeginFrame(); wiProfiler::GetInstance().BeginRange("CPU Frame", wiProfiler::DOMAIN_CPU); @@ -130,6 +116,8 @@ void MainComponent::Run() const double elapsedTime = max(0, timer.elapsed() / 1000.0); timer.record(); + fadeManager.Update((float)elapsedTime); + // Fixed time update: wiProfiler::GetInstance().BeginRange("Fixed Update", wiProfiler::DOMAIN_CPU); if (frameskip) @@ -196,8 +184,6 @@ void MainComponent::FixedUpdate() wiLua::GetGlobal()->FixedUpdate(); getActiveComponent()->FixedUpdate(); - - fadeManager.Update(); } void MainComponent::Render() @@ -205,8 +191,8 @@ void MainComponent::Render() wiLua::GetGlobal()->Render(); wiProfiler::GetInstance().BeginRange("GPU Frame", wiProfiler::DOMAIN_GPU, GRAPHICSTHREAD_IMMEDIATE); - wiRenderer::BindPersistentState(GRAPHICSTHREAD_IMMEDIATE); wiImage::BindPersistentState(GRAPHICSTHREAD_IMMEDIATE); + wiFont::BindPersistentState(GRAPHICSTHREAD_IMMEDIATE); getActiveComponent()->Render(); wiProfiler::GetInstance().EndRange(GRAPHICSTHREAD_IMMEDIATE); // GPU Frame } @@ -253,6 +239,10 @@ void MainComponent::Compose() #endif ss << endl; } + if (infoDisplay.initstats) + { + ss << "System init time: " << wiInitializer::GetInitializationTimeInSeconds() << " sec" << endl; + } if (infoDisplay.resolution) { ss << "Resolution: " << wiRenderer::GetDevice()->GetScreenWidth() << " x " << wiRenderer::GetDevice()->GetScreenHeight() << endl; diff --git a/WickedEngine/MainComponent.h b/WickedEngine/MainComponent.h index 49556ad05..3b793251a 100644 --- a/WickedEngine/MainComponent.h +++ b/WickedEngine/MainComponent.h @@ -10,24 +10,26 @@ class RenderableComponent; class MainComponent { private: - RenderableComponent* activeComponent; - bool frameskip; - int targetFrameRate; - double targetFrameRateInv; - int applicationControlLostThreshold; + RenderableComponent* activeComponent = nullptr; + bool frameskip = true; + int targetFrameRate = 60; + double targetFrameRateInv = 1.0f / 60.0f; + int applicationControlLostThreshold = 10; + bool component_dirty = true; wiFadeManager fadeManager; public: MainComponent(); virtual ~MainComponent(); - int screenW, screenH; - bool fullscreen; + int screenW = 0; + int screenH = 0; + bool fullscreen = false; // Runs the main engine loop void Run(); - void activateComponent(RenderableComponent* component, int fadeFrames = 0, const wiColor& fadeColor = wiColor(0,0,0,255)); + void activateComponent(RenderableComponent* component, float fadeSeconds = 0, const wiColor& fadeColor = wiColor(0,0,0,255)); RenderableComponent* getActiveComponent(){ return activeComponent; } wiResourceManager Content; @@ -67,6 +69,8 @@ public: bool cpuinfo; // display resolution info bool resolution; + // display engine initialization time + bool initstats; // text size int size; diff --git a/WickedEngine/MainComponent_BindLua.cpp b/WickedEngine/MainComponent_BindLua.cpp index 1442da97a..fe1a3a945 100644 --- a/WickedEngine/MainComponent_BindLua.cpp +++ b/WickedEngine/MainComponent_BindLua.cpp @@ -137,11 +137,11 @@ int MainComponent_BindLua::SetActiveComponent(lua_State *L) int argc = wiLua::SGetArgCount(L); if (argc > 0) { - int fadeFrames = 0; + float fadeSeconds = 0; wiColor fadeColor = wiColor(0, 0, 0, 255); if (argc > 1) { - fadeFrames = wiLua::SGetInt(L, 2); + fadeSeconds = wiLua::SGetFloat(L, 2); if (argc > 2) { fadeColor.r = wiLua::SGetInt(L, 3); @@ -159,56 +159,56 @@ int MainComponent_BindLua::SetActiveComponent(lua_State *L) ForwardRenderableComponent_BindLua* compFwd3D = Luna::lightcheck(L, 1); if (compFwd3D != nullptr) { - component->activateComponent(compFwd3D->component, fadeFrames, fadeColor); + component->activateComponent(compFwd3D->component, fadeSeconds, fadeColor); return 0; } DeferredRenderableComponent_BindLua* compDef3D = Luna::lightcheck(L, 1); if (compDef3D != nullptr) { - component->activateComponent(compDef3D->component, fadeFrames, fadeColor); + component->activateComponent(compDef3D->component, fadeSeconds, fadeColor); return 0; } TiledDeferredRenderableComponent_BindLua* compTDef3D = Luna::lightcheck(L, 1); if (compTDef3D != nullptr) { - component->activateComponent(compTDef3D->component, fadeFrames, fadeColor); + component->activateComponent(compTDef3D->component, fadeSeconds, fadeColor); return 0; } TiledForwardRenderableComponent_BindLua* compTFwd3D = Luna::lightcheck(L, 1); if (compTFwd3D != nullptr) { - component->activateComponent(compTFwd3D->component, fadeFrames, fadeColor); + component->activateComponent(compTFwd3D->component, fadeSeconds, fadeColor); return 0; } Renderable3DComponent_BindLua* comp3D = Luna::lightcheck(L, 1); if (comp3D != nullptr) { - component->activateComponent(comp3D->component, fadeFrames, fadeColor); + component->activateComponent(comp3D->component, fadeSeconds, fadeColor); return 0; } LoadingScreenComponent_BindLua* compLoad = Luna::lightcheck(L, 1); if (compLoad != nullptr) { - component->activateComponent(compLoad->component, fadeFrames, fadeColor); + component->activateComponent(compLoad->component, fadeSeconds, fadeColor); return 0; } Renderable2DComponent_BindLua* comp2D = Luna::lightcheck(L, 1); if (comp2D != nullptr) { - component->activateComponent(comp2D->component, fadeFrames, fadeColor); + component->activateComponent(comp2D->component, fadeSeconds, fadeColor); return 0; } RenderableComponent_BindLua* comp = Luna::lightcheck(L, 1); if (comp != nullptr) { - component->activateComponent(comp->component, fadeFrames, fadeColor); + component->activateComponent(comp->component, fadeSeconds, fadeColor); return 0; } } diff --git a/WickedEngine/ShaderInterop_Font.h b/WickedEngine/ShaderInterop_Font.h new file mode 100644 index 000000000..d2bb7fcb9 --- /dev/null +++ b/WickedEngine/ShaderInterop_Font.h @@ -0,0 +1,13 @@ +#ifndef _SHADERINTEROP_FONT_H_ +#define _SHADERINTEROP_FONT_H_ + +#include "ShaderInterop.h" + +CBUFFER(FontCB, CBSLOT_FONT) +{ + float4x4 g_xFont_Transform; + float4 g_xFont_Color; +}; + + +#endif // _SHADERINTEROP_FONT_H_ diff --git a/WickedEngine/WickedEngine_SHARED.vcxitems b/WickedEngine/WickedEngine_SHARED.vcxitems index 6dc2bad60..8d678ba5f 100644 --- a/WickedEngine/WickedEngine_SHARED.vcxitems +++ b/WickedEngine/WickedEngine_SHARED.vcxitems @@ -234,6 +234,7 @@ + @@ -726,6 +727,8 @@ + + diff --git a/WickedEngine/WickedEngine_SHARED.vcxitems.filters b/WickedEngine/WickedEngine_SHARED.vcxitems.filters index 5595b500f..d837623c2 100644 --- a/WickedEngine/WickedEngine_SHARED.vcxitems.filters +++ b/WickedEngine/WickedEngine_SHARED.vcxitems.filters @@ -1146,6 +1146,9 @@ ENGINE\Graphics + + ENGINE\Graphics\GPUMapping + @@ -1970,6 +1973,8 @@ Documentation + + diff --git a/WickedEngine/fontPS.hlsl b/WickedEngine/fontPS.hlsl index b1fc0b667..75e73e9ab 100644 --- a/WickedEngine/fontPS.hlsl +++ b/WickedEngine/fontPS.hlsl @@ -1,4 +1,5 @@ #include "globals.hlsli" +#include "ShaderInterop_Font.h" struct VertextoPixel { @@ -8,5 +9,5 @@ struct VertextoPixel float4 main(VertextoPixel PSIn) : SV_TARGET { - return texture_1.Sample(sampler_linear_clamp, PSIn.tex) * g_xColor; + return texture_1.Sample(sampler_linear_clamp, PSIn.tex) * g_xFont_Color; } \ No newline at end of file diff --git a/WickedEngine/fontVS.hlsl b/WickedEngine/fontVS.hlsl index dc4e4605d..4590c28a6 100644 --- a/WickedEngine/fontVS.hlsl +++ b/WickedEngine/fontVS.hlsl @@ -1,4 +1,5 @@ #include "globals.hlsli" +#include "ShaderInterop_Font.h" struct VertextoPixel { @@ -8,11 +9,11 @@ struct VertextoPixel VertextoPixel main(float2 inPos : POSITION, float2 inTex : TEXCOORD0) { - VertextoPixel Out = (VertextoPixel)0; + VertextoPixel Out; - Out.pos = mul(float4(inPos, 0, 1), g_xTransform); + Out.pos = mul(float4(inPos, 0, 1), g_xFont_Transform); - Out.tex=inTex; + Out.tex = inTex; return Out; } diff --git a/WickedEngine/wiCube.cpp b/WickedEngine/wiCube.cpp index 9ad9c96ab..e26102ef9 100644 --- a/WickedEngine/wiCube.cpp +++ b/WickedEngine/wiCube.cpp @@ -3,8 +3,8 @@ using namespace wiGraphicsTypes; -GPUBuffer Cube::vertexBuffer; -GPUBuffer Cube::indexBuffer; +static GPUBuffer vertexBuffer; +static GPUBuffer indexBuffer; Cube::Cube(const XMFLOAT3& center, const XMFLOAT3& halfwidth, const XMFLOAT4& color) { @@ -16,26 +16,29 @@ Cube::Cube(const XMFLOAT3& center, const XMFLOAT3& halfwidth, const XMFLOAT4& co } -void Cube::CleanUpStatic() +void Cube::Transform(const XMFLOAT4X4& mat) { - + desc.transform=mat; +} +void Cube::Transform(const XMMATRIX& mat) +{ + XMStoreFloat4x4( &desc.transform,mat ); } -void Cube::SetUpVertices() + +GPUBuffer* Cube::GetVertexBuffer() { + return &vertexBuffer; +} +GPUBuffer* Cube::GetIndexBuffer() +{ + return &indexBuffer; +} - //Vertex* verts = new Vertex[8]; - +void Cube::Initialize() +{ XMFLOAT4 min = XMFLOAT4(-1, -1, -1, 1); XMFLOAT4 max = XMFLOAT4(1, 1, 1, 1); - //verts[0].pos=min; - //verts[1].pos=XMFLOAT3(min.x,max.y,min.z); - //verts[2].pos=XMFLOAT3(min.x,max.y,max.z); - //verts[3].pos=XMFLOAT3(min.x,min.y,max.z); - //verts[4].pos=XMFLOAT3(max.x,min.y,min.z); - //verts[5].pos=XMFLOAT3(max.x,max.y,min.z); - //verts[6].pos=max; - //verts[7].pos=XMFLOAT3(max.x,min.y,max.z); XMFLOAT4 verts[] = { min, XMFLOAT4(1,1,1,1), @@ -49,45 +52,31 @@ void Cube::SetUpVertices() }; GPUBufferDesc bd; - ZeroMemory( &bd, sizeof(bd) ); + ZeroMemory(&bd, sizeof(bd)); bd.Usage = USAGE_DEFAULT; bd.ByteWidth = sizeof(verts); bd.BindFlags = BIND_VERTEX_BUFFER; bd.CPUAccessFlags = 0; SubresourceData InitData; - ZeroMemory( &InitData, sizeof(InitData) ); + ZeroMemory(&InitData, sizeof(InitData)); InitData.pSysMem = verts; - wiRenderer::GetDevice()->CreateBuffer( &bd, &InitData, &vertexBuffer ); + wiRenderer::GetDevice()->CreateBuffer(&bd, &InitData, &vertexBuffer); - //if(verts){ - // delete[](verts); - // verts=NULL; - //} - - uint16_t indices[]={ + uint16_t indices[] = { 0,1,1,2,0,3,0,4,1,5,4,5, 5,6,4,7,2,6,3,7,2,3,6,7 }; - ZeroMemory( &bd, sizeof(bd) ); + ZeroMemory(&bd, sizeof(bd)); bd.Usage = USAGE_DEFAULT; bd.ByteWidth = sizeof(indices); bd.BindFlags = BIND_INDEX_BUFFER; bd.CPUAccessFlags = 0; - ZeroMemory( &InitData, sizeof(InitData) ); + ZeroMemory(&InitData, sizeof(InitData)); InitData.pSysMem = indices; - wiRenderer::GetDevice()->CreateBuffer( &bd, &InitData, &indexBuffer ); + wiRenderer::GetDevice()->CreateBuffer(&bd, &InitData, &indexBuffer); } - -void Cube::Transform(const XMFLOAT4X4& mat) +void Cube::CleanUp() { - desc.transform=mat; + } -void Cube::Transform(const XMMATRIX& mat) -{ - XMStoreFloat4x4( &desc.transform,mat ); -} - -void Cube::LoadStatic(){ - SetUpVertices(); -} \ No newline at end of file diff --git a/WickedEngine/wiCube.h b/WickedEngine/wiCube.h index 43adb5ea6..f8b01c83b 100644 --- a/WickedEngine/wiCube.h +++ b/WickedEngine/wiCube.h @@ -22,7 +22,6 @@ private: ); }; }; - static void SetUpVertices(); public: Cube(const XMFLOAT3& center=XMFLOAT3(0,0,0), const XMFLOAT3& halfwidth=XMFLOAT3(1,1,1), const XMFLOAT4& color = XMFLOAT4(1,1,1,1)); @@ -31,11 +30,11 @@ public: Description desc; - static wiGraphicsTypes::GPUBuffer vertexBuffer; - static wiGraphicsTypes::GPUBuffer indexBuffer; - static void LoadStatic(); - static void CleanUpStatic(); + static wiGraphicsTypes::GPUBuffer* GetVertexBuffer(); + static wiGraphicsTypes::GPUBuffer* GetIndexBuffer(); + + static void Initialize(); + static void CleanUp(); - ALIGN_16 }; diff --git a/WickedEngine/wiEmittedParticle.cpp b/WickedEngine/wiEmittedParticle.cpp index b7e47c1ba..0bbe723fd 100644 --- a/WickedEngine/wiEmittedParticle.cpp +++ b/WickedEngine/wiEmittedParticle.cpp @@ -17,20 +17,41 @@ using namespace wiGraphicsTypes; namespace wiSceneSystem { -VertexShader *wiEmittedParticle::vertexShader = nullptr; -PixelShader *wiEmittedParticle::pixelShader[PARTICLESHADERTYPE_COUNT] = {}; -ComputeShader *wiEmittedParticle::kickoffUpdateCS = nullptr, *wiEmittedParticle::finishUpdateCS = nullptr, *wiEmittedParticle::emitCS = nullptr, *wiEmittedParticle::emitCS_FROMMESH = nullptr, *wiEmittedParticle::sphpartitionCS = nullptr, - *wiEmittedParticle::sphpartitionoffsetsCS = nullptr, *wiEmittedParticle::sphpartitionoffsetsresetCS = nullptr, *wiEmittedParticle::sphdensityCS = nullptr, *wiEmittedParticle::sphforceCS = nullptr, - *wiEmittedParticle::simulateCS = nullptr, *wiEmittedParticle::simulateCS_SORTING = nullptr, *wiEmittedParticle::simulateCS_DEPTHCOLLISIONS = nullptr, *wiEmittedParticle::simulateCS_SORTING_DEPTHCOLLISIONS = nullptr; +static VertexShader* vertexShader = nullptr; +static PixelShader* pixelShader[wiEmittedParticle::PARTICLESHADERTYPE_COUNT] = {}; +static ComputeShader* kickoffUpdateCS = nullptr; +static ComputeShader* finishUpdateCS = nullptr; +static ComputeShader* emitCS = nullptr; +static ComputeShader* emitCS_FROMMESH = nullptr; +static ComputeShader* sphpartitionCS = nullptr; +static ComputeShader* sphpartitionoffsetsCS = nullptr; +static ComputeShader* sphpartitionoffsetsresetCS = nullptr; +static ComputeShader* sphdensityCS = nullptr; +static ComputeShader* sphforceCS = nullptr; +static ComputeShader* simulateCS = nullptr; +static ComputeShader* simulateCS_SORTING = nullptr; +static ComputeShader* simulateCS_DEPTHCOLLISIONS = nullptr; +static ComputeShader* simulateCS_SORTING_DEPTHCOLLISIONS = nullptr; -BlendState wiEmittedParticle::blendStates[BLENDMODE_COUNT]; -RasterizerState wiEmittedParticle::rasterizerState, wiEmittedParticle::wireFrameRS; -DepthStencilState wiEmittedParticle::depthStencilState; -GraphicsPSO wiEmittedParticle::PSO[BLENDMODE_COUNT][PARTICLESHADERTYPE_COUNT]; -GraphicsPSO wiEmittedParticle::PSO_wire; -ComputePSO wiEmittedParticle::CPSO_kickoffUpdate, wiEmittedParticle::CPSO_finishUpdate, wiEmittedParticle::CPSO_emit, wiEmittedParticle::CPSO_emit_FROMMESH, wiEmittedParticle::CPSO_sphpartition, wiEmittedParticle::CPSO_sphpartitionoffsets, - wiEmittedParticle::CPSO_sphpartitionoffsetsreset, wiEmittedParticle::CPSO_sphdensity, wiEmittedParticle::CPSO_sphforce, wiEmittedParticle::CPSO_simulate, - wiEmittedParticle::CPSO_simulate_SORTING, wiEmittedParticle::CPSO_simulate_DEPTHCOLLISIONS, wiEmittedParticle::CPSO_simulate_SORTING_DEPTHCOLLISIONS; +static BlendState blendStates[BLENDMODE_COUNT]; +static RasterizerState rasterizerState; +static RasterizerState wireFrameRS; +static DepthStencilState depthStencilState; +static GraphicsPSO PSO[BLENDMODE_COUNT][wiEmittedParticle::PARTICLESHADERTYPE_COUNT]; +static GraphicsPSO PSO_wire; +static ComputePSO CPSO_kickoffUpdate; +static ComputePSO CPSO_finishUpdate; +static ComputePSO CPSO_emit; +static ComputePSO CPSO_emit_FROMMESH; +static ComputePSO CPSO_sphpartition; +static ComputePSO CPSO_sphpartitionoffsets; +static ComputePSO CPSO_sphpartitionoffsetsreset; +static ComputePSO CPSO_sphdensity; +static ComputePSO CPSO_sphforce; +static ComputePSO CPSO_simulate; +static ComputePSO CPSO_simulate_SORTING; +static ComputePSO CPSO_simulate_DEPTHCOLLISIONS; +static ComputePSO CPSO_simulate_SORTING_DEPTHCOLLISIONS; void wiEmittedParticle::SetMaxParticleCount(uint32_t value) @@ -693,44 +714,44 @@ void wiEmittedParticle::LoadShaders() } } -void wiEmittedParticle::LoadBuffers() -{ -} -void wiEmittedParticle::SetUpStates() +void wiEmittedParticle::Initialize() { + LoadShaders(); + + RasterizerStateDesc rs; - rs.FillMode=FILL_SOLID; - rs.CullMode=CULL_BACK; - rs.FrontCounterClockwise=true; - rs.DepthBias=0; - rs.DepthBiasClamp=0; - rs.SlopeScaledDepthBias=0; - rs.DepthClipEnable=false; - rs.MultisampleEnable=false; - rs.AntialiasedLineEnable=false; - wiRenderer::GetDevice()->CreateRasterizerState(&rs,&rasterizerState); + rs.FillMode = FILL_SOLID; + rs.CullMode = CULL_BACK; + rs.FrontCounterClockwise = true; + rs.DepthBias = 0; + rs.DepthBiasClamp = 0; + rs.SlopeScaledDepthBias = 0; + rs.DepthClipEnable = false; + rs.MultisampleEnable = false; + rs.AntialiasedLineEnable = false; + wiRenderer::GetDevice()->CreateRasterizerState(&rs, &rasterizerState); + + + rs.FillMode = FILL_WIREFRAME; + rs.CullMode = CULL_NONE; + rs.FrontCounterClockwise = true; + rs.DepthBias = 0; + rs.DepthBiasClamp = 0; + rs.SlopeScaledDepthBias = 0; + rs.DepthClipEnable = false; + rs.MultisampleEnable = false; + rs.AntialiasedLineEnable = false; + wiRenderer::GetDevice()->CreateRasterizerState(&rs, &wireFrameRS); - - rs.FillMode=FILL_WIREFRAME; - rs.CullMode=CULL_NONE; - rs.FrontCounterClockwise=true; - rs.DepthBias=0; - rs.DepthBiasClamp=0; - rs.SlopeScaledDepthBias=0; - rs.DepthClipEnable=false; - rs.MultisampleEnable=false; - rs.AntialiasedLineEnable=false; - wiRenderer::GetDevice()->CreateRasterizerState(&rs,&wireFrameRS); - DepthStencilStateDesc dsd; dsd.DepthEnable = false; dsd.StencilEnable = false; wiRenderer::GetDevice()->CreateDepthStencilState(&dsd, &depthStencilState); - + BlendStateDesc bd; - bd.RenderTarget[0].BlendEnable=true; + bd.RenderTarget[0].BlendEnable = true; bd.RenderTarget[0].SrcBlend = BLEND_SRC_ALPHA; bd.RenderTarget[0].DestBlend = BLEND_INV_SRC_ALPHA; bd.RenderTarget[0].BlendOp = BLEND_OP_ADD; @@ -738,10 +759,10 @@ void wiEmittedParticle::SetUpStates() bd.RenderTarget[0].DestBlendAlpha = BLEND_INV_SRC_ALPHA; bd.RenderTarget[0].BlendOpAlpha = BLEND_OP_ADD; bd.RenderTarget[0].RenderTargetWriteMask = COLOR_WRITE_ENABLE_ALL; - bd.IndependentBlendEnable=false; - wiRenderer::GetDevice()->CreateBlendState(&bd,&blendStates[BLENDMODE_ALPHA]); + bd.IndependentBlendEnable = false; + wiRenderer::GetDevice()->CreateBlendState(&bd, &blendStates[BLENDMODE_ALPHA]); - bd.RenderTarget[0].BlendEnable=true; + bd.RenderTarget[0].BlendEnable = true; bd.RenderTarget[0].SrcBlend = BLEND_SRC_ALPHA; bd.RenderTarget[0].DestBlend = BLEND_ONE; bd.RenderTarget[0].BlendOp = BLEND_OP_ADD; @@ -749,7 +770,7 @@ void wiEmittedParticle::SetUpStates() bd.RenderTarget[0].DestBlendAlpha = BLEND_ONE; bd.RenderTarget[0].BlendOpAlpha = BLEND_OP_ADD; bd.RenderTarget[0].RenderTargetWriteMask = COLOR_WRITE_ENABLE_ALL; - bd.IndependentBlendEnable=false; + bd.IndependentBlendEnable = false; wiRenderer::GetDevice()->CreateBlendState(&bd, &blendStates[BLENDMODE_ADDITIVE]); bd.RenderTarget[0].BlendEnable = true; @@ -766,13 +787,7 @@ void wiEmittedParticle::SetUpStates() bd.RenderTarget[0].BlendEnable = false; wiRenderer::GetDevice()->CreateBlendState(&bd, &blendStates[BLENDMODE_OPAQUE]); } -void wiEmittedParticle::SetUpStatic() -{ - LoadBuffers(); - SetUpStates(); - LoadShaders(); -} -void wiEmittedParticle::CleanUpStatic() +void wiEmittedParticle::CleanUp() { SAFE_DELETE(vertexShader); for (int i = 0; i < ARRAYSIZE(pixelShader); ++i) diff --git a/WickedEngine/wiEmittedParticle.h b/WickedEngine/wiEmittedParticle.h index 26b264089..6667242e4 100644 --- a/WickedEngine/wiEmittedParticle.h +++ b/WickedEngine/wiEmittedParticle.h @@ -42,25 +42,6 @@ private: std::unique_ptr constantBuffer; void CreateSelfBuffers(); - static wiGraphicsTypes::ComputeShader *kickoffUpdateCS, *finishUpdateCS, *emitCS, *emitCS_FROMMESH, *sphpartitionCS, *sphpartitionoffsetsCS, *sphpartitionoffsetsresetCS, *sphdensityCS, *sphforceCS, *simulateCS, *simulateCS_SORTING, *simulateCS_DEPTHCOLLISIONS, *simulateCS_SORTING_DEPTHCOLLISIONS; - static wiGraphicsTypes::VertexShader *vertexShader; - static wiGraphicsTypes::PixelShader *pixelShader[PARTICLESHADERTYPE_COUNT]; - static wiGraphicsTypes::BlendState blendStates[BLENDMODE_COUNT]; - static wiGraphicsTypes::RasterizerState rasterizerState,wireFrameRS; - static wiGraphicsTypes::DepthStencilState depthStencilState; - - static wiGraphicsTypes::GraphicsPSO PSO[BLENDMODE_COUNT][PARTICLESHADERTYPE_COUNT]; - static wiGraphicsTypes::GraphicsPSO PSO_wire; - static wiGraphicsTypes::ComputePSO CPSO_kickoffUpdate, CPSO_finishUpdate, CPSO_emit, CPSO_emit_FROMMESH, CPSO_sphpartition, CPSO_sphpartitionoffsets, CPSO_sphpartitionoffsetsreset, CPSO_sphdensity, CPSO_sphforce, CPSO_simulate, CPSO_simulate_SORTING, CPSO_simulate_DEPTHCOLLISIONS, CPSO_simulate_SORTING_DEPTHCOLLISIONS; - -public: - static void LoadShaders(); - static void SetUpStatic(); - static void CleanUpStatic(); -private: - static void LoadBuffers(); - static void SetUpStates(); - float emit = 0.0f; bool buffersUpToDate = false; @@ -131,6 +112,10 @@ public: inline void SetSPHEnabled(bool value) { if (value) { _flags |= SPH_FLUIDSIMULATION; } else { _flags &= ~SPH_FLUIDSIMULATION; } } void Serialize(wiArchive& archive, uint32_t seed = 0); + + static void LoadShaders(); + static void Initialize(); + static void CleanUp(); }; } diff --git a/WickedEngine/wiFFTGenerator.cpp b/WickedEngine/wiFFTGenerator.cpp index 3c2bb1530..9304a0c90 100644 --- a/WickedEngine/wiFFTGenerator.cpp +++ b/WickedEngine/wiFFTGenerator.cpp @@ -9,9 +9,10 @@ using namespace wiGraphicsTypes; -ComputeShader* CSFFT_512x512_Data_t::pRadix008A_CS = nullptr; -ComputeShader* CSFFT_512x512_Data_t::pRadix008A_CS2 = nullptr; -ComputePSO CSFFT_512x512_Data_t::PSO1, CSFFT_512x512_Data_t::PSO2; +static ComputeShader* pRadix008A_CS = nullptr; +static ComputeShader* pRadix008A_CS2 = nullptr; +static ComputePSO PSO1; +static ComputePSO PSO2; void radix008A(CSFFT512x512_Plan* fft_plan, GPUResource* pUAV_Dst, @@ -35,13 +36,11 @@ void radix008A(CSFFT512x512_Plan* fft_plan, // Shader if (istride > 1) { - //device->BindCS(fft_plan->pRadix008A_CS, threadID); - device->BindComputePSO(&fft_plan->PSO1, threadID); + device->BindComputePSO(&PSO1, threadID); } else { - //device->BindCS(fft_plan->pRadix008A_CS2, threadID); - device->BindComputePSO(&fft_plan->PSO2, threadID); + device->BindComputePSO(&PSO2, threadID); } // Execute diff --git a/WickedEngine/wiFFTGenerator.h b/WickedEngine/wiFFTGenerator.h index bb125d587..e6129d365 100644 --- a/WickedEngine/wiFFTGenerator.h +++ b/WickedEngine/wiFFTGenerator.h @@ -15,10 +15,6 @@ typedef struct CSFFT_512x512_Data_t { - static wiGraphicsTypes::ComputeShader* pRadix008A_CS; - static wiGraphicsTypes::ComputeShader* pRadix008A_CS2; - static wiGraphicsTypes::ComputePSO PSO1, PSO2; - // More than one array can be transformed at same time UINT slices; diff --git a/WickedEngine/wiFadeManager.cpp b/WickedEngine/wiFadeManager.cpp index 6151f1bee..376598f51 100644 --- a/WickedEngine/wiFadeManager.cpp +++ b/WickedEngine/wiFadeManager.cpp @@ -3,41 +3,48 @@ void wiFadeManager::Clear() { opacity = 0; - frame = 0; state = FADE_FINISHED; - color = wiColor(0, 0, 0, 1); } -void wiFadeManager::Update() +void wiFadeManager::Update(float dt) { if (!IsActive()) return; - opacity = wiMath::Lerp(0.0f, 1.0f, (float)frame / (float)targetFrames); + if (targetFadeTimeInSeconds <= 0) + { + // skip fade, just launch the job + onFade(); + state = FADE_FINISHED; + } + + float t = timer / targetFadeTimeInSeconds; + timer += wiMath::Clamp(dt, 0, 0.033f); if (state == FADE_IN) { - frame++; - if (frame >= targetFrames) + opacity = wiMath::Lerp(0.0f, 1.0f, t); + if (t >= 1.0f) { state = FADE_MID; opacity = 1.0f; } } - else if (state == FADE_OUT) - { - frame--; - if (frame <= 0) - { - state = FADE_FINISHED; - opacity = 0.0f; - } - } else if (state == FADE_MID) { state = FADE_OUT; opacity = 1.0f; onFade(); + timer = 0; + } + else if (state == FADE_OUT) + { + opacity = wiMath::Lerp(1.0f, 0.0f, t); + if (t >= 1.0f) + { + state = FADE_FINISHED; + opacity = 0.0f; + } } else if (state == FADE_FINISHED) { diff --git a/WickedEngine/wiFadeManager.h b/WickedEngine/wiFadeManager.h index 4c960a8b8..7c8aef720 100644 --- a/WickedEngine/wiFadeManager.h +++ b/WickedEngine/wiFadeManager.h @@ -10,16 +10,17 @@ class wiFadeManager { public: - float opacity; - int frame, targetFrames; + float opacity = 0; + float timer = 0; + float targetFadeTimeInSeconds = 1.0f; enum FADE_STATE { FADE_IN, // no fade -> faded FADE_MID, // completely faded FADE_OUT, // faded -> no fade FADE_FINISHED, - } state; - wiColor color; + } state = FADE_FINISHED; + wiColor color = wiColor(0, 0, 0, 255); std::function onFade; wiFadeManager() @@ -27,15 +28,15 @@ public: Clear(); } void Clear(); - void Start(int targetFrames, const wiColor& color, std::function onFadeFunction) + void Start(float seconds, const wiColor& color, std::function onFadeFunction) { - this->targetFrames = targetFrames; + targetFadeTimeInSeconds = seconds; this->color = color; - frame = 0; + timer = 0; state = FADE_IN; onFade = onFadeFunction; } - void Update(); + void Update(float dt); bool IsFaded() { return state == FADE_MID; diff --git a/WickedEngine/wiFont.cpp b/WickedEngine/wiFont.cpp index 83d29b57c..9ddd83072 100644 --- a/WickedEngine/wiFont.cpp +++ b/WickedEngine/wiFont.cpp @@ -3,7 +3,7 @@ #include "wiResourceManager.h" #include "wiHelper.h" #include "ResourceMapping.h" -#include "ShaderInterop_Renderer.h" +#include "ShaderInterop_Font.h" #include #include @@ -15,17 +15,80 @@ using namespace wiGraphicsTypes; #define WHITESPACE_SIZE 3 -std::string wiFont::FONTPATH = "fonts/"; -GPURingBuffer *wiFont::vertexBuffer = nullptr; -GPUBuffer *wiFont::indexBuffer = nullptr; -VertexLayout *wiFont::vertexLayout = nullptr; -VertexShader *wiFont::vertexShader = nullptr; -PixelShader *wiFont::pixelShader = nullptr; -BlendState *wiFont::blendState = nullptr; -RasterizerState *wiFont::rasterizerState = nullptr; -DepthStencilState *wiFont::depthStencilState = nullptr; -GraphicsPSO *wiFont::PSO = nullptr; -std::vector wiFont::fontStyles; +static std::string FONTPATH = "fonts/"; +static GPURingBuffer vertexBuffer; +static GPUBuffer indexBuffer; +static GPUBuffer constantBuffer; +static BlendState blendState; +static RasterizerState rasterizerState; +static DepthStencilState depthStencilState; + +static VertexLayout *vertexLayout = nullptr; +static VertexShader *vertexShader = nullptr; +static PixelShader *pixelShader = nullptr; +static GraphicsPSO *PSO = nullptr; + +static bool initialized = false; + +struct wiFontStyle +{ + std::string name; + wiGraphicsTypes::Texture2D* texture = nullptr; + + struct LookUp + { + int ascii; + char character; + float left; + float right; + int pixelWidth; + }; + LookUp lookup[128]; + int texWidth, texHeight; + int lineHeight; + + wiFontStyle() {} + wiFontStyle(const std::string& newName) + { + name = newName; + + ZeroMemory(lookup, sizeof(lookup)); + + std::stringstream ss(""), ss1(""); + ss << FONTPATH << name << ".wifont"; + ss1 << FONTPATH << name << ".dds"; + std::ifstream file(ss.str()); + if (file.is_open()) + { + texture = (Texture2D*)wiResourceManager::GetGlobal()->add(ss1.str()); + if (texture == nullptr) + { + return; + } + texWidth = texture->GetDesc().Width; + texHeight = texture->GetDesc().Height; + + string voidStr; + file >> voidStr >> lineHeight; + while (!file.eof()) + { + int code = 0; + file >> code; + lookup[code].ascii = code; + file >> lookup[code].character >> lookup[code].left >> lookup[code].right >> lookup[code].pixelWidth; + } + + + file.close(); + } + else + { + wiHelper::messageBox(name, "Could not load Font Data: " + ss.str()); + } + } +}; +static std::vector fontStyles; + wiFont::wiFont(const std::string& text, wiFontProps props, int style) : props(props), style(style) { @@ -41,71 +104,64 @@ wiFont::~wiFont() void wiFont::Initialize() { - SetUpStates(); - LoadShaders(); - LoadVertexBuffer(); - LoadIndices(); + if (initialized) + { + return; + } // add default font: addFontStyle("default_font"); -} -void wiFont::CleanUp() -{ - for (unsigned int i = 0; iCreateBuffer(&bd, NULL, vertexBuffer); -} -void wiFont::LoadIndices() -{ - uint16_t indices[MAX_TEXT * 6]; - for (uint16_t i = 0; i < MAX_TEXT * 4; i += 4) { - indices[i / 4 * 6 + 0] = i + 0; - indices[i / 4 * 6 + 1] = i + 2; - indices[i / 4 * 6 + 2] = i + 1; - indices[i / 4 * 6 + 3] = i + 1; - indices[i / 4 * 6 + 4] = i + 2; - indices[i / 4 * 6 + 5] = i + 3; + HRESULT hr = device->CreateBuffer(&bd, nullptr, &vertexBuffer); + assert(SUCCEEDED(hr)); } - GPUBufferDesc bd; - ZeroMemory(&bd, sizeof(bd)); - bd.Usage = USAGE_IMMUTABLE; - bd.ByteWidth = sizeof(indices); - bd.BindFlags = BIND_INDEX_BUFFER; - bd.CPUAccessFlags = 0; - SubresourceData InitData; - ZeroMemory(&InitData, sizeof(InitData)); - InitData.pSysMem = indices; - indexBuffer = new GPUBuffer; - wiRenderer::GetDevice()->CreateBuffer(&bd, &InitData, indexBuffer); -} + { + uint16_t indices[MAX_TEXT * 6]; + for (uint16_t i = 0; i < MAX_TEXT * 4; i += 4) + { + indices[i / 4 * 6 + 0] = i + 0; + indices[i / 4 * 6 + 1] = i + 2; + indices[i / 4 * 6 + 2] = i + 1; + indices[i / 4 * 6 + 3] = i + 1; + indices[i / 4 * 6 + 4] = i + 2; + indices[i / 4 * 6 + 5] = i + 3; + } + + GPUBufferDesc bd; + bd.Usage = USAGE_IMMUTABLE; + bd.ByteWidth = sizeof(indices); + bd.BindFlags = BIND_INDEX_BUFFER; + bd.CPUAccessFlags = 0; + SubresourceData InitData; + InitData.pSysMem = indices; + + HRESULT hr = device->CreateBuffer(&bd, &InitData, &indexBuffer); + assert(SUCCEEDED(hr)); + } + + { + GPUBufferDesc bd; + bd.Usage = USAGE_DYNAMIC; + bd.ByteWidth = sizeof(FontCB); + bd.BindFlags = BIND_CONSTANT_BUFFER; + bd.CPUAccessFlags = CPU_ACCESS_WRITE; + + HRESULT hr = device->CreateBuffer(&bd, nullptr, &constantBuffer); + assert(SUCCEEDED(hr)); + } + + -void wiFont::SetUpStates() -{ RasterizerStateDesc rs; rs.FillMode = FILL_SOLID; rs.CullMode = CULL_BACK; @@ -116,21 +172,13 @@ void wiFont::SetUpStates() rs.DepthClipEnable = false; rs.MultisampleEnable = false; rs.AntialiasedLineEnable = false; - rasterizerState = new RasterizerState; - wiRenderer::GetDevice()->CreateRasterizerState(&rs, rasterizerState); + device->CreateRasterizerState(&rs, &rasterizerState); - - - - DepthStencilStateDesc dsd; dsd.DepthEnable = false; dsd.StencilEnable = false; - depthStencilState = new DepthStencilState; - wiRenderer::GetDevice()->CreateDepthStencilState(&dsd, depthStencilState); + device->CreateDepthStencilState(&dsd, &depthStencilState); - - BlendStateDesc bd; bd.RenderTarget[0].BlendEnable = true; bd.RenderTarget[0].SrcBlend = BLEND_SRC_ALPHA; @@ -140,9 +188,20 @@ void wiFont::SetUpStates() bd.RenderTarget[0].DestBlendAlpha = BLEND_ONE; bd.RenderTarget[0].BlendOpAlpha = BLEND_OP_ADD; bd.RenderTarget[0].RenderTargetWriteMask = COLOR_WRITE_ENABLE_ALL; - blendState = new BlendState; - wiRenderer::GetDevice()->CreateBlendState(&bd,blendState); + device->CreateBlendState(&bd, &blendState); + + LoadShaders(); + + initialized = true; } +void wiFont::CleanUp() +{ + fontStyles.clear(); + + SAFE_DELETE(vertexShader); + SAFE_DELETE(pixelShader); +} + void wiFont::LoadShaders() { std::string path = wiRenderer::GetShaderPath(); @@ -165,16 +224,27 @@ void wiFont::LoadShaders() desc.vs = vertexShader; desc.ps = pixelShader; desc.il = vertexLayout; - desc.bs = blendState; - desc.rs = rasterizerState; - desc.dss = depthStencilState; + desc.bs = &blendState; + desc.rs = &rasterizerState; + desc.dss = &depthStencilState; desc.numRTs = 1; desc.RTFormats[0] = wiRenderer::GetDevice()->GetBackBufferFormat(); - SAFE_DELETE(PSO); - PSO = new GraphicsPSO; + RECREATE(PSO); wiRenderer::GetDevice()->CreateGraphicsPSO(&desc, PSO); } +void wiFont::BindPersistentState(GRAPHICSTHREAD threadID) +{ + if (!initialized) + { + return; + } + + GraphicsDevice* device = wiRenderer::GetDevice(); + + device->BindConstantBuffer(VS, &constantBuffer, CB_GETBINDSLOT(FontCB), threadID); + device->BindConstantBuffer(PS, &constantBuffer, CB_GETBINDSLOT(FontCB), threadID); +} void wiFont::ModifyGeo(volatile Vertex* vertexList, const std::wstring& text, wiFontProps props, int style) { @@ -264,7 +334,7 @@ void wiFont::ModifyGeo(volatile Vertex* vertexList, const std::wstring& text, wi void wiFont::Draw(GRAPHICSTHREAD threadID) { - if (text.length() <= 0) + if (!initialized || text.length() <= 0) { return; } @@ -288,16 +358,16 @@ void wiFont::Draw(GRAPHICSTHREAD threadID) device->BindGraphicsPSO(PSO, threadID); UINT vboffset; - volatile Vertex* textBuffer = (volatile Vertex*)device->AllocateFromRingBuffer(vertexBuffer, sizeof(Vertex) * text.length() * 4, vboffset, threadID); + volatile Vertex* textBuffer = (volatile Vertex*)device->AllocateFromRingBuffer(&vertexBuffer, sizeof(Vertex) * text.length() * 4, vboffset, threadID); if (textBuffer == nullptr) { return; } ModifyGeo(textBuffer, text, newProps, style); - device->InvalidateBufferAccess(vertexBuffer, threadID); + device->InvalidateBufferAccess(&vertexBuffer, threadID); GPUBuffer* vbs[] = { - vertexBuffer, + &vertexBuffer, }; const UINT strides[] = { sizeof(Vertex), @@ -308,32 +378,32 @@ void wiFont::Draw(GRAPHICSTHREAD threadID) device->BindVertexBuffers(vbs, 0, ARRAYSIZE(vbs), strides, offsets, threadID); assert(text.length() * 4 < 65536 && "The index buffer currently only supports so many characters!"); - device->BindIndexBuffer(indexBuffer, INDEXFORMAT_16BIT, 0, threadID); + device->BindIndexBuffer(&indexBuffer, INDEXFORMAT_16BIT, 0, threadID); device->BindResource(PS, fontStyles[style].texture, TEXSLOT_ONDEMAND1, threadID); - MiscCB cb; + FontCB cb; if (newProps.shadowColor.a > 0) { // font shadow render: - XMStoreFloat4x4(&cb.g_xTransform, XMMatrixTranspose( + XMStoreFloat4x4(&cb.g_xFont_Transform, XMMatrixTranspose( XMMatrixTranslation((float)newProps.posX + 1, (float)newProps.posY + 1, 0) * device->GetScreenProjection() )); - cb.g_xColor = float4(newProps.shadowColor.R, newProps.shadowColor.G, newProps.shadowColor.B, newProps.shadowColor.A); - device->UpdateBuffer(wiRenderer::GetConstantBuffer(CBTYPE_MISC), &cb, threadID); + cb.g_xFont_Color = float4(newProps.shadowColor.R, newProps.shadowColor.G, newProps.shadowColor.B, newProps.shadowColor.A); + device->UpdateBuffer(&constantBuffer, &cb, threadID); device->DrawIndexed((int)text.length() * 6, 0, 0, threadID); } // font base render: - XMStoreFloat4x4(&cb.g_xTransform, XMMatrixTranspose( + XMStoreFloat4x4(&cb.g_xFont_Transform, XMMatrixTranspose( XMMatrixTranslation((float)newProps.posX, (float)newProps.posY, 0) * device->GetScreenProjection() )); - cb.g_xColor = float4(newProps.color.R, newProps.color.G, newProps.color.B, newProps.color.A); - device->UpdateBuffer(wiRenderer::GetConstantBuffer(CBTYPE_MISC), &cb, threadID); + cb.g_xFont_Color = float4(newProps.color.R, newProps.color.G, newProps.color.B, newProps.color.A); + device->UpdateBuffer(&constantBuffer, &cb, threadID); device->DrawIndexed((int)text.length() * 6, 0, 0, threadID); @@ -407,47 +477,6 @@ string wiFont::GetTextA() return string(text.begin(),text.end()); } -wiFont::wiFontStyle::wiFontStyle(const std::string& newName) -{ - name=newName; - - ZeroMemory(lookup, sizeof(lookup)); - - std::stringstream ss(""),ss1(""); - ss<add(ss1.str()); - if (texture == nullptr) - { - return; - } - texWidth = texture->GetDesc().Width; - texHeight = texture->GetDesc().Height; - - string voidStr; - file >> voidStr >> lineHeight; - while (!file.eof()) - { - int code = 0; - file >> code; - lookup[code].ascii = code; - file >> lookup[code].character >> lookup[code].left >> lookup[code].right >> lookup[code].pixelWidth; - } - - - file.close(); - } - else - { - wiHelper::messageBox(name, "Could not load Font Data: " + ss.str()); - } -} -void wiFont::wiFontStyle::CleanUp(){ - SAFE_DELETE(texture); -} void wiFont::addFontStyle( const std::string& toAdd ){ for (auto& x : fontStyles) { @@ -463,3 +492,7 @@ int wiFont::getFontStyleByName( const std::string& get ){ return 0; } +std::string& wiFont::GetFontPath() +{ + return FONTPATH; +} diff --git a/WickedEngine/wiFont.h b/WickedEngine/wiFont.h index 83c8ba5ce..15c97a542 100644 --- a/WickedEngine/wiFont.h +++ b/WickedEngine/wiFont.h @@ -38,52 +38,16 @@ public: class wiFont { protected: - static std::string FONTPATH; struct Vertex { XMFLOAT2 Pos; XMHALF2 Tex; }; - static wiGraphicsTypes::GPURingBuffer *vertexBuffer; - static wiGraphicsTypes::GPUBuffer *indexBuffer; - - static wiGraphicsTypes::VertexLayout *vertexLayout; - static wiGraphicsTypes::VertexShader *vertexShader; - static wiGraphicsTypes::PixelShader *pixelShader; - static wiGraphicsTypes::BlendState *blendState; - static wiGraphicsTypes::RasterizerState *rasterizerState; - static wiGraphicsTypes::DepthStencilState *depthStencilState; - static wiGraphicsTypes::GraphicsPSO *PSO; - static void SetUpStates(); private: - static void LoadVertexBuffer(); - static void LoadIndices(); - struct wiFontStyle{ - std::string name; - wiGraphicsTypes::Texture2D* texture; - - struct LookUp{ - int ascii; - char character; - float left; - float right; - int pixelWidth; - }; - LookUp lookup[128]; - int texWidth, texHeight; - int lineHeight; - - wiFontStyle(){} - wiFontStyle(const std::string& newName); - void CleanUp(); - }; - static std::vector fontStyles; - - static void ModifyGeo(volatile Vertex* vertexList, const std::wstring& text, wiFontProps props, int style); public: @@ -91,6 +55,7 @@ public: static void CleanUp(); static void LoadShaders(); + static void BindPersistentState(GRAPHICSTHREAD threadID); std::wstring text; wiFontProps props; @@ -115,5 +80,5 @@ public: std::wstring GetText(); std::string GetTextA(); - static std::string& GetFontPath() { return FONTPATH; } + static std::string& GetFontPath(); }; diff --git a/WickedEngine/wiGPUBVH.cpp b/WickedEngine/wiGPUBVH.cpp index ad00f1c2d..47dd712aa 100644 --- a/WickedEngine/wiGPUBVH.cpp +++ b/WickedEngine/wiGPUBVH.cpp @@ -23,10 +23,10 @@ enum CSTYPES_BVH CSTYPE_BVH_PROPAGATEAABB, CSTYPE_BVH_COUNT }; -ComputeShader* computeShaders[CSTYPE_BVH_COUNT] = {}; -ComputePSO* CPSO[CSTYPE_BVH_COUNT] = {}; +static ComputeShader* computeShaders[CSTYPE_BVH_COUNT] = {}; +static ComputePSO* CPSO[CSTYPE_BVH_COUNT] = {}; -GPUBuffer* constantBuffer = nullptr; +static GPUBuffer* constantBuffer = nullptr; wiGPUBVH::wiGPUBVH() { diff --git a/WickedEngine/wiGPUSortLib.cpp b/WickedEngine/wiGPUSortLib.cpp index 33d4b15fb..beb2a757f 100644 --- a/WickedEngine/wiGPUSortLib.cpp +++ b/WickedEngine/wiGPUSortLib.cpp @@ -7,16 +7,16 @@ using namespace wiGraphicsTypes; namespace wiGPUSortLib { - GPUBuffer* indirectBuffer = nullptr; - GPUBuffer* sortCB = nullptr; - ComputeShader* kickoffSortCS = nullptr; - ComputeShader* sortCS = nullptr; - ComputeShader* sortInnerCS = nullptr; - ComputeShader* sortStepCS = nullptr; - ComputePSO CPSO_kickoffSort; - ComputePSO CPSO_sort; - ComputePSO CPSO_sortInner; - ComputePSO CPSO_sortStep; + static GPUBuffer* indirectBuffer = nullptr; + static GPUBuffer* sortCB = nullptr; + static ComputeShader* kickoffSortCS = nullptr; + static ComputeShader* sortCS = nullptr; + static ComputeShader* sortInnerCS = nullptr; + static ComputeShader* sortStepCS = nullptr; + static ComputePSO CPSO_kickoffSort; + static ComputePSO CPSO_sort; + static ComputePSO CPSO_sortInner; + static ComputePSO CPSO_sortStep; void Initialize() { diff --git a/WickedEngine/wiGraphicsDevice.h b/WickedEngine/wiGraphicsDevice.h index 5868b3278..624db3858 100644 --- a/WickedEngine/wiGraphicsDevice.h +++ b/WickedEngine/wiGraphicsDevice.h @@ -13,19 +13,20 @@ namespace wiGraphicsTypes class GraphicsDevice { protected: - uint64_t FRAMECOUNT; - bool VSYNC; - int SCREENWIDTH, SCREENHEIGHT; - bool FULLSCREEN; - bool RESOLUTIONCHANGED; - FORMAT BACKBUFFER_FORMAT; + uint64_t FRAMECOUNT = 0; + bool VSYNC = true; + int SCREENWIDTH = 0; + int SCREENHEIGHT = 0; + bool FULLSCREEN = false; + bool RESOLUTIONCHANGED = false; + FORMAT BACKBUFFER_FORMAT = FORMAT_R10G10B10A2_UNORM; static const UINT BACKBUFFER_COUNT = 2; - bool TESSELLATION, MULTITHREADED_RENDERING, CONSERVATIVE_RASTERIZATION, RASTERIZER_ORDERED_VIEWS, UNORDEREDACCESSTEXTURE_LOAD_EXT; + bool TESSELLATION = false; + bool MULTITHREADED_RENDERING = false; + bool CONSERVATIVE_RASTERIZATION = false; + bool RASTERIZER_ORDERED_VIEWS = false; + bool UNORDEREDACCESSTEXTURE_LOAD_EXT = false; public: - GraphicsDevice() - :FRAMECOUNT(0), VSYNC(true), SCREENWIDTH(0), SCREENHEIGHT(0), FULLSCREEN(false), RESOLUTIONCHANGED(false), BACKBUFFER_FORMAT(FORMAT_R10G10B10A2_UNORM), - TESSELLATION(false), MULTITHREADED_RENDERING(false), CONSERVATIVE_RASTERIZATION(false),RASTERIZER_ORDERED_VIEWS(false), UNORDEREDACCESSTEXTURE_LOAD_EXT(false) - {} virtual HRESULT CreateBuffer(const GPUBufferDesc *pDesc, const SubresourceData* pInitialData, GPUBuffer *ppBuffer) = 0; virtual HRESULT CreateTexture1D(const TextureDesc* pDesc, const SubresourceData *pInitialData, Texture1D **ppTexture1D) = 0; diff --git a/WickedEngine/wiGraphicsDevice_DX11.cpp b/WickedEngine/wiGraphicsDevice_DX11.cpp index 20b313385..53135d160 100644 --- a/WickedEngine/wiGraphicsDevice_DX11.cpp +++ b/WickedEngine/wiGraphicsDevice_DX11.cpp @@ -1380,7 +1380,7 @@ const void* const __nullBlob[1024] = {}; // this is initialized to nullptrs! // Engine functions -GraphicsDevice_DX11::GraphicsDevice_DX11(wiWindowRegistration::window_type window, bool fullscreen, bool debuglayer) : GraphicsDevice() +GraphicsDevice_DX11::GraphicsDevice_DX11(wiWindowRegistration::window_type window, bool fullscreen, bool debuglayer) { FULLSCREEN = fullscreen; diff --git a/WickedEngine/wiGraphicsDevice_DX12.cpp b/WickedEngine/wiGraphicsDevice_DX12.cpp index 8e13ef802..adfcf0808 100644 --- a/WickedEngine/wiGraphicsDevice_DX12.cpp +++ b/WickedEngine/wiGraphicsDevice_DX12.cpp @@ -1526,7 +1526,7 @@ namespace wiGraphicsTypes // Engine functions ID3D12GraphicsCommandList* GraphicsDevice_DX12::GetDirectCommandList(GRAPHICSTHREAD threadID) { return static_cast(GetFrameResources().commandLists[threadID]); } - GraphicsDevice_DX12::GraphicsDevice_DX12(wiWindowRegistration::window_type window, bool fullscreen, bool debuglayer) : GraphicsDevice() + GraphicsDevice_DX12::GraphicsDevice_DX12(wiWindowRegistration::window_type window, bool fullscreen, bool debuglayer) { FULLSCREEN = fullscreen; diff --git a/WickedEngine/wiGraphicsDevice_Vulkan.cpp b/WickedEngine/wiGraphicsDevice_Vulkan.cpp index 5f6171c6d..812e902bf 100644 --- a/WickedEngine/wiGraphicsDevice_Vulkan.cpp +++ b/WickedEngine/wiGraphicsDevice_Vulkan.cpp @@ -1556,7 +1556,7 @@ namespace wiGraphicsTypes // Engine functions VkCommandBuffer GraphicsDevice_Vulkan::GetDirectCommandList(GRAPHICSTHREAD threadID) { return GetFrameResources().commandBuffers[threadID]; } - GraphicsDevice_Vulkan::GraphicsDevice_Vulkan(wiWindowRegistration::window_type window, bool fullscreen, bool debuglayer) : GraphicsDevice() + GraphicsDevice_Vulkan::GraphicsDevice_Vulkan(wiWindowRegistration::window_type window, bool fullscreen, bool debuglayer) { BACKBUFFER_FORMAT = FORMAT::FORMAT_B8G8R8A8_UNORM; diff --git a/WickedEngine/wiHairParticle.cpp b/WickedEngine/wiHairParticle.cpp index 9492c37fa..570c9cd56 100644 --- a/WickedEngine/wiHairParticle.cpp +++ b/WickedEngine/wiHairParticle.cpp @@ -17,218 +17,16 @@ using namespace wiGraphicsTypes; namespace wiSceneSystem { -VertexShader *wiHairParticle::vs = nullptr; -PixelShader *wiHairParticle::ps[]; -PixelShader *wiHairParticle::ps_simplest = nullptr; -ComputeShader *wiHairParticle::cs_simulate = nullptr; -DepthStencilState wiHairParticle::dss_default, wiHairParticle::dss_equal, wiHairParticle::dss_rejectopaque_keeptransparent; -RasterizerState wiHairParticle::rs, wiHairParticle::ncrs, wiHairParticle::wirers; -BlendState wiHairParticle::bs[2]; -GraphicsPSO wiHairParticle::PSO[SHADERTYPE_COUNT][2]; -GraphicsPSO wiHairParticle::PSO_wire; -ComputePSO wiHairParticle::CPSO_simulate; - -void wiHairParticle::CleanUpStatic() -{ - SAFE_DELETE(vs); - for (int i = 0; i < SHADERTYPE_COUNT; ++i) - { - SAFE_DELETE(ps[i]); - } - - SAFE_DELETE(ps_simplest); - SAFE_DELETE(cs_simulate); -} -void wiHairParticle::LoadShaders() -{ - std::string path = wiRenderer::GetShaderPath(); - - vs = static_cast(wiResourceManager::GetShaderManager()->add(path + "hairparticleVS.cso", wiResourceManager::VERTEXSHADER)); - - - for (int i = 0; i < SHADERTYPE_COUNT; ++i) - { - SAFE_INIT(ps[i]); - } - - ps[SHADERTYPE_DEPTHONLY] = static_cast(wiResourceManager::GetShaderManager()->add(path + "hairparticlePS_alphatestonly.cso", wiResourceManager::PIXELSHADER)); - ps[SHADERTYPE_DEFERRED] = static_cast(wiResourceManager::GetShaderManager()->add(path + "hairparticlePS_deferred.cso", wiResourceManager::PIXELSHADER)); - ps[SHADERTYPE_FORWARD] = static_cast(wiResourceManager::GetShaderManager()->add(path + "hairparticlePS_forward.cso", wiResourceManager::PIXELSHADER)); - ps[SHADERTYPE_TILEDFORWARD] = static_cast(wiResourceManager::GetShaderManager()->add(path + "hairparticlePS_tiledforward.cso", wiResourceManager::PIXELSHADER)); - - - GraphicsDevice* device = wiRenderer::GetDevice(); - - for (int i = 0; i < SHADERTYPE_COUNT; ++i) - { - if (ps[i] == nullptr) - { - continue; - } - - for (int j = 0; j < 2; ++j) - { - if ((i == SHADERTYPE_DEPTHONLY || i == SHADERTYPE_DEFERRED) && j == 1) - { - continue; - } - - GraphicsPSODesc desc; - desc.vs = vs; - desc.ps = ps[i]; - desc.bs = &bs[j]; - desc.rs = &ncrs; - desc.dss = &dss_default; - - desc.DSFormat = wiRenderer::DSFormat_full; - - switch (i) - { - case SHADERTYPE_TEXTURE: - desc.numRTs = 1; - desc.RTFormats[0] = wiRenderer::RTFormat_hdr; - break; - case SHADERTYPE_FORWARD: - case SHADERTYPE_TILEDFORWARD: - desc.numRTs = 2; - desc.RTFormats[0] = wiRenderer::RTFormat_hdr; - desc.RTFormats[1] = wiRenderer::RTFormat_gbuffer_1; - break; - case SHADERTYPE_DEFERRED: - desc.numRTs = 4; - desc.RTFormats[0] = wiRenderer::RTFormat_gbuffer_0; - desc.RTFormats[1] = wiRenderer::RTFormat_gbuffer_1; - desc.RTFormats[2] = wiRenderer::RTFormat_gbuffer_2; - desc.RTFormats[3] = wiRenderer::RTFormat_gbuffer_3; - default: - break; - } - - if (i == SHADERTYPE_TILEDFORWARD) - { - desc.dss = &dss_equal; // opaque - } - - if(j == 1) - { - desc.dss = &dss_rejectopaque_keeptransparent; // transparent - desc.numRTs = 1; - } - - device->CreateGraphicsPSO(&desc, &PSO[i][j]); - } - } - - SAFE_INIT(ps_simplest); - ps_simplest = static_cast(wiResourceManager::GetShaderManager()->add(path + "hairparticlePS_simplest.cso", wiResourceManager::PIXELSHADER)); - - { - GraphicsPSODesc desc; - desc.vs = vs; - desc.ps = ps_simplest; - desc.bs = &bs[0]; - desc.rs = &wirers; - desc.dss = &dss_default; - desc.numRTs = 1; - desc.RTFormats[0] = wiRenderer::RTFormat_hdr; - desc.DSFormat = wiRenderer::DSFormat_full; - device->CreateGraphicsPSO(&desc, &PSO_wire); - } - - SAFE_INIT(cs_simulate); - cs_simulate = static_cast(wiResourceManager::GetShaderManager()->add(path + "hairparticle_simulateCS.cso", wiResourceManager::COMPUTESHADER)); - - { - ComputePSODesc desc; - desc.cs = cs_simulate; - device->CreateComputePSO(&desc, &CPSO_simulate); - } -} -void wiHairParticle::SetUpStatic() -{ - RasterizerStateDesc rsd; - rsd.FillMode=FILL_SOLID; - rsd.CullMode=CULL_BACK; - rsd.FrontCounterClockwise=true; - rsd.DepthBias=0; - rsd.DepthBiasClamp=0; - rsd.SlopeScaledDepthBias=0; - rsd.DepthClipEnable=true; - rsd.MultisampleEnable=false; - rsd.AntialiasedLineEnable=false; - wiRenderer::GetDevice()->CreateRasterizerState(&rsd, &rs); - - rsd.FillMode=FILL_SOLID; - rsd.CullMode=CULL_NONE; - rsd.FrontCounterClockwise=true; - rsd.DepthBias=0; - rsd.DepthBiasClamp=0; - rsd.SlopeScaledDepthBias=0; - rsd.DepthClipEnable=true; - rsd.MultisampleEnable=false; - rsd.AntialiasedLineEnable=false; - wiRenderer::GetDevice()->CreateRasterizerState(&rsd, &ncrs); - - rsd.FillMode = FILL_WIREFRAME; - rsd.CullMode = CULL_NONE; - rsd.FrontCounterClockwise = true; - rsd.DepthBias = 0; - rsd.DepthBiasClamp = 0; - rsd.SlopeScaledDepthBias = 0; - rsd.DepthClipEnable = true; - rsd.MultisampleEnable = false; - rsd.AntialiasedLineEnable = false; - wiRenderer::GetDevice()->CreateRasterizerState(&rsd, &wirers); - - - DepthStencilStateDesc dsd; - dsd.DepthEnable = true; - dsd.DepthWriteMask = DEPTH_WRITE_MASK_ALL; - dsd.DepthFunc = COMPARISON_GREATER; - - dsd.StencilEnable = true; - dsd.StencilReadMask = 0xFF; - dsd.StencilWriteMask = 0xFF; - dsd.FrontFace.StencilFunc = COMPARISON_ALWAYS; - dsd.FrontFace.StencilPassOp = STENCIL_OP_REPLACE; - dsd.FrontFace.StencilFailOp = STENCIL_OP_KEEP; - dsd.FrontFace.StencilDepthFailOp = STENCIL_OP_KEEP; - dsd.BackFace.StencilFunc = COMPARISON_ALWAYS; - dsd.BackFace.StencilPassOp = STENCIL_OP_REPLACE; - dsd.BackFace.StencilFailOp = STENCIL_OP_KEEP; - dsd.BackFace.StencilDepthFailOp = STENCIL_OP_KEEP; - wiRenderer::GetDevice()->CreateDepthStencilState(&dsd, &dss_default); - - dsd.DepthWriteMask = DEPTH_WRITE_MASK_ZERO; - dsd.DepthFunc = COMPARISON_EQUAL; - wiRenderer::GetDevice()->CreateDepthStencilState(&dsd, &dss_equal); - dsd.DepthFunc = COMPARISON_GREATER; - wiRenderer::GetDevice()->CreateDepthStencilState(&dsd, &dss_rejectopaque_keeptransparent); - - - BlendStateDesc bld; - bld.RenderTarget[0].BlendEnable=false; - bld.AlphaToCoverageEnable=false; // maybe for msaa - wiRenderer::GetDevice()->CreateBlendState(&bld, &bs[0]); - - bld.RenderTarget[0].SrcBlend = BLEND_SRC_ALPHA; - bld.RenderTarget[0].DestBlend = BLEND_INV_SRC_ALPHA; - bld.RenderTarget[0].BlendOp = BLEND_OP_ADD; - bld.RenderTarget[0].SrcBlendAlpha = BLEND_ONE; - bld.RenderTarget[0].DestBlendAlpha = BLEND_ONE; - bld.RenderTarget[0].BlendOpAlpha = BLEND_OP_ADD; - bld.RenderTarget[0].BlendEnable = true; - bld.RenderTarget[0].RenderTargetWriteMask = COLOR_WRITE_ENABLE_ALL; - bld.AlphaToCoverageEnable = false; - bld.IndependentBlendEnable = false; - wiRenderer::GetDevice()->CreateBlendState(&bld, &bs[1]); - - - - - - LoadShaders(); -} +static VertexShader *vs = nullptr; +static PixelShader *ps[SHADERTYPE_COUNT] = {}; +static PixelShader *ps_simplest = nullptr; +static ComputeShader *cs_simulate = nullptr; +static DepthStencilState dss_default, dss_equal, dss_rejectopaque_keeptransparent; +static RasterizerState rs, ncrs, wirers; +static BlendState bs[2]; +static GraphicsPSO PSO[SHADERTYPE_COUNT][2]; +static GraphicsPSO PSO_wire; +static ComputePSO CPSO_simulate; void wiHairParticle::UpdateRenderData(const MeshComponent& mesh, const MaterialComponent& material, GRAPHICSTHREAD threadID) { @@ -384,4 +182,207 @@ void wiHairParticle::Serialize(wiArchive& archive, uint32_t seed) } } + +void wiHairParticle::LoadShaders() +{ + std::string path = wiRenderer::GetShaderPath(); + + vs = static_cast(wiResourceManager::GetShaderManager()->add(path + "hairparticleVS.cso", wiResourceManager::VERTEXSHADER)); + + + for (int i = 0; i < SHADERTYPE_COUNT; ++i) + { + SAFE_INIT(ps[i]); + } + + ps[SHADERTYPE_DEPTHONLY] = static_cast(wiResourceManager::GetShaderManager()->add(path + "hairparticlePS_alphatestonly.cso", wiResourceManager::PIXELSHADER)); + ps[SHADERTYPE_DEFERRED] = static_cast(wiResourceManager::GetShaderManager()->add(path + "hairparticlePS_deferred.cso", wiResourceManager::PIXELSHADER)); + ps[SHADERTYPE_FORWARD] = static_cast(wiResourceManager::GetShaderManager()->add(path + "hairparticlePS_forward.cso", wiResourceManager::PIXELSHADER)); + ps[SHADERTYPE_TILEDFORWARD] = static_cast(wiResourceManager::GetShaderManager()->add(path + "hairparticlePS_tiledforward.cso", wiResourceManager::PIXELSHADER)); + + + GraphicsDevice* device = wiRenderer::GetDevice(); + + for (int i = 0; i < SHADERTYPE_COUNT; ++i) + { + if (ps[i] == nullptr) + { + continue; + } + + for (int j = 0; j < 2; ++j) + { + if ((i == SHADERTYPE_DEPTHONLY || i == SHADERTYPE_DEFERRED) && j == 1) + { + continue; + } + + GraphicsPSODesc desc; + desc.vs = vs; + desc.ps = ps[i]; + desc.bs = &bs[j]; + desc.rs = &ncrs; + desc.dss = &dss_default; + + desc.DSFormat = wiRenderer::DSFormat_full; + + switch (i) + { + case SHADERTYPE_TEXTURE: + desc.numRTs = 1; + desc.RTFormats[0] = wiRenderer::RTFormat_hdr; + break; + case SHADERTYPE_FORWARD: + case SHADERTYPE_TILEDFORWARD: + desc.numRTs = 2; + desc.RTFormats[0] = wiRenderer::RTFormat_hdr; + desc.RTFormats[1] = wiRenderer::RTFormat_gbuffer_1; + break; + case SHADERTYPE_DEFERRED: + desc.numRTs = 4; + desc.RTFormats[0] = wiRenderer::RTFormat_gbuffer_0; + desc.RTFormats[1] = wiRenderer::RTFormat_gbuffer_1; + desc.RTFormats[2] = wiRenderer::RTFormat_gbuffer_2; + desc.RTFormats[3] = wiRenderer::RTFormat_gbuffer_3; + default: + break; + } + + if (i == SHADERTYPE_TILEDFORWARD) + { + desc.dss = &dss_equal; // opaque + } + + if (j == 1) + { + desc.dss = &dss_rejectopaque_keeptransparent; // transparent + desc.numRTs = 1; + } + + device->CreateGraphicsPSO(&desc, &PSO[i][j]); + } + } + + SAFE_INIT(ps_simplest); + ps_simplest = static_cast(wiResourceManager::GetShaderManager()->add(path + "hairparticlePS_simplest.cso", wiResourceManager::PIXELSHADER)); + + { + GraphicsPSODesc desc; + desc.vs = vs; + desc.ps = ps_simplest; + desc.bs = &bs[0]; + desc.rs = &wirers; + desc.dss = &dss_default; + desc.numRTs = 1; + desc.RTFormats[0] = wiRenderer::RTFormat_hdr; + desc.DSFormat = wiRenderer::DSFormat_full; + device->CreateGraphicsPSO(&desc, &PSO_wire); + } + + SAFE_INIT(cs_simulate); + cs_simulate = static_cast(wiResourceManager::GetShaderManager()->add(path + "hairparticle_simulateCS.cso", wiResourceManager::COMPUTESHADER)); + + { + ComputePSODesc desc; + desc.cs = cs_simulate; + device->CreateComputePSO(&desc, &CPSO_simulate); + } +} +void wiHairParticle::CleanUp() +{ + SAFE_DELETE(vs); + for (int i = 0; i < SHADERTYPE_COUNT; ++i) + { + SAFE_DELETE(ps[i]); + } + + SAFE_DELETE(ps_simplest); + SAFE_DELETE(cs_simulate); +} +void wiHairParticle::Initialize() +{ + RasterizerStateDesc rsd; + rsd.FillMode = FILL_SOLID; + rsd.CullMode = CULL_BACK; + rsd.FrontCounterClockwise = true; + rsd.DepthBias = 0; + rsd.DepthBiasClamp = 0; + rsd.SlopeScaledDepthBias = 0; + rsd.DepthClipEnable = true; + rsd.MultisampleEnable = false; + rsd.AntialiasedLineEnable = false; + wiRenderer::GetDevice()->CreateRasterizerState(&rsd, &rs); + + rsd.FillMode = FILL_SOLID; + rsd.CullMode = CULL_NONE; + rsd.FrontCounterClockwise = true; + rsd.DepthBias = 0; + rsd.DepthBiasClamp = 0; + rsd.SlopeScaledDepthBias = 0; + rsd.DepthClipEnable = true; + rsd.MultisampleEnable = false; + rsd.AntialiasedLineEnable = false; + wiRenderer::GetDevice()->CreateRasterizerState(&rsd, &ncrs); + + rsd.FillMode = FILL_WIREFRAME; + rsd.CullMode = CULL_NONE; + rsd.FrontCounterClockwise = true; + rsd.DepthBias = 0; + rsd.DepthBiasClamp = 0; + rsd.SlopeScaledDepthBias = 0; + rsd.DepthClipEnable = true; + rsd.MultisampleEnable = false; + rsd.AntialiasedLineEnable = false; + wiRenderer::GetDevice()->CreateRasterizerState(&rsd, &wirers); + + + DepthStencilStateDesc dsd; + dsd.DepthEnable = true; + dsd.DepthWriteMask = DEPTH_WRITE_MASK_ALL; + dsd.DepthFunc = COMPARISON_GREATER; + + dsd.StencilEnable = true; + dsd.StencilReadMask = 0xFF; + dsd.StencilWriteMask = 0xFF; + dsd.FrontFace.StencilFunc = COMPARISON_ALWAYS; + dsd.FrontFace.StencilPassOp = STENCIL_OP_REPLACE; + dsd.FrontFace.StencilFailOp = STENCIL_OP_KEEP; + dsd.FrontFace.StencilDepthFailOp = STENCIL_OP_KEEP; + dsd.BackFace.StencilFunc = COMPARISON_ALWAYS; + dsd.BackFace.StencilPassOp = STENCIL_OP_REPLACE; + dsd.BackFace.StencilFailOp = STENCIL_OP_KEEP; + dsd.BackFace.StencilDepthFailOp = STENCIL_OP_KEEP; + wiRenderer::GetDevice()->CreateDepthStencilState(&dsd, &dss_default); + + dsd.DepthWriteMask = DEPTH_WRITE_MASK_ZERO; + dsd.DepthFunc = COMPARISON_EQUAL; + wiRenderer::GetDevice()->CreateDepthStencilState(&dsd, &dss_equal); + dsd.DepthFunc = COMPARISON_GREATER; + wiRenderer::GetDevice()->CreateDepthStencilState(&dsd, &dss_rejectopaque_keeptransparent); + + + BlendStateDesc bld; + bld.RenderTarget[0].BlendEnable = false; + bld.AlphaToCoverageEnable = false; // maybe for msaa + wiRenderer::GetDevice()->CreateBlendState(&bld, &bs[0]); + + bld.RenderTarget[0].SrcBlend = BLEND_SRC_ALPHA; + bld.RenderTarget[0].DestBlend = BLEND_INV_SRC_ALPHA; + bld.RenderTarget[0].BlendOp = BLEND_OP_ADD; + bld.RenderTarget[0].SrcBlendAlpha = BLEND_ONE; + bld.RenderTarget[0].DestBlendAlpha = BLEND_ONE; + bld.RenderTarget[0].BlendOpAlpha = BLEND_OP_ADD; + bld.RenderTarget[0].BlendEnable = true; + bld.RenderTarget[0].RenderTargetWriteMask = COLOR_WRITE_ENABLE_ALL; + bld.AlphaToCoverageEnable = false; + bld.IndependentBlendEnable = false; + wiRenderer::GetDevice()->CreateBlendState(&bld, &bs[1]); + + + + + + LoadShaders(); +} + } diff --git a/WickedEngine/wiHairParticle.h b/WickedEngine/wiHairParticle.h index 0a314d9df..7c2d071c9 100644 --- a/WickedEngine/wiHairParticle.h +++ b/WickedEngine/wiHairParticle.h @@ -17,26 +17,11 @@ private: std::unique_ptr cb; std::unique_ptr particleBuffer; std::unique_ptr simulationBuffer; - - static wiGraphicsTypes::VertexShader *vs; - static wiGraphicsTypes::PixelShader *ps[SHADERTYPE_COUNT]; - static wiGraphicsTypes::PixelShader *ps_simplest; - static wiGraphicsTypes::ComputeShader *cs_simulate; - static wiGraphicsTypes::DepthStencilState dss_default, dss_equal, dss_rejectopaque_keeptransparent; - static wiGraphicsTypes::RasterizerState rs, ncrs, wirers; - static wiGraphicsTypes::BlendState bs[2]; // opaque, transparent - static wiGraphicsTypes::GraphicsPSO PSO[SHADERTYPE_COUNT][2]; // shadertype * transparency - static wiGraphicsTypes::GraphicsPSO PSO_wire; - static wiGraphicsTypes::ComputePSO CPSO_simulate; public: - static void LoadShaders(); void UpdateRenderData(const MeshComponent& mesh, const MaterialComponent& material, GRAPHICSTHREAD threadID); void Draw(const CameraComponent& camera, const MaterialComponent& material, SHADERTYPE shaderType, bool transparent, GRAPHICSTHREAD threadID) const; - static void CleanUpStatic(); - static void SetUpStatic(); - enum FLAGS { EMPTY = 0, @@ -58,6 +43,10 @@ public: AABB aabb; void Serialize(wiArchive& archive, uint32_t seed = 0); + + static void LoadShaders(); + static void Initialize(); + static void CleanUp(); }; } diff --git a/WickedEngine/wiImage.cpp b/WickedEngine/wiImage.cpp index 6ac532c58..e9702d6d2 100644 --- a/WickedEngine/wiImage.cpp +++ b/WickedEngine/wiImage.cpp @@ -13,675 +13,709 @@ using namespace std; using namespace wiGraphicsTypes; -#pragma region STATICS -GPUBuffer wiImage::constantBuffer, wiImage::processCb; - -VertexShader* wiImage::vertexShader = nullptr; -VertexShader* wiImage::screenVS = nullptr; - -PixelShader* wiImage::imagePS[IMAGE_SHADER_COUNT]; -PixelShader* wiImage::postprocessPS[POSTPROCESS_COUNT]; -PixelShader* wiImage::deferredPS = nullptr; - -BlendState wiImage::blendStates[BLENDMODE_COUNT]; -RasterizerState wiImage::rasterizerState; -DepthStencilState wiImage::depthStencilStates[STENCILMODE_COUNT]; -BlendState wiImage::blendStateDisableColor; -DepthStencilState wiImage::depthStencilStateDepthWrite; - -GraphicsPSO wiImage::imagePSO[IMAGE_SHADER_COUNT][BLENDMODE_COUNT][STENCILMODE_COUNT][IMAGE_HDR_COUNT]; -GraphicsPSO wiImage::postprocessPSO[POSTPROCESS_COUNT]; -GraphicsPSO wiImage::deferredPSO; - -#pragma endregion - -wiImage::wiImage() -{ -} - -void wiImage::LoadBuffers() +namespace wiImage { - GPUBufferDesc bd; - ZeroMemory(&bd, sizeof(bd)); - bd.Usage = USAGE_DYNAMIC; - bd.ByteWidth = sizeof(ImageCB); - bd.BindFlags = BIND_CONSTANT_BUFFER; - bd.CPUAccessFlags = CPU_ACCESS_WRITE; - wiRenderer::GetDevice()->CreateBuffer(&bd, nullptr, &constantBuffer); + enum IMAGE_SHADER + { + IMAGE_SHADER_STANDARD, + IMAGE_SHADER_SEPARATENORMALMAP, + IMAGE_SHADER_DISTORTION, + IMAGE_SHADER_DISTORTION_MASKED, + IMAGE_SHADER_MASKED, + IMAGE_SHADER_FULLSCREEN, + IMAGE_SHADER_COUNT + }; + enum POSTPROCESS + { + POSTPROCESS_BLUR_H, + POSTPROCESS_BLUR_V, + POSTPROCESS_LIGHTSHAFT, + POSTPROCESS_OUTLINE, + POSTPROCESS_DEPTHOFFIELD, + POSTPROCESS_MOTIONBLUR, + POSTPROCESS_BLOOMSEPARATE, + POSTPROCESS_FXAA, + POSTPROCESS_SSAO, + POSTPROCESS_SSSS, + POSTPROCESS_SSR, + POSTPROCESS_COLORGRADE, + POSTPROCESS_STEREOGRAM, + POSTPROCESS_TONEMAP, + POSTPROCESS_REPROJECTDEPTHBUFFER, + POSTPROCESS_DOWNSAMPLEDEPTHBUFFER, + POSTPROCESS_TEMPORALAA, + POSTPROCESS_SHARPEN, + POSTPROCESS_LINEARDEPTH, + POSTPROCESS_COUNT + }; + enum IMAGE_HDR + { + IMAGE_HDR_DISABLED, + IMAGE_HDR_ENABLED, + IMAGE_HDR_COUNT + }; - ZeroMemory(&bd, sizeof(bd)); - bd.Usage = USAGE_DYNAMIC; - bd.ByteWidth = sizeof(PostProcessCB); - bd.BindFlags = BIND_CONSTANT_BUFFER; - bd.CPUAccessFlags = CPU_ACCESS_WRITE; - wiRenderer::GetDevice()->CreateBuffer(&bd, nullptr, &processCb); - - BindPersistentState(GRAPHICSTHREAD_IMMEDIATE); -} - -void wiImage::LoadShaders() -{ - std::string path = wiRenderer::GetShaderPath(); - - vertexShader = static_cast(wiResourceManager::GetShaderManager()->add(path + "imageVS.cso", wiResourceManager::VERTEXSHADER)); - screenVS = static_cast(wiResourceManager::GetShaderManager()->add(path + "screenVS.cso", wiResourceManager::VERTEXSHADER)); - - imagePS[IMAGE_SHADER_STANDARD] = static_cast(wiResourceManager::GetShaderManager()->add(path + "imagePS.cso", wiResourceManager::PIXELSHADER)); - imagePS[IMAGE_SHADER_SEPARATENORMALMAP] = static_cast(wiResourceManager::GetShaderManager()->add(path + "imagePS_separatenormalmap.cso", wiResourceManager::PIXELSHADER)); - imagePS[IMAGE_SHADER_DISTORTION] = static_cast(wiResourceManager::GetShaderManager()->add(path + "imagePS_distortion.cso", wiResourceManager::PIXELSHADER)); - imagePS[IMAGE_SHADER_DISTORTION_MASKED] = static_cast(wiResourceManager::GetShaderManager()->add(path + "imagePS_distortion_masked.cso", wiResourceManager::PIXELSHADER)); - imagePS[IMAGE_SHADER_MASKED] = static_cast(wiResourceManager::GetShaderManager()->add(path + "imagePS_masked.cso", wiResourceManager::PIXELSHADER)); - imagePS[IMAGE_SHADER_FULLSCREEN] = static_cast(wiResourceManager::GetShaderManager()->add(path + "screenPS.cso", wiResourceManager::PIXELSHADER)); - - postprocessPS[POSTPROCESS_BLUR_H] = static_cast(wiResourceManager::GetShaderManager()->add(path + "horizontalBlurPS.cso", wiResourceManager::PIXELSHADER)); - postprocessPS[POSTPROCESS_BLUR_V] = static_cast(wiResourceManager::GetShaderManager()->add(path + "verticalBlurPS.cso", wiResourceManager::PIXELSHADER)); - postprocessPS[POSTPROCESS_LIGHTSHAFT] = static_cast(wiResourceManager::GetShaderManager()->add(path + "lightShaftPS.cso", wiResourceManager::PIXELSHADER)); - postprocessPS[POSTPROCESS_OUTLINE] = static_cast(wiResourceManager::GetShaderManager()->add(path + "outlinePS.cso", wiResourceManager::PIXELSHADER)); - postprocessPS[POSTPROCESS_DEPTHOFFIELD] = static_cast(wiResourceManager::GetShaderManager()->add(path + "depthofFieldPS.cso", wiResourceManager::PIXELSHADER)); - postprocessPS[POSTPROCESS_MOTIONBLUR] = static_cast(wiResourceManager::GetShaderManager()->add(path + "motionBlurPS.cso", wiResourceManager::PIXELSHADER)); - postprocessPS[POSTPROCESS_BLOOMSEPARATE] = static_cast(wiResourceManager::GetShaderManager()->add(path + "bloomSeparatePS.cso", wiResourceManager::PIXELSHADER)); - postprocessPS[POSTPROCESS_FXAA] = static_cast(wiResourceManager::GetShaderManager()->add(path + "fxaa.cso", wiResourceManager::PIXELSHADER)); - postprocessPS[POSTPROCESS_SSAO] = static_cast(wiResourceManager::GetShaderManager()->add(path + "ssao.cso", wiResourceManager::PIXELSHADER)); - postprocessPS[POSTPROCESS_SSSS] = static_cast(wiResourceManager::GetShaderManager()->add(path + "ssss.cso", wiResourceManager::PIXELSHADER)); - postprocessPS[POSTPROCESS_LINEARDEPTH] = static_cast(wiResourceManager::GetShaderManager()->add(path + "linDepthPS.cso", wiResourceManager::PIXELSHADER)); - postprocessPS[POSTPROCESS_COLORGRADE] = static_cast(wiResourceManager::GetShaderManager()->add(path + "colorGradePS.cso", wiResourceManager::PIXELSHADER)); - postprocessPS[POSTPROCESS_SSR] = static_cast(wiResourceManager::GetShaderManager()->add(path + "ssr.cso", wiResourceManager::PIXELSHADER)); - postprocessPS[POSTPROCESS_STEREOGRAM] = static_cast(wiResourceManager::GetShaderManager()->add(path + "stereogramPS.cso", wiResourceManager::PIXELSHADER)); - postprocessPS[POSTPROCESS_TONEMAP] = static_cast(wiResourceManager::GetShaderManager()->add(path + "toneMapPS.cso", wiResourceManager::PIXELSHADER)); - postprocessPS[POSTPROCESS_REPROJECTDEPTHBUFFER] = static_cast(wiResourceManager::GetShaderManager()->add(path + "reprojectDepthBufferPS.cso", wiResourceManager::PIXELSHADER)); - postprocessPS[POSTPROCESS_DOWNSAMPLEDEPTHBUFFER] = static_cast(wiResourceManager::GetShaderManager()->add(path + "downsampleDepthBuffer4xPS.cso", wiResourceManager::PIXELSHADER)); - postprocessPS[POSTPROCESS_TEMPORALAA] = static_cast(wiResourceManager::GetShaderManager()->add(path + "temporalAAResolvePS.cso", wiResourceManager::PIXELSHADER)); - postprocessPS[POSTPROCESS_SHARPEN] = static_cast(wiResourceManager::GetShaderManager()->add(path + "sharpenPS.cso", wiResourceManager::PIXELSHADER)); - - deferredPS = static_cast(wiResourceManager::GetShaderManager()->add(path + "deferredPS.cso", wiResourceManager::PIXELSHADER)); + static GPUBuffer constantBuffer; + static GPUBuffer processCb; + static VertexShader* vertexShader = nullptr; + static VertexShader* screenVS = nullptr; + static PixelShader* imagePS[IMAGE_SHADER_COUNT]; + static PixelShader* postprocessPS[POSTPROCESS_COUNT]; + static PixelShader* deferredPS = nullptr; + static BlendState blendStates[BLENDMODE_COUNT]; + static RasterizerState rasterizerState; + static DepthStencilState depthStencilStates[STENCILMODE_COUNT]; + static BlendState blendStateDisableColor; + static DepthStencilState depthStencilStateDepthWrite; + static GraphicsPSO imagePSO[IMAGE_SHADER_COUNT][BLENDMODE_COUNT][STENCILMODE_COUNT][IMAGE_HDR_COUNT]; + static GraphicsPSO postprocessPSO[POSTPROCESS_COUNT]; + static GraphicsPSO deferredPSO; - GraphicsDevice* device = wiRenderer::GetDevice(); + void Draw(Texture2D* texture, const wiImageEffects& effects, GRAPHICSTHREAD threadID) + { + GraphicsDevice* device = wiRenderer::GetDevice(); + device->EventBegin("Image", threadID); - vector thread_pool(0); + bool fullScreenEffect = false; - thread_pool.push_back(thread([&] { - for (int i = 0; i < IMAGE_SHADER_COUNT; ++i) + device->BindResource(PS, texture, TEXSLOT_ONDEMAND0, threadID); + + device->BindStencilRef(effects.stencilRef, threadID); + + if (effects.quality == QUALITY_NEAREST) { - GraphicsPSODesc desc; - desc.vs = vertexShader; - if (i == IMAGE_SHADER_FULLSCREEN) - { - desc.vs = screenVS; - } - desc.ps = imagePS[i]; - desc.rs = &rasterizerState; - desc.pt = TRIANGLESTRIP; + if (effects.sampleFlag == SAMPLEMODE_MIRROR) + device->BindSampler(PS, wiRenderer::GetSampler(SSLOT_POINT_MIRROR), SSLOT_ONDEMAND0, threadID); + else if (effects.sampleFlag == SAMPLEMODE_WRAP) + device->BindSampler(PS, wiRenderer::GetSampler(SSLOT_POINT_WRAP), SSLOT_ONDEMAND0, threadID); + else if (effects.sampleFlag == SAMPLEMODE_CLAMP) + device->BindSampler(PS, wiRenderer::GetSampler(SSLOT_POINT_CLAMP), SSLOT_ONDEMAND0, threadID); + } + else if (effects.quality == QUALITY_BILINEAR) + { + if (effects.sampleFlag == SAMPLEMODE_MIRROR) + device->BindSampler(PS, wiRenderer::GetSampler(SSLOT_LINEAR_MIRROR), SSLOT_ONDEMAND0, threadID); + else if (effects.sampleFlag == SAMPLEMODE_WRAP) + device->BindSampler(PS, wiRenderer::GetSampler(SSLOT_LINEAR_WRAP), SSLOT_ONDEMAND0, threadID); + else if (effects.sampleFlag == SAMPLEMODE_CLAMP) + device->BindSampler(PS, wiRenderer::GetSampler(SSLOT_LINEAR_CLAMP), SSLOT_ONDEMAND0, threadID); + } + else if (effects.quality == QUALITY_ANISOTROPIC) + { + if (effects.sampleFlag == SAMPLEMODE_MIRROR) + device->BindSampler(PS, wiRenderer::GetSampler(SSLOT_ANISO_MIRROR), SSLOT_ONDEMAND0, threadID); + else if (effects.sampleFlag == SAMPLEMODE_WRAP) + device->BindSampler(PS, wiRenderer::GetSampler(SSLOT_ANISO_WRAP), SSLOT_ONDEMAND0, threadID); + else if (effects.sampleFlag == SAMPLEMODE_CLAMP) + device->BindSampler(PS, wiRenderer::GetSampler(SSLOT_ANISO_CLAMP), SSLOT_ONDEMAND0, threadID); + } - for (int j = 0; j < BLENDMODE_COUNT; ++j) - { - desc.bs = &blendStates[j]; - for (int k = 0; k < STENCILMODE_COUNT; ++k) + if (effects.presentFullScreen) + { + device->BindGraphicsPSO(&imagePSO[IMAGE_SHADER_FULLSCREEN][effects.blendFlag][effects.stencilComp][effects.hdr], threadID); + device->Draw(3, 0, threadID); + device->EventEnd(threadID); + return; + } + + if (!effects.blur) // NORMAL IMAGE + { + ImageCB cb; + + if (!effects.process.active && !effects.bloom.separate && !effects.sunPos.x && !effects.sunPos.y) { + if (effects.typeFlag == SCREEN) { - desc.dss = &depthStencilStates[k]; - - if (k == STENCILMODE_DISABLED) + XMStoreFloat4x4(&cb.xTransform, XMMatrixTranspose( + XMMatrixScaling(effects.scale.x*effects.siz.x, effects.scale.y*effects.siz.y, 1) + * XMMatrixRotationZ(effects.rotation) + * XMMatrixTranslation(effects.pos.x, effects.pos.y, 0) + * device->GetScreenProjection() + )); + } + else if (effects.typeFlag == WORLD) + { + XMMATRIX faceRot = XMMatrixIdentity(); + if (effects.lookAt.w) { - desc.DSFormat = FORMAT_UNKNOWN; + XMVECTOR vvv = (effects.lookAt.x == 1 && !effects.lookAt.y && !effects.lookAt.z) ? XMVectorSet(0, 1, 0, 0) : XMVectorSet(1, 0, 0, 0); + faceRot = + XMMatrixLookAtLH(XMVectorSet(0, 0, 0, 0) + , XMLoadFloat4(&effects.lookAt) + , XMVector3Cross( + vvv, XMLoadFloat4(&effects.lookAt) + ) + ); } else { - desc.DSFormat = wiRenderer::DSFormat_full; + faceRot = XMLoadFloat3x3(&wiRenderer::GetCamera().rotationMatrix); } - desc.numRTs = 1; + XMMATRIX view = wiRenderer::GetCamera().GetView(); + XMMATRIX projection = wiRenderer::GetCamera().GetProjection(); + // Remove possible jittering from temporal camera: + projection.r[2] = XMVectorSetX(projection.r[2], 0); + projection.r[2] = XMVectorSetY(projection.r[2], 0); - desc.RTFormats[0] = wiRenderer::GetDevice()->GetBackBufferFormat(); - device->CreateGraphicsPSO(&desc, &imagePSO[i][j][k][0]); + XMStoreFloat4x4(&cb.xTransform, XMMatrixTranspose( + XMMatrixScaling(effects.scale.x*effects.siz.x, -1 * effects.scale.y*effects.siz.y, 1) + *XMMatrixRotationZ(effects.rotation) + *faceRot + *XMMatrixTranslation(effects.pos.x, effects.pos.y, effects.pos.z) + *view * projection + )); + } - desc.RTFormats[0] = wiRenderer::RTFormat_hdr; - device->CreateGraphicsPSO(&desc, &imagePSO[i][j][k][1]); + // todo: effects.drawRec -> texmuladd! + + cb.xTexMulAdd = XMFLOAT4(1, 1, effects.texOffset.x, effects.texOffset.y); + cb.xColor = effects.col; + cb.xColor.x *= 1 - effects.fade; + cb.xColor.y *= 1 - effects.fade; + cb.xColor.z *= 1 - effects.fade; + cb.xColor.w *= effects.opacity; + cb.xPivot = effects.pivot; + cb.xMirror = effects.mirror; + cb.xPivot = effects.pivot; + cb.xMipLevel = effects.mipLevel; + + device->UpdateBuffer(&constantBuffer, &cb, threadID); + + // Determine relevant image rendering pixel shader: + IMAGE_SHADER targetShader; + bool NormalmapSeparate = effects.extractNormalMap; + bool Mask = effects.maskMap != nullptr; + bool Distort = effects.distortionMap != nullptr; + if (NormalmapSeparate) + { + targetShader = IMAGE_SHADER_SEPARATENORMALMAP; + } + else + { + if (Mask) + { + if (Distort) + { + targetShader = IMAGE_SHADER_DISTORTION_MASKED; + } + else + { + targetShader = IMAGE_SHADER_MASKED; + } + } + else if (Distort) + { + targetShader = IMAGE_SHADER_DISTORTION; + } + else + { + targetShader = IMAGE_SHADER_STANDARD; + } + } + + device->BindGraphicsPSO(&imagePSO[targetShader][effects.blendFlag][effects.stencilComp][effects.hdr], threadID); + + fullScreenEffect = false; + } + else if (abs(effects.sunPos.x + effects.sunPos.y) < FLT_EPSILON) // POSTPROCESS + { + PostProcessCB prcb; + + fullScreenEffect = true; + + POSTPROCESS targetShader; + + if (effects.process.outline) + { + targetShader = POSTPROCESS_OUTLINE; + + prcb.xPPParams0.y = effects.process.outline ? 1.0f : 0.0f; + device->UpdateBuffer(&processCb, &prcb, threadID); + } + else if (effects.process.motionBlur) + { + targetShader = POSTPROCESS_MOTIONBLUR; + + prcb.xPPParams0.x = effects.process.motionBlur ? 1.0f : 0.0f; + device->UpdateBuffer(&processCb, &prcb, threadID); + } + else if (effects.process.dofStrength) + { + targetShader = POSTPROCESS_DEPTHOFFIELD; + + prcb.xPPParams0.z = effects.process.dofStrength; + device->UpdateBuffer(&processCb, &prcb, threadID); + } + else if (effects.process.fxaa) + { + targetShader = POSTPROCESS_FXAA; + } + else if (effects.process.ssao) + { + targetShader = POSTPROCESS_SSAO; + } + else if (effects.process.linDepth) + { + targetShader = POSTPROCESS_LINEARDEPTH; + } + else if (effects.process.colorGrade) + { + targetShader = POSTPROCESS_COLORGRADE; + } + else if (effects.process.ssr) + { + targetShader = POSTPROCESS_SSR; + } + else if (effects.process.stereogram) + { + targetShader = POSTPROCESS_STEREOGRAM; + } + else if (effects.process.tonemap) + { + targetShader = POSTPROCESS_TONEMAP; + } + else if (effects.process.ssss.x + effects.process.ssss.y > 0) + { + targetShader = POSTPROCESS_SSSS; + + prcb.xPPParams0.x = effects.process.ssss.x; + prcb.xPPParams0.y = effects.process.ssss.y; + device->UpdateBuffer(&processCb, &prcb, threadID); + } + else if (effects.bloom.separate) + { + targetShader = POSTPROCESS_BLOOMSEPARATE; + + prcb.xPPParams1.x = effects.bloom.separate ? 1.0f : 0.0f; + prcb.xPPParams1.y = effects.bloom.threshold; + prcb.xPPParams1.z = effects.bloom.saturation; + device->UpdateBuffer(&processCb, &prcb, threadID); + } + else if (effects.process.reprojectDepthBuffer) + { + targetShader = POSTPROCESS_REPROJECTDEPTHBUFFER; + } + else if (effects.process.downsampleDepthBuffer4x) + { + targetShader = POSTPROCESS_DOWNSAMPLEDEPTHBUFFER; + } + else if (effects.process.temporalAAResolve) + { + targetShader = POSTPROCESS_TEMPORALAA; + } + else if (effects.process.sharpen > 0) + { + targetShader = POSTPROCESS_SHARPEN; + + prcb.xPPParams0.x = effects.process.sharpen; + device->UpdateBuffer(&processCb, &prcb, threadID); + } + else + { + assert(0); // not impl + } + + device->BindGraphicsPSO(&postprocessPSO[targetShader], threadID); + } + else // LIGHTSHAFT + { + PostProcessCB prcb; + + fullScreenEffect = true; + + //Density|Weight|Decay|Exposure + prcb.xPPParams0.x = 0.65f; + prcb.xPPParams0.y = 0.25f; + prcb.xPPParams0.z = 0.945f; + prcb.xPPParams0.w = 0.2f; + prcb.xPPParams1.x = effects.sunPos.x; + prcb.xPPParams1.y = effects.sunPos.y; + + device->UpdateBuffer(&processCb, &prcb, threadID); + + device->BindGraphicsPSO(&postprocessPSO[POSTPROCESS_LIGHTSHAFT], threadID); + } + device->BindResource(PS, effects.maskMap, TEXSLOT_ONDEMAND1, threadID); + device->BindResource(PS, effects.distortionMap, TEXSLOT_ONDEMAND2, threadID); + device->BindResource(PS, effects.refractionSource, TEXSLOT_ONDEMAND3, threadID); + } + else // BLUR + { + PostProcessCB prcb; + + fullScreenEffect = true; + + if (effects.blurDir == 0) + { + device->BindGraphicsPSO(&postprocessPSO[POSTPROCESS_BLUR_H], threadID); + prcb.xPPParams1.w = 1.0f / wiRenderer::GetInternalResolution().x; + } + else + { + device->BindGraphicsPSO(&postprocessPSO[POSTPROCESS_BLUR_V], threadID); + prcb.xPPParams1.w = 1.0f / wiRenderer::GetInternalResolution().y; + } + + static float weight0 = 1.0f; + static float weight1 = 0.9f; + static float weight2 = 0.55f; + static float weight3 = 0.18f; + static float weight4 = 0.1f; + const float normalization = 1.0f / (weight0 + 2.0f * (weight1 + weight2 + weight3 + weight4)); + prcb.xPPParams0.x = weight0 * normalization; + prcb.xPPParams0.y = weight1 * normalization; + prcb.xPPParams0.z = weight2 * normalization; + prcb.xPPParams0.w = weight3 * normalization; + prcb.xPPParams1.x = weight4 * normalization; + prcb.xPPParams1.y = effects.blur; + prcb.xPPParams1.z = effects.mipLevel; + + device->UpdateBuffer(&processCb, &prcb, threadID); + + } + + device->Draw((fullScreenEffect ? 3 : 4), 0, threadID); + + device->EventEnd(threadID); + } + + void DrawDeferred(Texture2D* lightmap_diffuse, Texture2D* lightmap_specular, Texture2D* ao, + GRAPHICSTHREAD threadID, int stencilRef) + { + GraphicsDevice* device = wiRenderer::GetDevice(); + + device->EventBegin("DeferredComposition", threadID); + + device->BindStencilRef(stencilRef, threadID); + + device->BindResource(PS, lightmap_diffuse, TEXSLOT_ONDEMAND0, threadID); + device->BindResource(PS, lightmap_specular, TEXSLOT_ONDEMAND1, threadID); + device->BindResource(PS, ao, TEXSLOT_ONDEMAND2, threadID); + + device->BindGraphicsPSO(&deferredPSO, threadID); + + device->Draw(3, 0, threadID); + + device->EventEnd(threadID); + } + + + void LoadShaders() + { + std::string path = wiRenderer::GetShaderPath(); + + vertexShader = static_cast(wiResourceManager::GetShaderManager()->add(path + "imageVS.cso", wiResourceManager::VERTEXSHADER)); + screenVS = static_cast(wiResourceManager::GetShaderManager()->add(path + "screenVS.cso", wiResourceManager::VERTEXSHADER)); + + imagePS[IMAGE_SHADER_STANDARD] = static_cast(wiResourceManager::GetShaderManager()->add(path + "imagePS.cso", wiResourceManager::PIXELSHADER)); + imagePS[IMAGE_SHADER_SEPARATENORMALMAP] = static_cast(wiResourceManager::GetShaderManager()->add(path + "imagePS_separatenormalmap.cso", wiResourceManager::PIXELSHADER)); + imagePS[IMAGE_SHADER_DISTORTION] = static_cast(wiResourceManager::GetShaderManager()->add(path + "imagePS_distortion.cso", wiResourceManager::PIXELSHADER)); + imagePS[IMAGE_SHADER_DISTORTION_MASKED] = static_cast(wiResourceManager::GetShaderManager()->add(path + "imagePS_distortion_masked.cso", wiResourceManager::PIXELSHADER)); + imagePS[IMAGE_SHADER_MASKED] = static_cast(wiResourceManager::GetShaderManager()->add(path + "imagePS_masked.cso", wiResourceManager::PIXELSHADER)); + imagePS[IMAGE_SHADER_FULLSCREEN] = static_cast(wiResourceManager::GetShaderManager()->add(path + "screenPS.cso", wiResourceManager::PIXELSHADER)); + + postprocessPS[POSTPROCESS_BLUR_H] = static_cast(wiResourceManager::GetShaderManager()->add(path + "horizontalBlurPS.cso", wiResourceManager::PIXELSHADER)); + postprocessPS[POSTPROCESS_BLUR_V] = static_cast(wiResourceManager::GetShaderManager()->add(path + "verticalBlurPS.cso", wiResourceManager::PIXELSHADER)); + postprocessPS[POSTPROCESS_LIGHTSHAFT] = static_cast(wiResourceManager::GetShaderManager()->add(path + "lightShaftPS.cso", wiResourceManager::PIXELSHADER)); + postprocessPS[POSTPROCESS_OUTLINE] = static_cast(wiResourceManager::GetShaderManager()->add(path + "outlinePS.cso", wiResourceManager::PIXELSHADER)); + postprocessPS[POSTPROCESS_DEPTHOFFIELD] = static_cast(wiResourceManager::GetShaderManager()->add(path + "depthofFieldPS.cso", wiResourceManager::PIXELSHADER)); + postprocessPS[POSTPROCESS_MOTIONBLUR] = static_cast(wiResourceManager::GetShaderManager()->add(path + "motionBlurPS.cso", wiResourceManager::PIXELSHADER)); + postprocessPS[POSTPROCESS_BLOOMSEPARATE] = static_cast(wiResourceManager::GetShaderManager()->add(path + "bloomSeparatePS.cso", wiResourceManager::PIXELSHADER)); + postprocessPS[POSTPROCESS_FXAA] = static_cast(wiResourceManager::GetShaderManager()->add(path + "fxaa.cso", wiResourceManager::PIXELSHADER)); + postprocessPS[POSTPROCESS_SSAO] = static_cast(wiResourceManager::GetShaderManager()->add(path + "ssao.cso", wiResourceManager::PIXELSHADER)); + postprocessPS[POSTPROCESS_SSSS] = static_cast(wiResourceManager::GetShaderManager()->add(path + "ssss.cso", wiResourceManager::PIXELSHADER)); + postprocessPS[POSTPROCESS_LINEARDEPTH] = static_cast(wiResourceManager::GetShaderManager()->add(path + "linDepthPS.cso", wiResourceManager::PIXELSHADER)); + postprocessPS[POSTPROCESS_COLORGRADE] = static_cast(wiResourceManager::GetShaderManager()->add(path + "colorGradePS.cso", wiResourceManager::PIXELSHADER)); + postprocessPS[POSTPROCESS_SSR] = static_cast(wiResourceManager::GetShaderManager()->add(path + "ssr.cso", wiResourceManager::PIXELSHADER)); + postprocessPS[POSTPROCESS_STEREOGRAM] = static_cast(wiResourceManager::GetShaderManager()->add(path + "stereogramPS.cso", wiResourceManager::PIXELSHADER)); + postprocessPS[POSTPROCESS_TONEMAP] = static_cast(wiResourceManager::GetShaderManager()->add(path + "toneMapPS.cso", wiResourceManager::PIXELSHADER)); + postprocessPS[POSTPROCESS_REPROJECTDEPTHBUFFER] = static_cast(wiResourceManager::GetShaderManager()->add(path + "reprojectDepthBufferPS.cso", wiResourceManager::PIXELSHADER)); + postprocessPS[POSTPROCESS_DOWNSAMPLEDEPTHBUFFER] = static_cast(wiResourceManager::GetShaderManager()->add(path + "downsampleDepthBuffer4xPS.cso", wiResourceManager::PIXELSHADER)); + postprocessPS[POSTPROCESS_TEMPORALAA] = static_cast(wiResourceManager::GetShaderManager()->add(path + "temporalAAResolvePS.cso", wiResourceManager::PIXELSHADER)); + postprocessPS[POSTPROCESS_SHARPEN] = static_cast(wiResourceManager::GetShaderManager()->add(path + "sharpenPS.cso", wiResourceManager::PIXELSHADER)); + + deferredPS = static_cast(wiResourceManager::GetShaderManager()->add(path + "deferredPS.cso", wiResourceManager::PIXELSHADER)); + + + GraphicsDevice* device = wiRenderer::GetDevice(); + + vector thread_pool(0); + + thread_pool.push_back(thread([&] { + for (int i = 0; i < IMAGE_SHADER_COUNT; ++i) + { + GraphicsPSODesc desc; + desc.vs = vertexShader; + if (i == IMAGE_SHADER_FULLSCREEN) + { + desc.vs = screenVS; + } + desc.ps = imagePS[i]; + desc.rs = &rasterizerState; + desc.pt = TRIANGLESTRIP; + + for (int j = 0; j < BLENDMODE_COUNT; ++j) + { + desc.bs = &blendStates[j]; + for (int k = 0; k < STENCILMODE_COUNT; ++k) + { + desc.dss = &depthStencilStates[k]; + + if (k == STENCILMODE_DISABLED) + { + desc.DSFormat = FORMAT_UNKNOWN; + } + else + { + desc.DSFormat = wiRenderer::DSFormat_full; + } + + desc.numRTs = 1; + + desc.RTFormats[0] = device->GetBackBufferFormat(); + device->CreateGraphicsPSO(&desc, &imagePSO[i][j][k][0]); + + desc.RTFormats[0] = wiRenderer::RTFormat_hdr; + device->CreateGraphicsPSO(&desc, &imagePSO[i][j][k][1]); + } } } - } - })); + })); + + thread_pool.push_back(thread([&] { + for (int i = 0; i < POSTPROCESS_COUNT; ++i) + { + GraphicsPSODesc desc; + desc.vs = screenVS; + desc.ps = postprocessPS[i]; + desc.bs = &blendStates[BLENDMODE_OPAQUE]; + desc.dss = &depthStencilStates[STENCILMODE_DISABLED]; + desc.rs = &rasterizerState; + desc.pt = TRIANGLELIST; + + if (i == POSTPROCESS_DOWNSAMPLEDEPTHBUFFER || i == POSTPROCESS_REPROJECTDEPTHBUFFER) + { + desc.dss = &depthStencilStateDepthWrite; + desc.DSFormat = wiRenderer::DSFormat_small; + desc.numRTs = 0; + } + else if (i == POSTPROCESS_SSSS) + { + desc.dss = &depthStencilStates[STENCILMODE_LESS]; + desc.numRTs = 1; + desc.RTFormats[0] = wiRenderer::RTFormat_deferred_lightbuffer; + desc.DSFormat = wiRenderer::DSFormat_full; + } + else if (i == POSTPROCESS_SSAO) + { + desc.numRTs = 1; + desc.RTFormats[0] = wiRenderer::RTFormat_ssao; + } + else if (i == POSTPROCESS_LINEARDEPTH) + { + desc.numRTs = 1; + desc.RTFormats[0] = wiRenderer::RTFormat_lineardepth; + } + else if (i == POSTPROCESS_TONEMAP) + { + desc.numRTs = 1; + desc.RTFormats[0] = device->GetBackBufferFormat(); + } + else if (i == POSTPROCESS_BLOOMSEPARATE || i == POSTPROCESS_BLUR_H || POSTPROCESS_BLUR_V) + { + // todo: bloom and DoF blur should really be HDR lol... + desc.numRTs = 1; + desc.RTFormats[0] = device->GetBackBufferFormat(); + } + else + { + desc.numRTs = 1; + desc.RTFormats[0] = wiRenderer::RTFormat_hdr; + } + + device->CreateGraphicsPSO(&desc, &postprocessPSO[i]); + } - thread_pool.push_back(thread([&] { - for (int i = 0; i < POSTPROCESS_COUNT; ++i) - { GraphicsPSODesc desc; desc.vs = screenVS; - desc.ps = postprocessPS[i]; + desc.ps = deferredPS; desc.bs = &blendStates[BLENDMODE_OPAQUE]; - desc.dss = &depthStencilStates[STENCILMODE_DISABLED]; + desc.dss = &depthStencilStates[STENCILMODE_LESS]; desc.rs = &rasterizerState; + desc.numRTs = 1; + desc.RTFormats[0] = wiRenderer::RTFormat_hdr; + desc.DSFormat = wiRenderer::DSFormat_full; desc.pt = TRIANGLELIST; - - if (i == POSTPROCESS_DOWNSAMPLEDEPTHBUFFER || i == POSTPROCESS_REPROJECTDEPTHBUFFER) - { - desc.dss = &depthStencilStateDepthWrite; - desc.DSFormat = wiRenderer::DSFormat_small; - desc.numRTs = 0; - } - else if (i == POSTPROCESS_SSSS) - { - desc.dss = &depthStencilStates[STENCILMODE_LESS]; - desc.numRTs = 1; - desc.RTFormats[0] = wiRenderer::RTFormat_deferred_lightbuffer; - desc.DSFormat = wiRenderer::DSFormat_full; - } - else if (i == POSTPROCESS_SSAO) - { - desc.numRTs = 1; - desc.RTFormats[0] = wiRenderer::RTFormat_ssao; - } - else if (i == POSTPROCESS_LINEARDEPTH) - { - desc.numRTs = 1; - desc.RTFormats[0] = wiRenderer::RTFormat_lineardepth; - } - else if (i == POSTPROCESS_TONEMAP) - { - desc.numRTs = 1; - desc.RTFormats[0] = wiRenderer::GetDevice()->GetBackBufferFormat(); - } - else if (i == POSTPROCESS_BLOOMSEPARATE || i == POSTPROCESS_BLUR_H || POSTPROCESS_BLUR_V) - { - // todo: bloom and DoF blur should really be HDR lol... - desc.numRTs = 1; - desc.RTFormats[0] = wiRenderer::GetDevice()->GetBackBufferFormat(); - } - else - { - desc.numRTs = 1; - desc.RTFormats[0] = wiRenderer::RTFormat_hdr; - } - - device->CreateGraphicsPSO(&desc, &postprocessPSO[i]); - } - - GraphicsPSODesc desc; - desc.vs = screenVS; - desc.ps = deferredPS; - desc.bs = &blendStates[BLENDMODE_OPAQUE]; - desc.dss = &depthStencilStates[STENCILMODE_LESS]; - desc.rs = &rasterizerState; - desc.numRTs = 1; - desc.RTFormats[0] = wiRenderer::RTFormat_hdr; - desc.DSFormat = wiRenderer::DSFormat_full; - desc.pt = TRIANGLELIST; - device->CreateGraphicsPSO(&desc, &deferredPSO); - })); + device->CreateGraphicsPSO(&desc, &deferredPSO); + })); - for (auto& x : thread_pool) - { - x.join(); - } - -} -void wiImage::SetUpStates() -{ - - RasterizerStateDesc rs; - rs.FillMode = FILL_SOLID; - rs.CullMode = CULL_NONE; - rs.FrontCounterClockwise = false; - rs.DepthBias = 0; - rs.DepthBiasClamp = 0; - rs.SlopeScaledDepthBias = 0; - rs.DepthClipEnable = false; - rs.MultisampleEnable = false; - rs.AntialiasedLineEnable = false; - wiRenderer::GetDevice()->CreateRasterizerState(&rs, &rasterizerState); - - - - - - DepthStencilStateDesc dsd; - dsd.DepthEnable = false; - dsd.DepthWriteMask = DEPTH_WRITE_MASK_ZERO; - dsd.DepthFunc = COMPARISON_GREATER; - - dsd.StencilEnable = true; - dsd.StencilReadMask = DEFAULT_STENCIL_READ_MASK; - dsd.StencilWriteMask = 0; - dsd.FrontFace.StencilFunc = COMPARISON_LESS_EQUAL; - dsd.FrontFace.StencilPassOp = STENCIL_OP_KEEP; - dsd.FrontFace.StencilFailOp = STENCIL_OP_KEEP; - dsd.FrontFace.StencilDepthFailOp = STENCIL_OP_KEEP; - dsd.BackFace.StencilFunc = COMPARISON_LESS_EQUAL; - dsd.BackFace.StencilPassOp = STENCIL_OP_KEEP; - dsd.BackFace.StencilFailOp = STENCIL_OP_KEEP; - dsd.BackFace.StencilDepthFailOp = STENCIL_OP_KEEP; - wiRenderer::GetDevice()->CreateDepthStencilState(&dsd, &depthStencilStates[STENCILMODE_LESS]); - - dsd.FrontFace.StencilFunc = COMPARISON_EQUAL; - dsd.BackFace.StencilFunc = COMPARISON_EQUAL; - wiRenderer::GetDevice()->CreateDepthStencilState(&dsd, &depthStencilStates[STENCILMODE_EQUAL]); - - - dsd.DepthEnable = false; - dsd.DepthWriteMask = DEPTH_WRITE_MASK_ZERO; - dsd.DepthFunc = COMPARISON_GREATER; - - dsd.StencilEnable = true; - dsd.StencilReadMask = DEFAULT_STENCIL_READ_MASK; - dsd.StencilWriteMask = 0; - dsd.FrontFace.StencilFunc = COMPARISON_GREATER; - dsd.FrontFace.StencilPassOp = STENCIL_OP_KEEP; - dsd.FrontFace.StencilFailOp = STENCIL_OP_KEEP; - dsd.FrontFace.StencilDepthFailOp = STENCIL_OP_KEEP; - dsd.BackFace.StencilFunc = COMPARISON_GREATER; - dsd.BackFace.StencilPassOp = STENCIL_OP_KEEP; - dsd.BackFace.StencilFailOp = STENCIL_OP_KEEP; - dsd.BackFace.StencilDepthFailOp = STENCIL_OP_KEEP; - wiRenderer::GetDevice()->CreateDepthStencilState(&dsd, &depthStencilStates[STENCILMODE_GREATER]); - - dsd.StencilEnable = false; - wiRenderer::GetDevice()->CreateDepthStencilState(&dsd, &depthStencilStates[STENCILMODE_DISABLED]); - - - dsd.DepthEnable = true; - dsd.DepthWriteMask = DEPTH_WRITE_MASK_ALL; - dsd.DepthFunc = COMPARISON_ALWAYS; - dsd.StencilEnable = false; - wiRenderer::GetDevice()->CreateDepthStencilState(&dsd, &depthStencilStateDepthWrite); - - - BlendStateDesc bd; - ZeroMemory(&bd, sizeof(bd)); - bd.RenderTarget[0].BlendEnable=true; - bd.RenderTarget[0].SrcBlend = BLEND_SRC_ALPHA; - bd.RenderTarget[0].DestBlend = BLEND_INV_SRC_ALPHA; - bd.RenderTarget[0].BlendOp = BLEND_OP_ADD; - bd.RenderTarget[0].SrcBlendAlpha = BLEND_ONE; - bd.RenderTarget[0].DestBlendAlpha = BLEND_ONE; - bd.RenderTarget[0].BlendOpAlpha = BLEND_OP_ADD; - bd.RenderTarget[0].RenderTargetWriteMask = COLOR_WRITE_ENABLE_ALL; - bd.IndependentBlendEnable = false; - wiRenderer::GetDevice()->CreateBlendState(&bd,&blendStates[BLENDMODE_ALPHA]); - - ZeroMemory(&bd, sizeof(bd)); - bd.RenderTarget[0].BlendEnable=true; - bd.RenderTarget[0].SrcBlend = BLEND_ONE; - bd.RenderTarget[0].DestBlend = BLEND_INV_SRC_ALPHA; - bd.RenderTarget[0].BlendOp = BLEND_OP_ADD; - bd.RenderTarget[0].SrcBlendAlpha = BLEND_ONE; - bd.RenderTarget[0].DestBlendAlpha = BLEND_ONE; - bd.RenderTarget[0].BlendOpAlpha = BLEND_OP_ADD; - bd.RenderTarget[0].RenderTargetWriteMask = COLOR_WRITE_ENABLE_ALL; - bd.IndependentBlendEnable = false; - wiRenderer::GetDevice()->CreateBlendState(&bd, &blendStates[BLENDMODE_PREMULTIPLIED]); - - ZeroMemory(&bd, sizeof(bd)); - bd.RenderTarget[0].BlendEnable=false; - bd.RenderTarget[0].RenderTargetWriteMask = COLOR_WRITE_ENABLE_ALL; - bd.IndependentBlendEnable = false; - wiRenderer::GetDevice()->CreateBlendState(&bd, &blendStates[BLENDMODE_OPAQUE]); - - ZeroMemory(&bd, sizeof(bd)); - bd.RenderTarget[0].BlendEnable=true; - bd.RenderTarget[0].SrcBlend = BLEND_SRC_ALPHA; - bd.RenderTarget[0].DestBlend = BLEND_ONE; - bd.RenderTarget[0].BlendOp = BLEND_OP_ADD; - bd.RenderTarget[0].SrcBlendAlpha = BLEND_ZERO; - bd.RenderTarget[0].DestBlendAlpha = BLEND_ONE; - bd.RenderTarget[0].BlendOpAlpha = BLEND_OP_ADD; - bd.RenderTarget[0].RenderTargetWriteMask = COLOR_WRITE_ENABLE_ALL; - bd.IndependentBlendEnable = false; - wiRenderer::GetDevice()->CreateBlendState(&bd, &blendStates[BLENDMODE_ADDITIVE]); - - ZeroMemory(&bd, sizeof(bd)); - bd.RenderTarget[0].BlendEnable = false; - bd.RenderTarget[0].RenderTargetWriteMask = COLOR_WRITE_DISABLE; - bd.IndependentBlendEnable=false; - wiRenderer::GetDevice()->CreateBlendState(&bd, &blendStateDisableColor); -} - -void wiImage::BindPersistentState(GRAPHICSTHREAD threadID) -{ - wiRenderer::GetDevice()->BindConstantBuffer(VS, &constantBuffer, CB_GETBINDSLOT(ImageCB), threadID); - wiRenderer::GetDevice()->BindConstantBuffer(PS, &constantBuffer, CB_GETBINDSLOT(ImageCB), threadID); - - wiRenderer::GetDevice()->BindConstantBuffer(PS, &processCb, CB_GETBINDSLOT(PostProcessCB), threadID); -} - -void wiImage::Draw(Texture2D* texture, const wiImageEffects& effects,GRAPHICSTHREAD threadID) -{ - GraphicsDevice* device = wiRenderer::GetDevice(); - device->EventBegin("Image", threadID); - - bool fullScreenEffect = false; - - device->BindResource(PS, texture, TEXSLOT_ONDEMAND0, threadID); - - device->BindStencilRef(effects.stencilRef, threadID); - - if (effects.quality == QUALITY_NEAREST) - { - if (effects.sampleFlag == SAMPLEMODE_MIRROR) - device->BindSampler(PS, wiRenderer::GetSampler(SSLOT_POINT_MIRROR), SSLOT_ONDEMAND0, threadID); - else if (effects.sampleFlag == SAMPLEMODE_WRAP) - device->BindSampler(PS, wiRenderer::GetSampler(SSLOT_POINT_WRAP), SSLOT_ONDEMAND0, threadID); - else if (effects.sampleFlag == SAMPLEMODE_CLAMP) - device->BindSampler(PS, wiRenderer::GetSampler(SSLOT_POINT_CLAMP), SSLOT_ONDEMAND0, threadID); - } - else if (effects.quality == QUALITY_BILINEAR) - { - if (effects.sampleFlag == SAMPLEMODE_MIRROR) - device->BindSampler(PS, wiRenderer::GetSampler(SSLOT_LINEAR_MIRROR), SSLOT_ONDEMAND0, threadID); - else if (effects.sampleFlag == SAMPLEMODE_WRAP) - device->BindSampler(PS, wiRenderer::GetSampler(SSLOT_LINEAR_WRAP), SSLOT_ONDEMAND0, threadID); - else if (effects.sampleFlag == SAMPLEMODE_CLAMP) - device->BindSampler(PS, wiRenderer::GetSampler(SSLOT_LINEAR_CLAMP), SSLOT_ONDEMAND0, threadID); - } - else if (effects.quality == QUALITY_ANISOTROPIC) - { - if (effects.sampleFlag == SAMPLEMODE_MIRROR) - device->BindSampler(PS, wiRenderer::GetSampler(SSLOT_ANISO_MIRROR), SSLOT_ONDEMAND0, threadID); - else if (effects.sampleFlag == SAMPLEMODE_WRAP) - device->BindSampler(PS, wiRenderer::GetSampler(SSLOT_ANISO_WRAP), SSLOT_ONDEMAND0, threadID); - else if (effects.sampleFlag == SAMPLEMODE_CLAMP) - device->BindSampler(PS, wiRenderer::GetSampler(SSLOT_ANISO_CLAMP), SSLOT_ONDEMAND0, threadID); - } - - if (effects.presentFullScreen) - { - device->BindGraphicsPSO(&imagePSO[IMAGE_SHADER_FULLSCREEN][effects.blendFlag][effects.stencilComp][effects.hdr], threadID); - device->Draw(3, 0, threadID); - device->EventEnd(threadID); - return; - } - - if(!effects.blur) // NORMAL IMAGE - { - ImageCB cb; - - if(!effects.process.active && !effects.bloom.separate && !effects.sunPos.x && !effects.sunPos.y){ - if (effects.typeFlag == SCREEN) - { - XMStoreFloat4x4(&cb.xTransform, XMMatrixTranspose( - XMMatrixScaling(effects.scale.x*effects.siz.x, effects.scale.y*effects.siz.y, 1) - * XMMatrixRotationZ(effects.rotation) - * XMMatrixTranslation(effects.pos.x, effects.pos.y, 0) - * device->GetScreenProjection() - )); - } - else if (effects.typeFlag == WORLD) - { - XMMATRIX faceRot = XMMatrixIdentity(); - if (effects.lookAt.w) - { - XMVECTOR vvv = (effects.lookAt.x == 1 && !effects.lookAt.y && !effects.lookAt.z) ? XMVectorSet(0, 1, 0, 0) : XMVectorSet(1, 0, 0, 0); - faceRot = - XMMatrixLookAtLH(XMVectorSet(0, 0, 0, 0) - , XMLoadFloat4(&effects.lookAt) - , XMVector3Cross( - vvv, XMLoadFloat4(&effects.lookAt) - ) - ); - } - else - { - faceRot = XMLoadFloat3x3(&wiRenderer::GetCamera().rotationMatrix); - } - - XMMATRIX view = wiRenderer::GetCamera().GetView(); - XMMATRIX projection = wiRenderer::GetCamera().GetProjection(); - // Remove possible jittering from temporal camera: - projection.r[2] = XMVectorSetX(projection.r[2], 0); - projection.r[2] = XMVectorSetY(projection.r[2], 0); - - XMStoreFloat4x4(&cb.xTransform, XMMatrixTranspose( - XMMatrixScaling(effects.scale.x*effects.siz.x, -1 * effects.scale.y*effects.siz.y, 1) - *XMMatrixRotationZ(effects.rotation) - *faceRot - *XMMatrixTranslation(effects.pos.x, effects.pos.y, effects.pos.z) - *view * projection - )); - } - - // todo: effects.drawRec -> texmuladd! - - cb.xTexMulAdd = XMFLOAT4(1,1,effects.texOffset.x, effects.texOffset.y); - cb.xColor = effects.col; - cb.xColor.x *= 1 - effects.fade; - cb.xColor.y *= 1 - effects.fade; - cb.xColor.z *= 1 - effects.fade; - cb.xColor.w *= effects.opacity; - cb.xPivot = effects.pivot; - cb.xMirror = effects.mirror; - cb.xPivot = effects.pivot; - cb.xMipLevel = effects.mipLevel; - - device->UpdateBuffer(&constantBuffer, &cb, threadID); - - // Determine relevant image rendering pixel shader: - IMAGE_SHADER targetShader; - bool NormalmapSeparate = effects.extractNormalMap; - bool Mask = effects.maskMap != nullptr; - bool Distort = effects.distortionMap != nullptr; - if (NormalmapSeparate) - { - targetShader = IMAGE_SHADER_SEPARATENORMALMAP; - } - else - { - if (Mask) - { - if (Distort) - { - targetShader = IMAGE_SHADER_DISTORTION_MASKED; - } - else - { - targetShader = IMAGE_SHADER_MASKED; - } - } - else if(Distort) - { - targetShader = IMAGE_SHADER_DISTORTION; - } - else - { - targetShader = IMAGE_SHADER_STANDARD; - } - } - - device->BindGraphicsPSO(&imagePSO[targetShader][effects.blendFlag][effects.stencilComp][effects.hdr], threadID); - - fullScreenEffect = false; - } - else if(abs(effects.sunPos.x + effects.sunPos.y) < FLT_EPSILON) // POSTPROCESS + for (auto& x : thread_pool) { - PostProcessCB prcb; - - fullScreenEffect = true; - - POSTPROCESS targetShader; - - if (effects.process.outline) - { - targetShader = POSTPROCESS_OUTLINE; - - prcb.xPPParams0.y = effects.process.outline ? 1.0f : 0.0f; - device->UpdateBuffer(&processCb, &prcb, threadID); - } - else if (effects.process.motionBlur) - { - targetShader = POSTPROCESS_MOTIONBLUR; - - prcb.xPPParams0.x = effects.process.motionBlur ? 1.0f : 0.0f; - device->UpdateBuffer(&processCb, &prcb, threadID); - } - else if (effects.process.dofStrength) - { - targetShader = POSTPROCESS_DEPTHOFFIELD; - - prcb.xPPParams0.z = effects.process.dofStrength; - device->UpdateBuffer(&processCb, &prcb, threadID); - } - else if (effects.process.fxaa) - { - targetShader = POSTPROCESS_FXAA; - } - else if (effects.process.ssao) - { - targetShader = POSTPROCESS_SSAO; - } - else if (effects.process.linDepth) - { - targetShader = POSTPROCESS_LINEARDEPTH; - } - else if (effects.process.colorGrade) - { - targetShader = POSTPROCESS_COLORGRADE; - } - else if (effects.process.ssr) - { - targetShader = POSTPROCESS_SSR; - } - else if (effects.process.stereogram) - { - targetShader = POSTPROCESS_STEREOGRAM; - } - else if (effects.process.tonemap) - { - targetShader = POSTPROCESS_TONEMAP; - } - else if (effects.process.ssss.x + effects.process.ssss.y > 0) - { - targetShader = POSTPROCESS_SSSS; - - prcb.xPPParams0.x = effects.process.ssss.x; - prcb.xPPParams0.y = effects.process.ssss.y; - device->UpdateBuffer(&processCb, &prcb, threadID); - } - else if (effects.bloom.separate) - { - targetShader = POSTPROCESS_BLOOMSEPARATE; - - prcb.xPPParams1.x = effects.bloom.separate ? 1.0f : 0.0f; - prcb.xPPParams1.y = effects.bloom.threshold; - prcb.xPPParams1.z = effects.bloom.saturation; - device->UpdateBuffer(&processCb, &prcb, threadID); - } - else if (effects.process.reprojectDepthBuffer) - { - targetShader = POSTPROCESS_REPROJECTDEPTHBUFFER; - } - else if (effects.process.downsampleDepthBuffer4x) - { - targetShader = POSTPROCESS_DOWNSAMPLEDEPTHBUFFER; - } - else if (effects.process.temporalAAResolve) - { - targetShader = POSTPROCESS_TEMPORALAA; - } - else if (effects.process.sharpen > 0) - { - targetShader = POSTPROCESS_SHARPEN; - - prcb.xPPParams0.x = effects.process.sharpen; - device->UpdateBuffer(&processCb, &prcb, threadID); - } - else - { - assert(0); // not impl - } - - device->BindGraphicsPSO(&postprocessPSO[targetShader], threadID); + x.join(); } - else // LIGHTSHAFT - { - PostProcessCB prcb; - fullScreenEffect = true; - - //Density|Weight|Decay|Exposure - prcb.xPPParams0.x = 0.65f; - prcb.xPPParams0.y = 0.25f; - prcb.xPPParams0.z = 0.945f; - prcb.xPPParams0.w = 0.2f; - prcb.xPPParams1.x = effects.sunPos.x; - prcb.xPPParams1.y = effects.sunPos.y; - - device->UpdateBuffer(&processCb,&prcb,threadID); - - device->BindGraphicsPSO(&postprocessPSO[POSTPROCESS_LIGHTSHAFT], threadID); - } - device->BindResource(PS, effects.maskMap, TEXSLOT_ONDEMAND1, threadID); - device->BindResource(PS, effects.distortionMap, TEXSLOT_ONDEMAND2, threadID); - device->BindResource(PS, effects.refractionSource, TEXSLOT_ONDEMAND3, threadID); } - else // BLUR + + void BindPersistentState(GRAPHICSTHREAD threadID) { - PostProcessCB prcb; + GraphicsDevice* device = wiRenderer::GetDevice(); - fullScreenEffect = true; - - if(effects.blurDir==0) - { - device->BindGraphicsPSO(&postprocessPSO[POSTPROCESS_BLUR_H], threadID); - prcb.xPPParams1.w = 1.0f / wiRenderer::GetInternalResolution().x; - } - else - { - device->BindGraphicsPSO(&postprocessPSO[POSTPROCESS_BLUR_V], threadID); - prcb.xPPParams1.w = 1.0f / wiRenderer::GetInternalResolution().y; - } - - static float weight0 = 1.0f; - static float weight1 = 0.9f; - static float weight2 = 0.55f; - static float weight3 = 0.18f; - static float weight4 = 0.1f; - const float normalization = 1.0f / (weight0 + 2.0f * (weight1 + weight2 + weight3 + weight4)); - prcb.xPPParams0.x = weight0 * normalization; - prcb.xPPParams0.y = weight1 * normalization; - prcb.xPPParams0.z = weight2 * normalization; - prcb.xPPParams0.w = weight3 * normalization; - prcb.xPPParams1.x = weight4 * normalization; - prcb.xPPParams1.y = effects.blur; - prcb.xPPParams1.z = effects.mipLevel; - - device->UpdateBuffer(&processCb, &prcb, threadID); + device->BindConstantBuffer(VS, &constantBuffer, CB_GETBINDSLOT(ImageCB), threadID); + device->BindConstantBuffer(PS, &constantBuffer, CB_GETBINDSLOT(ImageCB), threadID); + device->BindConstantBuffer(PS, &processCb, CB_GETBINDSLOT(PostProcessCB), threadID); + } + + void Initialize() + { + GraphicsDevice* device = wiRenderer::GetDevice(); + + LoadShaders(); + + { + GPUBufferDesc bd; + bd.Usage = USAGE_DYNAMIC; + bd.ByteWidth = sizeof(ImageCB); + bd.BindFlags = BIND_CONSTANT_BUFFER; + bd.CPUAccessFlags = CPU_ACCESS_WRITE; + HRESULT hr = device->CreateBuffer(&bd, nullptr, &constantBuffer); + assert(SUCCEEDED(hr)); + } + + { + GPUBufferDesc bd; + bd.Usage = USAGE_DYNAMIC; + bd.ByteWidth = sizeof(PostProcessCB); + bd.BindFlags = BIND_CONSTANT_BUFFER; + bd.CPUAccessFlags = CPU_ACCESS_WRITE; + HRESULT hr = device->CreateBuffer(&bd, nullptr, &processCb); + assert(SUCCEEDED(hr)); + } + + RasterizerStateDesc rs; + rs.FillMode = FILL_SOLID; + rs.CullMode = CULL_NONE; + rs.FrontCounterClockwise = false; + rs.DepthBias = 0; + rs.DepthBiasClamp = 0; + rs.SlopeScaledDepthBias = 0; + rs.DepthClipEnable = false; + rs.MultisampleEnable = false; + rs.AntialiasedLineEnable = false; + device->CreateRasterizerState(&rs, &rasterizerState); + + + + + + DepthStencilStateDesc dsd; + dsd.DepthEnable = false; + dsd.DepthWriteMask = DEPTH_WRITE_MASK_ZERO; + dsd.DepthFunc = COMPARISON_GREATER; + + dsd.StencilEnable = true; + dsd.StencilReadMask = DEFAULT_STENCIL_READ_MASK; + dsd.StencilWriteMask = 0; + dsd.FrontFace.StencilFunc = COMPARISON_LESS_EQUAL; + dsd.FrontFace.StencilPassOp = STENCIL_OP_KEEP; + dsd.FrontFace.StencilFailOp = STENCIL_OP_KEEP; + dsd.FrontFace.StencilDepthFailOp = STENCIL_OP_KEEP; + dsd.BackFace.StencilFunc = COMPARISON_LESS_EQUAL; + dsd.BackFace.StencilPassOp = STENCIL_OP_KEEP; + dsd.BackFace.StencilFailOp = STENCIL_OP_KEEP; + dsd.BackFace.StencilDepthFailOp = STENCIL_OP_KEEP; + device->CreateDepthStencilState(&dsd, &depthStencilStates[STENCILMODE_LESS]); + + dsd.FrontFace.StencilFunc = COMPARISON_EQUAL; + dsd.BackFace.StencilFunc = COMPARISON_EQUAL; + device->CreateDepthStencilState(&dsd, &depthStencilStates[STENCILMODE_EQUAL]); + + + dsd.DepthEnable = false; + dsd.DepthWriteMask = DEPTH_WRITE_MASK_ZERO; + dsd.DepthFunc = COMPARISON_GREATER; + + dsd.StencilEnable = true; + dsd.StencilReadMask = DEFAULT_STENCIL_READ_MASK; + dsd.StencilWriteMask = 0; + dsd.FrontFace.StencilFunc = COMPARISON_GREATER; + dsd.FrontFace.StencilPassOp = STENCIL_OP_KEEP; + dsd.FrontFace.StencilFailOp = STENCIL_OP_KEEP; + dsd.FrontFace.StencilDepthFailOp = STENCIL_OP_KEEP; + dsd.BackFace.StencilFunc = COMPARISON_GREATER; + dsd.BackFace.StencilPassOp = STENCIL_OP_KEEP; + dsd.BackFace.StencilFailOp = STENCIL_OP_KEEP; + dsd.BackFace.StencilDepthFailOp = STENCIL_OP_KEEP; + device->CreateDepthStencilState(&dsd, &depthStencilStates[STENCILMODE_GREATER]); + + dsd.StencilEnable = false; + device->CreateDepthStencilState(&dsd, &depthStencilStates[STENCILMODE_DISABLED]); + + + dsd.DepthEnable = true; + dsd.DepthWriteMask = DEPTH_WRITE_MASK_ALL; + dsd.DepthFunc = COMPARISON_ALWAYS; + dsd.StencilEnable = false; + device->CreateDepthStencilState(&dsd, &depthStencilStateDepthWrite); + + + BlendStateDesc bd; + ZeroMemory(&bd, sizeof(bd)); + bd.RenderTarget[0].BlendEnable = true; + bd.RenderTarget[0].SrcBlend = BLEND_SRC_ALPHA; + bd.RenderTarget[0].DestBlend = BLEND_INV_SRC_ALPHA; + bd.RenderTarget[0].BlendOp = BLEND_OP_ADD; + bd.RenderTarget[0].SrcBlendAlpha = BLEND_ONE; + bd.RenderTarget[0].DestBlendAlpha = BLEND_ONE; + bd.RenderTarget[0].BlendOpAlpha = BLEND_OP_ADD; + bd.RenderTarget[0].RenderTargetWriteMask = COLOR_WRITE_ENABLE_ALL; + bd.IndependentBlendEnable = false; + device->CreateBlendState(&bd, &blendStates[BLENDMODE_ALPHA]); + + ZeroMemory(&bd, sizeof(bd)); + bd.RenderTarget[0].BlendEnable = true; + bd.RenderTarget[0].SrcBlend = BLEND_ONE; + bd.RenderTarget[0].DestBlend = BLEND_INV_SRC_ALPHA; + bd.RenderTarget[0].BlendOp = BLEND_OP_ADD; + bd.RenderTarget[0].SrcBlendAlpha = BLEND_ONE; + bd.RenderTarget[0].DestBlendAlpha = BLEND_ONE; + bd.RenderTarget[0].BlendOpAlpha = BLEND_OP_ADD; + bd.RenderTarget[0].RenderTargetWriteMask = COLOR_WRITE_ENABLE_ALL; + bd.IndependentBlendEnable = false; + device->CreateBlendState(&bd, &blendStates[BLENDMODE_PREMULTIPLIED]); + + ZeroMemory(&bd, sizeof(bd)); + bd.RenderTarget[0].BlendEnable = false; + bd.RenderTarget[0].RenderTargetWriteMask = COLOR_WRITE_ENABLE_ALL; + bd.IndependentBlendEnable = false; + device->CreateBlendState(&bd, &blendStates[BLENDMODE_OPAQUE]); + + ZeroMemory(&bd, sizeof(bd)); + bd.RenderTarget[0].BlendEnable = true; + bd.RenderTarget[0].SrcBlend = BLEND_SRC_ALPHA; + bd.RenderTarget[0].DestBlend = BLEND_ONE; + bd.RenderTarget[0].BlendOp = BLEND_OP_ADD; + bd.RenderTarget[0].SrcBlendAlpha = BLEND_ZERO; + bd.RenderTarget[0].DestBlendAlpha = BLEND_ONE; + bd.RenderTarget[0].BlendOpAlpha = BLEND_OP_ADD; + bd.RenderTarget[0].RenderTargetWriteMask = COLOR_WRITE_ENABLE_ALL; + bd.IndependentBlendEnable = false; + device->CreateBlendState(&bd, &blendStates[BLENDMODE_ADDITIVE]); + + ZeroMemory(&bd, sizeof(bd)); + bd.RenderTarget[0].BlendEnable = false; + bd.RenderTarget[0].RenderTargetWriteMask = COLOR_WRITE_DISABLE; + bd.IndependentBlendEnable = false; + device->CreateBlendState(&bd, &blendStateDisableColor); + } + void CleanUp() + { + SAFE_DELETE(vertexShader); + SAFE_DELETE(screenVS); + SAFE_DELETE(deferredPS); } - - device->Draw((fullScreenEffect ? 3 : 4), 0, threadID); - device->EventEnd(threadID); -} - -void wiImage::DrawDeferred(Texture2D* lightmap_diffuse, Texture2D* lightmap_specular, Texture2D* ao, - GRAPHICSTHREAD threadID, int stencilRef) -{ - GraphicsDevice* device = wiRenderer::GetDevice(); - - device->EventBegin("DeferredComposition", threadID); - - device->BindStencilRef(stencilRef, threadID); - - device->BindResource(PS, lightmap_diffuse, TEXSLOT_ONDEMAND0, threadID); - device->BindResource(PS, lightmap_specular, TEXSLOT_ONDEMAND1, threadID); - device->BindResource(PS, ao,TEXSLOT_ONDEMAND2,threadID); - - device->BindGraphicsPSO(&deferredPSO, threadID); - - device->Draw(3, 0, threadID); - - device->EventEnd(threadID); -} - - -void wiImage::Initialize() -{ - LoadBuffers(); - SetUpStates(); - LoadShaders(); -} -void wiImage::CleanUp() -{ - SAFE_DELETE(vertexShader); - SAFE_DELETE(screenVS); - SAFE_DELETE(deferredPS); } diff --git a/WickedEngine/wiImage.h b/WickedEngine/wiImage.h index 108b07420..1703af04f 100644 --- a/WickedEngine/wiImage.h +++ b/WickedEngine/wiImage.h @@ -4,88 +4,17 @@ #include "ShaderInterop.h" #include "wiImageEffects.h" -enum BLENDMODE; - -class wiImage +namespace wiImage { -protected: - static wiGraphicsTypes::GPUBuffer constantBuffer, processCb; - - static wiGraphicsTypes::VertexShader* vertexShader; - static wiGraphicsTypes::VertexShader* screenVS; - - enum IMAGE_SHADER - { - IMAGE_SHADER_STANDARD, - IMAGE_SHADER_SEPARATENORMALMAP, - IMAGE_SHADER_DISTORTION, - IMAGE_SHADER_DISTORTION_MASKED, - IMAGE_SHADER_MASKED, - IMAGE_SHADER_FULLSCREEN, - IMAGE_SHADER_COUNT - }; - static wiGraphicsTypes::PixelShader* imagePS[IMAGE_SHADER_COUNT]; - - enum POSTPROCESS - { - POSTPROCESS_BLUR_H, - POSTPROCESS_BLUR_V, - POSTPROCESS_LIGHTSHAFT, - POSTPROCESS_OUTLINE, - POSTPROCESS_DEPTHOFFIELD, - POSTPROCESS_MOTIONBLUR, - POSTPROCESS_BLOOMSEPARATE, - POSTPROCESS_FXAA, - POSTPROCESS_SSAO, - POSTPROCESS_SSSS, - POSTPROCESS_SSR, - POSTPROCESS_COLORGRADE, - POSTPROCESS_STEREOGRAM, - POSTPROCESS_TONEMAP, - POSTPROCESS_REPROJECTDEPTHBUFFER, - POSTPROCESS_DOWNSAMPLEDEPTHBUFFER, - POSTPROCESS_TEMPORALAA, - POSTPROCESS_SHARPEN, - POSTPROCESS_LINEARDEPTH, - POSTPROCESS_COUNT - }; - static wiGraphicsTypes::PixelShader* postprocessPS[POSTPROCESS_COUNT]; - static wiGraphicsTypes::PixelShader* deferredPS; - - - static wiGraphicsTypes::BlendState blendStates[BLENDMODE_COUNT]; - static wiGraphicsTypes::BlendState blendStateDisableColor; - static wiGraphicsTypes::RasterizerState rasterizerState; - static wiGraphicsTypes::DepthStencilState depthStencilStates[STENCILMODE_COUNT]; - static wiGraphicsTypes::DepthStencilState depthStencilStateDepthWrite; - - enum IMAGE_HDR - { - IMAGE_HDR_DISABLED, - IMAGE_HDR_ENABLED, - IMAGE_HDR_COUNT - }; - static wiGraphicsTypes::GraphicsPSO imagePSO[IMAGE_SHADER_COUNT][BLENDMODE_COUNT][STENCILMODE_COUNT][IMAGE_HDR_COUNT]; - static wiGraphicsTypes::GraphicsPSO postprocessPSO[POSTPROCESS_COUNT]; - static wiGraphicsTypes::GraphicsPSO deferredPSO; - - -public: - static void LoadShaders(); - static void BindPersistentState(GRAPHICSTHREAD threadID); -private: - static void LoadBuffers(); - static void SetUpStates(); - -public: - wiImage(); + void LoadShaders(); + void BindPersistentState(GRAPHICSTHREAD threadID); - static void Draw(wiGraphicsTypes::Texture2D* texture, const wiImageEffects& effects,GRAPHICSTHREAD threadID); + void Draw(wiGraphicsTypes::Texture2D* texture, const wiImageEffects& effects,GRAPHICSTHREAD threadID); - static void DrawDeferred(wiGraphicsTypes::Texture2D* lightmap_diffuse, wiGraphicsTypes::Texture2D* lightmap_specular, + void DrawDeferred(wiGraphicsTypes::Texture2D* lightmap_diffuse, wiGraphicsTypes::Texture2D* lightmap_specular, wiGraphicsTypes::Texture2D* ao, GRAPHICSTHREAD threadID, int stencilref = 0); - static void Initialize(); - static void CleanUp(); + void Initialize(); + void CleanUp(); }; diff --git a/WickedEngine/wiInitializer.cpp b/WickedEngine/wiInitializer.cpp index 52d3fb4be..d0f32f957 100644 --- a/WickedEngine/wiInitializer.cpp +++ b/WickedEngine/wiInitializer.cpp @@ -14,21 +14,35 @@ #include "wiGPUBVH.h" #include "wiPhysicsEngine.h" +#include +#include + using namespace std; namespace wiInitializer { + static bool finished = false; + static float initializationTime = 0; - void InitializeComponents() + void InitializeComponentsImmediate() { + if (finished) + { + return; + } + + wiTimer timer; + timer.record(); + + wiFont::Initialize(); + wiImage::Initialize(); + wiBackLog::Initialize(); wiFrameRate::Initialize(); wiCpuInfo::Initialize(); wiRenderer::Initialize(); wiLensFlare::Initialize(); - wiImage::Initialize(); - wiFont::Initialize(); wiOcean::Initialize(); wiWidget::LoadShaders(); @@ -43,6 +57,34 @@ namespace wiInitializer ss << "Failed to Initialize Audio Device!"; wiHelper::messageBox(ss.str()); } + + initializationTime = (float)(timer.elapsed() / 1000.0); + + finished = true; + + } + void InitializeComponentsAsync() + { + if (finished) + { + return; + } + + std::thread([] { + + InitializeComponentsImmediate(); + + }).detach(); + } + bool IsInitializeFinished() + { + return finished; + } + + float GetInitializationTimeInSeconds() + { + return initializationTime; + } } \ No newline at end of file diff --git a/WickedEngine/wiInitializer.h b/WickedEngine/wiInitializer.h index f8fe57191..32c52736c 100644 --- a/WickedEngine/wiInitializer.h +++ b/WickedEngine/wiInitializer.h @@ -3,7 +3,14 @@ namespace wiInitializer { - void InitializeComponents(); + // Initializes systems and blocks CPU until it is complete + void InitializeComponentsImmediate(); + // Begins initializing systems, but doesn't block CPU. Check completion status with IsInitializeFinished() + void InitializeComponentsAsync(); + // Check if systems have been initialized or not + bool IsInitializeFinished(); + // Check the time it took to initialize systems + float GetInitializationTimeInSeconds(); } diff --git a/WickedEngine/wiLensFlare.cpp b/WickedEngine/wiLensFlare.cpp index 095c9fb00..cf149df86 100644 --- a/WickedEngine/wiLensFlare.cpp +++ b/WickedEngine/wiLensFlare.cpp @@ -6,168 +6,167 @@ using namespace wiGraphicsTypes; -GPUBuffer *wiLensFlare::constantBuffer = nullptr; -PixelShader *wiLensFlare::pixelShader = nullptr; -GeometryShader *wiLensFlare::geometryShader = nullptr; -VertexShader *wiLensFlare::vertexShader = nullptr; -Sampler *wiLensFlare::samplercmp = nullptr; -RasterizerState wiLensFlare::rasterizerState; -DepthStencilState wiLensFlare::depthStencilState; -BlendState wiLensFlare::blendState; -GraphicsPSO wiLensFlare::PSO; +namespace wiLensFlare +{ + static GPUBuffer *constantBuffer = nullptr; + static PixelShader *pixelShader = nullptr; + static GeometryShader *geometryShader = nullptr; + static VertexShader *vertexShader = nullptr; + static Sampler *samplercmp = nullptr; + static RasterizerState rasterizerState; + static DepthStencilState depthStencilState; + static BlendState blendState; + static GraphicsPSO PSO; -void wiLensFlare::Initialize(){ - SetUpCB(); - SetUpStates(); - LoadShaders(); -} -void wiLensFlare::CleanUp(){ - SAFE_DELETE(constantBuffer); - SAFE_DELETE(pixelShader); - SAFE_DELETE(geometryShader); - SAFE_DELETE(vertexShader); - SAFE_DELETE(samplercmp); -} -void wiLensFlare::Draw(GRAPHICSTHREAD threadID, const XMVECTOR& lightPos, const std::vector& rims){ + void Draw(GRAPHICSTHREAD threadID, const XMVECTOR& lightPos, const std::vector& rims) { - if(!rims.empty()) - { - GraphicsDevice* device = wiRenderer::GetDevice(); - device->EventBegin("LensFlare", threadID); - - device->BindGraphicsPSO(&PSO, threadID); - - LensFlareCB cb; - XMStoreFloat4(&cb.xSunPos, lightPos / XMVectorSet((float)wiRenderer::GetInternalResolution().x, (float)wiRenderer::GetInternalResolution().y, 1, 1)); - cb.xScreen = XMFLOAT4((float)wiRenderer::GetInternalResolution().x, (float)wiRenderer::GetInternalResolution().y, 0, 0); - - device->UpdateBuffer(constantBuffer,&cb,threadID); - device->BindConstantBuffer(GS, constantBuffer, CB_GETBINDSLOT(LensFlareCB),threadID); - - - int i=0; - for(Texture2D* x : rims) + if (!rims.empty()) { - if(x!=nullptr) + GraphicsDevice* device = wiRenderer::GetDevice(); + device->EventBegin("LensFlare", threadID); + + device->BindGraphicsPSO(&PSO, threadID); + + LensFlareCB cb; + XMStoreFloat4(&cb.xSunPos, lightPos / XMVectorSet((float)wiRenderer::GetInternalResolution().x, (float)wiRenderer::GetInternalResolution().y, 1, 1)); + cb.xScreen = XMFLOAT4((float)wiRenderer::GetInternalResolution().x, (float)wiRenderer::GetInternalResolution().y, 0, 0); + + device->UpdateBuffer(constantBuffer, &cb, threadID); + device->BindConstantBuffer(GS, constantBuffer, CB_GETBINDSLOT(LensFlareCB), threadID); + + + int i = 0; + for (Texture2D* x : rims) { - device->BindResource(PS, x, TEXSLOT_ONDEMAND0 + i, threadID); - device->BindResource(GS, x, TEXSLOT_ONDEMAND0 + i, threadID); - i++; + if (x != nullptr) + { + device->BindResource(PS, x, TEXSLOT_ONDEMAND0 + i, threadID); + device->BindResource(GS, x, TEXSLOT_ONDEMAND0 + i, threadID); + i++; + } } + + device->BindSampler(GS, samplercmp, SSLOT_ONDEMAND0, threadID); + + + device->Draw(i, 0, threadID); + + + device->EventEnd(threadID); } - - device->BindSampler(GS, samplercmp, SSLOT_ONDEMAND0, threadID); - - - device->Draw(i, 0, threadID); - - - device->EventEnd(threadID); } -} - -void wiLensFlare::LoadShaders() -{ - std::string path = wiRenderer::GetShaderPath(); - - vertexShader = static_cast(wiResourceManager::GetShaderManager()->add(path+ "lensFlareVS.cso", wiResourceManager::VERTEXSHADER)); - - pixelShader = static_cast(wiResourceManager::GetShaderManager()->add(path + "lensFlarePS.cso", wiResourceManager::PIXELSHADER)); - - geometryShader = static_cast(wiResourceManager::GetShaderManager()->add(path + "lensFlareGS.cso", wiResourceManager::GEOMETRYSHADER)); - - - GraphicsDevice* device = wiRenderer::GetDevice(); - - GraphicsPSODesc desc; - desc.vs = vertexShader; - desc.ps = pixelShader; - desc.gs = geometryShader; - desc.bs = &blendState; - desc.rs = &rasterizerState; - desc.dss = &depthStencilState; - desc.pt = POINTLIST; - desc.numRTs = 1; - desc.RTFormats[0] = wiRenderer::RTFormat_hdr; - device->CreateGraphicsPSO(&desc, &PSO); -} -void wiLensFlare::SetUpCB() -{ - GPUBufferDesc bd; - ZeroMemory( &bd, sizeof(bd) ); - bd.Usage = USAGE_DYNAMIC; - bd.ByteWidth = sizeof(LensFlareCB); - bd.BindFlags = BIND_CONSTANT_BUFFER; - bd.CPUAccessFlags = CPU_ACCESS_WRITE; - constantBuffer = new GPUBuffer; - wiRenderer::GetDevice()->CreateBuffer( &bd, NULL, constantBuffer ); - -} -void wiLensFlare::SetUpStates() -{ - RasterizerStateDesc rs; - rs.FillMode=FILL_SOLID; - rs.CullMode=CULL_NONE; - rs.FrontCounterClockwise=true; - rs.DepthBias=0; - rs.DepthBiasClamp=0; - rs.SlopeScaledDepthBias=0; - rs.DepthClipEnable=false; - rs.MultisampleEnable=false; - rs.AntialiasedLineEnable=false; - wiRenderer::GetDevice()->CreateRasterizerState(&rs,&rasterizerState); - - - - - - DepthStencilStateDesc dsd; - dsd.DepthEnable = false; - dsd.DepthWriteMask = DEPTH_WRITE_MASK_ZERO; - dsd.DepthFunc = COMPARISON_GREATER; - - dsd.StencilEnable = false; - dsd.StencilReadMask = 0xFF; - dsd.StencilWriteMask = 0xFF; - - // Stencil operations if pixel is front-facing. - dsd.FrontFace.StencilFailOp = STENCIL_OP_KEEP; - dsd.FrontFace.StencilDepthFailOp = STENCIL_OP_INCR; - dsd.FrontFace.StencilPassOp = STENCIL_OP_KEEP; - dsd.FrontFace.StencilFunc = COMPARISON_ALWAYS; - - // Stencil operations if pixel is back-facing. - dsd.BackFace.StencilFailOp = STENCIL_OP_KEEP; - dsd.BackFace.StencilDepthFailOp = STENCIL_OP_DECR; - dsd.BackFace.StencilPassOp = STENCIL_OP_KEEP; - dsd.BackFace.StencilFunc = COMPARISON_ALWAYS; - - // Create the depth stencil state. - wiRenderer::GetDevice()->CreateDepthStencilState(&dsd, &depthStencilState); - - - - BlendStateDesc bd; - ZeroMemory(&bd, sizeof(bd)); - bd.RenderTarget[0].BlendEnable=true; - bd.RenderTarget[0].SrcBlend = BLEND_SRC_ALPHA; - bd.RenderTarget[0].DestBlend = BLEND_ONE; - bd.RenderTarget[0].BlendOp = BLEND_OP_ADD; - bd.RenderTarget[0].SrcBlendAlpha = BLEND_ONE; - bd.RenderTarget[0].DestBlendAlpha = BLEND_ONE; - bd.RenderTarget[0].BlendOpAlpha = BLEND_OP_ADD; - bd.RenderTarget[0].RenderTargetWriteMask = 0x0f; - wiRenderer::GetDevice()->CreateBlendState(&bd,&blendState); - - - SamplerDesc samplerDesc; - samplerDesc.Filter = FILTER_COMPARISON_MIN_MAG_LINEAR_MIP_POINT; - samplerDesc.AddressU = TEXTURE_ADDRESS_CLAMP; - samplerDesc.AddressV = TEXTURE_ADDRESS_CLAMP; - samplerDesc.AddressW = TEXTURE_ADDRESS_CLAMP; - samplerDesc.MipLODBias = 0.0f; - samplerDesc.MaxAnisotropy = 0; - samplerDesc.ComparisonFunc = COMPARISON_GREATER_EQUAL; - samplercmp = new Sampler; - wiRenderer::GetDevice()->CreateSamplerState(&samplerDesc, samplercmp); + + void LoadShaders() + { + std::string path = wiRenderer::GetShaderPath(); + + vertexShader = static_cast(wiResourceManager::GetShaderManager()->add(path + "lensFlareVS.cso", wiResourceManager::VERTEXSHADER)); + + pixelShader = static_cast(wiResourceManager::GetShaderManager()->add(path + "lensFlarePS.cso", wiResourceManager::PIXELSHADER)); + + geometryShader = static_cast(wiResourceManager::GetShaderManager()->add(path + "lensFlareGS.cso", wiResourceManager::GEOMETRYSHADER)); + + + GraphicsDevice* device = wiRenderer::GetDevice(); + + GraphicsPSODesc desc; + desc.vs = vertexShader; + desc.ps = pixelShader; + desc.gs = geometryShader; + desc.bs = &blendState; + desc.rs = &rasterizerState; + desc.dss = &depthStencilState; + desc.pt = POINTLIST; + desc.numRTs = 1; + desc.RTFormats[0] = wiRenderer::RTFormat_hdr; + device->CreateGraphicsPSO(&desc, &PSO); + } + void Initialize() + { + LoadShaders(); + + GPUBufferDesc bd; + bd.Usage = USAGE_DYNAMIC; + bd.ByteWidth = sizeof(LensFlareCB); + bd.BindFlags = BIND_CONSTANT_BUFFER; + bd.CPUAccessFlags = CPU_ACCESS_WRITE; + constantBuffer = new GPUBuffer; + wiRenderer::GetDevice()->CreateBuffer(&bd, nullptr, constantBuffer); + + + RasterizerStateDesc rs; + rs.FillMode = FILL_SOLID; + rs.CullMode = CULL_NONE; + rs.FrontCounterClockwise = true; + rs.DepthBias = 0; + rs.DepthBiasClamp = 0; + rs.SlopeScaledDepthBias = 0; + rs.DepthClipEnable = false; + rs.MultisampleEnable = false; + rs.AntialiasedLineEnable = false; + wiRenderer::GetDevice()->CreateRasterizerState(&rs, &rasterizerState); + + + + + + DepthStencilStateDesc dsd; + dsd.DepthEnable = false; + dsd.DepthWriteMask = DEPTH_WRITE_MASK_ZERO; + dsd.DepthFunc = COMPARISON_GREATER; + + dsd.StencilEnable = false; + dsd.StencilReadMask = 0xFF; + dsd.StencilWriteMask = 0xFF; + + // Stencil operations if pixel is front-facing. + dsd.FrontFace.StencilFailOp = STENCIL_OP_KEEP; + dsd.FrontFace.StencilDepthFailOp = STENCIL_OP_INCR; + dsd.FrontFace.StencilPassOp = STENCIL_OP_KEEP; + dsd.FrontFace.StencilFunc = COMPARISON_ALWAYS; + + // Stencil operations if pixel is back-facing. + dsd.BackFace.StencilFailOp = STENCIL_OP_KEEP; + dsd.BackFace.StencilDepthFailOp = STENCIL_OP_DECR; + dsd.BackFace.StencilPassOp = STENCIL_OP_KEEP; + dsd.BackFace.StencilFunc = COMPARISON_ALWAYS; + + // Create the depth stencil state. + wiRenderer::GetDevice()->CreateDepthStencilState(&dsd, &depthStencilState); + + + { + BlendStateDesc bd; + ZeroMemory(&bd, sizeof(bd)); + bd.RenderTarget[0].BlendEnable = true; + bd.RenderTarget[0].SrcBlend = BLEND_SRC_ALPHA; + bd.RenderTarget[0].DestBlend = BLEND_ONE; + bd.RenderTarget[0].BlendOp = BLEND_OP_ADD; + bd.RenderTarget[0].SrcBlendAlpha = BLEND_ONE; + bd.RenderTarget[0].DestBlendAlpha = BLEND_ONE; + bd.RenderTarget[0].BlendOpAlpha = BLEND_OP_ADD; + bd.RenderTarget[0].RenderTargetWriteMask = 0x0f; + wiRenderer::GetDevice()->CreateBlendState(&bd, &blendState); + + + SamplerDesc samplerDesc; + samplerDesc.Filter = FILTER_COMPARISON_MIN_MAG_LINEAR_MIP_POINT; + samplerDesc.AddressU = TEXTURE_ADDRESS_CLAMP; + samplerDesc.AddressV = TEXTURE_ADDRESS_CLAMP; + samplerDesc.AddressW = TEXTURE_ADDRESS_CLAMP; + samplerDesc.MipLODBias = 0.0f; + samplerDesc.MaxAnisotropy = 0; + samplerDesc.ComparisonFunc = COMPARISON_GREATER_EQUAL; + samplercmp = new Sampler; + wiRenderer::GetDevice()->CreateSamplerState(&samplerDesc, samplercmp); + } + } + void CleanUp() { + SAFE_DELETE(constantBuffer); + SAFE_DELETE(pixelShader); + SAFE_DELETE(geometryShader); + SAFE_DELETE(vertexShader); + SAFE_DELETE(samplercmp); + } + } diff --git a/WickedEngine/wiLensFlare.h b/WickedEngine/wiLensFlare.h index 45bdf6f06..e9f7baa9b 100644 --- a/WickedEngine/wiLensFlare.h +++ b/WickedEngine/wiLensFlare.h @@ -3,28 +3,13 @@ #include "CommonInclude.h" #include "wiGraphicsAPI.h" -class wiLensFlare +namespace wiLensFlare { -private: - static wiGraphicsTypes::GPUBuffer *constantBuffer; - static wiGraphicsTypes::PixelShader *pixelShader; - static wiGraphicsTypes::GeometryShader *geometryShader; - static wiGraphicsTypes::VertexShader *vertexShader; - static wiGraphicsTypes::RasterizerState rasterizerState; - static wiGraphicsTypes::DepthStencilState depthStencilState; - static wiGraphicsTypes::BlendState blendState; - static wiGraphicsTypes::Sampler *samplercmp; - static wiGraphicsTypes::GraphicsPSO PSO; + void Draw(GRAPHICSTHREAD threadID, const XMVECTOR& lightPos, const std::vector& rims); -public: - static void LoadShaders(); -private: - static void SetUpStates(); - static void SetUpCB(); -public: - static void Initialize(); - static void CleanUp(); - static void Draw(GRAPHICSTHREAD threadID, const XMVECTOR& lightPos, const std::vector& rims); + void LoadShaders(); + void Initialize(); + void CleanUp(); }; #endif diff --git a/WickedEngine/wiRenderer.cpp b/WickedEngine/wiRenderer.cpp index 6aeb8520f..2164a30f6 100644 --- a/WickedEngine/wiRenderer.cpp +++ b/WickedEngine/wiRenderer.cpp @@ -48,23 +48,23 @@ namespace wiRenderer GraphicsDevice* graphicsDevice = nullptr; -Sampler *samplers[SSLOT_COUNT] = {}; -VertexShader *vertexShaders[VSTYPE_LAST] = {}; -PixelShader *pixelShaders[PSTYPE_LAST] = {}; -GeometryShader *geometryShaders[GSTYPE_LAST] = {}; -HullShader *hullShaders[HSTYPE_LAST] = {}; -DomainShader *domainShaders[DSTYPE_LAST] = {}; -ComputeShader *computeShaders[CSTYPE_LAST] = {}; -VertexLayout *vertexLayouts[VLTYPE_LAST] = {}; -RasterizerState *rasterizers[RSTYPE_LAST] = {}; -DepthStencilState *depthStencils[DSSTYPE_LAST] = {}; -BlendState *blendStates[BSTYPE_LAST] = {}; -GPUBuffer *constantBuffers[CBTYPE_LAST] = {}; -GPUBuffer *resourceBuffers[RBTYPE_LAST] = {}; -Texture *textures[TEXTYPE_LAST] = {}; -Sampler *customsamplers[SSTYPE_LAST] = {}; +static Sampler *samplers[SSLOT_COUNT] = {}; +static VertexShader *vertexShaders[VSTYPE_LAST] = {}; +static PixelShader *pixelShaders[PSTYPE_LAST] = {}; +static GeometryShader *geometryShaders[GSTYPE_LAST] = {}; +static HullShader *hullShaders[HSTYPE_LAST] = {}; +static DomainShader *domainShaders[DSTYPE_LAST] = {}; +static ComputeShader *computeShaders[CSTYPE_LAST] = {}; +static VertexLayout *vertexLayouts[VLTYPE_LAST] = {}; +static RasterizerState *rasterizers[RSTYPE_LAST] = {}; +static DepthStencilState *depthStencils[DSSTYPE_LAST] = {}; +static BlendState *blendStates[BSTYPE_LAST] = {}; +static GPUBuffer *constantBuffers[CBTYPE_LAST] = {}; +static GPUBuffer *resourceBuffers[RBTYPE_LAST] = {}; +static Texture *textures[TEXTYPE_LAST] = {}; +static Sampler *customsamplers[SSTYPE_LAST] = {}; -string SHADERPATH = "shaders/"; +static string SHADERPATH = "shaders/"; LinearAllocator frameAllocators[GRAPHICSTHREAD_COUNT]; GPURingBuffer dynamicVertexBufferPools[GRAPHICSTHREAD_COUNT] = {}; @@ -507,10 +507,10 @@ void Initialize() LoadBuffers(); LoadShaders(); - wiHairParticle::SetUpStatic(); - wiEmittedParticle::SetUpStatic(); + wiHairParticle::Initialize(); + wiEmittedParticle::Initialize(); - Cube::LoadStatic(); + Cube::Initialize(); SetShadowProps2D(SHADOWRES_2D, SHADOWCOUNT_2D, SOFTSHADOWQUALITY_2D); SetShadowPropsCube(SHADOWRES_CUBE, SHADOWCOUNT_CUBE); @@ -518,9 +518,9 @@ void Initialize() } void CleanUp() { - wiHairParticle::CleanUpStatic(); - wiEmittedParticle::CleanUpStatic(); - Cube::CleanUpStatic(); + wiHairParticle::CleanUp(); + wiEmittedParticle::CleanUp(); + Cube::CleanUp(); for (int i = 0; i < VSTYPE_LAST; ++i) { @@ -5321,13 +5321,13 @@ void DrawDebugWorld(const CameraComponent& camera, GRAPHICSTHREAD threadID) device->BindGraphicsPSO(PSO_debug[DEBUGRENDERING_CUBE], threadID); GPUBuffer* vbs[] = { - &Cube::vertexBuffer, + Cube::GetVertexBuffer(), }; const UINT strides[] = { sizeof(XMFLOAT4) + sizeof(XMFLOAT4), }; device->BindVertexBuffers(vbs, 0, ARRAYSIZE(vbs), strides, nullptr, threadID); - device->BindIndexBuffer(&Cube::indexBuffer, INDEXFORMAT_16BIT, 0, threadID); + device->BindIndexBuffer(Cube::GetIndexBuffer(), INDEXFORMAT_16BIT, 0, threadID); MiscCB sb; @@ -5356,7 +5356,7 @@ void DrawDebugWorld(const CameraComponent& camera, GRAPHICSTHREAD threadID) MiscCB sb; for (size_t i = 0; i < scene.probes.GetCount(); ++i) { - EnvironmentProbeComponent& probe = scene.probes[i]; + const EnvironmentProbeComponent& probe = scene.probes[i]; XMStoreFloat4x4(&sb.g_xTransform, XMMatrixTranspose(XMMatrixTranslationFromVector(XMLoadFloat3(&probe.position)))); device->UpdateBuffer(constantBuffers[CBTYPE_MISC], &sb, threadID); @@ -5379,17 +5379,17 @@ void DrawDebugWorld(const CameraComponent& camera, GRAPHICSTHREAD threadID) device->BindGraphicsPSO(PSO_debug[DEBUGRENDERING_CUBE], threadID); GPUBuffer* vbs[] = { - &Cube::vertexBuffer, + Cube::GetVertexBuffer(), }; const UINT strides[] = { sizeof(XMFLOAT4) + sizeof(XMFLOAT4), }; device->BindVertexBuffers(vbs, 0, ARRAYSIZE(vbs), strides, nullptr, threadID); - device->BindIndexBuffer(&Cube::indexBuffer, INDEXFORMAT_16BIT, 0, threadID); + device->BindIndexBuffer(Cube::GetIndexBuffer(), INDEXFORMAT_16BIT, 0, threadID); for (size_t i = 0; i < scene.probes.GetCount(); ++i) { - EnvironmentProbeComponent& probe = scene.probes[i]; + const EnvironmentProbeComponent& probe = scene.probes[i]; if (probe.textureIndex < 0) { @@ -5516,13 +5516,13 @@ void DrawDebugWorld(const CameraComponent& camera, GRAPHICSTHREAD threadID) // No mesh, just draw a box: device->BindGraphicsPSO(PSO_debug[DEBUGRENDERING_CUBE], threadID); GPUBuffer* vbs[] = { - &Cube::vertexBuffer, + Cube::GetVertexBuffer(), }; const UINT strides[] = { sizeof(XMFLOAT4) + sizeof(XMFLOAT4), }; device->BindVertexBuffers(vbs, 0, ARRAYSIZE(vbs), strides, nullptr, threadID); - device->BindIndexBuffer(&Cube::indexBuffer, INDEXFORMAT_16BIT, 0, threadID); + device->BindIndexBuffer(Cube::GetIndexBuffer(), INDEXFORMAT_16BIT, 0, threadID); device->DrawIndexed(24, 0, 0, threadID); } else @@ -5585,13 +5585,13 @@ void DrawDebugWorld(const CameraComponent& camera, GRAPHICSTHREAD threadID) device->BindGraphicsPSO(PSO_debug[DEBUGRENDERING_CUBE], threadID); GPUBuffer* vbs[] = { - &Cube::vertexBuffer, + Cube::GetVertexBuffer(), }; const UINT strides[] = { sizeof(XMFLOAT4) + sizeof(XMFLOAT4), }; device->BindVertexBuffers(vbs, 0, ARRAYSIZE(vbs), strides, nullptr, threadID); - device->BindIndexBuffer(&Cube::indexBuffer, INDEXFORMAT_16BIT, 0, threadID); + device->BindIndexBuffer(Cube::GetIndexBuffer(), INDEXFORMAT_16BIT, 0, threadID); MiscCB sb; sb.g_xColor = XMFLOAT4(1, 1, 1, 1); diff --git a/WickedEngine/wiResourceManager.cpp b/WickedEngine/wiResourceManager.cpp index bcc7ba6a1..8fd7370e7 100644 --- a/WickedEngine/wiResourceManager.cpp +++ b/WickedEngine/wiResourceManager.cpp @@ -10,12 +10,12 @@ using namespace std; using namespace wiGraphicsTypes; -static const std::map types = { - std::pair("JPG", wiResourceManager::IMAGE), - std::pair("PNG", wiResourceManager::IMAGE), - std::pair("DDS", wiResourceManager::IMAGE), - std::pair("TGA", wiResourceManager::IMAGE), - std::pair("WAV", wiResourceManager::SOUND) +static const std::unordered_map types = { + make_pair("JPG", wiResourceManager::IMAGE), + make_pair("PNG", wiResourceManager::IMAGE), + make_pair("DDS", wiResourceManager::IMAGE), + make_pair("TGA", wiResourceManager::IMAGE), + make_pair("WAV", wiResourceManager::SOUND) }; wiResourceManager* wiResourceManager::globalResources = nullptr; diff --git a/WickedEngine/wiResourceManager.h b/WickedEngine/wiResourceManager.h index 1cb7de133..5d37922a4 100644 --- a/WickedEngine/wiResourceManager.h +++ b/WickedEngine/wiResourceManager.h @@ -4,7 +4,6 @@ #include "wiGraphicsAPI.h" #include "wiHashString.h" -#include #include class wiResourceManager : public wiThreadSafeManager diff --git a/WickedEngine/wiSceneSystem.cpp b/WickedEngine/wiSceneSystem.cpp index cab3ef56d..3672ebba8 100644 --- a/WickedEngine/wiSceneSystem.cpp +++ b/WickedEngine/wiSceneSystem.cpp @@ -860,10 +860,7 @@ namespace wiSceneSystem void Scene::Update(float dt) { - if (weathers.GetCount() > 0) - { - weather = weathers[0]; - } + RunWeatherUpdateSystem(weathers, weather); RunPreviousFrameTransformUpdateSystem(transforms, prev_transforms); @@ -1330,6 +1327,15 @@ namespace wiSceneSystem + void RunWeatherUpdateSystem( + const ComponentManager& weathers, + WeatherComponent& weather) + { + if (weathers.GetCount() > 0) + { + weather = weathers[0]; + } + } void RunPreviousFrameTransformUpdateSystem( const ComponentManager& transforms, ComponentManager& prev_transforms diff --git a/WickedEngine/wiSceneSystem.h b/WickedEngine/wiSceneSystem.h index f62d91b0a..b5897a97e 100644 --- a/WickedEngine/wiSceneSystem.h +++ b/WickedEngine/wiSceneSystem.h @@ -986,6 +986,10 @@ namespace wiSceneSystem void Serialize(wiArchive& archive); }; + void RunWeatherUpdateSystem( + const wiECS::ComponentManager& weathers, + WeatherComponent& weather + ); void RunPreviousFrameTransformUpdateSystem( const wiECS::ComponentManager& transforms, wiECS::ComponentManager& prev_transforms diff --git a/WickedEngine/wiSprite.h b/WickedEngine/wiSprite.h index c2b25c4f2..6262af5ff 100644 --- a/WickedEngine/wiSprite.h +++ b/WickedEngine/wiSprite.h @@ -5,7 +5,7 @@ class wiResourceManager; -class wiSprite : public wiImage +class wiSprite { private: std::string texture, mask, normal; diff --git a/WickedEngine/wiVersion.cpp b/WickedEngine/wiVersion.cpp index 2d01abac3..c50bb9d32 100644 --- a/WickedEngine/wiVersion.cpp +++ b/WickedEngine/wiVersion.cpp @@ -9,7 +9,7 @@ namespace wiVersion // minor features, major updates const int minor = 21; // minor bug fixes, alterations, refactors, updates - const int revision = 20; + const int revision = 21; long GetVersion() diff --git a/scripts/camera_animation_clamped.lua b/scripts/camera_animation_clamped.lua index 55e7abad3..eaf00c4d0 100644 --- a/scripts/camera_animation_clamped.lua +++ b/scripts/camera_animation_clamped.lua @@ -18,6 +18,11 @@ scriptableCameraSpeed = 0.4 local tt = 0.0 local play = false local rot = 0 +ToggleCameraAnimation = function() + tt = 0.0 + play = not play + rot = 0 +end -- Gather camera proxy entities in the scene from "cam0" to "cam1", "cam2", ... "camN": local proxies={} @@ -35,10 +40,7 @@ runProcess(function() while true do if(input.Press(VK_F8)) then - -- Reset animation: - tt = 0.0 - play = not play - rot = 0 + ToggleCameraAnimation() end if(play) then -- Play animation: diff --git a/scripts/camera_animation_repeat.lua b/scripts/camera_animation_repeat.lua index 3c811fb49..3225a0cc4 100644 --- a/scripts/camera_animation_repeat.lua +++ b/scripts/camera_animation_repeat.lua @@ -18,6 +18,11 @@ scriptableCameraSpeed = 0.4 local tt = 0.0 local play = false local rot = 0 +ToggleCameraAnimation = function() + tt = 0.0 + play = not play + rot = 0 +end -- Gather camera proxy entities in the scene from "cam0" to "cam1", "cam2", ... "camN": local proxies={} @@ -35,10 +40,7 @@ runProcess(function() while true do if(input.Press(VK_F8)) then - -- Reset animation: - tt = 0.0 - play = not play - rot = 0 + ToggleCameraAnimation() end if(play) then -- Play animation: