Exemple #1
0
void sat_bruteforce(sat_t *sat) {
	state_t *state_best = state_init(sat->vars_cnt, STATE_ALL_0);
	state_t *state = state_init(sat->vars_cnt, STATE_ALL_0);

	sat_bruteforce_inner(sat, state, state_best, sat->vars_cnt);

	fprintf(stderr, "bf= %u ", cost_main(sat, state_best));

	state_free(state);
	state_free(state_best);
}
/** constructor(). */
void state_on_init(struct state_on *state_on)
{
	_MY_TRACE_STR("state_on_init(1)\n");
	memset(state_on, sizeof(*state_on), 0);
	state_init(&state_on->state);
	CLASS_OPS_INIT_SUPER(state_on->state.ops, state_ops);
}
Exemple #3
0
int init() {
  int status = 0;

  // initialize MPI task numbers
  status = comm_init();
  error_check(&status, "error in comm_init\n");
  if(status) return status;

  // initialize grid
  status = grid_init();
  error_check(&status, "error in grid_init\n");
  if(status) return status;

  // initialize fourier
  status = fourier_init();
  error_check(&status, "error in fourier_init\n");
  if(status) return status;

  // initialize state
  status = state_init();
  error_check(&status, "error in state_init\n");
  if(status) return status;

  // initialize model
  status = model_init();
  error_check(&status, "error in model_init\n");
  if(status) return status;

  // initialize time step
  status = time_init();
  error_check(&status, "error in time_init\n");
  if(status) return status;

  return status;
}
Exemple #4
0
struct wined3d_cs *wined3d_cs_create(struct wined3d_device *device)
{
    const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
    struct wined3d_cs *cs;

    if (!(cs = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*cs))))
        return NULL;

    if (!(cs->fb.render_targets = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
            sizeof(*cs->fb.render_targets) * gl_info->limits.buffers)))
    {
        HeapFree(GetProcessHeap(), 0, cs);
        return NULL;
    }

    if (FAILED(state_init(&cs->state, &cs->fb, gl_info, &device->adapter->d3d_info,
            WINED3D_STATE_NO_REF | WINED3D_STATE_INIT_DEFAULT)))
    {
        HeapFree(GetProcessHeap(), 0, cs->fb.render_targets);
        HeapFree(GetProcessHeap(), 0, cs);
        return NULL;
    }

    cs->ops = &wined3d_cs_st_ops;
    cs->device = device;

    cs->data_size = WINED3D_INITIAL_CS_SIZE;
    if (!(cs->data = HeapAlloc(GetProcessHeap(), 0, cs->data_size)))
    {
        HeapFree(GetProcessHeap(), 0, cs);
        return NULL;
    }

    return cs;
}
Exemple #5
0
void Blake2b::clear()
   {
   zeroise(m_H);
   zeroise(m_buffer);
   m_buflen = 0;
   state_init();
   }
Exemple #6
0
int main()
{

    int state = STATE_INIT;
    int number = 0;

    while ( 1 )
    {

        if ( state == STATE_INIT )
        {
            /*****  將註解區塊整個改成一個 function ********/
            state_init(&state,&number);
            /***********************************************/
        }
        else if ( state == STATE_PROCESSING )
        {

            /************************************************/
            state_processing(&state,number);

            /************************************************/
        }
        else if ( state == STATE_END )
        {
            break;
        }
    }



}
Exemple #7
0
/* The real main loop of the Eruta engine. Most of the work happens in state.c,
 * and the main.rb script, though. */
