Пример #1
0
/*virtual*/ void WBCompEldLight::HandleEvent( const WBEvent& Event )
{
	XTRACE_FUNCTION;

	Super::HandleEvent( Event );

	STATIC_HASHED_STRING( OnMoved );
	STATIC_HASHED_STRING( OnDestroyed );
	STATIC_HASHED_STRING( AddLight );
	STATIC_HASHED_STRING( RemoveLight );

	const HashedString EventName = Event.GetEventName();
	if( EventName == sOnMoved )
	{
		if( m_DeferAddLight )
		{
			// Do nothing
		}
		else
		{
			AddLight();
		}
	}
	else if( EventName == sAddLight )
	{
		AddLight();
	}
	else if( EventName == sOnDestroyed || EventName == sRemoveLight )
	{
		RemoveLight();
	}
}
Пример #2
0
void Canister::Update(float DeltaTime, Terrain* terrain)
{
	XMFLOAT3	newPos	=	GetFloat3Value( Position );

	if ( !gPointLight )
	{
		gPointLight	=	new PointLight();
		gPointLight->GetGPULight()->Color		=	XMFLOAT4( 0.0f, 0.0f, 1.0f, 0.0f );
		gPointLight->GetGPULight()->Position	=	newPos;
		gPointLight->GetGPULight()->Range		=	33.333f * 0.40f;
		gPointLight->GetGPULight()->HasShadow	=	false;

		AddLight( gPointLight );
	}

	gTimeSpan	+=	DeltaTime;

	XMVECTOR QuatV = XMQuaternionRotationRollPitchYaw(0, DeltaTime, 0);
	XMFLOAT4 Quat;

	XMStoreFloat4(&Quat, QuatV);
	AddRotation( Quat );
	newPos.y	=	gOffset.y + ( gOffset.y - 2 ) * sin( 8 * gTimeSpan );
	MoveTo( newPos );
	newPos.y	-=	1.0f;
	if ( gPointLight )
		gPointLight->GetGPULight()->Position	=	newPos;

	Item::Update( DeltaTime, terrain );
}
Пример #3
0
/*
================
idExplodingBarrel::ExplodingEffects
================
*/
void idExplodingBarrel::ExplodingEffects( void ) {
	const char *temp;

	StartSound( "snd_explode", SND_CHANNEL_ANY, 0, false, NULL );

	temp = spawnArgs.GetString( "model_damage" );
	if ( *temp != '\0' ) {
		SetModel( temp );
		Show();
	}

	temp = spawnArgs.GetString( "model_detonate" );
	if ( *temp != '\0' ) {
		AddParticles( temp, false );
	}

	temp = spawnArgs.GetString( "mtr_lightexplode" );
	if ( *temp != '\0' ) {
		AddLight( temp, false );
	}

	temp = spawnArgs.GetString( "mtr_burnmark" );
	if ( *temp != '\0' ) {
		gameLocal.ProjectDecal( GetPhysics()->GetOrigin(), GetPhysics()->GetGravity(), 128.0f, true, 96.0f, temp );
	}
}
Пример #4
0
	/*
	=====================
	Layer::Layer
	
		Add a light using a preloaded texture.
		Define the light texture to use with the identifier string.
		Lights can be preloaded through the PreloadLightDef method.
	=====================
	*/
	bool Layer::AddLight(GameNode *node, PreloadLightDef *pld, const string identifier) {
		if (lightSys) {
			if (!lightSys->UsePreloadedTexture(pld, identifier)) {
				return false;
			}

			AddLight(node, pld);
			return true;
		}

		return false;
	}
