Beispiel #1
0
/* Draw a 4d embedding of the projective plane projected into 3D. */
static int projective_plane(ModeInfo *mi, double umin, double umax,
                            double vmin, double vmax)
{
  int polys = 0;
  static const GLfloat mat_diff_red[]         = { 1.0, 0.0, 0.0, 1.0 };
  static const GLfloat mat_diff_green[]       = { 0.0, 1.0, 0.0, 1.0 };
  static const GLfloat mat_diff_trans_red[]   = { 1.0, 0.0, 0.0, 0.7 };
  static const GLfloat mat_diff_trans_green[] = { 0.0, 1.0, 0.0, 0.7 };
  float p[3], pu[3], pv[3], pm[3], n[3], b[3], mat[4][4];
  int i, j, k, l, m, o;
  double u, v;
  double xx[4], xxu[4], xxv[4], y[4], yu[4], yv[4];
  double q, r, s, t;
  double cu, su, cv2, sv2, cv4, sv4, c2u, s2u;
  float q1[4], q2[4], r1[4][4], r2[4][4];
  projectiveplanestruct *pp = &projectiveplane[MI_SCREEN(mi)];

  if (view == VIEW_WALK || view == VIEW_WALKTURN)
  {
    /* Compute the rotation that rotates the projective plane in 4D without
       the trackball rotations. */
    rotateall4d(pp->zeta,pp->eta,pp->theta,mat);

    u = pp->umove;
    v = pp->vmove;
    cu = cos(u);
    su = sin(u);
    c2u = cos(2.0*u);
    s2u = sin(2.0*u);
    sv2 = sin(0.5*v);
    cv4 = cos(0.25*v);
    sv4 = sin(0.25*v);
    xx[0] = 0.5*s2u*sv4*sv4;
    xx[1] = 0.5*su*sv2;
    xx[2] = 0.5*cu*sv2;
    xx[3] = 0.5*(su*su*sv4*sv4-cv4*cv4);
    /* Avoid degenerate tangential plane basis vectors. */
    if (v < FLT_EPSILON)
      v = FLT_EPSILON;
    cv2 = cos(0.5*v);
    sv2 = sin(0.5*v);
    sv4 = sin(0.25*v);
    xxu[0] = c2u*sv4*sv4;
    xxu[1] = 0.5*cu*sv2;
    xxu[2] = -0.5*su*sv2;
    xxu[3] = 0.5*s2u*sv4*sv4;
    xxv[0] = 0.125*s2u*sv2;
    xxv[1] = 0.25*su*cv2;
    xxv[2] = 0.25*cu*cv2;
    xxv[3] = 0.125*(su*su+1.0)*sv2;
    for (l=0; l<4; l++)
    {
      y[l] = (mat[l][0]*xx[0]+mat[l][1]*xx[1]+
              mat[l][2]*xx[2]+mat[l][3]*xx[3]);
      yu[l] = (mat[l][0]*xxu[0]+mat[l][1]*xxu[1]+
               mat[l][2]*xxu[2]+mat[l][3]*xxu[3]);
      yv[l] = (mat[l][0]*xxv[0]+mat[l][1]*xxv[1]+
               mat[l][2]*xxv[2]+mat[l][3]*xxv[3]);
    }
    if (projection_4d == DISP_4D_ORTHOGRAPHIC)
    {
      for (l=0; l<3; l++)
      {
        p[l] = y[l]+pp->offset4d[l];
        pu[l] = yu[l];
        pv[l] = yv[l];
      }
    }
    else
    {
      s = y[3]+pp->offset4d[3];
      q = 1.0/s;
      t = q*q;
      for (l=0; l<3; l++)
      {
        r = y[l]+pp->offset4d[l];
        p[l] = r*q;
        pu[l] = (yu[l]*s-r*yu[3])*t;
        pv[l] = (yv[l]*s-r*yv[3])*t;
      }
    }
    n[0] = pu[1]*pv[2]-pu[2]*pv[1];
    n[1] = pu[2]*pv[0]-pu[0]*pv[2];
    n[2] = pu[0]*pv[1]-pu[1]*pv[0];
    t = 1.0/(pp->side*4.0*sqrt(n[0]*n[0]+n[1]*n[1]+n[2]*n[2]));
    n[0] *= t;
    n[1] *= t;
    n[2] *= t;
    pm[0] = pu[0]*pp->dumove+pv[0]*pp->dvmove;
    pm[1] = pu[1]*pp->dumove+pv[1]*pp->dvmove;
    pm[2] = pu[2]*pp->dumove+pv[2]*pp->dvmove;
    t = 1.0/(4.0*sqrt(pm[0]*pm[0]+pm[1]*pm[1]+pm[2]*pm[2]));
    pm[0] *= t;
    pm[1] *= t;
    pm[2] *= t;
    b[0] = n[1]*pm[2]-n[2]*pm[1];
    b[1] = n[2]*pm[0]-n[0]*pm[2];
    b[2] = n[0]*pm[1]-n[1]*pm[0];
    t = 1.0/(4.0*sqrt(b[0]*b[0]+b[1]*b[1]+b[2]*b[2]));
    b[0] *= t;
    b[1] *= t;
    b[2] *= t;

    /* Compute alpha, beta, delta from the three basis vectors.
           |  -b[0]  -b[1]  -b[2] |
       m = |   n[0]   n[1]   n[2] |
           | -pm[0] -pm[1] -pm[2] |
    */
    pp->alpha = atan2(-n[2],-pm[2])*180/M_PI;
    pp->beta = atan2(-b[2],sqrt(b[0]*b[0]+b[1]*b[1]))*180/M_PI;
    pp->delta = atan2(b[1],-b[0])*180/M_PI;

    /* Compute the rotation that rotates the projective plane in 4D. */
    rotateall(pp->alpha,pp->beta,pp->delta,pp->zeta,pp->eta,pp->theta,mat);

    u = pp->umove;
    v = pp->vmove;
    cu = cos(u);
    su = sin(u);
    s2u = sin(2.0*u);
    sv2 = sin(0.5*v);
    cv4 = cos(0.25*v);
    sv4 = sin(0.25*v);
    xx[0] = 0.5*s2u*sv4*sv4;
    xx[1] = 0.5*su*sv2;
    xx[2] = 0.5*cu*sv2;
    xx[3] = 0.5*(su*su*sv4*sv4-cv4*cv4);
    for (l=0; l<4; l++)
    {
      r = 0.0;
      for (m=0; m<4; m++)
        r += mat[l][m]*xx[m];
      y[l] = r;
    }
    if (projection_4d == DISP_4D_ORTHOGRAPHIC)
    {
      for (l=0; l<3; l++)
        p[l] = y[l]+pp->offset4d[l];
    }
    else
    {
      s = y[3]+pp->offset4d[3];
      for (l=0; l<3; l++)
        p[l] = (y[l]+pp->offset4d[l])/s;
    }

    pp->offset3d[0] = -p[0];
    pp->offset3d[1] = -p[1]-DELTAY;
    pp->offset3d[2] = -p[2];
  }
  else
  {
    /* Compute the rotation that rotates the projective plane in 4D,
       including the trackball rotations. */
    rotateall(pp->alpha,pp->beta,pp->delta,pp->zeta,pp->eta,pp->theta,r1);

    gltrackball_get_quaternion(pp->trackballs[0],q1);
    gltrackball_get_quaternion(pp->trackballs[1],q2);
    quats_to_rotmat(q1,q2,r2);

    mult_rotmat(r2,r1,mat);
  }

  /* Project the points from 4D to 3D. */
  for (i=0; i<=NUMV; i++)
  {
    for (j=0; j<=NUMU; j++)
    {
      o = i*(NUMU+1)+j;
      for (l=0; l<4; l++)
      {
        y[l] = (mat[l][0]*pp->x[o][0]+mat[l][1]*pp->x[o][1]+
                mat[l][2]*pp->x[o][2]+mat[l][3]*pp->x[o][3]);
        yu[l] = (mat[l][0]*pp->xu[o][0]+mat[l][1]*pp->xu[o][1]+
                 mat[l][2]*pp->xu[o][2]+mat[l][3]*pp->xu[o][3]);
        yv[l] = (mat[l][0]*pp->xv[o][0]+mat[l][1]*pp->xv[o][1]+
                 mat[l][2]*pp->xv[o][2]+mat[l][3]*pp->xv[o][3]);
      }
      if (projection_4d == DISP_4D_ORTHOGRAPHIC)
      {
        for (l=0; l<3; l++)
        {
          pp->pp[o][l] = (y[l]+pp->offset4d[l])+pp->offset3d[l];
          pu[l] = yu[l];
          pv[l] = yv[l];
        }
      }
      else
      {
        s = y[3]+pp->offset4d[3];
        q = 1.0/s;
        t = q*q;
        for (l=0; l<3; l++)
        {
          r = y[l]+pp->offset4d[l];
          pp->pp[o][l] = r*q+pp->offset3d[l];
          pu[l] = (yu[l]*s-r*yu[3])*t;
          pv[l] = (yv[l]*s-r*yv[3])*t;
        }
      }
      pp->pn[o][0] = pu[1]*pv[2]-pu[2]*pv[1];
      pp->pn[o][1] = pu[2]*pv[0]-pu[0]*pv[2];
      pp->pn[o][2] = pu[0]*pv[1]-pu[1]*pv[0];
      t = 1.0/sqrt(pp->pn[o][0]*pp->pn[o][0]+pp->pn[o][1]*pp->pn[o][1]+
                   pp->pn[o][2]*pp->pn[o][2]);
      pp->pn[o][0] *= t;
      pp->pn[o][1] *= t;
      pp->pn[o][2] *= t;
    }
  }

  if (colors == COLORS_TWOSIDED)
  {
    glColor3fv(mat_diff_red);
    if (display_mode == DISP_TRANSPARENT)
    {
      glMaterialfv(GL_FRONT,GL_AMBIENT_AND_DIFFUSE,mat_diff_trans_red);
      glMaterialfv(GL_BACK,GL_AMBIENT_AND_DIFFUSE,mat_diff_trans_green);
    }
    else
    {
      glMaterialfv(GL_FRONT,GL_AMBIENT_AND_DIFFUSE,mat_diff_red);
      glMaterialfv(GL_BACK,GL_AMBIENT_AND_DIFFUSE,mat_diff_green);
    }
  }
  glBindTexture(GL_TEXTURE_2D,pp->tex_name);

  if (appearance != APPEARANCE_DIRECTION_BANDS)
  {
    for (i=0; i<NUMV; i++)
    {
      if (appearance == APPEARANCE_DISTANCE_BANDS &&
          ((i & (NUMB-1)) >= NUMB/4) && ((i & (NUMB-1)) < 3*NUMB/4))
        continue;
      if (display_mode == DISP_WIREFRAME)
        glBegin(GL_QUAD_STRIP);
      else
        glBegin(GL_TRIANGLE_STRIP);
      for (j=0; j<=NUMU; j++)
      {
        for (k=0; k<=1; k++)
        {
          l = (i+k);
          m = j;
          o = l*(NUMU+1)+m;
          glNormal3fv(pp->pn[o]);
          glTexCoord2fv(pp->tex[o]);
          if (colors != COLORS_TWOSIDED)
          {
            glColor3fv(pp->col[o]);
            glMaterialfv(GL_FRONT_AND_BACK,GL_AMBIENT_AND_DIFFUSE,pp->col[o]);
          }
          glVertex3fv(pp->pp[o]);
          polys++;
        }
      }
      glEnd();
    }
  }
  else /* appearance == APPEARANCE_DIRECTION_BANDS */
  {
    for (j=0; j<NUMU; j++)
    {
      if ((j & (NUMB-1)) >= NUMB/2)
        continue;
      if (display_mode == DISP_WIREFRAME)
        glBegin(GL_QUAD_STRIP);
      else
        glBegin(GL_TRIANGLE_STRIP);
      for (i=0; i<=NUMV; i++)
      {
        for (k=0; k<=1; k++)
        {
          l = i;
          m = (j+k);
          o = l*(NUMU+1)+m;
          glNormal3fv(pp->pn[o]);
          glTexCoord2fv(pp->tex[o]);
          if (colors != COLORS_TWOSIDED)
          {
            glColor3fv(pp->col[o]);
            glMaterialfv(GL_FRONT_AND_BACK,GL_AMBIENT_AND_DIFFUSE,pp->col[o]);
          }
          glVertex3fv(pp->pp[o]);
          polys++;
        }
      }
      glEnd();
    }
  }

  polys /= 2;
  return polys;
}
Beispiel #2
0
void hack_draw (xstuff_t * XStuff, double currentTime, float frameTime)
{
	int i;
	static int ionsReleased = 0;
	static float releaseTime = 0.0f;
	Display *dpy = XStuff->display;
#ifdef BENCHMARK
	static int a = 1;
#endif

	Window window = XStuff->window;

	elapsedTime = frameTime;

#ifdef BENCHMARK
	if (a++ == 1000)
		exit(0);
	elapsedTime = 0.1f;
#endif

	// Camera movements
	// first do translation (distance from center)
	static float oldCameraDistance;
	static float cameraDistance;
	static float targetCameraDistance = -1000.0f;
	static float preCameraInterp = PI;
	float cameraInterp;

	preCameraInterp += float (dCameraspeed) * elapsedTime * 0.01f;

	cameraInterp = 0.5f - (0.5f * cos (preCameraInterp));
	cameraDistance = (1.0f - cameraInterp) * oldCameraDistance + cameraInterp * targetCameraDistance;

	if (preCameraInterp >= PI) {
		oldCameraDistance = targetCameraDistance;
		targetCameraDistance = -rsRandf (1300.0f) - 200.0f;
		preCameraInterp = 0.0f;
	}

	glMatrixMode (GL_MODELVIEW);
	glLoadIdentity ();
	glTranslatef (0.0, 0.0, cameraDistance);

	// then do rotation
	static rsVec radialVel = rsVec (0.0f, 0.0f, 0.0f);
	static rsVec targetRadialVel = radialVel;
	static rsQuat rotQuat = rsQuat (0.0f, 0.0f, 0.0f, 1.0f);

	rsVec radialVelDiff = targetRadialVel - radialVel;
	float changeRemaining = radialVelDiff.normalize ();
	float change = float (dCameraspeed) * 0.0002f * elapsedTime;

	if (changeRemaining > change) {
		radialVelDiff *= change;
		radialVel += radialVelDiff;
	} else {
		radialVel = targetRadialVel;
		if (rsRandi (2)) {
			targetRadialVel = rsVec (rsRandf (1.0f), rsRandf (1.0f), rsRandf (1.0f));
			targetRadialVel.normalize ();
			targetRadialVel *= float (dCameraspeed) * rsRandf (0.002f);
		} else
			targetRadialVel = rsVec (0.0f, 0.0f, 0.0f);
	}

	rsVec tempRadialVel = radialVel;
	float angle = tempRadialVel.normalize ();

	rsQuat radialQuat;

	radialQuat.make (angle, tempRadialVel[0], tempRadialVel[1], tempRadialVel[2]);
	rotQuat.preMult (radialQuat);
	rsMatrix rotMat;

	rotMat.fromQuat (rotQuat);

	// make billboard matrix for rotating particles when they are drawn
	rotMat.get (billboardMat);

	// Calculate new color
	static rsVec oldHsl, newHsl = rsVec (rsRandf (1.0f), 1.0f, 1.0f), targetHsl;
	static float colorInterp = 1.0f, colorChange;

	colorInterp += elapsedTime * colorChange;
	if (colorInterp >= 1.0f) {
		if (!rsRandi (3) && dIons >= 100)	// change color suddenly
			newHsl = rsVec (rsRandf (1.0f), 1.0f - (rsRandf (1.0f) * rsRandf (1.0f)), 1.0f);
		oldHsl = newHsl;
		targetHsl = rsVec (rsRandf (1.0f), 1.0f - (rsRandf (1.0f) * rsRandf (1.0f)), 1.0f);
		colorInterp = 0.0f;
		// amount by which to change colorInterp each second
		colorChange = rsRandf (0.005f * float (dSpeed)) + (0.002f * float (dSpeed));
	} else {
		float diff = targetHsl[0] - oldHsl[0];

		if (diff < -0.5f || (diff > 0.0f && diff < 0.5f))
			newHsl[0] = oldHsl[0] + colorInterp * diff;
		else
			newHsl[0] = oldHsl[0] - colorInterp * diff;
		diff = targetHsl[1] - oldHsl[1];
		newHsl[1] = oldHsl[1] + colorInterp * diff;
		if (newHsl[0] < 0.0f)
			newHsl[0] += 1.0f;
		if (newHsl[0] > 1.0f)
			newHsl[0] -= 1.0f;
		hsl2rgb (newHsl[0], newHsl[1], 1.0f, newRgb[0], newRgb[1], newRgb[2]);
	}

	// Release ions
	if (ionsReleased < dIons) {
		releaseTime -= elapsedTime;
		while (ionsReleased < dIons && releaseTime <= 0.0f) {
			ilist[ionsReleased].start ();
			ionsReleased++;
			// all ions released after 2 minutes
			releaseTime += 120.0f / float (dIons);
		}
	}
	// Set interpolation value for emitters and attracters
	static float wait = 0.0f;
	static float preinterp = PI, interp;
	static float interpconst = 0.001f;

	wait -= elapsedTime;
	if (wait <= 0.0f) {
		preinterp += elapsedTime * float (dSpeed) * interpconst;

		interp = 0.5f - (0.5f * cos (preinterp));
	}
	if (preinterp >= PI) {
		// select new taget points (not the same pattern twice in a row)
		static int newTarget = 0, lastTarget;

		lastTarget = newTarget;
		newTarget = rsRandi (10);
		if (newTarget == lastTarget)
			newTarget++;
		setTargets (newTarget);
		preinterp = 0.0f;
		interp = 0.0f;
		wait = 10.0f;	// pause after forming each new pattern
		interpconst = 0.001f;
		if (!rsRandi (4))	// interpolate really fast sometimes
			interpconst = 0.1f;
	}
	// Update particles
	for (i = 0; i < dEmitters; i++) {
		elist[i].interppos (interp);
		elist[i].update ();
	}
	for (i = 0; i < dAttracters; i++) {
		alist[i].interppos (interp);
		alist[i].update ();
	}
	for (i = 0; i < ionsReleased; i++)
		ilist[i].update ();

	// Calculate surface
	if (dSurface) {
		for (i = 0; i < dEmitters; i++)
			spheres[i].setPosition (elist[i].pos[0], elist[i].pos[1], elist[i].pos[2]);
		for (i = 0; i < dAttracters; i++)
			spheres[dEmitters + i].setPosition (alist[i].pos[0], alist[i].pos[1], alist[i].pos[2]);

		impCrawlPointVector cpv;
		for(i=0; i<dEmitters+dAttracters; i++)
			spheres[i].addCrawlPoint(cpv);

		surface->reset ();

		static float valuetrig = 0.0f;
		valuetrig += elapsedTime;

		volume->setSurfaceValue(0.45f + 0.05f * cosf(valuetrig));
		volume->makeSurface(cpv);
	}
	// Draw
	// clear the screen
	if (dBlur) {		// partially
		glMatrixMode (GL_PROJECTION);
		glPushMatrix ();
			glLoadIdentity();
			glOrtho(0.0, 1.0, 0.0, 1.0, 1.0, -1.0);
			glMatrixMode(GL_MODELVIEW);
			glPushMatrix();
				glLoadIdentity();
				glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
				glColor4f(0.0f, 0.0f, 0.0f, 0.5f - (float(sqrtf(sqrtf(float(dBlur)))) * 0.15495f));
				glBegin(GL_TRIANGLE_STRIP);
					glVertex3f(0.0f, 0.0f, 0.0f);
					glVertex3f(1.0f, 0.0f, 0.0f);
					glVertex3f(0.0f, 1.0f, 0.0f);
					glVertex3f(1.0f, 1.0f, 0.0f);
			glEnd();
		glPopMatrix();
		glMatrixMode(GL_PROJECTION);
		glPopMatrix();
	} else			// completely
		glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	// Draw ions
	glMatrixMode(GL_MODELVIEW);
	glBlendFunc (GL_ONE, GL_ONE);
	glBindTexture (GL_TEXTURE_2D, 1);
	for (i = 0; i < ionsReleased; i++)
		ilist[i].draw ();

	// Draw surfaces
	float brightFactor = 0;
	float surfaceColor[3] = {
		0.0f,
		0.0f,
		0.0f
	};

	if (dSurface) {
		glBindTexture (GL_TEXTURE_2D, 2);
		glEnable (GL_TEXTURE_GEN_S);
		glEnable (GL_TEXTURE_GEN_T);
		// find color for surfaces
		if (dIons >= 100) {
			if (dWireframe)
				brightFactor = 2.0f / (float (dBlur + 30) * float (dBlur + 30));
			else
				brightFactor = 4.0f / (float (dBlur + 30) * float (dBlur + 30));
			for (i = 0; i < 100; i++) {
				surfaceColor[0] += ilist[i].rgb[0] * brightFactor;
				surfaceColor[1] += ilist[i].rgb[1] * brightFactor;
				surfaceColor[2] += ilist[i].rgb[2] * brightFactor;
			}
			glColor3fv (surfaceColor);
		} else {
			if (dWireframe)
				brightFactor = 200.0f / (float (dBlur + 30) * float (dBlur + 30));
			else
				brightFactor = 400.0f / (float (dBlur + 30) * float (dBlur + 30));
			glColor3f (newRgb[0] * brightFactor, newRgb[1] * brightFactor, newRgb[2] * brightFactor);
		}
		// draw the surface
		glPushMatrix ();
		glMultMatrixf (billboardMat);
		if (dWireframe) {
			glDisable (GL_TEXTURE_2D);
			surface->draw_wireframe ();
			glEnable (GL_TEXTURE_2D);
		} else
			surface->draw ();
		glPopMatrix ();
		glDisable (GL_TEXTURE_GEN_S);
		glDisable (GL_TEXTURE_GEN_T);
	}
	// If graphics card does a true buffer swap instead of a copy swap
	// then everything must get drawn on both buffers
	if (dBlur & pfd_swap_exchange) {
		glXSwapBuffers (dpy, window);
		// wglSwapLayerBuffers(hdc, WGL_SWAP_MAIN_PLANE);
		glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
		glColor4f (0.0f, 0.0f, 0.0f, 0.5f - (float (sqrt (sqrt (double (dBlur)))) * 0.15495f));

		glPushMatrix ();
		glLoadIdentity ();
		glBegin (GL_TRIANGLE_STRIP);
		glVertex3f (-5.0f, -4.0f, -3.0f);
		glVertex3f (5.0f, -4.0f, -3.0f);
		glVertex3f (-5.0f, 4.0f, -3.0f);
		glVertex3f (5.0f, 4.0f, -3.0f);
		glEnd ();
		glPopMatrix ();

		// Draw ions
		glBlendFunc (GL_ONE, GL_ONE);
		glBindTexture (GL_TEXTURE_2D, 1);
		for (i = 0; i < ionsReleased; i++)
			ilist[i].draw ();

		// Draw surfaces
		if (dSurface) {
			glBindTexture (GL_TEXTURE_2D, 2);
			glEnable (GL_TEXTURE_GEN_S);
			glEnable (GL_TEXTURE_GEN_T);
			if (dIons >= 100)
				glColor3fv (surfaceColor);
			else
				glColor3f (newRgb[0] * brightFactor, newRgb[1] * brightFactor, newRgb[2] * brightFactor);
			glPushMatrix ();
			glMultMatrixf (billboardMat);
			if (dWireframe) {
				glDisable (GL_TEXTURE_2D);
				surface->draw_wireframe ();
				glEnable (GL_TEXTURE_2D);
			} else
				surface->draw ();
			glPopMatrix ();
			glDisable (GL_TEXTURE_GEN_S);
			glDisable (GL_TEXTURE_GEN_T);
		}
	}
}
Beispiel #3
0
enum piglit_result
piglit_display(void)
{
	GLboolean pass = GL_TRUE;
	float array[] = {
		10, 10,	   1, 0, 0,
		27, 10,	   1, 0, 0,
		10, 30,	   1, 0, 0,

		30, 10,	   0, 1, 0,
		47, 10,	   0, 1, 0,
		30, 30,	   0, 1, 0,

		50, 10,	   0, 0, 1,
		67, 10,	   0, 0, 1,
		50, 30,	   0, 0, 1,

		70, 10,	   1, 0, 1,
		87, 10,	   1, 0, 1,
		70, 30,	   1, 0, 1
	};
	float seccol[] = {
		0.2, 0.2, 0.2,
		0.2, 0.2, 0.2,
		0.2, 0.2, 0.2,

		0.2, 0.2, 0.2,
		0.2, 0.2, 0.2,
		0.2, 0.2, 0.2,

		0.2, 0.2, 0.2,
		0.2, 0.2, 0.2,
		0.2, 0.2, 0.2,

		0.2, 0.2, 0.2,
		0.2, 0.2, 0.2,
		0.2, 0.2, 0.2,
	     };
	float c0[] = {1, 0.2, 0.2};
	float c1[] = {0.2, 1, 0.2};
	float c2[] = {0.2, 0.2, 1};
	float c3[] = {1, 0.2, 1};
	short indices[] = {
		0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11
	};
	int i, j;

	piglit_ortho_projection(piglit_width, piglit_height, GL_FALSE);

	printf("From bottom to top:\n");

	glEnable(GL_COLOR_SUM);
	glLoadIdentity();

	/* State change: Vertex arrays. */
	glVertexPointer(2, GL_FLOAT, 20, array);
	glColorPointer(3, GL_FLOAT, 20, array + 2);
	glSecondaryColorPointer(3, GL_FLOAT, 0, seccol);
	glEnableClientState(GL_VERTEX_ARRAY);
	glEnableClientState(GL_COLOR_ARRAY);
	glEnableClientState(GL_SECONDARY_COLOR_ARRAY);

	/* The vertex array state should be preserved after glClear. */
	glClear(GL_COLOR_BUFFER_BIT);

	/* Draw. */
	printf("DrawElements\n");
	for (i = 0; i < 4; i++)
		glDrawElements(GL_TRIANGLES, 3, GL_UNSIGNED_SHORT, indices + i*3);

	/* State change: Constant buffer. */
	glTranslatef(0, 30, 0);

	rotate_colors(array);

	/* Draw. */
	printf("DrawArrays\n");
	for (i = 0; i < 4; i++)
		glDrawArrays(GL_TRIANGLES, i*3, 3);

	/* State change: Vertex arrays. */
	glDisableClientState(GL_VERTEX_ARRAY);
	glDisableClientState(GL_COLOR_ARRAY);
	glDisableClientState(GL_SECONDARY_COLOR_ARRAY);

	/* State change: Constant buffer. */
	glTranslatef(0, 30, 0);

	rotate_colors(array);

	/* Draw. */
	printf("Begin/End\n");
	for (i = 0; i < 4; i++) {
		glBegin(GL_TRIANGLES);
		for (j = 0; j < 3; j++) {
			glColor3fv(array + i*15 + j*5 + 2);
			glSecondaryColor3fv(seccol);
			glVertex2fv(array + i*15 + j*5);
		}
		glEnd();
	}

	/* State change: Constant buffer. */
	glTranslatef(0, 30, 0);

	rotate_colors(array);

	/* Create display lists. */
	for (i = 0; i < 4; i++) {
		glNewList(i+1, GL_COMPILE);
		glBegin(GL_TRIANGLES);
		for (j = 0; j < 3; j++) {
			glColor3fv(array + i*15 + j*5 + 2);
			glSecondaryColor3fv(seccol);
			glVertex2fv(array + i*15 + j*5);
		}
		glEnd();
		glEndList();
	}

	/* Draw. */
	printf("CallList\n");
	for (i = 0; i < 4; i++) {
		glCallList(i+1);
	}

	pass = pass && piglit_probe_pixel_rgb(15, 15, c0);
	pass = pass && piglit_probe_pixel_rgb(35, 15, c1);
	pass = pass && piglit_probe_pixel_rgb(55, 15, c2);
	pass = pass && piglit_probe_pixel_rgb(75, 15, c3);

	pass = pass && piglit_probe_pixel_rgb(15, 45, c1);
	pass = pass && piglit_probe_pixel_rgb(35, 45, c2);
	pass = pass && piglit_probe_pixel_rgb(55, 45, c3);
	pass = pass && piglit_probe_pixel_rgb(75, 45, c0);

	pass = pass && piglit_probe_pixel_rgb(15, 75, c2);
	pass = pass && piglit_probe_pixel_rgb(35, 75, c3);
	pass = pass && piglit_probe_pixel_rgb(55, 75, c0);
	pass = pass && piglit_probe_pixel_rgb(75, 75, c1);

	pass = pass && piglit_probe_pixel_rgb(15, 105, c3);
	pass = pass && piglit_probe_pixel_rgb(35, 105, c0);
	pass = pass && piglit_probe_pixel_rgb(55, 105, c1);
	pass = pass && piglit_probe_pixel_rgb(75, 105, c2);

	piglit_present_results();
	return pass ? PIGLIT_PASS : PIGLIT_FAIL;
}
void clip_draw_dopesheet_channels(const bContext *C, ARegion *ar)
{
	ScrArea *sa = CTX_wm_area(C);
	SpaceClip *sc = CTX_wm_space_clip(C);
	View2D *v2d = &ar->v2d;
	MovieClip *clip = ED_space_clip_get_clip(sc);
	MovieTracking *tracking;
	MovieTrackingDopesheet *dopesheet;
	MovieTrackingDopesheetChannel *channel;
	uiStyle *style = UI_style_get();
	uiBlock *block;
	int fontid = style->widget.uifont_id;
	int height;
	float y;
	PropertyRNA *chan_prop_lock;

	if (!clip)
		return;

	tracking = &clip->tracking;
	dopesheet = &tracking->dopesheet;
	height = (dopesheet->tot_channel * CHANNEL_STEP) + (CHANNEL_HEIGHT);

	if (height > BLI_rcti_size_y(&v2d->mask)) {
		/* don't use totrect set, as the width stays the same
		 * (NOTE: this is ok here, the configuration is pretty straightforward)
		 */
		v2d->tot.ymin = (float)(-height);
	}

	/* need to do a view-sync here, so that the keys area doesn't jump around (it must copy this) */
	UI_view2d_sync(NULL, sa, v2d, V2D_LOCK_COPY);

	/* loop through channels, and set up drawing depending on their type
	 * first pass: just the standard GL-drawing for backdrop + text
	 */
	y = (float) CHANNEL_FIRST;

	BLF_size(fontid, 11.0f * U.pixelsize, U.dpi);

	for (channel = dopesheet->channels.first; channel; channel = channel->next) {
		float yminc = (float) (y - CHANNEL_HEIGHT_HALF);
		float ymaxc = (float) (y + CHANNEL_HEIGHT_HALF);

		/* check if visible */
		if (IN_RANGE(yminc, v2d->cur.ymin, v2d->cur.ymax) ||
		    IN_RANGE(ymaxc, v2d->cur.ymin, v2d->cur.ymax))
		{
			MovieTrackingTrack *track = channel->track;
			float font_height, color[3];
			bool sel = (track->flag & TRACK_DOPE_SEL) != 0;

			track_channel_color(track, NULL, color);
			glColor3fv(color);

			glRectf(v2d->cur.xmin, (float) y - CHANNEL_HEIGHT_HALF,
			        v2d->cur.xmax + EXTRA_SCROLL_PAD, (float) y + CHANNEL_HEIGHT_HALF);

			if (sel)
				UI_ThemeColor(TH_TEXT_HI);
			else
				UI_ThemeColor(TH_TEXT);

			font_height = BLF_height(fontid, channel->name, sizeof(channel->name));
			BLF_position(fontid, v2d->cur.xmin + CHANNEL_PAD,
			             y - font_height / 2.0f, 0.0f);
			BLF_draw(fontid, channel->name, strlen(channel->name));
		}

		/* adjust y-position for next one */
		y -= CHANNEL_STEP;
	}

	/* second pass: widgets */
	block = UI_block_begin(C, ar, __func__, UI_EMBOSS);
	y = (float) CHANNEL_FIRST;

	/* get RNA properties (once) */
	chan_prop_lock = RNA_struct_type_find_property(&RNA_MovieTrackingTrack, "lock");
	BLI_assert(chan_prop_lock);

	glEnable(GL_BLEND);
	for (channel = dopesheet->channels.first; channel; channel = channel->next) {
		float yminc = (float)(y - CHANNEL_HEIGHT_HALF);
		float ymaxc = (float)(y + CHANNEL_HEIGHT_HALF);

		/* check if visible */
		if (IN_RANGE(yminc, v2d->cur.ymin, v2d->cur.ymax) ||
		    IN_RANGE(ymaxc, v2d->cur.ymin, v2d->cur.ymax))
		{
			MovieTrackingTrack *track = channel->track;
			const int icon = (track->flag & TRACK_LOCKED) ? ICON_LOCKED : ICON_UNLOCKED;
			PointerRNA ptr;

			RNA_pointer_create(&clip->id, &RNA_MovieTrackingTrack, track, &ptr);

			UI_block_emboss_set(block, UI_EMBOSS_NONE);
			uiDefIconButR_prop(block, UI_BTYPE_ICON_TOGGLE, 1, icon,
			                   v2d->cur.xmax - UI_UNIT_X - CHANNEL_PAD, y - UI_UNIT_Y / 2.0f,
			                   UI_UNIT_X, UI_UNIT_Y, &ptr, chan_prop_lock, 0, 0, 0, 0, 0, NULL);
			UI_block_emboss_set(block, UI_EMBOSS);
		}

		/* adjust y-position for next one */
		y -= CHANNEL_STEP;
	}
	glDisable(GL_BLEND);

	UI_block_end(C, block);
	UI_block_draw(C, block);
}
Beispiel #5
0
/* draw method for ant */
static Bool draw_ant(antspotlightstruct *mp,
                     const GLfloat *Material, int mono, int shadow, 
	      float ant_step, Bool (*sphere)(float), Bool (*cone)(float))
{
  
  float cos1 = cos(ant_step);
  float cos2 = cos(ant_step + 2 * Pi / 3);
  float cos3 = cos(ant_step + 4 * Pi / 3);
  float sin1 = sin(ant_step);
  float sin2 = sin(ant_step + 2 * Pi / 3);
  float sin3 = sin(ant_step + 4 * Pi / 3);
  
/* Apparently this is a performance killer on many systems...
   glEnable(GL_POLYGON_SMOOTH);
 */
  glEnable(GL_BLEND);
  glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

  glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, mp->mono ? MaterialGray5 : Material);
  glEnable(GL_CULL_FACE);
  glPushMatrix();
  glScalef(1, 1.3, 1);
  if(!((*sphere)(0.18)))
    return False;
  glScalef(1, 1 / 1.3, 1);
  glTranslatef(0.00, 0.30, 0.00);
  if(!((*sphere)(0.2)))
    return False;
  
  glTranslatef(-0.05, 0.17, 0.05);
  glRotatef(-90, 1, 0, 0);
  glRotatef(-25, 0, 1, 0);
  if(!((*cone)(0.05)))
    return False;
  glTranslatef(0.00, 0.10, 0.00);
  if(!((*cone)(0.05)))
    return False;
  glRotatef(25, 0, 1, 0);
  glRotatef(90, 1, 0, 0);
  
  glScalef(1, 1.3, 1);
  glTranslatef(0.15, -0.65, 0.05);
  if(!((*sphere)(0.25)))
    return False;
  glScalef(1, 1 / 1.3, 1);
  glPopMatrix();
  glDisable(GL_CULL_FACE);
  
  glDisable(GL_LIGHTING);
  
  /* ANTENNAS */
  glEnable(GL_LINE_SMOOTH);
  glEnable(GL_BLEND);
  glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
   
  glBegin(GL_LINES);
  glColor3fv(mp->mono ? MaterialGray5 : Material);
  glVertex3f(0.00, 0.30, 0.00);
  glColor3fv(MaterialGray);
  glVertex3f(0.40, 0.70, 0.40);
  glColor3fv(mp->mono ? MaterialGray5 : Material);
  glVertex3f(0.00, 0.30, 0.00);
  glColor3fv(MaterialGray);
  glVertex3f(0.40, 0.70, -0.40);
  glEnd();

  if(!shadow) {
    glBegin(GL_POINTS);
    glColor3fv(mp->mono ? MaterialGray6 : MaterialGray5);
    glVertex3f(0.40, 0.70, 0.40);
    glVertex3f(0.40, 0.70, -0.40);
    glEnd();
  }

  /* LEFT-FRONT ARM */
  glBegin(GL_LINE_STRIP);
  glColor3fv(mp->mono ? MaterialGray5 : Material);
  glVertex3f(0.00, 0.05, 0.18);
  glVertex3f(0.35 + 0.05 * cos1, 0.15, 0.25);
  glColor3fv(MaterialGray);
  glVertex3f(-0.20 + 0.05 * cos1, 0.25 + 0.1 * sin1, 0.45);
  glEnd();

  /* LEFT-CENTER ARM */
  glBegin(GL_LINE_STRIP);
  glColor3fv(mp->mono ? MaterialGray5 : Material);
  glVertex3f(0.00, 0.00, 0.18);
  glVertex3f(0.35 + 0.05 * cos2, 0.00, 0.25);
  glColor3fv(MaterialGray);
  glVertex3f(-0.20 + 0.05 * cos2, 0.00 + 0.1 * sin2, 0.45);
  glEnd();

  /* LEFT-BACK ARM */
  glBegin(GL_LINE_STRIP);
  glColor3fv(mp->mono ? MaterialGray5 : Material);
  glVertex3f(0.00, -0.05, 0.18);
  glVertex3f(0.35 + 0.05 * cos3, -0.15, 0.25);
  glColor3fv(MaterialGray);
  glVertex3f(-0.20 + 0.05 * cos3, -0.25 + 0.1 * sin3, 0.45);
  glEnd();

  /* RIGHT-FRONT ARM */
  glBegin(GL_LINE_STRIP);
  glColor3fv(mp->mono ? MaterialGray5 : Material);
  glVertex3f(0.00, 0.05, -0.18);
  glVertex3f(0.35 - 0.05 * sin1, 0.15, -0.25);
  glColor3fv(MaterialGray);
  glVertex3f(-0.20 - 0.05 * sin1, 0.25 + 0.1 * cos1, -0.45);
  glEnd();

  /* RIGHT-CENTER ARM */
  glBegin(GL_LINE_STRIP);
  glColor3fv(mp->mono ? MaterialGray5 : Material);
  glVertex3f(0.00, 0.00, -0.18);
  glVertex3f(0.35 - 0.05 * sin2, 0.00, -0.25);
  glColor3fv(MaterialGray);
  glVertex3f(-0.20 - 0.05 * sin2, 0.00 + 0.1 * cos2, -0.45);
  glEnd();

  /* RIGHT-BACK ARM */
  glBegin(GL_LINE_STRIP);
  glColor3fv(mp->mono ? MaterialGray5 : Material);
  glVertex3f(0.00, -0.05, -0.18);
  glVertex3f(0.35 - 0.05 * sin3, -0.15, -0.25);
  glColor3fv(MaterialGray);
  glVertex3f(-0.20 - 0.05 * sin3, -0.25 + 0.1 * cos3, -0.45);
  glEnd();

  if(!shadow) {
    glBegin(GL_POINTS);
    glColor3fv(MaterialGray5);
    glVertex3f(-0.20 + 0.05 * cos1, 0.25 + 0.1 * sin1, 0.45);
    glVertex3f(-0.20 + 0.05 * cos2, 0.00 + 0.1 * sin2, 0.45);
    glVertex3f(-0.20 + 0.05 * cos3, -0.25 + 0.1 * sin3, 0.45);
    glVertex3f(-0.20 - 0.05 * sin1, 0.25 + 0.1 * cos1, -0.45);
    glVertex3f(-0.20 - 0.05 * sin2, 0.00 + 0.1 * cos2, -0.45);
    glVertex3f(-0.20 - 0.05 * sin3, -0.25 + 0.1 * cos3, -0.45);
    glEnd();
  }

  glEnable(GL_LIGHTING);

  return True;
}
Beispiel #6
0
static void SetColor(int c)
{
     glColor3fv(RGBMap[c]);
}
Beispiel #7
0
void ColorModifier::begin() {
    glPushAttrib(GL_CURRENT_BIT | GL_LIGHTING_BIT);
    glColor3fv(color_);
}
Beispiel #8
0
void ApplicationOverlay::renderAudioMeter() {

    Application* application = Application::getInstance();

    GLCanvas* glWidget = application->getGLWidget();
    Audio* audio = application->getAudio();

    //  Display a single screen-size quad to create an alpha blended 'collision' flash
    if (audio->getCollisionFlashesScreen()) {
        float collisionSoundMagnitude = audio->getCollisionSoundMagnitude();
        const float VISIBLE_COLLISION_SOUND_MAGNITUDE = 0.5f;
        if (collisionSoundMagnitude > VISIBLE_COLLISION_SOUND_MAGNITUDE) {
            renderCollisionOverlay(glWidget->width(), glWidget->height(),
                audio->getCollisionSoundMagnitude());
        }
    }

    //  Audio VU Meter and Mute Icon
    const int MUTE_ICON_SIZE = 24;
    const int AUDIO_METER_INSET = 2;
    const int MUTE_ICON_PADDING = 10;
    const int AUDIO_METER_WIDTH = MIRROR_VIEW_WIDTH - MUTE_ICON_SIZE - AUDIO_METER_INSET - MUTE_ICON_PADDING;
    const int AUDIO_METER_SCALE_WIDTH = AUDIO_METER_WIDTH - 2 * AUDIO_METER_INSET;
    const int AUDIO_METER_HEIGHT = 8;
    const int AUDIO_METER_GAP = 5;
    const int AUDIO_METER_X = MIRROR_VIEW_LEFT_PADDING + MUTE_ICON_SIZE + AUDIO_METER_INSET + AUDIO_METER_GAP;

    int audioMeterY;
    bool smallMirrorVisible = Menu::getInstance()->isOptionChecked(MenuOption::Mirror) && !OculusManager::isConnected();
    bool boxed = smallMirrorVisible &&
        !Menu::getInstance()->isOptionChecked(MenuOption::FullscreenMirror);
    if (boxed) {
        audioMeterY = MIRROR_VIEW_HEIGHT + AUDIO_METER_GAP + MUTE_ICON_PADDING;
    } else {
        audioMeterY = AUDIO_METER_GAP + MUTE_ICON_PADDING;
    }

    const float AUDIO_METER_BLUE[] = { 0.0, 0.0, 1.0 };
    const float AUDIO_METER_GREEN[] = { 0.0, 1.0, 0.0 };
    const float AUDIO_METER_RED[] = { 1.0, 0.0, 0.0 };
    const float AUDIO_GREEN_START = 0.25 * AUDIO_METER_SCALE_WIDTH;
    const float AUDIO_RED_START = 0.80 * AUDIO_METER_SCALE_WIDTH;
    const float CLIPPING_INDICATOR_TIME = 1.0f;
    const float AUDIO_METER_AVERAGING = 0.5;
    const float LOG2 = log(2.0f);
    const float METER_LOUDNESS_SCALE = 2.8f / 5.0f;
    const float LOG2_LOUDNESS_FLOOR = 11.0f;
    float audioLevel = 0.0f;
    float loudness = audio->getLastInputLoudness() + 1.0f;

    _trailingAudioLoudness = AUDIO_METER_AVERAGING * _trailingAudioLoudness + (1.0f - AUDIO_METER_AVERAGING) * loudness;
    float log2loudness = log(_trailingAudioLoudness) / LOG2;

    if (log2loudness <= LOG2_LOUDNESS_FLOOR) {
        audioLevel = (log2loudness / LOG2_LOUDNESS_FLOOR) * METER_LOUDNESS_SCALE * AUDIO_METER_SCALE_WIDTH;
    } else {
        audioLevel = (log2loudness - (LOG2_LOUDNESS_FLOOR - 1.0f)) * METER_LOUDNESS_SCALE * AUDIO_METER_SCALE_WIDTH;
    }
    if (audioLevel > AUDIO_METER_SCALE_WIDTH) {
        audioLevel = AUDIO_METER_SCALE_WIDTH;
    }
    bool isClipping = ((audio->getTimeSinceLastClip() > 0.0f) && (audio->getTimeSinceLastClip() < CLIPPING_INDICATOR_TIME));

    if ((audio->getTimeSinceLastClip() > 0.0f) && (audio->getTimeSinceLastClip() < CLIPPING_INDICATOR_TIME)) {
        const float MAX_MAGNITUDE = 0.7f;
        float magnitude = MAX_MAGNITUDE * (1 - audio->getTimeSinceLastClip() / CLIPPING_INDICATOR_TIME);
        renderCollisionOverlay(glWidget->width(), glWidget->height(), magnitude, 1.0f);
    }

    audio->renderToolBox(MIRROR_VIEW_LEFT_PADDING + AUDIO_METER_GAP, audioMeterY, boxed);

    audio->renderScope(glWidget->width(), glWidget->height());

    audio->renderStats(WHITE_TEXT, glWidget->width(), glWidget->height());

    glBegin(GL_QUADS);
    if (isClipping) {
        glColor3f(1, 0, 0);
    } else {
        glColor3f(0.475f, 0.475f, 0.475f);
    }

    audioMeterY += AUDIO_METER_HEIGHT;

    glColor3f(0, 0, 0);
    //  Draw audio meter background Quad
    glVertex2i(AUDIO_METER_X, audioMeterY);
    glVertex2i(AUDIO_METER_X + AUDIO_METER_WIDTH, audioMeterY);
    glVertex2i(AUDIO_METER_X + AUDIO_METER_WIDTH, audioMeterY + AUDIO_METER_HEIGHT);
    glVertex2i(AUDIO_METER_X, audioMeterY + AUDIO_METER_HEIGHT);

    if (audioLevel > AUDIO_RED_START) {
        if (!isClipping) {
            glColor3fv(AUDIO_METER_RED);
        } else {
            glColor3f(1, 1, 1);
        }
        // Draw Red Quad
        glVertex2i(AUDIO_METER_X + AUDIO_METER_INSET + AUDIO_RED_START, audioMeterY + AUDIO_METER_INSET);
        glVertex2i(AUDIO_METER_X + AUDIO_METER_INSET + audioLevel, audioMeterY + AUDIO_METER_INSET);
        glVertex2i(AUDIO_METER_X + AUDIO_METER_INSET + audioLevel, audioMeterY + AUDIO_METER_HEIGHT - AUDIO_METER_INSET);
        glVertex2i(AUDIO_METER_X + AUDIO_METER_INSET + AUDIO_RED_START, audioMeterY + AUDIO_METER_HEIGHT - AUDIO_METER_INSET);
        audioLevel = AUDIO_RED_START;
    }
    if (audioLevel > AUDIO_GREEN_START) {
        if (!isClipping) {
            glColor3fv(AUDIO_METER_GREEN);
        } else {
            glColor3f(1, 1, 1);
        }
        // Draw Green Quad
        glVertex2i(AUDIO_METER_X + AUDIO_METER_INSET + AUDIO_GREEN_START, audioMeterY + AUDIO_METER_INSET);
        glVertex2i(AUDIO_METER_X + AUDIO_METER_INSET + audioLevel, audioMeterY + AUDIO_METER_INSET);
        glVertex2i(AUDIO_METER_X + AUDIO_METER_INSET + audioLevel, audioMeterY + AUDIO_METER_HEIGHT - AUDIO_METER_INSET);
        glVertex2i(AUDIO_METER_X + AUDIO_METER_INSET + AUDIO_GREEN_START, audioMeterY + AUDIO_METER_HEIGHT - AUDIO_METER_INSET);
        audioLevel = AUDIO_GREEN_START;
    }
    //   Draw Blue Quad
    if (!isClipping) {
        glColor3fv(AUDIO_METER_BLUE);
    } else {
        glColor3f(1, 1, 1);
    }
    // Draw Blue (low level) quad
    glVertex2i(AUDIO_METER_X + AUDIO_METER_INSET, audioMeterY + AUDIO_METER_INSET);
    glVertex2i(AUDIO_METER_X + AUDIO_METER_INSET + audioLevel, audioMeterY + AUDIO_METER_INSET);
    glVertex2i(AUDIO_METER_X + AUDIO_METER_INSET + audioLevel, audioMeterY + AUDIO_METER_HEIGHT - AUDIO_METER_INSET);
    glVertex2i(AUDIO_METER_X + AUDIO_METER_INSET, audioMeterY + AUDIO_METER_HEIGHT - AUDIO_METER_INSET);
    glEnd();
}
//--------------------------------------------------------------------------------------------------
/// Draw the legend using immediate mode OpenGL
//--------------------------------------------------------------------------------------------------
void OverlayScalarMapperLegend::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);

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

    RenderStateLighting_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
    RenderStateLighting_FF resetLighting;
    resetLighting.applyOpenGL(oglContext);
    RenderStateDepth resetDepth;
    resetDepth.applyOpenGL(oglContext);

    CVF_CHECK_OGL(oglContext);
