Exemplo n.º 1
0
int SkpModel::AddFaceMaterial(SUFaceRef face){
	if (face.ptr==0)
		std::cout << "Null Face \n";

	SUResult res;
	SUMaterialRef material = SU_INVALID;
	res = SUFaceGetFrontMaterial(face, &material);
	if (res == SU_ERROR_NONE){
		AddMaterial(material);	
	}
	if (res != SU_ERROR_NO_DATA)
		ErrorHandler(res);
	//SUMaterialRelease(&material);

	
	material = SU_INVALID;
	res = SUFaceGetBackMaterial(face, &material);
	if (res == SU_ERROR_NONE){
		AddMaterial(material);	
		//res = SUMaterialRelease(&material);
		//ErrorHandler(res);
	}
	if (res != SU_ERROR_NO_DATA)
		ErrorHandler(res);

	
	return 0;
}
// TODO: All of these Get() functions look very similar.
// Keep them all for their interface, but have them call a common function
//-----------------------------------------------------------------------------
CPUTMaterial *CPUTAssetLibrary::GetMaterial(const cString &name, bool nameIsFullPathAndFilename, const cString &modelSuffix, const cString &meshSuffix)
{
    // Resolve name to absolute path before searching
    CPUTOSServices *pServices = CPUTOSServices::GetOSServices();
    cString absolutePathAndFilename;
    pServices->ResolveAbsolutePathAndFilename( nameIsFullPathAndFilename? name : (mMaterialDirectoryName + name + _L(".mtl")), &absolutePathAndFilename);

    // If we already have one by this name, then return it
    CPUTMaterial *pMaterial = FindMaterial(absolutePathAndFilename, true);
    if(NULL==pMaterial)
    {
        // We don't already have it in the library, so create it.
        pMaterial = CPUTMaterial::CreateMaterial( absolutePathAndFilename, modelSuffix, meshSuffix );
        return pMaterial;
    }
    else if( (0==modelSuffix.length()) && !pMaterial->MaterialRequiresPerModelPayload() )
    {
        // This material doesn't have per-model elements, so we don't need to clone it.
        pMaterial->AddRef();
        return pMaterial;
    }

#ifdef _DEBUG
    // We need to clone the material.  Do that by loading it again, but with a different name.
    // Add the model's suffix (address as string, plus model's material array index as string)
    CPUTMaterial *pUniqueMaterial = FindMaterial(absolutePathAndFilename + modelSuffix + meshSuffix, true);
    ASSERT( NULL == pUniqueMaterial, _L("Unique material already not unique: ") + absolutePathAndFilename + modelSuffix + meshSuffix );
#endif

    CPUTMaterial *pClonedMaterial = pMaterial->CloneMaterial( absolutePathAndFilename, modelSuffix, meshSuffix );
    AddMaterial( absolutePathAndFilename + modelSuffix + meshSuffix, pClonedMaterial );

    return pClonedMaterial;
}
Exemplo n.º 3
0
bool trpgMatTable::Read(trpgReadBuffer &buf)
{
	trpgMaterial mat;
	trpgToken matTok;
	int32 len;
	bool status;
	int i,j;
	int nMat,nTable;

	try {
		buf.Get(nTable);
		buf.Get(nMat);
		if (nTable <= 0 || nMat < 0) throw 1;
		// Read the materials
		for (i=0;i<nTable;i++)
			for (j=0;j<nMat;j++) {
				buf.GetToken(matTok,len);
				if (matTok != TRPGMATERIAL) throw 1;
				buf.PushLimit(len);
				mat.Reset();
				status = mat.Read(buf);
				buf.PopLimit();
				if (!status) throw 1;
				AddMaterial(mat,false);				
			}
			numTable += nTable;
			numMat = materialMap.size();
	}
	catch (...) {
		return false;
	}

	return isValid();
}
Exemplo n.º 4
0
void CScriptDoor::Think(float dt, CStateManager& mgr) {
  if (!GetActive())
    return;

  if (!x2a8_26_isOpen && x25c_animTime < 0.5f)
    x25c_animTime += dt;

  if (x2a8_27_conditionsMet && GetDoorOpenCondition(mgr) == 2) {
    x2a8_27_conditionsMet = false;
    OpenDoor(x280_prevDoor, mgr);
  }

  if (x2a8_24_closing) {
    x2a8_25_wasOpen = false;
    mgr.GetCameraManager()->GetBallCamera()->DoorClosed(GetUniqueId());
    x2a8_28_projectilesCollide = false;
    x2a8_24_closing = false;
    SendScriptMsgs(EScriptObjectState::Closed, mgr, EScriptObjectMessage::Decrement);
    x25c_animTime = 0.f;
    x2a8_30_doClose = false;
  }

  if (x2a8_26_isOpen && !x64_modelData->IsAnimating())
    RemoveMaterial(EMaterialTypes::Solid, EMaterialTypes::Occluder, EMaterialTypes::Orbit, EMaterialTypes::Scannable,
                   mgr);
  else {
    if (x2a8_25_wasOpen && !x64_modelData->IsAnimating()) {
      x2a8_25_wasOpen = false;
      mgr.GetCameraManager()->GetBallCamera()->DoorClosed(GetUniqueId());
      x2a8_28_projectilesCollide = false;
      x2a8_27_conditionsMet = false;
      SendScriptMsgs(EScriptObjectState::Closed, mgr, EScriptObjectMessage::None);
    }

    if (GetScannableObjectInfo())
      AddMaterial(EMaterialTypes::Solid, EMaterialTypes::Metal, EMaterialTypes::Occluder, EMaterialTypes::Orbit,
                  EMaterialTypes::Scannable, mgr);
    else
      AddMaterial(EMaterialTypes::Solid, EMaterialTypes::Metal, EMaterialTypes::Occluder, EMaterialTypes::Orbit, mgr);
  }

  if (x64_modelData->IsAnimating())
    UpdateAnimation((x64_modelData->GetAnimationDuration(s32(x260_doorAnimState)) / x258_animLen) * dt, mgr, true);

  xe7_31_targetable = mgr.GetPlayerState()->GetCurrentVisor() == CPlayerState::EPlayerVisor::Scan;
}
void CinematicGrid::AddQuadUVs(Vec2i depc, Vec2i tc, Vec2i bitmappos, Vec2i bitmapw, Texture2D * tex) {
	size_t matIdx = AddMaterial(tex);
	m_mats[matIdx].bitmapdep = bitmappos;
	m_mats[matIdx].bitmap = bitmapw;
	m_mats[matIdx].nbvertexs = (tc.x + 1) * (tc.y + 1);
	
	float v = 0.f;
	float du = 0.999999f / (float)tc.x;
	float dv = 0.999999f / (float)tc.y;
	tc.y++;
	tc.x++;
	int tcyy = tc.y;
	int depcyy = depc.y;

	while(tcyy--) {
		float u = 0.f;
		int depcxx = depc.x;
		int tcxx = tc.x;

		while(tcxx--) {
			int i0, i1, i2, i3;
			GetIndNumCube(depcxx, depcyy, &i0, &i1, &i2, &i3);

			//uvs
			C_UV cuv;
			cuv.indvertex = i0;
			cuv.uv.x = u;
			cuv.uv.y = v;
			m_uvs.push_back(cuv);
			depcxx++;
			u += du;
		}

		depcyy++;
		v += dv;
	}

	tc.x--;
	tc.y--;

	while(tc.y--) {
		int depcxx = depc.x;
		int tcxx = tc.x;

		while(tcxx--) {
			int i0, i1, i2, i3;
			GetIndNumCube(depcxx, depc.y, &i0, &i1, &i2, &i3);

			AddPoly(matIdx, i0, i1, i2);
			AddPoly(matIdx, i1, i2, i3);
			depcxx++;
		}

		depc.y++;
	}
}
Exemplo n.º 6
0
void CParasite::SetupIceZoomerCollision(CStateManager& mgr) {
  std::vector<CJointCollisionDescription> descs;
  descs.reserve(2);
  descs.push_back(CJointCollisionDescription::SphereCollision(
      x64_modelData->GetAnimationData()->GetLocatorSegId("Ice_LCTR"sv), 0.4f, "Ice_LCTR"sv, 0.001f));
  RemoveMaterial(EMaterialTypes::Solid, mgr);
  AddMaterial(EMaterialTypes::ProjectilePassthrough, mgr);
  x620_collisionActorManager =
      std::make_unique<CCollisionActorManager>(mgr, GetUniqueId(), GetAreaIdAlways(), descs, GetActive());
}
Exemplo n.º 7
0
/*************
 * DESCRIPTION:	Add a new default material to the material list
 * INPUT:			-
 * OUTPUT:			-
 *************/
