int main(void)
{
//	char pre_seq[] = "421356";
//	char in_seq[] = "123456";

//	root = init(pre_seq, in_seq, 6);

#if 0
	link a, b, c, d, e, f;

//	printf("demo binary tree!\n");	
	a = make_node('4');
	b = make_node('2');
	c = make_node('5');
	d = make_node('1');
	e = make_node('3');
	f = make_node('6');

	a->l = b;
//	a->r = c;
	b->l = d;
	d->l = c;
	c->l = f;
	b->r = e;
//	c->r = f;

	root = a;
#endif

	while (1) {
		char ch;
		ch = getchar();
		getchar();	
		if (ch == 'q')
			break;

		root = insert(root, ch);	

		printf("\\tree");
		traverse(root);
		printf("\n");
	}

	while (1) {
		char ch = getchar();
		getchar();

	link p = search(root, ch);
	if (p != NULL)
		printf("%c is found\n", ch);
	else
		printf("%c is NOT found\n", ch);
	}

		printf("count = %d\n", count(root));		
		printf("depth = %d\n", depth(root));		
		printf("balanced = %d\n", isbalanced(root));		
#if 0
	if (mypow(2, depth(root)) == count(root) + 1)
		printf("it is a FULL Btree\n");
	else
		printf("it is not a FULL Btree\n");
#endif

	return 0;
}
Exemple #2
0
void Renderer2d::render(cv::Mat &image_out, cv::Mat &depth_out, cv::Mat &mask_out, cv::Rect &rect) const {
  // Figure out the transform from an original image pixel to a projected pixel
  // original frame: 0 is the top left corner of the pattern, X goes right, Y down, Z away from the camera
  // projected frame: 0 is the center of the projection image, X goes right, Y up, Z towards the camera

  // Scale the image properly
  float s = physical_width_ / img_ori_.cols;
  cv::Matx44f T_img_physical = cv::Matx44f(s,0,0,0, 0,s,0,0, 0,0,s,0, 0,0,0,1);

  // Flip axes and center at 0,0,0
  float physical_height = img_ori_.rows * s;
  T_img_physical = cv::Matx44f(1,0,0,-float(physical_width_) / 2, 0,1,0,float(physical_height) / 2, 0,0,1,0, 0,0,0,1) *
      cv::Matx44f(1,0,0,0, 0,-1,0,0, 0,0,-1,0, 0,0,0,1) * T_img_physical;

  // Define the perspective transform to apply to the image (z=0 so we can ignore the 3rd column of P)
  cv::Matx34f P_noK = cv::Matx34f(R_(0, 0), R_(0, 1), R_(0, 2), T_(0), R_(1, 0), R_(1, 1), R_(1, 2), T_(1), R_(2, 0),
      R_(2, 1), R_(2, 2), T_(2)) * T_img_physical;
  cv::Matx33f T_to3d = cv::Matx33f(P_noK(0, 0), P_noK(0, 1), P_noK(0, 3), P_noK(1, 0), P_noK(1, 1), P_noK(1, 3),
      P_noK(2, 0), P_noK(2, 1), P_noK(2, 3));

  // Apply the camera transform
  cv::Matx33f T_img = K_ * T_to3d;

  // And readapt to an OpenCV image
  T_img = cv::Matx33f(1, 0, 0, 0, -1, 0, 0, 0, 1) * T_img;

  // Define the image corners
  std::vector<cv::Vec2f> corners(4);
  corners[0] = cv::Vec2f(0, 0);
  corners[1] = cv::Vec2f(img_ori_.cols, 0);
  corners[2] = cv::Vec2f(img_ori_.cols, img_ori_.rows);
  corners[3] = cv::Vec2f(0, corners[2][1]);

  // Project the image corners
  float x_min = std::numeric_limits<float>::max(), y_min = x_min;

  std::vector<cv::Vec2f> corners_dst(4);
  for (size_t i = 0; i < corners.size(); ++i) {
    cv::Vec3f res = T_img * cv::Vec3f(corners[i][0], corners[i][1], 1);
    x_min = std::min(res[0] / res[2], x_min);
    y_min = std::min(res[1] / res[2], y_min);
  }

  // Warp the mask
  cv::Size final_size(width_, height_);
  cv::Mat_<uchar> mask;
  T_img = cv::Matx33f(1, 0, -x_min, 0, 1, -y_min, 0, 0, 1) * T_img;

  // Compute the inverse
  cv::Matx33f T_img_inv = T_img.inv();

  cv::warpPerspective(mask_ori_, mask, T_img, final_size, cv::INTER_NEAREST, cv::BORDER_CONSTANT, cv::Scalar(0));

  // Warp the image/depth
  cv::Mat_<cv::Vec3b> image = cv::Mat_<cv::Vec3b>::zeros(final_size);
  cv::Mat_<unsigned short> depth = cv::Mat_<unsigned short>::zeros(final_size);
  cv::Mat_<uchar>::iterator mask_it = mask.begin(), mask_end = mask.end();

  unsigned int i_min = width_, i_max = 0, j_min = height_, j_max = 0;
  for (unsigned int j = 0; j < height_; ++j)
    for (unsigned int i = 0; i < width_; ++i, ++mask_it) {
      if (!*mask_it)
        continue;
      // Figure out the coordinates of the original point
      cv::Vec3f point_ori = T_img_inv * cv::Vec3f(i, j, 1);

      int j_ori = point_ori[1] / point_ori[2], i_ori = point_ori[0] / point_ori[2];
      image(j, i) = img_ori_(j_ori, i_ori);

      // Figure out the 3d position of the point
      cv::Vec3f pos = T_to3d * cv::Vec3f(i_ori, j_ori, 1);
      // Do not forget to re-scale in millimeters
      depth(j, i) = -pos[2]*1000;

      // Figure the inclusive bounding box of the mask, just for performance reasons for later
      if (j > j_max)
        j_max = j;
      else if (j < j_min)
        j_min = j;
      if (i > i_max)
        i_max = i;
      else if (i < i_min)
        i_min = i;
    }

  // Crop the images, just so that they are smaller to write/read
  if (i_min > 0)
    --i_min;
  if (i_max < width_ - 1)
    ++i_max;
  if (j_min > 0)
    --j_min;
  if (j_max < height_ - 1)
    ++j_max;
  rect = cv::Rect(i_min, j_min, i_max - i_min + 1, j_max - j_min + 1);

  depth(rect).copyTo(depth_out);
  image(rect).copyTo(image_out);
  mask(rect).copyTo(mask_out);
}
Exemple #3
0
//--------------------------------------------------------------------------------------------------
/// 
//--------------------------------------------------------------------------------------------------
void OverlayTextBox::renderBackgroundAndBorder(OpenGLContext* oglContext, const Vec2ui& position, const Vec2ui& size, bool software)
{
    CVF_CALLSITE_OPENGL(oglContext);

    // Prepare 2D pixel exact projection to draw texts
    Camera projCam;
    projCam.setViewport(position.x(), position.y(), size.x(), size.y());
    projCam.setProjectionAsPixelExact2D();
    projCam.setViewMatrix(Mat4d::IDENTITY);

    // Turn off depth test
    Depth depth(false, Depth::LESS, false);
    depth.applyOpenGL(oglContext);

    ref<ShaderProgram> backgroundShader;
    float vertexArray[12];

    projCam.viewport()->applyOpenGL(oglContext, Viewport::DO_NOT_CLEAR);

    if (software)
    {
        if (ShaderProgram::supportedOpenGL(oglContext))
        {
            ShaderProgram::useNoProgram(oglContext);
        }

#ifndef CVF_OPENGL_ES
        Material_FF mat;
        mat.enableColorMaterial(true);
        mat.applyOpenGL(oglContext);

        Lighting_FF light(false);
        light.applyOpenGL(oglContext);
#endif
        projCam.applyOpenGL();
    }
    else
    {
        glBindBuffer(GL_ARRAY_BUFFER, 0);
        glEnableVertexAttribArray(ShaderProgram::VERTEX);
        glVertexAttribPointer(ShaderProgram::VERTEX, 3, GL_FLOAT, GL_FALSE, 0, vertexArray);

        backgroundShader = oglContext->resourceManager()->getLinkedUnlitColorShaderProgram(oglContext);
        if (backgroundShader->useProgram(oglContext))
        {
            MatrixState projMatrixState(projCam);
            backgroundShader->clearUniformApplyTracking();
            backgroundShader->applyFixedUniforms(oglContext, projMatrixState);
        }
    }

    Vec3f min(1.0f, 1.0f, 0.0f);
    Vec3f max(static_cast<float>(size.x() - 1), static_cast<float>(size.y() - 1), 0.0f);

    // Setup the vertex array
    float* v1 = &vertexArray[0]; 
    float* v2 = &vertexArray[3];
    float* v3 = &vertexArray[6];
    float* v4 = &vertexArray[9];
    v1[0] = min.x(); v1[1] = min.y(); v1[2] = 0.0f;
    v2[0] = max.x(); v2[1] = min.y(); v2[2] = 0.0f;
    v3[0] = max.x(); v3[1] = max.y(); v3[2] = 0.0f;
    v4[0] = min.x(); v4[1] = max.y(); v4[2] = 0.0f;

    if (m_drawBackground)
    {
        if (software)
        {
#ifndef CVF_OPENGL_ES
            glColor4fv(m_backgroundColor.ptr());
            glBegin(GL_TRIANGLE_FAN);
            glVertex3fv(v1);
            glVertex3fv(v2);
            glVertex3fv(v3);
            glVertex3fv(v4);
            glEnd();
#endif
        }
        else
        {
            // Draw background
            UniformFloat backgroundColor("u_color", Color4f(m_backgroundColor));
            backgroundShader->applyUniform(oglContext, backgroundColor);
            glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
        }
    }

    if (m_drawBorder)
    {
        if (software)
        {
#ifndef CVF_OPENGL_ES
            glColor3fv(m_borderColor.ptr());
            glBegin(GL_LINE_LOOP);
            glVertex3fv(v1);
            glVertex3fv(v2);
            glVertex3fv(v3);
            glVertex3fv(v4);
            glEnd();
#endif
        }
        else
        {
            UniformFloat borderColor("u_color", Color4f(m_borderColor));
            backgroundShader->applyUniform(oglContext, borderColor);

            // Draw border
            glDrawArrays(GL_LINE_LOOP, 0, 4);
        }
    }
}
Exemple #4
0
void
migrate_to_level(struct monst *mtmp, xchar tolev,       /* destination level */
                 xchar xyloc,   /* MIGR_xxx destination xy location: */
                 coord * cc)
{       /* optional destination coordinates */
    struct obj *obj;
    d_level new_lev;
    xchar xyflags;
    int num_segs = 0;   /* count of worm segments */

    if (mtmp->isshk)
        set_residency(mtmp, TRUE);

    if (mtmp->wormno) {
        int cnt;

        /* **** NOTE: worm is truncated to # segs = max wormno size **** */
        cnt = count_wsegs(mtmp);
        num_segs = min(cnt, MAX_NUM_WORMS - 1);
        wormgone(mtmp);
    }

    /* set minvent's obj->no_charge to 0 */
    for (obj = mtmp->minvent; obj; obj = obj->nobj) {
        if (Has_contents(obj))
            picked_container(obj);      /* does the right thing */
        obj->no_charge = 0;
    }

    if (mtmp->mleashed) {
        mtmp->mtame--;
        m_unleash(mtmp, TRUE);
    }
    relmon(mtmp);
    mtmp->nmon = migrating_mons;
    migrating_mons = mtmp;
    if (mtmp->dlevel == level)
        newsym(mtmp->mx, mtmp->my);

    /* The dlevel pointer is meaningless for a migrating monster. Set it to NULL
       so that any uses of it are detected quickly via the resulting
       segfault. */
    mtmp->dlevel = NULL;

    new_lev.dnum = ledger_to_dnum((xchar) tolev);
    new_lev.dlevel = ledger_to_dlev((xchar) tolev);

    /* set migration data */
    xyflags = (depth(&new_lev) < depth(&u.uz)); /* 1 => up */
    if (In_W_tower(mtmp->mx, mtmp->my, &u.uz))
        xyflags |= 2;
    mtmp->wormno = num_segs;
    mtmp->mlstmv = moves;
    mtmp->xlocale = cc ? cc->x : mtmp->mx;
    mtmp->ylocale = cc ? cc->y : mtmp->my;
    mtmp->xyloc = xyloc;
    mtmp->xyflags = xyflags;
    mtmp->mux = new_lev.dnum;
    mtmp->muy = new_lev.dlevel;
    mtmp->mx = COLNO;
    mtmp->my = ROWNO;    /* this implies migration */
}
Exemple #5
0
/* ==================================== */
int32_t lfiltreordre(struct xvimage *f, struct xvimage *m, int32_t xc, int32_t yc, double r)
/* r : rang ramene a une echelle 0..1 (ex: 0.5 -> filtre median) */
/* m : masque representant l'element structurant */
/* xc, yc : coordonnees du "centre" de l'element structurant */
/* ==================================== */
{
  int32_t rang;
  int32_t x;                       /* index muet de pixel */
  int32_t y;                       /* index muet (generalement un voisin de x) */
  register int32_t i, j;                    /* index muet */
  register int32_t k, l;                    /* index muet */
  int32_t rs = rowsize(f);         /* taille ligne */
  int32_t cs = colsize(f);         /* taille colonne */
  int32_t N = rs * cs;             /* taille image */
  int32_t rsm = rowsize(m);        /* taille ligne masque */
  int32_t csm = colsize(m);        /* taille colonne masque */
  int32_t Nm = rsm * csm;
  uint8_t *M = UCHARDATA(m);
  uint8_t *F = UCHARDATA(f);
  uint8_t *H;                    /* image de travail */
  int32_t nptb;                    /* nombre de points de l'e.s. */
  int32_t *tab_es_x;               /* liste des coord. x des points de l'e.s. */
  int32_t *tab_es_y;               /* liste des coord. y des points de l'e.s. */
  uint8_t *tab_es_val;   /* liste des valeurs des points de l'e.s. */
  int32_t c;

  if (depth(f) != 1) 
  {
    fprintf(stderr, "lfiltreordre: cette version ne traite pas les images volumiques\n");
    exit(0);
  }

  H = (uint8_t *)calloc(1,N*sizeof(char));
  if (H == NULL)
  {  
     fprintf(stderr,"lfiltreordre() : malloc failed for H\n");
     return(0);
  }

  for (x = 0; x < N; x++) H[x] = F[x];

  nptb = 0;
  for (i = 0; i < Nm; i += 1)
    if (M[i])
      nptb += 1;

  rang = (int32_t)((double)(nptb - 1) * r);
#ifdef VERBOSE
  printf("r = %g ; nptb = %d ; rang = %d\n", r, nptb, rang);
#endif
  tab_es_x = (int32_t *)calloc(1,nptb * sizeof(int32_t));
  tab_es_y = (int32_t *)calloc(1,nptb * sizeof(int32_t));
  tab_es_val = (uint8_t *)calloc(1,nptb * sizeof(char));
  if ((tab_es_x == NULL) || (tab_es_y == NULL) || (tab_es_val == NULL))
  {  
     fprintf(stderr,"lfiltreordre() : malloc failed for tab_es\n");
     return(0);
  }

  k = 0;
  for (j = 0; j < csm; j += 1)
    for (i = 0; i < rsm; i += 1)
      if (M[j * rsm + i])
      {
         tab_es_x[k] = i;
         tab_es_y[k] = j;
         k += 1;
      }

  for (y = 0; y < cs; y++)
  for (x = 0; x < rs; x++)
  {
    for (c = 0; c < nptb ; c += 1)
    {
      l = y + tab_es_y[c] - yc;
      k = x + tab_es_x[c] - xc; 
      if ((l >= 0) && (l < cs) && (k >= 0) && (k < rs))
        tab_es_val[c] = H[l * rs + k];
      else
        tab_es_val[c] = 0;
    }
    F[y * rs + x] = lfiltreordre_SelectionStochastique(tab_es_val, 0, nptb - 1, rang);
  }

  free(H);
  free(tab_es_x);
  free(tab_es_y);
  free(tab_es_val);
  return 1;
} /* lfiltreordre() */
Exemple #6
0
 int depth(TreeNode *root) {
     if (root == NULL) return 0;
     return max(depth(root->left), depth(root->right)) + 1;
 }
Exemple #7
0
 double volume() const { return width() * height() * depth(); }
