Beispiel #1
0
/*!
  \brief Get feature geometry

  \return pointer to OGRGeometry or NULL on error
*/
OGRGeometry *IVFKFeature::GetGeometry()
{
    if (m_nGeometryType != wkbNone && !m_bGeometry)
        LoadGeometry();

    return m_paGeom;
}
Beispiel #2
0
/*!
  \brief Get feature by FID

  Modifies next feature id.
  
  \param nFID feature id

  \return pointer to feature definition
  \return NULL on failure (not found)
*/
IVFKFeature *IVFKDataBlock::GetFeature(long nFID)
{
    if (m_nFeatureCount < 0) {
        m_poReader->ReadDataRecords(this);
    }
    
    if (nFID < 1 || nFID > m_nFeatureCount)
        return NULL;

    if (m_bGeometryPerBlock && !m_bGeometry) {
        LoadGeometry();
    }
    
    if (m_nGeometryType == wkbPoint ||
        m_nGeometryType == wkbPolygon ||
        m_nGeometryType == wkbNone) {
        return GetFeatureByIndex(int (nFID) - 1); /* zero-based index */
    }
    else if (m_nGeometryType == wkbLineString) {
        /* line string is built from more data records */
        for (int i = 0; i < m_nFeatureCount; i++) {
            if (m_papoFeature[i]->GetFID() == nFID) {
                m_iNextFeature = i + 1;
                return m_papoFeature[i];
            }
        }
    }
    
    return NULL;
}
Beispiel #3
0
Model::Model(string &model) {
  bounding_box_ = new AABB();
  LoadGeometry(model);
  
  lod_levels_ = 0;
  lod_ = 0;
}
void PlaylistView::SetPlaylist(Playlist* playlist) {
  if (playlist_) {
    disconnect(playlist_, SIGNAL(CurrentSongChanged(Song)),
               this, SLOT(MaybeAutoscroll()));
    disconnect(playlist_, SIGNAL(DynamicModeChanged(bool)),
               this, SLOT(DynamicModeChanged(bool)));
    disconnect(playlist_, SIGNAL(destroyed()), this, SLOT(PlaylistDestroyed()));

    disconnect(dynamic_controls_, SIGNAL(Repopulate()),
               playlist_, SLOT(RepopulateDynamicPlaylist()));
    disconnect(dynamic_controls_, SIGNAL(TurnOff()),
               playlist_, SLOT(TurnOffDynamicPlaylist()));
  }

  playlist_ = playlist;
  LoadGeometry();
  ReloadSettings();
  DynamicModeChanged(playlist->is_dynamic());
  setFocus();
  read_only_settings_ = false;

  connect(playlist_, SIGNAL(RestoreFinished()), SLOT(JumpToLastPlayedTrack()));

  connect(playlist_, SIGNAL(CurrentSongChanged(Song)), SLOT(MaybeAutoscroll()));
  connect(playlist_, SIGNAL(DynamicModeChanged(bool)), SLOT(DynamicModeChanged(bool)));
  connect(playlist_, SIGNAL(destroyed()), SLOT(PlaylistDestroyed()));
  connect(dynamic_controls_, SIGNAL(Repopulate()), playlist_, SLOT(RepopulateDynamicPlaylist()));
  connect(dynamic_controls_, SIGNAL(TurnOff()), playlist_, SLOT(TurnOffDynamicPlaylist()));
}
Beispiel #5
0
//------------------------------------------------------------------------
bool CProjectile::Init(IGameObject *pGameObject)
{
	SetGameObject(pGameObject);

	g_pGame->GetWeaponSystem()->AddProjectile(GetEntity(), this);

	if (!GetGameObject()->CaptureProfileManager(this))
		return false;

	m_pAmmoParams = g_pGame->GetWeaponSystem()->GetAmmoParams(GetEntity()->GetClass());

	if (0 == (GetEntity()->GetFlags() & (ENTITY_FLAG_CLIENT_ONLY | ENTITY_FLAG_SERVER_ONLY)))
		if (!m_pAmmoParams->predictSpawn)
			if (!GetGameObject()->BindToNetwork())
				return false;

	GetGameObject()->EnablePhysicsEvent(true, eEPE_OnCollisionLogged);

	LoadGeometry();
	Physicalize();

	IEntityRenderProxy *pProxy = static_cast<IEntityRenderProxy *>(GetEntity()->GetProxy(ENTITY_PROXY_RENDER));
	if (pProxy && pProxy->GetRenderNode())
	{
		pProxy->GetRenderNode()->SetViewDistRatio(255);
		pProxy->GetRenderNode()->SetLodRatio(255);
	}

	float lifetime = m_pAmmoParams->lifetime;
	if (lifetime > 0.0f)
		GetEntity()->SetTimer(ePTIMER_LIFETIME, (int)(lifetime*1000.0f));

	float showtime = m_pAmmoParams->showtime;
	if (showtime > 0.0f)
	{
		GetEntity()->SetSlotFlags(0, GetEntity()->GetSlotFlags(0)&(~ENTITY_SLOT_RENDER));
		GetEntity()->SetTimer(ePTIMER_SHOWTIME, (int)(showtime*1000.0f));
	}
	else
		GetEntity()->SetSlotFlags(0, GetEntity()->GetSlotFlags(0)|ENTITY_SLOT_RENDER);

	// Only for bullets
	m_hitPoints = m_pAmmoParams->hitPoints;
	m_hitListener = false;
	if(m_hitPoints>0)
	{
		//Only projectiles with hit points are hit listeners
		g_pGame->GetGameRules()->AddHitListener(this);
		m_hitListener = true;
		m_noBulletHits = m_pAmmoParams->noBulletHits;
	}

	if (m_tracked) // if this is true here, it means m_tracked was serialized from spawn info
	{
		m_tracked=false;
		SetTracked(true);
	}

	return true;
}
/*!
  \brief Get feature by FID

  Modifies next feature id.

  \param nFID feature id

  \return pointer to feature definition or NULL on failure (not found)
*/
IVFKFeature *VFKDataBlockSQLite::GetFeature(GIntBig nFID)
{
    if (m_nFeatureCount < 0) {
        m_poReader->ReadDataRecords(this);
    }

    if (nFID < 1 || nFID > m_nFeatureCount)
        return NULL;

    if( m_bGeometryPerBlock && !m_bGeometry )
    {
        LoadGeometry();
    }

    VFKReaderSQLite *poReader = (VFKReaderSQLite*) m_poReader;

    CPLString osSQL;
    osSQL.Printf("SELECT rowid FROM %s WHERE %s = " CPL_FRMT_GIB,
                 m_pszName, FID_COLUMN, nFID);
    if (EQUAL(m_pszName, "SBP")) {
        osSQL += " AND PORADOVE_CISLO_BODU = 1";
    }
    sqlite3_stmt *hStmt = poReader->PrepareStatement(osSQL.c_str());

    int rowId = -1;
    if (poReader->ExecuteSQL(hStmt) == OGRERR_NONE) {
        rowId = sqlite3_column_int(hStmt, 0);
    }
    sqlite3_finalize(hStmt);

    return GetFeatureByIndex(rowId - 1);
}
Beispiel #7
0
void SAmmoParams::Init(const XmlNodeRef& ammoParamsNode, const IEntityClass* pEntityClass_)
{
	pEntityClass = pEntityClass_;
	fpGeometryName = "";

	if (!ammoParamsNode || !pEntityClass)
	{
		CRY_ASSERT(0);
		return;
	}

	LoadFlagsAndParams(ammoParamsNode);
	LoadPhysics(ammoParamsNode);
	LoadGeometry(ammoParamsNode);
	LoadCollision(ammoParamsNode);
	LoadExplosion(ammoParamsNode);
	LoadFlashbang(ammoParamsNode);
	LoadTrailsAndWhizzes(ammoParamsNode);
	LoadLTagGrenadeParams(ammoParamsNode);
	LoadHomingSwarmParams(ammoParamsNode);
	LoadMikeBulletParams(ammoParamsNode);
	LoadGrenadeParams(ammoParamsNode);
	LoadHomingMissileParams(ammoParamsNode);
	LoadKVoltParams(ammoParamsNode);
	LoadBulletTimeParams(ammoParamsNode);
	LoadLightningBoltParams(ammoParamsNode);
	LoadC4ExplosiveParams(ammoParamsNode);
	LoadHazardParams(ammoParamsNode);
	LoadElectriProjectileParams(ammoParamsNode);
}
/*!
  \brief Get feature by FID

  Modifies next feature id.

  \param nFID feature id

  \return pointer to feature definition or NULL on failure (not found)
*/
IVFKFeature *VFKDataBlockDB::GetFeature(GIntBig nFID)
{
    int rowId;
    CPLString osSQL;
    VFKReaderDB  *poReader;

    if (m_nFeatureCount < 0) {
        m_poReader->ReadDataRecords(this);
    }

    if (nFID < 1 || nFID > m_nFeatureCount)
        return NULL;

    if (m_bGeometryPerBlock && !m_bGeometry) {
        LoadGeometry();
    }

    poReader = (VFKReaderDB*) m_poReader;

    osSQL.Printf("SELECT rowid FROM %s WHERE %s = " CPL_FRMT_GIB,
                 m_pszName, FID_COLUMN, nFID);
    if (EQUAL(m_pszName, "SBP")) {
        osSQL += " AND PORADOVE_CISLO_BODU = 1";
    }
    if (poReader->ExecuteSQL(osSQL.c_str(), rowId) != OGRERR_NONE) {
        rowId = -1; // TODO: solve
    }

    return GetFeatureByIndex(rowId - 1);
}
void FMD3Model::BuildVertexBuffer()
{
	if (mVBuf == nullptr)
	{
		LoadGeometry();

		unsigned int vbufsize = 0;
		unsigned int ibufsize = 0;

		for (int i = 0; i < numSurfaces; i++)
		{
			MD3Surface * surf = &surfaces[i];
			vbufsize += numFrames * surf->numVertices;
			ibufsize += 3 * surf->numTriangles;
		}

		mVBuf = new FModelVertexBuffer(true, numFrames == 1);
		FModelVertex *vertptr = mVBuf->LockVertexBuffer(vbufsize);
		unsigned int *indxptr = mVBuf->LockIndexBuffer(ibufsize);

		assert(vertptr != nullptr && indxptr != nullptr);

		unsigned int vindex = 0, iindex = 0;

		for (int i = 0; i < numSurfaces; i++)
		{
			MD3Surface * surf = &surfaces[i];

			surf->vindex = vindex;
			surf->iindex = iindex;
			for (int j = 0; j < numFrames * surf->numVertices; j++)
			{
				MD3Vertex* vert = surf->vertices + j;

				FModelVertex *bvert = &vertptr[vindex++];

				int tc = j % surf->numVertices;
				bvert->Set(vert->x, vert->z, vert->y, surf->texcoords[tc].s, surf->texcoords[tc].t);
				bvert->SetNormal(vert->nx, vert->nz, vert->ny);
			}

			for (int k = 0; k < surf->numTriangles; k++)
			{
				for (int l = 0; l < 3; l++)
				{
					indxptr[iindex++] = surf->tris[k].VertIndex[l];
				}
			}
			surf->UnloadGeometry();
		}
		mVBuf->UnlockVertexBuffer();
		mVBuf->UnlockIndexBuffer();
	}
}
Beispiel #10
0
/*!
  \brief Get last feature

  \return pointer to VFKFeature instance
  \return NULL on error
*/
IVFKFeature *IVFKDataBlock::GetLastFeature()
{
    if (m_nFeatureCount < 0) {
        m_poReader->ReadDataRecords(this);
    }
    
    if (m_bGeometryPerBlock && !m_bGeometry) {
        LoadGeometry();
    }
    
    if (m_nFeatureCount < 1)
        return NULL;
    
    return m_papoFeature[m_nFeatureCount-1];
}
Beispiel #11
0
void TSRModel::LoadSkinnedGeometry( TSRModelSkinnedGeometry* pGeometry, TSRFileStream* _pFptr )
{
    /// read regular geometry data first
    LoadGeometry( pGeometry, _pFptr );
    fread( &pGeometry->m_BindShapeTransform, sizeof( TSRMatrix4 ), 1, _pFptr );
    fread( &pGeometry->m_uiBoneTransformsCount, sizeof( unsigned int ), 1, _pFptr );
    fread( &pGeometry->m_uiFirstBoneIndex, sizeof( unsigned int ), 1, _pFptr );
    fread( &pGeometry->m_uiBonesRange, sizeof( unsigned int ), 1, _pFptr );
    if ( pGeometry->m_uiBoneTransformsCount > 0 )
    {
        pGeometry->m_pBoneTransforms = new TSRMatrix4[ pGeometry->m_uiBoneTransformsCount ];
        pGeometry->m_pBonesIndices   = new unsigned int[ pGeometry->m_uiBoneTransformsCount ];
		fread( pGeometry->m_pBoneTransforms, sizeof( TSRMatrix4 ), pGeometry->m_uiBoneTransformsCount, _pFptr );
		fread( pGeometry->m_pBonesIndices, sizeof( unsigned int ), pGeometry->m_uiBoneTransformsCount, _pFptr );
    }
}
Beispiel #12
0
EntityNode* SceneLoader::LoadEntityNode(QDomElement element)
{
  if (element.nodeName() != QString ("node") ||
      QString::compare(element.attribute("type"), "entity", Qt::CaseInsensitive) != 0)
    {
      printf ("ceXMLDataLoader::LoadEntityNode: Illegal data format: '%s' != 'entitynode'\n", element.nodeName().toStdString().c_str()); fflush (stdout);
      return 0;
    }

  EntityNode* entity = new EntityNode();
  QString  name = element.attribute("name");
  if (!name.isNull())
    {
      entity->SetName(name.toStdString());
    }


  QDomElement geometryElement = element.firstChildElement("geometry");
  if (!geometryElement.isNull())
    {
      Geometry* geom = LoadGeometry(geometryElement);
      if (geom)
        {
          _geometryIdx++;
        }
      entity->SetGeometry(geom);
    }

  QDomElement shadowElement = element.firstChildElement("shadow");
  if (!shadowElement.isNull())
    {
      LoadShadow (entity, shadowElement);
    }
  entity->SetCastShadow(true);

  QDomElement transformElement = element.firstChildElement("transformation");
  if (!transformElement.isNull())
    {
      QDomElement matrixElement = transformElement.firstChildElement("matrix");
      entity->SetMatrix(LoadMatrix4f(matrixElement));
      entity->FinishTransformation(false);
    }

  return entity;
}
Beispiel #13
0
void QtPosSaver::Attach(QWidget *widget, const QString &name)
{
	attachedWidget = widget;

	if(NULL != attachedWidget)
	{
		if(name.isEmpty())
		{
			attachedWidgetName = attachedWidget->objectName();
		}
		else
		{
			attachedWidgetName = name;
		}

		LoadGeometry(attachedWidget);
	}
}
Beispiel #14
0
/*!
  \brief Get previous feature

  \return pointer to VFKFeature instance
  \return NULL on error
*/
IVFKFeature *IVFKDataBlock::GetPreviousFeature()
{
    if (m_nFeatureCount < 0) {
        m_poReader->ReadDataRecords(this);
    }
    
    if (m_bGeometryPerBlock && !m_bGeometry) {
       LoadGeometry();
    }

    if (m_iNextFeature < 0)
        ResetReading();
    
    if (m_iNextFeature < 0 || m_iNextFeature >= m_nFeatureCount)
        return NULL;
    
    return m_papoFeature[m_iNextFeature--];
}
Beispiel #15
0
//------------------------------------------------------------------------
bool CProjectile::Init(IGameObject *pGameObject)
{
	SetGameObject(pGameObject);

	g_pGame->GetWeaponSystem()->AddProjectile(GetEntity(), this);

	if(!GetGameObject()->CaptureProfileManager(this))
		return false;

	m_pAmmoParams = g_pGame->GetWeaponSystem()->GetAmmoParams(GetEntity()->GetClass());

	if(0 == (GetEntity()->GetFlags() & (ENTITY_FLAG_CLIENT_ONLY | ENTITY_FLAG_SERVER_ONLY)))
		if(!m_pAmmoParams->predictSpawn)
			if(!GetGameObject()->BindToNetwork())
				return false;

	LoadGeometry();
	Physicalize();

	IEntityRenderProxy *pProxy = static_cast<IEntityRenderProxy *>(GetEntity()->GetProxy(ENTITY_PROXY_RENDER));

	if(pProxy && pProxy->GetRenderNode())
	{
		pProxy->GetRenderNode()->SetViewDistRatio(255);
		pProxy->GetRenderNode()->SetLodRatio(255);
	}

	float lifetime = m_pAmmoParams->lifetime;

	if(lifetime > 0.0f)
		GetEntity()->SetTimer(ePTIMER_LIFETIME, (int)(lifetime*1000.0f));

	float showtime = m_pAmmoParams->showtime;

	if(showtime > 0.0f)
	{
		GetEntity()->SetSlotFlags(0, GetEntity()->GetSlotFlags(0)&(~ENTITY_SLOT_RENDER));
		GetEntity()->SetTimer(ePTIMER_SHOWTIME, (int)(showtime*1000.0f));
	}
	else
		GetEntity()->SetSlotFlags(0, GetEntity()->GetSlotFlags(0)|ENTITY_SLOT_RENDER);

	return true;
}
bool OBJLoaderApp::StartUp()
{

	if (!glfwInit())
	{
		return false;
	}

	mWindow = glfwCreateWindow(WINDOW_WIDTH, WINDOW_HEIGHT, WINDOW_TITLE, nullptr, nullptr);

	if (nullptr == mWindow)
	{
		glfwTerminate();
		return false;
	}

	glfwMakeContextCurrent(mWindow);

	if (ogl_LoadFunctions() == ogl_LOAD_FAILED)
	{
		glfwDestroyWindow(mWindow);
		glfwTerminate();
		return false;
	}

	//load model file
	LoadGeometry(OBJ_MODEL_FILE_PATH);
	//LoadGeometry(FBX_MODEL_FILE_PATH);

	InitCamera();

	// create shaders
	const char* vsSource = "#version 330\n \
							layout(location=0) in vec4 Position; \
							layout(location=1) in vec4 Colour; \
							out vec4 vColour; \
							uniform mat4 ProjectionView; \
							void main() \
							{ \
								vColour = Colour; \
								gl_Position = ProjectionView * Position;\
							}";
void SAmmoParams::Init(const IItemParamsNode *pItemParams_, const IEntityClass *pEntityClass_)
{
	pItemParams = pItemParams_;
	pEntityClass = pEntityClass_;
	fpGeometryName = "";

	if (!pItemParams || !pEntityClass)
	{
		assert(0);
		return;
	}

	pItemParams->AddRef();
	LoadFlagsAndParams();
	LoadPhysics();
	LoadGeometry();
	LoadScaledEffect();
	LoadCollision();
	LoadExplosion();
	LoadFlashbang();
	LoadTrailsAndWhizzes();
}
Beispiel #18
0
bool World::Load()
{
	conf.ParseConfigFile("Data/ConfigFile.txt"); // load configuration file
	
	// Order of loading: Lights -> Textures -> Shaders -> Geometry -> Particles -> Seasons

	LoadLights();
	LoadTextures();
	LoadSounds();
	LoadShaders();
	LoadGeometry();
	LoadParticles();
	
	SetupSeasons();
	
	//glLightModelfv(GL_LIGHT_MODEL_AMBIENT, Color::BLACK.GetVec());
	glLightModelfv(GL_LIGHT_MODEL_AMBIENT, Color::WHITE.GetVec());

	SetLightingMode(Spotlights);

	return true;
};
Beispiel #19
0
void FUE1Model::BuildVertexBuffer( FModelRenderer *renderer )
{
	if (GetVertexBuffer(renderer))
		return;
	if ( !mDataLoaded )
		LoadGeometry();
	int vsize = 0;
	for ( int i=0; i<numGroups; i++ )
		vsize += groups[i].numPolys*3;
	vsize *= numFrames;
	auto vbuf = renderer->CreateVertexBuffer(false,numFrames==1);
	SetVertexBuffer(renderer, vbuf);
	FModelVertex *vptr = vbuf->LockVertexBuffer(vsize);
	int vidx = 0;
	for ( int i=0; i<numFrames; i++ )
	{
		for ( int j=0; j<numGroups; j++ )
		{
			for ( int k=0; k<groups[j].numPolys; k++ )
			{
				for ( int l=0; l<3; l++ )
				{
					UE1Vertex V = verts[polys[groups[j].P[k]].V[l]+i*numVerts];
					FVector2 C = polys[groups[j].P[k]].C[l];
					FModelVertex *vert = &vptr[vidx++];
					vert->Set(V.Pos.X,V.Pos.Y,V.Pos.Z,C.X,C.Y);
					if ( groups[j].type&PT_Curvy )	// use facet normal
					{
						vert->SetNormal(polys[groups[j].P[k]].Normals[i].X,
							polys[groups[j].P[k]].Normals[i].Y,
							polys[groups[j].P[k]].Normals[i].Z);
					}
					else vert->SetNormal(V.Normal.X,V.Normal.Y,V.Normal.Z);
				}
			}
		}
	}
	vbuf->UnlockVertexBuffer();
}
Beispiel #20
0
Geometry::Geometry(string &file, AABB *aabb) {
  LoadGeometry(file, aabb);
}
Beispiel #21
0
void TSRModel::LoadModel( TSRModel* pModel, const char* _pFileName )
{
    /// new : if this is a .obj file, we create a dummy model  around its mesh
    string strFilename = _pFileName;

    string strExtension = strFilename.substr( strlen( _pFileName ) - 3, strlen( _pFileName ) );

    if ( strExtension == "obj" )
    {
        LoadFromOBJ( pModel, _pFileName );
        return;
    }

	TSRFileStream* fptr = TSRFileSystem::OpenFileStream( _pFileName, "rb" );

	// first read the version
	unsigned int uiVersion = 0;

	fread( &uiVersion, sizeof( unsigned int ), 1, fptr );

	// read geometries
	fread( &pModel->m_uiGeometriesCount, sizeof( unsigned int ), 1, fptr );
	if ( pModel->m_uiGeometriesCount > 0 )
	{
		pModel->m_pGeometries = new TSRModelGeometry[ pModel->m_uiGeometriesCount ];
	}
	for ( unsigned int i = 0; i < pModel->m_uiGeometriesCount; i++ )
	{
		LoadGeometry( pModel->m_pGeometries + i, fptr );
	}

	/// read skinned geometries
	fread( &pModel->m_uiSkinnedGeometriesCount, sizeof( unsigned int ), 1, fptr );
	if ( pModel->m_uiSkinnedGeometriesCount )
	{
		pModel->m_pSkinnedGeometries = new TSRModelSkinnedGeometry[ pModel->m_uiSkinnedGeometriesCount ];
	}
	for ( unsigned int i = 0; i < pModel->m_uiSkinnedGeometriesCount; i++ )
	{
		LoadSkinnedGeometry( pModel->m_pSkinnedGeometries + i, fptr );
	}


	/// read effects 
	fread( &pModel->m_uiEffectsCount, sizeof( unsigned int ), 1, fptr );

	if ( pModel->m_uiEffectsCount > 0 )
	{
		pModel->m_ppEffects = new TSREffect* [ pModel->m_uiEffectsCount ];
		for ( unsigned int i = 0; i < pModel->m_uiEffectsCount; i++ )
		{
			char effectName[ 16 ];
			fread( effectName, 16, 1, fptr );
			pModel->m_ppEffects[ i ] = EffectManager()->Aquire( effectName );
		}
	}

	/// read textures
	fread( &pModel->m_uiTexturesCount, sizeof( unsigned int ), 1, fptr );
	pModel->m_uiTexturesCount += 2;
	pModel->m_pModelTextures = new TSRModelTexture[ pModel->m_uiTexturesCount ];
	pModel->m_ppTextures = new TSRTexture*[ pModel->m_uiTexturesCount ];


	if ( pModel->m_uiTexturesCount > 2 )
	{
		fread( &pModel->m_pModelTextures[ 2 ], sizeof( TSRModelTexture ), pModel->m_uiTexturesCount - 2, fptr );
	}


	/// read materials
	fread( &pModel->m_uiMaterialsCount, sizeof( unsigned int ), 1, fptr );
	
	// always add one default material 
	pModel->m_pMaterials = new TSRModelMaterial[ pModel->m_uiMaterialsCount ];
	if ( pModel->m_uiMaterialsCount > 0 )
	{
		fread( pModel->m_pMaterials, sizeof( TSRModelMaterial ), pModel->m_uiMaterialsCount, fptr );
	}

	snprintf( pModel->m_RootNode.m_Name, 32, "RootNode" );

	// read the root node transform
	fread( &pModel->m_RootNode.m_LocalTransform, sizeof( TSRMatrix4 ), 1, fptr );

	// read number of nodes under root
	fread( &pModel->m_RootNode.m_uiChildrenCount, sizeof( unsigned int ), 1, fptr );

	// allocate them
	pModel->m_RootNode.m_pChildren = new TSRModelNode[ pModel->m_RootNode.m_uiChildrenCount ];
	for ( unsigned int i = 0; i < pModel->m_RootNode.m_uiChildrenCount; i++ )
	{
		ReadModelNodesRec( pModel->m_RootNode.m_pChildren + i, fptr );
	}

	// read the whole model aabb..
	fread( &pModel->m_BoundBox, sizeof( TSRBBox ), 1, fptr );

	// read number of render nodes.
	fread( &pModel->m_uiRenderNodesCount, sizeof( unsigned int ), 1, fptr );

	if ( pModel->m_uiRenderNodesCount > 0 )
	{
		pModel->m_pRenderNodes = new TSRModelRenderNode[ pModel->m_uiRenderNodesCount ];
	}

	for ( unsigned int i = 0; i < pModel->m_uiRenderNodesCount; i++ )
	{
		// allocate a new render node
		TSRModelRenderNode*  pNewRenderNode = pModel->m_pRenderNodes + i ;

		// read it without the trailing pointer (world transform and the number of geometry instances)
		fread( pNewRenderNode, sizeof( TSRMatrix4 ) + sizeof( int ), 1, fptr );

		// allocate  geometry indices
		pNewRenderNode->m_pGeometriesIndices = new int[ pNewRenderNode->m_uiGeometriesCount ];

		// read them
		fread( pNewRenderNode->m_pGeometriesIndices, pNewRenderNode->m_uiGeometriesCount * sizeof( int ), 1, fptr );
	}

	/// read skinned nodes
	fread( &pModel->m_uiSkinnedNodesCount, sizeof( unsigned int ), 1, fptr );

	if ( pModel->m_uiSkinnedNodesCount >  0 )
	{
		pModel->m_pSkinnedNodes = new TSRModelRenderNode[ pModel->m_uiSkinnedNodesCount ];
	}

	for ( unsigned int i = 0; i < pModel->m_uiSkinnedNodesCount; i++ )
	{
		// allocate a new skinned node
		TSRModelRenderNode*  pNewSkinnedNode = pModel->m_pSkinnedNodes + i ;

		// read it without the trailing pointer (world transform and the number of geometry instances)
		fread( pNewSkinnedNode, sizeof( TSRMatrix4 ) + sizeof( int ), 1, fptr );

		// allocate  geometry indices
		pNewSkinnedNode->m_pGeometriesIndices = new int[ pNewSkinnedNode->m_uiGeometriesCount ];

		// read them
		fread( pNewSkinnedNode->m_pGeometriesIndices, pNewSkinnedNode->m_uiGeometriesCount * sizeof( int ), 1, fptr );
	}

	// read the animations
	fread( &pModel->m_AnimationsCount, sizeof( unsigned int ), 1, fptr );

	// allocate the animations
	if ( pModel->m_AnimationsCount > 0 )
	{
		pModel->m_pAnimations = new TSRModelAnimation[ pModel->m_AnimationsCount ];

		for ( unsigned int i = 0; i < pModel->m_AnimationsCount; i++ )
		{
			LoadAnimation( pModel->m_pAnimations + i, fptr );
		}
	}

	// read lights 
	fread( &pModel->m_uiLightsCount, sizeof( unsigned int ), 1, fptr );

	// allocate lights and read them in one go..
	if ( pModel->m_uiLightsCount > 0 )
	{
		pModel->m_pLights = new TSRModelLight[ pModel->m_uiLightsCount ];
		fread( pModel->m_pLights, sizeof( TSRModelLight ), pModel->m_uiLightsCount, fptr );
	}

	/// read number of light nodes
	fread( &pModel->m_uiLightNodesCount, sizeof( unsigned int ), 1, fptr );

	if ( pModel->m_uiLightNodesCount > 0 )
	{
		pModel->m_pLightNodesIndices = new unsigned int[ pModel->m_uiLightNodesCount ];
		fread( pModel->m_pLightNodesIndices, sizeof( unsigned int ), pModel->m_uiLightNodesCount, fptr );
	}
	/// read number of bones and create the skeleton matrix data 
	fread( &pModel->m_uiBonesCount, sizeof( unsigned int ), 1, fptr );

	fclose( fptr );


    /// white and default normal are always first 2 textures..
    pModel->m_ppTextures[ 0 ] = TextureManager()->GetWhite();
    pModel->m_ppTextures[ 1 ] = TextureManager()->GetDefaultNormal();

    // change the current working directory according to the file's path, so textures can be read properly
    string fullPath = _pFileName;
    int iSlashPosition = ( int ) fullPath.find_last_of( "/" );
    string textureFileNameHeader = "";

	if ( iSlashPosition == -1 )
	{
		iSlashPosition = ( int ) fullPath.find_last_of( "\\" );
	}

    if ( iSlashPosition > -1 )
    {
        textureFileNameHeader = fullPath.substr( 0, iSlashPosition + 1 );
    }

    string textureFileName;

    // change directory if needed before getting the textures..
    for ( unsigned int i = 2; i < pModel->m_uiTexturesCount; i++ )
    {
        textureFileName = textureFileNameHeader + pModel->m_pModelTextures[ i ].m_Name;
        pModel->m_ppTextures[ i ] = TextureManager()->Aquire( textureFileName.c_str() );
    }
}
void XMLReader::LoadSceneFromFile(QFile &file, const QStringRef &local_path, Scene &scene, Integrator* &integrator)
{
    if(file.open(QIODevice::ReadOnly))
    {
        QXmlStreamReader xml_reader;
        xml_reader.setDevice(&file);
        QMap<QString, QList<Geometry*>> material_to_geometry_map;
        QMap<QString, QList<Material*>> bxdf_to_material_map;//Key is the bxdf's name
        while(!xml_reader.isEndDocument())
        {
            xml_reader.readNext();
            if(xml_reader.isStartElement())
            {
                //Get the tag name
                QString tag(xml_reader.name().toString());
                if(QString::compare(tag, QString("camera")) == 0)
                {
                    scene.SetCamera(LoadCamera(xml_reader));
                }
                else if(QString::compare(tag, QString("geometry")) == 0)
                {
                    Geometry* geometry = LoadGeometry(xml_reader, material_to_geometry_map, local_path);
                    if(geometry == NULL)
                    {
                        return;
                    }
                    scene.objects.append(geometry);
                }
                else if(QString::compare(tag, QString("material")) == 0)
                {
                    Material* material = LoadMaterial(xml_reader, local_path, bxdf_to_material_map);
                    if(material == NULL)
                    {
                        return;
                    }
                    scene.materials.append(material);
                }
                else if(QString::compare(tag, QString("bxdf")) == 0)
                {
                    BxDF* bxdf = LoadBxDF(xml_reader);
                    if(bxdf == NULL)
                    {
                        return;
                    }
                    scene.bxdfs.append(bxdf);
                }
                else if(QString::compare(tag, QString("integrator")) == 0)
                {
                    integrator = LoadIntegrator(xml_reader);
                }
                else if(QString::compare(tag, QString("pixelSampleLength"), Qt::CaseInsensitive) == 0)
                {
                    scene.sqrt_samples = LoadPixelSamples(xml_reader);
                }
            }
        }
        //Associate the materials in the XML file with the geometries that use those materials.
        for(int i = 0; i < scene.materials.size(); i++)
        {
            QList<Geometry*> l = material_to_geometry_map.value(scene.materials[i]->name);
            for(int j = 0; j < l.size(); j++)
            {
                l[j]->SetMaterial(scene.materials[i]);
            }
        }

        for(int i = 0; i < scene.bxdfs.size(); i++)
        {
            QList<Material*> l = bxdf_to_material_map.value(scene.bxdfs[i]->name);
            for(int j = 0; j < l.size(); j++)
            {
                l[j]->bxdfs.append(scene.bxdfs[i]);
            }
        }

        //Copy emissive geometry from the list of objects to the list of lights
        QList<Geometry*> to_lights;
        for(Geometry *g : scene.objects)
        {
            g->create();
            if(g->material->is_light_source)
            {
                to_lights.append(g);
            }
            g->ComputeArea();
        }
        for(Geometry *g : to_lights)
        {
            scene.lights.append(g);
        }
        file.close();
    }
}
Beispiel #23
0
int main(int argc, char *argv[]){

    if(!glfwInit()){
        throw std::runtime_error("glfwInit failed");
    }
    glfwOpenWindowHint(GLFW_FSAA_SAMPLES, 4);
    glfwOpenWindowHint(0, GLFW_OPENGL_CORE_PROFILE);
    glfwOpenWindowHint(GLFW_OPENGL_VERSION_MAJOR, 3);
    glfwOpenWindowHint(GLFW_OPENGL_VERSION_MINOR, 1);
    glfwOpenWindowHint(GLFW_WINDOW_NO_RESIZE, GL_TRUE);
    if(!glfwOpenWindow(800, 600, 0, 0, 0, 0, 32, 0, GLFW_WINDOW)){
        throw std::runtime_error("glfwOpenWindow failed. does this hardware work with 3.1");
    }

    glewExperimental = GL_TRUE;
    if(glewInit() != GLEW_OK){
        throw std::runtime_error("glewInit failed");
    }

    if(!GLEW_VERSION_3_1){
        throw std::runtime_error("OpenGL 3.1 API is not available");
    }

    LoadGeometry();
    LoadTexture();
    PrepVertexUniforms();
    init_font();
    printf("All data prepped\n");

    camera.setPosition(glm::vec3(0,0,8));
    camera.setViewportAspectRatio(screenwidth/screenheight);

    light.position = camera.position();
    light.intensities = glm::vec3(1,1,1);

    glfwDisable(GLFW_MOUSE_CURSOR);
    glfwSetMousePos(0, 0);
    glfwSetMouseWheel(0);

    printf("camera prepped\n");

    //turn on depth test so things dont look stupid
    glEnable(GL_DEPTH_TEST);
    glDepthFunc(GL_LESS);
    glEnable(GL_CULL_FACE);

    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

    printf("starting main loop\n");
    while(glfwGetWindowParam(GLFW_OPENED)){

        update();
        display();

        //check for errors
        GLenum error = glGetError();
        if(error != GL_NO_ERROR){
            glPrintError();
        }

        //esc == close
        if(glfwGetKey(GLFW_KEY_ESC)){
            glfwCloseWindow();
        }
    }
    glfwTerminate();

    return 0;

}
Beispiel #24
0
void USwFMOD::Update( FPointRegion Region, FCoords& Coords )
{
	guard(USwFMOD::Update);
	FMOD_RESULT result;
	//SWF_LOG( NAME_DevSound, TEXT("%s >> %s :: [%s],[%s]"), SWF_PLOG, *ToStr(Region), *ToStr(Coords) );

	if( !Viewport || !Viewport->IsValid() || !Viewport->Actor || !Viewport->Actor->IsValid() )
		return;

	// Load geometry
	if( bOcclusion )
	{
		static ULevel* level = NULL;
		if( Viewport->Actor->GetLevel() != level )
		{
			level = Viewport->Actor->GetLevel();
			LoadGeometry();
		}
	}

	// Time passes...
	DOUBLE DeltaTime = appSeconds() - LastTime;
	LastTime += DeltaTime;
	DeltaTime = Clamp( DeltaTime, 0.0, 1.0 );

	// Get viewactor
	AActor* ViewActor = Viewport->Actor->ViewTarget ? Viewport->Actor->ViewTarget : Viewport->Actor;
	
	// Is viewport realtime ?
	UBOOL Realtime = Viewport->IsRealtime() && Viewport->Actor->Level->Pauser == TEXT("");
	
	// Default viewport coords
	FVector location = FVector(0,0,0);
	FVector velocity = FVector(0,0,0);
	FVector forward = FVector(1,0,0);
	FVector up = FVector(0,0,1);


	//
	// Update listener
	//
	guard(USwFMODAudio::Update::UpdateListener);

	// Use ViewActor coords
	FCoords coords = GMath.UnitCoords / ViewActor->Rotation;;
	coords.Origin = ViewActor->Location;

	// Set viewport coords
	location = coords.Origin;
	velocity = ViewActor->Velocity;
	forward = coords.XAxis;
	up = coords.ZAxis;

	// verify
	SWF_VERIFY_FVECTOR(location);
	SWF_VERIFY_FVECTOR(velocity);
	SWF_VERIFY_FVECTOR_NORMAL(forward);
	SWF_VERIFY_FVECTOR_NORMAL(up);

	// Default listener coords
	FMOD_VECTOR fm_pos = {0,0,0};
	FMOD_VECTOR fm_vel = {0,0,0};
	FMOD_VECTOR fm_fwd = {0,0,1};
	FMOD_VECTOR fm_up  = {0,1,0};

	// Set listener coords
	fm_pos = ToFMODVector(location);
	fm_vel = ToFMODVector(velocity);
	fm_fwd = ToFMODNormal(forward);
	fm_up = ToFMODNormal(up);

	// verify
	SWF_VERIFY_FMODVECTOR(fm_pos);
	SWF_VERIFY_FMODVECTOR(fm_vel);
	SWF_VERIFY_FMODVECTOR_NORMAL(fm_fwd);
	SWF_VERIFY_FMODVECTOR_NORMAL(fm_up);

	// Update
	SWF_FMOD_CALL( System->set3DListenerAttributes( 0, &fm_pos, &fm_vel, &fm_fwd, &fm_up ) );
	unguard;


	//
	// Zone effects
	//
	guard(USwFMODAudio::Update::UpdateZone);

	/*// Default zone properties
	UBOOL bWaterZone = 0;
	UBOOL bReverbZone = 0;
	UBOOL bRaytraceReverb = 0;
	BYTE MasterGain = 100;
	INT CutoffHz = 6000;
	BYTE Delay[6] = {20,34,0,0,0,0};
	BYTE Gain[6] = {150,70,0,0,0,0};

	// Get zone properties
	if( Region.Zone && Region.Zone->IsValid() )
	{
		bWaterZone = Region.Zone->bWaterZone;
		bReverbZone = Region.Zone->bReverbZone;
		bRaytraceReverb = Region.Zone->bRaytraceReverb;
		MasterGain = Region.Zone->MasterGain;
		CutoffHz = Region.Zone->CutoffHz;
		appMemcpy(Delay, Region.Zone->Delay, 6*sizeof(BYTE));
		appMemcpy(Gain, Region.Zone->Gain, 6*sizeof(BYTE));
	}*/
	unguard;



	//
	// Update sounds.
	//
	guard(USwFMODAudio::Update::UpdateSounds);

	// Iterate through all channels
	for( FSwChannelEnumerator it(System); it; ++it )
	{
		FMOD::Channel* channel = *it;
		if( !IsChannelValid(channel) )
			continue;

		// Channel data
		FMOD::Sound* sample = GetChannelSample(channel);
		if( !sample )
			continue;

		UObject* object = GetSampleObject(sample);
		if( !object )
			continue;
		USound* sound = Cast<USound>(object);

		FSwSoundId id = GetChannelId(channel);
		AActor* actor = id.GetActor();

		FMOD_MODE fmode;
		SWF_FMOD_CALL( channel->getMode(&fmode) );
		UBOOL bIs3D = HasFlag(fmode,FMOD_3D);

		// Sample defaults
		FLOAT deffrequency;
		FLOAT defvolume;
		FLOAT defpanning;
		INT defpriority;
		SWF_FMOD_CALL( sample->getDefaults( &deffrequency, &defvolume, &defpanning, &defpriority ) );
	

		if( sound )
		{
			if( actor && actor->IsValid() )
			{
				// Ambient sounds
				if( id.GetSlot() == SLOT_Ambient )
				{
					if(	actor->AmbientSound != sound
					||	FDist(location, actor->Location) > actor->WorldSoundRadius() + AmbientHysteresis
					||  !Realtime )
					{
						// Stop ambient sound
						//SWF_LOG( NAME_DevSound, TEXT("%s -- %s :: Ambient OUT [%d]"), SWF_PLOG, *ToStr(id) );
						SWF_FMOD_CALL( channel->setUserData(NULL) );
						SWF_FMOD_CALL( channel->stop() );
						continue;
					}
					else
					{
						// Update ambient sound properties.
						FLOAT volume = actor->SoundVolume / 255.0f;
						FLOAT frequency = (actor->SoundPitch / 64.0f) * deffrequency;

						SWF_VERIFY_FLOAT(volume);
						SWF_VERIFY_FLOAT(frequency);

						SWF_FMOD_CALL( channel->setVolume( volume ) );
						SWF_FMOD_CALL( channel->setFrequency( frequency ) );

						if( bIs3D )
						{
							// Update 3D sound properties
							FLOAT mindist = ToFMODFloat(DistanceMin);
							FLOAT radius = ToFMODFloat( actor->WorldSoundRadius() );
							TSwSortMinMax( mindist, radius );

							SWF_VERIFY_FLOAT(radius);
							SWF_VERIFY_FLOAT(mindist);

							SWF_FMOD_CALL( channel->set3DMinMaxDistance( mindist, radius ) );
						}
					}
				}

				if( bIs3D )
				{
					// Update 3D sound properties
					FMOD_VECTOR snd_pos = ToFMODVector(actor->Location);
					FMOD_VECTOR snd_vel = ToFMODVector(actor->Velocity);
			
					SWF_VERIFY_FMODVECTOR(snd_pos);							
					SWF_VERIFY_FMODVECTOR(snd_vel);

					SWF_FMOD_CALL( channel->set3DAttributes(&snd_pos, &snd_vel) );
				}
			}
		}
	}
	unguard;


	//
	// Play ambient sounds
	//
	if( Realtime )
	{
		guard(USwFMODAudio::Update::PlayAmbient);
		for( INT i=0; i<Viewport->Actor->GetLevel()->Actors.Num(); ++i )
		{
			AActor* Actor = Viewport->Actor->GetLevel()->Actors(i);
			if(	Actor
			&&	Actor->AmbientSound
			&&	FDist(location, Actor->Location) <= Actor->WorldSoundRadius() )
			{
				FSwSoundId ambientid = FSwSoundId(Actor,SLOT_Ambient,0);
				//SWF_LOG( NAME_DevSound, TEXT("%s -- %s :: Ambient TEST IN [%s]"), SWF_PLOG, *ToStr(ambientid) );

				// Find this sound in currently playing ones
				FMOD::Channel* ambientchannel = NULL;
				for( FSwChannelEnumerator it(System,AmbientChannels); it; ++it )
				{
					FMOD::Channel* channel = *it;
					if( IsChannelValid(channel) && GetChannelId(channel) == ambientid )
					{
						//SWF_LOG( NAME_DevSound, TEXT("%s -- %s :: Ambient FOUND IN [%s]"), SWF_PLOG, *ToStr(GetChannelId(channel)) );
						ambientchannel = channel;
						break;
					}
				}

				// If not found play ambient
				if( !ambientchannel )
				{
					//SWF_LOG( NAME_DevSound, TEXT("%s -- %s :: Ambient PLAY IN [%s][%s]"), SWF_PLOG, *ToStr(ambientid), *ToStr(Actor->AmbientSound) );
					PlaySound( Actor, ambientid.GetId(), Actor->AmbientSound, Actor->Location, Actor->SoundVolume/255.0f, Actor->WorldSoundRadius(), Actor->SoundPitch/64.0f );
				}
			}
		}
		unguard;
	}
	

	//
	// Music
	//
	guard(UpdateMusic)

/*	REQUIREMENTS

	SongSection is updated at realtime by audio sys
	MTRAN_Fade* only fade out, not in
	music changes caused by transition only
	ttransition reset on change
	MTRAN_None = don't change
	MTRAN_Instant = instant change
	MTRAN_Segue = seamless?
	MTRAN_Fade = 1s fade
	MTRAN_FastFade = 1/3s fade
	MTRAN_SlowFade = 5s fade
*/
	// find music channel
	FMOD::Channel* musicchannel = NULL;
	for( FSwChannelEnumerator it(System,MusicChannels); it; ++it )
	{
		FMOD::Channel* channel = *it;
		if( !IsChannelValid(channel) )
			continue;

		if( !musicchannel )
		{
			musicchannel = channel;
		}
		else
		{
			// there can be only one music
			SWF_LOG( NAME_DevSound, TEXT("%s :: %s :: StopMusic %s"), SWF_PLOG, *PrintChannel(channel) );
			SWF_FMOD_CALL( channel->setUserData(NULL) );
			SWF_FMOD_CALL( channel->stop() );
		}
	}

	if( Viewport->Actor->Transition != MTRAN_None )
	{
		// init fading
		if( MusicFade < 0 )
		{
			SWF_LOG( NAME_DevSound, TEXT("%s :: %s :: Music transition %s S:%s T:%s "), SWF_PLOG
				, *ToStr(Viewport->Actor->Song)
				, *ToStr(Viewport->Actor->SongSection)
				, *ToStr(Viewport->Actor->Transition));

			switch( Viewport->Actor->Transition )
			{
				case MTRAN_Instant:		MusicFadeTime = -1.0f;	break;	// Instant
				case MTRAN_Segue:		MusicFadeTime = -1.0f;			// Instant precached
					if( Viewport->Actor->Song && !Viewport->Actor->Song->Handle )
						RegisterMusic(Viewport->Actor->Song);
					break;
				case MTRAN_Fade:		MusicFadeTime = 1.0f;	break;	// 1s fadeout
				case MTRAN_FastFade:	MusicFadeTime = 0.33f;	break;	// 1/3s fadeout
				case MTRAN_SlowFade:	MusicFadeTime = 5.0f;	break;	// 5s fadeout
				default:				MusicFadeTime = -1.0f;	break;	// Unknown,instant
					
			}
			MusicFade = MusicFadeTime;
		}

		// deduct delta
		MusicFade -= DeltaTime;
		//SWF_LOG( NAME_DevSound, TEXT("%s << %s :: MusicFade %s %s"), SWF_PLOG, *ToStr(MusicFade), *ToStr(MusicFadeTime) );

		if( MusicFade > 0 )
		{
			// fade volume
			if( musicchannel && MusicFadeTime > 0 )
			{
				SWF_FMOD_CALL( musicchannel->setVolume( MusicFade / MusicFadeTime) );
			}
		}
		else
		{
			// play new
			MusicFade = -1;
			Viewport->Actor->Transition = MTRAN_None;
			PlayMusic( Viewport->Actor->Song, musicchannel, Viewport->Actor->SongSection, Viewport->Actor->CdTrack, static_cast<EMusicTransition>(Viewport->Actor->Transition) );
		}
	}
	else
	{
		// Update section
		if( musicchannel )
		{
			// update section
			// FIXME:: getPosition doesn't work with volume 0 (virtual?)
			UINT sec = 0;
			result = musicchannel->getPosition(&sec,FMOD_TIMEUNIT_MODORDER);
			if( result == FMOD_OK )
			{
				Viewport->Actor->SongSection = sec;
			}

			// Update position
			if( IsChannelValid(musicchannel) )
			{
				UINT row = 0;
				result = musicchannel->getPosition(&row,FMOD_TIMEUNIT_MODROW);
				if( result == FMOD_OK )
				{
					// IT/MOD/XM
					UINT pattern = 0;
					result = musicchannel->getPosition(&pattern,FMOD_TIMEUNIT_MODPATTERN);
					if( result == FMOD_OK )
					{
						MusicPositions(Viewport->Actor->SongSection).row = row;
						MusicPositions(Viewport->Actor->SongSection).pattern = pattern;
					}
				}
				else
				{
					// MPEG/OGG
					UINT ms = 0;
					result = musicchannel->getPosition(&ms,FMOD_TIMEUNIT_MS);
					if( result == FMOD_OK )
					{
						MusicPositions(Viewport->Actor->SongSection).ms = ms;
					}
				}
			}
		}
		else if( Viewport->Actor->Song && VolumeMusic > 0 )
		{
			// Restart missing/dropped song (bad channel priorities?)
			SWF_LOG( NAME_DevSound, TEXT("%s :: %s :: Restarting missing song %s S:%s T:%s "), SWF_PLOG
				, *ToStr(Viewport->Actor->Song)
				, *ToStr(Viewport->Actor->SongSection)
				, *ToStr(Viewport->Actor->Transition));
			Viewport->Actor->Transition = MTRAN_Instant;
		}
	}



	unguard;

	// Update FMOD
	guard(UpdateFMOD);
	SWF_FMOD_CALL( System->update() );
	unguard;

	//SWF_LOG( NAME_DevSound, TEXT("%s << %s :: [%s],[%s]"), SWF_PLOG, *ToStr(Region), *ToStr(Coords) );
	unguard;
}
void XMLReader::LoadSceneFromFile(QFile &file, const QStringRef &local_path, Scene &scene, Integrator &integrator)
{
    if(file.open(QIODevice::ReadOnly))
    {
        QXmlStreamReader xml_reader;
        xml_reader.setDevice(&file);
        QMap<QString, QList<Geometry*>> material_to_geometry_map;
        while(!xml_reader.isEndDocument())
        {
            xml_reader.readNext();
            if(xml_reader.isStartElement())
            {
                //Get the tag name
                QString tag(xml_reader.name().toString());
                if(QString::compare(tag, QString("camera")) == 0)
                {
                    scene.SetCamera(LoadCamera(xml_reader));
                }
                else if(QString::compare(tag, QString("geometry")) == 0)
                {
                    Geometry* geometry = LoadGeometry(xml_reader, material_to_geometry_map, local_path);
                    if(geometry == NULL)
                    {
                        return;
                    }
                    scene.objects.append(geometry);
                }
                else if(QString::compare(tag, QString("material")) == 0)
                {
                    Material* material = LoadMaterial(xml_reader, local_path);
                    if(material == NULL)
                    {
                        return;
                    }
                    scene.materials.append(material);
                }
                else if(QString::compare(tag, QString("integrator")) == 0)
                {
                    integrator = LoadIntegrator(xml_reader);
                }
                else if(QString::compare(tag, QString("pixelSampler"), Qt::CaseInsensitive) == 0)
                {
                    PixelSampler* sampler = LoadPixelSampler(xml_reader);
                    if(sampler == NULL)
                    {
                        std::cout << "Did not properly load a pixel sampler!" << std::endl;
                        return;
                    }
                    if(scene.pixel_sampler != NULL)
                    {
                        delete scene.pixel_sampler;
                    }
                    scene.pixel_sampler = sampler;
                }
            }
        }
        //Associate the materials in the XML file with the geometries that use those materials.
        for(int i = 0; i < scene.materials.size(); i++)
        {
            QList<Geometry*> l = material_to_geometry_map.value(scene.materials[i]->name);
            for(int j = 0; j < l.size(); j++)
            {
                l[j]->SetMaterial(scene.materials[i]);
            }
        }

        //Copy emissive geometry from the list of objects to the list of lights
        QList<Geometry*> to_lights;
        for(Geometry *g : scene.objects)
        {
            g->create();
            if(g->material->emissive)
            {
                to_lights.append(g);
            }
        }
        for(Geometry *g : to_lights)
        {
            scene.lights.append(g);
        }
        file.close();
    }
}
int main( int argc, char ** argv )
{
    GDALDriverH     hDriver;
    const char      *pszSource=NULL, *pszDest=NULL, *pszFormat = "GTiff";
    int             bFormatExplicitelySet = FALSE;
    char            **papszLayers = NULL;
    const char      *pszBurnAttribute = NULL;
    double          dfIncreaseBurnValue = 0.0;
    double          dfMultiplyBurnValue = 1.0;
    const char      *pszWHERE = NULL, *pszSQL = NULL;
    GDALDataType    eOutputType = GDT_Float64;
    char            **papszCreateOptions = NULL;
    GUInt32         nXSize = 0, nYSize = 0;
    double          dfXMin = 0.0, dfXMax = 0.0, dfYMin = 0.0, dfYMax = 0.0;
    int             bIsXExtentSet = FALSE, bIsYExtentSet = FALSE;
    GDALGridAlgorithm eAlgorithm = GGA_InverseDistanceToAPower;
    void            *pOptions = NULL;
    char            *pszOutputSRS = NULL;
    int             bQuiet = FALSE;
    GDALProgressFunc pfnProgress = GDALTermProgress;
    int             i;
    OGRGeometry     *poSpatialFilter = NULL;
    int             bClipSrc = FALSE;
    OGRGeometry     *poClipSrc = NULL;
    const char      *pszClipSrcDS = NULL;
    const char      *pszClipSrcSQL = NULL;
    const char      *pszClipSrcLayer = NULL;
    const char      *pszClipSrcWhere = NULL;

    /* Check strict compilation and runtime library version as we use C++ API */
    if (! GDAL_CHECK_VERSION(argv[0]))
        exit(1);

    GDALAllRegister();
    OGRRegisterAll();

    argc = GDALGeneralCmdLineProcessor( argc, &argv, 0 );
    if( argc < 1 )
        exit( -argc );

/* -------------------------------------------------------------------- */
/*      Parse arguments.                                                */
/* -------------------------------------------------------------------- */
    for( i = 1; i < argc; i++ )
    {
        if( EQUAL(argv[i], "--utility_version") )
        {
            printf("%s was compiled against GDAL %s and is running against GDAL %s\n",
                   argv[0], GDAL_RELEASE_NAME, GDALVersionInfo("RELEASE_NAME"));
            return 0;
        }
        else if( EQUAL(argv[i],"--help") )
            Usage();
        else if( EQUAL(argv[i],"-of") )
        {
            CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1);
            pszFormat = argv[++i];
            bFormatExplicitelySet = TRUE;
        }

        else if( EQUAL(argv[i],"-q") || EQUAL(argv[i],"-quiet") )
        {
            bQuiet = TRUE;
            pfnProgress = GDALDummyProgress;
        }

        else if( EQUAL(argv[i],"-ot") )
        {
            CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1);
            int	iType;
            
            for( iType = 1; iType < GDT_TypeCount; iType++ )
            {
                if( GDALGetDataTypeName((GDALDataType)iType) != NULL
                    && EQUAL(GDALGetDataTypeName((GDALDataType)iType),
                             argv[i+1]) )
                {
                    eOutputType = (GDALDataType) iType;
                }
            }

            if( eOutputType == GDT_Unknown )
            {
                Usage(CPLSPrintf("Unknown output pixel type: %s.",
                                 argv[i + 1] ));
            }
            i++;
        }

        else if( EQUAL(argv[i],"-txe") )
        {
            CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(2);
            dfXMin = atof(argv[++i]);
            dfXMax = atof(argv[++i]);
            bIsXExtentSet = TRUE;
        }   

        else if( EQUAL(argv[i],"-tye") )
        {
            CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(2);
            dfYMin = atof(argv[++i]);
            dfYMax = atof(argv[++i]);
            bIsYExtentSet = TRUE;
        }   

        else if( EQUAL(argv[i],"-outsize") )
        {
            CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(2);
            nXSize = atoi(argv[++i]);
            nYSize = atoi(argv[++i]);
        }   

        else if( EQUAL(argv[i],"-co") )
        {
            CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1);
            papszCreateOptions = CSLAddString( papszCreateOptions, argv[++i] );
        }   

        else if( EQUAL(argv[i],"-zfield") )
        {
            CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1);
            pszBurnAttribute = argv[++i];
        }

        else if( EQUAL(argv[i],"-z_increase") )
        {
            CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1);
            dfIncreaseBurnValue = atof(argv[++i]);
        }

        else if( EQUAL(argv[i],"-z_multiply") )
        {
            CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1);
            dfMultiplyBurnValue = atof(argv[++i]);
        }

        else if( EQUAL(argv[i],"-where") )
        {
            CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1);
            pszWHERE = argv[++i];
        }

        else if( EQUAL(argv[i],"-l") )
        {
            CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1);
            papszLayers = CSLAddString( papszLayers, argv[++i] );
        }

        else if( EQUAL(argv[i],"-sql") )
        {
            CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1);
            pszSQL = argv[++i];
        }

        else if( EQUAL(argv[i],"-spat") )
        {
            CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(4);
            OGRLinearRing  oRing;

            oRing.addPoint( atof(argv[i+1]), atof(argv[i+2]) );
            oRing.addPoint( atof(argv[i+1]), atof(argv[i+4]) );
            oRing.addPoint( atof(argv[i+3]), atof(argv[i+4]) );
            oRing.addPoint( atof(argv[i+3]), atof(argv[i+2]) );
            oRing.addPoint( atof(argv[i+1]), atof(argv[i+2]) );

            poSpatialFilter = new OGRPolygon();
            ((OGRPolygon *) poSpatialFilter)->addRing( &oRing );
            i += 4;
        }

        else if ( EQUAL(argv[i],"-clipsrc") )
        {
            if (i + 1 >= argc)
                Usage(CPLSPrintf("%s option requires 1 or 4 arguments", argv[i]));

            bClipSrc = TRUE;
            errno = 0;
            const double unused = strtod( argv[i + 1], NULL );    // XXX: is it a number or not?
            if ( errno != 0
                 && argv[i + 2] != NULL
                 && argv[i + 3] != NULL
                 && argv[i + 4] != NULL)
            {
                OGRLinearRing  oRing;

                oRing.addPoint( atof(argv[i + 1]), atof(argv[i + 2]) );
                oRing.addPoint( atof(argv[i + 1]), atof(argv[i + 4]) );
                oRing.addPoint( atof(argv[i + 3]), atof(argv[i + 4]) );
                oRing.addPoint( atof(argv[i + 3]), atof(argv[i + 2]) );
                oRing.addPoint( atof(argv[i + 1]), atof(argv[i + 2]) );

                poClipSrc = new OGRPolygon();
                ((OGRPolygon *) poClipSrc)->addRing( &oRing );
                i += 4;

                (void)unused;
            }
            else if (EQUALN(argv[i + 1], "POLYGON", 7)
                     || EQUALN(argv[i + 1], "MULTIPOLYGON", 12))
            {
                OGRGeometryFactory::createFromWkt(&argv[i + 1], NULL, &poClipSrc);
                if ( poClipSrc == NULL )
                {
                    Usage("Invalid geometry. "
                             "Must be a valid POLYGON or MULTIPOLYGON WKT.");
                }
                i++;
            }
            else if (EQUAL(argv[i + 1], "spat_extent") )
            {
                i++;
            }
            else
            {
                pszClipSrcDS = argv[i + 1];
                i++;
            }
        }

        else if ( EQUAL(argv[i], "-clipsrcsql") )
        {
            CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1);
            pszClipSrcSQL = argv[i + 1];
            i++;
        }

        else if ( EQUAL(argv[i], "-clipsrclayer") )
        {
            CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1);
            pszClipSrcLayer = argv[i + 1];
            i++;
        }

        else if ( EQUAL(argv[i], "-clipsrcwhere") )
        {
            CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1);
            pszClipSrcWhere = argv[i + 1];
            i++;
        }

        else if( EQUAL(argv[i],"-a_srs") )
        {
            CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1);
            OGRSpatialReference oOutputSRS;

            if( oOutputSRS.SetFromUserInput( argv[i+1] ) != OGRERR_NONE )
            {
                fprintf( stderr, "Failed to process SRS definition: %s\n", 
                         argv[i+1] );
                GDALDestroyDriverManager();
                exit( 1 );
            }

            oOutputSRS.exportToWkt( &pszOutputSRS );
            i++;
        }   

        else if( EQUAL(argv[i],"-a") )
        {
            CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1);
            if ( ParseAlgorithmAndOptions( argv[++i], &eAlgorithm, &pOptions )
                 != CE_None )
            {
                fprintf( stderr,
                         "Failed to process algorithm name and parameters.\n" );
                exit( 1 );
            }
        }

        else if( argv[i][0] == '-' )
        {
            Usage(CPLSPrintf("Unknown option name '%s'", argv[i]));
        }

        else if( pszSource == NULL )
        {
            pszSource = argv[i];
        }

        else if( pszDest == NULL )
        {
            pszDest = argv[i];
        }

        else
        {
            Usage("Too many command options.");
        }
    }

    if( pszSource == NULL )
    {
        Usage("Source datasource is not specified.");
    }
    if( pszDest == NULL )
    {
        Usage("Target dataset is not specified.");
    }
    if( pszSQL == NULL && papszLayers == NULL )
    {
        Usage("Neither -sql nor -l are specified.");
    }
    
    if ( bClipSrc && pszClipSrcDS != NULL )
    {
        poClipSrc = LoadGeometry( pszClipSrcDS, pszClipSrcSQL,
                                  pszClipSrcLayer, pszClipSrcWhere );
        if ( poClipSrc == NULL )
        {
            Usage("Cannot load source clip geometry.");
        }
    }
    else if ( bClipSrc && poClipSrc == NULL && !poSpatialFilter )
    {
        Usage("-clipsrc must be used with -spat option or \n"
                 "a bounding box, WKT string or datasource must be "
                 "specified.");
    }

    if ( poSpatialFilter )
    {
        if ( poClipSrc )
        {
            OGRGeometry *poTemp = poSpatialFilter->Intersection( poClipSrc );

            if ( poTemp )
            {
                OGRGeometryFactory::destroyGeometry( poSpatialFilter );
                poSpatialFilter = poTemp;
            }

            OGRGeometryFactory::destroyGeometry( poClipSrc );
            poClipSrc = NULL;
        }
    }
    else
    {
        if ( poClipSrc )
        {
            poSpatialFilter = poClipSrc;
            poClipSrc = NULL;
        }
    }

