Пример #1
0
void ccOctree::RenderOctreeAs(  CC_OCTREE_DISPLAY_TYPE octreeDisplayType,
								CCLib::DgmOctree* theOctree,
								unsigned char level,
								ccGenericPointCloud* theAssociatedCloud,
								int &octreeGLListID,
								bool updateOctreeGLDisplay)
{
	if (!theOctree || !theAssociatedCloud)
		return;

	glPushAttrib(GL_LIGHTING_BIT);

	if (octreeDisplayType==WIRE)
	{
		//cet affichage demande trop de memoire pour le stocker sous forme de liste OpenGL
		//donc on doit le generer dynamiquement
		
		glDisable(GL_LIGHTING); //au cas où la lumiere soit allumee
		glColor3ubv(ccColor::green);
		theOctree->executeFunctionForAllCellsAtLevel(level,&DrawCellAsABox,NULL);
	}
	else
	{
		glDrawParams glParams;
		theAssociatedCloud->getDrawingParameters(glParams);

		if (glParams.showNorms)
		{
			//DGM: Strangely, when Qt::renderPixmap is called, the OpenGL version is sometimes 1.0!
            glEnable((QGLFormat::openGLVersionFlags() & QGLFormat::OpenGL_Version_1_2 ? GL_RESCALE_NORMAL : GL_NORMALIZE));
            glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT,	  CC_DEFAULT_CLOUD_AMBIENT_COLOR  );
            glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR,  CC_DEFAULT_CLOUD_SPECULAR_COLOR );
            glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE,   CC_DEFAULT_CLOUD_DIFFUSE_COLOR  );
			glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION,  CC_DEFAULT_CLOUD_EMISSION_COLOR );
            glMaterialf (GL_FRONT_AND_BACK, GL_SHININESS, CC_DEFAULT_CLOUD_SHININESS);
			glEnable(GL_LIGHTING);

			glEnable(GL_COLOR_MATERIAL);
			glColorMaterial(GL_FRONT_AND_BACK, GL_DIFFUSE);
		}

		if (!glParams.showColors)
			glColor3ubv(ccColor::white);

		if (updateOctreeGLDisplay || octreeGLListID<0)
		{
			if (octreeGLListID<0)
				octreeGLListID = glGenLists(1);
			else if (glIsList(octreeGLListID))
				glDeleteLists(octreeGLListID,1);
			glNewList(octreeGLListID,GL_COMPILE);

			if (octreeDisplayType == MEAN_POINTS)
			{
				void* additionalParameters[2] = {	(void*)&glParams,
													(void*)theAssociatedCloud,
				};

				glBegin(GL_POINTS);
				theOctree->executeFunctionForAllCellsAtLevel(level,&DrawCellAsAPoint,additionalParameters,0,"Render octree");
				glEnd();
			}
			else
			{
				//by default we use a box as primitive
				PointCoordinateType cs = theOctree->getCellSize(level);
				CCVector3 dims(cs,cs,cs);
				ccBox box(dims);
				box.showColors(glParams.showColors || glParams.showSF);
				box.showNormals(glParams.showNorms);

				//trick: replace all normal indexes so that they point on the first one
				{
					if (box.arePerTriangleNormalsEnabled())
						for (unsigned i=0;i<box.size();++i)
							box.setTriangleNormalIndexes(i,0,0,0);
				}

				//fake context
				CC_DRAW_CONTEXT context;
				context.flags = CC_DRAW_3D | CC_DRAW_FOREGROUND| CC_LIGHT_ENABLED;
				context._win = 0;

				void* additionalParameters[4] = {	(void*)&glParams,
													(void*)theAssociatedCloud,
													(void*)&box,
													(void*)&context
				};

				theOctree->executeFunctionForAllCellsAtLevel(level,&DrawCellAsAPrimitive,additionalParameters,0);
			}

			glEndList();
		}

		glCallList(octreeGLListID);

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

	glPopAttrib();
}
Пример #2
0
/*
 * Draw a sequence strip, bounds check already made
 * ARegion is currently only used to get the windows width in pixels
 * so wave file sample drawing precision is zoom adjusted
 */
static void draw_seq_strip(Scene *scene, ARegion *ar, Sequence *seq, int outline_tint, float pixelx)
{
	View2D *v2d = &ar->v2d;
	float x1, x2, y1, y2;
	unsigned char col[3], background_col[3], is_single_image;
	const float handsize_clamped = draw_seq_handle_size_get_clamped(seq, pixelx);

	/* we need to know if this is a single image/color or not for drawing */
	is_single_image = (char)BKE_sequence_single_check(seq);
	
	/* body */
	x1 = (seq->startstill) ? seq->start : seq->startdisp;
	y1 = seq->machine + SEQ_STRIP_OFSBOTTOM;
	x2 = (seq->endstill) ? (seq->start + seq->len) : seq->enddisp;
	y2 = seq->machine + SEQ_STRIP_OFSTOP;


	/* get the correct color per strip type*/
	//get_seq_color3ubv(scene, seq, col);
	get_seq_color3ubv(scene, seq, background_col);
	
	/* draw the main strip body */
	if (is_single_image) {  /* single image */
		draw_shadedstrip(seq, background_col,
		                 BKE_sequence_tx_get_final_left(seq, 0), y1,
		                 BKE_sequence_tx_get_final_right(seq, 0), y2);
	}
	else {  /* normal operation */
		draw_shadedstrip(seq, background_col, x1, y1, x2, y2);
	}
	
	/* draw additional info and controls */
	if (!is_single_image)
		draw_seq_extensions(scene, ar, seq);
	
	draw_seq_handle(v2d, seq, handsize_clamped, SEQ_LEFTHANDLE);
	draw_seq_handle(v2d, seq, handsize_clamped, SEQ_RIGHTHANDLE);
	
	/* draw the strip outline */
	x1 = seq->startdisp;
	x2 = seq->enddisp;
	
	/* draw sound wave */
	if (seq->type == SEQ_TYPE_SOUND_RAM) {
		drawseqwave(scene, seq, x1, y1, x2, y2, BLI_rctf_size_x(&ar->v2d.cur) / ar->winx);
	}

	/* draw lock */
	if (seq->flag & SEQ_LOCK) {
		glEnable(GL_POLYGON_STIPPLE);
		glEnable(GL_BLEND);

		/* light stripes */
		glColor4ub(255, 255, 255, 32);
		glPolygonStipple(stipple_diag_stripes_pos);
		glRectf(x1, y1, x2, y2);

		/* dark stripes */
		glColor4ub(0, 0, 0, 32);
		glPolygonStipple(stipple_diag_stripes_neg);
		glRectf(x1, y1, x2, y2);

		glDisable(GL_POLYGON_STIPPLE);
		glDisable(GL_BLEND);
	}

	if (!BKE_sequence_is_valid_check(seq)) {
		glEnable(GL_POLYGON_STIPPLE);

		/* panic! */
		glColor4ub(255, 0, 0, 255);
		glPolygonStipple(stipple_diag_stripes_pos);
		glRectf(x1, y1, x2, y2);

		glDisable(GL_POLYGON_STIPPLE);
	}

	get_seq_color3ubv(scene, seq, col);
	if ((G.moving & G_TRANSFORM_SEQ) && (seq->flag & SELECT)) {
		if (seq->flag & SEQ_OVERLAP) {
			col[0] = 255; col[1] = col[2] = 40;
		}
		else
			UI_GetColorPtrShade3ubv(col, col, 120 + outline_tint);
	}
	else
		UI_GetColorPtrShade3ubv(col, col, outline_tint);
	
	glColor3ubv((GLubyte *)col);
	
	if (seq->flag & SEQ_MUTE) {
		glEnable(GL_LINE_STIPPLE);
		glLineStipple(1, 0x8888);
	}
	
	uiDrawBoxShade(GL_LINE_LOOP, x1, y1, x2, y2, 0.0, 0.1, 0.0);
	
	if (seq->flag & SEQ_MUTE) {
		glDisable(GL_LINE_STIPPLE);
	}
	
	if (seq->type == SEQ_TYPE_META) {
		drawmeta_contents(scene, seq, x1, y1, x2, y2);
	}
	
	/* calculate if seq is long enough to print a name */
	x1 = seq->startdisp + handsize_clamped;
	x2 = seq->enddisp   - handsize_clamped;

	/* info text on the strip */
	if (x1 < v2d->cur.xmin) x1 = v2d->cur.xmin;
	else if (x1 > v2d->cur.xmax) x1 = v2d->cur.xmax;
	if (x2 < v2d->cur.xmin) x2 = v2d->cur.xmin;
	else if (x2 > v2d->cur.xmax) x2 = v2d->cur.xmax;

	/* nice text here would require changing the view matrix for texture text */
	if ((x2 - x1) / pixelx > 32) {
		draw_seq_text(v2d, seq, x1, x2, y1, y2, background_col);
	}
}
Пример #3
0
void ui_draw_but_CURVE(ARegion *ar, uiBut *but, uiWidgetColors *wcol, rcti *rect)
{
	CurveMapping *cumap;
	CurveMap *cuma;
	CurveMapPoint *cmp;
	float fx, fy, fac[2], zoomx, zoomy, offsx, offsy;
	GLint scissor[4];
	rcti scissor_new;
	int a;

	if (but->editcumap) {
		cumap = but->editcumap;
	}
	else {
		cumap = (CurveMapping *)but->poin;
	}

	cuma = &cumap->cm[cumap->cur];

	/* need scissor test, curve can draw outside of boundary */
	glGetIntegerv(GL_VIEWPORT, scissor);
	scissor_new.xmin = ar->winrct.xmin + rect->xmin;
	scissor_new.ymin = ar->winrct.ymin + rect->ymin;
	scissor_new.xmax = ar->winrct.xmin + rect->xmax;
	scissor_new.ymax = ar->winrct.ymin + rect->ymax;
	BLI_rcti_isect(&scissor_new, &ar->winrct, &scissor_new);
	glScissor(scissor_new.xmin,
	          scissor_new.ymin,
	          BLI_rcti_size_x(&scissor_new),
	          BLI_rcti_size_y(&scissor_new));

	/* calculate offset and zoom */
	zoomx = (BLI_rcti_size_x(rect) - 2.0f * but->aspect) / BLI_rctf_size_x(&cumap->curr);
	zoomy = (BLI_rcti_size_y(rect) - 2.0f * but->aspect) / BLI_rctf_size_y(&cumap->curr);
	offsx = cumap->curr.xmin - but->aspect / zoomx;
	offsy = cumap->curr.ymin - but->aspect / zoomy;
	
	/* backdrop */
	if (but->a1 == UI_GRAD_H) {
		/* magic trigger for curve backgrounds */
		rcti grid;
		float col[3] = {0.0f, 0.0f, 0.0f}; /* dummy arg */

		grid.xmin = rect->xmin + zoomx * (-offsx);
		grid.xmax = rect->xmax + zoomx * (-offsx);
		grid.ymin = rect->ymin + zoomy * (-offsy);
		grid.ymax = rect->ymax + zoomy * (-offsy);

		ui_draw_gradient(&grid, col, UI_GRAD_H, 1.0f);

		/* grid, hsv uses different grid */
		glEnable(GL_BLEND);
		glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
		glColor4ub(0, 0, 0, 48);
		ui_draw_but_curve_grid(rect, zoomx, zoomy, offsx, offsy, 0.1666666f);
		glDisable(GL_BLEND);
	}
	else {
		if (cumap->flag & CUMA_DO_CLIP) {
			gl_shaded_color((unsigned char *)wcol->inner, -20);
			glRectf(rect->xmin, rect->ymin, rect->xmax, rect->ymax);
			glColor3ubv((unsigned char *)wcol->inner);
			glRectf(rect->xmin + zoomx * (cumap->clipr.xmin - offsx),
			        rect->ymin + zoomy * (cumap->clipr.ymin - offsy),
			        rect->xmin + zoomx * (cumap->clipr.xmax - offsx),
			        rect->ymin + zoomy * (cumap->clipr.ymax - offsy));
		}
		else {
			glColor3ubv((unsigned char *)wcol->inner);
			glRectf(rect->xmin, rect->ymin, rect->xmax, rect->ymax);
		}

		/* grid, every 0.25 step */
		gl_shaded_color((unsigned char *)wcol->inner, -16);
		ui_draw_but_curve_grid(rect, zoomx, zoomy, offsx, offsy, 0.25f);
		/* grid, every 1.0 step */
		gl_shaded_color((unsigned char *)wcol->inner, -24);
		ui_draw_but_curve_grid(rect, zoomx, zoomy, offsx, offsy, 1.0f);
		/* axes */
		gl_shaded_color((unsigned char *)wcol->inner, -50);
		glBegin(GL_LINES);
		glVertex2f(rect->xmin, rect->ymin + zoomy * (-offsy));
		glVertex2f(rect->xmax, rect->ymin + zoomy * (-offsy));
		glVertex2f(rect->xmin + zoomx * (-offsx), rect->ymin);
		glVertex2f(rect->xmin + zoomx * (-offsx), rect->ymax);
		glEnd();
	}

	/* cfra option */
	/* XXX 2.48 */
#if 0
	if (cumap->flag & CUMA_DRAW_CFRA) {
		glColor3ub(0x60, 0xc0, 0x40);
		glBegin(GL_LINES);
		glVertex2f(rect->xmin + zoomx * (cumap->sample[0] - offsx), rect->ymin);
		glVertex2f(rect->xmin + zoomx * (cumap->sample[0] - offsx), rect->ymax);
		glEnd();
	}
#endif
	/* sample option */

	if (cumap->flag & CUMA_DRAW_SAMPLE) {
		if (but->a1 == UI_GRAD_H) {
			float tsample[3];
			float hsv[3];
			linearrgb_to_srgb_v3_v3(tsample, cumap->sample);
			rgb_to_hsv_v(tsample, hsv);
			glColor3ub(240, 240, 240);

			glBegin(GL_LINES);
			glVertex2f(rect->xmin + zoomx * (hsv[0] - offsx), rect->ymin);
			glVertex2f(rect->xmin + zoomx * (hsv[0] - offsx), rect->ymax);
			glEnd();
		}
		else if (cumap->cur == 3) {
			float lum = rgb_to_bw(cumap->sample);
			glColor3ub(240, 240, 240);
			
			glBegin(GL_LINES);
			glVertex2f(rect->xmin + zoomx * (lum - offsx), rect->ymin);
			glVertex2f(rect->xmin + zoomx * (lum - offsx), rect->ymax);
			glEnd();
		}
		else {
			if (cumap->cur == 0)
				glColor3ub(240, 100, 100);
			else if (cumap->cur == 1)
				glColor3ub(100, 240, 100);
			else
				glColor3ub(100, 100, 240);
			
			glBegin(GL_LINES);
			glVertex2f(rect->xmin + zoomx * (cumap->sample[cumap->cur] - offsx), rect->ymin);
			glVertex2f(rect->xmin + zoomx * (cumap->sample[cumap->cur] - offsx), rect->ymax);
			glEnd();
		}
	}

	/* the curve */
	glColor3ubv((unsigned char *)wcol->item);
	glEnable(GL_LINE_SMOOTH);
	glEnable(GL_BLEND);
	glBegin(GL_LINE_STRIP);
	
	if (cuma->table == NULL)
		curvemapping_changed(cumap, FALSE);
	cmp = cuma->table;
	
	/* first point */
	if ((cuma->flag & CUMA_EXTEND_EXTRAPOLATE) == 0) {
		glVertex2f(rect->xmin, rect->ymin + zoomy * (cmp[0].y - offsy));
	}
	else {
		fx = rect->xmin + zoomx * (cmp[0].x - offsx + cuma->ext_in[0]);
		fy = rect->ymin + zoomy * (cmp[0].y - offsy + cuma->ext_in[1]);
		glVertex2f(fx, fy);
	}
	for (a = 0; a <= CM_TABLE; a++) {
		fx = rect->xmin + zoomx * (cmp[a].x - offsx);
		fy = rect->ymin + zoomy * (cmp[a].y - offsy);
		glVertex2f(fx, fy);
	}
	/* last point */
	if ((cuma->flag & CUMA_EXTEND_EXTRAPOLATE) == 0) {
		glVertex2f(rect->xmax, rect->ymin + zoomy * (cmp[CM_TABLE].y - offsy));
	}
	else {
		fx = rect->xmin + zoomx * (cmp[CM_TABLE].x - offsx - cuma->ext_out[0]);
		fy = rect->ymin + zoomy * (cmp[CM_TABLE].y - offsy - cuma->ext_out[1]);
		glVertex2f(fx, fy);
	}
	glEnd();
	glDisable(GL_LINE_SMOOTH);
	glDisable(GL_BLEND);

	/* the points, use aspect to make them visible on edges */
	cmp = cuma->curve;
	glPointSize(3.0f);
	bglBegin(GL_POINTS);
	for (a = 0; a < cuma->totpoint; a++) {
		if (cmp[a].flag & CUMA_SELECT)
			UI_ThemeColor(TH_TEXT_HI);
		else
			UI_ThemeColor(TH_TEXT);
		fac[0] = rect->xmin + zoomx * (cmp[a].x - offsx);
		fac[1] = rect->ymin + zoomy * (cmp[a].y - offsy);
		bglVertex2fv(fac);
	}
	bglEnd();
	glPointSize(1.0f);
	
	/* restore scissortest */
	glScissor(scissor[0], scissor[1], scissor[2], scissor[3]);

	/* outline */
	glColor3ubv((unsigned char *)wcol->outline);
	fdrawbox(rect->xmin, rect->ymin, rect->xmax, rect->ymax);
}
Пример #4
0
void
drawimage(void)
{
    register short i;
    static int start, end, last;

    glutSetWindow(window);

    if (performance)
	start = glutGet(GLUT_ELAPSED_TIME);

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glPushMatrix();
    tbMatrix();

    for (i=0; i < TOTALBALLS; i++) {
	newpos[0] = balls[i].p[0];
	newpos[1] = balls[i].p[1];
	newpos[2] = balls[i].p[2];
	glLightfv(GL_LIGHT0 + i, GL_POSITION, newpos);
    }

    glCallList(wall_material);
    glEnable(GL_LIGHTING);
    drawbox();

    glEnable(GL_DEPTH_TEST);

    if (objecton)
    {
	glCallList(plane_material);
	glPushMatrix();
	glScalef(1.5, 1.5, 1.5);
	glRotatef(180.0, 0.0, 0.0, 1.0);
	if (spin)
	{
	    orx += 50;
	    ory += 50;
	}
	glRotatef(orx/10.0, 1.0, 0.0, 0.0);
	glRotatef(ory/10.0, 0.0, 1.0, 0.0);
	drawfastobj(obj);
	glPopMatrix();
    }

    glDisable(GL_LIGHTING);

    for (i=0; i < TOTALBALLS; i++) {
	if (lighton[i])
	{
	    glPushMatrix();
	    glTranslatef(balls[i].p[0],balls[i].p[1],balls[i].p[2]);
	    glColor3ubv(balls[i].color);
	    drawball();
	    glPopMatrix();
	}
    }

    glColor3f(1.0, 1.0, 1.0);
    if (performance) {
        if (end - last == 0) {
	    text(10, 73, 20, "unknown fps");
	} else {
	    text(10, 73, 20, "%.0f fps", 1.0 / ((end - last) / 1000.0));
	}
	last = start;
    }
    text(10, 43, 14, "Attenuation [%.2f]", fatt);
    text(10, 13, 14, "Tesselation [%3d]", wallgrid);


    glPopMatrix();
    glutSwapBuffers();

    if (performance)
	end = glutGet(GLUT_ELAPSED_TIME);
}
Пример #5
0
void drawConstraint(TransInfo *t)
{
	TransCon *tc = &(t->con);

	if (!ELEM(t->spacetype, SPACE_VIEW3D, SPACE_IMAGE))
		return;
	if (!(tc->mode & CON_APPLY))
		return;
	if (t->flag & T_USES_MANIPULATOR)
		return;
	if (t->flag & T_NO_CONSTRAINT)
		return;

	/* nasty exception for Z constraint in camera view */
	// TRANSFORM_FIX_ME
//	if((t->flag & T_OBJECT) && G.vd->camera==OBACT && G.vd->persp==V3D_CAMOB)
//		return;

	if (tc->drawExtra) {
		tc->drawExtra(t);
	}
	else {
		if (tc->mode & CON_SELECT) {
			float vec[3];
			char col2[3] = {255,255,255};
			int depth_test_enabled;

			convertViewVec(t, vec, (t->mval[0] - t->con.imval[0]), (t->mval[1] - t->con.imval[1]));
			add_v3_v3(vec, tc->center);

			drawLine(t, tc->center, tc->mtx[0], 'X', 0);
			drawLine(t, tc->center, tc->mtx[1], 'Y', 0);
			drawLine(t, tc->center, tc->mtx[2], 'Z', 0);

			glColor3ubv((GLubyte *)col2);

			depth_test_enabled = glIsEnabled(GL_DEPTH_TEST);
			if(depth_test_enabled)
				glDisable(GL_DEPTH_TEST);

			setlinestyle(1);
			glBegin(GL_LINE_STRIP);
				glVertex3fv(tc->center);
				glVertex3fv(vec);
			glEnd();
			setlinestyle(0);

			if(depth_test_enabled)
				glEnable(GL_DEPTH_TEST);
		}

		if (tc->mode & CON_AXIS0) {
			drawLine(t, tc->center, tc->mtx[0], 'X', DRAWLIGHT);
		}
		if (tc->mode & CON_AXIS1) {
			drawLine(t, tc->center, tc->mtx[1], 'Y', DRAWLIGHT);
		}
		if (tc->mode & CON_AXIS2) {
			drawLine(t, tc->center, tc->mtx[2], 'Z', DRAWLIGHT);
		}
	}
}
Пример #6
0
void R_DrawParticles (void)
{
	particle_t		*p, *kill;
	float			grav;
	int				i;
	float			time2, time3;
	float			time1;
	float			dvel;
	float			frametime;
#ifdef USE_OPENGLES
	float*			pPos = gVertexBuffer;
	unsigned char*	pColor = (unsigned char*) gColorBuffer;
	unsigned char*  pUV = (unsigned char*) gTexCoordBuffer;
	int				particleIndex = 0;
	int				maxParticleIndex = (int) sizeof(gVertexBuffer) / (sizeof(float) * 3) - 3;
#endif
#ifdef GLQUAKE
	vec3_t			up, right;
	float			scale;

	GL_Bind(particletexture);

	glEnable (GL_BLEND);
	glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);

