Esempio n. 1
0
//*******************************************************************************
void CWaterEnvMap::renderTestMesh(IDriver &driver)
{
	doInit();
	CMaterial testMat;
	testMat.setLighting(false);
	testMat.texEnvOpRGB(0, CMaterial::Modulate);
	testMat.texEnvArg0RGB(0, CMaterial::Texture, CMaterial::SrcColor);
	testMat.texEnvArg0RGB(1, CMaterial::Diffuse, CMaterial::SrcColor);
	testMat.texEnvOpAlpha(0, CMaterial::Replace);
	testMat.texEnvArg0Alpha(0, CMaterial::Constant, CMaterial::SrcAlpha);
	testMat.texConstantColor(0, CRGBA(255, 255, 255, 255));
	testMat.setDoubleSided(true);
	testMat.setZWrite(false);
	testMat.setZFunc(CMaterial::always);
	// tmp : test cubemap
	driver.activeVertexProgram(&testMeshVP);
	driver.activeVertexBuffer(_TestVB);
	driver.activeIndexBuffer(_TestIB);
	driver.setConstantMatrix(0, IDriver::ModelViewProjection, IDriver::Identity); // tmp
	_MaterialPassThruZTest.setTexture(0, _EnvCubic);
	driver.setConstantMatrix(0, IDriver::ModelViewProjection, IDriver::Identity);
	driver.setConstant(4, 2.f, 1.f, 0.f, 0.f);
	//driver.renderTriangles(testMat, 0, TEST_VB_NUM_TRIS);
	driver.renderTriangles(_MaterialPassThruZTest, 0, TEST_VB_NUM_TRIS);
	driver.activeVertexProgram(NULL);
}
Esempio n. 2
0
/*************
 * DESCRIPTION:	Load a material and assign it to the selected material
 * INPUT:			-
 * OUTPUT:			-
 *************/
void CMatView::OnLoadMaterial()
{
    CString file;
    SURFACE *pSurf;
    CMaterial *pMaterial;
    char *szErr;

    if (!utility.FileRequ((char*)LPCTSTR(file), FILEREQU_MATERIAL, FILEREQU_INITIALFILE))
        return;

    pSurf = sciCreateSurface(NULL);
    if (!pSurf)
        return;

    szErr = pSurf->Load((char*)LPCTSTR(file));
    if (szErr)
    {
        delete pSurf;
        utility.Request(szErr);
    }
    else
    {
        if (nSelectedMaterial != -1)
        {
            pMaterial = ((CMaterial*)aMaterials[nSelectedMaterial]);
            delete pMaterial->pSurface;
            pMaterial->pSurface = pSurf;
            pMaterial->Update();
            Invalidate(FALSE);
        }
    }
}
Esempio n. 3
0
//-----------------------------------------------------------------------------
// Purpose: Factory. Creates a material by name.
// Input  : pszMaterialName - Name of material, ie "brick/brickfloor01".
// Output : Returns a pointer to the new material object, NULL if the given
//			material did not exist.
//-----------------------------------------------------------------------------
CMaterial *CMaterial::CreateMaterial(const char *pszMaterialName, bool bLoadImmediately, bool* pFound)
{
	Assert (pszMaterialName);

 	CMaterial *pMaterial = new CMaterial;
	Assert( pMaterial );

	// Store off the material name so we can load it later if we need to
	Q_snprintf( pMaterial->m_szFileName, MAX_PATH, pszMaterialName );
	Q_snprintf( pMaterial->m_szName, MAX_PATH, pszMaterialName );

	//
	// Find the material by name and load it.
	//
	if (bLoadImmediately)
	{
		bool bFound = pMaterial->LoadMaterial();

		// Returns if the material was found or not
		if (pFound)
			*pFound = bFound;
	}

	return pMaterial;
}
Esempio n. 4
0
void CRenderer::ProcessNode(CNode* node)
{
	std::vector<CNode*> *vec = node->GetNodeVector();

	//Обновляем нод, рендерим сущности
	//Log("Node is updated\n");
	glTranslatef(node->GetPosX(), node->GetPosY(), node->GetPosZ());

	for(int i = 0; i < node->GetObjVector()->size(); i++)
	{
		if(node->GetObjVector()->at(i)->GetType()==OBJECT_ENTITY)
		{
			//TO DO:
			//Берем шейдер, соотвутствующий сущности и активируем его
			//-----
			CMaterial* mat;
			CShader* sh;
			if((mat = ((CEntity*)node->GetObjVector()->at(i))->GetMaterial())!=0)
			{
				if((sh = mat->GetShader())!=0)
				{
					if(sh->IsCompiled())
					{
						glUseProgram(sh->GetProgramId());
					}
				}
			}
			DrawMesh(((CEntity*)node->GetObjVector()->at(i))->GetMesh());
			glUseProgram(0);
		}
	}
	
	glDisable(GL_DEPTH_TEST);
	glBegin(GL_LINES);
	glColor3f(0.5, 1, 0.5);
	glVertex3f(0, 0, 0);
	glVertex3f(0, 1, 0);
	glColor3f(1, 0.5, 0.5);
	glVertex3f(0, 0, 0);
	glVertex3f(1, 0, 0);
	glColor3f(0.5, 0.5, 1);
	glVertex3f(0, 0, 0);
	glVertex3f(0, 0, 1);
	glColor3f(1,1,1);
	glEnd();
	glEnable(GL_DEPTH_TEST);

	for(int i = 0; i < vec->size(); i++)
	{
		ProcessNode(vec->at(i));	
	}
	glTranslatef(-node->GetPosX(), -node->GetPosY(), -node->GetPosZ());
}
Esempio n. 5
0
triebWerk::CMaterial* triebWerk::CPostEffectDrawable::AddMaterial(const CMaterial * a_pMaterial)
{
	if (a_pMaterial == nullptr)
	{
		DebugLogfile.LogfText(CDebugLogfile::ELogType::Warning, false, "Warning: You can't add a empty material as PostEffect");
		return nullptr;
	}

	CMaterial* material = new CMaterial();
	material->SetMaterial(a_pMaterial);

	m_Materials.push_back(material);

	return material;
}
Esempio n. 6
0
CMaterial::CMaterial(const CMaterial& Other)
:CNamed(Other.GetName()+"_copy")
,m_CurrentParameterData(0)
,m_Offset(0)
{
	m_RenderableObjectTechnique = Other.GetRenderableObjectTechnique();
	m_StaticFriction = Other.GetStaticFriction();
	m_DynamicFriction = Other.GetDynamicFriction();
	m_Restitution = Other.GetRestitution();

	for (size_t i = 0; i < Other.GetTextures().size(); ++i)
	{
		m_Textures.push_back(Other.GetTextures()[i]);
	}

	for (size_t i = 0; i < Other.GetParameters().size(); ++i)
	{
		CMaterialParameter* l_OtherMaterialParameter = Other.GetParameters()[i];
		CMaterialParameter::TMaterialType l_MaterialType = l_OtherMaterialParameter->GetMaterialType();
		std::string l_OtherDescription = l_OtherMaterialParameter->GetDescription();
		std::string l_OtherName = l_OtherMaterialParameter->GetName();

		CMaterialParameter* l_MaterialParameter = nullptr;

		if (l_MaterialType == CMaterialParameter::TMaterialType::FLOAT)
		{
			l_MaterialType = CMaterialParameter::FLOAT;
			float l_Value = *((float*)l_OtherMaterialParameter->GetValueAddress());
			l_MaterialParameter = new CTemplatedMaterialParameter<float>(this, l_OtherName, l_OtherDescription, l_Value, l_MaterialType);

		}
		else if (l_MaterialType == CMaterialParameter::TMaterialType::VECT2F)
		{
			l_MaterialType = CMaterialParameter::VECT2F;
			Vect2f l_Value = *((Vect2f*)l_OtherMaterialParameter->GetValueAddress());
			l_MaterialParameter = new CTemplatedMaterialParameter<Vect2f>(this, l_OtherName, l_OtherDescription, l_Value, l_MaterialType);
		}
		else if (l_MaterialType == CMaterialParameter::TMaterialType::VECT3F)
		{
			l_MaterialType = CMaterialParameter::VECT3F;
			Vect3f l_Value = *((Vect3f*)l_OtherMaterialParameter->GetValueAddress());
			l_MaterialParameter = new CTemplatedMaterialParameter<Vect3f>(this, l_OtherName, l_OtherDescription, l_Value, l_MaterialType);
		}
		else if (l_MaterialType == CMaterialParameter::TMaterialType::VECT4F)
		{
			l_MaterialType = CMaterialParameter::VECT4F;
			Vect4f l_Value = *((Vect4f*)l_OtherMaterialParameter->GetValueAddress());
			l_MaterialParameter = new CTemplatedMaterialParameter<Vect4f>(this, l_OtherName, l_OtherDescription, l_Value, l_MaterialType);
		}
		m_Parameters.push_back(l_MaterialParameter);
	}
}
Esempio n. 7
0
/*************
 * DESCRIPTION:	Rename current material
 * INPUT:			-
 * OUTPUT:			-
 *************/
void CMatView::OnRename()
{
    CRenameDlg dialog;
    CMaterial *pMat;

    if (nSelectedMaterial == -1)
        return;

    pMat = ((CMaterial*)aMaterials[nSelectedMaterial]);
    dialog.m_sName = pMat->pSurface->name;
    if (dialog.DoModal() == IDOK)
    {
        pMat->pSurface->SetName((char*)LPCTSTR(dialog.m_sName));
        pMat->Update();
        Invalidate(FALSE);
    }
}
Esempio n. 8
0
/**
* CRenderList::renderAll
* @date Modified Apr 25, 2006
*/
void CRenderList::renderAll(void)
{
	// Render Geomtery
	LPDIRECT3DDEVICE9 pDev = CRenderSystem::getInstance().getRenderDevice().getD3DDevice();
	m_poVertCache->begin();
	SRenderTriangle* pTri;
	CMaterial* pTriMat = NULL;
	for(DWORD i = 0; i < m_dwCurrentIndex; ++i)
	{
		pTri = (SRenderTriangle*)m_oPrimList[i];

		// Check for material change.
		pTriMat = pTri->m_pMaterial;
		if(pTriMat != m_pCurrentMaterial)
		{
			// Change material
			if(m_pCurrentMaterial) 
			{
				// Render previous if the new material has effect on the shader or texture
				if(pTriMat->getDiffuse() != m_pCurrentMaterial->getDiffuse())
				{
					// Make sure the straggler triangles get rendered.
					m_poVertCache->flush();
					m_dwCurrentPass = 0;

					m_pCurrentMaterial->end();
				};
			}
			m_pCurrentMaterial = pTriMat;
			m_pCurrentMaterial->begin();
		}

		// Add triangles
		m_poVertCache->insert(pTri->m_oVerts, 3, NULL, 3);
	}

	// Clean up last material
	if(m_pCurrentMaterial)
	{
		m_poVertCache->flush();
		m_dwCurrentPass = 0;
		pDev->SetTexture(0, NULL);
		m_pCurrentMaterial->end();
		m_pCurrentMaterial = NULL;
	}
}
Esempio n. 9
0
		void draw()
		{
			if(m_material)
			{
				m_material->bind();
			}

			glDrawElements(GL_TRIANGLES, m_count, GL_UNSIGNED_INT, m_startPtr);
		}
