Esempio n. 1
0
Vec3Df RayTracer::Brdf(const Vec3Df & camPos,
                       const Vec3Df & normal,
                       int idObj,
                       const Vec3Df & intersectionPoint,
                       float occlusion,
                       int PTRays){

    Scene * scene = Scene::getInstance ();
    std::vector<Light> lights = scene->getLights();
    Object & object = scene->getObjects()[idObj];
    Vec3Df ci;
    for(unsigned int i =0;i<lights.size();i++)
    {
        Light light = lights[i];
        Vec3Df n = normal;
        n.normalize();
        Vec3Df wi = light.getPos() - intersectionPoint;
        wi.normalize();
        Vec3Df w0 = (camPos-intersectionPoint);
        w0.normalize();
        Vec3Df r = 2*(Vec3Df::dotProduct(wi,n))*n-wi;
        r.normalize();
        float diffuse = Vec3Df::dotProduct(wi, n);
        float shininess = 11;
        float spec = pow(std::max(Vec3Df::dotProduct(r,w0),0.f),shininess);
        diffuse = std::max(diffuse,0.0f);
        Vec3Df lightColor = light.getColor();
        Material material = object.getMaterial();
        float matDiffuse = material.getDiffuse();
        float matSpecular = material.getSpecular();
        Vec3Df matDiffuseColor = material.getColor();
        Vec3Df matSpecularColor = material.getColor();

        Vec3Df intersectionPoint2;
        Vec3Df IntersPointNormal2;

        //Area Lighting
        float radius=0.3f;

        //Miroir
        if(scene->getObjects()[idObj].getRefl()>0 && activeMirror)
        {
            Vec3Df vDir= intersectionPoint-camPos;
            vDir.normalize();
            Vec3Df planA = Vec3Df::crossProduct(n, Vec3Df::crossProduct(vDir, n));
            Vec3Df newDir = Vec3Df::dotProduct(planA, vDir)*planA - Vec3Df::dotProduct(vDir, n)*n;
            float occ;
            int obj = getIntersectionPoint(intersectionPoint, newDir, intersectionPoint2, IntersPointNormal2, occ);
            if(obj>-1)
            {

                if(activeShadow)
                {
                    if(getIntersectionPoint(intersectionPoint,-intersectionPoint+light.getPos(),intersectionPoint2,IntersPointNormal2)==-1)
                    {
                        ci += Brdf(intersectionPoint,IntersPointNormal2,obj,intersectionPoint2,occ,0)*scene->getObjects()[idObj].getRefl();
                    }
                }
                else
                    ci += Brdf(intersectionPoint,IntersPointNormal2,obj,intersectionPoint2,occ,0)*scene->getObjects()[idObj].getRefl();
            }
        }

        //PathTracing
        if(activePT)
        {
            if(PTRays < depthPT)
            {
               for(int h=0; h< nbRayPT; h++)
                {
                    Vec3Df n1;
                    Vec3Df n2;

                    normal.getTwoOrthogonals(n1,n2);


                    float a = ((float)std::rand())/((float)RAND_MAX);
                    float b = ((float)std::rand())/((float)RAND_MAX)*2.-1.;
                    float c = ((float)std::rand())/((float)RAND_MAX)*2.-1.;

                    Vec3Df dir = normal*a+n1*b+n2*c;
                    dir.normalize();

                    int objPT = getIntersectionPoint(intersectionPoint,dir,intersectionPoint2,IntersPointNormal2);

                    ci+=Brdf(intersectionPoint,IntersPointNormal2,objPT,intersectionPoint2,0.,PTRays+1)/(nbRayPT*depthPT);
                }


            }



            //si pt<pt_max

            //lancer plein de rayons

            //contribution+=brdf(pt+1)
        }

        if(scene->getObjects()[idObj].getRefl()<1.0 || true)
        {
            if(nbRayShadow>0 && activeShadow)
                for(int p = 0;p<nbRayShadow;p++)
                {
                    float a = ((float)std::rand())/((float)RAND_MAX)*2.-1.;
                    float b = ((float)std::rand())/((float)RAND_MAX)*2.-1.;
                    float c = ((float)std::rand())/((float)RAND_MAX)*2.-1.;

                    float sum = a+b+c;
                    a=a/sum*radius;
                    b=b/sum*radius;
                    c=c/sum*radius;
                    Vec3Df lightposbis;

                    lightposbis[0]=light.getPos()[0]+a;
                    lightposbis[1]=light.getPos()[1]+b;
                    lightposbis[2]=light.getPos()[2]+c;

                    if(getIntersectionPoint(intersectionPoint,-intersectionPoint+lightposbis,intersectionPoint2,IntersPointNormal2)==-1)
                    {
                        ci += (((matDiffuse * diffuse * matDiffuseColor) +( matSpecular * spec * matSpecularColor*0.5))*lightColor)*255/nbRayShadow;
                    }
                }
            else if(activeShadow)
            {
                if(getIntersectionPoint(intersectionPoint,-intersectionPoint+light.getPos(),intersectionPoint2,IntersPointNormal2)==-1)
                {
                    ci += (((matDiffuse * diffuse * matDiffuseColor) +( matSpecular * spec * matSpecularColor*0.5))*lightColor)*255;
                }
            }
            else //sans ombre
            {
                ci += (((matDiffuse * diffuse * matDiffuseColor) +( matSpecular * spec * matSpecularColor*0.5))*lightColor)*255;
            }
            //ci += (((matDiffuse * diffuse * matDiffuseColor) +( matSpecular * spec * matSpecularColor*0.5))*lightColor)*255/nbrayshadow;
        }



    }

    if(activeAO) return ci*(1.f-occlusion);
    else return ci;
}
Esempio n. 2
0
Scene::Scene(const Scene & s)
	: Container(s)
{
	camera_ = shared_ptr<Camera>(new Camera(*(s.camera())));
}
Esempio n. 3
0
UINT WGRetUserDataHandler::Execute( WGRetUserData* pPacket, Player* pPlayer )
{
__ENTER_FUNCTION

	PlayerID_t PlayerID ;
	GamePlayer* pGamePlayer = NULL ;

	Assert( pPlayer ) ;
	
	if( pPlayer->IsServerPlayer() )
	{
		PlayerID = pPacket->GetPlayerID() ;
		pGamePlayer = g_pPlayerPool->GetPlayer(PlayerID) ;
		if( pGamePlayer==NULL )
		{
			Assert(FALSE) ;
			return PACKET_EXE_CONTINUE ;
		}
	}
	else if( pPlayer->IsGamePlayer() )
	{
		PlayerID = pPlayer->PlayerID() ;
		pGamePlayer = (GamePlayer*)pPlayer ;
	}
	else
	{
		Assert(FALSE) ;
		return PACKET_EXE_CONTINUE ;
	}

	if( pGamePlayer->GetPlayerStatus()==PS_SERVER_WAITING_FOR_SERVER_DATA )
	{//在ServerManager模块中执行部分
		Assert( MyGetCurrentThreadID()==g_pServerManager->m_ThreadID ) ;

		pGamePlayer->SetPlayerStatus( PS_SERVER_WAITING_FOR_SERVER_DATA_INCOMING ) ;

		g_pIncomingPlayerManager->SendPacket( pPacket, PlayerID ) ;

		g_pLog->FastSaveLog( LOG_FILE_1, "WGRetUserDataHandler::Execute(ret=%d) GUID=%X ServerPlayer...OK",
			pPacket->GetReturn(), pGamePlayer->m_HumanGUID ) ;

		return PACKET_EXE_NOTREMOVE ;
	}
	else if( pGamePlayer->GetPlayerStatus()==PS_SERVER_WAITING_FOR_SERVER_DATA_INCOMING )
	{//在IncomingPlayerManager模块中执行的
		Assert( MyGetCurrentThreadID()==g_pIncomingPlayerManager->m_ThreadID ) ;
	
		switch( pPacket->GetReturn() )
		{
		case UDR_NOTFINDUSERDATA:
			{
				g_pLog->FastSaveLog( LOG_FILE_1, "ERROR:WGRetUserDataHandler::Execute UDR_NOTFINDUSERDATA(PID=%d,GUID=%X)",
					pPacket->GetPlayerID(),pGamePlayer->m_HumanGUID ) ;

				return PACKET_EXE_ERROR ;
			}
			break ;
		case UDR_USERDATA:
			{
				GCConnect Msg ;
				Msg.SetServerID( g_pServerManager->GetServerID() ) ;
				//测试数据
				SceneID_t sceneid = pPacket->GetUserData()->m_Human.m_StartScene ;
				WORLD_POS enterpos = pPacket->GetUserData()->m_Human.m_Position ;
				Msg.SetSceneID( sceneid ) ;
				Msg.SetWorldPos( &enterpos ) ;
				Msg.SetEstate( 0 );
				//测试数据

				pGamePlayer->InitHuman( pPacket->GetUserData(),UDR_USERDATA, pPacket->GetPlayerAge() ) ;

				pGamePlayer->SetPlayerStatus( PS_SERVER_WAITING_FOR_ENTER ) ;

				pGamePlayer->SendPacket( &Msg ) ;

				g_pLog->FastSaveLog( LOG_FILE_1, "WGRetUserDataHandler::Execute(ret=%d) GUID=%X SceneID=%d Pos=(%.2f,%.2f)...OK ",
					pPacket->GetReturn(), pGamePlayer->m_HumanGUID, sceneid, enterpos.m_fX, enterpos.m_fZ ) ;
			
				return PACKET_EXE_CONTINUE ;
			}
			break ;
		
		case UDR_USERDATALIVING:
			{
				//取得已经用户此GUID数据的Obj_Human信息
				Obj_Human* pOldHuman = (Obj_Human*)(g_pGUIDManager->Get(pGamePlayer->m_HumanGUID)) ;
				if( pOldHuman==NULL )
				{
					GWNotifyUser* pMsg = (GWNotifyUser*)(g_pPacketFactoryManager->CreatePacket(PACKET_GW_NOTIFYUSER)) ;
					pMsg->SetGUID( pGamePlayer->m_HumanGUID ) ;
					pMsg->SetPlayerID( -1 ) ;
					pMsg->SetStatus( GWNotifyUser::NUS_NEED_WORLD_KICK ) ;
					g_pServerManager->SendPacket( pMsg, INVALID_ID ) ;

					g_pLog->FastSaveLog( LOG_FILE_1, "ERROR:WGRetUserDataHandler::Execute Cannot find HumanData (GUID=%X)",
						pGamePlayer->m_HumanGUID ) ;

					return PACKET_EXE_ERROR ;
				}
				//取得拥有此GUID的Obj_Human所在的场景指针
				Scene* pScene = pOldHuman->getScene() ;
				if( pScene==NULL )
				{
					GamePlayer* pOldPlayer = (GamePlayer*)(pOldHuman->GetPlayer()) ;
					if( pOldPlayer && pOldPlayer->GetPlayerStatus()==PS_SERVER_ENTER_RECYCLE )
					{
						g_pLog->FastSaveLog( LOG_FILE_1, "ERROR:WGRetUserDataHandler::Execute PS_SERVER_ENTER_RECYCLE (GUID=%X)",
							pGamePlayer->m_HumanGUID ) ;
					}
					else
					{
						GWNotifyUser* pMsg = (GWNotifyUser*)(g_pPacketFactoryManager->CreatePacket(PACKET_GW_NOTIFYUSER)) ;
						pMsg->SetGUID( pGamePlayer->m_HumanGUID ) ;
						pMsg->SetPlayerID( -1 ) ;
						pMsg->SetStatus( GWNotifyUser::NUS_NEED_WORLD_KICK ) ;
						g_pServerManager->SendPacket( pMsg, INVALID_ID ) ;

						g_pLog->FastSaveLog( LOG_FILE_1, "ERROR:WGRetUserDataHandler::Execute Scene==NULL (GUID=%X)",
							pGamePlayer->m_HumanGUID ) ;
					}

					return PACKET_EXE_ERROR ;
				}

				INT nStatus = ((GamePlayer*)(pOldHuman->GetPlayer()))->GetPlayerStatus() ;
				if( nStatus != PS_SERVER_NORMAL )
				{
					GWNotifyUser* pMsg = (GWNotifyUser*)(g_pPacketFactoryManager->CreatePacket(PACKET_GW_NOTIFYUSER)) ;
					pMsg->SetGUID( pGamePlayer->m_HumanGUID ) ;
					pMsg->SetPlayerID( -1 ) ;
					pMsg->SetStatus( GWNotifyUser::NUS_NEED_WORLD_KICK ) ;
					g_pServerManager->SendPacket( pMsg, INVALID_ID ) ;

					g_pLog->FastSaveLog( LOG_FILE_1, "ERROR:WGRetUserDataHandler::Execute GetPlayerStatus() != PS_SERVER_NORMAL (GUID=%X Status=%d)",
						pGamePlayer->m_HumanGUID, nStatus ) ;

					((GamePlayer*)(pOldHuman->GetPlayer()))->SetPlayerStatus(PS_SERVER_ANOTHER_GUID_ALSO_KICK) ;

					//向此场景发送当前消息
					pScene->SendPacket( pPacket, pOldHuman->GetPlayerID() ) ;

					return PACKET_EXE_NOTREMOVE_ERROR ;
				}

				((GamePlayer*)(pOldHuman->GetPlayer()))->SetPlayerStatus(PS_SERVER_ANOTHER_GUID_ENTER) ;
			
				//向此场景发送当前消息
				pScene->SendPacket( pPacket, pOldHuman->GetPlayerID() ) ;

				g_pLog->FastSaveLog( LOG_FILE_1, "WGRetUserDataHandler::Execute(ret=%d) UDR_USERDATALIVING GUID=%X SceneID=%d ...OK ",
					pPacket->GetReturn(), pGamePlayer->m_HumanGUID, pScene->SceneID() ) ;

				return PACKET_EXE_NOTREMOVE ;
			}
			break ;
		case UDR_USERSERVERCRASH: //取消对Server Crash 情况处理
			{
				g_pLog->FastSaveLog( LOG_FILE_1, "ERROR:WGRetUserDataHandler::Execute UDR_USERSERVERCRASH(PID=%d, GUID=%X)",
					pPacket->GetPlayerID(), pGamePlayer->m_HumanGUID ) ;

				return PACKET_EXE_ERROR ;
			}
			break;
		case UDR_KEYERROR:
			{
				g_pLog->FastSaveLog( LOG_FILE_1, "ERROR:WGRetUserDataHandler::Execute UDR_KEYERROR(PID=%d, GUID=%X)",
					pPacket->GetPlayerID(), pGamePlayer->m_HumanGUID ) ;

				return PACKET_EXE_ERROR ;
			}
			break ;
		default :
			{
				Assert(FALSE) ;
			}
			break ;
		}
	}
	else if( pGamePlayer->GetPlayerStatus()==PS_SERVER_ANOTHER_GUID_ENTER )
	{//旧的玩家所在的场景来执行 Scene
		Obj_Human* pHuman = pGamePlayer->GetHuman() ;
		Assert( pHuman ) ;

		Scene* pScene = pHuman->getScene() ;
		if( pScene==NULL )
		{
			g_pLog->FastSaveLog( LOG_FILE_1, "ERROR WGRetUserDataHandler::Scene==NULL(ret=%d) GUID=%X",
				pPacket->GetReturn(), pGamePlayer->m_HumanGUID) ;
			return PACKET_EXE_CONTINUE ;
		}

		//检测执行线程的数据是否正确
		Assert( MyGetCurrentThreadID()==pScene->m_ThreadID ) ;
		
		GamePlayer* pNewPlayer = g_pPlayerPool->GetPlayer( pPacket->GetPlayerID() ) ;
		Assert( pNewPlayer ) ;

		Obj_Human* pNewHuman = pNewPlayer->GetHuman() ;
		Assert( pNewHuman ) ;
		{//重设消息数据
			pPacket->SetReturn( UDR_USERDATA ) ;
			FULLUSERDATA* pData = pPacket->GetUserData() ;

			memcpy( &(pData->m_Human), pHuman->GetDB()->GetHumanDB(), sizeof(_HUMAN_DB_LOAD) ) ;
			memcpy( &(pData->m_Equip), pHuman->GetDB()->GetEquipDB(), sizeof(_EQUIP_DB_LOAD) ) ;
			memcpy( &(pData->m_Bag), pHuman->GetDB()->GetBag(), sizeof(_BAG_DB_LOAD) ) ;
			memcpy( &(pData->m_Bank), pHuman->GetDB()->GetBankDB(), sizeof(_BANK_DB_LOAD) ) ;
			memcpy( &(pData->m_Skill), pHuman->GetDB()->GetSkillDB(), sizeof(_SKILL_DB_LOAD) ) ;
			memcpy( &(pData->m_Cooldown), pHuman->GetDB()->GetCooldownDB(), sizeof(_COOLDOWN_DB_LOAD_FOR_HUMAN) ) ;
			memcpy( &(pData->m_XinFa), pHuman->GetDB()->GetXinFaDB(), sizeof(_XINFA_DB_LOAD) ) ;
			memcpy( &(pData->m_Impact), pHuman->GetDB()->GetImpactDB(), sizeof(_IMPACT_DB_LOAD) ) ;
			memcpy( &(pData->m_Ability), pHuman->GetDB()->GetAbilityDB(), sizeof(_ABILITY_DB_LOAD) ) ;
			memcpy( &(pData->m_Mission), pHuman->GetDB()->GetMissionDB(), sizeof(_MISSION_DB_LOAD) ) ;
			memcpy( &(pData->m_Setting), pHuman->GetDB()->GetSettingDB(), sizeof(_SETTING_DB_LOAD) ) ;
			memcpy( &(pData->m_PetList), pHuman->GetDB()->m_dbPetList, sizeof(_PET_DB_LIST_LOAD) ) ;
			memcpy( &(pData->m_Relation), pHuman->GetDB()->GetRelationDB(), sizeof(_RELATION_DB_LOAD) ) ;
			memcpy( &(pData->m_PrivateInfo), pHuman->GetDB()->GetPrivateInfoDB(), sizeof(_PRIVATE_INFO_DB_LOAD) ) ;
			// pData->m_bIsPasswdUnlock = pHuman->__IsPasswordUnlock(); // 此时不予设置
		}

		pGamePlayer->SetDirty( TRUE ) ;

		g_pIncomingPlayerManager->SendPacket( pPacket, pNewPlayer->PlayerID() ) ;

		g_pLog->FastSaveLog( LOG_FILE_1, "WGRetUserDataHandler::Execute(ret=%d) GUID=%X SceneID=%d IncomingPlayerManager...OK ",
			pPacket->GetReturn(), pGamePlayer->m_HumanGUID, pScene->SceneID() ) ;

		return PACKET_EXE_NOTREMOVE_ERROR ;
	}
	else if( pGamePlayer->GetPlayerStatus()==PS_SERVER_ANOTHER_GUID_ALSO_KICK )
	{
		Obj_Human* pHuman = pGamePlayer->GetHuman() ;
		Assert( pHuman ) ;

		Scene* pScene = pHuman->getScene() ;
		if( pScene==NULL )
		{
			g_pLog->FastSaveLog( LOG_FILE_1, "ERROR WGRetUserDataHandler::Scene==NULL(statuc=%d) GUID=%X",
				PS_SERVER_ANOTHER_GUID_ALSO_KICK, pGamePlayer->m_HumanGUID) ;
			return PACKET_EXE_CONTINUE ;
		}

		//检测执行线程的数据是否正确
		Assert( MyGetCurrentThreadID()==pScene->m_ThreadID ) ;

		g_pLog->FastSaveLog( LOG_FILE_1, "WGRetUserDataHandler::Execute(status=%d) GUID=%X SceneID=%d Kickout OldHuman...OK ",
			PS_SERVER_ANOTHER_GUID_ALSO_KICK, pGamePlayer->m_HumanGUID, pScene->SceneID() ) ;

		return PACKET_EXE_ERROR ;
	}

__LEAVE_FUNCTION

	return PACKET_EXE_ERROR ;
}
Esempio n. 4
0
// PathIntegrator Method Definitions
Spectrum PathIntegrator::Li(const RayDifferential &r, const Scene &scene,
                            Sampler &sampler, MemoryArena &arena,
                            int depth) const {
    ProfilePhase p(Prof::SamplerIntegratorLi);
    Spectrum L(0.f), alpha(1.f);
    RayDifferential ray(r);
    bool specularBounce = false;
    for (int bounces = 0;; ++bounces) {
        // Find next path vertex and accumulate contribution

        // Store intersection into _isect_
        SurfaceInteraction isect;
        bool foundIntersection = scene.Intersect(ray, &isect);

        // Possibly add emitted light and terminate
        if (bounces == 0 || specularBounce) {
            // Add emitted light at path vertex or from the environment
            if (foundIntersection)
                L += alpha * isect.Le(-ray.d);
            else
                for (const auto &light : scene.lights)
                    L += alpha * light->Le(ray);
        }
        if (!foundIntersection || bounces >= maxDepth) break;

        // Compute scattering functions and skip over medium boundaries
        isect.ComputeScatteringFunctions(ray, arena, true);
        if (!isect.bsdf) {
            ray = isect.SpawnRay(ray.d);
            bounces--;
            continue;
        }

        // Sample illumination from lights to find path contribution
        L += alpha * UniformSampleOneLight(isect, scene, sampler, arena);

        // Sample BSDF to get new path direction
        Vector3f wo = -ray.d, wi;
        Float pdf;
        BxDFType flags;
        Spectrum f = isect.bsdf->Sample_f(wo, &wi, sampler.Get2D(), &pdf,
                                          BSDF_ALL, &flags);
        if (f.IsBlack() || pdf == 0.f) break;
        alpha *= f * AbsDot(wi, isect.shading.n) / pdf;
        Assert(std::isinf(alpha.y()) == false);
        specularBounce = (flags & BSDF_SPECULAR) != 0;
        ray = isect.SpawnRay(wi);

        // Account for subsurface scattering, if applicable
        if (isect.bssrdf && (flags & BSDF_TRANSMISSION)) {
            // Importance sample the BSSRDF
            SurfaceInteraction pi;
            Spectrum S = isect.bssrdf->Sample_S(
                scene, sampler.Get1D(), sampler.Get2D(), arena, &pi, &pdf);
#ifndef NDEBUG
            Assert(std::isinf(alpha.y()) == false);
#endif
            if (S.IsBlack() || pdf == 0) break;
            alpha *= S / pdf;

            // Account for the direct subsurface scattering component
            L += alpha * UniformSampleOneLight(pi, scene, sampler, arena);

            // Account for the indirect subsurface scattering component
            Spectrum f = pi.bsdf->Sample_f(pi.wo, &wi, sampler.Get2D(), &pdf,
                                           BSDF_ALL, &flags);
            if (f.IsBlack() || pdf == 0.f) break;
            alpha *= f * AbsDot(wi, pi.shading.n) / pdf;
#ifndef NDEBUG
            Assert(std::isinf(alpha.y()) == false);
#endif
            specularBounce = (flags & BSDF_SPECULAR) != 0;
            ray = pi.SpawnRay(wi);
        }

        // Possibly terminate the path
        if (bounces > 3) {
            Float continueProbability = std::min((Float).5, alpha.y());
            if (sampler.Get1D() > continueProbability) break;
            alpha /= continueProbability;
            Assert(std::isinf(alpha.y()) == false);
        }
    }
    return L;
}
 // Calculate a target zoom level for display
 int targetZoomLevel(ViewState *viewState)
 {
     if (!viewState || !renderer || !scene)
         return minZoom;
     Point2f frameSize = renderer->getFramebufferSize();
     
     CoordSystemDisplayAdapter *coordAdapter = scene->getCoordAdapter();
     
     int zoomLevel = 0;
     // Start with the center (where we're looking) in model coordinates
     WhirlyKit::Point3d centerInModel = viewState->eyePos;
     // The coordinate adapter might have its own center
     Point3d adaptCenter = scene->getCoordAdapter()->getCenter();
     centerInModel += adaptCenter;
     if (!scene->getCoordAdapter()->isFlat())
     centerInModel.normalize();
     
     // Convert from model coordinates to the coord adapters local coordinates
     Point3d localPt = scene->getCoordAdapter()->displayToLocal(centerInModel);
     
     // Now convert into our coordinate system
     Point3d ourCenter = CoordSystemConvert3d(scene->getCoordAdapter()->getCoordSystem(), coordSys, localPt);
     Point2f ourCenter2d(ourCenter.x(),ourCenter.y());
     
     while (zoomLevel <= maxZoom)
     {
         WhirlyKit::Quadtree::Identifier ident;
         ident.x = 0;  ident.y = 0;  ident.level = zoomLevel;
         // Make an MBR right in the middle of where we're looking
         Mbr mbr = control->getQuadtree()->generateMbrForNode(ident);
         Point2f span = mbr.ur()-mbr.ll();
         mbr.ll() = ourCenter2d - span/2.0;
         mbr.ur() = ourCenter2d + span/2.0;
         // If that MBR is pushing the north or south boundaries, let's adjust it
         Mbr quadTreeMbr = control->getQuadtree()->getMbr();
         if (mbr.ur().y() > quadTreeMbr.ur().y())
         {
             double dy = mbr.ur().y() - quadTreeMbr.ur().y();
             mbr.ur().y() -= dy;
             mbr.ll().y() -= dy;
         } else
         if (mbr.ll().y() < quadTreeMbr.ll().y())
         {
             double dy = quadTreeMbr.ll().y() - mbr.ll().y();
             mbr.ur().y() += dy;
             mbr.ll().y() += dy;
         }
         // Also the east and west boundaries
         if (mbr.ur().x() > quadTreeMbr.ur().x())
         {
             double dx = mbr.ur().x() - quadTreeMbr.ur().x();
             mbr.ur().x() -= dx;
             mbr.ll().x() -= dx;
         } else
         if (mbr.ll().x() < quadTreeMbr.ll().x())
         {
             double dx = quadTreeMbr.ll().x() - mbr.ll().x();
             mbr.ur().x() += dx;
             mbr.ll().x() += dx;
         }
         Dictionary attrs;
         float import = ScreenImportance(viewState, frameSize, viewState->eyeVec, 1, coordSys, scene->getCoordAdapter(), mbr, ident, &attrs);
         if (import <= shortCircuitImportance/(importanceScale*importanceScale))
         {
             zoomLevel--;
             break;
         }
         zoomLevel++;
     }
     
     return std::min(zoomLevel,maxZoom);
 }
