예제 #1
0
//Runs the genetic algorithm
void Solver::runAStar()
{
    for(int i=0;i<gateLimit;++i)
    {
        circuits.push_back(Circuit());
    }
    bool go = true;
    int loc = -1;
    unsigned long long int generation=0;
    do
    {
        //algorithm adds new random gate every generation, and reverts if the fitness value goes lower
        ++generation;
        addGatesAstar();
        calcFitness();
        revert();
        runSortFitness();
        cull();
        loc = checkSolution();
        if(generation%1000 == 0)
        {
            cout<<"Generation: "<<generation<<"\n";
            cout<<"Num Gates:  "<<circuits[0].getGateNum()<<"\n";
        }
        if(loc != -1)
        {
            solutionLoc = loc;
            cout<<"Generation: "<<generation<<"\n";
            go = false;
        }
    }while(go);
}
예제 #2
0
void RayTracedTechnique::traverse(osg::NodeVisitor& nv)
{
    // OSG_NOTICE<<"RayTracedTechnique::traverse(osg::NodeVisitor& nv)"<<std::endl;
    if (!_volumeTile) return;

    // if app traversal update the frame count.
    if (nv.getVisitorType()==osg::NodeVisitor::UPDATE_VISITOR)
    {
        if (_volumeTile->getDirty()) _volumeTile->init();

        osgUtil::UpdateVisitor* uv = dynamic_cast<osgUtil::UpdateVisitor*>(&nv);
        if (uv)
        {
            update(uv);
            return;
        }

    }
    else if (nv.getVisitorType()==osg::NodeVisitor::CULL_VISITOR)
    {
        osgUtil::CullVisitor* cv = dynamic_cast<osgUtil::CullVisitor*>(&nv);
        if (cv)
        {
            cull(cv);
            return;
        }
    }


    if (_volumeTile->getDirty())
    {
        OSG_INFO<<"******* Doing init ***********"<<std::endl;
        _volumeTile->init();
    }
}
예제 #3
0
//This should be smarter
std::vector<GameObject*> World::getDrawn(int mountainSide)
{
   std::vector<GameObject*>objectsInScene = cull(mountainSide);
   objectsToDraw = objectsInScene;
   objectsInScene.push_back(&mount);
  
   return objectsInScene;
}
예제 #4
0
파일: osgposter.cpp 프로젝트: yueying/osg
 virtual void operator ()( osg::GraphicsContext* )
 {
     if ( _graphicsThreadDoesCull )
     {
         if (_cullOnly) cull();
         else cull_draw();
     }
 }
