Example #1
0
/////////////////////////////////////////////////////////
// Render
//
void GEMglPushName :: render(GemState *state) {
	glPushName (name);
}
Example #2
0
void Selection(void)											// This Is Where Selection Is Done
{
	GLuint	buffer[512];										// Set Up A Selection Buffer
	GLint	hits;												// The Number Of Objects That We Selected

	if (game)													// Is Game Over?
		return;													// If So, Don't Bother Checking For Hits
	
	PlaySound("data/shot.wav",NULL,SND_ASYNC);					// Play Gun Shot Sound

	// The Size Of The Viewport. [0] Is <x>, [1] Is <y>, [2] Is <length>, [3] Is <width>
	GLint	viewport[4];

	// This Sets The Array <viewport> To The Size And Location Of The Screen Relative To The Window
	glGetIntegerv(GL_VIEWPORT, viewport);
	glSelectBuffer(512, buffer);								// Tell OpenGL To Use Our Array For Selection

	// Puts OpenGL In Selection Mode. Nothing Will Be Drawn.  Object ID's and Extents Are Stored In The Buffer.
	(void) glRenderMode(GL_SELECT);

	glInitNames();												// Initializes The Name Stack
	glPushName(0);												// Push 0 (At Least One Entry) Onto The Stack

	glMatrixMode(GL_PROJECTION);								// Selects The Projection Matrix
	glPushMatrix();												// Push The Projection Matrix
	glLoadIdentity();											// Resets The Matrix

	// This Creates A Matrix That Will Zoom Up To A Small Portion Of The Screen, Where The Mouse Is.
	gluPickMatrix((GLdouble) mouse_x, (GLdouble) (viewport[3]-mouse_y), 1.0f, 1.0f, viewport);

	// Apply The Perspective Matrix
	gluPerspective(45.0f, (GLfloat) (viewport[2]-viewport[0])/(GLfloat) (viewport[3]-viewport[1]), 0.1f, 100.0f);
	glMatrixMode(GL_MODELVIEW);									// Select The Modelview Matrix
	DrawTargets();												// Render The Targets To The Selection Buffer
	glMatrixMode(GL_PROJECTION);								// Select The Projection Matrix
	glPopMatrix();												// Pop The Projection Matrix
	glMatrixMode(GL_MODELVIEW);									// Select The Modelview Matrix
	hits=glRenderMode(GL_RENDER);								// Switch To Render Mode, Find Out How Many
																// Objects Were Drawn Where The Mouse Was
	if (hits > 0)												// If There Were More Than 0 Hits
	{
		int	choose = buffer[3];									// Make Our Selection The First Object
		int depth = buffer[1];									// Store How Far Away It Is 

		for (int loop = 1; loop < hits; loop++)					// Loop Through All The Detected Hits
		{
			// If This Object Is Closer To Us Than The One We Have Selected
			if (buffer[loop*4+1] < GLuint(depth))
			{
				choose = buffer[loop*4+3];						// Select The Closer Object
				depth = buffer[loop*4+1];						// Store How Far Away It Is
			}       
		}

		if (!object[choose].hit)								// If The Object Hasn't Already Been Hit
		{
			object[choose].hit=TRUE;							// Mark The Object As Being Hit
			score+=1;											// Increase Score
			kills+=1;											// Increase Level Kills
			if (kills>level*5)									// New Level Yet?
			{
				miss=0;											// Misses Reset Back To Zero
				kills=0;										// Reset Level Kills
				level+=1;										// Increase Level
				if (level>30)									// Higher Than 30?
					level=30;									// Set Level To 30 (Are You A God?)
			}
		}
    }
}
Example #3
0
void cc2DLabel::drawMeOnly3D(CC_DRAW_CONTEXT& context)
{
	assert(!m_points.empty());

	//standard case: list names pushing
	bool pushName = MACRO_DrawEntityNames(context);
	if (pushName)
	{
		//not particularily fast
		if (MACRO_DrawFastNamesOnly(context))
			return;
		glPushName(getUniqueID());
	}

    const float c_sizeFactor = 4.0f;
    bool loop=false;

	size_t count = m_points.size();
    switch (count)
    {
    case 3:
		{
			glPushAttrib(GL_COLOR_BUFFER_BIT);
			glEnable(GL_BLEND);

			//we draw the triangle
			glColor4ub(255,255,0,128);
			glBegin(GL_TRIANGLES);
			for (unsigned i=0;i<count;++i)
				glVertex3fv(m_points[i].cloud->getPoint(m_points[i].index)->u);
			glEnd();

			glPopAttrib();
			loop=true;
		}
    case 2:
		{
			//segment width
			glPushAttrib(GL_LINE_BIT);
			glLineWidth(c_sizeFactor);

			//we draw the segments
			if (isSelected())
				glColor3ubv(ccColor::red);
			else
				glColor3ubv(ccColor::green);
			glBegin(GL_LINES);
			for (unsigned i=0; i<count; i++)
			{
				if (i+1<count || loop)
				{
					glVertex3fv(m_points[i].cloud->getPoint(m_points[i].index)->u);
					glVertex3fv(m_points[(i+1)%count].cloud->getPoint(m_points[(i+1)%count].index)->u);
				}
			}
			glEnd();
			glPopAttrib();
		}

    case 1:
		{
			//display point marker as spheres
			{
				if (!c_unitPointMarker)
				{
					c_unitPointMarker = QSharedPointer<ccSphere>(new ccSphere(1.0f,0,"PointMarker",12));
					c_unitPointMarker->showColors(true);
					c_unitPointMarker->setVisible(true);
					c_unitPointMarker->setEnabled(true);
				}
			
				//build-up point maker own 'context'
				CC_DRAW_CONTEXT markerContext = context;
				markerContext.flags &= (~CC_DRAW_ENTITY_NAMES); //we must remove the 'push name flag' so that the sphere doesn't push its own!
				markerContext._win = 0;

				if (isSelected() && !pushName)
					c_unitPointMarker->setTempColor(ccColor::red);
				else
					c_unitPointMarker->setTempColor(ccColor::magenta);

				for (unsigned i=0; i<count; i++)
				{
					glMatrixMode(GL_MODELVIEW);
					glPushMatrix();
					const CCVector3* P = m_points[i].cloud->getPoint(m_points[i].index);
					glTranslatef(P->x,P->y,P->z);
					glScalef(context.pickedPointsRadius,context.pickedPointsRadius,context.pickedPointsRadius);
					c_unitPointMarker->draw(markerContext);
					glPopMatrix();
				}
			}

			if (m_dispIn3D && !pushName) //no need to display label in point picking mode
			{
				QFont font(context._win->getTextDisplayFont());
				//font.setPointSize(font.pointSize()+2);
				font.setBold(true);

				//draw their name
				glPushAttrib(GL_DEPTH_BUFFER_BIT);
				glDisable(GL_DEPTH_TEST);
				for (unsigned j=0; j<count; j++)
				{
					const CCVector3* P = m_points[j].cloud->getPoint(m_points[j].index);
					QString title = (count == 1 ? getName() : QString("P#%0").arg(m_points[j].index));
					context._win->display3DLabel( title, *P+CCVector3(context.pickedPointsTextShift), ccColor::magenta, font);
				}
				glPopAttrib();
			}
		}
    }

	if (pushName)
		glPopName();
}
Example #4
0
  void operator () (GFace *f)
  {
    if(!f->getVisibility()) {
      if(f->getCompound()) {
        if(!f->getCompound()->getVisibility()) return;
      }
      else
        return;
    }

    bool select = (_ctx->render_mode == drawContext::GMSH_SELECT &&
                   f->model() == GModel::current());
    if(select) {
      glPushName(2);
      glPushName(f->tag());
    }

    drawArrays(_ctx, f, f->va_lines, GL_LINES,
               CTX::instance()->mesh.light && CTX::instance()->mesh.lightLines,
               CTX::instance()->mesh.surfacesFaces, CTX::instance()->color.mesh.line);
    drawArrays(_ctx, f, f->va_triangles, GL_TRIANGLES, CTX::instance()->mesh.light);

    if(CTX::instance()->mesh.surfacesNum) {
      if(CTX::instance()->mesh.triangles)
        drawElementLabels(_ctx, f, f->triangles, CTX::instance()->mesh.surfacesFaces,
                          CTX::instance()->color.mesh.line);
      if(CTX::instance()->mesh.quadrangles)
        drawElementLabels(_ctx, f, f->quadrangles, CTX::instance()->mesh.surfacesFaces,
                          CTX::instance()->color.mesh.line);
      drawElementLabels(_ctx, f, f->polygons, CTX::instance()->mesh.surfacesFaces,
                        CTX::instance()->color.mesh.line);
    }

    if(CTX::instance()->mesh.points || CTX::instance()->mesh.pointsNum){
      if(f->getAllElementsVisible())
        drawVerticesPerEntity(_ctx, f);
      else{
        if(CTX::instance()->mesh.triangles)
          drawVerticesPerElement(_ctx, f, f->triangles);
        if(CTX::instance()->mesh.quadrangles)
          drawVerticesPerElement(_ctx, f, f->quadrangles);
        drawVerticesPerElement(_ctx, f, f->polygons);
      }
    }

    if(CTX::instance()->mesh.normals) {
      if(CTX::instance()->mesh.triangles) drawNormals(_ctx, f->triangles);
      if(CTX::instance()->mesh.quadrangles) drawNormals(_ctx, f->quadrangles);
      drawNormals(_ctx, f->polygons);
    }

    if(CTX::instance()->mesh.dual) {
      if(CTX::instance()->mesh.triangles) drawBarycentricDual(f->triangles);
      if(CTX::instance()->mesh.quadrangles) drawBarycentricDual(f->quadrangles);
      drawBarycentricDual(f->polygons);
    }
    else if(CTX::instance()->mesh.voronoi) {
      if(CTX::instance()->mesh.triangles) drawVoronoiDual(f->triangles);
    }

    if(select) {
      glPopName();
      glPopName();
    }
  }
