Ejemplo n.º 1
0
void GrayBitmap::setClipRect(Rect rect)
{
    m_clip.left = my_max(rect.left, 0);
    m_clip.top = my_max(rect.top, 0);
    m_clip.right = my_min(rect.right, m_width);
    m_clip.bottom = my_min(rect.bottom, m_height);
}
Ejemplo n.º 2
0
static gboolean
on_motion_notify_event (GtkWidget *window, GdkEventMotion *ev, gpointer user_data)
{
	AbiTable* table = static_cast<AbiTable*>(user_data);
	gboolean changed = FALSE;
	guint selected_cols;
	guint selected_rows;

	if (ev->x < 0 || ev->y < 0)
		return TRUE;
	
	pixels_to_cells(static_cast<guint>(ev->x), static_cast<guint>(ev->y), &selected_cols, &selected_rows);

	if ((selected_cols != table->selected_cols) || (selected_rows != table->selected_rows))
	{
		/* grow or shrink the table widget as necessary */
		table->selected_cols = selected_cols;
		table->selected_rows = selected_rows;

		if (table->selected_rows <= 0 || table->selected_cols <= 0)
			table->selected_rows = table->selected_cols = 0;

		table->total_rows = my_max(table->selected_rows + 1, 3);
		table->total_cols = my_max(table->selected_cols + 1, 3);

		abi_table_resize(table);
		gtk_widget_queue_draw_area (window, 0, 0, 
					    window->allocation.width, window->allocation.height);

		changed = TRUE;
	}

	return TRUE;
}
Ejemplo n.º 3
0
gboolean
on_key_event(GtkWidget *widget, GdkEventKey *event, gpointer user_data)
{
	AbiTable* table = static_cast<AbiTable*>(user_data);
	gboolean grew = FALSE;

	switch (event->keyval)
	{
	case GDK_Up:
	case GDK_KP_Up:
		if (table->selected_rows > 0)
			--table->selected_rows;
		break;
	case GDK_Down:
	case GDK_KP_Down:
		grew = TRUE;
		++table->selected_rows;
		break;
	case GDK_Left:
	case GDK_KP_Left:
		if (table->selected_cols > 0)
			--table->selected_cols;
		break;
	case GDK_Right:
	case GDK_KP_Right:
		grew = TRUE;
		++table->selected_cols;
		break;
	case GDK_Escape:
		restart_widget(table);
		return TRUE;
	case GDK_KP_Space:
	case GDK_KP_Enter:
	case GDK_space:
	case GDK_3270_Enter:
	case GDK_ISO_Enter:
	case GDK_Return:
		emit_selected(table);
		return TRUE;
	}

	if(table->selected_rows == 0 || table->selected_cols == 0)
		table->selected_rows = table->selected_cols = (grew ? 1 : 0) ;

	table->total_rows = my_max(table->selected_rows + 1, 3);
	table->total_cols = my_max(table->selected_cols + 1, 3);

	abi_table_resize(table);
	gtk_widget_queue_draw_area (widget, 0, 0, widget->allocation.width,
				    widget->allocation.height);

	return TRUE;
}
Ejemplo n.º 4
0
static void
restart_widget (AbiTable *table)
{
	table->selected_cols = init_cols;
	table->selected_rows = init_rows;
	table->total_cols = my_max(init_cols + 1, 5);
	table->total_rows = my_max(init_rows + 1, 6);

	gtk_button_released(GTK_BUTTON(table));

	gtk_widget_hide(GTK_WIDGET(table->window));
}
Ejemplo n.º 5
0
Archivo: BBox.cpp Proyecto: janba/GEL
  void BBox::intersect_min_max(Ray &ray, double &t_min, double &t_max) const 
  {
    double tx1 = (min_corner[0]-ray.origin[0])/ray.direction[0];
    double ty1 = (min_corner[1]-ray.origin[1])/ray.direction[1];
    double tz1 = (min_corner[2]-ray.origin[2])/ray.direction[2];

    double tx2 = (max_corner[0]-ray.origin[0])/ray.direction[0];
    double ty2 = (max_corner[1]-ray.origin[1])/ray.direction[1];
    double tz2 = (max_corner[2]-ray.origin[2])/ray.direction[2];

    t_min = my_max(my_min(tx1, tx2), my_max(my_min(ty1, ty2), my_min(tz1,tz2)));
    t_max = my_min(my_max(tx1, tx2), my_min(my_max(ty1, ty2), my_max(tz1,tz2)));
  }
