Exemplo n.º 1
0
//-----------------------------------------------------------------------------
// Purpose: 
// Input  : pDC - 
//			dstRect - 
//			detectErrors - 
//-----------------------------------------------------------------------------
void CMaterial::DrawBrowserIcons( CDC *pDC, RECT& dstRect, bool detectErrors )
{
	static CMaterial* pTranslucentIcon = 0;
	static CMaterial* pOpaqueIcon = 0;
	static CMaterial* pSelfIllumIcon = 0;
	static CMaterial* pBaseAlphaEnvMapMaskIcon = 0;
	static CMaterial* pErrorIcon = 0;

	if (!pTranslucentIcon)
	{
		pTranslucentIcon			= CreateMaterial("editor/translucenticon", true);
		pOpaqueIcon					= CreateMaterial("editor/opaqueicon", true);
		pSelfIllumIcon				= CreateMaterial("editor/selfillumicon", true);
		pBaseAlphaEnvMapMaskIcon	= CreateMaterial("editor/basealphaenvmapmaskicon", true);
		pErrorIcon					= CreateMaterial("editor/erroricon", true);

		Assert( pTranslucentIcon && pOpaqueIcon && pSelfIllumIcon && pBaseAlphaEnvMapMaskIcon && pErrorIcon );
	}

	bool error = false;

	IMaterial* pMaterial = GetMaterial();
	if ( pMaterial->GetMaterialVarFlag( MATERIAL_VAR_TRANSLUCENT ) )
	{
		DrawIcon( pDC, pTranslucentIcon, dstRect );
		if (detectErrors)
		{
			error = error || !m_TranslucentBaseTexture; 
		}
	}
	else
	{
		DrawIcon( pDC, pOpaqueIcon, dstRect ); 
	}

	if ( pMaterial->GetMaterialVarFlag( MATERIAL_VAR_SELFILLUM ))
	{
		DrawIcon( pDC, pSelfIllumIcon, dstRect ); 
		if (detectErrors)
		{
			error = error || !m_TranslucentBaseTexture;
		}
	}

	if ( pMaterial->GetMaterialVarFlag( MATERIAL_VAR_BASEALPHAENVMAPMASK ))
	{
		DrawIcon( pDC, pBaseAlphaEnvMapMaskIcon, dstRect ); 
		if (detectErrors)
		{
			error = error || !m_TranslucentBaseTexture;
		}
	}

	if (error)
	{
		DrawIcon( pDC, pErrorIcon, dstRect );
	}
}
	i32 CMaterialManager::Init()
	{
		m_mDefaultMaterials.clear();
		//Create default material
		Resources::CMaterial* pMat = xst_new Resources::CMaterial( m_pShaderMgr, DEFAULT_TECHNIQUE, this, 0, "xse_default_material", XST::ResourceType::MATERIAL, XST::ResourceStates::CREATED/*, xst_null*/ );
		if( pMat == xst_null )
		{
			return XST_FAIL;
		}

		IPass* pPass = pMat->GetCurrentTechnique()->GetPass( 0 );
		pPass->SetVertexShader( m_pShaderMgr->GetDefaultVertexShader( ) );
		pPass->SetPixelShader( m_pShaderMgr->GetDefaultPixelShader() );

		m_pDefaultMat = MaterialPtr( pMat );

		//Create default simple use materials
		xst_astring strShaderCode;
		strShaderCode.reserve( 2048 );

		{
			MaterialPtr pMat = CreateMaterial( DEFAULT_MAT_COLOR, DEFAULT_GROUP );
            // TODO: implement case if pMat is null if( !pMat ) this resource should be destroyed
			IPass* pPass = pMat->CreateTechnique( DEFAULT_TECHNIQUE, true )->GetPass( 0 );
			strShaderCode = m_pShaderMgr->CreateShaderCode( ILE::POSITION | ILE::COLOR, ILE::POSITION | ILE::COLOR );	
			VertexShaderPtr pVS = m_pShaderMgr->CompileVertexShader( "xse_default_color_vs", "vs_main", ILE::POSITION | ILE::COLOR, strShaderCode );
			PixelShaderPtr pPS = m_pShaderMgr->CompilePixelShader( "xse_default_color_ps", "ps_main", strShaderCode );

			pPass->SetVertexShader( pVS );
			pPass->SetPixelShader( pPS );
		}

		return XST_OK;
	}
	i32 CMaterialManager::PrepareMaterials(xst_castring& strGroup)
	{
		XST::CLuaTable MaterialsTable( "materials" );

		if( MaterialsTable.Create( &m_LuaApi, "materials" ) != RESULT::OK )
		{
			return RESULT::FAILED;
		}

		CLuaMaterialParser Parser;

		XST::CLuaTable::ChildTableItr TableItr = MaterialsTable.GetChildTableMap().begin();
		for(; TableItr != MaterialsTable.GetChildTableMap().end(); ++TableItr)
		{
			XST::CLuaTable* pTmpTable = TableItr->second;
			if( pTmpTable || this->GetResource( TableItr->first ).IsValid() ) continue;

			MaterialPtr pMat = CreateMaterial( TableItr->first, strGroup );
			if( Parser.Parse( pMat.GetPtr(), pTmpTable ) != RESULT::OK )
			{
				continue;
			}
		}

		return RESULT::OK;
	}
Exemplo n.º 4
0
bool CMaxMesh::CreateMaterial(Mtl *pMtl)
{
    // check for valid material
    if(pMtl == 0)
    {
        theExporter.SetLastError("Invalid material, please set a material on the node.", __FILE__, __LINE__);
        return false;
    }

    // check if we have a standard material
    if(pMtl->ClassID() == Class_ID(DMTL_CLASS_ID, 0))
    {
        // insert new material
        m_vectorStdMat.push_back((StdMat *)pMtl);
    }

    // handle all submaterials
    int subId;
    for(subId = 0; subId < pMtl->NumSubMtls(); subId++)
    {
        CreateMaterial(pMtl->GetSubMtl(subId));
    }

    return true;
}
Exemplo n.º 5
0
	//! gets a material using creation info. Attempts to match with an existing instance.
	Material* MaterialProvider::GetMaterial(const Material::CreationInfo& info)
	{
		if (auto material = FindMaterial(info))
			return material;
		else
			return CreateMaterial(info);
	}
Exemplo n.º 6
0
void plPlate::CreateFromResource(const char *resName)
{
    if (resName)
    {
        plMipmap* resTexture = new plMipmap;
        resTexture->CopyFrom(plClientResMgr::Instance().getResource(resName));

        plString keyName = plString::Format( "PlateResource#%d", fMagicUniqueKeyInt++ );
        hsgResMgr::ResMgr()->NewKey(keyName, resTexture, plLocation::kGlobalFixedLoc);
        CreateMaterial(resTexture->GetWidth(), resTexture->GetHeight(), true, resTexture);
    }
    else
    {
        // Null resource request - Create a blank Material instead
        CreateMaterial(32, 32, true);
    }
}
Exemplo n.º 7
0
BOOL DMeshRender::CreateMeshTeapot()
{
	if (FAILED(D3DXCreateTeapot(DDEInitialize::gRootDevice, &m_pMess, nullptr)))
		return FALSE;
	CreateMaterial();
	m_isEnabled = TRUE;
	return TRUE;
}
Exemplo n.º 8
0
BOOL DMeshRender::CreateMeshSphere(FLOAT radius)
{
	if (FAILED(D3DXCreateSphere(DDEInitialize::gRootDevice, radius, 32, 32, &m_pMess, nullptr)))
		return FALSE;
	CreateMaterial();
	m_isEnabled = TRUE;
	return TRUE;
}
Exemplo n.º 9
0
BOOL DMeshRender::CreateMeshBox(D3DXVECTOR3 size)
{
	if (FAILED(D3DXCreateBox(DDEInitialize::gRootDevice, size.x, size.y, size.z, &m_pMess, nullptr)))
		return FALSE;
	CreateMaterial();
	//m_isEnabled = TRUE;
	return TRUE;
}
Exemplo n.º 10
0
Material* MaterialCache2D::GetMaterial(Texture2D* texture, BlendMode blendMode)
{
    HashMap<Texture2D*, HashMap<int, SharedPtr<Material> > >::Iterator t = materials_.Find(texture);
    if (t == materials_.End())
    {
        SharedPtr<Material> material(CreateMaterial(texture, blendMode));
        materials_[texture][blendMode] = material;
        return material;
    }

    HashMap<int, SharedPtr<Material> >& materials = t->second_;
    HashMap<int, SharedPtr<Material> >::Iterator b = materials.Find(blendMode);
    if (b != materials.End())
        return b->second_;

    SharedPtr<Material> material(CreateMaterial(texture, blendMode));
    materials[blendMode] = material;

    return material;
}
Exemplo n.º 11
0
    DiFoliageLayer::DiFoliageLayer( DiFoliageMap* map , DiFoliageLayerDesc* desc)
        :mDesc(desc),
        mNeedUpdateMaterial(true),
        mDensityMap(NULL)
    {
        mWaveCount = 0;

        mDensityMap = DI_NEW DiByteMap(desc->mDensityMap,FOLIAGE_DENSITY_MAP_SIZE,FOLIAGE_DENSITY_MAP_SIZE);

        CreateMaterial();
    }