Example #5
0
gint buttonpress(GtkWidget *glarea, GdkEventButton *event) {
  int x = (int) event->x;
  int y = (int) event->y;
  GLuint *buffer;
  GLint hits;
  GLint viewport[4];
  switch(event->button) {
    case 1:
      // button 1, do picking
      glGetIntegerv(GL_VIEWPORT, viewport);
      buffer = new GLuint[doc->world.list.size() * 4];
      glSelectBuffer(doc->world.list.size() * 4, buffer);
      glRenderMode(GL_SELECT);
      glInitNames();
      glPushName(0);
      glMatrixMode(GL_PROJECTION);
      glPushMatrix();
      glLoadIdentity();
      gluPickMatrix((double) x, (double) (viewport[3] - y), 1.0, 1.0, viewport);
      gluPerspective(45.0, (float) (viewport[2] - viewport[0]) / (float) (viewport[3] - viewport[1]), 3.0, 2500.0);
      glMatrixMode(GL_MODELVIEW);
      doc->world.render_targets();
      glMatrixMode(GL_PROJECTION);
      glPopMatrix();
      glMatrixMode(GL_MODELVIEW);
      hits = glRenderMode(GL_RENDER);
      if(hits > 0) {
	int choose = buffer[3];
	int depth = buffer[1];
	for(int i = 0; i < hits; i++) {
	  if(buffer[i * 4 + 1] < depth) {
	    choose = buffer[i * 4 + 3];
	    depth = buffer[i * 4 + 1];
	  }
	}
	choose--;
	mainwin->select(choose);
      } else {
	mainwin->unselectAll();
      }
      delete buffer;
      break;
    case 2:
      // button 2, pick and center
      glGetIntegerv(GL_VIEWPORT, viewport);
      buffer = new GLuint[doc->world.list.size() * 4];
      glSelectBuffer(doc->world.list.size() * 4, buffer);
      glRenderMode(GL_SELECT);
      glInitNames();
      glPushName(0);
      glMatrixMode(GL_PROJECTION);
      glPushMatrix();
      glLoadIdentity();
      gluPickMatrix((double) x, (double) (viewport[3] - y), 1.0, 1.0, viewport);
      gluPerspective(45.0, (float) (viewport[2] - viewport[0]) / (float) (viewport[3] - viewport[1]), 3.0, 2500.0);
      glMatrixMode(GL_MODELVIEW);
      doc->world.render_targets();
      glMatrixMode(GL_PROJECTION);
      glPopMatrix();
      glMatrixMode(GL_MODELVIEW);
      hits = glRenderMode(GL_RENDER);
      if(hits > 0) {
	int choose = buffer[3];
	int depth = buffer[1];
	for(int i = 0; i < hits; i++) {
	  if(buffer[i * 4 + 1] < depth) {
	    choose = buffer[i * 4 + 3];
	    depth = buffer[i * 4 + 1];
	  }
	}
	choose--;
	if(doc->world.list[choose].type != LINK) {
	  doc->camera.fx = doc->world.list[choose].obj->get_px();
	  doc->camera.fy = doc->world.list[choose].obj->get_py();
	  doc->camera.fz = doc->world.list[choose].obj->get_pz();
	  doc->camera.fcamera = true;
	}
	mainwin->select(choose);
      } else {
	doc->camera.fx = 0;
	doc->camera.fy = 0;
	doc->camera.fz = 0;
	doc->camera.fcamera = true;
	mainwin->unselectAll();
      }
      delete buffer;
      break;
    case 3:
      // button 3, start roaming
      mainwin->mouse_x = event->x_root;
      mainwin->mouse_y = event->y_root;
      break;
    case 4:
      // button 4, mouse wheel up, zoom in
      break;
    case 5:
      // button 5, mouse wheel down, zoom out
      break;
  }
  return TRUE;
}
static Icon *_cairo_dock_pick_icon_on_opengl_desklet (CairoDesklet *pDesklet)
{
	GLuint selectBuf[4];
	GLint hits=0;
	GLint viewport[4];
	
	if (! gldi_gl_container_make_current (CAIRO_CONTAINER (pDesklet)))
		return NULL;
	
	glGetIntegerv (GL_VIEWPORT, viewport);
	glSelectBuffer (4, selectBuf);
	
	glRenderMode(GL_SELECT);
	glInitNames();
	glPushName(0);
	
	glMatrixMode (GL_PROJECTION);
	glPushMatrix ();
	glLoadIdentity ();
	gluPickMatrix ((GLdouble) pDesklet->container.iMouseX, (GLdouble) (viewport[3] - pDesklet->container.iMouseY), 2.0, 2.0, viewport);
	gluPerspective (60.0, 1.0*(GLfloat)pDesklet->container.iWidth/(GLfloat)pDesklet->container.iHeight, 1., 4*pDesklet->container.iHeight);
	
	glMatrixMode (GL_MODELVIEW);
	glPushMatrix ();
	glLoadIdentity ();
	
	_set_desklet_matrix (pDesklet);
	
	if (pDesklet->iLeftSurfaceOffset != 0 || pDesklet->iTopSurfaceOffset != 0 || pDesklet->iRightSurfaceOffset != 0 || pDesklet->iBottomSurfaceOffset != 0)
	{
		glTranslatef ((pDesklet->iLeftSurfaceOffset - pDesklet->iRightSurfaceOffset)/2, (pDesklet->iBottomSurfaceOffset - pDesklet->iTopSurfaceOffset)/2, 0.);
		glScalef (1. - (double)(pDesklet->iLeftSurfaceOffset + pDesklet->iRightSurfaceOffset) / pDesklet->container.iWidth,
			1. - (double)(pDesklet->iTopSurfaceOffset + pDesklet->iBottomSurfaceOffset) / pDesklet->container.iHeight,
			1.);
	}
	
	glPolygonMode (GL_FRONT, GL_FILL);
	glColor4f (1., 1., 1., 1.);
	
	pDesklet->iPickedObject = 0;
	if (pDesklet->render_bounding_box != NULL)  // surclasse la fonction du moteur de rendu.
	{
		pDesklet->render_bounding_box (pDesklet);
	}
	else if (pDesklet->pRenderer && pDesklet->pRenderer->render_bounding_box != NULL)
	{
		pDesklet->pRenderer->render_bounding_box (pDesklet);
	}
	else  // on le fait nous-memes a partir des coordonnees des icones.
	{
		glTranslatef (-pDesklet->container.iWidth/2, -pDesklet->container.iHeight/2, 0.);
		
		double x, y, w, h;
		Icon *pIcon;
		
		pIcon = pDesklet->pIcon;
		if (pIcon != NULL && pIcon->image.iTexture != 0)
		{
			w = pIcon->fWidth/2;
			h = pIcon->fHeight/2;
			x = pIcon->fDrawX + w;
			y = pDesklet->container.iHeight - pIcon->fDrawY - h;
			
			glLoadName(pIcon->image.iTexture);
			
			glBegin(GL_QUADS);
			glVertex3f(x-w, y+h, 0.);
			glVertex3f(x+w, y+h, 0.);
			glVertex3f(x+w, y-h, 0.);
			glVertex3f(x-w, y-h, 0.);
			glEnd();
		}
		
		GList *ic;
		for (ic = pDesklet->icons; ic != NULL; ic = ic->next)
		{
			pIcon = ic->data;
			if (pIcon->image.iTexture == 0)
				continue;
			
			w = pIcon->fWidth/2;
			h = pIcon->fHeight/2;
			x = pIcon->fDrawX + w;
			y = pDesklet->container.iHeight - pIcon->fDrawY - h;
			
			glLoadName(pIcon->image.iTexture);
			
			glBegin(GL_QUADS);
			glVertex3f(x-w, y+h, 0.);
			glVertex3f(x+w, y+h, 0.);
			glVertex3f(x+w, y-h, 0.);
			glVertex3f(x-w, y-h, 0.);
			glEnd();
		}
	}
	
	glPopName();
	
	hits = glRenderMode (GL_RENDER);

	glMatrixMode (GL_PROJECTION);
	glPopMatrix ();
	glMatrixMode(GL_MODELVIEW);
	glPopMatrix ();
	
	Icon *pFoundIcon = NULL;
	if (hits != 0)
	{
		GLuint id = selectBuf[3];
		Icon *pIcon;
		
		if (pDesklet->render_bounding_box != NULL)
		{
			pDesklet->iPickedObject = id;
			//g_print ("iPickedObject <- %d\n", id);
			pFoundIcon = pDesklet->pIcon;  // il faut mettre qqch, sinon la notification est filtree par la macro CD_APPLET_ON_CLICK_BEGIN.
		}
		else
		{
			pIcon = pDesklet->pIcon;
			if (pIcon != NULL && pIcon->image.iTexture != 0)
			{
				if (pIcon->image.iTexture == id)
				{
					pFoundIcon = pIcon;
				}
			}
			
			if (pFoundIcon == NULL)
			{
				GList *ic;
				for (ic = pDesklet->icons; ic != NULL; ic = ic->next)
				{
					pIcon = ic->data;
					if (pIcon->image.iTexture == id)
					{
						pFoundIcon = pIcon;
						break ;
					}
				}
			}
		}
	}
	
	return pFoundIcon;
}
Example #7
0
void GLWidget::processFindingObject(double p_xPos, double p_yPos)
{
	int view[4];
	uint selectionBuffer[32] = {0};
	int numberOfSelectedObjects = 0;

	// For selected objects
	glSelectBuffer(32, selectionBuffer);
	glGetIntegerv(GL_VIEWPORT, view);
	glRenderMode(GL_SELECT);

	// Clearing object names for identifying objects
	glInitNames();
 	glPushName(0);

	// Backup projection matrix in order restore it after view restriction around cursor area
	glMatrixMode(GL_PROJECTION);
 	glPushMatrix();
	glLoadIdentity();
 
 	// Restrict the draw to an area around the cursor
	gluPickMatrix(p_xPos, p_yPos, 10.0, 10.0, view);
    gluPerspective(30.0, 1.0, 1.0, 10000.0); 

	// Redraw with restricted view area
	glMatrixMode(GL_MODELVIEW);
	m_mapRenderer.setSelectionMode();
	m_mapRenderer.render(this);

	// Restore projection matrix
	glMatrixMode(GL_PROJECTION);
 	glPopMatrix();

	numberOfSelectedObjects = glRenderMode(GL_RENDER);
	glMatrixMode(GL_MODELVIEW);

    std::vector<int> selectedObjects; 
	if(numberOfSelectedObjects > 0) {
		Hit* pHitArray = reinterpret_cast<Hit*>(selectionBuffer);
	    for(int i = 0; i < numberOfSelectedObjects; i++) {
			if(m_mapRenderer.getTurnMapId() == pHitArray[i].id && m_moveMap) {
				m_turnMap = true;
				return;
			}
			selectedObjects.push_back(pHitArray[i].id);
		}
	}
	else {
		selectedObjects.push_back(0);
	}

	if(m_moveMap) {
		return;
	}
	m_mapRenderer.selectObjects(selectedObjects);
	updateGL();

	int selectionNumber = selectedObjects.front();
	if(0 != selectionNumber && m_mapRenderer.getTurnMapId() != selectionNumber) {
		showPlaceDetailsWidget(selectionNumber);
	}
}
Example #8
0
void ccGenericMesh::drawMeOnly(CC_DRAW_CONTEXT& context)
{
	ccGenericPointCloud* vertices = getAssociatedCloud();
	if (!vertices)
		return;

	handleColorRamp(context);

	//3D pass
	if (MACRO_Draw3D(context))
	{
		//any triangle?
		unsigned triNum = size();
		if (triNum == 0)
			return;

		//L.O.D.
		bool lodEnabled = (triNum > context.minLODTriangleCount && context.decimateMeshOnMove && MACRO_LODActivated(context));
		unsigned decimStep = (lodEnabled ? static_cast<unsigned>(ceil(static_cast<double>(triNum*3) / context.minLODTriangleCount)) : 1);
		unsigned displayedTriNum = triNum / decimStep;

		//display parameters
		glDrawParams glParams;
		getDrawingParameters(glParams);
		glParams.showNorms &= bool(MACRO_LightIsEnabled(context));

		//vertices visibility
		const ccGenericPointCloud::VisibilityTableType* verticesVisibility = vertices->getTheVisibilityArray();
		bool visFiltering = (verticesVisibility && verticesVisibility->isAllocated());

		//wireframe ? (not compatible with LOD)
		bool showWired = isShownAsWire() && !lodEnabled;

		//per-triangle normals?
		bool showTriNormals = (hasTriNormals() && triNormsShown());
		//fix 'showNorms'
		glParams.showNorms = showTriNormals || (vertices->hasNormals() && m_normalsDisplayed);

		//materials & textures
		bool applyMaterials = (hasMaterials() && materialsShown());
		bool showTextures = (hasTextures() && materialsShown() && !lodEnabled);

		//GL name pushing
		bool pushName = MACRO_DrawEntityNames(context);
		//special case: triangle names pushing (for picking)
		bool pushTriangleNames = MACRO_DrawTriangleNames(context);
		pushName |= pushTriangleNames;

		if (pushName)
		{
			//not fast at all!
			if (MACRO_DrawFastNamesOnly(context))
				return;
			glPushName(getUniqueIDForDisplay());
			//minimal display for picking mode!
			glParams.showNorms = false;
			glParams.showColors = false;
			//glParams.showSF --> we keep it only if SF 'NaN' values are hidden
			showTriNormals = false;
			applyMaterials = false;
			showTextures = false;
		}

		//in the case we need to display scalar field colors
		ccScalarField* currentDisplayedScalarField = 0;
		bool greyForNanScalarValues = true;
		//unsigned colorRampSteps = 0;
		ccColorScale::Shared colorScale(0);

		if (glParams.showSF)
		{
			assert(vertices->isA(CC_TYPES::POINT_CLOUD));
			ccPointCloud* cloud = static_cast<ccPointCloud*>(vertices);

			greyForNanScalarValues = (cloud->getCurrentDisplayedScalarField() && cloud->getCurrentDisplayedScalarField()->areNaNValuesShownInGrey());
			if (greyForNanScalarValues && pushName)
			{
				//in picking mode, no need to take SF into account if we don't hide any points!
				glParams.showSF = false;
			}
			else
			{
				currentDisplayedScalarField = cloud->getCurrentDisplayedScalarField();
				colorScale = currentDisplayedScalarField->getColorScale();
				//colorRampSteps = currentDisplayedScalarField->getColorRampSteps();

				assert(colorScale);
				//get default color ramp if cloud has no scale associated?!
				if (!colorScale)
					colorScale = ccColorScalesManager::GetUniqueInstance()->getDefaultScale(ccColorScalesManager::BGYR);
			}
		}

		//materials or color?
		bool colorMaterial = false;
		if (glParams.showSF || glParams.showColors)
		{
			applyMaterials = false;
			colorMaterial = true;
			glColorMaterial(GL_FRONT_AND_BACK, GL_DIFFUSE);
			glEnable(GL_COLOR_MATERIAL);
		}

		//in the case we need to display vertex colors
		ColorsTableType* rgbColorsTable = 0;
		if (glParams.showColors)
		{
			if (isColorOverriden())
			{
				ccGL::Color3v(m_tempColor.rgb);
				glParams.showColors = false;
			}
			else
			{
				assert(vertices->isA(CC_TYPES::POINT_CLOUD));
				rgbColorsTable = static_cast<ccPointCloud*>(vertices)->rgbColors();
			}
		}
		else
		{
			glColor3fv(context.defaultMat->getDiffuseFront().rgba);
		}

		if (glParams.showNorms)
		{
			//DGM: Strangely, when Qt::renderPixmap is called, the OpenGL version can fall to 1.0!
			glEnable((QGLFormat::openGLVersionFlags() & QGLFormat::OpenGL_Version_1_2 ? GL_RESCALE_NORMAL : GL_NORMALIZE));
			glEnable(GL_LIGHTING);
			context.defaultMat->applyGL(true,colorMaterial);
		}

		//in the case we need normals (i.e. lighting)
		NormsIndexesTableType* normalsIndexesTable = 0;
		ccNormalVectors* compressedNormals = 0;
		if (glParams.showNorms)
		{
			assert(vertices->isA(CC_TYPES::POINT_CLOUD));
			normalsIndexesTable = static_cast<ccPointCloud*>(vertices)->normals();
			compressedNormals = ccNormalVectors::GetUniqueInstance();
		}

		//stipple mask
		if (stipplingEnabled())
			EnableGLStippleMask(true);

		if (!pushTriangleNames && !visFiltering && !(applyMaterials || showTextures) && (!glParams.showSF || greyForNanScalarValues))
		{
			//the GL type depends on the PointCoordinateType 'size' (float or double)
			GLenum GL_COORD_TYPE = sizeof(PointCoordinateType) == 4 ? GL_FLOAT : GL_DOUBLE;
			
			glEnableClientState(GL_VERTEX_ARRAY);
			glVertexPointer(3,GL_COORD_TYPE,0,GetVertexBuffer());

			if (glParams.showNorms)
			{
				glEnableClientState(GL_NORMAL_ARRAY);
				glNormalPointer(GL_COORD_TYPE,0,GetNormalsBuffer());
			}
			if (glParams.showSF || glParams.showColors)
			{
				glEnableClientState(GL_COLOR_ARRAY);
				glColorPointer(3,GL_UNSIGNED_BYTE,0,GetColorsBuffer());
			}

			//we can scan and process each chunk separately in an optimized way
			//we mimic the way ccMesh beahves by using virtual chunks!
			unsigned chunks = static_cast<unsigned>(ceil((double)displayedTriNum/(double)MAX_NUMBER_OF_ELEMENTS_PER_CHUNK));
			unsigned chunkStart = 0;
			const colorType* col = 0;
			for (unsigned k=0; k<chunks; ++k, chunkStart += MAX_NUMBER_OF_ELEMENTS_PER_CHUNK)
			{
				//virtual chunk size
				const unsigned chunkSize = k+1 < chunks ? MAX_NUMBER_OF_ELEMENTS_PER_CHUNK : (displayedTriNum % MAX_NUMBER_OF_ELEMENTS_PER_CHUNK);

				//vertices
				PointCoordinateType* _vertices = GetVertexBuffer();
				for (unsigned n=0; n<chunkSize; n+=decimStep)
				{
					const CCLib::TriangleSummitsIndexes* ti = getTriangleIndexes(chunkStart + n);
					memcpy(_vertices,vertices->getPoint(ti->i1)->u,sizeof(PointCoordinateType)*3);
					_vertices+=3;
					memcpy(_vertices,vertices->getPoint(ti->i2)->u,sizeof(PointCoordinateType)*3);
					_vertices+=3;
					memcpy(_vertices,vertices->getPoint(ti->i3)->u,sizeof(PointCoordinateType)*3);
					_vertices+=3;
				}

				//scalar field
				if (glParams.showSF)
				{
					colorType* _rgbColors = GetColorsBuffer();
					assert(colorScale);
					for (unsigned n=0; n<chunkSize; n+=decimStep)
					{
						const CCLib::TriangleSummitsIndexes* ti = getTriangleIndexes(chunkStart + n);
						col = currentDisplayedScalarField->getValueColor(ti->i1);
						memcpy(_rgbColors,col,sizeof(colorType)*3);
						_rgbColors += 3;
						col = currentDisplayedScalarField->getValueColor(ti->i2);
						memcpy(_rgbColors,col,sizeof(colorType)*3);
						_rgbColors += 3;
						col = currentDisplayedScalarField->getValueColor(ti->i3);
						memcpy(_rgbColors,col,sizeof(colorType)*3);
						_rgbColors += 3;
					}
				}
				//colors
				else if (glParams.showColors)
				{
					colorType* _rgbColors = GetColorsBuffer();

					for (unsigned n=0; n<chunkSize; n+=decimStep)
					{
						const CCLib::TriangleSummitsIndexes* ti = getTriangleIndexes(chunkStart + n);
						memcpy(_rgbColors,rgbColorsTable->getValue(ti->i1),sizeof(colorType)*3);
						_rgbColors += 3;
						memcpy(_rgbColors,rgbColorsTable->getValue(ti->i2),sizeof(colorType)*3);
						_rgbColors += 3;
						memcpy(_rgbColors,rgbColorsTable->getValue(ti->i3),sizeof(colorType)*3);
						_rgbColors += 3;
					}
				}

				//normals
				if (glParams.showNorms)
				{
					PointCoordinateType* _normals = GetNormalsBuffer();
					if (showTriNormals)
					{
						for (unsigned n=0; n<chunkSize; n+=decimStep)
						{
							CCVector3 Na, Nb, Nc;
							getTriangleNormals(chunkStart + n, Na, Nb, Nc);
							memcpy(_normals,Na.u,sizeof(PointCoordinateType)*3);
							_normals+=3;
							memcpy(_normals,Nb.u,sizeof(PointCoordinateType)*3);
							_normals+=3;
							memcpy(_normals,Nc.u,sizeof(PointCoordinateType)*3);
							_normals+=3;
						}
					}
					else
					{
						for (unsigned n=0; n<chunkSize; n+=decimStep)
						{
							const CCLib::TriangleSummitsIndexes* ti = getTriangleIndexes(chunkStart + n);
							memcpy(_normals,vertices->getPointNormal(ti->i1).u,sizeof(PointCoordinateType)*3);
							_normals+=3;
							memcpy(_normals,vertices->getPointNormal(ti->i2).u,sizeof(PointCoordinateType)*3);
							_normals+=3;
							memcpy(_normals,vertices->getPointNormal(ti->i3).u,sizeof(PointCoordinateType)*3);
							_normals+=3;
						}
					}
				}

				if (!showWired)
				{
					glDrawArrays(lodEnabled ? GL_POINTS : GL_TRIANGLES,0,(chunkSize/decimStep)*3);
				}
				else
				{
					glDrawElements(GL_LINES,(chunkSize/decimStep)*6,GL_UNSIGNED_INT,GetWireVertexIndexes());
				}
			}

			//disable arrays
			glDisableClientState(GL_VERTEX_ARRAY);
			if (glParams.showNorms)
				glDisableClientState(GL_NORMAL_ARRAY);
			if (glParams.showSF || glParams.showColors)
				glDisableClientState(GL_COLOR_ARRAY);
		}
		else
		{
			//current vertex color
			const colorType *col1=0,*col2=0,*col3=0;
			//current vertex normal
			const PointCoordinateType *N1=0,*N2=0,*N3=0;
			//current vertex texture coordinates
			float *Tx1=0,*Tx2=0,*Tx3=0;

			//loop on all triangles
			int lasMtlIndex = -1;

			if (showTextures)
			{
				//#define TEST_TEXTURED_BUNDLER_IMPORT
#ifdef TEST_TEXTURED_BUNDLER_IMPORT
				glPushAttrib(GL_COLOR_BUFFER_BIT);
				glEnable(GL_BLEND);
				glBlendFunc(context.sourceBlend, context.destBlend);
#endif

				glEnable(GL_TEXTURE_2D);
			}

			if (pushTriangleNames)
				glPushName(0);

			GLenum triangleDisplayType = lodEnabled ? GL_POINTS : showWired ? GL_LINE_LOOP : GL_TRIANGLES;
			glBegin(triangleDisplayType);

			//per-triangle normals
			const NormsIndexesTableType* triNormals = getTriNormsTable();
			//materials
			const ccMaterialSet* materials = getMaterialSet();

			for (unsigned n=0; n<triNum; ++n)
			{
				//current triangle vertices
				const CCLib::TriangleSummitsIndexes* tsi = getTriangleIndexes(n);

				//LOD: shall we display this triangle?
				if (n % decimStep)
					continue;

				if (visFiltering)
				{
					//we skip the triangle if at least one vertex is hidden
					if ((verticesVisibility->getValue(tsi->i1) != POINT_VISIBLE) ||
						(verticesVisibility->getValue(tsi->i2) != POINT_VISIBLE) ||
						(verticesVisibility->getValue(tsi->i3) != POINT_VISIBLE))
						continue;
				}

				if (glParams.showSF)
				{
					assert(colorScale);
					col1 = currentDisplayedScalarField->getValueColor(tsi->i1);
					if (!col1)
						continue;
					col2 = currentDisplayedScalarField->getValueColor(tsi->i2);
					if (!col2)
						continue;
					col3 = currentDisplayedScalarField->getValueColor(tsi->i3);
					if (!col3)
						continue;
				}
				else if (glParams.showColors)
				{
					col1 = rgbColorsTable->getValue(tsi->i1);
					col2 = rgbColorsTable->getValue(tsi->i2);
					col3 = rgbColorsTable->getValue(tsi->i3);
				}

				if (glParams.showNorms)
				{
					if (showTriNormals)
					{
						assert(triNormals);
						int n1,n2,n3;
						getTriangleNormalIndexes(n,n1,n2,n3);
						N1 = (n1>=0 ? ccNormalVectors::GetNormal(triNormals->getValue(n1)).u : 0);
						N2 = (n1==n2 ? N1 : n1>=0 ? ccNormalVectors::GetNormal(triNormals->getValue(n2)).u : 0);
						N3 = (n1==n3 ? N1 : n3>=0 ? ccNormalVectors::GetNormal(triNormals->getValue(n3)).u : 0);

					}
					else
					{
						N1 = compressedNormals->getNormal(normalsIndexesTable->getValue(tsi->i1)).u;
						N2 = compressedNormals->getNormal(normalsIndexesTable->getValue(tsi->i2)).u;
						N3 = compressedNormals->getNormal(normalsIndexesTable->getValue(tsi->i3)).u;
					}
				}

				if (applyMaterials || showTextures)
				{
					assert(materials);
					int newMatlIndex = this->getTriangleMtlIndex(n);

					//do we need to change material?
					if (lasMtlIndex != newMatlIndex)
					{
						assert(newMatlIndex < static_cast<int>(materials->size()));
						glEnd();
						if (showTextures)
						{
							GLuint texID = (newMatlIndex >= 0 ? context._win->getTextureID((*materials)[newMatlIndex]) : 0);
							assert(texID <= 0 || glIsTexture(texID));
							glBindTexture(GL_TEXTURE_2D, texID);
						}

						//if we don't have any current material, we apply default one
						if (newMatlIndex >= 0)
							(*materials)[newMatlIndex]->applyGL(glParams.showNorms,false);
						else
							context.defaultMat->applyGL(glParams.showNorms,false);
						glBegin(triangleDisplayType);
						lasMtlIndex = newMatlIndex;
					}

					if (showTextures)
					{
						getTriangleTexCoordinates(n,Tx1,Tx2,Tx3);
					}
				}

				if (pushTriangleNames)
				{
					glEnd();
					glLoadName(n);
					glBegin(triangleDisplayType);
				}
				else if (showWired)
				{
					glEnd();
					glBegin(triangleDisplayType);
				}

				//vertex 1
				if (N1)
					ccGL::Normal3v(N1);
				if (col1)
					glColor3ubv(col1);
				if (Tx1)
					glTexCoord2fv(Tx1);
				ccGL::Vertex3v(vertices->getPoint(tsi->i1)->u);

				//vertex 2
				if (N2)
					ccGL::Normal3v(N2);
				if (col2)
					glColor3ubv(col2);
				if (Tx2)
					glTexCoord2fv(Tx2);
				ccGL::Vertex3v(vertices->getPoint(tsi->i2)->u);

				//vertex 3
				if (N3)
					ccGL::Normal3v(N3);
				if (col3)
					glColor3ubv(col3);
				if (Tx3)
					glTexCoord2fv(Tx3);
				ccGL::Vertex3v(vertices->getPoint(tsi->i3)->u);
			}

			glEnd();

			if (pushTriangleNames)
				glPopName();

			if (showTextures)
			{
#ifdef TEST_TEXTURED_BUNDLER_IMPORT
				glPopAttrib(); //GL_COLOR_BUFFER_BIT 
#endif
				glBindTexture(GL_TEXTURE_2D, 0);
				glDisable(GL_TEXTURE_2D);
			}
		}

		if (stipplingEnabled())
			EnableGLStippleMask(false);

		if (colorMaterial)
			glDisable(GL_COLOR_MATERIAL);

		if (glParams.showNorms)
		{
			glDisable(GL_LIGHTING);
			glDisable((QGLFormat::openGLVersionFlags() & QGLFormat::OpenGL_Version_1_2 ? GL_RESCALE_NORMAL : GL_NORMALIZE));
		}

		if (pushName)
			glPopName();
	}
}
Example #9
0
void ccSymbolCloud::drawMeOnly(CC_DRAW_CONTEXT& context)
{
	if (!m_points->isAllocated())
		return;

	//nothing to do?!
	if (!m_showSymbols && !m_showLabels)
		return;

	if (MACRO_Draw2D(context) && MACRO_Foreground(context))
	{
		//we get display parameters
		glDrawParams glParams;
		getDrawingParameters(glParams);

		//standard case: list names pushing
		bool pushName = MACRO_DrawEntityNames(context);
		bool hasLabels = !m_labels.empty();
		if (pushName)
		{
			//not fast at all!
			if (MACRO_DrawFastNamesOnly(context))
				return;

			glPushName(getUniqueID());
			hasLabels = false; //no need to display labels in 'picking' mode
		}

		//we should already be in orthoprojective & centered omde
		//glOrtho(-halfW,halfW,-halfH,halfH,-maxS,maxS);

		//default color
		const unsigned char* color = context.pointsDefaultCol;
		if (isColorOverriden())
		{
			color = m_tempColor;
			glParams.showColors = false;
		}
		
		if (!glParams.showColors)
			glColor3ubv(color);

		unsigned numberOfPoints = size();

		//viewport parameters (will be used to project 3D positions to 2D)
		int VP[4];
		context._win->getViewportArray(VP);
		const double* MM = context._win->getModelViewMatd(); //viewMat
		const double* MP = context._win->getProjectionMatd(); //projMat

		//only usefull when displaying labels!
		QFont font(context._win->getTextDisplayFont()); //takes rendering zoom into account!
		font.setPointSize(static_cast<int>(m_fontSize * context.renderZoom));
		//font.setBold(true);
		QFontMetrics fontMetrics(font);

		double symbolSizeBackup = m_symbolSize;
		m_symbolSize *= static_cast<double>(context.renderZoom);

		double xpShift = 0.0;
		if (m_labelAlignFlags & ccGenericGLDisplay::ALIGN_HLEFT)
			xpShift = m_symbolSize/2.0;
		else if (m_labelAlignFlags & ccGenericGLDisplay::ALIGN_HRIGHT)
			xpShift = -m_symbolSize/2.0;

		double ypShift = 0.0;
		if (m_labelAlignFlags & ccGenericGLDisplay::ALIGN_VTOP)
			ypShift = m_symbolSize/2.0;
		else if (m_labelAlignFlags & ccGenericGLDisplay::ALIGN_VBOTTOM)
			ypShift = -m_symbolSize/2.0;

		//draw symbols + labels
		{
			for (unsigned i=0;i<numberOfPoints;i++)
			{
				//symbol center
				const CCVector3* P = getPoint(i);

				//project it in 2D screen coordinates
				GLdouble xp,yp,zp;
				gluProject(P->x,P->y,P->z,MM,MP,VP,&xp,&yp,&zp);

				//apply point color (if any)
				if (glParams.showColors)
				{
					color = getPointColor(i);
					glColor3ubv(color);
				}
			
				//draw associated symbol
				if (m_showSymbols && m_symbolSize > 0.0)
				{
					drawSymbolAt(xp-static_cast<double>(context.glW/2),yp-static_cast<double>(context.glH/2));
				}

				//draw associated label?
				if (m_showLabels && hasLabels && m_labels.size() > i && !m_labels[i].isNull())
				{
					//draw label
					context._win->displayText(m_labels[i],static_cast<int>(xp+xpShift),static_cast<int>(yp+ypShift),m_labelAlignFlags,0,color,&font);
				}

			}
		}

		//restore original symbol size
		m_symbolSize = symbolSizeBackup;

		if (pushName)
			glPopName();
	}
}
Example #10
0
void Renderer::drawCovers(bool showTarget){
#ifdef COVER_ALPHA
	glEnable(GL_BLEND);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
	glEnable(GL_ALPHA_TEST);
	glAlphaFunc(GL_GREATER,0.1f);
#endif
	
	if (cfgHighlightWidth == 0)
		showTarget = false;

	if (appInstance->albumCollection->getCount() == 0)
		return;

	float centerOffset = displayPos->getCenteredOffset();
	CollectionPos centerCover = displayPos->getCenteredPos();
	CollectionPos firstCover = displayPos->getOffsetPos(coverPos.getFirstCover() + 1);
	CollectionPos lastCover = displayPos->getOffsetPos(coverPos.getLastCover());
	lastCover++; // getOffsetPos does not return the end() element
	CollectionPos targetCover = appInstance->albumCollection->getTargetPos();

	int offset = appInstance->albumCollection->rank(firstCover) - appInstance->albumCollection->rank(centerCover);
	
	for (CollectionPos p = firstCover; p != lastCover; ++p, ++offset){
		float co = -centerOffset + offset;

		shared_ptr<ImgTexture> tex = texLoader->getLoadedImgTexture(p);
		tex->glBind();
		glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);

		// calculate darkening
		float g = 1-(min(1.0f,(abs(co)-2)/5))*0.5f;
		if (abs(co) < 2)
			g = 1;
		/*float g = 1 - (abs(co)-2)*0.2f;
		g = 1 - abs(co)*0.1f;
		g = 1 - abs(zRot)/80;
		g= 1;
		if (g < 0) g = 0;*/
		glColor3f( g, g, g);
		glVectord origin(0, 0.5, 0);

		glQuad coverQuad = coverPos.getCoverQuad(co, tex->getAspect());
		
		glPushName(SELECTION_CENTER + offset);

		glBegin(GL_QUADS);
		if (glFogCoordf) glFogCoordf((GLfloat)coverPos.distanceToMirror(coverQuad.topLeft));
			glTexCoord2f(0.0f, 1.0f); // top left
			glVertex3fv((GLfloat*)&(coverQuad.topLeft.x));

			if (glFogCoordf) glFogCoordf((GLfloat)coverPos.distanceToMirror(coverQuad.topRight));
			glTexCoord2f(1.0f, 1.0f); // top right
			glVertex3fv((GLfloat*)&(coverQuad.topRight.x));

			if (glFogCoordf) glFogCoordf((GLfloat)coverPos.distanceToMirror(coverQuad.bottomRight));
			glTexCoord2f(1.0f, 0.0f); // bottom right
			glVertex3fv((GLfloat*)&(coverQuad.bottomRight.x));

			if (glFogCoordf) glFogCoordf((GLfloat)coverPos.distanceToMirror(coverQuad.bottomLeft));
			glTexCoord2f(0.0f, 0.0f); // bottom left
			glVertex3fv((GLfloat*)&(coverQuad.bottomLeft.x));
		glEnd();
		glPopName();

		if (showTarget){
			if (p == targetCover){
				bool clipPlane = false;
				if (glIsEnabled(GL_CLIP_PLANE0)){
					glDisable(GL_CLIP_PLANE0);
					clipPlane = true;
				}

				showTarget = false;
				
				glColor3f(GetRValue(cfgTitleColor) / 255.0f, GetGValue(cfgTitleColor) / 255.0f, GetBValue(cfgTitleColor) / 255.0f);

				glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);
				glDisable(GL_TEXTURE_2D);

				glLineWidth((GLfloat)cfgHighlightWidth);
				glPolygonOffset(-1.0f, -1.0f);
				glEnable(GL_POLYGON_OFFSET_LINE);

				glEnable(GL_VERTEX_ARRAY);
				glVertexPointer(3, GL_FLOAT, 0, (void*) &coverQuad);
				glDrawArrays(GL_QUADS, 0, 4);

				glDisable(GL_POLYGON_OFFSET_LINE);

				glEnable(GL_TEXTURE_2D);


				if (clipPlane)
					glEnable(GL_CLIP_PLANE0);
			}
		}
	}