int real_main(void) {
  Image    * border   = NULL;
  Image    * sheet    = NULL;
  Tileset  * tileset  = NULL;
  Tile     * tile     = NULL;
  State    * state    = NULL;
  Camera   * camera   = NULL;
  Tilepane * tilepane = NULL;
  Tilemap  * map      = NULL;
  Thing    * actor    = NULL;
  Tracker  * tracker          = NULL;
  Tracker  * maptracker       = NULL;
  Sprite   * sprite           = NULL;
  SpriteState * spritestate   = NULL;
  AlpsShower shower;
  int        actor_id         = -1;
  int        sprite_id        = -1;
  int        npc1_id          = -1;
  int        npc2_id          = -1;
  
  
  React    react;
  ALLEGRO_COLOR myblack = {0.0, 0.0, 0.0, 1.0};
    
  state = state_alloc();
  state_set(state); 
  if((!(state)) || (!state_init(state, FALSE))) {
    perror(state_errmsg(state));
    return 1;
  }
  
  alpsshower_init(&shower, state_camera(state), 100, 1.0, bevec(10.0, 10000.0));

  /* Initializes the reactor, the game state is it's data. */
  react_initempty(&react, state);
  react.keyboard_key_up   = main_react_key_up;
  react.keyboard_key_down = main_react_key_down;
  
  puts_standard_path(ALLEGRO_EXENAME_PATH, "ALLEGRO_EXENAME_PATH:");

  camera  = state_camera(state);

  /* Finally initialize ruby and call the ruby startup function. */
  rh_load_main();
  callrb_on_start();
    
  /* Main game loop, controlled by the State object. */  
  while(state_busy(state)) { 
      Point spritenow = bevec(100, 120); 
      react_poll(&react, state);
      alpsshower_update(&shower, state_frametime(state));
      state_update(state);
      state_draw(state);
      /* alpsshower_draw(&shower, camera); */ 
      state_flip_display(state);
   }
   state_done(state);
   state_free(state); 
   return 0;
}
state_t* state_new(U16 frame, int function, float value, interpolation_t* inter)
{
    state_t* newState = (state_t*)malloc(sizeof(state_t));
    state_init(newState);
    newState->frame = frame;
    newState->function = function;
    newState->value = value;
    newState->interpolation = inter;
    return newState;
}
Exemple #9
0
static void wined3d_cs_exec_reset_state(struct wined3d_cs *cs, const void *data)
{
    struct wined3d_adapter *adapter = cs->device->adapter;
    HRESULT hr;

    state_cleanup(&cs->state);
    memset(&cs->state, 0, sizeof(cs->state));
    if (FAILED(hr = state_init(&cs->state, &cs->fb, &adapter->gl_info, &adapter->d3d_info,
            WINED3D_STATE_NO_REF | WINED3D_STATE_INIT_DEFAULT)))
        ERR("Failed to initialize CS state, hr %#x.\n", hr);
}
Exemple #10
0
int main(int argc, char* argv[]) 
{
    setlocale (LC_ALL, "");
    g_type_init();
    g_set_application_name ("eyerest-daemon");

    if (!config_init(argc, argv))
    {
        g_critical("config_init failed!\n");
        return -1;
    }

    if(!g_config.foreground)
    {
        daemon(0, 0);
    }

    if(!dbus_init())
    {
        g_critical("dbus_init failed!\n");
    }

    if (!notify_init())
    {
        g_critical("notify_init failed!\n");
    }

    if (!xfullscreen_init())
    {
        g_critical("xfullscreen_init failed!\n");
        return -1;
    }

    if (!xevent_init())
    {
        g_critical("xevent_init failed!\n");
        return -1;
    }
    xevent_run();

    if(!state_init())
    {
        g_critical("state_init failed\n");
        return -1;
    }

    if (!timer_init())
    {
        g_critical("timer_init failed!\n");
        return -1;
    }
    timer_loop();
    return 0;
}
//Quit for States
void
state_switch (run_state newstate)
{
  if (state != GAME_UNINITIALIZED)
    {
      state_quit ();
    }

  oldstate = state;
  state = newstate;

  ++state_switched;

  if (state_init ())
    {				//Not for GAME_USUAL
      state_quit ();
      state = GAME_USUAL;
      (void) state_init ();
    }
  --state_switched;
}
Exemple #12
0
// returns !=0 on error
int filler_start(void) {int i;
if(pregetinitflist()) return 1;
state_init();
for(i=0;i<nw;i++) words[i].commit=-1; // flag word uncommitted
state_push();
for(i=0;i<ne;i++) entries[i].upd=entries[i].flbm!=(1LL<<nl)-1;
for(i=0;i<nw;i++) words[i].upd=1;
winit=0;
clueorderindex=0;
phase=10;
return 0;
}
Exemple #13
0
int core_run(void)
{
	int s_server = 0, s_listener = 0;
	bool running = true;

	struct pollfd fds[MAX_SOCKETS];

	store_init();
	net_init();

	state_init();

	if((s_server = srv_init()) < 0)
		return EXIT_FAILURE;

	if(srv_connect() == -1){
		ERR("srv_connect() failed. Exiting...");
		return EXIT_FAILURE;
	}

	if((s_listener = clt_init()) == -1){
		ERR("clt_init() failed. Exiting...");
		return EXIT_FAILURE;
	}

	memset(fds, 0 , sizeof(fds));

	net_poll_add(s_server, POLLIN);
	net_poll_add_listener(s_listener, POLLIN);

	while(running){
		net_poll(POLLTIMEOUT);
		proc_tick();

		for(int i = 0; i < net_nfds(); i++){
			while(net_socket_avail(i)){
				char msg[513] = "";
				net_socket_msg(i, msg, sizeof msg);
				proc_proc(i, msg);
			}
		}

		while(proc_wqueue_length()){
			wqueue_entry_t ent = proc_wqueue_head();
			net_socket_write(ENT_GET(ent, target), ENT_GET(ent, data), ENT_GET(ent, datasz));
			proc_wqueue_next();
		}
	}

	return EXIT_SUCCESS;
}
Exemple #14
0
State *_state_deep_clone(State *state, BMapState *cloned, State *end, State *sibling_end, State *cont)
{
	BMapEntryState *in_states = bmap_state_get(cloned, (intptr_t)state);
	State *clone;

	if(!in_states) {
		clone = malloc(sizeof(State));
		state_init(clone);

		if(state == end) {
			// TODO: Fix possible cont leak?
			state_add_reference(clone, REF_TYPE_DEFAULT, REF_STRATEGY_SPLIT, NULL, cont);
		}

		// When the start/cont state is also the end state for the 
		// nonterminal the previous state for the loop also becomes a 
		// possible end state. When the copy operator clones the end 
		// state it adds references to the copy continuation, but only 
		// for the default end state, ignoring this particular case. 
		// In order to fix this, we need to add a ref from the sibling
		// end to the continuation
		if(state == sibling_end) {

			// TODO: Fix possible cont leak?
			state_add_reference(clone, REF_TYPE_DEFAULT, REF_STRATEGY_SPLIT, NULL, cont);
		}

		//TODO: Check insert errors
		bmap_state_insert(cloned, (intptr_t)state, clone);

		BMapCursorAction cursor;
		bmap_cursor_action_init(&cursor, &state->actions);
		while(bmap_cursor_action_next(&cursor)) {
			BMapEntryAction *entry;
			entry = bmap_cursor_action_current(&cursor);
			Action ac = entry->action;
			if(ac.state) {
				ac.state = _state_deep_clone(ac.state, cloned, end, sibling_end, cont);
			}
			// Skip accept to avoid problems with lexer_nonterminal
			if(ac.type != ACTION_ACCEPT) {
				bmap_action_m_append(&clone->actions, entry->key, ac);
			}
		}
		bmap_cursor_action_dispose(&cursor);
	} else {
		clone = in_states->state;
	}
	return clone;
}
Exemple #15
0
extern void #MARK_init(void);
void init_extensions(void) {
	ah_init();
	addrtype_init();
	comment_init();
	2connmark_init();
	conntrack_init();
	2dscp_init();
	2ecn_init();
	esp_init();
	hashlimit_init();
	helper_init();
	icmp_init();
	iprange_init();
	length_init();
	limit_init();
	mac_init();
	multiport_init();
	#2mark_init();
	owner_init();
	physdev_init();
	pkttype_init();
	policy_init();
	realm_init();
	sctp_init();
	standard_init();
	state_init();
	tcp_init();
	2tcpmss_init();
	2tos_init();
	2ttl_init();
	udp_init();
	unclean_init();
	CLASSIFY_init();
	CONNMARK_init();
	DNAT_init();
	LOG_init();
	#DSCP_init();
	ECN_init();
	MASQUERADE_init();
	MIRROR_init();
	NETMAP_init();
	NFQUEUE_init();
	NOTRACK_init();
	REDIRECT_init();
	REJECT_init();
	#MARK_init();
}
Exemple #16
0
static void init() {
	int i;
	DARNIT_INPUT_MAP map;

	d_init("pewpewtris", "pewpewtris", NULL);
	d_fs_mount_self();
	d_fs_mount("music.ldi");
	d_fs_mount("sounds.ldi");
	config_init();
	
	ppt.ui.offset_x = 288;
	ppt.ui.offset_y = 0;

	for (i = 0; i < 180; ppt.tile_lookup[i++] = -1);

	ppt.block = d_render_tilesheet_load("res/block.png", 24, 24, DARNIT_PFORMAT_RGB5A1);
	ppt.tile = d_render_tile_new(10 * 18, ppt.block);
	ppt.bbox = d_bbox_new(180);
	d_bbox_set_indexkey(ppt.bbox);
	ppt.tm = d_tilemap_new(0xFFF, ppt.block, 0xFFF, 10, 18);
	ppt.request_new = 0;
	ppt.font = d_font_load("res/font.ttf", 28, 256, 256);
	ui_init();
	bullet_init(30);
	highscore_init();
	state_init();
	music_init();
	
	ppt.ui.play_background = d_map_load("res/playfield_background.ldmz");
	ppt.ui.menu_background = d_map_load("res/mainmenu_background.ldmz");
	ppt.ui.highscore_background = d_map_load("res/highscore_background.ldmz");

	/* Re-map B to space */
	if (!(d_platform_get().platform & DARNIT_PLATFORM_PANDORA)) {
		map = d_keymapping_get();
		map.b = TPW_KEY_SPACE;
		d_keymapping_set(map);
	}

	block_particle_init();

	/* FIXME: Remove */
	ppt.fps = d_text_surface_new(ppt.font, 6, 1000, 0, 0);
}
Exemple #17
0
int main(int argc, char *argv[])
{
	struct sandbox_state *state;
	gd_t data;
	int ret;

	ret = state_init();
	if (ret)
		goto err;

	state = state_get_current();
	if (os_parse_args(state, argc, argv))
		return 1;

	ret = sandbox_read_state(state, state->state_fname);
	if (ret)
		goto err;

	/* Remove old memory file if required */
	if (state->ram_buf_rm && state->ram_buf_fname)
		os_unlink(state->ram_buf_fname);

	memset(&data, '\0', sizeof(data));
	gd = &data;
#if CONFIG_VAL(SYS_MALLOC_F_LEN)
	gd->malloc_base = CONFIG_MALLOC_F_ADDR;
#endif
	setup_ram_buf(state);

	/* Do pre- and post-relocation init */
	board_init_f(0);

	board_init_r(gd->new_gd, 0);

	/* NOTREACHED - board_init_r() does not return */
	return 0;

err:
	printf("Error %d\n", ret);
	return 1;
}
Exemple #18
0
int main(int argc, char *argv[])
{
	struct sandbox_state *state;
	int err;

	err = state_init();
	if (err)
		return err;

	state = state_get_current();
	if (os_parse_args(state, argc, argv))
		return 1;

	/*
	 * Do pre- and post-relocation init, then start up U-Boot. This will
	 * never return.
	 */
	board_init_f(0);

	/* NOTREACHED - board_init_f() does not return */
	return 0;
}
Exemple #19
0
/*
 * XXX Figure out the way to bind a specific adapter to a socket.
 */
