示例#1
0
void GLEngine::Init(HWND hWnd)
{
	logging::add_file_log("log.txt");
	m_hdc = GetDC(hWnd);
	
	m_viewManager = CreateManager();
	m_Object = m_viewManager->CreateObject();
	
	RECT rc;
	GetWindowRect(hWnd, &rc);
	m_camera.SetCenter(rc.left+(rc.right-rc.left)/2,rc.top+(rc.bottom-rc.top)/2);

	GLuint		PixelFormat;
	static	PIXELFORMATDESCRIPTOR pfd=				// pfd Tells Windows How We Want Things To Be
	{
		sizeof(PIXELFORMATDESCRIPTOR),				// Size Of This Pixel Format Descriptor
		1,											// Version Number
		PFD_DRAW_TO_WINDOW |						// Format Must Support Window
		PFD_SUPPORT_OPENGL |						// Format Must Support OpenGL
		PFD_DOUBLEBUFFER,							// Must Support Double Buffering
		PFD_TYPE_RGBA,								// Request An RGBA Format
		16,										// Select Our Color Depth
		0, 0, 0, 0, 0, 0,							// Color Bits Ignored
		0,											// No Alpha Buffer
		0,											// Shift Bit Ignored
		0,											// No Accumulation Buffer
		0, 0, 0, 0,									// Accumulation Bits Ignored
		16,											// 16Bit Z-Buffer (Depth Buffer)  
		0,											// No Stencil Buffer
		0,											// No Auxiliary Buffer
		PFD_MAIN_PLANE,								// Main Drawing Layer
		0,											// Reserved
		0, 0, 0										// Layer Masks Ignored
	};

	PixelFormat=ChoosePixelFormat(m_hdc, &pfd);	// Did Windows Find A Matching Pixel Format?

	BOOL res = SetPixelFormat(m_hdc, PixelFormat, &pfd);		// Are We Able To Set The Pixel Format?	

	m_hglrc = wglCreateContext(m_hdc);
	if(!m_hglrc)
	{
		BOOST_LOG_TRIVIAL(error) << "Error wglCreateContext: " << __LINE__;
		DWORD error = GetLastError();
	}

	if(!wglMakeCurrent(m_hdc, m_hglrc))
		BOOST_LOG_TRIVIAL(error) << "Error wglMakeCurrent: " << __LINE__;

	ResizeScene(800, 600);	
	InitGL();
	InitTextures();
}
示例#2
0
int main(){
	auto pLogger = CB::Log::CLogger::GetInstance();
	pLogger->AddStream(CB::IO::File::Open(L"main.log", CB::IO::File::AccessType::WriteOnly, CB::IO::File::OpenAction::AlwaysCreate).Cast<CB::IO::IStream>());
	pLogger->AddStream(CB::IO::Console::Create().Cast<CB::IO::IStream>(), CB::Log::CTextFormatter::Create(CB::String::Encoding::ANSI).Cast<CB::Log::IEntryFormatter>());
	pLogger->SetDebugMode(true);

	try{
		auto pWinDriver = CB::Window::LoadDriver(L"MSWindowDriver");
		auto pGraphicDriver = CB::Graphic::LoadDriver(L"OGLGraphicDriver");
		{
			auto pWinManager = pWinDriver->CreateManager();
			auto pGraphicManager = pGraphicDriver->CreateManager(pWinManager);
			
			CB::Math::CSize outSize(640, 480);
			auto pWindow = pWinManager->CreateWindow(L"GraphicTest", CB::Window::Style::Single, outSize);

			auto pGraphicAdapter = pGraphicManager->GetDefaultAdapter();

			CB::Graphic::CDisplayMode dispMode(pWindow->GetSize(), 0, CB::Graphic::BufferFormat::B8G8R8X8);
			CB::Graphic::CDeviceDesc devDesc(pWindow, dispMode, CB::Graphic::BufferFormat::D24S8, false);

			CB::Collection::CList<CB::Graphic::FeatureLevel> featureLevels;
			featureLevels.Add(CB::Graphic::FeatureLevel::Level_1);

			auto pGraphicDevice = pGraphicAdapter->CreateDevice(pWindow, devDesc, featureLevels);

			pWindow->OnClose += CB::Signals::CFunc<const bool, CB::CRefPtr<CB::Window::IWindow>>(CloseEvent);

			pWindow->SetVisible(true);

			CB::Graphic::CDepthStencilStateDesc depthDesc;
			depthDesc.bDepthTestEnabled = true;
			depthDesc.uDepthFunction = CB::Graphic::CompareFunc::LessEqual;
			auto pDepthState = pGraphicDevice->CreateState(depthDesc);
			pGraphicDevice->SetState(pDepthState.Cast<CB::Graphic::IDeviceState>());

			CB::Graphic::CRasterizerStateDesc rastDesc;
			rastDesc.uCullMode = CB::Graphic::CullMode::None;
			auto pRastState = pGraphicDevice->CreateState(rastDesc);
			pGraphicDevice->SetState(pRastState.Cast<CB::Graphic::IDeviceState>());

			CB::Graphic::CBlendStateDesc blendDesc;
			blendDesc.ColorBlend.uDestOperand = CB::Graphic::BlendOption::OneMinusSourceAlpha;
			blendDesc.ColorBlend.uSourceOperand = CB::Graphic::BlendOption::SourceAlpha;
			blendDesc.ColorBlend.uOperation = CB::Graphic::BlendOperation::Add;
			blendDesc.AlphaBlend.uDestOperand = CB::Graphic::BlendOption::OneMinusSourceAlpha;
			blendDesc.AlphaBlend.uSourceOperand = CB::Graphic::BlendOption::SourceAlpha;
			blendDesc.AlphaBlend.uOperation = CB::Graphic::BlendOperation::Add;
			blendDesc.bEnabled[0] = true;
			auto pBlendState = pGraphicDevice->CreateState(blendDesc);
			pGraphicDevice->SetState(pBlendState.Cast<CB::Graphic::IDeviceState>());

			auto pFontManager = CB::Font::CManager::Create();

			auto pFontStream = CB::IO::File::Open(L"Assets/font.ttf").Cast<CB::IO::IStream>();
			auto pFont = pFontManager->Load(pFontStream);
			
			pFont->SelectFace(0);
			pFont->SetSize(24);

			CB::Collection::CList<CB::Tools::CFontCharDesc> charDescs;
			CB::Tools::CFontTextureGenerator fontGen(pGraphicDevice);

			fontGen.MaxTextureSize.Set(512, 512);
			auto pTexture = fontGen.Generate(pFont, charDescs);

			CB::Tools::CTextMeshGenerator textGen(charDescs);
			CB::Tools::CMeshRawIVT textMesh;

			textGen.Generate(L"Marek	M³ynarski!", textMesh);

			CB::Collection::CList<CB::Graphic::CVertexElement> vEls;
			vEls.Add(CB::Graphic::CVertexElement(0, L"vinput.vPosition", CB::Graphic::VertexType::Float, 3, 0));
			vEls.Add(CB::Graphic::CVertexElement(1, L"vinput.vTexCoord", CB::Graphic::VertexType::Float, 2, 0));

			GraphicTest::CShaderLoader shaders(pGraphicDevice, L"Shaders/TextureShader.cg");

			auto pTextDecl = pGraphicDevice->CreateVertexDeclaration(shaders.pVertexShader, vEls);

			auto pTextVertexBuffer = pGraphicDevice->CreateBuffer(CB::Graphic::BufferType::Vertex, CB::Graphic::BufferUsage::Dynamic, CB::Graphic::BufferAccess::Write, textMesh.Vertices);
			auto pTextTCoordBuffer = pGraphicDevice->CreateBuffer(CB::Graphic::BufferType::Vertex, CB::Graphic::BufferUsage::Dynamic, CB::Graphic::BufferAccess::Write, textMesh.TexCoords);
			auto pTextIndexBuffer = pGraphicDevice->CreateBuffer(CB::Graphic::BufferType::Index, CB::Graphic::BufferUsage::Dynamic, CB::Graphic::BufferAccess::Write, textMesh.Indices);

			float32 fAspect = (float32)outSize.Width / (float32)outSize.Height;
			CB::Math::CMatrix mProj = CB::Math::CMatrix::GetPerspective(fAspect, 60.0f, 1.0f, 100.0f);
			CB::Math::CMatrix mView = CB::Math::CMatrix::GetTranslation(-4.0f, 0.0f, -3.4f);
			CB::Math::CMatrix mModel = CB::Math::CMatrix::GetIdentity();

			shaders.pFragmentShader->SetSampler(L"texDiffuse", pTexture.Cast<CB::Graphic::IBaseTexture>());
			pTexture->SetFilters(CB::Graphic::TextureFilter::Linear, CB::Graphic::TextureFilter::Linear, CB::Graphic::TextureFilter::Linear);
			pTexture->SetAnisotropy(8);
			//g_pTexture = texture.pTexture;			

			while(g_bRun){
				pGraphicDevice->Clear(1.0f, 1);
				pGraphicDevice->Clear(CB::Math::CColor(1.0f, 0.5f, 0.0f, 1.0f));

				pGraphicDevice->BeginRender();

				pGraphicDevice->SetShader(shaders.pVertexShader);
				pGraphicDevice->SetShader(shaders.pFragmentShader);

				static float32 fV = 0.0f;
				fV += 20 * g_Timer.GetTimeDelta();
				mModel = CB::Math::CMatrix::GetRotation(CB::Math::AxisOrientation::AxisX, fV);

				shaders.pVertexShader->SetUniform(L"vinput.mProj", mProj);
				shaders.pVertexShader->SetUniform(L"vinput.mView", mView);
				shaders.pVertexShader->SetUniform(L"vinput.mModel", mModel);

				pGraphicDevice->SetVertexDeclaration(pTextDecl);
				pGraphicDevice->SetVertexBuffer(0, pTextVertexBuffer);
				pGraphicDevice->SetVertexBuffer(1, pTextTCoordBuffer);
				pGraphicDevice->SetIndexBuffer(pTextIndexBuffer);

				pGraphicDevice->RenderIndexed(textMesh.uNumberOfPolygons);

				pGraphicDevice->EndRender();

				g_Timer.Update();
				pWinManager->ProcessEvents();

				float fFPS = 1.0f / (g_Timer.GetTimeDelta() == 0.0f ? 1.0f : g_Timer.GetTimeDelta());
				uint32 uFPS = (uint32)fFPS;

				textMesh.Clear();
				textGen.Generate(L"FPS: " + CB::String::ToString(uFPS), textMesh);

				pTextVertexBuffer->LoadData(textMesh.Vertices);
				pTextTCoordBuffer->LoadData(textMesh.TexCoords);
				pTextIndexBuffer->LoadData(textMesh.Indices);

				pGraphicDevice->Swap();
			}

			g_pTexture.Release();
		}
	}
	catch(CB::Exception::CException& Exception){
		CB::Log::Write(Exception, CB::Log::LogLevel::Fatal);
		CB::Message::Show(Exception, CB::Message::Icon::Error);
	}
	return 0;
}
示例#3
0
int _tmain (int argc, TCHAR* argv[]) {

	if (argc < 2) {
		_tprintf(_T("Usage:\n"));
		_tprintf(_T("%s max_filename [manager [port]]\n"),argv[0]);
		return 1;
	}

	//-- Come up with a temporary path for creating archives
	if (!ExpandEnvironmentStrings(_T("%TEMP%"),work_path,MAX_PATH)) {
		if (!ExpandEnvironmentStrings(_T("%TMP%"),work_path,MAX_PATH)) {
			if (!ExpandEnvironmentStrings(_T("%HOMEPATH%"),work_path,MAX_PATH))
				_tcscpy(work_path,_T("c:\\"));
		}
	}

	if (work_path[_tcslen(work_path) - 1] != _T('\\'))
		_tcscat(work_path,_T("\\"));

	//-- Creates new manager access module instance
	MaxNetManager* manager = CreateManager();
	if (manager) {
		try {
			//-- Setup default manager port
			short port = DF_MGRPORT;
			//-- Placeholder for manager name
			TCHAR managername[MAX_PATH];
			//-- If we have a port defined, use it
			if (argc > 3)
				port = _ttoi(argv[3]);
			//-- If we have a host name (or ip address) for the manager, use it
			if (argc > 2)
				_tcscpy(managername,argv[2]);
			else {
				//-- Otherwise, find out who is the manager (if any)
				//   The API will broadcast a message looking for a
				//   manager using the given port. If a manager is
				//   found, its name/ip address will be placed in 
				//   "managername" below.
				if (!manager->FindManager(port,managername)) {
					_tprintf(_T("Could not find a Manager\n"));
					DestroyManager(manager);
					return 1;
				}
			}
			//-- Connect to the manager
			manager->Connect(port,managername);
			//-- We're connected. Sumbmit Job(s)...
			WIN32_FIND_DATA find;
			HANDLE findhandle = FindFirstFile(argv[1],&find);
			if (findhandle != INVALID_HANDLE_VALUE) {
				TCHAR opath[MAX_PATH],npath[MAX_PATH];
				_tsplitpath(argv[1],opath,npath,0,0);
				_tcscat(opath,npath);
				if (opath[_tcslen(opath) - 1] != _T('\\'))
					_tcscat(opath,_T("\\"));
				do {
					_tcscpy(npath,opath);
					_tcscat(npath,find.cFileName);
					_tprintf(_T("Submitting %s..."),find.cFileName);
					if (!assign_job(manager,npath))
						break;
					_tprintf(_T("\r%s Submitted successfully...\n"),find.cFileName);
				} while (FindNextFile(findhandle,&find));
				FindClose(findhandle);
			}
			manager->Disconnect();
		//-- Exception Handler
		} catch (MaxNet* maxerr) {
			_tprintf(_T("\n%s (0x%08X)\n"),maxerr->GetErrorText(),maxerr->GetError());
		}
		//-- Clean up manager instance
		DestroyManager(manager);
	}
	return 0;
}
示例#4
0
    void Entresol::ConstructFromXML(const String& EngineDataPath, const Mezzanine::ArchiveType ArchType, const String& InitializerFile)
    {
        //Add default manager factories
        AddAllEngineDefaultManagerFactories();
        //Set some sane Defaults for some values.
        this->ManualLoopBreak = false;

        // Create Ogre.
        SetupOgre();

        // Load the necessary plugins.
        SubSystemParticleFXPlugin = new Ogre::ParticleFXPlugin();
        Ogre::Root::getSingleton().installPlugin(SubSystemParticleFXPlugin);

        // Set up the data we'll be populating.
        XML::Attribute CurrAttrib;
        String GUIInit, ResourceInit, PluginsInit, LogFileName;
        String PluginExtension, PluginPath;

        // Create or set the resource manager.
        /// @todo This currently forces our default resource manager to be constructed, which isn't in line with our factory/initiailzation design.
        /// This should be addressed somehow.
        if(ResourceManager::SingletonValid())
            { AddManager(ResourceManager::GetSingletonPtr()); }
        else
            { AddManager(new ResourceManager(EngineDataPath, ArchType)); }

        // Open and load the initializer doc.
        ResourceManager* ResourceMan = GetResourceManager();
        /// @todo Replace this stack allocated stream for one initialized from the Resource Manager, after the system is ready.
        Resource::FileStream InitStream(InitializerFile,EngineDataPath);
        XML::Document InitDoc;
        XML::ParseResult DocResult = InitDoc.Load(InitStream);
        if( DocResult.Status != XML::StatusOk )
        {
            StringStream ExceptionStream;
            ExceptionStream << "Failed to parse XML file \"" << InitializerFile << "\".";
            MEZZ_EXCEPTION(Exception::SYNTAX_ERROR_EXCEPTION_XML,ExceptionStream.str());
        }
        XML::Node InitRoot = InitDoc.GetChild("InitializerRoot");
        if( InitRoot.Empty() )
        {
            StringStream ExceptionStream;
            ExceptionStream << "Failed to find expected Root node in \"" << InitializerFile << "\".";
            MEZZ_EXCEPTION(Exception::SYNTAX_ERROR_EXCEPTION_XML,ExceptionStream.str());
        }

        // Get the world settings and set them.
        XML::Node WorldSettings = InitRoot.GetChild("WorldSettings");
        for( XML::NodeIterator SetIt = WorldSettings.begin() ; SetIt != WorldSettings.end() ; ++SetIt )
        {
            String SecName = (*SetIt).Name();
            if( "FrameSettings" == SecName )
            {
                CurrAttrib = (*SetIt).GetAttribute("TargetFrameRate");
                if(CurrAttrib.Empty())
                {
                    CurrAttrib = (*SetIt).GetAttribute("TargetFrameTime");
                    if(!CurrAttrib.Empty())
                        SetTargetFrameTimeMicroseconds(CurrAttrib.AsWhole());
                }else{
                    this->SetTargetFrameRate(CurrAttrib.AsWhole());
                }
            }
            else
            {
                MEZZ_EXCEPTION(Exception::SYNTAX_ERROR_EXCEPTION_XML,String("Unknown WorldSetting ")+SecName);
            }

        }

        SetupLogging(LogFileName);

        // Get the other initializer files we'll be using, since we'll need the plugins initializer.
        XML::Node InitFiles = InitRoot.GetChild("OtherInitializers");
        for( XML::NodeIterator InitIt = InitFiles.begin() ; InitIt != InitFiles.end() ; ++InitIt )
        {
            String InitFileName = (*InitIt).Name();
            if( "PluginInit" == InitFileName )
            {
                CurrAttrib = (*InitIt).GetAttribute("FileName");
                if(!CurrAttrib.Empty())
                    PluginsInit = CurrAttrib.AsString();
            }
            else if( "ResourceInit" == InitFileName )
            {
                CurrAttrib = (*InitIt).GetAttribute("FileName");
                if(!CurrAttrib.Empty())
                    ResourceInit = CurrAttrib.AsString();
            }
            else if( "GUIInit" == InitFileName )
            {
                CurrAttrib = (*InitIt).GetAttribute("FileName");
                if(!CurrAttrib.Empty())
                    GUIInit = CurrAttrib.AsString();
            }
        }

        // Load additional resource groups
        /*if(!ResourceInit.empty())
        {
            /// @todo Replace this stack allocated stream for one initialized from the Resource Manager, after the system is ready.
            Resource::FileStream ResourceStream(ResourceInit,EngineDataPath);
            XML::Document ResourceDoc;
            ResourceDoc.Load(ResourceStream);
            // Get an iterator to the first resource group node, and declare them all.
            XML::Node ResourceLocations = ResourceDoc.GetChild("ResourceLocations");
            for( XML::NodeIterator GroupIt = ResourceLocations.begin() ; GroupIt != ResourceLocations.end() ; ++GroupIt )
            {
                String GroupName, GroupType, GroupPath;
                bool GroupRecursive = false;
                // Get the group path
                CurrAttrib = (*GroupIt).GetAttribute("GroupPath");
                if(!CurrAttrib.Empty())
                    GroupPath = CurrAttrib.AsString();
                // Get the group type
                CurrAttrib = (*GroupIt).GetAttribute("GroupType");
                if(!CurrAttrib.Empty())
                    GroupType = CurrAttrib.AsString();
                // Get the group name
                CurrAttrib = (*GroupIt).GetAttribute("GroupName");
                if(!CurrAttrib.Empty())
                    GroupName = CurrAttrib.AsString();
                // Get whether this is recursive
                CurrAttrib = (*GroupIt).GetAttribute("Recursive");
                if(!CurrAttrib.Empty())
                    GroupRecursive = StringTool::ConvertToBool(CurrAttrib.AsString());
                // Finally create the resource location.
                ResourceMan->AddAssetLocation(GroupPath,GroupType,GroupName,GroupRecursive);
            }
            // Get what resource groups should be initialized.
            XML::Node InitGroups = ResourceDoc.GetChild("InitGroups");
            for( XML::NodeIterator InitIt = InitGroups.begin() ; InitIt != InitGroups.end() ; ++InitIt )
            {
                String GroupName;
                CurrAttrib = (*InitIt).GetAttribute("GroupName");
                if(!CurrAttrib.Empty())
                    GroupName = CurrAttrib.AsString();
                ResourceMan->InitAssetGroup(GroupName);
            }
        }//*/

        // Create the requested managers and set their necessary values.
        XML::Node Managers = InitRoot.GetChild("Managers");
        for( XML::NodeIterator ManIt = Managers.begin() ; ManIt != Managers.end() ; ++ManIt )
        {
            CreateManager( (*ManIt).Name(), (*ManIt) );
        }

        // Load additional resource groups
        if(!ResourceInit.empty())
        {
            /// @todo Replace this stack allocated stream for one initialized from the Resource Manager, after the system is ready.
            Resource::FileStream ResourceStream(ResourceInit,EngineDataPath);
            XML::Document ResourceDoc;
            ResourceDoc.Load(ResourceStream);
            // Get an iterator to the first resource group node, and declare them all.
            XML::Node ResourceLocations = ResourceDoc.GetChild("ResourceLocations");
            for( XML::NodeIterator GroupIt = ResourceLocations.begin() ; GroupIt != ResourceLocations.end() ; ++GroupIt )
            {
                String GroupName, GroupPath;
                ArchiveType GroupType;
                bool GroupRecursive = false;
                // Get the group path
                CurrAttrib = (*GroupIt).GetAttribute("GroupPath");
                if(!CurrAttrib.Empty())
                    GroupPath = CurrAttrib.AsString();
                // Get the group type
                CurrAttrib = (*GroupIt).GetAttribute("GroupType");
                if(!CurrAttrib.Empty())
                    GroupType = ResourceManager::GetArchiveTypeFromString(CurrAttrib.AsString());
                // Get the group name
                CurrAttrib = (*GroupIt).GetAttribute("GroupName");
                if(!CurrAttrib.Empty())
                    GroupName = CurrAttrib.AsString();
                // Get whether this is recursive
                CurrAttrib = (*GroupIt).GetAttribute("Recursive");
                if(!CurrAttrib.Empty())
                    GroupRecursive = StringTools::ConvertToBool(CurrAttrib.AsString());
                // Finally create the resource location.
                ResourceMan->AddAssetLocation(GroupPath,GroupType,GroupName,GroupRecursive);
            }
            // Get what resource groups should be initialized.
            XML::Node InitGroups = ResourceDoc.GetChild("InitGroups");
            for( XML::NodeIterator InitIt = InitGroups.begin() ; InitIt != InitGroups.end() ; ++InitIt )
            {
                String GroupName;
                CurrAttrib = (*InitIt).GetAttribute("GroupName");
                if(!CurrAttrib.Empty())
                    GroupName = CurrAttrib.AsString();
                ResourceMan->InitAssetGroup(GroupName);
            }
        }

        // Configure the UI
        if(!GUIInit.empty())
        {
            /// @todo This is currently not implemented.
        }

        SanityChecks();
    }