#ifdef COVER_ALPHA
	glDisable(GL_BLEND);
	glDisable(GL_ALPHA_TEST);
#endif
}
Example #11
0
int OGLWidget::getObjectAtScreenPos(int x, int y)
{
    // set up the selection buffer
    GLuint buffer[512];
    glSelectBuffer(512, buffer);

    // Get the viewport values
    GLint viewport[4];
    glGetIntegerv(GL_VIEWPORT, viewport);

    // Go into Selection Mode
    glRenderMode(GL_SELECT);
    glInitNames();		// Initializes The Name Stack
    glPushName(-1);		// Push at least one entry

    // go to projection matrix and limit the area around the mouse to be 'drawn'
    glMatrixMode(GL_PROJECTION);
    glPushMatrix();		// Push The Projection Matrix
    glLoadIdentity();	// Resets The Matrix
    gluPickMatrix((GLdouble) x, (GLdouble) (viewport[3]-y), 1.0f, 1.0f, viewport);

    // also set the perspective to ensure the new aspect ratio is correct
    gluPerspective(45.0f, (GLfloat) (viewport[2]-viewport[0])/(GLfloat) (viewport[3]-viewport[1]), 0.1f, 1500.0f);

    // now paint the objects
    glMatrixMode(GL_MODELVIEW);
    parentView_->drawNodes();

    // switch everything back
    glMatrixMode(GL_PROJECTION);
    glPopMatrix();
    glMatrixMode(GL_MODELVIEW);

    // check for hits by switching render mode
    GLint hits=glRenderMode(GL_RENDER);

    // do we have any?
    if (hits > 0)
    {
        // note: selection buffer has 4 values per hit: # of hits at time, min depth, max depth, name

        // start by picking the first hit
        int choose = buffer[3];
        int depth = buffer[1];

        // now loop over the rest
        for (int loop = 1; loop < hits; loop++)
        {
            // is this object closer?
            if (buffer[loop*4+1] < GLuint(depth))
            {
                choose = buffer[loop*4+3];
                depth = buffer[loop*4+1];
            }
        }

        return choose;
    }

    return -1;
}
Example #12
0
//---------------------------------------------------------------------------
void CFabAtHomeView::DrawScene(void)
//---------------------------------------------------------------------------
{// draw the scene

	m_bDrawing = true;
	CFabAtHomeDoc* pDoc = GetDocument();
	ASSERT_VALID(pDoc);
	CSingleLock lockModel(&pDoc->model.m_mutAccess);
	lockModel.Lock(100);
	if(!lockModel.IsLocked()) return;
	CFabAtHomeApp *pApp = (CFabAtHomeApp *) AfxGetApp();
	CVec platetop(0,0,0);
	//get the graphics position (offset by PrinterComponent home from the hardware home (0,0,0).
	if (pApp->printer.IsDefined())
		platetop = pApp->printer.component[3].GetGraphicsRTPos() + pApp->printer.component[3].pmax;

	// background

	glClearColor(1,1,1,1);
	ReportGLError(CString("ClearColor"));
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	ReportGLError(CString("Clear"));
	
	// lighting

	SetLighting();

	glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
	ReportGLError(CString("PolygonMode"));

	// draw

    glPushMatrix();
	ReportGLError(CString("PushMatrix1"));
	
	if(bPanning)
	{
		view.x=(eye.x+view.z)/view.z;
		view.y=(eye.y+view.z)/view.z;
	}
	gluLookAt(eye.x, eye.y, eye.z, view.x, view.y, view.z, up.x, up.y, up.z);
	ReportGLError(CString("gluLookAt"));

	glMultMatrixd(rotmat);
	ReportGLError(CString("MultMatrix"));
	glPushMatrix();
	ReportGLError(CString("PushMatrix2"));

	
	glEnable(GL_NORMALIZE);
	ReportGLError(CString("Enable"));

	if(bShowPrinter)
	{
		((CFabAtHomeApp*) AfxGetApp())->printer.Draw();
		ReportGLError(CString("printer.Draw"));
	}

	// model

	glPushMatrix();
	ReportGLError(CString("PushMatrix3"));
	glTranslated(0,0,platetop.z);
	ReportGLError(CString("Translate"));
	DrawMainAxes(20);
	ReportGLError(CString("DrawAxes"));

	glPushName(1);
	ReportGLError(CString("PushName1"));
	glLoadName(NAMESTACK_CHUNK);
	ReportGLError(CString("LoadName1"));
	glPushName(NAMESTACK_CHUNK);
	ReportGLError(CString("PushName"));

	if (bShowModel) {
		glColor3d(0.4,0.8,0.2);
		for (int i=0; i<pDoc->model.chunk.GetSize(); i++) {
			glLoadName(i);
			ReportGLError(CString("LoadName2"));

			pDoc->model.chunk[i].Draw(&pDoc->model, bModelNormals, bShaded);

			ReportGLError(CString("DrawChunk"));
		}
	}
	glPopName();
	ReportGLError(CString("PopName1"));
	
	// paths
	
	if(bFollowCurrentLayer) 
	{
		UpdateCurrentLayer();
	}
	pDoc->model.fab.DrawLayers(&pDoc->model, firstlayer, lastlayer, bShowPaths, bShowTrace);

	ReportGLError(CString("DrawLayers"));

	glColor3d(1,1,1);
	ReportGLError(CString("Color3d"));
	glLineWidth(5);
	ReportGLError(CString("LineWidth1"));
	glLineWidth(1);
	ReportGLError(CString("LineWidth2"));

	glPopName();
	ReportGLError(CString("PopName2"));
	glPopMatrix();
	ReportGLError(CString("PopMatrix1"));
	glPopMatrix();
	ReportGLError(CString("PopMatrix2"));

	// end

	glDisable(GL_COLOR_MATERIAL);
	ReportGLError(CString("Disable"));
	
    glPopMatrix();
	ReportGLError(CString("PopMatrix3"));
	glFinish();
	ReportGLError(CString("Finish"));
	HDC localDC = wglGetCurrentDC();
	ASSERT(localDC != NULL);
	SwapBuffers(localDC);
	ReportGLError(CString("SwapBuffers"));
	m_bDrawing = false;
}
Example #13
0
bool 
GLUTPick(int x, int y, R3Mesh *mesh, R3MeshFace **pick_face, R3Point *pick_position) 
{
  // Check position
  if ((x < 0) || (GLUTwindow_width <= x) || (y < 0) || (GLUTwindow_height <= y)) { 
    printf("Pick (%d,%d) outside viewport: (0,%d) (0,%d)\n", x, y, GLUTwindow_width, GLUTwindow_height); 
    return false;
  }

  // Allocate select buffer
  const int SELECT_BUFFER_SIZE = 1024;
  GLuint select_buffer[SELECT_BUFFER_SIZE];
  GLint select_buffer_hits;

  // Initialize select buffer
  glSelectBuffer(SELECT_BUFFER_SIZE, select_buffer);
  glRenderMode(GL_SELECT);
  glInitNames();
  glPushName(0);

  // Initialize view transformation
  GLint viewport[4];
  glViewport(0, 0, GLUTwindow_width, GLUTwindow_height);
  glGetIntegerv(GL_VIEWPORT, viewport);
  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();
  gluPickMatrix((GLdouble) x, (GLdouble) y, 1, 1, viewport);

  // Set projection transformation
  // NOTE: THIS MUST MATCH CODE IN GLUTRedraw
  double mesh_radius = mesh->Radius(); 
  gluPerspective(180.0*camera_yfov/M_PI, (GLdouble) GLUTwindow_width /(GLdouble) GLUTwindow_height, 
    0.01 * mesh_radius, 100 * mesh_radius);

  // Set camera transformation
  // NOTE: THIS MUST MATCH CODE IN GLUTRedraw
  R3Vector& t = camera_towards;
  R3Vector& u = camera_up;
  R3Vector r = camera_up % camera_towards;
  GLdouble camera_matrix[16] = { r[0], u[0], t[0], 0, r[1], u[1], t[1], 0, r[2], u[2], t[2], 0, 0, 0, 0, 1 };
  glMatrixMode(GL_MODELVIEW);
  glLoadIdentity();
  glMultMatrixd(camera_matrix);
  glTranslated(-camera_eye[0], -camera_eye[1], -camera_eye[2]);

  // Draw mesh with pick names into selection buffer
  glLoadName(0); 
  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  for (int i = 0; i < mesh->NFaces(); i++) { 
    R3MeshFace *face = mesh->Face(i);
    glLoadName(i + 1); 
    glBegin(GL_POLYGON);
    for (unsigned int j = 0; j < face->vertices.size(); j++) {
      R3MeshVertex *vertex = face->vertices[j];
      const R3Point& p = vertex->position;
      glVertex3f(p[0], p[1], p[2]);
    }
    glEnd();
  }
  glFlush();
  select_buffer_hits = glRenderMode(GL_RENDER);

  // Process select buffer to find front-most hit
  int hit = 0;
  GLuint hit_z = 0xFFFFFFFF;
  GLuint *bufp = select_buffer;
  GLuint numnames, z1, z2;
  for (int i = 0; i < select_buffer_hits; i++) {
    numnames = *bufp++;
    z1 = *bufp++;
    z2 = *bufp++;
    while (numnames--) {
      if (z1 < hit_z) {
        hit = (int) *bufp;
        hit_z = z1/2 + z2/2;
      }
      bufp++;
    }
  }

  // Return closest face
  if ((hit > 0) && (hit <= mesh->NFaces())) {
    // Find face
    if (pick_face) {
      // Subtract one because added one in glLoadName
      *pick_face = mesh->Face(hit - 1);
    }

    // Find hit position
    if (pick_position) {
      GLdouble p[3];
      GLdouble modelview_matrix[16];
      GLdouble projection_matrix[16];
      GLint viewport[16];
      glGetDoublev(GL_MODELVIEW_MATRIX, modelview_matrix);
      glGetDoublev(GL_PROJECTION_MATRIX, projection_matrix);
      glGetIntegerv(GL_VIEWPORT, viewport);
      GLdouble z = (GLdouble) hit_z / (GLdouble) 0xFFFFFFFF;
      gluUnProject(x, y, z, modelview_matrix, projection_matrix, viewport, &(p[0]), &(p[1]), &(p[2]));
      pick_position->Reset(p[0], p[1], p[2]);
    }

    // Return hit
    return true;
  }
  else {
    // Return no hit
    return false;
  }
}
void
GUICalibrator::drawGL(const GUIVisualizationSettings& s) const {
    glPushName(getGlID());
    std::string flow = "-";
    std::string speed = "-";
    if (isActive()) {
        if (myCurrentStateInterval->v >= 0) {
            speed = toString(myCurrentStateInterval->v) + "m/s";
        }
        if (myCurrentStateInterval->q >= 0) {
            flow = toString((int)myCurrentStateInterval->q) + "v/h";
        }
    }
    for (size_t i = 0; i < myFGPositions.size(); ++i) {
        const Position& pos = myFGPositions[i];
        SUMOReal rot = myFGRotations[i];
        glPushMatrix();
        glTranslated(pos.x(), pos.y(), getType());
        glRotated(rot, 0, 0, 1);
        glTranslated(0, 0, getType());
        glScaled(s.addExaggeration, s.addExaggeration, 1);
        glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);

        glBegin(GL_TRIANGLES);
        glColor3d(1, .8f, 0);
        // base
        glVertex2d(0 - 1.4, 0);
        glVertex2d(0 - 1.4, 6);
        glVertex2d(0 + 1.4, 6);
        glVertex2d(0 + 1.4, 0);
        glVertex2d(0 - 1.4, 0);
        glVertex2d(0 + 1.4, 6);
        glEnd();

        // draw text
        if (s.scale * s.addExaggeration >= 1.) {
            glTranslated(0, 0, .1);
            glColor3d(0, 0, 0);
            pfSetPosition(0, 0);
            pfSetScale(3.f);
            SUMOReal w = pfdkGetStringWidth("C");
            glRotated(180, 0, 1, 0);
            glTranslated(-w / 2., 2, 0);
            pfDrawString("C");
            glTranslated(w / 2., -2, 0);


            pfSetPosition(0, 0);
            pfSetScale(.7f);
            w = pfdkGetStringWidth(flow.c_str());
            glTranslated(-w / 2., 4, 0);
            pfDrawString(flow.c_str());
            glTranslated(w / 2., -4, 0);

            pfSetPosition(0, 0);
            pfSetScale(.7f);
            w = pfdkGetStringWidth(speed.c_str());
            glTranslated(-w / 2., 5, 0);
            pfDrawString(speed.c_str());
            glTranslated(-w / 2., -5, 0);
        }
        glPopMatrix();
    }
    drawName(getCenteringBoundary().getCenter(), s.scale, s.addName);
    glPopName();
}
Example #15
0
/* picking */
int pick(int x, int y)
{

    GLuint hits = 0;
    GLint viewport[4];
    GLuint selectBuf[512];
    GLuint *ptr;
    GLuint i,j;
    GLint  k;
    GLint picked = -1;
	real mv_matrix[16];

    GLuint names, z1, z2, zmax;
    
    glMatrixMode(GL_MODELVIEW);
    glGetDoublev( GL_MODELVIEW_MATRIX, mv_matrix);
        
    glGetIntegerv( GL_VIEWPORT, viewport);
    glSelectBuffer(sizeof(selectBuf)/sizeof(selectBuf[0]), selectBuf);
    
    glRenderMode(GL_SELECT);
    
    glMatrixMode(GL_PROJECTION);
    glPushMatrix();
    glLoadIdentity();
    gluPickMatrix( (GLdouble) x, (GLdouble) (viewport[3] - y), 2.0,2.0,
    			viewport);
    glOrtho(ViewCenter[0]-ViewSize,ViewCenter[0]+ViewSize, 
		    ViewCenter[1]-ViewSize,ViewCenter[1]+ViewSize, 
            -3*ViewDepth*ViewSize, 3*ViewDepth*ViewSize);

    glMatrixMode(GL_MODELVIEW);
	glPushMatrix();
    glLoadMatrixd(mv_matrix);
	glTranslated(-ObjectCenter[0], -ObjectCenter[1], -ObjectCenter[2]);

    glInitNames();
    glPushName((unsigned) -1);

    for (k= 1; k <=patch_num  ; k++)
    {
        glLoadName(k);
//		glCallList(patchList(k));
    }
    
    glPopMatrix();

    glMatrixMode(GL_PROJECTION);
    glPopMatrix();

    hits = glRenderMode(GL_RENDER);
    //printf("hits %d \n", hits);

    ptr = selectBuf;

    for (i = 0; i < hits; i++) { /*  for each hit  */
      names = *ptr;

      if(names !=1 ){
          //printf("something wrong?\n"); 
          break;  // wierd case, openGL bug? 
      }
      
      ptr++;
      z1 = *ptr;
      ptr++;
      z2 = *ptr;
      ptr++;

      // printf("names %d \n", names);
      
      if( i ==0 || z2 > zmax )
      {
          //printf("z: %ud \n", z2);
          zmax = z2;

        
          for (j = 0; j < names; j++) {     /*  for each name */
             if ( (*ptr <= (GLuint) patch_num) && (*ptr >= 1) )
             {
                picked = *ptr;
//                return picked;
             }
             ptr++;
          }
       }
    }
   
    return picked;
}
Example #16
0
guint Render::find_object_at(gdouble x, gdouble y)
{
  // Render everything in selection mode
  GdkGLContext *glcontext = gtk_widget_get_gl_context (get_widget());
  GdkGLDrawable *gldrawable = gtk_widget_get_gl_drawable (get_widget());

  const GLsizei BUFSIZE = 256;
  GLuint select_buffer[BUFSIZE];

  if (!gldrawable || !gdk_gl_drawable_gl_begin (gldrawable, glcontext))
    return 0;

  glSelectBuffer(BUFSIZE, select_buffer);
  (void)glRenderMode(GL_SELECT);

  GLint viewport[4];

  glMatrixMode (GL_PROJECTION);
  glPushMatrix();
  glLoadIdentity ();
  glGetIntegerv(GL_VIEWPORT,viewport);
  gluPickMatrix(x,viewport[3]-y,2,2,viewport); // 2x2 pixels around the cursor
  gluPerspective (45.0f, (float)get_width()/(float)get_height(),1.0f, 1000000.0f);
  glMatrixMode (GL_MODELVIEW);
  glInitNames();
  glPushName(0);
  glLoadIdentity ();

  glTranslatef (0.0, 0.0, -2.0 * m_zoom);
  glMultMatrixf (m_transform.M);
  CenterView();
  glPushMatrix();
  glColor3f(0.75f,0.75f,1.0f);

  glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, 1);

  Gtk::TreeModel::iterator no_object;
  m_view->Draw (no_object);

  // restor projection and model matrices
  glMatrixMode(GL_PROJECTION);
  glPopMatrix();
  glMatrixMode(GL_MODELVIEW);
  glPopMatrix();
  // restore rendering mode
  GLint hits = glRenderMode(GL_RENDER);

  if (gdk_gl_drawable_is_double_buffered(gldrawable))
    gdk_gl_drawable_swap_buffers (gldrawable);
  else
    glFlush();

  gdk_gl_drawable_gl_end (gldrawable);

  // Process the selection hits
  GLuint *ptr = select_buffer;
  GLuint name = 0;
  GLuint minZ = G_MAXUINT;

  for (GLint i = 0; i < hits; i++) { /*  for each hit  */
     GLuint n = *ptr++; // number of hits in this record
     GLuint z1 = *ptr++; // Minimum Z in the hit record
     ptr++; // Skip Maximum Z coord
     if (n > 0 && z1 < minZ) {
       // Found an object further forward.
       name = *ptr;
       minZ = z1;
     }
     ptr += n; // Skip n name records;
  }

  return name;
}
void ColoredMeshShape::draw() const
{
	if (!mesh_ || !meshColorIndexes_ || !palette_) return;

	//float nx, ny, nz;
	float r, g, b;
	size_t colorIndex;

	// save states
	glPushAttrib(GL_LIGHTING_BIT);

	// set attributes
	glDisable(GL_LIGHTING);

	const GLuint id = reinterpret_cast<GLuint>(this);
	glPushName(id);
		bool useObjectColor = false;
		swl::ObjectPickerMgr::color_type objectColor;
		if (swl::ObjectPickerMgr::getInstance().isPicking() && swl::ObjectPickerMgr::getInstance().isTemporarilyPickedObject(id))
		{
			objectColor = swl::ObjectPickerMgr::getInstance().getTemporarilyPickedColor();
			useObjectColor = true;
		}
		else if (swl::ObjectPickerMgr::getInstance().isPickedObject(id))
		{
			objectColor = swl::ObjectPickerMgr::getInstance().getPickedColor();
			useObjectColor = true;
		}

		float x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4, temp1, temp2, temp3, temp4;
		glBegin(GL_QUADS);
			for (size_t h = 0; h < meshHeight_ - 1; ++h)
				for (size_t w = 0; w < meshWidth_ - 1; ++w)
				{
					x1 = float(w) + xOffset_;
					x2 = float(w+1) + xOffset_;
					x3 = float(w+1) + xOffset_;
					x4 = float(w) + xOffset_;
#if 0
					y1 = float(h) + yOffset_;
					y2 = float(h) + yOffset_;
					y3 = float(h+1) + yOffset_;
					y4 = float(h+1) + yOffset_;
#else
					// flipped image
					y1 = float(meshHeight_ - h) + yOffset_;
					y2 = float(meshHeight_ - h) + yOffset_;
					y3 = float(meshHeight_ - (h+1)) + yOffset_;
					y4 = float(meshHeight_ - (h+1)) + yOffset_;
#endif

					temp1 = mesh_[h * meshWidth_ + w];
					z1 = temp1 * zScaleFactor_ + zOffset_;
					temp2 = mesh_[h * meshWidth_ + (w+1)];
					z2 = temp2 * zScaleFactor_ + zOffset_;
					temp3 = mesh_[(h+1) * meshWidth_ + (w+1)];
					z3 = temp3 * zScaleFactor_ + zOffset_;
					temp4 = mesh_[(h+1) * meshWidth_ + w];
					z4 = temp4 * zScaleFactor_ + zOffset_;

					//glEdgeFlag(GL_TRUE);

					//calculateNormal(x2 - x1, y2 - y1, z2 - z1, x3 - x1, y3 - y1, z3 - z1, nx, ny, nz);

					//
					if (useObjectColor) glColor4f(objectColor.r, objectColor.g, objectColor.b, objectColor.a);
					else
					{
						colorIndex = meshColorIndexes_[h * meshWidth_ + w] * paletteColorDim_;
						r = palette_[colorIndex] / 255.0f;
						g = palette_[colorIndex + 1] / 255.0f;
						b = palette_[colorIndex + 2] / 255.0f;
						glColor3f(r, g, b);
					}
					//glNormal3f(nx, ny, nz);
					glVertex3f(x1, y1, z1);
					//
					if (useObjectColor) glColor4f(objectColor.r, objectColor.g, objectColor.b, objectColor.a);
					else
					{
						colorIndex = meshColorIndexes_[h * meshWidth_ + (w+1)] * paletteColorDim_;
						r = palette_[colorIndex] / 255.0f;
						g = palette_[colorIndex + 1] / 255.0f;
						b = palette_[colorIndex + 2] / 255.0f;
						glColor3f(r, g, b);
					}
					//glNormal3f(nx, ny, nz);
					glVertex3f(x2, y2, z2);
					//
					if (useObjectColor) glColor4f(objectColor.r, objectColor.g, objectColor.b, objectColor.a);
					else
					{
						colorIndex = meshColorIndexes_[(h+1) * meshWidth_ + (w+1)] * paletteColorDim_;
						r = palette_[colorIndex] / 255.0f;
						g = palette_[colorIndex + 1] / 255.0f;
						b = palette_[colorIndex + 2] / 255.0f;
						glColor3f(r, g, b);
					}
					//glNormal3f(nx, ny, nz);
					glVertex3f(x3, y3, z3);
					//
					if (useObjectColor) glColor4f(objectColor.r, objectColor.g, objectColor.b, objectColor.a);
					else
					{
						colorIndex = meshColorIndexes_[(h+1) * meshWidth_ + w] * paletteColorDim_;
						r = palette_[colorIndex] / 255.0f;
						g = palette_[colorIndex + 1] / 255.0f;
						b = palette_[colorIndex + 2] / 255.0f;
						glColor3f(r, g, b);
					}
					//glNormal3f(nx, ny, nz);
					glVertex3f(x4, y4, z4);
				}
		glEnd();
	glPopName();

	// pop original attributes
	glPopAttrib();  // GL_LIGHTING_BIT
}
Example #18
0
void
GNEDetectorEntry::drawGL(const GUIVisualizationSettings& s) const {
    // Start drawing adding gl identificator
    glPushName(getGlID());

    // Push detector matrix
    glPushMatrix();
    glTranslated(0, 0, getType());

    // Set initial values
    if (isAdditionalSelected()) {
        glColor3d(myBaseColorSelected.red(), myBaseColorSelected.green(), myBaseColorSelected.blue());
    } else {
        glColor3d(myBaseColor.red(), myBaseColor.green(), myBaseColor.blue());
    }
    const SUMOReal exaggeration = s.addSize.getExaggeration(s);
    glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);

    // Push poligon matrix
    glPushMatrix();
    glScaled(exaggeration, exaggeration, 1);
    glTranslated(myShape[0].x(), myShape[0].y(), 0);
    glRotated(myShapeRotations[0], 0, 0, 1);

    // Draw poligon
    glBegin(GL_LINES);
    glVertex2d(1.7, 0);
    glVertex2d(-1.7, 0);
    glEnd();
    glBegin(GL_QUADS);
    glVertex2d(-1.7, .5);
    glVertex2d(-1.7, -.5);
    glVertex2d(1.7, -.5);
    glVertex2d(1.7, .5);
    glEnd();

    // first Arrow
    glTranslated(1.5, 0, 0);
    GLHelper::drawBoxLine(Position(0, 4), 0, 2, .05);
    GLHelper::drawTriangleAtEnd(Position(0, 4), Position(0, 1), (SUMOReal) 1, (SUMOReal) .25);

    // second Arrow
    glTranslated(-3, 0, 0);
    GLHelper::drawBoxLine(Position(0, 4), 0, 2, .05);
    GLHelper::drawTriangleAtEnd(Position(0, 4), Position(0, 1), (SUMOReal) 1, (SUMOReal) .25);

    // Pop poligon matrix
    glPopMatrix();

    // Pop detector matrix
    glPopMatrix();

    // Check if the distance is enought to draw details
    if (s.scale * exaggeration >= 10) {
        // Draw icon
        drawDetectorIcon(GUITextureSubSys::getTexture(GNETEXTURE_ENTRY), 1.5, 1);

        // Show Lock icon depending of the Edit mode
        drawLockIcon(0.4);
    }
    // Draw name
    drawName(getCenteringBoundary().getCenter(), s.scale, s.addName);

    // pop gl identificator
    glPopName();
}
Example #19
0
void GLwidget::mousePressEvent(QMouseEvent *ev)
{
    float posX = ev->x();
    float posy = ev->y();
    GLuint buff[64] = {0};
      GLint hits, view[4];

      /*
         This choose the buffer where store the values for the selection data
         */
      glSelectBuffer(64, buff);

      /*
         This retrieve info about the viewport
         */
      glGetIntegerv(GL_VIEWPORT, view);

      /*
         Switching in selecton mode
         */
      glRenderMode(GL_SELECT);

      /*
         Clearing the name's stack
         This stack contains all the info about the objects
         */
      glInitNames();

      /*
         Now fill the stack with one element (or glLoadName will generate an error)
         */
      glPushName(0);

      /*
         Now modify the vieving volume, restricting selection area around the cursor
         */
      glMatrixMode(GL_PROJECTION);
      glPushMatrix();
      glLoadIdentity();

      /*
         restrict the draw to an area around the cursor
         */
      gluPickMatrix(posX, posy, 1.0, 1.0, view);
      gluPerspective(60.0, this->width()/this->height(), 0.0001, 1000.0);

      /*
         Draw the objects onto the screen
         */
      glMatrixMode(GL_MODELVIEW);

      /*
         draw only the names in the stack, and fill the array
         */
      //glutSwapBuffers();
      swapBuffers();
      //gl_draw();
      paintGL();

      /*
         Do you remeber? We do pushMatrix in PROJECTION mode
         */
      glMatrixMode(GL_PROJECTION);
      glPopMatrix();

      /*
         get number of objects drawed in that area
         and return to render mode
         */
      hits = glRenderMode(GL_RENDER);
      qDebug() << hits;
      /*
         Print a list of the objects
         */
      list_hits(hits, buff);

      /*
         uncomment this to show the whole buffer
       * /
       gl_selall(hits, buff);
       */

      glMatrixMode(GL_MODELVIEW);
}
Example #20
0
void
GNEStop::drawGL(const GUIVisualizationSettings& s) const {
    // only drawn in super mode demand
    if (myViewNet->getViewOptions().showDemandElements()) {
        // Obtain exaggeration of the draw
        const double exaggeration = s.addSize.getExaggeration(s, this);
        // Start drawing adding an gl identificator
        glPushName(getGlID());
        // Add a draw matrix
        glPushMatrix();
        // Start with the drawing of the area traslating matrix to origin
        glTranslated(0, 0, getType());
        // Set color of the base
        if (drawUsingSelectColor()) {
            GLHelper::setColor(s.selectedAdditionalColor);
        } else {
            GLHelper::setColor(s.SUMO_color_stops);
        }
        // draw lines depending if it's placed over a lane or over a stoppingPlace
        if (getLaneParents().size() > 0) {
            // Draw the area using shape, shapeRotations, shapeLengths and value of exaggeration
            GLHelper::drawBoxLines(myGeometry.shape, myGeometry.shapeRotations, myGeometry.shapeLengths, exaggeration * 0.1, 0,
                                   getLaneParents().front()->getParentEdge().getNBEdge()->getLaneWidth(getLaneParents().front()->getIndex()) * 0.5);
            GLHelper::drawBoxLines(myGeometry.shape, myGeometry.shapeRotations, myGeometry.shapeLengths, exaggeration * 0.1, 0,
                                   getLaneParents().front()->getParentEdge().getNBEdge()->getLaneWidth(getLaneParents().front()->getIndex()) * -0.5);
        } else {
            // Draw the area using shape, shapeRotations, shapeLengths and value of exaggeration
            GLHelper::drawBoxLines(myGeometry.shape, myGeometry.shapeRotations, myGeometry.shapeLengths, exaggeration * 0.1, 0, exaggeration * -1);
            GLHelper::drawBoxLines(myGeometry.shape, myGeometry.shapeRotations, myGeometry.shapeLengths, exaggeration * 0.1, 0, exaggeration);
        }
        // pop draw matrix
        glPopMatrix();
        // Add a draw matrix
        glPushMatrix();
        // move to geometry front
        glTranslated(myGeometry.shape.back().x(), myGeometry.shape.back().y(), getType());
        glRotated(myGeometry.shapeRotations.back(), 0, 0, 1);
        // draw front of Stop depending if it's placed over a lane or over a stoppingPlace
        if (getLaneParents().size() > 0) {
            // draw front of Stop
            GLHelper::drawBoxLine(Position(0, 0), 0, exaggeration * 0.5,
                                  getLaneParents().front()->getParentEdge().getNBEdge()->getLaneWidth(getLaneParents().front()->getIndex()) * 0.5);
        } else {
            // draw front of Stop
            GLHelper::drawBoxLine(Position(0, 0), 0, exaggeration * 0.5, exaggeration);
        }
        // move to "S" position
        glTranslated(0, 1, 0);
        // draw "S" symbol
        GLHelper::drawText("S", Position(), .1, 2.8, s.SUMO_color_stops);
        // move to subtitle positin
        glTranslated(0, 1.4, 0);
        // draw subtitle depending of tag
        if (myTagProperty.getTag() == SUMO_TAG_STOP_BUSSTOP) {
            GLHelper::drawText("busStop", Position(), .1, .5, s.SUMO_color_stops, 180);
        } else if (myTagProperty.getTag() == SUMO_TAG_STOP_CONTAINERSTOP) {
            GLHelper::drawText("container", Position(), .1, .5, s.SUMO_color_stops, 180);
            glTranslated(0, 0.5, 0);
            GLHelper::drawText("Stop", Position(), .1, .5, s.SUMO_color_stops, 180);
        } else if (myTagProperty.getTag() == SUMO_TAG_STOP_CHARGINGSTATION) {
            GLHelper::drawText("charging", Position(), .1, .5, s.SUMO_color_stops, 180);
            glTranslated(0, 0.5, 0);
            GLHelper::drawText("Station", Position(), .1, .5, s.SUMO_color_stops, 180);
        } else if (myTagProperty.getTag() == SUMO_TAG_STOP_PARKINGAREA) {
            GLHelper::drawText("parking", Position(), .1, .5, s.SUMO_color_stops, 180);
            glTranslated(0, 0.5, 0);
            GLHelper::drawText("Area", Position(), .1, .5, s.SUMO_color_stops, 180);
        } else if (myTagProperty.getTag() == SUMO_TAG_STOP_LANE) {
            GLHelper::drawText("lane", Position(), .1, 1, s.SUMO_color_stops, 180);
        }
        // pop draw matrix
        glPopMatrix();
        // Draw name if isn't being drawn for selecting
        drawName(getCenteringBoundary().getCenter(), s.scale, s.addName);
        // check if dotted contour has to be drawn
        if (!s.drawForSelecting && (myViewNet->getDottedAC() == this)) {
            // draw dooted contour depending if it's placed over a lane or over a stoppingPlace
            if (getLaneParents().size() > 0) {
                GLHelper::drawShapeDottedContour(getType(), myGeometry.shape, getLaneParents().front()->getParentEdge().getNBEdge()->getLaneWidth(getLaneParents().front()->getIndex()) * 0.5);
            } else {
                GLHelper::drawShapeDottedContour(getType(), myGeometry.shape, exaggeration);
            }
        }
        // Pop name
        glPopName();
    }
}
Example #21
0
static void drawArrays(drawContext *ctx, GEntity *e, VertexArray *va, GLint type,
                       bool useNormalArray, int forceColor=0, unsigned int color=0)
{
  if(!va || !va->getNumVertices()) return;

  // If we want to be enable picking of individual elements we need to
  // draw each one separately
  bool select = (ctx->render_mode == drawContext::GMSH_SELECT &&
                 CTX::instance()->pickElements && e->model() == GModel::current());
  if(select) {
    if(va->getNumElementPointers() == va->getNumVertices()){
      for(int i = 0; i < va->getNumVertices(); i += va->getNumVerticesPerElement()){
        glPushName(va->getNumVerticesPerElement());
        glPushName(i);
        glBegin(type);
        for(int j = 0; j < va->getNumVerticesPerElement(); j++)
          glVertex3fv(va->getVertexArray(3 * (i + j)));
        glEnd();
        glPopName();
        glPopName();
      }
      return;
    }
  }

  glVertexPointer(3, GL_FLOAT, 0, va->getVertexArray());
  glEnableClientState(GL_VERTEX_ARRAY);

  if(useNormalArray){
    glEnable(GL_LIGHTING);
    glNormalPointer(GL_BYTE, 0, va->getNormalArray());
    glEnableClientState(GL_NORMAL_ARRAY);
  }
  else
    glDisableClientState(GL_NORMAL_ARRAY);

  if(forceColor){
    glDisableClientState(GL_COLOR_ARRAY);
    glColor4ubv((GLubyte *) & color);
  }
  else if(CTX::instance()->pickElements ||
          (!e->getSelection() && (CTX::instance()->mesh.colorCarousel == 0 ||
                                  CTX::instance()->mesh.colorCarousel == 3))){
    glColorPointer(4, GL_UNSIGNED_BYTE, 0, va->getColorArray());
    glEnableClientState(GL_COLOR_ARRAY);
  }
  else{
    glDisableClientState(GL_COLOR_ARRAY);
    color = getColorByEntity(e);
    glColor4ubv((GLubyte *) & color);
  }

  if(va->getNumVerticesPerElement() > 2 && CTX::instance()->polygonOffset)
    glEnable(GL_POLYGON_OFFSET_FILL);

  glDrawArrays(type, 0, va->getNumVertices());

  glDisable(GL_POLYGON_OFFSET_FILL);
  glDisable(GL_LIGHTING);

  glDisableClientState(GL_VERTEX_ARRAY);
  glDisableClientState(GL_NORMAL_ARRAY);
  glDisableClientState(GL_COLOR_ARRAY);
}
Example #22
0
static GLboolean
glgdGraphRender(glgdGraph *graph, GLenum renderMode)
{
    int             linkNdx;
    int             nodeDrawCount;
    glgdLinkList    *list;
    glgdLink        *link;
    glgdNode        *src;
    glgdNode        *dst;
    ScmObj          fn;

    if (graph != NULL)
    {
        fn = NULL;
        if (renderMode == GL_RENDER)
        {
            fn = graph->fn[GLGDGRAPH_FN_PRERENDER];
        }

        glgdGraphNodeListFlag(graph, GLGDNODE_FLAG_TOUCHED, GLGD_FLAGOP_CLEAR);

        linkNdx = 0;
        list = graph->linkListHead;
        while (list)
        {
            link = list->linkHead;
            while (link)
            {
                src = link->src;
                dst = link->dst;
                nodeDrawCount = 0;
                if (glgdBitfieldCompare(&graph->attributes, &src->attributes))
                {
                    /* Draw the src node */
                    if (glgdNodeIsTouched(src) == GL_FALSE)
                    {
                        glgdGraphNodeRender(graph, src, fn, renderMode);
                        glgdNodeFlagsSet(src, GLGDNODE_FLAG_TOUCHED,
                            GLGD_FLAGOP_SET);
                    }
                    nodeDrawCount++;

                    if (!(link->flags & GLGDLINK_FLAG_LONER) &&
                        glgdBitfieldCompare(&graph->attributes, &dst->attributes))
                    {
                        if (glgdNodeIsTouched(dst) == GL_FALSE)
                        {
                            glgdGraphNodeRender(graph, dst, fn, renderMode);
                            glgdNodeFlagsSet(dst, GLGDNODE_FLAG_TOUCHED,
                                GLGD_FLAGOP_SET);
                        }
                        nodeDrawCount++;
                    }
                }
            
                if (nodeDrawCount == 2)
                {
                    /* Draw the connecting link */
                    if (renderMode == GL_SELECT)
                    {
                        glPushName(GLGDGRAPH_LINKNAME);
                        glPushName(linkNdx);
                    }
                    glColor4d(graph->lineColor[0], graph->lineColor[1],
                        graph->lineColor[2], graph->lineColor[3]);
                    glgdLinkDraw(link, graph->dim, renderMode);
                    if (renderMode == GL_SELECT)
                    {
                        glPopName();
                        glPopName();
                    }
                }

                link = link->next;
                linkNdx++;
            }
            
            list = list->next;
        }

        return GL_TRUE;
    }
    
    return GL_FALSE;
}
Example #23
0
  void operator () (GRegion *r)
  {
    if(!r->getVisibility()) return;

    bool select = (_ctx->render_mode == drawContext::GMSH_SELECT &&
                   r->model() == GModel::current());
    if(select) {
      glPushName(3);
      glPushName(r->tag());
    }

    drawArrays(_ctx, r, r->va_lines, GL_LINES, CTX::instance()->mesh.light &&
               CTX::instance()->mesh.lightLines, CTX::instance()->mesh.volumesFaces,
               CTX::instance()->color.mesh.line);
    drawArrays(_ctx, r, r->va_triangles, GL_TRIANGLES, CTX::instance()->mesh.light);

    if(CTX::instance()->mesh.volumesNum) {
      if(CTX::instance()->mesh.tetrahedra)
        drawElementLabels(_ctx, r, r->tetrahedra, CTX::instance()->mesh.volumesFaces ||
                          CTX::instance()->mesh.surfacesFaces,
                          CTX::instance()->color.mesh.line);
      if(CTX::instance()->mesh.hexahedra)
        drawElementLabels(_ctx, r, r->hexahedra, CTX::instance()->mesh.volumesFaces ||
                          CTX::instance()->mesh.surfacesFaces,
                          CTX::instance()->color.mesh.line);
      if(CTX::instance()->mesh.prisms)
        drawElementLabels(_ctx, r, r->prisms, CTX::instance()->mesh.volumesFaces ||
                          CTX::instance()->mesh.surfacesFaces,
                          CTX::instance()->color.mesh.line);
      if(CTX::instance()->mesh.pyramids)
        drawElementLabels(_ctx, r, r->pyramids, CTX::instance()->mesh.volumesFaces ||
                          CTX::instance()->mesh.surfacesFaces,
                          CTX::instance()->color.mesh.line);
      drawElementLabels(_ctx, r, r->polyhedra, CTX::instance()->mesh.volumesFaces ||
                        CTX::instance()->mesh.surfacesFaces,
                        CTX::instance()->color.mesh.line);
    }

    if(CTX::instance()->mesh.points || CTX::instance()->mesh.pointsNum){
      if(r->getAllElementsVisible())
        drawVerticesPerEntity(_ctx, r);
      else{
        if(CTX::instance()->mesh.tetrahedra) drawVerticesPerElement(_ctx, r, r->tetrahedra);
        if(CTX::instance()->mesh.hexahedra) drawVerticesPerElement(_ctx, r, r->hexahedra);
        if(CTX::instance()->mesh.prisms) drawVerticesPerElement(_ctx, r, r->prisms);
        if(CTX::instance()->mesh.pyramids) drawVerticesPerElement(_ctx, r, r->pyramids);
        drawVerticesPerElement(_ctx, r, r->polyhedra);
      }
    }

    if(CTX::instance()->mesh.dual) {
      if(CTX::instance()->mesh.tetrahedra) drawBarycentricDual(r->tetrahedra);
      if(CTX::instance()->mesh.hexahedra) drawBarycentricDual(r->hexahedra);
      if(CTX::instance()->mesh.prisms) drawBarycentricDual(r->prisms);
      if(CTX::instance()->mesh.pyramids) drawBarycentricDual(r->pyramids);
      drawBarycentricDual(r->polyhedra);
    }

    if(CTX::instance()->mesh.voronoi) {
      if(CTX::instance()->mesh.tetrahedra) drawVoronoiDual(r->tetrahedra);
    }

    if(select) {
      glPopName();
      glPopName();
    }
  }