DWORD WINAPI AdapterDiscoveryThread(LPVOID Context) {
    PMIB_IFTABLE Table = (PMIB_IFTABLE) malloc(sizeof(MIB_IFTABLE));
    DWORD Error, Size = sizeof(MIB_IFTABLE);
    PDHCP_ADAPTER Adapter = NULL;
    HANDLE AdapterStateChangedEvent = (HANDLE)Context;
    struct interface_info *ifi = NULL;
    struct protocol *proto;
    int i, AdapterCount = 0, Broadcast;

    /* FIXME: Kill this thread when the service is stopped */

    do {
       DH_DbgPrint(MID_TRACE,("Getting Adapter List...\n"));

       while( (Error = GetIfTable(Table, &Size, 0 )) ==
               ERROR_INSUFFICIENT_BUFFER ) {
           DH_DbgPrint(MID_TRACE,("Error %d, New Buffer Size: %d\n", Error, Size));
           free( Table );
           Table = (PMIB_IFTABLE) malloc( Size );
       }

       if( Error != NO_ERROR )
       {
           /* HACK: We are waiting until TCP/IP starts */
           Sleep(2000);
           continue;
       }

       DH_DbgPrint(MID_TRACE,("Got Adapter List (%d entries)\n", Table->dwNumEntries));

       for( i = Table->dwNumEntries - 1; i >= 0; i-- ) {
            DH_DbgPrint(MID_TRACE,("Getting adapter %d attributes\n",
                                   Table->table[i].dwIndex));

            ApiLock();

            if ((Adapter = AdapterFindByHardwareAddress(Table->table[i].bPhysAddr, Table->table[i].dwPhysAddrLen)))
            {
                proto = find_protocol_by_adapter(&Adapter->DhclientInfo);

                /* This is an existing adapter */
                if (InterfaceConnected(&Table->table[i])) {
                    /* We're still active so we stay in the list */
                    ifi = &Adapter->DhclientInfo;

                    /* This is a hack because IP helper API sucks */
                    if (IsReconnectHackNeeded(Adapter, &Table->table[i]))
                    {
                        /* This handles a disconnect/reconnect */

                        if (proto)
                            remove_protocol(proto);
                        Adapter->DhclientInfo.client->state = S_INIT;

                        /* These are already invalid since the media state change */
                        Adapter->RouterMib.dwForwardNextHop = 0;
                        Adapter->NteContext = 0;

                        add_protocol(Adapter->DhclientInfo.name,
                                     Adapter->DhclientInfo.rfdesc,
                                     got_one, &Adapter->DhclientInfo);
                        state_init(&Adapter->DhclientInfo);

                        SetEvent(AdapterStateChangedEvent);
                    }

                } else {
                    if (proto)
                        remove_protocol(proto);

                    /* We've lost our link so out we go */
                    RemoveEntryList(&Adapter->ListEntry);
                    free(Adapter);
                }

                ApiUnlock();

                continue;
            }

            ApiUnlock();

            Adapter = (DHCP_ADAPTER*) calloc( sizeof( DHCP_ADAPTER ) + Table->table[i].dwMtu, 1 );

            if( Adapter && Table->table[i].dwType == MIB_IF_TYPE_ETHERNET && InterfaceConnected(&Table->table[i])) {
                memcpy( &Adapter->IfMib, &Table->table[i],
                        sizeof(Adapter->IfMib) );
                Adapter->DhclientInfo.client = &Adapter->DhclientState;
                Adapter->DhclientInfo.rbuf = Adapter->recv_buf;
                Adapter->DhclientInfo.rbuf_max = Table->table[i].dwMtu;
                Adapter->DhclientInfo.rbuf_len =
                    Adapter->DhclientInfo.rbuf_offset = 0;
                memcpy(Adapter->DhclientInfo.hw_address.haddr,
                       Adapter->IfMib.bPhysAddr,
                       Adapter->IfMib.dwPhysAddrLen);
                Adapter->DhclientInfo.hw_address.hlen = Adapter->IfMib.dwPhysAddrLen;

                /* I'm not sure where else to set this, but
                   some DHCP servers won't take a zero.
                   We checked the hardware type earlier in
                   the if statement. */
                Adapter->DhclientInfo.hw_address.htype = HTYPE_ETHER;

                if( DhcpSocket == INVALID_SOCKET ) {
                    DhcpSocket =
                        Adapter->DhclientInfo.rfdesc =
                        Adapter->DhclientInfo.wfdesc =
                        socket( AF_INET, SOCK_DGRAM, IPPROTO_UDP );

                    if (DhcpSocket != INVALID_SOCKET) {
						
						/* Allow broadcast on this socket */
						Broadcast = 1;
						setsockopt(DhcpSocket,
								   SOL_SOCKET,
								   SO_BROADCAST,
								   (const char *)&Broadcast,
								   sizeof(Broadcast));
						
                        Adapter->ListenAddr.sin_family = AF_INET;
                        Adapter->ListenAddr.sin_port = htons(LOCAL_PORT);
                        Adapter->BindStatus =
                             (bind( Adapter->DhclientInfo.rfdesc,
                                    (struct sockaddr *)&Adapter->ListenAddr,
                                    sizeof(Adapter->ListenAddr) ) == 0) ?
                             0 : WSAGetLastError();
                    } else {
                        error("socket() failed: %d\n", WSAGetLastError());
                    }
                } else {
                    Adapter->DhclientInfo.rfdesc =
                        Adapter->DhclientInfo.wfdesc = DhcpSocket;
                }

                Adapter->DhclientConfig.timeout = DHCP_PANIC_TIMEOUT;
                Adapter->DhclientConfig.initial_interval = DHCP_DISCOVER_INTERVAL;
                Adapter->DhclientConfig.retry_interval = DHCP_DISCOVER_INTERVAL;
                Adapter->DhclientConfig.select_interval = 1;
                Adapter->DhclientConfig.reboot_timeout = DHCP_REBOOT_TIMEOUT;
                Adapter->DhclientConfig.backoff_cutoff = DHCP_BACKOFF_MAX;
                Adapter->DhclientState.interval =
                    Adapter->DhclientConfig.retry_interval;

                if( PrepareAdapterForService( Adapter ) ) {
                    Adapter->DhclientInfo.next = ifi;
                    ifi = &Adapter->DhclientInfo;

                    read_client_conf(&Adapter->DhclientInfo);

                    if (Adapter->DhclientInfo.client->state == S_INIT)
                    {
                        add_protocol(Adapter->DhclientInfo.name,
                                     Adapter->DhclientInfo.rfdesc,
                                     got_one, &Adapter->DhclientInfo);

                        state_init(&Adapter->DhclientInfo);
                    }

                    ApiLock();
                    InsertTailList( &AdapterList, &Adapter->ListEntry );
                    AdapterCount++;
                    SetEvent(AdapterStateChangedEvent);
                    ApiUnlock();
                } else { free( Adapter ); Adapter = 0; }
            } else { free( Adapter ); Adapter = 0; }

            if( !Adapter )
                DH_DbgPrint(MID_TRACE,("Adapter %d was rejected\n",
                                       Table->table[i].dwIndex));
        }
#if 0
        Error = NotifyAddrChange(NULL, NULL);
        if (Error != NO_ERROR)
            break;
#else
        Sleep(3000);
#endif
    } while (TRUE);

    DbgPrint("DHCPCSVC: Adapter discovery thread is terminating! (Error: %d)\n", Error);

    if( Table ) free( Table );
    return Error;
}
Exemple #20
0
/**
 * Battery charging task
 */
