void EnterPhaseAir()
 {
     phase = PHASE_FLIGHT;
     events.SetPhase(PHASE_FLIGHT);
     initEvents(false);
     m_uiChromaticCheckTimer = 5000;
 }
Esempio n. 2
0
MyWebView::MyWebView()
{        
    // 扩展页面对象
    pageExtension = new PageExtension(this);

    // 使用自扩展的 page 对象
    myPage = new MyWebPage();
    this->setPage(myPage);

    myFrame = myPage->mainFrame();

    // 初始化页面首次渲染标志
    firstPaintFinished = false;

    // 建立首屏监控对象
    firstScreen = new FirstScreen(myPage);

    // 设置新引用
    QNetworkAccessManager* oldManager = myPage->networkAccessManager();
    newManager = new NetworkAccessManager(oldManager, this);
    myPage->setNetworkAccessManager(newManager);

    // 设置cookie处理
    cookieJar = new QNetworkCookieJar();
    myPage->networkAccessManager()->setCookieJar(cookieJar);

    initEventNameMap();
    initEvents();

}
 void EnterPhaseGround()
 {
     phase = PHASE_GROUND;
     events.SetPhase(PHASE_GROUND);
     initEvents(true);
     m_uiOnyxiaCheckTimer = 5000;
     m_uiDistanceCheckTimer = 5000;
 }
//------------------------------------------------------------------------------
int main(void)
{
    tOplkError  ret = kErrorOk;
    const UINT8 aMacAddr[] = {MAC_ADDR};
    UINT8       nodeid;

    // Initialize helper modules
    gpio_init();
    lcd_init();

    // get node ID from input
    nodeid = gpio_getNodeid();

    // initialize instance
    memset(&instance_l, 0, sizeof(instance_l));

    instance_l.cycleLen     = CYCLE_LEN;
    instance_l.nodeId       = (nodeid != 0) ? nodeid : NODEID;
    instance_l.fShutdown    = FALSE;
    instance_l.fGsOff       = FALSE;

    // set mac address (last byte is set to node ID)
    memcpy(instance_l.aMacAddr, aMacAddr, sizeof(aMacAddr));
    instance_l.aMacAddr[5]  = instance_l.nodeId;

    initEvents(&eventCbPowerlink);
    arp_init((UINT8)instance_l.nodeId);

    PRINTF("----------------------------------------------------\n");
    PRINTF("openPOWERLINK embedded CN DEMO application\n");
    PRINTF("using openPOWERLINK Stack: %s\n", PLK_DEFINED_STRING_VERSION);
    PRINTF("----------------------------------------------------\n");

    PRINTF("NODEID=0x%02X\n", instance_l.nodeId);
    lcd_printNodeId(instance_l.nodeId);

    if ((ret = initPowerlink(&instance_l)) != kErrorOk)
        goto Exit;

    if ((ret = initApp()) != kErrorOk)
        goto Exit;

    if ((ret = oplk_setNonPlkForward(TRUE)) != kErrorOk)
        goto Exit;

    loopMain(&instance_l);

Exit:
    arp_exit();
    shutdownPowerlink(&instance_l);
    shutdownApp();

    // Shutdown helper modules
    lcd_exit();
    gpio_exit();

    return 0;
}
 void EnterPhaseGround()
 {
     phase = PHASE_GROUND;
     me->SetReactState(REACT_AGGRESSIVE);
     me->RemoveByteFlag(UNIT_FIELD_BYTES_1, 3, 0x02);
     me->RemoveUnitMovementFlag(MOVEMENTFLAG_CAN_FLY | MOVEMENTFLAG_FLYING);
     events.SetPhase(PHASE_GROUND);
     initEvents(true);
 }
 void EnterPhaseAir()
 {
     phase = PHASE_FLIGHT;
     me->SetReactState(REACT_PASSIVE);
     me->SetByteFlag(UNIT_FIELD_BYTES_1, 3, 0x02);
     me->AddUnitMovementFlag(MOVEMENTFLAG_CAN_FLY | MOVEMENTFLAG_FLYING);
     events.SetPhase(PHASE_FLIGHT);
     initEvents(false);
 }
LLVMModelDataSymbols::LLVMModelDataSymbols(const libsbml::Model *model,
        bool computeAndAssignConsevationLaws) :
        linearlyIndependentFloatingSpeciesSize(0),
        independentFloatingSpeciesSize(0),
        independentBoundarySpeciesSize(0),
        independentGlobalParameterSize(0),
        independentCompartmentSize(0)
{
    modelName = model->getName();

    // first go through the rules, see if they determine other stuff
    {
        const ListOfRules * rules = model->getListOfRules();
        for (unsigned i = 0; i < rules->size(); ++i)
        {
            const Rule *rule = rules->get(i);

            if (dynamic_cast<const AssignmentRule*>(rule))
            {
                assigmentRules.insert(rule->getVariable());
            }
            else if (dynamic_cast<const RateRule*>(rule))
            {
                uint rri = rateRules.size();
                rateRules[rule->getId()] = rri;
            }
            else if (dynamic_cast<const AlgebraicRule*>(rule))
            {
                poco_warning(getLogger(), string("encountered algegraic rule: ")
                        + rule->getId() + string(", currently not handled"));
            }
        }
    }

    // get the compartments, need to reorder them to set the independent ones
    // first
    initCompartments(model);


    // process the floating species
    initFloatingSpecies(model, computeAndAssignConsevationLaws);

    // display compartment info. We need to get the compartments before the
    // so we can get the species compartments. But the struct anal dumps
    // a bunch of stuff, so to keep things looking nice in the log, we
    // display the compartment info here.
    displayCompartmentInfo();

    initBoundarySpecies(model);

    initGlobalParameters(model);

    initReactions(model);

    initEvents(model);
}
Esempio n. 8
0
void VoicerUGenInternal::handleIncomingMidiMessage (MidiInput* /*source*/, const MidiMessage& message) throw()
{
	if(message.isForChannel(midiChannel_) == false)	return;
	
	if(message.isNoteOnOrOff())
	{
		const ScopedLock sl(lock);
		sendMidiNote(message.getChannel(), message.getNoteNumber(), message.getVelocity());
	}
	else if(message.isController())
	{
		if((message.getControllerNumber() == 123) && (message.getControllerValue() == 0))
		{
			const ScopedLock sl(lock);
			initEvents();
		}
			
		getController(message.getControllerNumber()) = 
					 (message.getControllerValue() * (1.f / 127.f));
	}
	else if(message.isPitchWheel())
	{
		getPitchWheel() = (jlimit(-8191, 8191, message.getPitchWheelValue() - 8192) * (1.f / 8191.f));
	}
	else if(message.isChannelPressure())
	{
		getChannelPressure() = (message.getChannelPressureValue() * (1.f / 127.f));
	}
	else if(message.isAftertouch())
	{
		getKeyPressure(message.getNoteNumber()) = 
					  (message.getAfterTouchValue() * (1.f / 127.f));
	}
	else if(message.isProgramChange())
	{
		getProgram() = (message.getProgramChangeNumber());
	}
	else if(message.isAllNotesOff())
	{
		const ScopedLock sl(lock);
		initEvents();
	}
}
Esempio n. 9
0
MainWindow::MainWindow(const wxString& title,
                       const wxPoint& pos,
                       const wxSize& size)
	: wxFrame( NULL, -1, title, pos, size ),
      m_menuBar(NULL),
      m_toolBar(NULL),
	  m_bitmap(wxBitmap()),
      m_hsizer(NULL)
{
  m_mgr.SetManagedWindow(this);
  wxInitAllImageHandlers();
  initMenuBar();

  SetMenuBar( m_menuBar );

  initToolBars();
  initMainPanel();
  {
    wxPanel * pnSettings = new wxPanel(this, wxID_ANY);
    wxPanel * p = pnSettings;
    wxButton * btnInpaint =
        new wxButton(p, wxID_ANY, wxT("Inpaint"), // wxBitmap(inpaint_xpm),
                     wxDefaultPosition, wxDefaultSize);
    wxBoxSizer * vsizer = new wxBoxSizer(wxVERTICAL);
    vsizer->Add(btnInpaint, 0,
                wxALIGN_CENTER | wxALIGN_CENTER_VERTICAL | wxEXPAND
                );
    p->SetSizer(vsizer);
    p->SetSize(wxSize(200,150));
    //if (0)
    {
      wxPanel * pInpaint = new wxPanel(this, wxID_ANY);
      wxSpinCtrl * scThreshold =
          new wxSpinCtrl(pInpaint, wxID_ANY, wxT("threshold"));
      scThreshold->SetValue(5);
      scThreshold->SetRange(1,100);

      wxBoxSizer * pInpaintSizer = new wxBoxSizer(wxVERTICAL);
      pInpaintSizer->Add(scThreshold, 0,
                         wxALIGN_CENTER|wxALIGN_CENTER_VERTICAL|wxEXPAND);
      pInpaint->SetSizer(pInpaintSizer);
      pInpaint->SetSize(200, 150);
      p = pInpaint;
      // m_mgr.AddPane(p, wxRIGHT, wxT("Inpaint Panel"));
    }
    m_mgr.AddPane(p, wxRIGHT, wxT("Manipulations Panel"));
  }
  

  initEvents();
  m_mgr.Update();
}
Esempio n. 10
0
 void EnterPhaseTwo()
 {
     Talk(SAY_COG);
     Talk(SAY_PHASE2);
     phase = PHASE_TWO;
     events.SetPhase(PHASE_TWO);
     initEvents(false);
     if (me->HasAura(SPELL_F_O_PERIODIC) && me->HasAura(SPELL_S_O_PERIODIC)) // Remove P1 Orders triggers.
     {
         me->RemoveAurasDueToSpell(SPELL_F_O_PERIODIC);
         me->RemoveAurasDueToSpell(SPELL_S_O_PERIODIC);
     }
     // DoCast(me, SPELL_CONSUME_BLOOD);
 }