Example #24
0
void SceneCircle::draw(int id) {

    /*
     *  Code for this circle generation algorithm inspired from
     *
     *  URL: http://stackoverflow.com/questions/4197062/using-the-following-function-that-draws-a-filled-circle-in-opengl-how-do-i-make
     *  Jerry Coffin - StackOverflow,   Using the following function that draws a filled circle in opengl,
     *                                  how do I make it show at different coordinates of the window?,
     *
     *  Date: 16 novembre 2010,
     *  Consulté le: 30 septembre 2013
     */

    //draw outline if id matches
    if(getNodeId() == id) {
        /*
         * source for line stipple : http://fly.cc.fer.hr/~unreal/theredbook/chapter02.html
         */
        glLineStipple(4, 0xAAAA);
        glEnable(GL_LINE_STIPPLE);
        glLineWidth(3.0f);
        glBegin(GL_LINE_LOOP);
        {
            //assign color to shape
            if(getColor().r == 1 && getColor().g == 1 && getColor().b == 1){
                glColor3f(0, 1, 0);
            } else {
                glColor3f(1, 1, 1);
            }

            //define tempAngle and draw initial line
            double currentAngle = 0.0;
            glVertex2d(_radius * cos(currentAngle) , _radius * sin(currentAngle));

            //with every circlePoint draw a line of lenght radius at angle currentAngle then increment currentAngle
            for (unsigned int i=0; i < _circlePoints; i++) {
                glVertex2d(_radius * cos(currentAngle), _radius * sin(currentAngle));
                currentAngle += _angle;
            }
        }
        glEnd();
        glLineWidth(1.0f);
        glDisable(GL_LINE_STIPPLE);
    }

    glPushName(getNodeId());
    glBegin(GL_POLYGON);
    {
        //assign color to shape
        glColor3f(getColor().r, getColor().g, getColor().b);

        //define tempAngle and draw initial line
        double currentAngle = 0.0;
        glVertex2d(_radius * cos(currentAngle) , _radius * sin(currentAngle));

        //with every circlePoint draw a line of lenght radius at angle currentAngle then increment currentAngle
        for (unsigned int i=0; i < _circlePoints; i++) {
            glVertex2d(_radius * cos(currentAngle), _radius * sin(currentAngle));
            currentAngle += _angle;
        }
    }
    glEnd();
    glPopName();
}
Example #25
0
void
GUIPolygon::drawGL(const GUIVisualizationSettings& s) const {
    if (s.polySize.getExaggeration(s) == 0) {
        return;
    }
    Boundary boundary = myShape.getBoxBoundary();
    if (s.scale * MAX2(boundary.getWidth(), boundary.getHeight()) < s.polySize.minSize) {
        return;
    }
    if (getFill()) {
        if (myShape.size() < 3) {
            return;
        }
    } else {
        if (myShape.size() < 2) {
            return;
        }
    }
    AbstractMutex::ScopedLocker locker(myLock);
    //if (myDisplayList == 0 || (!getFill() && myLineWidth != s.polySize.getExaggeration(s))) {
    //    storeTesselation(s.polySize.getExaggeration(s));
    //}
    glPushName(getGlID());
    glPushMatrix();
    glTranslated(0, 0, getLayer());
    glRotated(-getNaviDegree(), 0, 0, 1);
    GLHelper::setColor(getColor());

    int textureID = -1;
    if (getFill()) {
        const std::string& file = getImgFile();
        if (file != "") {
            textureID = GUITexturesHelper::getTextureID(file, true);
        }
    }
    // init generation of texture coordinates
    if (textureID >= 0) {
        glEnable(GL_TEXTURE_2D);
        glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
        glDisable(GL_CULL_FACE);
        glDisable(GL_DEPTH_TEST); // without DEPTH_TEST vehicles may be drawn below roads
        glDisable(GL_LIGHTING);
        glDisable(GL_COLOR_MATERIAL);
        glDisable(GL_ALPHA_TEST);
        glEnable(GL_BLEND);
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
        glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
        glBindTexture(GL_TEXTURE_2D, textureID);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
        // http://www.gamedev.net/topic/133564-glutesselation-and-texture-mapping/
        glEnable(GL_TEXTURE_GEN_S);
        glEnable(GL_TEXTURE_GEN_T);
        glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR);
        glTexGenfv(GL_S, GL_OBJECT_PLANE, xPlane);
        glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR);
        glTexGenfv(GL_T, GL_OBJECT_PLANE, yPlane);
    }
    // recall tesselation
    //glCallList(myDisplayList);
    performTesselation(myLineWidth * s.polySize.getExaggeration(s));
    // de-init generation of texture coordinates
    if (textureID >= 0) {
        glEnable(GL_DEPTH_TEST);
        glBindTexture(GL_TEXTURE_2D, 0);
        glDisable(GL_TEXTURE_2D);
        glDisable(GL_TEXTURE_GEN_S);
        glDisable(GL_TEXTURE_GEN_T);
    }
