Browse Source

Refactoring GL render system and documenting

Marko Pintera 11 years ago
parent
commit
fa49144cd8

+ 9 - 3
BoostPort.txt

@@ -9,9 +9,15 @@
 cm_shared_ptr should use && for parameter forwarding?
 cm_core_ptr too
 
-When creating an OpenGL context I need to create the basic one, then initialize it (currently done in GLRenderSystem::initializeContext which I'll 
-need to move), and then destroy window/DC/context and recreate them using the attrib version. Check out win32_window.c in glwf from SB source 
-code for example parameters when creating one.
+Refactor GLRenderSystem:
+createRenderSystemCapabilities
+initialiseFromRenderSystemCapabilities
+initializeContext
+switchContext
+oneTimeContextInitialization
 
+and update its docs
+
+Perform refactor mentioned in the documentation e-mail
 
 Create a proper git repo of dependencies folder

+ 173 - 217
CamelotCore/Include/CmRenderSystem.h

@@ -1,34 +1,4 @@
-/*
------------------------------------------------------------------------------
-This source file is part of OGRE
-(Object-oriented Graphics Rendering Engine)
-For the latest info, see http://www.ogre3d.org
-
-Copyright (c) 2000-2011 Torus Knot Software Ltd
-
-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 __RenderSystem_H_
-#define __RenderSystem_H_
-
-// Precompiler options
+#pragma once
 #include "CmPrerequisites.h"
 
 #include <memory>
@@ -52,111 +22,96 @@ THE SOFTWARE.
 
 namespace BansheeEngine
 {
-	/** \addtogroup Core
-	*  @{
-	*/
-	/** \addtogroup RenderSystem
-	*  @{
-	*/
-
-	typedef MultiMap<UINT8, RenderTarget * > RenderTargetPriorityMap;
-
-	class TextureManager;
-
-	/** Defines the functionality of a 3D API
-	@remarks
-	The RenderSystem class provides a base interface
-	which abstracts the general functionality of the 3D API
-	e.g. Direct3D or OpenGL. Whilst a few of the general
-	methods have implementations, most of this class is
-	abstract, requiring a subclass based on a specific API
-	to be constructed to provide the full functionality.
-	@author
-	Steven Streeting
-	@version
-	1.0
-	*/
+	/**
+	 * @brief	Render system provides base functionality for a rendering API like
+	 *			DirectX or OpenGL. Most of the class is abstract and specific
+	 *			subclass for each rendering API needs to be implemented.
+	 *
+	 * @note	Core thread only unless specifically noted otherwise on per-method basis.
+	 */
 	class CM_EXPORT RenderSystem : public Module<RenderSystem>
 	{
 	public:
-		/** Default Constructor.
-		*/
 		RenderSystem();
-
-		/** Destructor.
-		*/
 		virtual ~RenderSystem();
 
-		/** Returns the name of the rendering system.
-		*/
-		virtual const String& getName(void) const = 0;
+		/**
+		 * @brief	Returns the name of the rendering system. 
+		 *
+		 * @note	Thread safe.
+		 */
+		virtual const String& getName() const = 0;
 
 		/**
-		 * @brief	Gets the name of the primary shading language.
+		 * @brief	Gets the name of the primary shading language
+		 *			used by the rendering system.
+		 *
+		 * @note	Thread safe.
 		 */
 		virtual const String& getShadingLanguageName() const = 0;
 
 		/**
 		 * @brief	Sets a sampler state for the specified texture unit.
+		 *
 		 * @see		SamplerState
 		 */
 		virtual void setSamplerState(GpuProgramType gptype, UINT16 texUnit, const SamplerStatePtr& samplerState) = 0;
-		/** Turns off a texture unit. */
-		virtual void disableTextureUnit(GpuProgramType gptype, UINT16 texUnit);
 
 		/**
 		 * @brief	Sets a blend state used for all active render targets.
+		 *
 		 * @see		BlendState
 		 */
 		virtual void setBlendState(const BlendStatePtr& blendState) = 0;
 
 		/**
 		 * @brief	Sets a state that controls various rasterizer options. 
+		 *
 		 * @see		RasterizerState
 		 */
 		virtual void setRasterizerState(const RasterizerStatePtr& rasterizerState) = 0;
 
 		/**
 		 * @brief	Sets a state that controls depth & stencil buffer options.
+		 *
 		 * @see		DepthStencilState
 		 */
 		virtual void setDepthStencilState(const DepthStencilStatePtr& depthStencilState, UINT32 stencilRefValue) = 0;
 
 		/**
-		Sets the texture to bind to a given texture unit.
-
-		User processes would not normally call this direct unless rendering
-		primitives themselves.
+		 * @brief	Binds a texture to the pipeline for the specified GPU program type at the specified slot.
+		 *			If the slot matches the one configured in the GPU program the program will be able to access
+		 *			this texture on the GPU.
+		 */
+		virtual void setTexture(GpuProgramType gptype, UINT16 unit, bool enabled, const TexturePtr& texPtr) = 0;
 
-		@param unit The index of the texture unit to modify. Multitexturing 
-		hardware can support multiple units (see 
-		RenderSystemCapabilites::getNumTextureUnits)
-		@param enabled Boolean to turn the unit on/off
-		@param texPtr Pointer to the texture to use.
+		/**
+		* @brief	Turns off a texture unit.
 		*/
-		virtual void setTexture(GpuProgramType gptype, UINT16 unit, bool enabled, const TexturePtr &texPtr) = 0;
+		virtual void disableTextureUnit(GpuProgramType gptype, UINT16 texUnit);
 
 		/**
-		* Signifies the beginning of a frame, i.e. the start of rendering on a single viewport. Will occur
-		* several times per complete frame if multiple viewports exist.
-		*/
-		virtual void beginFrame(void) = 0;
+		 * @brief	Signals that rendering for a specific viewport has started. Any draw calls
+		 *			need to be called between beginFrame and endFrame. You may not switch render targets
+		 *			until you call endFrame.
+		 */
+		virtual void beginFrame() = 0;
 		
 		/**
-		* Ends rendering of a frame to the current viewport.
-		*/
-		virtual void endFrame(void) = 0;
-		/**
-		Sets the provided viewport as the active one for future
-		rendering operations. This viewport is aware of it's own
-		camera and render target. Must be implemented by subclass.
+		 * @brief	Ends that rendering to a specific viewport has ended.
+		 */
+		virtual void endFrame() = 0;
 
-		@param target Viewport to render to.
-		*/
+		/**
+		 * @brief	Sets the active viewport that will be used for all render operations.
+		 *			Viewport will change active render target if needed.
+		 */
 		virtual void setViewport(const ViewportPtr& vp) = 0;
 
-		/** Sets the provided vertex buffers starting at the specified source index.   
-		/** @note Set buffer to nullptr to clear the buffer at the specified index.*/
+		/**
+		 * @brief	Sets the provided vertex buffers starting at the specified source index.
+		 *			Set buffer to nullptr to clear the buffer at the specified index.
+		 */
 		virtual void setVertexBuffers(UINT32 index, VertexBufferPtr* buffers, UINT32 numBuffers) = 0;
 
 		/**
@@ -192,17 +147,14 @@ namespace BansheeEngine
 		virtual void render(const MeshBasePtr& mesh, UINT32 indexOffset = 0, UINT32 indexCount = 0, bool useIndices = true, DrawOperationType drawOp = DOT_TRIANGLE_LIST);
 
 		/**
-		 * @brief	Draw an object based on currently set
-		 * 			shaders, vertex declaration index buffers.
+		 * @brief	Draw an object based on currently bound GPU programs, vertex declaration and vertex buffers.
 		 * 			
-		 *			Draws directly from the vertex buffer without using
-		 *			indices.
+		 *			Draws directly from the vertex buffer without using indices.
 		 */
 		virtual void draw(UINT32 vertexOffset, UINT32 vertexCount) = 0;
 
 		/**
-		 * @brief	Draw an object based on currently set
-		 * 			shaders, vertex declaration and vertex 
+		 * @brief	Draw an object based on currently bound GPU programs, vertex declaration, vertex 
 		 * 			and index buffers.
 		 */
 		virtual void drawIndexed(UINT32 startIndex, UINT32 indexCount, UINT32 vertexOffset, UINT32 vertexCount) = 0;
@@ -219,52 +171,54 @@ namespace BansheeEngine
 		 */
 		const RenderSystemCapabilities* getCapabilities() const;
 
-		/** Returns the driver version.
-		*/
+		/**
+		 * @brief	Returns information about the driver version.
+		 */
 		virtual const DriverVersion& getDriverVersion() const;
 
-		/** Binds a given GpuProgram (but not the parameters). 
-		@remarks Only one GpuProgram of each type can be bound at once, binding another
-		one will simply replace the existing one.
-		*/
+		/**
+		 * @brief	Binds the provided GPU program to the pipeline. Any following
+		 *			draw operations will use this program. 
+		 *
+		 * @note	You need to bind at least a vertex and a fragment program in order to draw something.
+		 */
 		virtual void bindGpuProgram(HGpuProgram prg);
 
-		/** Bind Gpu program parameters.
-		@param gptype The type of program to bind the parameters to
-		@param params The parameters to bind
-		*/
+		/**
+		 * @brief	Binds GPU program parameters. Caller must ensure these match the previously
+		 *			bound GPU program.
+		 */
 		virtual void bindGpuParams(GpuProgramType gptype, BindableGpuParams& params) = 0;
 
-		/** Unbinds GpuPrograms of a given GpuProgramType.
-		@remarks
-		This returns the pipeline to fixed-function processing for this type.
-		*/
+		/**
+		 * @brief	Unbinds a program of a given type. 
+		 */
 		virtual void unbindGpuProgram(GpuProgramType gptype);
 
-		/** Returns whether or not a Gpu program of the given type is currently bound. */
+		/**
+		 * @brief	Query if a GPU program of a given type is currently bound.
+		 */
 		virtual bool isGpuProgramBound(GpuProgramType gptype);
 
-		/** Sets the user clipping region.
-		*/
+		/**
+		 * @brief	Sets up clip planes that will clip drawn geometry on the negative side of the planes.
+		 */
 		virtual void setClipPlanes(const PlaneList& clipPlanes);
 
-		/** Add a user clipping plane. */
-		virtual void addClipPlane (const Plane& p);
+		/**
+		 * @brief	Adds a new clip plane. All drawn geometry will be clipped to this plane.
+		 */
+		virtual void addClipPlane(const Plane& p);
 
-		/** Clears the user clipping region.
-		*/
+		/**
+		 * @brief	Clears all clip planes.
+		 */
 		virtual void resetClipPlanes();
 
-		/** Sets the 'scissor region' ie the region of the target in which rendering can take place.
-		@remarks
-		This method allows you to 'mask off' rendering in all but a given rectangular area
-		as identified by the parameters to this method.
-		@note
-		Not all systems support this method. Check the RenderSystemCapabilities for the
-		RSC_SCISSOR_TEST capability to see if it is supported.
-		@param left, top, right, bottom The location of the corners of the rectangle, expressed in
-		<i>pixels</i>.
-		*/
+		/**
+		 * @brief	Allows you to set up a region in which rendering can take place. Coordinates are in pixels.
+		 *			No rendering will be done to render target pixels outside of the provided region.
+		 */
 		virtual void setScissorRect(UINT32 left, UINT32 top, UINT32 right, UINT32 bottom) = 0;
 
 		/**
@@ -291,17 +245,23 @@ namespace BansheeEngine
 		virtual void clearViewport(UINT32 buffers, const Color& color = Color::Black, float depth = 1.0f, UINT16 stencil = 0) = 0;
 
 		/**
-         * Set current render target to target, enabling its device context if needed
-         */
+		 * @brief	Change the render target into which we want to draw.
+		 */
         virtual void setRenderTarget(RenderTargetPtr target) = 0;
 
 		/**
 		 * @brief	Updates the resource with the specified data.
+		 *
+		 * @note	It is assumed GpuResourceData has been locked before being passed here. Data will be unlocked
+		 *			when this method finishes.
 		 */
 		void writeSubresource(GpuResourcePtr resource, UINT32 subresourceIdx, const GpuResourceDataPtr& data, bool discardEntireBuffer, AsyncOp& asyncOp);
 
 		/**
 		 * @brief	Reads data from a resource into a pre-allocated GpuResourceData instance.
+		 *
+		 * @note	It is assumed GpuResourceData has been locked before being passed here. Data will be unlocked
+		 *			when this method finishes.
 		 */
 		void readSubresource(GpuResourcePtr resource, UINT32 subresourceIdx, GpuResourceDataPtr& data, AsyncOp& asyncOp);
 
@@ -309,120 +269,116 @@ namespace BansheeEngine
 		/* 								UTILITY METHODS                    		*/
 		/************************************************************************/
 
-		/** Get the native VertexElementType for a compact 32-bit colour value
-		for this rendersystem.
-		*/
-		virtual VertexElementType getColorVertexElementType(void) const = 0;
+		/**
+		 * @brief	Gets the native type used for vertex colors.
+		 *
+		 * @note	Thread safe.
+		 */
+		virtual VertexElementType getColorVertexElementType() const = 0;
 
-		/** Converts a uniform projection matrix to suitable for this render system.
-		@remarks
-		Because different APIs have different requirements (some incompatible) for the
-		projection matrix, this method allows each to implement their own correctly and pass
-		back a generic Banshee matrix for storage in the engine.
-		*/
+		/**
+		 * @brief	Contains a default matrix into a matrix suitable for use
+		 *			by this specific render system.
+		 *
+		 * @note	Thread safe.
+		 */
 		virtual void convertProjectionMatrix(const Matrix4& matrix,
 			Matrix4& dest, bool forGpuProgram = false) = 0;
 
-		/** Returns the horizontal texel offset value required for mapping 
-		texel origins to pixel origins in this rendersystem.
-		@remarks
-		Since rendersystems sometimes disagree on the origin of a texel, 
-		mapping from texels to pixels can sometimes be problematic to 
-		implement generically. This method allows you to retrieve the offset
-		required to map the origin of a texel to the origin of a pixel in
-		the horizontal direction.
-		*/
-		virtual float getHorizontalTexelOffset(void) = 0;
-
-		/** Returns the vertical texel offset value required for mapping 
-		texel origins to pixel origins in this rendersystem.
-		@remarks
-		Since rendersystems sometimes disagree on the origin of a texel, 
-		mapping from texels to pixels can sometimes be problematic to 
-		implement generically. This method allows you to retrieve the offset
-		required to map the origin of a texel to the origin of a pixel in
-		the vertical direction.
-		*/
-		virtual float getVerticalTexelOffset(void) = 0;
-
-		/** Gets the minimum (closest) depth value to be used when rendering
-		using identity transforms.
-		@remarks
-		When using identity transforms you can manually set the depth
-		of a vertex; however the input values required differ per
-		rendersystem. This method lets you retrieve the correct value.
-		@see Renderable::getUseIdentityView, Renderable::getUseIdentityProjection
+		/**
+		 * @brief	Gets horizontal texel offset used for mapping texels to pixels
+		 *			in this render system.
+		 *
+		 * @note	Thread safe.
+		 */
+		virtual float getHorizontalTexelOffset() = 0;
+
+		/**
+		* @brief	Gets vertical texel offset used for mapping texels to pixels
+		*			in this render system.
+		*
+		* @note		Thread safe.
 		*/
-		virtual float getMinimumDepthInputValue(void) = 0;
-
-		/** Gets the maximum (farthest) depth value to be used when rendering
-		using identity transforms.
-		@remarks
-		When using identity transforms you can manually set the depth
-		of a vertex; however the input values required differ per
-		rendersystem. This method lets you retrieve the correct value.
-		@see Renderable::getUseIdentityView, Renderable::getUseIdentityProjection
+		virtual float getVerticalTexelOffset() = 0;
+
+		/**
+		 * @brief	Gets the minimum (closest) depth value used by this
+		 *			render system.
+		 *
+		 * @note	Thread safe.
+		 */
+		virtual float getMinimumDepthInputValue() = 0;
+
+		/**
+		* @brief	Gets the maximum (farthest) depth value used by this
+		*			render system.
+		*
+		* @note		Thread safe.
 		*/
 		virtual float getMaximumDepthInputValue(void) = 0;
 
 		/************************************************************************/
-		/* 						INTERNAL DATA & METHODS                      	*/
+		/* 							INTERNAL METHODS				        	*/
+		/************************************************************************/
+	protected:
+		/**
+		* @brief	Initializes the render system and creates a primary render window.
+		*
+		* @note		Although I'd like otherwise, due to the nature of some render system implementations,
+		* 			you cannot initialize the render system without a window.
+		*
+		*			Sim thread.
+		*/
+		RenderWindowPtr initialize(const RENDER_WINDOW_DESC& primaryWindowDesc);
+
+		/**
+		 * @brief	Performs second part of the initialization (on Core thread), first part
+		 *			being in initialize().
+		 */
+		virtual void initialize_internal(AsyncOp& asyncOp);
+
+		/**
+		 * @brief	Shuts down the render system and cleans up all resources.
+		 *
+		 * @note	Sim thread.
+		 */
+		void destroy();
+
+		/**
+		 * @brief	Performs second part of render system shutdown on the core thread.
+		 */
+		virtual void destroy_internal();
+
+		/**
+		 * @copydoc	setClipPlanes.
+		 */
+		virtual void setClipPlanesImpl(const PlaneList& clipPlanes) = 0;
+
+		/************************************************************************/
+		/* 								INTERNAL DATA					       	*/
 		/************************************************************************/
 	protected:
 		friend class RenderSystemManager;
 
-		/** The Active render target. */
 		RenderTargetPtr mActiveRenderTarget;
 
+		DriverVersion mDriverVersion;
 		CullingMode mCullingMode;
-
-		/// Texture units from this upwards are disabled
 		UINT16 mDisabledTexUnitsFrom;
 
 		bool mVertexProgramBound;
 		bool mGeometryProgramBound;
 		bool mFragmentProgramBound;
+		bool mDomainProgramBound;
+		bool mHullProgramBound;
+		bool mComputeProgramBound;
 
-		// Recording user clip planes
 		PlaneList mClipPlanes;
-		// Indicator that we need to re-set the clip planes on next render call
 		bool mClipPlanesDirty;
 
-		/// Used to store the capabilities of the graphics card
 		RenderSystemCapabilities* mCurrentCapabilities;
 
 		// TODO - Only used between initialize and initialize_internal. Handle it better?
 		RENDER_WINDOW_DESC mPrimaryWindowDesc;
-
-		/**
-		 * @brief	Initializes the render system and creates a primary render window.
-		 * 			
-		 * @note	Although I'd like otherwise, due to the nature of some render system implementations, 
-		 * 			you cannot initialize the render system without a window.
-		 */
-		RenderWindowPtr initialize(const RENDER_WINDOW_DESC& primaryWindowDesc);
-		virtual void initialize_internal(AsyncOp& asyncOp);
-
-		void destroy();
-		virtual void destroy_internal();
-
-		/// Internal method used to set the underlying clip planes when needed
-		virtual void setClipPlanesImpl(const PlaneList& clipPlanes) = 0;
-
-		/** Query the real capabilities of the GPU and driver in the RenderSystem*/
-		virtual RenderSystemCapabilities* createRenderSystemCapabilities() const = 0;
-
-		/** Initialize the render system from the capabilities*/
-		virtual void initialiseFromRenderSystemCapabilities(RenderSystemCapabilities* caps) = 0;
-
-		/** Returns a description of an error code.
-		*/
-		virtual String getErrorDescription(long errorNumber) const = 0;
-
-		DriverVersion mDriverVersion;
 	};