Ejemplo n.º 6
0
double Fluid::getIsovalue(int i, int j, int k) const {
  i = my_max(0,(my_min(i,nx-1)));
  j = my_max(0,(my_min(j,ny-1)));
  k = my_max(0,(my_min(k,nz-1)));
  Cell *c = getCell(i,j,k);
  if (c->getStatus() == CELL_EMPTY) return 0;
  // note: this is technically not a correct thing to do
  //       the number of particles is not an indication of it's "fullness"
  if (c->getStatus() == CELL_SURFACE) return 0.5 + c->numParticles()/double(density);
  if (c->getStatus() == CELL_FULL) return 2;
  assert(0);
  return 0;
}
Ejemplo n.º 7
0
void GLWidget::SetImage(int width, int height, std::vector<QColor> colorList)
{
	//textEdit->append("width :" + QString::number(width));
	//textEdit->append("height :" + QString::number(height));
	//textEdit->append("colorList size :" + QString::number(colorList.size()));

	bool isLoaded = true;
	_imgOriginal = QImage(width, height, QImage::Format_RGB32);

	// size
	this->_img_width = _imgOriginal.width();
	this->_img_height = _imgOriginal.height();

	for (int x = 0; x < this->_img_width; x++)
	{
		for (int y = 0; y < this->_img_height; y++)
		{
			//int idx = x + y * this->_img_width;
			//QColor col = colorList[idx];
			//QColor col = QColor(0, 255, 0, 255);
			QColor col = QColor(rand() % 255, rand() % 255, rand() % 255, 255);
			_imgOriginal.setPixel(x, y, col.rgba());
		}
	}

	// calculating power-of-two (pow) size
	int xpow = (int)std::pow(2.0, std::ceil(std::log10((double)_img_width) / std::log10(2.0)));
	int ypow = (int)std::pow(2.0, std::ceil(std::log10((double)_img_height) / std::log10(2.0)));

	xpow = my_max(xpow, ypow);	// the texture should be square too
	xpow = my_min(xpow, 1024);	// shrink if the size is too big
	ypow = xpow;

	// transform the image to square pow size
	_imgGL = _imgOriginal.scaled(xpow, ypow, Qt::IgnoreAspectRatio);
	_imgGL = QGLWidget::convertToGLFormat(_imgGL);

	_imgID = 0;

	glBindTexture(GL_TEXTURE_2D, 0); // I just want to make sure...
	//glEnable(GL_TEXTURE_2D); // should I have this ?

	glGenTextures(1, &_imgID);

	if (!_imgID)
	{
		//glGetError 1282 ???
		textEdit->append("glGetError :" + QString::number(glGetError()));
	}

	glBindTexture(GL_TEXTURE_2D, _imgID);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, _imgGL.width(), _imgGL.height(), 0, GL_RGBA, GL_UNSIGNED_BYTE, _imgGL.bits());

	//glDisable(GL_TEXTURE_2D);  // should I have this ?
	//textEdit->append("_imgID :" + QString::number(_imgID));
}
Ejemplo n.º 8
0
void wavetable_normalize(void *vol, void *unused2, void *unused3)
{
	snapshot(S_T_WAVE_DATA);
		
	CydWavetableEntry *w = &mused.mus.cyd->wavetable_entries[mused.selected_wavetable];
	
	if (w->samples > 0)
	{
		int m = 0;
				
		for (int s = 0 ; s < w->samples ; ++s)
		{
			m = my_max(m, abs(w->data[s]));
		}
		
		debug("Peak = %d", m);
		
		if (m != 0)
		{
			for (int s = 0 ; s < w->samples ; ++s)
			{
				w->data[s] = my_max(my_min((Sint32)w->data[s] * CASTPTR(int, vol) / m, 32767), -32768);
			}
		}
		
		invalidate_wavetable_view();
	}
Ejemplo n.º 9
0
char	*my_tabjoin(char **tab, char *glue)
{
  char	*str;
  int	extra;
  int	length;
  int	flength;

  length = my_tablen(tab);
  flength = my_tabflen(tab);
  extra = my_strlen(glue) * my_max(length - 1, 0);
  if ((str = malloc((extra + flength + 1) * sizeof(str))) == NULL)
  {
    return (NULL);
  }
  str[extra + flength] = '\0';
  flength = extra = 0;
  while (tab[extra])
  {
    my_strncpyz(str, tab[extra], flength, -1);
    flength += my_strlen(tab[extra]);
    if (extra + 1 != length)
      my_strncpyz(str, glue, flength, -1);
    flength += my_strlen(glue);
    extra++;
  }
  return (str);
}
Ejemplo n.º 10
0
void GrayBitmap::blitTo(GrayBitmap& dest, s32 destX, s32 destY) const
{
    s32 xstart = my_max(0, dest.m_clip.left - destX);
    s32 xend = my_min(m_width, dest.m_clip.right - destX);
    s32 ystart = my_max(0, dest.m_clip.top - destY);
    s32 yend = my_min(m_height, dest.m_clip.bottom - destY);

    if (xend <= xstart || yend <= ystart)
        return;

    for (s32 y = ystart; y < yend; ++y)
    {
        u8* destdata = dest.getScanline(y + destY) + (xstart + destX);
        const u8* srcdata = getScanline(y) + xstart;
        s32 len = xend - xstart;
        memcpy(static_cast<void*>(destdata), static_cast<const void*>(srcdata), len);
    }
}
Ejemplo n.º 11
0
int mumps_compute_nb_concerned_files(long long block_size, int * nb_concerned_files,long long vaddr){
  int file,pos,available_size;
  long long vaddr_loc;
  vaddr_loc=vaddr*(long long)mumps_elementary_data_size;
  mumps_gen_file_info(vaddr_loc,&pos,&file);
  available_size=mumps_io_max_file_size-pos+1;
  *nb_concerned_files=(int)my_ceil((double)(my_max(0,((block_size)*(double)(mumps_elementary_data_size))-available_size))/(double)mumps_io_max_file_size)+1;
  return 0;
}
Ejemplo n.º 12
0
bool IntR_ModelBuildingNew(vector<double> &epsiS,vector<double> &yiS,double rbPar[3])
{
	vector<double> yiW;
	vector<double>sdiW;
	size_t i,sg=yiS.size();
	for(i=0;i<sg;i++) yiS[i]=sqrt(yiS[i]);

	double y_min=my_min(yiS);
	double y_max=my_max(yiS);
	double yRange=y_max-y_min;	
	double yw=yRange/5;
	double ystep=yRange/50;
	double yb=y_min;
	double ye=y_min+yw;
	double yi=y_min+yw/2;
	size_t Ty=yiS.size();
	vector<double> tmpEPS;
	double mu,sigma,pw;
	OutlierRem ot;
	while(yb<y_max)
	{
		for(i=0;i<Ty;i++)
		{
			if(yiS[i]>=yb&&yiS[i]<ye) tmpEPS.push_back(epsiS[i]);
		}
		
		if(tmpEPS.size()<=10) break;
		mu=0;
		sigma=0;
		pw=0;		
		if(ot.oRemoveGTest(tmpEPS))sdiW.push_back(ot.std_new);	
		else sdiW.push_back(my_STD(tmpEPS));
		yiW.push_back(yi);
		tmpEPS.clear();
		yi+=ystep;
		yb+=ystep;
		ye+=ystep;
	}

	Ty=yiW.size();
	if(Ty<=5) 
	{
		printf("modeling failure,check your data.\n");
		return 0;
	}	
	for(i=0;i<Ty;i++) yiW[i]=1/yiW[i];

	double C[2];
	sdiW[0]=1.12*sdiW[0];
		
	rbPar[0]=my_fit_linear(yiW,sdiW,C);	
	rbPar[1]=C[1];
	rbPar[2]=C[0];
	printf("Iter end, LikeHood=%lf,a=%lf,b=%lf\n",rbPar[0],rbPar[1],rbPar[2]);
	return true;
}
Ejemplo n.º 13
0
/* DON'T MODIFY */
void BFP_CALLMODEL bfp_finishfactorization(lprec *lp)
{
  INVrec *lu;

  lu = lp->invB;

  lu->max_colcount = my_max(lu->max_colcount, lp->bfp_colcount(lp));
  lu->max_LUsize = my_max(lu->max_LUsize, lp->bfp_nonzeros(lp, FALSE));

  /* Signal that we done factorizing/reinverting */
  lu->is_dirty = FALSE;
  lp->justInverted = TRUE;
  lp->doInvert = FALSE;
  lu->force_refact = FALSE;

  /* Store information about the current inverse */
  lu->num_pivots = 0;

}
Ejemplo n.º 14
0
Archivo: bst.c Proyecto: gaibo/C
unsigned int bst_height(bst *t)
{
    // base case: empty tree
    if (t == NULL) {
        return 0;
    }
    
    // recursive step
    return 1 + my_max(bst_height(t->lsub), bst_height(t->rsub));
}
Ejemplo n.º 15
0
float get_saturation(int r, int g, int b)
{
    float max = my_max(r, g, b) / 255.0;
    float min = my_min(r, g, b) / 255.0;
    float c = (max - min);
    float L = 0.5 * (max + min);

    if (c == 0) return 0;

    return (1.0 *  c / (1 - fabs(2 * L - 1)));
}
Ejemplo n.º 16
0
static gboolean
on_leave_event (GtkWidget *area,
				GdkEventCrossing *event,
				gpointer user_data)
{
	AbiTable* table = static_cast<AbiTable*>(user_data);

	if (GTK_WIDGET_VISIBLE(GTK_WIDGET(table->window)) && (event->x < 0 || event->y < 0))
	{
		table->selected_rows = 0;
		table->selected_cols = 0;
		table->total_rows = my_max(table->selected_rows + 1, 3);
		table->total_cols = my_max(table->selected_cols + 1, 3);

		abi_table_resize(table);
		gtk_widget_queue_draw_area (area, 0, 0, area->allocation.width,
					    area->allocation.height);
	}

	return TRUE;
}
Ejemplo n.º 17
0
int LimitedEnc::get(int enc_pos){
  int delta = getDelta(enc_pos);
  if(ccw){
    delta = -delta;
  }
  if(delta > 0){
    selected = my_min(selected + delta, n_item - 1);
  }
  if(delta < 0){
    selected = my_max(selected + delta, 0);
  }
  return selected;
}
Ejemplo n.º 18
0
int main(void)
{
  int a, b, m;

  printf("Please input two numbers:\n");
  scanf("%d %d", &a, &b);
  printf("a = %d, b = %d.\n", a, b);
  m = my_max(&a, &b);
  printf("The greater number is %d\n", m);
  printf("a = %d, b = %d.\n", a, b);
  
  return 0;
}
Ejemplo n.º 19
0
bool my_RobustNormalFit(vector<double> &x,double *mu,double *sigma,double *PW)
{
	size_t n=x.size();
	*mu=my_mean(x);
	*sigma=my_STD(x,*mu);
	double a=my_min(x);
	double b=my_max(x);
	double alim=*mu-2*(*sigma);
	double blim=*mu+2*(*sigma);
	double L=alim-a+b-blim;
	double K=b-a;
	if(L<=0) return false; 
	size_t deltn=n-my_count(x,alim,blim);	
	double PW2=K*deltn/(L*n);
	double PW1=1-PW2;
	double muold=*mu;
	double sigmaold=*sigma;
	double e=1;
	int iter=0;
	double *PWP1,*PWAll;
	PWP1=new double[n];
	PWAll=new double[n];
	size_t i;
	while(e>0.0001)  
	{
		for(i=0;i<n;i++)
		{
			PWP1[i]=PW1*normpdf(x[i],muold,sigmaold);
			PWAll[i]=PWP1[i]+PW2/K;
			PWP1[i]=PWP1[i]/PWAll[i];
		}		
		PW1=my_sum(PWP1,n);
		*mu=0;
		for(i=0;i<n;i++)*mu+=PWP1[i]*x[i];		
		*mu/=PW1;
		*sigma=0;
		for(i=0;i<n;i++)*sigma+=PWP1[i]*(x[i]-muold)*(x[i]-muold);
		*sigma=sqrt(*sigma/PW1);
		PW1=PW1/n;
		PW2=1-PW1;
		e=fabs(*sigma-sigmaold)+fabs(*mu-muold);
		muold=*mu;
		sigmaold=*sigma;
		iter=iter+1;
		if(iter>100) break;
	}
	delete []PWP1;
	delete []PWAll;
	return true;
}
Ejemplo n.º 20
0
static int hash_value (char *name) {

/* Creates a hash key from a character string.  Only the first character and *
 * the last 8 characters of the string are used -- that may be dumb.         */

 int i, k;
 int val=0, mult=1;

 i = strlen(name);
 k = my_max(i-8,0);
 for (i=strlen(name)-1;i>=k;i--) {
    val += mult*((int) name[i]);
    mult *= 7;
 }
 val += (int) name[0];
 val %= HASHSIZE;
 return(val);
}
Ejemplo n.º 21
0
/*---------------------------------------------------------------------------*/
void lecentrx()    /* центрировать текст в текущей строке (по размерам окна) */
{
    int xll = my_max(Lxle, Lxlm), xl = xll, mvlen,
        xrr = my_min(Lxre, Lxrm), xr = xrr;
    if (xrr > Lwnd->wsw)          xr = xrr = Lwnd->wsw;

    do {
        if (xl >= xrr) return;
    }
    while (tcharIsBlank(Lebuf[xl++]));
    xl = xl - xll - 1;
    do {
        if (xr <= xll) return;
    }
    while (tcharIsBlank(Lebuf[--xr]));
    xr = xrr - xr - 1;
    mvlen = (xr-xl)/2;
    if (mvlen) llmove(xll, xrr, mvlen, NIL);
}
Ejemplo n.º 22
0
void GLWidget::SetImage(QString img)
{
	//bool isLoaded = true;
	//_imgOriginal = QImage(50, 50, QImage::Format_RGB32);
	bool isLoaded = _imgOriginal.load(img);

	// size
	this->_img_width = _imgOriginal.width();
	this->_img_height = _imgOriginal.height();

	/*
	for (int x = 0; x < this->_img_width; x++)
	{
		for (int y = 0; y < this->_img_height; y++)
		{
			//QColor col = QColor(0, 255, 0, 255);
			QColor col = QColor(rand() % 255, rand() % 255, rand() % 255, 255);
			_imgOriginal.setPixel(x, y, col.rgba());
		}
	}*/

	// calculating power-of-two (pow) size
	int xpow = (int)std::pow(2.0, std::ceil(std::log10((double)_img_width) / std::log10(2.0)));
	int ypow = (int)std::pow(2.0, std::ceil(std::log10((double)_img_height) / std::log10(2.0)));

	xpow = my_max(xpow, ypow);	// the texture should be square too
	xpow = my_min(xpow, 1024);	// shrink if the size is too big
	ypow = xpow;

	// transform the image to square pow size
	_imgGL = _imgOriginal.scaled(xpow, ypow, Qt::IgnoreAspectRatio);
	_imgGL = QGLWidget::convertToGLFormat(_imgGL);

	glGenTextures(1, &_imgID);
	glBindTexture(GL_TEXTURE_2D, _imgID);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, _imgGL.width(), _imgGL.height(), 0, GL_RGBA, GL_UNSIGNED_BYTE, _imgGL.bits());
}
Ejemplo n.º 23
0
float get_hue(int r, int g, int b)
{
    int min = my_min(r, g, b);
    int max = my_max(r, g, b);
    int c = max - min;

    float H1 = 0;

    if( c == 0) return 0;

    if (max == r) {
        H1 = (float)(g - b) / c;
        H1 = fmod(H1, 6);
    } else if (max == g) {
        H1 = (float)(b - r) / c;
        H1 += 2;
    } else if (max == b) {
        H1 = (float)(r - g) / c;
        H1 += 4;
    }

    return H1 * 60.0;
}
// trace a ray through pixel (i,j) of the image an return the color
Vec3f GLCanvas::TraceRay(double i, double j) {
  // compute and set the pixel color
  int max_d = my_max(args->width,args->height);
  Vec3f color = Vec3f(0,0,0);
  int sampleAA = args->num_antialias_samples;

  while(sampleAA>0){


  // ==================================
  // ASSIGNMENT: IMPLEMENT ANTIALIASING
  // ==================================
  // Here's what we do with a single sample per pixel:
  // construct & trace a ray through the center of the pixle
    double a = GLOBAL_mtrand.rand();
    double b = GLOBAL_mtrand.rand();
    double x = (i+a-args->width/2.0)/double(max_d)+0.5;
    double y = (j+b-args->height/2.0)/double(max_d)+0.5;
    Ray r = mesh->camera->generateRay(x,y);
    Hit hit = Hit();
    int num_timesteps = mesh->numTimesteps();
    Vec3f tmpcolor = Vec3f(0,0,0);
    
    if (num_timesteps == 1) tmpcolor = raytracer->TraceRay(r,hit,args->num_bounces,0);
    
    for (int t = 0; t<num_timesteps-1; t++) {
      tmpcolor += raytracer->TraceRay(r,hit,args->num_bounces,t);
    }
    color += (tmpcolor/(double)num_timesteps)/args->num_antialias_samples;
    // add that ray for visualization
    RayTree::AddMainSegment(r,0,hit.getT());
    sampleAA--;
  }

  // return the color
  return color;
}
Ejemplo n.º 25
0
void cydrvb_set_tap(CydReverb *rvb, int idx, int delay_ms, int gain_db, int panning)
{
	rvb->tap[idx].delay = delay_ms;
	rvb->tap[idx].position = (rvb->position - (delay_ms * rvb->rate / 1000) + rvb->size) % rvb->size;
	
	if (gain_db <= CYDRVB_LOW_LIMIT)
	{
		rvb->tap[idx].gain_l = 0;
		rvb->tap[idx].gain_r = 0;
	}
	else
	{
#ifdef STEREOOUTPUT
		panning = my_min(CYD_PAN_RIGHT, my_max(CYD_PAN_LEFT, panning));
		float a = M_PI / 2 * (float)(panning - CYD_PAN_LEFT) / (CYD_PAN_RIGHT - CYD_PAN_LEFT);
		int gain = pow(10.0, (double)gain_db * 0.01) * CYDRVB_0dB;
		rvb->tap[idx].gain_l = gain * cos(a);
		rvb->tap[idx].gain_r = gain * sin(a);
#else
		int gain = pow(10.0, (double)gain_db * 0.01) * CYDRVB_0dB;
		rvb->tap[idx].gain = gain;
#endif
	}
}
Ejemplo n.º 26
0
// This function is called each time the DSP receives a new picture 
void userProcessColorImageFunc_laser(bgr *ptrImage) {
	
	int i;	
	if (toggle)
	{
		// seeing blue golf ball
		specs_h = 131;
		specs_hrad = 26;
		if((specs_h-specs_hrad)<0) // wrap 0->360
		{
			specs_h2=specs_h+256;
		}
		else // wrap 360->0
		{
			specs_h2=specs_h-256;
		}
		specs_s = 91;
		specs_srad = 36;
		specs_v = 121;
		specs_vrad = 64;
	}
	else
	{
		// seeing green
		specs_h = 91;
		specs_hrad = 25;
		if((specs_h-specs_hrad)<0) // wrap 0->360
		{
			specs_h2=specs_h+256;
		}
		else // wrap 360->0
		{
			specs_h2=specs_h-256;
		}
		specs_s = 157;
		specs_srad = 50;
		specs_v = 170;
		specs_vrad = 25;
	}

	if (ptrImage != NULL) {
		
		// Initialize all arrays for equivalency
		for (i=0; i < MAX_NUM_EQUIVALENCIES; i++) {
			equivalency_objects[i] = 0; // initialze link array
			object_stats[i].num_pixels_in_object = 0;
			object_stats[i].sum_r = 0;
			object_stats[i].sum_c = 0;
		}

		num_unique_objects = 0;
		
		object_detected = 0;
		
        // First Pass thru image.  Convert RGB to HSV.  This code is taking into account that the robot's camera only returns
        // a value between 16 and 240 for pixel intensity.  It also adds a gain of 2 to the blue intensity.  
		for (r=0;r<IMAGE_ROWS;r++) {
			for(c=0;c<IMAGE_COLUMNS;c++) {
				
				red =  ((ptrImage[r*IMAGE_COLUMNS+c].red - 16)*255)/224;
				green = ((ptrImage[r*IMAGE_COLUMNS+c].green - 16)*255)/224;
				blue = ptrImage[r*IMAGE_COLUMNS+c].blue*2;

				if (blue > 240) {
					blue = 240;
				}
				blue = ((blue - 16)*255)/224;

				min = my_min( red, green, blue );
	 			value = my_max( red, green, blue );

			 	delta = value - min;
			 	if( value != 0 ) {
			 		sat = (delta*255) / value;		// s

			 		if (delta != 0) {
					 	if( red == value )
					 		hue = 60*( green - blue ) / delta;		// between yellow & magenta
					 	else if( green == value )
					 		hue = 120 + 60*( blue - red ) / delta;	// between cyan & yellow
					 	else
					 		hue = 240 + 60*( red - green ) / delta;	// between magenta & cyan
					 	if( hue < 0 )
					 		hue += 360;
					} else {
					 	hue = 0;
					 	sat = 0;
					}
			 	} else {
			 		// r = g = b = 0		// s = 0, v is undefined
			 		sat = 0;
			 		hue = 0;
			 	}

			 	hue = (hue*255)/360;


				if ( (abs(sat-specs_s)<=specs_srad)
                  && (abs(value-specs_v)<=specs_vrad)
                  && (   (abs(hue-specs_h)<=specs_hrad)
                      || (abs(hue-specs_h2)<=specs_hrad) // catch the hue wraparround
                     )
                   ) { 			 	

					object_detected = 1;	// Set a flag that at least one pixel found above threshold
					
					// -------- Connectivity calculations ------------
					// Labels pixels 1 to MAX_NUM_EQUIVALENCIES depending on top and left neighbors
					// The labels represent object number...
					if (r == 0) top = 0;  else top = Thres_Image[(r-1)*IMAGE_COLUMNS+c];  // previous row, same column												
					if (c == 0) left = 0; else left = Thres_Image[r*IMAGE_COLUMNS+(c-1)];  // same row, previous column
					
					neighbor_type = 0;
					if (left != 0) neighbor_type += 1;
					if (top != 0)  neighbor_type += 2;
													
					current_object = 0;				
					switch (neighbor_type) {
						case 0: // Both neighbors zero, New object needed
                            if (num_unique_objects < (MAX_NUM_EQUIVALENCIES-1) ) {
				            	num_unique_objects++;
                                equivalency_objects[num_unique_objects] = num_unique_objects;
				            } else {
                                too_many_objects++;
                            }
							current_object = num_unique_objects;
							break;	
						case 1:	// Top is zero, left is not zero
							current_object = left;
							break;
						case 2:	// Left is zero, top is not zero
							current_object = top;
							break;
						case 3:	// Top and left are not zero... must note equivalency
							if (top == left) current_object = left;
							else {
								if (Check_Equivalency(top,left) == 0) {
									current_object = Set_Equivalency(top,left);																
								}
								else {
									current_object = left; 
								}
							}
							break;
						default: // Should NEVER enter here
							current_object = 0;  // Object 0 stores errors
							break;
					}
					Thres_Image[r*IMAGE_COLUMNS+c] = current_object;
					object_stats[current_object].num_pixels_in_object +=1;
					object_stats[current_object].sum_r += r;						
					object_stats[current_object].sum_c += c;						
					// ---------- Done with connectivity calculations (first pass) ----------
												
				} else {
					Thres_Image[r*IMAGE_COLUMNS+c] = 0;
				}
				
				
				
			 }
		}

		// initialize final object stats
		for (i=1; i<= MAX_NUM_OBJECTS; i++) {
			final_object_stats[i].sum_r = 0;
			final_object_stats[i].sum_c = 0;
			final_object_stats[i].num_pixels_in_object = 0;
			final_object_stats[i].center_r = 0.0;
			final_object_stats[i].center_c = 0.0;
			final_object_stats[i].C02_sum = 0.0;
			final_object_stats[i].C11_sum = 0.0;
			final_object_stats[i].C20_sum = 0.0;
			final_object_stats[i].theta = 0.0;
		}

		if (object_detected == 0) {
			num_unique_objects = 0;
		}
		else {
			num_unique_objects = Fix_Equivalency(num_unique_objects);// num_unique_objects contains the number of initial equivalencies found
		}
		
        if (num_unique_objects > MAX_NUM_OBJECTS) num_unique_objects = MAX_NUM_OBJECTS;


		// Third pass: correct image for nice display and calculate object moments
        // This is commented out because for the 176X144 image this adds a large amount of proccessing time when a large blob is found
//		for (r=0; r < IMAGE_ROWS; r++) {	// Loop over rows
//			for (c=0; c < IMAGE_COLUMNS; c++) {		// Loop over columns
//				if (Thres_Image[r*IMAGE_COLUMNS+c] > 0) {
//					// Fix pixel equivalency
//					Thres_Image[r*IMAGE_COLUMNS+c] = equivalency_objects[Thres_Image[r*IMAGE_COLUMNS+c]];
//
//					// Calculate second moments here
//					if ((Thres_Image[r*IMAGE_COLUMNS+c] > 0) && (Thres_Image[r*IMAGE_COLUMNS+c] <= MAX_NUM_OBJECTS)) {
//						final_object_stats[Thres_Image[r*IMAGE_COLUMNS+c]].C02_sum += (c - final_object_stats[Thres_Image[r*IMAGE_COLUMNS+c]].center_c)*(c - final_object_stats[Thres_Image[r*IMAGE_COLUMNS+c]].center_c);
//						final_object_stats[Thres_Image[r*IMAGE_COLUMNS+c]].C11_sum += (r - final_object_stats[Thres_Image[r*IMAGE_COLUMNS+c]].center_r)*(c - final_object_stats[Thres_Image[r*IMAGE_COLUMNS+c]].center_c);
//						final_object_stats[Thres_Image[r*IMAGE_COLUMNS+c]].C20_sum += (r - final_object_stats[Thres_Image[r*IMAGE_COLUMNS+c]].center_r)*(r - final_object_stats[Thres_Image[r*IMAGE_COLUMNS+c]].center_r);
//					}
//
//				}
//			}
//		}

		// Find largest object and calculate object orientation
		largest_num_pixels = 0;
		largest_object = 1;
		for (k = 1; k <= num_unique_objects ; k++) {				
			if (final_object_stats[k].num_pixels_in_object > largest_num_pixels) {
				largest_num_pixels = final_object_stats[k].num_pixels_in_object;
				largest_object = k;
			}	
			  // find theta of found blob
			  // commented out because moments need to be calculated above to use this code.
//            if (final_object_stats[k].num_pixels_in_object > NUMPIXELS_TO_CALC_ANGLE) {
//                // Calculate the object orientation angle if there are NUMPIXELS_TO_CALC_ANGLE in the object
//                Cdifference = final_object_stats[k].C20_sum - final_object_stats[k].C02_sum;
//                if (Cdifference != 0.0F) { // can't divide by zero
//                    final_object_stats[k].theta = atansp(final_object_stats[k].C11_sum/Cdifference)/2.0F;
//                } else {
//                    final_object_stats[k].theta = 0.0;
//                }
//                if (final_object_stats[k].C20_sum > final_object_stats[k].C02_sum) {
//                    if (final_object_stats[k].theta < 0) final_object_stats[k].theta += PI/2.0F;
//                    else final_object_stats[k].theta += -PI/2.0F;
//                }
//            } else {
//                final_object_stats[k].theta = 0;
//            }
            
		} // Ends loop through objects
		
		// Find the middle
		if (new_vision_data == 0)
		{
			if (toggle)
			{
				blue_rbar = (int) (final_object_stats[largest_object].center_r);
				blue_cbar = (int) (final_object_stats[largest_object].center_c);
				blueNumPixels = (int) final_object_stats[largest_object].num_pixels_in_object;
				toggle = 0;
			}
			else
			{
				green_rbar = (int) (final_object_stats[largest_object].center_r);
				green_cbar = (int) (final_object_stats[largest_object].center_c);
				greenNumPixels = (int) final_object_stats[largest_object].num_pixels_in_object;
				toggle = 1;
			}

			new_vision_data = 1;
		}

		// pass data to RobotControl()
		if (new_coordata == 0) {
			if (final_object_stats[largest_object].num_pixels_in_object > 1) {
				noimagefound = 0;
				new_num_found_objects = num_unique_objects;
				object_x = cbar - IMAGE_COLUMNS/2;
				object_y = rbar - IMAGE_ROWS/2;
				numpels = final_object_stats[largest_object].num_pixels_in_object;
				//new_object_theta 	= final_object_stats[largest_object].theta;
				//new_C20				= final_object_stats[largest_object].C20_sum;
				//new_C02				= final_object_stats[largest_object].C02_sum;
				new_coordata = 1;
			} else {
				noimagefound = 1;
				new_num_found_objects = num_unique_objects;
				object_x = 0.0;
				object_y = 0.0;
				numpels = 0;
				//new_object_theta = 0.0;
				//new_C20 = 0.0;
				//new_C02 = 0.0;
				new_coordata = 1;
			}
		}

        //create green x for largest centroid position
        if (final_object_stats[largest_object].num_pixels_in_object > 6) {

            ptrImage[rbar*IMAGE_COLUMNS+cbar].red = 0;
            ptrImage[rbar*IMAGE_COLUMNS+cbar].blue = 0;
            ptrImage[rbar*IMAGE_COLUMNS+cbar].green = 255;
            if (rbar > 0) {
                ptrImage[(rbar-1)*IMAGE_COLUMNS+cbar].red =  0;
                ptrImage[(rbar-1)*IMAGE_COLUMNS+cbar].blue = 0;
                ptrImage[(rbar-1)*IMAGE_COLUMNS+cbar].green = 255;
            }
            if (rbar < (IMAGE_ROWS-1)) {
                ptrImage[(rbar+1)*IMAGE_COLUMNS+cbar].red = 0;
                ptrImage[(rbar+1)*IMAGE_COLUMNS+cbar].blue = 0;
                ptrImage[(rbar+1)*IMAGE_COLUMNS+cbar].green = 255;
            }
            if (cbar > 0) {
                ptrImage[rbar*IMAGE_COLUMNS+(cbar-1)].red = 0;
                ptrImage[rbar*IMAGE_COLUMNS+(cbar-1)].blue = 0;
                ptrImage[rbar*IMAGE_COLUMNS+(cbar-1)].green = 255;
            }
            if (cbar < (IMAGE_COLUMNS-1)) {
                ptrImage[rbar*IMAGE_COLUMNS+(cbar+1)].red = 0;
                ptrImage[rbar*IMAGE_COLUMNS+(cbar+1)].blue = 0;
                ptrImage[rbar*IMAGE_COLUMNS+(cbar+1)].green = 255;
            }
        }


        if ( 12 == switchstate) {
            UpdateLCDwithLADAR(ptrImage,1);
        }

        // Send image to Color LCD if LCD ready for new data
		if (updateLCD) {

			updateLCD = 0;

			BCACHE_inv((void *)(ADDR_VIDEO_DATA_BASE+0x1A900),IMAGE_ROWS*IMAGE_COLUMNS*3,EDMA3_CACHE_WAIT);
			// Flush or write back source
	        BCACHE_wb ((void *)ptrImage,IMAGE_ROWS*IMAGE_COLUMNS*3,EDMA3_CACHE_WAIT);
			//Need to clean the cache here
			EDMA3_1_Regs->PARAMENTRY[33].OPT = 0x0011E00C;
			EDMA3_1_Regs->PARAMENTRY[33].SRC = (unsigned int)Image_data;
			EDMA3_1_Regs->PARAMENTRY[33].A_B_CNT = 0x004004A4;   //Maybe to ACNT = 1188 and BCNT = 64
			EDMA3_1_Regs->PARAMENTRY[33].DST = (ADDR_VIDEO_DATA_BASE+LCD_IMAGE_OFFSET);
			EDMA3_1_Regs->PARAMENTRY[33].SRC_DST_BIDX = 0x04A404A4;
			EDMA3_1_Regs->PARAMENTRY[33].LINK_BCNTRLD = 0x0000FFFF;  // Null link
			EDMA3_1_Regs->PARAMENTRY[33].SRC_DST_CIDX = 0x0;
			EDMA3_1_Regs->PARAMENTRY[33].CCNT = 0x1;  //Last command triggers transmission

		}

		// If Linux is ready for another full 176X144 RGB image start the EDMA transfer of the image to external memory
		if (GET_IMAGE_TO_LINUX) {

			// Invalidate Destination
			BCACHE_inv((void *)Linux_Image,IMAGE_ROWS*IMAGE_COLUMNS*3,EDMA3_CACHE_WAIT);
			// Flush or write back source
	        BCACHE_wb ((void *)ptrImage,IMAGE_ROWS*IMAGE_COLUMNS*3,EDMA3_CACHE_WAIT);

			EDMA3_1_Regs->PARAMENTRY[32].OPT = 0x0011F00C;
			EDMA3_1_Regs->PARAMENTRY[32].SRC = (unsigned int)Image_data;
			EDMA3_1_Regs->PARAMENTRY[32].A_B_CNT = 0x004004A4;   //Maybe to ACNT = 1188 and BCNT = 64
			EDMA3_1_Regs->PARAMENTRY[32].DST = (ADDR_VIDEO_DATA_BASE+LINUX_IMAGE_OFFSET);
			EDMA3_1_Regs->PARAMENTRY[32].SRC_DST_BIDX = 0x04A404A4;
			EDMA3_1_Regs->PARAMENTRY[32].LINK_BCNTRLD = 0x0000FFFF;  // Null link
			EDMA3_1_Regs->PARAMENTRY[32].SRC_DST_CIDX = 0x0;
			EDMA3_1_Regs->PARAMENTRY[32].CCNT = 0x1;  //Last command triggers transmission

		}
		
	}  // Ends if statement to see if image pointer is null				
	
}
Ejemplo n.º 27
0
// Считывание параметров задачи из файла
void read_defines(int argc, char *argv[])
{
	FILE *defs;
	char str[250] = "", attr_name[50] = "", attr_value[50] = "";
	// Settings file name
	char file[32];

	printf("%d: %s %s \n", argc, argv[0], argv[1]);
	if (argc > 1)
	{
		strcpy(file, argv[1]);
	} else {
		strcpy(file, "defines.ini");
	}

	if (!(defs = fopen(file, "rt")))
	{
		if (!(defs = fopen(file, "rt")))
		{
			char error[30];
			sprintf(error, "Not open file \"%s\"", file);
			print_error("Not open file \"defines.ini\"", __FILE__, __LINE__);
		}
	}

	while (!feof(defs))
	{
		unsigned int i, j, a;
		fgets(str, 250, defs);
		if (str[0] == '#')
		{
			continue;
		}

		for (i = 0; str[i] != '='; i++)
		{
			if (i >= strlen(str))
			{
				continue;
			}
			attr_name[i] = str[i];
		}

		attr_name[i] = '\0';
		a = strlen(str);
		for (j = i + 1; str[j] != ' ' && (j < a); j++)
		{
			attr_value[j - i - 1] = str[j];
		}
		// remove \n symbol
		attr_value[j - i - 2] = '\0';

		//std::cout << str <<"\n";

		if (!strcmp(attr_name, "NX"))
		{
			def.Nx = atoi(attr_value);
			continue;
		}
		if (!strcmp(attr_name, "NY"))
		{
			def.Ny = atoi(attr_value);
			continue;
		}
		if (!strcmp(attr_name, "NZ"))
		{
			def.Nz = atoi(attr_value);
			continue;
		}
		if (!strcmp(attr_name, "TAU"))
		{
			def.tau = atof(attr_value);
			continue;
		}
		if (!strcmp(attr_name, "DT"))
		{
			def.dt = atof(attr_value);
			continue;
		}
		if (!strcmp(attr_name, "C_W"))
		{
			def.c_w = atof(attr_value);
			continue;
		}
		if (!strcmp(attr_name, "C_N"))
		{
			def.c_n = atof(attr_value);
			continue;
		}
		if (!strcmp(attr_name, "L"))
		{
			def.l = atof(attr_value);
			continue;
		}
		if (!strcmp(attr_name, "BETA_W"))
		{
			def.beta_w = atof(attr_value);
			continue;
		}
		if (!strcmp(attr_name, "BETA_N"))
		{
			def.beta_n = atof(attr_value);
			continue;
		}
		if (!strcmp(attr_name, "RO_W"))
		{
			def.ro0_w = atof(attr_value);
			continue;
		}
		if (!strcmp(attr_name, "RO_N"))
		{
			def.ro0_n = atof(attr_value);
			continue;
		}
		if (!strcmp(attr_name, "MU_W"))
		{
			def.mu_w = atof(attr_value);
			continue;
		}
		if (!strcmp(attr_name, "MU_N"))
		{
			def.mu_n = atof(attr_value);
			continue;
		}
		if (!strcmp(attr_name, "G_CONST"))
		{
			def.g_const = atof(attr_value);
			continue;
		}
		if (!strcmp(attr_name, "P_ATM"))
		{
			def.P_atm = atof(attr_value);
			continue;
		}
		if (!strcmp(attr_name, "LAMBDA_0"))
		{
			def.lambda[0] = atof(attr_value);
			continue;
		}
		if (!strcmp(attr_name, "M_0"))
		{
			def.porosity[0] = atof(attr_value);
			continue;
		}
		if (!strcmp(attr_name, "S_WR_0"))
		{
			def.S_wr[0] = atof(attr_value);
			continue;
		}
		if (!strcmp(attr_name, "K_0"))
		{
			def.K[0] = atof(attr_value);
			continue;
		}
		if (!strcmp(attr_name, "C_G"))
		{
			def.c_g = atof(attr_value);
			continue;
		}
		if (!strcmp(attr_name, "BETA_G"))
		{
			def.beta_g = atof(attr_value);
			continue;
		}
		if (!strcmp(attr_name, "RO_G"))
		{
			def.ro0_g = atof(attr_value);
			continue;
		}
		if (!strcmp(attr_name, "MU_G"))
		{
			def.mu_g = atof(attr_value);
			continue;
		}
		if (!strcmp(attr_name, "P_D_NW_0"))
		{
			def.P_d_nw[0] = atof(attr_value);
			continue;
		}
		if (!strcmp(attr_name, "P_D_GN_0"))
		{
			def.P_d_gn[0] = atof(attr_value);
			continue;
		}
		if (!strcmp(attr_name, "S_W_GR"))
		{
			def.S_w_gr = atof(attr_value);
			continue;
		}
		if (!strcmp(attr_name, "S_W_INIT"))
		{
			def.S_w_init = atof(attr_value);
			continue;
		}
		if (!strcmp(attr_name, "S_N_INIT"))
		{
			def.S_n_init = atof(attr_value);
			continue;
		}
		if (!strcmp(attr_name, "S_NR_0"))
		{
			def.S_nr[0] = atof(attr_value);
			continue;
		}
		if (!strcmp(attr_name, "S_GR_0"))
		{
			def.S_gr[0] = atof(attr_value);
			continue;
		}
		if (!strcmp(attr_name, "S_N_GR"))
		{
			def.S_n_gr = atof(attr_value);
			continue;
		}
#ifdef ENERGY
		if (!strcmp(attr_name, "T_0"))
		{
			def.T_0 = atof(attr_value);
			continue;
		}
		if (!strcmp(attr_name, "RO_R"))
		{
			def.ro_r = atof(attr_value);
			continue;
		}
		if (!strcmp(attr_name, "LAMBDA_0_W"))
		{
			def.lambda0_w = atof(attr_value);
			continue;
		}
		if (!strcmp(attr_name, "LAMBDA_0_N"))
		{
			def.lambda0_n = atof(attr_value);
			continue;
		}
		if (!strcmp(attr_name, "LAMBDA_0_G"))
		{
			def.lambda0_g = atof(attr_value);
			continue;
		}
		if (!strcmp(attr_name, "LAMBDA_0_R"))
		{
			def.lambda0_r = atof(attr_value);
			continue;
		}
		if (!strcmp(attr_name, "LAMBDA_A_W"))
		{
			def.lambdaA_w = atof(attr_value);
			continue;
		}
		if (!strcmp(attr_name, "LAMBDA_A_N"))
		{
			def.lambdaA_n = atof(attr_value);
			continue;
		}
		if (!strcmp(attr_name, "LAMBDA_A_G"))
		{
			def.lambdaA_g = atof(attr_value);
			continue;
		}
		if (!strcmp(attr_name, "C_0_W"))
		{
			def.c0_w = atof(attr_value);
			continue;
		}
		if (!strcmp(attr_name, "C_0_N"))
		{
			def.c0_n = atof(attr_value);
			continue;
		}
		if (!strcmp(attr_name, "C_0_G"))
		{
			def.c0_g = atof(attr_value);
			continue;
		}
		if (!strcmp(attr_name, "C_0_R"))
		{
			def.c0_r = atof(attr_value);
			continue;
		}
		if (!strcmp(attr_name, "C_1_W"))
		{
			def.C_w = atof(attr_value);
			continue;
		}
		if (!strcmp(attr_name, "C_1_W2"))
		{
			def.C_w2 = atof(attr_value);
			continue;
		}
		if (!strcmp(attr_name, "C_1_N"))
		{
			def.C_n = atof(attr_value);
			continue;
		}
		if (!strcmp(attr_name, "C_1_G"))
		{
			def.C_g = atof(attr_value);
			continue;
		}
		if (!strcmp(attr_name, "C_1_R"))
		{
			def.C_r = atof(attr_value);
			continue;
		}
		if (!strcmp(attr_name, "ALFA_W"))
		{
			def.alfa_w = atof(attr_value);
			continue;
		}
		if (!strcmp(attr_name, "ALFA_N"))
		{
			def.alfa_n = atof(attr_value);
			continue;
		}
#endif
		if (!strcmp(attr_name, "SOURCE"))
		{
			def.source = atoi(attr_value);
			continue;
		}
		if (!strcmp(attr_name, "ITERATIONS"))
		{
			def.newton_iterations = atoi(attr_value);
			continue;
		}
		if (!strcmp(attr_name, "TIMEX"))
		{
			def.timeX = atof(attr_value);
			continue;
		}
		if (!strcmp(attr_name, "SAVE_PLOTS"))
		{
			def.save_plots = atoi(attr_value);
			continue;
		}
		if (!strcmp(attr_name, "PLOTS_DIR"))
		{
			strcpy(def.plots_dir, attr_value);
			continue;
		}
		if (!strcmp(attr_name, "PRINT_SCREEN"))
		{
			def.print_screen = atoi(attr_value);
			continue;
		}
	}

	fclose(defs);

	// Determine hx, hy, hz from Nx, Ny, Nz
	def.hx = 1.0 / (my_max((double)def.Nx - 1, 1));
	def.hy = 1.0 / (my_max((double)def.Ny - 1, 1));
	def.hz = 1.0 / (my_max((double)def.Nz - 1, 1));

	// Если нет масштабирования, то 1
	def.upscale_l=1;
	def.upscale_t=1;

	read_defines_test();
}
Ejemplo n.º 28
0
static char *handle_memory_show_summary(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
{
#define my_max(a, b) ((a) >= (b) ? (a) : (b))

	const char *fn = NULL;
	int idx;
	int cmp;
	struct ast_region *reg;
	unsigned int whales_len;
	unsigned int minnows_len;
	unsigned int total_len = 0;
	unsigned int selected_len = 0;
	unsigned int cache_len = 0;
	unsigned int count = 0;
	struct file_summary {
		struct file_summary *next;
		unsigned int len;
		unsigned int cache_len;
		unsigned int count;
		unsigned int lineno;
		char name[my_max(sizeof(reg->file), sizeof(reg->func))];
	} *list = NULL, *cur, **prev;

	switch (cmd) {
	case CLI_INIT:
		e->command = "memory show summary";
		e->usage =
			"Usage: memory show summary [<file>]\n"
			"       Summarizes heap memory allocations by file, or optionally\n"
			"       by line if a file is specified.\n";
		return NULL;
	case CLI_GENERATE:
		return NULL;
	}

	if (a->argc == 4) {
		fn = a->argv[3];
	} else if (a->argc != 3) {
		return CLI_SHOWUSAGE;
	}

	ast_mutex_lock(&reglock);
	for (idx = 0; idx < ARRAY_LEN(regions); ++idx) {
		for (reg = regions[idx]; reg; reg = AST_LIST_NEXT(reg, node)) {
			total_len += reg->len;
			if (fn) {
				if (strcasecmp(fn, reg->file)) {
					continue;
				}

				/* Sort list by func/lineno.  Find existing or place to insert. */
				for (prev = &list; (cur = *prev); prev = &cur->next) {
					cmp = strcmp(cur->name, reg->func);
					if (cmp < 0) {
						continue;
					}
					if (cmp > 0) {
						/* Insert before current */
						cur = NULL;
						break;
					}
					cmp = cur->lineno - reg->lineno;
					if (cmp < 0) {
						continue;
					}
					if (cmp > 0) {
						/* Insert before current */
						cur = NULL;
					}
					break;
				}
			} else {
				/* Sort list by filename.  Find existing or place to insert. */
				for (prev = &list; (cur = *prev); prev = &cur->next) {
					cmp = strcmp(cur->name, reg->file);
					if (cmp < 0) {
						continue;
					}
					if (cmp > 0) {
						/* Insert before current */
						cur = NULL;
					}
					break;
				}
			}

			if (!cur) {
				cur = ast_alloca(sizeof(*cur));
				memset(cur, 0, sizeof(*cur));
				cur->lineno = reg->lineno;
				ast_copy_string(cur->name, fn ? reg->func : reg->file, sizeof(cur->name));

				cur->next = *prev;
				*prev = cur;
			}

			cur->len += reg->len;
			if (reg->cache) {
				cur->cache_len += reg->len;
			}
			++cur->count;
		}
	}

	whales_len = freed_regions_size(&whales);
	minnows_len = freed_regions_size(&minnows);
	ast_mutex_unlock(&reglock);

	/* Dump the whole list */
	for (cur = list; cur; cur = cur->next) {
		selected_len += cur->len;
		cache_len += cur->cache_len;
		count += cur->count;
		if (cur->cache_len) {
			if (fn) {
				ast_cli(a->fd, "%10u bytes (%10u cache) in %10u allocations by %20s() line %5u of %s\n",
					cur->len, cur->cache_len, cur->count, cur->name, cur->lineno, fn);
			} else {
				ast_cli(a->fd, "%10u bytes (%10u cache) in %10u allocations in file %s\n",
					cur->len, cur->cache_len, cur->count, cur->name);
			}
		} else {
			if (fn) {
				ast_cli(a->fd, "%10u bytes in %10u allocations by %20s() line %5u of %s\n",
					cur->len, cur->count, cur->name, cur->lineno, fn);
			} else {
				ast_cli(a->fd, "%10u bytes in %10u allocations in file %s\n",
					cur->len, cur->count, cur->name);
			}
		}
	}

	print_memory_show_common_stats(a->fd,
		whales_len, minnows_len, total_len,
		selected_len, cache_len, count);

	return CLI_SUCCESS;
}
Ejemplo n.º 29
0
static bool decompress_file(ilzham &lzham_dll, const char* pSrc_filename, const char *pDst_filename, comp_options options)
{
   FILE *pInFile = fopen(pSrc_filename, "rb");
   if (!pInFile)
   {
      print_error("Unable to read file: %s\n", pSrc_filename);
      return false;
   }

   _fseeki64(pInFile, 0, SEEK_END);
   uint64 src_file_size = _ftelli64(pInFile);
   _fseeki64(pInFile, 0, SEEK_SET);
   if (src_file_size < (5+9))
   {
      print_error("Compressed file is too small!\n");
      fclose(pInFile);
      return false;
   }

   int h0 = fgetc(pInFile);
   int h1 = fgetc(pInFile);
   int h2 = fgetc(pInFile);
   int h3 = fgetc(pInFile);
   int dict_size = fgetc(pInFile);
   if ((h0 != 'L') | (h1 != 'Z') || (h2 != 'H') || (h3 != '0'))
   {
      print_error("Unrecognized/invalid header in file: %s\n", pSrc_filename);
      fclose(pInFile);
      return false;
   }

   if ((dict_size < LZHAM_MIN_DICT_SIZE_LOG2) || (dict_size > LZHAM_MAX_DICT_SIZE_LOG2_X64))
   {
      print_error("Unrecognized/invalid header in file: %s\n", pSrc_filename);
      fclose(pInFile);
      return false;
   }

   FILE *pOutFile = fopen(pDst_filename, "wb");
   if (!pOutFile)
   {
      print_error("Unable to create file: %s\n", pDst_filename);
      fclose(pInFile);
      return false;
   }

   uint64 orig_file_size = 0;
   for (uint i = 0; i < 8; i++)
   {
      orig_file_size |= (static_cast<uint64>(fgetc(pInFile)) << (i * 8));
   }

   int total_header_bytes = ftell(pInFile);

   // Avoid running out of memory on large files when using unbuffered decompression.
#ifdef _XBOX
   if ((options.m_unbuffered_decompression) && (orig_file_size > 128*1024*1024))
#else
   if ((options.m_unbuffered_decompression) && (orig_file_size > 1024*1024*1024))
#endif
   {
      printf("Output file is too large for unbuffered decompression - switching to streaming decompression.\n");
      options.m_unbuffered_decompression = false;
   }

   if (options.m_unbuffered_decompression)
      printf("Testing: Unbuffered decompression\n");
   else
      printf("Testing: Streaming decompression\n");

   const uint cInBufSize = LZHAMTEST_DECOMP_INPUT_BUFFER_SIZE;
   uint8 *in_file_buf = static_cast<uint8*>(_aligned_malloc(cInBufSize, 16));

   uint out_buf_size = options.m_unbuffered_decompression ? static_cast<uint>(orig_file_size) : LZHAMTEST_DECOMP_OUTPUT_BUFFER_SIZE;
   uint8 *out_file_buf = static_cast<uint8*>(_aligned_malloc(out_buf_size, 16));
   if (!out_file_buf)
   {
      print_error("Failed allocating output buffer!\n");
      _aligned_free(in_file_buf);
      fclose(pInFile);
      fclose(pOutFile);
      return false;
   }

   uint64 src_bytes_left = src_file_size - total_header_bytes;
   uint64 dst_bytes_left = orig_file_size;

   uint in_file_buf_size = 0;
   uint in_file_buf_ofs = 0;

   lzham_decompress_params params;
   memset(&params, 0, sizeof(params));
   params.m_struct_size = sizeof(lzham_decompress_params);
   params.m_dict_size_log2 = dict_size;
   params.m_compute_adler32 = options.m_compute_adler32_during_decomp;
   params.m_output_unbuffered = options.m_unbuffered_decompression;

   timer_ticks start_time = timer::get_ticks();
   double decomp_only_time = 0;

   timer_ticks init_start_time = timer::get_ticks();
   lzham_decompress_state_ptr pDecomp_state = lzham_dll.lzham_decompress_init(&params);
   timer_ticks total_init_time = timer::get_ticks() - init_start_time;
   if (!pDecomp_state)
   {
      print_error("Failed initializing decompressor!\n");
      _aligned_free(in_file_buf);
      _aligned_free(out_file_buf);
      fclose(pInFile);
      fclose(pOutFile);
      return false;
   }

   printf("lzham_decompress_init took %3.3fms\n", timer::ticks_to_secs(total_init_time)*1000.0f);

   lzham_decompress_status_t status;
   for ( ; ; )
   {
      if (in_file_buf_ofs == in_file_buf_size)
      {
         in_file_buf_size = static_cast<uint>(my_min(cInBufSize, src_bytes_left));

         if (fread(in_file_buf, 1, in_file_buf_size, pInFile) != in_file_buf_size)
         {
            print_error("Failure reading from source file!\n");
            _aligned_free(in_file_buf);
            _aligned_free(out_file_buf);
            lzham_dll.lzham_decompress_deinit(pDecomp_state);
            fclose(pInFile);
            fclose(pOutFile);
            return false;
         }

         src_bytes_left -= in_file_buf_size;

         in_file_buf_ofs = 0;
      }

      uint8 *pIn_bytes = &in_file_buf[in_file_buf_ofs];
      size_t num_in_bytes = in_file_buf_size - in_file_buf_ofs;
      uint8* pOut_bytes = out_file_buf;
      size_t out_num_bytes = out_buf_size;

      {
         timer decomp_only_timer;
         decomp_only_timer.start();
         status = lzham_dll.lzham_decompress(pDecomp_state, pIn_bytes, &num_in_bytes, pOut_bytes, &out_num_bytes, src_bytes_left == 0);
         decomp_only_time += decomp_only_timer.get_elapsed_secs();
      }

      if (num_in_bytes)
      {
         in_file_buf_ofs += (uint)num_in_bytes;
         assert(in_file_buf_ofs <= in_file_buf_size);
      }

      if (out_num_bytes)
      {
         if (fwrite(out_file_buf, 1, static_cast<uint>(out_num_bytes), pOutFile) != out_num_bytes)
         {
            print_error("Failure writing to destination file!\n");
            _aligned_free(in_file_buf);
            _aligned_free(out_file_buf);
            lzham_dll.lzham_decompress_deinit(pDecomp_state);
            fclose(pInFile);
            fclose(pOutFile);
            return false;
         }

         if (out_num_bytes > dst_bytes_left)
         {
            print_error("Decompressor wrote too many bytes to destination file!\n");
            _aligned_free(in_file_buf);
            _aligned_free(out_file_buf);
            lzham_dll.lzham_decompress_deinit(pDecomp_state);
            fclose(pInFile);
            fclose(pOutFile);
            return false;
         }
         dst_bytes_left -= out_num_bytes;
      }

      if ((status != LZHAM_DECOMP_STATUS_NOT_FINISHED) && (status != LZHAM_DECOMP_STATUS_NEEDS_MORE_INPUT))
         break;
   }
   _aligned_free(in_file_buf);
   in_file_buf = NULL;

   _aligned_free(out_file_buf);
   out_file_buf = NULL;

   src_bytes_left += (in_file_buf_size - in_file_buf_ofs);

   uint32 adler32 = lzham_dll.lzham_decompress_deinit(pDecomp_state);
   pDecomp_state = NULL;

   timer_ticks end_time = timer::get_ticks();
   double total_time = timer::ticks_to_secs(my_max(1, end_time - start_time));

   fclose(pInFile);
   pInFile = NULL;

   fclose(pOutFile);
   pOutFile = NULL;

   if (status != LZHAM_DECOMP_STATUS_SUCCESS)
   {
      print_error("Decompression FAILED with status %i\n", status);
      return false;
   }

   if (dst_bytes_left)
   {
      print_error("Decompressor FAILED to output the entire output file!\n");
      return false;
   }

   if (src_bytes_left)
   {
      print_error("Decompressor FAILED to read " QUAD_INT_FMT " bytes from input buffer\n", src_bytes_left);
   }

   printf("Success\n");
   printf("Source file size: " QUAD_INT_FMT ", Decompressed file size: " QUAD_INT_FMT "\n", src_file_size, orig_file_size);
   printf("Decompressed adler32: 0x%08X\n", adler32);
   printf("Overall decompression time (decompression init+I/O+decompression): %3.6f\n  Consumption rate: %9.1f bytes/sec, Decompression rate: %9.1f bytes/sec\n", total_time, src_file_size / total_time, orig_file_size / total_time);
   printf("Decompression only time (not counting decompression init or I/O): %3.6f\n  Consumption rate: %9.1f bytes/sec, Decompression rate: %9.1f bytes/sec\n", decomp_only_time, src_file_size / decomp_only_time, orig_file_size / decomp_only_time);

   return true;
}
Ejemplo n.º 30
0
static bool compress_streaming(ilzham &lzham_dll, const char* pSrc_filename, const char *pDst_filename, const comp_options &options)
{
   printf("Testing: Streaming compression\n");

   FILE *pInFile = fopen(pSrc_filename, "rb");
   if (!pInFile)
   {
      print_error("Unable to read file: %s\n", pSrc_filename);
      return false;
   }

   FILE *pOutFile = fopen(pDst_filename, "wb");
   if (!pOutFile)
   {
      print_error("Unable to create file: %s\n", pDst_filename);
      return false;
   }

   _fseeki64(pInFile, 0, SEEK_END);
   uint64 src_file_size = _ftelli64(pInFile);
   _fseeki64(pInFile, 0, SEEK_SET);

   fputc('L', pOutFile);
   fputc('Z', pOutFile);
   fputc('H', pOutFile);
   fputc('0', pOutFile);
   fputc(options.m_dict_size_log2, pOutFile);

   for (uint i = 0; i < 8; i++)
   {
      fputc(static_cast<int>((src_file_size >> (i * 8)) & 0xFF), pOutFile);
   }

   const uint cInBufSize = LZHAMTEST_COMP_INPUT_BUFFER_SIZE;
   const uint cOutBufSize = LZHAMTEST_COMP_OUTPUT_BUFFER_SIZE;

   uint8 *in_file_buf = static_cast<uint8*>(_aligned_malloc(cInBufSize, 16));
   uint8 *out_file_buf = static_cast<uint8*>(_aligned_malloc(cOutBufSize, 16));
   if ((!in_file_buf) || (!out_file_buf))
   {
      print_error("Out of memory!\n");
      _aligned_free(in_file_buf);
      _aligned_free(out_file_buf);
      fclose(pInFile);
      fclose(pOutFile);
      return false;
   }

   uint64 src_bytes_left = src_file_size;

   uint in_file_buf_size = 0;
   uint in_file_buf_ofs = 0;

   uint64 total_output_bytes = 0;

   timer_ticks start_time = timer::get_ticks();

   lzham_compress_params params;
   memset(&params, 0, sizeof(params));
   params.m_struct_size = sizeof(lzham_compress_params);
   params.m_dict_size_log2 = options.m_dict_size_log2;
   params.m_max_helper_threads = options.m_max_helper_threads;
   params.m_level = options.m_comp_level;
   if (options.m_force_polar_codes)
   {
      params.m_compress_flags |= LZHAM_COMP_FLAG_FORCE_POLAR_CODING;
   }
   if (options.m_extreme_parsing)
   {
      params.m_compress_flags |= LZHAM_COMP_FLAG_EXTREME_PARSING;
   }
   if (options.m_deterministic_parsing)
   {
      params.m_compress_flags |= LZHAM_COMP_FLAG_DETERMINISTIC_PARSING;
   }
   params.m_cpucache_line_size = 0;
   params.m_cpucache_total_lines = 0;

   timer_ticks init_start_time = timer::get_ticks();
   lzham_compress_state_ptr pComp_state = lzham_dll.lzham_compress_init(&params);
   timer_ticks total_init_time = timer::get_ticks() - init_start_time;

   if (!pComp_state)
   {
      print_error("Failed initializing compressor!\n");
      _aligned_free(in_file_buf);
      _aligned_free(out_file_buf);
      fclose(pInFile);
      fclose(pOutFile);
      return false;
   }

   printf("lzham_compress_init took %3.3fms\n", timer::ticks_to_secs(total_init_time)*1000.0f);

   lzham_compress_status_t status;
   for ( ; ; )
   {
      if (src_file_size)
      {
         double total_elapsed_time = timer::ticks_to_secs(timer::get_ticks() - start_time);
         double total_bytes_processed = static_cast<double>(src_file_size - src_bytes_left);
         double comp_rate = (total_elapsed_time > 0.0f) ? total_bytes_processed / total_elapsed_time : 0.0f;

         for (int i = 0; i < 15; i++)
            printf("\b\b\b\b");
         printf("Progress: %3.1f%%, Bytes Remaining: %3.1fMB, %3.3fMB/sec", (1.0f - (static_cast<float>(src_bytes_left) / src_file_size)) * 100.0f, src_bytes_left / 1048576.0f, comp_rate / (1024.0f * 1024.0f));
         printf("                \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b");
      }

      if (in_file_buf_ofs == in_file_buf_size)
      {
         in_file_buf_size = static_cast<uint>(my_min(cInBufSize, src_bytes_left));

         if (fread(in_file_buf, 1, in_file_buf_size, pInFile) != in_file_buf_size)
         {
            printf("\n");
            print_error("Failure reading from source file!\n");
            _aligned_free(in_file_buf);
            _aligned_free(out_file_buf);
            fclose(pInFile);
            fclose(pOutFile);
            lzham_dll.lzham_decompress_deinit(pComp_state);
            return false;
         }

         src_bytes_left -= in_file_buf_size;

         in_file_buf_ofs = 0;
      }

      uint8 *pIn_bytes = &in_file_buf[in_file_buf_ofs];
      size_t num_in_bytes = in_file_buf_size - in_file_buf_ofs;
      uint8* pOut_bytes = out_file_buf;
      size_t out_num_bytes = cOutBufSize;

      status = lzham_dll.lzham_compress(pComp_state, pIn_bytes, &num_in_bytes, pOut_bytes, &out_num_bytes, src_bytes_left == 0);

      if (num_in_bytes)
      {
         in_file_buf_ofs += (uint)num_in_bytes;
         assert(in_file_buf_ofs <= in_file_buf_size);
      }

      if (out_num_bytes)
      {
         if (fwrite(out_file_buf, 1, static_cast<uint>(out_num_bytes), pOutFile) != out_num_bytes)
         {
            printf("\n");
            print_error("Failure writing to destination file!\n");
            _aligned_free(in_file_buf);
            _aligned_free(out_file_buf);
            fclose(pInFile);
            fclose(pOutFile);
            lzham_dll.lzham_decompress_deinit(pComp_state);
            return false;
         }

         total_output_bytes += out_num_bytes;
      }

      if ((status != LZHAM_COMP_STATUS_NOT_FINISHED) && (status != LZHAM_COMP_STATUS_NEEDS_MORE_INPUT))
         break;
   }

   for (int i = 0; i < 15; i++)
   {
      printf("\b\b\b\b    \b\b\b\b");
   }

   src_bytes_left += (in_file_buf_size - in_file_buf_ofs);

   uint32 adler32 = lzham_dll.lzham_compress_deinit(pComp_state);
   pComp_state = NULL;

   timer_ticks end_time = timer::get_ticks();
   double total_time = timer::ticks_to_secs(my_max(1, end_time - start_time));

   uint64 cmp_file_size = _ftelli64(pOutFile);

   _aligned_free(in_file_buf);
   in_file_buf = NULL;
   _aligned_free(out_file_buf);
   out_file_buf = NULL;

   fclose(pInFile);
   pInFile = NULL;
   fclose(pOutFile);
   pOutFile = NULL;

   if (status != LZHAM_COMP_STATUS_SUCCESS)
   {
      print_error("Compression failed with status %i\n", status);
      return false;
   }

   if (src_bytes_left)
   {
      print_error("Compressor failed to consume entire input file!\n");
      return false;
   }

   printf("Success\n");
   printf("Input file size: " QUAD_INT_FMT ", Compressed file size: " QUAD_INT_FMT ", Ratio: %3.2f%%\n", src_file_size, cmp_file_size, src_file_size ? ((1.0f - (static_cast<float>(cmp_file_size) / src_file_size)) * 100.0f) : 0.0f);
   printf("Compression time: %3.6f\nConsumption rate: %9.1f bytes/sec, Emission rate: %9.1f bytes/sec\n", total_time, src_file_size / total_time, cmp_file_size / total_time);
   printf("Input file adler32: 0x%08X\n", adler32);

   return true;
}