//------------------------------------------------------------------------------
int main(void)
{
    tOplkError  ret = kErrorOk;
    const UINT8 aMacAddr[] = {MAC_ADDR};
    UINT8       nodeid;

    lcd_init();

    // get node ID from input
    nodeid = gpio_getNodeid();

    // initialize instance
    OPLK_MEMSET(&instance_l, 0, sizeof(instance_l));

    instance_l.cycleLen         = CYCLE_LEN;
    instance_l.nodeId           = (nodeid != 0) ? nodeid : NODEID;
    instance_l.fShutdown        = FALSE;
    instance_l.fGsOff           = FALSE;
    instance_l.pCdcBuffer       = (unsigned char*)aCdcBuffer;
    instance_l.cdcBufferSize    = sizeof(aCdcBuffer);

    // set mac address (last byte is set to node ID)
    OPLK_MEMCPY(instance_l.aMacAddr, aMacAddr, sizeof(aMacAddr));
    instance_l.aMacAddr[5] = instance_l.nodeId;

    initEvents(&instance_l.fGsOff);

    PRINTF("----------------------------------------------------\n");
    PRINTF("openPOWERLINK console MN DEMO application\n");
    PRINTF("using openPOWERLINK Stack: %s\n", PLK_DEFINED_STRING_VERSION);
    PRINTF("----------------------------------------------------\n");

    PRINTF("NODEID=0x%02X\n", instance_l.nodeId);
    lcd_printNodeId((WORD)instance_l.nodeId);

    if ((ret = initPowerlink(&instance_l)) != kErrorOk)
        goto Exit;

    if ((ret = initApp()) != kErrorOk)
        goto Exit;

    loopMain(&instance_l);

Exit:
    shutdownPowerlink(&instance_l);
    shutdownApp();

    return 0;
}
Esempio n. 12
0
File: BRTOS.c Progetto: brtos/brtos
void BRTOSInit(void)
{  
  ////////////////////////////////////////////////////////////  
  /////      Initialize Event Control Blocks             /////
  ////////////////////////////////////////////////////////////
  initEvents();
  
  ////////////////////////////////////////////////////////////  
  /////          Initialize global variables             /////
  ////////////////////////////////////////////////////////////  
  PreInstallTasks();  
  
  ////////////////////////////////////////////////////////////  
  /////            Initialize Tick Timer                 /////
  ////////////////////////////////////////////////////////////  
  TickTimerSetup(); 
}
Esempio n. 13
0
void OSystem_Wii::initBackend() {
	_startup_time = gettime();

	char buf[MAXPATHLEN];
	if (!getcwd(buf, MAXPATHLEN))
		strcpy(buf, "/");

	_savefile = new DefaultSaveFileManager(buf);
	_mixer = new Audio::MixerImpl(this);
	_timer = new DefaultTimerManager();

	_fullscreen = ConfMan.getBool("fullscreen");

	initGfx();
	initSfx();
	initEvents();

	OSystem::initBackend();
}
Esempio n. 14
0
void OSystem_Wii::initBackend() {
	_startup_time = gettime();

	ConfMan.registerDefault("fullscreen", true);
	ConfMan.registerDefault("aspect_ratio", true);
	ConfMan.registerDefault("wii_video_default_underscan_x", 16);
	ConfMan.registerDefault("wii_video_default_underscan_y", 16);
	ConfMan.registerDefault("wii_video_ds_underscan_x", 16);
	ConfMan.registerDefault("wii_video_ds_underscan_y", 16);
	ConfMan.registerDefault("wii_pad_sensitivity", 48);
	ConfMan.registerDefault("wii_pad_acceleration", 5);
	ConfMan.registerDefault("wii_smb_server", "");
	ConfMan.registerDefault("wii_smb_share", "");
	ConfMan.registerDefault("wii_smb_username", "");
	ConfMan.registerDefault("wii_smb_password", "");

	WiiFilesystemFactory &fsf = WiiFilesystemFactory::instance();

#ifdef USE_WII_SMB
	fsf.setSMBLoginData(ConfMan.get("wii_smb_server"),
						ConfMan.get("wii_smb_share"),
						ConfMan.get("wii_smb_username"),
						ConfMan.get("wii_smb_password"));
#endif

	fsf.asyncInit();

	char buf[MAXPATHLEN];
	if (!getcwd(buf, MAXPATHLEN))
		strcpy(buf, "/");

	_savefile = new DefaultSaveFileManager(buf);
	_timer = new DefaultTimerManager();

	initGfx();
	initSfx();
	initEvents();

	OSystem::initBackend();
}
//------------------------------------------------------------------------------
int main(int argc, char** argv)
{
    tOplkError                  ret = kErrorOk;
    tOptions                    opts;

    getOptions(argc, argv, &opts);

#if defined(__COBALT__)
    mlockall(MCL_CURRENT | MCL_FUTURE);
#endif

    if (system_init() != 0)
    {
        fprintf(stderr, "Error initializing system!");
        return 0;
    }

    initEvents(&fGsOff_l);

    printf("----------------------------------------------------\n");
    printf("openPOWERLINK console MN DEMO application\n");
    printf("using openPOWERLINK Stack: %s\n", PLK_DEFINED_STRING_VERSION);
    printf("----------------------------------------------------\n");

    if ((ret = initPowerlink(CYCLE_LEN, opts.cdcFile, aMacAddr_g)) != kErrorOk)
        goto Exit;

    if ((ret = initApp()) != kErrorOk)
        goto Exit;

    loopMain();

Exit:
    shutdownPowerlink();
    shutdownApp();
    system_exit();

    return 0;
}
Esempio n. 16
0
AudioObject::AudioObject(GameHandle gameHandle, 
                         const std::string& audioName,
						 boost::shared_ptr<StreamWatch> streamWatch,
						 const AOPresetData& presetData,
						 const AOLocation& location,
						 AudioBlaster& audioBlaster,
						 bool updateable) : 
