示例#1
0
文件: main.cpp 项目: Russell91/space
void *zmq_update(void* threadid) {
    void *context = zmq_ctx_new ();
    void *requester = zmq_socket (context, ZMQ_REQ);
    zmq_connect (requester, "tcp://localhost:5555");
    while (true) {

        if (pause_zmq) {
            sleep(1);
            continue;
        }
#ifdef SIMPLESIM
        sim.cpp_update();
        continue;
#endif
        printf ("Sending Hello %d…\n", 0);
        
        zmq_send (requester, "Hello", 5, 0);
        char buffer [NUM_STARS * sizeof(circ)];

        zmq_recv (requester, buffer, NUM_STARS * sizeof(circ), 0);
        sim.buffer_to_vec((circ*)buffer);
        int sum = 0;
        for (int i = 0; i < N; ++i) {
            sum += buffer[i];
        }
        printf ("Received %d\n", sum);
    }
}
示例#2
0
GroundAI::GroundAI(SimObject* s)
: ship((Ship*) s), target(0), subtarget(0), exec_time(0), carrier_ai(0)
{
    Sim*  sim         = Sim::GetSim();
    Ship* pship       = sim->GetPlayerShip();
    int   player_team = 1;
    int   ai_level    = 1;

    if (pship)
    player_team = pship->GetIFF();

    Player* player = Player::GetCurrentPlayer();
    if (player) {
        if (ship && ship->GetIFF() && ship->GetIFF() != player_team) {
            ai_level = player->AILevel();
        }
        else if (player->AILevel() == 0) {
            ai_level = 1;
        }
    }

    // evil alien ships are *always* smart:
    if (ship && ship->GetIFF() > 1 && ship->Design()->auto_roll > 1) {
        ai_level = 2;
    }

    if (ship && ship->GetHangar() && ship->GetCommandAILevel() > 0)
    carrier_ai = new(__FILE__,__LINE__) CarrierAI(ship, ai_level);
}
示例#3
0
void
StarServer::InstantiateMission()
{
    Memory::Check();

    current_mission = 0;

    if (Campaign::GetCampaign()) {
        current_mission = Campaign::GetCampaign()->GetMission();
    }

    Sim* sim = (Sim*) world;

    if (sim) {
        sim->UnloadMission();

        if (current_mission) {
            sim->LoadMission(current_mission);
            sim->ExecMission();
            sim->SetTestMode(false);

            Print("  Mission Instantiated.\n");
        }

        else {
            Print("  *** WARNING: StarServer::InstantiateMission() - no mission selected ***\n");
        }
    }

    Memory::Check();
}
示例#4
0
int main()
{        
    // Initialize Variables
    
    Sim sim = loadInit();    
    DataExporter de(outpath, sim);
    
    // If init file missing, write template init file. Otherwise, simulate.
    
    if (!loaded)
    {    
        cout << "No valid init file exists. Creating template init file..." << endl;
        writeTemplateInit();
    }    
    else // Simulate
    {        
        de.start();    
        cout << endl << "Simulating..." << endl;
        while (sim.t < end_t)
        {
            sim.advance(dt);
            de.log();
        }    
        de.write();
    }
    return 0;
}
void
FltDlg::OnAlert(AWEvent* event)
{
	if (!filter_list || !hangar_list || !ship) return;

	int         squad  = filter_list->GetSelectedIndex();
	Hangar*     hangar = ship->GetHangar();
	Sim*        sim    = Sim::GetSim();
	const char* call   = sim->FindAvailCallsign(ship->GetIFF());
	Element*    elem   = sim->CreateElement(call, ship->GetIFF());
	FlightDeck* deck   = 0;
	int         queue  = 1000;
	const int*  load   = 0;

	elem->SetSquadron(hangar->SquadronName(squad));
	elem->SetCarrier(ship);

	for (int i = 0; i < ship->NumFlightDecks(); i++) {
		FlightDeck* d = ship->GetFlightDeck(i);

		if (d && d->IsLaunchDeck()) {
			int dq = hangar->PreflightQueue(d);

			if (dq < queue) {
				queue = dq;
				deck  = d;
			}
		}
	}

	int nalert = 0;
	int slots[4];

	for (int i = 0; i < 4; i++)
	slots[i] = -1;

	for (int i = 0; i < hangar_list->NumItems(); i++) {
		if (hangar_list->IsSelected(i)) {
			int nslot = hangar_list->GetItemData(i);
			slots[nalert] = nslot;

			if (!load) {
				const HangarSlot* hangar_slot = hangar->GetSlot(squad, nslot);
				if (hangar_slot) {
					load = hangar->GetLoadout(hangar_slot);
					elem->SetLoadout((int*) load);
				}
			}

			hangar->GotoAlert(squad, nslot, deck, elem);
			hangar_list->SetSelected(i, false);
			nalert++;

			if (nalert >= 4)
			break;
		}
	}

	NetUtil::SendElemCreate(elem, squad, slots, true);
}
示例#6
0
int main (void)
{
    FILE *fd;

    double *ic, *p, *out;
    char* errbuf;
    long i, j, outd;
    long internal = 0;

    double dt = 0.00001;

    int time_steps = 1000000;
    double u[NINP];
    for (int k = 0; k < NINP; k++) u[k] = .1;

    fd = fopen("output.dat", "w");

    Sim sim = Sim(dt, NULL);
    sim.reset(out, NULL); // ic = NULL, use default start state

    for(i=0; i<time_steps; i++)
    {
        sim.step(out, u);
        fprintf(fd,"%lf ",out[0]);
        for(j=0; j<NOUT; j++)
        {
            fprintf(fd,"%lf ",out[j+1]);
        }
        fprintf(fd, "\n");
    }

    fclose(fd);

    return 0;
}
示例#7
0
文件: simtools.cpp 项目: dkj/simtools
void commandGenoSNP(string infile, string outfile, string manfile, int start_pos, int end_pos, bool verbose)
{
	Sim *sim = new Sim();
	ofstream outFStream;
	ostream *outStream;

	outStream = &cout;
	if (outfile == "-") {
	} else {
		outFStream.open(outfile.c_str(),ios::binary | ios::trunc | ios::out);
		outStream = &outFStream;
	}

	sim->open(infile);

	if (end_pos == -1) end_pos = sim->numSamples - 1;

	char *sampleName = new char[sim->sampleNameSize];
    vector<uint16_t> *intensity = new vector<uint16_t>;;
    for (int n=0; n <= end_pos ; n++) {
        intensity->clear();
        sim->getNextRecord(sampleName, intensity);
	if (n < start_pos) continue;
		*outStream << sampleName << "\t" << sampleName;
		for (vector<uint16_t>::iterator i = intensity->begin(); i != intensity->end(); i+=2) {
			*outStream << "\t" << std::fixed << setprecision(3) << *i;
			*outStream << " " << std::fixed << setprecision(3) << *(i+1);
		}
		*outStream << endl;
	}

	delete sim;
}
示例#8
0
文件: exp.cpp 项目: amitahire/sim
int main(int argc, char *argv[])
{
    Sim sim;

    sim.run();

    return 0;
}
NetPlayer::~NetPlayer()
{
	if (ship) {
		ship->SetNetworkControl();
		
		Sim* sim = Sim::GetSim();
		sim->DestroyShip(ship);
	}
}
void
NetGameClient::DoObjDamage(NetMsg* msg)
{
	if (!msg) return;

	NetObjDamage obj_damage;
	obj_damage.Unpack(msg->Data());

	Ship* ship = FindShipByObjID(obj_damage.GetObjID());
	if (ship) {
		Sim*        sim         = Sim::GetSim();
		Shot*       shot        = FindShotByObjID(obj_damage.GetShotID());
		const Ship* owner       = 0;
		const char* owner_name  = "[NET]";

		ship->InflictNetDamage(obj_damage.GetDamage(), shot);

		if (shot && sim) {
			if (shot->Owner()) {
				owner       = shot->Owner();
				owner_name  = owner->Name();
			}

			if (shot->IsMissile()) {
				SimRegion*  region = ship->GetRegion();
				float       scale  = ship->Design()->explosion_scale;

				if (scale <= 0)
				scale = ship->Design()->scale;

				if (owner) {
					const ShipDesign* owner_design = owner->Design();
					if (owner_design && owner_design->scale < scale)
					scale = (float) owner_design->scale;
				}

				sim->CreateExplosion(shot->Location(), Point(), Explosion::SHOT_BLAST, 20.0f * scale, scale, region);
			}

			if (!shot->IsBeam()) {
				if (owner) {
					ShipStats* stats = ShipStats::Find(owner_name);

					if (stats) {
						if (shot->IsPrimary())
						stats->AddGunHit();
						else if (shot->Damage() > 0)
						stats->AddMissileHit();
					}
				}

				shot->Destroy();
			}
		}
	}
}
示例#11
0
/** Runs the simulation with different starting positions for
 * ball 2, printing the final velocity angles of each ball for
 * each iteration. Used to find a set of initial conditions
 * corresponding with those stipulated in a sample problem.
 */