Esempio n. 6
0
UINT CGCharMoveHandler::Execute( CGCharMove* pPacket, Player* pPlayer )
{
__ENTER_FUNCTION
    GamePlayer* pGamePlayer = (GamePlayer*)pPlayer ;
    if ( pGamePlayer == NULL )
    {
        g_pLog->FastSaveLog( LOG_FILE_1, "CGCharMoveHandler: Error (pGamePlayer == NULL) " ) ;
        return PACKET_EXE_CONTINUE ;
    }

    Obj_Human* pHuman = pGamePlayer->GetHuman() ;
    if ( pHuman == NULL )
    {
        g_pLog->FastSaveLog( LOG_FILE_1, "CGCharMoveHandler: Error (pHuman == NULL) " ) ;
        return PACKET_EXE_CONTINUE ;
    }

    Scene* pScene = pHuman->getScene() ;
    if ( pScene == NULL )
    {
        g_pLog->FastSaveLog( LOG_FILE_1, "CGCharMoveHandler: Error Obj = %d (pScene == NULL) ", pHuman->GetID() ) ;
        return PACKET_EXE_CONTINUE ;
    }

    //检查线程执行资源是否正确
    Assert( MyGetCurrentThreadID()==pScene->m_ThreadID ) ;
    if ( MyGetCurrentThreadID() != pScene->m_ThreadID )
    {
        g_pLog->FastSaveLog( LOG_FILE_1, "CGCharMoveHandler: Error Obj = %d (MyGetCurrentThreadID() != pScene->m_ThreadID) ", pHuman->GetID() ) ;
        return PACKET_EXE_CONTINUE ;
    }

    const WORLD_POS* pCur = pHuman->getWorldPos();
    WORLD_POS posCur = *pCur;
    pScene->GetMap()->VerifyPos( &posCur ) ;

    if(pHuman->m_StallBox.GetStallStatus() == ServerStallBox::STALL_OPEN)
    {//摆摊中
        GCCharMoveResult msgResult;
        msgResult.setResult(OR_CAN_NOT_MOVE_STALL_OPEN);
        msgResult.setHandleID(pPacket->getHandleID());
        pGamePlayer->SendPacket( &msgResult ) ;

        g_pLog->FastSaveLog( LOG_FILE_1, "CGCharMoveHandler::摆摊中") ;
        return PACKET_EXE_CONTINUE ;
    }

    ObjID_t ObjID = pHuman->GetID() ;
    INT nHandleID = pPacket->getHandleID();
    WORLD_POS CurPos = *pHuman->getWorldPos() ;
    WORD wNumPathNode = (WORD)(pPacket->getNumTargetPos());
    WORLD_POS *paTarPos = (WORLD_POS *)pPacket->getTargetPos() ;
    ORESULT oResult = pHuman->GetHumanAI()->PushCommand_Move( nHandleID, wNumPathNode, paTarPos, TRUE );
    if ( OR_FAILED( oResult ) )
    {
        GCCharMoveResult msgResult;
        msgResult.setResult(oResult);
        msgResult.setHandleID(pPacket->getHandleID());
        if( oResult == OR_CUT_PATHROUTE && wNumPathNode > 0 )
        {
            for(WORD w = 0; w < wNumPathNode; w ++ )
            {
                msgResult.addTargetPos(paTarPos+w);
            }
        }
        else
        {
            pHuman->GetHumanAI()->PushCommand_Idle( ) ;
            pHuman->Teleport( &posCur ) ;
        }
        pGamePlayer->SendPacket( &msgResult ) ;
    }

    if ( wNumPathNode > 0 )
    {
        g_pLog->FastSaveLog( LOG_FILE_1, "CGCharMoveHandler::ObjID=%d X=%f Y=%f", 
            ObjID, paTarPos[wNumPathNode-1].m_fX, paTarPos[wNumPathNode-1].m_fZ ) ;
    }
    else
    {
        g_pLog->FastSaveLog( LOG_FILE_1, "CGCharMoveHandler::ObjID=%d , no target pos", ObjID ) ;
    }

    return PACKET_EXE_CONTINUE ;

__LEAVE_FUNCTION

    return PACKET_EXE_ERROR ;
}
Esempio n. 7
0
bool SceneConverter::convert()
{
    //
    // Construt the scene
    //
    FbxNode *node = m_scene->GetRootNode();
    std::list<FbxNode *> nodes;
    std::map<FbxNode *, SceneNode *> fbxNode2SceneNodes;
    Scene scene;

    nodes.push_back(node);
    SceneNode *sceneNode = makeSceneNode(node);
    scene.addNode(sceneNode);
    fbxNode2SceneNodes.insert(std::make_pair(node, sceneNode));

    while (!nodes.empty())
    {
        FbxNode *ret = nodes.front();
        nodes.pop_front();

        for (int i = 0; i < ret->GetChildCount(); i++)
        {
            FbxNode *child = ret->GetChild(i);
            
            // Only output visible nodes.
            if (child->GetVisibility() && child->Show.Get())
            {
                SceneNode *sceneNode = makeSceneNode(child);
                if (sceneNode != NULL)
                {
                    if (sceneNode->type == "camera")
                    {
                        // The first camera will be the main camera of the scene
                        scene.setCamera(sceneNode);
                    }
                    scene.addNode(sceneNode, fbxNode2SceneNodes[ret]);
                    fbxNode2SceneNodes.insert(std::make_pair(child, sceneNode));
                }
            
                nodes.push_back(child);
            }
        }
    }

    // Create a camera if it is not included in FBX. The camera is evaluated
    // using the bounding box of all visible nodes.
    if (m_numCameras == 0)
    {
        FbxVector4 rootBboxMin;
        FbxVector4 rootBboxMax;
        FbxVector4 rootBboxCenter;

        rootBboxMin = FbxVector4(FLT_MAX, FLT_MAX, FLT_MAX, FLT_MAX);
        rootBboxMax = FbxVector4(-FLT_MAX, -FLT_MAX, -FLT_MAX, -FLT_MAX);
    
        FbxNode *node = m_scene->GetRootNode();

        nodes.push_back(node);

        while (!nodes.empty())
        {
            FbxNode *ret = nodes.front();
            nodes.pop_front();

            for (int i = 0; i < ret->GetChildCount(); i++)
            {
                FbxNode *child = ret->GetChild(i);
                
                nodes.push_back(child);
            }
                
            if (ret->GetChildCount() == 0 &&
                ret->GetVisibility() && 
                ret->Show.Get() &&
                ret->GetMesh() != NULL)
            {
                FbxVector4 bboxMin;
                FbxVector4 bboxMax;
                FbxVector4 bboxCenter;

                ret->EvaluateGlobalBoundingBoxMinMaxCenter(bboxMin, bboxMax, bboxCenter);

                rootBboxMin[0] = std::min(rootBboxMin[0], bboxMin[0]);
                rootBboxMin[1] = std::min(rootBboxMin[1], bboxMin[1]);
                rootBboxMin[2] = std::min(rootBboxMin[2], bboxMin[2]);
                
                rootBboxMax[0] = std::max(rootBboxMax[0], bboxMax[0]);
                rootBboxMax[1] = std::max(rootBboxMax[1], bboxMax[1]);
                rootBboxMax[2] = std::max(rootBboxMax[2], bboxMax[2]);
            }
        }

        rootBboxCenter = (rootBboxMin + rootBboxMax) / 2;
        FbxVector4 rootBboxSize = rootBboxMax - rootBboxMin;
            
        SceneNode *sceneNode = new SceneNode();

        sceneNode->type = FbxString("camera");
        sceneNode->attributes.push_back(std::make_pair(FbxString("name"), FbxString("camera")));
        sceneNode->attributes.push_back(std::make_pair(FbxString("fixed"), FbxString("true")));

        double diag = sqrt(rootBboxSize[0] * rootBboxSize[0] + 
                           rootBboxSize[1] * rootBboxSize[1] + 
                           rootBboxSize[2] * rootBboxSize[2]) * 0.5;
            
        double eye = diag / tan(15.0 * FBXSDK_PI_DIV_180);

        double position[3];
        double up[3];
        double znear;
        double zfar;
            
        znear = eye - diag - 1.0f;
        zfar  = eye + diag + 1.0f;

        if (rootBboxSize[0] <= rootBboxSize[1] && rootBboxSize[0] <= rootBboxSize[2])
        {
            position[0] = eye + rootBboxCenter[0]; 
            position[1] = rootBboxCenter[1];
            position[2] = rootBboxCenter[2];

            up[0] = 0;
            up[1] = 1;
            up[2] = 0;
        }
        else if (rootBboxSize[1] <= rootBboxSize[0] && rootBboxSize[1] <= rootBboxSize[2])
        {
            position[0] = rootBboxCenter[0]; 
            position[1] = eye + rootBboxCenter[1];
            position[2] = rootBboxCenter[2];

            up[0] = 0;
            up[1] = 0;
            up[2] = 1;
        }
        else
        {
            position[0] = rootBboxCenter[0]; 
            position[1] = rootBboxCenter[1];
            position[2] = eye + rootBboxCenter[2];

            up[0] = 0;
            up[1] = 1;
            up[2] = 0;
        }

        char lookat[1024];
        char perspective[1024];
            
        FBXSDK_sprintf(lookat, 1024, "eye:%8.5f,%8.5f,%8.5f,center:%8.5f,%8.5f,%8.5f,up:%8.5f,%8.5f,%8.5f",
                    (float)position[0], (float)position[1], (float)position[2],
                    (float)rootBboxCenter[0], (float)rootBboxCenter[1], (float)rootBboxCenter[2],
                    (float)up[0], (float)up[1], (float)up[2]);
        sceneNode->attributes.push_back(std::make_pair(FbxString("lookat"), FbxString(lookat)));
            
        FBXSDK_sprintf(perspective, 1024, "perspective,fov:%8.5f,aspect:-1,znear:%8.5f,zfar:%8.5f",
                    30.0f, (float)znear, (float)zfar);
        sceneNode->attributes.push_back(std::make_pair(FbxString("projection"), FbxString(perspective)));
                    
        scene.setCamera(sceneNode);
        scene.addNode(sceneNode, scene.root());
    }

    //
    // Output the file.
    //
    //FbxString outputFilename = FbxPathUtils::GetFileName(m_arguments->FBXFileName.Buffer()).Lower();
    //outputFilename.FindAndReplace(".fbx", ".psc");
    FbxString outputFilename("scene.psc");
    FbxString path = FbxPathUtils::Bind(m_arguments->outputFolder, outputFilename.Buffer());
    bool ret = scene.output(path.Buffer());

    if (!ret)
    {
        FBXSDK_printf("Exporting failed!\n\n");
    }

    return ret;
}
Esempio n. 8
0
// return true to retry later (e.g. after display lost)
static bool MainLoop(bool retryCreate)
{
    TextureBuffer * eyeRenderTexture[2] = { nullptr, nullptr };
    DepthBuffer   * eyeDepthBuffer[2] = { nullptr, nullptr };
    ovrMirrorTexture mirrorTexture = nullptr;
    GLuint          mirrorFBO = 0;
    Scene         * roomScene = nullptr; 
    bool isVisible = true;
    long long frameIndex = 0;

    ovrSession session;
	ovrGraphicsLuid luid;
    ovrResult result = ovr_Create(&session, &luid);
    if (!OVR_SUCCESS(result))
        return retryCreate;

    ovrHmdDesc hmdDesc = ovr_GetHmdDesc(session);

    // Setup Window and Graphics
    // Note: the mirror window can be any size, for this sample we use 1/2 the HMD resolution
    ovrSizei windowSize = { hmdDesc.Resolution.w / 2, hmdDesc.Resolution.h / 2 };
    if (!Platform.InitDevice(windowSize.w, windowSize.h, reinterpret_cast<LUID*>(&luid)))
        goto Done;

    // Make eye render buffers
    for (int eye = 0; eye < 2; ++eye)
    {
        ovrSizei idealTextureSize = ovr_GetFovTextureSize(session, ovrEyeType(eye), hmdDesc.DefaultEyeFov[eye], 1);
        eyeRenderTexture[eye] = new TextureBuffer(session, true, true, idealTextureSize, 1, NULL, 1);
        eyeDepthBuffer[eye]   = new DepthBuffer(eyeRenderTexture[eye]->GetSize(), 0);

        if (!eyeRenderTexture[eye]->TextureChain)
        {
            if (retryCreate) goto Done;
            VALIDATE(false, "Failed to create texture.");
        }
    }

    ovrMirrorTextureDesc desc;
    memset(&desc, 0, sizeof(desc));
    desc.Width = windowSize.w;
    desc.Height = windowSize.h;
    desc.Format = OVR_FORMAT_R8G8B8A8_UNORM_SRGB;

    // Create mirror texture and an FBO used to copy mirror texture to back buffer
    result = ovr_CreateMirrorTextureGL(session, &desc, &mirrorTexture);
    if (!OVR_SUCCESS(result))
    {
        if (retryCreate) goto Done;
        VALIDATE(false, "Failed to create mirror texture.");
    }

    // Configure the mirror read buffer
    GLuint texId;
    ovr_GetMirrorTextureBufferGL(session, mirrorTexture, &texId);

    glGenFramebuffers(1, &mirrorFBO);
    glBindFramebuffer(GL_READ_FRAMEBUFFER, mirrorFBO);
    glFramebufferTexture2D(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texId, 0);
    glFramebufferRenderbuffer(GL_READ_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, 0);
    glBindFramebuffer(GL_READ_FRAMEBUFFER, 0);

    // Turn off vsync to let the compositor do its magic
    wglSwapIntervalEXT(0);

    // Make scene - can simplify further if needed
    roomScene = new Scene(false);

    // FloorLevel will give tracking poses where the floor height is 0
    ovr_SetTrackingOriginType(session, ovrTrackingOrigin_FloorLevel);

    // Main loop
    while (Platform.HandleMessages())
    {
        // Keyboard inputs to adjust player orientation
        static float Yaw(3.141592f);  
        if (Platform.Key[VK_LEFT])  Yaw += 0.02f;
        if (Platform.Key[VK_RIGHT]) Yaw -= 0.02f;

        // Keyboard inputs to adjust player position
        static Vector3f Pos2(0.0f,0.0f,-5.0f);
        if (Platform.Key['W']||Platform.Key[VK_UP])     Pos2+=Matrix4f::RotationY(Yaw).Transform(Vector3f(0,0,-0.05f));
        if (Platform.Key['S']||Platform.Key[VK_DOWN])   Pos2+=Matrix4f::RotationY(Yaw).Transform(Vector3f(0,0,+0.05f));
        if (Platform.Key['D'])                          Pos2+=Matrix4f::RotationY(Yaw).Transform(Vector3f(+0.05f,0,0));
        if (Platform.Key['A'])                          Pos2+=Matrix4f::RotationY(Yaw).Transform(Vector3f(-0.05f,0,0));

		// Animate the cube
        static float cubeClock = 0;
        roomScene->Models[0]->Pos = Vector3f(9 * (float)sin(cubeClock), 3, 9 * (float)cos(cubeClock += 0.015f));

	    // Call ovr_GetRenderDesc each frame to get the ovrEyeRenderDesc, as the returned values (e.g. HmdToEyeOffset) may change at runtime.
	    ovrEyeRenderDesc eyeRenderDesc[2];
	    eyeRenderDesc[0] = ovr_GetRenderDesc(session, ovrEye_Left, hmdDesc.DefaultEyeFov[0]);
	    eyeRenderDesc[1] = ovr_GetRenderDesc(session, ovrEye_Right, hmdDesc.DefaultEyeFov[1]);

        // Get eye poses, feeding in correct IPD offset
        ovrPosef                  EyeRenderPose[2];
        ovrVector3f               HmdToEyeOffset[2] = { eyeRenderDesc[0].HmdToEyeOffset,
                                                        eyeRenderDesc[1].HmdToEyeOffset };

        double sensorSampleTime;    // sensorSampleTime is fed into the layer later
        ovr_GetEyePoses(session, frameIndex, ovrTrue, HmdToEyeOffset, EyeRenderPose, &sensorSampleTime);

        if (isVisible)
        {
            for (int eye = 0; eye < 2; ++eye)
            {
                // Switch to eye render target
                eyeRenderTexture[eye]->SetAndClearRenderSurface(eyeDepthBuffer[eye]);

                // Get view and projection matrices
                Matrix4f rollPitchYaw = Matrix4f::RotationY(Yaw);
                Matrix4f finalRollPitchYaw = rollPitchYaw * Matrix4f(EyeRenderPose[eye].Orientation);
                Vector3f finalUp = finalRollPitchYaw.Transform(Vector3f(0, 1, 0));
                Vector3f finalForward = finalRollPitchYaw.Transform(Vector3f(0, 0, -1));
                Vector3f shiftedEyePos = Pos2 + rollPitchYaw.Transform(EyeRenderPose[eye].Position);

                Matrix4f view = Matrix4f::LookAtRH(shiftedEyePos, shiftedEyePos + finalForward, finalUp);
                Matrix4f proj = ovrMatrix4f_Projection(hmdDesc.DefaultEyeFov[eye], 0.2f, 1000.0f, ovrProjection_None);

                // Render world
                roomScene->Render(view, proj);

                // Avoids an error when calling SetAndClearRenderSurface during next iteration.
                // Without this, during the next while loop iteration SetAndClearRenderSurface
                // would bind a framebuffer with an invalid COLOR_ATTACHMENT0 because the texture ID
                // associated with COLOR_ATTACHMENT0 had been unlocked by calling wglDXUnlockObjectsNV.
                eyeRenderTexture[eye]->UnsetRenderSurface();

                // Commit changes to the textures so they get picked up frame
                eyeRenderTexture[eye]->Commit();
            }
        }

        // Do distortion rendering, Present and flush/sync
        
        ovrLayerEyeFov ld;
        ld.Header.Type  = ovrLayerType_EyeFov;
        ld.Header.Flags = ovrLayerFlag_TextureOriginAtBottomLeft;   // Because OpenGL.

        for (int eye = 0; eye < 2; ++eye)
        {
            ld.ColorTexture[eye] = eyeRenderTexture[eye]->TextureChain;
            ld.Viewport[eye]     = Recti(eyeRenderTexture[eye]->GetSize());
            ld.Fov[eye]          = hmdDesc.DefaultEyeFov[eye];
            ld.RenderPose[eye]   = EyeRenderPose[eye];
            ld.SensorSampleTime  = sensorSampleTime;
        }

        ovrLayerHeader* layers = &ld.Header;
        ovrResult result = ovr_SubmitFrame(session, frameIndex, nullptr, &layers, 1);

		// exit the rendering loop if submit returns an error, will retry on ovrError_DisplayLost
        if (!OVR_SUCCESS(result)) goto Done;

        isVisible = (result == ovrSuccess);

        ovrSessionStatus sessionStatus;
        ovr_GetSessionStatus(session, &sessionStatus);
        if (sessionStatus.ShouldQuit) {
			OutputDebugString( "ShouldQuit\n" );
            goto Done;
		}
        if (sessionStatus.ShouldRecenter) {
			OutputDebugString( "ShouldRecenter\n" );
            ovr_RecenterTrackingOrigin(session);
		}

        // Blit mirror texture to back buffer
        glBindFramebuffer(GL_READ_FRAMEBUFFER, mirrorFBO);
        glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
        GLint w = windowSize.w;
        GLint h = windowSize.h;
        glBlitFramebuffer(0, h, w, 0,
                          0, 0, w, h,
                          GL_COLOR_BUFFER_BIT, GL_NEAREST);
        glBindFramebuffer(GL_READ_FRAMEBUFFER, 0);

        SwapBuffers(Platform.hDC);
    
        frameIndex++;
    }

Done:
    delete roomScene;
    if (mirrorFBO) glDeleteFramebuffers(1, &mirrorFBO);
    if (mirrorTexture) ovr_DestroyMirrorTexture(session, mirrorTexture);
    for (int eye = 0; eye < 2; ++eye)
    {
        delete eyeRenderTexture[eye];
        delete eyeDepthBuffer[eye];
    }
    Platform.ReleaseDevice();
    ovr_Destroy(session);

    // Retry on ovrError_DisplayLost
    return retryCreate || OVR_SUCCESS(result) || (result == ovrError_DisplayLost);
}
Esempio n. 9
0
void InputTestApp::OnIdle()
{
    double curtime = pPlatform->GetAppTime();
	time_t t = time(0);   // get time now
	struct tm * now = localtime(&t);

 //   float  dt      = float(LastUpdate - curtime);
    LastUpdate     = curtime;
    
    if (pBox)
    {
		Vector3f acceldata = SFusion.GetAcceleration();
		Vector3f gyrodata = SFusion.GetAngularVelocity();
		Vector3f magdata = SFusion.GetMagnetometer();	

        Quatf q = SFusion.GetOrientation();
        pBox->SetOrientation(q);

		//fstream outFile;
		//outFile.open("C://Users//Barrett//Documents//oculus_sensor_data.txt");
		// Output the sensor data to the text file
		ofstream outFile("C://Users//Barrett//Documents//oculus_sensor_data.csv", ios::app);
		outFile << \
			now->tm_sec << "," << \
			curtime << "," << \
			acceldata.x << "," << acceldata.y << "," << acceldata.z << "," << \
			gyrodata.x << "," << gyrodata.y << "," << gyrodata.z << "," << \
			magdata.x << "," << magdata.y << "," << magdata.z << "," << \
			q.x << "," << q.y << "," << q.z << q.w << "\n";
		
   // Test Euler conversion, alternative to the above:
   //     Vector3f euler;
   //     SFusion.GetOrientation().GetEulerABC<Axis_Y, Axis_X, Axis_Z, Rotate_CCW, Handed_R>(&euler.y, &euler.x, &euler.z);
   //     Matrix4f mat = Matrix4f::RotationY(euler.y) * Matrix4f::RotationX(euler.x) * Matrix4f::RotationZ(euler.z);
   //  pBox->SetMatrix(mat);    

        // Update titlebar every 20th of a second.
        if ((curtime - LastTitleUpdate) > 0.05f)
        {
            char                          titleBuffer[512];
            SensorDevice::CoordinateFrame coord = SensorDevice::Coord_Sensor;
            if (pSensor)
                coord = pSensor->GetCoordinateFrame();

            OVR_sprintf(titleBuffer, 512, "OVR SensorBox %s %s  Ang: %0.3f",
                        (SFusion.IsGravityEnabled() ?  "" : "[Grav Off]"),
                        (coord == SensorDevice::Coord_HMD) ? "[HMD Coord]" : "",
                        CalcDownAngleDegrees(q));
            pPlatform->SetWindowTitle(titleBuffer);
            LastTitleUpdate = curtime;
        }
    }

    if (pBox2)
    {
        pBox2->SetOrientation(SFusion2.GetOrientation());
    }

    // Render
    int w, h;
    pPlatform->GetWindowSize(&w, &h);

    pRender->SetViewport(0, 0, w, h);

    pRender->Clear();
    pRender->BeginScene();

    pRender->SetProjection(Proj);
    pRender->SetDepthMode(1,1);
    
    Sc.Render(pRender, View);

    pRender->Present();

}
Esempio n. 10
0
UINT WGCallOfHumanHandler::Execute( WGCallOfHuman* pPacket, Player* pPlayer )
{
__ENTER_FUNCTION

    PlayerID_t PlayerID = pPacket->GetCallOfTargetPlayerID();
    GamePlayer* pGamePlayer = g_pPlayerPool->GetPlayer(PlayerID);
    if( pGamePlayer==NULL )
    {
        g_pLog->FastSaveLog( LOG_FILE_3, "WGCallOfHumanHandler::Execute pGamePlayer==NULL" );
        return PACKET_EXE_CONTINUE;
    }

    if (pGamePlayer->m_HumanGUID != pPacket->GetGUID())
    {
        g_pLog->FastSaveLog( LOG_FILE_3, "WGCallOfHumanHandler::Execute pGamePlayer->m_HumanGUID[%d] != pPacket->GetGUID()[%d]",pGamePlayer->m_HumanGUID, pPacket->GetGUID());
        return PACKET_EXE_CONTINUE;
    }

    Obj_Human* pHuman = pGamePlayer->GetHuman();
    Assert( pHuman );
    Scene* pScene = pHuman->getScene();
    if( pScene==NULL )
    {
        g_pLog->FastSaveLog( LOG_FILE_3, "WGCallOfHumanHandler::Execute pHuman->getScene() == NULL" );
        return PACKET_EXE_CONTINUE;
    }

    if( pPlayer->IsServerPlayer() )
    {//服务器收到世界服务器发来的数据
        Assert( MyGetCurrentThreadID()==g_pServerManager->m_ThreadID );

        pScene->SendPacket( pPacket, PlayerID );

        g_pLog->FastSaveLog( LOG_FILE_1, "WGCallOfHumanHandler: CallerGUID=%u, SceneID=%d, Pos=%f,%f, Duration=%u",
            pPacket->GetCallOfInfo()->m_guidCaller,
            pPacket->GetCallOfInfo()->m_SceneID,
            pPacket->GetCallOfInfo()->m_Pos.m_fX,
            pPacket->GetCallOfInfo()->m_Pos.m_fZ,
            pPacket->GetCallOfInfo()->m_uDuration);
        return PACKET_EXE_NOTREMOVE;
    }
    else if( pPlayer->IsGamePlayer() )
    {//场景收到Cache里的消息
        if(MyGetCurrentThreadID()!=pScene->m_ThreadID)
        {
            Assert( FALSE && "WGCallOfHumanHandler::Execute MyGetCurrentThreadID()!=pScene->m_ThreadID");
            return PACKET_EXE_CONTINUE;
        }

        const _CALLOF_INFO *pCallOfInfo = pPacket->GetCallOfInfo();
        pHuman->SetCallOfInfo(pCallOfInfo);

        g_pLog->FastSaveLog( LOG_FILE_1, "WGCallOfHumanHandler: CallerGUID=%u, SceneID=%d, Pos=%f,%f, Duration=%u",
            pPacket->GetCallOfInfo()->m_guidCaller,
            pPacket->GetCallOfInfo()->m_SceneID,
            pPacket->GetCallOfInfo()->m_Pos.m_fX,
            pPacket->GetCallOfInfo()->m_Pos.m_fZ,
            pPacket->GetCallOfInfo()->m_uDuration);
        return PACKET_EXE_CONTINUE ;
    }
    else
    {
        Assert(FALSE && "WGCallOfHumanHandler::Execute (!pPlayer->IsServerPlayer() && !pPlayer->IsGamePlayer())");
    }
    return PACKET_EXE_CONTINUE ;

__LEAVE_FUNCTION

    return PACKET_EXE_ERROR ;
}
Esempio n. 11
0
Scene* createScene() {
  Scene* scene = new Scene(100);

  scene->addObject(new Sphere(Point(0, 7, 2), 1, RGB(1, 0.3, 0.3)));
  scene->addObject(new Sphere(Point(-3, 11, -2), 2, RGB(0.3, 0.3, 1)));
  scene->addObject(new Sphere(Point(0, 8, -2), 1, RGB(0.3, 1, 0.3)));
  scene->addObject(new Sphere(Point(1.5, 7, 0.5), 1, RGB(0.5, 0.5, 0.5)));
  scene->addObject(new Sphere(Point(-2, 6, 1), 0.7, RGB(0.3, 1, 1)));
  scene->addObject(new Sphere(Point(2.2, 8, 0), 1, RGB(0.5, 0.5, 0.5)));
  scene->addObject(new Sphere(Point(4, 10, 1), 0.7, RGB(0.3, 0.3, 1)));

  scene->addLight(new Light(Point(-15, -15, 0), RGB(0.5, 0.5, 0.5)));
  scene->addLight(new Light(Point(1, 0, 1), RGB(0.5, 0.5, 0.5)));
  scene->addLight(new Light(Point(0, 6, -10), RGB(0.5, 0.5, 0.5)));

  return scene;
}
void	init(int argc, char** argv)
{
	Display*	disp;
	int		width;
	int		height;
	PNG_Reader	P;
	int		i;
	BMP_Loader	B;
	JPEG_Loader	J;
	Scene*		scene;
	struct	tex*	t;

	scene = Scene::GetInstance();
	i = 2;
	disp = Display::GetInstance();
	width = disp->screen_width;
	height = disp->screen_height;
	glutInit(&argc, argv);
	glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
	glutInitWindowSize(800, 800);
	glutInitWindowPosition(0, 0);
	glutCreateWindow("Bviewer");
	glutDisplayFunc(display);
	glutIdleFunc(display);
	glutReshapeFunc(resize);
	glutKeyboardFunc(keyboard);
	glutSpecialFunc(keyboard_s);
	glutMotionFunc(mouse);
	glutMouseFunc(callback);
	atexit(exit);
	glClearColor(0.0, 0.0, 1.0, 0.0);
	glShadeModel(GL_SMOOTH);
	glViewport(0, 0, width, height);
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	gluPerspective(45.0f, (GLfloat)width / (GLfloat)height, 1.0f, 10000.0f);
	glEnable(GL_DEPTH_TEST);
	glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
	while (i < argc)
	{
		t = new tex();
		t->name = strdup(argv[i]);
		t->id = P.loadPNGTexture(argv[i]);
		if (t->id == -1)
		{
			t->id = B.Read(argv[i]);
			if (t->id == -1)
			{	
				t->id = J.Load_JPEG(argv[i]);
				if (t->id != -1)
					scene->Add_Texture(t);
			}
			else
				scene->Add_Texture(t);
		}
		else
			scene->Add_Texture(t);
		i ++;
	}
	glEnable(GL_TEXTURE_2D);
}
Esempio n. 13
0
void IntensityGenerator::createScenes()
{
    m_odd = new Scene(m_doc);
    m_odd->setName("Intensity - Odd");

    m_even = new Scene(m_doc);
    m_even->setName("Intensity - Even");

    m_full = new Scene(m_doc);
    m_full->setName("Intensity - Full");

    m_zero = new Scene(m_doc);
    m_zero->setName("Intensity - Zero");

    // Create sequence & random scene lists
    int i = 0;
    QListIterator <Fixture*> it(m_fixtures);
    while (it.hasNext() == true)
    {
        Fixture* fxi(it.next());
        Q_ASSERT(fxi != NULL);

        Scene* sq = new Scene(m_doc);
        sq->setName(QString("Intensity - ") + fxi->name());
        m_sequence << sq;

        sq = new Scene(m_doc);
        sq->setName(QString("Intensity - Random - %1").arg(++i));
        m_random << sq;
    }

    // Go thru all fixtures
    for (int i = 0; i < m_fixtures.size(); i++)
    {
        Fixture* fxi = m_fixtures[i];
        Q_ASSERT(fxi != NULL);

        // Find such channels from the fixture that belong to the
        // given channel group.
        QList <quint32> channels = findChannels(fxi, QLCChannel::Intensity);

        // Insert values to member scenes for each found channel
        for (int j = 0; j < channels.size(); j++)
        {
            quint32 ch = channels.at(j);
            const QLCChannel* channel = fxi->channel(ch);
            Q_ASSERT(channel != NULL);

            uchar min = 0;
            uchar max = UCHAR_MAX;
            int modulo = i;

            // Find the minimum and maximum intensity values for
            // the current channel
            findMinMax(channel, &min, &max);

            // Set all intensity channels to max in the $full scene
            m_full->setValue(fxi->id(), ch, max);

            // Set all intensity channels to min in the $zero scene
            m_zero->setValue(fxi->id(), ch, min);

            // Create even & odd values
            if (fxi->isDimmer() == false)
                modulo = i; // For each intelligent fixture
            else
                modulo = j; // For each dimmer channel

            if ((modulo % 2) == 0)
            {
                m_even->setValue(fxi->id(), ch, max);
                m_odd->setValue(fxi->id(), ch, min);
            }
            else
            {
                m_even->setValue(fxi->id(), ch, min);
                m_odd->setValue(fxi->id(), ch, max);
            }

            // Create sequence and random values
            for (int s = 0; s < m_sequence.size(); s++)
            {
                if (s == i)
                    m_sequence[s]->setValue(fxi->id(), ch, max);
                else
                    m_sequence[s]->setValue(fxi->id(), ch, min);

                if ((rand() % 2) == 0)
                    m_random[s]->setValue(fxi->id(), ch, max);
                else
                    m_random[s]->setValue(fxi->id(), ch, min);
            }
        }
    }
}
Esempio n. 14
0
QImage RayTracer::render (const Vec3Df & camPos,
                          const Vec3Df & direction,
                          const Vec3Df & upVector,
                          const Vec3Df & rightVector,
                          float fieldOfView,
                          float aspectRatio,
                          unsigned int screenWidth,
                          unsigned int screenHeight) {
    QImage image (QSize (screenWidth, screenHeight), QImage::Format_RGB888);
    Scene * scene = Scene::getInstance ();
    std::vector<Light> lights = scene->getLights();
    Light light = lights[0];

    QProgressDialog progressDialog ("Raytracing...", "Cancel", 0, 100);
    progressDialog.show ();

    //#pragma omp parallel for
    for (unsigned int i = 0; i < screenWidth; i++) {
        progressDialog.setValue ((100*i)/screenWidth);
        for (unsigned int j = 0; j < screenHeight; j++) {


            float tanX = tan (fieldOfView)*aspectRatio;
            float tanY = tan (fieldOfView);

            //Nombre de découpe par dimension du pixel (Antialiasing)
            int aliaNb = 2;
            if(!activeAA) aliaNb=1;
            aliaNb++;

            Vec3Df c (backgroundColor);
            Vec3Df tempc(0.,0.,0.);
            for(int pixi=1; pixi<aliaNb; pixi++){
                for(int pixj=1; pixj<aliaNb; pixj++){
                    Vec3Df stepX = (float (i)-0.5+float(pixi)/float(aliaNb) - screenWidth/2.f)/screenWidth * tanX * rightVector;
                    Vec3Df stepY = (float (j)-0.5+float(pixj)/float(aliaNb) - screenHeight/2.f)/screenHeight * tanY * upVector;
                    Vec3Df step = stepX + stepY;

                    Vec3Df dir = direction + step;
                    dir.normalize ();
                    Vec3Df intersectionPoint;
                    Vec3Df IntersPointNormal;
                    float occlusion;

                    int idObj = getIntersectionPoint(camPos,dir,intersectionPoint,IntersPointNormal,occlusion);

                    if(idObj>=0)
                    {

                        tempc += Brdf(camPos, IntersPointNormal, idObj,intersectionPoint,occlusion,0)/std::pow(aliaNb-1,2);
                        c=tempc;

                    }
                }
            }

            image.setPixel (i, j, qRgb (clamp (c[0], 0, 255), clamp (c[1], 0, 255), clamp (c[2], 0, 255)));
        }
    }
    progressDialog.setValue (100);
    return image;
}
uint CGShopRepairHandler::Execute( CGShopRepair* pPacket, Player* pPlayer )
{
	__ENTER_FUNCTION

	GamePlayer* pGamePlayer = (GamePlayer*)pPlayer ;
	Assert( pGamePlayer ) ;

	Obj_Human* pHuman = pGamePlayer->GetHuman() ;
	Assert( pHuman ) ;

	Scene* pScene = pHuman->getScene() ;
	if( pScene==NULL )
	{
		Assert(FALSE) ;
		return PACKET_EXE_ERROR ;
	}
	//检查线程执行资源是否正确
	Assert( MyGetCurrentThreadID()==pScene->m_ThreadID ) ;

	BYTE	Opt         =	pPacket->GetOpt();
	BOOL	RepairAll	=	pPacket->IsRepairAll();		//修理全部
	BYTE	BagIndex	=	pPacket->GetBagIndex();		//包中的位置
	UINT	UniqueID	=	pPacket->GetUniqueID();

	SceneID_t	SceneID =	UniqueID>>16;
	ObjID_t		NpcObjID=	UniqueID&0x00ff;

	if(SceneID != pScene->SceneID())
	{
		g_pLog->FastSaveLog( LOG_FILE_1, "CGShopRepairHandler Illegal scene ObjName = %s", pHuman->GetName()) ;
		return PACKET_EXE_CONTINUE ; 
	}

	//距离判定
	Obj* pNpcObj = (Obj*) (pScene->GetObjManager()->GetObj(NpcObjID));
	if(pNpcObj == NULL)
	{
		g_pLog->FastSaveLog( LOG_FILE_1, "CGShopRepairHandler Illegal Obj ObjName = %s", pHuman->GetName()) ;
		return PACKET_EXE_CONTINUE ; 
	}

	FLOAT fDist = MySqrt(pNpcObj->getWorldPos(), pHuman->getWorldPos());

	if(fDist>MAX_NPC_DISTANCE)
	{
		g_pLog->FastSaveLog( LOG_FILE_1, "CGShopRepairHandler Out Of Range ObjName = %s", pHuman->GetName()) ;
		return PACKET_EXE_CONTINUE ; 
	}

	Item*	pCurItem = NULL;
	INT				MoneySpent = 0;
	INT				MoneyLast = 0;
	INT				MoneyHave  = pHuman->GetMoney();
	INT				RepairedIndex = 0;
	GCShopRepair	Msg;
	GCShopRepair::REPAIRED_ITEM	ItemList[MAX_REPAIRED_NUMBER];

	_SHOP*		pShop	=	pHuman->Shop( )	;
	if(!pShop)
	{
		g_pLog->FastSaveLog( LOG_FILE_1, "ERROR:CGShopRepairHandler Npc Shop Lose");
		return PACKET_EXE_CONTINUE;
	}

	if(Opt == CGShopRepair::FromBag)
	{
		if(RepairAll)
		{
			INT nBeginPoint	= 0;
			INT nEndPoint	= 0;
			switch( pShop->m_nRepairType )
			{
			case SHOP_All:
				{
					nBeginPoint = HEQUIP_WEAPON;
					nEndPoint	= HEQUIP_RIDER;
				}
				break;
			case SHOP_WEAPON:		//防具
				{
					nBeginPoint = HEQUIP_WEAPON;
					nEndPoint	= HEQUIP_WEAPON;
				}
				break;
			case SHOP_DEFENCE:		//饰物
				{
					nBeginPoint = HEQUIP_CAP;
					nEndPoint	= HEQUIP_BOOT;
				}
				break;
			case SHOP_ADORN:		//武器
				{
					nBeginPoint = HEQUIP_SASH;
					nEndPoint	= HEQUIP_RIDER;
				}
				break;
			default:
				{
					return PACKET_EXE_CONTINUE;
				}
				break;
			}


			for(INT i =nBeginPoint; i<=nEndPoint; i++)
			{
				pCurItem	= HumanItemLogic::GetEquip(pHuman,(HUMAN_EQUIP)i);
				//pCurItem = pHuman->GetEquip((HUMAN_EQUIP)i);
				if(!pCurItem->IsEmpty())
				{//有东西
					//判定是否狗修理等级
					if(pCurItem->GetRequireLevel() > pShop->m_nRepairLevel)
					{
						continue;
					}

					FLOAT fCur = (FLOAT)pCurItem->GetDurPoints();
					FLOAT fMax = (FLOAT)pCurItem->GetMaxDurPoint();
					FLOAT V	   = (FLOAT)pCurItem->GetPrice();

					if(fCur != fMax)
					{
						//if(fCur<fMax/3)
						//	MoneySpent += (INT)(7*V*V*fCur*6/(4*fMax)+V*V);
						//else if(fCur>=fMax/3&&fCur<fMax*2/3)
						//	MoneySpent += (INT)(V*V*fCur*6/fMax+V*V*3/4);
						//else if(fCur>=fMax*2/3&&fCur<fMax)
						//	MoneySpent += (INT)(V*V*fCur*6/(4*fMax)+V*V/4);
						MoneySpent += (INT) ( ((REPAIR_SPEND * (1- fCur/fMax) * V) * pShop->m_nRepairSpend) + 0.5);

						//临时的修理费计算方法
//						FLOAT scale = (FLOAT)(fCur/fMax);
//						scale = 1-scale;
//						MoneySpent += static_cast<INT>(pCurItem->GetPrice()*scale);
						if(MoneyHave<MoneySpent)
							break;
						MoneyLast	=	MoneySpent;
						HumanItemLogic::SetEquipDur(pHuman,(HUMAN_EQUIP)i, (INT)fMax);

						ItemList[RepairedIndex].IsIn		=	GCShopRepair::EQUIP;					
						ItemList[RepairedIndex++].BagIndex	=	(BYTE)i;
					}
				}
			}

			if(MoneyHave<MoneySpent)
			{//break出来的
				if(RepairedIndex)
				{
					pHuman->SetMoney(MoneyHave - MoneyLast);
					
					MONEY_LOG_PARAM	MoneyLogParam;
					MoneyLogParam.CharGUID	=	pHuman->GetGUID();
					MoneyLogParam.OPType	=	MONEY_SHOP_REPAIR;
					MoneyLogParam.Count		=	MoneyLast;
					MoneyLogParam.SceneID	=	pHuman->getScene()->SceneID();
					MoneyLogParam.XPos		=	pHuman->getWorldPos()->m_fX;
					MoneyLogParam.ZPos		=	pHuman->getWorldPos()->m_fZ;
					SaveMoneyLog(&MoneyLogParam);


					Msg.SetAll(0);
					Msg.SetReListNum(RepairedIndex);
					Msg.SetReList(ItemList);
					pHuman->GetPlayer()->SendPacket(&Msg);
				}

				GCShopBuy Msg ;
				Msg.SetBuyOk((BYTE)GCShopBuy::BUY_MONEY_FAIL);
				pHuman->GetPlayer()->SendPacket( &Msg ) ;
				g_pLog->FastSaveLog( LOG_FILE_1, "CGShopRepairHandler BUY_MONEY_FAIL") ;
				return PACKET_EXE_CONTINUE ;
			}
			else if(MoneySpent != 0)
			{//全修完了
				pHuman->SetMoney(MoneyHave - MoneySpent);
				MONEY_LOG_PARAM	MoneyLogParam;
				MoneyLogParam.CharGUID	=	pHuman->GetGUID();
				MoneyLogParam.OPType	=	MONEY_SHOP_REPAIR;
				MoneyLogParam.Count		=	MoneySpent;
				MoneyLogParam.SceneID	=	pHuman->getScene()->SceneID();
				MoneyLogParam.XPos		=	pHuman->getWorldPos()->m_fX;
				MoneyLogParam.ZPos		=	pHuman->getWorldPos()->m_fZ;
				SaveMoneyLog(&MoneyLogParam);

				Msg.SetAll(1);
				Msg.SetReListNum(0);
				pHuman->GetPlayer()->SendPacket(&Msg);
			}
		}
		else
		{//修理单个,一定应该在背包中
			pCurItem =	HumanItemLogic::GetItem(pHuman,BagIndex);
			if(!pCurItem->IsEmpty())
			{
				if(pCurItem->GetRequireLevel()>pShop->m_nRepairLevel)
				{
					g_pLog->FastSaveLog( LOG_FILE_1, "CGShopRepairHandler Npc have no the Repair Levle") ;
					return PACKET_EXE_CONTINUE;
				}
				BOOL bCanRepair = TRUE;
				switch( pShop->m_nRepairType )
				{
				case SHOP_All:
					{
					}
					break;
				case SHOP_DEFENCE:		//防具
					{
						if( pCurItem->GetEquipPoint() != HEQUIP_CAP &&
							pCurItem->GetEquipPoint() != HEQUIP_ARMOR &&
							pCurItem->GetEquipPoint() != HEQUIP_CUFF &&
							pCurItem->GetEquipPoint() != HEQUIP_BOOT )
						{
							bCanRepair = FALSE;
						}
					}
					break;
				case SHOP_ADORN:		//饰物
					{
						if( pCurItem->GetEquipPoint() != HEQUIP_SASH &&
							pCurItem->GetEquipPoint() != HEQUIP_RING &&
							pCurItem->GetEquipPoint() != HEQUIP_NECKLACE &&
							pCurItem->GetEquipPoint() != HEQUIP_RIDER)
						{
							bCanRepair = FALSE;
						}
					}
					break;
				case SHOP_WEAPON:		//武器
					{
						if( pCurItem->GetEquipPoint() != HEQUIP_WEAPON )
						{
							bCanRepair = FALSE;
						}
					}
					break;
				default:
					{
						bCanRepair = FALSE;
					}
					break;
				}

				if(bCanRepair == FALSE)
				{
					g_pLog->FastSaveLog( LOG_FILE_1, "CGShopRepairHandler Npc have no the Repair type") ;
					return PACKET_EXE_CONTINUE;
				}


				FLOAT fCur = (FLOAT)pCurItem->GetDurPoints();
				FLOAT fMax = (FLOAT)pCurItem->GetMaxDurPoint();
				FLOAT V	   = (FLOAT)pCurItem->GetPrice();
				if(fCur != fMax)
				{
					//if(fCur<fMax/3)
					//	MoneySpent += (INT)(7*V*V*fCur*6/(4*fMax)+V*V);
					//else if(fCur>=fMax/3&&fCur<fMax*2/3)
					//	MoneySpent += (INT)(V*V*fCur*6/fMax+V*V*3/4);
					//else if(fCur>=fMax*2/3&&fCur<fMax)
					//	MoneySpent += (INT)(V*V*fCur*6/(4*fMax)+V*V/4);
					MoneySpent += (INT) ( ((REPAIR_SPEND * (1- fCur/fMax) * V) * pShop->m_nRepairSpend) + 0.99);


					if(MoneyHave>=MoneySpent)
					{//可以修
						pHuman->SetMoney(MoneyHave - MoneySpent);
						
						MONEY_LOG_PARAM	MoneyLogParam;
						MoneyLogParam.CharGUID	=	pHuman->GetGUID();
						MoneyLogParam.OPType	=	MONEY_SHOP_REPAIR;
						MoneyLogParam.Count		=	MoneySpent;
						MoneyLogParam.SceneID	=	pHuman->getScene()->SceneID();
						MoneyLogParam.XPos		=	pHuman->getWorldPos()->m_fX;
						MoneyLogParam.ZPos		=	pHuman->getWorldPos()->m_fZ;
						SaveMoneyLog(&MoneyLogParam);

						HumanItemLogic::SetBagItemDur(pHuman,(UINT)BagIndex,(INT)fMax);
						ItemList[0].IsIn		=	GCShopRepair::BAG;					
						ItemList[0].BagIndex	=	(BYTE)BagIndex;
						Msg.SetAll(0);
						Msg.SetReListNum(1);
						Msg.SetReList(ItemList);
						pHuman->GetPlayer()->SendPacket(&Msg);
					}
					else
					{//没钱还捣乱
						GCShopBuy Msg ;
						Msg.SetBuyOk((BYTE)GCShopBuy::BUY_MONEY_FAIL);
						pHuman->GetPlayer()->SendPacket( &Msg ) ;
						g_pLog->FastSaveLog( LOG_FILE_1, "CGShopRepairHandler BUY_MONEY_FAIL") ;
						return PACKET_EXE_CONTINUE ;
					}
				}
			}
			else
			{
				g_pLog->FastSaveLog( LOG_FILE_1, "CGShopRepairHandler BagIndex = %d", BagIndex) ;
				return PACKET_EXE_CONTINUE ;
			}
		}
	}
	else if(Opt == CGShopRepair::FromEquip)
	{
		pCurItem = HumanItemLogic::GetEquip(pHuman,(HUMAN_EQUIP)BagIndex);

		if(!pCurItem->IsEmpty())
		{//有东西
			FLOAT fCur = (FLOAT)pCurItem->GetDurPoints();
			FLOAT fMax = (FLOAT)pCurItem->GetMaxDurPoint();
			FLOAT V	   = (FLOAT)pCurItem->GetPrice();

			{
				if(pCurItem->GetRequireLevel()>pShop->m_nRepairLevel)
				{
					g_pLog->FastSaveLog( LOG_FILE_1, "CGShopRepairHandler Npc have no the Repair Levle") ;
					return PACKET_EXE_CONTINUE;
				}
				BOOL bCanRepair = TRUE;
				switch( pShop->m_nRepairType )
				{
				case SHOP_All:
					{
					}
					break;
				case SHOP_DEFENCE:		//防具
					{
						if( pCurItem->GetEquipPoint() != HEQUIP_CAP &&
							pCurItem->GetEquipPoint() != HEQUIP_ARMOR &&
							pCurItem->GetEquipPoint() != HEQUIP_CUFF &&
							pCurItem->GetEquipPoint() != HEQUIP_BOOT )
						{
							bCanRepair = FALSE;
						}
					}
					break;
				case SHOP_ADORN:		//饰物
					{
						if( pCurItem->GetEquipPoint() != HEQUIP_SASH &&
							pCurItem->GetEquipPoint() != HEQUIP_RING &&
							pCurItem->GetEquipPoint() != HEQUIP_NECKLACE &&
							pCurItem->GetEquipPoint() != HEQUIP_RIDER)
						{
							bCanRepair = FALSE;
						}
					}
					break;
				case SHOP_WEAPON:		//武器
					{
						if( pCurItem->GetEquipPoint() != HEQUIP_WEAPON )
						{
							bCanRepair = FALSE;
						}
					}
					break;
				default:
					{
						bCanRepair = FALSE;
					}
					break;
				}

				if(bCanRepair == FALSE)
				{
					g_pLog->FastSaveLog( LOG_FILE_1, "CGShopRepairHandler Npc have no the Repair type") ;
					return PACKET_EXE_CONTINUE;
				}
			}


			if(fCur != fMax)
			{
				//if(fCur<fMax/3)
				//	MoneySpent += (INT)(7*V*V*fCur*6/(4*fMax)+V*V);
				//else if(fCur>=fMax/3&&fCur<fMax*2/3)
				//	MoneySpent += (INT)(V*V*fCur*6/fMax+V*V*3/4);
				//else if(fCur>=fMax*2/3&&fCur<fMax)
				//	MoneySpent += (INT)(V*V*fCur*6/(4*fMax)+V*V/4);

				MoneySpent += (INT) ( ((REPAIR_SPEND * (1- fCur/fMax) * V) * pShop->m_nRepairSpend) + 0.5);

				if(MoneyHave>=MoneySpent)
				{//可以修
					pHuman->SetMoney(MoneyHave - MoneySpent);
					MONEY_LOG_PARAM	MoneyLogParam;
					MoneyLogParam.CharGUID	=	pHuman->GetGUID();
					MoneyLogParam.OPType	=	MONEY_SHOP_REPAIR;
					MoneyLogParam.Count		=	MoneySpent;
					MoneyLogParam.SceneID	=	pHuman->getScene()->SceneID();
					MoneyLogParam.XPos		=	pHuman->getWorldPos()->m_fX;
					MoneyLogParam.ZPos		=	pHuman->getWorldPos()->m_fZ;
					SaveMoneyLog(&MoneyLogParam);

					HumanItemLogic::SetEquipDur(pHuman,(HUMAN_EQUIP)BagIndex,(INT)fMax);
					ItemList[0].IsIn		=	GCShopRepair::EQUIP;					
					ItemList[0].BagIndex	=	(BYTE)BagIndex;
					Msg.SetAll(0);
					Msg.SetReListNum(1);
					Msg.SetReList(ItemList);
					pHuman->GetPlayer()->SendPacket(&Msg);
				}
				else
				{//没钱还捣乱
					GCShopBuy Msg ;
					Msg.SetBuyOk((BYTE)GCShopBuy::BUY_MONEY_FAIL);
					pHuman->GetPlayer()->SendPacket( &Msg ) ;
					g_pLog->FastSaveLog( LOG_FILE_1, "CGShopRepairHandler BUY_MONEY_FAIL") ;
					return PACKET_EXE_CONTINUE ;
				}
			}
		}

	}


	return PACKET_EXE_CONTINUE;

	__LEAVE_FUNCTION

	return PACKET_EXE_ERROR ;
}
void PathCPURenderThread::RenderFunc() {
	//SLG_LOG("[PathCPURenderEngine::" << threadIndex << "] Rendering thread started");

	//--------------------------------------------------------------------------
	// Initialization
	//--------------------------------------------------------------------------

	PathCPURenderEngine *engine = (PathCPURenderEngine *)renderEngine;
	RandomGenerator *rndGen = new RandomGenerator(engine->seedBase + threadIndex);
	Scene *scene = engine->renderConfig->scene;
	PerspectiveCamera *camera = scene->camera;
	Film * film = threadFilm;
	const unsigned int filmWidth = film->GetWidth();
	const unsigned int filmHeight = film->GetHeight();

	// Setup the sampler
	double metropolisSharedTotalLuminance, metropolisSharedSampleCount;
	Sampler *sampler = engine->renderConfig->AllocSampler(rndGen, film,
			&metropolisSharedTotalLuminance, &metropolisSharedSampleCount);
	const unsigned int sampleBootSize = 4;
	const unsigned int sampleStepSize = 9;
	const unsigned int sampleSize = 
		sampleBootSize + // To generate eye ray
		engine->maxPathDepth * sampleStepSize; // For each path vertex
	sampler->RequestSamples(sampleSize);

	//--------------------------------------------------------------------------
	// Trace paths
	//--------------------------------------------------------------------------

	vector<SampleResult> sampleResults(1);
	sampleResults[0].type = PER_PIXEL_NORMALIZED;
	while (!boost::this_thread::interruption_requested()) {
		float alpha = 1.f;

		Ray eyeRay;
		const float screenX = min(sampler->GetSample(0) * filmWidth, (float)(filmWidth - 1));
		const float screenY = min(sampler->GetSample(1) * filmHeight, (float)(filmHeight - 1));
		camera->GenerateRay(screenX, screenY, &eyeRay,
			sampler->GetSample(2), sampler->GetSample(3));

		int depth = 1;
		bool lastSpecular = true;
		float lastPdfW = 1.f;
		Spectrum radiance;
		Spectrum pathThrouput(1.f, 1.f, 1.f);
		BSDF bsdf;
		while (depth <= engine->maxPathDepth) {
			const unsigned int sampleOffset = sampleBootSize + (depth - 1) * sampleStepSize;

			RayHit eyeRayHit;
			Spectrum connectionThroughput;
			if (!scene->Intersect(device, false, sampler->GetSample(sampleOffset),
					&eyeRay, &eyeRayHit, &bsdf, &connectionThroughput)) {
				// Nothing was hit, look for infinitelight
				DirectHitInfiniteLight(lastSpecular, pathThrouput * connectionThroughput, eyeRay.d,
						lastPdfW, &radiance);

				if (depth == 1)
					alpha = 0.f;
				break;
			}
			pathThrouput *= connectionThroughput;

			// Something was hit

			// Check if it is a light source
			if (bsdf.IsLightSource()) {
				DirectHitFiniteLight(lastSpecular, pathThrouput,
						eyeRayHit.t, bsdf, lastPdfW, &radiance);
			}

			// Note: pass-through check is done inside SceneIntersect()

			//------------------------------------------------------------------
			// Direct light sampling
			//------------------------------------------------------------------

			DirectLightSampling(sampler->GetSample(sampleOffset + 1),
					sampler->GetSample(sampleOffset + 2),
					sampler->GetSample(sampleOffset + 3),
					sampler->GetSample(sampleOffset + 4),
					sampler->GetSample(sampleOffset + 5),
					pathThrouput, bsdf, depth, &radiance);

			//------------------------------------------------------------------
			// Build the next vertex path ray
			//------------------------------------------------------------------

			Vector sampledDir;
			BSDFEvent event;
			float cosSampledDir;
			const Spectrum bsdfSample = bsdf.Sample(&sampledDir,
					sampler->GetSample(sampleOffset + 6),
					sampler->GetSample(sampleOffset + 7),
					&lastPdfW, &cosSampledDir, &event);
			if (bsdfSample.Black())
				break;

			lastSpecular = ((event & SPECULAR) != 0);

			if ((depth >= engine->rrDepth) && !lastSpecular) {
				// Russian Roulette
				const float prob = Max(bsdfSample.Filter(), engine->rrImportanceCap);
				if (sampler->GetSample(sampleOffset + 8) < prob)
					lastPdfW *= prob;
				else
					break;
			}

			pathThrouput *= bsdfSample * (cosSampledDir / lastPdfW);
			assert (!pathThrouput.IsNaN() && !pathThrouput.IsInf());

			eyeRay = Ray(bsdf.hitPoint, sampledDir);
			++depth;
		}

		assert (!radiance.IsNaN() && !radiance.IsInf());

		sampleResults[0].screenX = screenX;
		sampleResults[0].screenY = screenY;
		sampleResults[0].radiance = radiance;
		sampleResults[0].alpha = alpha;
		sampler->NextSample(sampleResults);

#ifdef WIN32
		// Work around Windows bad scheduling
		renderThread->yield();
#endif
	}

	delete sampler;
	delete rndGen;

	//SLG_LOG("[PathCPURenderEngine::" << threadIndex << "] Rendering thread halted");
}
void SampleMaterial::update(Node* o, const int elapsedTime)
{
	if (o->frame()->updateNeeded())
	{
		Scene* scene = Scene::getInstance();
		//matrice modelView
		modelViewMatrix->Set(scene->camera()->getModelViewMatrix(o->frame()));
		//position de la caméra
		glm::vec3 cameraPos = scene->camera()->convertPtTo(glm::vec3(0.0), scene->getRoot()->frame());
		CamPos->Set(cameraPos);
		modelViewProjMatrix->Set(o->frame()->getTransformMatrix());
		o->frame()->setUpdate(true);
		//o->frame()->rotate(glm::vec3(0.0,1.0,0.0), 20);
		//tableau de positions mises a jour pour l'envoi dans le buffer
		const int taille = particleAtSameTime;
		glm::vec3* positionsMaj = new glm::vec3[taille];
		//tableau de duree de vie pour les particules
		float* lifetimeMaj = new float[taille];
		//tableau d'angle aléatoire pour les constructions de matrice
		float* angleMaj = new float[taille];
		float angleTmp;
		//maj du tableau de particules
		for (int i = 0; i < particleAtSameTime; i++){
			//particule morte
			if (tabParticles[i].life < 0){
				//swap de particule vivante et morte
				Particle partJustDied = tabParticles[i];
				tabParticles[i] = lastParticleAlive(tabParticles);
				tabParticles[indSwapParticle] = partJustDied;
				// plus de particules en vie
				if (tabParticles[i].life == -10.0){
					tabParticles = fillEmptyTabParticle(tabParticles);
				}
			}
			tabParticles[i].updateParticles(0.1f);
			positionsMaj[i] = tabParticles[i].position;
			tabParticles[i].life--;
			lifetimeMaj[i] = tabParticles[i].life;
			angleTmp = minAngle + static_cast <float> (rand()) / (static_cast <float> (RAND_MAX / (maxAngle - minAngle)));
			angleMaj[i] = angleTmp;
		}

		//envoi des données nécessaires sur le gpu (position des particules)
		//buffer de positions
		glGenBuffers(1, &VBOpos);
		glBindBuffer(GL_ARRAY_BUFFER, VBOpos);
		glBufferData(GL_ARRAY_BUFFER, sizeof(glm::vec3) * taille, &positionsMaj[0], GL_STATIC_DRAW);
		glBindBuffer(GL_ARRAY_BUFFER, 0);
		
		//buffer de duree de vie
		glGenBuffers(1, &VBOlife);
		glBindBuffer(GL_ARRAY_BUFFER, VBOlife);
		glBufferData(GL_ARRAY_BUFFER, sizeof(float) * taille, &lifetimeMaj[0], GL_STATIC_DRAW);
		glBindBuffer(GL_ARRAY_BUFFER, 0);

		//buffer angle
		glGenBuffers(1, &VBOangle);
		glBindBuffer(GL_ARRAY_BUFFER, VBOangle);
		glBufferData(GL_ARRAY_BUFFER, sizeof(float) * taille, &angleMaj[0], GL_STATIC_DRAW);
		glBindBuffer(GL_ARRAY_BUFFER, 0);

		//vertex array du modèle
		GLuint VAO = mod->VA_Main;
		//glGenVertexArrays(1, &VAO); créé un nouveau VAO, pas celui associé au modèle
		glBindVertexArray(VAO);

		glEnableVertexAttribArray(6);
		glBindBuffer(GL_ARRAY_BUFFER, VBOpos);
		glVertexAttribPointer(6, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), (GLvoid*)0);
		glBindBuffer(GL_ARRAY_BUFFER, 0);
		glVertexAttribDivisor(6, 1);

		glEnableVertexAttribArray(7);
		glBindBuffer(GL_ARRAY_BUFFER, VBOlife);
		glVertexAttribPointer(7, 1, GL_FLOAT, GL_FALSE, sizeof(GLfloat), (GLvoid*)0);
		glBindBuffer(GL_ARRAY_BUFFER, 0);
		glVertexAttribDivisor(7, 1);

		glEnableVertexAttribArray(8);
		glBindBuffer(GL_ARRAY_BUFFER, VBOangle);
		glVertexAttribPointer(8, 1, GL_FLOAT, GL_FALSE, sizeof(GLfloat), (GLvoid*)0);
		glBindBuffer(GL_ARRAY_BUFFER, 0);
		glVertexAttribDivisor(8, 1);

		glBindVertexArray(0);

	}
	

}
Esempio n. 18
0
Spectrum EstimateDirect(const Interaction &it, const Point2f &uScattering,
                        const Light &light, const Point2f &uLight,
                        const Scene &scene, Sampler &sampler,
                        MemoryArena &arena, bool handleMedia, bool specular) {
    BxDFType bsdfFlags =
        specular ? BSDF_ALL : BxDFType(BSDF_ALL & ~BSDF_SPECULAR);
    Spectrum Ld(0.f);
    // Sample light source with multiple importance sampling
    Vector3f wi;
    Float lightPdf = 0, scatteringPdf = 0;
    VisibilityTester visibility;
    Spectrum Li = light.Sample_Li(it, uLight, &wi, &lightPdf, &visibility);
    if (lightPdf > 0 && !Li.IsBlack()) {
        // Compute BSDF or phase function's value for light sample
        Spectrum f;
        if (it.IsSurfaceInteraction()) {
            // Evaluate BSDF for light sampling strategy
            const SurfaceInteraction &isect = (const SurfaceInteraction &)it;
            f = isect.bsdf->f(isect.wo, wi, bsdfFlags) *
                AbsDot(wi, isect.shading.n);
            scatteringPdf = isect.bsdf->Pdf(isect.wo, wi, bsdfFlags);
        } else {
            // Evaluate phase function for light sampling strategy
            const MediumInteraction &mi = (const MediumInteraction &)it;
            Float p = mi.phase->p(mi.wo, wi);
            f = Spectrum(p);
            scatteringPdf = p;
        }
        if (!f.IsBlack()) {
            // Compute effect of visibility for light source sample
            if (handleMedia)
                Li *= visibility.Tr(scene, sampler);
            else if (!visibility.Unoccluded(scene))
                Li = Spectrum(0.f);

            // Add light's contribution to reflected radiance
            if (!Li.IsBlack()) {
                if (IsDeltaLight(light.flags))
                    Ld += f * Li / lightPdf;
                else {
                    Float weight =
                        PowerHeuristic(1, lightPdf, 1, scatteringPdf);
                    Ld += f * Li * weight / lightPdf;
                }
            }
        }
    }

    // Sample BSDF with multiple importance sampling
    if (!IsDeltaLight(light.flags)) {
        Spectrum f;
        bool sampledSpecular = false;
        if (it.IsSurfaceInteraction()) {
            // Sample scattered direction for surface interactions
            BxDFType sampledType;
            const SurfaceInteraction &isect = (const SurfaceInteraction &)it;
            f = isect.bsdf->Sample_f(isect.wo, &wi, uScattering, &scatteringPdf,
                                     bsdfFlags, &sampledType);
            f *= AbsDot(wi, isect.shading.n);
            sampledSpecular = sampledType & BSDF_SPECULAR;
        } else {
            // Sample scattered direction for medium interactions
            const MediumInteraction &mi = (const MediumInteraction &)it;
            Float p = mi.phase->Sample_p(mi.wo, &wi, uScattering);
            f = Spectrum(p);
            scatteringPdf = p;
        }
        if (!f.IsBlack() && scatteringPdf > 0) {
            // Account for light contributions along sampled direction _wi_
            Float weight = 1;
            if (!sampledSpecular) {
                lightPdf = light.Pdf_Li(it, wi);
                if (lightPdf == 0) return Ld;
                weight = PowerHeuristic(1, scatteringPdf, 1, lightPdf);
            }

            // Find intersection and compute transmittance
            SurfaceInteraction lightIsect;
            Ray ray = it.SpawnRay(wi);
            Spectrum Tr(1.f);
            bool foundSurfaceInteraction =
                handleMedia ? scene.IntersectTr(ray, sampler, &lightIsect, &Tr)
                            : scene.Intersect(ray, &lightIsect);

            // Add light contribution from material sampling
            Spectrum Li(0.f);
            if (foundSurfaceInteraction) {
                if (lightIsect.primitive->GetAreaLight() == &light)
                    Li = lightIsect.Le(-wi);
            } else
                Li = light.Le(ray);
            if (!Li.IsBlack()) Ld += f * Li * Tr * weight / scatteringPdf;
        }
    }
    return Ld;
}
Esempio n. 19
0
int main() {
	int REN_HEIGHT = DEFAULT_HEIGHT;
	int REN_WIDTH = DEFAULT_WIDTH;
	const int LVL_WIDTH = 3600;
	const int LVL_HEIGHT = 3600;
	
	//REN_HEIGHT = LVL_HEIGHT; REN_WIDTH = LVL_WIDTH;
	const int CAMERA_WIDTH = REN_WIDTH;
	const int CAMERA_HEIGHT = REN_HEIGHT;

	try {
		SDL sdl;

		Window win("transistor");
		win.init();
	
		//win.pos(Point(0, 0));
		//win.resize(REN_WIDTH, REN_HEIGHT);
		//REN_HEIGHT = win.height();
		//REN_WIDTH = win.width();

		Renderer::create_renderer(win);
		Renderer::set_rendering_resolution (REN_WIDTH, REN_HEIGHT);

		Action_List animation_list;
		Action_List event_list;
		Control ctrl;
		Camera camera(Point(0, 0), CAMERA_WIDTH, CAMERA_HEIGHT);
		Event_Manager event_manager;
		Render_List render_list;
		Scene scene (Rect (Point (0,0), LVL_WIDTH, LVL_HEIGHT));

		
		Player_Factory player_factory;
		Player& player = player_factory.create_Player(Vec2(LVL_WIDTH/2, LVL_HEIGHT/2));

		event_manager.add_event_handler (win);
		event_manager.add_event_handler (ctrl);
		event_manager.add_state_handler (player);

		render_list.add_object (player);
		scene.add_dynamic_body (player.get_body());

		/*
		Texture tex[2];
		tex[0].load_from_file ("../rsc/ball_0_200.png", Color::WHITE);
		tex[1].load_from_file ("../rsc/ball_1_200.png", Color::WHITE);
		
		Texture_Stream ctex;
		ctex.add_texture (&tex[0]);
		ctex.add_texture (&tex[1]);

		const int ISIZE = 40;
		const int SSIZE = 80;
		const int SPEED = 10;
		const int SLICE = 20;
		const int ITEM_SIZE = 50;
		Sphere *item[ITEM_SIZE];
		for (int i = 0; i < ITEM_SIZE; ++i) {
			item[i] = new Sphere (&ctex, Vec2((i*ISIZE*8)%(LVL_WIDTH-SSIZE*10) + SSIZE*3, (i*ISIZE*8)/(LVL_WIDTH-SSIZE*10) * ISIZE*5 + SSIZE*20), Vec2(0, 0), 0.0f);
		}

		Guided_Sphere gs (&tex[0], Vec2 (ISIZE*20, ISIZE*8));
		gs.set_cmd ("xwdxxxxxxxxxxxxxxxxxxxxxxxxssxxxxxxxxxxxxxxxxxxxxxxxxaaxxxxxxxxxxxxxxxxxxxxxxxxwwxxxxxxxxxxxxxxxxxxxxxxxxsdxxxxxxxxxxxxxxxxxxxxxxxx");

		Rectangle_Texture* rtex1 = new Rectangle_Texture(LVL_WIDTH, SSIZE);
		Rectangle_Texture* rtex2 = new Rectangle_Texture(SSIZE, LVL_HEIGHT - 2 * SSIZE);
		Rectangle_Texture* rtex3 = new Rectangle_Texture(LVL_WIDTH / 2, SSIZE);
		Rectangle_Texture* rtex4 = new Rectangle_Texture(LVL_WIDTH / 4, SLICE);
		Rectangle_Texture* rtex5 = new Rectangle_Texture(LVL_WIDTH / 8, SLICE * 4);
		Rectangle_Texture* rtex6 = new Rectangle_Texture(SLICE * 4, LVL_WIDTH / 8);

		Moving_Slab* mslab1 = new Moving_Slab(rtex5, Vec2(SSIZE + SSIZE * 10, LVL_HEIGHT - SSIZE - SLICE * 14), Vec2 (0.0f, -20.0f), 1400.0f);
		Moving_Slab* mslab2 = new Moving_Slab(rtex6, Vec2(LVL_WIDTH - SSIZE * 3, LVL_HEIGHT / 2 - SSIZE * 5), Vec2 (-20.0f, 0.0), 1000.0f);
		Moving_Slab* mslab3 = new Moving_Slab(rtex5, Vec2(SSIZE * 3, LVL_HEIGHT / 2 - SSIZE * 4), Vec2 (20.0f, -20.0f), 1400.0f);
		Moving_Slab* mslab4 = new Moving_Slab(rtex5, Vec2(LVL_WIDTH - SSIZE * 20, LVL_HEIGHT / 2 + SSIZE), Vec2 (0.0f, -20.0f), 1000.0f);

		const int MOVING_SLAB_SIZE = 4;
		const int SLAB_SIZE = 12;
		Slab *slab[SLAB_SIZE+MOVING_SLAB_SIZE];
		slab[0] = new Slab(rtex1, Vec2(0, LVL_HEIGHT - SSIZE));
		slab[1] = new Slab(rtex1, Vec2(0, 0));
		slab[2] = new Slab(rtex2, Vec2(0, SSIZE));
		slab[3] = new Slab(rtex2, Vec2(LVL_WIDTH - SSIZE, SSIZE));
		slab[4] = new Slab(rtex3, Vec2(LVL_WIDTH / 2 - SSIZE, LVL_HEIGHT / 2 - SSIZE * 4));
		slab[5] = new Slab(rtex3, Vec2(SSIZE, LVL_HEIGHT / 2 - SSIZE * 8));
		slab[6] = new Slab(rtex4, Vec2(SSIZE, LVL_HEIGHT - SSIZE - SLICE * 6));
		slab[7] = new Slab(rtex4, Vec2(SSIZE + SLICE, LVL_HEIGHT - SSIZE - SLICE * 5));
		slab[8] = new Slab(rtex4, Vec2(SSIZE + SLICE * 2, LVL_HEIGHT - SSIZE - SLICE * 4));
		slab[9] = new Slab(rtex4, Vec2(SSIZE + SLICE * 3, LVL_HEIGHT - SSIZE - SLICE * 3));
		slab[10] = new Slab(rtex4, Vec2(SSIZE + SLICE * 4, LVL_HEIGHT - SSIZE - SLICE * 2));
		slab[11] = new Slab(rtex4, Vec2(SSIZE + SLICE * 5, LVL_HEIGHT - SSIZE - SLICE));
		slab[12] = mslab1;
		slab[13] = mslab2;
		slab[14] = mslab3;
		slab[15] = mslab4;


		//Circle_Texture* ptex = new Circle_Texture(ISIZE * 2, Color::GREEN);
		//Rectangle_Texture* ptex = new Rectangle_Texture(ISIZE * 2, ISIZE * 3);
		

		for (int i = 0; i < ITEM_SIZE; ++i) {
			scene.add_static_body(item[i]->get_body());
			alist.push_back (item[i]->get_action());
		}

		for (int i = 0; i < SLAB_SIZE; ++i) {
			scene.add_static_body(slab[i]->get_body());
			cerr<<"slab["<<i<<"]: ("<<slab[i]->min.x<<", "<<slab[i]->min.y<<"), ("<<slab[i]->max.x<<", "<<slab[i]->max.y<<")\n";
		}

		for (int i = SLAB_SIZE; i < MOVING_SLAB_SIZE+SLAB_SIZE; ++i) {
			scene.add_dynamic_body(slab[i]->get_body());
			cerr<<"slab["<<i<<"]: ("<<slab[i]->min.x<<", "<<slab[i]->min.y<<"), ("<<slab[i]->max.x<<", "<<slab[i]->max.y<<")\n";
		}



		scene.add_dynamic_body (p.get_body());
		scene.add_dynamic_body (gs.get_body());

		alist.push_back (mslab1->get_action());
		alist.push_back (mslab2->get_action());
		alist.push_back (mslab3->get_action());
		alist.push_back (mslab4->get_action());
		alist.push_back (p.get_action());

		elist.push_back (gs.get_action());
		

		Renderer::set_draw_color(Color::WHITE);

		Texture bg;
		bg.load_from_file ("../rsc/bg.png");

		cerr<<"QUADTREE HEIGHT: "<<scene.get_height()<<'\n';
		cerr<<"QUADTREE: \n";
		scene.draw_static_tree();
		*/

		const float fps = 40.0;
		const float dt = 1/fps;
		const float MAX_ACC = 0.2f;

		float accumulator = 0;
		float curr_fps;

		unsigned int frames = 0;
		unsigned int timer = 0;
		unsigned int t1 = 0;
		unsigned int start_time = SDL_GetTicks();

		unsigned int frame_start = SDL_GetTicks();

		while (!win.quit()) {
			timer = SDL_GetTicks();
			
			event_manager.poll_handle();

			if (win.is_hidden() || ctrl.is_paused())
				continue;

			event_list.update (dt);

#ifdef DEBUG
			cerr<<"accumulator: "<<accumulator<<'\n';
			t1 = SDL_GetTicks();
#endif

			accumulator += timer - frame_start;
			frame_start = timer;

			if (accumulator > MAX_ACC)
				accumulator = MAX_ACC;

			while (accumulator > dt) {
				scene.step (dt);
				accumulator -= dt;
			}

			animation_list.update (dt);

	
#ifdef DEBUG
			cerr<<"timer: "<<SDL_GetTicks() - t1<<'\n';
			cerr<<"accumulator: "<<accumulator<<'\n';
#endif

			// render
			camera.update_position (player.get_body()->pos, LVL_WIDTH, LVL_HEIGHT);
			render_list.render_all(camera);

			/*
			bg.render(Point(0,0), &camera);
			for (int i = 0; i < ITEM_SIZE; ++i)
				item[i]->render(camera);
			for (int i = 0; i < SLAB_SIZE+MOVING_SLAB_SIZE; ++i)
				slab[i]->render(camera);
			p.render(camera);
			gs.render(camera);
			//...
			*/


#ifdef DEBUG
			cerr<<"player_velocity: "<<p.get_body()->velocity.x<<' '<<p.get_body()->velocity.y<<'\n';
#endif

			timer = SDL_GetTicks() - timer;
			++frames;

#ifdef DEBUG
			curr_fps = 1000.0f/float(timer);
			cerr<<"fps: "<<curr_fps<<'\n';	// print current fps
#endif

		}
		timer = SDL_GetTicks()-start_time;
		cout<<"Frames : "<<frames<<"\nTime Taken : "<<timer/1000.0f<<"\nFPS : "<<frames/(timer/1000.0f)<<'\n';
	}
	catch (Exception& e) {
		cerr<<"Exception : "<<e.what()<<'\n';;
	}
	// deallocate memory?

	return 0;
}
Esempio n. 20
0
uint WGRetTeamDistribModeHandler::Execute( WGRetTeamDistribMode* pPacket, Player* pPlayer )
{
	__ENTER_FUNCTION

		PlayerID_t PlayerID = pPacket->getLeaderID();
	GamePlayer* pGamePlayer = g_pPlayerPool->GetPlayer(PlayerID);
	BYTE nMode = pPacket->getMode();
	if( pGamePlayer==NULL )
	{
		Assert(FALSE);
		return PACKET_EXE_CONTINUE;
	}
	if (nMode>= ITEM_DISTRIB_NUM)
	{
		return PACKET_EXE_CONTINUE;
	}
	Obj_Human* pHuman = pGamePlayer->GetHuman();
	Assert( pHuman );

	Scene* pScene = pHuman->getScene();
	if( pScene==NULL ) return PACKET_EXE_CONTINUE ;

	if( pPlayer->IsServerPlayer() )
	{//服务器收到世界服务器发来的数据
		Assert( MyGetCurrentThreadID()==g_pServerManager->m_ThreadID );

		pScene->SendPacket( pPacket, PlayerID );
		g_pLog->FastSaveLog( LOG_FILE_1, "WGRetTeamDistribMode: ServerPlayer GUID=%X ",pPacket->getLeaderID() );

		return PACKET_EXE_NOTREMOVE;
	}
	else if( pPlayer->IsGamePlayer() )
	{//场景收到Cache里的消息
		Assert( MyGetCurrentThreadID()==pScene->m_ThreadID );
		
		TeamInfo* pTeamInf = pHuman->GetTeamInfo();
		
		if (pTeamInf == NULL)
		{
			return PACKET_EXE_CONTINUE;
		}
		TeamID_t teamID = pTeamInf->GetTeamID();
		if (teamID == INVALID_INDEX)
		{
			return PACKET_EXE_CONTINUE;
		}
		GCRetTeamDistribMode Msg;
		Msg.setMode(nMode);
		Obj_Human* pOther = NULL;
		for( INT i=0; i<pTeamInf->GetTeamMemberCount(); ++i )
		{
			const TEAMMEMBER* pMember = pTeamInf->GetTeamMember( i );

			pOther = (Obj_Human*)pHuman->getScene()->GetObjManager()->GetObj( pMember->m_ObjID );
			if (pOther != NULL)
			{
				if( pOther->GetObjType() == Obj::OBJ_TYPE_HUMAN )
				{
					TeamInfo* pTeamInfo = pOther->GetTeamInfo();
					if (pTeamInfo->GetTeamID() == teamID)
					{
						pTeamInfo->SetDistribMode(nMode);
						GamePlayer* pTGamePlayer = (GamePlayer*)pOther->GetPlayer();
						if (pTGamePlayer)
						{
							pTGamePlayer->SendPacket(&Msg);
						}
					}
				}
			}

		}

		g_pLog->FastSaveLog( LOG_FILE_1, "WGRetTeamDistribMode: GamePlayer PlayerID=%X ",PlayerID );
	}
	else
	{
		Assert(FALSE);
	}

	return PACKET_EXE_CONTINUE;

	__LEAVE_FUNCTION

		return PACKET_EXE_ERROR;
}
Esempio n. 21
0
Scene* RaptorExample::scene () {
	Scene *scene = Scene::create();
	scene->addChild(RaptorExample::create());
	return scene;
}
Esempio n. 22
0
int main(int argc, char *argv[])
{
 // QApplication app(argc, argv);
 //// QEditorExternal w;
 // w.show();
//
 // app.exec();

  Engine engine;

  // intit the engine
	engine.initialize("engine_config.xml");//1680, 840, RENDER_SUBSYSTEM , 2, false);
  
  engine.setPostProcessing(PP_FXAA, true);
  engine.setPostProcessing(PP_HDR, true);
  engine.setPostProcessing(PP_BLOOM, true);

  // load and set the start scene
	Scene *  scene = new Scene();
	scene->load("island-scene.xml");

  Object * obj = scene->addObject( "models/energy_remain.obj",glm::vec3(0,0,0) , false);
  if(obj != nullptr)
  {
    Script * s1 = obj->addScript();
    RotationScriptElement * rs1= s1->addRotationScript();
    rs1->setupAlways();
    rs1->setup(glm::vec3(100,0,0) ); 
  }

  Object * obj2 = scene->addObject("models/rooster.dae", glm::vec3(1, 0, 0), false);
  if (obj2 != nullptr)
  {
    obj2->setScale(glm::vec3(0.1f,0.1f,0.1f));
    Script * s2 = obj2->addScript();
    RotationScriptElement * rs2 = s2->addRotationScript();
    rs2->setupAlways();
    rs2->setup(glm::vec3(0,100,0));
  }

	engine.setScene(scene, false);

  //std::future<void> future_editor = std::async(startEditor, argc, argv);
  

  // run the main loop
  while(engine.running())
  {
    scene->acquireLock();
    engine.update();
    engine.render();   
    scene->releaseLock();
  }
   
   // shut everything down
  engine.shutDown();

  //future_editor.get();

  if(scene != nullptr)
    delete scene;  


  return 0;  
}
    /// Return an importance value for the given tile
    virtual double importanceForTile(const Quadtree::Identifier &ident,const Mbr &mbr,ViewState *viewState,const Point2f &frameSize,Dictionary *attrs)
    {
        if (ident.level == 0)
            return MAXFLOAT;
        
        Quadtree::Identifier tileID;
        tileID.level = ident.level;
        tileID.x = ident.x;
        tileID.y = ident.y;
        
        if (!validTile(ident,mbr))
            return 0.0;
        
        // Note: Porting.  Variable size tiles.
        int thisTileSize = tileSize;
        //        if (variableSizeTiles)
        //        {
        //            thisTileSize = [_tileSource tileSizeForTile:tileID];
        //            if (thisTileSize <= 0)
        //                thisTileSize = [_tileSource tileSize];
        //        }
        
        double import = 0.0;
        if (canShortCircuitImportance && maxShortCircuitLevel != -1)
        {
            if (scene->getCoordAdapter()->isFlat())
            {
                if (TileIsOnScreen(viewState, frameSize, coordSys, scene->getCoordAdapter(), mbr, ident, attrs))
                {
                    import = 1.0/(ident.level+10);
                    if (ident.level <= maxShortCircuitLevel)
                        import += 1.0;
                }
            } else {
                // We need the backfacing checks that ScreenImportance does
                import = ScreenImportance(viewState, frameSize, viewState->eyeVec, tileSize, coordSys, scene->getCoordAdapter(), mbr, ident, attrs);
                
//                WHIRLYKIT_LOGV("ScreenImportance: %f, %d: (%d,%d)",import,ident.level,ident.x,ident.y);
                
                if (import > 0.0)
                {
                    import = 1.0/(ident.level+10);
                    if (ident.level <= maxShortCircuitLevel)
                        import += 1.0;
                }
            }
        } else {
            // Note: Porting
            //            if (elevDelegate)
            //            {
            //                import = ScreenImportance(viewState, frameSize, thisTileSize, coordSys, scene->getCoordAdapter(), mbr, _minElev, _maxElev, ident, attrs);
            //            } else {
            import = ScreenImportance(viewState, frameSize, viewState->eyeVec, thisTileSize, coordSys, scene->getCoordAdapter(), mbr, ident, attrs);
            //            }
            import *= importanceScale;
        }

//        if (import > 0.0)
//            __android_log_print(ANDROID_LOG_VERBOSE, "Maply", "Tile = %d: (%d,%d), import = %f",ident.level,ident.x,ident.y,import);
        
        return import;
    }