Exemplo n.º 12
0
EffectTranslucency::EffectTranslucency( Texture2D& _RTTarget ) : m_ErrorCode( 0 ), m_RTTarget( _RTTarget )
{
	//////////////////////////////////////////////////////////////////////////
	// Create the materials
	CHECK_MATERIAL( m_pMatDisplay = CreateMaterial( IDR_SHADER_TRANSLUCENCY_DISPLAY, "./Resources/Shaders/TranslucencyDisplay.hlsl", VertexFormatP3N3G3T2::DESCRIPTOR, "VS", NULL, "PS" ), 1 );
	CHECK_MATERIAL( m_pMatBuildZBuffer = CreateMaterial( IDR_SHADER_TRANSLUCENCY_BUILD_ZBUFFER, "./Resources/Shaders/TranslucencyBuildZBuffer.hlsl", VertexFormatP3N3G3T2::DESCRIPTOR, "VS", NULL, "PS" ), 2 );

	D3D_SHADER_MACRO	pMacros[2] = { { "TARGET_SIZE", "128" }, { NULL, NULL } };
	CHECK_MATERIAL( m_pMatDiffusion = CreateMaterial( IDR_SHADER_TRANSLUCENCY_DIFFUSION, "./Resources/Shaders/TranslucencyDiffusion.hlsl", VertexFormatPt4::DESCRIPTOR, "VS", NULL, "PS", pMacros ), 3 );

	//////////////////////////////////////////////////////////////////////////
	// Build some sphere primitives
	{
		Noise	N( 1 );

		m_pPrimTorusInternal = new Primitive( gs_Device, VertexFormatP3N3G3T2::DESCRIPTOR );
		GeometryBuilder::BuildTorus( 80, 50, 1.0f, 0.2f, *m_pPrimTorusInternal, NULL, TweakTorusInternal, &N );

		m_pPrimSphereExternal = new Primitive( gs_Device, VertexFormatP3N3G3T2::DESCRIPTOR );
		GeometryBuilder::MapperSpherical	Mapper( 4.0f, 2.0f );
		GeometryBuilder::BuildSphere( 80, 50, *m_pPrimSphereExternal, &Mapper, TweakSphereExternal, &N );
	}

	//////////////////////////////////////////////////////////////////////////
	// Build textures & render targets
	m_pRTZBuffer = new Texture2D( gs_Device, DIFFUSION_SIZE, DIFFUSION_SIZE, 1, PixelFormatRGBA16F::DESCRIPTOR, 1, NULL );
	m_pDepthStencil = new Texture2D( gs_Device, DIFFUSION_SIZE, DIFFUSION_SIZE, DepthStencilFormatD32F::DESCRIPTOR );

	m_ppRTDiffusion[0] = new Texture2D( gs_Device, DIFFUSION_SIZE, DIFFUSION_SIZE, 1, PixelFormatRGBA16F::DESCRIPTOR, 1, NULL );
	m_ppRTDiffusion[1] = new Texture2D( gs_Device, DIFFUSION_SIZE, DIFFUSION_SIZE, 1, PixelFormatRGBA16F::DESCRIPTOR, 1, NULL );


	//////////////////////////////////////////////////////////////////////////
	// Create the constant buffers
	m_pCB_Object = new CB<CBObject>( gs_Device, 10 );
	m_pCB_Diffusion = new CB<CBDiffusion>( gs_Device, 10 );
	m_pCB_Pass = new CB<CBPass>( gs_Device, 11 );
}
Exemplo n.º 13
0
//----------------------------------------------
// 8.01.2014
//----------------------------------------------
void BumpScene::Start()
{
    SimpleScene::Start();

    ShaderManager::Instance()->Load("Bump", "fx/Bump");
    CreateMaterial("Bump", "Bump");

    GameObject * plane = root->Find("l0");
    if (plane)
    {
        SphericalMoveBehavior * smb = new SphericalMoveBehavior(20, 5);
        plane->AddBehaviour(smb);
    }
}
Exemplo n.º 14
0
func InitializePlayer(int iPlr)
{
	// Message positioning
	SetPlrShowControlPos(iPlr, SHOWCTRLPOS_TopLeft);
	SetTutorialMessagePos(MSG_Top | MSG_Left | MSG_WidthRel | MSG_XRel, 50, 50, 30);
	
  SetPlrShowControl(0,"___345678_   345678 __________");  
  
  // Positionen speichern
  iBlnX = FindObject(BALN)->GetX(); iBlnY = FindObject(BALN)->GetY();
  iPlrX = FindObject(CLNK)->GetX(); iPlrY = FindObject(CLNK)->GetY();
  iCounter = 0;
  
  CreateMaterial(iPlr);
}
Exemplo n.º 15
0
bool CMaxMesh::Create(INode *pINode, Mesh *pIMesh, bool bDelete)
{
    // check for valid mesh
    if(pIMesh == 0)
    {
        theExporter.SetLastError("Invalid handle.", __FILE__, __LINE__);
        return false;
    }

    m_pINode = pINode;
    m_pIMesh = pIMesh;
    m_bDelete = bDelete;

    // recursively create materials
    if(!CreateMaterial(m_pINode->GetMtl())) return false;

    // build all normals if necessary
    m_pIMesh->checkNormals(TRUE);

    // precalculate the object transformation matrix
    m_tm = m_pINode->GetObjectTM(SecToTicks(theExporter.GetInterface()->GetCurrentTime()));

    // try to get the physique modifier
    m_pModifier = FindPhysiqueModifier(pINode);
    if(m_pModifier == 0)
    {
        // try to get the skin modifier
        m_pModifier = FindSkinModifier(pINode);
        if(m_pModifier == 0)
        {
                  m_pModifier = FindMorpherModifier(pINode);
                  if( m_pModifier == 0 ) {
                    m_modifierType = MODIFIER_NONE;
                  }
                  m_modifierType = MODIFIER_MORPHER;
        }
        else
        {
            m_modifierType = MODIFIER_SKIN;
        }
    }
    else
    {
        m_modifierType = MODIFIER_PHYSIQUE;
    }

    return true;
}
Exemplo n.º 16
0
void    plGraphPlate::SetDataRange( uint32_t min, uint32_t max, uint32_t width )
{
    uint32_t      height;


    width = IMakePow2( width + 4 );
    height = IMakePow2( max - min + 1 + 4 );

    CreateMaterial( width, height, true );
    fMin = min;
    fMax = max;

    SetDataLabels( fMin, fMax );
    SetColors();
    SetDataColors();
    ClearData();
}
Exemplo n.º 17
0
	inline void Renderer::m_RenderSprite(Camera* camera, Sprite* sprite, Transform* transform) {
		Material* material = sprite->material;
		if (material == NULL) return;
		
		CreateMaterial(material);
		CreateSpriteAttributes();
		SetProgram(material->GetOpenGLShader()->program);
		
		BindMaterial(material, camera->projection, camera->view, transform);
		BindSpriteAttributes(material);
		
		if (material->GetWireframe()) {
			glDrawArrays(GL_LINE_STRIP, 0, 4);
		} else {
			glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
		}
	}
Exemplo n.º 18
0
	inline void Renderer::m_RenderMeshFilter(Camera* camera, MeshFilter* meshFilter, Transform* transform) {
		Mesh* mesh = meshFilter->mesh;
		Material* material = meshFilter->material;
		if (mesh == NULL || material == NULL) return;
		
		CreateMaterial(material);
		CreateMeshAttributes(mesh);
		SetProgram(material->GetOpenGLShader()->program);
		
		BindMaterial(material, camera->projection, camera->view, transform);
		BindMeshAttributes(material, mesh);
		
		if (material->GetWireframe()) {
			glDrawElements(GL_LINES, mesh->indices.Length(), GL_UNSIGNED_INT, BUFFER_OFFSET(0));
		} else {
			glDrawElements(GL_TRIANGLES, mesh->indices.Length(), GL_UNSIGNED_INT, BUFFER_OFFSET(0));
		}
	}
Exemplo n.º 19
0
func RelaunchPlayer(iPlr)
{
	// Kommentar
	Sound("Oops");
	// Altes Material entfernen und neu erzeugen
  RemoveAll(FLAG); RemoveAll(LOAM); RemoveAll(BALN);
  CreateMaterial(iPlr);
  CreateObject(BALN, iBlnX, iBlnY, iPlr);
  // Neuen Clonk erzeugen, falls nötig
  if (!FindObject(CLNK)->GetAlive())
 	{
	  var pClonk = CreateObject(CLNK, iPlrX, iPlrY, iPlr);
	  MakeCrewMember(pClonk, iPlr);
	  SetCursor(iPlr, pClonk);
	}
  // Scriptcounter zurück setzen
  goto(iCounter);
}
Exemplo n.º 20
0
	void FbxUtil::LoadMaterial(const SceneNode::Ptr &ntNode, FbxNode *fbxNode)
	{
		if (fbxNode->GetMaterialCount() > 0)
		{
			FbxSurfaceMaterial *fbxMaterial = fbxNode->GetMaterial(0);

			// only supports phong material
			if (fbxMaterial->GetClassId().Is(FbxSurfacePhong::ClassId))
			{
				Material::Ptr material = EntityUtil::Instance()->FindEntity<Material>(fbxMaterial->GetName());

				if (material == nullptr)
				{
					material = CreateMaterial(fbxMaterial);
					EntityUtil::Instance()->AddEntity(material);
				}

				if (auto ptr = ntNode->GetComponent<MeshRender>())
					ptr->SetMaterial(material);
			}
		}
	}
Exemplo n.º 21
0
int XFileLoader::ReadMaterial(istream& s)
{
	XFileToken t = XFileToken::NextToken(s);
	string materialName;
	if (t.m_type == XFileToken::Identifier)
	{
		materialName = move(t.m_content);
		t = XFileToken::NextToken(s);
	}
    if (t.m_type != XFileToken::LeftBrace)
        THROW_EXCEPTION_T("Parsing error", ParsingException);
    vec4 diffColor;
    vec3 specColor;
    vec3 emisColor;
	float pow;
	ReadMember(s, diffColor);
	ReadMember(s, pow);
	ReadMember(s, specColor);
	ReadMember(s, emisColor);
	string texFile;
	while (true)
	{
		t = XFileToken::NextToken(s);
		if (t.m_type == XFileToken::Identifier)
		{
			if ( t.m_content == "TextureFilename")
				texFile = ReadTextureFilename(s);
			else
				SkipDataObject(s);
		}
		else if (t.m_type == XFileToken::LeftBrace)
			SkipDataReference(s);
		else if (t.m_type == XFileToken::RightBrace)
			break;
        else
            THROW_EXCEPTION_T("Parsing error", ParsingException);
	}
    return CreateMaterial(materialName, diffColor, vec4(specColor.x, specColor.y, specColor.z, pow), texFile);
}
Exemplo n.º 22
0
 virtual void ComputeLocalSystemMats(bool ifInitial) {
   int full_lfs = this->lfs_ * this->spaceDim_;
   if(!ifInitial) { 
     renewMaterialVector();	
     this->gradgradMats_ = Teuchos::rcp(new Intrepid::FieldContainer<Real>(this->numCells_, full_lfs, full_lfs));
     Construct_CBmats(ifInitial);
     Intrepid::FunctionSpaceTools::integrate<Real>(*this->gradgradMats_, // compute local grad.grad (stiffness) matrices
                                                   *this->CBMat_,
                                                   *this->BMatWeighted_,
                                                   Intrepid::COMP_CPP);
     return;
   }	
   CreateMaterial();
   this->gradgradMats0_ = Teuchos::rcp(new Intrepid::FieldContainer<Real>(this->numCells_, full_lfs, full_lfs));
   this->gradgradMats_  = Teuchos::rcp(new Intrepid::FieldContainer<Real>(this->numCells_, full_lfs, full_lfs));
   this->valvalMats_    = Teuchos::rcp(new Intrepid::FieldContainer<Real>(this->numCells_, full_lfs, full_lfs));
   
   this->BMat_		 = Teuchos::rcp(new Intrepid::FieldContainer<Real>(this->numCells_, full_lfs, this->numCubPoints_, this->materialTensorDim_));
   this->BMatWeighted_	 = Teuchos::rcp(new Intrepid::FieldContainer<Real>(this->numCells_, full_lfs, this->numCubPoints_, this->materialTensorDim_));
   CBMat0_ 		 = Teuchos::rcp(new Intrepid::FieldContainer<Real>(this->numCells_, full_lfs, this->numCubPoints_, this->materialTensorDim_));
   this->CBMat_         = Teuchos::rcp(new Intrepid::FieldContainer<Real>(this->numCells_, full_lfs, this->numCubPoints_, this->materialTensorDim_));
   this->NMat_		 = Teuchos::rcp(new Intrepid::FieldContainer<Real>(this->numCells_, full_lfs, this->numCubPoints_, this->spaceDim_));
   this->NMatWeighted_   = Teuchos::rcp(new Intrepid::FieldContainer<Real>(this->numCells_, full_lfs, this->numCubPoints_, this->spaceDim_));
   this->Construct_N_B_mats();
   Construct_CBmats(ifInitial);
   Intrepid::FunctionSpaceTools::integrate<Real>(*this->gradgradMats0_, // compute local grad.grad (stiffness) matrices
                                                 *CBMat0_,
                                                 *this->BMatWeighted_,
                                                 Intrepid::COMP_CPP);
   Intrepid::FunctionSpaceTools::integrate<Real>(*this->gradgradMats_,  // compute local grad.grad (stiffness) matrices
                                                 *this->CBMat_,
                                                 *this->BMatWeighted_,
                                                 Intrepid::COMP_CPP);
   Intrepid::FunctionSpaceTools::integrate<Real>(*this->valvalMats_,    // compute local val.val (mass) matrices
                                                 *this->NMat_,
                                                 *this->NMatWeighted_,
                                                 Intrepid::COMP_CPP);
 }