void bruteForceAngles(int coord, double start, double step, int n)
{
    for (int i = 0; i < n; i++)
    {
        Sim sim = loadInit();
        sim.balls[1].s[coord] = start + i * step;
        while (sim.t < end_t)
            sim.advance(dt);
        cout << "b2.s[" << coord <<"] " << start + i * step << " ; theta 1 =  " << 180 / M_PI * atan(sim.balls[0].v[1] / sim.balls[0].v[0]);
        cout << " theta 2 = " << 180 / M_PI * atan(sim.balls[1].v[1] / sim.balls[1].v[0]) << endl;        
    }
    
}
示例#12
0
/* Function: SimInitializeConditions ========================================
 * Abstract:
 *    In this function, you should initialize the continuous and discrete
 *    states for your S-function block.  The initial states are placed
 *    in the state vector, ssGetContStates(S) or ssGetRealDiscStates(S).
 *    You can also perform any other initialization activities that your
 *    S-function may require. Note, this routine will be called at the
 *    start of simulation and if it is present in an enabled subsystem
 *    configured to reset states, it will be call when the enabled subsystem
 *    restarts execution to reset the states.
 */
void SimInitializeConditions(SimStruct *S)
{
    Sim *sim = (Sim *) ssGetPWork(S)[0];   		// retrieve C++ object from the pointers vector and use member functions of the object

    try
    {
        sim->init_cond();
    }
    catch(Exception e)
    {
        e.kill(S);
        return;
    }
}
示例#13
0
/* Function: SimOutputs =======================================================
 * Abstract:
 *    In this function, you compute the outputs of your S-function
 *    block. Generally outputs are placed in the output vector, ssGetY(S).
 */