/* -------------------------------------------------------------------- */
/*      Find the output driver.                                         */
/* -------------------------------------------------------------------- */
    hDriver = GDALGetDriverByName( pszFormat );
    if( hDriver == NULL )
    {
        int	iDr;
        
        fprintf( stderr,
                 "FAILURE: Output driver `%s' not recognised.\n", pszFormat );
        fprintf( stderr,
        "The following format drivers are configured and support output:\n" );
        for( iDr = 0; iDr < GDALGetDriverCount(); iDr++ )
        {
            GDALDriverH hDriver = GDALGetDriver(iDr);

            if( GDALGetMetadataItem( hDriver, GDAL_DCAP_CREATE, NULL ) != NULL
                || GDALGetMetadataItem( hDriver, GDAL_DCAP_CREATECOPY,
                                        NULL ) != NULL )
            {
                fprintf( stderr, "  %s: %s\n",
                         GDALGetDriverShortName( hDriver  ),
                         GDALGetDriverLongName( hDriver ) );
            }
        }
        printf( "\n" );
        Usage();
    }

/* -------------------------------------------------------------------- */
/*      Open input datasource.                                          */
/* -------------------------------------------------------------------- */
    OGRDataSourceH hSrcDS;

    hSrcDS = OGROpen( pszSource, FALSE, NULL );
    if( hSrcDS == NULL )
    {
        fprintf( stderr, "Unable to open input datasource \"%s\".\n",
                 pszSource );
        fprintf( stderr, "%s\n", CPLGetLastErrorMsg() );
        exit( 3 );
    }