Exemplo n.º 23
0
void CComponentGraphic_GL::CreateMaterials()
{
    if (m_pFont == NULL)
    {
        m_pFont = FCGUI::CFontManager::GetInstance()->GetFace(_T("ComponentGraphicFont"));
        if (m_pFont == NULL)
        {
            m_pFont = FCGUI::CFontManager::GetInstance()->CreateFace(_T("ComponentGraphicFont"), _T("msyh.ttf"), 12, 0);
        }
    }
    BEATS_ASSERT(m_pFont != NULL);
    if (m_pMaterials[eCT_RectBG].Get() == NULL)
    {
        m_pMaterials[eCT_RectBG] = CreateMaterial(_T("Component/RectBG.jpg"));
        m_pMaterials[eCT_ConnectRect] = CreateMaterial(_T("Component/ConnectRect.jpg"));
        m_pMaterials[eCT_SelectedRectBG] = CreateMaterial(_T("Component/SelectedRect.png"));
        m_pMaterials[eCT_NormalLine] = CreateMaterial(_T("Component/NormalLine.jpg"));
        m_pMaterials[eCT_SelectedLine] = CreateMaterial(_T("Component/SelectedLine.jpg"));
        m_pMaterials[eCT_NormalArrow] = CreateMaterial(_T("Component/NormalArrow.png"));
        m_pMaterials[eCT_SelectedArrow] = CreateMaterial(_T("Component/SelectedArrow.png"));
        m_pMaterials[eCT_ConnectedDependency] = CreateMaterial(_T("Component/ConnectedDependency.jpg"));
        m_pMaterials[eCT_ConnectedDependencyList] = CreateMaterial(_T("Component/ConnectedDependencyList.jpg"));
        m_pMaterials[eCT_WeakDependency] = CreateMaterial(_T("Component/WeakDependency.jpg"));
        m_pMaterials[eCT_WeakDependencyList] = CreateMaterial(_T("Component/WeakDependencyList.jpg"));
        m_pMaterials[eCT_StrongDependency] = CreateMaterial(_T("Component/StrongDependency.jpg"));
        m_pMaterials[eCT_StrongDependencyList] = CreateMaterial(_T("Component/StrongDependencyList.jpg"));
    }
}
Exemplo n.º 24
0
bool CCharShape::Load (string dir, string filename, bool with_actions) {
	CSPList list (500);
	int i, ii, act;
	string line, order, name, mat_name, fullname;
	TVector3 scale, trans, rot;
	double visible;
	bool shadow;
	int node_name, parent_name;

	useActions = with_actions;
	CreateRootNode ();
	newActions = true;

	file_name = filename;
 	if (!list.Load (dir, filename)) {
		Message ("could not load character", filename.c_str());
		return false;
	}

	for (i=0; i<list.Count(); i++) {
		line = list.Line (i);
		node_name = SPIntN (line, "node", -1); 
		parent_name = SPIntN (line, "par", -1);		
		mat_name = SPStrN (line, "mat", "");
		name = SPStrN (line, "joint", "");	
		fullname = SPStrN (line, "name", "");

		if (SPIntN (line, "material", 0) > 0) {
			CreateMaterial (line.c_str());
			if (useActions) {
				Matlines[numMatlines] = line;
				numMatlines++;
			}
		} else {
			visible = SPFloatN (line, "vis", -1.0);	
			shadow = SPBoolN (line, "shad", false);
			order = SPStrN (line, "order", "");
 			CreateCharNode (parent_name, node_name, name, fullname, order, shadow);					
			rot = SPVector3N (line, "rot", NullVec);
			MaterialNode (node_name, mat_name);
			for (ii=0; ii<(int)order.size(); ii++) {
				act = order.at(ii)-48;	
				switch (act) {
					case 0:
						trans = SPVector3N (line, "trans", MakeVector (0,0,0));
						TranslateNode (node_name, trans);
						break;
					case 1: RotateNode (node_name, 1, rot.x); break;
					case 2: RotateNode (node_name, 2, rot.y); break;
					case 3: RotateNode (node_name, 3, rot.z); break;
					case 4:
						scale = SPVector3N (line, "scale", MakeVector (1,1,1));
						ScaleNode (node_name, scale);
						break;
					case 5: VisibleNode (node_name, visible); break;
					case 9: RotateNode (node_name, 2, rot.z); break;
					default: break;
				}
			}
		}
	}
	newActions = false;
	return true;
}
Exemplo n.º 25
0
bool CCharShape::Load (const string& dir, const string& filename, bool with_actions) {
	CSPList list (500);

	useActions = with_actions;
	CreateRootNode ();
	newActions = true;

	if (!list.Load (dir, filename)) {
		Message ("could not load character", filename);
		return false;
	}

	for (size_t i=0; i<list.Count(); i++) {
		const string& line = list.Line(i);
		int node_name = SPIntN (line, "node", -1);
		int parent_name = SPIntN (line, "par", -1);
		string mat_name = SPStrN (line, "mat");
		string name = SPStrN (line, "joint");
		string fullname = SPStrN (line, "name");

		if (SPIntN (line, "material", 0) > 0) {
			CreateMaterial (line);
		} else {
			float visible = SPFloatN (line, "vis", -1.0);
			bool shadow = SPBoolN (line, "shad", false);
			string order = SPStrN (line, "order");
			CreateCharNode (parent_name, node_name, name, fullname, order, shadow);
			TVector3d rot = SPVector3d(line, "rot");
			MaterialNode (node_name, mat_name);
			for (size_t ii = 0; ii < order.size(); ii++) {
				int act = order[ii]-48;
				switch (act) {
					case 0: {
						TVector3d trans = SPVector3d(line, "trans");
						TranslateNode (node_name, trans);
						break;
					}
					case 1:
						RotateNode (node_name, 1, rot.x);
						break;
					case 2:
						RotateNode (node_name, 2, rot.y);
						break;
					case 3:
						RotateNode (node_name, 3, rot.z);
						break;
					case 4: {
						TVector3d scale = SPVector3(line, "scale", TVector3d(1, 1, 1));
						ScaleNode (node_name, scale);
						break;
					}
					case 5:
						VisibleNode (node_name, visible);
						break;
					case 9:
						RotateNode (node_name, 2, rot.z);
						break;
					default:
						break;
				}
			}
		}
	}
	newActions = false;
	return true;
}
Exemplo n.º 26
0
/**
 * Emits a create material signal.
 */