mGameHandle(gameHandle),
mAudioName(audioName),
mUpdateHandler(NULL),
mStreamWatch(streamWatch),
mSourceId(0),
mAudioBlaster(audioBlaster),
mUpdateable(updateable)
{
	initEvents();
	initLocation(location);
	initPresetData(presetData);

	if (updateable)
		mUpdateHandler.reset(new OpenAlUpdateHandler(mSourceId, mGameHandle));
}
Esempio n. 17
0
void SSLManager::initDefaultContext(bool server)
{
	if (server && _ptrDefaultServerContext) return;
	if (!server && _ptrDefaultClientContext) return;

	initEvents(server);

	Poco::Util::LayeredConfiguration& config = Poco::Util::Application::instance().config();
	std::string prefix = server ? CFG_SERVER_PREFIX : CFG_CLIENT_PREFIX;
	if (!config.hasProperty(prefix+CFG_PRIV_KEY_FILE))
	{
		throw Poco::Util::EmptyOptionException(std::string("Missing Configuration Entry: ") + prefix+CFG_PRIV_KEY_FILE);
	}
	// mandatory options
	std::string privKeyFile = config.getString(prefix+CFG_PRIV_KEY_FILE);
	std::string caLocation = config.getString(prefix+CFG_CA_LOCATION);

	// optional options for which we have defaults defined
	Context::VerificationMode verMode = VAL_VER_MODE;
	if (config.hasProperty(prefix+CFG_VER_MODE))
	{
		// either: none, relaxed, strict, once
		std::string mode = config.getString(prefix+CFG_VER_MODE);
		verMode = Utility::convertVerificationMode(mode);
	}

	int verDepth = config.getInt(prefix+CFG_VER_DEPTH, VAL_VER_DEPTH);
	bool loadDefCA = config.getBool(prefix+CFG_ENABLE_DEFAULT_CA, VAL_ENABLE_DEFAULT_CA);
	std::string cypherList = config.getString(prefix+CFG_CYPHER_LIST, VAL_CYPHER_LIST);
	if (server)
	{
		_ptrDefaultServerContext = new Context(privKeyFile, caLocation, server, verMode, verDepth, loadDefCA, cypherList);
	}
	else
	{
		_ptrDefaultClientContext = new Context(privKeyFile, caLocation, server, verMode, verDepth, loadDefCA, cypherList);
	}
}
Esempio n. 18
0
//------------------------------------------------------------------------------
int main (int argc, char** argv)
{
    tOplkError                  ret = kErrorOk;
    tOptions                    opts;

    getOptions(argc, argv, &opts);

    if (system_init() != 0)
    {
        fprintf(stderr, "Error initializing system!");
        return 0;
    }

    initEvents(&fGsOff_l);

    printf("----------------------------------------------------\n");
    printf("openPOWERLINK console CN DEMO application\n");
    printf("using openPOWERLINK Stack: %s\n", PLK_DEFINED_STRING_VERSION);
    printf("----------------------------------------------------\n");

    if ((ret = initPowerlink(CYCLE_LEN, aMacAddr_l, opts.nodeId))
        != kErrorOk)
        goto Exit;

    if ((ret = initApp()) != kErrorOk)
        goto Exit;

    loopMain();

Exit:
    shutdownPowerlink();
    shutdownApp();
    system_exit();

    return 0;
}
Esempio n. 19
0
void SSLManager::initDefaultContext(bool server)
{
	if (server && _ptrDefaultServerContext) return;
	if (!server && _ptrDefaultClientContext) return;

	Poco::Crypto::OpenSSLInitializer openSSLInitializer;
	initEvents(server);
	Poco::Util::AbstractConfiguration& config = appConfig();

#ifdef OPENSSL_FIPS
	bool fipsEnabled = config.getBool(CFG_FIPS_MODE, VAL_FIPS_MODE);
	if (fipsEnabled && !Poco::Crypto::OpenSSLInitializer::isFIPSEnabled())
	{
		Poco::Crypto::OpenSSLInitializer::enableFIPSMode(true);
	}
#endif

	std::string prefix = server ? CFG_SERVER_PREFIX : CFG_CLIENT_PREFIX;

	// mandatory options
	std::string privKeyFile = config.getString(prefix + CFG_PRIV_KEY_FILE, "");
	std::string certFile = config.getString(prefix + CFG_CERTIFICATE_FILE, privKeyFile);
	std::string caLocation = config.getString(prefix + CFG_CA_LOCATION, "");

	if (server && certFile.empty() && privKeyFile.empty())
		throw SSLException("Configuration error: no certificate file has been specified");

	// optional options for which we have defaults defined
	Context::VerificationMode verMode = VAL_VER_MODE;
	if (config.hasProperty(prefix + CFG_VER_MODE))
	{
		// either: none, relaxed, strict, once
		std::string mode = config.getString(prefix + CFG_VER_MODE);
		verMode = Utility::convertVerificationMode(mode);
	}

	int verDepth = config.getInt(prefix + CFG_VER_DEPTH, VAL_VER_DEPTH);
	bool loadDefCA = config.getBool(prefix + CFG_ENABLE_DEFAULT_CA, VAL_ENABLE_DEFAULT_CA);
	std::string cipherList = config.getString(prefix + CFG_CIPHER_LIST, VAL_CIPHER_LIST);
	cipherList = config.getString(prefix + CFG_CYPHER_LIST, cipherList); // for backwards compatibility
	bool requireTLSv1 = config.getBool(prefix + CFG_REQUIRE_TLSV1, false);
	bool requireTLSv1_1 = config.getBool(prefix + CFG_REQUIRE_TLSV1_1, false);
	bool requireTLSv1_2 = config.getBool(prefix + CFG_REQUIRE_TLSV1_2, false);
	Context::Usage usage;

	if (server)
	{
		if (requireTLSv1_2)
			usage = Context::TLSV1_2_SERVER_USE;
		else if (requireTLSv1_1)
			usage = Context::TLSV1_1_SERVER_USE;
		else if (requireTLSv1)
			usage = Context::TLSV1_SERVER_USE;
		else
			usage = Context::SERVER_USE;
		_ptrDefaultServerContext = new Context(usage, privKeyFile, certFile, caLocation, verMode, verDepth, loadDefCA, cipherList);
	}
	else
	{
		if (requireTLSv1_2)
			usage = Context::TLSV1_2_CLIENT_USE;
		else if (requireTLSv1_1)
			usage = Context::TLSV1_1_CLIENT_USE;
		else if (requireTLSv1)
			usage = Context::TLSV1_CLIENT_USE;
		else
			usage = Context::CLIENT_USE;
		_ptrDefaultClientContext = new Context(usage, privKeyFile, certFile, caLocation, verMode, verDepth, loadDefCA, cipherList);
	}


	bool cacheSessions = config.getBool(prefix + CFG_CACHE_SESSIONS, false);
	if (server)
	{
		std::string sessionIdContext = config.getString(prefix + CFG_SESSION_ID_CONTEXT, config.getString("application.name", ""));
		_ptrDefaultServerContext->enableSessionCache(cacheSessions, sessionIdContext);
		if (config.hasProperty(prefix + CFG_SESSION_CACHE_SIZE))
		{
			int cacheSize = config.getInt(prefix + CFG_SESSION_CACHE_SIZE);
			_ptrDefaultServerContext->setSessionCacheSize(cacheSize);
		}
		if (config.hasProperty(prefix + CFG_SESSION_TIMEOUT))
		{
			int timeout = config.getInt(prefix + CFG_SESSION_TIMEOUT);
			_ptrDefaultServerContext->setSessionTimeout(timeout);
		}
	}
	else
	{
		_ptrDefaultClientContext->enableSessionCache(cacheSessions);
	}
	bool extendedVerification = config.getBool(prefix + CFG_EXTENDED_VERIFICATION, false);
	if (server)
		_ptrDefaultServerContext->enableExtendedCertificateVerification(extendedVerification);
	else
		_ptrDefaultClientContext->enableExtendedCertificateVerification(extendedVerification);
}
Esempio n. 20
0
int
main(int argc, char **argv)
{
    FdEventHandlerPtr listener;
    int i;
    int rc;
    int expire = 0, printConfig = 0;

    initAtoms();
    CONFIG_VARIABLE(daemonise, CONFIG_BOOLEAN, "Run as a daemon");
    CONFIG_VARIABLE(pidFile, CONFIG_ATOM, "File with pid of running daemon.");

    preinitChunks();
    preinitLog();
    preinitObject();
    preinitIo();
    preinitDns();
    preinitServer();
    preinitHttp();
    preinitDiskcache();
    preinitLocal();
    preinitForbidden();
    preinitSocks();
	preinitOffline();

    i = 1;
    while(i < argc) {
        if(argv[i][0] != '-')
            break;
        if(strcmp(argv[i], "--") == 0) {
            i++;
            break;
        } else if(strcmp(argv[i], "-h") == 0) {
            usage(argv[0]);
            exit(0);
        } else if(strcmp(argv[i], "-v") == 0) {
            printConfig = 1;
            i++;
        } else if(strcmp(argv[i], "-x") == 0) {
            expire = 1;
            i++;
        } else if(strcmp(argv[i], "-c") == 0) {
            i++;
            if(i >= argc) {
                usage(argv[0]);
                exit(1);
            }
            if(configFile)
                releaseAtom(configFile);
            configFile = internAtom(argv[i]);
            i++;
        } else {
            usage(argv[0]);
            exit(1);
        }
    }

    if(configFile)
        configFile = expandTilde(configFile);

    if(configFile == NULL) {
        configFile = expandTilde(internAtom("~/.polipo"));
        if(configFile)
            if(access(configFile->string, F_OK) < 0) {
                releaseAtom(configFile);
                configFile = NULL;
            }
    }

    if(configFile == NULL) {
        if(access("/etc/polipo/config", F_OK) >= 0)
            configFile = internAtom("/etc/polipo/config");
        if(configFile && access(configFile->string, F_OK) < 0) {
            releaseAtom(configFile);
            configFile = NULL;
        }
    }

    rc = parseConfigFile(configFile);
    if(rc < 0)
        exit(1);

    while(i < argc) {
        rc = parseConfigLine(argv[i], "command line", 0, 0);
        if(rc < 0)
            exit(1);
        i++;
    }

    initChunks();
    initLog();
    initObject();
    if(!expire && !printConfig)
        initEvents();
    initIo();
    initDns();
    initHttp();
    initServer();
    initDiskcache();
    initForbidden();
    initSocks();
	initOffline();

    if(printConfig) {
        printConfigVariables(stdout, 0);
        exit(0);
    }

    if(expire) {
        expireDiskObjects();
        exit(0);
    }

    if(daemonise)
        do_daemonise(logFile == NULL || logFile->length == 0);

    if(pidFile)
        writePid(pidFile->string);

    listener = create_listener(proxyAddress->string, 
                               proxyPort, httpAccept, NULL);
    if(!listener) {
        if(pidFile) unlink(pidFile->string);
        exit(1);
    }

    eventLoop();

    if(pidFile) unlink(pidFile->string);
    return 0;
}
Esempio n. 21
0
int parse (FILE *in, FILE *out) {
	char *input = malloc(MAXLEN);
	char *test = fgets(input, MAXLEN, in);
	
	size_t n = atoi(test); //number of events
	size_t step = 1; //current step;
	
	//create Events stacks
	AStack *Events = initEvents(n);
	if (!Events) {
		return 1;
	}
	
	//create process queue
	AQueue aQ = initQ(sizeof(TProcess));
	
	int check = 1; //used for checking function output
	
	test = fgets(input, MAXLEN, in);
	while (test != NULL && test[0] != '\n') {
		//tokenize input 
		char *cmd[3] = {0};
		int i = 0;
		char *aux = strtok(test, " \n");
		while (aux != NULL) {
			cmd[i] = aux;
			++i;
			aux = strtok(NULL, " \n");
		}
		
		if (cmd[0] != NULL) {
			//call function accordingly
			if (!strcmp(cmd[0], "start")) {
				check = start(atoi(cmd[1]), atoi(cmd[2]), step, aQ);
			} else if (!strcmp(cmd[0], "wait")) {
				check = wait(atoi(cmd[1]), atoi(cmd[2]), &aQ, Events);
			} else if (!strcmp(cmd[0], "event")) {
				check = event(atoi(cmd[1]), aQ, Events);
			} else if (!strcmp(cmd[0], "end")) {
				check = end(atoi(cmd[1]), &aQ);
			}
		}
		
		//if some of the functions encountered problems exit loop (and program)
		//most probably will not happen
		if (check != 1) {
			for (size_t i = 0; i < n; i++) {
				destroyS(&Events[i]);
			}
			free(Events);
			destroyQ(&aQ);
			free(input);
			return check;
		}
		
		printEnv(step, n, aQ, Events, out);
		test = fgets(input, MAXLEN, in);
		++step;
	}	
	
	//free what needs to be freed
	for (size_t i = 0; i < n; i++) {
		destroyS(&Events[i]);
	}
	free(Events);
	destroyQ(&aQ);
	free(input);
	return 1;
}
Esempio n. 22
0
SEXP call_rkImplicit(SEXP Xstart, SEXP Times, SEXP Func, SEXP Initfunc,
  SEXP Parms, SEXP eventfunc, SEXP elist, SEXP Nout, SEXP Rho,
  SEXP Tcrit, SEXP Verbose, SEXP Hini, SEXP Rpar, SEXP Ipar,
		  SEXP Method, SEXP Maxsteps, SEXP Flist) {

  /**  Initialization **/
  long int old_N_Protect = save_N_Protected();

  double *tt = NULL, *xs = NULL;

  double *y,  *f,  *Fj, *tmp, *tmp2, *tmp3, *FF, *rr;
  SEXP  R_yout;
  double *y0,  *y1, *dy1, *out, *yout;

  double t, dt, tmax;

  int fsal = FALSE;       /* fixed step methods have no FSAL */
  int interpolate = TRUE; /* polynomial interpolation is done by default */

  int i = 0, j=0, it=0, it_tot=0, it_ext=0, nt = 0, neq=0;
  int isForcing, isEvent;

  double *alpha;
  int *index;

  /**************************************************************************/
  /****** Processing of Arguments                                      ******/
  /**************************************************************************/
  double  tcrit = REAL(Tcrit)[0];
  double  hini  = REAL(Hini)[0];
  int  maxsteps = INTEGER(Maxsteps)[0];
  int  nout     = INTEGER(Nout)[0]; /* number of global outputs if func is in a DLL */
  int  verbose  = INTEGER(Verbose)[0];

  int stage     = (int)REAL(getListElement(Method, "stage"))[0];

  SEXP R_A, R_B1, R_C;
  double  *A, *bb1, *cc=NULL;

  PROTECT(R_A = getListElement(Method, "A")); incr_N_Protect();
  A = REAL(R_A);

  PROTECT(R_B1 = getListElement(Method, "b1")); incr_N_Protect();
  bb1 = REAL(R_B1);

  PROTECT(R_C = getListElement(Method, "c")); incr_N_Protect();
  if (length(R_C)) cc = REAL(R_C);
  
    double  qerr  = REAL(getListElement(Method, "Qerr"))[0];

  PROTECT(Times = AS_NUMERIC(Times)); incr_N_Protect();
  tt = NUMERIC_POINTER(Times);
  nt = length(Times);

  PROTECT(Xstart = AS_NUMERIC(Xstart)); incr_N_Protect();
  xs  = NUMERIC_POINTER(Xstart);
  neq = length(Xstart);

  /*------------------------------------------------------------------------*/
  /* timesteps (for advection computation in ReacTran)                      */
  /*------------------------------------------------------------------------*/
  for (i = 0; i < 2; i++) timesteps[i] = 0;
  
  /**************************************************************************/
  /****** DLL, ipar, rpar (to be compatible with lsoda)                ******/
  /**************************************************************************/
  int isDll = FALSE;
  //int ntot  = 0;
  int lrpar= 0, lipar = 0;
  int *ipar = NULL;

  if (inherits(Func, "NativeSymbol")) { /* function is a dll */
    isDll = TRUE;
    if (nout > 0) isOut = TRUE;
    //ntot  = neq + nout;           /* length of yout */
    lrpar = nout + LENGTH(Rpar);  /* length of rpar; LENGTH(Rpar) is always >0 */
    lipar = 3    + LENGTH(Ipar);  /* length of ipar */

  } else {                              /* function is not a dll */
    isDll = FALSE;
    isOut = FALSE;
    //ntot = neq;
    lipar = 3;    /* in lsoda = 1 */
    lrpar = nout; /* in lsoda = 1 */
  }
  out   = (double *) R_alloc(lrpar, sizeof(double)); 
  ipar  = (int *) R_alloc(lipar, sizeof(int));

  ipar[0] = nout;              /* first 3 elements of ipar are special */
  ipar[1] = lrpar;
  ipar[2] = lipar;
  if (isDll == 1) {
    /* other elements of ipar are set in R-function lsodx via argument *ipar* */
    for (j = 0; j < LENGTH(Ipar); j++) ipar[j+3] = INTEGER(Ipar)[j];
    /* out:  first nout elements of out are reserved for output variables
       other elements are set via argument *rpar*  */
    for (j = 0; j < nout; j++)         out[j] = 0.0;                
    for (j = 0; j < LENGTH(Rpar); j++) out[nout+j] = REAL(Rpar)[j];
  }

  /*------------------------------------------------------------------------*/
  /* Allocation of Workspace                                                */
  /*------------------------------------------------------------------------*/
  y0  =  (double *) R_alloc(neq, sizeof(double));
  y1  =  (double *) R_alloc(neq, sizeof(double));
  dy1 =  (double *) R_alloc(neq, sizeof(double));
  f   =  (double *) R_alloc(neq, sizeof(double));
  y   =  (double *) R_alloc(neq, sizeof(double));
  Fj  =  (double *) R_alloc(neq, sizeof(double));
  FF  =  (double *) R_alloc(neq * stage, sizeof(double));
  rr  =  (double *) R_alloc(neq * 5, sizeof(double));

  /* ks */
  alpha =  (double *) R_alloc(neq * stage * neq * stage, sizeof(double));
  index =  (int *)    R_alloc(neq * stage, sizeof(int));
  tmp   =  (double *) R_alloc(neq * stage, sizeof(double));
  tmp2  =  (double *) R_alloc(neq * stage, sizeof(double));
  tmp3  =  (double *) R_alloc(neq * stage, sizeof(double));


  /* matrix for polynomial interpolation */
  SEXP R_nknots;
  int nknots = 6;  /* 6 = 5th order polynomials by default*/
  int iknots = 0;  /* counter for knots buffer */
  double *yknots;

  PROTECT(R_nknots = getListElement(Method, "nknots")); incr_N_Protect();
  if (length(R_nknots)) nknots = INTEGER(R_nknots)[0] + 1;

  if (nknots < 2) {nknots=1; interpolate = FALSE;}
  
  yknots = (double *) R_alloc((neq + 1) * (nknots + 1), sizeof(double));


  /* matrix for holding states and global outputs */
  PROTECT(R_yout = allocMatrix(REALSXP, nt, neq + nout + 1)); incr_N_Protect();
  yout = REAL(R_yout);
  /* initialize outputs with NA first */
  for (i = 0; i < nt * (neq + nout + 1); i++) yout[i] = NA_REAL;

  /* attribute that stores state information, similar to lsoda */
  SEXP R_istate;
  int *istate;
  PROTECT(R_istate = allocVector(INTSXP, 22)); incr_N_Protect();
  istate = INTEGER(R_istate);
  istate[0] = 0; /* assume succesful return */
  for (i = 0; i < 22; i++) istate[i] = 0;

  /*------------------------------------------------------------------------*/
  /* Initialization of Parameters (for DLL functions)                       */
  /*------------------------------------------------------------------------*/
  PROTECT(Y = allocVector(REALSXP,(neq)));        incr_N_Protect(); 
  
  initParms(Initfunc, Parms);
  isForcing = initForcings(Flist);
  isEvent = initEvents(elist, eventfunc,0);
  if (isEvent) interpolate = FALSE;
  
  /*------------------------------------------------------------------------*/
  /* Initialization of Integration Loop                                     */
  /*------------------------------------------------------------------------*/
  yout[0]   = tt[0];              /* initial time                 */
  yknots[0] = tt[0];              /* for polynomial interpolation */
  for (i = 0; i < neq; i++) {
    y0[i]        = xs[i];         /* initial values               */
    yout[(i + 1) * nt] = y0[i];   /* output array                 */
    yknots[iknots + nknots * (i + 1)] = xs[i]; /* for polynomials */
  }
  iknots++;

  t = tt[0];                   
  tmax = fmax(tt[nt - 1], tcrit);

  /* Initialization of work arrays (to be on the safe side, remove this later) */
  for (i = 0; i < neq; i++)  {
    y1[i] = 0;
    Fj[i] = 0;
    for (j= 0; j < stage; j++)  {
      FF[i + j * neq] = 0;
    }
  }

  /*------------------------------------------------------------------------*/
  /* Main Loop                                                              */
  /*------------------------------------------------------------------------*/
  it     = 1; /* step counter; zero element is initial state   */
  it_ext = 0; /* counter for external time step (dense output) */
  it_tot = 0; /* total number of time steps                    */

  if (interpolate) {
  /* integrate over the whole time step and interpolate internally */
    rk_implicit( alpha, index, 
         fsal, neq, stage, isDll, isForcing, verbose, nknots, interpolate, 
         maxsteps, nt,
  	     &iknots, &it, &it_ext, &it_tot,
         istate, ipar,
  	     t, tmax, hini,
  	     &dt,
  	     tt, y0, y1, dy1, f, y, Fj, tmp, tmp2, tmp3, FF, rr, A,
  	     out, bb1, cc, yknots,  yout,
  	     Func, Parms, Rho
    );
  } else {
   for (int j = 0; j < nt - 1; j++) {
       t = tt[j];
       tmax = fmin(tt[j + 1], tcrit);
       dt = tmax - t;
       if (isEvent) {
         updateevent(&t, y0, istate);
       }
      rk_implicit(alpha, index, 
         fsal, neq, stage, isDll, isForcing, verbose, nknots, interpolate, 
         maxsteps, nt,
  	     &iknots, &it, &it_ext, &it_tot,
         istate, ipar,
  	     t, tmax, hini,
  	     &dt,
  	     tt, y0, y1, dy1, f, y, Fj, tmp, tmp2, tmp3, FF, rr, A,
  	     out, bb1, cc, yknots,  yout,
  	     Func, Parms, Rho
      );
      /* in this mode, internal interpolation is skipped,
         so we can simply store the results at the end of each call */
      yout[j + 1] = tmax;
      for (i = 0; i < neq; i++) yout[j + 1 + nt * (1 + i)] = y1[i];
    }
  }
  
  /*====================================================================*/
  /* call derivs again to get global outputs                            */
  /* j = -1 suppresses unnecessary internal copying                     */
  /*====================================================================*/

  if(nout > 0) {
    for (int j = 0; j < nt; j++) {
      t = yout[j];
      for (i = 0; i < neq; i++) tmp[i] = yout[j + nt * (1 + i)];
      derivs(Func, t, tmp, Parms, Rho, FF, out, -1, neq, ipar, isDll, isForcing);
      for (i = 0; i < nout; i++) {
        yout[j + nt * (1 + neq + i)] = out[i];
      }
    }
  }

  /* attach diagnostic information (codes are compatible to lsoda) */
  setIstate(R_yout, R_istate, istate, it_tot, stage, fsal, qerr, 0);

  /* release R resources */
  if (verbose) {
    Rprintf("Number of time steps it = %d, it_ext = %d, it_tot = %d\n", it, it_ext, it_tot);
    Rprintf("Maxsteps %d\n", maxsteps);
  }
  /* release R resources */
  timesteps[0] = 0;
  timesteps[1] = 0;
 
  restore_N_Protected(old_N_Protect);
  return(R_yout);
}
Esempio n. 23
0
int psiphonMain(
        int bindAll,
        int proxyPortParam,
        int localParentProxyPortParam)
{
    FdEventHandlerPtr listener;

    initAtoms();
    CONFIG_VARIABLE(daemonise, CONFIG_BOOLEAN, "Run as a daemon");
    CONFIG_VARIABLE(pidFile, CONFIG_ATOM, "File with pid of running daemon.");

    preinitChunks();
    preinitLog();
    preinitObject();
    preinitIo();
    preinitDns();
    preinitServer();
    preinitHttp();
    preinitDiskcache();
    preinitLocal();
    preinitForbidden();
    preinitSocks();

    const int MAX_SIZE = 80;
    char proxyAddressParamLine[MAX_SIZE];
    char proxyPortParamLine[MAX_SIZE];
    char localParentProxyPortParamLine[MAX_SIZE];
    snprintf(
        proxyAddressParamLine,
        MAX_SIZE,
        (0 == bindAll) ? "proxyAddress=127.0.0.1" : "proxyAddress=0.0.0.0");
    snprintf(
        proxyPortParamLine,
        MAX_SIZE,
        "proxyPort=%d",
        proxyPortParam);
    snprintf(
        localParentProxyPortParamLine,
        MAX_SIZE,
        "socksParentProxy=127.0.0.1:%d",
        localParentProxyPortParam);

    if (0 > parseConfigLine(proxyAddressParamLine, "psiphon", 0, 0)
        || 0 > parseConfigLine(proxyPortParamLine, "psiphon", 0, 0)
        || 0 > parseConfigLine(localParentProxyPortParamLine, "psiphon", 0, 0)
        || 0 > parseConfigLine("disableLocalInterface=true", "psiphon", 0, 0)
        || 0 > parseConfigLine("logLevel=1", "psiphon", 0, 0)
        /* Allow HTTPS on all ports */
        || 0 > parseConfigLine("tunnelAllowedPorts=1-65535", "psiphon", 0, 0))
    {
        return -1;
    }

    initChunks();
    initLog();
    initObject();
    initEvents();
    initIo();
    initDns();
    initHttp();
    initServer();
    initDiskcache();
    initForbidden();
    initSocks();

    listener = create_listener(
                    proxyAddress->string,
                    proxyPort,
                    httpAccept,
                    NULL);
    if (!listener)
    {
        return -1;
    }

    eventLoop();

    return 0;
}
Esempio n. 24
0
File: main.c Progetto: optixx/snes
void main(void) {

	initInternalRegisters();

	// Screen map data @ VRAM location $1000
	setTileMapLocation(0x1000, (byte) 0x00, (byte) 0);
	//*(byte*) 0x2107 = 0x10;
	
	// Plane 0 Tile graphics @ $2000
	setCharacterLocation(0x2000, (byte) 0);
	//*(byte*) 0x210b = 0x02;

	VRAMLoad((word) title_pic, 0x2000, 0x1BE0);
	VRAMLoad((word) title_map, 0x1000, 0x0800);
	CGRAMLoad((word) title_pal, (byte) 0x00, (word) 256);
	
	// TODO sitwch to mode 0 for trying
	*(byte*) 0x2105 = 0x01;	// MODE 1 value

	*(byte*) 0x212c = 0x01; // Plane 0 (bit one) enable register
	*(byte*) 0x212d = 0x00;	// All subPlane disable

	*(byte*) 0x2100 = 0x0f; // enable background

	currentScrollEvent = NULL;
	scrollValue = 0;

	initEvents();
	enablePad();

	addEvent(&NMIReadPad, 1);
	
	// Loop forever
	while(1) {

		waitForVBlank();

		if(pad1.left) {
			if(currentScrollEvent == NULL)
				currentScrollEvent = addEvent(&scrollLeft, 1);
		} 
		
		if(pad1.right) {
			if(currentScrollEvent != NULL) {
				removeEvent(currentScrollEvent);
				currentScrollEvent = NULL;
			} 
		}

		if(pad1.up) {
			addEvent(&fadeOut, 1);
			addEvent(&mosaicIn, 1);
		}

		if(pad1.down) {
			addEvent(&fadeIn, 1);
			addEvent(&mosaicOut, 1);
		}

		if(pad1.start) {
			debug();
		}
	}
}
Esempio n. 25
0
 void EnterPhaseOne()
 {
     phase = PHASE_ONE;
     events.SetPhase(PHASE_ONE);
     initEvents(true);
 }