#ifdef GUIPolygon_DEBUG_DRAW_VERTICES
    GLHelper::debugVertices(myShape, 80 / s.scale);
#endif
    glPopMatrix();
    const Position namePos = myShape.getPolygonCenter();
    drawName(namePos, s.scale, s.polyName);
    if (s.polyType.show) {
        GLHelper::drawText(myType, namePos + Position(0, -0.6 * s.polyType.size / s.scale),
                           GLO_MAX, s.polyType.size / s.scale, s.polyType.color);
    }
    glPopName();
}
Example #26
0
void
GNEDetectorEntry::drawGL(const GUIVisualizationSettings& s) const {
    // Start drawing adding gl identificator
    glPushName(getGlID());

    // Push detector matrix
    glPushMatrix();
    glTranslated(0, 0, getType());

    // Set initial values
    if (isAttributeCarrierSelected()) {
        GLHelper::setColor(myViewNet->getNet()->selectedAdditionalColor);
    } else {
        GLHelper::setColor(s.SUMO_color_E3Entry);
    }
    const double exaggeration = s.addSize.getExaggeration(s);
    glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);

    // Push polygon matrix
    glPushMatrix();
    glScaled(exaggeration, exaggeration, 1);
    glTranslated(myShape[0].x(), myShape[0].y(), 0);
    glRotated(myShapeRotations[0], 0, 0, 1);

    // Draw polygon
    glBegin(GL_LINES);
    glVertex2d(1.7, 0);
    glVertex2d(-1.7, 0);
    glEnd();
    glBegin(GL_QUADS);
    glVertex2d(-1.7, .5);
    glVertex2d(-1.7, -.5);
    glVertex2d(1.7, -.5);
    glVertex2d(1.7, .5);
    glEnd();
    
    // draw details if isn't being drawn for selecting
    if(!s.drawForSelecting) {
        // first Arrow
        glTranslated(1.5, 0, 0);
        GLHelper::drawBoxLine(Position(0, 4), 0, 2, .05);
        GLHelper::drawTriangleAtEnd(Position(0, 4), Position(0, 1), (double) 1, (double) .25);

        // second Arrow
        glTranslated(-3, 0, 0);
        GLHelper::drawBoxLine(Position(0, 4), 0, 2, .05);
        GLHelper::drawTriangleAtEnd(Position(0, 4), Position(0, 1), (double) 1, (double) .25);
    }

    // Pop polygon matrix
    glPopMatrix();

    // Pop detector matrix
    glPopMatrix();

    // Check if the distance is enought to draw details 
    if (((s.scale * exaggeration) >= 10)) {
        // Push matrix
        glPushMatrix();
        // Traslate to center of detector
        glTranslated(myShape.getLineCenter().x(), myShape.getLineCenter().y(), getType() + 0.1);
        // Rotate depending of myBlockIconRotation
        glRotated(myBlockIconRotation, 0, 0, -1);
        //move to logo position
        glTranslated(1.9, 0, 0);
        // draw Entry logo if isn't being drawn for selecting
        if(s.drawForSelecting) {
            GLHelper::setColor(s.SUMO_color_E3Entry);
            GLHelper::drawBoxLine(Position(0, 1), 0, 2, 1);
        } else if (isAttributeCarrierSelected()) {
            GLHelper::drawText("E3", Position(), .1, 2.8, myViewNet->getNet()->selectedAdditionalColor);
        } else {
            GLHelper::drawText("E3", Position(), .1, 2.8, s.SUMO_color_E3Entry);
        }
        //move to logo position
        glTranslated(1.7, 0, 0);
        // Rotate depending of myBlockIconRotation
        glRotated(90, 0, 0, 1);
        // draw Entry text if isn't being drawn for selecting
        if(s.drawForSelecting) {
            GLHelper::setColor(s.SUMO_color_E3Entry);
            GLHelper::drawBoxLine(Position(0, 1), 0, 2, 1);
        } else if (isAttributeCarrierSelected()) {
            GLHelper::drawText("Entry", Position(), .1, 1, myViewNet->getNet()->selectedAdditionalColor);
        } else {
            GLHelper::drawText("Entry", Position(), .1, 1, s.SUMO_color_E3Entry);
        }
        // pop matrix
        glPopMatrix();
        // Show Lock icon depending of the Edit mode and if isn't being drawn for selecting
        if(!s.drawForSelecting) {
            drawLockIcon(0.4);
        }
    }
    // Draw name if isn't being drawn for selecting
    if(!s.drawForSelecting) {
        drawName(getCenteringBoundary().getCenter(), s.scale, s.addName);
    }
    // check if dotted contour has to be drawn
    if(!s.drawForSelecting && (myViewNet->getACUnderCursor() == this)) {
        GLHelper::drawShapeDottedContour(getType(), myShape[0], 3.4, 5, myShapeRotations[0], 0, 2);
    }
    // pop gl identificator
    glPopName();
}
Example #27
0
   void VisualSceneOCCGeometry :: MouseDblClick (int px, int py)
   {
      int hits;

      // select surface triangle by mouse click

      GLuint selbuf[10000];
      glSelectBuffer (10000, selbuf);

      glRenderMode (GL_SELECT);

      GLint viewport[4];
      glGetIntegerv (GL_VIEWPORT, viewport);

      glMatrixMode (GL_PROJECTION);
      glPushMatrix();

      GLdouble projmat[16];
      glGetDoublev (GL_PROJECTION_MATRIX, projmat);

      glLoadIdentity();
      gluPickMatrix (px, viewport[3] - py, 1, 1, viewport);
      glMultMatrixd (projmat);

      glClearColor(backcolor, backcolor, backcolor, 1.0);
      glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

      glMatrixMode (GL_MODELVIEW);

      glPushMatrix();
      glMultMatrixf (transformationmat);

      glInitNames();
      glPushName (1);

      glPolygonOffset (1, 1);
      glEnable (GL_POLYGON_OFFSET_FILL);

      glDisable(GL_CLIP_PLANE0);

      // Philippose - 30/01/2009
      // Enable clipping planes for Selection mode in OCC Geometry
      if (vispar.clipenable)
      {
         Vec<3> n(clipplane[0], clipplane[1], clipplane[2]);
         double len = Abs(n);
         double mu = -clipplane[3] / (len*len);
         Point<3> p (mu * n);
         n /= len;
         Vec<3> t1 = n.GetNormal ();
         Vec<3> t2 = Cross (n, t1);

         double xi1mid = (center - p) * t1;
         double xi2mid = (center - p) * t2;

         glLoadName (0);
         glBegin (GL_QUADS);
         glVertex3dv (p + (xi1mid-rad) * t1 + (xi2mid-rad) * t2);
         glVertex3dv (p + (xi1mid+rad) * t1 + (xi2mid-rad) * t2);
         glVertex3dv (p + (xi1mid+rad) * t1 + (xi2mid+rad) * t2);
         glVertex3dv (p + (xi1mid-rad) * t1 + (xi2mid+rad) * t2);
         glEnd ();
      }

      glCallList (trilists.Get(1));

      glDisable (GL_POLYGON_OFFSET_FILL);

      glPopName();

      glMatrixMode (GL_PROJECTION);
      glPopMatrix();

      glMatrixMode (GL_MODELVIEW);
      glPopMatrix();

      glFlush();

      hits = glRenderMode (GL_RENDER);

      int minname = 0;
      GLuint mindepth = 0;

      // find clippingplane
      GLuint clipdepth = 0; // GLuint(-1);

      for (int i = 0; i < hits; i++)
      {
         int curname = selbuf[4*i+3];
         if (!curname) clipdepth = selbuf[4*i+1];
      }

      for (int i = 0; i < hits; i++)
      {
         int curname = selbuf[4*i+3];
         GLuint curdepth = selbuf[4*i+1];
         if (curname && (curdepth> clipdepth) &&
               (curdepth < mindepth || !minname))
         {
            mindepth = curdepth;
            minname = curname;
         }
      }

      occgeometry->LowLightAll();

      if (minname)
      {
         occgeometry->fvispar[minname-1].Highlight();

         if (vispar.occzoomtohighlightedentity)
         occgeometry->changed = OCCGEOMETRYVISUALIZATIONFULLCHANGE;
         else
         occgeometry->changed = OCCGEOMETRYVISUALIZATIONHALFCHANGE;
         cout << "Selected face: " << minname << endl;
      }
      else
      {
         occgeometry->changed = OCCGEOMETRYVISUALIZATIONHALFCHANGE;
      }

      glDisable(GL_CLIP_PLANE0);

      SelectFaceInOCCDialogTree (minname);

      // Philippose - 30/01/2009
      // Set the currently selected face in the array
      // for local face mesh size definition
      occgeometry->SetSelectedFace(minname);

      //  selecttimestamp = NextTimeStamp();
   }