void CMatView::OnNewMaterial()
{
    SURFACE *pSurf;

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

    AddMaterial(pSurf);
}
Exemplo n.º 8
0
void CzPlatformRender::AddPrimtives(CzRenderPrim* prims, CzRenderMaterial* materials, int num_prims, bool single_material)
{
#if defined(_DEBUG)
	if ((NextPrimitive + num_prims) >= MaxPrimitives)
	{
		CzDebug::Log(CZ_DEBUG_CHANNEL_INFO, "CzPlatformRender - Ran out of primitives, please increase maximum in CzPlatformRender::Init()");
		return;
	}
#endif
	int mat_id = -1;
	if (single_material)
		mat_id = AddMaterial(materials);

	while (num_prims-- > 0)
	{
		if (!single_material)
			mat_id = AddMaterial(materials++);
		CzRenderPrim** prim = Primitives + NextPrimitive++;
		prims->MaterialID = mat_id;
		*prim = prims++;
	}
}
Exemplo n.º 9
0
void DetailList::GetMaterials()
{
   Bool success = TRUE;
   fnMats = 0;
           
   Material m;
   AddMaterial( m );

   for( int di = 0; di < fnDetails; di++ )
      success = success && faDetails[di].GetMaterials( this );
   if( !success )
      throw GeneralError( "Unable to continue!" );
}
Exemplo n.º 10
0
/*************
 * DESCRIPTION:	Load a material and add it to the material list
 * INPUT:			-
 * OUTPUT:			-
 *************/