void ActionInsertMaterial::OnActionInsertMaterialTriggered()
{
	emit CreateMaterial( m_pTMaterialFactory );
}
Exemplo n.º 27
0
Ogre::Entity*
ModelFile::GetModel( const ModelInfo& info )
{
    VectorTexForGen textures;
    Ogre::MeshPtr mesh = Ogre::MeshManager::getSingleton().create( info.data.name + "export", "General" );
    Ogre::SkeletonPtr skeleton = Ogre::SkeletonManager::getSingleton().create( info.data.name + "export", "General" );

    int number_of_bones = GetU8( 0x02 );
    int number_of_parts = GetU8( 0x03 );
    int offset_to_bones = GetU32LE( 0x0c );
    int offset_to_parts = GetU32LE( 0x10 );



    Ogre::Bone* root1 = skeleton->createBone( "0", 0 );
    Ogre::Bone* root2 = skeleton->createBone( "1", 1 );
    root1->addChild( root2 );

    for( int i = 0; i < number_of_bones; ++i )
    {
        Bone bone;
        bone.parent_id = ( i != 0 ) ? ( s8 )GetU8( offset_to_bones + i * 0x04 + 0x03 ) : -1;
        bone.length    = ( s16 )GetU16LE( offset_to_bones + i * 0x04 + 0x00 );
        m_Skeleton.push_back(bone);

        Ogre::Bone* bone1 = skeleton->createBone( Ogre::StringConverter::toString( i * 2 + 2 ), i * 2 + 2 );
        Ogre::Bone* bone2 = skeleton->createBone( Ogre::StringConverter::toString( i * 2 + 3 ), i * 2 + 3 );

        LOGGER->Log( "Add skeleton bone: bone_id = " + Ogre::StringConverter::toString( i ) + ", length = " + Ogre::StringConverter::toString( bone.length ) + ", parent = " + Ogre::StringConverter::toString( bone.parent_id ) + ".\n" );

        if( bone.parent_id == -1 )
        {
            skeleton->getBone( 1 )->addChild( bone1 );
        }
        else
        {
            skeleton->getBone( bone.parent_id * 2 + 3 )->addChild( bone1 );
        }
        bone1->addChild( bone2 );
    }



    AnimationExtractor( skeleton, info, m_Skeleton );



    // draw skeleton
    {
        //DrawSkeleton( m_Skeleton, mesh );
    }



    for( int i = 0; i < number_of_parts; ++i )
    {
        MeshExtractor( info.data, "ffix/field_model/" + info.data.name, this, offset_to_parts + i * 0x28, textures, mesh );
    }



    // <OGRE> ///////////////////////////////
    skeleton->optimiseAllAnimations();
    Ogre::SkeletonSerializer skeleton_serializer;
    skeleton_serializer.exportSkeleton( skeleton.getPointer(), "exported/models/field/units/" + info.data.name + ".skeleton" );

    // Update bounds
    Ogre::AxisAlignedBox aabb( -999, -999, -999, 999, 999, 999 );
    mesh->_setBounds( aabb, false );
    mesh->_setBoundingSphereRadius( 999 );

    mesh->setSkeletonName( "models/field/units/" + info.data.name + ".skeleton" );

    Ogre::MeshSerializer ser;
    ser.exportMesh( mesh.getPointer(), "exported/models/field/units/" + info.data.name + ".mesh" );



    // create and export textures for model
    //if (textures.size() > 0)
    {
        Vram* vram = new Vram();

        File* tex = new File( "./data/field/5/1b/2/4/1.tim" );
        LoadTimFileToVram( tex, 0, vram );
        delete tex;
        tex = new File( "./data/field/5/1b/2/4/2.tim" );
        LoadTimFileToVram( tex, 0, vram );
        delete tex;

        vram->Save( "1.jpg" );

        CreateTexture( vram, info.data, "exported/models/field/units/" + info.data.name + ".png", textures );

        delete vram;
    }



    CreateMaterial( "ffix/field_model/" + info.data.name, "exported/models/field/units/" + info.data.name + ".material", ( textures.size() > 0 ) ? "models/field/units/" + info.data.name + ".png" : "", "", "" );



    Ogre::SceneManager* scene_manager = Ogre::Root::getSingleton().getSceneManager( "Scene" );
    Ogre::Entity* thisEntity = scene_manager->createEntity( info.data.name, "models/field/units/" + info.data.name + ".mesh" );
    //thisEntity->setDisplaySkeleton(true);
    //thisEntity->setDebugDisplayEnabled(true);
    thisEntity->setVisible( false );
    thisEntity->getAnimationState( info.animations_name[ 0 ] )->setEnabled(true);
    thisEntity->getAnimationState( info.animations_name[ 0 ] )->setLoop(true);
    Ogre::SceneNode* thisSceneNode = scene_manager->getRootSceneNode()->createChildSceneNode();
    thisSceneNode->setPosition( 0, 0, 0 );
    thisSceneNode->roll( Ogre::Radian( Ogre::Degree( 180.0f ) ) );
    thisSceneNode->yaw( Ogre::Radian( Ogre::Degree( 120.0f ) ) );
    thisSceneNode->pitch( Ogre::Radian( Ogre::Degree(90.0f ) ) );
    thisSceneNode->attachObject( thisEntity );

    return thisEntity;
}
Exemplo n.º 28
0
bool vtkOsgConverter::WriteAnActor()
{
	vtkMapper* actorMapper = _actor->GetMapper();
	// see if the actor has a mapper. it could be an assembly
	if (actorMapper == NULL)
		return false;
	// dont export when not visible
	if (_actor->GetVisibility() == 0)
		return false;

	vtkDataObject* inputDO = actorMapper->GetInputDataObject(0, 0);
	if (inputDO == NULL)
		return false;

	// Get PolyData. Convert if necessary becasue we only want polydata
	vtkSmartPointer<vtkPolyData> pd;
	if(inputDO->IsA("vtkCompositeDataSet"))
	{
		vtkCompositeDataGeometryFilter* gf = vtkCompositeDataGeometryFilter::New();
		gf->SetInput(inputDO);
		gf->Update();
		pd = gf->GetOutput();
		gf->Delete();
	}
	else if(inputDO->GetDataObjectType() != VTK_POLY_DATA)
	{
		vtkGeometryFilter* gf = vtkGeometryFilter::New();
		gf->SetInput(inputDO);
		gf->Update();
		pd = gf->GetOutput();
		gf->Delete();
	}
	else
		pd = static_cast<vtkPolyData*>(inputDO);

	// Get the color range from actors lookup table
	double range[2];
	vtkLookupTable* actorLut = static_cast<vtkLookupTable*>(actorMapper->GetLookupTable());
	actorLut->GetTableRange(range);

	// Copy mapper to a new one
	vtkPolyDataMapper* pm = vtkPolyDataMapper::New();
	// Convert cell data to point data
	// NOTE: Comment this out to export a mesh
	if (actorMapper->GetScalarMode() == VTK_SCALAR_MODE_USE_CELL_DATA ||
		actorMapper->GetScalarMode() == VTK_SCALAR_MODE_USE_CELL_FIELD_DATA)
	{
		vtkCellDataToPointData* cellDataToPointData = vtkCellDataToPointData::New();
		cellDataToPointData->PassCellDataOff();
		cellDataToPointData->SetInput(pd);
		cellDataToPointData->Update();
		pd = cellDataToPointData->GetPolyDataOutput();
		cellDataToPointData->Delete();

		pm->SetScalarMode(VTK_SCALAR_MODE_USE_POINT_DATA);
	}
	else
		pm->SetScalarMode(actorMapper->GetScalarMode());

	pm->SetInput(pd);
	pm->SetScalarVisibility(actorMapper->GetScalarVisibility());

	vtkLookupTable* lut = NULL;
	// ParaView OpenSG Exporter
	if (dynamic_cast<vtkDiscretizableColorTransferFunction*>(actorMapper->GetLookupTable()))
		lut = actorLut;
	// Clone the lut in OGS because otherwise the original lut gets destroyed
	else
	{
		lut = vtkLookupTable::New();
		lut->DeepCopy(actorLut);
		lut->Build();
	}
	pm->SetLookupTable(lut);
	pm->SetScalarRange(range);
	pm->Update();

	if(pm->GetScalarMode() == VTK_SCALAR_MODE_USE_POINT_FIELD_DATA ||
	   pm->GetScalarMode() == VTK_SCALAR_MODE_USE_CELL_FIELD_DATA )
	{
		if(actorMapper->GetArrayAccessMode() == VTK_GET_ARRAY_BY_ID )
			pm->ColorByArrayComponent(actorMapper->GetArrayId(),
			                          actorMapper->GetArrayComponent());
		else
			pm->ColorByArrayComponent(actorMapper->GetArrayName(),
			                          actorMapper->GetArrayComponent());
	}


	vtkPointData* pntData = pd->GetPointData();
	bool hasTexCoords = false;
	vtkUnsignedCharArray* vtkColors = pm->MapScalars(1.0);

	// ARRAY SIZES
	vtkIdType m_iNumPoints = pd->GetNumberOfPoints();
	if (m_iNumPoints == 0)
		return false;
	vtkIdType m_iNumGLPoints = pd->GetVerts()->GetNumberOfCells();
	vtkIdType m_iNumGLLineStrips = pd->GetLines()->GetNumberOfCells();
	vtkIdType m_iNumGLPolygons = pd->GetPolys()->GetNumberOfCells();
	vtkIdType m_iNumGLTriStrips = pd->GetStrips()->GetNumberOfCells();
	vtkIdType m_iNumGLPrimitives = m_iNumGLPoints + m_iNumGLLineStrips + m_iNumGLPolygons +
	                               m_iNumGLTriStrips;
	bool lit = !(m_iNumGLPolygons == 0 && m_iNumGLTriStrips == 0);

	if (_verbose)
	{
		std::cout << "Array sizes:" << std::endl;
		std::cout << "  number of vertices: " << m_iNumPoints << std::endl;
		std::cout << "  number of GL_POINTS: " << m_iNumGLPoints << std::endl;
		std::cout << "  number of GL_LINE_STRIPS: " << m_iNumGLLineStrips << std::endl;
		std::cout << "  number of GL_POLYGON's: " << m_iNumGLPolygons << std::endl;
		std::cout << "  number of GL_TRIANGLE_STRIPS: " << m_iNumGLTriStrips << std::endl;
		std::cout << "  number of primitives: " << m_iNumGLPrimitives << std::endl;
	}

	// NORMALS
	vtkDataArray* vtkNormals = NULL;
	int m_iNormalType = NOT_GIVEN;
	if (_actor->GetProperty()->GetInterpolation() == VTK_FLAT)
	{
		vtkNormals = pd->GetCellData()->GetNormals();
		if (vtkNormals != NULL)
			m_iNormalType = PER_CELL;
	}
	else
	{
		vtkNormals = pntData->GetNormals();
		if (vtkNormals != NULL)
			m_iNormalType = PER_VERTEX;
	}
	if (_verbose)
	{
		std::cout << "Normals:" << std::endl;
		if (m_iNormalType != NOT_GIVEN)
		{
			std::cout << "  number of normals: " << vtkNormals->GetNumberOfTuples() <<
			std::endl;
			std::cout << "  normals are given: ";
			std::cout <<
			((m_iNormalType == PER_VERTEX) ? "per vertex" : "per cell") << std::endl;
		}
		else
			std::cout << "  no normals are given" << std::endl;
	}

	// COLORS
	int m_iColorType = NOT_GIVEN;
	if(pm->GetScalarVisibility())
	{
		int iScalarMode = pm->GetScalarMode();
		if(vtkColors == NULL)
		{
			m_iColorType = NOT_GIVEN;
			std::cout << "WARNING: MapScalars(1.0) did not return array!" << std::endl;
		}
		else if(iScalarMode == VTK_SCALAR_MODE_USE_CELL_DATA)
			m_iColorType = PER_CELL;
		else if(iScalarMode == VTK_SCALAR_MODE_USE_POINT_DATA)
			m_iColorType = PER_VERTEX;
		else if(iScalarMode == VTK_SCALAR_MODE_USE_CELL_FIELD_DATA)
		{
			std::cout <<
			"WARNING TO BE REMOVED: Can not process colours with scalar mode using cell field data!"
			          << std::endl;
			m_iColorType = PER_CELL;
		}
		else if(iScalarMode == VTK_SCALAR_MODE_USE_POINT_FIELD_DATA)
		{
			std::cout <<
			"WARNING TO BE REMOVED: Can not process colours with scalar mode using point field data!"
			          << std::endl;
			m_iColorType = PER_VERTEX;
		}
		else if(iScalarMode == VTK_SCALAR_MODE_DEFAULT)
		{
			//Bummer, we do not know what it is. may be we can make a guess
			int numColors = vtkColors->GetNumberOfTuples();
			if (numColors == 0)
			{
				m_iColorType = NOT_GIVEN;
				std::cout << "WARNING: No colors found!" << std::endl;
			}
			else if (numColors == m_iNumPoints)
				m_iColorType = PER_VERTEX;
			else if (numColors == m_iNumGLPrimitives)
				m_iColorType = PER_CELL;
			else
			{
				m_iColorType = NOT_GIVEN;
				std::cout <<
				"WARNING: Number of colors do not match number of points / cells!"
				          << std::endl;
			}
		}
	}
	if (_verbose)
	{
		std::cout << "Colors:" << std::endl;
		if (m_iColorType != NOT_GIVEN)
		{
			std::cout << "  number of colors: " << vtkColors->GetNumberOfTuples() <<
			std::endl;
			std::cout << "  colors are given: " <<
			((m_iColorType == PER_VERTEX) ? "per vertex" : "per cell") << std::endl;
		}
		else
			std::cout << "  no colors are given" << std::endl;
	}

	// TEXCOORDS
	vtkDataArray* vtkTexCoords = pntData->GetTCoords();
	if (_verbose)
	{
		std::cout << "Tex-coords:" << std::endl;
		if (vtkTexCoords)
		{
			std::cout << "  Number of tex-coords: " <<
			vtkTexCoords->GetNumberOfTuples() << std::endl;
			hasTexCoords = true;
		}
		else
			std::cout << "  No tex-coords where given" << std::endl;
	}

	// TRANSFORMATION
	double scaling[3];
	double translation[3];
	// double rotation[3];

	_actor->GetPosition(translation);
	_actor->GetScale(scaling);
	//_actor->GetRotation(rotation[0], rotation[1], rotation[2]);

	if (_verbose)
		std::cout << "set scaling: " << scaling[0] << " " << scaling[1] << " " <<
		scaling[2] << std::endl;

	osg::Matrix m;
	m.setIdentity();
	m.setTranslate(translation[0], translation[1], translation[2]);
	m.setScale(scaling[0], scaling[1], scaling[2]);
	// TODO QUATERNION m.setRotate(rotation[0], rotation[1], rotation[2])
	beginEditCP(_osgTransform);
	_osgTransform->setMatrix(m);
	endEditCP(_osgTransform);

	//pm->Update();

	// Get the converted OpenSG node
	NodePtr osgGeomNode = Node::create();
	GeometryPtr osgGeometry = Geometry::create();
	beginEditCP(osgGeomNode);
	osgGeomNode->setCore(osgGeometry);
	endEditCP(osgGeomNode);

	bool osgConversionSuccess = false;

	GeoPTypesPtr osgTypes = GeoPTypesUI8::create();
	GeoPLengthsPtr osgLengths = GeoPLengthsUI32::create();
	GeoIndicesUI32Ptr osgIndices = GeoIndicesUI32::create();
	GeoPositions3fPtr osgPoints = GeoPositions3f::create();
	GeoNormals3fPtr osgNormals = GeoNormals3f::create();
	GeoColors3fPtr osgColors = GeoColors3f::create();
	GeoTexCoords2dPtr osgTexCoords = GeoTexCoords2d::create();

	//Rendering with OpenSG simple indexed geometry
	if (((m_iNormalType == PER_VERTEX) || (m_iNormalType == NOT_GIVEN)) &&
		((m_iColorType == PER_VERTEX) || (m_iColorType == NOT_GIVEN)))
	{
		if (_verbose)
			std::cout << "Start ProcessGeometryNormalsAndColorsPerVertex()" << std::endl;

		//getting the vertices:
		beginEditCP(osgPoints);
		{
			for (int i = 0; i < m_iNumPoints; i++)
			{
				double* aVertex = pd->GetPoint(i);
				osgPoints->addValue(Vec3f(aVertex[0], aVertex[1], aVertex[2]));
			}
		} endEditCP(osgPoints);

		//possibly getting the normals
		if (m_iNormalType == PER_VERTEX)
		{
			vtkIdType iNumNormals = vtkNormals->GetNumberOfTuples();
			beginEditCP(osgNormals);
			{
				double* aNormal;
				for (int i = 0; i < iNumNormals; i++)
				{
					aNormal = vtkNormals->GetTuple(i);
					osgNormals->addValue(Vec3f(aNormal[0], aNormal[1], aNormal[2]));
				}
			} endEditCP(osgNormals);
			if (iNumNormals != m_iNumPoints)
			{
				std::cout <<
				"WARNING: CVtkActorToOpenSG::ProcessGeometryNormalsAndColorsPerVertex() number of normals"
				          << std::endl;
				std::cout << "should equal the number of vertices (points)!" <<	std::endl << std::endl;
			}
		}

		//possibly getting the colors
		if (m_iColorType == PER_VERTEX)
		{
			vtkIdType iNumColors = vtkColors->GetNumberOfTuples();
			beginEditCP(osgColors);
			{
				unsigned char aColor[4];
				for (int i = 0; i < iNumColors; i++)
				{
					vtkColors->GetTupleValue(i, aColor);
					float r = ((float) aColor[0]) / 255.0f;
					float g = ((float) aColor[1]) / 255.0f;
					float b = ((float) aColor[2]) / 255.0f;
					osgColors->addValue(Color3f(r, g, b));
				}
			} endEditCP(osgColors);
			if (iNumColors != m_iNumPoints)
			{
				std::cout <<
				"WARNING: CVtkActorToOpenSG::ProcessGeometryNormalsAndColorsPerVertex() number of colors"
				          << std::endl;
				std::cout << "should equal the number of vertices (points)!" << std::endl << std::endl;
			}
		}

		//possibly getting the texture coordinates. These are alwary per vertex
		if (vtkTexCoords != NULL)
		{
			int numTuples = vtkTexCoords->GetNumberOfTuples();
			for (int i = 0; i < numTuples; i++)
			{
				double texCoords[3];
				vtkTexCoords->GetTuple(i, texCoords);
				osgTexCoords->addValue(Vec2f(texCoords[0], texCoords[1]));
			}
		}

		//getting the cells
		beginEditCP(osgTypes);
		beginEditCP(osgLengths);
		beginEditCP(osgIndices);
		{
			vtkCellArray* pCells;
			vtkIdType npts, * pts;
			int prim;

			prim = 0;
			pCells = pd->GetVerts();
			if (pCells->GetNumberOfCells() > 0)
				for (pCells->InitTraversal(); pCells->GetNextCell(npts, pts);
				     prim++)
				{
					osgLengths->addValue(npts);
					osgTypes->addValue(GL_POINTS);
					for (int i = 0; i < npts; i++)
						osgIndices->addValue(pts[i]);
				}

			prim = 0;
			pCells = pd->GetLines();
			if (pCells->GetNumberOfCells() > 0)
				for (pCells->InitTraversal(); pCells->GetNextCell(npts, pts);
				     prim++)
				{
					osgLengths->addValue(npts);
					osgTypes->addValue(GL_LINE_STRIP);
					for (int i = 0; i < npts; i++)
						osgIndices->addValue(pts[i]);
				}

			prim = 0;
			pCells = pd->GetPolys();
			if (pCells->GetNumberOfCells() > 0)
				for (pCells->InitTraversal(); pCells->GetNextCell(npts, pts);
				     prim++)
				{
					osgLengths->addValue(npts);
					osgTypes->addValue(GL_POLYGON);
					for (int i = 0; i < npts; i++)
						osgIndices->addValue(pts[i]);
				}

			prim = 0;
			pCells = pd->GetStrips();
			if (pCells->GetNumberOfCells() > 0)
				for (pCells->InitTraversal(); pCells->GetNextCell(npts, pts); prim++)
				{
					osgLengths->addValue(npts);
					osgTypes->addValue(GL_TRIANGLE_STRIP);
					for (int i = 0; i < npts; i++)
						osgIndices->addValue(pts[i]);
				}
		} endEditCP(osgIndices);
		endEditCP(osgLengths);
		endEditCP(osgTypes);

		ChunkMaterialPtr material = CreateMaterial(lit, hasTexCoords);
		beginEditCP(osgGeometry);
		{
			osgGeometry->setPositions(osgPoints);
			osgGeometry->setTypes(osgTypes);
			osgGeometry->setLengths(osgLengths);
			osgGeometry->setIndices(osgIndices);
			osgGeometry->setMaterial(material);

			if (m_iNormalType == PER_VERTEX)
				osgGeometry->setNormals(osgNormals);
			if (m_iColorType == PER_VERTEX)
				osgGeometry->setColors(osgColors);
			if (osgTexCoords->getSize() > 0)
				osgGeometry->setTexCoords(osgTexCoords);
		} endEditCP(osgGeometry);

		osgConversionSuccess = true;

		if (_verbose)
			std::cout << "    End ProcessGeometryNormalsAndColorsPerVertex()" <<
			std::endl;
	}
	else
	{
		//Rendering with OpenSG non indexed geometry by copying a lot of attribute data
		if (_verbose)
			std::cout <<
			"Start ProcessGeometryNonIndexedCopyAttributes(int gl_primitive_type)" <<
			std::endl;
		int gl_primitive_type = -1;
		if(m_iNumGLPolygons > 0)
		{
			if(m_iNumGLPolygons != m_iNumGLPrimitives)
				std::cout << "WARNING: vtkActor contains different kind of primitives" << std::endl;
			gl_primitive_type = GL_POLYGON;
			//osgConversionSuccess = this->ProcessGeometryNonIndexedCopyAttributes(GL_POLYGON, pd, osgGeometry);
		}
		else if(m_iNumGLLineStrips > 0)
		{
			if (m_iNumGLLineStrips != m_iNumGLPrimitives)
				std::cout << "WARNING: vtkActor contains different kind of primitives" << std::endl;
			gl_primitive_type = GL_LINE_STRIP;
			//osgConversionSuccess = this->ProcessGeometryNonIndexedCopyAttributes(GL_LINE_STRIP, pd osgGeometry);
		}
		else if(m_iNumGLTriStrips > 0)
		{
			if (m_iNumGLTriStrips != m_iNumGLPrimitives)
				std::cout << "WARNING: vtkActor contains different kind of primitives" << std::endl;
			gl_primitive_type = GL_TRIANGLE_STRIP;
			//osgConversionSuccess = this->ProcessGeometryNonIndexedCopyAttributes(GL_TRIANGLE_STRIP, pd osgGeometry);
		}
		else if (m_iNumGLPoints > 0)
		{
			if (m_iNumGLPoints != m_iNumGLPrimitives)
				std::cout << "WARNING: vtkActor contains different kind of primitives" << std::endl;
			gl_primitive_type = GL_POINTS;
			//osgConversionSuccess = this->ProcessGeometryNonIndexedCopyAttributes(GL_POINTS, pd osgGeometry);
		}
		if(gl_primitive_type != -1)
		{
			vtkCellArray* pCells;
			if (gl_primitive_type == GL_POINTS)
				pCells = pd->GetVerts();
			else if (gl_primitive_type == GL_LINE_STRIP)
				pCells = pd->GetLines();
			else if (gl_primitive_type == GL_POLYGON)
				pCells = pd->GetPolys();
			else if (gl_primitive_type == GL_TRIANGLE_STRIP)
				pCells = pd->GetStrips();
			else
			{
				std::cout <<
				"CVtkActorToOpenSG::ProcessGeometryNonIndexedCopyAttributes(int gl_primitive_type)"
				<< std::endl << " was called with non implemented gl_primitive_type!" << std::endl;
			}

			beginEditCP(osgTypes);
			beginEditCP(osgLengths);
			beginEditCP(osgPoints);
			beginEditCP(osgColors);
			beginEditCP(osgNormals);
			{
				int prim = 0;
				if (pCells->GetNumberOfCells() > 0)
				{
					vtkIdType npts, * pts;
					for (pCells->InitTraversal(); pCells->GetNextCell(npts, pts);
					     prim++)
					{
						osgLengths->addValue(npts);
						osgTypes->addValue(GL_POLYGON);
						for (int i = 0; i < npts; i++)
						{
							double* aVertex;
							double* aNormal;
							unsigned char aColor[4];

							aVertex = pd->GetPoint(pts[i]);
							osgPoints->addValue(Vec3f(aVertex[0], aVertex[1], aVertex[2]));

							if (m_iNormalType == PER_VERTEX)
							{
								aNormal =
								        vtkNormals->GetTuple(pts[i]);
								osgNormals->addValue(Vec3f(aNormal[0], aNormal[1], aNormal[2]));
							}
							else if (m_iNormalType == PER_CELL)
							{
								aNormal = vtkNormals->GetTuple(prim);
								osgNormals->addValue(Vec3f(aNormal[0], aNormal[1], aNormal[2]));
							}

							if (m_iColorType == PER_VERTEX)
							{
								vtkColors->GetTupleValue(pts[i], aColor);
								float r = ((float) aColor[0]) /	 255.0f;
								float g = ((float) aColor[1]) / 255.0f;
								float b = ((float) aColor[2]) / 255.0f;
								osgColors->addValue(Color3f(r, g, b));
							}
							else if (m_iColorType == PER_CELL)
							{
								vtkColors->GetTupleValue(prim,
								                         aColor);
								float r = ((float) aColor[0]) /	255.0f;
								float g = ((float) aColor[1]) / 255.0f;
								float b = ((float) aColor[2]) / 255.0f;
								osgColors->addValue(Color3f(r, g, b));
							}
						}
					}
				}
			} endEditCP(osgTypes);
			endEditCP(osgLengths);
			endEditCP(osgPoints);
			endEditCP(osgColors);
			endEditCP(osgNormals);

			//possibly getting the texture coordinates. These are always per vertex
			vtkPoints* points = pd->GetPoints();
			if ((vtkTexCoords != NULL) && (points != NULL))
			{
				int numPoints = points->GetNumberOfPoints();
				int numTexCoords = vtkTexCoords->GetNumberOfTuples();
				if (numPoints == numTexCoords)
				{
					beginEditCP(osgTexCoords);
					{
						int numTuples = vtkTexCoords->GetNumberOfTuples();
						for (int i = 0; i < numTuples; i++)
						{
							double texCoords[3];
							vtkTexCoords->GetTuple(i, texCoords);
							osgTexCoords->addValue(Vec2f(texCoords[0], texCoords[1]));
						}
					} endEditCP(osgTexCoords);
				}
			}

			ChunkMaterialPtr material = CreateMaterial(lit, hasTexCoords);
			//GeometryPtr geo = Geometry::create();
			beginEditCP(osgGeometry);
			{
				osgGeometry->setPositions(osgPoints);
				osgGeometry->setTypes(osgTypes);
				osgGeometry->setLengths(osgLengths);
				osgGeometry->setMaterial(material);

				if (m_iNormalType != NOT_GIVEN)
					osgGeometry->setNormals(osgNormals);
				if (m_iColorType != NOT_GIVEN)
					osgGeometry->setColors(osgColors);
				if (osgTexCoords->getSize() > 0)
					osgGeometry->setTexCoords(osgTexCoords);
				//geo->setMaterial(getDefaultMaterial());
			} endEditCP(osgGeometry);

			osgConversionSuccess = true;
		}
		if (_verbose)
			std::cout <<
			"    End ProcessGeometryNonIndexedCopyAttributes(int gl_primitive_type)" <<
			std::endl;
	}

	if(!osgConversionSuccess)
	{
		std::cout << "OpenSG converter was not able to convert this actor." << std::endl;
		return false;
	}

	if(m_iNormalType == NOT_GIVEN)
	{
		//GeometryPtr newGeometryPtr = GeometryPtr::dcast(newNodePtr->getCore());
		if((osgGeometry != NullFC) && (m_iColorType == PER_VERTEX))
		{
			std::cout <<
			"WARNING: Normals are missing in the vtk layer, calculating normals per vertex!"
			          << std::endl;
			calcVertexNormals(osgGeometry);
		}
		else if ((osgGeometry != NullFC) && (m_iColorType == PER_CELL))
		{
			std::cout <<
			"WARNING: Normals are missing in the vtk layer, calculating normals per face!"
			          << std::endl;
			calcFaceNormals(osgGeometry);
		}
		else if (osgGeometry != NullFC)
		{
			std::cout <<
			"WARNING: Normals are missing in the vtk layer, calculating normals per vertex!"
			          << std::endl;
			calcVertexNormals(osgGeometry);
		}
	}

	std::cout << "Conversion finished." << std::endl;

	// Add node to root
	beginEditCP(_osgRoot);
	_osgRoot->addChild(osgGeomNode);
	endEditCP(_osgRoot);

	pm->Delete();

	return true;
}
Exemplo n.º 29
0
Scene::Scene(const std::string &fileName,uint width, uint height ,const int aType ) {
	accelType = aType;

	extMeshCache = new ExtMeshCache();
	texMapCache = new TextureMapCache();

	SDL_LOG("Reading scene: " << fileName);

	scnProp = new Properties(fileName);

	//--------------------------------------------------------------------------
	// Read camera position and target
	//--------------------------------------------------------------------------

	std::vector<float> vf = GetParameters(*scnProp, "scene.camera.lookat", 6, "10.0 0.0 0.0  0.0 0.0 0.0");
	Point o(vf.at(0), vf.at(1), vf.at(2));
	Point t(vf.at(3), vf.at(4), vf.at(5));

	SDL_LOG("Camera postion: " << o);
	SDL_LOG("Camera target: " << t);

	vf = GetParameters(*scnProp, "scene.camera.up", 3, "0.0 0.0 0.1");
	const Vector up(vf.at(0), vf.at(1), vf.at(2));

	camera = new PerspectiveCamera(o, t, up);

	camera->lensRadius = scnProp->GetFloat("scene.camera.lensradius", 0.f);
	camera->focalDistance = scnProp->GetFloat("scene.camera.focaldistance", 10.f);
	camera->fieldOfView = scnProp->GetFloat("scene.camera.fieldofview", 45.f);
  
	// Check if camera motion blur is enabled
	if (scnProp->GetInt("scene.camera.motionblur.enable", 0)) {
		camera->motionBlur = true;

		vf = GetParameters(*scnProp, "scene.camera.motionblur.lookat", 6, "10.0 1.0 0.0  0.0 1.0 0.0");
		camera->mbOrig = Point(vf.at(0), vf.at(1), vf.at(2));
		camera->mbTarget = Point(vf.at(3), vf.at(4), vf.at(5));

		vf = GetParameters(*scnProp, "scene.camera.motionblur.up", 3, "0.0 0.0 0.1");
		camera->mbUp = Vector(vf.at(0), vf.at(1), vf.at(2));
	}

	//--------------------------------------------------------------------------
	// Read all materials
	//--------------------------------------------------------------------------

	std::vector<std::string> matKeys = scnProp->GetAllKeys("scene.materials.");
	if (matKeys.size() == 0)
		throw std::runtime_error("No material definition found");

	for (std::vector<std::string>::const_iterator matKey = matKeys.begin(); matKey != matKeys.end(); ++matKey) {
		const std::string &key = *matKey;
		const std::string matType = Properties::ExtractField(key, 2);
		if (matType == "")
			throw std::runtime_error("Syntax error in " + key);
		const std::string matName = Properties::ExtractField(key, 3);
		if (matName == "")
			throw std::runtime_error("Syntax error in " + key);
		SDL_LOG("Material definition: " << matName << " [" << matType << "]");

		Material *mat = CreateMaterial(key, *scnProp);

		materialIndices[matName] = materials.size();
		materials.push_back(mat);
	}

	//--------------------------------------------------------------------------
	// Read all objects .ply file
	//--------------------------------------------------------------------------

	std::vector<std::string> objKeys = scnProp->GetAllKeys("scene.objects.");
	if (objKeys.size() == 0)
		throw std::runtime_error("Unable to find object definitions");

	double lastPrint = WallClockTime();
	unsigned int objCount = 0;
	for (std::vector<std::string>::const_iterator objKey = objKeys.begin(); objKey != objKeys.end(); ++objKey) {
		const std::string &key = *objKey;

		// Check if it is the root of the definition of an object otherwise skip
		const size_t dot1 = key.find(".", std::string("scene.objects.").length());
		if (dot1 == std::string::npos)
			continue;
		const size_t dot2 = key.find(".", dot1 + 1);
		if (dot2 != std::string::npos)
			continue;

		const std::string objName = Properties::ExtractField(key, 3);
		if (objName == "")
			throw std::runtime_error("Syntax error in " + key);

		// Build the object
		const std::vector<std::string> args = scnProp->GetStringVector(key, "");
		const std::string plyFileName = args.at(0);
		const double now = WallClockTime();
		if (now - lastPrint > 2.0) {
			SDL_LOG("PLY object count: " << objCount);
			lastPrint = now;
		}
		++objCount;
		//SDL_LOG("PLY object [" << objName << "] file name: " << plyFileName);

		// Check if I have to calculate normal or not
		const bool usePlyNormals = (scnProp->GetInt(key + ".useplynormals", 0) != 0);

		// Check if I have to use an instance mesh or not
		ExtMesh *meshObject;
		if (scnProp->IsDefined(key + ".transformation")) {
			const std::vector<float> vf = GetParameters(*scnProp, key + ".transformation", 16, "1.0 0.0 0.0 0.0  0.0 1.0 0.0 0.0  0.0 0.0 1.0 0.0  0.0 0.0 0.0 1.0");
			const Matrix4x4 mat(
					vf.at(0), vf.at(4), vf.at(8), vf.at(12),
					vf.at(1), vf.at(5), vf.at(9), vf.at(13),
					vf.at(2), vf.at(6), vf.at(10), vf.at(14),
					vf.at(3), vf.at(7), vf.at(11), vf.at(15));
			const Transform trans(mat);

			meshObject = extMeshCache->GetExtMesh(plyFileName, usePlyNormals, trans);
		} else
			meshObject = extMeshCache->GetExtMesh(plyFileName, usePlyNormals);

		objectIndices[objName] = objects.size();
		objects.push_back(meshObject);

		// Get the material
		const std::string matName = Properties::ExtractField(key, 2);
		if (matName == "")
			throw std::runtime_error("Syntax error in material name: " + matName);
		if (materialIndices.count(matName) < 1)
			throw std::runtime_error("Unknown material: " + matName);
		Material *mat = materials[materialIndices[matName]];

		// Check if it is a light sources
		if (mat->IsLightSource()) {
			SDL_LOG("The " << objName << " object is a light sources with " << meshObject->GetTotalTriangleCount() << " triangles");

			AreaLightMaterial *light = (AreaLightMaterial *)mat;
			objectMaterials.push_back(mat);
			for (unsigned int i = 0; i < meshObject->GetTotalTriangleCount(); ++i) {
				TriangleLight *tl = new TriangleLight(light, static_cast<unsigned int>(objects.size()) - 1, i, objects);
				lights.push_back(tl);
			}
		} else {
			SurfaceMaterial *surfMat = (SurfaceMaterial *)mat;
			objectMaterials.push_back(surfMat);
		}

		// [old deprecated syntax] Check if there is a texture map associated to the object
		if (args.size() > 1) {
			// Check if the object has UV coords
			if (!meshObject->HasUVs())
				throw std::runtime_error("PLY object " + plyFileName + " is missing UV coordinates for texture mapping");

			TexMapInstance *tm = texMapCache->GetTexMapInstance(args.at(1), 2.2f);
			objectTexMaps.push_back(tm);
			objectBumpMaps.push_back(NULL);
			objectNormalMaps.push_back(NULL);
		} else {
			// Check for if there is a texture map associated to the object with the new syntax
			const std::string texMap = scnProp->GetString(key + ".texmap", "");
			if (texMap != "") {
				// Check if the object has UV coords
				if (!meshObject->HasUVs())
					throw std::runtime_error("PLY object " + plyFileName + " is missing UV coordinates for texture mapping");

				const float gamma = scnProp->GetFloat(key + ".texmap.gamma", 2.2f);
				TexMapInstance *tm = texMapCache->GetTexMapInstance(texMap, gamma);
				objectTexMaps.push_back(tm);
			} else
				objectTexMaps.push_back(NULL);

			/**
			 * Check if there is an alpha map associated to the object
			 * If there is, the map is added to a previously added texturemap.
			 * If no texture map (diffuse map) is detected, a black texture
			 * is created and the alpha map is added to it. --PC
			 */
			const std::string alphaMap = scnProp->GetString(key + ".alphamap", "");
			if (alphaMap != "") {
				// Got an alpha map, retrieve the textureMap and add the alpha channel to it.
				const std::string texMap = scnProp->GetString(key + ".texmap", "");
				const float gamma = scnProp->GetFloat(key + ".texmap.gamma", 2.2f);
				TextureMap *tm;
				if (!(tm = texMapCache->FindTextureMap(texMap, gamma))) {
					SDL_LOG("Alpha map " << alphaMap << " is for a materials without texture. A black texture has been created for support!");
					// We have an alpha map without a diffuse texture. In this case we need to create
					// a texture map filled with black
					tm = new TextureMap(alphaMap, gamma, 1.0, 1.0, 1.0);
					tm->AddAlpha(alphaMap);
					TexMapInstance *tmi = texMapCache->AddTextureMap(alphaMap, tm);
					// Remove the NULL inserted above, when no texmap was found. Without doing this the whole thing will not work
					objectTexMaps.pop_back();
					// Add the new texture to the chain
					objectTexMaps.push_back(tmi);
				} else {
					// Add an alpha map to the pre-existing diffuse texture
					tm->AddAlpha(alphaMap);
				}
			}
      
			// Check for if there is a bump map associated to the object
			const std::string bumpMap = scnProp->GetString(key + ".bumpmap", "");
			if (bumpMap != "") {
				// Check if the object has UV coords
				if (!meshObject->HasUVs())
					throw std::runtime_error("PLY object " + plyFileName + " is missing UV coordinates for bump mapping");

				const float scale = scnProp->GetFloat(key + ".bumpmap.scale", 1.f);

				BumpMapInstance *bm = texMapCache->GetBumpMapInstance(bumpMap, scale);
				objectBumpMaps.push_back(bm);
			} else
				objectBumpMaps.push_back(NULL);

			// Check for if there is a normal map associated to the object
			const std::string normalMap = scnProp->GetString(key + ".normalmap", "");
			if (normalMap != "") {
				// Check if the object has UV coords
				if (!meshObject->HasUVs())
					throw std::runtime_error("PLY object " + plyFileName + " is missing UV coordinates for normal mapping");

				NormalMapInstance *nm = texMapCache->GetNormalMapInstance(normalMap);
				objectNormalMaps.push_back(nm);
			} else
				objectNormalMaps.push_back(NULL);
		}
	}
	SDL_LOG("PLY object count: " << objCount);

	//--------------------------------------------------------------------------
	// Check if there is an infinitelight source defined
	//--------------------------------------------------------------------------

	const std::vector<std::string> ilParams = scnProp->GetStringVector("scene.infinitelight.file", "");
	if (ilParams.size() > 0) {
		const float gamma = scnProp->GetFloat("scene.infinitelight.gamma", 2.2f);
		TexMapInstance *tex = texMapCache->GetTexMapInstance(ilParams.at(0), gamma);

		// Check if I have to use InfiniteLightBF method
		if (scnProp->GetInt("scene.infinitelight.usebruteforce", 0)) {
			SDL_LOG("Using brute force infinite light sampling");
			infiniteLight = new InfiniteLightBF(tex);
			useInfiniteLightBruteForce = true;
		} else {
			if (ilParams.size() == 2)
				infiniteLight = new InfiniteLightPortal(tex, ilParams.at(1));
			else
				infiniteLight = new InfiniteLightIS(tex);

			// Add the infinite light to the list of light sources
			lights.push_back(infiniteLight);

			useInfiniteLightBruteForce = false;
		}

		std::vector<float> vf = GetParameters(*scnProp, "scene.infinitelight.gain", 3, "1.0 1.0 1.0");
		infiniteLight->SetGain(Spectrum(vf.at(0), vf.at(1), vf.at(2)));

		vf = GetParameters(*scnProp, "scene.infinitelight.shift", 2, "0.0 0.0");
		infiniteLight->SetShift(vf.at(0), vf.at(1));

		infiniteLight->Preprocess();
	} else {
		infiniteLight = NULL;
		useInfiniteLightBruteForce = false;
	}

	//--------------------------------------------------------------------------
	// Check if there is a SkyLight defined
	//--------------------------------------------------------------------------

	const std::vector<std::string> silParams = scnProp->GetStringVector("scene.skylight.dir", "");
	if (silParams.size() > 0) {
		if (infiniteLight)
			throw std::runtime_error("Can not define a skylight when there is already an infinitelight defined");

		std::vector<float> sdir = GetParameters(*scnProp, "scene.skylight.dir", 3, "0.0 0.0 1.0");
		const float turb = scnProp->GetFloat("scene.skylight.turbidity", 2.2f);
		std::vector<float> gain = GetParameters(*scnProp, "scene.skylight.gain", 3, "1.0 1.0 1.0");

		SkyLight *sl = new SkyLight(turb, Vector(sdir.at(0), sdir.at(1), sdir.at(2)));
		infiniteLight = sl;
		sl->SetGain(Spectrum(gain.at(0), gain.at(1), gain.at(2)));
		sl->Init();

		useInfiniteLightBruteForce = true;
	}

	//--------------------------------------------------------------------------
	// Check if there is a SunLight defined
	//--------------------------------------------------------------------------

	const std::vector<std::string> sulParams = scnProp->GetStringVector("scene.sunlight.dir", "");
	if (sulParams.size() > 0) {
		std::vector<float> sdir = GetParameters(*scnProp, "scene.sunlight.dir", 3, "0.0 0.0 1.0");
		const float turb = scnProp->GetFloat("scene.sunlight.turbidity", 2.2f);
		const float relSize = scnProp->GetFloat("scene.sunlight.relsize", 1.0f);
		std::vector<float> gain = GetParameters(*scnProp, "scene.sunlight.gain", 3, "1.0 1.0 1.0");

		SunLight *sunLight = new SunLight(turb, relSize, Vector(sdir.at(0), sdir.at(1), sdir.at(2)));
		sunLight->SetGain(Spectrum(gain.at(0), gain.at(1), gain.at(2)));
		sunLight->Init();

		lights.push_back(sunLight);
	}

	//--------------------------------------------------------------------------


	camera->Update(width, height);


}
Exemplo n.º 30
0
EffectParticles::EffectParticles() : m_ErrorCode( 0 )
{
	//////////////////////////////////////////////////////////////////////////
	// Create the materials
	CHECK_MATERIAL( m_pMatCompute = CreateMaterial( IDR_SHADER_PARTICLES_COMPUTE, "./Resources/Shaders/ParticlesCompute.hlsl", VertexFormatPt4::DESCRIPTOR, "VS", NULL, "PS" ), 1 );
	CHECK_MATERIAL( m_pMatDisplay = CreateMaterial( IDR_SHADER_PARTICLES_DISPLAY, "./Resources/Shaders/ParticlesDisplay.hlsl", VertexFormatPt4::DESCRIPTOR, "VS", "GS", "PS" ), 2 );
	CHECK_MATERIAL( m_pMatDebugVoronoi = CreateMaterial( IDR_SHADER_PARTICLES_DISPLAY, "./Resources/Shaders/ParticlesDisplay.hlsl", VertexFormatPt4::DESCRIPTOR, "VS_DEBUG", NULL, "PS_DEBUG" ), 3 );


	//////////////////////////////////////////////////////////////////////////
	// Build the awesome particle primitive
// 	{
// 		VertexFormatP3	Vertices;
// 		m_pPrimParticle = new Primitive( gs_Device, 1, &Vertices, 0, NULL, D3D11_PRIMITIVE_TOPOLOGY_POINTLIST, VertexFormatP3::DESCRIPTOR );
// 	}

	//////////////////////////////////////////////////////////////////////////
	// Build our voronoï texture & our initial positions & data
	NjFloat2*	pCellCenters = new NjFloat2[EFFECT_PARTICLES_COUNT*EFFECT_PARTICLES_COUNT];
	{
		TextureBuilder		TB( 1024, 1024 );
		VertexFormatPt4*	pVertices = new VertexFormatPt4[EFFECT_PARTICLES_COUNT*EFFECT_PARTICLES_COUNT];
		BuildVoronoiTexture( TB, pCellCenters, pVertices );

		TextureBuilder::ConversionParams	Conv =
		{
			0,		// int		PosR;
			1,		// int		PosG;
			-1,		// int		PosB;
			-1,		// int		PosA;
			false,

					// Position of the height & roughness fields
			-1,		// int		PosHeight;
			-1,		// int		PosRoughness;

					// Position of the Material ID
			-1,		// int		PosMatID;

					// Position of the normal fields
//			1.0f,	// float	NormalFactor;	// Factor to apply to the height to generate the normals
			true,
			-1,		// int		PosNormalX;
			-1,		// int		PosNormalY;
			-1,		// int		PosNormalZ;

					// Position of the AO field
//			1.0f,	// float	AOFactor;		// Factor to apply to the height to generate the AO
			-1,		// int		PosAO;
		};

		m_pTexVoronoi = TB.CreateTexture( PixelFormatRG32F::DESCRIPTOR, Conv );


		m_pPrimParticle = new Primitive( gs_Device, EFFECT_PARTICLES_COUNT*EFFECT_PARTICLES_COUNT, pVertices, 0, NULL, D3D11_PRIMITIVE_TOPOLOGY_POINTLIST, VertexFormatPt4::DESCRIPTOR );

		// Build cell centers
		for ( int ParticleIndex=0; ParticleIndex < EFFECT_PARTICLES_COUNT*EFFECT_PARTICLES_COUNT; ParticleIndex++ )
			pCellCenters[ParticleIndex].Set( 0.5f * (pVertices[ParticleIndex].Pt.x + pVertices[ParticleIndex].Pt.z), 0.5f * (pVertices[ParticleIndex].Pt.y + pVertices[ParticleIndex].Pt.w) );

		delete[] pVertices;
	}

	//////////////////////////////////////////////////////////////////////////
	// Build the initial positions & orientations of the particles from the surface of a torus
	PixelFormatRGBA32F*	pInitialPositions = new PixelFormatRGBA32F[EFFECT_PARTICLES_COUNT*EFFECT_PARTICLES_COUNT];
	PixelFormatRGBA32F*	pInitialNormals = new PixelFormatRGBA32F[EFFECT_PARTICLES_COUNT*EFFECT_PARTICLES_COUNT];
	PixelFormatRGBA32F*	pInitialTangents = new PixelFormatRGBA32F[EFFECT_PARTICLES_COUNT*EFFECT_PARTICLES_COUNT];
	PixelFormatRGBA32F*	pScanlinePosition = pInitialPositions;
	PixelFormatRGBA32F*	pScanlineNormal = pInitialNormals;
	PixelFormatRGBA32F*	pScanlineTangent = pInitialTangents;

	int		TotalCount = EFFECT_PARTICLES_COUNT*EFFECT_PARTICLES_COUNT;
	int		ParticlesPerDimension = U32(floorf(powf( float(TotalCount), 1.0f/3.0f )));
	float	R = 0.5f;	// Great radius of the torus
	float	r = 0.2f;	// Small radius of the torus

	for ( int Y=0; Y < EFFECT_PARTICLES_COUNT; Y++ )
		for ( int X=0; X < EFFECT_PARTICLES_COUNT; X++, pScanlinePosition++, pScanlineNormal++, pScanlineTangent++ )
		{
			NjFloat2&	CellCenter = pCellCenters[EFFECT_PARTICLES_COUNT*Y+X];
			float		Alpha = TWOPI * X / EFFECT_PARTICLES_COUNT;	// Angle on the great circle
			float		Beta = TWOPI * Y / EFFECT_PARTICLES_COUNT;	// Angle on the small circle

			NjFloat3	T( cosf(Alpha), 0.0f, -sinf(Alpha) );		// Gives the direction to the center on the great circle in the Z^X plane
			NjFloat3	Center = NjFloat3( 0, 0.8f, 0 ) + R * T;	// Center on the great circle
			NjFloat3	Ortho( T.z, 0, -T.x );						// Tangent to the great circle in the Z^X plane
			NjFloat3	B( 0, 1, 0 );								// Bitangent is obviously, always the Y vector

			NjFloat3	Normal = cosf(Beta) * T + sinf(Beta) * B;	// The normal to the small circle, also the direction to the point on the surface
			NjFloat3	Tangent = Ortho;
			NjFloat3	Pos = Center + r * Normal;					// Position on the surface of the small circle

			float		Radius = R + r * cosf(Beta);				// Radius of the circle where the particle is standing
			float		Perimeter = TWOPI * Radius;					// Perimeter of that circle
			float		ParticleSize = 0.5f * Perimeter;			// Size of a single particle on that circle

			float		ParticleLife = -1.0f - 4.0f * (1.0f - Normal.y);	// Start with a negative life depending on height
 
// DEBUG Generate on a plane for verification
// Pos.x = 2.0f * (CellCenter.x - 0.5f);
// Pos.y = 0.5f;
// Pos.z = -2.0f * (CellCenter.y - 0.5f);
// Normal.Set( 0, 1, 0 );	// Facing up
// Tangent.Set( 1, 0, 0 );	// Right
// ParticleSize = 1.0f;// / EFFECT_PARTICLES_COUNT;	// Size of a single particle on that circle
// DEBUG


			pScanlinePosition->R = Pos.x;
			pScanlinePosition->G = Pos.y;
			pScanlinePosition->B = Pos.z;
			pScanlinePosition->A = ParticleLife;

			pScanlineNormal->R = Normal.x;
			pScanlineNormal->G = Normal.y;
			pScanlineNormal->B = Normal.z;
//			pScanlineNormal->A = (0.025f + 0.002f) * EFFECT_PARTICLES_COUNT;	// Half size + a little epsilon to make the tiles join correctly
//			pScanlineNormal->A = (0.1f + 0*0.002f) * EFFECT_PARTICLES_COUNT;	// Half size + a little epsilon to make the tiles join correctly
			pScanlineNormal->A = ParticleSize;

			pScanlineTangent->R = Tangent.x;
			pScanlineTangent->G = Tangent.y;
			pScanlineTangent->B = Tangent.z;
			pScanlineTangent->A = Normal.y > 0.0f ? 1.0f : -1.0f;	// Determines the particle's behavior...
		}

	delete[]	pCellCenters;

	// Unfortunately, we need to create Textures to initialize our RenderTargets
	void*		ppContentPositions[1];
				ppContentPositions[0] = (void*) pInitialPositions;
	Texture2D*	pTempPositions = new Texture2D( gs_Device, EFFECT_PARTICLES_COUNT, EFFECT_PARTICLES_COUNT, 1, PixelFormatRGBA32F::DESCRIPTOR, 1, ppContentPositions );
	delete[]	pInitialPositions;

	void*		ppContentNormals[1];
				ppContentNormals[0] = (void*) pInitialNormals;
	Texture2D*	pTempNormals = new Texture2D( gs_Device, EFFECT_PARTICLES_COUNT, EFFECT_PARTICLES_COUNT, 1, PixelFormatRGBA32F::DESCRIPTOR, 1, ppContentNormals );
	delete[]	pInitialNormals;

	void*		ppContentTangents[1];
				ppContentTangents[0] = (void*) pInitialTangents;
	Texture2D*	pTempTangents = new Texture2D( gs_Device, EFFECT_PARTICLES_COUNT, EFFECT_PARTICLES_COUNT, 1, PixelFormatRGBA32F::DESCRIPTOR, 1, ppContentTangents );
	delete[]	pInitialTangents;

	// Finally, create the render targets and initialize them
	m_ppRTParticlePositions[0] = new Texture2D( gs_Device, EFFECT_PARTICLES_COUNT, EFFECT_PARTICLES_COUNT, 1, PixelFormatRGBA32F::DESCRIPTOR, 1, NULL );
	m_ppRTParticlePositions[1] = new Texture2D( gs_Device, EFFECT_PARTICLES_COUNT, EFFECT_PARTICLES_COUNT, 1, PixelFormatRGBA32F::DESCRIPTOR, 1, NULL );
	m_ppRTParticlePositions[2] = new Texture2D( gs_Device, EFFECT_PARTICLES_COUNT, EFFECT_PARTICLES_COUNT, 1, PixelFormatRGBA32F::DESCRIPTOR, 1, NULL );
	m_ppRTParticlePositions[0]->CopyFrom( *pTempPositions );
	m_ppRTParticlePositions[1]->CopyFrom( *pTempPositions );
	m_ppRTParticlePositions[2]->CopyFrom( *pTempPositions );
	delete	pTempPositions;

	m_ppRTParticleNormals[0] = new Texture2D( gs_Device, EFFECT_PARTICLES_COUNT, EFFECT_PARTICLES_COUNT, 1, PixelFormatRGBA32F::DESCRIPTOR, 1, NULL );
	m_ppRTParticleNormals[1] = new Texture2D( gs_Device, EFFECT_PARTICLES_COUNT, EFFECT_PARTICLES_COUNT, 1, PixelFormatRGBA32F::DESCRIPTOR, 1, NULL );
	m_ppRTParticleNormals[0]->CopyFrom( *pTempNormals );
	m_ppRTParticleNormals[1]->CopyFrom( *pTempNormals );
	delete pTempNormals;

	m_ppRTParticleTangents[0] = new Texture2D( gs_Device, EFFECT_PARTICLES_COUNT, EFFECT_PARTICLES_COUNT, 1, PixelFormatRGBA32F::DESCRIPTOR, 1, NULL );
	m_ppRTParticleTangents[1] = new Texture2D( gs_Device, EFFECT_PARTICLES_COUNT, EFFECT_PARTICLES_COUNT, 1, PixelFormatRGBA32F::DESCRIPTOR, 1, NULL );
	m_ppRTParticleTangents[0]->CopyFrom( *pTempTangents );
	m_ppRTParticleTangents[1]->CopyFrom( *pTempTangents );
	delete pTempTangents;


	//////////////////////////////////////////////////////////////////////////
	// Create the constant buffers
	m_pCB_Render = new CB<CBRender>( gs_Device, 10 );
	m_pCB_Render->m.DeltaTime.Set( 0, 1 );
}