Merge pull request #1559 from rextimmy/dx11_clean

Direct3D11 Support
This commit is contained in:
Areloch 2016-03-29 00:51:23 -05:00
commit 6a40b8bb84
395 changed files with 12732 additions and 2452 deletions

View file

@ -188,7 +188,7 @@ void CameraSpline::renderTimeMap()
gBuilding = true;
// Build vertex buffer
GFXVertexBufferHandle<GFXVertexPC> vb;
GFXVertexBufferHandle<GFXVertexPCT> vb;
vb.set(GFX, mTimeMap.size(), GFXBufferTypeVolatile);
void *ptr = vb.lock();
if(!ptr) return;

View file

@ -1557,7 +1557,7 @@ void Precipitation::renderObject(ObjectRenderInst *ri, SceneRenderState *state,
Point3F pos;
VectorF orthoDir, velocity, right, up, rightUp(0.0f, 0.0f, 0.0f), leftUp(0.0f, 0.0f, 0.0f);
F32 distance = 0;
GFXVertexPT* vertPtr = NULL;
GFXVertexPCT* vertPtr = NULL;
const Point2F *tc;
// Do this here and we won't have to in the loop!

View file

@ -239,7 +239,7 @@ class Precipitation : public GameBase
void destroySplash(Raindrop *drop); ///< Removes a drop from the splash list
GFXPrimitiveBufferHandle mRainIB;
GFXVertexBufferHandle<GFXVertexPT> mRainVB;
GFXVertexBufferHandle<GFXVertexPCT> mRainVB;
bool onAdd();
void onRemove();

View file

@ -317,8 +317,7 @@ void VolumetricFog::handleResize(VolumetricFogRTManager *RTM, bool resize)
{
F32 width = (F32)mPlatformWindow->getClientExtent().x;
F32 height = (F32)mPlatformWindow->getClientExtent().y;
if (!mPlatformWindow->isFullscreen())
height -= 20;//subtract caption bar from rendertarget size.
mTexScale.x = 2.0f - ((F32)mTexture.getWidth() / width);
mTexScale.y = 2.0f - ((F32)mTexture.getHeight() / height);
}
@ -1075,7 +1074,6 @@ void VolumetricFog::render(ObjectRenderInst *ri, SceneRenderState *state, BaseMa
mPPShaderConsts->setSafe(mPPModelViewProjSC, xform);
LightInfo *lightinfo = LIGHTMGR->getSpecialLight(LightManager::slSunLightType);
const ColorF &sunlight = state->getAmbientLightColor();
Point3F ambientColor(sunlight.red, sunlight.green, sunlight.blue);
@ -1160,6 +1158,11 @@ void VolumetricFog::render(ObjectRenderInst *ri, SceneRenderState *state, BaseMa
GFX->setStateBlock(mStateblockF);
GFX->drawPrimitive(0);
// Ensure these two textures are bound to the pixel shader input on the second run as they are used as pixel shader outputs (render targets).
GFX->setTexture(1, NULL); //mDepthBuffer
GFX->setTexture(2, NULL); //mFrontBuffer
GFX->updateStates(); //update the dirty texture state we set above
}
void VolumetricFog::reflect_render(ObjectRenderInst *ri, SceneRenderState *state, BaseMatInstance *overrideMat)
@ -1210,9 +1213,6 @@ void VolumetricFog::InitTexture()
F32 width = (F32)mPlatformWindow->getClientExtent().x;
F32 height = (F32)mPlatformWindow->getClientExtent().y;
if (!mPlatformWindow->isFullscreen())
height -= 20;//subtract caption bar from rendertarget size.
mTexScale.x = 2.0f - ((F32)mTexture.getWidth() / width);
mTexScale.y = 2.0f - ((F32)mTexture.getHeight() / height);
}

View file

@ -36,6 +36,7 @@
#include "windowManager/platformWindowMgr.h"
#include "console/engineAPI.h"
#include "gui/core/guiCanvas.h"
#include "gfx/gfxDevice.h"
MODULE_BEGIN(VolumetricFogRTManager)
@ -127,10 +128,10 @@ void VolumetricFogRTManager::consoleInit()
bool VolumetricFogRTManager::Init()
{
if (mIsInitialized)
{
{
Con::errorf("VolumetricFogRTManager allready initialized!!");
return true;
}
}
GuiCanvas* cv = dynamic_cast<GuiCanvas*>(Sim::findObject("Canvas"));
if (cv == NULL)
@ -142,15 +143,11 @@ bool VolumetricFogRTManager::Init()
mPlatformWindow = cv->getPlatformWindow();
mPlatformWindow->getScreenResChangeSignal().notify(this,&VolumetricFogRTManager::ResizeRT);
if (mTargetScale < 1)
if (mTargetScale < 1 || GFX->getAdapterType() == Direct3D11)
mTargetScale = 1;
mWidth = mFloor(mPlatformWindow->getClientExtent().x / mTargetScale);
mHeight = mPlatformWindow->getClientExtent().y;
mFullScreen = mPlatformWindow->isFullscreen();
if (!mFullScreen)
mHeight -= 20;//subtract caption bar from rendertarget size.
mHeight = mFloor(mHeight / mTargetScale);
mHeight = mFloor(mPlatformWindow->getClientExtent().y / mTargetScale);
mDepthBuffer = GFXTexHandle(mWidth, mHeight, GFXFormatR32F,
&GFXDefaultRenderTargetProfile, avar("%s() - mDepthBuffer (line %d)", __FUNCTION__, __LINE__));
@ -221,14 +218,11 @@ void VolumetricFogRTManager::FogAnswered()
bool VolumetricFogRTManager::Resize()
{
if (mTargetScale < 1)
if (mTargetScale < 1 || GFX->getAdapterType() == Direct3D11)
mTargetScale = 1;
mWidth = mFloor(mPlatformWindow->getClientExtent().x / mTargetScale);
mHeight = mPlatformWindow->getClientExtent().y;
if (!mPlatformWindow->isFullscreen())
mHeight -= 20;//subtract caption bar from rendertarget size.
mHeight = mFloor(mHeight / mTargetScale);
mHeight = mFloor(mPlatformWindow->getClientExtent().y / mTargetScale);
if (mWidth < 16 || mHeight < 16)
return false;
@ -248,19 +242,19 @@ bool VolumetricFogRTManager::Resize()
mFrontBuffer = GFXTexHandle(mWidth, mHeight, GFXFormatR32F,
&GFXDefaultRenderTargetProfile, avar("%s() - mFrontBuffer (line %d)", __FUNCTION__, __LINE__));
if (!mFrontBuffer.isValid())
{
{
Con::errorf("VolumetricFogRTManager::Resize() Fatal Error: Unable to create front buffer");
return false;
}
}
mFrontTarget.setTexture(mFrontBuffer);
mDepthBuffer = GFXTexHandle(mWidth, mHeight, GFXFormatR32F,
&GFXDefaultRenderTargetProfile, avar("%s() - mDepthBuffer (line %d)", __FUNCTION__, __LINE__));
if (!mDepthBuffer.isValid())
{
Con::errorf("VolumetricFogRTManager::Resize() Fatal Error: Unable to create Depthbuffer");
return false;
}
{
Con::errorf("VolumetricFogRTManager::Resize() Fatal Error: Unable to create Depthbuffer");
return false;
}
mDepthTarget.setTexture(mDepthBuffer);
return true;
}

View file

@ -62,7 +62,6 @@ class VolumetricFogRTManager : public SceneObject
U32 mFogHasAnswered;
U32 mWidth;
U32 mHeight;
bool mFullScreen;
void onRemove();
void onSceneRemove();

View file

@ -1067,17 +1067,17 @@ void ScatterSky::_renderMoon( ObjectRenderInst *ri, SceneRenderState *state, Bas
// Initialize points with basic info
Point3F points[4];
points[0] = Point3F(-BBRadius, 0.0, -BBRadius);
points[0] = Point3F( -BBRadius, 0.0, -BBRadius);
points[1] = Point3F( -BBRadius, 0.0, BBRadius);
points[2] = Point3F( BBRadius, 0.0, BBRadius);
points[3] = Point3F( BBRadius, 0.0, -BBRadius);
points[2] = Point3F( BBRadius, 0.0, -BBRadius);
points[3] = Point3F( BBRadius, 0.0, BBRadius);
static const Point2F sCoords[4] =
{
Point2F( 0.0f, 0.0f ),
Point2F( 0.0f, 1.0f ),
Point2F( 1.0f, 1.0f ),
Point2F( 1.0f, 0.0f )
Point2F( 1.0f, 0.0f ),
Point2F( 1.0f, 1.0f )
};
// Get info we need to adjust points
@ -1126,7 +1126,7 @@ void ScatterSky::_renderMoon( ObjectRenderInst *ri, SceneRenderState *state, Bas
mMoonMatInst->setSceneInfo( state, sgData );
GFX->setVertexBuffer( vb );
GFX->drawPrimitive( GFXTriangleFan, 0, 2 );
GFX->drawPrimitive( GFXTriangleStrip, 0, 2 );
}
}

View file

@ -467,15 +467,15 @@ void Sun::_renderCorona( ObjectRenderInst *ri, SceneRenderState *state, BaseMatI
Point3F points[4];
points[0] = Point3F(-BBRadius, 0.0, -BBRadius);
points[1] = Point3F( -BBRadius, 0.0, BBRadius);
points[2] = Point3F( BBRadius, 0.0, BBRadius);
points[3] = Point3F( BBRadius, 0.0, -BBRadius);
points[2] = Point3F( BBRadius, 0.0, -BBRadius);
points[3] = Point3F(BBRadius, 0.0, BBRadius);
static const Point2F sCoords[4] =
{
Point2F( 0.0f, 0.0f ),
Point2F( 0.0f, 1.0f ),
Point2F( 1.0f, 1.0f ),
Point2F( 1.0f, 0.0f )
Point2F( 1.0f, 0.0f ),
Point2F(1.0f, 1.0f)
};
// Get info we need to adjust points
@ -525,7 +525,7 @@ void Sun::_renderCorona( ObjectRenderInst *ri, SceneRenderState *state, BaseMatI
mCoronaMatInst->setSceneInfo( state, sgData );
GFX->setVertexBuffer( vb );
GFX->drawPrimitive( GFXTriangleFan, 0, 2 );
GFX->drawPrimitive( GFXTriangleStrip, 0, 2 );
}
}

View file

@ -826,25 +826,25 @@ void WaterObject::drawUnderwaterFilter( SceneRenderState *state )
// draw quad
GFXVertexBufferHandle<GFXVertexPC> verts( GFX, 4, GFXBufferTypeVolatile );
GFXVertexBufferHandle<GFXVertexPCT> verts( GFX, 4, GFXBufferTypeVolatile );
verts.lock();
verts[0].point.set( -1.0 - copyOffsetX, -1.0 + copyOffsetY, 0.0 );
verts[0].point.set(1.0 - copyOffsetX, -1.0 + copyOffsetY, 0.0);
verts[0].color = mUnderwaterColor;
verts[1].point.set( -1.0 - copyOffsetX, 1.0 + copyOffsetY, 0.0 );
verts[1].point.set(1.0 - copyOffsetX, 1.0 + copyOffsetY, 0.0);
verts[1].color = mUnderwaterColor;
verts[2].point.set( 1.0 - copyOffsetX, 1.0 + copyOffsetY, 0.0 );
verts[2].point.set(-1.0 - copyOffsetX, -1.0 + copyOffsetY, 0.0);
verts[2].color = mUnderwaterColor;
verts[3].point.set( 1.0 - copyOffsetX, -1.0 + copyOffsetY, 0.0 );
verts[3].point.set(-1.0 - copyOffsetX, 1.0 + copyOffsetY, 0.0);
verts[3].color = mUnderwaterColor;
verts.unlock();
GFX->setVertexBuffer( verts );
GFX->drawPrimitive( GFXTriangleFan, 0, 2 );
GFX->drawPrimitive( GFXTriangleStrip, 0, 2 );
// reset states / transforms
GFX->setProjectionMatrix( proj );
@ -1141,7 +1141,7 @@ bool WaterObject::initMaterial( S32 idx )
else
mat = MATMGR->createMatInstance( mSurfMatName[idx] );
const GFXVertexFormat *flags = getGFXVertexFormat<GFXVertexPC>();
const GFXVertexFormat *flags = getGFXVertexFormat<GFXVertexPCT>();
if ( mat && mat->init( MATMGR->getDefaultFeatures(), flags ) )
{

View file

@ -0,0 +1,72 @@
//-----------------------------------------------------------------------------
// Copyright (c) 2015 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#include "gfx/D3D11/gfxD3D11CardProfiler.h"
#include "gfx/D3D11/gfxD3D11Device.h"
#include "gfx/D3D11/gfxD3D11EnumTranslate.h"
#include "platformWin32/videoInfo/wmiVideoInfo.h"
#include "console/console.h"
#include "gfx/primBuilder.h"
GFXD3D11CardProfiler::GFXD3D11CardProfiler() : GFXCardProfiler()
{
}
GFXD3D11CardProfiler::~GFXD3D11CardProfiler()
{
}
void GFXD3D11CardProfiler::init()
{
U32 adapterIndex = D3D11->getAdaterIndex();
WMIVideoInfo wmiVidInfo;
if (wmiVidInfo.profileAdapters())
{
const PlatformVideoInfo::PVIAdapter &adapter = wmiVidInfo.getAdapterInformation(adapterIndex);
mCardDescription = adapter.description;
mChipSet = adapter.chipSet;
mVersionString = adapter.driverVersion;
mVideoMemory = adapter.vram;
}
Parent::init();
}
void GFXD3D11CardProfiler::setupCardCapabilities()
{
setCapability("maxTextureWidth", D3D11_REQ_TEXTURE2D_U_OR_V_DIMENSION);
setCapability("maxTextureHeight", D3D11_REQ_TEXTURE2D_U_OR_V_DIMENSION);
setCapability("maxTextureSize", D3D11_REQ_TEXTURE2D_U_OR_V_DIMENSION);
}
bool GFXD3D11CardProfiler::_queryCardCap(const String &query, U32 &foundResult)
{
return false;
}
bool GFXD3D11CardProfiler::_queryFormat( const GFXFormat fmt, const GFXTextureProfile *profile, bool &inOutAutogenMips )
{
// D3D11 feature level should guarantee that any format is valid!
return GFXD3D11TextureFormat[fmt] != DXGI_FORMAT_UNKNOWN;
}

View file

@ -0,0 +1,46 @@
//-----------------------------------------------------------------------------
// Copyright (c) 2015 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#ifndef _GFXD3D11CARDPROFILER_H_
#define _GFXD3D11CARDPROFILER_H_
#include "gfx/gfxCardProfile.h"
class GFXD3D11CardProfiler : public GFXCardProfiler
{
private:
typedef GFXCardProfiler Parent;
public:
GFXD3D11CardProfiler();
~GFXD3D11CardProfiler();
void init();
protected:
const String &getRendererString() const { static String sRS("Direct3D11"); return sRS; }
void setupCardCapabilities();
bool _queryCardCap(const String &query, U32 &foundResult);
bool _queryFormat(const GFXFormat fmt, const GFXTextureProfile *profile, bool &inOutAutogenMips);
};
#endif

View file

@ -0,0 +1,352 @@
//-----------------------------------------------------------------------------
// Copyright (c) 2015 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#include "gfx/D3D11/gfxD3D11Cubemap.h"
#include "gfx/gfxCardProfile.h"
#include "gfx/gfxTextureManager.h"
#include "gfx/D3D11/gfxD3D11EnumTranslate.h"
GFXD3D11Cubemap::GFXD3D11Cubemap() : mTexture(NULL), mSRView(NULL), mDSView(NULL)
{
mDynamic = false;
mAutoGenMips = false;
mFaceFormat = GFXFormatR8G8B8A8;
for (U32 i = 0; i < CubeFaces; i++)
{
mRTView[i] = NULL;
}
}
GFXD3D11Cubemap::~GFXD3D11Cubemap()
{
releaseSurfaces();
}
void GFXD3D11Cubemap::releaseSurfaces()
{
if (mDynamic)
GFXTextureManager::removeEventDelegate(this, &GFXD3D11Cubemap::_onTextureEvent);
for (U32 i = 0; i < CubeFaces; i++)
{
SAFE_RELEASE(mRTView[i]);
}
SAFE_RELEASE(mDSView);
SAFE_RELEASE(mSRView);
SAFE_RELEASE(mTexture);
}
void GFXD3D11Cubemap::_onTextureEvent(GFXTexCallbackCode code)
{
if (code == GFXZombify)
releaseSurfaces();
else if (code == GFXResurrect)
initDynamic(mTexSize);
}
bool GFXD3D11Cubemap::isCompressed(GFXFormat format)
{
if (format >= GFXFormatDXT1 && format <= GFXFormatDXT5)
return true;
return false;
}
void GFXD3D11Cubemap::initStatic(GFXTexHandle *faces)
{
AssertFatal( faces, "GFXD3D11Cubemap::initStatic - Got null GFXTexHandle!" );
AssertFatal( *faces, "empty texture passed to CubeMap::create" );
// NOTE - check tex sizes on all faces - they MUST be all same size
mTexSize = faces->getWidth();
mFaceFormat = faces->getFormat();
bool compressed = isCompressed(mFaceFormat);
UINT bindFlags = D3D11_BIND_SHADER_RESOURCE;
UINT miscFlags = D3D11_RESOURCE_MISC_TEXTURECUBE;
if (!compressed)
{
bindFlags |= D3D11_BIND_RENDER_TARGET;
miscFlags |= D3D11_RESOURCE_MISC_GENERATE_MIPS;
}
U32 mipLevels = faces->getPointer()->getMipLevels();
if (mipLevels > 1)
mAutoGenMips = true;
D3D11_TEXTURE2D_DESC desc;
ZeroMemory(&desc, sizeof(D3D11_TEXTURE2D_DESC));
desc.Width = mTexSize;
desc.Height = mTexSize;
desc.MipLevels = mAutoGenMips ? 0 : mipLevels;
desc.ArraySize = 6;
desc.Format = GFXD3D11TextureFormat[mFaceFormat];
desc.SampleDesc.Count = 1;
desc.SampleDesc.Quality = 0;
desc.Usage = D3D11_USAGE_DEFAULT;
desc.BindFlags = bindFlags;
desc.MiscFlags = miscFlags;
desc.CPUAccessFlags = 0;
HRESULT hr = D3D11DEVICE->CreateTexture2D(&desc, NULL, &mTexture);
if (FAILED(hr))
{
AssertFatal(false, "GFXD3D11Cubemap:initStatic(GFXTexhandle *faces) - failed to create texcube texture");
}
for (U32 i = 0; i < CubeFaces; i++)
{
GFXD3D11TextureObject *texObj = static_cast<GFXD3D11TextureObject*>((GFXTextureObject*)faces[i]);
U32 subResource = D3D11CalcSubresource(0, i, mipLevels);
D3D11DEVICECONTEXT->CopySubresourceRegion(mTexture, subResource, 0, 0, 0, texObj->get2DTex(), 0, NULL);
}
D3D11_SHADER_RESOURCE_VIEW_DESC SMViewDesc;
SMViewDesc.Format = GFXD3D11TextureFormat[mFaceFormat];
SMViewDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURECUBE;
SMViewDesc.TextureCube.MipLevels = mAutoGenMips ? -1 : mipLevels;
SMViewDesc.TextureCube.MostDetailedMip = 0;
hr = D3D11DEVICE->CreateShaderResourceView(mTexture, &SMViewDesc, &mSRView);
if (FAILED(hr))
{
AssertFatal(false, "GFXD3D11Cubemap::initStatic(GFXTexHandle *faces) - texcube shader resource view creation failure");
}
if (mAutoGenMips && !compressed)
D3D11DEVICECONTEXT->GenerateMips(mSRView);
}
void GFXD3D11Cubemap::initStatic(DDSFile *dds)
{
AssertFatal(dds, "GFXD3D11Cubemap::initStatic - Got null DDS file!");
AssertFatal(dds->isCubemap(), "GFXD3D11Cubemap::initStatic - Got non-cubemap DDS file!");
AssertFatal(dds->mSurfaces.size() == 6, "GFXD3D11Cubemap::initStatic - DDS has less than 6 surfaces!");
// NOTE - check tex sizes on all faces - they MUST be all same size
mTexSize = dds->getWidth();
mFaceFormat = dds->getFormat();
U32 levels = dds->getMipLevels();
D3D11_TEXTURE2D_DESC desc;
desc.Width = mTexSize;
desc.Height = mTexSize;
desc.MipLevels = levels;
desc.ArraySize = 6;
desc.Format = GFXD3D11TextureFormat[mFaceFormat];
desc.SampleDesc.Count = 1;
desc.SampleDesc.Quality = 0;
desc.Usage = D3D11_USAGE_IMMUTABLE;
desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
desc.MiscFlags = D3D11_RESOURCE_MISC_TEXTURECUBE | D3D11_RESOURCE_MISC_GENERATE_MIPS;
D3D11_SUBRESOURCE_DATA* pData = new D3D11_SUBRESOURCE_DATA[6 + levels];
for (U32 i = 0; i<CubeFaces; i++)
{
if (!dds->mSurfaces[i])
continue;
for(U32 j = 0; j < levels; j++)
{
pData[i + j].pSysMem = dds->mSurfaces[i]->mMips[j];
pData[i + j].SysMemPitch = dds->getSurfacePitch(j);
pData[i + j].SysMemSlicePitch = dds->getSurfaceSize(j);
}
}
HRESULT hr = D3D11DEVICE->CreateTexture2D(&desc, pData, &mTexture);
delete [] pData;
D3D11_SHADER_RESOURCE_VIEW_DESC SMViewDesc;
SMViewDesc.Format = GFXD3D11TextureFormat[mFaceFormat];
SMViewDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURECUBE;
SMViewDesc.TextureCube.MipLevels = levels;
SMViewDesc.TextureCube.MostDetailedMip = 0;
hr = D3D11DEVICE->CreateShaderResourceView(mTexture, &SMViewDesc, &mSRView);
if(FAILED(hr))
{
AssertFatal(false, "GFXD3D11Cubemap::initStatic(DDSFile *dds) - CreateTexture2D call failure");
}
}
void GFXD3D11Cubemap::initDynamic(U32 texSize, GFXFormat faceFormat)
{
if(!mDynamic)
GFXTextureManager::addEventDelegate(this, &GFXD3D11Cubemap::_onTextureEvent);
mDynamic = true;
mAutoGenMips = true;
mTexSize = texSize;
mFaceFormat = faceFormat;
bool compressed = isCompressed(mFaceFormat);
UINT bindFlags = D3D11_BIND_SHADER_RESOURCE;
UINT miscFlags = D3D11_RESOURCE_MISC_TEXTURECUBE;
if (!compressed)
{
bindFlags |= D3D11_BIND_RENDER_TARGET;
miscFlags |= D3D11_RESOURCE_MISC_GENERATE_MIPS;
}
D3D11_TEXTURE2D_DESC desc;
desc.Width = mTexSize;
desc.Height = mTexSize;
desc.MipLevels = 0;
desc.ArraySize = 6;
desc.Format = GFXD3D11TextureFormat[mFaceFormat];
desc.SampleDesc.Count = 1;
desc.SampleDesc.Quality = 0;
desc.Usage = D3D11_USAGE_DEFAULT;
desc.BindFlags = bindFlags;
desc.CPUAccessFlags = 0;
desc.MiscFlags = miscFlags;
HRESULT hr = D3D11DEVICE->CreateTexture2D(&desc, NULL, &mTexture);
D3D11_SHADER_RESOURCE_VIEW_DESC SMViewDesc;
SMViewDesc.Format = GFXD3D11TextureFormat[mFaceFormat];
SMViewDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURECUBE;
SMViewDesc.TextureCube.MipLevels = -1;
SMViewDesc.TextureCube.MostDetailedMip = 0;
hr = D3D11DEVICE->CreateShaderResourceView(mTexture, &SMViewDesc, &mSRView);
if(FAILED(hr))
{
AssertFatal(false, "GFXD3D11Cubemap::initDynamic - CreateTexture2D call failure");
}
D3D11_RENDER_TARGET_VIEW_DESC viewDesc;
viewDesc.Format = desc.Format;
viewDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2DARRAY;
viewDesc.Texture2DArray.ArraySize = 1;
viewDesc.Texture2DArray.MipSlice = 0;
for (U32 i = 0; i < CubeFaces; i++)
{
viewDesc.Texture2DArray.FirstArraySlice = i;
hr = D3D11DEVICE->CreateRenderTargetView(mTexture, &viewDesc, &mRTView[i]);
if(FAILED(hr))
{
AssertFatal(false, "GFXD3D11Cubemap::initDynamic - CreateRenderTargetView call failure");
}
}
D3D11_TEXTURE2D_DESC depthTexDesc;
depthTexDesc.Width = mTexSize;
depthTexDesc.Height = mTexSize;
depthTexDesc.MipLevels = 1;
depthTexDesc.ArraySize = 1;
depthTexDesc.SampleDesc.Count = 1;
depthTexDesc.SampleDesc.Quality = 0;
depthTexDesc.Format = DXGI_FORMAT_D32_FLOAT;
depthTexDesc.Usage = D3D11_USAGE_DEFAULT;
depthTexDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
depthTexDesc.CPUAccessFlags = 0;
depthTexDesc.MiscFlags = 0;
ID3D11Texture2D* depthTex = 0;
hr = D3D11DEVICE->CreateTexture2D(&depthTexDesc, 0, &depthTex);
if(FAILED(hr))
{
AssertFatal(false, "GFXD3D11Cubemap::initDynamic - CreateTexture2D for depth stencil call failure");
}
// Create the depth stencil view for the entire cube
D3D11_DEPTH_STENCIL_VIEW_DESC dsvDesc;
dsvDesc.Format = depthTexDesc.Format; //The format must match the depth texture we created above
dsvDesc.Flags = 0;
dsvDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
dsvDesc.Texture2D.MipSlice = 0;
hr = D3D11DEVICE->CreateDepthStencilView(depthTex, &dsvDesc, &mDSView);
if(FAILED(hr))
{
AssertFatal(false, "GFXD3D11Cubemap::initDynamic - CreateDepthStencilView call failure");
}
SAFE_RELEASE(depthTex);
}
//-----------------------------------------------------------------------------
// Set the cubemap to the specified texture unit num
//-----------------------------------------------------------------------------
void GFXD3D11Cubemap::setToTexUnit(U32 tuNum)
{
D3D11DEVICECONTEXT->PSSetShaderResources(tuNum, 1, &mSRView);
}
void GFXD3D11Cubemap::zombify()
{
// Static cubemaps are handled by D3D
if( mDynamic )
releaseSurfaces();
}
void GFXD3D11Cubemap::resurrect()
{
// Static cubemaps are handled by D3D
if( mDynamic )
initDynamic( mTexSize, mFaceFormat );
}
ID3D11ShaderResourceView* GFXD3D11Cubemap::getSRView()
{
return mSRView;
}
ID3D11RenderTargetView* GFXD3D11Cubemap::getRTView(U32 faceIdx)
{
AssertFatal(faceIdx < CubeFaces, "GFXD3D11Cubemap::getRTView - face index out of bounds");
return mRTView[faceIdx];
}
ID3D11RenderTargetView** GFXD3D11Cubemap::getRTViewArray()
{
return mRTView;
}
ID3D11DepthStencilView* GFXD3D11Cubemap::getDSView()
{
return mDSView;
}
ID3D11Texture2D* GFXD3D11Cubemap::get2DTex()
{
return mTexture;
}

View file

@ -0,0 +1,80 @@
//-----------------------------------------------------------------------------
// Copyright (c) 2015 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#ifndef _GFXD3D11CUBEMAP_H_
#define _GFXD3D11CUBEMAP_H_
#include "gfx/D3D11/gfxD3D11Device.h"
#include "gfx/gfxCubemap.h"
#include "gfx/gfxResource.h"
#include "gfx/gfxTarget.h"
const U32 CubeFaces = 6;
class GFXD3D11Cubemap : public GFXCubemap
{
public:
virtual void initStatic( GFXTexHandle *faces );
virtual void initStatic( DDSFile *dds );
virtual void initDynamic( U32 texSize, GFXFormat faceFormat = GFXFormatR8G8B8A8 );
virtual void setToTexUnit( U32 tuNum );
virtual U32 getSize() const { return mTexSize; }
virtual GFXFormat getFormat() const { return mFaceFormat; }
GFXD3D11Cubemap();
virtual ~GFXD3D11Cubemap();
// GFXResource interface
virtual void zombify();
virtual void resurrect();
// Get functions
ID3D11ShaderResourceView* getSRView();
ID3D11RenderTargetView* getRTView(U32 faceIdx);
ID3D11RenderTargetView** getRTViewArray();
ID3D11DepthStencilView* getDSView();
ID3D11Texture2D* get2DTex();
private:
friend class GFXD3D11TextureTarget;
friend class GFXD3D11Device;
ID3D11Texture2D* mTexture;
ID3D11ShaderResourceView* mSRView; // for shader resource input
ID3D11RenderTargetView* mRTView[CubeFaces]; // for render targets, 6 faces of the cubemap
ID3D11DepthStencilView* mDSView; //render target view for depth stencil
bool mAutoGenMips;
bool mDynamic;
U32 mTexSize;
GFXFormat mFaceFormat;
void releaseSurfaces();
bool isCompressed(GFXFormat format);
/// The callback used to get texture events.
/// @see GFXTextureManager::addEventDelegate
void _onTextureEvent(GFXTexCallbackCode code);
};
#endif

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,295 @@
//-----------------------------------------------------------------------------
// Copyright (c) 2015 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#ifndef _GFXD3D11DEVICE_H_
#define _GFXD3D11DEVICE_H_
#include <d3d11.h>
#include "platform/tmm_off.h"
#include "platformWin32/platformWin32.h"
#include "gfx/D3D11/gfxD3D11Shader.h"
#include "gfx/D3D11/gfxD3D11StateBlock.h"
#include "gfx/D3D11/gfxD3D11TextureManager.h"
#include "gfx/D3D11/gfxD3D11Cubemap.h"
#include "gfx/D3D11/gfxD3D11PrimitiveBuffer.h"
#include "gfx/gfxInit.h"
#include "gfx/gfxResource.h"
#include "platform/tmm_on.h"
#define D3D11 static_cast<GFXD3D11Device*>(GFX)
#define D3D11DEVICE D3D11->getDevice()
#define D3D11DEVICECONTEXT D3D11->getDeviceContext()
class PlatformWindow;
class GFXD3D11ShaderConstBuffer;
//------------------------------------------------------------------------------
class GFXD3D11Device : public GFXDevice
{
friend class GFXResource;
friend class GFXD3D11PrimitiveBuffer;
friend class GFXD3D11VertexBuffer;
friend class GFXD3D11TextureObject;
friend class GFXD3D11TextureTarget;
friend class GFXD3D11WindowTarget;
virtual GFXFormat selectSupportedFormat(GFXTextureProfile *profile,
const Vector<GFXFormat> &formats, bool texture, bool mustblend, bool mustfilter);
virtual void enumerateVideoModes();
virtual GFXWindowTarget *allocWindowTarget(PlatformWindow *window);
virtual GFXTextureTarget *allocRenderToTextureTarget();
virtual void enterDebugEvent(ColorI color, const char *name){};
virtual void leaveDebugEvent(){};
virtual void setDebugMarker(ColorI color, const char *name){};
protected:
class D3D11VertexDecl : public GFXVertexDecl
{
public:
virtual ~D3D11VertexDecl()
{
SAFE_RELEASE( decl );
}
ID3D11InputLayout *decl;
};
virtual void initStates() { };
static GFXAdapter::CreateDeviceInstanceDelegate mCreateDeviceInstance;
MatrixF mTempMatrix; ///< Temporary matrix, no assurances on value at all
RectI mClipRect;
typedef StrongRefPtr<GFXD3D11VertexBuffer> RPGDVB;
Vector<RPGDVB> mVolatileVBList;
/// Used to lookup a vertex declaration for the vertex format.
/// @see allocVertexDecl
typedef Map<String,D3D11VertexDecl*> VertexDeclMap;
VertexDeclMap mVertexDecls;
ID3D11RenderTargetView* mDeviceBackBufferView;
ID3D11DepthStencilView* mDeviceDepthStencilView;
ID3D11Texture2D *mDeviceBackbuffer;
ID3D11Texture2D *mDeviceDepthStencil;
/// The stream 0 vertex buffer used for volatile VB offseting.
GFXD3D11VertexBuffer *mVolatileVB;
//-----------------------------------------------------------------------
StrongRefPtr<GFXD3D11PrimitiveBuffer> mDynamicPB;
GFXD3D11PrimitiveBuffer *mCurrentPB;
ID3D11VertexShader *mLastVertShader;
ID3D11PixelShader *mLastPixShader;
S32 mCreateFenceType;
IDXGISwapChain *mSwapChain;
ID3D11Device* mD3DDevice;
ID3D11DeviceContext* mD3DDeviceContext;
GFXShader* mCurrentShader;
GFXShaderRef mGenericShader[GS_COUNT];
GFXShaderConstBufferRef mGenericShaderBuffer[GS_COUNT];
GFXShaderConstHandle *mModelViewProjSC[GS_COUNT];
U32 mAdapterIndex;
F32 mPixVersion;
bool mDebugLayers;
DXGI_SAMPLE_DESC mMultisampleDesc;
bool mOcclusionQuerySupported;
U32 mDrawInstancesCount;
/// To manage creating and re-creating of these when device is aquired
void reacquireDefaultPoolResources();
/// To release all resources we control from D3DPOOL_DEFAULT
void releaseDefaultPoolResources();
virtual GFXD3D11VertexBuffer* findVBPool( const GFXVertexFormat *vertexFormat, U32 numVertsNeeded );
virtual GFXD3D11VertexBuffer* createVBPool( const GFXVertexFormat *vertexFormat, U32 vertSize );
IDXGISwapChain* getSwapChain();
// State overrides
// {
///
virtual void setTextureInternal(U32 textureUnit, const GFXTextureObject* texture);
/// Called by GFXDevice to create a device specific stateblock
virtual GFXStateBlockRef createStateBlockInternal(const GFXStateBlockDesc& desc);
/// Called by GFXDevice to actually set a stateblock.
virtual void setStateBlockInternal(GFXStateBlock* block, bool force);
/// Track the last const buffer we've used. Used to notify new constant buffers that
/// they should send all of their constants up
StrongRefPtr<GFXD3D11ShaderConstBuffer> mCurrentConstBuffer;
/// Called by base GFXDevice to actually set a const buffer
virtual void setShaderConstBufferInternal(GFXShaderConstBuffer* buffer);
virtual void setMatrix( GFXMatrixType /*mtype*/, const MatrixF &/*mat*/ ) { };
virtual void setLightInternal(U32 /*lightStage*/, const GFXLightInfo /*light*/, bool /*lightEnable*/) { };
virtual void setLightMaterialInternal(const GFXLightMaterial /*mat*/) { };
virtual void setGlobalAmbientInternal(ColorF /*color*/) { };
// }
// Index buffer management
// {
virtual void _setPrimitiveBuffer( GFXPrimitiveBuffer *buffer );
virtual void drawIndexedPrimitive( GFXPrimitiveType primType,
U32 startVertex,
U32 minIndex,
U32 numVerts,
U32 startIndex,
U32 primitiveCount );
// }
virtual GFXShader* createShader();
/// Device helper function
virtual DXGI_SWAP_CHAIN_DESC setupPresentParams( const GFXVideoMode &mode, const HWND &hwnd );
String _createTempShaderInternal(const GFXVertexFormat *vertexFormat);
// Supress any debug layer messages we don't want to see
void _suppressDebugMessages();
public:
static GFXDevice *createInstance( U32 adapterIndex );
static void enumerateAdapters( Vector<GFXAdapter*> &adapterList );
GFXTextureObject* createRenderSurface( U32 width, U32 height, GFXFormat format, U32 mipLevel );
ID3D11DepthStencilView* getDepthStencilView() { return mDeviceDepthStencilView; }
ID3D11RenderTargetView* getRenderTargetView() { return mDeviceBackBufferView; }
ID3D11Texture2D* getBackBufferTexture() { return mDeviceBackbuffer; }
/// Constructor
/// @param d3d Direct3D object to instantiate this device with
/// @param index Adapter index since D3D can use multiple graphics adapters
GFXD3D11Device( U32 index );
virtual ~GFXD3D11Device();
// Activate/deactivate
// {
virtual void init( const GFXVideoMode &mode, PlatformWindow *window = NULL );
virtual void preDestroy() { GFXDevice::preDestroy(); if(mTextureManager) mTextureManager->kill(); }
GFXAdapterType getAdapterType(){ return Direct3D11; }
U32 getAdaterIndex() const { return mAdapterIndex; }
virtual GFXCubemap *createCubemap();
virtual F32 getPixelShaderVersion() const { return mPixVersion; }
virtual void setPixelShaderVersion( F32 version ){ mPixVersion = version;}
virtual void setShader(GFXShader *shader, bool force = false);
virtual U32 getNumSamplers() const { return 16; }
virtual U32 getNumRenderTargets() const { return 8; }
// }
// Misc rendering control
// {
virtual void clear( U32 flags, ColorI color, F32 z, U32 stencil );
virtual bool beginSceneInternal();
virtual void endSceneInternal();
virtual void setClipRect( const RectI &rect );
virtual const RectI& getClipRect() const { return mClipRect; }
// }
/// @name Render Targets
/// @{
virtual void _updateRenderTargets();
/// @}
// Vertex/Index buffer management
// {
virtual GFXVertexBuffer* allocVertexBuffer( U32 numVerts,
const GFXVertexFormat *vertexFormat,
U32 vertSize,
GFXBufferType bufferType,
void* data = NULL);
virtual GFXPrimitiveBuffer *allocPrimitiveBuffer( U32 numIndices,
U32 numPrimitives,
GFXBufferType bufferType,
void* data = NULL);
virtual GFXVertexDecl* allocVertexDecl( const GFXVertexFormat *vertexFormat );
virtual void setVertexDecl( const GFXVertexDecl *decl );
virtual void setVertexStream( U32 stream, GFXVertexBuffer *buffer );
virtual void setVertexStreamFrequency( U32 stream, U32 frequency );
// }
virtual U32 getMaxDynamicVerts() { return MAX_DYNAMIC_VERTS; }
virtual U32 getMaxDynamicIndices() { return MAX_DYNAMIC_INDICES; }
inline U32 primCountToIndexCount(GFXPrimitiveType primType, U32 primitiveCount);
// Rendering
// {
virtual void drawPrimitive( GFXPrimitiveType primType, U32 vertexStart, U32 primitiveCount );
// }
ID3D11DeviceContext* getDeviceContext(){ return mD3DDeviceContext; }
ID3D11Device* getDevice(){ return mD3DDevice; }
/// Reset
void reset( DXGI_SWAP_CHAIN_DESC &d3dpp );
virtual void setupGenericShaders( GenericShaderType type = GSColor );
inline virtual F32 getFillConventionOffset() const { return 0.0f; }
virtual void doParanoidStateCheck() {};
GFXFence *createFence();
GFXOcclusionQuery* createOcclusionQuery();
// Default multisample parameters
DXGI_SAMPLE_DESC getMultisampleType() const { return mMultisampleDesc; }
};
#endif

View file

@ -0,0 +1,156 @@
//-----------------------------------------------------------------------------
// Copyright (c) 2015 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#include "gfx/D3D11/gfxD3D11Device.h"
#include "gfx/D3D11/gfxD3D11EnumTranslate.h"
#include "console/console.h"
//------------------------------------------------------------------------------
DXGI_FORMAT GFXD3D11TextureFormat[GFXFormat_COUNT];
D3D11_FILTER GFXD3D11TextureFilter[GFXTextureFilter_COUNT];
D3D11_BLEND GFXD3D11Blend[GFXBlend_COUNT];
D3D11_BLEND_OP GFXD3D11BlendOp[GFXBlendOp_COUNT];
D3D11_STENCIL_OP GFXD3D11StencilOp[GFXStencilOp_COUNT];
D3D11_COMPARISON_FUNC GFXD3D11CmpFunc[GFXCmp_COUNT];
D3D11_CULL_MODE GFXD3D11CullMode[GFXCull_COUNT];
D3D11_FILL_MODE GFXD3D11FillMode[GFXFill_COUNT];
D3D11_PRIMITIVE_TOPOLOGY GFXD3D11PrimType[GFXPT_COUNT];
D3D11_TEXTURE_ADDRESS_MODE GFXD3D11TextureAddress[GFXAddress_COUNT];
DXGI_FORMAT GFXD3D11DeclType[GFXDeclType_COUNT];
//------------------------------------------------------------------------------
void GFXD3D11EnumTranslate::init()
{
GFXD3D11TextureFormat[GFXFormatR8G8B8] = DXGI_FORMAT_B8G8R8X8_UNORM;
GFXD3D11TextureFormat[GFXFormatR8G8B8A8] = DXGI_FORMAT_B8G8R8A8_UNORM;
GFXD3D11TextureFormat[GFXFormatR8G8B8X8] = DXGI_FORMAT_B8G8R8X8_UNORM;
GFXD3D11TextureFormat[GFXFormatB8G8R8A8] = DXGI_FORMAT_B8G8R8A8_UNORM;
GFXD3D11TextureFormat[GFXFormatR5G6B5] = DXGI_FORMAT_B5G6R5_UNORM;
GFXD3D11TextureFormat[GFXFormatR5G5B5A1] = DXGI_FORMAT_B5G5R5A1_UNORM;
GFXD3D11TextureFormat[GFXFormatR5G5B5X1] = DXGI_FORMAT_UNKNOWN;
GFXD3D11TextureFormat[GFXFormatR32F] = DXGI_FORMAT_R32_FLOAT;
GFXD3D11TextureFormat[GFXFormatA4L4] = DXGI_FORMAT_UNKNOWN;
GFXD3D11TextureFormat[GFXFormatA8L8] = DXGI_FORMAT_R8G8_UNORM;
GFXD3D11TextureFormat[GFXFormatA8] = DXGI_FORMAT_A8_UNORM;
GFXD3D11TextureFormat[GFXFormatL8] = DXGI_FORMAT_R8_UNORM;
GFXD3D11TextureFormat[GFXFormatDXT1] = DXGI_FORMAT_BC1_UNORM;
GFXD3D11TextureFormat[GFXFormatDXT2] = DXGI_FORMAT_BC1_UNORM;
GFXD3D11TextureFormat[GFXFormatDXT3] = DXGI_FORMAT_BC2_UNORM;
GFXD3D11TextureFormat[GFXFormatDXT4] = DXGI_FORMAT_BC2_UNORM;
GFXD3D11TextureFormat[GFXFormatDXT5] = DXGI_FORMAT_BC3_UNORM;
GFXD3D11TextureFormat[GFXFormatR32G32B32A32F] = DXGI_FORMAT_R32G32B32A32_FLOAT;
GFXD3D11TextureFormat[GFXFormatR16G16B16A16F] = DXGI_FORMAT_R16G16B16A16_FLOAT;
GFXD3D11TextureFormat[GFXFormatL16] = DXGI_FORMAT_R16_UNORM;
GFXD3D11TextureFormat[GFXFormatR16G16B16A16] = DXGI_FORMAT_R16G16B16A16_UNORM;
GFXD3D11TextureFormat[GFXFormatR16G16] = DXGI_FORMAT_R16G16_UNORM;
GFXD3D11TextureFormat[GFXFormatR16F] = DXGI_FORMAT_R16_FLOAT;
GFXD3D11TextureFormat[GFXFormatR16G16F] = DXGI_FORMAT_R16G16_FLOAT;
GFXD3D11TextureFormat[GFXFormatR10G10B10A2] = DXGI_FORMAT_R10G10B10A2_UNORM;
GFXD3D11TextureFormat[GFXFormatD32] = DXGI_FORMAT_UNKNOWN;
GFXD3D11TextureFormat[GFXFormatD24X8] = DXGI_FORMAT_UNKNOWN;
GFXD3D11TextureFormat[GFXFormatD24S8] = DXGI_FORMAT_D24_UNORM_S8_UINT;
GFXD3D11TextureFormat[GFXFormatD24FS8] = DXGI_FORMAT_UNKNOWN;
GFXD3D11TextureFormat[GFXFormatD16] = DXGI_FORMAT_D16_UNORM;
GFXD3D11TextureFormat[GFXFormatR8G8B8A8_SRGB] = DXGI_FORMAT_B8G8R8A8_UNORM_SRGB;
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
GFXD3D11TextureFilter[GFXTextureFilterNone] = D3D11_FILTER_MIN_MAG_MIP_POINT;
GFXD3D11TextureFilter[GFXTextureFilterPoint] = D3D11_FILTER_MIN_MAG_MIP_POINT;
GFXD3D11TextureFilter[GFXTextureFilterLinear] = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
GFXD3D11TextureFilter[GFXTextureFilterAnisotropic] = D3D11_FILTER_ANISOTROPIC;
GFXD3D11TextureFilter[GFXTextureFilterPyramidalQuad] = D3D11_FILTER_ANISOTROPIC;
GFXD3D11TextureFilter[GFXTextureFilterGaussianQuad] = D3D11_FILTER_ANISOTROPIC;
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
GFXD3D11Blend[GFXBlendZero] = D3D11_BLEND_ZERO;
GFXD3D11Blend[GFXBlendOne] = D3D11_BLEND_ONE;
GFXD3D11Blend[GFXBlendSrcColor] = D3D11_BLEND_SRC_COLOR;
GFXD3D11Blend[GFXBlendInvSrcColor] = D3D11_BLEND_INV_SRC_COLOR;
GFXD3D11Blend[GFXBlendSrcAlpha] = D3D11_BLEND_SRC_ALPHA;
GFXD3D11Blend[GFXBlendInvSrcAlpha] = D3D11_BLEND_INV_SRC_ALPHA;
GFXD3D11Blend[GFXBlendDestAlpha] = D3D11_BLEND_DEST_ALPHA;
GFXD3D11Blend[GFXBlendInvDestAlpha] = D3D11_BLEND_INV_DEST_ALPHA;
GFXD3D11Blend[GFXBlendDestColor] = D3D11_BLEND_DEST_COLOR;
GFXD3D11Blend[GFXBlendInvDestColor] = D3D11_BLEND_INV_DEST_COLOR;
GFXD3D11Blend[GFXBlendSrcAlphaSat] = D3D11_BLEND_SRC_ALPHA_SAT;
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
GFXD3D11BlendOp[GFXBlendOpAdd] = D3D11_BLEND_OP_ADD;
GFXD3D11BlendOp[GFXBlendOpSubtract] = D3D11_BLEND_OP_SUBTRACT;
GFXD3D11BlendOp[GFXBlendOpRevSubtract] = D3D11_BLEND_OP_REV_SUBTRACT;
GFXD3D11BlendOp[GFXBlendOpMin] = D3D11_BLEND_OP_MIN;
GFXD3D11BlendOp[GFXBlendOpMax] = D3D11_BLEND_OP_MAX;
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
GFXD3D11StencilOp[GFXStencilOpKeep] = D3D11_STENCIL_OP_KEEP;
GFXD3D11StencilOp[GFXStencilOpZero] = D3D11_STENCIL_OP_ZERO;
GFXD3D11StencilOp[GFXStencilOpReplace] = D3D11_STENCIL_OP_REPLACE;
GFXD3D11StencilOp[GFXStencilOpIncrSat] = D3D11_STENCIL_OP_INCR_SAT;
GFXD3D11StencilOp[GFXStencilOpDecrSat] = D3D11_STENCIL_OP_DECR_SAT;
GFXD3D11StencilOp[GFXStencilOpInvert] = D3D11_STENCIL_OP_INVERT;
GFXD3D11StencilOp[GFXStencilOpIncr] = D3D11_STENCIL_OP_INCR;
GFXD3D11StencilOp[GFXStencilOpDecr] = D3D11_STENCIL_OP_DECR;
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
GFXD3D11CmpFunc[GFXCmpNever] = D3D11_COMPARISON_NEVER;
GFXD3D11CmpFunc[GFXCmpLess] = D3D11_COMPARISON_LESS;
GFXD3D11CmpFunc[GFXCmpEqual] = D3D11_COMPARISON_EQUAL;
GFXD3D11CmpFunc[GFXCmpLessEqual] = D3D11_COMPARISON_LESS_EQUAL;
GFXD3D11CmpFunc[GFXCmpGreater] = D3D11_COMPARISON_GREATER;
GFXD3D11CmpFunc[GFXCmpNotEqual] = D3D11_COMPARISON_NOT_EQUAL;
GFXD3D11CmpFunc[GFXCmpGreaterEqual] = D3D11_COMPARISON_GREATER_EQUAL;
GFXD3D11CmpFunc[GFXCmpAlways] = D3D11_COMPARISON_ALWAYS;
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
GFXD3D11CullMode[GFXCullNone] = D3D11_CULL_NONE;
GFXD3D11CullMode[GFXCullCW] = D3D11_CULL_FRONT;
GFXD3D11CullMode[GFXCullCCW] = D3D11_CULL_BACK;
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
GFXD3D11FillMode[GFXFillPoint] = D3D11_FILL_SOLID;
GFXD3D11FillMode[GFXFillWireframe] = D3D11_FILL_WIREFRAME;
GFXD3D11FillMode[GFXFillSolid] = D3D11_FILL_SOLID;
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
GFXD3D11PrimType[GFXPointList] = D3D_PRIMITIVE_TOPOLOGY_POINTLIST;
GFXD3D11PrimType[GFXLineList] = D3D_PRIMITIVE_TOPOLOGY_LINELIST;
GFXD3D11PrimType[GFXLineStrip] = D3D_PRIMITIVE_TOPOLOGY_LINESTRIP;
GFXD3D11PrimType[GFXTriangleList] = D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST;
GFXD3D11PrimType[GFXTriangleStrip] = D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP;
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
GFXD3D11TextureAddress[GFXAddressWrap] = D3D11_TEXTURE_ADDRESS_WRAP;
GFXD3D11TextureAddress[GFXAddressMirror] = D3D11_TEXTURE_ADDRESS_MIRROR;
GFXD3D11TextureAddress[GFXAddressClamp] = D3D11_TEXTURE_ADDRESS_CLAMP;
GFXD3D11TextureAddress[GFXAddressBorder] = D3D11_TEXTURE_ADDRESS_BORDER;
GFXD3D11TextureAddress[GFXAddressMirrorOnce] = D3D11_TEXTURE_ADDRESS_MIRROR_ONCE;
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
GFXD3D11DeclType[GFXDeclType_Float] = DXGI_FORMAT_R32_FLOAT;
GFXD3D11DeclType[GFXDeclType_Float2] = DXGI_FORMAT_R32G32_FLOAT;
GFXD3D11DeclType[GFXDeclType_Float3] = DXGI_FORMAT_R32G32B32_FLOAT;
GFXD3D11DeclType[GFXDeclType_Float4] = DXGI_FORMAT_R32G32B32A32_FLOAT;
GFXD3D11DeclType[GFXDeclType_Color] = DXGI_FORMAT_B8G8R8A8_UNORM; // DXGI_FORMAT_R8G8B8A8_UNORM;
}

View file

@ -0,0 +1,51 @@
//-----------------------------------------------------------------------------
// Copyright (c) 2015 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#ifndef _GFXD3D11ENUMTRANSLATE_H_
#define _GFXD3D11ENUMTRANSLATE_H_
#include "gfx/D3D11/gfxD3D11Shader.h"
#include "gfx/gfxEnums.h"
//------------------------------------------------------------------------------
namespace GFXD3D11EnumTranslate
{
void init();
};
//------------------------------------------------------------------------------
extern DXGI_FORMAT GFXD3D11TextureFormat[GFXFormat_COUNT];
extern D3D11_FILTER GFXD3D11TextureFilter[GFXTextureFilter_COUNT];
extern D3D11_BLEND GFXD3D11Blend[GFXBlend_COUNT];
extern D3D11_BLEND_OP GFXD3D11BlendOp[GFXBlendOp_COUNT];
extern D3D11_STENCIL_OP GFXD3D11StencilOp[GFXStencilOp_COUNT];
extern D3D11_COMPARISON_FUNC GFXD3D11CmpFunc[GFXCmp_COUNT];
extern D3D11_CULL_MODE GFXD3D11CullMode[GFXCull_COUNT];
extern D3D11_FILL_MODE GFXD3D11FillMode[GFXFill_COUNT];
extern D3D11_PRIMITIVE_TOPOLOGY GFXD3D11PrimType[GFXPT_COUNT];
extern D3D11_TEXTURE_ADDRESS_MODE GFXD3D11TextureAddress[GFXAddress_COUNT];
extern DXGI_FORMAT GFXD3D11DeclType[GFXDeclType_COUNT];
#endif

View file

@ -0,0 +1,177 @@
//-----------------------------------------------------------------------------
// Copyright (c) 2015 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#include "gfx/D3D11/gfxD3D11Device.h"
#include "gfx/D3D11/gfxD3D11OcclusionQuery.h"
#include "gui/3d/guiTSControl.h"
#ifdef TORQUE_GATHER_METRICS
// For TickMs define
#include "T3D/gameBase/processList.h"
#endif
GFXD3D11OcclusionQuery::GFXD3D11OcclusionQuery(GFXDevice *device)
: GFXOcclusionQuery(device),
mQuery(NULL)
{
#ifdef TORQUE_GATHER_METRICS
mTimer = PlatformTimer::create();
mTimer->getElapsedMs();
mTimeSinceEnd = 0;
mBeginFrame = 0;
#endif
}
GFXD3D11OcclusionQuery::~GFXD3D11OcclusionQuery()
{
SAFE_RELEASE(mQuery);
#ifdef TORQUE_GATHER_METRICS
SAFE_DELETE(mTimer);
#endif
}
bool GFXD3D11OcclusionQuery::begin()
{
if(GFXDevice::getDisableOcclusionQuery())
return true;
if (mQuery == NULL)
{
D3D11_QUERY_DESC queryDesc;
queryDesc.Query = D3D11_QUERY_OCCLUSION;
queryDesc.MiscFlags = 0;
HRESULT hRes = D3D11DEVICE->CreateQuery(&queryDesc, &mQuery);
if(FAILED(hRes))
{
AssertFatal(false, "GFXD3D11OcclusionQuery::begin - Hardware does not support D3D11 Occlusion-Queries, this should be caught before this type is created");
}
AssertISV(hRes != E_OUTOFMEMORY, "GFXD3D11OcclusionQuery::begin - Out of memory");
}
// Add a begin marker to the command buffer queue.
D3D11DEVICECONTEXT->Begin(mQuery);
#ifdef TORQUE_GATHER_METRICS
mBeginFrame = GuiTSCtrl::getFrameCount();
#endif
return true;
}
void GFXD3D11OcclusionQuery::end()
{
if (GFXDevice::getDisableOcclusionQuery())
return;
// Add an end marker to the command buffer queue.
D3D11DEVICECONTEXT->End(mQuery);
#ifdef TORQUE_GATHER_METRICS
AssertFatal( mBeginFrame == GuiTSCtrl::getFrameCount(), "GFXD3D11OcclusionQuery::end - ended query on different frame than begin!" );
mTimer->getElapsedMs();
mTimer->reset();
#endif
}
GFXD3D11OcclusionQuery::OcclusionQueryStatus GFXD3D11OcclusionQuery::getStatus(bool block, U32 *data)
{
// If this ever shows up near the top of a profile then your system is
// GPU bound or you are calling getStatus too soon after submitting it.
//
// To test if you are GPU bound resize your window very small and see if
// this profile no longer appears at the top.
//
// To test if you are calling getStatus to soon after submitting it,
// check the value of mTimeSinceEnd in a debug build. If it is < half the length
// of time to render an individual frame you could have problems.
PROFILE_SCOPE(GFXD3D11OcclusionQuery_getStatus);
if ( GFXDevice::getDisableOcclusionQuery() )
return NotOccluded;
if ( mQuery == NULL )
return Unset;
#ifdef TORQUE_GATHER_METRICS
//AssertFatal( mBeginFrame < GuiTSCtrl::getFrameCount(), "GFXD3D11OcclusionQuery::getStatus - called on the same frame as begin!" );
//U32 mTimeSinceEnd = mTimer->getElapsedMs();
//AssertFatal( mTimeSinceEnd >= 5, "GFXD3DOcculsionQuery::getStatus - less than TickMs since called ::end!" );
#endif
HRESULT hRes;
U64 dwOccluded = 0;
if ( block )
{
while ((hRes = D3D11DEVICECONTEXT->GetData(mQuery, &dwOccluded, sizeof(U64), 0)) == S_FALSE);
}
else
{
hRes = D3D11DEVICECONTEXT->GetData(mQuery, &dwOccluded, sizeof(U64), 0);
}
if (hRes == S_OK)
{
if (data != NULL)
*data = (U32)dwOccluded;
return dwOccluded > 0 ? NotOccluded : Occluded;
}
if (hRes == S_FALSE)
return Waiting;
return Error;
}
void GFXD3D11OcclusionQuery::zombify()
{
SAFE_RELEASE( mQuery );
}
void GFXD3D11OcclusionQuery::resurrect()
{
// Recreate the query
if( mQuery == NULL )
{
D3D11_QUERY_DESC queryDesc;
queryDesc.Query = D3D11_QUERY_OCCLUSION;
queryDesc.MiscFlags = 0;
HRESULT hRes = D3D11DEVICE->CreateQuery(&queryDesc, &mQuery);
AssertISV( hRes != E_OUTOFMEMORY, "GFXD3D9QueryFence::resurrect - Out of memory" );
}
}
const String GFXD3D11OcclusionQuery::describeSelf() const
{
// We've got nothing
return String();
}

View file

@ -0,0 +1,58 @@
//-----------------------------------------------------------------------------
// Copyright (c) 2015 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#ifndef _GFX_D3D11_OCCLUSIONQUERY_H_
#define _GFX_D3D11_OCCLUSIONQUERY_H_
#include "gfx/D3D11/gfxD3D11Device.h"
#include "gfx/gfxOcclusionQuery.h"
#ifdef TORQUE_GATHER_METRICS
#include "platform/platformTimer.h"
#endif
class GFXD3D11OcclusionQuery : public GFXOcclusionQuery
{
private:
mutable ID3D11Query *mQuery;
#ifdef TORQUE_GATHER_METRICS
U32 mBeginFrame;
U32 mTimeSinceEnd;
PlatformTimer *mTimer;
#endif
public:
GFXD3D11OcclusionQuery(GFXDevice *device);
virtual ~GFXD3D11OcclusionQuery();
virtual bool begin();
virtual void end();
virtual OcclusionQueryStatus getStatus(bool block, U32 *data = NULL);
// GFXResource
virtual void zombify();
virtual void resurrect();
virtual const String describeSelf() const;
};
#endif

View file

@ -0,0 +1,222 @@
//-----------------------------------------------------------------------------
// Copyright (c) 2015 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#include "gfx/D3D11/gfxD3D11Device.h"
#include "gfx/D3D11/gfxD3D11EnumTranslate.h"
#include "gfx/D3D11/gfxD3D11PrimitiveBuffer.h"
#include "core/util/safeRelease.h"
void GFXD3D11PrimitiveBuffer::prepare()
{
D3D11->_setPrimitiveBuffer(this);
}
void GFXD3D11PrimitiveBuffer::lock(U32 indexStart, U32 indexEnd, void **indexPtr)
{
AssertFatal(!mLocked, "GFXD3D11PrimitiveBuffer::lock - Can't lock a primitive buffer more than once!");
mLocked = true;
D3D11_MAP flags = D3D11_MAP_WRITE_DISCARD;
switch(mBufferType)
{
case GFXBufferTypeImmutable:
case GFXBufferTypeStatic:
case GFXBufferTypeDynamic:
flags = D3D11_MAP_WRITE_DISCARD;
break;
case GFXBufferTypeVolatile:
// Get our range now...
AssertFatal(indexStart == 0, "Cannot get a subrange on a volatile buffer.");
AssertFatal(indexEnd < MAX_DYNAMIC_INDICES, "Cannot get more than MAX_DYNAMIC_INDICES in a volatile buffer. Up the constant!");
// Get the primtive buffer
mVolatileBuffer = D3D11->mDynamicPB;
AssertFatal( mVolatileBuffer, "GFXD3D11PrimitiveBuffer::lock - No dynamic primitive buffer was available!");
// We created the pool when we requested this volatile buffer, so assume it exists...
if(mVolatileBuffer->mIndexCount + indexEnd > MAX_DYNAMIC_INDICES)
{
flags = D3D11_MAP_WRITE_DISCARD;
mVolatileStart = indexStart = 0;
indexEnd = indexEnd;
}
else
{
flags = D3D11_MAP_WRITE_NO_OVERWRITE;
mVolatileStart = indexStart = mVolatileBuffer->mIndexCount;
indexEnd += mVolatileBuffer->mIndexCount;
}
mVolatileBuffer->mIndexCount = indexEnd + 1;
ib = mVolatileBuffer->ib;
break;
}
mIndexStart = indexStart;
mIndexEnd = indexEnd;
if (mBufferType == GFXBufferTypeStatic || mBufferType == GFXBufferTypeImmutable)
{
U32 sizeToLock = (indexEnd - indexStart) * sizeof(U16);
*indexPtr = new U8[sizeToLock];
mLockedBuffer = *indexPtr;
}
else
{
D3D11_MAPPED_SUBRESOURCE pIndexData;
ZeroMemory(&pIndexData, sizeof(D3D11_MAPPED_SUBRESOURCE));
HRESULT hr = D3D11DEVICECONTEXT->Map(ib, 0, flags, 0, &pIndexData);
if(FAILED(hr))
{
AssertFatal(false, "GFXD3D11PrimitiveBuffer::lock - Could not lock primitive buffer.");
}
*indexPtr = (U8*)pIndexData.pData + (indexStart * sizeof(U16)) ;
}
#ifdef TORQUE_DEBUG
// Allocate a debug buffer large enough for the lock
// plus space for over and under run guard strings.
mLockedSize = (indexEnd - indexStart) * sizeof(U16);
const U32 guardSize = sizeof( _PBGuardString );
mDebugGuardBuffer = new U8[mLockedSize+(guardSize*2)];
// Setup the guard strings.
dMemcpy( mDebugGuardBuffer, _PBGuardString, guardSize );
dMemcpy( mDebugGuardBuffer + mLockedSize + guardSize, _PBGuardString, guardSize );
// Store the real lock pointer and return our debug pointer.
mLockedBuffer = *indexPtr;
*indexPtr = (U16*)( mDebugGuardBuffer + guardSize );
#endif // TORQUE_DEBUG
}
void GFXD3D11PrimitiveBuffer::unlock()
{
#ifdef TORQUE_DEBUG
if ( mDebugGuardBuffer )
{
const U32 guardSize = sizeof( _PBGuardString );
// First check the guard areas for overwrites.
AssertFatal( dMemcmp( mDebugGuardBuffer, _PBGuardString, guardSize ) == 0,
"GFXD3D11PrimitiveBuffer::unlock - Caught lock memory underrun!" );
AssertFatal( dMemcmp( mDebugGuardBuffer + mLockedSize + guardSize, _PBGuardString, guardSize ) == 0,
"GFXD3D11PrimitiveBuffer::unlock - Caught lock memory overrun!" );
// Copy the debug content down to the real PB.
dMemcpy( mLockedBuffer, mDebugGuardBuffer + guardSize, mLockedSize );
// Cleanup.
delete [] mDebugGuardBuffer;
mDebugGuardBuffer = NULL;
//mLockedBuffer = NULL;
mLockedSize = 0;
}
#endif // TORQUE_DEBUG
const U32 totalSize = this->mIndexCount * sizeof(U16);
if (mBufferType == GFXBufferTypeStatic || mBufferType == GFXBufferTypeImmutable)
{
//set up the update region of the buffer
D3D11_BOX box;
box.back = 1;
box.front = 0;
box.top = 0;
box.bottom =1;
box.left = mIndexStart *sizeof(U16);
box.right = mIndexEnd * sizeof(U16);
//update the real ib buffer
D3D11DEVICECONTEXT->UpdateSubresource(ib, 0, &box,mLockedBuffer,totalSize, 0);
//clean up the old buffer
delete[] mLockedBuffer;
mLockedBuffer = NULL;
}
else
{
D3D11DEVICECONTEXT->Unmap(ib,0);
}
mLocked = false;
mIsFirstLock = false;
mVolatileBuffer = NULL;
}
GFXD3D11PrimitiveBuffer::~GFXD3D11PrimitiveBuffer()
{
if( mBufferType != GFXBufferTypeVolatile )
{
SAFE_RELEASE(ib);
}
}
void GFXD3D11PrimitiveBuffer::zombify()
{
if (mBufferType == GFXBufferTypeStatic || mBufferType == GFXBufferTypeImmutable)
return;
AssertFatal(!mLocked, "GFXD3D11PrimitiveBuffer::zombify - Cannot zombify a locked buffer!");
if (mBufferType == GFXBufferTypeVolatile)
{
// We must null the volatile buffer else we're holding
// a dead pointer which can be set on the device.
ib = NULL;
return;
}
// Dynamic buffers get released.
SAFE_RELEASE(ib);
}
void GFXD3D11PrimitiveBuffer::resurrect()
{
if ( mBufferType != GFXBufferTypeDynamic )
return;
D3D11_BUFFER_DESC desc;
desc.ByteWidth = sizeof(U16) * mIndexCount;
desc.Usage = D3D11_USAGE_DYNAMIC;
desc.BindFlags = D3D11_BIND_INDEX_BUFFER;
desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
desc.MiscFlags = 0;
desc.StructureByteStride = 0;
HRESULT hr = D3D11DEVICE->CreateBuffer(&desc, NULL, &ib);
if(FAILED(hr))
{
AssertFatal(false, "GFXD3D11PrimitiveBuffer::resurrect - Failed to allocate an index buffer.");
}
}

View file

@ -0,0 +1,83 @@
//-----------------------------------------------------------------------------
// Copyright (c) 2015 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#ifndef _GFXD3D11PRIMITIVEBUFFER_H_
#define _GFXD3D11PRIMITIVEBUFFER_H_
#include "gfx/gfxPrimitiveBuffer.h"
class GFXD3D11PrimitiveBuffer : public GFXPrimitiveBuffer
{
public:
ID3D11Buffer *ib;
StrongRefPtr<GFXD3D11PrimitiveBuffer> mVolatileBuffer;
U32 mVolatileStart;
U32 mIndexStart;
U32 mIndexEnd;
#ifdef TORQUE_DEBUG
#define _PBGuardString "GFX_PRIMTIVE_BUFFER_GUARD_STRING"
U8 *mDebugGuardBuffer;
U32 mLockedSize;
#endif TORQUE_DEBUG
void *mLockedBuffer;
bool mLocked;
bool mIsFirstLock;
GFXD3D11PrimitiveBuffer( GFXDevice *device,
U32 indexCount,
U32 primitiveCount,
GFXBufferType bufferType );
virtual ~GFXD3D11PrimitiveBuffer();
virtual void lock(U32 indexStart, U32 indexEnd, void **indexPtr);
virtual void unlock();
virtual void prepare();
// GFXResource interface
virtual void zombify();
virtual void resurrect();
};
inline GFXD3D11PrimitiveBuffer::GFXD3D11PrimitiveBuffer( GFXDevice *device,
U32 indexCount,
U32 primitiveCount,
GFXBufferType bufferType )
: GFXPrimitiveBuffer( device, indexCount, primitiveCount, bufferType )
{
mVolatileStart = 0;
ib = NULL;
mIsFirstLock = true;
mLocked = false;
#ifdef TORQUE_DEBUG
mDebugGuardBuffer = NULL;
mLockedBuffer = NULL;
mLockedSize = 0;
mIndexStart = 0;
mIndexEnd = 0;
#endif
}
#endif

View file

@ -0,0 +1,110 @@
//-----------------------------------------------------------------------------
// Copyright (c) 2015 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#include "gfx/D3D11/gfxD3D11Device.h"
#include "gfx/D3D11/gfxD3D11QueryFence.h"
GFXD3D11QueryFence::~GFXD3D11QueryFence()
{
SAFE_RELEASE(mQuery);
}
void GFXD3D11QueryFence::issue()
{
PROFILE_START(GFXD3D11QueryFence_issue);
// Create the query if we need to
if(mQuery == NULL)
{
D3D11_QUERY_DESC QueryDesc;
QueryDesc.Query = D3D11_QUERY_EVENT;
QueryDesc.MiscFlags = 0;
HRESULT hRes = D3D11DEVICE->CreateQuery(&QueryDesc, &mQuery);
if(FAILED(hRes))
{
AssertFatal(false, "Hardware does not support D3D11 Queries, this should be caught before this fence type is created" );
}
AssertISV(hRes != E_OUTOFMEMORY, "Out of memory");
}
// Issue the query
D3D11DEVICECONTEXT->End(mQuery);
PROFILE_END();
}
GFXFence::FenceStatus GFXD3D11QueryFence::getStatus() const
{
if(mQuery == NULL)
return GFXFence::Unset;
HRESULT hRes = D3D11DEVICECONTEXT->GetData(mQuery, NULL, 0, 0);
return (hRes == S_OK ? GFXFence::Processed : GFXFence::Pending);
}
void GFXD3D11QueryFence::block()
{
PROFILE_SCOPE(GFXD3D11QueryFence_block);
// Calling block() before issue() is valid, catch this case
if( mQuery == NULL )
return;
HRESULT hRes;
while((hRes = D3D11DEVICECONTEXT->GetData(mQuery, NULL, 0, 0)) == S_FALSE); //D3DGETDATA_FLUSH
}
void GFXD3D11QueryFence::zombify()
{
// Release our query
SAFE_RELEASE( mQuery );
}
void GFXD3D11QueryFence::resurrect()
{
// Recreate the query
if(mQuery == NULL)
{
D3D11_QUERY_DESC QueryDesc;
QueryDesc.Query = D3D11_QUERY_EVENT;
QueryDesc.MiscFlags = 0;
HRESULT hRes = D3D11DEVICE->CreateQuery(&QueryDesc, &mQuery);
if(FAILED(hRes))
{
AssertFatal(false, "GFXD3D11QueryFence::resurrect - Hardware does not support D3D11 Queries, this should be caught before this fence type is created");
}
AssertISV(hRes != E_OUTOFMEMORY, "GFXD3D11QueryFence::resurrect - Out of memory");
}
}
const String GFXD3D11QueryFence::describeSelf() const
{
// We've got nothing
return String();
}

View file

@ -0,0 +1,49 @@
//-----------------------------------------------------------------------------
// Copyright (c) 2015 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#ifndef _GFX_D3D11_QUERYFENCE_H_
#define _GFX_D3D11_QUERYFENCE_H_
#include "gfx/gfxFence.h"
#include "gfx/gfxResource.h"
#include "gfx/D3D11/gfxD3D11Device.h"
class GFXD3D11QueryFence : public GFXFence
{
private:
mutable ID3D11Query *mQuery;
public:
GFXD3D11QueryFence( GFXDevice *device ) : GFXFence( device ), mQuery( NULL ) {};
virtual ~GFXD3D11QueryFence();
virtual void issue();
virtual FenceStatus getStatus() const;
virtual void block();
// GFXResource interface
virtual void zombify();
virtual void resurrect();
virtual const String describeSelf() const;
};
#endif

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,471 @@
//-----------------------------------------------------------------------------
// Copyright (c) 2015 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#ifndef _GFXD3D11SHADER_H_
#define _GFXD3D11SHADER_H_
#include <d3dcompiler.h>
#include "core/util/path.h"
#include "core/util/tDictionary.h"
#include "gfx/gfxShader.h"
#include "gfx/gfxResource.h"
#include "gfx/genericConstBuffer.h"
#include "gfx/D3D11/gfxD3D11Device.h"
class GFXD3D11Shader;
enum CONST_CLASS
{
D3DPC_SCALAR,
D3DPC_VECTOR,
D3DPC_MATRIX_ROWS,
D3DPC_MATRIX_COLUMNS,
D3DPC_OBJECT,
D3DPC_STRUCT
};
enum CONST_TYPE
{
D3DPT_VOID,
D3DPT_BOOL,
D3DPT_INT,
D3DPT_FLOAT,
D3DPT_STRING,
D3DPT_TEXTURE,
D3DPT_TEXTURE1D,
D3DPT_TEXTURE2D,
D3DPT_TEXTURE3D,
D3DPT_TEXTURECUBE,
D3DPT_SAMPLER,
D3DPT_SAMPLER1D,
D3DPT_SAMPLER2D,
D3DPT_SAMPLER3D,
D3DPT_SAMPLERCUBE,
D3DPT_PIXELSHADER,
D3DPT_VERTEXSHADER,
D3DPT_PIXELFRAGMENT,
D3DPT_VERTEXFRAGMENT
};
enum REGISTER_TYPE
{
D3DRS_BOOL,
D3DRS_INT4,
D3DRS_FLOAT4,
D3DRS_SAMPLER
};
struct ConstantDesc
{
String Name;
S32 RegisterIndex;
S32 RegisterCount;
S32 Rows;
S32 Columns;
S32 Elements;
S32 StructMembers;
REGISTER_TYPE RegisterSet;
CONST_CLASS Class;
CONST_TYPE Type;
U32 Bytes;
};
class ConstantTable
{
public:
bool Create(const void* data);
U32 GetConstantCount() const { return m_constants.size(); }
const String& GetCreator() const { return m_creator; }
const ConstantDesc* GetConstantByIndex(U32 i) const { return &m_constants[i]; }
const ConstantDesc* GetConstantByName(const String& name) const;
void ClearConstants() { m_constants.clear(); }
private:
Vector<ConstantDesc> m_constants;
String m_creator;
};
// Structs
struct CTHeader
{
U32 Size;
U32 Creator;
U32 Version;
U32 Constants;
U32 ConstantInfo;
U32 Flags;
U32 Target;
};
struct CTInfo
{
U32 Name;
U16 RegisterSet;
U16 RegisterIndex;
U16 RegisterCount;
U16 Reserved;
U32 TypeInfo;
U32 DefaultValue;
};
struct CTType
{
U16 Class;
U16 Type;
U16 Rows;
U16 Columns;
U16 Elements;
U16 StructMembers;
U32 StructMemberInfo;
};
// Shader instruction opcodes
const U32 SIO_COMMENT = 0x0000FFFE;
const U32 SIO_END = 0x0000FFFF;
const U32 SI_OPCODE_MASK = 0x0000FFFF;
const U32 SI_COMMENTSIZE_MASK = 0x7FFF0000;
const U32 CTAB_CONSTANT = 0x42415443;
// Member functions
inline bool ConstantTable::Create(const void* data)
{
const U32* ptr = static_cast<const U32*>(data);
while(*++ptr != SIO_END)
{
if((*ptr & SI_OPCODE_MASK) == SIO_COMMENT)
{
// Check for CTAB comment
U32 comment_size = (*ptr & SI_COMMENTSIZE_MASK) >> 16;
if(*(ptr+1) != CTAB_CONSTANT)
{
ptr += comment_size;
continue;
}
// Read header
const char* ctab = reinterpret_cast<const char*>(ptr+2);
size_t ctab_size = (comment_size-1)*4;
const CTHeader* header = reinterpret_cast<const CTHeader*>(ctab);
if(ctab_size < sizeof(*header) || header->Size != sizeof(*header))
return false;
m_creator = ctab + header->Creator;
// Read constants
m_constants.reserve(header->Constants);
const CTInfo* info = reinterpret_cast<const CTInfo*>(ctab + header->ConstantInfo);
for(U32 i = 0; i < header->Constants; ++i)
{
const CTType* type = reinterpret_cast<const CTType*>(ctab + info[i].TypeInfo);
// Fill struct
ConstantDesc desc;
desc.Name = ctab + info[i].Name;
desc.RegisterSet = static_cast<REGISTER_TYPE>(info[i].RegisterSet);
desc.RegisterIndex = info[i].RegisterIndex;
desc.RegisterCount = info[i].RegisterCount;
desc.Rows = type->Rows;
desc.Class = static_cast<CONST_CLASS>(type->Class);
desc.Type = static_cast<CONST_TYPE>(type->Type);
desc.Columns = type->Columns;
desc.Elements = type->Elements;
desc.StructMembers = type->StructMembers;
desc.Bytes = 4 * desc.Elements * desc.Rows * desc.Columns;
m_constants.push_back(desc);
}
return true;
}
}
return false;
}
inline const ConstantDesc* ConstantTable::GetConstantByName(const String& name) const
{
Vector<ConstantDesc>::const_iterator it;
for(it = m_constants.begin(); it != m_constants.end(); ++it)
{
if(it->Name == name)
return &(*it);
}
return NULL;
}
/////////////////// Constant Buffers /////////////////////////////
// Maximum number of CBuffers ($Globals & $Params)
const U32 CBUFFER_MAX = 2;
struct ConstSubBufferDesc
{
U32 start;
U32 size;
ConstSubBufferDesc() : start(0), size(0){}
};
class GFXD3D11ConstBufferLayout : public GenericConstBufferLayout
{
public:
GFXD3D11ConstBufferLayout();
/// Get our constant sub buffer data
Vector<ConstSubBufferDesc> &getSubBufferDesc(){ return mSubBuffers; }
/// We need to manually set the size due to D3D11 alignment
void setSize(U32 size){ mBufferSize = size;}
/// Set a parameter, given a base pointer
virtual bool set(const ParamDesc& pd, const GFXShaderConstType constType, const U32 size, const void* data, U8* basePointer);
protected:
/// Set a matrix, given a base pointer
virtual bool setMatrix(const ParamDesc& pd, const GFXShaderConstType constType, const U32 size, const void* data, U8* basePointer);
Vector<ConstSubBufferDesc> mSubBuffers;
};
class GFXD3D11ShaderConstHandle : public GFXShaderConstHandle
{
public:
// GFXShaderConstHandle
const String& getName() const;
GFXShaderConstType getType() const;
U32 getArraySize() const;
WeakRefPtr<GFXD3D11Shader> mShader;
bool mVertexConstant;
GenericConstBufferLayout::ParamDesc mVertexHandle;
bool mPixelConstant;
GenericConstBufferLayout::ParamDesc mPixelHandle;
/// Is true if this constant is for hardware mesh instancing.
///
/// Note: We currently store its settings in mPixelHandle.
///
bool mInstancingConstant;
void setValid( bool valid ) { mValid = valid; }
S32 getSamplerRegister() const;
// Returns true if this is a handle to a sampler register.
bool isSampler() const
{
return ( mPixelConstant && mPixelHandle.constType >= GFXSCT_Sampler ) || ( mVertexConstant && mVertexHandle.constType >= GFXSCT_Sampler );
}
/// Restore to uninitialized state.
void clear()
{
mShader = NULL;
mVertexConstant = false;
mPixelConstant = false;
mInstancingConstant = false;
mVertexHandle.clear();
mPixelHandle.clear();
mValid = false;
}
GFXD3D11ShaderConstHandle();
};
/// The D3D11 implementation of a shader constant buffer.
class GFXD3D11ShaderConstBuffer : public GFXShaderConstBuffer
{
friend class GFXD3D11Shader;
public:
GFXD3D11ShaderConstBuffer(GFXD3D11Shader* shader,
GFXD3D11ConstBufferLayout* vertexLayout,
GFXD3D11ConstBufferLayout* pixelLayout);
virtual ~GFXD3D11ShaderConstBuffer();
/// Called by GFXD3D11Device to activate this buffer.
/// @param mPrevShaderBuffer The previously active buffer
void activate(GFXD3D11ShaderConstBuffer *prevShaderBuffer);
/// Used internally by GXD3D11ShaderConstBuffer to determine if it's dirty.
bool isDirty();
/// Called from GFXD3D11Shader when constants have changed and need
/// to be the shader this buffer references is reloaded.
void onShaderReload(GFXD3D11Shader *shader);
// GFXShaderConstBuffer
virtual GFXShader* getShader();
virtual void set(GFXShaderConstHandle* handle, const F32 fv);
virtual void set(GFXShaderConstHandle* handle, const Point2F& fv);
virtual void set(GFXShaderConstHandle* handle, const Point3F& fv);
virtual void set(GFXShaderConstHandle* handle, const Point4F& fv);
virtual void set(GFXShaderConstHandle* handle, const PlaneF& fv);
virtual void set(GFXShaderConstHandle* handle, const ColorF& fv);
virtual void set(GFXShaderConstHandle* handle, const S32 f);
virtual void set(GFXShaderConstHandle* handle, const Point2I& fv);
virtual void set(GFXShaderConstHandle* handle, const Point3I& fv);
virtual void set(GFXShaderConstHandle* handle, const Point4I& fv);
virtual void set(GFXShaderConstHandle* handle, const AlignedArray<F32>& fv);
virtual void set(GFXShaderConstHandle* handle, const AlignedArray<Point2F>& fv);
virtual void set(GFXShaderConstHandle* handle, const AlignedArray<Point3F>& fv);
virtual void set(GFXShaderConstHandle* handle, const AlignedArray<Point4F>& fv);
virtual void set(GFXShaderConstHandle* handle, const AlignedArray<S32>& fv);
virtual void set(GFXShaderConstHandle* handle, const AlignedArray<Point2I>& fv);
virtual void set(GFXShaderConstHandle* handle, const AlignedArray<Point3I>& fv);
virtual void set(GFXShaderConstHandle* handle, const AlignedArray<Point4I>& fv);
virtual void set(GFXShaderConstHandle* handle, const MatrixF& mat, const GFXShaderConstType matType = GFXSCT_Float4x4);
virtual void set(GFXShaderConstHandle* handle, const MatrixF* mat, const U32 arraySize, const GFXShaderConstType matrixType = GFXSCT_Float4x4);
// GFXResource
virtual const String describeSelf() const;
virtual void zombify();
virtual void resurrect();
protected:
void _createBuffers();
template<class T>
inline void SET_CONSTANT(GFXShaderConstHandle* handle,
const T& fv,
GenericConstBuffer *vBuffer,
GenericConstBuffer *pBuffer);
// Constant buffers, VSSetConstantBuffers1 has issues on win 7. So unfortunately for now we have multiple constant buffers
ID3D11Buffer* mConstantBuffersV[CBUFFER_MAX];
ID3D11Buffer* mConstantBuffersP[CBUFFER_MAX];
/// We keep a weak reference to the shader
/// because it will often be deleted.
WeakRefPtr<GFXD3D11Shader> mShader;
//vertex
GFXD3D11ConstBufferLayout* mVertexConstBufferLayout;
GenericConstBuffer* mVertexConstBuffer;
//pixel
GFXD3D11ConstBufferLayout* mPixelConstBufferLayout;
GenericConstBuffer* mPixelConstBuffer;
};
class gfxD3D11Include;
typedef StrongRefPtr<gfxD3D11Include> gfxD3DIncludeRef;
/////////////////// GFXShader implementation /////////////////////////////
class GFXD3D11Shader : public GFXShader
{
friend class GFXD3D11Device;
friend class GFXD3D11ShaderConstBuffer;
public:
typedef Map<String, GFXD3D11ShaderConstHandle*> HandleMap;
GFXD3D11Shader();
virtual ~GFXD3D11Shader();
// GFXShader
virtual GFXShaderConstBufferRef allocConstBuffer();
virtual const Vector<GFXShaderConstDesc>& getShaderConstDesc() const;
virtual GFXShaderConstHandle* getShaderConstHandle(const String& name);
virtual GFXShaderConstHandle* findShaderConstHandle(const String& name);
virtual U32 getAlignmentValue(const GFXShaderConstType constType) const;
virtual bool getDisassembly( String &outStr ) const;
// GFXResource
virtual void zombify();
virtual void resurrect();
protected:
virtual bool _init();
static const U32 smCompiledShaderTag;
ConstantTable table;
ID3D11VertexShader *mVertShader;
ID3D11PixelShader *mPixShader;
GFXD3D11ConstBufferLayout* mVertexConstBufferLayout;
GFXD3D11ConstBufferLayout* mPixelConstBufferLayout;
static gfxD3DIncludeRef smD3DInclude;
HandleMap mHandles;
/// The shader disassembly from DX when this shader is compiled.
/// We only store this data in non-release builds.
String mDissasembly;
/// Vector of sampler type descriptions consolidated from _compileShader.
Vector<GFXShaderConstDesc> mSamplerDescriptions;
/// Vector of descriptions (consolidated for the getShaderConstDesc call)
Vector<GFXShaderConstDesc> mShaderConsts;
// These two functions are used when compiling shaders from hlsl
virtual bool _compileShader( const Torque::Path &filePath,
const String &target,
const D3D_SHADER_MACRO *defines,
GenericConstBufferLayout *bufferLayout,
Vector<GFXShaderConstDesc> &samplerDescriptions );
void _getShaderConstants( ID3D11ShaderReflection* table,
GenericConstBufferLayout *bufferLayout,
Vector<GFXShaderConstDesc> &samplerDescriptions );
bool _convertShaderVariable(const D3D11_SHADER_TYPE_DESC &typeDesc, GFXShaderConstDesc &desc);
bool _saveCompiledOutput( const Torque::Path &filePath,
ID3DBlob *buffer,
GenericConstBufferLayout *bufferLayout,
Vector<GFXShaderConstDesc> &samplerDescriptions );
// Loads precompiled shaders
bool _loadCompiledOutput( const Torque::Path &filePath,
const String &target,
GenericConstBufferLayout *bufferLayoutF,
Vector<GFXShaderConstDesc> &samplerDescriptions );
// This is used in both cases
virtual void _buildShaderConstantHandles(GenericConstBufferLayout *layout, bool vertexConst);
virtual void _buildSamplerShaderConstantHandles( Vector<GFXShaderConstDesc> &samplerDescriptions );
/// Used to build the instancing shader constants from
/// the instancing vertex format.
void _buildInstancingShaderConstantHandles();
};
inline bool GFXD3D11Shader::getDisassembly(String &outStr) const
{
outStr = mDissasembly;
return (outStr.isNotEmpty());
}
#endif

View file

@ -0,0 +1,285 @@
//-----------------------------------------------------------------------------
// Copyright (c) 2015 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#include "gfx/gfxDevice.h"
#include "gfx/D3D11/gfxD3D11StateBlock.h"
#include "gfx/D3D11/gfxD3D11EnumTranslate.h"
GFXD3D11StateBlock::GFXD3D11StateBlock(const GFXStateBlockDesc& desc)
{
AssertFatal(D3D11DEVICE, "Invalid D3DDevice!");
mDesc = desc;
mCachedHashValue = desc.getHashValue();
// Color writes
mColorMask = 0;
mColorMask |= (mDesc.colorWriteRed ? D3D11_COLOR_WRITE_ENABLE_RED : 0);
mColorMask |= (mDesc.colorWriteGreen ? D3D11_COLOR_WRITE_ENABLE_GREEN : 0);
mColorMask |= (mDesc.colorWriteBlue ? D3D11_COLOR_WRITE_ENABLE_BLUE : 0);
mColorMask |= (mDesc.colorWriteAlpha ? D3D11_COLOR_WRITE_ENABLE_ALPHA : 0);
mBlendState = NULL;
for (U32 i = 0; i < GFX->getNumSamplers(); i++)
{
mSamplerStates[i] = NULL;
}
mDepthStencilState = NULL;
mRasterizerState = NULL;
mBlendDesc.AlphaToCoverageEnable = false;
mBlendDesc.IndependentBlendEnable = false;
mBlendDesc.RenderTarget[0].BlendEnable = mDesc.blendEnable;
mBlendDesc.RenderTarget[0].BlendOp = GFXD3D11BlendOp[mDesc.blendOp];
mBlendDesc.RenderTarget[0].BlendOpAlpha = GFXD3D11BlendOp[mDesc.separateAlphaBlendOp];
mBlendDesc.RenderTarget[0].DestBlend = GFXD3D11Blend[mDesc.blendDest];
mBlendDesc.RenderTarget[0].DestBlendAlpha = GFXD3D11Blend[mDesc.separateAlphaBlendDest];
mBlendDesc.RenderTarget[0].SrcBlend = GFXD3D11Blend[mDesc.blendSrc];
mBlendDesc.RenderTarget[0].SrcBlendAlpha = GFXD3D11Blend[mDesc.separateAlphaBlendSrc];
mBlendDesc.RenderTarget[0].RenderTargetWriteMask = mColorMask;
HRESULT hr = D3D11DEVICE->CreateBlendState(&mBlendDesc, &mBlendState);
if(FAILED(hr))
{
AssertFatal(false, "GFXD3D11StateBlock::GFXD3D11StateBlock - CreateBlendState call failure.");
}
mDepthStencilDesc.DepthWriteMask = mDesc.zWriteEnable ? D3D11_DEPTH_WRITE_MASK_ALL : D3D11_DEPTH_WRITE_MASK_ZERO;
mDepthStencilDesc.DepthEnable = mDesc.zEnable;
mDepthStencilDesc.DepthFunc = GFXD3D11CmpFunc[mDesc.zFunc];
mDepthStencilDesc.StencilWriteMask = mDesc.stencilWriteMask;
mDepthStencilDesc.StencilReadMask = mDesc.stencilMask;
mDepthStencilDesc.StencilEnable = mDesc.stencilEnable;
mDepthStencilDesc.FrontFace.StencilFunc = GFXD3D11CmpFunc[mDesc.stencilFunc];
mDepthStencilDesc.FrontFace.StencilFailOp = GFXD3D11StencilOp[mDesc.stencilFailOp];
mDepthStencilDesc.FrontFace.StencilDepthFailOp = GFXD3D11StencilOp[mDesc.stencilZFailOp];
mDepthStencilDesc.FrontFace.StencilPassOp = GFXD3D11StencilOp[mDesc.stencilPassOp];
mDepthStencilDesc.BackFace = mDepthStencilDesc.FrontFace;
hr = D3D11DEVICE->CreateDepthStencilState(&mDepthStencilDesc, &mDepthStencilState);
if(FAILED(hr))
{
AssertFatal(false, "GFXD3D11StateBlock::GFXD3D11StateBlock - CreateDepthStencilState call failure.");
}
mRasterizerDesc.CullMode = GFXD3D11CullMode[mDesc.cullMode];
mRasterizerDesc.FillMode = GFXD3D11FillMode[mDesc.fillMode];
mRasterizerDesc.DepthBias = mDesc.zBias;
mRasterizerDesc.SlopeScaledDepthBias = mDesc.zSlopeBias;
mRasterizerDesc.AntialiasedLineEnable = FALSE;
mRasterizerDesc.MultisampleEnable = FALSE;
mRasterizerDesc.ScissorEnable = FALSE;
mRasterizerDesc.DepthClipEnable = TRUE;
mRasterizerDesc.FrontCounterClockwise = FALSE;
mRasterizerDesc.DepthBiasClamp = D3D11_DEFAULT_DEPTH_BIAS_CLAMP;
hr = D3D11DEVICE->CreateRasterizerState(&mRasterizerDesc, &mRasterizerState);
if(FAILED(hr))
{
AssertFatal(false, "GFXD3D11StateBlock::GFXD3D11StateBlock - CreateDepthStencilState call failure.");
}
for ( U32 i = 0; i < GFX->getNumSamplers(); i++ )
{
mSamplerDesc[i].AddressU = GFXD3D11TextureAddress[mDesc.samplers[i].addressModeU];
mSamplerDesc[i].AddressV = GFXD3D11TextureAddress[mDesc.samplers[i].addressModeV];
mSamplerDesc[i].AddressW = GFXD3D11TextureAddress[mDesc.samplers[i].addressModeW];
mSamplerDesc[i].MaxAnisotropy = mDesc.samplers[i].maxAnisotropy;
mSamplerDesc[i].MipLODBias = mDesc.samplers[i].mipLODBias;
mSamplerDesc[i].MinLOD = 0;
mSamplerDesc[i].MaxLOD = FLT_MAX;
if(mDesc.samplers[i].magFilter == GFXTextureFilterPoint && mDesc.samplers[i].minFilter == GFXTextureFilterPoint && mDesc.samplers[i].mipFilter == GFXTextureFilterPoint)
mSamplerDesc[i].Filter = D3D11_FILTER_MIN_MAG_MIP_POINT;
else if(mDesc.samplers[i].magFilter == GFXTextureFilterPoint && mDesc.samplers[i].minFilter == GFXTextureFilterPoint && mDesc.samplers[i].mipFilter == GFXTextureFilterLinear)
mSamplerDesc[i].Filter = D3D11_FILTER_MIN_MAG_POINT_MIP_LINEAR;
else if(mDesc.samplers[i].magFilter == GFXTextureFilterLinear && mDesc.samplers[i].minFilter == GFXTextureFilterPoint && mDesc.samplers[i].mipFilter == GFXTextureFilterPoint)
mSamplerDesc[i].Filter = D3D11_FILTER_MIN_POINT_MAG_LINEAR_MIP_POINT;
else if(mDesc.samplers[i].magFilter == GFXTextureFilterLinear && mDesc.samplers[i].minFilter == GFXTextureFilterPoint && mDesc.samplers[i].mipFilter == GFXTextureFilterLinear)
mSamplerDesc[i].Filter = D3D11_FILTER_MIN_POINT_MAG_MIP_LINEAR;
else if(mDesc.samplers[i].magFilter == GFXTextureFilterPoint && mDesc.samplers[i].minFilter == GFXTextureFilterLinear && mDesc.samplers[i].mipFilter == GFXTextureFilterPoint)
mSamplerDesc[i].Filter = D3D11_FILTER_MIN_LINEAR_MAG_MIP_POINT;
else if(mDesc.samplers[i].magFilter == GFXTextureFilterPoint && mDesc.samplers[i].minFilter == GFXTextureFilterLinear && mDesc.samplers[i].mipFilter == GFXTextureFilterLinear)
mSamplerDesc[i].Filter = D3D11_FILTER_MIN_LINEAR_MAG_POINT_MIP_LINEAR;
else if(mDesc.samplers[i].magFilter == GFXTextureFilterLinear && mDesc.samplers[i].minFilter == GFXTextureFilterLinear && mDesc.samplers[i].mipFilter == GFXTextureFilterPoint)
mSamplerDesc[i].Filter = D3D11_FILTER_MIN_MAG_LINEAR_MIP_POINT;
else if(mDesc.samplers[i].magFilter == GFXTextureFilterLinear && mDesc.samplers[i].minFilter == GFXTextureFilterLinear && mDesc.samplers[i].mipFilter == GFXTextureFilterLinear)
mSamplerDesc[i].Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
else
mSamplerDesc[i].Filter = D3D11_FILTER_ANISOTROPIC;
mSamplerDesc[i].BorderColor[0] = 1.0f;
mSamplerDesc[i].BorderColor[1] = 1.0f;
mSamplerDesc[i].BorderColor[2] = 1.0f;
mSamplerDesc[i].BorderColor[3] = 1.0f;
mSamplerDesc[i].ComparisonFunc = D3D11_COMPARISON_NEVER;
hr = D3D11DEVICE->CreateSamplerState(&mSamplerDesc[i], &mSamplerStates[i]);
if(FAILED(hr))
{
AssertFatal(false, "GFXD3D11StateBlock::GFXD3D11StateBlock - CreateSamplerState call failure.");
}
}
}
GFXD3D11StateBlock::~GFXD3D11StateBlock()
{
SAFE_RELEASE(mBlendState);
SAFE_RELEASE(mRasterizerState);
SAFE_RELEASE(mDepthStencilState);
//Use TEXTURE_STAGE_COUNT here, not safe to rely on GFX pointer
for (U32 i = 0; i < TEXTURE_STAGE_COUNT; ++i)
{
SAFE_RELEASE(mSamplerStates[i]);
}
}
/// Returns the hash value of the desc that created this block
U32 GFXD3D11StateBlock::getHashValue() const
{
return mCachedHashValue;
}
/// Returns a GFXStateBlockDesc that this block represents
const GFXStateBlockDesc& GFXD3D11StateBlock::getDesc() const
{
return mDesc;
}
/// Called by D3D11 device to active this state block.
/// @param oldState The current state, used to make sure we don't set redundant states on the device. Pass NULL to reset all states.
void GFXD3D11StateBlock::activate(GFXD3D11StateBlock* oldState)
{
PROFILE_SCOPE( GFXD3D11StateBlock_Activate );
ID3D11DeviceContext* pDevCxt = D3D11DEVICECONTEXT;
mBlendDesc.AlphaToCoverageEnable = false;
mBlendDesc.IndependentBlendEnable = mDesc.separateAlphaBlendEnable;
mBlendDesc.RenderTarget[0].BlendEnable = mDesc.blendEnable;
mBlendDesc.RenderTarget[0].BlendOp = GFXD3D11BlendOp[mDesc.blendOp];
mBlendDesc.RenderTarget[0].BlendOpAlpha = GFXD3D11BlendOp[mDesc.separateAlphaBlendOp];
mBlendDesc.RenderTarget[0].DestBlend = GFXD3D11Blend[mDesc.blendDest];
mBlendDesc.RenderTarget[0].DestBlendAlpha = GFXD3D11Blend[mDesc.separateAlphaBlendDest];
mBlendDesc.RenderTarget[0].SrcBlend = GFXD3D11Blend[mDesc.blendSrc];
mBlendDesc.RenderTarget[0].SrcBlendAlpha = GFXD3D11Blend[mDesc.separateAlphaBlendSrc];
mBlendDesc.RenderTarget[0].RenderTargetWriteMask = mColorMask;
float blendFactor[] = { 1.0f, 1.0f, 1.0f, 1.0f };
pDevCxt->OMSetBlendState(mBlendState, blendFactor, 0xFFFFFFFF);
mDepthStencilDesc.DepthWriteMask = mDesc.zWriteEnable ? D3D11_DEPTH_WRITE_MASK_ALL : D3D11_DEPTH_WRITE_MASK_ZERO;
mDepthStencilDesc.DepthEnable = mDesc.zEnable;
mDepthStencilDesc.DepthFunc = GFXD3D11CmpFunc[mDesc.zFunc];
mDepthStencilDesc.StencilWriteMask = mDesc.stencilWriteMask;
mDepthStencilDesc.StencilReadMask = mDesc.stencilMask;
mDepthStencilDesc.StencilEnable = mDesc.stencilEnable;
mDepthStencilDesc.FrontFace.StencilFunc = GFXD3D11CmpFunc[mDesc.stencilFunc];
mDepthStencilDesc.FrontFace.StencilFailOp = GFXD3D11StencilOp[mDesc.stencilFailOp];
mDepthStencilDesc.FrontFace.StencilDepthFailOp = GFXD3D11StencilOp[mDesc.stencilZFailOp];
mDepthStencilDesc.FrontFace.StencilPassOp = GFXD3D11StencilOp[mDesc.stencilPassOp];
if (mDesc.stencilEnable)
mDepthStencilDesc.BackFace = mDepthStencilDesc.FrontFace;
else
{
mDepthStencilDesc.BackFace.StencilFunc = GFXD3D11CmpFunc[GFXCmpAlways];
mDepthStencilDesc.BackFace.StencilFailOp = GFXD3D11StencilOp[GFXStencilOpKeep];
mDepthStencilDesc.BackFace.StencilDepthFailOp = GFXD3D11StencilOp[GFXStencilOpKeep];
mDepthStencilDesc.BackFace.StencilPassOp = GFXD3D11StencilOp[GFXStencilOpKeep];
}
pDevCxt->OMSetDepthStencilState(mDepthStencilState, mDesc.stencilRef);
mRasterizerDesc.CullMode = GFXD3D11CullMode[mDesc.cullMode];
mRasterizerDesc.FillMode = GFXD3D11FillMode[mDesc.fillMode];
mRasterizerDesc.DepthBias = mDesc.zBias;
mRasterizerDesc.SlopeScaledDepthBias = mDesc.zSlopeBias;
mRasterizerDesc.AntialiasedLineEnable = FALSE;
mRasterizerDesc.MultisampleEnable = FALSE;
mRasterizerDesc.ScissorEnable = FALSE;
if (mDesc.zEnable)
mRasterizerDesc.DepthClipEnable = true;
else
mRasterizerDesc.DepthClipEnable = false;
mRasterizerDesc.FrontCounterClockwise = FALSE;
mRasterizerDesc.DepthBiasClamp = 0.0f;
pDevCxt->RSSetState(mRasterizerState);
U32 numSamplers = GFX->getNumSamplers();
for (U32 i = 0; i < numSamplers; i++)
{
mSamplerDesc[i].AddressU = GFXD3D11TextureAddress[mDesc.samplers[i].addressModeU];
mSamplerDesc[i].AddressV = GFXD3D11TextureAddress[mDesc.samplers[i].addressModeV];
mSamplerDesc[i].AddressW = GFXD3D11TextureAddress[mDesc.samplers[i].addressModeW];
mSamplerDesc[i].MaxAnisotropy = mDesc.samplers[i].maxAnisotropy;
mSamplerDesc[i].MipLODBias = mDesc.samplers[i].mipLODBias;
mSamplerDesc[i].MinLOD = 0;
mSamplerDesc[i].MaxLOD = FLT_MAX;
if(mDesc.samplers[i].magFilter == GFXTextureFilterPoint && mDesc.samplers[i].minFilter == GFXTextureFilterPoint && mDesc.samplers[i].mipFilter == GFXTextureFilterPoint)
mSamplerDesc[i].Filter = D3D11_FILTER_MIN_MAG_MIP_POINT;
else if(mDesc.samplers[i].magFilter == GFXTextureFilterPoint && mDesc.samplers[i].minFilter == GFXTextureFilterPoint && mDesc.samplers[i].mipFilter == GFXTextureFilterLinear)
mSamplerDesc[i].Filter = D3D11_FILTER_MIN_MAG_POINT_MIP_LINEAR;
else if(mDesc.samplers[i].magFilter == GFXTextureFilterLinear && mDesc.samplers[i].minFilter == GFXTextureFilterPoint && mDesc.samplers[i].mipFilter == GFXTextureFilterPoint)
mSamplerDesc[i].Filter = D3D11_FILTER_MIN_POINT_MAG_LINEAR_MIP_POINT;
else if(mDesc.samplers[i].magFilter == GFXTextureFilterLinear && mDesc.samplers[i].minFilter == GFXTextureFilterPoint && mDesc.samplers[i].mipFilter == GFXTextureFilterLinear)
mSamplerDesc[i].Filter = D3D11_FILTER_MIN_POINT_MAG_MIP_LINEAR;
else if(mDesc.samplers[i].magFilter == GFXTextureFilterPoint && mDesc.samplers[i].minFilter == GFXTextureFilterLinear && mDesc.samplers[i].mipFilter == GFXTextureFilterPoint)
mSamplerDesc[i].Filter = D3D11_FILTER_MIN_LINEAR_MAG_MIP_POINT;
else if(mDesc.samplers[i].magFilter == GFXTextureFilterPoint && mDesc.samplers[i].minFilter == GFXTextureFilterLinear && mDesc.samplers[i].mipFilter == GFXTextureFilterLinear)
mSamplerDesc[i].Filter = D3D11_FILTER_MIN_LINEAR_MAG_POINT_MIP_LINEAR;
else if(mDesc.samplers[i].magFilter == GFXTextureFilterLinear && mDesc.samplers[i].minFilter == GFXTextureFilterLinear && mDesc.samplers[i].mipFilter == GFXTextureFilterPoint)
mSamplerDesc[i].Filter = D3D11_FILTER_MIN_MAG_LINEAR_MIP_POINT;
else if(mDesc.samplers[i].magFilter == GFXTextureFilterLinear && mDesc.samplers[i].minFilter == GFXTextureFilterLinear && mDesc.samplers[i].mipFilter == GFXTextureFilterLinear)
mSamplerDesc[i].Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
else
mSamplerDesc[i].Filter = D3D11_FILTER_ANISOTROPIC;
mSamplerDesc[i].BorderColor[0] = 0.0f;
mSamplerDesc[i].BorderColor[1] = 0.0f;
mSamplerDesc[i].BorderColor[2] = 0.0f;
mSamplerDesc[i].BorderColor[3] = 0.0f;
mSamplerDesc[i].ComparisonFunc = D3D11_COMPARISON_NEVER;
}
//TODO samplers for vertex shader
// Set all the samplers with one call
//pDevCxt->VSSetSamplers(0, numSamplers, &mSamplerStates[0]);
pDevCxt->PSSetSamplers(0, numSamplers, &mSamplerStates[0]);
}

View file

@ -0,0 +1,76 @@
//-----------------------------------------------------------------------------
// Copyright (c) 2015 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#ifndef _GFXD3D11STATEBLOCK_H_
#define _GFXD3D11STATEBLOCK_H_
#include "gfx/D3D11/gfxD3D11Device.h"
#include "gfx/gfxStateBlock.h"
class GFXD3D11StateBlock : public GFXStateBlock
{
public:
GFXD3D11StateBlock(const GFXStateBlockDesc& desc);
virtual ~GFXD3D11StateBlock();
/// Called by D3D11 device to active this state block.
/// @param oldState The current state, used to make sure we don't set redundant states on the device. Pass NULL to reset all states.
void activate(GFXD3D11StateBlock* oldState);
//
// GFXStateBlock interface
//
/// Returns the hash value of the desc that created this block
virtual U32 getHashValue() const;
/// Returns a GFXStateBlockDesc that this block represents
virtual const GFXStateBlockDesc& getDesc() const;
//
// GFXResource
//
virtual void zombify() { }
/// When called the resource should restore all device sensitive information destroyed by zombify()
virtual void resurrect() { }
private:
D3D11_BLEND_DESC mBlendDesc;
D3D11_RASTERIZER_DESC mRasterizerDesc;
D3D11_DEPTH_STENCIL_DESC mDepthStencilDesc;
D3D11_SAMPLER_DESC mSamplerDesc[TEXTURE_STAGE_COUNT];
ID3D11BlendState* mBlendState;
ID3D11DepthStencilState* mDepthStencilState;
ID3D11RasterizerState* mRasterizerState;
ID3D11SamplerState* mSamplerStates[TEXTURE_STAGE_COUNT];
GFXStateBlockDesc mDesc;
U32 mCachedHashValue;
// Cached D3D specific things, these are "calculated" from GFXStateBlock
U32 mColorMask;
};
typedef StrongRefPtr<GFXD3D11StateBlock> GFXD3D11StateBlockRef;
#endif

View file

@ -0,0 +1,409 @@
//-----------------------------------------------------------------------------
// Copyright (c) 2015 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#include "platform/platform.h"
#include "gfx/D3D11/gfxD3D11Target.h"
#include "gfx/D3D11/gfxD3D11Cubemap.h"
#include "gfx/D3D11/gfxD3D11EnumTranslate.h"
#include "gfx/gfxDebugEvent.h"
#include "gfx/gfxStringEnumTranslate.h"
#include "windowManager/win32/win32Window.h"
GFXD3D11TextureTarget::GFXD3D11TextureTarget()
: mTargetSize( Point2I::Zero ),
mTargetFormat( GFXFormatR8G8B8A8 )
{
for(S32 i=0; i<MaxRenderSlotId; i++)
{
mTargets[i] = NULL;
mResolveTargets[i] = NULL;
mTargetViews[i] = NULL;
mTargetSRViews[i] = NULL;
}
}
GFXD3D11TextureTarget::~GFXD3D11TextureTarget()
{
// Release anything we might be holding.
for(S32 i=0; i<MaxRenderSlotId; i++)
{
mResolveTargets[i] = NULL;
SAFE_RELEASE(mTargetViews[i]);
SAFE_RELEASE(mTargets[i]);
SAFE_RELEASE(mTargetSRViews[i]);
}
zombify();
}
void GFXD3D11TextureTarget::attachTexture( RenderSlot slot, GFXTextureObject *tex, U32 mipLevel/*=0*/, U32 zOffset /*= 0*/ )
{
GFXDEBUGEVENT_SCOPE( GFXPCD3D11TextureTarget_attachTexture, ColorI::RED );
AssertFatal(slot < MaxRenderSlotId, "GFXD3D11TextureTarget::attachTexture - out of range slot.");
// TODO: The way this is implemented... you can attach a texture
// object multiple times and it will release and reset it.
//
// We should rework this to detect when no change has occured
// and skip out early.
// Mark state as dirty so device can know to update.
invalidateState();
// Release what we had, it's definitely going to change.
SAFE_RELEASE(mTargetViews[slot]);
SAFE_RELEASE(mTargets[slot]);
SAFE_RELEASE(mTargetSRViews[slot]);
mResolveTargets[slot] = NULL;
if(slot == Color0)
{
mTargetSize = Point2I::Zero;
mTargetFormat = GFXFormatR8G8B8A8;
}
// Are we clearing?
if(!tex)
{
// Yup - just exit, it'll stay NULL.
return;
}
// TODO: Mip map generation currently only supported on dynamic cubemaps
mTargetSRViews[slot] = NULL;
// Take care of default targets
if( tex == GFXTextureTarget::sDefaultDepthStencil )
{
mTargets[slot] = D3D11->mDeviceDepthStencil;
mTargetViews[slot] = D3D11->mDeviceDepthStencilView;
mTargets[slot]->AddRef();
mTargetViews[slot]->AddRef();
}
else
{
// Cast the texture object to D3D...
AssertFatal(static_cast<GFXD3D11TextureObject*>(tex), "GFXD3D11TextureTarget::attachTexture - invalid texture object.");
GFXD3D11TextureObject *d3dto = static_cast<GFXD3D11TextureObject*>(tex);
// Grab the surface level.
if( slot == DepthStencil )
{
mTargets[slot] = d3dto->getSurface();
if ( mTargets[slot] )
mTargets[slot]->AddRef();
mTargetViews[slot] = d3dto->getDSView();
if( mTargetViews[slot])
mTargetViews[slot]->AddRef();
}
else
{
// getSurface will almost always return NULL. It will only return non-NULL
// if the surface that it needs to render to is different than the mip level
// in the actual texture. This will happen with MSAA.
if( d3dto->getSurface() == NULL )
{
mTargets[slot] = d3dto->get2DTex();
mTargets[slot]->AddRef();
mTargetViews[slot] = d3dto->getRTView();
mTargetViews[slot]->AddRef();
}
else
{
mTargets[slot] = d3dto->getSurface();
mTargets[slot]->AddRef();
mTargetViews[slot]->AddRef();
// Only assign resolve target if d3dto has a surface to give us.
//
// That usually means there is an MSAA target involved, which is why
// the resolve is needed to get the data out of the target.
mResolveTargets[slot] = d3dto;
if ( tex && slot == Color0 )
{
mTargetSize.set( tex->getSize().x, tex->getSize().y );
mTargetFormat = tex->getFormat();
}
}
}
// Update surface size
if(slot == Color0)
{
ID3D11Texture2D *surface = mTargets[Color0];
if ( surface )
{
D3D11_TEXTURE2D_DESC sd;
surface->GetDesc(&sd);
mTargetSize = Point2I(sd.Width, sd.Height);
S32 format = sd.Format;
GFXREVERSE_LOOKUP( GFXD3D11TextureFormat, GFXFormat, format );
mTargetFormat = (GFXFormat)format;
}
}
}
}
void GFXD3D11TextureTarget::attachTexture( RenderSlot slot, GFXCubemap *tex, U32 face, U32 mipLevel/*=0*/ )
{
GFXDEBUGEVENT_SCOPE( GFXPCD3D11TextureTarget_attachTexture_Cubemap, ColorI::RED );
AssertFatal(slot < MaxRenderSlotId, "GFXD3D11TextureTarget::attachTexture - out of range slot.");
// Mark state as dirty so device can know to update.
invalidateState();
// Release what we had, it's definitely going to change.
SAFE_RELEASE(mTargetViews[slot]);
SAFE_RELEASE(mTargets[slot]);
SAFE_RELEASE(mTargetSRViews[slot]);
mResolveTargets[slot] = NULL;
// Cast the texture object to D3D...
AssertFatal(!tex || static_cast<GFXD3D11Cubemap*>(tex), "GFXD3DTextureTarget::attachTexture - invalid cubemap object.");
if(slot == Color0)
{
mTargetSize = Point2I::Zero;
mTargetFormat = GFXFormatR8G8B8A8;
}
// Are we clearing?
if(!tex)
{
// Yup - just exit, it'll stay NULL.
return;
}
GFXD3D11Cubemap *cube = static_cast<GFXD3D11Cubemap*>(tex);
mTargets[slot] = cube->get2DTex();
mTargets[slot]->AddRef();
mTargetViews[slot] = cube->getRTView(face);
mTargetViews[slot]->AddRef();
mTargetSRViews[slot] = cube->getSRView();
mTargetSRViews[slot]->AddRef();
// Update surface size
if(slot == Color0)
{
ID3D11Texture2D *surface = mTargets[Color0];
if ( surface )
{
D3D11_TEXTURE2D_DESC sd;
surface->GetDesc(&sd);
mTargetSize = Point2I(sd.Width, sd.Height);
S32 format = sd.Format;
GFXREVERSE_LOOKUP( GFXD3D11TextureFormat, GFXFormat, format );
mTargetFormat = (GFXFormat)format;
}
}
}
void GFXD3D11TextureTarget::activate()
{
GFXDEBUGEVENT_SCOPE( GFXPCD3D11TextureTarget_activate, ColorI::RED );
AssertFatal( mTargets[GFXTextureTarget::Color0], "GFXD3D11TextureTarget::activate() - You can never have a NULL primary render target!" );
// Clear the state indicator.
stateApplied();
// Now set all the new surfaces into the appropriate slots.
ID3D11RenderTargetView* rtViews[MaxRenderSlotId] = { NULL, NULL, NULL, NULL, NULL, NULL};
ID3D11DepthStencilView* dsView = (ID3D11DepthStencilView*)(mTargetViews[GFXTextureTarget::DepthStencil]);
for (U32 i = 0; i < 4; i++)
{
rtViews[i] = (ID3D11RenderTargetView*)mTargetViews[GFXTextureTarget::Color0 + i];
}
D3D11DEVICECONTEXT->OMSetRenderTargets(MaxRenderSlotId, rtViews, dsView);
}
void GFXD3D11TextureTarget::deactivate()
{
//re-gen mip maps
for (U32 i = 0; i < 4; i++)
{
ID3D11ShaderResourceView* pSRView = mTargetSRViews[GFXTextureTarget::Color0 + i];
if (pSRView)
D3D11DEVICECONTEXT->GenerateMips(pSRView);
}
}
void GFXD3D11TextureTarget::resolve()
{
GFXDEBUGEVENT_SCOPE( GFXPCD3D11TextureTarget_resolve, ColorI::RED );
for (U32 i = 0; i < MaxRenderSlotId; i++)
{
// We use existance @ mResolveTargets as a flag that we need to copy
// data from the rendertarget into the texture.
if (mResolveTargets[i])
{
D3D11_TEXTURE2D_DESC desc;
mTargets[i]->GetDesc(&desc);
D3D11DEVICECONTEXT->CopySubresourceRegion(mResolveTargets[i]->get2DTex(), 0, 0, 0, 0, mTargets[i], 0, NULL);
}
}
}
void GFXD3D11TextureTarget::resolveTo( GFXTextureObject *tex )
{
GFXDEBUGEVENT_SCOPE( GFXPCD3D11TextureTarget_resolveTo, ColorI::RED );
if ( mTargets[Color0] == NULL )
return;
D3D11_TEXTURE2D_DESC desc;
mTargets[Color0]->GetDesc(&desc);
D3D11DEVICECONTEXT->CopySubresourceRegion(((GFXD3D11TextureObject*)(tex))->get2DTex(), 0, 0, 0, 0, mTargets[Color0], 0, NULL);
}
void GFXD3D11TextureTarget::zombify()
{
for(U32 i = 0; i < MaxRenderSlotId; i++)
attachTexture(RenderSlot(i), NULL);
}
void GFXD3D11TextureTarget::resurrect()
{
}
GFXD3D11WindowTarget::GFXD3D11WindowTarget()
{
mWindow = NULL;
mBackbuffer = NULL;
}
GFXD3D11WindowTarget::~GFXD3D11WindowTarget()
{
SAFE_RELEASE(mBackbuffer);
}
void GFXD3D11WindowTarget::initPresentationParams()
{
// Get some video mode related info.
GFXVideoMode vm = mWindow->getVideoMode();
Win32Window* win = static_cast<Win32Window*>(mWindow);
HWND hwnd = win->getHWND();
mPresentationParams = D3D11->setupPresentParams(vm, hwnd);
}
const Point2I GFXD3D11WindowTarget::getSize()
{
return mWindow->getVideoMode().resolution;
}
GFXFormat GFXD3D11WindowTarget::getFormat()
{
S32 format = mPresentationParams.BufferDesc.Format;
GFXREVERSE_LOOKUP( GFXD3D11TextureFormat, GFXFormat, format );
return (GFXFormat)format;
}
bool GFXD3D11WindowTarget::present()
{
return (D3D11->getSwapChain()->Present(!D3D11->smDisableVSync, 0) == S_OK);
}
void GFXD3D11WindowTarget::setImplicitSwapChain()
{
if (!mBackbuffer)
D3D11->mSwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&mBackbuffer);
}
void GFXD3D11WindowTarget::resetMode()
{
mWindow->setSuppressReset(true);
// Setup our presentation params.
initPresentationParams();
// Otherwise, we have to reset the device, if we're the implicit swapchain.
D3D11->reset(mPresentationParams);
// Update our size, too.
mSize = Point2I(mPresentationParams.BufferDesc.Width, mPresentationParams.BufferDesc.Height);
mWindow->setSuppressReset(false);
GFX->beginReset();
}
void GFXD3D11WindowTarget::zombify()
{
SAFE_RELEASE(mBackbuffer);
}
void GFXD3D11WindowTarget::resurrect()
{
setImplicitSwapChain();
}
void GFXD3D11WindowTarget::activate()
{
GFXDEBUGEVENT_SCOPE(GFXPCD3D11WindowTarget_activate, ColorI::RED);
//clear ther rendertargets first
ID3D11RenderTargetView* rtViews[8] = { NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL };
D3D11DEVICECONTEXT->OMSetRenderTargets(8, rtViews, NULL);
D3D11DEVICECONTEXT->OMSetRenderTargets(1, &D3D11->mDeviceBackBufferView, D3D11->mDeviceDepthStencilView);
DXGI_SWAP_CHAIN_DESC pp;
D3D11->mSwapChain->GetDesc(&pp);
// Update our video mode here, too.
GFXVideoMode vm;
vm = mWindow->getVideoMode();
vm.resolution.x = pp.BufferDesc.Width;
vm.resolution.y = pp.BufferDesc.Height;
vm.fullScreen = !pp.Windowed;
mSize = vm.resolution;
}
void GFXD3D11WindowTarget::resolveTo(GFXTextureObject *tex)
{
GFXDEBUGEVENT_SCOPE(GFXPCD3D11WindowTarget_resolveTo, ColorI::RED);
D3D11_TEXTURE2D_DESC desc;
ID3D11Texture2D* surf = ((GFXD3D11TextureObject*)(tex))->get2DTex();
surf->GetDesc(&desc);
D3D11DEVICECONTEXT->ResolveSubresource(surf, 0, D3D11->mDeviceBackbuffer, 0, desc.Format);
}

View file

@ -0,0 +1,110 @@
//-----------------------------------------------------------------------------
// Copyright (c) 2015 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#ifndef _GFX_D3D_GFXD3D11TARGET_H_
#define _GFX_D3D_GFXD3D11TARGET_H_
#include "gfx/D3D11/gfxD3D11Device.h"
#include "gfx/D3D11/gfxD3D11TextureObject.h"
#include "gfx/gfxTarget.h"
#include "math/mPoint3.h"
#include "math/mPoint2.h"
class GFXD3D11TextureTarget : public GFXTextureTarget
{
friend class GFXD3D11Device;
// Array of target surfaces, this is given to us by attachTexture
ID3D11Texture2D* mTargets[MaxRenderSlotId];
// Array of shader resource views
ID3D11ShaderResourceView* mTargetSRViews[MaxRenderSlotId];
//ID3D11DepthStencilView* mDepthTargetView;
ID3D11View* mTargetViews[MaxRenderSlotId];
// Array of texture objects which correspond to the target surfaces above,
// needed for copy from RenderTarget to texture situations. Current only valid in those situations
GFXD3D11TextureObject* mResolveTargets[MaxRenderSlotId];
Point2I mTargetSize;
GFXFormat mTargetFormat;
public:
GFXD3D11TextureTarget();
~GFXD3D11TextureTarget();
// Public interface.
virtual const Point2I getSize() { return mTargetSize; }
virtual GFXFormat getFormat() { return mTargetFormat; }
virtual void attachTexture(RenderSlot slot, GFXTextureObject *tex, U32 mipLevel=0, U32 zOffset = 0);
virtual void attachTexture(RenderSlot slot, GFXCubemap *tex, U32 face, U32 mipLevel=0);
virtual void resolve();
/// Note we always copy the Color0 RenderSlot.
virtual void resolveTo( GFXTextureObject *tex );
virtual void activate();
virtual void deactivate();
void zombify();
void resurrect();
};
class GFXD3D11WindowTarget : public GFXWindowTarget
{
friend class GFXD3D11Device;
/// Our backbuffer
ID3D11Texture2D *mBackbuffer;
/// Maximum size we can render to.
Point2I mSize;
/// D3D presentation info.
DXGI_SWAP_CHAIN_DESC mPresentationParams;
/// Internal interface that notifies us we need to reset our video mode.
void resetMode();
public:
GFXD3D11WindowTarget();
~GFXD3D11WindowTarget();
virtual const Point2I getSize();
virtual GFXFormat getFormat();
virtual bool present();
void initPresentationParams();
void setImplicitSwapChain();
virtual void activate();
void zombify();
void resurrect();
virtual void resolveTo( GFXTextureObject *tex );
};
#endif

View file

@ -0,0 +1,587 @@
//-----------------------------------------------------------------------------
// Copyright (c) 2015 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#include "gfx/D3D11/gfxD3D11Device.h"
#include "gfx/D3D11/gfxD3D11EnumTranslate.h"
#include "gfx/bitmap/bitmapUtils.h"
#include "gfx/gfxCardProfile.h"
#include "gfx/gfxStringEnumTranslate.h"
#include "core/strings/unicode.h"
#include "core/util/swizzle.h"
#include "core/util/safeDelete.h"
#include "console/console.h"
#include "core/resourceManager.h"
GFXD3D11TextureManager::GFXD3D11TextureManager()
{
ZeroMemory(mCurTexSet, sizeof(mCurTexSet));
}
GFXD3D11TextureManager::~GFXD3D11TextureManager()
{
// Destroy texture table now so just in case some texture objects
// are still left, we don't crash on a pure virtual method call.
SAFE_DELETE_ARRAY( mHashTable );
}
void GFXD3D11TextureManager::_innerCreateTexture( GFXD3D11TextureObject *retTex,
U32 height,
U32 width,
U32 depth,
GFXFormat format,
GFXTextureProfile *profile,
U32 numMipLevels,
bool forceMips,
S32 antialiasLevel)
{
U32 usage = 0;
U32 bindFlags = 0;
U32 miscFlags = 0;
if(!retTex->mProfile->isZTarget() && !retTex->mProfile->isSystemMemory())
bindFlags = D3D11_BIND_SHADER_RESOURCE;
U32 cpuFlags = 0;
retTex->mProfile = profile;
retTex->isManaged = false;
DXGI_FORMAT d3dTextureFormat = GFXD3D11TextureFormat[format];
if( retTex->mProfile->isDynamic() )
{
usage = D3D11_USAGE_DYNAMIC;
cpuFlags |= D3D11_CPU_ACCESS_WRITE;
retTex->isManaged = false;
}
else if ( retTex->mProfile->isSystemMemory() )
{
usage |= D3D11_USAGE_STAGING;
cpuFlags |= D3D11_CPU_ACCESS_READ;
}
else
{
usage = D3D11_USAGE_DEFAULT;
retTex->isManaged = true;
}
if( retTex->mProfile->isRenderTarget() )
{
bindFlags |= D3D11_BIND_RENDER_TARGET;
//need to check to make sure this format supports render targets
U32 supportFlag = 0;
D3D11DEVICE->CheckFormatSupport(d3dTextureFormat, &supportFlag);
//if it doesn't support render targets then default to R8G8B8A8
if(!(supportFlag & D3D11_FORMAT_SUPPORT_RENDER_TARGET))
d3dTextureFormat = DXGI_FORMAT_R8G8B8A8_UNORM;
retTex->isManaged =false;
}
if( retTex->mProfile->isZTarget() )
{
bindFlags |= D3D11_BIND_DEPTH_STENCIL;
retTex->isManaged = false;
}
if( !forceMips && !retTex->mProfile->isSystemMemory() &&
numMipLevels == 0 &&
!(depth > 0) )
{
miscFlags |= D3D11_RESOURCE_MISC_GENERATE_MIPS;
bindFlags |= D3D11_BIND_RENDER_TARGET; // in order to automatically generate mips. Resource needs to be a rendertarget and shader resource
}
if( depth > 0 )
{
D3D11_TEXTURE3D_DESC desc;
ZeroMemory(&desc, sizeof(D3D11_TEXTURE3D_DESC));
desc.BindFlags = bindFlags;
desc.CPUAccessFlags = cpuFlags;
desc.Depth = depth;
desc.Width = width;
desc.Height = height;
desc.Format = d3dTextureFormat;
desc.Usage = (D3D11_USAGE)usage;
desc.MipLevels = numMipLevels;
HRESULT hr = D3D11DEVICE->CreateTexture3D(&desc, NULL, retTex->get3DTexPtr());
if(FAILED(hr))
{
AssertFatal(false, "GFXD3D11TextureManager::_createTexture - failed to create volume texture!");
}
retTex->mTextureSize.set(width, height, depth);
retTex->get3DTex()->GetDesc(&desc);
retTex->mMipLevels = numMipLevels;
retTex->mFormat = format;
}
else
{
UINT numQualityLevels = 0;
switch (antialiasLevel)
{
case 0:
case AA_MATCH_BACKBUFFER:
antialiasLevel = 1;
break;
default:
{
antialiasLevel = 0;
UINT numQualityLevels;
D3D11DEVICE->CheckMultisampleQualityLevels(d3dTextureFormat, antialiasLevel, &numQualityLevels);
AssertFatal(numQualityLevels, "Invalid AA level!");
break;
}
}
if(retTex->mProfile->isZTarget())
{
D3D11_TEXTURE2D_DESC desc;
ZeroMemory(&desc, sizeof(D3D11_TEXTURE2D_DESC));
desc.ArraySize = 1;
desc.BindFlags = bindFlags;
desc.CPUAccessFlags = cpuFlags;
//depth stencil must be a typeless format if it is bound on render target and shader resource simultaneously
// we'll send the real format for the creation of the views
desc.Format = DXGI_FORMAT_R24G8_TYPELESS;
desc.MipLevels = numMipLevels;
desc.SampleDesc.Count = antialiasLevel;
desc.SampleDesc.Quality = numQualityLevels;
desc.Height = height;
desc.Width = width;
desc.Usage = (D3D11_USAGE)usage;
HRESULT hr = D3D11DEVICE->CreateTexture2D(&desc, NULL, retTex->getSurfacePtr());
if(FAILED(hr))
{
AssertFatal(false, "Failed to create Zbuffer texture");
}
retTex->mFormat = format; // Assigning format like this should be fine.
}
else
{
D3D11_TEXTURE2D_DESC desc;
ZeroMemory(&desc, sizeof(D3D11_TEXTURE2D_DESC));
desc.ArraySize = 1;
desc.BindFlags = bindFlags;
desc.CPUAccessFlags = cpuFlags;
desc.Format = d3dTextureFormat;
desc.MipLevels = numMipLevels;
desc.SampleDesc.Count = antialiasLevel;
desc.SampleDesc.Quality = numQualityLevels;
desc.Height = height;
desc.Width = width;
desc.Usage = (D3D11_USAGE)usage;
desc.MiscFlags = miscFlags;
HRESULT hr = D3D11DEVICE->CreateTexture2D(&desc, NULL, retTex->get2DTexPtr());
if(FAILED(hr))
{
AssertFatal(false, "GFXD3D11TextureManager::_createTexture - failed to create texture!");
}
retTex->get2DTex()->GetDesc(&desc);
retTex->mMipLevels = desc.MipLevels;
}
// start creating the resource views...
// don't bother creating views for system memory/staging textures
// they are just used for copying
if (!retTex->mProfile->isSystemMemory())
{
createResourceView(height, width, depth, d3dTextureFormat, numMipLevels, bindFlags, retTex);
}
// Get the actual size of the texture...
D3D11_TEXTURE2D_DESC probeDesc;
ZeroMemory(&probeDesc, sizeof(D3D11_TEXTURE2D_DESC));
if( retTex->get2DTex() != NULL )
{
retTex->get2DTex()->GetDesc(&probeDesc);
}
else if( retTex->getSurface() != NULL )
{
retTex->getSurface()->GetDesc(&probeDesc);
}
retTex->mTextureSize.set(probeDesc.Width, probeDesc.Height, 0);
S32 fmt = 0;
if(!profile->isZTarget())
fmt = probeDesc.Format;
else
fmt = DXGI_FORMAT_D24_UNORM_S8_UINT; // we need to assign this manually.
GFXREVERSE_LOOKUP( GFXD3D11TextureFormat, GFXFormat, fmt );
retTex->mFormat = (GFXFormat)fmt;
}
}
//-----------------------------------------------------------------------------
// createTexture
//-----------------------------------------------------------------------------
GFXTextureObject *GFXD3D11TextureManager::_createTextureObject( U32 height,
U32 width,
U32 depth,
GFXFormat format,
GFXTextureProfile *profile,
U32 numMipLevels,
bool forceMips,
S32 antialiasLevel,
GFXTextureObject *inTex )
{
GFXD3D11TextureObject *retTex;
if ( inTex )
{
AssertFatal(static_cast<GFXD3D11TextureObject*>( inTex ), "GFXD3D11TextureManager::_createTexture() - Bad inTex type!");
retTex = static_cast<GFXD3D11TextureObject*>( inTex );
retTex->release();
}
else
{
retTex = new GFXD3D11TextureObject(GFX, profile);
retTex->registerResourceWithDevice(GFX);
}
_innerCreateTexture(retTex, height, width, depth, format, profile, numMipLevels, forceMips, antialiasLevel);
return retTex;
}
bool GFXD3D11TextureManager::_loadTexture(GFXTextureObject *aTexture, GBitmap *pDL)
{
PROFILE_SCOPE(GFXD3D11TextureManager_loadTexture);
GFXD3D11TextureObject *texture = static_cast<GFXD3D11TextureObject*>(aTexture);
// Check with profiler to see if we can do automatic mipmap generation.
const bool supportsAutoMips = GFX->getCardProfiler()->queryProfile("autoMipMapLevel", true);
// Helper bool
const bool isCompressedTexFmt = aTexture->mFormat >= GFXFormatDXT1 && aTexture->mFormat <= GFXFormatDXT5;
// Settings for mipmap generation
U32 maxDownloadMip = pDL->getNumMipLevels();
U32 nbMipMapLevel = pDL->getNumMipLevels();
if( supportsAutoMips && !isCompressedTexFmt )
{
maxDownloadMip = 1;
nbMipMapLevel = aTexture->mMipLevels;
}
GFXD3D11Device* dev = D3D11;
bool isDynamic = texture->mProfile->isDynamic();
// Fill the texture...
for( U32 i = 0; i < maxDownloadMip; i++ )
{
U32 subResource = D3D11CalcSubresource(i, 0, aTexture->mMipLevels);
if(!isDynamic)
{
U8* copyBuffer = NULL;
switch(texture->mFormat)
{
case GFXFormatR8G8B8:
{
PROFILE_SCOPE(Swizzle24_Upload);
AssertFatal(pDL->getFormat() == GFXFormatR8G8B8, "Assumption failed");
U8* Bits = new U8[pDL->getWidth(i) * pDL->getHeight(i) * 4];
dMemcpy(Bits, pDL->getBits(i), pDL->getWidth(i) * pDL->getHeight(i) * 3);
bitmapConvertRGB_to_RGBX(&Bits, pDL->getWidth(i) * pDL->getHeight(i));
copyBuffer = new U8[pDL->getWidth(i) * pDL->getHeight(i) * 4];
dev->getDeviceSwizzle32()->ToBuffer(copyBuffer, Bits, pDL->getWidth(i) * pDL->getHeight(i) * 4);
dev->getDeviceContext()->UpdateSubresource(texture->get2DTex(), subResource, NULL, copyBuffer, pDL->getWidth() * 4, pDL->getHeight() *4);
SAFE_DELETE_ARRAY(Bits);
break;
}
case GFXFormatR8G8B8A8:
case GFXFormatR8G8B8X8:
{
PROFILE_SCOPE(Swizzle32_Upload);
copyBuffer = new U8[pDL->getWidth(i) * pDL->getHeight(i) * pDL->getBytesPerPixel()];
dev->getDeviceSwizzle32()->ToBuffer(copyBuffer, pDL->getBits(i), pDL->getWidth(i) * pDL->getHeight(i) * pDL->getBytesPerPixel());
dev->getDeviceContext()->UpdateSubresource(texture->get2DTex(), subResource, NULL, copyBuffer, pDL->getWidth() * pDL->getBytesPerPixel(), pDL->getHeight() *pDL->getBytesPerPixel());
break;
}
default:
{
// Just copy the bits in no swizzle or padding
PROFILE_SCOPE(SwizzleNull_Upload);
AssertFatal( pDL->getFormat() == texture->mFormat, "Format mismatch");
dev->getDeviceContext()->UpdateSubresource(texture->get2DTex(), subResource, NULL, pDL->getBits(i), pDL->getWidth() *pDL->getBytesPerPixel(), pDL->getHeight() *pDL->getBytesPerPixel());
}
}
SAFE_DELETE_ARRAY(copyBuffer);
}
else
{
D3D11_MAPPED_SUBRESOURCE mapping;
HRESULT res = dev->getDeviceContext()->Map(texture->get2DTex(), subResource, D3D11_MAP_WRITE, 0, &mapping);
AssertFatal(res, "tex2d map call failure");
switch( texture->mFormat )
{
case GFXFormatR8G8B8:
{
PROFILE_SCOPE(Swizzle24_Upload);
AssertFatal(pDL->getFormat() == GFXFormatR8G8B8, "Assumption failed");
U8* Bits = new U8[pDL->getWidth(i) * pDL->getHeight(i) * 4];
dMemcpy(Bits, pDL->getBits(i), pDL->getWidth(i) * pDL->getHeight(i) * 3);
bitmapConvertRGB_to_RGBX(&Bits, pDL->getWidth(i) * pDL->getHeight(i));
dev->getDeviceSwizzle32()->ToBuffer(mapping.pData, Bits, pDL->getWidth(i) * pDL->getHeight(i) * 4);
SAFE_DELETE_ARRAY(Bits);
}
break;
case GFXFormatR8G8B8A8:
case GFXFormatR8G8B8X8:
{
PROFILE_SCOPE(Swizzle32_Upload);
dev->getDeviceSwizzle32()->ToBuffer(mapping.pData, pDL->getBits(i), pDL->getWidth(i) * pDL->getHeight(i) * pDL->getBytesPerPixel());
}
break;
default:
{
// Just copy the bits in no swizzle or padding
PROFILE_SCOPE(SwizzleNull_Upload);
AssertFatal( pDL->getFormat() == texture->mFormat, "Format mismatch");
dMemcpy(mapping.pData, pDL->getBits(i), pDL->getWidth(i) * pDL->getHeight(i) * pDL->getBytesPerPixel());
}
}
dev->getDeviceContext()->Unmap(texture->get2DTex(), subResource);
}
}
D3D11_TEXTURE2D_DESC desc;
// if the texture asked for mip generation. lets generate it.
texture->get2DTex()->GetDesc(&desc);
if (desc.MiscFlags &D3D11_RESOURCE_MISC_GENERATE_MIPS)
{
dev->getDeviceContext()->GenerateMips(texture->getSRView());
//texture->mMipLevels = desc.MipLevels;
}
return true;
}
bool GFXD3D11TextureManager::_loadTexture(GFXTextureObject *inTex, void *raw)
{
PROFILE_SCOPE(GFXD3D11TextureManager_loadTextureRaw);
GFXD3D11TextureObject *texture = (GFXD3D11TextureObject *) inTex;
GFXD3D11Device* dev = static_cast<GFXD3D11Device *>(GFX);
// currently only for volume textures...
if(texture->getDepth() < 1) return false;
U8* Bits = NULL;
if(texture->mFormat == GFXFormatR8G8B8)
{
// convert 24 bit to 32 bit
Bits = new U8[texture->getWidth() * texture->getHeight() * texture->getDepth() * 4];
dMemcpy(Bits, raw, texture->getWidth() * texture->getHeight() * texture->getDepth() * 3);
bitmapConvertRGB_to_RGBX(&Bits, texture->getWidth() * texture->getHeight() * texture->getDepth());
}
U32 bytesPerPix = 1;
switch(texture->mFormat)
{
case GFXFormatR8G8B8:
case GFXFormatR8G8B8A8:
case GFXFormatR8G8B8X8:
bytesPerPix = 4;
break;
}
D3D11_BOX box;
box.left = 0;
box.right = texture->getWidth();
box.front = 0;
box.back = texture->getDepth();
box.top = 0;
box.bottom = texture->getHeight();
if(texture->mFormat == GFXFormatR8G8B8) // converted format also for volume textures
dev->getDeviceContext()->UpdateSubresource(texture->get3DTex(), 0, &box, Bits, texture->getWidth() * bytesPerPix, texture->getHeight() * bytesPerPix);
else
dev->getDeviceContext()->UpdateSubresource(texture->get3DTex(), 0, &box, raw, texture->getWidth() * bytesPerPix, texture->getHeight() * bytesPerPix);
SAFE_DELETE_ARRAY(Bits);
return true;
}
bool GFXD3D11TextureManager::_refreshTexture(GFXTextureObject *texture)
{
U32 usedStrategies = 0;
GFXD3D11TextureObject *realTex = static_cast<GFXD3D11TextureObject *>(texture);
if(texture->mProfile->doStoreBitmap())
{
if(texture->mBitmap)
_loadTexture(texture, texture->mBitmap);
if(texture->mDDS)
_loadTexture(texture, texture->mDDS);
usedStrategies++;
}
if(texture->mProfile->isRenderTarget() || texture->mProfile->isDynamic() || texture->mProfile->isZTarget())
{
realTex->release();
_innerCreateTexture(realTex, texture->getHeight(), texture->getWidth(), texture->getDepth(), texture->mFormat, texture->mProfile, texture->mMipLevels, false, texture->mAntialiasLevel);
usedStrategies++;
}
AssertFatal(usedStrategies < 2, "GFXD3D11TextureManager::_refreshTexture - Inconsistent profile flags!");
return true;
}
bool GFXD3D11TextureManager::_freeTexture(GFXTextureObject *texture, bool zombify)
{
AssertFatal(dynamic_cast<GFXD3D11TextureObject *>(texture),"Not an actual d3d texture object!");
GFXD3D11TextureObject *tex = static_cast<GFXD3D11TextureObject *>( texture );
// If it's a managed texture and we're zombifying, don't blast it, D3D allows
// us to keep it.
if(zombify && tex->isManaged)
return true;
tex->release();
return true;
}
/// Load a texture from a proper DDSFile instance.
bool GFXD3D11TextureManager::_loadTexture(GFXTextureObject *aTexture, DDSFile *dds)
{
PROFILE_SCOPE(GFXD3D11TextureManager_loadTextureDDS);
GFXD3D11TextureObject *texture = static_cast<GFXD3D11TextureObject*>(aTexture);
GFXD3D11Device* dev = static_cast<GFXD3D11Device *>(GFX);
// Fill the texture...
for( U32 i = 0; i < aTexture->mMipLevels; i++ )
{
PROFILE_SCOPE(GFXD3DTexMan_loadSurface);
AssertFatal( dds->mSurfaces.size() > 0, "Assumption failed. DDSFile has no surfaces." );
U32 subresource = D3D11CalcSubresource(i, 0, aTexture->mMipLevels);
dev->getDeviceContext()->UpdateSubresource(texture->get2DTex(), subresource, 0, dds->mSurfaces[0]->mMips[i], dds->getSurfacePitch(i), 0);
}
D3D11_TEXTURE2D_DESC desc;
// if the texture asked for mip generation. lets generate it.
texture->get2DTex()->GetDesc(&desc);
if (desc.MiscFlags & D3D11_RESOURCE_MISC_GENERATE_MIPS)
dev->getDeviceContext()->GenerateMips(texture->getSRView());
return true;
}
void GFXD3D11TextureManager::createResourceView(U32 height, U32 width, U32 depth, DXGI_FORMAT format, U32 numMipLevels,U32 usageFlags, GFXTextureObject *inTex)
{
GFXD3D11TextureObject *tex = static_cast<GFXD3D11TextureObject*>(inTex);
ID3D11Resource* resource = NULL;
if(tex->get2DTex())
resource = tex->get2DTex();
else if(tex->getSurface())
resource = tex->getSurface();
else
resource = tex->get3DTex();
HRESULT hr;
//TODO: add MSAA support later.
if(usageFlags & D3D11_BIND_SHADER_RESOURCE)
{
D3D11_SHADER_RESOURCE_VIEW_DESC desc;
if(usageFlags & D3D11_BIND_DEPTH_STENCIL)
desc.Format = DXGI_FORMAT_R24_UNORM_X8_TYPELESS; // reads the depth
else
desc.Format = format;
if(depth > 0)
{
desc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE3D;
desc.Texture3D.MipLevels = -1;
desc.Texture3D.MostDetailedMip = 0;
}
else
{
desc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
desc.Texture2D.MipLevels = -1;
desc.Texture2D.MostDetailedMip = 0;
}
hr = D3D11DEVICE->CreateShaderResourceView(resource,&desc, tex->getSRViewPtr());
AssertFatal(SUCCEEDED(hr), "CreateShaderResourceView:: failed to create view!");
}
if(usageFlags & D3D11_BIND_RENDER_TARGET)
{
D3D11_RENDER_TARGET_VIEW_DESC desc;
desc.Format = format;
desc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D;
desc.Texture2D.MipSlice = 0;
hr = D3D11DEVICE->CreateRenderTargetView(resource, &desc, tex->getRTViewPtr());
AssertFatal(SUCCEEDED(hr), "CreateRenderTargetView:: failed to create view!");
}
if(usageFlags & D3D11_BIND_DEPTH_STENCIL)
{
D3D11_DEPTH_STENCIL_VIEW_DESC desc;
desc.Format = format;
desc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
desc.Texture2D.MipSlice = 0;
desc.Flags = 0;
hr = D3D11DEVICE->CreateDepthStencilView(resource,&desc, tex->getDSViewPtr());
AssertFatal(SUCCEEDED(hr), "CreateDepthStencilView:: failed to create view!");
}
}

View file

@ -0,0 +1,62 @@
//-----------------------------------------------------------------------------
// Copyright (c) 2015 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#ifndef _GFXD3DTEXTUREMANAGER_H_
#define _GFXD3DTEXTUREMANAGER_H_
#include "gfx/D3D11/gfxD3D11TextureObject.h"
#include "core/util/safeRelease.h"
class GFXD3D11TextureManager : public GFXTextureManager
{
friend class GFXD3D11TextureObject;
public:
GFXD3D11TextureManager();
virtual ~GFXD3D11TextureManager();
void createResourceView(U32 height, U32 width, U32 depth, DXGI_FORMAT format, U32 numMipLevels,U32 usageFlags, GFXTextureObject *inTex);
protected:
// GFXTextureManager
GFXTextureObject *_createTextureObject( U32 height,
U32 width,
U32 depth,
GFXFormat format,
GFXTextureProfile *profile,
U32 numMipLevels,
bool forceMips = false,
S32 antialiasLevel = 0,
GFXTextureObject *inTex = NULL );
bool _loadTexture(GFXTextureObject *texture, DDSFile *dds);
bool _loadTexture(GFXTextureObject *texture, GBitmap *bmp);
bool _loadTexture(GFXTextureObject *texture, void *raw);
bool _refreshTexture(GFXTextureObject *texture);
bool _freeTexture(GFXTextureObject *texture, bool zombify = false);
private:
U32 mCurTexSet[TEXTURE_STAGE_COUNT];
void _innerCreateTexture(GFXD3D11TextureObject *obj, U32 height, U32 width, U32 depth, GFXFormat format, GFXTextureProfile *profile, U32 numMipLevels, bool forceMips = false, S32 antialiasLevel = 0);
};
#endif

View file

@ -0,0 +1,280 @@
//-----------------------------------------------------------------------------
// Copyright (c) 2015 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#include "gfx/D3D11/gfxD3D11Device.h"
#include "gfx/D3D11/gfxD3D11TextureObject.h"
#include "platform/profiler.h"
#include "console/console.h"
#ifdef TORQUE_DEBUG
U32 GFXD3D11TextureObject::mTexCount = 0;
#endif
// GFXFormatR8G8B8 has now the same behaviour as GFXFormatR8G8B8X8.
// This is because 24 bit format are now deprecated by microsoft, for data alignment reason there's no changes beetween 24 and 32 bit formats.
// DirectX 10-11 both have 24 bit format no longer.
GFXD3D11TextureObject::GFXD3D11TextureObject( GFXDevice * d, GFXTextureProfile *profile) : GFXTextureObject( d, profile )
{
#ifdef D3D11_DEBUG_SPEW
mTexCount++;
Con::printf("+ texMake %d %x", mTexCount, this);
#endif
mD3DTexture = NULL;
mLocked = false;
mD3DSurface = NULL;
mLockedSubresource = 0;
mDSView = NULL;
mRTView = NULL;
mSRView = NULL;
}
GFXD3D11TextureObject::~GFXD3D11TextureObject()
{
kill();
#ifdef D3D11_DEBUG_SPEW
mTexCount--;
Con::printf("+ texkill %d %x", mTexCount, this);
#endif
}
GFXLockedRect *GFXD3D11TextureObject::lock(U32 mipLevel /*= 0*/, RectI *inRect /*= NULL*/)
{
AssertFatal( !mLocked, "GFXD3D11TextureObject::lock - The texture is already locked!" );
D3D11_MAPPED_SUBRESOURCE mapInfo;
if( mProfile->isRenderTarget() )
{
//AssertFatal( 0, "GFXD3D11TextureObject::lock - Need to handle mapping render targets" );
if( !mLockTex ||
mLockTex->getWidth() != getWidth() ||
mLockTex->getHeight() != getHeight() )
{
mLockTex.set( getWidth(), getHeight(), mFormat, &GFXSystemMemProfile, avar("%s() - mLockTex (line %d)", __FUNCTION__, __LINE__) );
}
PROFILE_START(GFXD3D11TextureObject_lockRT);
GFXD3D11Device* dev = D3D11;
GFXD3D11TextureObject* to = (GFXD3D11TextureObject*) &(*mLockTex);
dev->getDeviceContext()->CopyResource(to->get2DTex(), mD3DTexture);
mLockedSubresource = D3D11CalcSubresource(0, 0, 1);
HRESULT hr = dev->getDeviceContext()->Map(to->get2DTex(), mLockedSubresource, D3D11_MAP_READ, 0, &mapInfo);
if (FAILED(hr))
AssertFatal(false, "GFXD3D11TextureObject:lock- failed to map render target resource!");
mLocked = true;
PROFILE_END();
}
else
{
RECT r;
if(inRect)
{
r.top = inRect->point.y;
r.left = inRect->point.x;
r.bottom = inRect->point.y + inRect->extent.y;
r.right = inRect->point.x + inRect->extent.x;
}
mLockedSubresource = D3D11CalcSubresource(mipLevel, 0, getMipLevels());
HRESULT hr = D3D11DEVICECONTEXT->Map(mD3DTexture, mLockedSubresource, D3D11_MAP_WRITE_DISCARD, 0, &mapInfo);
if ( FAILED(hr) )
AssertFatal(false, "GFXD3D11TextureObject::lock - Failed to map subresource.");
mLocked = true;
}
mLockRect.pBits = static_cast<U8*>(mapInfo.pData);
mLockRect.Pitch = mapInfo.RowPitch;
return (GFXLockedRect*)&mLockRect;
}
void GFXD3D11TextureObject::unlock(U32 mipLevel)
{
AssertFatal( mLocked, "GFXD3D11TextureObject::unlock - Attempting to unlock a surface that has not been locked" );
if( mProfile->isRenderTarget() )
{
//AssertFatal( 0, "GFXD3D11TextureObject::unlock - Need to handle mapping render targets" );
GFXD3D11TextureObject* to = (GFXD3D11TextureObject*)&(*mLockTex);
D3D11->getDeviceContext()->Unmap(to->get2DTex(), mLockedSubresource);
mLockedSubresource = 0;
mLocked = false;
}
else
{
D3D11DEVICECONTEXT->Unmap(get2DTex(), mLockedSubresource);
mLockedSubresource = 0;
mLocked = false;
}
}
void GFXD3D11TextureObject::release()
{
SAFE_RELEASE(mSRView);
SAFE_RELEASE(mRTView);
SAFE_RELEASE(mDSView);
SAFE_RELEASE(mD3DTexture);
SAFE_RELEASE(mD3DSurface);
}
void GFXD3D11TextureObject::zombify()
{
// Managed textures are managed by D3D
AssertFatal(!mLocked, "GFXD3D11TextureObject::zombify - Cannot zombify a locked texture!");
if(isManaged)
return;
release();
}
void GFXD3D11TextureObject::resurrect()
{
// Managed textures are managed by D3D
if(isManaged)
return;
static_cast<GFXD3D11TextureManager*>(TEXMGR)->refreshTexture(this);
}
bool GFXD3D11TextureObject::copyToBmp(GBitmap* bmp)
{
if (!bmp)
return false;
// check format limitations
// at the moment we only support RGBA for the source (other 4 byte formats should
// be easy to add though)
AssertFatal(mFormat == GFXFormatR8G8B8A8, "copyToBmp: invalid format");
if (mFormat != GFXFormatR8G8B8A8)
return false;
PROFILE_START(GFXD3D11TextureObject_copyToBmp);
AssertFatal(bmp->getWidth() == getWidth(), "doh");
AssertFatal(bmp->getHeight() == getHeight(), "doh");
U32 width = getWidth();
U32 height = getHeight();
bmp->setHasTransparency(mHasTransparency);
// set some constants
const U32 sourceBytesPerPixel = 4;
U32 destBytesPerPixel = 0;
if(bmp->getFormat() == GFXFormatR8G8B8A8)
destBytesPerPixel = 4;
else if(bmp->getFormat() == GFXFormatR8G8B8)
destBytesPerPixel = 3;
else
// unsupported
AssertFatal(false, "unsupported bitmap format");
// lock the texture
DXGI_MAPPED_RECT* lockRect = (DXGI_MAPPED_RECT*) lock();
// set pointers
U8* srcPtr = (U8*)lockRect->pBits;
U8* destPtr = bmp->getWritableBits();
// we will want to skip over any D3D cache data in the source texture
const S32 sourceCacheSize = lockRect->Pitch - width * sourceBytesPerPixel;
AssertFatal(sourceCacheSize >= 0, "copyToBmp: cache size is less than zero?");
PROFILE_START(GFXD3D11TextureObject_copyToBmp_pixCopy);
// copy data into bitmap
for (U32 row = 0; row < height; ++row)
{
for (U32 col = 0; col < width; ++col)
{
destPtr[0] = srcPtr[2]; // red
destPtr[1] = srcPtr[1]; // green
destPtr[2] = srcPtr[0]; // blue
if (destBytesPerPixel == 4)
destPtr[3] = srcPtr[3]; // alpha
// go to next pixel in src
srcPtr += sourceBytesPerPixel;
// go to next pixel in dest
destPtr += destBytesPerPixel;
}
// skip past the cache data for this row (if any)
srcPtr += sourceCacheSize;
}
PROFILE_END();
// assert if we stomped or underran memory
AssertFatal(U32(destPtr - bmp->getWritableBits()) == width * height * destBytesPerPixel, "copyToBmp: doh, memory error");
AssertFatal(U32(srcPtr - (U8*)lockRect->pBits) == height * lockRect->Pitch, "copyToBmp: doh, memory error");
// unlock
unlock();
PROFILE_END();
return true;
}
ID3D11ShaderResourceView* GFXD3D11TextureObject::getSRView()
{
return mSRView;
}
ID3D11RenderTargetView* GFXD3D11TextureObject::getRTView()
{
return mRTView;
}
ID3D11DepthStencilView* GFXD3D11TextureObject::getDSView()
{
return mDSView;
}
ID3D11ShaderResourceView** GFXD3D11TextureObject::getSRViewPtr()
{
return &mSRView;
}
ID3D11RenderTargetView** GFXD3D11TextureObject::getRTViewPtr()
{
return &mRTView;
}
ID3D11DepthStencilView** GFXD3D11TextureObject::getDSViewPtr()
{
return &mDSView;
}

View file

@ -0,0 +1,89 @@
//-----------------------------------------------------------------------------
// Copyright (c) 2015 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#ifndef _GFXD3D11TEXTUREOBJECT_H_
#define _GFXD3D11TEXTUREOBJECT_H_
#include "gfx/D3D11/gfxD3D11Device.h"
#include "gfx/gfxTextureHandle.h"
#include "gfx/gfxTextureManager.h"
class GFXD3D11TextureObject : public GFXTextureObject
{
protected:
static U32 mTexCount;
GFXTexHandle mLockTex;
DXGI_MAPPED_RECT mLockRect;
bool mLocked;
U32 mLockedSubresource;
ID3D11Resource *mD3DTexture;
// used for z buffers...
ID3D11Texture2D *mD3DSurface;
ID3D11ShaderResourceView* mSRView; // for shader resource input
ID3D11RenderTargetView* mRTView; // for render targets
ID3D11DepthStencilView* mDSView; //render target view for depth stencil
public:
GFXD3D11TextureObject( GFXDevice * d, GFXTextureProfile *profile);
~GFXD3D11TextureObject();
ID3D11Resource* getResource(){ return mD3DTexture; }
ID3D11Texture2D* get2DTex(){ return (ID3D11Texture2D*) mD3DTexture; }
ID3D11Texture2D** get2DTexPtr(){ return (ID3D11Texture2D**) &mD3DTexture; }
ID3D11Texture3D* get3DTex(){ return (ID3D11Texture3D*) mD3DTexture; }
ID3D11Texture3D** get3DTexPtr(){ return (ID3D11Texture3D**) &mD3DTexture; }
ID3D11ShaderResourceView* getSRView();
ID3D11RenderTargetView* getRTView();
ID3D11DepthStencilView* getDSView();
ID3D11ShaderResourceView** getSRViewPtr();
ID3D11RenderTargetView** getRTViewPtr();
ID3D11DepthStencilView** getDSViewPtr();
void release();
bool isManaged; //setting to true tells this texture not to be released from being zombify
virtual GFXLockedRect * lock(U32 mipLevel = 0, RectI *inRect = NULL);
virtual void unlock(U32 mipLevel = 0 );
virtual bool copyToBmp(GBitmap* bmp);
ID3D11Texture2D* getSurface() {return mD3DSurface;}
ID3D11Texture2D** getSurfacePtr() {return &mD3DSurface;}
// GFXResource
void zombify();
void resurrect();
#ifdef TORQUE_DEBUG
virtual void pureVirtualCrash() {};
#endif
};
#endif

View file

@ -0,0 +1,233 @@
//-----------------------------------------------------------------------------
// Copyright (c) 2015 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#include "platform/platform.h"
#include "gfx/D3D11/gfxD3D11VertexBuffer.h"
#include "console/console.h"
GFXD3D11VertexBuffer::~GFXD3D11VertexBuffer()
{
if(getOwningDevice() != NULL)
{
if(mBufferType != GFXBufferTypeVolatile)
{
SAFE_RELEASE(vb);
}
}
}
void GFXD3D11VertexBuffer::lock(U32 vertexStart, U32 vertexEnd, void **vertexPtr)
{
PROFILE_SCOPE(GFXD3D11VertexBuffer_lock);
AssertFatal(lockedVertexStart == 0 && lockedVertexEnd == 0, "Cannot lock a buffer more than once!");
D3D11_MAP flags = D3D11_MAP_WRITE_DISCARD;
switch(mBufferType)
{
case GFXBufferTypeStatic:
case GFXBufferTypeDynamic:
flags = D3D11_MAP_WRITE_DISCARD;
break;
case GFXBufferTypeVolatile:
// Get or create the volatile buffer...
mVolatileBuffer = D3D11->findVBPool( &mVertexFormat, vertexEnd );
if( !mVolatileBuffer )
mVolatileBuffer = D3D11->createVBPool( &mVertexFormat, mVertexSize );
vb = mVolatileBuffer->vb;
// Get our range now...
AssertFatal(vertexStart == 0, "Cannot get a subrange on a volatile buffer.");
AssertFatal(vertexEnd <= MAX_DYNAMIC_VERTS, "Cannot get more than MAX_DYNAMIC_VERTS in a volatile buffer. Up the constant!");
AssertFatal(mVolatileBuffer->lockedVertexStart == 0 && mVolatileBuffer->lockedVertexEnd == 0, "Got more than one lock on the volatile pool.");
// We created the pool when we requested this volatile buffer, so assume it exists...
if( mVolatileBuffer->mNumVerts + vertexEnd > MAX_DYNAMIC_VERTS )
{
flags = D3D11_MAP_WRITE_DISCARD;
mVolatileStart = vertexStart = 0;
vertexEnd = vertexEnd;
}
else
{
flags = D3D11_MAP_WRITE_NO_OVERWRITE;
mVolatileStart = vertexStart = mVolatileBuffer->mNumVerts;
vertexEnd += mVolatileBuffer->mNumVerts;
}
mVolatileBuffer->mNumVerts = vertexEnd+1;
mVolatileBuffer->lockedVertexStart = vertexStart;
mVolatileBuffer->lockedVertexEnd = vertexEnd;
break;
}
lockedVertexStart = vertexStart;
lockedVertexEnd = vertexEnd;
// uncomment it for debugging purpose. called many times per frame... spammy!
//Con::printf("%x: Locking %s range (%d, %d)", this, (mBufferType == GFXBufferTypeVolatile ? "volatile" : "static"), lockedVertexStart, lockedVertexEnd);
U32 sizeToLock = (vertexEnd - vertexStart) * mVertexSize;
if(mBufferType == GFXBufferTypeStatic)
{
*vertexPtr = new U8[sizeToLock];
mLockedBuffer = *vertexPtr;
}
else
{
D3D11_MAPPED_SUBRESOURCE pVertexData;
ZeroMemory(&pVertexData, sizeof(D3D11_MAPPED_SUBRESOURCE));
HRESULT hr = D3D11DEVICECONTEXT->Map(vb, 0, flags, 0, &pVertexData);
if(FAILED(hr))
{
AssertFatal(false, "Unable to lock vertex buffer.");
}
*vertexPtr = (U8*)pVertexData.pData + (vertexStart * mVertexSize);
}
#ifdef TORQUE_DEBUG
// Allocate a debug buffer large enough for the lock
// plus space for over and under run guard strings.
const U32 guardSize = sizeof( _VBGuardString );
mDebugGuardBuffer = new U8[sizeToLock+(guardSize*2)];
// Setup the guard strings.
dMemcpy( mDebugGuardBuffer, _VBGuardString, guardSize );
dMemcpy( mDebugGuardBuffer + sizeToLock + guardSize, _VBGuardString, guardSize );
// Store the real lock pointer and return our debug pointer.
mLockedBuffer = *vertexPtr;
*vertexPtr = mDebugGuardBuffer + guardSize;
#endif // TORQUE_DEBUG
}
void GFXD3D11VertexBuffer::unlock()
{
PROFILE_SCOPE(GFXD3D11VertexBuffer_unlock);
#ifdef TORQUE_DEBUG
if ( mDebugGuardBuffer )
{
const U32 guardSize = sizeof( _VBGuardString );
const U32 sizeLocked = (lockedVertexEnd - lockedVertexStart) * mVertexSize;
// First check the guard areas for overwrites.
AssertFatal(dMemcmp( mDebugGuardBuffer, _VBGuardString, guardSize) == 0,
"GFXD3D11VertexBuffer::unlock - Caught lock memory underrun!" );
AssertFatal(dMemcmp( mDebugGuardBuffer + sizeLocked + guardSize, _VBGuardString, guardSize) == 0,
"GFXD3D11VertexBuffer::unlock - Caught lock memory overrun!" );
// Copy the debug content down to the real VB.
dMemcpy(mLockedBuffer, mDebugGuardBuffer + guardSize, sizeLocked);
// Cleanup.
delete [] mDebugGuardBuffer;
mDebugGuardBuffer = NULL;
//mLockedBuffer = NULL;
}
#endif // TORQUE_DEBUG
if(mBufferType == GFXBufferTypeStatic)
{
const U32 sizeLocked = (lockedVertexEnd - lockedVertexStart) * mVertexSize;
//set up the update region of the buffer
D3D11_BOX box;
box.back = 1;
box.front = 0;
box.top = 0;
box.bottom = 1;
box.left = lockedVertexStart * mVertexSize;
box.right = lockedVertexEnd * mVertexSize;
//update the real vb buffer
D3D11DEVICECONTEXT->UpdateSubresource(vb, 0, &box,mLockedBuffer,sizeLocked, 0);
//clean up the old buffer
delete[] mLockedBuffer;
mLockedBuffer = NULL;
}
else
{
D3D11DEVICECONTEXT->Unmap(vb,0);
}
mIsFirstLock = false;
//uncomment it for debugging purpose. called many times per frame... spammy!
//Con::printf("%x: Unlocking %s range (%d, %d)", this, (mBufferType == GFXBufferTypeVolatile ? "volatile" : "static"), lockedVertexStart, lockedVertexEnd);
lockedVertexEnd = lockedVertexStart = 0;
if(mVolatileBuffer.isValid())
{
mVolatileBuffer->lockedVertexStart = 0;
mVolatileBuffer->lockedVertexEnd = 0;
mVolatileBuffer = NULL;
}
}
void GFXD3D11VertexBuffer::zombify()
{
AssertFatal(lockedVertexStart == 0 && lockedVertexEnd == 0, "GFXD3D11VertexBuffer::zombify - Cannot zombify a locked buffer!");
// Static buffers are managed by D3D11 so we don't deal with them.
if(mBufferType == GFXBufferTypeDynamic)
{
SAFE_RELEASE(vb);
}
}
void GFXD3D11VertexBuffer::resurrect()
{
// Static buffers are managed by D3D11 so we don't deal with them.
if(mBufferType == GFXBufferTypeDynamic)
{
D3D11_BUFFER_DESC desc;
desc.ByteWidth = mVertexSize * mNumVerts;
desc.Usage = D3D11_USAGE_DYNAMIC;
desc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
desc.MiscFlags = 0;
desc.StructureByteStride = 0;
HRESULT hr = D3D11DEVICE->CreateBuffer(&desc, NULL, &vb);
if(FAILED(hr))
{
AssertFatal(false, "GFXD3D11VertexBuffer::resurrect - Failed to allocate VB");
}
}
}

View file

@ -0,0 +1,95 @@
//-----------------------------------------------------------------------------
// Copyright (c) 2015 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#ifndef _GFXD3D_VERTEXBUFFER_H_
#define _GFXD3D_VERTEXBUFFER_H_
#include "gfx/D3D11/gfxD3D11Device.h"
#include "core/util/safeDelete.h"
class GFXD3D11VertexBuffer : public GFXVertexBuffer
{
public:
ID3D11Buffer *vb;
StrongRefPtr<GFXD3D11VertexBuffer> mVolatileBuffer;
void *mLockedBuffer;
#ifdef TORQUE_DEBUG
#define _VBGuardString "GFX_VERTEX_BUFFER_GUARD_STRING"
U8 *mDebugGuardBuffer;
#endif TORQUE_DEBUG
bool mIsFirstLock;
bool mClearAtFrameEnd;
GFXD3D11VertexBuffer();
GFXD3D11VertexBuffer( GFXDevice *device,
U32 numVerts,
const GFXVertexFormat *vertexFormat,
U32 vertexSize,
GFXBufferType bufferType );
virtual ~GFXD3D11VertexBuffer();
void lock(U32 vertexStart, U32 vertexEnd, void **vertexPtr);
void unlock();
void prepare() {}
// GFXResource interface
virtual void zombify();
virtual void resurrect();
};
//-----------------------------------------------------------------------------
// This is for debugging vertex buffers and trying to track down which vbs
// aren't getting free'd
inline GFXD3D11VertexBuffer::GFXD3D11VertexBuffer() : GFXVertexBuffer(0,0,0,0,(GFXBufferType)0)
{
vb = NULL;
mIsFirstLock = true;
lockedVertexEnd = lockedVertexStart = 0;
mClearAtFrameEnd = false;
#ifdef TORQUE_DEBUG
mDebugGuardBuffer = NULL;
mLockedBuffer = NULL;
#endif
}
inline GFXD3D11VertexBuffer::GFXD3D11VertexBuffer( GFXDevice *device,
U32 numVerts,
const GFXVertexFormat *vertexFormat,
U32 vertexSize,
GFXBufferType bufferType )
: GFXVertexBuffer( device, numVerts, vertexFormat, vertexSize, bufferType )
{
vb = NULL;
mIsFirstLock = true;
mClearAtFrameEnd = false;
lockedVertexEnd = lockedVertexStart = 0;
mLockedBuffer = NULL;
#ifdef TORQUE_DEBUG
mDebugGuardBuffer = NULL;
#endif
}
#endif // _GFXD3D_VERTEXBUFFER_H_

View file

@ -0,0 +1,98 @@
//-----------------------------------------------------------------------------
// Copyright (c) 2016 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#include "platform/platform.h"
#include "gfx/D3D11/screenshotD3D11.h"
#include "gfx/D3D11/gfxD3D11Device.h"
//Note if MSAA is ever enabled this will need fixing
GBitmap* ScreenShotD3D11::_captureBackBuffer()
{
ID3D11Texture2D* backBuf = D3D11->getBackBufferTexture();
D3D11_TEXTURE2D_DESC desc;
backBuf->GetDesc(&desc);
desc.BindFlags = 0;
desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ | D3D11_CPU_ACCESS_WRITE;
desc.Usage = D3D11_USAGE_STAGING;
//create temp texure
ID3D11Texture2D* pNewTexture = NULL;
HRESULT hr = D3D11DEVICE->CreateTexture2D(&desc, NULL, &pNewTexture);
if (FAILED(hr))
return NULL;
U32 width = desc.Width;
U32 height = desc.Height;
// pixel data
U8 *pData = new U8[width * height * 4];
D3D11DEVICECONTEXT->CopyResource(pNewTexture, backBuf);
D3D11_MAPPED_SUBRESOURCE Resource;
hr = D3D11DEVICECONTEXT->Map(pNewTexture, 0, D3D11_MAP_READ, 0, &Resource);
if (FAILED(hr))
{
//cleanup
SAFE_DELETE(pData);
SAFE_RELEASE(pNewTexture);
return NULL;
}
const U32 pitch = width << 2;
const U8* pSource = (U8*)Resource.pData;
U32 totalPitch = 0;
for (U32 i = 0; i < height; ++i)
{
dMemcpy(pData, pSource, width * 4);
pSource += Resource.RowPitch;
pData += pitch;
totalPitch += pitch;
}
D3D11DEVICECONTEXT->Unmap(pNewTexture, 0);
pData -= totalPitch;
GBitmap *gb = new GBitmap(width, height);
//Set GBitmap data and convert from bgr to rgb
ColorI c;
for (S32 i = 0; i<height; i++)
{
const U8 *a = pData + i * width * 4;
for (S32 j = 0; j<width; j++)
{
c.blue = *(a++);
c.green = *(a++);
c.red = *(a++);
a++; // Ignore alpha.
gb->setColor(j, i, c);
}
}
//cleanup
SAFE_DELETE(pData);
SAFE_RELEASE(pNewTexture);
return gb;
}

View file

@ -0,0 +1,39 @@
//-----------------------------------------------------------------------------
// Copyright (c) 2016 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#ifndef _SCREENSHOTD3D11_H_
#define _SCREENSHOTD3D11_H_
#include "gfx/screenshot.h"
//**************************************************************************
// D3D implementation of screenshot
//**************************************************************************
class ScreenShotD3D11 : public ScreenShot
{
protected:
GBitmap* _captureBackBuffer();
};
#endif // _SCREENSHOTD3D11_H_

View file

@ -826,6 +826,7 @@ GFXVertexBuffer * GFXD3D9Device::allocVertexBuffer( U32 numVerts,
switch(bufferType)
{
case GFXBufferTypeImmutable:
case GFXBufferTypeStatic:
pool = isD3D9Ex() ? D3DPOOL_DEFAULT : D3DPOOL_MANAGED;
break;

View file

@ -1307,10 +1307,15 @@ void GFXD3D9Shader::_buildSamplerShaderConstantHandles( Vector<GFXShaderConstDes
void GFXD3D9Shader::_buildInstancingShaderConstantHandles()
{
// If we have no instancing than just return
if (!mInstancingFormat)
return;
U32 offset = 0;
for ( U32 i=0; i < mInstancingFormat.getElementCount(); i++ )
for ( U32 i=0; i < mInstancingFormat->getElementCount(); i++ )
{
const GFXVertexElement &element = mInstancingFormat.getElement( i );
const GFXVertexElement &element = mInstancingFormat->getElement( i );
String constName = String::ToString( "$%s", element.getSemantic().c_str() );
@ -1347,9 +1352,9 @@ void GFXD3D9Shader::_buildInstancingShaderConstantHandles()
// If this is a matrix we will have 2 or 3 more of these
// semantics with the same name after it.
for ( ; i < mInstancingFormat.getElementCount(); i++ )
for ( ; i < mInstancingFormat->getElementCount(); i++ )
{
const GFXVertexElement &nextElement = mInstancingFormat.getElement( i );
const GFXVertexElement &nextElement = mInstancingFormat->getElement( i );
if ( nextElement.getSemantic() != element.getSemantic() )
{
i--;

View file

@ -55,6 +55,7 @@ void GFXD3D9VertexBuffer::lock(U32 vertexStart, U32 vertexEnd, void **vertexPtr)
switch( mBufferType )
{
case GFXBufferTypeImmutable:
case GFXBufferTypeStatic:
break;
@ -203,7 +204,7 @@ void GFXD3D9VertexBuffer::zombify()
{
AssertFatal(lockedVertexStart == 0 && lockedVertexEnd == 0, "GFXD3D9VertexBuffer::zombify - Cannot zombify a locked buffer!");
// Static buffers are managed by D3D9 so we don't deal with them.
if(mBufferType == GFXBufferTypeDynamic)
if(mBufferType == GFXBufferTypeDynamic || mBufferType == GFXBufferTypeImmutable)
{
SAFE_RELEASE(vb);
}

View file

@ -114,6 +114,7 @@ void GFXD3D9EnumTranslate::init()
GFXD3D9TextureFormat[GFXFormatD24S8] = D3DFMT_D24S8;
GFXD3D9TextureFormat[GFXFormatD24FS8] = D3DFMT_D24FS8;
GFXD3D9TextureFormat[GFXFormatD16] = D3DFMT_D16;
GFXD3D9TextureFormat[GFXFormatR8G8B8A8_SRGB] = D3DFMT_UNKNOWN;
VALIDATE_LOOKUPTABLE( GFXD3D9TextureFormat, GFXFormat);
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
@ -302,7 +303,6 @@ void GFXD3D9EnumTranslate::init()
GFXD3D9PrimType[GFXLineStrip] = D3DPT_LINESTRIP;
GFXD3D9PrimType[GFXTriangleList] = D3DPT_TRIANGLELIST;
GFXD3D9PrimType[GFXTriangleStrip] = D3DPT_TRIANGLESTRIP;
GFXD3D9PrimType[GFXTriangleFan] = D3DPT_TRIANGLEFAN;
VALIDATE_LOOKUPTABLE( GFXD3D9PrimType, GFXPT );
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------

View file

@ -514,7 +514,7 @@ void GFXPCD3D9Device::init( const GFXVideoMode &mode, PlatformWindow *window /*
mCardProfiler = new GFXD3D9CardProfiler(mAdapterIndex);
mCardProfiler->init();
gScreenShot = new ScreenShotD3D;
gScreenShot = new ScreenShotD3D9;
// Set the video capture frame grabber.
mVideoFrameGrabber = new VideoFrameGrabberD3D9();

View file

@ -30,7 +30,7 @@
#include <d3dx9tex.h>
GBitmap* ScreenShotD3D::_captureBackBuffer()
GBitmap* ScreenShotD3D9::_captureBackBuffer()
{
#ifdef TORQUE_OS_XENON
return NULL;

View file

@ -19,15 +19,15 @@
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#ifndef _SCREENSHOTD3D_H_
#define _SCREENSHOTD3D_H_
#ifndef _SCREENSHOTD3D9_H_
#define _SCREENSHOTD3D9_H_
#include "gfx/screenshot.h"
//**************************************************************************
// D3D implementation of screenshot
//**************************************************************************
class ScreenShotD3D : public ScreenShot
class ScreenShotD3D9 : public ScreenShot
{
protected:
@ -36,4 +36,4 @@ protected:
};
#endif // _SCREENSHOTD3D_H_
#endif // _SCREENSHOTD3D9_H_

View file

@ -106,7 +106,7 @@ public:
virtual ~GenericConstBufferLayout() {}
/// Add a parameter to the buffer
void addParameter(const String& name, const GFXShaderConstType constType, const U32 offset, const U32 size, const U32 arraySize, const U32 alignValue);
virtual void addParameter(const String& name, const GFXShaderConstType constType, const U32 offset, const U32 size, const U32 arraySize, const U32 alignValue);
/// Get the size of the buffer
inline U32 getBufferSize() const { return mBufferSize; }
@ -210,6 +210,9 @@ public:
/// state at the same time.
inline const U8* getDirtyBuffer( U32 *start, U32 *size );
/// Gets the entire buffer ignoring dirty range
inline const U8* getEntireBuffer();
/// Sets the entire buffer as dirty or clears the dirty state.
inline void setDirty( bool dirty );
@ -348,6 +351,13 @@ inline const U8* GenericConstBuffer::getDirtyBuffer( U32 *start, U32 *size )
return buffer;
}
inline const U8* GenericConstBuffer::getEntireBuffer()
{
AssertFatal(mBuffer, "GenericConstBuffer::getDirtyBuffer() - Buffer is empty!");
return mBuffer;
}
inline bool GenericConstBuffer::isEqual( const GenericConstBuffer *buffer ) const
{
U32 bsize = mLayout->getBufferSize();

View file

@ -41,7 +41,7 @@ ImplementEnumType( GFXAdapterType,
"Back-end graphics API used by the GFX subsystem.\n\n"
"@ingroup GFX" )
{ OpenGL, "OpenGL", "OpenGL." },
{ Direct3D8, "D3D8", "Direct3D 8." },
{ Direct3D11, "D3D11", "Direct3D 11." },
{ Direct3D9, "D3D9", "Direct3D 9." },
{ NullDevice, "NullDevice", "Null device for dedicated servers." },
{ Direct3D9_360, "Xenon", "Direct3D 9 on Xbox 360." }

View file

@ -514,6 +514,8 @@ void GFXDevice::updateStates(bool forceSetAll /*=false*/)
mStateBlockDirty = false;
}
_updateRenderTargets();
if( mTexturesDirty )
{
mTexturesDirty = false;

View file

@ -458,7 +458,7 @@ void GFXDrawUtil::drawRect( const Point2F &upperLeft, const Point2F &lowerRight,
Point2F nw(-0.5f,-0.5f); /* \ */
Point2F ne(0.5f,-0.5f); /* / */
GFXVertexBufferHandle<GFXVertexPC> verts (mDevice, 10, GFXBufferTypeVolatile );
GFXVertexBufferHandle<GFXVertexPCT> verts (mDevice, 10, GFXBufferTypeVolatile );
verts.lock();
F32 ulOffset = 0.5f - mDevice->getFillConventionOffset();
@ -521,12 +521,12 @@ void GFXDrawUtil::drawRectFill( const Point2F &upperLeft, const Point2F &lowerRi
Point2F nw(-0.5,-0.5); /* \ */
Point2F ne(0.5,-0.5); /* / */
GFXVertexBufferHandle<GFXVertexPC> verts(mDevice, 4, GFXBufferTypeVolatile);
GFXVertexBufferHandle<GFXVertexPCT> verts(mDevice, 4, GFXBufferTypeVolatile);
verts.lock();
F32 ulOffset = 0.5f - mDevice->getFillConventionOffset();
verts[0].point.set( upperLeft.x + nw.x + ulOffset, upperLeft.y + nw.y + ulOffset, 0.0f);
verts[0].point.set( upperLeft.x+nw.x + ulOffset, upperLeft.y+nw.y + ulOffset, 0.0f );
verts[1].point.set( lowerRight.x + ne.x + ulOffset, upperLeft.y + ne.y + ulOffset, 0.0f);
verts[2].point.set( upperLeft.x - ne.x + ulOffset, lowerRight.y - ne.y + ulOffset, 0.0f);
verts[3].point.set( lowerRight.x - nw.x + ulOffset, lowerRight.y - nw.y + ulOffset, 0.0f);
@ -548,7 +548,7 @@ void GFXDrawUtil::draw2DSquare( const Point2F &screenPoint, F32 width, F32 spinA
Point3F offset( screenPoint.x, screenPoint.y, 0.0 );
GFXVertexBufferHandle<GFXVertexPC> verts( mDevice, 4, GFXBufferTypeVolatile );
GFXVertexBufferHandle<GFXVertexPCT> verts( mDevice, 4, GFXBufferTypeVolatile );
verts.lock();
verts[0].point.set( -width, -width, 0.0f );
@ -608,7 +608,7 @@ void GFXDrawUtil::drawLine( F32 x1, F32 y1, F32 x2, F32 y2, const ColorI &color
void GFXDrawUtil::drawLine( F32 x1, F32 y1, F32 z1, F32 x2, F32 y2, F32 z2, const ColorI &color )
{
GFXVertexBufferHandle<GFXVertexPC> verts( mDevice, 2, GFXBufferTypeVolatile );
GFXVertexBufferHandle<GFXVertexPCT> verts( mDevice, 2, GFXBufferTypeVolatile );
verts.lock();
verts[0].point.set( x1, y1, z1 );
@ -647,7 +647,7 @@ void GFXDrawUtil::drawSphere( const GFXStateBlockDesc &desc, F32 radius, const P
const SphereMesh::TriangleMesh * sphereMesh = gSphere.getMesh(2);
S32 numPoly = sphereMesh->numPoly;
S32 totalPoly = 0;
GFXVertexBufferHandle<GFXVertexPC> verts(mDevice, numPoly*3, GFXBufferTypeVolatile);
GFXVertexBufferHandle<GFXVertexPCT> verts(mDevice, numPoly*3, GFXBufferTypeVolatile);
verts.lock();
S32 vertexIndex = 0;
for (S32 i=0; i<numPoly; i++)
@ -712,7 +712,7 @@ void GFXDrawUtil::drawTriangle( const GFXStateBlockDesc &desc, const Point3F &p0
void GFXDrawUtil::_drawWireTriangle( const GFXStateBlockDesc &desc, const Point3F &p0, const Point3F &p1, const Point3F &p2, const ColorI &color, const MatrixF *xfm )
{
GFXVertexBufferHandle<GFXVertexPC> verts(mDevice, 4, GFXBufferTypeVolatile);
GFXVertexBufferHandle<GFXVertexPCT> verts(mDevice, 4, GFXBufferTypeVolatile);
verts.lock();
// Set up the line strip
@ -745,7 +745,7 @@ void GFXDrawUtil::_drawWireTriangle( const GFXStateBlockDesc &desc, const Point3
void GFXDrawUtil::_drawSolidTriangle( const GFXStateBlockDesc &desc, const Point3F &p0, const Point3F &p1, const Point3F &p2, const ColorI &color, const MatrixF *xfm )
{
GFXVertexBufferHandle<GFXVertexPC> verts(mDevice, 3, GFXBufferTypeVolatile);
GFXVertexBufferHandle<GFXVertexPCT> verts(mDevice, 3, GFXBufferTypeVolatile);
verts.lock();
// Set up the line strip
@ -778,7 +778,7 @@ void GFXDrawUtil::drawPolygon( const GFXStateBlockDesc& desc, const Point3F* poi
{
const bool isWireframe = ( desc.fillMode == GFXFillWireframe );
const U32 numVerts = isWireframe ? numPoints + 1 : numPoints;
GFXVertexBufferHandle< GFXVertexPC > verts( mDevice, numVerts, GFXBufferTypeVolatile );
GFXVertexBufferHandle< GFXVertexPCT > verts( mDevice, numVerts, GFXBufferTypeVolatile );
verts.lock();
for( U32 i = 0; i < numPoints; ++ i )
@ -809,7 +809,7 @@ void GFXDrawUtil::drawPolygon( const GFXStateBlockDesc& desc, const Point3F* poi
if( desc.fillMode == GFXFillWireframe )
mDevice->drawPrimitive( GFXLineStrip, 0, numPoints );
else
mDevice->drawPrimitive( GFXTriangleFan, 0, numPoints - 2 );
mDevice->drawPrimitive( GFXTriangleStrip, 0, numPoints - 2 );
}
void GFXDrawUtil::drawCube( const GFXStateBlockDesc &desc, const Box3F &box, const ColorI &color, const MatrixF *xfm )
@ -827,7 +827,7 @@ void GFXDrawUtil::drawCube( const GFXStateBlockDesc &desc, const Point3F &size,
void GFXDrawUtil::_drawWireCube( const GFXStateBlockDesc &desc, const Point3F &size, const Point3F &pos, const ColorI &color, const MatrixF *xfm )
{
GFXVertexBufferHandle<GFXVertexPC> verts(mDevice, 30, GFXBufferTypeVolatile);
GFXVertexBufferHandle<GFXVertexPCT> verts(mDevice, 30, GFXBufferTypeVolatile);
verts.lock();
Point3F halfSize = size * 0.5f;
@ -870,7 +870,7 @@ void GFXDrawUtil::_drawWireCube( const GFXStateBlockDesc &desc, const Point3F &s
void GFXDrawUtil::_drawSolidCube( const GFXStateBlockDesc &desc, const Point3F &size, const Point3F &pos, const ColorI &color, const MatrixF *xfm )
{
GFXVertexBufferHandle<GFXVertexPC> verts(mDevice, 36, GFXBufferTypeVolatile);
GFXVertexBufferHandle<GFXVertexPCT> verts(mDevice, 36, GFXBufferTypeVolatile);
verts.lock();
Point3F halfSize = size * 0.5f;
@ -950,7 +950,7 @@ void GFXDrawUtil::_drawWirePolyhedron( const GFXStateBlockDesc &desc, const AnyP
// Allocate a temporary vertex buffer.
GFXVertexBufferHandle< GFXVertexPC > verts( mDevice, numEdges * 2, GFXBufferTypeVolatile);
GFXVertexBufferHandle< GFXVertexPCT > verts( mDevice, numEdges * 2, GFXBufferTypeVolatile);
// Fill it with the vertices for the edges.
@ -997,7 +997,7 @@ void GFXDrawUtil::_drawSolidPolyhedron( const GFXStateBlockDesc &desc, const Any
// Create a temp buffer for the vertices and
// put all the polyhedron's points in there.
GFXVertexBufferHandle< GFXVertexPC > verts( mDevice, numPoints, GFXBufferTypeVolatile );
GFXVertexBufferHandle< GFXVertexPCT > verts( mDevice, numPoints, GFXBufferTypeVolatile );
verts.lock();
for( U32 i = 0; i < numPoints; ++ i )
@ -1071,7 +1071,7 @@ void GFXDrawUtil::_drawSolidPolyhedron( const GFXStateBlockDesc &desc, const Any
for( U32 i = 0; i < numPolys; ++ i )
{
U32 numVerts = numIndicesForPoly[ i ];
mDevice->drawIndexedPrimitive( GFXTriangleFan, 0, 0, numPoints, startIndex, numVerts - 2 );
mDevice->drawIndexedPrimitive( GFXTriangleStrip, 0, 0, numPoints, startIndex, numVerts - 2 );
startIndex += numVerts;
}
}
@ -1119,7 +1119,7 @@ void GFXDrawUtil::drawObjectBox( const GFXStateBlockDesc &desc, const Point3F &s
PrimBuild::end();
}
static const Point2F circlePoints[] =
static const Point2F circlePoints[] =
{
Point2F(0.707107f, 0.707107f),
Point2F(0.923880f, 0.382683f),
@ -1156,7 +1156,7 @@ void GFXDrawUtil::_drawSolidCapsule( const GFXStateBlockDesc &desc, const Point3
mat = MatrixF::Identity;
S32 numPoints = sizeof(circlePoints)/sizeof(Point2F);
GFXVertexBufferHandle<GFXVertexPC> verts(mDevice, numPoints * 2 + 2, GFXBufferTypeVolatile);
GFXVertexBufferHandle<GFXVertexPCT> verts(mDevice, numPoints * 2 + 2, GFXBufferTypeVolatile);
verts.lock();
for (S32 i=0; i<numPoints + 1; i++)
@ -1222,7 +1222,7 @@ void GFXDrawUtil::_drawWireCapsule( const GFXStateBlockDesc &desc, const Point3F
mDevice->multWorld(mat);
S32 numPoints = sizeof(circlePoints)/sizeof(Point2F);
GFXVertexBufferHandle<GFXVertexPC> verts(mDevice, numPoints, GFXBufferTypeVolatile);
GFXVertexBufferHandle<GFXVertexPCT> verts(mDevice, numPoints, GFXBufferTypeVolatile);
verts.lock();
for (S32 i=0; i< numPoints; i++)
{
@ -1268,27 +1268,57 @@ void GFXDrawUtil::drawCone( const GFXStateBlockDesc &desc, const Point3F &basePn
mDevice->multWorld(mat);
S32 numPoints = sizeof(circlePoints)/sizeof(Point2F);
GFXVertexBufferHandle<GFXVertexPC> verts(mDevice, numPoints + 2, GFXBufferTypeVolatile);
GFXVertexBufferHandle<GFXVertexPCT> verts(mDevice, numPoints * 3 + 2, GFXBufferTypeVolatile);
verts.lock();
verts[0].point = Point3F(0.0f,0.0f,1.0f);
verts[0].color = color;
for (S32 i=0; i<numPoints + 1; i++)
F32 sign = -1.f;
S32 indexDown = 0; //counting down from numPoints
S32 indexUp = 0; //counting up from 0
S32 index = 0; //circlePoints index for cap
for (S32 i = 0; i < numPoints + 1; i++)
{
//Top cap
if (i != numPoints)
{
if (sign < 0)
index = indexDown;
else
index = indexUp;
verts[i].point = Point3F(circlePoints[index].x, circlePoints[index].y, 0);
verts[i].color = color;
if (sign < 0)
indexUp += 1;
else
indexDown = numPoints - indexUp;
// invert sign
sign *= -1.0f;
}
//cone
S32 imod = i % numPoints;
verts[i + 1].point = Point3F(circlePoints[imod].x,circlePoints[imod].y, 0.0f);
verts[i + 1].color = color;
S32 vertindex = 2 * i + numPoints;
verts[vertindex].point = Point3F(circlePoints[imod].x, circlePoints[imod].y, 0);
verts[vertindex].color = color;
verts[vertindex + 1].point = Point3F(0.0f, 0.0f, 1.0f);
verts[vertindex + 1].color = color;
}
verts.unlock();
mDevice->setStateBlockByDesc( desc );
mDevice->setVertexBuffer( verts );
mDevice->setupGenericShaders( GFXDevice::GSModColorTexture );
mDevice->setupGenericShaders();
mDevice->drawPrimitive( GFXTriangleFan, 0, numPoints );
mDevice->drawPrimitive( GFXTriangleFan, 1, numPoints-1 );
mDevice->drawPrimitive(GFXTriangleStrip, 0, numPoints - 2);
mDevice->drawPrimitive(GFXTriangleStrip, numPoints, numPoints * 2);
mDevice->popWorldMatrix();
}
void GFXDrawUtil::drawCylinder( const GFXStateBlockDesc &desc, const Point3F &basePnt, const Point3F &tipPnt, F32 radius, const ColorI &color )
@ -1307,32 +1337,59 @@ void GFXDrawUtil::drawCylinder( const GFXStateBlockDesc &desc, const Point3F &ba
mDevice->pushWorldMatrix();
mDevice->multWorld(mat);
S32 numPoints = sizeof(circlePoints)/sizeof(Point2F);
GFXVertexBufferHandle<GFXVertexPC> verts(mDevice, numPoints * 4 + 4, GFXBufferTypeVolatile);
S32 numPoints = sizeof(circlePoints) / sizeof(Point2F);
GFXVertexBufferHandle<GFXVertexPCT> verts(mDevice, numPoints *4 + 2, GFXBufferTypeVolatile);
verts.lock();
for (S32 i=0; i<numPoints + 1; i++)
{
S32 imod = i % numPoints;
verts[i].point = Point3F(circlePoints[imod].x,circlePoints[imod].y, 0.5f);
verts[i].color = color;
verts[i + numPoints + 1].point = Point3F(circlePoints[imod].x,circlePoints[imod].y, 0);
verts[i + numPoints + 1].color = color;
verts[2*numPoints + 2 + 2 * i].point = Point3F(circlePoints[imod].x,circlePoints[imod].y, 0.5f);
verts[2*numPoints + 2 + 2 * i].color = color;
verts[2*numPoints + 2 + 2 * i + 1].point = Point3F(circlePoints[imod].x,circlePoints[imod].y, 0);
verts[2*numPoints + 2 + 2 * i + 1].color = color;
F32 sign = -1.f;
S32 indexDown = 0; //counting down from numPoints
S32 indexUp = 0; //counting up from 0
S32 index = 0; //circlePoints index for caps
for (S32 i = 0; i < numPoints + 1; i++)
{
//Top/Bottom cap
if (i != numPoints)
{
if (sign < 0)
index = indexDown;
else
index = indexUp;
verts[i].point = Point3F(circlePoints[index].x, circlePoints[index].y, 0);
verts[i].color = color;
verts[i + numPoints].point = Point3F(circlePoints[index].x, circlePoints[index].y, 0.5f);
verts[i + numPoints].color = color;
if (sign < 0)
indexUp += 1;
else
indexDown = numPoints - indexUp;
// invert sign
sign *= -1.0f;
}
//cylinder
S32 imod = i % numPoints;
S32 vertindex = 2 * i + (numPoints * 2);
verts[vertindex].point = Point3F(circlePoints[imod].x, circlePoints[imod].y, 0);
verts[vertindex].color = color;
verts[vertindex + 1].point = Point3F(circlePoints[imod].x, circlePoints[imod].y, 0.5f);
verts[vertindex + 1].color = color;
}
verts.unlock();
mDevice->setStateBlockByDesc( desc );
mDevice->setVertexBuffer( verts );
mDevice->setupGenericShaders( GFXDevice::GSModColorTexture );
mDevice->setupGenericShaders();
mDevice->drawPrimitive( GFXTriangleFan, 0, numPoints );
mDevice->drawPrimitive( GFXTriangleFan, numPoints + 1, numPoints );
mDevice->drawPrimitive( GFXTriangleStrip, 2 * numPoints + 2, 2 * numPoints);
mDevice->drawPrimitive( GFXTriangleStrip, 0, numPoints-2 );
mDevice->drawPrimitive( GFXTriangleStrip, numPoints, numPoints - 2);
mDevice->drawPrimitive( GFXTriangleStrip, numPoints*2, numPoints * 2);
mDevice->popWorldMatrix();
}
@ -1393,7 +1450,7 @@ void GFXDrawUtil::drawFrustum( const Frustum &f, const ColorI &color )
void GFXDrawUtil::drawSolidPlane( const GFXStateBlockDesc &desc, const Point3F &pos, const Point2F &size, const ColorI &color )
{
GFXVertexBufferHandle<GFXVertexPC> verts(mDevice, 4, GFXBufferTypeVolatile);
GFXVertexBufferHandle<GFXVertexPCT> verts(mDevice, 4, GFXBufferTypeVolatile);
verts.lock();
verts[0].point = pos + Point3F( -size.x / 2.0f, -size.y / 2.0f, 0 );
@ -1412,7 +1469,7 @@ void GFXDrawUtil::drawSolidPlane( const GFXStateBlockDesc &desc, const Point3F &
mDevice->setVertexBuffer( verts );
mDevice->setupGenericShaders();
mDevice->drawPrimitive( GFXTriangleFan, 0, 2 );
mDevice->drawPrimitive( GFXTriangleStrip, 0, 2 );
}
void GFXDrawUtil::drawPlaneGrid( const GFXStateBlockDesc &desc, const Point3F &pos, const Point2F &size, const Point2F &step, const ColorI &color, Plane plane )
@ -1449,7 +1506,7 @@ void GFXDrawUtil::drawPlaneGrid( const GFXStateBlockDesc &desc, const Point3F &p
break;
}
GFXVertexBufferHandle<GFXVertexPC> verts( mDevice, numVertices, GFXBufferTypeVolatile );
GFXVertexBufferHandle<GFXVertexPCT> verts( mDevice, numVertices, GFXBufferTypeVolatile );
verts.lock();
U32 vertCount = 0;
@ -1541,7 +1598,7 @@ void GFXDrawUtil::drawTransform( const GFXStateBlockDesc &desc, const MatrixF &m
GFX->multWorld( mat );
GFXVertexBufferHandle<GFXVertexPC> verts( mDevice, 6, GFXBufferTypeVolatile );
GFXVertexBufferHandle<GFXVertexPCT> verts( mDevice, 6, GFXBufferTypeVolatile );
verts.lock();
const static ColorI defColors[3] =

View file

@ -68,7 +68,6 @@ enum GFXPrimitiveType
GFXLineStrip,
GFXTriangleList,
GFXTriangleStrip,
GFXTriangleFan,
GFXPT_COUNT
};
@ -206,6 +205,9 @@ enum GFXFormat
GFXFormatDXT4,
GFXFormatDXT5,
// sRGB formats
GFXFormatR8G8B8A8_SRGB,
GFXFormat_COUNT,
GFXFormat_8BIT = GFXFormatA8,
@ -277,8 +279,8 @@ enum GFXBlend
enum GFXAdapterType
{
OpenGL = 0,
Direct3D11,
Direct3D9,
Direct3D8,
NullDevice,
Direct3D9_360,
GFXAdapterType_Count

View file

@ -77,8 +77,8 @@ inline static void _GFXInitReportAdapters(Vector<GFXAdapter*> &adapters)
case NullDevice:
Con::printf(" Null device found");
break;
case Direct3D8:
Con::printf(" Direct 3D (version 8.1) device found");
case Direct3D11:
Con::printf(" Direct 3D (version 11.x) device found");
break;
default :
Con::printf(" Unknown device found");
@ -221,7 +221,8 @@ GFXAdapter* GFXInit::chooseAdapter( GFXAdapterType type, const char* outputDevic
const char* GFXInit::getAdapterNameFromType(GFXAdapterType type)
{
static const char* _names[] = { "OpenGL", "D3D9", "D3D8", "NullDevice", "Xenon" };
// must match GFXAdapterType order
static const char* _names[] = { "OpenGL", "D3D11", "D3D9", "NullDevice", "Xenon" };
if( type < 0 || type >= GFXAdapterType_Count )
{
@ -268,51 +269,53 @@ GFXAdapter *GFXInit::getBestAdapterChoice()
//
// If D3D is unavailable, we're not on windows, so GL is de facto the
// best choice!
F32 highestSM9 = 0.f, highestSMGL = 0.f;
GFXAdapter *foundAdapter8 = NULL, *foundAdapter9 = NULL,
*foundAdapterGL = NULL;
F32 highestSMDX = 0.f, highestSMGL = 0.f;
GFXAdapter *foundAdapter9 = NULL, *foundAdapterGL = NULL, *foundAdapter11 = NULL;
for(S32 i=0; i<smAdapters.size(); i++)
for (S32 i = 0; i<smAdapters.size(); i++)
{
GFXAdapter *currAdapter = smAdapters[i];
switch(currAdapter->mType)
switch (currAdapter->mType)
{
case Direct3D9:
if(currAdapter->mShaderModel > highestSM9)
case Direct3D11:
if (currAdapter->mShaderModel > highestSMDX)
{
highestSM9 = currAdapter->mShaderModel;
highestSMDX = currAdapter->mShaderModel;
foundAdapter11 = currAdapter;
}
break;
case Direct3D9:
if (currAdapter->mShaderModel > highestSMDX)
{
highestSMDX = currAdapter->mShaderModel;
foundAdapter9 = currAdapter;
}
break;
case OpenGL:
if(currAdapter->mShaderModel > highestSMGL)
if (currAdapter->mShaderModel > highestSMGL)
{
highestSMGL = currAdapter->mShaderModel;
foundAdapterGL = currAdapter;
}
break;
case Direct3D8:
if(!foundAdapter8)
foundAdapter8 = currAdapter;
break;
default:
break;
}
}
// Return best found in order DX9, GL, DX8.
if(foundAdapter9)
// Return best found in order DX11,DX9, GL
if (foundAdapter11)
return foundAdapter11;
if (foundAdapter9)
return foundAdapter9;
if(foundAdapterGL)
if (foundAdapterGL)
return foundAdapterGL;
if(foundAdapter8)
return foundAdapter8;
// Uh oh - we didn't find anything. Grab whatever we can that's not Null...
for(S32 i=0; i<smAdapters.size(); i++)
if(smAdapters[i]->mType != NullDevice)

View file

@ -35,7 +35,8 @@ bool GFXShader::smLogWarnings = true;
GFXShader::GFXShader()
: mPixVersion( 0.0f ),
mReloadKey( 0 )
mReloadKey( 0 ),
mInstancingFormat( NULL )
{
}
@ -43,6 +44,8 @@ GFXShader::~GFXShader()
{
Torque::FS::RemoveChangeNotification( mVertexFile, this, &GFXShader::_onFileChanged );
Torque::FS::RemoveChangeNotification( mPixelFile, this, &GFXShader::_onFileChanged );
SAFE_DELETE(mInstancingFormat);
}
#ifndef TORQUE_OPENGL
@ -60,8 +63,16 @@ bool GFXShader::init( const Torque::Path &vertFile,
const Torque::Path &pixFile,
F32 pixVersion,
const Vector<GFXShaderMacro> &macros,
const Vector<String> &samplerNames)
const Vector<String> &samplerNames,
GFXVertexFormat *instanceFormat)
{
// Take care of instancing
if (instanceFormat)
{
mInstancingFormat = new GFXVertexFormat;
mInstancingFormat->copy(*instanceFormat);
}
// Store the inputs for use in reloading.
mVertexFile = vertFile;
mPixelFile = pixFile;

View file

@ -262,13 +262,12 @@ protected:
/// their destructor.
Vector<GFXShaderConstBuffer*> mActiveBuffers;
GFXVertexFormat *mInstancingFormat;
/// A protected constructor so it cannot be instantiated.
GFXShader();
public:
// TODO: Add this into init().
GFXVertexFormat mInstancingFormat;
public:
/// Adds a global shader macro which will be merged with
/// the script defined macros on every shader reload.
@ -312,7 +311,8 @@ public:
const Torque::Path &pixFile,
F32 pixVersion,
const Vector<GFXShaderMacro> &macros,
const Vector<String> &samplerNames);
const Vector<String> &samplerNames,
GFXVertexFormat *instanceFormat = NULL );
/// Reloads the shader from disk.
bool reload();
@ -358,6 +358,9 @@ public:
// GFXResource
const String describeSelf() const { return mDescription; }
// Get instancing vertex format
GFXVertexFormat *getInstancingFormat() { return mInstancingFormat; }
protected:
/// Called when the shader files change on disk.

View file

@ -347,7 +347,6 @@ void GFXStringEnumTranslate::init()
GFX_STRING_ASSIGN_MACRO( GFXStringPrimType, GFXLineStrip );
GFX_STRING_ASSIGN_MACRO( GFXStringPrimType, GFXTriangleList );
GFX_STRING_ASSIGN_MACRO( GFXStringPrimType, GFXTriangleStrip );
GFX_STRING_ASSIGN_MACRO( GFXStringPrimType, GFXTriangleFan );
VALIDATE_LOOKUPTABLE( GFXStringPrimType, GFXPT );
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------

View file

@ -70,6 +70,7 @@ GFXVertexFormat::GFXVertexFormat()
mHasColor( false ),
mHasNormal( false ),
mHasTangent( false ),
mHasInstancing( false ),
mTexCoordCount( 0 ),
mSizeInBytes( 0 ),
mDecl( NULL )
@ -83,6 +84,7 @@ void GFXVertexFormat::copy( const GFXVertexFormat &format )
mHasNormal = format.mHasNormal;
mHasTangent = format.mHasTangent;
mHasColor = format.mHasColor;
mHasInstancing = format.mHasInstancing;
mTexCoordCount = format.mTexCoordCount;
mSizeInBytes = format.mSizeInBytes;
mDescription = format.mDescription;
@ -161,6 +163,14 @@ bool GFXVertexFormat::hasColor() const
return mHasColor;
}
bool GFXVertexFormat::hasInstancing() const
{
if (mDirty)
const_cast<GFXVertexFormat*>(this)->_updateDirty();
return mHasInstancing;
}
U32 GFXVertexFormat::getTexCoordCount() const
{
if ( mDirty )
@ -177,6 +187,11 @@ U32 GFXVertexFormat::getSizeInBytes() const
return mSizeInBytes;
}
void GFXVertexFormat::enableInstancing()
{
mHasInstancing = true;
}
void GFXVertexFormat::_updateDirty()
{
PROFILE_SCOPE( GFXVertexFormat_updateDirty );

View file

@ -153,6 +153,9 @@ public:
/// The copy constructor.
GFXVertexFormat( const GFXVertexFormat &format ) { copy( format ); }
/// Tell this format it has instancing
void enableInstancing();
/// Copy the other vertex format.
void copy( const GFXVertexFormat &format );
@ -163,7 +166,7 @@ public:
const String& getDescription() const;
/// Clears all the vertex elements.
void clear();
void clear();
/// Adds a vertex element to the format.
///
@ -182,6 +185,9 @@ public:
/// Returns true if there is a COLOR semantic in this vertex format.
bool hasColor() const;
/// Return true if instancing is used with this vertex format.
bool hasInstancing() const;
/// Returns the texture coordinate count by
/// counting the number of TEXCOORD semantics.
U32 getTexCoordCount() const;
@ -225,6 +231,9 @@ protected:
/// Is true if there is a COLOR semantic in this vertex format.
bool mHasColor;
/// Is instaning used with this vertex format.
bool mHasInstancing;
/// The texture coordinate count by counting the
/// number of "TEXCOORD" semantics.
U32 mTexCoordCount;

View file

@ -513,9 +513,6 @@ inline GLsizei GFXGLDevice::primCountToIndexCount(GFXPrimitiveType primType, U32
case GFXTriangleStrip :
return 2 + primitiveCount;
break;
case GFXTriangleFan :
return 2 + primitiveCount;
break;
default:
AssertFatal(false, "GFXGLDevice::primCountToIndexCount - unrecognized prim type");
break;
@ -789,7 +786,8 @@ void GFXGLDevice::setupGenericShaders( GenericShaderType type )
shaderData->registerObject();
mGenericShader[GSColor] = shaderData->getShader();
mGenericShaderBuffer[GSColor] = mGenericShader[GSColor]->allocConstBuffer();
mModelViewProjSC[GSColor] = mGenericShader[GSColor]->getShaderConstHandle( "$modelView" );
mModelViewProjSC[GSColor] = mGenericShader[GSColor]->getShaderConstHandle( "$modelView" );
Sim::getRootGroup()->addObject(shaderData);
shaderData = new ShaderData();
shaderData->setField("OGLVertexShaderFile", "shaders/common/fixedFunction/gl/modColorTextureV.glsl");
@ -799,7 +797,8 @@ void GFXGLDevice::setupGenericShaders( GenericShaderType type )
shaderData->registerObject();
mGenericShader[GSModColorTexture] = shaderData->getShader();
mGenericShaderBuffer[GSModColorTexture] = mGenericShader[GSModColorTexture]->allocConstBuffer();
mModelViewProjSC[GSModColorTexture] = mGenericShader[GSModColorTexture]->getShaderConstHandle( "$modelView" );
mModelViewProjSC[GSModColorTexture] = mGenericShader[GSModColorTexture]->getShaderConstHandle( "$modelView" );
Sim::getRootGroup()->addObject(shaderData);
shaderData = new ShaderData();
shaderData->setField("OGLVertexShaderFile", "shaders/common/fixedFunction/gl/addColorTextureV.glsl");
@ -809,7 +808,8 @@ void GFXGLDevice::setupGenericShaders( GenericShaderType type )
shaderData->registerObject();
mGenericShader[GSAddColorTexture] = shaderData->getShader();
mGenericShaderBuffer[GSAddColorTexture] = mGenericShader[GSAddColorTexture]->allocConstBuffer();
mModelViewProjSC[GSAddColorTexture] = mGenericShader[GSAddColorTexture]->getShaderConstHandle( "$modelView" );
mModelViewProjSC[GSAddColorTexture] = mGenericShader[GSAddColorTexture]->getShaderConstHandle( "$modelView" );
Sim::getRootGroup()->addObject(shaderData);
shaderData = new ShaderData();
shaderData->setField("OGLVertexShaderFile", "shaders/common/fixedFunction/gl/textureV.glsl");
@ -820,6 +820,7 @@ void GFXGLDevice::setupGenericShaders( GenericShaderType type )
mGenericShader[GSTexture] = shaderData->getShader();
mGenericShaderBuffer[GSTexture] = mGenericShader[GSTexture]->allocConstBuffer();
mModelViewProjSC[GSTexture] = mGenericShader[GSTexture]->getShaderConstHandle( "$modelView" );
Sim::getRootGroup()->addObject(shaderData);
}
MatrixF tempMatrix = mProjectionMatrix * mViewMatrix * mWorldMatrix[mWorldStackSize];

View file

@ -53,7 +53,6 @@ void GFXGLEnumTranslate::init()
GFXGLPrimType[GFXLineStrip] = GL_LINE_STRIP;
GFXGLPrimType[GFXTriangleList] = GL_TRIANGLES;
GFXGLPrimType[GFXTriangleStrip] = GL_TRIANGLE_STRIP;
GFXGLPrimType[GFXTriangleFan] = GL_TRIANGLE_FAN;
// Blend
GFXGLBlend[GFXBlendZero] = GL_ZERO;
@ -191,6 +190,8 @@ void GFXGLEnumTranslate::init()
GFXGLTextureType[GFXFormatDXT4] = GL_ZERO;
GFXGLTextureType[GFXFormatDXT5] = GL_UNSIGNED_BYTE;
GFXGLTextureType[GFXFormatR8G8B8A8_SRGB] = GL_SRGB8_ALPHA8;
static GLint Swizzle_GFXFormatA8[] = { GL_NONE, GL_NONE, GL_NONE, GL_RED };
static GLint Swizzle_GFXFormatL[] = { GL_RED, GL_RED, GL_RED, GL_ALPHA };
GFXGLTextureSwizzle[GFXFormatA8] = Swizzle_GFXFormatA8; // old GL_ALPHA8

View file

@ -664,10 +664,14 @@ void GFXGLShader::initHandles()
glUseProgram(0);
//instancing
if (!mInstancingFormat)
return;
U32 offset = 0;
for ( U32 i=0; i < mInstancingFormat.getElementCount(); i++ )
for ( U32 i=0; i < mInstancingFormat->getElementCount(); i++ )
{
const GFXVertexElement &element = mInstancingFormat.getElement( i );
const GFXVertexElement &element = mInstancingFormat->getElement( i );
String constName = String::ToString( "$%s", element.getSemantic().c_str() );
@ -702,9 +706,9 @@ void GFXGLShader::initHandles()
// If this is a matrix we will have 2 or 3 more of these
// semantics with the same name after it.
for ( ; i < mInstancingFormat.getElementCount(); i++ )
for ( ; i < mInstancingFormat->getElementCount(); i++ )
{
const GFXVertexElement &nextElement = mInstancingFormat.getElement( i );
const GFXVertexElement &nextElement = mInstancingFormat->getElement( i );
if ( nextElement.getSemantic() != element.getSemantic() )
{
i--;

View file

@ -117,7 +117,6 @@ GFXVertexBuffer * endToBuffer( U32 &numPrims )
}
case GFXTriangleStrip:
case GFXTriangleFan:
{
numPrims = mCurVertIndex - 2;
break;
@ -171,7 +170,6 @@ void end( bool useGenericShaders )
}
case GFXTriangleStrip:
case GFXTriangleFan:
{
stripStart = 2;
vertStride = 1;

View file

@ -110,7 +110,7 @@ namespace
start -= lineVec;
end += lineVec;
GFXVertexBufferHandle<GFXVertexPC> verts(GFX, 4, GFXBufferTypeVolatile);
GFXVertexBufferHandle<GFXVertexPCT> verts(GFX, 4, GFXBufferTypeVolatile);
verts.lock();
verts[0].point.set( start.x+perp.x, start.y+perp.y, z1 );

View file

@ -319,81 +319,79 @@ void GuiGradientCtrl::renderColorBox(RectI &bounds)
void GuiGradientCtrl::drawBlendRangeBox(RectI &bounds, bool vertical, Vector<ColorRange> colorRange)
{
GFX->setStateBlock(mStateBlock);
// Create new global dimensions
// Create new global dimensions
S32 l = bounds.point.x + mSwatchFactor, r = bounds.point.x + bounds.extent.x - mSwatchFactor;
S32 t = bounds.point.y, b = bounds.point.y + bounds.extent.y - mSwatchFactor;
// Draw border using new global dimensions
if (mProfile->mBorder)
GFX->getDrawUtil()->drawRect( RectI( Point2I(l,t),Point2I(r,b) ), mProfile->mBorderColor);
// Update local dimensions
mBlendRangeBox.point = globalToLocalCoord(Point2I(l, t));
mBlendRangeBox.extent = globalToLocalCoord(Point2I(r, b));
ColorRange& firstColorRange = colorRange.first();
if(colorRange.size() == 1) // Only one color to draw
{
PrimBuild::begin( GFXTriangleFan, 4 );
// Draw border using new global dimensions
if (mProfile->mBorder)
GFX->getDrawUtil()->drawRect(RectI(Point2I(l, t), Point2I(r, b)), mProfile->mBorderColor);
PrimBuild::color(firstColorRange.swatch->getColor());
PrimBuild::vertex2i( l, t );
PrimBuild::vertex2i( l, b );
// Update local dimensions
mBlendRangeBox.point = globalToLocalCoord(Point2I(l, t));
mBlendRangeBox.extent = globalToLocalCoord(Point2I(r, b));
PrimBuild::color(firstColorRange.swatch->getColor());
PrimBuild::vertex2i( r, b );
PrimBuild::vertex2i( r, t );
if (colorRange.size() == 1) // Only one color to draw
{
PrimBuild::begin(GFXTriangleStrip, 4);
PrimBuild::end();
}
else
{
PrimBuild::begin( GFXTriangleFan, 4 );
PrimBuild::color(colorRange.first().swatch->getColor());
PrimBuild::vertex2i(l, t);
PrimBuild::vertex2i(r, t);
PrimBuild::color(firstColorRange.swatch->getColor());
PrimBuild::vertex2i( l, t );
PrimBuild::vertex2i( l, b );
PrimBuild::color(colorRange.first().swatch->getColor());
PrimBuild::vertex2i(l, b);
PrimBuild::vertex2i(r, b);
PrimBuild::color(firstColorRange.swatch->getColor());
PrimBuild::vertex2i(l + firstColorRange.swatch->getPosition().x, b);
PrimBuild::vertex2i(l + firstColorRange.swatch->getPosition().x, t);
PrimBuild::end();
}
else
{
PrimBuild::begin(GFXTriangleStrip, 4);
PrimBuild::end();
PrimBuild::color(colorRange.first().swatch->getColor());
PrimBuild::vertex2i(l, t);
PrimBuild::vertex2i(l + colorRange.first().swatch->getPosition().x, t);
for( U16 i = 0;i < colorRange.size() - 1; i++ )
{
PrimBuild::begin( GFXTriangleFan, 4 );
if (!vertical) // Horizontal (+x)
{
// First color
PrimBuild::color( colorRange[i].swatch->getColor() );
PrimBuild::vertex2i( l + colorRange[i].swatch->getPosition().x, t );
PrimBuild::vertex2i( l + colorRange[i].swatch->getPosition().x, b );
// First color
PrimBuild::color( colorRange[i+1].swatch->getColor() );
PrimBuild::vertex2i( l + colorRange[i+1].swatch->getPosition().x, b );
PrimBuild::vertex2i( l + colorRange[i+1].swatch->getPosition().x, t );
}
PrimBuild::end();
}
PrimBuild::color(colorRange.first().swatch->getColor());
PrimBuild::vertex2i(l, b);
PrimBuild::vertex2i(l + colorRange.first().swatch->getPosition().x, b);
ColorRange& lastColorRange = colorRange.last();
PrimBuild::end();
PrimBuild::begin( GFXTriangleFan, 4 );
for (U16 i = 0; i < colorRange.size() - 1; i++)
{
PrimBuild::begin(GFXTriangleStrip, 4);
if (!vertical) // Horizontal (+x)
{
// First color
PrimBuild::color(colorRange[i].swatch->getColor());
PrimBuild::vertex2i(l + colorRange[i].swatch->getPosition().x, t);
PrimBuild::color(colorRange[i + 1].swatch->getColor());
PrimBuild::vertex2i(l + colorRange[i + 1].swatch->getPosition().x, t);
PrimBuild::color(lastColorRange.swatch->getColor());
PrimBuild::vertex2i(l + lastColorRange.swatch->getPosition().x, t);
PrimBuild::vertex2i(l + lastColorRange.swatch->getPosition().x, b);
PrimBuild::color(lastColorRange.swatch->getColor());
PrimBuild::vertex2i( r, b );
PrimBuild::vertex2i( r, t );
// First color
PrimBuild::color(colorRange[i].swatch->getColor());
PrimBuild::vertex2i(l + colorRange[i].swatch->getPosition().x, b);
PrimBuild::color(colorRange[i + 1].swatch->getColor());
PrimBuild::vertex2i(l + colorRange[i + 1].swatch->getPosition().x, b);
}
PrimBuild::end();
}
PrimBuild::end();
}
PrimBuild::begin(GFXTriangleStrip, 4);
PrimBuild::color(colorRange.last().swatch->getColor());
PrimBuild::vertex2i(l + colorRange.last().swatch->getPosition().x, t);
PrimBuild::vertex2i(r, t);
PrimBuild::color(colorRange.last().swatch->getColor());
PrimBuild::vertex2i(l + colorRange.last().swatch->getPosition().x, b);
PrimBuild::vertex2i(r, b);
PrimBuild::end();
}
}
void GuiGradientCtrl::onMouseDown(const GuiEvent &event)

View file

@ -355,7 +355,7 @@ void GuiTextEditSliderCtrl::onRender(Point2I offset, const RectI &updateRect)
Point2I(start.x+14,midPoint.y),
mProfile->mFontColor);
GFXVertexBufferHandle<GFXVertexPC> verts(GFX, 6, GFXBufferTypeVolatile);
GFXVertexBufferHandle<GFXVertexPCT> verts(GFX, 6, GFXBufferTypeVolatile);
verts.lock();
verts[0].color.set( 0, 0, 0 );

View file

@ -114,7 +114,7 @@ class GuiEditCtrl : public GuiControl
SimSet* mSelectedSet;
// grid drawing
GFXVertexBufferHandle<GFXVertexPC> mDots;
GFXVertexBufferHandle<GFXVertexPCT> mDots;
GFXStateBlockRef mDotSB;
mouseModes mMouseDownMode;

View file

@ -196,7 +196,7 @@ void GuiFilterCtrl::onRender(Point2I offset, const RectI &updateRect)
}
// draw the curv
GFXVertexBufferHandle<GFXVertexPC> verts(GFX, ext.x, GFXBufferTypeVolatile);
GFXVertexBufferHandle<GFXVertexPCT> verts(GFX, ext.x, GFXBufferTypeVolatile);
verts.lock();

View file

@ -177,7 +177,7 @@ void GuiGraphCtrl::onRender(Point2I offset, const RectI &updateRect)
for( S32 sample = 0; sample < numSamples; ++ sample )
{
PrimBuild::begin( GFXTriangleFan, 4 );
PrimBuild::begin( GFXTriangleStrip, 4 );
PrimBuild::color( mGraphColor[ k ] );
F32 offset = F32( getExtent().x ) / F32( MaxDataPoints ) * F32( sample + 1 );

View file

@ -1315,7 +1315,7 @@ DefineEngineMethod( EditTSCtrl, renderCircle, void, ( Point3F pos, Point3F norma
{
PrimBuild::color( object->mConsoleFillColor );
PrimBuild::begin( GFXTriangleFan, points.size() + 2 );
PrimBuild::begin( GFXTriangleStrip, points.size() + 2 );
// Center point
PrimBuild::vertex3fv( pos );

View file

@ -1403,7 +1403,7 @@ void Gizmo::renderGizmo(const MatrixF &cameraTransform, F32 cameraFOV )
for(U32 j = 0; j < 6; j++)
{
PrimBuild::begin( GFXTriangleFan, 4 );
PrimBuild::begin( GFXTriangleStrip, 4 );
PrimBuild::vertex3fv( sgCenterBoxPnts[sgBoxVerts[j][0]] * tipScale);
PrimBuild::vertex3fv( sgCenterBoxPnts[sgBoxVerts[j][1]] * tipScale);
@ -1599,7 +1599,7 @@ void Gizmo::_renderAxisBoxes()
for(U32 j = 0; j < 6; j++)
{
PrimBuild::begin( GFXTriangleFan, 4 );
PrimBuild::begin( GFXTriangleStrip, 4 );
PrimBuild::vertex3fv( sgCenterBoxPnts[sgBoxVerts[j][0]] * tipScale + sgAxisVectors[axisIdx] * pos );
PrimBuild::vertex3fv( sgCenterBoxPnts[sgBoxVerts[j][1]] * tipScale + sgAxisVectors[axisIdx] * pos );
@ -1663,7 +1663,7 @@ void Gizmo::_renderAxisCircles()
ColorI color = mProfile->inActiveColor;
color.alpha = 100;
PrimBuild::color( color );
PrimBuild::begin( GFXTriangleFan, segments+2 );
PrimBuild::begin( GFXTriangleStrip, segments+2 );
PrimBuild::vertex3fv( Point3F(0,0,0) );

View file

@ -265,18 +265,18 @@ void GuiTerrPreviewCtrl::onRender(Point2I offset, const RectI &updateRect)
// the texture if flipped horz to reflect how the terrain is really drawn
PrimBuild::color3f(1.0f, 1.0f, 1.0f);
PrimBuild::begin(GFXTriangleFan, 4);
PrimBuild::texCoord2f(textureP1.x, textureP2.y);
PrimBuild::vertex2f(screenP1.x, screenP2.y); // left bottom
PrimBuild::begin(GFXTriangleStrip, 4);
PrimBuild::texCoord2f(textureP1.x, textureP1.y);
PrimBuild::vertex2f(screenP1.x, screenP1.y); // left top
PrimBuild::texCoord2f(textureP2.x, textureP2.y);
PrimBuild::vertex2f(screenP2.x, screenP2.y); // right bottom
PrimBuild::texCoord2f(textureP2.x, textureP1.y);
PrimBuild::vertex2f(screenP2.x, screenP1.y); // right top
PrimBuild::texCoord2f(textureP2.x, textureP1.y);
PrimBuild::vertex2f(screenP2.x, screenP1.y); // right top
PrimBuild::texCoord2f(textureP1.x, textureP1.y);
PrimBuild::vertex2f(screenP1.x, screenP1.y); // left top
PrimBuild::texCoord2f(textureP1.x, textureP2.y);
PrimBuild::vertex2f(screenP1.x, screenP2.y); // left bottom
PrimBuild::texCoord2f(textureP2.x, textureP2.y);
PrimBuild::vertex2f(screenP2.x, screenP2.y); // right bottom
PrimBuild::end();
}
}

View file

@ -658,7 +658,7 @@ void SelectionBrush::rebuild()
//... move the selection
}
void SelectionBrush::render(Vector<GFXVertexPC> & vertexBuffer, S32 & verts, S32 & elems, S32 & prims, const ColorF & inColorFull, const ColorF & inColorNone, const ColorF & outColorFull, const ColorF & outColorNone) const
void SelectionBrush::render(Vector<GFXVertexPCT> & vertexBuffer, S32 & verts, S32 & elems, S32 & prims, const ColorF & inColorFull, const ColorF & inColorNone, const ColorF & outColorFull, const ColorF & outColorNone) const
{
//... render the selection
}
@ -1342,8 +1342,8 @@ void TerrainEditor::renderPoints( const Vector<GFXVertexPCT> &pointList )
U32 vertsThisDrawCall = getMin( (U32)vertsLeft, (U32)MAX_DYNAMIC_VERTS );
vertsLeft -= vertsThisDrawCall;
GFXVertexBufferHandle<GFXVertexPC> vbuff( GFX, vertsThisDrawCall, GFXBufferTypeVolatile );
GFXVertexPC *vert = vbuff.lock();
GFXVertexBufferHandle<GFXVertexPCT> vbuff( GFX, vertsThisDrawCall, GFXBufferTypeVolatile );
GFXVertexPCT *vert = vbuff.lock();
const U32 loops = vertsThisDrawCall / 6;
@ -1394,7 +1394,7 @@ void TerrainEditor::renderSelection( const Selection & sel, const ColorF & inCol
if(sel.size() == 0)
return;
Vector<GFXVertexPC> vertexBuffer;
Vector<GFXVertexPCT> vertexBuffer;
ColorF color;
ColorI iColor;
@ -1430,15 +1430,15 @@ void TerrainEditor::renderSelection( const Selection & sel, const ColorF & inCol
//
iColor = color;
GFXVertexPC *verts = &(vertexBuffer[i * 5]);
GFXVertexPCT *verts = &(vertexBuffer[i * 5]);
verts[0].point = wPos + Point3F(-squareSize, -squareSize, 0);
verts[0].point = wPos + Point3F(-squareSize, squareSize, 0);
verts[0].color = iColor;
verts[1].point = wPos + Point3F( squareSize, -squareSize, 0);
verts[1].point = wPos + Point3F( squareSize, squareSize, 0);
verts[1].color = iColor;
verts[2].point = wPos + Point3F( squareSize, squareSize, 0);
verts[2].point = wPos + Point3F( -squareSize, -squareSize, 0);
verts[2].color = iColor;
verts[3].point = wPos + Point3F(-squareSize, squareSize, 0);
verts[3].point = wPos + Point3F( squareSize, -squareSize, 0);
verts[3].color = iColor;
verts[4].point = verts[0].point;
verts[4].color = iColor;
@ -1452,7 +1452,7 @@ void TerrainEditor::renderSelection( const Selection & sel, const ColorF & inCol
GridPoint selectedGridPoint = sel[i].mGridPoint;
Point2I gPos = selectedGridPoint.gridPos;
GFXVertexPC *verts = &(vertexBuffer[i * 5]);
GFXVertexPCT *verts = &(vertexBuffer[i * 5]);
bool center = gridToWorld(selectedGridPoint, verts[0].point);
gridToWorld(Point2I(gPos.x + 1, gPos.y), verts[1].point, selectedGridPoint.terrainBlock);
@ -1503,12 +1503,12 @@ void TerrainEditor::renderSelection( const Selection & sel, const ColorF & inCol
// Render this bad boy, by stuffing everything into a volatile buffer
// and rendering...
GFXVertexBufferHandle<GFXVertexPC> selectionVB(GFX, vertexBuffer.size(), GFXBufferTypeStatic);
GFXVertexBufferHandle<GFXVertexPCT> selectionVB(GFX, vertexBuffer.size(), GFXBufferTypeStatic);
selectionVB.lock(0, vertexBuffer.size());
// Copy stuff
dMemcpy((void*)&selectionVB[0], (void*)&vertexBuffer[0], sizeof(GFXVertexPC) * vertexBuffer.size());
dMemcpy((void*)&selectionVB[0], (void*)&vertexBuffer[0], sizeof(GFXVertexPCT) * vertexBuffer.size());
selectionVB.unlock();
@ -1518,7 +1518,7 @@ void TerrainEditor::renderSelection( const Selection & sel, const ColorF & inCol
if(renderFill)
for(U32 i=0; i < sel.size(); i++)
GFX->drawPrimitive( GFXTriangleFan, i*5, 4);
GFX->drawPrimitive( GFXTriangleStrip, i*5, 4);
if(renderFrame)
for(U32 i=0; i < sel.size(); i++)

View file

@ -173,7 +173,7 @@ public:
const char *getType() const { return "selection"; }
void rebuild();
void render(Vector<GFXVertexPC> & vertexBuffer, S32 & verts, S32 & elems, S32 & prims, const ColorF & inColorFull, const ColorF & inColorNone, const ColorF & outColorFull, const ColorF & outColorNone) const;
void render(Vector<GFXVertexPCT> & vertexBuffer, S32 & verts, S32 & elems, S32 & prims, const ColorF & inColorFull, const ColorF & inColorNone, const ColorF & outColorFull, const ColorF & outColorNone) const;
void setSize(const Point2I &){}
protected:

View file

@ -1503,7 +1503,7 @@ void WorldEditor::renderSplinePath(SimPath::Path *path)
if(vCount > 4000)
batchSize = 4000;
GFXVertexBufferHandle<GFXVertexPC> vb;
GFXVertexBufferHandle<GFXVertexPCT> vb;
vb.set(GFX, 3*batchSize, GFXBufferTypeVolatile);
void *lockPtr = vb.lock();
if(!lockPtr) return;

View file

@ -305,7 +305,7 @@ void AdvancedLightBinManager::render( SceneRenderState *state )
{
vectorMatInfo->matInstance->setSceneInfo( state, sgData );
vectorMatInfo->matInstance->setTransforms( matrixSet, state );
GFX->drawPrimitive( GFXTriangleFan, 0, 2 );
GFX->drawPrimitive( GFXTriangleStrip, 0, 2 );
}
}
@ -482,24 +482,24 @@ void AdvancedLightBinManager::_setupPerFrameParameters( const SceneRenderState *
// passes.... this is a volatile VB and updates every frame.
FarFrustumQuadVert verts[4];
{
verts[0].point.set( wsFrustumPoints[Frustum::FarBottomLeft] - cameraPos );
invCam.mulP( wsFrustumPoints[Frustum::FarBottomLeft], &verts[0].normal );
verts[0].texCoord.set( -1.0, -1.0 );
verts[0].tangent.set(wsFrustumPoints[Frustum::FarBottomLeft] - cameraOffsetPos);
verts[0].point.set(wsFrustumPoints[Frustum::FarTopLeft] - cameraPos);
invCam.mulP(wsFrustumPoints[Frustum::FarTopLeft], &verts[0].normal);
verts[0].texCoord.set(-1.0, 1.0);
verts[0].tangent.set(wsFrustumPoints[Frustum::FarTopLeft] - cameraOffsetPos);
verts[1].point.set( wsFrustumPoints[Frustum::FarTopLeft] - cameraPos );
invCam.mulP( wsFrustumPoints[Frustum::FarTopLeft], &verts[1].normal );
verts[1].texCoord.set( -1.0, 1.0 );
verts[1].tangent.set(wsFrustumPoints[Frustum::FarTopLeft] - cameraOffsetPos);
verts[1].point.set(wsFrustumPoints[Frustum::FarTopRight] - cameraPos);
invCam.mulP(wsFrustumPoints[Frustum::FarTopRight], &verts[1].normal);
verts[1].texCoord.set(1.0, 1.0);
verts[1].tangent.set(wsFrustumPoints[Frustum::FarTopRight] - cameraOffsetPos);
verts[2].point.set( wsFrustumPoints[Frustum::FarTopRight] - cameraPos );
invCam.mulP( wsFrustumPoints[Frustum::FarTopRight], &verts[2].normal );
verts[2].texCoord.set( 1.0, 1.0 );
verts[2].tangent.set(wsFrustumPoints[Frustum::FarTopRight] - cameraOffsetPos);
verts[2].point.set(wsFrustumPoints[Frustum::FarBottomLeft] - cameraPos);
invCam.mulP(wsFrustumPoints[Frustum::FarBottomLeft], &verts[2].normal);
verts[2].texCoord.set(-1.0, -1.0);
verts[2].tangent.set(wsFrustumPoints[Frustum::FarBottomLeft] - cameraOffsetPos);
verts[3].point.set( wsFrustumPoints[Frustum::FarBottomRight] - cameraPos );
invCam.mulP( wsFrustumPoints[Frustum::FarBottomRight], &verts[3].normal );
verts[3].texCoord.set( 1.0, -1.0 );
verts[3].point.set(wsFrustumPoints[Frustum::FarBottomRight] - cameraPos);
invCam.mulP(wsFrustumPoints[Frustum::FarBottomRight], &verts[3].normal);
verts[3].texCoord.set(1.0, -1.0);
verts[3].tangent.set(wsFrustumPoints[Frustum::FarBottomRight] - cameraOffsetPos);
}
mFarFrustumQuadVerts.set( GFX, 4 );

View file

@ -62,7 +62,6 @@ void DeferredSpecMapGLSL::processPix( Vector<ShaderComponent*> &componentList, c
specularMap->uniform = true;
specularMap->sampler = true;
specularMap->constNum = Var::getTexUnitNum();
LangElement *texOp = new GenOp( "tex2D(@, @)", specularMap, texCoord );
//matinfo.g slot reserved for AO later
meta->addStatement(new GenOp(" @.g = 1.0;\r\n", material));
meta->addStatement(new GenOp(" @.b = dot(tex2D(@, @).rgb, vec3(0.3, 0.59, 0.11));\r\n", material, specularMap, texCoord));

View file

@ -114,7 +114,7 @@ void GBufferConditionerGLSL::processVert( Vector<ShaderComponent*> &componentLis
// TODO: Total hack because Conditioner is directly derived
// from ShaderFeature and not from ShaderFeatureGLSL.
NamedFeatureGLSL dummy( String::EmptyString );
dummy.mInstancingFormat = mInstancingFormat;
dummy.setInstancingFormat( mInstancingFormat );
Var *worldViewOnly = dummy.getWorldView( componentList, fd.features[MFT_UseInstancing], meta );
meta->addStatement( new GenOp(" @ = tMul(@, float4( normalize(@), 0.0 ) ).xyz;\r\n",

View file

@ -126,6 +126,18 @@ void DeferredRTLightingFeatHLSL::processPix( Vector<ShaderComponent*> &component
lightInfoBuffer->sampler = true;
lightInfoBuffer->constNum = Var::getTexUnitNum(); // used as texture unit num here
Var* lightBufferTex = NULL;
if (mIsDirect3D11)
{
lightInfoBuffer->setType("SamplerState");
lightBufferTex = new Var;
lightBufferTex->setName("lightInfoBufferTex");
lightBufferTex->setType("Texture2D");
lightBufferTex->uniform = true;
lightBufferTex->texture = true;
lightBufferTex->constNum = lightInfoBuffer->constNum;
}
// Declare the RTLighting variables in this feature, they will either be assigned
// in this feature, or in the tonemap/lightmap feature
Var *d_lightcolor = new Var( "d_lightcolor", "float3" );
@ -140,8 +152,12 @@ void DeferredRTLightingFeatHLSL::processPix( Vector<ShaderComponent*> &component
// Perform the uncondition here.
String unconditionLightInfo = String::ToLower( AdvancedLightBinManager::smBufferName ) + "Uncondition";
meta->addStatement( new GenOp( avar( " %s(tex2D(@, @), @, @, @);\r\n",
unconditionLightInfo.c_str() ), lightInfoBuffer, uvScene, d_lightcolor, d_NL_Att, d_specular ) );
if (mIsDirect3D11)
meta->addStatement(new GenOp(avar(" %s(@.Sample(@, @), @, @, @);\r\n",
unconditionLightInfo.c_str()), lightBufferTex, lightInfoBuffer, uvScene, d_lightcolor, d_NL_Att, d_specular));
else
meta->addStatement(new GenOp(avar(" %s(tex2D(@, @), @, @, @);\r\n",
unconditionLightInfo.c_str()), lightInfoBuffer, uvScene, d_lightcolor, d_NL_Att, d_specular));
// If this has an interlaced pre-pass, do averaging here
if( fd.features[MFT_InterlacedPrePass] )
@ -157,8 +173,12 @@ void DeferredRTLightingFeatHLSL::processPix( Vector<ShaderComponent*> &component
}
meta->addStatement( new GenOp( " float id_NL_Att, id_specular;\r\n float3 id_lightcolor;\r\n" ) );
meta->addStatement( new GenOp( avar( " %s(tex2D(@, @ + float2(0.0, @.y)), id_lightcolor, id_NL_Att, id_specular);\r\n",
unconditionLightInfo.c_str() ), lightInfoBuffer, uvScene, oneOverTargetSize ) );
if (mIsDirect3D11)
meta->addStatement(new GenOp(avar(" %s(@.Sample(@, @ + float2(0.0, @.y)), id_lightcolor, id_NL_Att, id_specular);\r\n",
unconditionLightInfo.c_str()), lightBufferTex, lightInfoBuffer, uvScene, oneOverTargetSize));
else
meta->addStatement(new GenOp(avar(" %s(tex2D(@, @ + float2(0.0, @.y)), id_lightcolor, id_NL_Att, id_specular);\r\n",
unconditionLightInfo.c_str()), lightInfoBuffer, uvScene, oneOverTargetSize));
meta->addStatement( new GenOp(" @ = lerp(@, id_lightcolor, 0.5);\r\n", d_lightcolor, d_lightcolor ) );
meta->addStatement( new GenOp(" @ = lerp(@, id_NL_Att, 0.5);\r\n", d_NL_Att, d_NL_Att ) );
@ -272,8 +292,17 @@ void DeferredBumpFeatHLSL::processPix( Vector<ShaderComponent*> &componentList,
// create texture var
Var *bumpMap = getNormalMapTex();
Var *texCoord = getInTexCoord( "texCoord", "float2", true, componentList );
LangElement *texOp = new GenOp( "tex2D(@, @)", bumpMap, texCoord );
Var *texCoord = getInTexCoord("texCoord", "float2", true, componentList);
LangElement *texOp = NULL;
if (mIsDirect3D11)
{
Var *bumpMapTex = (Var*)LangElement::find("bumpMapTex");
texOp = new GenOp("@.Sample(@, @)", bumpMapTex, bumpMap, texCoord);
}
else
texOp = new GenOp("tex2D(@, @)", bumpMap, texCoord);
// create bump normal
Var *bumpNorm = new Var;
@ -295,8 +324,25 @@ void DeferredBumpFeatHLSL::processPix( Vector<ShaderComponent*> &componentList,
bumpMap->sampler = true;
bumpMap->constNum = Var::getTexUnitNum();
texCoord = getInTexCoord( "detCoord", "float2", true, componentList );
texOp = new GenOp( "tex2D(@, @)", bumpMap, texCoord );
Var* detailNormalTex = NULL;
if (mIsDirect3D11)
{
bumpMap->setType("SamplerState");
detailNormalTex = new Var;
detailNormalTex->setName("detailBumpMapTex");
detailNormalTex->setType("Texture2D");
detailNormalTex->uniform = true;
detailNormalTex->texture = true;
detailNormalTex->constNum = bumpMap->constNum;
}
texCoord = getInTexCoord("detCoord", "float2", true, componentList);
if (mIsDirect3D11)
texOp = new GenOp("@.Sample(@, @)", detailNormalTex, bumpMap, texCoord);
else
texOp = new GenOp("tex2D(@, @)", bumpMap, texCoord);
Var *detailBump = new Var;
detailBump->setName( "detailBump" );
@ -333,25 +379,32 @@ void DeferredBumpFeatHLSL::processPix( Vector<ShaderComponent*> &componentList,
else if (fd.features[MFT_AccuMap])
{
Var *bumpSample = (Var *)LangElement::find( "bumpSample" );
if( bumpSample == NULL )
if (bumpSample == NULL)
{
MultiLine *meta = new MultiLine;
Var *texCoord = getInTexCoord( "texCoord", "float2", true, componentList );
Var *texCoord = getInTexCoord("texCoord", "float2", true, componentList);
Var *bumpMap = getNormalMapTex();
bumpSample = new Var;
bumpSample->setType( "float4" );
bumpSample->setName( "bumpSample" );
LangElement *bumpSampleDecl = new DecOp( bumpSample );
bumpSample->setType("float4");
bumpSample->setName("bumpSample");
LangElement *bumpSampleDecl = new DecOp(bumpSample);
meta->addStatement( new GenOp( " @ = tex2D(@, @);\r\n", bumpSampleDecl, bumpMap, texCoord ) );
if (mIsDirect3D11)
{
Var *bumpMapTex = (Var *)LangElement::find("bumpMapTex");
output = new GenOp(" @ = @.Sample(@, @);\r\n", bumpSampleDecl, bumpMapTex, bumpMap, texCoord);
}
else
output = new GenOp(" @ = tex2D(@, @);\r\n", bumpSampleDecl, bumpMap, texCoord);
if ( fd.features.hasFeature( MFT_DetailNormalMap ) )
{
Var *bumpMap = (Var*)LangElement::find( "detailBumpMap" );
if ( !bumpMap ) {
if ( !bumpMap )
{
bumpMap = new Var;
bumpMap->setType( "sampler2D" );
bumpMap->setName( "detailBumpMap" );
@ -360,8 +413,24 @@ void DeferredBumpFeatHLSL::processPix( Vector<ShaderComponent*> &componentList,
bumpMap->constNum = Var::getTexUnitNum();
}
Var* bumpMapTex = (Var*)LangElement::find("detailBumpMap");
if (mIsDirect3D11 && !bumpMapTex)
{
bumpMap->setType("SamplerState");
bumpMapTex = new Var;
bumpMapTex->setName("detailBumpMapTex");
bumpMapTex->setType("Texture2D");
bumpMapTex->uniform = true;
bumpMapTex->texture = true;
bumpMapTex->constNum = bumpMap->constNum;
}
texCoord = getInTexCoord( "detCoord", "float2", true, componentList );
LangElement *texOp = new GenOp( "tex2D(@, @)", bumpMap, texCoord );
LangElement *texOp = NULL;
if (mIsDirect3D11)
texOp = new GenOp("@.Sample(@, @)", bumpMap, bumpMapTex, texCoord);
else
texOp = new GenOp( "tex2D(@, @)", bumpMap, texCoord );
Var *detailBump = new Var;
detailBump->setName( "detailBump" );
@ -402,7 +471,14 @@ void DeferredBumpFeatHLSL::processPix( Vector<ShaderComponent*> &componentList,
bumpSample->setName( "bumpSample" );
LangElement *bumpSampleDecl = new DecOp( bumpSample );
output = new GenOp( " @ = tex2D(@, @);\r\n", bumpSampleDecl, bumpMap, texCoord );
if (mIsDirect3D11)
{
Var *bumpMapTex = (Var *)LangElement::find("bumpMapTex");
output = new GenOp(" @ = @.Sample(@, @);\r\n", bumpSampleDecl, bumpMapTex, bumpMap, texCoord);
}
else
output = new GenOp(" @ = tex2D(@, @);\r\n", bumpSampleDecl, bumpMap, texCoord);
return;
}
}
@ -547,7 +623,8 @@ void DeferredPixelSpecularHLSL::processPix( Vector<ShaderComponent*> &component
AssertFatal( lightInfoSamp && d_specular && d_NL_Att,
"DeferredPixelSpecularHLSL::processPix - Something hosed the deferred features!" );
if (fd.features[ MFT_AccuMap ]) {
if (fd.features[ MFT_AccuMap ])
{
// change specularity where the accu texture is applied
Var *accuPlc = (Var*) LangElement::find( "plc" );
Var *accuSpecular = (Var*)LangElement::find( "accuSpecular" );
@ -671,6 +748,18 @@ void DeferredMinnaertHLSL::processPix( Vector<ShaderComponent*> &componentList,
prepassBuffer->sampler = true;
prepassBuffer->constNum = Var::getTexUnitNum(); // used as texture unit num here
Var* prePassTex = NULL;
if (mIsDirect3D11)
{
prepassBuffer->setType("SamplerState");
prePassTex = new Var;
prePassTex->setName("prePassTex");
prePassTex->setType("Texture2D");
prePassTex->uniform = true;
prePassTex->texture = true;
prePassTex->constNum = prepassBuffer->constNum;
}
// Texture coord
Var *uvScene = (Var*) LangElement::find( "uvScene" );
AssertFatal(uvScene != NULL, "Unable to find UVScene, no RTLighting feature?");
@ -684,7 +773,11 @@ void DeferredMinnaertHLSL::processPix( Vector<ShaderComponent*> &componentList,
Var *d_NL_Att = (Var*)LangElement::find( "d_NL_Att" );
meta->addStatement( new GenOp( avar( " float4 normalDepth = %s(@, @);\r\n", unconditionPrePassMethod.c_str() ), prepassBuffer, uvScene ) );
if (mIsDirect3D11)
meta->addStatement(new GenOp(avar(" float4 normalDepth = %s(@, ,@, @);\r\n", unconditionPrePassMethod.c_str()), prepassBuffer, prePassTex, uvScene));
else
meta->addStatement(new GenOp(avar(" float4 normalDepth = %s(@, @);\r\n", unconditionPrePassMethod.c_str()), prepassBuffer, uvScene));
meta->addStatement( new GenOp( " float vDotN = dot(normalDepth.xyz, @);\r\n", wsViewVec ) );
meta->addStatement( new GenOp( " float Minnaert = pow( @, @) * pow(vDotN, 1.0 - @);\r\n", d_NL_Att, minnaertConstant, minnaertConstant ) );
meta->addStatement( new GenOp( " @;\r\n", assignColor( new GenOp( "float4(Minnaert, Minnaert, Minnaert, 1.0)" ), Material::Mul ) ) );

View file

@ -62,12 +62,35 @@ void DeferredSpecMapHLSL::processPix( Vector<ShaderComponent*> &componentList, c
specularMap->uniform = true;
specularMap->sampler = true;
specularMap->constNum = Var::getTexUnitNum();
LangElement *texOp = new GenOp( "tex2D(@, @)", specularMap, texCoord );
Var* specularMapTex = NULL;
if (mIsDirect3D11)
{
specularMap->setType("SamplerState");
specularMapTex = new Var;
specularMapTex->setName("specularMapTex");
specularMapTex->setType("Texture2D");
specularMapTex->uniform = true;
specularMapTex->texture = true;
specularMapTex->constNum = specularMap->constNum;
}
//matinfo.g slot reserved for AO later
Var* specColor = new Var;
specColor->setName("specColor");
specColor->setType("float4");
LangElement *specColorElem = new DecOp(specColor);
meta->addStatement(new GenOp(" @.g = 1.0;\r\n", material));
meta->addStatement(new GenOp(" @.b = dot(tex2D(@, @).rgb, float3(0.3, 0.59, 0.11));\r\n", material, specularMap, texCoord));
meta->addStatement(new GenOp(" @.a = tex2D(@, @).a;\r\n", material, specularMap, texCoord));
//sample specular map
if (mIsDirect3D11)
meta->addStatement(new GenOp(" @ = @.Sample(@, @);\r\n", specColorElem, specularMapTex, specularMap, texCoord));
else
meta->addStatement(new GenOp(" @ = tex2D(@, @);\r\n", specColorElem, specularMap, texCoord));
meta->addStatement(new GenOp(" @.b = dot(@.rgb, float3(0.3, 0.59, 0.11));\r\n", material, specColor));
meta->addStatement(new GenOp(" @.a = @.a;\r\n", material, specColor));
output = meta;
}

View file

@ -28,7 +28,7 @@
#include "materials/materialFeatureTypes.h"
#include "materials/materialFeatureData.h"
#include "shaderGen/hlsl/shaderFeatureHLSL.h"
#include "gfx/gfxDevice.h"
GBufferConditionerHLSL::GBufferConditionerHLSL( const GFXFormat bufferFormat, const NormalSpace nrmSpace ) :
Parent( bufferFormat )
@ -114,7 +114,7 @@ void GBufferConditionerHLSL::processVert( Vector<ShaderComponent*> &componentLis
// TODO: Total hack because Conditioner is directly derived
// from ShaderFeature and not from ShaderFeatureHLSL.
NamedFeatureHLSL dummy( String::EmptyString );
dummy.mInstancingFormat = mInstancingFormat;
dummy.setInstancingFormat( mInstancingFormat );
Var *worldViewOnly = dummy.getWorldView( componentList, fd.features[MFT_UseInstancing], meta );
meta->addStatement( new GenOp(" @ = mul(@, float4( normalize(@), 0.0 ) ).xyz;\r\n",
@ -222,6 +222,7 @@ Var* GBufferConditionerHLSL::printMethodHeader( MethodType methodType, const Str
retVal = Parent::printMethodHeader( methodType, methodName, stream, meta );
else
{
const bool isDirect3D11 = GFX->getAdapterType() == Direct3D11;
Var *methodVar = new Var;
methodVar->setName(methodName);
methodVar->setType("inline float4");
@ -237,12 +238,28 @@ Var* GBufferConditionerHLSL::printMethodHeader( MethodType methodType, const Str
screenUV->setType("float2");
DecOp *screenUVDecl = new DecOp(screenUV);
Var *prepassTex = NULL;
DecOp *prepassTexDecl = NULL;
if (isDirect3D11)
{
prepassSampler->setType("SamplerState");
prepassTex = new Var;
prepassTex->setName("prepassTexVar");
prepassTex->setType("Texture2D");
prepassTex->texture = true;
prepassTex->constNum = prepassSampler->constNum;
prepassTexDecl = new DecOp(prepassTex);
}
Var *bufferSample = new Var;
bufferSample->setName("bufferSample");
bufferSample->setType("float4");
DecOp *bufferSampleDecl = new DecOp(bufferSample);
meta->addStatement( new GenOp( "@(@, @)\r\n", methodDecl, prepassSamplerDecl, screenUVDecl ) );
if (isDirect3D11)
meta->addStatement(new GenOp("@(@, @, @)\r\n", methodDecl, prepassSamplerDecl, prepassTexDecl, screenUVDecl));
else
meta->addStatement( new GenOp( "@(@, @)\r\n", methodDecl, prepassSamplerDecl, screenUVDecl ) );
meta->addStatement( new GenOp( "{\r\n" ) );
@ -255,10 +272,14 @@ Var* GBufferConditionerHLSL::printMethodHeader( MethodType methodType, const Str
// The gbuffer has no mipmaps, so use tex2dlod when
// possible so that the shader compiler can optimize.
meta->addStatement( new GenOp( " #if TORQUE_SM >= 30\r\n" ) );
meta->addStatement( new GenOp( " @ = tex2Dlod(@, float4(@,0,0));\r\n", bufferSampleDecl, prepassSampler, screenUV ) );
meta->addStatement( new GenOp( " #else\r\n" ) );
meta->addStatement( new GenOp( " @ = tex2D(@, @);\r\n", bufferSampleDecl, prepassSampler, screenUV ) );
meta->addStatement( new GenOp( " #endif\r\n\r\n" ) );
if (isDirect3D11)
meta->addStatement(new GenOp(" @ = @.SampleLevel(@, @,0);\r\n", bufferSampleDecl, prepassTex, prepassSampler, screenUV));
else
meta->addStatement(new GenOp(" @ = tex2Dlod(@, float4(@,0,0));\r\n", bufferSampleDecl, prepassSampler, screenUV));
meta->addStatement(new GenOp(" #else\r\n"));
meta->addStatement(new GenOp(" @ = tex2D(@, @);\r\n", bufferSampleDecl, prepassSampler, screenUV));
meta->addStatement(new GenOp(" #endif\r\n\r\n"));
#endif
// We don't use this way of passing var's around, so this should cause a crash

View file

@ -338,7 +338,7 @@ void BlobShadow::render( F32 camDist, const TSRenderState &rdata )
GFX->setVertexBuffer(mShadowBuffer);
for(U32 p=0; p<mPartition.size(); p++)
GFX->drawPrimitive(GFXTriangleFan, mPartition[p].vertexStart, (mPartition[p].vertexCount - 2));
GFX->drawPrimitive(GFXTriangleStrip, mPartition[p].vertexStart, (mPartition[p].vertexCount - 2));
// This is a bad nasty hack which forces the shadow to reconstruct itself every frame.
mPartition.clear();

View file

@ -22,10 +22,6 @@
#ifndef _MISCSHDRDAT_H_
#define _MISCSHDRDAT_H_
#ifndef _PLATFORM_H_
#include "platform/platform.h"
#endif
//**************************************************************************
// This file is an attempt to keep certain classes from having to know about
// the ShaderGen class
@ -45,6 +41,7 @@ enum RegisterType
RT_COLOR,
RT_TEXCOORD,
RT_VPOS,
RT_SVPOSITION
};
enum Components
@ -52,7 +49,7 @@ enum Components
C_VERT_STRUCT = 0,
C_CONNECTOR,
C_VERT_MAIN,
C_PIX_MAIN,
C_PIX_MAIN
};
#endif // _MISCSHDRDAT_H_

View file

@ -209,7 +209,7 @@ bool ProcessedShaderMaterial::init( const FeatureSet &features,
if ( mFeatures.hasFeature( MFT_UseInstancing ) )
{
mInstancingState = new InstancingState();
mInstancingState->setFormat( &_getRPD( 0 )->shader->mInstancingFormat, mVertexFormat );
mInstancingState->setFormat( _getRPD( 0 )->shader->getInstancingFormat(), mVertexFormat );
}
return true;
}

View file

@ -167,6 +167,8 @@ protected:
mInstFormat = instFormat;
mDeclFormat.copy( *vertexFormat );
mDeclFormat.append( *mInstFormat, 1 );
// Let the declaration know we have instancing.
mDeclFormat.enableInstancing();
mDeclFormat.getDecl();
delete [] mBuffer;

View file

@ -236,6 +236,7 @@ GFXShader* ShaderData::_createShader( const Vector<GFXShaderMacro> &macros )
{
case Direct3D9_360:
case Direct3D9:
case Direct3D11:
{
success = shader->init( mDXVertexShaderName,
mDXPixelShaderName,

View file

@ -25,6 +25,7 @@
//#include <comdef.h>
#include <wbemidl.h>
//#include <atlconv.h>
#include <DXGI.h>
#pragma comment(lib, "comsuppw.lib")
#pragma comment(lib, "wbemuuid.lib")
@ -53,58 +54,6 @@ struct MYGUID : public GUID
}
};
//------------------------------------------------------------------------------
// DXGI decls for retrieving device info on Vista. We manually declare that
// stuff here, so we don't depend on headers and compile on any setup. At
// run-time, it depends on whether we can successfully load the DXGI DLL; if
// not, nothing of this here will be used.
struct IDXGIObject;
struct IDXGIFactory;
struct IDXGIAdapter;
struct IDXGIOutput;
struct DXGI_SWAP_CHAIN_DESC;
struct DXGI_ADAPTER_DESC;
struct IDXGIObject : public IUnknown
{
virtual HRESULT STDMETHODCALLTYPE SetPrivateData( REFGUID, UINT, const void* ) = 0;
virtual HRESULT STDMETHODCALLTYPE SetPrivateDataInterface( REFGUID, const IUnknown* ) = 0;
virtual HRESULT STDMETHODCALLTYPE GetPrivateData( REFGUID, UINT*, void* ) = 0;
virtual HRESULT STDMETHODCALLTYPE GetParent( REFIID, void** ) = 0;
};
struct IDXGIFactory : public IDXGIObject
{
virtual HRESULT STDMETHODCALLTYPE EnumAdapters( UINT, IDXGIAdapter** ) = 0;
virtual HRESULT STDMETHODCALLTYPE MakeWindowAssociation( HWND, UINT ) = 0;
virtual HRESULT STDMETHODCALLTYPE GetWindowAssociation( HWND ) = 0;
virtual HRESULT STDMETHODCALLTYPE CreateSwapChain( IUnknown*, DXGI_SWAP_CHAIN_DESC* ) = 0;
virtual HRESULT STDMETHODCALLTYPE CreateSoftwareAdapter( HMODULE, IDXGIAdapter** ) = 0;
};
struct IDXGIAdapter : public IDXGIObject
{
virtual HRESULT STDMETHODCALLTYPE EnumOutputs( UINT, IDXGIOutput** ) = 0;
virtual HRESULT STDMETHODCALLTYPE GetDesc( DXGI_ADAPTER_DESC* ) = 0;
virtual HRESULT STDMETHODCALLTYPE CheckInterfaceSupport( REFGUID, LARGE_INTEGER* ) = 0;
};
struct DXGI_ADAPTER_DESC
{
WCHAR Description[ 128 ];
UINT VendorId;
UINT DeviceId;
UINT SubSysId;
UINT Revision;
SIZE_T DedicatedVideoMemory;
SIZE_T DedicatedSystemMemory;
SIZE_T SharedSystemMemory;
LUID AdapterLuid;
};
static MYGUID IID_IDXGIFactory( 0x7b7166ec, 0x21c7, 0x44ae, 0xb2, 0x1a, 0xc9, 0xae, 0x32, 0x1a, 0xe3, 0x69 );
//------------------------------------------------------------------------------
// DXDIAG declarations.
@ -184,6 +133,26 @@ WMIVideoInfo::~WMIVideoInfo()
//------------------------------------------------------------------------------
String WMIVideoInfo::_lookUpVendorId(U32 vendorId)
{
String vendor;
switch (vendorId)
{
case 0x10DE:
vendor = "NVIDIA";
break;
case 0x1002:
vendor = "AMD";
break;
case 0x8086:
vendor = "INTEL";
break;
}
return vendor;
}
//------------------------------------------------------------------------------
bool WMIVideoInfo::_initialize()
{
// Init COM
@ -282,16 +251,15 @@ bool WMIVideoInfo::_initializeWMI()
bool WMIVideoInfo::_initializeDXGI()
{
// Try going for DXGI. Will only succeed on Vista.
#if 0
// Try using for DXGI 1.1, will only succeed on Windows 7+.
mDXGIModule = ( HMODULE ) LoadLibrary( L"dxgi.dll" );
if( mDXGIModule != 0 )
{
typedef HRESULT (* CreateDXGIFactoryFuncType )( REFIID, void** );
typedef HRESULT (WINAPI* CreateDXGIFactoryFuncType )( REFIID, void** );
CreateDXGIFactoryFuncType factoryFunction =
( CreateDXGIFactoryFuncType ) GetProcAddress( ( HMODULE ) mDXGIModule, "CreateDXGIFactory" );
( CreateDXGIFactoryFuncType ) GetProcAddress( ( HMODULE ) mDXGIModule, "CreateDXGIFactory1" );
if( factoryFunction && factoryFunction( IID_IDXGIFactory, ( void** ) &mDXGIFactory ) == S_OK )
if( factoryFunction && factoryFunction( IID_IDXGIFactory1, ( void** ) &mDXGIFactory ) == S_OK )
return true;
else
{
@ -299,7 +267,7 @@ bool WMIVideoInfo::_initializeDXGI()
mDXGIModule = 0;
}
}
#endif
return false;
}
@ -483,20 +451,36 @@ bool WMIVideoInfo::_queryPropertyDxDiag( const PVIQueryType queryType, const U32
bool WMIVideoInfo::_queryPropertyDXGI( const PVIQueryType queryType, const U32 adapterId, String *outValue )
{
#if 0
if( mDXGIFactory )
{
IDXGIAdapter* adapter;
if( mDXGIFactory->EnumAdapters( adapterId, &adapter ) != S_OK )
// Special case to deal with PVI_NumAdapters
if (queryType == PVI_NumAdapters)
{
U32 count = 0;
IDXGIAdapter1 *adapter;
while (mDXGIFactory->EnumAdapters1(count, &adapter) != DXGI_ERROR_NOT_FOUND)
{
++count;
adapter->Release();
}
String value = String::ToString("%d", count);
*outValue = value;
return true;
}
IDXGIAdapter1* adapter;
if( mDXGIFactory->EnumAdapters1( adapterId, &adapter ) != S_OK )
return false;
DXGI_ADAPTER_DESC desc;
if( adapter->GetDesc( &desc ) != S_OK )
DXGI_ADAPTER_DESC1 desc;
if( adapter->GetDesc1( &desc ) != S_OK )
{
adapter->Release();
return false;
}
String value;
switch( queryType )
{
@ -511,15 +495,17 @@ bool WMIVideoInfo::_queryPropertyDXGI( const PVIQueryType queryType, const U32 a
case PVI_VRAM:
value = String( avar( "%i", desc.DedicatedVideoMemory / 1048576 ) );
break;
//RDTODO
case PVI_ChipSet:
value = _lookUpVendorId(desc.VendorId);
break;
//TODO PVI_DriverVersion
}
adapter->Release();
*outValue = value;
return true;
}
#endif
return false;
}

View file

@ -28,7 +28,7 @@
struct IWbemLocator;
struct IWbemServices;
struct IDXGIFactory;
struct IDXGIFactory1;
struct IDxDiagProvider;
class WMIVideoInfo : public PlatformVideoInfo
@ -39,7 +39,7 @@ private:
bool mComInitialized;
void* mDXGIModule;
IDXGIFactory* mDXGIFactory;
IDXGIFactory1* mDXGIFactory;
IDxDiagProvider* mDxDiagProvider;
bool _initializeDXGI();
@ -54,6 +54,7 @@ protected:
static WCHAR *smPVIQueryTypeToWMIString [];
bool _queryProperty( const PVIQueryType queryType, const U32 adapterId, String *outValue );
bool _initialize();
String _lookUpVendorId(U32 vendorId);
public:
WMIVideoInfo();

View file

@ -510,23 +510,23 @@ void PostEffect::_updateScreenGeometry( const Frustum &frustum,
PFXVertex *vert = outVB->lock();
vert->point.set( -1.0, -1.0, 0.0 );
vert->texCoord.set( 0.0f, 1.0f );
vert->wsEyeRay = frustumPoints[Frustum::FarBottomLeft] - cameraOffsetPos;
vert++;
vert->point.set( -1.0, 1.0, 0.0 );
vert->texCoord.set( 0.0f, 0.0f );
vert->point.set(-1.0, 1.0, 0.0);
vert->texCoord.set(0.0f, 0.0f);
vert->wsEyeRay = frustumPoints[Frustum::FarTopLeft] - cameraOffsetPos;
vert++;
vert->point.set( 1.0, 1.0, 0.0 );
vert->texCoord.set( 1.0f, 0.0f );
vert->point.set(1.0, 1.0, 0.0);
vert->texCoord.set(1.0f, 0.0f);
vert->wsEyeRay = frustumPoints[Frustum::FarTopRight] - cameraOffsetPos;
vert++;
vert->point.set( 1.0, -1.0, 0.0 );
vert->texCoord.set( 1.0f, 1.0f );
vert->point.set(-1.0, -1.0, 0.0);
vert->texCoord.set(0.0f, 1.0f);
vert->wsEyeRay = frustumPoints[Frustum::FarBottomLeft] - cameraOffsetPos;
vert++;
vert->point.set(1.0, -1.0, 0.0);
vert->texCoord.set(1.0f, 1.0f);
vert->wsEyeRay = frustumPoints[Frustum::FarBottomRight] - cameraOffsetPos;
vert++;
@ -1275,7 +1275,7 @@ void PostEffect::process( const SceneRenderState *state,
// Draw it.
GFX->setVertexBuffer( vb );
GFX->drawPrimitive( GFXTriangleFan, 0, 2 );
GFX->drawPrimitive( GFXTriangleStrip, 0, 2 );
// Allow PostEffecVis to hook in.
PFXVIS->onPFXProcessed( this );

View file

@ -388,7 +388,6 @@ void RenderPrePassMgr::render( SceneRenderState *state )
GFXTextureObject *lastLM = NULL;
GFXCubemap *lastCubemap = NULL;
GFXTextureObject *lastReflectTex = NULL;
GFXTextureObject *lastMiscTex = NULL;
GFXTextureObject *lastAccuTex = NULL;
// Next render all the meshes.

View file

@ -248,8 +248,18 @@ GFXTextureObject* ReflectionManager::getRefractTex( bool forceUpdate )
const U32 desWidth = targetSize.x;
const U32 desHeight = targetSize.y;
#else
const U32 desWidth = mFloor( (F32)targetSize.x * smRefractTexScale );
const U32 desHeight = mFloor( ( F32)targetSize.y * smRefractTexScale );
U32 desWidth, desHeight;
// D3D11 needs to be the same size as the active target
if (GFX->getAdapterType() == Direct3D11)
{
desWidth = targetSize.x;
desHeight = targetSize.y;
}
else
{
desWidth = mFloor((F32)targetSize.x * smRefractTexScale);
desHeight = mFloor((F32)targetSize.y * smRefractTexScale);
}
#endif
if ( mRefractTex.isNull() ||

View file

@ -273,7 +273,7 @@ DefineEngineMethod( Path, getPathId, S32, (),,
//--------------------------------------------------------------------------
GFXStateBlockRef Marker::smStateBlock;
GFXVertexBufferHandle<GFXVertexPC> Marker::smVertexBuffer;
GFXVertexBufferHandle<GFXVertexPCT> Marker::smVertexBuffer;
GFXPrimitiveBufferHandle Marker::smPrimitiveBuffer;
static Point3F wedgePoints[4] = {
@ -295,7 +295,7 @@ void Marker::initGFXResources()
smStateBlock = GFX->createStateBlock(d);
smVertexBuffer.set(GFX, 4, GFXBufferTypeStatic);
GFXVertexPC* verts = smVertexBuffer.lock();
GFXVertexPCT* verts = smVertexBuffer.lock();
verts[0].point = wedgePoints[0] * 0.25f;
verts[1].point = wedgePoints[1] * 0.25f;
verts[2].point = wedgePoints[2] * 0.25f;

View file

@ -132,7 +132,7 @@ class Marker : public SceneObject
static void initGFXResources();
static GFXStateBlockRef smStateBlock;
static GFXVertexBufferHandle<GFXVertexPC> smVertexBuffer;
static GFXVertexBufferHandle<GFXVertexPCT> smVertexBuffer;
static GFXPrimitiveBufferHandle smPrimitiveBuffer;
public:

View file

@ -85,7 +85,8 @@ void AccuTexFeatHLSL::processPix( Vector<ShaderComponent*> &componentList,
// accu constants
Var *accuScale = (Var*)LangElement::find( "accuScale" );
if ( !accuScale ) {
if ( !accuScale )
{
accuScale = new Var;
accuScale->setType( "float" );
accuScale->setName( "accuScale" );
@ -94,7 +95,8 @@ void AccuTexFeatHLSL::processPix( Vector<ShaderComponent*> &componentList,
accuScale->constSortPos = cspPotentialPrimitive;
}
Var *accuDirection = (Var*)LangElement::find( "accuDirection" );
if ( !accuDirection ) {
if ( !accuDirection )
{
accuDirection = new Var;
accuDirection->setType( "float" );
accuDirection->setName( "accuDirection" );
@ -103,7 +105,8 @@ void AccuTexFeatHLSL::processPix( Vector<ShaderComponent*> &componentList,
accuDirection->constSortPos = cspPotentialPrimitive;
}
Var *accuStrength = (Var*)LangElement::find( "accuStrength" );
if ( !accuStrength ) {
if ( !accuStrength )
{
accuStrength = new Var;
accuStrength->setType( "float" );
accuStrength->setName( "accuStrength" );
@ -112,7 +115,8 @@ void AccuTexFeatHLSL::processPix( Vector<ShaderComponent*> &componentList,
accuStrength->constSortPos = cspPotentialPrimitive;
}
Var *accuCoverage = (Var*)LangElement::find( "accuCoverage" );
if ( !accuCoverage ) {
if ( !accuCoverage )
{
accuCoverage = new Var;
accuCoverage->setType( "float" );
accuCoverage->setName( "accuCoverage" );
@ -121,7 +125,8 @@ void AccuTexFeatHLSL::processPix( Vector<ShaderComponent*> &componentList,
accuCoverage->constSortPos = cspPotentialPrimitive;
}
Var *accuSpecular = (Var*)LangElement::find( "accuSpecular" );
if ( !accuSpecular ) {
if ( !accuSpecular )
{
accuSpecular = new Var;
accuSpecular->setType( "float" );
accuSpecular->setName( "accuSpecular" );
@ -133,14 +138,26 @@ void AccuTexFeatHLSL::processPix( Vector<ShaderComponent*> &componentList,
Var *inTex = getInTexCoord( "texCoord", "float2", true, componentList );
Var *accuVec = getInTexCoord( "accuVec", "float3", true, componentList );
Var *bumpNorm = (Var *)LangElement::find( "bumpSample" );
if( bumpNorm == NULL ) {
if( bumpNorm == NULL )
{
bumpNorm = (Var *)LangElement::find( "bumpNormal" );
if (!bumpNorm)
return;
}
// get the accu pixel color
meta->addStatement( new GenOp( " @ = tex2D(@, @ * @);\r\n", colorAccuDecl, accuMap, inTex, accuScale ) );
if (mIsDirect3D11)
{
Var *accuMapTex = new Var;
accuMapTex->setType("Texture2D");
accuMapTex->setName("accuMapTex");
accuMapTex->uniform = true;
accuMapTex->texture = true;
accuMapTex->constNum = accuMap->constNum;
meta->addStatement(new GenOp(" @ = @.Sample(@, @ * @);\r\n", colorAccuDecl, accuMapTex, accuMap, inTex, accuScale));
}
else
meta->addStatement(new GenOp(" @ = tex2D(@, @ * @);\r\n", colorAccuDecl, accuMap, inTex, accuScale));
// scale up normals
meta->addStatement( new GenOp( " @.xyz = @.xyz * 2.0 - 0.5;\r\n", bumpNorm, bumpNorm ) );

View file

@ -70,6 +70,13 @@ void BumpFeatHLSL::processPix( Vector<ShaderComponent*> &componentList,
Var *bumpMap = getNormalMapTex();
LangElement *texOp = NULL;
//if it's D3D11 let's create the texture object
Var* bumpMapTex = NULL;
if (mIsDirect3D11)
{
bumpMapTex = (Var*)LangElement::find("bumpMapTex");
}
// Handle atlased textures
// http://www.infinity-universe.com/Infinity/index.php?option=com_content&task=view&id=65&Itemid=47
if(fd.features[MFT_NormalMapAtlas])
@ -127,18 +134,25 @@ void BumpFeatHLSL::processPix( Vector<ShaderComponent*> &componentList,
// Add a newline
meta->addStatement( new GenOp( "\r\n" ) );
if(is_sm3)
if (mIsDirect3D11)
{
texOp = new GenOp( "tex2Dlod(@, float4(@, 0.0, mipLod_bump))", bumpMap, texCoord );
texOp = new GenOp("@.SampleLevel(@, @, mipLod_bump)", bumpMapTex, bumpMap, texCoord);
}
else if (is_sm3)
{
texOp = new GenOp("tex2Dlod(@, float4(@, 0.0, mipLod_bump))", bumpMap, texCoord);
}
else
{
texOp = new GenOp( "tex2D(@, @)", bumpMap, texCoord );
texOp = new GenOp("tex2D(@, @)", bumpMap, texCoord);
}
}
else
{
texOp = new GenOp( "tex2D(@, @)", bumpMap, texCoord );
if (mIsDirect3D11)
texOp = new GenOp("@.Sample(@, @)", bumpMapTex, bumpMap, texCoord);
else
texOp = new GenOp("tex2D(@, @)", bumpMap, texCoord);
}
Var *bumpNorm = new Var( "bumpNormal", "float4" );
@ -156,8 +170,26 @@ void BumpFeatHLSL::processPix( Vector<ShaderComponent*> &componentList,
bumpMap->sampler = true;
bumpMap->constNum = Var::getTexUnitNum();
Var* detailBumpTex = NULL;
if (mIsDirect3D11)
{
bumpMap->setType("SamplerState");
detailBumpTex = new Var;
detailBumpTex->setName("detailBumpTex");
detailBumpTex->setType("Texture2D");
detailBumpTex->uniform = true;
detailBumpTex->texture = true;
detailBumpTex->constNum = bumpMap->constNum;
}
else
bumpMap->setType("sampler2D");
texCoord = getInTexCoord( "detCoord", "float2", true, componentList );
texOp = new GenOp( "tex2D(@, @)", bumpMap, texCoord );
if (mIsDirect3D11)
texOp = new GenOp("@.Sample(@, @)", detailBumpTex, bumpMap, texCoord);
else
texOp = new GenOp("tex2D(@, @)", bumpMap, texCoord);
Var *detailBump = new Var;
detailBump->setName( "detailBump" );
@ -345,17 +377,26 @@ void ParallaxFeatHLSL::processPix( Vector<ShaderComponent*> &componentList,
// Get the rest of our inputs.
Var *parallaxInfo = _getUniformVar( "parallaxInfo", "float", cspPotentialPrimitive );
Var *normalMap = getNormalMapTex();
Var *bumpMapTexture = (Var*)LangElement::find("bumpMapTex");
// Call the library function to do the rest.
if(fd.features.hasFeature( MFT_IsDXTnm, getProcessIndex() ))
if (fd.features.hasFeature(MFT_IsDXTnm, getProcessIndex()))
{
meta->addStatement( new GenOp( " @.xy += parallaxOffsetDxtnm( @, @.xy, @, @ );\r\n",
texCoord, normalMap, texCoord, negViewTS, parallaxInfo ) );
if (mIsDirect3D11)
meta->addStatement(new GenOp(" @.xy += parallaxOffsetDxtnm( @, @, @.xy, @, @ );\r\n",
texCoord, bumpMapTexture, normalMap, texCoord, negViewTS, parallaxInfo));
else
meta->addStatement(new GenOp(" @.xy += parallaxOffsetDxtnm( @, @.xy, @, @ );\r\n",
texCoord, normalMap, texCoord, negViewTS, parallaxInfo));
}
else
{
meta->addStatement( new GenOp( " @.xy += parallaxOffset( @, @.xy, @, @ );\r\n",
texCoord, normalMap, texCoord, negViewTS, parallaxInfo ) );
if (mIsDirect3D11)
meta->addStatement(new GenOp(" @.xy += parallaxOffset( @, @, @.xy, @, @ );\r\n",
texCoord, bumpMapTexture, normalMap, texCoord, negViewTS, parallaxInfo));
else
meta->addStatement(new GenOp(" @.xy += parallaxOffset( @, @.xy, @, @ );\r\n",
texCoord, normalMap, texCoord, negViewTS, parallaxInfo));
}
// TODO: Fix second UV maybe?

View file

@ -46,9 +46,13 @@ void ParaboloidVertTransformHLSL::processVert( Vector<ShaderComponent*> &compon
ShaderConnector *connectComp = dynamic_cast<ShaderConnector *>( componentList[C_CONNECTOR] );
// Grab connector out position.
Var *outPosition = connectComp->getElement( RT_POSITION );
outPosition->setName( "hpos" );
outPosition->setStructName( "OUT" );
RegisterType type = RT_POSITION;
if (mIsDirect3D11)
type = RT_SVPOSITION;
Var *outPosition = connectComp->getElement(type);
outPosition->setName("hpos");
outPosition->setStructName("OUT");
// Get the atlas scale.
Var *atlasScale = new Var;

View file

@ -77,8 +77,12 @@ void PixelSpecularHLSL::processPix( Vector<ShaderComponent*> &componentList,
{
LangElement * lightMap = LangElement::find( "lightMap" );
LangElement * lmCoord = LangElement::find( "texCoord2" );
LangElement * lightMapTex = LangElement::find("lightMapTex"); //used only DX11 shaders
lmColor = new GenOp( "tex2D(@, @)", lightMap, lmCoord );
if (lightMapTex)
lmColor = new GenOp("@.Sample(@, @)", lightMapTex, lightMap, lmCoord);
else
lmColor = new GenOp("tex2D(@, @)", lightMap, lmCoord);
}
final = new GenOp( "@ * float4(@.rgb,0)", specMul, lmColor );
@ -138,11 +142,33 @@ void SpecularMapHLSL::processPix( Vector<ShaderComponent*> &componentList, const
specularMap->uniform = true;
specularMap->sampler = true;
specularMap->constNum = Var::getTexUnitNum();
LangElement *texOp = new GenOp( "tex2D(@, @)", specularMap, texCoord );
Var *specularMapTex = NULL;
Var *specularColor = new Var( "specularColor", "float4" );
if (mIsDirect3D11)
{
specularMap->setType("SamplerState");
specularMapTex = new Var;
specularMapTex->setName("specularMapTex");
specularMapTex->setType("Texture2D");
specularMapTex->uniform = true;
specularMapTex->texture = true;
specularMapTex->constNum = specularMap->constNum;
}
else
{
specularMap->setType("sampler2D");
}
output = new GenOp( " @ = @;\r\n", new DecOp( specularColor ), texOp );
LangElement *texOp = NULL;
if (specularMapTex)
texOp = new GenOp("@.Sample(@, @)", specularMapTex, specularMap, texCoord);
else
texOp = new GenOp("tex2D(@, @)", specularMap, texCoord);
Var *specularColor = new Var("specularColor", "float4");
output = new GenOp(" @ = @;\r\n", new DecOp(specularColor), texOp);
}
ShaderFeature::Resources SpecularMapHLSL::getResources( const MaterialFeatureData &fd )

View file

@ -55,6 +55,25 @@ Var * ShaderConnectorHLSL::getIndexedElement( U32 index, RegisterType type, U32
Var *newVar = new Var;
mElementList.push_back( newVar );
newVar->setConnectName( "POSITION" );
newVar->rank = 0;
return newVar;
}
case RT_VPOS:
{
Var *newVar = new Var;
mElementList.push_back(newVar);
newVar->setConnectName("VPOS");
newVar->rank = 0;
return newVar;
}
case RT_SVPOSITION:
{
Var *newVar = new Var;
mElementList.push_back(newVar);
newVar->setConnectName("SV_Position");
newVar->rank = 0;
return newVar;
}
@ -63,6 +82,7 @@ Var * ShaderConnectorHLSL::getIndexedElement( U32 index, RegisterType type, U32
Var *newVar = new Var;
mElementList.push_back( newVar );
newVar->setConnectName( "NORMAL" );
newVar->rank = 1;
return newVar;
}
@ -71,6 +91,7 @@ Var * ShaderConnectorHLSL::getIndexedElement( U32 index, RegisterType type, U32
Var *newVar = new Var;
mElementList.push_back( newVar );
newVar->setConnectName( "BINORMAL" );
newVar->rank = 2;
return newVar;
}
@ -79,6 +100,7 @@ Var * ShaderConnectorHLSL::getIndexedElement( U32 index, RegisterType type, U32
Var *newVar = new Var;
mElementList.push_back( newVar );
newVar->setConnectName( "TANGENT" );
newVar->rank = 3;
return newVar;
}
@ -87,14 +109,7 @@ Var * ShaderConnectorHLSL::getIndexedElement( U32 index, RegisterType type, U32
Var *newVar = new Var;
mElementList.push_back( newVar );
newVar->setConnectName( "COLOR" );
return newVar;
}
case RT_VPOS:
{
Var *newVar = new Var;
mElementList.push_back( newVar );
newVar->setConnectName( "VPOS" );
newVar->rank = 4;
return newVar;
}
@ -113,6 +128,7 @@ Var * ShaderConnectorHLSL::getIndexedElement( U32 index, RegisterType type, U32
newVar->setConnectName( out );
newVar->constNum = index;
newVar->arraySize = numElements;
newVar->rank = 5 + index;
return newVar;
}
@ -124,67 +140,27 @@ Var * ShaderConnectorHLSL::getIndexedElement( U32 index, RegisterType type, U32
return NULL;
}
S32 QSORT_CALLBACK ShaderConnectorHLSL::_hlsl4VarSort(const void* e1, const void* e2)
{
Var* a = *((Var **)e1);
Var* b = *((Var **)e2);
return a->rank - b->rank;
}
void ShaderConnectorHLSL::sortVars()
{
if ( GFX->getPixelShaderVersion() >= 2.0 )
// If shader model 4+ than we gotta sort the vars to make sure the order is consistent
if (GFX->getPixelShaderVersion() >= 4.f)
{
dQsort((void *)&mElementList[0], mElementList.size(), sizeof(Var *), _hlsl4VarSort);
return;
// Sort connector variables - They must be sorted on hardware that is running
// ps 1.4 and below. The reason is that texture coordinate registers MUST
// map exactly to their respective texture stage. Ie. if you have fog
// coordinates being passed into a pixel shader in texture coordinate register
// number 4, the fog texture MUST reside in texture stage 4 for it to work.
// The problem is solved by pushing non-texture coordinate data to the end
// of the structure so that the texture coodinates are all at the "top" of the
// structure in the order that the features are processed.
// create list of just the texCoords, sorting by 'mapsToSampler'
Vector< Var * > texCoordList;
// - first pass is just coords mapped to a sampler
for( U32 i=0; i<mElementList.size(); i++ )
{
Var *var = mElementList[i];
if( var->mapsToSampler )
{
texCoordList.push_back( var );
}
}
// - next pass is for the others
for( U32 i=0; i<mElementList.size(); i++ )
{
Var *var = mElementList[i];
if( dStrstr( (const char *)var->connectName, "TEX" ) &&
!var->mapsToSampler )
{
texCoordList.push_back( var );
}
}
// rename the connectNames
for( U32 i=0; i<texCoordList.size(); i++ )
{
char out[32];
dSprintf( (char*)out, sizeof(out), "TEXCOORD%d", i );
texCoordList[i]->setConnectName( out );
}
// write new, sorted list over old one
if( texCoordList.size() )
{
U32 index = 0;
for( U32 i=0; i<mElementList.size(); i++ )
{
Var *var = mElementList[i];
if( dStrstr( (const char *)var->connectName, "TEX" ) )
{
mElementList[i] = texCoordList[index];
index++;
}
}
}
return;
}
void ShaderConnectorHLSL::setName( char *newName )
@ -246,7 +222,7 @@ void ParamsDefHLSL::assignConstantNumbers()
Var *var = dynamic_cast<Var*>(LangElement::elementList[i]);
if( var )
{
bool shaderConst = var->uniform && !var->sampler;
bool shaderConst = var->uniform && !var->sampler && !var->texture;
AssertFatal((!shaderConst) || var->constSortPos != cspUninit, "Const sort position has not been set, variable will not receive a constant number!!");
if( shaderConst && var->constSortPos == bin)
{
@ -328,6 +304,10 @@ void PixelParamsDefHLSL::print( Stream &stream, bool isVerterShader )
{
dSprintf( (char*)varNum, sizeof(varNum), ": register(S%d)", var->constNum );
}
else if (var->texture)
{
dSprintf((char*)varNum, sizeof(varNum), ": register(T%d)", var->constNum);
}
else
{
dSprintf( (char*)varNum, sizeof(varNum), ": register(C%d)", var->constNum );

View file

@ -30,6 +30,8 @@
class ShaderConnectorHLSL : public ShaderConnector
{
private:
static S32 QSORT_CALLBACK _hlsl4VarSort(const void* e1, const void* e2);
public:
// ShaderConnector

View file

@ -173,6 +173,7 @@ LangElement *ShaderFeatureHLSL::expandNormalMap( LangElement *sampleNormalOp,
ShaderFeatureHLSL::ShaderFeatureHLSL()
{
output = NULL;
mIsDirect3D11 = GFX->getAdapterType() == Direct3D11;
}
Var * ShaderFeatureHLSL::getVertTexCoord( const String &name )
@ -354,7 +355,7 @@ Var* ShaderFeatureHLSL::getOutTexCoord( const char *name,
if ( useTexAnim )
{
inTex->setType( "float4" );
inTex->setType( "float2" );
// create texture mat var
Var *texMat = new Var;
@ -365,7 +366,7 @@ Var* ShaderFeatureHLSL::getOutTexCoord( const char *name,
// Statement allows for casting of different types which
// eliminates vector truncation problems.
String statement = String::ToString( " @ = (%s)mul(@, @).xy;\r\n", type );
String statement = String::ToString(" @ = (%s)mul(@, float4(@,1,1));\r\n", type);
meta->addStatement( new GenOp( statement, texCoord, texMat, inTex ) );
}
else
@ -464,7 +465,17 @@ Var* ShaderFeatureHLSL::getInVpos( MultiLine *meta,
ShaderConnector *connectComp = dynamic_cast<ShaderConnector*>( componentList[C_CONNECTOR] );
if ( GFX->getPixelShaderVersion() >= 3.0f )
F32 pixelShaderVer = GFX->getPixelShaderVersion();
if ( pixelShaderVer >= 4.0f )
{
inVpos = connectComp->getElement( RT_SVPOSITION );
inVpos->setName( "vpos" );
inVpos->setStructName( "IN" );
inVpos->setType( "float4" );
return inVpos;
}
else if ( pixelShaderVer >= 3.0f )
{
inVpos = connectComp->getElement( RT_VPOS );
inVpos->setName( "vpos" );
@ -516,15 +527,30 @@ Var* ShaderFeatureHLSL::getInViewToTangent( Vector<ShaderComponent*> &componentL
Var* ShaderFeatureHLSL::getNormalMapTex()
{
Var *normalMap = (Var*)LangElement::find( "bumpMap" );
if ( !normalMap )
Var *normalMap = (Var*)LangElement::find("bumpMap");
if (!normalMap)
{
normalMap = new Var;
normalMap->setType( "sampler2D" );
normalMap->setName( "bumpMap" );
normalMap->setType("sampler2D");
normalMap->setName("bumpMap");
normalMap->uniform = true;
normalMap->sampler = true;
normalMap->constNum = Var::getTexUnitNum();
// D3D11
Var* normalMapTex = NULL;
if (GFX->getAdapterType() == Direct3D11)
{
normalMap->setType("SamplerState");
normalMapTex = new Var;
normalMapTex->setName("bumpMapTex");
normalMapTex->setType("Texture2D");
normalMapTex->uniform = true;
normalMapTex->texture = true;
normalMapTex->constNum = normalMap->constNum;
}
}
return normalMap;
@ -780,6 +806,7 @@ Var* ShaderFeatureHLSL::addOutDetailTexCoord( Vector<ShaderComponent*> &compon
// Grab incoming texture coords.
Var *inTex = getVertTexCoord( "texCoord" );
inTex->setType("float2");
// create detail variable
Var *detScale = new Var;
@ -798,8 +825,6 @@ Var* ShaderFeatureHLSL::addOutDetailTexCoord( Vector<ShaderComponent*> &compon
if ( useTexAnim )
{
inTex->setType( "float4" );
// Find or create the texture matrix.
Var *texMat = (Var*)LangElement::find( "texMat" );
if ( !texMat )
@ -811,7 +836,7 @@ Var* ShaderFeatureHLSL::addOutDetailTexCoord( Vector<ShaderComponent*> &compon
texMat->constSortPos = cspPass;
}
meta->addStatement( new GenOp( " @ = mul(@, @).xy * @;\r\n", outTex, texMat, inTex, detScale ) );
meta->addStatement(new GenOp(" @ = mul(@, float4(@,1,1)).xy * @;\r\n", outTex, texMat, inTex, detScale));
}
else
{
@ -869,6 +894,19 @@ void DiffuseMapFeatHLSL::processPix( Vector<ShaderComponent*> &componentList,
diffuseMap->sampler = true;
diffuseMap->constNum = Var::getTexUnitNum(); // used as texture unit num here
Var* diffuseMapTex = NULL;
if (mIsDirect3D11)
{
diffuseMap->setType("SamplerState");
diffuseMapTex = new Var;
diffuseMapTex->setName("diffuseMapTex");
diffuseMapTex->setType("Texture2D");
diffuseMapTex->uniform = true;
diffuseMapTex->texture = true;
diffuseMapTex->constNum = diffuseMap->constNum;
}
// create sample color
Var *diffColor = new Var;
diffColor->setType("float4");
@ -880,13 +918,14 @@ void DiffuseMapFeatHLSL::processPix( Vector<ShaderComponent*> &componentList,
if ( fd.features[MFT_CubeMap] )
{
meta->addStatement( new GenOp( " @ = tex2D(@, @);\r\n",
colorDecl,
diffuseMap,
inTex ) );
if (mIsDirect3D11)
meta->addStatement(new GenOp(" @ = @.Sample(@, @);\r\n", colorDecl, diffuseMapTex, diffuseMap, inTex));
else
meta->addStatement(new GenOp(" @ = tex2D(@, @);\r\n", colorDecl, diffuseMap, inTex));
if (!fd.features[MFT_Imposter])
meta->addStatement(new GenOp(" @ = toLinear(@);\r\n", diffColor, diffColor));
meta->addStatement(new GenOp(" @;\r\n", assignColor(diffColor, Material::Mul, NULL, targ)));
}
else if(fd.features[MFT_DiffuseMapAtlas])
@ -958,15 +997,19 @@ void DiffuseMapFeatHLSL::processPix( Vector<ShaderComponent*> &componentList,
return;
}
#endif
if(is_sm3)
if (mIsDirect3D11)
{
meta->addStatement(new GenOp(" @ = @.SampleLevel(@,@,mipLod);\r\n",
new DecOp(diffColor), diffuseMapTex, diffuseMap, inTex));
}
else if(is_sm3)
{
meta->addStatement(new GenOp( " @ = tex2Dlod(@, float4(@, 0.0, mipLod));\r\n",
new DecOp(diffColor), diffuseMap, inTex));
}
else
{
meta->addStatement(new GenOp( " @ = tex2D(@, @);\r\n",
meta->addStatement(new GenOp( " @ = tex2D(@, @);\r\n",
new DecOp(diffColor), diffuseMap, inTex));
}
if (!fd.features[MFT_Imposter])
@ -976,7 +1019,11 @@ void DiffuseMapFeatHLSL::processPix( Vector<ShaderComponent*> &componentList,
}
else
{
meta->addStatement(new GenOp("@ = tex2D(@, @);\r\n", colorDecl, diffuseMap, inTex));
if (mIsDirect3D11)
meta->addStatement(new GenOp("@ = @.Sample(@, @);\r\n", colorDecl, diffuseMapTex, diffuseMap, inTex));
else
meta->addStatement(new GenOp("@ = tex2D(@, @);\r\n", colorDecl, diffuseMap, inTex));
if (!fd.features[MFT_Imposter])
meta->addStatement(new GenOp(" @ = toLinear(@);\r\n", diffColor, diffColor));
meta->addStatement(new GenOp(" @;\r\n", assignColor(diffColor, Material::Mul, NULL, targ)));
@ -1067,7 +1114,24 @@ void OverlayTexFeatHLSL::processPix( Vector<ShaderComponent*> &componentList,
diffuseMap->sampler = true;
diffuseMap->constNum = Var::getTexUnitNum(); // used as texture unit num here
LangElement *statement = new GenOp( "tex2D(@, @)", diffuseMap, inTex );
Var* diffuseMapTex = NULL;
if (mIsDirect3D11)
{
diffuseMap->setType("SamplerState");
diffuseMapTex = new Var;
diffuseMapTex->setName("overlayMapTex");
diffuseMapTex->setType("Texture2D");
diffuseMapTex->uniform = true;
diffuseMapTex->texture = true;
diffuseMapTex->constNum = diffuseMap->constNum;
}
LangElement *statement = NULL;
if (mIsDirect3D11)
statement = new GenOp("@.Sample(@, @)", diffuseMapTex, diffuseMap, inTex);
else
statement = new GenOp("tex2D(@, @)", diffuseMap, inTex);
output = new GenOp( " @;\r\n", assignColor( statement, Material::LerpAlpha ) );
}
@ -1240,6 +1304,17 @@ void LightmapFeatHLSL::processPix( Vector<ShaderComponent*> &componentList,
lightMap->sampler = true;
lightMap->constNum = Var::getTexUnitNum(); // used as texture unit num here
Var *lightMapTex = NULL;
if (mIsDirect3D11)
{
lightMap->setType("SamplerState");
lightMapTex->setName("lightMapTex");
lightMapTex->setType("Texture2D");
lightMapTex->uniform = true;
lightMapTex->texture = true;
lightMapTex->constNum = lightMap->constNum;
}
// argh, pixel specular should prob use this too
if( fd.features[MFT_NormalMap] )
@ -1249,7 +1324,10 @@ void LightmapFeatHLSL::processPix( Vector<ShaderComponent*> &componentList,
lmColor->setType( "float4" );
LangElement *lmColorDecl = new DecOp( lmColor );
output = new GenOp( " @ = tex2D(@, @);\r\n", lmColorDecl, lightMap, inTex );
if (mIsDirect3D11)
output = new GenOp(" @ = @.Sample(@, @);\r\n", lmColorDecl, lightMapTex, lightMap, inTex);
else
output = new GenOp(" @ = tex2D(@, @);\r\n", lmColorDecl, lightMap, inTex);
return;
}
@ -1269,16 +1347,26 @@ void LightmapFeatHLSL::processPix( Vector<ShaderComponent*> &componentList,
// Lightmap has already been included in the advanced light bin, so
// no need to do any sampling or anything
if(bPreProcessedLighting)
statement = new GenOp( "float4(@, 1.0)", inColor );
if (bPreProcessedLighting)
statement = new GenOp("float4(@, 1.0)", inColor);
else
statement = new GenOp( "tex2D(@, @) + float4(@.rgb, 0.0)", lightMap, inTex, inColor );
{
if (mIsDirect3D11)
statement = new GenOp("@.Sample(@, @) + float4(@.rgb, 0.0)", lightMapTex, lightMap, inTex, inColor);
else
statement = new GenOp("tex2D(@, @) + float4(@.rgb, 0.0)", lightMap, inTex, inColor);
}
}
}
// If we still don't have it... then just sample the lightmap.
if ( !statement )
statement = new GenOp( "tex2D(@, @)", lightMap, inTex );
if (!statement)
{
if (mIsDirect3D11)
statement = new GenOp("@.Sample(@, @)", lightMapTex, lightMap, inTex);
else
statement = new GenOp("tex2D(@, @)", lightMap, inTex);
}
// Assign to proper render target
MultiLine *meta = new MultiLine;
@ -1365,6 +1453,18 @@ void TonemapFeatHLSL::processPix( Vector<ShaderComponent*> &componentList,
toneMap->sampler = true;
toneMap->constNum = Var::getTexUnitNum(); // used as texture unit num here
Var *toneMapTex = NULL;
if (mIsDirect3D11)
{
toneMap->setType("SamplerState");
toneMapTex = new Var;
toneMapTex->setName("toneMapTex");
toneMapTex->setType("Texture2D");
toneMapTex->uniform = true;
toneMapTex->texture = true;
toneMapTex->constNum = toneMap->constNum;
}
MultiLine * meta = new MultiLine;
// First get the toneMap color
@ -1373,7 +1473,10 @@ void TonemapFeatHLSL::processPix( Vector<ShaderComponent*> &componentList,
toneMapColor->setName( "toneMapColor" );
LangElement *toneMapColorDecl = new DecOp( toneMapColor );
meta->addStatement( new GenOp( " @ = tex2D(@, @);\r\n", toneMapColorDecl, toneMap, inTex2 ) );
if (mIsDirect3D11)
meta->addStatement(new GenOp(" @ = @.Sample(@, @);\r\n", toneMapColorDecl, toneMapTex, toneMap, inTex2));
else
meta->addStatement(new GenOp(" @ = tex2D(@, @);\r\n", toneMapColorDecl, toneMap, inTex2));
// We do a different calculation if there is a diffuse map or not
Material::BlendOp blendOp = Material::Mul;
@ -1602,6 +1705,18 @@ void DetailFeatHLSL::processPix( Vector<ShaderComponent*> &componentList,
detailMap->sampler = true;
detailMap->constNum = Var::getTexUnitNum(); // used as texture unit num here
Var* detailMapTex = NULL;
if (mIsDirect3D11)
{
detailMap->setType("SamplerState");
detailMapTex = new Var;
detailMapTex->setName("detailMapTex");
detailMapTex->setType("Texture2D");
detailMapTex->uniform = true;
detailMapTex->texture = true;
detailMapTex->constNum = detailMap->constNum;
}
// We're doing the standard greyscale detail map
// technique which can darken and lighten the
// diffuse texture.
@ -1609,7 +1724,12 @@ void DetailFeatHLSL::processPix( Vector<ShaderComponent*> &componentList,
// TODO: We could add a feature to toggle between this
// and a simple multiplication with the detail map.
LangElement *statement = new GenOp( "( tex2D(@, @) * 2.0 ) - 1.0", detailMap, inTex );
LangElement *statement = NULL;
if (mIsDirect3D11)
statement = new GenOp("( @.Sample(@, @) * 2.0 ) - 1.0", detailMapTex, detailMap, inTex);
else
statement = new GenOp("( tex2D(@, @) * 2.0 ) - 1.0", detailMap, inTex);
if ( fd.features[MFT_isDeferred])
output = new GenOp( " @;\r\n", assignColor( statement, Material::Add, NULL, ShaderFeature::RenderTarget1 ) );
else
@ -1665,7 +1785,12 @@ void VertPositionHLSL::processVert( Vector<ShaderComponent*> &componentList,
// grab connector position
ShaderConnector *connectComp = dynamic_cast<ShaderConnector *>( componentList[C_CONNECTOR] );
Var *outPosition = connectComp->getElement( RT_POSITION );
Var *outPosition = NULL;
if (mIsDirect3D11)
outPosition = connectComp->getElement(RT_SVPOSITION);
else
outPosition = connectComp->getElement(RT_POSITION);
outPosition->setName( "hpos" );
outPosition->setStructName( "OUT" );
@ -1679,6 +1804,19 @@ void VertPositionHLSL::processVert( Vector<ShaderComponent*> &componentList,
output = meta;
}
void VertPositionHLSL::processPix( Vector<ShaderComponent*> &componentList,
const MaterialFeatureData &fd)
{
if (mIsDirect3D11)
{
// grab connector position
ShaderConnector *connectComp = dynamic_cast<ShaderConnector *>(componentList[C_CONNECTOR]);
Var *outPosition = connectComp->getElement(RT_SVPOSITION);
outPosition->setName("vpos");
outPosition->setStructName("IN");
}
}
//****************************************************************************
// Reflect Cubemap
@ -1738,8 +1876,11 @@ void ReflectCubeFeatHLSL::processVert( Vector<ShaderComponent*> &componentList,
cubeNormal->setType( "float3" );
LangElement *cubeNormDecl = new DecOp( cubeNormal );
meta->addStatement( new GenOp( " @ = normalize( mul(@, float4(normalize(@),0.0)).xyz );\r\n",
cubeNormDecl, cubeTrans, inNormal ) );
meta->addStatement(new GenOp(" @ = ( mul( (@), float4(@, 0) ) ).xyz;\r\n",
cubeNormDecl, cubeTrans, inNormal));
meta->addStatement(new GenOp(" @ = bool(length(@)) ? normalize(@) : @;\r\n",
cubeNormal, cubeNormal, cubeNormal, cubeNormal));
// grab the eye position
Var *eyePos = (Var*)LangElement::find( "eyePosWorld" );
@ -1782,10 +1923,10 @@ void ReflectCubeFeatHLSL::processPix( Vector<ShaderComponent*> &componentList,
// current pass - we need to add one to the current pass to use
// its alpha channel as a gloss map.
if( !fd.features[MFT_DiffuseMap] &&
!fd.features[MFT_NormalMap] )
!fd.features[MFT_NormalMap])
{
if( fd.materialFeatures[MFT_DiffuseMap] ||
fd.materialFeatures[MFT_NormalMap] )
fd.materialFeatures[MFT_NormalMap])
{
// grab connector texcoord register
Var *inTex = getInTexCoord( "texCoord", "float2", true, componentList );
@ -1797,6 +1938,19 @@ void ReflectCubeFeatHLSL::processPix( Vector<ShaderComponent*> &componentList,
newMap->uniform = true;
newMap->sampler = true;
newMap->constNum = Var::getTexUnitNum(); // used as texture unit num here
Var* glowMapTex = NULL;
if (mIsDirect3D11)
{
newMap->setType("SamplerState");
glowMapTex = new Var;
glowMapTex->setName("glowMapTex");
glowMapTex->setType("Texture2D");
glowMapTex->uniform = true;
glowMapTex->texture = true;
glowMapTex->constNum = newMap->constNum;
}
// create sample color
Var *color = new Var;
@ -1806,7 +1960,10 @@ void ReflectCubeFeatHLSL::processPix( Vector<ShaderComponent*> &componentList,
glossColor = color;
meta->addStatement( new GenOp( " @ = tex2D( @, @ );\r\n", colorDecl, newMap, inTex ) );
if (mIsDirect3D11)
meta->addStatement(new GenOp(" @ = @.Sample( @, @ );\r\n", colorDecl, glowMapTex, newMap, inTex));
else
meta->addStatement(new GenOp(" @ = tex2D( @, @ );\r\n", colorDecl, newMap, inTex));
}
}
else
@ -1837,6 +1994,18 @@ void ReflectCubeFeatHLSL::processPix( Vector<ShaderComponent*> &componentList,
cubeMap->sampler = true;
cubeMap->constNum = Var::getTexUnitNum(); // used as texture unit num here
Var* cubeMapTex = NULL;
if (mIsDirect3D11)
{
cubeMap->setType("SamplerState");
cubeMapTex = new Var;
cubeMapTex->setName("cubeMapTex");
cubeMapTex->setType("TextureCube"); // cubeMapTex->setType("TextureCube");
cubeMapTex->uniform = true;
cubeMapTex->texture = true;
cubeMapTex->constNum = cubeMap->constNum;
}
// TODO: Restore the lighting attenuation here!
Var *attn = NULL;
//if ( fd.materialFeatures[MFT_DynamicLight] )
@ -1855,15 +2024,37 @@ void ReflectCubeFeatHLSL::processPix( Vector<ShaderComponent*> &componentList,
//LangElement *texCube = new GenOp( "texCUBElod( @, float4(@, min((1.0 - (@ / 128.0)) * 11.0 + 1.0, 8.0)) )", cubeMap, reflectVec, specPower );
if (fd.features[MFT_DeferredSpecMap])
texCube = new GenOp("texCUBElod( @, float4(@, (@.a*5)) )", cubeMap, reflectVec, matinfo);
{
if (mIsDirect3D11)
texCube = new GenOp("@.SampleLevel( @, @, @.a*5)", cubeMapTex, cubeMap, reflectVec, matinfo);
else
texCube = new GenOp("texCUBElod( @, float4(@, (@.a*5)) )", cubeMap, reflectVec, matinfo);
}
else
texCube = new GenOp("texCUBElod( @, float4(@, ((1.0-@.a)*6)) )", cubeMap, reflectVec, matinfo);
{
if (mIsDirect3D11)
texCube = new GenOp("@.SampleLevel( @, @, (1.0-@.a)*6 )", cubeMapTex, cubeMap, reflectVec, matinfo);
else
texCube = new GenOp("texCUBElod( @, float4(@, ((1.0-@.a)*6)) )", cubeMap, reflectVec, matinfo);
}
}
else
{
if (glossColor) //failing that, rtry and find color data
texCube = new GenOp("texCUBElod( @, float4(@, @.a*5))", cubeMap, reflectVec, glossColor);
{
if (mIsDirect3D11)
texCube = new GenOp("@.SampleLevel( @, @, @.a*5)", cubeMapTex, cubeMap, reflectVec, glossColor);
else
texCube = new GenOp("texCUBElod( @, float4(@, @.a*5))", cubeMap, reflectVec, glossColor);
}
else //failing *that*, just draw the cubemap
texCube = new GenOp("texCUBE( @, @)", cubeMap, reflectVec);
{
if (mIsDirect3D11)
texCube = new GenOp("@.Sample( @, @ )", cubeMapTex, cubeMap, reflectVec);
else
texCube = new GenOp("texCUBE( @, @ )", cubeMap, reflectVec);
}
}
LangElement *lerpVal = NULL;
Material::BlendOp blendOp = Material::LerpAlpha;
@ -1898,7 +2089,7 @@ void ReflectCubeFeatHLSL::processPix( Vector<ShaderComponent*> &componentList,
if (fd.features[MFT_DeferredSpecMap])
meta->addStatement(new GenOp(" @.rgb = lerp( @.rgb, (@).rgb, (@.b));\r\n", targ, targ, texCube, lerpVal));
else
meta->addStatement(new GenOp(" @.rgb = lerp( @.rgb, (@).rgb, (@.b));\r\n", targ, targ, texCube, lerpVal));
meta->addStatement(new GenOp(" @.rgb = lerp( @.rgb, (@).rgb, (@.b*128/5));\r\n", targ, targ, texCube, lerpVal));
}
else
meta->addStatement( new GenOp( " @;\r\n", assignColor( texCube, blendOp, lerpVal ) ) );
@ -1951,7 +2142,7 @@ void ReflectCubeFeatHLSL::setTexData( Material::StageData &stageDat,
}
}
}
if( stageDat.getCubemap() )
{
passData.mCubeMap = stageDat.getCubemap();
@ -2397,7 +2588,8 @@ void VisibilityFeatHLSL::processPix( Vector<ShaderComponent*> &componentList,
// Everything else does a fizzle.
Var *vPos = getInVpos( meta, componentList );
meta->addStatement( new GenOp( " fizzle( @, @ );\r\n", vPos, visibility ) );
// vpos is a float4 in d3d11
meta->addStatement( new GenOp( " fizzle( @.xy, @ );\r\n", vPos, visibility ) );
}
ShaderFeature::Resources VisibilityFeatHLSL::getResources( const MaterialFeatureData &fd )

View file

@ -33,6 +33,8 @@ struct RenderPassData;
class ShaderFeatureHLSL : public ShaderFeature
{
protected:
bool mIsDirect3D11;
public:
ShaderFeatureHLSL();
@ -188,6 +190,9 @@ class VertPositionHLSL : public ShaderFeatureHLSL
public:
virtual void processVert( Vector<ShaderComponent*> &componentList,
const MaterialFeatureData &fd );
virtual void processPix( Vector<ShaderComponent*> &componentList,
const MaterialFeatureData &fd);
virtual String getName()
{

View file

@ -63,21 +63,33 @@ void ShaderGenPrinterHLSL::printPixelShaderOutputStruct(Stream& stream, const Ma
for( U32 i = 0; i < FEATUREMGR->getFeatureCount(); i++ )
{
const FeatureInfo &info = FEATUREMGR->getAt( i );
if( featureData.features.hasFeature( *info.type ) )
if ( featureData.features.hasFeature( *info.type ) )
numMRTs |= info.feature->getOutputTargets( featureData );
}
WRITESTR( "struct Fragout\r\n" );
WRITESTR( "{\r\n" );
WRITESTR( " float4 col : COLOR0;\r\n" );
for( U32 i = 1; i < 4; i++ )
WRITESTR("struct Fragout\r\n");
WRITESTR("{\r\n");
if (GFX->getAdapterType() == Direct3D11)
{
if( numMRTs & 1 << i )
WRITESTR( avar( " float4 col%d : COLOR%d;\r\n", i, i ) );
WRITESTR(" float4 col : SV_Target0;\r\n");
for (U32 i = 1; i < 4; i++)
{
if (numMRTs & 1 << i)
WRITESTR(avar(" float4 col%d : SV_Target%d;\r\n", i, i));
}
}
WRITESTR( "};\r\n" );
WRITESTR( "\r\n" );
WRITESTR( "\r\n" );
else
{
WRITESTR(" float4 col : COLOR0;\r\n");
for (U32 i = 1; i < 4; i++)
{
if (numMRTs & 1 << i)
WRITESTR(avar(" float4 col%d : COLOR%d;\r\n", i, i));
}
}
WRITESTR("};\r\n");
WRITESTR("\r\n");
WRITESTR("\r\n");
}
void ShaderGenPrinterHLSL::printPixelShaderCloser(Stream& stream)
@ -141,8 +153,8 @@ ShaderComponent* ShaderGenComponentFactoryHLSL::createVertexInputConnector( cons
}
else if ( element.isSemantic( GFXSemantic::TANGENTW ) )
{
var = vertComp->getIndexedElement( element.getSemanticIndex(), RT_TEXCOORD );
var->setName( "tangentW" );
var = vertComp->getIndexedElement(element.getSemanticIndex(), RT_TEXCOORD);
var->setName("tangentW");
}
else if ( element.isSemantic( GFXSemantic::BINORMAL ) )
{

View file

@ -119,6 +119,7 @@ MODULE_BEGIN( ShaderGenHLSL )
sInitDelegate.bind(_initShaderGenHLSL);
SHADERGEN->registerInitDelegate(Direct3D9, sInitDelegate);
SHADERGEN->registerInitDelegate(Direct3D9_360, sInitDelegate);
SHADERGEN->registerInitDelegate(Direct3D11, sInitDelegate);
}
MODULE_END;

View file

@ -99,6 +99,8 @@ Var::Var()
sampler = false;
mapsToSampler = false;
arraySize = 1;
texture = false;
rank = 0;
}
Var::Var( const char *inName, const char *inType )
@ -113,6 +115,8 @@ Var::Var( const char *inName, const char *inType )
texCoordNum = 0;
constSortPos = cspUninit;
arraySize = 1;
texture = false;
rank = 0;
setName( inName );
setType( inType );

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