Example #28
0
void drawEvolvent(int r)
{
        Vertex3D v;
        Vector3D n;
        int i, j;

        glPushName(1);

        if (r) {
                glBegin(GL_QUADS);
                for (i = 0; i < PHI_STEPS; ++i) {
                        for (j = 0; j < PHI1_STEPS; ++j) {
                                n = R_EVOLN_IJ(i, j);
                                glNormal3f(n.x, n.y, n.z);
                                v = R_EVOL_IJ(i, j);
                                glVertex3f(v.x, v.y, v.z);

                                n = R_EVOLN_IJ(i+1, j);
                                glNormal3f(n.x, n.y, n.z);
                                v = R_EVOL_IJ(i+1, j);
                                glVertex3f(v.x, v.y, v.z);

                                n = R_EVOLN_IJ(i+1, j+1);
                                glNormal3f(n.x, n.y, n.z);
                                v = R_EVOL_IJ(i+1, j+1);
                                glVertex3f(v.x, v.y, v.z);

                                n = R_EVOLN_IJ(i, j+1);
                                glNormal3f(n.x, n.y, n.z);
                                v = R_EVOL_IJ(i, j+1);
                                glVertex3f(v.x, v.y, v.z);
                        }
                }
                glEnd();
        } else {
                glBegin(GL_QUADS);
                for (i = 0; i < PHI_STEPS; ++i) {
                        for (j = 0; j < PHI1_STEPS; ++j) {
                                n = L_EVOLN_IJ(i, j);
                                glNormal3f(n.x, n.y, n.z);
                                v = L_EVOL_IJ(i, j);
                                glVertex3f(v.x, v.y, v.z);

                                n = L_EVOLN_IJ(i+1, j);
                                glNormal3f(n.x, n.y, n.z);
                                v = L_EVOL_IJ(i+1, j);
                                glVertex3f(v.x, v.y, v.z);

                                n = L_EVOLN_IJ(i+1, j+1);
                                glNormal3f(n.x, n.y, n.z);
                                v = L_EVOL_IJ(i+1, j+1);
                                glVertex3f(v.x, v.y, v.z);

                                n = L_EVOLN_IJ(i, j+1);
                                glNormal3f(n.x, n.y, n.z);
                                v = L_EVOL_IJ(i, j+1);
                                glVertex3f(v.x, v.y, v.z);
                        }
                }
                glEnd();
        }

        glPopName();
}
Example #29
0
void cc2DLabel::drawMeOnly2D(CC_DRAW_CONTEXT& context)
{
	if (!m_dispIn2D)
		return;

	assert(!m_points.empty());

	//standard case: list names pushing
	bool pushName = MACRO_DrawEntityNames(context);
	if (pushName)
		glPushName(getUniqueID());

	//we should already be in orthoprojective & centered omde
	//glOrtho(-halfW,halfW,-halfH,halfH,-maxS,maxS);

	int strHeight = 0;
	int titleHeight = 0;
	QString title(getName());
	QStringList body;
	GLdouble arrowDestX=-1.0,arrowDestY=-1.0;
	QFont bodyFont,titleFont;
	if (!pushName)
	{
		/*** line from 2D point to label ***/

		//compute arrow head position
		CCVector3 arrowDest;
		m_points[0].cloud->getPoint(m_points[0].index,arrowDest);
		for (unsigned i=1;i<m_points.size();++i)
			arrowDest += *m_points[i].cloud->getPointPersistentPtr(m_points[i].index);
		arrowDest /= (PointCoordinateType)m_points.size();

		//project it in 2D screen coordinates
		int VP[4];
		context._win->getViewportArray(VP);
		const double* MM = context._win->getModelViewMatd(); //viewMat
		const double* MP = context._win->getProjectionMatd(); //projMat
		GLdouble zp;
		gluProject(arrowDest.x,arrowDest.y,arrowDest.z,MM,MP,VP,&arrowDestX,&arrowDestY,&zp);

		/*** label border ***/
		bodyFont = context._win->getTextDisplayFont();
		titleFont = QFont(context._win->getTextDisplayFont());
		titleFont.setBold(true);
		QFontMetrics titleFontMetrics(titleFont);
		QFontMetrics bodyFontMetrics(bodyFont);

		strHeight = bodyFontMetrics.height();
		titleHeight = titleFontMetrics.height();

		if (m_showFullBody)
			body = getLabelContent(context.dispNumberPrecision);

		//base box dimension
		int dx = 150;
		dx = std::max(dx,titleFontMetrics.width(title));

		int dy = c_margin;	//top vertical margin
		dy += titleHeight;	//title
		if (!body.empty())
		{
			dy += c_margin;	//vertical margin above separator
			for (int j=0;j<body.size();++j)
			{
				dx = std::max(dx,bodyFontMetrics.width(body[j]));
				dy += (c_margin+strHeight); //margin + body line height
			}
		}
		else
		{
			dy += c_margin;		// vertical margin (purely for aesthetics)
		}
		dy += c_margin;		// bottom vertical margin
		dx += c_margin*2;	// horizontal margins

		//main rectangle
		m_labelROI[0]=0;
		m_labelROI[1]=0;
		m_labelROI[2]=dx;
		m_labelROI[3]=dy;

		//close button
		/*m_closeButtonROI[2]=dx-c_margin;
		m_closeButtonROI[0]=m_closeButtonROI[2]-c_buttonSize;
		m_closeButtonROI[3]=c_margin;
		m_closeButtonROI[1]=m_closeButtonROI[3]+c_buttonSize;
		//*/

		//automatically elide the title
		//title = titleFontMetrics.elidedText(title,Qt::ElideRight,m_closeButtonROI[0]-2*c_margin);
	}

	int halfW = (context.glW>>1);
	int halfH = (context.glH>>1);

	//draw label rectangle
	int xStart = m_lastScreenPos[0] = (int)((float)context.glW * m_screenPos[0]);
	int yStart = m_lastScreenPos[1] = (int)((float)context.glH * (1.0f-m_screenPos[1]));

	//colors
	bool highlighted = (!pushName && isSelected());
	//default background color
	colorType defaultBkgColor[4];
	memcpy(defaultBkgColor,context.labelDefaultCol,sizeof(colorType)*3);
	defaultBkgColor[3]=(colorType)((float)context.labelsTransparency*(float)MAX_COLOR_COMP/100.0f);
	//default border color (mustn't be totally transparent!)
	colorType defaultBorderColor[4];
	if (highlighted)
		memcpy(defaultBorderColor,ccColor::red,sizeof(colorType)*3);
	else
		memcpy(defaultBorderColor,context.labelDefaultCol,sizeof(colorType)*3);
	defaultBorderColor[3]=(colorType)((float)(50+context.labelsTransparency/2)*(float)MAX_COLOR_COMP/100.0f);

	glPushAttrib(GL_COLOR_BUFFER_BIT);
	glEnable(GL_BLEND);

	glMatrixMode(GL_MODELVIEW);
	glPushMatrix();
	glTranslatef(-halfW+xStart,-halfH+yStart,0);

	if (!pushName)
	{
		//compute arrow base position relatively to the label rectangle (for 0 to 8)
		int arrowBaseConfig = 0;
		int iArrowDestX = (int)arrowDestX-xStart;
		int iArrowDestY = (int)arrowDestY-yStart;
		{
			if (iArrowDestX < m_labelROI[0]) //left
				arrowBaseConfig += 0;
			else if (iArrowDestX > m_labelROI[2]) //Right
				arrowBaseConfig += 2;
			else  //Middle
				arrowBaseConfig += 1;

			if (iArrowDestY > -m_labelROI[1]) //Top
				arrowBaseConfig += 0;
			else if (iArrowDestY < -m_labelROI[3]) //Bottom
				arrowBaseConfig += 6;
			else  //Middle
				arrowBaseConfig += 3;
		}

		//we make the arrow base start from the nearest corner
		if (arrowBaseConfig != 4) //4 = label above point!
		{
			glColor4ubv(defaultBorderColor);
			glBegin(GL_TRIANGLE_FAN);
			glVertex2d(arrowDestX-xStart,arrowDestY-yStart);
			switch(arrowBaseConfig)
			{
			case 0: //top-left corner
				glVertex2i(m_labelROI[0], -m_labelROI[1]-2*c_arrowBaseSize);
				glVertex2i(m_labelROI[0], -m_labelROI[1]);
				glVertex2i(m_labelROI[0]+2*c_arrowBaseSize, -m_labelROI[1]);
				break;
			case 1: //top-middle edge
				glVertex2i(std::max(m_labelROI[0],iArrowDestX-c_arrowBaseSize), -m_labelROI[1]);
				glVertex2i(std::min(m_labelROI[2],iArrowDestX+c_arrowBaseSize), -m_labelROI[1]);
				break;
			case 2: //top-right corner
				glVertex2i(m_labelROI[2], -m_labelROI[1]-2*c_arrowBaseSize);
				glVertex2i(m_labelROI[2], -m_labelROI[1]);
				glVertex2i(m_labelROI[2]-2*c_arrowBaseSize, -m_labelROI[1]);
				break;
			case 3: //middle-left edge
				glVertex2i(m_labelROI[0], std::min(-m_labelROI[1],iArrowDestY+c_arrowBaseSize));
				glVertex2i(m_labelROI[0], std::max(-m_labelROI[3],iArrowDestY-c_arrowBaseSize));
				break;
			case 4: //middle of rectangle!
				break;
			case 5: //middle-right edge
				glVertex2i(m_labelROI[2], std::min(-m_labelROI[1],iArrowDestY+c_arrowBaseSize));
				glVertex2i(m_labelROI[2], std::max(-m_labelROI[3],iArrowDestY-c_arrowBaseSize));
				break;
			case 6: //bottom-left corner
				glVertex2i(m_labelROI[0], -m_labelROI[3]+2*c_arrowBaseSize);
				glVertex2i(m_labelROI[0], -m_labelROI[3]);
				glVertex2i(m_labelROI[0]+2*c_arrowBaseSize, -m_labelROI[3]);
				break;
			case 7: //bottom-middle edge
				glVertex2i(std::max(m_labelROI[0],iArrowDestX-c_arrowBaseSize), -m_labelROI[3]);
				glVertex2i(std::min(m_labelROI[2],iArrowDestX+c_arrowBaseSize), -m_labelROI[3]);
				break;
			case 8: //bottom-right corner
				glVertex2i(m_labelROI[2], -m_labelROI[3]+2*c_arrowBaseSize);
				glVertex2i(m_labelROI[2], -m_labelROI[3]);
				glVertex2i(m_labelROI[2]-2*c_arrowBaseSize, -m_labelROI[3]);
				break;
			}
			glEnd();
		}
	}

	//main rectangle
	glColor4ubv(defaultBkgColor);
    glBegin(GL_QUADS);
    glVertex2i(m_labelROI[0], -m_labelROI[1]);
    glVertex2i(m_labelROI[0], -m_labelROI[3]);
    glVertex2i(m_labelROI[2], -m_labelROI[3]);
    glVertex2i(m_labelROI[2], -m_labelROI[1]);
    glEnd();

	//if (highlighted)
	{
		glPushAttrib(GL_LINE_BIT);
		glLineWidth(3.0f);
		glColor4ubv(defaultBorderColor);
		glBegin(GL_LINE_LOOP);
		glVertex2i(m_labelROI[0], -m_labelROI[1]);
		glVertex2i(m_labelROI[0], -m_labelROI[3]);
		glVertex2i(m_labelROI[2], -m_labelROI[3]);
		glVertex2i(m_labelROI[2], -m_labelROI[1]);
		glEnd();
		glPopAttrib();
	}

	//draw close button
	/*glColor3ubv(ccColor::black);
    glBegin(GL_LINE_LOOP);
    glVertex2i(m_closeButtonROI[0],-m_closeButtonROI[1]);
    glVertex2i(m_closeButtonROI[0],-m_closeButtonROI[3]);
    glVertex2i(m_closeButtonROI[2],-m_closeButtonROI[3]);
    glVertex2i(m_closeButtonROI[2],-m_closeButtonROI[1]);
    glEnd();
    glBegin(GL_LINES);
    glVertex2i(m_closeButtonROI[0]+2,-m_closeButtonROI[1]+2);
    glVertex2i(m_closeButtonROI[2]-2,-m_closeButtonROI[3]-2);
    glVertex2i(m_closeButtonROI[2]-2,-m_closeButtonROI[1]+2);
    glVertex2i(m_closeButtonROI[0]+2,-m_closeButtonROI[3]-2);
    glEnd();
	//*/

	//display text
	if (!pushName)
	{
		int xStartRel = c_margin;
		int yStartRel = -c_margin;
		yStartRel -= titleHeight;

		const colorType* defaultTextColor = (context.labelsTransparency<40 ? context.textDefaultCol : ccColor::darkBlue);

		context._win->displayText(title,xStart+xStartRel,yStart+yStartRel,ccGenericGLDisplay::ALIGN_DEFAULT,0,defaultTextColor,&titleFont);
		yStartRel -= c_margin;

		if (!body.empty())
		{
			//line separation
			glColor4ubv(defaultBorderColor);
			glBegin(GL_LINES);
			glVertex2i(xStartRel,yStartRel);
			glVertex2i(xStartRel+m_labelROI[2]-m_labelROI[0]-2*c_margin,yStartRel);
			glEnd();

			//display body
			yStartRel -= c_margin;
			for (int i=0;i<body.size();++i)
			{
				yStartRel -= strHeight;
				context._win->displayText(body[i],xStart+xStartRel,yStart+yStartRel,ccGenericGLDisplay::ALIGN_DEFAULT,0,defaultTextColor,&bodyFont);
			}
		}
	}

	glPopAttrib();

	glPopMatrix();

	if (pushName)
		glPopName();
}
Example #30
0
/* Render one gear in the proper position, creating the gear's
   display list first if necessary.
 */
