Ejemplo n.º 1
0
MediaScanImage *video_create_image_from_frame(MediaScanVideo *v, MediaScanResult *r) {
  MediaScanImage *i = image_create();
  AVFormatContext *avf = (AVFormatContext *)r->_avf;
  av_codecs_t *codecs = (av_codecs_t *)v->_codecs;
  AVCodec *codec = (AVCodec *)v->_avc;
  AVFrame *frame = NULL;
  AVPacket packet;
  struct SwsContext *swsc = NULL;
  int got_picture;
  int64_t duration_tb = ((double)avf->duration / AV_TIME_BASE) / av_q2d(codecs->vs->time_base);
  uint8_t *src;
  int x, y;
  int ofs = 0;
  int no_keyframe_found = 0;
  int skipped_frames = 0;

  if ((avcodec_open(codecs->vc, codec)) < 0) {
    LOG_ERROR("Couldn't open video codec %s for thumbnail creation\n", codec->name);
    goto err;
  }

  frame = avcodec_alloc_frame();
  if (!frame) {
    LOG_ERROR("Couldn't allocate a video frame\n");
    goto err;
  }

  av_init_packet(&packet);

  i->path = v->path;
  i->width = v->width;
  i->height = v->height;

  // XXX select best video frame, for example:
  // * Skip frames of all the same color (e.g. blank intro frames
  // * Use edge detection to skip blurry frames
  //   * http://code.google.com/p/fast-edge/
  //   * http://en.wikipedia.org/wiki/Canny_edge_detector 
  // * Use a frame some percentage into the video, what percentage?
  // * If really ambitious, use OpenCV for finding a frame with a face?

  // XXX other ways to seek if this fails
  // XXX for now, seek 10% into the video
  av_seek_frame(avf, codecs->vsid, (int)((double)duration_tb * 0.1), 0);

  for (;;) {
    int ret;
    int rgb_bufsize;
    AVFrame *frame_rgb = NULL;
    uint8_t *rgb_buffer = NULL;

    // Give up if we already tried the first frame
    if (no_keyframe_found) {
      LOG_ERROR("Error decoding video frame for thumbnail: %s\n", v->path);
      goto err;
    }

    if ((ret = av_read_frame(avf, &packet)) < 0) {
      if (ret == AVERROR_EOF || skipped_frames > 200) {
        LOG_DEBUG("Couldn't find a keyframe, using first frame\n");
        no_keyframe_found = 1;
        av_seek_frame(avf, codecs->vsid, 0, 0);
        av_read_frame(avf, &packet);
      }
      else {
        LOG_ERROR("Couldn't read video frame (%s): ", v->path);
        print_averror(ret);
        goto err;
      }
    }

    // Skip frame if it's not from the video stream
    if (!no_keyframe_found && packet.stream_index != codecs->vsid) {
      av_free_packet(&packet);
      skipped_frames++;
      continue;
    }

    // Skip non-key-frames
    if (!no_keyframe_found && !(packet.flags & AV_PKT_FLAG_KEY)) {
      av_free_packet(&packet);
      skipped_frames++;
      continue;
    }

    // Skip invalid packets, not sure why this isn't an error from av_read_frame
    if (packet.pos < 0) {
      av_free_packet(&packet);
      skipped_frames++;
      continue;
    }

    LOG_DEBUG("Using video packet: pos %lld size %d, stream_index %d, duration %d\n",
              packet.pos, packet.size, packet.stream_index, packet.duration);

    if ((ret = avcodec_decode_video2(codecs->vc, frame, &got_picture, &packet)) < 0) {
      LOG_ERROR("Error decoding video frame for thumbnail: %s\n", v->path);
      print_averror(ret);
      goto err;
    }

    if (!got_picture) {
      if (skipped_frames > 200) {
        LOG_ERROR("Error decoding video frame for thumbnail: %s\n", v->path);
        goto err;
      }
      if (!no_keyframe_found) {
        // Try next frame
        av_free_packet(&packet);
        skipped_frames++;
        continue;
      }
    }

    // use swscale to convert from source format to RGBA in our buffer with no resizing
    // XXX what scaler is fastest here when not actually resizing?
    swsc = sws_getContext(i->width, i->height, codecs->vc->pix_fmt,
                          i->width, i->height, PIX_FMT_RGB24, SWS_FAST_BILINEAR, NULL, NULL, NULL);
    if (!swsc) {
      LOG_ERROR("Unable to get swscale context\n");
      goto err;
    }

    frame_rgb = avcodec_alloc_frame();
    if (!frame_rgb) {
      LOG_ERROR("Couldn't allocate a video frame\n");
      goto err;
    }

    // XXX There is probably a way to get sws_scale to write directly to i->_pixbuf in our RGBA format

    rgb_bufsize = avpicture_get_size(PIX_FMT_RGB24, i->width, i->height);
    rgb_buffer = av_malloc(rgb_bufsize);
    if (!rgb_buffer) {
      LOG_ERROR("Couldn't allocate an RGB video buffer\n");
      av_free(frame_rgb);
      goto err;
    }
    LOG_MEM("new rgb_buffer of size %d @ %p\n", rgb_bufsize, rgb_buffer);

    avpicture_fill((AVPicture *)frame_rgb, rgb_buffer, PIX_FMT_RGB24, i->width, i->height);

    // Convert image to RGB24
    sws_scale(swsc, frame->data, frame->linesize, 0, i->height, frame_rgb->data, frame_rgb->linesize);

    // Allocate space for our version of the image
    image_alloc_pixbuf(i, i->width, i->height);

    src = frame_rgb->data[0];
    ofs = 0;
    for (y = 0; y < i->height; y++) {
      for (x = 0; x < i->width * 3; x += 3) {
        i->_pixbuf[ofs++] = COL(src[x], src[x + 1], src[x + 2]);
      }
      src += i->width * 3;
    }

    // Free the frame
    LOG_MEM("destroy rgb_buffer @ %p\n", rgb_buffer);
    av_free(rgb_buffer);

    av_free(frame_rgb);

    // Done!
    goto out;
  }

err:
  image_destroy(i);
  i = NULL;

out:
  sws_freeContext(swsc);
  av_free_packet(&packet);
  if (frame)
    av_free(frame);

  avcodec_close(codecs->vc);

  return i;
}
Ejemplo n.º 2
0
void xboard()
{
    char line[256], command[256], c;
    char args[4][64];
    int from, dest, i;
    MOVE moveBuf[200];
    MOVE theBest;
    int movecnt;
    //int illegal_king = 0;

    signal(SIGINT, SIG_IGN);

    printf ("\n");
//    hashKeyPosition(); /* hash of the initial position */
//    hashRndInit();
    startgame ();

    /* Waiting for a command from GUI */
    for (;;)
    {
        fflush (stdout);
        if (side == computerSide)
        {   /* Computer's turn */
            /* Find out the best move to reply to the current position */
            theBest = ComputerThink (maxDepth);
            if (theBest.type_of_move > 8)
                printf ("type of move the best %d \n", theBest.type_of_move);
            makeMove (theBest);
            /* send move */
            switch (theBest.type_of_move)
            {
            case MOVE_TYPE_PROMOTION_TO_QUEEN:
                c = 'q';
                break;
            case MOVE_TYPE_PROMOTION_TO_ROOK:
                c = 'r';
                break;
            case MOVE_TYPE_PROMOTION_TO_BISHOP:
                c = 'b';
                break;
            case MOVE_TYPE_PROMOTION_TO_KNIGHT:
                c = 'n';
                break;
            default:
                c = ' ';
            }
            printf ("move %c%d%c%d%c\n", 'a' + COL(theBest.from), 8
                    - ROW(theBest.from), 'a' + COL(theBest.dest), 8
                    - ROW(theBest.dest), c);

            fflush(stdout);
            continue;
        }

        if (!fgets (line, 256, stdin))
            return;
        if (line[0] == '\n')
            continue;
        sscanf (line, "%s", command);

        if (!strcmp (command, "xboard"))
        {
            continue;
        }
        if (!strcmp (command, "d"))
        {
            printBoard ();
            continue;
        }
        if (!strcmp (command, "new"))
        {
            startgame ();
            continue;
        }
        if (!strcmp (command, "quit"))
        {
            return;
        }
        if (!strcmp (command, "force"))
        {
            computerSide = EMPTY;
            continue;
        }
        /* If we get a result the engine must stop */
        if (!strcmp(command, "result"))
        {
            computerSide = EMPTY;
            continue;
        }
        if (!strcmp(command, "?")) {
            computerSide = EMPTY;
            continue;
        }
        if (!strcmp(command, ".")) {
            continue;
        }
        if (!strcmp(command, "exit")) {
            continue;
        }
        if (!strcmp(command,"setboard"))
        {
            strcpy(fenBuf, "");
            sscanf(line, "setboard %s %s %s %s", args[0],args[1],args[2],args[3]);
            strcat(fenBuf, args[0]);
            strcat(fenBuf, args[1]);
            strcat(fenBuf, args[2]);
            strcat(fenBuf, args[3]);
            setBoard(fenBuf);
            continue;
        }
        if (!strcmp (command, "white"))
        {
            side = WHITE;
            computerSide = BLACK;
            continue;
        }
        if (!strcmp (command, "black"))
        {
            side = BLACK;
            computerSide = WHITE;
            continue;
        }
        if (!strcmp (command, "sd"))
        {
            sscanf (line, "sd %d", &maxDepth);
            continue;
        }
        if (!strcmp (command, "go"))
        {
            computerSide = side;
            continue;
        }
        /* Taken from TSCP: we receive from the GUI the time we have */
        if (!strcmp(command, "time"))
        {
            sscanf (line, "time %ld", &maxTime);
            /* Convert to miliseconds */
            maxTime *= 10;
            maxTime /= 10;
            maxTime -= 300;
            totalTime = maxTime;

//            if (totalTime < 3000)
//                maxDepth = 6;
//            else
            maxDepth = 32;
            continue;
        }
        if (!strcmp(command, "otim"))
        {
            continue;
        }
        if (!strcmp (command, "undo"))
        {
            if (hdp == 0)
                continue;
            takeBack ();
            continue;
        }
        if (!strcmp (command, "remove"))
        {
            if (hdp <= 1)
                continue;
            takeBack ();
            takeBack ();
            continue;
        }

        /* Maybe the user entered a move? */
        /* Is that a move? */
        if (command[0] < 'a' || command[0] > 'h' ||
                command[1] < '0' || command[1] > '9' ||
                command[2] < 'a' || command[2] > 'h' ||
                command[3] < '0' || command[3] > '9')
        {
            printf("Error (unknown command): %s\n", command); /* No move, unknown command */
            continue;
        }

        from = command[0] - 'a';
        from += 8 * (8 - (command[1] - '0'));
        dest = command[2] - 'a';
        dest += 8 * (8 - (command[3] - '0'));
        ply = 0;
        movecnt = genMoves (side, moveBuf);

        /* Loop through the moves to see if it's legal */
        for (i = 0; i < movecnt; ++i) {
            if (moveBuf[i].from == from && moveBuf[i].dest == dest)
            {
                if (piece[from] == PAWN && (dest < 8 || dest > 55))
                {
                    if (command[4] != 'q' && command[4] != 'r' && command[4] != 'b' && command[4] != 'n')
                    {
                        printf ("Illegal move. Bad letter for promo\n");
                        goto goon;
                    }
                    switch (command[4])
                    {
                    case 'q':
                        moveBuf[i].type_of_move = MOVE_TYPE_PROMOTION_TO_QUEEN;
                        break;
                    case 'r':
                        moveBuf[i].type_of_move = MOVE_TYPE_PROMOTION_TO_ROOK;
                        break;
                    case 'b':
                        moveBuf[i].type_of_move = MOVE_TYPE_PROMOTION_TO_BISHOP;
                        break;
                    case 'n':
                        moveBuf[i].type_of_move = MOVE_TYPE_PROMOTION_TO_KNIGHT;
                        break;
                    }
                }

                if (moveBuf[i].type_of_move > 8)
                    printf ("Type of move the best %d \n", moveBuf[i].type_of_move);

                if (makeMove (moveBuf[i]))
                {
                    goto goon;	/* Legal move */
                }
                else {
                    printf ("Illegal move. King is in check\n");
                    goto goon;
                }
            }
        }
        printf ("Illegal move.\n");  /* illegal move */

goon:
        continue;
    }
}
Ejemplo n.º 3
0
	void LightBlinker::run()
	{
		COL result = impl->lightColorDefault;

		// update our local timer which is at correct (possibly varying) interval... 
		fb_assert(impl->game->gameTimer >= impl->lastGameTimer);
		impl->blinkerTimer += impl->game->gameTimer - impl->lastGameTimer;
		if (impl->blinkerTimer >= (impl->cycleTime + impl->pauseTime + impl->thisFrameRandomPauseTime) / GAME_TICK_MSEC)
		{
			// incorrect if lastGameTimer lags badly behind gameTimer?...
			//impl->blinkerTimer -= (impl->cycleTime + impl->pauseTime + impl->thisFrameRandomPauseTime) / GAME_TICK_MSEC;
			// incorrent, as should select the smallest of old/new pausetime to make sure this actually does something...
			//impl->blinkerTimer = impl->blinkerTimer % (impl->cycleTime + impl->pauseTime + impl->thisFrameRandomPauseTime) / GAME_TICK_MSEC;
			// should work?...
			impl->blinkerTimer = 0;

			impl->thisFrameRandomPauseTime = (int)(impl->pauseTimeVariation * (float)(impl->game->gameRandom->nextInt() % 101) / 100.0f);
		}
		impl->lastGameTimer = impl->game->gameTimer;


		if (impl->enabled)
		{
			float randomizedStrength = impl->strength;
			if (impl->randomVariation > 0.0f)
			{
				impl->randomTimeLeft -= GAME_TICK_MSEC;
				if (impl->randomTimeLeft <= 0)
				{
					impl->randomTimeLeft = impl->randomTime;

					impl->lastRandomValue = impl->randomVariation * (float)((impl->game->gameRandom->nextInt() % 201) - 100) / 100.0f;
				}
				randomizedStrength += impl->lastRandomValue;
				if (randomizedStrength > 1.0f) randomizedStrength = 1.0f;
				if (randomizedStrength < 0.0f) randomizedStrength = 0.0f;
			}

			float defaultColWeight = 1.0f - randomizedStrength;
			float weight = defaultColWeight;
			result = COL(defaultColWeight*impl->lightColorDefault.r,defaultColWeight*impl->lightColorDefault.g,defaultColWeight*impl->lightColorDefault.b);

			// color1/2 balance, 0 - 1 (- x if pausetime greater than zero)
			float colorBalanceZeroOne = (float)(impl->blinkerTimer % ((impl->cycleTime + impl->pauseTime + impl->thisFrameRandomPauseTime) / GAME_TICK_MSEC)) / (float)(impl->cycleTime / GAME_TICK_MSEC);

			// change the shape of the following sinwave...
			if (impl->blinkType == LightBlinker::LightBlinkTypeBiasColor2)
			{
				if (colorBalanceZeroOne <= 1.0f)
				{
					// going down faster
					if (colorBalanceZeroOne < 0.25f)
					{
						colorBalanceZeroOne *= 2.0f;
					} else {
						// and raising up slower
						colorBalanceZeroOne = 0.5f + (colorBalanceZeroOne - 0.25f) / 1.5f;
					}
				}
			}

			// color1/2 balance, sinwave -1 - +1
			// notice sinwave phase shift (90deg, thus, full color1 at 0 and 1 time - required by proper pausetime usage)
			float colorBalanceSinWave = (float)sinf((0.25f + colorBalanceZeroOne) * 3.1415926f * 2.0f);

			if (colorBalanceZeroOne > 1.0f)
			{
				// at pause time (use the default color only, strength zero)
				colorBalanceSinWave = 1.0f;
			}

			float col1Weight = randomizedStrength * (0.5f + colorBalanceSinWave * 0.5f);
			result.r += impl->lightColor1.r * col1Weight;
			result.g += impl->lightColor1.g * col1Weight;
			result.b += impl->lightColor1.b * col1Weight;
			weight += col1Weight;

			float col2Weight = randomizedStrength * (0.5f - colorBalanceSinWave * 0.5f);
			result.r += impl->lightColor2.r * col2Weight;
			result.g += impl->lightColor2.g * col2Weight;
			result.b += impl->lightColor2.b * col2Weight;
			weight += col2Weight;

			fb_assert(weight >= 0.99f);
			fb_assert(weight <= 2.11f);

			result.r /= weight;
			result.g /= weight;
			result.b /= weight;
		}

		// apply values only if changed since last run
		if (impl->lastResultColor.r != result.r
			|| impl->lastResultColor.g != result.g
			|| impl->lastResultColor.b != result.b)
		{
			// lightmap
			{
				//COL col = impl->game->gameUI->getTerrain()->GetTerrain()->getRenderer().getColorValue(IStorm3D_TerrainRenderer::LightmapMultiplierColor);
				COL col = COL(result.r, result.g, result.b);

				if (impl->outdoor)
				{
					impl->game->gameUI->getTerrain()->GetTerrain()->getRenderer().setColorValue(IStorm3D_TerrainRenderer::OutdoorLightmapMultiplierColor, col);

					VC3 camGroundPos = impl->game->gameUI->getGameCamera()->getPosition();
					impl->game->gameMap->keepWellInScaledBoundaries(&camGroundPos.x, &camGroundPos.z);
					camGroundPos.y = impl->game->gameMap->getScaledHeightAt(camGroundPos.x, camGroundPos.z);

					// HACK: some magic numbers here.
					// NEW: no longer necessary
					//if (SimpleOptions::getInt(DH_OPT_I_LIGHTING_LEVEL) >= 33)
					//{
						//float blinkRadius = 10.0f;
						//if (SimpleOptions::getInt(DH_OPT_I_LIGHTING_LEVEL) >= 66)
						//{
						//	blinkRadius = 20.0f;
						//}
						float blinkRadius = 20.0f;
						impl->game->gameUI->getTerrain()->setToOutdoorColorMultiplier(col, camGroundPos, blinkRadius);
					//}
				} else {
					impl->game->gameUI->getTerrain()->GetTerrain()->getRenderer().setColorValue(IStorm3D_TerrainRenderer::LightmapMultiplierColor, col);
					impl->game->gameUI->getTerrain()->setToColorMultiplier(col);
					impl->game->gameUI->getLightManager()->getSelfIlluminationChanger()->setFactor(col);
				}
			}

			// colormap
			{
				//COL col = impl->game->gameMap->colorMap->getMultiplier();
				COL col = COL(result.r, result.g, result.b);

				if (impl->outdoor)
				{
					impl->game->gameMap->colorMap->setMultiplier(util::ColorMap::Outdoor, col);
				} else {
					impl->game->gameMap->colorMap->setMultiplier(util::ColorMap::Indoor, col);
					impl->game->gameUI->getLightManager()->setLightColorMultiplier(col);
					impl->game->decorationManager->updateDecorationIllumination(impl->game->gameMap->colorMap);
				}

				impl->game->gameUI->updateUnitLighting(true);
			}
		}

		impl->lastResultColor = result;
	}