uint CGStallApplyHandler::Execute( CGStallApply* pPacket, Player* pPlayer )
{
	__ENTER_FUNCTION

	GamePlayer* pGamePlayer = (GamePlayer*)pPlayer ;
	Assert( pGamePlayer ) ;

	Obj_Human* pHuman = pGamePlayer->GetHuman() ;
	Assert( pHuman ) ;

	Scene* pScene = pHuman->getScene() ;
	if( pScene==NULL )
	{
		Assert(FALSE) ;
		return PACKET_EXE_ERROR ;
	}
	//检查线程执行资源是否正确
	Assert( MyGetCurrentThreadID()==pScene->m_ThreadID ) ;
	//获得本地税率
	UINT	PosTax		= 0;
	BYTE	TradeTax	= 0;
	GCStallApply	Msg;

	//验证是否有资格摆摊
	if(pHuman->GetLevel()<30)
	{
		g_pLog->FastSaveLog( LOG_FILE_1, "ERROR: CGStallApplyHandler::ObjID=%d level = %d ", pHuman->GetID(), pHuman->GetLevel()) ;
		return PACKET_EXE_CONTINUE ;
	}

	//摆摊地点判断
	StallInfoManager* pStallInfoMgr = pScene->GetStallInfoManager();
	if(pStallInfoMgr)
	{
		UINT PosX = (UINT)pHuman->getWorldPos()->m_fX;
		UINT PosZ = (UINT)pHuman->getWorldPos()->m_fZ;
		BOOL bCanStall = pStallInfoMgr->CanStall(PosX, PosZ);
		if(bCanStall == FALSE)
		{
			Msg.SetIsCanStall(FALSE);
		}
		else
		{
			PosTax		= pStallInfoMgr->StallPosPayment(PosX, PosZ);
			TradeTax	= pStallInfoMgr->StallExchangeTax(PosX, PosZ);

			pHuman->m_StallBox.CleanUp();
			pHuman->m_StallBox.SetStallStatus(ServerStallBox::STALL_READY);
			pHuman->m_StallBox.GetBBS()->LoadTitle();

			Msg.SetIsCanStall(TRUE);
			Msg.SetPosTax(PosTax);
			Msg.SetTradeTax(TradeTax);
		}
	}

	//验证完毕,通知客户端确定
	pGamePlayer->SendPacket(&Msg);

	g_pLog->FastSaveLog( LOG_FILE_1, "CGStallApplyHandler::ObjID=%d ", pHuman->GetID()) ;
	return PACKET_EXE_CONTINUE ;

	__LEAVE_FUNCTION

		return PACKET_EXE_ERROR ;
}
Esempio n. 25
0
void ViewerBase::renderingTraversals()
{
    bool _outputMasterCameraLocation = false;
    if (_outputMasterCameraLocation)
    {
        Views views;
        getViews(views);

        for(Views::iterator itr = views.begin();
            itr != views.end();
            ++itr)
        {
            osgViewer::View* view = *itr;
            if (view)
            {
                const osg::Matrixd& m = view->getCamera()->getInverseViewMatrix();
                OSG_NOTICE<<"View "<<view<<", Master Camera position("<<m.getTrans()<<"), rotation("<<m.getRotate()<<")"<<std::endl;
            }
        }
    }

    Contexts contexts;
    getContexts(contexts);

    // check to see if windows are still valid
    checkWindowStatus(contexts);
    if (_done) return;

    double beginRenderingTraversals = elapsedTime();

    osg::FrameStamp* frameStamp = getViewerFrameStamp();

    if (getViewerStats() && getViewerStats()->collectStats("scene"))
    {
        unsigned int frameNumber = frameStamp ? frameStamp->getFrameNumber() : 0;

        Views views;
        getViews(views);
        for(Views::iterator vitr = views.begin();
            vitr != views.end();
            ++vitr)
        {
            View* view = *vitr;
            osg::Stats* stats = view->getStats();
            osg::Node* sceneRoot = view->getSceneData();
            if (sceneRoot && stats)
            {
                osgUtil::StatsVisitor statsVisitor;
                sceneRoot->accept(statsVisitor);
                statsVisitor.totalUpStats();

                unsigned int unique_primitives = 0;
                osgUtil::Statistics::PrimitiveCountMap::iterator pcmitr;
                for(pcmitr = statsVisitor._uniqueStats.GetPrimitivesBegin();
                    pcmitr != statsVisitor._uniqueStats.GetPrimitivesEnd();
                    ++pcmitr)
                {
                    unique_primitives += pcmitr->second;
                }

                stats->setAttribute(frameNumber, "Number of unique StateSet", static_cast<double>(statsVisitor._statesetSet.size()));
                stats->setAttribute(frameNumber, "Number of unique Group", static_cast<double>(statsVisitor._groupSet.size()));
                stats->setAttribute(frameNumber, "Number of unique Transform", static_cast<double>(statsVisitor._transformSet.size()));
                stats->setAttribute(frameNumber, "Number of unique LOD", static_cast<double>(statsVisitor._lodSet.size()));
                stats->setAttribute(frameNumber, "Number of unique Switch", static_cast<double>(statsVisitor._switchSet.size()));
                stats->setAttribute(frameNumber, "Number of unique Geode", static_cast<double>(statsVisitor._geodeSet.size()));
                stats->setAttribute(frameNumber, "Number of unique Drawable", static_cast<double>(statsVisitor._drawableSet.size()));
                stats->setAttribute(frameNumber, "Number of unique Geometry", static_cast<double>(statsVisitor._geometrySet.size()));
                stats->setAttribute(frameNumber, "Number of unique Vertices", static_cast<double>(statsVisitor._uniqueStats._vertexCount));
                stats->setAttribute(frameNumber, "Number of unique Primitives", static_cast<double>(unique_primitives));

                unsigned int instanced_primitives = 0;
                for(pcmitr = statsVisitor._instancedStats.GetPrimitivesBegin();
                    pcmitr != statsVisitor._instancedStats.GetPrimitivesEnd();
                    ++pcmitr)
                {
                    instanced_primitives += pcmitr->second;
                }

                stats->setAttribute(frameNumber, "Number of instanced Stateset", static_cast<double>(statsVisitor._numInstancedStateSet));
                stats->setAttribute(frameNumber, "Number of instanced Group", static_cast<double>(statsVisitor._numInstancedGroup));
                stats->setAttribute(frameNumber, "Number of instanced Transform", static_cast<double>(statsVisitor._numInstancedTransform));
                stats->setAttribute(frameNumber, "Number of instanced LOD", static_cast<double>(statsVisitor._numInstancedLOD));
                stats->setAttribute(frameNumber, "Number of instanced Switch", static_cast<double>(statsVisitor._numInstancedSwitch));
                stats->setAttribute(frameNumber, "Number of instanced Geode", static_cast<double>(statsVisitor._numInstancedGeode));
                stats->setAttribute(frameNumber, "Number of instanced Drawable", static_cast<double>(statsVisitor._numInstancedDrawable));
                stats->setAttribute(frameNumber, "Number of instanced Geometry", static_cast<double>(statsVisitor._numInstancedGeometry));
                stats->setAttribute(frameNumber, "Number of instanced Vertices", static_cast<double>(statsVisitor._instancedStats._vertexCount));
                stats->setAttribute(frameNumber, "Number of instanced Primitives", static_cast<double>(instanced_primitives));
           }
        }
    }

    Scenes scenes;
    getScenes(scenes);

    for(Scenes::iterator sitr = scenes.begin();
        sitr != scenes.end();
        ++sitr)
    {
        Scene* scene = *sitr;
        osgDB::DatabasePager* dp = scene ? scene->getDatabasePager() : 0;
        if (dp)
        {
            dp->signalBeginFrame(frameStamp);
        }

        if (scene->getSceneData())
        {
            // fire off a build of the bounding volumes while we
            // are still running single threaded.
            scene->getSceneData()->getBound();
        }
    }

    // OSG_NOTICE<<std::endl<<"Start frame"<<std::endl;


    Cameras cameras;
    getCameras(cameras);

    Contexts::iterator itr;

    bool doneMakeCurrentInThisThread = false;

    if (_endDynamicDrawBlock.valid())
    {
        _endDynamicDrawBlock->reset();
    }

    // dispatch the rendering threads
    if (_startRenderingBarrier.valid()) _startRenderingBarrier->block();

    // reset any double buffer graphics objects
    for(Cameras::iterator camItr = cameras.begin();
        camItr != cameras.end();
        ++camItr)
    {
        osg::Camera* camera = *camItr;
        Renderer* renderer = dynamic_cast<Renderer*>(camera->getRenderer());
        if (renderer)
        {
            if (!renderer->getGraphicsThreadDoesCull() && !(camera->getCameraThread()))
            {
                renderer->cull();
            }
        }
    }

    for(itr = contexts.begin();
        itr != contexts.end();
        ++itr)
    {
        if (_done) return;
        if (!((*itr)->getGraphicsThread()) && (*itr)->valid())
        {
            doneMakeCurrentInThisThread = true;
            makeCurrent(*itr);
            (*itr)->runOperations();
        }
    }

    // OSG_NOTICE<<"Joing _endRenderingDispatchBarrier block "<<_endRenderingDispatchBarrier.get()<<std::endl;

    // wait till the rendering dispatch is done.
    if (_endRenderingDispatchBarrier.valid()) _endRenderingDispatchBarrier->block();

    for(itr = contexts.begin();
        itr != contexts.end();
        ++itr)
    {
        if (_done) return;

        if (!((*itr)->getGraphicsThread()) && (*itr)->valid())
        {
            doneMakeCurrentInThisThread = true;
            makeCurrent(*itr);
            (*itr)->swapBuffers();
        }
    }

    for(Scenes::iterator sitr = scenes.begin();
        sitr != scenes.end();
        ++sitr)
    {
        Scene* scene = *sitr;
        osgDB::DatabasePager* dp = scene ? scene->getDatabasePager() : 0;
        if (dp)
        {
            dp->signalEndFrame();
        }
    }

    // wait till the dynamic draw is complete.
    if (_endDynamicDrawBlock.valid())
    {
        // osg::Timer_t startTick = osg::Timer::instance()->tick();
        _endDynamicDrawBlock->block();
        // OSG_NOTICE<<"Time waiting "<<osg::Timer::instance()->delta_m(startTick, osg::Timer::instance()->tick())<<std::endl;;
    }

    if (_releaseContextAtEndOfFrameHint && doneMakeCurrentInThisThread)
    {
        //OSG_NOTICE<<"Doing release context"<<std::endl;
        releaseContext();
    }

    if (getViewerStats() && getViewerStats()->collectStats("update"))
    {
        double endRenderingTraversals = elapsedTime();

        // update current frames stats
        getViewerStats()->setAttribute(frameStamp->getFrameNumber(), "Rendering traversals begin time ", beginRenderingTraversals);
        getViewerStats()->setAttribute(frameStamp->getFrameNumber(), "Rendering traversals end time ", endRenderingTraversals);
        getViewerStats()->setAttribute(frameStamp->getFrameNumber(), "Rendering traversals time taken", endRenderingTraversals-beginRenderingTraversals);
    }

    _requestRedraw = false;
}
Esempio n. 26
0
File: art.cpp Progetto: Blizzara/ART
int ART(Scene& scene)
{
	bool profiling = false;
	Timer timer("Main");

	int x,y;
	Color pixel;

	Write file(scene.Width(), scene.Height());
	
	SDLEngine sdl(scene.Width(), scene.Height());
	if(sdl.Status() == SDLENGINE_FAIL)
		return EXIT_FAILURE;

	RTEngine rt(scene);

	int time;
	double last_time=0, total_time =0;
	double last_rays=0, total_rays =0;

	std::cout << "Begin rendering" << std::endl;


	for(int iterations = 1;  !sdl.PollGetEscape() && (profiling == false || iterations <2); ++iterations)
	{
		time = timer.StartNew();
		for(last_rays = 0; ( !sdl.PollGetRefresh() && (last_time = timer.Elapsed(time)) < 2  /*&& last_rays < 500000*/); ++last_rays)
		{
			rt.Trace();
		}

		timer.StopLast();
		total_rays += last_rays;
		total_time += last_time;
		std::cout << iterations << "th iteration, shot " << last_rays << " rays, total " << total_rays << " rays shot, total time "<< total_time << " seconds" << std::endl;

		// Let's write the image and update screen! or just update
	
		for(x = 0; x < sdl.GetWidth(); x++)
		{
			for(y = 0; y < sdl.GetHeight(); y++)
			{
// 				std::cout << "Showing x:  "  << x << " and y: " << y << std::endl;
				pixel = scene.Pixel(x,y);
				sdl.SetPixel(x,y, (int)(pixel.x*255), (int)(pixel.y*255), (int)(pixel.z*255));
// 				image.plot(x,sdl.GetHeight()-y,pixel.x,pixel.y,pixel.z);
			}
		}
		sdl.UpdateSc();
	}				

	std::cout << "Total " << total_rays << " casted in " <<  total_time << " seconds, averaging to " << total_rays/total_time << " rays per second" << std::endl;

	
	file.WritePixels(scene);

// 	sdl.UpdateSc();

	timer.SinceStart();
	if (!profiling) sdl.Wait();
	
	return EXIT_SUCCESS;
}
Esempio n. 27
0
int main(int argc, char **argv)
{
	Game game(Window(1900, 1200, "MyGame", Window::OPENGL));	
	Context context(game.window());
	Scene scene;

	scene.addMesh("ground")
		.fromFiles("res/models/ground.obj", "res/models/ground.mtl")
		.moveTo(0,-2,0);

	scene.getMesh("ground").material().normalMap().fromFile("res/textures/bricks_normal.jpg");

	scene.addMesh("box")
		.fromFiles("res/models/box.obj", "res/models/box.mtl")
		.attachTo(scene.getMesh("ground"))
		.moveTo(0,6,0);

	scene.addMesh("sphere")
		.fromFiles("res/models/sphere_hd_smooth.obj", "res/models/sphere_flat.mtl")
		.attachTo(scene.getMesh("ground"))
		.moveTo(0,2,0);

	scene.setAmbient(vec3(1,1,1) * 0.3f);
	scene.camera()
		.withPerspective(toRadian(70), game.window().aspect(), 0.01f, 1000.0f)
		.moveTo(0,0,7)
		.aimAt(0,0,0);

	scene.addLight("d1").directional(vec3(1,1,1) * 0.8f, vec3(1,-1,1));
	scene.addLight("d2").directional(vec3(0,1,0) * 0.5f, vec3(-1,-1,-1));

	scene.addLight("p1").point(vec3(1,0,0) * 0.4f, vec3(1,-1.5f,1));
	scene.addLight("p2").point(vec3(0,1,0) * 0.6f, vec3(2,-1.5f,2));
	scene.addLight("p3").point(vec3(0,0,1) * 0.6f, vec3(3,-1.5f,3));

	scene.addLight("s1").spot(vec3(1,1,0) * 1.0f, vec3(-2,-1.9,2), vec3(1,0,-1), 0.6f, 10);
	scene.addLight("s2").spot(vec3(0,1,1) * 1.0f, vec3(-3,-1.9,3), vec3(1,0,-1), 0.6f, 10);
		
 	game.add(FPSCounter());
 	game.add(WindowControl());
 	game.add(KeyboardControl(scene.camera()));
 	game.add(MouseControl(scene.camera()));
 	game.add(Renderer(context, scene));

 	game.start();
 	return EXIT_SUCCESS;
}
Esempio n. 28
0
bool OBS::SetScene(CTSTR lpScene)
{
    if(bDisableSceneSwitching)
        return false;

    HWND hwndScenes = GetDlgItem(hwndMain, ID_SCENES);
    UINT curSel = (UINT)SendMessage(hwndScenes, LB_GETCURSEL, 0, 0);

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

    if(curSel != LB_ERR)
    {
        UINT textLen = (UINT)SendMessage(hwndScenes, LB_GETTEXTLEN, curSel, 0);

        String strLBName;
        strLBName.SetLength(textLen);

        SendMessage(hwndScenes, LB_GETTEXT, curSel, (LPARAM)strLBName.Array());
        if(!strLBName.CompareI(lpScene))
        {
            UINT id = (UINT)SendMessage(hwndScenes, LB_FINDSTRINGEXACT, -1, (LPARAM)lpScene);
            if(id == LB_ERR)
                return false;

            SendMessage(hwndScenes, LB_SETCURSEL, id, 0);
        }
    }
    else
    {
        UINT id = (UINT)SendMessage(hwndScenes, LB_FINDSTRINGEXACT, -1, (LPARAM)lpScene);
        if(id == LB_ERR)
            return false;

        SendMessage(hwndScenes, LB_SETCURSEL, id, 0);
    }

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

    XElement *scenes = scenesConfig.GetElement(TEXT("scenes"));
    XElement *newSceneElement = scenes->GetElement(lpScene);
    if(!newSceneElement)
        return false;

    if(sceneElement == newSceneElement)
        return true;

    sceneElement = newSceneElement;

    CTSTR lpClass = sceneElement->GetString(TEXT("class"));
    if(!lpClass)
    {
        AppWarning(TEXT("OBS::SetScene: no class found for scene '%s'"), newSceneElement->GetName());
        return false;
    }

    DWORD sceneChangeStartTime;

    if(bRunning)
    {
        Log(TEXT("++++++++++++++++++++++++++++++++++++++++++++++++++++++"));
        Log(TEXT("  New Scene"));

        sceneChangeStartTime = OSGetTime();
    }

    XElement *sceneData = newSceneElement->GetElement(TEXT("data"));

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

    Scene *newScene = NULL;
    if(bRunning)
        newScene = CreateScene(lpClass, sceneData);

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

    HWND hwndSources = GetDlgItem(hwndMain, ID_SOURCES);

    SendMessage(hwndSources, WM_SETREDRAW, (WPARAM)FALSE, (LPARAM) 0);

    bChangingSources = true;
    ListView_DeleteAllItems(hwndSources);

    XElement *sources = sceneElement->GetElement(TEXT("sources"));
    if(sources)
    {
        UINT numSources = sources->NumElements();
        ListView_SetItemCount(hwndSources, numSources);

        for(UINT i=0; i<numSources; i++)
        {
            XElement *sourceElement = sources->GetElementByID(i);
            bool render = sourceElement->GetInt(TEXT("render"), 1) > 0;

            InsertSourceItem(i, (LPWSTR)sourceElement->GetName(), render);

            if(bRunning && newScene)
                newScene->AddImageSource(sourceElement);
        }
    }

    bChangingSources = false;
    SendMessage(hwndSources, WM_SETREDRAW, (WPARAM)TRUE, (LPARAM) 0);
    RedrawWindow(hwndSources, NULL, NULL, RDW_ERASE | RDW_FRAME | RDW_INVALIDATE | RDW_ALLCHILDREN);

    if(scene && newScene && newScene->HasMissingSources())
        MessageBox(hwndMain, Str("Scene.MissingSources"), NULL, 0);

    if(bRunning)
    {
        //todo: cache scenes maybe?  undecided.  not really as necessary with global sources
        OSEnterMutex(hSceneMutex);

        UINT numSources;

        if (scene)
        {
            //shutdown previous scene, if any
            numSources = scene->sceneItems.Num();
            for(UINT i=0; i<numSources; i++)
            {
                XElement *source = scene->sceneItems[i]->GetElement();
                String className = source->GetString(TEXT("class"));
                if(scene->sceneItems[i]->bRender && className == "GlobalSource") {
                    XElement *globalSourceData = source->GetElement(TEXT("data"));
                    String globalSourceName = globalSourceData->GetString(TEXT("name"));
                    if(App->GetGlobalSource(globalSourceName) != NULL) {
                        App->GetGlobalSource(globalSourceName)->GlobalSourceLeaveScene();
                    }
                }
            }

            scene->EndScene();
        }

        Scene *previousScene = scene;
        scene = newScene;

        scene->BeginScene();

        numSources = scene->sceneItems.Num();
        for(UINT i=0; i<numSources; i++)
        {
            XElement *source = scene->sceneItems[i]->GetElement();
            String className = source->GetString(TEXT("class"));
            if(scene->sceneItems[i]->bRender && className == "GlobalSource") {
                XElement *globalSourceData = source->GetElement(TEXT("data"));
                String globalSourceName = globalSourceData->GetString(TEXT("name"));
                if(App->GetGlobalSource(globalSourceName) != NULL) {
                    App->GetGlobalSource(globalSourceName)->GlobalSourceEnterScene();
                }
            }
        }

        if(!bTransitioning)
        {
            bTransitioning = true;
            transitionAlpha = 0.0f;
        }

        OSLeaveMutex(hSceneMutex);

        delete previousScene;

        DWORD sceneChangeTime = OSGetTime() - sceneChangeStartTime;
        if (sceneChangeTime >= 500)
            Log(TEXT("PERFORMANCE WARNING: Scene change took %u ms, maybe some sources should be global sources?"), sceneChangeTime);
    }

    if(API != NULL)
       ReportSwitchScenes(lpScene);

    return true;
}
Esempio n. 29
0
void PhotonShootingTask::Run() {
    // Declare local variables for _PhotonShootingTask_
    MemoryArena arena;
    RNG rng(31 * taskNum);
    vector<Photon> localDirectPhotons, localIndirectPhotons, localCausticPhotons;
    vector<RadiancePhoton> localRadiancePhotons;
    uint32_t totalPaths = 0;
    bool causticDone = (integrator->nCausticPhotonsWanted == 0);
    bool indirectDone = (integrator->nIndirectPhotonsWanted == 0);
    PermutedHalton halton(6, rng);
    vector<Spectrum> localRpReflectances, localRpTransmittances;
    while (true) {
        // Follow photon paths for a block of samples
        const uint32_t blockSize = 4096;
        for (uint32_t i = 0; i < blockSize; ++i) {
            float u[6];
            halton.Sample(++totalPaths, u);
            // Choose light to shoot photon from
            float lightPdf;
            int lightNum = lightDistribution->SampleDiscrete(u[0], &lightPdf);
            const Light *light = scene->lights[lightNum];

            // Generate _photonRay_ from light source and initialize _alpha_
            RayDifferential photonRay;
            float pdf;
            LightSample ls(u[1], u[2], u[3]);
            Normal Nl;
            Spectrum Le = light->Sample_L(scene, ls, u[4], u[5],
                                          time, &photonRay, &Nl, &pdf);
            if (pdf == 0.f || Le.IsBlack()) continue;
            Spectrum alpha = (AbsDot(Nl, photonRay.d) * Le) / (pdf * lightPdf);
            if (!alpha.IsBlack()) {
                // Follow photon path through scene and record intersections
                PBRT_PHOTON_MAP_STARTED_RAY_PATH(&photonRay, &alpha);
                bool specularPath = true;
                Intersection photonIsect;
                int nIntersections = 0;
                while (scene->Intersect(photonRay, &photonIsect)) {
                    ++nIntersections;
                    // Handle photon/surface intersection
                    alpha *= renderer->Transmittance(scene, photonRay, NULL, rng, arena);
                    BSDF *photonBSDF = photonIsect.GetBSDF(photonRay, arena);
                    BxDFType specularType = BxDFType(BSDF_REFLECTION |
                                            BSDF_TRANSMISSION | BSDF_SPECULAR);
                    bool hasNonSpecular = (photonBSDF->NumComponents() >
                                           photonBSDF->NumComponents(specularType));
                    Vector wo = -photonRay.d;
                    if (hasNonSpecular) {
                        // Deposit photon at surface
                        Photon photon(photonIsect.dg.p, alpha, wo);
                        bool depositedPhoton = false;
                        if (specularPath && nIntersections > 1) {
                            if (!causticDone) {
                                PBRT_PHOTON_MAP_DEPOSITED_CAUSTIC_PHOTON(&photonIsect.dg, &alpha, &wo);
                                depositedPhoton = true;
                                localCausticPhotons.push_back(photon);
                            }
                        }
                        else {
                            // Deposit either direct or indirect photon
                            // stop depositing direct photons once indirectDone is true; don't
                            // want to waste memory storing too many if we're going a long time
                            // trying to get enough caustic photons desposited.
                            if (nIntersections == 1 && !indirectDone && integrator->finalGather) {
                                PBRT_PHOTON_MAP_DEPOSITED_DIRECT_PHOTON(&photonIsect.dg, &alpha, &wo);
                                depositedPhoton = true;
                                localDirectPhotons.push_back(photon);
                            }
                            else if (nIntersections > 1 && !indirectDone) {
                                PBRT_PHOTON_MAP_DEPOSITED_INDIRECT_PHOTON(&photonIsect.dg, &alpha, &wo);
                                depositedPhoton = true;
                                localIndirectPhotons.push_back(photon);
                            }
                        }

                        // Possibly create radiance photon at photon intersection point
                        if (depositedPhoton && integrator->finalGather &&
                                rng.RandomFloat() < .125f) {
                            Normal n = photonIsect.dg.nn;
                            n = Faceforward(n, -photonRay.d);
                            localRadiancePhotons.push_back(RadiancePhoton(photonIsect.dg.p, n));
                            Spectrum rho_r = photonBSDF->rho(rng, BSDF_ALL_REFLECTION);
                            localRpReflectances.push_back(rho_r);
                            Spectrum rho_t = photonBSDF->rho(rng, BSDF_ALL_TRANSMISSION);
                            localRpTransmittances.push_back(rho_t);
                        }
                    }
                    if (nIntersections >= integrator->maxPhotonDepth) break;

                    // Sample new photon ray direction
                    Vector wi;
                    float pdf;
                    BxDFType flags;
                    Spectrum fr = photonBSDF->Sample_f(wo, &wi, BSDFSample(rng),
                                                       &pdf, BSDF_ALL, &flags);
                    if (fr.IsBlack() || pdf == 0.f) break;
                    Spectrum anew = alpha * fr *
                        AbsDot(wi, photonBSDF->dgShading.nn) / pdf;

                    // Possibly terminate photon path with Russian roulette
                    float continueProb = min(1.f, anew.y() / alpha.y());
                    if (rng.RandomFloat() > continueProb)
                        break;
                    alpha = anew / continueProb;
                    specularPath &= ((flags & BSDF_SPECULAR) != 0);

                    if (indirectDone && !specularPath) break;
                    photonRay = RayDifferential(photonIsect.dg.p, wi, photonRay,
                                                photonIsect.rayEpsilon);
                }
                PBRT_PHOTON_MAP_FINISHED_RAY_PATH(&photonRay, &alpha);
            }
            arena.FreeAll();
        }

        // Merge local photon data with data in _PhotonIntegrator_
        { MutexLock lock(mutex);

        // Give up if we're not storing enough photons
        if (abortTasks)
            return;
        if (nshot > 500000 &&
            (unsuccessful(integrator->nCausticPhotonsWanted,
                                      causticPhotons.size(), blockSize) ||
             unsuccessful(integrator->nIndirectPhotonsWanted,
                                      indirectPhotons.size(), blockSize))) {
            Error("Unable to store enough photons.  Giving up.\n");
            causticPhotons.erase(causticPhotons.begin(), causticPhotons.end());
            indirectPhotons.erase(indirectPhotons.begin(), indirectPhotons.end());
            radiancePhotons.erase(radiancePhotons.begin(), radiancePhotons.end());
            abortTasks = true;
            return;
        }
        progress.Update(localIndirectPhotons.size() + localCausticPhotons.size());
        nshot += blockSize;

        // Merge indirect photons into shared array
        if (!indirectDone) {
            integrator->nIndirectPaths += blockSize;
            for (uint32_t i = 0; i < localIndirectPhotons.size(); ++i)
                indirectPhotons.push_back(localIndirectPhotons[i]);
            localIndirectPhotons.erase(localIndirectPhotons.begin(),
                                       localIndirectPhotons.end());
            if (indirectPhotons.size() >= integrator->nIndirectPhotonsWanted)
                indirectDone = true;
            nDirectPaths += blockSize;
            for (uint32_t i = 0; i < localDirectPhotons.size(); ++i)
                directPhotons.push_back(localDirectPhotons[i]);
            localDirectPhotons.erase(localDirectPhotons.begin(),
                                     localDirectPhotons.end());
        }

        // Merge direct, caustic, and radiance photons into shared array
        if (!causticDone) {
            integrator->nCausticPaths += blockSize;
            for (uint32_t i = 0; i < localCausticPhotons.size(); ++i)
                causticPhotons.push_back(localCausticPhotons[i]);
            localCausticPhotons.erase(localCausticPhotons.begin(), localCausticPhotons.end());
            if (causticPhotons.size() >= integrator->nCausticPhotonsWanted)
                causticDone = true;
        }

        for (uint32_t i = 0; i < localRadiancePhotons.size(); ++i)
            radiancePhotons.push_back(localRadiancePhotons[i]);
        localRadiancePhotons.erase(localRadiancePhotons.begin(), localRadiancePhotons.end());
        for (uint32_t i = 0; i < localRpReflectances.size(); ++i)
            rpReflectances.push_back(localRpReflectances[i]);
        localRpReflectances.erase(localRpReflectances.begin(), localRpReflectances.end());
        for (uint32_t i = 0; i < localRpTransmittances.size(); ++i)
            rpTransmittances.push_back(localRpTransmittances[i]);
        localRpTransmittances.erase(localRpTransmittances.begin(), localRpTransmittances.end());
        }

        // Exit task if enough photons have been found
        if (indirectDone && causticDone)
            break;
    }
}
Esempio n. 30
0
int RayTracer::getIntersectionPoint(const Vec3Df & camPos,
                                    const Vec3Df & dir,
                                    Vec3Df & intersectionPoint,
                                    Vec3Df & IntersPointNormal,
                                    float & occlusion)
{
    Scene * scene = Scene::getInstance ();
    float smallestIntersectionDistance = 1000000.f;

    int idObj = -1;
    bool hasIntersection=false;
    for (unsigned int k = 0; k < scene->getObjects().size (); k++) {
        Object & o = scene->getObjects()[k];
        Ray ray (camPos-o.getTrans (), dir);
        hasIntersection = ray.intersect (o.getBoundingBox ());
        if (hasIntersection){
            Mesh mesh = o.getMesh();
            std::vector<Triangle> tabTriangle = mesh.getTriangles();
            std::vector<Vertex> vertices = mesh.getVertices();
            std::vector<Vec3Df> normals = o.getTrianglesNormals(); //Precomputed
            Vec3Df normal = normals[k];
            float intersectionDistance;
            float coefB[3]; //The three barycentric coefs of the intersection point
            unsigned idTriangle;
            bool hasIntersection = searchNode (o.getTree(), ray, tabTriangle, vertices, normals, intersectionDistance, idTriangle, coefB);

            if (hasIntersection) {

                if (intersectionDistance < smallestIntersectionDistance) {

                    Triangle triangle = tabTriangle[idTriangle];

                        if(o.getSmooth()) IntersPointNormal=normal;
                        else
                        {
                            IntersPointNormal =
                                    vertices[triangle.getVertex(0)].getNormal()*coefB[2]
                                    +vertices[triangle.getVertex(1)].getNormal()*coefB[0]
                                    +vertices[triangle.getVertex(2)].getNormal()*coefB[1];
                            IntersPointNormal = IntersPointNormal/(coefB[0]+coefB[1]+coefB[2]);
                        }


                        occlusion =
                                o.getMesh().getVertices()[triangle.getVertex(0)].getOcc()*coefB[2]
                                +o.getMesh().getVertices()[triangle.getVertex(1)].getOcc()*coefB[0]
                                +o.getMesh().getVertices()[triangle.getVertex(2)].getOcc()*coefB[1];
                        occlusion = occlusion/(coefB[0]+coefB[1]+coefB[2]);

                        intersectionPoint =
                                vertices[triangle.getVertex(0)].getPos()*coefB[2]
                                +vertices[triangle.getVertex(1)].getPos()*coefB[0]
                                +vertices[triangle.getVertex(2)].getPos()*coefB[1];
                        intersectionPoint = (intersectionPoint+o.getTrans())/(coefB[0]+coefB[1]+coefB[2]);

                    smallestIntersectionDistance = intersectionDistance;

                    idObj=k;


                }
            }
        }
    }

    return idObj;
}