//------------------------------------------------------------------------------
int main(void)
{
    tOplkError      ret = kErrorOk;
    const UINT8     aMacAddr[] = {MAC_ADDR};
    UINT8           nodeid;
#if (CONFIG_CDC_ON_SD != FALSE)
    tCdcBuffInfo    cdcBuffInfo;
#endif

    // Initialize helper modules
    gpio_init();
    lcd_init();

    // get node ID from input
    nodeid = gpio_getNodeid();

    // initialize instance
    memset(&instance_l, 0, sizeof(instance_l));

    instance_l.cycleLen         = CYCLE_LEN;
    instance_l.nodeId           = (nodeid != 0) ? nodeid : NODEID;
    instance_l.fShutdown        = FALSE;
    instance_l.fGsOff           = FALSE;
#if (CONFIG_CDC_ON_SD != FALSE)
    if (sdcard_getCdcOnSd(pszCdcFilename_g, &cdcBuffInfo) != 0)
    {
        goto Exit;
    }
    instance_l.pCdcBuffer       = (unsigned char*)cdcBuffInfo.pCdcBuffer;
    instance_l.cdcBufferSize    = cdcBuffInfo.cdcSize;
#else
    instance_l.pCdcBuffer       = (unsigned char*)aCdcBuffer;
    instance_l.cdcBufferSize    = sizeof(aCdcBuffer);
#endif
    // set mac address (last byte is set to node ID)
    memcpy(instance_l.aMacAddr, aMacAddr, sizeof(aMacAddr));
    instance_l.aMacAddr[5] = instance_l.nodeId;

    initEvents(&instance_l.fGsOff, &eventCbPowerlink);
    arp_init((UINT8)instance_l.nodeId);

    PRINTF("----------------------------------------------------\n");
    PRINTF("openPOWERLINK console MN DEMO application\n");
    PRINTF("using openPOWERLINK Stack: %s\n", PLK_DEFINED_STRING_VERSION);
    PRINTF("----------------------------------------------------\n");

    PRINTF("NODEID=0x%02X\n", instance_l.nodeId);
    lcd_printNodeId(instance_l.nodeId);

    if ((ret = initPowerlink(&instance_l)) != kErrorOk)
        goto Exit;

    if ((ret = initApp()) != kErrorOk)
        goto Exit;

    if ((ret = oplk_setNonPlkForward(TRUE)) != kErrorOk)
        goto Exit;

    loopMain(&instance_l);

Exit:
#if (CONFIG_CDC_ON_SD != FALSE)
    sdcard_freeCdcBuffer(&cdcBuffInfo);
#endif
    arp_exit();
    shutdownPowerlink(&instance_l);
    shutdownApp();

    // Shutdown helper modules
    lcd_exit();
    gpio_exit();

    return 0;
}
        void EnterCombat(Unit* /*who*/)
        {
            initEvents();

            _EnterCombat();
        }