void SimOutputs(SimStruct *S, int_T tid)
{
    Sim *sim = (Sim *) ssGetPWork(S)[0];   		// retrieve C++ object from the pointers vector and use member functions of the object

    try
    {
        sim->output();
    }
    catch(Exception e)
    {
        e.kill(S);
        return;
    }
}
void
FltDlg::UpdateObjective()
{
	if (!objective_list || mission_type < 0 || !ship) return;

	Sim* sim = Sim::GetSim();
	char txt[32];

	for (int item = 0; item < objective_list->NumItems(); item++) {
		const char* obj_name = objective_list->GetItemText(item);

		Element* elem = sim->FindElement(obj_name);

		// if element has expired, remove it from the objective list
		if (!elem || !elem->IsActive() || elem->IsFinished()) {
			objective_list->RemoveItem(item);
			item--;
		}

		// otherwise, the element is still active, so update range/region
		else {
			Ship*    s   = elem->GetShip(1);
			double   r   = 0;
			bool     con = false;

			if (s) {
				Point s_loc = s->Location()    + s->GetRegion()->Location();
				Point h_loc = ship->Location() + ship->GetRegion()->Location();

				r = (s_loc - h_loc).length();

				con = ship->FindContact(s) != 0;

				if (con) {
					FormatNumber(txt, r);
				}
				else {
					strcpy_s(txt, Game::GetText("FltDlg.Unknown").data());
					r = 2e9;
				}
			}

			objective_list->SetItemText(item, 1, s->GetRegion()->Name());

			objective_list->SetItemText(item, 2, txt);
			objective_list->SetItemData(item, 2, (DWORD) r);
		}
	}
}
示例#15
0
/* Function: SimTerminate =====================================================
 * Abstract:
 *    In this function, you should perform any actions that are necessary
 *    at the termination of a simulation.  For example, if memory was
 *    allocated in SimStart, this is the place to free it.
 */