Esempio n. 10
0
void CCustomParser::parse(const std::string& filename) {
	std::ifstream in(filename);
	std::string s;
	while(std::getline(in, s)) {
		std::istringstream s_stream(s);
		std::string cur_s;
		s_stream >> cur_s;
		if(cur_s == "sphere") {
			double c_x, c_y, c_z, radius;
			int r, g, b;
			s_stream >> c_x >> c_y >> c_z >> radius;
			s_stream >> r >> g >> b;
			CMaterial mat;
			mat.set_color(CColor(r, g, b));
			CSphere* sphere = new CSphere(radius, CPoint3D(c_x, c_y, c_z), mat);
			m_objects.push_back(sphere);	
		}
		else if(cur_s == "camera") {
Esempio n. 11
0
atUint32 CModelData::exportUVIdx(atUint32 texOff, SVertexDescriptor desc, CMaterial& mat, CMesh& mesh)
{
    atUint32 ret;
    if ((mat.materialFlags() & 0x2000) || (mesh.m_uvSource == 1))
        ret = desc.texCoord[1] + texOff;
    else
        ret = desc.texCoord[0] + texOff;

    return ret;
}
Esempio n. 12
0
 CMaterial(const CMaterial& that)
 {
     for(auto it = mTextures.begin(); it != mTextures.end(); ++it)
     {
         delete it->second;
         it->second = nullptr;
         mTextures[it->first] = that.getTexture(it->first);
     }
     mOptions = that.mOptions;
 }
Esempio n. 13
0
bool CStage::InitPhysicsManager()
{
	static TestContactReport s_TCR;
	static TestTriggerReport s_TTR;

	// initialize physics scene
	CSceneDesc phys_scene_desc;
	m_pPhysicsScene = PhysicsEngine().CreateScene( phys_scene_desc );

	if( m_pPhysicsScene == NULL )
		return false;

	m_pPhysicsScene->SetUserContactReport( &s_TCR );
	m_pPhysicsScene->SetActorGroupPairFlags(0,0,ContactPairFlag::NOTIFY_ALL);
//	m_pPhysicsScene->SetActorGroupPairFlags(0,0,NX_NOTIFY_ON_START_TOUCH|NX_NOTIFY_ON_TOUCH|NX_NOTIFY_ON_END_TOUCH);

	m_pPhysicsScene->SetUserTriggerReport( &s_TTR );

	// set pairs that don't collide with each other
/*	m_pPhysicsManager->SetCollisionGroupState( ENTITY_COLL_GROUP_STATICGEOMETRY,ENTITY_COLL_GROUP_STATICGEOMETRY, false );
	m_pPhysicsManager->SetCollisionGroupState( ENTITY_COLL_GROUP_PLAYER,		ENTITY_COLL_GROUP_ITEM, false );
	m_pPhysicsManager->SetCollisionGroupState( ENTITY_COLL_GROUP_DOOR,			ENTITY_COLL_GROUP_STATICGEOMETRY, false );
	m_pPhysicsManager->SetCollisionGroupState( ENTITY_COLL_GROUP_DOOR,			ENTITY_COLL_GROUP_DOOR, false );
	m_pPhysicsManager->SetCollisionGroupState( ENTITY_COLL_GROUP_PLAYER,		ENTITY_COLL_GROUP_PLAYER, false );
	m_pPhysicsManager->SetCollisionGroupState( ENTITY_COLL_GROUP_NOCLIP,		false );
*/

	int default_material_index = 0;
	CMaterial *pDefaultMaterial = m_pPhysicsScene->GetMaterial( default_material_index );
	float default_static_friction  = 1.5f;
	float default_dynamic_friction = 1.2f;
	float default_restitution      = 0.5f;
	float rc = 0;
	if( pDefaultMaterial )
	{
		// Peek at some default parameter values of the default material
		float sf = pDefaultMaterial->GetStaticFriction();
		float df = pDefaultMaterial->GetDynamicFriction();
		float rc = pDefaultMaterial->GetRestitution();
		pDefaultMaterial->SetStaticFriction( default_static_friction );
		pDefaultMaterial->SetDynamicFriction( default_dynamic_friction );
		pDefaultMaterial->SetRestitution( default_restitution );
	}

	// Register another material as a fallback
	CMaterialDesc mat_desc;
	mat_desc.StaticFriction  = default_static_friction;
	mat_desc.DynamicFriction = default_dynamic_friction;
	mat_desc.Restitution     = default_restitution;
	physics::CMaterial *pFallbackMaterial = m_pPhysicsScene->CreateMaterial( mat_desc );
	int mat_id = pFallbackMaterial->GetMaterialID();

	return true;
}
long CObjectManager::loadObjectTable()
{
	char * path = "Data/Objects/ObjectTable.dat";

	std::fstream objectTable;
	objectTable.open(path, std::ios::in);

	struct entry {
		long  type;
		char* path;
	};

	entry curEntry;

	std::string etype;
	std::string epath;

	while (!objectTable.eof()) {
		if (objectTable.get() == '{') {
			char* tmp = (char*)malloc(1024);
			objectTable.getline(tmp, 1024);
			int counter = 0;
			for (int it = 0; tmp[it] != ';' && tmp[it] != '}'; ++it) {
				if (tmp[it] == ' ') {
					continue;
				}
				etype.push_back(tmp[it]);
				counter = it;
			}
			for (int it = counter + 2; tmp[it] != ';' && tmp[it] != '}'; ++it) {
				if (tmp[it] == ' ') {
					continue;
				}
				epath.push_back(tmp[it]);
			}

			curEntry.type = getTypeFromString(etype.c_str());
			curEntry.path = const_cast<char*>(epath.c_str());

			CObject* obj;

			switch (curEntry.type) {
			case EMaterial: {
				CMaterial mat = loadMatFromFile(curEntry.path);
				obj = new CMaterial(mat.getName(), mat.getTexture(),
					mat.getCollision(), mat.getWalkspeed());
				obj->registerObj(mat.getName());
				m_ObjectMap.insert(std::pair<std::string, CObject*>(obj->getID(), obj));
			}break;
			}

			etype.clear();
			epath.clear();
		}
	}

	objectTable.close();
	return 0;
}
Esempio n. 15
0
void CPropResource::draw()
{
	unsigned short pid;
	CMaterial material;

	if(m_materialResources.size())
	{
		m_multiMeshResource->bind();

		pid = 0;
		material = m_materialResources[0];

		material->bind();

		while((pid = m_multiMeshResource->draw(m_meshId, pid)))
		{
			if(pid < m_materialResources.size())
			{
				material = m_materialResources[pid];
				material->bind();
			}
		}
	}
}
Esempio n. 16
0
void CHud::RenderAmmo(CEntity *pEntity)
{
    if(!pEntity->GetWeapon())
        return;
    
    bool bHasClip = (pEntity->GetWeapon()->GetClass()->nClipSize > 0);
    unsigned cClipAmmo = pEntity->GetWeapon()->GetAmmo();
    unsigned cAmmo = pEntity->GetAmmo(pEntity->GetWeapon()->GetClass()->pAmmoType);
    bool bHasAmmo = cClipAmmo > 0 || (!bHasClip && cAmmo > 0);
    
    const core::dimension2du &ScrSize = m_pGame->GetVideoDriver()->getScreenSize();
    
    const core::dimension2du &AmmoBarSize = m_pAmmoBarTex->GetFrame(0)->getSize();
    core::position2di AmmoBarDestPos(ScrSize.Width - AmmoBarSize.Width - 30, 30);
    core::recti AmmoBarSrcRect(0, 0, AmmoBarSize.Width, AmmoBarSize.Height);
    
    m_pGame->GetVideoDriver()->draw2DImage(m_pAmmoBarTex->GetFrame(0), AmmoBarDestPos, AmmoBarSrcRect, 0, video::SColor(96, 255, 255, 255), true);
    
    CMaterial *pSignalTex = bHasAmmo ? m_pAmmoSignalGreenTex : m_pAmmoSignalRedTex;
    const core::dimension2du &AmmoSignalSize = pSignalTex->GetFrame(0)->getSize();
    core::position2di AmmoSignalDestPos(ScrSize.Width - AmmoBarSize.Width - 30 - AmmoSignalSize.Width, 30);
    core::recti AmmoSignalSrcRect(0, 0, AmmoSignalSize.Width, AmmoSignalSize.Height);
    
    m_pGame->GetVideoDriver()->draw2DImage(pSignalTex->GetFrame(0), AmmoSignalDestPos, AmmoSignalSrcRect, 0, video::SColor(96, 255, 255, 255), true);
    
    gui::IGUIFont *pFont = m_pFont ? m_pFont : m_pGame->GetGuiEnv()->getBuiltInFont();
    wchar_t wszBuf[64];
    
    core::recti AmmoInClipRect(AmmoBarDestPos.X, AmmoBarDestPos.Y, AmmoBarDestPos.X + AmmoBarSize.Width*2/5, AmmoBarDestPos.Y + AmmoBarSize.Height);
    swprintf(wszBuf, L"%u", cClipAmmo);
    pFont->draw(wszBuf, AmmoInClipRect, video::SColor(255, 255, 255, 0), true, true);
    
    core::recti TotalAmmoRect(AmmoBarDestPos.X + AmmoBarSize.Width*2/5, AmmoBarDestPos.Y, AmmoBarDestPos.X + AmmoBarSize.Width, AmmoBarDestPos.Y + AmmoBarSize.Height);
    swprintf(wszBuf, L"%u", cAmmo);
    pFont->draw(wszBuf, TotalAmmoRect, video::SColor(255, 255, 255, 0), true, true);
}
Esempio n. 17
0
// ***************************************************************************
void CScene::renderOcclusionTestMeshs()
{
	nlassert(RenderTrav.getDriver());
	RenderTrav.getDriver()->setupViewport(RenderTrav.getViewport());
	RenderTrav.getDriver()->activeVertexProgram(NULL);
	RenderTrav.getDriver()->activePixelProgram(NULL);
	RenderTrav.getDriver()->activeGeometryProgram(NULL);
	IDriver::TPolygonMode oldPolygonMode = RenderTrav.getDriver()->getPolygonMode();
	CMaterial m;
	m.initUnlit();
	m.setColor(CRGBA(255, 255, 255, 127));
	m.setBlend(true);
	m.setDstBlend(CMaterial::invsrcalpha);
	m.setSrcBlend(CMaterial::srcalpha);
	m.setZWrite(false);
	RenderTrav.getDriver()->setupMaterial(m);
	getDriver()->setPolygonMode(IDriver::Filled);
	renderOcclusionTestMeshsWithCurrMaterial();
	m.setColor(CRGBA::Black);
	RenderTrav.getDriver()->setupMaterial(m);
	getDriver()->setPolygonMode(IDriver::Line);
	renderOcclusionTestMeshsWithCurrMaterial();
	getDriver()->setPolygonMode(oldPolygonMode);
}
Esempio n. 18
0
void CHud::RenderHealthArmor(CEntity *pEntity)
{
    int iHealthTex = static_cast<int>(pEntity->GetLife()) / 10;
    if(iHealthTex > 10)
        iHealthTex = 10;
    else if(iHealthTex < 0)
        iHealthTex = 0;
    
    CMaterial *pHealthTex = m_HealthTextures[iHealthTex];
    
    const core::dimension2du &HealthImgSize = pHealthTex->GetFrame(0)->getSize();
    core::position2di HealthDestPos(30, 30);
    core::recti HealthSrcRect(0, 0, HealthImgSize.Width, HealthImgSize.Height);
    
    m_pGame->GetVideoDriver()->draw2DImage(pHealthTex->GetFrame(0), HealthDestPos, HealthSrcRect, 0, video::SColor(96, 255, 255, 255), true);
    
    int iEnviroTex = static_cast<int>(pEntity->GetArmor()) / 10;
    if(iEnviroTex > 10)
        iEnviroTex = 10;
    else if(iEnviroTex < 0)
        iEnviroTex = 0;
    
    CMaterial *pEnviroTex = m_EnviroTextures[iEnviroTex];
    
    const core::dimension2du &EnviroImgSize = pEnviroTex->GetFrame(0)->getSize();
    core::position2di EnviroDestPos(10, 10);
    core::recti EnviroSrcRect(0, 0, EnviroImgSize.Width, EnviroImgSize.Height);
    
    m_pGame->GetVideoDriver()->draw2DImage(pEnviroTex->GetFrame(0), EnviroDestPos, EnviroSrcRect, 0, video::SColor(96, 255, 255, 255), true);
    
    gui::IGUIFont *pFont = m_pFont ? m_pFont : m_pGame->GetGuiEnv()->getBuiltInFont();
    wchar_t wszBuf[64];
    
    core::recti HealthTextRect(70, 55, 100, 80);
    swprintf(wszBuf, L"%.0f", pEntity->GetLife());
    pFont->draw(wszBuf, HealthTextRect, video::SColor(255, 255, 255, 0), true, true);
    
    core::recti EnviroTextRect(110, 55, 140, 80);
    swprintf(wszBuf, L"%.0f", pEntity->GetArmor());
    pFont->draw(wszBuf, EnviroTextRect, video::SColor(255, 255, 255, 0), true, true);
}
Esempio n. 19
0
// bind phong shader specific content for drawing
void CPhongShader::BindShaderWithObjectForDrawing( CObject* t_object ) {
    assert( t_object && _light );
    CPerspCamShader::BindShaderWithObjectForDrawing( t_object );

    glUniform3fv( _uni_lightPos, 1, glm::value_ptr( _light->GetPos() ) );
    glUniform3fv( _uni_lightLs, 1, glm::value_ptr( _light->GetLs() ) );
    glUniform3fv( _uni_lightLd, 1, glm::value_ptr( _light->GetLd() ) );
    glUniform3fv( _uni_lightLa, 1, glm::value_ptr( _light->GetLa() ) );

    CMaterial* mtl = &(t_object->GetMaterial());
    glUniform3fv( _uni_mtlKd, 1, glm::value_ptr( mtl->GetKd()._Color ) );
    if( mtl->GetHasSpecular() ) {
        glUniform3fv( _uni_mtlKs, 1, glm::value_ptr( mtl->GetKs()._Color ) );
        glUniform1f( _uni_mtlSplExp, mtl->GetSplExp() );
    }
    else{
        // set ks to all zeros
        glUniform3f( _uni_mtlKs, 0.f, 0.f, 0.f );
    }


    glUniform3fv( _uni_mtlKa, 1, glm::value_ptr( mtl->GetKa()._Color ) );

}
Esempio n. 20
0
// ---------------------------------------------------------------------------
void CBuilderZone::displayGrid (const NLMISC::CVector &viewMin, const NLMISC::CVector &viewMax)
{
	// Select all blocks visible
	float rMinX = floorf (viewMin.x / _Display->_CellSize)*_Display->_CellSize;
	float rMinY = floorf (viewMin.y / _Display->_CellSize)*_Display->_CellSize;
	float rMaxX = ceilf  (viewMax.x / _Display->_CellSize)*_Display->_CellSize;
	float rMaxY = ceilf  (viewMax.y / _Display->_CellSize)*_Display->_CellSize;

	sint32 nMinX = (sint32)floor (rMinX / _Display->_CellSize);
	sint32 nMinY = (sint32)floor (rMinY / _Display->_CellSize);
	sint32 nMaxX = (sint32)floor (rMaxX / _Display->_CellSize);
	sint32 nMaxY = (sint32)floor (rMaxY / _Display->_CellSize);

	static vector<uint8> vBars;
	sint32 nBarsW = (nMaxX-nMinX)+1;
	sint32 nBarsH = (nMaxY-nMinY)+1;
	vBars.resize (nBarsW*nBarsH);
	sint32 x, y, i, j, zoneSelected;
	for (i = 0; i < nBarsW*nBarsH; ++i)
		vBars[i] = 0;


	for (y = nMinY; y <= nMaxY; ++y)
	for (x = nMinX; x <= nMaxX; ++x)
	{

		string sZone = STRING_OUT_OF_BOUND;
		zoneSelected = 0;
		for (i = 0; i < (sint32)_ZoneRegions.size(); ++i)
		{
			const string &rSZone = getDocument ()->getZoneRegion (i).getName (x, y);
			if ((sZone == STRING_OUT_OF_BOUND) && (rSZone == STRING_UNUSED))
			{
				sZone = STRING_UNUSED;
				zoneSelected = i;
			}
			if ((rSZone != STRING_OUT_OF_BOUND) && (rSZone != STRING_UNUSED))
			{
				sZone = rSZone;
				zoneSelected = i;
			}
		}


		//const string &sZone = _ZoneRegion.getName (x, y);
		CZoneBankElement *pZBE = _ZoneBank.getElementByZoneName (sZone);
		if (pZBE != NULL)
		if ((pZBE->getSizeX() > 1) || (pZBE->getSizeY() > 1))
		{
			const CZoneRegion *pSelected = &(getDocument ()->getZoneRegion (zoneSelected));
			sint32 sizeX = pZBE->getSizeX(), sizeY = pZBE->getSizeY();
			sint32 posX = pSelected->getPosX (x, y), posY = pSelected->getPosY (x, y);
			uint8 rot = pSelected->getRot (x, y);
			uint8 flip = pSelected->getFlip (x, y);
			sint32 deltaX, deltaY;
		
			if (flip == 0)
			{
				switch (rot)
				{
					case 0: deltaX = -posX; deltaY = -posY; break;
					case 1: deltaX = -(sizeY-1-posY); deltaY = -posX; break;
					case 2: deltaX = -(sizeX-1-posX); deltaY = -(sizeY-1-posY); break;
					case 3: deltaX = -posY; deltaY = -(sizeX-1-posX); break;
				}
			}
			else
			{
				switch (rot)
				{
					case 0: deltaX = -(sizeX-1-posX); deltaY = -posY; break;
					case 1: deltaX = -(sizeY-1-posY); deltaY = -(sizeX-1-posX); break;
					case 2: deltaX = -posX; deltaY = -(sizeY-1-posY); break;
					case 3: deltaX = -posY; deltaY = -posX; break;
				}
			}

			static SPiece sMask;
			sMask.Tab.resize (sizeX*sizeY);
			for(i = 0; i < sizeX*sizeY; ++i)
				sMask.Tab[i] = pZBE->getMask()[i];
			sMask.w = sizeX;
			sMask.h = sizeY;
			sMask.rotFlip (rot, flip);

			for (j = 0; j < sMask.h; ++j)
			for (i = 0; i < sMask.w; ++i)
			if (sMask.Tab[i+j*sMask.w])
			{
				if (((x+deltaX+i-nMinX)>=0) && ((x+deltaX+i-nMinX)<nBarsW) &&
					((y+deltaY+j-nMinY)>=0) && ((y+deltaY+j-nMinY)<nBarsH))
				{
					if ((i > 0) && (sMask.Tab[i-1+j*sMask.w]))
						vBars[x+deltaX+i-nMinX + (y+deltaY+j-nMinY)*nBarsW] |= 1;

					if ((j > 0) && (sMask.Tab[i+(j-1)*sMask.w]))
						vBars[x+deltaX+i-nMinX + (y+deltaY+j-nMinY)*nBarsW] |= 2;
				}
			}
		}
	}

	CVertexBuffer VB;
	CIndexBuffer PB;
	CMaterial Mat;

	Mat.initUnlit ();
	Mat.setBlend (false);
	VB.setVertexFormat (CVertexBuffer::PositionFlag);
	VB.setNumVertices ((nBarsW+1)*(nBarsH+1));
	CVertexBufferReadWrite vba;
	VB.lock (vba);
	
	for (y = nMinY; y <= nMaxY+1; ++y)
	for (x = nMinX; x <= nMaxX+1; ++x)
	{
		CVector pos;

		pos.x = (x*_Display->_CellSize - viewMin.x)/(viewMax.x-viewMin.x);
		pos.y = 0.0f;
		pos.z = (y*_Display->_CellSize - viewMin.y)/(viewMax.y-viewMin.y);
		vba.setVertexCoord (x-nMinX+(y-nMinY)*(nBarsW+1), pos);
	}

	PB.setNumIndexes (nBarsW*nBarsH*2*2);
	CIndexBufferReadWrite iba;
	PB.lock (iba);
	uint32 nNbLine = 0;
	for (y = 0; y < nBarsH; ++y)
	for (x = 0; x < nBarsW; ++x)
	{
		// Vertical Line ?
		if ((vBars[x+y*nBarsW] & 1) == 0)
		{
			iba.setLine (nNbLine*2, x+y*(nBarsW+1), x+(y+1)*(nBarsW+1));
			++nNbLine;
		}

		// Horizontal Line ?
		if ((vBars[x+y*nBarsW] & 2) == 0)
		{
			iba.setLine (nNbLine*2, x+y*(nBarsW+1), (x+1)+y*(nBarsW+1));
			++nNbLine;
		}
	}
	iba.unlock();
	PB.setNumIndexes (nNbLine*2);

	if (DontUse3D)
		return;

	// Render with driver
	CMatrix mtx;
	mtx.identity();
	vba.unlock();
	CNELU::Driver->setupViewport (CViewport());
	CNELU::Driver->setupViewMatrix (mtx);
	CNELU::Driver->setupModelMatrix (mtx);
	CNELU::Driver->setFrustum (0.f, 1.f, 0.f, 1.f, -1.f, 1.f, false);
	CNELU::Driver->activeVertexBuffer (VB);
	CNELU::Driver->activeIndexBuffer (PB);
	CNELU::Driver->renderLines (Mat, 0, PB.getNumIndexes()/2);
	
}
Esempio n. 21
0
bool CSkyDome::Create(FLOAT fRadius, FLOAT fPhiDelta, FLOAT fThetaDelta, CGraphicsResource::HANDLE Material,
					  UINT uMainTextureIndex, UINT* pOffsetTextureIndices, UINT uOffsetNum)
{
	Destroy();

	CSceneManager* pSceneManager = CSceneManager::GetInstance();
	
	m_fUVOffsets.x = m_fUVOffsets.y = 0.0f;

	CMaterial* pMaterial = static_cast<CMaterial*>( pSceneManager->GetResource( Material, CGraphicsResource::MATERIAL ) );
	if(!pMaterial)
	{
		ALCHEMY_DEBUG_WARNING("CSkyDome::Create() - Error Material Handle!");
		return false;
	}

	const LPTEXTURE* ppMainTexture = pMaterial->GetTextures().Get(uMainTextureIndex);
	if(!ppMainTexture)
	{
		ALCHEMY_DEBUG_WARNING("CSkyDome::Create() - Error Main Texture Index!");
		return false;
	}

	CTexture::TEXTURETYPE textureType = (*ppMainTexture)->GetTextureType();

	CVertexDeclaration::VERTEXELEMENT vertexElement[2] = { {0,0, CVertexDeclaration::FLOAT4,CVertexDeclaration::POSITION, 0}, {1,0, CVertexDeclaration::FLOAT3,CVertexDeclaration::TEXCOORD, 1} };
	bool hasOffsetTextures = false;
	if(textureType == CTexture::NORMAL)
	{
		vertexElement[1].Type = CVertexDeclaration::FLOAT2;

		if(pOffsetTextureIndices != ALCHEMY_NULL && uOffsetNum > 0)
		{
			hasOffsetTextures = true;
			m_uOffsetTextureCount = uOffsetNum;
		}
	}

	UINT vertexUsages[] = { ALCHEMY_FLAG(VERTEXBUFFER::WRITE_ONLY), ALCHEMY_FLAG(VERTEXBUFFER::WRITE_ONLY)};

	m_uMeshData = ALCHEMY_MESH_MANAGER.CreateSkyDome(fRadius, fPhiDelta, fThetaDelta,vertexElement, vertexUsages, 2, ALCHEMY_FLAG(INDEXBUFFER::WRITE_ONLY));

	if(m_uMeshData == 0)
	{
		Destroy();
		ALCHEMY_DEBUG_WARNING("CSkyDome::Create() - Create Mesh Data Error!");
		return false;
	}

	CMesh* pMesh = pSceneManager->CreateMesh( m_uMeshData );
	if(!pMesh)
	{
		Destroy();
		ALCHEMY_DEBUG_WARNING("CSkyDome::Create() - Create Mesh Error!");
		return false;
	}

	//Create Effect

	CEffectCode Code( pSceneManager->GetRenderSystem().GetCompiler() );

	CEffectCode::CShaderParametersDefiner ShaderParametersDefiner( Code );

	ShaderParametersDefiner.AppendParameter(CVertexDeclaration::FLOAT4, CVertexDeclaration::POSITION, 0);
	if(textureType == CTexture::NORMAL)
		ShaderParametersDefiner.AppendParameter(CVertexDeclaration::FLOAT2, CVertexDeclaration::TEXCOORD, 0);
	else
		ShaderParametersDefiner.AppendParameter(CVertexDeclaration::FLOAT3, CVertexDeclaration::TEXCOORD, 0);

	UINT uShaderInput = ShaderParametersDefiner.EndDefine();

	ShaderParametersDefiner.AppendParameter(CVertexDeclaration::FLOAT4, CVertexDeclaration::POSITIONT, 0);
	if(textureType == CTexture::NORMAL)
		ShaderParametersDefiner.AppendParameter(CVertexDeclaration::FLOAT2, CVertexDeclaration::TEXCOORD, 0);
	else
		ShaderParametersDefiner.AppendParameter(CVertexDeclaration::FLOAT3, CVertexDeclaration::TEXCOORD, 0);

	UINT uShaderVarying = ShaderParametersDefiner.EndDefine();

	CEffectCode::CShaderFunctionDefiner VertexFunctionDefiner(Code, true);

	UINT uVertexShaderInput = VertexFunctionDefiner.BeginFunction( uShaderInput ), uVertexShaderOutput = VertexFunctionDefiner.EndFunction( uShaderVarying );
	UINT uOutputPosition = Code.GetAddressVariable( uVertexShaderOutput, 0 );

	CEffectCode::GLOBALVARIABLE WorldViewProjectionMatrix;
	WorldViewProjectionMatrix.GlobalType = CEffectCode::CAMERA_VARIABLE;
	WorldViewProjectionMatrix.ShaderType = IEffect::VERTEX_SHADER;
	WorldViewProjectionMatrix.uDetail    = CRenderMethod::CAMERA_WORLD_VIEW_PROJECTION_MATRIX;
	WorldViewProjectionMatrix.uCount     = 1;
	WorldViewProjectionMatrix.uIndex     = 0;
	WorldViewProjectionMatrix.pValue     = ALCHEMY_NULL;

	UINT uWorldViewProjMatrix = Code.AddGlobalVariable( WorldViewProjectionMatrix );
	UINT uPosition = VertexFunctionDefiner.ApplyVariable( CEffectCode::VECTOR4_VARIABLE, 1 );

	VertexFunctionDefiner.AppendInstruction( ICompiler::M44, uPosition, Code.GetAddressVariable( uVertexShaderInput, 0), uWorldViewProjMatrix);

	UINT subAddress[] = {0, 1, 3, 3};
	VertexFunctionDefiner.AppendInstruction(ICompiler::MOV, uOutputPosition, ALCHEMY_NULL, 0, uPosition, subAddress, 4, 0, ALCHEMY_NULL, 0);

	VertexFunctionDefiner.AppendInstruction( ICompiler::MOV, Code.GetAddressVariable(uVertexShaderOutput, 1), ALCHEMY_NULL, 0, Code.GetAddressVariable(uVertexShaderInput, 1), ALCHEMY_NULL, 0, 0, ALCHEMY_NULL, 0 );


	CEffectCode::CShaderFunctionDefiner FragmentFunctionDefiner(Code, false);

	ShaderParametersDefiner.AppendParameter(CVertexDeclaration::FLOAT4, CVertexDeclaration::COLOR, 0);

	UINT uTexCoord = Code.GetAddressVariable( FragmentFunctionDefiner.BeginFunction(uShaderVarying), 1), uOutputColor = Code.GetAddressVariable( FragmentFunctionDefiner.EndFunction( ShaderParametersDefiner.EndDefine() ), 0 );

	IEffect::SAMPLERDECLARATION SamplerDeclaration;

	if(textureType == CTexture::NORMAL)
	{
		SamplerDeclaration.Type     = IEffect::TEXTURE2D;
		SamplerDeclaration.AddressU = IEffect::WRAP;
		SamplerDeclaration.AddressV = IEffect::WRAP;
		SamplerDeclaration.AddressW = IEffect::WRAP;
	}
	else
	{
		SamplerDeclaration.Type     = IEffect::TEXTURE_CUBE;
		SamplerDeclaration.AddressU = IEffect::CLAMP;
		SamplerDeclaration.AddressV = IEffect::CLAMP;
		SamplerDeclaration.AddressW = IEffect::CLAMP;
	}

	SamplerDeclaration.MinFilter = IEffect::LINEAR;
	SamplerDeclaration.MagFilter = IEffect::LINEAR;
	SamplerDeclaration.MipFilter = IEffect::LINEAR;

	UINT uSampler = FragmentFunctionDefiner.AddSamplerVariable(SamplerDeclaration, 0);
	UINT* pOffsetSamplers = ALCHEMY_NULL;
	UINT uUVOffset = 0;
	if(hasOffsetTextures)
	{
		UINT uSourceTexColor = FragmentFunctionDefiner.ApplyVariable(CEffectCode::VECTOR4_VARIABLE, 1 );
		FragmentFunctionDefiner.AppendInstruction(ICompiler::TEX, uSourceTexColor, uTexCoord, uSampler );

		CEffectCode::GLOBALVARIABLE UVOffsetKey;
		UVOffsetKey.GlobalType = CEffectCode::NORMAL_VARIABLE;
		UVOffsetKey.ShaderType = IEffect::FRAGMENT_SHADER;
		UVOffsetKey.uDetail    = IRenderMethod::UV_OFFSET;
		UVOffsetKey.uCount     = 1;
		UVOffsetKey.uIndex     = 0;
		UVOffsetKey.pValue     = ALCHEMY_NULL;

		uUVOffset = Code.AddGlobalVariable(UVOffsetKey);

		UINT uTmpUVOffset = FragmentFunctionDefiner.ApplyVariable(CEffectCode::VECTOR2_VARIABLE, 1);

		FragmentFunctionDefiner.AppendInstruction(ICompiler::ADD, uTmpUVOffset, ALCHEMY_NULL, 0, uTexCoord, ALCHEMY_NULL, 0, uUVOffset, ALCHEMY_NULL, 0);

		UINT uBlendColor = FragmentFunctionDefiner.ApplyVariable( CEffectCode::VECTOR4_VARIABLE, 1);
		ALCHEMY_DEBUG_NEW(pOffsetSamplers,UINT[m_uOffsetTextureCount]);
		for (UINT i=0; i<m_uOffsetTextureCount; ++i)
		{
			pOffsetSamplers[i] = FragmentFunctionDefiner.AddSamplerVariable(sm_OFFSET_SAMPLER_DECLARATION, i+1);

			FragmentFunctionDefiner.AppendInstruction(ICompiler::TEX, uBlendColor, uTmpUVOffset, pOffsetSamplers[i] );

			UINT subAddress[] = {0,1,2,3};
			FragmentFunctionDefiner.AppendInstruction(ICompiler::MUL, uBlendColor, subAddress, 3, uBlendColor, subAddress,3, uBlendColor, &subAddress[3], 1);
			FragmentFunctionDefiner.AppendInstruction(ICompiler::ADD, uSourceTexColor, uSourceTexColor, uBlendColor);
		}

		FragmentFunctionDefiner.AppendInstruction(ICompiler::MOV, uOutputColor, uSourceTexColor, 0);
	}
	else
		FragmentFunctionDefiner.AppendInstruction(ICompiler::TEX, uOutputColor, uTexCoord, uSampler );

	Code.AddPass( VertexFunctionDefiner.EndDefine(), FragmentFunctionDefiner.EndDefine() );

	CEffect* pEffect = pSceneManager->GetRenderSystem().CreateEffect( Code );
	CRenderMethod* pRenderMethod = pSceneManager->CreateRenderMethod(Code);

	ALCHEMY_DEBUG_DELETE_ARRAY(pOffsetSamplers);

	if(!pEffect || !pRenderMethod)
	{
		Destroy();
		ALCHEMY_DEBUG_WARNING("CSkyDome::Create() - Create Effect Error!");
		return false;
	}

	return CStaticObject::Create(pMesh->GetResourceHandle(), 0, pEffect->GetResourceHandle(), pRenderMethod, 0, Material, pSceneManager);
}
Esempio n. 22
0
// *************************************************************************************************
void makeInstanceTransparent(UInstance	&inst, uint8 opacity, bool disableZWrite)
{
	UShape		shape= inst.getShape();
	if(shape.empty())
		return;
	uint	numMats= shape.getNumMaterials();
	if(numMats==0)
		return;
	if(numMats!=inst.getNumMaterials())
		return;

	// instance transparent or not?
	if (opacity == 255)
	{
		// reset default shape opacity / transparency
		inst.setOpacity(shape.getDefaultOpacity());
		inst.setTransparency(shape.getDefaultTransparency());
		inst.setBypassLODOpacityFlag(false);
	}
	else
	{
		// Will have some blend material => sure not to be rendered in Opaque pass
		inst.setOpacity(false);
		inst.setTransparency(true);
		inst.setBypassLODOpacityFlag(true); // these flags prevails over the current lods flags for multi-lod objects
	}

	// set all materials
	for (uint32 j = 0; j < numMats; ++j)
	{
		NL3D::UInstanceMaterial matInst = inst.getMaterial(j);
		NL3D::UMaterial			matShape= shape.getMaterial(j);

		// disalbe zwrite?
		if(disableZWrite)
			matInst.setZWrite(false);
		else
			matInst.setZWrite(matShape.getZWrite());

		// if no more transparent
		if (opacity == 255)
		{
			// reset to default
			matInst.setBlend(matShape.getBlend());
			matInst.setBlendFunc((NL3D::UInstanceMaterial::TBlend)matShape.getSrcBlend(),
				(NL3D::UInstanceMaterial::TBlend)matShape.getDstBlend());
			// if orginal material is opaque or additif and has no alpha test, then ensure restore last tex env if needed
			CMaterial *destInternalMat = matInst.getObjectPtr();
			if (!matShape.getBlend() && !matShape.getAlphaTest())
			{
				if (destInternalMat->getShader() == CMaterial::Normal)
				{
					CMaterial *srcInternalMat = matShape.getObjectPtr();
					uint numTex = 0;
					for (;numTex < 4 && srcInternalMat->getTexture(numTex) != NULL; ++numTex) {}
					if (numTex > 0)
					{
						if (srcInternalMat->getTexEnvMode(numTex - 1) != destInternalMat->getTexEnvMode(numTex - 1))
						{
							destInternalMat->setTexEnvMode(numTex - 1, srcInternalMat->getTexEnvMode(numTex - 1));
						}
					}
				}
			}
			if (destInternalMat->getShader() == CMaterial::Normal)
			{
				// if !lighted, restore color
				if (!destInternalMat->isLighted())
				{
					CMaterial *srcInternalMat = matShape.getObjectPtr();
					// restore alpha in color
					CRGBA color = destInternalMat->getColor();
					color.A = srcInternalMat->getColor().A;
					destInternalMat->setColor(color);
				}
			}
		}
		else
		{
			// Enable blend
			matInst.setBlend(true);
			// If default is ???/one or , then use a srcalpha/one  (eg: for Diamond-like weapons)
			if(matShape.getBlend() && (sint32)matShape.getDstBlend()==(sint32)NL3D::UInstanceMaterial::one)
				matInst.setBlendFunc(NL3D::UInstanceMaterial::srcalpha, NL3D::UInstanceMaterial::one);
			// else use a standard srcalpha/invsrcalpha
			else
				matInst.setBlendFunc(NL3D::UInstanceMaterial::srcalpha, NL3D::UInstanceMaterial::invsrcalpha);
			// if orginal material is opaque or additif and has no alpha test, then ensure that the alpha output is 'diffuse'
			CMaterial *internalMat = matInst.getObjectPtr();
			if (!matShape.getBlend() && !matShape.getAlphaTest())
			{
				if (internalMat->getShader() == CMaterial::Normal)
				{
					uint numTex = 0;
					for (;numTex < 4 && internalMat->getTexture(numTex) != NULL; ++numTex) {}
					if (numTex > 0)
					{
						internalMat->texEnvOpAlpha(numTex - 1, CMaterial::Replace);
						// if material is unlighted, then use the constant at this stage to set the alpha
						internalMat->texEnvArg0Alpha(numTex - 1, CMaterial::Diffuse, CMaterial::SrcAlpha);
					}
				}
			}
			if (internalMat->getShader() == CMaterial::Normal)
			{
				if (!internalMat->isLighted())
				{
					// replace alpha in color
					CRGBA color = internalMat->getColor();
					color.A = opacity;
					internalMat->setColor(color);
				}
			}
		}

		// suppose that default opacity is always 255
		if (matInst.isLighted())
		{
			matInst.setOpacity(opacity);
		}

		matInst.setAlphaTestThreshold(matShape.getAlphaTestThreshold()*((float)opacity)/255.0f);
	}
}
Esempio n. 23
0
bool CSimpleMesh::LoadMaterials(CString szFileName) {
	TArray<CString> m_oTextureNames;

	FILE *file = fopen(szFileName, "rt");
	if (!file)
		return false;

	char szLine[MAX_LINE_LEN];
	CString *ppsTokens;
	int iNumTokens;
	int iNumMaterials = 0;
	while (fgets(szLine, MAX_LINE_LEN, file)) {
		CString sLine(szLine);
		sLine.ToUpper();

		if (sLine.StartsWith("NEWMTL")) {
			CMaterial oMaterial;
			m_oMaterials.Append(oMaterial);

			sLine.Tokenize(&ppsTokens, &iNumTokens, sDelimiters);
			m_oMaterialNames.Append(ppsTokens[1]);
			SAFE_DELETE_ARRAY(ppsTokens);
			iNumMaterials++;

			//m_oTextureNames.Append(NULL);
			m_oMaterialsTextureIndex.Append(NO_TEXTURE);
		} else if (sLine.StartsWith("KA")) {
			sLine.Tokenize(&ppsTokens, &iNumTokens, sDelimiters);
			CMaterial *oMaterial = &m_oMaterials[m_oMaterials.GetSize() - 1];
			CColor *poColor = oMaterial->GetAmbientColor();
			poColor->red = ppsTokens[1].ToFloat();
			poColor->green = ppsTokens[2].ToFloat();
			poColor->blue = ppsTokens[3].ToFloat();

			SAFE_DELETE_ARRAY(ppsTokens);
		} else if (sLine.StartsWith("KD")) {
			sLine.Tokenize(&ppsTokens, &iNumTokens, sDelimiters);
			CMaterial *oMaterial = &m_oMaterials[m_oMaterials.GetSize() - 1];
			CColor *poColor = oMaterial->GetDiffuseColor();
			poColor->red = ppsTokens[1].ToFloat();
			poColor->green = ppsTokens[2].ToFloat();
			poColor->blue = ppsTokens[3].ToFloat();

			SAFE_DELETE_ARRAY(ppsTokens);
		} else if (sLine.StartsWith("KS")) {
			sLine.Tokenize(&ppsTokens, &iNumTokens, sDelimiters);
			CMaterial *oMaterial = &m_oMaterials[m_oMaterials.GetSize() - 1];
			CColor *poColor = oMaterial->GetSpecularColor();
			poColor->red = ppsTokens[1].ToFloat();
			poColor->green = ppsTokens[2].ToFloat();
			poColor->blue = ppsTokens[3].ToFloat();

			SAFE_DELETE_ARRAY(ppsTokens);
		} else if (sLine.StartsWith("NS")) {
			sLine.Tokenize(&ppsTokens, &iNumTokens, sDelimiters);
			CMaterial *oMaterial = &m_oMaterials[m_oMaterials.GetSize() - 1];

			oMaterial->SetPower(ppsTokens[1].ToFloat());

			SAFE_DELETE_ARRAY(ppsTokens);
		} else if (sLine.StartsWith("MAP_KD") || sLine.StartsWith("MAP_KA")) {
			sLine.Tokenize(&ppsTokens, &iNumTokens, sDelimiters);
			CString sTextureName(ppsTokens[1].StartsWith(".\\") ? ppsTokens[1].GetBuffer() + 2 : ppsTokens[1]);

			int index = m_oTextureNames.Find(sTextureName);

			if (index == -1) {
				m_oTextureNames.Append(sTextureName);
				m_oMaterialsTextureIndex[m_oMaterials.GetSize() - 1] = m_oTextureNames.GetSize() - 1;
			} else {
				m_oMaterialsTextureIndex[m_oMaterials.GetSize() - 1] = index;
			}

			SAFE_DELETE_ARRAY(ppsTokens);
		}
	}

	fclose(file);

	for (int i = 0; i < m_oTextureNames.GetSize(); i++)
		m_oTextures.Append(new CTexture(m_poDisplayDevice, m_oTextureNames[i].GetBuffer()));

	return true;
}
Esempio n. 24
0
//-----------------------------------------------------------------------------------------
TestTransformation::TestTransformation()
    : m_bPressed(false)
    , m_bTouch(false)
    , m_StartPan(-1, -1)
    , m_LastPan(-1, -1)
{
    // On cr�e une camera
    CCamera* pCamera = m_pSceneManager->createCamera();

    m_vNewEyePosition = QVector3D(8., 8., 4.);
    pCamera->setEyePosition(m_vNewEyePosition);
    pCamera->setCenter(QVector3D(0., 0., 0.));

    qDebug() << "Create View";
    m_pView = createWidget3D(pCamera);
    m_pView->setAttribute(Qt::WA_AcceptTouchEvents);
    qDebug() << "End create View";

    // On cr�e un noeud afin d'y placer une lumi�re
    CSceneNode* pRootNode = getSceneManager()->getRootNode();

    // On cr�e une lumi�re diffuse bleue
    CLight* pLight = getSceneManager()->createLight();
    pLight->setDiffuseColor(1.0, 1.0, 1.0);
    pLight->setAmbientColor(1.0, 1.0, 1.0);
    pLight->setDirection(QVector3D(-1, 0, 0));
    pLight->setSpecularColor(1.0f, 1.0f, 1.0f);

    // On l'associe au noeud
    pRootNode->addItem(pLight);

    // SkyBox
    CSkyBox* pSkyBoxMesh = CMeshManager::getInstance().createCustomMesh<CSkyBox>("CSkyBox", "SkyBoxMesh");

    CMeshInstance* pSkyBox = getSceneManager()->createMeshInstance(pSkyBoxMesh, "SkyBox");
    pSkyBox->setSelectable(false);
    CSceneNode* pSkyBoxNode = pRootNode->createChild("SkyBoxNode");
    pSkyBoxNode->scale(400.);
    pSkyBoxNode->addItem(pSkyBox);


    CMaterial* pSkyBoxMat = CMaterialManager::getInstance().createMaterial("SkyBoxMaterial");
    pSkyBox->setMaterialName(pSkyBoxMat->getName());

    QStringList fileNames;
    fileNames << "://Resources/xpos.png" << "://Resources/xneg.png" << "://Resources/ypos.png"
              << "://Resources/yneg.png" << "://Resources/zpos.png" << "://Resources/zneg.png";

    ATexture* pSkyBoxTexture = CTextureManager::getInstance().createTextureCube("SkyBoxTexCube", fileNames);
    pSkyBoxMat->addTexture(pSkyBoxTexture, eDiffuse);

#ifdef EMBEDDED_TARGET
    CShader* pShader = CShaderManager::getInstance().createShader(
                "SkyBoxShader",
                "://Resources/skyboxES.vertex.glsl",
                "",
                "://Resources/skyboxES.fragment.glsl");
#else
    CShader* pShader = CShaderManager::getInstance().createShader(
                "SkyBoxShader",
                "://Resources/skybox.vertex.glsl",
                "",
                "://Resources/skybox.fragment.glsl");
#endif

    pSkyBoxMat->getRenderPass(0)->setShaderName(pShader->getName());
    pSkyBoxMat->getRenderPass(0)->renderStates().setFaceCulling(CFaceCulling(false));

    // Particules
    CBillboard* pBillboard = getSceneManager()->createBillboard();
    QVector<QVector3D> pos;
    for (int i = 0; i < 1000; ++i)
        pos << QVector3D(
                   Math::randDouble(-200., +200.),
                   Math::randDouble(-200., +200.),
                   Math::randDouble(-200., +200.));
    pBillboard->addPositions(pos);

    CMaterial* pBillboardMat = CMaterialManager::getInstance().createMaterial("BillboardMaterial");
    pBillboardMat->getRenderPass(0)->renderStates().setFaceCulling(CFaceCulling(false));
    CBlending blending;
    blending.setEnabled(true);
    blending.setBlendEquation(eAdd, eAdd);

    blending.setBlendSeparateFunction(Source::eSourceAlpha, Destination::eOneMinusSourceAlpha, Source::eOne, Destination::eZero);
    pBillboardMat->getRenderPass(0)->renderStates().setBlending(blending);

    ATexture* pBillboardTexture = CTextureManager::getInstance().createTexture2D("BillBoardTex", "://Resources/particle.png");
    pBillboardMat->addTexture(pBillboardTexture, eDiffuse);

    CShader* pBillboardShader = CShaderManager::getInstance().createShader("BillboardShader",
        "://Resources/billboard.vertex.glsl",
        "://Resources/billboard.geometry.glsl",
        "://Resources/billboard.fragment.glsl");

    pBillboardMat->getRenderPass(0)->setShaderName(pBillboardShader->getName());
    pBillboard->setMaterialName(pBillboardMat->getName());
    pBillboardShader->setUniformValue("halfSize", 1.);

    CSceneNode* pBillboardNode = pRootNode->createChild("BillboardNode");
    pBillboardNode->addItem(pBillboard);

    // Orbites
    CPolyLine* pPolyLine = CMeshManager::getInstance().createCustomMesh<CPolyLine>("CPolyLine", "CPolyLine");

    QList<QVector3D> pts;

    for (int i = 0; i <= 360; ++i)
    {
        pts << QVector3D(cos(Math::degToRad((real)i)), 0., sin(Math::degToRad((real)i)));
    }

    pPolyLine->addPoints(pts);

    CSphereMesh* pSphereMesh = CMeshManager::getInstance().createCustomMesh<CSphereMesh>("CSphereMesh", "SphereMesh");

    CMeshInstance* pSun = getSceneManager()->createMeshInstance(pSphereMesh, "Sun");
    CMaterial* pSunMat = CMaterialManager::getInstance().createMaterial("SunMat");
    pSunMat->setAmbientColor(1., 1., 1.);

    CTexture2D* pSunTexture = CTextureManager::getInstance().createTexture2D("SunTex", ":/Resources/sun.png");
    pSunMat->addTexture(pSunTexture, eDiffuse);
    pSun->setMaterialName(pSunMat->getName());

    CMeshInstance* pEarth = getSceneManager()->createMeshInstance(pSphereMesh, "Earth");
    CMaterial* pEarthMat = CMaterialManager::getInstance().createMaterial("EarthMat");

    CTexture2D* pEarthTexture = CTextureManager::getInstance().createTexture2D("EarthTex", ":/Resources/earth.png");
    pEarthMat->addTexture(pEarthTexture, eDiffuse);

    pEarthMat->setAmbientColor(0.1, 0.1, 0.1);
    pEarthMat->setDiffuseColor(1.0, 1.0, 1.0);
    pEarthMat->setShininessFactor(10);
    pEarth->setMaterialName(pEarthMat->getName());

    CMeshInstance* pJupiter = getSceneManager()->createMeshInstance(pSphereMesh, "Jupiter");
    CMaterial* pJupiterMat = CMaterialManager::getInstance().createMaterial("JupiterMat");
    pJupiterMat->setAmbientColor(0.4, 0.4, 0.4);

    CTexture2D* pJupiterTexture = CTextureManager::getInstance().createTexture2D("JupiterTex", ":/Resources/jupiter.png");
    pJupiterMat->addTexture(pJupiterTexture, eDiffuse);
    pJupiter->setMaterialName(pJupiterMat->getName());

    CMeshInstance* pMoon = getSceneManager()->createMeshInstance(pSphereMesh, "Moon");
    CMaterial* pMoonMat = CMaterialManager::getInstance().createMaterial("MoonMat");
    CTexture2D* pMoonTexture = CTextureManager::getInstance().createTexture2D("MoonTex", ":/Resources/moon.png");
    pMoonMat->addTexture(pMoonTexture, eDiffuse);
    pMoon->setMaterialName(pMoonMat->getName());

    CCoordinateSystem* pCoordinateSystemMesh = CMeshManager::getInstance().createCustomMesh<CCoordinateSystem>("CCoordinateSystem", "CCoordinateSystem");
    CMeshInstance* pCoordinateSystem = getSceneManager()->createMeshInstance(pCoordinateSystemMesh, "CoordinateSystem");
    pRootNode->addItem(pCoordinateSystem);
    pRootNode->addItem(pSkyBox);

    m_pSolarSystemNode = pRootNode->createChild(QVector3D(0., 0., 0.));

    m_pSunNode = m_pSolarSystemNode->createChild(QVector3D(0., 0., 0.));
    m_pSunNode->scale(4.0);
    m_pSunNode->addItem(pSun);

    m_pSunToEarthNode = m_pSolarSystemNode->createChild();
    m_pSunToJupiterNode = m_pSolarSystemNode->createChild();

    CMeshInstance* pSunToEarthPLine = getSceneManager()->createMeshInstance(pPolyLine, "SunToEarth");
    pSunToEarthPLine->setMaterialName(CMaterialManager::getInstance().getMaterialNameByColor(Color::eWhite));
    m_pSunToEarthNode->addItem(pSunToEarthPLine);
    m_pSunToEarthNode->scale(10.0);
    m_pEarthNode = m_pSolarSystemNode->createChild(QVector3D(10.0, 0., 0.));
    m_pEarthNode->scale(1.0);
    m_pEarthNode->addItem(pEarth);

    CMeshInstance* pSunToJupiterPLine = getSceneManager()->createMeshInstance(pPolyLine, "SunToJupiter");
    pSunToJupiterPLine->setMaterialName(CMaterialManager::getInstance().getMaterialNameByColor(Color::eWhite));
    m_pSunToJupiterNode->addItem(pSunToJupiterPLine);
    m_pSunToJupiterNode->scale(20);
    m_pJupiterNode = m_pSolarSystemNode->createChild(QVector3D(20.0, 0., 0.));
    m_pJupiterNode->scale(4.0);
    m_pJupiterNode->addItem(pJupiter);

    m_pEarthToMoonNode = m_pEarthNode->createChild();
    CMeshInstance* pEarthToMoonPLine = getSceneManager()->createMeshInstance(pPolyLine, "EarthToMoon");
    pEarthToMoonPLine->setMaterialName(CMaterialManager::getInstance().getMaterialNameByColor(Color::eWhite));
    m_pEarthToMoonNode->addItem(pEarthToMoonPLine);
    m_pEarthToMoonNode->scale(2.0);
    m_pEarthToMoonNode->rotate(QVector3D(1.0, 0.0, 0.0), 30);
    m_pMoonNode = m_pEarthToMoonNode->createChild(QVector3D(1.0, 0.0, 0.));
    m_pMoonNode->scale(0.2);
    m_pMoonNode->addItem(pMoon);

    QTimer* pTimer = new QTimer(this);
    connect(pTimer, SIGNAL(timeout()), this, SLOT(onTimeout()));
    pTimer->start(5);


    connect(m_pView, SIGNAL(mouseMoved()),				this, SLOT(onMouseMoved()));
    connect(m_pView, SIGNAL(mouseReleased()),			this, SLOT(onMouseReleased()));
    connect(m_pView, SIGNAL(mousePressed()),			this, SLOT(onMousePressed()));
    connect(m_pView, SIGNAL(touchScaleStarted()),       this, SLOT(onTouchScaleStarted()));
    connect(m_pView, SIGNAL(touchScaleChanged(real)),	this, SLOT(onTouchScaleChanged(real)));
    connect(m_pView, SIGNAL(touchScaleEnded()),         this, SLOT(onTouchScaleEnded()));

    //m_pView->setGeometry(QRect(1920, 100, 400, 300));

    m_GlobalTime.start();
}
Esempio n. 25
0
bool CRenderSystem::prepareMaterial(/*const */CMaterial& material, float fOpacity) // 由于使用了自动注册纹理的机制,很遗憾的导致不能用“const”
{
	CTextureMgr& TM = GetTextureMgr();
	for (size_t i=0;i<8;++i)
	{
		if (material.uTexture[i]==-1)
		{
			material.uTexture[i] = TM.RegisterTexture(material.getTexture(i));
		}
		// ----
		SetTexture(i, material.uTexture[i]);
		// ----
		if (material.uTexture[i]==0)
		{
			break;
		}
	}
	if (material.uShader==-1)
	{
		material.uShader = GetShaderMgr().registerItem(material.getShader());
	}
	// ----
	SetLightingEnabled(material.bLightingEnabled);
	SetCullingMode((CullingMode)material.uCull);
	// ----
	SetAlphaTestFunc(material.bAlphaTest, (CompareFunction)material.nAlphaTestCompare, material.uAlphaTestValue);
	SetBlendFunc(material.bBlend, (SceneBlendOperation)material.nBlendOP, (SceneBlendFactor)material.nBlendSrc, (SceneBlendFactor)material.nBlendDest);
	SetDepthBufferFunc(material.bDepthTest,material.bDepthWrite);
	// ----
	if (0==material.uShader)
	{
		for (size_t i=0;i<8;++i)
		{
			CMaterial::TextureOP& texOP = material.textureOP[i];
			SetTextureColorOP(i, (TextureBlendOperation)texOP.nColorOP, (TextureBlendSource)texOP.nColorSrc1, (TextureBlendSource)texOP.nColorSrc2);
			SetTextureColorOP(i, (TextureBlendOperation)texOP.nAlphaOP, (TextureBlendSource)texOP.nAlphaSrc1, (TextureBlendSource)texOP.nAlphaSrc2);
			if (TBOP_DISABLE == texOP.nColorOP)
			{
				break;
			}
		}
	}
	else
	{
		CShader* pShader = GetShaderMgr().getSharedShader();
		if (pShader)
		{
			// for Terrain
			pShader->setVec2D("g_fScaleUV",material.vUVScale);
		}
		SetShader(material.uShader);
	}
	return true;
/*	if (material.bLightingEnabled)
	{
		SetMaterial(material.vAmbient,material.vDiffuse);
	}

	if (0==material.uShader)
	{
		//SetSamplerAddressUV(0,ADDRESS_WRAP,ADDRESS_WRAP);
		if (material.vTexAnim.lengthSquared()>0.0f)
		{
			Matrix matTex=Matrix::UNIT;
			float fTime = (float)GetGlobalTimer().GetTime();
			matTex._13=fTime*material.vTexAnim.x;
			matTex._23=fTime*material.vTexAnim.y;
			setTextureMatrix(0, TTF_COUNT3, matTex);
		}

		Color32 cFactor = material.cEmissive;
		if (material.m_fOpacity<0.0f)
		{
			fOpacity = (float)(rand()%255)/255.0f;
		}
		else
		{
			fOpacity *= material.m_fOpacity;
		}

		if (material.uDiffuse)
		{
			SetTexture(0, material.uDiffuse);
			cFactor.a=(unsigned char)(cFactor.a*fOpacity);
			SetTextureFactor(cFactor);
			if (material.bLightingEnabled)
			{
				SetTextureColorOP(0, TBOP_MODULATE, TBS_TEXTURE, TBS_DIFFUSE);
			}
			else
			{
				SetTextureColorOP(0, TBOP_MODULATE, TBS_TEXTURE, TBS_TFACTOR);
			}
			if(material.bBlend||material.m_fOpacity<1.0f)
			{
				SetBlendFunc(true, BLENDOP_ADD, SBF_SOURCE_ALPHA, SBF_ONE_MINUS_SOURCE_ALPHA);
			}

			if (material.m_fOpacity<1.0f)
			{
				SetTextureAlphaOP(0, TBOP_MODULATE, TBS_TEXTURE, TBS_TFACTOR);
			}
			else if (material.bAlphaTest||material.bBlend)
			{
				SetTextureAlphaOP(0, TBOP_SOURCE1, TBS_TEXTURE);
			}
			else
			{
				SetTextureAlphaOP(0, TBOP_DISABLE);
			}

			//////////////////////////////////////////////////////////////////////////
			if (material.uSpecular)
			{
				SetTexture(1, material.uSpecular);
				SetTextureColorOP(0, TBOP_MODULATE, TBS_TEXTURE, TBS_DIFFUSE);
				setResultARGToTemp(1,true);
				SetTextureColorOP(1, TBOP_MODULATE_X2, TBS_TEXTURE, TBS_SPECULAR);
				SetTextureColorOP(2, TBOP_ADD, TBS_CURRENT, TBS_TEMP);

				SetTexCoordIndex(0,0);
				SetTexCoordIndex(1,0);
				SetTexCoordIndex(2,0);
			}
			else if (material.uReflection)
			{
				SetTextureColorOP(1, TBOP_MODULATE_X2, TBS_CURRENT, TBS_TEXTURE);
				SetTexCoordIndex(1,TCI_CAMERASPACE_NORMAL|TCI_CAMERASPACE_POSITION);
				SetTexture(1, material.uReflection);
			}
			else if (material.uLightMap)
			{
				SetTextureColorOP(1, TBOP_MODULATE, TBS_CURRENT, TBS_TEXTURE);
				SetTexCoordIndex(1,1);
				SetTexture(1, material.uLightMap);
			}
			else if (material.uEmissive)
			{
				SetTextureColorOP(1, TBOP_ADD, TBS_CURRENT, TBS_TEXTURE);
				SetTexture(1, material.uEmissive);
			}
			else if(!material.bBlend&&material.m_fOpacity>=1.0f)
			{
				SetTextureColorOP(0, TBOP_MODULATE, TBS_TEXTURE, TBS_DIFFUSE);
			}
		}
		else
		{
			SetTextureFactor(cFactor);
			if (material.uSpecular)
			{
				//SetTexture(0, material.uSpecular);
				SetTextureColorOP(0, TBOP_SOURCE1, TBS_SPECULAR);
				SetTexCoordIndex(0,0);
			}
			else if(material.uReflection)
			{
				cFactor.r=(unsigned char)(cFactor.r*fOpacity);
				cFactor.g=(unsigned char)(cFactor.g*fOpacity);
				cFactor.b=(unsigned char)(cFactor.b*fOpacity);
				SetTextureFactor(cFactor);
				if (material.bBlend)
				{
					SetBlendFunc(true, BLENDOP_ADD, SBF_DEST_COLOUR, SBF_ONE);
				}
				SetTextureColorOP(0, TBOP_MODULATE, TBS_TEXTURE, TBS_TFACTOR);
				SetTextureAlphaOP(0, TBOP_DISABLE);
				SetTexCoordIndex(0,TCI_CAMERASPACE_NORMAL|TCI_CAMERASPACE_POSITION);
				SetTexture(0, material.uReflection);
			}
			else if (material.uLightMap)
			{
				if (material.bBlend)
				{
					SetBlendFunc(true, BLENDOP_ADD, SBF_DEST_COLOUR, SBF_ZERO);
				}
				SetTextureColorOP(0, TBOP_MODULATE, TBS_TEXTURE, TBS_TFACTOR);
				SetTextureAlphaOP(0, TBOP_DISABLE);
				SetTexture(0, material.uLightMap);
			}
			else if (material.uEmissive)
			{
				cFactor.r=(unsigned char)(cFactor.r*fOpacity);
				cFactor.g=(unsigned char)(cFactor.g*fOpacity);
				cFactor.b=(unsigned char)(cFactor.b*fOpacity);
				SetTextureFactor(cFactor);
				if (material.bBlend)
				{
					SetBlendFunc(true, BLENDOP_ADD, SBF_ONE, SBF_ONE);
				}
				SetTextureColorOP(0, TBOP_MODULATE, TBS_TEXTURE, TBS_TFACTOR);
				SetTextureAlphaOP(0, TBOP_DISABLE);
				SetTexture(0, material.uEmissive);
			}
			else if (material.uNormal)
			{
				CShader* pShader = GetShaderMgr().getSharedShader();
				if (pShader)
				{
					static size_t s_uShaderID = GetShaderMgr().registerItem("EngineRes\\fx\\SpaceBump.fx");
					pShader->setTexture("g_texNormal",material.uNormal);
					SetShader(s_uShaderID);
				}
				//SetBlendFunc(true, BLENDOP_ADD, SBF_DEST_COLOUR, SBF_ZERO);
				//SetTextureColorOP(0, TBOP_MODULATE, TBS_TEXTURE, TBS_TFACTOR);
				//SetTextureAlphaOP(0, TBOP_DISABLE);
				//SetTexture(0, uLightMap);
			}
			else
			{
				SetTextureColorOP(0,TBOP_SOURCE2);
				if (material.bBlend)
				{
					SetTextureAlphaOP(0,TBOP_SOURCE2);
				}
				else
				{
					SetTextureAlphaOP(0,TBOP_DISABLE);
				}
				//return false;
			}
		}
	}
	else
	{
		CShader* pShader = GetShaderMgr().getSharedShader();
		if (pShader)
		{
			pShader->setTexture("g_texDiffuse",material.uDiffuse);
			pShader->setTexture("g_texLight",material.uLightMap);
			pShader->setTexture("g_texNormal",material.uNormal);
			//pShader->setTexture("g_texEnvironment",uEmissive);
			//pShader->setTexture("g_texEmissive",uEmissive);
			pShader->setTexture("g_texSpecular",material.uSpecular);
			// for Terrain
			pShader->setVec2D("g_fScaleUV",material.vUVScale);
		}
		SetShader(material.uShader);
	}
	return true;*/
}
Esempio n. 26
0
/**
Build the shadow volume for this mesh
*/
void CGeoChunk::BuildShadowVolume(CMDXModel *model,const AnimInfo& animInfo, ShadowVolume * pShadowVolume, LightParams* pLight, D3DXMATRIX* mxWorld)
{
	CMaterial* mat = model->materialMap.materials[materialID<0 ? 0 : materialID];

	CalcGroupMatrix(model);

	bool bCanCastShadow = false; // we will only cast shadows from chunks that does not contain blending or additive layers
	int numLayers = (int)mat->layers.size();
	for(int l=0;l<numLayers;l++)
	{
		float alpha=mat->getFrameAlpha(animInfo.currentFrame,l);

		if(alpha < myEPSILON)
			continue;
		else
		{
			if(myEPSILON == 0.0f)
				alpha = 1.0f;
		}
		if(AnimAlphas[vertexGroups[triangles[0]]] < myEPSILON)
		{
			continue;
		}
		
		//(0:none;1:transparent;2:blend;3:additive)
		if((mat->layers[l]->filterMode == 1) || (mat->layers[l]->filterMode == 0))
		{
			bCanCastShadow = true;
			break;
		}
	}
	if(!bCanCastShadow)
		return;

	/** build shadow volume based on this geochunk
	*/

	// TODO: light's direction relative to the object.
	// here we assume the light is a directional light.
	D3DXVECTOR3 vLight = pLight->Direction; 
	float fRange = pLight->Range;
	vLight = -vLight;
	/// transform the local matrices to global matrices.
	for(int k=0; k<numGroups; k++)
		matrixes[k] *= (*mxWorld);
	
    // Allocate a temporary edge list
	hash_set <EdgeHash, hash_compare_edge> m_edgeTable;

	DWORD dwNumFaces = numTriangles;
    DWORD dwNumEdges = 0;
	
	D3DXVECTOR3 * pVertices = NULL;
	DWORD dwNumVertices = 0;
	int nUseCap = model->m_nUseShadowCap | 
		((pShadowVolume->m_shadowMethod == ShadowVolume::SHADOW_Z_FAIL)?1:0);
	if(nUseCap>0)
	{
		pShadowVolume->ReserveNewBlock(&pVertices, numTriangles*3);
	}
	
	// For each face
    for( DWORD i=0; i<dwNumFaces; i++ )
    {
        WORD wFace0 = triangles[3*i+0];
        WORD wFace1 = triangles[3*i+1];
        WORD wFace2 = triangles[3*i+2];

        D3DXVECTOR3 v0 = vertices[wFace0];
        D3DXVECTOR3 v1 = vertices[wFace1];
        D3DXVECTOR3 v2 = vertices[wFace2];
		
		// transform the vertices so that they are in world coordicate system.
		D3DXVec3TransformCoord(&v0,&v0,&matrixes[vertexGroups[wFace0]]);
		D3DXVec3TransformCoord(&v1,&v1,&matrixes[vertexGroups[wFace1]]);
		D3DXVec3TransformCoord(&v2,&v2,&matrixes[vertexGroups[wFace2]]);
		
        // Transform vertices or transform light?
		// we use vertice transform, it may be more accurate to use light transform
        D3DXVECTOR3 vCross1(v2-v1);
        D3DXVECTOR3 vCross2(v1-v0);
        D3DXVECTOR3 vNormal;
        D3DXVec3Cross( &vNormal, &vCross1, &vCross2 );

        if( D3DXVec3Dot( &vNormal, &vLight ) >= 0.0f )
        {
			CEdgeBuilder::AddEdge( m_edgeTable, dwNumEdges, wFace0, wFace1 );
			CEdgeBuilder::AddEdge( m_edgeTable, dwNumEdges, wFace1, wFace2 );
			CEdgeBuilder::AddEdge( m_edgeTable, dwNumEdges, wFace2, wFace0 );
			
			if(nUseCap>0)
			{
				pVertices[dwNumVertices++] = v0;
				pVertices[dwNumVertices++] = v2;
				pVertices[dwNumVertices++] = v1;
			}
	    }
    }

	if(nUseCap>0)
	{
		// commit shadow volume front cap vertices
		pShadowVolume->CommitBlock(dwNumVertices);
		dwNumVertices = 0;
		pVertices = NULL;
	}

	/** 
	build shadow volume for the edge array 
	Interestingly, the extrusion of geometries for point light sources and 
	infinite directional light sources are different. see below.
	*/
	
	if(pLight->bIsDirectional)
	{
		/**
		 infinite directional light sources would extrude all silhouette edges to 
		 a single point at infinity.
		*/
		pShadowVolume->ReserveNewBlock(&pVertices, dwNumEdges*3);
		D3DXVECTOR3 v3 = D3DXVECTOR3(mxWorld->_41, mxWorld->_42, mxWorld->_43) + pLight->Direction * pLight->Range;
		
		hash_set <EdgeHash, hash_compare_edge>::iterator itCurCP, itEndCP = m_edgeTable.end();
	
		// first shutdown all connections
		for( itCurCP = m_edgeTable.begin(); itCurCP != itEndCP; ++ itCurCP)
		{
			int index1 = (*itCurCP).m_v0;
			int index2 = (*itCurCP).m_v1;

			D3DXVECTOR3 v1 = vertices[index1];
			D3DXVECTOR3 v2 = vertices[index2];
			
			// transform the vertices so that they are in world coordicate system.
			D3DXVec3TransformCoord(&v1,&v1,&matrixes[vertexGroups[index1]]);
			D3DXVec3TransformCoord(&v2,&v2,&matrixes[vertexGroups[index2]]);
			
     		// Add a quad (two triangles) to the vertex list
			pVertices[dwNumVertices++] = v1;
			pVertices[dwNumVertices++] = v2;
			pVertices[dwNumVertices++] = v3;
		}
		pShadowVolume->CommitBlock(dwNumVertices);
	}
#ifdef POINTLIGHT_SUPPORT
	else // TODO: for point light, the listed method is not correct
	{
		/**
		Point light sources would extrude the silhouette edges exactly point for point 
		*/

		pShadowVolume->ReserveNewBlock(&pVertices, dwNumEdges*6);
		for( i=0; i<dwNumEdges; i++ )
		{
			int index1 = pEdges[2*i+0];
			int index2 = pEdges[2*i+1];

			D3DXVECTOR3 v1 = vertices[index1];
			D3DXVECTOR3 v2 = vertices[index2];
			
			// transform the vertices so that they are in world coordicate system.
			D3DXVec3TransformCoord(&v1,&v1,&matrixes[vertexGroups[index1]]);
			D3DXVec3TransformCoord(&v2,&v2,&matrixes[vertexGroups[index2]]);
			
			D3DXVECTOR3 v3 = v1 - vLight*fRange;
			D3DXVECTOR3 v4 = v2 - vLight*fRange;

     		// Add a quad (two triangles) to the vertex list
			pVertices[dwNumVertices++] = v1;
			pVertices[dwNumVertices++] = v2;
			pVertices[dwNumVertices++] = v3;

			pVertices[dwNumVertices++] = v2;
			pVertices[dwNumVertices++] = v4;
			pVertices[dwNumVertices++] = v3;
		}
		pShadowVolume->CommitBlock(dwNumVertices);
	}
#endif
	
}
Esempio n. 27
0
void CGeoChunk::Render(CMDXModel *model,const AnimInfo& animInfo)
{
	LPDIRECT3DDEVICE9 pd3dDevice = CGlobals::GetRenderDevice();
	CMaterial* mat = model->materialMap.materials[materialID<0 ? 0 : materialID];

	CalcGroupMatrix(model);

	int numLayers = (int)mat->layers.size();
	for(int l=0;l<numLayers;l++)
	{
		// LiXizhi: turn off light except for the last layer
		// Is it a rule for all mdx models?
		//if(l<mat->numLayers-1)
		//	pd3dDevice->SetRenderState(D3DRS_LIGHTING,FALSE);
		//else
		//	pd3dDevice->SetRenderState(D3DRS_LIGHTING,TRUE);

		float alpha=mat->getFrameAlpha(animInfo.currentFrame,l);

		if(alpha < myEPSILON)
			continue;
		else
		{
			if(myEPSILON == 0.0f)
				alpha = 1.0f;
		}
		if(AnimAlphas[vertexGroups[triangles[0]]] < myEPSILON)
		{
			continue;
		}

		LPDIRECT3DTEXTURE9 pTexture=model->texture.GetBindTexture(mat->layers[l]->textureID);

		// TODO: handle team glow here.
		// <see blp.cpp: LoadBlp for more information on replaceable bitmap>
		// replaceable bitmap are shared bitmaps. However, I do not use shared bitmap in Paraengine.
		// so in the ReplaceIDWithName(), The teamcolor and glow are simply set to NULL texture.
		//if(model->texture.bitmaps[mat->layers[l].textureID].replaceableID == 1) // ! team glow
		//{
		//	
		//}

		BOOL bHasTexture;
		if(pTexture==0)
			bHasTexture = false;
		else
			bHasTexture = true;

		pd3dDevice->SetTexture(0, pTexture);


		//(0:none;1:transparent;2:blend;3:additive)
		if(mat->layers[l]->filterMode == 1)
		// transparent
		{
			pd3dDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
			pd3dDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA);
			pd3dDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA);
			pd3dDevice->SetRenderState(D3DRS_ALPHATESTENABLE, TRUE);
			pd3dDevice->SetRenderState(D3DRS_ALPHAREF, (DWORD)0x0000000BE);
			pd3dDevice->SetRenderState(D3DRS_ALPHAFUNC, D3DCMP_GREATER);
			pd3dDevice->SetRenderState( D3DRS_ZWRITEENABLE, TRUE );
		}else
		if(mat->layers[l]->filterMode == 2)
		// blend
		{
			pd3dDevice->SetRenderState(D3DRS_ALPHATESTENABLE, FALSE);
			pd3dDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
			pd3dDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA);
			pd3dDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA);
			pd3dDevice->SetRenderState( D3DRS_ZWRITEENABLE, FALSE );
	
		}else
		// additive
		if(mat->layers[l]->filterMode == 3 )
		{
			pd3dDevice->SetRenderState(D3DRS_ALPHATESTENABLE, FALSE);
			pd3dDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);	
			pd3dDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_ONE);
			pd3dDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_ONE);
			pd3dDevice->SetRenderState( D3DRS_ZWRITEENABLE, FALSE );
		}
		else
		{
			pd3dDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
			pd3dDevice->SetRenderState(D3DRS_ALPHATESTENABLE, FALSE);
			pd3dDevice->SetRenderState( D3DRS_ZWRITEENABLE, TRUE );
		}

		/* 
		* fill vertex buffer with new data and draw it 
		*/

		// the color of the model when no texture is specified;
		D3DXCOLOR colorModel = *(model->GetModelColor()); 

		my_vertex* vb_vertices;
		int nNumLockedVertice;
		int nNumFinishedVertice = 0;
		DynamicVertexBufferEntity* pBufEntity =  CGlobals::GetAssetManager()->GetDynamicBuffer(DVB_XYZ_TEX1_NORM_DIF);
		do
		{
			if( (nNumLockedVertice = pBufEntity->Lock((numTriangles*3 - nNumFinishedVertice), 
				(void**)(&vb_vertices))) > 0)
			{
				int nLockedNum = nNumLockedVertice/3;
				int index;

				for(int i=0;i<nLockedNum;++i)
				{
					for(int k=0; k<3; ++k)
					{
						int nVB = 3*i+k;
						int n = nNumFinishedVertice+nVB;
						
						int v0=triangles[n];
						index = vertexGroups[v0];

						D3DXVec3TransformCoord(&vb_vertices[nVB].v,&vertices[v0],&matrixes[index]);
						D3DXVec3TransformNormal(&vb_vertices[nVB].n,&normals[v0],&matrixes[index]);

						vb_vertices[nVB].tu = uvs[v0].x;
						vb_vertices[nVB].tv = uvs[v0].y;

						vb_vertices[nVB].colour = (bHasTexture==FALSE ? colorModel : 
							D3DCOLOR_COLORVALUE(1.0f,1.0f, 1.0f, 1.0f));
					}
				}

				pBufEntity->Unlock();

				DirectXPerf::DrawPrimitive( pd3dDevice, DirectXPerf::DRAW_PERF_TRIANGLES_MESH, D3DPT_TRIANGLELIST,pBufEntity->m_dwBase,nLockedNum);

				if((numTriangles*3 - nNumFinishedVertice) > nNumLockedVertice)
				{
					nNumFinishedVertice += nNumLockedVertice;
				}
				else
					break;
			}
			else 
				break;
		}while(1);
	}
}
Esempio n. 28
0
void CBall::Draw(bool bWireFrame)
{
	int nIndex = s_bOffscreenRender ? 1 : 0;

	if(!dispList_init_flag[nIndex])
	{
		InitDisplayList();
	}

	const dReal* pos = dGeomGetPosition(transBall);
	const dReal* gpos = dGeomGetPosition(gBall);
	const dReal* rot = dGeomGetRotation(transBall);
	
	position[ 0] = rot[0];
	position[ 1] = rot[4];
	position[ 2] = rot[8];
	position[ 3] = rot[3];
	position[ 4] = rot[1];
	position[ 5] = rot[5];
	position[ 6] = rot[9];
	position[ 7] = rot[7];
	position[ 8] = rot[2];
	position[ 9] = rot[6];
	position[10] = rot[10];
	position[11] = rot[11];
	position[12] = pos[0];
	position[13] = pos[1];
	position[14] = pos[2];
	position[15] = 1;

	const int log_size		= 300;
	static int max_log		= 0;
	static int current_log	= 0;
	static double pos_log[log_size][16];
	if(bWireFrame)
	{
		glPushMatrix();
		glMultMatrixd(position);
		glTranslatef(gpos[0], gpos[1], gpos[2]);
		material.setMaterial();
		glCallList(dispList_wire[nIndex]);
		glPopMatrix();

		max_log = current_log = 0;
	}
	else
	{
		if (!s_bOffscreenRender)
		{

			static float dif[4]  = {0.75,0.4,0.2,0.0};
			static float amb[4]  = {0.5,0.2,0.1,0.0};
			static float spec[4] = {1.0,1.0,1.0,0.0};
			if (bDrawTail)
			{

				glDepthMask(0);

				glEnable(GL_BLEND);
				glDisable(GL_LIGHTING);

				glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, dif);
				glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, amb);
				glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, spec);
				glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, 300);

				glBlendFunc(GL_SRC_ALPHA, GL_ONE);

				for (int i = 0;i < max_log; i++)
				{
					int j;
					if (max_log == log_size)
						j = (current_log + i) % log_size;
					else
						j = i;
					glColor4f(0.75,0.4,0.2, 0.5*(double)i / log_size);
					glPushMatrix();
					glMultMatrixd(pos_log[j]);
					glCallList(dispList_polygon[nIndex]);
					glPopMatrix();
				}

				glDisable(GL_BLEND);
				glEnable(GL_LIGHTING);
				glDepthMask(1);

				for (int i = 0;i < 16; i++)	pos_log[current_log][i] = position[i];
				current_log++;
				current_log = current_log % log_size;
				if (max_log < log_size)max_log++;
			}
			else
			{
				max_log = 0;
				current_log = 0;
			}
		}

		glPushMatrix();
		glMultMatrixd(position);
		material.setMaterial();
		glTranslatef(gpos[0], gpos[1], gpos[2]);
		glCallList(dispList_polygon[nIndex]);
		glPopMatrix();


	}

	glPushMatrix();
	glMultMatrixd(position);
	if(bWireFrame)
	{
		matr_blue.setMaterial();
		DrawSphere(0.005);
	}
	else
	{
	}
	glPopMatrix();
}
Esempio n. 29
0
void CAnimationInstance::DrawMeshFrame( D3DXFRAME_ANIM * pFrame)
{
	//! TODO: Insert code to draw the mesh here.
	HRESULT hr = S_OK;
	D3DXFRAME_ANIM * pAnimFrame = pFrame;
	D3DXMESHCONTAINER_ANIM * pMeshContainer = (D3DXMESHCONTAINER_ANIM *)pFrame->pMeshContainer;
	CShader* pShader;
	CMaterial* pMat;

	unsigned int uiAttrib;
	LPD3DXBONECOMBINATION pBoneCombination;

	unsigned int uiMatrixIndex;
	unsigned int uiPaletteEntry;
	D3DXMATRIXA16 matrixTemp;
	D3DCAPS9 d3dCaps;
	m_pAnimatedMesh->m_pD3DDevice->GetDeviceCaps(&d3dCaps);

	//! Check to see that there is Skinning Information
	if( pFrame->pMeshContainer->pSkinInfo != NULL)
	{
		//! Draw via Indexed HLSL VertexShader
		pBoneCombination = reinterpret_cast<LPD3DXBONECOMBINATION>(pMeshContainer->pBoneCombinationBuffer->GetBufferPointer());

		for( uiAttrib = 0; uiAttrib < pMeshContainer->NumAttributeGroups; uiAttrib++)
		{
			//! Calculate all the world matrices.
			for( uiPaletteEntry = 0; uiPaletteEntry < pMeshContainer->NumPaletteEntries; uiPaletteEntry++)
			{
				uiMatrixIndex = pBoneCombination[uiAttrib].BoneId[uiPaletteEntry];

				if( uiMatrixIndex != UINT_MAX)
				{
					D3DXMatrixMultiply( &m_pAnimatedMesh->m_pBoneMatrices[uiPaletteEntry], &pMeshContainer->pBoneOffsetMatrices[uiMatrixIndex], pMeshContainer->ppBoneMatrixPointers[uiMatrixIndex]);
				}
			}

			// Draw Mesh
			// (MR): Modified rendering code to work with shader management
			if(uiAttrib < pMeshContainer->NumMaterials)
				pMat = pMeshContainer->ppMaterials[uiAttrib];
			else
				pMat = pMeshContainer->ppMaterials[0];
			pShader = pMat->getShader();
			CShaderParam& oMatWorldArray = pShader->getParamBySemantic("WorldMatrixArray");
			if(oMatWorldArray.isValid())
				oMatWorldArray.setMatrixArray(m_pAnimatedMesh->m_pBoneMatrices, pMeshContainer->NumPaletteEntries);
			CShaderParam& oBoneCount = pShader->getParamBySemantic("BlendIndexCount");
			if(oBoneCount.isValid())
				oBoneCount = pMeshContainer->NumInfl - 1;

			//! Start Effect.  All parameters should be updated at this point.
			CShaderManager::getInstance().beginObjectRender();

			pMat->begin();
			for(unsigned int uiPass = 0; uiPass < pMat->getNumPasses(); uiPass++)
			{
				CShaderManager::getInstance().beginPass();
				pMat->beginPass(uiPass);
				//! Draw the subset with the current material and world matrix palette
				pMeshContainer->MeshData.pMesh->DrawSubset(uiAttrib);
				pMat->endPass();
			}
			pMat->end();
		}
	}
	
}
Esempio n. 30
0
CMaterial* CMaterialLoader::Load(const char* szName) {
    std::string str = "material/";
    str += szName;
    
	byte* buffer = NULL;
	unsigned int size = 0;
	if (!CXFile::ReadText(str.c_str(), buffer, size)) {
        XELOG("material file error: %s", szName);
		return NULL;
	}

	Json::Reader reader;
	Json::Value root;
	if (!reader.parse((const char*)buffer, root)) {
        XELOG("material parse error: %s", szName);
		XEDELETE(buffer);
		return NULL;
	}
    XEDELETE(buffer);

    for (int i=0; i<root.size(); ++i) {
        Json::Value& value = root[i];
        std::string type = value["type"].asString();
        printf("%s\n", type.c_str());
    }
    
    Json::Value material = CJson::GetByType(root, "material");
    if (material.isNull()) {
        XELOG("material not find material: %s", szName);
        return NULL;
    }
    
    CMaterial* pMaterial = XENEW(CMaterial);
    if (!pMaterial) {
        return NULL;
    }
    
    // 技术列表,目前只解析一个
    Json::Value& t_list = material["list"];
    Json::Value& technique = t_list[0];
    
    CTechnique* pTechnique = XENEW(CTechnique);
    if (!pTechnique) {
        XEDELETE(pMaterial);
        return NULL;
    }
    pMaterial->SetTechnique(pTechnique);
    
    // 解析pass列表,目前只解析一个
    Json::Value& p_list = technique["list"];
    Json::Value& pass = p_list[0];
    
    // 解析pass
    CPass* pPass = ParsePass(pass, root);
    if (!pPass) {
        XEDELETE(pMaterial);
    }
    pTechnique->SetPass(pPass);
    
    return pMaterial;
}