#endif // CVF_OPENGL_ES
}
Beispiel #10
0
void    Bonus::draw() const
{
    const vector2& p_end = pos_ + sz_;
    glColor3fv(color_);
    drawRectangle(pos_, p_end);
}
Beispiel #11
0
/* draw an ant */
static Bool draw_antinspect_ant(ModeInfo *mi, antinspectstruct * mp, 
                                const float *Material, int mono,
                                Bool (*sphere)(float), Bool (*cone)(float)) 
{
  float       cos1 = cos(mp->ant_step);
  float       cos2 = cos(mp->ant_step + 2 * Pi / 3);
  float       cos3 = cos(mp->ant_step + 4 * Pi / 3);
  float       sin1 = sin(mp->ant_step);
  float       sin2 = sin(mp->ant_step + 2 * Pi / 3);
  float       sin3 = sin(mp->ant_step + 4 * Pi / 3);
  
  if (mono)
    glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, MaterialGray5);
  else
    glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, Material);
  glEnable(GL_CULL_FACE);
  glPushMatrix();
  glScalef(1, 1.3, 1);
  if (!((*sphere)(0.18)))
    return False;
  glScalef(1, 1 / 1.3, 1);
  glTranslatef(0.00, 0.30, 0.00);
  if (!((*sphere)(0.2)))
    return False;
  
  glTranslatef(-0.05, 0.17, 0.05);
  glRotatef(-90, 1, 0, 0);
  glRotatef(-25, 0, 1, 0);
  if (!((*cone)(0.05)))
    return False;
  glTranslatef(0.00, 0.10, 0.00);
  if (!((*cone)(0.05)))
    return False;
  glRotatef(25, 0, 1, 0);
  glRotatef(90, 1, 0, 0);
  
  glScalef(1, 1.3, 1);
  glTranslatef(0.15, -0.65, 0.05);
  if (!((*sphere)(0.25)))
    return False;
  glScalef(1, 1 / 1.3, 1);
  glPopMatrix();
  glDisable(GL_CULL_FACE);
  
  glDisable(GL_LIGHTING);
  
  /* ANTENNAS */
  glBegin(GL_LINES);
  if (mono)
    glColor3fv(MaterialGray5);
  else
    glColor3fv(Material);
  glVertex3f(0.00, 0.30, 0.00);
  glColor3fv(MaterialGray);
  glVertex3f(0.40, 0.70, 0.40);
  mi->polygon_count++;
  if (mono)
    glColor3fv(MaterialGray5);
  else
    glColor3fv(Material);
  glVertex3f(0.00, 0.30, 0.00);
  glColor3fv(MaterialGray);
  glVertex3f(0.40, 0.70, -0.40);
  mi->polygon_count++;
  glEnd();
  glBegin(GL_POINTS);
  if (mono)
    glColor3fv(MaterialGray6);
  else
    glColor3fv(Material);
  glVertex3f(0.40, 0.70, 0.40);
  mi->polygon_count++;
  glVertex3f(0.40, 0.70, -0.40);
  mi->polygon_count++;
  glEnd();
  
  /* LEFT-FRONT ARM */
  glBegin(GL_LINE_STRIP);
  if (mono)
    glColor3fv(MaterialGray5);
  else
    glColor3fv(Material);
  glVertex3f(0.00, 0.05, 0.18);
  glVertex3f(0.35 + 0.05 * cos1, 0.15, 0.25);
  mi->polygon_count++;
  glColor3fv(MaterialGray);
  glVertex3f(-0.20 + 0.05 * cos1, 0.25 + 0.1 * sin1, 0.45);
  mi->polygon_count++;
  glEnd();
  
  /* LEFT-CENTER ARM */
  glBegin(GL_LINE_STRIP);
  if (mono)
    glColor3fv(MaterialGray5);
  else
    glColor3fv(Material);
  glVertex3f(0.00, 0.00, 0.18);
  glVertex3f(0.35 + 0.05 * cos2, 0.00, 0.25);
  mi->polygon_count++;
  glColor3fv(MaterialGray);
  glVertex3f(-0.20 + 0.05 * cos2, 0.00 + 0.1 * sin2, 0.45);
  mi->polygon_count++;
  glEnd();
  mi->polygon_count++;
  
  /* LEFT-BACK ARM */
  glBegin(GL_LINE_STRIP);
  if (mono)
    glColor3fv(MaterialGray5);
  else
    glColor3fv(Material);
  glVertex3f(0.00, -0.05, 0.18);
  glVertex3f(0.35 + 0.05 * cos3, -0.15, 0.25);
  mi->polygon_count++;
  glColor3fv(MaterialGray);
  glVertex3f(-0.20 + 0.05 * cos3, -0.25 + 0.1 * sin3, 0.45);
  mi->polygon_count++;
  glEnd();
  
  /* RIGHT-FRONT ARM */
  glBegin(GL_LINE_STRIP);
  if (mono)
    glColor3fv(MaterialGray5);
  else
    glColor3fv(Material);
  glVertex3f(0.00, 0.05, -0.18);
  glVertex3f(0.35 - 0.05 * sin1, 0.15, -0.25);
  mi->polygon_count++;
  glColor3fv(MaterialGray);
  glVertex3f(-0.20 - 0.05 * sin1, 0.25 + 0.1 * cos1, -0.45);
  mi->polygon_count++;
  glEnd();
  
  /* RIGHT-CENTER ARM */
  glBegin(GL_LINE_STRIP);
  if (mono)
    glColor3fv(MaterialGray5);
  else
    glColor3fv(Material);
  glVertex3f(0.00, 0.00, -0.18);
  glVertex3f(0.35 - 0.05 * sin2, 0.00, -0.25);
  mi->polygon_count++;
  glColor3fv(MaterialGray);
  glVertex3f(-0.20 - 0.05 * sin2, 0.00 + 0.1 * cos2, -0.45);
  mi->polygon_count++;
  glEnd();
  
  /* RIGHT-BACK ARM */
  glBegin(GL_LINE_STRIP);
  if (mono)
    glColor3fv(MaterialGray5);
  else
    glColor3fv(Material);
  glVertex3f(0.00, -0.05, -0.18);
  glVertex3f(0.35 - 0.05 * sin3, -0.15, -0.25);
  mi->polygon_count++;
  glColor3fv(MaterialGray);
  glVertex3f(-0.20 - 0.05 * sin3, -0.25 + 0.1 * cos3, -0.45);
  mi->polygon_count++;
  glEnd();
    
  glEnable(GL_LIGHTING);
  
  return True;
}
void setNodeColor(size_t node_index){
	if( node_index == arm.current_node_index )
		glColor3fv(activeNodeColor);
	else
		glColor3fv(NodeColor);
}
Beispiel #13
0
// int main(int argc, char *argv[])
int APIENTRY WinMain(HINSTANCE hCurrentInst, HINSTANCE hPreviousInst,LPSTR lpszCmdLine, int nCmdShow)
{
	SpringNetwork cloth = SpringNetworkCreateRectangular(17, 17, 1.0f);
	for (auto &v : cloth.X) v.z -= 1.75f;  // put cloth object at 0,0,-1.5 region,  view/camera will be at origin.
	cloth.gravity = float3(0, -10.0f, 0);  // normally i perfer z-up for any environment or "world" space.
	cloth.dt = 0.033f;                     // speed it up a bit (regardless of fps, each frame advances cloth 1/30th of a second instead of just 1/60th).
	GLWin glwin("TestCloth sample");
	glwin.keyboardfunc = OnKeyboard;
	InitTex();                             // just initializes a checkerboard default texture
	int selection = 0;                     // index of currently selected point
	while (glwin.WindowUp())
	{
		int point_to_unpin = -1;           // if we temporarily move pin a point, we have to unpin it later after simulation.
		if (!glwin.MouseState)             // on mouse drag  
		{
			float3 v = glwin.MouseVector;  // assumes camera at 0,0,0 looking down -z axis
			selection = std::max_element(cloth.X.begin(), cloth.X.end(), [&v](const float3&a, const float3&b)->bool{return dot(v, normalize(a)) < dot(v, normalize(b)); })- cloth.X.begin();
		}
		else 
		{
			if (!cloth.PointStatusSet(selection, -1))
				 cloth.PointStatusSet((point_to_unpin = selection), 1);
			const float3 &v = glwin.MouseVector;
			cloth.X[selection] = v * (dot(v, cloth.X[selection]) / dot(v, v) *(1.0f + glwin.mousewheel*0.1f));
		}
	
		cloth.Simulate();

		if(point_to_unpin >=0)
			cloth.PointStatusSet(point_to_unpin, 0);

		glPushAttrib(GL_ALL_ATTRIB_BITS);
		glViewport(0, 0, glwin.res.x,glwin.res.y);           // Set up the viewport
		glClearColor(0.1f, 0.1f, 0.15f, 1);
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

		glMatrixMode(GL_PROJECTION);
		glPushMatrix();
		glLoadIdentity();
		gluPerspective(glwin.ViewAngle, (double)glwin.aspect_ratio(), 0.01, 10);

		glMatrixMode(GL_MODELVIEW);
		glPushMatrix();
		gluLookAt(0, 0, 0, 0, 0, -1, 0, 1, 0);

		glEnable(GL_DEPTH_TEST);
		glDisable(GL_TEXTURE_2D);
		glPointSize(3);
		glBegin(GL_POINTS);
		for (unsigned int i = 0; i < cloth.X.size(); i++ )
			glColor3f((i==selection)?1.0f:0 , 1, 0.5f), glVertex3fv(cloth.X[i]);
		glEnd();

		if (g_wireframe)
		{
			glBegin(GL_LINES);
			SpringNetworkDrawSprings(&cloth, [](const float3 &a, const float3 &b, const float3 &c){glColor3fv(c); glVertex3fv(a); glVertex3fv(b); });
			glColor3f(1, 0, 0);
			glEnd();
		}
		else
		{
			glEnable(GL_TEXTURE_2D);
			glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
			glEnable(GL_POLYGON_OFFSET_FILL);
			glPolygonOffset(1., 1. / (float)0x10000);
			glEnable(GL_LIGHTING);
			glEnable(GL_LIGHT0);
			glColor3f(0.5f, 0.5f, 0.5f);
			glBegin(GL_QUADS);
			for (auto const & q: cloth.quads)
			{
				for (int c = 0; c <4; c++)
					glTexCoord2f(q[c]%17/16.0f,q[c]/17/16.0f),glNormal3fv(cloth.N[q[c]]), glVertex3fv(cloth.X[q[c]]);
			}
			glEnd();
		}

		// Restore state
		glPopMatrix();  //should be currently in modelview mode
		glMatrixMode(GL_PROJECTION);
		glPopMatrix();
		glPopAttrib();
		glMatrixMode(GL_MODELVIEW);  

		glwin.PrintString({ 0, 0 }, "Press ESC to quit.  w toggles wireframe. ");
		glwin.PrintString({ 0, 1 }, "Use left mouse motion and wheel to move points.");
		glwin.PrintString({ 0, 2 }, "(w)ireframe %s   vert selected %d", ((g_wireframe) ? "ON " : "OFF"), selection);
#       ifdef _DEBUG
			glwin.PrintString({ 2, -1 }, "Running DEBUG Version.  Performance may be SLoooow.", 2, -1);
#       endif
		glwin.SwapBuffers();
	}
	std::cout << "\n";
	return 0;
}
Beispiel #14
0
void draw_3d_object_detail(object3d * object_id, Uint32 material_index, Uint32 use_lightning,
	Uint32 use_textures, Uint32 use_extra_textures)
{
	e3d_vertex_data* vertex_layout;
	Uint8 * data_ptr;

	// check for having to load the arrays
	load_e3d_detail_if_needed(object_id->e3d_data);

	CHECK_GL_ERRORS();
	//also, update the last time this object was used
	object_id->last_acessed_time = cur_time;

	//debug

	if (object_id->self_lit && (!is_day || dungeon) && use_lightning) 
	{
		glColor3fv(object_id->color);
	}

	CHECK_GL_ERRORS();

	glPushMatrix();//we don't want to affect the rest of the scene

	glMultMatrixf(object_id->matrix);

	CHECK_GL_ERRORS();

	if (!dungeon && (clouds_shadows || use_shadow_mapping) && use_extra_textures)
	{
		VECTOR4 plane;

		ELglActiveTextureARB(detail_unit);
		memcpy(plane, object_id->clouds_planes[0], sizeof(VECTOR4));
		plane[3] += clouds_movement_u;
		glTexGenfv(GL_S, GL_EYE_PLANE, plane);
		memcpy(plane, object_id->clouds_planes[1], sizeof(VECTOR4));
		plane[3] += clouds_movement_v;
		glTexGenfv(GL_T, GL_EYE_PLANE, plane);
		ELglActiveTextureARB(base_unit);
	}

	// watch for a change
	if (object_id->e3d_data != cur_e3d)
	{
		if ((cur_e3d != NULL) && (use_compiled_vertex_array))
		{
			ELglUnlockArraysEXT();
		}

		if (use_vertex_buffers)
		{
			ELglBindBufferARB(GL_ARRAY_BUFFER_ARB,
				object_id->e3d_data->vertex_vbo);
			data_ptr = 0;
		}
		else
		{
			data_ptr = object_id->e3d_data->vertex_data;
		}

		vertex_layout = object_id->e3d_data->vertex_layout;

		if ((vertex_layout->normal_count > 0) && use_lightning)
		{
			glEnableClientState(GL_NORMAL_ARRAY);
			glNormalPointer(vertex_layout->normal_type, vertex_layout->size,
				data_ptr + vertex_layout->normal_offset);
		}
		else
		{
			glDisableClientState(GL_NORMAL_ARRAY);
			glNormal3f(0.0f, 0.0f, 1.0f);
		}

		if (use_textures)
		{
			glEnableClientState(GL_TEXTURE_COORD_ARRAY);
			glTexCoordPointer(vertex_layout->texture_count, vertex_layout->texture_type,
				vertex_layout->size, data_ptr + vertex_layout->texture_offset);
		}
		else
		{
			glDisableClientState(GL_TEXTURE_COORD_ARRAY);
		}

		glVertexPointer(vertex_layout->position_count, vertex_layout->position_type,
			vertex_layout->size, data_ptr + vertex_layout->position_offset);

		if (use_vertex_buffers)
		{
			ELglBindBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB,
				object_id->e3d_data->indices_vbo);
		}

		// lock this new one
		if (use_compiled_vertex_array)
		{
			ELglLockArraysEXT(0, object_id->e3d_data->vertex_no);
		}
		// gather statistics
		if (object_id->e3d_data != cur_e3d)
		{
#ifdef  DEBUG
			if ((cur_e3d_count > 0) && (cur_e3d != NULL))
			{
				e3d_count++;
				e3d_total += cur_e3d_count;
			}
			cur_e3d_count = 0;
#endif    //DEBUG
			cur_e3d = object_id->e3d_data;
		}
	}