/* -------------------------------------------------------------------- */
/*      Create target raster file.                                      */
/* -------------------------------------------------------------------- */
    GDALDatasetH    hDstDS;
    int             nLayerCount = CSLCount(papszLayers);
    int             nBands = nLayerCount;

    if ( pszSQL )
        nBands++;

    // FIXME
    if ( nXSize == 0 )
        nXSize = 256;
    if ( nYSize == 0 )
        nYSize = 256;

    if (!bQuiet && !bFormatExplicitelySet)
        CheckExtensionConsistency(pszDest, pszFormat);

    hDstDS = GDALCreate( hDriver, pszDest, nXSize, nYSize, nBands,
                         eOutputType, papszCreateOptions );
    if ( hDstDS == NULL )
    {
        fprintf( stderr, "Unable to create target dataset \"%s\".\n",
                 pszDest );
        fprintf( stderr, "%s\n", CPLGetLastErrorMsg() );
        exit( 3 );
    }

/* -------------------------------------------------------------------- */
/*      If algorithm was not specified assigh default one.              */
/* -------------------------------------------------------------------- */
    if ( !pOptions )
        ParseAlgorithmAndOptions( szAlgNameInvDist, &eAlgorithm, &pOptions );

/* -------------------------------------------------------------------- */
/*      Process SQL request.                                            */
/* -------------------------------------------------------------------- */
    if( pszSQL != NULL )
    {
        OGRLayerH hLayer;

        hLayer = OGR_DS_ExecuteSQL( hSrcDS, pszSQL,
                                    (OGRGeometryH)poSpatialFilter, NULL ); 
        if( hLayer != NULL )
        {
            // Custom layer will be rasterized in the first band.
            ProcessLayer( hLayer, hDstDS, poSpatialFilter, nXSize, nYSize, 1,
                          bIsXExtentSet, bIsYExtentSet,
                          dfXMin, dfXMax, dfYMin, dfYMax, pszBurnAttribute,
                          dfIncreaseBurnValue, dfMultiplyBurnValue, eOutputType, eAlgorithm, pOptions,
                          bQuiet, pfnProgress );
        }
    }