void ghack_status_window_update_stats()
{
    char buf[BUFSZ];
    gchar *buf1;
    const char* hung;
    const char* enc;
    static int firstTime=TRUE;
#ifdef GOLDOBJ
    long umoney;
#endif

    /* First, fill in the player name and the dungeon level */
    strcpy(buf, plname);
    if ('a' <= buf[0] && buf[0] <= 'z') buf[0] += 'A'-'a';
    strcat(buf, " the ");
    if (u.mtimedone) {
        char mname[BUFSZ];
        int k = 0;

        strcpy(mname, mons[u.umonnum].mname);
        while(mname[k] != 0) {
            if ((k == 0 || (k > 0 && mname[k-1] == ' '))
             && 'a' <= mname[k] && mname[k] <= 'z')
            {
                mname[k] += 'A' - 'a';
            }
            k++;
        }
        strcat(buf, mname);
    } else {
        strcat(buf, rank_of(u.ulevel, pl_character[0], flags.female));
    }
    gtk_label_get( GTK_LABEL( titleLabel), &buf1);
    if (strcmp( buf1, buf) != 0 && firstTime==FALSE) {
	/* Ok, this changed so add it to the highlighing list */
	ghack_highlight_widget( titleLabel, bigStyle, bigGreenStyle);
    }
    gtk_label_set( GTK_LABEL( titleLabel), buf);


    if (In_endgame(&u.uz)) {
        strcpy(buf, (Is_astralevel(&u.uz) ? "Astral Plane":"End Game"));
    } else {
        sprintf(buf, "%s, level %d", dungeons[u.uz.dnum].dname, depth(&u.uz));
    }
    if (lastDepth > depth(&u.uz) && firstTime==FALSE) {
	/* Ok, this changed so add it to the highlighing list */
	ghack_highlight_widget( dgnLevelLabel, bigStyle, bigRedStyle);
    }
    else if (lastDepth < depth(&u.uz) && firstTime==FALSE) {
	/* Ok, this changed so add it to the highlighing list */
	ghack_highlight_widget( dgnLevelLabel, bigStyle, bigGreenStyle);
    }
    lastDepth = depth(&u.uz);
    gtk_label_set( GTK_LABEL( dgnLevelLabel), buf);

    /* Next, fill in the player's stats */
    if (ACURR(A_STR) > 118) {
        sprintf(buf,"STR:%d",ACURR(A_STR)-100);
    } else if (ACURR(A_STR)==118) {
        sprintf(buf,"STR:18/**");
    } else if(ACURR(A_STR) > 18) {
        sprintf(buf,"STR:18/%02d",ACURR(A_STR)-18);
    } else {
        sprintf(buf,"STR:%d",ACURR(A_STR));
    }
    if (lastStr < ACURR(A_STR) && firstTime==FALSE) {
	/* Ok, this changed so add it to the highlighing list */
	ghack_highlight_widget( strLabel, normalStyle, greenStyle);
    }
    else if (lastStr > ACURR(A_STR) && firstTime==FALSE) {
	/* Ok, this changed so add it to the highlighing list */
	ghack_highlight_widget( strLabel, normalStyle, redStyle);
    }
    lastStr = ACURR(A_STR);
    gtk_label_set( GTK_LABEL( strLabel), buf);

    sprintf(buf,"INT:%d",ACURR(A_INT));
    if (lastInt < ACURR(A_INT) && firstTime==FALSE) {
	/* Ok, this changed so add it to the highlighing list */
	ghack_highlight_widget( intLabel, normalStyle, greenStyle);
    }
    else if (lastInt > ACURR(A_INT) && firstTime==FALSE) {
	/* Ok, this changed so add it to the highlighing list */
	ghack_highlight_widget( intLabel, normalStyle, redStyle);
    }
    lastInt = ACURR(A_INT);
    gtk_label_set( GTK_LABEL( intLabel), buf);
    
    sprintf(buf,"WIS:%d",ACURR(A_WIS));
    if (lastWis < ACURR(A_WIS) && firstTime==FALSE) {
	/* Ok, this changed so add it to the highlighing list */
	ghack_highlight_widget( wisLabel, normalStyle, greenStyle);
    }
    else if (lastWis > ACURR(A_WIS) && firstTime==FALSE) {
	/* Ok, this changed so add it to the highlighing list */
	ghack_highlight_widget( wisLabel, normalStyle, redStyle);
    }
    lastWis = ACURR(A_WIS);
    gtk_label_set( GTK_LABEL( wisLabel), buf);
    
    sprintf(buf,"DEX:%d",ACURR(A_DEX));
    if (lastDex < ACURR(A_DEX) && firstTime==FALSE) {
	/* Ok, this changed so add it to the highlighing list */
	ghack_highlight_widget( dexLabel, normalStyle, greenStyle);
    }
    else if (lastDex > ACURR(A_DEX) && firstTime==FALSE) {
	/* Ok, this changed so add it to the highlighing list */
	ghack_highlight_widget( dexLabel, normalStyle, redStyle);
    }
    lastDex = ACURR(A_DEX);
    gtk_label_set( GTK_LABEL( dexLabel), buf);
    
    sprintf(buf,"CON:%d",ACURR(A_CON));
    if (lastCon < ACURR(A_CON) && firstTime==FALSE) {
	/* Ok, this changed so add it to the highlighing list */
	ghack_highlight_widget( conLabel, normalStyle, greenStyle);
    }
    else if (lastCon > ACURR(A_CON) && firstTime==FALSE) {
	/* Ok, this changed so add it to the highlighing list */
	ghack_highlight_widget( conLabel, normalStyle, redStyle);
    }
    lastCon = ACURR(A_CON);
    gtk_label_set( GTK_LABEL( conLabel), buf);
    
    sprintf(buf,"CHA:%d",ACURR(A_CHA));
    if (lastCha < ACURR(A_CHA) && firstTime==FALSE) {
	/* Ok, this changed so add it to the highlighing list */
	ghack_highlight_widget( chaLabel, normalStyle, greenStyle);
    }
    else if (lastCha > ACURR(A_CHA) && firstTime==FALSE) {
	/* Ok, this changed so add it to the highlighing list */
	ghack_highlight_widget( chaLabel, normalStyle, redStyle);
    }
    lastCha = ACURR(A_CHA);
    gtk_label_set( GTK_LABEL( chaLabel), buf);
    
    /* Now do the non-pixmaped stats (gold and such) */
#ifndef GOLDOBJ
    sprintf(buf,"Au:%ld", u.ugold);
    if (lastAu < u.ugold && firstTime==FALSE) {
#else
    umoney = money_cnt(invent);
    sprintf(buf,"Au:%ld", umoney);
    if (lastAu < umoney && firstTime==FALSE) {
#endif
	/* Ok, this changed so add it to the highlighing list */
	ghack_highlight_widget( goldLabel, normalStyle, greenStyle);
    }
#ifndef GOLDOBJ
    else if (lastAu > u.ugold && firstTime==FALSE) {
#else
    else if (lastAu > umoney && firstTime==FALSE) {
#endif
	/* Ok, this changed so add it to the highlighing list */
	ghack_highlight_widget( goldLabel, normalStyle, redStyle);
    }
#ifndef GOLDOBJ
    lastAu = u.ugold;
#else
    lastAu = umoney;
#endif
    gtk_label_set( GTK_LABEL( goldLabel), buf);
    
    if (u.mtimedone) {
        /* special case: when polymorphed, show "HD", disable exp */
	sprintf(buf,"HP:%d/%d", ( (u.mh  > 0)? u.mh  : 0), u.mhmax);
	if ((lastHP < u.mh || lastMHP < u.mhmax ) && firstTime==FALSE) {
	    /* Ok, this changed so add it to the highlighing list */
	    ghack_highlight_widget( hpLabel, normalStyle, greenStyle);
	}
	else if ((lastHP > u.mh || lastMHP > u.mhmax ) && firstTime==FALSE) {
	    /* Ok, this changed so add it to the highlighing list */
	    ghack_highlight_widget( hpLabel, normalStyle, redStyle);
	}
	lastHP = u.mh;
	lastMHP = u.mhmax;
    } else {
	sprintf(buf,"HP:%d/%d", ( (u.uhp  > 0)? u.uhp  : 0), u.uhpmax);
	if ((lastHP < u.uhp || lastMHP < u.uhpmax ) && firstTime==FALSE) {
	    /* Ok, this changed so add it to the highlighing list */
	    ghack_highlight_widget( hpLabel, normalStyle, greenStyle);
	}
	else if ((lastHP > u.uhp || lastMHP > u.uhpmax ) && firstTime==FALSE) {
	    /* Ok, this changed so add it to the highlighing list */
	    ghack_highlight_widget( hpLabel, normalStyle, redStyle);
	}
	lastHP = u.uhp;
	lastMHP = u.uhpmax;
    }
    gtk_label_set( GTK_LABEL( hpLabel), buf);
    
    if (u.mtimedone) {
        /* special case: when polymorphed, show "HD", disable exp */
	sprintf(buf,"HD:%d", mons[u.umonnum].mlevel);
	if (lastLevel < mons[u.umonnum].mlevel && firstTime==FALSE) {
	    /* Ok, this changed so add it to the highlighing list */
	    ghack_highlight_widget( levlLabel, normalStyle, greenStyle);
	}
	else if (lastLevel > mons[u.umonnum].mlevel && firstTime==FALSE) {
	    /* Ok, this changed so add it to the highlighing list */
	    ghack_highlight_widget( levlLabel, normalStyle, redStyle);
	}
	lastLevel = mons[u.umonnum].mlevel;
    } else {
	sprintf(buf,"Level:%d", u.ulevel);
	if (lastLevel < u.ulevel && firstTime==FALSE) {
	    /* Ok, this changed so add it to the highlighing list */
	    ghack_highlight_widget( levlLabel, normalStyle, greenStyle);
	}
	else if (lastLevel > u.ulevel && firstTime==FALSE) {
	    /* Ok, this changed so add it to the highlighing list */
	    ghack_highlight_widget( levlLabel, normalStyle, redStyle);
	}
	lastLevel = u.ulevel;
    }
    gtk_label_set( GTK_LABEL( levlLabel), buf);

    sprintf(buf,"Power:%d/%d", u.uen, u.uenmax);
    if ((lastPOW < u.uen || lastMPOW < u.uenmax) && firstTime==FALSE) {
	/* Ok, this changed so add it to the highlighing list */
	ghack_highlight_widget( powLabel, normalStyle, greenStyle);
    }
    if ((lastPOW > u.uen || lastMPOW > u.uenmax) && firstTime==FALSE) {
	/* Ok, this changed so add it to the highlighing list */
	ghack_highlight_widget( powLabel, normalStyle, redStyle);
    }
    lastPOW = u.uen;
    lastMPOW = u.uenmax;
    gtk_label_set( GTK_LABEL( powLabel), buf);
    
    sprintf(buf,"AC:%d", u.uac);
    if (lastAC > u.uac && firstTime==FALSE) {
	/* Ok, this changed so add it to the highlighing list */
	ghack_highlight_widget( acLabel, normalStyle, greenStyle);
    }
    else if (lastAC < u.uac && firstTime==FALSE) {
	/* Ok, this changed so add it to the highlighing list */
	ghack_highlight_widget( acLabel, normalStyle, redStyle);
    }
    lastAC = u.uac;
    gtk_label_set( GTK_LABEL( acLabel), buf);
    
#ifdef EXP_ON_BOTL
    if (flags.showexp) {
	sprintf(buf,"Exp:%ld", u.uexp);
	if (lastExp < u.uexp && firstTime==FALSE) {
	    /* Ok, this changed so add it to the highlighing list */
	    ghack_highlight_widget( expLabel, normalStyle, greenStyle);
	}
	else if (lastExp > u.uexp && firstTime==FALSE) {
	    /* Ok, this changed so add it to the highlighing list */
	    ghack_highlight_widget( expLabel, normalStyle, redStyle);
	}
	lastExp = u.uexp;
	gtk_label_set( GTK_LABEL( expLabel), buf);
   } else
#endif
    {
	gtk_label_set( GTK_LABEL( expLabel), "");
    }

    if (flags.time) {
	sprintf(buf,"Time:%ld", moves);
	gtk_label_set( GTK_LABEL( timeLabel), buf);
    }
    else
	gtk_label_set( GTK_LABEL( timeLabel), "");
#ifdef SCORE_ON_BOTL
    if (flags.showscore) {
	sprintf(buf,"Score:%ld", botl_score());
	gtk_label_set( GTK_LABEL( scoreLabel), buf);
    } else
	gtk_label_set( GTK_LABEL( scoreLabel), "");
#else
    {
	gtk_label_set( GTK_LABEL( scoreLabel), "");
    }
#endif

    /* See if their alignment has changed */
    if (lastAlignment != u.ualign.type) {
	if (firstTime==FALSE) {
	    /* Ok, this changed so add it to the highlighing list */
	    ghack_highlight_widget( alignLabel, normalStyle, redStyle);
	}

	lastAlignment = u.ualign.type;
	/* looks like their alignment has changed -- change out the icon */
	if (u.ualign.type==A_CHAOTIC) {
	    gtk_label_set( GTK_LABEL( alignLabel), "Chaotic");
	    gnome_pixmap_load_xpm_d( GNOME_PIXMAP(alignPix), chaotic_xpm);
	} else if (u.ualign.type==A_NEUTRAL) {
	    gtk_label_set( GTK_LABEL( alignLabel), "Neutral");
	    gnome_pixmap_load_xpm_d( GNOME_PIXMAP(alignPix), neutral_xpm);
	} else {
	    gtk_label_set( GTK_LABEL( alignLabel), "Lawful");
	    gnome_pixmap_load_xpm_d( GNOME_PIXMAP(alignPix), lawful_xpm);
	}
    }
    
    hung=uclockwork ? ca_hu_stat[u.uhs] : hu_stat[u.uhs];
    if (lastHungr != u.uhs) {
	if (firstTime==FALSE) {
	    /* Ok, this changed so add it to the highlighing list */
	    ghack_highlight_widget( hungerLabel, normalStyle, redStyle);
	}

	lastHungr = u.uhs;
	if (hung[0]==' ') {
	    gtk_label_set( GTK_LABEL( hungerLabel), "      ");
	    gnome_pixmap_load_xpm_d( GNOME_PIXMAP(hungerPix), nothing_xpm);
	} else 
	  if (u.uhs == 0 /* SATIATED */) {
	    gtk_label_set( GTK_LABEL( hungerLabel), hung);
	    gnome_pixmap_load_xpm_d( GNOME_PIXMAP(hungerPix), satiated_xpm);
	} else {
	    gtk_label_set( GTK_LABEL( hungerLabel), hung);
	    gnome_pixmap_load_xpm_d( GNOME_PIXMAP(hungerPix), hungry_xpm);
	}
    }

    if (lastConf != Confusion) {
	if (firstTime==FALSE) {
	    /* Ok, this changed so add it to the highlighing list */
	    ghack_highlight_widget( confuLabel, normalStyle, redStyle);
	}

	lastConf = Confusion;
	if (Confusion) {
	    gtk_label_set( GTK_LABEL( confuLabel), "Confused");
	    gnome_pixmap_load_xpm_d( GNOME_PIXMAP(confuPix), confused_xpm);
	}
	else { 
	    gtk_label_set( GTK_LABEL( confuLabel), "        ");
	    gnome_pixmap_load_xpm_d( GNOME_PIXMAP(confuPix), nothing_xpm);
	}
    }

    if (lastBlind != Blind) {
	if (firstTime==FALSE) {
	    /* Ok, this changed so add it to the highlighing list */
	    ghack_highlight_widget( blindLabel, normalStyle, redStyle);
	}

	lastBlind = Blind;
	if (Blind) {
	    gtk_label_set( GTK_LABEL( blindLabel), "Blind");
	    gnome_pixmap_load_xpm_d( GNOME_PIXMAP(blindPix), blind_xpm);
	}
	else { 
	    gtk_label_set( GTK_LABEL( blindLabel), "     ");
	    gnome_pixmap_load_xpm_d( GNOME_PIXMAP(blindPix), nothing_xpm);
	}
    }
    if (lastStun != Stunned) {
	if (firstTime==FALSE) {
	    /* Ok, this changed so add it to the highlighing list */
	    ghack_highlight_widget( stunLabel, normalStyle, redStyle);
	}

	lastStun = Stunned;
	if (Stunned) {
	    gtk_label_set( GTK_LABEL( stunLabel), "Stun");
	    gnome_pixmap_load_xpm_d( GNOME_PIXMAP(stunPix), stunned_xpm);
	}
	else { 
	    gtk_label_set( GTK_LABEL( stunLabel), "    ");
	    gnome_pixmap_load_xpm_d( GNOME_PIXMAP(stunPix), nothing_xpm);
	}
    }
    
    if (lastHalu != Hallucination) {
	if (firstTime==FALSE) {
	    /* Ok, this changed so add it to the highlighing list */
	    ghack_highlight_widget( halluLabel, normalStyle, redStyle);
	}

	lastHalu = Hallucination;
	if (Hallucination) {
	    gtk_label_set( GTK_LABEL( halluLabel), "Hallu");
	    gnome_pixmap_load_xpm_d( GNOME_PIXMAP(halluPix), hallu_xpm);
	}
	else { 
	    gtk_label_set( GTK_LABEL( halluLabel), "     ");
	    gnome_pixmap_load_xpm_d( GNOME_PIXMAP(halluPix), nothing_xpm);
	}
    }

    if (lastSick != Sick) {
	if (firstTime==FALSE) {
	    /* Ok, this changed so add it to the highlighing list */
	    ghack_highlight_widget( sickLabel, normalStyle, redStyle);
	}

	lastSick = Sick;
	if (Sick) {
	    if (u.usick_type & SICK_VOMITABLE) {
		gtk_label_set( GTK_LABEL( sickLabel), "FoodPois");
		gnome_pixmap_load_xpm_d( GNOME_PIXMAP(sickPix), sick_fp_xpm);
	    } else if (u.usick_type & SICK_NONVOMITABLE) {
		gtk_label_set( GTK_LABEL( sickLabel), "Ill");
		gnome_pixmap_load_xpm_d( GNOME_PIXMAP(sickPix), sick_il_xpm);
	    } else {
		gtk_label_set( GTK_LABEL( sickLabel), "FoodPois");
		gnome_pixmap_load_xpm_d( GNOME_PIXMAP(sickPix), sick_fp_xpm);
	    }
	} else {
	    gtk_label_set( GTK_LABEL( sickLabel), "        ");
	    gnome_pixmap_load_xpm_d( GNOME_PIXMAP(sickPix), nothing_xpm);
	}
    }

    enc=enc_stat[near_capacity()];
    if (lastEncumb != near_capacity()) {
	if (firstTime==FALSE) {
	    /* Ok, this changed so add it to the highlighing list */
	    ghack_highlight_widget( encumbLabel, normalStyle, redStyle);
	}

	lastEncumb = near_capacity();
	switch ( lastEncumb ) {
	    case 0:
		gtk_label_set( GTK_LABEL( encumbLabel), "        ");
		gnome_pixmap_load_xpm_d( GNOME_PIXMAP(encumbPix), nothing_xpm);
		break;
	    case 1:
		gtk_label_set( GTK_LABEL( encumbLabel), enc);
		gnome_pixmap_load_xpm_d( GNOME_PIXMAP(encumbPix), slt_enc_xpm);
		break;
	    case 2:
		gtk_label_set( GTK_LABEL( encumbLabel), enc);
		gnome_pixmap_load_xpm_d( GNOME_PIXMAP(encumbPix), mod_enc_xpm);
		break;
	    case 3:
		gtk_label_set( GTK_LABEL( encumbLabel), enc);
		gnome_pixmap_load_xpm_d( GNOME_PIXMAP(encumbPix), hvy_enc_xpm);
		break;
	    case 4:
		gtk_label_set( GTK_LABEL( encumbLabel), enc);
		gnome_pixmap_load_xpm_d( GNOME_PIXMAP(encumbPix), ext_enc_xpm);
		break;
	    case 5:
		gtk_label_set( GTK_LABEL( encumbLabel), enc);
		gnome_pixmap_load_xpm_d( GNOME_PIXMAP(encumbPix), ovr_enc_xpm);
	}
    }
    firstTime=FALSE;
}

static void ghack_fade_highlighting()
{
    GList *item;
    Highlight *highlt;

    /* Remove any items from the queue if their time is up */
    for (item = g_list_first( s_HighLightList) ; item ; ) {
	highlt = (Highlight*) item->data;
	if (highlt) {
	    if ( highlt->nTurnsLeft <= 0) {
		gtk_widget_set_style(  GTK_WIDGET( highlt->widget), 
			highlt->oldStyle);
		s_HighLightList = g_list_remove_link(s_HighLightList, item);
		g_free( highlt);
		g_list_free_1( item);
		item = g_list_first( s_HighLightList);
		continue;
	    } else
		(highlt->nTurnsLeft)--;
	}
	if (item)
	    item=item->next;
	else
	    break;
    }
}
Exemple #9
0
void
moveloop()
{
#if defined(MICRO) || defined(WIN32)
    char ch;
    int abort_lev;
#endif
    int moveamt = 0, wtcap = 0, change = 0;
    boolean didmove = FALSE, monscanmove = FALSE;

    flags.moonphase = phase_of_the_moon();
    if(flags.moonphase == FULL_MOON) {
	You("are lucky!  Full moon tonight.");
	change_luck(1);
    } else if(flags.moonphase == NEW_MOON) {
	pline("Be careful!  New moon tonight.");
    }
    flags.friday13 = friday_13th();
    if (flags.friday13) {
	pline("Watch out!  Bad things can happen on Friday the 13th.");
	change_luck(-1);
    }
    /* KMH -- February 2 */
    flags.groundhogday = groundhog_day();
    if (flags.groundhogday)
	pline("Happy Groundhog Day!");

    initrack();


    /* Note:  these initializers don't do anything except guarantee that
	    we're linked properly.
    */
    decl_init();
    monst_init();
    monstr_init();	/* monster strengths */
    objects_init();

#ifdef WIZARD
    if (wizard) add_debug_extended_commands();
#endif

    (void) encumber_msg(); /* in case they auto-picked up something */
    if (defer_see_monsters) {
	defer_see_monsters = FALSE;
	see_monsters();
    }

    u.uz0.dlevel = u.uz.dlevel;
    youmonst.movement = NORMAL_SPEED;	/* give the hero some movement points */

    for(;;) {
	get_nh_event();
#ifdef POSITIONBAR
	do_positionbar();
#endif

	didmove = flags.move;
	if(didmove) {
	    /* actual time passed */
	    youmonst.movement -= NORMAL_SPEED;

	    do { /* hero can't move this turn loop */
		wtcap = encumber_msg();

		flags.mon_moving = TRUE;
		do {
		    monscanmove = movemon();
		    if (youmonst.movement > NORMAL_SPEED)
			break;	/* it's now your turn */
		} while (monscanmove);
		flags.mon_moving = FALSE;

		if (!monscanmove && youmonst.movement < NORMAL_SPEED) {
		    /* both you and the monsters are out of steam this round */
		    /* set up for a new turn */
		    struct monst *mtmp;
		    mcalcdistress();	/* adjust monsters' trap, blind, etc */

		    /* reallocate movement rations to monsters */
		    for (mtmp = fmon; mtmp; mtmp = mtmp->nmon)
			mtmp->movement += mcalcmove(mtmp);

		    if(!rn2(u.uevent.udemigod ? 25 :
			    (depth(&u.uz) > depth(&stronghold_level)) ? 50 : 70))
			(void) makemon((struct permonst *)0, 0, 0, NO_MM_FLAGS);

		    /* calculate how much time passed. */
#ifdef STEED
		    if (u.usteed && u.umoved) {
			/* your speed doesn't augment steed's speed */
			moveamt = mcalcmove(u.usteed);
		    } else
#endif
		    {
			moveamt = youmonst.data->mmove;

			if (Very_fast) {	/* speed boots or potion */
			    /* average movement is 1.67 times normal */
			    moveamt += NORMAL_SPEED / 2;
			    if (rn2(3) == 0) moveamt += NORMAL_SPEED / 2;
			} else if (Fast) {
			    /* average movement is 1.33 times normal */
			    if (rn2(3) != 0) moveamt += NORMAL_SPEED / 2;
			}
			if (tech_inuse(T_BLINK)) { /* TECH: Blinking! */
			    /* Case    Average  Variance
			     * -------------------------
			     * Normal    12         0
			     * Fast      16        12
			     * V fast    20        12
			     * Blinking  24        12
			     * F & B     28        18
			     * V F & B   30        18
			     */
			    moveamt += NORMAL_SPEED * 2 / 3;
			    if (rn2(3) == 0) moveamt += NORMAL_SPEED / 2;
			}
		    }

		    switch (wtcap) {
			case UNENCUMBERED: break;
			case SLT_ENCUMBER: moveamt -= (moveamt / 4); break;
			case MOD_ENCUMBER: moveamt -= (moveamt / 2); break;
			case HVY_ENCUMBER: moveamt -= ((moveamt * 3) / 4); break;
			case EXT_ENCUMBER: moveamt -= ((moveamt * 7) / 8); break;
			default: break;
		    }

		    youmonst.movement += moveamt;
		    if (youmonst.movement < 0) youmonst.movement = 0;
		    settrack();

		    monstermoves++;
		    moves++;

		    /********************************/
		    /* once-per-turn things go here */
		    /********************************/

		    if (flags.bypasses) clear_bypasses();
		    if(Glib) glibr();
		    nh_timeout();
		    run_regions();

#ifdef DUNGEON_GROWTH
		    dgn_growths(TRUE, TRUE);
#endif

		    if (u.ublesscnt)  u.ublesscnt--;
		    
		    if(flags.time && !flags.run)
			flags.botl = 1;

		    /* One possible result of prayer is healing.  Whether or
		     * not you get healed depends on your current hit points.
		     * If you are allowed to regenerate during the prayer, the
		     * end-of-prayer calculation messes up on this.
		     * Another possible result is rehumanization, which requires
		     * that encumbrance and movement rate be recalculated.
		     */
		    if (u.uinvulnerable) {
			/* for the moment at least, you're in tiptop shape */
			wtcap = UNENCUMBERED;
		    } else if (Upolyd && youmonst.data->mlet == S_EEL && !is_pool(u.ux,u.uy) && !Is_waterlevel(&u.uz)) {
			if (u.mh > 1) {
			    u.mh--;
			    flags.botl = 1;
			} else if (u.mh < 1)
			    rehumanize();
		    } else if (Upolyd && u.mh < u.mhmax) {
			if (u.mh < 1)
			    rehumanize();
			else if (Regeneration ||
				    (wtcap < MOD_ENCUMBER && !(moves%20))) {
			    flags.botl = 1;
			    u.mh++;
			}
		    } else if (u.uhp < u.uhpmax &&
			 (wtcap < MOD_ENCUMBER || !u.umoved || Regeneration)) {
/*
 * KMH, balance patch -- New regeneration code
 * Healthstones have been added, which alter your effective
 * experience level and constitution (-2 cursed, +1 uncursed,
 * +2 blessed) for the basis of regeneration calculations.
 */

 			int efflev = u.ulevel + u.uhealbonus;
 			int effcon = ACURR(A_CON) + u.uhealbonus;
			int heal = 1;


			if (efflev > 9 && !(moves % 3)) {
			    if (effcon <= 12) {
				heal = 1;
			    } else {
				heal = rnd(effcon);
  				if (heal > efflev-9) heal = efflev-9;
			    }
			    flags.botl = 1;
			    u.uhp += heal;
			    if(u.uhp > u.uhpmax)
				u.uhp = u.uhpmax;
			} else if (Regeneration ||
			     (efflev <= 9 &&
			      !(moves % ((MAXULEV+12) / (u.ulevel+2) + 1)))) {
			    flags.botl = 1;
			    u.uhp++;
			}
		    }

		    if (!u.uinvulnerable && u.uen > 0 && u.uhp < u.uhpmax &&
			    tech_inuse(T_CHI_HEALING)) {
			u.uen--;
			u.uhp++;
			flags.botl = 1;
		    }

		    /* moving around while encumbered is hard work */
		    if (wtcap > MOD_ENCUMBER && u.umoved) {
			if(!(wtcap < EXT_ENCUMBER ? moves%30 : moves%10)) {
			    if (Upolyd && u.mh > 1) {
				u.mh--;
			    } else if (!Upolyd && u.uhp > 1) {
				u.uhp--;
			    } else {
				You("pass out from exertion!");
				exercise(A_CON, FALSE);
				fall_asleep(-10, FALSE);
			    }
			}
		    }

		    
		    /* KMH -- OK to regenerate if you don't move */
		    if ((u.uen < u.uenmax) && (Energy_regeneration ||
				((wtcap < MOD_ENCUMBER || !flags.mv) &&
				(!(moves%((MAXULEV + 15 - u.ulevel) *                                    
				(Role_if(PM_WIZARD) ? 3 : 4) / 6)))))) {
			u.uen += rn1((int)(ACURR(A_WIS) + ACURR(A_INT)) / 15 + 1,1);
#ifdef WIZ_PATCH_DEBUG
                pline("mana was = %d now = %d",temp,u.uen);
#endif

			if (u.uen > u.uenmax)  u.uen = u.uenmax;
			flags.botl = 1;
		    }

		    if(!u.uinvulnerable) {
			if(Teleportation && !rn2(85)) {
			    xchar old_ux = u.ux, old_uy = u.uy;
			    tele();
			    if (u.ux != old_ux || u.uy != old_uy) {
				if (!next_to_u()) {
				    check_leash(&youmonst, old_ux, old_uy, TRUE);
				}
#ifdef REDO
				/* clear doagain keystrokes */
				pushch(0);
				savech(0);
#endif
			    }
			}
			long ch = (80 - (40 * night())) / 2 * 
					 (Race_if(PM_HUMAN_WEREWOLF) ? 
					  u.ulevel * u.ulevel :
					  2);
			ch = (ch > LARGEST_INT) ? LARGEST_INT : ch;
			/* delayed change may not be valid anymore */
			if ((change == 1 && !Polymorph) ||
			    (change == 2 && u.ulycn == NON_PM))
			    change = 0;
			if(Polymorph && !rn2(100))
			    change = 1;
			else if (u.ulycn >= LOW_PM && !Upolyd &&
				 !rn2((int)ch))
			    change = 2;
			if (change && !Unchanging) {
			    if (multi >= 0) {
				if (occupation)
				    stop_occupation();
				else
				    nomul(0);
				if (change == 1) polyself(FALSE);
				else you_were();
				change = 0;
			    }
			}
		}	/* !u.uinvulnerable */

		    if(Searching && multi >= 0) (void) dosearch0(1);
		    dosounds();
		    do_storms();
		    gethungry();
		    age_spells();
		    exerchk();
		    invault();
		    if (u.uhave.amulet) amulet();
		if (!rn2(40+(int)(ACURR(A_DEX)*3))) u_wipe_engr(rnd(3));
		    if (u.uevent.udemigod && !u.uinvulnerable) {
			if (u.udg_cnt) u.udg_cnt--;
			if (!u.udg_cnt) {
			    intervene();
			    u.udg_cnt = rn1(200, 50);
			}
		    }
		    restore_attrib();

		    /* underwater and waterlevel vision are done here */
		    if (Is_waterlevel(&u.uz))
			movebubbles();
		    else if (Underwater)
			under_water(0);
		    /* vision while buried done here */
		    else if (u.uburied) under_ground(0);

		    /* when immobile, count is in turns */
		    if(multi < 0) {
			if (++multi == 0) {	/* finished yet? */
			    unmul((char *)0);
			    /* if unmul caused a level change, take it now */
			    if (u.utotype) deferred_goto();
			}
		    }
		}
	    } while (youmonst.movement<NORMAL_SPEED); /* hero can't move loop */

	    /******************************************/
	    /* once-per-hero-took-time things go here */
	    /******************************************/


	} /* actual time passed */

	/****************************************/
	/* once-per-player-input things go here */
	/****************************************/

	find_ac();
	if(!flags.mv || Blind) {
	    /* redo monsters if hallu or wearing a helm of telepathy */
	    if (Hallucination) {	/* update screen randomly */
		see_monsters();
		see_objects();
		see_traps();
		if (u.uswallow) swallowed(0);
	    } else if (Unblind_telepat) {
		see_monsters();
	    } else if (Warning || Warn_of_mon)
	     	see_monsters();

	    if (vision_full_recalc) vision_recalc(0);	/* vision! */
	}
	if(flags.botl || flags.botlx) bot();

	flags.move = 1;

	if(multi >= 0 && occupation) {
#if defined(MICRO) || defined(WIN32)
	    abort_lev = 0;
	    if (kbhit()) {
		if ((ch = Getchar()) == ABORT)
		    abort_lev++;
# ifdef REDO
		else
		    pushch(ch);
# endif /* REDO */
	    }
	    if (!abort_lev && (*occupation)() == 0)
#else
	    if ((*occupation)() == 0)
#endif
		occupation = 0;
	    if(
#if defined(MICRO) || defined(WIN32)
		   abort_lev ||
#endif
		   monster_nearby()) {
		stop_occupation();
		reset_eat();
	    }
#if defined(MICRO) || defined(WIN32)
	    if (!(++occtime % 7))
		display_nhwindow(WIN_MAP, FALSE);
#endif
	    continue;
	}

	if ((u.uhave.amulet || Clairvoyant) &&
	    !In_endgame(&u.uz) && !BClairvoyant &&
	    !(moves % 15) && !rn2(2))
		do_vicinity_map();

	if(u.utrap && u.utraptype == TT_LAVA) {
	    if(!is_lava(u.ux,u.uy))
		u.utrap = 0;
	    else if (!u.uinvulnerable) {
		u.utrap -= 1<<8;
		if(u.utrap < 1<<8) {
		    killer_format = KILLED_BY;
		    killer = "molten lava";
		    You("sink below the surface and die.");
		    done(DISSOLVED);
		} else if(didmove && !u.umoved) {
		    Norep("You sink deeper into the lava.");
		    u.utrap += rnd(4);
		}
	    }
	}

#ifdef WIZARD
	if (iflags.sanity_check)
	    sanity_check();
#endif

#ifdef CLIPPING
	/* just before rhack */
	cliparound(u.ux, u.uy);
#endif

	u.umoved = FALSE;

	if (multi > 0) {
	    lookaround();
	    if (!multi) {
		/* lookaround may clear multi */
		flags.move = 0;
		if (flags.time) flags.botl = 1;
		continue;
	    }
	    if (flags.mv) {
		if(multi < COLNO && !--multi)
		    flags.travel = iflags.travel1 = flags.mv = flags.run = 0;
		domove();
	    } else {
		--multi;
		rhack(save_cm);
	    }
	} else if (multi == 0) {
#ifdef MAIL
	    ckmailstatus();
#endif
	    rhack((char *)0);
	}
	if (u.utotype)		/* change dungeon level */
	    deferred_goto();	/* after rhack() */
	/* !flags.move here: multiple movement command stopped */
	else if (flags.time && (!flags.move || !flags.mv))
	    flags.botl = 1;

	if (vision_full_recalc) vision_recalc(0);	/* vision! */
	/* when running in non-tport mode, this gets done through domove() */
	if ((!flags.run || iflags.runmode == RUN_TPORT) &&
		(multi && (!flags.travel ? !(multi % 7) : !(moves % 7L)))) {
	    if (flags.time && flags.run) flags.botl = 1;
	    display_nhwindow(WIN_MAP, FALSE);
	}
    }
}
Exemple #10
0
	virtual int32_t priority() const { return layer_ * 1000 + static_cast<int32_t>(depth() * 1000.0f); }
Exemple #11
0
levelprint(tree*t)
{
	int i;
	for(i=0;i<=depth(t);i++)
		levorder(t,i);
}
Exemple #12
0
/* ==================================== */
int32_t lminima(
        struct xvimage *image,
        char* str_connexity
  )
/* ==================================== */
{
  int32_t nblabels, connex, i;
//  struct xvimage * image;
  struct xvimage * result;
  uint8_t * I;
  int32_t * IL;
  int32_t N;
  int32_t * R;
  
  N = rowsize(image) * colsize(image) * depth(image);

  if (str_connexity[0] == 'b') {
    connex = atoi(str_connexity+1);
  } else 
    connex = atoi(str_connexity);

  result = allocimage(NULL, rowsize(image), colsize(image), depth(image), VFF_TYP_4_BYTE);
  if (result == NULL)
  {   
    fprintf(stderr, "allocimage failed\n");
    exit(1);
  }
  R = SLONGDATA(result);

  if ((connex == 0) && strcmp(str_connexity, "b0") && strcmp(str_connexity, "b1"))
  {
    if (datatype(image) == VFF_TYP_1_BYTE)
    {   
      uint8_t absmin;
      I = UCHARDATA(image);
      absmin = I[0];
      for (i = 1; i < N; i++) if (I[i] < absmin) absmin = I[i];
      for (i = 0; i < N; i++) if (I[i] == absmin) I[i] = NDG_MAX; else I[i] = NDG_MIN;
    }
    else if (datatype(image) == VFF_TYP_4_BYTE) 
    {   
      int32_t absmin;
      IL = SLONGDATA(image);
      absmin = IL[0];
      for (i = 1; i < N; i++) if (IL[i] < absmin) absmin = IL[i];
      for (i = 0; i < N; i++) if (IL[i] == absmin) IL[i] = (int32_t)NDG_MAX; 
                                             else IL[i] = (int32_t)NDG_MIN;
    }
    else
    {
      fprintf(stderr, "wrong image type\n");
      exit(1);
    }
  }
  else
  {
    if (! llabelextrema(image, connex, LABMIN, result, &nblabels))
    {
      fprintf(stderr, "llabelextrema failed\n");
      exit(1);
    }

#ifdef VERBOSE
    printf("NOMBRE DE MINIMA : %d\n", nblabels-1);
#endif

    if (datatype(image) == VFF_TYP_1_BYTE)
    {   
      I = UCHARDATA(image);
      for (i = 0; i < N; i++)
        if (R[i]) I[i] = NDG_MAX; else I[i] = NDG_MIN;
    }
    else if (datatype(image) == VFF_TYP_4_BYTE) 
    {   
      IL = SLONGDATA(image);
      for (i = 0; i < N; i++)
        if (R[i]) IL[i] = (int32_t)NDG_MAX; else IL[i] = (int32_t)NDG_MIN;
    }
  }
  freeimage(result);

  return 1;
} /* lminima */
 inline int oclMat::ocltype() const
 {
     return CV_MAKE_TYPE(depth(), oclchannels());
 }
Exemple #14
0
int main(int argc, char * argv[])
{
    int width = 640;
    int height = 480;

    Resolution::getInstance(width, height);

    Intrinsics::getInstance(528, 528, 320, 240);

    cv::Mat intrinsicMatrix = cv::Mat(3,3,CV_64F);

    intrinsicMatrix.at<double>(0,0) = Intrinsics::getInstance().fx();
    intrinsicMatrix.at<double>(1,1) = Intrinsics::getInstance().fy();

    intrinsicMatrix.at<double>(0,2) = Intrinsics::getInstance().cx();
    intrinsicMatrix.at<double>(1,2) = Intrinsics::getInstance().cy();

    intrinsicMatrix.at<double>(0,1) =0;
    intrinsicMatrix.at<double>(1,0) =0;

    intrinsicMatrix.at<double>(2,0) =0;
    intrinsicMatrix.at<double>(2,1) =0;
    intrinsicMatrix.at<double>(2,2) =1;

    Bytef * decompressionBuffer = new Bytef[Resolution::getInstance().numPixels() * 2];
    IplImage * deCompImage = 0;

    std::string logFile="/home/lili/Kinect_Logs/2015-11-05.00.klg";
   // assert(pcl::console::parse_argument(argc, argv, "-l", logFile) > 0 && "Please provide a log file");

    RawLogReader logReader(decompressionBuffer,
                           deCompImage,
                           logFile,
                           true);


    cv::Mat1b tmp(height, width);
    cv::Mat3b depthImg(height, width);

    PlaceRecognition placeRecognition(&intrinsicMatrix);

    iSAMInterface iSAM;

    //Keyframes
    KeyframeMap map(true);
    Eigen::Vector3f lastPlaceRecognitionTrans = Eigen::Vector3f::Zero();
    Eigen::Matrix3f lastPlaceRecognitionRot = Eigen::Matrix3f::Identity();
    int64_t lastTime = 0;

    OdometryProvider * odom = 0;


    //int frame_index = 0;

   // uint64_t timestamp;

    /*if(true)
    {
        odom = new FOVISOdometry;
        if(logReader.hasMore())
        {
            logReader.getNext();

            Eigen::Matrix3f Rcurr = Eigen::Matrix3f::Identity();
            Eigen::Vector3f tcurr = Eigen::Vector3f::Zero();

            odom->getIncrementalTransformation(tcurr,
                                               Rcurr,
                                               logReader.timestamp,
                                               (unsigned char *)logReader.deCompImage->imageData,
                                               (unsigned short *)&decompressionBuffer[0]);
        }

    }*/
    //else
   // {
        odom = new DVOdometry;

        if(logReader.hasMore())
        {
            logReader.getNext();

            DVOdometry * dvo = static_cast<DVOdometry *>(odom);

            dvo->firstRun((unsigned char *)logReader.deCompImage->imageData,
                          (unsigned short *)&decompressionBuffer[0]);
        }
    //}

    ofstream fout1("camera_pose_DVOMarch28.txt");
    ofstream fout2("camera_pose_KeyframeMotionMetric0.1March28.txt");
    ofstream fout3("loop_closure_transformationMarch28.txt");
    ofstream fout4("camera_pose_after_optimizationMarch28.txt");
    ofstream fout5("camera_pose_after_optimizationMarch28DVOCov.txt");
    ofstream fout6("camera_pose_after_optimizationMarch28DVOLoopTransCov.txt");

    /*
    pcl::visualization::PCLVisualizer cloudViewer;

    cloudViewer.setBackgroundColor(1, 1, 1);
    cloudViewer.initCameraParameters();
    cloudViewer.addCoordinateSystem(0.1, 0, 0, 0);
    */
    //pcl::visualization::PointCloudColorHandlerRGBField<pcl::PointXYZRGB> color(cloud->makeShared());
    //cloudViewer.addPointCloud<pcl::PointXYZRGB>(cloud->makeShared(), color, "Cloud Viewer");


    int loopClosureCount=0;

    while(logReader.hasMore())
    {
        logReader.getNext();

        cv::Mat3b rgbImg(height, width, (cv::Vec<unsigned char, 3> *)logReader.deCompImage->imageData);

        cv::Mat1w depth(height, width, (unsigned short *)&decompressionBuffer[0]);

        cv::normalize(depth, tmp, 0, 255, cv::NORM_MINMAX, 0);

        cv::cvtColor(tmp, depthImg, CV_GRAY2RGB);

        cv::imshow("RGB", rgbImg);

        cv::imshow("Depth", depthImg);

        char key = cv::waitKey(1);

        if(key == 'q')
        {
            break;
        }
        else if(key == ' ')
        {
            key = cv::waitKey(0);
        }
        if(key == 'q')
        {
            break;
        }

        Eigen::Matrix3f Rcurr = Eigen::Matrix3f::Identity();
        Eigen::Vector3f tcurr = Eigen::Vector3f::Zero();



//        #1
        odom->getIncrementalTransformation(tcurr,
                                          Rcurr,
                                          logReader.timestamp,
                                          (unsigned char *)logReader.deCompImage->imageData,
                                          (unsigned short *)&decompressionBuffer[0]);


       fout1<<tcurr[0]<<" "<<tcurr[1]<<" "<<tcurr[2]<<" "<<Rcurr(0,0)<<" "<<Rcurr(0,1)<<" "<<Rcurr(0,2)<<" "<<Rcurr(1,0)<<" "<<Rcurr(1,1)<<" "<<Rcurr(1,2)<<" "<<Rcurr(2,0)<<" "<<Rcurr(2,1)<<" "<<Rcurr(2,2)<<endl;

        Eigen::Matrix3f Rdelta = Rcurr.inverse() * lastPlaceRecognitionRot;
        Eigen::Vector3f tdelta = tcurr - lastPlaceRecognitionTrans;

        //Eigen::MatrixXd covariance = odom->getCovariance();
         //Eigen::MatrixXd covariance=Eigen::Matrix<double, 6, 6>::Identity()* 1e-3;

        if((Projection::rodrigues2(Rdelta).norm() + tdelta.norm())  >= 0.1)
        {
            Eigen::MatrixXd covariance = odom->getCovariance();
            iSAM.addCameraCameraConstraint(lastTime,
                                           logReader.timestamp,
                                           lastPlaceRecognitionRot,
                                           lastPlaceRecognitionTrans,
                                           Rcurr,
                                           tcurr);
                                           //covariance);

            printCovariance(fout5,  covariance);

            lastTime = logReader.timestamp;

            lastPlaceRecognitionRot = Rcurr;
            lastPlaceRecognitionTrans = tcurr;

            cout<<"before add keyframe"<<endl;

//            #2
            map.addKeyframe((unsigned char *)logReader.deCompImage->imageData,
                            (unsigned short *)&decompressionBuffer[0],
                            Rcurr,
                            tcurr,
                            logReader.timestamp);

           fout2<<tcurr[0]<<" "<<tcurr[1]<<" "<<tcurr[2]<<" "<<Rcurr(0,0)<<" "<<Rcurr(0,1)<<" "<<Rcurr(0,2)<<" "<<Rcurr(1,0)<<" "<<Rcurr(1,1)<<" "<<Rcurr(1,2)<<" "<<Rcurr(2,0)<<" "<<Rcurr(2,1)<<" "<<Rcurr(2,2)<<endl;

           /*
            //Save keyframe
           {
            cv::Mat3b rgbImgKeyframe(height, width, (cv::Vec<unsigned char, 3> *)logReader.deCompImage->imageData);

            cv::Mat1w depthImgKeyframe(height, width, (unsigned short *)&decompressionBuffer[0]);

            //save keyframe depth
            char fileName[1024] = {NULL};
            sprintf(fileName, "keyframe_depth_%06d.png", frame_index);
            cv::imwrite(fileName, depthImgKeyframe);

            //save keyframe rgb

            sprintf(fileName, "keyframe_rgb_%06d.png", frame_index);
            cv::imwrite(fileName, rgbImgKeyframe);
            frame_index ++;

           }
        */

            int64_t matchTime;
            Eigen::Matrix4d transformation;
           // Eigen::MatrixXd cov(6,6);
            //isam::Covariance(0.001 * Eigen::Matrix<double, 6, 6>::Identity()))
            Eigen::MatrixXd cov=0.001 * Eigen::Matrix<double, 6, 6>::Identity();


            cout<<"map.addKeyframe is OK"<<endl;

//            #3
            if(placeRecognition.detectLoop((unsigned char *)logReader.deCompImage->imageData,
                                           (unsigned short *)&decompressionBuffer[0],
                                           logReader.timestamp,
                                           matchTime,
                                           transformation,
                                           cov,
                                           loopClosureCount))
            {

                //printCovariance(fout6,  cov);
               cout<<"logReader.timestamp "<<logReader.timestamp<<endl;
               cout<<"matchTime "<<matchTime<<endl;

               /*
               transformation << -0.2913457145219732, 0.228056050293173, -0.9290361201559172, 2.799184934345601,
                                0.6790194052589797, 0.7333821627861707, -0.03291277242681545, 1.310438143604587,
                                0.673832562222562, -0.6404225489719699, -0.3685222338703895, 6.988973505496276,
                                0, 0, 0, 0.999999999999998;
                */
                /*
              transformation << 0.9998996846969838, 0.003948215234314986, -0.01360265192291004, 0.05847011404293689,
                              -0.004032877285312574, 0.9999726343121815, -0.006202138950136233, 0.04528938486109094,
                                0.01357779229749574, 0.006256374606648019, 0.9998882444218992, 0.02203456132723125,
                                0, 0, 0, 1;
                */
              iSAM.addLoopConstraint(logReader.timestamp, matchTime, transformation);//, cov);
              fout3<<transformation(0,0)<<" "<<transformation(0,1)<<" "<<transformation(0,2)<<" "<<transformation(0,3)<<" "<<transformation(1,0)<<" "<<transformation(1,1)<<" "<<transformation(1,2)<<" "<<transformation(1,3)<<" "<<transformation(2,0)<<" "<<transformation(2,1)<<" "<<transformation(2,2)<<" "<<transformation(2,3)<<" "<<transformation(3,0)<<" "<<transformation(3,1)<<" "<<transformation(3,2)<<" "<<transformation(3,3)<<endl;
              loopClosureCount++;


            }

        }

        if(loopClosureCount>=1)
        {
            break;
        }
    }
    /*
    for(int i=0; i<loopClosureCount;i++)
    {

     iSAM.addLoopConstraint(placeRecognition.loopClosureConstraints.at(i)->time1,
                            placeRecognition.loopClosureConstraints.at(i)->time2,
                            placeRecognition.loopClosureConstraints.at(i)->constraint);

    }*/

    std::vector<std::pair<uint64_t, Eigen::Matrix4f> > posesBefore;
    iSAM.getCameraPoses(posesBefore);

    cout<<"It works good before optimization"<<endl;

//    #4
    double residual =iSAM.optimise();

    cout<<"It works good after optimize and before map.applyPoses"<<endl;

   // map.applyPoses(isam);
    //cout<<"It works good before *cloud=map.getMap and after map.applyPoses(isam)"<<endl;

    /*
    pcl::PointCloud<pcl::PointXYZRGB> *cloud = map.getMap();


     // Write it back to disk under a different name.
	// Another possibility would be "savePCDFileBinary()".
	cout<<"before storing the point cloud map"<<endl;
	pcl::io::savePCDFileASCII ("outputCloudMap03DVODensity005.pcd", *cloud);

    cout << "Saved data points to outputMap.pcd." << std::endl;


    cout<<"copy data into octomap..."<<endl;

    octomap::ColorOcTree tree( 0.05 );

    for (size_t i=0; i<(*cloud).points.size(); i++)
    {
        // 将点云里的点插入到octomap中
        tree.updateNode( octomap::point3d((*cloud).points[i].x, (*cloud).points[i].y, (*cloud).points[i].z), true );
    }

    for (size_t i=0; i<(*cloud).points.size(); i++)
    {
        tree.integrateNodeColor( (*cloud).points[i].x, (*cloud).points[i].y, (*cloud).points[i].z, (*cloud).points[i].r, (*cloud).points[i].g, (*cloud).points[i].b);
    }

    tree.updateInnerOccupancy();
    tree.write("OctomapColorLab03DVODensity005.ot");
    cout<<"please see the done."<<endl;
   */

    //pcl::visualization::PCLVisualizer cloudViewer;

   // cloudViewer.setBackgroundColor(1, 1, 1);
    //cloudViewer.initCameraParameters();
   // cloudViewer.addCoordinateSystem(0.1, 0, 0, 0);

    //pcl::visualization::PointCloudColorHandlerRGBField<pcl::PointXYZRGB> color(cloud->makeShared());
    //cloudViewer.addPointCloud<pcl::PointXYZRGB>(cloud->makeShared(), color, "Cloud Viewer");

    std::vector<std::pair<uint64_t, Eigen::Matrix4f> > newPoseGraph;

    iSAM.getCameraPoses(newPoseGraph);


    /*
    for(unsigned int i = 0; i < newPoseGraph.size(); i++)
    {
       // file << std::setprecision(6) << std::fixed << (double)newPoseGraph.at(i).first / 1000000.0 << " ";

        Eigen::Vector3f trans = newPoseGraph.at(i).second.topRightCorner(3, 1);
        Eigen::Matrix3f rot = newPoseGraph.at(i).second.topLeftCorner(3, 3);

        fout4 << trans(0) << " " << trans(1) << " " << trans(2) << " ";

        Eigen::Quaternionf currentCameraRotation(rot);

        //file << currentCameraRotation.x() << " " << currentCameraRotation.y() << " " << currentCameraRotation.z() << " " << currentCameraRotation.w() << "\n";
    }*/



    for(std::vector<std::pair<uint64_t, Eigen::Matrix4f> >::iterator ite=newPoseGraph.begin(); ite!=newPoseGraph.end(); ite++)
    {
        Eigen::Matrix3f Roptimized;
        Roptimized<<ite->second(0,0), ite->second(0,1), ite->second(0,2),
                    ite->second(1,0), ite->second(1,1), ite->second(1,2),
                    ite->second(2,0), ite->second(2,1), ite->second(2,2);

         Eigen::Quaternionf quatOptimized(Roptimized);

         fout4<<ite->second(0,3)<<" "<<ite->second(1,3)<<" "<<ite->second(2,3)<<" "<<quatOptimized.w()<<" "<<quatOptimized.x()<<" "<<quatOptimized.y()<<" "<<quatOptimized.z()<<endl;

    }

    cout<<"The number of optimized poses"<<newPoseGraph.size()<<endl;


   // drawPoses(poses, cloudViewer, 1.0, 0, 0);
    //drawPoses(posesBefore, cloudViewer, 0, 0, 1.0);







    //cloudViewer.spin();

    delete [] decompressionBuffer;

    return 0;
}
Exemple #15
0
void MainWindow::timerCallback()
{
    int64_t usedMemory = MemoryBuffer::getUsedSystemMemory();
    int64_t totalMemory = MemoryBuffer::getTotalSystemMemory();
    int64_t processMemory = MemoryBuffer::getProcessMemory();

    float usedGB = (usedMemory / (float)1073741824);
    float totalGB = (totalMemory / (float)1073741824);
    
#ifdef __APPLE__
    float processGB = (processMemory / (float)1073741824);
#else
    float processGB = (processMemory / (float)1048576);
#endif
    
    QString memoryInfo = QString::number(usedGB, 'f', 2) + "/" + QString::number(totalGB, 'f', 2) + "GB memory used, " + QString::number(processGB, 'f', 2) + "GB by Logger2";

    memoryStatus->setText(memoryInfo);

    if(!logger)
    {
        if(frameStats.size() >= 15)
        {
            logger = new Logger2(width, height, fps, tcp);

            if(!logger->getOpenNI2Interface()->ok())
            {
                memset(depthImage.bits(), 0, width * height * 3);
                painter->setPen(Qt::red);
                painter->setFont(QFont("Arial", 30));
                painter->drawText(10, 50, "Attempting to start OpenNI2... failed!");
                depthLabel->setPixmap(QPixmap::fromImage(depthImage));

                QMessageBox msgBox;
                msgBox.setText("Sorry, OpenNI2 is having trouble (it's still in beta). Please try running Logger2 again.");
                msgBox.setDetailedText(QString::fromStdString(logger->getOpenNI2Interface()->error()));
                msgBox.exec();
                exit(-1);
            }
            else
            {
                memset(depthImage.bits(), 0, width * height * 3);
                painter->setPen(Qt::green);
                painter->setFont(QFont("Arial", 30));
                painter->drawText(10, 50, "Starting stream...");
                depthLabel->setPixmap(QPixmap::fromImage(depthImage));
            }

            return;
        }
        else
        {
            frameStats.push_back(0);
            return;
        }
    }

    int lastDepth = logger->getOpenNI2Interface()->latestDepthIndex.getValue();

    if(lastDepth == -1)
    {
        return;
    }

    int bufferIndex = lastDepth % OpenNI2Interface::numBuffers;

    if(bufferIndex == lastDrawn)
    {
        return;
    }

    if(lastFrameTime == logger->getOpenNI2Interface()->frameBuffers[bufferIndex].second)
    {
        return;
    }

    memcpy(&depthBuffer[0], logger->getOpenNI2Interface()->frameBuffers[bufferIndex].first.first, width * height * 2);
    
    if(!(tcp && recording))
    {
        memcpy(rgbImage.bits(), logger->getOpenNI2Interface()->frameBuffers[bufferIndex].first.second, width * height * 3);
    }

    cv::Mat1w depth(height, width, (unsigned short *)&depthBuffer[0]);
    normalize(depth, tmp, 0, 255, cv::NORM_MINMAX, 0);

    cv::Mat3b depthImg(height, width, (cv::Vec<unsigned char, 3> *)depthImage.bits());
    cv::cvtColor(tmp, depthImg, CV_GRAY2RGB);

    painter->setPen(recording ? Qt::red : Qt::green);
    painter->setFont(QFont("Arial", 30));
    painter->drawText(10, 50, recording ? (tcp ? "Streaming & Recording" : "Recording") : "Viewing");

    frameStats.push_back(abs(logger->getOpenNI2Interface()->frameBuffers[bufferIndex].second - lastFrameTime));

    if(frameStats.size() > 15)
    {
        frameStats.erase(frameStats.begin());
    }

    int64_t speedSum = 0;

    for(unsigned int i = 0; i < frameStats.size(); i++)
    {
        speedSum += frameStats[i];
    }

    int64_t avgSpeed = (float)speedSum / (float)frameStats.size();

    float fps = 1.0f / ((float)avgSpeed / 1000000.0f);

    fps = floor(fps * 10.0f);

    fps /= 10.0f;

    std::stringstream str;
    str << (int)ceil(fps) << "fps";

    lastFrameTime = logger->getOpenNI2Interface()->frameBuffers[bufferIndex].second;

    painter->setFont(QFont("Arial", 24));

#ifdef __APPLE__
    int offset = 20;
#else
    int offset = 10;
#endif

    painter->drawText(10, height - offset, QString::fromStdString(str.str()));

    if(tcp)
    {
        cv::Mat3b modelImg(height / 4, width / 4);
        cv::Mat3b modelImgBig(height, width, (cv::Vec<unsigned char, 3> *)rgbImage.bits());
        std::string dataStr = comms->tryRecv();
        
        if(dataStr.length())
        {
            std::vector<char> data(dataStr.begin(), dataStr.end());
            modelImg = cv::imdecode(cv::Mat(data), 1);
            cv::Size bigSize(width, height);
            cv::resize(modelImg, modelImgBig, bigSize, 0, 0);
        }
    }

    depthLabel->setPixmap(QPixmap::fromImage(depthImage));
    imageLabel->setPixmap(QPixmap::fromImage(rgbImage));

    if(logger->getMemoryBuffer().memoryFull.getValue())
    {
        assert(recording);
        recordToggle();

        QMessageBox msgBox;
        msgBox.setText("Recording has been automatically stopped to prevent running out of system memory.");
        msgBox.exec();
    }

    std::pair<bool, int64_t> dropping = logger->dropping.getValue();

    if(!tcp && dropping.first)
    {
        assert(recording);
        recordToggle();

        std::stringstream strs;

        strs << "Recording has been automatically stopped. Logging experienced a jump of " << dropping.second / 1000
             << "ms, indicating a drop below 10fps. Please try enabling compression or recording to RAM to prevent this.";

        QMessageBox msgBox;
        msgBox.setText(QString::fromStdString(strs.str()));
        msgBox.exec();
    }
}
Exemple #16
0
static
depth findMaxWidth(const NGHolder &h, const SpecialEdgeFilter &filter,
                   NFAVertex src) {
    if (isLeafNode(src, h.g)) {
        return depth::unreachable();
    }

    if (hasReachableCycle(h, src)) {
        // There's a cycle reachable from this src, so we have inf width.
        return depth::infinity();
    }

    boost::filtered_graph<NFAGraph, SpecialEdgeFilter> g(h.g, filter);

    assert(hasCorrectlyNumberedVertices(h));
    const size_t num = num_vertices(h);
    vector<int> distance(num);
    vector<boost::default_color_type> colors(num);

    auto index_map = get(&NFAGraphVertexProps::index, g);

    // DAG shortest paths with negative edge weights.
    dag_shortest_paths(
        g, src,
        distance_map(make_iterator_property_map(distance.begin(), index_map))
            .weight_map(boost::make_constant_property<NFAEdge>(-1))
            .vertex_index_map(index_map)
            .color_map(make_iterator_property_map(colors.begin(), index_map)));

    depth acceptDepth, acceptEodDepth;
    if (colors.at(NODE_ACCEPT) == boost::white_color) {
        acceptDepth = depth::unreachable();
    } else {
        acceptDepth = -1 * distance.at(NODE_ACCEPT);
    }
    if (colors.at(NODE_ACCEPT_EOD) == boost::white_color) {
        acceptEodDepth = depth::unreachable();
    } else {
        acceptEodDepth = -1 * distance.at(NODE_ACCEPT_EOD);
    }

    depth d;
    if (acceptDepth.is_unreachable()) {
        d = acceptEodDepth;
    } else if (acceptEodDepth.is_unreachable()) {
        d = acceptDepth;
    } else {
        d = max(acceptDepth, acceptEodDepth);
    }

    if (d.is_unreachable()) {
        // If we're actually reachable, we'll have a min width, so we can
        // return infinity in this case.
        if (findMinWidth(h, filter, src).is_reachable()) {
            return depth::infinity();
        }
        return d;
    }

    // Invert sign and subtract one for start transition.
    assert(d.is_finite() && d > depth(0));
    return d - depth(1);
}
Exemple #17
0
int main(void) {
	int i;
	node *t1, *t2, *t3;

	/* recursive_insert() */
	printf("=== Tesing Insert Recursive ===\n");
	t1 = NULL;

	int tree_values[10] = {5, 8, 3, 6, 1, 4, 9, 0, 7, 2};

	for (i=0; i<10; i++) {
		recursive_insert(&t1,tree_values[i]);
	}

	printf("=== Inorder Traversal ===\n");
	print_inorder_traverse(t1);
	printf("\n");


	printf("=== PreOrder Traversal ===\n");
	print_preorder_traverse(t1);
	printf("\n");

	printf("=== PostOrder Traversal ===\n");
	print_postorder_traverse(t1);
	printf("\n");

	node *elem;
	printf("=== Recursive Search ===\n");
	elem = recursive_search(t1, 5);
	printf("%d\n", elem->value);
	printf("%d\n", elem->left->value);
	printf("%d\n", elem->right->value);
	printf("\n");

	printf("=== Copy Tree ===\n");
	t2=copy(t1);
	print_inorder_traverse(t1);
	printf("\n");
	print_inorder_traverse(t2);
	printf("\n");

	printf("=== Depth ===\n");
	int _d = depth(t1);
	printf("%d\n", _d);
	printf("\n");


	printf("=== Num Nodes ===\n");
	int _n = num_nodes(t1);
	printf("%d\n", _n);
	printf("\n");

	printf("=== Destroy ===\n");
	destroy(&t1);
	print_inorder_traverse(t1);
	printf("\n");


	printf("=== Is Identical ===\n");
	t1=NULL;
	t2=NULL;

	for (i=0; i<10; i++) {
		recursive_insert(&t1,tree_values[i]);
		recursive_insert(&t2,tree_values[i]);
	}

	int identical = is_identical(t1, t2);
	if (identical)
		printf("%s\n", "Trees are identical");
	else
		printf("%s\n", "Trees are not identical");
	printf("\n");


	printf("=== Num of Leaves ===\n");
	int leaves = num_leaves(t1);
	printf("%d\n", leaves);
	printf("\n");

}
Exemple #18
0
/* Locks the live log file and writes 'buffer' */
void livelog_write_string(char* buffer)
{
    FILE* livelogfile;
#ifdef FILE_AREAS
    if (lock_file_area(LOGAREA, LIVELOGFILE, 10)) {
#else
    if (lock_file(LIVELOGFILE, SCOREPREFIX, 10)) {
#endif
        if(!(livelogfile = fopen_datafile_area(LOGAREA, LIVELOGFILE, "a", SCOREPREFIX))) {
            pline("Cannot open live log file!");
        } else {
            fprintf(livelogfile, "%s", buffer);
            (void) fclose(livelogfile);
        }
        unlock_file_area(LOGAREA, LIVELOGFILE);
    }
}

static
char *livelog_prefix()
{
    s_level *lev = Is_special(&u.uz);
    snprintf(prefixbuf, STRBUF_LEN,
             "version=%s-%d.%d.%d:"
             "player=%s:turns=%ld:starttime=%ld:"
             "currenttime=%ld:"
             "dnum=%d:dname=%s:dlev=%d:maxlvl=%d:"
             "dlev_name=%s:"
             "hp=%d:maxhp=%d:deaths=%d:"
#ifdef RECORD_REALTIME
             "realtime=%ld:"
#endif
             "conduct=0x%lx:"
             "role=%s:race=%s:"
             "gender=%s:align=%s:"
             "gender0=%s:align0=%s:"
             "explvl=%d:exp=%ld:"
             "elbereths=%ld:"
             "xplevel=%d:" /* XP level */
             "exp=%ld:" /* Experience points */
             "mode=%s:"
             "gold=%ld",
             GAME_SHORT_NAME, VERSION_MAJOR, VERSION_MINOR, PATCHLEVEL,
             plname,
             moves,
             (long)u.ubirthday,
             (long)current_epoch(),
             u.uz.dnum, dungeons[u.uz.dnum].dname, depth(&u.uz), deepest_lev_reached(TRUE),
             lev ? lev->proto : "", /* proto level name if special level */
             u.uhp, u.uhpmax, u.umortality,
#ifdef RECORD_REALTIME
             (long)realtime_data.realtime,
#endif
             encodeconduct(),
             urole.filecode, urace.filecode,
             genders[flags.female].filecode, aligns[1-u.ualign.type].filecode,
             genders[flags.initgend].filecode, aligns[1-u.ualignbase[A_ORIGINAL]].filecode,
             u.ulevel,u.uexp,
             u.uconduct.elbereths,
             u.ulevel, /* XP level */
             (long)u.uexp, /* Experience points */
             (flags.debug ? "debug" : /* mode */
              flags.explore ? "explore" :
              hell_and_hell_mode ? "hah" :
              heaven_or_hell_mode ? "hoh" :
              "normal"),
#ifndef GOLDOBJ
             (u.ugold + hidden_gold())
#else
             (money_cnt(invent) + hidden_gold())
#endif
            );
    return prefixbuf;
}
Exemple #19
0
 bool isBalanced(TreeNode* root) {
     if (root == NULL) return true;
     return abs(depth(root->left) - depth(root->right)) <= 1 &&
         isBalanced(root->left) &&
         isBalanced(root->right);
 }
XnStatus XnFileDevice::HandleIntProperty(const XnChar *strModule, const XnChar *strName, XnUInt64 nValue)
{
	XnStatus nRetVal = XN_STATUS_OK;

	// ignore some properties
	if (strcmp(strModule, XN_MODULE_NAME_DEVICE) == 0 && strcmp(strName, XN_MODULE_PROPERTY_PRIMARY_STREAM) == 0)
	{
		return (XN_STATUS_OK);
	}

	// OpenNI props
	if (strcmp(strName, XN_STREAM_PROPERTY_STATE) == 0)
	{
		nRetVal = m_pNotifications->OnNodeIntPropChanged(m_pNotificationsCookie, strModule, XN_PROP_IS_GENERATING, nValue);
	}
	else if (strcmp(strName, XN_MODULE_PROPERTY_MIRROR) == 0)
	{
		nRetVal = m_pNotifications->OnNodeIntPropChanged(m_pNotificationsCookie, strModule, XN_PROP_MIRROR, nValue);
	}
	else if (strcmp(strName, XN_STREAM_PROPERTY_X_RES) == 0 ||
		strcmp(strName, XN_STREAM_PROPERTY_Y_RES) == 0 ||
		strcmp(strName, XN_STREAM_PROPERTY_FPS) == 0)
	{
		xn::MapGenerator node;
		nRetVal = m_context.GetProductionNodeByName(strModule, node);
		XN_IS_STATUS_OK(nRetVal);

		XnMapOutputMode mode;
		nRetVal = node.GetMapOutputMode(mode);
		XN_IS_STATUS_OK(nRetVal);

		if (strcmp(strName, XN_STREAM_PROPERTY_X_RES) == 0)
		{
			mode.nXRes = (XnUInt32)nValue;
		}
		else if (strcmp(strName, XN_STREAM_PROPERTY_Y_RES) == 0)
		{
			mode.nYRes = (XnUInt32)nValue;
		}
		else if (strcmp(strName, XN_STREAM_PROPERTY_FPS) == 0)
		{
			mode.nFPS = (XnUInt32)nValue;
		}

		// change supported modes to this one
		nRetVal = m_pNotifications->OnNodeIntPropChanged(m_pNotificationsCookie, strModule, XN_PROP_SUPPORTED_MAP_OUTPUT_MODES_COUNT, 1);
		XN_IS_STATUS_OK(nRetVal);

		nRetVal = m_pNotifications->OnNodeGeneralPropChanged(m_pNotificationsCookie, strModule, XN_PROP_SUPPORTED_MAP_OUTPUT_MODES, sizeof(XnMapOutputMode), &mode);
		XN_IS_STATUS_OK(nRetVal);

		// and set actual mode
		nRetVal = m_pNotifications->OnNodeGeneralPropChanged(m_pNotificationsCookie, strModule, XN_PROP_MAP_OUTPUT_MODE, sizeof(mode), &mode);
		XN_IS_STATUS_OK(nRetVal);
	}
	else if (strcmp(strName, XN_STREAM_PROPERTY_OUTPUT_FORMAT) == 0)
	{
		switch (nValue)
		{
		case XN_OUTPUT_FORMAT_SHIFT_VALUES:
		case XN_OUTPUT_FORMAT_DEPTH_VALUES:
		case XN_OUTPUT_FORMAT_GRAYSCALE16:
		case XN_OUTPUT_FORMAT_PCM:
			break;
		case XN_OUTPUT_FORMAT_GRAYSCALE8:
			nRetVal = m_pNotifications->OnNodeIntPropChanged(m_pNotificationsCookie, strModule, XN_PROP_PIXEL_FORMAT, XN_PIXEL_FORMAT_GRAYSCALE_8_BIT);
			break;
		case XN_OUTPUT_FORMAT_RGB24:
			nRetVal = m_pNotifications->OnNodeIntPropChanged(m_pNotificationsCookie, strModule, XN_PROP_PIXEL_FORMAT, XN_PIXEL_FORMAT_RGB24);
			break;
		case XN_OUTPUT_FORMAT_YUV422:
			nRetVal = m_pNotifications->OnNodeIntPropChanged(m_pNotificationsCookie, strModule, XN_PROP_PIXEL_FORMAT, XN_PIXEL_FORMAT_YUV422);
			break;
		default:
			XN_ASSERT(FALSE);
			return XN_STATUS_ERROR;
		}

		XN_IS_STATUS_OK(nRetVal);

		// also set property (we need it for IR compatibility)
		nRetVal = m_pNotifications->OnNodeIntPropChanged(m_pNotificationsCookie, strModule, strName, nValue);
	}
	else if (strcmp(strName, XN_STREAM_PROPERTY_DEVICE_MAX_DEPTH) == 0)
	{
		nRetVal = m_pNotifications->OnNodeIntPropChanged(m_pNotificationsCookie, strModule, XN_PROP_DEVICE_MAX_DEPTH, nValue);
	}
	else if (strcmp(strName, XN_STREAM_PROPERTY_SAMPLE_RATE) == 0 ||
		strcmp(strName, XN_STREAM_PROPERTY_NUMBER_OF_CHANNELS) == 0)
	{
		xn::AudioGenerator node;
		nRetVal = m_context.GetProductionNodeByName(strModule, node);
		XN_IS_STATUS_OK(nRetVal);

		XnWaveOutputMode mode;
		nRetVal = node.GetWaveOutputMode(mode);
		XN_IS_STATUS_OK(nRetVal);

		if (strcmp(strName, XN_STREAM_PROPERTY_SAMPLE_RATE) == 0)
		{
			mode.nSampleRate = (XnUInt32)nValue;
		}
		else if (strcmp(strName, XN_STREAM_PROPERTY_NUMBER_OF_CHANNELS) == 0)
		{
			mode.nChannels = (XnUInt8)nValue;
		}

		// change supported modes to this one
		nRetVal = m_pNotifications->OnNodeIntPropChanged(m_pNotificationsCookie, strModule, XN_PROP_WAVE_SUPPORTED_OUTPUT_MODES_COUNT, 1);
		XN_IS_STATUS_OK(nRetVal);

		nRetVal = m_pNotifications->OnNodeGeneralPropChanged(m_pNotificationsCookie, strModule, XN_PROP_WAVE_SUPPORTED_OUTPUT_MODES, sizeof(XnWaveOutputMode), &mode);
		XN_IS_STATUS_OK(nRetVal);

		// and set actual mode
		nRetVal = m_pNotifications->OnNodeGeneralPropChanged(m_pNotificationsCookie, strModule, XN_PROP_WAVE_OUTPUT_MODE, sizeof(mode), &mode);
		XN_IS_STATUS_OK(nRetVal);
	}
	else
	{
		nRetVal = m_pNotifications->OnNodeIntPropChanged(m_pNotificationsCookie, strModule, strName, nValue);
	}

	XN_IS_STATUS_OK(nRetVal);

	/********************/
	// Now for some additional logic...
	/********************/

	xn::ProductionNode node;
	nRetVal = m_context.GetProductionNodeByName(strModule, node);
	XN_IS_STATUS_OK(nRetVal);

	// replace codec?
	if (strcmp(strName, XN_STREAM_PROPERTY_COMPRESSION) == 0)
	{
		nRetVal = CreateCodec(node);
		XN_IS_STATUS_OK(nRetVal);
	}
	else if (strcmp(strName, XN_STREAM_PROPERTY_OUTPUT_FORMAT) == 0)
	{
		nRetVal = CheckIRCompatibility(node);
		XN_IS_STATUS_OK(nRetVal);
	}
	else if (strcmp(strModule, XN_MODULE_NAME_DEVICE) == 0 &&
		strcmp(strName, XN_MODULE_PROPERTY_HIGH_RES_TIMESTAMPS) == 0)
	{
		// check timestamps resolution
		m_bHighresTimestamps = (nValue == TRUE);
	}
	else if (strcmp(strName, XN_STREAM_PROPERTY_ZERO_PLANE_DISTANCE) == 0 ||
		strcmp(strName, XN_STREAM_PROPERTY_MAX_SHIFT) == 0 ||
		strcmp(strName, XN_STREAM_PROPERTY_DEVICE_MAX_DEPTH) == 0 ||
		strcmp(strName, XN_STREAM_PROPERTY_CONST_SHIFT) == 0 ||
		strcmp(strName, XN_STREAM_PROPERTY_PIXEL_SIZE_FACTOR) == 0 ||
		strcmp(strName, XN_STREAM_PROPERTY_PARAM_COEFF) == 0 ||
		strcmp(strName, XN_STREAM_PROPERTY_SHIFT_SCALE) == 0)
	{
		// only after node is ready
		xn::DepthGenerator depth(node);
		XnNodeInfo* pNodeInfo;
		if (m_nodeInfoMap.Get(strModule, pNodeInfo) == XN_STATUS_OK &&
			m_context.GetProductionNodeByName(strModule, depth) == XN_STATUS_OK)
		{
			nRetVal = UpdateS2DTables(depth);
			XN_IS_STATUS_OK(nRetVal);
		}
	}

	if (strcmp(strName, XN_STREAM_PROPERTY_ZERO_PLANE_DISTANCE) == 0 ||
		strcmp(strName, XN_STREAM_PROPERTY_X_RES) == 0)
	{
		// only after node is ready
		XnNodeInfo* pNodeInfo;
		if (m_nodeInfoMap.Get(strModule, pNodeInfo) == XN_STATUS_OK)
		{
			// check this is a depth node
			if (node.GetInfo().GetDescription().Type == XN_NODE_TYPE_DEPTH)
			{
				xn::DepthGenerator depth(node);
				nRetVal = UpdateRWData(depth);
				XN_IS_STATUS_OK(nRetVal);
			}
		}
	}

	return (XN_STATUS_OK);
}
Exemple #21
0
ECode CxxSourceCrcTask::operator()()
{
    const auto& path = apply_visitor(doim::vst::path(), cxxSource());

    defer(LOGEX(tags(),
                "{} for {} is {:x}",
                depth() == EDepth::kOne ? "Crc" : "Deep Crc",
                path,
                mCrcsum));

    auto origin =
        apply_visitor([](auto const& element) { return element->origin(); }, cxxSource());

    if (!apply_visitor(vst::isNullptr, origin))
    {
        if (origin.type() == typeid(doim::ProtobufFileSPtr))
        {
            auto originTask =
                ProtobufFileCrcTask::valid(boost::get<doim::ProtobufFileSPtr>(origin));
            gTPool->ensureScheduled(originTask);
            EHTest(originTask->join());
            mCrcsum = originTask->crc();
        }
        else
            ASSERT(false);
        EHEnd;
    }

    if (depth() == EDepth::kOne)
    {
        EHTest(one());
        EHEnd;
    }

    auto crcTask = valid(EDepth::kOne, cxxSource(), currentIncludeDirectory());
    gTPool->ensureScheduled(crcTask);

    auto headersTask = CxxSourceHeadersTask::valid(CxxSourceHeadersTask::EDepth::kAll,
                                                   cxxSource(),
                                                   currentIncludeDirectory());
    gTPool->ensureScheduled(headersTask);
    EHTest(headersTask->join());

    const auto& headersInfo = headersTask->headersInfo();
    std::vector<CxxSourceCrcTaskSPtr> tasks;
    tasks.reserve(headersInfo.size() + 1);

    tasks.push_back(crcTask);

    for (const auto& headerInfo : headersInfo)
    {
        if (headerInfo.mHeader->type() == doim::CxxHeader::EType::kSystem)
            continue;

        auto task = CxxSourceCrcTask::valid(CxxSourceCrcTask::EDepth::kOne,
                                            headerInfo.mHeader,
                                            headerInfo.mIncludeDirectory);
        task::gTPool->ensureScheduled(task);
        tasks.push_back(task);
    }

    auto group = tpool::TaskGroup::make(task::gTPool, 0, tasks);
    task::gTPool->ensureScheduled(group);

    EHTest(group->join());

    unordered_set<math::Crcsum> crcs;

    math::Crcsum x = 0;
    for (const auto& task : tasks)
    {
        auto n = task->crc();
        if (n == 0)
        {
            mCrcsum = 0;
            EHEnd;
        }
        auto unique = crcs.insert(n).second;
        if (!unique)
            EHBan(kTooMany, "There are at least two items with the same crc");

        x ^= n;
    }

    mCrcsum = math::obfuscate(x);
    EHEnd;
}
Exemple #22
0
F32 gpu_benchmark()
{
    if (!gGLManager.mHasShaderObjects || !gGLManager.mHasTimerQuery)
    {   // don't bother benchmarking the fixed function
        // or venerable drivers which don't support accurate timing anyway
        // and are likely to be correctly identified by the GPU table already.
        return -1.f;
    }

    if (gBenchmarkProgram.mProgramObject == 0)
    {
        LLViewerShaderMgr::instance()->initAttribsAndUniforms();

        gBenchmarkProgram.mName = "Benchmark Shader";
        gBenchmarkProgram.mFeatures.attachNothing = true;
        gBenchmarkProgram.mShaderFiles.clear();
        gBenchmarkProgram.mShaderFiles.push_back(std::make_pair("interface/benchmarkV.glsl", GL_VERTEX_SHADER_ARB));
        gBenchmarkProgram.mShaderFiles.push_back(std::make_pair("interface/benchmarkF.glsl", GL_FRAGMENT_SHADER_ARB));
        gBenchmarkProgram.mShaderLevel = 1;
        if (!gBenchmarkProgram.createShader(NULL, NULL))
        {
            return -1.f;
        }
    }

    LLGLDisable blend(GL_BLEND);

    //measure memory bandwidth by:
    // - allocating a batch of textures and render targets
    // - rendering those textures to those render targets
    // - recording time taken
    // - taking the median time for a given number of samples

    //resolution of textures/render targets
    const U32 res = 1024;

    //number of textures
    const U32 count = 32;

    //number of samples to take
    const S32 samples = 64;

    if (gGLManager.mHasTimerQuery)
    {
        LLGLSLShader::initProfile();
    }

    LLRenderTarget dest[count];
    U32 source[count];
    LLImageGL::generateTextures(count, source);
    std::vector<F32> results;

    //build a random texture
    U8* pixels = new U8[res*res*4];

    for (U32 i = 0; i < res*res*4; ++i)
    {
        pixels[i] = (U8) ll_rand(255);
    }


    gGL.setColorMask(true, true);
    LLGLDepthTest depth(GL_FALSE);

    for (U32 i = 0; i < count; ++i)
    {   //allocate render targets and textures
        dest[i].allocate(res,res,GL_RGBA,false, false, LLTexUnit::TT_TEXTURE, true);
        dest[i].bindTarget();
        dest[i].clear();
        dest[i].flush();

        gGL.getTexUnit(0)->bindManual(LLTexUnit::TT_TEXTURE, source[i]);
        LLImageGL::setManualImage(GL_TEXTURE_2D, 0, GL_RGBA, res,res,GL_RGBA, GL_UNSIGNED_BYTE, pixels);
    }

    delete [] pixels;

    //make a dummy triangle to draw with
    LLPointer<LLVertexBuffer> buff = new LLVertexBuffer(LLVertexBuffer::MAP_VERTEX | LLVertexBuffer::MAP_TEXCOORD0, GL_STATIC_DRAW_ARB);
    buff->allocateBuffer(3, 0, true);

    LLStrider<LLVector3> v;
    LLStrider<LLVector2> tc;

    buff->getVertexStrider(v);

    v[0].set(-1,1,0);
    v[1].set(-1,-3,0);
    v[2].set(3,1,0);

    buff->flush();

    gBenchmarkProgram.bind();

    bool busted_finish = false;

    buff->setBuffer(LLVertexBuffer::MAP_VERTEX);
    glFinish();

    for (S32 c = -1; c < samples; ++c)
    {
        LLTimer timer;
        timer.start();

        for (U32 i = 0; i < count; ++i)
        {
            dest[i].bindTarget();
            gGL.getTexUnit(0)->bindManual(LLTexUnit::TT_TEXTURE, source[i]);
            buff->drawArrays(LLRender::TRIANGLES, 0, 3);
            dest[i].flush();
        }

        //wait for current batch of copies to finish
        if (busted_finish)
        {
            //read a pixel off the last target since some drivers seem to ignore glFinish
            dest[count-1].bindTarget();
            U32 pixel = 0;
            glReadPixels(0,0,1,1,GL_RGBA, GL_UNSIGNED_BYTE, &pixel);
            dest[count-1].flush();
        }
        else
        {
            glFinish();
        }

        F32 time = timer.getElapsedTimeF32();

        if (c >= 0) // <-- ignore the first sample as it tends to be artificially slow
        {
            //store result in gigabytes per second
            F32 gb = (F32) ((F64) (res*res*8*count))/(1000000000);

            F32 gbps = gb/time;

            if (!gGLManager.mHasTimerQuery && !busted_finish && gbps > 128.f)
            {   //unrealistically high bandwidth for a card without timer queries, glFinish is probably ignored
                busted_finish = true;
                LL_WARNS() << "GPU Benchmark detected GL driver with broken glFinish implementation." << LL_ENDL;
            }
            else
            {
                results.push_back(gbps);
            }
        }
    }

    gBenchmarkProgram.unbind();

    if (gGLManager.mHasTimerQuery)
    {
        LLGLSLShader::finishProfile(false);
    }

    LLImageGL::deleteTextures(count, source);

    std::sort(results.begin(), results.end());

    F32 gbps = results[results.size()/2];

    LL_INFOS() << "Memory bandwidth is " << llformat("%.3f", gbps) << "GB/sec according to CPU timers" << LL_ENDL;

#if LL_DARWIN
    if (gbps > 512.f)
    {
        LL_WARNS() << "Memory bandwidth is improbably high and likely incorrect; discarding result." << LL_ENDL;
        //OSX is probably lying, discard result
        gbps = -1.f;
    }
#endif

    F32 ms = gBenchmarkProgram.mTimeElapsed/1000000.f;
    F32 seconds = ms/1000.f;

    F64 samples_drawn = res*res*count*samples;
    F32 samples_sec = (samples_drawn/1000000000.0)/seconds;
    gbps = samples_sec*8;

    LL_INFOS() << "Memory bandwidth is " << llformat("%.3f", gbps) << "GB/sec according to ARB_timer_query" << LL_ENDL;

    return gbps;
}
void pdf_format::handle_atom(stream_type& os, bool is_push) {
    const format_element_t& top(stack_top());
    name_t parent(stack_depth() >= 2 ? stack_n(1).tag() : name_t());
    name_t grandparent(stack_depth() >= 3 ? stack_n(2).tag() : name_t());
    const serializable_t& value(top.value());
    bool outputting_bag(parent == seq_name_g && grandparent == bag_name_g);
    std::size_t& num_out(outputting_bag ? stack_n(2).num_out_m : stack_n(1).num_out_m);
    bool named_argument(outputting_bag && num_out % 2 == 0);

    if (is_push) {
        // if this is not the first item in the element, add a comma and set up a newline
        if (num_out > 0) {
            if (!outputting_bag) {
                os << ' ';
            } else if (named_argument) {
                os << '\n' << indents(depth());
            }
        } else if (outputting_bag) {
            os << '\n' << indents(depth());
        }

        if (value.type_info() == typeid(string)) {
            os << '(' << value.cast<string>() << ')';
        } else if (value.type_info() == typeid(name_t)) {
            os << '/' << value.cast<name_t>();

            if (outputting_bag && named_argument)
                os << " ";
        } else if (value.type_info() == typeid(bool)) {
            os << (value.cast<bool>() ? "true" : "false");
        } else if (value.type_info() == typeid(double)) {
            double dbl_val(value.cast<double>());
            boost::int64_t int_val(static_cast<boost::int64_t>(dbl_val));

            if (dbl_val == int_val) {
                os << int_val;
            } else {
                // For pdf, we want to output floating-point values in decimal-based
                // fixed-point notation (asl_cel doesn't support any other format) with
                // a very high precision for accceptable roundtrip values.

                os.setf(std::ios_base::dec, std::ios_base::basefield);
                os.setf(std::ios_base::fixed, std::ios_base::floatfield);
                os.precision(16);

                os << dbl_val;
            }
        } else if (value.type_info() == typeid(empty_t)) {
            os << "null";
        } else if (value.type_info() == typeid(dictionary_t)) {
            os << value.cast<dictionary_t>();
        } else if (value.type_info() == typeid(array_t)) {
            os << value.cast<array_t>();
        } else {
            os << "(pdf_unknown: " << value.type_info().name() << ")";
        }
    } else {
        // up the number of outputted items for the parent to this atom
        ++num_out;
    }
}
void LLDrawPoolAvatar::renderAvatars(LLVOAvatar* single_avatar, S32 pass)
{
	if (pass == -1)
	{
		for (S32 i = 1; i < getNumPasses(); i++)
		{ //skip foot shadows
			prerender();
			beginRenderPass(i);
			renderAvatars(single_avatar, i);
			endRenderPass(i);
		}

		return;
	}

	if (mDrawFace.empty() && !single_avatar)
	{
		return;
	}

	LLVOAvatar *avatarp;

	if (single_avatar)
	{
		avatarp = single_avatar;
	}
	else
	{
		const LLFace *facep = mDrawFace[0];
		if (!facep->getDrawable())
		{
			return;
		}
		avatarp = (LLVOAvatar *)facep->getDrawable()->getVObj().get();
	}

    if (avatarp->isDead() || avatarp->mDrawable.isNull())
	{
		return;
	}

	if (!single_avatar && !avatarp->isFullyLoaded() )
	{
		if (pass==0 && (!gPipeline.hasRenderType(LLPipeline::RENDER_TYPE_PARTICLES) || LLViewerPartSim::getMaxPartCount() <= 0))
		{
			// debug code to draw a sphere in place of avatar
			gGL.getTexUnit(0)->bind(LLViewerFetchedTexture::sWhiteImagep);
			gGL.setColorMask(true, true);
			LLVector3 pos = avatarp->getPositionAgent();
			gGL.color4f(1.0f, 1.0f, 1.0f, 0.7f);
			
			gGL.pushMatrix();	 
			gGL.translatef((F32)(pos.mV[VX]),	 
						   (F32)(pos.mV[VY]),	 
							(F32)(pos.mV[VZ]));	 
			 gGL.scalef(0.15f, 0.15f, 0.3f);

			 gSphere.renderGGL();
				 
			 gGL.popMatrix();
			 gGL.setColorMask(true, false);
		}
		// don't render please
		return;
	}

	BOOL impostor = avatarp->isImpostor() && !single_avatar;

	if (impostor && pass != 0)
	{ //don't draw anything but the impostor for impostored avatars
		return;
	}
	
	if (pass == 0 && !impostor && LLPipeline::sUnderWaterRender)
	{ //don't draw foot shadows under water
		return;
	}

	if (pass == 0)
	{
		if (!LLPipeline::sReflectionRender)
		{
			LLVOAvatar::sNumVisibleAvatars++;
		}

		if (impostor)
		{
			if (LLPipeline::sRenderDeferred && !LLPipeline::sReflectionRender && avatarp->mImpostor.isComplete()) 
			{
				if (normal_channel > -1)
				{
					avatarp->mImpostor.bindTexture(2, normal_channel);
				}
				if (specular_channel > -1)
				{
					avatarp->mImpostor.bindTexture(1, specular_channel);
				}
			}
			avatarp->renderImpostor(LLColor4U(255,255,255,255), sDiffuseChannel);
		}
		return;
	}

	llassert(LLPipeline::sImpostorRender || !avatarp->isVisuallyMuted());

	/*if (single_avatar && avatarp->mSpecialRenderMode >= 1) // 1=anim preview, 2=image preview,  3=morph view
	{
		gPipeline.enableLightsAvatarEdit(LLColor4(.5f, .5f, .5f, 1.f));
	}*/
	
	if (pass == 1)
	{
		// render rigid meshes (eyeballs) first
		avatarp->renderRigid();
		return;
	}

	if (pass == 3)
	{
		if (is_deferred_render)
		{
			renderDeferredRiggedSimple(avatarp);
		}
		else
		{
			renderRiggedSimple(avatarp);
		}
		return;
	}

	if (pass == 4)
	{
		if (is_deferred_render)
		{
			renderDeferredRiggedBump(avatarp);
		}
		else
		{
			renderRiggedFullbright(avatarp);
		}

		return;
	}

	if (pass == 5)
	{
		renderRiggedShinySimple(avatarp);
		return;
	}

	if (pass == 6)
	{
		renderRiggedFullbrightShiny(avatarp);
		return;
	}

	if (pass >= 7 && pass < 9)
	{
		LLGLEnable blend(GL_BLEND);

		gGL.setColorMask(true, true);
		gGL.blendFunc(LLRender::BF_SOURCE_ALPHA,
					  LLRender::BF_ONE_MINUS_SOURCE_ALPHA,
					  LLRender::BF_ZERO,
					  LLRender::BF_ONE_MINUS_SOURCE_ALPHA);

		
		if (pass == 7)
		{
			renderRiggedAlpha(avatarp);
			return;
		}

		if (pass == 8)
		{
			renderRiggedFullbrightAlpha(avatarp);
			return;
		}
	}

	if (pass == 9)
	{
		LLGLEnable blend(GL_BLEND);
		LLGLDisable test(GL_ALPHA_TEST);
		gGL.flush();

		LLGLEnable polyOffset(GL_POLYGON_OFFSET_FILL);
		glPolygonOffset(-1.0f, -1.0f);
		gGL.setSceneBlendType(LLRender::BT_ADD);

		LLGLDepthTest depth(GL_TRUE, GL_FALSE);
		gGL.setColorMask(false, true);

		renderRiggedGlow(avatarp);
		gGL.setColorMask(true, false);
		gGL.setSceneBlendType(LLRender::BT_ALPHA);
		return;
	}
	
	if ((sShaderLevel >= SHADER_LEVEL_CLOTH))
	{
		LLMatrix4 rot_mat;
		LLViewerCamera::getInstance()->getMatrixToLocal(rot_mat);
		LLMatrix4 cfr(OGL_TO_CFR_ROTATION);
		rot_mat *= cfr;
		
		LLVector4 wind;
		wind.setVec(avatarp->mWindVec);
		wind.mV[VW] = 0;
		wind = wind * rot_mat;
		wind.mV[VW] = avatarp->mWindVec.mV[VW];

		sVertexProgram->uniform4fv(LLViewerShaderMgr::AVATAR_WIND, 1, wind.mV);
		F32 phase = -1.f * (avatarp->mRipplePhase);

		F32 freq = 7.f + (noise1(avatarp->mRipplePhase) * 2.f);
		LLVector4 sin_params(freq, freq, freq, phase);
		sVertexProgram->uniform4fv(LLViewerShaderMgr::AVATAR_SINWAVE, 1, sin_params.mV);

		LLVector4 gravity(0.f, 0.f, -CLOTHING_GRAVITY_EFFECT, 0.f);
		gravity = gravity * rot_mat;
		sVertexProgram->uniform4fv(LLViewerShaderMgr::AVATAR_GRAVITY, 1, gravity.mV);
	}

	if( !single_avatar || (avatarp == single_avatar) )
	{
		avatarp->renderSkinned(AVATAR_RENDER_PASS_SINGLE);
	}
}
Exemple #25
0
/* ==================================== */
int32_t lfiltreordre3d(struct xvimage *f, struct xvimage *m, int32_t xc, int32_t yc, int32_t zc, double r)
/* r : rang ramene a une echelle 0..1 (ex: 0.5 -> filtre median) */
/* m : masque representant l'element structurant */
/* xc, yc, zc : coordonnees du "centre" de l'element structurant */
/* ==================================== */
{
  int32_t rang;
  int32_t x,y,z;
  register int32_t i, j, k;                 /* index muet */
  register int32_t n, o, p;                 /* index muet */
  int32_t rs = rowsize(f);         /* taille ligne */
  int32_t cs = colsize(f);         /* taille colonne */
  int32_t ds = depth(f);           /* nb plans */
  int32_t ps = rs * cs;            /* taille plan */
  int32_t N = ps * ds;             /* taille image */
  int32_t rsm = rowsize(m);        /* taille ligne masque */
  int32_t csm = colsize(m);        /* taille colonne masque */
  int32_t dsm = depth(m);          /* nb plans masque */
  int32_t psm = rsm * csm;         /* taille plan masque */
  int32_t Nm = psm * dsm;          /* taille masque */
  uint8_t *M = UCHARDATA(m);
  uint8_t *F = UCHARDATA(f);
  uint8_t *H;                    /* image de travail */
  int32_t nptb;                    /* nombre de points de l'e.s. */
  int32_t *tab_es_x;               /* liste des coord. x des points de l'e.s. */
  int32_t *tab_es_y;               /* liste des coord. y des points de l'e.s. */
  int32_t *tab_es_z;               /* liste des coord. z des points de l'e.s. */
  uint8_t *tab_es_val;   /* liste des valeurs des points de l'e.s. */
  int32_t c;

  H = (uint8_t *)calloc(1,N*sizeof(char));
  if (H == NULL)
  {  
     fprintf(stderr,"lfiltreordre3d() : malloc failed for H\n");
     return(0);
  }

  for (x = 0; x < N; x++) H[x] = F[x];

  nptb = 0;
  for (i = 0; i < Nm; i += 1)
    if (M[i])
      nptb += 1;

  rang = (int32_t)((double)(nptb - 1) * r);
#ifdef VERBOSE
  printf("r = %g ; nptb = %d ; rang = %d\n", r, nptb, rang);
#endif

  tab_es_x = (int32_t *)calloc(1,nptb * sizeof(int32_t));
  tab_es_y = (int32_t *)calloc(1,nptb * sizeof(int32_t));
  tab_es_z = (int32_t *)calloc(1,nptb * sizeof(int32_t));
  tab_es_val = (uint8_t *)calloc(1,nptb * sizeof(char));
  if ((tab_es_x == NULL) || (tab_es_y == NULL) || (tab_es_z == NULL) || (tab_es_val == NULL))
  {  
     fprintf(stderr,"lfiltreordre3d() : malloc failed for tab_es\n");
     return(0);
  }

  n = 0;
  for (k = 0; k < dsm; k += 1)
    for (j = 0; j < csm; j += 1)
      for (i = 0; i < rsm; i += 1)
        if (M[k * psm + j * rsm + i])
        {
           tab_es_x[n] = i;
           tab_es_y[n] = j;
           tab_es_z[n] = k;
           n += 1;
        }

  for (z = 0; z < ds; z++)
  for (y = 0; y < cs; y++)
  for (x = 0; x < rs; x++)
  {
    for (c = 0; c < nptb ; c += 1)
    {
      o = z + tab_es_z[c] - zc;
      p = y + tab_es_y[c] - yc;
      n = x + tab_es_x[c] - xc; 
      if ((o >= 0) && (o < ds) && (p >= 0) && (p < cs) && (n >= 0) && (n < rs))
        tab_es_val[c] = H[o * ps + p * rs + n];
      else
        tab_es_val[c] = 0;
    }
    F[z * ps + y * rs + x] = lfiltreordre_SelectionStochastique(tab_es_val, 0, nptb - 1, rang);
  }

  free(H);
  free(tab_es_x);
  free(tab_es_y);
  free(tab_es_z);
  free(tab_es_val);
  return 1;
} /* lfiltreordre3d() */
Exemple #26
0
int depth(node *root) {
	if(root == NULL)
		return 0;
	return 1 + MAX(depth(root->child_0),depth(root->child_1));
}
KJS::Value Pixmap::call( KJS::ExecState *exec, KJS::Object &self, const KJS::List &args ) {

    if( !JSProxy::checkType( self, JSProxy::ValueProxy, "QPixmap") )
        return KJS::Value();

    JSValueProxy *op = JSProxy::toValueProxy( self.imp() );
    pix = op->toVariant().toPixmap();

    KJS::Value retValue = KJS::Value();
    switch ( mid ) {
    case Methodwidth:
        retValue = KJS::Number(width());
        break;
    case Methodheight:
        retValue = KJS::Number(height());
        break;
    case Methoddepth:
        retValue = KJS::Number(depth());
        break;
    case MethodisNull:
        retValue = KJS::Boolean(isNull());
        break;
    case Methodsize:
        retValue = convertToValue(exec, size());
        break;
    case Methodrect:
        retValue = convertToValue(exec, rect());
        break;
    case Methodresize:
    {
        if( args.size() == 2)
		resize(extractInt(exec, args, 0), extractInt(exec, args, 1));
	else if( args.size() == 1)
	    resize(extractQSize(exec, args, 0) );
	break;
    }
    case Methodfill:
        fill( extractQColor(exec, args, 0));
        break;
    case Methodmask:
    {
        retValue = convertToValue(exec, mask() );
        break;
    }
    case MethodsetMask:
    {
       setMask(extractQPixmap(exec, args, 0));
       break;
    }
    case MethodcreateHeuristicMask:
    {
       retValue = convertToValue(exec, createHeuristicMask(extractBool(exec, args, 0)));
       break;
    }
    case MethodgrabWindow:
    {
    	int winid = extractInt(exec, args,0);
	int x = extractInt(exec, args,1);
	int y = extractInt(exec, args,2);
	int w = extractInt(exec, args,3);
	int h = extractInt(exec, args,4);
    	grabWindow(winid,x,y,w,h);
	break;
    }
    default:
        kdWarning() << "Image has no method " << mid << endl;
        break;
    }

    op->setValue(pix);
    return retValue;
}
Exemple #28
0
/* ==================================== */
int32_t lsquel(struct xvimage *image, int32_t seuil, int32_t niseuil)
/* ==================================== */
{ 
  int32_t x;                       /* index muet de pixel */
  int32_t y;                       /* index muet (generalement un voisin de x) */
  int32_t rs = rowsize(image);     /* taille ligne */
  int32_t cs = colsize(image);     /* taille colonne */
  int32_t N = rs * cs;             /* taille image */
  uint8_t *SOURCE = UCHARDATA(image);      /* l'image de depart */
  struct xvimage *lab;
  int32_t *M;            /* l'image d'etiquettes de composantes connexes */
  int32_t nminima;                 /* nombre de minima differents */
  Fifo * FIFOn;
  Fifo * FIFOs;
  Fifo * FIFOe;
  Fifo * FIFOo;
  Fifo * FIFOna;
  Fifo * FIFOsa;
  Fifo * FIFOea;
  Fifo * FIFOoa;
  Fifo * FIFOtmp;
  Fifo * FIFO;
  int32_t niter;
#ifdef PERF
  chrono chrono1;
#endif

  if (depth(image) != 1) 
  {
    fprintf(stderr, "lsquel: cette version ne traite pas les images volumiques\n");
    exit(0);
  }

#ifdef PERF  
  start_chrono(&chrono1);  /* pour l'analyse de performances */
#endif

  lab = allocimage(NULL, rs, cs, 1, VFF_TYP_4_BYTE);
  if (lab == NULL)
  {   
    fprintf(stderr, "lhtkern: allocimage failed\n");
    return 0;
  }
  M = SLONGDATA(lab);

  if (!llabelextrema(image, 4, LABMIN, lab, &nminima))
  {   
    fprintf(stderr, "lhtkern: llabelextrema failed\n");
    return 0;
  }

  IndicsInit(N);

  FIFO = CreeFifoVide(N);
  FIFOn = CreeFifoVide(N/2);
  FIFOs = CreeFifoVide(N/2);
  FIFOe = CreeFifoVide(N/2);
  FIFOo = CreeFifoVide(N/2);
  if ((FIFO == NULL) && (FIFOn == NULL) && (FIFOs == NULL) && (FIFOe == NULL) && (FIFOo == NULL))
  {   fprintf(stderr, "lsquel() : CreeFifoVide failed\n");
      return(0);
  }

  /* ================================================ */
  /*                  DEBUT ALGO                      */
  /* ================================================ */

  /* ========================================================= */
  /*   INITIALISATION DES FIFOs: empile les voisins des minima */
  /* ========================================================= */

  for (x = 0; x < N; x++)
  {
    if (M[x] != 0)                  /* le pixel appartient a un minimum */
    {
        Set(x, MINI);
        y = voisin(x, NORD, rs, N);
        if ((y!=-1) && (M[y]==0) && !IsSet(y,EN_FIFO) && nonbord(y,rs,N))
          { FifoPush(FIFOn, y); Set(y, EN_FIFO); }
#ifdef DIAG
        y = voisin(x, NORD+1, rs, N);
        if ((y!=-1) && (M[y]==0) && !IsSet(y,EN_FIFO) && nonbord(y,rs,N))
          { FifoPush(FIFOn, y); Set(y, EN_FIFO); }
#endif
        y = voisin(x, EST, rs, N);
        if ((y!=-1) && (M[y]==0) && !IsSet(y,EN_FIFO) && nonbord(y,rs,N))
          { FifoPush(FIFOe, y); Set(y, EN_FIFO); }
#ifdef DIAG
        y = voisin(x, EST+1, rs, N);
        if ((y!=-1) && (M[y]==0) && !IsSet(y,EN_FIFO) && nonbord(y,rs,N))
          { FifoPush(FIFOe, y); Set(y, EN_FIFO); }
#endif
        y = voisin(x, SUD, rs, N);
        if ((y!=-1) && (M[y]==0) && !IsSet(y,EN_FIFO) && nonbord(y,rs,N))
          { FifoPush(FIFOs, y); Set(y, EN_FIFO); }
#ifdef DIAG
        y = voisin(x, SUD+1, rs, N);
        if ((y!=-1) && (M[y]==0) && !IsSet(y,EN_FIFO) && nonbord(y,rs,N))
          { FifoPush(FIFOs, y); Set(y, EN_FIFO); }
#endif
        y = voisin(x, OUEST, rs, N);
        if ((y!=-1) && (M[y]==0) && !IsSet(y,EN_FIFO) && nonbord(y,rs,N))
          { FifoPush(FIFOo, y); Set(y, EN_FIFO); }
#ifdef DIAG
        y = voisin(x, OUEST+1, rs, N);
        if ((y!=-1) && (M[y]==0) && !IsSet(y,EN_FIFO) && nonbord(y,rs,N))
          { FifoPush(FIFOo, y); Set(y, EN_FIFO); }
#endif
    } /* if (M[x] != 0) */
  } /* for x */

  freeimage(lab);

  FIFOna = CreeFifoVide(N/4);
  FIFOsa = CreeFifoVide(N/4);
  FIFOea = CreeFifoVide(N/4);
  FIFOoa = CreeFifoVide(N/4);
  if ((FIFOna == NULL) && (FIFOsa == NULL) && (FIFOea == NULL) && (FIFOoa == NULL))
  {   fprintf(stderr, "lsquel() : CreeFifoVide failed\n");
      return(0);
  }

  /* ================================================ */
  /*                  DEBUT SATURATION                */
  /* ================================================ */

  niter = 0;
  while (! (FifoVide(FIFOn) && FifoVide(FIFOe) && FifoVide(FIFOs) && FifoVide(FIFOo)))
  {
    niter++;
    while (! FifoVide(FIFOn))
    {
      x = FifoPop(FIFOn);
      UnSet(x, EN_FIFO);
      if (testabaisse(SOURCE, x, rs, N, seuil, niter, niseuil))
      {                                    /* modifie l'image le cas echeant */
        testmini(SOURCE, x, rs, N, FIFO);        /* reactualise l'image MINI */
        empilevoisins(x, rs, N, FIFOna, FIFOea, FIFOsa, FIFOoa);
      } /* if (testabaisse(SOURCE, x, rs, N, seuil, niter, niseuil)) */
    } /* while (! FifoVide(FIFOn)) */

    while (! FifoVide(FIFOs))
    {
      x = FifoPop(FIFOs);
      UnSet(x, EN_FIFO);
      if (testabaisse(SOURCE, x, rs, N, seuil, niter, niseuil))
      {                                    /* modifie l'image le cas echeant */
        testmini(SOURCE, x, rs, N, FIFO);        /* reactualise l'image MINI */
        empilevoisins(x, rs, N, FIFOna, FIFOea, FIFOsa, FIFOoa);
      } /* if (testabaisse(SOURCE, x, rs, N, seuil, niter, niseuil)) */
    } /* while (! FifoVide(FIFOs)) */

    while (! FifoVide(FIFOe))
    {
      x = FifoPop(FIFOe);
      UnSet(x, EN_FIFO);
      if (testabaisse(SOURCE, x, rs, N, seuil, niter, niseuil))
      {                                    /* modifie l'image le cas echeant */
        testmini(SOURCE, x, rs, N, FIFO);        /* reactualise l'image MINI */
        empilevoisins(x, rs, N, FIFOna, FIFOea, FIFOsa, FIFOoa);
      } /* if (testabaisse(SOURCE, x, rs, N, seuil, niter, niseuil)) */
    } /* while (! FifoVide(FIFOe)) */

    while (! FifoVide(FIFOo))
    {
      x = FifoPop(FIFOo);
      UnSet(x, EN_FIFO);
      if (testabaisse(SOURCE, x, rs, N, seuil, niter, niseuil))
      {                                    /* modifie l'image le cas echeant */
        testmini(SOURCE, x, rs, N, FIFO);        /* reactualise l'image MINI */
        empilevoisins(x, rs, N, FIFOna, FIFOea, FIFOsa, FIFOoa);
      } /* if (testabaisse(SOURCE, x, rs, N, seuil, niter, niseuil)) */
    } /* while (! FifoVide(FIFOo)) */

    FIFOtmp = FIFOn; FIFOn = FIFOna; FIFOna = FIFOtmp;
    FIFOtmp = FIFOe; FIFOe = FIFOea; FIFOea = FIFOtmp;
    FIFOtmp = FIFOs; FIFOs = FIFOsa; FIFOsa = FIFOtmp;
    FIFOtmp = FIFOo; FIFOo = FIFOoa; FIFOoa = FIFOtmp;

  } /* while (! (FifoVide(FIFOn) && FifoVide(FIFOe) && FifoVide(FIFOs) && FifoVide(FIFOo))) */

  /* ================================================ */
  /* UN PEU DE MENAGE                                 */
  /* ================================================ */

  IndicsTermine();
  FifoTermine(FIFO);
  FifoTermine(FIFOn);
  FifoTermine(FIFOe);
  FifoTermine(FIFOs);
  FifoTermine(FIFOo);
  FifoTermine(FIFOna);
  FifoTermine(FIFOea);
  FifoTermine(FIFOsa);
  FifoTermine(FIFOoa);

#ifdef PERF
  save_time(N, read_chrono(&chrono1), "lsquel", image->name);    
#endif
  return(1);
}
Exemple #29
0
DEM typ1 (DEM x)
{
int o, o1, o2;
DEM a, b, c, c1, f, x1, y, z, v, PIab, bz, s, tf, tf1, tz, tz1, t, n, n1, r;
#if 1
	return U(Order(0));
#else

    o = order(x);
    o1 = suc_order(o);
    o2 = suc_order(o1);

    switch (node(x))
    {
	case _Var : return subdem(0,x);

	case _It:
	    a = subdem(0,x);
	    t = Fott (o1, a, a);
	    return t;

        case _IT :
	    a = Var ("a", U(o1)); 
	    return PIott (o2, U(o1), lambda (a,
			   Fott (/*suc_order*/(o1), a, a) ));

	case _Kt:
	    a = subdem(0,x);
	    b = subdem(1,x);
	    t =  Fott (o1, a, Fott (o1, b, a));
	    return t;

        case _KT :
	    a = Var ("a", U(o1));
	    b = Var ("b", U(o1));
	    return PIott (o2, U(o1), lambda (a,
		    PIott (o2, U(o1), lambda(b,
		     Fott (o1, a, Fott (o1, b, a)) )) ));

	case _St:
	    a = subdem(0,x);
            b = subdem(1,x);
	    c = subdem(2,x);
     z = Var ("z", a);
     y = Var ("y", PIott (o1, a, b));
	    t = Fott (o1, PIott (o1, a, lambda (z,
		        PIott(o1, ap(b,z),ap(c,z)))),
		         PIott (o1, PIott (o1, a, b), lambda (y, 
			  Fott (o1, a, ap(ap(c,z),ap(y,z)))) ));
	    return t;

        case _ST :
	    a = Var ("a", U(o1));
	    b = Var ("b", Fott (o2, a, U(o1)));
            z = Var ("z", a);
	    c = Var ("c", PIott (o1, a, lambda (z, Fott (o2, ap(b,z), U(o1)))));
	    y = Var ("y", PIott (o1, a, b));
	    
	    return PIott (o2, U(o1), lambda (a,
		    Fott (o2, Fott (o2, a, U(o1)), lambda (b,
		     PIott (o1, PIott (o1, a, lambda (z, 
		      Fott (o2, ap(b,z), U(o1)))), lambda (c, 
		       Fott (o1, PIott (o1, a, lambda (z,
		        PIott(o1, ap(b,z),ap(c,z)))),
		         PIott (o1, PIott (o1, a, b), lambda (y, 
			  Fott (o1, a, ap(ap(c,z),ap(y,z)))) )))
			    ) ))));

	case _Yt:
	    a = subdem(0,x);
	    t = Fott (o1, Fott (o1, a, a), a);
	    return t;

	case _Ord:
	    return U(Order(1));

	case _Zero:
	    return Ord;

	case _Suc:
	    return Fott (Order(1), Ord, Ord);

	case _Lim:
	    return Fott (Order(1), Fott (Order(1), Ord, Ord), Ord);

	case _Rept:
	    o1 = Order(1);
	    a = subdem(0,x);
	    t = Fott (o1, Ord, 
		    Fott (o1, Fott (o1, a, a), Fott (o1, a, a)));
	    return t;

	case _Testt:
	    o1 = Order(1);
	    a = subdem(0,x);
	    n = Var ("n", Ord);
            n1 = Var ("n1", Ord);
            t = PIott (o1, Ord, lambda (n1, Fott (o1, ap (a, Zero),
                    Ftt ( PIott (o1, Ord, lambda (n, ap (a, ap (Suc, n)))),
                           ap (a, n1) ) )));
	    return t;

        case _F:
            return Fott (o1, U(o), Fott (o1, U(o), U(o)));

	case _PI:
	    a = Var ("a", U(o));
	    return PIott (o1, U(o), lambda (a,
			    Fott (o1, Fott (o1, a, U(o)), U(o)) ));
		     
        case _U: return U (suc_order (order_u (x)));

	case _ap:
            if (depth(x) == 1 && node(s=rfnc(1,x)) == _Kt)
	    {
		a = subdem(0,s);
		b = subdem(1,s);
		o = order(s);
		return Fott (o, b, a);
            }
	    if (node(subdem(0,x)) == _ap &&
	        node(subdem(0,subdem(0,x))) == _ap &&
                node(subdem(0,subdem(0,subdem(0,x)))) == _KT)
	    {
		a = subdem(1,subdem(0,subdem(0,x)));
		b = subdem(1,subdem(0,x));
		o = order(a);
		return Fott (o, b, a);
	    }
	    if (depth (x) == 2 && node(s=rfnc(2,x)) == _St)
	    {
		a = subdem(0,s);
		b = subdem(1,s);
		c = subdem(2,s);
		goto Sabc;				
	    }
            if (depth (x) == 5 && node(s=rfnc(5,x)) == _ST)
	    {
	    /* S a:Uo+1 b:(Uo(a)+1) c:(a)>\z:a.((bz)>Uo+1) 
		 x:(a)>\z:a.(cz(bz)) y:(a)>b z:a = xz(yz):cz(yz)
		 xz:(bz)>cz, yz:bz
	       S a b c x y : a ->> \z:a. cz(yz)
             */
	        a = subdem(1,rfnc(4,x));
		b = subdem(1,rfnc(3,x));
		c = subdem(1,rfnc(2,x));
	    Sabc:
		x1 = subdem(1,rfnc(1,x));
		y = subdem(1,rfnc(0,x));
		z = Var ("z", a);
		o = order(s);
		o1 = suc_order (o);
		/* t = PIott (o1, a, lambda (z, ap (ap (c, z), ap (y, z)))); */
		v = Var ("v", simplif (ap (b, z)));
		c1 = lambda (z, lambda (v, U(o1)));

		trace_dem ("c = ", c);

                t = PIott (o1, a, Sotttxx (o, a, b, c1, c, y));
		return t;
	    }
            if (node(subdem(0,x)) == _ap &&
                node(subdem(0,subdem(0,x))) == _F)
            {
                /*
                if (typ (subdem(1,subdem(0,x))) == typ (subdem(1,x)))
                    return typ (subdem(1,x)); 
                error ("F applied to different types", __LINE__, x);
                */
                return unio (typ(subdem(1,subdem(0,x))), 
                             typ(subdem(1,x)));
            }        
	    f = fnc (x);
	    z = arg (x);
	    /* PIab = typ (f);
            b = arg (PIab); */
            tf = typ (f);
            tz = typ (z);
        new_tz:
            print_string (print_param, "typ(z) = ");
            print_dem (print_param, tz);
        new_tf:    
            print_string (print_param, "  subdem(1,subdem(0,tf)) = ");
            print_dem (print_param, subdem(1,subdem(0,tf)));
            print_string (print_param, "\n");

            if (node(tf) == _ap &&
                node(subdem(0,tf)) == _ap &&
                node(subdem(0,subdem(0,tf))) == _F &&
                inclus (tz, subdem(1,subdem(0,tf))))
                return subdem(1,tf);

            if (node(tf) == _ap &&
                node(subdem(0,tf)) == _ap &&
                node(subdem(0,subdem(0,tf))) == _PI &&
                inclus (tz, subdem(1,subdem(0,tf))))
                {
                    /* return ap (subdem(1,tf), z); */
                    tf1 = subdem(1,tf);
                    print_string (print_param, "tf1 = ");
                    print_dem (print_param, tf1);
                    print_string (print_param, "\nz = ");
                    print_dem (print_param, z);
                    r = ap (tf1, z);
                    print_string (print_param, "\nr = ");
                    print_dem (print_param, r);
                    print_string (print_param, "\n");
                    return r;
                }
            print_string (print_param, "Bad type of function ");
            print_dem (print_param, f);
            print_string (print_param, " of type ");
            print_dem (print_param, tf);
            print_string (print_param, " applied to ");
            print_dem (print_param, z);
            print_string (print_param, " of type ");
            print_dem (print_param, tz);
            print_string (print_param, "\n");

            tf1 = simplif (tf);
            if (tf1 != tf)
            {
                tf = tf1;
                goto new_tf;
            }

            tz1 = simplif (tz);
            if (tz1 != tz)
            {
                tz = tz1;
                goto new_tz;
            }

            print_string (print_param, "Bad type of function ");
            print_dem (print_param, f);
            print_string (print_param, " of type ");
            print_dem (print_param, tf);
            print_string (print_param, " applied to ");
            print_dem (print_param, z);
            print_string (print_param, " of type ");
            print_dem (print_param, tz);
            print_string (print_param, "\n");

            error ("Bad type of function : ", __LINE__, tf);


                
	    /*bz = ap (b, z);
	    return bz;*/

        case _Lambda:
            z = subdem(0,x);
            r = subdem(1,x);
            a = typ (z);
            bz = typ (r);
            b = lambda (z, bz);
            t = PItt (a, b);
            return t;
            break;

        default:
	    print_string (print_param, "typ not implemented for ");
	    print_dem (print_param, x);
	    print_string (print_param, "\n");
	    return U(-1);

    }
#endif
}
//--------------------------------------------------------------------------------------------------
/// Render a semi transparent background frame
//--------------------------------------------------------------------------------------------------
void InternalLegendRenderTools::renderBackgroundUsingShaders(OpenGLContext* oglContext,
                                                     const MatrixState& matrixState,
                                                     const Vec2f& size,
                                                     const Color4f& backgroundColor,
                                                     const Color4f& backgroundFrameColor)
{
    CVF_CALLSITE_OPENGL(oglContext);

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

    RenderStateLine line(1.0f);
    line.applyOpenGL(oglContext);

    RenderStateBlending blend;
    blend.configureTransparencyBlending();
    blend.applyOpenGL(oglContext);

    // Shader program

    ref<ShaderProgram> shaderProgram = oglContext->resourceManager()->getLinkedUnlitColorShaderProgram(oglContext);
    CVF_TIGHT_ASSERT(shaderProgram.notNull());

    if (shaderProgram->useProgram(oglContext))
    {
        shaderProgram->clearUniformApplyTracking();
        shaderProgram->applyFixedUniforms(oglContext, matrixState);
    }

    std::array<Vec3f, 4> vertexArray ={
        Vec3f(1       ,        1, 0.0f),
        Vec3f(size.x(),        1, 0.0f),
        Vec3f(size.x(), size.y(), 0.0f),
        Vec3f(1       , size.y(), 0.0f),
    };


    glBindBuffer(GL_ARRAY_BUFFER, 0);
    glEnableVertexAttribArray(ShaderProgram::VERTEX);
    glVertexAttribPointer(ShaderProgram::VERTEX, 3, GL_FLOAT, GL_FALSE, 0, vertexArray.data());

    // Draw frame background

    UniformFloat backgroundColorUniform("u_color", backgroundColor);
    shaderProgram->applyUniform(oglContext, backgroundColorUniform);

    // Triangle indices for the frame background

    static const ushort backgroundTriangleIndices[] = { 0, 1, 2,  2, 3, 0};

    glDrawRangeElements(GL_TRIANGLES, 0, 3, 6, GL_UNSIGNED_SHORT, backgroundTriangleIndices);


    // Draw frame border lines

    UniformFloat uniformColor("u_color", backgroundFrameColor);
    shaderProgram->applyUniform(oglContext, uniformColor);

    static const ushort frameLineIndices[] = { 0, 1,
                                               1, 2,
                                               2, 3,
                                               3, 0 };

    glDrawRangeElements(GL_LINES, 0, 3, 8, GL_UNSIGNED_SHORT, frameLineIndices);

    glDisableVertexAttribArray(ShaderProgram::VERTEX);

    CVF_TIGHT_ASSERT(shaderProgram.notNull());
    shaderProgram->useNoProgram(oglContext);

    // Reset render states
    RenderStateDepth resetDepth;
    resetDepth.applyOpenGL(oglContext);

    RenderStateLine resetLine;
    resetLine.applyOpenGL(oglContext);

    RenderStateBlending resetblend;
    resetblend.applyOpenGL(oglContext);

    CVF_CHECK_OGL(oglContext);
}