-	/** @} */
-	/** @} */
-}
-
-#endif
+}

+ 32 - 38
CamelotCore/Source/CmRenderSystem.cpp

@@ -1,36 +1,3 @@
-/*
------------------------------------------------------------------------------
-This source file is part of OGRE
-    (Object-oriented Graphics Rendering Engine)
-For the latest info, see http://www.ogre3d.org/
-
-Copyright (c) 2000-2011 Torus Knot Software Ltd
-
-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.
------------------------------------------------------------------------------
-*/
-// RenderSystem implementation
-// Note that most of this class is abstract since
-//  we cannot know how to implement the behaviour without
-//  being aware of the 3D API. However there are a few
-//  simple functions which can have a base implementation
-
 #include "CmRenderSystem.h"
 
 #include "CmCoreThread.h"
@@ -57,6 +24,9 @@ namespace BansheeEngine {
         , mVertexProgramBound(false)
 		, mGeometryProgramBound(false)
         , mFragmentProgramBound(false)
+		, mDomainProgramBound(false)
+		, mHullProgramBound(false)
+		, mComputeProgramBound(false)
 		, mClipPlanesDirty(true)
 		, mCurrentCapabilities(nullptr)
     {
@@ -64,7 +34,7 @@ namespace BansheeEngine {
 
     RenderSystem::~RenderSystem()
     {
-		// Base classes need to call virtual destroy_internal method (queue it on core thread)
+		// Base classes need to call virtual destroy_internal method instead of a destructor
 
 		cm_delete(mCurrentCapabilities);
 		mCurrentCapabilities = nullptr;
@@ -86,6 +56,9 @@ namespace BansheeEngine {
 		mVertexProgramBound = false;
 		mGeometryProgramBound = false;
 		mFragmentProgramBound = false;
+		mDomainProgramBound = false;
+		mHullProgramBound = false;
+		mComputeProgramBound = false;
 	}
 
 	void RenderSystem::destroy()
@@ -155,7 +128,6 @@ namespace BansheeEngine {
 		switch(prg->getBindingDelegate()->getType())
 		{
 		case GPT_VERTEX_PROGRAM:
-			// mark clip planes dirty if changed (programmable can change space)
 			if (!mVertexProgramBound && !mClipPlanes.empty())
 				mClipPlanesDirty = true;
 
@@ -167,6 +139,15 @@ namespace BansheeEngine {
 		case GPT_FRAGMENT_PROGRAM:
 			mFragmentProgramBound = true;
 			break;
+		case GPT_DOMAIN_PROGRAM:
+			mDomainProgramBound = true;
+			break;
+		case GPT_HULL_PROGRAM:
+			mHullProgramBound = true;
+			break;
+		case GPT_COMPUTE_PROGRAM:
+			mComputeProgramBound = true;
+			break;
 		}
 	}
 
@@ -177,9 +158,9 @@ namespace BansheeEngine {
 		switch(gptype)
 		{
 		case GPT_VERTEX_PROGRAM:
-			// mark clip planes dirty if changed (programmable can change space)
 			if (mVertexProgramBound && !mClipPlanes.empty())
 				mClipPlanesDirty = true;
+
 			mVertexProgramBound = false;
 			break;
 		case GPT_GEOMETRY_PROGRAM:
@@ -188,6 +169,15 @@ namespace BansheeEngine {
 		case GPT_FRAGMENT_PROGRAM:
 			mFragmentProgramBound = false;
 			break;
+		case GPT_DOMAIN_PROGRAM:
+			mDomainProgramBound = false;
+			break;
+		case GPT_HULL_PROGRAM:
+			mHullProgramBound = false;
+			break;
+		case GPT_COMPUTE_PROGRAM:
+			mComputeProgramBound = false;
+			break;
 		}
 	}
 
@@ -203,6 +193,12 @@ namespace BansheeEngine {
             return mGeometryProgramBound;
         case GPT_FRAGMENT_PROGRAM:
             return mFragmentProgramBound;
+		case GPT_DOMAIN_PROGRAM:
+			return mDomainProgramBound;
+		case GPT_HULL_PROGRAM:
+			return mHullProgramBound;
+		case GPT_COMPUTE_PROGRAM:
+			return mComputeProgramBound;
 	    }
 
         return false;
@@ -214,8 +210,6 @@ namespace BansheeEngine {
 
 		gProfiler().beginSample("render");
 
-		// sort out clip planes
-		// have to do it here in case of matrix issues
 		if (mClipPlanesDirty)
 		{
 			setClipPlanesImpl(mClipPlanes);

+ 0 - 2
CamelotD3D11RenderSystem/Include/CmD3D11RenderSystem.h

@@ -69,8 +69,6 @@ namespace BansheeEngine
 		RenderSystemCapabilities* createRenderSystemCapabilities() const;
 		void initialiseFromRenderSystemCapabilities(RenderSystemCapabilities* caps);
 
-		String getErrorDescription(long errorNumber) const;
-
 		void convertProjectionMatrix(const Matrix4& matrix, Matrix4& dest, bool forGpuProgram = false);
 		VertexElementType getColorVertexElementType() const;
 		float getHorizontalTexelOffset();

+ 0 - 5
CamelotD3D11RenderSystem/Source/CmD3D11RenderSystem.cpp

@@ -864,11 +864,6 @@ namespace BansheeEngine
 		// Do nothing
 	}
 
-	String D3D11RenderSystem::getErrorDescription(long errorNumber) const
-	{
-		return mDevice->getErrorDescription();
-	}
-
 	void D3D11RenderSystem::determineFSAASettings(UINT32 fsaa, const String& fsaaHint, DXGI_FORMAT format, DXGI_SAMPLE_DESC* outFSAASettings)
 	{
 		bool ok = false;

+ 4 - 3
CamelotGLRenderer/Include/CmGLPrerequisites.h

@@ -30,7 +30,10 @@ THE SOFTWARE.
 
 #include "CmPrerequisites.h"
 
-namespace BansheeEngine {
+namespace BansheeEngine 
+{
+	extern String MODULE_NAME;
+
     // Forward declarations
     class GLSupport;
     class GLRenderSystem;
@@ -81,11 +84,9 @@ namespace BansheeEngine {
 #endif
 
 #if CM_THREAD_SUPPORT == 1
-	// implemented in OgreGLContext.cpp
 	GLEWContext * glewGetContext();
 
 #	if CM_PLATFORM == CM_PLATFORM_WIN32
-	// implemented in OgreWin32Context.cpp
 	WGLEWContext * wglewGetContext();
 #	endif
 

+ 124 - 179
CamelotGLRenderer/Include/CmGLRenderSystem.h

@@ -1,32 +1,4 @@
-/*
------------------------------------------------------------------------------
-This source file is part of OGRE
-    (Object-oriented Graphics Rendering Engine)
-For the latest info, see http://www.ogre3d.org
-
-Copyright (c) 2000-2011 Torus Knot Software Ltd
-
-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 __GLRenderSystem_H__
-#define __GLRenderSystem_H__
+#pragma once
 
 #include "CmGLPrerequisites.h"
 #include "CmRenderSystem.h"
@@ -35,10 +7,11 @@ THE SOFTWARE.
 #include "CmGLSLProgramFactory.h"
 #include "CmVector4.h"
 
-namespace BansheeEngine {
-    /**
-      Implementation of GL as a rendering system.
-     */
+namespace BansheeEngine 
+{
+	/**
+	 * @brief	Implementation of a render system using OpenGL.
+	 */
     class CM_RSGL_EXPORT GLRenderSystem : public RenderSystem
     {
     public:
@@ -200,100 +173,6 @@ namespace BansheeEngine {
 		GLContext* getMainContext() const { return mMainContext; } 
 		GLSupport* getGLSupport() const { return mGLSupport; }
 
-    private:
-		// Scissor test
-		UINT32 mScissorTop, mScissorBottom, mScissorLeft, mScissorRight;
-		UINT32 mViewportLeft, mViewportTop, mViewportWidth, mViewportHeight;
-
-		UINT32 mStencilReadMask;
-		UINT32 mStencilWriteMask;
-		UINT32 mStencilRefValue;
-		CompareFunction mStencilCompareFront;
-		CompareFunction mStencilCompareBack;
-
-        /// View matrix to set world against
-        Matrix4 mViewMatrix;
-
-        /// Last min & mip filtering options, so we can combine them
-        FilterOptions mMinFilter;
-        FilterOptions mMipFilter;
-
-        /// Holds texture type settings for every stage
-        UINT32	mNumTextureTypes;
-        GLenum* mTextureTypes;
-
-        void initInputDevices(void);
-        void processInputDevices(void);
-
-        void makeGLMatrix(GLfloat gl_matrix[16], const Matrix4& m);
- 
-        GLint getBlendMode(BlendFactor ogreBlend) const;
-		GLint getTextureAddressingMode(TextureAddressingMode tam) const;
-		void initializeContext(GLContext* primary);
-
-		/** See
-          RenderSystem
-         */
-		virtual RenderSystemCapabilities* createRenderSystemCapabilities() const;
-        /** See
-          RenderSystem
-         */
-		void initialiseFromRenderSystemCapabilities(RenderSystemCapabilities* caps);
-
-        /// Store last depth write state
-        bool mDepthWrite;
-		/// Store last colour write state
-		bool mColorWrite[4];
-
-        GLint convertCompareFunction(CompareFunction func) const;
-        GLint convertStencilOp(StencilOperation op, bool invert = false) const;
-
-		/// Internal method for anisotropy validation
-		GLfloat _getCurrentAnisotropy(UINT16 unit);
-		
-        /// GL support class, used for creating windows etc.
-        GLSupport* mGLSupport;
-
-        /// Check if the GL system has already been initialised
-        bool mGLInitialised;
-
-		GLSLProgramFactory* mGLSLProgramFactory;
-		GLSLProgramPipelineManager* mProgramPipelineManager;
-
-        GLuint getCombinedMinMipFilter(void) const;
-
-        GLSLGpuProgramPtr mCurrentVertexProgram;
-        GLSLGpuProgramPtr mCurrentFragmentProgram;
-		GLSLGpuProgramPtr mCurrentGeometryProgram;
-		GLSLGpuProgramPtr mCurrentHullProgram;
-		GLSLGpuProgramPtr mCurrentDomainProgram;
-
-		const GLSLProgramPipeline* mActivePipeline;
-
-		UINT32 mFragmentTexOffset;
-		UINT32 mVertexTexOffset;
-		UINT32 mGeometryTexOffset;
-
-		UINT32 mFragmentUBOffset;
-		UINT32 mVertexUBOffset;
-		UINT32 mGeometryUBOffset;
-		UINT32 mHullUBOffset;
-		UINT32 mDomainUBOffset;
-		UINT32 mComputeUBOffset;
-
-		UnorderedMap<UINT32, VertexBufferPtr> mBoundVertexBuffers;
-		VertexDeclarationPtr mBoundVertexDeclaration;
-		IndexBufferPtr mBoundIndexBuffer;
-		DrawOperationType mCurrentDrawOperation;
-
-        GLContext *mMainContext;
-        GLContext *mCurrentContext;
-
-		Vector<GLuint> mBoundAttributes; // Only full between begin/endDraw calls
-		bool mDrawCallInProgress;
-
-		UINT16 mActiveTextureUnit;
-
 	protected:
 		/**
 		 * @copydoc	RenderSystem::initialize_internal().
@@ -305,23 +184,63 @@ namespace BansheeEngine {
 		 */
         void destroy_internal(void);
 
+		/**
+		* @brief	Call before doing a draw operation, this method sets everything up.
+		*/
+		void beginDraw();
+
+		/**
+		* @brief	Needs to accompany every beginDraw after you are done with a single draw operation.
+		*/
+		void endDraw();
+
+		void clearArea(UINT32 buffers, const Color& color = Color::Black, float depth = 1.0f, UINT16 stencil = 0, const RectI& clearArea = RectI::EMPTY);
+
 		void setClipPlanesImpl(const PlaneList& clipPlanes);
 		bool activateGLTextureUnit(UINT16 unit);
 
-        /** See
-          RenderSystem
-         */
-        String getErrorDescription(long errorNumber) const;
-
-		/** See
-          RenderSystem
-         */
-        void setClipPlane (UINT16 index, float A, float B, float C, float D);
-        /** See
-          RenderSystem
-         */
+        void setClipPlane(UINT16 index, float A, float B, float C, float D);
         void enableClipPlane (UINT16 index, bool enable);
 
+		void setActiveProgram(GpuProgramType gptype, GLSLGpuProgramPtr program);
+		GLSLGpuProgramPtr getActiveProgram(GpuProgramType gptype) const;
+
+		GLint getBlendMode(BlendFactor ogreBlend) const;
+		GLint getTextureAddressingMode(TextureAddressingMode tam) const;
+		GLfloat getCurrentAnisotropy(UINT16 unit);
+		GLuint getCombinedMinMipFilter() const;
+
+		/**
+		* @brief	OpenGL shares all texture slots, but the engine prefers to keep textures
+		* 			separate per-stage. This will convert texture unit that is set per stage
+		* 			into a global texture unit usable by OpenGL.
+		*/
+		UINT32 getGLTextureUnit(GpuProgramType gptype, UINT32 unit);
+
+		/**
+		* @brief	OpenGL shares all buffer bindings, but the engine prefers to keep buffers
+		* 			separate per-stage. This will convert block buffer binding that is set per stage
+		* 			into a global block buffer binding usable by OpenGL.
+		*/
+		UINT32 getGLUniformBlockBinding(GpuProgramType gptype, UINT32 binding);
+
+		/**
+		* @brief	Returns the OpenGL specific mode used for drawing, depending on the
+		* 			currently set draw operation;
+		*/
+		GLint getGLDrawMode() const;
+
+		void initializeContext(GLContext* primary);
+		RenderSystemCapabilities* createRenderSystemCapabilities() const;
+		void initialiseFromRenderSystemCapabilities(RenderSystemCapabilities* caps);
+		/** One time initialization for the RenderState of a context. Things that
+		only need to be set once, like the LightingModel can be defined here.
+		*/
+		void oneTimeContextInitialization();
+		/** Switch GL context, dealing with involved internal cached states too
+		*/
+		void switchContext(GLContext *context);
+
 		/************************************************************************/
 		/* 								Sampler states                     		*/
 		/************************************************************************/
@@ -350,7 +269,7 @@ namespace BansheeEngine {
         void setTextureFiltering(UINT16 unit, FilterType ftype, FilterOptions filter);
 
 		/** Sets the maximal anisotropy for the specified texture unit.*/
-		void setTextureAnisotropy(UINT16 unit, unsigned int maxAnisotropy);
+		void setTextureAnisotropy(UINT16 unit, UINT32 maxAnisotropy);
 
 		/************************************************************************/
 		/* 								Blend states                      		*/
@@ -536,54 +455,80 @@ namespace BansheeEngine {
 		 */
 		void setStencilRefValue(UINT32 refValue);
 
-        /** One time initialization for the RenderState of a context. Things that
-            only need to be set once, like the LightingModel can be defined here.
-         */
-        void oneTimeContextInitialization();
-        /** Switch GL context, dealing with involved internal cached states too
-        */
-        void switchContext(GLContext *context);
+		/************************************************************************/
+		/* 							UTILITY METHODS                      		*/
+		/************************************************************************/
+
+		void makeGLMatrix(GLfloat gl_matrix[16], const Matrix4& m);
+
+		GLint convertCompareFunction(CompareFunction func) const;
+		GLint convertStencilOp(StencilOperation op, bool invert = false) const;
 
 		/**
-		 * @brief	Checks if there are any OpenGL errors and prints them to the log.
-		 */
+		* @brief	Checks if there are any OpenGL errors and prints them to the log.
+		*/
 		bool checkForErrors() const;
 
-		/**
-		 * @brief	OpenGL shares all texture slots, but the engine prefers to keep textures
-		 * 			separate per-stage. This will convert texture unit that is set per stage
-		 * 			into a global texture unit usable by OpenGL.
-		 */
-		UINT32 getGLTextureUnit(GpuProgramType gptype, UINT32 unit);
+	private:
+		UINT32 mScissorTop, mScissorBottom, mScissorLeft, mScissorRight;
+		UINT32 mViewportLeft, mViewportTop, mViewportWidth, mViewportHeight;
 
-		/**
-		 * @brief	OpenGL shares all buffer bindings, but the engine prefers to keep buffers
-		 * 			separate per-stage. This will convert block buffer binding that is set per stage
-		 * 			into a global block buffer binding usable by OpenGL.
-		 */
-		UINT32 getGLUniformBlockBinding(GpuProgramType gptype, UINT32 binding);
+		UINT32 mStencilReadMask;
+		UINT32 mStencilWriteMask;
+		UINT32 mStencilRefValue;
+		CompareFunction mStencilCompareFront;
+		CompareFunction mStencilCompareBack;
 
-		/**
-		 * @brief	Returns the OpenGL specific mode used for drawing, depending on the
-		 * 			currently set draw operation;
-		 */
-		GLint getGLDrawMode() const;
+		// View matrix to set world against
+		Matrix4 mViewMatrix;
 
-		/**
-		 * @brief	Call before doing a draw operation, this method sets everything up.
-		 */
-		void beginDraw();
+		// Last min & mip filtering options, so we can combine them
+		FilterOptions mMinFilter;
+		FilterOptions mMipFilter;
 
-		/**
-		 * @brief	Needs to accompany every beginDraw after you are done with a single draw operation.
-		 */
-		void endDraw();
+		// Holds texture type settings for every stage
+		UINT32	mNumTextureTypes;
+		GLenum* mTextureTypes;
 
-		void clearArea(UINT32 buffers, const Color& color = Color::Black, float depth = 1.0f, UINT16 stencil = 0, const RectI& clearArea = RectI::EMPTY);
+		bool mDepthWrite;
+		bool mColorWrite[4];
 
-		void setActiveProgram(GpuProgramType gptype, GLSLGpuProgramPtr program);
-		GLSLGpuProgramPtr getActiveProgram(GpuProgramType gptype) const;
+		GLSupport* mGLSupport;
+		bool mGLInitialised;
+
+		GLSLProgramFactory* mGLSLProgramFactory;
+		GLSLProgramPipelineManager* mProgramPipelineManager;
+
+		GLSLGpuProgramPtr mCurrentVertexProgram;
+		GLSLGpuProgramPtr mCurrentFragmentProgram;
+		GLSLGpuProgramPtr mCurrentGeometryProgram;
+		GLSLGpuProgramPtr mCurrentHullProgram;
+		GLSLGpuProgramPtr mCurrentDomainProgram;
+
+		const GLSLProgramPipeline* mActivePipeline;
+
+		UINT32 mFragmentTexOffset;
+		UINT32 mVertexTexOffset;
+		UINT32 mGeometryTexOffset;
+
+		UINT32 mFragmentUBOffset;
+		UINT32 mVertexUBOffset;
+		UINT32 mGeometryUBOffset;
+		UINT32 mHullUBOffset;
+		UINT32 mDomainUBOffset;
+		UINT32 mComputeUBOffset;
+
+		UnorderedMap<UINT32, VertexBufferPtr> mBoundVertexBuffers;
+		VertexDeclarationPtr mBoundVertexDeclaration;
+		IndexBufferPtr mBoundIndexBuffer;
+		DrawOperationType mCurrentDrawOperation;
+
+		GLContext *mMainContext;
+		GLContext *mCurrentContext;
+
+		Vector<GLuint> mBoundAttributes; // Only full between begin/endDraw calls
+		bool mDrawCallInProgress;
+
+		UINT16 mActiveTextureUnit;
     };
 }
-#endif
-

+ 61 - 103
CamelotGLRenderer/Include/CmGLSupport.h

@@ -1,111 +1,69 @@
-/*
------------------------------------------------------------------------------
-This source file is part of OGRE
-    (Object-oriented Graphics Rendering Engine)
-For the latest info, see http://www.ogre3d.org/
-
-Copyright (c) 2000-2011 Torus Knot Software Ltd
-
-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 OGRE_GLSUPPORT_H
-#define OGRE_GLSUPPORT_H
+#pragma once
 
 #include "CmGLPrerequisites.h"
 #include "CmGLRenderSystem.h"
-
 #include "CmRenderWindow.h"
 
 namespace BansheeEngine
 {
-    
-class CM_RSGL_EXPORT GLSupport
-{
-public:
-    GLSupport() { }
-    virtual ~GLSupport() { }
-
-	virtual RenderWindowPtr newWindow(RENDER_WINDOW_DESC& desc, RenderWindowPtr parentWindow) = 0;
-
-    virtual bool supportsPBuffers();
-
-    /**
-    * Start anything special
-    */
-    virtual void start() = 0;
-    /**
-    * Stop anything special
-    */
-    virtual void stop() = 0;
-
-    /**
-    * Get vendor information
-    */
-    const String& getGLVendor(void) const
-    {
-        return mVendor;
-    }
-
-    /**
-    * Get version information
-    */
-    const String& getGLVersion(void) const
-    {
-        return mVersion;
-    }
-
-    /**
-    * Compare GL version numbers
-    */
-    bool checkMinGLVersion(const String& v) const;
-
-    /**
-    * Check if an extension is available
-    */
-    virtual bool checkExtension(const String& ext) const;
-    /**
-    * Get the address of a function
-    */
-    virtual void* getProcAddress(const String& procname) = 0;
-
-    /** Initialises GL extensions, must be done AFTER the GL context has been
-        established.
-    */
-    virtual void initialiseExtensions();
-
-	/// @copydoc RenderSystem::getDisplayMonitorCount
-	virtual unsigned int getDisplayMonitorCount() const
+	class CM_RSGL_EXPORT GLSupport
 	{
-		return 1;
-	}
-
-protected:
-
-	// This contains the complete list of supported extensions
-    Set<String> extensionList;
-private:
-    String mVersion;
-    String mVendor;
-
-}; // class GLSupport
-
-};
-
-#endif 
+	public:
+		GLSupport() { }
+		virtual ~GLSupport() { }
+
+		virtual RenderWindowPtr newWindow(RENDER_WINDOW_DESC& desc, RenderWindowPtr parentWindow) = 0;
+
+		/**
+		* Start anything special
+		*/
+		virtual void start() = 0;
+
+		/**
+		* Stop anything special
+		*/
+		virtual void stop() = 0;
+
+		/**
+		* Get vendor information
+		*/
+		const String& getGLVendor() const
+		{
+			return mVendor;
+		}
+
+		/**
+		* Get version information
+		*/
+		const String& getGLVersion() const
+		{
+			return mVersion;
+		}
+
+		/**
+		* Compare GL version numbers
+		*/
+		bool checkMinGLVersion(const String& v) const;
+
+		/**
+		* Check if an extension is available
+		*/
+		virtual bool checkExtension(const String& ext) const;
+
+		/**
+		* Get the address of a function
+		*/
+		virtual void* getProcAddress(const String& procname) = 0;
+
+		/** Initialises GL extensions, must be done AFTER the GL context has been
+			established.
+		*/
+		virtual void initialiseExtensions();
+
+	protected:
+		Set<String> extensionList;
+
+		String mVersion;
+		String mVendor;
+	};
+};

+ 7 - 37
CamelotGLRenderer/Include/CmWin32Context.h

@@ -1,43 +1,14 @@
-/*
------------------------------------------------------------------------------
-This source file is part of OGRE
-    (Object-oriented Graphics Rendering Engine)
-For the latest info, see http://www.ogre3d.org/
-
-Copyright (c) 2000-2011 Torus Knot Software Ltd
-
-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 __OgreW32Context_H__
-#define __OgreW32Context_H__
+#pragma once
 
 #include "CmWin32Prerequisites.h"
 #include "CmGLContext.h"
 
-namespace BansheeEngine {
-
-    class CM_RSGL_EXPORT Win32Context: public GLContext
+namespace BansheeEngine 
+{
+    class CM_RSGL_EXPORT Win32Context : public GLContext
     {
     public:
-        Win32Context(HDC     HDC,
-                     HGLRC   Glrc);
+        Win32Context(HDC hdc, HGLRC glrc, bool ownsContext);
         virtual ~Win32Context();
 
         /** See GLContext */
@@ -50,7 +21,6 @@ namespace BansheeEngine {
 	protected:
         HDC     mHDC;
         HGLRC   mGlrc;
+		bool	mOwnsContext;
     };
-}
-
-#endif
+}

+ 6 - 24
CamelotGLRenderer/Include/CmWin32GLSupport.h

@@ -1,5 +1,4 @@
-#ifndef __OgreWin32GLSupport_H__
-#define __OgreWin32GLSupport_H__
+#pragma once
 
 #include "CmWin32Prerequisites.h"
 #include "CmGLSupport.h"
@@ -7,7 +6,6 @@
 
 namespace BansheeEngine
 {
-    
 	class CM_RSGL_EXPORT Win32GLSupport : public GLSupport
 	{
 	public:
@@ -20,6 +18,7 @@ namespace BansheeEngine
 		* Start anything special
 		*/
 		void start();
+
 		/**
 		* Stop anything special
 		*/
@@ -31,15 +30,13 @@ namespace BansheeEngine
 		void* getProcAddress(const String& procname);
 
 		/**
-		 * Initialise extensions
+		 * Initialize extensions
 		 */
 		virtual void initialiseExtensions();
 		
+		Win32Context* createContext(HDC hdc, HGLRC externalGlrc = 0);
 
 		bool selectPixelFormat(HDC hdc, int colourDepth, int multisample, bool hwGamma);
-
-		virtual bool supportsPBuffers();
-		virtual unsigned int getDisplayMonitorCount() const;
 	private:
 		// Allowed video modes
 		Vector<DEVMODE> mDevModes;
@@ -48,24 +45,9 @@ namespace BansheeEngine
 		bool mHasPixelFormatARB;
         bool mHasMultisample;
 		bool mHasHardwareGamma;
-
-		struct DisplayMonitorInfo
-		{
-			HMONITOR		hMonitor;
-			MONITORINFOEX	monitorInfoEx;
-		};
-
-		typedef Vector<DisplayMonitorInfo> DisplayMonitorInfoList;
-		typedef DisplayMonitorInfoList::iterator DisplayMonitorInfoIterator;
-
-		DisplayMonitorInfoList mMonitorInfoList;
+		bool mHasAdvancedContext;
 
 		void initialiseWGL();
 		static LRESULT CALLBACK dummyWndProc(HWND hwnd, UINT umsg, WPARAM wp, LPARAM lp);
-		static BOOL CALLBACK sCreateMonitorsInfoEnumProc(HMONITOR hMonitor, HDC hdcMonitor, 
-			LPRECT lprcMonitor, LPARAM dwData);
 	};
-
-}
-
-#endif
+}

+ 12 - 41
CamelotGLRenderer/Include/CmWin32Window.h

@@ -1,31 +1,3 @@
-/*
------------------------------------------------------------------------------
-This source file is part of OGRE
-    (Object-oriented Graphics Rendering Engine)
-For the latest info, see http://www.ogre3d.org/
-
-Copyright (c) 2000-2011 Torus Knot Software Ltd
-
-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
 
 #include "CmWin32Prerequisites.h"
@@ -125,19 +97,6 @@ namespace BansheeEngine
 
 		Win32Window(const RENDER_WINDOW_DESC& desc, Win32GLSupport &glsupport);
 
-		Win32GLSupport &mGLSupport;
-		HWND	mHWnd;					// Win32 Window handle
-		HDC		mHDC;
-		HGLRC	mGlrc;
-        bool    mIsExternal;
-		char*   mDeviceName;
-		bool    mIsExternalGLControl;
-		bool	mIsExternalGLContext;
-        bool    mSizing;
-		bool	mClosed;
-        int     mDisplayFrequency;      // fullscreen only, to restore display
-        Win32Context *mContext;
-
 		/**
 		 * @copydoc RenderWindow::initialize_internal().
 		 */
@@ -147,5 +106,17 @@ namespace BansheeEngine
 		 * @copydoc RenderWindow::destroy_internal().
 		 */
 		void destroy_internal();
+
+		protected:
+			Win32GLSupport &mGLSupport;
+			HWND	mHWnd;					// Win32 Window handle
+			HDC		mHDC;
+			bool    mIsExternal;
+			char*   mDeviceName;
+			bool    mIsExternalGLControl;
+			bool    mSizing;
+			bool	mClosed;
+			int     mDisplayFrequency;      // fullscreen only, to restore display
+			Win32Context *mContext;
     };
 }

File diff suppressed because it is too large
+ 219 - 374
CamelotGLRenderer/Source/CmGLRenderSystem.cpp


+ 6 - 37
CamelotGLRenderer/Source/CmGLSupport.cpp

@@ -1,44 +1,18 @@
-
-/*
------------------------------------------------------------------------------
-This source file is part of OGRE
-    (Object-oriented Graphics Rendering Engine)
-For the latest info, see http://www.ogre3d.org/
-
-Copyright (c) 2000-2011 Torus Knot Software Ltd
-
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in
-all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-THE SOFTWARE.
------------------------------------------------------------------------------
-*/
-
-
 #include "CmGLSupport.h"
 #include "CmGLTexture.h"
+#include "GL/glew.h"
+
+GLenum GLEWAPIENTRY glewContextInit(BansheeEngine::GLSupport *glSupport);
 
 namespace BansheeEngine
 {
-    void GLSupport::initialiseExtensions(void)
+    void GLSupport::initialiseExtensions()
     {
+		glewContextInit(this);
+
         // Set version string
         const GLubyte* pcVer = glGetString(GL_VERSION);
 
-
         assert(pcVer && "Problems getting GL version string using glGetString");
        
         String tmpStr = (const char*)pcVer;
@@ -108,9 +82,4 @@ namespace BansheeEngine
         
         return true;
     }
-    
-    bool GLSupport::supportsPBuffers()
-    {
-        return (GLEW_ARB_pixel_buffer_object || GLEW_EXT_pixel_buffer_object) != GL_FALSE;
-    }
 }

+ 95 - 154
CamelotGLRenderer/Source/CmWin32GLSupport.cpp

@@ -1,28 +1,16 @@
-#include "CmException.h"
-
-#include <algorithm>
-
 #include "CmWin32GLSupport.h"
 #include "CmGLTexture.h"
 #include "CmWin32Window.h"
+#include "CmGLRenderSystem.h"
+#include "CmWin32Context.h"
+#include "CmException.h"
+#include "GL/wglew.h"
+#include <algorithm>
 
-#if CM_THREAD_SUPPORT != 1
 GLenum __stdcall wglewContextInit (BansheeEngine::GLSupport *glSupport);
-#endif
 
 namespace BansheeEngine 
 {
-	Win32GLSupport::Win32GLSupport()
-        : mInitialWindow(0)
-        , mHasPixelFormatARB(false)
-        , mHasMultisample(false)
-		, mHasHardwareGamma(false)
-    {
-		// immediately test WGL_ARB_pixel_format and FSAA support
-		// so we can set configuration options appropriately
-		initialiseWGL();
-    } 
-
 	template<class C> void remove_duplicates(C& c)
 	{
 		std::sort(c.begin(), c.end());
@@ -30,28 +18,12 @@ namespace BansheeEngine
 		c.erase(p, c.end());
 	}
 
-	BOOL CALLBACK Win32GLSupport::sCreateMonitorsInfoEnumProc(
-		HMONITOR hMonitor,  // handle to display monitor
-		HDC hdcMonitor,     // handle to monitor DC
-		LPRECT lprcMonitor, // monitor intersection rectangle
-		LPARAM dwData       // data
-		)
-	{
-		DisplayMonitorInfoList* pArrMonitorsInfo = (DisplayMonitorInfoList*)dwData;
-
-		// Get monitor info
-		DisplayMonitorInfo displayMonitorInfo;
-
-		displayMonitorInfo.hMonitor = hMonitor;
-
-		memset(&displayMonitorInfo.monitorInfoEx, 0, sizeof(MONITORINFOEX));
-		displayMonitorInfo.monitorInfoEx.cbSize = sizeof(MONITORINFOEX);
-		GetMonitorInfo(hMonitor, &displayMonitorInfo.monitorInfoEx);
-
-		pArrMonitorsInfo->push_back(displayMonitorInfo);
-
-		return TRUE;
-	}
+	Win32GLSupport::Win32GLSupport()
+        : mInitialWindow(0), mHasPixelFormatARB(false), mHasMultisample(false), 
+		mHasHardwareGamma(false), mHasAdvancedContext(false)
+    {
+		initialiseWGL();
+    } 
 
 	RenderWindowPtr Win32GLSupport::newWindow(RENDER_WINDOW_DESC& desc, RenderWindowPtr parentWindow)
 	{		
@@ -64,41 +36,6 @@ namespace BansheeEngine
 
 		Win32Window* window = new (cm_alloc<Win32Window, PoolAlloc>()) Win32Window(desc, *this);
 		
-		// TODO - Looking for monitors is disabled for now, as it should be done on the core thread and I need to port it but 
-		//  I don't feel like it at the moment. Plus I'll probably implemented a more streamlined approach to this anyway.
-
-		//HMONITOR hMonitor = NULL;
-		//int monitorIndex = desc.monitorIndex;
-		//
-		//// If monitor index found, try to assign the monitor handle based on it.
-		//if(monitorIndex >= 0)
-		//{
-		//	if (mMonitorInfoList.empty())		
-		//		EnumDisplayMonitors(NULL, NULL, sCreateMonitorsInfoEnumProc, (LPARAM)&mMonitorInfoList);			
-
-		//	if (monitorIndex < (int)mMonitorInfoList.size())					
-		//		hMonitor = mMonitorInfoList[monitorIndex].hMonitor;	
-		//}
-
-		//// If we didn't specified the monitor index, or if it didn't find it
-		//if (hMonitor == NULL)
-		//{
-		//	POINT windowAnchorPoint;
-		//
-		//	// Fill in anchor point.
-		//	windowAnchorPoint.x = desc.left;
-		//	windowAnchorPoint.y = desc.top;
-
-
-		//	// Get the nearest monitor to this window.
-		//	hMonitor = MonitorFromPoint(windowAnchorPoint, MONITOR_DEFAULTTONEAREST);				
-		//}
-
-		//RENDER_WINDOW_DESC newDesc = desc;
-		//newDesc.platformSpecific["monitorHandle"] = toString((size_t)hMonitor);
-
-		//window->initialize(newDesc);
-
 		if(!mInitialWindow)
 			mInitialWindow = window;
 
@@ -111,24 +48,22 @@ namespace BansheeEngine
 
 	void Win32GLSupport::stop()
 	{
-		mInitialWindow = 0; // Since there is no removeWindow, although there should be...
+		mInitialWindow = nullptr;
 	}
 
 	void Win32GLSupport::initialiseExtensions()
 	{
-		assert(mInitialWindow);
-		// First, initialise the normal extensions
+		assert(mInitialWindow != nullptr);
+		
 		GLSupport::initialiseExtensions();
-		// wglew init
-#if CM_THREAD_SUPPORT != 1
+
 		wglewContextInit(this);
-#endif
 
 		// Check for W32 specific extensions probe function
-		PFNWGLGETEXTENSIONSSTRINGARBPROC _wglGetExtensionsString = 
-			(PFNWGLGETEXTENSIONSSTRINGARBPROC)wglGetProcAddress("wglGetExtensionsString");
-		if(!_wglGetExtensionsString)
+		PFNWGLGETEXTENSIONSSTRINGARBPROC _wglGetExtensionsString = (PFNWGLGETEXTENSIONSSTRINGARBPROC)wglGetProcAddress("wglGetExtensionsString");
+		if(_wglGetExtensionsString == nullptr)
 			return;
+
 		const char *wgl_extensions = _wglGetExtensionsString(mInitialWindow->_getHDC());
 
 		// Parse them, and add them to the main list
@@ -141,34 +76,71 @@ namespace BansheeEngine
         }
 	}
 
+	Win32Context* Win32GLSupport::createContext(HDC hdc, HGLRC externalGlrc)
+	{
+		GLRenderSystem* rs = static_cast<GLRenderSystem*>(RenderSystem::instancePtr());
+
+		// If RenderSystem has initialized a context use that, otherwise we create our own
+		HGLRC glrc = externalGlrc;
+		bool createdNew = false;
+		if (!rs->isContextInitialized())
+		{
+			if (externalGlrc == 0)
+			{
+				if (mHasAdvancedContext)
+				{
+					int attribs[40];
+					int i = 0;
+
+					attribs[i++] = WGL_CONTEXT_MAJOR_VERSION_ARB;
+					attribs[i++] = 4;
+					attribs[i++] = WGL_CONTEXT_MINOR_VERSION_ARB;
+					attribs[i++] = 3;
+					attribs[i++] = WGL_CONTEXT_PROFILE_MASK_ARB;
+					attribs[i++] = WGL_CONTEXT_CORE_PROFILE_BIT_ARB;
+
+#if CM_DEBUG_MODE
+					attribs[i++] = WGL_CONTEXT_FLAGS_ARB;
+					attribs[i++] = WGL_CONTEXT_DEBUG_BIT_ARB;				
+#endif
+
+					attribs[i++] = 0;
+					glrc = wglCreateContextAttribsARB(hdc, 0, attribs);
+				}
+				else
+					glrc = wglCreateContext(hdc);
+
+				if (glrc == 0)
+					CM_EXCEPT(RenderingAPIException, "wglCreateContext failed: " + translateWGLError());
+
+				createdNew = true;
+			}
+		}
+		else
+		{
+			rs->getMainContext()->setCurrent();
+			glrc = wglGetCurrentContext();
+		}
+
+		return cm_new<Win32Context>(hdc, glrc, createdNew);
+	}
 
 	void* Win32GLSupport::getProcAddress(const String& procname)
 	{
-        	return (void*)wglGetProcAddress( procname.c_str() );
+        return (void*)wglGetProcAddress(procname.c_str());
 	}
+
 	void Win32GLSupport::initialiseWGL()
 	{
-		// wglGetProcAddress does not work without an active OpenGL context,
-		// but we need wglChoosePixelFormatARB's address before we can
-		// create our main window.  Thank you very much, Microsoft!
-		//
-		// The solution is to create a dummy OpenGL window first, and then
-		// test for WGL_ARB_pixel_format support.  If it is not supported,
-		// we make sure to never call the ARB pixel format functions.
-		//
-		// If is is supported, we call the pixel format functions at least once
-		// to initialise them (pointers are stored by glprocs.h).  We can also
-		// take this opportunity to enumerate the valid FSAA modes.
+		// We need to create a dummy context in order to get functions
+		// that allow us to create a more advanced context. It seems
+		// hacky but that's the only way to do it.
 		
-		LPCSTR dummyText = "OgreWglDummy";
+		LPCSTR dummyText = "Dummy";
 #ifdef CM_STATIC_LIB
-		HINSTANCE hinst = GetModuleHandle( NULL );
+		HINSTANCE hinst = GetModuleHandle(NULL);
 #else
-#  if CM_DEBUG_MODE == 1
-		HINSTANCE hinst = GetModuleHandle("RenderSystem_GL_d.dll");
-#  else
-		HINSTANCE hinst = GetModuleHandle("RenderSystem_GL.dll");
-#  endif
+		HINSTANCE hinst = GetModuleHandle(MODULE_NAME.c_str());
 #endif
 		
 		WNDCLASS dummyClass;
@@ -179,19 +151,14 @@ namespace BansheeEngine
 		dummyClass.lpszClassName = dummyText;
 		RegisterClass(&dummyClass);
 
-		HWND hwnd = CreateWindow(dummyText, dummyText,
-			WS_POPUP | WS_CLIPCHILDREN,
+		HWND hwnd = CreateWindow(dummyText, dummyText, WS_POPUP | WS_CLIPCHILDREN,
 			0, 0, 32, 32, 0, 0, hinst, 0);
 
-		// if a simple CreateWindow fails, then boy are we in trouble...
-		if (hwnd == NULL)
+		if (hwnd == nullptr)
 			CM_EXCEPT(RenderingAPIException, "CreateWindow() failed");
 
-
-		// no chance of failure and no need to release thanks to CS_OWNDC
 		HDC hdc = GetDC(hwnd); 
 
-		// assign a simple OpenGL pixel format that everyone supports
 		PIXELFORMATDESCRIPTOR pfd;
 		memset(&pfd, 0, sizeof(PIXELFORMATDESCRIPTOR));
 		pfd.nSize = sizeof(PIXELFORMATDESCRIPTOR);
@@ -201,7 +168,6 @@ namespace BansheeEngine
 		pfd.dwFlags = PFD_DRAW_TO_WINDOW|PFD_SUPPORT_OPENGL|PFD_DOUBLEBUFFER;
 		pfd.iPixelType = PFD_TYPE_RGBA;
 		
-		// if these fail, wglCreateContext will also quietly fail
 		int format;
 		if ((format = ChoosePixelFormat(hdc, &pfd)) != 0)
 			SetPixelFormat(hdc, format, &pfd);
@@ -215,11 +181,19 @@ namespace BansheeEngine
 			wglMakeCurrent(hdc, hrc);
 			
 			PFNWGLGETEXTENSIONSSTRINGARBPROC _wglGetExtensionsStringARB =
-				(PFNWGLGETEXTENSIONSSTRINGARBPROC)
-				wglGetProcAddress("wglGetExtensionsStringARB");
+				(PFNWGLGETEXTENSIONSSTRINGARBPROC)wglGetProcAddress("wglGetExtensionsStringARB");
 			
-			// check for pixel format and multisampling support
-			if (_wglGetExtensionsStringARB)
+			PFNWGLCREATECONTEXTATTRIBSARBPROC _wglCreateContextAttribsARB = 
+				(PFNWGLCREATECONTEXTATTRIBSARBPROC)wglGetProcAddress("wglCreateContextAttribsARB");
+
+			if (_wglCreateContextAttribsARB != nullptr)
+			{
+				WGLEW_GET_FUN(__wglewCreateContextAttribsARB) = (PFNWGLCREATECONTEXTATTRIBSARBPROC)wglGetProcAddress("wglChoosePixelFormatARB");
+				mHasAdvancedContext = true;
+			}
+
+			// Check for pixel format and multisampling support
+			if (_wglGetExtensionsStringARB != nullptr)
 			{
 				std::istringstream wglexts(_wglGetExtensionsStringARB(hdc));
 				String ext;
@@ -236,28 +210,20 @@ namespace BansheeEngine
 
 			if (mHasPixelFormatARB && mHasMultisample)
 			{
-				// enumerate all formats w/ multisampling
+				// Enumerate all formats w/ multisampling
 				static const int iattr[] = {
 					WGL_DRAW_TO_WINDOW_ARB, GL_TRUE,
 					WGL_SUPPORT_OPENGL_ARB, GL_TRUE,
 					WGL_DOUBLE_BUFFER_ARB, GL_TRUE,
 					WGL_SAMPLE_BUFFERS_ARB, GL_TRUE,
 					WGL_ACCELERATION_ARB, WGL_FULL_ACCELERATION_ARB,
-                    /* We are no matter about the colour, depth and stencil buffers here
-					WGL_COLOR_BITS_ARB, 24,
-					WGL_ALPHA_BITS_ARB, 8,
-					WGL_DEPTH_BITS_ARB, 24,
-					WGL_STENCIL_BITS_ARB, 8,
-                    */
 					WGL_SAMPLES_ARB, 2,
 					0
 				};
+
 				int formats[256];
 				unsigned int count;
-                // cheating here.  wglChoosePixelFormatARB procc address needed later on
-                // when a valid GL context does not exist and glew is not initialized yet.
-                WGLEW_GET_FUN(__wglewChoosePixelFormatARB) =
-                    (PFNWGLCHOOSEPIXELFORMATARBPROC)wglGetProcAddress("wglChoosePixelFormatARB");
+                WGLEW_GET_FUN(__wglewChoosePixelFormatARB) = (PFNWGLCHOOSEPIXELFORMATARBPROC)wglGetProcAddress("wglChoosePixelFormatARB");
                 if (WGLEW_GET_FUN(__wglewChoosePixelFormatARB)(hdc, iattr, 0, 256, formats, &count))
                 {
                     // determine what multisampling levels are offered
@@ -315,7 +281,6 @@ namespace BansheeEngine
 		
 		if ((multisample || hwGamma) && WGLEW_GET_FUN(__wglewChoosePixelFormatARB))
 		{
-
 			// Use WGL to test extended caps (multisample, sRGB)
 			Vector<int> attribList;
 			attribList.push_back(WGL_DRAW_TO_WINDOW_ARB); attribList.push_back(GL_TRUE);
@@ -332,13 +297,11 @@ namespace BansheeEngine
 			{
 				attribList.push_back(WGL_FRAMEBUFFER_SRGB_CAPABLE_EXT); attribList.push_back(GL_TRUE);
 			}
+
 			// terminator
 			attribList.push_back(0);
 
-
 			UINT nformats;
-			// ChoosePixelFormatARB proc address was obtained when setting up a dummy GL context in initialiseWGL()
-			// since glew hasn't been initialized yet, we have to cheat and use the previously obtained address
 			if (!WGLEW_GET_FUN(__wglewChoosePixelFormatARB)(hdc, &(attribList[0]), NULL, 1, &format, &nformats) || nformats <= 0)
 				return false;
 		}
@@ -347,23 +310,9 @@ namespace BansheeEngine
 			format = ChoosePixelFormat(hdc, &pfd);
 		}
 
-
 		return (format && SetPixelFormat(hdc, format, &pfd));
 	}
 
-	bool Win32GLSupport::supportsPBuffers()
-	{
-		return WGLEW_GET_FUN(__WGLEW_ARB_pbuffer) != GL_FALSE;
-	}
-
-	unsigned int Win32GLSupport::getDisplayMonitorCount() const
-	{
-		if (mMonitorInfoList.empty())		
-			EnumDisplayMonitors(NULL, NULL, sCreateMonitorsInfoEnumProc, (LPARAM)&mMonitorInfoList);
-
-		return (unsigned int)mMonitorInfoList.size();
-	}
-
 	String translateWGLError()
 	{
 		int winError = GetLastError();
@@ -371,18 +320,10 @@ namespace BansheeEngine
 		int i;
 
 		// Try windows errors first
-		i = FormatMessage(
-			FORMAT_MESSAGE_FROM_SYSTEM |
-			FORMAT_MESSAGE_IGNORE_INSERTS,
-			NULL,
-			winError,
-			MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
-			(LPTSTR) errDesc,
-			255,
-			NULL
-			);
+		i = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
+			NULL, winError, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
+			(LPTSTR) errDesc, 255, NULL);
 
 		return String(errDesc);
 	}
-
 }

+ 8 - 82
CamelotGLRenderer/Source/CmWin32Window.cpp

@@ -1,34 +1,7 @@
-/*
------------------------------------------------------------------------------
-This source file is part of OGRE
-(Object-oriented Graphics Rendering Engine)
-For the latest info, see http://www.ogre3d.org/
-
-Copyright (c) 2000-2011 Torus Knot Software Ltd
-
-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 _WIN32_WINNT
 #define _WIN32_WINNT 0x0500
 #endif
+
 #include "CmWin32Window.h"
 #include "CmInput.h"
 #include "CmRenderSystem.h"
@@ -39,6 +12,8 @@ THE SOFTWARE.
 #include "CmPlatformWndProc.h"
 #include "CmGLPixelFormat.h"
 
+GLenum GLEWAPIENTRY wglewContextInit(BansheeEngine::GLSupport *glSupport);
+
 namespace BansheeEngine 
 {
 	#define _MAX_CLASS_NAME_ 128
@@ -50,10 +25,8 @@ namespace BansheeEngine
 	{
 		mIsFullScreen = false;
 		mHWnd = 0;
-		mGlrc = 0;
 		mIsExternal = false;
 		mIsExternalGLControl = false;
-		mIsExternalGLContext = false;
 		mSizing = false;
 		mClosed = false;
 		mDisplayFrequency = 0;
@@ -69,9 +42,9 @@ namespace BansheeEngine
 	void Win32Window::initialize_internal()
 	{
 #ifdef CM_STATIC_LIB
-		HINSTANCE hInst = GetModuleHandle( NULL );
+		HINSTANCE hInst = GetModuleHandle(NULL);
 #else
-		HINSTANCE hInst = GetModuleHandle("CamelotGLRenderSystem.dll");
+		HINSTANCE hInst = GetModuleHandle(MODULE_NAME.c_str());
 #endif
 
 		mHWnd = 0;
@@ -103,11 +76,10 @@ namespace BansheeEngine
 			}
 		}
 
+		HGLRC glrc = 0;
 		if ((opt = mDesc.platformSpecific.find("externalGLContext")) != end)
 		{
-			mGlrc = (HGLRC)parseUnsignedLong(opt->second);
-			if( mGlrc )
-				mIsExternalGLContext = true;
+			glrc = (HGLRC)parseUnsignedLong(opt->second);
 		}
 
 		// incompatible with fullscreen
@@ -341,48 +313,7 @@ namespace BansheeEngine
 		}
 		
 		mActive = true;
-
-		GLRenderSystem* rs = static_cast<GLRenderSystem*>(RenderSystem::instancePtr());
-
-		// If RenderSystem has initialized a context use that, otherwise we create our own
-		if(!rs->isContextInitialized())
-		{
-			if (!mIsExternalGLContext)
-			{
-#if CM_DEBUG_MODE
-				if (wglewIsSupported("WGL_ARB_create_context"))
-				{
-					int contextAttribs[] =
-					{
-						WGL_CONTEXT_FLAGS_ARB,
-						WGL_CONTEXT_DEBUG_BIT_ARB,
-						0
-					};
-
-					mGlrc = wglCreateContextAttribsARB(mHDC, 0, contextAttribs);
-				}
-				else
-					mGlrc = wglCreateContext(mHDC);
-#else
-				mGlrc = wglCreateContext(mHDC);
-#endif
-
-
-				if (!mGlrc)
-				{
-					CM_EXCEPT(RenderingAPIException, 
-						"wglCreateContext failed: " + translateWGLError());
-				}
-			}
-		}
-		else
-		{
-			rs->getMainContext()->setCurrent();
-			mGlrc = wglGetCurrentContext();
-		}
-
-		// Create RenderSystem context
-		mContext = cm_new<Win32Context>(mHDC, mGlrc);
+		mContext = mGLSupport.createContext(mHDC, glrc);
 
 		RenderWindow::initialize_internal();
 	}
@@ -395,11 +326,6 @@ namespace BansheeEngine
 		// Unregister and destroy GLContext
 		cm_delete(mContext);
 
-		if (!mIsExternalGLContext && mGlrc)
-		{
-			wglDeleteContext(mGlrc);
-			mGlrc = 0;
-		}
 		if (!mIsExternal)
 		{
 			if (mIsFullScreen)

+ 13 - 62
CamelotGLRenderer/Source/win32/CmWin32Context.cpp

@@ -1,89 +1,40 @@
-/*
------------------------------------------------------------------------------
-This source file is part of OGRE
-    (Object-oriented Graphics Rendering Engine)
-For the latest info, see http://www.ogre3d.org/
-
-Copyright (c) 2000-2011 Torus Knot Software Ltd
-
-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 _WIN32_WINNT
 #define _WIN32_WINNT 0x0500
 #endif
+
 #include "CmWin32Context.h"
 #include "CmException.h"
 
-namespace BansheeEngine {
-
-    Win32Context::Win32Context(HDC     HDC,
-                 HGLRC   Glrc):
-        mHDC(HDC),
-        mGlrc(Glrc)
+namespace BansheeEngine 
+{
+    Win32Context::Win32Context(HDC hdc, HGLRC glrc, bool ownsContext):
+		mHDC(hdc), mGlrc(glrc), mOwnsContext(ownsContext)
     {
     }
     
     Win32Context::~Win32Context()
     {
-
+		if (mOwnsContext)
+			releaseContext();
     }
         
     void Win32Context::setCurrent()
     {
          wglMakeCurrent(mHDC, mGlrc);      
     }
+
 	void Win32Context::endCurrent()
 	{
-		wglMakeCurrent(NULL, NULL);
+		wglMakeCurrent(0, 0);
 	}
 
 	void Win32Context::releaseContext()
 	{
-		if (mGlrc != NULL)
+		if (mGlrc != 0)
 		{
 			wglDeleteContext(mGlrc);
-			mGlrc = NULL;
-			mHDC  = NULL;
+			mGlrc = 0;
+			mHDC  = 0;
 		}		
 	}
-}
-
-#if CM_THREAD_SUPPORT == 1
-
-// declared in CmGLPrerequisites.h 
-WGLEWContext * wglewGetContext()
-{
-	using namespace BansheeEngine;
-	static CM_THREAD_POINTER_VAR(WGLEWContext, WGLEWContextsPtr);
-
-	WGLEWContext * currentWGLEWContextsPtr = CM_THREAD_POINTER_GET(WGLEWContextsPtr);
-	if (currentWGLEWContextsPtr == NULL)
-	{
-		currentWGLEWContextsPtr = cm_new<WGLEWContext>();
-		CM_THREAD_POINTER_SET(WGLEWContextsPtr, currentWGLEWContextsPtr);
-		ZeroMemory(currentWGLEWContextsPtr, sizeof(WGLEWContext));
-		wglewInit();
-
-	}
-	return currentWGLEWContextsPtr;
-}
-
-#endif
+}

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