Example #1
0
bool MgCmdErase::touchMoved(const MgMotion* sender)
{
    Box2d snap(sender->startPointM, sender->pointM);
    void *it = NULL;
    MgShape* shape = m_boxsel ? sender->view->shapes()->getFirstShape(it) : NULL;
    
    m_delIds.clear();
    for (; shape; shape = sender->view->shapes()->getNextShape(it)) {
        if (isIntersectMode(sender) ? shape->shape()->hitTestBox(snap)
            : snap.contains(shape->shape()->getExtent())) {
            m_delIds.push_back(shape->getID());
        }
    }
    sender->view->shapes()->freeIterator(it);
    sender->view->redraw(false);
    
    return true;
}
Example #2
0
int32 PopupMenu::processAction(QAction *a, int32 index, int32 w) {
	if (a->isSeparator() || a->text().isEmpty()) {
		_texts[index] = _shortcutTexts[index] = QString();
	} else {
		QStringList texts = a->text().split('\t');
		int32 textw = _st.itemFont->width(texts.at(0));
		int32 goodw = _padding.left() + _st.itemPadding.left() + textw + _st.itemPadding.right() + _padding.right();
		if (_menus.at(index)) {
			goodw += _st.itemPadding.left() + _st.arrow.width();
		} else if (texts.size() > 1) {
			goodw += _st.itemPadding.left() + _st.itemFont->width(texts.at(1));
		}
		w = snap(goodw, w, int32(_padding.left() + _st.widthMax + _padding.right()));
		_texts[index] = (w < goodw) ? _st.itemFont->elided(texts.at(0), w - (goodw - textw)) : texts.at(0);
		_shortcutTexts[index] = texts.size() > 1 ? texts.at(1) : QString();
	}
	return w;
}
 void VirtualFont::addCluster(const Cluster &cluster, const Vec3f &position)
 {
     for (auto &shape : cluster.shapes)
     {
         Vec2f p = properties.useMipmap ? position.xy() : Vec2f(snap(position.x), snap(position.y));
         
         Quad quad;
         auto glyph = cluster.font->fillQuad(quad, shape, p, sizeRatio);
         
         if (glyph)
         {
             if (!hasClip || clipQuad(quad, glyph->texture))
             {
                 auto batch = batchMap->getBatch(glyph->texture);
                 batch->addQuad(quad, position.z);
                 incrementSequence(batch);
             }
         }
     }
 }
    void object::test<2>()
    {
        GeomAutoPtr src(reader.read(
                "POLYGON ((0 0, 0 100, 100 100, 100 0, 0 0))"
        ));

        GeometrySnapper snapper( *(src.get()) );

        GeomAutoPtr snap(reader.read(
                "MULTIPOINT ((0.0000001 50))"
        ));

        GeomAutoPtr expected(reader.read(
                "POLYGON ((0 0, 0.0000001 50, 0 100, 100 100, 100 0, 0 0))"
        ));

        GeomAutoPtr ret(snapper.snapTo( *(snap.get()), 0.000001 ));

        ensure( ret->equalsExact(expected.get(),0) );
    }
Example #5
0
int WINAPI WinMain(	HINSTANCE hInstance,
					HINSTANCE hPrevInstance,
					LPTSTR    lpCmdLine,
					int       nCmdShow)
{
	ServerSocket serverSocket;

	if (serverSocket.init()) {
		SOCKET s = serverSocket.acceptClient();
		if (s != INVALID_SOCKET) {
			HANDLE clientEvent = CreateEvent (NULL, FALSE, FALSE, TEXT("WriteEvent"));
			Snap snap(s, clientEvent);
			if (snap.start()) {
				EventProcessor eventProcessor(s, clientEvent);
				eventProcessor.start();
			}
		}
	}

	return 0;
}
Example #6
0
static int
movealias(mmv_t *mmv, REP *first, REP *p, int *pprintaliased)
{
    int seq;
    int rv;
    int err;

    strcpy(mmv->pathbuf, p->r_hto->h_name);
    seq = make_alias_fname(mmv, p);
    rv = rename(mmv->fullrep, mmv->pathbuf);
    if (rv) {
        err = errno;
        eprint_filename(mmv->fullrep);
        fputs(" -> ", stderr);
        eprint_filename(mmv->pathbuf);
        fputs(" has failed.\n", stderr);
        eexplain_err(err);
        *pprintaliased = snap(mmv, first, p);
    }
    return (seq);
}
Example #7
0
  /**
   * Called to see if an object's metadata is still current.
   *
   * @param obj     The object to check.
   * @param exp_ver The version that we expect the object to be at.
   *
   * @returns       true if the object is current.
   */
  bool isCurrent(const Object* const obj, unsigned long version) const {
    // check if shared.header and expected_version agree on the currently
    // valid version of the data
    assert(obj);
    metadata_dword_t snap(obj->m_metadata);

    // if nobody has acquired this object, then the version will match
    // expected_ver
    if (snap.fields.ver.version == version)
      return true;

    // uh-oh!  It doesn't match.  If the version number is odd or 2, then we
    // must immediately fail.  If the version number is not a pointer to
    // /this/, then we must fail.  If the version number is a pointer to
    // /this/, then we succeed only if the clone's version is version.  So to
    // keep it easy, let's compare the ver.owner to /this/...
    if (snap.fields.ver.owner != this)
      return false;

    // ok, it should be safe to dereference the redoLog
    return snap.fields.redoLog->m_metadata.fields.ver.version == version;
  }