#ifdef  DEBUG
	cur_e3d_count++;
#endif  //DEBUG

	if (use_textures)
	{
		glEnable(GL_TEXTURE_2D);
#ifdef	NEW_TEXTURES
		bind_texture(object_id->e3d_data->materials[material_index].texture);
#else	/* NEW_TEXTURES */
		get_and_set_texture_id(object_id->e3d_data->materials[material_index].texture);
#endif	/* NEW_TEXTURES */
	}
	else
	{
		glDisable(GL_TEXTURE_2D);		
	}


	if (use_draw_range_elements && ELglDrawRangeElementsEXT)
		ELglDrawRangeElementsEXT(GL_TRIANGLES,
			object_id->e3d_data->materials[material_index].triangles_indices_min,
			object_id->e3d_data->materials[material_index].triangles_indices_max,
			object_id->e3d_data->materials[material_index].triangles_indices_count,
			object_id->e3d_data->index_type,
			object_id->e3d_data->materials[material_index].triangles_indices_index);
	else
		glDrawElements(GL_TRIANGLES,
			object_id->e3d_data->materials[material_index].triangles_indices_count,
			object_id->e3d_data->index_type,
			object_id->e3d_data->materials[material_index].triangles_indices_index);

	glPopMatrix();//restore the scene
	CHECK_GL_ERRORS();

	//OK, let's check if our mouse is over...
