Index: trunk/VUT/work/README_ONLINE.txt
===================================================================
--- trunk/VUT/work/README_ONLINE.txt	(revision 193)
+++ trunk/VUT/work/README_ONLINE.txt	(revision 193)
@@ -0,0 +1,38 @@
+How to install the Visibility Work Package
+
+
+1) Requirements: 
+   WindowsXP
+   Ogre 1.03 for vs 7.1
+   Ogre Dependencies
+   
+2) add following environment variables:
+   OGRE_PATH: directory where ogre.sln is located
+   GAMETOOLS_PATH: directory where the gametools repository is located (e.g., d:\gametools)
+
+3) copy VUT/work/ogre_changes into OGRE_PATH directory
+
+4) Set configuration of Ogre soluation to release. add preprocessor flag GTP_VISIBILITY_MODIFIED_OGRE to following projects:
+   Plugin_OctreeSceneManager
+   RenderSystem_GL
+   RenderSystem_Direct9
+   RenderSystem_Direct7
+   OgreMain
+   example projects
+
+5) Add following resources to OGRE_PATH/Samples/Common/bin/Release/resource.cfg
+
+   FileSystem=D:/gametools/trunk/VUT/Ogre/resources/materials/scripts
+   FileSystem=D:/gametools/trunk/VUT/Ogre/resources/materials/textures
+   FileSystem=D:/gametools/trunk/VUT/Ogre/resources/materials/textures/trees
+   FileSystem=D:/gametools/trunk/VUT/Ogre/resources/models
+   FileSystem=D:/gametools/trunk/VUT/Ogre/resources/models/trees
+   FileSystem=D:/gametools/trunk/VUT/Ogre/resources/overlays
+   FileSystem=D:/gametools/trunk/VUT/Ogre/resources/media
+
+6) Add Plugin_VisibilitySceneManager to OGRE_PATH/Samples/Common/bin/Release/Plugins.cfg
+   and comment out OctreeSceneManager
+
+7) Copy D:\gametools\trunk\VUT\Ogre\resources/terrain.cfg into OGRE_PATH/Samples/Common/bin/Release
+
+8) start TestCullingTerrain.exe
Index: trunk/VUT/work/IVReader/include/ivmanualmeshloader.h
===================================================================
--- trunk/VUT/work/IVReader/include/ivmanualmeshloader.h	(revision 183)
+++ trunk/VUT/work/IVReader/include/ivmanualmeshloader.h	(revision 193)
@@ -3,5 +3,5 @@
 
 
-#include "ogre.h"
+#include "Ogre.h"
 #include "ivmeshdata.h"
 
Index: trunk/VUT/work/ogre_changes/OgreMain/include/OgreRenderable.h
===================================================================
--- trunk/VUT/work/ogre_changes/OgreMain/include/OgreRenderable.h	(revision 158)
+++ trunk/VUT/work/ogre_changes/OgreMain/include/OgreRenderable.h	(revision 193)
@@ -53,5 +53,10 @@
     {
     public:
-		Renderable() {mId = -1;}
+		Renderable() : mRenderDetailOverrideable(true) 
+#ifdef GTP_VISIBILITY_MODIFIED_OGRE
+, mId(-1)
+#endif // GTP_VISIBILITY_MODIFIED_OGRE
+{}
+		
         /** Virtual destructor needed as class has virtual methods. */
         virtual ~Renderable() { }
@@ -227,4 +232,24 @@
             }
         }
+
+		/** Sets whether this renderable's chosen detail level can be
+			overridden (downgraded) by the camera setting. 
+		@param override true means that a lower camera detail will override this
+			renderables detail level, false means it won't.
+		*/
+		virtual void setRenderDetailOverrideable(bool override)
+		{
+			mRenderDetailOverrideable = override;
+		}
+
+		/** Gets whether this renderable's chosen detail level can be
+			overridden (downgraded) by the camera setting. 
+		*/
+		virtual bool getRenderDetailOverrideable(void) const
+		{
+			return mRenderDetailOverrideable;
+		}
+
+#ifdef GTP_VISIBILITY_MODIFIED_OGRE
 		/** Sets an id for this renderable.
 		*/
@@ -233,10 +258,13 @@
 		*/
 		int getId() {return mId;}
-
+#endif // GTP_VISIBILITY_MODIFIED_OGRE
     protected:
         static const PlaneList msDummyPlaneList;
         typedef std::map<size_t, Vector4> CustomParameterMap;
         CustomParameterMap mCustomParameters;
+		bool mRenderDetailOverrideable;
+#ifdef GTP_VISIBILITY_MODIFIED_OGRE
 		int mId;
+#endif // GTP_VISIBILITY_MODIFIED_OGRE
     };
 
Index: trunk/VUT/work/ogre_changes/OgreMain/include/OgreRenderSystem.h
===================================================================
--- trunk/VUT/work/ogre_changes/OgreMain/include/OgreRenderSystem.h	(revision 150)
+++ trunk/VUT/work/ogre_changes/OgreMain/include/OgreRenderSystem.h	(revision 193)
@@ -318,4 +318,15 @@
 				Values: true, false
 				Default: 0
+				** 
+				Key: "border" 
+				Description: The type of window border (in windowed mode)
+				Values: none, fixed, resize
+				Default: resize
+				**
+				Key: "outerDimensions" 
+				Description: Whether the width/height is expressed as the size of the 
+				outer window, rather than the content area
+				Values: true, false
+				Default: false 
         */
 		virtual RenderWindow* createRenderWindow(const String &name, unsigned int width, unsigned int height, 
@@ -980,5 +991,7 @@
         bool mInvertVertexWinding;
 
+#ifdef GTP_VISIBILITY_MODIFIED_OGRE
 		int mColour[4];
+#endif // GTP_VISIBILITY_MODIFIED_OGRE
     };
 }
Index: trunk/VUT/work/ogre_changes/OgreMain/include/OgreRenderQueueSortingGrouping.h
===================================================================
--- trunk/VUT/work/ogre_changes/OgreMain/include/OgreRenderQueueSortingGrouping.h	(revision 139)
+++ trunk/VUT/work/ogre_changes/OgreMain/include/OgreRenderQueueSortingGrouping.h	(revision 193)
@@ -48,5 +48,9 @@
         objects.
     */