void QgsMapToolAdvancedDigitizing::canvasReleaseEvent( QgsMapMouseEvent* e )
{
  snap( e );

  QgsAdvancedDigitizingDockWidget::AdvancedDigitizingMode dockMode;
  switch ( mCaptureMode )
  {
    case CaptureLine:
    case CapturePolygon:
      dockMode = QgsAdvancedDigitizingDockWidget::ManyPoints;
      break;
    case CaptureSegment:
      dockMode = QgsAdvancedDigitizingDockWidget::TwoPoints;
      break;
    default:
      dockMode = QgsAdvancedDigitizingDockWidget::SinglePoint;
      break;
  }

  if ( !mCadDockWidget->canvasReleaseEvent( e, dockMode ) )
    cadCanvasReleaseEvent( e );
}
Example #9
0
void Playback::updateState(const Player::TrackState &state) {
	qint64 position = 0, length = state.length;

	auto wasInLoadingState = _inLoadingState;
	if (wasInLoadingState) {
		_inLoadingState = false;
		if (_inLoadingStateChanged) {
			_inLoadingStateChanged(false);
		}
	}

	_playing = !Player::IsStopped(state.state);
	if (Player::IsStoppedAtEnd(state.state)) {
		position = state.length;
	} else if (!Player::IsStoppedOrStopping(state.state)) {
		position = state.position;
	} else {
		position = 0;
	}

	auto progress = 0.;
	if (position > length) {
		progress = 1.;
	} else if (length) {
		progress = snap(float64(position) / length, 0., 1.);
	}
	auto animatedPosition = position + (state.frequency * kPlaybackAnimationDurationMs / 1000);
	auto animatedProgress = length ? qMax(float64(animatedPosition) / length, 0.) : 0.;
	if (length != _length || position != _position || wasInLoadingState) {
		if (auto animated = (length && _length && animatedProgress > value())) {
			setValue(animatedProgress, animated);
		} else {
			setValue(progress, animated);
		}
		_position = position;
		_length = length;
	}
}
Example #10
0
void Fl_Sparkline::draw(void)
{
    int i;
    int index;

    width = w() - padding * 2;
    height = h() - padding * 2;

    if (num_values == 0) {
        draw_box();
        return;
    }

    if (damage() == FL_DAMAGE_USER1) {
        index = num_values * (Fl::event_x() - x() - padding) / width;
        index = snap(index);
        tip->position(Fl::event_x_root() + 10, Fl::event_y_root() + 10);
        tip->value(values[index]);
        tip->show();

        drawCursor();
        return;
    }

    draw_box();

    fl_color(FL_BLACK);

    drawPeaks();
    fl_color(FL_BLACK);

    for (i = 0; i < width; i++) {
        drawPoint(i);
    }

    draw_label();
}
Example #11
0
int Fl_Sparkline::handle(int e)
{
    switch (e) {
    case FL_MOVE:
        damage(FL_DAMAGE_USER1);
        return 1;

    case FL_LEAVE:
        damage(1);
        /* fall through */

    case FL_HIDE:
        tip->hide();
        return 1;

    case FL_PUSH:
        if (scrollFunc) {
            int x = Fl::event_x() - Fl_Widget::x();
            int index;

            x -= padding;

            index = num_values * x / width;
            index = snap(index);

            scrollFunc(index, table);
        }
        return 1;

    case FL_ENTER:
    case FL_DRAG:
        return 1;

    default:
        return Fl_Widget::handle(e);
    }
}
Example #12
0
 Vec3f Grid::snap(const Vec3f& p, const Plane& onPlane) const {
     Vec3f result;
     switch(onPlane.normal.firstComponent()) {
         case Axis::AX:
             result.y = snap(p.y);
             result.z = snap(p.z);
             result.x = onPlane.x(result.y, result.z);
             break;
         case Axis::AY:
             result.x = snap(p.x);
             result.z = snap(p.z);
             result.y = onPlane.y(result.x, result.z);
             break;
         case Axis::AZ:
             result.x = snap(p.x);
             result.y = snap(p.y);
             result.z = onPlane.z(result.x, result.y);
             break;
     }
     return result;
 }
Example #13
0
 Vec3f Grid::snap(const Vec3f& p, const Planef& onPlane) const {
     Vec3f result;
     switch(onPlane.normal.firstComponent()) {
         case Axis::AX:
             result[1] = snap(p.y());
             result[2] = snap(p.z());
             result[0] = onPlane.x(result.y(), result.z());
             break;
         case Axis::AY:
             result[0] = snap(p.x());
             result[2] = snap(p.z());
             result[1] = onPlane.y(result.x(), result.z());
             break;
         case Axis::AZ:
             result[0] = snap(p.x());
             result[1] = snap(p.y());
             result[2] = onPlane.z(result.x(), result.y());
             break;
     }
     return result;
 }
Example #14
0
QVariant Pin::itemChange(GraphicsItemChange change, const QVariant &value)
{
	// Note that pins are only movable within the symbol editor.

	PageScene *pageScene = dynamic_cast<PageScene *>(scene());
	if (ItemPositionChange == change && pageScene) {
		QPointF p = value.toPointF() + pageScene->reparentOffset(this);	// p is now the position relative to the current parent.
		SymbolEditor *se = dynamic_cast<SymbolEditor *>(pageScene->parent());
		if (se) {
			QGraphicsItem *anchor = se->closestPinAnchor(parentItem()->mapToScene(p), this);
			if (parentItem() != anchor) {
				pageScene->reparentWhileDragging(this, anchor);
				p = value.toPointF() + pageScene->reparentOffset(this);
				setData(FreeSCH::SectionChanged, true);
			}
			if (QGraphicsLineItem::Type == anchor->type()) {
				p.setX(anchor->pos().x());
				if (position.side() != PinPosition::Right) {
					position.setSide(PinPosition::Right);
					attributes.setValue("side", PinPosition::sideNames.at(PinPosition::Right));
					reorient();
				}
			} else if (Section::Type == anchor->type()) {
				Section *section = qgraphicsitem_cast<Section *>(anchor);
				if (section) {
					QRectF r = QRectF(QPointF(0,0), section->rect().size());
					PinPosition::PinSide newside = PinPosition::sideIndex(r, p);
					switch (newside) {
					case PinPosition::Right:
						p.setX(r.right());
						break;
					case PinPosition::Bottom:
						p.setY(r.bottom());
						break;
					case PinPosition::Left:
						p.setX(r.left());
						break;
					default: // top
						p.setY(r.top());
						break;
					}
					if (p.x() < 0)
						p.setX(0);
					if (p.x() > r.width())
						p.setX(r.width());
					if (p.y() < 0)
						p.setY(0);
					if (p.y() > r.height())
						p.setY(r.height());

					if (position.side() != newside) {
						position.setSide(newside);
						attributes.setValue("side", PinPosition::sideNames.at(newside));
						updateOffset(snap(p).toPoint());
						reorient();
						// As the pin moves around a corner of a section, it can switch sides without its pos() changing.
						// In that case the ItemPositionHasChanged event doesn't occur. So we need to emit the moved signal here.

						emit moved();
					}
				}
			}
		}
		return snap(p);
	}
	if (ItemPositionHasChanged == change && pageScene) {
		updateOffset(pos().toPoint());

		if (data(FreeSCH::SectionChanged).toBool()) {
			setData(FreeSCH::SectionChanged, false);
			emit sectionChanged(this, parentItem());
		}
		emit moved();
	}
	return QGraphicsItem::itemChange(change, value);
}
void QgsMapToolAdvancedDigitizing::canvasMoveEvent( QgsMapMouseEvent* e )
{
  snap( e );
  if ( !mCadDockWidget->canvasMoveEvent( e ) )
    cadCanvasMoveEvent( e );
}
Example #16
0
/*------------------------------------------------------------------------------
  Main program.
*/
int main(int argc, char *argv[])
{
    int ifile, nadj, nfiles, npoly, npolys, i;
    polygon **polys;
    polys=polys_global;

    /* default output format */
    fmt.out = keywords[POLYGON];
    /* default is to renumber output polygons with old id numbers */
    fmt.newid = 'o';

    /* parse arguments */
    parse_args(argc, argv);

    /* at least one input and output filename required as arguments */
    if (argc - optind < 2) {
	if (optind > 1 || argc - optind == 1) {
	    fprintf(stderr, "%s requires at least 2 arguments: polygon_infile and polygon_outfile\n", argv[0]);
	    usage();
	    exit(1);
	} else {
	    usage();
	    exit(0);
	}
    }

    msg("---------------- snap ----------------\n");

    /* snap angles */
    scale(&axtol, axunit, 's');
    scale(&btol, bunit, 's');
    scale(&thtol, thunit, 's');
    axunit = 's';
    bunit = 's';
    thunit = 's';
    msg("snap angles: axis %Lg%c latitude %Lg%c edge %Lg%c\n", axtol, axunit, btol, bunit, thtol, thunit);
    scale(&axtol, axunit, 'r');
    scale(&btol, bunit, 'r');
    scale(&thtol, thunit, 'r');
    axunit = 'r';
    bunit = 'r';
    thunit = 'r';

    /* tolerance angle for multiple intersections */
    if (mtol != 0.) {
	scale(&mtol, munit, 's');
	munit = 's';
	msg("multiple intersections closer than %Lg%c will be treated as coincident\n", mtol, munit);
	scale(&mtol, munit, 'r');
	munit = 'r';
    }

    /* advise data format */
    advise_fmt(&fmt);

    /* read polygons */
    npoly = 0;
    nfiles = argc - 1 - optind;
    for (ifile = optind; ifile < optind + nfiles; ifile++) {
	npolys = rdmask(argv[ifile], &fmt, NPOLYSMAX - npoly, &polys[npoly]);
	if (npolys == -1) exit(1);
	npoly += npolys;
    }
    if (nfiles >= 2) {
	msg("total of %d polygons read\n", npoly);
    }
    if (npoly == 0) {
	msg("STOP\n");
	exit(0);
    }

    /* adjust boundaries of polygons */
    nadj = snap(npoly, polys);
    if(nadj==-1) exit(1);

    snapped=1;
    
    /* write polygons */
    ifile = argc - 1;
    npoly = wrmask(argv[ifile], &fmt, npoly, polys);
    if (npoly == -1) exit(1);
 
    for(i=0;i<npoly;i++){
      free_poly(polys[i]);
    }

    return(0);
}
Example #17
0
int main ( int argc, char *argv[] )