#ifdef MAP_EDITOR2
	if (selected_3d_object == -1 && read_mouse_now && mouse_in_sphere(object_id->x_pos, object_id->y_pos, object_id->z_pos, object_id->e3d_data->radius))
		anything_under_the_mouse(object_id->id, UNDER_MOUSE_3D_OBJ);
#endif
}
Beispiel #15
0
void CMiniMap::DrawForReal(bool use_geo)
{
	SCOPED_TIMER("MiniMap::DrawForReal");

	//glEnable(GL_BLEND);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
	glPushAttrib(GL_DEPTH_BUFFER_BIT);
	glDisable(GL_DEPTH_TEST);
	glDepthFunc(GL_LEQUAL);
	glDepthMask(GL_FALSE);
	glDisable(GL_TEXTURE_2D);
	glMatrixMode(GL_MODELVIEW);

	if (minimized) {
		if (!slaveDrawMode) {
			DrawMinimizedButton();
		}
		glPopAttrib();
		glEnable(GL_TEXTURE_2D);
		return;
	}

	// draw the frameborder
	if (!slaveDrawMode && !globalRendering->dualScreenMode && !maximized) {
		glEnable(GL_BLEND);
		DrawFrame();
		glDisable(GL_BLEND);
	}


	bool resetTextureMatrix = false;

	if (use_geo) {
		glPushMatrix();

		// switch to normalized minimap coords
		if (globalRendering->dualScreenMode) {
			glViewport(xpos, ypos, width, height);
			glScalef(width * globalRendering->pixelX, height * globalRendering->pixelY, 1.0f);
		} else {
			glTranslatef(xpos * globalRendering->pixelX, ypos * globalRendering->pixelY, 0.0f);
			glScalef(width * globalRendering->pixelX, height * globalRendering->pixelY, 1.0f);
		}

		/* FIXME: fix mouse handling too and make it fully customizable, so Lua can rotate the minimap to any angle
		CCameraController* camController = &camHandler->GetCurrentController();
		COverheadController* taCam = dynamic_cast<COverheadController*>(camController);
		SmoothController* smCam = dynamic_cast<SmoothController*>(camController);

		if ((taCam && taCam->flipped) || (smCam && smCam->flipped)) {
			glTranslatef(1.0f, 1.0f, 0.0f);
			glScalef(-1.0f, -1.0f, 1.0f);

			glMatrixMode(GL_TEXTURE);
			glPushMatrix();
			glTranslatef(1.0f, 1.0f, 0.0f);
			glScalef(-1.0f, -1.0f, 1.0f);
			glMatrixMode(GL_MODELVIEW);

			resetTextureMatrix = true;
		}*/
	}

	setSurfaceCircleFunc(DrawSurfaceCircle);
	setSurfaceSquareFunc(DrawSurfaceSquare);
	cursorIcons.Enable(false);

	glColor4f(0.6f, 0.6f, 0.6f, 1.0f);

	// don't mirror the map texture with flipped cameras
	glMatrixMode(GL_TEXTURE);
	glPushMatrix();
	glLoadIdentity();
	glMatrixMode(GL_MODELVIEW);

	// draw the map
	glDisable(GL_BLEND);
		readmap->DrawMinimap();
	glEnable(GL_BLEND);

	glMatrixMode(GL_TEXTURE);
	glPopMatrix();
	glMatrixMode(GL_MODELVIEW);

	// clip everything outside of the minimap box
	{
		const double plane0[4] = {0,-1,0,1};
		const double plane1[4] = {0,1,0,0};
		const double plane2[4] = {-1,0,0,1};
		const double plane3[4] = {1,0,0,0};

		glClipPlane(GL_CLIP_PLANE0, plane0); // clip bottom
		glClipPlane(GL_CLIP_PLANE1, plane1); // clip top
		glClipPlane(GL_CLIP_PLANE2, plane2); // clip right
		glClipPlane(GL_CLIP_PLANE3, plane3); // clip left

		glEnable(GL_CLIP_PLANE0);
		glEnable(GL_CLIP_PLANE1);
		glEnable(GL_CLIP_PLANE2);
		glEnable(GL_CLIP_PLANE3);
	}

	// switch to top-down map/world coords (z is twisted with y compared to the real map/world coords)
	glPushMatrix();
	glTranslatef(0.0f, +1.0f, 0.0f);
	glScalef(+1.0f / (gs->mapx * SQUARE_SIZE), -1.0f / (gs->mapy * SQUARE_SIZE), 1.0f);

	glEnable(GL_TEXTURE_2D);
	glEnable(GL_ALPHA_TEST);
	glAlphaFunc(GL_GREATER, 0.0f);

	{
		GML_RECMUTEX_LOCK(unit); // DrawForReal

		const std::set<CUnit*>& units = unitDrawer->GetUnsortedUnits();

		for (std::set<CUnit*>::const_iterator it = units.begin(); it != units.end(); ++it) {
			DrawUnit(*it);
		}

		// highlight the selected unit
		CUnit* unit = GetSelectUnit(GetMapPosition(mouse->lastx, mouse->lasty));
		if (unit != NULL) {
			DrawUnitHighlight(unit);
		}
	}

	glDisable(GL_ALPHA_TEST);
	glDisable(GL_TEXTURE_2D);

	glPushMatrix();
	glRotatef(-90.0f, +1.0f, 0.0f, 0.0f); // real 'world' coordinates
	glScalef(1.0f, 0.0f, 1.0f); // skip the y-coord (Lua's DrawScreen is perspective and so any z-coord in it influence the x&y, too)

	// draw the projectiles
	if (drawProjectiles) {
		glPointSize(1.0f);
		WorkaroundATIPointSizeBug();
		projectileDrawer->DrawProjectilesMiniMap();
	}

	// draw the queued commands
	//
	// NOTE: this needlessly adds to the CursorIcons list, but at least
	//       they are not drawn  (because the input receivers are drawn
	//       after the command queues)

	LuaUnsyncedCtrl::DrawUnitCommandQueues();
	if ((drawCommands > 0) && guihandler->GetQueueKeystate()) {
		selectedUnits.DrawCommands();
	}

	lineDrawer.DrawAll();

	// draw the selection shape, and some ranges
	if (drawCommands > 0) {
		guihandler->DrawMapStuff(!!drawCommands);
	}

	{
		GML_RECMUTEX_LOCK(sel); // DrawForReal

		// draw unit ranges
		const float radarSquare = radarhandler->radarDiv;
		CUnitSet& selUnits = selectedUnits.selectedUnits;
		for(CUnitSet::iterator si = selUnits.begin(); si != selUnits.end(); ++si) {
			CUnit* unit = *si;
			if (unit->radarRadius && !unit->beingBuilt && unit->activated) {
				glColor3fv(cmdColors.rangeRadar);
				DrawCircle(unit->pos, (unit->radarRadius * radarSquare));
			}
			if (unit->sonarRadius && !unit->beingBuilt && unit->activated) {
				glColor3fv(cmdColors.rangeSonar);
				DrawCircle(unit->pos, (unit->sonarRadius * radarSquare));
			}
			if (unit->jammerRadius && !unit->beingBuilt && unit->activated) {
				glColor3fv(cmdColors.rangeJammer);
				DrawCircle(unit->pos, (unit->jammerRadius * radarSquare));
			}
			// change if someone someday create a non stockpiled interceptor
			const CWeapon* w = unit->stockpileWeapon;
			if((w != NULL) && w->weaponDef->interceptor) {
				if (w->numStockpiled) {
					glColor3fv(cmdColors.rangeInterceptorOn);
				} else {
					glColor3fv(cmdColors.rangeInterceptorOff);
				}
				DrawCircle(unit->pos, w->weaponDef->coverageRange);
			}
		}
	}

	glPopMatrix(); // revert to the 2d xform

	if (!minimap->maximized) {
		// draw the camera frustum lines
		cam2->GetFrustumSides(0.0f, 0.0f, 1.0f, true);
		cam2->ClipFrustumLines(true, -10000.0f, 400096.0f);

		const std::vector<CCamera::FrustumLine>& negSides = cam2->negFrustumSides;
//		const std::vector<CCamera::FrustumLine>& posSides = cam2->posFrustumSides;
		std::vector<CCamera::FrustumLine>::const_iterator fli;

		CVertexArray* va = GetVertexArray();
		va->Initialize();
		va->EnlargeArrays(negSides.size() * 2, 0, VA_SIZE_2D0);

		for (fli = negSides.begin(); fli != negSides.end(); ++fli) {
			if (fli->minz < fli->maxz) {
				va->AddVertex2dQ0(fli->base + (fli->dir * fli->minz), fli->minz);
				va->AddVertex2dQ0(fli->base + (fli->dir * fli->maxz), fli->maxz);
			}
		}

		glLineWidth(2.5f);
		glColor4f(0, 0, 0, 0.5f);
		va->DrawArray2d0(GL_LINES);

		glLineWidth(1.5f);
		glColor4f(1, 1, 1, 0.75f);
		va->DrawArray2d0(GL_LINES);
		glLineWidth(1.0f);
	}


	// selection box
	glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
	CMouseHandler::ButtonPressEvt& bp = mouse->buttons[SDL_BUTTON_LEFT];
	if (selecting && fullProxy && (bp.movement > 4)) {
		const float3 oldPos = GetMapPosition(bp.x, bp.y);
		const float3 newPos = GetMapPosition(mouse->lastx, mouse->lasty);
		glColor4fv(cmdColors.mouseBox);
		glBlendFunc((GLenum)cmdColors.MouseBoxBlendSrc(),
		            (GLenum)cmdColors.MouseBoxBlendDst());
		glLineWidth(cmdColors.MouseBoxLineWidth());

		float verts[] = {
			oldPos.x, oldPos.z,
			newPos.x, oldPos.z,
			newPos.x, newPos.z,
			oldPos.x, newPos.z,
		};
		glEnableClientState(GL_VERTEX_ARRAY);
		glVertexPointer(2, GL_FLOAT, 0, verts);
		glDrawArrays(GL_LINE_LOOP, 0, 4);
		glDisableClientState(GL_VERTEX_ARRAY);

		glLineWidth(1.0f);
		glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
	}

	DrawNotes();

	// reset 1
	if (resetTextureMatrix) {
		glMatrixMode(GL_TEXTURE_MATRIX);
		glPopMatrix();
	}
	glMatrixMode(GL_MODELVIEW);
	if (use_geo) {
		glPopMatrix();
	}

	// reset 2
	glPopMatrix();
	glPopAttrib();
	glEnable(GL_TEXTURE_2D);

	{
		//! prepare ClipPlanes for Lua's DrawInMinimap Modelview matrix

		//! quote from glClipPlane spec:
		//! "When glClipPlane is called, equation is transformed by the inverse of the modelview matrix and stored in the resulting eye coordinates.
		//!  Subsequent changes to the modelview matrix have no effect on the stored plane-equation components."
		//! -> we have to use the same modelview matrix when calling glClipPlane and later draw calls

		//! set the modelview matrix to the same as used in Lua's DrawInMinimap
		glPushMatrix();
		glLoadIdentity();
		glScalef(1.0f / width, 1.0f / height, 1.0f);

		const double plane0[4] = {0, -1, 0, double(height)};
		const double plane1[4] = {0, 1, 0, 0};
		const double plane2[4] = {-1, 0, 0, double(width)};
		const double plane3[4] = {1, 0, 0, 0};

		glClipPlane(GL_CLIP_PLANE0, plane0); // clip bottom
		glClipPlane(GL_CLIP_PLANE1, plane1); // clip top
		glClipPlane(GL_CLIP_PLANE2, plane2); // clip right
		glClipPlane(GL_CLIP_PLANE3, plane3); // clip left

		glPopMatrix();
	}

	//! allow the LUA scripts to draw into the minimap
	eventHandler.DrawInMiniMap();

	if (use_geo && globalRendering->dualScreenMode)
		glViewport(globalRendering->viewPosX,0,globalRendering->viewSizeX,globalRendering->viewSizeY);

	//FIXME: Lua modifies the matrices w/o reseting it! (quite complexe to fix because ClearMatrixStack() makes it impossible to use glPushMatrix)
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	gluOrtho2D(0,1,0,1);
	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();

	// disable ClipPlanes
	glDisable(GL_CLIP_PLANE0);
	glDisable(GL_CLIP_PLANE1);
	glDisable(GL_CLIP_PLANE2);
	glDisable(GL_CLIP_PLANE3);

	cursorIcons.Enable(true);
	setSurfaceCircleFunc(NULL);
	setSurfaceSquareFunc(NULL);
}
Beispiel #16
0
void Cursor::Draw3dCursorScale(const vec_t min, const vec_t mid, const vec_t max)
{
	glBegin(GL_LINES);
      
	// X Axis, red
	glColor3fv(RED);
	glVertex3f(0.0,  0.0, 0.0);
	glVertex3f(mid,  0.0, 0.0);

	// Y Axis, green
	glColor3fv(GREEN);	
	glVertex3f(0.0,  mid, 0.0);
	glVertex3f(0.0,  0.0, 0.0);	
      
	// Z Axis, blue
	glColor3fv(BLUE);
	glVertex3f(0.0,  0.0,  mid);
	glVertex3f(0.0,  0.0,  0.0);
	glEnd();


	glBegin(GL_QUADS);
      
	// X Axis, Red box
	glColor3fv(RED);
	glVertex3f(mid+min,  -min, min);
	glVertex3f(mid+min,  min, min);
	glVertex3f(mid-min,  min, min);
	glVertex3f(mid-min,  -min, min);

	glVertex3f(mid+min,  -min, -min);
	glVertex3f(mid+min,  min, -min);
	glVertex3f(mid-min,  min, -min);
	glVertex3f(mid-min,  -min, -min);

	glVertex3f(mid+min,  min, -min);
	glVertex3f(mid+min,  min, min);
	glVertex3f(mid-min,  min, min);
	glVertex3f(mid-min,  min, -min);

	glVertex3f(mid+min,  -min, -min);
	glVertex3f(mid+min,  -min, min);
	glVertex3f(mid-min,  -min, min);
	glVertex3f(mid-min,  -min, -min);

	glVertex3f(mid+min,  min, -min);
	glVertex3f(mid+min,  min, min);
	glVertex3f(mid+min,  -min, min);
	glVertex3f(mid+min,  -min, -min);


	// Y Axis, green
	glColor3fv(GREEN);	
	glVertex3f(-min, mid+min,  min);
	glVertex3f(min,mid+min,   min);
	glVertex3f(min,mid-min,   min);
	glVertex3f(-min,mid-min,   min);

	glVertex3f(-min,mid+min,   -min);
	glVertex3f(min,mid+min,   -min);
	glVertex3f( min,mid-min,  -min);
	glVertex3f(-min,mid-min,   -min);

	glVertex3f( min,mid+min,  -min);
	glVertex3f( min,mid+min,  min);
	glVertex3f(min,mid-min,   min);
	glVertex3f( min,mid-min,  -min);

	glVertex3f( -min,mid+min,  -min);
	glVertex3f( -min,mid+min,  min);
	glVertex3f(-min,mid-min,   min);
	glVertex3f(-min,mid-min,   -min);

	glVertex3f(min,mid+min,   -min);
	glVertex3f(min,mid+min,   min);
	glVertex3f( -min,mid+min,  min);
	glVertex3f(-min,mid+min,   -min);

      
	// Z Axis, blue
	glColor3fv(BLUE);
	glVertex3f(-min, min, mid+min);
	glVertex3f(min,   min, mid+min);
	glVertex3f(min,   min, mid-min);
	glVertex3f(-min,   min, mid-min);

	glVertex3f(-min,    -min, mid+min);
	glVertex3f(min,   -min, mid+min);
	glVertex3f( min,  -min, mid-min);
	glVertex3f(-min,   -min, mid-min);

	glVertex3f( min,  -min, mid+min);
	glVertex3f( min,  min, mid+min);
	glVertex3f(min,   min, mid-min);
	glVertex3f( min,  -min, mid-min);

	glVertex3f( -min,  -min, mid+min);
	glVertex3f( -min,  min, mid+min);
	glVertex3f(-min,   min, mid-min);
	glVertex3f(-min,   -min, mid-min);

	glVertex3f(min,   -min, mid+min);
	glVertex3f(min,   min, mid+min);
	glVertex3f( -min,  min, mid+min);
	glVertex3f(-min,   -min, mid+min);


	glEnd();
}
Beispiel #17
0
/* glmDraw: Renders the model to the current OpenGL context using the
 * mode specified.
 *
 * model    - initialized GLMmodel structure
 * mode     - a bitwise OR of values describing what is to be rendered.
 *            GLM_NONE     -  render with only vertices
 *            GLM_FLAT     -  render with facet normals
 *            GLM_SMOOTH   -  render with vertex normals
 *            GLM_TEXTURE  -  render with texture coords
 *            GLM_COLOR    -  render with colors (color material)
 *            GLM_MATERIAL -  render with materials
 *            GLM_COLOR and GLM_MATERIAL should not both be specified.  
 *            GLM_FLAT and GLM_SMOOTH should not both be specified.  
 */