void CMatView::OnLoadNewMaterial()
{
    CString file;
    SURFACE *surf;

    surf = sciCreateSurface(SURF_DEFAULTNAME);
    if (!surf)
        return;

    if (sciLoadMaterial(surf))
        AddMaterial(surf);
    else
        sciDeleteSurface(surf);
}
Exemplo n.º 11
0
void SceneDialog::RemoveMaterial(AglMaterial* pMaterial)
{
	vector<AglMaterial*> materials = Scene::GetInstance()->GetMaterials();
	for (unsigned int i = 0; i < materials.size(); i++)
	{
		string name = ("Material" + toString(materials[i]->id));
		TwRemoveVar(m_dialog, name.c_str());
	}
	Scene::GetInstance()->RemoveMaterial(pMaterial);
	materials = Scene::GetInstance()->GetMaterials();
	for (unsigned int i = 0; i < materials.size(); i++)
	{
		AddMaterial(materials[i]);
	}
}
Exemplo n.º 12
0
int MBSObjectFactory::AddObject(MBSObjectFactoryClass objectClass, int objectTypeId)
{
	switch(objectClass)
	{
	case OFCElement: return AddElement(objectTypeId);		// AddElement is generated automatically
	case OFCSensor: return AddSensor(objectTypeId);
	case OFCNode: return AddNode(objectTypeId); 
	case OFCLoad: return AddLoad(objectTypeId);
	case OFCMaterial:	return AddMaterial(objectTypeId);
	case OFCBeamProperties:	return AddBeamProperties(objectTypeId);
	case OFCGeomElement: return AddGeomElement(objectTypeId);
	}
	assert(0);
	return -1;
}
Exemplo n.º 13
0
void GmodelExp::BuildTable(void)
{
	m_iNumNodes = m_iNumMaterials = 0;
	TraceTree(ip->GetRootNode());

	if ( m_bExportMaterial )
	{
		for ( int i=0; i<m_iNumNodes; i++ )
		{
			INode *pNode = m_NodeTable[i];
			Mtl *mtl = pNode->GetMtl();
			if ( mtl )
				AddMaterial(mtl);
		}
	}
}
Exemplo n.º 14
0
Scene::Scene( const rgba& background /*= Fur::Colors::AmbientGrey */, real raybias ) : raybias( raybias ), vacuumprimitive( vacuum_arg ),
vacuummaterial( BasicMaterial( background, rgba::White, rgba::Transparent, 0, rgba::White, rgba::Transparent, rgba::Transparent, Ior::Vacuum, Absorption::Vacuum, background ) ),
vacuumhit( ),
box( ),
kdtree( nullptr ) {
	vacuumhit.distance0 = vacuumhit.distance1 = std::numeric_limits<real>::max( );
	vacuumhit.normal = vec3::Zero;
	vacuumhit.uvw = vec3::Zero;
	vacuumhit.contact = vec3( std::numeric_limits<real>::max( ), std::numeric_limits<real>::max( ), std::numeric_limits<real>::max( ) );

	primitives.reserve( 9182 );
	materials.reserve( 9182 );
	ambientlights.reserve( 2 );
	pointlights.reserve( 8 );
	directionallights.reserve( 8 );
	AddMaterial( BasicMaterial( ) );
}
Exemplo n.º 15
0
void CParasite::UpdateCollisionActors(float dt, CStateManager& mgr) {
  x620_collisionActorManager->Update(dt, mgr, CCollisionActorManager::EUpdateOptions::ObjectSpace);
  if (!x743_25_vulnerable) {
    float totalHP = 0.f;
    for (u32 i = 0; i < x620_collisionActorManager->GetNumCollisionActors(); ++i) {
      const CJointCollisionDescription& cDesc = x620_collisionActorManager->GetCollisionDescFromIndex(i);
      if (TCastToPtr<CCollisionActor> cact = mgr.ObjectById(cDesc.GetCollisionActorId()))
        totalHP += cact->HealthInfo(mgr)->GetHP();
    }
    if (totalHP <= 0.f) {
      x743_25_vulnerable = true;
      AddMaterial(EMaterialTypes::Solid, mgr);
      RemoveMaterial(EMaterialTypes::ProjectilePassthrough, mgr);
      DestroyActorManager(mgr);
      x64_modelData->AnimationData()->SubstituteModelData(x624_extraModel);
    }
  }
}
Exemplo n.º 16
0
IMaterial* CMaterialSystem::LoadMaterial(const char* file, string name)
{
	// We can reuse materials that are already loaded instead of creating new ones. Should save memory.
	for (uint i = 0; i < m_materialContainer.size(); i++)
	{
		// Checking if the filenames are equal.
		if (m_materialContainer[i]->GetMtlFIle() == file && m_materialContainer[i]->GetShapeName() == name)
		{
			return m_materialContainer[i];
		}	
	}

	CMaterial* nm = new CMaterial(file, name);

	if (nm != nullptr)
	{
		AddMaterial(nm);
		return nm;
	}

	return nullptr;
}
Exemplo n.º 17
0
void CParasite::Jump(CStateManager& mgr, EStateMsg msg, float) {
  switch (msg) {
  case EStateMsg::Activate:
    AddMaterial(EMaterialTypes::GroundCollider, mgr);
    SetMomentumWR({0.f, 0.f, -GetWeight()});
    x742_28_onGround = false;
    x5d6_24_alignToFloor = false;
    x742_27_landed = false;
    x743_27_inJump = true;
    break;
  case EStateMsg::Update:
    SetMomentumWR({0.f, 0.f, -GetWeight()});
    break;
  case EStateMsg::Deactivate:
    RemoveMaterial(EMaterialTypes::GroundCollider, mgr);
    SetMomentumWR(zeus::skZero3f);
    x742_28_onGround = true;
    x742_27_landed = false;
    x743_27_inJump = false;
    break;
  }
}
Exemplo n.º 18
0
// TODO: All of these Get() functions look very similar.
// Keep them all for their interface, but have them call a common function
//-----------------------------------------------------------------------------
CPUTMaterial *CPUTAssetLibrary::GetMaterial(
    const std::string   &name,
    bool                 nameIsFullPathAndFilename
){
    // Resolve name to absolute path before searching
    std::string absolutePathAndFilename;
    if (name[0] == '%')
    {
        absolutePathAndFilename = mSystemDirectoryName + "Material/" + name.substr(1) + ".mtl";  // TODO: Instead of having the Material/directory hardcoded here it could be set like the normal material directory. But then there would need to be a bunch new variables like SetSystemMaterialDirectory
        CPUTFileSystem::ResolveAbsolutePathAndFilename(absolutePathAndFilename, &absolutePathAndFilename);
    } else if( !nameIsFullPathAndFilename )
    {
        CPUTFileSystem::ResolveAbsolutePathAndFilename( mMaterialDirectoryName + name + ".mtl", &absolutePathAndFilename);
    } else
    {
        absolutePathAndFilename = name;
    }

    CPUTMaterial *pMaterial = NULL;

    pMaterial = FindMaterial(absolutePathAndFilename, true);

    if( pMaterial )
    {
        pMaterial->AddRef();
    }
    else
    {
        pMaterial = CPUTMaterial::Create(absolutePathAndFilename);
        LIBRARY_ASSERT(pMaterial, "Failed creating material Effect.");
        if (pMaterial != NULL)
        {
            AddMaterial(absolutePathAndFilename, "", "", pMaterial);
        }
    }
    return pMaterial;
}
Exemplo n.º 19
0
//-----------------------------------------------------------------------------
// Purpose: Factory. Creates a material by name, first looking in the cache.
// 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 *CMaterialCache::CreateMaterial(const char *pszMaterialName)
{
	CMaterial *pMaterial = NULL;

	if (pszMaterialName != NULL)
	{
		//
		// Find this material in the cache. If it is here, return it.
		//
		pMaterial = FindMaterial(pszMaterialName);
		if (pMaterial == NULL)
		{
			//
			// Not found in the cache, try to create it.
			//
			pMaterial = CMaterial::CreateMaterial(pszMaterialName, true);
			if (pMaterial != NULL)
			{
				//
				// Success. Add the newly created material to the cache.
				//
				AddMaterial(pMaterial);
				return(pMaterial);
			}
		}
		else
		{
			//
			// Found in the cache, bump the reference count.
			//
			AddRef(pMaterial);
		}
	}

	return(pMaterial);
}
Exemplo n.º 20
0
// AddEffective --
void V4SceneManager::AddEffective(GF_Node * node) {

  // gets the node type (equals pool number)
  u32 poolN = pools.poolN(gf_node_get_tag(node));

  // adds the node using a type specific function
  switch (poolN) {
    case DICT_GEN: {
      AddGen(node);
      break;
    }

    case DICT_GEOMETRY: {
      AddGeometry(node);
      break;
    }

    case DICT_APPEARANCE: {
      AddAppearance(node);
      break;
    }

    case DICT_TEXTURE: {
      AddTexture(node);
      break;
    }

    case DICT_MATERIAL: {
      AddMaterial(node);
      break;
    }

    // TODO : raise an exception when not found
  }

}
Exemplo n.º 21
0
bool trpgMatTable1_0::Read(trpgReadBuffer &buf)
{
    trpgMaterial mat;
    trpgToken matTok;
    int32 len;
    bool status;
    unsigned int i,j,k;

    std::vector<trpgShortMaterial> shortTable;
    std::vector<trpgMaterial> baseMats;

    try {
        buf.Get(numTable);
        buf.Get(numMat);
        if (numTable <= 0 || numMat < 0) throw 1;

        // Short material tables are always full size
        shortTable.resize(numTable*numMat);

        // Look for short material table
        buf.GetToken(matTok,len);
        if (matTok == TRPGSHORTMATTABLE) {
            int32 numTex,texId;
            buf.PushLimit(len);
            for (i=0;i<(unsigned int)numTable;i++) {
                for (j=0;j<(unsigned int)numMat;j++) {
                    trpgShortMaterial &smat = shortTable[i*numMat+j];
                    buf.Get(smat.baseMat);
                    buf.Get(numTex);
                    for (k=0;k<(unsigned int)numTex;k++) {
                        buf.Get(texId);
                        smat.texids.push_back(texId);
                    }
                }
            }
            buf.PopLimit();

            // Now read the base materials
            int32 numBaseMat;
            buf.Get(numBaseMat);
            if (numBaseMat < 0) throw 1;
            baseMats.resize(numBaseMat);
            for (i=0;i<(unsigned int)numBaseMat;i++) {
                buf.GetToken(matTok,len);
                if (matTok != TRPGMATERIAL) throw 1;
                buf.PushLimit(len);
                mat.Reset();
                status = mat.Read(buf);
                buf.PopLimit();
                if (!status) throw 1;
                baseMats[i] = mat;
            }
        }
    }
    catch (...) {
        return false;
    }

    // Now convert to the new style material table
    for (i=0;i<shortTable.size();i++) {
        trpgShortMaterial &shortMat = shortTable[i];
        trpgMaterial &baseMat = baseMats[shortMat.baseMat];
        AddMaterial(baseMat,false);

        trpgMaterial newMat = baseMat;
        newMat.SetNumTexture(shortMat.texids.size());
        for (j=0;j<shortMat.texids.size();j++) {
            int texId;
            trpgTextureEnv texEnv;
            baseMat.GetTexture(j,texId,texEnv);
            newMat.SetTexture(j,shortMat.texids[j],texEnv);
        }
    }

    valid = true;
    return true;
}
Exemplo n.º 22
0
HRESULT CModelContent::LoadFromFile(LPCWSTR filePath)
{
    HRESULT hr = S_OK;
    DWORD cbRead = 0;
    IStream* pStream = NULL;
    MODELCONTENTFILEHEADER header = {0};
        
    hr = FileStream::OpenFile(filePath, &pStream, false);
    GOTO_EXIT_IF_FAILED_MESSAGE(hr, "Failed to load model content file");

    // Read file header
    hr = pStream->Read(&header, sizeof(header), &cbRead);

    // Read vertices buffers
    for (UINT i = 0; i < header.numVertexBuffers; i++)
    {
        // Read header
        MODELCONTENTBUFFERHEADER bufHeader = {0};
        hr = pStream->Read(&bufHeader, sizeof(bufHeader), &cbRead);

        // Read data
        BYTE* pBuffer = new BYTE[bufHeader.numElements * bufHeader.stride];
        hr = pStream->Read(pBuffer, bufHeader.numElements * bufHeader.stride, &cbRead);

        // Add vertex buffer
        AddVertexBuffer(pBuffer, bufHeader.numElements, bufHeader.stride);

        SAFE_DELETE_ARRAY(pBuffer);
    }

    // Read indices buffers
    for (UINT i = 0; i < header.numIndexBuffers; i++)
    {
        MODELCONTENTBUFFERHEADER bufHeader = {0};
        hr = pStream->Read(&bufHeader, sizeof(bufHeader), &cbRead);
        
        // Read data
        BYTE* pBuffer = new BYTE[bufHeader.numElements * bufHeader.stride];
        hr = pStream->Read(pBuffer, bufHeader.numElements * bufHeader.stride, &cbRead);

        // Add index buffer
        AddIndexBuffer(pBuffer, bufHeader.numElements, bufHeader.stride);

        SAFE_DELETE_ARRAY(pBuffer);
    }

    // Read materials
    for (UINT i = 0; i < header.numMaterials; i++)
    {
        MODELCONTENTMATERIALHEADER materialheader = {0};
        hr = pStream->Read(&materialheader, sizeof(materialheader), &cbRead);

        // Add material
        AddMaterial(materialheader.diffuse, materialheader.specular, materialheader.normal);
    }

    // Read meshes
    for (UINT i = 0; i < header.numMeshes; i++)
    {
        MODELCONTENTMESHHEADER meshHeader = {0};
        hr = pStream->Read(&meshHeader, sizeof(meshHeader), &cbRead);

        // Add mesh
        //AddMesh(meshHeader.name, meshHeader.info.vertexBufferId, meshHeader.info.indexBufferId, meshHeader.info.materialId);
        m_meshMap.insert(std::pair<std::string,MeshInfo>(std::string(meshHeader.name), meshHeader.info));

    }

Exit:

    SAFE_RELEASE(pStream);

    return hr;
}
  SceneForRaytracingCamp3::SceneForRaytracingCamp3() {
    const Vector3 objectsCenter(0, 0, 0);

    std::vector<std::string> files;
    files.push_back("input_data/marble1.png");
    files.push_back("input_data/marble2.jpg");
    files.push_back("input_data/marble3.jpg");
    files.push_back("input_data/marble4.jpg");

    double refraction_rate = 2.0;
    double radius = 17.0;
    double haba = 5;

    Vector3 posOffset(50 - (radius+haba) * 2 * 5, 0, -150);

    int size = files.size();
    for (int texIdx = -10; texIdx < size; texIdx++)
    {
      double z = texIdx * (radius + haba) * 2.0 * 2.0;
      int trueTexIdx = texIdx;
      while (trueTexIdx < 0) trueTexIdx += size;
      trueTexIdx %= size;

      ImageHandler::IMAGE_ID tex_id = ImageHandler::GetInstance().LoadFromFile(files[trueTexIdx]);
      for (int rateIdx = -15; rateIdx <= 25; rateIdx++)
      {
        double rate1 = rateIdx*0.1;
        if (rate1 < 0) rate1 = -rate1;
        if (rate1 > 1) rate1 = 2 - rate1;
        rate1 = std::max(std::min(rate1, 1.0), 0.0);
        double rate2 = 1 - rate1;

        double x = rateIdx * (radius + haba) * 2.0;

        Vector3 pos1(x, radius, z), pos2(x, radius, z + (radius + haba) * 2);

        // Diffuse + Refraction
        {
          Material mat1(Material::REFLECTION_TYPE_LAMBERT, Color(), Color(1, 1, 1), 0, tex_id);
          Material mat2(Material::REFLECTION_TYPE_REFRACTION, Color(), Color(1, 1, 1), refraction_rate, ImageHandler::INVALID_IMAGE_ID);

          auto obj = new Sphere(radius, pos1 + posOffset, mat1);
          obj->GetMaterial(0)->rate_ = rate1;
          obj->AddMaterial(mat2, rate2);
          AddObject(obj, true, true);
        }

        // Diffuse + Reflection
        {
          Material mat1(Material::REFLECTION_TYPE_LAMBERT, Color(), Color(1, 1, 1), 0, tex_id);
          Material mat2(Material::REFLECTION_TYPE_SPECULAR, Color(), Color(1, 1, 1), refraction_rate, ImageHandler::INVALID_IMAGE_ID);

          auto obj = new Sphere(radius, pos2 + posOffset, mat1);
          obj->GetMaterial(0)->rate_ = rate1;
          obj->AddMaterial(mat2, rate2);
          AddObject(obj, true, true);
        }

      }
    }

    AddInfiniteFLoor(0, Material(Material::REFLECTION_TYPE_LAMBERT, Color(), Color(1, 1, 1)));

    m_ibl.reset(new IBL("input_data/Barce_Rooftop_C_Env.hdr", 1000000.0, objectsCenter));


    ConstructQBVH();
  }