#ifdef USE_OPENGLES
	glEnableClientState(GL_COLOR_ARRAY);
	glVertexPointer(3, GL_FLOAT, 0, gVertexBuffer);
	glTexCoordPointer(2, GL_BYTE, 0, gTexCoordBuffer);
	glColorPointer(4, GL_UNSIGNED_BYTE, 0, gColorBuffer);
	glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_FASTEST);
#else
	glBegin (GL_TRIANGLES);
#endif

	VectorScale (vup, 1.5, up);
	VectorScale (vright, 1.5, right);
#else
	D_StartParticles ();

	VectorScale (vright, xscaleshrink, r_pright);
	VectorScale (vup, yscaleshrink, r_pup);
	VectorCopy (vpn, r_ppn);
#endif
	frametime = cl.time - cl.oldtime;
	time3 = frametime * 15;
	time2 = frametime * 10; // 15;
	time1 = frametime * 5;
	grav = frametime * sv_gravity.value * 0.05;
	dvel = 4*frametime;

	for ( ;; )
	{
		kill = active_particles;
		if (kill && kill->die < cl.time)
		{
			active_particles = kill->next;
			kill->next = free_particles;
			free_particles = kill;
			continue;
		}
		break;
	}

	for (p=active_particles ; p ; p=p->next)
	{
		for ( ;; )
		{
			kill = p->next;
			if (kill && kill->die < cl.time)
			{
				p->next = kill->next;
				kill->next = free_particles;
				free_particles = kill;
				continue;
			}
			break;
		}

#ifdef GLQUAKE
		// hack a scale up to keep particles from disapearing
		scale = (p->org[0] - r_origin[0])*vpn[0] + (p->org[1] - r_origin[1])*vpn[1]
			+ (p->org[2] - r_origin[2])*vpn[2];
		if (scale < 20)
			scale = 1;
		else
			scale = 1 + scale * 0.004;
#ifdef USE_OPENGLES

		if(particleIndex >= maxParticleIndex)
		{
			glDrawArrays(GL_TRIANGLES, 0, particleIndex);
			particleIndex = 0;
			pPos = gVertexBuffer;
			pColor = (unsigned char*) gColorBuffer;
			pUV = (unsigned char*) gTexCoordBuffer;
		}

		memcpy(pColor, (byte *)&d_8to24table[(int)p->color], 3);
		pColor[3] = 255;
		pColor += 4;
		*pUV++ = 0;
		*pUV++ = 0;
		*pPos++ = p->org[0];
		*pPos++ = p->org[1];
		*pPos++ = p->org[2];

		memcpy(pColor, (byte *)&d_8to24table[(int)p->color], 3);
		pColor[3] = 255;
		pColor += 4;
		*pUV++ = 1;
		*pUV++ = 0;
		*pPos++ = p->org[0] + up[0]*scale;
		*pPos++ = p->org[1] + up[1]*scale;
		*pPos++ = p->org[2] + up[2]*scale;

		memcpy(pColor, (byte *)&d_8to24table[(int)p->color], 3);
		pColor[3] = 255;
		pColor += 4;
		*pUV++ = 0;
		*pUV++ = 1;
		*pPos++ = p->org[0] + right[0]*scale;
		*pPos++ = p->org[1] + right[1]*scale;
		*pPos++ = p->org[2] + right[2]*scale;

		particleIndex += 3;

#else
		glColor3ubv ((byte *)&d_8to24table[(int)p->color]);
		glTexCoord2f (0,0);
		glVertex3fv (p->org);
		glTexCoord2f (1,0);
		glVertex3f (p->org[0] + up[0]*scale, p->org[1] + up[1]*scale, p->org[2] + up[2]*scale);
		glTexCoord2f (0,1);
		glVertex3f (p->org[0] + right[0]*scale, p->org[1] + right[1]*scale, p->org[2] + right[2]*scale);
#endif // !USE_OPENGLES
#else
		D_DrawParticle (p);
#endif
		p->org[0] += p->vel[0]*frametime;
		p->org[1] += p->vel[1]*frametime;
		p->org[2] += p->vel[2]*frametime;

		switch (p->type)
		{
		case pt_static:
			break;
		case pt_fire:
			p->ramp += time1;
			if (p->ramp >= 6)
				p->die = -1;
			else
				p->color = ramp3[(int)p->ramp];
			p->vel[2] += grav;
			break;

		case pt_explode:
			p->ramp += time2;
			if (p->ramp >=8)
				p->die = -1;
			else
				p->color = ramp1[(int)p->ramp];
			for (i=0 ; i<3 ; i++)
				p->vel[i] += p->vel[i]*dvel;
			p->vel[2] -= grav;
			break;

		case pt_explode2:
			p->ramp += time3;
			if (p->ramp >=8)
				p->die = -1;
			else
				p->color = ramp2[(int)p->ramp];
			for (i=0 ; i<3 ; i++)
				p->vel[i] -= p->vel[i]*frametime;
			p->vel[2] -= grav;
			break;

		case pt_blob:
			for (i=0 ; i<3 ; i++)
				p->vel[i] += p->vel[i]*dvel;
			p->vel[2] -= grav;
			break;

		case pt_blob2:
			for (i=0 ; i<2 ; i++)
				p->vel[i] -= p->vel[i]*dvel;
			p->vel[2] -= grav;
			break;

		case pt_grav:
#ifdef QUAKE2
			p->vel[2] -= grav * 20;
			break;
#endif
		case pt_slowgrav:
			p->vel[2] -= grav;
			break;
	    default:
	        break;
		}
	}

#ifdef GLQUAKE
#ifdef USE_OPENGLES
	glDrawArrays(GL_TRIANGLES, 0, particleIndex);
	glDisableClientState(GL_COLOR_ARRAY);
	glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
#else
	glEnd ();
#endif
	glDisable (GL_BLEND);
	glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
#else
	D_EndParticles ();