Пример #5
0
void MapMode::AddLight(const std::string &main_flare_filename,
                       const std::string &secondary_flare_filename,
                       float x, float y,
                       const Color &main_color,
                       const Color &secondary_color)
{
    Light *light = new Light(main_flare_filename,
                             secondary_flare_filename,
                             x, y, main_color,
                             secondary_color);

    AddLight(light);
}
Пример #6
0
void Stage01::InitBackground()
{
	auto engine = STGEngine::GetInstance();
	auto background = engine->GetGameScene()->GetBackgroundLayer();

	SetupCamera();
	SetupFog();

	background->SetSkyBox(sky);
	background->EnableLighting(true);
	background->SetAmbientLight(Vector4f(0.3f, 0.3f, 0.3f, 1.0f));
	background->AddLight(Ptr<DirectionalLight>::New(Vector3f(1.8f, 1.8f, 1.8f), Vector3f(1.0f, -1.0f, 0.0f)).Get());

	InitBackgroundObjects();
}
Пример #7
0
//------------------------------------------------------------------------------
//turns lighting on.  returns true if lights were actually turned on. (they
//would not be if they had previously been bShot out).
int CTrigger::DoLightOn (void)
{
	int ret = 0;
	short nSegment, nSide;

for (int i = 0; i < m_info.nLinks; i++) {
	nSegment = m_info.segments [i];
	nSide = m_info.sides [i];
	//check if tmap2 casts light before turning the light on.  This
	//is to keep us from turning on blown-out lights
	if (gameData.pig.tex.tMapInfoP [SEGMENTS [nSegment].m_sides [nSide].m_nOvlTex].lighting) {
		ret |= AddLight (nSegment, nSide); 		//any light sets flag
		EnableVariableLight (nSegment, nSide);
		}
	}
return ret;
}
Пример #8
0
CBone::CBone( CObjectManager* _objManager, IObject* _parent ) : IObject( "Bone" )
{
    m_cpParent = _parent;
    m_bActive = false;
    m_fDespawnTime = DESPAWN_TIME;

    XMFLOAT3 newPos = { m_cpParent->GetPosition()->x, 50, m_cpParent->GetPosition()->z };
    SetPosition( newPos );

    //SetPosition( {500,100,0} );

    CMesh* theMesh = CAssetManager::GetInstance()->GetPrefabMesh("BonePile");
    m_cpRenderMesh = new CRenderMesh( theMesh,
                                      GRAPHICS->GetVertexShader(), GRAPHICS->GetPixelShader(),
                                      nullptr, nullptr, nullptr, L"../Game/Assets/Art/2D/Textures/Failbot_BoneLoot.dds" );
    m_cpRenderMesh->SetNormals( L"../Game/Assets/Art/2D/Normal Maps/Failbot_BoneLoot.dds" );

    m_cpRenderMesh->GetTransparent() = true;
    m_cpRenderMesh->GetTransparencyOverride() = 0.0f;
    GRAPHICS->AddRenderMesh( m_cpRenderMesh );

    XMFLOAT3 extents = XMFLOAT3{ 40, 100, 40 };
    AddCollider( new CCollider( true, new CAABB( *GetPosition(), extents ), false ) );

    _objManager->AddObject( this, CObjectManager::Dynamic );

    TPointLight tempLight;
    tempLight.m_fPosition[0] = GetPosition()->x;
    tempLight.m_fPosition[1] = GetPosition()->y;
    tempLight.m_fPosition[2] = GetPosition()->z;
    tempLight.m_fColor[0] = 0.3f;
    tempLight.m_fColor[1] = 0.3f;
    tempLight.m_fColor[2] = 0.3f;
    tempLight.m_fRadius = 500.0f;
    tempLight.m_fBrightness = 10.0f;
    AddLight(tempLight);

    //set up particles
    m_cpParticleManager = new CParticleManager( _objManager );
    m_unParticle = m_cpParticleManager->LoadEmitter( "DroppedItemParticle.xml" );
    m_cpParticleManager->GetEmitter( m_unParticle )->GetPosition( 0 ) = newPos.x;
    m_cpParticleManager->GetEmitter( m_unParticle )->GetPosition( 1 ) = newPos.y;
    m_cpParticleManager->GetEmitter( m_unParticle )->GetPosition( 2 ) = newPos.z;

    m_cpParticleManager->GetEmitter( m_unParticle )->Stop();
}
void MaterialPreviewPropView::OnPropertyButtonClick(NMHDR *nmhdr, LRESULT *lresult)
{
	NMPROPTREE		*nmProp;
	CPropTreeItem	*item;

	nmProp = (NMPROPTREE *)nmhdr;
	item = nmProp->pItem;

	idStr	itemLabel = item->GetLabelText();

	if (itemLabel == "Preview Lights") {
		AddLight();

	} else if (itemLabel.Left(5) == "Light") {
		CPropTreeItem	*light;
		int lightId = item->GetCtrlID();
		int testLightNum = 0;

		m_Tree.DeleteItem(item);

		for (light = m_Tree.GetRootItem()->GetChild(); light != NULL; light = light->GetSibling()) {
			idStr label = light->GetLabelText();

			if (label.Left(5) == "Light") {
				testLightNum++;
				light->SetLabelText(_T(va("Light #%d", testLightNum)));
				light->SetInfoText(_T(va("Parameters for light number %d.", testLightNum)));
				light->SetCtrlID(testLightNum - 1);
			}
		}

		materialPreview->OnDeleteLight(lightId);

		numLights--;
	} else if (itemLabel == "Custom Model") {
		CFileDialog dlg(TRUE);
		dlg.m_ofn.Flags |= OFN_FILEMUSTEXIST;
		item->Check(FALSE);

		if (dlg.DoModal()== IDOK) {
			item->Check(FALSE);
			item->SetItemValue((LPARAM)fileSystem->OSPathToRelativePath(dlg.m_ofn.lpstrFile));
			m_Tree.SendNotify(PTN_ITEMCHANGED, item);
		}
	}
}
Пример #10
0
void mglCanvas::DefaultPlotParam()
{
/* NOTE: following variables and mutex will not be changed by DefaultPlotParam()
long InUse;			///< Smart pointer (number of users)
mglFont *fnt;		///< Class for printing vector text
int Quality;		///< Quality of plot (0x0-pure, 0x1-fast; 0x2-fine; 0x4 - low memory)
int Width;			///< Width of the image
int Height;			///< Height of the image
int Depth;			///< Depth of the image
int CurFrameId;		///< Number of automaticle created frames
GifFileType *gif;*/
	SetDrawReg(1,1,0);		Perspective(0);
	memcpy(mgl_mask_val, mgl_mask_def, 16*sizeof(uint64_t));	// should be > 16*8
	ax.Clear();	ay.Clear();	az.Clear();	ac.Clear();
	mgl_clear_fft();		DefMaskAn=0;	ResetMask();
	SetTickRotate(true);	SetTickSkip(true);
	SetWarn(mglWarnNone,"");	mglGlobalMess = "";
	ObjId = -1;	HighId = INT_MIN;
	SetFunc(0,0);	CutOff(0);	Ternary(0);
	Stop=false;	event_cb = NULL;	event_par=NULL;
	SetRanges(mglPoint(-1,-1,-1,-1), mglPoint(1,1,1,1));
	SetOrigin(NAN,NAN,NAN,NAN);
	SetBarWidth(0.7);	SetMarkSize(1);	SetArrowSize(1);
	SetAlphaDef(0.5);		FontDef[0]=0;
	SetTranspType(0);		SetMeshNum(0);	// NOTE: default MeshNum=0
	SetRotatedText(true);	CurrPal = 0;
	SetLegendMarks();		SetFontSize(4);
	SetTuneTicks(3);		SetAmbient();	SetDiffuse();
	clr(MGL_DISABLE_SCALE);
	clr(MGL_USE_GMTIME);	clr(MGL_NOSUBTICKS);
	SetDifLight(false);		SetReduceAcc(false);
	SetDefScheme(MGL_DEF_SCH);	SetPalette(MGL_DEF_PAL);
	SetPenPal("k-1");		Alpha(false);
	stack.clear();	Restore();	DefColor('k');
	SetPlotFactor(0);	InPlot(0,1,0,1,false);
	SetTickLen(0);	SetCut(true);
	AdjustTicks("xyzc",true);	Clf('w');

	for(int i=0;i<10;i++)	{	AddLight(i, mglPoint(0,0,1));	Light(i,false);	}
	Light(0,true);	Light(false);	SetDifLight(true);
}
Пример #11
0
void CLightMgr::LoadZoneLight(const char* szFN)
{
	if(!szFN) return;
	
	DWORD dwRWC;
	HANDLE hFile = CreateFile(szFN, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
	if(INVALID_HANDLE_VALUE == hFile) return;

	int iVersion;
	ReadFile(hFile, &iVersion, sizeof(int), &dwRWC, NULL);

	int cnt;
	ReadFile(hFile, &cnt, sizeof(int), &dwRWC, NULL);
	for(int i=0;i<cnt;i++)
	{
		CN3Light* pLgt = new CN3Light;
		pLgt->m_iVersion = N3FORMAT_VER_DEFAULT;

		pLgt->Load(hFile);
		AddLight(pLgt);
	}
	CloseHandle(hFile);
}
Пример #12
0
bool ETHScene::GenerateLightmaps(const int id)
{
	const ETHSpriteEntity *pRender = (id >= 0) ? m_buckets.SeekEntity(id) : 0;
	const Vector2 v2Bucket = (pRender) ? ETHGlobal::GetBucket(pRender->GetPositionXY(), GetBucketSize()) : Vector2(0,0);

	for (ETHBucketMap::iterator bucketIter = m_buckets.GetFirstBucket(); bucketIter != m_buckets.GetLastBucket(); bucketIter++)
	{
		// if we're lighting only one entity and it is not in this bucket, skip it.
		// I know we could have used the find method to go directly to that bucket
		// but this function os not that critical to make the effort worth it.
		if (id >= 0)
			if (v2Bucket != bucketIter->first)
				continue;

		// iterate over all entities in this bucket
		ETHEntityList::const_iterator iEnd = bucketIter->second.end();
		for (ETHEntityList::iterator iter = bucketIter->second.begin(); iter != iEnd; iter++)
		{
			// if nID is valid, let's try to generate the lightmap for this one and only entity
			if (id >= 0)
				if (id != (*iter)->GetID())
					continue;

			Vector2 v2Size(1,1);
			Vector2 v2Origin(0,0);
			if ((*iter)->GetSprite())
			{
				v2Size = (*iter)->GetCurrentSize();
				v2Origin = (*iter)->ComputeOrigin(v2Size);
			}

			// Place the current entity at the top-left corner to align
			// it to the render target
			const Vector3 oldPos = (*iter)->GetPosition();
			const Vector3 newPos = Vector3(v2Origin.x, v2Origin.y, 0);

			// fill the light list
			for (ETHBucketMap::iterator lbucketIter = m_buckets.GetFirstBucket(); lbucketIter != m_buckets.GetLastBucket(); lbucketIter++)
			{
				ETHEntityList::const_iterator liEnd = lbucketIter->second.end();
				for (ETHEntityList::iterator liter = lbucketIter->second.begin(); liter != liEnd; liter++)
				{
					if ((*liter)->IsStatic() && (*liter)->HasLightSource())
					{
						AddLight(*((*liter)->GetLight()), newPos-oldPos+(*liter)->GetPosition());
					}
				}
			}

			ETHLightmapGen((*iter), m_provider->GetShaderManager(), m_lights.begin(), m_lights.end(),
							m_buckets, oldPos, newPos, m_minSceneHeight, m_maxSceneHeight, m_sceneProps);

			(*iter)->SetOrphanPosition(oldPos);
			m_lights.clear();
		}
	}
	#ifdef _DEBUG
	ETH_STREAM_DECL(ss) << GS_L("Lightmaps created... ");
	m_provider->Log(ss.str(), Platform::FileLogger::INFO);
	#endif
	return true;
}
Пример #13
0
/*****************************************************************
* CSkeleton()			Skeleton Constructor that initializes the data members
*
* Ins:					CObjectManager*
*						CAnimationManager*
*
* Outs:					None
*
* Returns:				void
*
* Mod. Date:		    08/20/2015
* Mod. Initials:	    NS
*****************************************************************/
CSkeleton::CSkeleton(CObjectManager* _manager, CAnimationManager* _animManager, CDayNight* _dayNight, CSkeletonController* skeletonController) : CBoid(10.0f, 500.0f, "Skeleton")
{
	// Drop Shadow Creation //
	CMesh cDropShadow;

	cDropShadow.GetIndices().push_back(0);
	cDropShadow.GetIndices().push_back(1);
	cDropShadow.GetIndices().push_back(2);

	cDropShadow.GetIndices().push_back(0);
	cDropShadow.GetIndices().push_back(2);
	cDropShadow.GetIndices().push_back(3);

	cDropShadow.GetVertices().push_back
		({
			{ -100.0f, 3.0f, 100.0f, 1.0f },
			{ 0.0f, 1.0f, 0.0f, 1.0f },
			{ 0, 0 }
	});

	cDropShadow.GetVertices().push_back
		({
			{ 100.0f, 3.0f, 100.0f, 1.0f },
			{ 0.0f, 1.0f, 0.0f, 1.0f },
			{ 1, 0 }
	});

	cDropShadow.GetVertices().push_back
		({
			{ 100.0f, 3.0f, -100.0f, 1.0f },
			{ 0.0f, 1.0f, 0.0f, 1.0f },
			{ 1, 1 }
	});

	cDropShadow.GetVertices().push_back
		({
			{ -100.0f, 3.0f, -100.0f, 1.0f },
			{ 0.0f, 1.0f, 0.0f, 1.0f },
			{ 0, 1 }
	});

	m_cDropShadow = new CRenderMesh(&cDropShadow, GRAPHICS->GetStandardVS(), GRAPHICS->GetStandardPS());
	m_cDropShadow->SetTexture(L"../Game/Assets/Art/2D/Textures/Shadow.dds");
	m_cDropShadow->GetTransparent() = true;
	m_cDropShadow->GetRender() = false;

	GRAPHICS->AddRenderMesh(m_cDropShadow);

	// Initilize Managers
#if _DEBUG
	m_pPathPlanner = new CPathFinding("SkeletonNavGraph", _manager, false);

#else
	m_pPathPlanner = new CPathFinding("SkeletonNavGraph", _manager, false);

#endif

	m_pDayNight = _dayNight;
	m_fScale = 1.0f;
	
	m_pAssetManager = CAssetManager::GetInstance();
	m_bPoweringUp = false;
	//Set the Animation Manager
	m_cpAnimationManager = _animManager;
	m_cpAnimations = new CAnimation[eAnimCount];

	m_cpSkeletonController = skeletonController;
	// Set the object manager
	m_cpObjectManager = _manager;
	m_bBuffed = false;

	TPointLight tempLight;
	tempLight.m_fRadius = 0.0f;
	tempLight.m_fColor[0] = 1.0f;
	tempLight.m_fColor[1] = 0.0f;
	tempLight.m_fColor[2] = 0.0f;
	tempLight.m_fBrightness = 2.5f;
	tempLight.m_fPosition[0] = 0.0f;
	tempLight.m_fPosition[1] = 0.0f;
	tempLight.m_fPosition[2] = 0.0f;
	tempLight.m_fPosition[3] = 1.0f;
	AddLight(tempLight);

	m_bHit = false;

	// Load the asset
	/*CMesh* m_cShieldMesh = m_pAssetManager->GetMesh(CAssetManager::eMeshType::SkeletonShield)[0];
	m_cShieldRender[0] = new CRenderMesh(m_cShieldMesh, GRAPHICS->GetStandardVS(), GRAPHICS->GetStandardPS(), nullptr, nullptr, nullptr, L"../Game/Assets/Art/2D/Textures/Shield2_Diffuse.dds");
	m_cShieldRender[1] = new CRenderMesh(m_cShieldMesh, GRAPHICS->GetStandardVS(), GRAPHICS->GetStandardPS(), nullptr, nullptr, nullptr, L"../Game/Assets/Art/2D/Textures/Shield2_Diffuse.dds");*/

	CMesh* m_cMesh = CAssetManager::GetInstance()->GetPrefabMesh("RemnantMesh");
	// Create a render mesh for the object

	m_cpRenderMesh = new CAnimationMesh(m_cMesh, GRAPHICS->GetSkinningVS(), GRAPHICS->GetNormalMapPS(), nullptr, nullptr, nullptr, L"../Game/Assets/Art/2D/Textures/RemnantDiffuse.dds");
	m_cpRenderMesh->SetNormals(L"../Game/Assets/Art/2D/Normal Maps/RemnantNormal.dds");
	// Set the animation mesh
	m_cpSword = new CSkeletonSword;

	XMMATRIX mSkele = XMMatrixIdentity();
	XMStoreFloat4x4(&m_mSkeleLocal, mSkele);

	//	AttachToJoint(m_cpSword->S(), LEFT_HAND);
	m_cpRenderMesh->GetRender() = false;

	m_cpAnimations[eRunAnim] = CAssetManager::GetInstance()->GetAnimation("RemnantRun");
	m_cpAnimations[eRunAnim].SetLooping(true);

	

	m_cpAnimations[eBlockWalkAnim] = CAssetManager::GetInstance()->GetAnimation("RemnantRun");
	m_cpAnimations[eBlockWalkAnim].SetLooping(true);

	m_cpAnimations[eAttackAnim] = CAssetManager::GetInstance()->GetAnimation("RemnantLightAttack1");
	m_cpAnimations[eAttackAnim].SetLooping(false);
	m_cpAnimations[eAttackAnim].SetScale(1.33f);

	m_cpAnimations[eDeathAnim] = CAssetManager::GetInstance()->GetAnimation("RemnantDeath1");
	m_cpAnimations[eDeathAnim].SetLooping(false);

	m_cpAnimations[eHurtAnim] = CAssetManager::GetInstance()->GetAnimation("RemnantHurt");
	m_cpAnimations[eHurtAnim].SetLooping(false);
	m_cpAnimations[eHurtAnim].SetScale(1.0f);

	m_cpAnimations[eHurt2Anim] = CAssetManager::GetInstance()->GetAnimation("RemnantHurt");
	m_cpAnimations[eHurt2Anim].SetLooping(false);

	m_cpAnimations[eSpawnAnim] = CAssetManager::GetInstance()->GetAnimation("RemnantSpawn1");
	m_cpAnimations[eSpawnAnim].SetLooping(false);
	m_cpAnimations[eSpawnAnim].SetScale(0.0f);

	m_pParticleManager = new CParticleManager(_manager);
	m_unParticleEmitters[eBoneParticle] = m_pParticleManager->LoadEmitter("BoneFragment.xml");
	m_unParticleEmitters[eDustParticle] = m_pParticleManager->LoadEmitter("BoneDust.xml");
	m_unParticleEmitters[eFadeAway] = m_pParticleManager->LoadEmitter("EnemyFadeAway.xml");

	for (unsigned int animation = 0; animation < eAnimCount; animation++)
	{
		m_cpAnimations[animation].SetAnimMesh((CAnimationMesh*)m_cpRenderMesh);
		m_cpAnimations[animation].IntializeAnimation();
	}

	// Add the starting animation
	m_cpAnimationManager->AddAnimation(&m_cpAnimations[eSpawnAnim]);

	// Set the current animaton
	m_unCurrAnim = eSpawnAnim;

	// Add collision box
	AddCollider(new CCollider(true, new CAABB(XMFLOAT3(m_mWorld._41, 55.0f, m_mWorld._43), XMFLOAT3(90.0f, 90.f, 90.f)), false));
	CCapsule* theCapsule = new CCapsule({ m_mWorld._41, 45.0f, m_mWorld._43 }, { m_mWorld._41, 240.0f, m_mWorld._43 }, 45.0f);
	AddCollider(new CCollider(true, theCapsule));

	((CAABB*)m_pvColliders[0]->GetBounds())->SetCenter({ m_mWorld._41, m_mWorld._42, m_mWorld._43 });


	// Create the attack instance
	AttachToJoint(m_cpSword->GetRenderMesh(), "RightHand");
	GRAPHICS->AddRenderMesh(m_cpSword->GetRenderMesh());
	m_cpAttack = new CAttack(this, CAssetManager::GetInstance()->GetPrefabMesh("OrcDagger"), &m_cpSword->GetRenderMesh()->GetPositionMatrix(), 20, "SkeletonAttack");
	m_cpAttack->SetParent(this);

	// Add the object to start attacking.
	CAddObjectMessage* addObj = new CAddObjectMessage(m_cpAttack, CObjectManager::Dynamic);

	// Send the message
	addObj->Send();

	SetWorldVelocity(XMFLOAT3(0.0f, 0.0f, 0.0f));

	
	GRAPHICS->AddRenderMesh(m_cpRenderMesh);
	GRAPHICS->AddLight(&m_vtPointLights[0]);


	m_ipCurrentState = SPAWN;
	EnterSubState();

	m_cpTheLoot = new CBone(m_cpObjectManager, this);
	m_cpThePowder = new CGunpowder(m_cpObjectManager, this);
}
void ETHEntityRenderingManager::AddDecomposedPieces(
	ETHRenderEntity* entity,
	const float minHeight,
	const float maxHeight,
	const ETHBackBufferTargetManagerPtr& backBuffer,
	const ETHSceneProperties& props)
{
	const VideoPtr& video = m_provider->GetVideo();
	const ETHShaderManagerPtr& shaderManager = m_provider->GetShaderManager();

	const bool spriteVisible = entity->IsSpriteVisible(props, backBuffer);
	
	// decompose entity sprite
	if (spriteVisible)
	{
		ETHEntityPieceRendererPtr spritePiece(
			new ETHEntitySpriteRenderer(
				entity,
				shaderManager,
				video,
				m_provider->AreLightmapsEnabled(),
				m_provider->AreRealTimeShadowsEnabled(),
				&m_lights));

		// add this entity to the multimap to sort it for an alpha-friendly rendering list
		const float depth = entity->ComputeDepth(maxHeight, minHeight);
		const float drawHash = ComputeDrawHash(video, depth, entity);

		// add the entity to the render map
		m_piecesToRender.insert(std::pair<float, ETHEntityPieceRendererPtr>(drawHash, spritePiece));
	}

	// decompose halo
	if (entity->HasLightSource() && entity->GetHalo())
	{
		const float haloZ = entity->GetPositionZ() + ((entity->GetType() == ETHEntityProperties::ET_VERTICAL) ? entity->GetCurrentSize().y : 0.0f);
		const float depth = ETHEntity::ComputeDepth(haloZ, maxHeight, minHeight);
		const float drawHash = ComputeDrawHash(video, depth, entity);

		ETHEntityPieceRendererPtr haloPiece(new ETHEntityHaloRenderer(entity, shaderManager, depth));
		m_piecesToRender.insert(std::pair<float, ETHEntityPieceRendererPtr>(drawHash, haloPiece));
	}

	// decompose the particle list for this entity
	if (entity->HasParticleSystems())
	{
		for (std::size_t t = 0; t < entity->GetNumParticleSystems(); t++)
		{
			ETHEntityPieceRendererPtr particlePiece(
				new ETHEntityParticleRenderer(entity, shaderManager, t));

			ETHParticleManagerPtr particle = entity->GetParticleManager(t);

			const float shift = ETHParticleManager::GetParticleDepthShift(ETHEntityProperties::ResolveDepthSortingMode(entity->GetType()));
			const float depth = ETHEntity::ComputeDepth(
				particle->GetZPosition() + entity->GetPositionZ() + shift,
				maxHeight,
				minHeight);

			const float drawHash = ComputeDrawHash(video, depth, entity);

			m_piecesToRender.insert(std::pair<float, ETHEntityPieceRendererPtr>(drawHash, particlePiece));
		}
	}

	// fill the light list for this frame
	if (entity->HasLightSource() && m_provider->IsRichLightingEnabled())
	{
		ETHLight light = *(entity->GetLight());
		light.color *= entity->ComputeLightIntensity();
		AddLight(BuildChildLight(light, entity->GetPosition(), entity->GetScale()), props);
	}
}
    TRef<Geo> Execute(const Matrix& mat, GroupGeo* pgroup)
    {
        ZString strName = pgroup->GetName();

        if (!strName.IsEmpty()) {
            if (   strName.Find("frm-") == 0
                    && (!pgroup->AnyChildGroups())
               ) {
                Vector vecPosition = mat.Transform(Vector(0, 0, 0));
                Vector vecForward  = mat.TransformDirection(Vector(0, 0, -1));
                Vector vecUp       = mat.TransformDirection(Vector(0, 1,  0));

                strName = strName.RightOf(4);

                if (strName.Find("SS") != -1) {
                    //
                    // a strobe light
                    //

                    ValueList* plist = pgroup->GetList();

                    if (plist->GetCount() == 1) {
                        MaterialGeo* pmatGeo;
                        CastTo(pmatGeo, plist->GetFirst());
                        Material* pmaterial = pmatGeo->GetMaterial();

                        AddLight(strName, pmaterial->GetDiffuse(), vecPosition);
                    } else {
                        AddLight(strName, Color(1, 1, 1), vecPosition);
                    }

                    return Geo::GetEmpty();
                } else if (
                    strName.Find("thrust") != -1
                    || strName.Find("smoke") != -1
                    || strName.Find("rocket") != -1
                ) {
                    //
                    // this is an engine
                    //

                    m_pframes->GetList().PushFront(
                        FrameData(strName, vecPosition, vecForward, vecUp)
                    );

                    return Geo::GetEmpty();
                } else if (
                    (strName.Find("weapon") != -1)
                    || (strName.Find("wepatt") != -1)
                    || (strName.Find("wepemt") != -1)
                    || (strName.Find("wepmnt") != -1)
                    || (strName.Find("trail")  != -1)
                ) {
                    //
                    // This is an attachment point
                    //

                    m_pframes->GetList().PushFront(
                        FrameData(strName, vecPosition, vecForward, vecUp)
                    );
                    return Geo::GetEmpty();
                } else if (
                    (strName.Find("garage") != -1)
                ) {
                    //
                    // This is a garage we need to leave the frame in the graph
                    //

                    m_pframes->GetList().PushFront(
                        FrameData(strName, vecPosition, vecForward, vecUp)
                    );
                }
            }
        }

        return NULL;
    }
Пример #16
0
void CLightMgr::Tick()
{
	int i;
	//거리에 따라 추려내고...
	int NumSlotEmpty = 0;
	float LimitLeft, LimitRight, LimitUp, LimitDown;
	LimitLeft = CN3Base::s_CameraData.vEye.x - LIGHT_VALIDRANGE;
	LimitRight = CN3Base::s_CameraData.vEye.x + LIGHT_VALIDRANGE;
	LimitUp = CN3Base::s_CameraData.vEye.z + LIGHT_VALIDRANGE;
	LimitDown = CN3Base::s_CameraData.vEye.z - LIGHT_VALIDRANGE;

	__Vector3 vPosTmp;
	for(i=LGT_ADDITIONAL0;i<LGT_MAX;i++)
	{
		if(!m_pActiveLight[i])
		{
			NumSlotEmpty++;
			continue;
		}

		vPosTmp = m_pActiveLight[i]->Pos();
		if(vPosTmp.x < LimitLeft || vPosTmp.x > LimitRight || vPosTmp.z < LimitDown || vPosTmp.z > LimitUp)
		{
			m_pActiveLight[i]->m_Data.bOn = false;
			m_pActiveLight[i]->Apply();

			AddLight(m_pActiveLight[i]);
			m_pActiveLight[i] = NULL;
			NumSlotEmpty++;

			continue;
		}
	}

	std::list<CN3Light*>::iterator it = m_Lights.begin();
	while(NumSlotEmpty>0 && it!=m_Lights.end())
	{
		CN3Light* pLgt = (*it);
		vPosTmp = pLgt->Pos();
		if(vPosTmp.x > LimitLeft && vPosTmp.x < LimitRight && vPosTmp.z > LimitDown && vPosTmp.z < LimitUp)
		{
			for(i=LGT_ADDITIONAL0;i<LGT_MAX;i++)
			{
				if(!m_pActiveLight[i])
				{
					m_pActiveLight[i] = pLgt;
					m_pActiveLight[i]->m_Data.bOn = true;
					m_pActiveLight[i]->m_Data.nNumber = i;
					NumSlotEmpty--;
					break;
				}
			}
			it = m_Lights.erase(it);
		}
		else it++;
	}

	//tick돌려라..
	for(i=0;i<LGT_MAX;i++)
	{
		if(m_pActiveLight[i])
		{
			m_pActiveLight[i]->Tick();
			m_pActiveLight[i]->Apply();
		}
	}
}
//Create sample data for the preview properties
void MaterialPreviewPropView::InitializePropTree(void)
{
	int i;
	CPropTreeItem		*pRoot;
	CPropTreeItem		*pParmRoot;
	CPropTreeItemCheck	*pCheck;
	CPropTreeItemEdit	*pEdit;

	pRoot = m_Tree.InsertItem(new CPropTreeItem());
	pRoot->SetLabelText(_T("Preview Properties"));
	pRoot->SetInfoText(_T("Properties for the preview window."));
	pRoot->Expand(); // have this item expanded by default

	CPropTreeItemCombo *pCombo;
	pCombo = (CPropTreeItemCombo *)m_Tree.InsertItem(new CPropTreeItemCombo(), pRoot);
	pCombo->SetLabelText(_T("Model Type"));
	pCombo->SetInfoText(_T("Select the type of model on which to preview the material."));
	pCombo->CreateComboBox();
	pCombo->InsertString(0, "Cube");
	pCombo->InsertString(1, "Box - 2:1");
	pCombo->InsertString(2, "Box - 4:1");
	pCombo->InsertString(3, "Box - 1:2");
	pCombo->InsertString(4, "Box - 1:4");
	pCombo->InsertString(5, "Cylinder - V");
	pCombo->InsertString(6, "Cylinder - H");
	pCombo->InsertString(7, "Sphere");
	pCombo->SetItemData(0, 0);
	pCombo->SetItemData(1, 1);
	pCombo->SetItemData(2, 2);
	pCombo->SetItemData(3, 3);
	pCombo->SetItemData(4, 4);
	pCombo->SetItemData(5, 5);
	pCombo->SetItemData(6, 6);
	pCombo->SetItemData(7, 7);

	pCombo->SetCurSel(0);

	// Custom model entry
	/*pEdit = (CPropTreeItemEdit*)m_Tree.InsertItem( new CPropTreeItemEdit(), pRoot );
	pEdit->SetLabelText(_T("Custom Model"));
	pEdit->SetInfoText(_T("Specify any model to display the current material."));
	pEdit->SetItemValue((LPARAM)_T(""));*/
	CPropTreeItemEditButton *pCutomButton;
	pCutomButton = (CPropTreeItemEditButton *)m_Tree.InsertItem(new CPropTreeItemEditButton(), pRoot);
	pCutomButton->SetButtonText(_T("..."));
	pCutomButton->SetLabelText(_T("Custom Model"));
	pCutomButton->SetInfoText(_T("Specify any model to display the current material."));
	pCutomButton->SetItemValue((LPARAM)_T(""));

	// Checkbox for showing debug light spheres
	pCheck = (CPropTreeItemCheck *)m_Tree.InsertItem(new CPropTreeItemCheck(), pRoot);
	pCheck->SetLabelText(_T("Show Lights"));
	pCheck->SetInfoText(_T("Show the light origin sphere and number in the preview."));
	pCheck->CreateCheckBox();
	pCheck->SetCheckState(BST_CHECKED);

	// Local and Global shader parms
	pParmRoot = m_Tree.InsertItem(new CPropTreeItem());
	pParmRoot->SetLabelText(_T("Local Parms"));
	pParmRoot->SetInfoText(_T("Local shaderparms for the model being displayed."));
	pParmRoot->Expand(FALSE);   // have this item NOT expanded by default

	for (i = 0; i < MAX_ENTITY_SHADER_PARMS; i++) {
		pEdit = (CPropTreeItemEdit *)m_Tree.InsertItem(new CPropTreeItemEdit(), pParmRoot);
		pEdit->SetLabelText(_T(va("parm%d", i)));
		pEdit->SetInfoText(_T("Set the local shaderparm for the model"));

		if (i < 4) {
			pEdit->SetItemValue((LPARAM)_T("1"));
		} else {
			pEdit->SetItemValue((LPARAM)_T("0"));
		}
	}

	pParmRoot = m_Tree.InsertItem(new CPropTreeItem());
	pParmRoot->SetLabelText(_T("Global Parms"));
	pParmRoot->SetInfoText(_T("Global shaderparms for the renderworld being displayed."));
	pParmRoot->Expand(FALSE);   // have this item NOT expanded by default

	for (i = 0; i < MAX_GLOBAL_SHADER_PARMS; i++) {
		pEdit = (CPropTreeItemEdit *)m_Tree.InsertItem(new CPropTreeItemEdit(), pParmRoot);
		pEdit->SetLabelText(_T(va("global%d", i)));
		pEdit->SetInfoText(_T("Set the global shaderparm for the renderworld"));

		if (i < 4) {
			pEdit->SetItemValue((LPARAM)_T("1"));
		} else {
			pEdit->SetItemValue((LPARAM)_T("0"));
		}
	}

	// Lights

	pRoot = m_Tree.InsertItem(new CPropTreeItem());
	pRoot->SetLabelText(_T(""));
	pRoot->SetInfoText(_T(""));

	CPropTreeItemButton *pButton;
	pButton = (CPropTreeItemButton *)m_Tree.InsertItem(new CPropTreeItemButton());
	pButton->SetButtonText(_T(" Add Light "));
	pButton->SetLabelText(_T("Preview Lights"));
	pButton->SetInfoText(_T("Test the button."));

	pRoot = m_Tree.InsertItem(new CPropTreeItem());
	pRoot->SetLabelText(_T(""));
	pRoot->SetInfoText(_T(""));

	AddLight();
}
Пример #18
0
void World::build()
{ 
	pTracer = new RayCast(this);
	pCurrentCamera = new PinholeCamera();
	pAmbientLight = new AmbientLight();

	PointLight *light1 = new PointLight();
	light1->SetPosition(Point3D(10,10,-5));
	AddLight((Light*)light1);

	PointLight *light2 = new PointLight();
	light2->SetPosition(Point3D(100,100,-1500));
	AddLight((Light*)light2);

	pAmbientLight->ScaleRadiance(0.05f);
	pAmbientLight->SetColor(RGBColor(1.0f,1.0f,1.0f));

	Sphere *sp1 = new Sphere();
	Phong *mat1 = new Phong();
	mat1->SetKd(1.0f);
	mat1->SetCd(RGBColor(1.0f,1.0f,1.0f));
	mat1->SetKs(RGBColor(0.3f,0.3f,0.3f));
	mat1->SetExp(0.25f);
	sp1->SetCenter(Point3D(-100.0, 100.0, -100.0));
	sp1->SetRadius(100.0);
	sp1->SetMaterial(mat1);

	Sphere *sp2 = new Sphere();	
	Matte *mat2 = new Matte();
	mat2->SetKd(1.0f);
	mat2->SetCd(RGBColor(1.0f,0.0f,0.0f));
	sp2->SetCenter(Point3D(200.0, 200.0, -150.0));
	sp2->SetRadius(80.0);
	sp2->SetMaterial(mat2);

	Sphere *sp3 = new Sphere();
	Phong *mat3 = new Phong();
	mat3->SetKd(1.0f);
	mat3->SetCd(RGBColor(0.0f,0.0f,1.0f));
	mat3->SetKs(RGBColor(0.3f,0.3f,0.3f));
	mat3->SetExp(0.9f);
	sp3->SetCenter(Point3D(150.0, -100.0, -200.0));
	sp3->SetRadius(130.0);
	sp3->SetMaterial(mat3);

	Sphere *sp4 = new Sphere();
	Phong *mat4 = new Phong();
	mat4->SetKd(1.0f);
	mat4->SetCd(RGBColor(0.0f,1.0f,0.0f));
	mat4->SetKs(RGBColor(1.0f,1.0f,1.0f));
	mat4->SetExp(300.0f);
	sp4->SetCenter(Point3D(-200.0, -150.0, -100.0));
	sp4->SetRadius(130.0);
	sp4->SetMaterial(mat4);

	Sphere *sp5 = new Sphere();
	Reflective *mat5 = new Reflective();
	mat5->SetKd(1.0f);
	mat5->SetCd(RGBColor(0.0f,0.0f,0.0f));
	mat5->SetKs(RGBColor(1.0f,0.0f,0.0f));
	mat5->SetExp(1.0f);
	sp5->SetCenter(Point3D(-300.0, 150.0, 100.0));
	sp5->SetRadius(130.0);
	sp5->SetMaterial(mat5);

	Sphere *sp6 = new Sphere();
	Reflective *mat7 = new Reflective();
	mat7->SetKd(1.0f);
	mat7->SetCd(RGBColor(0.0f,1.0f,0.0f));
	mat7->SetKs(RGBColor(0.0f,0.1f,0.4f));
	mat7->SetExp(8.0f);
	sp6->SetCenter(Point3D(0.0, -150.0, 50.0));
	sp6->SetRadius(70.0);
	sp6->SetMaterial(mat7);

	Triangle *tr1 = new Triangle(Point3D(4000,-200,0),Point3D(-4500,-200,0),Point3D(0,-200,4000));
	Phong *mat8 = new Phong();
	mat8->SetKd(1.0f);
	mat8->SetCd(RGBColor(1.0f,1.0f,1.0f));
	mat8->SetKs(RGBColor(0.0f,0.1f,0.4f));
	mat8->SetExp(8.0f);
	tr1->SetMaterial(mat8);

	Mesh *mesh = new Mesh();
	//mesh->LoadFromFile("c:\\temp\\dragon.ply");
	//mesh->LoadFromFile("c:\\temp\\bunny.ply");
	mesh->LoadFromFile("c:\\temp\\hand.ply");
	//mesh->LoadFromFile("c:\\temp\\sphere.ply");

	//objects.push_back(sp1);
	//objects.push_back(sp2);
	//objects.push_back(sp3);
	//objects.push_back(sp4);
	//objects.push_back(sp5);
	//objects.push_back(sp6);
	//objects.push_back(tr1);
	AddObject(mesh);

	//materials
	materials.push_back(mat1);
	materials.push_back(mat2);
	materials.push_back(mat3);
	materials.push_back(mat4);
	materials.push_back(mat5);
	materials.push_back(mat7);
	materials.push_back(mat8);


	//build KD-Tree
	kdtree = new KdTree<GeoObject,GeoObjectAdapter,ShadeRec>(objects,KdTree<GeoObject,GeoObjectAdapter,ShadeRec>::MULTI_THREADED);
	kdtree->Build();
}
Пример #19
0
void Scene::Deserialization( const char* filename /* = nullptr */ )
{
	SAFE_DELETE(mRendererPtr);

	mFilename = filename;

	tinyxml2::XMLDocument doc;
	doc.LoadFile( filename );

	tinyxml2::XMLElement* pRootElement = doc.FirstChildElement();

	// ---------------------------------------Environment--------------------------------------------
	tinyxml2::XMLElement* pEnvironmentElement = pRootElement->FirstChildElement( "Environment" );
	if( pEnvironmentElement )
	{
		const char* str = pEnvironmentElement->Attribute( "type" );

		Environment* pEnvironment = Environment::Create( pEnvironmentElement->Attribute( "type" ) );
		pEnvironment->Deserialization( pEnvironmentElement );
		AddEnvironment( pEnvironment );
	}
	else
	{
		Environment* pEnvironment = new ConstantEnvironment;
		AddEnvironment( pEnvironment );
	}

	// -------------------------------------Primitive-------------------------------------------------
	tinyxml2::XMLElement* pPrimitiveElement = pRootElement->FirstChildElement( "primitive" );
	while( pPrimitiveElement )
	{
		Primitive* pPrimitive = new Primitive;
		pPrimitive->Deserialization( pPrimitiveElement );
		AddEntity( pPrimitive );
		AddLight( pPrimitive->GetAreaLight() );
		pPrimitiveElement = pPrimitiveElement->NextSiblingElement( "primitive" );
	}

	// ---------------------------------------Light--------------------------------------------------
	tinyxml2::XMLElement* pLightElement = pRootElement->FirstChildElement( "light" );
	while( pLightElement )
	{
		const char* LightType = pLightElement->Attribute( "type" );

		Light* light = Light::Create( LightType );
		light->Deserialization( pLightElement );
		AddLight( light );

		pLightElement = pLightElement->NextSiblingElement( "light" );
	}

	// --------------------------------------Film-----------------------------------------------------
	Film* film = new Film;
	tinyxml2::XMLElement* pFilmElement = pRootElement->FirstChildElement( "Film" );
	film->Deserialization( pFilmElement );

	// --------------------------------------Camera--------------------------------------------------
	tinyxml2::XMLElement* pCameraElement = pRootElement->FirstChildElement( "Camera" );
	const char* CameraType = pCameraElement->Attribute( "type" );

	mCameraPtr = Camera::Create( CameraType );
	mCameraPtr->SetFilm( film );
	mCameraPtr->Deserialization( pCameraElement );

	// --------------------------------------Integrator---------------------------------------------
	tinyxml2::XMLElement* pIntegratorRootElement = pRootElement->FirstChildElement( "Integrator" );
	const char* IntegratorType = pIntegratorRootElement->Attribute( "type" );

	mSurfaceIntegratorPtr = SurfaceIntegrator::Create( IntegratorType );
	mSurfaceIntegratorPtr->Deserialization( pIntegratorRootElement );

	// --------------------------------------Sampler--------------------------------------------------
	tinyxml2::XMLElement* pSamplerRootElement = pRootElement->FirstChildElement( "Sampler" );
	const char* SamplerType = pSamplerRootElement->Attribute( "type" );

	mSamplerPtr = Sampler::Create( SamplerType );
	mSamplerPtr->Deserialization( pSamplerRootElement );

	// --------------------------------------Renderer---------------------------------------------------
	tinyxml2::XMLElement* pRendererRootElement = pRootElement->FirstChildElement( "Renderer" );
	const char* RendererType = pRendererRootElement->Attribute( "type" );

	mRendererPtr = Renderer::Create( RendererType );
	mRendererPtr->Deserialization( pRendererRootElement );

	// -------------------------------------Build Acceleration Structure---------------------------------
	Grid* pGrid = new Grid;
	pGrid->Setup( this );

	mRendererPtr->SetProperty( mSamplerPtr , mCameraPtr , mSurfaceIntegratorPtr , pGrid );
}
Пример #20
0
void CreateMenus (void)
{
	{
		TwBar *bar = TwNewBar ("pentachoron");
		TwDefine ("pentachoron label='Pentachoron'");

		TwType rendermodeType;
		TwEnumVal rendermodeEV[] = {
			{ 0, "compose" },
			{ 1, "color" },
			{ 2, "normal" },
			{ 3, "specular" },
			{ 4, "depth" },
			{ 5, "glow" },
			{ 6, "shadow" }
		};
		rendermodeType = TwDefineEnum ("rendermode", rendermodeEV, 7);

		TwAddVarCB (bar, "FPS", TW_TYPE_UINT32,
								NULL, [&] (void *v, void*) {
									*(unsigned int*)v = fps;
								}, NULL, NULL);
		TwAddVarCB (bar, "rendermode", rendermodeType,
								[&] (const void *v, void*) {
									r->postprocess.SetRenderMode (*(unsigned int*)v);
								}, [&] (void *v, void*) {
									*(unsigned int*)v = r->postprocess.GetRenderMode ();
								}, NULL, NULL);
		TwAddVarCB (bar, "tile-based light culling", TW_TYPE_BOOLCPP,
								[&] (const void *v, void*) {
									r->composition.SetTileBased (*(bool*)v);
								}, [&] (void *v, void*){
									*(bool*)v = r->composition.GetTileBased ();
								}, NULL, NULL);
		TwAddVarCB (bar, "wireframe", TW_TYPE_BOOLCPP,
								[&] (const void *v, void*) {
									r->gbuffer.SetWireframe (*(bool*)v);
								}, [&] (void *v, void*) {
									*(bool*)v = r->gbuffer.GetWireframe ();
								}, NULL, NULL);
		TwAddVarCB (bar, "tesslevel", TW_TYPE_UINT32,
								[&] (const void *v, void*) {
									r->geometry.SetTessLevel (*(uint32_t*)v);
								}, [&] (void *v, void*) {
									*(uint32_t*)v = r->geometry.GetTessLevel ();
								}, NULL, "label='tessellation level' min=1 max=64");
		TwAddVarCB (bar, "displacement", TW_TYPE_FLOAT,
								[&] (const void *v, void*) {
									r->geometry.SetDisplacement (*(float*)v);
								}, [&] (void *v, void*) {
									*(float*)v = r->geometry.GetDisplacement ();
								}, NULL, "label='displacement' min=0 step=0.01");
	}
	{
		TwBar *bar = TwNewBar ("lights");
		TwDefine ("lights label='Lights' iconified=true");

		TwAddButton (bar, "add light", [&] (void*) {
				AddLight ();
			}, NULL, NULL);
		TwAddButton (bar, "remove", [&] (void*) {
				RemoveLight ();
			}, NULL, "label='remove light' visible=false");

		TwAddVarRW (bar, "active", TW_TYPE_UINT32,
								&active_light, "label='active light' visible=false"); 
		TwAddSeparator (bar, NULL, NULL);

		TwStructMember lightposDesc[] = {
			{ "x", TW_TYPE_FLOAT, offsetof (glm::vec4, x), "step=0.1" },
			{ "y", TW_TYPE_FLOAT, offsetof (glm::vec4, y), "step=0.1" },
			{ "z", TW_TYPE_FLOAT, offsetof (glm::vec4, z), "step=0.1" }
		};
		TwStructMember attenuationDesc[] = {
			{ "constant", TW_TYPE_FLOAT, offsetof (glm::vec4, x), "step=0.01" },
			{ "linear", TW_TYPE_FLOAT, offsetof (glm::vec4, y), "step=0.01" },
			{ "quadratic", TW_TYPE_FLOAT, offsetof (glm::vec4, z), "step=0.01" },
			{ "cull distance", TW_TYPE_FLOAT, offsetof (glm::vec4, w), "step=0.1" }
		};
		typedef struct spotparam {
			 float angle;
			 float penumbra_angle;
			 float exponent;
		} spotparam_t;
		TwStructMember spotDesc[] = {
			{ "angle", TW_TYPE_FLOAT,
				offsetof (spotparam_t, angle), "step=1 min=0 max=360" },
			{ "penumbra angle", TW_TYPE_FLOAT,
				offsetof (spotparam_t, penumbra_angle), "step=1 min=0 max=360" },
			{ "exponent", TW_TYPE_FLOAT,
				offsetof (spotparam_t, exponent), "step=0.1" }
		};
		
		TwType lightposType = TwDefineStruct ("lightpos", lightposDesc, 3,
																					sizeof (glm::vec4),
																					NULL, NULL);
		TwType spotdescType = TwDefineStruct ("spotdesc", spotDesc, 3,
																					sizeof (spotparam_t),
																					NULL, NULL);
		TwType attenuationType = TwDefineStruct ("attenuation", attenuationDesc, 4,
																						 sizeof (glm::vec4),
																						 NULL, NULL);
		TwAddVarCB (bar, "position", lightposType,
								[&] (const void *v, void*) {
									r->GetLight (active_light).position
										 = *(glm::vec4*)v;
									r->UpdateLight (active_light);
								}, [&] (void *v, void*) {
									*(glm::vec4*)v = r->GetLight (active_light).position;
								}, NULL, "visible=false");
		TwAddVarCB (bar, "direction", TW_TYPE_DIR3F,
								[&] (const void *v, void*) {
									r->GetLight (active_light).direction
										 = glm::vec4 (*(const glm::vec3*)v, 0.0f);
									r->UpdateLight (active_light);
								}, [&] (void *v, void*) {
									*(glm::vec3*)v
										 = glm::vec3 (r->GetLight (active_light).direction);
								}, NULL, "visible=false");
		TwAddVarCB (bar, "color", TW_TYPE_COLOR3F,
								[&] (const void *v, void*) {
									r->GetLight (active_light).color
										 = glm::vec4 (*(const glm::vec3*)v, 1.0f);
									r->UpdateLight (active_light);
								}, [&] (void *v, void*) {
									*(glm::vec3*)v
										 = glm::vec3 (r->GetLight (active_light).color);
								}, NULL, "visible=false");
		TwAddVarCB (bar, "spot", spotdescType,
								[&] (const void *v, void*) {
									Light &light = r->GetLight (active_light);
									light.spot.exponent = ((spotparam_t*)v)->exponent;
									light.spot.angle = (((spotparam_t*)v)->angle)
										 * PCH_PI / 180.0f;
									light.spot.cosine = cosf (light.spot.angle);
									light.spot.tangent = tanf (light.spot.angle);
									light.spot.penumbra_angle
										 = ((spotparam_t*)v)->penumbra_angle * PCH_PI / 180.0f;
									light.spot.penumbra_cosine
										 = cosf (light.spot.penumbra_angle);
									r->UpdateLight (active_light);
								}, [&] (void *v, void*){
									const Light &light = r->GetLight (active_light);
									((spotparam_t*)v)->exponent = light.spot.exponent;
									((spotparam_t*)v)->angle = light.spot.angle
										 * 180.0f / PCH_PI;
									((spotparam_t*)v)->penumbra_angle
										 = light.spot.penumbra_angle * 180.0f / PCH_PI;
								}, NULL, "visible=false");
		TwAddVarCB (bar, "attenuation", attenuationType,
								[&] (const void *v, void*) {
									r->GetLight (active_light).attenuation
										 = *(glm::vec4*)v;
									r->GetLight (active_light).attenuation.z /= 100.0f;
									r->UpdateLight (active_light);
								}, [&] (void *v, void*) {
									*(glm::vec4*)v = r->GetLight (active_light).attenuation;
									((glm::vec4*)v)->z *= 100.0f;
								}, NULL, "visible=false");
		TwAddVarCB (bar, "specular", TW_TYPE_COLOR3F,
								[&] (const void *v, void*) {
									r->GetLight (active_light).specular.color
										 = *(const glm::vec3*)v;
									r->UpdateLight (active_light);
								}, [&] (void *v, void*) {
									*(glm::vec3*)v
										 = r->GetLight (active_light).specular.color;
								}, NULL, "label='specular color' visible=false");
	}
	{
		TwBar *bar = TwNewBar ("sky");
		TwDefine ("sky label='Sky' iconified=true");

		typedef struct perezcoefficients {
			 union {
					struct {
						 float A, B, C, D, E;
					};
					float p[5];
			 };
		} perezcoefficients_t;
		TwStructMember perezDesc[] = {
			{ "Darkening/Brightening to the horizon",
				TW_TYPE_FLOAT, offsetof (perezcoefficients_t, A),
				"step=0.01" },
			{ "Luminance gradient near the horizon",
				TW_TYPE_FLOAT, offsetof (perezcoefficients_t, B),
				"step=0.01" },
			{ "Relative intensity of circumsolar region",
				TW_TYPE_FLOAT, offsetof (perezcoefficients_t, C),
				"step=0.01" },
			{ "Width of the circumsolar region",
				TW_TYPE_FLOAT, offsetof (perezcoefficients_t, D),
				"step=0.01" },
			{ "Relative backscatered light at the earth surface",
				TW_TYPE_FLOAT, offsetof (perezcoefficients_t, E),
				"step=0.01" }

		};
		TwType perezType = TwDefineStruct ("perez", perezDesc, 5,
																			 sizeof (perezcoefficients_t),
																			 NULL, NULL);

		TwAddVarCB (bar, "turbidity", TW_TYPE_FLOAT,
								[&] (const void *v, void*) {
									r->composition.SetTurbidity (*(const float*)v);
								}, [&] (void *v, void*) {
									*(float*)v = r->composition.GetTurbidity ();
								}, NULL, "step=0.1 min=1.0 max=10.0");
		TwAddVarCB (bar, "time", TW_TYPE_FLOAT,
								[&] (const void *v, void*) {
									r->composition.SetTimeOfDay (*(const float*)v);
								}, [&] (void *v, void*) {
									*(float*)v = r->composition.GetTimeOfDay ();
								}, NULL, "step=0.01 min=0.0 max=24.0");
		TwType monthType;
		TwEnumVal monthEV[] = {
			{  0, "January" },
			{  1, "February" },
			{  2, "March" },
			{  3, "April" },
			{  4, "May" },
			{  5, "June" },
			{  6, "July" },
			{  7, "August" },
			{  8, "September" },
			{  9, "October" },
			{ 10, "November" },
			{ 11, "December" }
		};
		monthType = TwDefineEnum ("month", monthEV, 12);
		TwAddVarCB (bar, "month", monthType,
								[&] (const void *v, void*) {
									int month, day;
									ToCalendarDate (r->composition.GetDate (), &month, &day);
									month = *(const unsigned int*)v;
									r->composition.SetDate (ToOrdinalDate (month, day));
								}, [&] (void *v, void*) {
									int month, day;
									ToCalendarDate (r->composition.GetDate (), &month, &day);
									*(unsigned int*)v = month;
								}, NULL, NULL);
		TwAddVarCB (bar, "day", TW_TYPE_UINT8,
								[&] (const void *v, void*) {
									int month, day;
									ToCalendarDate (r->composition.GetDate (), &month, &day);
									day = *(const unsigned char*)v;
									r->composition.SetDate (ToOrdinalDate (month, day));
								}, [&] (void *v, void*) {
									int month, day;
									ToCalendarDate (r->composition.GetDate (), &month, &day);
									*(unsigned char*)v = day;
								}, NULL, "min=1 max=31");
		TwAddVarCB (bar, "luminosity", TW_TYPE_FLOAT,
								[&] (const void *v, void*) {
									r->composition.SetSkyLuminosity (0.01f * *(const float*)v);
								}, [&] (void *v, void*) {
									*(float*)v = r->composition.GetSkyLuminosity () * 100.0f;
								}, NULL, "step=0.01");
		TwAddVarCB (bar, "latitude", TW_TYPE_FLOAT,
								[&] (const void *v, void*) {
									r->composition.SetLatitude (*(const float*)v);
								}, [&] (void *v, void*) {
									*(float*)v = r->composition.GetLatitude ();
								}, NULL, "step=0.1 min=0.0 max=90.0");
		TwAddVarCB (bar, "Y", perezType,
								[&] (const void *v, void*) {
									for (auto i = 0; i < 5; i++)
										 r->composition.SetPerezY
												(i, ((perezcoefficients_t*)v)->p[i]);
								}, [&] (void *v, void *) {
									for (auto i = 0; i < 5; i++)
										 ((perezcoefficients_t*)v)->p[i]
												= r->composition.GetPerezY (i);
								}, NULL, "label='Coefficients Y'");
		TwAddVarCB (bar, "x", perezType,
								[&] (const void *v, void*) {
									for (auto i = 0; i < 5; i++)
										 r->composition.SetPerezx
												(i, ((perezcoefficients_t*)v)->p[i]);
								}, [&] (void *v, void *) {
									for (auto i = 0; i < 5; i++)
										 ((perezcoefficients_t*)v)->p[i]
												= r->composition.GetPerezx (i);
								}, NULL, "label='Coefficients x'");
		TwAddVarCB (bar, "y", perezType,
								[&] (const void *v, void*) {
									for (auto i = 0; i < 5; i++)
										 r->composition.SetPerezy
												(i, ((perezcoefficients_t*)v)->p[i]);
								}, [&] (void *v, void *) {
									for (auto i = 0; i < 5; i++)
										 ((perezcoefficients_t*)v)->p[i]
												= r->composition.GetPerezy (i);
								}, NULL, "label='Coefficients y'");
	}
	{
		TwBar *bar = TwNewBar ("tonemapping");
		TwDefine ("tonemapping label='Tonemapping' iconified=true");

		TwEnumVal tonemappingmodeEV[] = {
			{  0, "Default" },
			{  1, "Reinhard" },
			{  2, "Logarithmic" },
			{  3, "URQ" },
			{  4, "Exponential" },
			{  5, "Drago" },
		};
		TwType tonemappingmodeType;
		tonemappingmodeType = TwDefineEnum ("tonemappingmode",
																				tonemappingmodeEV, 6);
		TwAddVarCB (bar, "Mode", tonemappingmodeType,
								[&] (const void *v, void*) {
									r->postprocess.SetTonemappingMode (*(const unsigned int*)v);
								}, [&] (void *v, void*) {
									*(unsigned int*)v
										 = r->postprocess.GetTonemappingMode ();
								}, NULL, NULL);
		TwAddVarCB (bar, "Image Key", TW_TYPE_FLOAT,
								[&] (const void *v, void*) {
									r->postprocess.SetImageKey (*(const float*)v);
								}, [&] (void *v, void*) {
									*(float*)v
										 = r->postprocess.GetImageKey ();
								}, NULL, "step=0.001 min=0.001 max=5.0");
		TwAddVarCB (bar, "White threshold", TW_TYPE_FLOAT,
								[&] (const void *v, void*) {
									r->postprocess.SetWhiteThreshold (*(const float*)v);
								}, [&] (void *v, void*) {
									*(float*)v = r->postprocess.GetWhiteThreshold ();
								}, NULL, "step=0.01 min=0.0 max=5.0");
		TwAddVarCB (bar, "Sigma", TW_TYPE_FLOAT,
								[&] (const void *v, void*) {
									r->postprocess.SetTonemappingSigma (*(const float*)v);
								}, [&] (void *v, void*) {
									*(float*)v = r->postprocess.GetTonemappingSigma ();
								}, NULL, "step=0.01 min=0.0 max=5.0");
		TwAddVarCB (bar, "Exponent", TW_TYPE_FLOAT,
								[&] (const void *v, void*) {
									r->postprocess.SetTonemappingExponent (*(const float*)v);
								}, [&] (void *v, void*) {
									*(float*)v = r->postprocess.GetTonemappingExponent ();
								}, NULL, "step=0.01 min=0.0");

		TwStructMember avglumDesc[] = {
			{ "constant", TW_TYPE_FLOAT, offsetof (glm::vec4, x), "step=0.01" },
			{ "linear", TW_TYPE_FLOAT, offsetof (glm::vec4, y), "step=0.01" },
			{ "delta", TW_TYPE_FLOAT, offsetof (glm::vec4, z), "step=0.01" },
			{ "lod", TW_TYPE_FLOAT, offsetof (glm::vec4, w), "step=0.1" }
		};
		TwType avglumType = TwDefineStruct ("avglum", avglumDesc, 4,
																				sizeof (glm::vec4),
																				NULL, NULL);
		TwAddVarCB (bar, "avgLum", avglumType,
								[&] (const void *v, void*) {
									r->postprocess.SetAvgLumConst (((const glm::vec4*)v)->x);
									r->postprocess.SetAvgLumLinear (((const glm::vec4*)v)->y);
									r->postprocess.SetAvgLumDelta (((const glm::vec4*)v)->z);
									r->postprocess.SetAvgLumLod (((const glm::vec4*)v)->w);
								}, [&] (void *v, void*) {
									((glm::vec4*)v)->x = r->postprocess.GetAvgLumConst ();
									((glm::vec4*)v)->y = r->postprocess.GetAvgLumLinear ();
									((glm::vec4*)v)->z = r->postprocess.GetAvgLumDelta ();
									((glm::vec4*)v)->w = r->postprocess.GetAvgLumLod ();
								}, NULL, "label='Average Luminance'");
		TwEnumVal rgbworkingspaceEV[] = {
			{ 0, "Adobe RGB (1998)" },
			{  1, "AppleRGB" },
			{  2, "Best RGB" },
			{  3, "Beta RGB" },
			{  4, "Bruce RGB" },
			{  5, "CIE RGB" },
			{  6, "ColorMatch RGB" },
			{  7, "Don RGB 4" },
			{  8, "ECI RGB" },
			{  9, "Ekta Space PS5" },
			{ 10, "NTSC RGB" },
			{ 11, "PAL/SECAM RGB" },
			{ 12, "ProPhoto RGB" },
			{ 13, "SMPTE-C RGB" },
			{ 14, "sRGB" },
			{ 15, "Wide Gamut RGB" }
		};
		TwType rgbworkingspaceType;
		rgbworkingspaceType = TwDefineEnum ("rgbworkingspace",
																				rgbworkingspaceEV, 16);
		TwAddVarCB (bar, "RGB Working Space", rgbworkingspaceType,
								[&] (const void *v, void*) {
									r->postprocess.SetRGBWorkingSpace (*(const unsigned int*)v);
								}, [&] (void *v, void*) {
									*(unsigned int*)v
										 = r->postprocess.GetRGBWorkingSpace ();
								}, NULL, NULL);
	}
	{
		TwBar *bar = TwNewBar ("antialiasing");
		TwDefine ("antialiasing label='Antialiasing' iconified=true");
		TwEnumVal samplesEV[] = {
			{  0, "disabled" },
			{  4, "4x" },
			{  8, "8x" },
			{  12, "12x" },
			{  16, "16x" },
		};
		TwType samplesType;
		samplesType = TwDefineEnum ("samples",
																samplesEV, 5);
		TwAddVarCB (bar, "Mode", samplesType,
								[&] (const void *v, void*) {
									r->SetAntialiasing (*(const unsigned int*)v);
								}, [&] (void *v, void*) {
									*(unsigned int*)v
										 = r->GetAntialiasing ();
								}, NULL, NULL);
		TwAddVarCB (bar, "Threshold", TW_TYPE_FLOAT,
								[&] (const void *v, void*) {
									r->postprocess.SetAntialiasingThreshold
										 (0.01f * *(const float*)v);
								}, [&] (void *v, void*) {
									*(float*)v
										 = 100.0f * r->postprocess.GetAntialiasingThreshold ();
								}, NULL, "step=0.1 min=0.0");
	}
	{
		TwBar *bar = TwNewBar ("glow");
		TwDefine ("glow label='Glow' iconified=true");

		TwAddVarCB (bar, "blur size", TW_TYPE_UINT32,
								[&] (const void *v, void*) {
									r->composition.GetGlow ().SetSize (*(const unsigned int*)v);
								}, [&] (void *v, void*) {
									*(unsigned int*)v = r->composition.GetGlow ().GetSize ();
								}, NULL, "min=0 max=256");
		TwAddVarCB (bar, "luminance threshold", TW_TYPE_FLOAT,
								[&] (const void *v, void*) {
									r->composition.SetLuminanceThreshold (*(const float*)v);
								}, [&] (void *v, void*) {
									*(float*)v = r->composition.GetLuminanceThreshold ();
								}, NULL, "step=0.01 min=0");
// TODO: NOT YET REIMPLEMENTED!
		TwAddVarCB (bar, "limit", TW_TYPE_FLOAT,
								[&] (const void *v, void*) {
									r->composition.GetGlow ().SetLimit (*(const float*)v);
								}, [&] (void *v, void*) {
									*(float*)v = r->composition.GetGlow ().GetLimit ();
								}, NULL, "step=0.01 min=0 visible=false");
		TwAddVarCB (bar, "exponent", TW_TYPE_FLOAT,
								[&] (const void *v, void*) {
									r->composition.GetGlow ().SetExponent (*(const float*)v);
								}, [&] (void *v, void*) {
									*(float*)v = r->composition.GetGlow ().GetExponent ();
								}, NULL, "step=0.01 min=0 visible=false");
	}
	{
		TwBar *bar = TwNewBar ("parameter");
		TwDefine ("parameter label='Material Parameters' iconified=true");

		{
			std::vector<TwEnumVal> paramNames;
			for (auto i = 0; i < r->GetNumParameters (); i++)
			{
				paramNames.push_back (TwEnumVal ());
				paramNames.back ().Value = i;
				paramNames.back ().Label = r->GetParameterName (i).c_str ();
			}
			TwType paramnameType;
			paramnameType = TwDefineEnum ("paramname", &paramNames[0],
																		paramNames.size ());
			TwAddVarRW (bar, "active", paramnameType,
									&active_light, "label='active parameter set'"); 
		}
		TwAddSeparator (bar, NULL, NULL);

		TwEnumVal specmodelEV[] = {
			{ 0, "None" },
			{  1, "Gaussian" },
			{  2, "Phong" },
			{  3, "Beckmann" }
		};
		TwType specmodelType;
		specmodelType = TwDefineEnum ("specmodel",
																	specmodelEV, 4);

		typedef struct matspec {
			 unsigned int model;
			 float param1;
			 float param2;
			 float fresnel_n;
			 float fresnel_k;
		} matspec_t;
		TwStructMember matspecDesc[] = {
			{ "Specular Model",
				specmodelType, offsetof (matspec_t, model), NULL},
			{ "Smoothness/Shininess",
				TW_TYPE_FLOAT, offsetof (matspec_t, param1),
				"step=0.01" },
			{ "Gauss Factor/Ignored",
				TW_TYPE_FLOAT, offsetof (matspec_t, param2),
				"step=0.01" },
			{ "Fresnel n",
				TW_TYPE_FLOAT, offsetof (matspec_t, fresnel_n),
				"step=0.01" },
			{ "Fresnel k",
				TW_TYPE_FLOAT, offsetof (matspec_t, fresnel_k),
				"step=0.01" }

		};
		TwType matspecType = TwDefineStruct ("matspectype", matspecDesc, 5,
																				 sizeof (matspec_t),
																				 NULL, NULL);
		TwAddVarCB (bar, "matspec", matspecType,
								[&] (const void *v, void*) {
									Parameter &p = r->GetParameters (active_parameter);
									const matspec_t *m = (const matspec_t*) v;
									p.specular.model = m->model;
									p.specular.param1 = m->param1;
									p.specular.param2 = m->param2;
									p.specular.fresnel.n = m->fresnel_n;
									p.specular.fresnel.k = m->fresnel_k;
									r->UpdateParameters (active_parameter);
								}, [&] (void *v, void*) {
									Parameter &p = r->GetParameters (active_parameter);
									matspec_t *m = (matspec_t*) v;
									m->model = p.specular.model;
									m->param1 = p.specular.param1;
									m->param2 = p.specular.param2;
									m->fresnel_n = p.specular.fresnel.n;
									m->fresnel_k = p.specular.fresnel.k;
								}, NULL, "label='Specular Parameters'");

		typedef struct matrefl {
			 float factor;
			 float fresnel_n;
			 float fresnel_k;
		} matrefl_t;
		TwStructMember matreflDesc[] = {
			{ "Factor",
				TW_TYPE_FLOAT, offsetof (matrefl_t, factor),
				"step=0.01 min=0.0 max=1.0" },
			{ "Fresnel n",
				TW_TYPE_FLOAT, offsetof (matrefl_t, fresnel_n),
				"step=0.01" },
			{ "Fresnel k",
				TW_TYPE_FLOAT, offsetof (matrefl_t, fresnel_k),
				"step=0.01" }

		};
		TwType matreflType = TwDefineStruct ("matrefltype", matreflDesc, 3,
																				 sizeof (matrefl_t),
																				 NULL, NULL);
		TwAddVarCB (bar, "matrefl", matreflType,
								[&] (const void *v, void*) {
									Parameter &p = r->GetParameters (active_parameter);
									const matrefl_t *m = (const matrefl_t*) v;
									p.reflection.factor = m->factor;
									p.reflection.fresnel.n = m->fresnel_n;
									p.reflection.fresnel.k = m->fresnel_k;
									r->UpdateParameters (active_parameter);
								}, [&] (void *v, void*) {
									Parameter &p = r->GetParameters (active_parameter);
									matrefl_t *m = (matrefl_t*) v;
									m->factor = p.reflection.factor;
									m->fresnel_n = p.reflection.fresnel.n;
									m->fresnel_k = p.reflection.fresnel.k;
								}, NULL, "label='Reflection'");
	}
}
Пример #21
0
void SceneManager::LoadFromText(const char *text)
{
    TextParser parser;
    parser.Parse(text);
    TextParser::NODE *node = NULL;
    if ((node = parser.GetNode("FILETYPE")) && node->values[0] == "SCENE")
    {
        TextParser::NODE *node_data = parser.GetNode("DATA");
        if (node_data)
        {
            // Models
            TextParser::NODE *node_models = node_data->FindChild("MODELS");
            if (node_models)
            {
                for(size_t i=0;i<node_models->children.size();i++)
                {
                    TextParser::NODE *child = node_models->children[i];
                    TextParser::NODE *node_filename = NULL;
                    if ( child->name == "MODEL" && 
                        (node_filename = child->FindChild("FILENAME")))
                    {   // MODEL
                        Model *model = new Model(node_filename->values[0].GetCharPtr());
                        TextParser::NODE *node_position = child->FindChild("POSITION");
                        if (node_position) model->SetPosition(node_position->ToFVector3());
                        TextParser::NODE *node_scale = child->FindChild("SCALE");
                        if (node_scale) model->SetScale(node_scale->ToFVector3());
                        TextParser::NODE *node_rotation = child->FindChild("ROTATION");
                        if (node_rotation) model->SetRotation(node_rotation->ToFVector3());
                        mModels.push_back(model);
                    }
                }
            }

            // Lights
            TextParser::NODE *node_lights = node_data->FindChild("LIGHTS");
            if (node_lights)
            {
                for(size_t i=0;i<node_lights->children.size();i++)
                {
                    Light *light = NULL;
                    TextParser::NODE *child = node_lights->children[i];
                    TextParser::NODE *node_type = child->FindChild("TYPE");
                    if (node_type->values[0] == "Point")
                    {
                        light = new PointLight();
                    }
                    else if (node_type->values[0] == "Directional")
                    {
                        light = new DirectionalLight();
                    }
                    else if (node_type->values[0] == "Ambient")
                    {
                        light = new AmbientLight();
                    }
                    if (!light) continue;
                    TextParser::NODE *node_color = child->FindChild("COLOR");
                    if (node_color)
                    {
                        light->SetColor(node_color->ToFVector3());
                    }
                    TextParser::NODE *node_intensity = child->FindChild("INTENSITY");
                    if (node_intensity)
                    {
                        light->SetIntensity(node_intensity->values[0].ToFloat());
                    }
                    TextParser::NODE *node_pos = child->FindChild("POSITION");
                    if (node_pos && light->GetType() == Light::TYPE_POINT)
                    {
                        ((PointLight*)light)->SetPosition(node_pos->ToFVector3());
                    }
                    TextParser::NODE *node_scl = child->FindChild("SCALE");
                    if (node_scl && light->GetType() == Light::TYPE_POINT)
                    {
                        ((PointLight*)light)->SetScale(node_scl->ToFVector3());
                    }
                    switch(light->GetType())
                    {
                    case Light::TYPE_POINT:
                        {
                            TextParser::NODE *node_range = child->FindChild("RANGE");
                            if (node_range)
                            {
                                ((PointLight*)light)->SetRange(node_range->values[0].ToFloat());
                            }
                            TextParser::NODE *node_exp = child->FindChild("EXPONENT");
                            if (node_exp)
                            {
                                ((PointLight*)light)->SetExponent(node_exp->values[0].ToFloat());
                            }
                        } break;
                    }
                    AddLight(light);
                }
            }
        }
    }
}
Пример #22
0
// TODO-TO-DO: this method is too large...
bool ETHScene::RenderList(float &minHeight, float &maxHeight, SpritePtr pOutline, SpritePtr pInvisibleEntSymbol,
						  std::list<ETHRenderEntity*> &outParticles, std::list<ETHRenderEntity*> &outHalos, const bool roundUp)
{
	// This multimap will store all entities contained in the visible buckets
	// It will automatically sort entities to draw them in an "alpha friendly" order
	std::multimap<float, ETHRenderEntity*> mmEntities;

	// store the max and min height to assign when everything is drawn
	maxHeight = m_maxSceneHeight;
	minHeight = m_minSceneHeight;

	m_nRenderedEntities = 0;

	// don't let bucket size be equal to 0
	assert(GetBucketSize().x != 0 || GetBucketSize().y != 0);

	// Gets the list of visible buckets
	std::list<Vector2> bucketList;
	const Vector2& v2CamPos = m_provider->GetVideo()->GetCameraPos(); //for debugging pourposes
	ETHGlobal::GetIntersectingBuckets(bucketList, v2CamPos,
									m_provider->GetVideo()->GetScreenSizeF(), GetBucketSize(),
									IsDrawingBorderBuckets(), IsDrawingBorderBuckets());

	// Loop through all visible Buckets
	for (std::list<Vector2>::iterator bucketPositionIter = bucketList.begin(); bucketPositionIter != bucketList.end(); bucketPositionIter++)
	{
		ETHBucketMap::iterator bucketIter = m_buckets.Find(*bucketPositionIter);

		if (bucketIter == m_buckets.GetLastBucket())
			continue;

		if (bucketIter->second.empty())
			continue;

		ETHEntityList::const_iterator iEnd = bucketIter->second.end();
		for (ETHEntityList::iterator iter = bucketIter->second.begin(); iter != iEnd; iter++)
		{
			ETHSpriteEntity *pRenderEntity = (*iter);

			// update scene bounding for depth buffer
			maxHeight = Max(maxHeight, pRenderEntity->GetMaxHeight());
			minHeight = Min(minHeight, pRenderEntity->GetMinHeight());

			if (pRenderEntity->IsHidden())
				continue;

			// fill the light list for this frame
			// const ETHEntityFile &entity = pRenderEntity->GetData()->entity;
			if (pRenderEntity->HasLightSource())
			{
				ETHLight light = *(pRenderEntity->GetLight());
				// if it has a particle system in the first slot, adjust the light
				// brightness according to the number os active particles
				if (pRenderEntity->GetParticleManager(0) && !pRenderEntity->IsStatic())
				{
					boost::shared_ptr<ETHParticleManager> paticleManager = pRenderEntity->GetParticleManager(0);
					light.color *= 
						static_cast<float>(paticleManager->GetNumActiveParticles()) /
						static_cast<float>(paticleManager->GetNumParticles());
				}
				AddLight(light, pRenderEntity->GetPosition());
			}

			// add this entity to the multimap to sort it for an alpha-friendly rendering list
			const Vector3& v3Pos = pRenderEntity->GetPosition();
			const ETH_ENTITY_TYPE type = pRenderEntity->GetType();
			const float depth = pRenderEntity->ComputeDepth(maxHeight, minHeight);
			const float drawHash = ComputeDrawHash(depth, v2CamPos, v3Pos, type);

			// add the entity to the render map
			mmEntities.insert(std::pair<float, ETHRenderEntity*>(drawHash, *iter));
			m_nRenderedEntities++;
		}
	}

	// Draw visible entities ordered in an alpha-friendly map
	for (std::multimap<float, ETHRenderEntity*>::iterator iter = mmEntities.begin(); iter != mmEntities.end(); iter++)
	{
		ETHRenderEntity *pRenderEntity = (iter->second);

		m_provider->GetShaderManager()->BeginAmbientPass(pRenderEntity, maxHeight, minHeight);

		// draws the ambient pass and if we're at the editor, draw the collision box if it's an invisible entity
		#ifdef _ETHANON_EDITOR
		if (pOutline && pRenderEntity->IsInvisible() && pRenderEntity->Collidable())
		{
			pRenderEntity->DrawCollisionBox(true, pOutline, GS_WHITE, maxHeight, minHeight, m_sceneProps.zAxisDirection);
		}
		#endif

		m_provider->GetVideo()->RoundUpPosition(roundUp);
		pRenderEntity->DrawAmbientPass(m_maxSceneHeight, m_minSceneHeight, (m_enableLightmaps && m_showingLightmaps), m_sceneProps);

		// draw "invisible entity symbol" if we're in the editor
		#ifdef _ETHANON_EDITOR
		if (pOutline)
		{
			if (pRenderEntity->IsInvisible() && pRenderEntity->Collidable())
			{
				pRenderEntity->DrawCollisionBox(false, pOutline, GS_WHITE, maxHeight, minHeight, m_sceneProps.zAxisDirection);
			}
			if (pRenderEntity->IsInvisible() && !pRenderEntity->Collidable())
			{
				const float depth = m_provider->GetVideo()->GetSpriteDepth();
				m_provider->GetVideo()->SetSpriteDepth(1.0f);
				pInvisibleEntSymbol->Draw(pRenderEntity->GetPositionXY());
				m_provider->GetVideo()->SetSpriteDepth(depth);
			}
		}
		#endif

		// fill the halo list
		// const ETHEntityFile &entity = pRenderEntity->GetData()->entity;
		if (pRenderEntity->HasLightSource() && pRenderEntity->GetHalo())
		{
			outHalos.push_back(pRenderEntity);
		}

		// fill the particle list for this frame
		if (pRenderEntity->HasParticleSystems())
		{
			outParticles.push_back(pRenderEntity);
		}

		// fill the callback list
		m_tempEntities.AddCallbackWhenEligible(pRenderEntity);

		m_provider->GetShaderManager()->EndAmbientPass();

		//draw light pass
		for (std::list<ETHLight>::iterator iter = m_lights.begin(); iter != m_lights.end(); iter++)
		{
			if (!pRenderEntity->IsHidden())
			{
				if (!(pRenderEntity->IsStatic() && iter->staticLight && m_enableLightmaps))
				{
					m_provider->GetVideo()->RoundUpPosition(roundUp);
					if (m_provider->GetShaderManager()->BeginLightPass(pRenderEntity, &(*iter), m_maxSceneHeight, m_minSceneHeight, GetLightIntensity()))
					{
						pRenderEntity->DrawLightPass(GetZAxisDirection());
						m_provider->GetShaderManager()->EndLightPass();

						m_provider->GetVideo()->RoundUpPosition(false);
						if (AreRealTimeShadowsEnabled())
						{
							if (m_provider->GetShaderManager()->BeginShadowPass(pRenderEntity, &(*iter), m_maxSceneHeight, m_minSceneHeight))
							{
								pRenderEntity->DrawShadow(m_maxSceneHeight, m_minSceneHeight, m_sceneProps, *iter, 0);
								m_provider->GetShaderManager()->EndShadowPass();
							}
						}
						m_provider->GetVideo()->RoundUpPosition(roundUp);
					}
				}
			}
		}
	}

	mmEntities.clear();
	m_nCurrentLights = m_lights.size();

	// Show the buckets outline in debug mode
	#if defined _DEBUG || defined _ETHANON_EDITOR
	if (m_provider->GetInput()->IsKeyDown(GSK_PAUSE))
	{
		DrawBucketOutlines();
	}
	#endif

	return true;
}
Пример #23
0
/*
================
idExplodingBarrel::Think
================
*/
void idExplodingBarrel::Think( void ) {
	idBarrel::BarrelThink();

	#ifdef _DENTONMOD
		if ( thinkFlags & TH_UPDATEWOUNDPARTICLES )
			UpdateParticles();
	#endif

	if ( lightDefHandle >= 0 ){
		if ( state == BURNING ) {
			// ramp the color up over 250 ms
			float pct = (gameLocal.time - lightTime) / 250.f;
			if ( pct > 1.0f ) {
				pct = 1.0f;
			}
			light.origin = physicsObj.GetAbsBounds().GetCenter();
			light.axis = mat3_identity;
			light.shaderParms[ SHADERPARM_RED ] = pct;
			light.shaderParms[ SHADERPARM_GREEN ] = pct;
			light.shaderParms[ SHADERPARM_BLUE ] = pct;
			light.shaderParms[ SHADERPARM_ALPHA ] = pct;
			gameRenderWorld->UpdateLightDef( lightDefHandle, &light );
		} else {
			if ( gameLocal.time - lightTime > 250 ) {
				gameRenderWorld->FreeLightDef( lightDefHandle );
				lightDefHandle = -1;
			}
			return;
		}
	}

	if ( !gameLocal.isClient && state != BURNING && state != EXPLODING ) {
		BecomeInactive( TH_THINK );
		return;
	}

	// This condition fixes the problem where particleRenderEntity is used for explosion effect 
	// and it still tries to track the physics origin even after physics is put to rest.
#ifdef _DENTONMOD 
	if ( particleModelDefHandle >= 0 && state == BURNING ){
#else
	if ( particleModelDefHandle >= 0 ){
#endif
		particleRenderEntity.origin = physicsObj.GetAbsBounds().GetCenter();
		particleRenderEntity.axis = mat3_identity;
		gameRenderWorld->UpdateEntityDef( particleModelDefHandle, &particleRenderEntity );

	}
}

/*
================
idExplodingBarrel::AddParticles
================
*/
void idExplodingBarrel::AddParticles( const char *name, bool burn ) {
	if ( name && *name ) {
		if ( particleModelDefHandle >= 0 ){
			gameRenderWorld->FreeEntityDef( particleModelDefHandle );
		}
		memset( &particleRenderEntity, 0, sizeof ( particleRenderEntity ) );
		const idDeclModelDef *modelDef = static_cast<const idDeclModelDef *>( declManager->FindType( DECL_MODELDEF, name ) );
		if ( modelDef ) {
			particleRenderEntity.origin = physicsObj.GetAbsBounds().GetCenter();
			particleRenderEntity.axis = mat3_identity;
			particleRenderEntity.hModel = modelDef->ModelHandle();
			float rgb = ( burn ) ? 0.0f : 1.0f;
			particleRenderEntity.shaderParms[ SHADERPARM_RED ] = rgb;
			particleRenderEntity.shaderParms[ SHADERPARM_GREEN ] = rgb;
			particleRenderEntity.shaderParms[ SHADERPARM_BLUE ] = rgb;
			particleRenderEntity.shaderParms[ SHADERPARM_ALPHA ] = rgb;
			particleRenderEntity.shaderParms[ SHADERPARM_TIMEOFFSET ] = -MS2SEC( gameLocal.realClientTime );
			particleRenderEntity.shaderParms[ SHADERPARM_DIVERSITY ] = ( burn ) ? 1.0f : gameLocal.random.RandomInt( 90 );
			if ( !particleRenderEntity.hModel ) {
				particleRenderEntity.hModel = renderModelManager->FindModel( name );
			}
			particleModelDefHandle = gameRenderWorld->AddEntityDef( &particleRenderEntity );
			if ( burn ) {
				BecomeActive( TH_THINK );
			}
			particleTime = gameLocal.realClientTime;
		}
	}
}

/*
================
idExplodingBarrel::AddLight
================
*/
void idExplodingBarrel::AddLight( const char *name, bool burn ) {
	if ( lightDefHandle >= 0 ){
		gameRenderWorld->FreeLightDef( lightDefHandle );
	}
	memset( &light, 0, sizeof ( light ) );
	light.axis = mat3_identity;
	light.lightRadius.x = spawnArgs.GetFloat( "light_radius" );
	light.lightRadius.y = light.lightRadius.z = light.lightRadius.x;
	light.origin = physicsObj.GetOrigin();
	light.origin.z += 128;
	light.pointLight = true;
	light.shader = declManager->FindMaterial( name );
	light.shaderParms[ SHADERPARM_RED ] = 2.0f;
	light.shaderParms[ SHADERPARM_GREEN ] = 2.0f;
	light.shaderParms[ SHADERPARM_BLUE ] = 2.0f;
	light.shaderParms[ SHADERPARM_ALPHA ] = 2.0f;
	lightDefHandle = gameRenderWorld->AddLightDef( &light );
	lightTime = gameLocal.realClientTime;
	BecomeActive( TH_THINK );
}

/*
================
idExplodingBarrel::ExplodingEffects
================
*/
void idExplodingBarrel::ExplodingEffects( void ) {
	const char *temp;

	StartSound( "snd_explode", SND_CHANNEL_ANY, 0, false, NULL );

	temp = spawnArgs.GetString( "model_damage" );
	if ( *temp != '\0' ) {
		SetModel( temp );
		Show();
	}

	temp = spawnArgs.GetString( "mtr_lightexplode" );
	if ( *temp != '\0' ) {
		AddLight( temp, false );
	}

	temp = spawnArgs.GetString( "mtr_burnmark" );
	if ( *temp != '\0' ) {
		gameLocal.ProjectDecal( GetPhysics()->GetOrigin(), GetPhysics()->GetGravity(), 128.0f, true, 96.0f, temp );
	}
	// put the explosion particle effect to the end -- By Clone JCD
	temp = spawnArgs.GetString( "model_detonate" );
	if ( *temp != '\0' ) {
		AddParticles( temp, false );
	}
}

//ivan start
/*
================
idExplodingBarrel::SpawnDrops
================
*/
void idExplodingBarrel::SpawnDrops( void ){
	idVec3 offset;
	idStr offsetKey;
	const idKeyValue *kv = spawnArgs.MatchPrefix( "def_dropItem", NULL );
	while( kv ) {

		//get the offset
		offsetKey = kv->GetKey().c_str() + 4;
		offsetKey += "Offset";
		offset = spawnArgs.GetVector( offsetKey.c_str(), "0 0 0" );

		idMoveableItem::DropItem( kv->GetValue().c_str(), physicsObj.GetAbsBounds().GetCenter() + offset,physicsObj.GetAxis(), vec3_origin, 0, 0, false ); //don't drop to floor so offset is respected
		kv = spawnArgs.MatchPrefix( "def_dropItem", kv );
	}
}
Пример #24
0
void ETHScene::AddLight(const ETHLight &light, const Vector3& v3Pos)
{
	ETHLight childLight = light;
	childLight.pos += v3Pos;
	AddLight(childLight);
}
Пример #25
0
void TestFunction1(scene& scene1)
{

	AddSphere(scene1, vector3(1.5, -1.5, 0), 0.5, rgbf(0, 0, 1), false);
	//AddSphere(scene1, vector3(1, 1, 0), 0.5, rgbf(0, 1, 1), true);
		
	sphere_object* s1 = new sphere_object(0.5, vector3(1.5, -1, 0));
	s1->natrual_colour = rgbf(0, 0, 0);
	s1->reflective = true;
	s1->I_refl = 1;
	s1->k_spec = 1;	
	s1->ambient_colour = rgbf(0, 0, 0);
	s1->shininess = 100;
	//scene1.add_object(s1);

	sphere_object* s2 = new sphere_object(0.5, vector3(1.5, 1, 0));
	s2->transparent = true;
	s2->transparency = 0.9;
	s2->refindex = 0.9;
	scene1.add_object(s2);

	rgbf red(1, 0, 0);
	rgbf green(0, 1, 0);
	rgbf blue(0, 0, 1);
	rgbf yellow = red + green;
	rgbf magenta = red + blue;
	rgbf cyan = green + blue;


	AddWall(scene1, vector3(3, 0, -0.5), vector3(0, 1, 0), green * 0.7);
	AddWall(scene1, vector3(0, 3, -0.5), vector3(-1, 0, 0), red* 0.7);
	AddWall(scene1, vector3(-3, 0, -0.5), vector3(0, -1, 0), blue* 0.7);
	AddWall(scene1, vector3(0, -3, -0.5), vector3(1, 0, 0), yellow* 0.7);
	

	AddCeiling(scene1, vector3(0, 0, +3.5), magenta * 0.7);
	AddFloor(scene1, vector3(0, 0, -0.5), cyan * 0.7);

	//AddBox(scene1, vector3(1, -0.5, -0.3), 0.2, rgbf(1, 0, 1), true);

	box* box1 = new box(vector3(1, -0.5, 0), vector3(-0.2, -0.2, -0.2), vector3(0.2, 0.2, 0.2));
	box1->natrual_colour = rgbf(0, 0, 0);
	box1->reflective = false;
	box1->transparent = true;
	box1->transparency = 1;
	box1->I_refr = 1;
	box1->refindex = 2;
	scene1.add_object(box1);

	//AddLightBall(scene1, vector3(-0.8, 0, 3), 3, 0.1);

	AddLight(scene1, vector3(-1.5, 1.5, 3));
	//AddLight(scene1, vector3(2, 0, 4));
	//AddLight(scene1, vector3(-5, 3, 2));

	//IcoSphere(scene1, vector3(4, 0, 2));

	torus_object* tor1 = new torus_object(0.1,0.5,vector3(1,0,-0.5));
	tor1->natrual_colour = rgbf(1, 0, 0);	
	//tor1->ambient_colour = rgbf(0, 0, 0.5);
	//scene1.add_object(tor1);

	mesh* m1 = ReadMesh("teapot.obj", vector3(1, -0.25, -0.5));
	m1->natrual_colour = rgbf(0, 0, 0);
	m1->reflective = false;
	m1->transparent = true;
	m1->transparency = 1;
	m1->I_refr = 1;

	//scene1.add_object(m1);
	
	
}