void Gspan::lpboost(){
  std::cout << "in lpboost" << std::endl;
  const char *out = "model";
  //initialize
  unsigned int gnum = gdata.size(); 
  weight.resize(gnum);
  std::fill(weight.begin(),weight.end(),1.0);
  corlab.resize(gnum);
  for(unsigned int gid=0;gid<gnum;++gid){
    corlab[gid]=gdata[gid].class_label;
  }
  wbias=0.0;
  Hypothesis model;
  first_flag=true;
  need_to_cooc = false;
  cooc_is_opt = false;
  
  std::cout.setf(std::ios::fixed,std::ios::floatfield);
  std::cout.precision(8);
  //Initialize GLPK

  int* index = new int[gnum+2]; double* value = new double[gnum+2];
  LPX* lp = lpx_create_prob();
		       
  lpx_add_cols(lp, gnum+1); // set u_1,...u_l, beta
  for (unsigned int i = 0; i < gnum; ++i){
    lpx_set_col_bnds(lp, COL(i), LPX_DB, 0.0, 1/(nu*gnum));
    lpx_set_obj_coef(lp, COL(i), 0); // u
  }
  lpx_set_col_bnds(lp, COL(gnum), LPX_FR, 0.0, 0.0);
  lpx_set_obj_coef(lp, COL(gnum), 1); // beta
  lpx_set_obj_dir(lp, LPX_MIN); //optimization direction: min objective
		       
  lpx_add_rows(lp,1); // Add one row constraint s.t. sum_u == 1
  for (unsigned int i = 0; i < gnum; ++i){
    index[i+1] = COL(i);
    value[i+1] = 1;
  }
  lpx_set_mat_row(lp, ROW(0), gnum, index, value);
  lpx_set_row_bnds(lp, ROW(0), LPX_FX, 1, 1);
		       
  double beta = 0.0;
  double margin = 0.0;
  
  //main loop
  for(unsigned int itr=0;itr < max_itr;++itr){
    std::cout <<"itrator : "<<itr+1<<std::endl;
    if(itr==coocitr) need_to_cooc=true;
    opt_pat.gain=0.0;//gain init
    opt_pat.size=0;
    opt_pat.locsup.resize(0);
    pattern.resize(0);
    opt_pat.dfscode="";
    Crun();
    //std::cout<<opt_pat.gain<<"  :"<<opt_pat.dfscode<<std::endl;
    std::vector <int>     result (gnum);
    int _y;
    vector<int> locvec;
    std::string dfscode;
    if(cooc_is_opt == false){
      _y = opt_pat.gain > 0 ? +1 :-1;
      locvec =opt_pat.locsup;
      dfscode=opt_pat.dfscode;
    }else{
      _y = opt_pat_cooc.gain > 0 ? +1 :-1;
      locvec =opt_pat_cooc.locsup;
      dfscode=opt_pat_cooc.dfscode[0]+"\t"+opt_pat_cooc.dfscode[1];//=opt_pat_cooc.dfscode;
    }
    model.flag.resize(itr+1);
    model.flag[itr]=_y;

    std::fill (result.begin (), result.end(), -_y);
      
    for (unsigned int i = 0; i < locvec.size(); ++i) result[locvec[i]] = _y;
    double uyh = 0;
    for (unsigned int i = 0; i < gnum;  ++i) { // summarizing hypotheses
      uyh += weight[i]*corlab[i]*result[i];
    }
      
    std::cout << "Stopping criterion: " << uyh << "<=?" << beta << " + " << conv_epsilon << std::endl;

    if( (uyh <= beta + conv_epsilon ) ){
      std::cout << "*********************************" << std::endl;
      std::cout << "Convergence ! at iteration: " << itr+1 << std::endl;
      std::cout << "*********************************" << std::endl;
      if(!end_of_cooc || need_to_cooc == true) break;
      need_to_cooc = true;
    }
      
    lpx_add_rows(lp,1); // Add one row constraint s.t. sum( uyh - beta ) <= 0
    for (unsigned int i = 0; i < gnum; ++i){
      index[i+1] = COL(i);
      value[i+1] = result[i] * corlab[i];
    }
    index[gnum+1] = COL(gnum);
    value[gnum+1] = -1;
    lpx_set_mat_row(lp, ROW(itr+1), gnum+1, index, value);
    lpx_set_row_bnds(lp, ROW(itr+1), LPX_UP, 0.0, 0.0);

    model.weight.push_back(0);
    model.dfs_vector.push_back(dfscode);
      
    lpx_simplex(lp); 
    beta = lpx_get_obj_val(lp);
    for (unsigned int i = 0; i < gnum; ++i){
      double new_weight;
      new_weight = lpx_get_col_prim(lp, COL(i));
      if(new_weight < 0) new_weight = 0; // weight > 0
      weight[i] = new_weight;
    }
    margin = lpx_get_row_dual(lp, ROW(0));
    double margin_error = 0.0;
    for (unsigned int i = 0; i < gnum;  ++i) { // summarizing hypotheses
      if (corlab[i]*result[i] < margin){
	++margin_error;
      }
    }
    margin_error /= gnum;

    //next rule is estimated
    wbias = 0.0;
    for (unsigned int i = 0; i < gnum; ++i){
      wbias += corlab[i] * weight[i];
    }
    std::ofstream os (out);
    if (! os) {
      std::cerr << "FATAL: Cannot open output file: " << out << std::endl;
      return;
    }
    os.setf(std::ios::fixed,std::ios::floatfield);
    os.precision(12);
    for (unsigned int r = 0; r < itr; ++r){
      model.weight[r] = - lpx_get_row_dual(lp, ROW(r+1));
      if(model.weight[r] < 0) model.weight[r] = 0; // alpha > 0
      os << model.flag[r] * model.weight[r] << "\t" << model.dfs_vector[r] << std::endl;
      std::cout << model.flag[r] * model.weight[r] << "\t" << model.dfs_vector[r] << std::endl;
    }
    std::cout << "After iteration " << itr+1 << std::endl;
    std::cout << "Margin: " << margin << std::endl;
    std::cout << "Margin Error: " << margin_error << std::endl;
  }
  std::cout << "end lpboost" << std::endl;

}
Ejemplo n.º 5
0
uint8_t matrix_scan(void)
{

    // scan code reading states
    static enum {
        INIT,
        E0,
        E0_2A,
        E0_2A_E0,
        E0_B7,
        E0_B7_E0,

        // print screen
        E1,
        E1_1D,
        E1_1D_45,
        E1_1D_45_E1,
        E1_1D_45_E1_9D,
        // pause
    } state = INIT;


    is_modified = false;

    // 'pseudo break code' hack
    if (matrix_is_on(ROW(PAUSE), COL(PAUSE))) {
        matrix_break(PAUSE);
    }

    uint8_t code = xt_host_recv();
    switch (state) {
        case INIT:
            switch (code) {
                case 0xE0:
                    state = E0;
                    break;
                case 0xE1:
                    state = E1;
                    break;
                default:    // normal key make
                    if (code < 0x80 && code != 0x00) {
                        xprintf("make: %X\r\n", code);
                        matrix_make(code);
                    } else if (code > 0x80 && code < 0xFF && code != 0x00) {
                        xprintf("break %X\r\n", code);
                        matrix_break(code - 0x80);
                    }
                    state = INIT;
            }
            break;
        case E0:    // E0-Prefixed
            switch (code) { //move these codes to unused places on the matrix
                case 0x2A:
                    state = E0_2A;
                    break;
                case 0xB7:
                    state = E0_B7;
                    break;
                default:
                    if (code < 0x80 && code != 0x00) {
                        matrix_make(move_codes(code));
                    } else if (code > 0x80 && code < 0xFF && code != 0x00) {
                        matrix_break(move_codes(code - 0x80));
                    }
                    state = INIT;
            }
            break;
        case E0_2A:
            if(code == 0xE0)
                state = E0_2A_E0;
            else
                state = INIT;
            break;
        case E0_2A_E0:
            if(code == 0x37)
                matrix_make(PRINT_SCREEN);
            else
                state = INIT;
            break;
        case E0_B7:
            if(code == 0xE0)
                state = E0_B7;
            else
                state = INIT;
            break;
        case E0_B7_E0:
          if(code == 0xAA)
              matrix_break(PRINT_SCREEN);
          else
              state = INIT;
          break;
        case E1:
            if (code == 0x1D)
                state = E1_1D;
            else
                state = INIT;
            break;
        case E1_1D:
            if(code == 0x45)
                state = E1_1D_45;
            else
                state = INIT;
            break;
        case E1_1D_45:
            if(code == 0xE1)
                state = E1_1D_45_E1;
            else
                state = INIT;
            break;
        case E1_1D_45_E1:
            if(code == 0x9D)
                state = E1_1D_45_E1_9D;
            else
                state = INIT;
            break;
        case E1_1D_45_E1_9D:
            if(code == 0xC5)
                matrix_make(PAUSE);
            else
                state = INIT;
            break;
        default:
            state = INIT;
    }
    return 1;
}
Ejemplo n.º 6
0
Archivo: clip.c Proyecto: descent/twin
static byte InitClip(void) {
    twindow Window;

    return
	TwCheckMagic(clip_magic) && TwOpen(NULL) &&
	(Clip_MsgPort=TwCreateMsgPort(11, "twclipboard")) &&
	(Clip_Menu=TwCreateMenu(
	  COL(BLACK,WHITE), COL(BLACK,GREEN), COL(HIGH|BLACK,WHITE), COL(HIGH|BLACK,BLACK),
	  COL(RED,WHITE), COL(RED,GREEN), (byte)0)) &&
	(TwInfo4Menu(Clip_Menu, TW_ROW_ACTIVE, 16, " Twin Clipboard ", "ptpppptppppppppp"),
	 (Clip_Win=TwCreateWindow
	  (14, "Twin Clipboard", NULL,
	   Clip_Menu, COL(HIGH|WHITE,HIGH|BLACK),
	   TW_LINECURSOR,
	   TW_WINDOW_WANT_KEYS|TW_WINDOW_DRAG|TW_WINDOW_RESIZE|TW_WINDOW_X_BAR|TW_WINDOW_Y_BAR|TW_WINDOW_CLOSE,
	   TW_WINDOWFL_CURSOR_ON|TW_WINDOWFL_ROWS_DEFCOL,
	   38, 18, 0))) &&
	(Window=TwWin4Menu(Clip_Menu)) &&
	TwRow4Menu(Window, COD_QUIT, TW_ROW_INACTIVE, 17, " Quit      Alt-X ") &&
	TwItem4Menu(Clip_Menu, Window, TRUE, 6, " File ") &&
	(TwSetColorsWindow
	 (Clip_Win, 0x1FF,
	  COL(HIGH|GREEN,WHITE), COL(CYAN,BLUE), COL(HIGH|BLUE,BLACK), COL(HIGH|WHITE,HIGH|BLUE), COL(HIGH|WHITE,HIGH|BLUE),
	  COL(HIGH|WHITE,HIGH|BLACK), COL(HIGH|BLACK,WHITE), COL(BLACK,HIGH|BLACK), COL(BLACK,WHITE)),
	 TwConfigureWindow(Clip_Win, 0xF<<2, 0, 0, 7, 3, MAXDAT, MAXDAT),
	 (Window=TwWin4Menu(Clip_Menu))) &&
	TwItem4Menu(Clip_Menu, Window, FALSE, 6, " Clip ") &&
	TwRow4Menu(Window, (udat)0, TW_ROW_INACTIVE,16, " Undo           ") &&
	TwRow4Menu(Window, (udat)0, TW_ROW_INACTIVE,16, " Redo           ") &&
	TwRow4Menu(Window, (udat)0, TW_ROW_IGNORE,  16, "컴컴컴컴컴컴컴컴") &&
	TwRow4Menu(Window, (udat)0, TW_ROW_ACTIVE,  16, " Cut            ") &&
	TwRow4Menu(Window, (udat)0, TW_ROW_ACTIVE,  16, " Copy           ") &&
	TwRow4Menu(Window, (udat)0, TW_ROW_ACTIVE,  16, " Paste          ") &&
	TwRow4Menu(Window, (udat)0, TW_ROW_ACTIVE,  16, " Clear          ") &&
	TwRow4Menu(Window, (udat)0, TW_ROW_IGNORE,  16, "컴컴컴컴컴컴컴컴") &&
	TwRow4Menu(Window, (udat)0, TW_ROW_INACTIVE,16, " Show Clipboard ") &&
	(Window=TwWin4Menu(Clip_Menu)) &&
	TwItem4Menu(Clip_Menu, Window, TRUE, 8, " Search ") &&
	TwRow4Menu(Window, (udat)0, TW_ROW_ACTIVE,  9, " Find    ") &&
	TwRow4Menu(Window, (udat)0, TW_ROW_ACTIVE,  9, " Replace ") &&
	TwItem4MenuCommon(Clip_Menu) &&
	(TwMapWindow(Clip_Win, TwFirstScreen()),
	 TwFlush());
}
Ejemplo n.º 7
0
image_s *
image_new_from_jpeg(const char * path, int is_file, const char * buf, int size, int scale, int rotate)
{
	image_s *vimage;
	FILE  *file = NULL;
	struct jpeg_decompress_struct cinfo;
	unsigned char *line[16], *ptr;
	int x, y, i, w, h, ofs;
	int maxbuf;
	struct jpeg_error_mgr pub;

	cinfo.err = jpeg_std_error(&pub);
	pub.error_exit = libjpeg_error_handler;
	jpeg_create_decompress(&cinfo);
	if( is_file )
	{
		if( (file = fopen(path, "r")) == NULL )
		{
			return NULL;
		}
		jpeg_stdio_src(&cinfo, file);
	}
	else
	{
		jpeg_memory_src(&cinfo, (const unsigned char *)buf, size);
	}
	if( setjmp(setjmp_buffer) )
	{
		jpeg_destroy_decompress(&cinfo);
		if( is_file && file )
			fclose(file);
		return NULL;
	}
	jpeg_read_header(&cinfo, TRUE);
	cinfo.scale_denom = scale;
	cinfo.do_fancy_upsampling = FALSE;
	cinfo.do_block_smoothing = FALSE;
	jpeg_start_decompress(&cinfo);
	w = cinfo.output_width;
	h = cinfo.output_height;
	vimage = (rotate & (ROTATE_90|ROTATE_270)) ? image_new(h, w) : image_new(w, h);
	if(!vimage)
	{
		jpeg_destroy_decompress(&cinfo);
		if( is_file )
			fclose(file);
		return NULL;
	}

	if( setjmp(setjmp_buffer) )
	{
		jpeg_destroy_decompress(&cinfo);
		if( is_file && file )
			fclose(file);
		if( vimage )
		{
			free(vimage->buf);
			free(vimage);
		}
		return NULL;
	}

	if(cinfo.rec_outbuf_height > 16)
	{
		DPRINTF(E_WARN, L_METADATA, "ERROR image_from_jpeg : (image_from_jpeg.c) JPEG uses line buffers > 16. Cannot load.\n");
		jpeg_destroy_decompress(&cinfo);
		image_free(vimage);
		if( is_file )
			fclose(file);
		return NULL;
	}
	maxbuf = vimage->width * vimage->height;
	if(cinfo.output_components == 3)
	{
		int rx, ry;
		ofs = 0;
		if((ptr = malloc(w * 3 * cinfo.rec_outbuf_height + 16)) == NULL)
		{
			DPRINTF(E_WARN, L_METADATA, "malloc failed\n");
			jpeg_destroy_decompress(&cinfo);
			image_free(vimage);
			if( is_file )
				fclose(file);
			return NULL;
		}

		for(y = 0; y < h; y += cinfo.rec_outbuf_height)
		{
			ry = (rotate & (ROTATE_90|ROTATE_180)) ? (y - h + 1) * -1 : y;
			for(i = 0; i < cinfo.rec_outbuf_height; i++)
			{
				line[i] = ptr + (w * 3 * i);
			}
			jpeg_read_scanlines(&cinfo, line, cinfo.rec_outbuf_height);
			for(x = 0; x < w * cinfo.rec_outbuf_height; x++)
			{
				rx = (rotate & (ROTATE_180|ROTATE_270)) ? (x - w + 1) * -1 : x;
				ofs = (rotate & (ROTATE_90|ROTATE_270)) ? ry + (rx * h) : rx + (ry * w);
				if( ofs < maxbuf )
					vimage->buf[ofs] = COL(ptr[x + x + x], ptr[x + x + x + 1], ptr[x + x + x + 2]);
			}
		}
		free(ptr);
	}
	else if(cinfo.output_components == 1)
	{
		ofs = 0;
		for(i = 0; i < cinfo.rec_outbuf_height; i++)
		{
			if((line[i] = malloc(w)) == NULL)
			{
				int t = 0;

				for(t = 0; t < i; t++) free(line[t]);
				jpeg_destroy_decompress(&cinfo);
				image_free(vimage);
				if( is_file )
					fclose(file);
				return NULL;
			}
		}
		for(y = 0; y < h; y += cinfo.rec_outbuf_height)
		{
			jpeg_read_scanlines(&cinfo, line, cinfo.rec_outbuf_height);
			for(i = 0; i < cinfo.rec_outbuf_height; i++)
			{
				for(x = 0; x < w; x++)
				{
					vimage->buf[ofs++] = COL(line[i][x], line[i][x], line[i][x]);
				}
			}
		}
		for(i = 0; i < cinfo.rec_outbuf_height; i++)
		{
			 free(line[i]);
		}
	}
	jpeg_finish_decompress(&cinfo);
	jpeg_destroy_decompress(&cinfo);
	if( is_file )
		fclose(file);

	return vimage;
}
	void DebugTerrainObjectVisualizer::visualizeTerrainObject(game::Game *game, UnifiedHandle terrainObject, const VC3 &cameraPosition, DebugTerrainObjectVisFlags visFlags)
	{
		char textbuf[128];

		assert(VALIDATE_UNIFIED_HANDLE_BITS(terrainObject));

		if (!game->unifiedHandleManager->doesObjectExist(terrainObject))
		{
			return;
		}

		VC3 cullpos = game->unifiedHandleManager->getObjectPosition(terrainObject);
		VC3 distToCamVec = cullpos - cameraPosition;
		// 2D RANGE
		distToCamVec.y = 0;
		float distToCamSq = distToCamVec.GetSquareLength();
		if (distToCamSq < (DEBUGTERRAINOBJECTVISUALIZER_MAX_DIST * DEBUGTERRAINOBJECTVISUALIZER_MAX_DIST))
		{
			// ok
		} else {
			return;
		}

		std::string fname = game->gameUI->getTerrain()->getTypeFilenameByUnifiedHandle(terrainObject);
		std::string fnamecut;
		for (int i = (int)fname.length() - 1; i >= 0; i--)
		{
			if (fname[i] == '\\')
			{
				fname[i] = '/';
			}
			if (fname[i] == '/')
			{
				if (fnamecut.empty())
				{
					fnamecut = fname.substr(i + 1, fname.length() - (i + 1));
				}
			}
		}

		const char *totypename = game::SimpleOptions::getString(DH_OPT_S_DEBUG_VISUALIZE_TERRAINOBJECTS_OF_NAME);
		if (totypename != NULL
			&& totypename[0] != '\0')
		{
			if (strstr(fname.c_str(), totypename) != NULL)
			{
				// ok
			} else {
				return;
			}
		}

		COL col = COL(0.5f,0.5f,1.0f);

		if (visFlags & DEBUGTERRAINOBJECTVISUALIZER_FLAG_SELECTED)
		{
			// ok with that color?
		} else {
			col.r = col.r / 2.0f;
			col.g = col.g / 2.0f;
			col.b = col.b / 2.0f;
		}

		/*
		VC3 pos = game->unifiedHandleManager->getObjectPosition(terrainObject);
		pos.y += 0.03f;

		VC3 sizes = VC3(1.00f, 1.00f, 1.00f);

		VC3 c1 = VC3(pos.x - sizes.x, pos.y + sizes.y, pos.z - sizes.z);
		VC3 c2 = VC3(pos.x + sizes.x, pos.y + sizes.y, pos.z - sizes.z);
		VC3 c3 = VC3(pos.x + sizes.x, pos.y + sizes.y, pos.z + sizes.z);
		VC3 c4 = VC3(pos.x - sizes.x, pos.y + sizes.y, pos.z + sizes.z);
		VC3 cb1 = VC3(pos.x - sizes.x, pos.y - sizes.y, pos.z - sizes.z);
		VC3 cb2 = VC3(pos.x + sizes.x, pos.y - sizes.y, pos.z - sizes.z);
		VC3 cb3 = VC3(pos.x + sizes.x, pos.y - sizes.y, pos.z + sizes.z);
		VC3 cb4 = VC3(pos.x - sizes.x, pos.y - sizes.y, pos.z + sizes.z);
		*/

		OOBB oobb = game->gameUI->getTerrain()->getOOBB(terrainObject);

		VC3 pos = oobb.center;

		VC3 c1 = pos - (oobb.axes[0] * oobb.extents.x) + (oobb.axes[1] * oobb.extents.y) - (oobb.axes[2] * oobb.extents.z);
		VC3 c2 = pos + (oobb.axes[0] * oobb.extents.x) + (oobb.axes[1] * oobb.extents.y) - (oobb.axes[2] * oobb.extents.z);
		VC3 c3 = pos + (oobb.axes[0] * oobb.extents.x) + (oobb.axes[1] * oobb.extents.y) + (oobb.axes[2] * oobb.extents.z);
		VC3 c4 = pos - (oobb.axes[0] * oobb.extents.x) + (oobb.axes[1] * oobb.extents.y) + (oobb.axes[2] * oobb.extents.z);
		VC3 cb1 = pos - (oobb.axes[0] * oobb.extents.x) - (oobb.axes[1] * oobb.extents.y) - (oobb.axes[2] * oobb.extents.z);
		VC3 cb2 = pos + (oobb.axes[0] * oobb.extents.x) - (oobb.axes[1] * oobb.extents.y) - (oobb.axes[2] * oobb.extents.z);
		VC3 cb3 = pos + (oobb.axes[0] * oobb.extents.x) - (oobb.axes[1] * oobb.extents.y) + (oobb.axes[2] * oobb.extents.z);
		VC3 cb4 = pos - (oobb.axes[0] * oobb.extents.x) - (oobb.axes[1] * oobb.extents.y) + (oobb.axes[2] * oobb.extents.z);

		/*
		VC3 pos = game->unifiedHandleManager->getObjectPosition(terrainObject);
		OOBB oobb = game->gameUI->getTerrain()->getOOBB(terrainObject);

		pos = oobb.center;

		VC3 sizes = oobb.extents;

		VC3 c1 = VC3(pos.x - sizes.x, pos.y + sizes.y, pos.z - sizes.z);
		VC3 c2 = VC3(pos.x + sizes.x, pos.y + sizes.y, pos.z - sizes.z);
		VC3 c3 = VC3(pos.x + sizes.x, pos.y + sizes.y, pos.z + sizes.z);
		VC3 c4 = VC3(pos.x - sizes.x, pos.y + sizes.y, pos.z + sizes.z);
		VC3 cb1 = VC3(pos.x - sizes.x, pos.y - sizes.y, pos.z - sizes.z);
		VC3 cb2 = VC3(pos.x + sizes.x, pos.y - sizes.y, pos.z - sizes.z);
		VC3 cb3 = VC3(pos.x + sizes.x, pos.y - sizes.y, pos.z + sizes.z);
		VC3 cb4 = VC3(pos.x - sizes.x, pos.y - sizes.y, pos.z + sizes.z);
		*/

		disposable_scene->AddLine(c1, c2, col);
		disposable_scene->AddLine(c2, c3, col);
		disposable_scene->AddLine(c3, c4, col);
		disposable_scene->AddLine(c4, c1, col);
		disposable_scene->AddLine(cb1, cb2, col);
		disposable_scene->AddLine(cb2, cb3, col);
		disposable_scene->AddLine(cb3, cb4, col);
		disposable_scene->AddLine(cb4, cb1, col);
		disposable_scene->AddLine(c1, cb1, col);
		disposable_scene->AddLine(c2, cb2, col);
		disposable_scene->AddLine(c3, cb3, col);
		disposable_scene->AddLine(c4, cb4, col);
		disposable_scene->AddLine(c4, cb4, col);

		int textoffy = 0;

		if (game::SimpleOptions::getBool(DH_OPT_B_DEBUG_VISUALIZE_TERRAINOBJECTS_EXTENDED)
			&& distToCamSq < (DEBUGTERRAINOBJECTVISUALIZER_EXTENDED_MAX_DIST * DEBUGTERRAINOBJECTVISUALIZER_EXTENDED_MAX_DIST))
		{
			sprintf(textbuf, "uh: %d", terrainObject);
			DebugVisualizerTextUtil::renderText(pos, 0, textoffy, textbuf);
			textoffy += 16;

			sprintf(textbuf, "filename: %s", fnamecut.c_str());
			DebugVisualizerTextUtil::renderText(pos, 0, textoffy, textbuf);
			textoffy += 16;
		}

	}