void charger_task(void)
{
	struct charge_state_context *ctx = &task_ctx;
	timestamp_t ts;
	int sleep_usec = CHARGE_POLL_PERIOD_SHORT, diff_usec, sleep_next;
	enum charge_state new_state;
	uint8_t batt_flags;

	while (1) {
#ifdef CONFIG_SB_FIRMWARE_UPDATE
		if (sb_fw_update_in_progress()) {
			task_wait_event(CHARGE_MAX_SLEEP_USEC);
			continue;
		}
#endif
		state_common(ctx);

#ifdef CONFIG_CHARGER_TIMEOUT_HOURS
		if (ctx->curr.state == PWR_STATE_CHARGE &&
		    ctx->charge_state_updated_time.val +
		    CONFIG_CHARGER_TIMEOUT_HOURS * HOUR < ctx->curr.ts.val) {
			CPRINTS("Charge timed out after %d hours",
				CONFIG_CHARGER_TIMEOUT_HOURS);
			charge_force_idle(1);
		}
#endif /* CONFIG_CHARGER_TIMEOUT_HOURS */

		switch (ctx->prev.state) {
		case PWR_STATE_INIT:
		case PWR_STATE_REINIT:
			new_state = state_init(ctx);
			break;
		case PWR_STATE_IDLE0:
			new_state = state_idle(ctx);
			/* If still idling, move from IDLE0 to IDLE */
			if (new_state == PWR_STATE_UNCHANGE)
				new_state = PWR_STATE_IDLE;
			break;
		case PWR_STATE_IDLE:
			new_state = state_idle(ctx);
			break;
		case PWR_STATE_DISCHARGE:
			new_state = state_discharge(ctx);
			break;
		case PWR_STATE_CHARGE:
			new_state = state_charge(ctx);
			if (new_state == PWR_STATE_UNCHANGE &&
			    (ctx->curr.batt.state_of_charge >=
			     BATTERY_LEVEL_NEAR_FULL)) {
				/* Almost done charging */
				new_state = PWR_STATE_CHARGE_NEAR_FULL;
			}
			break;

		case PWR_STATE_CHARGE_NEAR_FULL:
			new_state = state_charge(ctx);
			if (new_state == PWR_STATE_UNCHANGE &&
			    (ctx->curr.batt.state_of_charge <
			     BATTERY_LEVEL_NEAR_FULL)) {
				/* Battery below almost-full threshold. */
				new_state = PWR_STATE_CHARGE;
			}
			break;
		case PWR_STATE_ERROR:
			new_state = state_error(ctx);
			break;
		default:
			CPRINTS("Charge state %d undefined",
				ctx->curr.state);
			ctx->curr.state = PWR_STATE_ERROR;
			new_state = PWR_STATE_ERROR;
		}

		if (state_machine_force_idle &&
		    ctx->prev.state != PWR_STATE_IDLE0 &&
		    ctx->prev.state != PWR_STATE_IDLE &&
		    ctx->prev.state != PWR_STATE_INIT &&
		    ctx->prev.state != PWR_STATE_REINIT)
			new_state = PWR_STATE_REINIT;

		if (new_state) {
			ctx->curr.state = new_state;
			CPRINTS("Charge state %s -> %s after %.6ld sec",
				state_name[ctx->prev.state],
				state_name[new_state],
				ctx->curr.ts.val -
				ctx->charge_state_updated_time.val);
			ctx->charge_state_updated_time = ctx->curr.ts;
			hook_notify(HOOK_CHARGE_STATE_CHANGE);
		}

		switch (new_state) {
		case PWR_STATE_IDLE0:
			/*
			 * First time transitioning from init -> idle.  Don't
			 * set the flags or LED yet because we may transition
			 * to charging on the next call and we don't want to
			 * blink the LED green.
			 */
			sleep_usec = CHARGE_POLL_PERIOD_SHORT;
			break;
		case PWR_STATE_CHARGE_NEAR_FULL:
			/*
			 * Battery is almost charged.  The last few percent
			 * take a loooong time, so fall through and look like
			 * we're charged.  This mirrors similar hacks at the
			 * ACPI/kernel/UI level.
			 */
		case PWR_STATE_IDLE:
			batt_flags = *ctx->memmap_batt_flags;
			batt_flags &= ~EC_BATT_FLAG_CHARGING;
			batt_flags &= ~EC_BATT_FLAG_DISCHARGING;
			*ctx->memmap_batt_flags = batt_flags;

			/* Charge done */
			sleep_usec = (new_state == PWR_STATE_IDLE
				      ? CHARGE_POLL_PERIOD_LONG
				      : CHARGE_POLL_PERIOD_CHARGE);
			break;
		case PWR_STATE_DISCHARGE:
			batt_flags = *ctx->memmap_batt_flags;
			batt_flags &= ~EC_BATT_FLAG_CHARGING;
			batt_flags |= EC_BATT_FLAG_DISCHARGING;
			*ctx->memmap_batt_flags = batt_flags;
			sleep_usec = CHARGE_POLL_PERIOD_LONG;
			break;
		case PWR_STATE_CHARGE:
			batt_flags = *ctx->memmap_batt_flags;
			batt_flags |= EC_BATT_FLAG_CHARGING;
			batt_flags &= ~EC_BATT_FLAG_DISCHARGING;
			*ctx->memmap_batt_flags = batt_flags;

			/* Charging */
			sleep_usec = CHARGE_POLL_PERIOD_CHARGE;
			break;
		case PWR_STATE_ERROR:
			/* Error */
			sleep_usec = CHARGE_POLL_PERIOD_CHARGE;
			break;
		case PWR_STATE_UNCHANGE:
			/* Don't change sleep duration */
			break;
		default:
			/* Other state; poll quickly and hope it goes away */
			sleep_usec = CHARGE_POLL_PERIOD_SHORT;
		}

#ifdef CONFIG_EXTPOWER_FALCO
		watch_adapter_closely(ctx);
		sleep_usec = EXTPOWER_FALCO_POLL_PERIOD;
#endif

		/* Show charging progress in console */
		charging_progress(ctx);

		ts = get_time();
		diff_usec = (int)(ts.val - ctx->curr.ts.val);
		sleep_next = sleep_usec - diff_usec;

		if (ctx->curr.state == PWR_STATE_DISCHARGE &&
		    chipset_in_state(CHIPSET_STATE_ANY_OFF |
				     CHIPSET_STATE_SUSPEND)) {
			/*
			 * Discharging and system is off or suspended, so no
			 * need to poll frequently.  charge_hook() will wake us
			 * up if anything important changes.
			 */
			sleep_next = CHARGE_POLL_PERIOD_VERY_LONG - diff_usec;
		} else if (sleep_next < CHARGE_MIN_SLEEP_USEC) {
			sleep_next = CHARGE_MIN_SLEEP_USEC;
		} else if (sleep_next > CHARGE_MAX_SLEEP_USEC) {
			sleep_next = CHARGE_MAX_SLEEP_USEC;
		}

		task_wait_event(sleep_next);
	}
}
Exemple #21
0
int
main(int argc, char** argv)
{
    uint32_t led_colors = 0;
    uint8_t at_parm_test[10];
    unsigned once;
    uint32_t i = 0;
    uint8_t canPrescaler = 0;
    uint8_t* uart_tx_packet = 0;
    uint8_t* uart_rx_packet;
    uint32_t old_loadcell_data;
    uint16_t timeStep = 1;

    clock_init();
    pin_init();
    led_init();
    timers_init();
    state_init();
    uart_init();

    // Set up UART2 for 115200 baud. There's no round() on the dsPICs, so we implement our own.
    double brg = (double) 140000000 / 2.0 / 16.0 / 115200.0 - 1.0;
    if (brg - floor(brg) >= 0.5) {
        brg = ceil(brg);
    }
    else {
        brg = floor(brg);
    }
    //  Uart2Init (brg); // Init UART 2 as 115200 baud/s

    loadcell_init();
    loadcell_start();


    led_rgb_off();
    led_rgb_set(50, 0, 100);

    can_state.init_return = RET_UNKNOWN;
    if (can_init()) {
        while (1);
    }

    timer_state.prev_systime = 0;
    timer_state.systime = 0;

#ifdef CONF71
    // Start Reading the int pin on IMU
    mpuData.startData = 0;
    if (IMU_Init(400000, 70000000) == 0) {
        // imu_state.init_return = RET_OK;
        mpuData.startData = 1;
    }
    else {
        //imu_state.init_return = RET_ERROR;
    }
#endif

    for (;;) {
        if (timer_state.systime != timer_state.prev_systime) {
            timer_state.prev_systime = timer_state.systime;
            //everything in here will be executed once every ms
            //make sure that everything in here takes less than 1ms
            //useful for checking state consistency, synchronization, watchdog...

            if(timer_state.systime % 1000 == 1) {
                LED_4 = 1;
            }

            led_update();
            if (timer_state.systime % 10 == 1) {
                IMU_GetQuaternion(quaterion);
                QuaternionToYawPitchRoll(quaterion, ypr);
            }

            if (timer_state.systime % 5 == 1) {
                IMU_normalizeData(&mpuData, &magData, &imuData);
                // Run AHRS algorithm
                IMU_UpdateAHRS (&imuData);

                // Run IMU algorithm (does not use MAG data)
//                IMU_UpdateIMU(&imuData);

                //copy state to CAN dictionary
                IMU_CopyOutput(&imuData, &mpuData, &magData);
            }

            /**
             * CANFestival Loop
             */
            if (can_state.init_return == RET_OK) {
                can_process();

                /**
                 * Sets CANFestival shared variables
                 * specific to Sensor Board
                 */
                can_push_state();
            }

            /**
             * Blinking LED Loop
             */
            if (timer_state.systime % 25 == 0) {
                              LED_1 = !LED_1;
            }


        }
        else {
            //untimed processes in main loop:
            //executed as fast as possible
            //these processes should NOT block the main loop
//            LED_4 = mpuData.accelX > 0;
//            LED_3 = mpuData.accelY > 0;
//            LED_1 = mpuData.accelZ > 0;

//            IMU_GetData();
            IMU_CopyI2CData(&mpuData, &magData);

            if (!T1CONbits.TON) {
                RGB_RED = 0;
                RGB_GREEN = RGB_BLUE = 1;
                while (1);

            }

            if(can_flag){
                TimeDispatch();
                can_flag = 0;
            }

            uart_rx_packet = uart_rx_cur_packet();
            if (uart_rx_packet != 0) {
                uart_rx_packet_consumed();
            }

            /**
             * Handles CAN transmission buffers
             */
            if ((txreq_bitarray & 0b00000001) && !C1TR01CONbits.TXREQ0) {
                C1TR01CONbits.TXREQ0 = 1;
                txreq_bitarray = txreq_bitarray & 0b11111110;
            }
            if ((txreq_bitarray & 0b00000010) && !C1TR01CONbits.TXREQ1) {
                C1TR01CONbits.TXREQ1 = 1;
                txreq_bitarray = txreq_bitarray & 0b11111101;
            }
            if ((txreq_bitarray & 0b00000100) && !C1TR23CONbits.TXREQ2) {
                C1TR23CONbits.TXREQ2 = 1;
                txreq_bitarray = txreq_bitarray & 0b11111011;
            }
            if ((txreq_bitarray & 0b00001000) && !C1TR23CONbits.TXREQ3) {
                C1TR23CONbits.TXREQ3 = 1;
                txreq_bitarray = txreq_bitarray & 0b11110111;
            }
            if ((txreq_bitarray & 0b00010000) && !C1TR45CONbits.TXREQ4) {
                C1TR45CONbits.TXREQ4 = 1;
                txreq_bitarray = txreq_bitarray & 0b11101111;
            }
            if ((txreq_bitarray & 0b00100000) && !C1TR45CONbits.TXREQ5) {
                C1TR45CONbits.TXREQ5 = 1;
                txreq_bitarray = txreq_bitarray & 0b11011111;
            }
            if ((txreq_bitarray & 0b01000000) && !C1TR67CONbits.TXREQ6) {
                C1TR67CONbits.TXREQ6 = 1;
                txreq_bitarray = txreq_bitarray & 0b10111111;
            }
        }
    }
    return (EXIT_SUCCESS);
}
Exemple #22
0
static void init_machine(running_machine *machine)
{
	mame_private *mame = machine->mame_data;
	int num;

	/* initialize basic can't-fail systems here */
	cpuintrf_init(machine);
	sndintrf_init(machine);
	fileio_init(machine);
	config_init(machine);
	output_init(machine);
	state_init(machine);
	state_save_allow_registration(TRUE);
	drawgfx_init(machine);
	palette_init(machine);
	render_init(machine);
	ui_init(machine);
	generic_machine_init(machine);
	generic_video_init(machine);
	mame->rand_seed = 0x9d14abd7;

	/* initialize the base time (if not doing record/playback) */
	if (!Machine->record_file && !Machine->playback_file)
		time(&mame->base_time);
	else
		mame->base_time = 0;

	/* init the osd layer */
	if (osd_init(machine) != 0)
		fatalerror("osd_init failed");

	/* initialize the input system */
	/* this must be done before the input ports are initialized */
	if (code_init(machine) != 0)
		fatalerror("code_init failed");

	/* initialize the input ports for the game */
	/* this must be done before memory_init in order to allow specifying */
	/* callbacks based on input port tags */
	if (input_port_init(machine, machine->gamedrv->ipt) != 0)
		fatalerror("input_port_init failed");

	/* load the ROMs if we have some */
	/* this must be done before memory_init in order to allocate memory regions */
	rom_init(machine, machine->gamedrv->rom);

	/* initialize the timers and allocate a soft_reset timer */
	/* this must be done before cpu_init so that CPU's can allocate timers */
	timer_init(machine);
	mame->soft_reset_timer = timer_alloc(soft_reset);

	/* initialize the memory system for this game */
	/* this must be done before cpu_init so that set_context can look up the opcode base */
	if (memory_init(machine) != 0)
		fatalerror("memory_init failed");

	/* now set up all the CPUs */
	if (cpuexec_init(machine) != 0)
		fatalerror("cpuexec_init failed");
	if (cpuint_init(machine) != 0)
		fatalerror("cpuint_init failed");

#ifdef MESS
	/* initialize the devices */
	devices_init(machine);
#endif

	/* start the save/load system */
	saveload_init(machine);

	/* call the game driver's init function */
	/* this is where decryption is done and memory maps are altered */
	/* so this location in the init order is important */
	ui_set_startup_text("Initializing...", TRUE);
	if (machine->gamedrv->driver_init != NULL)
		(*machine->gamedrv->driver_init)(machine);

	/* start the audio system */
	if (sound_init(machine) != 0)
		fatalerror("sound_init failed");

	/* start the video hardware */
	if (video_init(machine) != 0)
		fatalerror("video_init failed");

	/* start the cheat engine */
	if (options.cheat)
		cheat_init(machine);

	/* call the driver's _START callbacks */
	if (machine->drv->machine_start != NULL && (*machine->drv->machine_start)(machine) != 0)
		fatalerror("Unable to start machine emulation");
	if (machine->drv->sound_start != NULL && (*machine->drv->sound_start)(machine) != 0)
		fatalerror("Unable to start sound emulation");
	if (machine->drv->video_start != NULL && (*machine->drv->video_start)(machine) != 0)
		fatalerror("Unable to start video emulation");

	/* free memory regions allocated with REGIONFLAG_DISPOSE (typically gfx roms) */
	for (num = 0; num < MAX_MEMORY_REGIONS; num++)
		if (mame->mem_region[num].flags & ROMREGION_DISPOSE)
			free_memory_region(machine, num);

#ifdef MAME_DEBUG
	/* initialize the debugger */
	if (machine->debug_mode)
		mame_debug_init(machine);
#endif
}
Exemple #23
0
/*
 * eq: equlibirium factor
 * ti: temperature initial
 * te: temperature end
 * cf: cooling factor (0 < cf < 1)
 */