GLvoid
glmDraw(GLMmodel* model, GLuint mode)
{
  GLuint i;
  GLMgroup* group;

  assert(model);
  assert(model->vertices);

  /* do a bit of warning */
  if (mode & GLM_FLAT && !model->facetnorms) {
    printf("glmDraw() warning: flat render mode requested "
	   "with no facet normals defined.\n");
    mode &= ~GLM_FLAT;
  }
  if (mode & GLM_SMOOTH && !model->normals) {
    printf("glmDraw() warning: smooth render mode requested "
	   "with no normals defined.\n");
    mode &= ~GLM_SMOOTH;
  }
  if (mode & GLM_TEXTURE && !model->texcoords) {
    printf("glmDraw() warning: texture render mode requested "
	   "with no texture coordinates defined.\n");
    mode &= ~GLM_TEXTURE;
  }
  if (mode & GLM_FLAT && mode & GLM_SMOOTH) {
    printf("glmDraw() warning: flat render mode requested "
	   "and smooth render mode requested (using smooth).\n");
    mode &= ~GLM_FLAT;
  }
  if (mode & GLM_COLOR && !model->materials) {
    printf("glmDraw() warning: color render mode requested "
	   "with no materials defined.\n");
    mode &= ~GLM_COLOR;
  }
  if (mode & GLM_MATERIAL && !model->materials) {
    printf("glmDraw() warning: material render mode requested "
	   "with no materials defined.\n");
    mode &= ~GLM_MATERIAL;
  }
  if (mode & GLM_COLOR && mode & GLM_MATERIAL) {
    printf("glmDraw() warning: color and material render mode requested "
	   "using only material mode\n");
    mode &= ~GLM_COLOR;
  }
  if (mode & GLM_COLOR)
    glEnable(GL_COLOR_MATERIAL);
  if (mode & GLM_MATERIAL)
    glDisable(GL_COLOR_MATERIAL);

  glPushMatrix();
  glTranslatef(model->position[0], model->position[1], model->position[2]);

  glBegin(GL_TRIANGLES);
  group = model->groups;
  while (group) {
    if (mode & GLM_MATERIAL) {
      glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, 
		   model->materials[group->material].ambient);
      glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, 
		   model->materials[group->material].diffuse);
      glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, 
		   model->materials[group->material].specular);
       glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, 
  		  model->materials[group->material].shininess);
    }

    if (mode & GLM_COLOR) {
      glColor3fv(model->materials[group->material].diffuse);
    }

    for (i = 0; i < group->numtriangles; i++) {
      if (mode & GLM_FLAT)
	glNormal3fv(&model->facetnorms[3 * T(group->triangles[i]).findex]);
      
      if (mode & GLM_SMOOTH)
	glNormal3fv(&model->normals[3 * T(group->triangles[i]).nindices[0]]);
      if (mode & GLM_TEXTURE)
	glTexCoord2fv(&model->texcoords[2*T(group->triangles[i]).tindices[0]]);
      glVertex3fv(&model->vertices[3 * T(group->triangles[i]).vindices[0]]);
#if 0
      printf("%f %f %f\n", 
	     model->vertices[3 * T(group->triangles[i]).vindices[0] + X],
	     model->vertices[3 * T(group->triangles[i]).vindices[0] + Y],
	     model->vertices[3 * T(group->triangles[i]).vindices[0] + Z]);
#endif
      
      if (mode & GLM_SMOOTH)
	glNormal3fv(&model->normals[3 * T(group->triangles[i]).nindices[1]]);
      if (mode & GLM_TEXTURE)
	glTexCoord2fv(&model->texcoords[2*T(group->triangles[i]).tindices[1]]);
      glVertex3fv(&model->vertices[3 * T(group->triangles[i]).vindices[1]]);
#if 0
      printf("%f %f %f\n", 
	     model->vertices[3 * T(group->triangles[i]).vindices[1] + X],
	     model->vertices[3 * T(group->triangles[i]).vindices[1] + Y],
	     model->vertices[3 * T(group->triangles[i]).vindices[1] + Z]);
#endif
      
      if (mode & GLM_SMOOTH)
	glNormal3fv(&model->normals[3 * T(group->triangles[i]).nindices[2]]);
      if (mode & GLM_TEXTURE)
	glTexCoord2fv(&model->texcoords[2*T(group->triangles[i]).tindices[2]]);
      glVertex3fv(&model->vertices[3 * T(group->triangles[i]).vindices[2]]);
#if 0
      printf("%f %f %f\n", 
	     model->vertices[3 * T(group->triangles[i]).vindices[2] + X],
	     model->vertices[3 * T(group->triangles[i]).vindices[2] + Y],
	     model->vertices[3 * T(group->triangles[i]).vindices[2] + Z]);
#endif
      
    }
    
    group = group->next;
  }
  glEnd();

  glPopMatrix();
}
void GLUTSimLightController::draw() {
  int w = glutGet(GLUT_WINDOW_WIDTH);
  int h = glutGet(GLUT_WINDOW_HEIGHT);
  float light_position[4] = {0.0, 0.0, -1.0, 0.0};

  glViewport(0, 0, w, h);

  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();
  gluPerspective(35, (double) w/h, 0.1, 100.0);

  glMatrixMode(GL_MODELVIEW);
  glLoadIdentity();

  glClearColor(0, 0, 0, 1);
  glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);

  glLightfv(GL_LIGHT0, GL_POSITION, light_position);

  glTranslatef(0, 0, -3);

  glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, 1);

  glEnable(GL_DEPTH_TEST);
  glEnable(GL_POINT_SMOOTH);

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

  glEnable(GL_LIGHT0);
  glEnable(GL_NORMALIZE);

  struct Light {
    float radius;
    float color[3];
    float position[2];
  } lights[4] = {
    { .2, {  0, 0,.8 }, { -.5, -.5 } },
    { .2, { .8, 0, 0 }, {  .5, -.5 } },
    { .2, {  0,.8, 0 }, {  .5,  .5 } },
    { .2, { .9,.9,.9 }, { -.5,  .5 } },
  };
  for (unsigned i = 0; i != 4; ++i) {
    Light &l = lights[i];

    if (lights_enabled[i]) {
      glColor3fv(l.color);
      draw_circle_filled(l.position[0], l.position[1], l.radius);
    }
  }

  // Draw the beat monitor.
  const double beat_monitor_dim_time = .05;
  double elapsed = get_elapsed_time_in_seconds();
  if (elapsed - last_beat_time <= beat_monitor_dim_time) {
    double v = 1 - (elapsed - last_beat_time) / beat_monitor_dim_time;
    glColor3f(v, v, v);
    glRectf(-.9, -.9, -.7, -.8);
  }

  // Draw the 2D overlays.
  glEnable(GL_BLEND);
  glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();
  glOrtho(0, w, 0, h, -1, 1);

  glMatrixMode(GL_MODELVIEW);
  glLoadIdentity();

  const int textHeight = 15;
  char buffer[256];
  int y = 0;
  sprintf(buffer, "Time: %.4fs\n", elapsed);
  glColor3f(1, 1, 1);
  glutDrawString(10, 10 + textHeight*y++, buffer);

  if (true) {
    num_frames++;
    double fps = num_frames / elapsed;
    sprintf(buffer, "FPS: %.4fs\n", fps);
    glColor3f(1, 1, 1);
    glutDrawString(10, 10 + textHeight*y++, buffer);
  }

  if (light_manager) {
    double bpm = light_manager->GetRecentBPM();
    sprintf(buffer, "BPM: %.4fs\n", bpm);
    glColor3f(1, 1, 1);
    glutDrawString(10, 10 + textHeight*y++, buffer);
  }

  if (light_manager) {
    sprintf(buffer, "Program: %s\n", light_manager->GetProgramName().c_str());
    glColor3f(1, 1, 1);
    glutDrawString(10, 10 + textHeight*y++, buffer);
  }

  if (light_manager) {
    sprintf(buffer, "Strobe Enabled: %s\n",
            light_manager->GetStrobeEnabled() ? "yes" : "no");
    glColor3f(1, 1, 1);
    glutDrawString(10, 10 + textHeight*y++, buffer);
  }

  glFlush();

  glutSwapBuffers();
}
bool OGL_DoFades(float Left, float Top, float Right, float Bottom)
{
	if (!OGL_FaderActive()) return false;
	
	// Set up the vertices
	GLfloat Vertices[4][2];
	Vertices[0][0] = Left;
	Vertices[0][1] = Top;
	Vertices[1][0] = Right;
	Vertices[1][1] = Top;
	Vertices[2][0] = Right;
	Vertices[2][1] = Bottom;
	Vertices[3][0] = Left;
	Vertices[3][1] = Bottom;
	glVertexPointer(2,GL_FLOAT,0,Vertices[0]);
	
	// Do real blending
	glDisable(GL_ALPHA_TEST);
	glEnable(GL_BLEND);
	glDisable(GL_TEXTURE_2D);
	
	// Modified color:
	GLfloat BlendColor[4];	
	
	for (int f=0; f<NUMBER_OF_FADER_QUEUE_ENTRIES; f++)
	{
		OGL_Fader& Fader = FaderQueue[f];
		
		switch(Fader.Type)
		{
		case NONE:
			break;
		
		case _tint_fader_type:
			// The simplest kind: fade to the fader color.
			SglColor4fva(Fader.Color);
			glDrawArrays(GL_POLYGON,0,4);
			break;
		
		case _randomize_fader_type:
			UseFlatStatic = TEST_FLAG(Get_OGL_ConfigureData().Flags,OGL_Flag_FlatStatic);
			if (UseFlatStatic)
			{
				for (int c=0; c<3; c++)
					FlatStaticColor[c] = FlatStaticRandom.KISS() + FlatStaticRandom.LFIB4();
				FlatStaticColor[3] = PIN(int(65535*Fader.Color[3]+0.5),0,65535);
				glDisable(GL_ALPHA_TEST);
				glEnable(GL_BLEND);
				SglColor4usv(FlatStaticColor);
				glDrawArrays(GL_POLYGON,0,4);
			}
			else
			{
				// Do random flipping of the lower bits of color values;
				// the stronger the opacity (alpha), the more bits to flip.
				if (Using_sRGB) glDisable(GL_FRAMEBUFFER_SRGB_EXT);
				glDisable(GL_BLEND);
				MultAlpha(Fader.Color,BlendColor);
				glColor3fv(BlendColor);
				glEnable(GL_COLOR_LOGIC_OP);
				glLogicOp(GL_XOR);
				glDrawArrays(GL_POLYGON,0,4);
				// Revert to defaults
				glDisable(GL_COLOR_LOGIC_OP);
				glEnable(GL_BLEND);
				if (Using_sRGB) glEnable(GL_FRAMEBUFFER_SRGB_EXT);
			}
			break;
		
		case _negate_fader_type:
			// This is only a partial approximation of the negation effect
			// Neither glBlendColorEXT nor glBlendEquationEXT is currently supported
			// in ATI Rage 128 AppleGL, which makes my life more difficult :-P
			MultAlpha(Fader.Color,BlendColor);
			SglColor4fva(BlendColor);
			glBlendFunc(GL_ONE_MINUS_DST_COLOR,GL_ONE_MINUS_SRC_ALPHA);
			glDrawArrays(GL_POLYGON,0,4);
			// Revert to defaults
			glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
			break;
		
		case _dodge_fader_type:
			ComplementColor(Fader.Color,BlendColor);
			MultAlpha(BlendColor,BlendColor);
			SglColor4fva(BlendColor);
			glBlendFunc(GL_DST_COLOR,GL_ONE_MINUS_SRC_ALPHA);
			glDrawArrays(GL_POLYGON,0,4);
			glBlendFunc(GL_DST_COLOR,GL_ONE);
			glDrawArrays(GL_POLYGON,0,4);
			// Revert to defaults
			glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
			break;
		
		case _burn_fader_type:
			// Attempted to get that reversed-color effect at maximum intensity,
			// with it being only near maximum intensity
			// (MultAlpha + GL_SRC_ALPHA means opacity^2).
			MultAlpha(Fader.Color,BlendColor);
			SglColor4fva(BlendColor);
			glBlendFunc(GL_DST_COLOR,GL_ONE);
			glDrawArrays(GL_POLYGON,0,4);
			ComplementColor(Fader.Color,BlendColor);
			MultAlpha(BlendColor,BlendColor);
			SglColor4fva(BlendColor);
			glBlendFunc(GL_SRC_ALPHA,GL_ONE);
			glDrawArrays(GL_POLYGON,0,4);
			// Revert to defaults
			glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
			break;
		
		case _soft_tint_fader_type:
			// Fade to the color multiplied by the fader color,
			// as if the scene was illuminated by light with that fader color.
			if(Using_sRGB) {
				float alpha = std::sqrt(Fader.Color[3]);
				float corrected[4] = {
					sRGB_frob(Fader.Color[0])*alpha,
					sRGB_frob(Fader.Color[1])*alpha,
					sRGB_frob(Fader.Color[2])*alpha,
					alpha
				};
				MultAlpha(corrected,BlendColor);
			}
			else
				MultAlpha(Fader.Color,BlendColor);
			glColor4fv(BlendColor);
			glBlendFunc(GL_DST_COLOR,GL_ONE_MINUS_SRC_ALPHA);
			glDrawArrays(GL_POLYGON,0,4);
			// Revert to defaults
			glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
			break;
		}		
	}
	
	return true;
}
Beispiel #20
0
void DisplayScene()
{
	// kolor tła - zawartość bufora koloru
	glClearColor(1.0, 1.0, 1.0, 1.0);

	// czyszczenie bufora koloru i bufora głębokości
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	// wybór macierzy modelowania
	glMatrixMode(GL_MODELVIEW);

	// macierz modelowania = macierz jednostkowa
	glLoadIdentity();

	// przesunięcie układu współrzędnych obiektów do środka bryły odcinania
	glTranslatef(0.0, 0.0, -(near + far) / 2);

	// obroty obiektu
	glRotatef(rotatex, 1.0, 0.0, 0.0);
	glRotatef(rotatez, 0.0, 0.0, 1.0);

	// skalowanie obiektu - klawisze "+" i "-"
	glScalef(scale, scale, scale);

	// włączenie testu bufora głębokości
	glEnable(GL_DEPTH_TEST);

	// włączenie teksturowania dwuwymiarowego
	glEnable(GL_TEXTURE_2D);

	// filtr powiększający
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

	// filtr pomniejszający
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, min_filter);

	// dowiązanie wybranej tekstury
	glBindTexture(GL_TEXTURE_2D, texture);

	// ustawienie parametów środowiska tekstur
	glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);

	// utworzenie kwadryki
	GLUquadricObj *quadobj = gluNewQuadric();

	// styl (wygląd) generowanej kwadryki
	gluQuadricDrawStyle(quadobj, GLU_FILL);

	// sposób generacji wektorów normalnych
	gluQuadricNormals(quadobj, GLU_SMOOTH);

	// nałożenie tekstury na kwadrykę
	gluQuadricTexture(quadobj, GL_TRUE);

	// narysowanie kuli
	gluSphere(quadobj, 1.0, 30, 30);

	// usunięcie kwadryki
	gluDeleteQuadric(quadobj);

	// wyłączenie teksturowania dwuwymiarowego
	glDisable(GL_TEXTURE_2D);

	// informacje o wybranych parametrach bieżącej tekstury
	char string[200];
	GLfloat var;
	glColor3fv(Black);

	// wartość priorytetu tekstury
	glGetTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_PRIORITY, &var);
	sprintf_s(string, "GL_TEXTURE_PRIORITY = %f", var);
	DrawString(2, 2, string);

	// czy tekstura jest rezydentna
	glGetTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_RESIDENT, &var);
	if (var == GL_FALSE)
		strcpy_s(string, "GL_TEXTURE_RESIDENT = GL_FALSE");
	else
		strcpy_s(string, "GL_TEXTURE_RESIDENT = GL_TRUE");
	DrawString(2, 16, string);

	// szerokość tekstury (poziom 0)
	glGetTexLevelParameterfv(GL_TEXTURE_2D, 0, GL_TEXTURE_WIDTH, &var);
	sprintf_s(string, "GL_TEXTURE_WIDTH = %f", var);
	DrawString(2, 30, string);

	// wysokość tekstury (poziom 0)
	glGetTexLevelParameterfv(GL_TEXTURE_2D, 0, GL_TEXTURE_HEIGHT, &var);
	sprintf_s(string, "GL_TEXTURE_HEIGHT = %f", var);
	DrawString(2, 46, string);

	// skierowanie poleceñ do wykonania
	glFlush();

	// zamiana buforów koloru
	glutSwapBuffers();
}
void draw_cube(double radius) {
    GLfloat matspec[4] = {0.5, 0.5, 0.5, 0.0};
    glPushMatrix();
    glScaled(radius, radius, radius);
    glMaterialfv(GL_FRONT, GL_SPECULAR, matspec);
    glMaterialf(GL_FRONT, GL_SHININESS, 64.0);
    glBegin(GL_POLYGON);
    glColor3fv(lightblu_col);
    glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, lightblu_col);
    glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, lightblu_col);
    glNormal3f(0.0, 0.0, -1.0);
    glVertex3f(1.0, 1.0, -1.0);
    glVertex3f(1.0, -1.0, -1.0);
    glVertex3f(-1.0, -1.0, -1.0);
    glVertex3f(-1.0, 1.0, -1.0);
    glEnd();
    glBegin(GL_POLYGON);
    glColor3fv(blu_col);
    glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, blu_col);
    glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, blu_col);
    glNormal3f(0.0, 0.0, 1.0);
    glVertex3f(-1.0, 1.0, 1.0);
    glVertex3f(-1.0, -1.0, 1.0);
    glVertex3f(1.0, -1.0, 1.0);
    glVertex3f(1.0, 1.0, 1.0);
    glEnd();
    glBegin(GL_POLYGON);
    glColor3fv(yel_col);
    glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, yel_col);
    glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, yel_col);
    glNormal3f(0.0, -1.0, 0.0);
    glVertex3f(1.0, -1.0, 1.0);
    glVertex3f(-1.0, -1.0, 1.0);
    glVertex3f(-1.0, -1.0, -1.0);
    glVertex3f(1.0, -1.0, -1.0);
    glEnd();
    glBegin(GL_POLYGON);
    glColor3fv(grn_col);
    glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, grn_col);
    glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, grn_col);
    glNormal3f(0.0, 1.0, 0.0);
    glVertex3f(1.0, 1.0, 1.0);
    glVertex3f(1.0, 1.0, -1.0);
    glVertex3f(-1.0, 1.0, -1.0);
    glVertex3f(-1.0, 1.0, 1.0);
    glEnd();
    glBegin(GL_POLYGON);
    glColor3fv(pur_col);
    glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, pur_col);
    glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, pur_col);
    glNormal3f(-1.0, 0.0, 0.0);
    glVertex3f(-1.0, 1.0, 1.0);
    glVertex3f(-1.0, 1.0, -1.0);
    glVertex3f(-1.0, -1.0, -1.0);
    glVertex3f(-1.0, -1.0, 1.0);
    glEnd();
    glBegin(GL_POLYGON);
    glColor3fv(red_col);
    glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, red_col);
    glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, red_col);
    glNormal3f(1.0, 0.0, 0.0);
    glVertex3f(1.0, -1.0, 1.0);
    glVertex3f(1.0, -1.0, -1.0);
    glVertex3f(1.0, 1.0, -1.0);
    glVertex3f(1.0, 1.0, 1.0);
    glEnd();
    glPopMatrix();
}
Beispiel #22
0
static void draw_screen( OBJSC * model )
{
    /* Our angle of rotation. */

    /*
     * EXERCISE:
     * Replace this awful mess with vertex
     * arrays and a call to glDrawElements.
     *
     * EXERCISE:
     * After completing the above, change
     * it to use compiled vertex arrays.
     *
     * EXERCISE:
     * Verify my windings are correct here ;).
     */

    static GLubyte red[]    = { 255,   0,   0, 255 };
    static GLubyte green[]  = {   0, 255,   0, 255 };
    static GLubyte blue[]   = {   0,   0, 255, 255 };
    static GLubyte white[]  = { 255, 255, 255, 255 };
    static GLubyte yellow[] = {   0, 255, 255, 255 };
    static GLubyte black[]  = {   0,   0,   0, 255 };
    static GLubyte orange[] = { 255, 255,   0, 255 };
    static GLubyte purple[] = { 255,   0, 255,   0 };

    /* Clear the color and depth buffers. */
    glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );

    /* We don't want to modify the projection matrix. */
    glMatrixMode( GL_MODELVIEW );
    glLoadIdentity( );

    /* Move down the z-axis. */
    glRotatef( 20, 1.0, 0.0, 0.0 );
    glTranslatef( 0.0, -100.0, -150.0 );

    /* Rotate. */
    glRotatef( angle*8, 0.0, 1.0, 0.0 );

    /* Send our triangle data to the pipeline. */

    int i;
    for(i = 0; i < model->vlen; i++) {
        calc_vertex(model, i, game_time, speed);
        calc_vertex_normal(model, i, model->vntable[i]);
    }
    
    glBegin( GL_TRIANGLES );

    for(i = 0; i < model->flen; i++) {


        if(model->ftable[i].data == 2) {
            glColor4ubv( white );
        } else if(model->ftable[i].data == 3) {
            glColor4ubv( black );
        } else {
            glColor4ubv( black );
        }

        vec3 normal;


        vec3 a;
        vec3 b;
        vec3 c;

        vec3 an;
        vec3 bn;
        vec3 cn;

        vec3_cpy(a, model->vtable[model->ftable[i].a]);
        vec3_cpy(b, model->vtable[model->ftable[i].b]);
        vec3_cpy(c, model->vtable[model->ftable[i].c]);

        vec3_cpy(an, model->vntable[model->ftable[i].a]);
        vec3_cpy(bn, model->vntable[model->ftable[i].b]);
        vec3_cpy(cn, model->vntable[model->ftable[i].c]);

        glColor3fv( an);
        glVertex3fv( a );
        glColor3fv( bn);
        glVertex3fv( b );
        glColor3fv( cn);
        glVertex3fv( c );
    }


    glEnd( );

    /*
     * EXERCISE:
     * Draw text telling the user that 'Spc'
     * pauses the rotation and 'Esc' quits.
     * Do it using vetors and textured quads.
     */

    /*
     * Swap the buffers. This this tells the driver to
     * render the next frame from the contents of the
     * back-buffer, and to set all rendering operations
     * to occur on what was the front-buffer.
     *
     * Double buffering prevents nasty visual tearing
     * from the application drawing on areas of the
     * screen that are being updated at the same time.
     */
    SDL_GL_SwapBuffers( );
}
void			SceneRenderer::render(
				bool _lastFrame,
				bool _sameFrame,
				bool fullWindow)
{
  static const GLfloat blindnessColor[4] = { 1.0f, 1.0f, 0.0f, 1.0f };
  static const GLfloat dimnessColor[4] = { 0.0f, 0.0f, 0.0f, 1.0f };
  static const float dimDensity = 0.75f;
  bool               lighting   = BZDB.isTrue("lighting");

  lastFrame = _lastFrame;
  sameFrame = _sameFrame;

  // avoid OpenGL calls as long as possible -- there's a good
  // chance we're waiting on the vertical retrace.

  // set the view frustum
  if (sceneIterator) sceneIterator->resetFrustum(&frustum);

  // get the important lights in the scene
  int i;
  int numLights = 0;
  if (!sameFrame) {
    clearLights();
    if (sceneIterator && !blank && lighting) {
      // add lights
      sceneIterator->reset();
      SceneNode* node;
      while ((node = sceneIterator->getNext()) != NULL)
	node->addLight(*this);
      numLights = lights.size();

      // pick maxLights most important light sources
      // should go by full lighting function but we'll just go by distance
      if (numLights > maxLights) {
	const GLfloat* eye = frustum.getEye();
	for (i = 0; i < maxLights; i++) {
	  GLfloat maxImportance = lights[i]->getImportance(eye);
	  for (int j = i + 1; j < numLights; j++) {
	    GLfloat importance = lights[j]->getImportance(eye);
	    if (importance > maxImportance) {
	      OpenGLLight* temp = lights[i];
	      lights[j] = lights[i];
	      lights[i] = temp;
	      maxImportance = importance;
	    }
	  }
	}
	numLights = maxLights;
      }
    }
  }

  // get the nodes to draw
  if (!blank) {
    // empty the render node lists in preparation for the next frame
    OpenGLGState::clearLists();
    orderedList.clear();
    shadowList.clear();
    flareLightList.clear();

    // make the lists of render nodes sorted in optimal rendering order
    if (sceneIterator) {
      sceneIterator->reset();
      SceneNode* node;
      while ((node = sceneIterator->getNext()) != NULL)
	node->getRenderNodes(*this);
    }

    // sort ordered list in reverse depth order
    if (!inOrder)
      orderedList.sort(frustum.getEye());
  }

  // prepare transforms
  // note -- lights should not be positioned before view is set
  frustum.executeDeepProjection();
  glPushMatrix();
  frustum.executeView();

  // turn sunlight on -- the ground needs it
  if (lighting && sunOrMoonUp) {
    theSun.execute(SunLight);
    theSun.enableLight(SunLight);
  }

  // turn on fog for teleporter blindness if close to a teleporter
  float teleporterProximity = 0.0f;
  if (!blank && LocalPlayer::getMyTank() && (LocalPlayer::getMyTank()->getTeam() != ObserverTeam))
    teleporterProximity = LocalPlayer::getMyTank()->getTeleporterProximity();

  float worldSize = BZDB.eval(StateDatabase::BZDB_WORLDSIZE);
  bool reallyUseFogHack = useFogHack && (useQualityValue >= 2);
  if (reallyUseFogHack) {
    if (useDimming) {
      const float density = dimDensity;
      glFogi(GL_FOG_MODE, GL_LINEAR);
      glFogf(GL_FOG_START, -density * 1000.0f * worldSize);
      glFogf(GL_FOG_END, (1.0f - density) * 1000.0f * worldSize);
      glFogfv(GL_FOG_COLOR, dimnessColor);
      glEnable(GL_FOG);
    }
    else if (teleporterProximity > 0.0f && useFogHack) {
      const float density = (teleporterProximity > 0.75f) ?
				1.0f : teleporterProximity / 0.75f;
      glFogi(GL_FOG_MODE, GL_LINEAR);
      glFogf(GL_FOG_START, -density * 1000.0f * worldSize);
      glFogf(GL_FOG_END, (1.0f - density) * 1000.0f * worldSize);
      glFogfv(GL_FOG_COLOR, blindnessColor);
      glEnable(GL_FOG);
    }
  }

  // set scissor

  glScissor(window.getOriginX(), window.getOriginY() + window.getHeight() - window.getViewHeight(),
      window.getWidth(), window.getViewHeight());

  if (useDepthComplexityOn) {
  //  glEnable(GL_STENCIL_TEST);
   // glClear(GL_STENCIL_BUFFER_BIT);
  //  glStencilFunc(GL_ALWAYS, 0, 0xf);
	//	glStencilOp(GL_KEEP, GL_INCR, GL_INCR);
  }
  if (useHiddenLineOn) {
    //glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
   // glClear(GL_COLOR_BUFFER_BIT);
    glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
  }
  else if (useWireframeOn) {
    //glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
   // glClear(GL_COLOR_BUFFER_BIT);
    glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
  }

  // prepare z buffer
	/*
  if (BZDB.isTrue("zbuffer"))
	{
    if (sameFrame && ++depthRange == numDepthRanges)
			depthRange = 0;
    if (exposed || useHiddenLineOn || --depthRange < 0)
		{
      depthRange = numDepthRanges - 1;
      glClear(GL_DEPTH_BUFFER_BIT);
      exposed = false;
    }
    if (!sameFrame && numDepthRanges != 1)
		{
      if (useHiddenLineOn) {
	glDepthRange(0.0, 1.0);
      }
      else {
	GLclampd x_near = (GLclampd)depthRange * depthRangeSize;
	glDepthRange(x_near, x_near + depthRangeSize);
      }
    }
  }
	*/
  // draw start of background (no depth testing)
  OpenGLGState::resetState();
  if (background)
	{
    background->setBlank(blank);
    background->setInvert(invert);
    background->renderSkyAndGround(*this, fullWindow);
  }

  // prepare the other lights but don't turn them on yet --
  // we may need to turn them on when drawing the background.
  if (lighting) {
    for (i = 0; i < numLights; i++)
      lights[i]->execute(i + reservedLights);
  }

  // draw rest of background
  if (background)
    background->render(*this);

  if (!blank) {
    if (lighting) {
      // now turn on the remaining lights
      for (i = 0; i < numLights; i++)
	OpenGLLight::enableLight(i + reservedLights);
    }

    frustum.executeProjection();
    if (BZDB.isTrue("zbuffer")) glEnable(GL_DEPTH_TEST);

    if (useHiddenLineOn) {
#if defined(GL_VERSION_1_1)
      glEnable(GL_POLYGON_OFFSET_FILL);
#elif defined(GL_EXT_polygon_offset)
      glEnable(GL_POLYGON_OFFSET_EXT);
#endif
    }
		// render the normal stuff
   doRender();

    if (useHiddenLineOn) {
#if defined(GL_VERSION_1_1)
      glDisable(GL_POLYGON_OFFSET_FILL);
#elif defined(GL_EXT_polygon_offset)
      glDisable(GL_POLYGON_OFFSET_EXT);
#endif
      glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
      glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
      doRender();
      glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
    }

    OpenGLGState::resetState();

    // shut off lights
    if (lighting) {
      theSun.enableLight(SunLight, false);
      for (i = 0; i < numLights; i++)
	OpenGLLight::enableLight(i + reservedLights, false);
    }

    if (BZDB.isTrue("zbuffer")) glDisable(GL_DEPTH_TEST);

    // FIXME -- must do post-rendering: flare lights, etc.
    // flare lights are in world coordinates.  trace ray to that world
    // position and calculate opacity.  if opaque then don't render
    // flare, otherwise modulate input color by opacity and draw a
    // billboard texture (constant size in screen space).
  }

  // back to original state
  if (!useHiddenLineOn && useWireframeOn)
    glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
  glPopMatrix();

  if ((reallyUseFogHack && (teleporterProximity > 0.0f || useDimming)))
    glDisable(GL_FOG);

  if (!reallyUseFogHack) {
    float density = 0.0f;
    const GLfloat* color = NULL;
    if (useDimming) {
      density = dimDensity;
      color = dimnessColor;
    }
    else if (teleporterProximity > 0.0f) {
      density = (teleporterProximity > 0.75f) ?
			1.0f : teleporterProximity / 0.75f;
      color = blindnessColor;
    }
    if (density > 0.0f && color != NULL) {
      glMatrixMode(GL_PROJECTION);
      glLoadIdentity();
      glMatrixMode(GL_MODELVIEW);
      glColor4f(color[0], color[1], color[2], density);
			glRectf(-1.0f, -1.0f, 1.0f, 1.0f);
    }
  }

  if (useDepthComplexityOn) {
    static const GLfloat depthColors[][3] = {
				{ 0.0f, 0.0f, 0.0f },	// black -- 0 times
				{ 0.5f, 0.0f, 1.0f },	// purple -- 1 time
				{ 0.0f, 0.0f, 1.0f },	// blue -- 2 times
				{ 0.0f, 1.0f, 1.0f },	// cyan -- 3 times
				{ 0.0f, 1.0f, 0.0f },	// green -- 4 times
				{ 1.0f, 1.0f, 0.0f },	// yellow -- 5 times
				{ 1.0f, 0.5f, 0.0f },	// orange -- 6 times
				{ 1.0f, 0.0f, 0.0f }	// red -- 7 or more
			};
    static const int numColors = countof(depthColors);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glMatrixMode(GL_MODELVIEW);
    glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
    for (i = 0; i < numColors; i++) {
      glStencilFunc(i == numColors - 1 ? GL_LEQUAL : GL_EQUAL, i, 0xf);
      glColor3fv(depthColors[i]);
      glRectf(-1.0f, -1.0f, 1.0f, 1.0f);
    }
    glDisable(GL_STENCIL_TEST);
  }
}
Beispiel #24
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 > GET_MAX_LOD_FACES_NUMBER() && context.decimateMeshOnMove && MACRO_LODActivated(context));
		unsigned decimStep = (lodEnabled ? (unsigned)ceil((float)triNum*3 / (float)GET_MAX_LOD_FACES_NUMBER()) : 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())
			{
				glColor3ubv(m_tempColor);
				glParams.showColors = false;
			}
			else
			{
				assert(vertices->isA(CC_TYPES::POINT_CLOUD));
				rgbColorsTable = static_cast<ccPointCloud*>(vertices)->rgbColors();
			}
		}
		else
		{
			glColor3fv(context.defaultMat.diffuseFront);
		}

		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<(int)materials->size());
						glEnd();
						if (showTextures)
						{
							GLuint texID = (newMatlIndex>=0 ? (*materials)[newMatlIndex].texID : 0);
							if (texID>0)
								assert(glIsTexture(texID));
							glBindTexture(GL_TEXTURE_2D, texID);
						}

						//if we don't have any current material, we apply default one
						(newMatlIndex>=0 ? (*materials)[newMatlIndex] : 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();
	}
}
Beispiel #25
0
void GeometryEngine::drawBaseMesh(BaseMesh* mesh, QGLWidget* glWidget, unsigned int flags)
{
    if (mesh == NULL) return;
    glDisable(GL_TEXTURE_2D);
    glDisable(GL_LIGHTING);
    glEnable(GL_DEPTH_TEST);


    QVector<Edge *> edges = mesh->GetEdges();
    for(int i=0;i<edges.size();i++)
    {
        float UT_color[3];
        if(edges[i]->GetFlag()==1)
            glColor3f(1.0,0.0,0.0);
        else
            if(edges[i]->GetFlag()==-1)
                glColor3f(0.0,1.0,0.0);
            else
                glColor3f(0.0,0.0,1.0);

        Vertex* start_v = edges[i]->GetStart();
        Vertex* end_v = edges[i]->GetEnd();
        glBegin(GL_LINES);
        glVertex3f(start_v->x(),start_v->y(),start_v->z());
        glVertex3f(end_v->x(),end_v->y(),end_v->z());
        glEnd();

//        if(glWidget)
//        {
//            glDisable(GL_DEPTH_TEST);
//            glColor3f(0.0, 0.0, 0.0);
//            QFont m_font;
//            m_font.setPointSize(15);
//            QString cur = QString("%1").arg(edges[i]->Weight(),0,'f',3);
//            glWidget->renderText((start_v->x()+end_v->x())/2, (start_v->y()+end_v->y())/2, (start_v->z()+end_v->z())/2,cur,m_font);
//        }
    }


    float UT_color[3];
    QVector <Vertex*> verts = mesh->GetVertices();
    glBegin(GL_POINTS);
    for (int i=0; i<verts.size(); ++i){
        UTILS_color_hue_to_rgb(verts[i]->Value()/720.0,UT_color);
        glColor3fv(UT_color);
        glVertex3f(verts[i]->x(), verts[i]->y(), verts[i]->z());
    }
    glEnd();


    if (flags&SHADED)
    {
        QVector <Face*> faces = mesh->GetFaces();
        for (int i=0; i<faces.size(); ++i)  {
            QVector <Vertex* > vertices = faces[i]->GetVertices();
            float UT_color[3];
            glBegin(GL_POLYGON);

            for (int j=0; j<vertices.size(); ++j)
            {
                glColor4f(vertices[j]->Value(), vertices[j]->Value(), vertices[j]->Value(), 1);
                UTILS_color_hue_to_rgb(vertices[j]->Value()/720.0,UT_color);
                glColor3fv(UT_color);
                glVertex3f(vertices[j]->x(), vertices[j]->y(), vertices[j]->z());
            }
            glEnd();
        }
    }

    if (flags&VERTEX_DATA)
    {

        glDisable(GL_DEPTH_TEST);
        glColor3f(0.0, 0.0, 0.0);
        QFont m_font;
        m_font.setPointSize(15);

        for (int i=0; i<verts.size(); ++i)  {
            QString cur = QString("%1").arg(verts[i]->Value(),0,'f',3);
            glWidget->renderText(verts[i]->x(), verts[i]->y(), verts[i]->z(),cur,m_font);
        }
    }



/*
    QVector <Face*> faces = mesh->GetFaces();
    for (int i=0; i<faces.size(); ++i)  {
        QVector <Vertex* > vertices = faces[i]->GetVertices();
        float UT_color[3];
//        glBegin(GL_LINE_LOOP);

//        for (int j=0; j<vertices.size(); ++j)
//        {
////            glColor4f(vertices[j]->Value(), vertices[j]->Value(), vertices[j]->Value(), 1);
//            UTILS_color_hue_to_rgb(vertices[j]->Value()/720.0,UT_color);
//            glColor3fv(UT_color);
//            glVertex3f(vertices[j]->x(), vertices[j]->y(), vertices[j]->z());
//        }
//        glEnd();
        glBegin(GL_POINTS);
        for (int j=0; j<vertices.size(); ++j)
        {
//            glColor4f(vertices[j]->Value(), vertices[j]->Value(), vertices[j]->Value(), 1);
            UTILS_color_hue_to_rgb(vertices[j]->Value()/720.0,UT_color);
            glColor3fv(UT_color);
            glVertex3f(vertices[j]->x(), vertices[j]->y(), vertices[j]->z());
        }
        glEnd();


//        glColor4f(1.0, 1.0, 1.0, 0.5);
//        for (int j=0; j<faces.size(); ++j)
//        {
//            glBegin(GL_POLYGON);
//            QVector<Vertex*> f_vertices = faces[i]->GetVertices();
//            for(int k=0;k<f_vertices.size();k++)
//            {
//                UTILS_color_hue_to_rgb(f_vertices[k]->Value()/720.0,UT_color);
//                glColor3fv(UT_color);
//                glVertex3f(f_vertices[k]->x(), f_vertices[k]->y(), f_vertices[k]->z());
//            }
//            glEnd();
//        }


        if(glWidget && (flags&VERTEX_DATA))
        {
            glDisable(GL_DEPTH_TEST);
            glColor3f(0.0, 0.0, 0.0);
            QFont m_font;
            m_font.setPointSize(15);
            for (int j=0; j<vertices.size(); ++j)
            {
                QString cur = QString("%1").arg(vertices[j]->Value(),0,'f',3);
                glWidget->renderText(vertices[j]->x(), vertices[j]->y(), vertices[j]->z(),cur,m_font);
            }
        }

    }*/
}