Esempio n. 1
0
int g1_client_class::prepare_command(int command)
{
    g1_global_id.poll();
    switch (state)
    {
    case SYNCING:
    case LOADING:
    {
        state=SYNCING;
        PACKET(sp,r);
        r.write_8(G1_PK_LOADING_DONE);
        i4_warning("We are ready to start.");
        send_server(sp,&r);
    }
    return NE_ERROR_NOTREADY;

    case RUNNING:
    {
        if (!network_file)
        {
            network_file=new i4_temp_file_class(2000,2000);
        }

        switch (command)
        {
        case G1_PK_GAME_DATA:
        {
            network_file->clear();
            network_file->write_8(command);
            network_file->write_32(0); //placeholder for length
            network_file->write_32(g1_tick_counter);

        }
        break;
        case G1_PK_PROCESS:
        {
            send_server(network_file->get_buffer(),network_file);
            network_file->clear();
            network_file->write_8(G1_PK_GAME_DATA);
            network_file->write_32(0);
            network_file->write_32(g1_tick_counter);
        }
        break;
        }
    }
    break;
    }
    if (!g1_global_id.is_ready())
    {
        return NE_ERROR_NOTREADY;
    }
    return NE_ERROR_OK;
}
Esempio n. 2
0
int	readGrid(char *grid, int fd)
{
  int	check;
  bool	start;
  int	check_read;
  char	*tmp;

  check = -1;
  start = true;
  while (check)
    {
      if (socket_send(fd, "Hello") || !(tmp = socket_read(fd)) ||
	  strncmp(tmp, "OK", 2) != 0 ||
	  (check_read = readOneGrid(grid, &check, start)) == 1)
	return (disconnect_error(fd));
      free(tmp);
      if (check_read == 2 && send_server(grid, fd))
	return (1);
      if (start)
	start = false;
    }
  if (socket_send(fd, "ByeBye") ||
      !(tmp = socket_read(fd)) || close(fd) < 0)
    return (1);
  free(tmp);
  return (0);
}
Esempio n. 3
0
void
sample(const struct metrics *s)
{
    double timestamp = (s->timestamp - starttsc) / gbl.hz;
    double duration = s->duration / gbl.hz;
    double ibw = s->instrs / duration;
    double vibw = s->vinstrs / duration;
    double rbw = s->rbytes / duration;
    double wbw = s->wbytes / duration;
    double vbw = s->vpu_ea / duration;
    double data[nfields], outdata[nfields];


    if (duration < .01)
        return;
    data[fTime] = timestamp;
    data[fThreads] = s->nthreads;
    data[fInst] = ibw;
    data[fVPU] = vibw;
    data[fMem] = rbw + wbw;
    data[fVpuSP] = vbw;
    data[fVpuDP] = vbw;

    char buffer[1024];
    buffer[1023] = 0;
    buffer[0] = 0;
    bool first = true;
    for (int i = 0; i < nfields; ++i)
    {
        if (first)
            first = false;
        else
            strncat(buffer, ",", sizeof(buffer)-1);
        snprintf(buffer+strlen(buffer), sizeof(buffer)-1, "%g", data[i]);
    }
    strncat(buffer, "\n", sizeof(buffer)-1);
    if (outfile)
        fputs(buffer, outfile);
    else if (gbl.server)
        send_server("%s", buffer);

    /* Compute summary information */
    if (s->nthreads <= 4)
        summ.tserial += s->duration / gbl.hz;
    else
    {
        summ.pcount += 1;
        summ.threads += s->nthreads;
        summ.tparallel += duration;
        summ.rbytes += s->rbytes;
        summ.wbytes += s->wbytes;
        summ.vpu_ea += s->vpu_ea;
        summ.instrs += s->instrs;
        summ.vinstrs += s->vinstrs;
        summ.ncores += s->ncores;
    }
}
Esempio n. 4
0
void
sample(const struct metrics *s)
{
    double timestamp = (s->timestamp - starttsc) / gbl.hz;
    double duration = s->duration / gbl.hz;
    double ibw = s->instrs / duration;
    double rbw = s->rbytes / duration;
    double wbw = s->wbytes / duration;
    double dflops, sflops;
    double data[nfields];

    if (duration < .01)
        return;
    dflops =  (s->dsimd * 4 + s->dsse * 2 + s->dscalar) / duration;
    sflops =  (s->ssimd * 8 + s->ssse * 4 + s->sscalar) / duration;
    data[fTime] = timestamp;
    data[fThreads] = s->nthreads;
    data[fInst] = ibw;
    data[fMem] = rbw + wbw;
    data[fFlopsSP] = sflops;
    data[fFlopsDP] = dflops;

    char buffer[1024];
    buffer[1023] = 0;
    buffer[0] = 0;
    bool first = true;
    for (int i = 0; i < nfields; ++i)
    {
        if (first)
            first = false;
        else
            strncat(buffer, ",", sizeof(buffer)-1);
        int field = hdrIndexes[i];
        if (field != fTime && field != fThreads &&
            data[field] > 1.5*labels[field].max)
            data[i] = 0;        // saw this on SNB with FP...
        snprintf(buffer+strlen(buffer), sizeof(buffer)-1, "%g", data[i]);
    }
    strncat(buffer, "\n", sizeof(buffer)-1);
    if (outfile)
        fputs(buffer, outfile);
    else if (gbl.server)
        send_server("%s", buffer);

    /* Compute summary information */
    if (s->nthreads <= 2)
        summ.tserial += s->duration / gbl.hz;
    else
    {
        summ.pcount += 1;
        summ.threads += s->nthreads;
        summ.tparallel += duration;
        summ.instrs += s->instrs;
        summ.dsimd += s->dsimd;
        summ.dsse += s->dsse;
        summ.dscalar += s->dscalar;
        summ.ssimd += s->ssimd;
        summ.ssse += s->ssse;
        summ.sscalar += s->sscalar;
        summ.rbytes += s->rbytes;
        summ.wbytes += s->wbytes;
        summ.ncores += s->ncores;
    }
}
Esempio n. 5
0
i4_bool g1_client_class::poll()  // returns false if server is not responding
{
    if (!listen || !send)
    {
        return 0;
    }


    if (state==JOIN_START)
    {
        i4_time_class now;
        if (now.milli_diff(last_responce_time)>40000)  // if it's been 40 secs assume server dead
        {
            i4_message_box("Server not responding","The server is not responding any more. ",MSG_OK);
            return i4_F;
        }


        w8 packet[512];
        i4_ram_file_class r(packet, sizeof(packet));

        r.write_8(G1_PK_I_WANNA_JOIN);
        r.write_16(use_port);
        r.write_counted_str(*g1_resources.username);

        if (!send->write(packet, r.tell()))
        {
            return i4_F;
        }

    }
    if (state==SYNCING) //set from the main loop as soon as the map is loaded
    {
        PACKET(pack,fp); //we just resend this message till we get the matching reply
        fp.write_8(G1_PK_LOADING_DONE);
        send_server(pack,&fp);
    }

    int noloops=0;
    while (listen->ready_to_read() && noloops<10)
    {
        w8 packet[MAX_PACKET_SIZE];
        i4_net_address * a;
        int s=listen->read_from(packet, sizeof(packet), a);
        if (a->equals(server_address))
        {
            i4_ram_file_class r(packet, sizeof(packet));

            w8 new_message=r.read_8();
            switch (new_message)
            {
            case G1_PK_YOU_HAVE_JOINED:
            {
                player_num=(w8)r.read_16();

                if (map_name)
                {
                    delete map_name;
                }
                map_name=r.read_counted_str();
                i4_warning("We were accepted by the server to join");
                state=CONNECTING;
                last_responce_time.get();
            }
            break;
            case G1_PK_WE_ARE_STARTING:
            {
                num_players=r.read_32();
                if (state==CONNECTING)
                {
                    i4_warning("Loading game data");
                    //don't do this twice.
                    //i4_user_message_event_class u(G1_START_NEW_GAME);
                    i4_file_open_message_class u(G1_SAVEGAME_LOAD_OK, new i4_str (* map_name));
                    i4_kernel.send_event(i4_current_app, &u);
                    state=LOADING;
                }
                //li_call("hide_main_menu");
            }
            break;
            case G1_PK_GAME_START:
            {
                //from now on, it's the main loops task to know that
                //this is a net game
                if (state!=RUNNING)
                {
                    int num_ais=r.read_32();
                    if (num_ais>G1_MAX_PLAYERS)
                    {
                        i4_error("ERROR: Local Golgotha version supports fewer players than this game needs. Check your version.");
                        num_ais=G1_MAX_PLAYERS;
                    }
                    i4_str * ainame=0;
                    g1_team_api_class * newai=0;
                    for (int ais=0; ais<num_ais; ais++)
                    {
                        //the player the next ai is for
                        w32 aifor=r.read_32();
                        ainame=r.read_counted_str();
                        char buf[100];
                        i4_os_string(*ainame,buf,100);
                        newai=g1_create_ai(buf,0);
                        if (strcmp(buf,"human")==0)
                        {
                            //this will be the local player
                            g1_player_man.local_player=ais;
                            i4_warning("We were assigned player number %i.",ais);
                        }
                        g1_player_man.get(ais)->set_ai(newai);
                        newai->init();
                        delete ainame;
                    }
                    g1_global_id.enable_networking(ID_NET_CLIENT);
                    state=RUNNING;
                    i4_warning("The game is in sync and has started");
                }
                //this message is sent by the server if all clients are ready
            }
            break;

            case G1_PK_GAME_DATA:
            {
                process_data_packet(r,i4_F);
            }
            break;
            default:
            {
                if (new_message>=G1_PK_ID_BASE && new_message<=G1_PK_ID_END)
                {
                    r.seek(0);
                    g1_global_id.receive_packet(&r);
                }
            }
            }
        }
        delete a;
        noloops++;
    }
    return i4_T;
}
Esempio n. 6
0
File: 2048.c Progetto: mathiask/2048
int main(int argc, const char** argv) {
    struct timeb t;
    ftime(&t);
    srand(1000*t.time+t.millitm);

    unsigned tries = 1, playouts = 0;
    int average = 0;
    strategy strategy = s_up;
    const char* server = NULL;

    // parse command line options
    while (argc>1)
        if (!strcmp(argv[argc-1], "-v")) {
            argc--, verbose = 1;
        } else if (!strcmp(argv[argc-1], "--average")) {
            argc--, average = 1;
        } else if (!strcmp(argv[argc-1], "--highscore")) {
            argc--, tries = ~0;
        } else if (!strcmp(argv[argc-1], "--up")) {
            argc--, strategy = s_up;
        } else if (!strcmp(argv[argc-1], "--score")) {
            argc--, strategy = s_score;
        } else if (!strcmp(argv[argc-1], "--lr")) {
            argc--, strategy = s_lr;
        } else if (argc>2 && !strcmp(argv[argc-2], "--server")) {
            server = argv[argc-1];
            argc -= 2;
        } else {
            if (!strcmp(argv[argc-1], "-h"))
                argc--;
            else
                printf("%s: unknown option %s\n", basename((char*) argv[0]), argv[argc-1]);

            printf("usage: %s [--average] [--highscore] [--lr|--score|--up] [--server <ip-address>] [-v]\n", basename((char*) argv[0]));
            return argc-1;
        }

    board b; // board
    dir d = (dir) -1; // last move
    unsigned hs = 0; // highscore
    unsigned as = 0, an = 0; // average score
    while (tries--) {
        unsigned s = 0;
        int moved;
        playouts++;

        if (server) {
            // connect to server
            if (connect_server(server)) {
                printf("failure to communicate %s\n", server);
                return -1;
            }
        } else {
            // create a board
            memset(b, 0, sizeof(b));
            drop(b);
            drop(b);
        }

        // move until the board is full
        do {
            if (server &&
                ((d<last && !send_server(dirs[d])) ||
                 parse_notation(send_server("board"), b))) {
                printf("failure to communicate %s\n", server);
                return -1;
            }

            if (verbose)
                print_board(b);
        } while (
            // simple strategy: move up, left, right or down, whatever works
            (strategy==s_up && (
                ((s += move(b, d = up,    &moved)), (moved && drop(b))) ||
                ((s += move(b, d = left,  &moved)), (moved && drop(b))) ||
                ((s += move(b, d = right, &moved)), (moved && drop(b))) ||
                ((s += move(b, d = down,  &moved)), (moved && drop(b))))) ||
            // other strategies: evaluate moves
            (strategy!=s_up && (
                ((s += move(b, d = evaluate(b, strategy), &moved)), (moved && drop(b))))));

        // calculate the average score
        as += s;
        an++;

        // print the score/board
        if (s>hs) {
            printf("score %u (%u)\n", s, playouts);
            print_board(b);
            hs = s;
        } else if (average && tries%16384==0) {
            printf("avg.  %u\n", as/an);
        }

        // disconnect the server, if any
        if (server)
            send_server("gameover");
        disconnect_server();
    }

    return 0;
}
Esempio n. 7
0
File: init.c Progetto: goXXip/K9
int init(int ac, char **av)
{

/* temporary
ChannelInfo *ci;
NickInfo *ni;
*/

    int i;
    int openlog_failed = 0, openlog_errno = 0;
    int started_from_term = isatty(0) && isatty(1) && isatty(2);


    /* Initialize pseudo-random number generator. */
    srand(time(NULL) ^ getppid() ^ getpid()<<16);

    /* Set file creation mask and group ID. */
#if defined(DEFUMASK) && HAVE_UMASK
    umask(DEFUMASK);
#endif
    if (set_group() < 0)
	return -1;

    /* Parse command-line options; exit if an error occurs. */
    if (parse_options(ac, av) < 0)
	return -1;

    /* Chdir to Services data directory. */
    if (chdir(services_dir) < 0) {
	fprintf(stderr, "chdir(%s): %s\n", services_dir, strerror(errno));
	return -1;
    }

    /* Open logfile, and complain if we didn't. */
    if (open_log() < 0) {
	openlog_errno = errno;
	if (started_from_term) {
	    fprintf(stderr, "Warning: unable to open log file %s: %s\n",
			log_filename, strerror(errno));
	} else {
	    openlog_failed = 1;
	}
    }

    /* Read configuration file; exit if there are problems. */
    if (!read_config())
	return -1;

    /* Re-parse command-line options (to override configuration file). */
    parse_options(ac, av);

    /* Detach ourselves if requested. */
    if (!nofork) {
	if ((i = fork()) < 0) {
	    perror("fork()");
	    return -1;
	} else if (i != 0) {
	    exit(0);
	}
	if (started_from_term) {
	    close(0);
	    close(1);
	    close(2);
	}
	if (setpgid(0, 0) < 0) {
	    perror("setpgid()");
	    return -1;
	}
    }

#ifdef MEMCHECKS
    /* Account for runtime memory.  Do this after forking to avoid a bogus
     * "XXX bytes leaked on exit" message when the parent exits. */
    init_memory();
#endif

    /* Write our PID to the PID file. */
    write_pidfile();

    /* Announce ourselves to the logfile. */
    if (debug || readonly || skeleton || noexpire) {
	log("Services %s (compiled for %s) starting up (options:%s%s%s%s)",
	    version_number, version_protocol,
	    debug ? " debug" : "",
	    readonly ? " readonly" : "",
	    skeleton ? " skeleton" : "",
	    noexpire ? " noexpire" : "");
    } else {
	log("Services %s (compiled for %s) starting up",
	    version_number, version_protocol);
    }
    start_time = time(NULL);

    /* If in read-only mode, close the logfile again. */
    if (readonly)
	close_log();

    /* Set signal handlers.  Catch certain signals to let us do things or
     * panic as necessary, and ignore all others.
     */
#ifdef NSIG
    for (i = 1; i <= NSIG; i++) {
#else
    for (i = 1; i <= 32; i++) {
#endif
	if (i != SIGPROF)
	    signal(i, SIG_IGN);
    }

    signal(SIGINT, weirdsig_handler);
    signal(SIGTERM, weirdsig_handler);
    signal(SIGQUIT, weirdsig_handler);
#ifndef DUMPCORE
    signal(SIGSEGV, weirdsig_handler);
#endif
    signal(SIGBUS, weirdsig_handler);
    signal(SIGQUIT, weirdsig_handler);
    signal(SIGHUP, weirdsig_handler);
    signal(SIGILL, weirdsig_handler);
    signal(SIGTRAP, weirdsig_handler);
    signal(SIGFPE, weirdsig_handler);
#ifdef SIGIOT
    signal(SIGIOT, weirdsig_handler);
#endif

    /* This is our "out-of-memory" panic switch */
    signal(SIGUSR1, weirdsig_handler);

    /* Initialize multi-language support */
    lang_init();
    if (debug)
	log("debug: Loaded languages");

    /* Initialiize subservices */
    ns_init();
    cs_init();

#ifdef USE_MYSQL
    if(!db_connect(1))
      fatal("could not connect to mysql database");
#endif

    /* Load up databases */
    if (!skeleton) {

        db_load_ns();
	//load_ns_dbase();

	if (debug)
	    log("debug: Loaded %s database (1/7)", s_NickServ);

        db_load_cs();
	//load_cs_dbase();

	if (debug)
	    log("debug: Loaded %s database (2/7)", s_ChanServ);

/* start: temporary code */

/*
    for (ni = firstnick(); ni; ni = nextnick()) {
      genpass(ni->pass);
      email_pass(ni->email ? ni->email : "invalid", ni->pass, ni->nick);
      log("debug: genpass for [%s]", ni->nick);
#ifdef USE_ENCRYPTION
      encrypt_in_place(ni->pass, PASSMAX - 1);
#endif
      db_nick_set(ni, "pass", ni->pass);
    }

    for(ci = cs_firstchan(); ci; ci = cs_nextchan()) {
      genpass(ci->founderpass);
      email_pass(ci->email ? ci->email : "invalid", ci->founderpass, ci->name);
      log("debug: genpass for [%s]", ci->name);
#ifdef USE_ENCRYPTION
      encrypt_in_place(ci->founderpass, PASSMAX - 1);
#endif
      db_chan_set(ci, "founderpass", ci->founderpass);
    }

    exit(0);
*/

/*
    for (ni = firstnick(); ni; ni = nextnick()) {
       if(db_add_nick(ni) == -1)
         log("dberror: while adding nicks. continuing");
    }

    for(ci = cs_firstchan(); ci; ci = cs_nextchan()) {
      if(db_add_channel(ci) == -1)
        log("dberror: while adding channels. continuing");
    }

    exit(1);
*/

/* end: temporary code */

    }
    log("Databases loaded");

    /* Connect to the remote server */
    servsock = conn(RemoteServer, RemotePort, LocalHost, LocalPort);
    if (servsock < 0)
	fatal_perror("Can't connect to server");
    send_server();
    sgets2(inbuf, sizeof(inbuf), servsock);
    if (strnicmp(inbuf, "ERROR", 5) == 0) {
	/* Close server socket first to stop wallops, since the other
	 * server doesn't want to listen to us anyway */
	disconn(servsock);
	servsock = -1;
	fatal("Remote server returned: %s", inbuf);
    }

    /* Announce a logfile error if there was one */
    if (openlog_failed) {
	wallops(NULL, "Warning: couldn't open logfile: %s",
		strerror(openlog_errno));
    }

    /* Bring in our pseudo-clients */
    introduce_user(NULL);

    /* Success! */
    return 0;
}