/* -------------------------------------------------------------------- */
/*      Process each layer.                                             */
/* -------------------------------------------------------------------- */
    for( i = 0; i < nLayerCount; i++ )
    {
        OGRLayerH hLayer = OGR_DS_GetLayerByName( hSrcDS, papszLayers[i]);
        if( hLayer == NULL )
        {
            fprintf( stderr, "Unable to find layer \"%s\", skipping.\n", 
                     papszLayers[i] );
            continue;
        }

        if( pszWHERE )
        {
            if( OGR_L_SetAttributeFilter( hLayer, pszWHERE ) != OGRERR_NONE )
                break;
        }

        if ( poSpatialFilter != NULL )
            OGR_L_SetSpatialFilter( hLayer, (OGRGeometryH)poSpatialFilter );

        // Fetch the first meaningful SRS definition
        if ( !pszOutputSRS )
        {
            OGRSpatialReferenceH hSRS = OGR_L_GetSpatialRef( hLayer );
            if ( hSRS )
                OSRExportToWkt( hSRS, &pszOutputSRS );
        }

        ProcessLayer( hLayer, hDstDS, poSpatialFilter, nXSize, nYSize,
                      i + 1 + nBands - nLayerCount,
                      bIsXExtentSet, bIsYExtentSet,
                      dfXMin, dfXMax, dfYMin, dfYMax, pszBurnAttribute,
                      dfIncreaseBurnValue, dfMultiplyBurnValue, eOutputType, eAlgorithm, pOptions,
                      bQuiet, pfnProgress );
    }