예제 #5
0
파일: TileMap.cpp 프로젝트: ace24713/CS3113
void TileMap::generate()
{
    randomize();
    for (size_t i = 0; i < 5; ++i)
        smooth();
    cull();
    tileify();
    prepRenderData();
}
예제 #6
0
void GlobeView::drawLocalClient(){
	if(!mEarth) return;

	ci::gl::ScopedFaceCulling cull(true, GL_BACK);
	ci::gl::ScopedTextureBind tex0(mTexDiffuse, 0);
	ci::gl::ScopedTextureBind tex1(mTexNormal, 1);
	ci::gl::ScopedTextureBind tex2(mTexMask, 2);

	mEarth->draw();
}
예제 #7
0
void Camera::render( const Scene* scene )
{
	// This will contain all nodes used for rendering.
	RenderBlock renderBlock;

	// Perform frustum culling.
	cull( renderBlock, &scene->entities );

	// Submits the geometry to the renderer.
	render( renderBlock );
}
예제 #8
0
//Runs the genetic algorithm
//Note: Longer than 24 lines due to extensive commenting needed
void Solver::runGenetic()
{
    //Uses top 20% of children
    int keep = gateLimit/5;
    for(int i=0;i<keep;++i)
    {
        circuits.push_back(Circuit());
    }
    addNewGates(keep);
    bool go = true;
    int loc = -1;
    unsigned long long int generation=0;
    do
    {
        ++generation;
        //Randomly deletes a gate every 100 generations
        if(generation%100==0)
        {
            randomDelete();
        }
        //Gets all crosses for top 20% of children every 20 generations
        if(generation%20==0)
        {
            crossover(keep);
        }
        //Mutates a Random Gate every 10 generations
        if(generation%10==0)
        {
            mutate();
        }
        //Adds a new random Gate every generation
        addNewGates(keep);
        calcFitness();
        runSortFitness();
        shrink();
        cull();
        loc = checkSolution();
        if(generation%1000 == 0)
        {
            cout<<"Generation: "<<generation<<"\n";
            cout<<"Num Gates:  "<<circuits[0].getGateNum()<<"\n";
        }
        if(loc != -1)
        {
            solutionLoc = loc;
            cout<<"Generation: "<<generation<<"\n";
            go = false;
        }
    }while(go);
}
예제 #9
0
void RigGeometry::accept(osg::NodeVisitor &nv)
{
    if (!nv.validNodeMask(*this))
        return;

    nv.pushOntoNodePath(this);

    if (nv.getVisitorType() == osg::NodeVisitor::CULL_VISITOR)
        cull(&nv);
    else if (nv.getVisitorType() == osg::NodeVisitor::UPDATE_VISITOR)
        updateBounds(&nv);
    else
        nv.apply(*this);

    nv.popFromNodePath();
}
예제 #10
0
int
main(int argc, char **argv) {

  // allocate 4 times as many elements as we need (sparse-ish data)
  element_t * elements = (element_t *)malloc(NUM_ELEMENTS * 4 * sizeof(element_t));  

  // allocate two arrays of pointers to elements
  unsigned num_elements = NUM_ELEMENTS;
  element_t **list = (element_t **)malloc(num_elements * sizeof(element_t *));  
  element_t **list2 = (element_t **)malloc(num_elements * sizeof(element_t *));  

  // point list entries at random elements
  for (int i = 0 ; i < num_elements ; i ++) {
	 int index = random() % (NUM_ELEMENTS * 4);
	 list[i] = &elements[index];
	 initialize_element(list[i]);
  }
  
  vp_t *vp = get_a_vp();  

  // iteratively process the elements
  for (int step = 0 ; step < NUM_STEPS ; step ++) {

	 // pick two random elements
	 element_t *e_cull = list[random() % num_elements];
	 element_t *e_update = list[random() % num_elements];

	 // select those elements close to the element of interest
	 unsigned num_elements2 = 0;
	 for (int i = 0 ; i < num_elements ; i ++) {
		if (!cull(list[i], e_cull)) {
		  list2[num_elements2] = list[i];
		  num_elements2 ++;
		}
	 }

	 for (int i = 0 ; i < num_elements2 ; i ++) {
		transform(list2[i], vp);
	 }

	 // update based on the update element
	 for (int i = 0 ; i < num_elements2 ; i ++) {
		update(list2[i], e_update);
	 }
  }
}
예제 #11
0
void GPUDrawTechnique::traverse(osg::NodeVisitor& nv)
{
    if (!_GPUScene) return;

    if (nv.getVisitorType() == osg::NodeVisitor::UPDATE_VISITOR)
    {
       if (_dirty) init();

        update(nv);
    }
    else if (nv.getVisitorType() == osg::NodeVisitor::CULL_VISITOR)
    {
        osgUtil::CullVisitor* cv = nv.asCullVisitor();
        if (cv) cull(*cv);
        else _GPUScene->osg::Group::traverse(nv);
    }
    else
    {
        _GPUScene->osg::Group::traverse(nv);
    }
}
예제 #12
0
HRESULT KG3DShadowMapLevel::ProcessShadowMap(KG3DCamera* pCameraLight,D3DXVECTOR3& vFocusPos,KG3DSceneSceneEditor* pEditor,KG3DSceneShadowMap* pShadow,LPDIRECT3DSURFACE9 pColorSur)
{
    HRESULT hResult = E_FAIL;
	HRESULT hr = S_OK;
	LPDIRECT3DSURFACE9 pDepthSave = NULL;
	LPDIRECT3DSURFACE9 pTargetSave = NULL;
	D3DVIEWPORT9 ViewportSave;
	D3DVIEWPORT9 Viewport;
    BOOL bSetRenderTarget = FALSE;
    BOOL bSetDepthStencilSurface = FALSE;
    BOOL bSetViewport = FALSE;
	//float fDepthBias = 0.0002f;
	//float fBiasSlope = 0.5f;
	//g_pd3dDevice->SetRenderState(D3DRS_DEPTHBIAS,*(DWORD*)&fDepthBias);
	//g_pd3dDevice->SetRenderState(D3DRS_SLOPESCALEDEPTHBIAS,*(DWORD*)&fBiasSlope);

	pCameraLight->SetCamera();

	m_lpShadowMapEntityMgr->FrameMove(pEditor,FALSE);
	if(g_dwRenderCount % 2 < 1)
		m_lpShadowMapEntityMgr->GetVisibleEntityEx(pCameraLight,pEditor,vFocusPos);
	//////////////////////////////////////////////////////////////////////////

	Viewport.X = 0;
    Viewport.Y = 0;
	Viewport.Height = m_dwShadowmapSize;
    Viewport.Width = m_dwShadowmapSize;
	Viewport.MaxZ = 1;
    Viewport.MinZ = 0;

	hr = g_pd3dDevice->GetDepthStencilSurface(&pDepthSave);
    KGLOG_COM_PROCESS_ERROR(hr);

	hr = g_pd3dDevice->GetRenderTarget(0, &pTargetSave);
    KGLOG_COM_PROCESS_ERROR(hr);

	hr = g_pd3dDevice->GetViewport(&ViewportSave);
    KGLOG_COM_PROCESS_ERROR(hr);

	hr = g_pd3dDevice->SetRenderTarget(0, pColorSur);
	KGLOG_COM_PROCESS_ERROR(hr);

    bSetRenderTarget = TRUE;

	hr = g_pd3dDevice->SetDepthStencilSurface(m_lpSMShadowMapSurface);
	KGLOG_COM_PROCESS_ERROR(hr);

    bSetDepthStencilSurface = TRUE;

	hr = g_pd3dDevice->SetViewport(&Viewport);
    KGLOG_COM_PROCESS_ERROR(hr);

    bSetViewport = TRUE;

	//////////////////////////////////////////////////////////////////////////
	//hr = g_pd3dDevice->SetRenderState(D3DRS_ZENABLE, TRUE);
	//KGLOG_COM_PROCESS_ERROR(hr);

	//hr = g_pd3dDevice->SetRenderState(D3DRS_ZWRITEENABLE, TRUE);
	//KGLOG_COM_PROCESS_ERROR(hr);

    hr = g_pd3dDevice->Clear(0, 0, D3DCLEAR_ZBUFFER | D3DCLEAR_STENCIL, 0xFF000000, 1, 0);
    KGLOG_COM_PROCESS_ERROR(hr);

	{
		GraphicsStruct::RenderState cull(D3DRS_CULLMODE,D3DCULL_NONE);

		{
			GraphicsStruct::RenderStateAlpha Alpha(0x20,FALSE,FALSE,D3DBLEND_SRCALPHA,D3DBLEND_INVSRCALPHA);
			GraphicsStruct::RenderState colorWrite(D3DRS_COLORWRITEENABLE ,D3DCOLORWRITEENABLE_ALPHA);
			GraphicsStruct::RenderState ZWrite(D3DRS_ZWRITEENABLE,TRUE);
			GraphicsStruct::RenderState ZEnable(D3DRS_ZENABLE,TRUE);
			GraphicsStruct::RenderState lightEnable(D3DRS_LIGHTING,FALSE);
			GraphicsStruct::RenderState fog(D3DRS_FOGENABLE,FALSE);
			//GraphicsStruct::RenderState cullState(D3DRS_CULLMODE,D3DCULL_CW);
			if (g_cEngineOption.ModelShadowType >= EM_MODEL_SHADOW_TYPE_HIGH)
			{
				if(nIndex ==0)
				{
					m_lpShadowMapEntityMgr->RenderForShadowMap(
						pEditor,
						TRUE,
						g_cEngineManager.GetRenderOption(RENDER_TREE),
						g_cEngineManager.GetRenderOption(RENDER_ENTITY) && g_cEngineManager.GetRenderOption(RENDER_NORL_MESH),
						g_cEngineManager.GetRenderOption(RENDER_ENTITY) && g_cEngineManager.GetRenderOption(RENDER_SKIN_MESH)
						);

					if(pEditor->m_pRepresentNPC)
					{
						pEditor->m_pRepresentNPC->Render(0);
					}
				}
				else
				{
					m_lpShadowMapEntityMgr->RenderForShadowMap(
						pEditor,
						TRUE,
						g_cEngineManager.GetRenderOption(RENDER_TREE),
						g_cEngineManager.GetRenderOption(RENDER_ENTITY) && g_cEngineManager.GetRenderOption(RENDER_NORL_MESH),
						FALSE
						);
				}
			}
			else if (g_cEngineOption.ModelShadowType == EM_MODEL_SHADOW_TYPE_MIDDLE)
			{
				if(nIndex ==0)
				{
					m_lpShadowMapEntityMgr->RenderForShadowMap(
						pEditor,
						FALSE,
						FALSE,
						FALSE,
						g_cEngineManager.GetRenderOption(RENDER_ENTITY) && g_cEngineManager.GetRenderOption(RENDER_SKIN_MESH)
						);

					if(pEditor->m_pRepresentNPC)
					{
						pEditor->m_pRepresentNPC->Render(0);
					}
				}

			}

		}
	}

	g_RenderRenderTwiceInfo();
    m_lpShadowMapEntityMgr->RenderSpecialAlphaModel();

	hResult = S_OK;
Exit0:
    
    if (bSetRenderTarget)
    {
        hr = g_pd3dDevice->SetRenderTarget(0,pTargetSave);
        KGLOG_COM_CHECK_ERROR(hr);
    }
    KG_COM_RELEASE(pTargetSave);

    if (bSetDepthStencilSurface)
    {
    	hr = g_pd3dDevice->SetDepthStencilSurface(pDepthSave);
        KGLOG_COM_CHECK_ERROR(hr);
    }
    KG_COM_RELEASE(pDepthSave);

    if (bSetViewport)
    {
        hr = g_pd3dDevice->SetViewport(&ViewportSave);
        KGLOG_COM_CHECK_ERROR(hr);
    }
	//g_pd3dDevice->SetRenderState(D3DRS_DEPTHBIAS,0);
	//g_pd3dDevice->SetRenderState(D3DRS_SLOPESCALEDEPTHBIAS,0);
	return hResult;
}
예제 #13
0
void VectorLayer::_cull9( const iiCamera::Camera &camera )
{
    if(!_fgDataCache)
        return;

    _fgDataCache->clearQueue();

    Timestamp start;
    std::list<DrawablePatch> list = Globe::instance()->getGlobeSceneHandler()->getGlobeHandler()->getPatchList();
    if(list.size()==0)
    {
        AMIGO_LOG_I(TAG, "::cull() list is empty.\n");
        return;
    }

    DrawablePatch &dp = list.front();
    int level = dp.level;
    uint64 row = dp.row;
    uint64 col = dp.col;

    double lat;
    double lng;

    // Step 1 levels up
    Utils::levelRowColToLatLong(level, row, col, lat, lng );
    level-=1;
    if(level<2) level=2;
    Utils::levelLatLongToRowCol( level, lat, lng, row, col );

    int64 c1, c2, r1, r2;
    getSpanRowCol(row, col, c1, c2, r1, r2);
    
    bool allTilesExist = true;
    allTilesExist = _allTilesExist(level, c1, c2, r1, r2, true, _fgDataCache);
    if(allTilesExist)
    {
        _lastTiles.clear();
        for(uint64 c=c1; c<=c2; c++)
        {
            for(uint64 r=r1; r<=r2; r++)
            {
                VectorTileIdentity pa(level, r, c, _projectId, _datasetId);
                if(auto tile = _getTile( pa ))
                {
                    tile->cull(camera, OpaqueBin::instance());
                    _lastTiles.push_back( tile );
                }
            }
        }

        // Add Text  tile
        VectorTileIdentity pa(level, row, col, _projectId, _datasetId, true);
        auto tile = _getTile( pa );
        if(tile)
        {            
            tile->cull(camera, OpaqueBin::instance());
            _lastTiles.push_back( tile );
        } else
        {
            _fgDataCache->request( pa );
        }

    } else
    {
        for(auto t : _lastTiles)
        {
            int dl = level - t->getIdentity().level;
            if(dl < 7) // Don't render tiles if level is too far away
                t->cull(camera, OpaqueBin::instance());
        }   
    }

    _level = level;
}
예제 #14
0
//--------------------------------------------------------------------
// render()
//--------------------------------------------------------------------
U32 LLViewerJoint::render( F32 pixelArea, BOOL first_pass, BOOL is_dummy )
{
	stop_glerror();

	U32 triangle_count = 0;

	//----------------------------------------------------------------
	// ignore invisible objects
	//----------------------------------------------------------------
	if ( mValid )
	{


		//----------------------------------------------------------------
		// if object is transparent, defer it, otherwise
		// give the joint subclass a chance to draw itself
		//----------------------------------------------------------------
		if ( is_dummy )
		{
			triangle_count += drawShape( pixelArea, first_pass, is_dummy );
		}
		else if (LLPipeline::sShadowRender)
		{
			triangle_count += drawShape(pixelArea, first_pass, is_dummy );
		}
		else if ( isTransparent() && !LLPipeline::sReflectionRender)
		{
			// Hair and Skirt
			if ((pixelArea > MIN_PIXEL_AREA_3PASS_HAIR))
			{
				// render all three passes
				LLGLDisable cull(GL_CULL_FACE);
				// first pass renders without writing to the z buffer
				{
					LLGLDepthTest gls_depth(GL_TRUE, GL_FALSE);
					triangle_count += drawShape( pixelArea, first_pass, is_dummy );
				}
				// second pass writes to z buffer only
				gGL.setColorMask(false, false);
				{
					triangle_count += drawShape( pixelArea, FALSE, is_dummy  );
				}
				// third past respects z buffer and writes color
				gGL.setColorMask(true, false);
				{
					LLGLDepthTest gls_depth(GL_TRUE, GL_FALSE);
					triangle_count += drawShape( pixelArea, FALSE, is_dummy  );
				}
			}
			else
			{
				// Render Inside (no Z buffer write)
				glCullFace(GL_FRONT);
				{
					LLGLDepthTest gls_depth(GL_TRUE, GL_FALSE);
					triangle_count += drawShape( pixelArea, first_pass, is_dummy  );
				}
				// Render Outside (write to the Z buffer)
				glCullFace(GL_BACK);
				{
					triangle_count += drawShape( pixelArea, FALSE, is_dummy  );
				}
			}
		}
		else
		{
			// set up render state
			triangle_count += drawShape( pixelArea, first_pass );
		}
	}

	//----------------------------------------------------------------
	// render children
	//----------------------------------------------------------------
	for (child_list_t::iterator iter = mChildren.begin();
		 iter != mChildren.end(); ++iter)
	{
		LLViewerJoint* joint = (LLViewerJoint*)(*iter);
		F32 jointLOD = joint->getLOD();
		if (pixelArea >= jointLOD || sDisableLOD)
		{
			triangle_count += joint->render( pixelArea, TRUE, is_dummy );

			if (jointLOD != DEFAULT_LOD)
			{
				break;
			}
		}
	}

	return triangle_count;
}
예제 #15
0
void LLViewerParcelMgr::renderCollisionSegments(U8* segments, BOOL use_pass, LLViewerRegion* regionp)
{

	S32 x, y;
	F32 x1, y1;	// start point
	F32 x2, y2;	// end point
	F32 alpha = 0;
	F32 dist = 0;
	F32 dx, dy;
	F32 collision_height;

	const S32 STRIDE = (mParcelsPerEdge+1);
	
	LLVector3 pos = gAgent.getPositionAgent();

	F32 pos_x = pos.mV[VX];
	F32 pos_y = pos.mV[VY];

	LLGLSUIDefault gls_ui;
	LLGLDepthTest gls_depth(GL_TRUE, GL_FALSE);
	LLGLDisable cull(GL_CULL_FACE);
	
	if (mCollisionBanned == BA_BANNED)
	{
		collision_height = BAN_HEIGHT;
	}
	else
	{
		collision_height = PARCEL_HEIGHT;
	}

	
	if (use_pass && (mCollisionBanned == BA_NOT_ON_LIST))
	{
		gGL.getTexUnit(0)->bind(mPassImage);
	}
	else
	{
		gGL.getTexUnit(0)->bind(mBlockedImage);
	}

	gGL.begin(LLRender::QUADS);

	for (y = 0; y < STRIDE; y++)
	{
		for (x = 0; x < STRIDE; x++)
		{
			U8 segment_mask = segments[x + y*STRIDE];
			U8 direction;
			const F32 MAX_ALPHA = 0.95f;
			const S32 DIST_OFFSET = 5;
			const S32 MIN_DIST_SQ = DIST_OFFSET*DIST_OFFSET;
			const S32 MAX_DIST_SQ = 169;

			if (segment_mask & SOUTH_MASK)
			{
				x1 = x * PARCEL_GRID_STEP_METERS;
				y1 = y * PARCEL_GRID_STEP_METERS;

				x2 = x1 + PARCEL_GRID_STEP_METERS;
				y2 = y1;

				dy = (pos_y - y1) + DIST_OFFSET;

				if (pos_x < x1)
					dx = pos_x - x1;
				else if (pos_x > x2)
					dx = pos_x - x2;
				else
					dx = 0;

				dist = dx*dx+dy*dy;

				if (dist < MIN_DIST_SQ)
					alpha = MAX_ALPHA;
				else if (dist > MAX_DIST_SQ)
					alpha = 0.0f;
				else
					alpha = 30/dist;

				alpha = llclamp(alpha, 0.0f, MAX_ALPHA);

				gGL.color4f(1.f, 1.f, 1.f, alpha);

				if ((pos_y - y1) < 0) direction = SOUTH_MASK;
				else 		direction = NORTH_MASK;

				// avoid Z fighting
				renderOneSegment(x1+0.1f, y1+0.1f, x2+0.1f, y2+0.1f, collision_height, direction, regionp);

			}

			if (segment_mask & WEST_MASK)
			{
				x1 = x * PARCEL_GRID_STEP_METERS;
				y1 = y * PARCEL_GRID_STEP_METERS;

				x2 = x1;
				y2 = y1 + PARCEL_GRID_STEP_METERS;

				dx = (pos_x - x1) + DIST_OFFSET;

				if (pos_y < y1)
					dy = pos_y - y1;
				else if (pos_y > y2)
					dy = pos_y - y2;
				else
					dy = 0;

				dist = dx*dx+dy*dy;

				if (dist < MIN_DIST_SQ)
					alpha = MAX_ALPHA;
				else if (dist > MAX_DIST_SQ)
					alpha = 0.0f;
				else
					alpha = 30/dist;

				alpha = llclamp(alpha, 0.0f, MAX_ALPHA);

				gGL.color4f(1.f, 1.f, 1.f, alpha);

				if ((pos_x - x1) > 0) direction = WEST_MASK;
				else 		direction = EAST_MASK;
				
				// avoid Z fighting
				renderOneSegment(x1+0.1f, y1+0.1f, x2+0.1f, y2+0.1f, collision_height, direction, regionp);

			}
		}
	}

	gGL.end();
}
예제 #16
0
void EntryExitPoints::process() {
    // Check if no renderer exist or if geometry changed
    if (inport_.isChanged() && inport_.hasData()) {
        drawer_ = MeshDrawerFactory::getPtr()->create(inport_.getData().get());
    }
    if (!drawer_) return;

    utilgl::DepthFuncState depthfunc(GL_ALWAYS);
    utilgl::PointSizeState pointsize(1.0f);

    shader_.activate();
    auto geom = inport_.getData();
    mat4 modelMatrix = geom->getCoordinateTransformer(camera_.get()).getDataToClipMatrix();
    shader_.setUniform("dataToClip", modelMatrix);

    {
        // generate exit points
        utilgl::activateAndClearTarget(exitPort_, ImageType::ColorDepth);
        utilgl::CullFaceState cull(GL_FRONT);
        drawer_->draw();
        utilgl::deactivateCurrentTarget();
    }

    {
        // generate entry points
        if (capNearClipping_) {
            if (!tmpEntry_ ||
                tmpEntry_->getDimensions() != entryPort_.getDimensions() ||
                tmpEntry_->getDataFormat() != entryPort_.getData()->getDataFormat()) {
                tmpEntry_.reset(
                    new Image(entryPort_.getDimensions(), entryPort_.getData()->getDataFormat()));
            }
            utilgl::activateAndClearTarget(*tmpEntry_);
        } else {
            utilgl::activateAndClearTarget(entryPort_, ImageType::ColorDepth);
        }

        utilgl::CullFaceState cull(GL_BACK);
        drawer_->draw();
        shader_.deactivate();
        utilgl::deactivateCurrentTarget();
    }

    if (capNearClipping_ && tmpEntry_) {
        // render an image plane aligned quad to cap the proxy geometry
        utilgl::activateAndClearTarget(entryPort_, ImageType::ColorDepth);
        clipping_.activate();

        TextureUnitContainer units;
        utilgl::bindAndSetUniforms(clipping_, units, *tmpEntry_, "entry", ImageType::ColorDepth);
        utilgl::bindAndSetUniforms(clipping_, units, exitPort_, ImageType::ColorDepth);

        // the rendered plane is specified in camera coordinates
        // thus we must transform from camera to world to texture coordinates
        mat4 clipToTexMat = geom->getCoordinateTransformer(camera_.get()).getClipToDataMatrix();
        clipping_.setUniform("NDCToTextureMat", clipToTexMat);
        clipping_.setUniform("nearDist", camera_.getNearPlaneDist());

        utilgl::singleDrawImagePlaneRect();
        clipping_.deactivate();
        utilgl::deactivateCurrentTarget();
    }
}
예제 #17
0
//-----------------------------------------------------------------------------
// render()
//-----------------------------------------------------------------------------
BOOL LLImagePreviewSculpted::render()
{
	mNeedsUpdate = FALSE;

	LLGLSUIDefault def;
	LLGLDisable no_blend(GL_BLEND);
	LLGLEnable cull(GL_CULL_FACE);
	LLGLDepthTest depth(GL_TRUE);

	glMatrixMode(GL_PROJECTION);
	gGL.pushMatrix();
	glLoadIdentity();
	glOrtho(0.0f, mWidth, 0.0f, mHeight, -1.0f, 1.0f);

	glMatrixMode(GL_MODELVIEW);
	gGL.pushMatrix();
	glLoadIdentity();
		
	gGL.color4f(0.15f, 0.2f, 0.3f, 1.f);

	gl_rect_2d_simple( mWidth, mHeight );

	glMatrixMode(GL_PROJECTION);
	gGL.popMatrix();

	glMatrixMode(GL_MODELVIEW);
	gGL.popMatrix();

	glClear(GL_DEPTH_BUFFER_BIT);
	
	LLVector3 target_pos(0, 0, 0);

	LLQuaternion camera_rot = LLQuaternion(mCameraPitch, LLVector3::y_axis) * 
		LLQuaternion(mCameraYaw, LLVector3::z_axis);

	LLQuaternion av_rot = camera_rot;
	LLViewerCamera::getInstance()->setOriginAndLookAt(
		target_pos + ((LLVector3(mCameraDistance, 0.f, 0.f) + mCameraOffset) * av_rot),		// camera
		LLVector3::z_axis,																	// up
		target_pos + (mCameraOffset  * av_rot) );											// point of interest

	stop_glerror();

	LLViewerCamera::getInstance()->setAspect((F32) mWidth / mHeight);
	LLViewerCamera::getInstance()->setView(LLViewerCamera::getInstance()->getDefaultFOV() / mCameraZoom);
	LLViewerCamera::getInstance()->setPerspective(FALSE, mOrigin.mX, mOrigin.mY, mWidth, mHeight, FALSE);

	const LLVolumeFace &vf = mVolume->getVolumeFace(0);
	U32 num_indices = vf.mIndices.size();
	
	mVertexBuffer->setBuffer(LLVertexBuffer::MAP_VERTEX | LLVertexBuffer::MAP_NORMAL);

	gPipeline.enableLightsAvatar();
	gGL.pushMatrix();
	const F32 SCALE = 1.25f;
	gGL.scalef(SCALE, SCALE, SCALE);
	const F32 BRIGHTNESS = 0.9f;
	gGL.color3f(BRIGHTNESS, BRIGHTNESS, BRIGHTNESS);
	mVertexBuffer->draw(LLRender::TRIANGLES, num_indices, 0);

	gGL.popMatrix();
		
	return TRUE;
}
void LLDrawPoolAlpha::renderAlpha(U32 mask, S32 pass)
{
	BOOL initialized_lighting = FALSE;
	BOOL light_enabled = TRUE;
	
	BOOL use_shaders = gPipeline.canUseVertexShaders();
		
	for (LLCullResult::sg_iterator i = gPipeline.beginAlphaGroups(); i != gPipeline.endAlphaGroups(); ++i)
	{
		LLSpatialGroup* group = *i;
		llassert(group);
		llassert(group->getSpatialPartition());

		if (group->getSpatialPartition()->mRenderByGroup &&
		    !group->isDead())
		{
			bool is_particle_or_hud_particle = group->getSpatialPartition()->mPartitionType == LLViewerRegion::PARTITION_PARTICLE
													  || group->getSpatialPartition()->mPartitionType == LLViewerRegion::PARTITION_HUD_PARTICLE;


			// <FS:LO> Dont suspend partical processing while particles are hidden, just skip over drawing them
			if(!(gPipeline.sRenderParticles) && (
												 group->getSpatialPartition()->mPartitionType == LLViewerRegion::PARTITION_PARTICLE ||
												 group->getSpatialPartition()->mPartitionType == LLViewerRegion::PARTITION_HUD_PARTICLE))
			{
				continue;
			}
			// </FS:LO>


			bool draw_glow_for_this_partition = mVertexShaderLevel > 0; // no shaders = no glow.

			
			LL_RECORD_BLOCK_TIME(FTM_RENDER_ALPHA_GROUP_LOOP);

			bool disable_cull = is_particle_or_hud_particle;
			LLGLDisable cull(disable_cull ? GL_CULL_FACE : 0);

			LLSpatialGroup::drawmap_elem_t& draw_info = group->mDrawMap[LLRenderPass::PASS_ALPHA];

			for (LLSpatialGroup::drawmap_elem_t::iterator k = draw_info.begin(); k != draw_info.end(); ++k)	
			{
				LLDrawInfo& params = **k;

				if ((params.mVertexBuffer->getTypeMask() & mask) != mask)
				{ //FIXME!
					LL_WARNS() << "Missing required components, skipping render batch." << LL_ENDL;
					continue;
				}

				// Fix for bug - NORSPEC-271
				// If the face is more than 90% transparent, then don't update the Depth buffer for Dof
				// We don't want the nearly invisible objects to cause of DoF effects
				if(pass == 1 && !LLPipeline::sImpostorRender)
				{
					LLFace*	face = params.mFace;
					if(face)
					{
						const LLTextureEntry* tep = face->getTextureEntry();
						if(tep)
						{
							if(tep->getColor().mV[3] < 0.1f)
								continue;
						}
					}
				}

				LLRenderPass::applyModelMatrix(params);

				LLMaterial* mat = NULL;

				if (deferred_render)
				{
					mat = params.mMaterial;
				}
				
				if (params.mFullbright)
				{
					// Turn off lighting if it hasn't already been so.
					if (light_enabled || !initialized_lighting)
					{
						initialized_lighting = TRUE;
						if (use_shaders) 
						{
							target_shader = fullbright_shader;
						}
						else
						{
							gPipeline.enableLightsFullbright(LLColor4(1,1,1,1));
						}
						light_enabled = FALSE;
					}
				}
				// Turn on lighting if it isn't already.
				else if (!light_enabled || !initialized_lighting)
				{
					initialized_lighting = TRUE;
					if (use_shaders) 
					{
						target_shader = simple_shader;
					}
					else
					{
						gPipeline.enableLightsDynamic();
					}
					light_enabled = TRUE;
				}

				if (deferred_render && mat)
				{
					U32 mask = params.mShaderMask;

					llassert(mask < LLMaterial::SHADER_COUNT);
					target_shader = &(gDeferredMaterialProgram[mask]);

					if (LLPipeline::sUnderWaterRender)
					{
						target_shader = &(gDeferredMaterialWaterProgram[mask]);
					}

					if (current_shader != target_shader)
					{
						gPipeline.bindDeferredShader(*target_shader);
					}
				}
				else if (!params.mFullbright)
				{
					target_shader = simple_shader;
				}
				else
				{
					target_shader = fullbright_shader;
				}
				
				if(use_shaders && (current_shader != target_shader))
				{// If we need shaders, and we're not ALREADY using the proper shader, then bind it
				// (this way we won't rebind shaders unnecessarily).
					current_shader = target_shader;
					current_shader->bind();
				}
				else if (!use_shaders && current_shader != NULL)
				{
					LLGLSLShader::bindNoShader();
					current_shader = NULL;
				}

				if (use_shaders && mat)
				{
					// We have a material.  Supply the appropriate data here.
					if (LLPipeline::sRenderDeferred)
					{
						current_shader->uniform4f(LLShaderMgr::SPECULAR_COLOR, params.mSpecColor.mV[0], params.mSpecColor.mV[1], params.mSpecColor.mV[2], params.mSpecColor.mV[3]);						
						current_shader->uniform1f(LLShaderMgr::ENVIRONMENT_INTENSITY, params.mEnvIntensity);
						current_shader->uniform1f(LLShaderMgr::EMISSIVE_BRIGHTNESS, params.mFullbright ? 1.f : 0.f);

						if (params.mNormalMap)
						{
							params.mNormalMap->addTextureStats(params.mVSize);
							current_shader->bindTexture(LLShaderMgr::BUMP_MAP, params.mNormalMap);
						} 
						
						if (params.mSpecularMap)
						{
							params.mSpecularMap->addTextureStats(params.mVSize);
							current_shader->bindTexture(LLShaderMgr::SPECULAR_MAP, params.mSpecularMap);
						} 
					}

				} else if (LLPipeline::sRenderDeferred && current_shader && (current_shader == simple_shader))
				{
					current_shader->uniform4f(LLShaderMgr::SPECULAR_COLOR, 1.0f, 1.0f, 1.0f, 1.0f);						
					current_shader->uniform1f(LLShaderMgr::ENVIRONMENT_INTENSITY, 0.0f);			
					LLViewerFetchedTexture::sFlatNormalImagep->addTextureStats(params.mVSize);
					current_shader->bindTexture(LLShaderMgr::BUMP_MAP, LLViewerFetchedTexture::sFlatNormalImagep);						
					LLViewerFetchedTexture::sWhiteImagep->addTextureStats(params.mVSize);
					current_shader->bindTexture(LLShaderMgr::SPECULAR_MAP, LLViewerFetchedTexture::sWhiteImagep);
				}

				if (params.mGroup)
				{
					params.mGroup->rebuildMesh();
				}

				bool tex_setup = false;

				if (use_shaders && params.mTextureList.size() > 1)
				{
					for (U32 i = 0; i < params.mTextureList.size(); ++i)
					{
						if (params.mTextureList[i].notNull())
						{
							gGL.getTexUnit(i)->bind(params.mTextureList[i], TRUE);
						}
					}
				}
				else
				{ //not batching textures or batch has only 1 texture -- might need a texture matrix
					if (params.mTexture.notNull())
					{
						params.mTexture->addTextureStats(params.mVSize);
						if (use_shaders && mat)
						{
							current_shader->bindTexture(LLShaderMgr::DIFFUSE_MAP, params.mTexture);
						}
						else
						{
						gGL.getTexUnit(0)->bind(params.mTexture, TRUE) ;
						}
						
						if (params.mTextureMatrix)
						{
							tex_setup = true;
							gGL.getTexUnit(0)->activate();
							gGL.matrixMode(LLRender::MM_TEXTURE);
							gGL.loadMatrix((GLfloat*) params.mTextureMatrix->mMatrix);
							gPipeline.mTextureMatrixOps++;
						}
					}
					else
					{
						gGL.getTexUnit(0)->unbind(LLTexUnit::TT_TEXTURE);
					}
				}

				{
					LL_RECORD_BLOCK_TIME(FTM_RENDER_ALPHA_PUSH);
    gGL.blendFunc((LLRender::eBlendFactor) params.mBlendFuncSrc, (LLRender::eBlendFactor) params.mBlendFuncDst, mAlphaSFactor, mAlphaDFactor);					
				params.mVertexBuffer->setBuffer(mask & ~(params.mFullbright ? (LLVertexBuffer::MAP_TANGENT | LLVertexBuffer::MAP_TEXCOORD1 | LLVertexBuffer::MAP_TEXCOORD2) : 0));
                
				params.mVertexBuffer->drawRange(params.mDrawMode, params.mStart, params.mEnd, params.mCount, params.mOffset);
				gPipeline.addTrianglesDrawn(params.mCount, params.mDrawMode);
				}
				
				// If this alpha mesh has glow, then draw it a second time to add the destination-alpha (=glow).  Interleaving these state-changing calls could be expensive, but glow must be drawn Z-sorted with alpha.
				if (current_shader && 
					draw_glow_for_this_partition &&
					// <FS:Ansariel> Re-add particle rendering optimization
					//params.mVertexBuffer->hasDataType(LLVertexBuffer::TYPE_EMISSIVE))
					params.mVertexBuffer->hasDataType(LLVertexBuffer::TYPE_EMISSIVE) &&
					(!params.mParticle || params.mHasGlow))
					// </FS:Ansariel>
				{
					// <FS:Ansariel> LL materials support merge error
					LL_RECORD_BLOCK_TIME(FTM_RENDER_ALPHA_GLOW);

					// install glow-accumulating blend mode
					gGL.blendFunc(LLRender::BF_ZERO, LLRender::BF_ONE, // don't touch color
						      LLRender::BF_ONE, LLRender::BF_ONE); // add to alpha (glow)

					// <FS:Ansariel> LL materials support merge error
					//emissive_shader->bind();
					//
					//params.mVertexBuffer->setBuffer((mask & ~LLVertexBuffer::MAP_COLOR) | LLVertexBuffer::MAP_EMISSIVE);
					params.mVertexBuffer->setBuffer(mask | LLVertexBuffer::MAP_EMISSIVE);
					// </FS:Ansariel>
					
					// do the actual drawing, again
					params.mVertexBuffer->drawRange(params.mDrawMode, params.mStart, params.mEnd, params.mCount, params.mOffset);
					gPipeline.addTrianglesDrawn(params.mCount, params.mDrawMode);

					// restore our alpha blend mode
					// <FS:Ansariel> LL materials support merge error
					//gGL.blendFunc(mColorSFactor, mColorDFactor, mAlphaSFactor, mAlphaDFactor);

					//current_shader->bind();
					// </FS:Ansariel>
				}
			
				if (tex_setup)
				{
					gGL.getTexUnit(0)->activate();
					gGL.loadIdentity();
					gGL.matrixMode(LLRender::MM_MODELVIEW);
				}
			}
		}
	}

	gGL.setSceneBlendType(LLRender::BT_ALPHA);

	LLVertexBuffer::unbind();	
		
	if (!light_enabled)
	{
		gPipeline.enableLightsDynamic();
	}
}
예제 #19
0
// [fromDate,]間に購入して保持している人の購入価格予想
// サンプリングされたプレーヤー達の購入価格の配列を返す {3500,2800,2000,..}
vector<double> estimatedPurchasedPrices(vector<Record>& records, int fromDate, int toDay)
{
    int startIdx = indexOfDate(records, fromDate-1) + 1;
    int toIdx = indexOfDate(records, toDay) + 1;
    long long maxVolume = 0;
    for (int i = startIdx; i < records.size(); i++) {
        if (records[i].volume > maxVolume) maxVolume = records[i].volume;
    }

    double x = 1.0;
    vector<double> S;
    const int maxSize = 100000;
    
    // 保有:S人、ある日の購入者N人
    // 1. p∈Sが売却 => 買値v(p)を変更
    // 2. 以前からの保有者から購入 S += {v}
    // S >= N => Sですべて賄う。NをどうS上にマップするかという問題になる。
    // 購入価格が安い順にN人が売却と考えてしまおう。
    // S < N => N - S人が新規と考えてしまう

    for (int i = startIdx; i < toIdx; i++) {
        long long N = (long long)(records[i].volume * x);

        cerr << records[i].date << ":" << records[i].end << " => " << N << "(" << x << ")" << endl;
        
        // 新規が多すぎるのでSをまず減らす
        if (N > maxSize) {
            cull(S, 1.0 * maxSize / N);
            x *= 1.0 * maxSize / N;
            N = maxSize;
        }

        //
        vector<double> f;
        Price lo = records[i].low;
        Price hi = records[i].high;
        for (int i = 0; i < (int)N; i++) {
            // [lo, hi]に均等に分布と仮定
            if (N == 1)
                f.push_back((lo + hi) / 2);
            else
                f.push_back(lo + (hi - lo) * i / (N - 1));
        }

        int l = min((int)S.size(), (int)N);

        /* 基本下からだけどある程度ランダム性を入れる */
        vector<int> indices(S.size());
        for (int i = 0; i < S.size(); i++) indices[i] = i;
        // 例えば0.1だと下からピックアップしたうち1割をランダムにする
        const double random_factor = 0.6;
        for (int i = 0; i < l; i++)
            if ((rand() & 65535) / 65535.0 < random_factor) {
                int j = rand() % S.size();
                swap(indices[i], indices[j]);
            }
        for (int i = 0; i < l; i++) {
            S[indices[i]] = f[i];
        }

        for (int i = l; i < N; i++) {
            S.push_back(f[i]);
        }

        sort(S.begin(), S.end());
    }

    return S;
}
int main(int argc, char *argv[]) {
  char file[255];
  options_type opt;
  char *data;
  char *mask = NULL;
  unsigned int mask_len = 0;
  unsigned int word_size;
  char *min_str;
  int control;
  int control_c_rep_impar = 0;
  unsigned int i, j, o;
  int err;
  int time_min;
  FILE *idf;
  char *buffer;
  char *data_hex = NULL;
  char *data_hex2 = NULL;
  char *mask_hex = NULL;
  unsigned int c_hex = 0;
  unsigned int mask_hex_len = 0;
  double file_pre_size_mb;

  opt.n = 0;
  opt.mask_c = 0;
  opt.mask_c_on = 0;
  opt.h_on = 0;
  opt.h = 0;
  opt.r = 0;
  opt.min = 0;
  opt.max = 0;
  opt.c = 0;
  opt.q = 0;
  opt.rep = 0;
  time_seg=0;

  //sin argumentos o con -? muestra el menu
  if (argc<=1) {
    mostrarmenu();
    return 0;
  }
  if (strcmp(argv[1],"-?")==0) {
    mostrarmenu();
    return 0;
  }

  //Establecer archivo de salida
  strcpy(file,argv[1]);

  //Establecer opciones de los argumentos
  for(o=2;o<argc;o++) {
    if (strcmp(argv[o],"-?")==0) {
      mostrarmenu();
      return 0;
    } else if (strcmp(argv[o],"-n")==0) {
      if (opt.n!=0) {
        printf("\nParametro %c-n%c repetido o especificado junto con el parámetro incompatible %c-m%c\n",34,34,34,34);
        return 1;
      }
      if ((o+1)>=argc) {
        opt.n=13;  //(128-24)/8;
      } else {
        opt.n=cint(argv[o+1],&err,0);
        if (err) {
          opt.n=13;  //(128-24)/8;
        } else {
          if (!((opt.n==64) || (opt.n==128) || (opt.n==152) || (opt.n==256) || (opt.n==512))) {
            printf("\nEl parametro de %c-n%c es incorrecto\n",34,34);
            return 1;
          }
          opt.n=(opt.n-24)/8;
          o++;
        }
      }
    } else if (strcmp(argv[o],"-m")==0) {
      if (opt.n!=0) {
        printf("\nParametro %c-m%c repetido o especificado junto con el parámetro incompatible %c-n%c\n",34,34,34,34);
        return 1;
      }
      if ((o+1)>=argc) {
        printf("\nFalta el parametro de %c-m%c\n",34,34);
        return 1;
      }
      opt.n=cint(argv[o+1],&err,0);
      if ((err) || (opt.n<=0)) {
        printf("\nEl parametro de %c-m%c es incorrecto\n",34,34);
        return 1;
      }
      o++;
    } else if (strcmp(argv[o],"-h")==0) {
      if (opt.h_on) {
        printf("\nParametro %c-h%c repetido\n",34,34);
        return 1;
      }
      opt.h_on=1;
      opt.h=':';
      if (!((o+1)>=argc)) {
        if ((cint(argv[o+1],&err,0)<0) || (cint(argv[o+1],&err,0)>255) || ((cint(argv[o+1],&err,0)>47) && (cint(argv[o+1],&err,0)<58))) {
          printf("\nEl parametro de %c-h%c debe estar dentro del rango [0-47][58-255]\n",34,34);
          return 1;
        }
        opt.h=cint(argv[o+1],&err,0);
        if (err) {
          opt.h=':';
        } else {
          o++;
        }
      }
    } else if (strcmp(argv[o],"-min")==0) {
      if (opt.min!=0) {
        printf("\nParametro %c-min%c repetido\n",34,34);
        return 1;
      }
      if ((o+1)>=argc) {
        printf("\nFalta el parametro de %c-min%c\n",34,34);
        return 1;
      }
      if (strlen(argv[o+1])>15) {
        printf("\nEl parametro de %c-min%c no puede exceder de 15 digitos\n",34,34);
        return 1;
      }
      opt.min=cull(argv[o+1],&err,0);
      if (err) {
        printf("\nEl parametro de %c-min%c es incorrecto\n",34,34);
        return 1;
      }
      if (opt.max!=0) {
        if (opt.min>opt.max) {
          printf("\nEl parametro de %c-min%c debe ser menor o igual que el de %c-max%c\n",34,34,34,34);
          return 1;
        }
      }
      o++;
    } else if (strcmp(argv[o],"-max")==0) {
      if (opt.max!=0) {
        printf("\nParametro %c-max%c repetido\n",34,34);
        return 1;
      }
      if ((o+1)>=argc) {
        printf("\nFalta el parametro de %c-max%c\n",34,34);
        return 1;
      }
      if (strlen(argv[o+1])>15) {
        printf("\nEl parametro de %c-max%c no puede exceder de 15 digitos\n",34,34);
        return 1;
      }
      opt.max=cull(argv[o+1],&err,0);
      if ((err) || (opt.max==0)) {
        printf("\nEl parametro de %c-max%c es incorrecto\n",34,34);
        return 1;
      }
      if (opt.min!=0) {
        if (opt.min>opt.max) {
          printf("\nEl parametro de %c-min%c debe ser menor o igual que el de %c-max%c\n",34,34,34,34);
          return 1;
        }
      }
      o++;
    } else if (strcmp(argv[o],"-c")==0) {
      if (opt.c!=0) {
        printf("\nParametro %c-c%c repetido\n",34,34);
        return 1;
      }
      if ((o+1)>=argc) {
        printf("\nFalta el parametro de %c-c%c\n",34,34);
        return 1;
      }
      opt.c=cint(argv[o+1],&err,0);
      if ((err) || (opt.c<=0)) {
        printf("\nEl parametro de %c-c%c es incorrecto\n",34,34);
        return 1;
      }
      o++;
    } else if (strcmp(argv[o],"-cm")==0) {
      if (opt.mask_c_on!=0) {
        printf("\nPrametro %c-cm%c repetido\n",34,34);
        return 1;
      }
      if ((o+1)>=argc) {
        printf("\nFalta el parametro de %c-cm%c\n",34,34);
        return 1;
      }
      if ((cint(argv[o+1],&err,0)<0) || (cint(argv[o+1],&err,0)>255)) {
        printf("\nEl parametro de %c-cm%c debe estar dentro del rango [0-255]\n",34,34);
        return 1;
      }
      opt.mask_c=cint(argv[o+1],&err,0);
      if (err) {
        printf("\nEl parametro de %c-cm%c es incorrecto\n",34,34);
        return 1;
      }
      opt.mask_c_on=1;
      o++;
    } else if (strcmp(argv[o],"-r")==0) {
      opt.r=1;
    } else if (strcmp(argv[o],"-q")==0) {
      opt.q=1;
    } else if (strcmp(argv[o],"-rep")==0) {
      if ((o+1)>=argc) {
        printf("\nFalta el parametro de %c-rep%c\n",34,34);
        return 1;
      }
      opt.rep=cint(argv[o+1],&err,0);
      if ((err) || (opt.rep<=0)) {
        printf("\nEl parametro de %c-rep%c es incorrecto\n",34,34);
        return 1;
      }
      o++;
    } else {
      printf("\nParametro %c%s%c no reconocido\n",34,argv[o],34);
      return 1;
    }
  }

  //Opciones por defecto y ajuste
  if (opt.n==0) {
    opt.n=13;  //(128-24)/8
  }
  if (opt.c==0) {
    opt.c=8;
  }
  if (opt.h_on) {
    if (opt.rep) {
      if ((opt.c*(opt.rep+1))>(opt.n*2)) {
        printf("\nParametros de %c-c%c y de %c-rep%c incorrectos\n",34,34,34,34);
        return(1);
      }
    } else if (opt.c>(opt.n*2)) {
      opt.c=opt.n*2;
    }
  } else {
    if (opt.rep) {
      if ((opt.c*(opt.rep+1))>opt.n) {
        printf("\nParametros de %c-c%c y de %c-rep%c incorrectos\n",34,34,34,34);
        return(1);
      }
    } else if (opt.c>opt.n) {
      opt.c=opt.n;
    }
  }
  if (opt.mask_c_on==0) {
    opt.mask_c=48;
  }
  if (opt.min>(potull(10,opt.c)-1)) {
    printf("\nParametro de %c-min%c incorrecto\n",34,34);
    return(1);
  }
  if (opt.max>(potull(10,opt.c)-1)) {
    printf("\nParametro de %c-max%c incorrecto\n",34,34);
    return(1);
  }

  //Operaciones previas a la escritura
  min_str = (char *) calloc(1,16);
  if (min_str==NULL) {
    printf("\nMemoria insuficiente\n");
    return -1;
  }

  ullToStr(opt.min,&min_str,16);

  data=(char *) calloc(1,opt.c+1);
  if (data==NULL) {
    printf("\nMemoria insuficiente\n");
    free(min_str);
    return -1;
  }

  for(o=0;o<opt.c;o++) {
    if (o<(opt.c-strlen(min_str))) {
      data[o]=48;
    } else {
      data[o]=min_str[o-(opt.c-strlen(min_str))];
    }
  }
  if (opt.h_on) {
    mask_hex_len=(opt.n*3-1)-opt.c*(opt.rep+1)-(opt.c*(opt.rep+1)-1)/2 + 2 - opt.r;
    c_hex=opt.c+(opt.c-1)/2;
    data_hex=(char *) calloc(1,c_hex+1);
    if (data_hex==NULL) {
      printf("\nMemoria insuficiente\n");
      free(min_str);
      free(data);
      return -1;
    }
    if ((opt.rep) && (opt.c % 2)) {
      control_c_rep_impar = 1;
      data_hex2=(char *) calloc(1,c_hex+1);
      if (data_hex2==NULL) {
        printf("\nMemoria insuficiente\n");
        free(min_str);
        free(data);
        free(data_hex);
        return -1;
      }
    }
    mask_hex=(char *) calloc(1,mask_hex_len+1);
    if (mask_hex==NULL) {
      printf("\nMemoria insuficiente\n");
      free(min_str);
      free(data);
      free(data_hex);
      if (control_c_rep_impar) free(data_hex2);
      return -1;
    }
    for(o=0;o<mask_hex_len;o++) {
      if ((o%3)==(opt.c*(opt.rep+1)%2)) {
        mask_hex[o]=opt.h;
      } else {
        mask_hex[o]=opt.mask_c;
      }
    }
    if (opt.r) {
      mask_hex[mask_hex_len-1]=10;
    } else {
      mask_hex[mask_hex_len-2]=13;
      mask_hex[mask_hex_len-1]=10;
    }
    word_size = opt.n*3 + 1 - opt.r;
  } else {
    mask_len=opt.n-opt.c*(opt.rep+1)+1;
    if (opt.r==0) {
      mask_len++;
    }
    mask=(char *) calloc(1,mask_len+1);
    if (mask==NULL) {
      printf("\nMemoria insuficiente\n");
      free(min_str);
      free(data);
      return -1;
    }
    for(o=0;o<mask_len;o++) {
      mask[o]=opt.mask_c;
    }
    if (opt.r) {
      mask[mask_len-1]=10;
    } else {
      mask[mask_len-2]=13;
      mask[mask_len-1]=10;
    }
    word_size=(opt.n + 2 - opt.r);
  }
  buffer_len = (MEM_BUFFER/word_size)*word_size;
  buffer = (char *) malloc(buffer_len);
  if (buffer==NULL) {
    printf("\nMemoria insuficiente, se intentara reservar una memoria minima...");
    buffer_len = word_size;
    buffer = malloc(buffer_len);
    if (buffer==NULL) {
      printf(" FALLO!\n");  
      free(min_str);
      free(data);
      if (opt.h_on) {
        free(data_hex);
        if (control_c_rep_impar) free(data_hex2);
        free(mask_hex);
      } else {
        free(mask);
      }
      return(-1);
    } else {
      printf(" CORRECTO!\n");
    }
  }

  //Abrimos el archivo
  if ((idf=fopen(file, "wb"))==NULL) {
    printf("\nError accediendo al archivo %c%s%c\n",34,file,34);
    free(min_str);
    free(data);
    if (opt.h_on) {
      free(data_hex);
      if (control_c_rep_impar) free(data_hex2);
      free(mask_hex);
    } else {
      free(mask);
    }
    return -1;
  }

  //Establece algunos parametros
  if (opt.max) {
    nclaves=opt.max-opt.min+1;
  } else {
    nclaves=potull(10,opt.c)-opt.min;
  }
  file_pre_size=nclaves*word_size;
  file_pre_size_mb=(double) file_pre_size/1048576;

  printf("\n\nEl diccionario contendra %llu claves y ocupara %0.2lfMB\n",nclaves,file_pre_size_mb);
  printf("\nGenerando diccionario... (Ctrl+C para cancelar)\n\n\n\n");

  exit_th_mostrarProceso=1;
  control=1;
  v=0;
  n_buff_writes=0;
  time_i=time(NULL);
  if (!(opt.q)) {
    if (pthread_mutex_init(&proc_mutex,NULL)) opt.q=1;
    exit_th_mostrarProceso = 1;
    if (!(opt.q)) pthread_create(&th_mostrarProceso,NULL,(void *)&mostrarproceso,NULL);
  }
  //Empieza la generacion y escritura del diccionario
  if (opt.h_on) {
    //Modo: Hexadecimal
    while(control){
      ArrayToHex(data_hex,data,c_hex,opt.h,0);
      memcpy(&buffer[v],data_hex,c_hex);
      v+=c_hex;
      if (control_c_rep_impar) {
        ArrayToHex(data_hex2,data,c_hex,opt.h,-1);
        for (j=0;j<opt.rep;j++) {
          if (j%2) {
            memcpy(&buffer[v],&(opt.h),1);
            v++;
            memcpy(&buffer[v],data_hex,c_hex);
            v+=c_hex;
          } else {
            memcpy(&buffer[v],data_hex2,c_hex);
            v+=c_hex;
          }
        }
      } else {
        for (j=0;j<opt.rep;j++) {
          memcpy(&buffer[v],&(opt.h),1);
          v++;
          memcpy(&buffer[v],data_hex,c_hex);
          v+=c_hex;
        }
      }
      memcpy(&buffer[v],mask_hex,mask_hex_len);
      v+=mask_hex_len;
      if (v>=buffer_len) {
        fwrite(buffer, 1, buffer_len, idf);
        if (!(opt.q)) {
          pthread_mutex_lock(&proc_mutex);
          n_buff_writes++;
          v=0;
          pthread_mutex_unlock(&proc_mutex);
        } else {
          v=0;
        }
      }
      if ((opt.max) && (cull(data,&err,opt.c)>=opt.max)) {
        control=0;
      }
      i=opt.c-1;
      while(data[i]>=57) {
        data[i]=48;
        if (i>0) {
          i--;
        } else {
          control=0;
        }
      }
      data[i]++;
    }
    if (v!=0) {
      fwrite(buffer, 1, v, idf);
    }
    free(data_hex);
    if (control_c_rep_impar) free(data_hex2);
    free(mask_hex);
  } else {
    //Modo: ASCII
    while(control){
      memcpy(&buffer[v],data,opt.c);
      v+=opt.c;
      for (j=0;j<opt.rep;j++) {
        memcpy(&buffer[v],data,opt.c);
        v+=opt.c;
      }
      memcpy(&buffer[v],mask,mask_len);
      v+=mask_len;
      if (v>=buffer_len) {
        fwrite(buffer, 1, buffer_len, idf);
        if (!(opt.q)) {
          pthread_mutex_lock(&proc_mutex);
          n_buff_writes++;
          v=0;
          pthread_mutex_unlock(&proc_mutex);
        } else {
          v=0;
        }
      }
      if ((opt.max) && (cull(data,&err,opt.c)>=opt.max)) {
        control=0;
      }
      i=opt.c-1;
      while(data[i]>=57) {
        data[i]=48;
        if (i>0) {
          i--;
        } else {
          control=0;
        }
      }
      data[i]++;
    }
    if (v!=0) {
      fwrite(buffer, 1, v, idf);
    }
    free(mask);
  }
  time_seg=time(NULL)-time_i;

  //Finalizacion del proceso
  exit_th_mostrarProceso=0;

  if (!(opt.q)) {
    pthread_join(th_mostrarProceso,NULL);
  }

  time_min=0;
  while (time_seg>=60) {
    time_seg-=60;
    time_min++;
  }

  printf("\nDiccionario creado correctamente como %c%s%c\n",34,file,34);
  printf("Tiempo empleado: %d minutos %d segundos\n\n",time_min,time_seg);

  //Liberacion de memoria y recursos
  free(buffer);
  fclose(idf);
  free(min_str);
  free(data);
  if (!(opt.q)) pthread_mutex_destroy(&proc_mutex);

  return(0);
}
예제 #21
0
void Camera::cull( RenderBlock& block, const Entity* entity )
{
	if( !entity ) return;

	// Try to see if this is a Group-derived node.
	Class* klass = entity->getType();
	
	if( ClassInherits(klass, ReflectionGetType(Group)) )
	{
		const Group* group = (Group*) entity;

		const Array<EntityPtr>& entities = group->getEntities();

		// Cull the children entities recursively.
		for( size_t i = 0; i < entities.size(); i++ )
		{
			const Entity* child = entities[i].get();
			cull( block, child );
		}

		return;
	}

	// If this is a visible.renderable object, then we perform frustum culling
	// and then we push it to a list of things passed later to the renderer.

	//entity->onPreCull();

	if( !entity->isVisible() )
		return;

	const Transform* transform = entity->getTransform().get();
	const BoundingBox& box = transform->getWorldBoundingVolume();

	bool isCulled = !entity->getTag(Tags::NonCulled);
	
	if( frustumCulling && isCulled && !frustum.intersects(box) )
		return;

	#pragma TODO("Fix multiple geometry instancing")

	const Array<GeometryPtr>& geoms = entity->getGeometry();

	for( size_t i = 0; i < geoms.size(); i++ )
	{
		const GeometryPtr& geometry = geoms[i];
		geometry->appendRenderables( block.renderables, transform );
	}

#if 0
	const LightPtr& light = entity->getComponent<Light>();
	
	if( light ) 
	{
		LightState ls;
		ls.light = light.get();
		ls.transform = transform.get();
	
		block.lights.pushBack( ls );
	}
#endif

#ifdef BUILD_DEBUG
	const ComponentMap& components = entity->getComponents();
	for( auto it = components.begin(); it != components.end(); it++ )
	{
		const ComponentPtr& component = it->value;
		component->onPreRender(*this);

		if( !component->isDebugRenderableVisible() )
			continue;

		DebugDrawFlags flags = (DebugDrawFlags) 0;
		component->onDebugDraw(drawer, flags);
	}
#endif
}
예제 #22
0
HRESULT KG3DShadowMapLevel::ProcessShadowMapWithPVS(KG3DRepresentObjectPVS* pPVS)
{
	HRESULT hResult = E_FAIL;
	HRESULT hr = S_OK;
	LPDIRECT3DSURFACE9 pDepthSave = NULL;
	LPDIRECT3DSURFACE9 pTargetSave = NULL;
	D3DVIEWPORT9 ViewportSave;
	D3DVIEWPORT9 Viewport;
	BOOL bSetRenderTarget = FALSE;
	BOOL bSetDepthStencilSurface = FALSE;
	BOOL bSetViewport = FALSE;

	m_vCameraLight.SetCamera();

	//////////////////////////////////////////////////////////////////////////

	Viewport.X = 0;
	Viewport.Y = 0;
	Viewport.Height = m_dwShadowmapSize;
	Viewport.Width = m_dwShadowmapSize;
	Viewport.MaxZ = 1;
	Viewport.MinZ = 0;

	hr = g_pd3dDevice->GetDepthStencilSurface(&pDepthSave);
	KGLOG_COM_PROCESS_ERROR(hr);

	hr = g_pd3dDevice->GetRenderTarget(0, &pTargetSave);
	KGLOG_COM_PROCESS_ERROR(hr);

	hr = g_pd3dDevice->GetViewport(&ViewportSave);
	KGLOG_COM_PROCESS_ERROR(hr);

	hr = g_pd3dDevice->SetRenderTarget(0, m_lpSMColorSurface);
	KGLOG_COM_PROCESS_ERROR(hr);

	bSetRenderTarget = TRUE;

	hr = g_pd3dDevice->SetDepthStencilSurface(m_lpSMShadowMapSurface);
	KGLOG_COM_PROCESS_ERROR(hr);

	bSetDepthStencilSurface = TRUE;

	hr = g_pd3dDevice->SetViewport(&Viewport);
	KGLOG_COM_PROCESS_ERROR(hr);

	bSetViewport = TRUE;

	//////////////////////////////////////////////////////////////////////////
	g_pd3dDevice->BeginScene();

	hr = g_pd3dDevice->Clear(0, 0, D3DCLEAR_ZBUFFER | D3DCLEAR_STENCIL, 0xFF000000, 1, 0);
	KGLOG_COM_PROCESS_ERROR(hr);

	{
		GraphicsStruct::RenderState cull(D3DRS_CULLMODE,D3DCULL_NONE);
		g_bForceDisableCull = TRUE;

		pPVS->RenderHierarchy(FALSE,NULL);

		g_bForceDisableCull = FALSE;
	}

	g_pd3dDevice->EndScene();

	hResult = S_OK;
Exit0:

	if (bSetRenderTarget)
	{
		hr = g_pd3dDevice->SetRenderTarget(0,pTargetSave);
		KGLOG_COM_CHECK_ERROR(hr);
	}
	KG_COM_RELEASE(pTargetSave);

	if (bSetDepthStencilSurface)
	{
		hr = g_pd3dDevice->SetDepthStencilSurface(pDepthSave);
		KGLOG_COM_CHECK_ERROR(hr);
	}
	KG_COM_RELEASE(pDepthSave);

	if (bSetViewport)
	{
		hr = g_pd3dDevice->SetViewport(&ViewportSave);
		KGLOG_COM_CHECK_ERROR(hr);
	}

	return hResult;
}
예제 #23
0
DRReturn render(float fTime)
{
    glViewport(0, 0, g_pSDLWindow->w, g_pSDLWindow->h);
    
    glClearColor(0.1, 0.2, 0.0, 0);
    glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glColor3f(0.0f, 0.0f, 0.0f);
    
    glDisable(GL_LIGHTING);
    glDisable(GL_TEXTURE_2D);
    glEnable(GL_CULL_FACE);
    //if(g_terrain)
      //  g_terrain->bind();
    //if(g_Player.getSektor()->renderAll(fTime, g_Player.getCamera()))
    if(wireframe)
        glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
    else
        glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
    
    if(g_Player.getSektor()->renderAll(fTime, g_Player.getCamera()))
        LOG_ERROR("Fehler bei render sektor", DR_ERROR);
    ShaderProgram::unbind();
    glDisable(GL_LIGHTING);
    glEnable(GL_CULL_FACE);
    
    glClear (GL_DEPTH_BUFFER_BIT);    
    glColor3f(1.0f, 1.0f, 1.0f);    
    
    //Reseten der Matrixen
    glMatrixMode(GL_TEXTURE);
    glLoadIdentity();
    
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();

    //gluPerspective(g_Player.getCameraFOV(), (GLfloat)XWIDTH/(GLfloat)YHEIGHT, 0.1f, 2000.0f);
    glMultMatrixf(DRMatrix::perspective_projection(g_Player.getCameraFOV(), (GLfloat)XWIDTH/(GLfloat)YHEIGHT, 0.1f, 2000.0f));
    DRFrustumCulling cull(g_cam, g_Player.getCameraFOV(), (GLfloat)XWIDTH/(GLfloat)YHEIGHT, 0.1f, 1000.0f);
    glMatrixMode(GL_MODELVIEW);          // Select the modelview matrix

    glLoadIdentity();                    // Reset (init) the modelview matrix
    DRVector3 translate(0.0f);
    g_cam->setKameraMatrix();
    glEnable(GL_DEPTH_TEST);             // Enables depth test
        
    //light
    //Add ambient light
    GLfloat ambientColor[] = {0.4f, 0.4f, 0.4f, 1.0f}; //Color(0.2, 0.2, 0.2)
    glLightModelfv(GL_LIGHT_MODEL_AMBIENT, ambientColor);
    
    //Add positioned light
    GLfloat lightColor0[] = {1.0f, 1.0f, 1.0f, 1.0f}; //Color (0.5, 0.5, 0.5)
    GLfloat lightPos0[] = {4.0f, 0.0f, 8.0f, 1.0f}; //Positioned at (4, 0, 8)
    glLightfv(GL_LIGHT0, GL_DIFFUSE, lightColor0);
    glLightfv(GL_LIGHT0, GL_POSITION, lightPos0);
    glDisable(GL_LIGHT0);
    
    //Add directed light
    GLfloat lightColor1[] = {0.5f, 0.5f, 0.5f, 1.0f}; //Color (0.5, 0.2, 0.2)
    //Coming from the direction (-1, 0.5, 0.5)
    GLfloat lightPos1[] = {-1.0f, 0.5f, 0.5f, 0.0f};
    glLightfv(GL_LIGHT1, GL_DIFFUSE, lightColor1);
    glLightfv(GL_LIGHT1, GL_POSITION, lightPos1);
    glEnable(GL_LIGHT1);       
    
    if(g_tex.getResourcePtrHolder())
        g_tex->bind();
      
    //glColor3f(0.2f, 0.5f, 0.1f);
 /*   glColor3f(1.0f, 1.0f, 1.0f);
    glBegin(GL_QUADS);
        glTexCoord2f(1.0, 0.0f);
        glVertex3f( 50.0f, 0.0f, -50.0f);
        glTexCoord2f(0.0, 0.0f);
        glVertex3f(-50.0f, 0.0f, -50.0f);
        glTexCoord2f(0.0, 1.0f);
        glVertex3f(-50.0f, 0.0f,  50.0f);
        glTexCoord2f(1.0, 1.0f);
        glVertex3f( 50.0f, 0.0f,  50.0f);
    glEnd();
    
    //glDisable(GL_TEXTURE_2D);
    
    glTranslatef(0.0f, 2.0f, 0.0f);
    glBegin(GL_QUADS);
        glColor3f(0.0f, 0.0f, 1.0f);
        glVertex3f(1.0f, 0.0f, 0.0f);
        glVertex3f(-1.0f, 0.0f, 0.0f);
        glVertex3f(-1.0f, 0.0f, -1.0f);
        glVertex3f(1.0f, 0.0f, 0.0f);
    glEnd();
    glTranslatef(0.0f, -2.0f, 0.0f);
    
  //  printf("bevore renderBlock\n");
    
    glTranslatef(0.0f, 10.0f, 0.0f);
    translate.y += 10.0f;
	//*/
    RenderBlock* rb =  g_RenderBlockLoader.getRenderBlock("dirt");
	/*
    rb->render();
    
    glTranslatef(0.0f, -5.0f, 0.0f);
    translate.y -= 5.0f;
    rb = g_RenderBlockLoader.getRenderBlock("dirG");
    rb->render();
    glTranslatef(1.0f, 0.0f, 0.0f);
    translate.x += 1.0f;
    rb->render();
    glTranslatef(0.0f, 2.0f, 0.0f);
    translate.y += 2.0f;
    
	DRFrustumPosition res = cull.isBoxInFrustum(DRVector3(-0.5f), DRVector3(0.5f), DRMatrix::translation(translate));
    if(res != OUTSIDE)    
        g_RenderBlockLoader.getRenderBlock("benc")->render();
    
    glDisable(GL_TEXTURE_2D);
    //glDisable(GL_LIGHTING);
    
    //*/
    
    static u32 start = 0;
    float dir[] = {1.0f, 1.0f};
    int y = 0;
    const int length = 250;
    int clipCount = 0;
    int renderCount = 0;
    
    for(int i = 0; i < blockCount; i++)
    {           
        if(!(i % 10))
        {
            glTranslatef(0.0f, 1.0f, 0.0f);
            translate.y += 1.0f;
            
            if(cull.isSphereInFrustum(translate, 0.6f) != OUTSIDE)
            {
                rb->render();
                renderCount++;
            }
            else clipCount++;
            
            glTranslatef(0.0f, -1.0f, 0.0f);
            translate.y -= 1.0f;
        }
        if(!(i % length))
        {
            if(!(y % length))
            {
                glTranslatef(0.0f, 1.0f, 0.0f);
                translate.y += 1.0f;
                dir[1] *= -1.0f;
                dir[0] *= -1.0f;
            }
            else
            {
                glTranslatef(0.0f, 0.0f, 1.0f*dir[1]);
                translate.z += 1.0f*dir[1];
                dir[0] *= -1.0f;
             
            }
            y++;
        }
        else
        {
            glTranslatef(1.0f*dir[0], 0.0f, 0.0f);
            translate.x += 1.0f*dir[0];
        }
        if(cull.isSphereInFrustum(translate, 0.6f) != OUTSIDE)
        {
                rb->render();
                renderCount++;
        }
        else clipCount++;
    }
    u32 end = SDL_GetTicks();
          
    //FPS
    g_Font->begin();
        
    DRText text(g_Font);
    text.setFlags(DR_FF_RELATIVE | DR_FF_RELATIVSCALING);
    text.setText("FPS: %.0f", 1.0f/fTime);
    text.setPosition(DRVector2(0.0f, 0.0f));
    text.setColor12(DRColor(0.8f, 0.5f, 0.1f));
    text.setScaling(DRVector2(1.0f));
    text.drawText();    
    
    text.setText("Count: %d", blockCount);
    text.setPosition(DRVector2(0.0f, 0.04f));
    text.drawText();
    
    text.setText("milliseconds: %u", end-start);
    text.setPosition(DRVector2(0.1f, 0.0f));
    text.drawText();
    
    text.setText("Steuerung: %d - %s/s", gCurrentControlMode+1, gControlModes[gCurrentControlMode].mValue.print().data());
    text.setPosition(DRVector2(0.0f, 0.08f));
    text.drawText();

	GlobalRenderer& gb = GlobalRenderer::Instance();
    DRTextureManager& tx = DRTextureManager::Instance();
    text.setColor12(DRColor(1.0f, 1.0f, 1.0f));
    text.setScaling(DRVector2(0.8f));
	text.setText("Grafik Memory: %.0f MByte", static_cast<double>(tx.getGrafikMemoryTexture()+gb.getGrafikMemoryGeometrie())/(1024.0f*1024.0));
	text.setPosition(DRVector2(0.8f, 0.0f));
	text.drawText();
    
	text.setText("Texture: %.0f MByte", static_cast<double>(tx.getGrafikMemoryTexture())/(1024.0f*1024.0));
	text.setPosition(DRVector2(0.8f, 0.04f));
	text.drawText();

	text.setText("Geometrie: %.0f MByte",static_cast<double>(gb.getGrafikMemoryGeometrie())/(1024.0f*1024.0));
	text.setPosition(DRVector2(0.8f, 0.08f));
	text.drawText();
    
    g_Font->end();
   
    start = SDL_GetTicks();    
    if(GlobalRenderer::Instance().renderTasks())
        LOG_ERROR("Fehler bei calling GlobalRenderer::renderTasks", DR_ERROR);

    return DR_OK;
}