/******************************************************************************/
/*
  Purpose:

    MAIN is the main program for MD.

  Discussion:

    MD implements a simple molecular dynamics simulation.

    The velocity Verlet time integration scheme is used. 

    The particles interact with a central pair potential.

  Usage:

    md nd np step_num print_step_num dt mass printinfo scale_factor scale_offset seed outFile trajectoryFile
    where
    * nd is the spatial dimension (2 or 3);
    * np is the number of particles (500, for instance);
    * step_num is the number of time steps (500, for instance);
    * print_step_num is the number of snapshot prints (10 for instance);
    * dt is size of timestep;
    * mass is particle mass;
    * printinfo is a string to append to each particle coord
    * scale_offset and scale_factor are used to scale particle positions for logging/rendering (FIXME)
    * seed sets the initial configuration
    

  Licensing:

    This code is distributed under the GNU LGPL license. 

  Modified:

    05 November 2010

  Author:

    Original FORTRAN90 version by Bill Magro.
    C version by John Burkardt.

  Parameters:

    None
*/
{
  double *acc;
  double *box;
  double ctime;
  double ctime1;
  double ctime2;
  double dt = 0.0001;
  double e0;
  double *force;
  int i;
  int id;
  double kinetic;
  double mass = 1.0 * .0001;
  int nd;
  int np;
  double *pos;
  double potential;
  int seed = 123456789;
  int step;
  int step_num;
  int step_print;
  int step_print_index;
  int step_print_num=10;
  double *vel;

  timestamp ( );
  printf ( "\n" );
  printf ( "MD\n" );
  printf ( "  C version\n" );
  printf ( "  A molecular dynamics program.\n" );
/*
  Get the spatial dimension.
*/
  if ( 1 < argc )
  {
    nd = atoi ( argv[1] );
  }
  else
  {
    printf ( "\n" );
    printf ( "  Enter ND, the spatial dimension (2 or 3).\n" );
    scanf ( "%d", &nd );
  }
//
//  Get the number of points.
//
  if ( 2 < argc )
  {
    np = atoi ( argv[2] );
  }
  else
  {
    printf ( "\n" );
    printf ( "  Enter NP, the number of points (500, for instance).\n" );
    scanf ( "%d", &np );
  }
//
//  Get the number of time steps.
//
  if ( 3 < argc )
  {
    step_num = atoi ( argv[3] );
  }
  else
  {
    printf ( "\n" );
    printf ( "  Enter ND, the number of time steps (500 or 1000, for instance).\n" );
    scanf ( "%d", &step_num );
  }
  /*
	Get any additional args (command-line only)
	md nd np step_num [ step__print_num dt mass printinfo scale_factor scale_offset randomseed outfile trjfile ]
  */
  if ( 4 < argc )
  {
    step_print_num = atoi ( argv[4] );
  }
  if ( 5 < argc )
  {
    dt = atof ( argv[5] );
  }
  if ( 6 < argc )
  {
    mass = atof ( argv[6] );
  }
  if ( 7 < argc )
  {
    printinfo = ( argv[7] );
  }
  if ( 8 < argc )
  {
    scale_factor = atof ( argv[8] );
  }
  if ( 9 < argc )
  {
    scale_offset = atof ( argv[9] );
  }
  if ( 10 < argc )
  {
    seed = atof ( argv[10] );
  }
  if ( 11 < argc )
  {
    outfile = argv[11];
  }
  if ( 12 < argc )
  {
    trjfile = argv[12];
  }

/*
  Report.
*/
  printf ( "\n" );
  printf ( "  MD: Argument count: %d\n", argc );
  printf ( "  ND, the spatial dimension, is %d\n", nd );
  printf ( "  NP, the number of particles in the simulation, is %d\n", np );
  printf ( "  STEP_NUM, the number of time steps, is %d\n", step_num );
  printf ( "  STEP_PRINT_NUM, the number of snapshots to print, is %d\n", step_print_num );
  printf ( "  DT, the size of each time step, is %f\n", dt );
  printf ( "  MASS, the particle mass, is %f\n", mass );
  printf ( "  PRINTINFO, the pass-through info to c-ray, is %s\n", printinfo );
  printf ( "  SCALE_FACTOR, the particle position scaling factor, is %f\n", scale_factor );
  printf ( "  SCALE_OFFSET, the particle position scaling offset, is %f\n", scale_offset );
  printf ( "  SEED, the simulation randomization seed, is %d\n", seed );
/*
  Allocate memory.
*/
  acc = ( double * ) malloc ( nd * np * sizeof ( double ) );
  box = ( double * ) malloc ( nd * sizeof ( double ) );
  force = ( double * ) malloc ( nd * np * sizeof ( double ) );
  pos = ( double * ) malloc ( nd * np * sizeof ( double ) );
  vel = ( double * ) malloc ( nd * np * sizeof ( double ) );
/*
  Set the dimensions of the box.
*/
  for ( i = 0; i < nd; i++ )
  {
    box[i] = 10.0;
  }

  printf ( "\n" );
  printf ( "  Initializing positions, velocities, and accelerations.\n" );
/*
  Set initial positions, velocities, and accelerations.
*/
  initialize ( np, nd, box, &seed, pos, vel, acc );
/*
  Compute the forces and energies.
*/
  printf ( "\n" );
  printf ( "  Computing initial forces and energies.\n" );

  compute ( np, nd, pos, vel, mass, force, &potential, &kinetic );

  e0 = potential + kinetic;
/*
  This is the main time stepping loop:
    Compute forces and energies,
    Update positions, velocities, accelerations.
*/
  printf ( "\n" );
  printf ( "  At each step, we report the potential and kinetic energies.\n" );
  printf ( "  The sum of these energies should be a constant.\n" );
  printf ( "  As an accuracy check, we also print the relative error\n" );
  printf ( "  in the total energy.\n" );
  printf ( "\n" );
  printf ( "      Step      Potential       Kinetic        (P+K-E0)/E0\n" );
  printf ( "                Energy P        Energy K       Relative Energy Error\n" );
  printf ( "\n" );

  FILE *ofile = fopen(outfile,"w");
  fprintf (ofile, "      Step      Potential       Kinetic        RelativeErr\n" );

  step_print = 0;
  step_print_index = 0;
  
  step = 0;
  printf ( "  %8d  %14f  %14f  %14e\n",
    step, potential, kinetic, ( potential + kinetic - e0 ) / e0 );
  fprintf ( ofile, "  %8d  %14f  %14f  %14e\n",
    step, potential, kinetic, ( potential + kinetic - e0 ) / e0 );
  step_print_index = step_print_index + 1;
  step_print = ( step_print_index * step_num ) / step_print_num;

  ctime1 = cpu_time ( );

  for ( step = 1; step <= step_num; step++ )
  {
    compute ( np, nd, pos, vel, mass, force, &potential, &kinetic );

    if ( step == step_print )
    {
      printf ( "  %8d  %14f  %14f  %14e\n", step, potential, kinetic,
       ( potential + kinetic - e0 ) / e0 );
      fprintf ( ofile, "  %8d  %14f  %14f  %14e\n", step, potential, kinetic,
       ( potential + kinetic - e0 ) / e0 );
      step_print_index = step_print_index + 1;
      step_print = ( step_print_index * step_num ) / step_print_num;
    snap ( np, nd, pos, vel, force, acc, mass, dt );
    }
    update ( np, nd, pos, vel, force, acc, mass, dt );
  }
  ctime2 = cpu_time ( );
  ctime = ctime2 - ctime1;

  printf ( "\n" );
  printf ( "  Elapsed cpu time for main computation:\n" );
  printf ( "  %f seconds.\n", ctime );

  free ( acc );
  free ( box );
  free ( force );
  free ( pos );
  free ( vel );
  char tarcmd[2000];
  sprintf(tarcmd,"tar zcf %s md??.trj",trjfile);
  system(tarcmd);
/*
  Terminate.
*/
  printf ( "\n" );
  printf ( "MD\n" );
  printf ( "  Normal end of execution.\n" );

  printf ( "\n" );
  timestamp ( );

  fclose(ofile);
  return 0;
}
//----------------------------------------------------------------------------
// ** Note:  The vertex and plane normals values are swapped
// around to align with our normal viewing axis.
//
void ITR3DMImport::import(const char* file,PolyList* polyList)
{
   int version = 0;
   
   FILE* fp = fopen(file,"r");
   char buff[256];
   AssertFatal(fp != 0,"ITR3DMImport::import: Error openning file");

   // Load the vertex list - or the version number...
   do
      fgets(buff,256,fp);
   while( strcmp(buff,"VERTICES\n") && strcmp( buff, "VERSION\n" ) );
   
   // check if we got verion
   if( !strcmp( buff, "VERSION\n" ) )
   {
      fscanf( fp, "%d\n", &version );   
      
      // get to the vertices
      do
         fgets(buff,256,fp);
      while( strcmp(buff,"VERTICES\n") );
   }
   
   int vertexCount;
   fscanf(fp,"%d\n",&vertexCount);

   Vector<Point3F> pointList;
   pointList.setSize(vertexCount);
   for (int i = 0; i < vertexCount; i++) {
      Point3F pp;
      // Convert to our coordinate system.
      fscanf(fp,"%f %f %f\n",&pp.x,&pp.z,&pp.y);
      pp *= scale;
      pointList[i] = snap(pp);
   }

   // Load the faces
   do
      fgets(buff,256,fp);
   while (strcmp(buff,"POLYGONS\n"));
   int polyCount;
   fscanf(fp,"%d\n",&polyCount);
	int degeneratePoly = 0;

   polyList->reserve(polyCount);
   for (int i = 0; i < polyCount; i++) {
      Poly* poly = new Poly;
      fgets(buff,256,fp);
      poly->material = atoi(buff);

      int count;
      fscanf(fp,"%d\n",&count);
      if (count < 3) {
			degeneratePoly++;
         delete poly;
         continue;
      }
      poly->vertexList.setSize(count);

      // DMM - Scan in texture size and offset.  (New in Zed);
      fscanf(fp, "%d %d\n", &poly->textureSize.x, &poly->textureSize.y);
      fscanf(fp, "%d %d\n", &poly->textureOffset.x, &poly->textureOffset.y);
      
      // grab the texture scaling factor
      int textureScaleShift;
      fscanf(fp, "%d\n", &textureScaleShift );
      poly->textureScaleShift = textureScaleShift;

      // check if there is a ambient flag ( any version will have this... )
      if( version )
      {
         int tmp;
         fscanf( fp, "%d\n", &tmp );
         poly->applyAmbient = bool( tmp );
      }
      
		// Vertices
      for (int i = 0; i < count; i++) {
         int index;
         fscanf(fp,"%d",&index);
         poly->vertexList[i].point = pointList[index];
         poly->vertexList[i].colinear = false;
      }
      fscanf(fp,"\n",buff);

		// Texture coor.
      for (int i = 0; i < count; i++) {
         Point2F& texture = poly->vertexList[i].texture;
         fscanf(fp, "%f %f", &texture.x,&texture.y);
      }
      fscanf(fp,"\n",buff);

		// Volume mask
      fscanf(fp,"%lu\n",&poly->volumeMask);

#if 1
      // Read in the plane exported by zed
		fscanf(fp,"%f %f %f %f\n",
			&poly->plane.x, &poly->plane.z, &poly->plane.y, &poly->plane.d);
		poly->plane.d *= scale;

		// Use the plane class to make sure the polygon
		// is not degenerate.
		TPlaneF tmp;
      Point3F* vl[MaxPolyVertex];
      AssertFatal(poly->vertexList.size() <= MaxPolyVertex,
         "ITR3DMImport::import: Poly exceeded max vertex size");
      for (int v = 0; v < poly->vertexList.size(); v++)
         vl[v] = &poly->vertexList[v].point;
      if (!tmp.set(poly->vertexList.size(),vl)) {
			degeneratePoly++;
         delete poly;
         continue;
      }
#else
		// Build the plane using the vertices
      Point3F* vl[MaxPolyVertex];
      AssertFatal(poly->vertexList.size() <= MaxPolyVertex,
         "ITR3DMImport::import: Poly exceeded max vertex size");
      for (int v = 0; v < poly->vertexList.size(); v++)
         vl[v] = &poly->vertexList[v].point;
      if (!poly->plane.set(poly->vertexList.size(),vl)) {
			degeneratePoly++;
         delete poly;
         continue;
      }
#endif

      // If we have bad texture coordinates, let's try re-boxmapping
		// first.
      if (poly->textureSize.x == 0 || poly->textureSize.y == 0) {
         printf("   Degenerate poly textures (%d)\n",i);
         boxMap(poly);
      }
      normalizeTexture(poly);
      if (poly->textureSize.x == 0 || poly->textureSize.y == 0) {
			degeneratePoly++;
         delete poly;
         continue;
      }

		//
      polyList->push_back(poly);
   }

	if (degeneratePoly)
	   printf("\n   *****: %d Degenerate polys dropped\n   ",degeneratePoly);
   fclose(fp);
}  
Example #19
0
QPointF KeyFrameItem::snap(const QPointF &pos) const
{
  return QPointF(snap(pos.x()), 0);
}
Example #20
0
void PlayerWidget::updateState(SongMsgId playing, AudioPlayerState playingState, int64 playingPosition, int64 playingDuration, int32 playingFrequency) {
	if (!playing) {
		audioPlayer()->currentState(&playing, &playingState, &playingPosition, &playingDuration, &playingFrequency);
	}

	bool songChanged = false;
	if (playing && _song != playing) {
		songChanged = true;
		_song = playing;
		if (HistoryItem *item = App::histItemById(_song.msgId)) {
			_history = item->history();
			if (_history->peer->migrateFrom()) {
				_migrated = App::history(_history->peer->migrateFrom()->id);
				_msgmigrated = false;
			} else if (_history->peer->migrateTo()) {
				_migrated = _history;
				_history = App::history(_migrated->peer->migrateTo()->id);
				_msgmigrated = true;
			}
			findCurrent();
		} else {
			_history = 0;
			_msgmigrated = false;
			_index = -1;
		}
		SongData *song = _song.song->song();
		if (song->performer.isEmpty()) {
			_name.setText(st::linkFont, song->title.isEmpty() ? (_song.song->name.isEmpty() ? qsl("Unknown Track") : _song.song->name) : song->title, _textNameOptions);
		} else {
			TextCustomTagsMap custom;
			custom.insert(QChar('c'), qMakePair(textcmdStartLink(1), textcmdStopLink()));
			_name.setRichText(st::linkFont, QString::fromUtf8("[c]%1[/c] \xe2\x80\x93 %2").arg(textRichPrepare(song->performer)).arg(song->title.isEmpty() ? qsl("Unknown Track") : textRichPrepare(song->title)), _textNameOptions, custom);
		}
		updateControls();
	}

	qint64 position = 0, duration = 0, display = 0;
	if (playing == _song) {
		if (!(playingState & AudioPlayerStoppedMask) && playingState != AudioPlayerFinishing) {
			display = position = playingPosition;
			duration = playingDuration;
		} else {
			display = playingDuration;
		}
		display = display / (playingFrequency ? playingFrequency : AudioVoiceMsgFrequency);
	} else if (_song) {
		display = _song.song->song()->duration;
	}
	bool showPause = false, stopped = ((playingState & AudioPlayerStoppedMask) || playingState == AudioPlayerFinishing);
	bool wasPlaying = !!_duration;
	if (!stopped) {
		showPause = (playingState == AudioPlayerPlaying || playingState == AudioPlayerResuming || playingState == AudioPlayerStarting);
	}
	QString time;
	float64 progress = 0.;
	int32 loaded;
	float64 loadProgress = 1.;
	if (duration || !_song || !_song.song || !_song.song->loading()) {
		time = (_down == OverPlayback) ? _time : formatDurationText(display);
		progress = duration ? snap(float64(position) / duration, 0., 1.) : 0.;
		loaded = duration ? _song.song->size : 0;
	} else {
		loaded = _song.song->loading() ? _song.song->loadOffset() : 0;
		time = formatDownloadText(loaded, _song.song->size);
		loadProgress = snap(float64(loaded) / qMax(_song.song->size, 1), 0., 1.);
	}
	if (time != _time || showPause != _showPause) {
		if (_time != time) {
			_time = time;
			_timeWidth = st::linkFont->width(_time);
		}
		_showPause = showPause;
		if (duration != _duration || position != _position || loaded != _loaded) {
			if (!songChanged && ((!stopped && duration && _duration) || (!duration && _loaded != loaded))) {
				a_progress.start(progress);
				a_loadProgress.start(loadProgress);
				_a_progress.start();
			} else {
				a_progress = anim::fvalue(progress, progress);
				a_loadProgress = anim::fvalue(loadProgress, loadProgress);
				_a_progress.stop();
			}
			_position = position;
			_duration = duration;
			_loaded = loaded;
		}
		update();
	} else if (duration != _duration || position != _position || loaded != _loaded) {
		if (!songChanged && ((!stopped && duration && _duration) || (!duration && _loaded != loaded))) {
			a_progress.start(progress);
			a_loadProgress.start(loadProgress);
			_a_progress.start();
		} else {
			a_progress = anim::fvalue(progress, progress);
			a_loadProgress = anim::fvalue(loadProgress, loadProgress);
			_a_progress.stop();
		}
		_position = position;
		_duration = duration;
		_loaded = loaded;
	}

	if (wasPlaying && playingState == AudioPlayerStoppedAtEnd) {
		if (_repeat) {
			startPlay(_song.msgId);
		} else {
			nextPressed();
		}
	}

	if (songChanged) {
		emit playerSongChanged(_song.msgId);
	}
}
Example #21
0
/**
 * \fn VideoOutWindow::Zoom(ZoomDirection)
 * \brief Sets up zooming into to different parts of the video, the zoom
 *        is actually applied in MoveResize().
 * \sa ToggleAdjustFill(AdjustFillMode)
 */
