diff --git a/.gitignore b/.gitignore index d3f9aff55..0ddf3aba2 100644 --- a/.gitignore +++ b/.gitignore @@ -40,6 +40,11 @@ local.properties *.suo *.user *.sln.docstates +*.sln +*.vcxproj +*.vcxproj.filters +*.vcproj + # Build results [Dd]ebug/ @@ -62,6 +67,11 @@ local.properties *.vspscc .builds *.dotCover +*.dll +*.lib +*.exp +*.exe + ## TODO: If you have NuGet Package Restore enabled, uncomment this #packages/ diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 000000000..77057ec73 --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,11 @@ +cmake_minimum_required (VERSION 2.8.3) + +set(TORQUE_APP_NAME "" CACHE STRING "the app name") + +if("${TORQUE_APP_NAME}" STREQUAL "") + message(FATAL_ERROR "Please set TORQUE_APP_NAME first") +endif() + +project(${TORQUE_APP_NAME}) + +add_subdirectory(Tools/CMake) \ No newline at end of file diff --git a/Engine/lib/collada/include/dae/daeTypes.h b/Engine/lib/collada/include/dae/daeTypes.h index 27e560cdd..41e116a4a 100644 --- a/Engine/lib/collada/include/dae/daeTypes.h +++ b/Engine/lib/collada/include/dae/daeTypes.h @@ -21,6 +21,7 @@ #include #include #include +#include #include diff --git a/Engine/source/T3D/aiClient.cpp b/Engine/source/T3D/aiClient.cpp index 3decd3462..cbcf78e1e 100644 --- a/Engine/source/T3D/aiClient.cpp +++ b/Engine/source/T3D/aiClient.cpp @@ -63,7 +63,7 @@ AIClient::AIClient() { mMoveTolerance = 0.25f; // Clear the triggers - for( int i = 0; i < MaxTriggerKeys; i++ ) + for( S32 i = 0; i < MaxTriggerKeys; i++ ) mTriggers[i] = false; mAimToDestination = true; @@ -369,7 +369,7 @@ U32 AIClient::getMoveList( Move **movePtr,U32 *numMoves ) { } // Copy over the trigger status - for( int i = 0; i < MaxTriggerKeys; i++ ) { + for( S32 i = 0; i < MaxTriggerKeys; i++ ) { mMove.trigger[i] = mTriggers[i]; mTriggers[i] = false; } diff --git a/Engine/source/T3D/aiPlayer.cpp b/Engine/source/T3D/aiPlayer.cpp index 725aaed29..6d54358be 100644 --- a/Engine/source/T3D/aiPlayer.cpp +++ b/Engine/source/T3D/aiPlayer.cpp @@ -443,7 +443,7 @@ bool AIPlayer::getAIMove(Move *movePtr) // Replicate the trigger state into the move so that // triggers can be controlled from scripts. - for( int i = 0; i < MaxTriggerKeys; i++ ) + for( S32 i = 0; i < MaxTriggerKeys; i++ ) movePtr->trigger[i] = getImageTriggerState(i); mLastLocation = location; diff --git a/Engine/source/T3D/camera.cpp b/Engine/source/T3D/camera.cpp index f7e5322d7..ef4541f6c 100644 --- a/Engine/source/T3D/camera.cpp +++ b/Engine/source/T3D/camera.cpp @@ -1546,7 +1546,7 @@ void Camera::_validateEyePoint(F32 pos, MatrixF *mat) float dot = mDot(dir, collision.normal); if (dot > 0.01f) { - float colDist = mDot(startPos - collision.point, dir) - (1 / dot) * CameraRadius; + F32 colDist = mDot(startPos - collision.point, dir) - (1 / dot) * CameraRadius; if (colDist > pos) colDist = pos; if (colDist < 0.0f) diff --git a/Engine/source/T3D/cameraSpline.cpp b/Engine/source/T3D/cameraSpline.cpp index 94d0055f5..03eff64ef 100644 --- a/Engine/source/T3D/cameraSpline.cpp +++ b/Engine/source/T3D/cameraSpline.cpp @@ -194,7 +194,7 @@ void CameraSpline::renderTimeMap() if(!ptr) return; MRandomLCG random(1376312589 * (U32)this); - int index = 0; + S32 index = 0; for(Vector::iterator itr=mTimeMap.begin(); itr != mTimeMap.end(); itr++) { Knot a; diff --git a/Engine/source/T3D/debris.cpp b/Engine/source/T3D/debris.cpp index 78526b7ad..ab65304d0 100644 --- a/Engine/source/T3D/debris.cpp +++ b/Engine/source/T3D/debris.cpp @@ -41,7 +41,7 @@ #include "lighting/lightQuery.h" -const U32 csmStaticCollisionMask = TerrainObjectType; +const U32 csmStaticCollisionMask = TerrainObjectType | StaticShapeObjectType | StaticObjectType; const U32 csmDynamicCollisionMask = StaticShapeObjectType; @@ -122,7 +122,7 @@ bool DebrisData::onAdd() if(!Parent::onAdd()) return false; - for( int i=0; iwriteString( textureName ); stream->writeString( shapeName ); - for( int i=0; iwriteFlag( emitterList[i] != NULL ) ) { @@ -346,7 +346,7 @@ void DebrisData::unpackData(BitStream* stream) textureName = stream->readSTString(); shapeName = stream->readSTString(); - for( int i=0; ireadFlag() ) { @@ -512,7 +512,7 @@ bool Debris::onAdd() } // create emitters - for( int i=0; iemitterList[i] != NULL ) { @@ -631,7 +631,7 @@ bool Debris::onAdd() void Debris::onRemove() { - for( int i=0; imDataBlock) - ((char *)(*pd2)->mDataBlock)); } -int QSORT_CALLBACK cmpPointsXY( const void *p1, const void *p2 ) +S32 QSORT_CALLBACK cmpPointsXY( const void *p1, const void *p2 ) { const Point3F *pnt1 = (const Point3F*)p1; const Point3F *pnt2 = (const Point3F*)p2; @@ -142,7 +142,7 @@ int QSORT_CALLBACK cmpPointsXY( const void *p1, const void *p2 ) return 0; } -int QSORT_CALLBACK cmpQuadPointTheta( const void *p1, const void *p2 ) +S32 QSORT_CALLBACK cmpQuadPointTheta( const void *p1, const void *p2 ) { const Point4F *pnt1 = (const Point4F*)p1; const Point4F *pnt2 = (const Point4F*)p2; @@ -157,7 +157,7 @@ int QSORT_CALLBACK cmpQuadPointTheta( const void *p1, const void *p2 ) static Point3F gSortPoint; -int QSORT_CALLBACK cmpDecalDistance( const void *p1, const void *p2 ) +S32 QSORT_CALLBACK cmpDecalDistance( const void *p1, const void *p2 ) { const DecalInstance** pd1 = (const DecalInstance**)p1; const DecalInstance** pd2 = (const DecalInstance**)p2; @@ -168,7 +168,7 @@ int QSORT_CALLBACK cmpDecalDistance( const void *p1, const void *p2 ) return mSign( dist1 - dist2 ); } -int QSORT_CALLBACK cmpDecalRenderOrder( const void *p1, const void *p2 ) +S32 QSORT_CALLBACK cmpDecalRenderOrder( const void *p1, const void *p2 ) { const DecalInstance** pd1 = (const DecalInstance**)p1; const DecalInstance** pd2 = (const DecalInstance**)p2; @@ -179,14 +179,14 @@ int QSORT_CALLBACK cmpDecalRenderOrder( const void *p1, const void *p2 ) return 1; else { - int priority = (*pd1)->getRenderPriority() - (*pd2)->getRenderPriority(); + S32 priority = (*pd1)->getRenderPriority() - (*pd2)->getRenderPriority(); if ( priority != 0 ) return priority; if ( (*pd2)->mFlags & SaveDecal ) { - int id = ( (*pd1)->mDataBlock->getMaterial()->getId() - (*pd2)->mDataBlock->getMaterial()->getId() ); + S32 id = ( (*pd1)->mDataBlock->getMaterial()->getId() - (*pd2)->mDataBlock->getMaterial()->getId() ); if ( id != 0 ) return id; diff --git a/Engine/source/T3D/examples/renderMeshExample.cpp b/Engine/source/T3D/examples/renderMeshExample.cpp index a725fc2eb..880df57d0 100644 --- a/Engine/source/T3D/examples/renderMeshExample.cpp +++ b/Engine/source/T3D/examples/renderMeshExample.cpp @@ -108,6 +108,9 @@ bool RenderMeshExample::onAdd() // Add this object to the scene addToScene(); + // Refresh this object's material (if any) + updateMaterial(); + return true; } diff --git a/Engine/source/T3D/fx/cameraFXMgr.h b/Engine/source/T3D/fx/cameraFXMgr.h index 5a560bfc6..b40411f3a 100644 --- a/Engine/source/T3D/fx/cameraFXMgr.h +++ b/Engine/source/T3D/fx/cameraFXMgr.h @@ -45,6 +45,7 @@ protected: public: CameraFX(); + virtual ~CameraFX() { } MatrixF & getTrans(){ return mCamFXTrans; } virtual bool isExpired(){ return mElapsedTime >= mDuration; } diff --git a/Engine/source/T3D/fx/explosion.cpp b/Engine/source/T3D/fx/explosion.cpp index b84efad3f..40889a817 100644 --- a/Engine/source/T3D/fx/explosion.cpp +++ b/Engine/source/T3D/fx/explosion.cpp @@ -106,18 +106,31 @@ ConsoleDocClass( Explosion, " lightEndBrightness = 0.0;\n" " lightNormalOffset = 2.0;\n" "};\n\n" - "function createExplosion()\n" + "function ServerPlayExplosion(%position, %datablock)\n" "{\n" - " // Create a new explosion - it will explode automatically\n" - " %pos = \"0 0 100\";\n" - " %obj = new Explosion()\n" + " // Play the given explosion on every client.\n" + " // The explosion will be transmitted as an event, not attached to any object.\n" + " for(%idx = 0; %idx < ClientGroup.getCount(); %idx++)\n" " {\n" - " position = %pos;\n" - " dataBlock = GrenadeLauncherExplosion;\n" - " };\n" + " %client = ClientGroup.getObject(%idx);\n" + " commandToClient(%client, 'PlayExplosion', %position, %datablock.getId());\n" + " }\n" + "}\n\n" + "function clientCmdPlayExplosion(%position, %effectDataBlock)\n" + "{\n" + " // Play an explosion sent by the server. Make sure this function is defined\n" + " // on the client.\n" + " if (isObject(%effectDataBlock))\n" + " {\n" + " new Explosion()\n" + " {\n" + " position = %position;\n" + " dataBlock = %effectDataBlock;\n" + " };\n" + " }\n" "}\n\n" "// schedule an explosion\n" - "schedule(1000, 0, createExplosion);\n" + "schedule(1000, 0, ServerPlayExplosion, \"0 0 0\", GrenadeLauncherExplosion);\n" "@endtsexample" ); @@ -736,9 +749,9 @@ bool ExplosionData::preload(bool server, String &errorStr) if( !server ) { - String errorStr; - if( !sfxResolve( &soundProfile, errorStr ) ) - Con::errorf(ConsoleLogEntry::General, "Error, unable to load sound profile for explosion datablock: %s", errorStr.c_str()); + String sfxErrorStr; + if( !sfxResolve( &soundProfile, sfxErrorStr ) ) + Con::errorf(ConsoleLogEntry::General, "Error, unable to load sound profile for explosion datablock: %s", sfxErrorStr.c_str()); if (!particleEmitter && particleEmitterId != 0) if (Sim::findObject(particleEmitterId, particleEmitter) == false) Con::errorf(ConsoleLogEntry::General, "Error, unable to load particle emitter for explosion datablock"); @@ -929,7 +942,7 @@ bool Explosion::onAdd() void Explosion::onRemove() { - for( int i=0; idebrisList[j] ) { @@ -1160,7 +1173,7 @@ void Explosion::launchDebris( Point3F &axis ) U32 numDebris = mDataBlock->debrisNum + sgRandom.randI( -mDataBlock->debrisNumVariance, mDataBlock->debrisNumVariance ); - for( int i=0; idebrisThetaMin, mDataBlock->debrisThetaMax, @@ -1249,7 +1262,7 @@ bool Explosion::explode() Point3F::Zero, U32(mDataBlock->particleDensity * mFade)); } - for( int i=0; iemitterList[i] != NULL ) { diff --git a/Engine/source/T3D/fx/lightning.cpp b/Engine/source/T3D/fx/lightning.cpp index 338bd0a95..5c4c07bde 100644 --- a/Engine/source/T3D/fx/lightning.cpp +++ b/Engine/source/T3D/fx/lightning.cpp @@ -287,14 +287,14 @@ bool LightningData::preload(bool server, String &errorStr) if (server == false) { - String errorStr; + String sfxErrorStr; for (U32 i = 0; i < MaxThunders; i++) { - if( !sfxResolve( &thunderSounds[ i ], errorStr ) ) - Con::errorf(ConsoleLogEntry::General, "LightningData::preload: Invalid packet: %s", errorStr.c_str()); + if( !sfxResolve( &thunderSounds[ i ], sfxErrorStr ) ) + Con::errorf(ConsoleLogEntry::General, "LightningData::preload: Invalid packet: %s", sfxErrorStr.c_str()); } - if( !sfxResolve( &strikeSound, errorStr ) ) - Con::errorf(ConsoleLogEntry::General, "LightningData::preload: Invalid packet: %s", errorStr.c_str()); + if( !sfxResolve( &strikeSound, sfxErrorStr ) ) + Con::errorf(ConsoleLogEntry::General, "LightningData::preload: Invalid packet: %s", sfxErrorStr.c_str()); for (U32 i = 0; i < MaxTextures; i++) { @@ -1139,7 +1139,7 @@ void LightningBolt::generateMinorNodes() { mMinorNodes.clear(); - for( int i=0; iwriteInt(start,32); bstream->writeInt(count,MoveCountBits); Move * prevMove = NULL; - for (int i = 0; i < count; i++) + for (S32 i = 0; i < count; i++) { move[offset + i].sendCount++; move[offset + i].pack(bstream,prevMove); @@ -112,7 +112,7 @@ void StdMoveList::serverReadMovePacket(BitStream *bstream) // Skip forward (must be starting up), or over the moves // we already have. - int skip = mLastMoveAck - start; + S32 skip = mLastMoveAck - start; if (skip < 0) { mLastMoveAck = start; @@ -121,7 +121,7 @@ void StdMoveList::serverReadMovePacket(BitStream *bstream) { if (skip > count) skip = count; - for (int i = 0; i < skip; i++) + for (S32 i = 0; i < skip; i++) { prevMoveHolder.unpack(bstream,prevMove); prevMoveHolder.checksum = bstream->readInt(Move::ChecksumBits); @@ -141,7 +141,7 @@ void StdMoveList::serverReadMovePacket(BitStream *bstream) } // Put the rest on the move list. - int index = mMoveVec.size(); + S32 index = mMoveVec.size(); mMoveVec.increment(count); while (index < mMoveVec.size()) { diff --git a/Engine/source/T3D/item.cpp b/Engine/source/T3D/item.cpp index 50a43c1e8..1cd78fbb8 100644 --- a/Engine/source/T3D/item.cpp +++ b/Engine/source/T3D/item.cpp @@ -893,7 +893,7 @@ void Item::updatePos(const U32 /*mask*/, const F32 dt) // Pick the most resistant surface F32 bd = 0; const Collision* collision = 0; - for (int c = 0; c < collisionList.getCount(); c++) { + for (S32 c = 0; c < collisionList.getCount(); c++) { const Collision &cp = collisionList[c]; F32 dot = -mDot(mVelocity,cp.normal); if (dot > bd) { @@ -1204,7 +1204,7 @@ DefineEngineMethod( Item, isRotating, bool, (),, return object->isRotating(); } -DefineEngineMethod( Item, setCollisionTimeout, bool, (int ignoreColObj),(NULL), +DefineEngineMethod( Item, setCollisionTimeout, bool, (S32 ignoreColObj),(NULL), "@brief Temporarily disable collisions against a specific ShapeBase object.\n\n" "This is useful to prevent a player from immediately picking up an Item they have " diff --git a/Engine/source/T3D/missionArea.cpp b/Engine/source/T3D/missionArea.cpp index d11aa91ce..1e592b7b2 100644 --- a/Engine/source/T3D/missionArea.cpp +++ b/Engine/source/T3D/missionArea.cpp @@ -179,7 +179,7 @@ DefineEngineMethod( MissionArea, getArea, const char *, (),, char* returnBuffer = Con::getReturnBuffer(48); RectI area = object->getArea(); - dSprintf(returnBuffer, sizeof(returnBuffer), "%d %d %d %d", area.point.x, area.point.y, area.extent.x, area.extent.y); + dSprintf(returnBuffer, 48, "%d %d %d %d", area.point.x, area.point.y, area.extent.x, area.extent.y); return(returnBuffer); } diff --git a/Engine/source/T3D/pathCamera.cpp b/Engine/source/T3D/pathCamera.cpp index 185e7a675..43e6f9273 100644 --- a/Engine/source/T3D/pathCamera.cpp +++ b/Engine/source/T3D/pathCamera.cpp @@ -429,7 +429,7 @@ U32 PathCamera::packUpdate(NetConnection *con, U32 mask, BitStream *stream) if (stream->writeFlag(mask & WindowMask)) { stream->write(mNodeBase); stream->write(mNodeCount); - for (int i = 0; i < mNodeCount; i++) { + for (S32 i = 0; i < mNodeCount; i++) { CameraSpline::Knot *knot = mSpline.getKnot(i); mathWrite(*stream, knot->mPosition); mathWrite(*stream, knot->mRotation); @@ -477,7 +477,7 @@ void PathCamera::unpackUpdate(NetConnection *con, BitStream *stream) mSpline.removeAll(); stream->read(&mNodeBase); stream->read(&mNodeCount); - for (int i = 0; i < mNodeCount; i++) + for (S32 i = 0; i < mNodeCount; i++) { CameraSpline::Knot *knot = new CameraSpline::Knot(); mathRead(*stream, &knot->mPosition); diff --git a/Engine/source/T3D/pathCamera.h b/Engine/source/T3D/pathCamera.h index c94e2ad57..685118e6e 100644 --- a/Engine/source/T3D/pathCamera.h +++ b/Engine/source/T3D/pathCamera.h @@ -83,7 +83,7 @@ private: S32 mNodeBase; S32 mNodeCount; F32 mPosition; - int mState; + S32 mState; F32 mTarget; bool mTargetSet; diff --git a/Engine/source/T3D/physics/bullet/bt.h b/Engine/source/T3D/physics/bullet/bt.h index 45ae15414..b2c514ff5 100644 --- a/Engine/source/T3D/physics/bullet/bt.h +++ b/Engine/source/T3D/physics/bullet/bt.h @@ -24,7 +24,7 @@ #define _BULLET_H_ // NOTE: We set these defines which bullet needs here. -#ifdef TORQUE_OS_WIN32 +#ifdef TORQUE_OS_WIN #define WIN32 #endif diff --git a/Engine/source/T3D/physics/physx/px.h b/Engine/source/T3D/physics/physx/px.h index c4dd9dccb..856035cf7 100644 --- a/Engine/source/T3D/physics/physx/px.h +++ b/Engine/source/T3D/physics/physx/px.h @@ -46,7 +46,7 @@ #define __APPLE__ #elif defined(TORQUE_OS_LINUX) && !defined(LINUX) #define LINUX -#elif defined(TORQUE_OS_WIN32) && !defined(WIN32) +#elif defined(TORQUE_OS_WIN) && !defined(WIN32) #define WIN32 #endif diff --git a/Engine/source/T3D/physics/physx/pxMultiActor.cpp b/Engine/source/T3D/physics/physx/pxMultiActor.cpp index 8692afcec..6abdcdaad 100644 --- a/Engine/source/T3D/physics/physx/pxMultiActor.cpp +++ b/Engine/source/T3D/physics/physx/pxMultiActor.cpp @@ -527,7 +527,7 @@ bool PxMultiActorData::preload( bool server, String &errorBuffer ) return false; } - if (!shapeName || shapeName == '\0') + if (!shapeName || shapeName[0] == '\0') { errorBuffer = "PxMultiActorDatas::preload: no shape name!"; return false; diff --git a/Engine/source/T3D/physics/physx/pxPlugin.cpp b/Engine/source/T3D/physics/physx/pxPlugin.cpp index 7fff0559e..bb3352983 100644 --- a/Engine/source/T3D/physics/physx/pxPlugin.cpp +++ b/Engine/source/T3D/physics/physx/pxPlugin.cpp @@ -39,7 +39,7 @@ AFTER_MODULE_INIT( Sim ) { NamedFactory::add( "PhysX", &PxPlugin::create ); - #if defined(TORQUE_OS_WIN32) || defined(TORQUE_OS_XBOX) || defined(TORQUE_OS_XENON) + #if defined(TORQUE_OS_WIN) || defined(TORQUE_OS_XBOX) || defined(TORQUE_OS_XENON) NamedFactory::add( "default", &PxPlugin::create ); #endif diff --git a/Engine/source/T3D/physics/physx3/px3.h b/Engine/source/T3D/physics/physx3/px3.h index e7c8b6555..6db611b51 100644 --- a/Engine/source/T3D/physics/physx3/px3.h +++ b/Engine/source/T3D/physics/physx3/px3.h @@ -29,25 +29,25 @@ #define __APPLE__ #elif defined(TORQUE_OS_LINUX) && !defined(LINUX) #define LINUX -#elif defined(TORQUE_OS_WIN32) && !defined(WIN32) +#elif defined(TORQUE_OS_WIN) && !defined(WIN32) #define WIN32 #endif //------------------------------------------------------------------------- #include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include extern physx::PxPhysics* gPhysics3SDK; -#endif \ No newline at end of file +#endif // _PHYSX3_ diff --git a/Engine/source/T3D/physics/physx3/px3Body.cpp b/Engine/source/T3D/physics/physx3/px3Body.cpp index e4f437225..4adc39a3c 100644 --- a/Engine/source/T3D/physics/physx3/px3Body.cpp +++ b/Engine/source/T3D/physics/physx3/px3Body.cpp @@ -24,7 +24,7 @@ #include "T3D/physics/physx3/px3Body.h" #include "T3D/physics/physx3/px3.h" -#include "T3D/physics/physx3/px3Cast.h" +#include "T3D/physics/physx3/px3Casts.h" #include "T3D/physics/physx3/px3World.h" #include "T3D/physics/physx3/px3Collision.h" @@ -123,24 +123,23 @@ bool Px3Body::init( PhysicsCollision *shape, Con::errorf("PhysX3 Dynamic Triangle Mesh is not supported."); } } - physx::PxShape * pShape = mActor->createShape(*desc->pGeometry,*mMaterial,desc->pose); + physx::PxShape * pShape = mActor->createShape(*desc->pGeometry,*mMaterial); physx::PxFilterData colData; if(isDebris) colData.word0 = PX3_DEBRIS; else if(isTrigger) - { - //We don't want trigger shapes taking part in shape pair intersection tests - pShape->setFlag(physx::PxShapeFlag::eSIMULATION_SHAPE, false); - colData.word0 = PX3_TRIGGER; - } + colData.word0 = PX3_TRIGGER; else colData.word0 = PX3_DEFAULT; + //set local pose - actor->createShape with a local pose is deprecated in physx 3.3 + pShape->setLocalPose(desc->pose); //set the skin width pShape->setContactOffset(0.01f); + pShape->setFlag(physx::PxShapeFlag::eSIMULATION_SHAPE, !isTrigger); pShape->setFlag(physx::PxShapeFlag::eSCENE_QUERY_SHAPE,true); - pShape->setSimulationFilterData(colData); - pShape->setQueryFilterData(colData); + pShape->setSimulationFilterData(colData); + pShape->setQueryFilterData(colData); } //mass & intertia has to be set after creating the shape @@ -148,6 +147,10 @@ bool Px3Body::init( PhysicsCollision *shape, { physx::PxRigidDynamic *actor = mActor->is(); physx::PxRigidBodyExt::setMassAndUpdateInertia(*actor,mass); + if(mBodyFlags & BF_CCD) + actor->setRigidBodyFlag(physx::PxRigidBodyFlag::eENABLE_CCD, true); + else + actor->setRigidBodyFlag(physx::PxRigidBodyFlag::eENABLE_CCD, false); } // This sucks, but it has to happen if we want @@ -366,6 +369,23 @@ void Px3Body::setSimulationEnabled( bool enabled ) delete [] shapes; } +void Px3Body::moveKinematicTo( const MatrixF &transform ) +{ + AssertFatal( mActor, "Px3Body::moveKinematicTo - The actor is null!" ); + + const bool isKinematic = mBodyFlags & BF_KINEMATIC; + if (!isKinematic ) + { + Con::errorf("Px3Body::moveKinematicTo is only for kinematic bodies."); + return; + } + + mWorld->releaseWriteLock(); + + physx::PxRigidDynamic *actor = mActor->is(); + actor->setKinematicTarget(px3Cast(transform)); +} + void Px3Body::setTransform( const MatrixF &transform ) { AssertFatal( mActor, "Px3Body::setTransform - The actor is null!" ); diff --git a/Engine/source/T3D/physics/physx3/px3Body.h b/Engine/source/T3D/physics/physx3/px3Body.h index 379d5b4cd..4fcb223d1 100644 --- a/Engine/source/T3D/physics/physx3/px3Body.h +++ b/Engine/source/T3D/physics/physx3/px3Body.h @@ -20,8 +20,8 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- -#ifndef _T3D_PHYSICS_PX3BODY_H_ -#define _T3D_PHYSICS_PX3BODY_H_ +#ifndef _PX3BODY_H_ +#define _PX3BODY_H_ #ifndef _T3D_PHYSICS_PHYSICSBODY_H_ #include "T3D/physics/physicsBody.h" @@ -88,6 +88,7 @@ public: // PhysicsObject virtual PhysicsWorld* getWorld(); virtual void setTransform( const MatrixF &xfm ); + virtual void moveKinematicTo( const MatrixF &xfm ); virtual MatrixF& getTransform( MatrixF *outMatrix ); virtual Box3F getWorldBounds(); virtual void setSimulationEnabled( bool enabled ); @@ -118,4 +119,4 @@ public: virtual void applyImpulse( const Point3F &origin, const Point3F &force ); }; -#endif +#endif // _PX3BODY_H_ diff --git a/Engine/source/T3D/physics/physx3/px3Casts.h b/Engine/source/T3D/physics/physx3/px3Casts.h new file mode 100644 index 000000000..abc654fd8 --- /dev/null +++ b/Engine/source/T3D/physics/physx3/px3Casts.h @@ -0,0 +1,137 @@ +//----------------------------------------------------------------------------- +// Copyright (c) 2012 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 _PX3CASTS_H_ +#define _PX3CASTS_H_ + +#ifndef _MPOINT3_H_ +#include "math/mPoint3.h" +#endif +#ifndef _MMATRIX_H_ +#include "math/mMatrix.h" +#endif +#ifndef _MBOX_H_ +#include "math/mBox.h" +#endif +#ifndef _MQUAT_H_ +#include "math/mQuat.h" +#endif +#ifndef _MTRANSFORM_H_ +#include "math/mTransform.h" +#endif + + +template inline T px3Cast( const F &from ); + +//------------------------------------------------------------------------- + +template<> +inline Point3F px3Cast( const physx::PxVec3 &vec ) +{ + return Point3F( vec.x, vec.y, vec.z ); +} + +template<> +inline physx::PxVec3 px3Cast( const Point3F &point ) +{ + return physx::PxVec3( point.x, point.y, point.z ); +} +//------------------------------------------------------------------------- +template<> +inline QuatF px3Cast( const physx::PxQuat &quat ) +{ + /// The Torque quat has the opposite winding order. + return QuatF( -quat.x, -quat.y, -quat.z, quat.w ); +} + +template<> +inline physx::PxQuat px3Cast( const QuatF &quat ) +{ + /// The Torque quat has the opposite winding order. + physx::PxQuat result( -quat.x, -quat.y, -quat.z, quat.w ); + return result; +} +//------------------------------------------------------------------------- + +template<> +inline physx::PxExtendedVec3 px3Cast( const Point3F &point ) +{ + return physx::PxExtendedVec3( point.x, point.y, point.z ); +} + +template<> +inline Point3F px3Cast( const physx::PxExtendedVec3 &xvec ) +{ + return Point3F( xvec.x, xvec.y, xvec.z ); +} + +//------------------------------------------------------------------------- + +template<> +inline physx::PxBounds3 px3Cast( const Box3F &box ) +{ + physx::PxBounds3 bounds(px3Cast(box.minExtents), + px3Cast(box.maxExtents)); + return bounds; +} + +template<> +inline Box3F px3Cast( const physx::PxBounds3 &bounds ) +{ + return Box3F( bounds.minimum.x, + bounds.minimum.y, + bounds.minimum.z, + bounds.maximum.x, + bounds.maximum.y, + bounds.maximum.z ); +} + +//------------------------------------------------------------------------- + +template<> +inline physx::PxTransform px3Cast( const MatrixF &xfm ) +{ + physx::PxTransform out; + QuatF q; + q.set(xfm); + out.q = px3Cast(q); + out.p = px3Cast(xfm.getPosition()); + return out; +} + +template<> +inline TransformF px3Cast(const physx::PxTransform &xfm) +{ + TransformF out(px3Cast(xfm.p),AngAxisF(px3Cast(xfm.q))); + return out; +} + +template<> +inline MatrixF px3Cast( const physx::PxTransform &xfm ) +{ + MatrixF out; + TransformF t = px3Cast(xfm); + out = t.getMatrix(); + return out; +} + +#endif //_PX3CASTS_H_ diff --git a/Engine/source/T3D/physics/physx3/px3Collision.cpp b/Engine/source/T3D/physics/physx3/px3Collision.cpp index fb11a4400..e24b097e3 100644 --- a/Engine/source/T3D/physics/physx3/px3Collision.cpp +++ b/Engine/source/T3D/physics/physx3/px3Collision.cpp @@ -26,7 +26,7 @@ #include "math/mPoint3.h" #include "math/mMatrix.h" #include "T3D/physics/physx3/px3.h" -#include "T3D/physics/physx3/px3Cast.h" +#include "T3D/physics/physx3/px3Casts.h" #include "T3D/physics/physx3/px3World.h" #include "T3D/physics/physx3/px3Stream.h" @@ -105,7 +105,10 @@ bool Px3Collision::addConvex( const Point3F *points, convexMesh = gPhysics3SDK->createConvexMesh(in); Px3CollisionDesc *desc = new Px3CollisionDesc; - desc->pGeometry = new physx::PxConvexMeshGeometry(convexMesh); + physx::PxVec3 scale = px3Cast(localXfm.getScale()); + physx::PxQuat rotation = px3Cast(QuatF(localXfm)); + physx::PxMeshScale meshScale(scale,rotation); + desc->pGeometry = new physx::PxConvexMeshGeometry(convexMesh,meshScale); desc->pose = px3Cast(localXfm); mColShapes.push_back(desc); return true; @@ -177,13 +180,13 @@ bool Px3Collision::addHeightfield( const U16 *heights, if ( holes && holes[ getMax( (S32)index - 1, 0 ) ] ) // row index for holes adjusted so PhysX collision shape better matches rendered terrain { - currentSample->materialIndex0 = 0; - currentSample->materialIndex1 = 0; + currentSample->materialIndex0 = physx::PxHeightFieldMaterial::eHOLE; + currentSample->materialIndex1 = physx::PxHeightFieldMaterial::eHOLE; } else { - currentSample->materialIndex0 = 1; - currentSample->materialIndex1 = 1; + currentSample->materialIndex0 = 0; + currentSample->materialIndex1 = 0; } int flag = ( column + tess ) % 2; diff --git a/Engine/source/T3D/physics/physx3/px3Collision.h b/Engine/source/T3D/physics/physx3/px3Collision.h index 857f4f5e3..69bf38778 100644 --- a/Engine/source/T3D/physics/physx3/px3Collision.h +++ b/Engine/source/T3D/physics/physx3/px3Collision.h @@ -20,8 +20,8 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- -#ifndef _T3D_PHYSICS_PX3COLLISION_H_ -#define _T3D_PHYSICS_PX3COLLISION_H_ +#ifndef _PX3COLLISION_H_ +#define _PX3COLLISION_H_ #ifndef _T3D_PHYSICS_PHYSICSCOLLISION_H_ #include "T3D/physics/physicsCollision.h" @@ -32,7 +32,7 @@ #ifndef _MMATRIX_H_ #include "math/mMatrix.h" #endif -//nasty hate doing this! + #include //forward declare @@ -84,4 +84,4 @@ public: const MatrixF &localXfm ); }; -#endif \ No newline at end of file +#endif // _PX3COLLISION_H_ diff --git a/Engine/source/T3D/physics/physx3/px3Player.cpp b/Engine/source/T3D/physics/physx3/px3Player.cpp index 1c44068e9..e831c939c 100644 --- a/Engine/source/T3D/physics/physx3/px3Player.cpp +++ b/Engine/source/T3D/physics/physx3/px3Player.cpp @@ -24,7 +24,7 @@ #include "T3D/physics/physx3/px3Player.h" #include "T3D/physics/physicsPlugin.h" #include "T3D/physics/physx3/px3World.h" -#include "T3D/physics/physx3/px3Cast.h" +#include "T3D/physics/physx3/px3Casts.h" #include "T3D/physics/physx3/px3Utils.h" #include "collision/collision.h" @@ -322,7 +322,10 @@ void Px3Player::setScale( const Point3F &scale ) Box3F Px3Player::getWorldBounds() { - Con::warnf( "Px3Player::getWorldBounds - not implemented" ); - return Box3F::Invalid; + physx::PxBounds3 bounds; + physx::PxRigidDynamic *actor = mController->getActor(); + physx::PxShape *shape = px3GetFirstShape(actor); + bounds = physx::PxShapeExt::getWorldBounds(*shape,*actor); + return px3Cast( bounds ); } diff --git a/Engine/source/T3D/physics/physx3/px3Player.h b/Engine/source/T3D/physics/physx3/px3Player.h index c8dee08e6..55a1409cd 100644 --- a/Engine/source/T3D/physics/physx3/px3Player.h +++ b/Engine/source/T3D/physics/physx3/px3Player.h @@ -101,4 +101,4 @@ public: }; -#endif // _PXPLAYER_H \ No newline at end of file +#endif // _PX3PLAYER_H_ diff --git a/Engine/source/T3D/physics/physx3/px3Plugin.cpp b/Engine/source/T3D/physics/physx3/px3Plugin.cpp index 9da0ca026..76f811288 100644 --- a/Engine/source/T3D/physics/physx3/px3Plugin.cpp +++ b/Engine/source/T3D/physics/physx3/px3Plugin.cpp @@ -37,7 +37,7 @@ AFTER_MODULE_INIT( Sim ) { NamedFactory::add( "PhysX3", &Px3Plugin::create ); - #if defined(TORQUE_OS_WIN32) || defined(TORQUE_OS_XBOX) || defined(TORQUE_OS_XENON) + #if defined(TORQUE_OS_WIN) || defined(TORQUE_OS_XBOX) || defined(TORQUE_OS_XENON) NamedFactory::add( "default", &Px3Plugin::create ); #endif } @@ -224,4 +224,3 @@ U32 Px3Plugin::getWorldCount() const { return mPhysicsWorldLookup.size(); } - diff --git a/Engine/source/T3D/physics/physx3/px3Plugin.h b/Engine/source/T3D/physics/physx3/px3Plugin.h index 7972fe59a..3a001ca8d 100644 --- a/Engine/source/T3D/physics/physx3/px3Plugin.h +++ b/Engine/source/T3D/physics/physx3/px3Plugin.h @@ -20,13 +20,15 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- -#ifndef _T3D_PHYSICS_PX3PLUGIN_H_ -#define _T3D_PHYSICS_PX3PLUGIN_H_ +#ifndef _PX3PLUGIN_H_ +#define _PX3PLUGIN_H_ #ifndef _T3D_PHYSICS_PHYSICSPLUGIN_H_ #include "T3D/physics/physicsPlugin.h" #endif +class Px3ClothShape; + class Px3Plugin : public PhysicsPlugin { public: @@ -52,7 +54,6 @@ public: virtual PhysicsWorld* getWorld( const String &worldName ) const; virtual PhysicsWorld* getWorld() const; virtual U32 getWorldCount() const; - }; -#endif \ No newline at end of file +#endif // _PX3PLUGIN_H_ diff --git a/Engine/source/T3D/physics/physx3/px3Stream.h b/Engine/source/T3D/physics/physx3/px3Stream.h index 155165881..b7538b5e2 100644 --- a/Engine/source/T3D/physics/physx3/px3Stream.h +++ b/Engine/source/T3D/physics/physx3/px3Stream.h @@ -20,8 +20,8 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- -#ifndef _T3D_PHYSICS_PX3STREAM_H_ -#define _T3D_PHYSICS_PX3STREAM_H_ +#ifndef _PX3STREAM_H_ +#define _PX3STREAM_H_ #ifndef _PHYSX3_H_ #include "T3D/physics/physx3/px3.h" @@ -74,4 +74,4 @@ public: virtual ~Px3ConsoleStream(); }; -#endif \ No newline at end of file +#endif // _PX3STREAM_H_ diff --git a/Engine/source/T3D/physics/physx3/px3Utils.h b/Engine/source/T3D/physics/physx3/px3Utils.h index d80b5acce..5b69b1c50 100644 --- a/Engine/source/T3D/physics/physx3/px3Utils.h +++ b/Engine/source/T3D/physics/physx3/px3Utils.h @@ -20,8 +20,8 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- -#ifndef _PHYSX3_UTILS_H_ -#define _PHYSX3_UTILS_H_ +#ifndef _PX3UTILS_H_ +#define _PX3UTILS_H_ namespace physx { @@ -31,5 +31,4 @@ namespace physx extern physx::PxShape* px3GetFirstShape(physx::PxRigidActor *actor); - -#endif \ No newline at end of file +#endif // _PX3UTILS_H_ diff --git a/Engine/source/T3D/physics/physx3/px3World.cpp b/Engine/source/T3D/physics/physx3/px3World.cpp index 67fd78cf0..a7617a723 100644 --- a/Engine/source/T3D/physics/physx3/px3World.cpp +++ b/Engine/source/T3D/physics/physx3/px3World.cpp @@ -25,7 +25,7 @@ #include "T3D/physics/physx3/px3.h" #include "T3D/physics/physx3/px3Plugin.h" -#include "T3D/physics/physx3/px3Cast.h" +#include "T3D/physics/physx3/px3Casts.h" #include "T3D/physics/physx3/px3Stream.h" #include "T3D/physics/physicsUserData.h" @@ -54,6 +54,23 @@ physx::PxDefaultAllocator Px3World::smMemoryAlloc; F32 Px3World::smPhysicsStepTime = 1.0f/(F32)TickMs; U32 Px3World::smPhysicsMaxIterations = 4; +//filter shader with support for CCD pairs +static physx::PxFilterFlags sCcdFilterShader( + physx::PxFilterObjectAttributes attributes0, + physx::PxFilterData filterData0, + physx::PxFilterObjectAttributes attributes1, + physx::PxFilterData filterData1, + physx::PxPairFlags& pairFlags, + const void* constantBlock, + physx::PxU32 constantBlockSize) +{ + pairFlags = physx::PxPairFlag::eRESOLVE_CONTACTS; + pairFlags |= physx::PxPairFlag::eCCD_LINEAR; + return physx::PxFilterFlags(); +} + + + Px3World::Px3World(): mScene( NULL ), mProcessList( NULL ), mIsSimulating( false ), @@ -198,7 +215,6 @@ void Px3World::destroyWorld() mScene->release(); mScene = NULL; } - } bool Px3World::initWorld( bool isServer, ProcessList *processList ) @@ -221,10 +237,12 @@ bool Px3World::initWorld( bool isServer, ProcessList *processList ) sceneDesc.cpuDispatcher = smCpuDispatcher; Con::printf("PhysX3 using Cpu: %d workers", smCpuDispatcher->getWorkerCount()); } - + + + sceneDesc.flags |= physx::PxSceneFlag::eENABLE_CCD; sceneDesc.flags |= physx::PxSceneFlag::eENABLE_ACTIVETRANSFORMS; - sceneDesc.filterShader = physx::PxDefaultSimulationFilterShader; + sceneDesc.filterShader = sCcdFilterShader; mScene = gPhysics3SDK->createScene(sceneDesc); @@ -559,7 +577,6 @@ void Px3World::onDebugDraw( const SceneRenderState *state ) } } - //set simulation timing via script DefineEngineFunction( physx3SetSimulationTiming, void, ( F32 stepTime, U32 maxSteps ),, "Set simulation timing of the PhysX 3 plugin" ) { diff --git a/Engine/source/T3D/physics/physx3/px3World.h b/Engine/source/T3D/physics/physx3/px3World.h index faf51a41a..a1235d160 100644 --- a/Engine/source/T3D/physics/physx3/px3World.h +++ b/Engine/source/T3D/physics/physx3/px3World.h @@ -20,8 +20,8 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- -#ifndef _PHYSX3_WORLD_H_ -#define _PHYSX3_WORLD_H_ +#ifndef _PX3WORLD_H_ +#define _PX3WORLD_H_ #ifndef _T3D_PHYSICS_PHYSICSWORLD_H_ #include "T3D/physics/physicsWorld.h" @@ -53,7 +53,6 @@ class Px3World : public PhysicsWorld protected: physx::PxScene* mScene; - bool mIsEnabled; bool mIsSimulating; bool mIsServer; @@ -71,7 +70,6 @@ protected: static physx::PxVisualDebuggerConnection* smPvdConnection; static F32 smPhysicsStepTime; static U32 smPhysicsMaxIterations; - F32 mAccumulator; bool _simulate(const F32 dt); @@ -105,6 +103,4 @@ public: static void setTiming(F32 stepTime,U32 maxIterations); }; - - -#endif \ No newline at end of file +#endif // _PX3WORLD_H_ diff --git a/Engine/source/T3D/player.cpp b/Engine/source/T3D/player.cpp index da29b63e0..e81238fb3 100644 --- a/Engine/source/T3D/player.cpp +++ b/Engine/source/T3D/player.cpp @@ -427,9 +427,9 @@ bool PlayerData::preload(bool server, String &errorStr) { for( U32 i = 0; i < MaxSounds; ++ i ) { - String errorStr; - if( !sfxResolve( &sound[ i ], errorStr ) ) - Con::errorf( "PlayerData::preload: %s", errorStr.c_str() ); + String sfxErrorStr; + if( !sfxResolve( &sound[ i ], sfxErrorStr ) ) + Con::errorf( "PlayerData::preload: %s", sfxErrorStr.c_str() ); } } @@ -467,7 +467,7 @@ bool PlayerData::preload(bool server, String &errorStr) // Extract ground transform velocity from animations // Get the named ones first so they can be indexed directly. ActionAnimation *dp = &actionList[0]; - for (int i = 0; i < NumTableActionAnims; i++,dp++) + for (S32 i = 0; i < NumTableActionAnims; i++,dp++) { ActionAnimationDef *sp = &ActionAnimationList[i]; dp->name = sp->name; @@ -492,7 +492,7 @@ bool PlayerData::preload(bool server, String &errorStr) if (dStricmp(sp->name, "jet") != 0) AssertWarn(dp->sequence != -1, avar("PlayerData::preload - Unable to find named animation sequence '%s'!", sp->name)); } - for (int b = 0; b < mShape->sequences.size(); b++) + for (S32 b = 0; b < mShape->sequences.size(); b++) { if (!isTableSequence(b)) { @@ -509,7 +509,7 @@ bool PlayerData::preload(bool server, String &errorStr) // Resolve lookAction index dp = &actionList[0]; String lookName("look"); - for (int c = 0; c < actionCount; c++,dp++) + for (S32 c = 0; c < actionCount; c++,dp++) if( dStricmp( dp->name, lookName ) == 0 ) lookAction = c; @@ -557,7 +557,7 @@ bool PlayerData::preload(bool server, String &errorStr) if (!Sim::findObject(dustID, dustEmitter)) Con::errorf(ConsoleLogEntry::General, "PlayerData::preload - Invalid packet, bad datablockId(dustEmitter): 0x%x", dustID); - for (int i=0; igetChecksum(); @@ -647,7 +650,7 @@ bool PlayerData::isTableSequence(S32 seq) { // The sequences from the table must already have // been loaded for this to work. - for (int i = 0; i < NumTableActionAnims; i++) + for (S32 i = 0; i < NumTableActionAnims; i++) if (actionList[i].sequence == seq) return true; return false; @@ -1944,7 +1947,7 @@ void Player::reSkin() Vector skins; String(mSkinNameHandle.getString()).split( ";", skins ); - for ( int i = 0; i < skins.size(); i++ ) + for ( S32 i = 0; i < skins.size(); i++ ) { String oldSkin( mAppliedSkinName.c_str() ); String newSkin( skins[i] ); @@ -1961,7 +1964,7 @@ void Player::reSkin() // Apply skin to both 3rd person and 1st person shape instances mShapeInstance->reSkin( newSkin, oldSkin ); - for ( int j = 0; j < ShapeBase::MaxMountedImages; j++ ) + for ( S32 j = 0; j < ShapeBase::MaxMountedImages; j++ ) { if (mShapeFPInstance[j]) mShapeFPInstance[j]->reSkin( newSkin, oldSkin ); @@ -5822,7 +5825,7 @@ bool Player::castRay(const Point3F &start, const Point3F &end, RayInfo* info) F32 const *si = &start.x; F32 const *ei = &end.x; - for (int i = 0; i < 3; i++) { + for (S32 i = 0; i < 3; i++) { if (*si < *ei) { if (*si > *bmax || *ei < *bmin) return false; diff --git a/Engine/source/T3D/projectile.cpp b/Engine/source/T3D/projectile.cpp index 86886c2b5..24d78f80a 100644 --- a/Engine/source/T3D/projectile.cpp +++ b/Engine/source/T3D/projectile.cpp @@ -320,9 +320,9 @@ bool ProjectileData::preload(bool server, String &errorStr) if (Sim::findObject(decalId, decal) == false) Con::errorf(ConsoleLogEntry::General, "ProjectileData::preload: Invalid packet, bad datablockId(decal): %d", decalId); - String errorStr; - if( !sfxResolve( &sound, errorStr ) ) - Con::errorf(ConsoleLogEntry::General, "ProjectileData::preload: Invalid packet: %s", errorStr.c_str()); + String sfxErrorStr; + if( !sfxResolve( &sound, sfxErrorStr ) ) + Con::errorf(ConsoleLogEntry::General, "ProjectileData::preload: Invalid packet: %s", sfxErrorStr.c_str()); if (!lightDesc && lightDescId != 0) if (Sim::findObject(lightDescId, lightDesc) == false) @@ -1011,7 +1011,7 @@ void Projectile::explode( const Point3F &p, const Point3F &n, const U32 collideT // Client (impact) decal. if ( mDataBlock->decal ) - gDecalManager->addDecal( p, n, 0.0f, mDataBlock->decal ); + gDecalManager->addDecal(p, n, mRandF(0.0f, M_2PI_F), mDataBlock->decal); // Client object updateSound(); diff --git a/Engine/source/T3D/projectile.h b/Engine/source/T3D/projectile.h index fa7c9ffbf..17c90cfbc 100644 --- a/Engine/source/T3D/projectile.h +++ b/Engine/source/T3D/projectile.h @@ -215,9 +215,9 @@ public: void updateSound(); - virtual bool calculateImpact( float simTime, + virtual bool calculateImpact( F32 simTime, Point3F &pointOfImpact, - float &impactTime ); + F32 &impactTime ); void setInitialPosition( const Point3F& pos ); void setInitialVelocity( const Point3F& vel ); diff --git a/Engine/source/T3D/proximityMine.cpp b/Engine/source/T3D/proximityMine.cpp index c37947a16..89ffe9577 100644 --- a/Engine/source/T3D/proximityMine.cpp +++ b/Engine/source/T3D/proximityMine.cpp @@ -136,11 +136,11 @@ bool ProximityMineData::preload( bool server, String& errorStr ) if ( !server ) { // Resolve sounds - String errorStr; - if( !sfxResolve( &armingSound, errorStr ) ) - Con::errorf( ConsoleLogEntry::General, "ProximityMineData::preload: Invalid packet: %s", errorStr.c_str() ); - if( !sfxResolve( &triggerSound, errorStr ) ) - Con::errorf( ConsoleLogEntry::General, "ProximityMineData::preload: Invalid packet: %s", errorStr.c_str() ); + String sfxErrorStr; + if( !sfxResolve( &armingSound, sfxErrorStr ) ) + Con::errorf( ConsoleLogEntry::General, "ProximityMineData::preload: Invalid packet: %s", sfxErrorStr.c_str() ); + if( !sfxResolve( &triggerSound, sfxErrorStr ) ) + Con::errorf( ConsoleLogEntry::General, "ProximityMineData::preload: Invalid packet: %s", sfxErrorStr.c_str() ); } if ( mShape ) @@ -451,7 +451,7 @@ void ProximityMine::processTick( const Move* move ) SimpleQueryList sql; getContainer()->findObjects( triggerBox, sTriggerCollisionMask, SimpleQueryList::insertionCallback, &sql ); - for ( int i = 0; i < sql.mList.size(); i++ ) + for ( S32 i = 0; i < sql.mList.size(); i++ ) { // Detect movement in the trigger area if ( ( sql.mList[i] == mOwner && !mDataBlock->triggerOnOwner ) || diff --git a/Engine/source/T3D/rigid.cpp b/Engine/source/T3D/rigid.cpp index 079f97caf..e2441441f 100644 --- a/Engine/source/T3D/rigid.cpp +++ b/Engine/source/T3D/rigid.cpp @@ -265,8 +265,8 @@ void Rigid::translateCenterOfMass(const Point3F &oldPos,const Point3F &newPos) MatrixF oldx,newx; oldx.setCrossProduct(oldPos); newx.setCrossProduct(newPos); - for (int row = 0; row < 3; row++) - for (int col = 0; col < 3; col++) { + for (S32 row = 0; row < 3; row++) + for (S32 col = 0; col < 3; col++) { F32 n = newx(row,col), o = oldx(row,col); objectInertia(row,col) += mass * ((o * o) - (n * n)); } diff --git a/Engine/source/T3D/rigidShape.cpp b/Engine/source/T3D/rigidShape.cpp index 5d21d97c8..cb736ce8c 100644 --- a/Engine/source/T3D/rigidShape.cpp +++ b/Engine/source/T3D/rigidShape.cpp @@ -196,7 +196,7 @@ namespace { // Physics and collision constants static F32 sRestTol = 0.5; // % of gravity energy to be at rest - static int sRestCount = 10; // Consecutive ticks before comming to rest + static S32 sRestCount = 10; // Consecutive ticks before comming to rest const U32 sCollisionMoveMask = ( TerrainObjectType | PlayerObjectType | StaticShapeObjectType | VehicleObjectType | @@ -302,6 +302,7 @@ bool RigidShapeData::preload(bool server, String &errorStr) if (!collisionDetails.size() || collisionDetails[0] == -1) { Con::errorf("RigidShapeData::preload failed: Rigid shapes must define a collision-1 detail"); + errorStr = String::ToString("RigidShapeData: Couldn't load shape \"%s\"",shapeName); return false; } @@ -1652,7 +1653,7 @@ void RigidShape::_renderMassAndContacts( ObjectRenderInst *ri, SceneRenderState GFX->getDrawUtil()->drawCube( desc, Point3F(0.1f,0.1f,0.1f), mDataBlock->massCenter, ColorI(255, 255, 255), &mRenderObjToWorld ); // Collision points... - for (int i = 0; i < mCollisionList.getCount(); i++) + for (S32 i = 0; i < mCollisionList.getCount(); i++) { const Collision& collision = mCollisionList[i]; GFX->getDrawUtil()->drawCube( desc, Point3F(0.05f,0.05f,0.05f), collision.point, ColorI(0, 0, 255) ); @@ -1660,7 +1661,7 @@ void RigidShape::_renderMassAndContacts( ObjectRenderInst *ri, SceneRenderState // Render the normals as one big batch... PrimBuild::begin(GFXLineList, mCollisionList.getCount() * 2); - for (int i = 0; i < mCollisionList.getCount(); i++) + for (S32 i = 0; i < mCollisionList.getCount(); i++) { const Collision& collision = mCollisionList[i]; diff --git a/Engine/source/T3D/rigidShape.h b/Engine/source/T3D/rigidShape.h index 180b0d0ad..ca846dd40 100644 --- a/Engine/source/T3D/rigidShape.h +++ b/Engine/source/T3D/rigidShape.h @@ -195,7 +195,7 @@ class RigidShape: public ShapeBase CollisionList mContacts; Rigid mRigid; ShapeBaseConvex mConvex; - int restCount; + S32 restCount; SimObjectPtr mDustEmitterList[RigidShapeData::VC_NUM_DUST_EMITTERS]; SimObjectPtr mSplashEmitterList[RigidShapeData::VC_NUM_SPLASH_EMITTERS]; diff --git a/Engine/source/T3D/shapeBase.cpp b/Engine/source/T3D/shapeBase.cpp index 0ecde5097..eff6bd855 100644 --- a/Engine/source/T3D/shapeBase.cpp +++ b/Engine/source/T3D/shapeBase.cpp @@ -306,7 +306,10 @@ bool ShapeBaseData::preload(bool server, String &errorStr) Torque::FS::FileNodeRef fileRef = Torque::FS::GetFileNode(mShape.getPath()); if (!fileRef) + { + errorStr = String::ToString("ShapeBaseData: Couldn't load shape \"%s\"",shapeName); return false; + } if(server) mCRC = fileRef->getChecksum(); @@ -898,17 +901,9 @@ ShapeBase::ShapeBase() mCloakLevel( 0.0f ), mDamageFlash( 0.0f ), mWhiteOut( 0.0f ), - mInvincibleEffect( 0.0f ), - mInvincibleDelta( 0.0f ), - mInvincibleCount( 0.0f ), - mInvincibleSpeed( 0.0f ), - mInvincibleTime( 0.0f ), - mInvincibleFade( 0.1f ), - mInvincibleOn( false ), mIsControlled( false ), mConvexList( new Convex ), mCameraFov( 90.0f ), - mShieldNormal( 0.0f, 0.0f, 1.0f ), mFadeOut( true ), mFading( false ), mFadeVal( 1.0f ), @@ -1282,7 +1277,7 @@ void ShapeBase::processTick(const Move* move) { mMoveMotion = true; } - for (int i = 0; i < MaxMountedImages; i++) + for (S32 i = 0; i < MaxMountedImages; i++) { setImageMotionState(i, mMoveMotion); } @@ -1305,7 +1300,7 @@ void ShapeBase::processTick(const Move* move) // Advance images if (isServerObject()) { - for (int i = 0; i < MaxMountedImages; i++) + for (S32 i = 0; i < MaxMountedImages; i++) { if (mMountedImageList[i].dataBlock) updateImageState(i, TickSec); @@ -1347,7 +1342,7 @@ void ShapeBase::advanceTime(F32 dt) // advanced at framerate. advanceThreads(dt); updateAudioPos(); - for (int i = 0; i < MaxMountedImages; i++) + for (S32 i = 0; i < MaxMountedImages; i++) if (mMountedImageList[i].dataBlock) { updateImageState(i, dt); @@ -1382,9 +1377,6 @@ void ShapeBase::advanceTime(F32 dt) mCloakLevel = 0.0; } } - if(mInvincibleOn) - updateInvincibleEffect(dt); - if(mFading) { mFadeElapsedTime += dt; @@ -1987,119 +1979,6 @@ void ShapeBase::getCameraTransform(F32* pos,MatrixF* mat) mat->mul( gCamFXMgr.getTrans() ); } -// void ShapeBase::getCameraTransform(F32* pos,MatrixF* mat) -// { -// // Returns camera to world space transform -// // Handles first person / third person camera position - -// if (isServerObject() && mShapeInstance) -// mShapeInstance->animateNodeSubtrees(true); - -// if (*pos != 0) { -// F32 min,max; -// Point3F offset; -// MatrixF eye,rot; -// getCameraParameters(&min,&max,&offset,&rot); -// getRenderEyeTransform(&eye); -// mat->mul(eye,rot); - -// // Use the eye transform to orient the camera -// VectorF vp,vec; -// vp.x = vp.z = 0; -// vp.y = -(max - min) * *pos; -// eye.mulV(vp,&vec); - -// // Use the camera node's pos. -// Point3F osp,sp; -// if (mDataBlock->cameraNode != -1) { -// mShapeInstance->mNodeTransforms[mDataBlock->cameraNode].getColumn(3,&osp); -// getRenderTransform().mulP(osp,&sp); -// } -// else -// getRenderTransform().getColumn(3,&sp); - -// // Make sure we don't extend the camera into anything solid -// Point3F ep = sp + vec; -// ep += offset; -// disableCollision(); -// if (isMounted()) -// getObjectMount()->disableCollision(); -// RayInfo collision; -// if (mContainer->castRay(sp,ep,(0xFFFFFFFF & ~(WaterObjectType|ForceFieldObjectType|GameBaseObjectType|DefaultObjectType)),&collision)) { -// *pos = collision.t *= 0.9; -// if (*pos == 0) -// eye.getColumn(3,&ep); -// else -// ep = sp + vec * *pos; -// } -// mat->setColumn(3,ep); -// if (isMounted()) -// getObjectMount()->enableCollision(); -// enableCollision(); -// } -// else -// { -// getRenderEyeTransform(mat); -// } -// } - - -// void ShapeBase::getRenderCameraTransform(F32* pos,MatrixF* mat) -// { -// // Returns camera to world space transform -// // Handles first person / third person camera position - -// if (isServerObject() && mShapeInstance) -// mShapeInstance->animateNodeSubtrees(true); - -// if (*pos != 0) { -// F32 min,max; -// Point3F offset; -// MatrixF eye,rot; -// getCameraParameters(&min,&max,&offset,&rot); -// getRenderEyeTransform(&eye); -// mat->mul(eye,rot); - -// // Use the eye transform to orient the camera -// VectorF vp,vec; -// vp.x = vp.z = 0; -// vp.y = -(max - min) * *pos; -// eye.mulV(vp,&vec); - -// // Use the camera node's pos. -// Point3F osp,sp; -// if (mDataBlock->cameraNode != -1) { -// mShapeInstance->mNodeTransforms[mDataBlock->cameraNode].getColumn(3,&osp); -// getRenderTransform().mulP(osp,&sp); -// } -// else -// getRenderTransform().getColumn(3,&sp); - -// // Make sure we don't extend the camera into anything solid -// Point3F ep = sp + vec; -// ep += offset; -// disableCollision(); -// if (isMounted()) -// getObjectMount()->disableCollision(); -// RayInfo collision; -// if (mContainer->castRay(sp,ep,(0xFFFFFFFF & ~(WaterObjectType|ForceFieldObjectType|GameBaseObjectType|DefaultObjectType)),&collision)) { -// *pos = collision.t *= 0.9; -// if (*pos == 0) -// eye.getColumn(3,&ep); -// else -// ep = sp + vec * *pos; -// } -// mat->setColumn(3,ep); -// if (isMounted()) -// getObjectMount()->enableCollision(); -// enableCollision(); -// } -// else -// { -// getRenderEyeTransform(mat); -// } -// } - void ShapeBase::getCameraParameters(F32 *min,F32* max,Point3F* off,MatrixF* rot) { *min = mDataBlock->cameraMinDist; @@ -2153,52 +2032,6 @@ bool ShapeBase::useObjsEyePoint() const return mDataBlock->useEyePoint; } - -//---------------------------------------------------------------------------- -F32 ShapeBase::getInvincibleEffect() const -{ - return mInvincibleEffect; -} - -void ShapeBase::setupInvincibleEffect(F32 time, F32 speed) -{ - if(isClientObject()) - { - mInvincibleCount = mInvincibleTime = time; - mInvincibleSpeed = mInvincibleDelta = speed; - mInvincibleEffect = 0.0f; - mInvincibleOn = true; - mInvincibleFade = 1.0f; - } - else - { - mInvincibleTime = time; - mInvincibleSpeed = speed; - setMaskBits(InvincibleMask); - } -} - -void ShapeBase::updateInvincibleEffect(F32 dt) -{ - if(mInvincibleCount > 0.0f ) - { - if(mInvincibleEffect >= ((0.3 * mInvincibleFade) + 0.05f) && mInvincibleDelta > 0.0f) - mInvincibleDelta = -mInvincibleSpeed; - else if(mInvincibleEffect <= 0.05f && mInvincibleDelta < 0.0f) - { - mInvincibleDelta = mInvincibleSpeed; - mInvincibleFade = mInvincibleCount / mInvincibleTime; - } - mInvincibleEffect += mInvincibleDelta; - mInvincibleCount -= dt; - } - else - { - mInvincibleEffect = 0.0f; - mInvincibleOn = false; - } -} - //---------------------------------------------------------------------------- void ShapeBase::setVelocity(const VectorF&) { @@ -2240,7 +2073,7 @@ void ShapeBase::stopAudio(U32 slot) void ShapeBase::updateServerAudio() { // Timeout non-looping sounds - for (int i = 0; i < MaxSoundThreads; i++) { + for (S32 i = 0; i < MaxSoundThreads; i++) { Sound& st = mSoundThread[i]; if (st.play && st.timeout && st.timeout < Sim::getCurrentTime()) { clearMaskBits(SoundMaskN << i); @@ -2280,7 +2113,7 @@ void ShapeBase::updateAudioState(Sound& st) void ShapeBase::updateAudioPos() { - for (int i = 0; i < MaxSoundThreads; i++) + for (S32 i = 0; i < MaxSoundThreads; i++) { SFXSource* source = mSoundThread[i].sound; if ( source ) @@ -3102,8 +2935,7 @@ U32 ShapeBase::packUpdate(NetConnection *con, U32 mask, BitStream *stream) } if(!stream->writeFlag(mask & (NameMask | DamageMask | SoundMask | MeshHiddenMask | - ThreadMask | ImageMask | CloakMask | InvincibleMask | - ShieldMask | SkinMask))) + ThreadMask | ImageMask | CloakMask | SkinMask))) return retMask; if (stream->writeFlag(mask & DamageMask)) { @@ -3113,7 +2945,7 @@ U32 ShapeBase::packUpdate(NetConnection *con, U32 mask, BitStream *stream) } if (stream->writeFlag(mask & ThreadMask)) { - for (int i = 0; i < MaxScriptThreads; i++) { + for (S32 i = 0; i < MaxScriptThreads; i++) { Thread& st = mScriptThread[i]; if (stream->writeFlag( (st.sequence != -1 || st.state == Thread::Destroy) && (mask & (ThreadMaskN << i)) ) ) { stream->writeInt(st.sequence,ThreadSequenceBits); @@ -3126,7 +2958,7 @@ U32 ShapeBase::packUpdate(NetConnection *con, U32 mask, BitStream *stream) } if (stream->writeFlag(mask & SoundMask)) { - for (int i = 0; i < MaxSoundThreads; i++) { + for (S32 i = 0; i < MaxSoundThreads; i++) { Sound& st = mSoundThread[i]; if (stream->writeFlag(mask & (SoundMaskN << i))) if (stream->writeFlag(st.play)) @@ -3136,7 +2968,7 @@ U32 ShapeBase::packUpdate(NetConnection *con, U32 mask, BitStream *stream) } if (stream->writeFlag(mask & ImageMask)) { - for (int i = 0; i < MaxMountedImages; i++) + for (S32 i = 0; i < MaxMountedImages; i++) if (stream->writeFlag(mask & (ImageMaskN << i))) { MountedImage& image = mMountedImageList[i]; if (stream->writeFlag(image.dataBlock)) @@ -3158,9 +2990,9 @@ U32 ShapeBase::packUpdate(NetConnection *con, U32 mask, BitStream *stream) stream->writeFlag(image.triggerDown); stream->writeFlag(image.altTriggerDown); - for (U32 i=0; iwriteFlag(image.genericTrigger[i]); + stream->writeFlag(image.genericTrigger[j]); } stream->writeInt(image.fireCount,3); @@ -3173,7 +3005,7 @@ U32 ShapeBase::packUpdate(NetConnection *con, U32 mask, BitStream *stream) } // Group some of the uncommon stuff together. - if (stream->writeFlag(mask & (NameMask | ShieldMask | CloakMask | InvincibleMask | SkinMask | MeshHiddenMask ))) { + if (stream->writeFlag(mask & (NameMask | CloakMask | SkinMask | MeshHiddenMask ))) { if (stream->writeFlag(mask & CloakMask)) { @@ -3194,14 +3026,6 @@ U32 ShapeBase::packUpdate(NetConnection *con, U32 mask, BitStream *stream) if (stream->writeFlag(mask & NameMask)) { con->packNetStringHandleU(stream, mShapeNameHandle); } - if (stream->writeFlag(mask & ShieldMask)) { - stream->writeNormalVector(mShieldNormal, ShieldNormalBits); - stream->writeFloat( getEnergyValue(), EnergyLevelBits ); - } - if (stream->writeFlag(mask & InvincibleMask)) { - stream->write(mInvincibleTime); - stream->write(mInvincibleSpeed); - } if ( stream->writeFlag( mask & MeshHiddenMask ) ) stream->writeBits( mMeshHidden ); @@ -3271,7 +3095,7 @@ void ShapeBase::unpackUpdate(NetConnection *con, BitStream *stream) // Mounted Images if (stream->readFlag()) { - for (int i = 0; i < MaxMountedImages; i++) { + for (S32 i = 0; i < MaxMountedImages; i++) { if (stream->readFlag()) { MountedImage& image = mMountedImageList[i]; ShapeBaseImageData* imageData = 0; @@ -3303,14 +3127,14 @@ void ShapeBase::unpackUpdate(NetConnection *con, BitStream *stream) image.triggerDown = stream->readFlag(); image.altTriggerDown = stream->readFlag(); - for (U32 i=0; ireadFlag(); + image.genericTrigger[j] = stream->readFlag(); } - int count = stream->readInt(3); - int altCount = stream->readInt(3); - int reloadCount = stream->readInt(3); + S32 count = stream->readInt(3); + S32 altCount = stream->readInt(3); + S32 reloadCount = stream->readInt(3); bool datablockChange = image.dataBlock != imageData; if (datablockChange || (image.skinNameHandle != skinDesiredNameHandle)) @@ -3443,25 +3267,6 @@ void ShapeBase::unpackUpdate(NetConnection *con, BitStream *stream) if (stream->readFlag()) { // NameMask mShapeNameHandle = con->unpackNetStringHandleU(stream); } - if(stream->readFlag()) // ShieldMask - { - // Cloaking, Shield, and invul masking - Point3F shieldNormal; - stream->readNormalVector(&shieldNormal, ShieldNormalBits); - - // CodeReview [bjg 4/6/07] This is our energy level - why aren't we storing it? Was in a - // local variable called energyPercent. - stream->readFloat(EnergyLevelBits); - } - - if (stream->readFlag()) - { - // InvincibleMask - F32 time, speed; - stream->read(&time); - stream->read(&speed); - setupInvincibleEffect(time, speed); - } if ( stream->readFlag() ) // MeshHiddenMask { @@ -3742,7 +3547,7 @@ void ShapeBase::reSkin() Vector skins; String(mSkinNameHandle.getString()).split( ";", skins ); - for (int i = 0; i < skins.size(); i++) + for (S32 i = 0; i < skins.size(); i++) { String oldSkin( mAppliedSkinName.c_str() ); String newSkin( skins[i] ); @@ -4826,18 +4631,6 @@ DefineEngineMethod( ShapeBase, setCameraFov, void, ( F32 fov ),, object->setCameraFov( fov ); } -DefineEngineMethod( ShapeBase, setInvincibleMode, void, ( F32 time, F32 speed ),, - "@brief Setup the invincible effect.\n\n" - - "This effect is used for HUD feedback to the user that they are invincible.\n" - "@note Currently not implemented\n" - - "@param time duration in seconds for the invincible effect\n" - "@param speed speed at which the invincible effect progresses\n" ) -{ - object->setupInvincibleEffect( time, speed ); -} - DefineEngineMethod( ShapeBase, startFade, void, ( S32 time, S32 delay, bool fadeOut ),, "@brief Fade the object in or out without removing it from the scene.\n\n" diff --git a/Engine/source/T3D/shapeBase.h b/Engine/source/T3D/shapeBase.h index 2987163df..0bb54faf4 100644 --- a/Engine/source/T3D/shapeBase.h +++ b/Engine/source/T3D/shapeBase.h @@ -689,7 +689,6 @@ public: MaxMountedImages = 4, ///< Should be a power of 2 MaxImageEmitters = 3, NumImageBits = 3, - ShieldNormalBits = 8, CollisionTimeoutValue = 250 ///< Timeout in ms. }; @@ -743,17 +742,6 @@ protected: /// @} - /// @name Invincibility - /// @{ - F32 mInvincibleCount; - F32 mInvincibleTime; - F32 mInvincibleSpeed; - F32 mInvincibleDelta; - F32 mInvincibleEffect; - F32 mInvincibleFade; - bool mInvincibleOn; - /// @} - /// @name Motion /// @{ bool mMoveMotion; ///< Indicates that a Move has come in requesting x, y or z motion @@ -918,9 +906,6 @@ protected: bool mFlipFadeVal; - /// Last shield direction (cur. unused) - Point3F mShieldNormal; - /// Camera shake caused by weapon fire. CameraShake *mWeaponCamShake; @@ -1156,11 +1141,9 @@ public: DamageMask = Parent::NextFreeMask << 1, NoWarpMask = Parent::NextFreeMask << 2, CloakMask = Parent::NextFreeMask << 3, - ShieldMask = Parent::NextFreeMask << 4, - InvincibleMask = Parent::NextFreeMask << 5, - SkinMask = Parent::NextFreeMask << 6, - MeshHiddenMask = Parent::NextFreeMask << 7, - SoundMaskN = Parent::NextFreeMask << 8, ///< Extends + MaxSoundThreads bits + SkinMask = Parent::NextFreeMask << 4, + MeshHiddenMask = Parent::NextFreeMask << 5, + SoundMaskN = Parent::NextFreeMask << 6, ///< Extends + MaxSoundThreads bits ThreadMaskN = SoundMaskN << MaxSoundThreads, ///< Extends + MaxScriptThreads bits ImageMaskN = ThreadMaskN << MaxScriptThreads, ///< Extends + MaxMountedImage bits NextFreeMask = ImageMaskN << MaxMountedImages @@ -1702,26 +1685,6 @@ public: virtual void setWhiteOut(const F32); /// @} - /// @name Invincibility effect - /// This is the screen effect when invincible in the HUD - /// @see GameRenderFilters() - /// @{ - - /// Returns the level of invincibility effect - virtual F32 getInvincibleEffect() const; - - /// Initializes invincibility effect and interpolation parameters - /// - /// @param time Time it takes to become invincible - /// @param speed Speed at which invincibility effects progress - virtual void setupInvincibleEffect(F32 time, F32 speed); - - /// Advance invincibility effect animation - /// @param dt Time since last call of this function - virtual void updateInvincibleEffect(F32 dt); - - /// @} - /// @name Movement & velocity /// @{ diff --git a/Engine/source/T3D/shapeImage.cpp b/Engine/source/T3D/shapeImage.cpp index 554eeb55b..548984ca8 100644 --- a/Engine/source/T3D/shapeImage.cpp +++ b/Engine/source/T3D/shapeImage.cpp @@ -203,7 +203,7 @@ ShapeBaseImageData::ShapeBaseImageData() scriptAnimTransitionTime = 0.25f; // - for (int i = 0; i < MaxStates; i++) { + for (S32 i = 0; i < MaxStates; i++) { stateName[i] = 0; stateTransitionLoaded[i] = 0; @@ -462,7 +462,10 @@ bool ShapeBaseImageData::preload(bool server, String &errorStr) Torque::FS::FileNodeRef fileRef = Torque::FS::GetFileNode(shape[i].getPath()); if (!fileRef) + { + errorStr = String::ToString("ShapeBaseImageData: Couldn't load shape \"%s\"",name); return false; + } if(server) { @@ -3057,7 +3060,7 @@ TICKAGAIN: if (image.spinThread[i]) { - float timeScale; + F32 timeScale; switch (stateData.spin) { diff --git a/Engine/source/T3D/trigger.cpp b/Engine/source/T3D/trigger.cpp index 019b0c45c..bbc598b0c 100644 --- a/Engine/source/T3D/trigger.cpp +++ b/Engine/source/T3D/trigger.cpp @@ -188,7 +188,7 @@ bool Trigger::castRay(const Point3F &start, const Point3F &end, RayInfo* info) F32 const *si = &start.x; F32 const *ei = &end.x; - for (int i = 0; i < 3; i++) + for (S32 i = 0; i < 3; i++) { if (*si < *ei) { diff --git a/Engine/source/T3D/tsStatic.cpp b/Engine/source/T3D/tsStatic.cpp index f2e666c4f..1474bf96d 100644 --- a/Engine/source/T3D/tsStatic.cpp +++ b/Engine/source/T3D/tsStatic.cpp @@ -442,7 +442,7 @@ void TSStatic::reSkin() Vector skins; String(mSkinNameHandle.getString()).split( ";", skins ); - for (int i = 0; i < skins.size(); i++) + for (S32 i = 0; i < skins.size(); i++) { String oldSkin( mAppliedSkinName.c_str() ); String newSkin( skins[i] ); diff --git a/Engine/source/T3D/turret/aiTurretShape.cpp b/Engine/source/T3D/turret/aiTurretShape.cpp index f4da6522d..068523e0f 100644 --- a/Engine/source/T3D/turret/aiTurretShape.cpp +++ b/Engine/source/T3D/turret/aiTurretShape.cpp @@ -99,7 +99,7 @@ AITurretShapeData::AITurretShapeData() weaponLeadVelocity = 0; - for (int i = 0; i < MaxStates; i++) { + for (S32 i = 0; i < MaxStates; i++) { stateName[i] = 0; stateTransitionAtRest[i] = 0; stateTransitionNotAtRest[i] = 0; diff --git a/Engine/source/T3D/vehicles/vehicle.cpp b/Engine/source/T3D/vehicles/vehicle.cpp index f4b58ac61..df10b2cdc 100644 --- a/Engine/source/T3D/vehicles/vehicle.cpp +++ b/Engine/source/T3D/vehicles/vehicle.cpp @@ -69,7 +69,7 @@ const F32 sVehicleGravity = -20; // Physics and collision constants static F32 sRestTol = 0.5; // % of gravity energy to be at rest -static int sRestCount = 10; // Consecutive ticks before comming to rest +static S32 sRestCount = 10; // Consecutive ticks before comming to rest } // namespace {} @@ -218,6 +218,7 @@ bool VehicleData::preload(bool server, String &errorStr) if (!collisionDetails.size() || collisionDetails[0] == -1) { Con::errorf("VehicleData::preload failed: Vehicle models must define a collision-1 detail"); + errorStr = String::ToString("VehicleData: Couldn't load shape \"%s\"",shapeName); return false; } @@ -341,14 +342,14 @@ void VehicleData::packData(BitStream* stream) } } - for (int j = 0; j < VC_NUM_DAMAGE_EMITTER_AREAS; j++) + for (S32 j = 0; j < VC_NUM_DAMAGE_EMITTER_AREAS; j++) { stream->write( damageEmitterOffset[j].x ); stream->write( damageEmitterOffset[j].y ); stream->write( damageEmitterOffset[j].z ); } - for (int k = 0; k < VC_NUM_DAMAGE_LEVELS; k++) + for (S32 k = 0; k < VC_NUM_DAMAGE_LEVELS; k++) { stream->write( damageLevelTolerance[k] ); } @@ -440,14 +441,14 @@ void VehicleData::unpackData(BitStream* stream) } } - for( int j=0; jread( &damageEmitterOffset[j].x ); stream->read( &damageEmitterOffset[j].y ); stream->read( &damageEmitterOffset[j].z ); } - for( int k=0; kread( &damageLevelTolerance[k] ); } @@ -718,7 +719,7 @@ bool Vehicle::onAdd() { if( mDataBlock->dustEmitter ) { - for( int i=0; ionNewDataBlock( mDataBlock->dustEmitter, false ); @@ -1804,7 +1805,7 @@ void Vehicle::updateDamageSmoke( F32 dt ) F32 damagePercent = mDamage / mDataBlock->maxDamage; if( damagePercent >= mDataBlock->damageLevelTolerance[j] ) { - for( int i=0; inumDmgEmitterAreas; i++ ) + for( S32 i=0; inumDmgEmitterAreas; i++ ) { MatrixF trans = getTransform(); Point3F offset = mDataBlock->damageEmitterOffset[i]; @@ -1935,7 +1936,7 @@ void Vehicle::_renderMassAndContacts( ObjectRenderInst *ri, SceneRenderState *st GFX->getDrawUtil()->drawCube(desc, Point3F(0.1f,0.1f,0.1f),mDataBlock->massCenter, ColorI(255, 255, 255), &mRenderObjToWorld); // Now render all the contact points. - for (int i = 0; i < mCollisionList.getCount(); i++) + for (S32 i = 0; i < mCollisionList.getCount(); i++) { const Collision& collision = mCollisionList[i]; GFX->getDrawUtil()->drawCube(desc, Point3F(0.05f,0.05f,0.05f),collision.point, ColorI(0, 0, 255)); @@ -1943,7 +1944,7 @@ void Vehicle::_renderMassAndContacts( ObjectRenderInst *ri, SceneRenderState *st // Finally render the normals as one big batch. PrimBuild::begin(GFXLineList, mCollisionList.getCount() * 2); - for (int i = 0; i < mCollisionList.getCount(); i++) + for (S32 i = 0; i < mCollisionList.getCount(); i++) { const Collision& collision = mCollisionList[i]; PrimBuild::color3f(1, 1, 1); diff --git a/Engine/source/T3D/vehicles/vehicle.h b/Engine/source/T3D/vehicles/vehicle.h index da3b62eeb..695c16686 100644 --- a/Engine/source/T3D/vehicles/vehicle.h +++ b/Engine/source/T3D/vehicles/vehicle.h @@ -202,7 +202,7 @@ class Vehicle: public ShapeBase CollisionList mContacts; Rigid mRigid; ShapeBaseConvex mConvex; - int restCount; + S32 restCount; SimObjectPtr mDustEmitterList[VehicleData::VC_NUM_DUST_EMITTERS]; SimObjectPtr mDamageEmitterList[VehicleData::VC_NUM_DAMAGE_EMITTERS]; diff --git a/Engine/source/app/net/httpObject.cpp b/Engine/source/app/net/httpObject.cpp index c75faed8e..d521d5000 100644 --- a/Engine/source/app/net/httpObject.cpp +++ b/Engine/source/app/net/httpObject.cpp @@ -298,7 +298,7 @@ void HTTPObject::onDisconnect() Parent::onDisconnect(); } -bool HTTPObject::processLine(U8 *line) +bool HTTPObject::processLine(UTF8 *line) { if(mParseState == ParsingStatusLine) { diff --git a/Engine/source/app/net/httpObject.h b/Engine/source/app/net/httpObject.h index 76647401a..ac12690aa 100644 --- a/Engine/source/app/net/httpObject.h +++ b/Engine/source/app/net/httpObject.h @@ -72,7 +72,7 @@ public: virtual void onConnected(); virtual void onConnectFailed(); virtual void onDisconnect(); - bool processLine(U8 *line); + bool processLine(UTF8 *line); DECLARE_CONOBJECT(HTTPObject); }; diff --git a/Engine/source/app/net/tcpObject.cpp b/Engine/source/app/net/tcpObject.cpp index 37ee3ccd4..92b67df1d 100644 --- a/Engine/source/app/net/tcpObject.cpp +++ b/Engine/source/app/net/tcpObject.cpp @@ -421,7 +421,7 @@ DefineEngineMethod(TCPObject, send, void, (const char *data),, object->send( (const U8*)data, dStrlen(data) ); } -DefineEngineMethod(TCPObject, listen, void, (int port),, +DefineEngineMethod(TCPObject, listen, void, (U32 port),, "@brief Start listening on the specified port for connections.\n\n" "This method starts a listener which looks for incoming TCP connections to a port. " diff --git a/Engine/source/app/version.h b/Engine/source/app/version.h index 9a6bdff8d..03051c512 100644 --- a/Engine/source/app/version.h +++ b/Engine/source/app/version.h @@ -41,10 +41,10 @@ /// code version, the game name, and which type of game it is (TGB, TGE, TGEA, etc.). /// /// Version number is major * 1000 + minor * 100 + revision * 10. -#define TORQUE_GAME_ENGINE 3500 +#define TORQUE_GAME_ENGINE 3501 /// Human readable engine version string. -#define TORQUE_GAME_ENGINE_VERSION_STRING "3.5" +#define TORQUE_GAME_ENGINE_VERSION_STRING "3.5.1" /// Gets the engine version number. The version number is specified as a global in version.cc U32 getVersionNumber(); diff --git a/Engine/source/cinterface/c_consoleInterface.cpp b/Engine/source/cinterface/c_consoleInterface.cpp index b23c0b56d..21a2e48fd 100644 --- a/Engine/source/cinterface/c_consoleInterface.cpp +++ b/Engine/source/cinterface/c_consoleInterface.cpp @@ -43,7 +43,7 @@ extern "C" { return so->getClassName(); } - void *SimObject_GetFieldList(SimObject *so, int &outNumFields) + void *SimObject_GetFieldList(SimObject *so, S32 &outNumFields) { const AbstractClassRep::FieldList &fl = so->getFieldList(); outNumFields = fl.size(); diff --git a/Engine/source/cinterface/c_scripting.cpp b/Engine/source/cinterface/c_scripting.cpp index e6448089b..1f9aa2281 100644 --- a/Engine/source/cinterface/c_scripting.cpp +++ b/Engine/source/cinterface/c_scripting.cpp @@ -29,7 +29,7 @@ // External scripting cinterface, suitable for import into any scripting system which support "C" interfaces (C#, Python, Lua, Java, etc) -#ifdef TORQUE_OS_WIN32 +#ifdef TORQUE_OS_WIN #include "windowManager/win32/win32Window.h" #include "windowManager/win32/winDispatch.h" #endif @@ -164,7 +164,7 @@ extern "C" { return false; } - void script_simobject_setfield_int(U32 objectId, const char* fieldName, int v) + void script_simobject_setfield_int(U32 objectId, const char* fieldName, S32 v) { SimObject *object = Sim::findObject( objectId ); if( object ) @@ -222,7 +222,7 @@ extern "C" { { // maxArgs improper on a number of console function/methods if (argc < entry->mMinArgs)// || argc > entry->mMaxArgs) - return ""; + return false; SimObject* o = NULL; @@ -230,7 +230,7 @@ extern "C" { { o = Sim::findObject(dAtoi(argv[1])); if (!o) - return ""; + return false; } return entry->cb.mBoolCallbackFunc(o, argc, argv); @@ -291,12 +291,12 @@ extern "C" { entry->cb.mVoidCallbackFunc(o, argc, argv); } - int script_simobject_get_id(SimObject* so) + S32 script_simobject_get_id(SimObject* so) { return so->getId(); } - int script_simobject_find(const char* classname, const char* name) + S32 script_simobject_find(const char* classname, const char* name) { SimObject *object; if( Sim::findObject( name, object ) ) @@ -383,9 +383,9 @@ extern "C" { } -#ifdef TORQUE_OS_WIN32 +#ifdef TORQUE_OS_WIN - void script_input_event(int type, int value1, int value2) + void script_input_event(S32 type, S32 value1, S32 value2) { if (PlatformWindowManager::get() && PlatformWindowManager::get()->getFirstWindow()) { diff --git a/Engine/source/cinterface/cinterface.cpp b/Engine/source/cinterface/cinterface.cpp index f5b1c1412..ecfdeaf97 100644 --- a/Engine/source/cinterface/cinterface.cpp +++ b/Engine/source/cinterface/cinterface.cpp @@ -29,7 +29,7 @@ #include "windowManager/platformWindow.h" #include "windowManager/platformWindowMgr.h" -#ifdef TORQUE_OS_WIN32 +#ifdef TORQUE_OS_WIN #include "windowManager/win32/win32Window.h" #include "windowManager/win32/winDispatch.h" extern void createFontInit(void); @@ -37,7 +37,7 @@ extern void createFontShutdown(void); #endif #if defined( TORQUE_MINIDUMP ) && defined( TORQUE_RELEASE ) - extern INT CreateMiniDump(LPEXCEPTION_POINTERS ExceptionInfo); + extern S32 CreateMiniDump(LPEXCEPTION_POINTERS ExceptionInfo); #endif static HashTable gSecureScript; @@ -47,7 +47,7 @@ static HashTable gSecureScript; // ObjC hooks for shared library support // See: macMain.mm -void torque_mac_engineinit(int argc, const char **argv); +void torque_mac_engineinit(S32 argc, const char **argv); void torque_mac_enginetick(); void torque_mac_engineshutdown(); @@ -64,7 +64,7 @@ extern "C" { } // initialize Torque 3D including argument handling - int torque_engineinit(S32 argc, const char **argv) + S32 torque_engineinit(S32 argc, const char **argv) { #if defined( TORQUE_MINIDUMP ) && defined( TORQUE_RELEASE ) @@ -105,7 +105,7 @@ extern "C" { } // tick Torque 3D's main loop - int torque_enginetick() + S32 torque_enginetick() { #if defined( TORQUE_MINIDUMP ) && defined( TORQUE_RELEASE ) @@ -139,7 +139,7 @@ extern "C" { } // shutdown the engine - int torque_engineshutdown() + S32 torque_engineshutdown() { #if defined( TORQUE_MINIDUMP ) && defined( TORQUE_RELEASE ) @@ -181,7 +181,7 @@ extern "C" { } - int torque_getconsolebool(const char* name) + S32 torque_getconsolebool(const char* name) { return Con::getBoolVariable(name); } @@ -303,7 +303,7 @@ extern "C" { Namespace::Entry* entry = GetEntry(nameSpace, name); if (!entry) - return ""; + return false; return entry->cb.mBoolCallbackFunc(NULL, argc, argv); } @@ -415,7 +415,7 @@ extern "C" { PlatformWindowManager::get()->getFirstWindow()->setSize(Point2I(width,height)); } -#ifdef TORQUE_OS_WIN32 +#ifdef TORQUE_OS_WIN // retrieve the hwnd of our render window void* torque_gethwnd() { diff --git a/Engine/source/collision/collision.h b/Engine/source/collision/collision.h index a2a69df23..8dec9791c 100644 --- a/Engine/source/collision/collision.h +++ b/Engine/source/collision/collision.h @@ -96,7 +96,7 @@ public: } // Accessors - int getCount() const { return mCount; } + S32 getCount() const { return mCount; } F32 getTime() const { return mT; } F32 getMaxHeight() const { return mMaxHeight; } diff --git a/Engine/source/collision/gjk.cpp b/Engine/source/collision/gjk.cpp index bd84e6d4f..5dff5ec92 100644 --- a/Engine/source/collision/gjk.cpp +++ b/Engine/source/collision/gjk.cpp @@ -69,21 +69,21 @@ void GjkCollisionState::swap() void GjkCollisionState::compute_det() { // Dot new point with current set - for (int i = 0, bit = 1; i < 4; ++i, bit <<=1) + for (S32 i = 0, bit = 1; i < 4; ++i, bit <<=1) if (bits & bit) dp[i][last] = dp[last][i] = mDot(y[i], y[last]); dp[last][last] = mDot(y[last], y[last]); // Calulate the determinent det[last_bit][last] = 1; - for (int j = 0, sj = 1; j < 4; ++j, sj <<= 1) { + for (S32 j = 0, sj = 1; j < 4; ++j, sj <<= 1) { if (bits & sj) { - int s2 = sj | last_bit; + S32 s2 = sj | last_bit; det[s2][j] = dp[last][last] - dp[last][j]; det[s2][last] = dp[j][j] - dp[j][last]; - for (int k = 0, sk = 1; k < j; ++k, sk <<= 1) { + for (S32 k = 0, sk = 1; k < j; ++k, sk <<= 1) { if (bits & sk) { - int s3 = sk | s2; + S32 s3 = sk | s2; det[s3][k] = det[s2][j] * (dp[j][j] - dp[j][k]) + det[s2][last] * (dp[last][j] - dp[last][k]); det[s3][j] = det[sk | last_bit][k] * (dp[k][k] - dp[k][j]) + @@ -114,11 +114,11 @@ void GjkCollisionState::compute_det() //---------------------------------------------------------------------------- -inline void GjkCollisionState::compute_vector(int bits, VectorF& v) +inline void GjkCollisionState::compute_vector(S32 bits, VectorF& v) { F32 sum = 0; v.set(0, 0, 0); - for (int i = 0, bit = 1; i < 4; ++i, bit <<= 1) { + for (S32 i = 0, bit = 1; i < 4; ++i, bit <<= 1) { if (bits & bit) { sum += det[bits][i]; v += y[i] * det[bits][i]; @@ -130,9 +130,9 @@ inline void GjkCollisionState::compute_vector(int bits, VectorF& v) //---------------------------------------------------------------------------- -inline bool GjkCollisionState::valid(int s) +inline bool GjkCollisionState::valid(S32 s) { - for (int i = 0, bit = 1; i < 4; ++i, bit <<= 1) { + for (S32 i = 0, bit = 1; i < 4; ++i, bit <<= 1) { if (all_bits & bit) { if (s & bit) { if (det[s][i] <= 0) @@ -152,7 +152,7 @@ inline bool GjkCollisionState::valid(int s) inline bool GjkCollisionState::closest(VectorF& v) { compute_det(); - for (int s = bits; s; --s) { + for (S32 s = bits; s; --s) { if ((s & bits) == s) { if (valid(s | last_bit)) { bits = s | last_bit; @@ -175,7 +175,7 @@ inline bool GjkCollisionState::closest(VectorF& v) inline bool GjkCollisionState::degenerate(const VectorF& w) { - for (int i = 0, bit = 1; i < 4; ++i, bit <<= 1) + for (S32 i = 0, bit = 1; i < 4; ++i, bit <<= 1) if ((all_bits & bit) && y[i] == w) return true; return false; @@ -256,7 +256,7 @@ void GjkCollisionState::getClosestPoints(Point3F& p1, Point3F& p2) F32 sum = 0; p1.set(0, 0, 0); p2.set(0, 0, 0); - for (int i = 0, bit = 1; i < 4; ++i, bit <<= 1) { + for (S32 i = 0, bit = 1; i < 4; ++i, bit <<= 1) { if (bits & bit) { sum += det[bits][i]; p1 += p[i] * det[bits][i]; diff --git a/Engine/source/collision/gjk.h b/Engine/source/collision/gjk.h index d78555f72..b35f4570d 100644 --- a/Engine/source/collision/gjk.h +++ b/Engine/source/collision/gjk.h @@ -58,8 +58,8 @@ struct GjkCollisionState: public CollisionState /// void compute_det(); - bool valid(int s); - void compute_vector(int bits, VectorF& v); + bool valid(S32 s); + void compute_vector(S32 bits, VectorF& v); bool closest(VectorF& v); bool degenerate(const VectorF& w); void nextBit(); diff --git a/Engine/source/collision/polytope.cpp b/Engine/source/collision/polytope.cpp index 21d9d6a8e..f07116583 100644 --- a/Engine/source/collision/polytope.cpp +++ b/Engine/source/collision/polytope.cpp @@ -280,7 +280,7 @@ bool Polytope::intersect(const PlaneF& plane,const Point3F& sp,const Point3F& ep //---------------------------------------------------------------------------- -void Polytope::extrudeFace(int faceIdx,const VectorF& vec,Polytope* out) +void Polytope::extrudeFace(S32 faceIdx,const VectorF& vec,Polytope* out) { // Assumes the face belongs to the first volume. out->mVertexList.clear(); @@ -373,7 +373,7 @@ bool Polytope::findCollision(const VectorF& vec,Polytope::Collision *best) return false; if (!best->object) best->distance = 1.0E30f; - int bestVertex = -1; + S32 bestVertex = -1; Polytope::Volume* bestVolume = NULL; sideCount++; diff --git a/Engine/source/collision/polytope.h b/Engine/source/collision/polytope.h index a28f08854..c96a54979 100644 --- a/Engine/source/collision/polytope.h +++ b/Engine/source/collision/polytope.h @@ -102,7 +102,7 @@ public: void buildBox(const MatrixF& transform,const Box3F& box); void intersect(SimObject*, const BSPNode* node); inline bool didIntersect() { return mVolumeList.size() > 1; } - void extrudeFace(int fi,const VectorF& vec,Polytope* out); + void extrudeFace(S32 fi,const VectorF& vec,Polytope* out); bool findCollision(const VectorF& vec,Polytope::Collision *best); }; diff --git a/Engine/source/component/dynamicConsoleMethodComponent.cpp b/Engine/source/component/dynamicConsoleMethodComponent.cpp index c76cae60a..fa7adf896 100644 --- a/Engine/source/component/dynamicConsoleMethodComponent.cpp +++ b/Engine/source/component/dynamicConsoleMethodComponent.cpp @@ -139,7 +139,7 @@ const char *DynamicConsoleMethodComponent::_callMethod( U32 argc, const char *ar if( getComponentCount() > 0 ) { lockComponentList(); - for( int i = getComponentCount() - 1; i >= 0; i-- ) + for( S32 i = getComponentCount() - 1; i >= 0; i-- ) //for( SimComponentIterator nItr = componentList.end(); nItr != componentList.begin(); nItr-- ) { argv[0] = cbName; diff --git a/Engine/source/console/CMDscan.cpp b/Engine/source/console/CMDscan.cpp index 4ce606638..24f118d2d 100644 --- a/Engine/source/console/CMDscan.cpp +++ b/Engine/source/console/CMDscan.cpp @@ -1910,8 +1910,7 @@ extern int isatty (int ); b->yy_bs_column = 0; } - b->yy_is_interactive = file ? (isatty( fileno(file) ) > 0) : 0; - + b->yy_is_interactive = file ? (isatty( fileno(file) ) > 0) : 0; errno = oerrno; } @@ -2355,7 +2354,7 @@ void CMDerror(char *format, ...) char tempBuf[BUFMAX]; va_list args; va_start( args, format ); -#ifdef TORQUE_OS_WIN32 +#ifdef TORQUE_OS_WIN _vsnprintf( tempBuf, BUFMAX, format, args ); #else vsnprintf( tempBuf, BUFMAX, format, args ); diff --git a/Engine/source/console/CMDscan.l b/Engine/source/console/CMDscan.l index d6d37a5c6..cef682e89 100644 --- a/Engine/source/console/CMDscan.l +++ b/Engine/source/console/CMDscan.l @@ -245,7 +245,7 @@ void CMDerror(char *format, ...) char tempBuf[BUFMAX]; va_list args; va_start( args, format ); -#ifdef TORQUE_OS_WIN32 +#ifdef TORQUE_OS_WIN _vsnprintf( tempBuf, BUFMAX, format, args ); #else vsnprintf( tempBuf, BUFMAX, format, args ); diff --git a/Engine/source/console/SimXMLDocument.cpp b/Engine/source/console/SimXMLDocument.cpp index 6076b9711..31e2f9906 100644 --- a/Engine/source/console/SimXMLDocument.cpp +++ b/Engine/source/console/SimXMLDocument.cpp @@ -348,7 +348,7 @@ bool SimXMLDocument::pushFirstChildElement(const char* rName) TiXmlElement* pElement; if(!m_paNode.empty()) { - const int iLastElement = m_paNode.size() - 1; + const S32 iLastElement = m_paNode.size() - 1; TiXmlElement* pNode = m_paNode[iLastElement]; if(!pNode) { @@ -412,7 +412,7 @@ bool SimXMLDocument::pushChildElement(S32 index) TiXmlElement* pElement; if(!m_paNode.empty()) { - const int iLastElement = m_paNode.size() - 1; + const S32 iLastElement = m_paNode.size() - 1; TiXmlElement* pNode = m_paNode[iLastElement]; if(!pNode) { @@ -472,7 +472,7 @@ bool SimXMLDocument::nextSiblingElement(const char* rName) { return false; } - const int iLastElement = m_paNode.size() - 1; + const S32 iLastElement = m_paNode.size() - 1; TiXmlElement*& pElement = m_paNode[iLastElement]; if(!pElement) { @@ -506,7 +506,7 @@ const char* SimXMLDocument::elementValue() { return StringTable->insert(""); } - const int iLastElement = m_paNode.size() - 1; + const S32 iLastElement = m_paNode.size() - 1; TiXmlElement* pNode = m_paNode[iLastElement]; if(!pNode) { @@ -547,7 +547,7 @@ const char* SimXMLDocument::attribute(const char* rAttribute) { return StringTable->insert(""); } - const int iLastElement = m_paNode.size() - 1; + const S32 iLastElement = m_paNode.size() - 1; TiXmlElement* pNode = m_paNode[iLastElement]; if(!pNode) { @@ -597,7 +597,7 @@ bool SimXMLDocument::attributeExists(const char* rAttribute) { return false; } - const int iLastElement = m_paNode.size() - 1; + const S32 iLastElement = m_paNode.size() - 1; TiXmlElement* pNode = m_paNode[iLastElement]; if(!pNode) { @@ -630,7 +630,7 @@ const char* SimXMLDocument::firstAttribute() { return StringTable->insert(""); } - const int iLastElement = m_paNode.size() - 1; + const S32 iLastElement = m_paNode.size() - 1; TiXmlElement* pNode = m_paNode[iLastElement]; if(!pNode) { @@ -667,7 +667,7 @@ const char* SimXMLDocument::lastAttribute() { return StringTable->insert(""); } - const int iLastElement = m_paNode.size() - 1; + const S32 iLastElement = m_paNode.size() - 1; TiXmlElement* pNode = m_paNode[iLastElement]; if(!pNode) { @@ -766,7 +766,7 @@ void SimXMLDocument::setAttribute(const char* rAttribute, const char* rVal) return; } - const int iLastElement = m_paNode.size() - 1; + const S32 iLastElement = m_paNode.size() - 1; TiXmlElement* pElement = m_paNode[iLastElement]; if(!pElement) { @@ -798,7 +798,7 @@ void SimXMLDocument::setObjectAttributes(const char* objectID) if( pObject == NULL ) return; - const int iLastElement = m_paNode.size() - 1; + const S32 iLastElement = m_paNode.size() - 1; TiXmlElement* pElement = m_paNode[iLastElement]; if(!pElement) return; @@ -925,7 +925,7 @@ void SimXMLDocument::pushNewElement(const char* rName) } else { - const int iFinalElement = m_paNode.size() - 1; + const S32 iFinalElement = m_paNode.size() - 1; TiXmlElement* pNode = m_paNode[iFinalElement]; if(!pNode) { @@ -975,7 +975,7 @@ void SimXMLDocument::addNewElement(const char* rName) return; } - const int iParentElement = m_paNode.size() - 2; + const S32 iParentElement = m_paNode.size() - 2; if(iParentElement < 0) { pStackTop = dynamic_cast @@ -1002,7 +1002,7 @@ void SimXMLDocument::addNewElement(const char* rName) } // Overwrite top stack position. - const int iFinalElement = m_paNode.size() - 1; + const S32 iFinalElement = m_paNode.size() - 1; m_paNode[iFinalElement] = pStackTop; //pNode = pStackTop; } @@ -1091,7 +1091,7 @@ const char* SimXMLDocument::readComment( S32 index ) // Push the first element found under the current element of the given name if(!m_paNode.empty()) { - const int iLastElement = m_paNode.size() - 1; + const S32 iLastElement = m_paNode.size() - 1; TiXmlElement* pNode = m_paNode[iLastElement]; if(!pNode) { @@ -1159,7 +1159,7 @@ void SimXMLDocument::addText(const char* text) if(m_paNode.empty()) return; - const int iFinalElement = m_paNode.size() - 1; + const S32 iFinalElement = m_paNode.size() - 1; TiXmlElement* pNode = m_paNode[iFinalElement]; if(!pNode) return; @@ -1204,7 +1204,7 @@ const char* SimXMLDocument::getText() if(m_paNode.empty()) return ""; - const int iFinalElement = m_paNode.size() - 1; + const S32 iFinalElement = m_paNode.size() - 1; TiXmlNode* pNode = m_paNode[iFinalElement]; if(!pNode) return ""; @@ -1264,7 +1264,7 @@ void SimXMLDocument::removeText() if(m_paNode.empty()) return; - const int iFinalElement = m_paNode.size() - 1; + const S32 iFinalElement = m_paNode.size() - 1; TiXmlElement* pNode = m_paNode[iFinalElement]; if(!pNode) return; @@ -1300,7 +1300,7 @@ void SimXMLDocument::addData(const char* text) if(m_paNode.empty()) return; - const int iFinalElement = m_paNode.size() - 1; + const S32 iFinalElement = m_paNode.size() - 1; TiXmlElement* pNode = m_paNode[iFinalElement]; if(!pNode) return; @@ -1346,7 +1346,7 @@ const char* SimXMLDocument::getData() if(m_paNode.empty()) return ""; - const int iFinalElement = m_paNode.size() - 1; + const S32 iFinalElement = m_paNode.size() - 1; TiXmlNode* pNode = m_paNode[iFinalElement]; if(!pNode) return ""; diff --git a/Engine/source/console/ast.h b/Engine/source/console/ast.h index 71cfbeec0..4be4fef90 100644 --- a/Engine/source/console/ast.h +++ b/Engine/source/console/ast.h @@ -250,8 +250,8 @@ struct StreqExprNode : BinaryExprNode struct StrcatExprNode : BinaryExprNode { - int appendChar; - static StrcatExprNode *alloc( S32 lineNumber, ExprNode *left, ExprNode *right, int appendChar ); + S32 appendChar; + static StrcatExprNode *alloc( S32 lineNumber, ExprNode *left, ExprNode *right, S32 appendChar ); U32 precompile(TypeReq type); U32 compile(U32 *codeStream, U32 ip, TypeReq type); TypeReq getPreferredType(); diff --git a/Engine/source/console/astAlloc.cpp b/Engine/source/console/astAlloc.cpp index 842429822..19809a1e2 100644 --- a/Engine/source/console/astAlloc.cpp +++ b/Engine/source/console/astAlloc.cpp @@ -149,7 +149,7 @@ StreqExprNode *StreqExprNode::alloc( S32 lineNumber, ExprNode *left, ExprNode *r return ret; } -StrcatExprNode *StrcatExprNode::alloc( S32 lineNumber, ExprNode *left, ExprNode *right, int appendChar ) +StrcatExprNode *StrcatExprNode::alloc( S32 lineNumber, ExprNode *left, ExprNode *right, S32 appendChar ) { StrcatExprNode *ret = (StrcatExprNode *) consoleAlloc(sizeof(StrcatExprNode)); constructInPlace(ret); diff --git a/Engine/source/console/cmdgram.cpp b/Engine/source/console/cmdgram.cpp index 35ed58bd0..33dc24203 100644 --- a/Engine/source/console/cmdgram.cpp +++ b/Engine/source/console/cmdgram.cpp @@ -2059,12 +2059,6 @@ yydestruct (yymsg, yytype, yyvaluep) yymsg = "Deleting"; YY_SYMBOL_PRINT (yymsg, yytype, yyvaluep, yylocationp); - switch (yytype) - { - - default: - break; - } } diff --git a/Engine/source/console/codeBlock.cpp b/Engine/source/console/codeBlock.cpp index 896d2a4cf..c6efd9cf2 100644 --- a/Engine/source/console/codeBlock.cpp +++ b/Engine/source/console/codeBlock.cpp @@ -403,14 +403,14 @@ bool CodeBlock::read(StringTableEntry fileName, Stream &st) for(U32 i = 0; i < size; i++) st.read(&functionFloats[i]); } - U32 codeSize; - st.read(&codeSize); + U32 codeLength; + st.read(&codeLength); st.read(&lineBreakPairCount); - U32 totSize = codeSize + lineBreakPairCount * 2; + U32 totSize = codeLength + lineBreakPairCount * 2; code = new U32[totSize]; - for(i = 0; i < codeSize; i++) + for(i = 0; i < codeLength; i++) { U8 b; st.read(&b); @@ -420,10 +420,10 @@ bool CodeBlock::read(StringTableEntry fileName, Stream &st) code[i] = b; } - for(i = codeSize; i < totSize; i++) + for(i = codeLength; i < totSize; i++) st.read(&code[i]); - lineBreakPairs = code + codeSize; + lineBreakPairs = code + codeLength; // StringTable-ize our identifiers. U32 identCount; @@ -559,7 +559,7 @@ bool CodeBlock::compile(const char *codeFileName, StringTableEntry fileName, con } -const char *CodeBlock::compileExec(StringTableEntry fileName, const char *inString, bool noCalls, int setFrame) +const char *CodeBlock::compileExec(StringTableEntry fileName, const char *inString, bool noCalls, S32 setFrame) { // Check for a UTF8 script file char *string; diff --git a/Engine/source/console/codeBlock.h b/Engine/source/console/codeBlock.h index 98e581e46..bf09e79c7 100644 --- a/Engine/source/console/codeBlock.h +++ b/Engine/source/console/codeBlock.h @@ -129,7 +129,7 @@ public: /// -1 a new frame is created. If the index is out of range the /// top stack frame is used. const char *compileExec(StringTableEntry fileName, const char *script, - bool noCalls, int setFrame = -1 ); + bool noCalls, S32 setFrame = -1 ); /// Executes the existing code in the CodeBlock. The return string is any /// result of the code executed, if any, or an empty string. diff --git a/Engine/source/console/console.cpp b/Engine/source/console/console.cpp index 0e7099ff2..838b3ab14 100644 --- a/Engine/source/console/console.cpp +++ b/Engine/source/console/console.cpp @@ -248,7 +248,7 @@ static bool active = false; static bool newLogFile; static const char *logFileName; -static const int MaxCompletionBufferSize = 4096; +static const S32 MaxCompletionBufferSize = 4096; static char completionBuffer[MaxCompletionBufferSize]; static char tabBuffer[MaxCompletionBufferSize] = {0}; static SimObjectPtr tabObject; diff --git a/Engine/source/console/consoleDoc.cpp b/Engine/source/console/consoleDoc.cpp index 1170b256d..41c5e8027 100644 --- a/Engine/source/console/consoleDoc.cpp +++ b/Engine/source/console/consoleDoc.cpp @@ -223,7 +223,7 @@ void Namespace::printNamespaceEntries(Namespace * g, bool dumpScript, bool dumpE // Iterate through the methods of the namespace... for(Entry *ewalk = g->mEntryList; ewalk; ewalk = ewalk->mNext) { - int eType = ewalk->mType; + S32 eType = ewalk->mType; const char * funcName = ewalk->mFunctionName; if( ( eType == Entry::ConsoleFunctionType ) && !dumpScript ) diff --git a/Engine/source/console/consoleFunctions.cpp b/Engine/source/console/consoleFunctions.cpp index 537f583ba..e406ae9ce 100644 --- a/Engine/source/console/consoleFunctions.cpp +++ b/Engine/source/console/consoleFunctions.cpp @@ -259,7 +259,7 @@ DefineConsoleFunction( strstr, S32, ( const char* string, const char* substring //----------------------------------------------------------------------------- -DefineConsoleFunction( strpos, S32, ( const char* haystack, const char* needle, int offset ), ( 0 ), +DefineConsoleFunction( strpos, S32, ( const char* haystack, const char* needle, S32 offset ), ( 0 ), "Find the start of @a needle in @a haystack searching from left to right beginning at the given offset.\n" "@param haystack The string to search.\n" "@param needle The string to search for.\n" @@ -479,7 +479,7 @@ DefineConsoleFunction( strreplace, const char*, ( const char* source, const char if(!scan) { dStrcpy(ret + dstp, source + scanp); - return ret; + break; } U32 len = scan - (source + scanp); dStrncpy(ret + dstp, source + scanp, len); diff --git a/Engine/source/console/consoleLogger.cpp b/Engine/source/console/consoleLogger.cpp index aedc9baab..ec3408001 100644 --- a/Engine/source/console/consoleLogger.cpp +++ b/Engine/source/console/consoleLogger.cpp @@ -175,7 +175,7 @@ bool ConsoleLogger::detach() mStream.close(); // Remove this object from the list of active loggers - for( int i = 0; i < mActiveLoggers.size(); i++ ) + for( S32 i = 0; i < mActiveLoggers.size(); i++ ) { if( mActiveLoggers[i] == this ) { diff --git a/Engine/source/console/consoleTypes.cpp b/Engine/source/console/consoleTypes.cpp index a948686a4..059a9170c 100644 --- a/Engine/source/console/consoleTypes.cpp +++ b/Engine/source/console/consoleTypes.cpp @@ -29,6 +29,7 @@ #include "core/color.h" #include "console/simBase.h" #include "math/mRect.h" +#include "core/strings/stringUnit.h" //----------------------------------------------------------------------------- // TypeString @@ -567,7 +568,17 @@ ImplementConsoleTypeCasters( TypeColorF, ColorF ) ConsoleGetType( TypeColorF ) { - ColorF * color = (ColorF*)dptr; + // Fetch color. + const ColorF* color = (ColorF*)dptr; + + // Fetch stock color name. + StringTableEntry colorName = StockColor::name( *color ); + + // Write as color name if was found. + if ( colorName != StringTable->EmptyString() ) + return colorName; + + // Format as color components. char* returnBuffer = Con::getReturnBuffer(256); dSprintf(returnBuffer, 256, "%g %g %g %g", color->red, color->green, color->blue, color->alpha); return(returnBuffer); @@ -578,6 +589,22 @@ ConsoleSetType( TypeColorF ) ColorF *tmpColor = (ColorF *) dptr; if(argc == 1) { + // Is only a single argument passed? + if ( StringUnit::getUnitCount( argv[0], " " ) == 1 ) + { + // Is this a stock color name? + if ( !StockColor::isColor(argv[0]) ) + { + // No, so warn. + Con::warnf( "TypeColorF() - Invalid single argument of '%s' could not be interpreted as a stock color name. Using default.", argv[0] ); + } + + // Set stock color (if it's invalid we'll get the default. + tmpColor->set( argv[0] ); + + return; + } + tmpColor->set(0, 0, 0, 1); F32 r,g,b,a; S32 args = dSscanf(argv[0], "%g %g %g %g", &r, &g, &b, &a); @@ -602,7 +629,7 @@ ConsoleSetType( TypeColorF ) tmpColor->alpha = dAtof(argv[3]); } else - Con::printf("Color must be set as { r, g, b [,a] }"); + Con::printf("Color must be set as { r, g, b [,a] }, { r g b [b] } or { stockColorName }"); } //----------------------------------------------------------------------------- @@ -613,7 +640,17 @@ ImplementConsoleTypeCasters( TypeColorI, ColorI ) ConsoleGetType( TypeColorI ) { - ColorI *color = (ColorI *) dptr; + // Fetch color. + ColorI* color = (ColorI*)dptr; + + // Fetch stock color name. + StringTableEntry colorName = StockColor::name( *color ); + + // Write as color name if was found. + if ( colorName != StringTable->EmptyString() ) + return colorName; + + // Format as color components. char* returnBuffer = Con::getReturnBuffer(256); dSprintf(returnBuffer, 256, "%d %d %d %d", color->red, color->green, color->blue, color->alpha); return returnBuffer; @@ -624,6 +661,22 @@ ConsoleSetType( TypeColorI ) ColorI *tmpColor = (ColorI *) dptr; if(argc == 1) { + // Is only a single argument passed? + if ( StringUnit::getUnitCount( argv[0], " " ) == 1 ) + { + // Is this a stock color name? + if ( !StockColor::isColor(argv[0]) ) + { + // No, so warn. + Con::warnf( "TypeColorF() - Invalid single argument of '%s' could not be interpreted as a stock color name. Using default.", argv[0] ); + } + + // Set stock color (if it's invalid we'll get the default. + tmpColor->set( argv[0] ); + + return; + } + tmpColor->set(0, 0, 0, 255); S32 r,g,b,a; S32 args = dSscanf(argv[0], "%d %d %d %d", &r, &g, &b, &a); @@ -648,7 +701,7 @@ ConsoleSetType( TypeColorI ) tmpColor->alpha = dAtoi(argv[3]); } else - Con::printf("Color must be set as { r, g, b [,a] }"); + Con::printf("Color must be set as { r, g, b [,a] }, { r g b [b] } or { stockColorName }"); } //----------------------------------------------------------------------------- diff --git a/Engine/source/console/consoleXMLExport.cpp b/Engine/source/console/consoleXMLExport.cpp index f6764ac77..1b498a089 100644 --- a/Engine/source/console/consoleXMLExport.cpp +++ b/Engine/source/console/consoleXMLExport.cpp @@ -255,7 +255,7 @@ namespace Con { mXML->pushNewElement("EnumTables"); // write out the used EnumTables - for (int i = 0; i < enumTables.size(); i++) + for (S32 i = 0; i < enumTables.size(); i++) { mXML->pushNewElement("EnumTable"); @@ -267,7 +267,7 @@ namespace Con { mXML->pushNewElement("Enums"); - for (int j = 0; j < table->size; j++) + for (S32 j = 0; j < table->size; j++) { mXML->pushNewElement("Enum"); diff --git a/Engine/source/console/engineAPI.h b/Engine/source/console/engineAPI.h index 4358844b4..d8b27ea82 100644 --- a/Engine/source/console/engineAPI.h +++ b/Engine/source/console/engineAPI.h @@ -76,6 +76,7 @@ // Disable some VC warnings that are irrelevant to us. +#pragma warning( push ) #pragma warning( disable : 4510 ) // default constructor could not be generated; all the Args structures are never constructed by us #pragma warning( disable : 4610 ) // can never be instantiated; again Args is never constructed by us @@ -1383,14 +1384,14 @@ struct _EngineConsoleThunkCountArgs // Encapsulation of a legacy console function invocation. -template< int startArgc, typename T > +template< S32 startArgc, typename T > struct _EngineConsoleThunk {}; -template< int startArgc, typename R > +template< S32 startArgc, typename R > struct _EngineConsoleThunk< startArgc, R() > { typedef typename _EngineConsoleThunkType< R >::ReturnType ReturnType; - static const int NUM_ARGS = 0; + static const S32 NUM_ARGS = 0; static ReturnType thunk( S32 argc, const char** argv, R ( *fn )(), const _EngineFunctionDefaultArguments< void() >& ) { return _EngineConsoleThunkReturnValue( fn() ); @@ -1401,11 +1402,11 @@ struct _EngineConsoleThunk< startArgc, R() > return _EngineConsoleThunkReturnValue( ( frame->*fn )() ); } }; -template< int startArgc > +template< S32 startArgc > struct _EngineConsoleThunk< startArgc, void() > { typedef void ReturnType; - static const int NUM_ARGS = 0; + static const S32 NUM_ARGS = 0; static void thunk( S32 argc, const char** argv, void ( *fn )(), const _EngineFunctionDefaultArguments< void() >& ) { fn(); @@ -1417,11 +1418,11 @@ struct _EngineConsoleThunk< startArgc, void() > } }; -template< int startArgc, typename R, typename A > +template< S32 startArgc, typename R, typename A > struct _EngineConsoleThunk< startArgc, R( A ) > { typedef typename _EngineConsoleThunkType< R >::ReturnType ReturnType; - static const int NUM_ARGS = 1 + startArgc; + static const S32 NUM_ARGS = 1 + startArgc; static ReturnType thunk( S32 argc, const char** argv, R ( *fn )( A ), const _EngineFunctionDefaultArguments< void( A ) >& defaultArgs ) { A a = ( startArgc < argc ? EngineUnmarshallData< A >()( argv[ startArgc ] ) : A( defaultArgs.a ) ); @@ -1434,11 +1435,11 @@ struct _EngineConsoleThunk< startArgc, R( A ) > return _EngineConsoleThunkReturnValue( ( frame->*fn )( a ) ); } }; -template< int startArgc, typename A > +template< S32 startArgc, typename A > struct _EngineConsoleThunk< startArgc, void( A ) > { typedef void ReturnType; - static const int NUM_ARGS = 1 + startArgc; + static const S32 NUM_ARGS = 1 + startArgc; static void thunk( S32 argc, const char** argv, void ( *fn )( A ), const _EngineFunctionDefaultArguments< void( A ) >& defaultArgs ) { A a = ( startArgc < argc ? EngineUnmarshallData< A >()( argv[ startArgc ] ) : A( defaultArgs.a ) ); @@ -1452,11 +1453,11 @@ struct _EngineConsoleThunk< startArgc, void( A ) > } }; -template< int startArgc, typename R, typename A, typename B > +template< S32 startArgc, typename R, typename A, typename B > struct _EngineConsoleThunk< startArgc, R( A, B ) > { typedef typename _EngineConsoleThunkType< R >::ReturnType ReturnType; - static const int NUM_ARGS = 2 + startArgc; + static const S32 NUM_ARGS = 2 + startArgc; static ReturnType thunk( S32 argc, const char** argv, R ( *fn )( A, B ), const _EngineFunctionDefaultArguments< void( A, B ) >& defaultArgs ) { A a = ( startArgc < argc ? EngineUnmarshallData< A >()( argv[ startArgc ] ) : A( defaultArgs.a ) ); @@ -1471,11 +1472,11 @@ struct _EngineConsoleThunk< startArgc, R( A, B ) > return _EngineConsoleThunkReturnValue( ( frame->*fn )( a, b ) ); } }; -template< int startArgc, typename A, typename B > +template< S32 startArgc, typename A, typename B > struct _EngineConsoleThunk< startArgc, void( A, B ) > { typedef void ReturnType; - static const int NUM_ARGS = 2 + startArgc; + static const S32 NUM_ARGS = 2 + startArgc; static void thunk( S32 argc, const char** argv, void ( *fn )( A, B ), const _EngineFunctionDefaultArguments< void( A, B ) >& defaultArgs ) { A a = ( startArgc < argc ? EngineUnmarshallData< A >()( argv[ startArgc ] ) : A( defaultArgs.a ) ); @@ -1491,11 +1492,11 @@ struct _EngineConsoleThunk< startArgc, void( A, B ) > } }; -template< int startArgc, typename R, typename A, typename B, typename C > +template< S32 startArgc, typename R, typename A, typename B, typename C > struct _EngineConsoleThunk< startArgc, R( A, B, C ) > { typedef typename _EngineConsoleThunkType< R >::ReturnType ReturnType; - static const int NUM_ARGS = 3 + startArgc; + static const S32 NUM_ARGS = 3 + startArgc; static ReturnType thunk( S32 argc, const char** argv, R ( *fn )( A, B, C ), const _EngineFunctionDefaultArguments< void( A, B, C ) >& defaultArgs ) { A a = ( startArgc < argc ? EngineUnmarshallData< A >()( argv[ startArgc ] ) : A( defaultArgs.a ) ); @@ -1512,11 +1513,11 @@ struct _EngineConsoleThunk< startArgc, R( A, B, C ) > return _EngineConsoleThunkReturnValue( ( frame->*fn )( a, b, c ) ); } }; -template< int startArgc, typename A, typename B, typename C > +template< S32 startArgc, typename A, typename B, typename C > struct _EngineConsoleThunk< startArgc, void( A, B, C ) > { typedef void ReturnType; - static const int NUM_ARGS = 3 + startArgc; + static const S32 NUM_ARGS = 3 + startArgc; static void thunk( S32 argc, const char** argv, void ( *fn )( A, B, C ), const _EngineFunctionDefaultArguments< void( A, B, C ) >& defaultArgs ) { A a = ( startArgc < argc ? EngineUnmarshallData< A >()( argv[ startArgc ] ) : A( defaultArgs.a ) ); @@ -1534,11 +1535,11 @@ struct _EngineConsoleThunk< startArgc, void( A, B, C ) > } }; -template< int startArgc, typename R, typename A, typename B, typename C, typename D > +template< S32 startArgc, typename R, typename A, typename B, typename C, typename D > struct _EngineConsoleThunk< startArgc, R( A, B, C, D ) > { typedef typename _EngineConsoleThunkType< R >::ReturnType ReturnType; - static const int NUM_ARGS = 4 + startArgc; + static const S32 NUM_ARGS = 4 + startArgc; static ReturnType thunk( S32 argc, const char** argv, R ( *fn )( A, B, C, D ), const _EngineFunctionDefaultArguments< void( A, B, C, D ) >& defaultArgs ) { A a = ( startArgc < argc ? EngineUnmarshallData< A >()( argv[ startArgc ] ) : A( defaultArgs.a ) ); @@ -1557,11 +1558,11 @@ struct _EngineConsoleThunk< startArgc, R( A, B, C, D ) > return _EngineConsoleThunkReturnValue( ( frame->*fn )( a, b, c, d ) ); } }; -template< int startArgc, typename A, typename B, typename C, typename D > +template< S32 startArgc, typename A, typename B, typename C, typename D > struct _EngineConsoleThunk< startArgc, void( A, B, C, D ) > { typedef void ReturnType; - static const int NUM_ARGS = 4 + startArgc; + static const S32 NUM_ARGS = 4 + startArgc; static void thunk( S32 argc, const char** argv, void ( *fn )( A, B, C, D ), const _EngineFunctionDefaultArguments< void( A, B, C, D ) >& defaultArgs ) { A a = ( startArgc < argc ? EngineUnmarshallData< A >()( argv[ startArgc ] ) : A( defaultArgs.a ) ); @@ -1581,11 +1582,11 @@ struct _EngineConsoleThunk< startArgc, void( A, B, C, D ) > } }; -template< int startArgc, typename R, typename A, typename B, typename C, typename D, typename E > +template< S32 startArgc, typename R, typename A, typename B, typename C, typename D, typename E > struct _EngineConsoleThunk< startArgc, R( A, B, C, D, E ) > { typedef typename _EngineConsoleThunkType< R >::ReturnType ReturnType; - static const int NUM_ARGS = 5 + startArgc; + static const S32 NUM_ARGS = 5 + startArgc; static ReturnType thunk( S32 argc, const char** argv, R ( *fn )( A, B, C, D, E ), const _EngineFunctionDefaultArguments< void( A, B, C, D, E ) >& defaultArgs ) { A a = ( startArgc < argc ? EngineUnmarshallData< A >()( argv[ startArgc ] ) : A( defaultArgs.a ) ); @@ -1606,11 +1607,11 @@ struct _EngineConsoleThunk< startArgc, R( A, B, C, D, E ) > return _EngineConsoleThunkReturnValue( ( frame->*fn )( a, b, c, d, e ) ); } }; -template< int startArgc, typename A, typename B, typename C, typename D, typename E > +template< S32 startArgc, typename A, typename B, typename C, typename D, typename E > struct _EngineConsoleThunk< startArgc, void( A, B, C, D, E ) > { typedef void ReturnType; - static const int NUM_ARGS = 5 + startArgc; + static const S32 NUM_ARGS = 5 + startArgc; static void thunk( S32 argc, const char** argv, void ( *fn )( A, B, C, D, E ), const _EngineFunctionDefaultArguments< void( A, B, C, D, E ) >& defaultArgs ) { A a = ( startArgc < argc ? EngineUnmarshallData< A >()( argv[ startArgc ] ) : A( defaultArgs.a ) ); @@ -1632,11 +1633,11 @@ struct _EngineConsoleThunk< startArgc, void( A, B, C, D, E ) > } }; -template< int startArgc, typename R, typename A, typename B, typename C, typename D, typename E, typename F > +template< S32 startArgc, typename R, typename A, typename B, typename C, typename D, typename E, typename F > struct _EngineConsoleThunk< startArgc, R( A, B, C, D, E, F ) > { typedef typename _EngineConsoleThunkType< R >::ReturnType ReturnType; - static const int NUM_ARGS = 6 + startArgc; + static const S32 NUM_ARGS = 6 + startArgc; static ReturnType thunk( S32 argc, const char** argv, R ( *fn )( A, B, C, D, E, F ), const _EngineFunctionDefaultArguments< void( A, B, C, D, E, F ) >& defaultArgs ) { A a = ( startArgc < argc ? EngineUnmarshallData< A >()( argv[ startArgc ] ) : A( defaultArgs.a ) ); @@ -1659,11 +1660,11 @@ struct _EngineConsoleThunk< startArgc, R( A, B, C, D, E, F ) > return _EngineConsoleThunkReturnValue( ( frame->*fn )( a, b, c, d, e, f ) ); } }; -template< int startArgc, typename A, typename B, typename C, typename D, typename E, typename F > +template< S32 startArgc, typename A, typename B, typename C, typename D, typename E, typename F > struct _EngineConsoleThunk< startArgc, void( A, B, C, D, E, F ) > { typedef void ReturnType; - static const int NUM_ARGS = 6 + startArgc; + static const S32 NUM_ARGS = 6 + startArgc; static void thunk( S32 argc, const char** argv, void ( *fn )( A, B, C, D, E, F ), const _EngineFunctionDefaultArguments< void( A, B, C, D, E, F ) >& defaultArgs ) { A a = ( startArgc < argc ? EngineUnmarshallData< A >()( argv[ startArgc ] ) : A( defaultArgs.a ) ); @@ -1687,11 +1688,11 @@ struct _EngineConsoleThunk< startArgc, void( A, B, C, D, E, F ) > } }; -template< int startArgc, typename R, typename A, typename B, typename C, typename D, typename E, typename F, typename G > +template< S32 startArgc, typename R, typename A, typename B, typename C, typename D, typename E, typename F, typename G > struct _EngineConsoleThunk< startArgc, R( A, B, C, D, E, F, G ) > { typedef typename _EngineConsoleThunkType< R >::ReturnType ReturnType; - static const int NUM_ARGS = 7 + startArgc; + static const S32 NUM_ARGS = 7 + startArgc; static ReturnType thunk( S32 argc, const char** argv, R ( *fn )( A, B, C, D, E, F, G ), const _EngineFunctionDefaultArguments< void( A, B, C, D, E, F, G ) >& defaultArgs ) { A a = ( startArgc < argc ? EngineUnmarshallData< A >()( argv[ startArgc ] ) : A( defaultArgs.a ) ); @@ -1716,11 +1717,11 @@ struct _EngineConsoleThunk< startArgc, R( A, B, C, D, E, F, G ) > return _EngineConsoleThunkReturnValue( ( frame->*fn )( a, b, c, d, e, f, g ) ); } }; -template< int startArgc, typename A, typename B, typename C, typename D, typename E, typename F, typename G > +template< S32 startArgc, typename A, typename B, typename C, typename D, typename E, typename F, typename G > struct _EngineConsoleThunk< startArgc, void( A, B, C, D, E, F, G ) > { typedef void ReturnType; - static const int NUM_ARGS = 7 + startArgc; + static const S32 NUM_ARGS = 7 + startArgc; static void thunk( S32 argc, const char** argv, void ( *fn )( A, B, C, D, E, F, G ), const _EngineFunctionDefaultArguments< void( A, B, C, D, E, F, G ) >& defaultArgs ) { A a = ( startArgc < argc ? EngineUnmarshallData< A >()( argv[ startArgc ] ) : A( defaultArgs.a ) ); @@ -1746,11 +1747,11 @@ struct _EngineConsoleThunk< startArgc, void( A, B, C, D, E, F, G ) > } }; -template< int startArgc, typename R, typename A, typename B, typename C, typename D, typename E, typename F, typename G, typename H > +template< S32 startArgc, typename R, typename A, typename B, typename C, typename D, typename E, typename F, typename G, typename H > struct _EngineConsoleThunk< startArgc, R( A, B, C, D, E, F, G, H ) > { typedef typename _EngineConsoleThunkType< R >::ReturnType ReturnType; - static const int NUM_ARGS = 8 + startArgc; + static const S32 NUM_ARGS = 8 + startArgc; static ReturnType thunk( S32 argc, const char** argv, R ( *fn )( A, B, C, D, E, F, G, H ), const _EngineFunctionDefaultArguments< void( A, B, C, D, E, F, G, H ) >& defaultArgs ) { A a = ( startArgc < argc ? EngineUnmarshallData< A >()( argv[ startArgc ] ) : A( defaultArgs.a ) ); @@ -1777,11 +1778,11 @@ struct _EngineConsoleThunk< startArgc, R( A, B, C, D, E, F, G, H ) > return _EngineConsoleThunkReturnValue( ( frame->*fn )( a, b, c, d, e, f, g, h ) ); } }; -template< int startArgc, typename A, typename B, typename C, typename D, typename E, typename F, typename G, typename H > +template< S32 startArgc, typename A, typename B, typename C, typename D, typename E, typename F, typename G, typename H > struct _EngineConsoleThunk< startArgc, void( A, B, C, D, E, F, G, H ) > { typedef void ReturnType; - static const int NUM_ARGS = 8 + startArgc; + static const S32 NUM_ARGS = 8 + startArgc; static void thunk( S32 argc, const char** argv, void ( *fn )( A, B, C, D, E, F, G, H ), const _EngineFunctionDefaultArguments< void( A, B, C, D, E, F, G, H ) >& defaultArgs ) { A a = ( startArgc < argc ? EngineUnmarshallData< A >()( argv[ startArgc ] ) : A( defaultArgs.a ) ); @@ -1809,11 +1810,11 @@ struct _EngineConsoleThunk< startArgc, void( A, B, C, D, E, F, G, H ) > } }; -template< int startArgc, typename R, typename A, typename B, typename C, typename D, typename E, typename F, typename G, typename H, typename I > +template< S32 startArgc, typename R, typename A, typename B, typename C, typename D, typename E, typename F, typename G, typename H, typename I > struct _EngineConsoleThunk< startArgc, R( A, B, C, D, E, F, G, H, I ) > { typedef typename _EngineConsoleThunkType< R >::ReturnType ReturnType; - static const int NUM_ARGS = 9 + startArgc; + static const S32 NUM_ARGS = 9 + startArgc; static ReturnType thunk( S32 argc, const char** argv, R ( *fn )( A, B, C, D, E, F, G, H, I ), const _EngineFunctionDefaultArguments< void( A, B, C, D, E, F, G, H, I ) >& defaultArgs ) { A a = ( startArgc < argc ? EngineUnmarshallData< A >()( argv[ startArgc ] ) : A( defaultArgs.a ) ); @@ -1842,11 +1843,11 @@ struct _EngineConsoleThunk< startArgc, R( A, B, C, D, E, F, G, H, I ) > return _EngineConsoleThunkReturnValue( ( frame->*fn )( a, b, c, d, e, f, g, h, i ) ); } }; -template< int startArgc, typename A, typename B, typename C, typename D, typename E, typename F, typename G, typename H, typename I > +template< S32 startArgc, typename A, typename B, typename C, typename D, typename E, typename F, typename G, typename H, typename I > struct _EngineConsoleThunk< startArgc, void( A, B, C, D, E, F, G, H, I ) > { typedef void ReturnType; - static const int NUM_ARGS = 9 + startArgc; + static const S32 NUM_ARGS = 9 + startArgc; static void thunk( S32 argc, const char** argv, void ( *fn )( A, B, C, D, E, F, G, H, I ), const _EngineFunctionDefaultArguments< void( A, B, C, D, E, F, G, H, I ) >& defaultArgs ) { A a = ( startArgc < argc ? EngineUnmarshallData< A >()( argv[ startArgc ] ) : A( defaultArgs.a ) ); @@ -1876,11 +1877,11 @@ struct _EngineConsoleThunk< startArgc, void( A, B, C, D, E, F, G, H, I ) > } }; -template< int startArgc, typename R, typename A, typename B, typename C, typename D, typename E, typename F, typename G, typename H, typename I, typename J > +template< S32 startArgc, typename R, typename A, typename B, typename C, typename D, typename E, typename F, typename G, typename H, typename I, typename J > struct _EngineConsoleThunk< startArgc, R( A, B, C, D, E, F, G, H, I, J ) > { typedef typename _EngineConsoleThunkType< R >::ReturnType ReturnType; - static const int NUM_ARGS = 10 + startArgc; + static const S32 NUM_ARGS = 10 + startArgc; static ReturnType thunk( S32 argc, const char** argv, R ( *fn )( A, B, C, D, E, F, G, H, I, J ), const _EngineFunctionDefaultArguments< void( A, B, C, D, E, F, G, H, I, J ) >& defaultArgs ) { A a = ( startArgc < argc ? EngineUnmarshallData< A >()( argv[ startArgc ] ) : A( defaultArgs.a ) ); @@ -1911,11 +1912,11 @@ struct _EngineConsoleThunk< startArgc, R( A, B, C, D, E, F, G, H, I, J ) > return _EngineConsoleThunkReturnValue( ( frame->*fn )( a, b, c, d, e, f, g, h, i, j ) ); } }; -template< int startArgc, typename A, typename B, typename C, typename D, typename E, typename F, typename G, typename H, typename I, typename J > +template< S32 startArgc, typename A, typename B, typename C, typename D, typename E, typename F, typename G, typename H, typename I, typename J > struct _EngineConsoleThunk< startArgc, void( A, B, C, D, E, F, G, H, I, J ) > { typedef void ReturnType; - static const int NUM_ARGS = 10 + startArgc; + static const S32 NUM_ARGS = 10 + startArgc; static void thunk( S32 argc, const char** argv, void ( *fn )( A, B, C, D, E, F, G, H, I, J ), const _EngineFunctionDefaultArguments< void( A, B, C, D, E, F, G, H, I, J ) >& defaultArgs ) { A a = ( startArgc < argc ? EngineUnmarshallData< A >()( argv[ startArgc ] ) : A( defaultArgs.a ) ); @@ -1946,11 +1947,11 @@ struct _EngineConsoleThunk< startArgc, void( A, B, C, D, E, F, G, H, I, J ) > ( frame->*fn )( a, b, c, d, e, f, g, h, i, j ); } }; -template< int startArgc, typename R, typename A, typename B, typename C, typename D, typename E, typename F, typename G, typename H, typename I, typename J, typename K > +template< S32 startArgc, typename R, typename A, typename B, typename C, typename D, typename E, typename F, typename G, typename H, typename I, typename J, typename K > struct _EngineConsoleThunk< startArgc, R( A, B, C, D, E, F, G, H, I, J, K ) > { typedef typename _EngineConsoleThunkType< R >::ReturnType ReturnType; - static const int NUM_ARGS = 11 + startArgc; + static const S32 NUM_ARGS = 11 + startArgc; static ReturnType thunk( S32 argc, const char** argv, R ( *fn )( A, B, C, D, E, F, G, H, I, J, K ), const _EngineFunctionDefaultArguments< void( A, B, C, D, E, F, G, H, I, J, K ) >& defaultArgs ) { A a = ( startArgc < argc ? EngineUnmarshallData< A >()( argv[ startArgc ] ) : A( defaultArgs.a ) ); @@ -1983,11 +1984,11 @@ struct _EngineConsoleThunk< startArgc, R( A, B, C, D, E, F, G, H, I, J, K ) > return _EngineConsoleThunkReturnValue( ( frame->*fn )( a, b, c, d, e, f, g, h, i, j, k ) ); } }; -template< int startArgc, typename A, typename B, typename C, typename D, typename E, typename F, typename G, typename H, typename I, typename J, typename K > +template< S32 startArgc, typename A, typename B, typename C, typename D, typename E, typename F, typename G, typename H, typename I, typename J, typename K > struct _EngineConsoleThunk< startArgc, void( A, B, C, D, E, F, G, H, I, J, K ) > { typedef void ReturnType; - static const int NUM_ARGS = 11 + startArgc; + static const S32 NUM_ARGS = 11 + startArgc; static void thunk( S32 argc, const char** argv, void ( *fn )( A, B, C, D, E, F, G, H, I, J, K ), const _EngineFunctionDefaultArguments< void( A, B, C, D, E, F, G, H, I, J, K ) >& defaultArgs ) { A a = ( startArgc < argc ? EngineUnmarshallData< A >()( argv[ startArgc ] ) : A( defaultArgs.a ) ); @@ -2788,7 +2789,6 @@ struct _EngineConsoleCallbackHelper // Re-enable some VC warnings we disabled for this file. -#pragma warning( default : 4510 ) -#pragma warning( default : 4610 ) +#pragma warning( pop ) // 4510 and 4610 #endif // !_ENGINEAPI_H_ diff --git a/Engine/source/console/engineDoc.cpp b/Engine/source/console/engineDoc.cpp index f049b6cc3..2bc03cbe3 100644 --- a/Engine/source/console/engineDoc.cpp +++ b/Engine/source/console/engineDoc.cpp @@ -307,7 +307,7 @@ static void dumpNamespaceEntries( Stream &stream, Namespace *g, bool callbacks = // Go through all the entries in the namespace. for ( Namespace::Entry *ewalk = g->mEntryList; ewalk; ewalk = ewalk->mNext ) { - int eType = ewalk->mType; + S32 eType = ewalk->mType; // We do not dump script defined functions... only engine exports. if( eType == Namespace::Entry::ConsoleFunctionType diff --git a/Engine/source/console/fileSystemFunctions.cpp b/Engine/source/console/fileSystemFunctions.cpp index d6e29ecaa..7b159d30d 100644 --- a/Engine/source/console/fileSystemFunctions.cpp +++ b/Engine/source/console/fileSystemFunctions.cpp @@ -599,10 +599,10 @@ DefineEngineFunction(fileExt, String, ( const char* fileName ),, } DefineEngineFunction(fileBase, String, ( const char* fileName ),, - "@brief Get the base of a file name (removes extension)\n\n" + "@brief Get the base of a file name (removes extension and path)\n\n" "@param fileName Name and path of file to check\n" - "@return String containing the file name, minus extension\n" + "@return String containing the file name, minus extension and path\n" "@ingroup FileSystem") { @@ -626,10 +626,10 @@ DefineEngineFunction(fileBase, String, ( const char* fileName ),, } DefineEngineFunction(fileName, String, ( const char* fileName ),, - "@brief Get the file name of a file (removes extension and path)\n\n" + "@brief Get only the file name of a path and file name string (removes path)\n\n" "@param fileName Name and path of file to check\n" - "@return String containing the file name, minus extension and path\n" + "@return String containing the file name, minus the path\n" "@ingroup FileSystem") { S32 pathLen = dStrlen( fileName ); diff --git a/Engine/source/console/simObject.cpp b/Engine/source/console/simObject.cpp index 3385f3a91..9ad66e627 100644 --- a/Engine/source/console/simObject.cpp +++ b/Engine/source/console/simObject.cpp @@ -2663,7 +2663,7 @@ DefineConsoleMethod( SimObject, getDynamicFieldCount, S32, (),, //----------------------------------------------------------------------------- -DefineConsoleMethod( SimObject, getDynamicField, const char*, ( int index ),, +DefineConsoleMethod( SimObject, getDynamicField, const char*, ( S32 index ),, "Get a value of a dynamic field by index.\n" "@param index The index of the dynamic field.\n" "@return The value of the dynamic field at the given index or \"\"." ) @@ -2702,7 +2702,7 @@ DefineConsoleMethod( SimObject, getFieldCount, S32, (),, const AbstractClassRep::Field* f; U32 numDummyEntries = 0; - for(int i = 0; i < list.size(); i++) + for(S32 i = 0; i < list.size(); i++) { f = &list[i]; @@ -2716,7 +2716,7 @@ DefineConsoleMethod( SimObject, getFieldCount, S32, (),, //----------------------------------------------------------------------------- -DefineConsoleMethod( SimObject, getField, const char*, ( int index ),, +DefineConsoleMethod( SimObject, getField, const char*, ( S32 index ),, "Retrieve the value of a static field by index.\n" "@param index The index of the static field.\n" "@return The value of the static field with the given index or \"\"." ) diff --git a/Engine/source/console/simObject.h b/Engine/source/console/simObject.h index 541c15bbc..f7f5f550f 100644 --- a/Engine/source/console/simObject.h +++ b/Engine/source/console/simObject.h @@ -781,7 +781,7 @@ class SimObject: public ConsoleObject void setCanSaveDynamicFields( bool bCanSave ) { mCanSaveFieldDictionary = bCanSave; } /// Get whether fields created at runtime should be saved. Default is true. - bool getCanSaveDynamicFields( bool bCanSave ) { return mCanSaveFieldDictionary;} + bool getCanSaveDynamicFields( ) { return mCanSaveFieldDictionary;} /// Return the object that this object is copying fields from. SimObject* getCopySource() const { return mCopySource; } diff --git a/Engine/source/console/telnetDebugger.h b/Engine/source/console/telnetDebugger.h index 6916ae935..5a30c9cf7 100644 --- a/Engine/source/console/telnetDebugger.h +++ b/Engine/source/console/telnetDebugger.h @@ -127,7 +127,7 @@ public: void breakProcess(); - virtual void executionStopped(CodeBlock *code, U32 lineNumber); + void executionStopped(CodeBlock *code, U32 lineNumber); void send(const char *s); void setDebugParameters(S32 port, const char *password, bool waitForClient); void processConsoleLine(const char *consoleLine); diff --git a/Engine/source/core/bitRender.cpp b/Engine/source/core/bitRender.cpp index 39bbe127f..0365e6ac2 100644 --- a/Engine/source/core/bitRender.cpp +++ b/Engine/source/core/bitRender.cpp @@ -799,7 +799,7 @@ void BitRender::bitTo8Bit_3(U32 * bits, U32 * eightBits, S32 dim) #if defined(TORQUE_BIG_ENDIAN) #define MAX_SHADOW_TEXELS (256 + 4) //256 seems big enough, +4 so we can run off end of buffer. // slow fake gaussian - int i, j, c; + S32 i, j, c; U8 tmpLine[3][MAX_SHADOW_TEXELS]; U8 *src0, *src1, *src2; U8 *s0, *s1, *s2; @@ -809,7 +809,7 @@ void BitRender::bitTo8Bit_3(U32 * bits, U32 * eightBits, S32 dim) U32 currVal; U32 sampleVal; U8 c00, c01, c02, c10, c11, c12, c20, c21, c22; - int openBuf; + S32 openBuf; src0 = tmpLine[0]; src1 = tmpLine[1]; @@ -902,9 +902,9 @@ void BitRender::bitTo8Bit_3(U32 * bits, U32 * eightBits, S32 dim) sampleVal = 0; //c12; // take end. else // inner pixel { - const int wXP = 3; // corners - const int wPP = 4; // plus/NSEW - const int wCP = 4; // center + const S32 wXP = 3; // corners + const S32 wPP = 4; // plus/NSEW + const S32 wCP = 4; // center sampleVal = (c00+c02+c20+c22)*wXP + (c01+c10+c12+c21)*wPP + c11*wCP; sampleVal >>= 5; // div by 32 subsamples } diff --git a/Engine/source/core/color.cpp b/Engine/source/core/color.cpp index 17df1cb44..a28ef430f 100644 --- a/Engine/source/core/color.cpp +++ b/Engine/source/core/color.cpp @@ -38,3 +38,507 @@ const ColorI ColorI::BLACK( 0, 0, 0 ); const ColorI ColorI::RED( 255, 0, 0 ); const ColorI ColorI::GREEN( 0, 255, 0 ); const ColorI ColorI::BLUE( 0, 0, 255 ); + +#include "console/console.h" +#include "console/consoleTypes.h" + +#ifndef _STRINGUNIT_H_ +#include "core/strings/stringUnit.h" +#endif + +#ifndef _TDICTIONARY_H_ +#include "core/util/tDictionary.h" +#endif + +#include "console/consoleInternal.h" + +//----------------------------------------------------------------------------- + +typedef HashTable typeNameToColorFHash; +typedef HashTable typeNameToColorIHash; +typedef HashTable typeColorFToNameHash; +typedef HashTable typeColorIToNameHash; + +static typeNameToColorFHash mNameToColorF; +static typeNameToColorIHash mNameToColorI; +static typeColorFToNameHash mColorFToName; +static typeColorIToNameHash mColorIToName; + +#define DEFAULT_UNKNOWN_STOCK_COLOR_NAME "White" + +MODULE_BEGIN( StockColors ) + + MODULE_INIT_AFTER( GFX ) + + MODULE_INIT + { + // Create the stock colors. + StockColor::create(); + } + + MODULE_SHUTDOWN + { + // Destroy the stock colors. + StockColor::destroy(); + } + +MODULE_END; + +//----------------------------------------------------------------------------- + +StockColorItem StockColorTable[] = +{ + StockColorItem( "InvisibleBlack", 0, 0, 0, 0 ), + StockColorItem( "TransparentWhite", 255, 255, 255, 0 ), + StockColorItem( "AliceBlue", 240, 248, 255 ), + StockColorItem( "AntiqueWhite", 250, 235, 215 ), + StockColorItem( "Aqua", 0, 255, 255 ), + StockColorItem( "Aquamarine", 127, 255, 212 ), + StockColorItem( "Azure", 240, 255, 255 ), + StockColorItem( "Beige", 245, 245, 220 ), + StockColorItem( "Bisque", 255, 228, 196 ), + StockColorItem( "Black", 0, 0, 0, 255 ), + StockColorItem( "BlanchedAlmond", 255, 235, 205, 255 ), + StockColorItem( "Blue", 0, 0, 255 ), + StockColorItem( "BlueViolet", 138, 43, 226 ), + StockColorItem( "Brown", 165, 42, 42, 255 ), + StockColorItem( "BurlyWood", 222, 184, 135 ), + StockColorItem( "CadetBlue", 95, 158, 160 ), + StockColorItem( "Chartreuse", 127, 255, 0 ), + StockColorItem( "Chocolate", 210, 105, 30 ), + StockColorItem( "Coral", 255, 127, 80 ), + StockColorItem( "CornflowerBlue", 100, 149, 237 ), + StockColorItem( "Cornsilk", 255, 248, 220 ), + StockColorItem( "Crimson", 220, 20, 60 ), + StockColorItem( "Cyan", 0, 255, 255 ), + StockColorItem( "DarkBlue", 0, 0, 139 ), + StockColorItem( "DarkCyan", 0, 139, 139 ), + StockColorItem( "DarkGoldenrod", 184, 134, 11 ), + StockColorItem( "DarkGray", 169, 169, 169), + StockColorItem( "DarkGreen", 0, 100, 0 ), + StockColorItem( "DarkKhaki", 189, 183, 107 ), + StockColorItem( "DarkMagenta", 139, 0, 139 ), + StockColorItem( "DarkOliveGreen", 85, 107, 47 ), + StockColorItem( "DarkOrange", 255, 140, 0 ), + StockColorItem( "DarkOrchid", 153, 50, 204 ), + StockColorItem( "DarkRed", 139, 0, 0 ), + StockColorItem( "DarkSalmon", 233, 150, 122 ), + StockColorItem( "DarkSeaGreen", 143, 188, 139 ), + StockColorItem( "DarkSlateBlue", 72, 61, 139 ), + StockColorItem( "DarkSlateGray", 47, 79, 79 ), + StockColorItem( "DarkTurquoise", 0, 206, 209 ), + StockColorItem( "DarkViolet", 148, 0, 211 ), + StockColorItem( "DeepPink", 255, 20, 147 ), + StockColorItem( "DeepSkyBlue", 0, 191, 255 ), + StockColorItem( "DimGray", 105, 105, 105 ), + StockColorItem( "DodgerBlue", 30, 144, 255 ), + StockColorItem( "Firebrick", 178, 34, 34 ), + StockColorItem( "FloralWhite", 255, 250, 240 ), + StockColorItem( "ForestGreen", 34, 139, 34 ), + StockColorItem( "Fuchsia", 255, 0, 255 ), + StockColorItem( "Gainsboro", 220, 220, 220 ), + StockColorItem( "GhostWhite", 248, 248, 255 ), + StockColorItem( "Gold", 255, 215, 0 ), + StockColorItem( "Goldenrod", 218, 165, 32 ), + StockColorItem( "Gray", 128, 128, 128 ), + StockColorItem( "Green", 0, 128, 0 ), + StockColorItem( "GreenYellow", 173, 255, 47 ), + StockColorItem( "Honeydew", 240, 255, 24 ), + StockColorItem( "HotPink", 255, 105, 180 ), + StockColorItem( "IndianRed", 205, 92, 92 ), + StockColorItem( "Indigo", 75, 0, 130 ), + StockColorItem( "Ivory", 255, 255, 240 ), + StockColorItem( "Khaki", 240, 230, 140 ), + StockColorItem( "Lavender", 230, 230, 250 ), + StockColorItem( "LavenderBlush", 255, 240, 245 ), + StockColorItem( "LawnGreen", 124, 252, 0 ), + StockColorItem( "LemonChiffon", 255, 250, 205 ), + StockColorItem( "LightBlue", 173, 216, 230 ), + StockColorItem( "LightCoral", 240, 128, 128 ), + StockColorItem( "LightCyan", 224, 255, 255), + StockColorItem( "LightGoldenrodYellow", 250, 250, 210 ), + StockColorItem( "LightGray", 211, 211, 211), + StockColorItem( "LightGreen", 144, 238, 144 ), + StockColorItem( "LightPink", 255, 182, 193 ), + StockColorItem( "LightSalmon", 255, 160, 122 ), + StockColorItem( "LightSeaGreen", 32, 178, 170 ), + StockColorItem( "LightSkyBlue",135, 206, 250 ), + StockColorItem( "LightSlateGray", 119, 136, 153 ), + StockColorItem( "LightSteelBlue", 176, 196, 222 ), + StockColorItem( "LightYellow", 255, 255, 224 ), + StockColorItem( "Lime", 0, 255, 0 ), + StockColorItem( "LimeGreen", 50, 205, 50 ), + StockColorItem( "Linen", 250, 240, 230 ), + StockColorItem( "Magenta", 255, 0, 255 ), + StockColorItem( "Maroon", 128, 0, 0 ), + StockColorItem( "MediumAquamarine", 102, 205, 170 ), + StockColorItem( "MediumBlue", 0, 0, 205 ), + StockColorItem( "MediumOrchid", 186, 85, 211 ), + StockColorItem( "MediumPurple", 147, 112, 219 ), + StockColorItem( "MediumSeaGreen", 60, 179, 113 ), + StockColorItem( "MediumSlateBlue", 123, 104, 238 ), + StockColorItem( "MediumSpringGreen", 0, 250, 154 ), + StockColorItem( "MediumTurquoise", 72, 209, 204 ), + StockColorItem( "MediumVioletRed", 199, 21, 133 ), + StockColorItem( "MidnightBlue", 25, 25, 112 ), + StockColorItem( "MintCream", 245, 255, 250 ), + StockColorItem( "MistyRose", 255, 228, 225 ), + StockColorItem( "Moccasin", 255, 228, 181 ), + StockColorItem( "NavajoWhite", 255, 222, 173 ), + StockColorItem( "Navy", 0, 0, 128 ), + StockColorItem( "OldLace", 253, 245, 230 ), + StockColorItem( "Olive", 128, 128, 0 ), + StockColorItem( "OliveDrab", 107, 142, 35 ), + StockColorItem( "Orange", 255, 165, 0 ), + StockColorItem( "OrangeRed", 255, 69, 0 ), + StockColorItem( "Orchid", 218, 112, 214 ), + StockColorItem( "PaleGoldenrod", 238, 232, 170 ), + StockColorItem( "PaleGreen", 152, 251, 152 ), + StockColorItem( "PaleTurquoise", 175, 238, 238 ), + StockColorItem( "PaleVioletRed", 219, 112, 147 ), + StockColorItem( "PapayaWhip", 255, 239, 213 ), + StockColorItem( "PeachPuff", 255, 218, 185 ), + StockColorItem( "Peru", 205, 133, 63 ), + StockColorItem( "Pink", 55, 192, 203 ), + StockColorItem( "Plum", 221, 160, 221 ), + StockColorItem( "PowderBlue", 176, 224, 230 ), + StockColorItem( "Purple", 128, 0, 128 ), + StockColorItem( "Red", 255, 0, 0 ), + StockColorItem( "RosyBrown", 188, 143, 143 ), + StockColorItem( "RoyalBlue", 65, 105, 225 ), + StockColorItem( "SaddleBrown", 139, 69, 19 ), + StockColorItem( "Salmon", 250, 128, 114 ), + StockColorItem( "SandyBrown", 244, 164, 96 ), + StockColorItem( "SeaGreen", 46, 139, 87 ), + StockColorItem( "SeaShell", 255, 245, 238 ), + StockColorItem( "Sienna", 160, 82, 45 ), + StockColorItem( "Silver", 192, 192, 192 ), + StockColorItem( "SkyBlue", 135, 206, 235 ), + StockColorItem( "SlateBlue", 106, 90, 205 ), + StockColorItem( "SlateGray", 112, 128, 144 ), + StockColorItem( "Snow", 255, 250, 250 ), + StockColorItem( "SpringGreen", 0, 255, 127 ), + StockColorItem( "SteelBlue", 70, 130, 180 ), + StockColorItem( "Tan", 210, 180, 140 ), + StockColorItem( "Teal", 0, 128, 128 ), + StockColorItem( "Thistle", 216, 191, 216 ), + StockColorItem( "Tomato", 255, 99, 71 ), + StockColorItem( "Turquoise", 64, 224, 208 ), + StockColorItem( "Violet", 238, 130, 238 ), + StockColorItem( "Wheat", 245, 222, 179 ), + StockColorItem( "White", 255, 255, 255 ), + StockColorItem( "WhiteSmoke", 245, 245, 245 ), + StockColorItem( "Yellow", 255, 255, 0 ), + StockColorItem( "YellowGreen", 154, 205, 50 ) +}; + +//----------------------------------------------------------------------------- + +static bool stockColorsCreated = false; + +void StockColor::create( void ) +{ + // Finish if already created. + if ( stockColorsCreated ) + return; + + // Fetch stock color count. + const S32 stockColorCount = sizeof(StockColorTable) / sizeof(StockColorItem); + + // Insert all stock colors. + for( S32 index = 0; index < stockColorCount; ++index ) + { + // Fetch stock color item. + StockColorItem& stockColor = StockColorTable[index]; + + // Fetch stock color item. + StringTableEntry colorName = StringTable->insert( stockColor.mColorName ); + + // Insert stock color mappings. + mNameToColorF.insertUnique(colorName, stockColor.mColorF); + mNameToColorI.insertUnique(colorName, stockColor.mColorI); + mColorFToName.insertUnique(stockColor.mColorF, colorName); + mColorIToName.insertUnique(stockColor.mColorI, colorName); + } + + // Flag as created. + stockColorsCreated = true; +} + +//----------------------------------------------------------------------------- + +void StockColor::destroy( void ) +{ + // Finish if not created. + if ( !stockColorsCreated ) + return; + + // Clear stock color mappings. + mNameToColorF.clear(); + mNameToColorI.clear(); + mColorFToName.clear(); + mColorIToName.clear(); + + // Flag as not created. + stockColorsCreated = false; +} + +//----------------------------------------------------------------------------- + +bool StockColor::isColor( const char* pStockColorName ) +{ + // Sanity! + AssertFatal( pStockColorName != NULL, "Cannot fetch a NULL stock color name." ); + + // Fetch color name. + StringTableEntry colorName = StringTable->insert( pStockColorName ); + + // Find if color name exists or not. + return mNameToColorF.find( colorName ) != mNameToColorF.end(); +} + +//----------------------------------------------------------------------------- + +const ColorF& StockColor::colorF( const char* pStockColorName ) +{ + // Sanity! + AssertFatal( pStockColorName != NULL, "Cannot fetch a NULL stock color name." ); + + // Fetch color name. + StringTableEntry colorName = StringTable->insert( pStockColorName ); + + // Find stock color. + typeNameToColorFHash::Iterator colorItr = mNameToColorF.find( colorName ); + + // Return color if found. + if ( colorItr != mNameToColorF.end() ) + return colorItr->value; + + // Warn. + Con::warnf( "Could not find stock color name '%s'.", pStockColorName ); + + // Return default stock color. + return mNameToColorF.find( DEFAULT_UNKNOWN_STOCK_COLOR_NAME )->value; +} + +//----------------------------------------------------------------------------- + +const ColorI& StockColor::colorI( const char* pStockColorName ) +{ + // Sanity! + AssertFatal( pStockColorName != NULL, "Cannot fetch a NULL stock color name." ); + + // Fetch color name. + StringTableEntry colorName = StringTable->insert( pStockColorName ); + + // Find stock color. + typeNameToColorIHash::Iterator colorItr = mNameToColorI.find( colorName ); + + // Return color if found. + if ( colorItr != mNameToColorI.end() ) + return colorItr->value; + + // Warn. + Con::warnf( "Could not find stock color name '%s'.", colorName ); + + // Return default stock color. + return mNameToColorI.find( DEFAULT_UNKNOWN_STOCK_COLOR_NAME )->value; +} + +//----------------------------------------------------------------------------- + +StringTableEntry StockColor::name( const ColorF& color ) +{ + // Find stock color name. + typeColorFToNameHash::Iterator colorNameItr = mColorFToName.find( color ); + + // Return name if found. + if ( colorNameItr != mColorFToName.end() ) + return colorNameItr->value; + + // Return empty string. + return StringTable->EmptyString(); +} + +//----------------------------------------------------------------------------- + +StringTableEntry StockColor::name( const ColorI& color ) +{ + // Find stock color name. + typeColorIToNameHash::Iterator colorNameItr = mColorIToName.find( color ); + + // Return name if found. + if ( colorNameItr != mColorIToName.end() ) + return colorNameItr->value; + + // Return empty string. + return StringTable->EmptyString(); +} + +//----------------------------------------------------------------------------- + +S32 StockColor::getCount( void ) +{ + return sizeof(StockColorTable) / sizeof(StockColorItem); +} + +//----------------------------------------------------------------------------- + +const StockColorItem* StockColor::getColorItem( const S32 index ) +{ + // Fetch stock color count. + const S32 stockColorCount = StockColor::getCount(); + + // Is the stock color index in range? + if ( index < 0 || index >= stockColorCount ) + { + // No, so warn. + Con::warnf("StockColor::getName() - Specified color index '%d' is out of range. Range is 0 to %d.", index, stockColorCount-1 ); + return NULL; + } + + // Return color name. + return &(StockColorTable[index]); +} + +//----------------------------------------------------------------------------- + +ColorF::ColorF( const char* pStockColorName ) +{ + // Set stock color. + *this = StockColor::colorF( pStockColorName ); +} + +//----------------------------------------------------------------------------- + +void ColorF::set( const char* pStockColorName ) +{ + // Set stock color. + *this = StockColor::colorF( pStockColorName ); +} + +//----------------------------------------------------------------------------- + +const ColorF& ColorF::StockColor( const char* pStockColorName ) +{ + return StockColor::colorF( pStockColorName ); +} + +//----------------------------------------------------------------------------- + +StringTableEntry ColorF::StockColor( void ) +{ + // Return stock color name. + return StockColor::name( *this ); +} + +//----------------------------------------------------------------------------- + +ColorI::ColorI( const char* pStockColorName ) +{ + // Set stock color. + *this = StockColor::colorI( pStockColorName ); +} + +//----------------------------------------------------------------------------- + +void ColorI::set( const char* pStockColorName ) +{ + // Set stock color. + *this = StockColor::colorI( pStockColorName ); +} + +//----------------------------------------------------------------------------- + +const ColorI& ColorI::StockColor( const char* pStockColorName ) +{ + return StockColor::colorI( pStockColorName ); +} + +//----------------------------------------------------------------------------- + +StringTableEntry ColorI::StockColor( void ) +{ + // Return stock color name. + return StockColor::name( *this ); +} + +//----------------------------------------------------------------------------- + +ConsoleFunction( getStockColorCount, S32, 1, 1, "() - Gets a count of available stock colors.\n" + "@return A count of available stock colors." ) +{ + return StockColor::getCount(); +} + +//----------------------------------------------------------------------------- + +ConsoleFunction( getStockColorName, const char*, 2, 2, "(stockColorIndex) - Gets the stock color name at the specified index.\n" + "@param stockColorIndex The zero-based index of the stock color name to retrieve.\n" + "@return The stock color name at the specified index or nothing if the string is invalid." ) +{ + // Fetch stock color index. + const S32 stockColorIndex = dAtoi(argv[1]); + + // Fetch the color item. + const StockColorItem* pColorItem = StockColor::getColorItem( stockColorIndex ); + + return pColorItem == NULL ? NULL : pColorItem->getColorName(); +} + +//----------------------------------------------------------------------------- + +ConsoleFunction( isStockColor, bool, 2, 2, "(stockColorName) - Gets whether the specified name is a stock color or not.\n" + "@param stockColorName - The stock color name to test for.\n" + "@return Whether the specified name is a stock color or not.\n" ) +{ + // Fetch stock color name. + const char* pStockColorName = argv[1]; + + // Return whether this is a stock color name or not. + return StockColor::isColor( pStockColorName ); +} + +//----------------------------------------------------------------------------- + +ConsoleFunction( getStockColorF, const char*, 2, 2, "(stockColorName) - Gets a floating-point-based stock color by name.\n" + "@param stockColorName - The stock color name to retrieve.\n" + "@return The stock color that matches the specified color name. Returns nothing if the color name is not found.\n" ) +{ + // Fetch stock color name. + const char* pStockColorName = argv[1]; + + // Return nothing if stock color name is invalid. + if ( !StockColor::isColor( pStockColorName ) ) + return StringTable->EmptyString(); + + // Fetch stock color. + const ColorF& color = StockColor::colorF( pStockColorName ); + + // Format stock color. + char* returnBuffer = Con::getReturnBuffer(256); + dSprintf(returnBuffer, 256, "%g %g %g %g", color.red, color.green, color.blue, color.alpha); + return(returnBuffer); +} + +//----------------------------------------------------------------------------- + +ConsoleFunction( getStockColorI, const char*, 2, 2, "(stockColorName) - Gets a byte-based stock color by name.\n" + "@param stockColorName - The stock color name to retrieve.\n" + "@return The stock color that matches the specified color name. Returns nothing if the color name is not found.\n" ) +{ + // Fetch stock color name. + const char* pStockColorName = argv[1]; + + // Return nothing if stock color name is invalid. + if ( !StockColor::isColor( pStockColorName ) ) + return StringTable->EmptyString(); + + // Fetch stock color. + const ColorI& color = StockColor::colorI( pStockColorName ); + + // Format stock color. + char* returnBuffer = Con::getReturnBuffer(256); + dSprintf(returnBuffer, 256, "%d %d %d %d", color.red, color.green, color.blue, color.alpha); + return(returnBuffer); +} \ No newline at end of file diff --git a/Engine/source/core/color.h b/Engine/source/core/color.h index 7a9206cd3..b0620fc4f 100644 --- a/Engine/source/core/color.h +++ b/Engine/source/core/color.h @@ -49,11 +49,18 @@ class ColorF const F32 in_b, const F32 in_a = 1.0f); + ColorF( const char* pStockColorName ); + void set(const F32 in_r, const F32 in_g, const F32 in_b, const F32 in_a = 1.0f); + void set( const char* pStockColorName ); + + static const ColorF& StockColor( const char* pStockColorName ); + StringTableEntry StockColor( void ); + ColorF& operator*=(const ColorF& in_mul); // Can be useful for lighting ColorF operator*(const ColorF& in_mul) const; ColorF& operator+=(const ColorF& in_rAdd); @@ -123,6 +130,8 @@ class ColorI const U8 in_a = U8(255)); ColorI(const ColorI& in_rCopy, const U8 in_a); + ColorI( const char* pStockColorName ); + void set(const U8 in_r, const U8 in_g, const U8 in_b, @@ -131,6 +140,11 @@ class ColorI void set(const ColorI& in_rCopy, const U8 in_a); + void set( const char* pStockColorName ); + + static const ColorI& StockColor( const char* pStockColorName ); + StringTableEntry StockColor( void ); + ColorI& operator*=(const F32 in_mul); ColorI operator*(const F32 in_mul) const; @@ -175,6 +189,53 @@ class ColorI static const ColorI BLUE; }; +//----------------------------------------------------------------------------- + +class StockColorItem +{ +private: + StockColorItem() {} + +public: + StockColorItem( const char* pName, const U8 red, const U8 green, const U8 blue, const U8 alpha = 255 ) + { + // Sanity! + AssertFatal( pName != NULL, "Stock color name cannot be NULL." ); + + // Set stock color. + // NOTE:- We'll use the char pointer here. We can yet use the string-table unfortunately. + mColorName = pName; + mColorI.set( red, green, blue, alpha ); + mColorF = mColorI; + } + + inline const char* getColorName( void ) const { return mColorName; } + inline const ColorF& getColorF( void ) const { return mColorF; } + inline const ColorI& getColorI( void ) const { return mColorI; } + + const char* mColorName; + ColorF mColorF; + ColorI mColorI; +}; + +//----------------------------------------------------------------------------- + +class StockColor +{ +public: + static bool isColor( const char* pStockColorName ); + static const ColorF& colorF( const char* pStockColorName ); + static const ColorI& colorI( const char* pStockColorName ); + static StringTableEntry name( const ColorF& color ); + static StringTableEntry name( const ColorI& color ); + + static S32 getCount( void ); + static const StockColorItem* getColorItem( const S32 index ); + + static void create( void ); + static void destroy( void ); +}; + //------------------------------------------------------------------------------ //-------------------------------------- INLINES (ColorF) // diff --git a/Engine/source/core/fileio.h b/Engine/source/core/fileio.h index 31b367033..a7deb1078 100644 --- a/Engine/source/core/fileio.h +++ b/Engine/source/core/fileio.h @@ -31,7 +31,7 @@ class File { public: /// What is the status of our file handle? - enum Status + enum FileStatus { Ok = 0, ///< Ok! IOError, ///< Read or Write error @@ -59,7 +59,7 @@ public: private: void *handle; ///< Pointer to the file handle. - Status currentStatus; ///< Current status of the file (Ok, IOError, etc.). + FileStatus currentStatus; ///< Current status of the file (Ok, IOError, etc.). U32 capability; ///< Keeps track of file capabilities. File(const File&); ///< This is here to disable the copy constructor. @@ -72,7 +72,7 @@ public: /// Opens a file for access using the specified AccessMode /// /// @returns The status of the file - Status open(const char *filename, const AccessMode openMode); + FileStatus open(const char *filename, const AccessMode openMode); /// Gets the current position in the file /// @@ -99,7 +99,7 @@ public: /// @endcode /// /// @returns The status of the file - Status setPosition(S32 position, bool absolutePos = true); + FileStatus setPosition(S32 position, bool absolutePos = true); /// Returns the size of the file U32 getSize() const; @@ -107,25 +107,25 @@ public: /// Make sure everything that's supposed to be written to the file gets written. /// /// @returns The status of the file. - Status flush(); + FileStatus flush(); /// Closes the file /// /// @returns The status of the file. - Status close(); + FileStatus close(); /// Gets the status of the file - Status getStatus() const; + FileStatus getStatus() const; /// Reads "size" bytes from the file, and dumps data into "dst". /// The number of actual bytes read is returned in bytesRead /// @returns The status of the file - Status read(U32 size, char *dst, U32 *bytesRead = NULL); + FileStatus read(U32 size, char *dst, U32 *bytesRead = NULL); /// Writes "size" bytes into the file from the pointer "src". /// The number of actual bytes written is returned in bytesWritten /// @returns The status of the file - Status write(U32 size, const char *src, U32 *bytesWritten = NULL); + FileStatus write(U32 size, const char *src, U32 *bytesWritten = NULL); /// Returns whether or not this file is capable of the given function. bool hasCapability(Capability cap) const; @@ -133,8 +133,8 @@ public: const void* getHandle() { return handle; } protected: - Status setStatus(); ///< Called after error encountered. - Status setStatus(Status status); ///< Setter for the current status. + FileStatus setStatus(); ///< Called after error encountered. + FileStatus setStatus(FileStatus status); ///< Setter for the current status. }; #endif // _FILE_IO_H_ diff --git a/Engine/source/core/frameAllocator.h b/Engine/source/core/frameAllocator.h index 6abdd13cf..86884085c 100644 --- a/Engine/source/core/frameAllocator.h +++ b/Engine/source/core/frameAllocator.h @@ -234,7 +234,7 @@ public: mWaterMark = FrameAllocator::getWaterMark(); mMemory = reinterpret_cast( FrameAllocator::alloc( sizeof( T ) * count ) ); - for( int i = 0; i < mNumObjectsInMemory; i++ ) + for( S32 i = 0; i < mNumObjectsInMemory; i++ ) constructInPlace( &mMemory[i] ); } @@ -242,7 +242,7 @@ public: ~FrameTemp() { // Call destructor - for( int i = 0; i < mNumObjectsInMemory; i++ ) + for( S32 i = 0; i < mNumObjectsInMemory; i++ ) destructInPlace( &mMemory[i] ); FrameAllocator::setWaterMark( mWaterMark ); diff --git a/Engine/source/core/memVolume.cpp b/Engine/source/core/memVolume.cpp index 284e753fb..56d53174f 100644 --- a/Engine/source/core/memVolume.cpp +++ b/Engine/source/core/memVolume.cpp @@ -324,7 +324,7 @@ namespace Torque return mFileData->mPath; } - FileNode::Status MemFile::getStatus() const + FileNode::NodeStatus MemFile::getStatus() const { return mStatus; } @@ -502,7 +502,7 @@ namespace Torque return mDirectoryData->getAttributes(attr); } - FileNode::Status MemDirectory::getStatus() const + FileNode::NodeStatus MemDirectory::getStatus() const { return mStatus; } diff --git a/Engine/source/core/memVolume.h b/Engine/source/core/memVolume.h index 18e4641fb..0a20fa84f 100644 --- a/Engine/source/core/memVolume.h +++ b/Engine/source/core/memVolume.h @@ -74,7 +74,7 @@ namespace Torque virtual ~MemFile(); Path getName() const; - Status getStatus() const; + NodeStatus getStatus() const; bool getAttributes(Attributes*); U32 getPosition(); @@ -91,7 +91,7 @@ namespace Torque MemFileSystem* mFileSystem; MemFileData* mFileData; - Status mStatus; + NodeStatus mStatus; U32 mCurrentPos; bool _updateInfo(); @@ -108,7 +108,7 @@ namespace Torque ~MemDirectory(); Path getName() const; - Status getStatus() const; + NodeStatus getStatus() const; bool getAttributes(Attributes*); bool open(); @@ -122,7 +122,7 @@ namespace Torque U32 calculateChecksum(); - Status mStatus; + NodeStatus mStatus; U32 mSearchIndex; }; diff --git a/Engine/source/core/ogg/oggInputStream.cpp b/Engine/source/core/ogg/oggInputStream.cpp index 7704f3152..e0777e6ad 100644 --- a/Engine/source/core/ogg/oggInputStream.cpp +++ b/Engine/source/core/ogg/oggInputStream.cpp @@ -55,7 +55,7 @@ bool OggDecoder::_readNextPacket( ogg_packet* packet ) while( 1 ) { - int result = ogg_stream_packetout( &mOggStreamState, packet ); + S32 result = ogg_stream_packetout( &mOggStreamState, packet ); if( result == 0 ) { if( !mOggStream->_requestData() ) diff --git a/Engine/source/core/ogg/oggTheoraDecoder.cpp b/Engine/source/core/ogg/oggTheoraDecoder.cpp index b0c62ea5f..1259c3afb 100644 --- a/Engine/source/core/ogg/oggTheoraDecoder.cpp +++ b/Engine/source/core/ogg/oggTheoraDecoder.cpp @@ -169,7 +169,7 @@ bool OggTheoraDecoder::_init() break; } - int result = th_decode_headerin( &mTheoraInfo, &mTheoraComment, &mTheoraSetup, &nextPacket ); + S32 result = th_decode_headerin( &mTheoraInfo, &mTheoraComment, &mTheoraSetup, &nextPacket ); if( result < 0 ) { haveTheoraHeader = false; diff --git a/Engine/source/core/ogg/oggVorbisDecoder.cpp b/Engine/source/core/ogg/oggVorbisDecoder.cpp index 3df624df3..885c3fd53 100644 --- a/Engine/source/core/ogg/oggVorbisDecoder.cpp +++ b/Engine/source/core/ogg/oggVorbisDecoder.cpp @@ -89,7 +89,7 @@ bool OggVorbisDecoder::_init() break; } - int result = vorbis_synthesis_headerin( &mVorbisInfo, &mVorbisComment, &nextPacket ); + S32 result = vorbis_synthesis_headerin( &mVorbisInfo, &mVorbisComment, &nextPacket ); if( result != 0 ) { haveVorbisHeader = false; diff --git a/Engine/source/core/stream/stream.cpp b/Engine/source/core/stream/stream.cpp index a11d40010..873bdeba6 100644 --- a/Engine/source/core/stream/stream.cpp +++ b/Engine/source/core/stream/stream.cpp @@ -91,7 +91,7 @@ Stream::Stream() { } -const char* Stream::getStatusString(const Status in_status) +const char* Stream::getStatusString(const StreamStatus in_status) { switch (in_status) { case Ok: diff --git a/Engine/source/core/stream/stream.h b/Engine/source/core/stream/stream.h index c4d17a791..c50acb659 100644 --- a/Engine/source/core/stream/stream.h +++ b/Engine/source/core/stream/stream.h @@ -57,7 +57,7 @@ class Stream // Public structs and enumerations... public: /// Status constants for the stream - enum Status { + enum StreamStatus { Ok = 0, ///< Ok! IOError, ///< Read or Write error EOS, ///< End of Stream reached (mostly for reads) @@ -74,20 +74,20 @@ public: // Accessible only through inline accessors private: - Status m_streamStatus; + StreamStatus m_streamStatus; // Derived accessible data modifiers... protected: - void setStatus(const Status in_newStatus) { m_streamStatus = in_newStatus; } + void setStatus(const StreamStatus in_newStatus) { m_streamStatus = in_newStatus; } public: Stream(); virtual ~Stream() {} /// Gets the status of the stream - Stream::Status getStatus() const { return m_streamStatus; } + Stream::StreamStatus getStatus() const { return m_streamStatus; } /// Gets a printable string form of the status - static const char* getStatusString(const Status in_status); + static const char* getStatusString(const StreamStatus in_status); // Derived classes must override these... protected: diff --git a/Engine/source/core/stringBuffer.cpp b/Engine/source/core/stringBuffer.cpp index be2840153..fd16d159b 100644 --- a/Engine/source/core/stringBuffer.cpp +++ b/Engine/source/core/stringBuffer.cpp @@ -438,7 +438,7 @@ void StringBufferManager::updateStats() request8 = 0; request16 = 0; U32 nstrings = strings.size(); - for(int i=0; i < nstrings; i++) + for(S32 i=0; i < nstrings; i++) { request8 += strings[i]->rc->requestCount8; request16 += strings[i]->rc->requestCount16; @@ -459,7 +459,7 @@ void StringBufferManager::dumpAllStrings() U32 nstrings = strings.size(); Con::printf("===== String Manager: All Strings ====="); Con::printf(" utf8 | utf16 | string"); - for(int i=0; i < nstrings; i++) + for(S32 i=0; i < nstrings; i++) { UTF8* tmp = strings[i]->createCopy8(); strings[i]->rc->requestCount8--; diff --git a/Engine/source/core/stringTable.cpp b/Engine/source/core/stringTable.cpp index 3c2ff86f8..e94ca50e7 100644 --- a/Engine/source/core/stringTable.cpp +++ b/Engine/source/core/stringTable.cpp @@ -195,8 +195,11 @@ StringTableEntry _StringTable::lookupn(const char* val, S32 len, const bool cas } //-------------------------------------- -void _StringTable::resize(const U32 newSize) +void _StringTable::resize(const U32 _newSize) { + /// avoid a possible 0 division + const U32 newSize = _newSize ? _newSize : 1; + Node *head = NULL, *walk, *temp; U32 i; // reverse individual bucket lists diff --git a/Engine/source/core/strings/findMatch.cpp b/Engine/source/core/strings/findMatch.cpp index c41dd9230..1bb35128e 100644 --- a/Engine/source/core/strings/findMatch.cpp +++ b/Engine/source/core/strings/findMatch.cpp @@ -140,7 +140,7 @@ bool FindMatch::isMatch( const char *exp, const char *str, bool caseSensitive ) bool FindMatch::isMatchMultipleExprs( const char *exps, const char *str, bool caseSensitive ) { char *tok = 0; - int len = dStrlen(exps); + S32 len = dStrlen(exps); char *e = new char[len+1]; dStrcpy(e,exps); diff --git a/Engine/source/core/strings/stringFunctions.cpp b/Engine/source/core/strings/stringFunctions.cpp index 25c7e22b1..63377cfd4 100644 --- a/Engine/source/core/strings/stringFunctions.cpp +++ b/Engine/source/core/strings/stringFunctions.cpp @@ -27,7 +27,7 @@ #include "platform/platform.h" -#if defined(TORQUE_OS_WIN32) || defined(TORQUE_OS_XBOX) || defined(TORQUE_OS_XENON) +#if defined(TORQUE_OS_WIN) || defined(TORQUE_OS_XBOX) || defined(TORQUE_OS_XENON) // This standard function is not defined when compiling with VC7... #define vsnprintf _vsnprintf #endif @@ -97,10 +97,10 @@ nat_toupper( nat_char a ) -static int +static S32 compare_right(const nat_char* a, const nat_char* b) { - int bias = 0; + S32 bias = 0; /* The longest run of digits wins. That aside, the greatest value wins, but we can't know that it will until we've scanned @@ -108,7 +108,7 @@ compare_right(const nat_char* a, const nat_char* b) remember it in BIAS. */ for (;; a++, b++) { if (!nat_isdigit(*a) && !nat_isdigit(*b)) - return bias; + break; else if (!nat_isdigit(*a)) return -1; else if (!nat_isdigit(*b)) @@ -123,7 +123,7 @@ compare_right(const nat_char* a, const nat_char* b) return bias; } - return 0; + return bias; } @@ -134,7 +134,7 @@ compare_left(const nat_char* a, const nat_char* b) different value wins. */ for (;; a++, b++) { if (!nat_isdigit(*a) && !nat_isdigit(*b)) - return 0; + break; else if (!nat_isdigit(*a)) return -1; else if (!nat_isdigit(*b)) @@ -149,11 +149,11 @@ compare_left(const nat_char* a, const nat_char* b) } -static int strnatcmp0(const nat_char* a, const nat_char* b, int fold_case) +static S32 strnatcmp0(const nat_char* a, const nat_char* b, S32 fold_case) { - int ai, bi; + S32 ai, bi; nat_char ca, cb; - int fractional, result; + S32 fractional, result; ai = bi = 0; while (1) { @@ -200,13 +200,13 @@ static int strnatcmp0(const nat_char* a, const nat_char* b, int fold_case) } -int dStrnatcmp(const nat_char* a, const nat_char* b) { +S32 dStrnatcmp(const nat_char* a, const nat_char* b) { return strnatcmp0(a, b, 0); } /* Compare, recognizing numeric string and ignoring case. */ -int dStrnatcasecmp(const nat_char* a, const nat_char* b) { +S32 dStrnatcasecmp(const nat_char* a, const nat_char* b) { return strnatcmp0(a, b, 1); } @@ -328,12 +328,12 @@ char* dStrcpyl(char *dst, dsize_t dstSize, ...) } -int dStrcmp( const UTF16 *str1, const UTF16 *str2) +S32 dStrcmp( const UTF16 *str1, const UTF16 *str2) { -#if defined(TORQUE_OS_WIN32) || defined(TORQUE_OS_XBOX) || defined(TORQUE_OS_XENON) +#if defined(TORQUE_OS_WIN) || defined(TORQUE_OS_XBOX) || defined(TORQUE_OS_XENON) return wcscmp( reinterpret_cast( str1 ), reinterpret_cast( str2 ) ); #else - int ret; + S32 ret; const UTF16 *a, *b; a = str1; b = str2; @@ -347,7 +347,7 @@ int dStrcmp( const UTF16 *str1, const UTF16 *str2) char* dStrupr(char *str) { -#if defined(TORQUE_OS_WIN32) || defined(TORQUE_OS_XBOX) || defined(TORQUE_OS_XENON) +#if defined(TORQUE_OS_WIN) || defined(TORQUE_OS_XBOX) || defined(TORQUE_OS_XENON) return _strupr(str); #else if (str == NULL) @@ -365,7 +365,7 @@ char* dStrupr(char *str) char* dStrlwr(char *str) { -#if defined(TORQUE_OS_WIN32) || defined(TORQUE_OS_XBOX) || defined(TORQUE_OS_XENON) +#if defined(TORQUE_OS_WIN) || defined(TORQUE_OS_XBOX) || defined(TORQUE_OS_XENON) return _strlwr(str); #else if (str == NULL) @@ -421,7 +421,7 @@ S32 dVsprintf(char *buffer, U32 bufferSize, const char *format, void *arglist) S32 dSscanf(const char *buffer, const char *format, ...) { -#if defined(TORQUE_OS_WIN32) || defined(TORQUE_OS_XBOX) || defined(TORQUE_OS_XENON) +#if defined(TORQUE_OS_WIN) || defined(TORQUE_OS_XBOX) || defined(TORQUE_OS_XENON) va_list args; va_start(args, format); diff --git a/Engine/source/core/strings/stringFunctions.h b/Engine/source/core/strings/stringFunctions.h index 34af03b9b..e211454d0 100644 --- a/Engine/source/core/strings/stringFunctions.h +++ b/Engine/source/core/strings/stringFunctions.h @@ -31,10 +31,12 @@ #include "platform/types.h" #endif -#if defined(TORQUE_OS_WIN32) || defined(TORQUE_OS_XBOX) || defined(TORQUE_OS_XENON) +#if defined(TORQUE_OS_WIN) || defined(TORQUE_OS_XBOX) || defined(TORQUE_OS_XENON) // These standard functions are not defined on Win32 and other Microsoft platforms... #define strcasecmp _stricmp #define strncasecmp _strnicmp +#endif +#if (_MSC_VER < 1800) && (defined(TORQUE_OS_WIN) || defined(TORQUE_OS_XBOX) || defined(TORQUE_OS_XENON)) #define strtof (float)strtod #endif @@ -52,22 +54,22 @@ inline char *dStrncat(char *dst, const char *src, dsize_t len) return strncat(dst,src,len); } -inline int dStrcmp(const char *str1, const char *str2) +inline S32 dStrcmp(const char *str1, const char *str2) { return strcmp(str1, str2); } -inline int dStrncmp(const char *str1, const char *str2, dsize_t len) +inline S32 dStrncmp(const char *str1, const char *str2, dsize_t len) { return strncmp(str1, str2, len); } -inline int dStricmp(const char *str1, const char *str2) +inline S32 dStricmp(const char *str1, const char *str2) { return strcasecmp( str1, str2 ); } -inline int dStrnicmp(const char *str1, const char *str2, dsize_t len) +inline S32 dStrnicmp(const char *str1, const char *str2, dsize_t len) { return strncasecmp( str1, str2, len ); } @@ -87,22 +89,22 @@ inline dsize_t dStrlen(const char *str) return strlen(str); } -inline char *dStrchr(char *str, int c) +inline char *dStrchr(char *str, S32 c) { return strchr(str,c); } -inline const char *dStrchr(const char *str, int c) +inline const char *dStrchr(const char *str, S32 c) { return strchr(str,c); } -inline char *dStrrchr(char *str, int c) +inline char *dStrrchr(char *str, S32 c) { return strrchr(str,c); } -inline const char *dStrrchr(const char *str, int c) +inline const char *dStrrchr(const char *str, S32 c) { return strrchr(str,c); } @@ -198,9 +200,9 @@ extern char *dStrlwr(char *str); extern char* dStrichr( char* str, char ch ); extern const char* dStrichr( const char* str, char ch ); -extern int dStrcmp(const UTF16 *str1, const UTF16 *str2); -extern int dStrnatcmp( const char* str1, const char* str2 ); -extern int dStrnatcasecmp( const char* str1, const char* str2 ); +extern S32 dStrcmp(const UTF16 *str1, const UTF16 *str2); +extern S32 dStrnatcmp( const char* str1, const char* str2 ); +extern S32 dStrnatcasecmp( const char* str1, const char* str2 ); inline bool dAtob(const char *str) { @@ -219,9 +221,9 @@ char* dStripPath(const char* filename); // standard I/O functions [defined in platformString.cpp] extern void dPrintf(const char *format, ...); -extern int dVprintf(const char *format, void *arglist); -extern int dSprintf(char *buffer, U32 bufferSize, const char *format, ...); -extern int dVsprintf(char *buffer, U32 bufferSize, const char *format, void *arglist); -extern int dSscanf(const char *buffer, const char *format, ...); +extern S32 dVprintf(const char *format, void *arglist); +extern S32 dSprintf(char *buffer, U32 bufferSize, const char *format, ...); +extern S32 dVsprintf(char *buffer, U32 bufferSize, const char *format, void *arglist); +extern S32 dSscanf(const char *buffer, const char *format, ...); #endif diff --git a/Engine/source/core/strings/unicode.cpp b/Engine/source/core/strings/unicode.cpp index 2edea59e8..b6c915e05 100644 --- a/Engine/source/core/strings/unicode.cpp +++ b/Engine/source/core/strings/unicode.cpp @@ -311,7 +311,7 @@ UTF32 oneUTF8toUTF32( const UTF8* codepoint, U32 *unitsWalked) U8 codeunit; // check the first byte ( a.k.a. codeunit ) . - unsigned char c = codepoint[0]; + U8 c = codepoint[0]; c = c >> 1; expectedByteCount = sgFirstByteLUT[c]; if(expectedByteCount > 0) // 0 or negative is illegal to start with @@ -469,7 +469,7 @@ U32 oneUTF32toUTF8(const UTF32 codepoint, UTF8 *threeByteCodeunitBuf) U8 marker = ( ~mask << 1); // 1000 0000 // Process the low order bytes, shifting the codepoint down 6 each pass. - for( int i = bytecount-1; i > 0; i--) + for( S32 i = bytecount-1; i > 0; i--) { threeByteCodeunitBuf[i] = marker | (working & mask); working >>= 6; diff --git a/Engine/source/core/tagDictionary.cpp b/Engine/source/core/tagDictionary.cpp index e31bb5e29..a25ed4f5b 100644 --- a/Engine/source/core/tagDictionary.cpp +++ b/Engine/source/core/tagDictionary.cpp @@ -308,7 +308,7 @@ bool TagDictionary::match(const char* pattern, const char* str) //------------------------------------------------------------------------------ -static int QSORT_CALLBACK idCompare(const void *in_p1, const void *in_p2) +static S32 QSORT_CALLBACK idCompare(const void *in_p1, const void *in_p2) { return *((S32 *) in_p1) - *((S32 *) in_p2); } diff --git a/Engine/source/core/threadStatic.cpp b/Engine/source/core/threadStatic.cpp index 511db4259..aff06730f 100644 --- a/Engine/source/core/threadStatic.cpp +++ b/Engine/source/core/threadStatic.cpp @@ -103,7 +103,7 @@ TorqueThreadStaticListHandle _TorqueThreadStaticReg::spawnThreadStaticsInstance( // Copy mThreadStaticInstances[0] (master copy) into new memory, and // pass it back. - for( int i = 0; i < getThreadStaticListVector()[0].size(); i++ ) + for( S32 i = 0; i < getThreadStaticListVector()[0].size(); i++ ) { getThreadStaticListVector().last().push_back( getThreadStaticListVector()[0][i]->_createInstance() ); } diff --git a/Engine/source/core/threadStatic.h b/Engine/source/core/threadStatic.h index 716d590b9..2f5a16cbf 100644 --- a/Engine/source/core/threadStatic.h +++ b/Engine/source/core/threadStatic.h @@ -47,6 +47,7 @@ public: : mHitCount( 0 ) #endif { }; + virtual ~_TorqueThreadStatic() { } static const U32 getListIndex(){ return mListIndex; } diff --git a/Engine/source/core/util/FastDelegate.h b/Engine/source/core/util/FastDelegate.h index b977a6a12..f2494d475 100644 --- a/Engine/source/core/util/FastDelegate.h +++ b/Engine/source/core/util/FastDelegate.h @@ -174,7 +174,7 @@ inline OutputClass horrible_cast(const InputClass input){ // Cause a compile-time error if in, out and u are not the same size. // If the compile fails here, it means the compiler has peculiar // unions which would prevent the cast from working. - typedef int ERROR_CantUseHorrible_cast[sizeof(InputClass)==sizeof(u) + typedef S32 ERROR_CantUseHorrible_cast[sizeof(InputClass)==sizeof(u) && sizeof(InputClass)==sizeof(OutputClass) ? 1 : -1]; u.in = input; return u.out; @@ -270,7 +270,7 @@ struct VoidToDefaultVoid { typedef DefaultVoid type; }; #endif // The size of a single inheritance member function pointer. -const int SINGLE_MEMFUNCPTR_SIZE = sizeof(void (GenericClass::*)()); +const S32 SINGLE_MEMFUNCPTR_SIZE = sizeof(void (GenericClass::*)()); // SimplifyMemFunc< >::Convert() // @@ -284,7 +284,7 @@ const int SINGLE_MEMFUNCPTR_SIZE = sizeof(void (GenericClass::*)()); // template specialisation, I use full specialisation of a wrapper struct. // general case -- don't know how to convert it. Force a compile failure -template +template struct SimplifyMemFunc { template inline static GenericClass *Convert(X *pthis, XFuncType function_to_bind, @@ -344,11 +344,11 @@ struct SimplifyMemFunc< SINGLE_MEMFUNCPTR_SIZE + sizeof(int) > { XFuncType func; struct { GenericMemFuncType funcaddress; // points to the actual member function - int delta; // #BYTES to be added to the 'this' pointer + S32 delta; // #BYTES to be added to the 'this' pointer }s; } u; // Check that the horrible_cast will work - typedef int ERROR_CantUsehorrible_cast[sizeof(function_to_bind)==sizeof(u.s)? 1 : -1]; + typedef S32 ERROR_CantUsehorrible_cast[sizeof(function_to_bind)==sizeof(u.s)? 1 : -1]; u.func = function_to_bind; bound_func = u.s.funcaddress; return reinterpret_cast(reinterpret_cast(pthis) + u.s.delta); @@ -367,8 +367,8 @@ struct SimplifyMemFunc< SINGLE_MEMFUNCPTR_SIZE + sizeof(int) > { // is internally defined as: struct MicrosoftVirtualMFP { void (GenericClass::*codeptr)(); // points to the actual member function - int delta; // #bytes to be added to the 'this' pointer - int vtable_index; // or 0 if no virtual inheritance + S32 delta; // #bytes to be added to the 'this' pointer + S32 vtable_index; // or 0 if no virtual inheritance }; // The CRUCIAL feature of Microsoft/Intel MFPs which we exploit is that the // m_codeptr member is *always* called, regardless of the values of the other @@ -405,7 +405,7 @@ struct SimplifyMemFunc MicrosoftVirtualMFP s; } u2; // Check that the horrible_cast<>s will work - typedef int ERROR_CantUsehorrible_cast[sizeof(function_to_bind)==sizeof(u.s) + typedef S32 ERROR_CantUsehorrible_cast[sizeof(function_to_bind)==sizeof(u.s) && sizeof(function_to_bind)==sizeof(u.ProbeFunc) && sizeof(u2.virtfunc)==sizeof(u2.s) ? 1 : -1]; // Unfortunately, taking the address of a MF prevents it from being inlined, so @@ -477,24 +477,24 @@ struct SimplifyMemFunc // is internally defined as: struct { GenericMemFuncType m_funcaddress; // points to the actual member function - int delta; // #bytes to be added to the 'this' pointer - int vtordisp; // #bytes to add to 'this' to find the vtable - int vtable_index; // or 0 if no virtual inheritance + S32 delta; // #bytes to be added to the 'this' pointer + S32 vtordisp; // #bytes to add to 'this' to find the vtable + S32 vtable_index; // or 0 if no virtual inheritance } s; } u; // Check that the horrible_cast will work - typedef int ERROR_CantUsehorrible_cast[sizeof(XFuncType)==sizeof(u.s)? 1 : -1]; + typedef S32 ERROR_CantUsehorrible_cast[sizeof(XFuncType)==sizeof(u.s)? 1 : -1]; u.func = function_to_bind; bound_func = u.s.funcaddress; - int virtual_delta = 0; + S32 virtual_delta = 0; if (u.s.vtable_index) { // Virtual inheritance is used // First, get to the vtable. // It is 'vtordisp' bytes from the start of the class. - const int * vtable = *reinterpret_cast( + const S32 * vtable = *reinterpret_cast( reinterpret_cast(pthis) + u.s.vtordisp ); // 'vtable_index' tells us where in the table we should be looking. - virtual_delta = u.s.vtordisp + *reinterpret_cast( + virtual_delta = u.s.vtordisp + *reinterpret_cast( reinterpret_cast(vtable) + u.s.vtable_index); } // The int at 'virtual_delta' gives us the amount to add to 'this'. @@ -777,7 +777,7 @@ public: // Ensure that there's a compilation failure if function pointers // and data pointers have different sizes. // If you get this error, you need to #undef FASTDELEGATE_USESTATICFUNCTIONHACK. - typedef int ERROR_CantUseEvilMethod[sizeof(GenericClass *)==sizeof(function_to_bind) ? 1 : -1]; + typedef S32 ERROR_CantUseEvilMethod[sizeof(GenericClass *)==sizeof(function_to_bind) ? 1 : -1]; m_pthis = horrible_cast(function_to_bind); // MSVC, SunC++ and DMC accept the following (non-standard) code: // m_pthis = static_cast(static_cast(function_to_bind)); @@ -792,7 +792,7 @@ public: // Ensure that there's a compilation failure if function pointers // and data pointers have different sizes. // If you get this error, you need to #undef FASTDELEGATE_USESTATICFUNCTIONHACK. - typedef int ERROR_CantUseEvilMethod[sizeof(UnvoidStaticFuncPtr)==sizeof(this) ? 1 : -1]; + typedef S32 ERROR_CantUseEvilMethod[sizeof(UnvoidStaticFuncPtr)==sizeof(this) ? 1 : -1]; return horrible_cast(this); } #endif // !defined(FASTDELEGATE_USESTATICFUNCTIONHACK) @@ -906,7 +906,7 @@ public: // Implicit conversion to "bool" using the safe_bool idiom private: typedef struct SafeBoolStruct { - int a_data_pointer_to_this_is_0_on_buggy_compilers; + S32 a_data_pointer_to_this_is_0_on_buggy_compilers; StaticFunctionPtr m_nonzero; } UselessTypedef; typedef StaticFunctionPtr SafeBoolStruct::*unspecified_bool_type; @@ -991,7 +991,7 @@ public: // Implicit conversion to "bool" using the safe_bool idiom private: typedef struct SafeBoolStruct { - int a_data_pointer_to_this_is_0_on_buggy_compilers; + S32 a_data_pointer_to_this_is_0_on_buggy_compilers; StaticFunctionPtr m_nonzero; } UselessTypedef; typedef StaticFunctionPtr SafeBoolStruct::*unspecified_bool_type; @@ -1076,7 +1076,7 @@ public: // Implicit conversion to "bool" using the safe_bool idiom private: typedef struct SafeBoolStruct { - int a_data_pointer_to_this_is_0_on_buggy_compilers; + S32 a_data_pointer_to_this_is_0_on_buggy_compilers; StaticFunctionPtr m_nonzero; } UselessTypedef; typedef StaticFunctionPtr SafeBoolStruct::*unspecified_bool_type; @@ -1161,7 +1161,7 @@ public: // Implicit conversion to "bool" using the safe_bool idiom private: typedef struct SafeBoolStruct { - int a_data_pointer_to_this_is_0_on_buggy_compilers; + S32 a_data_pointer_to_this_is_0_on_buggy_compilers; StaticFunctionPtr m_nonzero; } UselessTypedef; typedef StaticFunctionPtr SafeBoolStruct::*unspecified_bool_type; @@ -1246,7 +1246,7 @@ public: // Implicit conversion to "bool" using the safe_bool idiom private: typedef struct SafeBoolStruct { - int a_data_pointer_to_this_is_0_on_buggy_compilers; + S32 a_data_pointer_to_this_is_0_on_buggy_compilers; StaticFunctionPtr m_nonzero; } UselessTypedef; typedef StaticFunctionPtr SafeBoolStruct::*unspecified_bool_type; @@ -1331,7 +1331,7 @@ public: // Implicit conversion to "bool" using the safe_bool idiom private: typedef struct SafeBoolStruct { - int a_data_pointer_to_this_is_0_on_buggy_compilers; + S32 a_data_pointer_to_this_is_0_on_buggy_compilers; StaticFunctionPtr m_nonzero; } UselessTypedef; typedef StaticFunctionPtr SafeBoolStruct::*unspecified_bool_type; @@ -1416,7 +1416,7 @@ public: // Implicit conversion to "bool" using the safe_bool idiom private: typedef struct SafeBoolStruct { - int a_data_pointer_to_this_is_0_on_buggy_compilers; + S32 a_data_pointer_to_this_is_0_on_buggy_compilers; StaticFunctionPtr m_nonzero; } UselessTypedef; typedef StaticFunctionPtr SafeBoolStruct::*unspecified_bool_type; @@ -1501,7 +1501,7 @@ public: // Implicit conversion to "bool" using the safe_bool idiom private: typedef struct SafeBoolStruct { - int a_data_pointer_to_this_is_0_on_buggy_compilers; + S32 a_data_pointer_to_this_is_0_on_buggy_compilers; StaticFunctionPtr m_nonzero; } UselessTypedef; typedef StaticFunctionPtr SafeBoolStruct::*unspecified_bool_type; @@ -1586,7 +1586,7 @@ public: // Implicit conversion to "bool" using the safe_bool idiom private: typedef struct SafeBoolStruct { - int a_data_pointer_to_this_is_0_on_buggy_compilers; + S32 a_data_pointer_to_this_is_0_on_buggy_compilers; StaticFunctionPtr m_nonzero; } UselessTypedef; typedef StaticFunctionPtr SafeBoolStruct::*unspecified_bool_type; @@ -1671,7 +1671,7 @@ public: // Implicit conversion to "bool" using the safe_bool idiom private: typedef struct SafeBoolStruct { - int a_data_pointer_to_this_is_0_on_buggy_compilers; + S32 a_data_pointer_to_this_is_0_on_buggy_compilers; StaticFunctionPtr m_nonzero; } UselessTypedef; typedef StaticFunctionPtr SafeBoolStruct::*unspecified_bool_type; @@ -1756,7 +1756,7 @@ public: // Implicit conversion to "bool" using the safe_bool idiom private: typedef struct SafeBoolStruct { - int a_data_pointer_to_this_is_0_on_buggy_compilers; + S32 a_data_pointer_to_this_is_0_on_buggy_compilers; StaticFunctionPtr m_nonzero; } UselessTypedef; typedef StaticFunctionPtr SafeBoolStruct::*unspecified_bool_type; @@ -1841,7 +1841,7 @@ public: // Implicit conversion to "bool" using the safe_bool idiom private: typedef struct SafeBoolStruct { - int a_data_pointer_to_this_is_0_on_buggy_compilers; + S32 a_data_pointer_to_this_is_0_on_buggy_compilers; StaticFunctionPtr m_nonzero; } UselessTypedef; typedef StaticFunctionPtr SafeBoolStruct::*unspecified_bool_type; diff --git a/Engine/source/core/util/delegate.h b/Engine/source/core/util/delegate.h index 6dbf1f668..0b1e51ec5 100644 --- a/Engine/source/core/util/delegate.h +++ b/Engine/source/core/util/delegate.h @@ -55,7 +55,7 @@ public: } protected: - int mOffset; + S32 mOffset; }; #endif // _UTIL_DELEGATE_H_ \ No newline at end of file diff --git a/Engine/source/core/util/dxt5nmSwizzle.h b/Engine/source/core/util/dxt5nmSwizzle.h index 555a21eee..58acbac66 100644 --- a/Engine/source/core/util/dxt5nmSwizzle.h +++ b/Engine/source/core/util/dxt5nmSwizzle.h @@ -37,7 +37,7 @@ public: volatile U8 *u8Mem = reinterpret_cast( memory ); - for( int i = 0; i < size >> 2; i++ ) + for( S32 i = 0; i < size >> 2; i++ ) { // g = garbage byte // Input: [X|Y|Z|g] (rgba) @@ -57,7 +57,7 @@ public: volatile const U8 *srcU8 = reinterpret_cast( source ); volatile U8 *dstU8 = reinterpret_cast( destination ); - for( int i = 0; i < size >> 2; i++ ) + for( S32 i = 0; i < size >> 2; i++ ) { // g = garbage byte // Input: [X|Y|Z|g] (rgba) @@ -85,13 +85,13 @@ public: virtual void ToBuffer( void *destination, const void *source, const dsize_t size ) const { AssertFatal( size % 3 == 0, "Bad buffer size for DXT5nm Swizzle" ); - const int pixels = size / 3; + const S32 pixels = size / 3; volatile const U8 *srcU8 = reinterpret_cast( source ); volatile U8 *dstU8 = reinterpret_cast( destination ); // destination better damn well be the right size - for( int i = 0; i < pixels; i++ ) + for( S32 i = 0; i < pixels; i++ ) { // g = garbage byte // Input: [X|Y|Z|g] (rgba) diff --git a/Engine/source/core/util/journal/process.h b/Engine/source/core/util/journal/process.h index 19040e747..4d21898d9 100644 --- a/Engine/source/core/util/journal/process.h +++ b/Engine/source/core/util/journal/process.h @@ -96,6 +96,11 @@ public: get()._signalProcess.notify(del,order); } + static void notify(SignalSlot &slot, F32 order = PROCESS_DEFAULT_ORDER) + { + get()._signalProcess.notify(slot,order); + } + template static void notify(T func, F32 order = PROCESS_DEFAULT_ORDER) { diff --git a/Engine/source/core/util/md5.cpp b/Engine/source/core/util/md5.cpp index 8358d7655..41503cb86 100644 --- a/Engine/source/core/util/md5.cpp +++ b/Engine/source/core/util/md5.cpp @@ -154,7 +154,7 @@ void MD5Final( unsigned char digest[16], MD5Context* ctx) MD5Transform(ctx->buf, (int *) ctx->in); byteReverse((unsigned char *) ctx->buf, 4); memcpy(digest, ctx->buf, 16); - memset(ctx, 0, sizeof(ctx)); /* In case it's sensitive */ + memset(ctx, 0, sizeof(MD5Context)); /* In case it's sensitive */ } diff --git a/Engine/source/core/util/path.cpp b/Engine/source/core/util/path.cpp index 5bcea08fb..f188b5342 100644 --- a/Engine/source/core/util/path.cpp +++ b/Engine/source/core/util/path.cpp @@ -56,7 +56,7 @@ void Path::_split(String name) idx = name.find('/', 0, String::Right); if (idx >= pos) { - int len = idx - pos; + S32 len = idx - pos; mPath = name.substr(pos,len? len: 1); mPath = Path::CleanSeparators(mPath); pos = idx + 1; @@ -408,7 +408,7 @@ String Path::getDirectory(U32 count) const U32 end = offset; - while (mPath[end] != '/' && end < mPath.length()) + while (end < mPath.length() && mPath[end] != '/') end++; return mPath.substr(offset,end - offset); diff --git a/Engine/source/core/util/path.h b/Engine/source/core/util/path.h index 604b48f76..73cc5af13 100644 --- a/Engine/source/core/util/path.h +++ b/Engine/source/core/util/path.h @@ -40,7 +40,7 @@ class Path public: enum Separator { -#if defined(TORQUE_OS_WIN32) || defined(TORQUE_OS_XENON) +#if defined(TORQUE_OS_WIN) || defined(TORQUE_OS_XENON) OsSeparator = '\\' #else OsSeparator = '/' diff --git a/Engine/source/core/util/str.cpp b/Engine/source/core/util/str.cpp index 9a89ef2a1..36b0637de 100644 --- a/Engine/source/core/util/str.cpp +++ b/Engine/source/core/util/str.cpp @@ -760,7 +760,7 @@ String& String::operator=(const String &src) String& String::operator+=(const StringChar *src) { - if( src == NULL && !*src ) + if( src == NULL || !*src ) return *this; // Append the given string into a new string @@ -1419,7 +1419,7 @@ void String::copy(StringChar* dst, const StringChar *src, U32 len) //----------------------------------------------------------------------------- -#if defined(TORQUE_OS_WIN32) || defined(TORQUE_OS_XBOX) || defined(TORQUE_OS_XENON) +#if defined(TORQUE_OS_WIN) || defined(TORQUE_OS_XBOX) || defined(TORQUE_OS_XENON) // This standard function is not defined when compiling with VC7... #define vsnprintf _vsnprintf #endif diff --git a/Engine/source/core/util/swizzle.h b/Engine/source/core/util/swizzle.h index 4cf929fce..abbff288f 100644 --- a/Engine/source/core/util/swizzle.h +++ b/Engine/source/core/util/swizzle.h @@ -126,11 +126,11 @@ inline void Swizzle::ToBuffer( void *destination, const void *sour T *dest = reinterpret_cast( destination ); const T *src = reinterpret_cast( source ); - for( int i = 0; i < size / ( mapLength * sizeof( T ) ); i++ ) + for( S32 i = 0; i < size / ( mapLength * sizeof( T ) ); i++ ) { dMemcpy( dest, src, mapLength * sizeof( T ) ); - for( int j = 0; j < mapLength; j++ ) + for( S32 j = 0; j < mapLength; j++ ) *dest++ = src[mMap[j]]; src += mapLength; diff --git a/Engine/source/core/util/swizzleSpec.h b/Engine/source/core/util/swizzleSpec.h index d45273498..ee0259ac4 100644 --- a/Engine/source/core/util/swizzleSpec.h +++ b/Engine/source/core/util/swizzleSpec.h @@ -37,7 +37,7 @@ inline void Swizzle::InPlace( void *memory, const dsize_t size ) const U8 *src = reinterpret_cast( memory ); // Fast divide by 4 since we are assured a proper size - for( int i = 0; i < size >> 2; i++ ) + for( S32 i = 0; i < size >> 2; i++ ) { BYTESWAP( *dest++, src[mMap[0]] ); BYTESWAP( *dest++, src[mMap[1]] ); @@ -57,7 +57,7 @@ inline void Swizzle::ToBuffer( void *destination, const void *source, con const U8 *src = reinterpret_cast( source ); // Fast divide by 4 since we are assured a proper size - for( int i = 0; i < size >> 2; i++ ) + for( S32 i = 0; i < size >> 2; i++ ) { *dest++ = src[mMap[0]]; *dest++ = src[mMap[1]]; @@ -80,7 +80,7 @@ inline void Swizzle::InPlace( void *memory, const dsize_t size ) const U8 *dest = reinterpret_cast( memory ); U8 *src = reinterpret_cast( memory ); - for( int i = 0; i < size /3; i++ ) + for( S32 i = 0; i < size /3; i++ ) { BYTESWAP( *dest++, src[mMap[0]] ); BYTESWAP( *dest++, src[mMap[1]] ); @@ -98,7 +98,7 @@ inline void Swizzle::ToBuffer( void *destination, const void *source, con U8 *dest = reinterpret_cast( destination ); const U8 *src = reinterpret_cast( source ); - for( int i = 0; i < size / 3; i++ ) + for( S32 i = 0; i < size / 3; i++ ) { *dest++ = src[mMap[0]]; *dest++ = src[mMap[1]]; diff --git a/Engine/source/core/util/tFixedSizeVector.h b/Engine/source/core/util/tFixedSizeVector.h index cab8a2186..fedd12587 100644 --- a/Engine/source/core/util/tFixedSizeVector.h +++ b/Engine/source/core/util/tFixedSizeVector.h @@ -25,7 +25,7 @@ /// A vector with a compile-time constant size. -template< typename T, int SIZE > +template< typename T, S32 SIZE > class FixedSizeVector { protected: @@ -46,19 +46,19 @@ class FixedSizeVector FixedSizeVector( const T& a, const T& b, const T& c, const T& d, const T& e, const T& f ) { mArray[ 0 ] = a; mArray[ 1 ] = b; mArray[ 2 ] = c; mArray[ 3 ] = d; mArray[ 4 ] = e; mArray[ 5 ] = f; } FixedSizeVector( const T& a, const T& b, const T& c, const T& d, const T& e, const T& f, const T& g ) - { mArray[ 0 ] = a; mArray[ 1 ] = b; mArray[ 2 ] = c; mArray[ 3 ] = d; mArray[ 4 ] = e; mArray[ 5 ] = f; mArray[ 6 ]; } + { mArray[ 0 ] = a; mArray[ 1 ] = b; mArray[ 2 ] = c; mArray[ 3 ] = d; mArray[ 4 ] = e; mArray[ 5 ] = f; mArray[ 6 ] = g; } FixedSizeVector( const T& a, const T& b, const T& c, const T& d, const T& e, const T& f, const T& g, const T& h ) - { mArray[ 0 ] = a; mArray[ 1 ] = b; mArray[ 2 ] = c; mArray[ 3 ] = d; mArray[ 4 ] = e; mArray[ 5 ] = f; mArray[ 6 ]; mArray[ 7 ] = h; } + { mArray[ 0 ] = a; mArray[ 1 ] = b; mArray[ 2 ] = c; mArray[ 3 ] = d; mArray[ 4 ] = e; mArray[ 5 ] = f; mArray[ 6 ] = g; mArray[ 7 ] = h; } FixedSizeVector( const T& a, const T& b, const T& c, const T& d, const T& e, const T& f, const T& g, const T& h, const T& i ) - { mArray[ 0 ] = a; mArray[ 1 ] = b; mArray[ 2 ] = c; mArray[ 3 ] = d; mArray[ 4 ] = e; mArray[ 5 ] = f; mArray[ 6 ]; mArray[ 7 ] = h; mArray[ 8 ] = i; } + { mArray[ 0 ] = a; mArray[ 1 ] = b; mArray[ 2 ] = c; mArray[ 3 ] = d; mArray[ 4 ] = e; mArray[ 5 ] = f; mArray[ 6 ] = g; mArray[ 7 ] = h; mArray[ 8 ] = i; } FixedSizeVector( const T& a, const T& b, const T& c, const T& d, const T& e, const T& f, const T& g, const T& h, const T& i, const T& j ) - { mArray[ 0 ] = a; mArray[ 1 ] = b; mArray[ 2 ] = c; mArray[ 3 ] = d; mArray[ 4 ] = e; mArray[ 5 ] = f; mArray[ 6 ]; mArray[ 7 ] = h; mArray[ 8 ] = i; mArray[ 9 ] = j; } + { mArray[ 0 ] = a; mArray[ 1 ] = b; mArray[ 2 ] = c; mArray[ 3 ] = d; mArray[ 4 ] = e; mArray[ 5 ] = f; mArray[ 6 ] = g; mArray[ 7 ] = h; mArray[ 8 ] = i; mArray[ 9 ] = j; } FixedSizeVector( const T& a, const T& b, const T& c, const T& d, const T& e, const T& f, const T& g, const T& h, const T& i, const T& j, const T& k ) - { mArray[ 0 ] = a; mArray[ 1 ] = b; mArray[ 2 ] = c; mArray[ 3 ] = d; mArray[ 4 ] = e; mArray[ 5 ] = f; mArray[ 6 ]; mArray[ 7 ] = h; mArray[ 8 ] = i; mArray[ 9 ] = j; mArray[ 10 ] = k; } + { mArray[ 0 ] = a; mArray[ 1 ] = b; mArray[ 2 ] = c; mArray[ 3 ] = d; mArray[ 4 ] = e; mArray[ 5 ] = f; mArray[ 6 ] = g; mArray[ 7 ] = h; mArray[ 8 ] = i; mArray[ 9 ] = j; mArray[ 10 ] = k; } FixedSizeVector( const T& a, const T& b, const T& c, const T& d, const T& e, const T& f, const T& g, const T& h, const T& i, const T& j, const T& k, const T& l ) - { mArray[ 0 ] = a; mArray[ 1 ] = b; mArray[ 2 ] = c; mArray[ 3 ] = d; mArray[ 4 ] = e; mArray[ 5 ] = f; mArray[ 6 ]; mArray[ 7 ] = h; mArray[ 8 ] = i; mArray[ 9 ] = j; mArray[ 10 ] = k; mArray[ 11 ] = l; } + { mArray[ 0 ] = a; mArray[ 1 ] = b; mArray[ 2 ] = c; mArray[ 3 ] = d; mArray[ 4 ] = e; mArray[ 5 ] = f; mArray[ 6 ] = g; mArray[ 7 ] = h; mArray[ 8 ] = i; mArray[ 9 ] = j; mArray[ 10 ] = k; mArray[ 11 ] = l; } FixedSizeVector( const T& a, const T& b, const T& c, const T& d, const T& e, const T& f, const T& g, const T& h, const T& i, const T& j, const T& k, const T& l, const T& m ) - { mArray[ 0 ] = a; mArray[ 1 ] = b; mArray[ 2 ] = c; mArray[ 3 ] = d; mArray[ 4 ] = e; mArray[ 5 ] = f; mArray[ 6 ]; mArray[ 7 ] = h; mArray[ 8 ] = i; mArray[ 9 ] = j; mArray[ 10 ] = k; mArray[ 11 ] = l; mArray[ 12 ] =m; } + { mArray[ 0 ] = a; mArray[ 1 ] = b; mArray[ 2 ] = c; mArray[ 3 ] = d; mArray[ 4 ] = e; mArray[ 5 ] = f; mArray[ 6 ] = g; mArray[ 7 ] = h; mArray[ 8 ] = i; mArray[ 9 ] = j; mArray[ 10 ] = k; mArray[ 11 ] = l; mArray[ 12 ] =m; } U32 size() const { return SIZE; } bool empty() const { return ( SIZE == 0 ); } diff --git a/Engine/source/core/util/tSignal.cpp b/Engine/source/core/util/tSignal.cpp index 8bc5e8164..30980a715 100644 --- a/Engine/source/core/util/tSignal.cpp +++ b/Engine/source/core/util/tSignal.cpp @@ -24,7 +24,7 @@ #include "core/util/tSignal.h" -void SignalBase::DelegateLink::insert(DelegateLink* node, float order) +void SignalBase::DelegateLink::insert(DelegateLink* node, F32 order) { // Note: can only legitimately be called on list head DelegateLink * walk = next; diff --git a/Engine/source/core/util/tSignal.h b/Engine/source/core/util/tSignal.h index ea2e67954..07a412a38 100644 --- a/Engine/source/core/util/tSignal.h +++ b/Engine/source/core/util/tSignal.h @@ -77,6 +77,8 @@ protected: void insert(DelegateLink* node, F32 order); void unlink(); + + virtual ~DelegateLink() {} }; DelegateLink mList; @@ -92,6 +94,78 @@ protected: Vector mTriggerNext; }; +template class SignalBaseT; + +/// Class for handle automatic diconnect form Signal when destroyed +template< typename Signature > +class SignalSlot +{ +public: + typedef Delegate< Signature > DelegateSig; + typedef SignalBaseT< Signature > SignalSig; + + SignalSlot() : mSignal(NULL) + { + + } + + ~SignalSlot() + { + disconnect(); + } + + const DelegateSig& getDelegate() { return mDlg; } + + /// setDelegate disconect form Signal old delegate and connect new delegate + template + void setDelegate( const X &fn ) { setDelegate( DelegateSig( fn ) ); } + + template + void setDelegate( const X &ptr, const Y &fn ) { setDelegate( DelegateSig( ptr, fn ) ); } + + void setDelegate( const DelegateSig &dlg) + { + SignalSig* signal = mSignal; + if( isConnected() ) + disconnect(); + + mDlg = dlg; + if( signal && mDlg ) + signal->notify( mDlg ); + } + + /// is connected to Signal + bool isConnected() const { return mSignal; } + + /// disconnect from Signal + void disconnect() + { + if( mSignal ) + { + SignalSig *oldSignal = mSignal; + mSignal = NULL; + oldSignal->remove( mDlg ); + } + } + +protected: + friend class SignalBaseT< Signature >; + + void _setSignal(SignalSig *sig) + { + mSignal = sig; + } + + SignalSig* _getSignal() const { return mSignal; } + + DelegateSig mDlg; + SignalSig *mSignal; + +private: + SignalSlot( const SignalSlot&) {} + SignalSlot& operator=( const SignalSlot&) {} +}; + template class SignalBaseT : public SignalBase { public: @@ -135,7 +209,7 @@ public: { if( del->mDelegate == dlg ) { - for ( int i = 0; i < mTriggerNext.size(); i++ ) + for ( S32 i = 0; i < mTriggerNext.size(); i++ ) { if( mTriggerNext[i] == ptr ) mTriggerNext[i] = ptr->next; @@ -163,6 +237,18 @@ public: notify(dlg, order); } + void notify( SignalSlot &slot, F32 order = 0.5f) + { + if( !slot.getDelegate() ) + return; + + if( slot.isConnected() ) + slot.disconnect(); + + slot._setSignal( this ); + mList.insert( new SlotLinkImpl(slot), order ); + } + template void remove(T obj,U func) { @@ -198,6 +284,23 @@ protected: DelegateLinkImpl(DelegateSig dlg) : mDelegate(dlg) {} }; + struct SlotLinkImpl : public DelegateLinkImpl + { + SlotLinkImpl(SignalSlot& slot) : mSlot( &slot ), DelegateLinkImpl( slot.getDelegate() ) + { + + } + + ~SlotLinkImpl() + { + if( mSlot ) + mSlot->_setSignal( NULL ); + } + + protected: + SignalSlot *mSlot; + }; + DelegateSig & getDelegate(SignalBase::DelegateLink * link) { return ((DelegateLinkImpl*)link)->mDelegate; diff --git a/Engine/source/core/util/tVector.h b/Engine/source/core/util/tVector.h index 457ac5245..5042c4ba8 100644 --- a/Engine/source/core/util/tVector.h +++ b/Engine/source/core/util/tVector.h @@ -28,6 +28,7 @@ #ifndef _PLATFORM_H_ #include "platform/platform.h" #endif +#include //----------------------------------------------------------------------------- // Helper definitions for the vector class. @@ -181,6 +182,9 @@ class Vector /// void merge( const T *addr, U32 count ); + // Reverses the order of elements. + void reverse(); + /// @} }; @@ -504,7 +508,7 @@ template inline void Vector::compact() resize(mElementCount); } -typedef int (QSORT_CALLBACK *qsort_compare_func)(const void *, const void *); +typedef S32 (QSORT_CALLBACK *qsort_compare_func)(const void *, const void *); template inline void Vector::sort(compare_func f) { @@ -760,6 +764,12 @@ template inline void Vector::merge( const T *addr, U32 count ) mElementCount = newSize; } +template inline void Vector::reverse() +{ + for (U32 i = 0, j = size(); (i != j) && (i != --j); ++i) + std::swap( mArray[ i ], mArray[ j ] ); +} + //----------------------------------------------------------------------------- /// Template for vectors of pointers. template @@ -790,7 +800,7 @@ class VectorPtr : public Vector const_iterator end() const; void insert(iterator,const T&); - void insert(int idx) { Parent::insert(idx); } + void insert(S32 idx) { Parent::insert(idx); } void erase(iterator); T& front(); diff --git a/Engine/source/core/util/test/testVector2.cpp b/Engine/source/core/util/test/testVector2.cpp index 7c0cf2189..cbdf45487 100644 --- a/Engine/source/core/util/test/testVector2.cpp +++ b/Engine/source/core/util/test/testVector2.cpp @@ -72,10 +72,10 @@ CreateUnitTest( TestVector, "Util/Vector" ) TEST( dtorVals[ 9 ] ); } - static S32 QSORT_CALLBACK sortInts( const int* a, const int* b ) + static S32 QSORT_CALLBACK sortInts( const S32* a, const S32* b ) { - int av = *a; - int bv = *b; + S32 av = *a; + S32 bv = *b; if( av < bv ) return -1; @@ -87,7 +87,7 @@ CreateUnitTest( TestVector, "Util/Vector" ) void testSort() { - Vector< int > v; + Vector< S32 > v; v.push_back( 0 ); v.push_back( 10 ); diff --git a/Engine/source/core/util/zip/zipObject.cpp b/Engine/source/core/util/zip/zipObject.cpp index 60c05c183..419733350 100644 --- a/Engine/source/core/util/zip/zipObject.cpp +++ b/Engine/source/core/util/zip/zipObject.cpp @@ -216,7 +216,7 @@ String ZipObject::getFileEntry(S32 idx) const Zip::CentralDir &dir = (*mZipArchive)[idx]; char buffer[1024]; - int chars = dSprintf(buffer, sizeof(buffer), "%s\t%d\t%d\t%d\t%08x", + S32 chars = dSprintf(buffer, sizeof(buffer), "%s\t%d\t%d\t%d\t%08x", dir.mFilename.c_str(), dir.mUncompressedSize, dir.mCompressedSize, dir.mCompressMethod, dir.mCRC32); if (chars < sizeof(buffer)) diff --git a/Engine/source/core/util/zip/zipVolume.cpp b/Engine/source/core/util/zip/zipVolume.cpp index 16bad16dd..6982c70c0 100644 --- a/Engine/source/core/util/zip/zipVolume.cpp +++ b/Engine/source/core/util/zip/zipVolume.cpp @@ -55,7 +55,7 @@ public: } virtual Path getName() const { return mZipFilename; } - virtual Status getStatus() const + virtual NodeStatus getStatus() const { if (mZipStream) { @@ -182,7 +182,7 @@ public: Torque::Path getName() const { return mPath; } // getStatus() doesn't appear to be used for directories - Status getStatus() const + NodeStatus getStatus() const { return FileNode::Open; } @@ -274,7 +274,7 @@ public: Torque::Path getName() const { return mPath; } // getStatus() doesn't appear to be used for directories - Status getStatus() const + NodeStatus getStatus() const { return FileNode::Open; } diff --git a/Engine/source/core/volume.cpp b/Engine/source/core/volume.cpp index 1e0b6cda7..05a139eeb 100644 --- a/Engine/source/core/volume.cpp +++ b/Engine/source/core/volume.cpp @@ -651,7 +651,7 @@ bool MountSystem::unmount(FileSystemRef fs) // also check that fs is not null each time since its a strong ref // so it could be nulled during removal. bool unmounted = false; - for (int i = mMountList.size() - 1; !fs.isNull() && i >= 0; --i) + for (S32 i = mMountList.size() - 1; !fs.isNull() && i >= 0; --i) { if (mMountList[i].fileSystem.getPointer() == fs.getPointer()) { diff --git a/Engine/source/core/volume.h b/Engine/source/core/volume.h index db0d0e5e8..bd041fa42 100644 --- a/Engine/source/core/volume.h +++ b/Engine/source/core/volume.h @@ -79,7 +79,7 @@ public: class FileNode : public FileBase { public: - enum Status + enum NodeStatus { Open, ///< In an open state Closed, ///< In a closed state @@ -122,7 +122,7 @@ public: // Properties virtual Path getName() const = 0; - virtual Status getStatus() const = 0; + virtual NodeStatus getStatus() const = 0; virtual bool getAttributes(Attributes*) = 0; diff --git a/Engine/source/environment/meshRoad.cpp b/Engine/source/environment/meshRoad.cpp index fac154f72..6a5e3fbd1 100644 --- a/Engine/source/environment/meshRoad.cpp +++ b/Engine/source/environment/meshRoad.cpp @@ -1074,7 +1074,7 @@ void MeshRoad::unpackUpdate(NetConnection * con, BitStream * stream) stream->read( &mMaterialName[i] ); if ( !Sim::findObject( mMaterialName[i], pMat ) ) - Con::printf( "DecalRoad::unpackUpdate, failed to find Material of name &s!", mMaterialName[i].c_str() ); + Con::printf( "DecalRoad::unpackUpdate, failed to find Material of name %s", mMaterialName[i].c_str() ); else mMaterial[i] = pMat; } diff --git a/Engine/source/environment/scatterSky.cpp b/Engine/source/environment/scatterSky.cpp index 7fdf25296..ed5f8d3ad 100644 --- a/Engine/source/environment/scatterSky.cpp +++ b/Engine/source/environment/scatterSky.cpp @@ -1057,7 +1057,7 @@ void ScatterSky::_renderMoon( ObjectRenderInst *ri, SceneRenderState *state, Bas const MatrixF &camView = state->getCameraTransform(); // Finalize points - for(int i = 0; i < 4; i++) + for(S32 i = 0; i < 4; i++) { // align with camera camView.mulV(points[i]); @@ -1114,13 +1114,13 @@ void ScatterSky::_generateSkyPoints() F32 deltaSegAngle = ( 2.0f * M_PI_F / (F32)segments ); // Generate the group of rings for the sphere. - for( int ring = 0; ring < 2; ring++ ) + for( S32 ring = 0; ring < 2; ring++ ) { F32 r0 = mSin( ring * deltaRingAngle ); F32 y0 = mCos( ring * deltaRingAngle ); // Generate the group of segments for the current ring. - for( int seg = 0; seg < segments + 1 ; seg++ ) + for( S32 seg = 0; seg < segments + 1 ; seg++ ) { F32 x0 = r0 * sinf( seg * deltaSegAngle ); F32 z0 = r0 * cosf( seg * deltaSegAngle ); diff --git a/Engine/source/environment/scatterSky.h b/Engine/source/environment/scatterSky.h index 254756bc9..2ce581ad3 100644 --- a/Engine/source/environment/scatterSky.h +++ b/Engine/source/environment/scatterSky.h @@ -62,7 +62,7 @@ GFXDeclareVertexFormat( ScatterSkyVertex ) { Point3F point; VectorF normal; - ColorF color; + GFXVertexColor color; }; class ScatterSky : public SceneObject, public ISceneLight diff --git a/Engine/source/environment/skyBox.cpp b/Engine/source/environment/skyBox.cpp index a41b0a361..7d3e600f7 100644 --- a/Engine/source/environment/skyBox.cpp +++ b/Engine/source/environment/skyBox.cpp @@ -400,7 +400,11 @@ void SkyBox::_initRender() } GFXVertexPNTT *vertPtr = mVB.lock(); - if(!vertPtr) return; + if (!vertPtr) + { + delete[] tmpVerts; + return; + } dMemcpy( vertPtr, tmpVerts, sizeof ( GFXVertexPNTT ) * vertCount ); diff --git a/Engine/source/environment/sun.cpp b/Engine/source/environment/sun.cpp index ae42f2bbc..bd89d4cca 100644 --- a/Engine/source/environment/sun.cpp +++ b/Engine/source/environment/sun.cpp @@ -470,7 +470,7 @@ void Sun::_renderCorona( ObjectRenderInst *ri, SceneRenderState *state, BaseMatI const MatrixF &camView = state->getCameraTransform(); // Finalize points - for(int i = 0; i < 4; i++) + for(S32 i = 0; i < 4; i++) { // align with camera camView.mulV(points[i]); diff --git a/Engine/source/environment/waterPlane.cpp b/Engine/source/environment/waterPlane.cpp index eab66a466..afa3dc254 100644 --- a/Engine/source/environment/waterPlane.cpp +++ b/Engine/source/environment/waterPlane.cpp @@ -163,7 +163,7 @@ void WaterPlane::unpackUpdate(NetConnection* con, BitStream* stream) if( stream->readFlag() ) // UpdateMask { - float posZ; + F32 posZ; stream->read( &posZ ); Point3F newPos = getPosition(); newPos.z = posZ; diff --git a/Engine/source/forest/editor/forestBrushTool.cpp b/Engine/source/forest/editor/forestBrushTool.cpp index a32e28ed7..4dd1734df 100644 --- a/Engine/source/forest/editor/forestBrushTool.cpp +++ b/Engine/source/forest/editor/forestBrushTool.cpp @@ -650,7 +650,7 @@ void ForestBrushTool::_collectElements() } } -bool ForestBrushTool::getGroundAt( const Point3F &worldPt, float *zValueOut, VectorF *normalOut ) +bool ForestBrushTool::getGroundAt( const Point3F &worldPt, F32 *zValueOut, VectorF *normalOut ) { const U32 mask = TerrainObjectType | StaticShapeObjectType; diff --git a/Engine/source/forest/editor/forestBrushTool.h b/Engine/source/forest/editor/forestBrushTool.h index 510146ff4..0debad616 100644 --- a/Engine/source/forest/editor/forestBrushTool.h +++ b/Engine/source/forest/editor/forestBrushTool.h @@ -82,7 +82,7 @@ public: void setPressure( F32 val ); void setHardness( F32 val ); void collectElements() { _collectElements(); } - bool getGroundAt( const Point3F &worldPt, float *zValueOut, VectorF *normalOut ); + bool getGroundAt( const Point3F &worldPt, F32 *zValueOut, VectorF *normalOut ); protected: diff --git a/Engine/source/forest/glsl/windDeformationGLSL.cpp b/Engine/source/forest/glsl/windDeformationGLSL.cpp index 00502caa9..ae32b51f7 100644 --- a/Engine/source/forest/glsl/windDeformationGLSL.cpp +++ b/Engine/source/forest/glsl/windDeformationGLSL.cpp @@ -40,6 +40,9 @@ static void _onRegisterFeatures( GFXAdapterType type ) { + if ( type != OpenGL ) + return; + FEATUREMGR->registerFeature( MFT_WindEffect, new WindDeformationGLSL ); } @@ -83,29 +86,14 @@ void WindDeformationGLSL::processVert( Vector &componentList, // save constant space and reduce the memory copied to the // card. // - // This in particular helps when we're instancing. - // // .x = bend scale // .y = branch amplitude // .z = detail amplitude // .w = detail frequency // - Var *windParams; - if ( fd.features[MFT_UseInstancing] ) - { - ShaderConnector *vertStruct = dynamic_cast( componentList[C_VERT_STRUCT] ); - windParams = vertStruct->getElement( RT_TEXCOORD ); - windParams->setName( "inst_windParams" ); - windParams->setType( "vec4" ); - - mInstancingFormat->addElement( "windParams", GFXDeclType_Float4, windParams->constNum ); - } - else - { - windParams = new Var( "windParams", "vec4" ); + Var *windParams = new Var( "windParams", "vec4" ); windParams->uniform = true; windParams->constSortPos = cspPotentialPrimitive; - } // If we're instancing then we need to instance the wind direction // and speed as its unique for each tree instance. @@ -114,6 +102,7 @@ void WindDeformationGLSL::processVert( Vector &componentList, { ShaderConnector *vertStruct = dynamic_cast( componentList[C_VERT_STRUCT] ); windDirAndSpeed = vertStruct->getElement( RT_TEXCOORD ); + windDirAndSpeed->setStructName( "IN" ); windDirAndSpeed->setName( "inst_windDirAndSpeed" ); windDirAndSpeed->setType( "vec3" ); @@ -143,16 +132,31 @@ void WindDeformationGLSL::processVert( Vector &componentList, if ( !inPosition ) inPosition = (Var*)LangElement::find( "position" ); + // Copy the input position to the output first as + // the wind effects are conditional. + Var *outPosition = (Var*)LangElement::find( "inPosition" ); + if ( !outPosition ) + { + outPosition = new Var; + outPosition->setType( "vec3" ); + outPosition->setName( "inPosition" ); + meta->addStatement( new GenOp(" @ = @.xyz;\r\n", new DecOp( outPosition ), inPosition ) ); + } + // Get the incoming color data Var *inColor = (Var*)LangElement::find( "diffuse" ); + // Do a dynamic branch based on wind force. + if ( GFX->getPixelShaderVersion() >= 3.0f ) + meta->addStatement( new GenOp(" if ( any( bvec3(@) ) ) {\r\n", windDirAndSpeed ) ); + // Do the branch and detail bending first so that // it can work in pure object space of the tree. LangElement *effect = new GenOp( "windBranchBending( " - "@.xyz, " // vPos - "normalize( normal ), " // vNormal + "@, " // vPos + "normalize( IN_normal ), " // vNormal "@, " // fTime "@.z, " // fWindSpeed @@ -161,13 +165,13 @@ void WindDeformationGLSL::processVert( Vector &componentList, "@.y, " // fBranchAmp "@.r, " // fBranchAtten - "dot( @[3], vec4( 1.0 ) ), " // fDetailPhase + "dot( @[3], vec4(1) ), " // fDetailPhase "@.z, " // fDetailAmp "@.w, " // fDetailFreq - + "@.b )", // fEdgeAtten - inPosition, // vPos + outPosition, // vPos // vNormal accumTime, // fTime @@ -183,22 +187,15 @@ void WindDeformationGLSL::processVert( Vector &componentList, inColor ); // fEdgeAtten - Var *outPosition = (Var*)LangElement::find( "inPosition" ); - if ( outPosition ) - meta->addStatement( new GenOp( " @.xyz = @;\r\n", outPosition, effect, inPosition ) ); - else - { - outPosition = new Var; - outPosition->setType( "vec3" ); - outPosition->setName( "inPosition" ); - meta->addStatement( new GenOp(" vec3 inPosition = @;\r\n", effect, inPosition ) ); - } + meta->addStatement( new GenOp( " @ = @;\r\n", outPosition, effect ) ); // Now do the trunk bending. - effect = new GenOp( "windTrunkBending( @, @.xy, @.z * @.x )", - outPosition, windDirAndSpeed, outPosition, windParams ); + meta->addStatement( new GenOp(" @ = windTrunkBending( @, @.xy, @.z * @.x );\r\n", + outPosition, outPosition, windDirAndSpeed, outPosition, windParams ) ); - meta->addStatement( new GenOp(" @ = @;\r\n", outPosition, effect ) ); + // End the dynamic branch. + if ( GFX->getPixelShaderVersion() >= 3.0f ) + meta->addStatement( new GenOp(" } // [branch]\r\n" ) ); } ShaderFeatureConstHandles* WindDeformationGLSL::createConstHandles( GFXShader *shader, SimObject *userObject ) diff --git a/Engine/source/gfx/D3D9/gfxD3D9CardProfiler.cpp b/Engine/source/gfx/D3D9/gfxD3D9CardProfiler.cpp index a2fd892fe..988e3a4e2 100644 --- a/Engine/source/gfx/D3D9/gfxD3D9CardProfiler.cpp +++ b/Engine/source/gfx/D3D9/gfxD3D9CardProfiler.cpp @@ -25,7 +25,7 @@ #include "gfx/primBuilder.h" #include "gfx/D3D9/gfxD3D9CardProfiler.h" #include "gfx/D3D9/gfxD3D9EnumTranslate.h" -#ifdef TORQUE_OS_WIN32 +#ifdef TORQUE_OS_WIN #include "platformWin32/videoInfo/wmiVideoInfo.h" #endif diff --git a/Engine/source/gfx/D3D9/gfxD3D9EnumTranslate.h b/Engine/source/gfx/D3D9/gfxD3D9EnumTranslate.h index 00448bad0..b0ec97eae 100644 --- a/Engine/source/gfx/D3D9/gfxD3D9EnumTranslate.h +++ b/Engine/source/gfx/D3D9/gfxD3D9EnumTranslate.h @@ -54,8 +54,8 @@ extern _D3DTEXTUREOP GFXD3D9TextureOp[GFXTOP_COUNT]; extern _D3DDECLTYPE GFXD3D9DeclType[GFXDeclType_COUNT]; #define GFXREVERSE_LOOKUP( tablearray, enumprefix, val ) \ - for( int i = enumprefix##_FIRST; i < enumprefix##_COUNT; i++ ) \ - if( (int)tablearray##[i] == val ) \ + for( S32 i = enumprefix##_FIRST; i < enumprefix##_COUNT; i++ ) \ + if( (S32)tablearray##[i] == val ) \ { \ val = i; \ break; \ diff --git a/Engine/source/gfx/D3D9/gfxD3D9Shader.cpp b/Engine/source/gfx/D3D9/gfxD3D9Shader.cpp index 34b9c47d2..a7ff68a78 100644 --- a/Engine/source/gfx/D3D9/gfxD3D9Shader.cpp +++ b/Engine/source/gfx/D3D9/gfxD3D9Shader.cpp @@ -444,7 +444,7 @@ const String GFXD3D9ShaderConstBuffer::describeSelf() const GenericConstBufferLayout::ParamDesc pd; mVertexConstBufferLayoutF->getDesc(i, pd); - ret += String::ToString(" Constant name: %s", pd.name); + ret += String::ToString(" Constant name: %s", pd.name.c_str()); } return ret; diff --git a/Engine/source/gfx/D3D9/gfxD3D9TextureManager.cpp b/Engine/source/gfx/D3D9/gfxD3D9TextureManager.cpp index 417d7f803..41556630f 100644 --- a/Engine/source/gfx/D3D9/gfxD3D9TextureManager.cpp +++ b/Engine/source/gfx/D3D9/gfxD3D9TextureManager.cpp @@ -236,7 +236,7 @@ void GFXD3D9TextureManager::_innerCreateTexture( GFXD3D9TextureObject *retTex, // If this is a render target, and it wants AA or wants to match the backbuffer (for example, to share the z) // Check the caps though, if we can't stretchrect between textures, use the old RT method. (Which hopefully means // that they can't force AA on us as well.) - if (retTex->mProfile->isRenderTarget() && mslevel != 0 && (mDeviceCaps.Caps2 && D3DDEVCAPS2_CAN_STRETCHRECT_FROM_TEXTURES)) + if (retTex->mProfile->isRenderTarget() && mslevel != 0 && (mDeviceCaps.Caps2 & D3DDEVCAPS2_CAN_STRETCHRECT_FROM_TEXTURES)) { D3D9Assert(mD3DDevice->CreateRenderTarget(width, height, d3dTextureFormat, mstype, mslevel, false, retTex->getSurfacePtr(), NULL), @@ -259,7 +259,7 @@ void GFXD3D9TextureManager::_innerCreateTexture( GFXD3D9TextureObject *retTex, retTex->mTextureSize.set(probeDesc.Width, probeDesc.Height, 0); - int fmt = probeDesc.Format; + S32 fmt = probeDesc.Format; #if !defined(TORQUE_OS_XENON) GFXREVERSE_LOOKUP( GFXD3D9TextureFormat, GFXFormat, fmt ); @@ -568,7 +568,7 @@ bool GFXD3D9TextureManager::_loadTexture(GFXTextureObject *aTexture, DDSFile *dd GFXD3D9TextureObject *texture = static_cast(aTexture); // Fill the texture... - for( int i = 0; i < aTexture->mMipLevels; i++ ) + for( S32 i = 0; i < aTexture->mMipLevels; i++ ) { PROFILE_SCOPE(GFXD3DTexMan_loadSurface); diff --git a/Engine/source/gfx/D3D9/gfxD3D9TextureObject.cpp b/Engine/source/gfx/D3D9/gfxD3D9TextureObject.cpp index be859b857..ff9c69096 100644 --- a/Engine/source/gfx/D3D9/gfxD3D9TextureObject.cpp +++ b/Engine/source/gfx/D3D9/gfxD3D9TextureObject.cpp @@ -242,9 +242,9 @@ bool GFXD3D9TextureObject::copyToBmp(GBitmap* bmp) PROFILE_START(GFXD3D9TextureObject_copyToBmp_pixCopy); // copy data into bitmap - for (int row = 0; row < height; ++row) + for (S32 row = 0; row < height; ++row) { - for (int col = 0; col < width; ++col) + for (S32 col = 0; col < width; ++col) { destPtr[0] = srcPtr[2]; // red destPtr[1] = srcPtr[1]; // green diff --git a/Engine/source/gfx/D3D9/pc/gfxD3D9EnumTranslate.pc.cpp b/Engine/source/gfx/D3D9/pc/gfxD3D9EnumTranslate.pc.cpp index ae143cfc3..f4e4accff 100644 --- a/Engine/source/gfx/D3D9/pc/gfxD3D9EnumTranslate.pc.cpp +++ b/Engine/source/gfx/D3D9/pc/gfxD3D9EnumTranslate.pc.cpp @@ -46,14 +46,14 @@ _D3DDECLTYPE GFXD3D9DeclType[GFXDeclType_COUNT]; //------------------------------------------------------------------------------ #define INIT_LOOKUPTABLE( tablearray, enumprefix, type ) \ - for( int i = enumprefix##_FIRST; i < enumprefix##_COUNT; i++ ) \ + for( S32 i = enumprefix##_FIRST; i < enumprefix##_COUNT; i++ ) \ tablearray##[i] = (##type##)GFX_UNINIT_VAL; #define VALIDATE_LOOKUPTABLE( tablearray, enumprefix ) \ - for( int i = enumprefix##_FIRST; i < enumprefix##_COUNT; i++ ) \ - if( (int)tablearray##[i] == GFX_UNINIT_VAL ) \ + for( S32 i = enumprefix##_FIRST; i < enumprefix##_COUNT; i++ ) \ + if( (S32)tablearray##[i] == GFX_UNINIT_VAL ) \ Con::warnf( "GFXD3D9EnumTranslate: Unassigned value in " #tablearray ": %i", i ); \ - else if( (int)tablearray##[i] == GFX_UNSUPPORTED_VAL ) \ + else if( (S32)tablearray##[i] == GFX_UNSUPPORTED_VAL ) \ Con::warnf( "GFXD3D9EnumTranslate: Unsupported value in " #tablearray ": %i", i ); //------------------------------------------------------------------------------ diff --git a/Engine/source/gfx/D3D9/pc/gfxPCD3D9Target.cpp b/Engine/source/gfx/D3D9/pc/gfxPCD3D9Target.cpp index 194e304fd..0ac4114cf 100644 --- a/Engine/source/gfx/D3D9/pc/gfxPCD3D9Target.cpp +++ b/Engine/source/gfx/D3D9/pc/gfxPCD3D9Target.cpp @@ -330,7 +330,7 @@ void GFXPCD3D9TextureTarget::resolveTo( GFXTextureObject *tex ) void GFXPCD3D9TextureTarget::zombify() { - for(int i = 0; i < MaxRenderSlotId; i++) + for(S32 i = 0; i < MaxRenderSlotId; i++) attachTexture(RenderSlot(i), NULL); } diff --git a/Engine/source/gfx/bitmap/ddsLoader.cpp b/Engine/source/gfx/bitmap/ddsLoader.cpp index 3405547a9..4ad23ef39 100644 --- a/Engine/source/gfx/bitmap/ddsLoader.cpp +++ b/Engine/source/gfx/bitmap/ddsLoader.cpp @@ -883,7 +883,7 @@ DDSFile *DDSFile::createDDSFileFromGBitmap( const GBitmap *gbmp ) ret->mSurfaces.push_back( new SurfaceData() ); // Load the mips - for( int i = 0; i < ret->mMipMapCount; i++ ) + for( S32 i = 0; i < ret->mMipMapCount; i++ ) { const U32 mipSz = ret->getSurfaceSize(i); ret->mSurfaces.last()->mMips.push_back( new U8[mipSz] ); @@ -898,7 +898,7 @@ DDSFile *DDSFile::createDDSFileFromGBitmap( const GBitmap *gbmp ) // Assumption: AssertFatal( gbmp->getBytesPerPixel() + 1 == ret->mBytesPerPixel, "Assumption failed, not 24->32 bit straight convert." ); - for( int pxl = 0; pxl < gbmp->getWidth(i) * gbmp->getHeight(i); pxl++ ) + for( S32 pxl = 0; pxl < gbmp->getWidth(i) * gbmp->getHeight(i); pxl++ ) { U8 *dst = &mipMem[pxl * ret->mBytesPerPixel]; const U8 *src = &gbmp->getBits(i)[pxl * gbmp->getBytesPerPixel()]; diff --git a/Engine/source/gfx/bitmap/ddsUtils.cpp b/Engine/source/gfx/bitmap/ddsUtils.cpp index 42971bfdc..b5e5fa4a8 100644 --- a/Engine/source/gfx/bitmap/ddsUtils.cpp +++ b/Engine/source/gfx/bitmap/ddsUtils.cpp @@ -77,7 +77,7 @@ bool DDSUtil::squishDDS( DDSFile *srcDDS, const GFXFormat dxtFormat ) // are done, we can discard the old surface, and replace it with this one. DDSFile::SurfaceData *newSurface = new DDSFile::SurfaceData(); - for( int i = 0; i < srcDDS->mMipMapCount; i++ ) + for( S32 i = 0; i < srcDDS->mMipMapCount; i++ ) { const U8 *srcBits = srcSurface->mMips[i]; @@ -106,7 +106,7 @@ bool DDSUtil::squishDDS( DDSFile *srcDDS, const GFXFormat dxtFormat ) void DDSUtil::swizzleDDS( DDSFile *srcDDS, const Swizzle &swizzle ) { - for( int i = 0; i < srcDDS->mMipMapCount; i++ ) + for( S32 i = 0; i < srcDDS->mMipMapCount; i++ ) { swizzle.InPlace( srcDDS->mSurfaces.last()->mMips[i], srcDDS->getSurfaceSize( i ) ); } diff --git a/Engine/source/gfx/bitmap/gBitmap.cpp b/Engine/source/gfx/bitmap/gBitmap.cpp index f0e0ad11e..151a792ed 100644 --- a/Engine/source/gfx/bitmap/gBitmap.cpp +++ b/Engine/source/gfx/bitmap/gBitmap.cpp @@ -796,11 +796,11 @@ bool GBitmap::combine( const GBitmap *bitmapA, const GBitmap *bitmapB, const GFX const U8 *aBits = bitmapA->getBits(); const U8 *bBits = bitmapB->getBits(); - for( int y = 0; y < getHeight(); y++ ) + for( S32 y = 0; y < getHeight(); y++ ) { - for( int x = 0; x < getWidth(); x++ ) + for( S32 x = 0; x < getWidth(); x++ ) { - for( int _byte = 0; _byte < mBytesPerPixel; _byte++ ) + for( S32 _byte = 0; _byte < mBytesPerPixel; _byte++ ) { U8 pxA = 0; U8 pxB = 0; diff --git a/Engine/source/gfx/bitmap/loaders/bitmapBmp.cpp b/Engine/source/gfx/bitmap/loaders/bitmapBmp.cpp index 925d676dd..a54c3997e 100644 --- a/Engine/source/gfx/bitmap/loaders/bitmapBmp.cpp +++ b/Engine/source/gfx/bitmap/loaders/bitmapBmp.cpp @@ -152,7 +152,7 @@ static bool sReadBMP(Stream &stream, GBitmap *bitmap) if(bytesPerPixel == 3 && bi.biBitCount != 8) // do BGR swap { U8 *ptr = bitmap->getAddress(0,0); - for(int i = 0; i < width * height; i++) + for(S32 i = 0; i < width * height; i++) { U8 tmp = ptr[0]; ptr[0] = ptr[2]; diff --git a/Engine/source/gfx/bitmap/loaders/bitmapGif.cpp b/Engine/source/gfx/bitmap/loaders/bitmapGif.cpp index ef1bb783b..d4c031026 100644 --- a/Engine/source/gfx/bitmap/loaders/bitmapGif.cpp +++ b/Engine/source/gfx/bitmap/loaders/bitmapGif.cpp @@ -54,7 +54,7 @@ static struct _privateRegisterGIF //-------------------------------------- Replacement I/O for standard LIBjpeg // functions. we don't wanna use // FILE*'s... -static int gifReadDataFn(GifFileType *gifinfo, GifByteType *data, int length) +static S32 gifReadDataFn(GifFileType *gifinfo, GifByteType *data, S32 length) { Stream *stream = (Stream*)gifinfo->UserData; AssertFatal(stream != NULL, "gifReadDataFn::No stream."); @@ -72,7 +72,7 @@ static int gifReadDataFn(GifFileType *gifinfo, GifByteType *data, int length) //-------------------------------------- #if 0 // CodeReview - until we can write these, get rid of warning by disabling method. -static int gifWriteDataFn(GifFileType *gifinfo, GifByteType *data, int length) +static S32 gifWriteDataFn(GifFileType *gifinfo, GifByteType *data, S32 length) { Stream *stream = (Stream*)gifinfo->UserData; AssertFatal(stream != NULL, "gifWriteDataFn::No stream."); diff --git a/Engine/source/gfx/bitmap/loaders/bitmapJpeg.cpp b/Engine/source/gfx/bitmap/loaders/bitmapJpeg.cpp index 790369f32..8a647afda 100644 --- a/Engine/source/gfx/bitmap/loaders/bitmapJpeg.cpp +++ b/Engine/source/gfx/bitmap/loaders/bitmapJpeg.cpp @@ -50,11 +50,11 @@ static struct _privateRegisterJPG //-------------------------------------- Replacement I/O for standard LIBjpeg // functions. we don't wanna use // FILE*'s... -static int jpegReadDataFn(void *client_data, unsigned char *data, int length) +static S32 jpegReadDataFn(void *client_data, U8 *data, S32 length) { Stream *stream = (Stream*)client_data; AssertFatal(stream != NULL, "jpegReadDataFn::No stream."); - int pos = stream->getPosition(); + S32 pos = stream->getPosition(); if (stream->read(length, data)) return length; @@ -66,7 +66,7 @@ static int jpegReadDataFn(void *client_data, unsigned char *data, int length) //-------------------------------------- -static int jpegWriteDataFn(void *client_data, unsigned char *data, int length) +static S32 jpegWriteDataFn(void *client_data, U8 *data, S32 length) { Stream *stream = (Stream*)client_data; AssertFatal(stream != NULL, "jpegWriteDataFn::No stream."); @@ -78,7 +78,7 @@ static int jpegWriteDataFn(void *client_data, unsigned char *data, int length) //-------------------------------------- -static int jpegFlushDataFn(void *) +static S32 jpegFlushDataFn(void *) { // do nothing since we can't flush the stream object return 0; @@ -86,7 +86,7 @@ static int jpegFlushDataFn(void *) //-------------------------------------- -static int jpegErrorFn(void *client_data) +static S32 jpegErrorFn(void *client_data) { Stream *stream = (Stream*)client_data; AssertFatal(stream != NULL, "jpegErrorFn::No stream."); diff --git a/Engine/source/gfx/gFont.cpp b/Engine/source/gfx/gFont.cpp index ec8ce4205..7c838915d 100644 --- a/Engine/source/gfx/gFont.cpp +++ b/Engine/source/gfx/gFont.cpp @@ -42,7 +42,7 @@ GFX_ImplementTextureProfile(GFXFontTextureProfile, GFXTextureProfile::Static | GFXTextureProfile::KeepBitmap | GFXTextureProfile::NoMipmap, - GFXTextureProfile::None); + GFXTextureProfile::NONE); template<> void *Resource::create(const Torque::Path &path) { @@ -265,7 +265,7 @@ void GFont::dumpInfo() const if(mapCount) Con::printf(" - Codepoints range from 0x%x to 0x%x.", mapBegin, mapEnd); else - Con::printf(" - No mapped codepoints.", mapBegin, mapEnd); + Con::printf(" - No mapped codepoints."); Con::printf(" - Platform font is %s.", (mPlatformFont ? "present" : "not present") ); } diff --git a/Engine/source/gfx/gfxDevice.cpp b/Engine/source/gfx/gfxDevice.cpp index fbf1f3c4b..3bb634027 100644 --- a/Engine/source/gfx/gfxDevice.cpp +++ b/Engine/source/gfx/gfxDevice.cpp @@ -103,7 +103,7 @@ GFXDevice::GFXDevice() mViewMatrix.identity(); mProjectionMatrix.identity(); - for( int i = 0; i < WORLD_STACK_MAX; i++ ) + for( S32 i = 0; i < WORLD_STACK_MAX; i++ ) mWorldMatrix[i].identity(); AssertFatal(smGFXDevice == NULL, "Already a GFXDevice created! Bad!"); @@ -184,8 +184,8 @@ GFXDevice::GFXDevice() // Add a few system wide shader macros. GFXShader::addGlobalMacro( "TORQUE", "1" ); GFXShader::addGlobalMacro( "TORQUE_VERSION", String::ToString(getVersionNumber()) ); - #if defined TORQUE_OS_WIN32 - GFXShader::addGlobalMacro( "TORQUE_OS_WIN32" ); + #if defined TORQUE_OS_WIN + GFXShader::addGlobalMacro( "TORQUE_OS_WIN" ); #elif defined TORQUE_OS_MAC GFXShader::addGlobalMacro( "TORQUE_OS_MAC" ); #elif defined TORQUE_OS_LINUX @@ -451,7 +451,7 @@ void GFXDevice::updateStates(bool forceSetAll /*=false*/) if( mTextureMatrixCheckDirty ) { - for( int i = 0; i < getNumSamplers(); i++ ) + for( S32 i = 0; i < getNumSamplers(); i++ ) { if( mTextureMatrixDirty[i] ) { @@ -1279,7 +1279,7 @@ DefineEngineFunction( getPixelShaderVersion, F32, (),, return GFX->getPixelShaderVersion(); } -DefineEngineFunction( setPixelShaderVersion, void, ( float version ),, +DefineEngineFunction( setPixelShaderVersion, void, ( F32 version ),, "@brief Sets the pixel shader version for the active device.\n" "This can be used to force a lower pixel shader version than is supported by " "the device for testing or performance optimization.\n" diff --git a/Engine/source/gfx/gfxDrawUtil.cpp b/Engine/source/gfx/gfxDrawUtil.cpp index d7e4b921e..c03aecb5c 100644 --- a/Engine/source/gfx/gfxDrawUtil.cpp +++ b/Engine/source/gfx/gfxDrawUtil.cpp @@ -183,7 +183,7 @@ U32 GFXDrawUtil::drawTextN( GFont *font, const Point2I &ptDraw, const UTF16 *in_ U32 i; UTF16 c; - for(i = 0, c = in_string[i]; in_string[i] && i < n; i++, c = in_string[i]) + for (i = 0, c = in_string[i]; i < n && in_string[i]; i++, c = in_string[i]) { switch(c) { @@ -445,7 +445,7 @@ void GFXDrawUtil::drawRect( const Point2F &upperLeft, const Point2F &lowerRight, // Into Triangle-Strip Outline // v0-----------v2 // | a x | - // | v1-----v3 | + // | v1-----v3 | // | | | | // | v7-----v5 | // | x b | @@ -474,7 +474,7 @@ void GFXDrawUtil::drawRect( const Point2F &upperLeft, const Point2F &lowerRight, verts[8].point.set( upperLeft.x + ulOffset + nw.x, upperLeft.y + ulOffset + nw.y, 0.0f ); // same as 0 verts[9].point.set( upperLeft.x + ulOffset - nw.x, upperLeft.y + ulOffset - nw.y, 0.0f ); // same as 1 - for (int i=0; i<10; i++) + for (S32 i=0; i<10; i++) verts[i].color = color; verts.unlock(); @@ -512,7 +512,7 @@ void GFXDrawUtil::drawRectFill( const Point2F &upperLeft, const Point2F &lowerRi // Into Quad // v0---------v1 // | a x | - // | | + // | | // | x b | // v2---------v3 // @@ -531,7 +531,7 @@ void GFXDrawUtil::drawRectFill( const Point2F &upperLeft, const Point2F &lowerRi verts[2].point.set( upperLeft.x-ne.x+ulOffset, lowerRight.y-ne.y, 0.0f ); verts[3].point.set( lowerRight.x-nw.x, lowerRight.y-nw.y, 0.0f ); - for (int i=0; i<4; i++) + for (S32 i=0; i<4; i++) verts[i].color = color; verts.unlock(); @@ -828,11 +828,11 @@ void GFXDrawUtil::_drawWireCube( const GFXStateBlockDesc &desc, const Point3F &s // setup 6 line loops U32 vertexIndex = 0; - for(int i = 0; i < 6; i++) + for(S32 i = 0; i < 6; i++) { - for(int j = 0; j < 5; j++) + for(S32 j = 0; j < 5; j++) { - int idx = cubeFaces[i][j%4]; + S32 idx = cubeFaces[i][j%4]; verts[vertexIndex].point = cubePoints[idx] * halfSize; verts[vertexIndex].color = color; @@ -872,7 +872,7 @@ void GFXDrawUtil::_drawSolidCube( const GFXStateBlockDesc &desc, const Point3F & // setup 6 line loops U32 vertexIndex = 0; U32 idx; - for(int i = 0; i < 6; i++) + for(S32 i = 0; i < 6; i++) { idx = cubeFaces[i][0]; verts[vertexIndex].point = cubePoints[idx] * halfSize; diff --git a/Engine/source/gfx/gfxFormatUtils.cpp b/Engine/source/gfx/gfxFormatUtils.cpp index 1dc101d80..433d6b8a9 100644 --- a/Engine/source/gfx/gfxFormatUtils.cpp +++ b/Engine/source/gfx/gfxFormatUtils.cpp @@ -81,7 +81,7 @@ void GFXCopyPixels( GFXFormat fromFormat, U32 fromWidth, U32 fromHeight, U8* fr { if( fromFormat == toFormat && fromWidth == toWidth - && fromHeight == fromHeight ) + && fromHeight == toHeight ) dMemcpy( toData, fromData, fromWidth * fromHeight * GFXFormatInfo( fromFormat ).getBytesPerPixel() ); else { diff --git a/Engine/source/gfx/gfxShader.cpp b/Engine/source/gfx/gfxShader.cpp index 0bbcb4942..5e81d8a10 100644 --- a/Engine/source/gfx/gfxShader.cpp +++ b/Engine/source/gfx/gfxShader.cpp @@ -45,16 +45,29 @@ GFXShader::~GFXShader() Torque::FS::RemoveChangeNotification( mPixelFile, this, &GFXShader::_onFileChanged ); } +#ifndef TORQUE_OPENGL bool GFXShader::init( const Torque::Path &vertFile, const Torque::Path &pixFile, F32 pixVersion, const Vector ¯os ) +{ + Vector samplerNames; + return init( vertFile, pixFile, pixVersion, macros, samplerNames ); +} +#endif + +bool GFXShader::init( const Torque::Path &vertFile, + const Torque::Path &pixFile, + F32 pixVersion, + const Vector ¯os, + const Vector &samplerNames) { // Store the inputs for use in reloading. mVertexFile = vertFile; mPixelFile = pixFile; mPixVersion = pixVersion; mMacros = macros; + mSamplerNamesOrdered = samplerNames; // Before we compile the shader make sure the // conditioner features have been updated. diff --git a/Engine/source/gfx/gfxShader.h b/Engine/source/gfx/gfxShader.h index 8c77a5448..4b2c10f46 100644 --- a/Engine/source/gfx/gfxShader.h +++ b/Engine/source/gfx/gfxShader.h @@ -237,6 +237,13 @@ protected: /// The macros to be passed to the shader. Vector mMacros; + /// Ordered SamplerNames + /// We need to store a list of sampler for allow OpenGL to + /// assign correct location for each sampler. + /// GLSL 150 not allow explicit uniform location. + /// Only used on OpenGL + Vector mSamplerNamesOrdered; + /// The pixel version this is compiled for. F32 mPixVersion; @@ -292,10 +299,20 @@ public: virtual ~GFXShader(); /// + /// Deprecated. Remove on T3D 4.0 +#ifndef TORQUE_OPENGL bool init( const Torque::Path &vertFile, const Torque::Path &pixFile, F32 pixVersion, const Vector ¯os ); +#endif + + /// + bool init( const Torque::Path &vertFile, + const Torque::Path &pixFile, + F32 pixVersion, + const Vector ¯os, + const Vector &samplerNames); /// Reloads the shader from disk. bool reload(); diff --git a/Engine/source/gfx/gfxStringEnumTranslate.cpp b/Engine/source/gfx/gfxStringEnumTranslate.cpp index 108422aec..ff21e41ac 100644 --- a/Engine/source/gfx/gfxStringEnumTranslate.cpp +++ b/Engine/source/gfx/gfxStringEnumTranslate.cpp @@ -76,20 +76,20 @@ _STRING_VALUE_LOOKUP_FXN(GFXStringBlendOp); //------------------------------------------------------------------------------ #define INIT_LOOKUPTABLE( tablearray, enumprefix, type ) \ - for( int i = enumprefix##_FIRST; i < enumprefix##_COUNT; i++ ) \ + for( S32 i = enumprefix##_FIRST; i < enumprefix##_COUNT; i++ ) \ tablearray[i] = (type)GFX_UNINIT_VAL; #define INIT_LOOKUPTABLE_EX( tablearray, enumprefix, type, typeTable ) \ - for( int i = enumprefix##_FIRST; i < enumprefix##_COUNT; i++ ) \ + for( S32 i = enumprefix##_FIRST; i < enumprefix##_COUNT; i++ ) \ {\ tablearray[i] = (type)GFX_UNINIT_VAL;\ typeTable[i] = &defaultStringValueLookup;\ } #define VALIDATE_LOOKUPTABLE( tablearray, enumprefix ) \ - for( int i = enumprefix##_FIRST; i < enumprefix##_COUNT; i++ ) \ - if( (int)tablearray[i] == GFX_UNINIT_VAL ) \ + for( S32 i = enumprefix##_FIRST; i < enumprefix##_COUNT; i++ ) \ + if( (S32)tablearray[i] == GFX_UNINIT_VAL ) \ Con::warnf( "GFXStringEnumTranslate: Unassigned value in " #tablearray ": %i", i ); \ - else if( (int)tablearray[i] == GFX_UNSUPPORTED_VAL ) \ + else if( (S32)tablearray[i] == GFX_UNSUPPORTED_VAL ) \ Con::warnf( "GFXStringEnumTranslate: Unsupported value in " #tablearray ": %i", i ); //------------------------------------------------------------------------------ diff --git a/Engine/source/gfx/gfxStringEnumTranslate.h b/Engine/source/gfx/gfxStringEnumTranslate.h index 2184ab18f..37aab7590 100644 --- a/Engine/source/gfx/gfxStringEnumTranslate.h +++ b/Engine/source/gfx/gfxStringEnumTranslate.h @@ -71,8 +71,8 @@ extern StringValueLookupFn GFXStringSamplerStateValueLookup[GFXSAMP_COUNT]; extern StringValueLookupFn GFXStringTextureStageStateValueLookup[GFXTSS_COUNT]; #define GFXREVERSE_LOOKUP( tablearray, enumprefix, val ) \ - for( int i = enumprefix##_FIRST; i < enumprefix##_COUNT; i++ ) \ - if( (int)tablearray##[i] == val ) \ + for( S32 i = enumprefix##_FIRST; i < enumprefix##_COUNT; i++ ) \ + if( (S32)tablearray##[i] == val ) \ { \ val = i; \ break; \ diff --git a/Engine/source/gfx/gfxTextureManager.cpp b/Engine/source/gfx/gfxTextureManager.cpp index 7978eb6da..c997d1d2b 100644 --- a/Engine/source/gfx/gfxTextureManager.cpp +++ b/Engine/source/gfx/gfxTextureManager.cpp @@ -1031,9 +1031,9 @@ void GFXTextureManager::_validateTexParams( const U32 width, const U32 height, // If the format is non-compressed, and the profile requests a compressed format // than change the format. GFXFormat testingFormat = inOutFormat; - if( profile->getCompression() != GFXTextureProfile::None ) + if( profile->getCompression() != GFXTextureProfile::NONE ) { - const int offset = profile->getCompression() - GFXTextureProfile::DXT1; + const S32 offset = profile->getCompression() - GFXTextureProfile::DXT1; testingFormat = GFXFormat( GFXFormatDXT1 + offset ); // No auto-gen mips on compressed textures diff --git a/Engine/source/gfx/gfxTextureObject.h b/Engine/source/gfx/gfxTextureObject.h index b9db600f1..bed37bdce 100644 --- a/Engine/source/gfx/gfxTextureObject.h +++ b/Engine/source/gfx/gfxTextureObject.h @@ -63,7 +63,7 @@ struct GFXLockedRect { /// Pitch of the lock. This is the spacing in bytes of the start /// of each row of the locked region. - int pitch; + S32 pitch; /// Pointer to the start of locked rectangle. U8* bits; diff --git a/Engine/source/gfx/gfxTextureProfile.cpp b/Engine/source/gfx/gfxTextureProfile.cpp index 1c75b11ef..0272d6b31 100644 --- a/Engine/source/gfx/gfxTextureProfile.cpp +++ b/Engine/source/gfx/gfxTextureProfile.cpp @@ -34,15 +34,15 @@ GFX_ImplementTextureProfile(GFXDefaultRenderTargetProfile, GFXTextureProfile::DiffuseMap, GFXTextureProfile::PreserveSize | GFXTextureProfile::NoMipmap | GFXTextureProfile::RenderTarget, - GFXTextureProfile::None); + GFXTextureProfile::NONE); GFX_ImplementTextureProfile(GFXDefaultStaticDiffuseProfile, GFXTextureProfile::DiffuseMap, GFXTextureProfile::Static, - GFXTextureProfile::None); + GFXTextureProfile::NONE); GFX_ImplementTextureProfile(GFXDefaultStaticNormalMapProfile, GFXTextureProfile::NormalMap, GFXTextureProfile::Static, - GFXTextureProfile::None); + GFXTextureProfile::NONE); GFX_ImplementTextureProfile(GFXDefaultStaticDXT5nmProfile, GFXTextureProfile::NormalMap, GFXTextureProfile::Static, @@ -50,15 +50,15 @@ GFX_ImplementTextureProfile(GFXDefaultStaticDXT5nmProfile, GFX_ImplementTextureProfile(GFXDefaultPersistentProfile, GFXTextureProfile::DiffuseMap, GFXTextureProfile::PreserveSize | GFXTextureProfile::Static | GFXTextureProfile::KeepBitmap, - GFXTextureProfile::None); + GFXTextureProfile::NONE); GFX_ImplementTextureProfile(GFXSystemMemProfile, GFXTextureProfile::DiffuseMap, GFXTextureProfile::PreserveSize | GFXTextureProfile::NoMipmap | GFXTextureProfile::SystemMemory, - GFXTextureProfile::None); + GFXTextureProfile::NONE); GFX_ImplementTextureProfile(GFXDefaultZTargetProfile, GFXTextureProfile::DiffuseMap, GFXTextureProfile::PreserveSize | GFXTextureProfile::NoMipmap | GFXTextureProfile::ZTarget | GFXTextureProfile::NoDiscard, - GFXTextureProfile::None); + GFXTextureProfile::NONE); //----------------------------------------------------------------------------- diff --git a/Engine/source/gfx/gfxTextureProfile.h b/Engine/source/gfx/gfxTextureProfile.h index 9153256e3..e5abbc4da 100644 --- a/Engine/source/gfx/gfxTextureProfile.h +++ b/Engine/source/gfx/gfxTextureProfile.h @@ -106,7 +106,7 @@ public: enum Compression { - None, + NONE, DXT1, DXT2, DXT3, @@ -114,7 +114,7 @@ public: DXT5, }; - GFXTextureProfile(const String &name, Types type, U32 flags, Compression compression = None); + GFXTextureProfile(const String &name, Types type, U32 flags, Compression compression = NONE); // Accessors String getName() const { return mName; }; diff --git a/Engine/source/gfx/screenshot.h b/Engine/source/gfx/screenshot.h index 63de45280..9de224f06 100644 --- a/Engine/source/gfx/screenshot.h +++ b/Engine/source/gfx/screenshot.h @@ -74,6 +74,7 @@ public: /// Constructor. ScreenShot(); + virtual ~ScreenShot() { } /// Used to start the screenshot capture. void setPending( const char *filename, bool writeJPG, S32 tiles, F32 overlap ); diff --git a/Engine/source/gfx/test/stanfordBunny.cpp b/Engine/source/gfx/test/stanfordBunny.cpp index 90a79fae6..31a3c571b 100644 --- a/Engine/source/gfx/test/stanfordBunny.cpp +++ b/Engine/source/gfx/test/stanfordBunny.cpp @@ -13606,8 +13606,8 @@ void setupBunny(GFXVertexPCN* v) { for(j=0;j<3;j++) { - int vi=face_indicies[i][j]; - int ni=face_indicies[i][j+3];//Normal index + S32 vi=face_indicies[i][j]; + S32 ni=face_indicies[i][j+3];//Normal index Point3F point = Point3F(vertices[vi][0], vertices[vi][1], vertices[vi][2]); v[vert].normal = Point3F(normals[ni][0], normals[ni][1], normals[ni][2]); v[vert].point = point; diff --git a/Engine/source/gfx/util/distanceField.cpp b/Engine/source/gfx/util/distanceField.cpp index 91069ee25..229a07eec 100644 --- a/Engine/source/gfx/util/distanceField.cpp +++ b/Engine/source/gfx/util/distanceField.cpp @@ -32,7 +32,7 @@ struct DistanceFieldSearchSpaceStruct F32 distance; }; -int QSORT_CALLBACK cmpSortDistanceFieldSearchSpaceStruct(const void* p1, const void* p2) +S32 QSORT_CALLBACK cmpSortDistanceFieldSearchSpaceStruct(const void* p1, const void* p2) { const DistanceFieldSearchSpaceStruct* sp1 = (const DistanceFieldSearchSpaceStruct*)p1; const DistanceFieldSearchSpaceStruct* sp2 = (const DistanceFieldSearchSpaceStruct*)p2; diff --git a/Engine/source/gfx/util/triListOpt.cpp b/Engine/source/gfx/util/triListOpt.cpp index 8ed7e4d12..95c8fd65e 100644 --- a/Engine/source/gfx/util/triListOpt.cpp +++ b/Engine/source/gfx/util/triListOpt.cpp @@ -48,11 +48,11 @@ void OptimizeTriangleOrdering(const dsize_t numVerts, const dsize_t numIndices, FrameTemp triangleData(NumPrimitives); U32 curIdx = 0; - for(int tri = 0; tri < NumPrimitives; tri++) + for(S32 tri = 0; tri < NumPrimitives; tri++) { TriData &curTri = triangleData[tri]; - for(int c = 0; c < 3; c++) + for(S32 c = 0; c < 3; c++) { const U32 &curVIdx = indices[curIdx]; AssertFatal(curVIdx < numVerts, "Out of range index."); @@ -71,7 +71,7 @@ void OptimizeTriangleOrdering(const dsize_t numVerts, const dsize_t numIndices, // Allocate per-vertex triangle lists, and calculate the starting score of // each of the verts - for(int v = 0; v < numVerts; v++) + for(S32 v = 0; v < numVerts; v++) { VertData &curVert = vertexData[v]; curVert.triIndex = new S32[curVert.numUnaddedReferences]; @@ -89,11 +89,11 @@ void OptimizeTriangleOrdering(const dsize_t numVerts, const dsize_t numIndices, // Fill-in per-vertex triangle lists, and sum the scores of each vertex used // per-triangle, to get the starting triangle score curIdx = 0; - for(int tri = 0; tri < NumPrimitives; tri++) + for(S32 tri = 0; tri < NumPrimitives; tri++) { TriData &curTri = triangleData[tri]; - for(int c = 0; c < 3; c++) + for(S32 c = 0; c < 3; c++) { const U32 &curVIdx = indices[curIdx]; AssertFatal(curVIdx < numVerts, "Out of range index."); @@ -117,7 +117,7 @@ void OptimizeTriangleOrdering(const dsize_t numVerts, const dsize_t numIndices, // Step 2: Start emitting triangles...this is the emit loop // LRUCacheModel lruCache; - for(int outIdx = 0; outIdx < numIndices; /* this space intentionally left blank */ ) + for(S32 outIdx = 0; outIdx < numIndices; /* this space intentionally left blank */ ) { // If there is no next best triangle, than search for the next highest // scored triangle that isn't in the list already @@ -127,7 +127,7 @@ void OptimizeTriangleOrdering(const dsize_t numVerts, const dsize_t numIndices, nextBestTriScore = nextNextBestTriScore = -1.0f; nextBestTriIdx = nextNextBestTriIdx = -1; - for(int tri = 0; tri < NumPrimitives; tri++) + for(S32 tri = 0; tri < NumPrimitives; tri++) { TriData &curTri = triangleData[tri]; @@ -143,7 +143,7 @@ void OptimizeTriangleOrdering(const dsize_t numVerts, const dsize_t numIndices, // Emit the next best triangle TriData &nextBestTri = triangleData[nextBestTriIdx]; AssertFatal(!nextBestTri.isInList, "Next best triangle already in list, this is no good."); - for(int i = 0; i < 3; i++) + for(S32 i = 0; i < 3; i++) { // Emit index outIndices[outIdx++] = IndexType(nextBestTri.vertIdx[i]); @@ -151,7 +151,7 @@ void OptimizeTriangleOrdering(const dsize_t numVerts, const dsize_t numIndices, // Update the list of triangles on the vert VertData &curVert = vertexData[nextBestTri.vertIdx[i]]; curVert.numUnaddedReferences--; - for(int t = 0; t < curVert.numReferences; t++) + for(S32 t = 0; t < curVert.numReferences; t++) { if(curVert.triIndex[t] == nextBestTriIdx) { @@ -184,7 +184,7 @@ void OptimizeTriangleOrdering(const dsize_t numVerts, const dsize_t numIndices, { tri.score = 0.0f; - for(int i = 0; i < 3; i++) + for(S32 i = 0; i < 3; i++) tri.score += vertexData[tri.vertIdx[i]].score; _CHECK_NEXT_BEST(tri.score, *itr); @@ -288,12 +288,12 @@ void LRUCacheModel::enforceSize(const dsize_t maxSize, Vector &outTrisToUpd // Update cache position on verts still in cache vData.cachePosition = length++; - for(int i = 0; i < vData.numReferences; i++) + for(S32 i = 0; i < vData.numReferences; i++) { const S32 &triIdx = vData.triIndex[i]; if(triIdx > -1) { - int j = 0; + S32 j = 0; for(; j < outTrisToUpdate.size(); j++) if(outTrisToUpdate[j] == triIdx) break; @@ -378,7 +378,7 @@ F32 score(const VertData &vertexData) AssertFatal(vertexData.cachePosition < MaxSizeVertexCache, "Out of range cache position for vertex"); // Points for being high in the cache. - const float Scaler = 1.0f / (MaxSizeVertexCache - 3); + const F32 Scaler = 1.0f / (MaxSizeVertexCache - 3); Score = 1.0f - (vertexData.cachePosition - 3) * Scaler; Score = mPow(Score, FindVertexScore::CacheDecayPower); } @@ -387,7 +387,7 @@ F32 score(const VertData &vertexData) // Bonus points for having a low number of tris still to // use the vert, so we get rid of lone verts quickly. - float ValenceBoost = mPow(vertexData.numUnaddedReferences, -FindVertexScore::ValenceBoostPower); + F32 ValenceBoost = mPow(vertexData.numUnaddedReferences, -FindVertexScore::ValenceBoostPower); Score += FindVertexScore::ValenceBoostScale * ValenceBoost; return Score; diff --git a/Engine/source/gfx/video/theoraTexture.cpp b/Engine/source/gfx/video/theoraTexture.cpp index 95b513c26..039cbb392 100644 --- a/Engine/source/gfx/video/theoraTexture.cpp +++ b/Engine/source/gfx/video/theoraTexture.cpp @@ -60,7 +60,7 @@ GFX_ImplementTextureProfile( GFXTheoraTextureProfile, GFXTextureProfile::DiffuseMap, GFXTextureProfile::NoMipmap | GFXTextureProfile::Dynamic, - GFXTextureProfile::None ); + GFXTextureProfile::NONE ); //----------------------------------------------------------------------------- diff --git a/Engine/source/gfx/video/videoCapture.h b/Engine/source/gfx/video/videoCapture.h index 5ef80c836..7f46b133f 100644 --- a/Engine/source/gfx/video/videoCapture.h +++ b/Engine/source/gfx/video/videoCapture.h @@ -221,6 +221,8 @@ protected: // List with bitmaps which are done encoding ThreadSafeDeque< GBitmap* > mProcessedBitmaps; public: + virtual ~VideoEncoder() { } + // Stores an encoded bitmap to be dealt with later void pushProcessedBitmap( GBitmap* bitmap ); diff --git a/Engine/source/gfx/video/videoEncoderTheora.cpp b/Engine/source/gfx/video/videoEncoderTheora.cpp index c0b094a52..3e6160a12 100644 --- a/Engine/source/gfx/video/videoEncoderTheora.cpp +++ b/Engine/source/gfx/video/videoEncoderTheora.cpp @@ -150,8 +150,8 @@ class VideoEncoderTheora : public VideoEncoder, public Thread F64 videotime = th_granule_time(td,ogg_page_granulepos(&videopage)); if (videotime > 0) { - int hundredths=(int)(videotime*100-(long)videotime*100); - int seconds=(long)videotime%60; + S32 hundredths=(int)(videotime*100-(long)videotime*100); + S32 seconds=(long)videotime%60; Platform::outputDebugString("Encoding time %g %02i.%02i", videotime, seconds, hundredths); } } @@ -254,12 +254,12 @@ public: th_info_clear(&ti); // This is needed for youtube compatibility - int vp3_compatible = 1; + S32 vp3_compatible = 1; th_encode_ctl(td, TH_ENCCTL_SET_VP3_COMPATIBLE, &vp3_compatible, sizeof(vp3_compatible)); // Set the encoder to max speed - int speed_max; - int ret; + S32 speed_max; + S32 ret; ret = th_encode_ctl(td, TH_ENCCTL_GET_SPLEVEL_MAX, &speed_max, sizeof(speed_max)); if(ret<0){ Platform::outputDebugString("VideoEncoderTheora::begin() - could not determine maximum speed level."); diff --git a/Engine/source/gui/3d/guiTSControl.cpp b/Engine/source/gui/3d/guiTSControl.cpp index 4e42dbf84..71d419159 100644 --- a/Engine/source/gui/3d/guiTSControl.cpp +++ b/Engine/source/gui/3d/guiTSControl.cpp @@ -539,7 +539,7 @@ DefineEngineMethod( GuiTSCtrl, getWorldToScreenScale, Point2F, (),, //----------------------------------------------------------------------------- -DefineEngineMethod( GuiTSCtrl, calculateViewDistance, float, ( float radius ),, +DefineEngineMethod( GuiTSCtrl, calculateViewDistance, F32, ( F32 radius ),, "Given the camera's current FOV, get the distance from the camera's viewpoint at which the given radius will fit in the render area.\n" "@param radius Radius in world-space units which should fit in the view.\n" "@return The distance from the viewpoint at which the given radius would be fully visible." ) diff --git a/Engine/source/gui/buttons/guiIconButtonCtrl.cpp b/Engine/source/gui/buttons/guiIconButtonCtrl.cpp index 55a0efb16..b4aed4ec7 100644 --- a/Engine/source/gui/buttons/guiIconButtonCtrl.cpp +++ b/Engine/source/gui/buttons/guiIconButtonCtrl.cpp @@ -230,7 +230,7 @@ void GuiIconButtonCtrl::renderButton( Point2I &offset, const RectI& updateRect ) bool highlight = mMouseOver; bool depressed = mDepressed; - ColorI fontColor = mActive ? (highlight ? mProfile->mFontColor : mProfile->mFontColor) : mProfile->mFontColorNA; + ColorI fontColor = mActive ? (highlight ? mProfile->mFontColorHL : mProfile->mFontColor) : mProfile->mFontColorNA; RectI boundsRect(offset, getExtent()); @@ -436,4 +436,4 @@ DefineEngineMethod( GuiIconButtonCtrl, setBitmap, void, (const char* buttonFilen char* argBuffer = Con::getArgBuffer( 512 ); Platform::makeFullPathName( buttonFilename, argBuffer, 512 ); object->setBitmap( argBuffer ); -} \ No newline at end of file +} diff --git a/Engine/source/gui/containers/guiWindowCtrl.cpp b/Engine/source/gui/containers/guiWindowCtrl.cpp index 724154910..0132a75d6 100644 --- a/Engine/source/gui/containers/guiWindowCtrl.cpp +++ b/Engine/source/gui/containers/guiWindowCtrl.cpp @@ -1478,7 +1478,7 @@ void GuiWindowCtrl::positionButtons(void) // Until a pref, if alignment is LEFT, put buttons RIGHT justified. // ELSE, put buttons LEFT justified. - int closeLeft = mainOff.x, closeTop = mainOff.y, closeOff = buttonWidth + 2; + S32 closeLeft = mainOff.x, closeTop = mainOff.y, closeOff = buttonWidth + 2; if ( mProfile->mAlignment == GuiControlProfile::LeftJustify ) { closeOff = -closeOff; diff --git a/Engine/source/gui/controls/guiBitmapCtrl.cpp b/Engine/source/gui/controls/guiBitmapCtrl.cpp index 29766d197..e95263701 100644 --- a/Engine/source/gui/controls/guiBitmapCtrl.cpp +++ b/Engine/source/gui/controls/guiBitmapCtrl.cpp @@ -178,13 +178,13 @@ void GuiBitmapCtrl::onRender(Point2I offset, const RectI &updateRect) GFXTextureObject* texture = mTextureObject; RectI srcRegion; RectI dstRegion; - float xdone = ((float)getExtent().x/(float)texture->mBitmapSize.x)+1; - float ydone = ((float)getExtent().y/(float)texture->mBitmapSize.y)+1; + F32 xdone = ((F32)getExtent().x/(F32)texture->mBitmapSize.x)+1; + F32 ydone = ((F32)getExtent().y/(F32)texture->mBitmapSize.y)+1; - int xshift = mStartPoint.x%texture->mBitmapSize.x; - int yshift = mStartPoint.y%texture->mBitmapSize.y; - for(int y = 0; y < ydone; ++y) - for(int x = 0; x < xdone; ++x) + S32 xshift = mStartPoint.x%texture->mBitmapSize.x; + S32 yshift = mStartPoint.y%texture->mBitmapSize.y; + for(S32 y = 0; y < ydone; ++y) + for(S32 x = 0; x < xdone; ++x) { srcRegion.set(0,0,texture->mBitmapSize.x,texture->mBitmapSize.y); dstRegion.set( ((texture->mBitmapSize.x*x)+offset.x)-xshift, diff --git a/Engine/source/gui/controls/guiFileTreeCtrl.cpp b/Engine/source/gui/controls/guiFileTreeCtrl.cpp index 7fe7e3ba4..60e0c3b86 100644 --- a/Engine/source/gui/controls/guiFileTreeCtrl.cpp +++ b/Engine/source/gui/controls/guiFileTreeCtrl.cpp @@ -260,7 +260,7 @@ bool GuiFileTreeCtrl::matchesFilters(const char* filename) if( !mFilters.size() ) return true; - for(int i = 0; i < mFilters.size(); i++) + for(S32 i = 0; i < mFilters.size(); i++) { if(FindMatch::isMatch( mFilters[i], filename)) return true; diff --git a/Engine/source/gui/controls/guiGameListOptionsCtrl.cpp b/Engine/source/gui/controls/guiGameListOptionsCtrl.cpp index 42eb38092..1c5bdba0f 100644 --- a/Engine/source/gui/controls/guiGameListOptionsCtrl.cpp +++ b/Engine/source/gui/controls/guiGameListOptionsCtrl.cpp @@ -213,7 +213,7 @@ void GuiGameListOptionsCtrl::addRow(const char* label, const char* optionsList, Row * row = new Row(); Vector options( __FILE__, __LINE__ ); S32 count = StringUnit::getUnitCount(optionsList, DELIM); - for (int i = 0; i < count; ++i) + for (S32 i = 0; i < count; ++i) { const char * option = StringUnit::getUnit(optionsList, i, DELIM); options.push_back(StringTable->insert(option, true)); @@ -238,7 +238,7 @@ void GuiGameListOptionsCtrl::setOptions(S32 rowIndex, const char * optionsList) S32 count = StringUnit::getUnitCount(optionsList, DELIM); row->mOptions.setSize(count); - for (int i = 0; i < count; ++i) + for (S32 i = 0; i < count; ++i) { const char * option = StringUnit::getUnit(optionsList, i, DELIM); row->mOptions[i] = StringTable->insert(option, true); diff --git a/Engine/source/gui/controls/guiMLTextCtrl.cpp b/Engine/source/gui/controls/guiMLTextCtrl.cpp index 63f9c7cdd..4233190c6 100644 --- a/Engine/source/gui/controls/guiMLTextCtrl.cpp +++ b/Engine/source/gui/controls/guiMLTextCtrl.cpp @@ -91,7 +91,7 @@ GFX_ImplementTextureProfile(GFXMLTextureProfile, GFXTextureProfile::DiffuseMap, GFXTextureProfile::PreserveSize | GFXTextureProfile::Static, - GFXTextureProfile::None); + GFXTextureProfile::NONE); const U32 GuiMLTextCtrl::csmTextBufferGrowthSize = 1024; @@ -138,7 +138,7 @@ DefineEngineMethod( GuiMLTextCtrl, addText, void, ( const char* text, bool refor object->addText(text, dStrlen(text), reformat); } -DefineEngineMethod( GuiMLTextCtrl, setCursorPosition, bool, (int newPos),, +DefineEngineMethod( GuiMLTextCtrl, setCursorPosition, bool, (S32 newPos),, "@brief Change the text cursor's position to a new defined offset within the text in the control.\n\n" "@param newPos Offset to place cursor.\n" "@tsexample\n" @@ -153,7 +153,7 @@ DefineEngineMethod( GuiMLTextCtrl, setCursorPosition, bool, (int newPos),, return object->setCursorPosition(newPos); } -DefineEngineMethod( GuiMLTextCtrl, scrollToTag, void, (int tagID),, +DefineEngineMethod( GuiMLTextCtrl, scrollToTag, void, (S32 tagID),, "@brief Scroll down to a specified tag.\n\n" "Detailed description\n\n" "@param tagID TagID to scroll the control to\n" diff --git a/Engine/source/gui/controls/guiPopUpCtrl.cpp b/Engine/source/gui/controls/guiPopUpCtrl.cpp index e4b2903f7..b67776461 100644 --- a/Engine/source/gui/controls/guiPopUpCtrl.cpp +++ b/Engine/source/gui/controls/guiPopUpCtrl.cpp @@ -1011,8 +1011,8 @@ void GuiPopUpMenuCtrl::onRender( Point2I offset, const RectI &updateRect ) { // We're making use of a bitmap border, so take into account the // right cap of the border. - RectI* mBitmapBounds = mProfile->mBitmapArrayRects.address(); - localStart.x = getWidth() - mBitmapBounds[2].extent.x - txt_w; + RectI* bitmapBounds = mProfile->mBitmapArrayRects.address(); + localStart.x = getWidth() - bitmapBounds[2].extent.x - txt_w; } else { @@ -1024,8 +1024,8 @@ void GuiPopUpMenuCtrl::onRender( Point2I offset, const RectI &updateRect ) { // We're making use of a bitmap border, so take into account the // right cap of the border. - RectI* mBitmapBounds = mProfile->mBitmapArrayRects.address(); - localStart.x = (getWidth() - mBitmapBounds[2].extent.x - txt_w) / 2; + RectI* bitmapBounds = mProfile->mBitmapArrayRects.address(); + localStart.x = (getWidth() - bitmapBounds[2].extent.x - txt_w) / 2; } else { @@ -1043,8 +1043,8 @@ void GuiPopUpMenuCtrl::onRender( Point2I offset, const RectI &updateRect ) { // We're making use of a bitmap border, so take into account the // right cap of the border. - RectI* mBitmapBounds = mProfile->mBitmapArrayRects.address(); - localStart.x = getWidth() - mBitmapBounds[2].extent.x - txt_w; + RectI* bitmapBounds = mProfile->mBitmapArrayRects.address(); + localStart.x = getWidth() - bitmapBounds[2].extent.x - txt_w; } else { @@ -1095,8 +1095,8 @@ void GuiPopUpMenuCtrl::onRender( Point2I offset, const RectI &updateRect ) { // We're making use of a bitmap border, so take into account the // right cap of the border. - RectI* mBitmapBounds = mProfile->mBitmapArrayRects.address(); - Point2I textpos = localToGlobalCoord( Point2I( getWidth() - txt_w - mBitmapBounds[2].extent.x, localStart.y ) ); + RectI* bitmapBounds = mProfile->mBitmapArrayRects.address(); + Point2I textpos = localToGlobalCoord( Point2I( getWidth() - txt_w - bitmapBounds[2].extent.x, localStart.y ) ); GFX->getDrawUtil()->drawText( mProfile->mFont, textpos, buff, mProfile->mFontColors ); } else diff --git a/Engine/source/gui/controls/guiPopUpCtrlEx.cpp b/Engine/source/gui/controls/guiPopUpCtrlEx.cpp index 275faf75c..4db07ed33 100644 --- a/Engine/source/gui/controls/guiPopUpCtrlEx.cpp +++ b/Engine/source/gui/controls/guiPopUpCtrlEx.cpp @@ -1167,8 +1167,8 @@ void GuiPopUpMenuCtrlEx::onRender(Point2I offset, const RectI &updateRect) { // We're making use of a bitmap border, so take into account the // right cap of the border. - RectI* mBitmapBounds = mProfile->mBitmapArrayRects.address(); - localStart.x = getWidth() - mBitmapBounds[2].extent.x - txt_w; + RectI* bitmapBounds = mProfile->mBitmapArrayRects.address(); + localStart.x = getWidth() - bitmapBounds[2].extent.x - txt_w; } else { @@ -1180,8 +1180,8 @@ void GuiPopUpMenuCtrlEx::onRender(Point2I offset, const RectI &updateRect) { // We're making use of a bitmap border, so take into account the // right cap of the border. - RectI* mBitmapBounds = mProfile->mBitmapArrayRects.address(); - localStart.x = (getWidth() - mBitmapBounds[2].extent.x - txt_w) / 2; + RectI* bitmapBounds = mProfile->mBitmapArrayRects.address(); + localStart.x = (getWidth() - bitmapBounds[2].extent.x - txt_w) / 2; } else { @@ -1199,8 +1199,8 @@ void GuiPopUpMenuCtrlEx::onRender(Point2I offset, const RectI &updateRect) { // We're making use of a bitmap border, so take into account the // right cap of the border. - RectI* mBitmapBounds = mProfile->mBitmapArrayRects.address(); - localStart.x = getWidth() - mBitmapBounds[2].extent.x - txt_w; + RectI* bitmapBounds = mProfile->mBitmapArrayRects.address(); + localStart.x = getWidth() - bitmapBounds[2].extent.x - txt_w; } else { @@ -1251,8 +1251,8 @@ void GuiPopUpMenuCtrlEx::onRender(Point2I offset, const RectI &updateRect) { // We're making use of a bitmap border, so take into account the // right cap of the border. - RectI* mBitmapBounds = mProfile->mBitmapArrayRects.address(); - Point2I textpos = localToGlobalCoord( Point2I( getWidth() - txt_w - mBitmapBounds[2].extent.x, localStart.y ) ); + RectI* bitmapBounds = mProfile->mBitmapArrayRects.address(); + Point2I textpos = localToGlobalCoord( Point2I( getWidth() - txt_w - bitmapBounds[2].extent.x, localStart.y ) ); GFX->getDrawUtil()->drawText( mProfile->mFont, textpos, buff, mProfile->mFontColors ); } else diff --git a/Engine/source/gui/controls/guiTextEditCtrl.cpp b/Engine/source/gui/controls/guiTextEditCtrl.cpp index 1748d5ce7..c451400b7 100644 --- a/Engine/source/gui/controls/guiTextEditCtrl.cpp +++ b/Engine/source/gui/controls/guiTextEditCtrl.cpp @@ -1688,7 +1688,7 @@ DefineEngineMethod( GuiTextEditCtrl, getCursorPos, S32, (),, return( object->getCursorPos() ); } -DefineEngineMethod( GuiTextEditCtrl, setCursorPos, void, (int position),, +DefineEngineMethod( GuiTextEditCtrl, setCursorPos, void, (S32 position),, "@brief Sets the text cursor at the defined position within the control.\n\n" "@param position Text position to set the text cursor.\n" "@tsexample\n" diff --git a/Engine/source/gui/controls/guiTextListCtrl.cpp b/Engine/source/gui/controls/guiTextListCtrl.cpp index 7c6b9602a..dfd191795 100644 --- a/Engine/source/gui/controls/guiTextListCtrl.cpp +++ b/Engine/source/gui/controls/guiTextListCtrl.cpp @@ -79,12 +79,12 @@ IMPLEMENT_CALLBACK( GuiTextListCtrl, onDeleteKey, void, ( const char* id ),( id "@see GuiControl\n\n" ); -static int sortColumn; +static S32 sortColumn; static bool sIncreasing; static const char *getColumn(const char *text) { - int ct = sortColumn; + S32 ct = sortColumn; while(ct--) { text = dStrchr(text, '\t'); @@ -530,7 +530,7 @@ DefineEngineMethod( GuiTextListCtrl, getSelectedId, S32, (),, return object->getSelectedId(); } -DefineEngineMethod( GuiTextListCtrl, setSelectedById, void, (int id),, +DefineEngineMethod( GuiTextListCtrl, setSelectedById, void, (S32 id),, "@brief Finds the specified entry by id, then marks its row as selected.\n\n" "@param id Entry within the text list to make selected.\n" "@tsexample\n" @@ -548,7 +548,7 @@ DefineEngineMethod( GuiTextListCtrl, setSelectedById, void, (int id),, object->setSelectedCell(Point2I(0, index)); } -DefineEngineMethod( GuiTextListCtrl, setSelectedRow, void, (int rowNum),, +DefineEngineMethod( GuiTextListCtrl, setSelectedRow, void, (S32 rowNum),, "@briefSelects the specified row.\n\n" "@param rowNum Row number to set selected.\n" "@tsexample\n" @@ -584,7 +584,7 @@ DefineEngineMethod( GuiTextListCtrl, clearSelection, void, (),, object->setSelectedCell(Point2I(-1, -1)); } -DefineEngineMethod( GuiTextListCtrl, addRow, S32, (int id, const char* text, int index),(0,"",-1), +DefineEngineMethod( GuiTextListCtrl, addRow, S32, (S32 id, const char* text, S32 index),(0,"",-1), "@brief Adds a new row at end of the list with the defined id and text.\n" "If index is used, then the new row is inserted at the row location of 'index'.\n\n" "@param id Id of the new row.\n" @@ -612,7 +612,7 @@ DefineEngineMethod( GuiTextListCtrl, addRow, S32, (int id, const char* text, int return ret; } -DefineEngineMethod( GuiTextListCtrl, setRowById, void, (int id, const char* text),, +DefineEngineMethod( GuiTextListCtrl, setRowById, void, (S32 id, const char* text),, "@brief Sets the text at the defined id.\n\n" "@param id Id to change.\n" "@param text Text to use at the Id.\n" @@ -629,7 +629,7 @@ DefineEngineMethod( GuiTextListCtrl, setRowById, void, (int id, const char* text object->setEntry(id, text); } -DefineEngineMethod( GuiTextListCtrl, sort, void, ( int columnId, bool increasing ), ( true ), +DefineEngineMethod( GuiTextListCtrl, sort, void, ( S32 columnId, bool increasing ), ( true ), "@brief Performs a standard (alphabetical) sort on the values in the specified column.\n\n" "@param columnId Column ID to perform the sort on.\n" "@param increasing If false, sort will be performed in reverse.\n" @@ -646,7 +646,7 @@ DefineEngineMethod( GuiTextListCtrl, sort, void, ( int columnId, bool increasing object->sort( columnId, increasing ); } -DefineEngineMethod( GuiTextListCtrl, sortNumerical, void, (int columnID, bool increasing), ( true ), +DefineEngineMethod( GuiTextListCtrl, sortNumerical, void, (S32 columnID, bool increasing), ( true ), "@brief Perform a numerical sort on the values in the specified column.\n\n" "Detailed description\n\n" "@param columnId Column ID to perform the sort on.\n" @@ -687,7 +687,7 @@ DefineEngineMethod( GuiTextListCtrl, rowCount, S32, (),, return object->getNumEntries(); } -DefineEngineMethod( GuiTextListCtrl, getRowId, S32, (int index),, +DefineEngineMethod( GuiTextListCtrl, getRowId, S32, (S32 index),, "@brief Get the row ID for an index.\n\n" "@param index Index to get the RowID at\n" "@tsexample\n" @@ -705,7 +705,7 @@ DefineEngineMethod( GuiTextListCtrl, getRowId, S32, (int index),, return object->mList[index].id; } -DefineEngineMethod( GuiTextListCtrl, getRowTextById, const char*, (int id),, +DefineEngineMethod( GuiTextListCtrl, getRowTextById, const char*, (S32 id),, "@brief Get the text of a row with the specified id.\n\n" "@tsexample\n" "// Define the id\n" @@ -722,7 +722,7 @@ DefineEngineMethod( GuiTextListCtrl, getRowTextById, const char*, (int id),, return object->mList[index].text; } -DefineEngineMethod( GuiTextListCtrl, getRowNumById, S32, (int id),, +DefineEngineMethod( GuiTextListCtrl, getRowNumById, S32, (S32 id),, "@brief Get the row number for a specified id.\n\n" "@param id Id to get the row number at\n" "@tsexample\n" @@ -739,7 +739,7 @@ DefineEngineMethod( GuiTextListCtrl, getRowNumById, S32, (int id),, return index; } -DefineEngineMethod( GuiTextListCtrl, getRowText, const char*, (int index),, +DefineEngineMethod( GuiTextListCtrl, getRowText, const char*, (S32 index),, "@brief Get the text of the row with the specified index.\n\n" "@param index Row index to acquire the text at.\n" "@tsexample\n" @@ -756,7 +756,7 @@ DefineEngineMethod( GuiTextListCtrl, getRowText, const char*, (int index),, return object->mList[index].text; } -DefineEngineMethod( GuiTextListCtrl, removeRowById, void, (int id),, +DefineEngineMethod( GuiTextListCtrl, removeRowById, void, (S32 id),, "@brief Remove row with the specified id.\n\n" "@param id Id to remove the row entry at\n" "@tsexample\n" @@ -770,7 +770,7 @@ DefineEngineMethod( GuiTextListCtrl, removeRowById, void, (int id),, object->removeEntry(id); } -DefineEngineMethod( GuiTextListCtrl, removeRow, void, (int index),, +DefineEngineMethod( GuiTextListCtrl, removeRow, void, (S32 index),, "@brief Remove a row from the table, based on its index.\n\n" "@param index Row index to remove from the list.\n" "@tsexample\n" @@ -784,7 +784,7 @@ DefineEngineMethod( GuiTextListCtrl, removeRow, void, (int index),, object->removeEntryByIndex(index); } -DefineEngineMethod( GuiTextListCtrl, scrollVisible, void, (int rowNum),, +DefineEngineMethod( GuiTextListCtrl, scrollVisible, void, (S32 rowNum),, "@brief Scroll so the specified row is visible\n\n" "@param rowNum Row number to make visible\n" "@tsexample\n" @@ -813,7 +813,7 @@ DefineEngineMethod( GuiTextListCtrl, findTextIndex, S32, (const char* needle),, return( object->findEntryByText(needle) ); } -DefineEngineMethod( GuiTextListCtrl, setRowActive, void, (int rowNum, bool active),, +DefineEngineMethod( GuiTextListCtrl, setRowActive, void, (S32 rowNum, bool active),, "@brief Mark a specified row as active/not.\n\n" "@param rowNum Row number to change the active state.\n" "@param active Boolean active state to set the row number.\n" @@ -830,7 +830,7 @@ DefineEngineMethod( GuiTextListCtrl, setRowActive, void, (int rowNum, bool activ object->setEntryActive( U32( rowNum ), active ); } -DefineEngineMethod( GuiTextListCtrl, isRowActive, bool, (int rowNum),, +DefineEngineMethod( GuiTextListCtrl, isRowActive, bool, (S32 rowNum),, "@brief Check if the specified row is currently active or not.\n\n" "@param rowNum Row number to check the active state.\n" "@tsexample\n" diff --git a/Engine/source/gui/controls/guiTreeViewCtrl.cpp b/Engine/source/gui/controls/guiTreeViewCtrl.cpp index b6d2c99de..bf55bf3a2 100644 --- a/Engine/source/gui/controls/guiTreeViewCtrl.cpp +++ b/Engine/source/gui/controls/guiTreeViewCtrl.cpp @@ -3583,7 +3583,7 @@ void GuiTreeViewCtrl::onMiddleMouseDown(const GuiEvent & event) for (S32 j = 0; j < mSelected.size(); j++) { Con::printf("%d", mSelected[j]); } - S32 mCurrentDragCell = mMouseOverCell.y; + mCurrentDragCell = mMouseOverCell.y; S32 midpCell = (mCurrentDragCell) * mItemHeight + (mItemHeight/2); S32 currentY = pt.y; S32 yDiff = currentY-midpCell; @@ -3648,7 +3648,7 @@ void GuiTreeViewCtrl::onMouseDown(const GuiEvent & event) break; } } - S32 mCurrentDragCell = mMouseOverCell.y; + mCurrentDragCell = mMouseOverCell.y; if (mVisibleItems[firstSelectedIndex] != firstItem ) { /* @@ -4920,7 +4920,7 @@ ConsoleMethod( GuiTreeViewCtrl, open, void, 3, 4, "(SimSet obj, bool okToEdit=tr ConsoleMethod( GuiTreeViewCtrl, setItemTooltip, void, 4, 4, "( int id, string text ) - Set the tooltip to show for the given item." ) { - int id = dAtoi( argv[ 2 ] ); + S32 id = dAtoi( argv[ 2 ] ); GuiTreeViewCtrl::Item* item = object->getItem( id ); if( !item ) @@ -4934,7 +4934,7 @@ ConsoleMethod( GuiTreeViewCtrl, setItemTooltip, void, 4, 4, "( int id, string te ConsoleMethod( GuiTreeViewCtrl, setItemImages, void, 5, 5, "( int id, int normalImage, int expandedImage ) - Sets the normal and expanded images to show for the given item." ) { - int id = dAtoi( argv[ 2 ] ); + S32 id = dAtoi( argv[ 2 ] ); GuiTreeViewCtrl::Item* item = object->getItem( id ); if( !item ) @@ -4949,7 +4949,7 @@ ConsoleMethod( GuiTreeViewCtrl, setItemImages, void, 5, 5, "( int id, int normal ConsoleMethod( GuiTreeViewCtrl, isParentItem, bool, 3, 3, "( int id ) - Returns true if the given item contains child items." ) { - int id = dAtoi( argv[ 2 ] ); + S32 id = dAtoi( argv[ 2 ] ); if( !id && object->getItemCount() ) return true; @@ -5065,7 +5065,7 @@ ConsoleMethod(GuiTreeViewCtrl, getSelectedObjectList, const char*, 2, 2, dSprintf(buff,1024,""); const Vector< GuiTreeViewCtrl::Item* > selectedItems = object->getSelectedItems(); - for(int i = 0; i < selectedItems.size(); i++) + for(S32 i = 0; i < selectedItems.size(); i++) { GuiTreeViewCtrl::Item *item = selectedItems[i]; @@ -5130,7 +5130,7 @@ ConsoleMethod(GuiTreeViewCtrl, getSelectedItemList,const char*, 2,2,"returns a s dSprintf(buff,1024,""); const Vector< S32 >& selected = object->getSelected(); - for(int i = 0; i < selected.size(); i++) + for(S32 i = 0; i < selected.size(); i++) { S32 id = selected[i]; //get the current length of the buffer diff --git a/Engine/source/gui/core/guiCanvas.cpp b/Engine/source/gui/core/guiCanvas.cpp index 65792e81b..cbef4673c 100644 --- a/Engine/source/gui/core/guiCanvas.cpp +++ b/Engine/source/gui/core/guiCanvas.cpp @@ -1561,7 +1561,7 @@ void GuiCanvas::setupFences() mFences = new GFXFence*[mNumFences]; // Allocate the new fences - for( int i = 0; i < mNumFences; i++ ) + for( S32 i = 0; i < mNumFences; i++ ) mFences[i] = GFX->createFence(); } diff --git a/Engine/source/gui/core/guiTypes.cpp b/Engine/source/gui/core/guiTypes.cpp index 31929f78c..7332459b4 100644 --- a/Engine/source/gui/core/guiTypes.cpp +++ b/Engine/source/gui/core/guiTypes.cpp @@ -63,13 +63,13 @@ GFX_ImplementTextureProfile(GFXGuiCursorProfile, GFXTextureProfile::DiffuseMap, GFXTextureProfile::PreserveSize | GFXTextureProfile::Static, - GFXTextureProfile::None); + GFXTextureProfile::NONE); GFX_ImplementTextureProfile(GFXDefaultGUIProfile, GFXTextureProfile::DiffuseMap, GFXTextureProfile::PreserveSize | GFXTextureProfile::Static | GFXTextureProfile::NoPadding, - GFXTextureProfile::None); + GFXTextureProfile::NONE); GuiCursor::GuiCursor() diff --git a/Engine/source/gui/editor/guiDebugger.cpp b/Engine/source/gui/editor/guiDebugger.cpp index 625704bee..dbebc4e83 100644 --- a/Engine/source/gui/editor/guiDebugger.cpp +++ b/Engine/source/gui/editor/guiDebugger.cpp @@ -79,7 +79,7 @@ ConsoleMethod(DbgFileView, getCurrentLine, const char *, 2, 2, "()" S32 lineNum; const char *file = object->getCurrentLine(lineNum); char* ret = Con::getReturnBuffer(256); - dSprintf(ret, sizeof(ret), "%s\t%d", file, lineNum); + dSprintf(ret, 256, "%s\t%d", file, lineNum); return ret; } diff --git a/Engine/source/gui/editor/guiEaseViewCtrl.cpp b/Engine/source/gui/editor/guiEaseViewCtrl.cpp index 87dff9d5e..59713b682 100644 --- a/Engine/source/gui/editor/guiEaseViewCtrl.cpp +++ b/Engine/source/gui/editor/guiEaseViewCtrl.cpp @@ -97,7 +97,7 @@ void GuiEaseViewCtrl::onRender(Point2I offset, const RectI &updateRect) // Draw curve. - for( int i = 1; i <= numPoints; ++ i ) + for( S32 i = 1; i <= numPoints; ++ i ) { F32 x = ( F32 ) i / ( F32 ) numPoints; F32 y = mEase.getValue( x, 0, 1, 1 ); diff --git a/Engine/source/gui/editor/guiGraphCtrl.cpp b/Engine/source/gui/editor/guiGraphCtrl.cpp index f056bb44d..e00998b0b 100644 --- a/Engine/source/gui/editor/guiGraphCtrl.cpp +++ b/Engine/source/gui/editor/guiGraphCtrl.cpp @@ -274,7 +274,7 @@ void GuiGraphCtrl::addDatum(S32 plotID, F32 v) //----------------------------------------------------------------------------- -float GuiGraphCtrl::getDatum( int plotID, int sample) +F32 GuiGraphCtrl::getDatum( S32 plotID, S32 sample) { AssertFatal(plotID > -1 && plotID < MaxPlots, "Invalid plot specified!"); AssertFatal(sample > -1 && sample < MaxDataPoints, "Invalid sample specified!"); diff --git a/Engine/source/gui/editor/guiImageList.cpp b/Engine/source/gui/editor/guiImageList.cpp index 18cb973ed..c51f715b6 100644 --- a/Engine/source/gui/editor/guiImageList.cpp +++ b/Engine/source/gui/editor/guiImageList.cpp @@ -182,7 +182,7 @@ DefineEngineMethod( GuiImageList, count, S32, (),, return object->Count(); } -DefineEngineMethod( GuiImageList, remove, bool, (int index),, +DefineEngineMethod( GuiImageList, remove, bool, (S32 index),, "@brief Removes an image from the list by index.\n\n" "@param index Image index to remove.\n" "@tsexample\n" diff --git a/Engine/source/gui/editor/guiMenuBar.cpp b/Engine/source/gui/editor/guiMenuBar.cpp index c2bdbb6a7..c8abfe72f 100644 --- a/Engine/source/gui/editor/guiMenuBar.cpp +++ b/Engine/source/gui/editor/guiMenuBar.cpp @@ -193,7 +193,7 @@ DefineEngineMethod( GuiMenuBar, setMenuMargins, void, (S32 horizontalMargin, S32 object->mBitmapMargin = bitmapToTextSpacing; } -DefineEngineMethod(GuiMenuBar, addMenu, void, (const char* menuText, int menuId),, +DefineEngineMethod(GuiMenuBar, addMenu, void, (const char* menuText, S32 menuId),, "@brief Adds a new menu to the menu bar.\n\n" "@param menuText Text to display for the new menu item.\n" "@param menuId ID for the new menu item.\n" @@ -215,7 +215,7 @@ DefineEngineMethod(GuiMenuBar, addMenu, void, (const char* menuText, int menuId) object->addMenu(menuText, menuId); } -DefineEngineMethod(GuiMenuBar, addMenuItem, void, (const char* targetMenu, const char* menuItemText, int menuItemId, const char* accelerator, int checkGroup), +DefineEngineMethod(GuiMenuBar, addMenuItem, void, (const char* targetMenu, const char* menuItemText, S32 menuItemId, const char* accelerator, int checkGroup), ("","",0,NULL,-1), "@brief Adds a menu item to the specified menu. The menu argument can be either the text of a menu or its id.\n\n" "@param menu Menu name or menu Id to add the new item to.\n" @@ -496,7 +496,7 @@ DefineEngineMethod(GuiMenuBar, setMenuItemVisible, void, (const char* menuTarget menuItem->visible = isVisible; } -DefineEngineMethod(GuiMenuBar, setMenuItemBitmap, void, (const char* menuTarget, const char* menuItemTarget, int bitmapIndex),, +DefineEngineMethod(GuiMenuBar, setMenuItemBitmap, void, (const char* menuTarget, const char* menuItemTarget, S32 bitmapIndex),, "@brief Sets the specified menu item bitmap index in the bitmap array. Setting the item's index to -1 will remove any bitmap.\n\n" "@param menuTarget Menu to affect the menuItem in\n" "@param menuItem Menu item to affect\n" diff --git a/Engine/source/gui/editor/guiParticleGraphCtrl.cpp b/Engine/source/gui/editor/guiParticleGraphCtrl.cpp index 37cc0365e..2bfbbf467 100644 --- a/Engine/source/gui/editor/guiParticleGraphCtrl.cpp +++ b/Engine/source/gui/editor/guiParticleGraphCtrl.cpp @@ -40,7 +40,7 @@ ConsoleDocClass( GuiParticleGraphCtrl, GuiParticleGraphCtrl::GuiParticleGraphCtrl() { - for(int i = 0; i < MaxPlots; i++) + for(S32 i = 0; i < MaxPlots; i++) { mPlots[i].mGraphColor = ColorF(1.0, 1.0, 1.0); VECTOR_SET_ASSOCIATION(mPlots[i].mGraphData); @@ -140,7 +140,7 @@ void GuiParticleGraphCtrl::onRender(Point2I offset, const RectI &updateRect) ColorF color(1.0f, 1.0f, 1.0f, 0.5f); pDrawUtil->drawRectFill(updateRect, color); - for (int k = 0; k < MaxPlots; k++) + for (S32 k = 0; k < MaxPlots; k++) { // Nothing to graph if ((mPlots[k].mGraphData.size() == 0) || (mPlots[k].mHidden == true)) diff --git a/Engine/source/gui/editor/guiShapeEdPreview.cpp b/Engine/source/gui/editor/guiShapeEdPreview.cpp index 128266f6d..098ff38f3 100644 --- a/Engine/source/gui/editor/guiShapeEdPreview.cpp +++ b/Engine/source/gui/editor/guiShapeEdPreview.cpp @@ -42,7 +42,7 @@ static const F32 sMoveScaler = 50.0f; static const F32 sZoomScaler = 200.0f; -static const int sNodeRectSize = 16; +static const S32 sNodeRectSize = 16; IMPLEMENT_CONOBJECT( GuiShapeEdPreview ); diff --git a/Engine/source/gui/editor/inspector/field.cpp b/Engine/source/gui/editor/inspector/field.cpp index 64b434abc..ce5b0a560 100644 --- a/Engine/source/gui/editor/inspector/field.cpp +++ b/Engine/source/gui/editor/inspector/field.cpp @@ -58,7 +58,7 @@ GuiInspectorField::GuiInspectorField( GuiInspector* inspector, setCanSave( false ); setBounds(0,0,100,18); - if( field ) + if( field != NULL ) _setFieldDocs( field->pFieldDocs ); } @@ -378,8 +378,9 @@ void GuiInspectorField::setInspectorField( AbstractClassRep::Field *field, Strin mCaption = getFieldName(); else mCaption = caption; - - _setFieldDocs( mField->pFieldDocs ); + + if ( mField != NULL ) + _setFieldDocs( mField->pFieldDocs ); } //----------------------------------------------------------------------------- diff --git a/Engine/source/gui/game/guiIdleCamFadeBitmapCtrl.cpp b/Engine/source/gui/game/guiIdleCamFadeBitmapCtrl.cpp index 641f629cb..d648a4177 100644 --- a/Engine/source/gui/game/guiIdleCamFadeBitmapCtrl.cpp +++ b/Engine/source/gui/game/guiIdleCamFadeBitmapCtrl.cpp @@ -123,13 +123,13 @@ public: GFXTextureObject* texture = mTextureObject; RectI srcRegion; RectI dstRegion; - float xdone = ((float)getExtent().x/(float)texture->mBitmapSize.x)+1; - float ydone = ((float)getExtent().y/(float)texture->mBitmapSize.y)+1; + F32 xdone = ((F32)getExtent().x/(F32)texture->mBitmapSize.x)+1; + F32 ydone = ((F32)getExtent().y/(F32)texture->mBitmapSize.y)+1; - int xshift = mStartPoint.x%texture->mBitmapSize.x; - int yshift = mStartPoint.y%texture->mBitmapSize.y; - for(int y = 0; y < ydone; ++y) - for(int x = 0; x < xdone; ++x) + S32 xshift = mStartPoint.x%texture->mBitmapSize.x; + S32 yshift = mStartPoint.y%texture->mBitmapSize.y; + for(S32 y = 0; y < ydone; ++y) + for(S32 x = 0; x < xdone; ++x) { srcRegion.set(0,0,texture->mBitmapSize.x,texture->mBitmapSize.y); dstRegion.set( ((texture->mBitmapSize.x*x)+offset.x)-xshift, diff --git a/Engine/source/gui/worldEditor/editTSCtrl.cpp b/Engine/source/gui/worldEditor/editTSCtrl.cpp index 123362123..7781525c6 100644 --- a/Engine/source/gui/worldEditor/editTSCtrl.cpp +++ b/Engine/source/gui/worldEditor/editTSCtrl.cpp @@ -1298,7 +1298,7 @@ DefineEngineMethod( EditTSCtrl, renderCircle, void, ( Point3F pos, Point3F norma PrimBuild::begin( GFXLineStrip, points.size() + 1 ); - for( int i = 0; i < points.size(); i++ ) + for( S32 i = 0; i < points.size(); i++ ) PrimBuild::vertex3fv( points[i] ); // GFX does not have a LineLoop primitive, so connect the last line @@ -1321,7 +1321,7 @@ DefineEngineMethod( EditTSCtrl, renderCircle, void, ( Point3F pos, Point3F norma PrimBuild::vertex3fv( pos ); // Edge verts - for( int i = 0; i < points.size(); i++ ) + for( S32 i = 0; i < points.size(); i++ ) PrimBuild::vertex3fv( points[i] ); PrimBuild::vertex3fv( points[0] ); diff --git a/Engine/source/lighting/advanced/advancedLightManager.cpp b/Engine/source/lighting/advanced/advancedLightManager.cpp index 9a911acfb..7034545d7 100644 --- a/Engine/source/lighting/advanced/advancedLightManager.cpp +++ b/Engine/source/lighting/advanced/advancedLightManager.cpp @@ -606,7 +606,7 @@ GFXVertexBufferHandle AdvancedLightManager::g mConeIndices.lock( &idx ); // Build the cone U32 idxIdx = 0; - for( int i = 1; i < numPoints + 1; i++ ) + for( U32 i = 1; i < numPoints + 1; i++ ) { idx[idxIdx++] = 0; // Triangles on cone start at top point idx[idxIdx++] = i; @@ -614,7 +614,7 @@ GFXVertexBufferHandle AdvancedLightManager::g } // Build the bottom of the cone (reverse winding order) - for( int i = 1; i < numPoints - 1; i++ ) + for( U32 i = 1; i < numPoints - 1; i++ ) { idx[idxIdx++] = 1; idx[idxIdx++] = i + 2; diff --git a/Engine/source/lighting/advanced/advancedLightingFeatures.cpp b/Engine/source/lighting/advanced/advancedLightingFeatures.cpp index fb61494b5..32deccc55 100644 --- a/Engine/source/lighting/advanced/advancedLightingFeatures.cpp +++ b/Engine/source/lighting/advanced/advancedLightingFeatures.cpp @@ -55,7 +55,7 @@ void AdvancedLightingFeatures::registerFeatures( const GFXFormat &prepassTargetF if(GFX->getAdapterType() == OpenGL) { #if defined( TORQUE_OS_MAC ) || defined( TORQUE_OS_LINUX ) - cond = new GBufferConditionerGLSL( prepassTargetFormat ); + cond = new GBufferConditionerGLSL( prepassTargetFormat, GBufferConditionerGLSL::ViewSpace ); FEATUREMGR->registerFeature(MFT_PrePassConditioner, cond); FEATUREMGR->registerFeature(MFT_RTLighting, new DeferredRTLightingFeatGLSL()); FEATUREMGR->registerFeature(MFT_NormalMap, new DeferredBumpFeatGLSL()); diff --git a/Engine/source/lighting/advanced/glsl/advancedLightingFeaturesGLSL.cpp b/Engine/source/lighting/advanced/glsl/advancedLightingFeaturesGLSL.cpp index 1da348f03..c5f85234a 100644 --- a/Engine/source/lighting/advanced/glsl/advancedLightingFeaturesGLSL.cpp +++ b/Engine/source/lighting/advanced/glsl/advancedLightingFeaturesGLSL.cpp @@ -35,16 +35,12 @@ void DeferredRTLightingFeatGLSL::processPixMacros( Vector ¯os, const MaterialFeatureData &fd ) { - /// TODO: This needs to be done via some sort of material - /// feature and not just allow all translucent elements to - /// read from the light prepass. - /* - if ( fd.features[MFT_IsTranslucent] ) + // Skip deferred features, and use forward shading instead + if ( fd.features[MFT_ForwardShading] ) { Parent::processPixMacros( macros, fd ); return; } - */ // Pull in the uncondition method for the light info buffer NamedTexTarget *texTarget = NamedTexTarget::find( AdvancedLightBinManager::smBufferName ); @@ -59,48 +55,42 @@ void DeferredRTLightingFeatGLSL::processPixMacros( Vector ¯o void DeferredRTLightingFeatGLSL::processVert( Vector &componentList, const MaterialFeatureData &fd ) { - /// TODO: This needs to be done via some sort of material - /// feature and not just allow all translucent elements to - /// read from the light prepass. - /* - if ( fd.features[MFT_IsTranslucent] ) + // Skip deferred features, and use forward shading instead + if ( fd.features[MFT_ForwardShading] ) { Parent::processVert( componentList, fd ); return; } - */ // Pass screen space position to pixel shader to compute a full screen buffer uv ShaderConnector *connectComp = dynamic_cast( componentList[C_CONNECTOR] ); Var *ssPos = connectComp->getElement( RT_TEXCOORD ); ssPos->setName( "screenspacePos" ); + ssPos->setStructName( "OUT" ); ssPos->setType( "vec4" ); -// Var *outPosition = (Var*) LangElement::find( "hpos" ); -// AssertFatal( outPosition, "No hpos, ohnoes." ); + Var *outPosition = (Var*) LangElement::find( "gl_Position" ); + AssertFatal( outPosition, "No gl_Position, ohnoes." ); - output = new GenOp( " @ = gl_Position;\r\n", ssPos ); + output = new GenOp( " @ = @;\r\n", ssPos, outPosition ); } void DeferredRTLightingFeatGLSL::processPix( Vector &componentList, const MaterialFeatureData &fd ) { - /// TODO: This needs to be done via some sort of material - /// feature and not just allow all translucent elements to - /// read from the light prepass. - /* - if ( fd.features[MFT_IsTranslucent] ) + // Skip deferred features, and use forward shading instead + if ( fd.features[MFT_ForwardShading] ) { Parent::processPix( componentList, fd ); return; } - */ MultiLine *meta = new MultiLine; ShaderConnector *connectComp = dynamic_cast( componentList[C_CONNECTOR] ); Var *ssPos = connectComp->getElement( RT_TEXCOORD ); ssPos->setName( "screenspacePos" ); + ssPos->setStructName( "IN" ); ssPos->setType( "vec4" ); Var *uvScene = new Var; @@ -108,18 +98,20 @@ void DeferredRTLightingFeatGLSL::processPix( Vector &component uvScene->setName( "uvScene" ); LangElement *uvSceneDecl = new DecOp( uvScene ); - Var *rtParams = (Var*) LangElement::find( "renderTargetParams" ); + String rtParamName = String::ToString( "rtParams%s", "lightInfoBuffer" ); + Var *rtParams = (Var*) LangElement::find( rtParamName ); if( !rtParams ) { rtParams = new Var; rtParams->setType( "vec4" ); - rtParams->setName( "renderTargetParams" ); + rtParams->setName( rtParamName ); rtParams->uniform = true; rtParams->constSortPos = cspPass; } meta->addStatement( new GenOp( " @ = @.xy / @.w;\r\n", uvSceneDecl, ssPos, ssPos ) ); // get the screen coord... its -1 to +1 meta->addStatement( new GenOp( " @ = ( @ + 1.0 ) / 2.0;\r\n", uvScene, uvScene ) ); // get the screen coord to 0 to 1 + meta->addStatement( new GenOp( " @.y = 1.0 - @.y;\r\n", uvScene, uvScene ) ); // flip the y axis meta->addStatement( new GenOp( " @ = ( @ * @.zw ) + @.xy;\r\n", uvScene, uvScene, rtParams, rtParams) ); // scale it down and offset it to the rt size Var *lightInfoSamp = new Var; @@ -134,36 +126,60 @@ void DeferredRTLightingFeatGLSL::processPix( Vector &component lightInfoBuffer->sampler = true; lightInfoBuffer->constNum = Var::getTexUnitNum(); // used as texture unit num here - String unconditionLightInfo = String::ToLower( AdvancedLightBinManager::smBufferName ) + "Uncondition"; - - meta->addStatement( new GenOp( " vec3 d_lightcolor;\r\n" ) ); - meta->addStatement( new GenOp( " float d_NL_Att;\r\n" ) ); - meta->addStatement( new GenOp( " float d_specular;\r\n" ) ); - meta->addStatement( new GenOp( avar( " %s(texture2D(@, @), d_lightcolor, d_NL_Att, d_specular);\r\n", unconditionLightInfo.c_str() ), - lightInfoBuffer, uvScene ) ); + // 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", "vec3" ); + meta->addStatement( new GenOp( " @;\r\n", new DecOp( d_lightcolor ) ) ); - Var *rtShading = new Var; - rtShading->setType( "vec4" ); - rtShading->setName( "rtShading" ); - LangElement *rtShadingDecl = new DecOp( rtShading ); - meta->addStatement( new GenOp( " @ = vec4( d_lightcolor, 1.0 );\r\n", rtShadingDecl ) ); + Var *d_NL_Att = new Var( "d_NL_Att", "float" ); + meta->addStatement( new GenOp( " @;\r\n", new DecOp( d_NL_Att ) ) ); + + Var *d_specular = new Var( "d_specular", "float" ); + meta->addStatement( new GenOp( " @;\r\n", new DecOp( d_specular ) ) ); + + + // 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 this has an interlaced pre-pass, do averaging here + if( fd.features[MFT_InterlacedPrePass] ) + { + Var *oneOverTargetSize = (Var*) LangElement::find( "oneOverTargetSize" ); + if( !oneOverTargetSize ) + { + oneOverTargetSize = new Var; + oneOverTargetSize->setType( "vec2" ); + oneOverTargetSize->setName( "oneOverTargetSize" ); + oneOverTargetSize->uniform = true; + oneOverTargetSize->constSortPos = cspPass; + } + + 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 ) ); + + 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 ) ); + meta->addStatement( new GenOp(" @ = lerp(@, id_specular, 0.5);\r\n", d_specular, d_specular ) ); + } // This is kind of weak sauce - if( !fd.features[MFT_SubSurface] && !fd.features[MFT_ToneMap] && !fd.features[MFT_LightMap] ) - meta->addStatement( new GenOp( " @;\r\n", assignColor( rtShading, Material::Mul ) ) ); + if( !fd.features[MFT_VertLit] && !fd.features[MFT_ToneMap] && !fd.features[MFT_LightMap] && !fd.features[MFT_SubSurface] ) + meta->addStatement( new GenOp( " @;\r\n", assignColor( new GenOp( "float4(@, 1.0)", d_lightcolor ), Material::Mul ) ) ); output = meta; } ShaderFeature::Resources DeferredRTLightingFeatGLSL::getResources( const MaterialFeatureData &fd ) { - /// TODO: This needs to be done via some sort of material - /// feature and not just allow all translucent elements to - /// read from the light prepass. - /* - if( fd.features[MFT_IsTranslucent] ) + // Skip deferred features, and use forward shading instead + if ( fd.features[MFT_ForwardShading] ) return Parent::getResources( fd ); - */ + + // HACK: See DeferredRTLightingFeatGLSL::setTexData. + mLastTexIndex = 0; Resources res; res.numTex = 1; @@ -176,21 +192,22 @@ void DeferredRTLightingFeatGLSL::setTexData( Material::StageData &stageDat, RenderPassData &passData, U32 &texIndex ) { - /// TODO: This needs to be done via some sort of material - /// feature and not just allow all translucent elements to - /// read from the light prepass. - /* - if( fd.features[MFT_IsTranslucent] ) + // Skip deferred features, and use forward shading instead + if ( fd.features[MFT_ForwardShading] ) { Parent::setTexData( stageDat, fd, passData, texIndex ); return; } - */ NamedTexTarget *texTarget = NamedTexTarget::find( AdvancedLightBinManager::smBufferName ); if( texTarget ) { - passData.mTexType[ texIndex ] = Material::TexTarget; + // HACK: We store this for use in DeferredRTLightingFeatGLSL::processPix() + // which cannot deduce the texture unit itself. + mLastTexIndex = texIndex; + + passData.mTexType[ texIndex ] = Material::TexTarget; + passData.mSamplerNames[ texIndex ]= "lightInfoBuffer"; passData.mTexSlot[ texIndex++ ].texTarget = texTarget; } } @@ -205,92 +222,31 @@ void DeferredBumpFeatGLSL::processVert( Vector &componentLis // to the pixel shader. MultiLine *meta = new MultiLine; - // setup texture space matrix - Var *texSpaceMat = (Var*) LangElement::find( "objToTangentSpace" ); - if( !texSpaceMat ) - { - LangElement * texSpaceSetup = setupTexSpaceMat( componentList, &texSpaceMat ); - meta->addStatement( texSpaceSetup ); - texSpaceMat = (Var*) LangElement::find( "objToTangentSpace" ); - } - - // turn obj->tangent into world->tangent - Var *worldToTangent = new Var; - worldToTangent->setType( "mat3" ); - worldToTangent->setName( "worldToTangent" ); - LangElement *worldToTangentDecl = new DecOp( worldToTangent ); - - // Get the world->obj transform - Var *worldToObj = new Var; - worldToObj->setType( "mat4" ); - worldToObj->setName( "worldToObj" ); - worldToObj->uniform = true; - worldToObj->constSortPos = cspPrimitive; - - Var *mat3Conversion = new Var; - mat3Conversion->setType( "mat3" ); - mat3Conversion->setName( "worldToObjMat3" ); - LangElement* mat3Lang = new DecOp(mat3Conversion); - meta->addStatement( new GenOp( " @ = mat3(@[0].xyz, @[1].xyz, @[2].xyz);\r\n ", mat3Lang, worldToObj, worldToObj, worldToObj) ); - - // assign world->tangent transform - meta->addStatement( new GenOp( " @ = @ * @;\r\n", worldToTangentDecl, texSpaceMat, mat3Conversion ) ); - - // send transform to pixel shader - ShaderConnector *connectComp = dynamic_cast( componentList[C_CONNECTOR] ); - - Var *worldToTangentR1 = connectComp->getElement( RT_TEXCOORD ); - worldToTangentR1->setName( "worldToTangentR1" ); - worldToTangentR1->setType( "vec3" ); - meta->addStatement( new GenOp( " @ = @[0];\r\n", worldToTangentR1, worldToTangent ) ); - - Var *worldToTangentR2 = connectComp->getElement( RT_TEXCOORD ); - worldToTangentR2->setName( "worldToTangentR2" ); - worldToTangentR2->setType( "vec3" ); - meta->addStatement( new GenOp( " @ = @[1];\r\n", worldToTangentR2, worldToTangent ) ); - - Var *worldToTangentR3 = connectComp->getElement( RT_TEXCOORD ); - worldToTangentR3->setName( "worldToTangentR3" ); - worldToTangentR3->setType( "vec3" ); - meta->addStatement( new GenOp( " @ = @[2];\r\n", worldToTangentR3, worldToTangent ) ); + // We need the view to tangent space transform in the pixel shader. + getOutViewToTangent( componentList, meta, fd ); // Make sure there are texcoords - if( !fd.features[MFT_DiffuseMap] ) + if( !fd.features[MFT_Parallax] && !fd.features[MFT_DiffuseMap] ) { - // find incoming texture var - Var *inTex = getVertTexCoord( "texCoord" ); + const bool useTexAnim = fd.features[MFT_TexAnim]; - // grab connector texcoord register - ShaderConnector *connectComp = dynamic_cast( componentList[C_CONNECTOR] ); - Var *outTex = connectComp->getElement( RT_TEXCOORD ); - outTex->setName( "outTexCoord" ); - outTex->setType( "vec2" ); - outTex->mapsToSampler = true; + getOutTexCoord( "texCoord", + "vec2", + true, + useTexAnim, + meta, + componentList ); - if( fd.features[MFT_TexAnim] ) - { - inTex->setType( "vec4" ); - - // create texture mat var - Var *texMat = new Var; - texMat->setType( "mat4" ); - texMat->setName( "texMat" ); - texMat->uniform = true; - texMat->constSortPos = cspPotentialPrimitive; - - meta->addStatement( new GenOp( " @ = @ * @;\r\n", outTex, texMat, inTex ) ); - } - else - { - // setup language elements to output incoming tex coords to output - meta->addStatement( new GenOp( " @ = @;\r\n", outTex, inTex ) ); - } + if ( fd.features.hasFeature( MFT_DetailNormalMap ) ) + addOutDetailTexCoord( componentList, + meta, + useTexAnim ); } output = meta; } else if ( fd.materialFeatures[MFT_NormalsOut] || - fd.features[MFT_IsTranslucent] || + fd.features[MFT_ForwardShading] || !fd.features[MFT_RTLighting] ) { Parent::processVert( componentList, fd ); @@ -312,52 +268,12 @@ void DeferredBumpFeatGLSL::processPix( Vector &componentList, { MultiLine *meta = new MultiLine; - // Pull the world->tangent transform from the vertex shader - ShaderConnector *connectComp = dynamic_cast( componentList[C_CONNECTOR] ); - - Var *worldToTangentR1 = connectComp->getElement( RT_TEXCOORD ); - worldToTangentR1->setName( "worldToTangentR1" ); - worldToTangentR1->setType( "vec3" ); - - Var *worldToTangentR2 = connectComp->getElement( RT_TEXCOORD ); - worldToTangentR2->setName( "worldToTangentR2" ); - worldToTangentR2->setType( "vec3" ); - - Var *worldToTangentR3 = connectComp->getElement( RT_TEXCOORD ); - worldToTangentR3->setName( "worldToTangentR3" ); - worldToTangentR3->setType( "vec3" ); - - Var *worldToTangent = new Var; - worldToTangent->setType( "mat3" ); - worldToTangent->setName( "worldToTangent" ); - LangElement *worldToTangentDecl = new DecOp( worldToTangent ); - - // Build world->tangent matrix - meta->addStatement( new GenOp( " @;\r\n", worldToTangentDecl ) ); - meta->addStatement( new GenOp( " @[0] = @;\r\n", worldToTangent, worldToTangentR1 ) ); - meta->addStatement( new GenOp( " @[1] = @;\r\n", worldToTangent, worldToTangentR2 ) ); - meta->addStatement( new GenOp( " @[2] = @;\r\n", worldToTangent, worldToTangentR3 ) ); + Var *viewToTangent = getInViewToTangent( componentList ); // create texture var - Var *bumpMap = new Var; - bumpMap->setType( "sampler2D" ); - bumpMap->setName( "bumpMap" ); - bumpMap->uniform = true; - bumpMap->sampler = true; - bumpMap->constNum = Var::getTexUnitNum(); // used as texture unit num here - - Var *texCoord = (Var*) LangElement::find( "outTexCoord" ); - if( !texCoord ) - { - // grab connector texcoord register - ShaderConnector *connectComp = dynamic_cast( componentList[C_CONNECTOR] ); - texCoord = connectComp->getElement( RT_TEXCOORD ); - texCoord->setName( "outTexCoord" ); - texCoord->setType( "vec2" ); - texCoord->mapsToSampler = true; - } - - LangElement * texOp = new GenOp( "texture2D(@, @)", bumpMap, texCoord ); + Var *bumpMap = getNormalMapTex(); + Var *texCoord = getInTexCoord( "texCoord", "vec2", true, componentList ); + LangElement *texOp = new GenOp( "tex2D(@, @)", bumpMap, texCoord ); // create bump normal Var *bumpNorm = new Var; @@ -367,56 +283,75 @@ void DeferredBumpFeatGLSL::processPix( Vector &componentList, LangElement *bumpNormDecl = new DecOp( bumpNorm ); meta->addStatement( expandNormalMap( texOp, bumpNormDecl, bumpNorm, fd ) ); + // If we have a detail normal map we add the xy coords of + // it to the base normal map. This gives us the effect we + // want with few instructions and minial artifacts. + if ( fd.features.hasFeature( MFT_DetailNormalMap ) ) + { + bumpMap = new Var; + bumpMap->setType( "sampler2D" ); + bumpMap->setName( "detailBumpMap" ); + bumpMap->uniform = true; + bumpMap->sampler = true; + bumpMap->constNum = Var::getTexUnitNum(); + + texCoord = getInTexCoord( "detCoord", "vec2", true, componentList ); + texOp = new GenOp( "tex2D(@, @)", bumpMap, texCoord ); + + Var *detailBump = new Var; + detailBump->setName( "detailBump" ); + detailBump->setType( "vec4" ); + meta->addStatement( expandNormalMap( texOp, new DecOp( detailBump ), detailBump, fd ) ); + + Var *detailBumpScale = new Var; + detailBumpScale->setType( "float" ); + detailBumpScale->setName( "detailBumpStrength" ); + detailBumpScale->uniform = true; + detailBumpScale->constSortPos = cspPass; + meta->addStatement( new GenOp( " @.xy += @.xy * @;\r\n", bumpNorm, detailBump, detailBumpScale ) ); + } + // This var is read from GBufferConditionerHLSL and // used in the prepass output. + // + // By using the 'half' type here we get a bunch of partial + // precision optimized code on further operations on the normal + // which helps alot on older Geforce cards. + // Var *gbNormal = new Var; gbNormal->setName( "gbNormal" ); - gbNormal->setType( "vec3" ); + gbNormal->setType( "half3" ); LangElement *gbNormalDecl = new DecOp( gbNormal ); // Normalize is done later... // Note: The reverse mul order is intentional. Affine matrix. - meta->addStatement( new GenOp( " @ = @.xyz * @;\r\n", gbNormalDecl, bumpNorm, worldToTangent ) ); + meta->addStatement( new GenOp( " @ = half3(tMul( @.xyz, @ ));\r\n", gbNormalDecl, bumpNorm, viewToTangent ) ); output = meta; return; } else if ( fd.materialFeatures[MFT_NormalsOut] || - fd.features[MFT_IsTranslucent] || + fd.features[MFT_ForwardShading] || !fd.features[MFT_RTLighting] ) { Parent::processPix( componentList, fd ); return; } - else if ( fd.features[MFT_PixSpecular] ) + else if ( fd.features[MFT_PixSpecular] && !fd.features[MFT_SpecularMap] ) { Var *bumpSample = (Var *)LangElement::find( "bumpSample" ); if( bumpSample == NULL ) { - Var *texCoord = (Var*) LangElement::find( "outTexCoord" ); - if( !texCoord ) - { - // grab connector texcoord register - ShaderConnector *connectComp = dynamic_cast( componentList[C_CONNECTOR] ); - texCoord = connectComp->getElement( RT_TEXCOORD ); - texCoord->setName( "outTexCoord" ); - texCoord->setType( "vec2" ); - texCoord->mapsToSampler = true; - } + Var *texCoord = getInTexCoord( "texCoord", "vec2", true, componentList ); - Var *bumpMap = new Var; - bumpMap->setType( "sampler2D" ); - bumpMap->setName( "bumpMap" ); - bumpMap->uniform = true; - bumpMap->sampler = true; - bumpMap->constNum = Var::getTexUnitNum(); // used as texture unit num here + Var *bumpMap = getNormalMapTex(); bumpSample = new Var; bumpSample->setType( "vec4" ); bumpSample->setName( "bumpSample" ); LangElement *bumpSampleDecl = new DecOp( bumpSample ); - output = new GenOp( " @ = texture2D(@, @);\r\n", bumpSampleDecl, bumpMap, texCoord ); + output = new GenOp( " @ = tex2D(@, @);\r\n", bumpSampleDecl, bumpMap, texCoord ); return; } } @@ -427,7 +362,7 @@ void DeferredBumpFeatGLSL::processPix( Vector &componentList, ShaderFeature::Resources DeferredBumpFeatGLSL::getResources( const MaterialFeatureData &fd ) { if ( fd.materialFeatures[MFT_NormalsOut] || - fd.features[MFT_IsTranslucent] || + fd.features[MFT_ForwardShading] || fd.features[MFT_Parallax] || !fd.features[MFT_RTLighting] ) return Parent::getResources( fd ); @@ -437,7 +372,16 @@ ShaderFeature::Resources DeferredBumpFeatGLSL::getResources( const MaterialFeatu { res.numTex = 1; res.numTexReg = 1; + + if ( fd.features[MFT_PrePassConditioner] && + fd.features.hasFeature( MFT_DetailNormalMap ) ) + { + res.numTex += 1; + if ( !fd.features.hasFeature( MFT_DetailMap ) ) + res.numTexReg += 1; + } } + return res; } @@ -447,21 +391,28 @@ void DeferredBumpFeatGLSL::setTexData( Material::StageData &stageDat, U32 &texIndex ) { if ( fd.materialFeatures[MFT_NormalsOut] || - fd.features[MFT_IsTranslucent] || + fd.features[MFT_ForwardShading] || !fd.features[MFT_RTLighting] ) { Parent::setTexData( stageDat, fd, passData, texIndex ); return; } - GFXTextureObject *normalMap = stageDat.getTex( MFT_NormalMap ); if ( !fd.features[MFT_Parallax] && !fd.features[MFT_SpecularMap] && ( fd.features[MFT_PrePassConditioner] || - fd.features[MFT_PixSpecular] ) && - normalMap ) + fd.features[MFT_PixSpecular] ) ) { passData.mTexType[ texIndex ] = Material::Bump; - passData.mTexSlot[ texIndex++ ].texObject = normalMap; + passData.mSamplerNames[ texIndex ] = "bumpMap"; + passData.mTexSlot[ texIndex++ ].texObject = stageDat.getTex( MFT_NormalMap ); + + if ( fd.features[MFT_PrePassConditioner] && + fd.features.hasFeature( MFT_DetailNormalMap ) ) + { + passData.mTexType[ texIndex ] = Material::DetailBump; + passData.mSamplerNames[ texIndex ] = "detailBumpMap"; + passData.mTexSlot[ texIndex++ ].texObject = stageDat.getTex( MFT_DetailNormalMap ); + } } } @@ -469,7 +420,7 @@ void DeferredBumpFeatGLSL::setTexData( Material::StageData &stageDat, void DeferredPixelSpecularGLSL::processVert( Vector &componentList, const MaterialFeatureData &fd ) { - if( fd.features[MFT_IsTranslucent] || !fd.features[MFT_RTLighting] ) + if( fd.features[MFT_ForwardShading] || !fd.features[MFT_RTLighting] ) { Parent::processVert( componentList, fd ); return; @@ -480,7 +431,7 @@ void DeferredPixelSpecularGLSL::processVert( Vector &component void DeferredPixelSpecularGLSL::processPix( Vector &componentList, const MaterialFeatureData &fd ) { - if( fd.features[MFT_IsTranslucent] || !fd.features[MFT_RTLighting] ) + if( fd.features[MFT_ForwardShading] || !fd.features[MFT_RTLighting] ) { Parent::processPix( componentList, fd ); return; @@ -523,19 +474,18 @@ void DeferredPixelSpecularGLSL::processPix( Vector &component specStrength->uniform = true; specStrength->constSortPos = cspPotentialPrimitive; - Var *constSpecPow = new Var; - constSpecPow->setType( "float" ); - constSpecPow->setName( "constantSpecularPower" ); - constSpecPow->uniform = true; - constSpecPow->constSortPos = cspPass; - Var *lightInfoSamp = (Var *)LangElement::find( "lightInfoSample" ); - AssertFatal( lightInfoSamp, "Something hosed the deferred features! Can't find lightInfoSample" ); + Var *d_specular = (Var*)LangElement::find( "d_specular" ); + Var *d_NL_Att = (Var*)LangElement::find( "d_NL_Att" ); + + AssertFatal( lightInfoSamp && d_specular && d_NL_Att, + "DeferredPixelSpecularGLSL::processPix - Something hosed the deferred features!" ); // (a^m)^n = a^(m*n) - meta->addStatement( new GenOp( " @ = pow(d_specular, ceil(@ / @)) * @;\r\n", specDecl, specPow, constSpecPow, specStrength ) ); + meta->addStatement( new GenOp( " @ = pow( abs(@), max((@ / AL_ConstantSpecularPower),1.0f)) * @;\r\n", + specDecl, d_specular, specPow, specStrength ) ); - LangElement *specMul = new GenOp( "@ * @", specCol, specular ); + LangElement *specMul = new GenOp( "float4( @.rgb, 0 ) * @", specCol, specular ); LangElement *final = specMul; // We we have a normal map then mask the specular @@ -545,14 +495,15 @@ void DeferredPixelSpecularGLSL::processPix( Vector &component final = new GenOp( "@ * @.a", final, bumpSample ); } - // add to color meta->addStatement( new GenOp( " @;\r\n", assignColor( final, Material::Add ) ) ); + // add to color + meta->addStatement( new GenOp( " @;\r\n", assignColor( final, Material::Add ) ) ); output = meta; } ShaderFeature::Resources DeferredPixelSpecularGLSL::getResources( const MaterialFeatureData &fd ) { - if( fd.features[MFT_IsTranslucent] || !fd.features[MFT_RTLighting] ) + if( fd.features[MFT_ForwardShading] || !fd.features[MFT_RTLighting] ) return Parent::getResources( fd ); Resources res; @@ -563,7 +514,7 @@ ShaderFeature::Resources DeferredPixelSpecularGLSL::getResources( const Material ShaderFeature::Resources DeferredMinnaertGLSL::getResources( const MaterialFeatureData &fd ) { Resources res; - if( !fd.features[MFT_IsTranslucent] && fd.features[MFT_RTLighting] ) + if( !fd.features[MFT_ForwardShading] && fd.features[MFT_RTLighting] ) { res.numTex = 1; res.numTexReg = 1; @@ -576,7 +527,7 @@ void DeferredMinnaertGLSL::setTexData( Material::StageData &stageDat, RenderPassData &passData, U32 &texIndex ) { - if( !fd.features[MFT_IsTranslucent] && fd.features[MFT_RTLighting] ) + if( !fd.features[MFT_ForwardShading] && fd.features[MFT_RTLighting] ) { NamedTexTarget *texTarget = NamedTexTarget::find(RenderPrePassMgr::BufferName); if ( texTarget ) @@ -590,7 +541,7 @@ void DeferredMinnaertGLSL::setTexData( Material::StageData &stageDat, void DeferredMinnaertGLSL::processPixMacros( Vector ¯os, const MaterialFeatureData &fd ) { - if( !fd.features[MFT_IsTranslucent] && fd.features[MFT_RTLighting] ) + if( !fd.features[MFT_ForwardShading] && fd.features[MFT_RTLighting] ) { // Pull in the uncondition method for the g buffer NamedTexTarget *texTarget = NamedTexTarget::find( RenderPrePassMgr::BufferName ); @@ -607,55 +558,24 @@ void DeferredMinnaertGLSL::processVert( Vector &componentLis const MaterialFeatureData &fd ) { // If there is no deferred information, bail on this feature - if( fd.features[MFT_IsTranslucent] || !fd.features[MFT_RTLighting] ) + if( fd.features[MFT_ForwardShading] || !fd.features[MFT_RTLighting] ) { output = NULL; return; } - // grab incoming vert position - Var *inVertPos = (Var*) LangElement::find( "position" ); - AssertFatal( inVertPos, "Something went bad with ShaderGen. The vertex position should be already defined." ); - - // grab output for gbuffer normal - ShaderConnector *connectComp = dynamic_cast( componentList[C_CONNECTOR] ); - Var *outWSEyeVec= connectComp->getElement( RT_TEXCOORD ); - outWSEyeVec->setName( "outWSViewVec" ); - outWSEyeVec->setType( "vec4" ); - - // create objToWorld variable - Var *objToWorld = (Var*) LangElement::find( "objTrans" ); - if( !objToWorld ) - { - objToWorld = new Var; - objToWorld->setType( "mat4x4" ); - objToWorld->setName( "objTrans" ); - objToWorld->uniform = true; - objToWorld->constSortPos = cspPrimitive; - } - - // Eye Pos world - Var *eyePosWorld = (Var*) LangElement::find( "eyePosWorld" ); - if( !eyePosWorld ) - { - eyePosWorld = new Var; - eyePosWorld->setType( "vec3" ); - eyePosWorld->setName( "eyePosWorld" ); - eyePosWorld->uniform = true; - eyePosWorld->constSortPos = cspPass; - } - - // Kick out the world-space normal - LangElement *statement = new GenOp( " @ = vec4(@, @) - vec4(@, 0.0);\r\n", - outWSEyeVec, objToWorld, inVertPos, eyePosWorld ); - output = statement; + // Make sure we pass the world space position to the + // pixel shader so we can calculate a view vector. + MultiLine *meta = new MultiLine; + addOutWsPosition( componentList, fd.features[MFT_UseInstancing], meta ); + output = meta; } void DeferredMinnaertGLSL::processPix( Vector &componentList, const MaterialFeatureData &fd ) { // If there is no deferred information, bail on this feature - if( fd.features[MFT_IsTranslucent] || !fd.features[MFT_RTLighting] ) + if( fd.features[MFT_ForwardShading] || !fd.features[MFT_RTLighting] ) { output = NULL; return; @@ -679,25 +599,19 @@ void DeferredMinnaertGLSL::processPix( Vector &componentList, Var *uvScene = (Var*) LangElement::find( "uvScene" ); AssertFatal(uvScene != NULL, "Unable to find UVScene, no RTLighting feature?"); - ShaderConnector *connectComp = dynamic_cast( componentList[C_CONNECTOR] ); - Var *wsViewVec = (Var*) LangElement::find( "wsPos" ); - if( !wsViewVec ) - { - wsViewVec = connectComp->getElement( RT_TEXCOORD ); - wsViewVec->setName( "outWSViewVec" ); - wsViewVec->setType( "vec4" ); - wsViewVec->mapsToSampler = false; - wsViewVec->uniform = false; - } + MultiLine *meta = new MultiLine; + + // Get the world space view vector. + Var *wsViewVec = getWsView( getInWsPosition( componentList ), meta ); String unconditionPrePassMethod = String::ToLower(RenderPrePassMgr::BufferName) + "Uncondition"; - MultiLine *meta = new MultiLine; - meta->addStatement( new GenOp( avar( " vec4 normalDepth = %s(texture2D(@, @));\r\n", unconditionPrePassMethod.c_str() ), prepassBuffer, uvScene ) ); - meta->addStatement( new GenOp( " vec3 worldViewVec = normalize(@.xyz / @.w);\r\n", wsViewVec, wsViewVec ) ); - meta->addStatement( new GenOp( " float vDotN = dot(normalDepth.xyz, worldViewVec);\r\n" ) ); - meta->addStatement( new GenOp( " float Minnaert = pow(d_NL_Att, @) * pow(vDotN, 1.0 - @);\r\n", minnaertConstant, minnaertConstant ) ); - meta->addStatement( new GenOp( " @;\r\n", assignColor( new GenOp( "vec4(Minnaert, Minnaert, Minnaert, 1.0)" ), Material::Mul ) ) ); + 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 ) ); + 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 ) ) ); output = meta; } @@ -707,7 +621,7 @@ void DeferredSubSurfaceGLSL::processPix( Vector &componentLis const MaterialFeatureData &fd ) { // If there is no deferred information, bail on this feature - if( fd.features[MFT_IsTranslucent] || !fd.features[MFT_RTLighting] ) + if( fd.features[MFT_ForwardShading] || !fd.features[MFT_RTLighting] ) { output = NULL; return; @@ -719,12 +633,13 @@ void DeferredSubSurfaceGLSL::processPix( Vector &componentLis subSurfaceParams->uniform = true; subSurfaceParams->constSortPos = cspPotentialPrimitive; - Var *inColor = (Var*) LangElement::find( "rtShading" ); + Var *d_lightcolor = (Var*)LangElement::find( "d_lightcolor" ); + Var *d_NL_Att = (Var*)LangElement::find( "d_NL_Att" ); MultiLine *meta = new MultiLine; - meta->addStatement( new GenOp( " float subLamb = smoothstep(-@.a, 1.0, d_NL_Att) - smoothstep(0.0, 1.0, d_NL_Att);\r\n", subSurfaceParams ) ); + meta->addStatement( new GenOp( " float subLamb = smoothstep(-@.a, 1.0, @) - smoothstep(0.0, 1.0, @);\r\n", subSurfaceParams, d_NL_Att, d_NL_Att ) ); meta->addStatement( new GenOp( " subLamb = max(0.0, subLamb);\r\n" ) ); - meta->addStatement( new GenOp( " @;\r\n", assignColor( new GenOp( "vec4(@.rgb + (subLamb * @.rgb), 1.0)", inColor, subSurfaceParams ), Material::Mul ) ) ); + meta->addStatement( new GenOp( " @;\r\n", assignColor( new GenOp( "float4(@ + (subLamb * @.rgb), 1.0)", d_lightcolor, subSurfaceParams ), Material::Mul ) ) ); output = meta; } diff --git a/Engine/source/lighting/advanced/glsl/advancedLightingFeaturesGLSL.h b/Engine/source/lighting/advanced/glsl/advancedLightingFeaturesGLSL.h index fb37848a8..0e326de6a 100644 --- a/Engine/source/lighting/advanced/glsl/advancedLightingFeaturesGLSL.h +++ b/Engine/source/lighting/advanced/glsl/advancedLightingFeaturesGLSL.h @@ -30,13 +30,25 @@ class ConditionerMethodDependency; -/// Lights the pixel by sampling from the light prepass buffer. It will -/// fall back to default vertex lighting functionality if +/// Lights the pixel by sampling from the light prepass +/// buffer. It will fall back to forward lighting +/// functionality for non-deferred rendered surfaces. +/// +/// Also note that this feature is only used in the +/// forward rendering pass. It is not used during the +/// prepass step. +/// class DeferredRTLightingFeatGLSL : public RTLightingFeatGLSL { typedef RTLightingFeatGLSL Parent; +protected: + + /// @see DeferredRTLightingFeatHLSL::processPix() + U32 mLastTexIndex; + public: + virtual void processVert( Vector &componentList, const MaterialFeatureData &fd ); @@ -57,12 +69,12 @@ public: virtual String getName() { - return "Deferred RT Lighting Feature"; + return "Deferred RT Lighting"; } }; -/// Used to write the normals during the depth/normal prepass. +/// This is used during the class DeferredBumpFeatGLSL : public BumpFeatGLSL { typedef BumpFeatGLSL Parent; diff --git a/Engine/source/lighting/advanced/glsl/gBufferConditionerGLSL.cpp b/Engine/source/lighting/advanced/glsl/gBufferConditionerGLSL.cpp index fd3b27d85..17a98c969 100644 --- a/Engine/source/lighting/advanced/glsl/gBufferConditionerGLSL.cpp +++ b/Engine/source/lighting/advanced/glsl/gBufferConditionerGLSL.cpp @@ -27,9 +27,10 @@ #include "gfx/gfxStringEnumTranslate.h" #include "materials/materialFeatureTypes.h" #include "materials/materialFeatureData.h" +#include "shaderGen/GLSL/shaderFeatureGLSL.h" -GBufferConditionerGLSL::GBufferConditionerGLSL( const GFXFormat bufferFormat ) : +GBufferConditionerGLSL::GBufferConditionerGLSL( const GFXFormat bufferFormat, const NormalSpace nrmSpace ) : Parent( bufferFormat ) { // Figure out how we should store the normal data. These are the defaults. @@ -39,20 +40,18 @@ GBufferConditionerGLSL::GBufferConditionerGLSL( const GFXFormat bufferFormat ) : // Note: We clear to a depth 1 (the w component) so // that the unrendered parts of the scene end up // farthest to the camera. - + const NormalStorage &twoCmpNrmStorageType = ( nrmSpace == WorldSpace ? Spherical : LambertAzimuthal ); switch(bufferFormat) { case GFXFormatR8G8B8A8: - // TODO: Some kind of logic here. Spherical is better, but is more - // expensive. - mNormalStorageType = Spherical; + mNormalStorageType = twoCmpNrmStorageType; mBitsPerChannel = 8; break; case GFXFormatR16G16B16A16F: // Floating point buffers don't need to encode negative values mCanWriteNegativeValues = true; - mNormalStorageType = Spherical; + mNormalStorageType = twoCmpNrmStorageType; mBitsPerChannel = 16; break; @@ -61,7 +60,7 @@ GBufferConditionerGLSL::GBufferConditionerGLSL( const GFXFormat bufferFormat ) : // precision and high quality normals within a 64bit // buffer format. case GFXFormatR16G16B16A16: - mNormalStorageType = Spherical; + mNormalStorageType = twoCmpNrmStorageType; mBitsPerChannel = 16; break; @@ -83,34 +82,43 @@ GBufferConditionerGLSL::~GBufferConditionerGLSL() void GBufferConditionerGLSL::processVert( Vector &componentList, const MaterialFeatureData &fd ) { - output = NULL; + // If we have a normal map then that feature will + // take care of passing gbNormal to the pixel shader. + if ( fd.features[MFT_NormalMap] ) + return; - if( !fd.features[MFT_NormalMap] ) + MultiLine *meta = new MultiLine; + output = meta; + + // grab incoming vert normal + Var *inNormal = (Var*) LangElement::find( "normal" ); + AssertFatal( inNormal, "Something went bad with ShaderGen. The normal should be already defined." ); + + // grab output for gbuffer normal + ShaderConnector *connectComp = dynamic_cast( componentList[C_CONNECTOR] ); + Var *outNormal = connectComp->getElement( RT_TEXCOORD ); + outNormal->setName( "gbNormal" ); + outNormal->setStructName( "OUT" ); + outNormal->setType( "float3" ); + + if( !fd.features[MFT_ParticleNormal] ) { - // grab incoming vert normal - Var *inNormal = (Var*) LangElement::find( "normal" ); - AssertFatal( inNormal, "Something went bad with ShaderGen. The normal should be already defined." ); + // Kick out the view-space normal - // grab output for gbuffer normal - ShaderConnector *connectComp = dynamic_cast( componentList[C_CONNECTOR] ); - Var *outNormal = connectComp->getElement( RT_TEXCOORD ); - outNormal->setName( "gbNormal" ); - outNormal->setType( "vec3" ); + // TODO: Total hack because Conditioner is directly derived + // from ShaderFeature and not from ShaderFeatureGLSL. + NamedFeatureGLSL dummy( String::EmptyString ); + dummy.mInstancingFormat = mInstancingFormat; + Var *worldViewOnly = dummy.getWorldView( componentList, fd.features[MFT_UseInstancing], meta ); - // create objToWorld variable - Var *objToWorld = (Var*) LangElement::find( "objTrans" ); - if( !objToWorld ) - { - objToWorld = new Var; - objToWorld->setType( "mat4" ); - objToWorld->setName( "objTrans" ); - objToWorld->uniform = true; - objToWorld->constSortPos = cspPrimitive; - } - - // Kick out the world-space normal - LangElement *statement = new GenOp( " @ = vec3(@ * vec4(normalize(@), 0.0));\r\n", outNormal, objToWorld, inNormal ); - output = statement; + meta->addStatement( new GenOp(" @ = tMul(@, float4( normalize(@), 0.0 ) ).xyz;\r\n", + outNormal, worldViewOnly, inNormal ) ); + } + else + { + // Assume the particle normal generator has already put this in view space + // and normalized it + meta->addStatement( new GenOp( " @ = @;\r\n", outNormal, inNormal ) ); } } @@ -129,7 +137,8 @@ void GBufferConditionerGLSL::processPix( Vector &componentLis { gbNormal = connectComp->getElement( RT_TEXCOORD ); gbNormal->setName( "gbNormal" ); - gbNormal->setType( "vec3" ); + gbNormal->setStructName( "IN" ); + gbNormal->setType( "float3" ); gbNormal->mapsToSampler = false; gbNormal->uniform = false; } @@ -143,16 +152,45 @@ void GBufferConditionerGLSL::processPix( Vector &componentLis Var *unconditionedOut = new Var; - unconditionedOut->setType("vec4"); + unconditionedOut->setType("float4"); unconditionedOut->setName("normal_depth"); LangElement *outputDecl = new DecOp( unconditionedOut ); + // If we're doing prepass blending then we need + // to steal away the alpha channel before the + // conditioner stomps on it. + Var *alphaVal = NULL; + if ( fd.features[ MFT_IsTranslucentZWrite ] ) + { + alphaVal = new Var( "outAlpha", "float" ); + meta->addStatement( new GenOp( " @ = col.a; // MFT_IsTranslucentZWrite\r\n", new DecOp( alphaVal ) ) ); + } + + // If using interlaced normals, invert the normal + if(fd.features[MFT_InterlacedPrePass]) + { + // NOTE: Its safe to not call ShaderFeatureGLSL::addOutVpos() in the vertex + // shader as for SM 3.0 nothing is needed there. + Var *Vpos = (Var*) LangElement::find( "gl_Position" ); //Var *Vpos = ShaderFeatureGLSL::getInVpos( meta, componentList ); + + Var *iGBNormal = new Var( "interlacedGBNormal", "float3" ); + meta->addStatement(new GenOp(" @ = (frac(@.y * 0.5) < 0.1 ? reflect(@, float3(0.0, -1.0, 0.0)) : @);\r\n", new DecOp(iGBNormal), Vpos, gbNormal, gbNormal)); + gbNormal = iGBNormal; + } + // NOTE: We renormalize the normal here as they // will not stay normalized during interpolation. - meta->addStatement( new GenOp(" @ = @;", outputDecl, new GenOp( "vec4(normalize(@), @)", gbNormal, depth ) ) ); + meta->addStatement( new GenOp(" @ = @;", outputDecl, new GenOp( "float4(normalize(@), @)", gbNormal, depth ) ) ); meta->addStatement( assignOutput( unconditionedOut ) ); + // If we have an alpha var then we're doing prepass lerp blending. + if ( alphaVal ) + { + Var *outColor = (Var*)LangElement::find( getOutputTargetVarName( DefaultTarget ) ); + meta->addStatement( new GenOp( " @.ba = float2( 0, @ ); // MFT_IsTranslucentZWrite\r\n", outColor, alphaVal ) ); + } + output = meta; } @@ -180,7 +218,7 @@ Var* GBufferConditionerGLSL::printMethodHeader( MethodType methodType, const Str { Var *methodVar = new Var; methodVar->setName(methodName); - methodVar->setType("vec4"); + methodVar->setType("float4"); DecOp *methodDecl = new DecOp(methodVar); Var *prepassSampler = new Var; @@ -190,12 +228,12 @@ Var* GBufferConditionerGLSL::printMethodHeader( MethodType methodType, const Str Var *screenUV = new Var; screenUV->setName("screenUVVar"); - screenUV->setType("vec2"); + screenUV->setType("float2"); DecOp *screenUVDecl = new DecOp(screenUV); Var *bufferSample = new Var; bufferSample->setName("bufferSample"); - bufferSample->setType("vec4"); + bufferSample->setType("float4"); DecOp *bufferSampleDecl = new DecOp(bufferSample); meta->addStatement( new GenOp( "@(@, @)\r\n", methodDecl, prepassSamplerDecl, screenUVDecl ) ); @@ -204,9 +242,18 @@ Var* GBufferConditionerGLSL::printMethodHeader( MethodType methodType, const Str meta->addStatement( new GenOp( " // Sampler g-buffer\r\n" ) ); +#ifdef TORQUE_OS_XENON + meta->addStatement( new GenOp( " @;\r\n", bufferSampleDecl ) ); + meta->addStatement( new GenOp( " asm { tfetch2D @, @, @, MagFilter = point, MinFilter = point, MipFilter = point };\r\n", bufferSample, screenUV, prepassSampler ) ); +#else // The gbuffer has no mipmaps, so use tex2dlod when - // so that the shader compiler can optimize. - meta->addStatement( new GenOp( " @ = texture2DLod(@, @, 0.0);\r\n", bufferSampleDecl, prepassSampler, screenUV ) ); + // 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" ) ); +#endif // We don't use this way of passing var's around, so this should cause a crash // if something uses this improperly @@ -218,39 +265,67 @@ Var* GBufferConditionerGLSL::printMethodHeader( MethodType methodType, const Str GenOp* GBufferConditionerGLSL::_posnegEncode( GenOp *val ) { - return mCanWriteNegativeValues ? val : new GenOp("0.5 * (@ + 1.0)", val); + if(mNormalStorageType == LambertAzimuthal) + return mCanWriteNegativeValues ? val : new GenOp(avar("(%f * (@ + %f))", 1.0f/(M_SQRT2_F * 2.0f), M_SQRT2_F), val); + else + return mCanWriteNegativeValues ? val : new GenOp("(0.5 * (@ + 1.0))", val); } GenOp* GBufferConditionerGLSL::_posnegDecode( GenOp *val ) { - return mCanWriteNegativeValues ? val : new GenOp("@ * 2.0 - 1.0", val); + if(mNormalStorageType == LambertAzimuthal) + return mCanWriteNegativeValues ? val : new GenOp(avar("(@ * %f - %f)", M_SQRT2_F * 2.0f, M_SQRT2_F), val); + else + return mCanWriteNegativeValues ? val : new GenOp("(@ * 2.0 - 1.0)", val); } Var* GBufferConditionerGLSL::_conditionOutput( Var *unconditionedOutput, MultiLine *meta ) { Var *retVar = new Var; - retVar->setType("vec4"); + retVar->setType("float4"); retVar->setName("_gbConditionedOutput"); LangElement *outputDecl = new DecOp( retVar ); switch(mNormalStorageType) { case CartesianXYZ: - meta->addStatement( new GenOp( " // g-buffer conditioner: vec4(normal.xyz, depth)\r\n" ) ); - meta->addStatement( new GenOp( " @ = vec4(@, @.a);\r\n", outputDecl, + meta->addStatement( new GenOp( " // g-buffer conditioner: float4(normal.xyz, depth)\r\n" ) ); + meta->addStatement( new GenOp( " @ = float4(@, @.a);\r\n", outputDecl, _posnegEncode(new GenOp("@.xyz", unconditionedOutput)), unconditionedOutput ) ); break; case CartesianXY: - meta->addStatement( new GenOp( " // g-buffer conditioner: vec4(normal.xy, depth Hi + z-sign, depth Lo)\r\n" ) ); - meta->addStatement( new GenOp( " @ = vec4(@, @.a);", outputDecl, - _posnegEncode(new GenOp("vec3(@.xy, sign(@.z))", unconditionedOutput, unconditionedOutput)), unconditionedOutput ) ); + meta->addStatement( new GenOp( " // g-buffer conditioner: float4(normal.xy, depth Hi + z-sign, depth Lo)\r\n" ) ); + meta->addStatement( new GenOp( " @ = float4(@, @.a);", outputDecl, + _posnegEncode(new GenOp("float3(@.xy, sign(@.z))", unconditionedOutput, unconditionedOutput)), unconditionedOutput ) ); break; case Spherical: - meta->addStatement( new GenOp( " // g-buffer conditioner: vec4(normal.theta, normal.phi, depth Hi, depth Lo)\r\n" ) ); - meta->addStatement( new GenOp( " @ = vec4(@, 0.0, @.a);\r\n", outputDecl, - _posnegEncode(new GenOp("vec2(atan2(@.y, @.x) / 3.14159265358979323846f, @.z)", unconditionedOutput, unconditionedOutput, unconditionedOutput ) ), + meta->addStatement( new GenOp( " // g-buffer conditioner: float4(normal.theta, normal.phi, depth Hi, depth Lo)\r\n" ) ); + meta->addStatement( new GenOp( " @ = float4(@, 0.0, @.a);\r\n", outputDecl, + _posnegEncode(new GenOp("float2(atan2(@.y, @.x) / 3.14159265358979323846f, @.z)", unconditionedOutput, unconditionedOutput, unconditionedOutput ) ), + unconditionedOutput ) ); + + // HACK: This fixes the noise present when using a floating point + // gbuffer on Geforce cards and the "flat areas unlit" issues. + // + // We need work around atan2() above to fix this issue correctly + // without the extra overhead of this test. + // + meta->addStatement( new GenOp( " if ( abs( dot( @.xyz, float3( 0.0, 0.0, 1.0 ) ) ) > 0.999f ) @ = float4( 0, 1 * sign( @.z ), 0, @.a );\r\n", + unconditionedOutput, retVar, unconditionedOutput, unconditionedOutput ) ); + break; + + case LambertAzimuthal: + //http://en.wikipedia.org/wiki/Lambert_azimuthal_equal-area_projection + // + // Note we're casting to half to use partial precision + // sqrt which is much faster on older Geforces while + // still being acceptable for normals. + // + meta->addStatement( new GenOp( " // g-buffer conditioner: float4(normal.X, normal.Y, depth Hi, depth Lo)\r\n" ) ); + meta->addStatement( new GenOp( " @ = float4(@, 0.0, @.a);\r\n", outputDecl, + _posnegEncode(new GenOp("sqrt(half(2.0/(1.0 - @.y))) * half2(@.xz)", unconditionedOutput, unconditionedOutput)), unconditionedOutput ) ); break; } @@ -259,11 +334,10 @@ Var* GBufferConditionerGLSL::_conditionOutput( Var *unconditionedOutput, MultiLi if(mNormalStorageType != CartesianXYZ) { const U64 maxValPerChannel = 1 << mBitsPerChannel; - const U64 extraVal = (maxValPerChannel * maxValPerChannel - 1) - (maxValPerChannel - 1) * 2; meta->addStatement( new GenOp( " \r\n // Encode depth into hi/lo\r\n" ) ); - meta->addStatement( new GenOp( avar( " vec3 _tempDepth = fract(@.a * vec3(1.0, %llu.0, %llu.0));\r\n", maxValPerChannel - 1, extraVal ), + meta->addStatement( new GenOp( avar( " float2 _tempDepth = frac(@.a * float2(1.0, %llu.0));\r\n", maxValPerChannel - 1 ), unconditionedOutput ) ); - meta->addStatement( new GenOp( avar( " @.zw = _tempDepth.xy - _tempDepth.yz * vec2(1.0/%llu.0, 1.0/%llu.0);\r\n\r\n", maxValPerChannel - 1, maxValPerChannel - 1 ), + meta->addStatement( new GenOp( avar( " @.zw = _tempDepth.xy - _tempDepth.yy * float2(1.0/%llu.0, 0.0);\r\n\r\n", maxValPerChannel - 1 ), retVar ) ); } @@ -274,33 +348,43 @@ Var* GBufferConditionerGLSL::_conditionOutput( Var *unconditionedOutput, MultiLi Var* GBufferConditionerGLSL::_unconditionInput( Var *conditionedInput, MultiLine *meta ) { Var *retVar = new Var; - retVar->setType("vec4"); + retVar->setType("float4"); retVar->setName("_gbUnconditionedInput"); LangElement *outputDecl = new DecOp( retVar ); switch(mNormalStorageType) { case CartesianXYZ: - meta->addStatement( new GenOp( " // g-buffer unconditioner: vec4(normal.xyz, depth)\r\n" ) ); - meta->addStatement( new GenOp( " @ = vec4(@, @.a);\r\n", outputDecl, + meta->addStatement( new GenOp( " // g-buffer unconditioner: float4(normal.xyz, depth)\r\n" ) ); + meta->addStatement( new GenOp( " @ = float4(@, @.a);\r\n", outputDecl, _posnegDecode(new GenOp("@.xyz", conditionedInput)), conditionedInput ) ); break; case CartesianXY: - meta->addStatement( new GenOp( " // g-buffer unconditioner: vec4(normal.xy, depth Hi + z-sign, depth Lo)\r\n" ) ); - meta->addStatement( new GenOp( " @ = vec4(@, @.a);\r\n", outputDecl, + meta->addStatement( new GenOp( " // g-buffer unconditioner: float4(normal.xy, depth Hi + z-sign, depth Lo)\r\n" ) ); + meta->addStatement( new GenOp( " @ = float4(@, @.a);\r\n", outputDecl, _posnegDecode(new GenOp("@.xyz", conditionedInput)), conditionedInput ) ); meta->addStatement( new GenOp( " @.z *= sqrt(1.0 - dot(@.xy, @.xy));\r\n", retVar, retVar, retVar ) ); break; case Spherical: - meta->addStatement( new GenOp( " // g-buffer unconditioner: vec4(normal.theta, normal.phi, depth Hi, depth Lo)\r\n" ) ); - meta->addStatement( new GenOp( " vec2 spGPUAngles = @;\r\n", _posnegDecode(new GenOp("@.xy", conditionedInput)) ) ); - meta->addStatement( new GenOp( " vec2 sincosTheta;\r\n" ) ); - meta->addStatement( new GenOp( " sincosTheta.x = sin(spGPUAngles.x * 3.14159265358979323846);\r\n" ) ); - meta->addStatement( new GenOp( " sincosTheta.y = cos(spGPUAngles.x * 3.14159265358979323846);\r\n" ) ); - meta->addStatement( new GenOp( " vec2 sincosPhi = vec2(sqrt(1.0 - spGPUAngles.y * spGPUAngles.y), spGPUAngles.y);\r\n" ) ); - meta->addStatement( new GenOp( " @ = vec4(sincosTheta.y * sincosPhi.x, sincosTheta.x * sincosPhi.x, sincosPhi.y, @.a);\r\n", outputDecl, conditionedInput ) ); + meta->addStatement( new GenOp( " // g-buffer unconditioner: float4(normal.theta, normal.phi, depth Hi, depth Lo)\r\n" ) ); + meta->addStatement( new GenOp( " float2 spGPUAngles = @;\r\n", _posnegDecode(new GenOp("@.xy", conditionedInput)) ) ); + meta->addStatement( new GenOp( " float2 sincosTheta;\r\n" ) ); + meta->addStatement( new GenOp( " sincos(spGPUAngles.x * 3.14159265358979323846f, sincosTheta.x, sincosTheta.y);\r\n" ) ); + meta->addStatement( new GenOp( " float2 sincosPhi = float2(sqrt(1.0 - spGPUAngles.y * spGPUAngles.y), spGPUAngles.y);\r\n" ) ); + meta->addStatement( new GenOp( " @ = float4(sincosTheta.y * sincosPhi.x, sincosTheta.x * sincosPhi.x, sincosPhi.y, @.a);\r\n", outputDecl, conditionedInput ) ); + break; + + case LambertAzimuthal: + // Note we're casting to half to use partial precision + // sqrt which is much faster on older Geforces while + // still being acceptable for normals. + // + meta->addStatement( new GenOp( " // g-buffer unconditioner: float4(normal.X, normal.Y, depth Hi, depth Lo)\r\n" ) ); + meta->addStatement( new GenOp( " float2 _inpXY = @;\r\n", _posnegDecode(new GenOp("@.xy", conditionedInput)) ) ); + meta->addStatement( new GenOp( " float _xySQ = dot(_inpXY, _inpXY);\r\n" ) ); + meta->addStatement( new GenOp( " @ = float4( sqrt(half(1.0 - (_xySQ / 4.0))) * _inpXY, -1.0 + (_xySQ / 2.0), @.a).xzyw;\r\n", outputDecl, conditionedInput ) ); break; } @@ -309,7 +393,7 @@ Var* GBufferConditionerGLSL::_unconditionInput( Var *conditionedInput, MultiLine { const U64 maxValPerChannel = 1 << mBitsPerChannel; meta->addStatement( new GenOp( " \r\n // Decode depth\r\n" ) ); - meta->addStatement( new GenOp( avar( " @.w = dot( @.zw, vec2(1.0, 1.0/%llu.0));\r\n", maxValPerChannel - 1 ), + meta->addStatement( new GenOp( avar( " @.w = dot( @.zw, float2(1.0, 1.0/%llu.0));\r\n", maxValPerChannel - 1 ), retVar, conditionedInput ) ); } diff --git a/Engine/source/lighting/advanced/glsl/gBufferConditionerGLSL.h b/Engine/source/lighting/advanced/glsl/gBufferConditionerGLSL.h index 9e9364c88..640891824 100644 --- a/Engine/source/lighting/advanced/glsl/gBufferConditionerGLSL.h +++ b/Engine/source/lighting/advanced/glsl/gBufferConditionerGLSL.h @@ -42,6 +42,13 @@ public: CartesianXYZ, CartesianXY, Spherical, + LambertAzimuthal, + }; + + enum NormalSpace + { + WorldSpace, + ViewSpace, }; protected: @@ -52,7 +59,7 @@ protected: public: - GBufferConditionerGLSL( const GFXFormat bufferFormat ); + GBufferConditionerGLSL( const GFXFormat bufferFormat, const NormalSpace nrmSpace ); virtual ~GBufferConditionerGLSL(); diff --git a/Engine/source/lighting/advanced/hlsl/advancedLightingFeaturesHLSL.cpp b/Engine/source/lighting/advanced/hlsl/advancedLightingFeaturesHLSL.cpp index c2bf42834..9e04f3f76 100644 --- a/Engine/source/lighting/advanced/hlsl/advancedLightingFeaturesHLSL.cpp +++ b/Engine/source/lighting/advanced/hlsl/advancedLightingFeaturesHLSL.cpp @@ -479,7 +479,7 @@ void DeferredPixelSpecularHLSL::processPix( Vector &component "DeferredPixelSpecularHLSL::processPix - Something hosed the deferred features!" ); // (a^m)^n = a^(m*n) - meta->addStatement( new GenOp( " @ = pow( @, ceil(@ / AL_ConstantSpecularPower)) * @;\r\n", + meta->addStatement( new GenOp( " @ = pow( abs(@), max((@ / AL_ConstantSpecularPower),1.0f)) * @;\r\n", specDecl, d_specular, specPow, specStrength ) ); LangElement *specMul = new GenOp( "float4( @.rgb, 0 ) * @", specCol, specular ); diff --git a/Engine/source/lighting/advanced/hlsl/gBufferConditionerHLSL.cpp b/Engine/source/lighting/advanced/hlsl/gBufferConditionerHLSL.cpp index d4d30f9ad..ed946e944 100644 --- a/Engine/source/lighting/advanced/hlsl/gBufferConditionerHLSL.cpp +++ b/Engine/source/lighting/advanced/hlsl/gBufferConditionerHLSL.cpp @@ -333,7 +333,7 @@ Var* GBufferConditionerHLSL::_conditionOutput( Var *unconditionedOutput, MultiLi // Encode depth into two channels if(mNormalStorageType != CartesianXYZ) { - const U64 maxValPerChannel = 1 << mBitsPerChannel; + const U64 maxValPerChannel = (U64)1 << mBitsPerChannel; meta->addStatement( new GenOp( " \r\n // Encode depth into hi/lo\r\n" ) ); meta->addStatement( new GenOp( avar( " float2 _tempDepth = frac(@.a * float2(1.0, %llu.0));\r\n", maxValPerChannel - 1 ), unconditionedOutput ) ); @@ -391,7 +391,7 @@ Var* GBufferConditionerHLSL::_unconditionInput( Var *conditionedInput, MultiLine // Recover depth from encoding if(mNormalStorageType != CartesianXYZ) { - const U64 maxValPerChannel = 1 << mBitsPerChannel; + const U64 maxValPerChannel = (U64)1 << mBitsPerChannel; meta->addStatement( new GenOp( " \r\n // Decode depth\r\n" ) ); meta->addStatement( new GenOp( avar( " @.w = dot( @.zw, float2(1.0, 1.0/%llu.0));\r\n", maxValPerChannel - 1 ), retVar, conditionedInput ) ); diff --git a/Engine/source/lighting/common/projectedShadow.cpp b/Engine/source/lighting/common/projectedShadow.cpp index ed4a7b903..8918ddf5a 100644 --- a/Engine/source/lighting/common/projectedShadow.cpp +++ b/Engine/source/lighting/common/projectedShadow.cpp @@ -53,8 +53,8 @@ SimObjectPtr ProjectedShadow::smRenderPass = NULL; SimObjectPtr ProjectedShadow::smShadowFilter = NULL; F32 ProjectedShadow::smDepthAdjust = 10.0f; -float ProjectedShadow::smFadeStartPixelSize = 200.0f; -float ProjectedShadow::smFadeEndPixelSize = 35.0f; +F32 ProjectedShadow::smFadeStartPixelSize = 200.0f; +F32 ProjectedShadow::smFadeEndPixelSize = 35.0f; GFX_ImplementTextureProfile( BLProjectedShadowProfile, @@ -62,14 +62,14 @@ GFX_ImplementTextureProfile( BLProjectedShadowProfile, GFXTextureProfile::PreserveSize | GFXTextureProfile::RenderTarget | GFXTextureProfile::Pooled, - GFXTextureProfile::None ); + GFXTextureProfile::NONE ); GFX_ImplementTextureProfile( BLProjectedShadowZProfile, GFXTextureProfile::DiffuseMap, GFXTextureProfile::PreserveSize | GFXTextureProfile::ZTarget | GFXTextureProfile::Pooled, - GFXTextureProfile::None ); + GFXTextureProfile::NONE ); ProjectedShadow::ProjectedShadow( SceneObject *object ) diff --git a/Engine/source/lighting/common/projectedShadow.h b/Engine/source/lighting/common/projectedShadow.h index 7b519f3ab..e43501a8d 100644 --- a/Engine/source/lighting/common/projectedShadow.h +++ b/Engine/source/lighting/common/projectedShadow.h @@ -109,8 +109,8 @@ protected: public: /// @see DecalData - static float smFadeStartPixelSize; - static float smFadeEndPixelSize; + static F32 smFadeStartPixelSize; + static F32 smFadeEndPixelSize; ProjectedShadow( SceneObject *object ); virtual ~ProjectedShadow(); diff --git a/Engine/source/lighting/common/sceneLighting.cpp b/Engine/source/lighting/common/sceneLighting.cpp index f542753ab..aa62782f8 100644 --- a/Engine/source/lighting/common/sceneLighting.cpp +++ b/Engine/source/lighting/common/sceneLighting.cpp @@ -859,7 +859,7 @@ struct CacheEntry { }; // object list sort methods: want list in reverse -static int QSORT_CALLBACK minSizeSort(const void * p1, const void * p2) +static S32 QSORT_CALLBACK minSizeSort(const void * p1, const void * p2) { const CacheEntry * entry1 = (const CacheEntry *)p1; const CacheEntry * entry2 = (const CacheEntry *)p2; @@ -867,7 +867,7 @@ static int QSORT_CALLBACK minSizeSort(const void * p1, const void * p2) return(entry2->mFileObject->getSize() - entry1->mFileObject->getSize()); } -static int QSORT_CALLBACK maxSizeSort(const void * p1, const void * p2) +static S32 QSORT_CALLBACK maxSizeSort(const void * p1, const void * p2) { const CacheEntry * entry1 = (const CacheEntry *)p1; const CacheEntry * entry2 = (const CacheEntry *)p2; @@ -875,7 +875,7 @@ static int QSORT_CALLBACK maxSizeSort(const void * p1, const void * p2) return(entry1->mFileObject->getSize() - entry2->mFileObject->getSize()); } -static int QSORT_CALLBACK lastCreatedSort(const void * p1, const void * p2) +static S32 QSORT_CALLBACK lastCreatedSort(const void * p1, const void * p2) { const CacheEntry * entry1 = (const CacheEntry *)p1; const CacheEntry * entry2 = (const CacheEntry *)p2; @@ -899,7 +899,7 @@ static int QSORT_CALLBACK lastCreatedSort(const void * p1, const void * p2) return(Platform::compareFileTimes(create[1], create[0])); } -static int QSORT_CALLBACK lastModifiedSort(const void * p1, const void * p2) +static S32 QSORT_CALLBACK lastModifiedSort(const void * p1, const void * p2) { const CacheEntry * entry1 = (const CacheEntry *)p1; const CacheEntry * entry2 = (const CacheEntry *)p2; @@ -1051,7 +1051,7 @@ U32 SceneLighting::calcMissionCRC() // of U32's, and so the result will be different on big/little endian hardware. // To fix this, swap endians on the CRC's in the vector. This must be done // _after_ the qsort. - for( int i = 0; i < crc.size(); i++ ) + for( S32 i = 0; i < crc.size(); i++ ) crc[i] = endianSwap( crc[i] ); #endif diff --git a/Engine/source/lighting/shadowMap/lightShadowMap.cpp b/Engine/source/lighting/shadowMap/lightShadowMap.cpp index a25b7e706..3a85a0b40 100644 --- a/Engine/source/lighting/shadowMap/lightShadowMap.cpp +++ b/Engine/source/lighting/shadowMap/lightShadowMap.cpp @@ -70,7 +70,7 @@ GFX_ImplementTextureProfile( ShadowMapProfile, GFXTextureProfile::PreserveSize | GFXTextureProfile::RenderTarget | GFXTextureProfile::Pooled, - GFXTextureProfile::None ); + GFXTextureProfile::NONE ); GFX_ImplementTextureProfile( ShadowMapZProfile, GFXTextureProfile::DiffuseMap, @@ -78,7 +78,7 @@ GFX_ImplementTextureProfile( ShadowMapZProfile, GFXTextureProfile::NoMipmap | GFXTextureProfile::ZTarget | GFXTextureProfile::Pooled, - GFXTextureProfile::None ); + GFXTextureProfile::NONE ); LightShadowMap::LightShadowMap( LightInfo *light ) diff --git a/Engine/source/lighting/shadowMap/pssmLightShadowMap.h b/Engine/source/lighting/shadowMap/pssmLightShadowMap.h index 8ced7b875..d2fffde8e 100644 --- a/Engine/source/lighting/shadowMap/pssmLightShadowMap.h +++ b/Engine/source/lighting/shadowMap/pssmLightShadowMap.h @@ -58,7 +58,7 @@ protected: Box3F _calcClipSpaceAABB(const Frustum& f, const MatrixF& transform, F32 farDist); void _roundProjection(const MatrixF& lightMat, const MatrixF& cropMatrix, Point3F &offset, U32 splitNum); - static const int MAX_SPLITS = 4; + static const S32 MAX_SPLITS = 4; U32 mNumSplits; F32 mSplitDist[MAX_SPLITS+1]; // +1 because we store a cap RectI mViewports[MAX_SPLITS]; diff --git a/Engine/source/lighting/shadowMap/shadowMapManager.cpp b/Engine/source/lighting/shadowMap/shadowMapManager.cpp index 078737db9..cfcf75f81 100644 --- a/Engine/source/lighting/shadowMap/shadowMapManager.cpp +++ b/Engine/source/lighting/shadowMap/shadowMapManager.cpp @@ -37,7 +37,7 @@ GFX_ImplementTextureProfile(ShadowMapTexProfile, GFXTextureProfile::DiffuseMap, GFXTextureProfile::PreserveSize | GFXTextureProfile::Dynamic , - GFXTextureProfile::None); + GFXTextureProfile::NONE); MODULE_BEGIN( ShadowMapManager ) diff --git a/Engine/source/main/main.cpp b/Engine/source/main/main.cpp index 86907b5e5..fbc97226a 100644 --- a/Engine/source/main/main.cpp +++ b/Engine/source/main/main.cpp @@ -25,48 +25,57 @@ #ifdef WIN32 #include -#include +#include extern "C" { int (*torque_winmain)( HINSTANCE hInstance, HINSTANCE h, LPSTR lpszCmdLine, int nShow) = NULL; }; +bool getDllName(std::wstring& dllName) +{ + wchar_t filenameBuf[MAX_PATH]; + DWORD length = GetModuleFileNameW( NULL, filenameBuf, MAX_PATH ); + if(length == 0) return false; + dllName = std::wstring(filenameBuf); + size_t dotPos = dllName.find_last_of(L"."); + if(dotPos == std::wstring::npos) return false; + dllName.erase(dotPos); + dllName += L".dll"; + return true; +} + int PASCAL WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpszCmdLine, int nCommandShow) { - char filename[4096]; - char gameLib[4096]; + std::wstring dllName = std::wstring(); + if(!getDllName(dllName)) + { + MessageBoxW(NULL, L"Unable to find game dll", L"Error", MB_OK|MB_ICONWARNING); + return -1; + } - GetModuleFileNameA(NULL, filename, 4096); - filename[strlen(filename)-4] = 0; - sprintf(gameLib, "%s.dll", filename); - - HMODULE hGame = LoadLibraryA(gameLib); - - if (hGame) - torque_winmain = (int (*)(HINSTANCE hInstance, HINSTANCE h, LPSTR lpszCmdLine, int nShow))GetProcAddress(hGame, "torque_winmain"); - - char error[4096]; + HMODULE hGame = LoadLibraryW(dllName.c_str()); if (!hGame) { - sprintf(error, "Unable to load game library: %s. Please make sure it exists and the latest DirectX is installed.", gameLib); - MessageBoxA(NULL, error, "Error", MB_OK|MB_ICONWARNING); + wchar_t error[4096]; + _swprintf_l(error, sizeof(error), L"Unable to load game library: %s. Please make sure it exists and the latest DirectX is installed.", _get_current_locale(), dllName.c_str()); + MessageBoxW(NULL, error, L"Error", MB_OK|MB_ICONWARNING); return -1; } + torque_winmain = (int (*)(HINSTANCE hInstance, HINSTANCE h, LPSTR lpszCmdLine, int nShow))GetProcAddress(hGame, "torque_winmain"); if (!torque_winmain) { - sprintf(error, "Missing torque_winmain export in game library: %s. Please make sure that it exists and the latest DirectX is installed.", gameLib); - MessageBoxA(NULL, error, "Error", MB_OK|MB_ICONWARNING); + wchar_t error[4096]; + _swprintf_l(error, sizeof(error), L"Missing torque_winmain export in game library: %s. Please make sure that it exists and the latest DirectX is installed.", _get_current_locale(), dllName.c_str()); + MessageBoxW(NULL, error, L"Error", MB_OK|MB_ICONWARNING); return -1; } - int ret = torque_winmain(hInstance, hPrevInstance, lpszCmdLine, nCommandShow ); + int ret = torque_winmain(hInstance, hPrevInstance, lpszCmdLine, nCommandShow); FreeLibrary(hGame); - return ret; - } #endif // WIN32 diff --git a/Engine/source/materials/miscShdrDat.h b/Engine/source/materials/miscShdrDat.h index 6441f1b07..25422008d 100644 --- a/Engine/source/materials/miscShdrDat.h +++ b/Engine/source/materials/miscShdrDat.h @@ -41,6 +41,7 @@ enum RegisterType RT_NORMAL, RT_BINORMAL, RT_TANGENT, + RT_TANGENTW, RT_COLOR, RT_TEXCOORD, RT_VPOS, diff --git a/Engine/source/materials/processedMaterial.cpp b/Engine/source/materials/processedMaterial.cpp index 34ce285a0..9e82c65b1 100644 --- a/Engine/source/materials/processedMaterial.cpp +++ b/Engine/source/materials/processedMaterial.cpp @@ -41,7 +41,10 @@ RenderPassData::RenderPassData() void RenderPassData::reset() { for( U32 i = 0; i < Material::MAX_TEX_PER_PASS; ++ i ) + { destructInPlace( &mTexSlot[ i ] ); + mSamplerNames[ i ].clear(); + } dMemset( &mTexSlot, 0, sizeof(mTexSlot) ); dMemset( &mTexType, 0, sizeof(mTexType) ); diff --git a/Engine/source/materials/processedMaterial.h b/Engine/source/materials/processedMaterial.h index 841825aab..b72422cf9 100644 --- a/Engine/source/materials/processedMaterial.h +++ b/Engine/source/materials/processedMaterial.h @@ -68,6 +68,7 @@ public: } mTexSlot[Material::MAX_TEX_PER_PASS]; U32 mTexType[Material::MAX_TEX_PER_PASS]; + String mSamplerNames[Material::MAX_TEX_PER_PASS]; /// The cubemap to use when the texture type is /// set to Material::Cube. diff --git a/Engine/source/materials/processedShaderMaterial.cpp b/Engine/source/materials/processedShaderMaterial.cpp index 01741f496..410773d7e 100644 --- a/Engine/source/materials/processedShaderMaterial.cpp +++ b/Engine/source/materials/processedShaderMaterial.cpp @@ -285,7 +285,7 @@ void ProcessedShaderMaterial::_determineFeatures( U32 stageNum, { PROFILE_SCOPE( ProcessedShaderMaterial_DetermineFeatures ); - const float shaderVersion = GFX->getPixelShaderVersion(); + const F32 shaderVersion = GFX->getPixelShaderVersion(); AssertFatal(shaderVersion > 0.0 , "Cannot create a shader material if we don't support shaders"); bool lastStage = stageNum == (mMaxStages-1); diff --git a/Engine/source/math/mBox.cpp b/Engine/source/math/mBox.cpp index 2cdd730e3..c37e091c3 100644 --- a/Engine/source/math/mBox.cpp +++ b/Engine/source/math/mBox.cpp @@ -61,7 +61,7 @@ bool Box3F::collideLine(const Point3F& start, const Point3F& end, F32* t, Point3 static const Point3F na[3] = { Point3F(1.0f, 0.0f, 0.0f), Point3F(0.0f, 1.0f, 0.0f), Point3F(0.0f, 0.0f, 1.0f) }; Point3F finalNormal(0.0f, 0.0f, 0.0f); - for (int i = 0; i < 3; i++) { + for (S32 i = 0; i < 3; i++) { bool n_neg = false; if (si[i] < ei[i]) { if (si[i] > bmax[i] || ei[i] < bmin[i]) diff --git a/Engine/source/math/mBox.h b/Engine/source/math/mBox.h index e0c028b60..379d5291a 100644 --- a/Engine/source/math/mBox.h +++ b/Engine/source/math/mBox.h @@ -334,10 +334,18 @@ inline Box3F Box3F::getOverlap( const Box3F& otherBox ) const Box3F overlap; for( U32 i = 0; i < 3; ++ i ) + { if( minExtents[ i ] > otherBox.maxExtents[ i ] || otherBox.minExtents[ i ] > maxExtents[ i ] ) + { overlap.minExtents[ i ] = 0.f; + overlap.maxExtents[ i ] = 0.f; + } else + { overlap.minExtents[ i ] = getMax( minExtents[ i ], otherBox.minExtents[ i ] ); + overlap.maxExtents[ i ] = getMin( maxExtents[ i ], otherBox.maxExtents[ i ] ); + } + } return overlap; } diff --git a/Engine/source/math/mMathAltivec.cpp b/Engine/source/math/mMathAltivec.cpp index 6bdc9d752..c056a6449 100644 --- a/Engine/source/math/mMathAltivec.cpp +++ b/Engine/source/math/mMathAltivec.cpp @@ -38,9 +38,9 @@ /// because we get a much better speed gain if we can assume the data is aligned. void vec_MatrixF_x_MatrixF(const F32 *matA, const F32 *matB, F32 *result) { - vector float A[4][1]; - vector float B[4][1]; - vector float C[4][1]; + vector F32 A[4][1]; + vector F32 B[4][1]; + vector F32 C[4][1]; /// If the incoming pointers are not 16-byte aligned, we have to load & store the slow way. if((int)matA & 0xF || (int)matB & 0xF || (int)result & 0xF) diff --git a/Engine/source/math/mMathFn.h b/Engine/source/math/mMathFn.h index cdeb4b4f5..6b41cfa89 100644 --- a/Engine/source/math/mMathFn.h +++ b/Engine/source/math/mMathFn.h @@ -442,7 +442,7 @@ inline bool mIsNaN_F( const F32 x ) inline bool mIsInf_F( const F32 x ) { - return ( x == std::numeric_limits< float >::infinity() ); + return ( x == std::numeric_limits< F32 >::infinity() ); } inline F32 mSign( const F32 n ) diff --git a/Engine/source/math/mPolyhedron.h b/Engine/source/math/mPolyhedron.h index 00723466f..dbb874817 100644 --- a/Engine/source/math/mPolyhedron.h +++ b/Engine/source/math/mPolyhedron.h @@ -229,7 +229,7 @@ struct PolyhedronUnmanagedVectorData : public PolyhedronData }; /// Polyhedron data stored in fixed size arrays. -template< int NUM_PLANES, int NUM_POINTS, int NUM_EDGES > +template< S32 NUM_PLANES, S32 NUM_POINTS, S32 NUM_EDGES > struct PolyhedronFixedVectorData : public PolyhedronData { typedef FixedSizeVector< PlaneF, NUM_PLANES > PlaneListType; @@ -479,7 +479,7 @@ inline PolyhedronVectorData::operator AnyPolyhedron() const //----------------------------------------------------------------------------- -template< int NUM_PLANES, int NUM_POINTS, int NUM_EDGES > +template< S32 NUM_PLANES, S32 NUM_POINTS, S32 NUM_EDGES > inline PolyhedronFixedVectorData< NUM_PLANES, NUM_POINTS, NUM_EDGES >::operator AnyPolyhedron() const { return AnyPolyhedron( diff --git a/Engine/source/math/mQuadPatch.cpp b/Engine/source/math/mQuadPatch.cpp index 24e67dd33..efb300e0b 100644 --- a/Engine/source/math/mQuadPatch.cpp +++ b/Engine/source/math/mQuadPatch.cpp @@ -52,7 +52,7 @@ void QuadPatch::submitControlPoints( SplCtrlPts &points ) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -void QuadPatch::setControlPoint( Point3F &point, int index ) +void QuadPatch::setControlPoint( Point3F &point, S32 index ) { ( (SplCtrlPts*) getControlPoints() )->setPoint( point, index ); calcABC( getControlPoint(0) ); diff --git a/Engine/source/math/mQuadPatch.h b/Engine/source/math/mQuadPatch.h index 22dcb1ffc..d579ca367 100644 --- a/Engine/source/math/mQuadPatch.h +++ b/Engine/source/math/mQuadPatch.h @@ -51,7 +51,7 @@ public: virtual void calc( F32 t, Point3F &result ); virtual void calc( Point3F *points, F32 t, Point3F &result ); - virtual void setControlPoint( Point3F &point, int index ); + virtual void setControlPoint( Point3F &point, S32 index ); virtual void submitControlPoints( SplCtrlPts &points ); diff --git a/Engine/source/math/mQuat.cpp b/Engine/source/math/mQuat.cpp index 78c9fb100..c78252bc2 100644 --- a/Engine/source/math/mQuat.cpp +++ b/Engine/source/math/mQuat.cpp @@ -262,12 +262,12 @@ QuatF & QuatF::interpolate( const QuatF & q1, const QuatF & q2, F32 t ) //----------------------------------- // calculate interpolating coeffs: - double scale1, scale2; + F64 scale1, scale2; if ( (1.0 - cosOmega) > 0.00001 ) { // standard case - double omega = mAcos(cosOmega); - double sinOmega = mSin(omega); + F64 omega = mAcos(cosOmega); + F64 sinOmega = mSin(omega); scale1 = mSin((1.0 - t) * omega) / sinOmega; scale2 = sign2 * mSin(t * omega) / sinOmega; } diff --git a/Engine/source/math/mQuat.h b/Engine/source/math/mQuat.h index 34cae7e84..433b30155 100644 --- a/Engine/source/math/mQuat.h +++ b/Engine/source/math/mQuat.h @@ -55,8 +55,8 @@ public: QuatF& set( const AngAxisF & a ); QuatF& set( const EulerF & e ); - int operator ==( const QuatF & c ) const; - int operator !=( const QuatF & c ) const; + S32 operator ==( const QuatF & c ) const; + S32 operator !=( const QuatF & c ) const; QuatF& operator *=( const QuatF & c ); QuatF& operator /=( const QuatF & c ); QuatF& operator +=( const QuatF & c ); @@ -75,7 +75,7 @@ public: QuatF& normalize(); QuatF& inverse(); QuatF& identity(); - int isIdentity() const; + S32 isIdentity() const; QuatF& slerp( const QuatF & q, F32 t ); QuatF& extrapolate( const QuatF & q1, const QuatF & q2, F32 t ); QuatF& interpolate( const QuatF & q1, const QuatF & q2, F32 t ); diff --git a/Engine/source/math/mSplinePatch.cpp b/Engine/source/math/mSplinePatch.cpp index 467feb9df..9d52c5150 100644 --- a/Engine/source/math/mSplinePatch.cpp +++ b/Engine/source/math/mSplinePatch.cpp @@ -68,7 +68,7 @@ void SplCtrlPts::submitPoints( Point3F *pts, U32 num ) { mPoints.clear(); - for( int i=0; iremoveTile(nm->getTileRefAt(tile.x, tile.y, 0), 0, 0); // Add new data (navmesh owns and deletes the data). dtStatus status = nm->addTile(data, dataSize, DT_TILE_FREE_DATA, 0, 0); - int success = 1; + if(dtStatusFailed(status)) { - success = 0; dtFree(data); } } diff --git a/Engine/source/platform/input/event.cpp b/Engine/source/platform/input/event.cpp index 254aca29d..45b89e85f 100644 --- a/Engine/source/platform/input/event.cpp +++ b/Engine/source/platform/input/event.cpp @@ -381,7 +381,7 @@ CodeMapping gVirtualMap[] = { "lpov2", SI_POV, SI_LPOV2 }, { "rpov2", SI_POV, SI_RPOV2 }, -#if defined( TORQUE_OS_WIN32 ) || defined( TORQUE_OS_XENON ) +#if defined( TORQUE_OS_WIN ) || defined( TORQUE_OS_XENON ) //-------------------------------------- XINPUT EVENTS // Controller connect / disconnect: { "connect", SI_BUTTON, XI_CONNECT }, @@ -500,7 +500,7 @@ void InputEventManager::buildInputEvent(U32 deviceType, U32 deviceInst, InputEve newEvent.postToSignal(Input::smInputEvent); } -void InputEventManager::buildInputEvent(U32 deviceType, U32 deviceInst, InputEventType objType, InputObjectInstances objInst, InputActionType action, float fValue) +void InputEventManager::buildInputEvent(U32 deviceType, U32 deviceInst, InputEventType objType, InputObjectInstances objInst, InputActionType action, F32 fValue) { InputEventInfo newEvent; diff --git a/Engine/source/platform/input/event.h b/Engine/source/platform/input/event.h index 965dc0ac6..916d1910f 100644 --- a/Engine/source/platform/input/event.h +++ b/Engine/source/platform/input/event.h @@ -496,7 +496,7 @@ public: void buildInputEvent(U32 deviceType, U32 deviceInst, InputEventType objType, InputObjectInstances objInst, InputActionType action, S32 iValue); /// Build an input event based on a single fValue - void buildInputEvent(U32 deviceType, U32 deviceInst, InputEventType objType, InputObjectInstances objInst, InputActionType action, float fValue); + void buildInputEvent(U32 deviceType, U32 deviceInst, InputEventType objType, InputObjectInstances objInst, InputActionType action, F32 fValue); /// Build an input event based on a Point3F void buildInputEvent(U32 deviceType, U32 deviceInst, InputEventType objType, InputObjectInstances objInst, InputActionType action, Point3F& pValue); diff --git a/Engine/source/platform/input/razerHydra/razerHydraDevice.cpp b/Engine/source/platform/input/razerHydra/razerHydraDevice.cpp index 89dd771f3..8a36bd9d6 100644 --- a/Engine/source/platform/input/razerHydra/razerHydraDevice.cpp +++ b/Engine/source/platform/input/razerHydra/razerHydraDevice.cpp @@ -260,7 +260,7 @@ bool RazerHydraDevice::enable() #endif const char* dllName; -#ifdef TORQUE_OS_WIN32 +#ifdef TORQUE_OS_WIN #ifdef TORQUE_DEBUG dllName = "sixensed.dll"; #else diff --git a/Engine/source/platform/platform.h b/Engine/source/platform/platform.h index eeda303b9..3b5a57358 100644 --- a/Engine/source/platform/platform.h +++ b/Engine/source/platform/platform.h @@ -212,7 +212,7 @@ namespace Platform void debugBreak(); // Random - float getRandom(); + F32 getRandom(); // Window state void setWindowLocked(bool locked); @@ -412,7 +412,7 @@ namespace Platform //------------------------------------------------------------------------------ // Misc StdLib functions #define QSORT_CALLBACK FN_CDECL -inline void dQsort(void *base, U32 nelem, U32 width, int (QSORT_CALLBACK *fcmp)(const void *, const void *)) +inline void dQsort(void *base, U32 nelem, U32 width, S32 (QSORT_CALLBACK *fcmp)(const void *, const void *)) { qsort(base, nelem, width, fcmp); } @@ -507,7 +507,7 @@ extern void* dRealloc_r(void* in_pResize, dsize_t in_size, const char*, const ds extern void* dRealMalloc(dsize_t); extern void dRealFree(void*); -extern void *dMalloc_aligned(dsize_t in_size, int alignment); +extern void *dMalloc_aligned(dsize_t in_size, S32 alignment); extern void dFree_aligned(void *); @@ -525,8 +525,8 @@ template void dCopyArray(T *dst, const S *src, dsize_t size) extern void* dMemcpy(void *dst, const void *src, dsize_t size); extern void* dMemmove(void *dst, const void *src, dsize_t size); -extern void* dMemset(void *dst, int c, dsize_t size); -extern int dMemcmp(const void *ptr1, const void *ptr2, dsize_t size); +extern void* dMemset(void *dst, S32 c, dsize_t size); +extern S32 dMemcmp(const void *ptr1, const void *ptr2, dsize_t size); // Special case of the above function when the arrays are the same type (use memcpy) template void dCopyArray(T *dst, const T *src, dsize_t size) @@ -565,8 +565,8 @@ enum DFILE_STATUS extern FILE_HANDLE dOpenFileRead(const char *name, DFILE_STATUS &error); extern FILE_HANDLE dOpenFileReadWrite(const char *name, bool append, DFILE_STATUS &error); -extern int dFileRead(FILE_HANDLE handle, U32 bytes, char *dst, DFILE_STATUS &error); -extern int dFileWrite(FILE_HANDLE handle, U32 bytes, const char *dst, DFILE_STATUS &error); +extern S32 dFileRead(FILE_HANDLE handle, U32 bytes, char *dst, DFILE_STATUS &error); +extern S32 dFileWrite(FILE_HANDLE handle, U32 bytes, const char *dst, DFILE_STATUS &error); extern void dFileClose(FILE_HANDLE handle); extern StringTableEntry osGetTemporaryDirectory(); diff --git a/Engine/source/platform/platformAssert.h b/Engine/source/platform/platformAssert.h index 4865d387c..60ed7d3d5 100644 --- a/Engine/source/platform/platformAssert.h +++ b/Engine/source/platform/platformAssert.h @@ -96,8 +96,8 @@ public: { if ( ::PlatformAssert::processAssert(::PlatformAssert::Fatal, __FILE__, __LINE__, y) ) { ::Platform::debugBreak(); } } } #else - #define AssertFatal(x, y) { (void)sizeof(x); (void)sizeof(y); } - #define AssertWarn(x, y) { (void)sizeof(x); (void)sizeof(y); } + #define AssertFatal(x, y) { TORQUE_UNUSED(x); TORQUE_UNUSED(y); } + #define AssertWarn(x, y) { TORQUE_UNUSED(x); TORQUE_UNUSED(y); } #endif /*! diff --git a/Engine/source/platform/platformCPUCount.cpp b/Engine/source/platform/platformCPUCount.cpp index 116251e08..7db6500e3 100644 --- a/Engine/source/platform/platformCPUCount.cpp +++ b/Engine/source/platform/platformCPUCount.cpp @@ -53,7 +53,7 @@ EConfig CPUCount(U32& TotAvailLogical, U32& TotAvailCore, U32& PhysicalNum) #include #include #define DWORD unsigned long -#elif defined( TORQUE_OS_WIN32 ) +#elif defined( TORQUE_OS_WIN ) #include #elif defined( TORQUE_OS_MAC ) # include @@ -80,13 +80,13 @@ namespace CPUInfo { #ifndef TORQUE_OS_MAC - static unsigned int CpuIDSupported(void); - static unsigned int find_maskwidth(unsigned int); - static unsigned int HWD_MTSupported(void); - static unsigned int MaxLogicalProcPerPhysicalProc(void); - static unsigned int MaxCorePerPhysicalProc(void); - static unsigned char GetAPIC_ID(void); - static unsigned char GetNzbSubID(unsigned char, unsigned char, unsigned char); + static U32 CpuIDSupported(void); + static U32 find_maskwidth(unsigned int); + static U32 HWD_MTSupported(void); + static U32 MaxLogicalProcPerPhysicalProc(void); + static U32 MaxCorePerPhysicalProc(void); + static U8 GetAPIC_ID(void); + static U8 GetNzbSubID(U8, U8, U8); #endif static char g_s3Levels[2048]; @@ -97,14 +97,13 @@ namespace CPUInfo { // CpuIDSupported will return 0 if CPUID instruction is unavailable. Otherwise, it will return // the maximum supported standard function. // - static unsigned int CpuIDSupported(void) + static U32 CpuIDSupported(void) { - unsigned int MaxInputValue; + U32 maxInputValue = 0; // If CPUID instruction is supported #ifdef TORQUE_COMPILER_GCC try { - MaxInputValue = 0; // call cpuid with eax = 0 asm ( @@ -112,7 +111,7 @@ namespace CPUInfo { "xorl %%eax,%%eax\n\t" "cpuid\n\t" "popl %%ebx\n\t" - : "=a" (MaxInputValue) + : "=a" (maxInputValue) : : "%ecx", "%edx" ); @@ -124,25 +123,23 @@ namespace CPUInfo { #elif defined( TORQUE_COMPILER_VISUALC ) try { - MaxInputValue = 0; // call cpuid with eax = 0 __asm { xor eax, eax cpuid - mov MaxInputValue, eax + mov maxInputValue, eax } } catch (...) { - return(0); // cpuid instruction is unavailable + // cpuid instruction is unavailable } #else # error Not implemented. #endif - return MaxInputValue; - + return maxInputValue; } @@ -153,12 +150,12 @@ namespace CPUInfo { // maximum value. // - static unsigned int MaxCorePerPhysicalProc(void) + static U32 MaxCorePerPhysicalProc(void) { - unsigned int Regeax = 0; + U32 Regeax = 0; - if (!HWD_MTSupported()) return (unsigned int) 1; // Single core + if (!HWD_MTSupported()) return (U32) 1; // Single core #ifdef TORQUE_COMPILER_GCC { asm @@ -209,7 +206,7 @@ multi_core: #else # error Not implemented. #endif - return (unsigned int)((Regeax & NUM_CORE_BITS) >> 26)+1; + return (U32)((Regeax & NUM_CORE_BITS) >> 26)+1; } @@ -218,11 +215,11 @@ multi_core: // // The function returns 0 when the hardware multi-threaded bit is not set. // - static unsigned int HWD_MTSupported(void) + static U32 HWD_MTSupported(void) { - unsigned int Regedx = 0; + U32 Regedx = 0; if ((CpuIDSupported() >= 1)) @@ -262,12 +259,12 @@ multi_core: // AVAILABLE logical processors per physical to be used by an application might be less than this // maximum value. // - static unsigned int MaxLogicalProcPerPhysicalProc(void) + static U32 MaxLogicalProcPerPhysicalProc(void) { - unsigned int Regebx = 0; + U32 Regebx = 0; - if (!HWD_MTSupported()) return (unsigned int) 1; + if (!HWD_MTSupported()) return (U32) 1; #ifdef TORQUE_COMPILER_GCC asm ( @@ -292,10 +289,10 @@ multi_core: } - static unsigned char GetAPIC_ID(void) + static U8 GetAPIC_ID(void) { - unsigned int Regebx = 0; + U32 Regebx = 0; #ifdef TORQUE_COMPILER_GCC asm ( @@ -324,9 +321,9 @@ multi_core: // // Determine the width of the bit field that can represent the value count_item. // - unsigned int find_maskwidth(unsigned int CountItem) + U32 find_maskwidth(U32 CountItem) { - unsigned int MaskWidth, + U32 MaskWidth, count = CountItem; #ifdef TORQUE_COMPILER_GCC asm @@ -392,16 +389,16 @@ next: // // Extract the subset of bit field from the 8-bit value FullID. It returns the 8-bit sub ID value // - static unsigned char GetNzbSubID(unsigned char FullID, - unsigned char MaxSubIDValue, - unsigned char ShiftCount) + static U8 GetNzbSubID(U8 FullID, + U8 MaxSubIDValue, + U8 ShiftCount) { - unsigned int MaskWidth; - unsigned char MaskBits; + U32 MaskWidth; + U8 MaskBits; - MaskWidth = find_maskwidth((unsigned int) MaxSubIDValue); + MaskWidth = find_maskwidth((U32) MaxSubIDValue); MaskBits = (0xff << ShiftCount) ^ - ((unsigned char) (0xff << (ShiftCount + MaskWidth))); + ((U8) (0xff << (ShiftCount + MaskWidth))); return (FullID & MaskBits); } @@ -420,8 +417,8 @@ next: TotAvailCore = 1; PhysicalNum = 1; - unsigned int numLPEnabled = 0; - int MaxLPPerCore = 1; + U32 numLPEnabled = 0; + S32 MaxLPPerCore = 1; #ifdef TORQUE_OS_MAC @@ -430,8 +427,8 @@ next: // like there isn't a way to do this that's working across all OSX incarnations // and machine configurations anyway. - int numCPUs; - int numPackages; + S32 numCPUs; + S32 numPackages; // Get the number of CPUs. @@ -450,9 +447,9 @@ next: #else U32 dwAffinityMask; - int j = 0; - unsigned char apicID, PackageIDMask; - unsigned char tblPkgID[256], tblCoreID[256], tblSMTID[256]; + S32 j = 0; + U8 apicID, PackageIDMask; + U8 tblPkgID[256], tblCoreID[256], tblSMTID[256]; char tmp[256]; #ifdef TORQUE_OS_LINUX @@ -464,19 +461,19 @@ next: // Linux doesn't easily allow us to look at the Affinity Bitmask directly, // but it does provide an API to test affinity maskbits of the current process // against each logical processor visible under OS. - int sysNumProcs = sysconf(_SC_NPROCESSORS_CONF); //This will tell us how many + S32 sysNumProcs = sysconf(_SC_NPROCESSORS_CONF); //This will tell us how many //CPUs are currently enabled. //this will tell us which processors this process can run on. cpu_set_t allowedCPUs; sched_getaffinity(0, sizeof(allowedCPUs), &allowedCPUs); - for (int i = 0; i < sysNumProcs; i++ ) + for (S32 i = 0; i < sysNumProcs; i++ ) { if ( CPU_ISSET(i, &allowedCPUs) == 0 ) return CONFIG_UserConfigIssue; } -#elif defined( TORQUE_OS_WIN32 ) +#elif defined( TORQUE_OS_WIN ) DWORD dwProcessAffinity, dwSystemAffinity; GetProcessAffinityMask(GetCurrentProcess(), &dwProcessAffinity, @@ -504,7 +501,7 @@ next: if ( sched_setaffinity (0, sizeof(currentCPU), ¤tCPU) == 0 ) { sleep(0); // Ensure system to switch to the right CPU -#elif defined( TORQUE_OS_WIN32 ) +#elif defined( TORQUE_OS_WIN ) while (dwAffinityMask && dwAffinityMask <= dwSystemAffinity) { if (SetThreadAffinityMask(GetCurrentThread(), dwAffinityMask)) @@ -522,8 +519,8 @@ next: // processors per core tblSMTID[j] = GetNzbSubID(apicID, MaxLPPerCore, 0); - unsigned char maxCorePPP = MaxCorePerPhysicalProc(); - unsigned char maskWidth = find_maskwidth(MaxLPPerCore); + U8 maxCorePPP = MaxCorePerPhysicalProc(); + U8 maskWidth = find_maskwidth(MaxLPPerCore); tblCoreID[j] = GetNzbSubID(apicID, maxCorePPP, maskWidth); // Extract package ID, assume single cluster. @@ -549,7 +546,7 @@ next: #ifdef TORQUE_OS_LINUX sched_setaffinity (0, sizeof(allowedCPUs), &allowedCPUs); sleep(0); -#elif defined( TORQUE_OS_WIN32 ) +#elif defined( TORQUE_OS_WIN ) SetThreadAffinityMask(GetCurrentThread(), dwProcessAffinity); Sleep(0); #else @@ -560,9 +557,9 @@ next: // // Count available cores (TotAvailCore) in the system // - unsigned char CoreIDBucket[256]; + U8 CoreIDBucket[256]; DWORD ProcessorMask, pCoreMask[256]; - unsigned int i, ProcessorNum; + U32 i, ProcessorNum; CoreIDBucket[0] = tblPkgID[0] | tblCoreID[0]; ProcessorMask = 1; @@ -598,7 +595,7 @@ next: // // Count physical processor (PhysicalNum) in the system // - unsigned char PackageIDBucket[256]; + U8 PackageIDBucket[256]; DWORD pPackageMask[256]; PackageIDBucket[0] = tblPkgID[0]; diff --git a/Engine/source/platform/platformFileIO.cpp b/Engine/source/platform/platformFileIO.cpp index 0209f239e..fc42c0565 100644 --- a/Engine/source/platform/platformFileIO.cpp +++ b/Engine/source/platform/platformFileIO.cpp @@ -140,7 +140,7 @@ inline void catPath(char *dst, const char *src, U32 len) // converts the posix root path "/" to "c:/" for win32 // FIXME: this is not ideal. the c: drive is not guaranteed to exist. -#if defined(TORQUE_OS_WIN32) +#if defined(TORQUE_OS_WIN) static inline void _resolveLeadingSlash(char* buf, U32 size) { if(buf[0] != '/') @@ -227,7 +227,7 @@ char * Platform::makeFullPathName(const char *path, char *buffer, U32 size, cons if(Platform::isFullPath(bspath)) { // Already a full path - #if defined(TORQUE_OS_WIN32) + #if defined(TORQUE_OS_WIN) _resolveLeadingSlash(bspath, sizeof(bspath)); #endif dStrncpy(buffer, bspath, size); diff --git a/Engine/source/platform/platformInput.h b/Engine/source/platform/platformInput.h index 6abc459e7..083e7ea85 100644 --- a/Engine/source/platform/platformInput.h +++ b/Engine/source/platform/platformInput.h @@ -118,6 +118,9 @@ public: static U8 getModifierKeys() {return smModifierKeys;} static void setModifierKeys(U8 mod) {smModifierKeys = mod;} + + static void attemptSwitchToKeyboardLayout( U32 layout ); + #ifdef LOG_INPUT static void log( const char* format, ... ); #endif diff --git a/Engine/source/platform/platformMemory.cpp b/Engine/source/platform/platformMemory.cpp index 925a15422..44a68d8a7 100644 --- a/Engine/source/platform/platformMemory.cpp +++ b/Engine/source/platform/platformMemory.cpp @@ -367,7 +367,7 @@ static U32 validateTreeRecurse(TreeNode *tree) if(tree == NIL) return 1; // check my left tree - int lcount, rcount, nc = 0; + S32 lcount, rcount, nc = 0; if(tree->color == Red) { @@ -798,19 +798,17 @@ void checkPtr( void* ptr ) AllocatedHeader* header = ( AllocatedHeader* ) *iter; if( header->getUserPtr() == ptr ) { - char buffer[ 1024 ]; - #ifdef TORQUE_DEBUG_GUARD + char buffer[ 1024 ]; if( !checkGuard( *iter, true ) ) { dSprintf( buffer, sizeof( buffer ), "0x%x is a valid heap pointer but has its guards corrupted", ptr ); Platform::outputDebugString( buffer ); return; } -#endif - //dSprintf( buffer, sizeof( buffer ), "0x%x is a valid heap pointer", ptr ); //Platform::outputDebugString( buffer ); +#endif return; } } @@ -1588,7 +1586,7 @@ dsize_t getMemoryUsed() } #ifdef TORQUE_DEBUG_GUARD -DefineEngineFunction( dumpAlloc, void, ( int allocNum ),, +DefineEngineFunction( dumpAlloc, void, ( S32 allocNum ),, "@brief Dumps information about the given allocated memory block.\n\n" "@param allocNum Memory block to dump information about." "@note Available in debug builds only. " diff --git a/Engine/source/platform/platformNet.cpp b/Engine/source/platform/platformNet.cpp index 786fcf62d..acc4e9905 100644 --- a/Engine/source/platform/platformNet.cpp +++ b/Engine/source/platform/platformNet.cpp @@ -23,14 +23,18 @@ #include "platform/platformNet.h" #include "core/strings/stringFunctions.h" -#if defined (TORQUE_OS_WIN32) +#if defined (TORQUE_OS_WIN) #define TORQUE_USE_WINSOCK #include #include + +#ifndef EINPROGRESS #define EINPROGRESS WSAEINPROGRESS +#endif // EINPROGRESS + #define ioctl ioctlsocket -typedef int socklen_t; +typedef S32 socklen_t; #elif defined ( TORQUE_OS_MAC ) @@ -84,7 +88,7 @@ typedef in_addr IN_ADDR; #define TORQUE_USE_WINSOCK #define EINPROGRESS WSAEINPROGRESS #define ioctl ioctlsocket -typedef int socklen_t; +typedef S32 socklen_t; DWORD _getLastErrorAndClear() { @@ -99,7 +103,7 @@ DWORD _getLastErrorAndClear() #endif #if defined(TORQUE_USE_WINSOCK) -static const char* strerror_wsa( int code ) +static const char* strerror_wsa( S32 code ) { switch( code ) { @@ -137,7 +141,7 @@ static const char* strerror_wsa( int code ) static Net::Error getLastError(); static S32 defaultPort = 28000; static S32 netPort = 0; -static int udpSocket = InvalidSocket; +static S32 udpSocket = InvalidSocket; ConnectionNotifyEvent Net::smConnectionNotify; ConnectionAcceptedEvent Net::smConnectionAccept; @@ -441,7 +445,7 @@ void Net::closeConnectTo(NetSocket sock) return; // if this socket is in the list of polled sockets, remove it - for (int i = 0; i < gPolledSockets.size(); ++i) + for (S32 i = 0; i < gPolledSockets.size(); ++i) { if (gPolledSockets[i]->fd == sock) { @@ -454,7 +458,7 @@ void Net::closeConnectTo(NetSocket sock) closeSocket(sock); } -Net::Error Net::sendtoSocket(NetSocket socket, const U8 *buffer, int bufferSize) +Net::Error Net::sendtoSocket(NetSocket socket, const U8 *buffer, S32 bufferSize) { if(Journal::IsPlaying()) { @@ -480,7 +484,7 @@ bool Net::openPort(S32 port, bool doBind) // we turn off VDP in non-release builds because VDP does not support broadcast packets // which are required for LAN queries (PC->Xbox connectivity). The wire protocol still // uses the VDP packet structure, though. - int protocol = 0; + S32 protocol = 0; bool useVDP = false; #ifdef TORQUE_DISABLE_PC_CONNECTIVITY // Xbox uses a VDP (voice/data protocol) socket for networking @@ -617,7 +621,7 @@ void Net::process() sockaddr_in ipAddr; NetSocket incoming = InvalidSocket; char out_h_addr[1024]; - int out_h_length = 0; + S32 out_h_length = 0; RawData readBuff; for (S32 i = 0; i < gPolledSockets.size(); @@ -727,7 +731,7 @@ void Net::process() if(::connect(currentSock->fd, (struct sockaddr *)&ipAddr, sizeof(ipAddr)) == -1) { - int errorCode; + S32 errorCode; #if defined(TORQUE_USE_WINSOCK) errorCode = WSAGetLastError(); if( errorCode == WSAEINPROGRESS || errorCode == WSAEWOULDBLOCK ) @@ -786,7 +790,7 @@ void Net::process() NetSocket Net::openSocket() { - int retSocket; + S32 retSocket; retSocket = socket(AF_INET, SOCK_STREAM, 0); if(retSocket == InvalidSocket) @@ -831,7 +835,7 @@ NetSocket Net::accept(NetSocket acceptSocket, NetAddress *remoteAddress) sockaddr_in socketAddress; socklen_t addrLen = sizeof(socketAddress); - int retVal = ::accept(acceptSocket, (sockaddr *) &socketAddress, &addrLen); + S32 retVal = ::accept(acceptSocket, (sockaddr *) &socketAddress, &addrLen); if(retVal != InvalidSocket) { IPSocketToNetAddress(&socketAddress, remoteAddress); diff --git a/Engine/source/platform/platformNet.h b/Engine/source/platform/platformNet.h index b37558ebd..16a809927 100644 --- a/Engine/source/platform/platformNet.h +++ b/Engine/source/platform/platformNet.h @@ -31,14 +31,14 @@ #define MAXPACKETSIZE 1500 #endif -typedef int NetConnectionId; +typedef S32 NetConnectionId; /// Generic network address /// /// This is used to represent IP addresses. struct NetAddress { - int type; ///< Type of address (IPAddress currently) + S32 type; ///< Type of address (IPAddress currently) /// Acceptable NetAddress types. enum @@ -93,7 +93,7 @@ struct Net TCPProtocol }; - static const int MaxPacketDataSize = MAXPACKETSIZE; + static const S32 MaxPacketDataSize = MAXPACKETSIZE; static ConnectionNotifyEvent smConnectionNotify; static ConnectionAcceptedEvent smConnectionAccept; diff --git a/Engine/source/platform/platformNetAsync.cpp b/Engine/source/platform/platformNetAsync.cpp index 8f246d39f..701410e38 100644 --- a/Engine/source/platform/platformNetAsync.cpp +++ b/Engine/source/platform/platformNetAsync.cpp @@ -25,7 +25,7 @@ #include "platform/threads/threadPool.h" #include "console/console.h" -#if defined(TORQUE_OS_WIN32) +#if defined(TORQUE_OS_WIN) # include #elif defined(TORQUE_OS_XENON) # include @@ -48,7 +48,7 @@ struct NetAsync::NameLookupRequest NetSocket sock; char remoteAddr[4096]; char out_h_addr[4096]; - int out_h_length; + S32 out_h_length; bool complete; NameLookupRequest() @@ -140,7 +140,7 @@ void NetAsync::queueLookup(const char* remoteAddr, NetSocket socket) { // do we have it already? - unsigned int i = 0; + U32 i = 0; for (i = 0; i < mLookupRequests.size(); ++i) { if (mLookupRequests[i].sock == socket) @@ -160,7 +160,7 @@ void NetAsync::queueLookup(const char* remoteAddr, NetSocket socket) } bool NetAsync::checkLookup(NetSocket socket, char* out_h_addr, - int* out_h_length, int out_h_addr_size) + S32* out_h_length, S32 out_h_addr_size) { bool found = false; diff --git a/Engine/source/platform/platformNetAsync.h b/Engine/source/platform/platformNetAsync.h index ddeff56f3..dc59a1a87 100644 --- a/Engine/source/platform/platformNetAsync.h +++ b/Engine/source/platform/platformNetAsync.h @@ -54,7 +54,7 @@ class NetAsync // out_h_length will be set appropriately. if out_h_length is -1, then // name could not be resolved. otherwise, it provides the number of // address bytes copied into out_h_addr. - bool checkLookup(NetSocket socket, char* out_h_addr, int* out_h_length, int out_h_addr_size); + bool checkLookup(NetSocket socket, char* out_h_addr, int* out_h_length, S32 out_h_addr_size); }; // the global net async object diff --git a/Engine/source/platform/platformVolume.cpp b/Engine/source/platform/platformVolume.cpp index 526e5d0a3..9304ea891 100644 --- a/Engine/source/platform/platformVolume.cpp +++ b/Engine/source/platform/platformVolume.cpp @@ -22,7 +22,7 @@ #include "platform/platform.h" -#if defined(TORQUE_OS_WIN32) || defined(TORQUE_OS_XBOX) || defined(TORQUE_OS_XENON) +#if defined(TORQUE_OS_WIN) || defined(TORQUE_OS_XBOX) || defined(TORQUE_OS_XENON) #include #else #include @@ -84,7 +84,7 @@ bool MountZips(const String &root) bool Touch( const Path &path ) { -#if defined(TORQUE_OS_WIN32) || defined(TORQUE_OS_XBOX) || defined(TORQUE_OS_XENON) +#if defined(TORQUE_OS_WIN) || defined(TORQUE_OS_XBOX) || defined(TORQUE_OS_XENON) return( utime( path.getFullPath(), 0 ) != -1 ); #else return( utimes( path.getFullPath(), NULL) == 0 ); // utimes returns 0 on success. diff --git a/Engine/source/platform/profiler.cpp b/Engine/source/platform/profiler.cpp index f97100f09..8aaf483ef 100644 --- a/Engine/source/platform/profiler.cpp +++ b/Engine/source/platform/profiler.cpp @@ -22,7 +22,7 @@ #include "platform/platform.h" -#if defined(TORQUE_OS_WIN32) +#if defined(TORQUE_OS_WIN) #include // for SetThreadAffinityMask #endif @@ -462,7 +462,7 @@ void Profiler::hashPop(ProfilerRootData *expected) if(!mEnabled && mNextEnable) startHighResolutionTimer(mCurrentProfilerData->mStartTime); -#if defined(TORQUE_OS_WIN32) +#if defined(TORQUE_OS_WIN) // The high performance counters under win32 are unreliable when running on multiple // processors. When the profiler is enabled, we restrict Torque to a single processor. if(mNextEnable != mEnabled) diff --git a/Engine/source/platform/test/testThreading.cpp b/Engine/source/platform/test/testThreading.cpp index ede62a507..6eea80ee3 100644 --- a/Engine/source/platform/test/testThreading.cpp +++ b/Engine/source/platform/test/testThreading.cpp @@ -311,7 +311,7 @@ CreateUnitTest( SemaphoreWaitTest, "Platform/Threads/SemaphoreWaitTest") void *mMutex; U32 mDoneCount; - const static int csmThreadCount = 10; + const static S32 csmThreadCount = 10; void run() { @@ -381,7 +381,7 @@ CreateUnitTest( MutexWaitTest, "Platform/Threads/MutexWaitTest") void *mMutex; U32 mDoneCount; - const static int csmThreadCount = 10; + const static S32 csmThreadCount = 10; void run() { diff --git a/Engine/source/platform/types.codewarrior.h b/Engine/source/platform/types.codewarrior.h index 64912784d..db0d60400 100644 --- a/Engine/source/platform/types.codewarrior.h +++ b/Engine/source/platform/types.codewarrior.h @@ -51,10 +51,16 @@ typedef unsigned long long U64; ///< Compiler independent Unsigned 64-bit in //-------------------------------------- // Identify the Operating System +#if defined(_WIN64) +# define TORQUE_OS_STRING "Win64" +# define TORQUE_OS_WIN +# define TORQUE_OS_WIN64 +# include "platform/types.win.h" #if defined(_WIN32) # define TORQUE_OS_STRING "Win32" +# define TORQUE_OS_WIN # define TORQUE_OS_WIN32 -# include "platform/types.win32.h" +# include "platform/types.win.h" #elif defined(macintosh) || defined(__APPLE__) # define TORQUE_OS_STRING "Mac" diff --git a/Engine/source/platform/types.gcc.h b/Engine/source/platform/types.gcc.h index 406b07ef1..1d49feacc 100644 --- a/Engine/source/platform/types.gcc.h +++ b/Engine/source/platform/types.gcc.h @@ -55,12 +55,18 @@ typedef unsigned long long U64; //-------------------------------------- // Identify the Operating System -#if defined(__WIN32__) || defined(_WIN32) +#if defined(_WIN64) +# define TORQUE_OS_STRING "Win64" +# define TORQUE_OS_WIN +# define TORQUE_OS_WIN64 +# include "platform/types.win.h" +#elif defined(__WIN32__) || defined(_WIN32) # define TORQUE_OS_STRING "Win32" +# define TORQUE_OS_WIN # define TORQUE_OS_WIN32 # define TORQUE_SUPPORTS_NASM # define TORQUE_SUPPORTS_GCC_INLINE_X86_ASM -# include "platform/types.win32.h" +# include "platform/types.win.h" #elif defined(SN_TARGET_PS3) # define TORQUE_OS_STRING "PS3" diff --git a/Engine/source/platform/types.h b/Engine/source/platform/types.h index c53bd87fc..0a7bd63ba 100644 --- a/Engine/source/platform/types.h +++ b/Engine/source/platform/types.h @@ -40,7 +40,7 @@ typedef double F64; ///< Compiler independent 64-bit float struct EmptyType {}; ///< "Null" type used by templates -#define TORQUE_UNUSED(var) (void)var +#define TORQUE_UNUSED(var) (void)sizeof(var) //------------------------------------------------------------------------------ //------------------------------------- String Types @@ -218,13 +218,13 @@ inline S8 getMin(S8 a, S8 b) } /// Returns the lesser of the two parameters: a & b. -inline float getMin(float a, float b) +inline F32 getMin(F32 a, F32 b) { return a>b ? b : a; } /// Returns the lesser of the two parameters: a & b. -inline double getMin(double a, double b) +inline F64 getMin(F64 a, F64 b) { return a>b ? b : a; } @@ -266,13 +266,13 @@ inline S8 getMax(S8 a, S8 b) } /// Returns the greater of the two parameters: a & b. -inline float getMax(float a, float b) +inline F32 getMax(F32 a, F32 b) { return a>b ? a : b; } /// Returns the greater of the two parameters: a & b. -inline double getMax(double a, double b) +inline F64 getMax(F64 a, F64 b) { return a>b ? a : b; } @@ -290,7 +290,7 @@ inline double getMax(double a, double b) #define BIT(x) (1 << (x)) ///< Returns value with bit x set (2^x) -#if defined(TORQUE_OS_WIN32) +#if defined(TORQUE_OS_WIN) #define STDCALL __stdcall #else #define STDCALL diff --git a/Engine/source/platform/types.lint.h b/Engine/source/platform/types.lint.h index fff33d28d..f2268e9a2 100644 --- a/Engine/source/platform/types.lint.h +++ b/Engine/source/platform/types.lint.h @@ -39,7 +39,7 @@ struct FileTime #define TORQUE_LITTLE_ENDIAN #define TORQUE_SUPPORTS_NASM #define TORQUE_SUPPORTS_VC_INLINE_X86_ASM -#define TORQUE_OS_WIN32 +#define TORQUE_OS_WIN #define TORQUE_COMPILER_VISUALC 1500 #ifndef FN_CDECL diff --git a/Engine/source/platform/types.visualc.h b/Engine/source/platform/types.visualc.h index 4379e8a57..2104565bb 100644 --- a/Engine/source/platform/types.visualc.h +++ b/Engine/source/platform/types.visualc.h @@ -58,11 +58,17 @@ typedef unsigned _int64 U64; #elif defined( _XBOX_VER ) # define TORQUE_OS_STRING "Xbox" # define TORQUE_OS_XBOX -# include "platform/types.win32.h" -#elif defined(_WIN32) +# include "platform/types.win.h" +#elif defined( _WIN32 ) # define TORQUE_OS_STRING "Win32" +# define TORQUE_OS_WIN # define TORQUE_OS_WIN32 -# include "platform/types.win32.h" +# include "platform/types.win.h" +#elif defined( _WIN64 ) +# define TORQUE_OS_STRING "Win64" +# define TORQUE_OS_WIN +# define TORQUE_OS_WIN64 +# include "platform/types.win.h" #else # error "VC: Unsupported Operating System" #endif @@ -70,13 +76,17 @@ typedef unsigned _int64 U64; //-------------------------------------- // Identify the CPU -#if defined(_M_IX86) +#if defined( _M_X64 ) +# define TORQUE_CPU_STRING "x64" +# define TORQUE_CPU_X64 +# define TORQUE_LITTLE_ENDIAN +#elif defined( _M_IX86 ) # define TORQUE_CPU_STRING "x86" # define TORQUE_CPU_X86 # define TORQUE_LITTLE_ENDIAN # define TORQUE_SUPPORTS_NASM # define TORQUE_SUPPORTS_VC_INLINE_X86_ASM -#elif defined(TORQUE_OS_XENON) +#elif defined( TORQUE_OS_XENON ) # define TORQUE_CPU_STRING "ppc" # define TORQUE_CPU_PPC # define TORQUE_BIG_ENDIAN diff --git a/Engine/source/platform/types.win32.h b/Engine/source/platform/types.win.h similarity index 94% rename from Engine/source/platform/types.win32.h rename to Engine/source/platform/types.win.h index d95d3cec5..68e0e3a63 100644 --- a/Engine/source/platform/types.win32.h +++ b/Engine/source/platform/types.win.h @@ -29,7 +29,12 @@ // size_t is needed to overload new // size_t tends to be OS and compiler specific and may need to // be if/def'ed in the future -typedef unsigned int dsize_t; + +#ifdef _WIN64 +typedef unsigned long long dsize_t; +#else +typedef unsigned int dsize_t; +#endif // _WIN64 /// Platform dependent file date-time structure. The definition of this structure diff --git a/Engine/source/platform/typesWin32.h b/Engine/source/platform/typesWin32.h index c4b2aa2b2..029b1a341 100644 --- a/Engine/source/platform/typesWin32.h +++ b/Engine/source/platform/typesWin32.h @@ -76,7 +76,12 @@ typedef double F64; ///< Compiler independent 64-bit float // size_t is needed to overload new // size_t tends to be OS and compiler specific and may need to // be if/def'ed in the future + +#ifdef _WIN64 +typedef unsigned long long dsize_t; +#else typedef unsigned int dsize_t; +#endif // _WIN64 typedef const char* StringTableEntry; diff --git a/Engine/source/platformPOSIX/posixVolume.cpp b/Engine/source/platformPOSIX/posixVolume.cpp index 604611543..a5d0871d0 100644 --- a/Engine/source/platformPOSIX/posixVolume.cpp +++ b/Engine/source/platformPOSIX/posixVolume.cpp @@ -251,7 +251,7 @@ Path PosixFile::getName() const return _path; } -FileNode::Status PosixFile::getStatus() const +FileNode::NodeStatus PosixFile::getStatus() const { return _status; } @@ -536,7 +536,7 @@ bool PosixDirectory::getAttributes(Attributes* attr) return true; } -FileNode::Status PosixDirectory::getStatus() const +FileNode::NodeStatus PosixDirectory::getStatus() const { return _status; } diff --git a/Engine/source/platformPOSIX/posixVolume.h b/Engine/source/platformPOSIX/posixVolume.h index 3f6b48cf0..4445ed38e 100644 --- a/Engine/source/platformPOSIX/posixVolume.h +++ b/Engine/source/platformPOSIX/posixVolume.h @@ -68,7 +68,7 @@ class PosixFile: public File Path _path; String _name; FILE* _handle; - Status _status; + NodeStatus _status; PosixFile(const Path& path,String name); bool _updateInfo(); @@ -78,7 +78,7 @@ public: ~PosixFile(); Path getName() const; - Status getStatus() const; + NodeStatus getStatus() const; bool getAttributes(Attributes*); U32 getPosition(); @@ -103,7 +103,7 @@ class PosixDirectory: public Directory Path _path; String _name; DIR* _handle; - Status _status; + NodeStatus _status; PosixDirectory(const Path& path,String name); void _updateStatus(); @@ -112,7 +112,7 @@ public: ~PosixDirectory(); Path getName() const; - Status getStatus() const; + NodeStatus getStatus() const; bool getAttributes(Attributes*); bool open(); diff --git a/Engine/source/platformWin32/minidump/winMiniDump.cpp b/Engine/source/platformWin32/minidump/winMiniDump.cpp index fd1ad9ab2..fbe2b96f6 100644 --- a/Engine/source/platformWin32/minidump/winMiniDump.cpp +++ b/Engine/source/platformWin32/minidump/winMiniDump.cpp @@ -191,9 +191,9 @@ INT CreateMiniDump( LPEXCEPTION_POINTERS ExceptionInfo) //----------------------------------------------------------------------------------------------------------------------------------------- // MiniDumpDialogProc - Used By DisplayMiniDumpDialog //----------------------------------------------------------------------------------------------------------------------------------------- -const int ID_TEXT=200; -const int ID_USERTEXT=300; -const int ID_DONE=400; +const S32 ID_TEXT=200; +const S32 ID_USERTEXT=300; +const S32 ID_DONE=400; BOOL CALLBACK MiniDumpDialogProc(HWND hwndDlg, UINT message, WPARAM wParam, LPARAM lParam) { char text[128]= ""; @@ -259,7 +259,7 @@ LRESULT DisplayMiniDumpDialog(HINSTANCE hinst, HWND hwndOwner) *lpw++ = 0; // Predefined dialog box class (by default) LPWSTR lpwsz = (LPWSTR)lpw; - int nchar = 1 + MultiByteToWideChar(CP_ACP, 0, "MiniDump Crash Report", -1, lpwsz, 50); + S32 nchar = 1 + MultiByteToWideChar(CP_ACP, 0, "MiniDump Crash Report", -1, lpwsz, 50); lpw += nchar; //----------------------------------------------------------------- diff --git a/Engine/source/platformWin32/minidump/winStackWalker.cpp b/Engine/source/platformWin32/minidump/winStackWalker.cpp index a533aa97f..c4b72211d 100644 --- a/Engine/source/platformWin32/minidump/winStackWalker.cpp +++ b/Engine/source/platformWin32/minidump/winStackWalker.cpp @@ -48,7 +48,7 @@ #endif // Entry for each Callstack-Entry -const int STACKWALK_MAX_NAMELEN = 1024; // max name length for symbols +const S32 STACKWALK_MAX_NAMELEN = 1024; // max name length for symbols struct CallstackEntry { DWORD64 offset; // if 0, we have no valid entry @@ -393,7 +393,7 @@ bool StackWalker::ShowCallstack(HANDLE hThread, CONTEXT const & context, PReadPr IMAGEHLP_SYMBOL64 *pSym = NULL; IMAGEHLP_MODULE64 Module; IMAGEHLP_LINE64 Line; - int frameNum; + S32 frameNum; if (!m_modulesLoaded) LoadModules(); @@ -687,7 +687,7 @@ bool StackWalker::GetModuleListTH32(HANDLE hProcess, DWORD pid) return false; keepGoing = !!pM32F( hSnap, &me ); - int cnt = 0; + S32 cnt = 0; while (keepGoing) { this->LoadModule(hProcess, me.szExePath, me.szModule, (DWORD64) me.modBaseAddr, me.modBaseSize); @@ -715,7 +715,7 @@ bool StackWalker::GetModuleListPSAPI(HANDLE hProcess) char *tt = NULL; char *tt2 = NULL; const SIZE_T TTBUFLEN = 8096; - int cnt = 0; + S32 cnt = 0; hMods = (HMODULE*) malloc(sizeof(HMODULE) * (TTBUFLEN / sizeof HMODULE)); tt = (char*) malloc(sizeof(char) * TTBUFLEN); diff --git a/Engine/source/platformWin32/minidump/winStackWalker.h b/Engine/source/platformWin32/minidump/winStackWalker.h index d39219de4..a7341ace1 100644 --- a/Engine/source/platformWin32/minidump/winStackWalker.h +++ b/Engine/source/platformWin32/minidump/winStackWalker.h @@ -76,7 +76,7 @@ private: DWORD m_dwProcessId; bool m_modulesLoaded; LPSTR m_szSymPath; - int m_options; + S32 m_options; char * m_pOutputBuffer; static BOOL __stdcall myReadProcMem(HANDLE hProcess, DWORD64 qwBaseAddress, PVOID lpBuffer, DWORD nSize, LPDWORD lpNumberOfBytesRead); diff --git a/Engine/source/platformWin32/threads/thread.cpp b/Engine/source/platformWin32/threads/thread.cpp index 6e66ddc6d..d1ba59cc2 100644 --- a/Engine/source/platformWin32/threads/thread.cpp +++ b/Engine/source/platformWin32/threads/thread.cpp @@ -68,7 +68,7 @@ public: // Neccesary because Thread::run() is provided as a non-threaded // way to execute the thread's run function. So we have to keep // track of the thread's lock here. -static unsigned int __stdcall ThreadRunHandler(void * arg) +static U32 __stdcall ThreadRunHandler(void * arg) { PlatformThreadData* mData = reinterpret_cast(arg); mData->mThreadID = GetCurrentThreadId(); @@ -164,7 +164,7 @@ U32 Thread::getId() void Thread::_setName( const char* name ) { -#if defined( TORQUE_DEBUG ) && defined( TORQUE_COMPILER_VISUALC ) && defined( TORQUE_OS_WIN32 ) +#if defined( TORQUE_DEBUG ) && defined( TORQUE_COMPILER_VISUALC ) && defined( TORQUE_OS_WIN ) // See http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx diff --git a/Engine/source/platformWin32/winConsole.cpp b/Engine/source/platformWin32/winConsole.cpp index 339c41b2b..25f172abb 100644 --- a/Engine/source/platformWin32/winConsole.cpp +++ b/Engine/source/platformWin32/winConsole.cpp @@ -130,7 +130,7 @@ WinConsole::~WinConsole() void WinConsole::printf(const char *s, ...) { // Get the line into a buffer. - static const int BufSize = 4096; + static const S32 BufSize = 4096; static char buffer[4096]; DWORD bytes; va_list args; diff --git a/Engine/source/platformWin32/winDInputDevice.cpp b/Engine/source/platformWin32/winDInputDevice.cpp index 759a34643..8d036352f 100644 --- a/Engine/source/platformWin32/winDInputDevice.cpp +++ b/Engine/source/platformWin32/winDInputDevice.cpp @@ -896,8 +896,8 @@ bool DInputDevice::buildEvent( DWORD offset, S32 newData, S32 oldData ) // Scale to the range -1.0 to 1.0: if ( objInfo.mMin != DIPROPRANGE_NOMIN && objInfo.mMax != DIPROPRANGE_NOMAX ) { - float range = float( objInfo.mMax - objInfo.mMin ); - newEvent.fValue = float( ( 2 * newData ) - objInfo.mMax - objInfo.mMin ) / range; + F32 range = F32( objInfo.mMax - objInfo.mMin ); + newEvent.fValue = F32( ( 2 * newData ) - objInfo.mMax - objInfo.mMin ) / range; } else newEvent.fValue = (F32)newData; @@ -1041,7 +1041,7 @@ bool DInputDevice::buildEvent( DWORD offset, S32 newData, S32 oldData ) return true; } -void DInputDevice::rumble(float x, float y) +void DInputDevice::rumble(F32 x, F32 y) { LONG rglDirection[2] = { 0, 0 }; DICONSTANTFORCE cf = { 0 }; diff --git a/Engine/source/platformWin32/winDInputDevice.h b/Engine/source/platformWin32/winDInputDevice.h index e8cd13e66..b242df789 100644 --- a/Engine/source/platformWin32/winDInputDevice.h +++ b/Engine/source/platformWin32/winDInputDevice.h @@ -117,7 +117,7 @@ class DInputDevice : public InputDevice const char* getProductName(); // Constant Effect Force Feedback - void rumble( float x, float y ); + void rumble( F32 x, F32 y ); // Console interface functions: const char* getJoystickAxesString(); diff --git a/Engine/source/platformWin32/winDirectInput.cpp b/Engine/source/platformWin32/winDirectInput.cpp index 86bb52bd2..fa02285b0 100644 --- a/Engine/source/platformWin32/winDirectInput.cpp +++ b/Engine/source/platformWin32/winDirectInput.cpp @@ -437,14 +437,14 @@ bool DInputManager::isXInputEnabled() } //------------------------------------------------------------------------------ -bool DInputManager::isXInputConnected(int controllerID) +bool DInputManager::isXInputConnected(S32 controllerID) { return( mXInputStateNew[controllerID].bConnected ); } -int DInputManager::getXInputState(int controllerID, int property, bool current) +int DInputManager::getXInputState(S32 controllerID, S32 property, bool current) { - int retVal; + S32 retVal; switch(property) { @@ -511,7 +511,7 @@ void DInputManager::deactivateXInput() } //------------------------------------------------------------------------------ -bool DInputManager::rumble( const char *pDeviceName, float x, float y ) +bool DInputManager::rumble( const char *pDeviceName, F32 x, F32 y ) { // Determine the device U32 deviceType; @@ -566,7 +566,7 @@ bool DInputManager::rumble( const char *pDeviceName, float x, float y ) } } -void DInputManager::buildXInputEvent( U32 deviceInst, InputEventType objType, InputObjectInstances objInst, InputActionType action, float fValue ) +void DInputManager::buildXInputEvent( U32 deviceInst, InputEventType objType, InputObjectInstances objInst, InputActionType action, F32 fValue ) { InputEventInfo newEvent; @@ -586,7 +586,7 @@ void DInputManager::buildXInputEvent( U32 deviceInst, InputEventType objType, In // "mXInputStateReset" is the exception and is true whenever DirectInput gets reset (because // the user ALT-TABBED away, for example). That means that after every context switch, // you will get a full set of updates on the "true" state of the controller. -inline void DInputManager::fireXInputConnectEvent( int controllerID, bool condition, bool connected ) +inline void DInputManager::fireXInputConnectEvent( S32 controllerID, bool condition, bool connected ) { if ( mXInputStateReset || condition ) { @@ -597,7 +597,7 @@ inline void DInputManager::fireXInputConnectEvent( int controllerID, bool condit } } -inline void DInputManager::fireXInputMoveEvent( int controllerID, bool condition, InputObjectInstances objInst, float fValue ) +inline void DInputManager::fireXInputMoveEvent( S32 controllerID, bool condition, InputObjectInstances objInst, F32 fValue ) { if ( mXInputStateReset || condition ) { @@ -620,7 +620,7 @@ inline void DInputManager::fireXInputMoveEvent( int controllerID, bool condition } } -inline void DInputManager::fireXInputButtonEvent( int controllerID, bool forceFire, int button, InputObjectInstances objInst ) +inline void DInputManager::fireXInputButtonEvent( S32 controllerID, bool forceFire, S32 button, InputObjectInstances objInst ) { if ( mXInputStateReset || forceFire || ((mXInputStateNew[controllerID].state.Gamepad.wButtons & button) != (mXInputStateOld[controllerID].state.Gamepad.wButtons & button)) ) { @@ -663,7 +663,7 @@ void DInputManager::processXInput( void ) if ( mfnXInputGetState ) { - for ( int i=0; i<4; i++ ) + for ( S32 i=0; i<4; i++ ) { // Calling XInputGetState on a disconnected controller takes a fair // amount of time (probably because it tries to locate it), so we @@ -855,7 +855,7 @@ ConsoleFunction( isXInputConnected, bool, 2, 2, "( int controllerID )" } //------------------------------------------------------------------------------ -ConsoleFunction( getXInputState, int, 3, 4, "( int controllerID, string property, bool current )" +ConsoleFunction( getXInputState, S32, 3, 4, "( int controllerID, string property, bool current )" "@brief Queries the current state of a connected Xbox 360 controller.\n\n" "XInput Properties:\n\n" " - XI_THUMBLX, XI_THUMBLY - X and Y axes of the left thumbstick. \n" diff --git a/Engine/source/platformWin32/winDirectInput.h b/Engine/source/platformWin32/winDirectInput.h index 378cbec03..d7ebd1b70 100644 --- a/Engine/source/platformWin32/winDirectInput.h +++ b/Engine/source/platformWin32/winDirectInput.h @@ -85,10 +85,10 @@ class DInputManager : public InputManager void unacquire( U8 deviceType, U8 deviceID ); // XInput worker functions - void buildXInputEvent( U32 deviceInst, InputEventType objType, InputObjectInstances objInst, InputActionType action, float fValue ); - void fireXInputConnectEvent( int controllerID, bool condition, bool connected ); - void fireXInputMoveEvent( int controllerID, bool condition, InputObjectInstances objInst, float fValue ); - void fireXInputButtonEvent( int controllerID, bool forceFire, int button, InputObjectInstances objInst ); + void buildXInputEvent( U32 deviceInst, InputEventType objType, InputObjectInstances objInst, InputActionType action, F32 fValue ); + void fireXInputConnectEvent( S32 controllerID, bool condition, bool connected ); + void fireXInputMoveEvent( S32 controllerID, bool condition, InputObjectInstances objInst, F32 fValue ); + void fireXInputButtonEvent( S32 controllerID, bool forceFire, S32 button, InputObjectInstances objInst ); void processXInput(); public: @@ -120,13 +120,13 @@ class DInputManager : public InputManager void deactivateXInput(); bool isXInputActive() { return( mXInputActive ); } void resetXInput() { mXInputStateReset = true; } - bool isXInputConnected(int controllerID); - int getXInputState(int controllerID, int property, bool current); + bool isXInputConnected(S32 controllerID); + S32 getXInputState(S32 controllerID, S32 property, bool current); // Console interface: const char* getJoystickAxesString( U32 deviceID ); - bool rumble( const char *pDeviceName, float x, float y ); + bool rumble( const char *pDeviceName, F32 x, F32 y ); }; #endif // _H_WINDIRECTINPUT_ diff --git a/Engine/source/platformWin32/winFileio.cpp b/Engine/source/platformWin32/winFileio.cpp index 0d9c7c132..7296ed32e 100644 --- a/Engine/source/platformWin32/winFileio.cpp +++ b/Engine/source/platformWin32/winFileio.cpp @@ -248,7 +248,7 @@ File::~File() // Sets capability appropriate to the openMode. // Returns the currentStatus of the file. //----------------------------------------------------------------------------- -File::Status File::open(const char *filename, const AccessMode openMode) +File::FileStatus File::open(const char *filename, const AccessMode openMode) { AssertFatal(NULL != filename, "File::open: NULL fname"); AssertWarn(INVALID_HANDLE_VALUE == (HANDLE)handle, "File::open: handle already valid"); @@ -363,7 +363,7 @@ U32 File::getPosition() const // // Returns the currentStatus of the file. //----------------------------------------------------------------------------- -File::Status File::setPosition(S32 position, bool absolutePos) +File::FileStatus File::setPosition(S32 position, bool absolutePos) { AssertFatal(Closed != currentStatus, "File::setPosition: file closed"); AssertFatal(INVALID_HANDLE_VALUE != (HANDLE)handle, "File::setPosition: invalid file handle"); @@ -425,7 +425,7 @@ U32 File::getSize() const // It is an error to flush a read-only file. // Returns the currentStatus of the file. //----------------------------------------------------------------------------- -File::Status File::flush() +File::FileStatus File::flush() { AssertFatal(Closed != currentStatus, "File::flush: file closed"); AssertFatal(INVALID_HANDLE_VALUE != (HANDLE)handle, "File::flush: invalid file handle"); @@ -442,7 +442,7 @@ File::Status File::flush() // // Returns the currentStatus //----------------------------------------------------------------------------- -File::Status File::close() +File::FileStatus File::close() { // check if it's already closed... if (Closed == currentStatus) @@ -461,7 +461,7 @@ File::Status File::close() //----------------------------------------------------------------------------- // Self-explanatory. //----------------------------------------------------------------------------- -File::Status File::getStatus() const +File::FileStatus File::getStatus() const { return currentStatus; } @@ -469,7 +469,7 @@ File::Status File::getStatus() const //----------------------------------------------------------------------------- // Sets and returns the currentStatus when an error has been encountered. //----------------------------------------------------------------------------- -File::Status File::setStatus() +File::FileStatus File::setStatus() { switch (GetLastError()) { @@ -489,7 +489,7 @@ File::Status File::setStatus() //----------------------------------------------------------------------------- // Sets and returns the currentStatus to status. //----------------------------------------------------------------------------- -File::Status File::setStatus(File::Status status) +File::FileStatus File::setStatus(File::FileStatus status) { return currentStatus = status; } @@ -500,7 +500,7 @@ File::Status File::setStatus(File::Status status) // The number of bytes read is available in bytesRead if a non-Null pointer is // provided. //----------------------------------------------------------------------------- -File::Status File::read(U32 size, char *dst, U32 *bytesRead) +File::FileStatus File::read(U32 size, char *dst, U32 *bytesRead) { AssertFatal(Closed != currentStatus, "File::read: file closed"); AssertFatal(INVALID_HANDLE_VALUE != (HANDLE)handle, "File::read: invalid file handle"); @@ -531,7 +531,7 @@ File::Status File::read(U32 size, char *dst, U32 *bytesRead) // The number of bytes written is available in bytesWritten if a non-Null // pointer is provided. //----------------------------------------------------------------------------- -File::Status File::write(U32 size, const char *src, U32 *bytesWritten) +File::FileStatus File::write(U32 size, const char *src, U32 *bytesWritten) { AssertFatal(Closed != currentStatus, "File::write: file closed"); AssertFatal(INVALID_HANDLE_VALUE != (HANDLE)handle, "File::write: invalid file handle"); @@ -1140,7 +1140,7 @@ void Platform::getVolumeNamesList( Vector& out_rNameVector, bool bO out_rNameVector.clear(); - for(int i = 0; i < 32; i++ ) + for(S32 i = 0; i < 32; i++ ) { dMemset(driveLetter,0,12); if( dwDrives & dwMask ) diff --git a/Engine/source/platformWin32/winInput.cpp b/Engine/source/platformWin32/winInput.cpp index e4fcdba57..6d5f87248 100644 --- a/Engine/source/platformWin32/winInput.cpp +++ b/Engine/source/platformWin32/winInput.cpp @@ -33,6 +33,8 @@ #include #endif +#include + // Static class variables: InputManager* Input::smManager; bool Input::smActive; @@ -79,6 +81,10 @@ void Input::init() destroy(); +#ifdef TORQUE_DEFAULT_KEYBOARD_LAYOUT + attemptSwitchToKeyboardLayout( TORQUE_DEFAULT_KEYBOARD_LAYOUT ); +#endif + #ifdef LOG_INPUT struct tm* newTime; time_t aclock; @@ -487,6 +493,18 @@ InputManager* Input::getManager() return( smManager ); } +//------------------------------------------------------------------------------ +void Input::attemptSwitchToKeyboardLayout( U32 layout ) +{ + const LANGID lang = MAKELANGID( layout, SUBLANG_DEFAULT ); + std::wstringstream ss; + ss << std::hex << lang; + const wchar_t* hexLang = ss.str().c_str(); + ActivateKeyboardLayout( LoadKeyboardLayout( + hexLang, KLF_ACTIVATE | KLF_REPLACELANG + ), KLF_REORDER ); +} + #ifdef LOG_INPUT //------------------------------------------------------------------------------ void Input::log( const char* format, ... ) diff --git a/Engine/source/platformWin32/winMemory.cpp b/Engine/source/platformWin32/winMemory.cpp index c4cb821bc..8cb593f48 100644 --- a/Engine/source/platformWin32/winMemory.cpp +++ b/Engine/source/platformWin32/winMemory.cpp @@ -63,7 +63,7 @@ void dRealFree(void* p) free(p); } -void *dMalloc_aligned(dsize_t in_size, int alignment) +void *dMalloc_aligned(dsize_t in_size, S32 alignment) { return _mm_malloc(in_size, alignment); } diff --git a/Engine/source/platformWin32/winTime.cpp b/Engine/source/platformWin32/winTime.cpp index e4174eb83..4c27f5ffd 100644 --- a/Engine/source/platformWin32/winTime.cpp +++ b/Engine/source/platformWin32/winTime.cpp @@ -66,7 +66,7 @@ String Platform::localTimeToString( const LocalTime < ) TCHAR buffer[1024] = {0}; - int result = 0; + S32 result = 0; String outStr; diff --git a/Engine/source/platformWin32/winVolume.cpp b/Engine/source/platformWin32/winVolume.cpp index 1df04e3ca..04422d9eb 100644 --- a/Engine/source/platformWin32/winVolume.cpp +++ b/Engine/source/platformWin32/winVolume.cpp @@ -333,7 +333,7 @@ Path Win32File::getName() const return mPath; } -FileNode::Status Win32File::getStatus() const +FileNode::NodeStatus Win32File::getStatus() const { return mStatus; } @@ -620,7 +620,7 @@ bool Win32Directory::getAttributes(Attributes* attr) return true; } -FileNode::Status Win32Directory::getStatus() const +FileNode::NodeStatus Win32Directory::getStatus() const { return mStatus; } diff --git a/Engine/source/platformWin32/winVolume.h b/Engine/source/platformWin32/winVolume.h index b41b6938c..b4211898d 100644 --- a/Engine/source/platformWin32/winVolume.h +++ b/Engine/source/platformWin32/winVolume.h @@ -65,7 +65,7 @@ public: ~Win32File(); Path getName() const; - Status getStatus() const; + NodeStatus getStatus() const; bool getAttributes(Attributes*); U64 getSize(); @@ -86,7 +86,7 @@ private: Path mPath; String mName; void *mHandle; - Status mStatus; + NodeStatus mStatus; Win32File(const Path &path, String name); @@ -103,7 +103,7 @@ public: ~Win32Directory(); Path getName() const; - Status getStatus() const; + NodeStatus getStatus() const; bool getAttributes(Attributes*); bool open(); @@ -118,7 +118,7 @@ private: Path mPath; String mName; void *mHandle; - Status mStatus; + NodeStatus mStatus; Win32Directory(const Path &path,String name); diff --git a/Engine/source/platformWin32/winWindow.cpp b/Engine/source/platformWin32/winWindow.cpp index 53b3a2b48..5c2bac019 100644 --- a/Engine/source/platformWin32/winWindow.cpp +++ b/Engine/source/platformWin32/winWindow.cpp @@ -350,7 +350,7 @@ S32 PASCAL WinMain( HINSTANCE hInstance, HINSTANCE, LPSTR lpszCmdLine, S32) // Add the word to the argument list. if (*word) { - int len = ptr - word; + S32 len = ptr - word; char *arg = (char *) dMalloc(len + 1); dStrncpy(arg, word, len); arg[len] = 0; @@ -373,12 +373,12 @@ S32 PASCAL WinMain( HINSTANCE hInstance, HINSTANCE, LPSTR lpszCmdLine, S32) extern "C" { - bool torque_engineinit(int argc, const char **argv); - int torque_enginetick(); + bool torque_engineinit(S32 argc, const char **argv); + S32 torque_enginetick(); bool torque_engineshutdown(); }; -int TorqueMain(int argc, const char **argv) +S32 TorqueMain(int argc, const char **argv) { if (!torque_engineinit(argc, argv)) return 1; @@ -442,7 +442,7 @@ S32 torque_winmain( HINSTANCE hInstance, HINSTANCE, LPSTR lpszCmdLine, S32) // Add the word to the argument list. if (*word) { - int len = ptr - word; + S32 len = ptr - word; char *arg = (char *) dMalloc(len + 1); dStrncpy(arg, word, len); arg[len] = 0; @@ -499,7 +499,7 @@ bool Platform::openWebBrowser( const char* webAddress ) return( false ); } - if ( RegQueryValueEx( regKey, dT(""), NULL, NULL, (unsigned char *)sWebKey, &size ) != ERROR_SUCCESS ) + if ( RegQueryValueEx( regKey, dT(""), NULL, NULL, (U8 *)sWebKey, &size ) != ERROR_SUCCESS ) { Con::errorf( ConsoleLogEntry::General, "Platform::openWebBrowser - Failed to query the open command registry key!!!" ); return( false ); diff --git a/Engine/source/platformX86UNIX/x86UNIXConsole.cpp b/Engine/source/platformX86UNIX/x86UNIXConsole.cpp index 859b420fa..50a319562 100644 --- a/Engine/source/platformX86UNIX/x86UNIXConsole.cpp +++ b/Engine/source/platformX86UNIX/x86UNIXConsole.cpp @@ -217,7 +217,7 @@ void StdConsole::process() // mojo for select call fd_set rfds; struct timeval tv; - int retval; + FD_ZERO(&rfds); FD_SET(stdIn, &rfds); // don't wait at all in select diff --git a/Engine/source/platformX86UNIX/x86UNIXFileio.cpp b/Engine/source/platformX86UNIX/x86UNIXFileio.cpp index 680faf822..22c40a187 100644 --- a/Engine/source/platformX86UNIX/x86UNIXFileio.cpp +++ b/Engine/source/platformX86UNIX/x86UNIXFileio.cpp @@ -469,7 +469,7 @@ bool dPathCopy(const char *fromName, const char *toName, bool nooverwrite) // Sets capability appropriate to the openMode. // Returns the currentStatus of the file. //----------------------------------------------------------------------------- - File::Status File::open(const char *filename, const AccessMode openMode) + File::FileStatus File::open(const char *filename, const AccessMode openMode) { AssertFatal(NULL != filename, "File::open: NULL filename"); AssertWarn(NULL == handle, "File::open: handle already valid"); @@ -584,7 +584,7 @@ bool dPathCopy(const char *fromName, const char *toName, bool nooverwrite) // // Returns the currentStatus of the file. //----------------------------------------------------------------------------- - File::Status File::setPosition(S32 position, bool absolutePos) + File::FileStatus File::setPosition(S32 position, bool absolutePos) { AssertFatal(Closed != currentStatus, "File::setPosition: file closed"); AssertFatal(NULL != handle, "File::setPosition: invalid file handle"); @@ -645,7 +645,7 @@ bool dPathCopy(const char *fromName, const char *toName, bool nooverwrite) // It is an error to flush a read-only file. // Returns the currentStatus of the file. //----------------------------------------------------------------------------- - File::Status File::flush() + File::FileStatus File::flush() { AssertFatal(Closed != currentStatus, "File::flush: file closed"); AssertFatal(NULL != handle, "File::flush: invalid file handle"); @@ -662,7 +662,7 @@ bool dPathCopy(const char *fromName, const char *toName, bool nooverwrite) // // Returns the currentStatus //----------------------------------------------------------------------------- - File::Status File::close() + File::FileStatus File::close() { // if the handle is non-NULL, close it if necessary and free it if (NULL != handle) @@ -684,7 +684,7 @@ bool dPathCopy(const char *fromName, const char *toName, bool nooverwrite) //----------------------------------------------------------------------------- // Self-explanatory. //----------------------------------------------------------------------------- - File::Status File::getStatus() const + File::FileStatus File::getStatus() const { return currentStatus; } @@ -692,7 +692,7 @@ bool dPathCopy(const char *fromName, const char *toName, bool nooverwrite) //----------------------------------------------------------------------------- // Sets and returns the currentStatus when an error has been encountered. //----------------------------------------------------------------------------- - File::Status File::setStatus() + File::FileStatus File::setStatus() { Con::printf("File IO error: %s", strerror(errno)); return currentStatus = IOError; @@ -701,7 +701,7 @@ bool dPathCopy(const char *fromName, const char *toName, bool nooverwrite) //----------------------------------------------------------------------------- // Sets and returns the currentStatus to status. //----------------------------------------------------------------------------- - File::Status File::setStatus(File::Status status) + File::FileStatus File::setStatus(File::FileStatus status) { return currentStatus = status; } @@ -712,7 +712,7 @@ bool dPathCopy(const char *fromName, const char *toName, bool nooverwrite) // The number of bytes read is available in bytesRead if a non-Null pointer is // provided. //----------------------------------------------------------------------------- - File::Status File::read(U32 size, char *dst, U32 *bytesRead) + File::FileStatus File::read(U32 size, char *dst, U32 *bytesRead) { #ifdef DEBUG // fprintf(stdout,"reading %d bytes\n",size);fflush(stdout); @@ -770,7 +770,7 @@ bool dPathCopy(const char *fromName, const char *toName, bool nooverwrite) // The number of bytes written is available in bytesWritten if a non-Null // pointer is provided. //----------------------------------------------------------------------------- - File::Status File::write(U32 size, const char *src, U32 *bytesWritten) + File::FileStatus File::write(U32 size, const char *src, U32 *bytesWritten) { // JMQ: despite the U32 parameters, the maximum filesize supported by this // function is probably the max value of S32, due to the unix syscall diff --git a/Engine/source/postFx/postEffect.cpp b/Engine/source/postFx/postEffect.cpp index aff1e6f2c..0638a5fe4 100644 --- a/Engine/source/postFx/postEffect.cpp +++ b/Engine/source/postFx/postEffect.cpp @@ -134,7 +134,7 @@ GFX_ImplementTextureProfile( PostFxTargetProfile, GFXTextureProfile::PreserveSize | GFXTextureProfile::RenderTarget | GFXTextureProfile::Pooled, - GFXTextureProfile::None ); + GFXTextureProfile::NONE ); IMPLEMENT_CONOBJECT(PostEffect); @@ -142,7 +142,7 @@ IMPLEMENT_CONOBJECT(PostEffect); GFX_ImplementTextureProfile( PostFxTextureProfile, GFXTextureProfile::DiffuseMap, GFXTextureProfile::Static | GFXTextureProfile::PreserveSize | GFXTextureProfile::NoMipmap, - GFXTextureProfile::None ); + GFXTextureProfile::NONE ); void PostEffect::EffectConst::set( const String &newVal ) @@ -374,7 +374,7 @@ bool PostEffect::onAdd() scriptPath.setExtension( String::EmptyString ); // Find additional textures - for( int i = 0; i < NumTextures; i++ ) + for( S32 i = 0; i < NumTextures; i++ ) { String texFilename = mTexFilename[i]; diff --git a/Engine/source/renderInstance/renderFormatChanger.cpp b/Engine/source/renderInstance/renderFormatChanger.cpp index bba53ed53..c9042c766 100644 --- a/Engine/source/renderInstance/renderFormatChanger.cpp +++ b/Engine/source/renderInstance/renderFormatChanger.cpp @@ -243,7 +243,7 @@ void RenderFormatToken::_teardownTargets() { mTarget.release(); - for(int i = 0; i < TargetChainLength; i++) + for(S32 i = 0; i < TargetChainLength; i++) { mTargetColorTexture[i] = NULL; mTargetDepthStencilTexture[i] = NULL; diff --git a/Engine/source/renderInstance/renderGlowMgr.cpp b/Engine/source/renderInstance/renderGlowMgr.cpp index 86bbadcbc..e3801e85e 100644 --- a/Engine/source/renderInstance/renderGlowMgr.cpp +++ b/Engine/source/renderInstance/renderGlowMgr.cpp @@ -54,6 +54,7 @@ RenderGlowMgr::GlowMaterialHook::GlowMaterialHook( BaseMatInstance *matInst ) { mGlowMatInst = (MatInstance*)matInst->getMaterial()->createMatInstance(); mGlowMatInst->getFeaturesDelegate().bind( &GlowMaterialHook::_overrideFeatures ); + mGlowMatInst->setUserObject(matInst->getUserObject()); mGlowMatInst->init( matInst->getRequestedFeatures(), matInst->getVertexFormat() ); } diff --git a/Engine/source/renderInstance/renderOcclusionMgr.cpp b/Engine/source/renderInstance/renderOcclusionMgr.cpp index 4e9839eb5..126d375a8 100644 --- a/Engine/source/renderInstance/renderOcclusionMgr.cpp +++ b/Engine/source/renderInstance/renderOcclusionMgr.cpp @@ -106,7 +106,7 @@ void RenderOcclusionMgr::init() U32 vertexIndex = 0; U32 idx; - for(int i = 0; i < 6; i++) + for(S32 i = 0; i < 6; i++) { idx = cubeFaces[i][0]; verts[vertexIndex].point = cubePoints[idx]; diff --git a/Engine/source/renderInstance/renderParticleMgr.cpp b/Engine/source/renderInstance/renderParticleMgr.cpp index 76c3ec2ff..d1d36f39e 100644 --- a/Engine/source/renderInstance/renderParticleMgr.cpp +++ b/Engine/source/renderInstance/renderParticleMgr.cpp @@ -157,7 +157,7 @@ void RenderParticleMgr::addElement( RenderInst *inst ) pri->bbModelViewProj->mul(tempPt); tempPt = tempPt / tempPt.w; - for(int i = 0; i < 1; i++) + for(S32 i = 0; i < 1; i++) { screenClipper.mPlaneList.push_back(planes[i]); screenClipper.mPlaneList.last() += tempPt.asPoint3F(); @@ -167,7 +167,7 @@ void RenderParticleMgr::addElement( RenderInst *inst ) screenSpaceBoundingBox.minExtents = Point3F::Zero; screenSpaceBoundingBox.maxExtents = Point3F::Zero; - for(int i = 0; i < 8; i++) + for(S32 i = 0; i < 8; i++) { tempPt = cubePoints[i]; pri->bbModelViewProj->mul(tempPt); diff --git a/Engine/source/renderInstance/renderPassManager.h b/Engine/source/renderInstance/renderPassManager.h index 5547b723c..1f07a8ac7 100644 --- a/Engine/source/renderInstance/renderPassManager.h +++ b/Engine/source/renderInstance/renderPassManager.h @@ -65,12 +65,17 @@ protected: public: - RenderInstType( const RenderInstType &type = Invalid ) + RenderInstType() + : mName( Invalid.mName ) + { + } + + RenderInstType( const RenderInstType &type ) : mName( type.mName ) { } - RenderInstType( const String &name ) + RenderInstType( const String &name ) : mName( name ) { } diff --git a/Engine/source/scene/reflectionManager.cpp b/Engine/source/scene/reflectionManager.cpp index c6b78ad65..2c86a700f 100644 --- a/Engine/source/scene/reflectionManager.cpp +++ b/Engine/source/scene/reflectionManager.cpp @@ -59,14 +59,14 @@ MODULE_END; GFX_ImplementTextureProfile( ReflectRenderTargetProfile, GFXTextureProfile::DiffuseMap, GFXTextureProfile::PreserveSize | GFXTextureProfile::NoMipmap | GFXTextureProfile::RenderTarget | GFXTextureProfile::Pooled, - GFXTextureProfile::None ); + GFXTextureProfile::NONE ); GFX_ImplementTextureProfile( RefractTextureProfile, GFXTextureProfile::DiffuseMap, GFXTextureProfile::PreserveSize | GFXTextureProfile::RenderTarget | GFXTextureProfile::Pooled, - GFXTextureProfile::None ); + GFXTextureProfile::NONE ); static S32 QSORT_CALLBACK compareReflectors( const void *a, const void *b ) { @@ -189,11 +189,8 @@ void ReflectionManager::update( F32 timeSlice, break; } - U32 totalElapsed = mTimer->getElapsedMs(); - // Set metric/debug related script variables... - U32 numEnabled = mReflectors.size(); U32 numVisible = 0; U32 numOccluded = 0; @@ -208,6 +205,8 @@ void ReflectionManager::update( F32 timeSlice, } #ifdef TORQUE_GATHER_METRICS + U32 numEnabled = mReflectors.size(); + U32 totalElapsed = mTimer->getElapsedMs(); const GFXTextureProfileStats &stats = ReflectRenderTargetProfile.getStats(); F32 mb = ( stats.activeBytes / 1024.0f ) / 1024.0f; diff --git a/Engine/source/scene/reflector.cpp b/Engine/source/scene/reflector.cpp index 2b96737e6..f224a913a 100644 --- a/Engine/source/scene/reflector.cpp +++ b/Engine/source/scene/reflector.cpp @@ -760,7 +760,7 @@ MatrixF PlaneReflector::getCameraReflection( const MatrixF &camTrans ) return newTrans; } -inline float sgn(float a) +inline F32 sgn(F32 a) { if (a > 0.0F) return (1.0F); if (a < 0.0F) return (-1.0F); diff --git a/Engine/source/scene/sceneContainer.cpp b/Engine/source/scene/sceneContainer.cpp index e99f5be11..7270eaa1b 100644 --- a/Engine/source/scene/sceneContainer.cpp +++ b/Engine/source/scene/sceneContainer.cpp @@ -1197,7 +1197,7 @@ void SceneContainer::cleanupSearchVectors() //----------------------------------------------------------------------------- static Point3F sgSortReferencePoint; -static int QSORT_CALLBACK cmpSearchPointers(const void* inP1, const void* inP2) +static S32 QSORT_CALLBACK cmpSearchPointers(const void* inP1, const void* inP2) { SimObjectPtr** p1 = (SimObjectPtr**)inP1; SimObjectPtr** p2 = (SimObjectPtr**)inP2; diff --git a/Engine/source/scene/sceneManager.cpp b/Engine/source/scene/sceneManager.cpp index 3fcd37422..fa6721ac7 100644 --- a/Engine/source/scene/sceneManager.cpp +++ b/Engine/source/scene/sceneManager.cpp @@ -156,9 +156,7 @@ void SceneManager::renderScene( ScenePassType passType, U32 objectMask ) { // Store the camera state so if we lock, this will become the // locked state. - - if( passType == SPT_Diffuse ) - smLockedDiffuseCamera = cameraState; + smLockedDiffuseCamera = cameraState; } // Create the render state. diff --git a/Engine/source/scene/zones/sceneZoneSpaceManager.h b/Engine/source/scene/zones/sceneZoneSpaceManager.h index 51b696326..1c7631949 100644 --- a/Engine/source/scene/zones/sceneZoneSpaceManager.h +++ b/Engine/source/scene/zones/sceneZoneSpaceManager.h @@ -79,7 +79,7 @@ class SceneZoneSpaceManager { public: - ZoneContentIterator( SceneZoneSpaceManager* manager, int zoneId, bool upToDate = true ) + ZoneContentIterator( SceneZoneSpaceManager* manager, S32 zoneId, bool upToDate = true ) { AssertFatal( zoneId < manager->getNumZones(), "SceneZoneSpaceManager::ZoneContentIterator - Zone ID out of range" ); diff --git a/Engine/source/sfx/fmod/sfxFMODDevice.h b/Engine/source/sfx/fmod/sfxFMODDevice.h index df90eae0d..f710faa20 100644 --- a/Engine/source/sfx/fmod/sfxFMODDevice.h +++ b/Engine/source/sfx/fmod/sfxFMODDevice.h @@ -59,7 +59,7 @@ // This doesn't appear to exist in some contexts, so let's just add it. -#if defined(TORQUE_OS_WIN32) || defined(TORQUE_OS_XENON) +#if defined(TORQUE_OS_WIN) || defined(TORQUE_OS_XENON) #ifndef WINAPI #define WINAPI __stdcall #endif diff --git a/Engine/source/sfx/fmod/sfxFMODProvider.cpp b/Engine/source/sfx/fmod/sfxFMODProvider.cpp index f11996c97..a55609a89 100644 --- a/Engine/source/sfx/fmod/sfxFMODProvider.cpp +++ b/Engine/source/sfx/fmod/sfxFMODProvider.cpp @@ -169,7 +169,7 @@ void SFXFMODProvider::init() const char* pDllName; // plugin-based DLL const char* eventDllName; -#ifdef TORQUE_OS_WIN32 +#ifdef TORQUE_OS_WIN dllName = "fmodex.dll"; pDllName = "fmodexp.dll"; eventDllName = "fmod_event.dll"; diff --git a/Engine/source/sfx/media/sfxVorbisStream.cpp b/Engine/source/sfx/media/sfxVorbisStream.cpp index 7ed1c51ec..789f136e2 100644 --- a/Engine/source/sfx/media/sfxVorbisStream.cpp +++ b/Engine/source/sfx/media/sfxVorbisStream.cpp @@ -91,7 +91,7 @@ size_t SFXVorbisStream::_read_func( void *ptr, size_t size, size_t nmemb, void * return readItems; } -int SFXVorbisStream::_seek_func( void *datasource, ogg_int64_t offset, int whence ) +S32 SFXVorbisStream::_seek_func( void *datasource, ogg_int64_t offset, S32 whence ) { Stream *stream = reinterpret_cast( datasource ); @@ -133,7 +133,7 @@ bool SFXVorbisStream::_openVorbis() cb.tell_func = canSeek ? _tell_func : NULL; // Open it. - int ovResult = ov_open_callbacks( mStream, mVF, NULL, 0, cb ); + S32 ovResult = ov_open_callbacks( mStream, mVF, NULL, 0, cb ); if( ovResult != 0 ) return false; @@ -196,9 +196,9 @@ S32 SFXVorbisStream::read( U8 *buffer, mBitstream = *bitstream; #ifdef TORQUE_BIG_ENDIAN - static const int isBigEndian = 1; + static const S32 isBigEndian = 1; #else - static const int isBigEndian = 0; + static const S32 isBigEndian = 0; #endif // Vorbis doesn't seem to like reading diff --git a/Engine/source/sfx/media/sfxVorbisStream.h b/Engine/source/sfx/media/sfxVorbisStream.h index 680d550fa..74b9d0964 100644 --- a/Engine/source/sfx/media/sfxVorbisStream.h +++ b/Engine/source/sfx/media/sfxVorbisStream.h @@ -56,7 +56,7 @@ class SFXVorbisStream : public SFXFileStream, // The ov_callbacks. static size_t _read_func( void *ptr, size_t size, size_t nmemb, void *datasource ); - static int _seek_func( void *datasource, ogg_int64_t offset, int whence ); + static S32 _seek_func( void *datasource, ogg_int64_t offset, S32 whence ); static long _tell_func( void *datasource ); // SFXStream diff --git a/Engine/source/sfx/openal/aldlist.cpp b/Engine/source/sfx/openal/aldlist.cpp index e3991a7ee..13ee1409c 100644 --- a/Engine/source/sfx/openal/aldlist.cpp +++ b/Engine/source/sfx/openal/aldlist.cpp @@ -161,9 +161,9 @@ const char *ALDeviceList::GetDeviceName(int index) void ALDeviceList::GetDeviceVersion(int index, int *major, int *minor) { if (index < GetNumDevices()) { - if (*major) + if (major) *major = vDeviceInfo[index].iMajorVersion; - if (*minor) + if (minor) *minor = vDeviceInfo[index].iMinorVersion; } return; @@ -172,7 +172,7 @@ void ALDeviceList::GetDeviceVersion(int index, int *major, int *minor) /* * Returns the maximum number of Sources that can be generate on the given device */ -unsigned int ALDeviceList::GetMaxNumSources(int index) +U32 ALDeviceList::GetMaxNumSources(S32 index) { if (index < GetNumDevices()) return vDeviceInfo[index].uiSourceCount; @@ -204,10 +204,10 @@ int ALDeviceList::GetDefaultDevice() /* * Deselects devices which don't have the specified minimum version */ -void ALDeviceList::FilterDevicesMinVer(int major, int minor) +void ALDeviceList::FilterDevicesMinVer(S32 major, S32 minor) { int dMajor, dMinor; - for (unsigned int i = 0; i < vDeviceInfo.size(); i++) { + for (U32 i = 0; i < vDeviceInfo.size(); i++) { GetDeviceVersion(i, &dMajor, &dMinor); if ((dMajor < major) || ((dMajor == major) && (dMinor < minor))) { vDeviceInfo[i].bSelected = false; @@ -218,10 +218,10 @@ void ALDeviceList::FilterDevicesMinVer(int major, int minor) /* * Deselects devices which don't have the specified maximum version */ -void ALDeviceList::FilterDevicesMaxVer(int major, int minor) +void ALDeviceList::FilterDevicesMaxVer(S32 major, S32 minor) { - int dMajor, dMinor; - for (unsigned int i = 0; i < vDeviceInfo.size(); i++) { + S32 dMajor, dMinor; + for (U32 i = 0; i < vDeviceInfo.size(); i++) { GetDeviceVersion(i, &dMajor, &dMinor); if ((dMajor > major) || ((dMajor == major) && (dMinor > minor))) { vDeviceInfo[i].bSelected = false; @@ -234,7 +234,7 @@ void ALDeviceList::FilterDevicesMaxVer(int major, int minor) */ void ALDeviceList::FilterDevicesExtension(SFXALCaps cap) { - for (unsigned int i = 0; i < vDeviceInfo.size(); i++) + for (U32 i = 0; i < vDeviceInfo.size(); i++) vDeviceInfo[i].bSelected = vDeviceInfo[i].iCapsFlags & cap; } @@ -243,7 +243,7 @@ void ALDeviceList::FilterDevicesExtension(SFXALCaps cap) */ void ALDeviceList::ResetFilters() { - for (int i = 0; i < GetNumDevices(); i++) { + for (S32 i = 0; i < GetNumDevices(); i++) { vDeviceInfo[i].bSelected = true; } filterIndex = 0; @@ -287,7 +287,7 @@ int ALDeviceList::GetNextFilteredDevice() unsigned int ALDeviceList::GetMaxNumSources() { ALuint uiSources[256]; - unsigned int iSourceCount = 0; + U32 iSourceCount = 0; // Clear AL Error Code ALFunction.alGetError(); @@ -304,7 +304,7 @@ unsigned int ALDeviceList::GetMaxNumSources() ALFunction.alDeleteSources(iSourceCount, uiSources); if (ALFunction.alGetError() != AL_NO_ERROR) { - for (unsigned int i = 0; i < 256; i++) + for (U32 i = 0; i < 256; i++) { ALFunction.alDeleteSources(1, &uiSources[i]); } diff --git a/Engine/source/sfx/openal/aldlist.h b/Engine/source/sfx/openal/aldlist.h index 00b0eaec3..3b2d7e948 100644 --- a/Engine/source/sfx/openal/aldlist.h +++ b/Engine/source/sfx/openal/aldlist.h @@ -32,10 +32,10 @@ typedef struct { char strDeviceName[256]; - int iMajorVersion; - int iMinorVersion; - unsigned int uiSourceCount; - int iCapsFlags; + S32 iMajorVersion; + S32 iMinorVersion; + U32 uiSourceCount; + S32 iCapsFlags; bool bSelected; } ALDEVICEINFO, *LPALDEVICEINFO; @@ -44,27 +44,27 @@ class ALDeviceList private: OPENALFNTABLE ALFunction; Vector vDeviceInfo; - int defaultDeviceIndex; - int filterIndex; + S32 defaultDeviceIndex; + S32 filterIndex; public: ALDeviceList ( const OPENALFNTABLE &oalft ); ~ALDeviceList (); - int GetNumDevices(); - const char *GetDeviceName(int index); - void GetDeviceVersion(int index, int *major, int *minor); - unsigned int GetMaxNumSources(int index); - bool IsExtensionSupported(int index, SFXALCaps caps); - int GetDefaultDevice(); - void FilterDevicesMinVer(int major, int minor); - void FilterDevicesMaxVer(int major, int minor); + S32 GetNumDevices(); + const char *GetDeviceName(S32 index); + void GetDeviceVersion(S32 index, S32 *major, S32 *minor); + U32 GetMaxNumSources(S32 index); + bool IsExtensionSupported(S32 index, SFXALCaps caps); + S32 GetDefaultDevice(); + void FilterDevicesMinVer(S32 major, S32 minor); + void FilterDevicesMaxVer(S32 major, S32 minor); void FilterDevicesExtension(SFXALCaps caps); void ResetFilters(); - int GetFirstFilteredDevice(); - int GetNextFilteredDevice(); + S32 GetFirstFilteredDevice(); + S32 GetNextFilteredDevice(); private: - unsigned int GetMaxNumSources(); + U32 GetMaxNumSources(); }; #endif // ALDEVICELIST_H diff --git a/Engine/source/sfx/openal/sfxALProvider.cpp b/Engine/source/sfx/openal/sfxALProvider.cpp index 7570500d6..bd4f8cfdd 100644 --- a/Engine/source/sfx/openal/sfxALProvider.cpp +++ b/Engine/source/sfx/openal/sfxALProvider.cpp @@ -93,18 +93,18 @@ void SFXALProvider::init() const char *deviceFormat = "OpenAL v%d.%d %s"; char temp[256]; - for( int i = 0; i < mALDL->GetNumDevices(); i++ ) + for( S32 i = 0; i < mALDL->GetNumDevices(); i++ ) { ALDeviceInfo* info = new ALDeviceInfo; info->name = String( mALDL->GetDeviceName( i ) ); - int major, minor, eax = 0; + S32 major, minor, eax = 0; mALDL->GetDeviceVersion( i, &major, &minor ); // Apologies for the blatent enum hack -patw - for( int j = SFXALEAX2; j < SFXALEAXRAM; j++ ) + for( S32 j = SFXALEAX2; j < SFXALEAXRAM; j++ ) eax += (int)mALDL->IsExtensionSupported( i, (SFXALCaps)j ); if( eax > 0 ) diff --git a/Engine/source/sfx/sfxCommon.h b/Engine/source/sfx/sfxCommon.h index 587672ca0..956f24055 100644 --- a/Engine/source/sfx/sfxCommon.h +++ b/Engine/source/sfx/sfxCommon.h @@ -561,7 +561,7 @@ class SFXMaterialProperties /// An array of float values with optional random variances. -template< int NUM_VALUES > +template< S32 NUM_VALUES > struct SFXVariantFloat { /// Base value. diff --git a/Engine/source/sfx/sfxSystem.cpp b/Engine/source/sfx/sfxSystem.cpp index c43a44b2f..9faa5dd4c 100644 --- a/Engine/source/sfx/sfxSystem.cpp +++ b/Engine/source/sfx/sfxSystem.cpp @@ -854,7 +854,7 @@ void SFXSystem::_updateSources() if( source->getLastStatus() == SFXStatusStopped && source->getSavedStatus() != SFXStatusPlaying ) { - int index = iter - mPlayOnceSources.begin(); + S32 index = iter - mPlayOnceSources.begin(); // Erase it from the vector first, so that onRemoveSource // doesn't do it during cleanup and screw up our loop here! diff --git a/Engine/source/sfx/sfxWorld.h b/Engine/source/sfx/sfxWorld.h index 2806cc4c8..289455b69 100644 --- a/Engine/source/sfx/sfxWorld.h +++ b/Engine/source/sfx/sfxWorld.h @@ -101,7 +101,7 @@ enum SFXObjectFlags /// 3D voices active on the device at any one point is defined as the set of /// current sound sources. /// -template< int NUM_DIMENSIONS > +template< S32 NUM_DIMENSIONS > class SFXObject : public ScopeTrackerObject< NUM_DIMENSIONS > { public: @@ -184,7 +184,7 @@ class SFXObject : public ScopeTrackerObject< NUM_DIMENSIONS > /// occlusion manager installed on the system and tracking the listener traveling through /// the ambient spaces is /// -template< int NUM_DIMENSIONS, typename Object > +template< S32 NUM_DIMENSIONS, typename Object > class SFXWorld : public ScopeTracker< NUM_DIMENSIONS, Object > { public: @@ -250,7 +250,7 @@ class SFXWorld : public ScopeTracker< NUM_DIMENSIONS, Object > //----------------------------------------------------------------------------- -template< int NUM_DIMENSIONS, class Object > +template< S32 NUM_DIMENSIONS, class Object > SFXWorld< NUM_DIMENSIONS, Object >::SFXWorld() { VECTOR_SET_ASSOCIATION( mScopeStack ); @@ -258,7 +258,7 @@ SFXWorld< NUM_DIMENSIONS, Object >::SFXWorld() //----------------------------------------------------------------------------- -template< int NUM_DIMENSIONS, class Object > +template< S32 NUM_DIMENSIONS, class Object > void SFXWorld< NUM_DIMENSIONS, Object >::update() { if( !this->mReferenceObject ) @@ -320,7 +320,7 @@ void SFXWorld< NUM_DIMENSIONS, Object >::update() //----------------------------------------------------------------------------- -template< int NUM_DIMENSIONS, class Object > +template< S32 NUM_DIMENSIONS, class Object > void SFXWorld< NUM_DIMENSIONS, Object >::notifyChanged( Object object ) { SFXAmbience* ambience = Deref( object ).getAmbience(); @@ -369,7 +369,7 @@ void SFXWorld< NUM_DIMENSIONS, Object >::_onScopeIn( Object object ) //----------------------------------------------------------------------------- -template< int NUM_DIMENSIONS, class Object > +template< S32 NUM_DIMENSIONS, class Object > void SFXWorld< NUM_DIMENSIONS, Object >::_onScopeOut( Object object ) { #ifdef DEBUG_SPEW @@ -393,7 +393,7 @@ void SFXWorld< NUM_DIMENSIONS, Object >::_onScopeOut( Object object ) //----------------------------------------------------------------------------- -template< int NUM_DIMENSIONS, class Object > +template< S32 NUM_DIMENSIONS, class Object > F32 SFXWorld< NUM_DIMENSIONS, Object >::_getSortValue( Object object ) { //RDTODO: probably need to work with the overlap here instead of the full volumes @@ -414,7 +414,7 @@ F32 SFXWorld< NUM_DIMENSIONS, Object >::_getSortValue( Object object ) //----------------------------------------------------------------------------- -template< int NUM_DIMENSIONS, class Object > +template< S32 NUM_DIMENSIONS, class Object > S32 SFXWorld< NUM_DIMENSIONS, Object >::_findScope( Object object ) { for( U32 i = 0; i < mScopeStack.size(); ++ i ) diff --git a/Engine/source/shaderGen/GLSL/bumpGLSL.cpp b/Engine/source/shaderGen/GLSL/bumpGLSL.cpp index 737ddcbaf..1b1cd0437 100644 --- a/Engine/source/shaderGen/GLSL/bumpGLSL.cpp +++ b/Engine/source/shaderGen/GLSL/bumpGLSL.cpp @@ -64,14 +64,14 @@ void BumpFeatGLSL::processPix( Vector &componentList, output = meta; // Get the texture coord. - Var *texCoord = getInTexCoord( "out_texCoord", "vec2", true, componentList ); + Var *texCoord = getInTexCoord( "texCoord", "vec2", true, componentList ); // Sample the bumpmap. Var *bumpMap = getNormalMapTex(); - LangElement *texOp = NULL; //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]) { // This is a big block of code, so put a comment in the shader code @@ -79,52 +79,49 @@ void BumpFeatGLSL::processPix( Vector &componentList, Var *atlasedTex = new Var; atlasedTex->setName("atlasedBumpCoord"); - atlasedTex->setType("vec2"); + atlasedTex->setType( "vec2" ); LangElement *atDecl = new DecOp(atlasedTex); // Parameters of the texture atlas Var *atParams = new Var; - atParams->setType("vec4"); + atParams->setType( "float4" ); atParams->setName("bumpAtlasParams"); atParams->uniform = true; atParams->constSortPos = cspPotentialPrimitive; // Parameters of the texture (tile) this object is using in the atlas Var *tileParams = new Var; - tileParams->setType("vec4"); + tileParams->setType( "float4" ); tileParams->setName("bumpAtlasTileParams"); tileParams->uniform = true; tileParams->constSortPos = cspPotentialPrimitive; const bool is_sm3 = (GFX->getPixelShaderVersion() > 2.0f); - // getPixelShaderVersion() on Mac currently returns 2.0, - // or 3.0 if Advanced Lighting is enabled if(is_sm3) { // Figure out the mip level - meta->addStatement(new GenOp(" vec2 _dx_bump = dFdx(@ * @.z);\r\n", texCoord, atParams)); - meta->addStatement(new GenOp(" vec2 _dy_bump = dFdy(@ * @.z);\r\n", texCoord, atParams)); - meta->addStatement(new GenOp(" float mipLod_bump = 0.5 * log2(max(dot(_dx_bump, _dx_bump), dot(_dy_bump, _dy_bump)));\r\n")); - meta->addStatement(new GenOp(" mipLod_bump = clamp(mipLod_bump, 0.0, @.w);\r\n", atParams)); + meta->addStatement( new GenOp( " float2 _dx_bump = ddx(@ * @.z);\r\n", texCoord, atParams ) ); + meta->addStatement( new GenOp( " float2 _dy_bump = ddy(@ * @.z);\r\n", texCoord, atParams ) ); + meta->addStatement( new GenOp( " float mipLod_bump = 0.5 * log2(max(dot(_dx_bump, _dx_bump), dot(_dy_bump, _dy_bump)));\r\n")); + meta->addStatement( new GenOp( " mipLod_bump = clamp(mipLod_bump, 0.0, @.w);\r\n", atParams)); // And the size of the mip level meta->addStatement(new GenOp(" float mipPixSz_bump = pow(2.0, @.w - mipLod_bump);\r\n", atParams)); - meta->addStatement(new GenOp(" vec2 mipSz_bump = mipPixSz_bump / @.xy;\r\n", atParams)); + meta->addStatement( new GenOp( " float2 mipSz_bump = mipPixSz_bump / @.xy;\r\n", atParams ) ); } else { - meta->addStatement(new GenOp(" vec2 mipSz = float2(1.0, 1.0);\r\n")); + meta->addStatement(new GenOp(" float2 mipSz = float2(1.0, 1.0);\r\n")); } // Tiling mode - // TODO: Select wrap or clamp somehow if( true ) // Wrap - meta->addStatement(new GenOp(" @ = fract(@);\r\n", atDecl, texCoord)); + meta->addStatement( new GenOp( " @ = frac(@);\r\n", atDecl, texCoord ) ); else // Clamp meta->addStatement(new GenOp(" @ = saturate(@);\r\n", atDecl, texCoord)); // Finally scale/offset, and correct for filtering - meta->addStatement(new GenOp(" @ = @ * ((mipSz_bump * @.xy - 1.0) / mipSz_bump) + 0.5 / mipSz_bump + @.xy * @.xy;\r\n", + meta->addStatement( new GenOp( " @ = @ * ((mipSz_bump * @.xy - 1.0) / mipSz_bump) + 0.5 / mipSz_bump + @.xy * @.xy;\r\n", atlasedTex, atlasedTex, atParams, atParams, tileParams)); // Add a newline @@ -132,19 +129,19 @@ void BumpFeatGLSL::processPix( Vector &componentList, if(is_sm3) { - texOp = new GenOp( "texture2DLod(@, vec4(@, 0.0, mipLod_bump)", bumpMap, texCoord ); + texOp = new GenOp( "tex2Dlod(@, float4(@, 0.0, mipLod_bump))", bumpMap, texCoord ); } else { - texOp = new GenOp( "texture2D(@, @)", bumpMap, texCoord ); + texOp = new GenOp( "tex2D(@, @)", bumpMap, texCoord ); } } else { - texOp = new GenOp( "texture2D(@, @)", bumpMap, texCoord ); + texOp = new GenOp( "tex2D(@, @)", bumpMap, texCoord ); } - Var *bumpNorm = new Var( "bumpNormal", "vec4" ); + Var *bumpNorm = new Var( "bumpNormal", "float4" ); meta->addStatement( expandNormalMap( texOp, new DecOp( bumpNorm ), bumpNorm, fd ) ); // If we have a detail normal map we add the xy coords of @@ -160,11 +157,11 @@ void BumpFeatGLSL::processPix( Vector &componentList, bumpMap->constNum = Var::getTexUnitNum(); texCoord = getInTexCoord( "detCoord", "vec2", true, componentList ); - texOp = new GenOp( "texture2D(@, @)", bumpMap, texCoord ); + texOp = new GenOp( "tex2D(@, @)", bumpMap, texCoord ); Var *detailBump = new Var; detailBump->setName( "detailBump" ); - detailBump->setType( "vec4" ); + detailBump->setType( "float4" ); meta->addStatement( expandNormalMap( texOp, new DecOp( detailBump ), detailBump, fd ) ); Var *detailBumpScale = new Var; @@ -175,13 +172,11 @@ void BumpFeatGLSL::processPix( Vector &componentList, meta->addStatement( new GenOp( " @.xy += @.xy * @;\r\n", bumpNorm, detailBump, detailBumpScale ) ); } - // We transform it into world space by reversing the // multiplication by the worldToTanget transform. Var *wsNormal = new Var( "wsNormal", "vec3" ); Var *worldToTanget = getInWorldToTangent( componentList ); - meta->addStatement( new GenOp( " @ = normalize( vec3( @.xyz * @ ) );\r\n", new DecOp( wsNormal ), bumpNorm, worldToTanget ) ); - + meta->addStatement( new GenOp( " @ = normalize( tMul( @.xyz, @ ) );\r\n", new DecOp( wsNormal ), bumpNorm, worldToTanget ) ); } ShaderFeature::Resources BumpFeatGLSL::getResources( const MaterialFeatureData &fd ) @@ -227,20 +222,26 @@ void BumpFeatGLSL::setTexData( Material::StageData &stageDat, if ( fd.features[MFT_NormalMap] ) { passData.mTexType[ texIndex ] = Material::Bump; + passData.mSamplerNames[ texIndex ] = "bumpMap"; passData.mTexSlot[ texIndex++ ].texObject = stageDat.getTex( MFT_NormalMap ); } - if ( fd.features[ MFT_DetailNormalMap ] ) { passData.mTexType[ texIndex ] = Material::DetailBump; + passData.mSamplerNames[ texIndex ] = "detailBumpMap"; passData.mTexSlot[ texIndex++ ].texObject = stageDat.getTex( MFT_DetailNormalMap ); } } -// -Var* ParallaxFeatGLSL::_getUniformVar( const char *name, const char *type ) +ParallaxFeatGLSL::ParallaxFeatGLSL() + : mIncludeDep( "shaders/common/gl/torque.glsl" ) +{ + addDependency( &mIncludeDep ); +} + +Var* ParallaxFeatGLSL::_getUniformVar( const char *name, const char *type, ConstantSortPosition csp ) { Var *theVar = (Var*)LangElement::find( name ); if ( !theVar ) @@ -249,7 +250,7 @@ Var* ParallaxFeatGLSL::_getUniformVar( const char *name, const char *type ) theVar->setType( type ); theVar->setName( name ); theVar->uniform = true; - theVar->constSortPos = cspPass; + theVar->constSortPos = csp; } return theVar; @@ -259,13 +260,13 @@ void ParallaxFeatGLSL::processVert( Vector &componentList, const MaterialFeatureData &fd ) { AssertFatal( GFX->getPixelShaderVersion() >= 2.0, - "ParallaxFeatGLSL::processVert - We don't support SM 1.x!" ); + "ParallaxFeatGLSL::processVert - We don't support SM 1.x!" ); MultiLine *meta = new MultiLine; // Add the texture coords. getOutTexCoord( "texCoord", - "vec2", + "vec2", true, fd.features[MFT_TexAnim], meta, @@ -276,18 +277,36 @@ void ParallaxFeatGLSL::processVert( Vector &componentList, if ( !inPos ) inPos = (Var*)LangElement::find( "position" ); - // Get the object space eye position and the world - // to tangent transform. - Var *eyePos = _getUniformVar( "eyePos", "vec3" ); + // Get the object space eye position and the + // object to tangent space transform. + Var *eyePos = _getUniformVar( "eyePos", "vec3", cspPrimitive ); Var *objToTangentSpace = getOutObjToTangentSpace( componentList, meta, fd ); - // send transform to pixel shader + // Now send the negative view vector in tangent space to the pixel shader. ShaderConnector *connectComp = dynamic_cast( componentList[C_CONNECTOR] ); - Var *outViewTS = connectComp->getElement( RT_TEXCOORD, 1 ); - outViewTS->setName( "outViewTS" ); - outViewTS->setType( "vec3" ); - meta->addStatement( new GenOp( " @ = ( @ - @.xyz ) * transpose( @ );\r\n", - outViewTS, inPos, eyePos, objToTangentSpace ) ); + Var *outNegViewTS = connectComp->getElement( RT_TEXCOORD ); + outNegViewTS->setName( "outNegViewTS" ); + outNegViewTS->setStructName( "OUT" ); + outNegViewTS->setType( "vec3" ); + meta->addStatement( new GenOp( " @ = tMul( @, float3( @.xyz - @ ) );\r\n", + outNegViewTS, objToTangentSpace, inPos, eyePos ) ); + + // TODO: I'm at a loss at why i need to flip the binormal/y coord + // to get a good view vector for parallax. Lighting works properly + // with the TS matrix as is... but parallax does not. + // + // Someone figure this out! + // + meta->addStatement( new GenOp( " @.y = -@.y;\r\n", outNegViewTS, outNegViewTS ) ); + + // If we have texture anim matrix the tangent + // space view vector may need to be rotated. + Var *texMat = (Var*)LangElement::find( "texMat" ); + if ( texMat ) + { + meta->addStatement( new GenOp( " @ = tMul(@, float4(@,0)).xyz;\r\n", + outNegViewTS, texMat, outNegViewTS ) ); + } output = meta; } @@ -296,7 +315,7 @@ void ParallaxFeatGLSL::processPix( Vector &componentList, const MaterialFeatureData &fd ) { AssertFatal( GFX->getPixelShaderVersion() >= 2.0, - "ParallaxFeatGLSL::processPix - We don't support SM 1.x!" ); + "ParallaxFeatGLSL::processPix - We don't support SM 1.x!" ); MultiLine *meta = new MultiLine; @@ -310,38 +329,28 @@ void ParallaxFeatGLSL::processPix( Vector &componentList, Var *negViewTS = (Var*)LangElement::find( "negViewTS" ); if ( !negViewTS ) { - Var *inViewTS = (Var*)LangElement::find( "outViewTS" ); - if ( !inViewTS ) + Var *inNegViewTS = (Var*)LangElement::find( "outNegViewTS" ); + if ( !inNegViewTS ) { - inViewTS = connectComp->getElement( RT_TEXCOORD, 1 ); - inViewTS->setName( "outViewTS" ); - inViewTS->setType( "vec3" ); + inNegViewTS = connectComp->getElement( RT_TEXCOORD ); + inNegViewTS->setName( "outNegViewTS" ); + inNegViewTS->setStructName( "IN" ); + inNegViewTS->setType( "vec3" ); } negViewTS = new Var( "negViewTS", "vec3" ); - meta->addStatement( new GenOp( " @ = -normalize( @ );\r\n", new DecOp( negViewTS ), inViewTS ) ); + meta->addStatement( new GenOp( " @ = normalize( @ );\r\n", new DecOp( negViewTS ), inNegViewTS ) ); } // Get the rest of our inputs. - Var *parallaxInfo = _getUniformVar( "parallaxInfo", "float" ); + Var *parallaxInfo = _getUniformVar( "parallaxInfo", "float", cspPotentialPrimitive ); Var *normalMap = getNormalMapTex(); - // Do 3 parallax samples to get acceptable - // quality without too much overhead. - Var *pdepth = findOrCreateLocal( "pdepth", "float", meta ); - Var *poffset = findOrCreateLocal( "poffset", "vec2", meta ); - meta->addStatement( new GenOp( " @ = texture2D( @, @.xy ).a;\r\n", pdepth, normalMap, texCoord ) ); - meta->addStatement( new GenOp( " @ = @.xy * ( @ * @ );\r\n", poffset, negViewTS, pdepth, parallaxInfo ) ); - - meta->addStatement( new GenOp( " @ = ( @ + texture2D( @, @.xy + @ ).a ) * 0.5;\r\n", pdepth, pdepth, normalMap, texCoord, poffset ) ); - meta->addStatement( new GenOp( " @ = @.xy * ( @ * @ );\r\n", poffset, negViewTS, pdepth, parallaxInfo ) ); - - meta->addStatement( new GenOp( " @ = ( @ + texture2D( @, @.xy + @ ).a ) * 0.5;\r\n", pdepth, pdepth, normalMap, texCoord, poffset ) ); - meta->addStatement( new GenOp( " @ = @.xy * ( @ * @ );\r\n", poffset, negViewTS, pdepth, parallaxInfo ) ); - - meta->addStatement( new GenOp( " @.xy += @;\r\n", texCoord, poffset ) ); + // Call the library function to do the rest. + meta->addStatement( new GenOp( " @.xy += parallaxOffset( @, @.xy, @, @ );\r\n", + texCoord, normalMap, texCoord, negViewTS, parallaxInfo ) ); - // TODO: Fix second UV. + // TODO: Fix second UV maybe? output = meta; } @@ -349,7 +358,7 @@ void ParallaxFeatGLSL::processPix( Vector &componentList, ShaderFeature::Resources ParallaxFeatGLSL::getResources( const MaterialFeatureData &fd ) { AssertFatal( GFX->getPixelShaderVersion() >= 2.0, - "ParallaxFeatGLSL::getResources - We don't support SM 1.x!" ); + "ParallaxFeatGLSL::getResources - We don't support SM 1.x!" ); Resources res; @@ -370,7 +379,7 @@ void ParallaxFeatGLSL::setTexData( Material::StageData &stageDat, U32 &texIndex ) { AssertFatal( GFX->getPixelShaderVersion() >= 2.0, - "ParallaxFeatGLSL::setTexData - We don't support SM 1.x!" ); + "ParallaxFeatGLSL::setTexData - We don't support SM 1.x!" ); GFXTextureObject *tex = stageDat.getTex( MFT_NormalMap ); if ( tex ) @@ -381,7 +390,6 @@ void ParallaxFeatGLSL::setTexData( Material::StageData &stageDat, } -// void NormalsOutFeatGLSL::processVert( Vector &componentList, const MaterialFeatureData &fd ) { @@ -397,6 +405,7 @@ void NormalsOutFeatGLSL::processVert( Vector &componentList, Var *outNormal = connectComp->getElement( RT_TEXCOORD ); outNormal->setName( "wsNormal" ); + outNormal->setStructName( "OUT" ); outNormal->setType( "vec3" ); outNormal->mapsToSampler = false; @@ -406,13 +415,13 @@ void NormalsOutFeatGLSL::processVert( Vector &componentList, { // Transform the normal to world space. Var *objTrans = getObjTrans( componentList, fd.features[MFT_UseInstancing], meta ); - meta->addStatement( new GenOp( " @ = @ * normalize( @ );\r\n", outNormal, objTrans, inNormal ) ); + meta->addStatement( new GenOp( " @ = tMul( @, normalize( vec4(@, 0.0) ) ).xyz;\r\n", outNormal, objTrans, inNormal ) ); } else { // If we don't have a vertex normal... just pass the // camera facing normal to the pixel shader. - meta->addStatement( new GenOp( " @ = vec3( 0.0, 0.0, 1.0 );\r\n", outNormal ) ); + meta->addStatement( new GenOp( " @ = float3( 0.0, 0.0, 1.0 );\r\n", outNormal ) ); } } @@ -428,20 +437,26 @@ void NormalsOutFeatGLSL::processPix( Vector &componentList, ShaderConnector *connectComp = dynamic_cast( componentList[C_CONNECTOR] ); wsNormal = connectComp->getElement( RT_TEXCOORD ); wsNormal->setName( "wsNormal" ); + wsNormal->setStructName( "IN" ); wsNormal->setType( "vec3" ); // If we loaded the normal its our resposibility // to normalize it... the interpolators won't. // - meta->addStatement( new GenOp( " @ = normalize( @ );\r\n", wsNormal, wsNormal ) ); + // Note we cast to half here to get partial precision + // optimized code which is an acceptable loss of + // precision for normals and performs much better + // on older Geforce cards. + // + meta->addStatement( new GenOp( " @ = normalize( half3( @ ) );\r\n", wsNormal, wsNormal ) ); } LangElement *normalOut; Var *outColor = (Var*)LangElement::find( "col" ); - if ( outColor ) - normalOut = new GenOp( "vec4( ( -@ + 1 ) * 0.5, @.a )", wsNormal, outColor ); + if ( outColor && !fd.features[MFT_AlphaTest] ) + normalOut = new GenOp( "float4( ( -@ + 1 ) * 0.5, @.a )", wsNormal, outColor ); else - normalOut = new GenOp( "vec4( ( -@ + 1 ) * 0.5, 1 )", wsNormal ); + normalOut = new GenOp( "float4( ( -@ + 1 ) * 0.5, 1 )", wsNormal ); meta->addStatement( new GenOp( " @;\r\n", assignColor( normalOut, Material::None ) ) ); diff --git a/Engine/source/shaderGen/GLSL/bumpGLSL.h b/Engine/source/shaderGen/GLSL/bumpGLSL.h index 899434f15..b37bb9099 100644 --- a/Engine/source/shaderGen/GLSL/bumpGLSL.h +++ b/Engine/source/shaderGen/GLSL/bumpGLSL.h @@ -26,6 +26,9 @@ #ifndef _SHADERGEN_GLSL_SHADERFEATUREGLSL_H_ #include "shaderGen/GLSL/shaderFeatureGLSL.h" #endif +#ifndef _LANG_ELEMENT_H_ +#include "shaderGen/langElement.h" +#endif struct RenderPassData; class MultiLine; @@ -50,7 +53,6 @@ public: const MaterialFeatureData &fd, RenderPassData &passData, U32 &texIndex ); - virtual String getName() { return "Bumpmap"; } }; @@ -62,10 +64,16 @@ class ParallaxFeatGLSL : public ShaderFeatureGLSL { protected: - static Var* _getUniformVar( const char *name, const char *type ); + static Var* _getUniformVar( const char *name, + const char *type, + ConstantSortPosition csp ); + + ShaderIncludeDependency mIncludeDep; public: + ParallaxFeatGLSL(); + // ShaderFeatureGLSL virtual void processVert( Vector &componentList, const MaterialFeatureData &fd ); @@ -80,7 +88,6 @@ public: }; - /// This feature is used to render normals to the /// diffuse target for imposter rendering. class NormalsOutFeatGLSL : public ShaderFeatureGLSL diff --git a/Engine/source/shaderGen/GLSL/depthGLSL.cpp b/Engine/source/shaderGen/GLSL/depthGLSL.cpp index 4c5f1b837..71bdbb96e 100644 --- a/Engine/source/shaderGen/GLSL/depthGLSL.cpp +++ b/Engine/source/shaderGen/GLSL/depthGLSL.cpp @@ -24,36 +24,36 @@ #include "shaderGen/GLSL/depthGLSL.h" #include "materials/materialFeatureTypes.h" +#include "materials/materialFeatureData.h" void EyeSpaceDepthOutGLSL::processVert( Vector &componentList, const MaterialFeatureData &fd ) { - - MultiLine *meta = new MultiLine; + MultiLine *meta = new MultiLine; output = meta; - // grab output + // grab output ShaderConnector *connectComp = dynamic_cast( componentList[C_CONNECTOR] ); Var *outWSEyeVec = connectComp->getElement( RT_TEXCOORD ); - outWSEyeVec->setName( "outWSEyeVec" ); - - - // grab incoming vert position - Var *wsPosition = new Var( "depthPos", "vec3" ); + outWSEyeVec->setName( "wsEyeVec" ); + outWSEyeVec->setStructName( "OUT" ); + + // grab incoming vert position + Var *wsPosition = new Var( "depthPos", "float3" ); getWsPosition( componentList, fd.features[MFT_UseInstancing], meta, new DecOp( wsPosition ) ); Var *eyePos = (Var*)LangElement::find( "eyePosWorld" ); if( !eyePos ) { eyePos = new Var; - eyePos->setType("vec3"); + eyePos->setType("float3"); eyePos->setName("eyePosWorld"); eyePos->uniform = true; eyePos->constSortPos = cspPass; } -meta->addStatement( new GenOp( " @ = vec4( @.xyz - @, 1 );\r\n", outWSEyeVec, wsPosition, eyePos ) ); + meta->addStatement( new GenOp( " @ = float4( @.xyz - @, 1 );\r\n", outWSEyeVec, wsPosition, eyePos ) ); } void EyeSpaceDepthOutGLSL::processPix( Vector &componentList, @@ -64,14 +64,15 @@ void EyeSpaceDepthOutGLSL::processPix( Vector &componentList, // grab connector position ShaderConnector *connectComp = dynamic_cast( componentList[C_CONNECTOR] ); Var *wsEyeVec = connectComp->getElement( RT_TEXCOORD ); - wsEyeVec->setName( "outWSEyeVec" ); - wsEyeVec->setType( "vec4" ); + wsEyeVec->setName( "wsEyeVec" ); + wsEyeVec->setStructName( "IN" ); + wsEyeVec->setType( "float4" ); wsEyeVec->mapsToSampler = false; wsEyeVec->uniform = false; // get shader constants Var *vEye = new Var; - vEye->setType("vec3"); + vEye->setType("float3"); vEye->setName("vEye"); vEye->uniform = true; vEye->constSortPos = cspPass; @@ -83,12 +84,27 @@ void EyeSpaceDepthOutGLSL::processPix( Vector &componentList, LangElement *depthOutDecl = new DecOp( depthOut ); + meta->addStatement( new GenOp( "#ifndef CUBE_SHADOW_MAP\r\n" ) ); meta->addStatement( new GenOp( " @ = dot(@, (@.xyz / @.w));\r\n", depthOutDecl, vEye, wsEyeVec, wsEyeVec ) ); + meta->addStatement( new GenOp( "#else\r\n" ) ); + + Var *farDist = (Var*)Var::find( "oneOverFarplane" ); + if ( !farDist ) + { + farDist = new Var; + farDist->setType("float4"); + farDist->setName("oneOverFarplane"); + farDist->uniform = true; + farDist->constSortPos = cspPass; + } + + meta->addStatement( new GenOp( " @ = length( @.xyz / @.w ) * @.x;\r\n", depthOutDecl, wsEyeVec, wsEyeVec, farDist ) ); + meta->addStatement( new GenOp( "#endif\r\n" ) ); // If there isn't an output conditioner for the pre-pass, than just write // out the depth to rgba and return. if( !fd.features[MFT_PrePassConditioner] ) - meta->addStatement( new GenOp( " @;\r\n", assignColor( new GenOp( "vec4(@)", depthOut ), Material::None ) ) ); + meta->addStatement( new GenOp( " @;\r\n", assignColor( new GenOp( "float4(float3(@),1)", depthOut ), Material::None ) ) ); output = meta; } @@ -111,11 +127,12 @@ void DepthOutGLSL::processVert( Vector &componentList, ShaderConnector *connectComp = dynamic_cast( componentList[C_CONNECTOR] ); // Grab the output vert. - Var *outPosition = (Var*)LangElement::find( "gl_Position" ); + Var *outPosition = (Var*)LangElement::find( "gl_Position" ); //hpos // Grab our output depth. Var *outDepth = connectComp->getElement( RT_TEXCOORD ); - outDepth->setName( "outDepth" ); + outDepth->setName( "depth" ); + outDepth->setStructName( "OUT" ); outDepth->setType( "float" ); output = new GenOp( " @ = @.z / @.w;\r\n", outDepth, outPosition, outPosition ); @@ -128,7 +145,8 @@ void DepthOutGLSL::processPix( Vector &componentList, // grab connector position Var *depthVar = connectComp->getElement( RT_TEXCOORD ); - depthVar->setName( "outDepth" ); + depthVar->setName( "depth" ); + depthVar->setStructName( "IN" ); depthVar->setType( "float" ); depthVar->mapsToSampler = false; depthVar->uniform = false; @@ -140,7 +158,7 @@ void DepthOutGLSL::processPix( Vector &componentList, depthOut->setName(getOutputVarName()); */ - LangElement *depthOut = new GenOp( "vec4( @, @ * @, 0, 1 )", depthVar, depthVar, depthVar ); + LangElement *depthOut = new GenOp( "float4( @, 0, 0, 1 )", depthVar ); output = new GenOp( " @;\r\n", assignColor( depthOut, Material::None ) ); } diff --git a/Engine/source/shaderGen/GLSL/depthGLSL.h b/Engine/source/shaderGen/GLSL/depthGLSL.h index 97cb62095..c92326415 100644 --- a/Engine/source/shaderGen/GLSL/depthGLSL.h +++ b/Engine/source/shaderGen/GLSL/depthGLSL.h @@ -54,7 +54,7 @@ public: virtual Resources getResources( const MaterialFeatureData &fd ); virtual String getName() { return "Depth (Out)"; } virtual Material::BlendOp getBlendOp() { return Material::None; } - virtual const char* getOutputVarName() const { return "outDepth"; } + virtual const char* getOutputVarName() const { return "IN_depth"; } }; #endif // _DEPTH_GLSL_H_ \ No newline at end of file diff --git a/Engine/source/shaderGen/GLSL/paraboloidGLSL.cpp b/Engine/source/shaderGen/GLSL/paraboloidGLSL.cpp index 373712c36..61e56d215 100644 --- a/Engine/source/shaderGen/GLSL/paraboloidGLSL.cpp +++ b/Engine/source/shaderGen/GLSL/paraboloidGLSL.cpp @@ -65,7 +65,7 @@ void ParaboloidVertTransformGLSL::processVert( Vector &compon // http://www.gamedev.net/reference/articles/article2308.asp // Swizzle z and y post-transform - meta->addStatement( new GenOp( " @ = vec4(@ * vec4(@.xyz,1)).xzyw;\r\n", outPosition, worldViewOnly, inPosition ) ); + meta->addStatement( new GenOp( " @ = tMul(@, float4(@.xyz,1)).xzyw;\r\n", outPosition, worldViewOnly, inPosition ) ); meta->addStatement( new GenOp( " float L = length(@.xyz);\r\n", outPosition ) ); if ( isSinglePass ) @@ -73,7 +73,8 @@ void ParaboloidVertTransformGLSL::processVert( Vector &compon // Flip the z in the back case Var *outIsBack = connectComp->getElement( RT_TEXCOORD ); outIsBack->setType( "float" ); - outIsBack->setName( "outIsBack" ); + outIsBack->setName( "isBack" ); + outIsBack->setStructName( "OUT" ); meta->addStatement( new GenOp( " bool isBack = @.z < 0.0;\r\n", outPosition ) ); meta->addStatement( new GenOp( " @ = isBack ? -1.0 : 1.0;\r\n", outIsBack ) ); @@ -94,15 +95,16 @@ void ParaboloidVertTransformGLSL::processVert( Vector &compon // TODO: If we change other shadow shaders to write out // linear depth, than fix this as well! // - // (L - 1.0)/(lightParams.x - 1.0); + // (L - zNear)/(lightParams.x - zNear); // meta->addStatement( new GenOp( " @.z = L / @.x;\r\n", outPosition, lightParams ) ); meta->addStatement( new GenOp( " @.w = 1.0;\r\n", outPosition ) ); // Pass unmodified to pixel shader to allow it to clip properly. Var *outPosXY = connectComp->getElement( RT_TEXCOORD ); - outPosXY->setType( "vec2" ); - outPosXY->setName( "outPosXY" ); + outPosXY->setType( "float2" ); + outPosXY->setName( "posXY" ); + outPosXY->setStructName( "OUT" ); meta->addStatement( new GenOp( " @ = @.xy;\r\n", outPosXY, outPosition ) ); // Scale and offset so it shows up in the atlas properly. @@ -136,16 +138,18 @@ void ParaboloidVertTransformGLSL::processPix( Vector &compon { // Cull things on the back side of the map. Var *isBack = connectComp->getElement( RT_TEXCOORD ); - isBack->setName( "outIsBack" ); + isBack->setName( "isBack" ); + isBack->setStructName( "IN" ); isBack->setType( "float" ); meta->addStatement( new GenOp( " if ( ( abs( @ ) - 0.999 ) < 0 ) discard;\r\n", isBack ) ); } // Cull pixels outside of the valid paraboloid. Var *posXY = connectComp->getElement( RT_TEXCOORD ); - posXY->setName( "outPosXY" ); - posXY->setType( "vec2" ); - meta->addStatement( new GenOp( " if ( ( 1.0 - length( @ ) ) < 0 ) discard;\r\n", posXY ) ); + posXY->setName( "posXY" ); + posXY->setStructName( "IN" ); + posXY->setType( "float2" ); + meta->addStatement( new GenOp( " clip( 1.0 - abs(@.x) );\r\n", posXY ) ); output = meta; } diff --git a/Engine/source/shaderGen/GLSL/pixSpecularGLSL.cpp b/Engine/source/shaderGen/GLSL/pixSpecularGLSL.cpp index ac313a103..4e34e2116 100644 --- a/Engine/source/shaderGen/GLSL/pixSpecularGLSL.cpp +++ b/Engine/source/shaderGen/GLSL/pixSpecularGLSL.cpp @@ -38,98 +38,35 @@ PixelSpecularGLSL::PixelSpecularGLSL() void PixelSpecularGLSL::processVert( Vector &componentList, const MaterialFeatureData &fd ) { - /* AssertFatal( fd.features[MFT_RTLighting], "PixelSpecularHLSL requires RTLighting to be enabled!" ); - MultiLine *meta = new MultiLine; - - // Get the eye world position. - Var *eyePos = (Var*)LangElement::find( "eyePosWorld" ); - if( !eyePos ) - { - eyePos = new Var; - eyePos->setType( "float3" ); - eyePos->setName( "eyePosWorld" ); - eyePos->uniform = true; - eyePos->constSortPos = cspPass; - } - - // Grab a register for passing the - // world space view vector. - ShaderConnector *connectComp = dynamic_cast( componentList[C_CONNECTOR] ); - Var *wsView = connectComp->getElement( RT_TEXCOORD ); - wsView->setName( "wsView" ); - wsView->setStructName( "OUT" ); - wsView->setType( "float3" ); - - // Get the input position. - Var *position = (Var*)LangElement::find( "inPosition" ); - if ( !position ) - position = (Var*)LangElement::find( "position" ); - - // Get the object to world transform. - Var *objTrans = (Var*) LangElement::find( "objTrans" ); - if ( !objTrans ) - { - objTrans = new Var; - objTrans->setType( "float4x4" ); - objTrans->setName( "objTrans" ); - objTrans->uniform = true; - objTrans->constSortPos = cspPrimitive; - } - - meta->addStatement( new GenOp( " @ = @ - mul( @, float4( @.xyz,1 ) ).xyz;\r\n", - wsView, eyePos, objTrans, position ) ); - - output = meta; - */ + // Nothing to do here... MFT_RTLighting should have + // taken care of passing everything to the pixel shader. } void PixelSpecularGLSL::processPix( Vector &componentList, const MaterialFeatureData &fd ) -{ - /* +{ AssertFatal( fd.features[MFT_RTLighting], "PixelSpecularHLSL requires RTLighting to be enabled!" ); - ShaderConnector *connectComp = dynamic_cast( componentList[C_CONNECTOR] ); + // RTLighting should have spit out the 4 specular + // powers for the 4 potential lights on this pass. + // + // This can sometimes be NULL if RTLighting skips out + // on us for lightmaps or missing normals. + Var *specular = (Var*)LangElement::find( "specular" ); + if ( !specular ) + return; MultiLine *meta = new MultiLine; - // Get the normal and light vectors from which the - // RTLighting feature should have already setup. - Var *wsNormal = (Var*)LangElement::find( "wsNormal" ); - Var *inLightVec = (Var*)LangElement::find( "inLightVec" ); - - // Grab the world space position to eye vector. - Var *wsView = connectComp->getElement( RT_TEXCOORD ); - wsView->setName( "wsView" ); - wsView->setStructName( "IN" ); - wsView->setType( "float3" ); - - // Get the specular power and color. - Var *specPow = new Var( "specularPower", "float" ); - specPow->uniform = true; - specPow->constSortPos = cspPass; - Var *specCol = (Var*)LangElement::find("specularColor"); - if(specCol == NULL) - { - specCol = new Var( "specularColor", "vec4" ); - specCol->uniform = true; - specCol->constSortPos = cspPass; - } - - // Calcuate the specular factor. - Var *specular = new Var( "specular", "float" ); - meta->addStatement( new GenOp( " @ = calcSpecular( -@, normalize( @ ), normalize( @ ), @ );\r\n", - new DecOp( specular ), inLightVec, wsNormal, wsView, specPow ) ); - - LangElement *specMul = new GenOp( "float4(@.rgb,0) * @", specCol, specular ); + LangElement *specMul = new GenOp( "@", specular ); LangElement *final = specMul; // mask out with lightmap if present - if( fd.features[MFT_LightMap] ) + if ( fd.features[MFT_LightMap] ) { LangElement *lmColor = NULL; @@ -141,37 +78,44 @@ void PixelSpecularGLSL::processPix( Vector &componentList, LangElement * lightMap = LangElement::find( "lightMap" ); LangElement * lmCoord = LangElement::find( "texCoord2" ); - lmColor = new GenOp( "tex2D(@, @)", lightMap, lmCoord ); + lmColor = new GenOp( "texture(@, @)", lightMap, lmCoord ); } - final = new GenOp( "@ * float4(@.rgb,0)", specMul, lmColor ); + final = new GenOp( "@ * vec4(@.rgb,0)", specMul, lmColor ); } - // We we have a normal map then mask the specular - if ( !fd.features[MFT_SpecularMap] && fd.features[MFT_NormalMap] ) + // If we have a normal map then mask the specular + if ( fd.features[MFT_SpecularMap] ) + { + Var *specularColor = (Var*)LangElement::find( "specularColor" ); + if (specularColor) + final = new GenOp( "@ * @", final, specularColor ); + } + else if ( fd.features[MFT_NormalMap] && !fd.features[MFT_IsDXTnm] ) { Var *bumpColor = (Var*)LangElement::find( "bumpNormal" ); final = new GenOp( "@ * @.a", final, bumpColor ); } - // Add the specular to the final color. - meta->addStatement( new GenOp( " @;\r\n", assignColor( final, Material::Add ) ) ); + // Add the specular to the final color. + // search for color var + Var *color = (Var*)LangElement::find( "col" ); + meta->addStatement( new GenOp( " @.rgb += ( @ ).rgb;\r\n", color, final ) ); output = meta; - */ } ShaderFeature::Resources PixelSpecularGLSL::getResources( const MaterialFeatureData &fd ) { Resources res; - res.numTexReg = 1; return res; } + void SpecularMapGLSL::processPix( Vector &componentList, const MaterialFeatureData &fd ) { // Get the texture coord. - Var *texCoord = getInTexCoord( "out_texCoord", "vec2", true, componentList ); + Var *texCoord = getInTexCoord( "texCoord", "vec2", true, componentList ); // create texture var Var *specularMap = new Var; @@ -180,7 +124,7 @@ void SpecularMapGLSL::processPix( Vector &componentList, const specularMap->uniform = true; specularMap->sampler = true; specularMap->constNum = Var::getTexUnitNum(); - LangElement *texOp = new GenOp( "texture2D(@, @)", specularMap, texCoord ); + LangElement *texOp = new GenOp( "texture(@, @)", specularMap, texCoord ); Var *specularColor = new Var( "specularColor", "vec4" ); @@ -203,6 +147,7 @@ void SpecularMapGLSL::setTexData( Material::StageData &stageDat, if ( tex ) { passData.mTexType[ texIndex ] = Material::Standard; + passData.mSamplerNames[ texIndex ] = "specularMap"; passData.mTexSlot[ texIndex++ ].texObject = tex; } } \ No newline at end of file diff --git a/Engine/source/shaderGen/GLSL/pixSpecularGLSL.h b/Engine/source/shaderGen/GLSL/pixSpecularGLSL.h index eb49b4504..2b7c92b95 100644 --- a/Engine/source/shaderGen/GLSL/pixSpecularGLSL.h +++ b/Engine/source/shaderGen/GLSL/pixSpecularGLSL.h @@ -53,7 +53,6 @@ public: } }; - /// A texture source for the PixSpecular feature class SpecularMapGLSL : public ShaderFeatureGLSL { @@ -75,5 +74,4 @@ public: } }; - -#endif // _PIXSPECULAR_GLSL_H_ \ No newline at end of file +#endif // _PIXSPECULAR_HLSL_H_ \ No newline at end of file diff --git a/Engine/source/shaderGen/GLSL/shaderCompGLSL.cpp b/Engine/source/shaderGen/GLSL/shaderCompGLSL.cpp index 7a476ff3b..faf5f92e1 100644 --- a/Engine/source/shaderGen/GLSL/shaderCompGLSL.cpp +++ b/Engine/source/shaderGen/GLSL/shaderCompGLSL.cpp @@ -38,7 +38,7 @@ Var * AppVertConnectorGLSL::getElement( RegisterType type, { Var *newVar = new Var; mElementList.push_back( newVar ); - newVar->setConnectName( "gl_Vertex" ); + newVar->setConnectName( "vPosition" ); return newVar; } @@ -46,28 +46,49 @@ Var * AppVertConnectorGLSL::getElement( RegisterType type, { Var *newVar = new Var; mElementList.push_back( newVar ); - newVar->setConnectName( "gl_Normal" ); + newVar->setConnectName( "vNormal" ); return newVar; } - + + case RT_BINORMAL: + { + Var *newVar = new Var; + mElementList.push_back( newVar ); + newVar->setConnectName( "vBinormal" ); + return newVar; + } case RT_COLOR: { Var *newVar = new Var; mElementList.push_back( newVar ); - newVar->setConnectName( "gl_Color" ); + newVar->setConnectName( "vColor" ); + return newVar; + } + + case RT_TANGENT: + { + Var *newVar = new Var; + mElementList.push_back( newVar ); + newVar->setConnectName( "vTangent" ); + return newVar; + } + + case RT_TANGENTW: + { + Var *newVar = new Var; + mElementList.push_back( newVar ); + newVar->setConnectName( "vTangentW" ); return newVar; } case RT_TEXCOORD: - case RT_BINORMAL: - case RT_TANGENT: { Var *newVar = new Var; mElementList.push_back( newVar ); char out[32]; - dSprintf( (char*)out, sizeof(out), "gl_MultiTexCoord%d", mCurTexElem ); + dSprintf( (char*)out, sizeof(out), "vTexCoord%d", mCurTexElem ); newVar->setConnectName( out ); newVar->constNum = mCurTexElem; newVar->arraySize = numElements; @@ -108,29 +129,55 @@ void AppVertConnectorGLSL::reset() mCurTexElem = 0; } -void AppVertConnectorGLSL::print( Stream &stream ) +void AppVertConnectorGLSL::print( Stream &stream, bool isVertexShader ) { - // print out elements + if(!isVertexShader) + return; + + U8 output[256]; + + // print struct + dSprintf( (char*)output, sizeof(output), "struct VertexData\r\n" ); + stream.write( dStrlen((char*)output), output ); + dSprintf( (char*)output, sizeof(output), "{\r\n" ); + stream.write( dStrlen((char*)output), output ); + for( U32 i=0; itype, "float")) - swizzle = "x"; - else if(!dStrcmp((const char*)var->type, "vec2")) - swizzle = "xy"; - else if(!dStrcmp((const char*)var->type, "vec3")) - swizzle = "xyz"; + + if( var->arraySize == 1) + { + dSprintf( (char*)output, sizeof(output), " %s %s;\r\n", var->type, (char*)var->name ); + stream.write( dStrlen((char*)output), output ); + } else - swizzle = "xyzw"; + { + dSprintf( (char*)output, sizeof(output), " %s %s[%d];\r\n", var->type, (char*)var->name, var->arraySize ); + stream.write( dStrlen((char*)output), output ); + } + } - // This is ugly. We use #defines to match user defined names with - // built in vars. There is no cleaner way to do this. - dSprintf( (char*)output, sizeof(output), "#define %s %s.%s\r\n", var->name, var->connectName, swizzle ); + dSprintf( (char*)output, sizeof(output), "} IN;\r\n\r\n" ); + stream.write( dStrlen((char*)output), output ); + // print in elements + for( U32 i=0; iarraySize; ++j) + { + const char *name = j == 0 ? var->connectName : avar("vTexCoord%d", var->constNum + j) ; + dSprintf( (char*)output, sizeof(output), "in %s %s;\r\n", var->type, name ); + stream.write( dStrlen((char*)output), output ); + } + + dSprintf( (char*)output, sizeof(output), "#define IN_%s IN.%s\r\n", var->name, var->name ); // TODO REMOVE stream.write( dStrlen((char*)output), output ); } + const char* newLine ="\r\n"; + stream.write( dStrlen((char*)newLine), newLine ); } Var * VertPixelConnectorGLSL::getElement( RegisterType type, @@ -140,14 +187,45 @@ Var * VertPixelConnectorGLSL::getElement( RegisterType type, switch( type ) { case RT_POSITION: + { + Var *newVar = new Var; + mElementList.push_back( newVar ); + newVar->setConnectName( "POSITION" ); + return newVar; + } + case RT_NORMAL: + { + Var *newVar = new Var; + mElementList.push_back( newVar ); + newVar->setConnectName( "NORMAL" ); + return newVar; + } + case RT_COLOR: { Var *newVar = new Var; mElementList.push_back( newVar ); + newVar->setConnectName( "COLOR" ); return newVar; } + /*case RT_BINORMAL: + { + Var *newVar = new Var; + mElementList.push_back( newVar ); + newVar->setConnectName( "BINORMAL" ); + return newVar; + } + + case RT_TANGENT: + { + Var *newVar = new Var; + mElementList.push_back( newVar ); + newVar->setConnectName( "TANGENT" ); + return newVar; + } */ + case RT_TEXCOORD: case RT_BINORMAL: case RT_TANGENT: @@ -155,6 +233,10 @@ Var * VertPixelConnectorGLSL::getElement( RegisterType type, Var *newVar = new Var; newVar->arraySize = numElements; + char out[32]; + dSprintf( (char*)out, sizeof(out), "TEXCOORD%d", mCurTexElem ); + newVar->setConnectName( out ); + if ( numRegisters != -1 ) mCurTexElem += numRegisters; else @@ -192,7 +274,7 @@ void VertPixelConnectorGLSL::reset() mCurTexElem = 0; } -void VertPixelConnectorGLSL::print( Stream &stream ) +void VertPixelConnectorGLSL::print( Stream &stream, bool isVerterShader ) { // print out elements for( U32 i=0; iarraySize <= 1) - dSprintf((char*)output, sizeof(output), "varying %s %s;\r\n", var->type, var->name); + dSprintf((char*)output, sizeof(output), "%s %s _%s_;\r\n", (isVerterShader ? "out" : "in"), var->type, var->connectName); else - dSprintf((char*)output, sizeof(output), "varying %s %s[%d];\r\n", var->type, var->name, var->arraySize); + dSprintf((char*)output, sizeof(output), "%s %s _%s_[%d];\r\n", (isVerterShader ? "out" : "in"),var->type, var->connectName, var->arraySize); stream.write( dStrlen((char*)output), output ); } + + printStructDefines(stream, !isVerterShader); } -void VertexParamsDefGLSL::print( Stream &stream ) +void VertPixelConnectorGLSL::printOnMain( Stream &stream, bool isVerterShader ) +{ + if(isVerterShader) + return; + + const char *newLine = "\r\n"; + const char *header = " //-------------------------\r\n"; + stream.write( dStrlen((char*)newLine), newLine ); + stream.write( dStrlen((char*)header), header ); + + // print out elements + for( U32 i=0; iname, "gl_Position")) + continue; + + dSprintf((char*)output, sizeof(output), " %s IN_%s = _%s_;\r\n", var->type, var->name, var->connectName); + + stream.write( dStrlen((char*)output), output ); + } + + stream.write( dStrlen((char*)header), header ); + stream.write( dStrlen((char*)newLine), newLine ); +} + + +void AppVertConnectorGLSL::printOnMain( Stream &stream, bool isVerterShader ) +{ + if(!isVerterShader) + return; + + const char *newLine = "\r\n"; + const char *header = " //-------------------------\r\n"; + stream.write( dStrlen((char*)newLine), newLine ); + stream.write( dStrlen((char*)header), header ); + + // print out elements + for( U32 i=0; iarraySize <= 1) + { + dSprintf((char*)output, sizeof(output), " IN.%s = %s;\r\n", var->name, var->connectName); + stream.write( dStrlen((char*)output), output ); + } + else + { + for(int j = 0; j < var->arraySize; ++j) + { + const char *name = j == 0 ? var->connectName : avar("vTexCoord%d", var->constNum + j) ; + dSprintf((char*)output, sizeof(output), " IN.%s[%d] = %s;\r\n", var->name, j, name ); + stream.write( dStrlen((char*)output), output ); + } + } + } + + stream.write( dStrlen((char*)header), header ); + stream.write( dStrlen((char*)newLine), newLine ); +} + + + + +Vector initDeprecadedDefines() +{ + Vector vec; + vec.push_back( "isBack"); + return vec; +} + +void VertPixelConnectorGLSL::printStructDefines( Stream &stream, bool in ) +{ + const char* connectionDir; + + if(in) + { + connectionDir = "IN"; + } + else + { + + connectionDir = "OUT"; + } + + static Vector deprecatedDefines = initDeprecadedDefines(); + + const char *newLine = "\r\n"; + const char *header = "// Struct defines\r\n"; + stream.write( dStrlen((char*)newLine), newLine ); + stream.write( dStrlen((char*)header), header ); + + // print out elements + for( U32 i=0; iname, "gl_Position")) + continue; + + if(!in) + { + dSprintf((char*)output, sizeof(output), "#define %s_%s _%s_\r\n", connectionDir, var->name, var->connectName); + stream.write( dStrlen((char*)output), output ); + } + + if( deprecatedDefines.contains((char*)var->name)) + continue; + + dSprintf((char*)output, sizeof(output), "#define %s %s_%s\r\n", var->name, connectionDir, var->name); + stream.write( dStrlen((char*)output), output ); + } + + stream.write( dStrlen((char*)newLine), newLine ); +} + +void VertexParamsDefGLSL::print( Stream &stream, bool isVerterShader ) { // find all the uniform variables and print them out for( U32 i=0; i(LangElement::elementList[i]); + if( var ) + { + if( var->uniform && !var->sampler) + { + U8 output[256]; + if(var->arraySize <= 1) + dSprintf((char*)output, sizeof(output), " %s %s = %s;\r\n", var->type, var->name, var->name); + else + dSprintf((char*)output, sizeof(output), " %s %s[%d] = %s;\r\n", var->type, var->name, var->arraySize, var->name); + + stream.write( dStrlen((char*)output), output ); + } + } + } } diff --git a/Engine/source/shaderGen/GLSL/shaderCompGLSL.h b/Engine/source/shaderGen/GLSL/shaderCompGLSL.h index 5b306c0c8..12cd4ae93 100644 --- a/Engine/source/shaderGen/GLSL/shaderCompGLSL.h +++ b/Engine/source/shaderGen/GLSL/shaderCompGLSL.h @@ -40,7 +40,10 @@ public: virtual void reset(); virtual void sortVars(); - virtual void print( Stream &stream ); + virtual void print( Stream &stream) {} // TODO OPENGL temporal fix for dedicated build on Linux + virtual void print( Stream &stream, bool isVerterShader ); + void printStructDefines( Stream &stream, bool in ); + virtual void printOnMain( Stream &stream, bool isVerterShader ); }; class AppVertConnectorGLSL : public ShaderConnector @@ -53,21 +56,23 @@ public: virtual void reset(); virtual void sortVars(); - virtual void print( Stream &stream ); + virtual void print( Stream &stream) {} // TODO OPENGL temporal fix for dedicated build on Linux + virtual void print( Stream &stream, bool isVerterShader ); + virtual void printOnMain( Stream &stream, bool isVerterShader ); }; class VertexParamsDefGLSL : public ParamsDef { public: - virtual void print( Stream &stream ); + virtual void print( Stream &stream, bool isVerterShader ); }; class PixelParamsDefGLSL : public ParamsDef { public: - virtual void print( Stream &stream ); + virtual void print( Stream &stream, bool isVerterShader ); }; -#endif // _SHADERCOMP_GLSL_H_ \ No newline at end of file +#endif // _SHADERCOMP_GLSL_H_ diff --git a/Engine/source/shaderGen/GLSL/shaderFeatureGLSL.cpp b/Engine/source/shaderGen/GLSL/shaderFeatureGLSL.cpp index 0e0c1ac46..c8942f454 100644 --- a/Engine/source/shaderGen/GLSL/shaderFeatureGLSL.cpp +++ b/Engine/source/shaderGen/GLSL/shaderFeatureGLSL.cpp @@ -41,26 +41,37 @@ LangElement * ShaderFeatureGLSL::setupTexSpaceMat( Vector &, / Var *B = (Var*) LangElement::find( "B" ); Var *T = (Var*) LangElement::find( "T" ); + Var *tangentW = (Var*) LangElement::find( "tangentW" ); + // setup matrix var *texSpaceMat = new Var; - (*texSpaceMat)->setType( "mat3" ); + (*texSpaceMat)->setType( "float3x3" ); (*texSpaceMat)->setName( "objToTangentSpace" ); MultiLine * meta = new MultiLine; + meta->addStatement( new GenOp( " @;\r\n", new DecOp( *texSpaceMat ) ) ); - // Recreate the binormal if we don't have one. - if ( !B ) + // Protect against missing normal and tangent. + if ( !N || !T ) { - B = new Var; - B->setType( "vec3" ); - B->setName( "B" ); - meta->addStatement( new GenOp( " @ = cross( @, normalize(@) );\r\n", new DecOp( B ), T, N ) ); + meta->addStatement( new GenOp( " tSetMatrixRow(@, 0, float3( 1, 0, 0 )); tSetMatrixRow(@, 1,float3( 0, 1, 0 )); tSetMatrixRow(@,2, float3( 0, 0, 1 ));\r\n", + *texSpaceMat, *texSpaceMat, *texSpaceMat ) ); + return meta; } - meta->addStatement( new GenOp( " @;\r\n", new DecOp( *texSpaceMat ) ) ); - meta->addStatement( new GenOp( " @[0] = vec3(@.x, @.x, normalize(@).x);\r\n", *texSpaceMat, T, B, N ) ); - meta->addStatement( new GenOp( " @[1] = vec3(@.y, @.y, normalize(@).y);\r\n", *texSpaceMat, T, B, N ) ); - meta->addStatement( new GenOp( " @[2] = vec3(@.z, @.z, normalize(@).z);\r\n", *texSpaceMat, T, B, N ) ); + meta->addStatement( new GenOp( " tSetMatrixRow(@, 0, @);\r\n", *texSpaceMat, T ) ); + if ( B ) + meta->addStatement( new GenOp( " tSetMatrixRow(@, 1, @);\r\n", *texSpaceMat, B ) ); + else + { + if(dStricmp((char*)T->type, "vec4") == 0) + meta->addStatement( new GenOp( " tSetMatrixRow(@, 1, cross( @, normalize(@) ) * @.w);\r\n", *texSpaceMat, T, N, T ) ); + else if(tangentW) + meta->addStatement( new GenOp( " tSetMatrixRow(@, 1, cross( @, normalize(@) ) * @);\r\n", *texSpaceMat, T, N, tangentW ) ); + else + meta->addStatement( new GenOp( " tSetMatrixRow(@, 1, cross( @, normalize(@) ));\r\n", *texSpaceMat, T, N ) ); + } + meta->addStatement( new GenOp( " tSetMatrixRow(@, 2, normalize(@));\r\n", *texSpaceMat, N ) ); return meta; } @@ -107,7 +118,7 @@ LangElement* ShaderFeatureGLSL::assignColor( LangElement *elem, case Material::LerpAlpha: if ( !lerpElem ) lerpElem = elem; - assign = new GenOp( "@.rgb = mix( @.rgb, (@).rgb, (@).a )", color, elem, color, lerpElem ); + assign = new GenOp( "@.rgb = lerp( @.rgb, (@).rgb, (@).a )", color, color, elem, lerpElem ); break; case Material::ToneMap: @@ -136,10 +147,19 @@ LangElement *ShaderFeatureGLSL::expandNormalMap( LangElement *sampleNormalOp, if ( fd.features.hasFeature( MFT_IsDXTnm, getProcessIndex() ) ) { + if ( fd.features[MFT_ImposterVert] ) + { + // The imposter system uses object space normals and + // encodes them with the z axis in the alpha component. + meta->addStatement( new GenOp( " @ = float4( normalize( @.xyw * 2.0 - 1.0 ), 0.0 ); // Obj DXTnm\r\n", normalDecl, sampleNormalOp ) ); + } + else + { // DXT Swizzle trick - meta->addStatement( new GenOp( " @ = vec4( @.ag * 2.0 - 1.0, 0.0, 0.0 ); // DXTnm\r\n", normalDecl, sampleNormalOp ) ); + meta->addStatement( new GenOp( " @ = float4( @.ag * 2.0 - 1.0, 0.0, 0.0 ); // DXTnm\r\n", normalDecl, sampleNormalOp ) ); meta->addStatement( new GenOp( " @.z = sqrt( 1.0 - dot( @.xy, @.xy ) ); // DXTnm\r\n", normalVar, normalVar, normalVar ) ); } + } else { meta->addStatement( new GenOp( " @ = @;\r\n", normalDecl, sampleNormalOp ) ); @@ -165,6 +185,18 @@ Var * ShaderFeatureGLSL::getVertTexCoord( const String &name ) inTex = dynamic_cast( LangElement::elementList[i] ); if ( inTex ) { + // NOTE: This used to do this check... + // + // dStrcmp( (char*)inTex->structName, "IN" ) + // + // ... to ensure that the var was from the input + // vertex structure, but this kept some features + // ( ie. imposter vert ) from decoding their own + // coords for other features to use. + // + // If we run into issues with collisions between + // IN vars and local vars we may need to revise. + break; } } @@ -201,7 +233,7 @@ Var* ShaderFeatureGLSL::getOutWorldToTangent( Vector &compon { // turn obj->tangent into world->tangent worldToTangent = new Var; - worldToTangent->setType( "mat3x3" ); + worldToTangent->setType( "float3x3" ); worldToTangent->setName( "worldToTangent" ); LangElement *worldToTangentDecl = new DecOp( worldToTangent ); @@ -211,16 +243,29 @@ Var* ShaderFeatureGLSL::getOutWorldToTangent( Vector &compon { worldToObj = new Var; worldToObj->setName( "worldToObj" ); - worldToObj->setType( "mat4x4" ); + + if ( fd.features[MFT_UseInstancing] ) + { + // We just use transpose to convert the 3x3 portion of + // the object transform to its inverse. + worldToObj->setType( "float3x3" ); + Var *objTrans = getObjTrans( componentList, true, meta ); + meta->addStatement( new GenOp( " @ = transpose( float3x3(@) ); // Instancing!\r\n", new DecOp( worldToObj ), objTrans ) ); + } + else + { + worldToObj->setType( "float4x4" ); worldToObj->uniform = true; worldToObj->constSortPos = cspPrimitive; } + } // assign world->tangent transform - meta->addStatement( new GenOp( " @ = @ * mat3x3( @[0].xyz, @[1].xyz, @[2].xyz );\r\n", worldToTangentDecl, texSpaceMat, worldToObj, worldToObj, worldToObj ) ); + meta->addStatement( new GenOp( " @ = tMul( @, float3x3(@) );\r\n", worldToTangentDecl, texSpaceMat, worldToObj ) ); } else { + // Assume particle normal generation has set this up in the proper space worldToTangent = texSpaceMat; } } @@ -230,13 +275,14 @@ Var* ShaderFeatureGLSL::getOutWorldToTangent( Vector &compon outWorldToTangent = connectComp->getElement( RT_TEXCOORD, 1, 3 ); outWorldToTangent->setName( "outWorldToTangent" ); - outWorldToTangent->setType( "mat3x3" ); + outWorldToTangent->setStructName( "OUT" ); + outWorldToTangent->setType( "float3x3" ); meta->addStatement( new GenOp( " @ = @;\r\n", outWorldToTangent, worldToTangent ) ); return outWorldToTangent; } -Var* ShaderFeatureGLSL::getOutViewToTangent( Vector &componentList, +Var* ShaderFeatureGLSL::getOutViewToTangent( Vector &componentList, MultiLine *meta, const MaterialFeatureData &fd ) { @@ -247,14 +293,14 @@ Var* ShaderFeatureGLSL::getOutViewToTangent( Vector &compone Var *viewToTangent = (Var*)LangElement::find( "viewToTangent" ); if ( !viewToTangent ) { + Var *texSpaceMat = getOutObjToTangentSpace( componentList, meta, fd ); if(!fd.features[MFT_ParticleNormal]) { - // turn obj->tangent into world->tangent viewToTangent = new Var; - viewToTangent->setType( "mat3" ); + viewToTangent->setType( "float3x3" ); viewToTangent->setName( "viewToTangent" ); LangElement *viewToTangentDecl = new DecOp( viewToTangent ); @@ -262,11 +308,7 @@ Var* ShaderFeatureGLSL::getOutViewToTangent( Vector &compone Var *viewToObj = getInvWorldView( componentList, fd.features[MFT_UseInstancing], meta ); // assign world->tangent transform - meta->addStatement( new GenOp( " mat3 mat3ViewToObj;\r\n" ) ); - meta->addStatement( new GenOp( " mat3ViewToObj[0] = @[0].xyz;\r\n", viewToObj ) ); - meta->addStatement( new GenOp( " mat3ViewToObj[1] = @[1].xyz;\r\n", viewToObj ) ); - meta->addStatement( new GenOp( " mat3ViewToObj[2] = @[2].xyz;\r\n", viewToObj ) ); - meta->addStatement( new GenOp( " @ = @ * mat3ViewToObj;\r\n", viewToTangentDecl, texSpaceMat ) ); + meta->addStatement( new GenOp( " @ = tMul( (@), float3x3(@) );\r\n", viewToTangentDecl, texSpaceMat, viewToObj ) ); } else { @@ -280,7 +322,8 @@ Var* ShaderFeatureGLSL::getOutViewToTangent( Vector &compone outViewToTangent = connectComp->getElement( RT_TEXCOORD, 1, 3 ); outViewToTangent->setName( "outViewToTangent" ); - outViewToTangent->setType( "mat3" ); + outViewToTangent->setStructName( "OUT" ); + outViewToTangent->setType( "float3x3" ); meta->addStatement( new GenOp( " @ = @;\r\n", outViewToTangent, viewToTangent ) ); return outViewToTangent; @@ -304,6 +347,7 @@ Var* ShaderFeatureGLSL::getOutTexCoord( const char *name, texCoord = connectComp->getElement( RT_TEXCOORD ); texCoord->setName( outTexName ); + texCoord->setStructName( "OUT" ); texCoord->setType( type ); texCoord->mapsToSampler = mapsToSampler; @@ -313,21 +357,21 @@ Var* ShaderFeatureGLSL::getOutTexCoord( const char *name, // create texture mat var Var *texMat = new Var; - texMat->setType( "mat4" ); + texMat->setType( "float4x4" ); texMat->setName( "texMat" ); texMat->uniform = true; texMat->constSortPos = cspPass; // Statement allows for casting of different types which // eliminates vector truncation problems. - String statement = String::ToString( " @ = %s(@ * @);\r\n", type ); + String statement = String::ToString( " @ = %s(tMul(@, @));\r\n", type ); meta->addStatement( new GenOp( statement , texCoord, texMat, inTex ) ); } else { // Statement allows for casting of different types which // eliminates vector truncation problems. - String statement = String::ToString( " @ = %s(@);\r\n", type ); + String statement = String::ToString( " @ = %s(@);\r\n", type ); meta->addStatement( new GenOp( statement, texCoord, inTex ) ); } } @@ -349,6 +393,7 @@ Var* ShaderFeatureGLSL::getInTexCoord( const char *name, ShaderConnector *connectComp = dynamic_cast( componentList[C_CONNECTOR] ); texCoord = connectComp->getElement( RT_TEXCOORD ); texCoord->setName( name ); + texCoord->setStructName( "IN" ); texCoord->setType( type ); texCoord->mapsToSampler = mapsToSampler; } @@ -359,15 +404,97 @@ Var* ShaderFeatureGLSL::getInTexCoord( const char *name, return texCoord; } +Var* ShaderFeatureGLSL::getInColor( const char *name, + const char *type, + Vector &componentList ) +{ + Var *inColor = (Var*)LangElement::find( name ); + if ( !inColor ) + { + ShaderConnector *connectComp = dynamic_cast( componentList[C_CONNECTOR] ); + inColor = connectComp->getElement( RT_COLOR ); + inColor->setName( name ); + inColor->setStructName( "IN" ); + inColor->setType( type ); + } + + AssertFatal( dStrcmp( type, (const char*)inColor->type ) == 0, + "ShaderFeatureGLSL::getInColor - Type mismatch!" ); + + return inColor; +} + +Var* ShaderFeatureGLSL::addOutVpos( MultiLine *meta, + Vector &componentList ) +{ + /* + // Nothing to do if we're on SM 3.0... we use the real vpos. + if ( GFX->getPixelShaderVersion() >= 3.0f ) + return NULL; + */ + + // For SM 2.x we need to generate the vpos in the vertex shader + // and pass it as a texture coord to the pixel shader. + + Var *outVpos = (Var*)LangElement::find( "outVpos" ); + if ( !outVpos ) + { + ShaderConnector *connectComp = dynamic_cast( componentList[C_CONNECTOR] ); + + outVpos = connectComp->getElement( RT_TEXCOORD ); + outVpos->setName( "outVpos" ); + outVpos->setStructName( "OUT" ); + outVpos->setType( "vec4" ); + outVpos->mapsToSampler = false; + + Var *outPosition = (Var*) LangElement::find( "gl_Position" ); + AssertFatal( outPosition, "ShaderFeatureGLSL::addOutVpos - Didn't find the output position." ); + + meta->addStatement( new GenOp( " @ = @;\r\n", outVpos, outPosition ) ); + } + + return outVpos; +} + +Var* ShaderFeatureGLSL::getInVpos( MultiLine *meta, + Vector &componentList ) +{ + Var *inVpos = (Var*)LangElement::find( "vpos" ); + if ( inVpos ) + return inVpos; + + ShaderConnector *connectComp = dynamic_cast( componentList[C_CONNECTOR] ); + /* + if ( GFX->getPixelShaderVersion() >= 3.0f ) + { + inVpos = connectComp->getElement( RT_VPOS ); + inVpos->setName( "vpos" ); + inVpos->setStructName( "IN" ); + inVpos->setType( "vec2" ); + return inVpos; + } + */ + inVpos = connectComp->getElement( RT_TEXCOORD ); + inVpos->setName( "inVpos" ); + inVpos->setStructName( "IN" ); + inVpos->setType( "vec4" ); + + Var *vpos = new Var( "vpos", "vec2" ); + meta->addStatement( new GenOp( " @ = @.xy / @.w;\r\n", new DecOp( vpos ), inVpos, inVpos ) ); + + return vpos; +} + Var* ShaderFeatureGLSL::getInWorldToTangent( Vector &componentList ) { - Var *worldToTangent = (Var*)LangElement::find( "outWorldToTangent" ); + Var *worldToTangent = (Var*)LangElement::find( "worldToTangent" ); if ( !worldToTangent ) { ShaderConnector *connectComp = dynamic_cast( componentList[C_CONNECTOR] ); worldToTangent = connectComp->getElement( RT_TEXCOORD, 1, 3 ); - worldToTangent->setName( "outWorldToTangent" ); - worldToTangent->setType( "mat3x3" ); + worldToTangent->setName( "worldToTangent" ); + worldToTangent->setStructName( "IN" ); + worldToTangent->setType( "float3x3" ); } return worldToTangent; @@ -375,13 +502,14 @@ Var* ShaderFeatureGLSL::getInWorldToTangent( Vector &component Var* ShaderFeatureGLSL::getInViewToTangent( Vector &componentList ) { - Var *viewToTangent = (Var*)LangElement::find( "outViewToTangent" ); + Var *viewToTangent = (Var*)LangElement::find( "viewToTangent" ); if ( !viewToTangent ) { ShaderConnector *connectComp = dynamic_cast( componentList[C_CONNECTOR] ); viewToTangent = connectComp->getElement( RT_TEXCOORD, 1, 3 ); - viewToTangent->setName( "outViewToTangent" ); - viewToTangent->setType( "mat3" ); + viewToTangent->setName( "viewToTangent" ); + viewToTangent->setStructName( "IN" ); + viewToTangent->setType( "float3x3" ); } return viewToTangent; @@ -403,16 +531,43 @@ Var* ShaderFeatureGLSL::getNormalMapTex() return normalMap; } -Var* ShaderFeatureGLSL::getObjTrans( Vector &componentList, +Var* ShaderFeatureGLSL::getObjTrans( Vector &componentList, bool useInstancing, MultiLine *meta ) { - Var *objTrans = (Var*) LangElement::find( "objTrans" ); if ( objTrans ) + Var *objTrans = (Var*)LangElement::find( "objTrans" ); + if ( objTrans ) return objTrans; - objTrans = new Var; objTrans->setType( "mat4x4" ); + + if ( useInstancing ) + { + ShaderConnector *vertStruct = dynamic_cast( componentList[C_VERT_STRUCT] ); + Var *instObjTrans = vertStruct->getElement( RT_TEXCOORD, 4, 4 ); + instObjTrans->setStructName( "IN" ); + instObjTrans->setName( "inst_objectTrans" ); + + mInstancingFormat->addElement( "objTrans", GFXDeclType_Float4, instObjTrans->constNum+0 ); + mInstancingFormat->addElement( "objTrans", GFXDeclType_Float4, instObjTrans->constNum+1 ); + mInstancingFormat->addElement( "objTrans", GFXDeclType_Float4, instObjTrans->constNum+2 ); + mInstancingFormat->addElement( "objTrans", GFXDeclType_Float4, instObjTrans->constNum+3 ); + + objTrans = new Var; + objTrans->setType( "mat4x4" ); + objTrans->setName( "objTrans" ); + meta->addStatement( new GenOp( " @ = mat4x4( // Instancing!\r\n", new DecOp( objTrans ), instObjTrans ) ); + meta->addStatement( new GenOp( " @[0],\r\n", instObjTrans ) ); + meta->addStatement( new GenOp( " @[1],\r\n", instObjTrans ) ); + meta->addStatement( new GenOp( " @[2],\r\n",instObjTrans ) ); + meta->addStatement( new GenOp( " @[3] );\r\n", instObjTrans ) ); + } + else + { + objTrans = new Var; + objTrans->setType( "float4x4" ); objTrans->setName( "objTrans" ); objTrans->uniform = true; objTrans->constSortPos = cspPrimitive; + } return objTrans; } @@ -425,12 +580,33 @@ Var* ShaderFeatureGLSL::getModelView( Vector &componentList, if ( modelview ) return modelview; - // create modelview variable + if ( useInstancing ) + { + Var *objTrans = getObjTrans( componentList, useInstancing, meta ); + + Var *viewProj = (Var*)LangElement::find( "viewProj" ); + if ( !viewProj ) + { + viewProj = new Var; + viewProj->setType( "float4x4" ); + viewProj->setName( "viewProj" ); + viewProj->uniform = true; + viewProj->constSortPos = cspPass; + } + modelview = new Var; - modelview->setType( "mat4" ); + modelview->setType( "float4x4" ); + modelview->setName( "modelview" ); + meta->addStatement( new GenOp( " @ = tMul( @, @ ); // Instancing!\r\n", new DecOp( modelview ), viewProj, objTrans ) ); + } + else + { + modelview = new Var; + modelview->setType( "float4x4" ); modelview->setName( "modelview" ); modelview->uniform = true; modelview->constSortPos = cspPrimitive; + } return modelview; } @@ -443,15 +619,39 @@ Var* ShaderFeatureGLSL::getWorldView( Vector &componentList, if ( worldView ) return worldView; + if ( useInstancing ) + { + Var *objTrans = getObjTrans( componentList, useInstancing, meta ); + + Var *worldToCamera = (Var*)LangElement::find( "worldToCamera" ); + if ( !worldToCamera ) + { + worldToCamera = new Var; + worldToCamera->setType( "float4x4" ); + worldToCamera->setName( "worldToCamera" ); + worldToCamera->uniform = true; + worldToCamera->constSortPos = cspPass; + } + + worldView = new Var; + worldView->setType( "float4x4" ); + worldView->setName( "worldViewOnly" ); + + meta->addStatement( new GenOp( " @ = tMul( @, @ ); // Instancing!\r\n", new DecOp( worldView ), worldToCamera, objTrans ) ); + } + else + { worldView = new Var; - worldView->setType( "mat4x4" ); + worldView->setType( "float4x4" ); worldView->setName( "worldViewOnly" ); worldView->uniform = true; worldView->constSortPos = cspPrimitive; + } return worldView; } + Var* ShaderFeatureGLSL::getInvWorldView( Vector &componentList, bool useInstancing, MultiLine *meta ) @@ -460,11 +660,27 @@ Var* ShaderFeatureGLSL::getInvWorldView( Vector &componentLis if ( viewToObj ) return viewToObj; + if ( useInstancing ) + { + Var *worldView = getWorldView( componentList, useInstancing, meta ); + + viewToObj = new Var; + viewToObj->setType( "float3x3" ); + viewToObj->setName( "viewToObj" ); + + // We just use transpose to convert the 3x3 portion + // of the world view transform into its inverse. + + meta->addStatement( new GenOp( " @ = transpose( float3x3(@) ); // Instancing!\r\n", new DecOp( viewToObj ), worldView ) ); + } + else + { viewToObj = new Var; - viewToObj->setType( "mat4" ); + viewToObj->setType( "float4x4" ); viewToObj->setName( "viewToObj" ); viewToObj->uniform = true; viewToObj->constSortPos = cspPrimitive; + } return viewToObj; } @@ -491,7 +707,7 @@ void ShaderFeatureGLSL::getWsPosition( Vector &componentList, Var *objTrans = getObjTrans( componentList, useInstancing, meta ); - meta->addStatement( new GenOp( " @ = ( @ * vec4( @.xyz, 1 ) ).xyz;\r\n", + meta->addStatement( new GenOp( " @ = tMul( @, float4( @.xyz, 1 ) ).xyz;\r\n", wsPosition, objTrans, inPosition ) ); } @@ -505,6 +721,7 @@ Var* ShaderFeatureGLSL::addOutWsPosition( Vector &componentLis ShaderConnector *connectComp = dynamic_cast( componentList[C_CONNECTOR] ); outWsPosition = connectComp->getElement( RT_TEXCOORD ); outWsPosition->setName( "outWsPosition" ); + outWsPosition->setStructName( "OUT" ); outWsPosition->setType( "vec3" ); outWsPosition->mapsToSampler = false; @@ -516,12 +733,13 @@ Var* ShaderFeatureGLSL::addOutWsPosition( Vector &componentLis Var* ShaderFeatureGLSL::getInWsPosition( Vector &componentList ) { - Var *wsPosition = (Var*)LangElement::find( "outWsPosition" ); + Var *wsPosition = (Var*)LangElement::find( "wsPosition" ); if ( !wsPosition ) { ShaderConnector *connectComp = dynamic_cast( componentList[C_CONNECTOR] ); wsPosition = connectComp->getElement( RT_TEXCOORD ); - wsPosition->setName( "outWsPosition" ); + wsPosition->setName( "wsPosition" ); + wsPosition->setStructName( "IN" ); wsPosition->setType( "vec3" ); } @@ -566,7 +784,7 @@ Var* ShaderFeatureGLSL::addOutDetailTexCoord( Vector &compon // create detail variable Var *detScale = new Var; - detScale->setType( "vec2" ); + detScale->setType( "vec2" ); detScale->setName( "detailScale" ); detScale->uniform = true; detScale->constSortPos = cspPotentialPrimitive; @@ -575,25 +793,26 @@ Var* ShaderFeatureGLSL::addOutDetailTexCoord( Vector &compon ShaderConnector *connectComp = dynamic_cast( componentList[C_CONNECTOR] ); outTex = connectComp->getElement( RT_TEXCOORD ); outTex->setName( "detCoord" ); - outTex->setType( "vec2" ); + outTex->setStructName( "OUT" ); + outTex->setType( "vec2" ); outTex->mapsToSampler = true; if ( useTexAnim ) { - inTex->setType( "vec4" ); + inTex->setType( "vec4" ); // Find or create the texture matrix. Var *texMat = (Var*)LangElement::find( "texMat" ); if ( !texMat ) { texMat = new Var; - texMat->setType( "mat4x4" ); + texMat->setType( "float4x4" ); texMat->setName( "texMat" ); texMat->uniform = true; texMat->constSortPos = cspPass; } - meta->addStatement( new GenOp( " @ = (@ * @) * @;\r\n", outTex, texMat, inTex, detScale ) ); + meta->addStatement( new GenOp( " @ = tMul(@, @) * @;\r\n", outTex, texMat, inTex, detScale ) ); } else { @@ -608,7 +827,7 @@ Var* ShaderFeatureGLSL::addOutDetailTexCoord( Vector &compon // Base Texture //**************************************************************************** -void DiffuseMapFeatGLSL::processVert( Vector &componentList, +void DiffuseMapFeatGLSL::processVert( Vector &componentList, const MaterialFeatureData &fd ) { MultiLine *meta = new MultiLine; @@ -625,7 +844,7 @@ void DiffuseMapFeatGLSL::processPix( Vector &componentList, const MaterialFeatureData &fd ) { // grab connector texcoord register - Var *inTex = getInTexCoord( "out_texCoord", "vec2", true, componentList ); + Var *inTex = getInTexCoord( "texCoord", "vec2", true, componentList ); // create texture var Var *diffuseMap = new Var; @@ -645,7 +864,7 @@ void DiffuseMapFeatGLSL::processPix( Vector &componentList, diffColor->setName( "diffuseColor" ); LangElement *colorDecl = new DecOp( diffColor ); - meta->addStatement( new GenOp( " @ = texture2D(@, @);\r\n", + meta->addStatement( new GenOp( " @ = tex2D(@, @);\r\n", colorDecl, diffuseMap, inTex ) ); @@ -662,19 +881,19 @@ void DiffuseMapFeatGLSL::processPix( Vector &componentList, Var *atlasedTex = new Var; atlasedTex->setName("atlasedTexCoord"); - atlasedTex->setType("float2"); + atlasedTex->setType("vec2"); LangElement *atDecl = new DecOp(atlasedTex); // Parameters of the texture atlas Var *atParams = new Var; - atParams->setType("float4"); + atParams->setType("vec4"); atParams->setName("diffuseAtlasParams"); atParams->uniform = true; atParams->constSortPos = cspPotentialPrimitive; // Parameters of the texture (tile) this object is using in the atlas Var *tileParams = new Var; - tileParams->setType("float4"); + tileParams->setType("vec4"); tileParams->setName("diffuseAtlasTileParams"); tileParams->uniform = true; tileParams->constSortPos = cspPotentialPrimitive; @@ -683,24 +902,24 @@ void DiffuseMapFeatGLSL::processPix( Vector &componentList, if(is_sm3) { // Figure out the mip level - meta->addStatement(new GenOp(" vec2 _dx = ddx(@ * @.z);\r\n", inTex, atParams)); - meta->addStatement(new GenOp(" vec2 _dy = ddy(@ * @.z);\r\n", inTex, atParams)); + meta->addStatement(new GenOp(" float2 _dx = ddx(@ * @.z);\r\n", inTex, atParams)); + meta->addStatement(new GenOp(" float2 _dy = ddy(@ * @.z);\r\n", inTex, atParams)); meta->addStatement(new GenOp(" float mipLod = 0.5 * log2(max(dot(_dx, _dx), dot(_dy, _dy)));\r\n")); meta->addStatement(new GenOp(" mipLod = clamp(mipLod, 0.0, @.w);\r\n", atParams)); // And the size of the mip level meta->addStatement(new GenOp(" float mipPixSz = pow(2.0, @.w - mipLod);\r\n", atParams)); - meta->addStatement(new GenOp(" vec2 mipSz = mipPixSz / @.xy;\r\n", atParams)); + meta->addStatement(new GenOp(" float2 mipSz = mipPixSz / @.xy;\r\n", atParams)); } else { - meta->addStatement(new GenOp(" vec2 mipSz = float2(1.0, 1.0);\r\n")); + meta->addStatement(new GenOp(" float2 mipSz = float2(1.0, 1.0);\r\n")); } // Tiling mode // TODO: Select wrap or clamp somehow if( true ) // Wrap - meta->addStatement(new GenOp(" @ = fract(@);\r\n", atDecl, inTex)); + meta->addStatement(new GenOp(" @ = frac(@);\r\n", atDecl, inTex)); else // Clamp meta->addStatement(new GenOp(" @ = saturate(@);\r\n", atDecl, inTex)); @@ -724,7 +943,7 @@ void DiffuseMapFeatGLSL::processPix( Vector &componentList, #ifdef DEBUG_ATLASED_UV_COORDS if(!fd.features[MFT_PrePassConditioner]) { - meta->addStatement(new GenOp(" @ = vec4(@.xy, mipLod / @.w, 1.0);\r\n", new DecOp(diffColor), inTex, atParams)); + meta->addStatement(new GenOp(" @ = float4(@.xy, mipLod / @.w, 1.0);\r\n", new DecOp(diffColor), inTex, atParams)); meta->addStatement(new GenOp(" @; return OUT;\r\n", assignColor(diffColor, Material::Mul))); return; } @@ -732,12 +951,12 @@ void DiffuseMapFeatGLSL::processPix( Vector &componentList, if(is_sm3) { - meta->addStatement(new GenOp( " @ = texture2Dlod(@, float4(@, 0.0, mipLod));\r\n", + meta->addStatement(new GenOp( " @ = tex2Dlod(@, float4(@, 0.0, mipLod));\r\n", new DecOp(diffColor), diffuseMap, inTex)); } else { - meta->addStatement(new GenOp( " @ = texture2D(@, @);\r\n", + meta->addStatement(new GenOp( " @ = tex2D(@, @);\r\n", new DecOp(diffColor), diffuseMap, inTex)); } @@ -745,7 +964,7 @@ void DiffuseMapFeatGLSL::processPix( Vector &componentList, } else { - LangElement *statement = new GenOp( "texture2D(@, @)", diffuseMap, inTex ); + LangElement *statement = new GenOp( "tex2D(@, @)", diffuseMap, inTex ); output = new GenOp( " @;\r\n", assignColor( statement, Material::Mul ) ); } @@ -767,7 +986,10 @@ void DiffuseMapFeatGLSL::setTexData( Material::StageData &stageDat, { GFXTextureObject *tex = stageDat.getTex( MFT_DiffuseMap ); if ( tex ) + { + passData.mSamplerNames[ texIndex ] = "diffuseMap"; passData.mTexSlot[ texIndex++ ].texObject = tex; + } } @@ -785,6 +1007,7 @@ void OverlayTexFeatGLSL::processVert( Vector &componentList, ShaderConnector *connectComp = dynamic_cast( componentList[C_CONNECTOR] ); Var *outTex = connectComp->getElement( RT_TEXCOORD ); outTex->setName( "outTexCoord2" ); + outTex->setStructName( "OUT" ); outTex->setType( "vec2" ); outTex->mapsToSampler = true; @@ -797,13 +1020,13 @@ void OverlayTexFeatGLSL::processVert( Vector &componentList, if ( !texMat ) { texMat = new Var; - texMat->setType( "mat4x4" ); + texMat->setType( "float4x4" ); texMat->setName( "texMat" ); texMat->uniform = true; texMat->constSortPos = cspPass; } - output = new GenOp( " @ = @ * @;\r\n", outTex, texMat, inTex ); + output = new GenOp( " @ = tMul(@, @);\r\n", outTex, texMat, inTex ); return; } @@ -818,7 +1041,8 @@ void OverlayTexFeatGLSL::processPix( Vector &componentList, // grab connector texcoord register ShaderConnector *connectComp = dynamic_cast( componentList[C_CONNECTOR] ); Var *inTex = connectComp->getElement( RT_TEXCOORD ); - inTex->setName( "outTexCoord2" ); + inTex->setName( "texCoord2" ); + inTex->setStructName( "IN" ); inTex->setType( "vec2" ); inTex->mapsToSampler = true; @@ -830,7 +1054,7 @@ void OverlayTexFeatGLSL::processPix( Vector &componentList, diffuseMap->sampler = true; diffuseMap->constNum = Var::getTexUnitNum(); // used as texture unit num here - LangElement *statement = new GenOp( "texture2D(@, @)", diffuseMap, inTex ); + LangElement *statement = new GenOp( "tex2D(@, @)", diffuseMap, inTex ); output = new GenOp( " @;\r\n", assignColor( statement, Material::LerpAlpha ) ); } @@ -899,6 +1123,7 @@ void DiffuseVertColorFeatureGLSL::processVert( Vector< ShaderComponent* >& comp AssertFatal( connectComp, "DiffuseVertColorFeatureGLSL::processVert - C_CONNECTOR is not a ShaderConnector" ); Var* outColor = connectComp->getElement( RT_COLOR ); outColor->setName( "vertColor" ); + outColor->setStructName( "OUT" ); outColor->setType( "vec4" ); output = new GenOp( " @ = @;\r\n", outColor, inColor ); @@ -917,6 +1142,7 @@ void DiffuseVertColorFeatureGLSL::processPix( Vector &compon AssertFatal( connectComp, "DiffuseVertColorFeatureGLSL::processVert - C_CONNECTOR is not a ShaderConnector" ); vertColor = connectComp->getElement( RT_COLOR ); vertColor->setName( "vertColor" ); + vertColor->setStructName( "IN" ); vertColor->setType( "vec4" ); } @@ -934,12 +1160,13 @@ void LightmapFeatGLSL::processVert( Vector &componentList, const MaterialFeatureData &fd ) { // grab tex register from incoming vert - Var *inTex = (Var*) LangElement::find( "texCoord2" ); + Var *inTex = getVertTexCoord( "texCoord2" ); // grab connector texcoord register ShaderConnector *connectComp = dynamic_cast( componentList[C_CONNECTOR] ); Var *outTex = connectComp->getElement( RT_TEXCOORD ); - outTex->setName( "outTexCoord2" ); + outTex->setName( "texCoord2" ); + outTex->setStructName( "OUT" ); outTex->setType( "vec2" ); outTex->mapsToSampler = true; @@ -953,7 +1180,8 @@ void LightmapFeatGLSL::processPix( Vector &componentList, // grab connector texcoord register ShaderConnector *connectComp = dynamic_cast( componentList[C_CONNECTOR] ); Var *inTex = connectComp->getElement( RT_TEXCOORD ); - inTex->setName( "outTexCoord2" ); + inTex->setName( "texCoord2" ); + inTex->setStructName( "IN" ); inTex->setType( "vec2" ); inTex->mapsToSampler = true; @@ -974,7 +1202,7 @@ void LightmapFeatGLSL::processPix( Vector &componentList, lmColor->setType( "vec4" ); LangElement *lmColorDecl = new DecOp( lmColor ); - output = new GenOp( " @ = texture2D(@, @);\r\n", lmColorDecl, lightMap, inTex ); + output = new GenOp( " @ = tex2D(@, @);\r\n", lmColorDecl, lightMap, inTex ); return; } @@ -995,21 +1223,27 @@ void LightmapFeatGLSL::processPix( Vector &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( "vec4(@, 1.0)", inColor ); + statement = new GenOp( "float4(@, 1.0)", inColor ); else - statement = new GenOp( "texture2D(@, @) + vec4(@.rgb, 0.0)", lightMap, inTex, inColor ); + statement = new GenOp( "tex2D(@, @) + float4(@.rgb, 0.0)", lightMap, inTex, inColor ); } } - else - { - statement = new GenOp( "texture2D(@, @)", lightMap, inTex ); - } + + // If we still don't have it... then just sample the lightmap. + if ( !statement ) + statement = new GenOp( "tex2D(@, @)", lightMap, inTex ); // Assign to proper render target + MultiLine *meta = new MultiLine; if( fd.features[MFT_LightbufferMRT] ) - output = new GenOp( " @;\r\n", assignColor( statement, Material::None, NULL, ShaderFeature::RenderTarget1 ) ); + { + meta->addStatement( new GenOp( " @;\r\n", assignColor( statement, Material::None, NULL, ShaderFeature::RenderTarget1 ) ) ); + meta->addStatement( new GenOp( " @.a = 0.0001;\r\n", LangElement::find( getOutputTargetVarName(ShaderFeature::RenderTarget1) ) ) ); + } else - output = new GenOp( " @;\r\n", assignColor( statement, Material::Mul ) ); + meta->addStatement( new GenOp( " @;\r\n", assignColor( statement, Material::Mul ) ) ); + + output = meta; } ShaderFeature::Resources LightmapFeatGLSL::getResources( const MaterialFeatureData &fd ) @@ -1027,6 +1261,7 @@ void LightmapFeatGLSL::setTexData( Material::StageData &stageDat, U32 &texIndex ) { GFXTextureObject *tex = stageDat.getTex( MFT_LightMap ); + passData.mSamplerNames[ texIndex ] = "lightMap"; if ( tex ) passData.mTexSlot[ texIndex++ ].texObject = tex; else @@ -1054,7 +1289,8 @@ void TonemapFeatGLSL::processVert( Vector &componentList, if ( inTex2 ) { Var *outTex2 = connectComp->getElement( RT_TEXCOORD ); - outTex2->setName( "toneMapCoord" ); + outTex2->setName( "texCoord2" ); + outTex2->setStructName( "OUT" ); outTex2->setType( "vec2" ); outTex2->mapsToSampler = true; @@ -1069,7 +1305,8 @@ void TonemapFeatGLSL::processPix( Vector &componentList, ShaderConnector *connectComp = dynamic_cast( componentList[C_CONNECTOR] ); Var *inTex2 = connectComp->getElement( RT_TEXCOORD ); - inTex2->setName( "toneMapCoord" ); + inTex2->setName( "texCoord2" ); + inTex2->setStructName( "IN" ); inTex2->setType( "vec2" ); inTex2->mapsToSampler = true; @@ -1089,14 +1326,14 @@ void TonemapFeatGLSL::processPix( Vector &componentList, toneMapColor->setName( "toneMapColor" ); LangElement *toneMapColorDecl = new DecOp( toneMapColor ); - meta->addStatement( new GenOp( " @ = texture2D(@, @);\r\n", toneMapColorDecl, toneMap, inTex2 ) ); + 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; if ( fd.features[MFT_DiffuseMap] ) { // Reverse the tonemap - meta->addStatement( new GenOp( " @ = -1.0 * log(1.0 - @);\r\n", toneMapColor, toneMapColor ) ); + meta->addStatement( new GenOp( " @ = -1.0f * log(1.0f - @);\r\n", toneMapColor, toneMapColor ) ); // Re-tonemap with the current color factored in blendOp = Material::ToneMap; @@ -1126,7 +1363,10 @@ void TonemapFeatGLSL::processPix( Vector &componentList, // Assign to proper render target if( fd.features[MFT_LightbufferMRT] ) + { meta->addStatement( new GenOp( " @;\r\n", assignColor( toneMapColor, Material::None, NULL, ShaderFeature::RenderTarget1 ) ) ); + meta->addStatement( new GenOp( " @.a = 0.0001;\r\n", LangElement::find( getOutputTargetVarName(ShaderFeature::RenderTarget1) ) ) ); + } else meta->addStatement( new GenOp( " @;\r\n", assignColor( toneMapColor, blendOp ) ) ); @@ -1151,6 +1391,7 @@ void TonemapFeatGLSL::setTexData( Material::StageData &stageDat, if ( tex ) { passData.mTexType[ texIndex ] = Material::ToneMapTex; + passData.mSamplerNames[ texIndex ] = "toneMap"; passData.mTexSlot[ texIndex++ ].texObject = tex; } } @@ -1194,6 +1435,7 @@ void VertLitGLSL::processVert( Vector &componentList, ShaderConnector *connectComp = dynamic_cast( componentList[C_CONNECTOR] ); Var *outColor = connectComp->getElement( RT_COLOR ); outColor->setName( "vertColor" ); + outColor->setStructName( "OUT" ); outColor->setType( "vec4" ); output = new GenOp( " @ = @;\r\n", outColor, inColor ); @@ -1221,6 +1463,7 @@ void VertLitGLSL::processPix( Vector &componentList, AssertFatal( connectComp, "VertLitGLSL::processVert - C_CONNECTOR is not a ShaderConnector" ); vertColor = connectComp->getElement( RT_COLOR ); vertColor->setName( "vertColor" ); + vertColor->setStructName( "IN" ); vertColor->setType( "vec4" ); } @@ -1239,12 +1482,11 @@ void VertLitGLSL::processPix( Vector &componentList, LangElement *finalVertColorDecl = new DecOp( finalVertColor ); // Reverse the tonemap - meta->addStatement( new GenOp( " @ = -1.0 * log(1.0 - @);\r\n", finalVertColorDecl, vertColor ) ); + meta->addStatement( new GenOp( " @ = -1.0f * log(1.0f - @);\r\n", finalVertColorDecl, vertColor ) ); // Set the blend op to tonemap blendOp = Material::ToneMap; outColor = finalVertColor; - } // Add in the realtime lighting contribution, if applicable @@ -1253,7 +1495,6 @@ void VertLitGLSL::processPix( Vector &componentList, Var *rtLightingColor = (Var*) LangElement::find( "d_lightcolor" ); if(rtLightingColor != NULL) { - // Find out if RTLighting should be added or substituted bool bPreProcessedLighting = false; AdvancedLightBinManager *lightBin; if ( Sim::findObject( "AL_LightBinMgr", lightBin ) ) @@ -1263,15 +1504,18 @@ void VertLitGLSL::processPix( Vector &componentList, // the dynamic light buffer, and it already has the baked-vertex-color // included in it if(bPreProcessedLighting) - outColor = new GenOp( "vec4(@.rgb, 1.0)", rtLightingColor ); + outColor = new GenOp( "float4(@.rgb, 1.0)", rtLightingColor ); else - outColor = new GenOp( "vec4(@.rgb, 0.0) + @", rtLightingColor, outColor ); + outColor = new GenOp( "float4(@.rgb + @.rgb, 1.0)", rtLightingColor, outColor ); } } // Output the color if ( fd.features[MFT_LightbufferMRT] ) + { meta->addStatement( new GenOp( " @;\r\n", assignColor( outColor, Material::None, NULL, ShaderFeature::RenderTarget1 ) ) ); + meta->addStatement( new GenOp( " @.a = 0.0001;\r\n", LangElement::find( getOutputTargetVarName(ShaderFeature::RenderTarget1) ) ) ); + } else meta->addStatement( new GenOp( " @;\r\n", assignColor( outColor, blendOp ) ) ); @@ -1283,7 +1527,6 @@ U32 VertLitGLSL::getOutputTargets( const MaterialFeatureData &fd ) const return fd.features[MFT_LightbufferMRT] ? ShaderFeature::RenderTarget1 : ShaderFeature::DefaultTarget; } - //**************************************************************************** // Detail map //**************************************************************************** @@ -1319,7 +1562,7 @@ void DetailFeatGLSL::processPix( Vector &componentList, // TODO: We could add a feature to toggle between this // and a simple multiplication with the detail map. - LangElement *statement = new GenOp( "( texture2D(@, @) * 2.0 ) - 1.0", detailMap, inTex ); + LangElement *statement = new GenOp( "( tex2D(@, @) * 2.0 ) - 1.0", detailMap, inTex ); output = new GenOp( " @;\r\n", assignColor( statement, Material::Add ) ); } @@ -1339,7 +1582,10 @@ void DetailFeatGLSL::setTexData( Material::StageData &stageDat, { GFXTextureObject *tex = stageDat.getTex( MFT_DetailMap ); if ( tex ) + { + passData.mSamplerNames[texIndex] = "detailMap"; passData.mTexSlot[ texIndex++ ].texObject = tex; + } } @@ -1347,6 +1593,17 @@ void DetailFeatGLSL::setTexData( Material::StageData &stageDat, // Vertex position //**************************************************************************** +void VertPositionGLSL::determineFeature( Material *material, + const GFXVertexFormat *vertexFormat, + U32 stageNum, + const FeatureType &type, + const FeatureSet &features, + MaterialFeatureData *outFeatureData ) +{ + // This feature is always on! + outFeatureData->features.addFeature( type ); +} + void VertPositionGLSL::processVert( Vector &componentList, const MaterialFeatureData &fd ) { @@ -1365,7 +1622,8 @@ void VertPositionGLSL::processVert( Vector &componentList, Var *modelview = getModelView( componentList, fd.features[MFT_UseInstancing], meta ); - meta->addStatement( new GenOp( " @ = @ * vec4(@.xyz,1);\r\n", outPosition, modelview, inPosition ) ); + meta->addStatement( new GenOp( " @ = tMul(@, float4(@.xyz,1));\r\n", + outPosition, modelview, inPosition ) ); output = meta; } @@ -1378,6 +1636,11 @@ void VertPositionGLSL::processVert( Vector &componentList, void ReflectCubeFeatGLSL::processVert( Vector &componentList, const MaterialFeatureData &fd ) { + // search for vert normal + Var *inNormal = (Var*) LangElement::find( "normal" ); + if ( !inNormal ) + return; + MultiLine * meta = new MultiLine; // If a base or bump tex is present in the material, but not in the @@ -1395,7 +1658,8 @@ void ReflectCubeFeatGLSL::processVert( Vector &componentList, // grab connector texcoord register ShaderConnector *connectComp = dynamic_cast( componentList[C_CONNECTOR] ); Var *outTex = connectComp->getElement( RT_TEXCOORD ); - outTex->setName( "outTexCoord" ); + outTex->setName( "texCoord" ); + outTex->setStructName( "OUT" ); outTex->setType( "vec2" ); outTex->mapsToSampler = true; @@ -1405,54 +1669,60 @@ void ReflectCubeFeatGLSL::processVert( Vector &componentList, } // create cubeTrans - Var *cubeTrans = new Var; - cubeTrans->setType( "mat3" ); - cubeTrans->setName( "cubeTrans" ); - cubeTrans->uniform = true; - cubeTrans->constSortPos = cspPrimitive; - - // create cubeEye position - Var *cubeEyePos = new Var; - cubeEyePos->setType( "vec3" ); - cubeEyePos->setName( "cubeEyePos" ); - cubeEyePos->uniform = true; - cubeEyePos->constSortPos = cspPrimitive; - - // search for vert normal - Var *inNormal = (Var*) LangElement::find( "normal" ); + bool useInstancing = fd.features[MFT_UseInstancing]; + Var *cubeTrans = getObjTrans( componentList, useInstancing, meta ); // cube vert position Var * cubeVertPos = new Var; cubeVertPos->setName( "cubeVertPos" ); - cubeVertPos->setType( "vec3" ); + cubeVertPos->setType( "vec3" ); LangElement *cubeVertPosDecl = new DecOp( cubeVertPos ); - meta->addStatement( new GenOp( " @ = @ * @.xyz;\r\n", + meta->addStatement( new GenOp( " @ = tMul(mat3( @ ), @).xyz;\r\n", cubeVertPosDecl, cubeTrans, LangElement::find( "position" ) ) ); // cube normal Var * cubeNormal = new Var; cubeNormal->setName( "cubeNormal" ); - cubeNormal->setType( "vec3" ); + cubeNormal->setType( "vec3" ); LangElement *cubeNormDecl = new DecOp( cubeNormal ); - meta->addStatement( new GenOp( " @ = normalize( @ * normalize(@).xyz );\r\n", + meta->addStatement( new GenOp( " @ = ( tMul( (@), vec4(@, 0) ) ).xyz;\r\n", cubeNormDecl, cubeTrans, inNormal ) ); + // grab the eye position + Var *eyePos = (Var*)LangElement::find( "eyePosWorld" ); + if ( !eyePos ) + { + eyePos = new Var( "eyePosWorld", "vec3" ); + eyePos->uniform = true; + eyePos->constSortPos = cspPass; + } + + // cube position + Var * cubePos = new Var; + cubePos->setName( "cubePos" ); + cubePos->setType( "vec3" ); + LangElement *cubePosDecl = new DecOp( cubePos ); + + meta->addStatement( new GenOp( " @ = vec3( @[3][0], @[3][1], @[3][2] );\r\n", + cubePosDecl, cubeTrans, cubeTrans, cubeTrans ) ); + // eye to vert Var * eyeToVert = new Var; eyeToVert->setName( "eyeToVert" ); - eyeToVert->setType( "vec3" ); + eyeToVert->setType( "vec3" ); LangElement *e2vDecl = new DecOp( eyeToVert ); - meta->addStatement( new GenOp( " @ = @ - @;\r\n", - e2vDecl, cubeVertPos, cubeEyePos ) ); + meta->addStatement( new GenOp( " @ = @ - ( @ - @ );\r\n", + e2vDecl, cubeVertPos, eyePos, cubePos ) ); // grab connector texcoord register ShaderConnector *connectComp = dynamic_cast( componentList[C_CONNECTOR] ); Var *reflectVec = connectComp->getElement( RT_TEXCOORD ); reflectVec->setName( "reflectVec" ); - reflectVec->setType( "vec3" ); + reflectVec->setStructName( "OUT" ); + reflectVec->setType( "vec3" ); reflectVec->mapsToSampler = true; meta->addStatement( new GenOp( " @ = reflect(@, @);\r\n", reflectVec, eyeToVert, cubeNormal ) ); @@ -1476,7 +1746,7 @@ void ReflectCubeFeatGLSL::processPix( Vector &componentList, fd.materialFeatures[MFT_NormalMap] ) { // grab connector texcoord register - Var *inTex = getInTexCoord( "outTexCoord", "vec2", true, componentList ); + Var *inTex = getInTexCoord( "texCoord", "vec2", true, componentList ); // create texture var Var *newMap = new Var; @@ -1494,7 +1764,7 @@ void ReflectCubeFeatGLSL::processPix( Vector &componentList, glossColor = color; - meta->addStatement( new GenOp( " @ = texture2D( @, @ );\r\n", colorDecl, newMap, inTex ) ); + meta->addStatement( new GenOp( " @ = tex2D( @, @ );\r\n", colorDecl, newMap, inTex ) ); } } else @@ -1508,12 +1778,13 @@ void ReflectCubeFeatGLSL::processPix( Vector &componentList, ShaderConnector *connectComp = dynamic_cast( componentList[C_CONNECTOR] ); Var *reflectVec = connectComp->getElement( RT_TEXCOORD ); reflectVec->setName( "reflectVec" ); + reflectVec->setStructName( "IN" ); reflectVec->setType( "vec3" ); reflectVec->mapsToSampler = true; // create cubemap var Var *cubeMap = new Var; - cubeMap->setType( "samplerCube" ); + cubeMap->setType( "samplerCUBE" ); cubeMap->setName( "cubeMap" ); cubeMap->uniform = true; cubeMap->sampler = true; @@ -1527,7 +1798,7 @@ void ReflectCubeFeatGLSL::processPix( Vector &componentList, if ( fd.materialFeatures[MFT_RTLighting] ) attn =(Var*)LangElement::find("d_NL_Att"); - LangElement *texCube = new GenOp( "textureCube( @, @ )", cubeMap, reflectVec ); + LangElement *texCube = new GenOp( "texCUBE( @, @ )", cubeMap, reflectVec ); LangElement *lerpVal = NULL; Material::BlendOp blendOp = Material::LerpAlpha; @@ -1583,22 +1854,27 @@ void ReflectCubeFeatGLSL::setTexData( Material::StageData &stageDat, !passData.mFeatureData.features[MFT_NormalMap] ) { GFXTextureObject *tex = stageDat.getTex( MFT_DetailMap ); - if ( tex && - stageFeatures.features[MFT_DiffuseMap] ) + if ( tex && stageFeatures.features[MFT_DiffuseMap] ) + { + passData.mSamplerNames[ texIndex ] = "diffuseMap"; passData.mTexSlot[ texIndex++ ].texObject = tex; + } else { tex = stageDat.getTex( MFT_NormalMap ); - if ( tex && - stageFeatures.features[ MFT_NormalMap ] ) + if ( tex && stageFeatures.features[ MFT_NormalMap ] ) + { + passData.mSamplerNames[ texIndex ] = "bumpMap"; passData.mTexSlot[ texIndex++ ].texObject = tex; + } } } if( stageDat.getCubemap() ) { passData.mCubeMap = stageDat.getCubemap(); + passData.mSamplerNames[texIndex] = "cubeMap"; passData.mTexType[texIndex++] = Material::Cube; } else @@ -1606,6 +1882,7 @@ void ReflectCubeFeatGLSL::setTexData( Material::StageData &stageDat, if( stageFeatures.features[MFT_CubeMap] ) { // assuming here that it is a scenegraph cubemap + passData.mSamplerNames[texIndex] = "cubeMap"; passData.mTexType[texIndex++] = Material::SGCube; } } @@ -1639,18 +1916,17 @@ void RTLightingFeatGLSL::processVert( Vector &componentList, Var *eyePos = (Var*)LangElement::find( "eyePosWorld" ); if ( !eyePos ) { - eyePos = new Var( "eyePosWorld", "float3" ); + eyePos = new Var( "eyePosWorld", "vec3" ); eyePos->uniform = true; eyePos->constSortPos = cspPass; } - //TODO: should this be the same as "Find the incoming vertex normal" below? Var *inPosition = (Var*)LangElement::find( "position" ); Var *outNormal = connectComp->getElement( RT_TEXCOORD ); outNormal->setName( "wsNormal" ); outNormal->setStructName( "OUT" ); - outNormal->setType( "float3" ); + outNormal->setType( "vec3" ); outNormal->mapsToSampler = false; // Transform the normal to world space. @@ -1665,9 +1941,7 @@ void RTLightingFeatGLSL::processVert( Vector &componentList, } // Find the incoming vertex normal. - Var *inNormal = (Var*)LangElement::find( "inNormal" ); - if ( !inNormal ) - inNormal = (Var*)LangElement::find( "normal" ); + Var *inNormal = (Var*)LangElement::find( "normal" ); // Skip out on realtime lighting if we don't have a normal // or we're doing some sort of baked lighting. @@ -1675,29 +1949,25 @@ void RTLightingFeatGLSL::processVert( Vector &componentList, fd.features[MFT_LightMap] || fd.features[MFT_ToneMap] || fd.features[MFT_VertLit] ) - return; - - // Get the transform to world space. - Var *objTrans = getObjTrans( componentList, fd.features[MFT_UseInstancing], meta ); + return; // If there isn't a normal map then we need to pass // the world space normal to the pixel shader ourselves. if ( !fd.features[MFT_NormalMap] ) { Var *outNormal = connectComp->getElement( RT_TEXCOORD ); - outNormal->setName( "outWsNormal" ); + outNormal->setName( "wsNormal" ); + outNormal->setStructName( "OUT" ); outNormal->setType( "vec3" ); outNormal->mapsToSampler = false; + + // Get the transform to world space. + Var *objTrans = getObjTrans( componentList, fd.features[MFT_UseInstancing], meta ); // Transform the normal to world space. - meta->addStatement( new GenOp( " @ = ( @ * vec4( normalize( @ ), 0.0 ) ).xyz;\r\n", outNormal, objTrans, inNormal ) ); + meta->addStatement( new GenOp( " @ = tMul( @, float4( normalize( @ ), 0.0 ) ).xyz;\r\n", outNormal, objTrans, inNormal ) ); } - // Get the input position. - Var *inPosition = (Var*)LangElement::find( "inPosition" ); - if ( !inPosition ) - inPosition = (Var*)LangElement::find( "position" ); - addOutWsPosition( componentList, fd.features[MFT_UseInstancing], meta ); output = meta; @@ -1723,41 +1993,25 @@ void RTLightingFeatGLSL::processPix( Vector &componentList, Var *wsNormal = (Var*)LangElement::find( "wsNormal" ); if ( !wsNormal ) { - Var *outWsNormal = connectComp->getElement( RT_TEXCOORD ); - outWsNormal->setName( "outWsNormal" ); - outWsNormal->setType( "vec3" ); + wsNormal = connectComp->getElement( RT_TEXCOORD ); + wsNormal->setName( "wsNormal" ); + wsNormal->setStructName( "IN" ); + wsNormal->setType( "vec3" ); - wsNormal = new Var( "wsNormal", "vec3" ); - - // If we loaded the normal its our resposibility + // If we loaded the normal its our responsibility // to normalize it... the interpolators won't. - meta->addStatement( new GenOp( " @ = normalize( @ );\r\n", - new DecOp( wsNormal ), outWsNormal ) ); + // + // Note we cast to half here to get partial precision + // optimized code which is an acceptable loss of + // precision for normals and performs much better + // on older Geforce cards. + // + meta->addStatement( new GenOp( " @ = normalize( half3( @ ) );\r\n", wsNormal, wsNormal ) ); } - Var *wsPosition = getInWsPosition( componentList ); - - // If we have a specular feature then we need to - // get the world space view vector to pass to the - // lighting calculation. - Var *wsView = new Var( "wsView", "vec3" ); - if ( fd.features[MFT_PixSpecular] ) - { - Var *eyePos = (Var*)LangElement::find( "eyePosWorld" ); - if ( !eyePos ) - { - eyePos = new Var; - eyePos->setType( "vec3" ); - eyePos->setName( "eyePosWorld" ); - eyePos->uniform = true; - eyePos->constSortPos = cspPass; - } - - meta->addStatement( new GenOp( " @ = normalize( @ - @ );\r\n", - new DecOp( wsView ), eyePos, wsPosition ) ); - } - else - meta->addStatement( new GenOp( " @ = vec3( 0 );\r\n", new DecOp( wsView ) ) ); + // Now the wsPosition and wsView. + Var *wsPosition = getInWsPosition( componentList ); + Var *wsView = getWsView( wsPosition, meta ); // Create temporaries to hold results of lighting. Var *rtShading = new Var( "rtShading", "vec4" ); @@ -1765,18 +2019,66 @@ void RTLightingFeatGLSL::processPix( Vector &componentList, meta->addStatement( new GenOp( " @; @;\r\n", new DecOp( rtShading ), new DecOp( specular ) ) ); - // Calculate the diffuse shading and specular powers. - meta->addStatement( new GenOp( " compute4Lights( @, @, @, @, @ );\r\n", - wsView, wsPosition, wsNormal, rtShading, specular ) ); - // Look for a light mask generated from a previous // feature (this is done for BL terrain lightmaps). - Var *lightMask = (Var*)LangElement::find( "lightMask" ); - if ( lightMask ) - meta->addStatement( new GenOp( " @.rgb *= @;\r\n", rtShading, lightMask ) ); + LangElement *lightMask = LangElement::find( "lightMask" ); + if ( !lightMask ) + lightMask = new GenOp( "float4( 1, 1, 1, 1 )" ); + + // Get all the light constants. + Var *inLightPos = new Var( "inLightPos", "vec4" ); + inLightPos->uniform = true; + inLightPos->arraySize = 3; + inLightPos->constSortPos = cspPotentialPrimitive; + + Var *inLightInvRadiusSq = new Var( "inLightInvRadiusSq", "vec4" ); + inLightInvRadiusSq->uniform = true; + inLightInvRadiusSq->constSortPos = cspPotentialPrimitive; + + Var *inLightColor = new Var( "inLightColor", "vec4" ); + inLightColor->uniform = true; + inLightColor->arraySize = 4; + inLightColor->constSortPos = cspPotentialPrimitive; + + Var *inLightSpotDir = new Var( "inLightSpotDir", "vec4" ); + inLightSpotDir->uniform = true; + inLightSpotDir->arraySize = 3; + inLightSpotDir->constSortPos = cspPotentialPrimitive; + + Var *inLightSpotAngle = new Var( "inLightSpotAngle", "vec4" ); + inLightSpotAngle->uniform = true; + inLightSpotAngle->constSortPos = cspPotentialPrimitive; + + Var *lightSpotFalloff = new Var( "inLightSpotFalloff", "vec4" ); + lightSpotFalloff->uniform = true; + lightSpotFalloff->constSortPos = cspPotentialPrimitive; + + Var *specularPower = new Var( "specularPower", "float" ); + specularPower->uniform = true; + specularPower->constSortPos = cspPotentialPrimitive; + + Var *specularColor = (Var*)LangElement::find( "specularColor" ); + if ( !specularColor ) + { + specularColor = new Var( "specularColor", "vec4" ); + specularColor->uniform = true; + specularColor->constSortPos = cspPotentialPrimitive; + } + + Var *ambient = new Var( "ambient", "vec4" ); + ambient->uniform = true; + ambient->constSortPos = cspPass; + + // Calculate the diffuse shading and specular powers. + meta->addStatement( new GenOp( " compute4Lights( @, @, @, @,\r\n" + " @, @, @, @, @, @, @, @,\r\n" + " @, @ );\r\n", + wsView, wsPosition, wsNormal, lightMask, + inLightPos, inLightInvRadiusSq, inLightColor, inLightSpotDir, inLightSpotAngle, lightSpotFalloff, specularPower, specularColor, + rtShading, specular ) ); // Apply the lighting to the diffuse color. - LangElement *lighting = new GenOp( "vec4( @.rgb + ambient.rgb, 1 )", rtShading ); + LangElement *lighting = new GenOp( "float4( @.rgb + @.rgb, 1 )", rtShading, ambient ); meta->addStatement( new GenOp( " @;\r\n", assignColor( lighting, Material::Mul ) ) ); output = meta; } @@ -1844,6 +2146,7 @@ void FogFeatGLSL::processVert( Vector &componentList, ShaderConnector *connectComp = dynamic_cast( componentList[C_CONNECTOR] ); Var *fogAmount = connectComp->getElement( RT_TEXCOORD ); fogAmount->setName( "fogAmount" ); + fogAmount->setStructName( "OUT" ); fogAmount->setType( "float" ); fogAmount->mapsToSampler = false; @@ -1891,6 +2194,7 @@ void FogFeatGLSL::processPix( Vector &componentList, ShaderConnector *connectComp = dynamic_cast( componentList[C_CONNECTOR] ); fogAmount = connectComp->getElement( RT_TEXCOORD ); fogAmount->setName( "fogAmount" ); + fogAmount->setStructName( "IN" ); fogAmount->setType( "float" ); } else @@ -1917,7 +2221,7 @@ void FogFeatGLSL::processPix( Vector &componentList, } // Lerp between the fog color and diffuse color. - LangElement *fogLerp = new GenOp( "mix( @.rgb, @.rgb, @ )", fogColor, color, fogAmount ); + LangElement *fogLerp = new GenOp( "lerp( @.rgb, @.rgb, @ )", fogColor, color, fogAmount ); meta->addStatement( new GenOp( " @.rgb = @;\r\n", color, fogLerp ) ); output = meta; @@ -1935,42 +2239,59 @@ ShaderFeature::Resources FogFeatGLSL::getResources( const MaterialFeatureData &f // Visibility //**************************************************************************** +VisibilityFeatGLSL::VisibilityFeatGLSL() + : mTorqueDep( "shaders/common/gl/torque.glsl" ) +{ + addDependency( &mTorqueDep ); +} + void VisibilityFeatGLSL::processVert( Vector &componentList, const MaterialFeatureData &fd ) { - // Pass screen space position to pixel shader to compute a full screen buffer uv - Var* ssPos = ( Var* ) LangElement::find( "screenspacePos" ); - if( !ssPos ) + MultiLine *meta = new MultiLine; + output = meta; + + if ( fd.features[ MFT_UseInstancing ] ) { - ShaderConnector* connectComp = dynamic_cast< ShaderConnector* >( componentList[C_CONNECTOR] ); - AssertFatal( connectComp, "VisibilityFeatGLSL::processVert - invalid ShaderConnector" ); + // We pass the visibility to the pixel shader via + // another output register. + // + // TODO: We should see if we can share this register + // with some other common instanced data. + // + ShaderConnector *conn = dynamic_cast( componentList[C_CONNECTOR] ); + Var *outVisibility = conn->getElement( RT_TEXCOORD ); + outVisibility->setStructName( "OUT" ); + outVisibility->setName( "visibility" ); + outVisibility->setType( "float" ); + + ShaderConnector *vertStruct = dynamic_cast( componentList[C_VERT_STRUCT] ); + Var *instVisibility = vertStruct->getElement( RT_TEXCOORD, 1 ); + instVisibility->setStructName( "IN" ); + instVisibility->setName( "inst_visibility" ); + instVisibility->setType( "float" ); + mInstancingFormat->addElement( "visibility", GFXDeclType_Float, instVisibility->constNum ); - Var* ssPos = connectComp->getElement( RT_TEXCOORD ); - ssPos->setName( "screenspacePos" ); - ssPos->setType( "vec4" ); - - Var* outPosition = ( Var* ) LangElement::find( "gl_Position" ); - AssertFatal( outPosition, "VisibilityFeatGLSL::processVert - No gl_Position" ); - - output = new GenOp( " @ = @;\r\n", ssPos, outPosition ); + meta->addStatement( new GenOp( " @ = @; // Instancing!\r\n", outVisibility, instVisibility ) ); } + + if ( fd.features[ MFT_IsTranslucent ] ) + return; + + addOutVpos( meta, componentList ); } void VisibilityFeatGLSL::processPix( Vector &componentList, const MaterialFeatureData &fd ) -{ - // Look up output color. - - Var* color = ( Var* ) LangElement::find( "col" ); - if( !color ) +{ + // Get the visibility constant. + Var *visibility = NULL; + if ( fd.features[ MFT_UseInstancing ] ) + visibility = getInTexCoord( "visibility", "float", false, componentList ); + else { - output = NULL; - return; - } + visibility = (Var*)LangElement::find( "visibility" ); - Var* visibility = (Var*)LangElement::find( "visibility" ); - - // Create visibility var. if ( !visibility ) { visibility = new Var(); @@ -1979,94 +2300,36 @@ void VisibilityFeatGLSL::processPix( Vector &componentList, visibility->uniform = true; visibility->constSortPos = cspPotentialPrimitive; } - - Var* ssPos = ( Var* ) LangElement::find( "screenspacePos" ); - if( !ssPos ) - { - ShaderConnector *connectComp = dynamic_cast( componentList[C_CONNECTOR] ); - AssertFatal( connectComp, "VisibilityFeatGLSL::processPix - invalid ShaderConnector" ); - - ssPos = connectComp->getElement( RT_TEXCOORD ); - ssPos->setName( "screenspacePos" ); - ssPos->setType( "vec4" ); } MultiLine* meta = new MultiLine; output = meta; - //Compute final visibility from incoming visibility and strength of fade effects - Var *finalVisibility = new Var( "finalVisibility", "float" ); - meta->addStatement(new GenOp( " @ = @;\r\n", new DecOp( finalVisibility ), visibility ) ); - Var *imposterFade = (Var*) LangElement::find( "imposterFade" ); - if ( imposterFade ) - meta->addStatement( new GenOp( " @ *= @;\r\n", finalVisibility, imposterFade ) ); - Var *foliageFade = (Var*) LangElement::find( "foliageFade" ); - if ( foliageFade ) - meta->addStatement( new GenOp( " @ *= @;\r\n", finalVisibility, foliageFade ) ); - - if( !fd.features[ MFT_IsTranslucent ] ) + // Translucent objects do a simple alpha fade. + if ( fd.features[ MFT_IsTranslucent ] ) { - // Create fizzMap sampler. - - Var* fizzMap = ( Var* ) LangElement::find( "fizzMap" ); - if( !fizzMap ) - { - fizzMap = new Var; - fizzMap->setType( "sampler2D" ); - fizzMap->setName( "fizzMap" ); - fizzMap->uniform = true; - fizzMap->sampler = true; - fizzMap->constNum = Var::getTexUnitNum(); + Var *color = (Var*) LangElement::find( "col" ); + meta->addStatement( new GenOp( " @.a *= @;\r\n", color, visibility ) ); + return; } - // Create fizzScale uniform. - - Var* fizzScale = new Var; - fizzScale->setType( "float2" ); - fizzScale->setName( "fizzScale" ); - fizzScale->uniform = true; - fizzScale->constSortPos = cspPass; - - meta->addStatement( new GenOp( " float fizz = tex2D( @, (@.xy / @.w) * fizzScale ).r + 0.15;\r\n", fizzMap, ssPos, ssPos ) ); - meta->addStatement( new GenOp( " if( ( fizz * @ - 0.329 ) < 0.0 )\r\n" - " discard\r\n;", finalVisibility ) ); - } - else if( color ) - { - meta->addStatement( new GenOp( " @.w *= @;\r\n", color, finalVisibility ) ); - } + // Everything else does a fizzle. + Var *vPos = getInVpos( meta, componentList ); + meta->addStatement( new GenOp( " fizzle( @, @ );\r\n", vPos, visibility ) ); } ShaderFeature::Resources VisibilityFeatGLSL::getResources( const MaterialFeatureData &fd ) { Resources res; + // TODO: Fix for instancing. + if ( !fd.features[ MFT_IsTranslucent ] ) - { - res.numTex = 1; res.numTexReg = 1; - } return res; } -void VisibilityFeatGLSL::setTexData( Material::StageData &stageDat, - const MaterialFeatureData &fd, - RenderPassData &passData, - U32 &texIndex ) -{ - if ( !fd.features[ MFT_IsTranslucent ] ) - { - GFXTexHandle texHandle( "core/art/fizz_noise.dds", &GFXDefaultStaticDiffuseProfile, "VisibilityFeatHLSL_fizz_noise" ); - stageDat.setTex( MFT_Visibility, texHandle ); - - GFXTextureObject *tex = stageDat.getTex( MFT_Visibility ); - if ( tex ) - passData.mTexSlot[ texIndex++ ].texObject = tex; - } -} - - //**************************************************************************** // AlphaTest //**************************************************************************** @@ -2100,7 +2363,7 @@ void AlphaTestGLSL::processPix( Vector &componentList, alphaTestVal->constSortPos = cspPotentialPrimitive; // Do the clip. - output = new GenOp( " if ( ( @.a - @ ) < 0 ) discard;\r\n", color, alphaTestVal ); + output = new GenOp( " clip( @.a - @ );\r\n", color, alphaTestVal ); } @@ -2123,6 +2386,7 @@ void GlowMaskGLSL::processPix( Vector &componentList, output = new GenOp( " @.rgb = 0;\r\n", color ); } + //**************************************************************************** // RenderTargetZero //**************************************************************************** @@ -2140,10 +2404,11 @@ void RenderTargetZeroGLSL::processPix( Vector &componentList, //**************************************************************************** HDROutGLSL::HDROutGLSL() -: mTorqueDep( "shaders/common/gl/torque.glsl" ) + : mTorqueDep( "shaders/common/gl/torque.glsl" ) { addDependency( &mTorqueDep ); } + void HDROutGLSL::processPix( Vector &componentList, const MaterialFeatureData &fd ) { @@ -2153,7 +2418,6 @@ void HDROutGLSL::processPix( Vector &componentList, output = new GenOp( " @ = hdrEncode( @ );\r\n", color, color ); } - //**************************************************************************** // FoliageFeatureGLSL //**************************************************************************** @@ -2169,42 +2433,23 @@ FoliageFeatureGLSL::FoliageFeatureGLSL() void FoliageFeatureGLSL::processVert( Vector &componentList, const MaterialFeatureData &fd ) { - - MultiLine *meta = new MultiLine; - // Get the input variables we need. Var *inPosition = (Var*)LangElement::find( "inPosition" ); - if ( !inPosition ) { - // inPosition = (Var*)LangElement::find( "position" ); - inPosition = new Var( "inPosition", "vec3" ); - meta->addStatement( new GenOp( " @ = @;\n", new DecOp( inPosition ), (Var*)LangElement::find( "position" ) ) ); - } + if ( !inPosition ) + inPosition = (Var*)LangElement::find( "position" ); Var *inColor = (Var*)LangElement::find( "diffuse" ); - Var *outColor = new Var( "inDiffuse", "vec4" ); - meta->addStatement( new GenOp( " @ = @;\n", new DecOp( outColor ), inColor ) ); Var *inParams = (Var*)LangElement::find( "texCoord" ); - Var *outParams = getOutTexCoord( "texCoord", - "vec2", - true, - fd.features[MFT_TexAnim], - meta, - componentList ); - + MultiLine *meta = new MultiLine; // Declare the normal and tangent variables since they do not exist // in this vert type, but we do need to set them up for others. - Var *inNormal = (Var*)LangElement::find( "inNormal" ); - if ( !inNormal ) { - inNormal = new Var( "inNormal", "vec3" ); - meta->addStatement( new GenOp( " @ = @;\n", new DecOp( inNormal ), (Var*)LangElement::find( "normal" ) ) ); - } - //Var *normal = (Var*)LangElement::find( "normal" ); - AssertFatal( inNormal, "FoliageFeatureHLSL requires vert normal!" ); + Var *normal = (Var*)LangElement::find( "normal" ); + AssertFatal( normal, "FoliageFeatureGLSL requires vert normal!" ); Var *tangent = new Var; tangent->setType( "vec3" ); @@ -2216,6 +2461,7 @@ void FoliageFeatureGLSL::processVert( Vector &componentList, ShaderConnector *connectComp = dynamic_cast( componentList[C_CONNECTOR] ); Var *fade = connectComp->getElement( RT_TEXCOORD ); fade->setName( "foliageFade" ); + fade->setStructName( "OUT" ); fade->setType( "float" ); // grab the eye position @@ -2227,12 +2473,11 @@ void FoliageFeatureGLSL::processVert( Vector &componentList, eyePos->constSortPos = cspPass; } - // All actual work is offloaded to this method. - meta->addStatement( new GenOp( " foliageProcessVert( @, @, @, @, @, @, @ );\r\n", inPosition, outColor, inParams, outParams, inNormal, tangent, eyePos ) ); + meta->addStatement( new GenOp( " foliageProcessVert( @, @, @, @, @, @ );\r\n", inPosition, inColor, inParams, normal, tangent, eyePos ) ); // Assign to foliageFade. InColor.a was set to the correct value inside foliageProcessVert. - meta->addStatement( new GenOp( " @ = @.a;\r\n", fade, outColor ) ); + meta->addStatement( new GenOp( " @ = @.a;\r\n", fade, inColor ) ); output = meta; } @@ -2244,7 +2489,26 @@ void FoliageFeatureGLSL::processPix( Vector &componentList, ShaderConnector *connectComp = dynamic_cast( componentList[C_CONNECTOR] ); Var *fade = connectComp->getElement( RT_TEXCOORD ); fade->setName( "foliageFade" ); + fade->setStructName( "IN" ); fade->setType( "float" ); + + // Find / create visibility + Var *visibility = (Var*) LangElement::find( "visibility" ); + if ( !visibility ) + { + visibility = new Var(); + visibility->setType( "float" ); + visibility->setName( "visibility" ); + visibility->uniform = true; + visibility->constSortPos = cspPotentialPrimitive; + } + + MultiLine *meta = new MultiLine; + + // Multiply foliageFade into visibility. + meta->addStatement( new GenOp( " @ *= @;\r\n", visibility, fade ) ); + + output = meta; } void FoliageFeatureGLSL::determineFeature( Material *material, const GFXVertexFormat *vertexFormat, U32 stageNum, const FeatureType &type, const FeatureSet &features, MaterialFeatureData *outFeatureData ) @@ -2255,6 +2519,7 @@ void FoliageFeatureGLSL::determineFeature( Material *material, const GFXVertexFo outFeatureData->features.addFeature( type ); } + ShaderFeatureConstHandles* FoliageFeatureGLSL::createConstHandles( GFXShader *shader, SimObject *userObject ) { GroundCover *gcover = dynamic_cast< GroundCover* >( userObject ); @@ -2269,10 +2534,6 @@ ShaderFeatureConstHandles* FoliageFeatureGLSL::createConstHandles( GFXShader *sh } -//**************************************************************************** -// ParticleNormal -//**************************************************************************** - void ParticleNormalFeatureGLSL::processVert(Vector &componentList, const MaterialFeatureData &fd) { MultiLine *meta = new MultiLine; @@ -2292,7 +2553,7 @@ void ParticleNormalFeatureGLSL::processVert(Vector &componentL // screen because there is a discontinuity at (0, 1, 0) for gbuffer encoding. Do not // cause this value to be (0, -1, 0) or interlaced normals will be discontinuous. // [11/23/2009 Pat] - meta->addStatement(new GenOp(" @ = vec3(0.0, -0.97, 0.14);\r\n", new DecOp(normal))); + meta->addStatement(new GenOp(" @ = float3(0.0, -0.97, 0.14);\r\n", new DecOp(normal))); } Var *T = (Var*) LangElement::find( "T" ); @@ -2301,17 +2562,16 @@ void ParticleNormalFeatureGLSL::processVert(Vector &componentL T = new Var; T->setType( "vec3" ); T->setName( "T" ); - meta->addStatement(new GenOp(" @ = vec3(0.0, 0.0, -1.0);\r\n", new DecOp(T))); + meta->addStatement(new GenOp(" @ = float3(0.0, 0.0, -1.0);\r\n", new DecOp(T))); } } - //**************************************************************************** // ImposterVertFeatureGLSL //**************************************************************************** ImposterVertFeatureGLSL::ImposterVertFeatureGLSL() -: mDep( "shaders/common/gl/imposter.glsl" ) + : mDep( "shaders/common/gl/imposter.glsl" ) { addDependency( &mDep ); } @@ -2338,7 +2598,7 @@ void ImposterVertFeatureGLSL::processVert( Vector &component Var *imposterUVs = new Var; imposterUVs->setType( "vec4" ); imposterUVs->setName( "imposterUVs" ); - imposterUVs->arraySize = 64; // See imposter.hlsl + imposterUVs->arraySize = 64; // See imposter.glsl imposterUVs->uniform = true; imposterUVs->constSortPos = cspPotentialPrimitive; @@ -2362,15 +2622,15 @@ void ImposterVertFeatureGLSL::processVert( Vector &component meta->addStatement( new GenOp( " @;\r\n", new DecOp( outTexCoord ) ) ); Var *outWorldToTangent = new Var; - outWorldToTangent->setType( "mat3" ); + outWorldToTangent->setType( "float3x3" ); outWorldToTangent->setName( "worldToTangent" ); meta->addStatement( new GenOp( " @;\r\n", new DecOp( outWorldToTangent ) ) ); - //Var *outWorldToTangent = getOutWorldToTangent( componentList, meta, fd ); // Add imposterFade to the OUT structure. ShaderConnector *connectComp = dynamic_cast( componentList[C_CONNECTOR] ); Var *outFade = connectComp->getElement( RT_TEXCOORD ); outFade->setName( "imposterFade" ); + outFade->setStructName( "OUT" ); outFade->setType( "float" ); // Assign OUT.imposterFade @@ -2410,7 +2670,7 @@ void ImposterVertFeatureGLSL::processVert( Vector &component // If we new viewToTangent... its the same as the // world to tangent for an imposter. Var *viewToTangent = new Var; - viewToTangent->setType( "mat3" ); + viewToTangent->setType( "float3x3" ); viewToTangent->setName( "viewToTangent" ); meta->addStatement( new GenOp( " @ = @;\r\n", new DecOp( viewToTangent ), outWorldToTangent ) ); } @@ -2418,14 +2678,13 @@ void ImposterVertFeatureGLSL::processVert( Vector &component void ImposterVertFeatureGLSL::processPix( Vector &componentList, const MaterialFeatureData &fd ) { - // Find / create IN.imposterFade ShaderConnector *connectComp = dynamic_cast( componentList[C_CONNECTOR] ); Var *fade = connectComp->getElement( RT_TEXCOORD ); fade->setName( "imposterFade" ); + fade->setStructName( "IN" ); fade->setType( "float" ); - /* // Find / create visibility Var *visibility = (Var*) LangElement::find( "visibility" ); if ( !visibility ) @@ -2440,10 +2699,9 @@ void ImposterVertFeatureGLSL::processPix( Vector &componentLis MultiLine *meta = new MultiLine; // Multiply foliageFade into visibility. - //meta->addStatement( new GenOp( " @ *= @;\r\n", visibility, fade ) ); + meta->addStatement( new GenOp( " @ *= @;\r\n", visibility, fade ) ); output = meta; - */ } void ImposterVertFeatureGLSL::determineFeature( Material *material, @@ -2455,4 +2713,5 @@ void ImposterVertFeatureGLSL::determineFeature( Material *material, { if ( features.hasFeature( MFT_ImposterVert ) ) outFeatureData->features.addFeature( MFT_ImposterVert ); -} \ No newline at end of file +} + diff --git a/Engine/source/shaderGen/GLSL/shaderFeatureGLSL.h b/Engine/source/shaderGen/GLSL/shaderFeatureGLSL.h index 14af0300f..a0e831e93 100644 --- a/Engine/source/shaderGen/GLSL/shaderFeatureGLSL.h +++ b/Engine/source/shaderGen/GLSL/shaderFeatureGLSL.h @@ -25,9 +25,6 @@ #ifndef _SHADERFEATURE_H_ #include "shaderGen/shaderFeature.h" #endif -#ifndef _MATERIALFEATUREDATA_H_ - #include "materials/materialFeatureData.h" -#endif struct LangElement; struct MaterialFeatureData; @@ -54,13 +51,25 @@ public: bool mapsToSampler, Vector &componentList ); + static Var* getInColor( const char *name, + const char *type, + Vector &componentList ); + + /// + static Var* addOutVpos( MultiLine *meta, + Vector &componentList ); + + /// Returns the VPOS input register for the pixel shader. + static Var* getInVpos( MultiLine *meta, + Vector &componentList ); + /// Returns the "objToTangentSpace" transform or creates one if this /// is the first feature to need it. Var* getOutObjToTangentSpace( Vector &componentList, MultiLine *meta, const MaterialFeatureData &fd ); - /// Returns the existing output "worldToTangent" transform or + /// Returns the existing output "outWorldToTangent" transform or /// creates one if this is the first feature to need it. Var* getOutWorldToTangent( Vector &componentList, MultiLine *meta, @@ -70,7 +79,7 @@ public: /// adding it to the input connector if it doesn't exist. static Var* getInWorldToTangent( Vector &componentList ); - /// Returns the existing output "viewToTangent" transform or + /// Returns the existing output "outViewToTangent" transform or /// creates one if this is the first feature to need it. Var* getOutViewToTangent( Vector &componentList, MultiLine *meta, @@ -81,17 +90,16 @@ public: static Var* getInViewToTangent( Vector &componentList ); /// Calculates the world space position in the vertex shader and - /// assigns it to the passed language element. It does not pass /// it across the connector to the pixel shader. + /// assigns it to the passed language element. It does not pass + /// it across the connector to the pixel shader. /// @see addOutWsPosition void getWsPosition( Vector &componentList, - bool useInstancing, MultiLine *meta, LangElement *wsPosition ); /// Adds the "wsPosition" to the input connector if it doesn't exist. Var* addOutWsPosition( Vector &componentList, - bool useInstancing, MultiLine *meta ); @@ -129,7 +137,6 @@ public: bool useInstancing, MultiLine *meta ); - // ShaderFeature Var* getVertTexCoord( const String &name ); LangElement* setupTexSpaceMat( Vector &componentList, Var **texSpaceMat ); @@ -151,25 +158,27 @@ public: virtual String getName() { return mName; } }; - class RenderTargetZeroGLSL : public ShaderFeatureGLSL { -protected: ShaderFeature::OutputTarget mOutputTargetMask; +protected: + ShaderFeature::OutputTarget mOutputTargetMask; String mFeatureName; public: RenderTargetZeroGLSL( const ShaderFeature::OutputTarget target ) : mOutputTargetMask( target ) { - char buffer[256]; dSprintf(buffer, sizeof(buffer), "Render Target Output = 0.0, output mask %04b", mOutputTargetMask); - mFeatureName = buffer; } + char buffer[256]; + dSprintf(buffer, sizeof(buffer), "Render Target Output = 0.0, output mask %04b", mOutputTargetMask); + mFeatureName = buffer; + } virtual String getName() { return mFeatureName; } virtual void processPix( Vector &componentList, const MaterialFeatureData &fd ); - virtual U32 getOutputTargets( const MaterialFeatureData &fd ) const { return - mOutputTargetMask; } + + virtual U32 getOutputTargets( const MaterialFeatureData &fd ) const { return mOutputTargetMask; } }; @@ -190,11 +199,7 @@ public: U32 stageNum, const FeatureType &type, const FeatureSet &features, - MaterialFeatureData *outFeatureData ) - { - // This feature is always on! - outFeatureData->features.addFeature( type ); - } + MaterialFeatureData *outFeatureData ); }; @@ -297,7 +302,6 @@ public: } }; - /// Diffuse vertex color class DiffuseVertColorFeatureGLSL : public ShaderFeatureGLSL { @@ -316,7 +320,6 @@ public: } }; - /// Lightmap class LightmapFeatGLSL : public ShaderFeatureGLSL { @@ -491,7 +494,14 @@ public: /// Visibility class VisibilityFeatGLSL : public ShaderFeatureGLSL { +protected: + + ShaderIncludeDependency mTorqueDep; + public: + + VisibilityFeatGLSL(); + virtual void processVert( Vector &componentList, const MaterialFeatureData &fd ); @@ -500,11 +510,6 @@ public: virtual Resources getResources( const MaterialFeatureData &fd ); - virtual void setTexData( Material::StageData &stageDat, - const MaterialFeatureData &fd, - RenderPassData &passData, - U32 &texIndex ); - virtual Material::BlendOp getBlendOp() { return Material::None; } virtual String getName() @@ -547,10 +552,10 @@ public: } }; - /// This should be the final feature on most pixel shaders which /// encodes the color for the current HDR target format. -/// @see HDRPostFx/// @see LightManager +/// @see HDRPostFx +/// @see LightManager /// @see torque.glsl class HDROutGLSL : public ShaderFeatureGLSL { @@ -570,9 +575,9 @@ public: virtual String getName() { return "HDR Output"; } }; - /// -class FoliageFeatureGLSL : public ShaderFeatureGLSL{ +class FoliageFeatureGLSL : public ShaderFeatureGLSL +{ protected: ShaderIncludeDependency mDep; @@ -583,6 +588,7 @@ public: virtual void processVert( Vector &componentList, const MaterialFeatureData &fd ); + virtual void processPix( Vector &componentList, const MaterialFeatureData &fd ); @@ -597,11 +603,10 @@ public: const FeatureType &type, const FeatureSet &features, MaterialFeatureData *outFeatureData ); + virtual ShaderFeatureConstHandles* createConstHandles( GFXShader *shader, SimObject *userObject ); }; - -/// class ParticleNormalFeatureGLSL : public ShaderFeatureGLSL { public: @@ -616,6 +621,9 @@ public: }; + +/// Special feature for unpacking imposter verts. +/// @see RenderImposterMgr class ImposterVertFeatureGLSL : public ShaderFeatureGLSL { protected: @@ -623,9 +631,12 @@ protected: ShaderIncludeDependency mDep; public: - ImposterVertFeatureGLSL(); + + ImposterVertFeatureGLSL(); + virtual void processVert( Vector &componentList, const MaterialFeatureData &fd ); + virtual void processPix( Vector &componentList, const MaterialFeatureData &fd ); diff --git a/Engine/source/shaderGen/GLSL/shaderGenGLSL.cpp b/Engine/source/shaderGen/GLSL/shaderGenGLSL.cpp index ebbf2b3d8..f694b11e3 100644 --- a/Engine/source/shaderGen/GLSL/shaderGenGLSL.cpp +++ b/Engine/source/shaderGen/GLSL/shaderGenGLSL.cpp @@ -56,7 +56,9 @@ void ShaderGenPrinterGLSL::printMainComment( Stream& stream ) void ShaderGenPrinterGLSL::printVertexShaderCloser( Stream& stream ) { - const char *closer = "}\r\n"; + // We are render OpenGL upside down for use DX9 texture coords. + // Must be the last vertex feature. + const char *closer = " gl_Position.y *= -1;\r\n}\r\n"; stream.write( dStrlen(closer), closer ); } @@ -67,7 +69,7 @@ void ShaderGenPrinterGLSL::printPixelShaderOutputStruct( Stream& stream, const M void ShaderGenPrinterGLSL::printPixelShaderCloser( Stream& stream ) { - const char *closer = " gl_FragColor = col;\r\n}\r\n"; + const char *closer = " OUT_FragColor0 = col;\r\n}\r\n"; stream.write( dStrlen(closer), closer ); } @@ -124,6 +126,11 @@ ShaderComponent* ShaderGenComponentFactoryGLSL::createVertexInputConnector( cons var = vertComp->getElement( RT_TANGENT ); var->setName( "T" ); } + else if ( element.isSemantic( GFXSemantic::TANGENTW ) ) + { + var = vertComp->getElement( RT_TANGENTW ); + var->setName( "tangentW" ); + } else if ( element.isSemantic( GFXSemantic::BINORMAL ) ) { var = vertComp->getElement( RT_BINORMAL ); @@ -152,7 +159,7 @@ ShaderComponent* ShaderGenComponentFactoryGLSL::createVertexInputConnector( cons if ( !var ) continue; - var->setStructName( "" ); + var->setStructName( "IN" ); var->setType( typeToString( element.getType() ) ); } diff --git a/Engine/source/shaderGen/GLSL/shaderGenGLSLInit.cpp b/Engine/source/shaderGen/GLSL/shaderGenGLSLInit.cpp index 1318137bb..03634fa50 100644 --- a/Engine/source/shaderGen/GLSL/shaderGenGLSLInit.cpp +++ b/Engine/source/shaderGen/GLSL/shaderGenGLSLInit.cpp @@ -76,6 +76,8 @@ void _initShaderGenGLSL( ShaderGen *shaderGen ) FEATUREMGR->registerFeature( MFT_ParaboloidVertTransform, new ParaboloidVertTransformGLSL ); FEATUREMGR->registerFeature( MFT_IsSinglePassParaboloid, new NamedFeatureGLSL( "Single Pass Paraboloid" ) ); + FEATUREMGR->registerFeature( MFT_UseInstancing, new NamedFeatureGLSL( "Hardware Instancing" ) ); + FEATUREMGR->registerFeature( MFT_RenderTarget1_Zero, new RenderTargetZeroGLSL ( ShaderFeature::RenderTarget1 ) ); @@ -89,6 +91,10 @@ void _initShaderGenGLSL( ShaderGen *shaderGen ) FEATUREMGR->registerFeature( MFT_ImposterVert, new ImposterVertFeatureGLSL ); + //FEATUREMGR->registerFeature( MFT_LightbufferMRT, new NamedFeatureGLSL( "Lightbuffer MRT" ) ); + //FEATUREMGR->registerFeature( MFT_IsTranslucentZWrite, new NamedFeatureGLSL( "Translucent ZWrite" ) ); + //FEATUREMGR->registerFeature( MFT_InterlacedPrePass, new NamedFeatureGLSL( "Interlaced Pre Pass" ) ); + } MODULE_BEGIN( ShaderGenGLSL ) diff --git a/Engine/source/shaderGen/shaderFeature.h b/Engine/source/shaderGen/shaderFeature.h index a5f0a7d89..f18fae7f9 100644 --- a/Engine/source/shaderGen/shaderFeature.h +++ b/Engine/source/shaderGen/shaderFeature.h @@ -48,6 +48,8 @@ class ShaderFeatureConstHandles { public: + virtual ~ShaderFeatureConstHandles() { } + virtual void init( GFXShader *shader ) = 0; virtual void setConsts( SceneRenderState *state, diff --git a/Engine/source/shaderGen/shaderGen.cpp b/Engine/source/shaderGen/shaderGen.cpp index 6c7775353..5cd18f10c 100644 --- a/Engine/source/shaderGen/shaderGen.cpp +++ b/Engine/source/shaderGen/shaderGen.cpp @@ -389,7 +389,7 @@ void ShaderGen::_printDependencies(Stream &stream) { mPrinter->printLine(stream, "// Dependencies:"); - for( int i = 0; i < dependencies.size(); i++ ) + for( S32 i = 0; i < dependencies.size(); i++ ) dependencies[i]->print( stream ); mPrinter->printLine(stream, ""); diff --git a/Engine/source/sim/actionMap.cpp b/Engine/source/sim/actionMap.cpp index 43169f471..05feff688 100644 --- a/Engine/source/sim/actionMap.cpp +++ b/Engine/source/sim/actionMap.cpp @@ -458,8 +458,12 @@ bool ActionMap::createEventDescriptor(const char* pEventString, EventDescriptor* } // Now we need to map the key string to the proper KEY code from event.h - // - AssertFatal(dStrlen(pObjectString) != 0, "Error, no key was specified!"); + AssertFatal( + dStrlen( pObjectString ) > 0, + "Error, no key was specified!\n" + "Review file 'scripts/client/config.cs' and remove symbols" + " which is not latin. Or delete this file." + ); if (dStrlen(pObjectString) == 1) { diff --git a/Engine/source/sim/netConnection.cpp b/Engine/source/sim/netConnection.cpp index ee1815e82..9bfdce3ee 100644 --- a/Engine/source/sim/netConnection.cpp +++ b/Engine/source/sim/netConnection.cpp @@ -1116,7 +1116,6 @@ void NetConnection::validateSendString(const char *str) void NetConnection::packString(BitStream *stream, const char *str) { - char buf[16]; if(!*str) { stream->writeInt(NullString, 2); @@ -1130,6 +1129,7 @@ void NetConnection::packString(BitStream *stream, const char *str) } if(str[0] == '-' || (str[0] >= '0' && str[0] <= '9')) { + char buf[16]; S32 num = dAtoi(str); dSprintf(buf, sizeof(buf), "%d", num); if(!dStrcmp(buf, str)) diff --git a/Engine/source/sim/netInterface.cpp b/Engine/source/sim/netInterface.cpp index 226bd0ca3..e839d6e64 100644 --- a/Engine/source/sim/netInterface.cpp +++ b/Engine/source/sim/netInterface.cpp @@ -531,7 +531,7 @@ void NetInterface::checkTimeouts() #define F3(x, y, z) (x ^ y ^ z) #define F4(x, y, z) (y ^ (x | ~z)) -inline U32 rotlFixed(U32 x, unsigned int y) +inline U32 rotlFixed(U32 x, U32 y) { return (x >> y) | (x << (32 - y)); } diff --git a/Engine/source/terrain/glsl/terrFeatureGLSL.cpp b/Engine/source/terrain/glsl/terrFeatureGLSL.cpp index c23d4d85d..63bc8cb60 100644 --- a/Engine/source/terrain/glsl/terrFeatureGLSL.cpp +++ b/Engine/source/terrain/glsl/terrFeatureGLSL.cpp @@ -30,22 +30,35 @@ #include "shaderGen/langElement.h" #include "shaderGen/shaderOp.h" #include "shaderGen/featureMgr.h" +#include "shaderGen/shaderGen.h" #include "core/module.h" +namespace +{ + void register_glsl_shader_features_for_terrain(GFXAdapterType type) + { + if(type != OpenGL) + return; + + FEATUREMGR->registerFeature( MFT_TerrainBaseMap, new TerrainBaseMapFeatGLSL ); + FEATUREMGR->registerFeature( MFT_TerrainParallaxMap, new NamedFeatureGLSL( "Terrain Parallax Texture" ) ); + FEATUREMGR->registerFeature( MFT_TerrainDetailMap, new TerrainDetailMapFeatGLSL ); + FEATUREMGR->registerFeature( MFT_TerrainNormalMap, new TerrainNormalMapFeatGLSL ); + FEATUREMGR->registerFeature( MFT_TerrainMacroMap, new TerrainMacroMapFeatGLSL ); + FEATUREMGR->registerFeature( MFT_TerrainLightMap, new TerrainLightMapFeatGLSL ); + FEATUREMGR->registerFeature( MFT_TerrainSideProject, new NamedFeatureGLSL( "Terrain Side Projection" ) ); + FEATUREMGR->registerFeature( MFT_TerrainAdditive, new TerrainAdditiveFeatGLSL ); + } + +}; MODULE_BEGIN( TerrainFeatGLSL ) - MODULE_INIT_AFTER( ShaderGenFeatureMgr ) + MODULE_INIT_AFTER( ShaderGen ) MODULE_INIT - { - FEATUREMGR->registerFeature( MFT_TerrainBaseMap, new TerrainBaseMapFeatGLSL ); - FEATUREMGR->registerFeature( MFT_TerrainParallaxMap, new TerrainParallaxMapFeatGLSL ); - FEATUREMGR->registerFeature( MFT_TerrainDetailMap, new TerrainDetailMapFeatGLSL ); - FEATUREMGR->registerFeature( MFT_TerrainNormalMap, new TerrainNormalMapFeatGLSL ); - FEATUREMGR->registerFeature( MFT_TerrainLightMap, new TerrainLightMapFeatGLSL ); - FEATUREMGR->registerFeature( MFT_TerrainSideProject, new NamedFeatureGLSL( "Terrain Side Projection" ) ); - FEATUREMGR->registerFeature( MFT_TerrainAdditive, new TerrainAdditiveFeatGLSL ); + { + SHADERGEN->getFeatureInitSignal().notify(®ister_glsl_shader_features_for_terrain); } MODULE_END; @@ -68,7 +81,7 @@ Var* TerrainFeatGLSL::_getUniformVar( const char *name, const char *type, Consta Var* TerrainFeatGLSL::_getInDetailCoord( Vector &componentList ) { - String name( String::ToString( "outDetCoord%d", getProcessIndex() ) ); + String name( String::ToString( "detCoord%d", getProcessIndex() ) ); Var *inDet = (Var*)LangElement::find( name ); if ( !inDet ) @@ -77,6 +90,7 @@ Var* TerrainFeatGLSL::_getInDetailCoord( Vector &componentList inDet = connectComp->getElement( RT_TEXCOORD ); inDet->setName( name ); + inDet->setStructName( "IN" ); inDet->setType( "vec4" ); inDet->mapsToSampler = true; } @@ -84,6 +98,25 @@ Var* TerrainFeatGLSL::_getInDetailCoord( Vector &componentList return inDet; } +Var* TerrainFeatGLSL::_getInMacroCoord( Vector &componentList ) +{ + String name( String::ToString( "macroCoord%d", getProcessIndex() ) ); + Var *inDet = (Var*)LangElement::find( name ); + + if ( !inDet ) + { + ShaderConnector *connectComp = dynamic_cast( componentList[C_CONNECTOR] ); + + inDet = connectComp->getElement( RT_TEXCOORD ); + inDet->setName( name ); + inDet->setStructName( "IN" ); + inDet->setType( "vec4" ); + inDet->mapsToSampler = true; + } + + return inDet; +} + Var* TerrainFeatGLSL::_getNormalMapTex() { String name( String::ToString( "normalMap%d", getProcessIndex() ) ); @@ -119,6 +152,24 @@ Var* TerrainFeatGLSL::_getDetailIdStrengthParallax() return detailInfo; } +Var* TerrainFeatGLSL::_getMacroIdStrengthParallax() +{ + String name( String::ToString( "macroIdStrengthParallax%d", getProcessIndex() ) ); + + Var *detailInfo = (Var*)LangElement::find( name ); + if ( !detailInfo ) + { + detailInfo = new Var; + detailInfo->setType( "vec3" ); + detailInfo->setName( name ); + detailInfo->uniform = true; + detailInfo->constSortPos = cspPotentialPrimitive; + } + + return detailInfo; +} + + void TerrainBaseMapFeatGLSL::processVert( Vector &componentList, const MaterialFeatureData &fd ) { @@ -146,7 +197,7 @@ void TerrainBaseMapFeatGLSL::processVert( Vector &componentLis // So instead i fixed this by flipping the base and detail // coord y scale to compensate when rendering. // - meta->addStatement( new GenOp( " @ = @.xyz * vec3( @, @, -@ );\r\n", + meta->addStatement( new GenOp( " @ = @.xyz * float3( @, @, -@ );\r\n", new DecOp( inTex ), inPos, oneOverTerrainSize, oneOverTerrainSize, oneOverTerrainSize ) ); } @@ -155,6 +206,7 @@ void TerrainBaseMapFeatGLSL::processVert( Vector &componentLis // Pass the texture coord to the pixel shader. Var *outTex = connectComp->getElement( RT_TEXCOORD ); outTex->setName( "outTexCoord" ); + outTex->setStructName( "OUT" ); outTex->setType( "vec3" ); outTex->mapsToSampler = true; meta->addStatement( new GenOp( " @.xy = @.xy;\r\n", outTex, inTex ) ); @@ -166,7 +218,7 @@ void TerrainBaseMapFeatGLSL::processVert( Vector &componentLis { Var *inNormal = (Var*)LangElement::find( "normal" ); meta->addStatement( - new GenOp( " @.z = pow( abs( dot( normalize( vec3( @.x, @.y, 0.0 ) ), vec3( 0, 1, 0 ) ) ), 10.0 );\r\n", + new GenOp( " @.z = pow( abs( dot( normalize( float3( @.x, @.y, 0 ) ), float3( 0, 1, 0 ) ) ), 10.0 );\r\n", outTex, inNormal, inNormal ) ); } else @@ -182,7 +234,7 @@ void TerrainBaseMapFeatGLSL::processVert( Vector &componentLis Var *inTangentZ = getVertTexCoord( "tcTangentZ" ); Var *inTanget = new Var( "T", "vec3" ); Var *squareSize = _getUniformVar( "squareSize", "float", cspPass ); - meta->addStatement( new GenOp( " @ = normalize( vec3( @, 0.0, @ ) );\r\n", + meta->addStatement( new GenOp( " @ = normalize( float3( @, 0, @ ) );\r\n", new DecOp( inTanget ), squareSize, inTangentZ ) ); } @@ -190,7 +242,7 @@ void TerrainBaseMapFeatGLSL::processPix( Vector &componentLis const MaterialFeatureData &fd ) { // grab connector texcoord register - Var *texCoord = getInTexCoord( "outTexCoord", "vec3", true, componentList ); + Var *texCoord = getInTexCoord( "texCoord", "vec3", true, componentList ); // We do nothing more if this is a prepass. if ( fd.features.hasFeature( MFT_PrePassConditioner ) ) @@ -209,7 +261,7 @@ void TerrainBaseMapFeatGLSL::processPix( Vector &componentLis Var *baseColor = new Var; baseColor->setType( "vec4" ); baseColor->setName( "baseColor" ); - meta->addStatement( new GenOp( " @ = texture2D( @, @.xy );\r\n", new DecOp( baseColor ), diffuseMap, texCoord ) ); + meta->addStatement( new GenOp( " @ = tex2D( @, @.xy );\r\n", new DecOp( baseColor ), diffuseMap, texCoord ) ); meta->addStatement( new GenOp( " @;\r\n", assignColor( baseColor, Material::Mul ) ) ); output = meta; @@ -228,8 +280,11 @@ ShaderFeature::Resources TerrainBaseMapFeatGLSL::getResources( const MaterialFea } TerrainDetailMapFeatGLSL::TerrainDetailMapFeatGLSL() - : mTerrainDep( "shaders/common/terrain/terrain.glsl" ) + : mTorqueDep( "shaders/common/gl/torque.glsl" ), + mTerrainDep( "shaders/common/terrain/terrain.glsl" ) + { + addDependency( &mTorqueDep ); addDependency( &mTerrainDep ); } @@ -238,13 +293,6 @@ void TerrainDetailMapFeatGLSL::processVert( Vector &component { const U32 detailIndex = getProcessIndex(); - - // If this is a prepass and we don't have a - // matching normal map... we have nothing to do. - if ( fd.features.hasFeature( MFT_PrePassConditioner ) && - !fd.features.hasFeature( MFT_TerrainNormalMap, detailIndex ) ) - return; - // Grab incoming texture coords... the base map feature // made sure this was created. Var *inTex = (Var*)LangElement::find( "texCoord" ); @@ -260,6 +308,26 @@ void TerrainDetailMapFeatGLSL::processVert( Vector &component MultiLine *meta = new MultiLine; + // If we have parallax mapping then make sure we've sent + // the negative view vector to the pixel shader. + if ( fd.features.hasFeature( MFT_TerrainParallaxMap ) && + !LangElement::find( "outNegViewTS" ) ) + { + // Get the object to tangent transform which + // will consume 3 output registers. + Var *objToTangentSpace = getOutObjToTangentSpace( componentList, meta, fd ); + + // Now use a single output register to send the negative + // view vector in tangent space to the pixel shader. + ShaderConnector *connectComp = dynamic_cast( componentList[C_CONNECTOR] ); + Var *outNegViewTS = connectComp->getElement( RT_TEXCOORD ); + outNegViewTS->setName( "outNegViewTS" ); + outNegViewTS->setStructName( "OUT" ); + outNegViewTS->setType( "vec3" ); + meta->addStatement( new GenOp( " @ = tMul( @, float3( @ - @.xyz ) );\r\n", + outNegViewTS, objToTangentSpace, eyePos, inPos ) ); + } + // Get the distance from the eye to this vertex. Var *dist = (Var*)LangElement::find( "dist" ); if ( !dist ) @@ -275,7 +343,8 @@ void TerrainDetailMapFeatGLSL::processVert( Vector &component // grab connector texcoord register ShaderConnector *connectComp = dynamic_cast( componentList[C_CONNECTOR] ); Var *outTex = connectComp->getElement( RT_TEXCOORD ); - outTex->setName( String::ToString( "outDetCoord%d", detailIndex ) ); + outTex->setName( String::ToString( "detCoord%d", detailIndex ) ); + outTex->setStructName( "OUT" ); outTex->setType( "vec4" ); outTex->mapsToSampler = true; @@ -293,7 +362,7 @@ void TerrainDetailMapFeatGLSL::processVert( Vector &component // its scale is flipped to correct for the non negative y // in texCoord. // - // See TerrainBaseMapFeatHLSL::processVert(). + // See TerrainBaseMapFeatGLSL::processVert(). // meta->addStatement( new GenOp( " @.xyz = @ * @.xyx;\r\n", outTex, inTex, detScaleAndFade ) ); @@ -308,17 +377,30 @@ void TerrainDetailMapFeatGLSL::processPix( Vector &component const MaterialFeatureData &fd ) { const U32 detailIndex = getProcessIndex(); + Var *inTex = getVertTexCoord( "texCoord" ); - // If this is a prepass and we don't have a - // matching normal map... we have nothing to do. - if ( fd.features.hasFeature( MFT_PrePassConditioner ) && - !fd.features.hasFeature( MFT_TerrainNormalMap, detailIndex ) ) - return; - - Var *inTex = getVertTexCoord( "outTexCoord" ); - MultiLine *meta = new MultiLine; + // We need the negative tangent space view vector + // as in parallax mapping we step towards the camera. + Var *negViewTS = (Var*)LangElement::find( "negViewTS" ); + if ( !negViewTS && + fd.features.hasFeature( MFT_TerrainParallaxMap ) ) + { + Var *inNegViewTS = (Var*)LangElement::find( "outNegViewTS" ); + if ( !inNegViewTS ) + { + ShaderConnector *connectComp = dynamic_cast( componentList[C_CONNECTOR] ); + inNegViewTS = connectComp->getElement( RT_TEXCOORD ); + inNegViewTS->setName( "outNegViewTS" ); + inNegViewTS->setStructName( "IN" ); + inNegViewTS->setType( "vec3" ); + } + + negViewTS = new Var( "negViewTS", "vec3" ); + meta->addStatement( new GenOp( " @ = normalize( @ );\r\n", new DecOp( negViewTS ), inNegViewTS ) ); + } + // Get the layer samples. Var *layerSample = (Var*)LangElement::find( "layerSample" ); if ( !layerSample ) @@ -336,7 +418,7 @@ void TerrainDetailMapFeatGLSL::processPix( Vector &component layerTex->constNum = Var::getTexUnitNum(); // Read the layer texture to get the samples. - meta->addStatement( new GenOp( " @ = round( texture2D( @, @.xy ) * 255.0f );\r\n", + meta->addStatement( new GenOp( " @ = round( tex2D( @, @.xy ) * 255.0f );\r\n", new DecOp( layerSample ), layerTex, inTex ) ); } @@ -372,17 +454,43 @@ void TerrainDetailMapFeatGLSL::processPix( Vector &component blendTotal = new Var; blendTotal->setName( "blendTotal" ); blendTotal->setType( "float" ); - meta->addStatement( new GenOp( " @ = 0.0;\r\n", new DecOp( blendTotal ) ) ); + meta->addStatement( new GenOp( " @ = 0;\r\n", new DecOp( blendTotal ) ) ); } // Add to the blend total. - meta->addStatement( new GenOp( " @ += @;\r\n", blendTotal, detailBlend ) ); - //meta->addStatement( new GenOp( " @ += @ * @.y * @.w;\r\n", - //blendTotal, detailBlend, detailInfo, inDet ) ); + meta->addStatement( new GenOp( " @ = max( @, @ );\r\n", blendTotal, blendTotal, detailBlend ) ); - // Nothing more to do for a detail texture in prepass. + // If we had a parallax feature... then factor in the parallax + // amount so that it fades out with the layer blending. + if ( fd.features.hasFeature( MFT_TerrainParallaxMap, detailIndex ) ) + { + // Get the rest of our inputs. + Var *normalMap = _getNormalMapTex(); + + // Call the library function to do the rest. + meta->addStatement( new GenOp( " @.xy += parallaxOffset( @, @.xy, @, @.z * @ );\r\n", + inDet, normalMap, inDet, negViewTS, detailInfo, detailBlend ) ); + } + + // If this is a prepass then we skip color. if ( fd.features.hasFeature( MFT_PrePassConditioner ) ) { + // Check to see if we have a gbuffer normal. + Var *gbNormal = (Var*)LangElement::find( "gbNormal" ); + + // If we have a gbuffer normal and we don't have a + // normal map feature then we need to lerp in a + // default normal else the normals below this layer + // will show thru. + if ( gbNormal && + !fd.features.hasFeature( MFT_TerrainNormalMap, detailIndex ) ) + { + Var *viewToTangent = getInViewToTangent( componentList ); + + meta->addStatement( new GenOp( " @ = lerp( @, tGetMatrix3Row(@, 2), min( @, @.w ) );\r\n", + gbNormal, gbNormal, viewToTangent, detailBlend, inDet ) ); + } + output = meta; return; } @@ -407,6 +515,7 @@ void TerrainDetailMapFeatGLSL::processPix( Vector &component // If we're using SM 3.0 then take advantage of // dynamic branching to skip layers per-pixel. + if ( GFX->getPixelShaderVersion() >= 3.0f ) meta->addStatement( new GenOp( " if ( @ > 0.0f )\r\n", detailBlend ) ); @@ -421,12 +530,12 @@ void TerrainDetailMapFeatGLSL::processPix( Vector &component // if ( fd.features.hasFeature( MFT_TerrainSideProject, detailIndex ) ) { - meta->addStatement( new GenOp( " @ = ( mix( texture2D( @, @.yz ), texture2D( @, @.xz ), @.z ) * 2.0 ) - 1.0;\r\n", + meta->addStatement( new GenOp( " @ = ( lerp( tex2D( @, @.yz ), tex2D( @, @.xz ), @.z ) * 2.0 ) - 1.0;\r\n", detailColor, detailMap, inDet, detailMap, inDet, inTex ) ); } else { - meta->addStatement( new GenOp( " @ = ( texture2D( @, @.xy ) * 2.0 ) - 1.0;\r\n", + meta->addStatement( new GenOp( " @ = ( tex2D( @, @.xy ) * 2.0 ) - 1.0;\r\n", detailColor, detailMap, inDet ) ); } @@ -436,7 +545,7 @@ void TerrainDetailMapFeatGLSL::processPix( Vector &component Var *baseColor = (Var*)LangElement::find( "baseColor" ); Var *outColor = (Var*)LangElement::find( "col" ); - meta->addStatement( new GenOp( " @ = mix( @, @ + @, @ );\r\n", + meta->addStatement( new GenOp( " @ = lerp( @, @ + @, @ );\r\n", outColor, outColor, baseColor, detailColor, detailBlend ) ); meta->addStatement( new GenOp( " }\r\n" ) ); @@ -448,28 +557,293 @@ ShaderFeature::Resources TerrainDetailMapFeatGLSL::getResources( const MaterialF { Resources res; + if ( getProcessIndex() == 0 ) + { + // If this is the first detail pass then we + // samples from the layer tex. + res.numTex += 1; + + // If this material also does parallax then it + // will generate the negative view vector and the + // worldToTanget transform. + if ( fd.features.hasFeature( MFT_TerrainParallaxMap ) ) + res.numTexReg += 4; + } + + // If this isn't the prepass then we sample + // from the detail texture for diffuse coloring. + if ( !fd.features.hasFeature( MFT_PrePassConditioner ) ) + res.numTex += 1; + + // If we have parallax for this layer then we'll also + // be sampling the normal map for the parallax heightmap. + if ( fd.features.hasFeature( MFT_TerrainParallaxMap, getProcessIndex() ) ) + res.numTex += 1; + + // Finally we always send the detail texture + // coord to the pixel shader. + res.numTexReg += 1; + + return res; +} + + +TerrainMacroMapFeatGLSL::TerrainMacroMapFeatGLSL() + : mTorqueDep( "shaders/common/gl/torque.glsl" ), + mTerrainDep( "shaders/common/terrain/terrain.glsl" ) + +{ + addDependency( &mTorqueDep ); + addDependency( &mTerrainDep ); +} + + +void TerrainMacroMapFeatGLSL::processVert( Vector &componentList, + const MaterialFeatureData &fd ) +{ + const U32 detailIndex = getProcessIndex(); + + // Grab incoming texture coords... the base map feature + // made sure this was created. + Var *inTex = (Var*)LangElement::find( "texCoord" ); + AssertFatal( inTex, "The texture coord is missing!" ); + + // Grab the input position. + Var *inPos = (Var*)LangElement::find( "inPosition" ); + if ( !inPos ) + inPos = (Var*)LangElement::find( "position" ); + + // Get the object space eye position. + Var *eyePos = _getUniformVar( "eyePos", "vec3", cspPotentialPrimitive ); + + MultiLine *meta = new MultiLine; + + // Get the distance from the eye to this vertex. + Var *dist = (Var*)LangElement::find( "macroDist" ); + if ( !dist ) + { + dist = new Var; + dist->setType( "float" ); + dist->setName( "macroDist" ); + + meta->addStatement( new GenOp( " @ = distance( @.xyz, @ );\r\n", + new DecOp( dist ), inPos, eyePos ) ); + } + + // grab connector texcoord register + ShaderConnector *connectComp = dynamic_cast( componentList[C_CONNECTOR] ); + Var *outTex = connectComp->getElement( RT_TEXCOORD ); + outTex->setName( String::ToString( "macroCoord%d", detailIndex ) ); + outTex->setStructName( "OUT" ); + outTex->setType( "vec4" ); + outTex->mapsToSampler = true; + + // Get the detail scale and fade info. + Var *detScaleAndFade = new Var; + detScaleAndFade->setType( "vec4" ); + detScaleAndFade->setName( String::ToString( "macroScaleAndFade%d", detailIndex ) ); + detScaleAndFade->uniform = true; + detScaleAndFade->constSortPos = cspPotentialPrimitive; + + // Setup the detail coord. + meta->addStatement( new GenOp( " @.xyz = @ * @.xyx;\r\n", outTex, inTex, detScaleAndFade ) ); + + // And sneak the detail fade thru the w detailCoord. + meta->addStatement( new GenOp( " @.w = clamp( ( @.z - @ ) * @.w, 0.0, 1.0 );\r\n", + outTex, detScaleAndFade, dist, detScaleAndFade ) ); + + output = meta; +} + + +void TerrainMacroMapFeatGLSL::processPix( Vector &componentList, + const MaterialFeatureData &fd ) +{ + const U32 detailIndex = getProcessIndex(); + Var *inTex = getVertTexCoord( "texCoord" ); + + MultiLine *meta = new MultiLine; + + // We need the negative tangent space view vector + // as in parallax mapping we step towards the camera. + Var *negViewTS = (Var*)LangElement::find( "negViewTS" ); + if ( !negViewTS && + fd.features.hasFeature( MFT_TerrainParallaxMap ) ) + { + Var *inNegViewTS = (Var*)LangElement::find( "outNegViewTS" ); + if ( !inNegViewTS ) + { + ShaderConnector *connectComp = dynamic_cast( componentList[C_CONNECTOR] ); + inNegViewTS = connectComp->getElement( RT_TEXCOORD ); + inNegViewTS->setName( "outNegViewTS" ); + inNegViewTS->setStructName( "IN" ); + inNegViewTS->setType( "vec3" ); + } + + negViewTS = new Var( "negViewTS", "vec3" ); + meta->addStatement( new GenOp( " @ = normalize( @ );\r\n", new DecOp( negViewTS ), inNegViewTS ) ); + } + + // Get the layer samples. + Var *layerSample = (Var*)LangElement::find( "layerSample" ); + if ( !layerSample ) + { + layerSample = new Var; + layerSample->setType( "vec4" ); + layerSample->setName( "layerSample" ); + + // Get the layer texture var + Var *layerTex = new Var; + layerTex->setType( "sampler2D" ); + layerTex->setName( "macrolayerTex" ); + layerTex->uniform = true; + layerTex->sampler = true; + layerTex->constNum = Var::getTexUnitNum(); + + // Read the layer texture to get the samples. + meta->addStatement( new GenOp( " @ = round( tex2D( @, @.xy ) * 255.0f );\r\n", + new DecOp( layerSample ), layerTex, inTex ) ); + } + + Var *layerSize = (Var*)LangElement::find( "layerSize" ); + if ( !layerSize ) + { + layerSize = new Var; + layerSize->setType( "float" ); + layerSize->setName( "layerSize" ); + layerSize->uniform = true; + layerSize->constSortPos = cspPass; + } + + // Grab the incoming detail coord. + Var *inDet = _getInMacroCoord( componentList ); + + // Get the detail id. + Var *detailInfo = _getMacroIdStrengthParallax(); + + // Create the detail blend var. + Var *detailBlend = new Var; + detailBlend->setType( "float" ); + detailBlend->setName( String::ToString( "macroBlend%d", detailIndex ) ); + + // Calculate the blend for this detail texture. + meta->addStatement( new GenOp( " @ = calcBlend( @.x, @.xy, @, @ );\r\n", + new DecOp( detailBlend ), detailInfo, inTex, layerSize, layerSample ) ); + + // Get a var and accumulate the blend amount. + Var *blendTotal = (Var*)LangElement::find( "blendTotal" ); + if ( !blendTotal ) + { + blendTotal = new Var; + //blendTotal->setName( "blendTotal" ); + blendTotal->setName( "blendTotal" ); + blendTotal->setType( "float" ); + meta->addStatement( new GenOp( " @ = 0;\r\n", new DecOp( blendTotal ) ) ); + } + + // Add to the blend total. + meta->addStatement( new GenOp( " @ = max( @, @ );\r\n", blendTotal, blendTotal, detailBlend ) ); + + // If this is a prepass then we skip color. if ( fd.features.hasFeature( MFT_PrePassConditioner ) ) { - // If this is a prepass and we don't have a - // matching normal map... we use no resources. - if ( !fd.features.hasFeature( MFT_TerrainNormalMap, getProcessIndex() ) ) - return res; + // Check to see if we have a gbuffer normal. + Var *gbNormal = (Var*)LangElement::find( "gbNormal" ); - // If this is the first matching normal map then - // it also samples from the layer tex. - if ( !fd.features.hasFeature( MFT_TerrainNormalMap, getProcessIndex() - 1 ) ) - res.numTex += 1; + // If we have a gbuffer normal and we don't have a + // normal map feature then we need to lerp in a + // default normal else the normals below this layer + // will show thru. + if ( gbNormal && + !fd.features.hasFeature( MFT_TerrainNormalMap, detailIndex ) ) + { + Var *viewToTangent = getInViewToTangent( componentList ); + + meta->addStatement( new GenOp( " @ = lerp( @, tGetMatrix3Row(@, 2), min( @, @.w ) );\r\n", + gbNormal, gbNormal, viewToTangent, detailBlend, inDet ) ); + } + + output = meta; + return; + } + + Var *detailColor = (Var*)LangElement::find( "macroColor" ); + if ( !detailColor ) + { + detailColor = new Var; + detailColor->setType( "vec4" ); + detailColor->setName( "macroColor" ); + meta->addStatement( new GenOp( " @;\r\n", new DecOp( detailColor ) ) ); + } + + // Get the detail texture. + Var *detailMap = new Var; + detailMap->setType( "sampler2D" ); + detailMap->setName( String::ToString( "macroMap%d", detailIndex ) ); + detailMap->uniform = true; + detailMap->sampler = true; + detailMap->constNum = Var::getTexUnitNum(); // used as texture unit num here + + // If we're using SM 3.0 then take advantage of + // dynamic branching to skip layers per-pixel. + if ( GFX->getPixelShaderVersion() >= 3.0f ) + meta->addStatement( new GenOp( " if ( @ > 0.0f )\r\n", detailBlend ) ); + + meta->addStatement( new GenOp( " {\r\n" ) ); + + // Note that we're doing the standard greyscale detail + // map technique here which can darken and lighten the + // diffuse texture. + // + // We take two color samples and lerp between them for + // side projection layers... else a single sample. + // + if ( fd.features.hasFeature( MFT_TerrainSideProject, detailIndex ) ) + { + meta->addStatement( new GenOp( " @ = ( lerp( tex2D( @, @.yz ), tex2D( @, @.xz ), @.z ) * 2.0 ) - 1.0;\r\n", + detailColor, detailMap, inDet, detailMap, inDet, inTex ) ); } else { - // If this is the first detail pass then it - // also samples from the layer tex. - if ( !fd.features.hasFeature( MFT_TerrainDetailMap, getProcessIndex() - 1 ) ) - res.numTex += 1; - - res.numTex += 1; + meta->addStatement( new GenOp( " @ = ( tex2D( @, @.xy ) * 2.0 ) - 1.0;\r\n", + detailColor, detailMap, inDet ) ); } + meta->addStatement( new GenOp( " @ *= @.y * @.w;\r\n", + detailColor, detailInfo, inDet ) ); + + Var *baseColor = (Var*)LangElement::find( "baseColor" ); + Var *outColor = (Var*)LangElement::find( "col" ); + + meta->addStatement( new GenOp( " @ = lerp( @, @ + @, @ );\r\n", + outColor, outColor, outColor, detailColor, detailBlend ) ); + //outColor, outColor, baseColor, detailColor, detailBlend ) ); + + meta->addStatement( new GenOp( " }\r\n" ) ); + + output = meta; +} + + + +ShaderFeature::Resources TerrainMacroMapFeatGLSL::getResources( const MaterialFeatureData &fd ) +{ + Resources res; + + if ( getProcessIndex() == 0 ) + { + // If this is the first detail pass then we + // samples from the layer tex. + res.numTex += 1; + } + + // If this isn't the prepass then we sample + // from the detail texture for diffuse coloring. + if ( !fd.features.hasFeature( MFT_PrePassConditioner ) ) + res.numTex += 1; + + // Finally we always send the detail texture + // coord to the pixel shader. res.numTexReg += 1; return res; @@ -510,7 +884,7 @@ void TerrainNormalMapFeatGLSL::processPix( Vector &component gbNormal = new Var; gbNormal->setName( "gbNormal" ); gbNormal->setType( "vec3" ); - meta->addStatement( new GenOp( " @ = @[2];\r\n", new DecOp( gbNormal ), viewToTangent ) ); + meta->addStatement( new GenOp( " @ = tGetMatrix3Row(@, 2);\r\n", new DecOp( gbNormal ), viewToTangent ) ); } const U32 normalIndex = getProcessIndex(); @@ -520,7 +894,6 @@ void TerrainNormalMapFeatGLSL::processPix( Vector &component // If we're using SM 3.0 then take advantage of // dynamic branching to skip layers per-pixel. - if ( GFX->getPixelShaderVersion() >= 3.0f ) meta->addStatement( new GenOp( " if ( @ > 0.0f )\r\n", detailBlend ) ); @@ -531,7 +904,7 @@ void TerrainNormalMapFeatGLSL::processPix( Vector &component /// Get the texture coord. Var *inDet = _getInDetailCoord( componentList ); - Var *inTex = getVertTexCoord( "outTexCoord" ); + Var *inTex = getVertTexCoord( "texCoord" ); // Sample the normal map. // @@ -540,11 +913,11 @@ void TerrainNormalMapFeatGLSL::processPix( Vector &component LangElement *texOp; if ( fd.features.hasFeature( MFT_TerrainSideProject, normalIndex ) ) { - texOp = new GenOp( "mix( texture2D( @, @.yz ), texture2D( @, @.xz ), @.z )", + texOp = new GenOp( "lerp( tex2D( @, @.yz ), tex2D( @, @.xz ), @.z )", normalMap, inDet, normalMap, inDet, inTex ); } else - texOp = new GenOp( "texture2D(@, @.xy)", normalMap, inDet ); + texOp = new GenOp( "tex2D(@, @.xy)", normalMap, inDet ); // create bump normal Var *bumpNorm = new Var; @@ -556,7 +929,7 @@ void TerrainNormalMapFeatGLSL::processPix( Vector &component // Normalize is done later... // Note: The reverse mul order is intentional. Affine matrix. - meta->addStatement( new GenOp( " @ = mix( @, @.xyz * @, min( @, @.w ) );\r\n", + meta->addStatement( new GenOp( " @ = lerp( @, tMul( @.xyz, @ ), min( @, @.w ) );\r\n", gbNormal, gbNormal, bumpNorm, viewToTangent, detailBlend, inDet ) ); // End the conditional block. @@ -578,9 +951,11 @@ ShaderFeature::Resources TerrainNormalMapFeatGLSL::getResources( const MaterialF // We only need to process normals during the prepass. if ( fd.features.hasFeature( MFT_PrePassConditioner ) ) { - // If this is the first normal map then it - // will generate the worldToTanget transform. - if ( !fd.features.hasFeature( MFT_TerrainNormalMap, getProcessIndex() - 1 ) ) + // If this is the first normal map and there + // are no parallax features then we will + // generate the worldToTanget transform. + if ( !fd.features.hasFeature( MFT_TerrainParallaxMap ) && + ( getProcessIndex() == 0 || !fd.features.hasFeature( MFT_TerrainNormalMap, getProcessIndex() - 1 ) ) ) res.numTexReg = 3; res.numTex = 1; @@ -589,100 +964,11 @@ ShaderFeature::Resources TerrainNormalMapFeatGLSL::getResources( const MaterialF return res; } -TerrainParallaxMapFeatGLSL::TerrainParallaxMapFeatGLSL() - : mIncludeDep( "shaders/common/gl/torque.glsl" ) -{ - addDependency( &mIncludeDep ); -} - -void TerrainParallaxMapFeatGLSL::processVert( Vector &componentList, - const MaterialFeatureData &fd ) -{ - if ( LangElement::find( "outNegViewTS" ) ) - return; - - MultiLine *meta = new MultiLine; - - // Grab the input position. - Var *inPos = (Var*)LangElement::find( "inPosition" ); - if ( !inPos ) - inPos = (Var*)LangElement::find( "position" ); - - // Get the object space eye position and the - // object to tangent transform. - Var *eyePos = _getUniformVar( "eyePos", "vec3" , cspPotentialPrimitive ); - Var *objToTangentSpace = getOutObjToTangentSpace( componentList, meta,fd ); - - // Now send the negative view vector in tangent space to the pixel shader. - ShaderConnector *connectComp = dynamic_cast( componentList[C_CONNECTOR] ); - Var *outNegViewTS = connectComp->getElement( RT_TEXCOORD ); - outNegViewTS->setName( "outNegViewTS" ); - outNegViewTS->setType( "vec3" ); - meta->addStatement( new GenOp( " @ = @ * vec3( @ - @.xyz );\r\n", - outNegViewTS, objToTangentSpace, eyePos, inPos ) ); - - output = meta; -} - -void TerrainParallaxMapFeatGLSL::processPix( Vector &componentList, - const MaterialFeatureData &fd ) -{ - MultiLine *meta = new MultiLine; - - ShaderConnector *connectComp = dynamic_cast( componentList[C_CONNECTOR] ); - - // We need the negative tangent space view vector - // as in parallax mapping we step towards the camera. - Var *negViewTS = (Var*)LangElement::find( "negViewTS" ); - if ( !negViewTS ) - { - Var *inNegViewTS = (Var*)LangElement::find( "outNegViewTS" ); - if ( !inNegViewTS ) - { - inNegViewTS = connectComp->getElement( RT_TEXCOORD ); - inNegViewTS->setName( "outNegViewTS" ); - inNegViewTS->setType( "vec3" ); - } - - negViewTS = new Var( "negViewTS", "vec3" ); - meta->addStatement( new GenOp( " @ = normalize( @ );\r\n", new DecOp( negViewTS ), inNegViewTS ) ); - } - - // Get the rest of our inputs. - Var *detailInfo = _getDetailIdStrengthParallax(); - Var *normalMap = _getNormalMapTex(); - Var *texCoord = _getInDetailCoord( componentList ); - - // Call the library function to do the rest. - meta->addStatement( new GenOp( " @.xy += parallaxOffset( @, @.xy, @, @.z );\r\n", - texCoord, normalMap, texCoord, negViewTS, detailInfo ) ); - - output = meta; -} - -ShaderFeature::Resources TerrainParallaxMapFeatGLSL::getResources( const MaterialFeatureData &fd ) -{ - Resources res; - - // If this is the first parallax feature then - // it will generate the tangetEye vector and - // the worldToTanget transform. - if ( getProcessIndex() == 0 || !fd.features.hasFeature( MFT_TerrainParallaxMap, getProcessIndex() - 1 ) ) - res.numTexReg = 4; - - // If this isn't the prepass then we will - // be adding a normal map. - if ( !fd.features.hasFeature( MFT_PrePassConditioner ) ) - res.numTex = 1; - - return res; -} - void TerrainLightMapFeatGLSL::processPix( Vector &componentList, const MaterialFeatureData &fd ) { // grab connector texcoord register - Var *inTex = (Var*)LangElement::find( "outTexCoord" ); + Var *inTex = (Var*)LangElement::find( "texCoord" ); if ( !inTex ) return; @@ -694,13 +980,23 @@ void TerrainLightMapFeatGLSL::processPix( Vector &componentLis lightMap->sampler = true; lightMap->constNum = Var::getTexUnitNum(); - // Create a 'lightMask' value which is read by - // RTLighting to mask out the directional lighting. - Var *lightMask = new Var; - lightMask->setType( "vec3" ); - lightMask->setName( "lightMask" ); + MultiLine *meta = new MultiLine; - output = new GenOp( " @ = texture2D( @, @.xy ).rgb;\r\n", new DecOp( lightMask ), lightMap, inTex ); + // Find or create the lightMask value which is read by + // RTLighting to mask out the lights. + // + // The first light is always the sunlight so we apply + // the shadow mask to only the first channel. + // + Var *lightMask = (Var*)LangElement::find( "lightMask" ); + if ( !lightMask ) + { + lightMask = new Var( "lightMask", "vec4" ); + meta->addStatement( new GenOp( " @ = vec4(1);\r\n", new DecOp( lightMask ) ) ); + } + + meta->addStatement( new GenOp( " @[0] = tex2D( @, @.xy ).r;\r\n", lightMask, lightMap, inTex ) ); + output = meta; } ShaderFeature::Resources TerrainLightMapFeatGLSL::getResources( const MaterialFeatureData &fd ) @@ -721,7 +1017,7 @@ void TerrainAdditiveFeatGLSL::processPix( Vector &componentLis MultiLine *meta = new MultiLine; - meta->addStatement( new GenOp( " if ( @ - 0.0001 < 0.0 ) discard;\r\n", blendTotal ) ); + meta->addStatement( new GenOp( " clip( @ - 0.0001 );\r\n", blendTotal ) ); meta->addStatement( new GenOp( " @.a = @;\r\n", color, blendTotal ) ); output = meta; diff --git a/Engine/source/terrain/glsl/terrFeatureGLSL.h b/Engine/source/terrain/glsl/terrFeatureGLSL.h index c181ef493..790a8a342 100644 --- a/Engine/source/terrain/glsl/terrFeatureGLSL.h +++ b/Engine/source/terrain/glsl/terrFeatureGLSL.h @@ -30,6 +30,7 @@ #include "shaderGen/langElement.h" #endif + /// A shared base class for terrain features which /// includes some helper functions. class TerrainFeatGLSL : public ShaderFeatureGLSL @@ -38,14 +39,18 @@ protected: Var* _getInDetailCoord(Vector &componentList ); + Var* _getInMacroCoord(Vector &componentList ); + Var* _getNormalMapTex(); static Var* _getUniformVar( const char *name, const char *type, ConstantSortPosition csp ); Var* _getDetailIdStrengthParallax(); + Var* _getMacroIdStrengthParallax(); }; + class TerrainBaseMapFeatGLSL : public TerrainFeatGLSL { public: @@ -61,10 +66,12 @@ public: virtual String getName() { return "Terrain Base Texture"; } }; + class TerrainDetailMapFeatGLSL : public TerrainFeatGLSL { protected: + ShaderIncludeDependency mTorqueDep; ShaderIncludeDependency mTerrainDep; public: @@ -83,10 +90,17 @@ public: }; -class TerrainNormalMapFeatGLSL : public TerrainFeatGLSL +class TerrainMacroMapFeatGLSL : public TerrainFeatGLSL { +protected: + + ShaderIncludeDependency mTorqueDep; + ShaderIncludeDependency mTerrainDep; + public: + TerrainMacroMapFeatGLSL(); + virtual void processVert( Vector &componentList, const MaterialFeatureData &fd ); @@ -95,19 +109,14 @@ public: virtual Resources getResources( const MaterialFeatureData &fd ); - virtual String getName() { return "Terrain Normal Texture"; } + virtual String getName() { return "Terrain Macro Texture"; } }; -class TerrainParallaxMapFeatGLSL : public TerrainFeatGLSL + +class TerrainNormalMapFeatGLSL : public TerrainFeatGLSL { -protected: - - ShaderIncludeDependency mIncludeDep; - public: - TerrainParallaxMapFeatGLSL(); - virtual void processVert( Vector &componentList, const MaterialFeatureData &fd ); @@ -116,7 +125,7 @@ public: virtual Resources getResources( const MaterialFeatureData &fd ); - virtual String getName() { return "Terrain Parallax Texture"; } + virtual String getName() { return "Terrain Normal Texture"; } }; class TerrainLightMapFeatGLSL : public TerrainFeatGLSL diff --git a/Engine/source/terrain/hlsl/terrFeatureHLSL.cpp b/Engine/source/terrain/hlsl/terrFeatureHLSL.cpp index f7d2c740a..6c94e0743 100644 --- a/Engine/source/terrain/hlsl/terrFeatureHLSL.cpp +++ b/Engine/source/terrain/hlsl/terrFeatureHLSL.cpp @@ -800,7 +800,7 @@ void TerrainMacroMapFeatHLSL::processPix( Vector &componentL meta->addStatement( new GenOp( " @ *= @.y * @.w;\r\n", detailColor, detailInfo, inDet ) ); - Var *baseColor = (Var*)LangElement::find( "baseColor" ); + //Var *baseColor = (Var*)LangElement::find( "baseColor" ); Var *outColor = (Var*)LangElement::find( "col" ); meta->addStatement( new GenOp( " @ = lerp( @, @ + @, @ );\r\n", diff --git a/Engine/source/terrain/terrCell.cpp b/Engine/source/terrain/terrCell.cpp index dac6c910a..a0478ed77 100644 --- a/Engine/source/terrain/terrCell.cpp +++ b/Engine/source/terrain/terrCell.cpp @@ -849,7 +849,7 @@ void TerrCell::_updateMaterials() if ( index == U8_MAX || index > 63 ) continue; - mMaterials |= (U64)(1<point; - for (int i = 0; i < 4 ; i++,pos++) { + for (S32 i = 0; i < 4 ; i++,pos++) { S32 dx = i >> 1; S32 dy = dx ^ (i & 1); pos->x = (F32)((x + dx) * mSquareSize); @@ -562,7 +562,7 @@ bool TerrainBlock::buildPolyList(PolyListContext context, AbstractPolyList* poly // Add the missing points U32 vi[5]; - for (int i = 0; i < 4 ; i++) + for (S32 i = 0; i < 4 ; i++) { S32 dx = i >> 1; S32 dy = dx ^ (i & 1); @@ -669,10 +669,10 @@ bool TerrainBlock::castRayI(const Point3F &start, const Point3F &end, RayInfo *i Point3F pStart(start.x * invBlockWorldSize, start.y * invBlockWorldSize, start.z); Point3F pEnd(end.x * invBlockWorldSize, end.y * invBlockWorldSize, end.z); - int blockX = (S32)mFloor(pStart.x); - int blockY = (S32)mFloor(pStart.y); + S32 blockX = (S32)mFloor(pStart.x); + S32 blockY = (S32)mFloor(pStart.y); - int dx, dy; + S32 dx, dy; F32 invDeltaX; if(pEnd.x == pStart.x) @@ -904,7 +904,7 @@ bool TerrainBlock::castRayBlock( const Point3F &pStart, } continue; } - int subSqWidth = 1 << (level - 1); + S32 subSqWidth = 1 << (level - 1); F32 xIntercept = (blockPos.x + subSqWidth) * invBlockSize; F32 xInt = calcInterceptX(pStart.x, invDeltaX, xIntercept); F32 yIntercept = (blockPos.y + subSqWidth) * invBlockSize; diff --git a/Engine/source/terrain/terrRender.cpp b/Engine/source/terrain/terrRender.cpp index 5d7146fec..4b03ac812 100644 --- a/Engine/source/terrain/terrRender.cpp +++ b/Engine/source/terrain/terrRender.cpp @@ -62,7 +62,7 @@ GFX_ImplementTextureProfile( TerrainLayerTexProfile, GFXTextureProfile::DiffuseMap, GFXTextureProfile::PreserveSize | GFXTextureProfile::Dynamic, - GFXTextureProfile::None ); + GFXTextureProfile::NONE ); void TerrainBlock::_onFlushMaterials() diff --git a/Engine/source/ts/arch/tsMeshIntrinsics.sse.cpp b/Engine/source/ts/arch/tsMeshIntrinsics.sse.cpp index c83add0a1..1e343ac23 100644 --- a/Engine/source/ts/arch/tsMeshIntrinsics.sse.cpp +++ b/Engine/source/ts/arch/tsMeshIntrinsics.sse.cpp @@ -38,10 +38,10 @@ void zero_vert_normal_bulk_SSE(const dsize_t count, U8 * __restrict const outPtr vMask = _mm_load_ps((const F32*)&_point3f_zero_mask); // pre-populate cache - for(int i = 0; i < 8; i++) + for(S32 i = 0; i < 8; i++) _mm_prefetch(reinterpret_cast(outData + outStride * i), _MM_HINT_T0); - for(int i = 0; i < count; i++) + for(S32 i = 0; i < count; i++) { TSMesh::__TSMeshVertexBase *curElem = reinterpret_cast(outData); @@ -102,13 +102,13 @@ void m_matF_x_BatchedVertWeightList_SSE(const MatrixF &mat, // pre-populate cache const TSSkinMesh::BatchData::BatchedVertWeight &firstElem = batch[0]; - for(int i = 0; i < 8; i++) + for(S32 i = 0; i < 8; i++) { _mm_prefetch(reinterpret_cast(iPtr + inStride * i), _MM_HINT_T0); _mm_prefetch(reinterpret_cast(outPtr + outStride * (i + firstElem.vidx)), _MM_HINT_T0); } - for(register int i = 0; i < count; i++) + for(register S32 i = 0; i < count; i++) { const TSSkinMesh::BatchData::BatchedVertWeight &inElem = batch[i]; TSMesh::__TSMeshVertexBase *outElem = reinterpret_cast(outPtr + inElem.vidx * outStride); diff --git a/Engine/source/ts/arch/tsMeshIntrinsics.sse4.cpp b/Engine/source/ts/arch/tsMeshIntrinsics.sse4.cpp index 8dba501c5..9aba0f027 100644 --- a/Engine/source/ts/arch/tsMeshIntrinsics.sse4.cpp +++ b/Engine/source/ts/arch/tsMeshIntrinsics.sse4.cpp @@ -46,13 +46,13 @@ void m_matF_x_BatchedVertWeightList_SSE4(const MatrixF &mat, // pre-populate cache const TSSkinMesh::BatchData::BatchedVertWeight &firstElem = batch[0]; - for(int i = 0; i < 8; i++) + for(S32 i = 0; i < 8; i++) { _mm_prefetch(reinterpret_cast(iPtr + inStride * i), _MM_HINT_T0); _mm_prefetch(reinterpret_cast(outPtr + outStride * (i + firstElem.vidx)), _MM_HINT_T0); } - for(int i = 0; i < count; i++) + for(S32 i = 0; i < count; i++) { const TSSkinMesh::BatchData::BatchedVertWeight &inElem = batch[i]; TSMesh::__TSMeshVertexBase *outElem = reinterpret_cast(outPtr + inElem.vidx * outStride); diff --git a/Engine/source/ts/collada/colladaAppMesh.cpp b/Engine/source/ts/collada/colladaAppMesh.cpp index 1b58140e5..83c0f207c 100644 --- a/Engine/source/ts/collada/colladaAppMesh.cpp +++ b/Engine/source/ts/collada/colladaAppMesh.cpp @@ -179,7 +179,7 @@ private: const domVertices* vertices = daeSafeCast(element); // Search for the input with the desired semantic const char* semantic = SourceTypeToSemantic( type ); - for (int iInput = 0; iInput < vertices->getInput_array().getCount(); iInput++) + for (S32 iInput = 0; iInput < vertices->getInput_array().getCount(); iInput++) { domInputLocal* input = vertices->getInput_array().get(iInput); if (dStrEqual(input->getSemantic(), semantic)) @@ -230,12 +230,12 @@ public: *maxOffset = 0; // Clear output array - for (int i = 0; i < NumStreams; i++) + for (S32 i = 0; i < NumStreams; i++) sortedInputs[i] = 0; // Separate inputs by type, and sort by set (ie. lowest TEXCOORD set becomes UV, // next TEXCOORD set becomes UV2 etc) - for (int iInput = 0; iInput < inputs.getCount(); iInput++) { + for (S32 iInput = 0; iInput < inputs.getCount(); iInput++) { const T& input = inputs[iInput]; const daeString semantic = input->getSemantic(); @@ -247,7 +247,7 @@ public: // The element may contain multiple inputs (eg. POSITION, NORMAL etc) domInputLocalRef verticesInputs[NumStreams]; classifyInputs(vertices->getInput_array(), verticesInputs); - for (int iStream = 0; iStream < NumStreams; iStream++) + for (S32 iStream = 0; iStream < NumStreams; iStream++) { if (verticesInputs[iStream] != 0) sortedInputs[iStream] = input; @@ -367,7 +367,7 @@ bool ColladaAppMesh::animatesMatFrame(const AppSequence* appSeq) // - by animating the morph weights for morph targets with different UVs // Check if the MAYA profile texture transform is animated - for (int iMat = 0; iMat < appMaterials.size(); iMat++) { + for (S32 iMat = 0; iMat < appMaterials.size(); iMat++) { ColladaAppMaterial* appMat = static_cast(appMaterials[iMat]); if (appMat->effectExt && appMat->effectExt->animatesTextureTransform(appSeq->getStart(), appSeq->getEnd())) @@ -379,7 +379,7 @@ bool ColladaAppMesh::animatesMatFrame(const AppSequence* appSeq) bool animated = false; bool differentUVs = false; if (const domMorph* morph = getMorph()) { - for (int iInput = 0; iInput < morph->getTargets()->getInput_array().getCount(); iInput++) { + for (S32 iInput = 0; iInput < morph->getTargets()->getInput_array().getCount(); iInput++) { const domInputLocal* input = morph->getTargets()->getInput_array()[iInput]; if (dStrEqual(input->getSemantic(), "MORPH_TARGET")) { // @todo: Check if morph targets have different UVs to base geometry @@ -402,7 +402,7 @@ bool ColladaAppMesh::animatesFrame(const AppSequence* appSeq) // the morph weights are animated within the sequence interval bool animated = false; if (const domMorph* morph = getMorph()) { - for (int iInput = 0; iInput < morph->getTargets()->getInput_array().getCount(); iInput++) { + for (S32 iInput = 0; iInput < morph->getTargets()->getInput_array().getCount(); iInput++) { const domInputLocal* input = morph->getTargets()->getInput_array()[iInput]; if (dStrEqual(input->getSemantic(), "MORPH_WEIGHT")) { const domSource* source = daeSafeCast(findInputSource(input)); @@ -441,7 +441,7 @@ S32 ColladaAppMesh::addMaterial(const char* symbol) instanceCtrl->getBind_material(); if (binds) { const domInstance_material_Array& matArray = binds->getTechnique_common()->getInstance_material_array(); - for (int iBind = 0; iBind < matArray.getCount(); iBind++) { + for (S32 iBind = 0; iBind < matArray.getCount(); iBind++) { if (dStrEqual(matArray[iBind]->getSymbol(), symbol)) { // Find the index of the bound material in the shape global list @@ -488,7 +488,7 @@ void ColladaAppMesh::getPrimitives(const domGeometry* geometry) // about unsupported elements Vector meshPrims; const daeElementRefArray& contents = geometry->getMesh()->getContents(); - for (int iElem = 0; iElem < contents.getCount(); iElem++) { + for (S32 iElem = 0; iElem < contents.getCount(); iElem++) { if (BasePrimitive::isPrimitive(contents[iElem])) { if (BasePrimitive::isSupportedPrimitive(contents[iElem])) @@ -505,7 +505,7 @@ void ColladaAppMesh::getPrimitives(const domGeometry* geometry) VertTupleMap tupleMap; // Create Torque primitives - for (int iPrim = 0; iPrim < meshPrims.size(); iPrim++) { + for (S32 iPrim = 0; iPrim < meshPrims.size(); iPrim++) { // Primitive element must have at least 1 triangle const domListOfUInts* pTriData = meshPrims[iPrim]->getTriangleData(); @@ -619,11 +619,11 @@ void ColladaAppMesh::getPrimitives(const domGeometry* geometry) } } - for (int iPrim = 0; iPrim < meshPrims.size(); iPrim++) + for (S32 iPrim = 0; iPrim < meshPrims.size(); iPrim++) delete meshPrims[iPrim]; } -void ColladaAppMesh::getVertexData(const domGeometry* geometry, F32 time, const MatrixF& objectOffset, +void ColladaAppMesh::getVertexData(const domGeometry* geometry, F32 time, const MatrixF& objOffset, Vector& v_points, Vector& v_norms, Vector& v_colors, @@ -641,7 +641,7 @@ void ColladaAppMesh::getVertexData(const domGeometry* geometry, F32 time, const // Get the supported primitive elements for this geometry Vector meshPrims; const daeElementRefArray& contents = geometry->getMesh()->getContents(); - for (int iElem = 0; iElem < contents.getCount(); iElem++) { + for (S32 iElem = 0; iElem < contents.getCount(); iElem++) { if (BasePrimitive::isSupportedPrimitive(contents[iElem])) meshPrims.push_back(BasePrimitive::get(contents[iElem])); } @@ -659,7 +659,7 @@ void ColladaAppMesh::getVertexData(const domGeometry* geometry, F32 time, const ColorI* colors_array = NULL; Point2F* uv2s_array = NULL; - for (int iVert = 0; iVert < vertTuples.size(); iVert++) { + for (S32 iVert = 0; iVert < vertTuples.size(); iVert++) { const VertTuple& tuple = vertTuples[iVert]; @@ -693,7 +693,7 @@ void ColladaAppMesh::getVertexData(const domGeometry* geometry, F32 time, const if (appNode->invertMeshes) points_array[iVert].z = -points_array[iVert].z; - objectOffset.mulP(points_array[iVert]); + objOffset.mulP(points_array[iVert]); } if (appendValues || ((tuple.uv >= 0) && (tuple.uv < streams.uvs.size()))) { @@ -751,11 +751,11 @@ void ColladaAppMesh::getVertexData(const domGeometry* geometry, F32 time, const } } - for (int iPrim = 0; iPrim < meshPrims.size(); iPrim++) + for (S32 iPrim = 0; iPrim < meshPrims.size(); iPrim++) delete meshPrims[iPrim]; } -void ColladaAppMesh::getMorphVertexData(const domMorph* morph, F32 time, const MatrixF& objectOffset, +void ColladaAppMesh::getMorphVertexData(const domMorph* morph, F32 time, const MatrixF& objOffset, Vector& v_points, Vector& v_norms, Vector& v_colors, @@ -768,7 +768,7 @@ void ColladaAppMesh::getMorphVertexData(const domMorph* morph, F32 time, const M Vector targetGeoms; domListOfFloats targetWeights; - for (int iInput = 0; iInput < morph->getTargets()->getInput_array().getCount(); iInput++) { + for (S32 iInput = 0; iInput < morph->getTargets()->getInput_array().getCount(); iInput++) { const domInputLocal* input = morph->getTargets()->getInput_array()[iInput]; const domSource* source = daeSafeCast(findInputSource(input)); @@ -777,7 +777,7 @@ void ColladaAppMesh::getMorphVertexData(const domMorph* morph, F32 time, const M _SourceReader srcTargets; srcTargets.initFromSource(source); - for (int iTarget = 0; iTarget < srcTargets.size(); iTarget++) { + for (S32 iTarget = 0; iTarget < srcTargets.size(); iTarget++) { // Lookup the element and add to the targets list daeIDRef idref(srcTargets.getStringValue(iTarget)); idref.setContainer(morph->getDocument()->getDomRoot()); @@ -807,7 +807,7 @@ void ColladaAppMesh::getMorphVertexData(const domMorph* morph, F32 time, const M return; getPrimitives(baseGeometry); - getVertexData(baseGeometry, time, objectOffset, v_points, v_norms, v_colors, v_uvs, v_uv2s, true); + getVertexData(baseGeometry, time, objOffset, v_points, v_norms, v_colors, v_uvs, v_uv2s, true); // Get pointers to the arrays of base geometry data Point3F* points_array = &v_points[v_points.size() - vertTuples.size()]; @@ -820,27 +820,27 @@ void ColladaAppMesh::getMorphVertexData(const domMorph* morph, F32 time, const M if (morph->getMethod() == MORPHMETHODTYPE_NORMALIZED) { F32 weightSum = 0.0f; - for (int iWeight = 0; iWeight < targetWeights.getCount(); iWeight++) { + for (S32 iWeight = 0; iWeight < targetWeights.getCount(); iWeight++) { weightSum += targetWeights[iWeight]; } // Result = Base*(1.0-w1-w2 ... -wN) + w1*Target1 + w2*Target2 ... + wN*TargetN weightSum = mClampF(1.0f - weightSum, 0.0f, 1.0f); - for (int iVert = 0; iVert < vertTuples.size(); iVert++) { + for (S32 iVert = 0; iVert < vertTuples.size(); iVert++) { points_array[iVert] *= weightSum; norms_array[iVert] *= weightSum; uvs_array[iVert] *= weightSum; } if (uv2s_array) { - for (int iVert = 0; iVert < vertTuples.size(); iVert++) + for (S32 iVert = 0; iVert < vertTuples.size(); iVert++) uv2s_array[iVert] *= weightSum; } } // Interpolate using the target geometry and weights - for (int iTarget = 0; iTarget < targetGeoms.size(); iTarget++) { + for (S32 iTarget = 0; iTarget < targetGeoms.size(); iTarget++) { // Ignore empty weights if (targetWeights[iTarget] == 0.0f) @@ -863,27 +863,27 @@ void ColladaAppMesh::getMorphVertexData(const domMorph* morph, F32 time, const M if (uv2s_array) targetUv2s.set(uv2s_array, vertTuples.size()); - getVertexData(targetGeoms[iTarget], time, objectOffset, targetPoints, targetNorms, targetColors, targetUvs, targetUv2s, false); + getVertexData(targetGeoms[iTarget], time, objOffset, targetPoints, targetNorms, targetColors, targetUvs, targetUv2s, false); // Combine with base geometry - for (int iVert = 0; iVert < vertTuples.size(); iVert++) { + for (S32 iVert = 0; iVert < vertTuples.size(); iVert++) { points_array[iVert] += targetPoints[iVert] * targetWeights[iTarget]; norms_array[iVert] += targetNorms[iVert] * targetWeights[iTarget]; uvs_array[iVert] += targetUvs[iVert] * targetWeights[iTarget]; } if (uv2s_array) { - for (int iVert = 0; iVert < vertTuples.size(); iVert++) + for (S32 iVert = 0; iVert < vertTuples.size(); iVert++) uv2s_array[iVert] += targetUv2s[iVert] * targetWeights[iTarget]; } if (colors_array) { - for (int iVert = 0; iVert < vertTuples.size(); iVert++) + for (S32 iVert = 0; iVert < vertTuples.size(); iVert++) colors_array[iVert] += targetColors[iVert] * (F32)targetWeights[iTarget]; } } } -void ColladaAppMesh::lockMesh(F32 t, const MatrixF& objectOffset) +void ColladaAppMesh::lockMesh(F32 t, const MatrixF& objOffset) { // Find the geometry element for this mesh. Could be one of 3 things: // 1) a simple static mesh (Collada element) @@ -923,10 +923,10 @@ void ColladaAppMesh::lockMesh(F32 t, const MatrixF& objectOffset) // Now get the vertex data at the specified time if (geometry->getElementType() == COLLADA_TYPE::GEOMETRY) { getPrimitives(daeSafeCast(geometry)); - getVertexData(daeSafeCast(geometry), t, objectOffset, points, normals, colors, uvs, uv2s, true); + getVertexData(daeSafeCast(geometry), t, objOffset, points, normals, colors, uvs, uv2s, true); } else if (geometry->getElementType() == COLLADA_TYPE::MORPH) { - getMorphVertexData(daeSafeCast(geometry), t, objectOffset, points, normals, colors, uvs, uv2s); + getMorphVertexData(daeSafeCast(geometry), t, objOffset, points, normals, colors, uvs, uv2s); } else { daeErrorHandler::get()->handleWarning(avar("Unsupported geometry type " @@ -963,7 +963,7 @@ void ColladaAppMesh::lookupSkinData() // vertex may have multiple [bone, weight] pairs in the array) Vector vindicesOffset; const domInt* vindices = (domInt*)weights_v.getRaw(0); - for (int iWeight = 0; iWeight < weights_vcount.getCount(); iWeight++) { + for (S32 iWeight = 0; iWeight < weights_vcount.getCount(); iWeight++) { // Store the offset into the vindices array for this vertex vindicesOffset.push_back(vindices - (domInt*)weights_v.getRaw(0)); vindices += (weights_vcount[iWeight]*2); // 2 indices [bone, weight] per vert @@ -971,14 +971,14 @@ void ColladaAppMesh::lookupSkinData() // Set vertex weights bool tooManyWeightsWarning = false; - for (int iVert = 0; iVert < vertsPerFrame; iVert++) { + for (S32 iVert = 0; iVert < vertsPerFrame; iVert++) { const domUint* vcount = (domUint*)weights_vcount.getRaw(0); const domInt* vindices = (domInt*)weights_v.getRaw(0); vindices += vindicesOffset[vertTuples[iVert].vertex]; S32 nonZeroWeightCount = 0; - for (int iWeight = 0; iWeight < vcount[vertTuples[iVert].vertex]; iWeight++) { + for (S32 iWeight = 0; iWeight < vcount[vertTuples[iVert].vertex]; iWeight++) { S32 bIndex = vindices[iWeight*2]; F32 bWeight = streams.weights.getFloatValue( vindices[iWeight*2 + 1] ); @@ -1027,12 +1027,12 @@ void ColladaAppMesh::lookupSkinData() } // Normalize vertex weights (force weights for each vert to sum to 1) - int iWeight = 0; + S32 iWeight = 0; while (iWeight < weight.size()) { // Find the last weight with the same vertex number, and sum all weights for // that vertex F32 invTotalWeight = 0; - int iLast; + S32 iLast; for (iLast = iWeight; iLast < weight.size(); iLast++) { if (vertexIndex[iLast] != vertexIndex[iWeight]) break; @@ -1048,7 +1048,7 @@ void ColladaAppMesh::lookupSkinData() // Add dummy AppNodes to allow Collada joints to be mapped to 3space nodes bones.setSize(streams.joints.size()); initialTransforms.setSize(streams.joints.size()); - for (int iJoint = 0; iJoint < streams.joints.size(); iJoint++) + for (S32 iJoint = 0; iJoint < streams.joints.size(); iJoint++) { const char* jointName = streams.joints.getStringValue(iJoint); @@ -1056,7 +1056,7 @@ void ColladaAppMesh::lookupSkinData() const domNode* joint = 0; if (instanceCtrl->getSkeleton_array().getCount()) { // Search for the node using the as the base element - for (int iSkel = 0; iSkel < instanceCtrl->getSkeleton_array().getCount(); iSkel++) { + for (S32 iSkel = 0; iSkel < instanceCtrl->getSkeleton_array().getCount(); iSkel++) { xsAnyURI skeleton = instanceCtrl->getSkeleton_array()[iSkel]->getValue(); daeSIDResolver resolver(skeleton.getElement(), jointName); joint = daeSafeCast(resolver.getElement()); diff --git a/Engine/source/ts/collada/colladaAppMesh.h b/Engine/source/ts/collada/colladaAppMesh.h index e7d07c376..17ac1cad1 100644 --- a/Engine/source/ts/collada/colladaAppMesh.h +++ b/Engine/source/ts/collada/colladaAppMesh.h @@ -109,11 +109,11 @@ protected: bool checkGeometryType(const daeElement* element); void getPrimitives(const domGeometry* geometry); - void getVertexData( const domGeometry* geometry, F32 time, const MatrixF& objectOffset, + void getVertexData( const domGeometry* geometry, F32 time, const MatrixF& objOffset, Vector& points, Vector& norms, Vector& colors, Vector& uvs, Vector& uv2s, bool appendValues); - void getMorphVertexData( const domMorph* morph, F32 time, const MatrixF& objectOffset, + void getMorphVertexData( const domMorph* morph, F32 time, const MatrixF& objOffset, Vector& points, Vector& norms, Vector& colors, Vector& uvs, Vector& uv2s ); @@ -211,8 +211,8 @@ public: /// Generate the vertex, normal and triangle data for the mesh. /// /// @param time Time at which to generate the mesh data - /// @param objectOffset Transform to apply to the generated data (bounds transform) - void lockMesh(F32 time, const MatrixF& objectOffset); + /// @param objOffset Transform to apply to the generated data (bounds transform) + void lockMesh(F32 time, const MatrixF& objOffset); /// Get the transform of this mesh at a certain time /// diff --git a/Engine/source/ts/collada/colladaAppNode.cpp b/Engine/source/ts/collada/colladaAppNode.cpp index 8a0dcacab..fdf56c775 100644 --- a/Engine/source/ts/collada/colladaAppNode.cpp +++ b/Engine/source/ts/collada/colladaAppNode.cpp @@ -90,7 +90,7 @@ ColladaAppNode::ColladaAppNode(const domNode* node, ColladaAppNode* parent) dFree( properties ); // Create vector of transform elements - for (int iChild = 0; iChild < node->getContents().getCount(); iChild++) { + for (S32 iChild = 0; iChild < node->getContents().getCount(); iChild++) { switch (node->getContents()[iChild]->getElementType()) { case COLLADA_TYPE::TRANSLATE: case COLLADA_TYPE::ROTATE: @@ -109,7 +109,7 @@ ColladaAppNode::ColladaAppNode(const domNode* node, ColladaAppNode* parent) void ColladaAppNode::buildChildList() { // Process children: collect and elements - for (int iChild = 0; iChild < p_domNode->getContents().getCount(); iChild++) { + for (S32 iChild = 0; iChild < p_domNode->getContents().getCount(); iChild++) { daeElement* child = p_domNode->getContents()[iChild]; switch (child->getElementType()) { @@ -139,7 +139,7 @@ void ColladaAppNode::buildChildList() void ColladaAppNode::buildMeshList() { // Process children: collect and elements - for (int iChild = 0; iChild < p_domNode->getContents().getCount(); iChild++) { + for (S32 iChild = 0; iChild < p_domNode->getContents().getCount(); iChild++) { daeElement* child = p_domNode->getContents()[iChild]; switch (child->getElementType()) { @@ -167,7 +167,7 @@ bool ColladaAppNode::animatesTransform(const AppSequence* appSeq) { // Check if any of this node's transform elements are animated during the // sequence interval - for (int iTxfm = 0; iTxfm < nodeTransforms.size(); iTxfm++) { + for (S32 iTxfm = 0; iTxfm < nodeTransforms.size(); iTxfm++) { if (nodeTransforms[iTxfm].isAnimated(appSeq->getStart(), appSeq->getEnd())) return true; } @@ -227,7 +227,7 @@ MatrixF ColladaAppNode::getTransform(F32 time) } // Multiply by local node transform elements - for (int iTxfm = 0; iTxfm < nodeTransforms.size(); iTxfm++) { + for (S32 iTxfm = 0; iTxfm < nodeTransforms.size(); iTxfm++) { MatrixF mat(true); diff --git a/Engine/source/ts/collada/colladaAppSequence.cpp b/Engine/source/ts/collada/colladaAppSequence.cpp index 3422fe029..6f65a01bf 100644 --- a/Engine/source/ts/collada/colladaAppSequence.cpp +++ b/Engine/source/ts/collada/colladaAppSequence.cpp @@ -74,7 +74,7 @@ F32 ColladaAppSequence::getBlendRefTime() void ColladaAppSequence::setActive(bool active) { - for (int iAnim = 0; iAnim < getClip()->getInstance_animation_array().getCount(); iAnim++) { + for (S32 iAnim = 0; iAnim < getClip()->getInstance_animation_array().getCount(); iAnim++) { domAnimation* anim = daeSafeCast(getClip()->getInstance_animation_array()[iAnim]->getUrl().getElement()); if (anim) setAnimationActive(anim, active); @@ -84,7 +84,7 @@ void ColladaAppSequence::setActive(bool active) void ColladaAppSequence::setAnimationActive(const domAnimation* anim, bool active) { // Enabled/disable data channels for this animation - for (int iChannel = 0; iChannel < anim->getChannel_array().getCount(); iChannel++) { + for (S32 iChannel = 0; iChannel < anim->getChannel_array().getCount(); iChannel++) { domChannel* channel = anim->getChannel_array()[iChannel]; AnimData* animData = reinterpret_cast(channel->getUserData()); if (animData) @@ -92,6 +92,6 @@ void ColladaAppSequence::setAnimationActive(const domAnimation* anim, bool activ } // Recurse into child animations - for (int iAnim = 0; iAnim < anim->getAnimation_array().getCount(); iAnim++) + for (S32 iAnim = 0; iAnim < anim->getAnimation_array().getCount(); iAnim++) setAnimationActive(anim->getAnimation_array()[iAnim], active); } diff --git a/Engine/source/ts/collada/colladaExtensions.h b/Engine/source/ts/collada/colladaExtensions.h index ab6d69289..40e490267 100644 --- a/Engine/source/ts/collada/colladaExtensions.h +++ b/Engine/source/ts/collada/colladaExtensions.h @@ -59,8 +59,8 @@ protected: template const domTechnique* findExtraTechnique(const T* element, const char* name) const { if (element) { - for (int iExt = 0; iExt < element->getExtra_array().getCount(); iExt++) { - for (int iTech = 0; iTech < element->getExtra_array()[iExt]->getTechnique_array().getCount(); iTech++) { + for (S32 iExt = 0; iExt < element->getExtra_array().getCount(); iExt++) { + for (S32 iTech = 0; iTech < element->getExtra_array()[iExt]->getTechnique_array().getCount(); iTech++) { if (dStrEqual(element->getExtra_array()[iExt]->getTechnique_array()[iTech]->getProfile(), name)) return element->getExtra_array()[iExt]->getTechnique_array()[iTech]; } @@ -75,7 +75,7 @@ protected: const domCommon_color_or_texture_type_complexType::domTexture* element, const char* name) const { if (element && element->getExtra()) { - for (int iTech = 0; iTech < element->getExtra()->getTechnique_array().getCount(); iTech++) { + for (S32 iTech = 0; iTech < element->getExtra()->getTechnique_array().getCount(); iTech++) { if (dStrEqual(element->getExtra()->getTechnique_array()[iTech]->getProfile(), name)) return element->getExtra()->getTechnique_array()[iTech]; } @@ -88,7 +88,7 @@ protected: { if (pTechnique) { // search the technique contents for the desired parameter - for (int iParam = 0; iParam < pTechnique->getContents().getCount(); iParam++) { + for (S32 iParam = 0; iParam < pTechnique->getContents().getCount(); iParam++) { const domAny* param = daeSafeCast(pTechnique->getContents()[iParam]); if (param && !dStrcmp(param->getElementName(), name)) return param; @@ -290,7 +290,7 @@ public: // Torque profile pTechnique = findExtraTechnique(clip, "Torque"); GET_EXTRA_PARAM(num_triggers, 0); - for (int iTrigger = 0; iTrigger < num_triggers; iTrigger++) { + for (S32 iTrigger = 0; iTrigger < num_triggers; iTrigger++) { triggers.increment(); get(avar("trigger_time%d", iTrigger), triggers.last().time, 0.0f); get(avar("trigger_state%d", iTrigger), triggers.last().state, 0); diff --git a/Engine/source/ts/collada/colladaImport.cpp b/Engine/source/ts/collada/colladaImport.cpp index 7692dcc77..1657d22c4 100644 --- a/Engine/source/ts/collada/colladaImport.cpp +++ b/Engine/source/ts/collada/colladaImport.cpp @@ -50,7 +50,7 @@ static void processNode(GuiTreeViewCtrl* tree, domNode* node, S32 parentID, Scen S32 nodeID = tree->insertItem(parentID, _GetNameOrId(node), "node", "", 0, 0); // Update mesh and poly counts - for (int i = 0; i < node->getContents().getCount(); i++) + for (S32 i = 0; i < node->getContents().getCount(); i++) { domGeometry* geom = 0; const char* elemName = ""; @@ -178,13 +178,13 @@ ConsoleFunction( enumColladaForImport, bool, 3, 3, SceneStats stats; // Query DOM for shape summary details - for (int i = 0; i < root->getLibrary_visual_scenes_array().getCount(); i++) + for (S32 i = 0; i < root->getLibrary_visual_scenes_array().getCount(); i++) { const domLibrary_visual_scenes* libScenes = root->getLibrary_visual_scenes_array()[i]; - for (int j = 0; j < libScenes->getVisual_scene_array().getCount(); j++) + for (S32 j = 0; j < libScenes->getVisual_scene_array().getCount(); j++) { const domVisual_scene* visualScene = libScenes->getVisual_scene_array()[j]; - for (int k = 0; k < visualScene->getNode_array().getCount(); k++) + for (S32 k = 0; k < visualScene->getNode_array().getCount(); k++) processNode(tree, visualScene->getNode_array()[k], nodesID, stats); } } diff --git a/Engine/source/ts/collada/colladaLights.cpp b/Engine/source/ts/collada/colladaLights.cpp index 1388278d0..71d2c33df 100644 --- a/Engine/source/ts/collada/colladaLights.cpp +++ b/Engine/source/ts/collada/colladaLights.cpp @@ -215,11 +215,11 @@ ConsoleFunction( loadColladaLights, bool, 2, 4, // First grab all of the top-level nodes Vector sceneNodes; - for (int iSceneLib = 0; iSceneLib < root->getLibrary_visual_scenes_array().getCount(); iSceneLib++) { + for (S32 iSceneLib = 0; iSceneLib < root->getLibrary_visual_scenes_array().getCount(); iSceneLib++) { const domLibrary_visual_scenes* libScenes = root->getLibrary_visual_scenes_array()[iSceneLib]; - for (int iScene = 0; iScene < libScenes->getVisual_scene_array().getCount(); iScene++) { + for (S32 iScene = 0; iScene < libScenes->getVisual_scene_array().getCount(); iScene++) { const domVisual_scene* visualScene = libScenes->getVisual_scene_array()[iScene]; - for (int iNode = 0; iNode < visualScene->getNode_array().getCount(); iNode++) + for (S32 iNode = 0; iNode < visualScene->getNode_array().getCount(); iNode++) sceneNodes.push_back(new ColladaAppNode(visualScene->getNode_array()[iNode])); } } diff --git a/Engine/source/ts/collada/colladaShapeLoader.cpp b/Engine/source/ts/collada/colladaShapeLoader.cpp index 3822e9e01..219b07459 100644 --- a/Engine/source/ts/collada/colladaShapeLoader.cpp +++ b/Engine/source/ts/collada/colladaShapeLoader.cpp @@ -96,8 +96,8 @@ ColladaShapeLoader::ColladaShapeLoader(domCOLLADA* _root) ColladaShapeLoader::~ColladaShapeLoader() { // Delete all of the animation channels - for (int iAnim = 0; iAnim < animations.size(); iAnim++) { - for (int iChannel = 0; iChannel < animations[iAnim]->size(); iChannel++) + for (S32 iAnim = 0; iAnim < animations.size(); iAnim++) { + for (S32 iChannel = 0; iChannel < animations[iAnim]->size(); iChannel++) delete (*animations[iAnim])[iChannel]; delete animations[iAnim]; } @@ -113,7 +113,7 @@ void ColladaShapeLoader::processAnimation(const domAnimation* anim, F32& maxEndT const char* sSKEWNames[] = { ".ROTATEX", ".ROTATEY", ".ROTATEZ", ".AROUNDX", ".AROUNDY", ".AROUNDZ", ".ANGLE", "" }; const char* sNullNames[] = { "" }; - for (int iChannel = 0; iChannel < anim->getChannel_array().getCount(); iChannel++) { + for (S32 iChannel = 0; iChannel < anim->getChannel_array().getCount(); iChannel++) { // Get the animation elements: , domChannel* channel = anim->getChannel_array()[iChannel]; @@ -150,7 +150,7 @@ void ColladaShapeLoader::processAnimation(const domAnimation* anim, F32& maxEndT channel->setUserData(targetChannels->last()); AnimData& data = *targetChannels->last(); - for (int iInput = 0; iInput < sampler->getInput_array().getCount(); iInput++) { + for (S32 iInput = 0; iInput < sampler->getInput_array().getCount(); iInput++) { const domInputLocal* input = sampler->getInput_array()[iInput]; const domSource* source = daeSafeCast(input->getSource().getElement()); @@ -219,7 +219,7 @@ void ColladaShapeLoader::processAnimation(const domAnimation* anim, F32& maxEndT } // Process child animations - for (int iAnim = 0; iAnim < anim->getAnimation_array().getCount(); iAnim++) + for (S32 iAnim = 0; iAnim < anim->getAnimation_array().getCount(); iAnim++) processAnimation(anim->getAnimation_array()[iAnim], maxEndTime, minFrameTime); } @@ -227,20 +227,20 @@ void ColladaShapeLoader::enumerateScene() { // Get animation clips Vector animationClips; - for (int iClipLib = 0; iClipLib < root->getLibrary_animation_clips_array().getCount(); iClipLib++) { + for (S32 iClipLib = 0; iClipLib < root->getLibrary_animation_clips_array().getCount(); iClipLib++) { const domLibrary_animation_clips* libraryClips = root->getLibrary_animation_clips_array()[iClipLib]; - for (int iClip = 0; iClip < libraryClips->getAnimation_clip_array().getCount(); iClip++) + for (S32 iClip = 0; iClip < libraryClips->getAnimation_clip_array().getCount(); iClip++) appSequences.push_back(new ColladaAppSequence(libraryClips->getAnimation_clip_array()[iClip])); } // Process all animations => this attaches animation channels to the targeted // Collada elements, and determines the length of the sequence if it is not // already specified in the Collada element - for (int iSeq = 0; iSeq < appSequences.size(); iSeq++) { + for (S32 iSeq = 0; iSeq < appSequences.size(); iSeq++) { ColladaAppSequence* appSeq = dynamic_cast(appSequences[iSeq]); F32 maxEndTime = 0; F32 minFrameTime = 1000.0f; - for (int iAnim = 0; iAnim < appSeq->getClip()->getInstance_animation_array().getCount(); iAnim++) { + for (S32 iAnim = 0; iAnim < appSeq->getClip()->getInstance_animation_array().getCount(); iAnim++) { domAnimation* anim = daeSafeCast(appSeq->getClip()->getInstance_animation_array()[iAnim]->getUrl().getElement()); if (anim) processAnimation(anim, maxEndTime, minFrameTime); @@ -256,11 +256,11 @@ void ColladaShapeLoader::enumerateScene() // First grab all of the top-level nodes Vector sceneNodes; - for (int iSceneLib = 0; iSceneLib < root->getLibrary_visual_scenes_array().getCount(); iSceneLib++) { + for (S32 iSceneLib = 0; iSceneLib < root->getLibrary_visual_scenes_array().getCount(); iSceneLib++) { const domLibrary_visual_scenes* libScenes = root->getLibrary_visual_scenes_array()[iSceneLib]; - for (int iScene = 0; iScene < libScenes->getVisual_scene_array().getCount(); iScene++) { + for (S32 iScene = 0; iScene < libScenes->getVisual_scene_array().getCount(); iScene++) { const domVisual_scene* visualScene = libScenes->getVisual_scene_array()[iScene]; - for (int iNode = 0; iNode < visualScene->getNode_array().getCount(); iNode++) + for (S32 iNode = 0; iNode < visualScene->getNode_array().getCount(); iNode++) sceneNodes.push_back(visualScene->getNode_array()[iNode]); } } @@ -272,10 +272,10 @@ void ColladaShapeLoader::enumerateScene() case ColladaUtils::ImportOptions::DetectDTS: // Check for a baseXX->startXX hierarchy at the top-level, if we find // one, use trailing numbers for LOD, otherwise use a single size - for (int iNode = 0; singleDetail && (iNode < sceneNodes.size()); iNode++) { + for (S32 iNode = 0; singleDetail && (iNode < sceneNodes.size()); iNode++) { domNode* node = sceneNodes[iNode]; if (dStrStartsWith(_GetNameOrId(node), "base")) { - for (int iChild = 0; iChild < node->getNode_array().getCount(); iChild++) { + for (S32 iChild = 0; iChild < node->getNode_array().getCount(); iChild++) { domNode* child = node->getNode_array()[iChild]; if (dStrStartsWith(_GetNameOrId(child), "start")) { singleDetail = false; @@ -484,7 +484,7 @@ void updateMaterialsScript(const Torque::Path &path, bool copyTextures = false) // If importing a sketchup file, the paths will point inside the KMZ so we need to cache them. if (copyTextures) { - for (int iMat = 0; iMat < persistMgr.getDirtyList().size(); iMat++) + for (S32 iMat = 0; iMat < persistMgr.getDirtyList().size(); iMat++) { Material *mat = dynamic_cast( persistMgr.getDirtyList()[iMat].getObject() ); diff --git a/Engine/source/ts/collada/colladaUtils.cpp b/Engine/source/ts/collada/colladaUtils.cpp index 7bd5b2e9d..0c409fc95 100644 --- a/Engine/source/ts/collada/colladaUtils.cpp +++ b/Engine/source/ts/collada/colladaUtils.cpp @@ -84,7 +84,7 @@ const domProfile_COMMON* ColladaUtils::findEffectCommonProfile(const domEffect* if (effect) { // Find the COMMON profile const domFx_profile_abstract_Array& profiles = effect->getFx_profile_abstract_array(); - for (int iProfile = 0; iProfile < profiles.getCount(); iProfile++) { + for (S32 iProfile = 0; iProfile < profiles.getCount(); iProfile++) { if (profiles[iProfile]->getElementType() == COLLADA_TYPE::PROFILE_COMMON) return daeSafeCast(profiles[iProfile]); } @@ -245,7 +245,7 @@ BasePrimitive* BasePrimitive::get(const daeElement* element) // Collada animation curves /// Determine which elements are being targeted -void AnimData::parseTargetString(const char* target, int fullCount, const char* elements[]) +void AnimData::parseTargetString(const char* target, S32 fullCount, const char* elements[]) { // Assume targeting all elements at offset 0 targetValueCount = fullCount; @@ -253,7 +253,7 @@ void AnimData::parseTargetString(const char* target, int fullCount, const char* // Check for array syntax: (n) or (n)(m) if (const char* p = dStrchr(target, '(')) { - int indN, indM; + S32 indN, indM; if (dSscanf(p, "(%d)(%d)", &indN, &indM) == 2) { targetValueOffset = (indN * 4) + indM; // @todo: 4x4 matrix only targetValueCount = 1; @@ -265,7 +265,7 @@ void AnimData::parseTargetString(const char* target, int fullCount, const char* } else if (const char* p = dStrrchr(target, '.')) { // Check for named elements - for (int iElem = 0; elements[iElem][0] != 0; iElem++) { + for (S32 iElem = 0; elements[iElem][0] != 0; iElem++) { if (!dStrcmp(p, elements[iElem])) { targetValueOffset = iElem; targetValueCount = 1; @@ -278,9 +278,9 @@ void AnimData::parseTargetString(const char* target, int fullCount, const char* /// Solve the cubic spline B(s) = param for s F32 AnimData::invertParamCubic(F32 param, F32 x0, F32 x1, F32 x2, F32 x3) const { - const double INVERTPARAMCUBIC_TOL = 1.0e-09; - const double INVERTPARAMCUBIC_SMALLERTOL = 1.0e-20; - const double INVERTPARAMCUBIC_MAXIT = 100; + const F64 INVERTPARAMCUBIC_TOL = 1.0e-09; + const F64 INVERTPARAMCUBIC_SMALLERTOL = 1.0e-20; + const F64 INVERTPARAMCUBIC_MAXIT = 100; // check input value for outside range if ((param - x0) < INVERTPARAMCUBIC_SMALLERTOL) @@ -295,12 +295,12 @@ F32 AnimData::invertParamCubic(F32 param, F32 x0, F32 x1, F32 x2, F32 x3) const F32 v = 1.0f; while (iterations < INVERTPARAMCUBIC_MAXIT) { - double a = (x0 + x1)*0.5f; - double b = (x1 + x2)*0.5f; - double c = (x2 + x3)*0.5f; - double d = (a + b)*0.5f; - double e = (b + c)*0.5f; - double f = (d + e)*0.5f; + F64 a = (x0 + x1)*0.5f; + F64 b = (x1 + x2)*0.5f; + F64 c = (x2 + x3)*0.5f; + F64 d = (a + b)*0.5f; + F64 e = (b + c)*0.5f; + F64 f = (d + e)*0.5f; if (mFabs(f - param) < INVERTPARAMCUBIC_TOL) break; @@ -344,7 +344,7 @@ void AnimData::interpValue(F32 t, U32 offset, double* value) const t = mClampF(t, curveStart, curveEnd); // find the index of the input keyframe BEFORE 't' - int index; + S32 index; for (index = 0; index < input.size()-2; index++) { if (input.getFloatValue(index + 1) > t) break; @@ -470,7 +470,7 @@ void AnimData::interpValue(F32 t, U32 offset, const char** value) const t = mClampF(t, curveStart, curveEnd); // find the index of the input keyframe BEFORE 't' - int index; + S32 index; for (index = 0; index < input.size()-2; index++) { if (input.getFloatValue(index + 1) > t) break; @@ -487,9 +487,9 @@ void AnimData::interpValue(F32 t, U32 offset, const char** value) const static void conditioner_fixupTextureSIDs(domCOLLADA* root) { - for (int iLib = 0; iLib < root->getLibrary_effects_array().getCount(); iLib++) { + for (S32 iLib = 0; iLib < root->getLibrary_effects_array().getCount(); iLib++) { domLibrary_effects* lib = root->getLibrary_effects_array()[iLib]; - for (int iEffect = 0; iEffect < lib->getEffect_array().getCount(); iEffect++) { + for (S32 iEffect = 0; iEffect < lib->getEffect_array().getCount(); iEffect++) { domEffect* effect = lib->getEffect_array()[iEffect]; const domCommon_color_or_texture_type_complexType* diffuse = findEffectDiffuse(effect); if (!diffuse || !diffuse->getTexture()) @@ -542,9 +542,9 @@ static void conditioner_fixupTextureSIDs(domCOLLADA* root) static void conditioner_fixupImageURIs(domCOLLADA* root) { - for (int iLib = 0; iLib < root->getLibrary_images_array().getCount(); iLib++) { + for (S32 iLib = 0; iLib < root->getLibrary_images_array().getCount(); iLib++) { domLibrary_images* lib = root->getLibrary_images_array()[iLib]; - for (int iImage = 0; iImage < lib->getImage_array().getCount(); iImage++) { + for (S32 iImage = 0; iImage < lib->getImage_array().getCount(); iImage++) { domImage* image = lib->getImage_array()[iImage]; if (image->getInit_from()) { xsAnyURI& uri = image->getInit_from()->getValue(); @@ -595,7 +595,7 @@ static void conditioner_fixupTransparency(domCOLLADA* root) // Get the string const char *authoringTool = ""; if (const domAsset* asset = root->getAsset()) { - for (int iContrib = 0; iContrib < asset->getContributor_array().getCount(); iContrib++) { + for (S32 iContrib = 0; iContrib < asset->getContributor_array().getCount(); iContrib++) { const domAsset::domContributor* contrib = asset->getContributor_array()[iContrib]; if (contrib->getAuthoring_tool()) { authoringTool = contrib->getAuthoring_tool()->getValue(); @@ -608,7 +608,7 @@ static void conditioner_fixupTransparency(domCOLLADA* root) bool invertTransparency = false; const char *toolNames[] = { "FBX COLLADA exporter", "Google SketchUp", "Illusoft Collada Exporter", "FCollada" }; - for (int iName = 0; iName < (sizeof(toolNames)/sizeof(toolNames[0])); iName++) { + for (S32 iName = 0; iName < (sizeof(toolNames)/sizeof(toolNames[0])); iName++) { if (dStrstr(authoringTool, toolNames[iName])) { invertTransparency = true; break; @@ -619,9 +619,9 @@ static void conditioner_fixupTransparency(domCOLLADA* root) return; // Invert transparency as required for each effect - for (int iLib = 0; iLib < root->getLibrary_effects_array().getCount(); iLib++) { + for (S32 iLib = 0; iLib < root->getLibrary_effects_array().getCount(); iLib++) { domLibrary_effects* lib = root->getLibrary_effects_array()[iLib]; - for (int iEffect = 0; iEffect < lib->getEffect_array().getCount(); iEffect++) { + for (S32 iEffect = 0; iEffect < lib->getEffect_array().getCount(); iEffect++) { domEffect* effect = lib->getEffect_array()[iEffect]; // Find the common profile @@ -658,9 +658,9 @@ static void conditioner_fixupTransparency(domCOLLADA* root) static void conditioner_checkBindShapeMatrix(domCOLLADA* root) { - for (int iLib = 0; iLib < root->getLibrary_controllers_array().getCount(); iLib++) { + for (S32 iLib = 0; iLib < root->getLibrary_controllers_array().getCount(); iLib++) { domLibrary_controllers* lib = root->getLibrary_controllers_array().get(iLib); - for (int iCon = 0; iCon < lib->getController_array().getCount(); iCon++) { + for (S32 iCon = 0; iCon < lib->getController_array().getCount(); iCon++) { domController* con = lib->getController_array().get(iCon); if (con->getSkin() && con->getSkin()->getBind_shape_matrix()) { @@ -677,14 +677,14 @@ static void conditioner_checkBindShapeMatrix(domCOLLADA* root) static void conditioner_fixupVertexWeightJoints(domCOLLADA* root) { - for (int iLib = 0; iLib < root->getLibrary_controllers_array().getCount(); iLib++) { + for (S32 iLib = 0; iLib < root->getLibrary_controllers_array().getCount(); iLib++) { domLibrary_controllers* lib = root->getLibrary_controllers_array().get(iLib); - for (int iCon = 0; iCon < lib->getController_array().getCount(); iCon++) { + for (S32 iCon = 0; iCon < lib->getController_array().getCount(); iCon++) { domController* con = lib->getController_array().get(iCon); if (con->getSkin() && con->getSkin()->getVertex_weights()) { domInputLocalOffset_Array& vw_inputs = con->getSkin()->getVertex_weights()->getInput_array(); - for (int vInput = 0; vInput < vw_inputs.getCount(); vInput++) { + for (S32 vInput = 0; vInput < vw_inputs.getCount(); vInput++) { domInputLocalOffset *vw_input = vw_inputs.get(vInput); if (dStrEqual(vw_input->getSemantic(), "JOINT")) { @@ -695,7 +695,7 @@ static void conditioner_fixupVertexWeightJoints(domCOLLADA* root) // Copy the value from the JOINTS input instead domInputLocal_Array& joint_inputs = con->getSkin()->getJoints()->getInput_array(); - for (int jInput = 0; jInput < joint_inputs.getCount(); jInput++) { + for (S32 jInput = 0; jInput < joint_inputs.getCount(); jInput++) { domInputLocal *joint_input = joint_inputs.get(jInput); if (dStrEqual(joint_input->getSemantic(), "JOINT")) { @@ -714,16 +714,16 @@ static void conditioner_fixupVertexWeightJoints(domCOLLADA* root) static void conditioner_createDefaultClip(domCOLLADA* root) { // Check if the document has any s - for (int iLib = 0; iLib < root->getLibrary_animation_clips_array().getCount(); iLib++) { + for (S32 iLib = 0; iLib < root->getLibrary_animation_clips_array().getCount(); iLib++) { if (root->getLibrary_animation_clips_array()[iLib]->getAnimation_clip_array().getCount()) return; } // Get all top-level s into an array domAnimation_Array animations; - for (int iAnimLib = 0; iAnimLib < root->getLibrary_animations_array().getCount(); iAnimLib++) { + for (S32 iAnimLib = 0; iAnimLib < root->getLibrary_animations_array().getCount(); iAnimLib++) { const domLibrary_animations* libraryAnims = root->getLibrary_animations_array()[iAnimLib]; - for (int iAnim = 0; iAnim < libraryAnims->getAnimation_array().getCount(); iAnim++) + for (S32 iAnim = 0; iAnim < libraryAnims->getAnimation_array().getCount(); iAnim++) animations.append(libraryAnims->getAnimation_array()[iAnim]); } @@ -748,7 +748,7 @@ static void conditioner_createDefaultClip(domCOLLADA* root) // Add all top_level animations to the clip (sub-animations will be included // when the clip is procesed) - for (int iAnim = 0; iAnim < animations.getCount(); iAnim++) { + for (S32 iAnim = 0; iAnim < animations.getCount(); iAnim++) { if (!animations[iAnim]->getId()) animations[iAnim]->setId(avar("dummy-animation-id%d", iAnim)); CREATE_ELEMENT(animation_clip, instance_animation, domInstanceWithExtra) @@ -767,7 +767,7 @@ static void conditioner_createDefaultClip(domCOLLADA* root) static void conditioner_fixupAnimation(domAnimation* anim) { - for (int iChannel = 0; iChannel < anim->getChannel_array().getCount(); iChannel++) { + for (S32 iChannel = 0; iChannel < anim->getChannel_array().getCount(); iChannel++) { // Get the animation elements: , domChannel* channel = anim->getChannel_array()[iChannel]; @@ -848,7 +848,7 @@ static void conditioner_fixupAnimation(domAnimation* anim) } // Process child animations - for (int iAnim = 0; iAnim < anim->getAnimation_array().getCount(); iAnim++) + for (S32 iAnim = 0; iAnim < anim->getAnimation_array().getCount(); iAnim++) conditioner_fixupAnimation(anim->getAnimation_array()[iAnim]); } @@ -893,9 +893,9 @@ void ColladaUtils::applyConditioners(domCOLLADA* root) // 2) Some exporters generate visibility animations but don't add the FCOLLADA // extension, so the target doesn't actually exist! Detect this situation // and add the extension manually so the animation still works. - for (int iLib = 0; iLib < root->getLibrary_animations_array().getCount(); iLib++) { + for (S32 iLib = 0; iLib < root->getLibrary_animations_array().getCount(); iLib++) { const domLibrary_animations* lib = root->getLibrary_animations_array()[iLib]; - for (int iAnim = 0; iAnim < lib->getAnimation_array().getCount(); iAnim++) + for (S32 iAnim = 0; iAnim < lib->getAnimation_array().getCount(); iAnim++) conditioner_fixupAnimation(lib->getAnimation_array()[iAnim]); } } diff --git a/Engine/source/ts/collada/colladaUtils.h b/Engine/source/ts/collada/colladaUtils.h index e2ee4b377..04592126e 100644 --- a/Engine/source/ts/collada/colladaUtils.h +++ b/Engine/source/ts/collada/colladaUtils.h @@ -185,7 +185,7 @@ template<> inline MatrixF vecToMatrixF(const domListOfFloats& vec) template<> inline MatrixF vecToMatrixF(const domListOfFloats& vec) { MatrixF mat; - for (int i = 0; i < 16; i++) + for (S32 i = 0; i < 16; i++) mat[i] = vec[i]; return mat; } @@ -332,7 +332,7 @@ public: // If no input params were specified, just map the source params directly if (!offsets.size()) { - for (int iParam = 0; iParam < accessor->getParam_array().getCount(); iParam++) + for (S32 iParam = 0; iParam < accessor->getParam_array().getCount(); iParam++) offsets.push_back(iParam); } @@ -348,9 +348,9 @@ public: //------------------------------------------------------ // Get a pointer to the start of a group of values (index advances by stride) - //template T getArrayData(int index) const { return 0; } + //template T getArrayData(S32 index) const { return 0; } - const double* getStringArrayData(int index) const + const double* getStringArrayData(S32 index) const { if ((index >= 0) && (index < size())) { if (source->getFloat_array()) @@ -361,9 +361,9 @@ public: //------------------------------------------------------ // Read a single value from the source array - //template T getValue(int index) const { return T; } + //template T getValue(S32 index) const { return T; } - const char* getStringValue(int index) const + const char* getStringValue(S32 index) const { if ((index >= 0) && (index < size())) { // could be plain strings or IDREFs @@ -375,7 +375,7 @@ public: return ""; } - F32 getFloatValue(int index) const + F32 getFloatValue(S32 index) const { F32 value(0); if (const double* data = getStringArrayData(index)) @@ -383,7 +383,7 @@ public: return value; } - Point2F getPoint2FValue(int index) const + Point2F getPoint2FValue(S32 index) const { Point2F value(0, 0); if (const double* data = getStringArrayData(index)) @@ -391,7 +391,7 @@ public: return value; } - Point3F getPoint3FValue(int index) const + Point3F getPoint3FValue(S32 index) const { Point3F value(1, 0, 0); if (const double* data = getStringArrayData(index)) @@ -399,7 +399,7 @@ public: return value; } - ColorI getColorIValue(int index) const + ColorI getColorIValue(S32 index) const { ColorI value(255, 255, 255, 255); if (const double* data = getStringArrayData(index)) @@ -413,11 +413,11 @@ public: return value; } - MatrixF getMatrixFValue(int index) const + MatrixF getMatrixFValue(S32 index) const { MatrixF value(true); if (const double* data = getStringArrayData(index)) { - for (int i = 0; i < 16; i++) + for (S32 i = 0; i < 16; i++) value[i] = data[i]; } return value; @@ -430,6 +430,8 @@ public: class BasePrimitive { public: + virtual ~BasePrimitive() { } + /// Return true if the element is a geometric primitive type static bool isPrimitive(const daeElement* element) { @@ -486,7 +488,7 @@ public: // Determine stride stride = 0; - for (int iInput = 0; iInput < getInputs().getCount(); iInput++) { + for (S32 iInput = 0; iInput < getInputs().getCount(); iInput++) { if (getInputs()[iInput]->getOffset() >= stride) stride = getInputs()[iInput]->getOffset() + 1; } @@ -524,7 +526,7 @@ template<> inline const domListOfUInts *ColladaPrimitive::getTrian // Convert strips to triangles pTriangleData = new domListOfUInts(); - for (int iStrip = 0; iStrip < primitive->getCount(); iStrip++) { + for (S32 iStrip = 0; iStrip < primitive->getCount(); iStrip++) { domP* P = primitive->getP_array()[iStrip]; @@ -537,7 +539,7 @@ template<> inline const domListOfUInts *ColladaPrimitive::getTrian // Convert the strip back to a triangle list domUint* v0 = pSrcData; - for (int iTri = 0; iTri < numTriangles; iTri++, v0 += stride) { + for (S32 iTri = 0; iTri < numTriangles; iTri++, v0 += stride) { if (iTri & 0x1) { // CW triangle @@ -565,7 +567,7 @@ template<> inline const domListOfUInts *ColladaPrimitive::getTriangl // Convert strips to triangles pTriangleData = new domListOfUInts(); - for (int iStrip = 0; iStrip < primitive->getCount(); iStrip++) { + for (S32 iStrip = 0; iStrip < primitive->getCount(); iStrip++) { domP* P = primitive->getP_array()[iStrip]; @@ -578,7 +580,7 @@ template<> inline const domListOfUInts *ColladaPrimitive::getTriangl // Convert the fan back to a triangle list domUint* v0 = pSrcData + stride; - for (int iTri = 0; iTri < numTriangles; iTri++, v0 += stride) { + for (S32 iTri = 0; iTri < numTriangles; iTri++, v0 += stride) { pTriangleData->appendArray(stride, pSrcData); // shared vertex pTriangleData->appendArray(stride, v0); // previous vertex pTriangleData->appendArray(stride, v0+stride); // current vertex @@ -597,7 +599,7 @@ template<> inline const domListOfUInts *ColladaPrimitive::getTriang // Convert polygons to triangles pTriangleData = new domListOfUInts(); - for (int iPoly = 0; iPoly < primitive->getCount(); iPoly++) { + for (S32 iPoly = 0; iPoly < primitive->getCount(); iPoly++) { domP* P = primitive->getP_array()[iPoly]; @@ -612,7 +614,7 @@ template<> inline const domListOfUInts *ColladaPrimitive::getTriang // converting the polygon to triangles. domUint* v0 = pSrcData; pSrcData += stride; - for (int iTri = 0; iTri < numPoints-2; iTri++) { + for (S32 iTri = 0; iTri < numPoints-2; iTri++) { pTriangleData->appendArray(stride, v0); pTriangleData->appendArray(stride*2, pSrcData); pSrcData += stride; @@ -636,7 +638,7 @@ template<> inline const domListOfUInts *ColladaPrimitive::getTriang const domListOfUInts& vcount = primitive->getVcount()->getValue(); U32 expectedCount = 0; - for (int iPoly = 0; iPoly < vcount.getCount(); iPoly++) + for (S32 iPoly = 0; iPoly < vcount.getCount(); iPoly++) expectedCount += vcount[iPoly]; expectedCount *= stride; @@ -648,13 +650,13 @@ template<> inline const domListOfUInts *ColladaPrimitive::getTriang } domUint* pSrcData = &(primitive->getP()->getValue()[0]); - for (int iPoly = 0; iPoly < vcount.getCount(); iPoly++) { + for (S32 iPoly = 0; iPoly < vcount.getCount(); iPoly++) { // Use a simple tri-fan (centered at the first point) method of // converting the polygon to triangles. domUint* v0 = pSrcData; pSrcData += stride; - for (int iTri = 0; iTri < vcount[iPoly]-2; iTri++) { + for (S32 iTri = 0; iTri < vcount[iPoly]-2; iTri++) { pTriangleData->appendArray(stride, v0); pTriangleData->appendArray(stride*2, pSrcData); pSrcData += stride; @@ -671,7 +673,7 @@ template<> inline const domListOfUInts *ColladaPrimitive::getTriang template inline T convert(const char* value) { return value; } template<> inline bool convert(const char* value) { return dAtob(value); } template<> inline S32 convert(const char* value) { return dAtoi(value); } -template<> inline double convert(const char* value) { return dAtof(value); } +template<> inline F64 convert(const char* value) { return dAtof(value); } template<> inline F32 convert(const char* value) { return convert(value); } //----------------------------------------------------------------------------- @@ -713,7 +715,7 @@ struct AnimData AnimData() : enabled(false) { } - void parseTargetString(const char* target, int fullCount, const char* elements[]); + void parseTargetString(const char* target, S32 fullCount, const char* elements[]); F32 invertParamCubic(F32 param, F32 x0, F32 x1, F32 x2, F32 x3) const; void interpValue(F32 t, U32 offset, double* value) const; @@ -757,7 +759,7 @@ struct AnimatedElement // Animate the value const AnimChannels* channels = AnimData::getAnimChannels(element); if (channels && (time >= 0)) { - for (int iChannel = 0; iChannel < channels->size(); iChannel++) { + for (S32 iChannel = 0; iChannel < channels->size(); iChannel++) { const AnimData* animData = (*channels)[iChannel]; if (animData->enabled) animData->interpValue(time, 0, &value); @@ -787,10 +789,10 @@ template struct AnimatedElementList : public AnimatedElement // Animate the vector const AnimChannels* channels = AnimData::getAnimChannels(this->element); if (channels && (time >= 0)) { - for (int iChannel = 0; iChannel < channels->size(); iChannel++) { + for (S32 iChannel = 0; iChannel < channels->size(); iChannel++) { const AnimData* animData = (*channels)[iChannel]; if (animData->enabled) { - for (int iValue = 0; iValue < animData->targetValueCount; iValue++) + for (S32 iValue = 0; iValue < animData->targetValueCount; iValue++) animData->interpValue(time, iValue, &vec[animData->targetValueOffset + iValue]); } } diff --git a/Engine/source/ts/loader/tsShapeLoader.cpp b/Engine/source/ts/loader/tsShapeLoader.cpp index 5170867df..a1b1b4ac4 100644 --- a/Engine/source/ts/loader/tsShapeLoader.cpp +++ b/Engine/source/ts/loader/tsShapeLoader.cpp @@ -32,9 +32,9 @@ const F32 TSShapeLoader::DefaultTime = -1.0f; -const double TSShapeLoader::MinFrameRate = 15.0f; -const double TSShapeLoader::MaxFrameRate = 60.0f; -const double TSShapeLoader::AppGroundFrameRate = 10.0f; +const F64 TSShapeLoader::MinFrameRate = 15.0f; +const F64 TSShapeLoader::MaxFrameRate = 60.0f; +const F64 TSShapeLoader::AppGroundFrameRate = 10.0f; Torque::Path TSShapeLoader::shapePath; //------------------------------------------------------------------------------ @@ -102,7 +102,7 @@ void TSShapeLoader::generateNodeTransform(AppNode* node, F32 t, bool blend, F32 //----------------------------------------------------------------------------- -void TSShapeLoader::updateProgress(int major, const char* msg, int numMinor, int minor) +void TSShapeLoader::updateProgress(S32 major, const char* msg, S32 numMinor, S32 minor) { // Calculate progress value F32 progress = (F32)major / NumLoadPhases; @@ -229,7 +229,7 @@ bool cmpShapeName(const String& key, const Vector& names, void* arg1, vo String getUniqueName(const char* name, NameCmpFunc isNameUnique, const Vector& names, void* arg1=0, void* arg2=0) { - const int MAX_ITERATIONS = 0x10000; // maximum of 4 characters (A-P) will be appended + const S32 MAX_ITERATIONS = 0x10000; // maximum of 4 characters (A-P) will be appended String suffix; for (S32 i = 0; i < MAX_ITERATIONS; i++) @@ -336,7 +336,7 @@ void TSShapeLoader::recurseSubshape(AppNode* appNode, S32 parentIndex, bool recu // Create children if (recurseChildren) { - for (int iChild = 0; iChild < appNode->getNumChildNodes(); iChild++) + for (S32 iChild = 0; iChild < appNode->getNumChildNodes(); iChild++) recurseSubshape(appNode->getChildNode(iChild), myIndex, true); } } @@ -500,9 +500,9 @@ void TSShapeLoader::generateObjects() void TSShapeLoader::generateSkins() { Vector skins; - for (int iObject = 0; iObject < shape->objects.size(); iObject++) + for (S32 iObject = 0; iObject < shape->objects.size(); iObject++) { - for (int iMesh = 0; iMesh < shape->objects[iObject].numMeshes; iMesh++) + for (S32 iMesh = 0; iMesh < shape->objects[iObject].numMeshes; iMesh++) { AppMesh* mesh = appMeshes[shape->objects[iObject].startMeshIndex + iMesh]; if (mesh->isSkin()) @@ -510,7 +510,7 @@ void TSShapeLoader::generateSkins() } } - for (int iSkin = 0; iSkin < skins.size(); iSkin++) + for (S32 iSkin = 0; iSkin < skins.size(); iSkin++) { updateProgress(Load_GenerateSkins, "Generating skins...", skins.size(), iSkin); @@ -524,11 +524,11 @@ void TSShapeLoader::generateSkins() // Map bones to nodes skin->nodeIndex.setSize(skin->bones.size()); - for (int iBone = 0; iBone < skin->bones.size(); iBone++) + for (S32 iBone = 0; iBone < skin->bones.size(); iBone++) { // Find the node that matches this bone skin->nodeIndex[iBone] = -1; - for (int iNode = 0; iNode < appNodes.size(); iNode++) + for (S32 iNode = 0; iNode < appNodes.size(); iNode++) { if (appNodes[iNode]->isEqual(skin->bones[iBone])) { @@ -551,7 +551,7 @@ void TSShapeLoader::generateSkins() void TSShapeLoader::generateDefaultStates() { // Generate default object states (includes initial geometry) - for (int iObject = 0; iObject < shape->objects.size(); iObject++) + for (S32 iObject = 0; iObject < shape->objects.size(); iObject++) { updateProgress(Load_GenerateDefaultStates, "Generating initial mesh and node states...", shape->objects.size(), iObject); @@ -559,7 +559,7 @@ void TSShapeLoader::generateDefaultStates() TSShape::Object& obj = shape->objects[iObject]; // Calculate the objectOffset for each mesh at T=0 - for (int iMesh = 0; iMesh < obj.numMeshes; iMesh++) + for (S32 iMesh = 0; iMesh < obj.numMeshes; iMesh++) { AppMesh* appMesh = appMeshes[obj.startMeshIndex + iMesh]; AppNode* appNode = obj.nodeIndex >= 0 ? appNodes[obj.nodeIndex] : boundsNode; @@ -576,7 +576,7 @@ void TSShapeLoader::generateDefaultStates() } // Generate default node transforms - for (int iNode = 0; iNode < appNodes.size(); iNode++) + for (S32 iNode = 0; iNode < appNodes.size(); iNode++) { // Determine the default translation and rotation for the node QuatF rot, srot; @@ -610,7 +610,7 @@ void TSShapeLoader::generateObjectState(TSShape::Object& obj, F32 t, bool addFra void TSShapeLoader::generateFrame(TSShape::Object& obj, F32 t, bool addFrame, bool addMatFrame) { - for (int iMesh = 0; iMesh < obj.numMeshes; iMesh++) + for (S32 iMesh = 0; iMesh < obj.numMeshes; iMesh++) { AppMesh* appMesh = appMeshes[obj.startMeshIndex + iMesh]; @@ -690,7 +690,7 @@ void TSShapeLoader::generateMaterialList() { // Install the materials into the material list shape->materialList = new TSMaterialList; - for (int iMat = 0; iMat < AppMesh::appMaterials.size(); iMat++) + for (S32 iMat = 0; iMat < AppMesh::appMaterials.size(); iMat++) { updateProgress(Load_GenerateMaterials, "Generating materials...", AppMesh::appMaterials.size(), iMat); @@ -705,7 +705,7 @@ void TSShapeLoader::generateMaterialList() void TSShapeLoader::generateSequences() { - for (int iSeq = 0; iSeq < appSequences.size(); iSeq++) + for (S32 iSeq = 0; iSeq < appSequences.size(); iSeq++) { updateProgress(Load_GenerateSequences, "Generating sequences...", appSequences.size(), iSeq); @@ -783,14 +783,14 @@ void TSShapeLoader::setNodeMembership(TSShape::Sequence& seq, const AppSequence* void TSShapeLoader::setRotationMembership(TSShape::Sequence& seq) { - for (int iNode = 0; iNode < appNodes.size(); iNode++) + for (S32 iNode = 0; iNode < appNodes.size(); iNode++) { // Check if any of the node rotations are different to // the default rotation QuatF defaultRot; shape->defaultRotations[iNode].getQuatF(&defaultRot); - for (int iFrame = 0; iFrame < seq.numKeyframes; iFrame++) + for (S32 iFrame = 0; iFrame < seq.numKeyframes; iFrame++) { if (nodeRotCache[iNode][iFrame] != defaultRot) { @@ -803,13 +803,13 @@ void TSShapeLoader::setRotationMembership(TSShape::Sequence& seq) void TSShapeLoader::setTranslationMembership(TSShape::Sequence& seq) { - for (int iNode = 0; iNode < appNodes.size(); iNode++) + for (S32 iNode = 0; iNode < appNodes.size(); iNode++) { // Check if any of the node translations are different to // the default translation Point3F& defaultTrans = shape->defaultTranslations[iNode]; - for (int iFrame = 0; iFrame < seq.numKeyframes; iFrame++) + for (S32 iFrame = 0; iFrame < seq.numKeyframes; iFrame++) { if (!nodeTransCache[iNode][iFrame].equal(defaultTrans)) { @@ -828,10 +828,10 @@ void TSShapeLoader::setScaleMembership(TSShape::Sequence& seq) U32 alignedScaleCount = 0; U32 uniformScaleCount = 0; - for (int iNode = 0; iNode < appNodes.size(); iNode++) + for (S32 iNode = 0; iNode < appNodes.size(); iNode++) { // Check if any of the node scales are not the unit scale - for (int iFrame = 0; iFrame < seq.numKeyframes; iFrame++) + for (S32 iFrame = 0; iFrame < seq.numKeyframes; iFrame++) { Point3F& scale = nodeScaleCache[iNode][iFrame]; if (!unitScale.equal(scale)) @@ -865,7 +865,7 @@ void TSShapeLoader::setObjectMembership(TSShape::Sequence& seq, const AppSequenc seq.frameMatters.clearAll(); // vert animation (morph) (size = objects.size()) seq.matFrameMatters.clearAll(); // UV animation (size = objects.size()) - for (int iObject = 0; iObject < shape->objects.size(); iObject++) + for (S32 iObject = 0; iObject < shape->objects.size(); iObject++) { if (!appMeshes[shape->objects[iObject].startMeshIndex]) continue; @@ -883,16 +883,16 @@ void TSShapeLoader::setObjectMembership(TSShape::Sequence& seq, const AppSequenc void TSShapeLoader::clearNodeTransformCache() { // clear out the transform caches - for (int i = 0; i < nodeRotCache.size(); i++) + for (S32 i = 0; i < nodeRotCache.size(); i++) delete [] nodeRotCache[i]; nodeRotCache.clear(); - for (int i = 0; i < nodeTransCache.size(); i++) + for (S32 i = 0; i < nodeTransCache.size(); i++) delete [] nodeTransCache[i]; nodeTransCache.clear(); - for (int i = 0; i < nodeScaleRotCache.size(); i++) + for (S32 i = 0; i < nodeScaleRotCache.size(); i++) delete [] nodeScaleRotCache[i]; nodeScaleRotCache.clear(); - for (int i = 0; i < nodeScaleCache.size(); i++) + for (S32 i = 0; i < nodeScaleCache.size(); i++) delete [] nodeScaleCache[i]; nodeScaleCache.clear(); } @@ -903,23 +903,23 @@ void TSShapeLoader::fillNodeTransformCache(TSShape::Sequence& seq, const AppSequ clearNodeTransformCache(); nodeRotCache.setSize(appNodes.size()); - for (int i = 0; i < nodeRotCache.size(); i++) + for (S32 i = 0; i < nodeRotCache.size(); i++) nodeRotCache[i] = new QuatF[seq.numKeyframes]; nodeTransCache.setSize(appNodes.size()); - for (int i = 0; i < nodeTransCache.size(); i++) + for (S32 i = 0; i < nodeTransCache.size(); i++) nodeTransCache[i] = new Point3F[seq.numKeyframes]; nodeScaleRotCache.setSize(appNodes.size()); - for (int i = 0; i < nodeScaleRotCache.size(); i++) + for (S32 i = 0; i < nodeScaleRotCache.size(); i++) nodeScaleRotCache[i] = new QuatF[seq.numKeyframes]; nodeScaleCache.setSize(appNodes.size()); - for (int i = 0; i < nodeScaleCache.size(); i++) + for (S32 i = 0; i < nodeScaleCache.size(); i++) nodeScaleCache[i] = new Point3F[seq.numKeyframes]; // get the node transforms for every frame - for (int iFrame = 0; iFrame < seq.numKeyframes; iFrame++) + for (S32 iFrame = 0; iFrame < seq.numKeyframes; iFrame++) { F32 time = appSeq->getStart() + seq.duration * iFrame / getMax(1, seq.numKeyframes - 1); - for (int iNode = 0; iNode < appNodes.size(); iNode++) + for (S32 iNode = 0; iNode < appNodes.size(); iNode++) { generateNodeTransform(appNodes[iNode], time, seq.isBlend(), appSeq->getBlendRefTime(), nodeRotCache[iNode][iFrame], nodeTransCache[iNode][iFrame], @@ -973,9 +973,9 @@ void TSShapeLoader::generateNodeAnimation(TSShape::Sequence& seq) (seq.flags & TSShape::AlignedScale) ? shape->nodeAlignedScales.size() : shape->nodeUniformScales.size(); - for (int iNode = 0; iNode < appNodes.size(); iNode++) + for (S32 iNode = 0; iNode < appNodes.size(); iNode++) { - for (int iFrame = 0; iFrame < seq.numKeyframes; iFrame++) + for (S32 iFrame = 0; iFrame < seq.numKeyframes; iFrame++) { if (seq.rotationMatters.test(iNode)) addNodeRotation(nodeRotCache[iNode][iFrame], false); @@ -1001,7 +1001,7 @@ void TSShapeLoader::generateObjectAnimation(TSShape::Sequence& seq, const AppSeq { seq.baseObjectState = shape->objectStates.size(); - for (int iObject = 0; iObject < shape->objects.size(); iObject++) + for (S32 iObject = 0; iObject < shape->objects.size(); iObject++) { bool visMatters = seq.visMatters.test(iObject); bool frameMatters = seq.frameMatters.test(iObject); @@ -1009,7 +1009,7 @@ void TSShapeLoader::generateObjectAnimation(TSShape::Sequence& seq, const AppSeq if (visMatters || frameMatters || matFrameMatters) { - for (int iFrame = 0; iFrame < seq.numKeyframes; iFrame++) + for (S32 iFrame = 0; iFrame < seq.numKeyframes; iFrame++) { F32 time = appSeq->getStart() + seq.duration * iFrame / getMax(1, seq.numKeyframes - 1); generateObjectState(shape->objects[iObject], time, frameMatters, matFrameMatters); @@ -1036,7 +1036,7 @@ void TSShapeLoader::generateGroundAnimation(TSShape::Sequence& seq, const AppSeq zapScale(invStartMat); invStartMat.inverse(); - for (int iFrame = 0; iFrame < seq.numGroundFrames; iFrame++) + for (S32 iFrame = 0; iFrame < seq.numGroundFrames; iFrame++) { F32 time = appSeq->getStart() + seq.duration * iFrame / getMax(1, seq.numGroundFrames - 1); @@ -1064,7 +1064,7 @@ void TSShapeLoader::generateFrameTriggers(TSShape::Sequence& seq, const AppSeque seq.flags |= TSShape::MakePath; // Add triggers - for (int iTrigger = 0; iTrigger < seq.numTriggers; iTrigger++) + for (S32 iTrigger = 0; iTrigger < seq.numTriggers; iTrigger++) { shape->triggers.increment(); appSeq->getTrigger(iTrigger, shape->triggers.last()); @@ -1075,7 +1075,7 @@ void TSShapeLoader::generateFrameTriggers(TSShape::Sequence& seq, const AppSeque // need to mark ourselves as such so that on/off can become off/on when sequence // is played in reverse... U32 offTriggers = 0; - for (int iTrigger = 0; iTrigger < seq.numTriggers; iTrigger++) + for (S32 iTrigger = 0; iTrigger < seq.numTriggers; iTrigger++) { U32 state = shape->triggers[seq.firstTrigger+iTrigger].state; if ((state & TSShape::Trigger::StateOn) == 0) @@ -1098,18 +1098,18 @@ void TSShapeLoader::sortDetails() // Insert NULL meshes where required - for (int iSub = 0; iSub < subshapes.size(); iSub++) + for (S32 iSub = 0; iSub < subshapes.size(); iSub++) { Vector validDetails; shape->getSubShapeDetails(iSub, validDetails); - for (int iDet = 0; iDet < validDetails.size(); iDet++) + for (S32 iDet = 0; iDet < validDetails.size(); iDet++) { TSShape::Detail &detail = shape->details[validDetails[iDet]]; if (detail.subShapeNum >= 0) detail.objectDetailNum = iDet; - for (int iObj = shape->subShapeFirstObject[iSub]; + for (S32 iObj = shape->subShapeFirstObject[iSub]; iObj < (shape->subShapeFirstObject[iSub] + shape->subShapeNumObjects[iSub]); iObj++) { @@ -1126,7 +1126,7 @@ void TSShapeLoader::sortDetails() object.numMeshes++; // Fixup the start index for the other objects - for (int k = iObj+1; k < shape->objects.size(); k++) + for (S32 k = iObj+1; k < shape->objects.size(); k++) shape->objects[k].startMeshIndex++; } } @@ -1256,17 +1256,17 @@ TSShapeLoader::~TSShapeLoader() clearNodeTransformCache(); // Clear shared AppMaterial list - for (int iMat = 0; iMat < AppMesh::appMaterials.size(); iMat++) + for (S32 iMat = 0; iMat < AppMesh::appMaterials.size(); iMat++) delete AppMesh::appMaterials[iMat]; AppMesh::appMaterials.clear(); // Delete Subshapes delete boundsNode; - for (int iSub = 0; iSub < subshapes.size(); iSub++) + for (S32 iSub = 0; iSub < subshapes.size(); iSub++) delete subshapes[iSub]; // Delete AppSequences - for (int iSeq = 0; iSeq < appSequences.size(); iSeq++) + for (S32 iSeq = 0; iSeq < appSequences.size(); iSeq++) delete appSequences[iSeq]; appSequences.clear(); } diff --git a/Engine/source/ts/loader/tsShapeLoader.h b/Engine/source/ts/loader/tsShapeLoader.h index 83e9db0ca..2c76ffbb2 100644 --- a/Engine/source/ts/loader/tsShapeLoader.h +++ b/Engine/source/ts/loader/tsShapeLoader.h @@ -63,7 +63,7 @@ public: Load_Complete = NumLoadPhases }; - static void updateProgress(int major, const char* msg, int numMinor=0, int minor=0); + static void updateProgress(S32 major, const char* msg, S32 numMinor=0, S32 minor=0); protected: struct Subshape @@ -82,9 +82,9 @@ protected: public: static const F32 DefaultTime; - static const double MinFrameRate; - static const double MaxFrameRate; - static const double AppGroundFrameRate; + static const F64 MinFrameRate; + static const F64 MaxFrameRate; + static const F64 AppGroundFrameRate; protected: // Variables used during loading that must be held until the shape is deleted diff --git a/Engine/source/ts/tsLastDetail.h b/Engine/source/ts/tsLastDetail.h index adfd6b5ac..abfb3bac1 100644 --- a/Engine/source/ts/tsLastDetail.h +++ b/Engine/source/ts/tsLastDetail.h @@ -62,12 +62,12 @@ GFXDeclareVertexFormat( ImposterState ) /// .xyz = imposter center /// .w = billboard corner... damn SM 2.0 Point3F center; - float corner; + F32 corner; /// .x = scaled half size /// .y = alpha fade out - float halfSize; - float alpha; + F32 halfSize; + F32 alpha; /// The rotation encoded as the up /// and right vectors... cross FTW. diff --git a/Engine/source/ts/tsMesh.cpp b/Engine/source/ts/tsMesh.cpp index d857c0547..f1af288f1 100644 --- a/Engine/source/ts/tsMesh.cpp +++ b/Engine/source/ts/tsMesh.cpp @@ -1203,7 +1203,7 @@ void TSSkinMesh::updateSkin( const Vector &transforms, TSVertexBufferHa // set up bone transforms PROFILE_START(TSSkinMesh_UpdateTransforms); - for( int i=0; i &transforms, TSVertexBufferHa skinnedVert.zero(); skinnedNorm.zero(); - for( int tOp = 0; tOp < curVert.transformCount; tOp++ ) + for( S32 tOp = 0; tOp < curVert.transformCount; tOp++ ) { const BatchData::TransformOp &transformOp = curVert.transform[tOp]; @@ -1418,7 +1418,7 @@ void TSSkinMesh::createBatchData() itr != batchOperations.end(); itr++ ) { const BatchData::BatchedVertex &curTransform = *itr; - for( int i = 0; i < curTransform.transformCount; i++ ) + for( S32 i = 0; i < curTransform.transformCount; i++ ) { const BatchData::TransformOp &transformOp = curTransform.transform[i]; @@ -1443,8 +1443,8 @@ void TSSkinMesh::createBatchData() // Now iterate the resulting operations and convert the vectors to aligned // memory locations - const int numBatchOps = batchData.transformKeys.size(); - for(int i = 0; i < numBatchOps; i++) + const S32 numBatchOps = batchData.transformKeys.size(); + for(S32 i = 0; i < numBatchOps; i++) { BatchData::BatchedTransform &curTransform = *batchData.transformBatchOperations.retreive(batchData.transformKeys[i]); const S32 numVerts = curTransform._tmpVec->size(); @@ -1462,7 +1462,7 @@ void TSSkinMesh::createBatchData() } // Now sort the batch data so that the skin function writes close to linear output - for(int i = 0; i < numBatchOps; i++) + for(S32 i = 0; i < numBatchOps; i++) { BatchData::BatchedTransform &curTransform = *batchData.transformBatchOperations.retreive(batchData.transformKeys[i]); dQsort(curTransform.alignedMem, curTransform.numElements, sizeof(BatchData::BatchedVertWeight), _sort_BatchedVertWeight); @@ -2558,7 +2558,7 @@ void TSMesh::assemble( bool skip ) // need to copy to temporary arrays deleteInputArrays = true; primIn = new TSDrawPrimitive[szPrimIn]; - for (int i = 0; i < szPrimIn; i++) + for (S32 i = 0; i < szPrimIn; i++) { primIn[i].start = prim16[i*2]; primIn[i].numElements = prim16[i*2+1]; @@ -2917,8 +2917,11 @@ inline void TSMesh::findTangent( U32 index1, F32 denom = (s1 * t2 - s2 * t1); if( mFabs( denom ) < 0.0001f ) - return; // handle degenerate triangles from strips - + { + // handle degenerate triangles from strips + if (denom<0) denom = -0.0001f; + else denom = 0.0001f; + } F32 r = 1.0f / denom; Point3F sdir( (t2 * x1 - t1 * x2) * r, diff --git a/Engine/source/ts/tsMesh.h b/Engine/source/ts/tsMesh.h index 0db76ecc8..d2ac79087 100644 --- a/Engine/source/ts/tsMesh.h +++ b/Engine/source/ts/tsMesh.h @@ -214,7 +214,7 @@ class TSMesh } // Vector-like interface - __TSMeshVertexBase &operator[](int idx) const { AssertFatal(idx < numElements, "Out of bounds access!"); return *reinterpret_cast<__TSMeshVertexBase *>(base + idx * vertSz); } + __TSMeshVertexBase &operator[](S32 idx) const { AssertFatal(idx < numElements, "Out of bounds access!"); return *reinterpret_cast<__TSMeshVertexBase *>(base + idx * vertSz); } __TSMeshVertexBase *address() const { return reinterpret_cast<__TSMeshVertexBase *>(base); } U32 size() const { return numElements; } dsize_t mem_size() const { return numElements * vertSz; } diff --git a/Engine/source/ts/tsMeshIntrinsics.cpp b/Engine/source/ts/tsMeshIntrinsics.cpp index fbc93fbe8..94b9abd22 100644 --- a/Engine/source/ts/tsMeshIntrinsics.cpp +++ b/Engine/source/ts/tsMeshIntrinsics.cpp @@ -38,7 +38,7 @@ void zero_vert_normal_bulk_C(const dsize_t count, U8 * __restrict const outPtr, // TODO: Try prefetch w/ ptr de-reference - for(register int i = 0; i < count; i++) + for(register S32 i = 0; i < count; i++) { TSMesh::__TSMeshVertexBase *outElem = reinterpret_cast(outData); outElem->_vert.zero(); @@ -60,7 +60,7 @@ void m_matF_x_BatchedVertWeightList_C(const MatrixF &mat, register Point3F tempPt; register Point3F tempNrm; - for(register int i = 0; i < count; i++) + for(register S32 i = 0; i < count; i++) { const TSSkinMesh::BatchData::BatchedVertWeight &inElem = batch[i]; diff --git a/Engine/source/ts/tsShape.cpp b/Engine/source/ts/tsShape.cpp index 726efabff..d01a871c5 100644 --- a/Engine/source/ts/tsShape.cpp +++ b/Engine/source/ts/tsShape.cpp @@ -1225,7 +1225,7 @@ void TSShape::assembleShape() if (smReadVersion<23) { // get detail information about skins... - S32 * detailFirstSkin = tsalloc.getPointer32(numDetails); + S32 * detFirstSkin = tsalloc.getPointer32(numDetails); S32 * detailNumSkins = tsalloc.getPointer32(numDetails); tsalloc.checkGuard(); @@ -1257,7 +1257,7 @@ void TSShape::assembleShape() ptr32 = tsalloc.allocShape32(numSkins); for (i=0; i= 0) && ((subShapeNum == -1) || (details[i].subShapeNum == subShapeNum))) @@ -1521,7 +1521,7 @@ bool TSShape::addSequence(const Torque::Path& path, const String& fromSeq, // Check if visibility is animated within the frames to be copied const F32 defaultVis = srcShape->objectStates[i].vis; S32 objNum = srcSeq->visMatters.count(i); - for (int iFrame = startFrame; iFrame <= endFrame; iFrame++) + for (S32 iFrame = startFrame; iFrame <= endFrame; iFrame++) { if (srcShape->getObjectState(*srcSeq, iFrame, objNum).vis != defaultVis) { @@ -1600,7 +1600,7 @@ bool TSShape::addSequence(const Torque::Path& path, const String& fromSeq, // Check if node position is animated within the frames to be copied const Point3F& defaultTrans = srcShape->defaultTranslations[i]; S32 tranNum = srcSeq->translationMatters.count(i); - for (int iFrame = startFrame; iFrame <= endFrame; iFrame++) + for (S32 iFrame = startFrame; iFrame <= endFrame; iFrame++) { if (srcShape->getTranslation(*srcSeq, iFrame, tranNum) != defaultTrans) { @@ -1615,7 +1615,7 @@ bool TSShape::addSequence(const Torque::Path& path, const String& fromSeq, // Check if node rotation is animated within the frames to be copied const QuatF defaultRot = srcShape->defaultRotations[i].getQuatF(); S32 rotNum = srcSeq->rotationMatters.count(i); - for (int iFrame = startFrame; iFrame <= endFrame; iFrame++) + for (S32 iFrame = startFrame; iFrame <= endFrame; iFrame++) { QuatF temp; if (srcShape->getRotation(*srcSeq, iFrame, rotNum, &temp) != defaultRot) @@ -1634,7 +1634,7 @@ bool TSShape::addSequence(const Torque::Path& path, const String& fromSeq, { TSScale defaultScale; defaultScale.identity(); - for (int iFrame = startFrame; iFrame <= endFrame; iFrame++) + for (S32 iFrame = startFrame; iFrame <= endFrame; iFrame++) { TSScale temp; if (!(srcShape->getArbitraryScale(*srcSeq, iFrame, scaleNum, &temp) == defaultScale)) @@ -1647,7 +1647,7 @@ bool TSShape::addSequence(const Torque::Path& path, const String& fromSeq, else if (srcSeq->animatesAlignedScale()) { const Point3F defaultScale(Point3F::One); - for (int iFrame = startFrame; iFrame <= endFrame; iFrame++) + for (S32 iFrame = startFrame; iFrame <= endFrame; iFrame++) { if (srcShape->getAlignedScale(*srcSeq, iFrame, scaleNum) != defaultScale) { @@ -1659,7 +1659,7 @@ bool TSShape::addSequence(const Torque::Path& path, const String& fromSeq, else if (srcSeq->animatesUniformScale()) { const F32 defaultScale = 1.0f; - for (int iFrame = startFrame; iFrame <= endFrame; iFrame++) + for (S32 iFrame = startFrame; iFrame <= endFrame; iFrame++) { if (srcShape->getUniformScale(*srcSeq, iFrame, scaleNum) != defaultScale) { diff --git a/Engine/source/ts/tsShapeInstance.cpp b/Engine/source/ts/tsShapeInstance.cpp index cbe2ffc94..d8722b6f9 100644 --- a/Engine/source/ts/tsShapeInstance.cpp +++ b/Engine/source/ts/tsShapeInstance.cpp @@ -616,6 +616,11 @@ S32 TSShapeInstance::setDetailFromDistance( const SceneRenderState *state, F32 s F32 pixelRadius = ( mShape->radius / scaledDistance ) * state->getWorldToScreenScale().y * pixelScale; F32 pixelSize = pixelRadius * smDetailAdjust; + if ( pixelSize < smSmallestVisiblePixelSize ) { + mCurrentDetailLevel = -1; + return mCurrentDetailLevel; + } + if ( pixelSize > smSmallestVisiblePixelSize && pixelSize <= mShape->mSmallestVisibleSize ) pixelSize = mShape->mSmallestVisibleSize + 0.01f; diff --git a/Engine/source/ts/tsShapeInstance.h b/Engine/source/ts/tsShapeInstance.h index f507f7153..7f83851c4 100644 --- a/Engine/source/ts/tsShapeInstance.h +++ b/Engine/source/ts/tsShapeInstance.h @@ -485,8 +485,8 @@ protected: /// @} - virtual void render( const TSRenderState &rdata ); - virtual void render( const TSRenderState &rdata, S32 dl, F32 intraDL = 0.0f ); + void render( const TSRenderState &rdata ); + void render( const TSRenderState &rdata, S32 dl, F32 intraDL = 0.0f ); void animate() { animate( mCurrentDetailLevel ); } void animate(S32 dl); diff --git a/Engine/source/ts/tsShapeOldRead.cpp b/Engine/source/ts/tsShapeOldRead.cpp index e76198de3..d20175a2e 100644 --- a/Engine/source/ts/tsShapeOldRead.cpp +++ b/Engine/source/ts/tsShapeOldRead.cpp @@ -29,7 +29,7 @@ // put old skins into object list //------------------------------------------------- -void TSShape::fixupOldSkins(S32 numMeshes, S32 numSkins, S32 numDetails, S32 * detailFirstSkin, S32 * detailNumSkins) +void TSShape::fixupOldSkins(S32 numMeshes, S32 numSkins, S32 numDetails, S32 * detFirstSkin, S32 * detailNumSkins) { #if !defined(TORQUE_MAX_LIB) // this method not necessary in exporter, and a couple lines won't compile for exporter @@ -63,9 +63,9 @@ void TSShape::fixupOldSkins(S32 numMeshes, S32 numSkins, S32 numDetails, S32 * d // find one mesh per detail to add to this object // don't really need to be versions of the same object i = 0; - while (i *src, Vector *dst, U32 iterations for (S32 k=0; k < (size*size); k++) c[k] = 0.0f; - for (int i=0; i +template< S32 NUM_DIMENSIONS > class ScopeTrackerObject { public: @@ -264,7 +264,7 @@ class ScopeTrackerObject /// /// @param NUM_DIMENSIONS Number of dimensions to track; must be <=4. /// @param Object Value type for objects tracked by the ScopeTracker. Must have pointer behavior. -template< int NUM_DIMENSIONS, typename Object > +template< S32 NUM_DIMENSIONS, typename Object > class ScopeTracker { public: @@ -356,7 +356,7 @@ class ScopeTracker //----------------------------------------------------------------------------- -template< int NUM_DIMENSIONS, class Object > +template< S32 NUM_DIMENSIONS, class Object > ScopeTracker< NUM_DIMENSIONS, Object >::ScopeTracker() : mReferenceObject( NULL ) { @@ -385,7 +385,7 @@ ScopeTracker< NUM_DIMENSIONS, Object >::ScopeTracker() //----------------------------------------------------------------------------- -template< int NUM_DIMENSIONS, class Object > +template< S32 NUM_DIMENSIONS, class Object > void ScopeTracker< NUM_DIMENSIONS, Object >::setReferenceObject( Object object ) { AssertFatal( !object || !Deref( object ).isRegistered(), @@ -433,7 +433,7 @@ void ScopeTracker< NUM_DIMENSIONS, Object >::setReferenceObject( Object object ) //----------------------------------------------------------------------------- -template< int NUM_DIMENSIONS, class Object > +template< S32 NUM_DIMENSIONS, class Object > void ScopeTracker< NUM_DIMENSIONS, Object >::registerObject( Object object ) { PROFILE_SCOPE( ScopeTracker_registerObject ); @@ -469,7 +469,7 @@ void ScopeTracker< NUM_DIMENSIONS, Object >::registerObject( Object object ) //----------------------------------------------------------------------------- -template< int NUM_DIMENSIONS, class Object > +template< S32 NUM_DIMENSIONS, class Object > void ScopeTracker< NUM_DIMENSIONS, Object >::unregisterObject( Object object ) { PROFILE_SCOPE( ScopeTracker_unregisterObject ); @@ -494,7 +494,7 @@ void ScopeTracker< NUM_DIMENSIONS, Object >::unregisterObject( Object object ) //----------------------------------------------------------------------------- -template< int NUM_DIMENSIONS, class Object > +template< S32 NUM_DIMENSIONS, class Object > void ScopeTracker< NUM_DIMENSIONS, Object >::updateObject( Object object ) { PROFILE_SCOPE( ScopeTracker_updateObject ); @@ -554,7 +554,7 @@ void ScopeTracker< NUM_DIMENSIONS, Object >::updateObject( Object object ) //----------------------------------------------------------------------------- -template< int NUM_DIMENSIONS, class Object > +template< S32 NUM_DIMENSIONS, class Object > void ScopeTracker< NUM_DIMENSIONS, Object >::_insertTrackingNode( U32 dimension, NodeType* node ) { //RDTODO: substitute brute-force search with some smarter insertion algorithm @@ -579,7 +579,7 @@ void ScopeTracker< NUM_DIMENSIONS, Object >::_insertTrackingNode( U32 dimension, //----------------------------------------------------------------------------- -template< int NUM_DIMENSIONS, class Object > +template< S32 NUM_DIMENSIONS, class Object > void ScopeTracker< NUM_DIMENSIONS, Object >::_removeTrackingNode( U32 dimension, NodeType* node ) { NodeType* next = node->getNext(); @@ -597,7 +597,7 @@ void ScopeTracker< NUM_DIMENSIONS, Object >::_removeTrackingNode( U32 dimension, //----------------------------------------------------------------------------- -template< int NUM_DIMENSIONS, class Object > +template< S32 NUM_DIMENSIONS, class Object > void ScopeTracker< NUM_DIMENSIONS, Object >::_moveTrackingNode( U32 dimension, NodeType* node, F32 newPosition ) { PROFILE_SCOPE( ScopeTracker_moveTrackingNode ); @@ -713,7 +713,7 @@ void ScopeTracker< NUM_DIMENSIONS, Object >::_moveTrackingNode( U32 dimension, N //----------------------------------------------------------------------------- -template< int NUM_DIMENSIONS, class Object > +template< S32 NUM_DIMENSIONS, class Object > void ScopeTracker< NUM_DIMENSIONS, Object >::_setScope( Object object ) { // If there's no reference object, all objects are out of scope. @@ -756,7 +756,7 @@ void ScopeTracker< NUM_DIMENSIONS, Object >::_setScope( Object object ) //----------------------------------------------------------------------------- -template< int NUM_DIMENSIONS, class Object > +template< S32 NUM_DIMENSIONS, class Object > void ScopeTracker< NUM_DIMENSIONS, Object >::_initTracking() { PROFILE_SCOPE( ScopeTracker_initTracking ); @@ -813,7 +813,7 @@ void ScopeTracker< NUM_DIMENSIONS, Object >::_initTracking() //----------------------------------------------------------------------------- -template< int NUM_DIMENSIONS, class Object > +template< S32 NUM_DIMENSIONS, class Object > void ScopeTracker< NUM_DIMENSIONS, Object >::_uninitTracking() { PROFILE_SCOPE( ScopeTracker_uninitTracking ); @@ -842,7 +842,7 @@ void ScopeTracker< NUM_DIMENSIONS, Object >::_uninitTracking() //----------------------------------------------------------------------------- -template< int NUM_DIMENSIONS, class Object > +template< S32 NUM_DIMENSIONS, class Object > void ScopeTracker< NUM_DIMENSIONS, Object >::debugDump() { for( U32 n = 0; n < NUM_DIMENSIONS; ++ n ) diff --git a/Engine/source/util/settings.cpp b/Engine/source/util/settings.cpp index 19de55673..826c26cff 100644 --- a/Engine/source/util/settings.cpp +++ b/Engine/source/util/settings.cpp @@ -288,7 +288,6 @@ void Settings::readLayer(SimXMLDocument *document, String groupStack) { for(S32 i=0; document->pushChildElement(i); i++) { - bool groupCount = 0; const UTF8 *type = document->elementValue(); const UTF8 *name = document->attribute("name"); const UTF8 *value = document->getText(); @@ -302,7 +301,6 @@ void Settings::readLayer(SimXMLDocument *document, String groupStack) newStack += name; readLayer(document, newStack); - groupCount++; } else if(dStrcmp(type, "Setting") == 0) { String nameString = groupStack; @@ -635,13 +633,13 @@ void SettingSaveNode::buildDocument(SimXMLDocument *document, bool skipWrite) document->addText(mValue); } else { - for(int i=0; ibuildDocument(document); } - for(int i=0; ibuildDocument(document); diff --git a/Engine/source/windowManager/platformInterface.cpp b/Engine/source/windowManager/platformInterface.cpp index ff34d37db..b756b988a 100644 --- a/Engine/source/windowManager/platformInterface.cpp +++ b/Engine/source/windowManager/platformInterface.cpp @@ -70,7 +70,7 @@ static struct ModifierBitMap { { IM_LOPT, SI_MAC_LOPT }, { IM_ROPT, SI_MAC_ROPT }, }; -static int _ModifierBitMapCount = sizeof(_ModifierBitMap) / sizeof(ModifierBitMap); +static S32 _ModifierBitMapCount = sizeof(_ModifierBitMap) / sizeof(ModifierBitMap); InputModifiers convertModifierBits(const U32 in) { @@ -121,7 +121,7 @@ void Platform::closeWindow() -#ifdef TORQUE_OS_WIN32 +#ifdef TORQUE_OS_WIN // Hack so we can get the HWND of the global window more easily - replacement // for the HWND that was in the platstate. #include "windowManager/win32/win32Window.h" diff --git a/Engine/source/windowManager/win32/win32Window.cpp b/Engine/source/windowManager/win32/win32Window.cpp index 2094bc663..0cbb59433 100644 --- a/Engine/source/windowManager/win32/win32Window.cpp +++ b/Engine/source/windowManager/win32/win32Window.cpp @@ -1068,7 +1068,7 @@ bool Win32Window::translateMessage(MSG &msg) if(mAccelHandle == NULL || mWindowHandle == NULL || !mEnableAccelerators) return false; - int ret = TranslateAccelerator(mWindowHandle, mAccelHandle, &msg); + S32 ret = TranslateAccelerator(mWindowHandle, mAccelHandle, &msg); return ret != 0; } diff --git a/Engine/source/windowManager/win32/win32WindowMgr.cpp b/Engine/source/windowManager/win32/win32WindowMgr.cpp index 05e889c9a..3777a01f6 100644 --- a/Engine/source/windowManager/win32/win32WindowMgr.cpp +++ b/Engine/source/windowManager/win32/win32WindowMgr.cpp @@ -41,7 +41,8 @@ PlatformWindowManager * CreatePlatformWindowManager() Win32WindowManager::Win32WindowManager() { // Register in the process list. - Process::notify(this, &Win32WindowManager::_process, PROCESS_INPUT_ORDER); + mOnProcessSignalSlot.setDelegate( this, &Win32WindowManager::_process ); + Process::notify( mOnProcessSignalSlot, PROCESS_INPUT_ORDER ); // Init our list of allocated windows. mWindowListHead = NULL; @@ -58,9 +59,6 @@ Win32WindowManager::Win32WindowManager() Win32WindowManager::~Win32WindowManager() { - // Get ourselves off the process list. - Process::remove(this, &Win32WindowManager::_process); - // Kill all our windows first. while(mWindowListHead) // The destructors update the list, so this works just fine. @@ -452,7 +450,7 @@ void Win32WindowManager::_processCmdLineArgs( const S32 argc, const char **argv { if (argc > 1) { - for (int i = 1; i < argc; i++) + for (S32 i = 1; i < argc; i++) { if ( dStrnicmp( argv[i], "-window", 7 ) == 0 ) { diff --git a/Engine/source/windowManager/win32/win32WindowMgr.h b/Engine/source/windowManager/win32/win32WindowMgr.h index a5c747501..be9cdaa42 100644 --- a/Engine/source/windowManager/win32/win32WindowMgr.h +++ b/Engine/source/windowManager/win32/win32WindowMgr.h @@ -85,6 +85,8 @@ class Win32WindowManager : public PlatformWindowManager /// If a curtain window is present, then its HWND will be stored here. HWND mCurtainWindow; + SignalSlot mOnProcessSignalSlot; + public: Win32WindowManager(); ~Win32WindowManager(); diff --git a/Engine/source/windowManager/win32/winDispatch.cpp b/Engine/source/windowManager/win32/winDispatch.cpp index f49010f0e..7038d0a29 100644 --- a/Engine/source/windowManager/win32/winDispatch.cpp +++ b/Engine/source/windowManager/win32/winDispatch.cpp @@ -283,7 +283,7 @@ static bool _dispatch(HWND hWnd,UINT message,WPARAM wParam,WPARAM lParam) case WM_LBUTTONDOWN: case WM_MBUTTONDOWN: case WM_RBUTTONDOWN: { - int index = (message - WM_LBUTTONDOWN) / 3; + S32 index = (message - WM_LBUTTONDOWN) / 3; button[index] = true; // Capture the mouse on button down to allow dragging outside @@ -299,7 +299,7 @@ static bool _dispatch(HWND hWnd,UINT message,WPARAM wParam,WPARAM lParam) case WM_LBUTTONUP: case WM_MBUTTONUP: case WM_RBUTTONUP: { - int index = (message - WM_LBUTTONUP) / 3; + S32 index = (message - WM_LBUTTONUP) / 3; button[index] = false; // Release mouse capture from button down. diff --git a/My Projects/readme.txt b/My Projects/readme.txt index 299a8f786..9663bd6e3 100644 --- a/My Projects/readme.txt +++ b/My Projects/readme.txt @@ -1 +1 @@ -The Torque Toolbox places your projects here. +your projects will go in this folder \ No newline at end of file diff --git a/Templates/Empty/buildFiles/config/torque3D_dedicated.conf b/Templates/Empty/buildFiles/config/torque3D_dedicated.conf index eecf2fc4f..ec0b6281d 100644 --- a/Templates/Empty/buildFiles/config/torque3D_dedicated.conf +++ b/Templates/Empty/buildFiles/config/torque3D_dedicated.conf @@ -60,14 +60,14 @@ addProjectDependency( 'libbullet' ); } - if ( Generator::$platform == "mac" ) + if ( T3D_Generator::$platform == "mac" ) { addProjectDefine( '__MACOSX__' ); addProjectDefine( 'LTM_DESC' ); } - if (Generator::$platform == "win32") + if (T3D_Generator::$platform == "win32") { setProjectModuleDefinitionFile('../../' . getLibSrcDir() . 'Torque3D/msvc/torque3d.def'); diff --git a/Templates/Empty/game/core/scripts/gui/messageBoxes/messageBox.ed.cs b/Templates/Empty/game/core/scripts/gui/messageBoxes/messageBox.ed.cs index d778ae7ee..7c970c341 100644 --- a/Templates/Empty/game/core/scripts/gui/messageBoxes/messageBox.ed.cs +++ b/Templates/Empty/game/core/scripts/gui/messageBoxes/messageBox.ed.cs @@ -42,8 +42,8 @@ if( isObject( IODropdownDlg ) ) exec("./messageBoxOk.ed.gui"); exec("./messageBoxYesNo.ed.gui"); exec("./messageBoxYesNoCancel.ed.gui"); -exec("./messageBoxOKCancel.ed.gui"); -exec("./messageBoxOKCancelDetailsDlg.ed.gui"); +exec("./messageBoxOkCancel.ed.gui"); +exec("./MessageBoxOKCancelDetailsDlg.ed.gui"); exec("./messagePopup.ed.gui"); exec("./IODropdownDlg.ed.gui"); diff --git a/Templates/Empty/game/main.cs.in b/Templates/Empty/game/main.cs.in new file mode 100644 index 000000000..db8436e7d --- /dev/null +++ b/Templates/Empty/game/main.cs.in @@ -0,0 +1,280 @@ +//----------------------------------------------------------------------------- +// Copyright (c) 2012 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. +//----------------------------------------------------------------------------- + +// Set the name of our application +$appName = "@TORQUE_APP_NAME@"; + +// The directory it is run from +$defaultGame = "scripts"; + +// Set profile directory +$Pref::Video::ProfilePath = "core/profile"; + +function createCanvas(%windowTitle) +{ + if ($isDedicated) + { + GFXInit::createNullDevice(); + return true; + } + + // Create the Canvas + %foo = new GuiCanvas(Canvas); + + // Set the window title + if (isObject(Canvas)) + Canvas.setWindowTitle(getEngineName() @ " - " @ $appName); + + return true; +} + +// Display the optional commandline arguements +$displayHelp = false; + +// Use these to record and play back crashes +//saveJournal("editorOnFileQuitCrash.jrn"); +//playJournal("editorOnFileQuitCrash.jrn", false); + +//------------------------------------------------------------------------------ +// Check if a script file exists, compiled or not. +function isScriptFile(%path) +{ + if( isFile(%path @ ".dso") || isFile(%path) ) + return true; + + return false; +} + +//------------------------------------------------------------------------------ +// Process command line arguments +exec("core/parseArgs.cs"); + +$isDedicated = false; +$dirCount = 2; +$userDirs = $defaultGame @ ";art;levels"; + +// load tools scripts if we're a tool build +if (isToolBuild()) + $userDirs = "tools;" @ $userDirs; + + +// Parse the executable arguments with the standard +// function from core/main.cs +defaultParseArgs(); + + +if($dirCount == 0) { + $userDirs = $defaultGame; + $dirCount = 1; +} + +//----------------------------------------------------------------------------- +// Display a splash window immediately to improve app responsiveness before +// engine is initialized and main window created +if (!$isDedicated) + displaySplashWindow(); + + +//----------------------------------------------------------------------------- +// The displayHelp, onStart, onExit and parseArgs function are overriden +// by mod packages to get hooked into initialization and cleanup. + +function onStart() +{ + // Default startup function +} + +function onExit() +{ + // OnExit is called directly from C++ code, whereas onStart is + // invoked at the end of this file. +} + +function parseArgs() +{ + // Here for mod override, the arguments have already + // been parsed. +} + +function compileFiles(%pattern) +{ + %path = filePath(%pattern); + + %saveDSO = $Scripts::OverrideDSOPath; + %saveIgnore = $Scripts::ignoreDSOs; + + $Scripts::OverrideDSOPath = %path; + $Scripts::ignoreDSOs = false; + %mainCsFile = makeFullPath("main.cs"); + + for (%file = findFirstFileMultiExpr(%pattern); %file !$= ""; %file = findNextFileMultiExpr(%pattern)) + { + // we don't want to try and compile the primary main.cs + if(%mainCsFile !$= %file) + compile(%file, true); + } + + $Scripts::OverrideDSOPath = %saveDSO; + $Scripts::ignoreDSOs = %saveIgnore; + +} + +if($compileAll) +{ + echo(" --- Compiling all files ---"); + compileFiles("*.cs"); + compileFiles("*.gui"); + compileFiles("*.ts"); + echo(" --- Exiting after compile ---"); + quit(); +} + +if($compileTools) +{ + echo(" --- Compiling tools scritps ---"); + compileFiles("tools/*.cs"); + compileFiles("tools/*.gui"); + compileFiles("tools/*.ts"); + echo(" --- Exiting after compile ---"); + quit(); +} + +package Help { + function onExit() { + // Override onExit when displaying help + } +}; + +function displayHelp() { + activatePackage(Help); + + // Notes on logmode: console logging is written to console.log. + // -log 0 disables console logging. + // -log 1 appends to existing logfile; it also closes the file + // (flushing the write buffer) after every write. + // -log 2 overwrites any existing logfile; it also only closes + // the logfile when the application shuts down. (default) + + error( + "Torque Demo command line options:\n"@ + " -log Logging behavior; see main.cs comments for details\n"@ + " -game Reset list of mods to only contain \n"@ + " Works like the -game argument\n"@ + " -dir Add to list of directories\n"@ + " -console Open a separate console\n"@ + " -show Deprecated\n"@ + " -jSave Record a journal\n"@ + " -jPlay Play back a journal\n"@ + " -jDebug Play back a journal and issue an int3 at the end\n"@ + " -help Display this help message\n" + ); +} + + +//-------------------------------------------------------------------------- + +// Default to a new logfile each session. +if( !$logModeSpecified ) +{ + if( $platform !$= "xbox" && $platform !$= "xenon" ) + setLogMode(6); +} + +// Get the first dir on the list, which will be the last to be applied... this +// does not modify the list. +nextToken($userDirs, currentMod, ";"); + +// Execute startup scripts for each mod, starting at base and working up +function loadDir(%dir) +{ + pushback($userDirs, %dir, ";"); + + if (isScriptFile(%dir @ "/main.cs")) + exec(%dir @ "/main.cs"); +} + +echo("--------- Loading DIRS ---------"); +function loadDirs(%dirPath) +{ + %dirPath = nextToken(%dirPath, token, ";"); + if (%dirPath !$= "") + loadDirs(%dirPath); + + if(exec(%token @ "/main.cs") != true) + { + error("Error: Unable to find specified directory: " @ %token ); + $dirCount--; + } +} +loadDirs($userDirs); +echo(""); + +if($dirCount == 0) { + enableWinConsole(true); + error("Error: Unable to load any specified directories"); + quit(); +} +// Parse the command line arguments +echo("--------- Parsing Arguments ---------"); +parseArgs(); + +// Either display the help message or startup the app. +if ($displayHelp) { + enableWinConsole(true); + displayHelp(); + quit(); +} +else { + onStart(); + echo("Engine initialized..."); + + // Auto-load on the 360 + if( $platform $= "xenon" ) + { + %mission = "levels/Empty Terrain.mis"; + + echo("Xbox360 Autoloading level: '" @ %mission @ "'"); + + + if ($pref::HostMultiPlayer) + %serverType = "MultiPlayer"; + else + %serverType = "SinglePlayer"; + + createAndConnectToLocalServer( %serverType, %mission ); + } +} + +// Display an error message for unused arguments +for ($i = 1; $i < $Game::argc; $i++) { + if (!$argUsed[$i]) + error("Error: Unknown command line argument: " @ $Game::argv[$i]); +} + +// Automatically start up the appropriate eidtor, if any +if ($startWorldEditor) { + Canvas.setCursor("DefaultCursor"); + Canvas.setContent(EditorChooseLevelGui); +} else if ($startGUIEditor) { + Canvas.setCursor("DefaultCursor"); + Canvas.setContent(EditorChooseGUI); +} diff --git a/Templates/Empty/game/shaders/common/gl/blurP.glsl b/Templates/Empty/game/shaders/common/gl/blurP.glsl index bc05b992f..5c37ebc6b 100644 --- a/Templates/Empty/game/shaders/common/gl/blurP.glsl +++ b/Templates/Empty/game/shaders/common/gl/blurP.glsl @@ -26,12 +26,12 @@ uniform vec4 kernel; uniform sampler2D diffuseMap; -varying vec2 texc0, texc1, texc2, texc3; +in vec2 texc0, texc1, texc2, texc3; void main() { - gl_FragColor = texture2D(diffuseMap, texc0) * kernel.x; - gl_FragColor += texture2D(diffuseMap, texc1) * kernel.y; - gl_FragColor += texture2D(diffuseMap, texc2) * kernel.z; - gl_FragColor += texture2D(diffuseMap, texc3) * kernel.w; + OUT_FragColor0 = texture(diffuseMap, texc0) * kernel.x; + OUT_FragColor0 += texture(diffuseMap, texc1) * kernel.y; + OUT_FragColor0 += texture(diffuseMap, texc2) * kernel.z; + OUT_FragColor0 += texture(diffuseMap, texc3) * kernel.w; } diff --git a/Templates/Empty/game/shaders/common/gl/blurV.glsl b/Templates/Empty/game/shaders/common/gl/blurV.glsl index d5d615fb9..1bfb0cd1b 100644 --- a/Templates/Empty/game/shaders/common/gl/blurV.glsl +++ b/Templates/Empty/game/shaders/common/gl/blurV.glsl @@ -24,20 +24,25 @@ // Glow shader //***************************************************************************** +in vec4 vPosition; +in vec4 vColor; +in vec2 vTexCoord0; + uniform mat4 modelview; uniform vec2 offset0, offset1, offset2, offset3; -varying vec2 texc0, texc1, texc2, texc3; +out vec2 texc0, texc1, texc2, texc3; void main() { - gl_Position = modelview * gl_Vertex; + gl_Position = modelview * vPosition; - vec2 tc = gl_MultiTexCoord0.st; + vec2 tc = vTexCoord0.st; tc.y = 1.0 - tc.y; texc0 = tc + offset0; texc1 = tc + offset1; texc2 = tc + offset2; texc3 = tc + offset3; + gl_Position.y *= -1; } \ No newline at end of file diff --git a/Templates/Empty/game/shaders/common/gl/cloudLayerP.glsl b/Templates/Empty/game/shaders/common/gl/cloudLayerP.glsl index 326f2d3c6..da3996d58 100644 --- a/Templates/Empty/game/shaders/common/gl/cloudLayerP.glsl +++ b/Templates/Empty/game/shaders/common/gl/cloudLayerP.glsl @@ -22,12 +22,20 @@ #include "hlslCompat.glsl" -varying vec4 texCoord12; -varying vec4 texCoord34; -varying vec3 vLightTS; // light vector in tangent space, denormalized -varying vec3 vViewTS; // view vector in tangent space, denormalized -varying vec3 vNormalWS; // Normal vector in world space -varying float worldDist; +//----------------------------------------------------------------------------- +// Structures +//----------------------------------------------------------------------------- +//ConnectData +in vec4 texCoord12; +#define IN_texCoord12 texCoord12 +in vec4 texCoord34; +#define IN_texCoord34 texCoord34 +in vec3 vLightTS; // light vector in tangent space, denormalized +#define IN_vLightTS vLightTS +in vec3 vViewTS; // view vector in tangent space, denormalized +#define IN_vViewTS vViewTS +in float worldDist; +#define IN_worldDist worldDist //----------------------------------------------------------------------------- // Uniforms @@ -37,6 +45,7 @@ uniform vec3 ambientColor; uniform vec3 sunColor; uniform float cloudCoverage; uniform vec3 cloudBaseColor; +uniform float cloudExposure; //----------------------------------------------------------------------------- // Globals @@ -97,26 +106,25 @@ void main() // Normalize the interpolated vectors: vec3 vViewTS = normalize( vViewTS ); vec3 vLightTS = normalize( vLightTS ); - vec3 vNormalWS = normalize( vNormalWS ); - vec4 cResultColor = float4( 0, 0, 0, 1 ); + vec4 cResultColor = vec4( 0, 0, 0, 1 ); - vec2 texSample = texCoord12.xy; + vec2 texSample = IN_texCoord12.xy; - vec4 noise1 = texture2D( normalHeightMap, texCoord12.zw ); + vec4 noise1 = texture( normalHeightMap, IN_texCoord12.zw ); noise1 = normalize( ( noise1 - 0.5 ) * 2.0 ); //return noise1; - vec4 noise2 = texture2D( normalHeightMap, texCoord34.xy ); + vec4 noise2 = texture( normalHeightMap, IN_texCoord34.xy ); noise2 = normalize( ( noise2 - 0.5 ) * 2.0 ); //return noise2; vec3 noiseNormal = normalize( noise1 + noise2 ).xyz; - //return float4( noiseNormal, 1.0 ); + //return vec4( noiseNormal, 1.0 ); float noiseHeight = noise1.a * noise2.a * ( cloudCoverage / 2.0 + 0.5 ); - vec3 vNormalTS = normalize( texture2D( normalHeightMap, texSample ).xyz * 2.0 - 1.0 ); + vec3 vNormalTS = normalize( texture( normalHeightMap, texSample ).xyz * 2.0 - 1.0 ); vNormalTS += noiseNormal; vNormalTS = normalize( vNormalTS ); @@ -124,16 +132,14 @@ void main() cResultColor.rgb = ComputeIllumination( texSample, vLightTS, vViewTS, vNormalTS ); float coverage = ( cloudCoverage - 0.5 ) * 2.0; - cResultColor.a = texture2D( normalHeightMap, texSample ).a + coverage + noiseHeight; + cResultColor.a = texture( normalHeightMap, texSample ).a + coverage + noiseHeight; if ( cloudCoverage > -1.0 ) cResultColor.a /= 1.0 + coverage; - cResultColor.a = saturate( cResultColor.a * pow( saturate(cloudCoverage), 0.25 ) ); + cResultColor.a = clamp( cResultColor.a * pow( saturate(cloudCoverage), 0.25 ), 0.0, 1.0 ); - cResultColor.a = mix( cResultColor.a, 0.0, 1.0 - pow(worldDist,2.0) ); + cResultColor.a = mix( cResultColor.a, 0.0, 1.0 - pow(IN_worldDist,2.0) ); - // If using HDR rendering, make sure to tonemap the resuld color prior to outputting it. - // But since this example isn't doing that, we just output the computed result color here: - gl_FragColor = cResultColor; + OUT_FragColor0 = cResultColor; } diff --git a/Templates/Empty/game/shaders/common/gl/cloudLayerV.glsl b/Templates/Empty/game/shaders/common/gl/cloudLayerV.glsl index 39a6f4ba8..395c6f286 100644 --- a/Templates/Empty/game/shaders/common/gl/cloudLayerV.glsl +++ b/Templates/Empty/game/shaders/common/gl/cloudLayerV.glsl @@ -20,12 +20,24 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- -varying vec4 texCoord12; -varying vec4 texCoord34; -varying vec3 vLightTS; // light vector in tangent space, denormalized -varying vec3 vViewTS; // view vector in tangent space, denormalized -varying vec3 vNormalWS; // Normal vector in world space -varying float worldDist; +#include "hlslCompat.glsl" + +in vec4 vPosition; +in vec3 vNormal; +in vec3 vBinormal; +in vec3 vTangent; +in vec2 vTexCoord0; + +out vec4 texCoord12; +#define OUT_texCoord12 texCoord12 +out vec4 texCoord34; +#define OUT_texCoord34 texCoord34 +out vec3 vLightTS; // light vector in tangent space, denormalized +#define OUT_vLightTS vLightTS +out vec3 vViewTS; // view vector in tangent space, denormalized +#define OUT_vViewTS vViewTS +out float worldDist; +#define OUT_worldDist worldDist //----------------------------------------------------------------------------- // Uniforms @@ -43,37 +55,37 @@ uniform vec3 texScale; //----------------------------------------------------------------------------- void main() { - vec4 pos = gl_Vertex; - vec3 normal = gl_Normal; - vec3 binormal = gl_MultiTexCoord0.xyz; - vec3 tangent = gl_MultiTexCoord1.xyz; - vec2 uv0 = gl_MultiTexCoord2.st; + vec4 IN_pos = vPosition; + vec3 IN_normal = vNormal; + vec3 IN_binormal = vBinormal; + vec3 IN_tangent = vTangent; + vec2 IN_uv0 = vTexCoord0.st; - gl_Position = modelview * pos; + gl_Position = modelview * IN_pos; // Offset the uv so we don't have a seam directly over our head. - vec2 uv = uv0 + vec2( 0.5, 0.5 ); + vec2 uv = IN_uv0 + vec2( 0.5, 0.5 ); - texCoord12.xy = uv * texScale.x; - texCoord12.xy += texOffset0; + OUT_texCoord12.xy = uv * texScale.x; + OUT_texCoord12.xy += texOffset0; - texCoord12.zw = uv * texScale.y; - texCoord12.zw += texOffset1; + OUT_texCoord12.zw = uv * texScale.y; + OUT_texCoord12.zw += texOffset1; - texCoord34.xy = uv * texScale.z; - texCoord34.xy += texOffset2; + OUT_texCoord34.xy = uv * texScale.z; + OUT_texCoord34.xy += texOffset2; - texCoord34.z = pos.z; - texCoord34.w = 0.0; + OUT_texCoord34.z = IN_pos.z; + OUT_texCoord34.w = 0.0; // Transform the normal, tangent and binormal vectors from object space to // homogeneous projection space: - vNormalWS = -normal; - vec3 vTangentWS = -tangent; - vec3 vBinormalWS = -binormal; + vec3 vNormalWS = -IN_normal; + vec3 vTangentWS = -IN_tangent; + vec3 vBinormalWS = -IN_binormal; // Compute position in world space: - vec4 vPositionWS = pos + vec4( eyePosWorld, 1 ); //mul( pos, objTrans ); + vec4 vPositionWS = IN_pos + vec4( eyePosWorld, 1 ); //tMul( IN_pos, objTrans ); // Compute and output the world view vector (unnormalized): vec3 vViewWS = eyePosWorld - vPositionWS.xyz; @@ -81,12 +93,14 @@ void main() // Compute denormalized light vector in world space: vec3 vLightWS = -sunVec; - // Normalize the light and view vectors and transform it to the tangent space: + // Normalize the light and view vectors and transform it to the IN_tangent space: mat3 mWorldToTangent = mat3( vTangentWS, vBinormalWS, vNormalWS ); // Propagate the view and the light vectors (in tangent space): - vLightTS = mWorldToTangent * vLightWS; - vViewTS = vViewWS * mWorldToTangent; - - worldDist = clamp( pow( pos.z, 2.0 ), 0.0, 1.0 ); + OUT_vLightTS = vLightWS * mWorldToTangent; + OUT_vViewTS = mWorldToTangent * vViewWS; + + OUT_worldDist = clamp( pow( max( IN_pos.z, 0 ), 2 ), 0.0, 1.0 ); + + correctSSP(gl_Position); } diff --git a/Templates/Empty/game/shaders/common/gl/foliage.glsl b/Templates/Empty/game/shaders/common/gl/foliage.glsl index 2fee902e3..38b66e767 100644 --- a/Templates/Empty/game/shaders/common/gl/foliage.glsl +++ b/Templates/Empty/game/shaders/common/gl/foliage.glsl @@ -46,7 +46,19 @@ uniform vec3 gc_gustInfo; uniform vec2 gc_turbInfo; -//static float sMovableCorner[4] = { 0.0, 0.0, 1.0, 1.0 }; +const float sCornerRight[4] = float[]( -0.5, 0.5, 0.5, -0.5 ); + +const float sCornerUp[4] = float[]( 0, 0, 1, 1 ); + +const float sMovableCorner[4] = float[]( 0, 0, 1, 1 ); + +const vec2 sUVCornerExtent[4] = vec2[] +( + vec2( 0, 1 ), + vec2( 1, 1 ), + vec2( 1, 0 ), + vec2( 0, 0 ) +); /////////////////////////////////////////////////////////////////////////////// @@ -106,34 +118,13 @@ vec2 windEffect( float bbPhase, void foliageProcessVert( inout vec3 position, inout vec4 diffuse, - in vec4 texCoord, - out vec2 outTexCoord, + inout vec4 texCoord, inout vec3 normal, inout vec3 T, in vec3 eyePos ) { - - float sCornerRight[4]; - sCornerRight[0] = -0.5; - sCornerRight[1] = 0.5; - sCornerRight[2] = 0.5; - sCornerRight[3] = -0.5; - - float sCornerUp[4]; - sCornerUp[0] = 0.0; - sCornerUp[1] = 0.0; - sCornerUp[2] = 1.0; - sCornerUp[3] = 1.0; - - vec2 sUVCornerExtent[4]; - sUVCornerExtent[0] = vec2( 0.0, 1.0 ); - sUVCornerExtent[1] = vec2( 1.0, 1.0 ); - sUVCornerExtent[2] = vec2( 1.0, 0.0 ); - sUVCornerExtent[3] = vec2( 0.0, 0.0 ); - - // Assign the normal and tagent values. - //normal = cross( gc_camUp, gc_camRight ); + //normal = vec3( 0, 0, 1 );//cross( gc_camUp, gc_camRight ); T = gc_camRight; // Pull out local vars we need for work. @@ -172,8 +163,8 @@ void foliageProcessVert( inout vec3 position, // Grab the uv set and setup the texture coord. vec4 uvSet = gc_typeRects[type]; - outTexCoord.x = uvSet.x + ( uvSet.z * sUVCornerExtent[corner].x ); - outTexCoord.y = uvSet.y + ( uvSet.w * sUVCornerExtent[corner].y ); + texCoord.x = uvSet.x + ( uvSet.z * sUVCornerExtent[corner].x ); + texCoord.y = uvSet.y + ( uvSet.w * sUVCornerExtent[corner].y ); // Animate the normal to get lighting changes // across the the wind swept foliage. @@ -184,7 +175,6 @@ void foliageProcessVert( inout vec3 position, normal.xy += wind.xy * ( 10.0 * texCoord.w ); normal = normalize( normal ); - // Get the alpha fade value. float fadeStart = gc_fadeParams.x; diff --git a/Templates/Empty/game/shaders/common/gl/fxFoliageReplicatorP.glsl b/Templates/Empty/game/shaders/common/gl/fxFoliageReplicatorP.glsl index 9e5b34caa..fb5abb91e 100644 --- a/Templates/Empty/game/shaders/common/gl/fxFoliageReplicatorP.glsl +++ b/Templates/Empty/game/shaders/common/gl/fxFoliageReplicatorP.glsl @@ -26,15 +26,15 @@ uniform sampler2D diffuseMap, alphaMap; uniform vec4 groundAlpha; -varying vec4 color, groundAlphaCoeff; -varying vec2 outTexCoord, alphaLookup; +in vec4 color, groundAlphaCoeff; +in vec2 outTexCoord, alphaLookup; //----------------------------------------------------------------------------- // Main //----------------------------------------------------------------------------- void main() { - vec4 alpha = texture2D(alphaMap, alphaLookup); - gl_FragColor = color * texture2D(diffuseMap, outTexCoord); - gl_FragColor.a = gl_FragColor.a * min(alpha, groundAlpha + groundAlphaCoeff.x).x; + vec4 alpha = texture(alphaMap, alphaLookup); + OUT_FragColor0 = color * texture(diffuseMap, outTexCoord); + OUT_FragColor0.a = OUT_FragColor0.a * min(alpha, groundAlpha + groundAlphaCoeff.x).x; } diff --git a/Templates/Empty/game/shaders/common/gl/fxFoliageReplicatorV.glsl b/Templates/Empty/game/shaders/common/gl/fxFoliageReplicatorV.glsl index 94a7af2b0..c8dcf1ddb 100644 --- a/Templates/Empty/game/shaders/common/gl/fxFoliageReplicatorV.glsl +++ b/Templates/Empty/game/shaders/common/gl/fxFoliageReplicatorV.glsl @@ -23,13 +23,20 @@ //----------------------------------------------------------------------------- // Data //----------------------------------------------------------------------------- +in vec4 vPosition; +in vec3 vNormal; +in vec4 vColor; +in vec2 vTexCoord0; +in vec2 vTexCoord1; +in vec2 vTexCoord2; + uniform mat4 projection, world; uniform vec3 CameraPos; uniform float GlobalSwayPhase, SwayMagnitudeSide, SwayMagnitudeFront, GlobalLightPhase, LuminanceMagnitude, LuminanceMidpoint, DistanceRange; -varying vec4 color, groundAlphaCoeff; -varying vec2 outTexCoord, alphaLookup; +out vec4 color, groundAlphaCoeff; +out vec2 outTexCoord, alphaLookup; //----------------------------------------------------------------------------- // Main @@ -42,9 +49,9 @@ void main() trans[1][1] = 1.0; trans[2][2] = 1.0; trans[3][3] = 1.0; - trans[3][0] = gl_Vertex.x; - trans[3][1] = gl_Vertex.y; - trans[3][2] = gl_Vertex.z; + trans[3][0] = vPosition.x; + trans[3][1] = vPosition.y; + trans[3][2] = vPosition.z; // Billboard transform * world matrix mat4 o = world; @@ -64,28 +71,29 @@ void main() // Handle sway. Sway is stored in a texture coord. The x coordinate is the sway phase multiplier, // the y coordinate determines if this vertex actually sways or not. float xSway, ySway; - float wavePhase = GlobalSwayPhase * gl_MultiTexCoord1.x; + float wavePhase = GlobalSwayPhase * vTexCoord1.x; ySway = sin(wavePhase); xSway = cos(wavePhase); - xSway = xSway * gl_MultiTexCoord1.y * SwayMagnitudeSide; - ySway = ySway * gl_MultiTexCoord1.y * SwayMagnitudeFront; + xSway = xSway * vTexCoord1.y * SwayMagnitudeSide; + ySway = ySway * vTexCoord1.y * SwayMagnitudeFront; vec4 p; - p = o * vec4(gl_Normal.x + xSway, ySway, gl_Normal.z, 1.0); + p = o * vec4(vNormal.x + xSway, ySway, vNormal.z, 1.0); // Project the point gl_Position = projection * p; // Lighting - float Luminance = LuminanceMidpoint + LuminanceMagnitude * cos(GlobalLightPhase + gl_Normal.y); + float Luminance = LuminanceMidpoint + LuminanceMagnitude * cos(GlobalLightPhase + vNormal.y); // Alpha - vec3 worldPos = vec3(gl_Vertex.x, gl_Vertex.y, gl_Vertex.z); + vec3 worldPos = vec3(vPosition.x, vPosition.y, vPosition.z); float alpha = abs(distance(worldPos, CameraPos)) / DistanceRange; alpha = clamp(alpha, 0.0, 1.0); //pass it through alphaLookup = vec2(alpha, 0.0); - bool alphaCoeff = bool(gl_Normal.z); + bool alphaCoeff = bool(vNormal.z); groundAlphaCoeff = vec4(float(alphaCoeff)); - outTexCoord = gl_MultiTexCoord0.st; + outTexCoord = vTexCoord0.st; color = vec4(Luminance, Luminance, Luminance, 1.0); + gl_Position.y *= -1; } \ No newline at end of file diff --git a/Templates/Empty/game/shaders/common/gl/guiMaterialV.glsl b/Templates/Empty/game/shaders/common/gl/guiMaterialV.glsl index cd44de2f2..de3845ee7 100644 --- a/Templates/Empty/game/shaders/common/gl/guiMaterialV.glsl +++ b/Templates/Empty/game/shaders/common/gl/guiMaterialV.glsl @@ -20,16 +20,20 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- +in vec4 vPosition; +in vec2 vTexCoord0; + uniform mat4x4 modelview; -varying vec4 hpos; -varying vec2 uv0; +out vec4 hpos; +out vec2 uv0; void main() { - hpos = vec4( modelview * gl_Vertex ); + hpos = vec4( modelview * vPosition ); gl_Position = hpos; - uv0 = gl_MultiTexCoord0.st; + uv0 = vTexCoord0.st; + gl_Position.y *= -1; } diff --git a/Templates/Empty/game/shaders/common/gl/hlslCompat.glsl b/Templates/Empty/game/shaders/common/gl/hlslCompat.glsl index be5c63340..0815df51f 100644 --- a/Templates/Empty/game/shaders/common/gl/hlslCompat.glsl +++ b/Templates/Empty/game/shaders/common/gl/hlslCompat.glsl @@ -27,17 +27,79 @@ #define float3 vec3 #define float2 vec2 -#define texCUBE textureCube -#define tex2D texture2D +#define half float +#define half2 vec2 +#define half3 vec3 +#define half4 vec4 + +#define float4x4 mat4 +#define float3x3 mat3 +#define float2x2 mat2 + +#define texCUBE texture +#define tex2D texture +#define tex1D texture +#define tex2Dproj textureProj +#define tex2Dlod( sampler, texCoord ) textureLod(sampler, texCoord.xy, texCoord.w) + +#define samplerCUBE samplerCube + +#define frac fract #define lerp mix -float saturate( float val ) { return clamp( val, 0.0, 1.0 ); } -vec2 saturate( vec2 val ) { return clamp( val, 0.0, 1.0 ); } -vec3 saturate( vec3 val ) { return clamp( val, 0.0, 1.0 ); } -vec4 saturate( vec4 val ) { return clamp( val, 0.0, 1.0 ); } +void tSetMatrixRow(out float3x3 m, int row, float3 value) +{ + m[0][row] = value.x; + m[1][row] = value.y; + m[2][row] = value.z; +} -float round( float n ) { return sign( n ) * floor( abs( n ) + 0.5 ); } -vec2 round( vec2 n ) { return sign( n ) * floor( abs( n ) + 0.5 ); } -vec3 round( vec3 n ) { return sign( n ) * floor( abs( n ) + 0.5 ); } -vec4 round( vec4 n ) { return sign( n ) * floor( abs( n ) + 0.5 ); } +void tSetMatrixRow(out float4x4 m, int row, float4 value) +{ + m[0][row] = value.x; + m[1][row] = value.y; + m[2][row] = value.z; + m[3][row] = value.w; +} + +#define tGetMatrix3Row(matrix, row) float3(matrix[0][row], matrix[1][row], matrix[2][row]) +#define tGetMatrix4Row(matrix, row) float4(matrix[0][row], matrix[1][row], matrix[2][row], matrix[3][row]) + +float3x3 float4x4to3x3(float4x4 m) +{ + return float3x3( vec3(m[0]).xyz, m[1].xyz, m[2].xyz); +} + +float3x3 float4x4to3x3_(float4x4 m) +{ + return float3x3( vec3(m[0]), m[1].xyz, m[2].xyz); +} + +mat4 mat4FromRow( float r0c0, float r0c1, float r0c2, float r0c3, + float r1c0, float r1c1, float r1c2, float r1c3, + float r2c0, float r2c1, float r2c2, float r2c3, + float r3c0, float r3c1, float r3c2, float r3c3 ) +{ + return mat4( r0c0, r1c0, r2c0, r3c0, + r0c1, r1c1, r2c1, r3c1, + r0c2, r1c2, r2c2, r3c2, + r0c3, r1c3, r2c3, r3c3 ); +} + + +#define saturate( val ) clamp( val, 0.0, 1.0 ) + +#define round( n ) (sign( n ) * floor( abs( n ) + 0.5 )) + +#define tMul(a, b) (a*b) + +#define inversesqrt( n ) inversesqrt( n ) + +#define correctSSP(vec) vec.y *= -1 + +#ifdef TORQUE_PIXEL_SHADER + void clip(float a) { if(a < 0) discard;} + + out vec4 OUT_FragColor0; +#endif diff --git a/Templates/Empty/game/shaders/common/gl/lighting.glsl b/Templates/Empty/game/shaders/common/gl/lighting.glsl index 3f8867d3b..4483c7526 100644 --- a/Templates/Empty/game/shaders/common/gl/lighting.glsl +++ b/Templates/Empty/game/shaders/common/gl/lighting.glsl @@ -20,73 +20,181 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- + +#ifndef TORQUE_SHADERGEN + // These are the uniforms used by most lighting shaders. -uniform vec3 inLightPos[4]; +uniform vec4 inLightPos[3]; uniform vec4 inLightInvRadiusSq; uniform vec4 inLightColor[4]; + +#ifndef TORQUE_BL_NOSPOTLIGHT + uniform vec4 inLightSpotDir[3]; + uniform vec4 inLightSpotAngle; + uniform vec4 inLightSpotFalloff; +#endif + uniform vec4 ambient; uniform float specularPower; uniform vec4 specularColor; - -// This is used to limit the maximum processed -// lights in the compute4Lights down for really -// low end GPUs. -// -// NOTE: If you want to support 10.5.x, this needs to be changed to 2. -#define C4L_MAX_LIGHTS 4 +#endif // !TORQUE_SHADERGEN void compute4Lights( vec3 wsView, vec3 wsPosition, - vec3 wsNormal, + vec3 wsNormal, + vec4 shadowMask, + + #ifdef TORQUE_SHADERGEN + + vec4 inLightPos[3], + vec4 inLightInvRadiusSq, + vec4 inLightColor[4], + vec4 inLightSpotDir[3], + vec4 inLightSpotAngle, + vec4 inLightSpotFalloff, + float specularPower, + vec4 specularColor, + + #endif // TORQUE_SHADERGEN + out vec4 outDiffuse, out vec4 outSpecular ) { - #ifdef PHONG_SPECULAR - // (R.V)^c - float reflected = reflect( wsView, wsNormal ); - #endif - - vec4 nDotL = vec4( 0.0 ); - vec4 rDotL = vec4( 0.0 ); - vec4 sqDists = vec4( 0.0 ); + // NOTE: The light positions and spotlight directions + // are stored in SoA order, so inLightPos[0] is the + // x coord for all 4 lights... inLightPos[1] is y... etc. + // + // This is the key to fully utilizing the vector units and + // saving a huge amount of instructions. + // + // For example this change saved more than 10 instructions + // over a simple for loop for each light. + int i; - for ( i = 0; i < C4L_MAX_LIGHTS; ++i ) - { - vec3 lightVector = inLightPos[i] - wsPosition; - vec3 lightDirection = normalize( lightVector ); + vec4 lightVectors[3]; + for ( i = 0; i < 3; i++ ) + lightVectors[i] = wsPosition[i] - inLightPos[i]; - nDotL[i] = max( dot( lightDirection, wsNormal ), 0.0 ); + vec4 squareDists = vec4(0); + for ( i = 0; i < 3; i++ ) + squareDists += lightVectors[i] * lightVectors[i]; - #ifdef PHONG_SPECULAR - rDotL[i] = saturate( dot( lightDirection, reflected ) ); - #else - // (N.H)^c [Blinn-Phong, TGEA style, default] - rDotL[i] = dot( wsNormal, normalize( lightDirection + wsView ) ); - #endif + // Accumulate the dot product between the light + // vector and the normal. + // + // The normal is negated because it faces away from + // the surface and the light faces towards the + // surface... this keeps us from needing to flip + // the light vector direction which complicates + // the spot light calculations. + // + // We normalize the result a little later. + // + vec4 nDotL = vec4(0); + for ( i = 0; i < 3; i++ ) + nDotL += lightVectors[i] * -wsNormal[i]; - sqDists[i] = dot( lightVector, lightVector ); - } + vec4 rDotL = vec4(0); + #ifndef TORQUE_BL_NOSPECULAR - // Attenuation - vec4 atten = vec4( 1.0 ) - ( sqDists * inLightInvRadiusSq ); + // We're using the Phong specular reflection model + // here where traditionally Torque has used Blinn-Phong + // which has proven to be more accurate to real materials. + // + // We do so because its cheaper as do not need to + // calculate the half angle for all 4 lights. + // + // Advanced Lighting still uses Blinn-Phong, but the + // specular reconstruction it does looks fairly similar + // to this. + // + vec3 R = reflect( wsView, -wsNormal ); + + for ( i = 0; i < 3; i++ ) + rDotL += lightVectors[i] * R[i]; + + #endif + + // Normalize the dots. + // + // Notice we're using the half type here to get a + // much faster sqrt via the rsq_pp instruction at + // the loss of some precision. + // + // Unless we have some extremely large point lights + // i don't believe the precision loss will matter. + // + half4 correction = half4(inversesqrt( squareDists )); + nDotL = saturate( nDotL * correction ); + rDotL = clamp( rDotL * correction, 0.00001, 1.0 ); + + // First calculate a simple point light linear + // attenuation factor. + // + // If this is a directional light the inverse + // radius should be greater than the distance + // causing the attenuation to have no affect. + // + vec4 atten = saturate( 1.0 - ( squareDists * inLightInvRadiusSq ) ); + + #ifndef TORQUE_BL_NOSPOTLIGHT + + // The spotlight attenuation factor. This is really + // fast for what it does... 6 instructions for 4 spots. + + vec4 spotAtten = vec4(0); + for ( i = 0; i < 3; i++ ) + spotAtten += lightVectors[i] * inLightSpotDir[i]; + + vec4 cosAngle = ( spotAtten * correction ) - inLightSpotAngle; + atten *= saturate( cosAngle * inLightSpotFalloff ); + + #endif + + // Finally apply the shadow masking on the attenuation. + atten *= shadowMask; + + // Get the final light intensity. + vec4 intensity = nDotL * atten; // Combine the light colors for output. - vec4 diffuse = clamp( nDotL * atten, vec4( 0.0 ), vec4( 1.0 ) ); - outDiffuse = vec4( 0.0 ); - for ( i = 0; i < C4L_MAX_LIGHTS; ++i ) - outDiffuse += vec4( diffuse[i] ) * inLightColor[i]; + outDiffuse = vec4(0); + for ( i = 0; i < 4; i++ ) + outDiffuse += intensity[i] * inLightColor[i]; // Output the specular power. - rDotL = max( rDotL, vec4( 0.00001 ) ); - outSpecular = pow( rDotL, vec4( specularPower ) ); + vec4 specularIntensity = pow( rDotL, vec4(specularPower) ) * atten; + + // Apply the per-light specular attenuation. + vec4 specular = vec4(0,0,0,1); + for ( i = 0; i < 4; i++ ) + specular += vec4( inLightColor[i].rgb * inLightColor[i].a * specularIntensity[i], 1 ); + + // Add the final specular intensity values together + // using a single dot product operation then get the + // final specular lighting color. + outSpecular = specularColor * specular; } -/// The standard specular calculation. +// This value is used in AL as a constant power to raise specular values +// to, before storing them into the light info buffer. The per-material +// specular value is then computer by using the integer identity of +// exponentiation: +// +// (a^m)^n = a^(m*n) +// +// or +// +// (specular^constSpecular)^(matSpecular/constSpecular) = specular^(matSpecular*constSpecular) +// +#define AL_ConstantSpecularPower 12.0f + +/// The specular calculation used in Advanced Lighting. /// /// @param toLight Normalized vector representing direction from the pixel /// being lit, to the light source, in world space. @@ -96,11 +204,7 @@ void compute4Lights( vec3 wsView, /// @param toEye The normalized vector representing direction from the pixel /// being lit to the camera. /// -/// @param specPwr The specular exponent. -/// -/// @param specScale A scalar on the specular output used in RGB accumulation. -/// -float calcSpecular( vec3 toLight, vec3 normal, vec3 toEye, float specPwr ) +float AL_CalcSpecular( vec3 toLight, vec3 normal, vec3 toEye ) { #ifdef PHONG_SPECULAR // (R.V)^c @@ -111,5 +215,5 @@ float calcSpecular( vec3 toLight, vec3 normal, vec3 toEye, float specPwr ) #endif // Return the specular factor. - return pow( max( specVal, 0.00001f ), specPwr ); + return pow( max( specVal, 0.00001f ), AL_ConstantSpecularPower ); } diff --git a/Templates/Empty/game/shaders/common/gl/particleCompositeP.glsl b/Templates/Empty/game/shaders/common/gl/particleCompositeP.glsl index 4f2d9b359..6971e1013 100644 --- a/Templates/Empty/game/shaders/common/gl/particleCompositeP.glsl +++ b/Templates/Empty/game/shaders/common/gl/particleCompositeP.glsl @@ -21,6 +21,13 @@ //----------------------------------------------------------------------------- #include "torque.glsl" +#include "hlslCompat.glsl" + +in vec4 offscreenPos; +in vec4 backbufferPos; + +#define IN_offscreenPos offscreenPos +#define IN_backbufferPos backbufferPos uniform sampler2D colorSource; uniform vec4 offscreenTargetParams; @@ -31,8 +38,6 @@ uniform sampler2D edgeSource; uniform vec4 edgeTargetParams; #endif -varying vec4 backbufferPos; -varying vec4 offscreenPos; void main() { @@ -47,11 +52,10 @@ void main() #ifdef REJECT_EDGES // Cut out particles along the edges, this will create the stencil mask uvScene.zw = viewportCoordToRenderTarget(uvScene.zw, edgeTargetParams); - float edge = texture2D( edgeSource, uvScene.zw ).r; - if (-edge < 0.0) - discard; + float edge = texture( edgeSource, uvScene.zw ).r; + clip( -edge ); #endif // Sample offscreen target and return - gl_FragColor = texture2D( colorSource, uvScene.xy ); -} + OUT_FragColor0 = texture( colorSource, uvScene.xy ); +} \ No newline at end of file diff --git a/Templates/Empty/game/shaders/common/gl/particleCompositeV.glsl b/Templates/Empty/game/shaders/common/gl/particleCompositeV.glsl index 88a9431d1..8c8f840d1 100644 --- a/Templates/Empty/game/shaders/common/gl/particleCompositeV.glsl +++ b/Templates/Empty/game/shaders/common/gl/particleCompositeV.glsl @@ -20,16 +20,29 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- -uniform mat4 modelViewProj; -uniform mat4 targetModelViewProj; +#include "hlslCompat.glsl" -varying vec4 offscreenPos; -varying vec4 backbufferPos; +in vec2 vTexCoord0; +#define uvCoord vTexCoord0 + +out vec4 offscreenPos; +out vec4 backbufferPos; + +#define OUT_hpos gl_Position +#define OUT_offscreenPos offscreenPos +#define OUT_backbufferPos backbufferPos + +uniform vec4 screenRect; // point, extent void main() { - gl_Position = modelViewProj * gl_Vertex; - backbufferPos = gl_Position; - offscreenPos = targetModelViewProj * gl_Vertex; + OUT_hpos = vec4(uvCoord.xy, 1.0, 1.0); + OUT_hpos.xy *= screenRect.zw; + OUT_hpos.xy += screenRect.xy; + + OUT_backbufferPos = OUT_hpos; + OUT_offscreenPos = OUT_hpos; + + correctSSP(gl_Position); } diff --git a/Templates/Empty/game/shaders/common/gl/particlesP.glsl b/Templates/Empty/game/shaders/common/gl/particlesP.glsl index 66a3fee28..efd930302 100644 --- a/Templates/Empty/game/shaders/common/gl/particlesP.glsl +++ b/Templates/Empty/game/shaders/common/gl/particlesP.glsl @@ -20,63 +20,92 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- -#include "hlslCompat.glsl" #include "torque.glsl" - +#include "hlslCompat.glsl" + // With advanced lighting we get soft particles. #ifdef TORQUE_LINEAR_DEPTH #define SOFTPARTICLES #endif -#define CLIP_Z // TODO: Make this a proper macro - -uniform sampler2D diffuseMap; - #ifdef SOFTPARTICLES #include "shadergen:/autogenConditioners.h" uniform float oneOverSoftness; uniform float oneOverFar; - uniform sampler2D prepassTex; + uniform sampler2D prepassTex; //uniform vec3 vEye; uniform vec4 prePassTargetParams; #endif +#define CLIP_Z // TODO: Make this a proper macro + +in vec4 color; +in vec2 uv0; +in vec4 pos; + +#define IN_color color +#define IN_uv0 uv0 +#define IN_pos pos + +uniform sampler2D diffuseMap; + +uniform sampler2D paraboloidLightMap; + +vec4 lmSample( vec3 nrm ) +{ + bool calcBack = (nrm.z < 0.0); + if ( calcBack ) + nrm.z = nrm.z * -1.0; + + vec2 lmCoord; + lmCoord.x = (nrm.x / (2*(1 + nrm.z))) + 0.5; + lmCoord.y = 1-((nrm.y / (2*(1 + nrm.z))) + 0.5); + + + // If this is the back, offset in the atlas + if ( calcBack ) + lmCoord.x += 1.0; + + // Atlasing front and back maps, so scale + lmCoord.x *= 0.5; + + return texture(paraboloidLightMap, lmCoord); +} + + uniform float alphaFactor; uniform float alphaScale; -varying vec4 color; -varying vec2 uv0; -varying vec4 pos; - - void main() { - float softBlend = 1.0; + float softBlend = 1; #ifdef SOFTPARTICLES - float2 tc = pos.xy * vec2(1.0, -1.0 ) / pos.w; + vec2 tc = IN_pos.xy * vec2(1.0, -1.0) / IN_pos.w; tc = viewportCoordToRenderTarget(saturate( ( tc + 1.0 ) * 0.5 ), prePassTargetParams); float sceneDepth = prepassUncondition( prepassTex, tc ).w; - float depth = pos.w * oneOverFar; - float diff = sceneDepth - depth; + float depth = IN_pos.w * oneOverFar; + float diff = sceneDepth - depth; #ifdef CLIP_Z // If drawing offscreen, this acts as the depth test, since we don't line up with the z-buffer // When drawing high-res, though, we want to be able to take advantage of hi-z // so this is #ifdef'd out - if (diff < 0.0) - discard; + //clip(diff); #endif softBlend = saturate( diff * oneOverSoftness ); #endif - - vec4 diffuse = texture2D( diffuseMap, uv0 ); + + vec4 diffuse = texture( diffuseMap, IN_uv0 ); + + //OUT_FragColor0 = vec4( lmSample(vec3(0, 0, -1)).rgb, IN_color.a * diffuse.a * softBlend * alphaScale); // Scale output color by the alpha factor (turn LerpAlpha into pre-multiplied alpha) - vec3 colorScale = ( alphaFactor < 0.0 ? color.rgb * diffuse.rgb : ( alphaFactor > 0.0 ? vec3(color.a * alphaFactor * diffuse.a * softBlend) : vec3(softBlend) ) ); + vec3 colorScale = ( alphaFactor < 0.0 ? IN_color.rgb * diffuse.rgb : vec3( alphaFactor > 0.0 ? IN_color.a * diffuse.a * alphaFactor * softBlend : softBlend ) ); - gl_FragColor = hdrEncode( vec4(color.rgb * diffuse.rgb * colorScale, softBlend * color.a * diffuse.a * alphaScale) ); + OUT_FragColor0 = hdrEncode( vec4( IN_color.rgb * diffuse.rgb * colorScale, + IN_color.a * diffuse.a * softBlend * alphaScale ) ); } diff --git a/Templates/Empty/game/shaders/common/gl/particlesV.glsl b/Templates/Empty/game/shaders/common/gl/particlesV.glsl index da896431f..3d75a6fb6 100644 --- a/Templates/Empty/game/shaders/common/gl/particlesV.glsl +++ b/Templates/Empty/game/shaders/common/gl/particlesV.glsl @@ -20,18 +20,35 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- -varying vec4 color; -varying vec2 uv0; -varying vec4 pos; +#include "hlslCompat.glsl" + +in vec4 vPosition; +in vec4 vColor; +in vec2 vTexCoord0; + +#define In_pos vPosition +#define In_color vColor +#define In_uv0 vTexCoord0 + +out vec4 color; +out vec2 uv0; +out vec4 pos; + +#define OUT_hpos gl_Position +#define OUT_color color +#define OUT_uv0 uv0 +#define OUT_pos pos uniform mat4 modelViewProj; uniform mat4 fsModelViewProj; void main() { - gl_Position = modelViewProj * gl_Vertex; - pos = fsModelViewProj * gl_Vertex; - color = gl_Color; - uv0 = gl_MultiTexCoord0.st; + OUT_hpos = tMul( modelViewProj, In_pos ); + OUT_pos = tMul( fsModelViewProj, In_pos ); + OUT_color = In_color; + OUT_uv0 = In_uv0; + + correctSSP(gl_Position); } diff --git a/Templates/Empty/game/shaders/common/gl/planarReflectBumpP.glsl b/Templates/Empty/game/shaders/common/gl/planarReflectBumpP.glsl index 00413aa3b..334c70a70 100644 --- a/Templates/Empty/game/shaders/common/gl/planarReflectBumpP.glsl +++ b/Templates/Empty/game/shaders/common/gl/planarReflectBumpP.glsl @@ -26,8 +26,8 @@ uniform sampler2D diffuseMap, refractMap, bumpMap; uniform vec4 shadeColor; -varying vec2 TEX0; -varying vec4 TEX1; +in vec2 TEX0; +in vec4 TEX1; //----------------------------------------------------------------------------- // Fade edges of axis for texcoord passed in @@ -49,7 +49,7 @@ float fadeAxis( float val ) //----------------------------------------------------------------------------- void main() { - vec3 bumpNorm = texture2D( bumpMap, TEX0 ).rgb * 2.0 - 1.0; + vec3 bumpNorm = texture( bumpMap, TEX0 ).rgb * 2.0 - 1.0; vec2 offset = vec2( bumpNorm.x, bumpNorm.y ); vec4 texIndex = TEX1; @@ -61,8 +61,8 @@ void main() const float distortion = 0.2; texIndex.xy += offset * distortion * fadeVal; - vec4 diffuseColor = texture2D( diffuseMap, TEX0 ); - vec4 reflectColor = texture2DProj( refractMap, texIndex ); + vec4 diffuseColor = texture( diffuseMap, TEX0 ); + vec4 reflectColor = textureProj( refractMap, texIndex ); - gl_FragColor = diffuseColor + reflectColor * diffuseColor.a; + OUT_FragColor0 = diffuseColor + reflectColor * diffuseColor.a; } diff --git a/Templates/Empty/game/shaders/common/gl/planarReflectBumpV.glsl b/Templates/Empty/game/shaders/common/gl/planarReflectBumpV.glsl index 820bdf698..90bcd27d8 100644 --- a/Templates/Empty/game/shaders/common/gl/planarReflectBumpV.glsl +++ b/Templates/Empty/game/shaders/common/gl/planarReflectBumpV.glsl @@ -23,10 +23,13 @@ //----------------------------------------------------------------------------- // Data //----------------------------------------------------------------------------- +in vec4 vPosition; +in vec2 vTexCoord0; + uniform mat4 modelview; -varying vec2 TEX0; -varying vec4 TEX1; +out vec2 TEX0; +out vec4 TEX1; //----------------------------------------------------------------------------- // Main @@ -38,11 +41,11 @@ void main() 0.0, 0.0, 1.0, 0.0, 0.5, 0.5, 0.0, 1.0); - gl_Position = modelview * gl_Vertex; + gl_Position = modelview * vPosition; - TEX0 = gl_MultiTexCoord0.st; + TEX0 = vTexCoord0.st; TEX1 = texGenTest * gl_Position; TEX1.y = -TEX1.y; - + gl_Position.y *= -1; } diff --git a/Templates/Empty/game/shaders/common/gl/planarReflectP.glsl b/Templates/Empty/game/shaders/common/gl/planarReflectP.glsl index b4f4fab39..77914b80e 100644 --- a/Templates/Empty/game/shaders/common/gl/planarReflectP.glsl +++ b/Templates/Empty/game/shaders/common/gl/planarReflectP.glsl @@ -26,16 +26,16 @@ uniform sampler2D diffuseMap, refractMap; uniform vec4 shadeColor; -varying vec2 TEX0; -varying vec4 TEX1; +in vec2 TEX0; +in vec4 TEX1; //----------------------------------------------------------------------------- // Main //----------------------------------------------------------------------------- void main() { - vec4 diffuseColor = texture2D( diffuseMap, TEX0 ); - vec4 reflectColor = texture2DProj( refractMap, TEX1 ); + vec4 diffuseColor = texture( diffuseMap, TEX0 ); + vec4 reflectColor = textureProj( refractMap, TEX1 ); - gl_FragColor = diffuseColor + reflectColor * diffuseColor.a; + OUT_FragColor0 = diffuseColor + reflectColor * diffuseColor.a; } diff --git a/Templates/Empty/game/shaders/common/gl/planarReflectV.glsl b/Templates/Empty/game/shaders/common/gl/planarReflectV.glsl index 820bdf698..ba2484f66 100644 --- a/Templates/Empty/game/shaders/common/gl/planarReflectV.glsl +++ b/Templates/Empty/game/shaders/common/gl/planarReflectV.glsl @@ -23,10 +23,13 @@ //----------------------------------------------------------------------------- // Data //----------------------------------------------------------------------------- +in vec4 vPosition; +in vec2 vTexCoord0; + uniform mat4 modelview; -varying vec2 TEX0; -varying vec4 TEX1; +out vec2 TEX0; +out vec4 TEX1; //----------------------------------------------------------------------------- // Main @@ -38,9 +41,9 @@ void main() 0.0, 0.0, 1.0, 0.0, 0.5, 0.5, 0.0, 1.0); - gl_Position = modelview * gl_Vertex; + gl_Position = modelview * vPosition; - TEX0 = gl_MultiTexCoord0.st; + TEX0 = vTexCoord0; TEX1 = texGenTest * gl_Position; TEX1.y = -TEX1.y; diff --git a/Templates/Empty/game/shaders/common/gl/precipP.glsl b/Templates/Empty/game/shaders/common/gl/precipP.glsl index a04f16e4b..3c669517d 100644 --- a/Templates/Empty/game/shaders/common/gl/precipP.glsl +++ b/Templates/Empty/game/shaders/common/gl/precipP.glsl @@ -25,13 +25,13 @@ //----------------------------------------------------------------------------- uniform sampler2D diffuseMap; -varying vec4 color; -varying vec2 texCoord; +in vec4 color; +in vec2 texCoord; //----------------------------------------------------------------------------- // Main //----------------------------------------------------------------------------- void main() { - gl_FragColor = texture2D(diffuseMap, texCoord) * color; + OUT_FragColor0 = texture(diffuseMap, texCoord) * color; } diff --git a/Templates/Empty/game/shaders/common/gl/precipV.glsl b/Templates/Empty/game/shaders/common/gl/precipV.glsl index 3535f2f38..29f921630 100644 --- a/Templates/Empty/game/shaders/common/gl/precipV.glsl +++ b/Templates/Empty/game/shaders/common/gl/precipV.glsl @@ -23,28 +23,32 @@ //----------------------------------------------------------------------------- // Data //----------------------------------------------------------------------------- +in vec4 vPosition; +in vec2 vTexCoord0; + uniform mat4 modelview; uniform vec3 cameraPos, ambient; uniform vec2 fadeStartEnd; -varying vec4 color; -varying vec2 texCoord; +out vec4 color; +out vec2 texCoord; //----------------------------------------------------------------------------- // Main //----------------------------------------------------------------------------- void main() { - gl_Position = modelview * gl_Vertex; - texCoord = gl_MultiTexCoord0.st; + gl_Position = modelview * vPosition; + texCoord = vTexCoord0.st; color = vec4( ambient.r, ambient.g, ambient.b, 1.0 ); // Do we need to do a distance fade? if ( fadeStartEnd.x < fadeStartEnd.y ) { - float distance = length( cameraPos - gl_Vertex.xyz ); + float distance = length( cameraPos - vPosition.xyz ); color.a = abs( clamp( ( distance - fadeStartEnd.x ) / ( fadeStartEnd.y - fadeStartEnd.x ), 0.0, 1.0 ) - 1.0 ); } + gl_Position.y *= -1; } diff --git a/Templates/Empty/game/shaders/common/gl/projectedShadowP.glsl b/Templates/Empty/game/shaders/common/gl/projectedShadowP.glsl index 1dc963a4f..8ce0fba13 100644 --- a/Templates/Empty/game/shaders/common/gl/projectedShadowP.glsl +++ b/Templates/Empty/game/shaders/common/gl/projectedShadowP.glsl @@ -20,9 +20,11 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- -varying vec2 texCoord; -varying vec4 color; -varying float fade; +in vec2 texCoord; +in vec4 color; +in float fade; + +out vec4 OUT_FragColor0; uniform sampler2D inputTex; uniform vec4 ambient; @@ -30,17 +32,6 @@ uniform vec4 ambient; void main() { - vec3 LUMINANCE_VECTOR = vec3(0.2125f, 0.4154f, 0.1721f); - float esmFactor = 200.0; - - float lum = dot( ambient.rgb, LUMINANCE_VECTOR ); - - gl_FragColor.rgb = ambient.rgb * lum; - gl_FragColor.a = 0.0; - float depth = texture2D(inputTex, texCoord).a; - - depth = depth * exp(depth - 10.0); - depth = exp(esmFactor * depth) - 1.0; - - gl_FragColor.a = clamp(depth * 300.0, 0.0, 1.0) * (1.0 - lum) * fade * color.a; + float shadow = texture( inputTex, texCoord ).a * color.a; + OUT_FragColor0 = ( ambient * shadow ) + ( 1 - shadow ); } diff --git a/Templates/Empty/game/shaders/common/gl/projectedShadowV.glsl b/Templates/Empty/game/shaders/common/gl/projectedShadowV.glsl index c8abde742..b5de84181 100644 --- a/Templates/Empty/game/shaders/common/gl/projectedShadowV.glsl +++ b/Templates/Empty/game/shaders/common/gl/projectedShadowV.glsl @@ -20,13 +20,16 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- -//***************************************************************************** -// Precipitation vertex shader -//***************************************************************************** +#include "hlslCompat.glsl" -varying vec2 texCoord; -varying vec4 color; -varying float fade; +in vec4 vPosition; +in vec4 vColor; +in vec2 vTexCoord0; +in vec2 vTexCoord1; + +out vec2 texCoord; +out vec4 color; +out float fade; uniform mat4 modelview; uniform float shadowLength; @@ -34,11 +37,13 @@ uniform vec3 shadowCasterPosition; void main() { - gl_Position = modelview * vec4(gl_Vertex.xyz, 1.0); + gl_Position = modelview * vec4(vPosition.xyz, 1.0); - color = gl_Color; - texCoord = gl_MultiTexCoord1.st; + color = vColor; + texCoord = vTexCoord1.st; - float fromCasterDist = length(gl_Vertex.xyz - shadowCasterPosition) - shadowLength; - fade = 1.0 - clamp(fromCasterDist/shadowLength, 0.0, 1.0); + float fromCasterDist = length(vPosition.xyz - shadowCasterPosition) - shadowLength; + fade = 1.0 - clamp( fromCasterDist / shadowLength , 0.0, 1.0 ); + + correctSSP(gl_Position); } diff --git a/Templates/Empty/game/shaders/common/gl/scatterSkyP.glsl b/Templates/Empty/game/shaders/common/gl/scatterSkyP.glsl index 6a6b9b97c..691567a37 100644 --- a/Templates/Empty/game/shaders/common/gl/scatterSkyP.glsl +++ b/Templates/Empty/game/shaders/common/gl/scatterSkyP.glsl @@ -21,36 +21,32 @@ //----------------------------------------------------------------------------- #include "torque.glsl" +#include "hlslCompat.glsl" -// Calculates the Mie phase function -float getMiePhase(float fCos, float fCos2, float g, float g2) -{ - return 1.5 * ((1.0 - g2) / (2.0 + g2)) * (1.0 + fCos2) / pow(abs(1.0 + g2 - 2.0*g*fCos), 1.5); -} -// Calculates the Rayleigh phase function -float getRayleighPhase(float fCos2) -{ - //return 1.0; - return 0.75 + 0.75*fCos2; -} +// Conn +in vec4 rayleighColor; +#define IN_rayleighColor rayleighColor +in vec4 mieColor; +#define IN_mieColor mieColor +in vec3 v3Direction; +#define IN_v3Direction v3Direction +in float zPosition; +#define IN_zPosition zPosition +in vec3 pos; +#define IN_pos pos -varying vec4 rayleighColor; -varying vec4 mieColor; -varying vec3 v3Direction; -varying float zPosition; -varying vec3 pos; - -uniform samplerCube nightSky; +uniform samplerCube nightSky ; uniform vec4 nightColor; uniform vec2 nightInterpAndExposure; uniform float useCubemap; uniform vec3 lightDir; uniform vec3 sunDir; -void main() +void main() { - float fCos = dot( lightDir, v3Direction ) / length(v3Direction); + + float fCos = dot( lightDir, IN_v3Direction ) / length(IN_v3Direction); float fCos2 = fCos*fCos; float g = -0.991; @@ -58,15 +54,15 @@ void main() float fMiePhase = 1.5 * ((1.0 - g2) / (2.0 + g2)) * (1.0 + fCos2) / pow(abs(1.0 + g2 - 2.0*g*fCos), 1.5); - vec4 color = rayleighColor + fMiePhase * mieColor; + vec4 color = IN_rayleighColor + fMiePhase * IN_mieColor; color.a = color.b; - vec4 nightSkyColor = textureCube(nightSky, -v3Direction); + vec4 nightSkyColor = texture(nightSky, -v3Direction); nightSkyColor = mix(nightColor, nightSkyColor, useCubemap); float fac = dot( normalize( pos ), sunDir ); fac = max( nightInterpAndExposure.y, pow( clamp( fac, 0.0, 1.0 ), 2 ) ); - gl_FragColor = mix( color, nightSkyColor, nightInterpAndExposure.y ); + OUT_FragColor0 = mix( color, nightSkyColor, nightInterpAndExposure.y ); // Clip based on the camera-relative // z position of the vertex, passed through @@ -74,6 +70,6 @@ void main() if(zPosition < 0.0) discard; - gl_FragColor.a = 1; - gl_FragColor = hdrEncode( gl_FragColor ); + OUT_FragColor0.a = 1; + OUT_FragColor0 = hdrEncode( OUT_FragColor0 ); } diff --git a/Templates/Empty/game/shaders/common/gl/scatterSkyV.glsl b/Templates/Empty/game/shaders/common/gl/scatterSkyV.glsl index 53abd5a6b..61580d785 100644 --- a/Templates/Empty/game/shaders/common/gl/scatterSkyV.glsl +++ b/Templates/Empty/game/shaders/common/gl/scatterSkyV.glsl @@ -20,12 +20,7 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- -const int nSamples = 4; -const float fSamples = 4.0; - -// The scale depth (the altitude at which the average atmospheric density is found) -const float fScaleDepth = 0.25; -const float fInvScaleDepth = 1.0 / 0.25; +#include "hlslCompat.glsl" // The scale equation calculated by Vernier's Graphical Analysis float vernierScale(float fCos) @@ -40,12 +35,27 @@ float vernierScale(float fCos) return 0.25 * outx; } +in vec4 vPosition; +in vec3 vNormal; +in vec4 vColor; +in vec2 vTexCoord0; + +// This is the shader input vertex structure. +#define IN_position vPosition +#define IN_normal vNormal +#define IN_color vColor + // This is the shader output data. -varying vec4 rayleighColor; -varying vec4 mieColor; -varying vec3 v3Direction; -varying float zPosition; -varying vec3 pos; +out vec4 rayleighColor; +#define OUT_rayleighColor rayleighColor +out vec4 mieColor; +#define OUT_mieColor mieColor +out vec3 v3Direction; +#define OUT_v3Direction v3Direction +out float zPosition; +#define OUT_zPosition zPosition +out vec3 pos; +#define OUT_pos pos uniform mat4 modelView; uniform vec4 misc; @@ -54,13 +64,16 @@ uniform vec4 scatteringCoeffs; uniform vec3 camPos; uniform vec3 lightDir; uniform vec4 invWaveLength; - -void main() -{ - vec4 position = gl_Vertex.xyzw; - vec3 normal = gl_Normal.xyz; - vec4 color = gl_MultiTexCoord0.xyzw; +uniform vec4 colorize; +vec3 desaturate(const vec3 color, const float desaturation) +{ + const vec3 gray_conv = vec3 (0.30, 0.59, 0.11); + return mix(color, vec3(dot(gray_conv , color)), desaturation); +} + +void main() +{ // Pull some variables out: float camHeight = misc.x; float camHeightSqr = misc.y; @@ -83,7 +96,7 @@ void main() // Get the ray from the camera to the vertex, // and its length (which is the far point of the ray // passing through the atmosphere). - vec3 v3Pos = position.xyz / 6378000.0;// / outerRadius; + vec3 v3Pos = vec3(IN_position / 6378000.0);// / outerRadius; vec3 newCamPos = vec3( 0, 0, camHeight ); v3Pos.z += innerRadius; vec3 v3Ray = v3Pos.xyz - newCamPos; @@ -97,16 +110,7 @@ void main() float fDepth = exp(scaleOverScaleDepth * (innerRadius - camHeight)); float fStartAngle = dot(v3Ray, v3Start) / fHeight; - float x = 1.0 - fStartAngle; - float x5 = x * 5.25; - float x5p6 = (-6.80 + x5); - float xnew = (3.83 + x * x5p6); - float xfinal = (0.459 + x * xnew); - float xfinal2 = -0.00287 + x * xfinal; - float othx = exp( xfinal2 ); - float vscale1 = 0.25 * othx; - - float fStartOffset = fDepth * vscale1;//vernierScale(fStartAngle); + float fStartOffset = fDepth * vernierScale( fStartAngle ); // Initialize the scattering loop variables. float fSampleLength = fFar / 2.0; @@ -123,24 +127,8 @@ void main() float fLightAngle = dot(lightDir, v3SamplePoint) / fHeight; float fCameraAngle = dot(v3Ray, v3SamplePoint) / fHeight; - x = 1.0 - fCameraAngle; - x5 = x * 5.25; - x5p6 = (-6.80 + x5); - xnew = (3.83 + x * x5p6); - xfinal = (0.459 + x * xnew); - xfinal2 = -0.00287 + x * xfinal; - othx = exp( xfinal2 ); - float vscale3 = 0.25 * othx; - - - x = 1.0 - fLightAngle; - x5 = x * 5.25; - x5p6 = (-6.80 + x5); - xnew = (3.83 + x * x5p6); - xfinal = (0.459 + x * xnew); - xfinal2 = -0.00287 + x * xfinal; - othx = exp( xfinal2 ); - float vscale2 = 0.25 * othx; + float vscale3 = vernierScale( fCameraAngle ); + float vscale2 = vernierScale( fLightAngle ); float fScatter = (fStartOffset + fDepth*(vscale2 - vscale3)); vec3 v3Attenuate = exp(-fScatter * (invWaveLength.xyz * rayleigh4PI + mie4PI)); @@ -150,16 +138,24 @@ void main() // Finally, scale the Mie and Rayleigh colors // and set up the varying variables for the pixel shader. - gl_Position = modelView * position; - mieColor.rgb = v3FrontColor * mieBrightness; - mieColor.a = 1.0; - rayleighColor.rgb = v3FrontColor * (invWaveLength.xyz * rayleighBrightness); - rayleighColor.a = 1.0; - v3Direction = newCamPos - v3Pos.xyz; + gl_Position = modelView * IN_position; + OUT_mieColor.rgb = v3FrontColor * mieBrightness; + OUT_mieColor.a = 1.0; + OUT_rayleighColor.rgb = v3FrontColor * (invWaveLength.xyz * rayleighBrightness); + OUT_rayleighColor.a = 1.0; + OUT_v3Direction = newCamPos - v3Pos.xyz; + OUT_pos = IN_position.xyz; - // This offset is to get rid of the black line between the atmosky and the waterPlane - // along the horizon. - zPosition = position.z + 4000.0; - pos = position.xyz; +#ifdef USE_COLORIZE + + OUT_rayleighColor.rgb = desaturate(OUT_rayleighColor.rgb, 1) * colorize.a; + + OUT_rayleighColor.r *= colorize.r; + OUT_rayleighColor.g *= colorize.g; + OUT_rayleighColor.b *= colorize.b; + +#endif + + correctSSP(gl_Position); } diff --git a/Templates/Empty/game/shaders/common/gl/torque.glsl b/Templates/Empty/game/shaders/common/gl/torque.glsl index dc73a706f..a98ef859f 100644 --- a/Templates/Empty/game/shaders/common/gl/torque.glsl +++ b/Templates/Empty/game/shaders/common/gl/torque.glsl @@ -117,6 +117,7 @@ mat3x3 quatToMat( vec4 quat ) return mat; } + /// The number of additional substeps we take when refining /// the results of the offset parallax mapping function below. /// @@ -129,19 +130,20 @@ mat3x3 quatToMat( vec4 quat ) /// Performs fast parallax offset mapping using /// multiple refinement steps. -////// @param texMap The texture map whos alpha channel we sample the parallax depth. +/// +/// @param texMap The texture map whos alpha channel we sample the parallax depth. /// @param texCoord The incoming texture coordinate for sampling the parallax depth. /// @param negViewTS The negative view vector in tangent space. /// @param depthScale The parallax factor used to scale the depth result. /// vec2 parallaxOffset( sampler2D texMap, vec2 texCoord, vec3 negViewTS, float depthScale ) { - float depth = texture2D( texMap, texCoord ).a; + float depth = texture( texMap, texCoord ).a; vec2 offset = negViewTS.xy * ( depth * depthScale ); for ( int i=0; i < PARALLAX_REFINE_STEPS; i++ ) { - depth = ( depth + texture2D( texMap, texCoord + offset ).a ) * 0.5; + depth = ( depth + texture( texMap, texCoord + offset ).a ) * 0.5; offset = negViewTS.xy * ( depth * depthScale ); } @@ -151,59 +153,61 @@ vec2 parallaxOffset( sampler2D texMap, vec2 texCoord, vec3 negViewTS, float dept /// The maximum value for 16bit per component integer HDR encoding. const float HDR_RGB16_MAX = 100.0; -/// The maximum value for 10bit per component integer HDR encoding.const float HDR_RGB10_MAX = 4.0; +/// The maximum value for 10bit per component integer HDR encoding. +const float HDR_RGB10_MAX = 4.0; /// Encodes an HDR color for storage into a target. -vec3 hdrEncode( vec3 sample ){ +vec3 hdrEncode( vec3 _sample ) +{ #if defined( TORQUE_HDR_RGB16 ) - return sample / HDR_RGB16_MAX; + return _sample / HDR_RGB16_MAX; #elif defined( TORQUE_HDR_RGB10 ) - return sample / HDR_RGB10_MAX; + return _sample / HDR_RGB10_MAX; #else // No encoding. - return sample; + return _sample; #endif } /// Encodes an HDR color for storage into a target. -vec4 hdrEncode( vec4 sample ) +vec4 hdrEncode( vec4 _sample ) { - return vec4( hdrEncode( sample.rgb ), sample.a ); + return vec4( hdrEncode( _sample.rgb ), _sample.a ); } /// Decodes an HDR color from a target. -vec3 hdrDecode( vec3 sample ) +vec3 hdrDecode( vec3 _sample ) { #if defined( TORQUE_HDR_RGB16 ) - return sample * HDR_RGB16_MAX; + return _sample * HDR_RGB16_MAX; #elif defined( TORQUE_HDR_RGB10 ) - return sample * HDR_RGB10_MAX; + return _sample * HDR_RGB10_MAX; #else // No encoding. - return sample; + return _sample; #endif } /// Decodes an HDR color from a target. -vec4 hdrDecode( vec4 sample ) +vec4 hdrDecode( vec4 _sample ) { - return vec4( hdrDecode( sample.rgb ), sample.a ); + return vec4( hdrDecode( _sample.rgb ), _sample.a ); } /// Returns the luminance for an HDR pixel. -float hdrLuminance( vec3 sample ) +float hdrLuminance( vec3 _sample ) { // There are quite a few different ways to // calculate luminance from an rgb value. @@ -216,7 +220,7 @@ float hdrLuminance( vec3 sample ) // // Max component luminance. // - //float lum = max( sample.r, max( sample.g, sample.b ) ); + //float lum = max( _sample.r, max( _sample.g, _sample.b ) ); //////////////////////////////////////////////////////////////////////////// // The perceptual relative luminance. @@ -224,23 +228,45 @@ float hdrLuminance( vec3 sample ) // See http://en.wikipedia.org/wiki/Luminance_(relative) // const vec3 RELATIVE_LUMINANCE = vec3( 0.2126, 0.7152, 0.0722 ); - float lum = dot( sample, RELATIVE_LUMINANCE ); + float lum = dot( _sample, RELATIVE_LUMINANCE ); //////////////////////////////////////////////////////////////////////////// // // The average component luminance. // //const vec3 AVERAGE_LUMINANCE = vec3( 0.3333, 0.3333, 0.3333 ); - //float lum = dot( sample, AVERAGE_LUMINANCE ); + //float lum = dot( _sample, AVERAGE_LUMINANCE ); return lum; } +#ifdef TORQUE_PIXEL_SHADER +/// Called from the visibility feature to do screen +/// door transparency for fading of objects. +void fizzle(vec2 vpos, float visibility) +{ + // NOTE: The magic values below are what give us + // the nice even pattern during the fizzle. + // + // These values can be changed to get different + // patterns... some better than others. + // + // Horizontal Blinds - { vpos.x, 0.916, vpos.y, 0 } + // Vertical Lines - { vpos.x, 12.9898, vpos.y, 78.233 } + // + // I'm sure there are many more patterns here to + // discover for different effects. + + mat2x2 m = mat2x2( vpos.x, vpos.y, 0.916, 0.350 ); + if( (visibility - fract( determinant( m ) )) < 0 ) //if(a < 0) discard; + discard; +} +#endif //TORQUE_PIXEL_SHADER /// Basic assert macro. If the condition fails, then the shader will output color. /// @param condition This should be a bvec[2-4]. If any items is false, condition is considered to fail. /// @param color The color that should be outputted if the condition fails. /// @note This macro will only work in the void main() method of a pixel shader. -#define assert(condition, color) { if(!any(condition)) { gl_FragColor = color; return; } } +#define assert(condition, color) { if(!any(condition)) { OUT_FragColor0 = color; return; } } #endif // _TORQUE_GLSL_ diff --git a/Templates/Empty/game/shaders/common/gl/wavesP.glsl b/Templates/Empty/game/shaders/common/gl/wavesP.glsl index 24bd8cbb4..ddb683947 100644 --- a/Templates/Empty/game/shaders/common/gl/wavesP.glsl +++ b/Templates/Empty/game/shaders/common/gl/wavesP.glsl @@ -28,10 +28,10 @@ uniform float specularPower; uniform vec4 ambient; uniform float accumTime; -varying vec2 TEX0; -varying vec4 outLightVec; -varying vec3 outPos; -varying vec3 outEyePos; +in vec2 TEX0; +in vec4 outLightVec; +in vec3 outPos; +in vec3 outEyePos; void main() { @@ -42,14 +42,14 @@ void main() texOffset.x = TEX0.x + sinOffset1 + sinOffset2; texOffset.y = TEX0.y + cos( accumTime * 3.0 + TEX0.x * 6.28319 * 2.0 ) * 0.05; - vec4 bumpNorm = texture2D(bumpMap, texOffset) * 2.0 - 1.0; - vec4 diffuse = texture2D(diffMap, texOffset); + vec4 bumpNorm = texture(bumpMap, texOffset) * 2.0 - 1.0; + vec4 diffuse = texture(diffMap, texOffset); - gl_FragColor = diffuse * (clamp(dot(outLightVec.xyz, bumpNorm.xyz), 0.0, 1.0) + ambient); + OUT_FragColor0 = diffuse * (clamp(dot(outLightVec.xyz, bumpNorm.xyz), 0.0, 1.0) + ambient); vec3 eyeVec = normalize(outEyePos - outPos); vec3 halfAng = normalize(eyeVec + outLightVec.xyz); float specular = clamp(dot(bumpNorm.xyz, halfAng), 0.0, 1.0) * outLightVec.w; specular = pow(specular, specularPower); - gl_FragColor += specularColor * specular; + OUT_FragColor0 += specularColor * specular; } diff --git a/Templates/Empty/game/shaders/common/lighting/advanced/gl/convexGeometryV.glsl b/Templates/Empty/game/shaders/common/lighting/advanced/gl/convexGeometryV.glsl index 6d3e36e7e..1807ac43f 100644 --- a/Templates/Empty/game/shaders/common/lighting/advanced/gl/convexGeometryV.glsl +++ b/Templates/Empty/game/shaders/common/lighting/advanced/gl/convexGeometryV.glsl @@ -20,16 +20,33 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- -varying vec4 wsEyeDir; -varying vec4 ssPos; +#include "../../../gl/hlslCompat.glsl" + +in vec4 vPosition; + +#define IN_pos vPosition + +out vec4 wsEyeDir; +out vec4 ssPos; +out vec4 vsEyeDir; + +#define OUT_hpos gl_Position +#define OUT_wsEyeDir wsEyeDir +#define OUT_ssPos ssPos +#define OUT_vsEyeDir vsEyeDir uniform mat4 modelview; uniform mat4 objTrans; +uniform mat4 worldViewOnly; uniform vec3 eyePosWorld; void main() { - gl_Position = modelview * gl_Vertex; - wsEyeDir = objTrans * gl_Vertex - vec4( eyePosWorld, 0.0 ); - ssPos = gl_Position; + OUT_hpos = tMul( modelview, IN_pos ); + OUT_wsEyeDir = tMul( objTrans, IN_pos ) - vec4( eyePosWorld, 0.0 ); + OUT_vsEyeDir = tMul( worldViewOnly, IN_pos ); + OUT_ssPos = OUT_hpos; + + correctSSP(gl_Position); } + diff --git a/Templates/Empty/game/shaders/common/lighting/advanced/gl/dbgDepthVisualizeP.glsl b/Templates/Empty/game/shaders/common/lighting/advanced/gl/dbgDepthVisualizeP.glsl index 4a954ae84..e3ee59c8a 100644 --- a/Templates/Empty/game/shaders/common/lighting/advanced/gl/dbgDepthVisualizeP.glsl +++ b/Templates/Empty/game/shaders/common/lighting/advanced/gl/dbgDepthVisualizeP.glsl @@ -20,14 +20,15 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- +#include "../../../gl/hlslCompat.glsl" #include "shadergen:/autogenConditioners.h" -varying vec2 uv0; +in vec2 uv0; uniform sampler2D prepassBuffer; uniform sampler1D depthViz; void main() { float depth = prepassUncondition( prepassBuffer, uv0 ).w; - gl_FragColor = vec4( texture1D( depthViz, depth ).rgb, 1 ); + OUT_FragColor0 = vec4( texture( depthViz, depth ).rgb, 1.0 ); } \ No newline at end of file diff --git a/Templates/Empty/game/shaders/common/lighting/advanced/gl/dbgLightColorVisualizeP.glsl b/Templates/Empty/game/shaders/common/lighting/advanced/gl/dbgLightColorVisualizeP.glsl index 580204487..aa17df4d6 100644 --- a/Templates/Empty/game/shaders/common/lighting/advanced/gl/dbgLightColorVisualizeP.glsl +++ b/Templates/Empty/game/shaders/common/lighting/advanced/gl/dbgLightColorVisualizeP.glsl @@ -20,15 +20,16 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- +#include "../../../gl/hlslCompat.glsl" #include "shadergen:/autogenConditioners.h" -varying vec2 uv0; +in vec2 uv0; uniform sampler2D lightInfoBuffer; void main() { - vec3 lightcolor; + vec3 lightcolor; float nl_Att, specular; - lightinfoUncondition( texture2DLod( lightInfoBuffer, uv0 ), lightcolor, nl_Att, specular ); - gl_FragColor = vec4( lightcolor, 1.0 ); + lightinfoUncondition( texture( lightInfoBuffer, uv0 ), lightcolor, nl_Att, specular ); + OUT_FragColor0 = vec4( lightcolor, 1.0 ); } \ No newline at end of file diff --git a/Templates/Empty/game/shaders/common/lighting/advanced/gl/dbgLightSpecularVisualizeP.glsl b/Templates/Empty/game/shaders/common/lighting/advanced/gl/dbgLightSpecularVisualizeP.glsl index 6f7c52486..e549922ff 100644 --- a/Templates/Empty/game/shaders/common/lighting/advanced/gl/dbgLightSpecularVisualizeP.glsl +++ b/Templates/Empty/game/shaders/common/lighting/advanced/gl/dbgLightSpecularVisualizeP.glsl @@ -20,15 +20,16 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- +#include "../../../gl/hlslCompat.glsl" #include "shadergen:/autogenConditioners.h" -varying vec2 uv0; +in vec2 uv0; uniform sampler2D lightInfoBuffer; void main() { - vec3 lightcolor; + vec3 lightcolor; float nl_Att, specular; - lightinfoUncondition( texture2DLod( lightInfoBuffer, uv0 ), lightcolor, nl_Att, specular ); - gl_FragColor = vec4( specular, specular, specular, 1.0 ); + lightinfoUncondition( texture( lightInfoBuffer, uv0 ), lightcolor, nl_Att, specular ); + OUT_FragColor0 = vec4( specular, specular, specular, 1.0 ); } \ No newline at end of file diff --git a/Templates/Empty/game/shaders/common/lighting/advanced/gl/dbgNormalVisualizeP.glsl b/Templates/Empty/game/shaders/common/lighting/advanced/gl/dbgNormalVisualizeP.glsl index 96b645524..f61706393 100644 --- a/Templates/Empty/game/shaders/common/lighting/advanced/gl/dbgNormalVisualizeP.glsl +++ b/Templates/Empty/game/shaders/common/lighting/advanced/gl/dbgNormalVisualizeP.glsl @@ -20,14 +20,14 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- +#include "../../../gl/hlslCompat.glsl" #include "shadergen:/autogenConditioners.h" - -varying vec2 uv0; -uniform sampler2D prepassTex; +in vec2 uv0; +uniform sampler2D prepassBuffer; void main() { - vec3 normal = prepassUncondition( prepassTex, uv0 ).xyz; - gl_FragColor = vec4( ( normal + 1.0 ) * 0.5, 1.0 ); + vec3 normal = prepassUncondition( prepassBuffer, uv0 ).xyz; + OUT_FragColor0 = vec4( ( normal + 1.0 ) * 0.5, 1.0 ); } \ No newline at end of file diff --git a/Templates/Empty/game/shaders/common/lighting/advanced/gl/dbgShadowVisualizeP.glsl b/Templates/Empty/game/shaders/common/lighting/advanced/gl/dbgShadowVisualizeP.glsl index 51609fc6b..e997950ab 100644 --- a/Templates/Empty/game/shaders/common/lighting/advanced/gl/dbgShadowVisualizeP.glsl +++ b/Templates/Empty/game/shaders/common/lighting/advanced/gl/dbgShadowVisualizeP.glsl @@ -19,13 +19,14 @@ // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. //----------------------------------------------------------------------------- +#include "../../../gl/hlslCompat.glsl" -varying vec2 uv0; +in vec2 uv0; uniform sampler2D shadowMap; uniform sampler1D depthViz; void main() { - float depth = clamp( texture2DLod( shadowMap, uv0, 0 ).r, 0.0, 1.0 ); - gl_FragColor = vec4( texture1D( depthViz, depth ).rgb, 1.0 ); + float depth = saturate( texture( shadowMap, uv0 ).r ); + OUT_FragColor0 = vec4( texture( depthViz, depth ).rgb, 1 ); } \ No newline at end of file diff --git a/Templates/Empty/game/shaders/common/lighting/advanced/gl/farFrustumQuad.glsl b/Templates/Empty/game/shaders/common/lighting/advanced/gl/farFrustumQuad.glsl index 866a39b0b..76054eb09 100644 --- a/Templates/Empty/game/shaders/common/lighting/advanced/gl/farFrustumQuad.glsl +++ b/Templates/Empty/game/shaders/common/lighting/advanced/gl/farFrustumQuad.glsl @@ -24,7 +24,7 @@ vec2 getUVFromSSPos( vec3 ssPos, vec4 rtParams ) { vec2 outPos = ( ssPos.xy + 1.0 ) / 2.0; + outPos.y = 1.0 - outPos.y; outPos = ( outPos * rtParams.zw ) + rtParams.xy; - //outPos.y = 1.0 - outPos.y; return outPos; } diff --git a/Templates/Empty/game/shaders/common/lighting/advanced/gl/farFrustumQuadV.glsl b/Templates/Empty/game/shaders/common/lighting/advanced/gl/farFrustumQuadV.glsl index ce5c2ad81..a80e856ed 100644 --- a/Templates/Empty/game/shaders/common/lighting/advanced/gl/farFrustumQuadV.glsl +++ b/Templates/Empty/game/shaders/common/lighting/advanced/gl/farFrustumQuadV.glsl @@ -20,24 +20,32 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- +#include "../../../gl/hlslCompat.glsl" #include "farFrustumQuad.glsl" -uniform vec4 renderTargetParams; - -varying vec4 hpos; -varying vec2 uv0; -varying vec3 wsEyeRay; +in vec4 vPosition; +in vec3 vNormal; +in vec3 vTangent; +in vec2 vTexCoord0; +uniform vec4 rtParams0; +out vec4 hpos; +out vec2 uv0; +out vec3 wsEyeRay; +out vec3 vsEyeRay; void main() -{ - // Expand the SS coordinate (stored in uv0) - hpos = vec4( gl_MultiTexCoord0.st * 2.0 - 1.0, 1.0, 1.0 ); - gl_Position = hpos; - +{ + hpos = vec4( vTexCoord0, 0, 1 ); + // Get a RT-corrected UV from the SS coord - uv0 = getUVFromSSPos( hpos.xyz, renderTargetParams ); + uv0 = getUVFromSSPos( hpos.xyz, rtParams0 ); + gl_Position = hpos; - // Interpolators will generate eye ray from far-frustum corners - wsEyeRay = gl_Vertex.xyz; + // Interpolators will generate eye rays the + // from far-frustum corners. + wsEyeRay = vTangent; + vsEyeRay = vNormal; + + correctSSP(gl_Position); } diff --git a/Templates/Empty/game/shaders/common/lighting/advanced/gl/pointLightP.glsl b/Templates/Empty/game/shaders/common/lighting/advanced/gl/pointLightP.glsl index b135f1aa8..c0610508b 100644 --- a/Templates/Empty/game/shaders/common/lighting/advanced/gl/pointLightP.glsl +++ b/Templates/Empty/game/shaders/common/lighting/advanced/gl/pointLightP.glsl @@ -21,34 +21,26 @@ //----------------------------------------------------------------------------- #include "../../../gl/hlslCompat.glsl" -#include "farFrustumQuad.glsl" -#include "lightingUtils.glsl" -#include "../../shadowMap/shadowMapIO_GLSL.h" #include "shadergen:/autogenConditioners.h" +#include "farFrustumQuad.glsl" +#include "lightingUtils.glsl" +#include "../../../gl/lighting.glsl" +#include "../../shadowMap/shadowMapIO_GLSL.h" +#include "softShadow.glsl" -#if TORQUE_SM >= 30 +in vec4 wsEyeDir; +in vec4 ssPos; +in vec4 vsEyeDir; - // Enables high quality soft shadow - // filtering for SM3.0 and above. - #define SOFTSHADOW_SM3 - - #include "softShadow.glsl" - -#else +#ifdef USE_COOKIE_TEX +/// The texture for cookie rendering. +uniform samplerCube cookieMap ; #endif - -// I am not sure if we should do this in a better way -//#define SHADOW_CUBE -//#define SHADOW_PARABOLOID -#define SHADOW_DUALPARABOLOID -#define SHADOW_DUALPARABOLOID_SINGLE_PASS - - #ifdef SHADOW_CUBE vec3 decodeShadowCoord( vec3 shadowCoord ) @@ -56,39 +48,47 @@ return shadowCoord; } - vec4 shadowSample( samplerCUBE shadowMap, vec3 shadowCoord ) + vec4 shadowSample( samplerCube shadowMap, vec3 shadowCoord ) { - return textureCUBE( shadowMap, shadowCoord ); + return texture( shadowMap, shadowCoord ); } - -#elif defined( SHADOW_DUALPARABOLOID ) + +#else vec3 decodeShadowCoord( vec3 paraVec ) { - // Swizzle z and y + // Flip y and z paraVec = paraVec.xzy; - #ifdef SHADOW_DUALPARABOLOID_SINGLE_PASS + #ifndef SHADOW_PARABOLOID bool calcBack = (paraVec.z < 0.0); - if(calcBack) + if ( calcBack ) + { paraVec.z = paraVec.z * -1.0; + + #ifdef SHADOW_DUALPARABOLOID + paraVec.x = -paraVec.x; + #endif + } #endif vec3 shadowCoord; - shadowCoord.x = (paraVec.x / (2.0*(1.0 + paraVec.z))) + 0.5; - shadowCoord.y = ((paraVec.y / (2.0*(1.0 + paraVec.z))) + 0.5); + shadowCoord.x = (paraVec.x / (2*(1 + paraVec.z))) + 0.5; + shadowCoord.y = 1-((paraVec.y / (2*(1 + paraVec.z))) + 0.5); shadowCoord.z = 0; // adjust the co-ordinate slightly if it is near the extent of the paraboloid // this value was found via experementation - shadowCoord.xy *= 0.997; + // NOTE: this is wrong, it only biases in one direction, not towards the uv + // center ( 0.5 0.5 ). + //shadowCoord.xy *= 0.997; - #ifdef SHADOW_DUALPARABOLOID_SINGLE_PASS + #ifndef SHADOW_PARABOLOID // If this is the back, offset in the atlas - if(calcBack) + if ( calcBack ) shadowCoord.x += 1.0; // Atlasing front and back maps, so scale @@ -99,51 +99,35 @@ return shadowCoord; } -#else - - #error Unknown shadow type! - #endif -varying vec4 wsEyeDir; -varying vec4 ssPos; - - uniform sampler2D prePassBuffer; #ifdef SHADOW_CUBE - uniform samplerCube shadowMap; + uniform samplerCube shadowMap; #else - uniform sampler2D shadowMap; -#endif -#ifdef ACCUMULATE_LUV - uniform sampler2D scratchTarget; + uniform sampler2D shadowMap; #endif -uniform vec4 renderTargetParams; +uniform vec4 rtParams0; uniform vec3 lightPosition; uniform vec4 lightColor; -uniform float lightBrightness; -uniform float lightRange; +uniform float lightBrightness; +uniform float lightRange; uniform vec2 lightAttenuation; uniform vec4 lightMapParams; - -uniform vec3 eyePosWorld; -uniform vec4 farPlane; -uniform float negFarPlaneDotEye; -uniform mat3x3 worldToLightProj; - +uniform vec4 vsFarPlane; +uniform mat3 viewToLightProj; uniform vec4 lightParams; uniform float shadowSoftness; -uniform float constantSpecularPower; + - -void main() -{ +void main() +{ // Compute scene UV - vec3 ssPosP = ssPos.xyz / ssPos.w; - vec2 uvScene = getUVFromSSPos( ssPosP, renderTargetParams ); + vec3 ssPos = ssPos.xyz / ssPos.w; + vec2 uvScene = getUVFromSSPos( ssPos, rtParams0 ); // Sample/unpack the normal/z data vec4 prepassSample = prepassUncondition( prePassBuffer, uvScene ); @@ -151,21 +135,17 @@ void main() float depth = prepassSample.a; // Eye ray - Eye -> Pixel - vec3 eyeRay = getDistanceVectorToPlane( negFarPlaneDotEye, wsEyeDir.xyz / wsEyeDir.w , farPlane ); - - // Get world space pixel position - vec3 worldPos = eyePosWorld + eyeRay * depth; + vec3 eyeRay = getDistanceVectorToPlane( -vsFarPlane.w, vsEyeDir.xyz, vsFarPlane ); + vec3 viewSpacePos = eyeRay * depth; // Build light vec, get length, clip pixel if needed - vec3 lightVec = lightPosition - worldPos; + vec3 lightVec = lightPosition - viewSpacePos; float lenLightV = length( lightVec ); - if ( lightRange - lenLightV < 0.0 ) - discard; - + clip( lightRange - lenLightV ); + // Get the attenuated falloff. float atten = attenuate( lightColor, lightAttenuation, lenLightV ); - if ( atten - 1e-6 < 0.0 ) - discard; + clip( atten - 1e-6 ); // Normalize lightVec lightVec /= lenLightV; @@ -181,61 +161,73 @@ void main() #else - // Convert the light vector into a shadow map - // here once instead of in the filtering loop. - vec4 shadowCoord = vec4(0.0); - #ifdef SHADOW_CUBE - shadowCoord.xy = decodeShadowCoord( -lightVec ); - #else - shadowCoord.xy = decodeShadowCoord( worldToLightProj * -lightVec ).xy; - #endif - // Get a linear depth from the light source. - float distToLight = lenLightV / lightRange; + float distToLight = lenLightV / lightRange; - #ifdef SOFTSHADOW_SM3 + #ifdef SHADOW_CUBE + + // TODO: We need to fix shadow cube to handle soft shadows! + float occ = texture( shadowMap, tMul( viewToLightProj, -lightVec ) ).r; + float shadowed = saturate( exp( lightParams.y * ( occ - distToLight ) ) ); + + #else + vec2 shadowCoord = decodeShadowCoord( tMul( viewToLightProj, -lightVec ) ).xy; + float shadowed = softShadow_filter( shadowMap, - gTapRotationTex, - ssPosP.xy, - shadowCoord.xy, + ssPos.xy, + shadowCoord, shadowSoftness, distToLight, nDotL, lightParams.y ); - - #else // !SOFTSHADOW_SM3 - - // TODO: Implement the SM2 lower quality - // shadow filtering method. #endif #endif // !NO_SHADOW - + + #ifdef USE_COOKIE_TEX + + // Lookup the cookie sample. + vec4 cookie = texture( cookieMap, tMul( viewToLightProj, -lightVec ) ); + + // Multiply the light with the cookie tex. + lightColor.rgb *= cookie.rgb; + + // Use a maximum channel luminance to attenuate + // the lighting else we get specular in the dark + // regions of the cookie texture. + atten *= max( cookie.r, max( cookie.g, cookie.b ) ); + + #endif + // NOTE: Do not clip on fully shadowed pixels as it would // cause the hardware occlusion query to disable the shadow. // Specular term - float specular = calcSpecular( lightVec, - normal, - normalize( -eyeRay ), - constantSpecularPower, - shadowed * atten * lightBrightness ); - - // N.L * Attenuation - float Sat_NL_Att = clamp( nDotL * atten * shadowed, 0.0, 1.0 ); - - // In LUV color mode we need to blend in the - // output from the previous target. - vec4 previousPix = vec4(0.0); - #ifdef ACCUMULATE_LUV - previousPix = texture2DLod( scratchTarget, uvScene, 0 ); - #endif + float specular = AL_CalcSpecular( lightVec, + normal, + normalize( -eyeRay ) ) * lightBrightness * atten * shadowed; - // Output - gl_FragColor = lightinfoCondition( lightColor.rgb * lightBrightness, - Sat_NL_Att, - specular, - previousPix ) * lightMapParams; + float Sat_NL_Att = saturate( nDotL * atten * shadowed ) * lightBrightness; + vec3 lightColorOut = lightMapParams.rgb * lightColor.rgb; + vec4 addToResult = vec4(0.0); + + // TODO: This needs to be removed when lightmapping is disabled + // as its extra work per-pixel on dynamic lit scenes. + // + // Special lightmapping pass. + if ( lightMapParams.a < 0.0 ) + { + // This disables shadows on the backsides of objects. + shadowed = nDotL < 0.0f ? 1.0f : shadowed; + + Sat_NL_Att = 1.0f; + shadowed = mix( 1.0f, shadowed, atten ); + lightColorOut = vec3(shadowed); + specular *= lightBrightness; + addToResult = ( 1.0 - shadowed ) * abs(lightMapParams); + } + + OUT_FragColor0 = lightinfoCondition( lightColorOut, Sat_NL_Att, specular, addToResult ); } diff --git a/Templates/Empty/game/shaders/common/lighting/advanced/gl/softShadow.glsl b/Templates/Empty/game/shaders/common/lighting/advanced/gl/softShadow.glsl index 8ef09ed2f..a14213946 100644 --- a/Templates/Empty/game/shaders/common/lighting/advanced/gl/softShadow.glsl +++ b/Templates/Empty/game/shaders/common/lighting/advanced/gl/softShadow.glsl @@ -19,113 +19,141 @@ // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. //----------------------------------------------------------------------------- - - -#define NUM_TAPS 12 - -#define NUM_PRE_TAPS 4 - -/// The non-uniform poisson disk used in the -/// high quality shadow filtering. -vec2 sNonUniformTaps[NUM_TAPS]; -void initNonUniformTaps() + +#if defined( SOFTSHADOW ) && defined( SOFTSHADOW_HIGH_QUALITY ) + +#define NUM_PRE_TAPS 4 +#define NUM_TAPS 12 + +/// The non-uniform poisson disk used in the +/// high quality shadow filtering. +vec2 sNonUniformTaps[NUM_TAPS] = vec2[] +( + // These first 4 taps are located around the edges + // of the disk and are used to predict fully shadowed + // or unshadowed areas. + vec2( 0.992833, 0.979309 ), + vec2( -0.998585, 0.985853 ), + vec2( 0.949299, -0.882562 ), + vec2( -0.941358, -0.893924 ), + + // The rest of the samples. + vec2( 0.545055, -0.589072 ), + vec2( 0.346526, 0.385821 ), + vec2( -0.260183, 0.334412 ), + vec2( 0.248676, -0.679605 ), + vec2( -0.569502, -0.390637 ), + vec2( -0.614096, 0.212577 ), + vec2( -0.259178, 0.876272 ), + vec2( 0.649526, 0.864333 ) +); + +#else + +#define NUM_PRE_TAPS 5 + +/// The non-uniform poisson disk used in the +/// high quality shadow filtering. +vec2 sNonUniformTaps[NUM_PRE_TAPS] = vec2[] +( + vec2( 0.892833, 0.959309 ), + vec2( -0.941358, -0.873924 ), + vec2( -0.260183, 0.334412 ), + vec2( 0.348676, -0.679605 ), + vec2( -0.569502, -0.390637 ) +); + +#endif + + +/// The texture used to do per-pixel pseudorandom +/// rotations of the filter taps. +uniform sampler2D gTapRotationTex ; + + +float softShadow_sampleTaps( sampler2D shadowMap, + vec2 sinCos, + vec2 shadowPos, + float filterRadius, + float distToLight, + float esmFactor, + int startTap, + int endTap ) { - // These first 4 taps are located around the edges - // of the disk and are used to predict fully shadowed - // or unshadowed areas. - sNonUniformTaps[0] = vec2( 0.992833, 0.979309 ); - sNonUniformTaps[1] = vec2( -0.998585, 0.985853 ); - sNonUniformTaps[2] = vec2( 0.949299, -0.882562 ); - sNonUniformTaps[3] = vec2( -0.941358, -0.893924 ); - - // The rest of the samples. - sNonUniformTaps[4] = vec2( 0.545055, -0.589072 ); - sNonUniformTaps[5] = vec2( 0.346526, 0.385821 ); - sNonUniformTaps[6] = vec2( -0.260183, 0.334412 ); - sNonUniformTaps[7] = vec2( 0.248676, -0.679605 ); - sNonUniformTaps[8] = vec2( -0.569502, -0.390637 ); - sNonUniformTaps[9] = vec2( -0.014096, 0.012577 ); - sNonUniformTaps[10] = vec2( -0.259178, 0.876272 ); - sNonUniformTaps[11] = vec2( 0.649526, 0.664333 ); + float shadow = 0; + + vec2 tap = vec2(0); + for ( int t = startTap; t < endTap; t++ ) + { + tap.x = ( sNonUniformTaps[t].x * sinCos.y - sNonUniformTaps[t].y * sinCos.x ) * filterRadius; + tap.y = ( sNonUniformTaps[t].y * sinCos.y + sNonUniformTaps[t].x * sinCos.x ) * filterRadius; + float occluder = tex2Dlod( shadowMap, vec4( shadowPos + tap, 0, 0 ) ).r; + + float esm = saturate( exp( esmFactor * ( occluder - distToLight ) ) ); + shadow += esm / float( endTap - startTap ); + } + + return shadow; } - -/// The texture used to do per-pixel pseudorandom -/// rotations of the filter taps. -uniform sampler2D gTapRotationTex; - - -float softShadow_sampleTaps( sampler2D shadowMap, - vec2 sinCos, - vec2 shadowPos, - float filterRadius, - float distToLight, - float esmFactor, - int startTap, - int endTap ) -{ - initNonUniformTaps(); - float shadow = 0.0; - - vec2 tap = vec2(0.0); - for ( int t = startTap; t < endTap; t++ ) - { - tap.x = ( sNonUniformTaps[t].x * sinCos.y - sNonUniformTaps[t].y * sinCos.x ) * filterRadius; - tap.y = ( sNonUniformTaps[t].y * sinCos.y + sNonUniformTaps[t].x * sinCos.x ) * filterRadius; - float occluder = texture2DLod( shadowMap, shadowPos + tap, 0.0 ).r; - - float esm = clamp( exp( esmFactor * ( occluder - distToLight ) ), 0.0, 1.0 ); - shadow += esm / float( endTap - startTap ); - } - - return shadow; -} - - -// HACK! HACK! HACK! -// We take the noise texture directly as the second parameter to ensure that it -// is the "last used" sampler, and thus doesn't collide with the prepass buffer -// or shadow map. If we use gTapRotationTex directly here, then it is the first -// used sampler and will collide with the prepass buffer. -float softShadow_filter( sampler2D shadowMap, - sampler2D noiseTexture, - vec2 vpos, - vec2 shadowPos, - float filterRadius, - float distToLight, - float dotNL, - float esmFactor ) -{ - // Lookup the random rotation for this screen pixel. - vec2 sinCos = ( texture2DLod( noiseTexture, vpos * 16.0, 0.0 ).rg - 0.5 ) * 2.0; - - // Do the prediction taps first. - float shadow = softShadow_sampleTaps( shadowMap, - sinCos, - shadowPos, - filterRadius, - distToLight, - esmFactor, - 0, - NUM_PRE_TAPS ); - - // Only do the expensive filtering if we're really - // in a partially shadowed area. - if ( shadow * ( 1.0 - shadow ) * max( dotNL, 0.0 ) > 0.06 ) - { - shadow += softShadow_sampleTaps( shadowMap, - sinCos, - shadowPos, - filterRadius, - distToLight, - esmFactor, - NUM_PRE_TAPS, - NUM_TAPS ); - - // This averages the taps above with the results - // of the prediction samples. - shadow *= 0.5; - } - - return shadow; -} \ No newline at end of file + + +float softShadow_filter( sampler2D shadowMap, + vec2 vpos, + vec2 shadowPos, + float filterRadius, + float distToLight, + float dotNL, + float esmFactor ) +{ + #ifndef SOFTSHADOW + + // If softshadow is undefined then we skip any complex + // filtering... just do a single sample ESM. + + float occluder = tex2Dlod( shadowMap, vec4( shadowPos, 0, 0 ) ).r; + float shadow = saturate( exp( esmFactor * ( occluder - distToLight ) ) ); + + #else + + // Lookup the random rotation for this screen pixel. + vec2 sinCos = ( tex2Dlod( gTapRotationTex, vec4( vpos * 16, 0, 0 ) ).rg - 0.5 ) * 2; + + // Do the prediction taps first. + float shadow = softShadow_sampleTaps( shadowMap, + sinCos, + shadowPos, + filterRadius, + distToLight, + esmFactor, + 0, + NUM_PRE_TAPS ); + + // We live with only the pretap results if we don't + // have high quality shadow filtering enabled. + #ifdef SOFTSHADOW_HIGH_QUALITY + + // Only do the expensive filtering if we're really + // in a partially shadowed area. + if ( shadow * ( 1.0 - shadow ) * max( dotNL, 0 ) > 0.06 ) + { + shadow += softShadow_sampleTaps( shadowMap, + sinCos, + shadowPos, + filterRadius, + distToLight, + esmFactor, + NUM_PRE_TAPS, + NUM_TAPS ); + + // This averages the taps above with the results + // of the prediction samples. + shadow *= 0.5; + } + + #endif // SOFTSHADOW_HIGH_QUALITY + + #endif // SOFTSHADOW + + return shadow; +} \ No newline at end of file diff --git a/Templates/Empty/game/shaders/common/lighting/advanced/gl/spotLightP.glsl b/Templates/Empty/game/shaders/common/lighting/advanced/gl/spotLightP.glsl index d29f5edb0..c07be1f34 100644 --- a/Templates/Empty/game/shaders/common/lighting/advanced/gl/spotLightP.glsl +++ b/Templates/Empty/game/shaders/common/lighting/advanced/gl/spotLightP.glsl @@ -25,58 +25,49 @@ #include "lightingUtils.glsl" #include "../../shadowMap/shadowMapIO_GLSL.h" #include "shadergen:/autogenConditioners.h" +#include "softShadow.glsl" +#include "../../../gl/lighting.glsl" +in vec4 wsEyeDir; +in vec4 ssPos; +in vec4 vsEyeDir; -#if TORQUE_SM >= 30 +#define IN_wsEyeDir wsEyeDir +#define IN_ssPos ssPos +#define IN_vsEyeDir vsEyeDir - // Enables high quality soft shadow - // filtering for SM3.0 and above. - #define SOFTSHADOW_SM3 - - #include "softShadow.glsl" - -#else +#ifdef USE_COOKIE_TEX +/// The texture for cookie rendering. +uniform sampler2D cookieMap; #endif - -varying vec4 ssPos; -varying vec4 wsEyeDir; - - uniform sampler2D prePassBuffer; uniform sampler2D shadowMap; -#ifdef ACCUMULATE_LUV - uniform sampler2D scratchTarget; -#endif -uniform vec4 renderTargetParams; +uniform vec4 rtParams0; uniform vec3 lightPosition; uniform vec4 lightColor; -uniform float lightBrightness; -uniform float lightRange; +uniform float lightBrightness; +uniform float lightRange; uniform vec2 lightAttenuation; uniform vec3 lightDirection; uniform vec4 lightSpotParams; uniform vec4 lightMapParams; -uniform vec3 eyePosWorld; -uniform vec4 farPlane; -uniform float negFarPlaneDotEye; -uniform mat4x4 worldToLightProj; +uniform vec4 vsFarPlane; +uniform mat4 viewToLightProj; uniform vec4 lightParams; uniform float shadowSoftness; -uniform float constantSpecularPower; - void main() -{ +{ // Compute scene UV - vec3 ssPosP = ssPos.xyz / ssPos.w; - vec2 uvScene = getUVFromSSPos( ssPosP, renderTargetParams ); + vec3 ssPos = IN_ssPos.xyz / IN_ssPos.w; + vec2 uvScene = getUVFromSSPos( ssPos, rtParams0 ); // Sample/unpack the normal/z data vec4 prepassSample = prepassUncondition( prePassBuffer, uvScene ); @@ -84,85 +75,92 @@ void main() float depth = prepassSample.a; // Eye ray - Eye -> Pixel - vec3 eyeRay = getDistanceVectorToPlane( negFarPlaneDotEye, wsEyeDir.xyz / wsEyeDir.w , farPlane ); - - // Get world space pixel position - vec3 worldPos = eyePosWorld + eyeRay * depth; + vec3 eyeRay = getDistanceVectorToPlane( -vsFarPlane.w, IN_vsEyeDir.xyz, vsFarPlane ); + vec3 viewSpacePos = eyeRay * depth; // Build light vec, get length, clip pixel if needed - vec3 lightToPxlVec = worldPos - lightPosition; + vec3 lightToPxlVec = viewSpacePos - lightPosition; float lenLightV = length( lightToPxlVec ); lightToPxlVec /= lenLightV; - //lightDirection = float3( -lightDirection.xy, lightDirection.z ); //float3( 0, 0, -1 ); + //lightDirection = vec3( -lightDirection.xy, lightDirection.z ); //vec3( 0, 0, -1 ); float cosAlpha = dot( lightDirection, lightToPxlVec ); - if ( cosAlpha - lightSpotParams.x < 0.0 ) discard; - if ( lightRange - lenLightV < 0.0 ) discard; + clip( cosAlpha - lightSpotParams.x ); + clip( lightRange - lenLightV ); float atten = attenuate( lightColor, lightAttenuation, lenLightV ); atten *= ( cosAlpha - lightSpotParams.x ) / lightSpotParams.y; - if ( atten - 1e-6 < 0.0 ) discard; + clip( atten - 1e-6 ); + atten = saturate( atten ); float nDotL = dot( normal, -lightToPxlVec ); + // Get the shadow texture coordinate + vec4 pxlPosLightProj = tMul( viewToLightProj, vec4( viewSpacePos, 1 ) ); + vec2 shadowCoord = ( ( pxlPosLightProj.xy / pxlPosLightProj.w ) * 0.5 ) + vec2( 0.5, 0.5 ); + shadowCoord.y = 1.0f - shadowCoord.y; + #ifdef NO_SHADOW float shadowed = 1.0; #else - // Find Shadow coordinate - vec4 pxlPosLightProj = vec4( worldToLightProj * vec4( worldPos, 1.0 ) ); - vec2 shadowCoord = ( ( pxlPosLightProj.xy / pxlPosLightProj.w ) * 0.5 ) + vec2( 0.5, 0.5 ); - // Get a linear depth from the light source. float distToLight = pxlPosLightProj.z / lightRange; - #ifdef SOFTSHADOW_SM3 - - float shadowed = softShadow_filter( shadowMap, - gTapRotationTex, - ssPosP.xy, - shadowCoord, - shadowSoftness, - distToLight, - nDotL, - lightParams.y ); - - #else // !SOFTSHADOW_SM3 - - // Simple exponential shadow map. - float occluder = decodeShadowMap( texture2DLod( shadowMap, shadowCoord, 0.0 ) ); - float esmFactor = lightParams.y; - float shadowed = clamp( exp( esmFactor * ( occluder - distToLight ) ), 0.0, 1.0 ); - - #endif + float shadowed = softShadow_filter( shadowMap, + ssPos.xy, + shadowCoord, + shadowSoftness, + distToLight, + nDotL, + lightParams.y ); #endif // !NO_SHADOW - + + #ifdef USE_COOKIE_TEX + + // Lookup the cookie sample. + vec4 cookie = texture( cookieMap, shadowCoord ); + + // Multiply the light with the cookie tex. + lightColor.rgb *= cookie.rgb; + + // Use a maximum channel luminance to attenuate + // the lighting else we get specular in the dark + // regions of the cookie texture. + atten *= max( cookie.r, max( cookie.g, cookie.b ) ); + + #endif + // NOTE: Do not clip on fully shadowed pixels as it would // cause the hardware occlusion query to disable the shadow. // Specular term - float specular = calcSpecular( -lightToPxlVec, - normal, - normalize( -eyeRay ), - constantSpecularPower, - shadowed * atten * lightBrightness ); - - // N.L * Attenuation - float Sat_NL_Att = clamp( nDotL * atten * shadowed, 0.0, 1.0 ); - - // In LUV color mode we need to blend in the - // output from the previous target. - vec4 previousPix = vec4(0.0); - #ifdef ACCUMULATE_LUV - previousPix = texture2DLod( scratchTarget, uvScene, 0.0 ); - #endif + float specular = AL_CalcSpecular( -lightToPxlVec, + normal, + normalize( -eyeRay ) ) * lightBrightness * atten * shadowed; - // Output - gl_FragColor = lightinfoCondition( lightColor.rgb * lightBrightness, - Sat_NL_Att, - specular, - previousPix ) * lightMapParams; + float Sat_NL_Att = saturate( nDotL * atten * shadowed ) * lightBrightness; + vec3 lightColorOut = lightMapParams.rgb * lightColor.rgb; + vec4 addToResult = vec4(0.0); + + // TODO: This needs to be removed when lightmapping is disabled + // as its extra work per-pixel on dynamic lit scenes. + // + // Special lightmapping pass. + if ( lightMapParams.a < 0.0 ) + { + // This disables shadows on the backsides of objects. + shadowed = nDotL < 0.0f ? 1.0f : shadowed; + + Sat_NL_Att = 1.0f; + shadowed = mix( 1.0f, shadowed, atten ); + lightColorOut = vec3(shadowed); + specular *= lightBrightness; + addToResult = ( 1.0 - shadowed ) * abs(lightMapParams); + } + + OUT_FragColor0 = lightinfoCondition( lightColorOut, Sat_NL_Att, specular, addToResult ); } diff --git a/Templates/Empty/game/shaders/common/lighting/advanced/gl/vectorLightP.glsl b/Templates/Empty/game/shaders/common/lighting/advanced/gl/vectorLightP.glsl index bbd567fd0..0178c35ea 100644 --- a/Templates/Empty/game/shaders/common/lighting/advanced/gl/vectorLightP.glsl +++ b/Templates/Empty/game/shaders/common/lighting/advanced/gl/vectorLightP.glsl @@ -22,40 +22,32 @@ #include "../../../gl/hlslCompat.glsl" #include "shadergen:/autogenConditioners.h" +#include "farFrustumQuad.glsl" +#include "../../../gl/torque.glsl" +#include "../../../gl/lighting.glsl" #include "lightingUtils.glsl" #include "../../shadowMap/shadowMapIO_GLSL.h" +#include "softShadow.glsl" -varying vec2 uv0; -varying vec3 wsEyeRay; +in vec4 hpos; +in vec2 uv0; +in vec3 wsEyeRay; +in vec3 vsEyeRay; -uniform sampler2D prePassBuffer; -uniform sampler2D ShadowMap; +uniform sampler2D ShadowMap ; -#if TORQUE_SM >= 30 - - // Enables high quality soft shadow - // filtering for SM3.0 and above. - #define SOFTSHADOW_SM3 - - #include "softShadow.glsl" - -#else - - - +#ifdef USE_SSAO_MASK +uniform sampler2D ssaoMask ; +uniform vec4 rtParams2; #endif - + +uniform sampler2D prePassBuffer; uniform vec3 lightDirection; uniform vec4 lightColor; -uniform float lightBrightness; -uniform vec4 lightAmbient; -uniform vec4 lightTrilight; - -uniform vec3 eyePosWorld; - -uniform mat4 worldToLightProj; -uniform vec4 splitDistStart; -uniform vec4 splitDistEnd; +uniform float lightBrightness; +uniform vec4 lightAmbient; +uniform vec3 eyePosWorld; +uniform mat4x4 worldToLightProj; uniform vec4 scaleX; uniform vec4 scaleY; uniform vec4 offsetX; @@ -65,16 +57,12 @@ uniform vec4 atlasYOffset; uniform vec2 atlasScale; uniform vec4 zNearFarInvNearFar; uniform vec4 lightMapParams; - -uniform float constantSpecularPower; uniform vec2 fadeStartLength; uniform vec4 farPlaneScalePSSM; -uniform vec4 splitFade; uniform vec4 overDarkPSSM; uniform float shadowSoftness; - -void main() +void main() { // Sample/unpack the normal/z data vec4 prepassSample = prepassUncondition( prePassBuffer, uv0 ); @@ -83,148 +71,162 @@ void main() // Use eye ray to get ws pos vec4 worldPos = vec4(eyePosWorld + wsEyeRay * depth, 1.0f); - + // Get the light attenuation. float dotNL = dot(-lightDirection, normal); + + #ifdef PSSM_DEBUG_RENDER + vec3 debugColor = vec3(0); + #endif #ifdef NO_SHADOW // Fully unshadowed. float shadowed = 1.0; + #ifdef PSSM_DEBUG_RENDER + debugColor = vec3(1.0); + #endif + #else - + // Compute shadow map coordinate - vec4 pxlPosLightProj = worldToLightProj * worldPos; + vec4 pxlPosLightProj = tMul(worldToLightProj, worldPos); vec2 baseShadowCoord = pxlPosLightProj.xy / pxlPosLightProj.w; - - float distOffset = 0.0; - float shadowed = 0.0; - float fadeAmt = 0.0; - vec4 zDist = vec4(zNearFarInvNearFar.x + zNearFarInvNearFar.y * depth); - - // Calculate things dependant on the shadowmap split - for ( int i = 0; i < 2; i++ ) - { - float zDistSplit = zDist.x + distOffset; - vec4 mask0; - mask0.x = float(zDistSplit >= splitDistStart.x); - mask0.y = float(zDistSplit >= splitDistStart.y); - mask0.z = float(zDistSplit >= splitDistStart.z); - mask0.w = float(zDistSplit >= splitDistStart.w); + + // Distance to light, in shadowmap space + float distToLight = pxlPosLightProj.z / pxlPosLightProj.w; - vec4 mask1; - mask1.x = float(zDistSplit < splitDistEnd.x); - mask1.y = float(zDistSplit < splitDistEnd.y); - mask1.z = float(zDistSplit < splitDistEnd.z); - mask1.w = float(zDistSplit < splitDistEnd.w); + // Figure out which split to sample from. Basically, we compute the shadowmap sample coord + // for all of the splits and then check if its valid. + vec4 shadowCoordX = vec4( baseShadowCoord.x ); + vec4 shadowCoordY = vec4( baseShadowCoord.y ); + vec4 farPlaneDists = vec4( distToLight ); + shadowCoordX *= scaleX; + shadowCoordY *= scaleY; + shadowCoordX += offsetX; + shadowCoordY += offsetY; + farPlaneDists *= farPlaneScalePSSM; + + // If the shadow sample is within -1..1 and the distance + // to the light for this pixel is less than the far plane + // of the split, use it. + vec4 finalMask; + if ( shadowCoordX.x > -0.99 && shadowCoordX.x < 0.99 && + shadowCoordY.x > -0.99 && shadowCoordY.x < 0.99 && + farPlaneDists.x < 1.0 ) + finalMask = vec4(1, 0, 0, 0); + + else if ( shadowCoordX.y > -0.99 && shadowCoordX.y < 0.99 && + shadowCoordY.y > -0.99 && shadowCoordY.y < 0.99 && + farPlaneDists.y < 1.0 ) + finalMask = vec4(0, 1, 0, 0); + + else if ( shadowCoordX.z > -0.99 && shadowCoordX.z < 0.99 && + shadowCoordY.z > -0.99 && shadowCoordY.z < 0.99 && + farPlaneDists.z < 1.0 ) + finalMask = vec4(0, 0, 1, 0); - vec4 finalMask = mask0 * mask1; + else + finalMask = vec4(0, 0, 0, 1); - float splitFadeDist = dot( finalMask, splitFade ); - vec2 finalScale; - finalScale.x = dot(finalMask, scaleX); - finalScale.y = dot(finalMask, scaleY); + #ifdef PSSM_DEBUG_RENDER + if ( finalMask.x > 0 ) + debugColor += vec3( 1, 0, 0 ); + else if ( finalMask.y > 0 ) + debugColor += vec3( 0, 1, 0 ); + else if ( finalMask.z > 0 ) + debugColor += vec3( 0, 0, 1 ); + else if ( finalMask.w > 0 ) + debugColor += vec3( 1, 1, 0 ); + #endif - vec2 finalOffset; - finalOffset.x = dot(finalMask, offsetX); - finalOffset.y = dot(finalMask, offsetY); - - vec2 shadowCoord; - shadowCoord = baseShadowCoord * finalScale; - shadowCoord += finalOffset; + // Here we know what split we're sampling from, so recompute the texcoord location + // Yes, we could just use the result from above, but doing it this way actually saves + // shader instructions. + vec2 finalScale; + finalScale.x = dot(finalMask, scaleX); + finalScale.y = dot(finalMask, scaleY); - // Convert to texcoord space - shadowCoord = 0.5 * shadowCoord + vec2(0.5, 0.5); - //shadowCoord.y = 1.0f - shadowCoord.y; + vec2 finalOffset; + finalOffset.x = dot(finalMask, offsetX); + finalOffset.y = dot(finalMask, offsetY); - // Move around inside of atlas - vec2 aOffset; - aOffset.x = dot(finalMask, atlasXOffset); - aOffset.y = dot(finalMask, atlasYOffset); + vec2 shadowCoord; + shadowCoord = baseShadowCoord * finalScale; + shadowCoord += finalOffset; - shadowCoord *= atlasScale; - shadowCoord += aOffset; - - // Distance to light, in shadowmap space - float distToLight = pxlPosLightProj.z / pxlPosLightProj.w; - - // Each split has a different far plane, take this into account. - float farPlaneScale = dot( farPlaneScalePSSM, finalMask ); - distToLight *= farPlaneScale; - - #ifdef SOFTSHADOW_SM3 + // Convert to texcoord space + shadowCoord = 0.5 * shadowCoord + vec2(0.5, 0.5); + shadowCoord.y = 1.0f - shadowCoord.y; - float esmShadow = softShadow_filter( ShadowMap, - gTapRotationTex, - uv0.xy, - shadowCoord, - farPlaneScale * shadowSoftness, - distToLight, - dotNL, - dot( finalMask, overDarkPSSM ) ); - - #else // !SOFTSHADOW_SM3 + // Move around inside of atlas + vec2 aOffset; + aOffset.x = dot(finalMask, atlasXOffset); + aOffset.y = dot(finalMask, atlasYOffset); - float occluder = decodeShadowMap( texture2DLod( ShadowMap, shadowCoord, 0.0 ) ); - float overDark = dot( finalMask, overDarkPSSM ); - float esmShadow = saturate( exp( esmFactor * ( occluder - distToLight ) ) ); - - #endif - - if ( i == 0 ) - { - float endDist = dot(splitDistEnd, finalMask); - fadeAmt = smoothstep(endDist - splitFadeDist, endDist, zDist).x; - shadowed = esmShadow * ( 1.0 - fadeAmt ); - } - else - shadowed += esmShadow * fadeAmt; - - distOffset += splitFadeDist; - } + shadowCoord *= atlasScale; + shadowCoord += aOffset; + + // Each split has a different far plane, take this into account. + float farPlaneScale = dot( farPlaneScalePSSM, finalMask ); + distToLight *= farPlaneScale; + + float shadowed = softShadow_filter( ShadowMap, + uv0.xy, + shadowCoord, + farPlaneScale * shadowSoftness, + distToLight, + dotNL, + dot( finalMask, overDarkPSSM ) ); // Fade out the shadow at the end of the range. + vec4 zDist = vec4(zNearFarInvNearFar.x + zNearFarInvNearFar.y * depth); float fadeOutAmt = ( zDist.x - fadeStartLength.x ) * fadeStartLength.y; - shadowed = mix( shadowed, 1.0, clamp( fadeOutAmt, 0.0, 1.0 ) ); + shadowed = mix( shadowed, 1.0, saturate( fadeOutAmt ) ); + + #ifdef PSSM_DEBUG_RENDER + if ( fadeOutAmt > 1.0 ) + debugColor = vec3(1.0); + #endif #endif // !NO_SHADOW - - // Calc lighting coefficents - float specular = calcSpecular( -lightDirection, - normal, - normalize(-wsEyeRay), - constantSpecularPower, - shadowed * lightBrightness ); - - float Sat_NL_Att = clamp(dotNL, 0.0, 1.0) * shadowed; - - // Trilight, described by Tom Forsyth - // http://home.comcast.net/~tom_forsyth/papers/trilight/trilight.html -#ifdef ACCUMULATE_LUV - // In LUV multiply in the brightness of the light color (normaly done in the attenuate function) - Sat_NL_Att *= lightColor.a; + // Specular term + float specular = AL_CalcSpecular( -lightDirection, + normal, + normalize(-vsEyeRay) ) * lightBrightness * shadowed; - vec4 ambientBlend = lightAmbient; - ambientBlend.b *= clamp(-dotNL, 0.0, 1.0); - - vec3 trilight = lightTrilight.rgb; - trilight.b *= clamp(1.0 - abs(dotNL), 0.0, 1.0); - - ambientBlend.rg = mix(ambientBlend.rg, trilight.rg, clamp(0.5 * trilight.b / lightAmbient.b, 0.0, 1.0)); - ambientBlend.b += trilight.b; + float Sat_NL_Att = saturate( dotNL * shadowed ) * lightBrightness; + vec3 lightColorOut = lightMapParams.rgb * lightColor.rgb; + vec4 addToResult = lightAmbient; -#else + // TODO: This needs to be removed when lightmapping is disabled + // as its extra work per-pixel on dynamic lit scenes. + // + // Special lightmapping pass. + if ( lightMapParams.a < 0.0 ) + { + // This disables shadows on the backsides of objects. + shadowed = dotNL < 0.0f ? 1.0f : shadowed; - // RGB - // TODO: Trilight seems broken... it does lighting in shadows! - //vec4 ambientBlend = vec4(lightTrilight.rgb * clamp(1.0 - abs(dotNL), 0.0, 1.0) + lightAmbient.rgb * clamp(-dotNL, 0.0, 1.0), 0.0); - vec4 ambientBlend = vec4(lightAmbient.rgb, 0.0); + Sat_NL_Att = 1.0f; + lightColorOut = vec3(shadowed); + specular *= lightBrightness; + addToResult = ( 1.0 - shadowed ) * abs(lightMapParams); + } -#endif + // Sample the AO texture. + #ifdef USE_SSAO_MASK + float ao = 1.0 - texture( ssaoMask, viewportCoordToRenderTarget( uv0.xy, rtParams2 ) ).r; + addToResult *= ao; + #endif + + #ifdef PSSM_DEBUG_RENDER + lightColorOut = debugColor; + #endif + + OUT_FragColor0 = lightinfoCondition( lightColorOut, Sat_NL_Att, specular, addToResult ); - // Output - gl_FragColor = lightinfoCondition( lightColor.rgb * lightBrightness, Sat_NL_Att, specular, ambientBlend) * lightMapParams; } diff --git a/Templates/Empty/game/shaders/common/lighting/basic/gl/shadowFilterP.glsl b/Templates/Empty/game/shaders/common/lighting/basic/gl/shadowFilterP.glsl index 238721e5e..4e97fa347 100644 --- a/Templates/Empty/game/shaders/common/lighting/basic/gl/shadowFilterP.glsl +++ b/Templates/Empty/game/shaders/common/lighting/basic/gl/shadowFilterP.glsl @@ -20,35 +20,27 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- +#include "../../../gl/hlslCompat.glsl" + uniform sampler2D diffuseMap; -varying vec2 uv; +in vec2 uv; uniform vec2 oneOverTargetSize; +const float offset[3] = float[]( 0.0, 1.3846153846, 3.2307692308 ); +const float weight[3] = float[]( 0.2270270270, 0.3162162162, 0.0702702703 ); + void main() { - vec2 sNonUniformTaps[8]; - - sNonUniformTaps[0] = vec2(0.992833, 0.979309); - sNonUniformTaps[1] = vec2(-0.998585, 0.985853); - sNonUniformTaps[2] = vec2(0.949299, -0.882562); - sNonUniformTaps[3] = vec2(-0.941358, -0.893924); - sNonUniformTaps[4] = vec2(0.545055, -0.589072); - sNonUniformTaps[5] = vec2(0.346526, 0.385821); - sNonUniformTaps[6] = vec2(-0.260183, 0.334412); - sNonUniformTaps[7] = vec2(0.248676, -0.679605); + vec4 OUT = texture( diffuseMap, uv ) * weight[0]; - gl_FragColor = vec4(0.0); - - vec2 texScale = vec2(1.0); - - for ( int i=0; i < 4; i++ ) + for ( int i=1; i < 3; i++ ) { - vec2 offset = (oneOverTargetSize * texScale) * sNonUniformTaps[i]; - gl_FragColor += texture2D( diffuseMap, uv + offset ); + vec2 _sample = (BLUR_DIR * offset[i]) * oneOverTargetSize; + OUT += texture( diffuseMap, uv + _sample ) * weight[i]; + OUT += texture( diffuseMap, uv - _sample ) * weight[i]; } - - gl_FragColor /= vec4(4.0); - gl_FragColor.rgb = vec3(0.0); + + OUT_FragColor0 = OUT; } diff --git a/Templates/Empty/game/shaders/common/lighting/basic/gl/shadowFilterV.glsl b/Templates/Empty/game/shaders/common/lighting/basic/gl/shadowFilterV.glsl index cbf3696be..0eeb2e0fd 100644 --- a/Templates/Empty/game/shaders/common/lighting/basic/gl/shadowFilterV.glsl +++ b/Templates/Empty/game/shaders/common/lighting/basic/gl/shadowFilterV.glsl @@ -22,13 +22,16 @@ #include "../../../../../../shaders/common/gl/torque.glsl" -uniform vec2 oneOverTargetSize; +in vec4 vPosition; +in vec2 vTexCoord0; + uniform vec4 rtParams0; -varying vec2 uv; +out vec2 uv; void main() { - gl_Position = gl_Vertex; - uv = viewportCoordToRenderTarget( gl_MultiTexCoord0.st, rtParams0 ); + gl_Position = vPosition; + uv = viewportCoordToRenderTarget( vTexCoord0.st, rtParams0 ); + gl_Position.y *= -1; //correct ssp } diff --git a/Templates/Empty/game/shaders/common/lighting/shadowMap/gl/boxFilterP.glsl b/Templates/Empty/game/shaders/common/lighting/shadowMap/gl/boxFilterP.glsl index 2800a3f17..0f568c716 100644 --- a/Templates/Empty/game/shaders/common/lighting/shadowMap/gl/boxFilterP.glsl +++ b/Templates/Empty/game/shaders/common/lighting/shadowMap/gl/boxFilterP.glsl @@ -26,7 +26,7 @@ uniform sampler2D diffuseMap0; uniform float texSize; uniform vec2 blurDimension; -varying vec2 tex0; +in vec2 tex0; void main() { @@ -40,8 +40,8 @@ void main() vec4 accum = vec4(0.0, 0.0, 0.0, 0.0); for(int i = 0; i < int(blurSamples); i++) { - accum += texture2D(diffuseMap0, BaseTexCoord + float(i) * SampleOffset); + accum += texture(diffuseMap0, BaseTexCoord + float(i) * SampleOffset); } accum /= blurSamples; - gl_FragColor = accum; + OUT_FragColor0 = accum; } \ No newline at end of file diff --git a/Templates/Empty/game/shaders/common/lighting/shadowMap/gl/boxFilterV.glsl b/Templates/Empty/game/shaders/common/lighting/shadowMap/gl/boxFilterV.glsl index 3850f83c7..9fc436f6c 100644 --- a/Templates/Empty/game/shaders/common/lighting/shadowMap/gl/boxFilterV.glsl +++ b/Templates/Empty/game/shaders/common/lighting/shadowMap/gl/boxFilterV.glsl @@ -20,12 +20,15 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- +in vec4 vPosition; +in vec2 vTexCoord0; + uniform mat4 modelview; -varying vec2 tex0; +out vec2 tex0; void main() { - gl_Position = modelview * gl_Vertex; - tex0 = gl_MultiTexCoord0.st; + gl_Position = modelview * vPosition; + tex0 = vTexCoord0.st; } \ No newline at end of file diff --git a/Templates/Empty/game/shaders/common/postFx/postFxV.glsl b/Templates/Empty/game/shaders/common/postFx/postFxV.glsl index 3aded2e0f..96a5ec819 100644 --- a/Templates/Empty/game/shaders/common/postFx/postFxV.glsl +++ b/Templates/Empty/game/shaders/common/postFx/postFxV.glsl @@ -22,27 +22,30 @@ #include "./../gl/torque.glsl" +in vec4 vPosition; +in vec2 vTexCoord0; +in vec3 vTexCoord1; uniform vec4 rtParams0; uniform vec4 rtParams1; uniform vec4 rtParams2; uniform vec4 rtParams3; -varying vec2 uv0; -varying vec2 uv1; -varying vec2 uv2; -varying vec2 uv3; -varying vec3 wsEyeRay; +out vec2 uv0; +out vec2 uv1; +out vec2 uv2; +out vec2 uv3; +out vec3 wsEyeRay; void main() { - gl_Position = gl_Vertex; + gl_Position = vPosition; - uv0 = viewportCoordToRenderTarget( gl_MultiTexCoord0.st, rtParams0 ); - uv1 = viewportCoordToRenderTarget( gl_MultiTexCoord0.st, rtParams1 ); - uv2 = viewportCoordToRenderTarget( gl_MultiTexCoord0.st, rtParams2 ); - uv3 = viewportCoordToRenderTarget( gl_MultiTexCoord0.st, rtParams3 ); + uv0 = viewportCoordToRenderTarget( vTexCoord0, rtParams0 ); + uv1 = viewportCoordToRenderTarget( vTexCoord0, rtParams1 ); + uv2 = viewportCoordToRenderTarget( vTexCoord0, rtParams2 ); + uv3 = viewportCoordToRenderTarget( vTexCoord0, rtParams3 ); - wsEyeRay = gl_MultiTexCoord1.xyz; + wsEyeRay = vTexCoord1; } diff --git a/Templates/Empty/game/shaders/common/terrain/gl/blendP.glsl b/Templates/Empty/game/shaders/common/terrain/gl/blendP.glsl index 3817e1de2..a2e4af787 100644 --- a/Templates/Empty/game/shaders/common/terrain/gl/blendP.glsl +++ b/Templates/Empty/game/shaders/common/terrain/gl/blendP.glsl @@ -23,8 +23,10 @@ #include "../terrain.glsl" #include "../../gl/hlslCompat.glsl" -varying vec2 layerCoord; -varying vec2 texCoord; +in vec2 layerCoord; +#define IN_layerCoord layerCoord +in vec2 texCoord; +#define IN_texCoord texCoord uniform sampler2D layerTex; uniform sampler2D textureMap; @@ -33,12 +35,12 @@ uniform float layerSize; void main() { - vec4 layerSample = round(texture2D( layerTex, layerCoord ) * 255.0); + vec4 layerSample = round(texture( layerTex, IN_layerCoord ) * 255.0); - float blend = calcBlend( texId, layerCoord, layerSize, layerSample ); + float blend = calcBlend( texId, IN_layerCoord, layerSize, layerSample ); if(blend - 0.0001 < 0.0) discard; - gl_FragColor = vec4( texture2D( textureMap, texCoord ).rgb, blend ); + OUT_FragColor0 = vec4( texture( textureMap, IN_texCoord ).rgb, blend ); } diff --git a/Templates/Empty/game/shaders/common/terrain/gl/blendV.glsl b/Templates/Empty/game/shaders/common/terrain/gl/blendV.glsl index 44362085b..dc7b7befa 100644 --- a/Templates/Empty/game/shaders/common/terrain/gl/blendV.glsl +++ b/Templates/Empty/game/shaders/common/terrain/gl/blendV.glsl @@ -23,14 +23,19 @@ /// The vertex shader used in the generation and caching of the /// base terrain texture. -varying vec2 layerCoord; -varying vec2 texCoord; +in vec4 vPosition; +in vec2 vTexCoord0; + +out vec2 layerCoord; +out vec2 texCoord; uniform vec2 texScale; void main() { - gl_Position = vec4(gl_Vertex.xyz, 1.0); - layerCoord = gl_MultiTexCoord0.st; - texCoord = gl_MultiTexCoord0.st * texScale; + gl_Position = vec4(vPosition.xyz, 1.0); + layerCoord = vTexCoord0.st; + texCoord = vTexCoord0.st * texScale; + + gl_Position.y *= -1; } diff --git a/Templates/Empty/game/shaders/common/water/gl/waterBasicP.glsl b/Templates/Empty/game/shaders/common/water/gl/waterBasicP.glsl index 72232622a..44207dea9 100644 --- a/Templates/Empty/game/shaders/common/water/gl/waterBasicP.glsl +++ b/Templates/Empty/game/shaders/common/water/gl/waterBasicP.glsl @@ -31,7 +31,7 @@ #define FRESNEL_BIAS miscParams[0] #define FRESNEL_POWER miscParams[1] #define CLARITY miscParams[2] -#define ISRIVER miscParams[3] +#define ISRIVER miscParams[3] // reflectParams #define REFLECT_PLANE_Z reflectParams[0] @@ -45,40 +45,49 @@ #define DISTORT_FULL_DEPTH distortionParams[2] // ConnectData.misc -#define LIGHT_VEC misc.xyz -#define WORLD_Z objPos.w +#define LIGHT_VEC IN_misc.xyz +#define WORLD_Z IN_objPos.w // specularParams #define SPEC_POWER specularParams[3] #define SPEC_COLOR specularParams.xyz +//----------------------------------------------------------------------------- +// Defines +//----------------------------------------------------------------------------- + // TexCoord 0 and 1 (xy,zw) for ripple texture lookup -varying vec4 rippleTexCoord01; +in vec4 rippleTexCoord01; +#define IN_rippleTexCoord01 rippleTexCoord01 // TexCoord 2 for ripple texture lookup -varying vec2 rippleTexCoord2; +in vec2 rippleTexCoord2; +#define IN_rippleTexCoord2 rippleTexCoord2 // Screenspace vert position BEFORE wave transformation -varying vec4 posPreWave; +in vec4 posPreWave; +#define IN_posPreWave posPreWave // Screenspace vert position AFTER wave transformation -varying vec4 posPostWave; +in vec4 posPostWave; +#define IN_posPostWave posPostWave // Worldspace unit distance/depth of this vertex/pixel -varying float pixelDist; - -// Objectspace vert position BEFORE wave transformation -// w coord is world space z position. -varying vec4 objPos; +in float pixelDist; +#define IN_pixelDist pixelDist -varying vec3 misc; +in vec4 objPos; +#define IN_objPos objPos + +in vec3 misc; +#define IN_misc misc //----------------------------------------------------------------------------- // approximate Fresnel function //----------------------------------------------------------------------------- float fresnel(float NdotV, float bias, float power) { - return bias + (1.0-bias)*pow(abs(1.0 - max(NdotV, 0.0)), power); + return bias + (1.0-bias)*pow(abs(1.0 - max(NdotV, 0)), power); } //----------------------------------------------------------------------------- @@ -89,7 +98,7 @@ uniform sampler2D bumpMap; uniform sampler2D reflectMap; uniform sampler2D refractBuff; uniform samplerCube skyMap; -//uniform sampler foamMap; +//uniform sampler2D foamMap; uniform vec4 baseColor; uniform vec4 miscParams; uniform vec4 reflectParams; @@ -98,8 +107,9 @@ uniform vec3 eyePos; uniform vec3 distortionParams; uniform vec3 fogData; uniform vec4 fogColor; -uniform vec3 rippleMagnitude; +uniform vec4 rippleMagnitude; uniform vec4 specularParams; +uniform mat4 modelMat; //----------------------------------------------------------------------------- // Main @@ -107,31 +117,35 @@ uniform vec4 specularParams; void main() { // Modulate baseColor by the ambientColor. - vec4 waterBaseColor = baseColor * vec4( ambientColor.rgb, 1.0 ); + vec4 waterBaseColor = baseColor * vec4( ambientColor.rgb, 1 ); // Get the bumpNorm... - vec3 bumpNorm = ( texture2D( bumpMap, rippleTexCoord01.xy ).rgb * 2.0 - 1.0 ) * rippleMagnitude.x; - bumpNorm += ( texture2D( bumpMap, rippleTexCoord01.zw ).rgb * 2.0 - 1.0 ) * rippleMagnitude.y; - bumpNorm += ( texture2D( bumpMap, rippleTexCoord2 ).rgb * 2.0 - 1.0 ) * rippleMagnitude.z; - + vec3 bumpNorm = ( texture( bumpMap, IN_rippleTexCoord01.xy ).rgb * 2.0 - 1.0 ) * rippleMagnitude.x; + bumpNorm += ( texture( bumpMap, IN_rippleTexCoord01.zw ).rgb * 2.0 - 1.0 ) * rippleMagnitude.y; + bumpNorm += ( texture( bumpMap, IN_rippleTexCoord2 ).rgb * 2.0 - 1.0 ) * rippleMagnitude.z; + + bumpNorm = normalize( bumpNorm ); + bumpNorm = mix( bumpNorm, vec3(0,0,1), 1.0 - rippleMagnitude.w ); + // We subtract a little from it so that we don't // distort where the water surface intersects the // camera near plane. - float distortAmt = saturate( pixelDist / 1.0 ) * 0.8; + float distortAmt = saturate( IN_pixelDist / 1.0 ) * 0.8; - vec4 distortPos = posPostWave; + vec4 distortPos = IN_posPostWave; distortPos.xy += bumpNorm.xy * distortAmt; #ifdef UNDERWATER - gl_FragColor = texture2DProj( refractBuff, distortPos.xyz ); + OUT_FragColor0 = hdrEncode( textureProj( refractBuff, distortPos ) ); #else - vec3 eyeVec = objPos.xyz - eyePos; - vec3 reflectionVec = reflect( eyeVec, normalize(bumpNorm) ); + vec3 eyeVec = IN_objPos.xyz - eyePos; + eyeVec = tMul( mat3(modelMat), eyeVec ); + vec3 reflectionVec = reflect( eyeVec, bumpNorm ); // Color that replaces the reflection color when we do not // have one that is appropriate. - vec4 fakeColor = vec4(ambientColor,1.0); + vec4 fakeColor = vec4(ambientColor,1); // Use fakeColor for ripple-normals that are angled towards the camera eyeVec = -eyeVec; @@ -140,58 +154,61 @@ void main() float fakeColorAmt = ang; // Get reflection map color - vec4 refMapColor = texture2DProj( reflectMap, distortPos ); + vec4 refMapColor = hdrDecode( textureProj( reflectMap, distortPos ) ); // If we do not have a reflection texture then we use the cubemap. - refMapColor = mix( refMapColor, textureCube( skyMap, -reflectionVec ), NO_REFLECT ); + refMapColor = mix( refMapColor, texture( skyMap, reflectionVec ), NO_REFLECT ); // Combine reflection color and fakeColor. vec4 reflectColor = mix( refMapColor, fakeColor, fakeColorAmt ); //return refMapColor; // Get refract color - vec4 refractColor = texture2DProj( refractBuff, distortPos.xyz ); + vec4 refractColor = hdrDecode( textureProj( refractBuff, distortPos ) ); // calc "diffuse" color by lerping from the water color // to refraction image based on the water clarity. - vec4 diffuseColor = mix( refractColor, waterBaseColor, 1.0 - CLARITY ); + vec4 diffuseColor = mix( refractColor, waterBaseColor, 1.0f - CLARITY ); // fresnel calculation float fresnelTerm = fresnel( ang, FRESNEL_BIAS, FRESNEL_POWER ); + //return vec4( fresnelTerm.rrr, 1 ); // Also scale the frensel by our distance to the // water surface. This removes the hard reflection // when really close to the water surface. - fresnelTerm *= saturate( pixelDist - 0.1 ); + fresnelTerm *= saturate( IN_pixelDist - 0.1 ); // Combine the diffuse color and reflection image via the // fresnel term and set out output color. - gl_FragColor = mix( diffuseColor, reflectColor, fresnelTerm ); - + vec4 OUT = mix( diffuseColor, reflectColor, fresnelTerm ); + #ifdef WATER_SPEC // Get some specular reflection. vec3 newbump = bumpNorm; newbump.xy *= 3.5; newbump = normalize( bumpNorm ); - vec3 halfAng = normalize( eyeVec + -LIGHT_VEC ); + half3 halfAng = normalize( eyeVec + -LIGHT_VEC ); float specular = saturate( dot( newbump, halfAng ) ); specular = pow( specular, SPEC_POWER ); - gl_FragColor.rgb = gl_FragColor.rgb + ( SPEC_COLOR * specular.xxx ); + OUT.rgb = OUT.rgb + ( SPEC_COLOR * specular.xxx ); #else // Disable fogging if spec is on because otherwise we run out of instructions. // Fog it. float factor = computeSceneFog( eyePos, - objPos.xyz, + IN_objPos.xyz, WORLD_Z, fogData.x, fogData.y, fogData.z ); - gl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor.rgb, 1.0 - saturate( factor ) ); - - #endif + //OUT.rgb = mix( OUT.rgb, fogColor.rgb, 1.0 - saturate( factor ) ); + #endif + + OUT_FragColor0 = OUT; + #endif } diff --git a/Templates/Empty/game/shaders/common/water/gl/waterBasicV.glsl b/Templates/Empty/game/shaders/common/water/gl/waterBasicV.glsl index bb2a0c954..1634fd2de 100644 --- a/Templates/Empty/game/shaders/common/water/gl/waterBasicV.glsl +++ b/Templates/Empty/game/shaders/common/water/gl/waterBasicV.glsl @@ -27,23 +27,30 @@ //----------------------------------------------------------------------------- // TexCoord 0 and 1 (xy,zw) for ripple texture lookup -varying vec4 rippleTexCoord01; +out vec4 rippleTexCoord01; +#define OUT_rippleTexCoord01 rippleTexCoord01 // TexCoord 2 for ripple texture lookup -varying vec2 rippleTexCoord2; +out vec2 rippleTexCoord2; +#define OUT_rippleTexCoord2 rippleTexCoord2 // Screenspace vert position BEFORE wave transformation -varying vec4 posPreWave; +out vec4 posPreWave; +#define OUT_posPreWave posPreWave // Screenspace vert position AFTER wave transformation -varying vec4 posPostWave; +out vec4 posPostWave; +#define OUT_posPostWave posPostWave // Worldspace unit distance/depth of this vertex/pixel -varying float pixelDist; +out float pixelDist; +#define OUT_pixelDist pixelDist -varying vec4 objPos; +out vec4 objPos; +#define OUT_objPos objPos -varying vec3 misc; +out vec3 misc; +#define OUT_misc misc //----------------------------------------------------------------------------- // Uniforms @@ -63,49 +70,56 @@ uniform float gridElementSize; uniform float elapsedTime; uniform float undulateMaxDist; +in vec4 vPosition; +in vec3 vNormal; +in vec4 vColor; +in vec2 vTexCoord0; +in vec4 vTexCoord1; + //----------------------------------------------------------------------------- // Main //----------------------------------------------------------------------------- void main() { - vec4 position = gl_Vertex; - vec3 normal = gl_Normal; - vec2 undulateData = gl_MultiTexCoord0.st; - vec4 horizonFactor = gl_MultiTexCoord1; + vec4 IN_position = vPosition; + vec3 IN_normal = vNormal; + vec2 IN_undulateData = vTexCoord0; + vec4 IN_horizonFactor = vTexCoord1; + vec4 OUT_hpos = vec4(0); // use projection matrix for reflection / refraction texture coords - mat4 texGen = mat4(0.5, 0.0, 0.0, 0.0, - 0.0, 0.5, 0.0, 0.0, - 0.0, 0.0, 1.0, 0.0, - 0.5, 0.5, 0.0, 1.0); + mat4 texGen = mat4FromRow( 0.5, 0.0, 0.0, 0.5, + 0.0, -0.5, 0.0, 0.5, + 0.0, 0.0, 1.0, 0.0, + 0.0, 0.0, 0.0, 1.0 ); // Move the vertex based on the horizonFactor if specified to do so for this vert. - //if ( horizonFactor.z > 0.0 ) - //{ - //vec2 offsetXY = eyePos.xy - mod(eyePos.xy, gridElementSize); - //position.xy += offsetXY; - //undulateData += offsetXY; - //} + // if ( IN_horizonFactor.z > 0 ) + // { + // vec2 offsetXY = eyePos.xy - eyePos.xy % gridElementSize; + // IN_position.xy += offsetXY; + // IN_undulateData += offsetXY; + // } - vec4 worldPos = modelMat * position; - //fogPos = position.xyz; - position.z = mix( position.z, eyePos.z, horizonFactor.x ); - - objPos.xyz = position.xyz; - objPos.w = worldPos.z; + vec4 worldPos = tMul( modelMat, IN_position ); + + IN_position.z = mix( IN_position.z, eyePos.z, IN_horizonFactor.x ); + + //OUT_objPos = worldPos; + OUT_objPos.xyz = IN_position.xyz; + OUT_objPos.w = worldPos.z; // Send pre-undulation screenspace position - posPreWave = modelview * position; - posPreWave = texGen * posPreWave; + OUT_posPreWave = tMul( modelview, IN_position ); + OUT_posPreWave = tMul( texGen, OUT_posPreWave ); // Calculate the undulation amount for this vertex. - vec2 undulatePos = (modelMat * vec4( undulateData.xy, 0, 1 )).xy; - - //if ( undulatePos.x < 0.0 ) - //undulatePos = position.xy; - - float undulateAmt = 0.0; + vec2 undulatePos = tMul( modelMat, vec4( IN_undulateData.xy, 0, 1 ) ).xy; + //if ( undulatePos.x < 0 ) + // undulatePos = IN_position.xy; + float undulateAmt = 0.0; + undulateAmt += waveData[0].y * sin( elapsedTime * waveData[0].x + undulatePos.x * waveDir[0].x + undulatePos.y * waveDir[0].y ); @@ -114,118 +128,84 @@ void main() undulatePos.y * waveDir[1].y ); undulateAmt += waveData[2].y * sin( elapsedTime * waveData[2].x + undulatePos.x * waveDir[2].x + - undulatePos.y * waveDir[2].y ); - - float undulateFade = 1.0; - - // Scale down wave magnitude amount based on distance from the camera. - float dist = length( position.xyz - eyePos ); + undulatePos.y * waveDir[2].y ); + + float undulateFade = 1; + + // Scale down wave magnitude amount based on distance from the camera. + float dist = distance( IN_position.xyz, eyePos ); dist = clamp( dist, 1.0, undulateMaxDist ); - undulateFade *= ( 1.0 - dist / undulateMaxDist ); + undulateFade *= ( 1 - dist / undulateMaxDist ); // Also scale down wave magnitude if the camera is very very close. - undulateFade *= saturate( ( length( position.xyz - eyePos ) - 0.5 ) / 10.0 ); - + undulateFade *= saturate( ( distance( IN_position.xyz, eyePos ) - 0.5 ) / 10.0 ); + undulateAmt *= undulateFade; + //#endif //undulateAmt = 0; // Apply wave undulation to the vertex. - posPostWave = position; - posPostWave.xyz += normal.xyz * undulateAmt; + OUT_posPostWave = IN_position; + OUT_posPostWave.xyz += IN_normal.xyz * undulateAmt; // Save worldSpace position of this pixel/vert - //worldPos = posPostWave.xyz; + //OUT_worldPos = OUT_posPostWave.xyz; + //OUT_worldPos = tMul( modelMat, OUT_posPostWave.xyz ); + //OUT_worldPos.z += objTrans[2][2]; //91.16; - //worldSpaceZ = ( modelMat * vec4(fogPos,1.0) ).z; - //if ( horizonFactor.x > 0.0 ) - //{ - //vec3 awayVec = normalize( fogPos.xyz - eyePos ); - //fogPos.xy += awayVec.xy * 1000.0; - //} + // OUT_misc.w = tMul( modelMat, OUT_fogPos ).z; + // if ( IN_horizonFactor.x > 0 ) + // { + // vec3 awayVec = normalize( OUT_fogPos.xyz - eyePos ); + // OUT_fogPos.xy += awayVec.xy * 1000.0; + // } // Convert to screen - posPostWave = modelview * posPostWave; + OUT_posPostWave = tMul( modelview, OUT_posPostWave ); // tMul( modelview, vec4( OUT_posPostWave.xyz, 1 ) ); // Setup the OUT position symantic variable - gl_Position = posPostWave; - //gl_Position.z = mix(gl_Position.z, gl_Position.w, horizonFactor.x); + OUT_hpos = OUT_posPostWave; // tMul( modelview, vec4( IN_position.xyz, 1 ) ); //vec4( OUT_posPostWave.xyz, 1 ); + //OUT_hpos.z = mix( OUT_hpos.z, OUT_hpos.w, IN_horizonFactor.x ); // Save world space camera dist/depth of the outgoing pixel - pixelDist = gl_Position.z; + OUT_pixelDist = OUT_hpos.z; // Convert to reflection texture space - posPostWave = texGen * posPostWave; + OUT_posPostWave = tMul( texGen, OUT_posPostWave ); vec2 txPos = undulatePos; - if ( horizonFactor.x > 0.0 ) + if ( bool(IN_horizonFactor.x) ) txPos = normalize( txPos ) * 50000.0; - - - // set up tex coordinates for the 3 interacting normal maps - rippleTexCoord01.xy = txPos * rippleTexScale[0]; - rippleTexCoord01.xy += rippleDir[0] * elapsedTime * rippleSpeed.x; + + // set up tex coordinates for the 3 interacting normal maps + OUT_rippleTexCoord01.xy = txPos * rippleTexScale[0]; + OUT_rippleTexCoord01.xy += rippleDir[0] * elapsedTime * rippleSpeed.x; mat2 texMat; texMat[0][0] = rippleMat[0].x; texMat[1][0] = rippleMat[0].y; texMat[0][1] = rippleMat[0].z; texMat[1][1] = rippleMat[0].w; - rippleTexCoord01.xy = texMat * rippleTexCoord01.xy ; + OUT_rippleTexCoord01.xy = tMul( texMat, OUT_rippleTexCoord01.xy ); - rippleTexCoord01.zw = txPos * rippleTexScale[1]; - rippleTexCoord01.zw += rippleDir[1] * elapsedTime * rippleSpeed.y; + OUT_rippleTexCoord01.zw = txPos * rippleTexScale[1]; + OUT_rippleTexCoord01.zw += rippleDir[1] * elapsedTime * rippleSpeed.y; texMat[0][0] = rippleMat[1].x; texMat[1][0] = rippleMat[1].y; texMat[0][1] = rippleMat[1].z; texMat[1][1] = rippleMat[1].w; - rippleTexCoord01.zw = texMat * rippleTexCoord01.zw ; + OUT_rippleTexCoord01.zw = tMul( texMat, OUT_rippleTexCoord01.zw ); - rippleTexCoord2.xy = txPos * rippleTexScale[2]; - rippleTexCoord2.xy += rippleDir[2] * elapsedTime * rippleSpeed.z; + OUT_rippleTexCoord2.xy = txPos * rippleTexScale[2]; + OUT_rippleTexCoord2.xy += rippleDir[2] * elapsedTime * rippleSpeed.z; texMat[0][0] = rippleMat[2].x; texMat[1][0] = rippleMat[2].y; texMat[0][1] = rippleMat[2].z; texMat[1][1] = rippleMat[2].w; - rippleTexCoord2.xy = texMat * rippleTexCoord2.xy ; - - - /*rippleTexCoord01.xy = mix( position.xy * rippleTexScale[0], txPos.xy * rippleTexScale[0], horizonFactor.x ); - rippleTexCoord01.xy += rippleDir[0] * elapsedTime * rippleSpeed.x; - - rippleTexCoord01.zw = mix( position.xy * rippleTexScale[1], txPos.xy * rippleTexScale[1], horizonFactor.x ); - rippleTexCoord01.zw += rippleDir[1] * elapsedTime * rippleSpeed.y; - - rippleTexCoord2.xy = mix( position.xy * rippleTexScale[2], txPos.xy * rippleTexScale[2], horizonFactor.x ); - rippleTexCoord2.xy += rippleDir[2] * elapsedTime * rippleSpeed.z; */ - - - /*rippleTexCoord01.xy = mix( position.xy * rippleTexScale[0], txPos.xy * rippleTexScale[0], horizonFactor.x ); - rippleTexCoord01.xy += rippleDir[0] * elapsedTime * rippleSpeed.x; - mat2 texMat; - texMat[0][0] = rippleMat[0].x; - texMat[1][0] = rippleMat[0].y; - texMat[0][1] = rippleMat[0].z; - texMat[1][1] = rippleMat[0].w; - rippleTexCoord01.xy = texMat * rippleTexCoord01.xy ; - - rippleTexCoord01.zw = mix( position.xy * rippleTexScale[1], txPos.xy * rippleTexScale[1], horizonFactor.x ); - rippleTexCoord01.zw += rippleDir[1] * elapsedTime * rippleSpeed.y; - texMat[0][0] = rippleMat[1].x; - texMat[1][0] = rippleMat[1].y; - texMat[0][1] = rippleMat[1].z; - texMat[1][1] = rippleMat[1].w; - rippleTexCoord01.zw = texMat * rippleTexCoord01.zw ; - - rippleTexCoord2.xy = mix( position.xy * rippleTexScale[2], txPos.xy * rippleTexScale[2], horizonFactor.x ); - rippleTexCoord2.xy += rippleDir[2] * elapsedTime * rippleSpeed.z; - texMat[0][0] = rippleMat[2].x; - texMat[1][0] = rippleMat[2].y; - texMat[0][1] = rippleMat[2].z; - texMat[1][1] = rippleMat[2].w; - rippleTexCoord2.xy = texMat * rippleTexCoord2.xy ;*/ + OUT_rippleTexCoord2.xy = tMul( texMat, OUT_rippleTexCoord2.xy ); #ifdef WATER_SPEC @@ -234,8 +214,8 @@ void main() vec3 normal; for ( int i = 0; i < 3; i++ ) { - binormal.z += undulateFade * waveDir[i].x * waveData[i].y * cos( waveDir[i].x * undulateData.x + waveDir[i].y * undulateData.y + elapsedTime * waveData[i].x ); - tangent.z += undulateFade * waveDir[i].y * waveData[i].y * cos( waveDir[i].x * undulateData.x + waveDir[i].y * undulateData.y + elapsedTime * waveData[i].x ); + binormal.z += undulateFade * waveDir[i].x * waveData[i].y * cos( waveDir[i].x * IN_undulateData.x + waveDir[i].y * IN_undulateData.y + elapsedTime * waveData[i].x ); + tangent.z += undulateFade * waveDir[i].y * waveData[i].y * cos( waveDir[i].x * IN_undulateData.x + waveDir[i].y * IN_undulateData.y + elapsedTime * waveData[i].x ); } binormal = normalize( binormal ); @@ -246,15 +226,19 @@ void main() worldToTangent[0] = binormal; worldToTangent[1] = tangent; worldToTangent[2] = normal; + + worldToTangent = transpose(worldToTangent); - misc.xyz = inLightVec * modelMat; - misc.xyz = worldToTangent * misc.xyz; + OUT_misc.xyz = tMul( inLightVec, modelMat ); + OUT_misc.xyz = tMul( worldToTangent, OUT_misc.xyz ); #else - misc.xyz = inLightVec; - + OUT_misc.xyz = inLightVec; + #endif - + + gl_Position = OUT_hpos; + correctSSP(gl_Position); } diff --git a/Templates/Empty/game/shaders/common/water/gl/waterP.glsl b/Templates/Empty/game/shaders/common/water/gl/waterP.glsl index bf482d724..3e15fe576 100644 --- a/Templates/Empty/game/shaders/common/water/gl/waterP.glsl +++ b/Templates/Empty/game/shaders/common/water/gl/waterP.glsl @@ -20,6 +20,7 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- +#include "../../gl/hlslCompat.glsl" #include "shadergen:/autogenConditioners.h" #include "../../gl/torque.glsl" @@ -27,10 +28,7 @@ // Defines //----------------------------------------------------------------------------- -#ifdef TORQUE_BASIC_LIGHTING - #define BASIC -#endif - +#define PIXEL_DIST IN_rippleTexCoord2.z // miscParams #define FRESNEL_BIAS miscParams[0] #define FRESNEL_POWER miscParams[1] @@ -57,33 +55,54 @@ #define DISTORT_FULL_DEPTH distortionParams[2] // foamParams -#define FOAM_SCALE foamParams[0] +#define FOAM_OPACITY foamParams[0] #define FOAM_MAX_DEPTH foamParams[1] +#define FOAM_AMBIENT_LERP foamParams[2] +#define FOAM_RIPPLE_INFLUENCE foamParams[3] -// Incoming data -// Worldspace position of this pixel -varying vec3 worldPos; +// specularParams +#define SPEC_POWER specularParams[3] +#define SPEC_COLOR specularParams.xyz + +//----------------------------------------------------------------------------- +// Structures +//----------------------------------------------------------------------------- + +//ConnectData IN + +in vec4 hpos; // TexCoord 0 and 1 (xy,zw) for ripple texture lookup -varying vec4 rippleTexCoord01; +in vec4 rippleTexCoord01; -// TexCoord 2 for ripple texture lookup -varying vec2 rippleTexCoord2; +// xy is TexCoord 2 for ripple texture lookup +// z is the Worldspace unit distance/depth of this vertex/pixel +// w is amount of the crestFoam ( more at crest of waves ). +in vec4 rippleTexCoord2; // Screenspace vert position BEFORE wave transformation -varying vec4 posPreWave; +in vec4 posPreWave; // Screenspace vert position AFTER wave transformation -varying vec4 posPostWave; +in vec4 posPostWave; -// Worldspace unit distance/depth of this vertex/pixel -varying float pixelDist; +// Objectspace vert position BEFORE wave transformation +// w coord is world space z position. +in vec4 objPos; -varying vec3 fogPos; +in vec4 foamTexCoords; -varying float worldSpaceZ; +in mat3 tangentMat; -varying vec4 foamTexCoords; + +#define IN_hpos hpos +#define IN_rippleTexCoord01 rippleTexCoord01 +#define IN_rippleTexCoord2 rippleTexCoord2 +#define IN_posPreWave posPreWave +#define IN_posPostWave posPostWave +#define IN_objPos objPos +#define IN_foamTexCoords foamTexCoords +#define IN_tangentMat tangentMat //----------------------------------------------------------------------------- // approximate Fresnel function @@ -100,10 +119,10 @@ uniform sampler2D bumpMap; uniform sampler2D prepassTex; uniform sampler2D reflectMap; uniform sampler2D refractBuff; -uniform samplerCUBE skyMap; +uniform samplerCube skyMap; uniform sampler2D foamMap; -uniform vec4 specularColor; -uniform float specularPower; +uniform sampler1D depthGradMap; +uniform vec4 specularParams; uniform vec4 baseColor; uniform vec4 miscParams; uniform vec2 fogParams; @@ -112,64 +131,45 @@ uniform vec3 reflectNormal; uniform vec2 wetnessParams; uniform float farPlaneDist; uniform vec3 distortionParams; -//uniform vec4 renderTargetParams; -uniform vec2 foamParams; -uniform vec3 foamColorMod; +uniform vec4 foamParams; uniform vec3 ambientColor; -uniform vec3 eyePos; -uniform vec3 inLightVec; +uniform vec3 eyePos; // This is in object space! uniform vec3 fogData; uniform vec4 fogColor; -//uniform vec4 rtParams; -uniform vec2 rtScale; -uniform vec2 rtHalfPixel; -uniform vec4 rtOffset; -uniform vec3 rippleMagnitude; +uniform vec4 rippleMagnitude; +uniform vec4 rtParams1; +uniform float depthGradMax; +uniform vec3 inLightVec; +uniform mat4 modelMat; +uniform vec4 sunColor; +uniform float sunBrightness; +uniform float reflectivity; //----------------------------------------------------------------------------- // Main //----------------------------------------------------------------------------- void main() { - vec4 rtParams = vec4( rtOffset.x / rtOffset.z + rtHalfPixel.x, - rtOffset.y / rtOffset.w + rtHalfPixel.x, - rtScale ); - - // Modulate baseColor by the ambientColor. - vec4 waterBaseColor = baseColor * vec4( ambientColor.rgb, 1 ); - // Get the bumpNorm... - vec3 bumpNorm = ( tex2D( bumpMap, IN.rippleTexCoord01.xy ) * 2.0 - 1.0 ) * rippleMagnitude.x; - bumpNorm += ( tex2D( bumpMap, IN.rippleTexCoord01.zw ) * 2.0 - 1.0 ) * rippleMagnitude.y; - bumpNorm += ( tex2D( bumpMap, IN.rippleTexCoord2 ) * 2.0 - 1.0 ) * rippleMagnitude.z; - - // JCF: this was here, but seems to make the dot product against the bump - // normal we use below for cubeMap fade-in to be less reliable. - //bumpNorm.xy *= 0.75; - //bumpNorm = normalize( bumpNorm ); - //return vec4( bumpNorm, 1 ); + vec3 bumpNorm = ( texture( bumpMap, IN_rippleTexCoord01.xy ).rgb * 2.0 - 1.0 ) * rippleMagnitude.x; + bumpNorm += ( texture( bumpMap, IN_rippleTexCoord01.zw ).rgb * 2.0 - 1.0 ) * rippleMagnitude.y; + bumpNorm += ( texture( bumpMap, IN_rippleTexCoord2.xy ).rgb * 2.0 - 1.0 ) * rippleMagnitude.z; + + bumpNorm = normalize( bumpNorm ); + bumpNorm = mix( bumpNorm, vec3(0,0,1), 1.0 - rippleMagnitude.w ); + bumpNorm = tMul( bumpNorm, IN_tangentMat ); // Get depth of the water surface (this pixel). // Convert from WorldSpace to EyeSpace. - float pixelDepth = IN.pixelDist / farPlaneDist; + float pixelDepth = PIXEL_DIST / farPlaneDist; - // Get prepass depth at the undistorted pixel. - //vec4 prepassCoord = IN.posPostWave; - //prepassCoord.xy += renderTargetParams.xy; - vec2 prepassCoord = viewportCoordToRenderTarget( IN.posPostWave, rtParams ); - //vec2 prepassCoord = IN.posPostWave.xy; + vec2 prepassCoord = viewportCoordToRenderTarget( IN_posPostWave, rtParams1 ); - float startDepth = prepassUncondition( tex2D( prepassTex, prepassCoord ) ).w; - //return vec4( startDepth.rrr, 1 ); + float startDepth = prepassUncondition( prepassTex, prepassCoord ).w; // The water depth in world units of the undistorted pixel. float startDelta = ( startDepth - pixelDepth ); - if ( startDelta <= 0.0 ) - { - //return vec4( 1, 0, 0, 1 ); - startDelta = 0; - } - + startDelta = max( startDelta, 0.0 ); startDelta *= farPlaneDist; // Calculate the distortion amount for the water surface. @@ -177,23 +177,22 @@ void main() // We subtract a little from it so that we don't // distort where the water surface intersects the // camera near plane. - float distortAmt = saturate( ( IN.pixelDist - DISTORT_START_DIST ) / DISTORT_END_DIST ); + float distortAmt = saturate( ( PIXEL_DIST - DISTORT_START_DIST ) / DISTORT_END_DIST ); // Scale down distortion in shallow water. distortAmt *= saturate( startDelta / DISTORT_FULL_DEPTH ); - //distortAmt = 0; // Do the intial distortion... we might remove it below. vec2 distortDelta = bumpNorm.xy * distortAmt; - vec4 distortPos = IN.posPostWave; + vec4 distortPos = IN_posPostWave; distortPos.xy += distortDelta; - prepassCoord = viewportCoordToRenderTarget( distortPos, rtParams ); - //prepassCoord = distortPos; - //prepassCoord.xy += renderTargetParams.xy; + prepassCoord = viewportCoordToRenderTarget( distortPos, rtParams1 ); // Get prepass depth at the position of this distorted pixel. - float prepassDepth = prepassUncondition( tex2D( prepassTex, prepassCoord ) ).w; + float prepassDepth = prepassUncondition( prepassTex, prepassCoord ).w; + if ( prepassDepth > 0.99 ) + prepassDepth = 5.0; float delta = ( prepassDepth - pixelDepth ) * farPlaneDist; @@ -202,7 +201,7 @@ void main() // If we got a negative delta then the distorted // sample is above the water surface. Mask it out // by removing the distortion. - distortPos = IN.posPostWave; + distortPos = IN_posPostWave; delta = startDelta; distortAmt = 0; } @@ -212,20 +211,20 @@ void main() if ( diff < 0 ) { - distortAmt = saturate( ( IN.pixelDist - DISTORT_START_DIST ) / DISTORT_END_DIST ); + distortAmt = saturate( ( PIXEL_DIST - DISTORT_START_DIST ) / DISTORT_END_DIST ); distortAmt *= saturate( delta / DISTORT_FULL_DEPTH ); distortDelta = bumpNorm.xy * distortAmt; - distortPos = IN.posPostWave; + distortPos = IN_posPostWave; distortPos.xy += distortDelta; - prepassCoord = viewportCoordToRenderTarget( distortPos, rtParams ); - //prepassCoord = distortPos; - //prepassCoord.xy += renderTargetParams.xy; + prepassCoord = viewportCoordToRenderTarget( distortPos, rtParams1 ); // Get prepass depth at the position of this distorted pixel. - prepassDepth = prepassUncondition( tex2D( prepassTex, prepassCoord ) ).w; + prepassDepth = prepassUncondition( prepassTex, prepassCoord ).w; + if ( prepassDepth > 0.99 ) + prepassDepth = 5.0; delta = ( prepassDepth - pixelDepth ) * farPlaneDist; } @@ -234,133 +233,78 @@ void main() // If we got a negative delta then the distorted // sample is above the water surface. Mask it out // by removing the distortion. - distortPos = IN.posPostWave; + distortPos = IN_posPostWave; delta = startDelta; distortAmt = 0; } } - //return vec4( prepassDepth.rrr, 1 ); - - vec4 temp = IN.posPreWave; + vec4 temp = IN_posPreWave; temp.xy += bumpNorm.xy * distortAmt; - vec2 reflectCoord = viewportCoordToRenderTarget( temp, rtParams ); + vec2 reflectCoord = viewportCoordToRenderTarget( temp, rtParams1 ); - vec2 refractCoord = viewportCoordToRenderTarget( distortPos, rtParams ); + vec2 refractCoord = viewportCoordToRenderTarget( distortPos, rtParams1 ); - // Use cubemap colors instead of reflection colors in several cases... - - // First lookup the CubeMap color - // JCF: which do we want to use here, the reflectNormal or the bumpNormal - // neithor of them is exactly right and how can we combine the two together? - //bumpNorm = reflectNormal; - vec3 eyeVec = IN.worldPos - eyePos; + vec4 fakeColor = vec4(ambientColor,1); + vec3 eyeVec = IN_objPos.xyz - eyePos; + eyeVec = tMul( mat3(modelMat), eyeVec ); + eyeVec = tMul( IN_tangentMat, eyeVec ); vec3 reflectionVec = reflect( eyeVec, bumpNorm ); - //vec4 cubeColor = texCUBE( skyMap, reflectionVec ); - //return cubeColor; - // JCF: using ambient color instead of cubeColor for waterPlane, how do we still use the cubemap for rivers? - vec4 cubeColor = vec4(ambientColor,1); - //cubeColor.rgb = vec3( 0, 0, 1 ); - // Use cubeColor for waves that are angled towards camera + // Use fakeColor for ripple-normals that are angled towards the camera eyeVec = -eyeVec; eyeVec = normalize( eyeVec ); float ang = saturate( dot( eyeVec, bumpNorm ) ); - float cubeAmt = ang; + float fakeColorAmt = ang; - //float rplaneDist = (reflectPlane.x * IN.pos.x + reflectPlane.y * IN.pos.y + reflectPlane.z * IN.pos.z) + reflectPlane.w; - //rplaneDist = saturate( abs( rplaneDist ) / 0.5 ); - - -//#ifdef RIVER // for verts far from the reflect plane z position - float rplaneDist = abs( REFLECT_PLANE_Z - IN.worldPos.z ); + float rplaneDist = abs( REFLECT_PLANE_Z - IN_objPos.w ); rplaneDist = saturate( ( rplaneDist - 1.0 ) / 2.0 ); - //rplaneDist = REFLECT_PLANE_Z / eyePos.z; rplaneDist *= ISRIVER; - cubeAmt = max( cubeAmt, rplaneDist ); -//#endif - - //rplaneDist = IN.worldPos.z / eyePos.z; - - //return vec4( rplaneDist.rrr, 1 ); - //return vec4( (reflectParams[REFLECT_PLANE_Z] / 86.0 ).rrr, 1 ); - - // and for verts farther from the camera - //float cubeAmt = ( eyeDist - reflectParams[REFLECT_MIN_DIST] ) / ( reflectParams[REFLECT_MAX_DIST] - reflectParams[REFLECT_MIN_DIST] ); - //cubeAmt = saturate ( cubeAmt ); - - //float temp = ( eyeDist - reflectParams[REFLECT_MIN_DIST] ) / ( reflectParams[REFLECT_MAX_DIST] - reflectParams[REFLECT_MIN_DIST] ); - //temp = saturate ( temp ); - - // If the camera is very very close to the reflect plane. - //float eyeToPlaneDist = eyePos.z - REFLECT_PLANE_Z; // dot( reflectNormal, eyePos ) + REFLECT_PLANE_Z; - //eyeToPlaneDist = abs( eyeToPlaneDist ); - //eyeToPlaneDist = 1.0 - saturate( abs( eyeToPlaneDist ) / 1 ); - - //return vec4( eyeToPlaneDist.rrr, 1 ); - - //cubeAmt = max( cubeAmt, eyeToPlaneDist ); - //cubeAmt = max( cubeAmt, rplaneDist ); - //cubeAmt = max( cubeAmt, ang ); - //cubeAmt = max( cubeAmt, rplaneDist ); - //cubeAmt = max( cubeAmt, IN.depth.w ); - - // All cubemap if fullReflect is specifically user disabled - cubeAmt = max( cubeAmt, NO_REFLECT ); + fakeColorAmt = max( fakeColorAmt, rplaneDist ); #ifndef UNDERWATER - // Get foam color and amount - IN.foamTexCoords.xy += distortDelta * 0.5; - IN.foamTexCoords.zw += distortDelta * 0.5; + vec2 foamRippleOffset = bumpNorm.xy * FOAM_RIPPLE_INFLUENCE; + vec4 IN_foamTexCoords = IN_foamTexCoords; + IN_foamTexCoords.xy += foamRippleOffset; + IN_foamTexCoords.zw += foamRippleOffset; - vec4 foamColor = tex2D( foamMap, IN.foamTexCoords.xy ); - foamColor += tex2D( foamMap, IN.foamTexCoords.zw ); - //foamColor += tex2D( foamMap, IN.rippleTexCoord2 ) * 0.3; + vec4 foamColor = texture( foamMap, IN_foamTexCoords.xy ); + foamColor += texture( foamMap, IN_foamTexCoords.zw ); foamColor = saturate( foamColor ); - // Modulate foam color by ambient color so we don't have glowing white - // foam at night. - foamColor.rgb = lerp( foamColor.rgb, ambientColor.rgb, foamColorMod.rgb ); + + // Modulate foam color by ambient color + // so we don't have glowing white foam at night. + foamColor.rgb = mix( foamColor.rgb, ambientColor.rgb, FOAM_AMBIENT_LERP ); float foamDelta = saturate( delta / FOAM_MAX_DEPTH ); - float foamAmt = 1.0 - foamDelta; + float foamAmt = 1 - pow( foamDelta, 2 ); // Fade out the foam in very very low depth, // this improves the shoreline a lot. float diff = 0.8 - foamAmt; if ( diff < 0.0 ) - { - //return vec4( 1,0,0,1 ); foamAmt -= foamAmt * abs( diff ) / 0.2; - } - //return vec4( foamAmt.rrr, 1 ); - - foamAmt *= FOAM_SCALE * foamColor.a; - //return vec4( foamAmt.rrr, 1 ); - // Get reflection map color - vec4 refMapColor = tex2D( reflectMap, reflectCoord ); + foamAmt *= FOAM_OPACITY * foamColor.a; - //cubeAmt = 0; + foamColor.rgb *= FOAM_OPACITY * foamAmt * foamColor.a; - // Combine cube and foam colors into reflect color - vec4 reflectColor = lerp( refMapColor, cubeColor, cubeAmt ); - //return refMapColor; + // Get reflection map color. + vec4 refMapColor = hdrDecode( texture( reflectMap, reflectCoord ) ); - // This doesn't work because REFLECT_PLANE_Z is in worldSpace - // while eyePos is actually in objectSpace! + // If we do not have a reflection texture then we use the cubemap. + refMapColor = mix( refMapColor, texture( skyMap, reflectionVec ), NO_REFLECT ); - //float eyeToPlaneDist = eyePos.z - REFLECT_PLANE_Z; // dot( reflectNormal, eyePos ) + REFLECT_PLANE_Z; - //float transitionFactor = 1.0 - saturate( ( abs( eyeToPlaneDist ) - 0.5 ) / 5 ); - //reflectColor = lerp( reflectColor, waterBaseColor, transitionFactor ); - - //return reflectColor; + fakeColor = ( texture( skyMap, reflectionVec ) ); + fakeColor.a = 1; + // Combine reflection color and fakeColor. + vec4 reflectColor = mix( refMapColor, fakeColor, fakeColorAmt ); // Get refract color - vec4 refractColor = tex2D( refractBuff, refractCoord ); - //return refractColor; + vec4 refractColor = hdrDecode( texture( refractBuff, refractCoord ) ); // We darken the refraction color a bit to make underwater // elements look wet. We fade out this darkening near the @@ -371,86 +315,80 @@ void main() // Add Water fog/haze. float fogDelta = delta - FOG_DENSITY_OFFSET; - //return vec4( fogDelta.rrr, 1 ); + if ( fogDelta < 0.0 ) fogDelta = 0.0; float fogAmt = 1.0 - saturate( exp( -FOG_DENSITY * fogDelta ) ); - //return vec4( fogAmt.rrr, 1 ); + + // Calculate the water "base" color based on depth. + vec4 waterBaseColor = baseColor * texture( depthGradMap, saturate( delta / depthGradMax ) ); + + // Modulate baseColor by the ambientColor. + waterBaseColor *= vec4( ambientColor.rgb, 1 ); // calc "diffuse" color by lerping from the water color // to refraction image based on the water clarity. - vec4 diffuseColor = lerp( refractColor, waterBaseColor, fogAmt ); + vec4 diffuseColor = mix( refractColor, waterBaseColor, fogAmt ); // fresnel calculation float fresnelTerm = fresnel( ang, FRESNEL_BIAS, FRESNEL_POWER ); - //return vec4( fresnelTerm.rrr, 1 ); // Scale the frensel strength by fog amount // so that parts that are very clear get very little reflection. fresnelTerm *= fogAmt; - //return vec4( fresnelTerm.rrr, 1 ); // Also scale the frensel by our distance to the // water surface. This removes the hard reflection // when really close to the water surface. - fresnelTerm *= saturate( IN.pixelDist - 0.1 ); + fresnelTerm *= saturate( PIXEL_DIST - 0.1 ); + + fresnelTerm *= reflectivity; // Combine the diffuse color and reflection image via the // fresnel term and set out output color. - vec4 gl_FragColor = lerp( diffuseColor, reflectColor, fresnelTerm ); + vec4 OUT = mix( diffuseColor, reflectColor, fresnelTerm ); - //float brightness = saturate( 1.0 - ( waterHeight - eyePosWorld.z - 5.0 ) / 50.0 ); - //gl_FragColor.rgb *= brightness; + vec3 lightVec = inLightVec; + + // Get some specular reflection. + vec3 newbump = bumpNorm; + newbump.xy *= 3.5; + newbump = normalize( bumpNorm ); + vec3 halfAng = normalize( eyeVec + -lightVec ); + float specular = saturate( dot( newbump, halfAng ) ); + specular = pow( specular, SPEC_POWER ); + + // Scale down specularity in very shallow water to improve the transparency of the shoreline. + specular *= saturate( delta / 2 ); + OUT.rgb = OUT.rgb + ( SPEC_COLOR * vec3(specular) ); #else - vec4 refractColor = tex2D( refractBuff, refractCoord ); - vec4 gl_FragColor = refractColor; + + vec4 refractColor = hdrDecode( texture( refractBuff, refractCoord ) ); + vec4 OUT = refractColor; + #endif #ifndef UNDERWATER - gl_FragColor.rgb = lerp( gl_FragColor.rgb, foamColor.rgb, foamAmt ); -#endif - gl_FragColor.a = 1.0; - - // specular experiments - -// 1: -/* - float fDot = dot( bumpNorm, inLightVec ); - vec3 reflect = normalize( 2.0 * bumpNorm * fDot - eyeVec ); - // float specular = saturate(dot( reflect, inLightVec ) ); - float specular = pow( reflect, specularPower ); - gl_FragColor += specularColor * specular; -*/ - - -// 2: This almost looks good -/* - bumpNorm.xy *= 2.0; - bumpNorm = normalize( bumpNorm ); - - vec3 halfAng = normalize( eyeVec + inLightVec ); - float specular = saturate( dot( bumpNorm, halfAng) ); - specular = pow(specular, specularPower); - gl_FragColor += specularColor * specular; -*/ - -#ifndef UNDERWATER + OUT.rgb = OUT.rgb + foamColor.rgb; float factor = computeSceneFog( eyePos, - IN.fogPos, - IN.worldSpaceZ, + IN_objPos.xyz, + IN_objPos.w, fogData.x, fogData.y, fogData.z ); - gl_FragColor.rgb = lerp( gl_FragColor.rgb, fogColor.rgb, 1.0 - saturate( factor ) ); + OUT.rgb = mix( OUT.rgb, fogColor.rgb, 1.0 - saturate( factor ) ); + + //OUT.rgb = fogColor.rgb; #endif - //return vec4( refMapColor.rgb, 1 ); - gl_FragColor.a = 1.0; + OUT.a = 1.0; + + //return OUT; - return gl_FragColor; + OUT_FragColor0 = hdrEncode( OUT ); } diff --git a/Templates/Empty/game/shaders/common/water/gl/waterV.glsl b/Templates/Empty/game/shaders/common/water/gl/waterV.glsl index d4337476f..490af63a7 100644 --- a/Templates/Empty/game/shaders/common/water/gl/waterV.glsl +++ b/Templates/Empty/game/shaders/common/water/gl/waterV.glsl @@ -20,58 +20,86 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- +#include "../../gl/hlslCompat.glsl" #include "shadergen:/autogenConditioners.h" +//----------------------------------------------------------------------------- +// Structures +//----------------------------------------------------------------------------- +struct VertData +{ + vec4 position ;// POSITION; + vec3 normal ;// NORMAL; + vec2 undulateData ;// TEXCOORD0; + vec4 horizonFactor ;// TEXCOORD1; +}; + //----------------------------------------------------------------------------- // Defines //----------------------------------------------------------------------------- +//VertData IN +in vec4 vPosition; +in vec3 vNormal; +in vec2 vTexCoord0; +in vec4 vTexCoord1; -// waveData -#define WAVE_SPEED(i) waveData[i].x -#define WAVE_MAGNITUDE(i) waveData[i].y +#define IN_position_ vPosition +#define IN_normal vNormal +#define IN_undulateData vTexCoord0 +#define IN_horizonFactor vTexCoord1 -// Outgoing data -// Worldspace position of this pixel -varying vec3 worldPos; +//ConnectData OUT +// + out vec4 hpos ; // TexCoord 0 and 1 (xy,zw) for ripple texture lookup -varying vec4 rippleTexCoord01; +out vec4 rippleTexCoord01; -// TexCoord 2 for ripple texture lookup -varying vec2 rippleTexCoord2; + // xy is TexCoord 2 for ripple texture lookup + // z is the Worldspace unit distance/depth of this vertex/pixel + // w is amount of the crestFoam ( more at crest of waves ). + out vec4 rippleTexCoord2 ; // Screenspace vert position BEFORE wave transformation -varying vec4 posPreWave; +out vec4 posPreWave; // Screenspace vert position AFTER wave transformation -varying vec4 posPostWave; +out vec4 posPostWave; -// Worldspace unit distance/depth of this vertex/pixel -varying float pixelDist; + // Objectspace vert position BEFORE wave transformation + // w coord is world space z position. + out vec4 objPos ; -varying vec3 fogPos; + out vec4 foamTexCoords ; -varying float worldSpaceZ; + out mat3 tangentMat ; +// -varying vec4 foamTexCoords; +#define OUT_hpos hpos +#define OUT_rippleTexCoord01 rippleTexCoord01 +#define OUT_rippleTexCoord2 rippleTexCoord2 +#define OUT_posPreWave posPreWave +#define OUT_posPostWave posPostWave +#define OUT_objPos objPos +#define OUT_foamTexCoords foamTexCoords +#define OUT_tangentMat tangentMat //----------------------------------------------------------------------------- // Uniforms //----------------------------------------------------------------------------- uniform mat4 modelMat; uniform mat4 modelview; -uniform mat3 cubeTrans; -uniform mat4 objTrans; -uniform vec3 cubeEyePos; +uniform vec4 rippleMat[3]; uniform vec3 eyePos; uniform vec2 waveDir[3]; uniform vec2 waveData[3]; uniform vec2 rippleDir[3]; uniform vec2 rippleTexScale[3]; uniform vec3 rippleSpeed; -uniform vec2 reflectTexSize; +uniform vec4 foamDir; +uniform vec4 foamTexScale; +uniform vec2 foamSpeed; uniform vec3 inLightVec; -uniform vec3 reflectNormal; uniform float gridElementSize; uniform float elapsedTime; uniform float undulateMaxDist; @@ -81,97 +109,133 @@ uniform float undulateMaxDist; //----------------------------------------------------------------------------- void main() { - // Copy incoming attributes into locals so we can modify them in place. - vec4 position = gl_Vertex.xyzw; - vec3 normal = gl_Normal.xyz; - vec2 undulateData = gl_MultiTexCoord0.st; - vec4 horizonFactor = gl_MultiTexCoord1.xyzw; + vec4 IN_position = IN_position_; // use projection matrix for reflection / refraction texture coords - mat4 texGen = { 0.5, 0.0, 0.0, 0.5, //+ 0.5 / reflectTexSize.x, - 0.0, 0.5, 0.0, 0.5, //+ 1.0 / reflectTexSize.y, - 0.0, 0.0, 1.0, 0.0, - 0.0, 0.0, 0.0, 1.0 }; + mat4 texGen = mat4FromRow( 0.5, 0.0, 0.0, 0.5, + 0.0, -0.5, 0.0, 0.5, + 0.0, 0.0, 1.0, 0.0, + 0.0, 0.0, 0.0, 1.0 ); - // Move the vertex based on the horizonFactor if specified to do so for this vert. - if ( horizonFactor.z > 0 ) - { - vec2 offsetXY = eyePos.xy - eyePos.xy % gridElementSize; - position.xy += offsetXY; - undulateData += offsetXY; - } + IN_position.z = mix( IN_position.z, eyePos.z, IN_horizonFactor.x ); - fogPos = position; - position.z = mix( position.z, eyePos.z, horizonFactor.x ); + OUT_objPos = IN_position; + OUT_objPos.w = tMul( modelMat, IN_position ).z; // Send pre-undulation screenspace position - posPreWave = modelview * position; - posPreWave = texGen * posPreWave; + OUT_posPreWave = tMul( modelview, IN_position ); + OUT_posPreWave = tMul( texGen, OUT_posPreWave ); // Calculate the undulation amount for this vertex. - vec2 undulatePos = undulateData; - float undulateAmt = 0; + vec2 undulatePos = tMul( modelMat, vec4 ( IN_undulateData.xy, 0, 1 ) ).xy; + float undulateAmt = 0.0; - for ( int i = 0; i < 3; i++ ) - { - undulateAmt += WAVE_MAGNITUDE(i) * sin( elapsedTime * WAVE_SPEED(i) + - undulatePos.x * waveDir[i].x + - undulatePos.y * waveDir[i].y ); - } + undulateAmt += waveData[0].y * sin( elapsedTime * waveData[0].x + + undulatePos.x * waveDir[0].x + + undulatePos.y * waveDir[0].y ); + undulateAmt += waveData[1].y * sin( elapsedTime * waveData[1].x + + undulatePos.x * waveDir[1].x + + undulatePos.y * waveDir[1].y ); + undulateAmt += waveData[2].y * sin( elapsedTime * waveData[2].x + + undulatePos.x * waveDir[2].x + + undulatePos.y * waveDir[2].y ); + + float undulateFade = 1; // Scale down wave magnitude amount based on distance from the camera. - float dist = distance( position, eyePos ); + float dist = distance( IN_position.xyz, eyePos ); dist = clamp( dist, 1.0, undulateMaxDist ); - undulateAmt *= ( 1 - dist / undulateMaxDist ); + undulateFade *= ( 1 - dist / undulateMaxDist ); // Also scale down wave magnitude if the camera is very very close. - undulateAmt *= clamp( ( distance( IN.position, eyePos ) - 0.5 ) / 10.0, 0.0, 1.0 ); + undulateFade *= saturate( ( distance( IN_position.xyz, eyePos ) - 0.5 ) / 10.0 ); + + undulateAmt *= undulateFade; + + OUT_rippleTexCoord2.w = undulateAmt / ( waveData[0].y + waveData[1].y + waveData[2].y ); + OUT_rippleTexCoord2.w = saturate( OUT_rippleTexCoord2.w - 0.2 ) / 0.8; // Apply wave undulation to the vertex. - posPostWave = position; - posPostWave.xyz += normal.xyz * undulateAmt; - - // Save worldSpace position of this pixel/vert - worldPos = posPostWave.xyz; + OUT_posPostWave = IN_position; + OUT_posPostWave.xyz += IN_normal.xyz * undulateAmt; // Convert to screen - posPostWave = modelview * posPostWave; + OUT_posPostWave = tMul( modelview, OUT_posPostWave ); // Setup the OUT position symantic variable - gl_Position = posPostWave; - gl_Position.z = mix(gl_Position.z, gl_Position.w, horizonFactor.x); + OUT_hpos = OUT_posPostWave; + //OUT_hpos.z = mix( OUT_hpos.z, OUT_hpos.w, IN_horizonFactor.x ); - worldSpaceZ = modelMat * vec4(fogPos, 1.0) ).z; - if ( horizonFactor.x > 0.0 ) - { - vec3 awayVec = normalize( fogPos.xyz - eyePos ); - fogPos.xy += awayVec.xy * 1000.0; - } + // if ( IN_horizonFactor.x > 0 ) + // { + // vec3 awayVec = normalize( OUT_objPos.xyz - eyePos ); + // OUT_objPos.xy += awayVec.xy * 1000.0; + // } // Save world space camera dist/depth of the outgoing pixel - pixelDist = gl_Position.z; + OUT_rippleTexCoord2.z = OUT_hpos.z; // Convert to reflection texture space - posPostWave = texGen * posPostWave; + OUT_posPostWave = tMul( texGen, OUT_posPostWave ); - float2 ripplePos = undulateData; - float2 txPos = normalize( ripplePos ); - txPos *= 50000.0; - ripplePos = mix( ripplePos, txPos, IN.horizonFactor.x ); + vec2 txPos = undulatePos; + if ( bool(IN_horizonFactor.x) ) + txPos = normalize( txPos ) * 50000.0; // set up tex coordinates for the 3 interacting normal maps - rippleTexCoord01.xy = mix( ripplePos * rippleTexScale[0], txPos.xy * rippleTexScale[0], IN.horizonFactor.x ); - rippleTexCoord01.xy += rippleDir[0] * elapsedTime * rippleSpeed.x; + OUT_rippleTexCoord01.xy = txPos * rippleTexScale[0]; + OUT_rippleTexCoord01.xy += rippleDir[0] * elapsedTime * rippleSpeed.x; - rippleTexCoord01.zw = mix( ripplePos * rippleTexScale[1], txPos.xy * rippleTexScale[1], IN.horizonFactor.x ); - rippleTexCoord01.zw += rippleDir[1] * elapsedTime * rippleSpeed.y; + mat2 texMat; + texMat[0][0] = rippleMat[0].x; + texMat[1][0] = rippleMat[0].y; + texMat[0][1] = rippleMat[0].z; + texMat[1][1] = rippleMat[0].w; + OUT_rippleTexCoord01.xy = tMul( texMat, OUT_rippleTexCoord01.xy ); - rippleTexCoord2.xy = mix( ripplePos * rippleTexScale[2], txPos.xy * rippleTexScale[2], IN.horizonFactor.x ); - rippleTexCoord2.xy += rippleDir[2] * elapsedTime * rippleSpeed.z; + OUT_rippleTexCoord01.zw = txPos * rippleTexScale[1]; + OUT_rippleTexCoord01.zw += rippleDir[1] * elapsedTime * rippleSpeed.y; + + texMat[0][0] = rippleMat[1].x; + texMat[1][0] = rippleMat[1].y; + texMat[0][1] = rippleMat[1].z; + texMat[1][1] = rippleMat[1].w; + OUT_rippleTexCoord01.zw = tMul( texMat, OUT_rippleTexCoord01.zw ); - foamTexCoords.xy = mix( ripplePos * 0.2, txPos.xy * rippleTexScale[0], IN.horizonFactor.x ); - foamTexCoords.xy += rippleDir[0] * sin( ( elapsedTime + 500.0 ) * -0.4 ) * 0.15; + OUT_rippleTexCoord2.xy = txPos * rippleTexScale[2]; + OUT_rippleTexCoord2.xy += rippleDir[2] * elapsedTime * rippleSpeed.z; - foamTexCoords.zw = mix( ripplePos * 0.3, txPos.xy * rippleTexScale[1], IN.horizonFactor.x ); - foamTexCoords.zw += rippleDir[1] * sin( elapsedTime * 0.4 ) * 0.15; + texMat[0][0] = rippleMat[2].x; + texMat[1][0] = rippleMat[2].y; + texMat[0][1] = rippleMat[2].z; + texMat[1][1] = rippleMat[2].w; + OUT_rippleTexCoord2.xy = tMul( texMat, OUT_rippleTexCoord2.xy ); + + OUT_foamTexCoords.xy = txPos * foamTexScale.xy + foamDir.xy * foamSpeed.x * elapsedTime; + OUT_foamTexCoords.zw = txPos * foamTexScale.zw + foamDir.zw * foamSpeed.y * elapsedTime; + + + vec3 binormal = vec3 ( 1, 0, 0 ); + vec3 tangent = vec3 ( 0, 1, 0 ); + vec3 normal; + for ( int i = 0; i < 3; i++ ) + { + binormal.z += undulateFade * waveDir[i].x * waveData[i].y * cos( waveDir[i].x * undulatePos.x + waveDir[i].y * undulatePos.y + elapsedTime * waveData[i].x ); + tangent.z += undulateFade * waveDir[i].y * waveData[i].y * cos( waveDir[i].x * undulatePos.x + waveDir[i].y * undulatePos.y + elapsedTime * waveData[i].x ); + } + + binormal = binormal; + tangent = tangent; + normal = cross( binormal, tangent ); + + mat3 worldToTangent; + worldToTangent[0] = binormal; + worldToTangent[1] = tangent; + worldToTangent[2] = normal; + + OUT_tangentMat = transpose(worldToTangent); + + gl_Position = OUT_hpos; + correctSSP(gl_Position); } + diff --git a/Templates/Empty/game/tools/gui/profiles.ed.cs b/Templates/Empty/game/tools/gui/profiles.ed.cs index 8d6718601..b3a5b2295 100644 --- a/Templates/Empty/game/tools/gui/profiles.ed.cs +++ b/Templates/Empty/game/tools/gui/profiles.ed.cs @@ -764,7 +764,7 @@ singleton GuiControlProfile( GuiInspectorGroupProfile ) opaque = false; border = false; - bitmap = "tools/editorclasses/gui/images/rollout"; + bitmap = "tools/editorClasses/gui/images/rollout"; textOffset = "20 0"; diff --git a/Templates/Empty/game/tools/riverEditor/main.cs b/Templates/Empty/game/tools/riverEditor/main.cs index b51bd5273..eafb3c3c8 100644 --- a/Templates/Empty/game/tools/riverEditor/main.cs +++ b/Templates/Empty/game/tools/riverEditor/main.cs @@ -25,8 +25,8 @@ function initializeRiverEditor() echo(" % - Initializing River Editor"); exec( "./riverEditor.cs" ); - exec( "./riverEditorGui.gui" ); - exec( "./riverEditorToolbar.gui" ); + exec( "./RiverEditorGui.gui" ); + exec( "./RiverEditorToolbar.gui" ); exec( "./riverEditorGui.cs" ); // Add ourselves to EditorGui, where all the other tools reside diff --git a/Templates/Empty/game/tools/roadEditor/main.cs b/Templates/Empty/game/tools/roadEditor/main.cs index cb7ea052c..f45823670 100644 --- a/Templates/Empty/game/tools/roadEditor/main.cs +++ b/Templates/Empty/game/tools/roadEditor/main.cs @@ -25,8 +25,8 @@ function initializeRoadEditor() echo( " - Initializing Road and Path Editor" ); exec( "./roadEditor.cs" ); - exec( "./roadEditorGui.gui" ); - exec( "./roadEditorToolbar.gui"); + exec( "./RoadEditorGui.gui" ); + exec( "./RoadEditorToolbar.gui"); exec( "./roadEditorGui.cs" ); // Add ourselves to EditorGui, where all the other tools reside diff --git a/Templates/Empty/game/tools/shapeEditor/gui/Profiles.ed.cs b/Templates/Empty/game/tools/shapeEditor/gui/Profiles.ed.cs index 0b92a30e2..cb42ef169 100644 --- a/Templates/Empty/game/tools/shapeEditor/gui/Profiles.ed.cs +++ b/Templates/Empty/game/tools/shapeEditor/gui/Profiles.ed.cs @@ -41,7 +41,7 @@ singleton GuiControlProfile(GuiShapeEdTextListProfile : ToolsGuiTextListProfile) singleton GuiControlProfile(GuiShapeEdRolloutProfile : GuiInspectorRolloutProfile0) { - bitmap = "tools/editorclasses/gui/images/rollout"; + bitmap = "tools/editorClasses/gui/images/rollout"; category = "Editor"; }; diff --git a/Templates/Empty/game/tools/shapeEditor/main.cs b/Templates/Empty/game/tools/shapeEditor/main.cs index f033bae86..721313e95 100644 --- a/Templates/Empty/game/tools/shapeEditor/main.cs +++ b/Templates/Empty/game/tools/shapeEditor/main.cs @@ -33,7 +33,7 @@ function initializeShapeEditor() exec("./gui/shapeEdPreviewWindow.ed.gui"); exec("./gui/shapeEdAnimWindow.ed.gui"); exec("./gui/shapeEdAdvancedWindow.ed.gui"); - exec("./gui/shapeEditorToolbar.ed.gui"); + exec("./gui/ShapeEditorToolbar.ed.gui"); exec("./gui/shapeEdSelectWindow.ed.gui"); exec("./gui/shapeEdPropWindow.ed.gui"); diff --git a/Templates/Empty/game/tools/worldEditor/main.cs b/Templates/Empty/game/tools/worldEditor/main.cs index 1b20201e0..773dbac17 100644 --- a/Templates/Empty/game/tools/worldEditor/main.cs +++ b/Templates/Empty/game/tools/worldEditor/main.cs @@ -29,7 +29,7 @@ function initializeWorldEditor() exec("./scripts/cursors.ed.cs"); exec("./gui/guiCreateNewTerrainGui.gui" ); - exec("./gui/genericPromptDialog.ed.gui" ); + exec("./gui/GenericPromptDialog.ed.gui" ); exec("./gui/guiTerrainImportGui.gui" ); exec("./gui/guiTerrainExportGui.gui" ); exec("./gui/EditorGui.ed.gui"); diff --git a/Templates/Empty/source/torqueConfig.h b/Templates/Empty/source/torqueConfig.h index d9de1b1d1..e18b00f63 100644 --- a/Templates/Empty/source/torqueConfig.h +++ b/Templates/Empty/source/torqueConfig.h @@ -148,6 +148,13 @@ /// texture manager. #define TORQUE_FRAME_SIZE 16 << 20 +// Default keyboard layout for launching the game. It's fixed crash when a +// game running with the extend unicode keyboard (cyrillic, for example). +// Windows only. +// @see For choice language > +// http://msdn.microsoft.com/en-us/library/windows/desktop/dd318693%28v=vs.85%29.aspx +#define TORQUE_DEFAULT_KEYBOARD_LAYOUT LANG_ENGLISH + // Finally, we define some dependent #defines. This enables some subsidiary // functionality to get automatically turned on in certain configurations. diff --git a/Templates/Full/buildFiles/config/torque3D_dedicated.conf b/Templates/Full/buildFiles/config/torque3D_dedicated.conf index eecf2fc4f..ec0b6281d 100644 --- a/Templates/Full/buildFiles/config/torque3D_dedicated.conf +++ b/Templates/Full/buildFiles/config/torque3D_dedicated.conf @@ -60,14 +60,14 @@ addProjectDependency( 'libbullet' ); } - if ( Generator::$platform == "mac" ) + if ( T3D_Generator::$platform == "mac" ) { addProjectDefine( '__MACOSX__' ); addProjectDefine( 'LTM_DESC' ); } - if (Generator::$platform == "win32") + if (T3D_Generator::$platform == "win32") { setProjectModuleDefinitionFile('../../' . getLibSrcDir() . 'Torque3D/msvc/torque3d.def'); diff --git a/Templates/Full/game/art/datablocks/weapons/grenadefx.cs b/Templates/Full/game/art/datablocks/weapons/grenadefx.cs index 473cd81b8..2db50a5bd 100644 --- a/Templates/Full/game/art/datablocks/weapons/grenadefx.cs +++ b/Templates/Full/game/art/datablocks/weapons/grenadefx.cs @@ -893,7 +893,7 @@ datablock ProjectileData(GrenadeLauncherProjectile) explosion = GrenadeLauncherExplosion; waterExplosion = GrenadeLauncherWaterExplosion; - decal = ExpBlastDecal; + decal = ScorchRXDecal; splash = GrenadeSplash; particleEmitter = GrenadeProjSmokeTrailEmitter; diff --git a/Templates/Full/game/core/scripts/gui/messageBoxes/messageBox.ed.cs b/Templates/Full/game/core/scripts/gui/messageBoxes/messageBox.ed.cs index d778ae7ee..7c970c341 100644 --- a/Templates/Full/game/core/scripts/gui/messageBoxes/messageBox.ed.cs +++ b/Templates/Full/game/core/scripts/gui/messageBoxes/messageBox.ed.cs @@ -42,8 +42,8 @@ if( isObject( IODropdownDlg ) ) exec("./messageBoxOk.ed.gui"); exec("./messageBoxYesNo.ed.gui"); exec("./messageBoxYesNoCancel.ed.gui"); -exec("./messageBoxOKCancel.ed.gui"); -exec("./messageBoxOKCancelDetailsDlg.ed.gui"); +exec("./messageBoxOkCancel.ed.gui"); +exec("./MessageBoxOKCancelDetailsDlg.ed.gui"); exec("./messagePopup.ed.gui"); exec("./IODropdownDlg.ed.gui"); diff --git a/Templates/Full/game/main.cs.in b/Templates/Full/game/main.cs.in new file mode 100644 index 000000000..db8436e7d --- /dev/null +++ b/Templates/Full/game/main.cs.in @@ -0,0 +1,280 @@ +//----------------------------------------------------------------------------- +// Copyright (c) 2012 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. +//----------------------------------------------------------------------------- + +// Set the name of our application +$appName = "@TORQUE_APP_NAME@"; + +// The directory it is run from +$defaultGame = "scripts"; + +// Set profile directory +$Pref::Video::ProfilePath = "core/profile"; + +function createCanvas(%windowTitle) +{ + if ($isDedicated) + { + GFXInit::createNullDevice(); + return true; + } + + // Create the Canvas + %foo = new GuiCanvas(Canvas); + + // Set the window title + if (isObject(Canvas)) + Canvas.setWindowTitle(getEngineName() @ " - " @ $appName); + + return true; +} + +// Display the optional commandline arguements +$displayHelp = false; + +// Use these to record and play back crashes +//saveJournal("editorOnFileQuitCrash.jrn"); +//playJournal("editorOnFileQuitCrash.jrn", false); + +//------------------------------------------------------------------------------ +// Check if a script file exists, compiled or not. +function isScriptFile(%path) +{ + if( isFile(%path @ ".dso") || isFile(%path) ) + return true; + + return false; +} + +//------------------------------------------------------------------------------ +// Process command line arguments +exec("core/parseArgs.cs"); + +$isDedicated = false; +$dirCount = 2; +$userDirs = $defaultGame @ ";art;levels"; + +// load tools scripts if we're a tool build +if (isToolBuild()) + $userDirs = "tools;" @ $userDirs; + + +// Parse the executable arguments with the standard +// function from core/main.cs +defaultParseArgs(); + + +if($dirCount == 0) { + $userDirs = $defaultGame; + $dirCount = 1; +} + +//----------------------------------------------------------------------------- +// Display a splash window immediately to improve app responsiveness before +// engine is initialized and main window created +if (!$isDedicated) + displaySplashWindow(); + + +//----------------------------------------------------------------------------- +// The displayHelp, onStart, onExit and parseArgs function are overriden +// by mod packages to get hooked into initialization and cleanup. + +function onStart() +{ + // Default startup function +} + +function onExit() +{ + // OnExit is called directly from C++ code, whereas onStart is + // invoked at the end of this file. +} + +function parseArgs() +{ + // Here for mod override, the arguments have already + // been parsed. +} + +function compileFiles(%pattern) +{ + %path = filePath(%pattern); + + %saveDSO = $Scripts::OverrideDSOPath; + %saveIgnore = $Scripts::ignoreDSOs; + + $Scripts::OverrideDSOPath = %path; + $Scripts::ignoreDSOs = false; + %mainCsFile = makeFullPath("main.cs"); + + for (%file = findFirstFileMultiExpr(%pattern); %file !$= ""; %file = findNextFileMultiExpr(%pattern)) + { + // we don't want to try and compile the primary main.cs + if(%mainCsFile !$= %file) + compile(%file, true); + } + + $Scripts::OverrideDSOPath = %saveDSO; + $Scripts::ignoreDSOs = %saveIgnore; + +} + +if($compileAll) +{ + echo(" --- Compiling all files ---"); + compileFiles("*.cs"); + compileFiles("*.gui"); + compileFiles("*.ts"); + echo(" --- Exiting after compile ---"); + quit(); +} + +if($compileTools) +{ + echo(" --- Compiling tools scritps ---"); + compileFiles("tools/*.cs"); + compileFiles("tools/*.gui"); + compileFiles("tools/*.ts"); + echo(" --- Exiting after compile ---"); + quit(); +} + +package Help { + function onExit() { + // Override onExit when displaying help + } +}; + +function displayHelp() { + activatePackage(Help); + + // Notes on logmode: console logging is written to console.log. + // -log 0 disables console logging. + // -log 1 appends to existing logfile; it also closes the file + // (flushing the write buffer) after every write. + // -log 2 overwrites any existing logfile; it also only closes + // the logfile when the application shuts down. (default) + + error( + "Torque Demo command line options:\n"@ + " -log Logging behavior; see main.cs comments for details\n"@ + " -game Reset list of mods to only contain \n"@ + " Works like the -game argument\n"@ + " -dir Add to list of directories\n"@ + " -console Open a separate console\n"@ + " -show Deprecated\n"@ + " -jSave Record a journal\n"@ + " -jPlay Play back a journal\n"@ + " -jDebug Play back a journal and issue an int3 at the end\n"@ + " -help Display this help message\n" + ); +} + + +//-------------------------------------------------------------------------- + +// Default to a new logfile each session. +if( !$logModeSpecified ) +{ + if( $platform !$= "xbox" && $platform !$= "xenon" ) + setLogMode(6); +} + +// Get the first dir on the list, which will be the last to be applied... this +// does not modify the list. +nextToken($userDirs, currentMod, ";"); + +// Execute startup scripts for each mod, starting at base and working up +function loadDir(%dir) +{ + pushback($userDirs, %dir, ";"); + + if (isScriptFile(%dir @ "/main.cs")) + exec(%dir @ "/main.cs"); +} + +echo("--------- Loading DIRS ---------"); +function loadDirs(%dirPath) +{ + %dirPath = nextToken(%dirPath, token, ";"); + if (%dirPath !$= "") + loadDirs(%dirPath); + + if(exec(%token @ "/main.cs") != true) + { + error("Error: Unable to find specified directory: " @ %token ); + $dirCount--; + } +} +loadDirs($userDirs); +echo(""); + +if($dirCount == 0) { + enableWinConsole(true); + error("Error: Unable to load any specified directories"); + quit(); +} +// Parse the command line arguments +echo("--------- Parsing Arguments ---------"); +parseArgs(); + +// Either display the help message or startup the app. +if ($displayHelp) { + enableWinConsole(true); + displayHelp(); + quit(); +} +else { + onStart(); + echo("Engine initialized..."); + + // Auto-load on the 360 + if( $platform $= "xenon" ) + { + %mission = "levels/Empty Terrain.mis"; + + echo("Xbox360 Autoloading level: '" @ %mission @ "'"); + + + if ($pref::HostMultiPlayer) + %serverType = "MultiPlayer"; + else + %serverType = "SinglePlayer"; + + createAndConnectToLocalServer( %serverType, %mission ); + } +} + +// Display an error message for unused arguments +for ($i = 1; $i < $Game::argc; $i++) { + if (!$argUsed[$i]) + error("Error: Unknown command line argument: " @ $Game::argv[$i]); +} + +// Automatically start up the appropriate eidtor, if any +if ($startWorldEditor) { + Canvas.setCursor("DefaultCursor"); + Canvas.setContent(EditorChooseLevelGui); +} else if ($startGUIEditor) { + Canvas.setCursor("DefaultCursor"); + Canvas.setContent(EditorChooseGUI); +} diff --git a/Templates/Full/game/scripts/client/init.cs b/Templates/Full/game/scripts/client/init.cs index 3f7f2d96a..56da1c945 100644 --- a/Templates/Full/game/scripts/client/init.cs +++ b/Templates/Full/game/scripts/client/init.cs @@ -73,8 +73,8 @@ function initClient() // Load up the Game GUIs exec("art/gui/defaultGameProfiles.cs"); - exec("art/gui/PlayGui.gui"); - exec("art/gui/ChatHud.gui"); + exec("art/gui/playGui.gui"); + exec("art/gui/chatHud.gui"); exec("art/gui/playerList.gui"); exec("art/gui/hudlessGui.gui"); diff --git a/Templates/Full/game/shaders/common/gl/blurP.glsl b/Templates/Full/game/shaders/common/gl/blurP.glsl index bc05b992f..5c37ebc6b 100644 --- a/Templates/Full/game/shaders/common/gl/blurP.glsl +++ b/Templates/Full/game/shaders/common/gl/blurP.glsl @@ -26,12 +26,12 @@ uniform vec4 kernel; uniform sampler2D diffuseMap; -varying vec2 texc0, texc1, texc2, texc3; +in vec2 texc0, texc1, texc2, texc3; void main() { - gl_FragColor = texture2D(diffuseMap, texc0) * kernel.x; - gl_FragColor += texture2D(diffuseMap, texc1) * kernel.y; - gl_FragColor += texture2D(diffuseMap, texc2) * kernel.z; - gl_FragColor += texture2D(diffuseMap, texc3) * kernel.w; + OUT_FragColor0 = texture(diffuseMap, texc0) * kernel.x; + OUT_FragColor0 += texture(diffuseMap, texc1) * kernel.y; + OUT_FragColor0 += texture(diffuseMap, texc2) * kernel.z; + OUT_FragColor0 += texture(diffuseMap, texc3) * kernel.w; } diff --git a/Templates/Full/game/shaders/common/gl/blurV.glsl b/Templates/Full/game/shaders/common/gl/blurV.glsl index d5d615fb9..1bfb0cd1b 100644 --- a/Templates/Full/game/shaders/common/gl/blurV.glsl +++ b/Templates/Full/game/shaders/common/gl/blurV.glsl @@ -24,20 +24,25 @@ // Glow shader //***************************************************************************** +in vec4 vPosition; +in vec4 vColor; +in vec2 vTexCoord0; + uniform mat4 modelview; uniform vec2 offset0, offset1, offset2, offset3; -varying vec2 texc0, texc1, texc2, texc3; +out vec2 texc0, texc1, texc2, texc3; void main() { - gl_Position = modelview * gl_Vertex; + gl_Position = modelview * vPosition; - vec2 tc = gl_MultiTexCoord0.st; + vec2 tc = vTexCoord0.st; tc.y = 1.0 - tc.y; texc0 = tc + offset0; texc1 = tc + offset1; texc2 = tc + offset2; texc3 = tc + offset3; + gl_Position.y *= -1; } \ No newline at end of file diff --git a/Templates/Full/game/shaders/common/gl/cloudLayerP.glsl b/Templates/Full/game/shaders/common/gl/cloudLayerP.glsl index 326f2d3c6..da3996d58 100644 --- a/Templates/Full/game/shaders/common/gl/cloudLayerP.glsl +++ b/Templates/Full/game/shaders/common/gl/cloudLayerP.glsl @@ -22,12 +22,20 @@ #include "hlslCompat.glsl" -varying vec4 texCoord12; -varying vec4 texCoord34; -varying vec3 vLightTS; // light vector in tangent space, denormalized -varying vec3 vViewTS; // view vector in tangent space, denormalized -varying vec3 vNormalWS; // Normal vector in world space -varying float worldDist; +//----------------------------------------------------------------------------- +// Structures +//----------------------------------------------------------------------------- +//ConnectData +in vec4 texCoord12; +#define IN_texCoord12 texCoord12 +in vec4 texCoord34; +#define IN_texCoord34 texCoord34 +in vec3 vLightTS; // light vector in tangent space, denormalized +#define IN_vLightTS vLightTS +in vec3 vViewTS; // view vector in tangent space, denormalized +#define IN_vViewTS vViewTS +in float worldDist; +#define IN_worldDist worldDist //----------------------------------------------------------------------------- // Uniforms @@ -37,6 +45,7 @@ uniform vec3 ambientColor; uniform vec3 sunColor; uniform float cloudCoverage; uniform vec3 cloudBaseColor; +uniform float cloudExposure; //----------------------------------------------------------------------------- // Globals @@ -97,26 +106,25 @@ void main() // Normalize the interpolated vectors: vec3 vViewTS = normalize( vViewTS ); vec3 vLightTS = normalize( vLightTS ); - vec3 vNormalWS = normalize( vNormalWS ); - vec4 cResultColor = float4( 0, 0, 0, 1 ); + vec4 cResultColor = vec4( 0, 0, 0, 1 ); - vec2 texSample = texCoord12.xy; + vec2 texSample = IN_texCoord12.xy; - vec4 noise1 = texture2D( normalHeightMap, texCoord12.zw ); + vec4 noise1 = texture( normalHeightMap, IN_texCoord12.zw ); noise1 = normalize( ( noise1 - 0.5 ) * 2.0 ); //return noise1; - vec4 noise2 = texture2D( normalHeightMap, texCoord34.xy ); + vec4 noise2 = texture( normalHeightMap, IN_texCoord34.xy ); noise2 = normalize( ( noise2 - 0.5 ) * 2.0 ); //return noise2; vec3 noiseNormal = normalize( noise1 + noise2 ).xyz; - //return float4( noiseNormal, 1.0 ); + //return vec4( noiseNormal, 1.0 ); float noiseHeight = noise1.a * noise2.a * ( cloudCoverage / 2.0 + 0.5 ); - vec3 vNormalTS = normalize( texture2D( normalHeightMap, texSample ).xyz * 2.0 - 1.0 ); + vec3 vNormalTS = normalize( texture( normalHeightMap, texSample ).xyz * 2.0 - 1.0 ); vNormalTS += noiseNormal; vNormalTS = normalize( vNormalTS ); @@ -124,16 +132,14 @@ void main() cResultColor.rgb = ComputeIllumination( texSample, vLightTS, vViewTS, vNormalTS ); float coverage = ( cloudCoverage - 0.5 ) * 2.0; - cResultColor.a = texture2D( normalHeightMap, texSample ).a + coverage + noiseHeight; + cResultColor.a = texture( normalHeightMap, texSample ).a + coverage + noiseHeight; if ( cloudCoverage > -1.0 ) cResultColor.a /= 1.0 + coverage; - cResultColor.a = saturate( cResultColor.a * pow( saturate(cloudCoverage), 0.25 ) ); + cResultColor.a = clamp( cResultColor.a * pow( saturate(cloudCoverage), 0.25 ), 0.0, 1.0 ); - cResultColor.a = mix( cResultColor.a, 0.0, 1.0 - pow(worldDist,2.0) ); + cResultColor.a = mix( cResultColor.a, 0.0, 1.0 - pow(IN_worldDist,2.0) ); - // If using HDR rendering, make sure to tonemap the resuld color prior to outputting it. - // But since this example isn't doing that, we just output the computed result color here: - gl_FragColor = cResultColor; + OUT_FragColor0 = cResultColor; } diff --git a/Templates/Full/game/shaders/common/gl/cloudLayerV.glsl b/Templates/Full/game/shaders/common/gl/cloudLayerV.glsl index 39a6f4ba8..395c6f286 100644 --- a/Templates/Full/game/shaders/common/gl/cloudLayerV.glsl +++ b/Templates/Full/game/shaders/common/gl/cloudLayerV.glsl @@ -20,12 +20,24 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- -varying vec4 texCoord12; -varying vec4 texCoord34; -varying vec3 vLightTS; // light vector in tangent space, denormalized -varying vec3 vViewTS; // view vector in tangent space, denormalized -varying vec3 vNormalWS; // Normal vector in world space -varying float worldDist; +#include "hlslCompat.glsl" + +in vec4 vPosition; +in vec3 vNormal; +in vec3 vBinormal; +in vec3 vTangent; +in vec2 vTexCoord0; + +out vec4 texCoord12; +#define OUT_texCoord12 texCoord12 +out vec4 texCoord34; +#define OUT_texCoord34 texCoord34 +out vec3 vLightTS; // light vector in tangent space, denormalized +#define OUT_vLightTS vLightTS +out vec3 vViewTS; // view vector in tangent space, denormalized +#define OUT_vViewTS vViewTS +out float worldDist; +#define OUT_worldDist worldDist //----------------------------------------------------------------------------- // Uniforms @@ -43,37 +55,37 @@ uniform vec3 texScale; //----------------------------------------------------------------------------- void main() { - vec4 pos = gl_Vertex; - vec3 normal = gl_Normal; - vec3 binormal = gl_MultiTexCoord0.xyz; - vec3 tangent = gl_MultiTexCoord1.xyz; - vec2 uv0 = gl_MultiTexCoord2.st; + vec4 IN_pos = vPosition; + vec3 IN_normal = vNormal; + vec3 IN_binormal = vBinormal; + vec3 IN_tangent = vTangent; + vec2 IN_uv0 = vTexCoord0.st; - gl_Position = modelview * pos; + gl_Position = modelview * IN_pos; // Offset the uv so we don't have a seam directly over our head. - vec2 uv = uv0 + vec2( 0.5, 0.5 ); + vec2 uv = IN_uv0 + vec2( 0.5, 0.5 ); - texCoord12.xy = uv * texScale.x; - texCoord12.xy += texOffset0; + OUT_texCoord12.xy = uv * texScale.x; + OUT_texCoord12.xy += texOffset0; - texCoord12.zw = uv * texScale.y; - texCoord12.zw += texOffset1; + OUT_texCoord12.zw = uv * texScale.y; + OUT_texCoord12.zw += texOffset1; - texCoord34.xy = uv * texScale.z; - texCoord34.xy += texOffset2; + OUT_texCoord34.xy = uv * texScale.z; + OUT_texCoord34.xy += texOffset2; - texCoord34.z = pos.z; - texCoord34.w = 0.0; + OUT_texCoord34.z = IN_pos.z; + OUT_texCoord34.w = 0.0; // Transform the normal, tangent and binormal vectors from object space to // homogeneous projection space: - vNormalWS = -normal; - vec3 vTangentWS = -tangent; - vec3 vBinormalWS = -binormal; + vec3 vNormalWS = -IN_normal; + vec3 vTangentWS = -IN_tangent; + vec3 vBinormalWS = -IN_binormal; // Compute position in world space: - vec4 vPositionWS = pos + vec4( eyePosWorld, 1 ); //mul( pos, objTrans ); + vec4 vPositionWS = IN_pos + vec4( eyePosWorld, 1 ); //tMul( IN_pos, objTrans ); // Compute and output the world view vector (unnormalized): vec3 vViewWS = eyePosWorld - vPositionWS.xyz; @@ -81,12 +93,14 @@ void main() // Compute denormalized light vector in world space: vec3 vLightWS = -sunVec; - // Normalize the light and view vectors and transform it to the tangent space: + // Normalize the light and view vectors and transform it to the IN_tangent space: mat3 mWorldToTangent = mat3( vTangentWS, vBinormalWS, vNormalWS ); // Propagate the view and the light vectors (in tangent space): - vLightTS = mWorldToTangent * vLightWS; - vViewTS = vViewWS * mWorldToTangent; - - worldDist = clamp( pow( pos.z, 2.0 ), 0.0, 1.0 ); + OUT_vLightTS = vLightWS * mWorldToTangent; + OUT_vViewTS = mWorldToTangent * vViewWS; + + OUT_worldDist = clamp( pow( max( IN_pos.z, 0 ), 2 ), 0.0, 1.0 ); + + correctSSP(gl_Position); } diff --git a/Templates/Full/game/shaders/common/gl/foliage.glsl b/Templates/Full/game/shaders/common/gl/foliage.glsl index 2fee902e3..38b66e767 100644 --- a/Templates/Full/game/shaders/common/gl/foliage.glsl +++ b/Templates/Full/game/shaders/common/gl/foliage.glsl @@ -46,7 +46,19 @@ uniform vec3 gc_gustInfo; uniform vec2 gc_turbInfo; -//static float sMovableCorner[4] = { 0.0, 0.0, 1.0, 1.0 }; +const float sCornerRight[4] = float[]( -0.5, 0.5, 0.5, -0.5 ); + +const float sCornerUp[4] = float[]( 0, 0, 1, 1 ); + +const float sMovableCorner[4] = float[]( 0, 0, 1, 1 ); + +const vec2 sUVCornerExtent[4] = vec2[] +( + vec2( 0, 1 ), + vec2( 1, 1 ), + vec2( 1, 0 ), + vec2( 0, 0 ) +); /////////////////////////////////////////////////////////////////////////////// @@ -106,34 +118,13 @@ vec2 windEffect( float bbPhase, void foliageProcessVert( inout vec3 position, inout vec4 diffuse, - in vec4 texCoord, - out vec2 outTexCoord, + inout vec4 texCoord, inout vec3 normal, inout vec3 T, in vec3 eyePos ) { - - float sCornerRight[4]; - sCornerRight[0] = -0.5; - sCornerRight[1] = 0.5; - sCornerRight[2] = 0.5; - sCornerRight[3] = -0.5; - - float sCornerUp[4]; - sCornerUp[0] = 0.0; - sCornerUp[1] = 0.0; - sCornerUp[2] = 1.0; - sCornerUp[3] = 1.0; - - vec2 sUVCornerExtent[4]; - sUVCornerExtent[0] = vec2( 0.0, 1.0 ); - sUVCornerExtent[1] = vec2( 1.0, 1.0 ); - sUVCornerExtent[2] = vec2( 1.0, 0.0 ); - sUVCornerExtent[3] = vec2( 0.0, 0.0 ); - - // Assign the normal and tagent values. - //normal = cross( gc_camUp, gc_camRight ); + //normal = vec3( 0, 0, 1 );//cross( gc_camUp, gc_camRight ); T = gc_camRight; // Pull out local vars we need for work. @@ -172,8 +163,8 @@ void foliageProcessVert( inout vec3 position, // Grab the uv set and setup the texture coord. vec4 uvSet = gc_typeRects[type]; - outTexCoord.x = uvSet.x + ( uvSet.z * sUVCornerExtent[corner].x ); - outTexCoord.y = uvSet.y + ( uvSet.w * sUVCornerExtent[corner].y ); + texCoord.x = uvSet.x + ( uvSet.z * sUVCornerExtent[corner].x ); + texCoord.y = uvSet.y + ( uvSet.w * sUVCornerExtent[corner].y ); // Animate the normal to get lighting changes // across the the wind swept foliage. @@ -184,7 +175,6 @@ void foliageProcessVert( inout vec3 position, normal.xy += wind.xy * ( 10.0 * texCoord.w ); normal = normalize( normal ); - // Get the alpha fade value. float fadeStart = gc_fadeParams.x; diff --git a/Templates/Full/game/shaders/common/gl/fxFoliageReplicatorP.glsl b/Templates/Full/game/shaders/common/gl/fxFoliageReplicatorP.glsl index 9e5b34caa..fb5abb91e 100644 --- a/Templates/Full/game/shaders/common/gl/fxFoliageReplicatorP.glsl +++ b/Templates/Full/game/shaders/common/gl/fxFoliageReplicatorP.glsl @@ -26,15 +26,15 @@ uniform sampler2D diffuseMap, alphaMap; uniform vec4 groundAlpha; -varying vec4 color, groundAlphaCoeff; -varying vec2 outTexCoord, alphaLookup; +in vec4 color, groundAlphaCoeff; +in vec2 outTexCoord, alphaLookup; //----------------------------------------------------------------------------- // Main //----------------------------------------------------------------------------- void main() { - vec4 alpha = texture2D(alphaMap, alphaLookup); - gl_FragColor = color * texture2D(diffuseMap, outTexCoord); - gl_FragColor.a = gl_FragColor.a * min(alpha, groundAlpha + groundAlphaCoeff.x).x; + vec4 alpha = texture(alphaMap, alphaLookup); + OUT_FragColor0 = color * texture(diffuseMap, outTexCoord); + OUT_FragColor0.a = OUT_FragColor0.a * min(alpha, groundAlpha + groundAlphaCoeff.x).x; } diff --git a/Templates/Full/game/shaders/common/gl/fxFoliageReplicatorV.glsl b/Templates/Full/game/shaders/common/gl/fxFoliageReplicatorV.glsl index 94a7af2b0..c8dcf1ddb 100644 --- a/Templates/Full/game/shaders/common/gl/fxFoliageReplicatorV.glsl +++ b/Templates/Full/game/shaders/common/gl/fxFoliageReplicatorV.glsl @@ -23,13 +23,20 @@ //----------------------------------------------------------------------------- // Data //----------------------------------------------------------------------------- +in vec4 vPosition; +in vec3 vNormal; +in vec4 vColor; +in vec2 vTexCoord0; +in vec2 vTexCoord1; +in vec2 vTexCoord2; + uniform mat4 projection, world; uniform vec3 CameraPos; uniform float GlobalSwayPhase, SwayMagnitudeSide, SwayMagnitudeFront, GlobalLightPhase, LuminanceMagnitude, LuminanceMidpoint, DistanceRange; -varying vec4 color, groundAlphaCoeff; -varying vec2 outTexCoord, alphaLookup; +out vec4 color, groundAlphaCoeff; +out vec2 outTexCoord, alphaLookup; //----------------------------------------------------------------------------- // Main @@ -42,9 +49,9 @@ void main() trans[1][1] = 1.0; trans[2][2] = 1.0; trans[3][3] = 1.0; - trans[3][0] = gl_Vertex.x; - trans[3][1] = gl_Vertex.y; - trans[3][2] = gl_Vertex.z; + trans[3][0] = vPosition.x; + trans[3][1] = vPosition.y; + trans[3][2] = vPosition.z; // Billboard transform * world matrix mat4 o = world; @@ -64,28 +71,29 @@ void main() // Handle sway. Sway is stored in a texture coord. The x coordinate is the sway phase multiplier, // the y coordinate determines if this vertex actually sways or not. float xSway, ySway; - float wavePhase = GlobalSwayPhase * gl_MultiTexCoord1.x; + float wavePhase = GlobalSwayPhase * vTexCoord1.x; ySway = sin(wavePhase); xSway = cos(wavePhase); - xSway = xSway * gl_MultiTexCoord1.y * SwayMagnitudeSide; - ySway = ySway * gl_MultiTexCoord1.y * SwayMagnitudeFront; + xSway = xSway * vTexCoord1.y * SwayMagnitudeSide; + ySway = ySway * vTexCoord1.y * SwayMagnitudeFront; vec4 p; - p = o * vec4(gl_Normal.x + xSway, ySway, gl_Normal.z, 1.0); + p = o * vec4(vNormal.x + xSway, ySway, vNormal.z, 1.0); // Project the point gl_Position = projection * p; // Lighting - float Luminance = LuminanceMidpoint + LuminanceMagnitude * cos(GlobalLightPhase + gl_Normal.y); + float Luminance = LuminanceMidpoint + LuminanceMagnitude * cos(GlobalLightPhase + vNormal.y); // Alpha - vec3 worldPos = vec3(gl_Vertex.x, gl_Vertex.y, gl_Vertex.z); + vec3 worldPos = vec3(vPosition.x, vPosition.y, vPosition.z); float alpha = abs(distance(worldPos, CameraPos)) / DistanceRange; alpha = clamp(alpha, 0.0, 1.0); //pass it through alphaLookup = vec2(alpha, 0.0); - bool alphaCoeff = bool(gl_Normal.z); + bool alphaCoeff = bool(vNormal.z); groundAlphaCoeff = vec4(float(alphaCoeff)); - outTexCoord = gl_MultiTexCoord0.st; + outTexCoord = vTexCoord0.st; color = vec4(Luminance, Luminance, Luminance, 1.0); + gl_Position.y *= -1; } \ No newline at end of file diff --git a/Templates/Full/game/shaders/common/gl/guiMaterialV.glsl b/Templates/Full/game/shaders/common/gl/guiMaterialV.glsl index cd44de2f2..de3845ee7 100644 --- a/Templates/Full/game/shaders/common/gl/guiMaterialV.glsl +++ b/Templates/Full/game/shaders/common/gl/guiMaterialV.glsl @@ -20,16 +20,20 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- +in vec4 vPosition; +in vec2 vTexCoord0; + uniform mat4x4 modelview; -varying vec4 hpos; -varying vec2 uv0; +out vec4 hpos; +out vec2 uv0; void main() { - hpos = vec4( modelview * gl_Vertex ); + hpos = vec4( modelview * vPosition ); gl_Position = hpos; - uv0 = gl_MultiTexCoord0.st; + uv0 = vTexCoord0.st; + gl_Position.y *= -1; } diff --git a/Templates/Full/game/shaders/common/gl/hlslCompat.glsl b/Templates/Full/game/shaders/common/gl/hlslCompat.glsl index be5c63340..0815df51f 100644 --- a/Templates/Full/game/shaders/common/gl/hlslCompat.glsl +++ b/Templates/Full/game/shaders/common/gl/hlslCompat.glsl @@ -27,17 +27,79 @@ #define float3 vec3 #define float2 vec2 -#define texCUBE textureCube -#define tex2D texture2D +#define half float +#define half2 vec2 +#define half3 vec3 +#define half4 vec4 + +#define float4x4 mat4 +#define float3x3 mat3 +#define float2x2 mat2 + +#define texCUBE texture +#define tex2D texture +#define tex1D texture +#define tex2Dproj textureProj +#define tex2Dlod( sampler, texCoord ) textureLod(sampler, texCoord.xy, texCoord.w) + +#define samplerCUBE samplerCube + +#define frac fract #define lerp mix -float saturate( float val ) { return clamp( val, 0.0, 1.0 ); } -vec2 saturate( vec2 val ) { return clamp( val, 0.0, 1.0 ); } -vec3 saturate( vec3 val ) { return clamp( val, 0.0, 1.0 ); } -vec4 saturate( vec4 val ) { return clamp( val, 0.0, 1.0 ); } +void tSetMatrixRow(out float3x3 m, int row, float3 value) +{ + m[0][row] = value.x; + m[1][row] = value.y; + m[2][row] = value.z; +} -float round( float n ) { return sign( n ) * floor( abs( n ) + 0.5 ); } -vec2 round( vec2 n ) { return sign( n ) * floor( abs( n ) + 0.5 ); } -vec3 round( vec3 n ) { return sign( n ) * floor( abs( n ) + 0.5 ); } -vec4 round( vec4 n ) { return sign( n ) * floor( abs( n ) + 0.5 ); } +void tSetMatrixRow(out float4x4 m, int row, float4 value) +{ + m[0][row] = value.x; + m[1][row] = value.y; + m[2][row] = value.z; + m[3][row] = value.w; +} + +#define tGetMatrix3Row(matrix, row) float3(matrix[0][row], matrix[1][row], matrix[2][row]) +#define tGetMatrix4Row(matrix, row) float4(matrix[0][row], matrix[1][row], matrix[2][row], matrix[3][row]) + +float3x3 float4x4to3x3(float4x4 m) +{ + return float3x3( vec3(m[0]).xyz, m[1].xyz, m[2].xyz); +} + +float3x3 float4x4to3x3_(float4x4 m) +{ + return float3x3( vec3(m[0]), m[1].xyz, m[2].xyz); +} + +mat4 mat4FromRow( float r0c0, float r0c1, float r0c2, float r0c3, + float r1c0, float r1c1, float r1c2, float r1c3, + float r2c0, float r2c1, float r2c2, float r2c3, + float r3c0, float r3c1, float r3c2, float r3c3 ) +{ + return mat4( r0c0, r1c0, r2c0, r3c0, + r0c1, r1c1, r2c1, r3c1, + r0c2, r1c2, r2c2, r3c2, + r0c3, r1c3, r2c3, r3c3 ); +} + + +#define saturate( val ) clamp( val, 0.0, 1.0 ) + +#define round( n ) (sign( n ) * floor( abs( n ) + 0.5 )) + +#define tMul(a, b) (a*b) + +#define inversesqrt( n ) inversesqrt( n ) + +#define correctSSP(vec) vec.y *= -1 + +#ifdef TORQUE_PIXEL_SHADER + void clip(float a) { if(a < 0) discard;} + + out vec4 OUT_FragColor0; +#endif diff --git a/Templates/Full/game/shaders/common/gl/lighting.glsl b/Templates/Full/game/shaders/common/gl/lighting.glsl index 3f8867d3b..4483c7526 100644 --- a/Templates/Full/game/shaders/common/gl/lighting.glsl +++ b/Templates/Full/game/shaders/common/gl/lighting.glsl @@ -20,73 +20,181 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- + +#ifndef TORQUE_SHADERGEN + // These are the uniforms used by most lighting shaders. -uniform vec3 inLightPos[4]; +uniform vec4 inLightPos[3]; uniform vec4 inLightInvRadiusSq; uniform vec4 inLightColor[4]; + +#ifndef TORQUE_BL_NOSPOTLIGHT + uniform vec4 inLightSpotDir[3]; + uniform vec4 inLightSpotAngle; + uniform vec4 inLightSpotFalloff; +#endif + uniform vec4 ambient; uniform float specularPower; uniform vec4 specularColor; - -// This is used to limit the maximum processed -// lights in the compute4Lights down for really -// low end GPUs. -// -// NOTE: If you want to support 10.5.x, this needs to be changed to 2. -#define C4L_MAX_LIGHTS 4 +#endif // !TORQUE_SHADERGEN void compute4Lights( vec3 wsView, vec3 wsPosition, - vec3 wsNormal, + vec3 wsNormal, + vec4 shadowMask, + + #ifdef TORQUE_SHADERGEN + + vec4 inLightPos[3], + vec4 inLightInvRadiusSq, + vec4 inLightColor[4], + vec4 inLightSpotDir[3], + vec4 inLightSpotAngle, + vec4 inLightSpotFalloff, + float specularPower, + vec4 specularColor, + + #endif // TORQUE_SHADERGEN + out vec4 outDiffuse, out vec4 outSpecular ) { - #ifdef PHONG_SPECULAR - // (R.V)^c - float reflected = reflect( wsView, wsNormal ); - #endif - - vec4 nDotL = vec4( 0.0 ); - vec4 rDotL = vec4( 0.0 ); - vec4 sqDists = vec4( 0.0 ); + // NOTE: The light positions and spotlight directions + // are stored in SoA order, so inLightPos[0] is the + // x coord for all 4 lights... inLightPos[1] is y... etc. + // + // This is the key to fully utilizing the vector units and + // saving a huge amount of instructions. + // + // For example this change saved more than 10 instructions + // over a simple for loop for each light. + int i; - for ( i = 0; i < C4L_MAX_LIGHTS; ++i ) - { - vec3 lightVector = inLightPos[i] - wsPosition; - vec3 lightDirection = normalize( lightVector ); + vec4 lightVectors[3]; + for ( i = 0; i < 3; i++ ) + lightVectors[i] = wsPosition[i] - inLightPos[i]; - nDotL[i] = max( dot( lightDirection, wsNormal ), 0.0 ); + vec4 squareDists = vec4(0); + for ( i = 0; i < 3; i++ ) + squareDists += lightVectors[i] * lightVectors[i]; - #ifdef PHONG_SPECULAR - rDotL[i] = saturate( dot( lightDirection, reflected ) ); - #else - // (N.H)^c [Blinn-Phong, TGEA style, default] - rDotL[i] = dot( wsNormal, normalize( lightDirection + wsView ) ); - #endif + // Accumulate the dot product between the light + // vector and the normal. + // + // The normal is negated because it faces away from + // the surface and the light faces towards the + // surface... this keeps us from needing to flip + // the light vector direction which complicates + // the spot light calculations. + // + // We normalize the result a little later. + // + vec4 nDotL = vec4(0); + for ( i = 0; i < 3; i++ ) + nDotL += lightVectors[i] * -wsNormal[i]; - sqDists[i] = dot( lightVector, lightVector ); - } + vec4 rDotL = vec4(0); + #ifndef TORQUE_BL_NOSPECULAR - // Attenuation - vec4 atten = vec4( 1.0 ) - ( sqDists * inLightInvRadiusSq ); + // We're using the Phong specular reflection model + // here where traditionally Torque has used Blinn-Phong + // which has proven to be more accurate to real materials. + // + // We do so because its cheaper as do not need to + // calculate the half angle for all 4 lights. + // + // Advanced Lighting still uses Blinn-Phong, but the + // specular reconstruction it does looks fairly similar + // to this. + // + vec3 R = reflect( wsView, -wsNormal ); + + for ( i = 0; i < 3; i++ ) + rDotL += lightVectors[i] * R[i]; + + #endif + + // Normalize the dots. + // + // Notice we're using the half type here to get a + // much faster sqrt via the rsq_pp instruction at + // the loss of some precision. + // + // Unless we have some extremely large point lights + // i don't believe the precision loss will matter. + // + half4 correction = half4(inversesqrt( squareDists )); + nDotL = saturate( nDotL * correction ); + rDotL = clamp( rDotL * correction, 0.00001, 1.0 ); + + // First calculate a simple point light linear + // attenuation factor. + // + // If this is a directional light the inverse + // radius should be greater than the distance + // causing the attenuation to have no affect. + // + vec4 atten = saturate( 1.0 - ( squareDists * inLightInvRadiusSq ) ); + + #ifndef TORQUE_BL_NOSPOTLIGHT + + // The spotlight attenuation factor. This is really + // fast for what it does... 6 instructions for 4 spots. + + vec4 spotAtten = vec4(0); + for ( i = 0; i < 3; i++ ) + spotAtten += lightVectors[i] * inLightSpotDir[i]; + + vec4 cosAngle = ( spotAtten * correction ) - inLightSpotAngle; + atten *= saturate( cosAngle * inLightSpotFalloff ); + + #endif + + // Finally apply the shadow masking on the attenuation. + atten *= shadowMask; + + // Get the final light intensity. + vec4 intensity = nDotL * atten; // Combine the light colors for output. - vec4 diffuse = clamp( nDotL * atten, vec4( 0.0 ), vec4( 1.0 ) ); - outDiffuse = vec4( 0.0 ); - for ( i = 0; i < C4L_MAX_LIGHTS; ++i ) - outDiffuse += vec4( diffuse[i] ) * inLightColor[i]; + outDiffuse = vec4(0); + for ( i = 0; i < 4; i++ ) + outDiffuse += intensity[i] * inLightColor[i]; // Output the specular power. - rDotL = max( rDotL, vec4( 0.00001 ) ); - outSpecular = pow( rDotL, vec4( specularPower ) ); + vec4 specularIntensity = pow( rDotL, vec4(specularPower) ) * atten; + + // Apply the per-light specular attenuation. + vec4 specular = vec4(0,0,0,1); + for ( i = 0; i < 4; i++ ) + specular += vec4( inLightColor[i].rgb * inLightColor[i].a * specularIntensity[i], 1 ); + + // Add the final specular intensity values together + // using a single dot product operation then get the + // final specular lighting color. + outSpecular = specularColor * specular; } -/// The standard specular calculation. +// This value is used in AL as a constant power to raise specular values +// to, before storing them into the light info buffer. The per-material +// specular value is then computer by using the integer identity of +// exponentiation: +// +// (a^m)^n = a^(m*n) +// +// or +// +// (specular^constSpecular)^(matSpecular/constSpecular) = specular^(matSpecular*constSpecular) +// +#define AL_ConstantSpecularPower 12.0f + +/// The specular calculation used in Advanced Lighting. /// /// @param toLight Normalized vector representing direction from the pixel /// being lit, to the light source, in world space. @@ -96,11 +204,7 @@ void compute4Lights( vec3 wsView, /// @param toEye The normalized vector representing direction from the pixel /// being lit to the camera. /// -/// @param specPwr The specular exponent. -/// -/// @param specScale A scalar on the specular output used in RGB accumulation. -/// -float calcSpecular( vec3 toLight, vec3 normal, vec3 toEye, float specPwr ) +float AL_CalcSpecular( vec3 toLight, vec3 normal, vec3 toEye ) { #ifdef PHONG_SPECULAR // (R.V)^c @@ -111,5 +215,5 @@ float calcSpecular( vec3 toLight, vec3 normal, vec3 toEye, float specPwr ) #endif // Return the specular factor. - return pow( max( specVal, 0.00001f ), specPwr ); + return pow( max( specVal, 0.00001f ), AL_ConstantSpecularPower ); } diff --git a/Templates/Full/game/shaders/common/gl/particleCompositeP.glsl b/Templates/Full/game/shaders/common/gl/particleCompositeP.glsl index 4f2d9b359..6971e1013 100644 --- a/Templates/Full/game/shaders/common/gl/particleCompositeP.glsl +++ b/Templates/Full/game/shaders/common/gl/particleCompositeP.glsl @@ -21,6 +21,13 @@ //----------------------------------------------------------------------------- #include "torque.glsl" +#include "hlslCompat.glsl" + +in vec4 offscreenPos; +in vec4 backbufferPos; + +#define IN_offscreenPos offscreenPos +#define IN_backbufferPos backbufferPos uniform sampler2D colorSource; uniform vec4 offscreenTargetParams; @@ -31,8 +38,6 @@ uniform sampler2D edgeSource; uniform vec4 edgeTargetParams; #endif -varying vec4 backbufferPos; -varying vec4 offscreenPos; void main() { @@ -47,11 +52,10 @@ void main() #ifdef REJECT_EDGES // Cut out particles along the edges, this will create the stencil mask uvScene.zw = viewportCoordToRenderTarget(uvScene.zw, edgeTargetParams); - float edge = texture2D( edgeSource, uvScene.zw ).r; - if (-edge < 0.0) - discard; + float edge = texture( edgeSource, uvScene.zw ).r; + clip( -edge ); #endif // Sample offscreen target and return - gl_FragColor = texture2D( colorSource, uvScene.xy ); -} + OUT_FragColor0 = texture( colorSource, uvScene.xy ); +} \ No newline at end of file diff --git a/Templates/Full/game/shaders/common/gl/particleCompositeV.glsl b/Templates/Full/game/shaders/common/gl/particleCompositeV.glsl index 88a9431d1..8c8f840d1 100644 --- a/Templates/Full/game/shaders/common/gl/particleCompositeV.glsl +++ b/Templates/Full/game/shaders/common/gl/particleCompositeV.glsl @@ -20,16 +20,29 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- -uniform mat4 modelViewProj; -uniform mat4 targetModelViewProj; +#include "hlslCompat.glsl" -varying vec4 offscreenPos; -varying vec4 backbufferPos; +in vec2 vTexCoord0; +#define uvCoord vTexCoord0 + +out vec4 offscreenPos; +out vec4 backbufferPos; + +#define OUT_hpos gl_Position +#define OUT_offscreenPos offscreenPos +#define OUT_backbufferPos backbufferPos + +uniform vec4 screenRect; // point, extent void main() { - gl_Position = modelViewProj * gl_Vertex; - backbufferPos = gl_Position; - offscreenPos = targetModelViewProj * gl_Vertex; + OUT_hpos = vec4(uvCoord.xy, 1.0, 1.0); + OUT_hpos.xy *= screenRect.zw; + OUT_hpos.xy += screenRect.xy; + + OUT_backbufferPos = OUT_hpos; + OUT_offscreenPos = OUT_hpos; + + correctSSP(gl_Position); } diff --git a/Templates/Full/game/shaders/common/gl/particlesP.glsl b/Templates/Full/game/shaders/common/gl/particlesP.glsl index 66a3fee28..efd930302 100644 --- a/Templates/Full/game/shaders/common/gl/particlesP.glsl +++ b/Templates/Full/game/shaders/common/gl/particlesP.glsl @@ -20,63 +20,92 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- -#include "hlslCompat.glsl" #include "torque.glsl" - +#include "hlslCompat.glsl" + // With advanced lighting we get soft particles. #ifdef TORQUE_LINEAR_DEPTH #define SOFTPARTICLES #endif -#define CLIP_Z // TODO: Make this a proper macro - -uniform sampler2D diffuseMap; - #ifdef SOFTPARTICLES #include "shadergen:/autogenConditioners.h" uniform float oneOverSoftness; uniform float oneOverFar; - uniform sampler2D prepassTex; + uniform sampler2D prepassTex; //uniform vec3 vEye; uniform vec4 prePassTargetParams; #endif +#define CLIP_Z // TODO: Make this a proper macro + +in vec4 color; +in vec2 uv0; +in vec4 pos; + +#define IN_color color +#define IN_uv0 uv0 +#define IN_pos pos + +uniform sampler2D diffuseMap; + +uniform sampler2D paraboloidLightMap; + +vec4 lmSample( vec3 nrm ) +{ + bool calcBack = (nrm.z < 0.0); + if ( calcBack ) + nrm.z = nrm.z * -1.0; + + vec2 lmCoord; + lmCoord.x = (nrm.x / (2*(1 + nrm.z))) + 0.5; + lmCoord.y = 1-((nrm.y / (2*(1 + nrm.z))) + 0.5); + + + // If this is the back, offset in the atlas + if ( calcBack ) + lmCoord.x += 1.0; + + // Atlasing front and back maps, so scale + lmCoord.x *= 0.5; + + return texture(paraboloidLightMap, lmCoord); +} + + uniform float alphaFactor; uniform float alphaScale; -varying vec4 color; -varying vec2 uv0; -varying vec4 pos; - - void main() { - float softBlend = 1.0; + float softBlend = 1; #ifdef SOFTPARTICLES - float2 tc = pos.xy * vec2(1.0, -1.0 ) / pos.w; + vec2 tc = IN_pos.xy * vec2(1.0, -1.0) / IN_pos.w; tc = viewportCoordToRenderTarget(saturate( ( tc + 1.0 ) * 0.5 ), prePassTargetParams); float sceneDepth = prepassUncondition( prepassTex, tc ).w; - float depth = pos.w * oneOverFar; - float diff = sceneDepth - depth; + float depth = IN_pos.w * oneOverFar; + float diff = sceneDepth - depth; #ifdef CLIP_Z // If drawing offscreen, this acts as the depth test, since we don't line up with the z-buffer // When drawing high-res, though, we want to be able to take advantage of hi-z // so this is #ifdef'd out - if (diff < 0.0) - discard; + //clip(diff); #endif softBlend = saturate( diff * oneOverSoftness ); #endif - - vec4 diffuse = texture2D( diffuseMap, uv0 ); + + vec4 diffuse = texture( diffuseMap, IN_uv0 ); + + //OUT_FragColor0 = vec4( lmSample(vec3(0, 0, -1)).rgb, IN_color.a * diffuse.a * softBlend * alphaScale); // Scale output color by the alpha factor (turn LerpAlpha into pre-multiplied alpha) - vec3 colorScale = ( alphaFactor < 0.0 ? color.rgb * diffuse.rgb : ( alphaFactor > 0.0 ? vec3(color.a * alphaFactor * diffuse.a * softBlend) : vec3(softBlend) ) ); + vec3 colorScale = ( alphaFactor < 0.0 ? IN_color.rgb * diffuse.rgb : vec3( alphaFactor > 0.0 ? IN_color.a * diffuse.a * alphaFactor * softBlend : softBlend ) ); - gl_FragColor = hdrEncode( vec4(color.rgb * diffuse.rgb * colorScale, softBlend * color.a * diffuse.a * alphaScale) ); + OUT_FragColor0 = hdrEncode( vec4( IN_color.rgb * diffuse.rgb * colorScale, + IN_color.a * diffuse.a * softBlend * alphaScale ) ); } diff --git a/Templates/Full/game/shaders/common/gl/particlesV.glsl b/Templates/Full/game/shaders/common/gl/particlesV.glsl index da896431f..3d75a6fb6 100644 --- a/Templates/Full/game/shaders/common/gl/particlesV.glsl +++ b/Templates/Full/game/shaders/common/gl/particlesV.glsl @@ -20,18 +20,35 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- -varying vec4 color; -varying vec2 uv0; -varying vec4 pos; +#include "hlslCompat.glsl" + +in vec4 vPosition; +in vec4 vColor; +in vec2 vTexCoord0; + +#define In_pos vPosition +#define In_color vColor +#define In_uv0 vTexCoord0 + +out vec4 color; +out vec2 uv0; +out vec4 pos; + +#define OUT_hpos gl_Position +#define OUT_color color +#define OUT_uv0 uv0 +#define OUT_pos pos uniform mat4 modelViewProj; uniform mat4 fsModelViewProj; void main() { - gl_Position = modelViewProj * gl_Vertex; - pos = fsModelViewProj * gl_Vertex; - color = gl_Color; - uv0 = gl_MultiTexCoord0.st; + OUT_hpos = tMul( modelViewProj, In_pos ); + OUT_pos = tMul( fsModelViewProj, In_pos ); + OUT_color = In_color; + OUT_uv0 = In_uv0; + + correctSSP(gl_Position); } diff --git a/Templates/Full/game/shaders/common/gl/planarReflectBumpP.glsl b/Templates/Full/game/shaders/common/gl/planarReflectBumpP.glsl index 00413aa3b..334c70a70 100644 --- a/Templates/Full/game/shaders/common/gl/planarReflectBumpP.glsl +++ b/Templates/Full/game/shaders/common/gl/planarReflectBumpP.glsl @@ -26,8 +26,8 @@ uniform sampler2D diffuseMap, refractMap, bumpMap; uniform vec4 shadeColor; -varying vec2 TEX0; -varying vec4 TEX1; +in vec2 TEX0; +in vec4 TEX1; //----------------------------------------------------------------------------- // Fade edges of axis for texcoord passed in @@ -49,7 +49,7 @@ float fadeAxis( float val ) //----------------------------------------------------------------------------- void main() { - vec3 bumpNorm = texture2D( bumpMap, TEX0 ).rgb * 2.0 - 1.0; + vec3 bumpNorm = texture( bumpMap, TEX0 ).rgb * 2.0 - 1.0; vec2 offset = vec2( bumpNorm.x, bumpNorm.y ); vec4 texIndex = TEX1; @@ -61,8 +61,8 @@ void main() const float distortion = 0.2; texIndex.xy += offset * distortion * fadeVal; - vec4 diffuseColor = texture2D( diffuseMap, TEX0 ); - vec4 reflectColor = texture2DProj( refractMap, texIndex ); + vec4 diffuseColor = texture( diffuseMap, TEX0 ); + vec4 reflectColor = textureProj( refractMap, texIndex ); - gl_FragColor = diffuseColor + reflectColor * diffuseColor.a; + OUT_FragColor0 = diffuseColor + reflectColor * diffuseColor.a; } diff --git a/Templates/Full/game/shaders/common/gl/planarReflectBumpV.glsl b/Templates/Full/game/shaders/common/gl/planarReflectBumpV.glsl index 820bdf698..90bcd27d8 100644 --- a/Templates/Full/game/shaders/common/gl/planarReflectBumpV.glsl +++ b/Templates/Full/game/shaders/common/gl/planarReflectBumpV.glsl @@ -23,10 +23,13 @@ //----------------------------------------------------------------------------- // Data //----------------------------------------------------------------------------- +in vec4 vPosition; +in vec2 vTexCoord0; + uniform mat4 modelview; -varying vec2 TEX0; -varying vec4 TEX1; +out vec2 TEX0; +out vec4 TEX1; //----------------------------------------------------------------------------- // Main @@ -38,11 +41,11 @@ void main() 0.0, 0.0, 1.0, 0.0, 0.5, 0.5, 0.0, 1.0); - gl_Position = modelview * gl_Vertex; + gl_Position = modelview * vPosition; - TEX0 = gl_MultiTexCoord0.st; + TEX0 = vTexCoord0.st; TEX1 = texGenTest * gl_Position; TEX1.y = -TEX1.y; - + gl_Position.y *= -1; } diff --git a/Templates/Full/game/shaders/common/gl/planarReflectP.glsl b/Templates/Full/game/shaders/common/gl/planarReflectP.glsl index b4f4fab39..77914b80e 100644 --- a/Templates/Full/game/shaders/common/gl/planarReflectP.glsl +++ b/Templates/Full/game/shaders/common/gl/planarReflectP.glsl @@ -26,16 +26,16 @@ uniform sampler2D diffuseMap, refractMap; uniform vec4 shadeColor; -varying vec2 TEX0; -varying vec4 TEX1; +in vec2 TEX0; +in vec4 TEX1; //----------------------------------------------------------------------------- // Main //----------------------------------------------------------------------------- void main() { - vec4 diffuseColor = texture2D( diffuseMap, TEX0 ); - vec4 reflectColor = texture2DProj( refractMap, TEX1 ); + vec4 diffuseColor = texture( diffuseMap, TEX0 ); + vec4 reflectColor = textureProj( refractMap, TEX1 ); - gl_FragColor = diffuseColor + reflectColor * diffuseColor.a; + OUT_FragColor0 = diffuseColor + reflectColor * diffuseColor.a; } diff --git a/Templates/Full/game/shaders/common/gl/planarReflectV.glsl b/Templates/Full/game/shaders/common/gl/planarReflectV.glsl index 820bdf698..ba2484f66 100644 --- a/Templates/Full/game/shaders/common/gl/planarReflectV.glsl +++ b/Templates/Full/game/shaders/common/gl/planarReflectV.glsl @@ -23,10 +23,13 @@ //----------------------------------------------------------------------------- // Data //----------------------------------------------------------------------------- +in vec4 vPosition; +in vec2 vTexCoord0; + uniform mat4 modelview; -varying vec2 TEX0; -varying vec4 TEX1; +out vec2 TEX0; +out vec4 TEX1; //----------------------------------------------------------------------------- // Main @@ -38,9 +41,9 @@ void main() 0.0, 0.0, 1.0, 0.0, 0.5, 0.5, 0.0, 1.0); - gl_Position = modelview * gl_Vertex; + gl_Position = modelview * vPosition; - TEX0 = gl_MultiTexCoord0.st; + TEX0 = vTexCoord0; TEX1 = texGenTest * gl_Position; TEX1.y = -TEX1.y; diff --git a/Templates/Full/game/shaders/common/gl/precipP.glsl b/Templates/Full/game/shaders/common/gl/precipP.glsl index a04f16e4b..3c669517d 100644 --- a/Templates/Full/game/shaders/common/gl/precipP.glsl +++ b/Templates/Full/game/shaders/common/gl/precipP.glsl @@ -25,13 +25,13 @@ //----------------------------------------------------------------------------- uniform sampler2D diffuseMap; -varying vec4 color; -varying vec2 texCoord; +in vec4 color; +in vec2 texCoord; //----------------------------------------------------------------------------- // Main //----------------------------------------------------------------------------- void main() { - gl_FragColor = texture2D(diffuseMap, texCoord) * color; + OUT_FragColor0 = texture(diffuseMap, texCoord) * color; } diff --git a/Templates/Full/game/shaders/common/gl/precipV.glsl b/Templates/Full/game/shaders/common/gl/precipV.glsl index 3535f2f38..29f921630 100644 --- a/Templates/Full/game/shaders/common/gl/precipV.glsl +++ b/Templates/Full/game/shaders/common/gl/precipV.glsl @@ -23,28 +23,32 @@ //----------------------------------------------------------------------------- // Data //----------------------------------------------------------------------------- +in vec4 vPosition; +in vec2 vTexCoord0; + uniform mat4 modelview; uniform vec3 cameraPos, ambient; uniform vec2 fadeStartEnd; -varying vec4 color; -varying vec2 texCoord; +out vec4 color; +out vec2 texCoord; //----------------------------------------------------------------------------- // Main //----------------------------------------------------------------------------- void main() { - gl_Position = modelview * gl_Vertex; - texCoord = gl_MultiTexCoord0.st; + gl_Position = modelview * vPosition; + texCoord = vTexCoord0.st; color = vec4( ambient.r, ambient.g, ambient.b, 1.0 ); // Do we need to do a distance fade? if ( fadeStartEnd.x < fadeStartEnd.y ) { - float distance = length( cameraPos - gl_Vertex.xyz ); + float distance = length( cameraPos - vPosition.xyz ); color.a = abs( clamp( ( distance - fadeStartEnd.x ) / ( fadeStartEnd.y - fadeStartEnd.x ), 0.0, 1.0 ) - 1.0 ); } + gl_Position.y *= -1; } diff --git a/Templates/Full/game/shaders/common/gl/projectedShadowP.glsl b/Templates/Full/game/shaders/common/gl/projectedShadowP.glsl index 1dc963a4f..8ce0fba13 100644 --- a/Templates/Full/game/shaders/common/gl/projectedShadowP.glsl +++ b/Templates/Full/game/shaders/common/gl/projectedShadowP.glsl @@ -20,9 +20,11 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- -varying vec2 texCoord; -varying vec4 color; -varying float fade; +in vec2 texCoord; +in vec4 color; +in float fade; + +out vec4 OUT_FragColor0; uniform sampler2D inputTex; uniform vec4 ambient; @@ -30,17 +32,6 @@ uniform vec4 ambient; void main() { - vec3 LUMINANCE_VECTOR = vec3(0.2125f, 0.4154f, 0.1721f); - float esmFactor = 200.0; - - float lum = dot( ambient.rgb, LUMINANCE_VECTOR ); - - gl_FragColor.rgb = ambient.rgb * lum; - gl_FragColor.a = 0.0; - float depth = texture2D(inputTex, texCoord).a; - - depth = depth * exp(depth - 10.0); - depth = exp(esmFactor * depth) - 1.0; - - gl_FragColor.a = clamp(depth * 300.0, 0.0, 1.0) * (1.0 - lum) * fade * color.a; + float shadow = texture( inputTex, texCoord ).a * color.a; + OUT_FragColor0 = ( ambient * shadow ) + ( 1 - shadow ); } diff --git a/Templates/Full/game/shaders/common/gl/projectedShadowV.glsl b/Templates/Full/game/shaders/common/gl/projectedShadowV.glsl index c8abde742..b5de84181 100644 --- a/Templates/Full/game/shaders/common/gl/projectedShadowV.glsl +++ b/Templates/Full/game/shaders/common/gl/projectedShadowV.glsl @@ -20,13 +20,16 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- -//***************************************************************************** -// Precipitation vertex shader -//***************************************************************************** +#include "hlslCompat.glsl" -varying vec2 texCoord; -varying vec4 color; -varying float fade; +in vec4 vPosition; +in vec4 vColor; +in vec2 vTexCoord0; +in vec2 vTexCoord1; + +out vec2 texCoord; +out vec4 color; +out float fade; uniform mat4 modelview; uniform float shadowLength; @@ -34,11 +37,13 @@ uniform vec3 shadowCasterPosition; void main() { - gl_Position = modelview * vec4(gl_Vertex.xyz, 1.0); + gl_Position = modelview * vec4(vPosition.xyz, 1.0); - color = gl_Color; - texCoord = gl_MultiTexCoord1.st; + color = vColor; + texCoord = vTexCoord1.st; - float fromCasterDist = length(gl_Vertex.xyz - shadowCasterPosition) - shadowLength; - fade = 1.0 - clamp(fromCasterDist/shadowLength, 0.0, 1.0); + float fromCasterDist = length(vPosition.xyz - shadowCasterPosition) - shadowLength; + fade = 1.0 - clamp( fromCasterDist / shadowLength , 0.0, 1.0 ); + + correctSSP(gl_Position); } diff --git a/Templates/Full/game/shaders/common/gl/scatterSkyP.glsl b/Templates/Full/game/shaders/common/gl/scatterSkyP.glsl index 6a6b9b97c..691567a37 100644 --- a/Templates/Full/game/shaders/common/gl/scatterSkyP.glsl +++ b/Templates/Full/game/shaders/common/gl/scatterSkyP.glsl @@ -21,36 +21,32 @@ //----------------------------------------------------------------------------- #include "torque.glsl" +#include "hlslCompat.glsl" -// Calculates the Mie phase function -float getMiePhase(float fCos, float fCos2, float g, float g2) -{ - return 1.5 * ((1.0 - g2) / (2.0 + g2)) * (1.0 + fCos2) / pow(abs(1.0 + g2 - 2.0*g*fCos), 1.5); -} -// Calculates the Rayleigh phase function -float getRayleighPhase(float fCos2) -{ - //return 1.0; - return 0.75 + 0.75*fCos2; -} +// Conn +in vec4 rayleighColor; +#define IN_rayleighColor rayleighColor +in vec4 mieColor; +#define IN_mieColor mieColor +in vec3 v3Direction; +#define IN_v3Direction v3Direction +in float zPosition; +#define IN_zPosition zPosition +in vec3 pos; +#define IN_pos pos -varying vec4 rayleighColor; -varying vec4 mieColor; -varying vec3 v3Direction; -varying float zPosition; -varying vec3 pos; - -uniform samplerCube nightSky; +uniform samplerCube nightSky ; uniform vec4 nightColor; uniform vec2 nightInterpAndExposure; uniform float useCubemap; uniform vec3 lightDir; uniform vec3 sunDir; -void main() +void main() { - float fCos = dot( lightDir, v3Direction ) / length(v3Direction); + + float fCos = dot( lightDir, IN_v3Direction ) / length(IN_v3Direction); float fCos2 = fCos*fCos; float g = -0.991; @@ -58,15 +54,15 @@ void main() float fMiePhase = 1.5 * ((1.0 - g2) / (2.0 + g2)) * (1.0 + fCos2) / pow(abs(1.0 + g2 - 2.0*g*fCos), 1.5); - vec4 color = rayleighColor + fMiePhase * mieColor; + vec4 color = IN_rayleighColor + fMiePhase * IN_mieColor; color.a = color.b; - vec4 nightSkyColor = textureCube(nightSky, -v3Direction); + vec4 nightSkyColor = texture(nightSky, -v3Direction); nightSkyColor = mix(nightColor, nightSkyColor, useCubemap); float fac = dot( normalize( pos ), sunDir ); fac = max( nightInterpAndExposure.y, pow( clamp( fac, 0.0, 1.0 ), 2 ) ); - gl_FragColor = mix( color, nightSkyColor, nightInterpAndExposure.y ); + OUT_FragColor0 = mix( color, nightSkyColor, nightInterpAndExposure.y ); // Clip based on the camera-relative // z position of the vertex, passed through @@ -74,6 +70,6 @@ void main() if(zPosition < 0.0) discard; - gl_FragColor.a = 1; - gl_FragColor = hdrEncode( gl_FragColor ); + OUT_FragColor0.a = 1; + OUT_FragColor0 = hdrEncode( OUT_FragColor0 ); } diff --git a/Templates/Full/game/shaders/common/gl/scatterSkyV.glsl b/Templates/Full/game/shaders/common/gl/scatterSkyV.glsl index 53abd5a6b..61580d785 100644 --- a/Templates/Full/game/shaders/common/gl/scatterSkyV.glsl +++ b/Templates/Full/game/shaders/common/gl/scatterSkyV.glsl @@ -20,12 +20,7 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- -const int nSamples = 4; -const float fSamples = 4.0; - -// The scale depth (the altitude at which the average atmospheric density is found) -const float fScaleDepth = 0.25; -const float fInvScaleDepth = 1.0 / 0.25; +#include "hlslCompat.glsl" // The scale equation calculated by Vernier's Graphical Analysis float vernierScale(float fCos) @@ -40,12 +35,27 @@ float vernierScale(float fCos) return 0.25 * outx; } +in vec4 vPosition; +in vec3 vNormal; +in vec4 vColor; +in vec2 vTexCoord0; + +// This is the shader input vertex structure. +#define IN_position vPosition +#define IN_normal vNormal +#define IN_color vColor + // This is the shader output data. -varying vec4 rayleighColor; -varying vec4 mieColor; -varying vec3 v3Direction; -varying float zPosition; -varying vec3 pos; +out vec4 rayleighColor; +#define OUT_rayleighColor rayleighColor +out vec4 mieColor; +#define OUT_mieColor mieColor +out vec3 v3Direction; +#define OUT_v3Direction v3Direction +out float zPosition; +#define OUT_zPosition zPosition +out vec3 pos; +#define OUT_pos pos uniform mat4 modelView; uniform vec4 misc; @@ -54,13 +64,16 @@ uniform vec4 scatteringCoeffs; uniform vec3 camPos; uniform vec3 lightDir; uniform vec4 invWaveLength; - -void main() -{ - vec4 position = gl_Vertex.xyzw; - vec3 normal = gl_Normal.xyz; - vec4 color = gl_MultiTexCoord0.xyzw; +uniform vec4 colorize; +vec3 desaturate(const vec3 color, const float desaturation) +{ + const vec3 gray_conv = vec3 (0.30, 0.59, 0.11); + return mix(color, vec3(dot(gray_conv , color)), desaturation); +} + +void main() +{ // Pull some variables out: float camHeight = misc.x; float camHeightSqr = misc.y; @@ -83,7 +96,7 @@ void main() // Get the ray from the camera to the vertex, // and its length (which is the far point of the ray // passing through the atmosphere). - vec3 v3Pos = position.xyz / 6378000.0;// / outerRadius; + vec3 v3Pos = vec3(IN_position / 6378000.0);// / outerRadius; vec3 newCamPos = vec3( 0, 0, camHeight ); v3Pos.z += innerRadius; vec3 v3Ray = v3Pos.xyz - newCamPos; @@ -97,16 +110,7 @@ void main() float fDepth = exp(scaleOverScaleDepth * (innerRadius - camHeight)); float fStartAngle = dot(v3Ray, v3Start) / fHeight; - float x = 1.0 - fStartAngle; - float x5 = x * 5.25; - float x5p6 = (-6.80 + x5); - float xnew = (3.83 + x * x5p6); - float xfinal = (0.459 + x * xnew); - float xfinal2 = -0.00287 + x * xfinal; - float othx = exp( xfinal2 ); - float vscale1 = 0.25 * othx; - - float fStartOffset = fDepth * vscale1;//vernierScale(fStartAngle); + float fStartOffset = fDepth * vernierScale( fStartAngle ); // Initialize the scattering loop variables. float fSampleLength = fFar / 2.0; @@ -123,24 +127,8 @@ void main() float fLightAngle = dot(lightDir, v3SamplePoint) / fHeight; float fCameraAngle = dot(v3Ray, v3SamplePoint) / fHeight; - x = 1.0 - fCameraAngle; - x5 = x * 5.25; - x5p6 = (-6.80 + x5); - xnew = (3.83 + x * x5p6); - xfinal = (0.459 + x * xnew); - xfinal2 = -0.00287 + x * xfinal; - othx = exp( xfinal2 ); - float vscale3 = 0.25 * othx; - - - x = 1.0 - fLightAngle; - x5 = x * 5.25; - x5p6 = (-6.80 + x5); - xnew = (3.83 + x * x5p6); - xfinal = (0.459 + x * xnew); - xfinal2 = -0.00287 + x * xfinal; - othx = exp( xfinal2 ); - float vscale2 = 0.25 * othx; + float vscale3 = vernierScale( fCameraAngle ); + float vscale2 = vernierScale( fLightAngle ); float fScatter = (fStartOffset + fDepth*(vscale2 - vscale3)); vec3 v3Attenuate = exp(-fScatter * (invWaveLength.xyz * rayleigh4PI + mie4PI)); @@ -150,16 +138,24 @@ void main() // Finally, scale the Mie and Rayleigh colors // and set up the varying variables for the pixel shader. - gl_Position = modelView * position; - mieColor.rgb = v3FrontColor * mieBrightness; - mieColor.a = 1.0; - rayleighColor.rgb = v3FrontColor * (invWaveLength.xyz * rayleighBrightness); - rayleighColor.a = 1.0; - v3Direction = newCamPos - v3Pos.xyz; + gl_Position = modelView * IN_position; + OUT_mieColor.rgb = v3FrontColor * mieBrightness; + OUT_mieColor.a = 1.0; + OUT_rayleighColor.rgb = v3FrontColor * (invWaveLength.xyz * rayleighBrightness); + OUT_rayleighColor.a = 1.0; + OUT_v3Direction = newCamPos - v3Pos.xyz; + OUT_pos = IN_position.xyz; - // This offset is to get rid of the black line between the atmosky and the waterPlane - // along the horizon. - zPosition = position.z + 4000.0; - pos = position.xyz; +#ifdef USE_COLORIZE + + OUT_rayleighColor.rgb = desaturate(OUT_rayleighColor.rgb, 1) * colorize.a; + + OUT_rayleighColor.r *= colorize.r; + OUT_rayleighColor.g *= colorize.g; + OUT_rayleighColor.b *= colorize.b; + +#endif + + correctSSP(gl_Position); } diff --git a/Templates/Full/game/shaders/common/gl/torque.glsl b/Templates/Full/game/shaders/common/gl/torque.glsl index dc73a706f..a98ef859f 100644 --- a/Templates/Full/game/shaders/common/gl/torque.glsl +++ b/Templates/Full/game/shaders/common/gl/torque.glsl @@ -117,6 +117,7 @@ mat3x3 quatToMat( vec4 quat ) return mat; } + /// The number of additional substeps we take when refining /// the results of the offset parallax mapping function below. /// @@ -129,19 +130,20 @@ mat3x3 quatToMat( vec4 quat ) /// Performs fast parallax offset mapping using /// multiple refinement steps. -////// @param texMap The texture map whos alpha channel we sample the parallax depth. +/// +/// @param texMap The texture map whos alpha channel we sample the parallax depth. /// @param texCoord The incoming texture coordinate for sampling the parallax depth. /// @param negViewTS The negative view vector in tangent space. /// @param depthScale The parallax factor used to scale the depth result. /// vec2 parallaxOffset( sampler2D texMap, vec2 texCoord, vec3 negViewTS, float depthScale ) { - float depth = texture2D( texMap, texCoord ).a; + float depth = texture( texMap, texCoord ).a; vec2 offset = negViewTS.xy * ( depth * depthScale ); for ( int i=0; i < PARALLAX_REFINE_STEPS; i++ ) { - depth = ( depth + texture2D( texMap, texCoord + offset ).a ) * 0.5; + depth = ( depth + texture( texMap, texCoord + offset ).a ) * 0.5; offset = negViewTS.xy * ( depth * depthScale ); } @@ -151,59 +153,61 @@ vec2 parallaxOffset( sampler2D texMap, vec2 texCoord, vec3 negViewTS, float dept /// The maximum value for 16bit per component integer HDR encoding. const float HDR_RGB16_MAX = 100.0; -/// The maximum value for 10bit per component integer HDR encoding.const float HDR_RGB10_MAX = 4.0; +/// The maximum value for 10bit per component integer HDR encoding. +const float HDR_RGB10_MAX = 4.0; /// Encodes an HDR color for storage into a target. -vec3 hdrEncode( vec3 sample ){ +vec3 hdrEncode( vec3 _sample ) +{ #if defined( TORQUE_HDR_RGB16 ) - return sample / HDR_RGB16_MAX; + return _sample / HDR_RGB16_MAX; #elif defined( TORQUE_HDR_RGB10 ) - return sample / HDR_RGB10_MAX; + return _sample / HDR_RGB10_MAX; #else // No encoding. - return sample; + return _sample; #endif } /// Encodes an HDR color for storage into a target. -vec4 hdrEncode( vec4 sample ) +vec4 hdrEncode( vec4 _sample ) { - return vec4( hdrEncode( sample.rgb ), sample.a ); + return vec4( hdrEncode( _sample.rgb ), _sample.a ); } /// Decodes an HDR color from a target. -vec3 hdrDecode( vec3 sample ) +vec3 hdrDecode( vec3 _sample ) { #if defined( TORQUE_HDR_RGB16 ) - return sample * HDR_RGB16_MAX; + return _sample * HDR_RGB16_MAX; #elif defined( TORQUE_HDR_RGB10 ) - return sample * HDR_RGB10_MAX; + return _sample * HDR_RGB10_MAX; #else // No encoding. - return sample; + return _sample; #endif } /// Decodes an HDR color from a target. -vec4 hdrDecode( vec4 sample ) +vec4 hdrDecode( vec4 _sample ) { - return vec4( hdrDecode( sample.rgb ), sample.a ); + return vec4( hdrDecode( _sample.rgb ), _sample.a ); } /// Returns the luminance for an HDR pixel. -float hdrLuminance( vec3 sample ) +float hdrLuminance( vec3 _sample ) { // There are quite a few different ways to // calculate luminance from an rgb value. @@ -216,7 +220,7 @@ float hdrLuminance( vec3 sample ) // // Max component luminance. // - //float lum = max( sample.r, max( sample.g, sample.b ) ); + //float lum = max( _sample.r, max( _sample.g, _sample.b ) ); //////////////////////////////////////////////////////////////////////////// // The perceptual relative luminance. @@ -224,23 +228,45 @@ float hdrLuminance( vec3 sample ) // See http://en.wikipedia.org/wiki/Luminance_(relative) // const vec3 RELATIVE_LUMINANCE = vec3( 0.2126, 0.7152, 0.0722 ); - float lum = dot( sample, RELATIVE_LUMINANCE ); + float lum = dot( _sample, RELATIVE_LUMINANCE ); //////////////////////////////////////////////////////////////////////////// // // The average component luminance. // //const vec3 AVERAGE_LUMINANCE = vec3( 0.3333, 0.3333, 0.3333 ); - //float lum = dot( sample, AVERAGE_LUMINANCE ); + //float lum = dot( _sample, AVERAGE_LUMINANCE ); return lum; } +#ifdef TORQUE_PIXEL_SHADER +/// Called from the visibility feature to do screen +/// door transparency for fading of objects. +void fizzle(vec2 vpos, float visibility) +{ + // NOTE: The magic values below are what give us + // the nice even pattern during the fizzle. + // + // These values can be changed to get different + // patterns... some better than others. + // + // Horizontal Blinds - { vpos.x, 0.916, vpos.y, 0 } + // Vertical Lines - { vpos.x, 12.9898, vpos.y, 78.233 } + // + // I'm sure there are many more patterns here to + // discover for different effects. + + mat2x2 m = mat2x2( vpos.x, vpos.y, 0.916, 0.350 ); + if( (visibility - fract( determinant( m ) )) < 0 ) //if(a < 0) discard; + discard; +} +#endif //TORQUE_PIXEL_SHADER /// Basic assert macro. If the condition fails, then the shader will output color. /// @param condition This should be a bvec[2-4]. If any items is false, condition is considered to fail. /// @param color The color that should be outputted if the condition fails. /// @note This macro will only work in the void main() method of a pixel shader. -#define assert(condition, color) { if(!any(condition)) { gl_FragColor = color; return; } } +#define assert(condition, color) { if(!any(condition)) { OUT_FragColor0 = color; return; } } #endif // _TORQUE_GLSL_ diff --git a/Templates/Full/game/shaders/common/gl/wavesP.glsl b/Templates/Full/game/shaders/common/gl/wavesP.glsl index 24bd8cbb4..ddb683947 100644 --- a/Templates/Full/game/shaders/common/gl/wavesP.glsl +++ b/Templates/Full/game/shaders/common/gl/wavesP.glsl @@ -28,10 +28,10 @@ uniform float specularPower; uniform vec4 ambient; uniform float accumTime; -varying vec2 TEX0; -varying vec4 outLightVec; -varying vec3 outPos; -varying vec3 outEyePos; +in vec2 TEX0; +in vec4 outLightVec; +in vec3 outPos; +in vec3 outEyePos; void main() { @@ -42,14 +42,14 @@ void main() texOffset.x = TEX0.x + sinOffset1 + sinOffset2; texOffset.y = TEX0.y + cos( accumTime * 3.0 + TEX0.x * 6.28319 * 2.0 ) * 0.05; - vec4 bumpNorm = texture2D(bumpMap, texOffset) * 2.0 - 1.0; - vec4 diffuse = texture2D(diffMap, texOffset); + vec4 bumpNorm = texture(bumpMap, texOffset) * 2.0 - 1.0; + vec4 diffuse = texture(diffMap, texOffset); - gl_FragColor = diffuse * (clamp(dot(outLightVec.xyz, bumpNorm.xyz), 0.0, 1.0) + ambient); + OUT_FragColor0 = diffuse * (clamp(dot(outLightVec.xyz, bumpNorm.xyz), 0.0, 1.0) + ambient); vec3 eyeVec = normalize(outEyePos - outPos); vec3 halfAng = normalize(eyeVec + outLightVec.xyz); float specular = clamp(dot(bumpNorm.xyz, halfAng), 0.0, 1.0) * outLightVec.w; specular = pow(specular, specularPower); - gl_FragColor += specularColor * specular; + OUT_FragColor0 += specularColor * specular; } diff --git a/Templates/Full/game/shaders/common/lighting/advanced/gl/convexGeometryV.glsl b/Templates/Full/game/shaders/common/lighting/advanced/gl/convexGeometryV.glsl index 6d3e36e7e..1807ac43f 100644 --- a/Templates/Full/game/shaders/common/lighting/advanced/gl/convexGeometryV.glsl +++ b/Templates/Full/game/shaders/common/lighting/advanced/gl/convexGeometryV.glsl @@ -20,16 +20,33 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- -varying vec4 wsEyeDir; -varying vec4 ssPos; +#include "../../../gl/hlslCompat.glsl" + +in vec4 vPosition; + +#define IN_pos vPosition + +out vec4 wsEyeDir; +out vec4 ssPos; +out vec4 vsEyeDir; + +#define OUT_hpos gl_Position +#define OUT_wsEyeDir wsEyeDir +#define OUT_ssPos ssPos +#define OUT_vsEyeDir vsEyeDir uniform mat4 modelview; uniform mat4 objTrans; +uniform mat4 worldViewOnly; uniform vec3 eyePosWorld; void main() { - gl_Position = modelview * gl_Vertex; - wsEyeDir = objTrans * gl_Vertex - vec4( eyePosWorld, 0.0 ); - ssPos = gl_Position; + OUT_hpos = tMul( modelview, IN_pos ); + OUT_wsEyeDir = tMul( objTrans, IN_pos ) - vec4( eyePosWorld, 0.0 ); + OUT_vsEyeDir = tMul( worldViewOnly, IN_pos ); + OUT_ssPos = OUT_hpos; + + correctSSP(gl_Position); } + diff --git a/Templates/Full/game/shaders/common/lighting/advanced/gl/dbgDepthVisualizeP.glsl b/Templates/Full/game/shaders/common/lighting/advanced/gl/dbgDepthVisualizeP.glsl index 4a954ae84..e3ee59c8a 100644 --- a/Templates/Full/game/shaders/common/lighting/advanced/gl/dbgDepthVisualizeP.glsl +++ b/Templates/Full/game/shaders/common/lighting/advanced/gl/dbgDepthVisualizeP.glsl @@ -20,14 +20,15 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- +#include "../../../gl/hlslCompat.glsl" #include "shadergen:/autogenConditioners.h" -varying vec2 uv0; +in vec2 uv0; uniform sampler2D prepassBuffer; uniform sampler1D depthViz; void main() { float depth = prepassUncondition( prepassBuffer, uv0 ).w; - gl_FragColor = vec4( texture1D( depthViz, depth ).rgb, 1 ); + OUT_FragColor0 = vec4( texture( depthViz, depth ).rgb, 1.0 ); } \ No newline at end of file diff --git a/Templates/Full/game/shaders/common/lighting/advanced/gl/dbgLightColorVisualizeP.glsl b/Templates/Full/game/shaders/common/lighting/advanced/gl/dbgLightColorVisualizeP.glsl index 580204487..aa17df4d6 100644 --- a/Templates/Full/game/shaders/common/lighting/advanced/gl/dbgLightColorVisualizeP.glsl +++ b/Templates/Full/game/shaders/common/lighting/advanced/gl/dbgLightColorVisualizeP.glsl @@ -20,15 +20,16 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- +#include "../../../gl/hlslCompat.glsl" #include "shadergen:/autogenConditioners.h" -varying vec2 uv0; +in vec2 uv0; uniform sampler2D lightInfoBuffer; void main() { - vec3 lightcolor; + vec3 lightcolor; float nl_Att, specular; - lightinfoUncondition( texture2DLod( lightInfoBuffer, uv0 ), lightcolor, nl_Att, specular ); - gl_FragColor = vec4( lightcolor, 1.0 ); + lightinfoUncondition( texture( lightInfoBuffer, uv0 ), lightcolor, nl_Att, specular ); + OUT_FragColor0 = vec4( lightcolor, 1.0 ); } \ No newline at end of file diff --git a/Templates/Full/game/shaders/common/lighting/advanced/gl/dbgLightSpecularVisualizeP.glsl b/Templates/Full/game/shaders/common/lighting/advanced/gl/dbgLightSpecularVisualizeP.glsl index 6f7c52486..e549922ff 100644 --- a/Templates/Full/game/shaders/common/lighting/advanced/gl/dbgLightSpecularVisualizeP.glsl +++ b/Templates/Full/game/shaders/common/lighting/advanced/gl/dbgLightSpecularVisualizeP.glsl @@ -20,15 +20,16 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- +#include "../../../gl/hlslCompat.glsl" #include "shadergen:/autogenConditioners.h" -varying vec2 uv0; +in vec2 uv0; uniform sampler2D lightInfoBuffer; void main() { - vec3 lightcolor; + vec3 lightcolor; float nl_Att, specular; - lightinfoUncondition( texture2DLod( lightInfoBuffer, uv0 ), lightcolor, nl_Att, specular ); - gl_FragColor = vec4( specular, specular, specular, 1.0 ); + lightinfoUncondition( texture( lightInfoBuffer, uv0 ), lightcolor, nl_Att, specular ); + OUT_FragColor0 = vec4( specular, specular, specular, 1.0 ); } \ No newline at end of file diff --git a/Templates/Full/game/shaders/common/lighting/advanced/gl/dbgNormalVisualizeP.glsl b/Templates/Full/game/shaders/common/lighting/advanced/gl/dbgNormalVisualizeP.glsl index 96b645524..f61706393 100644 --- a/Templates/Full/game/shaders/common/lighting/advanced/gl/dbgNormalVisualizeP.glsl +++ b/Templates/Full/game/shaders/common/lighting/advanced/gl/dbgNormalVisualizeP.glsl @@ -20,14 +20,14 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- +#include "../../../gl/hlslCompat.glsl" #include "shadergen:/autogenConditioners.h" - -varying vec2 uv0; -uniform sampler2D prepassTex; +in vec2 uv0; +uniform sampler2D prepassBuffer; void main() { - vec3 normal = prepassUncondition( prepassTex, uv0 ).xyz; - gl_FragColor = vec4( ( normal + 1.0 ) * 0.5, 1.0 ); + vec3 normal = prepassUncondition( prepassBuffer, uv0 ).xyz; + OUT_FragColor0 = vec4( ( normal + 1.0 ) * 0.5, 1.0 ); } \ No newline at end of file diff --git a/Templates/Full/game/shaders/common/lighting/advanced/gl/dbgShadowVisualizeP.glsl b/Templates/Full/game/shaders/common/lighting/advanced/gl/dbgShadowVisualizeP.glsl index 51609fc6b..e997950ab 100644 --- a/Templates/Full/game/shaders/common/lighting/advanced/gl/dbgShadowVisualizeP.glsl +++ b/Templates/Full/game/shaders/common/lighting/advanced/gl/dbgShadowVisualizeP.glsl @@ -19,13 +19,14 @@ // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. //----------------------------------------------------------------------------- +#include "../../../gl/hlslCompat.glsl" -varying vec2 uv0; +in vec2 uv0; uniform sampler2D shadowMap; uniform sampler1D depthViz; void main() { - float depth = clamp( texture2DLod( shadowMap, uv0, 0 ).r, 0.0, 1.0 ); - gl_FragColor = vec4( texture1D( depthViz, depth ).rgb, 1.0 ); + float depth = saturate( texture( shadowMap, uv0 ).r ); + OUT_FragColor0 = vec4( texture( depthViz, depth ).rgb, 1 ); } \ No newline at end of file diff --git a/Templates/Full/game/shaders/common/lighting/advanced/gl/farFrustumQuad.glsl b/Templates/Full/game/shaders/common/lighting/advanced/gl/farFrustumQuad.glsl index 866a39b0b..76054eb09 100644 --- a/Templates/Full/game/shaders/common/lighting/advanced/gl/farFrustumQuad.glsl +++ b/Templates/Full/game/shaders/common/lighting/advanced/gl/farFrustumQuad.glsl @@ -24,7 +24,7 @@ vec2 getUVFromSSPos( vec3 ssPos, vec4 rtParams ) { vec2 outPos = ( ssPos.xy + 1.0 ) / 2.0; + outPos.y = 1.0 - outPos.y; outPos = ( outPos * rtParams.zw ) + rtParams.xy; - //outPos.y = 1.0 - outPos.y; return outPos; } diff --git a/Templates/Full/game/shaders/common/lighting/advanced/gl/farFrustumQuadV.glsl b/Templates/Full/game/shaders/common/lighting/advanced/gl/farFrustumQuadV.glsl index ce5c2ad81..a80e856ed 100644 --- a/Templates/Full/game/shaders/common/lighting/advanced/gl/farFrustumQuadV.glsl +++ b/Templates/Full/game/shaders/common/lighting/advanced/gl/farFrustumQuadV.glsl @@ -20,24 +20,32 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- +#include "../../../gl/hlslCompat.glsl" #include "farFrustumQuad.glsl" -uniform vec4 renderTargetParams; - -varying vec4 hpos; -varying vec2 uv0; -varying vec3 wsEyeRay; +in vec4 vPosition; +in vec3 vNormal; +in vec3 vTangent; +in vec2 vTexCoord0; +uniform vec4 rtParams0; +out vec4 hpos; +out vec2 uv0; +out vec3 wsEyeRay; +out vec3 vsEyeRay; void main() -{ - // Expand the SS coordinate (stored in uv0) - hpos = vec4( gl_MultiTexCoord0.st * 2.0 - 1.0, 1.0, 1.0 ); - gl_Position = hpos; - +{ + hpos = vec4( vTexCoord0, 0, 1 ); + // Get a RT-corrected UV from the SS coord - uv0 = getUVFromSSPos( hpos.xyz, renderTargetParams ); + uv0 = getUVFromSSPos( hpos.xyz, rtParams0 ); + gl_Position = hpos; - // Interpolators will generate eye ray from far-frustum corners - wsEyeRay = gl_Vertex.xyz; + // Interpolators will generate eye rays the + // from far-frustum corners. + wsEyeRay = vTangent; + vsEyeRay = vNormal; + + correctSSP(gl_Position); } diff --git a/Templates/Full/game/shaders/common/lighting/advanced/gl/pointLightP.glsl b/Templates/Full/game/shaders/common/lighting/advanced/gl/pointLightP.glsl index b135f1aa8..c0610508b 100644 --- a/Templates/Full/game/shaders/common/lighting/advanced/gl/pointLightP.glsl +++ b/Templates/Full/game/shaders/common/lighting/advanced/gl/pointLightP.glsl @@ -21,34 +21,26 @@ //----------------------------------------------------------------------------- #include "../../../gl/hlslCompat.glsl" -#include "farFrustumQuad.glsl" -#include "lightingUtils.glsl" -#include "../../shadowMap/shadowMapIO_GLSL.h" #include "shadergen:/autogenConditioners.h" +#include "farFrustumQuad.glsl" +#include "lightingUtils.glsl" +#include "../../../gl/lighting.glsl" +#include "../../shadowMap/shadowMapIO_GLSL.h" +#include "softShadow.glsl" -#if TORQUE_SM >= 30 +in vec4 wsEyeDir; +in vec4 ssPos; +in vec4 vsEyeDir; - // Enables high quality soft shadow - // filtering for SM3.0 and above. - #define SOFTSHADOW_SM3 - - #include "softShadow.glsl" - -#else +#ifdef USE_COOKIE_TEX +/// The texture for cookie rendering. +uniform samplerCube cookieMap ; #endif - -// I am not sure if we should do this in a better way -//#define SHADOW_CUBE -//#define SHADOW_PARABOLOID -#define SHADOW_DUALPARABOLOID -#define SHADOW_DUALPARABOLOID_SINGLE_PASS - - #ifdef SHADOW_CUBE vec3 decodeShadowCoord( vec3 shadowCoord ) @@ -56,39 +48,47 @@ return shadowCoord; } - vec4 shadowSample( samplerCUBE shadowMap, vec3 shadowCoord ) + vec4 shadowSample( samplerCube shadowMap, vec3 shadowCoord ) { - return textureCUBE( shadowMap, shadowCoord ); + return texture( shadowMap, shadowCoord ); } - -#elif defined( SHADOW_DUALPARABOLOID ) + +#else vec3 decodeShadowCoord( vec3 paraVec ) { - // Swizzle z and y + // Flip y and z paraVec = paraVec.xzy; - #ifdef SHADOW_DUALPARABOLOID_SINGLE_PASS + #ifndef SHADOW_PARABOLOID bool calcBack = (paraVec.z < 0.0); - if(calcBack) + if ( calcBack ) + { paraVec.z = paraVec.z * -1.0; + + #ifdef SHADOW_DUALPARABOLOID + paraVec.x = -paraVec.x; + #endif + } #endif vec3 shadowCoord; - shadowCoord.x = (paraVec.x / (2.0*(1.0 + paraVec.z))) + 0.5; - shadowCoord.y = ((paraVec.y / (2.0*(1.0 + paraVec.z))) + 0.5); + shadowCoord.x = (paraVec.x / (2*(1 + paraVec.z))) + 0.5; + shadowCoord.y = 1-((paraVec.y / (2*(1 + paraVec.z))) + 0.5); shadowCoord.z = 0; // adjust the co-ordinate slightly if it is near the extent of the paraboloid // this value was found via experementation - shadowCoord.xy *= 0.997; + // NOTE: this is wrong, it only biases in one direction, not towards the uv + // center ( 0.5 0.5 ). + //shadowCoord.xy *= 0.997; - #ifdef SHADOW_DUALPARABOLOID_SINGLE_PASS + #ifndef SHADOW_PARABOLOID // If this is the back, offset in the atlas - if(calcBack) + if ( calcBack ) shadowCoord.x += 1.0; // Atlasing front and back maps, so scale @@ -99,51 +99,35 @@ return shadowCoord; } -#else - - #error Unknown shadow type! - #endif -varying vec4 wsEyeDir; -varying vec4 ssPos; - - uniform sampler2D prePassBuffer; #ifdef SHADOW_CUBE - uniform samplerCube shadowMap; + uniform samplerCube shadowMap; #else - uniform sampler2D shadowMap; -#endif -#ifdef ACCUMULATE_LUV - uniform sampler2D scratchTarget; + uniform sampler2D shadowMap; #endif -uniform vec4 renderTargetParams; +uniform vec4 rtParams0; uniform vec3 lightPosition; uniform vec4 lightColor; -uniform float lightBrightness; -uniform float lightRange; +uniform float lightBrightness; +uniform float lightRange; uniform vec2 lightAttenuation; uniform vec4 lightMapParams; - -uniform vec3 eyePosWorld; -uniform vec4 farPlane; -uniform float negFarPlaneDotEye; -uniform mat3x3 worldToLightProj; - +uniform vec4 vsFarPlane; +uniform mat3 viewToLightProj; uniform vec4 lightParams; uniform float shadowSoftness; -uniform float constantSpecularPower; + - -void main() -{ +void main() +{ // Compute scene UV - vec3 ssPosP = ssPos.xyz / ssPos.w; - vec2 uvScene = getUVFromSSPos( ssPosP, renderTargetParams ); + vec3 ssPos = ssPos.xyz / ssPos.w; + vec2 uvScene = getUVFromSSPos( ssPos, rtParams0 ); // Sample/unpack the normal/z data vec4 prepassSample = prepassUncondition( prePassBuffer, uvScene ); @@ -151,21 +135,17 @@ void main() float depth = prepassSample.a; // Eye ray - Eye -> Pixel - vec3 eyeRay = getDistanceVectorToPlane( negFarPlaneDotEye, wsEyeDir.xyz / wsEyeDir.w , farPlane ); - - // Get world space pixel position - vec3 worldPos = eyePosWorld + eyeRay * depth; + vec3 eyeRay = getDistanceVectorToPlane( -vsFarPlane.w, vsEyeDir.xyz, vsFarPlane ); + vec3 viewSpacePos = eyeRay * depth; // Build light vec, get length, clip pixel if needed - vec3 lightVec = lightPosition - worldPos; + vec3 lightVec = lightPosition - viewSpacePos; float lenLightV = length( lightVec ); - if ( lightRange - lenLightV < 0.0 ) - discard; - + clip( lightRange - lenLightV ); + // Get the attenuated falloff. float atten = attenuate( lightColor, lightAttenuation, lenLightV ); - if ( atten - 1e-6 < 0.0 ) - discard; + clip( atten - 1e-6 ); // Normalize lightVec lightVec /= lenLightV; @@ -181,61 +161,73 @@ void main() #else - // Convert the light vector into a shadow map - // here once instead of in the filtering loop. - vec4 shadowCoord = vec4(0.0); - #ifdef SHADOW_CUBE - shadowCoord.xy = decodeShadowCoord( -lightVec ); - #else - shadowCoord.xy = decodeShadowCoord( worldToLightProj * -lightVec ).xy; - #endif - // Get a linear depth from the light source. - float distToLight = lenLightV / lightRange; + float distToLight = lenLightV / lightRange; - #ifdef SOFTSHADOW_SM3 + #ifdef SHADOW_CUBE + + // TODO: We need to fix shadow cube to handle soft shadows! + float occ = texture( shadowMap, tMul( viewToLightProj, -lightVec ) ).r; + float shadowed = saturate( exp( lightParams.y * ( occ - distToLight ) ) ); + + #else + vec2 shadowCoord = decodeShadowCoord( tMul( viewToLightProj, -lightVec ) ).xy; + float shadowed = softShadow_filter( shadowMap, - gTapRotationTex, - ssPosP.xy, - shadowCoord.xy, + ssPos.xy, + shadowCoord, shadowSoftness, distToLight, nDotL, lightParams.y ); - - #else // !SOFTSHADOW_SM3 - - // TODO: Implement the SM2 lower quality - // shadow filtering method. #endif #endif // !NO_SHADOW - + + #ifdef USE_COOKIE_TEX + + // Lookup the cookie sample. + vec4 cookie = texture( cookieMap, tMul( viewToLightProj, -lightVec ) ); + + // Multiply the light with the cookie tex. + lightColor.rgb *= cookie.rgb; + + // Use a maximum channel luminance to attenuate + // the lighting else we get specular in the dark + // regions of the cookie texture. + atten *= max( cookie.r, max( cookie.g, cookie.b ) ); + + #endif + // NOTE: Do not clip on fully shadowed pixels as it would // cause the hardware occlusion query to disable the shadow. // Specular term - float specular = calcSpecular( lightVec, - normal, - normalize( -eyeRay ), - constantSpecularPower, - shadowed * atten * lightBrightness ); - - // N.L * Attenuation - float Sat_NL_Att = clamp( nDotL * atten * shadowed, 0.0, 1.0 ); - - // In LUV color mode we need to blend in the - // output from the previous target. - vec4 previousPix = vec4(0.0); - #ifdef ACCUMULATE_LUV - previousPix = texture2DLod( scratchTarget, uvScene, 0 ); - #endif + float specular = AL_CalcSpecular( lightVec, + normal, + normalize( -eyeRay ) ) * lightBrightness * atten * shadowed; - // Output - gl_FragColor = lightinfoCondition( lightColor.rgb * lightBrightness, - Sat_NL_Att, - specular, - previousPix ) * lightMapParams; + float Sat_NL_Att = saturate( nDotL * atten * shadowed ) * lightBrightness; + vec3 lightColorOut = lightMapParams.rgb * lightColor.rgb; + vec4 addToResult = vec4(0.0); + + // TODO: This needs to be removed when lightmapping is disabled + // as its extra work per-pixel on dynamic lit scenes. + // + // Special lightmapping pass. + if ( lightMapParams.a < 0.0 ) + { + // This disables shadows on the backsides of objects. + shadowed = nDotL < 0.0f ? 1.0f : shadowed; + + Sat_NL_Att = 1.0f; + shadowed = mix( 1.0f, shadowed, atten ); + lightColorOut = vec3(shadowed); + specular *= lightBrightness; + addToResult = ( 1.0 - shadowed ) * abs(lightMapParams); + } + + OUT_FragColor0 = lightinfoCondition( lightColorOut, Sat_NL_Att, specular, addToResult ); } diff --git a/Templates/Full/game/shaders/common/lighting/advanced/gl/softShadow.glsl b/Templates/Full/game/shaders/common/lighting/advanced/gl/softShadow.glsl index 8ef09ed2f..a14213946 100644 --- a/Templates/Full/game/shaders/common/lighting/advanced/gl/softShadow.glsl +++ b/Templates/Full/game/shaders/common/lighting/advanced/gl/softShadow.glsl @@ -19,113 +19,141 @@ // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. //----------------------------------------------------------------------------- - - -#define NUM_TAPS 12 - -#define NUM_PRE_TAPS 4 - -/// The non-uniform poisson disk used in the -/// high quality shadow filtering. -vec2 sNonUniformTaps[NUM_TAPS]; -void initNonUniformTaps() + +#if defined( SOFTSHADOW ) && defined( SOFTSHADOW_HIGH_QUALITY ) + +#define NUM_PRE_TAPS 4 +#define NUM_TAPS 12 + +/// The non-uniform poisson disk used in the +/// high quality shadow filtering. +vec2 sNonUniformTaps[NUM_TAPS] = vec2[] +( + // These first 4 taps are located around the edges + // of the disk and are used to predict fully shadowed + // or unshadowed areas. + vec2( 0.992833, 0.979309 ), + vec2( -0.998585, 0.985853 ), + vec2( 0.949299, -0.882562 ), + vec2( -0.941358, -0.893924 ), + + // The rest of the samples. + vec2( 0.545055, -0.589072 ), + vec2( 0.346526, 0.385821 ), + vec2( -0.260183, 0.334412 ), + vec2( 0.248676, -0.679605 ), + vec2( -0.569502, -0.390637 ), + vec2( -0.614096, 0.212577 ), + vec2( -0.259178, 0.876272 ), + vec2( 0.649526, 0.864333 ) +); + +#else + +#define NUM_PRE_TAPS 5 + +/// The non-uniform poisson disk used in the +/// high quality shadow filtering. +vec2 sNonUniformTaps[NUM_PRE_TAPS] = vec2[] +( + vec2( 0.892833, 0.959309 ), + vec2( -0.941358, -0.873924 ), + vec2( -0.260183, 0.334412 ), + vec2( 0.348676, -0.679605 ), + vec2( -0.569502, -0.390637 ) +); + +#endif + + +/// The texture used to do per-pixel pseudorandom +/// rotations of the filter taps. +uniform sampler2D gTapRotationTex ; + + +float softShadow_sampleTaps( sampler2D shadowMap, + vec2 sinCos, + vec2 shadowPos, + float filterRadius, + float distToLight, + float esmFactor, + int startTap, + int endTap ) { - // These first 4 taps are located around the edges - // of the disk and are used to predict fully shadowed - // or unshadowed areas. - sNonUniformTaps[0] = vec2( 0.992833, 0.979309 ); - sNonUniformTaps[1] = vec2( -0.998585, 0.985853 ); - sNonUniformTaps[2] = vec2( 0.949299, -0.882562 ); - sNonUniformTaps[3] = vec2( -0.941358, -0.893924 ); - - // The rest of the samples. - sNonUniformTaps[4] = vec2( 0.545055, -0.589072 ); - sNonUniformTaps[5] = vec2( 0.346526, 0.385821 ); - sNonUniformTaps[6] = vec2( -0.260183, 0.334412 ); - sNonUniformTaps[7] = vec2( 0.248676, -0.679605 ); - sNonUniformTaps[8] = vec2( -0.569502, -0.390637 ); - sNonUniformTaps[9] = vec2( -0.014096, 0.012577 ); - sNonUniformTaps[10] = vec2( -0.259178, 0.876272 ); - sNonUniformTaps[11] = vec2( 0.649526, 0.664333 ); + float shadow = 0; + + vec2 tap = vec2(0); + for ( int t = startTap; t < endTap; t++ ) + { + tap.x = ( sNonUniformTaps[t].x * sinCos.y - sNonUniformTaps[t].y * sinCos.x ) * filterRadius; + tap.y = ( sNonUniformTaps[t].y * sinCos.y + sNonUniformTaps[t].x * sinCos.x ) * filterRadius; + float occluder = tex2Dlod( shadowMap, vec4( shadowPos + tap, 0, 0 ) ).r; + + float esm = saturate( exp( esmFactor * ( occluder - distToLight ) ) ); + shadow += esm / float( endTap - startTap ); + } + + return shadow; } - -/// The texture used to do per-pixel pseudorandom -/// rotations of the filter taps. -uniform sampler2D gTapRotationTex; - - -float softShadow_sampleTaps( sampler2D shadowMap, - vec2 sinCos, - vec2 shadowPos, - float filterRadius, - float distToLight, - float esmFactor, - int startTap, - int endTap ) -{ - initNonUniformTaps(); - float shadow = 0.0; - - vec2 tap = vec2(0.0); - for ( int t = startTap; t < endTap; t++ ) - { - tap.x = ( sNonUniformTaps[t].x * sinCos.y - sNonUniformTaps[t].y * sinCos.x ) * filterRadius; - tap.y = ( sNonUniformTaps[t].y * sinCos.y + sNonUniformTaps[t].x * sinCos.x ) * filterRadius; - float occluder = texture2DLod( shadowMap, shadowPos + tap, 0.0 ).r; - - float esm = clamp( exp( esmFactor * ( occluder - distToLight ) ), 0.0, 1.0 ); - shadow += esm / float( endTap - startTap ); - } - - return shadow; -} - - -// HACK! HACK! HACK! -// We take the noise texture directly as the second parameter to ensure that it -// is the "last used" sampler, and thus doesn't collide with the prepass buffer -// or shadow map. If we use gTapRotationTex directly here, then it is the first -// used sampler and will collide with the prepass buffer. -float softShadow_filter( sampler2D shadowMap, - sampler2D noiseTexture, - vec2 vpos, - vec2 shadowPos, - float filterRadius, - float distToLight, - float dotNL, - float esmFactor ) -{ - // Lookup the random rotation for this screen pixel. - vec2 sinCos = ( texture2DLod( noiseTexture, vpos * 16.0, 0.0 ).rg - 0.5 ) * 2.0; - - // Do the prediction taps first. - float shadow = softShadow_sampleTaps( shadowMap, - sinCos, - shadowPos, - filterRadius, - distToLight, - esmFactor, - 0, - NUM_PRE_TAPS ); - - // Only do the expensive filtering if we're really - // in a partially shadowed area. - if ( shadow * ( 1.0 - shadow ) * max( dotNL, 0.0 ) > 0.06 ) - { - shadow += softShadow_sampleTaps( shadowMap, - sinCos, - shadowPos, - filterRadius, - distToLight, - esmFactor, - NUM_PRE_TAPS, - NUM_TAPS ); - - // This averages the taps above with the results - // of the prediction samples. - shadow *= 0.5; - } - - return shadow; -} \ No newline at end of file + + +float softShadow_filter( sampler2D shadowMap, + vec2 vpos, + vec2 shadowPos, + float filterRadius, + float distToLight, + float dotNL, + float esmFactor ) +{ + #ifndef SOFTSHADOW + + // If softshadow is undefined then we skip any complex + // filtering... just do a single sample ESM. + + float occluder = tex2Dlod( shadowMap, vec4( shadowPos, 0, 0 ) ).r; + float shadow = saturate( exp( esmFactor * ( occluder - distToLight ) ) ); + + #else + + // Lookup the random rotation for this screen pixel. + vec2 sinCos = ( tex2Dlod( gTapRotationTex, vec4( vpos * 16, 0, 0 ) ).rg - 0.5 ) * 2; + + // Do the prediction taps first. + float shadow = softShadow_sampleTaps( shadowMap, + sinCos, + shadowPos, + filterRadius, + distToLight, + esmFactor, + 0, + NUM_PRE_TAPS ); + + // We live with only the pretap results if we don't + // have high quality shadow filtering enabled. + #ifdef SOFTSHADOW_HIGH_QUALITY + + // Only do the expensive filtering if we're really + // in a partially shadowed area. + if ( shadow * ( 1.0 - shadow ) * max( dotNL, 0 ) > 0.06 ) + { + shadow += softShadow_sampleTaps( shadowMap, + sinCos, + shadowPos, + filterRadius, + distToLight, + esmFactor, + NUM_PRE_TAPS, + NUM_TAPS ); + + // This averages the taps above with the results + // of the prediction samples. + shadow *= 0.5; + } + + #endif // SOFTSHADOW_HIGH_QUALITY + + #endif // SOFTSHADOW + + return shadow; +} \ No newline at end of file diff --git a/Templates/Full/game/shaders/common/lighting/advanced/gl/spotLightP.glsl b/Templates/Full/game/shaders/common/lighting/advanced/gl/spotLightP.glsl index d29f5edb0..c07be1f34 100644 --- a/Templates/Full/game/shaders/common/lighting/advanced/gl/spotLightP.glsl +++ b/Templates/Full/game/shaders/common/lighting/advanced/gl/spotLightP.glsl @@ -25,58 +25,49 @@ #include "lightingUtils.glsl" #include "../../shadowMap/shadowMapIO_GLSL.h" #include "shadergen:/autogenConditioners.h" +#include "softShadow.glsl" +#include "../../../gl/lighting.glsl" +in vec4 wsEyeDir; +in vec4 ssPos; +in vec4 vsEyeDir; -#if TORQUE_SM >= 30 +#define IN_wsEyeDir wsEyeDir +#define IN_ssPos ssPos +#define IN_vsEyeDir vsEyeDir - // Enables high quality soft shadow - // filtering for SM3.0 and above. - #define SOFTSHADOW_SM3 - - #include "softShadow.glsl" - -#else +#ifdef USE_COOKIE_TEX +/// The texture for cookie rendering. +uniform sampler2D cookieMap; #endif - -varying vec4 ssPos; -varying vec4 wsEyeDir; - - uniform sampler2D prePassBuffer; uniform sampler2D shadowMap; -#ifdef ACCUMULATE_LUV - uniform sampler2D scratchTarget; -#endif -uniform vec4 renderTargetParams; +uniform vec4 rtParams0; uniform vec3 lightPosition; uniform vec4 lightColor; -uniform float lightBrightness; -uniform float lightRange; +uniform float lightBrightness; +uniform float lightRange; uniform vec2 lightAttenuation; uniform vec3 lightDirection; uniform vec4 lightSpotParams; uniform vec4 lightMapParams; -uniform vec3 eyePosWorld; -uniform vec4 farPlane; -uniform float negFarPlaneDotEye; -uniform mat4x4 worldToLightProj; +uniform vec4 vsFarPlane; +uniform mat4 viewToLightProj; uniform vec4 lightParams; uniform float shadowSoftness; -uniform float constantSpecularPower; - void main() -{ +{ // Compute scene UV - vec3 ssPosP = ssPos.xyz / ssPos.w; - vec2 uvScene = getUVFromSSPos( ssPosP, renderTargetParams ); + vec3 ssPos = IN_ssPos.xyz / IN_ssPos.w; + vec2 uvScene = getUVFromSSPos( ssPos, rtParams0 ); // Sample/unpack the normal/z data vec4 prepassSample = prepassUncondition( prePassBuffer, uvScene ); @@ -84,85 +75,92 @@ void main() float depth = prepassSample.a; // Eye ray - Eye -> Pixel - vec3 eyeRay = getDistanceVectorToPlane( negFarPlaneDotEye, wsEyeDir.xyz / wsEyeDir.w , farPlane ); - - // Get world space pixel position - vec3 worldPos = eyePosWorld + eyeRay * depth; + vec3 eyeRay = getDistanceVectorToPlane( -vsFarPlane.w, IN_vsEyeDir.xyz, vsFarPlane ); + vec3 viewSpacePos = eyeRay * depth; // Build light vec, get length, clip pixel if needed - vec3 lightToPxlVec = worldPos - lightPosition; + vec3 lightToPxlVec = viewSpacePos - lightPosition; float lenLightV = length( lightToPxlVec ); lightToPxlVec /= lenLightV; - //lightDirection = float3( -lightDirection.xy, lightDirection.z ); //float3( 0, 0, -1 ); + //lightDirection = vec3( -lightDirection.xy, lightDirection.z ); //vec3( 0, 0, -1 ); float cosAlpha = dot( lightDirection, lightToPxlVec ); - if ( cosAlpha - lightSpotParams.x < 0.0 ) discard; - if ( lightRange - lenLightV < 0.0 ) discard; + clip( cosAlpha - lightSpotParams.x ); + clip( lightRange - lenLightV ); float atten = attenuate( lightColor, lightAttenuation, lenLightV ); atten *= ( cosAlpha - lightSpotParams.x ) / lightSpotParams.y; - if ( atten - 1e-6 < 0.0 ) discard; + clip( atten - 1e-6 ); + atten = saturate( atten ); float nDotL = dot( normal, -lightToPxlVec ); + // Get the shadow texture coordinate + vec4 pxlPosLightProj = tMul( viewToLightProj, vec4( viewSpacePos, 1 ) ); + vec2 shadowCoord = ( ( pxlPosLightProj.xy / pxlPosLightProj.w ) * 0.5 ) + vec2( 0.5, 0.5 ); + shadowCoord.y = 1.0f - shadowCoord.y; + #ifdef NO_SHADOW float shadowed = 1.0; #else - // Find Shadow coordinate - vec4 pxlPosLightProj = vec4( worldToLightProj * vec4( worldPos, 1.0 ) ); - vec2 shadowCoord = ( ( pxlPosLightProj.xy / pxlPosLightProj.w ) * 0.5 ) + vec2( 0.5, 0.5 ); - // Get a linear depth from the light source. float distToLight = pxlPosLightProj.z / lightRange; - #ifdef SOFTSHADOW_SM3 - - float shadowed = softShadow_filter( shadowMap, - gTapRotationTex, - ssPosP.xy, - shadowCoord, - shadowSoftness, - distToLight, - nDotL, - lightParams.y ); - - #else // !SOFTSHADOW_SM3 - - // Simple exponential shadow map. - float occluder = decodeShadowMap( texture2DLod( shadowMap, shadowCoord, 0.0 ) ); - float esmFactor = lightParams.y; - float shadowed = clamp( exp( esmFactor * ( occluder - distToLight ) ), 0.0, 1.0 ); - - #endif + float shadowed = softShadow_filter( shadowMap, + ssPos.xy, + shadowCoord, + shadowSoftness, + distToLight, + nDotL, + lightParams.y ); #endif // !NO_SHADOW - + + #ifdef USE_COOKIE_TEX + + // Lookup the cookie sample. + vec4 cookie = texture( cookieMap, shadowCoord ); + + // Multiply the light with the cookie tex. + lightColor.rgb *= cookie.rgb; + + // Use a maximum channel luminance to attenuate + // the lighting else we get specular in the dark + // regions of the cookie texture. + atten *= max( cookie.r, max( cookie.g, cookie.b ) ); + + #endif + // NOTE: Do not clip on fully shadowed pixels as it would // cause the hardware occlusion query to disable the shadow. // Specular term - float specular = calcSpecular( -lightToPxlVec, - normal, - normalize( -eyeRay ), - constantSpecularPower, - shadowed * atten * lightBrightness ); - - // N.L * Attenuation - float Sat_NL_Att = clamp( nDotL * atten * shadowed, 0.0, 1.0 ); - - // In LUV color mode we need to blend in the - // output from the previous target. - vec4 previousPix = vec4(0.0); - #ifdef ACCUMULATE_LUV - previousPix = texture2DLod( scratchTarget, uvScene, 0.0 ); - #endif + float specular = AL_CalcSpecular( -lightToPxlVec, + normal, + normalize( -eyeRay ) ) * lightBrightness * atten * shadowed; - // Output - gl_FragColor = lightinfoCondition( lightColor.rgb * lightBrightness, - Sat_NL_Att, - specular, - previousPix ) * lightMapParams; + float Sat_NL_Att = saturate( nDotL * atten * shadowed ) * lightBrightness; + vec3 lightColorOut = lightMapParams.rgb * lightColor.rgb; + vec4 addToResult = vec4(0.0); + + // TODO: This needs to be removed when lightmapping is disabled + // as its extra work per-pixel on dynamic lit scenes. + // + // Special lightmapping pass. + if ( lightMapParams.a < 0.0 ) + { + // This disables shadows on the backsides of objects. + shadowed = nDotL < 0.0f ? 1.0f : shadowed; + + Sat_NL_Att = 1.0f; + shadowed = mix( 1.0f, shadowed, atten ); + lightColorOut = vec3(shadowed); + specular *= lightBrightness; + addToResult = ( 1.0 - shadowed ) * abs(lightMapParams); + } + + OUT_FragColor0 = lightinfoCondition( lightColorOut, Sat_NL_Att, specular, addToResult ); } diff --git a/Templates/Full/game/shaders/common/lighting/advanced/gl/vectorLightP.glsl b/Templates/Full/game/shaders/common/lighting/advanced/gl/vectorLightP.glsl index bbd567fd0..0178c35ea 100644 --- a/Templates/Full/game/shaders/common/lighting/advanced/gl/vectorLightP.glsl +++ b/Templates/Full/game/shaders/common/lighting/advanced/gl/vectorLightP.glsl @@ -22,40 +22,32 @@ #include "../../../gl/hlslCompat.glsl" #include "shadergen:/autogenConditioners.h" +#include "farFrustumQuad.glsl" +#include "../../../gl/torque.glsl" +#include "../../../gl/lighting.glsl" #include "lightingUtils.glsl" #include "../../shadowMap/shadowMapIO_GLSL.h" +#include "softShadow.glsl" -varying vec2 uv0; -varying vec3 wsEyeRay; +in vec4 hpos; +in vec2 uv0; +in vec3 wsEyeRay; +in vec3 vsEyeRay; -uniform sampler2D prePassBuffer; -uniform sampler2D ShadowMap; +uniform sampler2D ShadowMap ; -#if TORQUE_SM >= 30 - - // Enables high quality soft shadow - // filtering for SM3.0 and above. - #define SOFTSHADOW_SM3 - - #include "softShadow.glsl" - -#else - - - +#ifdef USE_SSAO_MASK +uniform sampler2D ssaoMask ; +uniform vec4 rtParams2; #endif - + +uniform sampler2D prePassBuffer; uniform vec3 lightDirection; uniform vec4 lightColor; -uniform float lightBrightness; -uniform vec4 lightAmbient; -uniform vec4 lightTrilight; - -uniform vec3 eyePosWorld; - -uniform mat4 worldToLightProj; -uniform vec4 splitDistStart; -uniform vec4 splitDistEnd; +uniform float lightBrightness; +uniform vec4 lightAmbient; +uniform vec3 eyePosWorld; +uniform mat4x4 worldToLightProj; uniform vec4 scaleX; uniform vec4 scaleY; uniform vec4 offsetX; @@ -65,16 +57,12 @@ uniform vec4 atlasYOffset; uniform vec2 atlasScale; uniform vec4 zNearFarInvNearFar; uniform vec4 lightMapParams; - -uniform float constantSpecularPower; uniform vec2 fadeStartLength; uniform vec4 farPlaneScalePSSM; -uniform vec4 splitFade; uniform vec4 overDarkPSSM; uniform float shadowSoftness; - -void main() +void main() { // Sample/unpack the normal/z data vec4 prepassSample = prepassUncondition( prePassBuffer, uv0 ); @@ -83,148 +71,162 @@ void main() // Use eye ray to get ws pos vec4 worldPos = vec4(eyePosWorld + wsEyeRay * depth, 1.0f); - + // Get the light attenuation. float dotNL = dot(-lightDirection, normal); + + #ifdef PSSM_DEBUG_RENDER + vec3 debugColor = vec3(0); + #endif #ifdef NO_SHADOW // Fully unshadowed. float shadowed = 1.0; + #ifdef PSSM_DEBUG_RENDER + debugColor = vec3(1.0); + #endif + #else - + // Compute shadow map coordinate - vec4 pxlPosLightProj = worldToLightProj * worldPos; + vec4 pxlPosLightProj = tMul(worldToLightProj, worldPos); vec2 baseShadowCoord = pxlPosLightProj.xy / pxlPosLightProj.w; - - float distOffset = 0.0; - float shadowed = 0.0; - float fadeAmt = 0.0; - vec4 zDist = vec4(zNearFarInvNearFar.x + zNearFarInvNearFar.y * depth); - - // Calculate things dependant on the shadowmap split - for ( int i = 0; i < 2; i++ ) - { - float zDistSplit = zDist.x + distOffset; - vec4 mask0; - mask0.x = float(zDistSplit >= splitDistStart.x); - mask0.y = float(zDistSplit >= splitDistStart.y); - mask0.z = float(zDistSplit >= splitDistStart.z); - mask0.w = float(zDistSplit >= splitDistStart.w); + + // Distance to light, in shadowmap space + float distToLight = pxlPosLightProj.z / pxlPosLightProj.w; - vec4 mask1; - mask1.x = float(zDistSplit < splitDistEnd.x); - mask1.y = float(zDistSplit < splitDistEnd.y); - mask1.z = float(zDistSplit < splitDistEnd.z); - mask1.w = float(zDistSplit < splitDistEnd.w); + // Figure out which split to sample from. Basically, we compute the shadowmap sample coord + // for all of the splits and then check if its valid. + vec4 shadowCoordX = vec4( baseShadowCoord.x ); + vec4 shadowCoordY = vec4( baseShadowCoord.y ); + vec4 farPlaneDists = vec4( distToLight ); + shadowCoordX *= scaleX; + shadowCoordY *= scaleY; + shadowCoordX += offsetX; + shadowCoordY += offsetY; + farPlaneDists *= farPlaneScalePSSM; + + // If the shadow sample is within -1..1 and the distance + // to the light for this pixel is less than the far plane + // of the split, use it. + vec4 finalMask; + if ( shadowCoordX.x > -0.99 && shadowCoordX.x < 0.99 && + shadowCoordY.x > -0.99 && shadowCoordY.x < 0.99 && + farPlaneDists.x < 1.0 ) + finalMask = vec4(1, 0, 0, 0); + + else if ( shadowCoordX.y > -0.99 && shadowCoordX.y < 0.99 && + shadowCoordY.y > -0.99 && shadowCoordY.y < 0.99 && + farPlaneDists.y < 1.0 ) + finalMask = vec4(0, 1, 0, 0); + + else if ( shadowCoordX.z > -0.99 && shadowCoordX.z < 0.99 && + shadowCoordY.z > -0.99 && shadowCoordY.z < 0.99 && + farPlaneDists.z < 1.0 ) + finalMask = vec4(0, 0, 1, 0); - vec4 finalMask = mask0 * mask1; + else + finalMask = vec4(0, 0, 0, 1); - float splitFadeDist = dot( finalMask, splitFade ); - vec2 finalScale; - finalScale.x = dot(finalMask, scaleX); - finalScale.y = dot(finalMask, scaleY); + #ifdef PSSM_DEBUG_RENDER + if ( finalMask.x > 0 ) + debugColor += vec3( 1, 0, 0 ); + else if ( finalMask.y > 0 ) + debugColor += vec3( 0, 1, 0 ); + else if ( finalMask.z > 0 ) + debugColor += vec3( 0, 0, 1 ); + else if ( finalMask.w > 0 ) + debugColor += vec3( 1, 1, 0 ); + #endif - vec2 finalOffset; - finalOffset.x = dot(finalMask, offsetX); - finalOffset.y = dot(finalMask, offsetY); - - vec2 shadowCoord; - shadowCoord = baseShadowCoord * finalScale; - shadowCoord += finalOffset; + // Here we know what split we're sampling from, so recompute the texcoord location + // Yes, we could just use the result from above, but doing it this way actually saves + // shader instructions. + vec2 finalScale; + finalScale.x = dot(finalMask, scaleX); + finalScale.y = dot(finalMask, scaleY); - // Convert to texcoord space - shadowCoord = 0.5 * shadowCoord + vec2(0.5, 0.5); - //shadowCoord.y = 1.0f - shadowCoord.y; + vec2 finalOffset; + finalOffset.x = dot(finalMask, offsetX); + finalOffset.y = dot(finalMask, offsetY); - // Move around inside of atlas - vec2 aOffset; - aOffset.x = dot(finalMask, atlasXOffset); - aOffset.y = dot(finalMask, atlasYOffset); + vec2 shadowCoord; + shadowCoord = baseShadowCoord * finalScale; + shadowCoord += finalOffset; - shadowCoord *= atlasScale; - shadowCoord += aOffset; - - // Distance to light, in shadowmap space - float distToLight = pxlPosLightProj.z / pxlPosLightProj.w; - - // Each split has a different far plane, take this into account. - float farPlaneScale = dot( farPlaneScalePSSM, finalMask ); - distToLight *= farPlaneScale; - - #ifdef SOFTSHADOW_SM3 + // Convert to texcoord space + shadowCoord = 0.5 * shadowCoord + vec2(0.5, 0.5); + shadowCoord.y = 1.0f - shadowCoord.y; - float esmShadow = softShadow_filter( ShadowMap, - gTapRotationTex, - uv0.xy, - shadowCoord, - farPlaneScale * shadowSoftness, - distToLight, - dotNL, - dot( finalMask, overDarkPSSM ) ); - - #else // !SOFTSHADOW_SM3 + // Move around inside of atlas + vec2 aOffset; + aOffset.x = dot(finalMask, atlasXOffset); + aOffset.y = dot(finalMask, atlasYOffset); - float occluder = decodeShadowMap( texture2DLod( ShadowMap, shadowCoord, 0.0 ) ); - float overDark = dot( finalMask, overDarkPSSM ); - float esmShadow = saturate( exp( esmFactor * ( occluder - distToLight ) ) ); - - #endif - - if ( i == 0 ) - { - float endDist = dot(splitDistEnd, finalMask); - fadeAmt = smoothstep(endDist - splitFadeDist, endDist, zDist).x; - shadowed = esmShadow * ( 1.0 - fadeAmt ); - } - else - shadowed += esmShadow * fadeAmt; - - distOffset += splitFadeDist; - } + shadowCoord *= atlasScale; + shadowCoord += aOffset; + + // Each split has a different far plane, take this into account. + float farPlaneScale = dot( farPlaneScalePSSM, finalMask ); + distToLight *= farPlaneScale; + + float shadowed = softShadow_filter( ShadowMap, + uv0.xy, + shadowCoord, + farPlaneScale * shadowSoftness, + distToLight, + dotNL, + dot( finalMask, overDarkPSSM ) ); // Fade out the shadow at the end of the range. + vec4 zDist = vec4(zNearFarInvNearFar.x + zNearFarInvNearFar.y * depth); float fadeOutAmt = ( zDist.x - fadeStartLength.x ) * fadeStartLength.y; - shadowed = mix( shadowed, 1.0, clamp( fadeOutAmt, 0.0, 1.0 ) ); + shadowed = mix( shadowed, 1.0, saturate( fadeOutAmt ) ); + + #ifdef PSSM_DEBUG_RENDER + if ( fadeOutAmt > 1.0 ) + debugColor = vec3(1.0); + #endif #endif // !NO_SHADOW - - // Calc lighting coefficents - float specular = calcSpecular( -lightDirection, - normal, - normalize(-wsEyeRay), - constantSpecularPower, - shadowed * lightBrightness ); - - float Sat_NL_Att = clamp(dotNL, 0.0, 1.0) * shadowed; - - // Trilight, described by Tom Forsyth - // http://home.comcast.net/~tom_forsyth/papers/trilight/trilight.html -#ifdef ACCUMULATE_LUV - // In LUV multiply in the brightness of the light color (normaly done in the attenuate function) - Sat_NL_Att *= lightColor.a; + // Specular term + float specular = AL_CalcSpecular( -lightDirection, + normal, + normalize(-vsEyeRay) ) * lightBrightness * shadowed; - vec4 ambientBlend = lightAmbient; - ambientBlend.b *= clamp(-dotNL, 0.0, 1.0); - - vec3 trilight = lightTrilight.rgb; - trilight.b *= clamp(1.0 - abs(dotNL), 0.0, 1.0); - - ambientBlend.rg = mix(ambientBlend.rg, trilight.rg, clamp(0.5 * trilight.b / lightAmbient.b, 0.0, 1.0)); - ambientBlend.b += trilight.b; + float Sat_NL_Att = saturate( dotNL * shadowed ) * lightBrightness; + vec3 lightColorOut = lightMapParams.rgb * lightColor.rgb; + vec4 addToResult = lightAmbient; -#else + // TODO: This needs to be removed when lightmapping is disabled + // as its extra work per-pixel on dynamic lit scenes. + // + // Special lightmapping pass. + if ( lightMapParams.a < 0.0 ) + { + // This disables shadows on the backsides of objects. + shadowed = dotNL < 0.0f ? 1.0f : shadowed; - // RGB - // TODO: Trilight seems broken... it does lighting in shadows! - //vec4 ambientBlend = vec4(lightTrilight.rgb * clamp(1.0 - abs(dotNL), 0.0, 1.0) + lightAmbient.rgb * clamp(-dotNL, 0.0, 1.0), 0.0); - vec4 ambientBlend = vec4(lightAmbient.rgb, 0.0); + Sat_NL_Att = 1.0f; + lightColorOut = vec3(shadowed); + specular *= lightBrightness; + addToResult = ( 1.0 - shadowed ) * abs(lightMapParams); + } -#endif + // Sample the AO texture. + #ifdef USE_SSAO_MASK + float ao = 1.0 - texture( ssaoMask, viewportCoordToRenderTarget( uv0.xy, rtParams2 ) ).r; + addToResult *= ao; + #endif + + #ifdef PSSM_DEBUG_RENDER + lightColorOut = debugColor; + #endif + + OUT_FragColor0 = lightinfoCondition( lightColorOut, Sat_NL_Att, specular, addToResult ); - // Output - gl_FragColor = lightinfoCondition( lightColor.rgb * lightBrightness, Sat_NL_Att, specular, ambientBlend) * lightMapParams; } diff --git a/Templates/Full/game/shaders/common/lighting/basic/gl/shadowFilterP.glsl b/Templates/Full/game/shaders/common/lighting/basic/gl/shadowFilterP.glsl index 238721e5e..4e97fa347 100644 --- a/Templates/Full/game/shaders/common/lighting/basic/gl/shadowFilterP.glsl +++ b/Templates/Full/game/shaders/common/lighting/basic/gl/shadowFilterP.glsl @@ -20,35 +20,27 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- +#include "../../../gl/hlslCompat.glsl" + uniform sampler2D diffuseMap; -varying vec2 uv; +in vec2 uv; uniform vec2 oneOverTargetSize; +const float offset[3] = float[]( 0.0, 1.3846153846, 3.2307692308 ); +const float weight[3] = float[]( 0.2270270270, 0.3162162162, 0.0702702703 ); + void main() { - vec2 sNonUniformTaps[8]; - - sNonUniformTaps[0] = vec2(0.992833, 0.979309); - sNonUniformTaps[1] = vec2(-0.998585, 0.985853); - sNonUniformTaps[2] = vec2(0.949299, -0.882562); - sNonUniformTaps[3] = vec2(-0.941358, -0.893924); - sNonUniformTaps[4] = vec2(0.545055, -0.589072); - sNonUniformTaps[5] = vec2(0.346526, 0.385821); - sNonUniformTaps[6] = vec2(-0.260183, 0.334412); - sNonUniformTaps[7] = vec2(0.248676, -0.679605); + vec4 OUT = texture( diffuseMap, uv ) * weight[0]; - gl_FragColor = vec4(0.0); - - vec2 texScale = vec2(1.0); - - for ( int i=0; i < 4; i++ ) + for ( int i=1; i < 3; i++ ) { - vec2 offset = (oneOverTargetSize * texScale) * sNonUniformTaps[i]; - gl_FragColor += texture2D( diffuseMap, uv + offset ); + vec2 _sample = (BLUR_DIR * offset[i]) * oneOverTargetSize; + OUT += texture( diffuseMap, uv + _sample ) * weight[i]; + OUT += texture( diffuseMap, uv - _sample ) * weight[i]; } - - gl_FragColor /= vec4(4.0); - gl_FragColor.rgb = vec3(0.0); + + OUT_FragColor0 = OUT; } diff --git a/Templates/Full/game/shaders/common/lighting/basic/gl/shadowFilterV.glsl b/Templates/Full/game/shaders/common/lighting/basic/gl/shadowFilterV.glsl index cbf3696be..0eeb2e0fd 100644 --- a/Templates/Full/game/shaders/common/lighting/basic/gl/shadowFilterV.glsl +++ b/Templates/Full/game/shaders/common/lighting/basic/gl/shadowFilterV.glsl @@ -22,13 +22,16 @@ #include "../../../../../../shaders/common/gl/torque.glsl" -uniform vec2 oneOverTargetSize; +in vec4 vPosition; +in vec2 vTexCoord0; + uniform vec4 rtParams0; -varying vec2 uv; +out vec2 uv; void main() { - gl_Position = gl_Vertex; - uv = viewportCoordToRenderTarget( gl_MultiTexCoord0.st, rtParams0 ); + gl_Position = vPosition; + uv = viewportCoordToRenderTarget( vTexCoord0.st, rtParams0 ); + gl_Position.y *= -1; //correct ssp } diff --git a/Templates/Full/game/shaders/common/lighting/shadowMap/gl/boxFilterP.glsl b/Templates/Full/game/shaders/common/lighting/shadowMap/gl/boxFilterP.glsl index 2800a3f17..0f568c716 100644 --- a/Templates/Full/game/shaders/common/lighting/shadowMap/gl/boxFilterP.glsl +++ b/Templates/Full/game/shaders/common/lighting/shadowMap/gl/boxFilterP.glsl @@ -26,7 +26,7 @@ uniform sampler2D diffuseMap0; uniform float texSize; uniform vec2 blurDimension; -varying vec2 tex0; +in vec2 tex0; void main() { @@ -40,8 +40,8 @@ void main() vec4 accum = vec4(0.0, 0.0, 0.0, 0.0); for(int i = 0; i < int(blurSamples); i++) { - accum += texture2D(diffuseMap0, BaseTexCoord + float(i) * SampleOffset); + accum += texture(diffuseMap0, BaseTexCoord + float(i) * SampleOffset); } accum /= blurSamples; - gl_FragColor = accum; + OUT_FragColor0 = accum; } \ No newline at end of file diff --git a/Templates/Full/game/shaders/common/lighting/shadowMap/gl/boxFilterV.glsl b/Templates/Full/game/shaders/common/lighting/shadowMap/gl/boxFilterV.glsl index 3850f83c7..9fc436f6c 100644 --- a/Templates/Full/game/shaders/common/lighting/shadowMap/gl/boxFilterV.glsl +++ b/Templates/Full/game/shaders/common/lighting/shadowMap/gl/boxFilterV.glsl @@ -20,12 +20,15 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- +in vec4 vPosition; +in vec2 vTexCoord0; + uniform mat4 modelview; -varying vec2 tex0; +out vec2 tex0; void main() { - gl_Position = modelview * gl_Vertex; - tex0 = gl_MultiTexCoord0.st; + gl_Position = modelview * vPosition; + tex0 = vTexCoord0.st; } \ No newline at end of file diff --git a/Templates/Full/game/shaders/common/postFx/postFxV.glsl b/Templates/Full/game/shaders/common/postFx/postFxV.glsl index 3aded2e0f..96a5ec819 100644 --- a/Templates/Full/game/shaders/common/postFx/postFxV.glsl +++ b/Templates/Full/game/shaders/common/postFx/postFxV.glsl @@ -22,27 +22,30 @@ #include "./../gl/torque.glsl" +in vec4 vPosition; +in vec2 vTexCoord0; +in vec3 vTexCoord1; uniform vec4 rtParams0; uniform vec4 rtParams1; uniform vec4 rtParams2; uniform vec4 rtParams3; -varying vec2 uv0; -varying vec2 uv1; -varying vec2 uv2; -varying vec2 uv3; -varying vec3 wsEyeRay; +out vec2 uv0; +out vec2 uv1; +out vec2 uv2; +out vec2 uv3; +out vec3 wsEyeRay; void main() { - gl_Position = gl_Vertex; + gl_Position = vPosition; - uv0 = viewportCoordToRenderTarget( gl_MultiTexCoord0.st, rtParams0 ); - uv1 = viewportCoordToRenderTarget( gl_MultiTexCoord0.st, rtParams1 ); - uv2 = viewportCoordToRenderTarget( gl_MultiTexCoord0.st, rtParams2 ); - uv3 = viewportCoordToRenderTarget( gl_MultiTexCoord0.st, rtParams3 ); + uv0 = viewportCoordToRenderTarget( vTexCoord0, rtParams0 ); + uv1 = viewportCoordToRenderTarget( vTexCoord0, rtParams1 ); + uv2 = viewportCoordToRenderTarget( vTexCoord0, rtParams2 ); + uv3 = viewportCoordToRenderTarget( vTexCoord0, rtParams3 ); - wsEyeRay = gl_MultiTexCoord1.xyz; + wsEyeRay = vTexCoord1; } diff --git a/Templates/Full/game/shaders/common/terrain/gl/blendP.glsl b/Templates/Full/game/shaders/common/terrain/gl/blendP.glsl index 3817e1de2..a2e4af787 100644 --- a/Templates/Full/game/shaders/common/terrain/gl/blendP.glsl +++ b/Templates/Full/game/shaders/common/terrain/gl/blendP.glsl @@ -23,8 +23,10 @@ #include "../terrain.glsl" #include "../../gl/hlslCompat.glsl" -varying vec2 layerCoord; -varying vec2 texCoord; +in vec2 layerCoord; +#define IN_layerCoord layerCoord +in vec2 texCoord; +#define IN_texCoord texCoord uniform sampler2D layerTex; uniform sampler2D textureMap; @@ -33,12 +35,12 @@ uniform float layerSize; void main() { - vec4 layerSample = round(texture2D( layerTex, layerCoord ) * 255.0); + vec4 layerSample = round(texture( layerTex, IN_layerCoord ) * 255.0); - float blend = calcBlend( texId, layerCoord, layerSize, layerSample ); + float blend = calcBlend( texId, IN_layerCoord, layerSize, layerSample ); if(blend - 0.0001 < 0.0) discard; - gl_FragColor = vec4( texture2D( textureMap, texCoord ).rgb, blend ); + OUT_FragColor0 = vec4( texture( textureMap, IN_texCoord ).rgb, blend ); } diff --git a/Templates/Full/game/shaders/common/terrain/gl/blendV.glsl b/Templates/Full/game/shaders/common/terrain/gl/blendV.glsl index 44362085b..dc7b7befa 100644 --- a/Templates/Full/game/shaders/common/terrain/gl/blendV.glsl +++ b/Templates/Full/game/shaders/common/terrain/gl/blendV.glsl @@ -23,14 +23,19 @@ /// The vertex shader used in the generation and caching of the /// base terrain texture. -varying vec2 layerCoord; -varying vec2 texCoord; +in vec4 vPosition; +in vec2 vTexCoord0; + +out vec2 layerCoord; +out vec2 texCoord; uniform vec2 texScale; void main() { - gl_Position = vec4(gl_Vertex.xyz, 1.0); - layerCoord = gl_MultiTexCoord0.st; - texCoord = gl_MultiTexCoord0.st * texScale; + gl_Position = vec4(vPosition.xyz, 1.0); + layerCoord = vTexCoord0.st; + texCoord = vTexCoord0.st * texScale; + + gl_Position.y *= -1; } diff --git a/Templates/Full/game/shaders/common/water/gl/waterBasicP.glsl b/Templates/Full/game/shaders/common/water/gl/waterBasicP.glsl index 72232622a..44207dea9 100644 --- a/Templates/Full/game/shaders/common/water/gl/waterBasicP.glsl +++ b/Templates/Full/game/shaders/common/water/gl/waterBasicP.glsl @@ -31,7 +31,7 @@ #define FRESNEL_BIAS miscParams[0] #define FRESNEL_POWER miscParams[1] #define CLARITY miscParams[2] -#define ISRIVER miscParams[3] +#define ISRIVER miscParams[3] // reflectParams #define REFLECT_PLANE_Z reflectParams[0] @@ -45,40 +45,49 @@ #define DISTORT_FULL_DEPTH distortionParams[2] // ConnectData.misc -#define LIGHT_VEC misc.xyz -#define WORLD_Z objPos.w +#define LIGHT_VEC IN_misc.xyz +#define WORLD_Z IN_objPos.w // specularParams #define SPEC_POWER specularParams[3] #define SPEC_COLOR specularParams.xyz +//----------------------------------------------------------------------------- +// Defines +//----------------------------------------------------------------------------- + // TexCoord 0 and 1 (xy,zw) for ripple texture lookup -varying vec4 rippleTexCoord01; +in vec4 rippleTexCoord01; +#define IN_rippleTexCoord01 rippleTexCoord01 // TexCoord 2 for ripple texture lookup -varying vec2 rippleTexCoord2; +in vec2 rippleTexCoord2; +#define IN_rippleTexCoord2 rippleTexCoord2 // Screenspace vert position BEFORE wave transformation -varying vec4 posPreWave; +in vec4 posPreWave; +#define IN_posPreWave posPreWave // Screenspace vert position AFTER wave transformation -varying vec4 posPostWave; +in vec4 posPostWave; +#define IN_posPostWave posPostWave // Worldspace unit distance/depth of this vertex/pixel -varying float pixelDist; - -// Objectspace vert position BEFORE wave transformation -// w coord is world space z position. -varying vec4 objPos; +in float pixelDist; +#define IN_pixelDist pixelDist -varying vec3 misc; +in vec4 objPos; +#define IN_objPos objPos + +in vec3 misc; +#define IN_misc misc //----------------------------------------------------------------------------- // approximate Fresnel function //----------------------------------------------------------------------------- float fresnel(float NdotV, float bias, float power) { - return bias + (1.0-bias)*pow(abs(1.0 - max(NdotV, 0.0)), power); + return bias + (1.0-bias)*pow(abs(1.0 - max(NdotV, 0)), power); } //----------------------------------------------------------------------------- @@ -89,7 +98,7 @@ uniform sampler2D bumpMap; uniform sampler2D reflectMap; uniform sampler2D refractBuff; uniform samplerCube skyMap; -//uniform sampler foamMap; +//uniform sampler2D foamMap; uniform vec4 baseColor; uniform vec4 miscParams; uniform vec4 reflectParams; @@ -98,8 +107,9 @@ uniform vec3 eyePos; uniform vec3 distortionParams; uniform vec3 fogData; uniform vec4 fogColor; -uniform vec3 rippleMagnitude; +uniform vec4 rippleMagnitude; uniform vec4 specularParams; +uniform mat4 modelMat; //----------------------------------------------------------------------------- // Main @@ -107,31 +117,35 @@ uniform vec4 specularParams; void main() { // Modulate baseColor by the ambientColor. - vec4 waterBaseColor = baseColor * vec4( ambientColor.rgb, 1.0 ); + vec4 waterBaseColor = baseColor * vec4( ambientColor.rgb, 1 ); // Get the bumpNorm... - vec3 bumpNorm = ( texture2D( bumpMap, rippleTexCoord01.xy ).rgb * 2.0 - 1.0 ) * rippleMagnitude.x; - bumpNorm += ( texture2D( bumpMap, rippleTexCoord01.zw ).rgb * 2.0 - 1.0 ) * rippleMagnitude.y; - bumpNorm += ( texture2D( bumpMap, rippleTexCoord2 ).rgb * 2.0 - 1.0 ) * rippleMagnitude.z; - + vec3 bumpNorm = ( texture( bumpMap, IN_rippleTexCoord01.xy ).rgb * 2.0 - 1.0 ) * rippleMagnitude.x; + bumpNorm += ( texture( bumpMap, IN_rippleTexCoord01.zw ).rgb * 2.0 - 1.0 ) * rippleMagnitude.y; + bumpNorm += ( texture( bumpMap, IN_rippleTexCoord2 ).rgb * 2.0 - 1.0 ) * rippleMagnitude.z; + + bumpNorm = normalize( bumpNorm ); + bumpNorm = mix( bumpNorm, vec3(0,0,1), 1.0 - rippleMagnitude.w ); + // We subtract a little from it so that we don't // distort where the water surface intersects the // camera near plane. - float distortAmt = saturate( pixelDist / 1.0 ) * 0.8; + float distortAmt = saturate( IN_pixelDist / 1.0 ) * 0.8; - vec4 distortPos = posPostWave; + vec4 distortPos = IN_posPostWave; distortPos.xy += bumpNorm.xy * distortAmt; #ifdef UNDERWATER - gl_FragColor = texture2DProj( refractBuff, distortPos.xyz ); + OUT_FragColor0 = hdrEncode( textureProj( refractBuff, distortPos ) ); #else - vec3 eyeVec = objPos.xyz - eyePos; - vec3 reflectionVec = reflect( eyeVec, normalize(bumpNorm) ); + vec3 eyeVec = IN_objPos.xyz - eyePos; + eyeVec = tMul( mat3(modelMat), eyeVec ); + vec3 reflectionVec = reflect( eyeVec, bumpNorm ); // Color that replaces the reflection color when we do not // have one that is appropriate. - vec4 fakeColor = vec4(ambientColor,1.0); + vec4 fakeColor = vec4(ambientColor,1); // Use fakeColor for ripple-normals that are angled towards the camera eyeVec = -eyeVec; @@ -140,58 +154,61 @@ void main() float fakeColorAmt = ang; // Get reflection map color - vec4 refMapColor = texture2DProj( reflectMap, distortPos ); + vec4 refMapColor = hdrDecode( textureProj( reflectMap, distortPos ) ); // If we do not have a reflection texture then we use the cubemap. - refMapColor = mix( refMapColor, textureCube( skyMap, -reflectionVec ), NO_REFLECT ); + refMapColor = mix( refMapColor, texture( skyMap, reflectionVec ), NO_REFLECT ); // Combine reflection color and fakeColor. vec4 reflectColor = mix( refMapColor, fakeColor, fakeColorAmt ); //return refMapColor; // Get refract color - vec4 refractColor = texture2DProj( refractBuff, distortPos.xyz ); + vec4 refractColor = hdrDecode( textureProj( refractBuff, distortPos ) ); // calc "diffuse" color by lerping from the water color // to refraction image based on the water clarity. - vec4 diffuseColor = mix( refractColor, waterBaseColor, 1.0 - CLARITY ); + vec4 diffuseColor = mix( refractColor, waterBaseColor, 1.0f - CLARITY ); // fresnel calculation float fresnelTerm = fresnel( ang, FRESNEL_BIAS, FRESNEL_POWER ); + //return vec4( fresnelTerm.rrr, 1 ); // Also scale the frensel by our distance to the // water surface. This removes the hard reflection // when really close to the water surface. - fresnelTerm *= saturate( pixelDist - 0.1 ); + fresnelTerm *= saturate( IN_pixelDist - 0.1 ); // Combine the diffuse color and reflection image via the // fresnel term and set out output color. - gl_FragColor = mix( diffuseColor, reflectColor, fresnelTerm ); - + vec4 OUT = mix( diffuseColor, reflectColor, fresnelTerm ); + #ifdef WATER_SPEC // Get some specular reflection. vec3 newbump = bumpNorm; newbump.xy *= 3.5; newbump = normalize( bumpNorm ); - vec3 halfAng = normalize( eyeVec + -LIGHT_VEC ); + half3 halfAng = normalize( eyeVec + -LIGHT_VEC ); float specular = saturate( dot( newbump, halfAng ) ); specular = pow( specular, SPEC_POWER ); - gl_FragColor.rgb = gl_FragColor.rgb + ( SPEC_COLOR * specular.xxx ); + OUT.rgb = OUT.rgb + ( SPEC_COLOR * specular.xxx ); #else // Disable fogging if spec is on because otherwise we run out of instructions. // Fog it. float factor = computeSceneFog( eyePos, - objPos.xyz, + IN_objPos.xyz, WORLD_Z, fogData.x, fogData.y, fogData.z ); - gl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor.rgb, 1.0 - saturate( factor ) ); - - #endif + //OUT.rgb = mix( OUT.rgb, fogColor.rgb, 1.0 - saturate( factor ) ); + #endif + + OUT_FragColor0 = OUT; + #endif } diff --git a/Templates/Full/game/shaders/common/water/gl/waterBasicV.glsl b/Templates/Full/game/shaders/common/water/gl/waterBasicV.glsl index bb2a0c954..1634fd2de 100644 --- a/Templates/Full/game/shaders/common/water/gl/waterBasicV.glsl +++ b/Templates/Full/game/shaders/common/water/gl/waterBasicV.glsl @@ -27,23 +27,30 @@ //----------------------------------------------------------------------------- // TexCoord 0 and 1 (xy,zw) for ripple texture lookup -varying vec4 rippleTexCoord01; +out vec4 rippleTexCoord01; +#define OUT_rippleTexCoord01 rippleTexCoord01 // TexCoord 2 for ripple texture lookup -varying vec2 rippleTexCoord2; +out vec2 rippleTexCoord2; +#define OUT_rippleTexCoord2 rippleTexCoord2 // Screenspace vert position BEFORE wave transformation -varying vec4 posPreWave; +out vec4 posPreWave; +#define OUT_posPreWave posPreWave // Screenspace vert position AFTER wave transformation -varying vec4 posPostWave; +out vec4 posPostWave; +#define OUT_posPostWave posPostWave // Worldspace unit distance/depth of this vertex/pixel -varying float pixelDist; +out float pixelDist; +#define OUT_pixelDist pixelDist -varying vec4 objPos; +out vec4 objPos; +#define OUT_objPos objPos -varying vec3 misc; +out vec3 misc; +#define OUT_misc misc //----------------------------------------------------------------------------- // Uniforms @@ -63,49 +70,56 @@ uniform float gridElementSize; uniform float elapsedTime; uniform float undulateMaxDist; +in vec4 vPosition; +in vec3 vNormal; +in vec4 vColor; +in vec2 vTexCoord0; +in vec4 vTexCoord1; + //----------------------------------------------------------------------------- // Main //----------------------------------------------------------------------------- void main() { - vec4 position = gl_Vertex; - vec3 normal = gl_Normal; - vec2 undulateData = gl_MultiTexCoord0.st; - vec4 horizonFactor = gl_MultiTexCoord1; + vec4 IN_position = vPosition; + vec3 IN_normal = vNormal; + vec2 IN_undulateData = vTexCoord0; + vec4 IN_horizonFactor = vTexCoord1; + vec4 OUT_hpos = vec4(0); // use projection matrix for reflection / refraction texture coords - mat4 texGen = mat4(0.5, 0.0, 0.0, 0.0, - 0.0, 0.5, 0.0, 0.0, - 0.0, 0.0, 1.0, 0.0, - 0.5, 0.5, 0.0, 1.0); + mat4 texGen = mat4FromRow( 0.5, 0.0, 0.0, 0.5, + 0.0, -0.5, 0.0, 0.5, + 0.0, 0.0, 1.0, 0.0, + 0.0, 0.0, 0.0, 1.0 ); // Move the vertex based on the horizonFactor if specified to do so for this vert. - //if ( horizonFactor.z > 0.0 ) - //{ - //vec2 offsetXY = eyePos.xy - mod(eyePos.xy, gridElementSize); - //position.xy += offsetXY; - //undulateData += offsetXY; - //} + // if ( IN_horizonFactor.z > 0 ) + // { + // vec2 offsetXY = eyePos.xy - eyePos.xy % gridElementSize; + // IN_position.xy += offsetXY; + // IN_undulateData += offsetXY; + // } - vec4 worldPos = modelMat * position; - //fogPos = position.xyz; - position.z = mix( position.z, eyePos.z, horizonFactor.x ); - - objPos.xyz = position.xyz; - objPos.w = worldPos.z; + vec4 worldPos = tMul( modelMat, IN_position ); + + IN_position.z = mix( IN_position.z, eyePos.z, IN_horizonFactor.x ); + + //OUT_objPos = worldPos; + OUT_objPos.xyz = IN_position.xyz; + OUT_objPos.w = worldPos.z; // Send pre-undulation screenspace position - posPreWave = modelview * position; - posPreWave = texGen * posPreWave; + OUT_posPreWave = tMul( modelview, IN_position ); + OUT_posPreWave = tMul( texGen, OUT_posPreWave ); // Calculate the undulation amount for this vertex. - vec2 undulatePos = (modelMat * vec4( undulateData.xy, 0, 1 )).xy; - - //if ( undulatePos.x < 0.0 ) - //undulatePos = position.xy; - - float undulateAmt = 0.0; + vec2 undulatePos = tMul( modelMat, vec4( IN_undulateData.xy, 0, 1 ) ).xy; + //if ( undulatePos.x < 0 ) + // undulatePos = IN_position.xy; + float undulateAmt = 0.0; + undulateAmt += waveData[0].y * sin( elapsedTime * waveData[0].x + undulatePos.x * waveDir[0].x + undulatePos.y * waveDir[0].y ); @@ -114,118 +128,84 @@ void main() undulatePos.y * waveDir[1].y ); undulateAmt += waveData[2].y * sin( elapsedTime * waveData[2].x + undulatePos.x * waveDir[2].x + - undulatePos.y * waveDir[2].y ); - - float undulateFade = 1.0; - - // Scale down wave magnitude amount based on distance from the camera. - float dist = length( position.xyz - eyePos ); + undulatePos.y * waveDir[2].y ); + + float undulateFade = 1; + + // Scale down wave magnitude amount based on distance from the camera. + float dist = distance( IN_position.xyz, eyePos ); dist = clamp( dist, 1.0, undulateMaxDist ); - undulateFade *= ( 1.0 - dist / undulateMaxDist ); + undulateFade *= ( 1 - dist / undulateMaxDist ); // Also scale down wave magnitude if the camera is very very close. - undulateFade *= saturate( ( length( position.xyz - eyePos ) - 0.5 ) / 10.0 ); - + undulateFade *= saturate( ( distance( IN_position.xyz, eyePos ) - 0.5 ) / 10.0 ); + undulateAmt *= undulateFade; + //#endif //undulateAmt = 0; // Apply wave undulation to the vertex. - posPostWave = position; - posPostWave.xyz += normal.xyz * undulateAmt; + OUT_posPostWave = IN_position; + OUT_posPostWave.xyz += IN_normal.xyz * undulateAmt; // Save worldSpace position of this pixel/vert - //worldPos = posPostWave.xyz; + //OUT_worldPos = OUT_posPostWave.xyz; + //OUT_worldPos = tMul( modelMat, OUT_posPostWave.xyz ); + //OUT_worldPos.z += objTrans[2][2]; //91.16; - //worldSpaceZ = ( modelMat * vec4(fogPos,1.0) ).z; - //if ( horizonFactor.x > 0.0 ) - //{ - //vec3 awayVec = normalize( fogPos.xyz - eyePos ); - //fogPos.xy += awayVec.xy * 1000.0; - //} + // OUT_misc.w = tMul( modelMat, OUT_fogPos ).z; + // if ( IN_horizonFactor.x > 0 ) + // { + // vec3 awayVec = normalize( OUT_fogPos.xyz - eyePos ); + // OUT_fogPos.xy += awayVec.xy * 1000.0; + // } // Convert to screen - posPostWave = modelview * posPostWave; + OUT_posPostWave = tMul( modelview, OUT_posPostWave ); // tMul( modelview, vec4( OUT_posPostWave.xyz, 1 ) ); // Setup the OUT position symantic variable - gl_Position = posPostWave; - //gl_Position.z = mix(gl_Position.z, gl_Position.w, horizonFactor.x); + OUT_hpos = OUT_posPostWave; // tMul( modelview, vec4( IN_position.xyz, 1 ) ); //vec4( OUT_posPostWave.xyz, 1 ); + //OUT_hpos.z = mix( OUT_hpos.z, OUT_hpos.w, IN_horizonFactor.x ); // Save world space camera dist/depth of the outgoing pixel - pixelDist = gl_Position.z; + OUT_pixelDist = OUT_hpos.z; // Convert to reflection texture space - posPostWave = texGen * posPostWave; + OUT_posPostWave = tMul( texGen, OUT_posPostWave ); vec2 txPos = undulatePos; - if ( horizonFactor.x > 0.0 ) + if ( bool(IN_horizonFactor.x) ) txPos = normalize( txPos ) * 50000.0; - - - // set up tex coordinates for the 3 interacting normal maps - rippleTexCoord01.xy = txPos * rippleTexScale[0]; - rippleTexCoord01.xy += rippleDir[0] * elapsedTime * rippleSpeed.x; + + // set up tex coordinates for the 3 interacting normal maps + OUT_rippleTexCoord01.xy = txPos * rippleTexScale[0]; + OUT_rippleTexCoord01.xy += rippleDir[0] * elapsedTime * rippleSpeed.x; mat2 texMat; texMat[0][0] = rippleMat[0].x; texMat[1][0] = rippleMat[0].y; texMat[0][1] = rippleMat[0].z; texMat[1][1] = rippleMat[0].w; - rippleTexCoord01.xy = texMat * rippleTexCoord01.xy ; + OUT_rippleTexCoord01.xy = tMul( texMat, OUT_rippleTexCoord01.xy ); - rippleTexCoord01.zw = txPos * rippleTexScale[1]; - rippleTexCoord01.zw += rippleDir[1] * elapsedTime * rippleSpeed.y; + OUT_rippleTexCoord01.zw = txPos * rippleTexScale[1]; + OUT_rippleTexCoord01.zw += rippleDir[1] * elapsedTime * rippleSpeed.y; texMat[0][0] = rippleMat[1].x; texMat[1][0] = rippleMat[1].y; texMat[0][1] = rippleMat[1].z; texMat[1][1] = rippleMat[1].w; - rippleTexCoord01.zw = texMat * rippleTexCoord01.zw ; + OUT_rippleTexCoord01.zw = tMul( texMat, OUT_rippleTexCoord01.zw ); - rippleTexCoord2.xy = txPos * rippleTexScale[2]; - rippleTexCoord2.xy += rippleDir[2] * elapsedTime * rippleSpeed.z; + OUT_rippleTexCoord2.xy = txPos * rippleTexScale[2]; + OUT_rippleTexCoord2.xy += rippleDir[2] * elapsedTime * rippleSpeed.z; texMat[0][0] = rippleMat[2].x; texMat[1][0] = rippleMat[2].y; texMat[0][1] = rippleMat[2].z; texMat[1][1] = rippleMat[2].w; - rippleTexCoord2.xy = texMat * rippleTexCoord2.xy ; - - - /*rippleTexCoord01.xy = mix( position.xy * rippleTexScale[0], txPos.xy * rippleTexScale[0], horizonFactor.x ); - rippleTexCoord01.xy += rippleDir[0] * elapsedTime * rippleSpeed.x; - - rippleTexCoord01.zw = mix( position.xy * rippleTexScale[1], txPos.xy * rippleTexScale[1], horizonFactor.x ); - rippleTexCoord01.zw += rippleDir[1] * elapsedTime * rippleSpeed.y; - - rippleTexCoord2.xy = mix( position.xy * rippleTexScale[2], txPos.xy * rippleTexScale[2], horizonFactor.x ); - rippleTexCoord2.xy += rippleDir[2] * elapsedTime * rippleSpeed.z; */ - - - /*rippleTexCoord01.xy = mix( position.xy * rippleTexScale[0], txPos.xy * rippleTexScale[0], horizonFactor.x ); - rippleTexCoord01.xy += rippleDir[0] * elapsedTime * rippleSpeed.x; - mat2 texMat; - texMat[0][0] = rippleMat[0].x; - texMat[1][0] = rippleMat[0].y; - texMat[0][1] = rippleMat[0].z; - texMat[1][1] = rippleMat[0].w; - rippleTexCoord01.xy = texMat * rippleTexCoord01.xy ; - - rippleTexCoord01.zw = mix( position.xy * rippleTexScale[1], txPos.xy * rippleTexScale[1], horizonFactor.x ); - rippleTexCoord01.zw += rippleDir[1] * elapsedTime * rippleSpeed.y; - texMat[0][0] = rippleMat[1].x; - texMat[1][0] = rippleMat[1].y; - texMat[0][1] = rippleMat[1].z; - texMat[1][1] = rippleMat[1].w; - rippleTexCoord01.zw = texMat * rippleTexCoord01.zw ; - - rippleTexCoord2.xy = mix( position.xy * rippleTexScale[2], txPos.xy * rippleTexScale[2], horizonFactor.x ); - rippleTexCoord2.xy += rippleDir[2] * elapsedTime * rippleSpeed.z; - texMat[0][0] = rippleMat[2].x; - texMat[1][0] = rippleMat[2].y; - texMat[0][1] = rippleMat[2].z; - texMat[1][1] = rippleMat[2].w; - rippleTexCoord2.xy = texMat * rippleTexCoord2.xy ;*/ + OUT_rippleTexCoord2.xy = tMul( texMat, OUT_rippleTexCoord2.xy ); #ifdef WATER_SPEC @@ -234,8 +214,8 @@ void main() vec3 normal; for ( int i = 0; i < 3; i++ ) { - binormal.z += undulateFade * waveDir[i].x * waveData[i].y * cos( waveDir[i].x * undulateData.x + waveDir[i].y * undulateData.y + elapsedTime * waveData[i].x ); - tangent.z += undulateFade * waveDir[i].y * waveData[i].y * cos( waveDir[i].x * undulateData.x + waveDir[i].y * undulateData.y + elapsedTime * waveData[i].x ); + binormal.z += undulateFade * waveDir[i].x * waveData[i].y * cos( waveDir[i].x * IN_undulateData.x + waveDir[i].y * IN_undulateData.y + elapsedTime * waveData[i].x ); + tangent.z += undulateFade * waveDir[i].y * waveData[i].y * cos( waveDir[i].x * IN_undulateData.x + waveDir[i].y * IN_undulateData.y + elapsedTime * waveData[i].x ); } binormal = normalize( binormal ); @@ -246,15 +226,19 @@ void main() worldToTangent[0] = binormal; worldToTangent[1] = tangent; worldToTangent[2] = normal; + + worldToTangent = transpose(worldToTangent); - misc.xyz = inLightVec * modelMat; - misc.xyz = worldToTangent * misc.xyz; + OUT_misc.xyz = tMul( inLightVec, modelMat ); + OUT_misc.xyz = tMul( worldToTangent, OUT_misc.xyz ); #else - misc.xyz = inLightVec; - + OUT_misc.xyz = inLightVec; + #endif - + + gl_Position = OUT_hpos; + correctSSP(gl_Position); } diff --git a/Templates/Full/game/shaders/common/water/gl/waterP.glsl b/Templates/Full/game/shaders/common/water/gl/waterP.glsl index bf482d724..3e15fe576 100644 --- a/Templates/Full/game/shaders/common/water/gl/waterP.glsl +++ b/Templates/Full/game/shaders/common/water/gl/waterP.glsl @@ -20,6 +20,7 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- +#include "../../gl/hlslCompat.glsl" #include "shadergen:/autogenConditioners.h" #include "../../gl/torque.glsl" @@ -27,10 +28,7 @@ // Defines //----------------------------------------------------------------------------- -#ifdef TORQUE_BASIC_LIGHTING - #define BASIC -#endif - +#define PIXEL_DIST IN_rippleTexCoord2.z // miscParams #define FRESNEL_BIAS miscParams[0] #define FRESNEL_POWER miscParams[1] @@ -57,33 +55,54 @@ #define DISTORT_FULL_DEPTH distortionParams[2] // foamParams -#define FOAM_SCALE foamParams[0] +#define FOAM_OPACITY foamParams[0] #define FOAM_MAX_DEPTH foamParams[1] +#define FOAM_AMBIENT_LERP foamParams[2] +#define FOAM_RIPPLE_INFLUENCE foamParams[3] -// Incoming data -// Worldspace position of this pixel -varying vec3 worldPos; +// specularParams +#define SPEC_POWER specularParams[3] +#define SPEC_COLOR specularParams.xyz + +//----------------------------------------------------------------------------- +// Structures +//----------------------------------------------------------------------------- + +//ConnectData IN + +in vec4 hpos; // TexCoord 0 and 1 (xy,zw) for ripple texture lookup -varying vec4 rippleTexCoord01; +in vec4 rippleTexCoord01; -// TexCoord 2 for ripple texture lookup -varying vec2 rippleTexCoord2; +// xy is TexCoord 2 for ripple texture lookup +// z is the Worldspace unit distance/depth of this vertex/pixel +// w is amount of the crestFoam ( more at crest of waves ). +in vec4 rippleTexCoord2; // Screenspace vert position BEFORE wave transformation -varying vec4 posPreWave; +in vec4 posPreWave; // Screenspace vert position AFTER wave transformation -varying vec4 posPostWave; +in vec4 posPostWave; -// Worldspace unit distance/depth of this vertex/pixel -varying float pixelDist; +// Objectspace vert position BEFORE wave transformation +// w coord is world space z position. +in vec4 objPos; -varying vec3 fogPos; +in vec4 foamTexCoords; -varying float worldSpaceZ; +in mat3 tangentMat; -varying vec4 foamTexCoords; + +#define IN_hpos hpos +#define IN_rippleTexCoord01 rippleTexCoord01 +#define IN_rippleTexCoord2 rippleTexCoord2 +#define IN_posPreWave posPreWave +#define IN_posPostWave posPostWave +#define IN_objPos objPos +#define IN_foamTexCoords foamTexCoords +#define IN_tangentMat tangentMat //----------------------------------------------------------------------------- // approximate Fresnel function @@ -100,10 +119,10 @@ uniform sampler2D bumpMap; uniform sampler2D prepassTex; uniform sampler2D reflectMap; uniform sampler2D refractBuff; -uniform samplerCUBE skyMap; +uniform samplerCube skyMap; uniform sampler2D foamMap; -uniform vec4 specularColor; -uniform float specularPower; +uniform sampler1D depthGradMap; +uniform vec4 specularParams; uniform vec4 baseColor; uniform vec4 miscParams; uniform vec2 fogParams; @@ -112,64 +131,45 @@ uniform vec3 reflectNormal; uniform vec2 wetnessParams; uniform float farPlaneDist; uniform vec3 distortionParams; -//uniform vec4 renderTargetParams; -uniform vec2 foamParams; -uniform vec3 foamColorMod; +uniform vec4 foamParams; uniform vec3 ambientColor; -uniform vec3 eyePos; -uniform vec3 inLightVec; +uniform vec3 eyePos; // This is in object space! uniform vec3 fogData; uniform vec4 fogColor; -//uniform vec4 rtParams; -uniform vec2 rtScale; -uniform vec2 rtHalfPixel; -uniform vec4 rtOffset; -uniform vec3 rippleMagnitude; +uniform vec4 rippleMagnitude; +uniform vec4 rtParams1; +uniform float depthGradMax; +uniform vec3 inLightVec; +uniform mat4 modelMat; +uniform vec4 sunColor; +uniform float sunBrightness; +uniform float reflectivity; //----------------------------------------------------------------------------- // Main //----------------------------------------------------------------------------- void main() { - vec4 rtParams = vec4( rtOffset.x / rtOffset.z + rtHalfPixel.x, - rtOffset.y / rtOffset.w + rtHalfPixel.x, - rtScale ); - - // Modulate baseColor by the ambientColor. - vec4 waterBaseColor = baseColor * vec4( ambientColor.rgb, 1 ); - // Get the bumpNorm... - vec3 bumpNorm = ( tex2D( bumpMap, IN.rippleTexCoord01.xy ) * 2.0 - 1.0 ) * rippleMagnitude.x; - bumpNorm += ( tex2D( bumpMap, IN.rippleTexCoord01.zw ) * 2.0 - 1.0 ) * rippleMagnitude.y; - bumpNorm += ( tex2D( bumpMap, IN.rippleTexCoord2 ) * 2.0 - 1.0 ) * rippleMagnitude.z; - - // JCF: this was here, but seems to make the dot product against the bump - // normal we use below for cubeMap fade-in to be less reliable. - //bumpNorm.xy *= 0.75; - //bumpNorm = normalize( bumpNorm ); - //return vec4( bumpNorm, 1 ); + vec3 bumpNorm = ( texture( bumpMap, IN_rippleTexCoord01.xy ).rgb * 2.0 - 1.0 ) * rippleMagnitude.x; + bumpNorm += ( texture( bumpMap, IN_rippleTexCoord01.zw ).rgb * 2.0 - 1.0 ) * rippleMagnitude.y; + bumpNorm += ( texture( bumpMap, IN_rippleTexCoord2.xy ).rgb * 2.0 - 1.0 ) * rippleMagnitude.z; + + bumpNorm = normalize( bumpNorm ); + bumpNorm = mix( bumpNorm, vec3(0,0,1), 1.0 - rippleMagnitude.w ); + bumpNorm = tMul( bumpNorm, IN_tangentMat ); // Get depth of the water surface (this pixel). // Convert from WorldSpace to EyeSpace. - float pixelDepth = IN.pixelDist / farPlaneDist; + float pixelDepth = PIXEL_DIST / farPlaneDist; - // Get prepass depth at the undistorted pixel. - //vec4 prepassCoord = IN.posPostWave; - //prepassCoord.xy += renderTargetParams.xy; - vec2 prepassCoord = viewportCoordToRenderTarget( IN.posPostWave, rtParams ); - //vec2 prepassCoord = IN.posPostWave.xy; + vec2 prepassCoord = viewportCoordToRenderTarget( IN_posPostWave, rtParams1 ); - float startDepth = prepassUncondition( tex2D( prepassTex, prepassCoord ) ).w; - //return vec4( startDepth.rrr, 1 ); + float startDepth = prepassUncondition( prepassTex, prepassCoord ).w; // The water depth in world units of the undistorted pixel. float startDelta = ( startDepth - pixelDepth ); - if ( startDelta <= 0.0 ) - { - //return vec4( 1, 0, 0, 1 ); - startDelta = 0; - } - + startDelta = max( startDelta, 0.0 ); startDelta *= farPlaneDist; // Calculate the distortion amount for the water surface. @@ -177,23 +177,22 @@ void main() // We subtract a little from it so that we don't // distort where the water surface intersects the // camera near plane. - float distortAmt = saturate( ( IN.pixelDist - DISTORT_START_DIST ) / DISTORT_END_DIST ); + float distortAmt = saturate( ( PIXEL_DIST - DISTORT_START_DIST ) / DISTORT_END_DIST ); // Scale down distortion in shallow water. distortAmt *= saturate( startDelta / DISTORT_FULL_DEPTH ); - //distortAmt = 0; // Do the intial distortion... we might remove it below. vec2 distortDelta = bumpNorm.xy * distortAmt; - vec4 distortPos = IN.posPostWave; + vec4 distortPos = IN_posPostWave; distortPos.xy += distortDelta; - prepassCoord = viewportCoordToRenderTarget( distortPos, rtParams ); - //prepassCoord = distortPos; - //prepassCoord.xy += renderTargetParams.xy; + prepassCoord = viewportCoordToRenderTarget( distortPos, rtParams1 ); // Get prepass depth at the position of this distorted pixel. - float prepassDepth = prepassUncondition( tex2D( prepassTex, prepassCoord ) ).w; + float prepassDepth = prepassUncondition( prepassTex, prepassCoord ).w; + if ( prepassDepth > 0.99 ) + prepassDepth = 5.0; float delta = ( prepassDepth - pixelDepth ) * farPlaneDist; @@ -202,7 +201,7 @@ void main() // If we got a negative delta then the distorted // sample is above the water surface. Mask it out // by removing the distortion. - distortPos = IN.posPostWave; + distortPos = IN_posPostWave; delta = startDelta; distortAmt = 0; } @@ -212,20 +211,20 @@ void main() if ( diff < 0 ) { - distortAmt = saturate( ( IN.pixelDist - DISTORT_START_DIST ) / DISTORT_END_DIST ); + distortAmt = saturate( ( PIXEL_DIST - DISTORT_START_DIST ) / DISTORT_END_DIST ); distortAmt *= saturate( delta / DISTORT_FULL_DEPTH ); distortDelta = bumpNorm.xy * distortAmt; - distortPos = IN.posPostWave; + distortPos = IN_posPostWave; distortPos.xy += distortDelta; - prepassCoord = viewportCoordToRenderTarget( distortPos, rtParams ); - //prepassCoord = distortPos; - //prepassCoord.xy += renderTargetParams.xy; + prepassCoord = viewportCoordToRenderTarget( distortPos, rtParams1 ); // Get prepass depth at the position of this distorted pixel. - prepassDepth = prepassUncondition( tex2D( prepassTex, prepassCoord ) ).w; + prepassDepth = prepassUncondition( prepassTex, prepassCoord ).w; + if ( prepassDepth > 0.99 ) + prepassDepth = 5.0; delta = ( prepassDepth - pixelDepth ) * farPlaneDist; } @@ -234,133 +233,78 @@ void main() // If we got a negative delta then the distorted // sample is above the water surface. Mask it out // by removing the distortion. - distortPos = IN.posPostWave; + distortPos = IN_posPostWave; delta = startDelta; distortAmt = 0; } } - //return vec4( prepassDepth.rrr, 1 ); - - vec4 temp = IN.posPreWave; + vec4 temp = IN_posPreWave; temp.xy += bumpNorm.xy * distortAmt; - vec2 reflectCoord = viewportCoordToRenderTarget( temp, rtParams ); + vec2 reflectCoord = viewportCoordToRenderTarget( temp, rtParams1 ); - vec2 refractCoord = viewportCoordToRenderTarget( distortPos, rtParams ); + vec2 refractCoord = viewportCoordToRenderTarget( distortPos, rtParams1 ); - // Use cubemap colors instead of reflection colors in several cases... - - // First lookup the CubeMap color - // JCF: which do we want to use here, the reflectNormal or the bumpNormal - // neithor of them is exactly right and how can we combine the two together? - //bumpNorm = reflectNormal; - vec3 eyeVec = IN.worldPos - eyePos; + vec4 fakeColor = vec4(ambientColor,1); + vec3 eyeVec = IN_objPos.xyz - eyePos; + eyeVec = tMul( mat3(modelMat), eyeVec ); + eyeVec = tMul( IN_tangentMat, eyeVec ); vec3 reflectionVec = reflect( eyeVec, bumpNorm ); - //vec4 cubeColor = texCUBE( skyMap, reflectionVec ); - //return cubeColor; - // JCF: using ambient color instead of cubeColor for waterPlane, how do we still use the cubemap for rivers? - vec4 cubeColor = vec4(ambientColor,1); - //cubeColor.rgb = vec3( 0, 0, 1 ); - // Use cubeColor for waves that are angled towards camera + // Use fakeColor for ripple-normals that are angled towards the camera eyeVec = -eyeVec; eyeVec = normalize( eyeVec ); float ang = saturate( dot( eyeVec, bumpNorm ) ); - float cubeAmt = ang; + float fakeColorAmt = ang; - //float rplaneDist = (reflectPlane.x * IN.pos.x + reflectPlane.y * IN.pos.y + reflectPlane.z * IN.pos.z) + reflectPlane.w; - //rplaneDist = saturate( abs( rplaneDist ) / 0.5 ); - - -//#ifdef RIVER // for verts far from the reflect plane z position - float rplaneDist = abs( REFLECT_PLANE_Z - IN.worldPos.z ); + float rplaneDist = abs( REFLECT_PLANE_Z - IN_objPos.w ); rplaneDist = saturate( ( rplaneDist - 1.0 ) / 2.0 ); - //rplaneDist = REFLECT_PLANE_Z / eyePos.z; rplaneDist *= ISRIVER; - cubeAmt = max( cubeAmt, rplaneDist ); -//#endif - - //rplaneDist = IN.worldPos.z / eyePos.z; - - //return vec4( rplaneDist.rrr, 1 ); - //return vec4( (reflectParams[REFLECT_PLANE_Z] / 86.0 ).rrr, 1 ); - - // and for verts farther from the camera - //float cubeAmt = ( eyeDist - reflectParams[REFLECT_MIN_DIST] ) / ( reflectParams[REFLECT_MAX_DIST] - reflectParams[REFLECT_MIN_DIST] ); - //cubeAmt = saturate ( cubeAmt ); - - //float temp = ( eyeDist - reflectParams[REFLECT_MIN_DIST] ) / ( reflectParams[REFLECT_MAX_DIST] - reflectParams[REFLECT_MIN_DIST] ); - //temp = saturate ( temp ); - - // If the camera is very very close to the reflect plane. - //float eyeToPlaneDist = eyePos.z - REFLECT_PLANE_Z; // dot( reflectNormal, eyePos ) + REFLECT_PLANE_Z; - //eyeToPlaneDist = abs( eyeToPlaneDist ); - //eyeToPlaneDist = 1.0 - saturate( abs( eyeToPlaneDist ) / 1 ); - - //return vec4( eyeToPlaneDist.rrr, 1 ); - - //cubeAmt = max( cubeAmt, eyeToPlaneDist ); - //cubeAmt = max( cubeAmt, rplaneDist ); - //cubeAmt = max( cubeAmt, ang ); - //cubeAmt = max( cubeAmt, rplaneDist ); - //cubeAmt = max( cubeAmt, IN.depth.w ); - - // All cubemap if fullReflect is specifically user disabled - cubeAmt = max( cubeAmt, NO_REFLECT ); + fakeColorAmt = max( fakeColorAmt, rplaneDist ); #ifndef UNDERWATER - // Get foam color and amount - IN.foamTexCoords.xy += distortDelta * 0.5; - IN.foamTexCoords.zw += distortDelta * 0.5; + vec2 foamRippleOffset = bumpNorm.xy * FOAM_RIPPLE_INFLUENCE; + vec4 IN_foamTexCoords = IN_foamTexCoords; + IN_foamTexCoords.xy += foamRippleOffset; + IN_foamTexCoords.zw += foamRippleOffset; - vec4 foamColor = tex2D( foamMap, IN.foamTexCoords.xy ); - foamColor += tex2D( foamMap, IN.foamTexCoords.zw ); - //foamColor += tex2D( foamMap, IN.rippleTexCoord2 ) * 0.3; + vec4 foamColor = texture( foamMap, IN_foamTexCoords.xy ); + foamColor += texture( foamMap, IN_foamTexCoords.zw ); foamColor = saturate( foamColor ); - // Modulate foam color by ambient color so we don't have glowing white - // foam at night. - foamColor.rgb = lerp( foamColor.rgb, ambientColor.rgb, foamColorMod.rgb ); + + // Modulate foam color by ambient color + // so we don't have glowing white foam at night. + foamColor.rgb = mix( foamColor.rgb, ambientColor.rgb, FOAM_AMBIENT_LERP ); float foamDelta = saturate( delta / FOAM_MAX_DEPTH ); - float foamAmt = 1.0 - foamDelta; + float foamAmt = 1 - pow( foamDelta, 2 ); // Fade out the foam in very very low depth, // this improves the shoreline a lot. float diff = 0.8 - foamAmt; if ( diff < 0.0 ) - { - //return vec4( 1,0,0,1 ); foamAmt -= foamAmt * abs( diff ) / 0.2; - } - //return vec4( foamAmt.rrr, 1 ); - - foamAmt *= FOAM_SCALE * foamColor.a; - //return vec4( foamAmt.rrr, 1 ); - // Get reflection map color - vec4 refMapColor = tex2D( reflectMap, reflectCoord ); + foamAmt *= FOAM_OPACITY * foamColor.a; - //cubeAmt = 0; + foamColor.rgb *= FOAM_OPACITY * foamAmt * foamColor.a; - // Combine cube and foam colors into reflect color - vec4 reflectColor = lerp( refMapColor, cubeColor, cubeAmt ); - //return refMapColor; + // Get reflection map color. + vec4 refMapColor = hdrDecode( texture( reflectMap, reflectCoord ) ); - // This doesn't work because REFLECT_PLANE_Z is in worldSpace - // while eyePos is actually in objectSpace! + // If we do not have a reflection texture then we use the cubemap. + refMapColor = mix( refMapColor, texture( skyMap, reflectionVec ), NO_REFLECT ); - //float eyeToPlaneDist = eyePos.z - REFLECT_PLANE_Z; // dot( reflectNormal, eyePos ) + REFLECT_PLANE_Z; - //float transitionFactor = 1.0 - saturate( ( abs( eyeToPlaneDist ) - 0.5 ) / 5 ); - //reflectColor = lerp( reflectColor, waterBaseColor, transitionFactor ); - - //return reflectColor; + fakeColor = ( texture( skyMap, reflectionVec ) ); + fakeColor.a = 1; + // Combine reflection color and fakeColor. + vec4 reflectColor = mix( refMapColor, fakeColor, fakeColorAmt ); // Get refract color - vec4 refractColor = tex2D( refractBuff, refractCoord ); - //return refractColor; + vec4 refractColor = hdrDecode( texture( refractBuff, refractCoord ) ); // We darken the refraction color a bit to make underwater // elements look wet. We fade out this darkening near the @@ -371,86 +315,80 @@ void main() // Add Water fog/haze. float fogDelta = delta - FOG_DENSITY_OFFSET; - //return vec4( fogDelta.rrr, 1 ); + if ( fogDelta < 0.0 ) fogDelta = 0.0; float fogAmt = 1.0 - saturate( exp( -FOG_DENSITY * fogDelta ) ); - //return vec4( fogAmt.rrr, 1 ); + + // Calculate the water "base" color based on depth. + vec4 waterBaseColor = baseColor * texture( depthGradMap, saturate( delta / depthGradMax ) ); + + // Modulate baseColor by the ambientColor. + waterBaseColor *= vec4( ambientColor.rgb, 1 ); // calc "diffuse" color by lerping from the water color // to refraction image based on the water clarity. - vec4 diffuseColor = lerp( refractColor, waterBaseColor, fogAmt ); + vec4 diffuseColor = mix( refractColor, waterBaseColor, fogAmt ); // fresnel calculation float fresnelTerm = fresnel( ang, FRESNEL_BIAS, FRESNEL_POWER ); - //return vec4( fresnelTerm.rrr, 1 ); // Scale the frensel strength by fog amount // so that parts that are very clear get very little reflection. fresnelTerm *= fogAmt; - //return vec4( fresnelTerm.rrr, 1 ); // Also scale the frensel by our distance to the // water surface. This removes the hard reflection // when really close to the water surface. - fresnelTerm *= saturate( IN.pixelDist - 0.1 ); + fresnelTerm *= saturate( PIXEL_DIST - 0.1 ); + + fresnelTerm *= reflectivity; // Combine the diffuse color and reflection image via the // fresnel term and set out output color. - vec4 gl_FragColor = lerp( diffuseColor, reflectColor, fresnelTerm ); + vec4 OUT = mix( diffuseColor, reflectColor, fresnelTerm ); - //float brightness = saturate( 1.0 - ( waterHeight - eyePosWorld.z - 5.0 ) / 50.0 ); - //gl_FragColor.rgb *= brightness; + vec3 lightVec = inLightVec; + + // Get some specular reflection. + vec3 newbump = bumpNorm; + newbump.xy *= 3.5; + newbump = normalize( bumpNorm ); + vec3 halfAng = normalize( eyeVec + -lightVec ); + float specular = saturate( dot( newbump, halfAng ) ); + specular = pow( specular, SPEC_POWER ); + + // Scale down specularity in very shallow water to improve the transparency of the shoreline. + specular *= saturate( delta / 2 ); + OUT.rgb = OUT.rgb + ( SPEC_COLOR * vec3(specular) ); #else - vec4 refractColor = tex2D( refractBuff, refractCoord ); - vec4 gl_FragColor = refractColor; + + vec4 refractColor = hdrDecode( texture( refractBuff, refractCoord ) ); + vec4 OUT = refractColor; + #endif #ifndef UNDERWATER - gl_FragColor.rgb = lerp( gl_FragColor.rgb, foamColor.rgb, foamAmt ); -#endif - gl_FragColor.a = 1.0; - - // specular experiments - -// 1: -/* - float fDot = dot( bumpNorm, inLightVec ); - vec3 reflect = normalize( 2.0 * bumpNorm * fDot - eyeVec ); - // float specular = saturate(dot( reflect, inLightVec ) ); - float specular = pow( reflect, specularPower ); - gl_FragColor += specularColor * specular; -*/ - - -// 2: This almost looks good -/* - bumpNorm.xy *= 2.0; - bumpNorm = normalize( bumpNorm ); - - vec3 halfAng = normalize( eyeVec + inLightVec ); - float specular = saturate( dot( bumpNorm, halfAng) ); - specular = pow(specular, specularPower); - gl_FragColor += specularColor * specular; -*/ - -#ifndef UNDERWATER + OUT.rgb = OUT.rgb + foamColor.rgb; float factor = computeSceneFog( eyePos, - IN.fogPos, - IN.worldSpaceZ, + IN_objPos.xyz, + IN_objPos.w, fogData.x, fogData.y, fogData.z ); - gl_FragColor.rgb = lerp( gl_FragColor.rgb, fogColor.rgb, 1.0 - saturate( factor ) ); + OUT.rgb = mix( OUT.rgb, fogColor.rgb, 1.0 - saturate( factor ) ); + + //OUT.rgb = fogColor.rgb; #endif - //return vec4( refMapColor.rgb, 1 ); - gl_FragColor.a = 1.0; + OUT.a = 1.0; + + //return OUT; - return gl_FragColor; + OUT_FragColor0 = hdrEncode( OUT ); } diff --git a/Templates/Full/game/shaders/common/water/gl/waterV.glsl b/Templates/Full/game/shaders/common/water/gl/waterV.glsl index d4337476f..490af63a7 100644 --- a/Templates/Full/game/shaders/common/water/gl/waterV.glsl +++ b/Templates/Full/game/shaders/common/water/gl/waterV.glsl @@ -20,58 +20,86 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- +#include "../../gl/hlslCompat.glsl" #include "shadergen:/autogenConditioners.h" +//----------------------------------------------------------------------------- +// Structures +//----------------------------------------------------------------------------- +struct VertData +{ + vec4 position ;// POSITION; + vec3 normal ;// NORMAL; + vec2 undulateData ;// TEXCOORD0; + vec4 horizonFactor ;// TEXCOORD1; +}; + //----------------------------------------------------------------------------- // Defines //----------------------------------------------------------------------------- +//VertData IN +in vec4 vPosition; +in vec3 vNormal; +in vec2 vTexCoord0; +in vec4 vTexCoord1; -// waveData -#define WAVE_SPEED(i) waveData[i].x -#define WAVE_MAGNITUDE(i) waveData[i].y +#define IN_position_ vPosition +#define IN_normal vNormal +#define IN_undulateData vTexCoord0 +#define IN_horizonFactor vTexCoord1 -// Outgoing data -// Worldspace position of this pixel -varying vec3 worldPos; +//ConnectData OUT +// + out vec4 hpos ; // TexCoord 0 and 1 (xy,zw) for ripple texture lookup -varying vec4 rippleTexCoord01; +out vec4 rippleTexCoord01; -// TexCoord 2 for ripple texture lookup -varying vec2 rippleTexCoord2; + // xy is TexCoord 2 for ripple texture lookup + // z is the Worldspace unit distance/depth of this vertex/pixel + // w is amount of the crestFoam ( more at crest of waves ). + out vec4 rippleTexCoord2 ; // Screenspace vert position BEFORE wave transformation -varying vec4 posPreWave; +out vec4 posPreWave; // Screenspace vert position AFTER wave transformation -varying vec4 posPostWave; +out vec4 posPostWave; -// Worldspace unit distance/depth of this vertex/pixel -varying float pixelDist; + // Objectspace vert position BEFORE wave transformation + // w coord is world space z position. + out vec4 objPos ; -varying vec3 fogPos; + out vec4 foamTexCoords ; -varying float worldSpaceZ; + out mat3 tangentMat ; +// -varying vec4 foamTexCoords; +#define OUT_hpos hpos +#define OUT_rippleTexCoord01 rippleTexCoord01 +#define OUT_rippleTexCoord2 rippleTexCoord2 +#define OUT_posPreWave posPreWave +#define OUT_posPostWave posPostWave +#define OUT_objPos objPos +#define OUT_foamTexCoords foamTexCoords +#define OUT_tangentMat tangentMat //----------------------------------------------------------------------------- // Uniforms //----------------------------------------------------------------------------- uniform mat4 modelMat; uniform mat4 modelview; -uniform mat3 cubeTrans; -uniform mat4 objTrans; -uniform vec3 cubeEyePos; +uniform vec4 rippleMat[3]; uniform vec3 eyePos; uniform vec2 waveDir[3]; uniform vec2 waveData[3]; uniform vec2 rippleDir[3]; uniform vec2 rippleTexScale[3]; uniform vec3 rippleSpeed; -uniform vec2 reflectTexSize; +uniform vec4 foamDir; +uniform vec4 foamTexScale; +uniform vec2 foamSpeed; uniform vec3 inLightVec; -uniform vec3 reflectNormal; uniform float gridElementSize; uniform float elapsedTime; uniform float undulateMaxDist; @@ -81,97 +109,133 @@ uniform float undulateMaxDist; //----------------------------------------------------------------------------- void main() { - // Copy incoming attributes into locals so we can modify them in place. - vec4 position = gl_Vertex.xyzw; - vec3 normal = gl_Normal.xyz; - vec2 undulateData = gl_MultiTexCoord0.st; - vec4 horizonFactor = gl_MultiTexCoord1.xyzw; + vec4 IN_position = IN_position_; // use projection matrix for reflection / refraction texture coords - mat4 texGen = { 0.5, 0.0, 0.0, 0.5, //+ 0.5 / reflectTexSize.x, - 0.0, 0.5, 0.0, 0.5, //+ 1.0 / reflectTexSize.y, - 0.0, 0.0, 1.0, 0.0, - 0.0, 0.0, 0.0, 1.0 }; + mat4 texGen = mat4FromRow( 0.5, 0.0, 0.0, 0.5, + 0.0, -0.5, 0.0, 0.5, + 0.0, 0.0, 1.0, 0.0, + 0.0, 0.0, 0.0, 1.0 ); - // Move the vertex based on the horizonFactor if specified to do so for this vert. - if ( horizonFactor.z > 0 ) - { - vec2 offsetXY = eyePos.xy - eyePos.xy % gridElementSize; - position.xy += offsetXY; - undulateData += offsetXY; - } + IN_position.z = mix( IN_position.z, eyePos.z, IN_horizonFactor.x ); - fogPos = position; - position.z = mix( position.z, eyePos.z, horizonFactor.x ); + OUT_objPos = IN_position; + OUT_objPos.w = tMul( modelMat, IN_position ).z; // Send pre-undulation screenspace position - posPreWave = modelview * position; - posPreWave = texGen * posPreWave; + OUT_posPreWave = tMul( modelview, IN_position ); + OUT_posPreWave = tMul( texGen, OUT_posPreWave ); // Calculate the undulation amount for this vertex. - vec2 undulatePos = undulateData; - float undulateAmt = 0; + vec2 undulatePos = tMul( modelMat, vec4 ( IN_undulateData.xy, 0, 1 ) ).xy; + float undulateAmt = 0.0; - for ( int i = 0; i < 3; i++ ) - { - undulateAmt += WAVE_MAGNITUDE(i) * sin( elapsedTime * WAVE_SPEED(i) + - undulatePos.x * waveDir[i].x + - undulatePos.y * waveDir[i].y ); - } + undulateAmt += waveData[0].y * sin( elapsedTime * waveData[0].x + + undulatePos.x * waveDir[0].x + + undulatePos.y * waveDir[0].y ); + undulateAmt += waveData[1].y * sin( elapsedTime * waveData[1].x + + undulatePos.x * waveDir[1].x + + undulatePos.y * waveDir[1].y ); + undulateAmt += waveData[2].y * sin( elapsedTime * waveData[2].x + + undulatePos.x * waveDir[2].x + + undulatePos.y * waveDir[2].y ); + + float undulateFade = 1; // Scale down wave magnitude amount based on distance from the camera. - float dist = distance( position, eyePos ); + float dist = distance( IN_position.xyz, eyePos ); dist = clamp( dist, 1.0, undulateMaxDist ); - undulateAmt *= ( 1 - dist / undulateMaxDist ); + undulateFade *= ( 1 - dist / undulateMaxDist ); // Also scale down wave magnitude if the camera is very very close. - undulateAmt *= clamp( ( distance( IN.position, eyePos ) - 0.5 ) / 10.0, 0.0, 1.0 ); + undulateFade *= saturate( ( distance( IN_position.xyz, eyePos ) - 0.5 ) / 10.0 ); + + undulateAmt *= undulateFade; + + OUT_rippleTexCoord2.w = undulateAmt / ( waveData[0].y + waveData[1].y + waveData[2].y ); + OUT_rippleTexCoord2.w = saturate( OUT_rippleTexCoord2.w - 0.2 ) / 0.8; // Apply wave undulation to the vertex. - posPostWave = position; - posPostWave.xyz += normal.xyz * undulateAmt; - - // Save worldSpace position of this pixel/vert - worldPos = posPostWave.xyz; + OUT_posPostWave = IN_position; + OUT_posPostWave.xyz += IN_normal.xyz * undulateAmt; // Convert to screen - posPostWave = modelview * posPostWave; + OUT_posPostWave = tMul( modelview, OUT_posPostWave ); // Setup the OUT position symantic variable - gl_Position = posPostWave; - gl_Position.z = mix(gl_Position.z, gl_Position.w, horizonFactor.x); + OUT_hpos = OUT_posPostWave; + //OUT_hpos.z = mix( OUT_hpos.z, OUT_hpos.w, IN_horizonFactor.x ); - worldSpaceZ = modelMat * vec4(fogPos, 1.0) ).z; - if ( horizonFactor.x > 0.0 ) - { - vec3 awayVec = normalize( fogPos.xyz - eyePos ); - fogPos.xy += awayVec.xy * 1000.0; - } + // if ( IN_horizonFactor.x > 0 ) + // { + // vec3 awayVec = normalize( OUT_objPos.xyz - eyePos ); + // OUT_objPos.xy += awayVec.xy * 1000.0; + // } // Save world space camera dist/depth of the outgoing pixel - pixelDist = gl_Position.z; + OUT_rippleTexCoord2.z = OUT_hpos.z; // Convert to reflection texture space - posPostWave = texGen * posPostWave; + OUT_posPostWave = tMul( texGen, OUT_posPostWave ); - float2 ripplePos = undulateData; - float2 txPos = normalize( ripplePos ); - txPos *= 50000.0; - ripplePos = mix( ripplePos, txPos, IN.horizonFactor.x ); + vec2 txPos = undulatePos; + if ( bool(IN_horizonFactor.x) ) + txPos = normalize( txPos ) * 50000.0; // set up tex coordinates for the 3 interacting normal maps - rippleTexCoord01.xy = mix( ripplePos * rippleTexScale[0], txPos.xy * rippleTexScale[0], IN.horizonFactor.x ); - rippleTexCoord01.xy += rippleDir[0] * elapsedTime * rippleSpeed.x; + OUT_rippleTexCoord01.xy = txPos * rippleTexScale[0]; + OUT_rippleTexCoord01.xy += rippleDir[0] * elapsedTime * rippleSpeed.x; - rippleTexCoord01.zw = mix( ripplePos * rippleTexScale[1], txPos.xy * rippleTexScale[1], IN.horizonFactor.x ); - rippleTexCoord01.zw += rippleDir[1] * elapsedTime * rippleSpeed.y; + mat2 texMat; + texMat[0][0] = rippleMat[0].x; + texMat[1][0] = rippleMat[0].y; + texMat[0][1] = rippleMat[0].z; + texMat[1][1] = rippleMat[0].w; + OUT_rippleTexCoord01.xy = tMul( texMat, OUT_rippleTexCoord01.xy ); - rippleTexCoord2.xy = mix( ripplePos * rippleTexScale[2], txPos.xy * rippleTexScale[2], IN.horizonFactor.x ); - rippleTexCoord2.xy += rippleDir[2] * elapsedTime * rippleSpeed.z; + OUT_rippleTexCoord01.zw = txPos * rippleTexScale[1]; + OUT_rippleTexCoord01.zw += rippleDir[1] * elapsedTime * rippleSpeed.y; + + texMat[0][0] = rippleMat[1].x; + texMat[1][0] = rippleMat[1].y; + texMat[0][1] = rippleMat[1].z; + texMat[1][1] = rippleMat[1].w; + OUT_rippleTexCoord01.zw = tMul( texMat, OUT_rippleTexCoord01.zw ); - foamTexCoords.xy = mix( ripplePos * 0.2, txPos.xy * rippleTexScale[0], IN.horizonFactor.x ); - foamTexCoords.xy += rippleDir[0] * sin( ( elapsedTime + 500.0 ) * -0.4 ) * 0.15; + OUT_rippleTexCoord2.xy = txPos * rippleTexScale[2]; + OUT_rippleTexCoord2.xy += rippleDir[2] * elapsedTime * rippleSpeed.z; - foamTexCoords.zw = mix( ripplePos * 0.3, txPos.xy * rippleTexScale[1], IN.horizonFactor.x ); - foamTexCoords.zw += rippleDir[1] * sin( elapsedTime * 0.4 ) * 0.15; + texMat[0][0] = rippleMat[2].x; + texMat[1][0] = rippleMat[2].y; + texMat[0][1] = rippleMat[2].z; + texMat[1][1] = rippleMat[2].w; + OUT_rippleTexCoord2.xy = tMul( texMat, OUT_rippleTexCoord2.xy ); + + OUT_foamTexCoords.xy = txPos * foamTexScale.xy + foamDir.xy * foamSpeed.x * elapsedTime; + OUT_foamTexCoords.zw = txPos * foamTexScale.zw + foamDir.zw * foamSpeed.y * elapsedTime; + + + vec3 binormal = vec3 ( 1, 0, 0 ); + vec3 tangent = vec3 ( 0, 1, 0 ); + vec3 normal; + for ( int i = 0; i < 3; i++ ) + { + binormal.z += undulateFade * waveDir[i].x * waveData[i].y * cos( waveDir[i].x * undulatePos.x + waveDir[i].y * undulatePos.y + elapsedTime * waveData[i].x ); + tangent.z += undulateFade * waveDir[i].y * waveData[i].y * cos( waveDir[i].x * undulatePos.x + waveDir[i].y * undulatePos.y + elapsedTime * waveData[i].x ); + } + + binormal = binormal; + tangent = tangent; + normal = cross( binormal, tangent ); + + mat3 worldToTangent; + worldToTangent[0] = binormal; + worldToTangent[1] = tangent; + worldToTangent[2] = normal; + + OUT_tangentMat = transpose(worldToTangent); + + gl_Position = OUT_hpos; + correctSSP(gl_Position); } + diff --git a/Templates/Full/game/tools/gui/profiles.ed.cs b/Templates/Full/game/tools/gui/profiles.ed.cs index 8d6718601..b3a5b2295 100644 --- a/Templates/Full/game/tools/gui/profiles.ed.cs +++ b/Templates/Full/game/tools/gui/profiles.ed.cs @@ -764,7 +764,7 @@ singleton GuiControlProfile( GuiInspectorGroupProfile ) opaque = false; border = false; - bitmap = "tools/editorclasses/gui/images/rollout"; + bitmap = "tools/editorClasses/gui/images/rollout"; textOffset = "20 0"; diff --git a/Templates/Full/game/tools/riverEditor/main.cs b/Templates/Full/game/tools/riverEditor/main.cs index b51bd5273..eafb3c3c8 100644 --- a/Templates/Full/game/tools/riverEditor/main.cs +++ b/Templates/Full/game/tools/riverEditor/main.cs @@ -25,8 +25,8 @@ function initializeRiverEditor() echo(" % - Initializing River Editor"); exec( "./riverEditor.cs" ); - exec( "./riverEditorGui.gui" ); - exec( "./riverEditorToolbar.gui" ); + exec( "./RiverEditorGui.gui" ); + exec( "./RiverEditorToolbar.gui" ); exec( "./riverEditorGui.cs" ); // Add ourselves to EditorGui, where all the other tools reside diff --git a/Templates/Full/game/tools/roadEditor/main.cs b/Templates/Full/game/tools/roadEditor/main.cs index cb7ea052c..f45823670 100644 --- a/Templates/Full/game/tools/roadEditor/main.cs +++ b/Templates/Full/game/tools/roadEditor/main.cs @@ -25,8 +25,8 @@ function initializeRoadEditor() echo( " - Initializing Road and Path Editor" ); exec( "./roadEditor.cs" ); - exec( "./roadEditorGui.gui" ); - exec( "./roadEditorToolbar.gui"); + exec( "./RoadEditorGui.gui" ); + exec( "./RoadEditorToolbar.gui"); exec( "./roadEditorGui.cs" ); // Add ourselves to EditorGui, where all the other tools reside diff --git a/Templates/Full/game/tools/shapeEditor/gui/Profiles.ed.cs b/Templates/Full/game/tools/shapeEditor/gui/Profiles.ed.cs index 0b92a30e2..cb42ef169 100644 --- a/Templates/Full/game/tools/shapeEditor/gui/Profiles.ed.cs +++ b/Templates/Full/game/tools/shapeEditor/gui/Profiles.ed.cs @@ -41,7 +41,7 @@ singleton GuiControlProfile(GuiShapeEdTextListProfile : ToolsGuiTextListProfile) singleton GuiControlProfile(GuiShapeEdRolloutProfile : GuiInspectorRolloutProfile0) { - bitmap = "tools/editorclasses/gui/images/rollout"; + bitmap = "tools/editorClasses/gui/images/rollout"; category = "Editor"; }; diff --git a/Templates/Full/game/tools/shapeEditor/main.cs b/Templates/Full/game/tools/shapeEditor/main.cs index f033bae86..721313e95 100644 --- a/Templates/Full/game/tools/shapeEditor/main.cs +++ b/Templates/Full/game/tools/shapeEditor/main.cs @@ -33,7 +33,7 @@ function initializeShapeEditor() exec("./gui/shapeEdPreviewWindow.ed.gui"); exec("./gui/shapeEdAnimWindow.ed.gui"); exec("./gui/shapeEdAdvancedWindow.ed.gui"); - exec("./gui/shapeEditorToolbar.ed.gui"); + exec("./gui/ShapeEditorToolbar.ed.gui"); exec("./gui/shapeEdSelectWindow.ed.gui"); exec("./gui/shapeEdPropWindow.ed.gui"); diff --git a/Templates/Full/game/tools/worldEditor/main.cs b/Templates/Full/game/tools/worldEditor/main.cs index 1b20201e0..773dbac17 100644 --- a/Templates/Full/game/tools/worldEditor/main.cs +++ b/Templates/Full/game/tools/worldEditor/main.cs @@ -29,7 +29,7 @@ function initializeWorldEditor() exec("./scripts/cursors.ed.cs"); exec("./gui/guiCreateNewTerrainGui.gui" ); - exec("./gui/genericPromptDialog.ed.gui" ); + exec("./gui/GenericPromptDialog.ed.gui" ); exec("./gui/guiTerrainImportGui.gui" ); exec("./gui/guiTerrainExportGui.gui" ); exec("./gui/EditorGui.ed.gui"); diff --git a/Templates/Full/source/torqueConfig.h b/Templates/Full/source/torqueConfig.h index 4d8f124f2..775fa91f4 100644 --- a/Templates/Full/source/torqueConfig.h +++ b/Templates/Full/source/torqueConfig.h @@ -169,6 +169,13 @@ /// texture manager. #define TORQUE_FRAME_SIZE 16 << 20 +// Default keyboard layout for launching the game. It's fixed crash when a +// game running with the extend unicode keyboard (cyrillic, for example). +// Windows only. +// @see For choice language > +// http://msdn.microsoft.com/en-us/library/windows/desktop/dd318693%28v=vs.85%29.aspx +#define TORQUE_DEFAULT_KEYBOARD_LAYOUT LANG_ENGLISH + // Finally, we define some dependent #defines. This enables some subsidiary // functionality to get automatically turned on in certain configurations. diff --git a/Tools/CMake/CMakeLists.txt b/Tools/CMake/CMakeLists.txt new file mode 100644 index 000000000..950d8cf99 --- /dev/null +++ b/Tools/CMake/CMakeLists.txt @@ -0,0 +1,28 @@ +include(basics.cmake) + +setupVersionNumbers() + +#the libs +include(lmng.cmake) +include(lpng.cmake) +include(lungif.cmake) +include(zlib.cmake) +include(ljpeg.cmake) +include(tinyxml.cmake) +include(opcode.cmake) +include(squish.cmake) +include(collada.cmake) +include(pcre.cmake) +include(convexDecomp.cmake) +if(TORQUE_SFX_VORBIS) + include(libvorbis.cmake) + include(libogg.cmake) +endif() +if(TORQUE_THEORA) + include(libtheora.cmake) +endif() + +# the main engine, should come last +include(torque3d.cmake) + +#setupPackaging() \ No newline at end of file diff --git a/Tools/CMake/app-debug-win.bat.in b/Tools/CMake/app-debug-win.bat.in new file mode 100644 index 000000000..8885f2e5b --- /dev/null +++ b/Tools/CMake/app-debug-win.bat.in @@ -0,0 +1,15 @@ +:: little debug helper script that helps you starting Torque3D with command line arguments. + +:: possible args: +:: -log +:: -console +:: -level +:: -worldeditor +:: -guieditor +:: -help + +:: as example, we just show the console +"@PROJECT_NAME@.exe" -console + +:: or load a level and open the editor: +:: "@PROJECT_NAME@.exe" -console -level mylevel.mis -worldeditor diff --git a/Tools/CMake/basics.cmake b/Tools/CMake/basics.cmake new file mode 100644 index 000000000..1903efc2f --- /dev/null +++ b/Tools/CMake/basics.cmake @@ -0,0 +1,323 @@ +project("Torque3DEngine") + +set(TORQUE_TEMPLATE "Full" CACHE STRING "the template to use") + +if(NOT projectDir) + set(projectDir "${CMAKE_SOURCE_DIR}/My Projects/${TORQUE_APP_NAME}") +endif() +if(NOT projectOutDir) + set(projectOutDir "${projectDir}/game") +endif() +if(NOT projectSrcDir) + set(projectSrcDir "${projectDir}/source") +endif() +set(libDir "${CMAKE_SOURCE_DIR}/Engine/lib") +set(srcDir "${CMAKE_SOURCE_DIR}/Engine/source") +set(cmakeDir "${CMAKE_SOURCE_DIR}/Tools/CMake") + + +# hide some things +mark_as_advanced(CMAKE_INSTALL_PREFIX) +mark_as_advanced(CMAKE_CONFIGURATION_TYPES) + +# output folders +#set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${projectOutDir}/game) +#set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${projectOutDir}/game) +#set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${projectOutDir}/game) + +# finds and adds sources files in a folder +macro(addPath dir) + set(tmpa "") + file(GLOB tmpa + ${dir}/*.cpp + ${dir}/*.c + ${dir}/*.cc + ${dir}/*.h) + LIST(APPEND ${PROJECT_NAME}_files "${tmpa}") + LIST(APPEND ${PROJECT_NAME}_paths "${dir}") + #message(STATUS "addPath ${PROJECT_NAME} : ${tmpa}") + #set(t "${${t}};${tmpa}") +endmacro() + +# adds a file to the sources +macro(addFile filename) + LIST(APPEND ${PROJECT_NAME}_files "${filename}") + #message(STATUS "addFile ${PROJECT_NAME} : ${filename}") +endmacro() + +# finds and adds sources files in a folder recursively +macro(addPathRec dir) + set(tmpa "") + file(GLOB_RECURSE tmpa + ${dir}/*.cpp + ${dir}/*.c + ${dir}/*.cc + ${dir}/*.h) + LIST(APPEND ${PROJECT_NAME}_files "${tmpa}") + LIST(APPEND ${PROJECT_NAME}_paths "${dir}") + #message(STATUS "addPathRec ${PROJECT_NAME} : ${tmpa}") +endmacro() + +# adds a definition +macro(addDef def) + set_property(TARGET ${PROJECT_NAME} APPEND PROPERTY COMPILE_DEFINITIONS "${def}") +endmacro() +# adds a definition +macro(addDebugDef def) + set_property(TARGET ${PROJECT_NAME} APPEND PROPERTY COMPILE_DEFINITIONS_DEBUG "${def}") +endmacro() + +# adds a required definition. Are processed on addExecutable or addStaticLib +macro(addRequiredDefinition def) + #message(STATUS "${PROJECT_NAME} : add def : ${def}") + LIST( APPEND ${PROJECT_NAME}_required_definition ${def} ) +endmacro() +# adds a required debug definition. Are processed on addExecutable or addStaticLib +macro(addRequiredDebugDefinition def) + #message(STATUS "${PROJECT_NAME} : add def : ${def}") + LIST( APPEND ${PROJECT_NAME}_required_debug_definition ${def} ) +endmacro() + +# add definitions to project +macro( _processProjectDefinition ) + foreach( def ${${PROJECT_NAME}_required_definition} ) + addDef( ${def} ) + endforeach() + + foreach( def ${${PROJECT_NAME}_required_debug_definition} ) + addDebugDef( ${def} ) + endforeach() + + #clear required defs + set( ${PROJECT_NAME}_required_definition ) + set( ${PROJECT_NAME}_required_debug_definition ) +endmacro() + +# adds an include path +macro(addInclude incPath) + #message(STATUS "${PROJECT_NAME} : add include path : ${incPath}") + set_property(TARGET ${PROJECT_NAME} APPEND PROPERTY INCLUDE_DIRECTORIES "${incPath}") +endmacro() + +# adds a library to link against +macro(addLib lib) + #message(STATUS "${PROJECT_NAME} : add lib : ${lib}") + target_link_libraries(${PROJECT_NAME} "${lib}") +endmacro() + +# adds a library dependency. Are processed on addExecutable or addStaticLib +macro(addRequiredLibrary lib) + #message(STATUS "${PROJECT_NAME} : add lib : ${lib}") + LIST( APPEND ${PROJECT_NAME}_required_library ${lib} ) +endmacro() + +# adds a link dependency. Are processed on addExecutable or addStaticLib +macro(addRequiredLink lib) + #message(STATUS "${PROJECT_NAME} : add lib : ${lib}") + LIST( APPEND ${PROJECT_NAME}_required_link ${lib} ) +endmacro() + +macro( _processProjectLibrary ) + # Append currect project to PROJECT_STACK + LIST( APPEND PROJECT_STACK "${PROJECT_NAME}" ) + + foreach( lib ${${PROJECT_NAME}_required_library} ) + #message( "adding library dependency: ${lib}" ) + include( ${lib} ) + endforeach() + + #clear required libraries + set( ${PROJECT_NAME}_required_library ) + + # pop currect project form PROJECT_STACK + LIST(REMOVE_AT PROJECT_STACK -1) + + # get currect project form stack + if( PROJECT_STACK ) + LIST(GET PROJECT_STACK -1 TEMP_PROJECT) + project( ${TEMP_PROJECT} ) + endif() + + +endmacro() + +macro( _processProjectLinks ) + #message( "_processProjectLinks: ${PROJECT_NAME}" ) + foreach( lib ${${PROJECT_NAME}_required_link} ) + addLib( ${lib} ) + endforeach() + + #clear required libraries + set( ${PROJECT_NAME}_required_link ) +endmacro() + + +# adds a path to search for libs +macro(addLibPath dir) + link_directories(${dir}) +endmacro() + +# creates a proper filter for VS +macro(generateFilters relDir) + foreach(f ${${PROJECT_NAME}_files}) + # Get the path of the file relative to ${DIRECTORY}, + # then alter it (not compulsory) + file(RELATIVE_PATH SRCGR ${relDir} ${f}) + set(SRCGR "${PROJECT_NAME}/${SRCGR}") + # Extract the folder, ie remove the filename part + string(REGEX REPLACE "(.*)(/[^/]*)$" "\\1" SRCGR ${SRCGR}) + # do not have any ../ dirs + string(REPLACE "../" "" SRCGR ${SRCGR}) + # Source_group expects \\ (double antislash), not / (slash) + string(REPLACE / \\ SRCGR ${SRCGR}) + #STRING(REPLACE "//" "/" SRCGR ${SRCGR}) + #message(STATUS "FILE: ${f} -> ${SRCGR}") + source_group("${SRCGR}" FILES ${f}) + endforeach() +endmacro() + +# creates a proper filter for VS +macro(generateFiltersSpecial relDir) + foreach(f ${${PROJECT_NAME}_files}) + # Get the path of the file relative to ${DIRECTORY}, + # then alter it (not compulsory) + file(RELATIVE_PATH SRCGR ${relDir} ${f}) + set(SRCGR "torque3d/${SRCGR}") + # Extract the folder, ie remove the filename part + string(REGEX REPLACE "(.*)(/[^/]*)$" "\\1" SRCGR ${SRCGR}) + # do not have any ../ dirs + string(REPLACE "../" "" SRCGR ${SRCGR}) + IF("${SRCGR}" MATCHES "^torque3d/My Projects/.*$") + string(REPLACE "torque3d/My Projects/${PROJECT_NAME}/" "" SRCGR ${SRCGR}) + string(REPLACE "/source" "" SRCGR ${SRCGR}) + endif() + # Source_group expects \\ (double antislash), not / (slash) + string(REPLACE / \\ SRCGR ${SRCGR}) + #STRING(REPLACE "//" "/" SRCGR ${SRCGR}) + IF(EXISTS "${f}" AND NOT IS_DIRECTORY "${f}") + #message(STATUS "FILE: ${f} -> ${SRCGR}") + source_group("${SRCGR}" FILES ${f}) + endif() + endforeach() +endmacro() +# macro to add a static library +macro(addStaticLib) + # more paths? + if(${ARGC} GREATER 0) + foreach(dir ${ARGV0}) + addPath("${dir}") + endforeach() + endif() + # now inspect the paths we got + set(firstDir "") + foreach(dir ${${PROJECT_NAME}_paths}) + if("${firstDir}" STREQUAL "") + set(firstDir "${dir}") + endif() + endforeach() + generateFilters("${firstDir}") + if(TORQUE_STATIC) + add_library("${PROJECT_NAME}" STATIC ${${PROJECT_NAME}_files}) + else() + add_library("${PROJECT_NAME}" SHARED ${${PROJECT_NAME}_files}) + endif() + # omg - only use the first folder ... otehrwise we get lots of header name collisions + #foreach(dir ${${PROJECT_NAME}_paths}) + addInclude("${firstDir}") + #endforeach() + + _processProjectLinks() + _processProjectLibrary() + _processProjectDefinition() +endmacro() + +# macro to add an executable +macro(addExecutable) + # now inspect the paths we got + set(firstDir "") + foreach(dir ${${PROJECT_NAME}_paths}) + if("${firstDir}" STREQUAL "") + set(firstDir "${dir}") + endif() + endforeach() + generateFiltersSpecial("${firstDir}") + add_executable("${PROJECT_NAME}" WIN32 ${${PROJECT_NAME}_files}) + # omg - only use the first folder ... otehrwise we get lots of header name collisions + addInclude("${firstDir}") + + _processProjectLinks() + _processProjectLibrary() + _processProjectDefinition() +endmacro() + +macro(setupVersionNumbers) + set(TORQUE_APP_VERSION_MAJOR 1 CACHE INTEGER "") + set(TORQUE_APP_VERSION_MINOR 0 CACHE INTEGER "") + set(TORQUE_APP_VERSION_PATCH 0 CACHE INTEGER "") + set(TORQUE_APP_VERSION_TWEAK 0 CACHE INTEGER "") + mark_as_advanced(TORQUE_APP_VERSION_TWEAK) + MATH(EXPR TORQUE_APP_VERSION "${TORQUE_APP_VERSION_MAJOR} * 1000 + ${TORQUE_APP_VERSION_MINOR} * 100 + ${TORQUE_APP_VERSION_PATCH} * 10 + ${TORQUE_APP_VERSION_TWEAK}") + set(TORQUE_APP_VERSION_STRING "${TORQUE_APP_VERSION_MAJOR}.${TORQUE_APP_VERSION_MINOR}.${TORQUE_APP_VERSION_PATCH}.${TORQUE_APP_VERSION_TWEAK}") + #message(STATUS "version numbers: ${TORQUE_APP_VERSION} / ${TORQUE_APP_VERSION_STRING}") +endmacro() + +macro(setupPackaging) + INCLUDE(CPack) + # only enable zips for now + set(CPACK_BINARY_NSIS OFF CACHE INTERNAL "" FORCE) + set(CPACK_BINARY_ZIP ON CACHE INTERNAL "" FORCE) + set(CPACK_SOURCE_ZIP OFF CACHE INTERNAL "" FORCE) + SET(CPACK_GENERATOR "ZIP") + SET(CPACK_PACKAGE_VENDOR "${PROJECT_NAME}") + SET(CPACK_PACKAGE_DESCRIPTION_SUMMARY "${PROJECT_NAME}") + SET(CPACK_INCLUDE_TOPLEVEL_DIRECTORY 1) + SET(CPACK_OUTPUT_FILE_PREFIX "${projectDir}/packages/${PROJECT_NAME}") + SET(CPACK_PACKAGE_INSTALL_DIRECTORY "") + #SET(CPACK_PACKAGE_DESCRIPTION_FILE "${CMAKE_CURRENT_SOURCE_DIR}/ReadMe.txt") + #SET(CPACK_RESOURCE_FILE_LICENSE "${CMAKE_CURRENT_SOURCE_DIR}/Copyright.txt") + SET(CPACK_PACKAGE_VERSION_MAJOR "${TORQUE_APP_VERSION_MAJOR}") + SET(CPACK_PACKAGE_VERSION_MINOR "${TORQUE_APP_VERSION_MINOR}") + SET(CPACK_PACKAGE_VERSION_PATCH "${TORQUE_APP_VERSION_PATCH}") + #SET(CPACK_PACKAGE_EXECUTABLES "${PROJECT_NAME}" "${PROJECT_NAME}") + SET(CPACK_SOURCE_PACKAGE_FILE_NAME "${PROJECT_NAME}-${TORQUE_APP_VERSION_STRING}") + #SET(CPACK_SOURCE_STRIP_FILES "") +endmacro() +# always static for now +set(TORQUE_STATIC ON) +#option(TORQUE_STATIC "enables or disable static" OFF) + +if(WIN32) + set(TORQUE_CXX_FLAGS "/MP /O2 /Ob2 /Oi /Ot /Oy /GT /Zi /W4 /nologo /GF /EHsc /GS- /Gy- /Qpar- /arch:SSE2 /fp:fast /fp:except- /GR /Zc:wchar_t- /wd4018 /wd4100 /wd4121 /wd4127 /wd4130 /wd4244 /wd4245 /wd4389 /wd4511 /wd4512 /wd4800 /wd4995 /D_CRT_SECURE_NO_WARNINGS " CACHE TYPE STRING) + mark_as_advanced(TORQUE_CXX_FLAGS) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${TORQUE_CXX_FLAGS}") + set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${CMAKE_CXX_FLAGS}") + set(CMAKE_EXE_LINKER_FLAGS "/LARGEADDRESSAWARE") + #set(STATIC_LIBRARY_FLAGS "/OPT:NOREF") + + # Force static runtime libraries + if(TORQUE_STATIC) + FOREACH(flag + CMAKE_C_FLAGS_RELEASE + CMAKE_C_FLAGS_RELWITHDEBINFO + CMAKE_C_FLAGS_DEBUG + CMAKE_C_FLAGS_DEBUG_INIT + CMAKE_CXX_FLAGS_RELEASE + CMAKE_CXX_FLAGS_RELWITHDEBINFO + CMAKE_CXX_FLAGS_DEBUG + CMAKE_CXX_FLAGS_DEBUG_INIT) + STRING(REPLACE "/MD" "/MT" "${flag}" "${${flag}}") + SET("${flag}" "${${flag}} /EHsc") + ENDFOREACH() + endif() +endif() + + +# fix the debug/release subfolders on windows +if(MSVC) + FOREACH(CONF ${CMAKE_CONFIGURATION_TYPES}) + # Go uppercase (DEBUG, RELEASE...) + STRING(TOUPPER "${CONF}" CONF) + #SET("CMAKE_ARCHIVE_OUTPUT_DIRECTORY_${CONF}" "${projectOutDir}") + SET("CMAKE_RUNTIME_OUTPUT_DIRECTORY_${CONF}" "${projectOutDir}") + ENDFOREACH() +endif() diff --git a/Tools/CMake/cleanup-win.bat.in b/Tools/CMake/cleanup-win.bat.in new file mode 100644 index 000000000..0e9906dd8 --- /dev/null +++ b/Tools/CMake/cleanup-win.bat.in @@ -0,0 +1,47 @@ +@ECHO off + +:: Delete procedural shaders +echo shaders +del /q /a:-R shaders\procedural\*.* +:: Delete dumped shader disassembly files +for /R %%a IN (*._dis.txt) do IF EXIST "%%a._dis.txt" del "%%a._dis.txt" + +:: Delete fonts +echo fonts +del /q /a:-R core\fonts\*.* + +:: CEF cache +echo browser cache +del /q /a:-R cache + + +:: the cached meshes and alike +echo meshes and alike +for /R %%a IN (*.dae) do IF EXIST "%%~pna.cached.dts" del "%%~pna.cached.dts" +for /R %%a IN (*.imposter*.dds) do del "%%a" + +:: the torque script compilations +echo compiled script +for /R %%a IN (*.cs) do IF EXIST "%%a.dso" del "%%a.dso" +for /R %%a IN (*.cs) do IF EXIST "%%a.edso" del "%%a.edso" +for /R %%a IN (*.gui) do IF EXIST "%%a.dso" del "%%a.dso" +for /R %%a IN (*.gui) do IF EXIST "%%a.edso" del "%%a.edso" +for /R %%a IN (*.ts) do IF EXIST "%%a.dso" del "%%a.dso" +for /R %%a IN (*.ts) do IF EXIST "%%a.edso" del "%%a.edso" + +:: the user settings and alike +echo settings +IF EXIST "prefs.cs" del /s prefs.cs +IF EXIST "core\prefs.cs" del /s core\prefs.cs +::IF EXIST "scripts\client\prefs.cs" del /s scripts\client\prefs.cs +IF EXIST "scripts\server\banlist.cs" del /s scripts\server\banlist.cs +IF EXIST "scripts\server\prefs.cs" del /s scripts\server\prefs.cs +IF EXIST "client\config.cs" del /s client\config.cs +IF EXIST "config.cs" del /s config.cs +IF EXIST "tools\settings.xml" del /s tools\settings.xml +IF EXIST "banlist.cs" del /s banlist.cs + +:: logs +echo logs +IF EXIST "torque3d.log" del /s torque3d.log +echo DONE! \ No newline at end of file diff --git a/Tools/CMake/collada.cmake b/Tools/CMake/collada.cmake new file mode 100644 index 000000000..a875643d8 --- /dev/null +++ b/Tools/CMake/collada.cmake @@ -0,0 +1,17 @@ +project(collada) + +addPath("${libDir}/collada/src/1.4/dom") +addPath("${libDir}/collada/src/dae") +addPath("${libDir}/collada/src/modules/LIBXMLPlugin") +addPath("${libDir}/collada/src/modules/stdErrPlugin") +addPath("${libDir}/collada/src/modules/STLDatabase") + +addStaticLib() + +addDef(DOM_INCLUDE_TINYXML) +addDef(PCRE_STATIC) + +addInclude(${libDir}/collada/include) +addInclude(${libDir}/collada/include/1.4) +addInclude(${libDir}/pcre) +addInclude(${libDir}/tinyxml) diff --git a/Tools/CMake/convexDecomp.cmake b/Tools/CMake/convexDecomp.cmake new file mode 100644 index 000000000..eb98a6144 --- /dev/null +++ b/Tools/CMake/convexDecomp.cmake @@ -0,0 +1,3 @@ +project(convexDecomp) + +addStaticLib("${libDir}/convexDecomp") diff --git a/Tools/CMake/libogg.cmake b/Tools/CMake/libogg.cmake new file mode 100644 index 000000000..fc83fd957 --- /dev/null +++ b/Tools/CMake/libogg.cmake @@ -0,0 +1,7 @@ +project(libogg) + +addPathRec("${libDir}/libogg") + +addStaticLib() + +addInclude(${libDir}/libogg/include) diff --git a/Tools/CMake/libraries/library_recast.cmake b/Tools/CMake/libraries/library_recast.cmake new file mode 100644 index 000000000..677459606 --- /dev/null +++ b/Tools/CMake/libraries/library_recast.cmake @@ -0,0 +1,18 @@ +# Recast library +project(recast) + +# Source +addPathRec( "${libDir}/recast/DebugUtils/Source" ) +addPathRec( "${libDir}/recast/Recast/Source" ) +addPathRec( "${libDir}/recast/Detour/Source" ) +addPathRec( "${libDir}/recast/DetourCrowd/Source" ) +addPathRec( "${libDir}/recast/DetourTileCache/Source" ) + +# Additional includes +include_directories( "${libDir}/recast/DebugUtils/Include" ) +include_directories( "${libDir}/recast/Recast/Include" ) +include_directories( "${libDir}/recast/Detour/Include" ) +include_directories( "${libDir}/recast/DetourTileCache/Include" ) +include_directories( "${libDir}/recast/DetourCrowd/Include" ) + +addStaticLib() \ No newline at end of file diff --git a/Tools/CMake/libtheora.cmake b/Tools/CMake/libtheora.cmake new file mode 100644 index 000000000..0e6dda65d --- /dev/null +++ b/Tools/CMake/libtheora.cmake @@ -0,0 +1,10 @@ +project(libtheora) + +addPathRec("${libDir}/libtheora") + +addStaticLib() + +addDef(TORQUE_OGGTHEORA) +addDef(TORQUE_OGGVORIBS) +addInclude(${libDir}/libogg/include) +addInclude(${libDir}/libtheora/include) diff --git a/Tools/CMake/libvorbis.cmake b/Tools/CMake/libvorbis.cmake new file mode 100644 index 000000000..9f1e2eb4a --- /dev/null +++ b/Tools/CMake/libvorbis.cmake @@ -0,0 +1,9 @@ +project(libvorbis) + +addPathRec("${libDir}/libvorbis") + +addStaticLib() + +addDef(TORQUE_OGGVORBIS) +addInclude(${libDir}/libvorbis/include) +addInclude(${libDir}/libogg/include) diff --git a/Tools/CMake/ljpeg.cmake b/Tools/CMake/ljpeg.cmake new file mode 100644 index 000000000..d518cb504 --- /dev/null +++ b/Tools/CMake/ljpeg.cmake @@ -0,0 +1,3 @@ +project(ljpeg) + +addStaticLib("${libDir}/ljpeg") diff --git a/Tools/CMake/lmng.cmake b/Tools/CMake/lmng.cmake new file mode 100644 index 000000000..27da5444f --- /dev/null +++ b/Tools/CMake/lmng.cmake @@ -0,0 +1,9 @@ +project(lmng) + +addStaticLib("${libDir}/${PROJECT_NAME}") + +addDef(MNG_OPTIMIZE_OBJCLEANUP) + +addInclude(${libDir}/lpng) +addInclude(${libDir}/zlib) +addInclude(${libDir}/ljpeg) diff --git a/Tools/CMake/lpng.cmake b/Tools/CMake/lpng.cmake new file mode 100644 index 000000000..0dbb15501 --- /dev/null +++ b/Tools/CMake/lpng.cmake @@ -0,0 +1,7 @@ +project(lpng) + +addStaticLib("${libDir}/${PROJECT_NAME}") + +# addDef(PNG_NO_ASSEMBLER_CODE) + +addInclude(${libDir}/zlib) diff --git a/Tools/CMake/lungif.cmake b/Tools/CMake/lungif.cmake new file mode 100644 index 000000000..2ede4dd3a --- /dev/null +++ b/Tools/CMake/lungif.cmake @@ -0,0 +1,5 @@ +project(lungif) + +addStaticLib("${libDir}/${PROJECT_NAME}") + +addDef(_GBA_NO_FILEIO) diff --git a/Tools/CMake/modules/module_hydra.cmake b/Tools/CMake/modules/module_hydra.cmake new file mode 100644 index 000000000..a3139e6c2 --- /dev/null +++ b/Tools/CMake/modules/module_hydra.cmake @@ -0,0 +1,19 @@ +# module OculusVR + +# Source +addPathRec( "${srcDir}/platform/input/razerHydra" ) + +# Includes +include_directories( "${TORQUE_RAZERHYDRA_SDK_PATH}/include" ) + +# Install +if( WIN32 ) + # File Copy for Release + INSTALL(FILES "${TORQUE_RAZERHYDRA_SDK_PATH}/bin/win32/release_dll/sixense.dll" DESTINATION "${projectOutDir}") + + # File Copy for Debug + INSTALL(FILES "${TORQUE_RAZERHYDRA_SDK_PATH}/bin/win32/debug_dll/sixensed.dll" DESTINATION "${projectOutDir}" CONFIGURATIONS "Debug" ) + # Only needed by the debug sixense library + INSTALL(FILES "${TORQUE_RAZERHYDRA_SDK_PATH}/samples/win32/sixense_simple3d/DeviceDLL.dll" DESTINATION "${projectOutDir}" CONFIGURATIONS "Debug" ) +endif() + diff --git a/Tools/CMake/modules/module_navigation.cmake b/Tools/CMake/modules/module_navigation.cmake new file mode 100644 index 000000000..512ed42f3 --- /dev/null +++ b/Tools/CMake/modules/module_navigation.cmake @@ -0,0 +1,16 @@ +# Navigation module + +addRequiredDefinition( "TORQUE_NAVIGATION_ENABLED" ) +addRequiredLibrary( "libraries/library_recast.cmake" ) +addRequiredLink( "recast" ) + +# files +addPathRec( "${srcDir}/navigation" ) + +# include paths +include_directories( "${libDir}/recast/DebugUtils/Include" ) +include_directories( "${libDir}/recast/Recast/Include" ) +include_directories( "${libDir}/recast/Detour/Include" ) +include_directories( "${libDir}/recast/DetourTileCache/Include" ) +include_directories( "${libDir}/recast/DetourCrowd/Include" ) + diff --git a/Tools/CMake/modules/module_oculusVR.cmake b/Tools/CMake/modules/module_oculusVR.cmake new file mode 100644 index 000000000..044154f7c --- /dev/null +++ b/Tools/CMake/modules/module_oculusVR.cmake @@ -0,0 +1,15 @@ +# module OculusVR + +# Source +addPathRec( "${srcDir}/platform/input/oculusVR" ) + +# Includes +include_directories( "${TORQUE_OCULUSVR_SDK_PATH}/LibOVR/Include" ) +include_directories( "${TORQUE_OCULUSVR_SDK_PATH}/LibOVR/Src" ) + +# Libs +if( WIN32 ) + link_directories( "${TORQUE_OCULUSVR_SDK_PATH}/LibOVR/Lib/Win32" ) + addRequiredLink( "libovr.lib" ) + addRequiredLink( "libovrd.lib" ) +endif() \ No newline at end of file diff --git a/Tools/CMake/opcode.cmake b/Tools/CMake/opcode.cmake new file mode 100644 index 000000000..df94b0c7f --- /dev/null +++ b/Tools/CMake/opcode.cmake @@ -0,0 +1,9 @@ +project(opcode) + +addPath("${libDir}/${PROJECT_NAME}") +addPath("${libDir}/${PROJECT_NAME}/Ice") + +addStaticLib() + +addDef(TORQUE_OPCODE) +addDef(ICE_NO_DLL) diff --git a/Tools/CMake/pcre.cmake b/Tools/CMake/pcre.cmake new file mode 100644 index 000000000..0f86b50b2 --- /dev/null +++ b/Tools/CMake/pcre.cmake @@ -0,0 +1,8 @@ +project(pcre) + +addStaticLib("${libDir}/pcre") + +addDef(PCRE_STATIC) +addDef(HAVE_CONFIG_H) + +set_property(TARGET pcre PROPERTY COMPILE_FLAGS /TP) #/TP = compile as C++ diff --git a/Tools/CMake/squish.cmake b/Tools/CMake/squish.cmake new file mode 100644 index 000000000..acc3332bc --- /dev/null +++ b/Tools/CMake/squish.cmake @@ -0,0 +1,3 @@ +project(squish) + +addStaticLib("${libDir}/${PROJECT_NAME}") diff --git a/Tools/CMake/template.cmake b/Tools/CMake/template.cmake new file mode 100644 index 000000000..8040cddb0 --- /dev/null +++ b/Tools/CMake/template.cmake @@ -0,0 +1,21 @@ +# this is a template file that should help you write a new cmake build script for a new library + + +# 1st thing: the project name +project(pcre) + +# 2nd: add the paths where the source code is + +addPath("${libDir}/pcre") +addPathRec("${libDir}/pcre") + +# 3rd: add addStaticLib() +addStaticLib() + +# then add definitions +addDef(PCRE_STATIC) +addDef(HAVE_CONFIG_H) + +# and maybe more include paths +addInclude(${libDir}/libvorbis/include) +addInclude(${libDir}/libogg/include) diff --git a/Tools/CMake/template.torsion.in b/Tools/CMake/template.torsion.in new file mode 100644 index 000000000..f832ad13b --- /dev/null +++ b/Tools/CMake/template.torsion.in @@ -0,0 +1,39 @@ + +@TORQUE_APP_NAME@ + +main.cs +dbgSetParameters( #port#, "#password#", true ); + +core +scripts +art +levels +shaders +tools + +cs; gui + + +Release +@TORQUE_APP_NAME@.exe + +true +true +true +false + + +Debug +@TORQUE_APP_NAME@.exe + +true +true +true +false + + + +@TORQUE_APP_NAME@ +HEAD +true + diff --git a/Tools/CMake/tinyxml.cmake b/Tools/CMake/tinyxml.cmake new file mode 100644 index 000000000..c17dfbba1 --- /dev/null +++ b/Tools/CMake/tinyxml.cmake @@ -0,0 +1,3 @@ +project(tinyxml) + +addStaticLib("${libDir}/${PROJECT_NAME}") diff --git a/Tools/CMake/torque-win.rc.in b/Tools/CMake/torque-win.rc.in new file mode 100644 index 000000000..498d1e95e --- /dev/null +++ b/Tools/CMake/torque-win.rc.in @@ -0,0 +1,123 @@ +//Microsoft Developer Studio generated resource script. +// +#define IDI_ICON1 103 +#define IDI_ICON2 107 + +// Next default values for new objects +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NEXT_RESOURCE_VALUE 108 +#define _APS_NEXT_COMMAND_VALUE 40001 +#define _APS_NEXT_CONTROL_VALUE 1000 +#define _APS_NEXT_SYMED_VALUE 101 +#endif +#endif + +#define APSTUDIO_READONLY_SYMBOLS +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 2 resource. +// +#include "windows.h" + +///////////////////////////////////////////////////////////////////////////// +#undef APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +// English (U.S.) resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) +#ifdef _WIN32 +LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US +#pragma code_page(1252) +#endif //_WIN32 + +///////////////////////////////////////////////////////////////////////////// +// +// Icon +// + +// Icon with lowest ID value placed first to ensure application icon +// remains consistent on all systems. +IDI_ICON1 ICON DISCARDABLE "torque.ico" +IDI_ICON2 ICON DISCARDABLE "torque.ico" + +#ifdef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +1 TEXTINCLUDE DISCARDABLE +BEGIN + "resource.h\0" +END + +2 TEXTINCLUDE DISCARDABLE +BEGIN + "#include ""windows.h""\r\n" + "\0" +END + +3 TEXTINCLUDE DISCARDABLE +BEGIN + "\r\n" + "\0" +END + +#endif // APSTUDIO_INVOKED + +///////////////////////////////////////////////////////////////////////////// + +///////////////////////////////////////////////////////////////////////////// +// +// Version +// + +VS_VERSION_INFO VERSIONINFO + FILEVERSION @TORQUE_APP_VERSION_MAJOR@,@TORQUE_APP_VERSION_MINOR@,@TORQUE_APP_VERSION_PATCH@,@TORQUE_APP_VERSION_TWEAK@ + PRODUCTVERSION @TORQUE_APP_VERSION_MAJOR@,@TORQUE_APP_VERSION_MINOR@,@TORQUE_APP_VERSION_PATCH@,@TORQUE_APP_VERSION_TWEAK@ + FILEFLAGSMASK 0x3fL +#ifdef _DEBUG + FILEFLAGS 0x1L +#else + FILEFLAGS 0x0L +#endif + FILEOS 0x40004L + FILETYPE 0x1L + FILESUBTYPE 0x0L +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904b0" + BEGIN + VALUE "CompanyName", "@PROJECT_NAME@" + VALUE "FileDescription", "@PROJECT_NAME@" + VALUE "FileVersion", "@TORQUE_APP_VERSION_STRING@" + VALUE "InternalName", "@PROJECT_NAME@" + VALUE "LegalCopyright", "Copyright (C) 2014" + VALUE "OriginalFilename", "@PROJECT_NAME@" + VALUE "ProductName", "@PROJECT_NAME@" + VALUE "ProductVersion", "@TORQUE_APP_VERSION_STRING@" + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x409, 1200 + END +END + +#endif // English (U.S.) resources +///////////////////////////////////////////////////////////////////////////// + + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// + + +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED diff --git a/Tools/CMake/torque.ico b/Tools/CMake/torque.ico new file mode 100644 index 000000000..22ac1a3d1 Binary files /dev/null and b/Tools/CMake/torque.ico differ diff --git a/Tools/CMake/torque3d.cmake b/Tools/CMake/torque3d.cmake new file mode 100644 index 000000000..1e9fb9bf6 --- /dev/null +++ b/Tools/CMake/torque3d.cmake @@ -0,0 +1,493 @@ +project(${TORQUE_APP_NAME}) + +# TODO: fmod support + +############################################################################### +# modules +############################################################################### +option(TORQUE_SFX_VORBIS "Vorbis Sound" ON) +mark_as_advanced(TORQUE_SFX_VORBIS) +option(TORQUE_ADVANCED_LIGHTING "Advanced Lighting" ON) +mark_as_advanced(TORQUE_ADVANCED_LIGHTING) +option(TORQUE_BASIC_LIGHTING "Basic Lighting" ON) +mark_as_advanced(TORQUE_BASIC_LIGHTING) +option(TORQUE_THEORA "Theora Video Support" ON) +mark_as_advanced(TORQUE_THEORA) +option(TORQUE_SFX_DirectX "DirectX Sound" ON) +mark_as_advanced(TORQUE_SFX_DirectX) +option(TORQUE_SFX_OPENAL "OpenAL Sound" ON) +mark_as_advanced(TORQUE_SFX_OPENAL) +option(TORQUE_HIFI "HIFI? support" OFF) +mark_as_advanced(TORQUE_HIFI) +option(TORQUE_EXTENDED_MOVE "Extended move support" OFF) +mark_as_advanced(TORQUE_EXTENDED_MOVE) +option(TORQUE_NAVIGATION "Enable Navigation module" OFF) +#mark_as_advanced(TORQUE_NAVIGATION) + +#Oculus VR +option(TORQUE_OCULUSVR "Enable OCULUSVR module" OFF) +mark_as_advanced(TORQUE_OCULUSVR) +if(TORQUE_OCULUSVR) + set(TORQUE_OCULUSVR_SDK_PATH "" CACHE PATH "OCULUSVR library path" FORCE) +else() # hide variable + set(TORQUE_OCULUSVR_SDK_PATH "" CACHE INTERNAL "" FORCE) +endif() + +#Hydra +option(TORQUE_HYDRA "Enable HYDRA module" OFF) +mark_as_advanced(TORQUE_HYDRA) +if(TORQUE_HYDRA) + set(TORQUE_HYDRA_SDK_PATH "" CACHE PATH "HYDRA library path" FORCE) +else() # hide variable + set(TORQUE_HYDRA_SDK_PATH "" CACHE INTERNAL "" FORCE) +endif() + +############################################################################### +# options +############################################################################### +option(TORQUE_MULTITHREAD "Multi Threading" ON) +mark_as_advanced(TORQUE_MULTITHREAD) + +option(TORQUE_DISABLE_MEMORY_MANAGER "Disable memory manager" OFF) +mark_as_advanced(TORQUE_DISABLE_MEMORY_MANAGER) + +option(TORQUE_DISABLE_VIRTUAL_MOUNT_SYSTEM "Disable virtual mount system" OFF) +mark_as_advanced(TORQUE_DISABLE_VIRTUAL_MOUNT_SYSTEM) + +option(TORQUE_PLAYER "Playback only?" OFF) +mark_as_advanced(TORQUE_PLAYER) + +option(TORQUE_TOOLS "Enable or disable the tools" ON) +mark_as_advanced(TORQUE_TOOLS) + +option(TORQUE_ENABLE_PROFILER "Enable or disable the profiler" OFF) +mark_as_advanced(TORQUE_ENABLE_PROFILER) + +option(TORQUE_DEBUG "T3D Debug mode" OFF) +mark_as_advanced(TORQUE_DEBUG) + +option(TORQUE_SHIPPING "T3D Shipping build?" OFF) +mark_as_advanced(TORQUE_SHIPPING) + +option(TORQUE_DEBUG_NET "debug network" OFF) +mark_as_advanced(TORQUE_DEBUG_NET) + +option(TORQUE_DEBUG_NET_MOVES "debug network moves" OFF) +mark_as_advanced(TORQUE_DEBUG_NET_MOVES) + +option(TORQUE_ENABLE_ASSERTS "enables or disable asserts" OFF) +mark_as_advanced(TORQUE_ENABLE_ASSERTS) + +option(TORQUE_DEBUG_GFX_MODE "triggers graphics debug mode" OFF) +mark_as_advanced(TORQUE_DEBUG_GFX_MODE) + +#option(DEBUG_SPEW "more debug" OFF) +set(TORQUE_NO_DSO_GENERATION ON) + +if(WIN32) + # warning C4800: 'XXX' : forcing value to bool 'true' or 'false' (performance warning) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -wd4800") + # warning C4018: '<' : signed/unsigned mismatch + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -wd4018") + # warning C4244: 'initializing' : conversion from 'XXX' to 'XXX', possible loss of data + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -wd4244") + + link_directories($ENV{DXSDK_DIR}/Lib/x86) +endif() + +############################################################################### +# Always enabled paths first +############################################################################### +addPath("${srcDir}/") # must come first :) +addPathRec("${srcDir}/app") +addPath("${srcDir}/sfx/media") +addPath("${srcDir}/sfx/null") +addPath("${srcDir}/sfx") +addPath("${srcDir}/component") +addPath("${srcDir}/component/interfaces") +addPath("${srcDir}/console") +addPath("${srcDir}/core") +addPath("${srcDir}/core/stream") +addPath("${srcDir}/core/strings") +addPath("${srcDir}/core/util") +addPath("${srcDir}/core/util/test") +addPath("${srcDir}/core/util/journal") +addPath("${srcDir}/core/util/journal/test") +addPath("${srcDir}/core/util/zip") +addPath("${srcDir}/core/util/zip/unitTests") +addPath("${srcDir}/core/util/zip/compressors") +addPath("${srcDir}/i18n") +addPath("${srcDir}/sim") +#addPath("${srcDir}/unit/tests") +addPath("${srcDir}/unit") +addPath("${srcDir}/util") +addPath("${srcDir}/windowManager") +addPath("${srcDir}/windowManager/torque") +addPath("${srcDir}/windowManager/test") +addPath("${srcDir}/math") +addPath("${srcDir}/math/util") +addPath("${srcDir}/math/test") +addPath("${srcDir}/platform") +addPath("${srcDir}/cinterface") +addPath("${srcDir}/platform/nativeDialogs") +addPath("${srcDir}/platform/menus") +addPath("${srcDir}/platform/test") +addPath("${srcDir}/platform/threads") +addPath("${srcDir}/platform/async") +addPath("${srcDir}/platform/input") +addPath("${srcDir}/platform/output") +addPath("${srcDir}/app") +addPath("${srcDir}/app/net") +addPath("${srcDir}/util/messaging") +addPath("${srcDir}/gfx/Null") +addPath("${srcDir}/gfx/test") +addPath("${srcDir}/gfx/bitmap") +addPath("${srcDir}/gfx/bitmap/loaders") +addPath("${srcDir}/gfx/util") +addPath("${srcDir}/gfx/video") +addPath("${srcDir}/gfx") +addPath("${srcDir}/shaderGen") +addPath("${srcDir}/gfx/sim") +addPath("${srcDir}/gui/buttons") +addPath("${srcDir}/gui/containers") +addPath("${srcDir}/gui/controls") +addPath("${srcDir}/gui/core") +addPath("${srcDir}/gui/game") +addPath("${srcDir}/gui/shiny") +addPath("${srcDir}/gui/utility") +addPath("${srcDir}/gui") +addPath("${srcDir}/collision") +addPath("${srcDir}/materials") +addPath("${srcDir}/lighting") +addPath("${srcDir}/lighting/common") +addPath("${srcDir}/renderInstance") +addPath("${srcDir}/scene") +addPath("${srcDir}/scene/culling") +addPath("${srcDir}/scene/zones") +addPath("${srcDir}/scene/mixin") +addPath("${srcDir}/shaderGen") +addPath("${srcDir}/terrain") +addPath("${srcDir}/environment") +addPath("${srcDir}/forest") +addPath("${srcDir}/forest/ts") +addPath("${srcDir}/ts") +addPath("${srcDir}/ts/arch") +addPath("${srcDir}/physics") +addPath("${srcDir}/gui/3d") +addPath("${srcDir}/postFx") +addPath("${srcDir}/T3D") +addPath("${srcDir}/T3D/examples") +addPath("${srcDir}/T3D/fps") +addPath("${srcDir}/T3D/fx") +addPath("${srcDir}/T3D/vehicles") +addPath("${srcDir}/T3D/physics") +addPath("${srcDir}/T3D/decal") +addPath("${srcDir}/T3D/sfx") +addPath("${srcDir}/T3D/gameBase") +addPath("${srcDir}/T3D/turret") +addPath("${srcDir}/main/") +addPathRec("${srcDir}/ts/collada") +addPathRec("${srcDir}/ts/loader") +addPathRec("${projectSrcDir}") + +############################################################################### +# modular paths +############################################################################### +# lighting +if(TORQUE_ADVANCED_LIGHTING) + addPath("${srcDir}/lighting/advanced") + addPathRec("${srcDir}/lighting/shadowMap") + addPathRec("${srcDir}/lighting/advanced/hlsl") + #addPathRec("${srcDir}/lighting/advanced/glsl") +endif() +if(TORQUE_BASIC_LIGHTING) + addPathRec("${srcDir}/lighting/basic") + addPathRec("${srcDir}/lighting/shadowMap") +endif() + +# DirectX Sound +if(TORQUE_SFX_DirectX) + addPathRec("${srcDir}/sfx/dsound") + addPathRec("${srcDir}/sfx/xaudio") +endif() + +# OpenAL +if(TORQUE_SFX_OPENAL) + addPath("${srcDir}/sfx/openal") + #addPath("${srcDir}/sfx/openal/mac") + addPath("${srcDir}/sfx/openal/win32") +endif() + +# Theora +if(TORQUE_THEORA) + addPath("${srcDir}/core/ogg") + addPath("${srcDir}/gfx/video") + addPath("${srcDir}/gui/theora") +endif() + +# Include tools for non-tool builds (or define player if a tool build) +if(TORQUE_TOOLS) + addPath("${srcDir}/gui/worldEditor") + addPath("${srcDir}/environment/editors") + addPath("${srcDir}/forest/editor") + addPath("${srcDir}/gui/editor") + addPath("${srcDir}/gui/editor/inspector") +endif() + +if(TORQUE_HIFI) + addPath("${srcDir}/T3D/gameBase/hifi") +endif() + +if(TORQUE_EXTENDED_MOVE) + addPath("${srcDir}/T3D/gameBase/extended") +else() + addPath("${srcDir}/T3D/gameBase/std") +endif() + +if(TORQUE_NAVIGATION) + include( "modules/module_navigation.cmake" ) +endif() + +if(TORQUE_OCULUSVR) + include( "modules/module_oculusVR.cmake" ) +endif() + +if(TORQUE_HYDRA) + include( "modules/module_hydra.cmake" ) +endif() + +############################################################################### +# platform specific things +############################################################################### +if(WIN32) + addPath("${srcDir}/platformWin32") + addPath("${srcDir}/platformWin32/nativeDialogs") + addPath("${srcDir}/platformWin32/menus") + addPath("${srcDir}/platformWin32/threads") + addPath("${srcDir}/platformWin32/videoInfo") + addPath("${srcDir}/platformWin32/minidump") + addPath("${srcDir}/windowManager/win32") + #addPath("${srcDir}/gfx/D3D8") + addPath("${srcDir}/gfx/D3D") + addPath("${srcDir}/gfx/D3D9") + addPath("${srcDir}/gfx/D3D9/pc") + addPath("${srcDir}/shaderGen/HLSL") + addPath("${srcDir}/terrain/hlsl") + addPath("${srcDir}/forest/hlsl") + # add windows rc file for the icon + addFile("${projectSrcDir}/torque.rc") +endif() + +if(APPLE) + addPath("${srcDir}/platformMac") + addPath("${srcDir}/platformMac/menus") + addPath("${srcDir}/platformPOSIX") + addPath("${srcDir}/windowManager/mac") + addPath("${srcDir}/gfx/gl") + addPath("${srcDir}/gfx/gl/ggl") + addPath("${srcDir}/gfx/gl/ggl/mac") + addPath("${srcDir}/gfx/gl/ggl/generated") + addPath("${srcDir}/shaderGen/GLSL") + addPath("${srcDir}/terrain/glsl") + addPath("${srcDir}/forest/glsl") +endif() + +if(XBOX360) + addPath("${srcDir}/platformXbox") + addPath("${srcDir}/platformXbox/threads") + addPath("${srcDir}/windowManager/360") + addPath("${srcDir}/gfx/D3D9") + addPath("${srcDir}/gfx/D3D9/360") + addPath("${srcDir}/shaderGen/HLSL") + addPath("${srcDir}/shaderGen/360") + addPath("${srcDir}/ts/arch/360") + addPath("${srcDir}/terrain/hlsl") + addPath("${srcDir}/forest/hlsl") +endif() + +if(PS3) + addPath("${srcDir}/platformPS3") + addPath("${srcDir}/platformPS3/threads") + addPath("${srcDir}/windowManager/ps3") + addPath("${srcDir}/gfx/gl") + addPath("${srcDir}/gfx/gl/ggl") + addPath("${srcDir}/gfx/gl/ggl/ps3") + addPath("${srcDir}/gfx/gl/ggl/generated") + addPath("${srcDir}/shaderGen/GLSL") + addPath("${srcDir}/ts/arch/ps3") + addPath("${srcDir}/terrain/glsl") + addPath("${srcDir}/forest/glsl") +endif() + +if(UNIX) + # linux_dedicated + addPath("${srcDir}/windowManager/dedicated") + # linux + addPath("${srcDir}/platformX86UNIX") + addPath("${srcDir}/platformX86UNIX/threads") + addPath("${srcDir}/platformPOSIX") + addPath("${srcDir}/gfx/gl") + addPath("${srcDir}/gfx/gl/ggl") + addPath("${srcDir}/gfx/gl/ggl/x11") # This one is not yet implemented! + addPath("${srcDir}/gfx/gl/ggl/generated") + addPath("${srcDir}/shaderGen/GLSL") + addPath("${srcDir}/terrain/glsl") + addPath("${srcDir}/forest/glsl") +endif() + +############################################################################### +############################################################################### +addExecutable() +############################################################################### +############################################################################### + +# configure the relevant files only once +if(NOT EXISTS "${projectSrcDir}/torqueConfig.h") + message(STATUS "writing ${projectSrcDir}/torqueConfig.h") + CONFIGURE_FILE("${cmakeDir}/torqueConfig.h.in" "${projectSrcDir}/torqueConfig.h") +endif() +if(NOT EXISTS "${projectSrcDir}/torque.ico") + CONFIGURE_FILE("${cmakeDir}/torque.ico" "${projectSrcDir}/torque.ico" COPYONLY) +endif() +if(NOT EXISTS "${projectOutDir}/${PROJECT_NAME}.torsion") + CONFIGURE_FILE("${cmakeDir}/template.torsion.in" "${projectOutDir}/${PROJECT_NAME}.torsion") +endif() +if(EXISTS "${CMAKE_SOURCE_DIR}/Templates/${TORQUE_TEMPLATE}/game/main.cs.in" AND NOT EXISTS "${projectOutDir}/main.cs") + CONFIGURE_FILE("${CMAKE_SOURCE_DIR}/Templates/${TORQUE_TEMPLATE}/game/main.cs.in" "${projectOutDir}/main.cs") +endif() +if(WIN32) + if(NOT EXISTS "${projectSrcDir}/torque.rc") + CONFIGURE_FILE("${cmakeDir}/torque-win.rc.in" "${projectSrcDir}/torque.rc") + endif() + if(NOT EXISTS "${projectOutDir}/${PROJECT_NAME}-debug.bat") + CONFIGURE_FILE("${cmakeDir}/app-debug-win.bat.in" "${projectOutDir}/${PROJECT_NAME}-debug.bat") + endif() + if(NOT EXISTS "${projectOutDir}/cleanup.bat") + CONFIGURE_FILE("${cmakeDir}/cleanup-win.bat.in" "${projectOutDir}/cleanup.bat") + endif() +endif() + +############################################################################### +# Common Libraries +############################################################################### +addLib(lmng) +addLib(lpng) +addLib(lungif) +addLib(ljpeg) +addLib(zlib) +addLib(tinyxml) +addLib(opcode) +addLib(squish) +addLib(collada) +addLib(pcre) +addLib(convexDecomp) + +if(WIN32) + # copy pasted from T3D build system, some might not be needed + set(TORQUE_EXTERNAL_LIBS "COMCTL32.LIB;COMDLG32.LIB;USER32.LIB;ADVAPI32.LIB;GDI32.LIB;WINMM.LIB;WSOCK32.LIB;vfw32.lib;Imm32.lib;d3d9.lib;d3dx9.lib;DxErr.lib;ole32.lib;shell32.lib;oleaut32.lib;version.lib" CACHE STRING "external libs to link against") + mark_as_advanced(TORQUE_EXTERNAL_LIBS) + addLib("${TORQUE_EXTERNAL_LIBS}") +endif() + +############################################################################### +# Always enabled Definitions +############################################################################### +addDebugDef(TORQUE_DEBUG) +addDebugDef(TORQUE_ENABLE_ASSERTS) +addDebugDef(TORQUE_DEBUG_GFX_MODE) + +addDef(TORQUE_SHADERGEN) +addDef(INITGUID) +addDef(NTORQUE_SHARED) +addDef(UNICODE) +addDef(_UNICODE) # for VS +addDef(TORQUE_UNICODE) +#addDef(TORQUE_SHARED) # not used anymore as the game is the executable directly +addDef(LTC_NO_PROTOTYPES) # for libTomCrypt +addDef(BAN_OPCODE_AUTOLINK) +addDef(ICE_NO_DLL) +addDef(TORQUE_OPCODE) +addDef(TORQUE_COLLADA) +addDef(DOM_INCLUDE_TINYXML) +addDef(PCRE_STATIC) +addDef(_CRT_SECURE_NO_WARNINGS) +addDef(_CRT_SECURE_NO_DEPRECATE) + + +############################################################################### +# Modules +############################################################################### +if(TORQUE_SFX_DirectX) + addLib(x3daudio.lib) +endif() + +if(TORQUE_ADVANCED_LIGHTING) + addDef(TORQUE_ADVANCED_LIGHTING) +endif() +if(TORQUE_BASIC_LIGHTING) + addDef(TORQUE_BASIC_LIGHTING) +endif() + +if(TORQUE_SFX_OPENAL) + addInclude("${libDir}/openal/win32") +endif() + +if(TORQUE_SFX_VORBIS) + addInclude(${libDir}/libvorbis/include) + addDef(TORQUE_OGGVORBIS) + addLib(libvorbis) + addLib(libogg) +endif() + +if(TORQUE_THEORA) + addDef(TORQUE_OGGTHEORA) + addDef(TORQUE_OGGVORIBS) + addInclude(${libDir}/libtheora/include) + addLib(libtheora) +endif() + +if(TORQUE_HIFI) + addDef(TORQUE_HIFI_NET) +endif() +if(TORQUE_EXTENDED_MOVE) + addDef(TORQUE_EXTENDED_MOVE) +endif() + +############################################################################### +# Include Paths +############################################################################### +addInclude("${projectSrcDir}") +addInclude("${srcDir}/") +addInclude("${libDir}/lmpg") +addInclude("${libDir}/lpng") +addInclude("${libDir}/ljpeg") +addInclude("${libDir}/lungif") +addInclude("${libDir}/zlib") +addInclude("${libDir}/") # for tinyxml +addInclude("${libDir}/tinyxml") +addInclude("${libDir}/squish") +addInclude("${libDir}/convexDecomp") +addInclude("${libDir}/libogg/include") +addInclude("${libDir}/opcode") +addInclude("${libDir}/collada/include") +addInclude("${libDir}/collada/include/1.4") + +# external things +if(WIN32) + set_property(TARGET ${PROJECT_NAME} APPEND PROPERTY INCLUDE_DIRECTORIES $ENV{DXSDK_DIR}/Include) +endif() + +############################################################################### +# Installation +############################################################################### + +if(TORQUE_TEMPLATE) + message("Prepare Template(${TORQUE_TEMPLATE}) install...") + INSTALL(DIRECTORY "${CMAKE_SOURCE_DIR}/Templates/${TORQUE_TEMPLATE}/game" DESTINATION "${projectDir}") + if(WIN32) + INSTALL(FILES "${CMAKE_SOURCE_DIR}/Templates/${TORQUE_TEMPLATE}/cleanShaders.bat" DESTINATION "${projectDir}") + INSTALL(FILES "${CMAKE_SOURCE_DIR}/Templates/${TORQUE_TEMPLATE}/DeleteCachedDTSs.bat" DESTINATION "${projectDir}") + INSTALL(FILES "${CMAKE_SOURCE_DIR}/Templates/${TORQUE_TEMPLATE}/DeleteDSOs.bat" DESTINATION "${projectDir}") + INSTALL(FILES "${CMAKE_SOURCE_DIR}/Templates/${TORQUE_TEMPLATE}/DeletePrefs.bat" DESTINATION "${projectDir}") + endif() +endif() diff --git a/Tools/CMake/torqueConfig.h.in b/Tools/CMake/torqueConfig.h.in new file mode 100644 index 000000000..9acb419df --- /dev/null +++ b/Tools/CMake/torqueConfig.h.in @@ -0,0 +1,208 @@ +//----------------------------------------------------------------------------- +// Copyright (c) 2012 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. +//----------------------------------------------------------------------------- + +#pragma once + +//----------------------------------------------------------------------------- +//Hi, and welcome to the Torque Config file. +// +//This file is a central reference for the various configuration flags that +//you'll be using when controlling what sort of a Torque build you have. In +//general, the information here is global for your entire codebase, applying +//not only to your game proper, but also to all of your tools. + +/// What's the name of your application? Used in a variety of places. +#define TORQUE_APP_NAME "@TORQUE_APP_NAME@" + +/// What version of the application specific source code is this? +/// +/// Version number is major * 1000 + minor * 100 + revision * 10. +#define TORQUE_APP_VERSION @TORQUE_APP_VERSION@ + +/// Human readable application version string. +#define TORQUE_APP_VERSION_STRING "@TORQUE_APP_VERSION_STRING@" + +/// Define me if you want to enable multithreading support. +#cmakedefine TORQUE_MULTITHREAD + +/// Define me if you want to disable Torque memory manager. +#cmakedefine TORQUE_DISABLE_MEMORY_MANAGER + +/// Define me if you want to disable the virtual mount system. +#cmakedefine TORQUE_DISABLE_VIRTUAL_MOUNT_SYSTEM + +/// Define me if you want to disable looking for the root of a given path +/// within a zip file. This means that the zip file name itself must be +/// the root of the path. Requires the virtual mount system to be active. +#cmakedefine TORQUE_DISABLE_FIND_ROOT_WITHIN_ZIP + +//Uncomment this define if you want to use the alternative zip support where you can +//define your directories and files inside the zip just like you would on disk +//instead of the default zip support that treats the zip as an extra directory. +#cmakedefine TORQUE_ZIP_DISK_LAYOUT + +/// Define me if you don't want Torque to compile dso's +#cmakedefine TORQUE_NO_DSO_GENERATION + +// Define me if this build is a tools build +#cmakedefine TORQUE_PLAYER +#cmakedefine TORQUE_TOOLS + +/// Define me if you want to enable the profiler. +/// See also the TORQUE_SHIPPING block below +#cmakedefine TORQUE_ENABLE_PROFILER + +/// Define me to enable debug mode; enables a great number of additional +/// sanity checks, as well as making AssertFatal and AssertWarn do something. +/// This is usually defined by the build target. + +// TORQUE_DEBUG is now set dynamically and not here anymore +// #cmakedefine TORQUE_DEBUG + +#cmakedefine DEBUG_SPEW +#cmakedefine TORQUE_DEBUG_GFX_MODE + +/// Define me if this is a shipping build; if defined I will instruct Torque +/// to batten down some hatches and generally be more "final game" oriented. +/// Notably this disables a liberal resource manager file searching, and +/// console help strings. +#cmakedefine TORQUE_SHIPPING + +/// Define me to enable a variety of network debugging aids. +/// +/// - NetConnection packet logging. +/// - DebugChecksum guards to detect mismatched pack/unpacks. +/// - Detection of invalid destination ghosts. +/// +#cmakedefine TORQUE_DEBUG_NET + +/// Define me to enable detailed console logging of net moves. +#cmakedefine TORQUE_DEBUG_NET_MOVES + +/// Enable this define to change the default Net::MaxPacketDataSize +/// Do this at your own risk since it has the potential to cause packets +/// to be split up by old routers and Torque does not have a mechanism to +/// stitch split packets back together. Using this define can be very useful +/// in controlled network hardware environments (like a LAN) or for singleplayer +/// games (like BArricade and its large paths) +//#define MAXPACKETSIZE 1500 + +/// Modify me to enable metric gathering code in the renderers. +/// +/// 0 does nothing; higher numbers enable higher levels of metric gathering. +//#define TORQUE_GATHER_METRICS 0 + +/// Define me if you want to enable debug guards in the memory manager. +/// +/// Debug guards are known values placed before and after every block of +/// allocated memory. They are checked periodically by Memory::validate(), +/// and if they are modified (indicating an access to memory the app doesn't +/// "own"), an error is flagged (ie, you'll see a crash in the memory +/// manager's validate code). Using this and a debugger, you can track down +/// memory corruption issues quickly. +//#define TORQUE_DEBUG_GUARD + +/// Define me if you want to enable instanced-static behavior +//#define TORQUE_ENABLE_THREAD_STATICS + +/// Define me if you want to gather static-usage metrics +//#define TORQUE_ENABLE_THREAD_STATIC_METRICS + +/// Define me if you want to enable debug guards on the FrameAllocator. +/// +/// This is similar to the above memory manager guards, but applies only to the +/// fast FrameAllocator temporary pool memory allocations. The guards are only +/// checked when the FrameAllocator frees memory (when it's water mark changes). +/// This is most useful for detecting buffer overruns when using FrameTemp<> . +/// A buffer overrun in the FrameAllocator is unlikely to cause a crash, but may +/// still result in unexpected behavior, if other FrameTemp's are stomped. +//#define FRAMEALLOCATOR_DEBUG_GUARD + +/// This #define is used by the FrameAllocator to set the size of the frame. +/// +/// It was previously set to 3MB but I've increased it to 16MB due to the +/// FrameAllocator being used as temporary storage for bitmaps in the D3D9 +/// texture manager. +#define TORQUE_FRAME_SIZE 16 << 20 + +// Finally, we define some dependent #defines. This enables some subsidiary +// functionality to get automatically turned on in certain configurations. + +#ifdef TORQUE_DEBUG + + #define TORQUE_GATHER_METRICS 0 + #define TORQUE_ENABLE_PROFILE_PATH + #ifndef TORQUE_DEBUG_GUARD + #define TORQUE_DEBUG_GUARD + #endif + #ifndef TORQUE_NET_STATS + #define TORQUE_NET_STATS + #endif + + // Enables the C++ assert macros AssertFatal, AssertWarn, etc. + #ifndef TORQUE_ENABLE_ASSERTS + #define TORQUE_ENABLE_ASSERTS + #endif + +#endif + +#ifdef TORQUE_RELEASE + // If it's not DEBUG, it's a RELEASE build, put appropriate things here. +#endif + +#ifdef TORQUE_SHIPPING + + // TORQUE_SHIPPING flags here. + +#else + + // Enable the profiler by default, if we're not doing a shipping build. + #define TORQUE_ENABLE_PROFILER + + // Enable the TorqueScript assert() instruction if not shipping. + #define TORQUE_ENABLE_SCRIPTASSERTS + + // We also enable GFX debug events for use in Pix and other graphics + // debugging tools. + #define TORQUE_ENABLE_GFXDEBUGEVENTS + +#endif + +#ifdef TORQUE_TOOLS +# define TORQUE_INSTANCE_EXCLUSION "TorqueToolsTest" +#else +# define TORQUE_INSTANCE_EXCLUSION "TorqueTest" +#endif + +// Someday, it might make sense to do some pragma magic here so we error +// on inconsistent flags. + +// The Xbox360 has it's own profiling tools, the Torque Profiler should not be used +#ifdef TORQUE_OS_XENON +# ifdef TORQUE_ENABLE_PROFILER +# undef TORQUE_ENABLE_PROFILER +# endif +# +# ifdef TORQUE_ENABLE_PROFILE_PATH +# undef TORQUE_ENABLE_PROFILE_PATH +#endif +#endif diff --git a/Tools/CMake/zlib.cmake b/Tools/CMake/zlib.cmake new file mode 100644 index 000000000..6df47de04 --- /dev/null +++ b/Tools/CMake/zlib.cmake @@ -0,0 +1,3 @@ +project(zlib) + +addStaticLib("${libDir}/${PROJECT_NAME}") diff --git a/Tools/dae2dts/source/main.cpp b/Tools/dae2dts/source/main.cpp index 64a78c82e..f92b9fa24 100644 --- a/Tools/dae2dts/source/main.cpp +++ b/Tools/dae2dts/source/main.cpp @@ -31,7 +31,7 @@ #include "ts/tsShape.h" #include "ts/tsShapeConstruct.h" -#ifdef TORQUE_OS_WIN32 +#ifdef TORQUE_OS_WIN #include "platformWin32/platformWin32.h" #include "platformWin32/winConsole.h" #endif diff --git a/Tools/projectGenerator/btargets/targets.inc b/Tools/projectGenerator/btargets/targets.inc index 5637164aa..0f010c936 100644 --- a/Tools/projectGenerator/btargets/targets.inc +++ b/Tools/projectGenerator/btargets/targets.inc @@ -184,7 +184,7 @@ $c->setDontCompilePatterns( "*\.h*", "*win32*", "*\.win\.*", "/D3D.*/", "#/gl/#" ///////////////////////////// Build ///////////////////////////// -// 'buildManifest_'.$name.'_'.Generator::$platform.'.txt', +// 'buildManifest_'.$name.'_'.T3D_Generator::$platform.'.txt', $c = BuildTarget::add( 'build', // Name 'buildFiles', // Solution output directory diff --git a/Tools/projectGenerator/classes/Generator.php b/Tools/projectGenerator/classes/Generator.php index 257b3933b..564339594 100644 --- a/Tools/projectGenerator/classes/Generator.php +++ b/Tools/projectGenerator/classes/Generator.php @@ -37,7 +37,7 @@ require_once( "NPWebPlugin.php"); require_once( "SafariWebPlugin.php"); -class Generator +class T3D_Generator { public static $app_name; public static $paths = array(); @@ -275,14 +275,14 @@ class Generator array_push( self::$libGuard, $lib ); // if currently in a project, delay the include - if (Generator::inProjectConfig()) + if (T3D_Generator::inProjectConfig()) { array_push( self::$project_cur->lib_includes, $lib ); return; } // otherwise include it immediately - require( Generator::getGeneratorLibsPath() . $lib . '.conf' ); + require( T3D_Generator::getGeneratorLibsPath() . $lib . '.conf' ); } static function addProjectDependency( $pd ) @@ -335,7 +335,7 @@ class Generator if( !self::$module_cur ) self::$module_cur = $name; else - echo( "Generator::beginModule() - already in module!" ); + echo( "T3D_Generator::beginModule() - already in module!" ); } static function endModule() @@ -343,7 +343,7 @@ class Generator if( self::$module_cur ) self::$module_cur = null; else - trigger_error( "Generator::endModule() - no active module!", E_USER_ERROR ); + trigger_error( "T3D_Generator::endModule() - no active module!", E_USER_ERROR ); } static function inProjectConfig() @@ -367,7 +367,7 @@ class Generator self::$config_projects[ $name ] = self::$project_cur; } else - trigger_error( "Generator::beginProjectConfig() - a project is already open!", E_USER_ERROR ); + trigger_error( "T3D_Generator::beginProjectConfig() - a project is already open!", E_USER_ERROR ); } static function endProjectConfig( $type ) @@ -424,14 +424,14 @@ class Generator // Now include any libraries included in the modules foreach( $p->lib_includes as $libName ) - require( Generator::getGeneratorLibsPath() . $libName . '.conf' ); + require( T3D_Generator::getGeneratorLibsPath() . $libName . '.conf' ); } else - trigger_error( "Generator::endProjectConfig() - closing type mismatch!", E_USER_ERROR ); + trigger_error( "T3D_Generator::endProjectConfig() - closing type mismatch!", E_USER_ERROR ); } else - trigger_error( "Generator::endProjectConfig() - no currently open project!", E_USER_ERROR ); + trigger_error( "T3D_Generator::endProjectConfig() - no currently open project!", E_USER_ERROR ); } static function beginActiveXConfig( $lib_name, $guid = '', $game_dir = 'game', $output_name = '' ) @@ -571,7 +571,7 @@ class Generator self::$solutions[ $name ] = self::$solution_cur; } else - trigger_error( "Generator::beginSolution() - tried to start $name but already in the ".self::$solution_cur->name." solution!", E_USER_ERROR ); + trigger_error( "T3D_Generator::beginSolution() - tried to start $name but already in the ".self::$solution_cur->name." solution!", E_USER_ERROR ); } static function addSolutionProjectRef( $pname ) @@ -579,7 +579,7 @@ class Generator if( isset( self::$solution_cur ) ) self::$solution_cur->addProjectRef( $pname ); else - trigger_error( "Generator::addSolutionProjectRef(): no such project - " . $pname . "\n", E_USER_ERROR ); + trigger_error( "T3D_Generator::addSolutionProjectRef(): no such project - " . $pname . "\n", E_USER_ERROR ); } static function addSolutionProjectRefExt( $pname, $ppath, $pguid ) @@ -587,7 +587,7 @@ class Generator if( isset( self::$solution_cur ) ) self::$solution_cur->addSolutionProjectRefExt( $pname, $ppath, $pguid ); else - trigger_error( "Generator::addSolutionProjectRefExt(): no such project - " . $pname . "\n", E_USER_ERROR ); + trigger_error( "T3D_Generator::addSolutionProjectRefExt(): no such project - " . $pname . "\n", E_USER_ERROR ); } static function endSolution() @@ -599,7 +599,7 @@ class Generator self::$solution_cur = null; } else - trigger_error( "Generator::endSolution(): no active solution!\n", E_USER_ERROR ); + trigger_error( "T3D_Generator::endSolution(): no active solution!\n", E_USER_ERROR ); } static function generateSolutions( $tpl ) diff --git a/Tools/projectGenerator/classes/Project.php b/Tools/projectGenerator/classes/Project.php index 068174c70..50a9343ac 100644 --- a/Tools/projectGenerator/classes/Project.php +++ b/Tools/projectGenerator/classes/Project.php @@ -165,7 +165,7 @@ class Project foreach( $this->dependencies as $pname ) { - $p = Generator::lookupProjectByName( $pname ); + $p = T3D_Generator::lookupProjectByName( $pname ); if( $p ) array_push( $pguids, $p->guid ); @@ -200,10 +200,10 @@ class Project { // This could be consolidated into a single OR statement but it is easier to // read as two separate if's - if ( !Generator::$absPath ) + if ( !T3D_Generator::$absPath ) $newEntry->path = $output->project_rel_path . $newEntry->path; - if ( Generator::$absPath && !stristr($newEntry->path, Generator::$absPath) ) + if ( T3D_Generator::$absPath && !stristr($newEntry->path, T3D_Generator::$absPath) ) $newEntry->path = $output->project_rel_path . $newEntry->path; } @@ -230,10 +230,10 @@ class Project $curPath = FileUtil::collapsePath( $output->base_dir . $dir ); $pathWalk = &$projectFiles[ $projName ]; - if ( Generator::$absPath ) + if ( T3D_Generator::$absPath ) { if ( stristr($curPath, getEngineSrcDir()) || stristr($curPath, getLibSrcDir()) ) - $curPath = Generator::$absPath . "/". str_replace("../", "", $curPath); + $curPath = T3D_Generator::$absPath . "/". str_replace("../", "", $curPath); } // Check if its a file or a directory. @@ -344,7 +344,7 @@ class Project $tpl->assign_by_ref( 'projModuleDefinitionFile', $this->moduleDefinitionFile ); $tpl->assign_by_ref( 'projSubSystem', $this->projSubSystem ); - if (Generator::$useDLLRuntime) + if (T3D_Generator::$useDLLRuntime) { // /MD and /MDd $tpl->assign( 'projRuntimeRelease', 2 ); @@ -381,7 +381,7 @@ class Project foreach ($this->dependencies as $pname) { - $p = Generator::lookupProjectByName( $pname ); + $p = T3D_Generator::lookupProjectByName( $pname ); $projectDepends[$pname] = $p; if ( $p ) @@ -394,18 +394,18 @@ class Project // Assign some handy paths for the template to reference $tpl->assign( 'projectOffset', $output->project_rel_path ); - if ( Generator::$absPath ) - $tpl->assign( 'srcDir', Generator::$absPath . "/". str_replace("../", "", getAppEngineSrcDir()) ); + if ( T3D_Generator::$absPath ) + $tpl->assign( 'srcDir', T3D_Generator::$absPath . "/". str_replace("../", "", getAppEngineSrcDir()) ); else $tpl->assign( 'srcDir', $output->project_rel_path . getAppEngineSrcDir() ); - if ( Generator::$absPath ) - $tpl->assign( 'libDir', Generator::$absPath . "/". str_replace("../", "", getAppLibSrcDir()) ); + if ( T3D_Generator::$absPath ) + $tpl->assign( 'libDir', T3D_Generator::$absPath . "/". str_replace("../", "", getAppLibSrcDir()) ); else $tpl->assign( 'libDir', $output->project_rel_path . getAppLibSrcDir() ); - if ( Generator::$absPath ) - $tpl->assign( 'binDir', Generator::$absPath . "/". str_replace("../", "", getAppEngineBinDir()) ); + if ( T3D_Generator::$absPath ) + $tpl->assign( 'binDir', T3D_Generator::$absPath . "/". str_replace("../", "", getAppEngineBinDir()) ); else $tpl->assign( 'binDir', $output->project_rel_path . getAppEngineBinDir() ); @@ -427,18 +427,18 @@ class Project $libDirs = $output->project_rel_path . $libDirs; } - if ( Generator::$absPath ) + if ( T3D_Generator::$absPath ) { foreach ($this->includes as &$include) { if ( stristr($include, getEngineSrcDir()) || stristr($include, getLibSrcDir()) ) - $include = Generator::$absPath . "/". str_replace("../", "", $include); + $include = T3D_Generator::$absPath . "/". str_replace("../", "", $include); } foreach ($this->lib_dirs as &$libDirs) { if ( stristr($libDirs, getEngineSrcDir()) || stristr($libDirs, getLibSrcDir()) ) - $libDirs = Generator::$absPath . "/". str_replace("../", "", $libDirs); + $libDirs = T3D_Generator::$absPath . "/". str_replace("../", "", $libDirs); } } } diff --git a/Tools/projectGenerator/classes/Solution.php b/Tools/projectGenerator/classes/Solution.php index ad352b9af..dbc52f1c2 100644 --- a/Tools/projectGenerator/classes/Solution.php +++ b/Tools/projectGenerator/classes/Solution.php @@ -85,7 +85,7 @@ class Solution // Look up each project ref and add its info to the list foreach( $refs as $pname ) { - $project = Generator::lookupProjectByName( $pname ); + $project = T3D_Generator::lookupProjectByName( $pname ); if( isset( $project ) ) { diff --git a/Tools/projectGenerator/classes/Torque3D.php b/Tools/projectGenerator/classes/Torque3D.php index 64c088a55..b682092c6 100644 --- a/Tools/projectGenerator/classes/Torque3D.php +++ b/Tools/projectGenerator/classes/Torque3D.php @@ -45,7 +45,7 @@ class Torque3D includeLib( 'convexDecomp' ); // Use FMOD on consoles - if ( Generator::$platform != "360" && Generator::$platform != "ps3" ) + if ( T3D_Generator::$platform != "360" && T3D_Generator::$platform != "ps3" ) { includeLib( 'libvorbis' ); includeLib( 'libogg' ); @@ -63,12 +63,12 @@ class Torque3D self::includeDefaultLibs(); $ext = "DLL"; - if ( Generator::$platform == "mac" ) + if ( T3D_Generator::$platform == "mac" ) $ext = "Bundle"; //some platforms will not want a shared config - if ( Generator::$platform == "360" || Generator::$platform == "ps3" ) + if ( T3D_Generator::$platform == "360" || T3D_Generator::$platform == "ps3" ) self::$sharedConfig = false; //begin either a shared lib config, or a static app config @@ -105,7 +105,7 @@ class Torque3D addLibIncludePath( "squish" ); addLibIncludePath( 'convexDecomp' ); - if ( Generator::$platform != "360" && Generator::$platform != "ps3" ) + if ( T3D_Generator::$platform != "360" && T3D_Generator::$platform != "ps3" ) { addLibIncludePath( "libvorbis/include" ); addLibIncludePath( "libogg/include" ); @@ -121,13 +121,13 @@ class Torque3D includeModule( 'basicLighting' ); includeModule( 'collada' ); - if ( Generator::$platform != "360" && Generator::$platform != "ps3" ) + if ( T3D_Generator::$platform != "360" && T3D_Generator::$platform != "ps3" ) { includeModule( 'vorbis' ); includeModule( 'theora' ); } - if(Generator::$platform == "mac" || Generator::$platform == "win32") + if(T3D_Generator::$platform == "mac" || T3D_Generator::$platform == "win32") includeModule( 'openal' ); @@ -145,20 +145,20 @@ class Torque3D addProjectDependency( 'pcre' ); addProjectDependency( 'convexDecomp' ); - if ( Generator::$platform != "360" && Generator::$platform != "ps3" ) + if ( T3D_Generator::$platform != "360" && T3D_Generator::$platform != "ps3" ) { addProjectDependency( 'libvorbis' ); addProjectDependency( 'libogg' ); addProjectDependency( 'libtheora' ); } - if ( Generator::$platform == "mac" ) + if ( T3D_Generator::$platform == "mac" ) { addProjectDefine( '__MACOSX__' ); addProjectDefine( 'LTM_DESC' ); } - if (Generator::$platform == "win32") + if (T3D_Generator::$platform == "win32") { setProjectModuleDefinitionFile('../../' . getLibSrcDir() . 'Torque3D/msvc/torque3d.def'); @@ -209,13 +209,13 @@ class Torque3D addEngineSrcDir( 'main' ); - if (Generator::$platform == "win32") + if (T3D_Generator::$platform == "win32") { addProjectDefine( 'WIN32' ); addProjectDependency( getGameProjectName() . ' DLL' ); } - if (Generator::$platform == "mac") + if (T3D_Generator::$platform == "mac") { addProjectDefine( '__MACOSX__' ); addProjectDependency( getGameProjectName() . ' Bundle' ); @@ -226,7 +226,7 @@ class Torque3D } // Add solution references for Visual Studio projects - if (Generator::$platform == "win32" || Generator::$platform == "360" || Generator::$platform == "ps3") + if (T3D_Generator::$platform == "win32" || T3D_Generator::$platform == "360" || T3D_Generator::$platform == "ps3") { if ( !self::$sharedConfig ) beginSolutionConfig( getGameProjectName(), '{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}' ); @@ -247,7 +247,7 @@ class Torque3D addSolutionProjectRef( 'zlib' ); addSolutionProjectRef( 'convexDecomp' ); - if (Generator::$platform == "win32") + if (T3D_Generator::$platform == "win32") { addSolutionProjectRef( 'libogg' ); addSolutionProjectRef( 'libvorbis' ); diff --git a/Tools/projectGenerator/libs/Torque3D.conf b/Tools/projectGenerator/libs/Torque3D.conf index 7ddc28cef..83833c2d5 100644 --- a/Tools/projectGenerator/libs/Torque3D.conf +++ b/Tools/projectGenerator/libs/Torque3D.conf @@ -35,7 +35,7 @@ includeLib( 'pcre' ); includeLib( 'convexDecomp' ); // Use FMOD on consoles -if ( Generator::$platform != "360" && Generator::$platform != "ps3" ) +if ( T3D_Generator::$platform != "360" && T3D_Generator::$platform != "ps3" ) { includeLib( 'libvorbis' ); includeLib( 'libogg' ); @@ -43,7 +43,7 @@ if ( Generator::$platform != "360" && Generator::$platform != "ps3" ) } $ext = "DLL"; -if ( Generator::$platform == "mac" ) +if ( T3D_Generator::$platform == "mac" ) $ext = "Bundle"; // We need to pick the right physics engine to include. @@ -52,7 +52,7 @@ global $PHYSX_SDK_PATH; //some platforms will not want a shared config $useSharedConfig = true; -if ( Generator::$platform == "360" || Generator::$platform == "ps3" ) +if ( T3D_Generator::$platform == "360" || T3D_Generator::$platform == "ps3" ) $useSharedConfig = false; //begin either a shared lib config, or a static app config @@ -89,7 +89,7 @@ else addLibIncludePath( "squish" ); addLibIncludePath( "convexDecomp" ); - if ( Generator::$platform != "360" && Generator::$platform != "ps3" ) + if ( T3D_Generator::$platform != "360" && T3D_Generator::$platform != "ps3" ) { addLibIncludePath( "libvorbis/include" ); addLibIncludePath( "libogg/include" ); @@ -107,13 +107,13 @@ else includeModule( 'basicLighting' ); includeModule( 'collada' ); - if ( Generator::$platform != "360" && Generator::$platform != "ps3" ) + if ( T3D_Generator::$platform != "360" && T3D_Generator::$platform != "ps3" ) { includeModule( 'vorbis' ); includeModule( 'theora' ); } - if(Generator::$platform == "mac" || Generator::$platform == "win32") + if(T3D_Generator::$platform == "mac" || T3D_Generator::$platform == "win32") includeModule( 'openal' ); // Demo functionality @@ -142,7 +142,7 @@ else addProjectDependency( 'pcre' ); addProjectDependency( 'convexDecomp' ); - if ( Generator::$platform != "360" && Generator::$platform != "ps3" ) + if ( T3D_Generator::$platform != "360" && T3D_Generator::$platform != "ps3" ) { addProjectDependency( 'libvorbis' ); addProjectDependency( 'libogg' ); @@ -162,13 +162,13 @@ else addProjectDependency( 'nxuStream' ); } - if ( Generator::$platform == "mac" ) + if ( T3D_Generator::$platform == "mac" ) { addProjectDefine( '__MACOSX__' ); addProjectDefine( 'LTM_DESC' ); } - if (Generator::$platform == "win32") + if (T3D_Generator::$platform == "win32") { setProjectModuleDefinitionFile('../../' . getLibSrcDir() . 'Torque3D/msvc/torque3d.def'); @@ -216,13 +216,13 @@ beginSharedAppConfig( getGameProjectName(), '{CDECDFF9-E125-523F-87BC-2D89DB971C addEngineSrcDir( 'main' ); - if (Generator::$platform == "win32") + if (T3D_Generator::$platform == "win32") { addProjectDefine( 'WIN32' ); addProjectDependency( getGameProjectName() . ' DLL' ); } - if (Generator::$platform == "mac") + if (T3D_Generator::$platform == "mac") { addProjectDefine( '__MACOSX__' ); addProjectDependency( getGameProjectName() . ' Bundle' ); @@ -233,7 +233,7 @@ endSharedAppConfig(); } // Add solution references for Visual Studio projects -if (Generator::$platform == "win32" || Generator::$platform == "360" || Generator::$platform == "ps3") +if (T3D_Generator::$platform == "win32" || T3D_Generator::$platform == "360" || T3D_Generator::$platform == "ps3") { if ( !$useSharedConfig ) beginSolutionConfig( getGameProjectName(), '{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}' ); @@ -253,7 +253,7 @@ if ( !$useSharedConfig ) addSolutionProjectRef( 'zlib' ); addSolutionProjectRef( 'convexDecomp' ); - if (Generator::$platform == "win32") + if (T3D_Generator::$platform == "win32") { addSolutionProjectRef( 'libogg' ); addSolutionProjectRef( 'libvorbis' ); diff --git a/Tools/projectGenerator/libs/WebDeploy.conf b/Tools/projectGenerator/libs/WebDeploy.conf index b92f21f41..11c3619e0 100644 --- a/Tools/projectGenerator/libs/WebDeploy.conf +++ b/Tools/projectGenerator/libs/WebDeploy.conf @@ -21,7 +21,7 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- -if (Generator::$platform == "win32") +if (T3D_Generator::$platform == "win32") { // Include the web deployment settings $webDeployConf = realpath($argv[1])."/buildFiles/config/webDeploy.conf"; @@ -55,7 +55,7 @@ if (Generator::$platform == "win32") } -if (Generator::$platform == "mac") +if (T3D_Generator::$platform == "mac") { // Include the web deployment settings $webDeployConf = realpath($argv[1])."/buildFiles/config/webDeploy.mac.conf"; diff --git a/Tools/projectGenerator/libs/convexDecomp.conf b/Tools/projectGenerator/libs/convexDecomp.conf index 4cc356883..b38352ce1 100644 --- a/Tools/projectGenerator/libs/convexDecomp.conf +++ b/Tools/projectGenerator/libs/convexDecomp.conf @@ -29,13 +29,13 @@ beginLibConfig( 'convexDecomp', '{4EF87A4E-16ED-4E64-BF04-841B2675AEE0}' ); // Additional includes addLibIncludePath( 'convexDecomp' ); - if ( Generator::$platform == "360" ) + if ( T3D_Generator::$platform == "360" ) addProjectDefine( '_XBOX' ); - else if ( Generator::$platform == "ps3" ) + else if ( T3D_Generator::$platform == "ps3" ) addProjectDefine( '__CELLOS_LV2__' ); - else if ( Generator::$platform == "mac" ) + else if ( T3D_Generator::$platform == "mac" ) addProjectDefine( '__APPLE__' ); - else if ( Generator::$platform == "win32" ) + else if ( T3D_Generator::$platform == "win32" ) addProjectDefine( 'WIN32' ); endLibConfig(); diff --git a/Tools/projectGenerator/libs/libbullet.conf b/Tools/projectGenerator/libs/libbullet.conf index faaceb832..a4a7d9e0b 100644 --- a/Tools/projectGenerator/libs/libbullet.conf +++ b/Tools/projectGenerator/libs/libbullet.conf @@ -39,8 +39,8 @@ beginLibConfig( 'libbullet', '{4368B65C-F5EF-4D28-B533-B02A04EBE921}' ); addLibSrcDir( 'bullet/src/LinearMath' ); // TODO: Can we do multicore on OSX? - if ( Generator::$platform == "win32" || - Generator::$platform == "360" ) + if ( T3D_Generator::$platform == "win32" || + T3D_Generator::$platform == "360" ) { addProjectDefine( 'WIN32' ); diff --git a/Tools/projectGenerator/libs/librecast.conf b/Tools/projectGenerator/libs/librecast.conf index bb0aa66f7..3033fc07e 100644 --- a/Tools/projectGenerator/libs/librecast.conf +++ b/Tools/projectGenerator/libs/librecast.conf @@ -24,11 +24,11 @@ beginLibConfig( 'librecast', '{F2C0209B-1B90-4F73-816A-A0920FF8B107}' ); // Source - addSrcDir( Generator::getLibSrcDir() . 'recast/DebugUtils/Source', true ); - addSrcDir( Generator::getLibSrcDir() . 'recast/Recast/Source', true ); - addSrcDir( Generator::getLibSrcDir() . 'recast/Detour/Source', true ); - addSrcDir( Generator::getLibSrcDir() . 'recast/DetourCrowd/Source', true ); - addSrcDir( Generator::getLibSrcDir() . 'recast/DetourTileCache/Source', true ); + addSrcDir( T3D_Generator::getLibSrcDir() . 'recast/DebugUtils/Source', true ); + addSrcDir( T3D_Generator::getLibSrcDir() . 'recast/Recast/Source', true ); + addSrcDir( T3D_Generator::getLibSrcDir() . 'recast/Detour/Source', true ); + addSrcDir( T3D_Generator::getLibSrcDir() . 'recast/DetourCrowd/Source', true ); + addSrcDir( T3D_Generator::getLibSrcDir() . 'recast/DetourTileCache/Source', true ); // Additional includes addLibIncludePath( 'recast/DebugUtils/Include' ); diff --git a/Tools/projectGenerator/modules/T3D.inc b/Tools/projectGenerator/modules/T3D.inc index f72a12908..df256468a 100644 --- a/Tools/projectGenerator/modules/T3D.inc +++ b/Tools/projectGenerator/modules/T3D.inc @@ -74,7 +74,7 @@ else addEngineSrcDir('T3D/gameBase/std'); // Plstform specific stuff. -switch( Generator::$platform ) +switch( T3D_Generator::$platform ) { case "360": addEngineSrcDir('ts/arch/360'); diff --git a/Tools/projectGenerator/modules/advancedLighting.inc b/Tools/projectGenerator/modules/advancedLighting.inc index 9e013dc2d..ec2ff3890 100644 --- a/Tools/projectGenerator/modules/advancedLighting.inc +++ b/Tools/projectGenerator/modules/advancedLighting.inc @@ -28,7 +28,7 @@ beginModule( 'advancedLighting' ); addEngineSrcDir( 'lighting/advanced' ); addEngineSrcDir( 'lighting/shadowMap' ); - switch( Generator::$platform ) + switch( T3D_Generator::$platform ) { case "win32": addEngineSrcDir( 'lighting/advanced/hlsl' ); diff --git a/Tools/projectGenerator/modules/core.inc b/Tools/projectGenerator/modules/core.inc index a6f3cae5a..10e870025 100644 --- a/Tools/projectGenerator/modules/core.inc +++ b/Tools/projectGenerator/modules/core.inc @@ -31,7 +31,7 @@ addEngineSrcDir('component'); addEngineSrcDir('component/interfaces'); // Core -if (Generator::isApp()) +if (T3D_Generator::isApp()) addSrcDir( '../source' ); addEngineSrcDir('console'); @@ -59,7 +59,7 @@ addEngineSrcDir('math/test'); addEngineSrcDir('platform'); addEngineSrcDir('cinterface'); -switch( Generator::$platform ) +switch( T3D_Generator::$platform ) { case "win32": case "mac": @@ -80,7 +80,7 @@ addEngineSrcDir('app/net'); // Moved this here temporarily because PopupMenu uses on it and is currently in core addEngineSrcDir('util/messaging'); -switch( Generator::$platform ) +switch( T3D_Generator::$platform ) { case "win32": addEngineSrcDir('platformWin32'); @@ -132,7 +132,7 @@ addEngineSrcDir( 'gfx/video' ); addEngineSrcDir( 'gfx' ); addEngineSrcDir( 'shaderGen' ); -switch( Generator::$platform ) +switch( T3D_Generator::$platform ) { case "win32": //addEngineSrcDir( 'gfx/D3D8' ); @@ -199,7 +199,7 @@ addIncludePath( '../../source' ); // product source (relative to solution ou addIncludePath( getAppEngineSrcDir() ); // main engine source dir relative to app project file addIncludePath( getAppLibSrcDir() ); // main lib source dir relative to app project file -if ( Generator::$platform == "win32" ) +if ( T3D_Generator::$platform == "win32" ) { addIncludePath( getAppLibSrcDir() . 'directx8' ); addIncludePath( getAppLibSrcDir() . 'openal/win32' ); diff --git a/Tools/projectGenerator/modules/dsound.inc b/Tools/projectGenerator/modules/dsound.inc index 178d910ff..5fc82c28d 100644 --- a/Tools/projectGenerator/modules/dsound.inc +++ b/Tools/projectGenerator/modules/dsound.inc @@ -23,13 +23,13 @@ beginModule( 'dsound' ); - if ( Generator::$platform == "win32" ) + if ( T3D_Generator::$platform == "win32" ) { addEngineSrcDir('sfx/dsound'); addEngineSrcDir('sfx/xaudio'); addProjectLibInput('x3daudio.lib'); } - else if ( Generator::$platform == "360" ) + else if ( T3D_Generator::$platform == "360" ) addEngineSrcDir('sfx/xaudio'); endModule(); diff --git a/Tools/projectGenerator/modules/fmod.inc b/Tools/projectGenerator/modules/fmod.inc index 377ec798f..2bb15d48e 100644 --- a/Tools/projectGenerator/modules/fmod.inc +++ b/Tools/projectGenerator/modules/fmod.inc @@ -25,7 +25,7 @@ beginModule( 'fmod' ); $allgood = true; // Additional includes - switch( Generator::$platform ) + switch( T3D_Generator::$platform ) { case "win32": case "mac": diff --git a/Tools/projectGenerator/modules/jpeg.inc b/Tools/projectGenerator/modules/jpeg.inc index 1fe72955b..16d3fd688 100644 --- a/Tools/projectGenerator/modules/jpeg.inc +++ b/Tools/projectGenerator/modules/jpeg.inc @@ -30,7 +30,7 @@ addLibSrcDir( 'ljpeg' ); addLibIncludePath( 'ljpeg' ); // Defines - if ( Generator::$platform == "360" ) + if ( T3D_Generator::$platform == "360" ) addProjectDefines( 'NO_GETENV;' ); endModule(); diff --git a/Tools/projectGenerator/modules/leapMotion.inc b/Tools/projectGenerator/modules/leapMotion.inc index d25e8df4c..5ffd9dfc8 100644 --- a/Tools/projectGenerator/modules/leapMotion.inc +++ b/Tools/projectGenerator/modules/leapMotion.inc @@ -61,7 +61,7 @@ beginModule( 'leapMotion' ); } // Only Windows is supported at this time - if ( Generator::$platform == "win32" ) + if ( T3D_Generator::$platform == "win32" ) { // Source addEngineSrcDir( "platform/input/leapMotion" ); diff --git a/Tools/projectGenerator/modules/libtheora.inc b/Tools/projectGenerator/modules/libtheora.inc index dfba45845..e1467201f 100644 --- a/Tools/projectGenerator/modules/libtheora.inc +++ b/Tools/projectGenerator/modules/libtheora.inc @@ -27,7 +27,7 @@ addLibSrcDir( 'libtheora/include/theora' ); addLibSrcDir( 'libtheora/lib' ); addLibSrcDir( 'libtheora/lib/dec' ); -switch( Generator::$platform ) +switch( T3D_Generator::$platform ) { case "win32": addLibSrcDir( 'libtheora/lib/dec/x86_vc' ); @@ -41,7 +41,7 @@ switch( Generator::$platform ) // As we don't use the encoder, disable this for now. addLibSrcDir( 'libtheora/lib/enc' ); -switch( Generator::$platform ) +switch( T3D_Generator::$platform ) { case "win32": addLibSrcDir( 'libtheora/lib/enc/x86_32_vs' ); diff --git a/Tools/projectGenerator/modules/oculusVR.inc b/Tools/projectGenerator/modules/oculusVR.inc index 4945a9ad9..bcf2a3199 100644 --- a/Tools/projectGenerator/modules/oculusVR.inc +++ b/Tools/projectGenerator/modules/oculusVR.inc @@ -61,7 +61,7 @@ beginModule( 'oculusVR' ); } // Only Windows is supported at this time - if ( Generator::$platform == "win32" ) + if ( T3D_Generator::$platform == "win32" ) { // Source addEngineSrcDir( "platform/input/oculusVR" ); diff --git a/Tools/projectGenerator/modules/openal.inc b/Tools/projectGenerator/modules/openal.inc index d3356b55f..471b4e42f 100644 --- a/Tools/projectGenerator/modules/openal.inc +++ b/Tools/projectGenerator/modules/openal.inc @@ -26,7 +26,7 @@ addEngineSrcDir('sfx/openal'); addEngineSrcDir('sfx/openal/mac'); addEngineSrcDir('sfx/openal/win32'); -if ( Generator::$platform == "win32" ) +if ( T3D_Generator::$platform == "win32" ) addIncludePath( getAppLibSrcDir() . 'openal/win32' ); ?> diff --git a/Tools/projectGenerator/modules/physX3.inc b/Tools/projectGenerator/modules/physX3.inc index 42eb48b5a..74fad8f82 100644 --- a/Tools/projectGenerator/modules/physX3.inc +++ b/Tools/projectGenerator/modules/physX3.inc @@ -75,10 +75,16 @@ beginModule( 'physX3' ); // Source addEngineSrcDir( "T3D/physics/physx3" ); + addEngineSrcDir( "T3D/physics/physx3/Cloth" ); + addEngineSrcDir( "T3D/physics/physx3/Particles" ); // Includes addIncludePath( $PHYSX3_SDK_PATH . "/Include" ); - + addIncludePath( $PHYSX3_SDK_PATH . "/Include/extensions" ); + addIncludePath( $PHYSX3_SDK_PATH . "/Include/foundation" ); + addIncludePath( $PHYSX3_SDK_PATH . "/Include/characterkinematic" ); + addIncludePath( $PHYSX3_SDK_PATH . "/Include/common" ); + // Libs addProjectLibDir( $PHYSX3_SDK_PATH . "/Lib/win32" ); addProjectLibInput( "PhysX3_x86.lib","PhysX3CHECKED_x86.lib" ); diff --git a/Tools/projectGenerator/modules/png.inc b/Tools/projectGenerator/modules/png.inc index 4165225e3..97ab5dccf 100644 --- a/Tools/projectGenerator/modules/png.inc +++ b/Tools/projectGenerator/modules/png.inc @@ -30,7 +30,7 @@ beginModule( 'lpng' ); addLibIncludePath( 'lpng' ); // Defines - if ( Generator::$platform == "360" ) + if ( T3D_Generator::$platform == "360" ) addProjectDefines( 'PNG_NO_ASSEMBLER_CODE' ); endModule(); diff --git a/Tools/projectGenerator/modules/razerHydra.inc b/Tools/projectGenerator/modules/razerHydra.inc index c381c976b..8a3bea037 100644 --- a/Tools/projectGenerator/modules/razerHydra.inc +++ b/Tools/projectGenerator/modules/razerHydra.inc @@ -61,7 +61,7 @@ beginModule( 'razerHydra' ); } // Only Windows is supported at this time - if ( Generator::$platform == "win32" ) + if ( T3D_Generator::$platform == "win32" ) { // Source addEngineSrcDir( "platform/input/razerHydra" ); diff --git a/Tools/projectGenerator/projectGenUtils.inc b/Tools/projectGenerator/projectGenUtils.inc index f3e599ac9..416dfa8f1 100644 --- a/Tools/projectGenerator/projectGenUtils.inc +++ b/Tools/projectGenerator/projectGenUtils.inc @@ -32,7 +32,7 @@ function beginProject($name, $sharedConfig) // Set the game project name, this is what your game's exe/dll will be called setGameProjectName($name); - if (Generator::$platform == "win32" && $sharedConfig) + if (T3D_Generator::$platform == "win32" && $sharedConfig) beginSolutionConfig( $name, '{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}' ); @@ -40,18 +40,18 @@ function beginProject($name, $sharedConfig) function endProject($sharedConfig) { - if (Generator::$platform == "win32" && $sharedConfig) + if (T3D_Generator::$platform == "win32" && $sharedConfig) endSolutionConfig(); } function beginSolutionConfig( $name, $guid = '' ) { - Generator::beginSolution( $name, $guid ); + T3D_Generator::beginSolution( $name, $guid ); } function addSolutionProjectRef( $pname ) { - Generator::addSolutionProjectRef( $pname ); + T3D_Generator::addSolutionProjectRef( $pname ); } // Add a reference to an external project, this is used for WPF projects currently @@ -59,114 +59,114 @@ function addSolutionProjectRef( $pname ) // However, it is nice to not have to add the project to the solution whenever you run the project generator function addSolutionProjectRefExt( $pname, $ppath, $pguid ) { - Generator::addSolutionProjectRefExt( $pname, $ppath, $pguid ); + T3D_Generator::addSolutionProjectRefExt( $pname, $ppath, $pguid ); } function endSolutionConfig() { - Generator::endSolution(); + T3D_Generator::endSolution(); } function setPlatform( $platform ) { echo(' - Setting platform to: ' . $platform . "\n"); - Generator::$platform = $platform; + T3D_Generator::$platform = $platform; } function includeLib( $libName ) { - //echo( "GLP: " . Generator::getGeneratorLibsPath() . $libName . "\n" ); + //echo( "GLP: " . T3D_Generator::getGeneratorLibsPath() . $libName . "\n" ); - Generator::includeLib( $libName ); + T3D_Generator::includeLib( $libName ); } function includeModule( $modName ) { - require( Generator::getGeneratorModulesPath() . $modName . '.inc' ); + require( T3D_Generator::getGeneratorModulesPath() . $modName . '.inc' ); } function beginActiveXConfig( $lib_name, $guid = '', $gameDir = 'game', $output_name = '' ) { - Generator::beginActiveXConfig( $lib_name, $guid, $gameDir, $output_name ); + T3D_Generator::beginActiveXConfig( $lib_name, $guid, $gameDir, $output_name ); } function endActiveXConfig() { - Generator::endActiveXConfig(); + T3D_Generator::endActiveXConfig(); } function beginSafariConfig( $lib_name, $guid = '', $gameDir = 'game', $output_name = '' ) { - Generator::beginSafariConfig( $lib_name, $guid, $gameDir, $output_name ); + T3D_Generator::beginSafariConfig( $lib_name, $guid, $gameDir, $output_name ); } function endSafariConfig() { - Generator::endSafariConfig(); + T3D_Generator::endSafariConfig(); } function beginSharedLibConfig( $lib_name, $guid = '', $gameDir = 'game', $output_name = '' ) { - Generator::beginSharedLibConfig( $lib_name, $guid, $gameDir, $output_name ); + T3D_Generator::beginSharedLibConfig( $lib_name, $guid, $gameDir, $output_name ); } function endSharedLibConfig() { - Generator::endSharedLibConfig(); + T3D_Generator::endSharedLibConfig(); } function beginNPPluginConfig( $lib_name, $guid = '', $gameDir = 'game', $output_name = '' ) { - Generator::beginNPPluginConfig( $lib_name, $guid, $gameDir, $output_name ); + T3D_Generator::beginNPPluginConfig( $lib_name, $guid, $gameDir, $output_name ); } function endNPPluginConfig() { - Generator::endNPPluginConfig(); + T3D_Generator::endNPPluginConfig(); } function beginLibConfig( $lib_name, $guid = '', $gameDir = 'game', $output_name = '' ) { - Generator::beginLibConfig( $lib_name, $guid, $gameDir, $output_name ); + T3D_Generator::beginLibConfig( $lib_name, $guid, $gameDir, $output_name ); } function endLibConfig() { - Generator::endLibConfig(); + T3D_Generator::endLibConfig(); } function beginAppConfig( $app_name, $guid = '', $game_dir = 'game', $output_name = '' ) { - Generator::beginAppConfig( $app_name, $guid, $game_dir, $output_name ); + T3D_Generator::beginAppConfig( $app_name, $guid, $game_dir, $output_name ); } function endAppConfig() { - Generator::endAppConfig(); + T3D_Generator::endAppConfig(); } function beginSharedAppConfig( $app_name, $guid = '', $game_dir = 'game', $output_name = '' ) { - Generator::beginSharedAppConfig( $app_name, $guid, $game_dir, $output_name ); + T3D_Generator::beginSharedAppConfig( $app_name, $guid, $game_dir, $output_name ); } function endSharedAppConfig() { - Generator::endSharedAppConfig(); + T3D_Generator::endSharedAppConfig(); } function beginCSProjectConfig( $app_name, $guid = '', $game_dir = 'game', $output_name = '' ) { - Generator::beginCSProjectConfig( $app_name, $guid, $game_dir, $output_name ); + T3D_Generator::beginCSProjectConfig( $app_name, $guid, $game_dir, $output_name ); } function endCSProjectConfig() { - Generator::endCSProjectConfig(); + T3D_Generator::endCSProjectConfig(); } @@ -175,26 +175,26 @@ function endCSProjectConfig() function beginModule( $name ) { - Generator::beginModule( $name ); + T3D_Generator::beginModule( $name ); } function endModule() { - Generator::endModule(); + T3D_Generator::endModule(); } function addSrcDir( $dir, $recurse = false ) { //echo( "ADD SRC DIR: " . $dir . "\n" ); - Generator::addSrcDir( $dir, $recurse ); + T3D_Generator::addSrcDir( $dir, $recurse ); } function addSrcFile( $file ) { //echo( "ADD SRC FILE: " . $file . "\n" ); - Generator::addSrcFile( $file ); + T3D_Generator::addSrcFile( $file ); } function addEngineSrcDir( $dir ) @@ -213,12 +213,12 @@ function addEngineSrcFile( $file ) function addLibSrcDir( $dir ) { - addSrcDir( Generator::getLibSrcDir() . $dir ); + addSrcDir( T3D_Generator::getLibSrcDir() . $dir ); } function addLibSrcFile( $file ) { - addSrcDir( Generator::getLibSrcDir() . $file ); + addSrcDir( T3D_Generator::getLibSrcDir() . $file ); } function addLibIncludePath( $path ) @@ -253,29 +253,29 @@ function getAppEngineBinDir() function getEngineSrcDir() { - return Generator::getEngineSrcDir(); + return T3D_Generator::getEngineSrcDir(); } function getLibSrcDir() { - return Generator::getLibSrcDir(); + return T3D_Generator::getLibSrcDir(); } function getEngineBinDir() { - return Generator::getEngineBinDir(); + return T3D_Generator::getEngineBinDir(); } function addIncludePath( $path ) { //echo( "ADD INCLUDE: " . $path . "\n" ); - Generator::addIncludePath( $path ); + T3D_Generator::addIncludePath( $path ); } /// Add a preprocessor directive/define function addProjectDefine( $d, $v = null ) { - Generator::addProjectDefine( $d, $v ); + T3D_Generator::addProjectDefine( $d, $v ); } /// Add a list of defines in one call function addProjectDefines() @@ -284,143 +284,143 @@ function addProjectDefines() $count = func_num_args(); if( $count > 0 ) - Generator::addProjectDefines( $args ); + T3D_Generator::addProjectDefines( $args ); else echo( "addProjectDefines() - no arguments passed!" ); } function setProjectGUID( $guid ) { - Generator::setProjectGUID( $guid ); + T3D_Generator::setProjectGUID( $guid ); } function setProjectModuleDefinitionFile( $mdef ) { - Generator::setProjectModuleDefinitionFile( $mdef ); + T3D_Generator::setProjectModuleDefinitionFile( $mdef ); } function addProjectLibDir( $dir ) { - Generator::addProjectLibDir( $dir ); + T3D_Generator::addProjectLibDir( $dir ); } function addProjectLibInput( $lib_name, $libDebug = null ) { - Generator::addProjectLibInput( $lib_name, $libDebug ); + T3D_Generator::addProjectLibInput( $lib_name, $libDebug ); } function addProjectIgnoreDefaultLib( $lib ) { - Generator::addProjectIgnoreDefaultLib( $lib ); + T3D_Generator::addProjectIgnoreDefaultLib( $lib ); } function copyFileToProject( $sourcePath, $projPath ) { - Generator::copyFileToProject( $sourcePath, $projPath ); + T3D_Generator::copyFileToProject( $sourcePath, $projPath ); } function addProjectDependency( $pd ) { - Generator::addProjectDependency( $pd ); + T3D_Generator::addProjectDependency( $pd ); } function removeProjectDependency( $pd ) { - Generator::removeProjectDependency( $pd ); + T3D_Generator::removeProjectDependency( $pd ); } function addProjectReference( $refName, $version = "" ) { - Generator::addProjectReference( $refName, $version ); + T3D_Generator::addProjectReference( $refName, $version ); } // disable a specific project compiler warning function disableProjectWarning( $warning ) { - Generator::disableProjectWarning( $warning ); + T3D_Generator::disableProjectWarning( $warning ); } function setGameProjectName($name) { - Generator::setGameProjectName($name); + T3D_Generator::setGameProjectName($name); } function getGameProjectName() { - return Generator::getGameProjectName(); + return T3D_Generator::getGameProjectName(); } function setToolBuild($tb) { - Generator::setToolBuild($tb); + T3D_Generator::setToolBuild($tb); } function getToolBuild() { - return Generator::getToolBuild(); + return T3D_Generator::getToolBuild(); } function setWatermarkBuild($wb) { - Generator::setWatermarkBuild($wb); + T3D_Generator::setWatermarkBuild($wb); } function getWatermarkBuild() { - return Generator::getWatermarkBuild(); + return T3D_Generator::getWatermarkBuild(); } function setPurchaseScreenBuild($psb) { - Generator::setPurchaseScreenBuild($psb); + T3D_Generator::setPurchaseScreenBuild($psb); } function getPurchaseScreenBuild() { - return Generator::getPurchaseScreenBuild(); + return T3D_Generator::getPurchaseScreenBuild(); } function setDemoBuild($db) { - Generator::setDemoBuild($db); + T3D_Generator::setDemoBuild($db); } function getDemoBuild() { - return Generator::getDemoBuild(); + return T3D_Generator::getDemoBuild(); } function setObjectLimitBuild($olb) { - Generator::setObjectLimitBuild($olb); + T3D_Generator::setObjectLimitBuild($olb); } function getObjectLimitBuild() { - return Generator::getObjectLimitBuild(); + return T3D_Generator::getObjectLimitBuild(); } function setTimeOutBuild($tob) { - Generator::setTimeOutBuild($tob); + T3D_Generator::setTimeOutBuild($tob); } function getTimeOutBuild() { - return Generator::getTimeOutBuild(); + return T3D_Generator::getTimeOutBuild(); } function inProjectConfig() { - return Generator::inProjectConfig(); + return T3D_Generator::inProjectConfig(); } // On Windows, 1 - Console, 2 - Windows function setProjectSubSystem( $subSystem ) { - Generator::setProjectSubSystem( $subSystem ); + T3D_Generator::setProjectSubSystem( $subSystem ); } // Sets whether to use /MT or /MD code generation/runtime on Windows @@ -429,7 +429,7 @@ function setProjectSubSystem( $subSystem ) // You must include or install via the redistributable package the appropriate VS runtime for end users. function setDLLRuntime ($val) { - Generator::setDLLRuntime( $val ); + T3D_Generator::setDLLRuntime( $val ); } //-------------------------------------------------------------------------------- UTIL diff --git a/Tools/projectGenerator/projectGenerator.php b/Tools/projectGenerator/projectGenerator.php index 103fa536e..692f5c046 100644 --- a/Tools/projectGenerator/projectGenerator.php +++ b/Tools/projectGenerator/projectGenerator.php @@ -70,7 +70,7 @@ if ( $argc >= 3 ) $torqueRoot = str_replace( "\\", "/", $argv[2] ); // Kick off the generator -Generator::init( $torqueRoot ); +T3D_Generator::init( $torqueRoot ); // Ready to read our config file. echo( " - Loading config file " . realpath($argv[1])."\n" ); @@ -78,12 +78,12 @@ echo( " - Loading config file " . realpath($argv[1])."\n" ); require( $argv[ 1 ] ); // Generate all projects -Generator::generateProjects( $tpl ); +T3D_Generator::generateProjects( $tpl ); // Now the solutions (if any) $tpl->clear_all_cache(); -Generator::generateSolutions( $tpl ); +T3D_Generator::generateSolutions( $tpl ); // finally write out the sample.html for web deployment (if any) WebPlugin::writeSampleHtml();