Esempio n. 28
0
SEXP call_rkAuto(SEXP Xstart, SEXP Times, SEXP Func, SEXP Initfunc,
  SEXP Parms, SEXP eventfunc, SEXP elist, SEXP Nout, SEXP Rho,
  SEXP Rtol, SEXP Atol, SEXP Tcrit, SEXP Verbose,
  SEXP Hmin, SEXP Hmax, SEXP Hini, SEXP Rpar, SEXP Ipar,
  SEXP Method, SEXP Maxsteps, SEXP Flist) {

  /**  Initialization **/
  long int old_N_Protect = save_N_Protected();

  double *tt = NULL, *xs = NULL;

  double *y,  *f,  *Fj, *tmp, *FF, *rr;
  SEXP  R_yout;
  double *y0,  *y1,  *y2,  *dy1,  *dy2, *out, *yout;

  double errold = 0.0, t, dt, tmax;

  SEXP R_FSAL, Alpha, Beta;
  int fsal = FALSE;       /* assume no FSAL */
  
  /* Use polynomial interpolation if not disabled by the method
     or when events come in to play (stop-and-go mode).
     Methods with dense output interpolate by default,
     all others do not.
  */
  int interpolate = TRUE;

  int i = 0, j = 0, it = 0, it_tot = 0, it_ext = 0, nt = 0, neq = 0, it_rej = 0;
  int isForcing, isEvent;

  /*------------------------------------------------------------------------*/
  /* Processing of Arguments                                                */
  /*------------------------------------------------------------------------*/
  int lAtol = LENGTH(Atol);
  double *atol = (double*) R_alloc((int) lAtol, sizeof(double));

  int lRtol = LENGTH(Rtol);
  double *rtol = (double*) R_alloc((int) lRtol, sizeof(double));

  for (j = 0; j < lRtol; j++) rtol[j] = REAL(Rtol)[j];
  for (j = 0; j < lAtol; j++) atol[j] = REAL(Atol)[j];

  double  tcrit = REAL(Tcrit)[0];
  double  hmin  = REAL(Hmin)[0];
  double  hmax  = REAL(Hmax)[0];
  double  hini  = REAL(Hini)[0];
  int  maxsteps = INTEGER(Maxsteps)[0];
  int  nout     = INTEGER(Nout)[0]; /* number of global outputs is func is in a DLL */
  int  verbose  = INTEGER(Verbose)[0];

  int stage     = (int)REAL(getListElement(Method, "stage"))[0];

  SEXP R_A, R_B1, R_B2, R_C, R_D, R_densetype;
  double  *A, *bb1, *bb2 = NULL, *cc = NULL, *dd = NULL;

  PROTECT(R_A = getListElement(Method, "A")); incr_N_Protect();
  A = REAL(R_A);

  PROTECT(R_B1 = getListElement(Method, "b1")); incr_N_Protect();
  bb1 = REAL(R_B1);

  PROTECT(R_B2 = getListElement(Method, "b2")); incr_N_Protect();
  if (length(R_B2)) bb2 = REAL(R_B2);

  PROTECT(R_C = getListElement(Method, "c")); incr_N_Protect();
  if (length(R_C)) cc = REAL(R_C);

  PROTECT(R_D = getListElement(Method, "d")); incr_N_Protect();
  if (length(R_D)) dd = REAL(R_D);

  /* dense output Cash-Karp: densetype = 2 */
  int densetype = 0;
  PROTECT(R_densetype = getListElement(Method, "densetype")); incr_N_Protect();
  if (length(R_densetype)) densetype = INTEGER(R_densetype)[0];

  double  qerr = REAL(getListElement(Method, "Qerr"))[0];
  double  beta = 0;      /* 0.4/qerr; */

  PROTECT(Beta = getListElement(Method, "beta")); incr_N_Protect();
  if (length(Beta)) beta = REAL(Beta)[0];

  double  alpha = 1/qerr - 0.75 * beta;
  PROTECT(Alpha = getListElement(Method, "alpha")); incr_N_Protect();
  if (length(Alpha)) alpha = REAL(Alpha)[0];

  PROTECT(R_FSAL = getListElement(Method, "FSAL")); incr_N_Protect();
  if (length(R_FSAL)) fsal = INTEGER(R_FSAL)[0];

  PROTECT(Times = AS_NUMERIC(Times)); incr_N_Protect();
  tt = NUMERIC_POINTER(Times);
  nt = length(Times);

  PROTECT(Xstart = AS_NUMERIC(Xstart)); incr_N_Protect();
  xs  = NUMERIC_POINTER(Xstart);
  neq = length(Xstart);
  /*------------------------------------------------------------------------*/
  /* timesteps (for advection computation in ReacTran)                      */
  /*------------------------------------------------------------------------*/
  for (i = 0; i < 2; i++) timesteps[i] = 0;

  /*------------------------------------------------------------------------*/
  /* DLL, ipar, rpar (for compatibility with lsoda)                         */
  /*------------------------------------------------------------------------*/
  int isDll = FALSE;
  int lrpar= 0, lipar = 0;
  int *ipar = NULL;

  /* code adapted from lsoda to improve compatibility */
  if (inherits(Func, "NativeSymbol")) { 
    /* function is a dll */
    isDll = TRUE;
    if (nout > 0) isOut = TRUE;
    //ntot  = neq + nout;           /* length of yout */
    lrpar = nout + LENGTH(Rpar);  /* length of rpar; LENGTH(Rpar) is always >0 */
    lipar = 3    + LENGTH(Ipar);  /* length of ipar */

  } else {
    /* function is not a dll */
    isDll = FALSE;
    isOut = FALSE;
    //ntot = neq;
    lipar = 3;    /* in lsoda = 1 */
    lrpar = nout; /* in lsoda = 1 */
  }
  out   = (double*) R_alloc(lrpar, sizeof(double)); 
  ipar  = (int *) R_alloc(lipar, sizeof(int));

  /* first 3 elements of ipar are special */
  ipar[0] = nout;              
  ipar[1] = lrpar;
  ipar[2] = lipar;
  if (isDll == 1) {
    /* other elements of ipar are set in R-function lsodx via argument "ipar" */
    for (j = 0; j < LENGTH(Ipar); j++) ipar[j+3] = INTEGER(Ipar)[j];
 
    /* out: first nout elements of out are reserved for output variables
       other elements are set via argument "rpar" */
    for (j = 0; j < nout; j++)         out[j] = 0.0;                
    for (j = 0; j < LENGTH(Rpar); j++) out[nout+j] = REAL(Rpar)[j];
  }

  /*------------------------------------------------------------------------*/
  /* Allocation of Workspace                                                */
  /*------------------------------------------------------------------------*/
  y0  =  (double*) R_alloc(neq, sizeof(double));
  y1  =  (double*) R_alloc(neq, sizeof(double));
  y2  =  (double*) R_alloc(neq, sizeof(double));
  dy1 =  (double*) R_alloc(neq, sizeof(double));
  dy2 =  (double*) R_alloc(neq, sizeof(double));
  f   =  (double*) R_alloc(neq, sizeof(double));
  y   =  (double*) R_alloc(neq, sizeof(double));
  Fj  =  (double*) R_alloc(neq, sizeof(double));
  tmp =  (double*) R_alloc(neq, sizeof(double));
  FF  =  (double*) R_alloc(neq * stage, sizeof(double));
  rr  =  (double*) R_alloc(neq * 5, sizeof(double));

  /* matrix for polynomial interpolation */
  SEXP R_nknots;
  int nknots = 6;  /* 6 = 5th order polynomials by default*/
  int iknots = 0;  /* counter for knots buffer */
  double *yknots;

  PROTECT(R_nknots = getListElement(Method, "nknots")); incr_N_Protect();
  if (length(R_nknots)) nknots = INTEGER(R_nknots)[0] + 1;
  if (nknots < 2) {nknots = 1; interpolate = FALSE;}
  if (densetype > 0) interpolate = TRUE;
  yknots = (double*) R_alloc((neq + 1) * (nknots + 1), sizeof(double));

  /* matrix for holding states and global outputs */
  PROTECT(R_yout = allocMatrix(REALSXP, nt, neq + nout + 1)); incr_N_Protect();
  yout = REAL(R_yout);
  /* initialize outputs with NA first */
  for (i = 0; i < nt * (neq + nout + 1); i++) yout[i] = NA_REAL;

  /* attribute that stores state information, similar to lsoda */
  SEXP R_istate;
  int *istate;
  PROTECT(R_istate = allocVector(INTSXP, 22)); incr_N_Protect();
  istate = INTEGER(R_istate);
  istate[0] = 0; /* assume succesful return */
  for (i = 0; i < 22; i++) istate[i] = 0;

  /*------------------------------------------------------------------------*/
  /* Initialization of Parameters (for DLL functions)                       */
  /*------------------------------------------------------------------------*/
  PROTECT(Y = allocVector(REALSXP,(neq)));        incr_N_Protect(); 
  
  initParms(Initfunc, Parms);
  isForcing = initForcings(Flist);
  isEvent = initEvents(elist, eventfunc, 0);
  if (isEvent) interpolate = FALSE;

  /*------------------------------------------------------------------------*/
  /* Initialization of Integration Loop                                     */
  /*------------------------------------------------------------------------*/
  yout[0]   = tt[0];              /* initial time                 */
  yknots[0] = tt[0];              /* for polynomial interpolation */
  for (i = 0; i < neq; i++) {
    y0[i]        = xs[i];         /* initial values               */
    yout[(i + 1) * nt] = y0[i];   /* output array                 */
    yknots[iknots + nknots * (i + 1)] = xs[i]; /* for polynomials */
  }
  iknots++;

  t = tt[0];
  tmax = fmax(tt[nt - 1], tcrit);
  dt   = fmin(hmax, hini);
  hmax = fmin(hmax, tmax - t);

  /* Initialize work arrays (to be on the safe side, remove this later) */
  for (i = 0; i < neq; i++)  {
    y1[i] = 0;
    y2[i] = 0;
    Fj[i] = 0;
    for (j= 0; j < stage; j++)  {
      FF[i + j * neq] = 0;
    }
  }

  /*------------------------------------------------------------------------*/
  /* Main Loop                                                              */
  /*------------------------------------------------------------------------*/
  it     = 1; /* step counter; zero element is initial state   */
  it_ext = 0; /* counter for external time step (dense output) */
  it_tot = 0; /* total number of time steps                    */
  it_rej = 0;
  
  if (interpolate) {
  /* integrate over the whole time step and interpolate internally */
    rk_auto(
      fsal, neq, stage, isDll, isForcing, verbose, nknots, interpolate, 
      densetype, maxsteps, nt,
      &iknots, &it, &it_ext, &it_tot, &it_rej,
      istate, ipar, 
      t, tmax, hmin, hmax, alpha, beta,
      &dt, &errold,
      tt, y0, y1, y2, dy1, dy2, f, y, Fj, tmp, FF, rr, A,
      out, bb1, bb2, cc, dd, atol, rtol, yknots, yout,
      Func, Parms, Rho
    );
  } else {  
     /* integrate separately between external time steps; do not interpolate */
     for (int j = 0; j < nt - 1; j++) {
       t = tt[j];
       tmax = fmin(tt[j + 1], tcrit);
       dt = tmax - t;
       if (isEvent) {
         updateevent(&t, y0, istate);
       }
       if (verbose) Rprintf("\n %d th time interval = %g ... %g", j, t, tmax);
       rk_auto(
          fsal, neq, stage, isDll, isForcing, verbose, nknots, interpolate, 
          densetype, maxsteps, nt,
          &iknots, &it, &it_ext, &it_tot, &it_rej,
          istate, ipar,
          t,  tmax, hmin, hmax, alpha, beta,
          &dt, &errold,
          tt, y0, y1, y2, dy1, dy2, f, y, Fj, tmp, FF, rr, A,
          out, bb1, bb2, cc, dd, atol, rtol, yknots, yout,
          Func, Parms, Rho
      );
      /* in this mode, internal interpolation is skipped,
         so we can simply store the results at the end of each call */
      yout[j + 1] = tmax;
      for (i = 0; i < neq; i++) yout[j + 1 + nt * (1 + i)] = y2[i];
    }
  }

  /*====================================================================*/
  /* call derivs again to get global outputs                            */
  /* j = -1 suppresses unnecessary internal copying                     */
  /*====================================================================*/
  if (nout > 0) {
    for (int j = 0; j < nt; j++) {
      t = yout[j];
      for (i = 0; i < neq; i++) tmp[i] = yout[j + nt * (1 + i)];
      derivs(Func, t, tmp, Parms, Rho, FF, out, -1, neq, ipar, isDll, isForcing);
      for (i = 0; i < nout; i++) {
        yout[j + nt * (1 + neq + i)] = out[i];
      }
    }
  }

  /* attach diagnostic information (codes are compatible to lsoda) */
  setIstate(R_yout, R_istate, istate, it_tot, stage, fsal, qerr, it_rej);
  if (densetype == 2)   istate[12] = it_tot * stage + 2; /* number of function evaluations */

  /* verbose printing in debugging mode*/
  if (verbose) 
    Rprintf("\nNumber of time steps it = %d, it_ext = %d, it_tot = %d it_rej %d\n", 
      it, it_ext, it_tot, it_rej);

  /* release R resources */
  timesteps[0] = 0;
  timesteps[1] = 0;
  
  restore_N_Protected(old_N_Protect);
  return(R_yout);
}
Esempio n. 29
0
void EventManager::init() {
    loadLibs();

    initEvents();
}
Esempio n. 30
0
void VoicerUGenInternal::processBlock(bool& shouldDelete, const unsigned int blockID, const int /*channel*/) throw()
{	
	if(shouldStopAllEvents() == true) initEvents();
	
	if(midiMessages.isEmpty() == true)
	{
		const ScopedLock sl(lock);
		SpawnBaseUGenInternal::processBlock(shouldDelete, blockID, -1);
	}
	else
	{
		const int blockSize = uGenOutput.getBlockSize();
		MidiBuffer::Iterator iter(midiMessages);
		MidiMessage message(0xf4, 0.0);
		
		int samplePos = 0;
		int startSample = 0;
		
		const int numChannels = getNumChannels();
		const int midiChannel = midiChannel_;
		
		while(iter.getNextEvent(message, samplePos) && (samplePos < blockSize))
		{
			const ScopedLock sl(lock);
				
			if(samplePos < 0) samplePos = 0;
			
			const int numSamples = samplePos - startSample;
		
			if(numSamples > 0)
			{				
				for(int channel = 0; channel < numChannels; channel++)
				{
					bufferData[channel] = proxies[channel]->getSampleData() + startSample;
				}
				
				mixer.prepareForBlock(numSamples, blockID + startSample, -1);
				mixer.setOutputs(bufferData, numSamples, numChannels);
				mixer.processBlock(shouldDelete, blockID + startSample, -1);				
			}
			
			startSample = samplePos;
			
			if(message.isForChannel(midiChannel))
			{
				if(message.isNoteOnOrOff())
				{
					const int midiNote = message.getNoteNumber();
					const int velocity = message.getVelocity();
										
					if(velocity > 0)
					{
						if(numVoices_ > 0)
						{
							const int voicesUsed = countNonstealingVoices();
							if(voicesUsed >= numVoices_)
							{
								UGen stealee = chooseStealee();
								
								if(stealee.isNotNull())
								{
									stealee.userData = stealingUserData;
									stealee.steal(forcedSteal_);
								}
							}
						}
						
						// stop double notes, AU lab was sending two ons but one off - seems fixed in Au Lab 2.2
						//stealNote(midiChannel, midiNote, false, true); 
						
						UGen newEvent = spawnEvent(*this, currentEventIndex++, midiChannel, midiNote, velocity);
						newEvent.userData = createUserData(midiChannel, midiNote);
						events.add(newEvent);
					}
					else
					{
						UGen releasee = chooseReleasee(midiChannel, midiNote);
						if(releasee.isNotNull()) releasee.release();
					}
				}
				else if(message.isController())
				{
					getController(message.getControllerNumber()) = message.getControllerValue() / 127.f;
				}
				else if(message.isPitchWheel())
				{
					getPitchWheel() = (jlimit(-8191, 8191, message.getPitchWheelValue() - 8192) / 8191.f);
				}
				else if(message.isChannelPressure())
				{
					getChannelPressure() = (message.getChannelPressureValue() / 127.f);
				}
				else if(message.isAftertouch())
				{
					getKeyPressure(message.getNoteNumber()) = (message.getAfterTouchValue() / 127.f);
				}
				else if(message.isProgramChange())
				{
					getProgram() = (message.getProgramChangeNumber());
				}
				else if(message.isAllNotesOff())
				{
					initEvents();
				}
			}
		}
		
		const ScopedLock sl(lock);
		
		const int numSamples = blockSize - startSample;
		
		if(numSamples > 0)
		{			
			for(int channel = 0; channel < numChannels; channel++)
			{
				bufferData[channel] = proxies[channel]->getSampleData() + startSample;
			}
			
			mixer.prepareForBlock(numSamples, blockID + startSample, -1);
			mixer.setOutputs(bufferData, numSamples, numChannels);
			mixer.processBlock(shouldDelete, blockID + startSample, -1);
		}
				
		midiMessages.clear();
		events.removeNulls();
	}	
}