void SimTerminate(SimStruct *S)
{
    Sim *sim = (Sim *) ssGetPWork(S)[0]; 		// retrieve C++ object from the pointers vector

    try
    {
        sim->terminate();
    }
    catch(Exception e)
    {
        e.kill(S);
        return;
    }

    delete sim;									// Delete C++ object
}
示例#16
0
文件: simtools.cpp 项目: dkj/simtools
void commandView(string infile, bool verbose)
{
	Sim *sim = new Sim();

	cout << endl << "Reading SIM file: " << infile << endl;
	sim->open(infile);
	if (!sim->errorMsg.empty()) {
		cout << sim->errorMsg << endl;
		exit(1);
	}
	cout << "Magic:     " << sim->magic << endl;
	cout << "Version:   " << (int)sim->version << endl;
	cout << "Name Size: " << sim->sampleNameSize << endl;
	cout << "Samples:   " << sim->numSamples << endl;
	cout << "Probes:    " << sim->numProbes << endl;
	cout << "Channels:  " << (int)sim->numChannels << endl;
	cout << "Format:    " << (int)sim->numberFormat << endl;
	cout << "RecLength: " << (int)sim->recordLength << endl;
	cout << endl;

	char *sampleName = new char[sim->sampleNameSize];
	vector<uint16_t> *intensity_int = new vector<uint16_t>;
	vector<float> *intensity_float = new vector<float>;
	for (unsigned int n = 0; n < sim->numSamples; n++) {
		intensity_int->clear();
		intensity_float->clear();
		if (sim->numberFormat == 0) sim->getNextRecord(sampleName,intensity_float);
		else                        sim->getNextRecord(sampleName,intensity_int);
		cout << sampleName << "\t: ";
		if (verbose) {	// dump intensities as well as sample names
			// there *must* be a better way of doing this...
			if (sim->numberFormat == 0) {
				for (vector<float>::iterator i = intensity_float->begin(); i != intensity_float->end(); i++) {
					cout << *i << " ";
				}
			} else {
				for (vector<uint16_t>::iterator i = intensity_int->begin(); i != intensity_int->end(); i++) {
					cout << *i << " ";
				}
			}
		}
		cout << endl;
	}
	delete intensity_int;
	delete intensity_float;
	delete sampleName;
}
示例#17
0
/* Function: SimStart =======================================================
 * Abstract:
 *    This function is called once at start of model execution. If you
 *    have states that should be initialized once, this is the place
 *    to do it.
 */
void SimStart(SimStruct *S)
{
    //printf("---SimStart---\n");

    Sim *sim = createSim(S);   		 // create new sim object
    ssGetPWork(S)[0] = (void *) sim; // store new C++ object in the pointers vector

    try
    {
        sim->start();
    }
    catch(Exception e)
    {
        e.kill(S);
        return;
    }
}
示例#18
0
/* Function: SimDerivatives =================================================
 * Abstract:
 *    In this function, you compute the S-function block's derivatives.
 *    The derivatives are placed in the derivative vector, ssGetdX(S).
 */