Exemplo n.º 24
0
static std::shared_ptr<asd::Mesh> CreateMesh(asd::Graphics* graphics)
{
	uint8_t weights1[4];
	weights1[0] = 255;
	weights1[1] = 0;
	weights1[2] = 0;
	weights1[3] = 0;
	int* pweights1 = (int*) weights1;

	uint8_t weights2[4];
	weights2[0] = 0;
	weights2[1] = 255;
	weights2[2] = 0;
	weights2[3] = 0;
	int* pweights2 = (int*) weights2;

	uint8_t indexes[4];
	indexes[0] = 0;
	indexes[1] = 1;
	indexes[2] = 0;
	indexes[3] = 0;
	int* pindexes = (int*) indexes;

	auto mesh = graphics->CreateMesh();
	mesh->AddVertex(asd::Vector3DF(-0.5, 0.5, 0.5), asd::Vector3DF(0, 0, 1), asd::Vector3DF(0, 1, 0), asd::Vector2DF(0, 0), asd::Vector2DF(0, 0), asd::Color(255, 255, 255, 255), *pweights1, *pindexes);
	mesh->AddVertex(asd::Vector3DF(-0.5, -0.5, 0.5), asd::Vector3DF(0, 0, 1), asd::Vector3DF(0, 1, 0), asd::Vector2DF(0, 1), asd::Vector2DF(0, 1), asd::Color(255, 255, 255, 255), *pweights2, *pindexes);
	mesh->AddVertex(asd::Vector3DF(0.5, 0.5, 0.5), asd::Vector3DF(0, 0, 1), asd::Vector3DF(0, 1, 0), asd::Vector2DF(1, 0), asd::Vector2DF(1, 0), asd::Color(255, 255, 255, 255), *pweights1, *pindexes);
	mesh->AddVertex(asd::Vector3DF(0.5, -0.5, 0.5), asd::Vector3DF(0, 0, 1), asd::Vector3DF(0, 1, 0), asd::Vector2DF(1, 1), asd::Vector2DF(1, 1), asd::Color(255, 255, 255, 255), *pweights2, *pindexes);
	mesh->AddVertex(asd::Vector3DF(0.5, 0.5, -0.5), asd::Vector3DF(1, 0, 0), asd::Vector3DF(0, 1, 0), asd::Vector2DF(1, 0), asd::Vector2DF(1, 0), asd::Color(255, 255, 255, 255), *pweights1, *pindexes);
	mesh->AddVertex(asd::Vector3DF(0.5, -0.5, -0.5), asd::Vector3DF(1, 0, 0), asd::Vector3DF(0, 1, 0), asd::Vector2DF(1, 1), asd::Vector2DF(1, 1), asd::Color(255, 255, 255, 255), *pweights2, *pindexes);
	mesh->AddVertex(asd::Vector3DF(-0.5, 0.5, -0.5), asd::Vector3DF(0, 0, -1), asd::Vector3DF(0, 1, 0), asd::Vector2DF(1, 0), asd::Vector2DF(1, 0), asd::Color(255, 255, 255, 255), *pweights1, *pindexes);
	mesh->AddVertex(asd::Vector3DF(-0.5, -0.5, -0.5), asd::Vector3DF(0, 0, -1), asd::Vector3DF(0, 1, 0), asd::Vector2DF(1, 1), asd::Vector2DF(1, 1), asd::Color(255, 255, 255, 255), *pweights2, *pindexes);
	mesh->AddVertex(asd::Vector3DF(-0.5, 0.5, 0.5), asd::Vector3DF(-1, 0, 0), asd::Vector3DF(0, 1, 0), asd::Vector2DF(1, 0), asd::Vector2DF(1, 0), asd::Color(255, 255, 255, 255), *pweights1, *pindexes);
	mesh->AddVertex(asd::Vector3DF(-0.5, 0.5, 0.5), asd::Vector3DF(0, 1, 0), asd::Vector3DF(0, 0, -1), asd::Vector2DF(0, 1), asd::Vector2DF(0, 1), asd::Color(255, 255, 255, 255), *pweights1, *pindexes);
	mesh->AddVertex(asd::Vector3DF(-0.5, -0.5, 0.5), asd::Vector3DF(-1, 0, 0), asd::Vector3DF(0, 1, 0), asd::Vector2DF(1, 1), asd::Vector2DF(1, 1), asd::Color(255, 255, 255, 255), *pweights2, *pindexes);
	mesh->AddVertex(asd::Vector3DF(-0.5, -0.5, 0.5), asd::Vector3DF(0, -1, 0), asd::Vector3DF(0, 0, 1), asd::Vector2DF(0, 0), asd::Vector2DF(0, 0), asd::Color(255, 255, 255, 255), *pweights2, *pindexes);
	mesh->AddVertex(asd::Vector3DF(0.5, 0.5, 0.5), asd::Vector3DF(1, 0, 0), asd::Vector3DF(0, 1, 0), asd::Vector2DF(0, 0), asd::Vector2DF(0, 0), asd::Color(255, 255, 255, 255), *pweights1, *pindexes);
	mesh->AddVertex(asd::Vector3DF(0.5, 0.5, 0.5), asd::Vector3DF(0, 1, 0), asd::Vector3DF(0, 0, -1), asd::Vector2DF(1, 1), asd::Vector2DF(1, 1), asd::Color(255, 255, 255, 255), *pweights1, *pindexes);
	mesh->AddVertex(asd::Vector3DF(0.5, -0.5, 0.5), asd::Vector3DF(1, 0, 0), asd::Vector3DF(0, 1, 0), asd::Vector2DF(0, 1), asd::Vector2DF(0, 1), asd::Color(255, 255, 255, 255), *pweights2, *pindexes);
	mesh->AddVertex(asd::Vector3DF(0.5, -0.5, 0.5), asd::Vector3DF(0, -1, 0), asd::Vector3DF(0, 0, 1), asd::Vector2DF(1, 0), asd::Vector2DF(1, 0), asd::Color(255, 255, 255, 255), *pweights2, *pindexes);
	mesh->AddVertex(asd::Vector3DF(0.5, 0.5, -0.5), asd::Vector3DF(0, 0, -1), asd::Vector3DF(0, 1, 0), asd::Vector2DF(0, 0), asd::Vector2DF(0, 0), asd::Color(255, 255, 255, 255), *pweights1, *pindexes);
	mesh->AddVertex(asd::Vector3DF(0.5, 0.5, -0.5), asd::Vector3DF(0, 1, 0), asd::Vector3DF(0, 0, -1), asd::Vector2DF(1, 0), asd::Vector2DF(1, 0), asd::Color(255, 255, 255, 255), *pweights1, *pindexes);
	mesh->AddVertex(asd::Vector3DF(0.5, -0.5, -0.5), asd::Vector3DF(0, 0, -1), asd::Vector3DF(0, 1, 0), asd::Vector2DF(0, 1), asd::Vector2DF(0, 1), asd::Color(255, 255, 255, 255), *pweights2, *pindexes);
	mesh->AddVertex(asd::Vector3DF(0.5, -0.5, -0.5), asd::Vector3DF(0, -1, 0), asd::Vector3DF(0, 0, 1), asd::Vector2DF(1, 1), asd::Vector2DF(1, 1), asd::Color(255, 255, 255, 255), *pweights2, *pindexes);
	mesh->AddVertex(asd::Vector3DF(-0.5, 0.5, -0.5), asd::Vector3DF(-1, 0, 0), asd::Vector3DF(0, 1, 0), asd::Vector2DF(0, 0), asd::Vector2DF(0, 0), asd::Color(255, 255, 255, 255), *pweights1, *pindexes);
	mesh->AddVertex(asd::Vector3DF(-0.5, 0.5, -0.5), asd::Vector3DF(0, 1, 0), asd::Vector3DF(0, 0, -1), asd::Vector2DF(0, 0), asd::Vector2DF(0, 0), asd::Color(255, 255, 255, 255), *pweights1, *pindexes);
	mesh->AddVertex(asd::Vector3DF(-0.5, -0.5, -0.5), asd::Vector3DF(-1, 0, 0), asd::Vector3DF(0, 1, 0), asd::Vector2DF(0, 1), asd::Vector2DF(0, 1), asd::Color(255, 255, 255, 255), *pweights2, *pindexes);
	mesh->AddVertex(asd::Vector3DF(-0.5, -0.5, -0.5), asd::Vector3DF(0, -1, 0), asd::Vector3DF(0, 0, 1), asd::Vector2DF(0, 1), asd::Vector2DF(0, 1), asd::Color(255, 255, 255, 255), *pweights2, *pindexes);

	mesh->AddFace(0, 2, 3, 0);
	mesh->AddFace(0, 3, 1, 0);
	mesh->AddFace(12, 4, 5, 0);
	mesh->AddFace(12, 5, 14, 0);
	mesh->AddFace(16, 6, 7, 0);
	mesh->AddFace(16, 7, 18, 0);
	mesh->AddFace(20, 8, 10, 0);
	mesh->AddFace(20, 10, 22, 0);
	mesh->AddFace(21, 17, 13, 0);
	mesh->AddFace(21, 13, 9, 0);
	mesh->AddFace(11, 15, 19, 0);
	mesh->AddFace(11, 19, 23, 0);

	mesh->AddMaterial();

	auto texture = graphics->CreateTexture2D(asd::ToAString(L"Data/Texture/Sample1.png").c_str());

	mesh->SetColorTexture(0, texture.get());
	return mesh;
}
Exemplo n.º 25
0
/**
****************************************************************************************************
@brief Create render target using framebuffer and attached texture
@param resX X-size of framebuffer texture
@param resY Y-size of framebuffer texture
@param tex_format OpenGL texture format (can be GL_RGBA, GL_RGBA16F or GL_RGBA32F)
@param tex_type internal data format (can be GL_UNSIGNED_BYTE or GL_FLOAT)
@param normal_buffer should we create another render target for normal and depth buffer?
***************************************************************************************************/
void TScene::CreateHDRRenderTarget(int resX, int resY, GLint tex_format, GLenum tex_type, bool normal_buffer)
{
    //if no resolution given, use current scene resolution
    if(resX == -1 || resY == -1)
    {
        resX = m_resx;
        resY = m_resy;
    }
    //force use of normal buffer if SSAO or IPSM is enabled
    if(m_useSSAO || m_dpshadow_method >= IPSM) 
        normal_buffer = true;
    m_useNormalBuffer = normal_buffer;

    //save render target size
    m_RT_resX = resX;
    m_RT_resY = resY;

    //create texture - for original image
    CreateDataTexture("render_texture", resX, resY, tex_format, tex_type, GL_TEXTURE_2D);
    //create texture - for bloom effect
    CreateDataTexture("bloom_texture", resX, resY, tex_format, tex_type, GL_TEXTURE_2D);
    //create texture - for blur
    CreateDataTexture("blur_texture", resX, resY, tex_format, tex_type, GL_TEXTURE_2D);
    //create texture - for store normal values
    if(m_useNormalBuffer)
        CreateDataTexture("normal_texture", resX, resY, tex_format, tex_type, GL_TEXTURE_2D);

    //create renderbuffers
    glGenRenderbuffers(1, &m_r_buffer_depth);
    glBindRenderbuffer(GL_RENDERBUFFER, m_r_buffer_depth);
    glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT,resX, resY);

    //if MSAA enabled, create also multisampled framebuffer (only when platform supports it)
    if(m_msamples > 1 && GLEW_EXT_framebuffer_multisample)
    {
        //Create multisampled color renderbuffer
        glGenRenderbuffers(1, &m_r_buffer_colorMSAA);
        glBindRenderbuffer(GL_RENDERBUFFER, m_r_buffer_colorMSAA);
        glRenderbufferStorageMultisample(GL_RENDERBUFFER, m_msamples, tex_format, resX, resY);

        //Create multisampled normal renderbuffer
        if(m_useNormalBuffer)
        {
            glGenRenderbuffers(1, &m_r_buffer_normalMSAA);
            glBindRenderbuffer(GL_RENDERBUFFER, m_r_buffer_normalMSAA);
            glRenderbufferStorageMultisample(GL_RENDERBUFFER, m_msamples, tex_format, resX, resY);
        }

        //Create multisampled depth renderbuffer
        glGenRenderbuffers(1, &m_r_buffer_depthMSAA);
        glBindRenderbuffer(GL_RENDERBUFFER, m_r_buffer_depthMSAA);
        glRenderbufferStorageMultisample(GL_RENDERBUFFER, m_msamples, GL_DEPTH_COMPONENT,resX, resY);

        //Attach to multisampled framebuffer
        glGenFramebuffers(1, &m_f_bufferMSAA);
        glBindFramebuffer(GL_FRAMEBUFFER, m_f_bufferMSAA);
        glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, m_r_buffer_colorMSAA);
        if(m_useNormalBuffer)
            glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_RENDERBUFFER, m_r_buffer_normalMSAA);
        glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, m_r_buffer_depthMSAA);

        //check FBO creation
        if(!CheckFBO())
        {
            cout<<"WARNING: Multisampled FBO creation failed, falling back to regular FBO.\n";
            m_msamples = 1;
        }
    }

    //Finally, create framebuffer
    glGenFramebuffers(1, &m_f_buffer);
    glBindFramebuffer(GL_FRAMEBUFFER, m_f_buffer);

    //attach texture to the frame buffer
    glFramebufferTexture2D(GL_FRAMEBUFFER,GL_COLOR_ATTACHMENT0,GL_TEXTURE_2D, m_tex_cache["render_texture"], 0);
    //attach also normal texture if desired (e.g. for SSAO)
    if(m_useNormalBuffer)
        glFramebufferTexture2D(GL_FRAMEBUFFER,GL_COLOR_ATTACHMENT1,GL_TEXTURE_2D, m_tex_cache["normal_texture"], 0);
    //attach render buffers
    glFramebufferRenderbuffer(GL_FRAMEBUFFER,GL_DEPTH_ATTACHMENT,GL_RENDERBUFFER, m_r_buffer_depth);


    //check FBO creation
    if(!CheckFBO())
    {
        m_useHDR = m_useSSAO = m_useNormalBuffer = false;
        throw ERR;
    }

    // Go back to regular frame buffer rendering
    glBindFramebuffer(GL_FRAMEBUFFER, 0);

    //update load list
    UpdateLoadList(34);

    //HDR passes - render to texture, bloom effect, SSAO and tonemapping
    AddMaterial("mat_bloom_hdr_ssao",white,white,white,0.0,0.0,0.0,SCREEN_SPACE);
    
    //various defines depending if we want HDR only, SSAO only or both together
    string defines = "#define BLOOM\n";
    if(m_useSSAO)       //SSAO only
    {
        defines = "#define SSAO\n";        
        AddTexture("mat_bloom_hdr_ssao","normal_texture",RENDER_TEXTURE);   //add normal texture
        if(m_useHDR)    //HDR + SSAO
            defines = "#define BLOOM\n#define SSAO\n";
    }
    AddTexture("mat_bloom_hdr_ssao","render_texture",RENDER_TEXTURE);
    AddTexture("mat_bloom_hdr_ssao","data/tex/random.tga");
    CustomShader("mat_bloom_hdr_ssao","data/shaders/quad.vert", "data/shaders/bloom_ssao.frag", " ",defines.c_str());

    //tonemapping
    AddMaterial("mat_tonemap",white,white,white,0.0,0.0,0.0,SCREEN_SPACE);
    AddTexture("mat_tonemap","render_texture",RENDER_TEXTURE);
    AddTexture("mat_tonemap","blur_texture",RENDER_TEXTURE);
    if(m_useNormalBuffer)
        AddTexture("mat_tonemap","normal_texture",RENDER_TEXTURE);
    CustomShader("mat_tonemap","data/shaders/quad.vert","data/shaders/tonemap.frag");

    //blur
    AddMaterial("mat_blur_horiz",white,white,white,0.0,0.0,0.0,SCREEN_SPACE);
    AddTexture("mat_blur_horiz","bloom_texture",RENDER_TEXTURE);
    CustomShader("mat_blur_horiz","data/shaders/quad.vert","data/shaders/blur.frag", " ","#define HORIZONTAL\n");
    SetUniform("mat_blur_horiz", "texsize", glm::ivec2(resX, resY));       //send texture size info

    AddMaterial("mat_blur_vert",white,white,white,0.0,0.0,0.0,SCREEN_SPACE);
    AddTexture("mat_blur_vert","bloom_texture",RENDER_TEXTURE);
    CustomShader("mat_blur_vert","data/shaders/quad.vert","data/shaders/blur.frag", " ", "#define VERTICAL\n");
    SetUniform("mat_blur_vert", "texsize", glm::ivec2(resX, resY));       //send texture size info
}
Exemplo n.º 26
0
	bool MTLParser::Parse(Stream& stream)
	{
		m_currentStream = &stream;

		// Force stream in text mode, reset it at the end
		Nz::CallOnExit resetTextMode;
		if ((stream.GetStreamOptions() & StreamOption_Text) == 0)
		{
			stream.EnableTextMode(true);

			resetTextMode.Reset([&stream] ()
			{
				stream.EnableTextMode(false);
			});
		}

		m_keepLastLine = false;
		m_lineCount = 0;
		m_materials.clear();

		Material* currentMaterial = nullptr;

		while (Advance(false))
		{
			String keyword = m_currentLine.GetWord(0).ToLower();
			if (keyword == "ka")
			{
				float r, g, b;
				if (std::sscanf(&m_currentLine[3], "%f %f %f", &r, &g, &b) == 3)
				{
					if (!currentMaterial)
						currentMaterial = AddMaterial("default");

					currentMaterial->ambient = Color(static_cast<UInt8>(r*255.f), static_cast<UInt8>(g*255.f), static_cast<UInt8>(b*255.f));
				}
				#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING
				else
					UnrecognizedLine();
				#endif
			}
			else if (keyword == "kd")
			{
				float r, g, b;
				if (std::sscanf(&m_currentLine[3], "%f %f %f", &r, &g, &b) == 3)
				{
					if (!currentMaterial)
						currentMaterial = AddMaterial("default");

					currentMaterial->diffuse = Color(static_cast<UInt8>(r*255.f), static_cast<UInt8>(g*255.f), static_cast<UInt8>(b*255.f));
				}
				#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING
				else
					UnrecognizedLine();
				#endif
			}
			else if (keyword == "ks")
			{
				float r, g, b;
				if (std::sscanf(&m_currentLine[3], "%f %f %f", &r, &g, &b) == 3)
				{
					if (!currentMaterial)
						currentMaterial = AddMaterial("default");

					currentMaterial->specular = Color(static_cast<UInt8>(r*255.f), static_cast<UInt8>(g*255.f), static_cast<UInt8>(b*255.f));
				}
				#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING
				else
					UnrecognizedLine();
				#endif
			}
			else if (keyword == "ni")
			{
				float density;
				if (std::sscanf(&m_currentLine[3], "%f", &density) == 1)
				{
					if (!currentMaterial)
						currentMaterial = AddMaterial("default");

					currentMaterial->refractionIndex = density;
				}
				#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING
				else
					UnrecognizedLine();
				#endif
			}
			else if (keyword == "ns")
			{
				float coef;
				if (std::sscanf(&m_currentLine[3], "%f", &coef) == 1)
				{
					if (!currentMaterial)
						currentMaterial = AddMaterial("default");

					currentMaterial->shininess = coef;
				}
				#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING
				else
					UnrecognizedLine();
				#endif
			}
			else if (keyword == 'd')
			{
				float alpha;
				if (std::sscanf(&m_currentLine[(keyword[0] == 'd') ? 2 : 3], "%f", &alpha) == 1)
				{
					if (!currentMaterial)
						currentMaterial = AddMaterial("default");

					currentMaterial->alpha = alpha;
				}
				#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING
				else
					UnrecognizedLine();
				#endif
			}
			else if (keyword == "tr")
			{
				float alpha;
				if (std::sscanf(&m_currentLine[(keyword[0] == 'd') ? 2 : 3], "%f", &alpha) == 1)
				{
					if (!currentMaterial)
						currentMaterial = AddMaterial("default");

					currentMaterial->alpha = 1.f - alpha; // tr vaut pour la "valeur de transparence", 0 = opaque
				}
				#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING
				else
					UnrecognizedLine();
				#endif
			}
			else if (keyword == "illum")
			{
				unsigned int model;
				if (std::sscanf(&m_currentLine[6], "%u", &model) == 1)
				{
					if (!currentMaterial)
						currentMaterial = AddMaterial("default");

					currentMaterial->illumModel = model;
				}
				#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING
				else
					UnrecognizedLine();
				#endif
			}
			else if (keyword == "map_ka")
			{
				std::size_t mapPos = m_currentLine.GetWordPosition(1);
				if (mapPos != String::npos)
				{
					String map = m_currentLine.SubString(mapPos);
					if (!currentMaterial)
						currentMaterial = AddMaterial("default");

					currentMaterial->ambientMap = map;
				}
			}
			else if (keyword == "map_kd")
			{
				std::size_t mapPos = m_currentLine.GetWordPosition(1);
				if (mapPos != String::npos)
				{
					String map = m_currentLine.SubString(mapPos);
					if (!currentMaterial)
						currentMaterial = AddMaterial("default");

					currentMaterial->diffuseMap = map;
				}
			}
			else if (keyword == "map_ks")
			{
				std::size_t mapPos = m_currentLine.GetWordPosition(1);
				if (mapPos != String::npos)
				{
					String map = m_currentLine.SubString(mapPos);
					if (!currentMaterial)
						currentMaterial = AddMaterial("default");

					currentMaterial->specularMap = map;
				}
			}
			else if (keyword == "map_bump" || keyword == "bump")
			{
				std::size_t mapPos = m_currentLine.GetWordPosition(1);
				if (mapPos != String::npos)
				{
					String map = m_currentLine.SubString(mapPos);
					if (!currentMaterial)
						currentMaterial = AddMaterial("default");

					currentMaterial->bumpMap = map;
				}
			}
			else if (keyword == "map_d")
			{
				std::size_t mapPos = m_currentLine.GetWordPosition(1);
				if (mapPos != String::npos)
				{
					String map = m_currentLine.SubString(mapPos);
					if (!currentMaterial)
						currentMaterial = AddMaterial("default");

					currentMaterial->alphaMap = map;
				}
			}
			else if (keyword == "map_decal" || keyword == "decal")
			{
				std::size_t mapPos = m_currentLine.GetWordPosition(1);
				if (mapPos != String::npos)
				{
					String map = m_currentLine.SubString(mapPos);
					if (!currentMaterial)
						currentMaterial = AddMaterial("default");

					currentMaterial->decalMap = map;
				}
			}
			else if (keyword == "map_disp" || keyword == "disp")
			{
				std::size_t mapPos = m_currentLine.GetWordPosition(1);
				if (mapPos != String::npos)
				{
					String map = m_currentLine.SubString(mapPos);
					if (!currentMaterial)
						currentMaterial = AddMaterial("default");

					currentMaterial->displacementMap = map;
				}
			}
			else if (keyword == "map_refl" || keyword == "refl")
			{
				std::size_t mapPos = m_currentLine.GetWordPosition(1);
				if (mapPos != String::npos)
				{
					String map = m_currentLine.SubString(mapPos);
					if (!currentMaterial)
						currentMaterial = AddMaterial("default");

					currentMaterial->reflectionMap = map;
				}
			}
			else if (keyword == "newmtl")
			{
				String materialName = m_currentLine.SubString(m_currentLine.GetWordPosition(1));
				if (!materialName.IsEmpty())
					currentMaterial = AddMaterial(materialName);
				#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING
				else
					UnrecognizedLine();
				#endif
			}
			#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING
			else
				UnrecognizedLine();
			#endif
		}

		return true;
	}