static void
draw_gear (ModeInfo *mi, int which)
{
  Bool wire_p = MI_IS_WIREFRAME(mi);
  pinion_configuration *pp = &pps[MI_SCREEN(mi)];
  gear *g = pp->gears[which];
  GLfloat th;

  Bool visible_p = (g->x + g->r + g->tooth_h >= pp->render_left &&
                    g->x - g->r - g->tooth_h <= pp->render_right);

  if (!visible_p && !debug_p)
    return;

  if (! g->dlist)
    {
      g->dlist = glGenLists (1);
      if (! g->dlist)
        {
          /* I don't know how many display lists a GL implementation
             is supposed to provide, but hopefully it's more than
             "a few hundred", or we'll be in trouble...
           */
          check_gl_error ("glGenLists");
          abort();
        }

      glNewList (g->dlist, GL_COMPILE);
      g->polygons = draw_involute_gear (g, (wire_p && debug_p ? 2 : wire_p));
      glEndList ();
    }

  glPushMatrix();

  glTranslatef (g->x, g->y, g->z);

  if (g->motion_blur_p && !pp->button_down_p)
    {
      /* If we're in motion-blur mode, then draw the gear so that each
         frame rotates it by exactly one half tooth-width, so that it
         looks flickery around the edges.  But, revert to the normal
         way when the mouse button is down lest the user see overlapping
         polygons.
       */
      th = g->motion_blur_p * 180.0 / g->nteeth * (g->th > 0 ? 1 : -1);
      g->motion_blur_p++;
    }
  else
    th = g->th;

  glRotatef (th, 0, 0, 1);

  glPushName (g->id);

  if (! visible_p)
    mi->polygon_count += draw_involute_schematic (g, wire_p);
  else
    {
      glCallList (g->dlist);
      mi->polygon_count += g->polygons;
    }

  glPopName();
  glPopMatrix();
}