uint32_t simulated_annealing(sat_t *sat, double te, double steps) {
	state_t *state = state_init(sat->vars_cnt, STATE_RANDOMIZE);
	state_t *state_next = state_init(sat->vars_cnt, STATE_ALL_0);
	uint32_t ret = 0;
	uint32_t real_cost = 0;
	uint32_t eq; /* equlibrium */
	double cf; /* cooling factor */
	double ti; /* temperature initial */

	ti = sat->vars_cnt * sat->weight_max * 10;
	cf = pow(te / ti, 1 / (steps - 1));
//	cf = 1 - ((ti - te) / steps);

	static bool print_once = false; //true;

	uint32_t it = 0;

//	printf("ti=%lf te=%lf cf=%lf, eq=%d\n", ti, te, cf, eq);

//	for (double t = ti; te < t; t *= cf) {
//		for (int i = 0; i < eq; i++) {
//			state_gen_next(state, state_next);
//			double d = ((double) cost(sat, state))
//					- ((double) cost(sat, state_next));
//
//			if (d < 0 || randd() < pow(M_E, -d / t)) {
//				state_swap(&state, &state_next);
//				continue;
//			}
//
//			//printf("it= %4u best= %4u bits= ", it++, cost(sat, state));
//			//			state_print(state);
//		}
//	}
	//http://www.cs.ubc.ca/~hoos/SATLIB/benchm.html
	eq = (uint32_t) (sat->vars_cnt / (double) 2.0);
	uint32_t *p = calloc(sat->vars_cnt, sizeof(uint32_t));
	for (double t = ti; te < t; t *= cf) {
		permutation(p, sat->vars_cnt);
		it++;
//		printf("t=%lf\n", t);
		for (uint32_t i = 0; i < eq; i++) {

			double c = cost(sat, state);

			uint32_t ind = p[i];
			state->ch[ind] = (state->ch[ind] + 1) % 2;

			double d = (c - (double) cost(sat, state));

			if (d < 0 || randd() < pow(M_E, -d / t)) {
				continue;
			}

			state->ch[ind] = (state->ch[ind] + 1) % 2;
		}

		real_cost = cost_main(sat, state);

		if (g_print_progress) {
			printf("%u %u %lf\n", it, real_cost, cost(sat, state));
		}

		ret = max(ret, real_cost);
	}

	if (print_once) {
		fprintf(stderr, "ti=%lf cf=%lf it=%u eq=%u\n", ti, cf, it, eq);
		assert(0 < cf && cf < 1);
		print_once = false;
		state_print(state);
	}

	free(p);
	state_free(state);
	state_free(state_next);

	return (ret);
}
Exemple #24
0
int main(int argc, char **argv)
{
	int i, result;

	progname = strrchr(argv[0], '/');
	progname = progname ? progname + 1 : argv[0];

	is_module = 0;
	ipc_init_struct();
	gettimeofday(&self.start, NULL);


	/*
	 * Solaris doesn't support MSG_NOSIGNAL, so
	 * we ignore SIGPIPE globally instead
	 */
	signal(SIGPIPE, SIG_IGN);

	for (i = 1; i < argc; i++) {
		char *opt, *arg = argv[i];

		if (*arg != '-') {
			if (!merlin_conf) {
				merlin_conf = arg;
				continue;
			}
			goto unknown_argument;
		}

		if (!strcmp(arg, "-h") || !strcmp(arg, "--help"))
			usage(NULL);
		if (!strcmp(arg, "-k") || !strcmp(arg, "--kill")) {
			killing = 1;
			continue;
		}
		if (!strcmp(arg, "-d") || !strcmp(arg, "--debug")) {
			debug++;
			continue;
		}

		if ((opt = strchr(arg, '=')))
			opt++;
		else if (i < argc - 1)
			opt = argv[i + 1];
		else
			usage("Unknown argument, or argument '%s' requires a parameter", arg);

		i++;
		if (!strcmp(arg, "--config") || !strcmp(arg, "-c")) {
			merlin_conf = opt;
			continue;
		}
		unknown_argument:
		usage("Unknown argument: %s", arg);
	}

	if (!merlin_conf)
		usage("No config-file specified\n");

	if (!grok_config(merlin_conf)) {
		fprintf(stderr, "%s contains errors. Bailing out\n", merlin_conf);
		return 1;
	}

	if (!pidfile)
		pidfile = "/var/run/merlin.pid";

	if (killing)
		return kill_daemon(pidfile);

	if (use_database && !import_program) {
		lwarn("Using database, but no import program configured. Are you sure about this?");
		lwarn("If not, make sure you specify the import_program directive in");
		lwarn("the \"daemon\" section of your merlin configuration file");
	}

	ipc.action = ipc_action_handler;
	result = ipc_init();
	if (result < 0) {
		printf("Failed to initalize ipc socket: %s\n", strerror(errno));
		return 1;
	}
	if (net_init() < 0) {
		printf("Failed to initialize networking: %s\n", strerror(errno));
		return 1;
	}

	if (!debug) {
		if (daemonize(merlin_user, NULL, pidfile, 0) < 0)
			exit(EXIT_FAILURE);

		/*
		 * we'll leak these file-descriptors, but that
		 * doesn't really matter as we just want accidental
		 * output to go somewhere where it'll be ignored
		 */
		fclose(stdin);
		open("/dev/null", O_RDONLY);
		fclose(stdout);
		open("/dev/null", O_WRONLY);
		fclose(stderr);
		open("/dev/null", O_WRONLY);
	}

	signal(SIGINT, clean_exit);
	signal(SIGTERM, clean_exit);
	signal(SIGUSR1, sigusr_handler);
	signal(SIGUSR2, sigusr_handler);

	sql_init();
	if (use_database) {
		sql_query("TRUNCATE TABLE program_status");
		sql_query("INSERT INTO program_status(instance_id, instance_name, is_running) "
		          "VALUES(0, 'Local Nagios daemon', 0)");
		for (i = 0; i < (int)num_nodes; i++) {
			char *node_name;
			merlin_node *node = noc_table[i];

			sql_quote(node->name, &node_name);
			sql_query("INSERT INTO program_status(instance_id, instance_name, is_running) "
			          "VALUES(%d, %s, 0)", node->id + 1, node_name);
			safe_free(node_name);
		}
	}
	state_init();
	linfo("Merlin daemon %s successfully initialized", merlin_version);
	polling_loop();

	clean_exit(0);

	return 0;
}
Exemple #25
0
void running_machine::start()
{
	// initialize basic can't-fail systems here
	fileio_init(this);
	config_init(this);
	input_init(this);
	output_init(this);
	state_init(this);
	state_save_allow_registration(this, true);
	palette_init(this);
	render_init(this);
	ui_init(this);
	generic_machine_init(this);
	generic_video_init(this);
	generic_sound_init(this);

	// initialize the timers and allocate a soft_reset timer
	// this must be done before cpu_init so that CPU's can allocate timers
	timer_init(this);
	m_soft_reset_timer = timer_alloc(this, static_soft_reset, NULL);

	// init the osd layer
	osd_init(this);

	// initialize the base time (needed for doing record/playback)
	time(&m_base_time);

	// initialize the input system and input ports for the game
	// this must be done before memory_init in order to allow specifying
	// callbacks based on input port tags
	time_t newbase = input_port_init(this, m_game.ipt);
	if (newbase != 0)
		m_base_time = newbase;

	// intialize UI input
	ui_input_init(this);

	// initialize the streams engine before the sound devices start
	streams_init(this);

	// first load ROMs, then populate memory, and finally initialize CPUs
	// these operations must proceed in this order
	rom_init(this);
	memory_init(this);
	watchdog_init(this);

	// allocate the gfx elements prior to device initialization
	gfx_init(this);

	// initialize natural keyboard support
	inputx_init(this);

	// initialize image devices
	image_init(this);

	// start up the devices
	m_devicelist.start_all();

	// call the game driver's init function
	// this is where decryption is done and memory maps are altered
	// so this location in the init order is important
	ui_set_startup_text(this, "Initializing...", true);
	if (m_game.driver_init != NULL)
		(*m_game.driver_init)(this);

	// finish image devices init process
	image_postdevice_init(this);

	// start the video and audio hardware
	video_init(this);
	tilemap_init(this);
	crosshair_init(this);

	sound_init(this);

	// initialize the debugger
	if ((debug_flags & DEBUG_FLAG_ENABLED) != 0)
		debugger_init(this);

	// call the driver's _START callbacks
	if (m_config.m_machine_start != NULL)
		(*m_config.m_machine_start)(this);
	if (m_config.m_sound_start != NULL)
		(*m_config.m_sound_start)(this);
	if (m_config.m_video_start != NULL)
		(*m_config.m_video_start)(this);

	// if we're coming in with a savegame request, process it now
	const char *savegame = options_get_string(&m_options, OPTION_STATE);
	if (savegame[0] != 0)
		schedule_load(savegame);

	// if we're in autosave mode, schedule a load
	else if (options_get_bool(&m_options, OPTION_AUTOSAVE) && (m_game.flags & GAME_SUPPORTS_SAVE) != 0)
		schedule_load("auto");

	// set up the cheat engine
	if (options_get_bool(&m_options, OPTION_CHEAT))
		cheat_init(this);

	// disallow save state registrations starting here
	state_save_allow_registration(this, false);
}
Exemple #26
0
int run_iterations(int run_index, parameters params) {
	FILE *stats = stats_open_file(run_index);
	stats_print_header(stats);

	int counter = 1;
	int *count;
	int max_infected = 0, time_of_max_infected;
	int day;
	
	igraph_t graph;
	
	for(int K = params.K_low; K < params.K_high; K += params.K_step) {
		for(double p = params.p_low; p < params.p_high; p += params.p_step) {
			for(int i = 0; i < REPITITIONS; i++) {
				printf("%i\n", counter);

				// Initialize the graph
				igraph_watts_strogatz_game(&graph, 1, NETWORK_SIZE, K, p);

				//
				// Initialize the variables that keep track of the state of 
				// each vertex.
				 
				// For each vertex, we track what state it is in (susceptible, latent, infectious, recovered)
				// and how long they have been in their current state.

				state_init(&graph);
				state_counter_init(&graph);

				count = state_counts(&graph);

				//
				// The main loop
				//
				max_infected = 0;
				time_of_max_infected = 1;
				for(day = 1; day <= SIMULATION_LENGTH; day++) {
					spread_infection(&graph);

					//char graph_file[100];
					//sprintf(&graph_file[0], "graph-data/graph%i-k-%i-p-%f.graphml", day, K, p);

					//graph_save(&graph, graph_file);

					count = state_counts(&graph);

					if(count[INFECTIOUS] > max_infected) {
						max_infected = count[INFECTIOUS];
						time_of_max_infected = day;
					}

					if(count[INFECTIOUS] == 0) {
						break;
					}
				}

				stats_save(&graph, stats, counter, K, p, max_infected, time_of_max_infected, count[SUSCEPTIBLE], count[LATENT], count[INFECTIOUS], count[RECOVERED], day);

				counter += 1;
				igraph_destroy(&graph);
			}
		}
	}
	

	stats_close_file(stats);
}
Exemple #27
0
static int _clone_fs_action(BMapAction *action_set, Reference *ref, int key, Action *action)
{
	int result = REF_RESULT_SOLVED;
	//TODO: Make type for clone a parameter, do not override by
	// default.

	// When a symbol is present, assume nonterminal invocation
	int clone_type;

	if(ref->type == REF_TYPE_DEFAULT) {
		// It could happen when merging loops in final states
		// that action->type == ACTION_REDUCE
		clone_type = action->type;
	} else if(ref->type == REF_TYPE_SHIFT) {
		if (action->type == ACTION_REDUCE) {
			// This could happen when the start state of a
			// nonterminal is also an end state.
			trace_op(
				"skip",
				ref->state,
				action,
				key,
				"reduction on first-set",
				0
			);
			goto end;
		}
		clone_type = ACTION_SHIFT;
	} else if(ref->type == REF_TYPE_START) {
		if (action->type == ACTION_REDUCE || action->type == ACTION_ACCEPT) {
			trace_op(
				"skip",
				ref->state,
				action,
				key,
				"reduction on first-set",
				0
			);
			goto end;
		}
		clone_type = ACTION_START;
	}

	//TODO: Detect collision for ranges (only testing `key` for now)
	Action *col = state_get_transition(ref->state, key);

	// TODO: Unify collision detection, skipping and merging with the ones
	// used in the state functions.
	if(col && ref->strategy == REF_STRATEGY_MERGE) {
		if(!action_compare(*action, *col)) {
			trace_op(
				"collision",
				ref->state,
				action,
				key,
				"skip duplicate",
				0
			);
			goto end;
		}

		if(col->state == NULL || action->state == NULL) {
			trace_op(
				"collision",
				ref->state,
				action,
				key,
				"unhandled",
				0
			);
			goto end;
		}

		//Collision: redefine actions in order to disambiguate.
		trace_op(
			"collision",
			ref->state,
			col,
			key,
			"deambiguate state",
			0
		);

		//TODO: should only merge if actions are identical
		//TODO: Make this work with ranges.
		State *merge = malloc(sizeof(State));
		state_init(merge);

		//Merge first set for the actions continuations.
		state_add_reference(merge, REF_TYPE_DEFAULT, REF_STRATEGY_MERGE, NULL, col->state);
		state_add_reference(merge, REF_TYPE_DEFAULT, REF_STRATEGY_MERGE, NULL, action->state);

		//Create unified action pointing to merged state.
		action_init(col, clone_type, col->reduction, merge, col->flags, col->end_symbol);

		result = REF_RESULT_CHANGED;
	} else {

		//No collision detected, clone the action an add it.
		Action clone;
		action_init(&clone, clone_type, action->reduction, action->state, action->flags, action->end_symbol);

		trace_op(
			"add",
			ref->state,
			&clone,
			key,
			"first-set",
			0
		);

		bmap_action_m_append(action_set, key, clone);
	}
end:
	return result;
}
Exemple #28
0
void running_machine::start()
{
	/* initialize basic can't-fail systems here */
	fileio_init(this);
	config_init(this);
	input_init(this);
	output_init(this);
	state_init(this);
	state_save_allow_registration(this, true);
	palette_init(this);
	render_init(this);
	ui_init(this);
	generic_machine_init(this);
	generic_video_init(this);
	generic_sound_init(this);

	/* initialize the timers and allocate a soft_reset timer
	   this must be done before cpu_init so that CPU's can allocate timers */
	timer_init(this);
	m_soft_reset_timer = timer_alloc(this, static_soft_reset, NULL);

	/* init the osd layer */
	osd_init(this);

	/* initialize the base time (needed for doing record/playback) */
	time(&m_base_time);

	/* initialize the input system and input ports for the game
	   this must be done before memory_init in order to allow specifying
	   callbacks based on input port tags */
	time_t newbase = input_port_init(this, m_game.ipt);
	if (newbase != 0)
		m_base_time = newbase;

	/* intialize UI input */
	ui_input_init(this);

	/* initialize the streams engine before the sound devices start */
	streams_init(this);

	/* first load ROMs, then populate memory, and finally initialize CPUs
	   these operations must proceed in this order */
	rom_init(this);
	memory_init(this);
	watchdog_init(this);

	/* allocate the gfx elements prior to device initialization */
	gfx_init(this);

	/* initialize natural keyboard support */
	inputx_init(this);

	/* initialize image devices */
	image_init(this);

	/* start up the devices */
	m_devicelist.start_all();

	/* call the game driver's init function
	   this is where decryption is done and memory maps are altered
	   so this location in the init order is important */
	ui_set_startup_text(this, "Initializing...", true);
	if (m_game.driver_init != NULL)
		(*m_game.driver_init)(this);

	/* finish image devices init process */
	image_postdevice_init(this);

	/* start the video and audio hardware */
	video_init(this);
	tilemap_init(this);
	crosshair_init(this);

	sound_init(this);

	/* initialize the debugger */
	if ((debug_flags & DEBUG_FLAG_ENABLED) != 0)
		debugger_init(this);

	/* call the driver's _START callbacks */
	if (m_config.m_machine_start != NULL)
		(*m_config.m_machine_start)(this);
	if (m_config.m_sound_start != NULL)
		(*m_config.m_sound_start)(this);
	if (m_config.m_video_start != NULL)
		(*m_config.m_video_start)(this);

	/* set up the cheat engine */    
	cheat_init(this);
	/* set up the hiscore engine */    
    hiscore_init(this);

	/* disallow save state registrations starting here */
	state_save_allow_registration(this, false);
}
Exemple #29
0
int main(int ac, char** av)
{
  grid_t g;
  state_t state;
  bfs_t b;
  cmdline_t cmd;
  rulset_t rulset;
  const rule_t* ru;
  unsigned int i;

  grid_init(&g, 5);
  state_init(&state);
  rulset_init(&rulset);

  /* start with first rule */
  state.cur_rule = rulset.rules;

  while (state.is_done == 0)
  {
    cmdline_get(&cmd);

    switch (cmd.op)
    {
    case CMDLINE_OP_PUT_BLOCK:
      if (state.items[state.cur_color])
      {
	if (*grid_at(&g, cmd.x, cmd.y) == BLOCK_COLOR_INVALID)
        {
	  *grid_at(&g, cmd.x, cmd.y) = state.cur_color;
	  --state.items[state.cur_color];
	}
      }
      break ;

    case CMDLINE_OP_GET_BLOCK:
      if (*grid_at(&g, cmd.x, cmd.y) != BLOCK_COLOR_INVALID)
      {
	++state.items[*grid_at(&g, cmd.x, cmd.y)];
	*grid_at(&g, cmd.x, cmd.y) = BLOCK_COLOR_INVALID;
      }
      break ;

    case CMDLINE_OP_SEL_COLOR:
      state.cur_color = cmd.color;
      break ;

    case CMDLINE_OP_SEL_RULE:
      ru = rulset.rules;
      for (i = 0; ru && (i < cmd.rule); ++i, ru = ru->next) ;
      state.cur_rule = (rule_t*)ru;
      if (ru == NULL) { printf("no such rule\n"); break ; }
      goto eval_rule_case;
      break ;

    case CMDLINE_OP_LIST_RULES:
      ru = rulset.rules;
      for (i = 0; ru; ++i, ru = ru->next)
	printf("[%u] %u\n", i, ru->outcome);
      break ;

    case CMDLINE_OP_LIST_ITEMS:
      for (i = 0; i < 3; ++i) printf(" %u", state.items[i]);
      printf("\n");
      break ;

    case CMDLINE_OP_EVAL_RULE:
    eval_rule_case:
      if (state.cur_rule == NULL)
      {
	printf("no rule selected\n");
	break ;
      }

      bfs_do(&b, &g, state.cur_rule);
      state.cur_dist = b.dist;
      printf("distance: %u\n", state.cur_dist);

      break ;

    case CMDLINE_OP_PRINT_GRID:
      grid_print(&g);
      break ;

    case CMDLINE_OP_QUIT:
      state.is_done = 1;
      break ;

    case CMDLINE_OP_INVALID:
    default:
      break ;
    }
  }

  grid_fini(&g);
  rulset_fini(&rulset);

  return 0;
}
Exemple #30
0
task main()
{
	writeDebugStream("-----------started big bothar f****r----------\n");

  state_init();
	bFloatDuringInactiveMotorPWM = false;

	int cub = escape_cubicle();



	if (cub == 1) {
		// 1 -> 2 -> 3 -> 1

		writeDebugStream("I just left cubicle 1\n");
		// Rotate 90 to right
		droid_rotate(90);

		// Fine move the sonar to the left
		sonar_move_at_async(90,true);
		// get to wall follow range.
		droid_move(DEFAULT_POWER);
		wait1Msec(1500);
		// Wall follow from 1 to 2
		follow_wall(21, 1, false);
		enter_cubicle(1);
		// exit cube
		droid_exit_cube();
		droid_rotate(-90);

		// Fine move the sonar to the left
		sonar_move_at_async(90, true);
		// get to wall follow range.
		droid_move(DEFAULT_POWER);
		wait1Msec(1500);
		// Wall follow from 2 to 3
		follow_wall(21, 1, false);
		enter_cubicle(1);
		// exit cube
		droid_exit_cube();
		droid_rotate(90);

		// Fine move the sonar to the right
		sonar_move_at_async(-90,true);
		// get to wall follow range.
		droid_move(DEFAULT_POWER);
		wait1Msec(1500);

		// Wall follow from 3 to 1
		follow_wall(21, -1, true);
		enter_cubicle(-1);
		// We're done!

	} else if (cub == 2) {
		writeDebugStream("I just left cubicle 2\n");
		// 2 -> 1 -> 3 -> 2

		// Rotate 90 to right
		droid_rotate(-90);
		// Fine move the sonar to the right
		sonar_move_at_async(-90,true)
		// get to wall follow range.
		droid_move(DEFAULT_POWER);
		wait1Msec(1500);
		// Wall follow from 2 to 1
		follow_wall(21,-1, false);
		enter_cubicle(-1);
		// exit cube
		droid_exit_cube();
		droid_rotate(-90);

		// Fine move the sonar back to left
		sonar_move_at_async(90,true);
		// get to wall follow range.
		droid_move(DEFAULT_POWER);
		wait1Msec(1500);
		// Wall follow from 1 to 3
		follow_wall(21,1,true);
		enter_cubicle(1);
		// exit cube
		droid_exit_cube();
		droid_rotate(90);



		// Fine move the sonar back to left
		sonar_move_at_async(-90,true);
		// get to wall follow range.
		droid_move(DEFAULT_POWER);
		wait1Msec(1500);
		// Wall follow from 3 to 2
		follow_wall(21, -1, false);
		enter_cubicle(-1);
		// We're done!


	} else if (cub == 3) {
		// 3 -> 2 -> 1 -> 3

		// Rotate 90 to right
		droid_rotate(-90);

		// Fine move the sonar to the right
		sonar_move_at_async(-90,true);
		// get to wall follow range.
		droid_move(DEFAULT_POWER);
		wait1Msec(1500);
		// Wall follow from 3 to 2
		follow_wall(21,-1, false);
		enter_cubicle(-1);
		// exit cube
		droid_exit_cube();
		droid_rotate(90);


		// Fine move the sonar to the right
		sonar_move_at_async(-90,true);
		// get to wall follow range.
		droid_move(DEFAULT_POWER);
		wait1Msec(1500);
		// Wall follow from 2 to 1
		follow_wall(21,-1,false);
		enter_cubicle(-1);
		// exit cube
		droid_exit_cube();
		droid_rotate(-90);

		// Fine move the sonar to the right
		sonar_move_at_async(90,true);
		// get to wall follow range.
		droid_move(DEFAULT_POWER);
		wait1Msec(1500);
		// Wall follow from 1 to 3
		follow_wall(21, 1, true);
		enter_cubicle(1);
		// We're done!

	} else {
		// better not get here
		writeDebugStream("UNREACHABLE CODE REACHED\n");
		StopAllTasks();
	}
}