// ****************************************************************************
//  Method: avtMatvfExpression::ProcessArguments
//
//  Purpose:
//      Tells the first argument to go generate itself.  Parses the second
//      argument into a list of material names.
//
//  Arguments:
//      inDS      The input dataset.
//
//  Returns:      The derived variable.  The calling class must free this
//                memory.
//
//  Programmer:   Sean Ahern
//  Creation:     Tue Mar 18 23:20:06 America/Los_Angeles 2003
//
//  Modifications:
//    Jeremy Meredith, Mon Sep 29 12:13:04 PDT 2003
//    Added support for integer material indices.
//    Added support for integer ranges.
//
//    Hank Childs, Thu Jul 15 14:44:17 PDT 2004
//    Make sure the base pointer type for the dynamic cast is in the 
//    inheritance tree of what we are downcasting type. ('5201)
//
//    Jeremy Meredith, Wed Nov 24 12:26:21 PST 2004
//    Renamed EngineExprNode to avtExprNode due to a refactoring.
//    Also renamed Token to ExprToken for the same reason.
//    Changed the base type for an Arg's expression.
//
//    Jeremy Meredith, Mon Jun 13 11:42:38 PDT 2005
//    Changed the way constant expressions work.
//
// ****************************************************************************
void
avtMatvfExpression::ProcessArguments(ArgsExpr *args, ExprPipelineState *state)
{
    // Check the number of arguments
    std::vector<ArgExpr*> *arguments = args->GetArgs();
    int nargs = arguments->size();
    if (nargs == 0)
    {
        EXCEPTION2(ExpressionException, outputVariableName, "avtMatvfExpression: No arguments given.");
    }
    // Tell the first argument to create its filters.
    ArgExpr *firstarg = (*arguments)[0];
    avtExprNode *firstTree = dynamic_cast<avtExprNode*>(firstarg->GetExpr());
    firstTree->CreateFilters(state);

    // Check if there's a second argument.
    if (nargs == 1)
    {
        debug5 << "avtMatvfExpression: No second argument." << endl;
        return;
    }

    // See if there are other arguments.
    if (nargs > 2)
    {
        EXCEPTION2(ExpressionException, outputVariableName, "avtMatvfExpression only expects two "
                   "arguments.  To specify more than one material, use a "
                   "list (e.g. [1,4,5:9].");
    }

    // Pull off the second argument and see if it's a string or a list.
    ArgExpr *secondarg = (*arguments)[1];
    ExprParseTreeNode *secondTree = secondarg->GetExpr();
    std::string type = secondTree->GetTypeName();
    if ((type != "IntegerConst") && (type != "StringConst") && (type != "List"))
    {
        debug5 << "avtMatvfExpression: Second argument is not a constant or a list: " << type.c_str() << endl;
        EXCEPTION2(ExpressionException, outputVariableName, "avtMatvfExpression: Second argument is not a constant or a list.");
    }

    if (type == "IntegerConst" || type == "StringConst")
    {
        // It's a single constant.
        AddMaterial(dynamic_cast<ConstExpr*>(secondTree));
    }
    else
    {
        // It's a list.  Process all of them.
        ListExpr *list = dynamic_cast<ListExpr*>(secondTree);
        std::vector<ListElemExpr*> *elems = list->GetElems();
        for(int i=0;i<elems->size();i++)
        {
            if ((*elems)[i]->GetEnd())
            {
                // it's a range
                ExprNode *begExpr  = (*elems)[i]->GetBeg();
                ExprNode *endExpr  = (*elems)[i]->GetEnd();
                ExprNode *skipExpr = (*elems)[i]->GetSkip();
                
                if (begExpr->GetTypeName() != "IntegerConst" ||
                    endExpr->GetTypeName() != "IntegerConst" ||
                    (skipExpr && skipExpr->GetTypeName() != "IntegerConst"))
                {
                    EXCEPTION2(ExpressionException, outputVariableName, "avtMatvfExpression: "
                               "Range must contain integers.");
                }

                int beg  = dynamic_cast<IntegerConstExpr*>(begExpr)->GetValue();
                int end  = dynamic_cast<IntegerConstExpr*>(endExpr)->GetValue();
                int skip = !skipExpr ? 1 : 
                           dynamic_cast<IntegerConstExpr*>(skipExpr)->GetValue();

                if (skip <= 0 || beg > end)
                {
                    EXCEPTION2(ExpressionException, outputVariableName, "avtMatvfExpression: "
                               "Range must be of the form beg:end[:skip].");
                }

                for (int m = beg; m <= end ; m += skip)
                    matIndices.push_back(m);
            }
            else
            {
                ExprNode *item = (*elems)[i]->GetItem();
                std::string type = item->GetTypeName();
                if (type != "IntegerConst" && type != "StringConst")
                {
                    debug5 << "avtMatvfExpression: List element is not an "
                              "integer constant, a string constant, "
                              "or a list: " << type.c_str() << endl;
                    EXCEPTION2(ExpressionException, outputVariableName, "avtMatvfExpression: "
                               "List element is not an int/string constant "
                               "or a list.");
                }

                AddMaterial(dynamic_cast<ConstExpr*>(item));
            }
        }
    }
}
Exemplo n.º 28
0
// to read in a filed mesh
// Currently ignores material info.
int Mesh::readFile(std::string fileName)
{
	int nVertis = 0;
	int nFaces = 0;
	int nFaceVerts = 0;
	int nVNormals = 0;
	int nFNormals = 0;
	int nFNormVerts = 0;
	int nTexCoors = 0;
	int nMaterials = 0;
	int nMaterialFacesAdded = 0;
	std::string line;
	std::string token;
	bool bInMesh = false;
	bool bInVertices = false;
	bool bInFaces = false;
	bool bFirstLine = false;
	bool bSecondLine = false;
	bool bInVNormals = false;
	bool bInFNormals = false;
	bool bInMaterials = false;
	bool bInMaterialList = false;
	bool bInTexCoors = false;

	size_t pos;
	Vector3 p3;
	int index[4]; // support triangles or quads only
	float vert[4]; // also used for RGBA

	std::ifstream myfile (fileName.c_str());
	if (myfile.is_open())
	{
		while ( myfile.good() )
		{
			getline (myfile,line);
			//std::cout << line << std::endl;

			if ((pos = line.find("//")) != std::string::npos) {
					line = line.substr(0, pos);
			}
			if ((pos = line.find("#")) != std::string::npos) {
					line = line.substr(0, pos);
			}
			
			if (line.length() == 0) {
				continue;
			}
			else if ((pos = line.find("Mesh ")) != std::string::npos) {
				bInMesh = true;
				bInVertices = true;
				bFirstLine = true;
			}
			else if (bInVertices && bFirstLine) {
				bFirstLine = false;
				pos = line.find(";");
				if (pos != std::string::npos) {
					line.erase(pos);
					nVertis = atoi(line.c_str());
				}
				else {
					myfile.close();
					return(1);
				}
			}
			else if (bInVertices) {
				int i = 0;
				while (i < 3) {
					if ((pos = line.find(";")) != std::string::npos) {
						token = line.substr(0, pos);
						line = line.substr(pos+1);
						vert[i] = atof(token.c_str());
						i++;
					}
					else {
						myfile.close();
						return(1);
					}
				}
				p3 = vert;
				AddVertex(p3);
				if (nVertis == numVerts) {
					bInVertices = false;
					bInFaces = true;
					bFirstLine = true;
				}
			}


			else if (bInFaces && bFirstLine) {
				bFirstLine = false;
				pos = line.find(";");
				if (pos != std::string::npos) {
					line.erase(pos);
					nFaces = atoi(line.c_str());
				}
				else {
					myfile.close();
					return(1);
				}
			}
			else if (bInFaces) {
				int i = 0;
				if ((pos = line.find(";")) != std::string::npos) {
					token = line.substr(0, pos);
					line = line.substr(pos+1);
					nFaceVerts = atoi(token.c_str());
				}
				else {
					myfile.close();
					return(1);
				}
				while (i < nFaceVerts) {
					if ((pos = line.find(",")) != std::string::npos) {
						token = line.substr(0, pos);
						line = line.substr(pos+1);
						index[i] = atoi(token.c_str());
						i++;
					}
					else if ((pos = line.find(";")) != std::string::npos) {
						token = line.substr(0, pos);
						line = line.substr(pos+1);
						index[i] = atoi(token.c_str());
						i++;
					}
					else {
						myfile.close();
						return(1);
					}
				}
				AddFace(nFaceVerts, index);
				if (nFaces == numFaces) {
					bInFaces = false;
				}
			}




			else if ((pos = line.find("MeshNormals")) != std::string::npos) {
				bInVNormals = true;
				bFirstLine = true;
			}
			else if (bInVNormals && bFirstLine) {
				bFirstLine = false;
				pos = line.find(";");
				if (pos != std::string::npos) {
					line.erase(pos);
					nVNormals = atoi(line.c_str());
				}
				else {
					myfile.close();
					return(1);
				}
			}
			else if (bInVNormals) {
				int i = 0;
				while (i < 3) {
					if ((pos = line.find(";")) != std::string::npos) {
						token = line.substr(0, pos);
						line = line.substr(pos+1);
						vert[i] = atof(token.c_str());
						i++;
					}
					else {
						myfile.close();
						return(1);
					}
				}
				p3 = vert;
				AddNormal(p3);
				if (nVNormals == numNormals) {
					bInVNormals = false;
					bInFNormals = true;
					bFirstLine = true;
				}
			}

			else if (bInFNormals && bFirstLine) {
				bFirstLine = false;
				pos = line.find(";");
				if (pos != std::string::npos) {
					line.erase(pos);
					//nFNormals = atoi(line.c_str());
				}
				else {
					myfile.close();
					return(1);
				}
			}
			else if (bInFNormals) {
				int i = 0;
				if ((pos = line.find(";")) != std::string::npos) {
					token = line.substr(0, pos);
					line = line.substr(pos+1);
					nFNormVerts = atoi(token.c_str());
				}
				else {
					myfile.close();
					return(1);
				}
				while (i < nFNormVerts) {
					if ((pos = line.find(",")) != std::string::npos) {
						token = line.substr(0, pos);
						line = line.substr(pos+1);
						index[i] = atoi(token.c_str());
						i++;
					}
					else if ((pos = line.find(";")) != std::string::npos) {
						token = line.substr(0, pos);
						line = line.substr(pos+1);
						index[i] = atoi(token.c_str());
						i++;
					}
					else {
						myfile.close();
						return(1);
					}
				}
				AddNormal(nFNormals, index);
				nFNormals++;
				if (nFNormals == numFaces) {
					bInFNormals = false;
				}
			}

			else if ((pos = line.find("MaterialList ")) != std::string::npos) {
				bInMaterialList = true;
				bFirstLine = true;
			}
			else if (bInMaterialList && bFirstLine) {
				bFirstLine = false;
				bSecondLine = true;

				int numMat = atoi(line.c_str());
				if (numMat == 0) {
					bInMaterialList = false;
					bSecondLine = false;
				}
			}
			else if (bInMaterialList && bSecondLine) {
				bFirstLine = false;
				bSecondLine = false;
			}
			else if (bInMaterialList) {
				vecFaces[nMaterialFacesAdded].materialIndex = atoi(line.c_str());
				nMaterialFacesAdded++;
				if (nMaterialFacesAdded == nFaces) {
					bInMaterialList = false;
				}
			}


			else if ((pos = line.find("Material ")) != std::string::npos) {
				bInMaterials = true;
				bFirstLine = true;
			}
			else if (bInMaterials && bFirstLine) {
				bInMaterials = false;
				bFirstLine = false;
				int i = 0;

				while (i < 4) {
					if ((pos = line.find(";")) != std::string::npos) {
						token = line.substr(0, pos);
						line = line.substr(pos+1);
						vert[i] = atof(token.c_str());
						i++;
					}
					else {
						myfile.close();
						return(1);
					}
				}
				AddMaterial(vert);
			}



			else if ((pos = line.find("MeshTextureCoords")) != std::string::npos) {
				bInTexCoors = true;
				bFirstLine = true;
			}
			else if (bInTexCoors && bFirstLine) {
				bFirstLine = false;
				pos = line.find(";");
				if (pos != std::string::npos) {
					line.erase(pos);
					nTexCoors = atoi(line.c_str());
				}
				else {
					myfile.close();
					return(1);
				}
			}
			else if (bInTexCoors) {
				int i = 0;
				while (i < 2) {
					if ((pos = line.find(";")) != std::string::npos) {
						token = line.substr(0, pos);
						line = line.substr(pos+1);
						vert[i] = atof(token.c_str());
						i++;
					}
					else {
						myfile.close();
						return(1);
					}
				}
				p3 = vert;
				AddTexCoor(p3);
				if (nTexCoors == numTexCoors) {
					bInTexCoors = false;
					bFirstLine = true;
				}
			}




		}
		myfile.close();
	}
	else {
		std::cout << "Unable to open file" << std::endl; 
	}

	return(0);
}