-    class RenderPriorityGroup
+#ifdef GTP_VISIBILITY_MODIFIED_OGRE
+	class _OgreExport RenderPriorityGroup
+#else
+    class _OgrePrivate RenderPriorityGroup
+#endif // GTP_VISIBILITY_MODIFIED_OGRE
     {
         /** Internal struct reflecting a single Pass for a Renderable. 
@@ -247,5 +251,5 @@
         This is an internal OGRE class, not intended for apps to use.
     */
-    class RenderQueueGroup
+    class _OgrePrivate RenderQueueGroup
     {
     public:
Index: trunk/VUT/work/ogre_changes/OgreMain/src/OgreFrustum.cpp
===================================================================
--- trunk/VUT/work/ogre_changes/OgreMain/src/OgreFrustum.cpp	(revision 61)
+++ trunk/VUT/work/ogre_changes/OgreMain/src/OgreFrustum.cpp	(revision 193)
@@ -496,4 +496,9 @@
             updateFrustum();
 
+			Vector3 newpos = position;
+			if (mReflect)
+			{
+				newpos = mReflectMatrix * newpos;
+			}
             Matrix4 combo = mStandardProjMatrix * mViewMatrix;
             mFrustumPlanes[FRUSTUM_PLANE_LEFT].normal.x = combo[3][0] + combo[0][0];
@@ -520,13 +525,17 @@
             mFrustumPlanes[FRUSTUM_PLANE_NEAR].normal.y = combo[3][1] + combo[2][1];
             mFrustumPlanes[FRUSTUM_PLANE_NEAR].normal.z = combo[3][2] + combo[2][2];
-            mFrustumPlanes[FRUSTUM_PLANE_NEAR].d = combo[3][3] + combo[2][3];
+			mFrustumPlanes[FRUSTUM_PLANE_NEAR].normal.normalise();
+			mFrustumPlanes[FRUSTUM_PLANE_NEAR].d = 
+				-(mFrustumPlanes[FRUSTUM_PLANE_NEAR].normal.dotProduct(newpos) + mNearDist);
 
             mFrustumPlanes[FRUSTUM_PLANE_FAR].normal.x = combo[3][0] - combo[2][0];
             mFrustumPlanes[FRUSTUM_PLANE_FAR].normal.y = combo[3][1] - combo[2][1];
             mFrustumPlanes[FRUSTUM_PLANE_FAR].normal.z = combo[3][2] - combo[2][2];
-            mFrustumPlanes[FRUSTUM_PLANE_FAR].d = combo[3][3] - combo[2][3];
-
-            // Renormalise any normals which were not unit length
-            for(int i=0; i<6; i++ ) 
+			mFrustumPlanes[FRUSTUM_PLANE_FAR].normal.normalise();
+			mFrustumPlanes[FRUSTUM_PLANE_FAR].d = 
+				-(mFrustumPlanes[FRUSTUM_PLANE_FAR].normal.dotProduct(newpos) - mFarDist);
+
+            // Renormalise any normals which were not unit length (not near & far)
+            for(int i=2; i<6; i++ ) 
             {
                 float length = mFrustumPlanes[i].normal.normalise();
Index: trunk/VUT/work/ogre_changes/OgreMain/src/OgreSceneManager.cpp
===================================================================
--- trunk/VUT/work/ogre_changes/OgreMain/src/OgreSceneManager.cpp	(revision 183)
+++ trunk/VUT/work/ogre_changes/OgreMain/src/OgreSceneManager.cpp	(revision 193)
@@ -130,5 +130,7 @@
 	mShadowCasterQueryListener = new ShadowCasterSceneQueryListener(this);
 
-
+    Root *root = Root::getSingletonPtr();
+    if (root)
+        _setDestinationRenderSystem(root->getRenderSystem());
 }
 //-----------------------------------------------------------------------
@@ -392,8 +394,7 @@
                 // Calc squared distance
                 lt->tempSquareDist = (lt->getDerivedPosition() - position).squaredLength();
-                lt->tempSquareDist -= squaredRadius;
                 // only add in-range lights
                 Real range = lt->getAttenuationRange();
-                if (lt->tempSquareDist <= (range * range))
+                if ((lt->tempSquareDist - squaredRadius) <= (range * range))
                 {
                     destList.push_back(lt);
@@ -403,6 +404,6 @@
     }
 
-    // Sort
-    std::sort(destList.begin(), destList.end(), lightLess());
+    // Sort (stable to guarantee ordering on directional lights)
+    std::stable_sort(destList.begin(), destList.end(), lightLess());
 
 
@@ -527,4 +528,12 @@
 {
 	removeAllStaticGeometry();
+    removeAllEntities();
+    removeAllBillboardSets();
+    removeAllLights();
+
+	// Clear root node of all children
+	mSceneRoot->removeAllChildren();
+	mSceneRoot->detachAllObjects();
+
     // Delete all SceneNodes, except root that is
     for (SceneNodeList::iterator i = mSceneNodes.begin();
@@ -536,11 +545,5 @@
     mAutoTrackingSceneNodes.clear();
 
-    // Clear root node of all children
-    mSceneRoot->removeAllChildren();
-    mSceneRoot->detachAllObjects();
-
-    removeAllEntities();
-    removeAllBillboardSets();
-    removeAllLights();
+
 
     // Clear animations
@@ -607,4 +610,11 @@
     }
 
+	// detach from parent (don't do this in destructor since bulk destruction
+	// behaves differently)
+	Node* parentNode = i->second->getParent();
+	if (parentNode)
+	{
+		parentNode->removeChild(i->second);
+	}
     delete i->second;
     mSceneNodes.erase(i);
@@ -646,8 +656,8 @@
 
     // TEST
-    
-    //LogManager::getSingleton().logMessage("BEGIN PASS " + StringConverter::toString(pass->getIndex()) + 
-    //" of " + pass->getParent()->getParent()->getName() + "\n");
-    
+    /*
+    LogManager::getSingleton().logMessage("BEGIN PASS " + StringConverter::toString(pass->getIndex()) + 
+    " of " + pass->getParent()->getParent()->getName());
+    */
     bool passSurfaceAndLightParams = true;
 
@@ -868,4 +878,6 @@
     // Tell params about current ambient light
     mAutoParamDataSource.setAmbientLightColour(mAmbientLight);
+	// Tell rendersystem
+	mDestRenderSystem->setAmbientLight(mAmbientLight.r, mAmbientLight.g, mAmbientLight.b);
 
     // Tell params about render target
@@ -1540,5 +1552,4 @@
             renderShadowVolumesToStencil(l, mCameraInProgress);
             // render full-screen shadow modulator for all lights
-			//LogManager::getSingleton().logMessage("setting shadow modulative pass");
             setPass(mShadowModulativePass);
             // turn stencil check on
@@ -1801,5 +1812,4 @@
             continue;
 
-		//LogManager::getSingleton().logMessage("setting solid pass");
         // For solids, we try to do each pass in turn
         Pass* usedPass = setPass(ipass->first);
@@ -1832,5 +1842,4 @@
         itrans != itransend; ++itrans)
     {
-		//LogManager::getSingleton().logMessage("setting transparent pass");
         // For transparents, we have to accept that we can't sort entirely by pass
         setPass(itrans->pass);
@@ -1909,5 +1918,6 @@
 
 	itransend = objs.end();
-	for (itrans = objs.begin(); itrans != itransend; ++itrans)
+	for (itrans = objs.begin(); 
+		itrans != itransend; ++itrans)
 	{
 		Renderable *r = itrans->renderable;
@@ -1917,5 +1927,4 @@
 		if (p->getParent()->getParent()->getTransparencyCastsShadows())
 		{
-			//LogManager::getSingleton().logMessage("setting transparent shadow pass");
 			setPass(p);
 			renderSingleObject(itrans->renderable, p, doLightIteration, manualLightList);
@@ -1930,5 +1939,5 @@
     unsigned short numMatrices;
     static bool normalisedNormals = false;
-    static SceneDetailLevel camDetailLevel = mCameraInProgress->getDetailLevel();
+    SceneDetailLevel camDetailLevel = mCameraInProgress->getDetailLevel();
     static SceneDetailLevel lastDetailLevel = camDetailLevel;
     static RenderOperation ro;
@@ -1981,6 +1990,7 @@
     // Set up the solid / wireframe override
     SceneDetailLevel reqDetail = rend->getRenderDetail();
-    if (reqDetail != lastDetailLevel || reqDetail != camDetailLevel)
-    {
+    if (rend->getRenderDetailOverrideable())
+    {
+        // check camera detial only when render detail is overridable
         if (reqDetail > camDetailLevel)
         {
@@ -1988,4 +1998,7 @@
             reqDetail = camDetailLevel;
         }
+    }
+    if (reqDetail != lastDetailLevel)
+    {
         mDestRenderSystem->_setRasterisationMode(reqDetail);
         lastDetailLevel = reqDetail;
@@ -2416,5 +2429,4 @@
         mDestRenderSystem->_beginFrame();
 
-	//LogManager::getSingleton().logMessage("setting manual pass");
     setPass(pass);
     mDestRenderSystem->_render(*rend);
@@ -2814,4 +2826,9 @@
 void SceneManager::initShadowVolumeMaterials(void)
 {
+    /* This should have been set in the SceneManager constructor, but if you
+       created the SceneManager BEFORE the Root object, you will need to call
+       SceneManager::_setDestinationRenderSystem manually.
+     */
+    assert( mDestRenderSystem );
 
     if (mShadowMaterialInitDone)
@@ -3012,5 +3029,4 @@
 Pass* SceneManager::deriveShadowCasterPass(Pass* pass)
 {
-	//LogManager::getSingleton().logMessage("*********derive shadow caster pass*********");
     switch (mShadowTechnique)
     {
@@ -3018,10 +3034,8 @@
 		if (mShadowTextureCustomCasterPass)
 		{
-			//LogManager::getSingleton().logMessage("custom caster pass");
 			// Caster pass has been customised
 
 			if (!pass->getShadowCasterVertexProgramName().empty())
 			{
-				//LogManager::getSingleton().logMessage("custom caster pass has vertex program");
 				// Have to merge the shadow caster vertex program in
 				mShadowTextureCustomCasterPass->setVertexProgram(
@@ -3040,5 +3054,4 @@
 			else if (mShadowTextureCasterVPDirty)
 			{
-				//LogManager::getSingleton().logMessage("caster pass dirty");
 				// reset
 				mShadowTextureCustomCasterPass->setVertexProgram(
@@ -3056,9 +3069,7 @@
 		else
 		{
-			//LogManager::getSingleton().logMessage("standard caster pass");
 			// Standard pass
 			if (pass->hasVertexProgram())
 			{
-				//LogManager::getSingleton().logMessage("standard caster pass has vertex program");
 				// Have to merge the shadow caster vertex program in
 				// This may in fact be blank, in which case it falls back on 
@@ -3081,5 +3092,4 @@
 			else if (mShadowCasterPlainBlackPass->hasVertexProgram())
 			{
-				//LogManager::getSingleton().logMessage("standard caster pass no vertex program");
 				// reset
 				mShadowCasterPlainBlackPass->setVertexProgram("");
@@ -3095,5 +3105,5 @@
 Pass* SceneManager::deriveShadowReceiverPass(Pass* pass)
 {
-	//LogManager::getSingleton().logMessage("*********derive shadow receiver pass*********");
+
     switch (mShadowTechnique)
     {
@@ -3102,8 +3112,7 @@
 		{
 			// Receiver pass has been customised
-			//LogManager::getSingleton().logMessage("custom receiver pass");
+
 			if (!pass->getShadowReceiverVertexProgramName().empty())
 			{
-				//LogManager::getSingleton().logMessage("merge receiver pass shadow vertex program");
 				// Have to merge the shadow Receiver vertex program in
 				mShadowTextureCustomReceiverPass->setVertexProgram(
@@ -3122,5 +3131,4 @@
 			else if (mShadowTextureReceiverVPDirty)
 			{
-				//LogManager::getSingleton().logMessage("receiver pass dirty");
 				// reset
 				mShadowTextureCustomReceiverPass->setVertexProgram(
@@ -3138,8 +3146,6 @@
 		else
 		{
-			//LogManager::getSingleton().logMessage("no custom receiver pass");
 			if (pass->hasVertexProgram())
 			{
-				//LogManager::getSingleton().logMessage("standard receiver pass has vertex program");
 				// Have to merge the receiver vertex program in
 				// This may return "" which means fixed function will be used
@@ -3161,5 +3167,4 @@
 			else if (mShadowReceiverPass->hasVertexProgram())
 			{
-				//LogManager::getSingleton().logMessage("standard receiver pass no vertex program");
 				// reset
 				mShadowReceiverPass->setVertexProgram("");
@@ -3383,5 +3388,4 @@
                 setColourOperationEx(LBX_MODULATE, LBS_MANUAL, LBS_CURRENT,
                 zfailAlgo ? ColourValue(0.7, 0.0, 0.2) : ColourValue(0.0, 0.7, 0.2));
-			//LogManager::getSingleton().logMessage("setting shadow debug pass");
             setPass(mShadowDebugPass);
             renderShadowVolumeObjects(iShadowRenderables, mShadowDebugPass, &lightList, flags,
Index: trunk/VUT/work/ogre_changes/Plugins/OctreeSceneManager/include/OgreOctree.h
===================================================================
--- trunk/VUT/work/ogre_changes/Plugins/OctreeSceneManager/include/OgreOctree.h	(revision 158)
+++ trunk/VUT/work/ogre_changes/Plugins/OctreeSceneManager/include/OgreOctree.h	(revision 193)
@@ -36,5 +36,7 @@
 #define OCTREE_H
 
+#ifdef GTP_VISIBILITY_MODIFIED_OGRE
 #include "OgreTerrainPrerequisites.h"
+#endif
 #include <OgreAxisAlignedBox.h>
 #include <OgreWireBoundingBox.h>
@@ -58,5 +60,9 @@
 */
 
+#ifdef GTP_VISIBILITY_MODIFIED_OGRE
 class _OgreTerrainExport Octree
+#else
+class Octree
+#endif // GTP_VISIBILITY_MODIFIED_OGRE
 {
 public:
Index: trunk/VUT/work/ogre_changes/Plugins/OctreeSceneManager/include/OgreOctreeNode.h
===================================================================
--- trunk/VUT/work/ogre_changes/Plugins/OctreeSceneManager/include/OgreOctreeNode.h	(revision 187)
+++ trunk/VUT/work/ogre_changes/Plugins/OctreeSceneManager/include/OgreOctreeNode.h	(revision 193)
@@ -47,6 +47,9 @@
 *
 */
-
+#ifdef GTP_VISIBILITY_MODIFIED_OGRE
 class _OgreTerrainExport OctreeNode : public SceneNode
+#else
+class OctreeNode : public SceneNode
+#endif // GTP_VISIBILITY_MODIFIED_OGRE
 {
 public:
@@ -104,4 +107,6 @@
     };
 
+
+
 #ifdef GTP_VISIBILITY_MODIFIED_OGRE
 	/// scale for node visualization
Index: trunk/VUT/work/ogre_changes/Plugins/OctreeSceneManager/include/OgreTerrainRenderable.h
===================================================================
--- trunk/VUT/work/ogre_changes/Plugins/OctreeSceneManager/include/OgreTerrainRenderable.h	(revision 159)
+++ trunk/VUT/work/ogre_changes/Plugins/OctreeSceneManager/include/OgreTerrainRenderable.h	(revision 193)
@@ -231,5 +231,9 @@
         inline int getRenderLevel() const
         {
+#ifdef GTP_VISIBILITY_MODIFIED_OGRE
             return mRenderLevel[msCurrentRenderLevelIndex];
+#else
+            return mRenderLevel;
+#endif // GTP_VISIBILITY_MODIFIED_OGRE
         };
 
Index: trunk/VUT/work/ogre_changes/Plugins/OctreeSceneManager/include/OgreOctreeCamera.h
===================================================================
--- trunk/VUT/work/ogre_changes/Plugins/OctreeSceneManager/include/OgreOctreeCamera.h	(revision 61)
+++ trunk/VUT/work/ogre_changes/Plugins/OctreeSceneManager/include/OgreOctreeCamera.h	(revision 193)
@@ -59,4 +59,5 @@
 than the default.
 */
+
 #ifdef GTP_VISIBILITY_MODIFIED_OGRE
 class _OgreTerrainExport OctreeCamera : public Camera
Index: trunk/VUT/work/ogre_changes/Plugins/OctreeSceneManager/include/OgreOctreeSceneManager.h
===================================================================
--- trunk/VUT/work/ogre_changes/Plugins/OctreeSceneManager/include/OgreOctreeSceneManager.h	(revision 139)
+++ trunk/VUT/work/ogre_changes/Plugins/OctreeSceneManager/include/OgreOctreeSceneManager.h	(revision 193)
@@ -35,5 +35,7 @@
 #define OCTREESCENEMANAGER_H
 
+#ifdef GTP_VISIBILITY_MODIFIED_OGRE
 #include "OgreTerrainPrerequisites.h"
+#endif // GTP_VISIBILITY_MODIFIED_OGRE
 #include "OgreSceneManager.h"
 #include "OgreRenderOperation.h"
@@ -71,5 +73,9 @@
 */
 
+#ifdef GTP_VISIBILITY_MODIFIED_OGRE
 class _OgreTerrainExport OctreeSceneManager : public SceneManager
+#else
+class OctreeSceneManager : public SceneManager
+#endif GTP_VISIBILITY_MODIFIED_OGRE
 {
     friend class OctreeIntersectionSceneQuery;
Index: trunk/VUT/work/ogre_changes/Plugins/OctreeSceneManager/src/OgreOctree.cpp
===================================================================
--- trunk/VUT/work/ogre_changes/Plugins/OctreeSceneManager/src/OgreOctree.cpp	(revision 160)
+++ trunk/VUT/work/ogre_changes/Plugins/OctreeSceneManager/src/OgreOctree.cpp	(revision 193)
@@ -36,5 +36,4 @@
 #include <OgreOctree.h>
 #include <OgreOctreeNode.h>
-#include <OgreLogManager.h>
 
 namespace Ogre
@@ -174,7 +173,9 @@
     if(mWireBoundingBox == 0)
         mWireBoundingBox = new WireBoundingBox();
-
-	//mWireBoundingBox->setupBoundingBox(mBox);
+#ifdef GTP_VISIBILITY_MODIFIED_OGRE
 	mWireBoundingBox->setupBoundingBox(mWorldAABB);
+#else
+	mWireBoundingBox->setupBoundingBox(mBox);
+#endif	
 
     return mWireBoundingBox;
Index: trunk/VUT/work/ogre_changes/Plugins/OctreeSceneManager/src/OgreOctreeNode.cpp
===================================================================
--- trunk/VUT/work/ogre_changes/Plugins/OctreeSceneManager/src/OgreOctreeNode.cpp	(revision 187)
+++ trunk/VUT/work/ogre_changes/Plugins/OctreeSceneManager/src/OgreOctreeNode.cpp	(revision 193)
@@ -38,5 +38,4 @@
 #include <OgreOctreeNode.h>
 #include <OgreOctreeSceneManager.h>
-#include <OgreLogManager.h>
 #include <OgreMeshManager.h>
 #include <OgreSubMesh.h>
@@ -157,10 +156,8 @@
         MovableObject * mo = mit->second;
 
-		//LogManager::getSingleton().logMessage("notify");
         mo->_notifyCurrentCamera(cam);
         if ( mo->isVisible() &&
             (!onlyShadowCasters || mo->getCastShadows()))
         {
-			//LogManager::getSingleton().logMessage("update queue");
             mo -> _updateRenderQueue( queue );
         }
Index: trunk/VUT/work/ogre_changes/Plugins/OctreeSceneManager/src/OgreTerrainRenderable.cpp
===================================================================
--- trunk/VUT/work/ogre_changes/Plugins/OctreeSceneManager/src/OgreTerrainRenderable.cpp	(revision 159)
+++ trunk/VUT/work/ogre_changes/Plugins/OctreeSceneManager/src/OgreTerrainRenderable.cpp	(revision 193)
@@ -67,5 +67,5 @@
     //-----------------------------------------------------------------------
     TerrainRenderable::TerrainRenderable(const String& name)
-        : mTerrain(0), mName(name),  mDeltaBuffers(0), mPositionBuffer(0)
+        : Renderable(), mTerrain(0), mName(name),  mDeltaBuffers(0), mPositionBuffer(0)
     {
         mForcedRenderLevel = -1;
@@ -220,9 +220,9 @@
                 *pSysPos++ = *pPos++ = ( float ) j * msOptions->scale.z; //z
 
-                *pTex0++ = ( float ) i / ( float ) msOptions->pageSize;
-                *pTex0++ = ( float ) ( float ) j / ( float ) msOptions->pageSize;
-
-                *pTex1++ = ( ( float ) i / ( float ) msOptions->tileSize ) * msOptions->detailTile;
-                *pTex1++ = ( ( float ) ( float ) j / ( float ) msOptions->tileSize ) * msOptions->detailTile;
+                *pTex0++ = ( float ) i / ( float ) ( msOptions->pageSize - 1 );
+                *pTex0++ = ( float ) j / ( float ) ( msOptions->pageSize - 1 );
+
+                *pTex1++ = ( ( float ) i / ( float ) ( msOptions->tileSize - 1 ) ) * msOptions->detailTile;
+                *pTex1++ = ( ( float ) j / ( float ) ( msOptions->tileSize - 1 ) ) * msOptions->detailTile;
 
                 if ( height < min )
@@ -261,6 +261,4 @@
 
         _calculateMinLevelDist2( C );
-        if (msOptions->lit)
-            _calculateNormals();
 
     }
@@ -301,4 +299,5 @@
     void TerrainRenderable::_calculateNormals()
     {
+
         Vector3 norm;
 
@@ -342,4 +341,5 @@
             return ;
         }
+
 
 		Vector3 cpos = cam -> getDerivedPosition();
@@ -381,5 +381,5 @@
             int nextLevel = mNextLevelDown[getRenderLevel()];
 #else
-			int nextLevel = mNextLevelDown;
+			int nextLevel = mNextLevelDown[mRenderLevel];
 #endif // GTP_VISIBILITY_MODIFIED_OGRE
             
@@ -393,8 +393,16 @@
                 // Set the morph such that the morph happens in the last 0.25 of
                 // the distance range
-                Real range = mMinLevelDistSqr[nextLevel] - mMinLevelDistSqr[getRenderLevel()];
+ #ifdef GTP_VISIBILITY_MODIFIED_OGRE
+Real range = mMinLevelDistSqr[nextLevel] - mMinLevelDistSqr[getRenderLevel()];
+#else
+                Real range = mMinLevelDistSqr[nextLevel] - mMinLevelDistSqr[mRenderLevel];
+#endif // GTP_VISIBILITY_MODIFIED_OGRE               
                 if (range)
                 {
-                    Real percent = (L - mMinLevelDistSqr[getRenderLevel()]) / range;
+#ifdef GTP_VISIBILITY_MODIFIED_OGRE
+Real percent = (L - mMinLevelDistSqr[getRenderLevel()]) / range;
+#else
+                    Real percent = (L - mMinLevelDistSqr[mRenderLevel]) / range;
+#endif // GTP_VISIBILITY_MODIFIED_OGRE
                     // scale result so that msLODMorphStart == 0, 1 == 1, clamp to 0 below that
                     Real rescale = 1.0f / (1.0f - msOptions->lodMorphStart);
@@ -430,4 +438,5 @@
 
         }
+
     }
     //-----------------------------------------------------------------------
@@ -668,9 +677,12 @@
             return ;
 
+
 	    if ( mLevelIndex.size() == 0 )
         {
             for ( int i = 0; i < 16; i++ )
             {
+
 				mLevelIndex.push_back( new IndexMap() );
+
             }
 
@@ -695,4 +707,5 @@
     void TerrainRenderable::_adjustRenderLevel( int i )
     {
+
 #ifdef GTP_VISIBILITY_MODIFIED_OGRE
         mRenderLevel[msCurrentRenderLevelIndex] = i;
Index: trunk/VUT/work/ogre_changes/RenderSystems/GL/include/OgreGLPrerequisites.h
===================================================================
--- trunk/VUT/work/ogre_changes/RenderSystems/GL/include/OgreGLPrerequisites.h	(revision 115)
+++ trunk/VUT/work/ogre_changes/RenderSystems/GL/include/OgreGLPrerequisites.h	(revision 193)
@@ -52,4 +52,5 @@
 #       define APIENTRY
 #   endif
+#   define GL_GLEXT_LEGACY 
 #   include <OpenGL/gl.h>
 #   include <OpenGL/glu.h>
@@ -270,5 +271,5 @@
     if (errCode != GL_NO_ERROR) {  \
     errString = gluErrorString (errCode);  \
-    LogManager::getSingleton().logMessage  ("[GL] :" + ERROR_MSG +  \
+    LogManager::getSingleton().logMessage  ("[GL] :" + Ogre::String(ERROR_MSG) +  \
     " : " + Ogre::String( (const char*) errString)); \
         } \
@@ -282,5 +283,5 @@
     errString = gluErrorString (errCode);  \
     OGRE_EXCEPT (Exception::ERR_INTERNAL_ERROR,  \
-    ERROR_MSG +  \
+    Ogre::String(ERROR_MSG) +  \
     " : " + Ogre::String( (const char*) errString), String("")); \
         } \
Index: trunk/VUT/work/ogre_changes/RenderSystems/GL/include/OgreWin32Window.h
===================================================================
--- trunk/VUT/work/ogre_changes/RenderSystems/GL/include/OgreWin32Window.h	(revision 153)
+++ trunk/VUT/work/ogre_changes/RenderSystems/GL/include/OgreWin32Window.h	(revision 193)
@@ -40,5 +40,5 @@
 	            bool fullScreen, const NameValuePairList *miscParams);
         void destroy(void);
-        bool isActive(void) const;
+        bool isVisible() const;
         bool isClosed(void) const;
         void reposition(int left, int top);
@@ -61,7 +61,4 @@
 		// Method for dealing with resize / move & 3d library
 		virtual void windowMovedOrResized(void);
-		bool isReady() const { return mReady; }
-		void setReady(bool set) { mReady = set; }
-		void setActive(bool set) { mActive = set; }
 		
 		void getCustomAttribute( const String& name, void* pData );
@@ -72,8 +69,8 @@
 		HDC		mHDC;
 		HGLRC	mGlrc;
-		int		mOldSwapIntervall;
-		bool	mActive;				// Is active i.e. visible
-		bool	mReady;					// Is ready i.e. available for update
+        bool    mIsExternal;
+        bool    mSizing;
 		bool	mClosed;
+        int     mDisplayFrequency;      // fullscreen only, to restore display
         Win32Context *mContext;
 
Index: trunk/VUT/work/ogre_changes/RenderSystems/GL/src/OgreGLTexture.cpp
===================================================================
--- trunk/VUT/work/ogre_changes/RenderSystems/GL/src/OgreGLTexture.cpp	(revision 156)
+++ trunk/VUT/work/ogre_changes/RenderSystems/GL/src/OgreGLTexture.cpp	(revision 193)
@@ -37,5 +37,5 @@
 #include "OgreCodec.h"
 #include "OgreImageCodec.h"
-
+#include "OgreStringConverter.h"
 
 #if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
@@ -200,5 +200,5 @@
 				if(depth>1)		depth = depth/2;
 			}
-			delete tmpdata;
+			delete [] tmpdata;
 		}
 		else
@@ -355,8 +355,19 @@
 			for(int mip=0; mip<=getNumMipmaps(); mip++)
 			{
-				mSurfaceList.push_back(HardwarePixelBufferSharedPtr(
-					new GLHardwarePixelBuffer(getGLTextureTarget(), mTextureID, face, mip,
-						static_cast<HardwareBuffer::Usage>(mUsage), doSoftware && mip==0)
-				));
+                GLHardwarePixelBuffer *buf = new GLHardwarePixelBuffer(getGLTextureTarget(), mTextureID, face, mip,
+						static_cast<HardwareBuffer::Usage>(mUsage), doSoftware && mip==0);
+				mSurfaceList.push_back(HardwarePixelBufferSharedPtr(buf));
+                
+                /// Check for error
+                if(buf->getWidth()==0 || buf->getHeight()==0 || buf->getDepth()==0)
+                {
+                    OGRE_EXCEPT(
+                        Exception::ERR_RENDERINGAPI_ERROR, 
+                        "Zero sized texture surface on texture "+getName()+
+                            " face "+StringConverter::toString(face)+
+                            " mipmap "+StringConverter::toString(mip)+
+                            ". Probably, the GL driver refused to create the texture.", 
+                            "GLTexture::_createSurfaceList");
+                }
 			}
 		}
Index: trunk/VUT/work/ogre_changes/RenderSystems/GL/src/OgreGLHardwareOcclusionQuery.cpp
===================================================================
--- trunk/VUT/work/ogre_changes/RenderSystems/GL/src/OgreGLHardwareOcclusionQuery.cpp	(revision 115)
+++ trunk/VUT/work/ogre_changes/RenderSystems/GL/src/OgreGLHardwareOcclusionQuery.cpp	(revision 193)
@@ -27,5 +27,4 @@
 #include "OgreException.h"
 
-
 namespace Ogre {
 
@@ -52,6 +51,9 @@
 	// Check for hardware occlusion support
 	// This is a hack to see if hw occlusion is supported. pointer is 0 if it's not supported.
-	//if (glGenQueriesARB_ptr != 0)
+#ifdef GTP_VISIBILITY_USE_ARB_QUERIES
+	if (glGenQueriesARB_ptr != 0)
+#else
 	if (glGenOcclusionQueriesNV_ptr != 0)
+#endif
     {
 		mHasOcclusionSupport = true;
@@ -64,6 +66,9 @@
 	if(mHasOcclusionSupport)
 	{
-		//glGenQueriesARB_ptr(1, &mQueryID );	
+#ifdef GTP_VISIBILITY_USE_ARB_QUERIES
+		glGenQueriesARB_ptr(1, &mQueryID );	
+#else
 		glGenOcclusionQueriesNV_ptr(1, &mQueryID);
+#endif
 	}
 }
@@ -76,6 +81,9 @@
 	if( mHasOcclusionSupport )
 	{
-		//glDeleteQueriesARB_ptr(1, &mQueryID);  
+#ifdef GTP_VISIBILITY_USE_ARB_QUERIES
+		glDeleteQueriesARB_ptr(1, &mQueryID);
+#else
 		glDeleteOcclusionQueriesNV_ptr(1, &mQueryID);  
+#endif
 	}	
 }
@@ -101,6 +109,9 @@
 		if (mSkipCounter == 0)
 		{
-			//glBeginQueryARB_ptr(GL_SAMPLES_PASSED_ARB, mQueryID);
+#ifdef GTP_VISIBILITY_USE_ARB_QUERIES
+			glBeginQueryARB_ptr(GL_SAMPLES_PASSED_ARB, mQueryID);
+#else
 			glBeginOcclusionQueryNV_ptr(mQueryID);
+#endif
 		}
 	}
@@ -114,6 +125,9 @@
 		if( mSkipCounter == 0)
 		{
-			//glEndQueryARB_ptr(GL_SAMPLES_PASSED_ARB);
+#ifdef GTP_VISIBILITY_USE_ARB_QUERIES
+			glEndQueryARB_ptr(GL_SAMPLES_PASSED_ARB);
+#else
 			glEndOcclusionQueryNV_ptr();
+#endif
 		}
 
@@ -129,6 +143,9 @@
 	if( mHasOcclusionSupport )	// Make it fail silently if hardware occlusion isn't supported
 	{
-		//glGetQueryObjectuivARB_ptr(mQueryID, GL_QUERY_RESULT_ARB, NumOfFragments);
+#ifdef GTP_VISIBILITY_USE_ARB_QUERIES
+		glGetQueryObjectuivARB_ptr(mQueryID, GL_QUERY_RESULT_ARB, NumOfFragments);
+#else
 glGetOcclusionQueryuivNV_ptr(mQueryID, GL_PIXEL_COUNT_NV, NumOfFragments);
+#endif
 	}
 	else
Index: trunk/VUT/work/ogre_changes/RenderSystems/GL/src/OgreGLRenderSystem.cpp
===================================================================
--- trunk/VUT/work/ogre_changes/RenderSystems/GL/src/OgreGLRenderSystem.cpp	(revision 150)
+++ trunk/VUT/work/ogre_changes/RenderSystems/GL/src/OgreGLRenderSystem.cpp	(revision 193)
@@ -149,5 +149,5 @@
 
     GLRenderSystem::GLRenderSystem()
-      : mExternalWindowHandle(0), mDepthWrite(true), mHardwareBufferManager(0),
+      : mDepthWrite(true), mHardwareBufferManager(0),
         mGpuProgramManager(0)
     {
@@ -173,5 +173,6 @@
         for (i = 0; i < OGRE_MAX_TEXTURE_COORD_SETS; i++)
         {
-            mTextureCoordIndex[i] = 0;
+			// Dummy value
+            mTextureCoordIndex[i] = 99;
         }
 
@@ -334,6 +335,18 @@
             GLint units;
             glGetIntegerv( GL_MAX_TEXTURE_UNITS, &units );
+			mFixedFunctionTextureUnits = units;
+
+			if (mGLSupport->checkExtension("GL_ARB_fragment_program"))
+			{
+				// Also check GL_MAX_TEXTURE_IMAGE_UNITS_ARB since NV at least
+				// only increased this on the FX/6x00 series
+				GLint arbUnits;
+				glGetIntegerv( GL_MAX_TEXTURE_IMAGE_UNITS_ARB, &arbUnits );
+				if (arbUnits > units)
+					units = arbUnits;
+			}
 
             mCapabilities->setNumTextureUnits(units);
+
         }
         else
@@ -405,4 +418,17 @@
             mGpuProgramManager->_pushSyntaxCode("arbvp1");
             mGpuProgramManager->registerProgramFactory("arbvp1", createGLArbGpuProgram);
+			if (mGLSupport->checkExtension("GL_NV_vertex_program2_option"))
+			{
+				mCapabilities->setMaxVertexProgramVersion("vp30");
+				mGpuProgramManager->_pushSyntaxCode("vp30");
+				mGpuProgramManager->registerProgramFactory("vp30", createGLArbGpuProgram);
+			}
+
+			if (mGLSupport->checkExtension("GL_NV_vertex_program3"))
+			{
+				mCapabilities->setMaxVertexProgramVersion("vp40");
+				mGpuProgramManager->_pushSyntaxCode("vp40");
+				mGpuProgramManager->registerProgramFactory("vp40", createGLArbGpuProgram);
+			}
         }
 
@@ -455,4 +481,17 @@
             mGpuProgramManager->_pushSyntaxCode("arbfp1");
             mGpuProgramManager->registerProgramFactory("arbfp1", createGLArbGpuProgram);
+			if (mGLSupport->checkExtension("GL_NV_fragment_program_option"))
+			{
+				mCapabilities->setMaxFragmentProgramVersion("fp30");
+				mGpuProgramManager->_pushSyntaxCode("fp30");
+				mGpuProgramManager->registerProgramFactory("fp30", createGLArbGpuProgram);
+			}
+
+			if (mGLSupport->checkExtension("GL_NV_fragment_program2"))
+			{
+				mCapabilities->setMaxFragmentProgramVersion("fp40");
+				mGpuProgramManager->_pushSyntaxCode("fp40");
+				mGpuProgramManager->registerProgramFactory("fp40", createGLArbGpuProgram);
+			}        
         }
 
@@ -911,10 +950,7 @@
 
         GLfloat mat[16];
-        makeGLMatrix(mat, mViewMatrix);
+		makeGLMatrix( mat, mViewMatrix * mWorldMatrix );
         glMatrixMode(GL_MODELVIEW);
         glLoadMatrixf(mat);
-
-        makeGLMatrix(mat, mWorldMatrix);
-        glMultMatrixf(mat);
 
         setGLClipPlanes();
@@ -1025,13 +1061,23 @@
             if(lastTextureType != mTextureTypes[stage] && lastTextureType != 0)
             {
+				if (stage < mFixedFunctionTextureUnits)
+				{
                 glDisable( lastTextureType );
             }
-
+            }
+
+			if (stage < mFixedFunctionTextureUnits)
+			{
 			glEnable( mTextureTypes[stage] );
+			}
+
 			if(!tex.isNull())
 				glBindTexture( mTextureTypes[stage], tex->getGLID() );
+
         }
         else
         {
+			if (stage < mFixedFunctionTextureUnits)
+			{
             if (lastTextureType != 0)
             {
@@ -1040,6 +1086,8 @@
 			glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
         }
+        }
 
         glActiveTextureARB_ptr( GL_TEXTURE0 );
+
     }
 
@@ -1053,4 +1101,11 @@
         const Frustum* frustum)
     {
+		if (stage >= mFixedFunctionTextureUnits)
+		{
+			// Can't do this
+			return;
+		}
+
+		
         GLfloat M[16];
         Matrix4 projectionBias;
@@ -1209,4 +1264,10 @@
     void GLRenderSystem::_setTextureMatrix(size_t stage, const Matrix4& xform)
     {
+		if (stage >= mFixedFunctionTextureUnits)
+		{
+			// Can't do this
+			return;
+		}
+
         GLfloat mat[16];
         makeGLMatrix(mat, xform);
@@ -1286,13 +1347,26 @@
         GLint sourceBlend = getBlendMode(sourceFactor);
         GLint destBlend = getBlendMode(destFactor);
-        
+        if(sourceFactor == SBF_ONE && destFactor == SBF_ZERO)
+        {
+            glDisable(GL_BLEND);
+        }
+        else
+        {
         glEnable(GL_BLEND);
         glBlendFunc(sourceBlend, destBlend);
     }
+    }
     //-----------------------------------------------------------------------------
     void GLRenderSystem::_setAlphaRejectSettings(CompareFunction func, unsigned char value)
     {
+        if(func == CMPF_ALWAYS_PASS)
+        {
+            glDisable(GL_ALPHA_TEST);
+        }
+        else
+        {
         glEnable(GL_ALPHA_TEST);
         glAlphaFunc(convertCompareFunction(func), value / 255.0f);
+    }
     }
     //-----------------------------------------------------------------------------
@@ -1345,10 +1419,9 @@
                 "GLRenderSystem::_beginFrame");
 
+        // Activate the viewport clipping
+        glEnable(GL_SCISSOR_TEST);
         // Clear the viewport if required
         if (mActiveViewport->getClearEveryFrame())
         {
-            // Activate the viewport clipping
-            glEnable(GL_SCISSOR_TEST);
-
             clearFrameBuffer(FBT_COLOUR | FBT_DEPTH, 
                 mActiveViewport->getBackgroundColour());
@@ -1839,4 +1912,10 @@
     void GLRenderSystem::_setTextureBlendMode(size_t stage, const LayerBlendModeEx& bm)
     {       
+		if (stage >= mFixedFunctionTextureUnits)
+		{
+			// Can't do this
+			return;
+		}
+
         // Check to see if blending is supported
         if(!mCapabilities->hasCapability(RSC_BLENDING))
@@ -2095,4 +2174,8 @@
             {
                 pBufferData = static_cast<const GLDefaultHardwareVertexBuffer*>(vertexBuffer.get())->getDataPtr(elem->getOffset());
+            }
+            if (op.vertexData->vertexStart)
+            {
+                pBufferData = static_cast<char*>(pBufferData) + op.vertexData->vertexStart * vertexBuffer->getVertexSize();
             }
 
@@ -2132,5 +2215,5 @@
             case VES_TEXTURE_COORDINATES:
 
-                for (i = 0; i < mCapabilities->getNumTextureUnits(); i++)
+                for (i = 0; i < OGRE_MAX_TEXTURE_COORD_SETS; i++)
                 {
 					// Only set this texture unit's texcoord pointer if it
@@ -2227,10 +2310,9 @@
         else
         {
-            glDrawArrays(primType, op.vertexData->vertexStart,
-                op.vertexData->vertexCount);
+            glDrawArrays(primType, 0, op.vertexData->vertexCount);
         }
 
         glDisableClientState( GL_VERTEX_ARRAY );
-        for (int i = 0; i < mCapabilities->getNumTextureUnits(); i++)
+        for (int i = 0; i < OGRE_MAX_TEXTURE_COORD_SETS; i++)
         {
             glClientActiveTextureARB_ptr(GL_TEXTURE0 + i);
@@ -2451,4 +2533,5 @@
         dest[3][2] = -1;
     }
+
     // ------------------------------------------------------------------
     void GLRenderSystem::setClipPlane (ushort index, Real A, Real B, Real C, Real D)
@@ -2496,16 +2579,4 @@
     }
  	//---------------------------------------------------------------------
- 	void GLRenderSystem::resizeRepositionWindow(void* wich)
- 	{
- 		mGLSupport->resizeRepositionWindow(wich);
- 		for (RenderTargetMap::iterator it = mRenderTargets.begin(); it != mRenderTargets.end(); ++it)		
- 		{
- 			if (it->second->isActive())
- 			{
- 				mGLSupport->resizeReposition(it->second);
- 			}
- 		}
- 	}
-    //---------------------------------------------------------------------
     void GLRenderSystem::_applyObliqueDepthProjection(Matrix4& matrix, const Plane& plane, 
         bool forGpuProgram)
@@ -2541,4 +2612,5 @@
         glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, 1);        
         glEnable(GL_COLOR_SUM);
+        glDisable(GL_DITHER);
 
         // Check for FSAA
Index: trunk/VUT/work/ogre_changes/RenderSystems/GL/src/OgreWin32Window.cpp
===================================================================
--- trunk/VUT/work/ogre_changes/RenderSystems/GL/src/OgreWin32Window.cpp	(revision 156)
+++ trunk/VUT/work/ogre_changes/RenderSystems/GL/src/OgreWin32Window.cpp	(revision 193)
@@ -42,7 +42,9 @@
 		mIsFullScreen = false;
 		mHWnd = 0;
+		mIsExternal = false;
+		mSizing = false;
+		mClosed = false;
+		mDisplayFrequency = 0;
 		mActive = false;
-		mReady = false;
-		mClosed = false;
     }
 
@@ -55,15 +57,29 @@
 	            bool fullScreen, const NameValuePairList *miscParams)
     {
-        HWND parentHWnd = 0;
-		HWND externalHandle = 0;
+		// destroy current window, if any
+		if (mHWnd)
+			destroy();
+
 		HINSTANCE hInst = GetModuleHandle("RenderSystem_GL.dll");
+
+		mHWnd = 0;
+		mName = name;
+		mIsFullScreen = fullScreen;
+		mClosed = false;
+
+		// load window defaults
+		mLeft = mTop = -1; // centered
+		mWidth = width;
+		mHeight = height;
+		mDisplayFrequency = 0;
+		mIsDepthBuffered = true;
+		mColourDepth = mIsFullScreen? 32 : GetDeviceCaps(GetDC(0), BITSPIXEL);
+
+		HWND parent = 0;
+		String title = name;
 		bool vsync = false;
-		unsigned int displayFrequency = 0;
-		String title = name;
-		unsigned int colourDepth = 32;
-		unsigned int left = 0; // Defaults to screen center
-		unsigned int top = 0; // Defaults to screen center
-		bool depthBuffer = true;
-		int multisample = 0;
+		int fsaa = 0;
+		String border = "";
+		bool outerSize = false;
 
 		if(miscParams)
@@ -71,187 +87,172 @@
 			// Get variable-length params
 			NameValuePairList::const_iterator opt;
-			// left (x)
-			opt = miscParams->find("left");
+			NameValuePairList::const_iterator end = miscParams->end();
+
+			if ((opt = miscParams->find("title")) != end)
+				title = opt->second;
+
+			if ((opt = miscParams->find("left")) != end)
+				mLeft = StringConverter::parseInt(opt->second);
+
+			if ((opt = miscParams->find("top")) != end)
+				mTop = StringConverter::parseInt(opt->second);
+
+			if ((opt = miscParams->find("depthBuffer")) != end)
+				mIsDepthBuffered = StringConverter::parseBool(opt->second);
+
+			if ((opt = miscParams->find("vsync")) != end)
+				vsync = StringConverter::parseBool(opt->second);
+
+			if ((opt = miscParams->find("FSAA")) != end)
+				fsaa = StringConverter::parseUnsignedInt(opt->second);
+
+			if ((opt = miscParams->find("externalWindowHandle")) != end)
+			{
+				mHWnd = (HWND)StringConverter::parseUnsignedInt(opt->second);
+				if (mHWnd)
+				{
+					mIsExternal = true;
+					mIsFullScreen = false;
+				}
+			}
+			// window border style
+			opt = miscParams->find("border");
 			if(opt != miscParams->end())
-				left = StringConverter::parseUnsignedInt(opt->second);
-			// top (y)
-			opt = miscParams->find("top");
+				border = opt->second;
+			// set outer dimensions?
+			opt = miscParams->find("outerDimensions");
 			if(opt != miscParams->end())
-				top = StringConverter::parseUnsignedInt(opt->second);
-			// Window title
-			opt = miscParams->find("title");
-			if(opt != miscParams->end())
-				title = opt->second;
-			// externalWindowHandle		-> externalHandle
-			opt = miscParams->find("externalWindowHandle");
-			if(opt != miscParams->end())
-				externalHandle = (HWND)StringConverter::parseUnsignedInt(opt->second);
-			// parentWindowHandle -> parentHWnd
-			opt = miscParams->find("parentWindowHandle");
-			if(opt != miscParams->end()) 
-				parentHWnd = (HWND)StringConverter::parseUnsignedInt(opt->second);
-			// vsync	[parseBool]
-			opt = miscParams->find("vsync");
-			if(opt != miscParams->end())
-				vsync = StringConverter::parseBool(opt->second);
-			// displayFrequency
-			opt = miscParams->find("displayFrequency");
-			if(opt != miscParams->end())
-				displayFrequency = StringConverter::parseUnsignedInt(opt->second);
-			// colourDepth
-			opt = miscParams->find("colourDepth");
-			if(opt != miscParams->end())
-				colourDepth = StringConverter::parseUnsignedInt(opt->second);
-			// depthBuffer [parseBool]
-			opt = miscParams->find("depthBuffer");
-			if(opt != miscParams->end())
-				depthBuffer = StringConverter::parseBool(opt->second);
-			// FSAA
-			opt = miscParams->find("FSAA");
-			if(opt != miscParams->end())
-				multisample = StringConverter::parseUnsignedInt(opt->second);
-		}
+				outerSize = StringConverter::parseBool(opt->second);
 		
-		// Destroy current window if any
-		if( mHWnd )
-			destroy();
-
-        if (fullScreen)
+			if (mIsFullScreen)
         {
-			mColourDepth = colourDepth;
+				// only available with fullscreen
+				if ((opt = miscParams->find("displayFrequency")) != end)
+					mDisplayFrequency = StringConverter::parseUnsignedInt(opt->second);
+				if ((opt = miscParams->find("colourDepth")) != end)
+					mColourDepth = StringConverter::parseUnsignedInt(opt->second);
         }
 		else 
 		{
-			// Get colour depth from display
-			mColourDepth = GetDeviceCaps(GetDC(0), BITSPIXEL);
-		}
-
-		if (!externalHandle) {
-			DWORD dwStyle = (fullScreen ? WS_POPUP : WS_OVERLAPPEDWINDOW) | WS_CLIPCHILDREN | WS_CLIPSIBLINGS;
-			RECT rc;
-
-			mWidth = width;
-			mHeight = height;
-
-			if (!fullScreen)
+				// incompatible with fullscreen
+				if ((opt = miscParams->find("parentWindowHandle")) != end)
+					parent = (HWND)StringConverter::parseUnsignedInt(opt->second);
+			}
+		}
+
+		if (!mIsExternal)
 			{
-				// Calculate window dimensions required to get the requested client area
-				SetRect(&rc, 0, 0, mWidth, mHeight);
-				AdjustWindowRect(&rc, dwStyle, false);
-				mWidth = rc.right - rc.left;
-				mHeight = rc.bottom - rc.top;
-
-				// Clamp width and height to the desktop dimensions
-				if (mWidth > (unsigned)GetSystemMetrics(SM_CXSCREEN))
-					mWidth = (unsigned)GetSystemMetrics(SM_CXSCREEN);
-				if (mHeight > (unsigned)GetSystemMetrics(SM_CYSCREEN))
-					mHeight = (unsigned)GetSystemMetrics(SM_CYSCREEN);
-
-				if (!left)
+			DWORD dwStyle = WS_VISIBLE | WS_CLIPCHILDREN | WS_CLIPSIBLINGS;
+			DWORD dwStyleEx = 0;
+			int outerw, outerh;
+
+			if (mIsFullScreen)
                 {
-					mLeft = (GetSystemMetrics(SM_CXSCREEN) / 2) - (mWidth / 2);
+				dwStyle |= WS_POPUP;
+				dwStyleEx |= WS_EX_TOPMOST;
+				outerw = mWidth;
+				outerh = mHeight;
+				mLeft = mTop = 0;
                 }
 				else
                 {
-					mLeft = left;
-                }
-				if (!top)
+				if (border == "none")
+					dwStyle |= WS_POPUP;
+				else if (border == "fixed")
+					dwStyle |= WS_OVERLAPPED | WS_BORDER | WS_CAPTION |
+					WS_SYSMENU | WS_MINIMIZEBOX;
+				else
+					dwStyle |= WS_OVERLAPPEDWINDOW;
+
+				int screenw = GetSystemMetrics(SM_CXSCREEN);
+				int screenh = GetSystemMetrics(SM_CYSCREEN);
+
+				if (!outerSize)
                 {
-					mTop = (GetSystemMetrics(SM_CYSCREEN) / 2) - (mHeight / 2);
-                }
-				else
-                {
-                    mTop = top;
-                }
+					// calculate overall dimensions for requested client area
+					RECT rc = { 0, 0, mWidth, mHeight };
+					AdjustWindowRect(&rc, dwStyle, false);
+
+					// clamp window dimensions to screen size
+					outerw = (rc.right-rc.left < screenw)? rc.right-rc.left : screenw;
+					outerh = (rc.bottom-rc.top < screenh)? rc.bottom-rc.top : screenh;
+            }
+
+				// center window if given negative coordinates
+				if (mLeft < 0)
+					mLeft = (screenw - outerw) / 2;
+				if (mTop < 0)
+					mTop = (screenh - outerh) / 2;
+
+				// keep window contained in visible screen area
+				if (mLeft > screenw - outerw)
+					mLeft = screenw - outerw;
+				if (mTop > screenh - outerh)
+					mTop = screenh - outerh;
 			}
-			else
-            {
-				mTop = mLeft = 0;
-            }
-
-			// Register the window class
-
-			WNDCLASS wndClass = { CS_HREDRAW | CS_VREDRAW | CS_OWNDC,
-				WndProc, 0, 4, hInst,
-				LoadIcon( NULL, IDI_APPLICATION ),
-				LoadCursor( NULL, IDC_ARROW ),
-				(HBRUSH)GetStockObject( BLACK_BRUSH ), NULL,
-				TEXT(title.c_str()) };
-			RegisterClass( &wndClass );
-
-			// Create our main window
-			// Pass pointer to self
-			HWND hWnd = CreateWindowEx(fullScreen?WS_EX_TOPMOST:0, TEXT(title.c_str()), TEXT(title.c_str()),
-				dwStyle, mLeft, mTop, mWidth, mHeight, 0L, 0L, hInst, this);
-			mHWnd = hWnd;
-
-			GetClientRect(mHWnd,&rc);
-			mWidth = rc.right;
-			mHeight = rc.bottom;
-
-            if (fullScreen) {
-			    DEVMODE DevMode;
-			    DevMode.dmSize = sizeof(DevMode);
-			    DevMode.dmBitsPerPel = mColourDepth;
-			    DevMode.dmPelsWidth = mWidth;
-			    DevMode.dmPelsHeight = mHeight;
-			    DevMode.dmDisplayFrequency = displayFrequency;
-			    DevMode.dmFields = DM_BITSPERPEL|DM_PELSWIDTH|DM_PELSHEIGHT|DM_DISPLAYFREQUENCY;
-			    if (ChangeDisplaySettings(&DevMode, CDS_FULLSCREEN) != DISP_CHANGE_SUCCESSFUL)
-				    LogManager::getSingleton().logMessage(LML_CRITICAL, "ChangeDisplaySettingsEx");
-
+
+			// register class and create window
+			WNDCLASS wc = { CS_OWNDC, WndProc, 0, 0, hInst,
+				LoadIcon(NULL, IDI_APPLICATION), LoadCursor(NULL, IDC_ARROW),
+				(HBRUSH)GetStockObject(BLACK_BRUSH), NULL, "OgreGLWindow" };
+			RegisterClass(&wc);
+
+			// Pass pointer to self as WM_CREATE parameter
+			mHWnd = CreateWindowEx(dwStyleEx, "OgreGLWindow", title.c_str(),
+				dwStyle, mLeft, mTop, outerw, outerh, parent, 0, hInst, this);
+
+			StringUtil::StrStreamType str;
+			str << "Created Win32Window '"
+				<< mName << "' : " << mWidth << "x" << mHeight
+				<< ", " << mColourDepth << "bpp";
+			LogManager::getSingleton().logMessage(LML_NORMAL, str.str());
+
+			if (mIsFullScreen)
+			{
+				DEVMODE dm;
+				dm.dmSize = sizeof(DEVMODE);
+				dm.dmBitsPerPel = mColourDepth;
+				dm.dmPelsWidth = mWidth;
+				dm.dmPelsHeight = mHeight;
+				dm.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;
+				if (mDisplayFrequency)
+				{
+					dm.dmDisplayFrequency = mDisplayFrequency;
+					dm.dmFields |= DM_DISPLAYFREQUENCY;
+				}
+				if (ChangeDisplaySettings(&dm, CDS_FULLSCREEN) != DISP_CHANGE_SUCCESSFUL)
+					LogManager::getSingleton().logMessage(LML_CRITICAL, "ChangeDisplaySettings failed");
+			}
 		    }
 
-		}
-		else {
-			mHWnd = externalHandle;
 			RECT rc;
+		// top and left represent outer window position
+		GetWindowRect(mHWnd, &rc);
+		mTop = rc.top;
+		mLeft = rc.left;
+		// width and height represent drawable area only
 			GetClientRect(mHWnd, &rc);
 			mWidth = rc.right;
 			mHeight = rc.bottom;
-			mLeft = rc.left;
-			mTop = rc.top;
-		}
-		ShowWindow(mHWnd, SW_SHOWNORMAL);
-		UpdateWindow(mHWnd);
-		mName = name;
-		mIsDepthBuffered = depthBuffer;
-		mIsFullScreen = fullScreen;
-
 		
-		HDC hdc = GetDC(mHWnd);
-
-        StringUtil::StrStreamType str;
-        str << "Created Win32Window '"
-            << mName << "' : " << mWidth << "x" << mHeight
-            << ", " << mColourDepth << "bpp";
-        LogManager::getSingleton().logMessage(LML_NORMAL, str.str());
-
-		if (!mGLSupport.selectPixelFormat(hdc, mColourDepth, multisample))
-		{
-			if (multisample == 0)
+		mHDC = GetDC(mHWnd);
+
+		if (!mGLSupport.selectPixelFormat(mHDC, mColourDepth, fsaa))
+		{
+			if (fsaa == 0)
 				OGRE_EXCEPT(0, "selectPixelFormat failed", "Win32Window::create");
 
 			LogManager::getSingleton().logMessage(LML_NORMAL, "FSAA level not supported, falling back");
-			if (!mGLSupport.selectPixelFormat(hdc, mColourDepth, 0))
+			if (!mGLSupport.selectPixelFormat(mHDC, mColourDepth, 0))
 				OGRE_EXCEPT(0, "selectPixelFormat failed", "Win32Window::create");
 		}
 
-		HGLRC glrc = wglCreateContext(hdc);
-		if (!glrc)
+		mGlrc = wglCreateContext(mHDC);
+		if (!mGlrc)
 			OGRE_EXCEPT(0, "wglCreateContext", "Win32Window::create");
-		if (!wglMakeCurrent(hdc, glrc))
+		if (!wglMakeCurrent(mHDC, mGlrc))
 			OGRE_EXCEPT(0, "wglMakeCurrent", "Win32Window::create");
 		
-		mGlrc = glrc;
-		mHDC = hdc;
-
-		mOldSwapIntervall = wglGetSwapIntervalEXT();
-		if (vsync) 
-			wglSwapIntervalEXT(1);
-		else
-			wglSwapIntervalEXT(0);
-
-		mReady = true;
+		wglSwapIntervalEXT(vsync? 1 : 0);
 
         // Create RenderSystem context
@@ -260,8 +261,13 @@
         GLRenderSystem *rs = static_cast<GLRenderSystem*>(Root::getSingleton().getRenderSystem());
         rs->_registerContext(this, mContext);
+
+		mActive = true;
     }
 
     void Win32Window::destroy(void)
     {
+		if (!mHWnd)
+			return;
+
         // Unregister and destroy OGRE GLContext
         if (mContext)
@@ -270,32 +276,25 @@
             rs->_unregisterContext(this);
             delete mContext;
-            mContext = NULL;
-
-            wglSwapIntervalEXT(mOldSwapIntervall);
+			mContext = 0;
         }
-		if (mGlrc) {
-			wglMakeCurrent(NULL, NULL);
+		if (mGlrc)
+		{
 			wglDeleteContext(mGlrc);
-			mGlrc = NULL;
-		}
-		if (mHDC) {
-			ReleaseDC(mHWnd, mHDC);
-			mHDC = NULL;
-		}
+			mGlrc = 0;
+		}
+		if (!mIsExternal)
+		{
 		if (mIsFullScreen)
-		{
 			ChangeDisplaySettings(NULL, 0);
-		}
-        if (mHWnd)
-        {
 	        DestroyWindow(mHWnd);
-            mHWnd = 0;
         }
         mActive = false;
-    }
-
-    bool Win32Window::isActive() const
-    {
-        return mActive;
+		mHDC = 0; // no release thanks to CS_OWNDC wndclass style
+		mHWnd = 0;
+    }
+
+	bool Win32Window::isVisible() const
+    {
+		return (mHWnd && !IsIconic(mHWnd));
     }
 
@@ -307,12 +306,42 @@
     void Win32Window::reposition(int left, int top)
     {
-        // XXX FIXME
+		if (mHWnd && !mIsFullScreen)
+		{
+			SetWindowPos(mHWnd, 0, left, top, 0, 0,
+				SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE);
+		}
     }
 
     void Win32Window::resize(unsigned int width, unsigned int height)
     {
-
-		mWidth = width;
-		mHeight = height;
+		if (mHWnd && !mIsFullScreen)
+		{
+			RECT rc = { 0, 0, width, height };
+			AdjustWindowRect(&rc, GetWindowLong(mHWnd, GWL_STYLE), false);
+			width = rc.right - rc.left;
+			height = rc.bottom - rc.top;
+			SetWindowPos(mHWnd, 0, 0, 0, width, height,
+				SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE);
+		}
+	}
+
+	void Win32Window::windowMovedOrResized()
+	{
+		if (!isVisible())
+			return;
+
+		RECT rc;
+		// top and left represent outer window position
+		GetWindowRect(mHWnd, &rc);
+		mTop = rc.top;
+		mLeft = rc.left;
+		// width and height represent drawable area only
+		GetClientRect(mHWnd, &rc);
+
+		if (mWidth == rc.right && mHeight == rc.bottom)
+			return;
+
+		mWidth = rc.right;
+		mHeight = rc.bottom;
 
 		// Notify viewports of resize
@@ -321,13 +350,4 @@
 		for( it = mViewportList.begin(); it != itend; ++it )
 			(*it).second->_updateDimensions();
-		// TODO - resize window
-    }
-
-	void Win32Window::windowMovedOrResized()
-	{
-		RECT temprect;
-		::GetClientRect(getWindowHandle(),&temprect);
-		resize(temprect.right-temprect.left,temprect.bottom-temprect.top);
-		// TODO
 	}
 
@@ -406,66 +426,64 @@
 	LRESULT Win32Window::WndProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam )
 	{
-		Win32Window* win;
+
+		if (uMsg == WM_CREATE)
+		{
+			// Store pointer to Win32Window in user data area
+			SetWindowLong(hWnd, GWL_USERDATA,
+				(LONG)(((LPCREATESTRUCT)lParam)->lpCreateParams));
+			return 0;
+		}
 
 		// look up window instance
-		if( WM_CREATE != uMsg )
-			win = (Win32Window*)GetWindowLong( hWnd, 0 );
+		// note: it is possible to get a WM_SIZE before WM_CREATE
+		Win32Window* win = (Win32Window*)GetWindowLong(hWnd, GWL_USERDATA);
+		if (!win)
+			return DefWindowProc(hWnd, uMsg, wParam, lParam);
 
 		switch( uMsg )
 		{
 		case WM_ACTIVATE:
-			if( WA_INACTIVE == LOWORD( wParam ) )
+			if (win->mIsFullScreen)
+			{
+				if (LOWORD(wParam) == WA_INACTIVE)
+				{
 				win->mActive = false;
+					ChangeDisplaySettings(NULL, 0);
+					ShowWindow(hWnd, SW_SHOWMINNOACTIVE);
+				}
 			else
+				{
 				win->mActive = true;
+					ShowWindow(hWnd, SW_SHOWNORMAL);
+
+					DEVMODE dm;
+					dm.dmSize = sizeof(DEVMODE);
+					dm.dmBitsPerPel = win->mColourDepth;
+					dm.dmPelsWidth = win->mWidth;
+					dm.dmPelsHeight = win->mHeight;
+					dm.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;
+					if (win->mDisplayFrequency)
+					{
+						dm.dmDisplayFrequency = win->mDisplayFrequency;
+						dm.dmFields |= DM_DISPLAYFREQUENCY;
+					}
+					ChangeDisplaySettings(&dm, CDS_FULLSCREEN);
+				}
+			}
 			break;
 
-		case WM_CREATE: {
-			// Log the new window
-			// Get CREATESTRUCT
-			LPCREATESTRUCT lpcs = (LPCREATESTRUCT)lParam;
-			win = (Win32Window*)(lpcs->lpCreateParams);
-			// Store pointer in window user data area
-			SetWindowLong( hWnd, 0, (long)win );
-			win->mActive = true;
-
-			return 0; }
-			break;
-
-		case WM_PAINT:
-			// If we get WM_PAINT messges, it usually means our window was
-			// comvered up, so we need to refresh it by re-showing the contents
-			// of the current frame.
-			if( win->mActive && win->mReady )
-				win->update();
-			break;
-
-		case WM_MOVE:
-			// Move messages need to be tracked to update the screen rects
-			// used for blitting the backbuffer to the primary
-			// *** This doesn't need to be used to Direct3D9 ***
-			break;
-
 		case WM_ENTERSIZEMOVE:
-			// Previent rendering while moving / sizing
-			win->mReady = false;
+			win->mSizing = true;
 			break;
 
 		case WM_EXITSIZEMOVE:
 			win->windowMovedOrResized();
-			win->mReady = true;
+			win->mSizing = false;
 			break;
 
+		case WM_MOVE:
 		case WM_SIZE:
-			// Check to see if we are losing or gaining our window.  Set the 
-			// active flag to match
-			if( SIZE_MAXHIDE == wParam || SIZE_MINIMIZED == wParam )
-				win->mActive = false;
-			else
-			{
-				win->mActive = true;
-				if( win->mReady )
+			if (!win->mSizing)
 					win->windowMovedOrResized();
-			}
 			break;
 
@@ -477,5 +495,5 @@
 
 		case WM_CLOSE:
-			DestroyWindow( win->mHWnd );
+			win->destroy(); // will call DestroyWindow
 			win->mClosed = true;
 			return 0;
Index: trunk/VUT/work/ogre_changes/RenderSystems/Direct3D9/include/OgreD3D9Texture.h
===================================================================
--- trunk/VUT/work/ogre_changes/RenderSystems/Direct3D9/include/OgreD3D9Texture.h	(revision 154)
+++ trunk/VUT/work/ogre_changes/RenderSystems/Direct3D9/include/OgreD3D9Texture.h	(revision 193)
@@ -161,8 +161,8 @@
 		static PixelFormat _getClosestSupportedPF(PixelFormat ogrePF);
 
-		/// For dealing with lost devices - release the resource if in the default pool
-		void releaseIfDefaultPool(void);
-		/// For dealing with lost devices - recreate the resource if in the default pool
-		void recreateIfDefaultPool(LPDIRECT3DDEVICE9 pDev);
+		/// For dealing with lost devices - release the resource if in the default pool (and return true)
+		bool releaseIfDefaultPool(void);
+		/// For dealing with lost devices - recreate the resource if in the default pool (and return true)
+		bool recreateIfDefaultPool(LPDIRECT3DDEVICE9 pDev);
 
     };
@@ -243,4 +243,5 @@
                 (mName + "_PRIVATE##", ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, 
                 texType, mWidth, mHeight, 0, internalFormat, TU_RENDERTARGET );
+			mPrivateTex->load();
         }
 		
Index: trunk/VUT/work/ogre_changes/RenderSystems/Direct3D9/include/OgreD3D9RenderWindow.h
===================================================================
--- trunk/VUT/work/ogre_changes/RenderSystems/Direct3D9/include/OgreD3D9RenderWindow.h	(revision 153)
+++ trunk/VUT/work/ogre_changes/RenderSystems/Direct3D9/include/OgreD3D9RenderWindow.h	(revision 193)
@@ -46,7 +46,7 @@
 	            bool fullScreen, const NameValuePairList *miscParams);
 		void destroy(void);
-		bool isActive() const { return mActive; }
+		bool isVisible() const;
 		bool isClosed() const { return mClosed; }
-		void reposition( int left, int top ) {}
+		void reposition(int left, int top);
 		void resize( unsigned int width, unsigned int height );
 		void swapBuffers( bool waitForVSync = true );
@@ -61,26 +61,26 @@
 		*/
 		void writeContentsToFile(const String& filename);
+		bool requiresTextureFlipping() const { return false; }
 
+		// Method for dealing with resize / move & 3d library
+		void windowMovedOrResized();
 #ifdef GTP_VISIBILITY_MODIFIED_OGRE
 		uchar *getBufferContents(int &dimx, int &dimy);
 #endif // GTP_VISIBILITY_MODIFIED_OGRE
 
-		bool requiresTextureFlipping() const { return false; }
-
-		// Method for dealing with resize / move & 3d library
-		virtual void WindowMovedOrResized(void);
-
-		bool isReady() const { return mReady; }
-		void setReady(bool set) { mReady = set; }
-		void setActive(bool set) { mActive = set; }
 		/// Get the presentation parameters used with this window
 		D3DPRESENT_PARAMETERS* getPresentationParameters(void) 
 		{ return &md3dpp; }
+
 		/// @copydoc RenderTarget::update
-		void update(void);
+		void update();
 
 		/** Create (or recreate) the D3D device or SwapChain for this window.
 		*/
-		void createD3DResources(void);
+		void createD3DResources();
+	
+		/** Destroy the D3D device or SwapChain for this window.
+		*/
+		void destroyD3DResources();
 	
 	protected:
@@ -88,6 +88,6 @@
 		D3D9Driver *mDriver;			// D3D9 driver
 		HWND	mHWnd;					// Win32 Window handle
-		bool	mActive;				// Is active i.e. visible
-		bool	mReady;					// Is ready i.e. available for update
+		bool	mIsExternal;			// window not created by Ogre
+		bool	mSizing;
 		bool	mClosed;
 		bool	mIsSwapChain;			// Is this a secondary window?
Index: trunk/VUT/work/ogre_changes/RenderSystems/Direct3D9/src/OgreD3D9HardwareOcclusionQuery.cpp
===================================================================
--- trunk/VUT/work/ogre_changes/RenderSystems/Direct3D9/src/OgreD3D9HardwareOcclusionQuery.cpp	(revision 115)
+++ trunk/VUT/work/ogre_changes/RenderSystems/Direct3D9/src/OgreD3D9HardwareOcclusionQuery.cpp	(revision 193)
@@ -87,6 +87,4 @@
 				mSkipCounter = 0; 
 }
-			//std::stringstream d; d << "count: " << mSkipCounter;
-			//LogManager::getSingleton().logMessage(d.str());
 			if (mSkipCounter == 0)
 		{
Index: trunk/VUT/work/ogre_changes/RenderSystems/Direct3D9/src/OgreD3D9RenderWindow.cpp
===================================================================
--- trunk/VUT/work/ogre_changes/RenderSystems/Direct3D9/src/OgreD3D9RenderWindow.cpp	(revision 183)
+++ trunk/VUT/work/ogre_changes/RenderSystems/Direct3D9/src/OgreD3D9RenderWindow.cpp	(revision 193)
@@ -45,84 +45,37 @@
 	LRESULT D3D9RenderWindow::WndProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam )
 	{
-		LPCREATESTRUCT lpcs;
-		D3D9RenderWindow* win;
-
-		// look up window instance
-		if( WM_CREATE != uMsg )
-			// Get window pointer
-			win = (D3D9RenderWindow*)GetWindowLong( hWnd, 0 );
+		if (uMsg == WM_CREATE)
+		{
+			// copy D3D9RenderWindow* from createwindow param to userdata slot
+			SetWindowLong(hWnd, GWL_USERDATA,
+				(LONG)(((LPCREATESTRUCT)lParam)->lpCreateParams));
+			return 0;
+		}
+
+		D3D9RenderWindow* win =
+			(D3D9RenderWindow*)GetWindowLong(hWnd, GWL_USERDATA);
+
+		if (!win)
+			return DefWindowProc(hWnd, uMsg, wParam, lParam);
 
 		switch( uMsg )
 		{
 		case WM_ACTIVATE:
-			if( WA_INACTIVE == LOWORD( wParam ) )
-				win->mActive = false;
-			else
-				win->mActive = true;
+			win->mActive = (LOWORD(wParam) != WA_INACTIVE);
 			break;
 
-		case WM_CREATE:
-			// Log the new window
-			// Get CREATESTRUCT
-			lpcs = (LPCREATESTRUCT)lParam;
-			win = (D3D9RenderWindow*)(lpcs->lpCreateParams);
-			// Store pointer in window user data area
-			SetWindowLong( hWnd, 0, (long)win );
-			win->mActive = true;
-
-			return 0;
+		case WM_ENTERSIZEMOVE:
+			win->mSizing = true;
 			break;
 
-		case WM_KEYDOWN:
-			// TEMPORARY CODE
-			// TODO - queue up keydown / keyup events with
-			//  window name and timestamp to be processed
-			//  by main loop
-
-			// ESCAPE closes window
-			/*
-			if (wParam == VK_ESCAPE)
-			{
-			win->mClosed = true;
-			return 0L;
-			}
-			*/
+		case WM_EXITSIZEMOVE:
+			win->windowMovedOrResized();
+			win->mSizing = false;
 			break;
 
-		case WM_PAINT:
-			// If we get WM_PAINT messges, it usually means our window was
-			// comvered up, so we need to refresh it by re-showing the contents
-			// of the current frame.
-			if( win->mActive && win->mReady )
-				win->update();
-			break;
-
 		case WM_MOVE:
-			// Move messages need to be tracked to update the screen rects
-			// used for blitting the backbuffer to the primary
-			// *** This doesn't need to be used to Direct3D9 ***
-			break;
-
-		case WM_ENTERSIZEMOVE:
-			// Previent rendering while moving / sizing
-			win->mReady = false;
-			break;
-
-		case WM_EXITSIZEMOVE:
-			win->WindowMovedOrResized();
-			win->mReady = true;
-			break;
-
 		case WM_SIZE:
-			// Check to see if we are losing or gaining our window.  Set the 
-			// active flag to match
-			if( SIZE_MAXHIDE == wParam || SIZE_MINIMIZED == wParam )
-				win->mActive = false;
-			else
-			{
-				win->mActive = true;
-				if( win->mReady )
-					win->WindowMovedOrResized();
-			}
+			if (!win->mSizing)
+				win->windowMovedOrResized();
 			break;
 
@@ -134,5 +87,5 @@
 
 		case WM_CLOSE:
-			DestroyWindow( win->mHWnd );
+			win->destroy(); // cleanup and call DestroyWindow
 			win->mClosed = true;
 			return 0;
@@ -147,8 +100,9 @@
 	{
 		mIsFullScreen = false;
-		mIsSwapChain = deviceIfSwapChain != NULL;
+		mIsSwapChain = (deviceIfSwapChain != NULL);
+		mIsExternal = false;
 		mHWnd = 0;
 		mActive = false;
-		mReady = false;
+		mSizing = false;
 		mClosed = false;
 	}
@@ -161,5 +115,5 @@
 			LPDIRECT3DDEVICE9 mpD3DDevice = mDriver->getD3DDevice();
 			SAFE_RELEASE( mpD3DDevice );
-			mDriver->setD3DDevice( mpD3DDevice );
+			mDriver->setD3DDevice( NULL );
 		}
 	}
@@ -192,7 +146,9 @@
 		String title = name;
 		unsigned int colourDepth = 32;
-		unsigned int left = 0; // Defaults to screen center
-		unsigned int top = 0; // Defaults to screen center
+		int left = -1; // Defaults to screen center
+		int top = -1; // Defaults to screen center
 		bool depthBuffer = true;
+		String border = "";
+		bool outerSize = false;
 		
 		if(miscParams)
@@ -203,13 +159,17 @@
 			opt = miscParams->find("left");
 			if(opt != miscParams->end())
-				left = StringConverter::parseUnsignedInt(opt->second);
+				left = StringConverter::parseInt(opt->second);
 			// top (y)
 			opt = miscParams->find("top");
 			if(opt != miscParams->end())
-				top = StringConverter::parseUnsignedInt(opt->second);
+				top = StringConverter::parseInt(opt->second);
 			// Window title
 			opt = miscParams->find("title");
 			if(opt != miscParams->end())
 				title = opt->second;
+			// parentWindowHandle		-> parentHWnd
+			opt = miscParams->find("parentWindowHandle");
+			if(opt != miscParams->end())
+				parentHWnd = (HWND)StringConverter::parseUnsignedInt(opt->second);
 			// externalWindowHandle		-> externalHandle
 			opt = miscParams->find("externalWindowHandle");
@@ -240,4 +200,12 @@
 			if(opt != miscParams->end())
 				mFSAAQuality = StringConverter::parseUnsignedInt(opt->second);
+			// window border style
+			opt = miscParams->find("border");
+			if(opt != miscParams->end())
+				border = opt->second;
+			// set outer dimensions?
+			opt = miscParams->find("outerDimensions");
+			if(opt != miscParams->end())
+				outerSize = StringConverter::parseBool(opt->second);
 		}
 		
@@ -249,13 +217,33 @@
 		if (!externalHandle)
 		{
-			DWORD dwStyle = (fullScreen ? WS_POPUP : WS_OVERLAPPEDWINDOW) | WS_CLIPCHILDREN | WS_CLIPSIBLINGS;
+			DWORD dwStyle = WS_VISIBLE | WS_CLIPCHILDREN | WS_CLIPSIBLINGS;
 			RECT rc;
 
 			mWidth = width;
 			mHeight = height;
+			mTop = top;
+			mLeft = left;
 
 			if (!fullScreen)
 			{
-				// Calculate window dimensions required to get the requested client area
+				if (parentHWnd)
+				{
+					dwStyle |= WS_CHILD;
+				}
+				else
+				{
+					if (border == "none")
+						dwStyle |= WS_POPUP;
+					else if (border == "fixed")
+						dwStyle |= WS_OVERLAPPED | WS_BORDER | WS_CAPTION |
+						WS_SYSMENU | WS_MINIMIZEBOX;
+					else
+						dwStyle |= WS_OVERLAPPEDWINDOW;
+				}
+
+				if (!outerSize)
+				{
+					// Calculate window dimensions required
+					// to get the requested client area
 				SetRect(&rc, 0, 0, mWidth, mHeight);
 				AdjustWindowRect(&rc, dwStyle, false);
@@ -264,66 +252,54 @@
 
 				// Clamp width and height to the desktop dimensions
-				if (mWidth > (unsigned)GetSystemMetrics(SM_CXSCREEN))
-					mWidth = (unsigned)GetSystemMetrics(SM_CXSCREEN);
-				if (mHeight > (unsigned)GetSystemMetrics(SM_CYSCREEN))
-					mHeight = (unsigned)GetSystemMetrics(SM_CYSCREEN);
-
-				if (!left)
-					mLeft = (GetSystemMetrics(SM_CXSCREEN) / 2) - (mWidth / 2);
-				else
-					mLeft = left;
-				if (!top)
-					mTop = (GetSystemMetrics(SM_CYSCREEN) / 2) - (mHeight / 2);
-				else
-					mTop = top;
+					int screenw = GetSystemMetrics(SM_CXSCREEN);
+					int screenh = GetSystemMetrics(SM_CYSCREEN);
+					if ((int)mWidth > screenw)
+						mWidth = screenw;
+					if ((int)mHeight > screenh)
+						mHeight = screenh;
+					if (mLeft < 0)
+						mLeft = (screenw - mWidth) / 2;
+					if (mTop < 0)
+						mTop = (screenh - mHeight) / 2;
+				}
 			}
 			else
+			{
+				dwStyle |= WS_POPUP;
 				mTop = mLeft = 0;
+			}
 
 			// Register the window class
 			// NB allow 4 bytes of window data for D3D9RenderWindow pointer
-            WNDCLASS wndClass = { CS_HREDRAW | CS_VREDRAW, WndProc, 0, 4, hInst,
-				LoadIcon( NULL, IDI_APPLICATION ),
-				LoadCursor( NULL, IDC_ARROW ),
-				(HBRUSH)GetStockObject( BLACK_BRUSH ), NULL,
-				TEXT(title.c_str()) };
-			RegisterClass( &wndClass );
+			WNDCLASS wc = { 0, WndProc, 0, 0, hInst,
+				LoadIcon(0, IDI_APPLICATION), LoadCursor(NULL, IDC_ARROW),
+				(HBRUSH)GetStockObject(BLACK_BRUSH), 0, "OgreD3D9Wnd" };
+			RegisterClass(&wc);
 
 			// Create our main window
 			// Pass pointer to self
-			HWND hWnd = CreateWindow(TEXT(title.c_str()),
-									 TEXT(title.c_str()),
-									 dwStyle, mLeft, mTop,
-									 mWidth, mHeight, 0L, 0L, hInst, this);
-			GetClientRect(hWnd,&rc);
+			mIsExternal = false;
+			mHWnd = CreateWindow("OgreD3D9Wnd", title.c_str(), dwStyle,
+				mLeft, mTop, mWidth, mHeight, parentHWnd, 0, hInst, this);
+		}
+		else
+		{
+			mHWnd = externalHandle;
+			mIsExternal = true;
+		}
+
+			RECT rc;
+		// top and left represent outer window coordinates
+		GetWindowRect(mHWnd, &rc);
+		mTop = rc.top;
+		mLeft = rc.left;
+		// width and height represent interior drawable area
+			GetClientRect(mHWnd,&rc);
 			mWidth = rc.right;
 			mHeight = rc.bottom;
 
-			ShowWindow(hWnd, SW_SHOWNORMAL);
-			UpdateWindow(hWnd);
-
-			mHWnd = hWnd;
-			// Store info
 			mName = name;
 			mIsDepthBuffered = depthBuffer;
 			mIsFullScreen = fullScreen;
-		}
-		else
-		{
-			mHWnd = externalHandle;
-			ShowWindow(mHWnd, SW_SHOWNORMAL);
-			UpdateWindow(mHWnd);
-			RECT rc;
-			GetClientRect(mHWnd,&rc);
-			mWidth = rc.right;
-			mHeight = rc.bottom;
-			mLeft = rc.left;
-			mTop = rc.top;
-			mName = name;
-			mIsDepthBuffered = depthBuffer;
-			mIsFullScreen = fullScreen;
-		}
-
-		// track colour depth
 		mColourDepth = colourDepth;
 
@@ -337,5 +313,5 @@
 		createD3DResources();
 
-		mReady = true;
+		mActive = true;
 	}
 
@@ -365,4 +341,5 @@
 		md3dpp.BackBufferWidth			= mWidth;
 		md3dpp.BackBufferHeight			= mHeight;
+
 #ifdef GTP_VISIBILITY_MODIFIED_OGRE
 	//md3dpp.Flags |= D3DPRESENTFLAG_LOCKABLE_BACKBUFFER;
@@ -504,6 +481,5 @@
 	}
 
-	
-	void D3D9RenderWindow::destroy()
+	void D3D9RenderWindow::destroyD3DResources()
 	{
 		mpRenderSurface = 0;
@@ -515,16 +491,63 @@
 		else
 		{
-			// ignore deptzh buffer, access device through driver
+			// ignore depth buffer, access device through driver
 			mpRenderZBuffer = 0;
 			LPDIRECT3DDEVICE9 mpD3DDevice = mDriver->getD3DDevice();
 			SAFE_RELEASE(mpD3DDevice);
-			mDriver->setD3DDevice( mpD3DDevice );
+			mDriver->setD3DDevice(NULL);
+		}
+	}
+
+	void D3D9RenderWindow::destroy()
+	{
+		if (mHWnd && !mIsExternal)
 			DestroyWindow( mHWnd );
-		}
 		mHWnd = 0;
+		mActive = false;
+	}
+
+	bool D3D9RenderWindow::isVisible() const
+	{
+		return (mHWnd && !IsIconic(mHWnd));
+	}
+
+	void D3D9RenderWindow::reposition(int top, int left)
+	{
+		if (mHWnd && !mIsFullScreen)
+		{
+			SetWindowPos(mHWnd, 0, top, left, 0, 0,
+				SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE);
+		}
 	}
 
 	void D3D9RenderWindow::resize( unsigned int width, unsigned int height )
 	{
+		if (mHWnd && !mIsFullScreen)
+		{
+			RECT rc = { 0, 0, width, height };
+			AdjustWindowRect(&rc, GetWindowLong(mHWnd, GWL_STYLE), false);
+			width = rc.right - rc.left;
+			height = rc.bottom - rc.top;
+			SetWindowPos(mHWnd, 0, 0, 0, width, height,
+				SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE);
+		}
+	}
+
+	void D3D9RenderWindow::windowMovedOrResized()
+	{
+		if (!mHWnd || IsIconic(mHWnd))
+			return;
+
+		RECT rc;
+		// top and left represent outer window position
+		GetWindowRect(mHWnd, &rc);
+		mTop = rc.top;
+		mLeft = rc.left;
+		// width and height represent drawable area only
+		GetClientRect(mHWnd, &rc);
+		unsigned int width = rc.right;
+		unsigned int height = rc.bottom;
+		if (mWidth == width && mHeight == height)
+			return;
 		
 		if (mIsSwapChain) 
@@ -584,9 +607,11 @@
 			}
 		}
-		// primary windows would reset the device - not implemented yet.
+		// primary windows must reset the device
 		else 
 		{
-			mWidth = width;
-			mHeight = height;
+			md3dpp.BackBufferWidth = mWidth = width;
+			md3dpp.BackBufferHeight = mHeight = height;
+			static_cast<D3D9RenderSystem*>(
+				Root::getSingleton().getRenderSystem())->_notifyDeviceLost();
 		}
 
@@ -595,5 +620,4 @@
 		while( it != mViewportList.end() )
 			(*it++).second->_updateDimensions();
-		// TODO - resize window
 	}
 
@@ -617,6 +641,4 @@
 				static_cast<D3D9RenderSystem*>(
 					Root::getSingleton().getRenderSystem())->_notifyDeviceLost();
-				Sleep(500);
-
 			}
 			else if( FAILED(hr) )
@@ -668,9 +690,4 @@
 			return;
 		}
-	}
-
-	void D3D9RenderWindow::WindowMovedOrResized()
-	{
-		// TODO
 	}
 
@@ -863,8 +880,8 @@
 				else
 					SAFE_RELEASE (mpRenderZBuffer);
-				Sleep(500);
+				Sleep(50);
 				return;
 			}
-			else if (hr == D3DERR_DEVICENOTRESET)
+			else
 			{
 				// device lost, and we can reset
@@ -875,5 +892,5 @@
 				{
 					// Wait a while
-					Sleep(500);
+					Sleep(50);
 					return;
 				}
Index: trunk/VUT/work/iv/TestCullingIVApplication.cpp
===================================================================
--- trunk/VUT/work/iv/TestCullingIVApplication.cpp	(revision 187)
+++ trunk/VUT/work/iv/TestCullingIVApplication.cpp	(revision 193)
@@ -91,6 +91,6 @@
 	Real scale = 1;
 	mSceneMgr->setOption("NodeVizScale", &scale);
-
-	String path = "E:/gametools/trunk/VUT/Ogre/resources/";
+	// HACK: change this to relative path
+	String path = "D:/gametools/trunk/VUT/Ogre/resources/";
 		
 	SceneNode *node1 = mSceneMgr->getRootSceneNode()->createChildSceneNode("Node1");
Index: trunk/VUT/work/iv/Demo_IV.vcproj
===================================================================
--- trunk/VUT/work/iv/Demo_IV.vcproj	(revision 187)
+++ trunk/VUT/work/iv/Demo_IV.vcproj	(revision 193)
@@ -46,5 +46,5 @@
 				LinkIncremental="1"
 				SuppressStartupBanner="TRUE"
-				AdditionalLibraryDirectories="&quot;$(OGRE_PATH)\OgreMain\Lib\$(ConfigurationName)&quot;;&quot;..\IVReader\Lib\$(ConfigurationName)&quot;;&quot;$(OGRE_PATH)\Samples\Common\CEGUIRenderer\lib&quot;;&quot;$(OGRE_PATH)\Dependencies\Lib\$(ConfigurationName)&quot;;&quot;$(OGRE_PATH)\PlugIns\OctreeSceneManager\bin\$(ConfigurationName)&quot;;&quot;$(GAMETOOLS_PATH)\trunk\VUT\Ogre\lib\$(ConfigurationName)&quot;"
+				AdditionalLibraryDirectories="&quot;$(OGRE_PATH)\OgreMain\Lib\$(ConfigurationName)&quot;;&quot;$(OGRE_PATH)\Samples\Common\CEGUIRenderer\lib&quot;;&quot;..\IVReader\Lib\$(ConfigurationName)&quot;;&quot;$(OGRE_PATH)\Dependencies\Lib\$(ConfigurationName)&quot;;&quot;$(OGRE_PATH)\PlugIns\OctreeSceneManager\bin\$(ConfigurationName)&quot;;&quot;$(GAMETOOLS_PATH)\trunk\VUT\Ogre\lib\$(ConfigurationName)&quot;"
 				ProgramDatabaseFile=".\..\bin\Release/Demo_IV.pdb"
 				SubSystem="2"