#endif
}
Пример #7
0
void R_DrawSkyChain (void) {
    msurface_t *fa;
    extern cvar_t gl_fogsky;
    if (!skychain)
        return;

    GL_DisableMultitexture();

    if (gl_fogenable.value && gl_fogsky.value)
        glEnable(GL_FOG);
    if (r_fastsky.value || cl.worldmodel->bspversion == HL_BSPVERSION) {
        glDisable (GL_TEXTURE_2D);

        glColor3ubv (r_skycolor.color);

        for (fa = skychain; fa; fa = fa->texturechain)
            EmitFlatPoly (fa);

        glEnable (GL_TEXTURE_2D);
        glColor3ubv (color_white);
    } else {
        if (gl_mtexable) {
            glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
            GL_Bind (solidskytexture);

            GL_EnableMultitexture();
            glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL);
            GL_Bind (alphaskytexture);

            speedscale = r_refdef2.time * 8;
            speedscale -= (int) speedscale & ~127;
            speedscale2 = r_refdef2.time * 16;
            speedscale2 -= (int) speedscale2 & ~127;

            for (fa = skychain; fa; fa = fa->texturechain)
                EmitSkyPolys (fa, true);

            GL_DisableMultitexture();
            glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
        } else {
            GL_Bind(solidskytexture);
            speedscale = r_refdef2.time * 8;
            speedscale -= (int) speedscale & ~127;

            for (fa = skychain; fa; fa = fa->texturechain)
                EmitSkyPolys (fa, false);

            glEnable (GL_BLEND);
            GL_Bind (alphaskytexture);

            speedscale = r_refdef2.time * 16;
            speedscale -= (int) speedscale & ~127;

            for (fa = skychain; fa; fa = fa->texturechain)
                EmitSkyPolys (fa, false);

            glDisable (GL_BLEND);
        }
    }

    if (gl_fogenable.value && gl_fogsky.value)
        glDisable(GL_FOG);

    skychain = NULL;
    skychain_tail = &skychain;
}
Пример #8
0
void ccRenderingTools::DrawColorRamp(const CC_DRAW_CONTEXT& context)
{
	const ccScalarField* sf = context.sfColorScaleToDisplay;
	if (!sf || !sf->getColorScale())
		return;

//#define USE_OLD_SCALE_RENDERING
#ifndef USE_OLD_SCALE_RENDERING

	ccGLWindow* win = static_cast<ccGLWindow*>(context._win);
	if (!win)
		return;

	bool logScale = sf->logScale();
	bool symmetricalScale = sf->symmetricalScale();
	bool alwaysShowZero = sf->isZeroAlwaysShown();
	
	//set of particular values
	//DGM: we work with doubles for maximum accuracy
	std::set<double> keyValues;
	if (!logScale)
	{
		keyValues.insert(sf->displayRange().min());
		keyValues.insert(sf->displayRange().start());
		keyValues.insert(sf->displayRange().stop());
		keyValues.insert(sf->displayRange().max());
		keyValues.insert(sf->saturationRange().min());
		keyValues.insert(sf->saturationRange().start());
		keyValues.insert(sf->saturationRange().stop());
		keyValues.insert(sf->saturationRange().max());

		if (symmetricalScale)
			keyValues.insert(-sf->saturationRange().max());

		if (alwaysShowZero)
			keyValues.insert(0.0);
	}
	else
	{
		ScalarType minDisp = sf->displayRange().min();
		ScalarType maxDisp = sf->displayRange().max();
		ConvertToLogScale(minDisp,maxDisp);
		keyValues.insert(minDisp);
		keyValues.insert(maxDisp);

		ScalarType startDisp = sf->displayRange().start();
		ScalarType stopDisp = sf->displayRange().stop();
		ConvertToLogScale(startDisp,stopDisp);
		keyValues.insert(startDisp);
		keyValues.insert(stopDisp);

		keyValues.insert(sf->saturationRange().min());
		keyValues.insert(sf->saturationRange().start());
		keyValues.insert(sf->saturationRange().stop());
		keyValues.insert(sf->saturationRange().max());
	}

	//Internally, the elements in a set are already sorted
	//std::sort(keyValues.begin(),keyValues.end());

	if (!sf->areNaNValuesShownInGrey())
	{
		//remove 'hidden' values
		if (!logScale)
		{
			for (std::set<double>::iterator it = keyValues.begin(); it != keyValues.end(); )
			{
				if (!sf->displayRange().isInRange(static_cast<ScalarType>(*it)) && (!alwaysShowZero || *it != 0)) //we keep zero if the user has explicitely asked for it!
				{
					std::set<double>::iterator toDelete = it;
					++it;
					keyValues.erase(toDelete);
				}
				else
				{
					++it;
				}
		}
      }
		else
		{
			//convert actual display range to log scale
			//(we can't do the opposite, otherwise we get accuracy/round-off issues!)
			ScalarType dispMin = sf->displayRange().start();
			ScalarType dispMax = sf->displayRange().stop();
			ConvertToLogScale(dispMin,dispMax);

			for (std::set<double>::iterator it = keyValues.begin(); it != keyValues.end(); )
			{
				if (*it >= dispMin && *it <= dispMax)
				{
					++it;
				}
				else
				{
					std::set<double>::iterator toDelete = it;
					++it;
					keyValues.erase(toDelete);
				}
			}
		}
	}

	//Font metrics for proper display of labels!
	QFontMetrics strMetrics(win->font());

	//default color: text color
	const unsigned char* textColor = ccGui::Parameters().textDefaultCol;

	//histogram?
	const::ccScalarField::Histogram histogram = sf->getHistogram();
	bool showHistogram = (ccGui::Parameters().colorScaleShowHistogram && !logScale && histogram.maxValue != 0 && histogram.size() > 1);

	//display area
	const int strHeight = strMetrics.height();
	const int scaleWidth = ccGui::Parameters().colorScaleRampWidth;
	const int scaleMaxHeight = (keyValues.size() > 1 ? std::max(context.glH-120,2*strHeight) : scaleWidth); //if 1 value --> we draw a cube

	//centered orthoprojective view (-halfW,-halfH,halfW,halfH)
	int halfW = (context.glW>>1);
	int halfH = (context.glH>>1);

	//top-right corner of the scale ramp
	const int xShift = 20 + (showHistogram ? scaleWidth/2 : 0);
	const int yShift = halfH-scaleMaxHeight/2;

	glPushAttrib(GL_LINE_BIT | GL_DEPTH_BUFFER_BIT);
	glEnable(GL_LINE_SMOOTH);
	glDisable(GL_DEPTH_TEST);
	
	std::vector<double> sortedKeyValues(keyValues.begin(),keyValues.end());
	double maxRange = sortedKeyValues.back()-sortedKeyValues.front();

	//const colorType* lineColor = ccColor::white;
	////clear background?
	//if (ccGui::Parameters().backgroundCol[0] + ccGui::Parameters().backgroundCol[1] + ccGui::Parameters().backgroundCol[2] > 3*128)
	//	lineColor = ccColor::black;
	const colorType* lineColor = textColor;

	//display color ramp
	{
		//(x,y): current display area coordinates (top-left corner)
		int x = halfW-xShift-scaleWidth;
		int y = halfH-yShift-scaleMaxHeight;

		if (keyValues.size() > 1)
		{
			int histoStart = x+scaleWidth+std::min(std::max(scaleWidth/8,3),15);

			glLineWidth(1.0f);
			glBegin(GL_LINES);
			for (int j=0; j<scaleMaxHeight; ++j)
			{
				double value = sortedKeyValues.front() + ((double)j * maxRange) / (double)scaleMaxHeight;
				if (logScale)
					value = exp(value*c_log10);
				const colorType* col = sf->getColor(static_cast<ScalarType>(value));
				glColor3ubv(col ? col : ccColor::lightGrey);

				glVertex2i(x,y+j);
				glVertex2i(x+scaleWidth,y+j);
				
				if (showHistogram)
				{
					double bind = (value-(double)sf->displayRange().min())*(double)(histogram.size()-1)/(double)sf->displayRange().maxRange();
					int bin = static_cast<int>(floor(bind));
					
					double hVal = 0.0;
					if (bin >= 0 && bin < (int)histogram.size()) //in symmetrical case we can get values outside of the real SF range
					{
						hVal = (double)histogram[bin];
						if (bin+1 < (int)histogram.size())
						{
							//linear interpolation
							double alpha = bind-(double)bin;
							hVal = (1.0-alpha) * hVal + alpha * (double)histogram[bin+1];
						}
					}

					int xSpan = std::max(static_cast<int>(hVal / (double)histogram.maxValue * (double)(scaleWidth/2)),1);
					glVertex2i(histoStart,y+j);
					glVertex2i(histoStart+xSpan,y+j);
				}
			}
			glEnd();
		}
		else
		{
			//if there's a unique (visible) scalar value, we only draw a square!
			double value = sortedKeyValues.front();
			if (logScale)
				value = exp(value*c_log10);
			const colorType* col = sf->getColor(value);
			glColor3ubv(col ? col : ccColor::lightGrey);
			glBegin(GL_POLYGON);
			glVertex2i(x,y);
			glVertex2i(x+scaleWidth,y);
			glVertex2i(x+scaleWidth,y+scaleMaxHeight-1);
			glVertex2i(x,y+scaleMaxHeight-1);
			glEnd();
		}

		//scale border
		glLineWidth(2.0);
		glColor3ubv(lineColor);
		glBegin(GL_LINE_LOOP);
		glVertex2i(x,y);
		glVertex2i(x+scaleWidth,y);
		glVertex2i(x+scaleWidth,y+scaleMaxHeight);
		glVertex2i(x,y+scaleMaxHeight);
		glEnd();
	}

	//display labels
	{
		//list of labels to draw
		vlabelSet drawnLabels;

		//add first label
		drawnLabels.push_back(vlabel(0,0,strHeight,sortedKeyValues.front()));

		if (keyValues.size() > 1)
		{
			//add last label
			drawnLabels.push_back(vlabel(scaleMaxHeight,scaleMaxHeight-strHeight,scaleMaxHeight,sortedKeyValues.back()));
		}

		//we try to display the other keyPoints (if any)
		if (keyValues.size() > 2)
		{
			assert(maxRange > 0.0);
			const int minGap = strHeight;
			for (size_t i=1; i<keyValues.size()-1; ++i)
			{
				int yScale = static_cast<int>((sortedKeyValues[i]-sortedKeyValues[0]) * (double)scaleMaxHeight / maxRange);
				vlabelPair nLabels = GetVLabelsAround(yScale,drawnLabels);

				assert(nLabels.first != drawnLabels.end() && nLabels.second != drawnLabels.end());
				if (	(nLabels.first == drawnLabels.end() || nLabels.first->yMax <= yScale - minGap)
					&&	(nLabels.second == drawnLabels.end() || nLabels.second->yMin >= yScale + minGap))
				{
					//insert it at the right place (so as to keep a sorted list!)
					drawnLabels.insert(nLabels.second,vlabel(yScale,yScale-strHeight/2,yScale+strHeight/2,sortedKeyValues[i]));
				}
			}
		}

		//now we recursively display labels where we have some rool left
		if (drawnLabels.size() > 1)
		{
			const int minGap = strHeight*2;

			size_t drawnLabelsBefore = 0; //just to init the loop
			size_t drawnLabelsAfter = drawnLabels.size(); 

			//proceed until no more label can be inserted
			while (drawnLabelsAfter > drawnLabelsBefore)
			{
				drawnLabelsBefore = drawnLabelsAfter;

				vlabelSet::iterator it1 = drawnLabels.begin();
				vlabelSet::iterator it2 = it1; it2++;
				for (; it2 != drawnLabels.end(); ++it2)
				{
					if (it1->yMax + 2*minGap < it2->yMin)
					{
						//insert label
						double val = (it1->val + it2->val)/2.0;
						int yScale = static_cast<int>((val-sortedKeyValues[0]) * (double)scaleMaxHeight / maxRange);

						//insert it at the right place (so as to keep a sorted list!)
						drawnLabels.insert(it2,vlabel(yScale,yScale-strHeight/2,yScale+strHeight/2,val));
					}
					it1 = it2;
				}

				drawnLabelsAfter = drawnLabels.size();
			}
		}

		//display labels

		//Some versions of Qt seem to need glColorf instead of glColorub! (see https://bugreports.qt-project.org/browse/QTBUG-6217)
		glColor3f((float)textColor[0]/255.0f,(float)textColor[1]/255.0f,(float)textColor[2]/255.0f);

		//Scalar field name
		const char* sfName = sf->getName();
		if (sfName)
		{
			//QString sfTitle = QString("[%1]").arg(sfName);
			QString sfTitle(sfName);
			if (logScale)
				sfTitle += QString("[Log scale]");
			//we leave some (vertical) space for the top-most label!
			win->displayText(sfTitle, context.glW-xShift, context.glH-yShift+strMetrics.height(), ccGLWindow::ALIGN_HRIGHT | ccGLWindow::ALIGN_VTOP);
		}

		//precision (same as color scale)
		const unsigned precision = ccGui::Parameters().displayedNumPrecision;
		//format
		const char format = (sf->logScale() ? 'E' : 'f');
		//tick
		const int tickSize = 4;

		//for labels
		const int x = context.glW-xShift-scaleWidth-2*tickSize-1;
		const int y = context.glH-yShift-scaleMaxHeight;
		//for ticks
		const int xTick = halfW-xShift-scaleWidth-tickSize-1;
		const int yTick = halfH-yShift-scaleMaxHeight;

		for (vlabelSet::iterator it = drawnLabels.begin(); it != drawnLabels.end(); ++it)
		{
			vlabelSet::iterator itNext = it; itNext++;
			//position
			unsigned char align = ccGLWindow::ALIGN_HRIGHT;
			if (it == drawnLabels.begin())
				align |= ccGLWindow::ALIGN_VTOP;
			else if (itNext == drawnLabels.end())
				align |= ccGLWindow::ALIGN_VBOTTOM;
			else
				align |= ccGLWindow::ALIGN_VMIDDLE;

			double value = it->val;
			if (logScale)
				value = exp(value*c_log10);

			win->displayText(QString::number(value,format,precision), x, y+it->yPos, align);
			glBegin(GL_LINES);
			glVertex2f(xTick,yTick+it->yPos);
			glVertex2f(xTick+tickSize,yTick+it->yPos);
			glEnd();
		}
	}

	glPopAttrib();

#else

	double minVal = sf->getMin();
	double minDisplayed = sf->displayRange().start();
	double minSaturation = sf->saturationRange().start();
	double maxSaturation = sf->saturationRange().stop();
	double maxDisplayed = sf->displayRange().stop();
	double maxVal = sf->getMax();

	bool strictlyPositive = (minVal >= 0);
	bool symmetricalScale = sf->symmetricalScale();
	bool logScale = sf->logScale();

	const int c_cubeSize = ccGui::Parameters().colorScaleRampWidth;
	const int c_defaultSpace = 4;

	//this vector stores the values that will be "represented" by the scale
	//they will be automatically displayed in a regular "pace"
	std::vector<ScaleElement> theScaleElements;
	std::vector<double> theCubeEquivalentDist; //to deduce its color!

	int maxNumberOfCubes = (int)(floor((float)(context.glH-120)/(float)(c_cubeSize+2*c_defaultSpace)));

	ccColorScale::Shared colorScale = context.sfColorScaleToDisplay->getColorScale();
	if (!colorScale)
	{
		assert(false);
		return;
	}
	unsigned colorRampSteps = context.sfColorScaleToDisplay->getColorRampSteps();

	//first we fill the two vectors below with scale "values"
	if (strictlyPositive || !symmetricalScale) //only positive values
	{
		bool dispZero = minDisplayed>0.0 && strictlyPositive;
		bool dispMinVal = false;//(minVal<minDisplayed);
		bool dispMinDispVal = true;
		bool dispMinSat = (minSaturation>minDisplayed && minSaturation<maxSaturation);
		bool dispMaxSat = (maxSaturation>=minSaturation && maxSaturation<maxDisplayed);
		bool dispMaxDispVal = (maxDisplayed>minDisplayed && maxDisplayed<maxVal);
		bool dispMaxVal = true;

		int addedCubes = int(dispZero) + int(dispMinVal) + int(dispMinDispVal) + int(dispMinSat) + int(dispMaxSat) + int(dispMaxDispVal) + int(dispMaxVal);

		//not enough room for display!
		if (maxNumberOfCubes < addedCubes)
			return;

		//number of cubes available for ramp display
		int numberOfCubes = std::min<int>(maxNumberOfCubes-addedCubes,colorRampSteps);

		double startValue = minVal; //we want it to be the same color as 'minVal' even if we start at '0'
		if (dispZero)
			theScaleElements.push_back(ScaleElement(0.0,true,true));

		if (dispMinVal)
		{
			//precedent cube color
			if (!theScaleElements.empty())
				theCubeEquivalentDist.push_back(startValue);

			theScaleElements.push_back(ScaleElement(minVal,true,dispMinDispVal || dispMinSat));
			startValue = minVal;
		}

		if (dispMinDispVal)
		{
			//precedent cube color
			if (!theScaleElements.empty())
				theCubeEquivalentDist.push_back(startValue);

			theScaleElements.push_back(ScaleElement(minDisplayed,true,dispMinSat));
			startValue = minDisplayed;
		}

		if (dispMinSat)
		{
			//precedent cube color
			if (!theScaleElements.empty())
				theCubeEquivalentDist.push_back(startValue);

			theScaleElements.push_back(ScaleElement(minSaturation));
			startValue = minSaturation;
		}

		//the actual color ramp
		if (numberOfCubes>0 && minSaturation<maxSaturation && minDisplayed<maxDisplayed)
		{
			double endValue = (dispMaxSat ? maxSaturation : maxDisplayed);
			double intervale = (endValue-startValue)/(double)numberOfCubes;
			double firstValue = startValue;

			if (logScale)
			{
				double endValueLog = log10(std::max<double>(ZERO_TOLERANCE,fabs(endValue)));
				double startValueLog = log10(std::max<double>(ZERO_TOLERANCE,fabs(startValue)));
				intervale = (endValueLog-startValueLog)/(double)numberOfCubes;
				firstValue = startValueLog;
			}

			if (intervale < ZERO_TOLERANCE)
			{
				//finally, we won't draw this ramp!
				theScaleElements.back().condensed = true;
			}
			else
			{
				if (logScale)
				{
					for (int i=0;i<numberOfCubes;++i)
					{
						double val = firstValue+intervale*static_cast<double>(i);
						double logVal = val+intervale*0.5;
						theCubeEquivalentDist.push_back(exp(logVal*log(10.0)));

						theScaleElements.push_back(ScaleElement(exp((val+intervale)*log(10.0)),true,false));
					}
				}
				else
				{
					for (int i=0;i<numberOfCubes;++i)
					{
						double val = firstValue+intervale*static_cast<double>(i);

						theCubeEquivalentDist.push_back(val+intervale*0.5);
						theScaleElements.push_back(ScaleElement(val+intervale,true,false));
					}
				}
			}
		}

		if (dispMaxSat && dispMaxDispVal)
		{
			theCubeEquivalentDist.push_back(maxSaturation);
			theScaleElements.back().condensed = true;
			theScaleElements.push_back(ScaleElement(maxDisplayed, true, true));
		}

		if ((dispMaxSat || dispMaxDispVal) && dispMaxVal)
		{
			theCubeEquivalentDist.push_back(maxVal);
			theScaleElements.back().condensed = true;
			theScaleElements.push_back(ScaleElement(maxVal));
		}
	}
	else //both positive and negative values
	{
		//TODO FIXME!!!

		//if the ramp should be symmetrical
		bool symmetry = ccGui::Parameters().colorScaleAlwaysSymmetrical;
		if (symmetry)
		{
			//we display the color ramp between -maxDisp and +maxDisp
			double maxDisp = std::max(-minVal,maxVal);

			bool dispZero = true;
			bool dispMinSat = (minSaturation>0.0);
			bool dispMaxSat = (maxSaturation>minSaturation && maxSaturation<maxDisp);
			bool dispMaxVal = true;

			int addedCubes = 2 * (int(dispZero && dispMinSat) + int(dispMaxSat && dispMaxVal));

			//not enough room for display!
			if (maxNumberOfCubes < addedCubes)
				return;

			//number of cubes available for ramp display
			int numberOfCubes = std::min<int>((maxNumberOfCubes-addedCubes)/2,colorRampSteps);

			//1st section: -maxDisp
			double startValue = -maxDisp;
			if (dispMaxVal)
				theScaleElements.push_back(ScaleElement(-maxDisp,true,dispMaxSat));

			//2nd section: -maxSaturation
			if (dispMaxSat)
			{
				//precedent cube color
				if (!theScaleElements.empty())
					theCubeEquivalentDist.push_back(startValue);
				theScaleElements.push_back(ScaleElement(-maxSaturation));
				startValue = -maxSaturation;
			}

			//3rd section: the real color ramp (negative part)
			if (numberOfCubes>1)
			{
				double endValue = (dispMinSat ? -minSaturation : 0.0);
				double intervale = (endValue-startValue)/(double)numberOfCubes;
				double firstValue = startValue;

				if (logScale)
				{
					double endValueLog = log10(std::max<double>(ZERO_TOLERANCE,fabs(-endValue)));
					double startValueLog = log10(std::max<double>(ZERO_TOLERANCE,fabs(-startValue)));
					intervale = -(endValueLog-startValueLog)/(double)numberOfCubes;
					firstValue = startValueLog;
				}

				if (intervale < ZERO_TOLERANCE)
				{
					//finally, we won't draw this ramp!
					theScaleElements.back().condensed = true;
				}
				else
				{
					if (logScale)
					{
						for (int i=0;i<numberOfCubes-1;++i)
						{
							double logVal = firstValue-intervale*0.5;
							theCubeEquivalentDist.push_back(-exp(logVal*log(10.0)));
							firstValue -= intervale;
							//if (i==0 && firstValue>maxVal) //specific case: all values in the tail
							//	theScaleElements.push_back(ScaleElement(maxVal,true));
							//else
								theScaleElements.push_back(ScaleElement(-exp(firstValue*log(10.0)),true));
						}
					}
					else
					{
						for (int i=0;i<numberOfCubes-1;++i)
						{
							theCubeEquivalentDist.push_back(firstValue + intervale*0.5);
							firstValue += intervale;
							//if (i==0 && firstValue>maxVal) //specific case: all values in the tail
							//	theScaleElements.push_back(ScaleElement(maxVal,true));
							//else
								theScaleElements.push_back(ScaleElement(firstValue,true));
						}
					}
				}
			}

			//4th section: -minSaturation
			if (dispMinSat)
			{
				theCubeEquivalentDist.push_back(-minSaturation);
				theScaleElements.push_back(ScaleElement(-minSaturation, true, true));
			}

			//5th section: zero
			if (dispZero)
			{
				theCubeEquivalentDist.push_back(0.5*theCubeEquivalentDist.back());
				theScaleElements.push_back(ScaleElement(0, true, dispMinSat));
			}

			//6th section: minSaturation
			if (dispMinSat)
			{
				theCubeEquivalentDist.push_back(0.0);
				theScaleElements.push_back(ScaleElement(minSaturation));
			}

			//7th section: the real color ramp (positive part)
			if (numberOfCubes>1)
			{
				double intervale = (maxSaturation-minSaturation)/(double)numberOfCubes;
				double firstValue = minSaturation;

				if (logScale)
				{
					double endValueLog = log10(std::max<double>(ZERO_TOLERANCE,fabs(maxSaturation)));
					double startValueLog = log10(std::max<double>(ZERO_TOLERANCE,fabs(minSaturation)));
					intervale = (endValueLog-startValueLog)/(double)numberOfCubes;
					firstValue = startValueLog;
				}

				if (intervale < ZERO_TOLERANCE)
				{
					//finally, we won't draw this ramp!
					theScaleElements.back().condensed = true;
				}
				else
				{
					if (logScale)
					{
						for (int i=0;i<numberOfCubes-1;++i)
						{
							double logVal = firstValue+intervale*0.5;
							theCubeEquivalentDist.push_back(exp(logVal*log(10.0)));
							firstValue += intervale;
							//if (i+2==numberOfCubes && firstValue<minVal) //specific case: all values in the head
							//	theScaleElements.push_back(ScaleElement(minVal,true));
							//else
								theScaleElements.push_back(ScaleElement(exp(firstValue*log(10.0)),true));
						}
					}
					else
					{
						for (int i=0;i<numberOfCubes-1;++i)
						{
							theCubeEquivalentDist.push_back(firstValue + intervale*0.5);
							firstValue += intervale;
							//if (i+2==numberOfCubes && firstValue<minVal) //specific case: all values in the head
							//	theScaleElements.push_back(ScaleElement(minVal,true));
							//else
								theScaleElements.push_back(ScaleElement(firstValue,true));
						}
					}
				}
			}

			//8th section: maxSaturation
			if (dispMaxSat)
			{
				theCubeEquivalentDist.push_back(maxSaturation);
				theScaleElements.push_back(ScaleElement(maxSaturation,true,true));
			}

			//9th section: maxVal
			if (dispMaxVal)
			{
				theCubeEquivalentDist.push_back(maxDisp);
				theScaleElements.push_back(ScaleElement(maxDisp));
			}
		}
		else
		{
			//TODO
		}
	}

	if (theScaleElements.empty())
		return;

	//scale height
	unsigned n = (unsigned)theScaleElements.size();
	//assert(theCubeEquivalentDist.size()+(dispZero ? 1 : 0)==n);
	int scaleHeight = (c_cubeSize+2*c_defaultSpace)*n;

	const int xShift = c_cubeSize+20;
	const int yShift = 40;

	//centered orthoprojective view (-halfW,-halfH,halfW,halfH)
	int halfW = (context.glW>>1);
	int halfH = (context.glH>>1);

	/*** now we can render the scale ***/

	//(x,y): current display area coordinates
	int x = halfW-xShift;
	int y = yShift-scaleHeight/2;

	//first horizontal delimiter
	glBegin(GL_LINES);
	glVertex2i(x,y);
	glVertex2i(x+c_cubeSize,y);
	glEnd();

	ccGLWindow* win = (ccGLWindow*)context._win;
	assert(win);

	if (theScaleElements[0].textDisplayed)
		win->displayText(QString::number(theScaleElements[0].value, logScale ? 'E' : 'f', ccGui::Parameters().displayedNumPrecision), halfW+x-5, y+halfH, ccGLWindow::ALIGN_HRIGHT | ccGLWindow::ALIGN_VMIDDLE);

	const colorType* lineColor = ccColor::white;
	//clear background?
	if (ccGui::Parameters().backgroundCol[0] + ccGui::Parameters().backgroundCol[1] + ccGui::Parameters().backgroundCol[2] > 3*128)
		lineColor = ccColor::black;

	for (int i=0;i+1<(int)n;++i)
	{
		y += c_defaultSpace;

		//a colored cube
		//d = 0.5*(theScaleElements[i].value + theScaleElements[i+1].value);
		double d = theCubeEquivalentDist[i];

		const colorType* col = sf->getColor(d);

		if (i==0 && theScaleElements[i].condensed)
		{
			//DOWN ARROW

			glBegin(GL_LINE_LOOP);
			glColor3ubv(lineColor);
			glVertex2i(x,y+c_cubeSize);
			glVertex2i(x+c_cubeSize,y+c_cubeSize);
			glVertex2i(x+c_cubeSize/2,y);
			glEnd();

			if (col)
			{
				glBegin(GL_POLYGON);
				glColor3ubv(col);
				glVertex2i(x,y+c_cubeSize);
				glVertex2i(x+c_cubeSize,y+c_cubeSize);
				glVertex2i(x+c_cubeSize/2,y);
				glEnd();
			}
		}
		else if (i+2 == (int)n && theScaleElements[i].condensed)
		{
			//UP ARROW

			glBegin(GL_LINE_LOOP);
			glColor3ubv(lineColor);
			glVertex2i(x,y);
			glVertex2i(x+c_cubeSize,y);
			glVertex2i(x+c_cubeSize/2,y+c_cubeSize);
			glEnd();

			if (col)
			{
				glBegin(GL_POLYGON);
				glColor3ubv(col);
				glVertex2i(x,y+1);
				glVertex2i(x+c_cubeSize,y+1);
				glVertex2i(x+c_cubeSize/2,y+c_cubeSize);
				glEnd();
			}
		}
		else //RECTANGLE
		{
			if (!theScaleElements[i].condensed)
			{
				//simple box
				if (col)
				{
					glBegin(GL_POLYGON);
					glColor3ubv(col);
					glVertex2i(x,y);
					glVertex2i(x+c_cubeSize,y);
					glVertex2i(x+c_cubeSize,y+c_cubeSize);
					glVertex2i(x,y+c_cubeSize);
					glEnd();
				}

				glBegin(GL_LINE_LOOP);
				glColor3ubv(lineColor);
				glVertex2i(x,y);
				glVertex2i(x+c_cubeSize,y);
				glVertex2i(x+c_cubeSize,y+c_cubeSize);
				glVertex2i(x,y+c_cubeSize);
				glEnd();
			}
			else
			{
				float third = (float)c_cubeSize *0.8/3.0f;
				//slashed box
				if (col)
				{
					glColor3ubv(col);

					glBegin(GL_POLYGON);
					glVertex2i(x,y);
					glVertex2f(x,(float)y+third);
					glVertex2f(x+c_cubeSize,(float)y+2.0f*third);
					glVertex2i(x+c_cubeSize,y);
					glEnd();

					glBegin(GL_POLYGON);
					glVertex2i(x,y+c_cubeSize);
					glVertex2i(x+c_cubeSize,y+c_cubeSize);
					glVertex2f(x+c_cubeSize,(float)(y+c_cubeSize)-third);
					glVertex2f(x,(float)(y+c_cubeSize)-2.0*third);
					glEnd();
				}

				glColor3ubv(lineColor);
				glBegin(GL_LINE_LOOP);
				glVertex2i(x,y);
				glVertex2f(x,(float)y+third);
				glVertex2f(x+c_cubeSize,(float)y+2.0f*third);
				glVertex2i(x+c_cubeSize,y);
				glEnd();

				glBegin(GL_LINE_LOOP);
				glVertex2i(x,y+c_cubeSize);
				glVertex2i(x+c_cubeSize,y+c_cubeSize);
				glVertex2f(x+c_cubeSize,(float)(y+c_cubeSize)-third);
				glVertex2f(x,(float)(y+c_cubeSize)-2.0*third);
				glEnd();
			}
		}

		y += c_cubeSize+c_defaultSpace;

		//separator
		glColor3ubv(lineColor);
		glBegin(GL_LINES);
		glVertex2i(x,y);
		glVertex2i(x+c_cubeSize,y);
		glEnd();

		if (theScaleElements[i+1].textDisplayed)
		{
			double dispValue = theScaleElements[i+1].value;
			win->displayText(QString::number(dispValue,logScale ? 'E' : 'f',ccGui::Parameters().displayedNumPrecision), halfW+x-5, y+halfH, ccGLWindow::ALIGN_HRIGHT | ccGLWindow::ALIGN_VMIDDLE);
		}
	}

	//Scale title
	const char* sfName = context.sfColorScaleToDisplay->getName();
	if (sfName)
	{
		//QString sfTitle = QString("[%1]").arg(sfName);
		QString sfTitle(sfName);
		win->displayText(sfTitle, context.glW-c_cubeSize/2, (y+c_cubeSize)+halfH, ccGLWindow::ALIGN_HRIGHT | ccGLWindow::ALIGN_VTOP);
	}

#endif
}
void RenderManagerGL2D::draw()
{
	glClear(GL_DEPTH_BUFFER_BIT);
	if (!mDrawGame)
		return;
		
	// Background
	glDisable(GL_ALPHA_TEST);
	glColor4f(1.0, 1.0, 1.0, 1.0);
	glBindTexture(mBackground);
	glLoadIdentity();
	drawQuad2(400.0, 300.0, 1024.0, 1024.0);
	
	
	if(mShowShadow)
	{
		// Generic shadow settings
		
		glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
		glEnable(GL_BLEND);

		// Blob shadows
		Vector2 pos;
	
		pos = blobShadowPosition(mLeftBlobPosition);
		glColor4ub(mLeftBlobColor.r, mLeftBlobColor.g, mLeftBlobColor.b, 128);
		glBindTexture(mBlobShadow[int(mLeftBlobAnimationState)  % 5]);
		drawQuad2(pos.x, pos.y, 128.0, 32.0);
	
		pos = blobShadowPosition(mRightBlobPosition);
		glColor4ub(mRightBlobColor.r, mRightBlobColor.g, mRightBlobColor.b, 128);
		glBindTexture(mBlobShadow[int(mRightBlobAnimationState)  % 5]);
		drawQuad2(pos.x, pos.y, 128.0, 32.0);

		// Ball shadow	
		pos = ballShadowPosition(mBallPosition);
		glColor4f(1.0, 1.0, 1.0, 0.5);
		glBindTexture(mBallShadow);
		drawQuad2(pos.x, pos.y, 128.0, 32.0);

		glDisable(GL_BLEND);
	}
	
	glEnable(GL_ALPHA_TEST);
		
	// General object settings
	glBlendFunc(GL_SRC_ALPHA, GL_ONE);
	// The Ball
	
	glColor4f(1.0, 1.0, 1.0, 1.0);
	glBindTexture(mBall[int(mBallRotation / M_PI / 2 * 16) % 16]);
/*
	float opacity = 0.0;
	for (std::list<Vector2>::iterator iter = mLastBallStates.begin();
		iter != mLastBallStates.end(); ++iter)
	{
//		glColor4f(1.0 / MotionBlurIterations, 
//			1.0 / MotionBlurIterations, 1.0 / MotionBlurIterations, 1.0 - opacity);
		glColor4f(1.0, 1.0, 1.0, opacity);
		
		
		Vector2& ballPosition = *iter;
*/
		drawQuad2(mBallPosition.x, mBallPosition.y, 64.0, 64.0);

/*
		opacity += 0.1;
	}
	if (mLastBallStates.size() > MotionBlurIterations)
			mLastBallStates.pop_back();
	glDisable(GL_BLEND);
*/	
	
	// blob normal
	// left blob
	glBindTexture(mBlob[int(mLeftBlobAnimationState)  % 5]);
	glColor3ubv(mLeftBlobColor.val);
	drawQuad2(mLeftBlobPosition.x, mLeftBlobPosition.y, 128.0, 128.0);
	
	// right blob
	glBindTexture(mBlob[int(mRightBlobAnimationState)  % 5]);
	glColor3ubv(mRightBlobColor.val);
	drawQuad2(mRightBlobPosition.x, mRightBlobPosition.y, 128.0, 128.0);

	// blob specular
	glEnable(GL_BLEND);
	glColor4f(1.0, 1.0, 1.0, 1.0);
	// left blob
	glBindTexture(mBlobSpecular[int(mLeftBlobAnimationState)  % 5]);
	drawQuad2(mLeftBlobPosition.x, mLeftBlobPosition.y, 128.0, 128.0);

	// right blob
	glBindTexture(mBlobSpecular[int(mRightBlobAnimationState)  % 5]);
	drawQuad2(mRightBlobPosition.x, mRightBlobPosition.y, 128.0, 128.0);
	
	glDisable(GL_BLEND);
	

	// Ball marker
	glDisable(GL_ALPHA_TEST);
	glDisable(GL_TEXTURE_2D);
	GLubyte markerColor = SDL_GetTicks() % 1000 >= 500 ? 255 : 0;
	glColor3ub(markerColor, markerColor, markerColor);
	drawQuad2(mBallPosition.x, 7.5, 5.0, 5.0);

	// Mouse marker

	// Position relativ zu BallMarker
	drawQuad2(mMouseMarkerPosition, 592.5, 5.0, 5.0);
	
	glEnable(GL_TEXTURE_2D);
	glEnable(GL_ALPHA_TEST);
	
	// Scores
	char textBuffer[64];
	snprintf(textBuffer, 8, mLeftPlayerWarning ? "%02d!" : "%02d",
			mLeftPlayerScore);
	drawText(textBuffer, Vector2(24, 24), false);
	snprintf(textBuffer, 8, mRightPlayerWarning ? "%02d!" : "%02d",
			mRightPlayerScore);	
	drawText(textBuffer, Vector2(728, 24), false);

	// Drawing the names
	drawText(mLeftPlayerName, Vector2(12, 550), false);

	drawText(mRightPlayerName, Vector2(788-(24*mRightPlayerName.length()), 550), false);
	
	// Drawing the clock
	drawText(mTime, Vector2(400 - mTime.length()*12, 24), false);
}
Пример #10
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();
	}
}
Пример #11
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();
	}
}
Пример #12
0
void R_DrawParticles (void)
{
	particle_t		*p, *kill;
	float			grav;
	int				i;
	float			time2, time3;
	float			time1;
	float			dvel;
	float			frametime;
	
#ifdef GLQUAKE
	vec3_t			up, right;
	float			scale;

    GL_Bind(particletexture);
	glEnable (GL_BLEND);
	glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
	glBegin (GL_TRIANGLES);

	VectorScale (vup, 1.5, up);
	VectorScale (vright, 1.5, right);
#else
	D_StartParticles ();

	VectorScale (vright, xscaleshrink, r_pright);
	VectorScale (vup, yscaleshrink, r_pup);
	VectorCopy (vpn, r_ppn);
#endif
	frametime = cl.time - cl.oldtime;
	time3 = frametime * 15;
	time2 = frametime * 10; // 15;
	time1 = frametime * 5;
	grav = frametime * sv_gravity.value * 0.05;
	dvel = 4*frametime;
	
	for ( ;; ) 
	{
		kill = active_particles;
		if (kill && kill->die < cl.time)
		{
			active_particles = kill->next;
			kill->next = free_particles;
			free_particles = kill;
			continue;
		}
		break;
	}

	for (p=active_particles ; p ; p=p->next)
	{
		for ( ;; )
		{
			kill = p->next;
			if (kill && kill->die < cl.time)
			{
				p->next = kill->next;
				kill->next = free_particles;
				free_particles = kill;
				continue;
			}
			break;
		}

#ifdef GLQUAKE
		// hack a scale up to keep particles from disapearing
		scale = (p->org[0] - r_origin[0])*vpn[0] + (p->org[1] - r_origin[1])*vpn[1]
			+ (p->org[2] - r_origin[2])*vpn[2];
		if (scale < 20)
			scale = 1;
		else
			scale = 1 + scale * 0.004;
		glColor3ubv ((byte *)&d_8to24table[(int)p->color]);
		glTexCoord2f (0,0);
		glVertex3fv (p->org);
		glTexCoord2f (1,0);
		glVertex3f (p->org[0] + up[0]*scale, p->org[1] + up[1]*scale, p->org[2] + up[2]*scale);
		glTexCoord2f (0,1);
		glVertex3f (p->org[0] + right[0]*scale, p->org[1] + right[1]*scale, p->org[2] + right[2]*scale);
#else
		D_DrawParticle (p);
#endif
		p->org[0] += p->vel[0]*frametime;
		p->org[1] += p->vel[1]*frametime;
		p->org[2] += p->vel[2]*frametime;
		
		switch (p->type)
		{
		case pt_static:
			break;
		case pt_fire:
			p->ramp += time1;
			if (p->ramp >= 6)
				p->die = -1;
			else
				p->color = ramp3[(int)p->ramp];
			p->vel[2] += grav;
			break;

		case pt_explode:
			p->ramp += time2;
			if (p->ramp >=8)
				p->die = -1;
			else
				p->color = ramp1[(int)p->ramp];
			for (i=0 ; i<3 ; i++)
				p->vel[i] += p->vel[i]*dvel;
			p->vel[2] -= grav;
			break;

		case pt_explode2:
			p->ramp += time3;
			if (p->ramp >=8)
				p->die = -1;
			else
				p->color = ramp2[(int)p->ramp];
			for (i=0 ; i<3 ; i++)
				p->vel[i] -= p->vel[i]*frametime;
			p->vel[2] -= grav;
			break;

		case pt_blob:
			for (i=0 ; i<3 ; i++)
				p->vel[i] += p->vel[i]*dvel;
			p->vel[2] -= grav;
			break;

		case pt_blob2:
			for (i=0 ; i<2 ; i++)
				p->vel[i] -= p->vel[i]*dvel;
			p->vel[2] -= grav;
			break;

		case pt_grav:
#ifdef QUAKE2
			p->vel[2] -= grav * 20;
			break;
#endif
		case pt_slowgrav:
			p->vel[2] -= grav;
			break;
		}
	}

#ifdef GLQUAKE
	glEnd ();
	glDisable (GL_BLEND);
	glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
#else
	D_EndParticles ();
#endif
}
Пример #13
0
/* draws a shaded strip, made from gradient + flat color + gradient */
static void draw_shadedstrip(Sequence *seq, unsigned char col[3], float x1, float y1, float x2, float y2)
{
    float ymid1, ymid2;

    if (seq->flag & SEQ_MUTE) {
        glEnable(GL_POLYGON_STIPPLE);
        glPolygonStipple(stipple_halftone);
    }

    ymid1 = (y2-y1)*0.25f + y1;
    ymid2 = (y2-y1)*0.65f + y1;

    glShadeModel(GL_SMOOTH);
    glBegin(GL_QUADS);

    if(seq->flag & SEQ_INVALID_EFFECT) {
        col[0]= 255;
        col[1]= 0;
        col[2]= 255;
    }
    else if(seq->flag & SELECT) UI_GetColorPtrShade3ubv(col, col, -50);
    /* else UI_GetColorPtrShade3ubv(col, col, 0); */ /* DO NOTHING */

    glColor3ubv(col);

    glVertex2f(x1,y1);
    glVertex2f(x2,y1);

    if(seq->flag & SEQ_INVALID_EFFECT) {
        col[0]= 255;
        col[1]= 0;
        col[2]= 255;
    }
    else if(seq->flag & SELECT) UI_GetColorPtrBlendShade3ubv(col, col, col, 0.0, 5);
    else UI_GetColorPtrShade3ubv(col, col, -5);

    glColor3ubv((GLubyte *)col);

    glVertex2f(x2,ymid1);
    glVertex2f(x1,ymid1);

    glEnd();

    glRectf(x1,  ymid1,  x2,  ymid2);

    glBegin(GL_QUADS);

    glVertex2f(x1,ymid2);
    glVertex2f(x2,ymid2);

    if(seq->flag & SELECT) UI_GetColorPtrShade3ubv(col, col, -15);
    else UI_GetColorPtrShade3ubv(col, col, 25);

    glColor3ubv((GLubyte *)col);

    glVertex2f(x2,y2);
    glVertex2f(x1,y2);

    glEnd();

    if (seq->flag & SEQ_MUTE) {
        glDisable(GL_POLYGON_STIPPLE);
    }
}
Пример #14
0
void View::drawOverlay(Colour& colour, std::string& title)
{
  //2D overlay objects, apply text scaling
  Viewport2d(width, height);
  glScalef(scale2d, scale2d, scale2d);
  int w = width / scale2d;
  int h = height / scale2d;
  GL_Error_Check;

  //Colour bars
  int last_B[4] = {0, 0, 0, 0};
  for (unsigned int i=0; i<objects.size(); i++)
  {
    //Only when flagged as colour bar
    if (!objects[i]->properties["colourbar"] || !objects[i]->properties["visible"]) continue;
    objects[i]->setup(); //Required to cache colouring values
    ColourMap* cmap = objects[i]->colourMap;
    //Use the first available colourmap by default
    if (!cmap && objects[i]->colourMaps && objects[i]->colourMaps->size() > 0)
      cmap = (*objects[i]->colourMaps)[0];
    if (!cmap) continue;

    float position = objects[i]->properties["position"];
    std::string align = objects[i]->properties["align"];
    int ww = w, hh = h;
    bool vertical = false;
    bool opposite = (align == "left" || align == "bottom");
    int side = 0;
    if (opposite) side += 1;
    //Vertical?
    if (align == "left" || align == "right")
    {
      side += 2;
      vertical = true;
      //Default position for vertical is offset from top
      if (position == 0 && !objects[i]->properties.has("position"))
        position = -0.06;
      ww = h;
      hh = w;
    }

    //Dimensions, default is to calculate automatically
    json size = objects[i]->properties["size"];
    float breadth = size[1];
    float length = size[0];
    if (length == 0)
      length = vertical ? 0.5 : 0.8;
    if (breadth == 0)
      breadth = vertical ? 20 : 10;

    //Size: if in range [0,1] they are a ratio of window size so multiply to get pixels
    if (length < 1.0) length *= ww;
    if (breadth < 1.0) breadth *= hh;

    //Margin offset
    float margin = objects[i]->properties["offset"];
    if (margin == 0)
    {
      //Calculate a sensible default margin
      drawstate.fonts.setFont(objects[i]->properties);
      if (vertical)
        margin = 18 + drawstate.fonts.printWidth("1.000001");
      else
        margin = 7 + drawstate.fonts.printWidth("1.1");
    }

    //Position: if in range [0,1] they are a ratio of window size so multiply to get pixels
    if (fabs(position) < 1.0) position *= ww;
    if (margin < 1.0) margin *= hh;

    //Add previous offset used and store for next
    margin = last_B[side] + margin;
    last_B[side] = margin + breadth;
    
    //Calc corner coords
    int start_A = (ww - length) / 2; //Centred, default for horizontal
    if (position > 0) start_A = position;
    if (position < 0) start_A = ww + position - length;
    int start_B = margin;

    if (!opposite) start_B = hh - start_B - breadth;

    //Default to vector font if downsampling and no other font requested
    if (scale2d != 1.0 && !objects[i]->properties.has("font"))
    {
      objects[i]->properties.data["font"] = "vector";
      if (!objects[i]->properties.has("fontscale"))
        objects[i]->properties.data["fontscale"] = 0.4;
    }

    cmap->draw(drawstate, objects[i]->properties, start_A, start_B, length, breadth, colour, vertical);
    GL_Error_Check;
  }

  GL_Error_Check;

  //Title
  if (title.length())
  {
    glColor3ubv(colour.rgba);
    drawstate.fonts.setFont(properties, "vector", 1.0);
    if (drawstate.fonts.charset == FONT_VECTOR)
      drawstate.fonts.fontscale *= 0.6; //Scale down vector font slightly for title
    drawstate.fonts.print(0.5 * (w - drawstate.fonts.printWidth(title.c_str())), h - 3 - drawstate.fonts.printWidth("W"), title.c_str());
  }

  GL_Error_Check;
  //Restore 3d
  Viewport2d(0, 0);
  GL_Error_Check;
}
Пример #15
0
void R_DrawParticles (void)
{
#ifdef WIN32
	particle_t		*p, *kill;
	int				i;
	float			vel0, vel1, vel2;
	vec3_t			save_org;

#ifdef GLQUAKE
	float			scale;

	GL_Bind(particletexture);
	glEnable (GL_BLEND);
	glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
	glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
	glBegin (GL_TRIANGLES);

	VectorScale (vup, 1.5, r_pup);
	VectorScale (vright, 1.5, r_pright);
#else

	VectorScale (vright, xscaleshrink, r_pright);
	VectorScale (vup, yscaleshrink, r_pup);
	VectorCopy (vpn, r_ppn);
#endif

	for ( ;; ) 
	{
		kill = active_particles;
		if (kill && kill->die < cl.time)
		{
			active_particles = kill->next;
			kill->next = free_particles;
			free_particles = kill;
			continue;
		}
		break;
	}

	for (p=active_particles ; p ; p=p->next)
	{
		for ( ;; )
		{
			kill = p->next;
			if (kill && kill->die < cl.time)
			{
				p->next = kill->next;
				kill->next = free_particles;
				free_particles = kill;
				continue;
			}
			break;
		}
		
		if (p->type==pt_rain)
		{
#ifdef GLQUAKE
			// hack a scale up to keep particles from disapearing
			scale = (p->org[0] - r_origin[0])*vpn[0] + (p->org[1] - r_origin[1])*vpn[1]
				+ (p->org[2] - r_origin[2])*vpn[2];
			if (scale < 20)
				scale = 1;
			else
				scale = 1 + scale * 0.004;
			if (p->color <= 255)
				glColor3ubv ((byte *)&d_8to24table[(int)p->color]);
			else
				glColor4ubv ((byte *)&d_8to24TranslucentTable[(int)p->color-256]);
			
			//fixme: need rain texture
			glTexCoord2f (1,0);
			glVertex3fv (p->org);
			glTexCoord2f (1,0.5);
			glVertex3f (p->org[0] + r_pup[0]*scale, p->org[1] + r_pup[1]*scale, p->org[2] + r_pup[2]*scale);
			glTexCoord2f (0.5,0);
			glVertex3f (p->org[0] + r_pright[0]*scale, p->org[1] + r_pright[1]*scale, p->org[2] + r_pright[2]*scale);
#else
			VectorCopy(p->org,save_org);

			vel0 = p->vel[0]*.001;
			vel1 = p->vel[1]*.001;
			vel2 = p->vel[2]*.001;

			for(i=0;i<4;i++)
			{
				D_DrawParticle(p);
				p->org[0] += vel0;
				p->org[1] += vel1;
				p->org[2] += vel2;
 			}
			D_DrawParticle(p);

			VectorCopy(save_org,p->org);//Restore origin
#endif
		}
		else if (p->type==pt_snow)
		{
#ifdef GLQUAKE
//IDEA: Put a snowflake texture on two-sided poly
//texture comes from glrmisc.c: R_InitParticleTexture 
			scale = (p->org[0] - r_origin[0])*vpn[0] + (p->org[1] - r_origin[1])*vpn[1]
				+ (p->org[2] - r_origin[2])*vpn[2];
			if (scale < 20)
				scale = p->count/10;	
			else
				scale = p->count/10 + scale * 0.004;

			if (p->color <= 255)
				glColor3ubv ((byte *)&d_8to24table[(int)p->color]);
			else
				glColor4ubv ((byte *)&d_8to24TranslucentTable[(int)p->color-256]);
	
			if(p->count>=69)
				glTexCoord2f (1,1);//happy snow!- bottom right
			else if(p->count>=40)	
				glTexCoord2f (0,0);	//normal snow - top left
			else if(p->count>=30)
				glTexCoord2f (0,1);	//bottom left
			else
				glTexCoord2f (1,0);	//top right

			glVertex3fv (p->org);
			if(p->count>=69)
				glTexCoord2f (1,.18);//top right
			else if(p->count>=40)	
				glTexCoord2f (.815,0);//top right
			else if(p->count>=30)
				glTexCoord2f (0.5,1);//bottom middle
			else
				glTexCoord2f (1,0.5);//middle right

			glVertex3f (p->org[0] + r_pup[0]*scale, p->org[1] + r_pup[1]*scale, p->org[2] + r_pup[2]*scale);

			if(p->count>=69)
				glTexCoord2f (.18,1);//bottom left
			else if(p->count>=40)	
				glTexCoord2f (0,.815);//bottom left
			else if(p->count>=30)
				glTexCoord2f (0,0.5);//left middle
			else
				glTexCoord2f (0.5,0);//middle top
			
			glVertex3f (p->org[0] + r_pright[0]*scale, p->org[1] + r_pright[1]*scale, p->org[2] + r_pright[2]*scale);
#else
			VectorCopy(p->org,save_org);
			D_DrawParticle (p);

			for(i=1;i<p->count;i++)
			{
				switch(i)
				{//FIXME:  More translucency on outside particles?
//				case 0:	//original
//					break;
				case 1:	//One to right
					p->org[0] = save_org[0] + vright[0];
					p->org[1] = save_org[1] + vright[1];
					p->org[2] = save_org[2] + vright[2];
					break;
				case 2: //One above
					p->org[0] = save_org[0] + vup[0];
					p->org[1] = save_org[1] + vup[1];
					p->org[2] = save_org[2] + vup[2];
					break;
				case 3:	//One to left
					p->org[0] = save_org[0] - vright[0];
					p->org[1] = save_org[1] - vright[1];
					p->org[2] = save_org[2] - vright[2];
					break;
				case 4:	//One below
					p->org[0] = save_org[0] - vup[0];
					p->org[1] = save_org[1] - vup[1];					
					p->org[2] = save_org[2] - vup[2];
					break;
				default:
				   Con_Printf ("count too big!\n");
					break;
				}
				D_DrawParticle (p);
			}
			VectorCopy(save_org,p->org);//Restore origin
#endif
		}
		else
		{
#ifdef GLQUAKE
			// hack a scale up to keep particles from disapearing
			scale = (p->org[0] - r_origin[0])*vpn[0] + (p->org[1] - r_origin[1])*vpn[1]
				+ (p->org[2] - r_origin[2])*vpn[2];
			if (scale < 20)
				scale = 1;
			else
				scale = 1 + scale * 0.004;
			if (p->color <= 255)
				glColor3ubv ((byte *)&d_8to24table[(int)p->color]);
			else
				glColor4ubv ((byte *)&d_8to24TranslucentTable[(int)p->color-256]);
			glTexCoord2f (1,0);
			glVertex3fv (p->org);
			glTexCoord2f (1,0.5);
			glVertex3f (p->org[0] + r_pup[0]*scale, p->org[1] + r_pup[1]*scale, p->org[2] + r_pup[2]*scale);
			glTexCoord2f (0.5,0);
			glVertex3f (p->org[0] + r_pright[0]*scale, p->org[1] + r_pright[1]*scale, p->org[2] + r_pright[2]*scale);
#else
			D_DrawParticle (p);
#endif
		}
	}

#ifdef GLQUAKE
	glEnd ();
	glDisable (GL_BLEND);
	glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
#endif
#endif
}
Пример #16
0
static void ruler_info_draw_pixel(const struct bContext *C, ARegion *ar, void *arg)
{
	Scene *scene = CTX_data_scene(C);
	UnitSettings *unit = &scene->unit;
	RulerItem *ruler_item;
	RulerInfo *ruler_info = arg;
	RegionView3D *rv3d = ruler_info->ar->regiondata;
//	ARegion *ar = ruler_info->ar;
	const float cap_size = 4.0f;
	const float bg_margin = 4.0f * U.pixelsize;
	const float bg_radius = 4.0f * U.pixelsize;
	const float arc_size = 64.0f * U.pixelsize;
#define ARC_STEPS 24
	const int arc_steps = ARC_STEPS;
	int i;
	//unsigned int color_act = 0x666600;
	unsigned int color_act = 0xffffff;
	unsigned int color_base = 0x0;
	unsigned char color_back[4] = {0xff, 0xff, 0xff, 0x80};
	unsigned char color_text[3];
	unsigned char color_wire[3];

	/* anti-aliased lines for more consistent appearance */
	glEnable(GL_LINE_SMOOTH);

	BLF_enable(blf_mono_font, BLF_ROTATION);
	BLF_size(blf_mono_font, 14 * U.pixelsize, U.dpi);
	BLF_rotation(blf_mono_font, 0.0f);

	UI_GetThemeColor3ubv(TH_TEXT, color_text);
	UI_GetThemeColor3ubv(TH_WIRE, color_wire);

	for (ruler_item = ruler_info->items.first, i = 0; ruler_item; ruler_item = ruler_item->next, i++) {
		const bool is_act = (i == ruler_info->item_active);
		float dir_ruler[2];
		float co_ss[3][2];
		int j;

		/* should these be checked? - ok for now not to */
		for (j = 0; j < 3; j++) {
			ED_view3d_project_float_global(ar, ruler_item->co[j], co_ss[j], V3D_PROJ_TEST_NOP);
		}

		glEnable(GL_BLEND);

		cpack(is_act ? color_act : color_base);

		if (ruler_item->flag & RULERITEM_USE_ANGLE) {
			glBegin(GL_LINE_STRIP);
			for (j = 0; j < 3; j++) {
				glVertex2fv(co_ss[j]);
			}
			glEnd();
			cpack(0xaaaaaa);
			setlinestyle(3);
			glBegin(GL_LINE_STRIP);
			for (j = 0; j < 3; j++) {
				glVertex2fv(co_ss[j]);
			}
			glEnd();
			setlinestyle(0);

			/* arc */
			{
				float dir_tmp[3];
				float co_tmp[3];
				float arc_ss_coords[ARC_STEPS + 1][2];

				float dir_a[3];
				float dir_b[3];
				float quat[4];
				float axis[3];
				float angle;
				const float px_scale = (ED_view3d_pixel_size(rv3d, ruler_item->co[1]) *
				                        min_fff(arc_size,
				                                len_v2v2(co_ss[0], co_ss[1]) / 2.0f,
				                                len_v2v2(co_ss[2], co_ss[1]) / 2.0f));

				sub_v3_v3v3(dir_a, ruler_item->co[0], ruler_item->co[1]);
				sub_v3_v3v3(dir_b, ruler_item->co[2], ruler_item->co[1]);
				normalize_v3(dir_a);
				normalize_v3(dir_b);

				cross_v3_v3v3(axis, dir_a, dir_b);
				angle = angle_normalized_v3v3(dir_a, dir_b);

				axis_angle_to_quat(quat, axis, angle / arc_steps);

				copy_v3_v3(dir_tmp, dir_a);

				glColor3ubv(color_wire);

				for (j = 0; j <= arc_steps; j++) {
					madd_v3_v3v3fl(co_tmp, ruler_item->co[1], dir_tmp, px_scale);
					ED_view3d_project_float_global(ar, co_tmp, arc_ss_coords[j], V3D_PROJ_TEST_NOP);
					mul_qt_v3(quat, dir_tmp);
				}

				glEnableClientState(GL_VERTEX_ARRAY);
				glVertexPointer(2, GL_FLOAT, 0, arc_ss_coords);
				glDrawArrays(GL_LINE_STRIP, 0, arc_steps + 1);
				glDisableClientState(GL_VERTEX_ARRAY);
			}

			/* text */
			{
				char numstr[256];
				float numstr_size[2];
				float pos[2];
				const int prec = 2;  /* XXX, todo, make optional */

				ruler_item_as_string(ruler_item, unit, numstr, sizeof(numstr), prec);

				BLF_width_and_height(blf_mono_font, numstr, &numstr_size[0], &numstr_size[1]);

				pos[0] = co_ss[1][0] + (cap_size * 2.0f);
				pos[1] = co_ss[1][1] - (numstr_size[1] / 2.0f);

				/* draw text (bg) */
				glColor4ubv(color_back);
				uiSetRoundBox(UI_CNR_ALL);
				uiRoundBox(pos[0] - bg_margin,                  pos[1] - bg_margin,
				           pos[0] + bg_margin + numstr_size[0], pos[1] + bg_margin + numstr_size[1],
				           bg_radius);
				/* draw text */
				glColor3ubv(color_text);
				BLF_position(blf_mono_font, pos[0], pos[1], 0.0f);
				BLF_rotation(blf_mono_font, 0.0f);
				BLF_draw(blf_mono_font, numstr, sizeof(numstr));
			}

			/* capping */
			{
				float rot_90_vec_a[2];
				float rot_90_vec_b[2];
				float cap[2];

				sub_v2_v2v2(dir_ruler, co_ss[0], co_ss[1]);
				rot_90_vec_a[0] = -dir_ruler[1];
				rot_90_vec_a[1] =  dir_ruler[0];
				normalize_v2(rot_90_vec_a);

				sub_v2_v2v2(dir_ruler, co_ss[1], co_ss[2]);
				rot_90_vec_b[0] = -dir_ruler[1];
				rot_90_vec_b[1] =  dir_ruler[0];
				normalize_v2(rot_90_vec_b);

				glEnable(GL_BLEND);

				glColor3ubv(color_wire);

				glBegin(GL_LINES);

				madd_v2_v2v2fl(cap, co_ss[0], rot_90_vec_a, cap_size);
				glVertex2fv(cap);
				madd_v2_v2v2fl(cap, co_ss[0], rot_90_vec_a, -cap_size);
				glVertex2fv(cap);

				madd_v2_v2v2fl(cap, co_ss[2], rot_90_vec_b, cap_size);
				glVertex2fv(cap);
				madd_v2_v2v2fl(cap, co_ss[2], rot_90_vec_b, -cap_size);
				glVertex2fv(cap);

				/* angle vertex */
				glVertex2f(co_ss[1][0] - cap_size, co_ss[1][1] - cap_size);
				glVertex2f(co_ss[1][0] + cap_size, co_ss[1][1] + cap_size);
				glVertex2f(co_ss[1][0] - cap_size, co_ss[1][1] + cap_size);
				glVertex2f(co_ss[1][0] + cap_size, co_ss[1][1] - cap_size);
				glEnd();

				glDisable(GL_BLEND);
			}
		}
		else {
			glBegin(GL_LINE_STRIP);
			for (j = 0; j < 3; j += 2) {
				glVertex2fv(co_ss[j]);
			}
			glEnd();
			cpack(0xaaaaaa);
			setlinestyle(3);
			glBegin(GL_LINE_STRIP);
			for (j = 0; j < 3; j += 2) {
				glVertex2fv(co_ss[j]);
			}
			glEnd();
			setlinestyle(0);

			sub_v2_v2v2(dir_ruler, co_ss[0], co_ss[2]);

			/* text */
			{
				char numstr[256];
				float numstr_size[2];
				const int prec = 6;  /* XXX, todo, make optional */
				float pos[2];

				ruler_item_as_string(ruler_item, unit, numstr, sizeof(numstr), prec);

				BLF_width_and_height(blf_mono_font, numstr, &numstr_size[0], &numstr_size[1]);

				mid_v2_v2v2(pos, co_ss[0], co_ss[2]);

				/* center text */
				pos[0] -= numstr_size[0] / 2.0f;
				pos[1] -= numstr_size[1] / 2.0f;

				/* draw text (bg) */
				glColor4ubv(color_back);
				uiSetRoundBox(UI_CNR_ALL);
				uiRoundBox(pos[0] - bg_margin,                  pos[1] - bg_margin,
				           pos[0] + bg_margin + numstr_size[0], pos[1] + bg_margin + numstr_size[1],
				           bg_radius);
				/* draw text */
				glColor3ubv(color_text);
				BLF_position(blf_mono_font, pos[0], pos[1], 0.0f);
				BLF_draw(blf_mono_font, numstr, sizeof(numstr));
			}

			/* capping */
			{
				float rot_90_vec[2] = {-dir_ruler[1], dir_ruler[0]};
				float cap[2];

				normalize_v2(rot_90_vec);

				glEnable(GL_BLEND);
				glColor3ubv(color_wire);

				glBegin(GL_LINES);
				madd_v2_v2v2fl(cap, co_ss[0], rot_90_vec, cap_size);
				glVertex2fv(cap);
				madd_v2_v2v2fl(cap, co_ss[0], rot_90_vec, -cap_size);
				glVertex2fv(cap);

				madd_v2_v2v2fl(cap, co_ss[2], rot_90_vec, cap_size);
				glVertex2fv(cap);
				madd_v2_v2v2fl(cap, co_ss[2], rot_90_vec, -cap_size);
				glVertex2fv(cap);
				glEnd();

				glDisable(GL_BLEND);
			}
		}
	}

	glDisable(GL_LINE_SMOOTH);

	BLF_disable(blf_mono_font, BLF_ROTATION);

#undef ARC_STEPS

	/* draw snap */
	if ((ruler_info->snap_flag & RULER_SNAP_OK) && (ruler_info->state == RULER_STATE_DRAG)) {
		ruler_item = ruler_item_active_get(ruler_info);
		if (ruler_item) {
			/* size from drawSnapping */
			const float size = 2.5f * UI_GetThemeValuef(TH_VERTEX_SIZE);
			float co_ss[3];
			ED_view3d_project_float_global(ar, ruler_item->co[ruler_item->co_index], co_ss, V3D_PROJ_TEST_NOP);

			cpack(color_act);
			circ(co_ss[0], co_ss[1], size * U.pixelsize);
		}
	}

}
Пример #17
0
void cc2DViewportLabel::drawMeOnly(CC_DRAW_CONTEXT& context)
{
	//2D foreground only
	if (!MACRO_Foreground(context) || !MACRO_Draw2D(context))
		return;

	//test viewport parameters
	const ccViewportParameters& params = context._win->getViewportParameters();

	//in perspective mode, screenPan or zoom cannot be easily compensated
	if (m_params.perspectiveView && 
			(  params.zoom != m_params.zoom
			|| params.globalZoom != m_params.globalZoom
			|| params.screenPan[0] != m_params.screenPan[0]
			|| params.screenPan[1] != m_params.screenPan[1]
			|| (params.pivotPoint - m_params.pivotPoint).norm() > ZERO_TOLERANCE))
		return;

	//test base view matrix
	for (unsigned i=0;i<12;++i)
		if (fabs(params.baseViewMat.data()[i] - m_params.baseViewMat.data()[i])>ZERO_TOLERANCE)
			return;

	//general parameters
	if (params.perspectiveView != m_params.perspectiveView
		|| params.objectCenteredPerspective != m_params.objectCenteredPerspective
		//|| (params.pivotPoint - m_params.pivotPoint).norm() > ZERO_TOLERANCE
		|| params.aspectRatio != m_params.aspectRatio
		|| params.fov != m_params.fov)
			return;

	glPushAttrib(GL_LINE_BIT);

	//Screen pan & pivot compensation
	float dx=0.0f,dy=0.0f,relativeZoom=1.0f;
	if (!m_params.perspectiveView)
	{
		float totalZoom = m_params.zoom*m_params.globalZoom;
		float winTotalZoom = params.zoom*params.globalZoom;
		relativeZoom = winTotalZoom/totalZoom;

		dx = m_params.screenPan[0] - params.screenPan[0];
		dy = m_params.screenPan[1] - params.screenPan[1];

		CCVector3 P = m_params.pivotPoint-params.pivotPoint;
		m_params.baseViewMat.apply(P);
		dx += P.x;
		dy += P.y;

		dx *= winTotalZoom;
		dy *= winTotalZoom;
	}

	//thick dotted line
	glLineWidth(2);
	glLineStipple(1, 0xAAAA);
	glEnable(GL_LINE_STIPPLE);

	const colorType* defaultColor = selected ? ccColor::red : context.textDefaultCol;
	glColor3ubv(defaultColor); 

	glBegin(GL_LINE_LOOP);
	glVertex2f(dx+m_roi[0]*relativeZoom,dy+m_roi[1]*relativeZoom);
	glVertex2f(dx+m_roi[2]*relativeZoom,dy+m_roi[1]*relativeZoom);
	glVertex2f(dx+m_roi[2]*relativeZoom,dy+m_roi[3]*relativeZoom);
	glVertex2f(dx+m_roi[0]*relativeZoom,dy+m_roi[3]*relativeZoom);
	glEnd();

	glPopAttrib();

	//title
	QString title(getName());
	if (!title.isEmpty())
	{
		QFont titleFont(context._win->getTextDisplayFont());
		titleFont.setBold(true);
		QFontMetrics titleFontMetrics(titleFont);
		int titleHeight = titleFontMetrics.height();

		int xStart = (int)(dx+0.5f*(float)context.glW+std::min<float>(m_roi[0],m_roi[2])*relativeZoom);
		int yStart = (int)(dy+0.5f*(float)context.glH+std::min<float>(m_roi[1],m_roi[3])*relativeZoom);

		context._win->displayText(title,xStart,yStart-5-titleHeight,false,defaultColor,titleFont);
	}
}
Пример #18
0
void draw()
{
	int j;
	
	glClear(GL_COLOR_BUFFER_BIT);
	
	// draw white circle (large)
	glColor3f(1.0, 1.0, 1.0);
	glBegin(GL_TRIANGLE_FAN);
		glVertex2f(0.0, 0.0);
		for(j = 0; j <= 360; j += 5)
		{
			glVertex2f(cosd(j) * RING_WIDTH / 2.0, sind(j) * RING_WIDTH / 2.0);
		}
	glEnd();
	
	// draw black circle
	glColor3f(0.05, 0.05, 0.05);
	glBegin(GL_TRIANGLE_FAN);
		glVertex2f(0.0, 0.0);
		for(j = 0; j <= 360; j += 5)
		{
			glVertex2f(cosd(j) * RING_INNER_WIDTH / 2.0, 
				sind(j) * RING_INNER_WIDTH / 2.0);
		}
	glEnd();
	
	// draw Shikiri Lines
	glColor3f(0.5, 0.164, 0.164);
	glBegin(GL_QUADS);
		glVertex2f(10.0, -10.0);
		glVertex2f(10.0, 10.0);
		glVertex2f(12.0, 10.0);
		glVertex2f(12.0, -10.0);
		glVertex2f(-10.0, -10.0);
		glVertex2f(-10.0, 10.0);
		glVertex2f(-12.0, 10.0);
		glVertex2f(-12.0, -10.0);
	glEnd();
	
	// draw robots
	for(j = 0; j < robots_size; j++)
	{
		glPushMatrix();
		glTranslatef(robots[j].pos.x, robots[j].pos.y, 0.0);
		glRotatef(robots[j].rot, 0.0, 0.0, 1.0);
		glColor3f(0.9, 0.9, 0.9);
		glBegin(GL_QUADS);
			glVertex2f(-robots[j].width / 2.0, -robots[j].width / 2.0);
			glVertex2f(-robots[j].width / 2.0, robots[j].width / 2.0);
			glVertex2f(robots[j].width / 2.0, robots[j].width / 2.0);
			glVertex2f(robots[j].width / 2.0, -robots[j].width / 2.0);
		glEnd();
		glColor3ubv(&robots[j].color.r);
		glBegin(GL_TRIANGLES);
			glVertex2f(-robots[j].width / 2.0, robots[j].width / 2.0);
			glVertex2f(robots[j].width / 2.0, 0.0);
			glVertex2f(-robots[j].width / 2.0, -robots[j].width / 2.0);
		glEnd();
		glPopMatrix();
	}
	
	glFlush();
}
Пример #19
0
//Does a water warp on the pre-fragmented glpoly_t chain
void EmitWaterPolys (msurface_t *fa) {
    glpoly_t *p;
    float *v, s, t, os, ot;
    int i;
    byte *col;
    extern cvar_t r_telecolor, r_watercolor, r_slimecolor, r_lavacolor;
    float wateralpha = bound((1 - r_refdef2.max_watervis), r_wateralpha.value, 1);

    vec3_t nv;
    GLint shader, u_gamma, u_contrast;

    GL_DisableMultitexture();

    if (gl_fogenable.value)
        glEnable(GL_FOG);

    GL_Bind (fa->texinfo->texture->gl_texturenum);

    /* FIXME: do the uniforms somewhere else */
    shader = glsl_shaders[SHADER_TURB].shader;
    qglUseProgram(shader);
    u_gamma    = qglGetUniformLocation(shader, "gamma");
    u_contrast = qglGetUniformLocation(shader, "contrast");
    qglUniform1f(u_gamma, v_gamma.value);
    qglUniform1f(u_contrast, v_contrast.value);

    if (r_fastturb.value)
    {
        GL_Bind(whitetexture);

        if (strstr (fa->texinfo->texture->name, "water") || strstr (fa->texinfo->texture->name, "mwat"))
            col = r_watercolor.color;
        else if (strstr (fa->texinfo->texture->name, "slime"))
            col = r_slimecolor.color;
        else if (strstr (fa->texinfo->texture->name, "lava"))
            col = r_lavacolor.color;
        else if (strstr (fa->texinfo->texture->name, "tele"))
            col = r_telecolor.color;
        else
            col = (byte *) &fa->texinfo->texture->flatcolor3ub;

        glColor3ubv (col);

        if (wateralpha < 1.0 && wateralpha >= 0) {
            glEnable (GL_BLEND);
            col[3] = wateralpha*255;
            glColor4ubv (col); // 1, 1, 1, wateralpha
            glTexEnvf (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
            if (wateralpha < 0.9)
                glDepthMask (GL_FALSE);
        }

        EmitFlatWaterPoly (fa);

        if (wateralpha < 1.0 && wateralpha >= 0) {
            glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
            glColor3ubv (color_white);
            glDisable (GL_BLEND);
            if (wateralpha < 0.9)
                glDepthMask (GL_TRUE);
        }

        glColor3ubv (color_white);
    } else {
        for (p = fa->polys; p; p = p->next) {
            glBegin(GL_POLYGON);
            for (i = 0, v = p->verts[0]; i < p->numverts; i++, v += VERTEXSIZE) {
                os = v[3];
                ot = v[4];

                s = os + SINTABLE_APPROX(ot * 2 + r_refdef2.time);
                s *= (1.0 / 64);

                t = ot + SINTABLE_APPROX(os * 2 + r_refdef2.time);
                t *= (1.0 / 64);

                //VULT RIPPLE : Not sure where this came from first, but I've seen in it more than one engine
                //I got this one from the QMB engine though
                VectorCopy(v, nv);
                //Over 20 this setting gets pretty cheaty
                if (amf_waterripple.value && (cls.demoplayback || cl.spectator) && !strstr (fa->texinfo->texture->name, "tele"))
                    nv[2] = v[2] + (bound(0, amf_waterripple.value, 20)) *sin(v[0]*0.02+r_refdef2.time)*sin(v[1]*0.02+r_refdef2.time)*sin(v[2]*0.02+r_refdef2.time);

                glTexCoord2f (s, t);
                glVertex3fv (nv);

            }
            glEnd();
        }
    }
    qglUseProgram(0);

    if (gl_fogenable.value)
        glDisable(GL_FOG);
}
Пример #20
0
/* used by node view too */
void ED_image_draw_info(Scene *scene, ARegion *ar, int color_manage, int use_default_view, int channels, int x, int y,
                        const unsigned char cp[4], const float fp[4], int *zp, float *zpf)
{
	char str[256];
	float dx = 6;
	/* text colors */
	/* XXX colored text not allowed in Blender UI */
	#if 0
	unsigned char red[3] = {255, 50, 50};
	unsigned char green[3] = {0, 255, 0};
	unsigned char blue[3] = {100, 100, 255};
	#else
	unsigned char red[3] = {255, 255, 255};
	unsigned char green[3] = {255, 255, 255};
	unsigned char blue[3] = {255, 255, 255};
	#endif
	float hue = 0, sat = 0, val = 0, lum = 0, u = 0, v = 0;
	float col[4], finalcol[4];

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

	/* noisy, high contrast make impossible to read if lower alpha is used. */
	glColor4ub(0, 0, 0, 190);
	glRecti(0.0, 0.0, BLI_rcti_size_x(&ar->winrct) + 1, 20);
	glDisable(GL_BLEND);

	BLF_size(blf_mono_font, 11, 72);

	glColor3ub(255, 255, 255);
	BLI_snprintf(str, sizeof(str), "X:%-4d  Y:%-4d |", x, y);
	// UI_DrawString(6, 6, str); // works ok but fixed width is nicer.
	BLF_position(blf_mono_font, dx, 6, 0);
	BLF_draw_ascii(blf_mono_font, str, sizeof(str));
	dx += BLF_width(blf_mono_font, str);

	if (zp) {
		glColor3ub(255, 255, 255);
		BLI_snprintf(str, sizeof(str), " Z:%-.4f |", 0.5f + 0.5f * (((float)*zp) / (float)0x7fffffff));
		BLF_position(blf_mono_font, dx, 6, 0);
		BLF_draw_ascii(blf_mono_font, str, sizeof(str));
		dx += BLF_width(blf_mono_font, str);
	}
	if (zpf) {
		glColor3ub(255, 255, 255);
		BLI_snprintf(str, sizeof(str), " Z:%-.3f |", *zpf);
		BLF_position(blf_mono_font, dx, 6, 0);
		BLF_draw_ascii(blf_mono_font, str, sizeof(str));
		dx += BLF_width(blf_mono_font, str);
	}

	if (channels >= 3) {
		glColor3ubv(red);
		if (fp)
			BLI_snprintf(str, sizeof(str), "  R:%-.5f", fp[0]);
		else if (cp)
			BLI_snprintf(str, sizeof(str), "  R:%-3d", cp[0]);
		else
			BLI_snprintf(str, sizeof(str), "  R:-");
		BLF_position(blf_mono_font, dx, 6, 0);
		BLF_draw_ascii(blf_mono_font, str, sizeof(str));
		dx += BLF_width(blf_mono_font, str);
		
		glColor3ubv(green);
		if (fp)
			BLI_snprintf(str, sizeof(str), "  G:%-.5f", fp[1]);
		else if (cp)
			BLI_snprintf(str, sizeof(str), "  G:%-3d", cp[1]);
		else
			BLI_snprintf(str, sizeof(str), "  G:-");
		BLF_position(blf_mono_font, dx, 6, 0);
		BLF_draw_ascii(blf_mono_font, str, sizeof(str));
		dx += BLF_width(blf_mono_font, str);
		
		glColor3ubv(blue);
		if (fp)
			BLI_snprintf(str, sizeof(str), "  B:%-.5f", fp[2]);
		else if (cp)
			BLI_snprintf(str, sizeof(str), "  B:%-3d", cp[2]);
		else
			BLI_snprintf(str, sizeof(str), "  B:-");
		BLF_position(blf_mono_font, dx, 6, 0);
		BLF_draw_ascii(blf_mono_font, str, sizeof(str));
		dx += BLF_width(blf_mono_font, str);
		
		if (channels == 4) {
			glColor3ub(255, 255, 255);
			if (fp)
				BLI_snprintf(str, sizeof(str), "  A:%-.4f", fp[3]);
			else if (cp)
				BLI_snprintf(str, sizeof(str), "  A:%-3d", cp[3]);
			else
				BLI_snprintf(str, sizeof(str), "- ");
			BLF_position(blf_mono_font, dx, 6, 0);
			BLF_draw_ascii(blf_mono_font, str, sizeof(str));
			dx += BLF_width(blf_mono_font, str);
		}

		if (color_manage && channels == 4) {
			float pixel[4];

			if (use_default_view)
				IMB_colormanagement_pixel_to_display_space_v4(pixel, fp,  NULL, &scene->display_settings);
			else
				IMB_colormanagement_pixel_to_display_space_v4(pixel, fp,  &scene->view_settings, &scene->display_settings);

			BLI_snprintf(str, sizeof(str), "  |  CM  R:%-.4f  G:%-.4f  B:%-.4f", pixel[0], pixel[1], pixel[2]);
			BLF_position(blf_mono_font, dx, 6, 0);
			BLF_draw_ascii(blf_mono_font, str, sizeof(str));
			dx += BLF_width(blf_mono_font, str);
		}
	}
	
	/* color rectangle */
	if (channels == 1) {
		if (fp) {
			col[0] = col[1] = col[2] = fp[0];
		}
		else if (cp) {
			col[0] = col[1] = col[2] = (float)cp[0] / 255.0f;
		}
		else {
			col[0] = col[1] = col[2] = 0.0f;
		}
		col[3] = 1.0f;
	}
	else if (channels == 3) {
		if (fp) {
			copy_v3_v3(col, fp);
		}
		else if (cp) {
			rgb_uchar_to_float(col, cp);
		}
		else {
			zero_v3(col);
		}
		col[3] = 1.0f;
	}
	else if (channels == 4) {
		if (fp)
			copy_v4_v4(col, fp);
		else if (cp) {
			rgba_uchar_to_float(col, cp);
		}
		else {
			zero_v4(col);
		}
	}
	else {
		BLI_assert(0);
		zero_v4(col);
	}

	if (color_manage) {
		if (use_default_view)
			IMB_colormanagement_pixel_to_display_space_v4(finalcol, col,  NULL, &scene->display_settings);
		else
			IMB_colormanagement_pixel_to_display_space_v4(finalcol, col,  &scene->view_settings, &scene->display_settings);
	}
	else {
		copy_v4_v4(finalcol, col);
	}

	glDisable(GL_BLEND);
	glColor3fv(finalcol);
	dx += 5;
	glBegin(GL_QUADS);
	glVertex2f(dx, 3);
	glVertex2f(dx, 17);
	glVertex2f(dx + 30, 17);
	glVertex2f(dx + 30, 3);
	glEnd();

	/* draw outline */
	glColor3ub(128, 128, 128);
	glBegin(GL_LINE_LOOP);
	glVertex2f(dx, 3);
	glVertex2f(dx, 17);
	glVertex2f(dx + 30, 17);
	glVertex2f(dx + 30, 3);
	glEnd();

	dx += 35;

	glColor3ub(255, 255, 255);
	if (channels == 1) {
		if (fp) {
			rgb_to_hsv(fp[0], fp[0], fp[0], &hue, &sat, &val);
			rgb_to_yuv(fp[0], fp[0], fp[0], &lum, &u, &v);
		}
		else if (cp) {
			rgb_to_hsv((float)cp[0] / 255.0f, (float)cp[0] / 255.0f, (float)cp[0] / 255.0f, &hue, &sat, &val);
			rgb_to_yuv((float)cp[0] / 255.0f, (float)cp[0] / 255.0f, (float)cp[0] / 255.0f, &lum, &u, &v);
		}
		
		BLI_snprintf(str, sizeof(str), "V:%-.4f", val);
		BLF_position(blf_mono_font, dx, 6, 0);
		BLF_draw_ascii(blf_mono_font, str, sizeof(str));
		dx += BLF_width(blf_mono_font, str);

		BLI_snprintf(str, sizeof(str), "   L:%-.4f", lum);
		BLF_position(blf_mono_font, dx, 6, 0);
		BLF_draw_ascii(blf_mono_font, str, sizeof(str));
		dx += BLF_width(blf_mono_font, str);
	}
	else if (channels >= 3) {
		if (fp) {
			rgb_to_hsv(fp[0], fp[1], fp[2], &hue, &sat, &val);
			rgb_to_yuv(fp[0], fp[1], fp[2], &lum, &u, &v);
		}
		else if (cp) {
			rgb_to_hsv((float)cp[0] / 255.0f, (float)cp[1] / 255.0f, (float)cp[2] / 255.0f, &hue, &sat, &val);
			rgb_to_yuv((float)cp[0] / 255.0f, (float)cp[1] / 255.0f, (float)cp[2] / 255.0f, &lum, &u, &v);
		}

		BLI_snprintf(str, sizeof(str), "H:%-.4f", hue);
		BLF_position(blf_mono_font, dx, 6, 0);
		BLF_draw_ascii(blf_mono_font, str, sizeof(str));
		dx += BLF_width(blf_mono_font, str);

		BLI_snprintf(str, sizeof(str), "  S:%-.4f", sat);
		BLF_position(blf_mono_font, dx, 6, 0);
		BLF_draw_ascii(blf_mono_font, str, sizeof(str));
		dx += BLF_width(blf_mono_font, str);

		BLI_snprintf(str, sizeof(str), "  V:%-.4f", val);
		BLF_position(blf_mono_font, dx, 6, 0);
		BLF_draw_ascii(blf_mono_font, str, sizeof(str));
		dx += BLF_width(blf_mono_font, str);

		BLI_snprintf(str, sizeof(str), "   L:%-.4f", lum);
		BLF_position(blf_mono_font, dx, 6, 0);
		BLF_draw_ascii(blf_mono_font, str, sizeof(str));
		dx += BLF_width(blf_mono_font, str);
	}

	(void)dx;
}
Пример #21
0
/*
==============
R_DrawSky

Draw either the classic cloudy quake sky or a skybox
==============
*/
void R_DrawSky (void)
{
    msurface_t	*fa;
    qbool		ignore_z;
    extern msurface_t *skychain;

    GL_DisableMultitexture ();

    if (r_fastsky.value) {
        glDisable (GL_TEXTURE_2D);
        glColor3ubv (r_skycolor.color);

        for (fa = skychain; fa; fa = fa->texturechain)
            EmitFlatPoly (fa);
        skychain = NULL;

        glEnable (GL_TEXTURE_2D);
        glColor3f (1, 1, 1);
        return;
    }

    if (r_viewleaf->contents == CONTENTS_SOLID) {
        // always draw if we're in a solid leaf (probably outside the level)
        // FIXME: we don't really want to add all six planes every time!
        // FIXME: also handle r_fastsky case
        int i;
        for (i = 0; i < 6; i++) {
            skymins[0][i] = skymins[1][i] = -1;
            skymaxs[0][i] = skymaxs[1][i] = 1;
        }
        ignore_z = true;
    }
    else {
        if (!skychain)
            return;		// no sky at all

        // figure out how much of the sky box we need to draw
        ClearSky ();
        for (fa = skychain; fa; fa = fa->texturechain)
            R_AddSkyBoxSurface (fa);

        ignore_z = false;
    }

    // turn off Z tests & writes to avoid problems on large maps
    glDisable (GL_DEPTH_TEST);

    // draw a skybox or classic quake clouds
    if (r_skyboxloaded)
        R_DrawSkyBox ();
    else
        R_DrawSkyDome ();

    glEnable (GL_DEPTH_TEST);

    // draw the sky polys into the Z buffer
    // don't need depth test yet
    if (!ignore_z) {
        if (gl_fogenable.value && gl_fogsky.value) {
            glEnable(GL_FOG);
            glColor4f(gl_fogred.value, gl_foggreen.value, gl_fogblue.value, 1);
            glBlendFunc(GL_ONE, GL_ZERO);
        }
        else {
            glColorMask (GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
            glBlendFunc(GL_ZERO, GL_ONE);
        }
        glDisable(GL_TEXTURE_2D);
        glEnable(GL_BLEND);

        for (fa = skychain; fa; fa = fa->texturechain)
            EmitFlatPoly (fa);

        if (gl_fogenable.value && gl_fogsky.value)
            glDisable (GL_FOG);
        else {
            glColorMask (GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
        }
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
        glEnable (GL_TEXTURE_2D);
        glDisable(GL_BLEND);
    }

    skychain = NULL;
    skychain_tail = &skychain;
}
Пример #22
0
void PLYObject::draw()
{

  // setup default material
  glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, ambient);
  glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, diffuse);
  glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, specular);
  glMaterialfv(GL_FRONT_AND_BACK, GL_SHININESS, shininess);
  glColor3fv(diffuse);

  // set lighting if enabled
	// Otherwise, compute colors
  if (light)
		{
			glEnable(GL_LIGHTING);
		}
  else
		{

			glDisable(GL_LIGHTING);
			for (int v=0; v<nv; v++)
				{
					// Instead of this, use the Phong illumination equation to find the color

                    // Phong equation with attenuation factor att
                    // If = (As*Am) + ((Al*Am) + Id + Is) * att

                    // Get ModelView

                    float M[16];
                    Matrix4f modelViewMatrix;

                    glGetFloatv(GL_MODELVIEW_MATRIX, M);
                    for (int i = 0; i < 3; i++) {
                        modelViewMatrix[i][3] = 0.0;
                        modelViewMatrix[3][i] = 0.0;
                        for (int j = 0; j < 3; j++) {
                            modelViewMatrix[i][j] = M[i*4+j];
                        }
                    }
                    modelViewMatrix[3][3] = 1.0;

                    // ModelView is already here in a Matrix4f for operations

                    Vector3f vVertex;
                    multVector(vVertex, modelViewMatrix, vertices[v]);

                    Vector4f lightSource;
                    copy(lightSource, light_pos);
                    //glGetLightfv(GL_LIGHT0, GL_POSITION, lightSource);

                    Vector3f lightDir;
                    sub(lightDir, lightSource, vVertex);

                    float d = length(lightDir);

                    // Get parameters for the ambient part
                    float Al[4] = {0.0f, 0.0f, 0.0f, 0.0f };
                    glGetLightfv( GL_LIGHT0, GL_AMBIENT, Al );

                    Vector4f As = {0.0f, 0.0f, 0.0f, 0.0f };
                    glGetFloatv( GL_LIGHT_MODEL_AMBIENT, As );

                    float Dl[4] = {0.0f, 0.0f, 0.0f, 0.0f };
                    glGetLightfv( GL_LIGHT0, GL_DIFFUSE, Dl );

                    float Sl[4] = {0.0f, 0.0f, 0.0f, 0.0f };
                    glGetLightfv( GL_LIGHT0, GL_SPECULAR, Sl );

                    Vector4f Am = {0.0f, 0.0f, 0.0f, 0.0f };
                    copy(Am, ambient);

                    float Dm[4] = {0.0f, 0.0f, 0.0f, 0.0f };
                    copy(Dm, diffuse);

                    float Sm[4] = {0.0f, 0.0f, 0.0f, 0.0f };
                    copy(Sm, specular);

                    float f = shininess[0];  // copy shininess

                    float constantAttenuation = 0.0f;
                    glGetLightfv( GL_LIGHT0, GL_CONSTANT_ATTENUATION, &constantAttenuation);

                    float linearAttenuation = 0.0f;
                    glGetLightfv( GL_LIGHT0, GL_LINEAR_ATTENUATION , &linearAttenuation );

                    float quadraticAttenuation = 0.0f;
                    glGetLightfv( GL_LIGHT0, GL_QUADRATIC_ATTENUATION , &quadraticAttenuation);

                    float att = (constantAttenuation +
                                (linearAttenuation*d) +
                                (quadraticAttenuation*d*d) );

					// Start the phong equation with the ambient component
					Vector4f temp1;
					multVectors4(temp1, As, Am);
					Vector4f temp2;
                    multVectors4(temp2, Al, Am);
                    scale4(temp2, att);
					Vector4f final_color;
					//final_color = (As * Am) + (Al * Am)*att;
					add(final_color, temp1, temp2);

                    // Calculate lambertTerm
                    Vector3f N;
                    normalizeVector(N, normals[v]);
                    Vector3f L;
                    normalizeVector(L, lightDir);

                    float lambertTerm = dotProd(N,L);

                    if (lambertTerm > 0.0){
                        // diffuse component
                        multVectors4(temp1,Dl,Dm);
                        scale4(temp1,lambertTerm);
                        add(final_color, final_color, temp1);

                        // specular component
                        Vector3f E;
                        normalizeVector(E,viewer_pos);
                        Vector3f R;
                        scale4(temp1,lambertTerm*2,N);
                        sub(R, temp1, L); // reflect(-L,N)

                        float dotProduct = dotProd(R,E);
                        float specular_factor;
                        if(dotProduct > 0.0){
                            specular_factor = pow(dotProduct, f);
                        } else {
                            specular_factor = 0; // pow(0.0, f);
                        }

                        multVectors4(temp1, Sl, Sm);
                        scale4(temp1, specular_factor*att, temp1);
                        add(final_color, final_color, temp1);
                        // printf("DM are %f , %f and %f", final_color[0], final_color[1], final_color[2]);
                    }


                    //Colors [v][i] should take the colors of final_color, how?
                    colors[v][0] = final_color[0]*255;
                    colors[v][1] = final_color[1]*255;
                    colors[v][2] = final_color[2]*255;
				}
		}

	// Now do the actual drawing of the model
  glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
  glBegin(GL_TRIANGLES);

  for (int i = 0; i < nf; i++)
    {
      for (int j = 0; j < 3; j++)
        {
            glColor3ubv((GLubyte*)colors[faces[i][j]]);
            glNormal3fv(normals[faces[i][j]]);	// vertex normal
            glVertex3fv(vertices[faces[i][j]]);	// vertex coordinates
        }
    }
  glEnd();

  glDisable(GL_POLYGON_OFFSET_FILL);
  if (hascolor)
    glDisable(GL_COLOR_MATERIAL);
}
Пример #23
0
void ui_draw_but_CURVE(ARegion *ar, uiBut *but, uiWidgetColors *wcol, rcti *rect)
{
	CurveMapping *cumap;
	CurveMap *cuma;
	CurveMapPoint *cmp;
	float fx, fy, fac[2], zoomx, zoomy, offsx, offsy;
	GLint scissor[4];
	rcti scissor_new;
	int a;

	cumap= (CurveMapping *)(but->editcumap? but->editcumap: but->poin);
	cuma= cumap->cm+cumap->cur;
	
	/* need scissor test, curve can draw outside of boundary */
	glGetIntegerv(GL_VIEWPORT, scissor);
	scissor_new.xmin= ar->winrct.xmin + rect->xmin;
	scissor_new.ymin= ar->winrct.ymin + rect->ymin;
	scissor_new.xmax= ar->winrct.xmin + rect->xmax;
	scissor_new.ymax= ar->winrct.ymin + rect->ymax;
	BLI_isect_rcti(&scissor_new, &ar->winrct, &scissor_new);
	glScissor(scissor_new.xmin, scissor_new.ymin, scissor_new.xmax-scissor_new.xmin, scissor_new.ymax-scissor_new.ymin);
	
	/* calculate offset and zoom */
	zoomx= (rect->xmax-rect->xmin-2.0f*but->aspect)/(cumap->curr.xmax - cumap->curr.xmin);
	zoomy= (rect->ymax-rect->ymin-2.0f*but->aspect)/(cumap->curr.ymax - cumap->curr.ymin);
	offsx= cumap->curr.xmin-but->aspect/zoomx;
	offsy= cumap->curr.ymin-but->aspect/zoomy;
	
	/* backdrop */
	if(cumap->flag & CUMA_DO_CLIP) {
		glColor3ubvShade((unsigned char *)wcol->inner, -20);
		glRectf(rect->xmin, rect->ymin, rect->xmax, rect->ymax);
		glColor3ubv((unsigned char*)wcol->inner);
		glRectf(rect->xmin + zoomx*(cumap->clipr.xmin-offsx),
				rect->ymin + zoomy*(cumap->clipr.ymin-offsy),
				rect->xmin + zoomx*(cumap->clipr.xmax-offsx),
				rect->ymin + zoomy*(cumap->clipr.ymax-offsy));
	}
	else {
		glColor3ubv((unsigned char*)wcol->inner);
		glRectf(rect->xmin, rect->ymin, rect->xmax, rect->ymax);
	}
		
	/* grid, every .25 step */
	glColor3ubvShade((unsigned char *)wcol->inner, -16);
	ui_draw_but_curve_grid(rect, zoomx, zoomy, offsx, offsy, 0.25f);
	/* grid, every 1.0 step */
	glColor3ubvShade((unsigned char *)wcol->inner, -24);
	ui_draw_but_curve_grid(rect, zoomx, zoomy, offsx, offsy, 1.0f);
	/* axes */
	glColor3ubvShade((unsigned char *)wcol->inner, -50);
	glBegin(GL_LINES);
	glVertex2f(rect->xmin, rect->ymin + zoomy*(-offsy));
	glVertex2f(rect->xmax, rect->ymin + zoomy*(-offsy));
	glVertex2f(rect->xmin + zoomx*(-offsx), rect->ymin);
	glVertex2f(rect->xmin + zoomx*(-offsx), rect->ymax);
	glEnd();
	
	/* magic trigger for curve backgrounds */
	if (but->a1 != -1) {
		if (but->a1 == UI_GRAD_H) {
			rcti grid;
			float col[3]= {0.0f, 0.0f, 0.0f}; /* dummy arg */
			
			grid.xmin = rect->xmin + zoomx*(-offsx);
			grid.xmax = rect->xmax + zoomx*(-offsx);
			grid.ymin = rect->ymin + zoomy*(-offsy);
			grid.ymax = rect->ymax + zoomy*(-offsy);
			
			glEnable(GL_BLEND);
			ui_draw_gradient(&grid, col, UI_GRAD_H, 0.5f);
			glDisable(GL_BLEND);
		}
	}
	
	
	/* cfra option */
	/* XXX 2.48
	if(cumap->flag & CUMA_DRAW_CFRA) {
		glColor3ub(0x60, 0xc0, 0x40);
		glBegin(GL_LINES);
		glVertex2f(rect->xmin + zoomx*(cumap->sample[0]-offsx), rect->ymin);
		glVertex2f(rect->xmin + zoomx*(cumap->sample[0]-offsx), rect->ymax);
		glEnd();
	}*/
	/* sample option */
	/* XXX 2.48
	 * if(cumap->flag & CUMA_DRAW_SAMPLE) {
		if(cumap->cur==3) {
			float lum= cumap->sample[0]*0.35f + cumap->sample[1]*0.45f + cumap->sample[2]*0.2f;
			glColor3ub(240, 240, 240);
			
			glBegin(GL_LINES);
			glVertex2f(rect->xmin + zoomx*(lum-offsx), rect->ymin);
			glVertex2f(rect->xmin + zoomx*(lum-offsx), rect->ymax);
			glEnd();
		}
		else {
			if(cumap->cur==0)
				glColor3ub(240, 100, 100);
			else if(cumap->cur==1)
				glColor3ub(100, 240, 100);
			else
				glColor3ub(100, 100, 240);
			
			glBegin(GL_LINES);
			glVertex2f(rect->xmin + zoomx*(cumap->sample[cumap->cur]-offsx), rect->ymin);
			glVertex2f(rect->xmin + zoomx*(cumap->sample[cumap->cur]-offsx), rect->ymax);
			glEnd();
		}
	}*/
	
	/* the curve */
	glColor3ubv((unsigned char*)wcol->item);
	glEnable(GL_LINE_SMOOTH);
	glEnable(GL_BLEND);
	glBegin(GL_LINE_STRIP);
	
	if(cuma->table==NULL)
		curvemapping_changed(cumap, 0);	/* 0 = no remove doubles */
	cmp= cuma->table;
	
	/* first point */
	if((cuma->flag & CUMA_EXTEND_EXTRAPOLATE)==0)
		glVertex2f(rect->xmin, rect->ymin + zoomy*(cmp[0].y-offsy));
	else {
		fx= rect->xmin + zoomx*(cmp[0].x-offsx + cuma->ext_in[0]);
		fy= rect->ymin + zoomy*(cmp[0].y-offsy + cuma->ext_in[1]);
		glVertex2f(fx, fy);
	}
	for(a=0; a<=CM_TABLE; a++) {
		fx= rect->xmin + zoomx*(cmp[a].x-offsx);
		fy= rect->ymin + zoomy*(cmp[a].y-offsy);
		glVertex2f(fx, fy);
	}
	/* last point */
	if((cuma->flag & CUMA_EXTEND_EXTRAPOLATE)==0)
		glVertex2f(rect->xmax, rect->ymin + zoomy*(cmp[CM_TABLE].y-offsy));	
	else {
		fx= rect->xmin + zoomx*(cmp[CM_TABLE].x-offsx - cuma->ext_out[0]);
		fy= rect->ymin + zoomy*(cmp[CM_TABLE].y-offsy - cuma->ext_out[1]);
		glVertex2f(fx, fy);
	}
	glEnd();
	glDisable(GL_LINE_SMOOTH);
	glDisable(GL_BLEND);

	/* the points, use aspect to make them visible on edges */
	cmp= cuma->curve;
	glPointSize(3.0f);
	bglBegin(GL_POINTS);
	for(a=0; a<cuma->totpoint; a++) {
		if(cmp[a].flag & SELECT)
			UI_ThemeColor(TH_TEXT_HI);
		else
			UI_ThemeColor(TH_TEXT);
		fac[0]= rect->xmin + zoomx*(cmp[a].x-offsx);
		fac[1]= rect->ymin + zoomy*(cmp[a].y-offsy);
		bglVertex2fv(fac);
	}
	bglEnd();
	glPointSize(1.0f);
	
	/* restore scissortest */
	glScissor(scissor[0], scissor[1], scissor[2], scissor[3]);

	/* outline */
	glColor3ubv((unsigned char*)wcol->outline);
	fdrawbox(rect->xmin, rect->ymin, rect->xmax, rect->ymax);
}
Пример #24
0
//--------------------------------------------------------------------------------------------------
/// Draw the legend using immediate mode OpenGL
//--------------------------------------------------------------------------------------------------
void OverlayColorLegend::renderLegendImmediateMode(OpenGLContext* oglContext, OverlayColorLegendLayoutInfo* layout)
{
#ifdef CVF_OPENGL_ES
    CVF_UNUSED(layout);
    CVF_FAIL_MSG("Not supported on OpenGL ES");
#else
    CVF_TIGHT_ASSERT(layout);
    CVF_TIGHT_ASSERT(layout->size.x() > 0);
    CVF_TIGHT_ASSERT(layout->size.y() > 0);

    Depth depth(false);
    depth.applyOpenGL(oglContext);

    Lighting_FF lighting(false);
    lighting.applyOpenGL(oglContext);

    // All vertices. Initialized here to set Z to zero once and for all.
    static float vertexArray[] = 
    {
        0.0f, 0.0f, 0.0f,
        0.0f, 0.0f, 0.0f,
        0.0f, 0.0f, 0.0f,
        0.0f, 0.0f, 0.0f,
        0.0f, 0.0f, 0.0f,
    };

    // Per vector convenience pointers
    float* v0 = &vertexArray[0];    
    float* v1 = &vertexArray[3];    
    float* v2 = &vertexArray[6];    
    float* v3 = &vertexArray[9];    
    float* v4 = &vertexArray[12];   

    // Constant coordinates
    v0[0] = v3[0] = layout->x0;
    v1[0] = v4[0] = layout->x1;

    // Render color bar as one colored quad per pixel

    int legendHeightPixelCount = static_cast<int>(layout->tickPixelPos->get(m_tickValues.size() - 1) - layout->tickPixelPos->get(0) + 0.01);
    if (m_scalarMapper.notNull())
    {
        int iPx;
        for (iPx = 0; iPx < legendHeightPixelCount; iPx++)
        {
            const Color3ub& clr = m_scalarMapper->mapToColor(m_scalarMapper->domainValue((iPx+0.5)/legendHeightPixelCount));
            float y0 = static_cast<float>(layout->legendRect.min().y() + iPx);
            float y1 = static_cast<float>(layout->legendRect.min().y() + iPx + 1);

            // Dynamic coordinates for rectangle
            v0[1] = v1[1] = y0;
            v3[1] = v4[1] = y1;

            // Draw filled rectangle elements
            glColor3ubv(clr.ptr());
            glBegin(GL_TRIANGLE_FAN);
            glVertex3fv(v0);
            glVertex3fv(v1);
            glVertex3fv(v4);
            glVertex3fv(v3);
            glEnd();
        }
    }

    // Render frame

    // Dynamic coordinates for  tickmarks-lines
    bool isRenderingFrame = true;
    if (isRenderingFrame)
    {
        v0[0] = v2[0] = layout->legendRect.min().x()-0.5f;
        v1[0] = v3[0] = layout->legendRect.max().x()-0.5f;
        v0[1] = v1[1] = layout->legendRect.min().y()-0.5f;
        v2[1] = v3[1] = layout->legendRect.max().y()-0.5f;

        glColor3fv(m_color.ptr());
        glBegin(GL_LINES);
        glVertex3fv(v0);
        glVertex3fv(v1);
        glVertex3fv(v1);
        glVertex3fv(v3);
        glVertex3fv(v3);
        glVertex3fv(v2);
        glVertex3fv(v2);
        glVertex3fv(v0);
        glEnd();

    }

    // Render tickmarks
    bool isRenderingTicks = true;

    if (isRenderingTicks)
    {
        // Constant coordinates
        v0[0] = layout->x0;
        v1[0] = layout->x1 - 0.5f*(layout->tickX - layout->x1) - 0.5f;
        v2[0] = layout->x1;
        v3[0] = layout->tickX - 0.5f*(layout->tickX - layout->x1) - 0.5f;
        v4[0] = layout->tickX;

        size_t ic;
        for (ic = 0; ic < m_tickValues.size(); ic++)
        {
            float y0 = static_cast<float>(layout->legendRect.min().y() + layout->tickPixelPos->get(ic) - 0.5f);

            // Dynamic coordinates for  tickmarks-lines
            v0[1] = v1[1] = v2[1] = v3[1] = v4[1] = y0;

            glColor3fv(m_color.ptr());
            glBegin(GL_LINES);
            if ( m_visibleTickLabels[ic])
            {
                glVertex3fv(v0);
                glVertex3fv(v4); 
            }
            else
            {
                glVertex3fv(v2);
                glVertex3fv(v3);
            }
            glEnd();
        }
    }

    // Reset render states
    Lighting_FF resetLighting;
    resetLighting.applyOpenGL(oglContext);
    Depth resetDepth;
    resetDepth.applyOpenGL(oglContext);

    CVF_CHECK_OGL(oglContext);
#endif // CVF_OPENGL_ES
}
Пример #25
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(getUniqueIDForDisplay());
	}

    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)
				ccGL::Vertex3v(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)
				{
					ccGL::Vertex3v(m_points[i].cloud->getPoint(m_points[i].index)->u);
					ccGL::Vertex3v(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);
					ccGL::Translate(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()); //takes rendering zoom into account!
				//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();
}
Пример #26
0
void ccRenderingTools::DrawColorRamp(const ccScalarField* sf, ccGLWindow* win, int glW, int glH, float renderZoom/*=1.0f*/)
{
	if (!sf || !sf->getColorScale())
		return;

	if (!win)
		return;

	bool logScale = sf->logScale();
	bool symmetricalScale = sf->symmetricalScale();
	bool alwaysShowZero = sf->isZeroAlwaysShown();
	
	//set of particular values
	//DGM: we work with doubles for maximum accuracy
	std::set<double> keyValues;
	if (!logScale)
	{
		keyValues.insert(sf->displayRange().min());
		keyValues.insert(sf->displayRange().start());
		keyValues.insert(sf->displayRange().stop());
		keyValues.insert(sf->displayRange().max());
		keyValues.insert(sf->saturationRange().min());
		keyValues.insert(sf->saturationRange().start());
		keyValues.insert(sf->saturationRange().stop());
		keyValues.insert(sf->saturationRange().max());

		if (symmetricalScale)
			keyValues.insert(-sf->saturationRange().max());

		if (alwaysShowZero)
			keyValues.insert(0.0);
	}
	else
	{
		ScalarType minDisp = sf->displayRange().min();
		ScalarType maxDisp = sf->displayRange().max();
		ConvertToLogScale(minDisp,maxDisp);
		keyValues.insert(minDisp);
		keyValues.insert(maxDisp);

		ScalarType startDisp = sf->displayRange().start();
		ScalarType stopDisp = sf->displayRange().stop();
		ConvertToLogScale(startDisp,stopDisp);
		keyValues.insert(startDisp);
		keyValues.insert(stopDisp);

		keyValues.insert(sf->saturationRange().min());
		keyValues.insert(sf->saturationRange().start());
		keyValues.insert(sf->saturationRange().stop());
		keyValues.insert(sf->saturationRange().max());
	}

	//magic fix (for infinite values!)
	{
		for (std::set<double>::iterator it = keyValues.begin(); it != keyValues.end(); ++it)
		{
#ifdef CC_WINDOWS
			if (!_finite(*it))
#else
			if (!std::isfinite(*it))
#endif
			{
				bool minusInf = (*it < 0);
				keyValues.erase(it);
				if (minusInf)
					keyValues.insert(-std::numeric_limits<ScalarType>::max());
				else
					keyValues.insert(std::numeric_limits<ScalarType>::max());
				it = keyValues.begin(); //restart the process (easier than trying to be intelligent here ;)
			}
		}
	}

	//Internally, the elements in a set are already sorted
	//std::sort(keyValues.begin(),keyValues.end());

	if (!sf->areNaNValuesShownInGrey())
	{
		//remove 'hidden' values
		if (!logScale)
		{
			for (std::set<double>::iterator it = keyValues.begin(); it != keyValues.end(); )
			{
				if (!sf->displayRange().isInRange(static_cast<ScalarType>(*it)) && (!alwaysShowZero || *it != 0)) //we keep zero if the user has explicitely asked for it!
				{
					std::set<double>::iterator toDelete = it;
					++it;
					keyValues.erase(toDelete);
				}
				else
				{
					++it;
				}
		}
		}
		else
		{
			//convert actual display range to log scale
			//(we can't do the opposite, otherwise we get accuracy/round-off issues!)
			ScalarType dispMin = sf->displayRange().start();
			ScalarType dispMax = sf->displayRange().stop();
			ConvertToLogScale(dispMin,dispMax);

			for (std::set<double>::iterator it = keyValues.begin(); it != keyValues.end(); )
			{
				if (*it >= dispMin && *it <= dispMax)
				{
					++it;
				}
				else
				{
					std::set<double>::iterator toDelete = it;
					++it;
					keyValues.erase(toDelete);
				}
			}
		}
	}

	const ccGui::ParamStruct& displayParams = win->getDisplayParameters();

	//default color: text color
	const unsigned char* textColor = displayParams.textDefaultCol;

	//histogram?
	const ccScalarField::Histogram histogram = sf->getHistogram();
	bool showHistogram = (displayParams.colorScaleShowHistogram && !logScale && histogram.maxValue != 0 && histogram.size() > 1);

	//display area
	QFont font = win->getTextDisplayFont(); //takes rendering zoom into account!
	const int strHeight = static_cast<int>(displayParams.defaultFontSize * renderZoom); //QFontMetrics(font).height() --> always returns the same value?!
	const int scaleWidth = static_cast<int>(displayParams.colorScaleRampWidth * renderZoom);
	const int scaleMaxHeight = (keyValues.size() > 1 ? std::max(glH-static_cast<int>(140 * renderZoom), 2*strHeight) : scaleWidth); //if 1 value --> we draw a cube

	//centered orthoprojective view (-halfW,-halfH,halfW,halfH)
	int halfW = (glW>>1);
	int halfH = (glH>>1);

	//top-right corner of the scale ramp
	const int xShift = static_cast<int>(20 * renderZoom) + (showHistogram ? scaleWidth/2 : 0);
	const int yShift = halfH-scaleMaxHeight/2 - static_cast<int>(10 * renderZoom);

	glPushAttrib(GL_LINE_BIT | GL_DEPTH_BUFFER_BIT);
	glEnable(GL_LINE_SMOOTH);
	glDisable(GL_DEPTH_TEST);
	
	std::vector<double> sortedKeyValues(keyValues.begin(),keyValues.end());
	double maxRange = sortedKeyValues.back()-sortedKeyValues.front();

	//const colorType* lineColor = ccColor::white;
	////clear background?
	//if (displayParams.backgroundCol[0] + displayParams.backgroundCol[1] + displayParams.backgroundCol[2] > 3*128)
	//	lineColor = ccColor::black;
	const colorType* lineColor = textColor;

	//display color ramp
	{
		//(x,y): current display area coordinates (top-left corner)
		int x = halfW-xShift-scaleWidth;
		int y = halfH-yShift-scaleMaxHeight;

		if (keyValues.size() > 1)
		{
			int histoStart = x+scaleWidth+std::min(std::max(scaleWidth/8,3),static_cast<int>(15 * renderZoom));

			glLineWidth(1.0f * renderZoom);
			glBegin(GL_LINES);
			for (int j=0; j<scaleMaxHeight; ++j)
			{
				double value = sortedKeyValues.front() + ((double)j * maxRange) / (double)scaleMaxHeight;
				if (logScale)
					value = exp(value*c_log10);
				const colorType* col = sf->getColor(static_cast<ScalarType>(value));
				glColor3ubv(col ? col : ccColor::lightGrey);

				glVertex2i(x,y+j);
				glVertex2i(x+scaleWidth,y+j);
				
				if (showHistogram)
				{
					double bind = (value-(double)sf->displayRange().min())*(double)(histogram.size()-1)/(double)sf->displayRange().maxRange();
					int bin = static_cast<int>(floor(bind));
					
					double hVal = 0.0;
					if (bin >= 0 && bin < (int)histogram.size()) //in symmetrical case we can get values outside of the real SF range
					{
						hVal = (double)histogram[bin];
						if (bin+1 < (int)histogram.size())
						{
							//linear interpolation
							double alpha = bind-(double)bin;
							hVal = (1.0-alpha) * hVal + alpha * (double)histogram[bin+1];
						}
					}

					int xSpan = std::max(static_cast<int>(hVal / (double)histogram.maxValue * (double)(scaleWidth/2)),1);
					glVertex2i(histoStart,y+j);
					glVertex2i(histoStart+xSpan,y+j);
				}
			}
			glEnd();
		}
		else
		{
			//if there's a unique (visible) scalar value, we only draw a square!
			double value = sortedKeyValues.front();
			if (logScale)
				value = exp(value*c_log10);
			const colorType* col = sf->getColor(static_cast<ScalarType>(value));
			glColor3ubv(col ? col : ccColor::lightGrey);
			glBegin(GL_POLYGON);
			glVertex2i(x,y);
			glVertex2i(x+scaleWidth,y);
			glVertex2i(x+scaleWidth,y+scaleMaxHeight-1);
			glVertex2i(x,y+scaleMaxHeight-1);
			glEnd();
		}

		//scale border
		glLineWidth(2.0f * renderZoom);
		glColor3ubv(lineColor);
		glBegin(GL_LINE_LOOP);
		glVertex2i(x,y);
		glVertex2i(x+scaleWidth,y);
		glVertex2i(x+scaleWidth,y+scaleMaxHeight);
		glVertex2i(x,y+scaleMaxHeight);
		glEnd();
	}

	//display labels
	{
		//list of labels to draw
		vlabelSet drawnLabels;

		//add first label
		drawnLabels.push_back(vlabel(0,0,strHeight,sortedKeyValues.front()));

		if (keyValues.size() > 1)
		{
			//add last label
			drawnLabels.push_back(vlabel(scaleMaxHeight,scaleMaxHeight-strHeight,scaleMaxHeight,sortedKeyValues.back()));
		}

		//we try to display the other keyPoints (if any)
		if (keyValues.size() > 2)
		{
			assert(maxRange > 0.0);
			const int minGap = strHeight;
			for (size_t i=1; i<keyValues.size()-1; ++i)
			{
				int yScale = static_cast<int>((sortedKeyValues[i]-sortedKeyValues[0]) * (double)scaleMaxHeight / maxRange);
				vlabelPair nLabels = GetVLabelsAround(yScale,drawnLabels);

				assert(nLabels.first != drawnLabels.end() && nLabels.second != drawnLabels.end());
				if (	(nLabels.first == drawnLabels.end() || nLabels.first->yMax <= yScale - minGap)
					&&	(nLabels.second == drawnLabels.end() || nLabels.second->yMin >= yScale + minGap))
				{
					//insert it at the right place (so as to keep a sorted list!)
					drawnLabels.insert(nLabels.second,vlabel(yScale,yScale-strHeight/2,yScale+strHeight/2,sortedKeyValues[i]));
				}
			}
		}

		//now we recursively display labels for which we have some room left
		if (drawnLabels.size() > 1)
		{
			const int minGap = strHeight*2;

			size_t drawnLabelsBefore = 0; //just to init the loop
			size_t drawnLabelsAfter = drawnLabels.size();

			//proceed until no more label can be inserted
			while (drawnLabelsAfter > drawnLabelsBefore)
			{
				drawnLabelsBefore = drawnLabelsAfter;

				vlabelSet::iterator it1 = drawnLabels.begin();
				vlabelSet::iterator it2 = it1; it2++;
				for (; it2 != drawnLabels.end(); ++it2)
				{
					if (it1->yMax + 2*minGap < it2->yMin)
					{
						//insert label
						double val = (it1->val + it2->val)/2.0;
						int yScale = static_cast<int>((val-sortedKeyValues[0]) * (double)scaleMaxHeight / maxRange);

						//insert it at the right place (so as to keep a sorted list!)
						drawnLabels.insert(it2,vlabel(yScale,yScale-strHeight/2,yScale+strHeight/2,val));
					}
					it1 = it2;
				}

				drawnLabelsAfter = drawnLabels.size();
			}
		}

		//display labels

		//Some versions of Qt seem to need glColorf instead of glColorub! (see https://bugreports.qt-project.org/browse/QTBUG-6217)
		glColor3f((float)textColor[0]/255.0f,(float)textColor[1]/255.0f,(float)textColor[2]/255.0f);

		//Scalar field name
		const char* sfName = sf->getName();
		if (sfName)
		{
			//QString sfTitle = QString("[%1]").arg(sfName);
			QString sfTitle(sfName);
			if (logScale)
				sfTitle += QString("[Log scale]");
			//we leave some (vertical) space for the top-most label!
			win->displayText(sfTitle, glW-xShift, glH-yShift+strHeight, ccGLWindow::ALIGN_HRIGHT | ccGLWindow::ALIGN_VTOP, 0, 0, &font);
		}

		//precision (same as color scale)
		const unsigned precision = displayParams.displayedNumPrecision;
		//format
		const char format = (sf->logScale() ? 'E' : 'f');
		//tick
		const int tickSize = static_cast<int>(4 * renderZoom);

		//for labels
		const int x = glW-xShift-scaleWidth-2*tickSize-1;
		const int y = glH-yShift-scaleMaxHeight;
		//for ticks
		const int xTick = halfW-xShift-scaleWidth-tickSize-1;
		const int yTick = halfH-yShift-scaleMaxHeight;

		for (vlabelSet::iterator it = drawnLabels.begin(); it != drawnLabels.end(); ++it)
		{
			vlabelSet::iterator itNext = it; itNext++;
			//position
			unsigned char align = ccGLWindow::ALIGN_HRIGHT;
			if (it == drawnLabels.begin())
				align |= ccGLWindow::ALIGN_VTOP;
			else if (itNext == drawnLabels.end())
				align |= ccGLWindow::ALIGN_VBOTTOM;
			else
				align |= ccGLWindow::ALIGN_VMIDDLE;

			double value = it->val;
			if (logScale)
				value = exp(value*c_log10);

			win->displayText(QString::number(value,format,precision), x, y+it->yPos, align, 0, 0, &font);
			glBegin(GL_LINES);
			glVertex2i(xTick,yTick+it->yPos);
			glVertex2i(xTick+tickSize,yTick+it->yPos);
			glEnd();
		}
	}

	glPopAttrib();
}
Пример #27
0
void ui_draw_but_NORMAL(uiBut *but, uiWidgetColors *wcol, rcti *rect)
{
	static GLuint displist = 0;
	int a, old[8];
	GLfloat diff[4], diffn[4] = {1.0f, 1.0f, 1.0f, 1.0f};
	float vec0[4] = {0.0f, 0.0f, 0.0f, 0.0f};
	float dir[4], size;
	
	/* store stuff */
	glGetMaterialfv(GL_FRONT, GL_DIFFUSE, diff);
		
	/* backdrop */
	glColor3ubv((unsigned char *)wcol->inner);
	uiSetRoundBox(UI_CNR_ALL);
	uiDrawBox(GL_POLYGON, rect->xmin, rect->ymin, rect->xmax, rect->ymax, 5.0f);
	
	/* sphere color */
	glMaterialfv(GL_FRONT, GL_DIFFUSE, diffn);
	glCullFace(GL_BACK);
	glEnable(GL_CULL_FACE);
	
	/* disable blender light */
	for (a = 0; a < 8; a++) {
		old[a] = glIsEnabled(GL_LIGHT0 + a);
		glDisable(GL_LIGHT0 + a);
	}
	
	/* own light */
	glEnable(GL_LIGHT7);
	glEnable(GL_LIGHTING);
	
	ui_get_but_vectorf(but, dir);

	dir[3] = 0.0f;   /* glLightfv needs 4 args, 0.0 is sun */
	glLightfv(GL_LIGHT7, GL_POSITION, dir); 
	glLightfv(GL_LIGHT7, GL_DIFFUSE, diffn); 
	glLightfv(GL_LIGHT7, GL_SPECULAR, vec0); 
	glLightf(GL_LIGHT7, GL_CONSTANT_ATTENUATION, 1.0f);
	glLightf(GL_LIGHT7, GL_LINEAR_ATTENUATION, 0.0f);
	
	/* transform to button */
	glPushMatrix();
	glTranslatef(rect->xmin + 0.5f * BLI_rcti_size_x(rect), rect->ymin + 0.5f * BLI_rcti_size_y(rect), 0.0f);
	
	if (BLI_rcti_size_x(rect) < BLI_rcti_size_y(rect))
		size = BLI_rcti_size_x(rect) / 200.f;
	else
		size = BLI_rcti_size_y(rect) / 200.f;
	
	glScalef(size, size, size);

	if (displist == 0) {
		GLUquadricObj *qobj;

		displist = glGenLists(1);
		glNewList(displist, GL_COMPILE);
		
		qobj = gluNewQuadric();
		gluQuadricDrawStyle(qobj, GLU_FILL);
		glShadeModel(GL_SMOOTH);
		gluSphere(qobj, 100.0, 32, 24);
		glShadeModel(GL_FLAT);
		gluDeleteQuadric(qobj);
		
		glEndList();
	}

	glCallList(displist);

	/* restore */
	glDisable(GL_LIGHTING);
	glDisable(GL_CULL_FACE);
	glMaterialfv(GL_FRONT, GL_DIFFUSE, diff); 
	glDisable(GL_LIGHT7);
	
	/* AA circle */
	glEnable(GL_BLEND);
	glEnable(GL_LINE_SMOOTH);
	glColor3ubv((unsigned char *)wcol->inner);
	glutil_draw_lined_arc(0.0f, M_PI * 2.0, 100.0f, 32);
	glDisable(GL_BLEND);
	glDisable(GL_LINE_SMOOTH);

	/* matrix after circle */
	glPopMatrix();

	/* enable blender light */
	for (a = 0; a < 8; a++) {
		if (old[a])
			glEnable(GL_LIGHT0 + a);
	}
}
Пример #28
0
void ccHObject::draw(CC_DRAW_CONTEXT& context)
{
    if (!isEnabled())
        return;

    //are we currently drawing objects in 2D or 3D?
    bool draw3D = MACRO_Draw3D(context);

    //the entity must be either visible and selected, and of course it should be displayed in this context
    bool drawInThisContext = ((m_visible || m_selected) && m_currentDisplay == context._win);

    //no need to display anything but clouds and meshes in "element picking mode"
    drawInThisContext &= (( !MACRO_DrawPointNames(context) || isKindOf(CC_POINT_CLOUD) ) ||
                          ( !MACRO_DrawTriangleNames(context) || isKindOf(CC_MESH) ));

    //apply 3D 'temporary' transformation (for display only)
    if (draw3D && m_glTransEnabled)
    {
        glMatrixMode(GL_MODELVIEW);
        glPushMatrix();
        glMultMatrixf(m_glTrans.data());
    }

    //draw entity
    if (m_visible && drawInThisContext)
    {
        if (( !m_selected || !MACRO_SkipSelected(context) ) &&
                ( m_selected || !MACRO_SkipUnselected(context) ))
        {
            //apply default color (in case of)
            glColor3ubv(context.pointsDefaultCol);

            drawMeOnly(context);

            //draw name in 3D (we display it in the 2D foreground layer in fact!)
            if (m_showNameIn3D && MACRO_Draw2D(context) && MACRO_Foreground(context) && !MACRO_DrawNames(context))
                drawNameIn3D(context);
        }
    }

    //draw entity's children
    for (Container::iterator it = m_children.begin(); it!=m_children.end(); ++it)
        (*it)->draw(context);

    //if the entity is currently selected, we draw its bounding-box
    if (m_selected && draw3D && drawInThisContext && !MACRO_DrawNames(context))
    {
        switch (m_selectionBehavior)
        {
        case SELECTION_AA_BBOX:
            drawBB(context.bbDefaultCol);
            break;
        case SELECTION_FIT_BBOX:
        {
            ccGLMatrix trans;
            ccBBox box = getFitBB(trans);
            if (box.isValid())
            {
                glMatrixMode(GL_MODELVIEW);
                glPushMatrix();
                glMultMatrixf(trans.data());
                box.draw(context.bbDefaultCol);
                glPopMatrix();
            }
        }
        break;
        case SELECTION_IGNORED:
            break;
        default:
            assert(false);
        }
    }

    if (draw3D && m_glTransEnabled)
        glPopMatrix();
}
Пример #29
0
static void draw_seq_extensions(Scene *scene, ARegion *ar, Sequence *seq)
{
	float x1, x2, y1, y2, pixely, a;
	unsigned char col[3], blendcol[3];
	View2D *v2d = &ar->v2d;
	
	if (seq->type >= SEQ_TYPE_EFFECT) return;

	x1 = seq->startdisp;
	x2 = seq->enddisp;
	
	y1 = seq->machine + SEQ_STRIP_OFSBOTTOM;
	y2 = seq->machine + SEQ_STRIP_OFSTOP;

	pixely = BLI_rctf_size_y(&v2d->cur) / BLI_rcti_size_y(&v2d->mask);
	
	if (pixely <= 0) return;  /* can happen when the view is split/resized */
	
	blendcol[0] = blendcol[1] = blendcol[2] = 120;

	if (seq->startofs) {
		glEnable(GL_BLEND);
		glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
		
		get_seq_color3ubv(scene, seq, col);
		
		if (seq->flag & SELECT) {
			UI_GetColorPtrBlendShade3ubv(col, blendcol, col, 0.3, -40);
			glColor4ub(col[0], col[1], col[2], 170);
		}
		else {
			UI_GetColorPtrBlendShade3ubv(col, blendcol, col, 0.6, 0);
			glColor4ub(col[0], col[1], col[2], 110);
		}
		
		glRectf((float)(seq->start), y1 - SEQ_STRIP_OFSBOTTOM, x1, y1);
		
		if (seq->flag & SELECT) glColor4ub(col[0], col[1], col[2], 255);
		else glColor4ub(col[0], col[1], col[2], 160);

		fdrawbox((float)(seq->start), y1 - SEQ_STRIP_OFSBOTTOM, x1, y1);  //outline
		
		glDisable(GL_BLEND);
	}
	if (seq->endofs) {
		glEnable(GL_BLEND);
		glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
		
		get_seq_color3ubv(scene, seq, col);
		
		if (seq->flag & SELECT) {
			UI_GetColorPtrBlendShade3ubv(col, blendcol, col, 0.3, -40);
			glColor4ub(col[0], col[1], col[2], 170);
		}
		else {
			UI_GetColorPtrBlendShade3ubv(col, blendcol, col, 0.6, 0);
			glColor4ub(col[0], col[1], col[2], 110);
		}
		
		glRectf(x2, y2, (float)(seq->start + seq->len), y2 + SEQ_STRIP_OFSBOTTOM);
		
		if (seq->flag & SELECT) glColor4ub(col[0], col[1], col[2], 255);
		else glColor4ub(col[0], col[1], col[2], 160);

		fdrawbox(x2, y2, (float)(seq->start + seq->len), y2 + SEQ_STRIP_OFSBOTTOM); //outline
		
		glDisable(GL_BLEND);
	}
	if (seq->startstill) {
		get_seq_color3ubv(scene, seq, col);
		UI_GetColorPtrBlendShade3ubv(col, blendcol, col, 0.75, 40);
		glColor3ubv((GLubyte *)col);
		
		draw_shadedstrip(seq, col, x1, y1, (float)(seq->start), y2);
		
		/* feint pinstripes, helps see exactly which is extended and which isn't,
		 * especially when the extension is very small */ 
		if (seq->flag & SELECT) UI_GetColorPtrBlendShade3ubv(col, col, col, 0.0, 24);
		else UI_GetColorPtrShade3ubv(col, col, -16);
		
		glColor3ubv((GLubyte *)col);
		
		for (a = y1; a < y2; a += pixely * 2.0f) {
			fdrawline(x1,  a,  (float)(seq->start),  a);
		}
	}
	if (seq->endstill) {
		get_seq_color3ubv(scene, seq, col);
		UI_GetColorPtrBlendShade3ubv(col, blendcol, col, 0.75, 40);
		glColor3ubv((GLubyte *)col);
		
		draw_shadedstrip(seq, col, (float)(seq->start + seq->len), y1, x2, y2);
		
		/* feint pinstripes, helps see exactly which is extended and which isn't,
		 * especially when the extension is very small */ 
		if (seq->flag & SELECT) UI_GetColorPtrShade3ubv(col, col, 24);
		else UI_GetColorPtrShade3ubv(col, col, -16);
		
		glColor3ubv((GLubyte *)col);
		
		for (a = y1; a < y2; a += pixely * 2.0f) {
			fdrawline((float)(seq->start + seq->len),  a,  x2,  a);
		}
	}
}
Пример #30
0
void testApp::drawMesh() {
	bool* mask = threePhase->getMask();
	float* depth = threePhase->getDepth();
	byte* color = threePhase->getColor();

	int srcWidth = threePhase->getWidth();
	int srcHeight = threePhase->getHeight();

	glBegin(GL_TRIANGLES);
	for (int y = 0; y < srcHeight - 1; y++) {
		for (int x = 0; x < srcWidth - 1; x++) {
			int nw = y * srcWidth + x;
			int ne = nw + 1;
			int sw = nw + srcWidth;
			int se = ne + srcWidth;
			if (!mask[nw] && !mask[se]) {
				if (!mask[ne]) { // nw, ne, se
					glColor3ubv(&color[nw * 3]);
					glVertex3f(x, y, depth[nw]);
					glColor3ubv(&color[ne * 3]);
					glVertex3f(x + 1, y, depth[ne]);
					glColor3ubv(&color[se * 3]);
					glVertex3f(x + 1, y + 1, depth[se]);
				}
				if (!mask[sw]) { // nw, se, sw
					glColor3ubv(&color[nw * 3]);
					glVertex3f(x, y, depth[nw]);
					glColor3ubv(&color[se * 3]);
					glVertex3f(x + 1, y + 1, depth[se]);
					glColor3ubv(&color[sw * 3]);
					glVertex3f(x, y + 1, depth[sw]);
				}
			} else if (!mask[ne] && !mask[sw]) {
				if (!mask[nw]) { // nw, ne, sw
					glColor3ubv(&color[nw * 3]);
					glVertex3f(x, y, depth[nw]);
					glColor3ubv(&color[ne * 3]);
					glVertex3f(x + 1, y, depth[ne]);
					glColor3ubv(&color[sw * 3]);
					glVertex3f(x, y + 1, depth[sw]);
				}
				if (!mask[se]) { // ne, se, sw
					glColor3ubv(&color[ne * 3]);
					glVertex3f(x + 1, y, depth[ne]);
					glColor3ubv(&color[se * 3]);
					glVertex3f(x + 1, y + 1, depth[se]);
					glColor3ubv(&color[sw * 3]);
					glVertex3f(x, y + 1, depth[sw]);
				}
			}
		}
	}
	glEnd();
}