Ejemplo n.º 9
0
int evaluator::eval_orig(const node_t& board)
{
    int i;
    int f;  // file
    int score[2];  // each side's score

    f = i = 0;
    score[0] = score[1] = 0;

    // this is the first pass: set up pawn_rank, piece_mat, and pawn_mat.
    for (i = 0; i < 10; ++i) {
        pawn_rank[LIGHT][i] = 0;
        pawn_rank[DARK][i] = 7;
    }
    piece_mat[LIGHT] = 0;
    piece_mat[DARK] = 0;
    pawn_mat[LIGHT] = 0;
    pawn_mat[DARK] = 0;
    for (i = 0; i < 64; ++i) {
        if (board.color[i] == EMPTY)
            continue;
        if (board.piece[i] == PAWN) {
            pawn_mat[(int)board.color[i]] += piece_value[PAWN];
            f = COL(i) + 1;  // add 1 because of the extra file in the array
            if (board.color[i] == LIGHT) {
                if (pawn_rank[LIGHT][f] < ROW(i))
                    pawn_rank[LIGHT][f] = ROW(i);
            }
            else {
                if (pawn_rank[DARK][f] > ROW(i))
                    pawn_rank[DARK][f] = ROW(i);
            }
        }
        else
            piece_mat[(int)board.color[i]] += piece_value[(int)board.piece[i]];
    }

    // this is the second pass: evaluate each piece
    score[LIGHT] = piece_mat[LIGHT] + pawn_mat[LIGHT];
    score[DARK] = piece_mat[DARK] + pawn_mat[DARK];
    for (i = 0; i < 64; ++i) {
        if (board.color[i] == EMPTY)
            continue;
        if (board.color[i] == LIGHT) {
            switch (board.piece[i]) {
                case PAWN:
                    score[LIGHT] += eval_light_pawn(i);
                    break;
                case KNIGHT:
                    score[LIGHT] += knight_pcsq[i];
                    break;
                case BISHOP:
                    score[LIGHT] += bishop_pcsq[i];
                    break;
                case ROOK:
                    if (pawn_rank[LIGHT][COL(i) + 1] == 0) {
                        if (pawn_rank[DARK][COL(i) + 1] == 7)
                            score[LIGHT] += ROOK_OPEN_FILE_BONUS;
                        else
                            score[LIGHT] += ROOK_SEMI_OPEN_FILE_BONUS;
                    }
                    if (ROW(i) == 1)
                        score[LIGHT] += ROOK_ON_SEVENTH_BONUS;
                    break;
                case KING:
                    if (piece_mat[DARK] <= 1200)
                        score[LIGHT] += king_endgame_pcsq[i];
                    else
                        score[LIGHT] += eval_light_king(i);
                    break;
            }
        }
        else {
            switch (board.piece[i]) {
                case PAWN:
                    score[DARK] += eval_dark_pawn(i);
                    break;
                case KNIGHT:
                    score[DARK] += knight_pcsq[flip[i]];
                    break;
                case BISHOP:
                    score[DARK] += bishop_pcsq[flip[i]];
                    break;
                case ROOK:
                    if (pawn_rank[DARK][COL(i) + 1] == 7) {
                        if (pawn_rank[LIGHT][COL(i) + 1] == 0)
                            score[DARK] += ROOK_OPEN_FILE_BONUS;
                        else
                            score[DARK] += ROOK_SEMI_OPEN_FILE_BONUS;
                    }
                    if (ROW(i) == 6)
                        score[DARK] += ROOK_ON_SEVENTH_BONUS;
                    break;
                case KING:
                    if (piece_mat[LIGHT] <= 1200)
                        score[DARK] += king_endgame_pcsq[flip[i]];
                    else
                        score[DARK] += eval_dark_king(i);
                    break;
            }
        }
    }

    /* the score[] array is set, now return the score relative
       to the side to chess_move */
    if (board.side == LIGHT)
        return score[LIGHT] - score[DARK];
    return score[DARK] - score[LIGHT];
}
Ejemplo n.º 10
0
/* ---------------------------------------------------------------------------------------
	char *get_move(CHESS_STATE *current_state, int ui_flag)
	
	purpose: gets the movetext for a chess state
	
	Notes: if ui_flag!=0, the MoveTextUI string is returned.   
		   This routine checks all bitboards.
		   Move is valid if:
		   1. Maximum of 1 piece moves
		   2. Exception to #1 above is castling
		   3. Maximum of 1 piece removed

	The full move is either normal text or UI text
	normal text, eg xe3 (pawn captures piece at e3)
	UI text , eg d2:e3 e3:P (black pawn captures white pawn at e3)
	
	when ui_text==0, the standard algebraic chess notation
	for the move is returned. This is the abbreviated form
	UNLESS an explicit representation is required, in order
	of:
	1. specific rank qualifier
	2. specific row qualifier
	3. specific exact starting square
	
	Special treatment required for:
	1. en passant moves
		   	
--------------------------------------------------------------------------------------- */
char *get_move(CHESS_STATE *current_state, int ui_flag)
{
	// full move
	char *move = malloc(20 * sizeof (char));
	memset(move,0,20);

	char from_str[3] = {0};
	char to_str[3] = {0};
	char captured_str[2] = {0};
	char enpassant_suffix[5]={0};
		
	int number_moved = 0;		// number of pieces moved - normally = 1
	int number_captured = 0;	// number of pieces captured - <=1
	int number_friendly_captured = 0;	// pawn promotion
	int number_new = 0;			// number of new pieces (pawn promotion)
	int captured_piece = 0;		// captured piece index
	int friendly_captured_piece = 0; // the pawn 'removed'
	int moved_piece=0;			// moving piece index
	int new_piece=0;			// the new piece (normally queen for promoted pawn)

	int explicit_row = 0;	// flags to denote explicit move text
	int explicit_col = 0;	// flags to denote explicit move text
	
	CHESS_STATE* parent = current_state->parent;
	
	// the color of the moving piece is the 'parent' move.
	// the current state is the 'position' after the move, where
	// the other piece has become the active color.
	COLOR_ENUM bb_color = (parent->flg_is_white_move) ? BB_WHITE : BB_BLACK;

	int i;
	for (i=0; i<BB_COUNT; i++)
	{
		if (parent->boards[i] != current_state->boards[i])
		{
			bitboard delta = (parent->boards[i])^
				(current_state->boards[i]);
			bitboard from = parent->boards[i] & delta;
			bitboard to = current_state->boards[i] & delta;
			
			if (bit_count(to) == bit_count(from))
			{
				// moved
				number_moved += bit_count(to);
				if (number_moved > 1)
				{
					printf("Too may pieces Moved !");
					abort();
				}
				
				moved_piece=i;
				
				// at this point, see if any other moves from same
				// parent state involve the same piece type moving
				// to the same finishing square
				CHESS_STATE *other_states;
				for (other_states = current_state->parent->child_head;
					other_states!=NULL;
					other_states=other_states->next)
				{
					if (other_states!=current_state)
					{
						//see if other state shares similar move:
						bitboard other_delta = (parent->boards[i])^
							(other_states->boards[i]);
						bitboard other_from = parent->boards[i] & other_delta;
						bitboard other_to = current_state->boards[i] & other_delta;

						if (other_to==to && other_from != from)	// other move cannot start from same square !
						{
							// another move DOES share the same finishing square
							explicit_row += 
								((ROW(floor_log2(from))==(ROW(floor_log2(other_from)))));
							explicit_col +=
								((COL(floor_log2(from))==(COL(floor_log2(other_from)))));
						}														
					}
				}				

				// special treatment #1 (en passant)
				if (moved_piece-bb_color==BB_PAWN &&
					parent->flg_is_enpassant==1 &&
					to == (parent->flg_enpassant_file + (bb_color==BB_WHITE?A6:A3)))
				{
					explicit_col += 1;
					strcpy(enpassant_suffix,"e.p.");
				}
								
				strcpy(from_str,get_square_text(floor_log2(from)));
				strcpy(to_str,get_square_text(floor_log2(to)));
			}
			else if (bit_count(from)>0 && i != (bb_color+BB_PAWN))
			{
				// captured (opponents only) - excluding pawn promotion
				number_captured +=  bit_count(from);
				if (number_captured > 1)
				{
					printf("more than one piece captured");					
					exit(1);
				}
				captured_piece=i;
				strcpy(captured_str,"x");
			}
			else if (bit_count(from) > 0)
			{
				// friendly pawn removed for pawn promotion
				number_friendly_captured +=  bit_count(from);
				if (number_friendly_captured > 1)
				{
					printf("more than one friendly piece captured");					
					exit(1);
				}
				friendly_captured_piece = i;
				strcpy(from_str,get_square_text(floor_log2(from)));
			}
			
			else if (bit_count(to) > 0)
			{
				// pawn_promotion
				number_new += bit_count(to);
				if (number_new > 1)
				{
					printf("more than one new piece");					
					exit(1);
				}
				new_piece = i;
				strcpy(to_str,get_square_text(floor_log2(to)));
			}
		}
	}

	// 1. piece moving (normal text)
	if (ui_flag==0 && moved_piece % 6 != BB_PAWN)
		move[0] = piece_chr[moved_piece];
	
	// 2. from square
	if (ui_flag!=0)
		strcat(move,from_str);
	else
	{
		if (explicit_col!=0)
			strncat(move,&from_str[0],1);
	
		if (explicit_row!=0)
			strncat(move,&from_str[1],1);
	}

	// 3. capture string or ':'
	if (ui_flag==0)
		if (number_captured>0)
			strcat(move, captured_str);
		else {}
	else
	{
		strcat(move, ":");
	}

	// 4. to square
	strcat(move,to_str);
	
	// 5. en passant suffix
	if (ui_flag==0)
		strcat(move,enpassant_suffix);

	// 6. piece to delete (UI text only)
	if (ui_flag!=0 && number_captured>0)
	{
		strcat(move," ");
		strcat(move,to_str);
		strcat(move,":");
		move[strlen(move)] = piece_chr[captured_piece];
	}		

	// 7. pawn promotion
	if (ui_flag==0 && number_new > 0)
	{
		move[strlen(move)] = piece_chr[new_piece];
	}

	if (ui_flag!=0 && number_new > 0)
	{
		// pawn
		strcat(move," ");
		strcat(move,from_str);
		strcat(move,":");
		move[strlen(move)] = piece_chr[friendly_captured_piece];
		
		//queen
		strcat(move," ");
		strcat(move,to_str);
		strcat(move,":");
		move[strlen(move)] = piece_chr[new_piece];
	}
		
	return move;
}
Ejemplo n.º 11
0
void flandmark_argmax(double *smax, FLANDMARK_Options *options, const int *mapTable, FLANDMARK_PSI_SPARSE *Psi_sparse, double **q, double **g)
{
    uint8_t M = options->M;

    // compute argmax
    int * indices = (int*)malloc(M*sizeof(int));
    int tsize = mapTable[INDEX(1, 3, M)] - mapTable[INDEX(1, 2, M)] + 1;

    // left branch - store maximum and index of s5 for all positions of s1
    int q1_length = Psi_sparse[1].PSI_COLS;

    double * s1 = (double *)calloc(2*q1_length, sizeof(double));
    double * s1_maxs = (double *)calloc(q1_length, sizeof(double));
    for (int i = 0; i < q1_length; ++i)
    {
        // dot product <g_5, PsiGS1>
        flandmark_maximize_gdotprod(
                //s2_maxs, s2_idxs,
                &s1[INDEX(0, i, 2)], (double*)&s1[INDEX(1, i, 2)],
                q[5], g[4], options->PsiGS1[INDEX(i, 0, options->PSIG_ROWS[1])].disp,
                options->PsiGS1[INDEX(i, 0, options->PSIG_ROWS[1])].COLS, tsize
                );
        s1[INDEX(0, i, 2)] += q[1][i];
    }
    for (int i = 0; i < q1_length; ++i)
    {
        s1_maxs[i] = s1[INDEX(0, i, 2)];
    }

    // right branch (s2->s6) - store maximum and index of s6 for all positions of s2
    int q2_length = Psi_sparse[2].PSI_COLS;
    double * s2 = (double *)calloc(2*q2_length, sizeof(double));
    double * s2_maxs = (double *)calloc(q2_length, sizeof(double));
    for (int i = 0; i < q2_length; ++i)
    {
        // dot product <g_6, PsiGS2>
        flandmark_maximize_gdotprod(
                //s2_maxs, s2_idxs,
                &s2[INDEX(0, i, 2)], (double*)&s2[INDEX(1, i, 2)],
                q[6], g[5], options->PsiGS2[INDEX(i, 0, options->PSIG_ROWS[2])].disp,
                options->PsiGS2[INDEX(i, 0, options->PSIG_ROWS[2])].COLS, tsize);
        s2[INDEX(0, i, 2)] += q[2][i];
    }
    for (int i = 0; i < q2_length; ++i)
    {
        s2_maxs[i] = s2[INDEX(0, i, 2)];
    }

    // the root s0 and its connections
    int q0_length = Psi_sparse[0].PSI_COLS;
    double maxs0 = -FLT_MAX; int maxs0_idx = -1;
    double maxq10 = -FLT_MAX, maxq20 = -FLT_MAX, maxq30 = -FLT_MAX, maxq40 = -FLT_MAX, maxq70 = -FLT_MAX;
    double * s0 = (double *)calloc(M*q0_length, sizeof(double));
    for (int i = 0; i < q0_length; ++i)
    {
        // q10
        maxq10 = -FLT_MAX;
        flandmark_maximize_gdotprod(
                &maxq10, &s0[INDEX(1, i, M)],
                s1_maxs, g[0], options->PsiGS0[INDEX(i, 0, options->PSIG_ROWS[0])].disp,
                options->PsiGS0[INDEX(i, 0, options->PSIG_ROWS[0])].COLS, tsize);
        s0[INDEX(5, i, M)] = s1[INDEX(1, (int)s0[INDEX(1, i, M)], 2)];
        // q20
        maxq20 = -FLT_MAX;
        flandmark_maximize_gdotprod(
                &maxq20, &s0[INDEX(2, i, M)],
                s2_maxs, g[1], options->PsiGS0[INDEX(i, 1, options->PSIG_ROWS[0])].disp,
                options->PsiGS0[INDEX(i, 1, options->PSIG_ROWS[0])].COLS, tsize);
        s0[INDEX(6, i, M)] = s2[INDEX(1, (int)s0[INDEX(2, i, M)], 2)];
        // q30
        maxq30 = -FLT_MAX;
        flandmark_maximize_gdotprod(
                &maxq30, &s0[INDEX(3, i, M)],
                q[3], g[2], options->PsiGS0[INDEX(i, 2, options->PSIG_ROWS[0])].disp,
                options->PsiGS0[INDEX(i, 2, options->PSIG_ROWS[0])].COLS, tsize);
        // q40
        maxq40 = -FLT_MAX;
        flandmark_maximize_gdotprod(
                &maxq40, &s0[INDEX(4, i, M)],
                q[4], g[3], options->PsiGS0[INDEX(i, 3, options->PSIG_ROWS[0])].disp,
                options->PsiGS0[INDEX(i, 3, options->PSIG_ROWS[0])].COLS, tsize);
        // q70
        maxq70 = -FLT_MAX;
        flandmark_maximize_gdotprod(
                &maxq70, &s0[INDEX(7, i, M)],
                q[7], g[6], options->PsiGS0[INDEX(i, 4, options->PSIG_ROWS[0])].disp,
                options->PsiGS0[INDEX(i, 4, options->PSIG_ROWS[0])].COLS, tsize);
        // sum q10+q20+q30+q40+q70
        if (maxs0 < maxq10+maxq20+maxq30+maxq40+maxq70+q[0][i])
        {
            maxs0_idx = i;
            s0[INDEX(0, i, M)] = i;
            maxs0 = maxq10+maxq20+maxq30+maxq40+maxq70+q[0][i];
        }
    }

    // get indices
    for (int i = 0; i < M; ++i)
    {
        indices[i] = (int)s0[INDEX(0, maxs0_idx, M)+i]+1;
    }

    // cleanup temp variables
    free(s0);
    free(s1); free(s1_maxs);
    free(s2); free(s2_maxs);

    // convert 1D indices to 2D coordinates of estimated positions
    //int * optionsS = &options->S[0];
    const int * optionsS = options->S;
    for (int i = 0; i < M; ++i)
    {
        int rows = optionsS[INDEX(3, i, 4)] - optionsS[INDEX(1, i, 4)] + 1;
        smax[INDEX(0, i, 2)] = float(COL(indices[i], rows) + optionsS[INDEX(0, i, 4)]);
        smax[INDEX(1, i, 2)] = float(ROW(indices[i], rows) + optionsS[INDEX(1, i, 4)]);
    }
    free(indices);
}
Ejemplo n.º 12
0
/*
 * PS/2 Scan Code Set 2: Exceptional Handling
 *
 * There are several keys to be handled exceptionally.
 * The scan code for these keys are varied or prefix/postfix'd
 * depending on modifier key state.
 *
 * Keyboard Scan Code Specification:
 *     http://www.microsoft.com/whdc/archive/scancode.mspx
 *     http://download.microsoft.com/download/1/6/1/161ba512-40e2-4cc9-843a-923143f3456c/scancode.doc
 *
 *
 * 1) Insert, Delete, Home, End, PageUp, PageDown, Up, Down, Right, Left
 *     a) when Num Lock is off
 *     modifiers | make                      | break
 *     ----------+---------------------------+----------------------
 *     Ohter     |                    <make> | <break>
 *     LShift    | E0 F0 12           <make> | <break>  E0 12
 *     RShift    | E0 F0 59           <make> | <break>  E0 59
 *     L+RShift  | E0 F0 12  E0 F0 59 <make> | <break>  E0 59 E0 12
 *
 *     b) when Num Lock is on
 *     modifiers | make                      | break
 *     ----------+---------------------------+----------------------
 *     Other     | E0 12              <make> | <break>  E0 F0 12
 *     Shift'd   |                    <make> | <break>
 *
 *     Handling: These prefix/postfix codes are ignored.
 *
 *
 * 2) Keypad /
 *     modifiers | make                      | break
 *     ----------+---------------------------+----------------------
 *     Ohter     |                    <make> | <break>
 *     LShift    | E0 F0 12           <make> | <break>  E0 12
 *     RShift    | E0 F0 59           <make> | <break>  E0 59
 *     L+RShift  | E0 F0 12  E0 F0 59 <make> | <break>  E0 59 E0 12
 *
 *     Handling: These prefix/postfix codes are ignored.
 *
 *
 * 3) PrintScreen
 *     modifiers | make         | break
 *     ----------+--------------+-----------------------------------
 *     Other     | E0 12  E0 7C | E0 F0 7C  E0 F0 12
 *     Shift'd   |        E0 7C | E0 F0 7C
 *     Control'd |        E0 7C | E0 F0 7C
 *     Alt'd     |           84 | F0 84
 *
 *     Handling: These prefix/postfix codes are ignored, and both scan codes
 *               'E0 7C' and 84 are seen as PrintScreen.
 *
 * 4) Pause
 *     modifiers | make(no break code)
 *     ----------+--------------------------------------------------
 *     Other     | E1 14 77 E1 F0 14 F0 77
 *     Control'd | E0 7E E0 F0 7E
 *
 *     Handling: Both code sequences are treated as a whole.
 *               And we need a ad hoc 'pseudo break code' hack to get the key off
 *               because it has no break code.
 *
 */