void VideoOutWindow::Zoom(ZoomDirection direction)
{
    if (kZoomHome == direction)
    {
        mz_scale_v = 1.0f;
        mz_scale_h = 1.0f;
        mz_move = QPoint(0, 0);
    }
    else if (kZoomIn == direction)
    {
        if ((mz_scale_h < kManualZoomMaxHorizontalZoom) &&
            (mz_scale_v < kManualZoomMaxVerticalZoom))
        {
            mz_scale_h *= 1.05f;
            mz_scale_v *= 1.05f;
        }
        else
        {
            float ratio = mz_scale_v / mz_scale_h;
            mz_scale_h = 1.0f;
            mz_scale_v = ratio * mz_scale_h;
        }
    }
    else if (kZoomOut == direction)
    {
        if ((mz_scale_h > kManualZoomMinHorizontalZoom) &&
            (mz_scale_v > kManualZoomMinVerticalZoom))
        {
            mz_scale_h *= 1.0f / 1.05f;
            mz_scale_v *= 1.0f / 1.05f;
        }
        else
        {
            float ratio = mz_scale_v / mz_scale_h;
            mz_scale_h = 1.0f;
            mz_scale_v = ratio * mz_scale_h;
        }
    }
    else if (kZoomAspectUp == direction)
    {
        if ((mz_scale_h < kManualZoomMaxHorizontalZoom) &&
            (mz_scale_v > kManualZoomMinVerticalZoom))
        {
            mz_scale_h *= 1.05f;
            mz_scale_v *= 1.0 / 1.05f;
        }
    }
    else if (kZoomAspectDown == direction)
    {
        if ((mz_scale_h > kManualZoomMinHorizontalZoom) &&
            (mz_scale_v < kManualZoomMaxVerticalZoom))
        {
            mz_scale_h *= 1.0 / 1.05f;
            mz_scale_v *= 1.05f;
        }
    }
    else if (kZoomUp    == direction && (mz_move.y() <= +kManualZoomMaxMove))
        mz_move.setY(mz_move.y() + 2);
    else if (kZoomDown  == direction && (mz_move.y() >= -kManualZoomMaxMove))
        mz_move.setY(mz_move.y() - 2);
    else if (kZoomLeft  == direction && (mz_move.x() <= +kManualZoomMaxMove))
        mz_move.setX(mz_move.x() + 2);
    else if (kZoomRight == direction && (mz_move.x() >= -kManualZoomMaxMove))
        mz_move.setX(mz_move.x() - 2);

    mz_scale_v = snap(mz_scale_v, 1.0f, 0.03f);
    mz_scale_h = snap(mz_scale_h, 1.0f, 0.03f);
}
Example #22
0
static void
doreps(mmv_t *mmv)
{
    REP *first;
    int k;
    int alias = 0;

    signal(SIGINT, breakrep);

    for (first = mmv->hrep.r_next, k = 0; first != NULL; first = first->r_next) {
        REP *p;
        int printaliased;

        printaliased = 0;
        for (p = first; p != NULL; p = p->r_thendo, ++k) {
            size_t aliaslen;
            char *fstart;

            if (gotsig) {
                fflush(stdout);
                eprint("User break.\n");
                printaliased = snap(mmv, first, p);
                gotsig = 0;
            }
            strcpy(mmv->fullrep, p->r_hto->h_name);
            strcat(mmv->fullrep, p->r_nto);
            if (!mmv->noex && (p->r_flags & R_ISCYCLE)) {
                if (mmv->op & APPEND) {
                    aliaslen = appendalias(mmv, first, p, &printaliased);
                }
                else {
                    alias = movealias(mmv, first, p, &printaliased);
                }
            }
            strcpy(mmv->pathbuf, p->r_hfrom->h_name);
            fstart = mmv->pathbuf + strlen(mmv->pathbuf);
            if ((p->r_flags & R_ISALIASED) && !(mmv->op & APPEND)) {
                sprintf(fstart, "%s%03d", TEMP, alias);
            }
            else {
                strcpy(fstart, p->r_ffrom->fi_name);
            }

            if (!mmv->noex) {
                sc_status_t scstat;

                do_move_pair(mmv, p, &scstat, aliaslen);
                if (scstat.rv) {
                    eprint_filename(mmv->pathbuf);
                    fputs(" -> ", stderr);
                    eprint_filename(mmv->fullrep);
                    fputs(" ", stderr);
                    fputs(scstat.sc_name, stderr);
                    fputs(" has failed.\n", stderr);
                    eexplain_err(scstat.err);
                    printaliased = snap(mmv, first, p);
                }
            }

            if (mmv->verbose || mmv->noex) {
                if (p->r_flags & R_ISALIASED && !printaliased) {
                    strcpy(fstart, p->r_ffrom->fi_name);
                }
                fprintf(mmv->outfile, "%s %c%c %s%s%s\n",
                        mmv->pathbuf,
                        p->r_flags & R_ISALIASED ? '=' : '-',
                        p->r_flags & R_ISCYCLE ? '^' : '>',
                        mmv->fullrep,
                        (p->r_fdel != NULL && !(mmv->op & APPEND)) ? " (*)" : "", mmv->noex ? "" : " : done");
            }
        }
    }

    if (k != mmv->nreps) {
        eprintf("Strange, did %d reps; %d were expected.\n", k, mmv->nreps);
    }
    if (k == 0) {
        eprint("Nothing done.\n");
    }
}
Example #23
0
void RoundImageCheckbox::paint(Painter &p, uint64 ms, int x, int y, int outerWidth) {
	_selection.step(ms);
	for (auto &icon : _icons) {
		icon.fadeIn.step(ms);
		icon.fadeOut.step(ms);
	}
	removeFadeOutedIcons();

	auto selectionLevel = _selection.current(_checked ? 1. : 0.);
	if (_selection.animating()) {
		auto userpicRadius = qRound(kWideScale * (_st.imageRadius + (_st.imageSmallRadius - _st.imageRadius) * selectionLevel));
		auto userpicShift = kWideScale * _st.imageRadius - userpicRadius;
		auto userpicLeft = x - (kWideScale - 1) * _st.imageRadius + userpicShift;
		auto userpicTop = y - (kWideScale - 1) * _st.imageRadius + userpicShift;
		auto to = QRect(userpicLeft, userpicTop, userpicRadius * 2, userpicRadius * 2);
		auto from = QRect(QPoint(0, 0), _wideCache.size());

		p.setRenderHint(QPainter::SmoothPixmapTransform, true);
		p.drawPixmapLeft(to, outerWidth, _wideCache, from);
		p.setRenderHint(QPainter::SmoothPixmapTransform, false);
	} else {
		if (!_wideCache.isNull()) {
			_wideCache = QPixmap();
		}
		auto userpicRadius = _checked ? _st.imageSmallRadius : _st.imageRadius;
		auto userpicShift = _st.imageRadius - userpicRadius;
		auto userpicLeft = x + userpicShift;
		auto userpicTop = y + userpicShift;
		_paintRoundImage(p, userpicLeft, userpicTop, outerWidth, userpicRadius * 2);
	}

	if (selectionLevel > 0) {
		p.setRenderHint(QPainter::HighQualityAntialiasing, true);
		p.setOpacity(snap(selectionLevel, 0., 1.));
		p.setBrush(Qt::NoBrush);
		auto pen = _st.selectFg->p;
		pen.setWidth(_st.selectWidth);
		p.setPen(pen);
		p.drawEllipse(rtlrect(x, y, _st.imageRadius * 2, _st.imageRadius * 2, outerWidth));
		p.setOpacity(1.);
		p.setRenderHint(QPainter::HighQualityAntialiasing, false);
	}

	p.setRenderHint(QPainter::SmoothPixmapTransform, true);
	for (auto &icon : _icons) {
		auto fadeIn = icon.fadeIn.current(1.);
		auto fadeOut = icon.fadeOut.current(1.);
		auto iconRadius = qRound(kWideScale * (_st.checkSmallRadius + fadeOut * (_st.checkRadius - _st.checkSmallRadius)));
		auto iconShift = kWideScale * _st.checkRadius - iconRadius;
		auto iconLeft = x + 2 * _st.imageRadius + _st.selectWidth - 2 * _st.checkRadius - (kWideScale - 1) * _st.checkRadius + iconShift;
		auto iconTop = y + 2 * _st.imageRadius + _st.selectWidth - 2 * _st.checkRadius - (kWideScale - 1) * _st.checkRadius + iconShift;
		auto to = QRect(iconLeft, iconTop, iconRadius * 2, iconRadius * 2);
		auto from = QRect(QPoint(0, 0), _wideCheckFullCache.size());
		auto opacity = fadeIn * fadeOut;
		p.setOpacity(opacity);
		if (fadeOut < 1.) {
			p.drawPixmapLeft(to, outerWidth, icon.wideCheckCache, from);
		} else {
			auto divider = qRound((kWideScale - 2) * _st.checkRadius + fadeIn * 3 * _st.checkRadius);
			p.drawPixmapLeft(QRect(iconLeft, iconTop, divider, iconRadius * 2), outerWidth, _wideCheckFullCache, QRect(0, 0, divider * cIntRetinaFactor(), _wideCheckFullCache.height()));
			p.drawPixmapLeft(QRect(iconLeft + divider, iconTop, iconRadius * 2 - divider, iconRadius * 2), outerWidth, _wideCheckBgCache, QRect(divider * cIntRetinaFactor(), 0, _wideCheckBgCache.width() - divider * cIntRetinaFactor(), _wideCheckBgCache.height()));
		}
	}
	p.setRenderHint(QPainter::SmoothPixmapTransform, false);
	p.setOpacity(1.);
}
Example #24
0
float64 RoundImageCheckbox::checkedAnimationRatio() const {
	return snap(_selection.current(_checked ? 1. : 0.), 0., 1.);
}
Example #25
0
float64 FileLoader::currentProgress() const {
	if (_complete) return 1.;
	if (!fullSize()) return 0.;
	return snap(float64(currentOffset()) / fullSize(), 0., 1.);
}
Example #26
0
Slider::Slider(QWidget *parent, const style::slider &st, int32 count, int32 sel) : QWidget(parent),
_count(count), _sel(snap(sel, 0, _count)), _wasSel(_sel), _st(st), _pressed(false) {
	resize(_st.width, _st.bar.pxHeight());
	setCursor(style::cur_pointer);
}
Example #27
0
RadialState InfiniteRadialAnimation::computeState() {
	const auto now = getms();
	const auto linear = int(((now * FullArcLength) / _st.linearPeriod)
		% FullArcLength);
	if (!_workStarted || (_workFinished && _workFinished <= now)) {
		const auto shown = 0.;
		_animation.stop();
		return {
			shown,
			linear,
			FullArcLength };
	}
	if (anim::Disabled()) {
		const auto shown = 1.;
		return { 1., 0, FullArcLength };
	}
	const auto min = int(std::round(FullArcLength * _st.arcMin));
	const auto max = int(std::round(FullArcLength * _st.arcMax));
	if (now <= _workStarted) {
		// zero .. _workStarted
		const auto zero = _workStarted - _st.sineDuration;
		const auto shown = (now - zero) / float64(_st.sineDuration);
		const auto length = anim::interpolate(
			FullArcLength,
			min,
			anim::sineInOut(1., snap(shown, 0., 1.)));
		return {
			shown,
			linear + (FullArcLength - length),
			length };
	} else if (!_workFinished || now <= _workFinished - _st.sineDuration) {
		// _workStared .. _workFinished - _st.sineDuration
		const auto shown = 1.;
		const auto cycles = (now - _workStarted) / _st.sinePeriod;
		const auto relative = (now - _workStarted) % _st.sinePeriod;
		const auto smallDuration = _st.sineShift - _st.sineDuration;
		const auto largeDuration = _st.sinePeriod
			- _st.sineShift
			- _st.sineDuration;
		const auto basic = int((linear
			+ (FullArcLength - min)
			+ cycles * (max - min)) % FullArcLength);
		if (relative <= smallDuration) {
			// localZero .. growStart
			return {
				shown,
				basic,
				min };
		} else if (relative <= smallDuration + _st.sineDuration) {
			// growStart .. growEnd
			const auto growLinear = (relative - smallDuration) /
				float64(_st.sineDuration);
			const auto growProgress = anim::sineInOut(1., growLinear);
			return {
				shown,
				basic,
				anim::interpolate(min, max, growProgress) };
		} else if (relative <= _st.sinePeriod - _st.sineDuration) {
			// growEnd .. shrinkStart
			return {
				shown,
				basic,
				max };
		} else {
			// shrinkStart .. shrinkEnd
			const auto shrinkLinear = (relative
				- (_st.sinePeriod - _st.sineDuration))
					/ float64(_st.sineDuration);
			const auto shrinkProgress = anim::sineInOut(1., shrinkLinear);
			const auto shrink = anim::interpolate(
				0,
				max - min,
				shrinkProgress);
			return {
				shown,
				basic + shrink,
				max - shrink }; // interpolate(max, min, shrinkProgress)
		}
	} else {
		// _workFinished - _st.sineDuration .. _workFinished
		const auto hidden = (now - (_workFinished - _st.sineDuration))
			/ float64(_st.sineDuration);
		const auto cycles = (_workFinished - _workStarted) / _st.sinePeriod;
		const auto basic = int((linear
			+ (FullArcLength - min)
			+ cycles * (max - min)) % FullArcLength);
		const auto length = anim::interpolate(
			min,
			FullArcLength,
			anim::sineInOut(1., snap(hidden, 0., 1.)));
		return {
			1. - hidden,
			basic,
			length };
	}
	//const auto frontPeriods = time / st.sinePeriod;
	//const auto frontCurrent = time % st.sinePeriod;
	//const auto frontProgress = anim::sineInOut(
	//	st.arcMax - st.arcMin,
	//	std::min(frontCurrent, TimeMs(st.sineDuration))
	//	/ float64(st.sineDuration));
	//const auto backTime = std::max(time - st.sineShift, 0LL);
	//const auto backPeriods = backTime / st.sinePeriod;
	//const auto backCurrent = backTime % st.sinePeriod;
	//const auto backProgress = anim::sineInOut(
	//	st.arcMax - st.arcMin,
	//	std::min(backCurrent, TimeMs(st.sineDuration))
	//	/ float64(st.sineDuration));
	//const auto front = linear + std::round((st.arcMin + frontProgress + frontPeriods * (st.arcMax - st.arcMin)) * FullArcLength);
	//const auto from = linear + std::round((backProgress + backPeriods * (st.arcMax - st.arcMin)) * FullArcLength);
	//const auto length = (front - from);

	//return {
	//	_opacity,
	//	from,
	//	length
	//};
}
Example #28
0
void KeyFrameItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
  setPos(snap(event->scenePos()));
}
void FGHSensorPing::onRender(GFXSurface *sfc, Point2I offset, const Box2I& /*updateRect*/)
{
    Point2I canvasSize(sfc->getWidth(), sfc->getHeight());

    //check for lowres
    if (canvasSize.x < 512 || canvasSize.y < 384)
    {
        if (! mbLowRes)
        {
            mbLowRes = TRUE;
            extent.set(20, 15);
            snap();
        }
    }
    else
    {
        if (mbLowRes)
        {
            mbLowRes = FALSE;
            extent.set(32, 23);
            snap();
            return;
        }
    }

    //make sure the HUD can fit on the canvas
    if ((canvasSize.x < extent.x) || (canvasSize.y < extent.y))
        return;

    if (!cg.psc || !cg.player || (cg.player != cg.psc->getControlObject() && !(cg.psc->getControlObject()->getType() & VehicleObjectType)))
        return;

    //draw the base bmp
    sfc->drawBitmap2d((! mbLowRes ? mBmpBase : lrBmpBase), &offset);

    //first, check the status
    GFXBitmap *bmp = NULL;

    //get the ping status
    BYTE pingStatus = cg.psc->getControlObject()->getSensorPinged(); // cg.player->getSensorPinged();

    //set the bitmap
    if (pingStatus == GameBase::PingStatusSupressed)
    {
        bmp = mBmpSupressed;
        startBlinkTime = -1;
    }

    else if (pingStatus == GameBase::PingStatusOn)
    {
        //find out how much time has passed since the light blinked
        SimTime curTime = manager->getCurrentTime();
        if (startBlinkTime <= 0) startBlinkTime = curTime;

        int bmpValue = int((curTime - startBlinkTime) * 10) % 6;
        if (bmpValue == 0)
            bmp = (! mbLowRes ? mBmpPingedLo : lrBmpPingedLo);
        else if (bmpValue == 1)
            bmp = (! mbLowRes ? mBmpPingedMed : lrBmpPingedMed);
        else
            bmp = (! mbLowRes ? mBmpPingedHi : lrBmpPingedHi);

    }
    else
    {
        startBlinkTime = -1;
    }

    //now draw the bmp
    if (bmp)
    {
        sfc->drawBitmap2d(bmp, &Point2I(offset.x + (extent.x - bmp->getWidth()) / 2,
                                        offset.y + (extent.y - bmp->getHeight()) / 2));
    }
}
Example #30
0
/* Main command loop */
void
mainloop(void)
{
	int	k;
	int	c, lastc = 0;
	int repeat = 1;

	for (;;) {
		if (wantstop) {
			endwin();
			length(moves);
			exit(0);
		}

		/* Highlight you, not left & above */
		move(you.line + 1, you.col + 1);
		refresh();
		if (((c = getch()) <= '9') && (c >= '0')) {
			repeat = c - '0';
			while (((c = getch()) <= '9') && (c >= '0'))
				repeat = 10 * repeat + (c - '0');
		} else {
			if (c != '.')
				repeat = 1;
		}
		if (c == '.')
			c = lastc;
		if (!fast)
			flushinp();
		lastc = c;

		switch (c) {
		case CTRL('z'):
			suspend();
			continue;
		case '\044':
		case 'x':
		case 0177:	/* del or end of file */
		case ERR:
			endwin();
			length(moves);
#ifdef LOGGING
			logit("quit");
#endif
			exit(0);
		case CTRL('l'):
			setup();
			winnings(cashvalue);
			continue;
		case 'p':
		case 'd':
			snap();
			continue;
		case 'w':
			spacewarp(0);
			continue;
		case 'A':
			repeat = you.col;
			c = 'h';
			break;
		case 'H':
		case 'S':
			repeat = you.col - money.col;
			c = 'h';
			break;
		case 'T':
			repeat = you.line;
			c = 'k';
			break;
		case 'K':
		case 'E':
			repeat = you.line - money.line;
			c = 'k';
			break;
		case 'P':
			repeat = ccnt - 1 - you.col;
			c = 'l';
			break;
		case 'L':
		case 'F':
			repeat = money.col - you.col;
			c = 'l';
			break;
		case 'B':
			repeat = lcnt - 1 - you.line;
			c = 'j';
			break;
		case 'J':
		case 'C':
			repeat = money.line - you.line;
			c = 'j';
			break;
		}
		for (k = 1; k <= repeat; k++) {
			moves++;
			switch (c) {
			case 's':
			case 'h':
#ifdef KEY_LEFT
			case KEY_LEFT:
#endif
			case '\b':
				if (you.col > 0) {
					if ((fast) || (k == 1))
						pchar(&you, ' ');
					you.col--;
					if ((fast) || (k == repeat) ||
					    (you.col == 0))
						pchar(&you, ME);
				}
				break;
			case 'f':
			case 'l':
#ifdef KEY_RIGHT
			case KEY_RIGHT:
#endif
			case ' ':
				if (you.col < ccnt - 1) {
					if ((fast) || (k == 1))
						pchar(&you, ' ');
					you.col++;
					if ((fast) || (k == repeat) ||
					    (you.col == ccnt - 1))
						pchar(&you, ME);
				}
				break;
			case CTRL('p'):
			case 'e':
			case 'k':
#ifdef KEY_UP
			case KEY_UP:
#endif
			case 'i':
				if (you.line > 0) {
					if ((fast) || (k == 1))
						pchar(&you, ' ');
					you.line--;
					if ((fast) || (k == repeat) ||
					    (you.line == 0))
						pchar(&you, ME);
				}
				break;
			case CTRL('n'):
			case 'c':
			case 'j':
#ifdef KEY_DOWN
			case KEY_DOWN:
#endif
			case '\n':
			case '\r':
			case 'm':
				if (you.line + 1 < lcnt) {
					if ((fast) || (k == 1))
						pchar(&you, ' ');
					you.line++;
					if ((fast) || (k == repeat) ||
					    (you.line == lcnt - 1))
						pchar(&you, ME);
				}
				break;
			}

			if (same(&you, &money)) {
				loot += 25;
				if (k < repeat)
					pchar(&you, ' ');
				do {
					snrand(&money);
				} while ((money.col == finish.col &&
				    money.line == finish.line) ||
				    (money.col < 5 && money.line == 0) ||
				    (money.col == you.col &&
				    money.line == you.line));
				pchar(&money, TREASURE);
				winnings(cashvalue);
/*				continue;		 Previously, snake missed a turn! */
			}
			if (same(&you, &finish)) {
				win(&finish);
				flushinp();
				endwin();
				printf("You have won with $%d.\n", cashvalue);
				fflush(stdout);
#ifdef LOGGING
				logit("won");
#endif
				length(moves);
				post(cashvalue, 1);
				close(rawscores);
				exit(0);
			}
			if (pushsnake())
				break;
		}
	}
}