void SimDerivatives(SimStruct *S)
{
    Sim *sim = (Sim *) ssGetPWork(S)[0];   		// retrieve C++ object from the pointers vector and use member functions of the object

    try
    {
        // Invalidate the dx pointers so they will be updated.
        sim->getInterfaceContainer()->invalidateDx();

        sim->derivative();
    }
    catch(Exception e)
    {
        e.kill(S);
        return;
    }
}
示例#19
0
SimObject*
Instruction::GetTarget()
{
    if (!target && tgt_name.length() > 0) {
        Sim*  sim = Sim::GetSim();

        if (sim) {
            Ship* s = sim->FindShip(tgt_name, rgn_name);

            if (s) {
                target = s;
                Observe(target);
            }
        }
    }

    return target;
}
示例#20
0
int main()
{
	Sim sim;

	//namedWindow( "Robot mower simulator");
	//imshow("bfield", imgBfield);

	printf("press...\n");
	printf("l   - toggle mowed lawn drawing\n");
	printf("+   - increase step wait\n");
	printf("-   - decrease step wait\n");
	printf("s   - skip tracking\n");
	printf("ESC - exit\n");

    int stepWait = 10;
	while( 1 ){
		// Exit on esc key
		char key = cvWaitKey( stepWait );
		switch (key){
		  case 27:
            return 0;
		  case '+':
            stepWait = min(20, stepWait +1);
            printf("stepWait=%d\n", stepWait);
		    break;
		  case '-':
            stepWait = max(5, stepWait -1);
            printf("stepWait=%d\n", stepWait);
		    break;
		  case 'l':
            sim.world.drawMowedLawn = !sim.world.drawMowedLawn;
            printf("toggled draw mowed lawn\n");
		    break;
          case 's':
            sim.robot.x = sim.robot.y = 100;
            sim.robot.state = STATE_LANE_FORW;
            break;
		}
		sim.step();
        sim.draw();
	}

	return 0;
}
示例#21
0
void
CmpSceneDlg::Show()
{
    FormWindow::Show();

    Starshatter* stars = Starshatter::GetInstance();

    if (stars->InCutscene()) {
        Sim* sim = Sim::GetSim();

        if (sim) {
            cam_view->UseCamera(CameraDirector::GetInstance()->GetCamera());
            cam_view->UseScene(sim->GetScene());
        }

        // initialize lens flare bitmaps:
        if (stars->LensFlare()) {
            cam_view->LensFlareElements(flare1, flare4, flare2, flare3);
            cam_view->LensFlare(true);
        }

        // if lens flare disabled, just create the corona:
        else if (stars->Corona()) {
            cam_view->LensFlareElements(flare1, 0, 0, 0);
            cam_view->LensFlare(true);
        }

        if (disp_view) {
            old_disp_win = disp_view->GetWindow();

            disp_view->SetWindow(mov_scene);
            mov_scene->AddView(disp_view);
        }

        if (subtitles_box) {
            subtitles_box->SetText(stars->GetSubtitles());
            subtitles_delay = 0;
            subtitles_time  = 0;
        }
    }
}
示例#22
0
TacticalAI::TacticalAI(ShipAI* ai)
: ship(0), ship_ai(0), carrier_ai(0), navpt(0), orders(0),
action(0), threat_level(0), support_level(1),
directed_tgtid(0)
{
    if (ai) {
        ship_ai     = ai;
        ship        = ai->GetShip();

        Sim* sim    = Sim::GetSim();

        if (ship && ship->GetHangar() && ship->GetCommandAILevel() > 0 &&
                ship != sim->GetPlayerShip())
        carrier_ai = new(__FILE__,__LINE__) CarrierAI(ship, ship_ai->GetAILevel());
    }

    agression      = 0;
    roe            = FLEXIBLE;
    element_index  = 1;
    exec_time      = exec_time_seed;
    exec_time_seed += 17;
}
示例#23
0
void
Element::ResumeAssignment()
{
	SetAssignment(0);

	if (objectives.isEmpty())
	return;

	Instruction* objective = 0;

	for (int i = 0; i < objectives.size() && !objective; i++) {
		Instruction* instr = objectives[i];

		if (instr->Status() <= Instruction::ACTIVE) {
			switch (instr->Action()) {
			case Instruction::INTERCEPT:
			case Instruction::STRIKE:
			case Instruction::ASSAULT:
				objective = instr;
				break;
			}
		}
	}

	if (objective) {
		Sim* sim = Sim::GetSim();

		ListIter<Element> iter = sim->GetElements();
		while (++iter) {
			Element*    elem = iter.value();
			SimObject*  tgt  = objective->GetTarget();

			if (tgt && tgt->Type() == SimObject::SIM_SHIP && elem->Contains((const Ship*) tgt)) {
				SetAssignment(elem);
				return;
			}
		}
	}
}
void
RadioTraffic::SendMessage(RadioMessage* msg)
{
	if (!msg) return;

	Sim*  sim    = Sim::GetSim();
	Ship* player = sim->GetPlayerShip();
	int   iff    = 0;

	if (player)
	iff = player->GetIFF();

	if (msg->DestinationShip()) {
		traffic.append(msg);

		if (msg->Channel() == 0 || msg->Channel() == iff)
		DisplayMessage(msg);

		if (!NetGame::IsNetGameClient())
		msg->DestinationShip()->HandleRadioMessage(msg);
	}

	else if (msg->DestinationElem()) {
		traffic.append(msg);

		if (msg->Channel() == 0 || msg->Channel() == iff)
		DisplayMessage(msg);

		if (!NetGame::IsNetGameClient())
		msg->DestinationElem()->HandleRadioMessage(msg);
	}

	else {
		if (msg->Channel() == 0 || msg->Channel() == iff)
		DisplayMessage(msg);

		delete msg;
	}
}
示例#25
0
void
DebriefDlg::OnClose(AWEvent* event)
{
    Sim* sim = Sim::GetSim();

    sim->CommitMission();
    sim->UnloadMission();

    NetLobby* lobby = NetLobby::GetInstance();
    if (lobby && lobby->IsHost()) {
        lobby->SelectMission(0);
        lobby->ExecFrame();
    }

    Player* player = Player::GetCurrentPlayer();
    if (player && player->ShowAward()) {
        manager->ShowAwardDlg();
    }

    else {
        Starshatter* stars = Starshatter::GetInstance();

        if (stars) {
            Mouse::Show(false);

            Campaign* campaign = Campaign::GetCampaign();
            if (campaign && campaign->GetCampaignId() < Campaign::SINGLE_MISSIONS)
            stars->SetGameMode(Starshatter::CMPN_MODE);
            else
            stars->SetGameMode(Starshatter::MENU_MODE);
        }

        else {
            Game::Panic("DebriefDlg::OnClose() - Game instance not found");
        }
    }
}
示例#26
0
void
StarServer::SetGameMode(int m)
{
    if (game_mode == m)
    return;

    if (m == LOAD_MODE) {
        Print("  game_mode = LOAD_MODE\n");
        paused = true;
    }

    else if (m == PLAY_MODE) {
        Print("  game_mode = PLAY_MODE\n");

        if (!world) {
            CreateWorld();
            InstantiateMission();
        }

        // stand alone server should wait for players to connect
        // before unpausing the simulation...
        SetTimeCompression(1);
        Pause(true);
    }

    else if (m == MENU_MODE) {
        Print("  game_mode = MENU_MODE\n");
        paused = true;

        Sim* sim = (Sim*) world;

        if (sim)
        sim->UnloadMission();
    }

    game_mode = m;
}
bool
NetPlayer::DoObjHyper(NetObjHyper* obj_hyper)
{
	if (ship && obj_hyper) {
		Sim*        sim       = Sim::GetSim();
		SimRegion*  rgn       = sim->FindRegion(obj_hyper->GetRegion());
		DWORD       fc1_id    = obj_hyper->GetFarcaster1();
		DWORD       fc2_id    = obj_hyper->GetFarcaster2();
		Ship*       fc1       = 0;
		Ship*       fc2       = 0;
		int         trans     = obj_hyper->GetTransitionType();

		if (ship->GetRegion() == rgn) {
			::Print("NetPlayer::DoObjHyper ship: '%s' rgn: '%s' trans: %d (IGNORED)\n\n",
			ship->Name(), obj_hyper->GetRegion().data(), trans);

			return false;
		}

		::Print("NetPlayer::DoObjHyper ship: '%s' rgn: '%s' trans: %d\n\n",
		ship->Name(), obj_hyper->GetRegion().data(), trans);

		// orbital transition?
		if (trans == Ship::TRANSITION_DROP_ORBIT) {
			ship->SetTransition(1.0f, Ship::TRANSITION_DROP_ORBIT, ship->Location());
			ship->CompleteTransition();
		}

		else if (trans == Ship::TRANSITION_MAKE_ORBIT) {
			ship->SetTransition(1.0f, Ship::TRANSITION_MAKE_ORBIT, ship->Location());
			ship->CompleteTransition();
		}

		else {
			if (fc1_id)
			fc1 = sim->FindShipByObjID(fc1_id);

			if (fc2_id)
			fc2 = sim->FindShipByObjID(fc2_id);

			sim->CreateExplosion(ship->Location(), Point(0,0,0), 
			Explosion::QUANTUM_FLASH, 1.0f, 0, ship->GetRegion());

			sim->RequestHyperJump(ship, rgn, obj_hyper->GetLocation(), trans, fc1, fc2);

			ShipStats* stats = ShipStats::Find(ship->Name());
			stats->AddEvent(SimEvent::QUANTUM_JUMP, rgn->Name());
		}

		return true;
	}

	return false;
}
示例#28
0
void PlantScript::DoTick(U32 delta)
{
	// We need process at a steady rate so that
	// the time between ticks is constant.
	// This is performance regressive, so something
	// to keep an eye on.
	static const int MAP2 = MAX_MAP_SIZE*MAX_MAP_SIZE;
	static const int DELTA = 100*1000;	// How frequenty to tick a given plant
	static const int N_PER_MSEC = MAP2 / DELTA;
	static const int GROWTH_CHANCE = 8;
	static const int PRIME = 1553;

	static const float SHADE_EFFECT = 0.7f;

	int n = N_PER_MSEC * delta;
	Weather* weather = Weather::Instance();

	WorldMap* worldMap = context->worldMap;
	Rectangle2I bounds = worldMap->Bounds();
	bounds.Outset(-1);	// edge of map: don't want to tap over the edge.

	const Vector3F& light = context->engine->lighting.direction;
	const float		norm = Max(fabs(light.x), fabs(light.z));
	Vector2I		lightTap = { int(LRintf(light.x / norm)), int(LRintf(light.z / norm)) };
	Census*			census = &context->chitBag->census;

	for (int i = 0; i < n; ++i) {
		index += PRIME;

		int x = IndexToMapX(index);
		int y = IndexToMapY(index);

		const WorldGrid& wg = worldMap->GetWorldGrid(x, y);
		if (!wg.Plant()) continue;

		Vector2I pos2i = { x, y };
		Vector2F pos2f = ToWorld2F(pos2i);

		// --- Light Tap --- //
		const float	height = PlantScript::PlantRes(wg.Plant() - 1, wg.PlantStage())->AABB().SizeY();
		const float	rainBase		= weather->RainFraction(pos2f.x, pos2f.y);
		const float sunBase			= (1.0f - rainBase);
		const float temperatureBase	= weather->Temperature(pos2f.x, pos2f.y);

		float rain			= rainBase;
		float sun			= sunBase;
		float temperature	= temperatureBase;
		float growth		= 1.0f;

		Vector2I tap = pos2i + lightTap;

		// Check for something between us and the light.
		const WorldGrid& wgTap = worldMap->GetWorldGrid(tap);
		float tapHeight = float(wgTap.RockHeight());
		if (wgTap.PlantStage()) {
			tapHeight = PlantScript::PlantRes(wgTap.Plant() - 1, wgTap.PlantStage())->AABB().SizeY();
		}

		if (tapHeight > (height + 0.1f)) {
			// in shade
			sun *= SHADE_EFFECT;
			temperature *= SHADE_EFFECT;
		}

		// ---- Adjacent --- //
		static const int NADJ = 4;
		static const Vector2I check[NADJ] = { { -1, 0 }, { 1, 0 }, { 0, -1 }, { 0, 1 } };
		int same = 0;
		for (int i = 0; i<NADJ; ++i) {
			tap = pos2i + check[i];
			const WorldGrid& wgAdj = worldMap->GetWorldGrid(tap.x, tap.y);
			if (wgAdj.Plant() == wg.Plant()) {
				++same;
			}

			if (wgAdj.RockHeight()) {
				// Water or rock runoff increase water.
				rain += 0.25f * rainBase;
			}
			if (wgAdj.IsFluid()) {
				rain += 0.25f;	// just a lot of water.
			}
			if (wgAdj.IsWater()) {
				rain += 0.25f;	// more water
				temperature = Mean(0.5f, temperature); // moderate temperature
			}
		}
		// Nutrient depletion? Too packed in?
		if (same == NADJ) {
			growth *= 0.25f;
		}

		// Are we under water?
		float fluidHeight = wg.FluidHeight();
		if (fluidHeight > 0.01f) {
			// Any amount of water goes to rain 100%
			rain = 1.0f;
			// not sure what to do with temp...assume a little cooler?
			temperature *= 0.8f;

			// blocks light...
			float sizeY = PlantScript::PlantRes(wg.Plant() - 1, wg.PlantStage())->AABB().SizeY();
			if (fluidHeight > sizeY)
				sun = 0;
			else if (fluidHeight > sizeY * 0.5f)
				sun = sun * (1.0f - fluidHeight / sizeY);
		}

		rain = Clamp(rain, 0.0f, 1.0f);
		temperature = Clamp(temperature, 0.0f, 1.0f);
		sun = Clamp(sun, 0.0f, 1.0f);

		// ------- calc ------- //
		Vector3F actual = { sun, rain, temperature };
		Vector3F optimal = { 0.5f, 0.5f, 0.5f };

		const GameItem* item = PlantScript::PlantDef(wg.Plant() - 1);
		item->keyValues.Get(ISC::sun, &optimal.x);
		item->keyValues.Get(ISC::rain, &optimal.y);
		item->keyValues.Get(ISC::temp, &optimal.z);

		float distance = (optimal - actual).Length();
		distance = distance / growth;

		const float GROW = Lerp(0.2f, 0.1f, (float)wg.PlantStage() / (float)(MAX_PLANT_STAGES - 1));
		const float DIE = 0.4f;
		float seconds = float(DELTA) / 1000.0f;

		if (distance < GROW) {
			// Heal.
			float hp = HP_PER_SECOND*seconds;
			DamageDesc heal( -hp, 0 );
			worldMap->VoxelHit(pos2i, heal);

			// Grow
			int nStage = wg.IsFlower() ? PLANT_BLOCKING_STAGE : MAX_PLANT_STAGES;

			if (wg.HPFraction() > 0.8f) {
				if (wg.PlantStage() < (nStage - 1)) {
					int hp = wg.HP();
					worldMap->SetPlant(pos2i.x, pos2i.y, wg.Plant(), wg.PlantStage() + 1);
					worldMap->SetWorldGridHP(pos2i.x, pos2i.y, hp);
				}
				if (random.Rand(GROWTH_CHANCE) < wg.PlantStage()) {
					// Number range reflects wind direction.
					int dx = -1 + random.Rand(4);	// [-1,2]
					int dy = -1 + random.Rand(3);	// [-1,1]

					// Remember that create plant will favor creating
					// existing plants, so we don't need to specify
					// what to create.
					Sim* sim = context->chitBag->GetSim();
					GLASSERT(sim);
					sim->CreatePlant(pos2i.x + dx, pos2i.y + dy, -1);
				}
			}
			int stage = wg.PlantStage();	// 0-3
			CoreScript* cs = CoreScript::GetCore(ToSector(pos2i));
			// Totally "what feels right in world gen" constant in the random.Rand()
			if ((census->wildFruit < MAX_WILD_FRUIT) && cs && (!cs->InUse()) && int(random.Rand(200)) < (stage*stage)) {
				context->chitBag->NewWildFruit(pos2i);
			}
		}
		else if (distance > DIE) {
			DamageDesc dd(HP_PER_SECOND * seconds, 0);
			worldMap->VoxelHit(pos2i, dd);
			if (wg.HP() == 0) {
				worldMap->SetPlant(pos2i.x, pos2i.y, 0, 0);
			}
		}
	}
}
示例#29
0
int 
main(int argc, char **argv)
{
	Sim::initSim();
	Sim *sim = Sim::getSim();

	int delay = 1;
	int lines = 100;
	int line_size = 128;	//has to be a multiple of 8
	int cachel1_id1 = 1;
	int cachel1_id2 = 2;
	int cachel2_id = 10;
	int processor_id1 = 1;
	int processor_id2 = 2;

	//allocate buffers
	unsigned long *buffer;
	char *dirty_bit_buffer;
	buffer = new unsigned long[lines];
	dirty_bit_buffer = new char[lines];

	Processor p1(processor_id1, "small1.out");
	Processor p2(processor_id1, "small1.out");
	
	Cache l1_1(cachel1_id1, delay, lines, line_size, buffer, dirty_bit_buffer);
	Cache l1_2(cachel1_id2, delay, lines, line_size, buffer, dirty_bit_buffer);

	Cache l2(cachel2_id, 5*delay, 5*lines, line_size, buffer, dirty_bit_buffer);

	Bus b(3);

	Memory m(1);

	/*p.out.data >> m.in.data;
	m.out.busy >> p.in.busy;
	m.out.data >> p.in.data;*/

	/*p.out.data >> l1.p_in.data;
	l1.p_out.busy >> p.in.busy;
	l1.p_out.data >> p.in.data;
	l1.m_out.data >> m.in.data;
	m.out.busy >> l1.m_in.busy;
	m.out.data >> l1.m_in.data; */


	//Port connections of p1 and l1_1
	p1.out.data >> l1_1.p_in.data;
	l1_1.p_out.busy >> p1.in.busy;
	l1_1.p_out.data >> p1.in.data;

	//Port connections of p2 and l1_2
	p2.out.data >> l1_2.p_in.data;
	l1_2.p_out.busy >> p2.in.busy;
	l1_2.p_out.data >> p2.in.data;

	//Port connections of l1_1 and bus
	l1_1.m_out.data >> b.l1_in1.data;
	b.l1_out1.busy >> l1_1.m_in.busy;
	b.l1_out1.data >> l1_1.m_in.data;
/*
	//Port connections of l1_2 and bus
	l1_2.m_out.data >> b.l1_in2.data;
	b.l1_out2.busy >> l1_2.m_in.busy;
	b.l1_out2.data >> l1_2.m_in.data;

	//Port connections of bus and l2
	b.l2_out.data >> l2.p_in.data;
	l2.p_out.busy >> b.l2_in.busy;
	l2.p_out.data >> b.l2_in.data;
*/
	//Port connections of l2 and memory
	l2.m_out.data >> m.in.data;
	m.out.busy >> l2.m_in.busy;
	m.out.data >> l2.m_in.data;

	sim->Reset();
	sim->Run();
	sim->Print();

	delete []buffer;
	delete []dirty_bit_buffer;

	return 0;
}
示例#30
0
int main()
{
	Sim *sim = new Sim();
	sim->run();
	return 0;
}