uint8_t matrix_scan(void)
{

    // scan code reading states
    static enum {
        INIT,
        F0,
        E0,
        E0_F0,
        // Pause
        E1,
        E1_14,
        E1_14_77,
        E1_14_77_E1,
        E1_14_77_E1_F0,
        E1_14_77_E1_F0_14,
        E1_14_77_E1_F0_14_F0,
        // Control'd Pause
        E0_7E,
        E0_7E_E0,
        E0_7E_E0_F0,
    } state = INIT;


    is_modified = false;

    // 'pseudo break code' hack
    if (matrix_is_on(ROW(PAUSE), COL(PAUSE))) {
        matrix_break(PAUSE);
    }

    uint8_t code = ps2_host_recv();
    if (code) xprintf("%i\r\n", code);
    if (!ps2_error) {
        switch (state) {
            case INIT:
                switch (code) {
                    case 0xE0:
                        state = E0;
                        break;
                    case 0xF0:
                        state = F0;
                        break;
                    case 0xE1:
                        state = E1;
                        break;
                    case 0x83:  // F7
                        matrix_make(F7);
                        state = INIT;
                        break;
                    case 0x84:  // Alt'd PrintScreen
                        matrix_make(PRINT_SCREEN);
                        state = INIT;
                        break;
                    case 0x00:  // Overrun [3]p.25
                        matrix_clear();
                        clear_keyboard();
                        print("Overrun\n");
                        state = INIT;
                        break;
                    default:    // normal key make
                        if (code < 0x80) {
                            matrix_make(code);
                        } else {
                            matrix_clear();
                            clear_keyboard();
                            xprintf("unexpected scan code at INIT: %02X\n", code);
                        }
                        state = INIT;
                }
                break;
            case E0:    // E0-Prefixed
                switch (code) {
                    case 0x12:  // to be ignored
                    case 0x59:  // to be ignored
                        state = INIT;
                        break;
                    case 0x7E:  // Control'd Pause
                        state = E0_7E;
                        break;
                    case 0xF0:
                        state = E0_F0;
                        break;
                    default:
                        if (code < 0x80) {
                            matrix_make(code|0x80);
                        } else {
                            matrix_clear();
                            clear_keyboard();
                            xprintf("unexpected scan code at E0: %02X\n", code);
                        }
                        state = INIT;
                }
                break;
            case F0:    // Break code
                switch (code) {
                    case 0x83:  // F7
                        matrix_break(F7);
                        state = INIT;
                        break;
                    case 0x84:  // Alt'd PrintScreen
                        matrix_break(PRINT_SCREEN);
                        state = INIT;
                        break;
                    case 0xF0:
                        matrix_clear();
                        clear_keyboard();
                        xprintf("unexpected scan code at F0: F0(clear and cont.)\n");
                        break;
                    default:
                    if (code < 0x80) {
                        matrix_break(code);
                    } else {
                        matrix_clear();
                        clear_keyboard();
                        xprintf("unexpected scan code at F0: %02X\n", code);
                    }
                    state = INIT;
                }
                break;
            case E0_F0: // Break code of E0-prefixed
                switch (code) {
                    case 0x12:  // to be ignored
                    case 0x59:  // to be ignored
                        state = INIT;
                        break;
                    default:
                        if (code < 0x80) {
                            matrix_break(code|0x80);
                        } else {
                            matrix_clear();
                            clear_keyboard();
                            xprintf("unexpected scan code at E0_F0: %02X\n", code);
                        }
                        state = INIT;
                }
                break;
            // following are states of Pause
            case E1:
                switch (code) {
                    case 0x14:
                        state = E1_14;
                        break;
                    default:
                        state = INIT;
                }
                break;
            case E1_14:
                switch (code) {
                    case 0x77:
                        state = E1_14_77;
                        break;
                    default:
                        state = INIT;
                }
                break;
            case E1_14_77:
                switch (code) {
                    case 0xE1:
                        state = E1_14_77_E1;
                        break;
                    default:
                        state = INIT;
                }
                break;
            case E1_14_77_E1:
                switch (code) {
                    case 0xF0:
                        state = E1_14_77_E1_F0;
                        break;
                    default:
                        state = INIT;
                }
                break;
            case E1_14_77_E1_F0:
                switch (code) {
                    case 0x14:
                        state = E1_14_77_E1_F0_14;
                        break;
                    default:
                        state = INIT;
                }
                break;
            case E1_14_77_E1_F0_14:
                switch (code) {
                    case 0xF0:
                        state = E1_14_77_E1_F0_14_F0;
                        break;
                    default:
                        state = INIT;
                }
                break;
            case E1_14_77_E1_F0_14_F0:
                switch (code) {
                    case 0x77:
                        matrix_make(PAUSE);
                        state = INIT;
                        break;
                    default:
                        state = INIT;
                }
                break;
            // Following are states of Control'd Pause
            case E0_7E:
                if (code == 0xE0)
                    state = E0_7E_E0;
                else
                    state = INIT;
                break;
            case E0_7E_E0:
                if (code == 0xF0)
                    state = E0_7E_E0_F0;
                else
                    state = INIT;
                break;
            case E0_7E_E0_F0:
                if (code == 0x7E)
                    matrix_make(PAUSE);
                state = INIT;
                break;
            default:
                state = INIT;
        }
    }

    // TODO: request RESEND when error occurs?
/*
    if (PS2_IS_FAILED(ps2_error)) {
        uint8_t ret = ps2_host_send(PS2_RESEND);
        xprintf("Resend: %02X\n", ret);
    }
*/
    return 1;
}
Ejemplo n.º 13
0
void gen_moves()
{
	int i, j, n;

	/* so far, we have no moves for the current ply */
	first_move[ply + 1] = first_move[ply];

	for (i = 0; i < 64; ++i)
		if (color[i] == side) {
			if (piece[i] == PAWN) {
				if (side == LIGHT) {
					if (COL(i) != 0 && color[i - 9] == DARK)
						gen_push(i, i - 9, 17);
					if (COL(i) != 7 && color[i - 7] == DARK)
						gen_push(i, i - 7, 17);
					if (color[i - 8] == EMPTY) {
						gen_push(i, i - 8, 16);
						if (i >= 48 && color[i - 16] == EMPTY)
							gen_push(i, i - 16, 24);
					}
				}
				else {
					if (COL(i) != 0 && color[i + 7] == LIGHT)
						gen_push(i, i + 7, 17);
					if (COL(i) != 7 && color[i + 9] == LIGHT)
						gen_push(i, i + 9, 17);
					if (color[i + 8] == EMPTY) {
						gen_push(i, i + 8, 16);
						if (i <= 15 && color[i + 16] == EMPTY)
							gen_push(i, i + 16, 24);
					}
				}
			}
			else
				for (j = 0; j < offsets[piece[i]]; ++j)
					for (n = i;;) {
						n = mailbox[mailbox64[n] + offset[piece[i]][j]];
						if (n == -1)
							break;
						if (color[n] != EMPTY) {
							if (color[n] == xside)
								gen_push(i, n, 1);
							break;
						}
						gen_push(i, n, 0);
						if (!slide[piece[i]])
							break;
					}
		}

	/* generate castle moves */
	if (side == LIGHT) {
		if (castle & 1)
			gen_push(E1, G1, 2);
		if (castle & 2)
			gen_push(E1, C1, 2);
	}
	else {
		if (castle & 4)
			gen_push(E8, G8, 2);
		if (castle & 8)
			gen_push(E8, C8, 2);
	}
	
	/* generate en passant moves */
	if (ep != -1) {
		if (side == LIGHT) {
			if (COL(ep) != 0 && color[ep + 7] == LIGHT && piece[ep + 7] == PAWN)
				gen_push(ep + 7, ep, 21);
			if (COL(ep) != 7 && color[ep + 9] == LIGHT && piece[ep + 9] == PAWN)
				gen_push(ep + 9, ep, 21);
		}
		else {
			if (COL(ep) != 0 && color[ep - 9] == DARK && piece[ep - 9] == PAWN)
				gen_push(ep - 9, ep, 21);
			if (COL(ep) != 7 && color[ep - 7] == DARK && piece[ep - 7] == PAWN)
				gen_push(ep - 7, ep, 21);
		}
	}
}