/* -------------------------------------------------------------------- */
/*      Apply geotransformation matrix.                                 */
/* -------------------------------------------------------------------- */
    double  adfGeoTransform[6];
    adfGeoTransform[0] = dfXMin;
    adfGeoTransform[1] = (dfXMax - dfXMin) / nXSize;
    adfGeoTransform[2] = 0.0;
    adfGeoTransform[3] = dfYMin;
    adfGeoTransform[4] = 0.0;
    adfGeoTransform[5] = (dfYMax - dfYMin) / nYSize;
    GDALSetGeoTransform( hDstDS, adfGeoTransform );

/* -------------------------------------------------------------------- */
/*      Apply SRS definition if set.                                    */
/* -------------------------------------------------------------------- */
    if ( pszOutputSRS )
    {
        GDALSetProjection( hDstDS, pszOutputSRS );
        CPLFree( pszOutputSRS );
    }

/* -------------------------------------------------------------------- */
/*      Cleanup                                                         */
/* -------------------------------------------------------------------- */
    OGR_DS_Destroy( hSrcDS );
    GDALClose( hDstDS );
    OGRGeometryFactory::destroyGeometry( poSpatialFilter );

    CPLFree( pOptions );
    CSLDestroy( papszCreateOptions );
    CSLDestroy( argv );
    CSLDestroy( papszLayers );

    OGRCleanupAll();

    GDALDestroyDriverManager();
 
    return 0;
}