size_t NonblockingSource::GeneralPump2( lword& byteCount, bool blockingOutput, unsigned long maxTime, bool checkDelimiter, byte delimiter) { m_blockedBySpeedLimit = false; if (!GetMaxBytesPerSecond()) { size_t ret = DoPump(byteCount, blockingOutput, maxTime, checkDelimiter, delimiter); m_doPumpBlocked = (ret != 0); return ret; } bool forever = (maxTime == INFINITE_TIME); unsigned long timeToGo = maxTime; Timer timer(Timer::MILLISECONDS, forever); lword maxSize = byteCount; byteCount = 0; timer.StartTimer(); while (true) { lword curMaxSize = UnsignedMin(ComputeCurrentTransceiveLimit(), maxSize - byteCount); if (curMaxSize || m_doPumpBlocked) { if (!forever) timeToGo = SaturatingSubtract(maxTime, timer.ElapsedTime()); size_t ret = DoPump(curMaxSize, blockingOutput, timeToGo, checkDelimiter, delimiter); m_doPumpBlocked = (ret != 0); if (curMaxSize) { NoteTransceive(curMaxSize); byteCount += curMaxSize; } if (ret) return ret; } if (maxSize != ULONG_MAX && byteCount >= maxSize) break; if (!forever) { timeToGo = SaturatingSubtract(maxTime, timer.ElapsedTime()); if (!timeToGo) break; } double waitTime = TimeToNextTransceive(); if (!forever && waitTime > timeToGo) { m_blockedBySpeedLimit = true; break; } WaitObjectContainer container; LimitedBandwidth::GetWaitObjects(container, CallStack("NonblockingSource::GeneralPump2() - speed limit", 0)); container.Wait((unsigned long)waitTime); } return 0; }
int main() { GDT::init(); Console::init(); IDT::init(); ExceptionHandler::init_dispatcher(); IRQ::init(); InterruptHandler::init_dispatcher(); /* -- EXAMPLE OF AN EXCEPTION HANDLER -- */ class DBZ_Handler : public ExceptionHandler { public: virtual void handle_exception(REGS * _regs) { Console::puts("DIVISION BY ZERO!\n"); for(;;); } } dbz_handler; ExceptionHandler::register_handler(0, &dbz_handler); /* -- INITIALIZE MEMORY -- */ /* NOTE: We don't have paging enabled in this MP. */ /* NOTE2: This is not an exercise in memory management. The implementation of the memory management is accordingly *very* primitive! */ /* ---- Initialize a frame pool; details are in its implementation */ FramePool system_frame_pool; SYSTEM_FRAME_POOL = &system_frame_pool; /* ---- Create a memory pool of 256 frames. */ MemPool memory_pool(SYSTEM_FRAME_POOL, 256); MEMORY_POOL = &memory_pool; /* -- INITIALIZE THE TIMER (we use a very simple timer).-- */ /* Question: Why do we want a timer? We have it to make sure that we enable interrupts correctly. If we forget to do it, the timer "dies". */ SimpleTimer timer(100); /* timer ticks every 10ms. */ InterruptHandler::register_handler(0, &timer); /* The Timer is implemented as an interrupt handler. */ #ifdef _USES_SCHEDULER_ /* -- SCHEDULER -- IF YOU HAVE ONE -- */ Scheduler system_scheduler = Scheduler(); SYSTEM_SCHEDULER = &system_scheduler; #endif #ifdef _USES_DISK_ /* -- DISK DEVICE -- IF YOU HAVE ONE -- */ //SimpleDisk system_disk = SimpleDisk(MASTER, SYSTEM_DISK_SIZE); BlockingDisk system_disk = BlockingDisk(MASTER, SYSTEM_DISK_SIZE); SYSTEM_DISK = &system_disk; #endif #ifdef _USES_FILESYSTEM_ /* -- FILE SYSTEM -- IF YOU HAVE ONE -- */ FileSystem file_system = FileSystem(); FILE_SYSTEM = &file_system; #endif /* NOTE: The timer chip starts periodically firing as soon as we enable interrupts. It is important to install a timer handler, as we would get a lot of uncaptured interrupts otherwise. */ /* -- ENABLE INTERRUPTS -- */ machine_enable_interrupts(); /* -- MOST OF WHAT WE NEED IS SETUP. THE KERNEL CAN START. */ Console::puts("Hello World!\n"); /* -- LET'S CREATE SOME THREADS... */ Console::puts("CREATING THREAD 1...\n"); char * stack1 = new char[1024]; thread1 = new Thread(fun1, stack1, 1024); Console::puts("DONE\n"); Console::puts("CREATING THREAD 2..."); char * stack2 = new char[4096]; thread2 = new Thread(fun2, stack2, 4096); Console::puts("DONE\n"); Console::puts("CREATING THREAD 3..."); char * stack3 = new char[8192]; thread3 = new Thread(fun3, stack3, 8192); Console::puts("DONE\n"); Console::puts("CREATING THREAD 4..."); char * stack4 = new char[1024]; thread4 = new Thread(fun4, stack4, 1024); Console::puts("DONE\n"); #ifdef _USES_SCHEDULER_ /* WE ADD thread2 - thread4 TO THE READY QUEUE OF THE SCHEDULER. */ SYSTEM_SCHEDULER->add(thread2); SYSTEM_SCHEDULER->add(thread3); SYSTEM_SCHEDULER->add(thread4); #endif /* -- KICK-OFF THREAD1 ... */ Console::puts("STARTING THREAD 1 ...\n"); Thread::dispatch_to(thread1); /* -- AND ALL THE REST SHOULD FOLLOW ... */ assert(FALSE); /* WE SHOULD NEVER REACH THIS POINT. */ /* -- WE DO THE FOLLOWING TO KEEP THE COMPILER HAPPY. */ return 1; }
static void * reduce_test(void* p) { thread_data_t *td = (thread_data_t*)p; pami_context_t myContext = (pami_context_t)td->context; /* Barrier variables */ size_t barrier_num_algorithm[2]; pami_algorithm_t *bar_always_works_algo = NULL; pami_metadata_t *bar_always_works_md = NULL; pami_algorithm_t *bar_must_query_algo = NULL; pami_metadata_t *bar_must_query_md = NULL; pami_xfer_type_t barrier_xfer = PAMI_XFER_BARRIER; volatile unsigned bar_poll_flag = 0; /* Reduce variables */ size_t reduce_num_algorithm[2]; pami_algorithm_t *reduce_always_works_algo = NULL; pami_metadata_t *reduce_always_works_md = NULL; pami_algorithm_t *reduce_must_query_algo = NULL; pami_metadata_t *reduce_must_query_md = NULL; pami_xfer_type_t reduce_xfer = PAMI_XFER_REDUCE; volatile unsigned reduce_poll_flag = 0; int nalg= 0; double ti, tf, usec; pami_xfer_t barrier; pami_xfer_t reduce; int rc = 0; /* Allocate buffer(s) */ int err = 0; void* sbuf = NULL; err = posix_memalign(&sbuf, 128, gMax_byte_count + gBuffer_offset); assert(err == 0); sbuf = (char*)sbuf + gBuffer_offset; void* rbuf = NULL; err = posix_memalign(&rbuf, 128, gMax_byte_count + gBuffer_offset); assert(err == 0); rbuf = (char*)rbuf + gBuffer_offset; /* Query the world geometry for barrier algorithms */ rc |= query_geometry(client, myContext, newgeometry, barrier_xfer, barrier_num_algorithm, &bar_always_works_algo, &bar_always_works_md, &bar_must_query_algo, &bar_must_query_md); /* Query the world geometry for reduce algorithms */ rc |= query_geometry(client, myContext, newgeometry, reduce_xfer, reduce_num_algorithm, &reduce_always_works_algo, &reduce_always_works_md, &reduce_must_query_algo, &reduce_must_query_md); barrier.cb_done = cb_done; barrier.cookie = (void*) & bar_poll_flag; barrier.algorithm = bar_always_works_algo[0]; blocking_coll(myContext, &barrier, &bar_poll_flag); pami_endpoint_t my_ep, zero_ep; PAMI_Endpoint_create(client,task_id,td->tid,&my_ep); PAMI_Endpoint_create(client,0,0,&zero_ep); for (nalg = 0; nalg < reduce_num_algorithm[0]; nalg++) { if (my_ep == zero_ep) { printf("# Reduce Bandwidth Test(size:%zu) -- context = %d, root varies, protocol: %s\n",num_tasks, td->tid, reduce_always_works_md[nalg].name); printf("# Size(bytes) iterations bytes/sec usec\n"); printf("# ----------- ----------- ----------- ---------\n"); } if (((strstr(reduce_always_works_md[nalg].name, gSelected) == NULL) && gSelector) || ((strstr(reduce_always_works_md[nalg].name, gSelected) != NULL) && !gSelector)) continue; gProtocolName = reduce_always_works_md[nalg].name; reduce.cb_done = cb_done; reduce.cookie = (void*) & reduce_poll_flag; reduce.algorithm = reduce_always_works_algo[nalg]; reduce.cmd.xfer_reduce.sndbuf = sbuf; reduce.cmd.xfer_reduce.rcvbuf = rbuf; reduce.cmd.xfer_reduce.rtype = PAMI_TYPE_BYTE; reduce.cmd.xfer_reduce.rtypecount = 0; int op, dt; for (dt = 0; dt < dt_count; dt++) { for (op = 0; op < op_count; op++) { if (gValidTable[op][dt]) { if (my_ep == zero_ep) printf("Running Reduce: %s, %s\n", dt_array_str[dt], op_array_str[op]); int i; for (i = MAX(1,gMin_byte_count/get_type_size(dt_array[dt])); i <= gMax_byte_count/get_type_size(dt_array[dt]); i *= 2) { size_t sz=get_type_size(dt_array[dt]); size_t dataSent = i * sz; int niter; if (dataSent < CUTOFF) niter = gNiterlat; else niter = NITERBW; reduce.cmd.xfer_reduce.stypecount = i; reduce.cmd.xfer_reduce.rtypecount = dataSent; reduce.cmd.xfer_reduce.stype = dt_array[dt]; reduce.cmd.xfer_reduce.op = op_array[op]; reduce_initialize_sndbuf (sbuf, i, op, dt, td->logical_rank, num_ep); memset(rbuf, 0xFF, dataSent); blocking_coll(myContext, &barrier, &bar_poll_flag); ti = timer(); pami_task_t root_task = 0; int j, ctxt_id = 0; /* Performance run*/ for (j = 0; j < niter; j++) { pami_endpoint_t root_ep; PAMI_Endpoint_create(client, root_task, ctxt_id, &root_ep); reduce.cmd.xfer_reduce.root = root_ep; if (my_ep == root_ep) reduce.cmd.xfer_reduce.rcvbuf = rbuf; else reduce.cmd.xfer_reduce.rcvbuf = NULL; blocking_coll(myContext, &reduce, &reduce_poll_flag); ctxt_id = (ctxt_id + 1)%gNum_contexts; if(ctxt_id == 0) root_task = (root_task +1)%num_tasks; } tf = timer(); blocking_coll(myContext, &barrier, &bar_poll_flag); /* Correctness*/ reduce_initialize_sndbuf (sbuf, i, op, dt, td->logical_rank, num_ep); memset(rbuf, 0xFF, dataSent); ctxt_id=0; root_task=0; for(j =0; j<gNum_contexts*num_tasks; j++) { pami_endpoint_t root_ep; PAMI_Endpoint_create(client, root_task, ctxt_id, &root_ep); reduce.cmd.xfer_reduce.root = root_ep; if (my_ep == root_ep) reduce.cmd.xfer_reduce.rcvbuf = rbuf; else reduce.cmd.xfer_reduce.rcvbuf = NULL; blocking_coll(myContext, &reduce, &reduce_poll_flag); ctxt_id = (ctxt_id + 1)%gNum_contexts; if(ctxt_id == 0) root_task = (root_task +1)%num_tasks; } int rc_check; rc |= rc_check = reduce_check_rcvbuf (rbuf, i, op, dt, td->logical_rank, num_ep); if (rc_check) fprintf(stderr, "%s FAILED validation\n", gProtocolName); usec = (tf - ti) / (double)niter; if (my_ep == zero_ep) { printf(" %11lld %16d %14.1f %12.2f\n", (long long)dataSent, niter, (double)1e6*(double)dataSent / (double)usec, usec); fflush(stdout); } } } } } } free(bar_always_works_algo); free(bar_always_works_md); free(bar_must_query_algo); free(bar_must_query_md); free(reduce_always_works_algo); free(reduce_always_works_md); free(reduce_must_query_algo); free(reduce_must_query_md); sbuf = (char*)sbuf - gBuffer_offset; free(sbuf); rbuf = (char*)rbuf - gBuffer_offset; free(rbuf); rc = PAMI_Fence_all (myContext, fence_cb_done, &fence_arrivals); while (fence_arrivals != 0) rc = PAMI_Context_advance (myContext, 1); pthread_exit(NULL); }
bool Executer::startExecution(bool onlySelection) { Q_ASSERT(mScriptAgent); Q_ASSERT(mScriptEngine); #ifdef ACT_PROFILE Tools::HighResolutionTimer timer("Executer::startExecution"); #endif Code::CodeTools::addClassToScriptEngine<CodeActiona>("Actiona", mScriptEngine); CodeActiona::setActExec(mIsActExec); CodeActiona::setActionaVersion(mActionaVersion); CodeActiona::setScriptVersion(mScriptVersion); Code::CodeTools::addClassGlobalFunctionToScriptEngine("Actiona", &CodeActiona::version, "version", mScriptEngine); Code::CodeTools::addClassGlobalFunctionToScriptEngine("Actiona", &CodeActiona::scriptVersion, "scriptVersion", mScriptEngine); Code::CodeTools::addClassGlobalFunctionToScriptEngine("Actiona", &CodeActiona::isActExec, "isActExec", mScriptEngine); Code::CodeTools::addClassGlobalFunctionToScriptEngine("Actiona", &CodeActiona::isActiona, "isActiona", mScriptEngine); mScriptAgent->setContext(ScriptAgent::ActionInit); CodeInitializer::initialize(mScriptEngine, mScriptAgent, mActionFactory); mScriptAgent->setContext(ScriptAgent::Parameters); QScriptValue script = mScriptEngine->newObject(); mScriptEngine->globalObject().setProperty("Script", script, QScriptValue::ReadOnly); script.setProperty("nextLine", 1); script.setProperty("line", 1, QScriptValue::ReadOnly); QScriptValue callProcedureFun = mScriptEngine->newFunction(callProcedureFunction); callProcedureFun.setData(mScriptEngine->newQObject(this)); script.setProperty("callProcedure", callProcedureFun); QScriptValue console = mScriptEngine->newObject(); mScriptEngine->globalObject().setProperty("Console", console, QScriptValue::ReadOnly); QScriptValue function = mScriptEngine->newFunction(printFunction); function.setData(mScriptEngine->newQObject(this)); console.setProperty("print", function); function = mScriptEngine->newFunction(printWarningFunction); function.setData(mScriptEngine->newQObject(this)); console.setProperty("printWarning", function); function = mScriptEngine->newFunction(printErrorFunction); function.setData(mScriptEngine->newQObject(this)); console.setProperty("printError", function); function = mScriptEngine->newFunction(clearConsoleFunction); function.setData(mScriptEngine->newQObject(this)); console.setProperty("clear", function); mExecuteOnlySelection = onlySelection; mCurrentActionIndex = 0; mActiveActionsCount = 0; mExecutionPaused = false; bool initSucceeded = true; int lastBeginProcedure = -1; mScript->clearProcedures(); mScript->clearCallStack(); const QHash<QString, ActionTools::Resource> &resources = mScript->resources(); for(const QString &key: resources.keys()) { const ActionTools::Resource &resource = resources.value(key); QScriptValue value; switch(resource.type()) { case ActionTools::Resource::BinaryType: case ActionTools::Resource::TypeCount: value = Code::RawData::constructor(resource.data(), mScriptEngine); break; case ActionTools::Resource::TextType: value = QString::fromUtf8(resource.data(), resource.data().size()); break; case ActionTools::Resource::ImageType: { QImage image; if(!image.loadFromData(resource.data())) { mConsoleWidget->addResourceLine(tr("Invalid image resource"), key, ActionTools::ConsoleWidget::Error); return false; } value = Code::Image::constructor(image, mScriptEngine); } break; } mScriptEngine->globalObject().setProperty(key, value, QScriptValue::ReadOnly | QScriptValue::Undeletable); } for(int actionIndex = 0; actionIndex < mScript->actionCount(); ++actionIndex) { ActionTools::ActionInstance *actionInstance = mScript->actionAt(actionIndex); actionInstance->reset(); actionInstance->clearRuntimeParameters(); actionInstance->setupExecution(mScriptEngine, mScript, actionIndex); mActionEnabled.append(true); qint64 currentActionRuntimeId = -1; if(actionInstance) currentActionRuntimeId = actionInstance->runtimeId(); if(canExecuteAction(actionIndex) == CanExecute) { ++mActiveActionsCount; if(actionInstance->definition()->id() == "ActionBeginProcedure") { if(lastBeginProcedure != -1) { mConsoleWidget->addActionLine(tr("Invalid Begin procedure action, you have to end the previous procedure before starting another one"), currentActionRuntimeId, QString(), QString(), -1, -1, ActionTools::ConsoleWidget::Error); return false; } lastBeginProcedure = actionIndex; const ActionTools::SubParameter &nameParameter = actionInstance->subParameter("name", "value"); const QString &procedureName = nameParameter.value().toString(); if(procedureName.isEmpty()) { mConsoleWidget->addActionLine(tr("A procedure name cannot be empty"), currentActionRuntimeId, QString(), QString(), -1, -1, ActionTools::ConsoleWidget::Error); return false; } if(mScript->findProcedure(procedureName) != -1) { mConsoleWidget->addActionLine(tr("A procedure with the name \"%1\" has already been declared").arg(procedureName), currentActionRuntimeId, QString(), QString(), -1, -1, ActionTools::ConsoleWidget::Error); return false; } mScript->addProcedure(procedureName, actionIndex); } else if(actionInstance->definition()->id() == "ActionEndProcedure") { if(lastBeginProcedure == -1) { mConsoleWidget->addActionLine(tr("Invalid End procedure"), currentActionRuntimeId, QString(), QString(), -1, -1, ActionTools::ConsoleWidget::Error); return false; } ActionTools::ActionInstance *beginProcedureActionInstance = mScript->actionAt(lastBeginProcedure); actionInstance->setRuntimeParameter("procedureBeginLine", lastBeginProcedure); beginProcedureActionInstance->setRuntimeParameter("procedureEndLine", actionIndex); lastBeginProcedure = -1; } } } if(lastBeginProcedure != -1) { ActionTools::ActionInstance *actionInstance = mScript->actionAt(lastBeginProcedure); qint64 actionRuntimeId = -1; if(actionInstance) actionRuntimeId = actionInstance->runtimeId(); mConsoleWidget->addActionLine(tr("Begin procedure action without end procedure"), actionRuntimeId, QString(), QString(), -1, -1, ActionTools::ConsoleWidget::Error); return false; } for(int parameterIndex = 0; parameterIndex < mScript->parameterCount(); ++parameterIndex) { mScriptAgent->setCurrentParameter(parameterIndex); const ActionTools::ScriptParameter &scriptParameter = mScript->parameter(parameterIndex); QRegExp nameRegExp("[a-z_][a-z0-9_]*", Qt::CaseInsensitive); if(!nameRegExp.exactMatch(scriptParameter.name())) { mConsoleWidget->addScriptParameterLine(tr("Incorrect parameter name: \"%1\"").arg(scriptParameter.name()), parameterIndex, -1, -1, ActionTools::ConsoleWidget::Error); initSucceeded = false; continue; } QString value; if(scriptParameter.isCode()) { QScriptValue result = mScriptEngine->evaluate(scriptParameter.value()); if(result.isError()) { mConsoleWidget->addScriptParameterLine(tr("Error while evaluating parameter \"%1\", error message: \"%2\"") .arg(scriptParameter.name()) .arg(result.toString()), parameterIndex, -1, -1, ActionTools::ConsoleWidget::Error); initSucceeded = false; continue; } else value = result.toString(); } else value = scriptParameter.value(); mScriptEngine->globalObject().setProperty(scriptParameter.name(), value, QScriptValue::ReadOnly | QScriptValue::Undeletable); } if(!initSucceeded || mScript->actionCount() == 0) return false; if(mShowExecutionWindow) { QRect screenRect = QApplication::desktop()->availableGeometry(mExecutionWindowScreen); QPoint position; if(mExecutionWindowPosition >= 0 && mExecutionWindowPosition <= 2)//Left position.setX(screenRect.left()); else if(mExecutionWindowPosition >= 3 && mExecutionWindowPosition <= 5)//HCenter position.setX(screenRect.left() + screenRect.width() / 2 - mExecutionWindow->width() / 2); else if(mExecutionWindowPosition >= 6 && mExecutionWindowPosition <= 8)//Right position.setX(screenRect.left() + screenRect.width() - mExecutionWindow->width()); if(mExecutionWindowPosition == 0 || mExecutionWindowPosition == 3 || mExecutionWindowPosition == 6)//Up position.setY(screenRect.top()); else if(mExecutionWindowPosition == 1 || mExecutionWindowPosition == 4 || mExecutionWindowPosition == 7)//VCenter position.setY(screenRect.top() + screenRect.height() / 2 - mExecutionWindow->height() / 2); else if(mExecutionWindowPosition == 2 || mExecutionWindowPosition == 5 || mExecutionWindowPosition == 8)//Down position.setY(screenRect.top() + screenRect.height() - mExecutionWindow->height()); mExecutionWindow->setPauseStatus(false); mExecutionWindow->move(position); mExecutionWindow->show(); } if(mShowConsoleWindow) { QRect screenRect = QApplication::desktop()->availableGeometry(mConsoleWindowScreen); QPoint position; if(mConsoleWindowPosition >= 0 && mConsoleWindowPosition <= 2)//Left position.setX(screenRect.left()); else if(mConsoleWindowPosition >= 3 && mConsoleWindowPosition <= 5)//HCenter position.setX(screenRect.left() + screenRect.width() / 2 - mConsoleWidget->width() / 2); else if(mConsoleWindowPosition >= 6 && mConsoleWindowPosition <= 8)//Right position.setX(screenRect.left() + screenRect.width() - mConsoleWidget->width()); if(mConsoleWindowPosition == 0 || mConsoleWindowPosition == 3 || mConsoleWindowPosition == 6)//Up position.setY(screenRect.top()); else if(mConsoleWindowPosition == 1 || mConsoleWindowPosition == 4 || mConsoleWindowPosition == 7)//VCenter position.setY(screenRect.top() + screenRect.height() / 2 - mConsoleWidget->height() / 2); else if(mConsoleWindowPosition == 2 || mConsoleWindowPosition == 5 || mConsoleWindowPosition == 8)//Down position.setY(screenRect.top() + screenRect.height() - mConsoleWidget->height()); mConsoleWidget->move(position); mConsoleWidget->show(); } mExecutionStarted = true; mScriptAgent->setContext(ScriptAgent::Actions); mHasExecuted = true; executeCurrentAction(); return true; }
void EngineMaster::processChannels(int iBufferSize) { m_activeBusChannels[EngineChannel::LEFT].clear(); m_activeBusChannels[EngineChannel::CENTER].clear(); m_activeBusChannels[EngineChannel::RIGHT].clear(); m_activeHeadphoneChannels.clear(); m_activeTalkoverChannels.clear(); m_activeChannels.clear(); ScopedTimer timer("EngineMaster::processChannels"); EngineChannel* pMasterChannel = m_pMasterSync->getMaster(); // Reserve the first place for the master channel which // should be processed first m_activeChannels.append(NULL); int activeChannelsStartIndex = 1; // Nothing at 0 yet for (int i = 0; i < m_channels.size(); ++i) { ChannelInfo* pChannelInfo = m_channels[i]; EngineChannel* pChannel = pChannelInfo->m_pChannel; // Skip inactive channels. if (!pChannel || !pChannel->isActive()) { continue; } if (pChannel->isTalkoverEnabled()) { // talkover is an exclusive channel // once talkover is enabled it is not used in // xFader-Mix m_activeTalkoverChannels.append(pChannelInfo); // Check if we need to fade out the master channel GainCache& gainCache = m_channelMasterGainCache[i]; if (gainCache.m_gain) { gainCache.m_fadeout = true; m_activeBusChannels[pChannel->getOrientation()].append(pChannelInfo); } } else { // Check if we need to fade out the channel GainCache& gainCache = m_channelTalkoverGainCache[i]; if (gainCache.m_gain) { gainCache.m_fadeout = true; m_activeTalkoverChannels.append(pChannelInfo); } if (pChannel->isMasterEnabled() && !pChannelInfo->m_pMuteControl->toBool()) { // the xFader-Mix m_activeBusChannels[pChannel->getOrientation()].append(pChannelInfo); } else { // Check if we need to fade out the channel GainCache& gainCache = m_channelMasterGainCache[i]; if (gainCache.m_gain) { gainCache.m_fadeout = true; m_activeBusChannels[pChannel->getOrientation()].append(pChannelInfo); } } } // If the channel is enabled for previewing in headphones, copy it // over to the headphone buffer if (pChannel->isPflEnabled()) { m_activeHeadphoneChannels.append(pChannelInfo); } else { // Check if we need to fade out the channel GainCache& gainCache = m_channelHeadphoneGainCache[i]; if (gainCache.m_gain) { m_channelHeadphoneGainCache[i].m_fadeout = true; m_activeHeadphoneChannels.append(pChannelInfo); } } // If necessary, add the channel to the list of buffers to process. if (pChannel == pMasterChannel) { // If this is the sync master, it should be processed first. m_activeChannels.replace(0, pChannelInfo); activeChannelsStartIndex = 0; } else { m_activeChannels.append(pChannelInfo); } } // Now that the list is built and ordered, do the processing. for (int i = activeChannelsStartIndex; i < m_activeChannels.size(); ++i) { ChannelInfo* pChannelInfo = m_activeChannels[i]; EngineChannel* pChannel = pChannelInfo->m_pChannel; pChannel->process(pChannelInfo->m_pBuffer, iBufferSize); // Collect metadata for effects if (m_pEngineEffectsManager) { GroupFeatureState features; pChannel->collectFeatures(&features); pChannelInfo->m_features = features; } } // After all the engines have been processed, trigger post-processing // which ensures that all channels are updating certain values at the // same point in time. This prevents sync from failing depending on // if the sync target was processed before or after the sync origin. for (int i = activeChannelsStartIndex; i < m_activeChannels.size(); ++i) { m_activeChannels[i]->m_pChannel->postProcess(iBufferSize); } }
int main(int argc, char **argv) { string inp = "secrets! very secrets!"; cout << "inp = \"" << inp << "\"" << endl; vector<pt_key32> k = pt_genKey(); pt_expandKey(k); printKey(k); // initialize helib long m=0, p=2, r=1; long L=23; long c=3; long w=64; long d=0; long security = 128; cout << "L=" << L << endl; ZZX G; cout << "Finding m..." << endl; m = FindM(security,L,c,p,d,0,0); cout << "Generating context..." << endl; FHEcontext context(m, p, r); cout << "Building mod-chain..." << endl; buildModChain(context, L, c); cout << "Generating keys..." << endl; FHESecKey seckey(context); const FHEPubKey& pubkey = seckey; G = context.alMod.getFactorsOverZZ()[0]; seckey.GenSecKey(w); addSome1DMatrices(seckey); EncryptedArray ea(context, G); global_nslots = ea.size(); cout << "nslots = " << global_nslots << endl; // set up globals CTvec maxint (ea, pubkey, transpose(uint32ToBits(0xFFFFFFFF))); global_maxint = &maxint; // HEencrypt key timer(true); cout << "Encrypting SIMON key..." << flush; vector<CTvec> encryptedKey = heEncrypt(ea, pubkey, k); timer(); // HEencrypt input cout << "Encrypting inp..." << flush; heblock ct = heEncrypt(ea, pubkey, inp); timer(); cout << "Running protocol..." << endl; for (size_t i = 0; i < T; i++) { cout << "Round " << i+1 << "/" << T << "..." << flush; encRound(encryptedKey[i], ct); timer(); // check intermediate result for noise cout << "decrypting..." << flush; vector<pt_block> bs = heblockToBlocks(seckey, ct); timer(); printf("block0 : 0x%08x 0x%08x\n", bs[0].x, bs[0].y); vector<pt_block> pt_bs = pt_simonEnc(k, inp, i+1); printf("should be : 0x%08x 0x%08x\n", pt_bs[0].x, pt_bs[0].y); cout << "decrypted : \"" << pt_simonDec(k, bs, i+1) << "\" " << endl; } return 0; }
bool StandaloneSetup() { timer(0, g_cur_fractal_specific->calctype); return false; // effectively disable solid-guessing }
int powerMethodTests(Epetra_RowMatrix & A, Epetra_RowMatrix & JadA, Epetra_Map & Map, Epetra_Vector & q, Epetra_Vector & z, Epetra_Vector & resid, bool verbose) { // variable needed for iteration double lambda = 0.0; // int niters = 10000; int niters = 300; double tolerance = 1.0e-2; int ierr = 0; ///////////////////////////////////////////////////////////////////////////////////////////////// // Iterate Epetra_Time timer(Map.Comm()); double startTime = timer.ElapsedTime(); EPETRA_TEST_ERR(power_method(false, A, q, z, resid, &lambda, niters, tolerance, verbose),ierr); double elapsed_time = timer.ElapsedTime() - startTime; double total_flops = q.Flops(); double MFLOPs = total_flops/elapsed_time/1000000.0; double lambdaref = lambda; double flopsref = total_flops; if (verbose) cout << "\n\nTotal MFLOPs for reference first solve = " << MFLOPs << endl << "Total FLOPS = " <<total_flops <<endl<<endl; lambda = 0.0; startTime = timer.ElapsedTime(); EPETRA_TEST_ERR(power_method(false, JadA, q, z, resid, &lambda, niters, tolerance, verbose),ierr); elapsed_time = timer.ElapsedTime() - startTime; total_flops = q.Flops(); MFLOPs = total_flops/elapsed_time/1000000.0; if (verbose) cout << "\n\nTotal MFLOPs for candidate first solve = " << MFLOPs << endl << "Total FLOPS = " <<total_flops <<endl<<endl; EPETRA_TEST_ERR(checkValues(lambda,lambdaref," No-transpose Power Method result", verbose),ierr); //EPETRA_TEST_ERR(checkValues(total_flops,flopsref," No-transpose Power Method flop count", verbose),ierr); ///////////////////////////////////////////////////////////////////////////////////////////////// // Solve transpose problem if (verbose) cout << "\n\nUsing transpose of matrix and solving again (should give same result).\n\n" << endl; // Iterate lambda = 0.0; startTime = timer.ElapsedTime(); EPETRA_TEST_ERR(power_method(true, A, q, z, resid, &lambda, niters, tolerance, verbose),ierr); elapsed_time = timer.ElapsedTime() - startTime; total_flops = q.Flops(); MFLOPs = total_flops/elapsed_time/1000000.0; lambdaref = lambda; flopsref = total_flops; if (verbose) cout << "\n\nTotal MFLOPs for reference transpose solve = " << MFLOPs << endl << "Total FLOPS = " <<total_flops <<endl<<endl; lambda = 0.0; startTime = timer.ElapsedTime(); EPETRA_TEST_ERR(power_method(true, JadA, q, z, resid, &lambda, niters, tolerance, verbose),ierr); elapsed_time = timer.ElapsedTime() - startTime; total_flops = q.Flops(); MFLOPs = total_flops/elapsed_time/1000000.0; if (verbose) cout << "\n\nTotal MFLOPs for candidate transpose solve = " << MFLOPs << endl << "Total FLOPS = " <<total_flops <<endl<<endl; EPETRA_TEST_ERR(checkValues(lambda,lambdaref,"Transpose Power Method result", verbose),ierr); //EPETRA_TEST_ERR(checkValues(total_flops,flopsref,"Transpose Power Method flop count", verbose),ierr); EPETRA_TEST_ERR(check(A, JadA, verbose),ierr); return(0); }
void ClientLauncher::speed_tests() { // volatile to avoid some potential compiler optimisations volatile static s16 temp16; volatile static f32 tempf; static v3f tempv3f1; static v3f tempv3f2; static std::string tempstring; static std::string tempstring2; tempv3f1 = v3f(); tempv3f2 = v3f(); tempstring = std::string(); tempstring2 = std::string(); { infostream << "The following test should take around 20ms." << std::endl; TimeTaker timer("Testing std::string speed"); const u32 jj = 10000; for (u32 j = 0; j < jj; j++) { tempstring = ""; tempstring2 = ""; const u32 ii = 10; for (u32 i = 0; i < ii; i++) { tempstring2 += "asd"; } for (u32 i = 0; i < ii+1; i++) { tempstring += "asd"; if (tempstring == tempstring2) break; } } } infostream << "All of the following tests should take around 100ms each." << std::endl; { TimeTaker timer("Testing floating-point conversion speed"); tempf = 0.001; for (u32 i = 0; i < 4000000; i++) { temp16 += tempf; tempf += 0.001; } } { TimeTaker timer("Testing floating-point vector speed"); tempv3f1 = v3f(1, 2, 3); tempv3f2 = v3f(4, 5, 6); for (u32 i = 0; i < 10000000; i++) { tempf += tempv3f1.dotProduct(tempv3f2); tempv3f2 += v3f(7, 8, 9); } } { TimeTaker timer("Testing std::map speed"); std::map<v2s16, f32> map1; tempf = -324; const s16 ii = 300; for (s16 y = 0; y < ii; y++) { for (s16 x = 0; x < ii; x++) { map1[v2s16(x, y)] = tempf; tempf += 1; } } for (s16 y = ii - 1; y >= 0; y--) { for (s16 x = 0; x < ii; x++) { tempf = map1[v2s16(x, y)]; } } } { infostream << "Around 5000/ms should do well here." << std::endl; TimeTaker timer("Testing mutex speed"); Mutex m; u32 n = 0; u32 i = 0; do { n += 10000; for (; i < n; i++) { m.lock(); m.unlock(); } } // Do at least 10ms while(timer.getTimerTime() < 10); u32 dtime = timer.stop(); u32 per_ms = n / dtime; infostream << "Done. " << dtime << "ms, " << per_ms << "/ms" << std::endl; } }
void SaveGame(const std::string& filename, const ServerSaveGameData& server_save_game_data, const std::vector<PlayerSaveGameData>& player_save_game_data, const Universe& universe, const EmpireManager& empire_manager, const SpeciesManager& species_manager, const CombatLogManager& combat_log_manager, const GalaxySetupData& galaxy_setup_data, bool multiplayer) { ScopedTimer timer("SaveGame: " + filename, true); bool use_binary = GetOptionsDB().Get<bool>("binary-serialization"); DebugLogger() << "SaveGame(" << (use_binary ? "binary" : "zlib-xml") << ") filename: " << filename; GetUniverse().EncodingEmpire() = ALL_EMPIRES; DebugLogger() << "Compiling save empire and preview data"; std::map<int, SaveGameEmpireData> empire_save_game_data = CompileSaveGameEmpireData(empire_manager); SaveGamePreviewData save_preview_data; CompileSaveGamePreviewData(server_save_game_data, player_save_game_data, empire_save_game_data, save_preview_data); // reinterpret save game data as header data for uncompressed header std::vector<PlayerSaveHeaderData> player_save_header_data; for (std::vector<PlayerSaveGameData>::const_iterator it = player_save_game_data.begin(); it != player_save_game_data.end(); ++it) { player_save_header_data.push_back(*it); } try { fs::path path = FilenameToPath(filename); // A relative path should be relative to the save directory. if (path.is_relative()) { path = GetSaveDir() / path; DebugLogger() << "Made save path relative to save dir. Is now: " << path; } if (multiplayer) { // Make sure the path points into our save directory if (!IsInside(path, GetSaveDir())) { path = GetSaveDir() / path.filename(); } } // set up output archive / stream for saving fs::ofstream ofs(path, std::ios_base::binary); if (!ofs) throw std::runtime_error(UNABLE_TO_OPEN_FILE); if (use_binary) { DebugLogger() << "Creating binary oarchive"; freeorion_bin_oarchive boa(ofs); boa << BOOST_SERIALIZATION_NVP(save_preview_data); boa << BOOST_SERIALIZATION_NVP(galaxy_setup_data); boa << BOOST_SERIALIZATION_NVP(server_save_game_data); boa << BOOST_SERIALIZATION_NVP(player_save_header_data); boa << BOOST_SERIALIZATION_NVP(empire_save_game_data); boa << BOOST_SERIALIZATION_NVP(player_save_game_data); boa << BOOST_SERIALIZATION_NVP(empire_manager); boa << BOOST_SERIALIZATION_NVP(species_manager); boa << BOOST_SERIALIZATION_NVP(combat_log_manager); Serialize(boa, universe); DebugLogger() << "Done serializing"; } else { // Two-tier serialization: // main archive is uncompressed serialized header data first // then contains a string for compressed second archive // that contains the main gamestate info // allocate buffers for serialized gamestate DebugLogger() << "Allocating buffers for XML serialization..."; std::string serial_str, compressed_str; try { serial_str.reserve( std::pow(2.0, 29.0)); compressed_str.reserve(std::pow(2.0, 26.0)); } catch (...) { DebugLogger() << "Unable to preallocate full serialization buffers. Attempting serialization with dynamic buffer allocation."; } // wrap buffer string in iostream::stream to receive serialized data typedef boost::iostreams::back_insert_device<std::string> InsertDevice; InsertDevice serial_inserter(serial_str); boost::iostreams::stream<InsertDevice> s_sink(serial_inserter); // create archive with (preallocated) buffer... freeorion_xml_oarchive xoa(s_sink); // serialize main gamestate info xoa << BOOST_SERIALIZATION_NVP(player_save_game_data); xoa << BOOST_SERIALIZATION_NVP(empire_manager); xoa << BOOST_SERIALIZATION_NVP(species_manager); xoa << BOOST_SERIALIZATION_NVP(combat_log_manager); Serialize(xoa, universe); s_sink.flush(); // wrap gamestate string in iostream::stream to extract serialized data typedef boost::iostreams::basic_array_source<char> SourceDevice; SourceDevice source(serial_str.data(), serial_str.size()); boost::iostreams::stream<SourceDevice> s_source(source); // wrap compresed buffer string in iostream::streams to receive compressed string InsertDevice compressed_inserter(compressed_str); boost::iostreams::stream<InsertDevice> c_sink(compressed_inserter); // compression-filter gamestate into compressed string boost::iostreams::filtering_ostreambuf o; o.push(boost::iostreams::zlib_compressor()); o.push(c_sink); boost::iostreams::copy(s_source, o); c_sink.flush(); // write to save file: uncompressed header serialized data, with compressed main archive string at end... freeorion_xml_oarchive xoa2(ofs); // serialize uncompressed save header info xoa2 << BOOST_SERIALIZATION_NVP(save_preview_data); xoa2 << BOOST_SERIALIZATION_NVP(galaxy_setup_data); xoa2 << BOOST_SERIALIZATION_NVP(server_save_game_data); xoa2 << BOOST_SERIALIZATION_NVP(player_save_header_data); xoa2 << BOOST_SERIALIZATION_NVP(empire_save_game_data); // append compressed gamestate info xoa2 << BOOST_SERIALIZATION_NVP(compressed_str); } } catch (const std::exception& e) { ErrorLogger() << UserString("UNABLE_TO_WRITE_SAVE_FILE") << " SaveGame exception: " << ": " << e.what(); throw e; } DebugLogger() << "SaveGame : Successfully wrote save file"; }
void LoadGame(const std::string& filename, ServerSaveGameData& server_save_game_data, std::vector<PlayerSaveGameData>& player_save_game_data, Universe& universe, EmpireManager& empire_manager, SpeciesManager& species_manager, CombatLogManager& combat_log_manager, GalaxySetupData& galaxy_setup_data) { //boost::this_thread::sleep_for(boost::chrono::seconds(1)); ScopedTimer timer("LoadGame: " + filename, true); // player notifications if (ServerApp* server = ServerApp::GetApp()) server->Networking().SendMessage(TurnProgressMessage(Message::LOADING_GAME)); GetUniverse().EncodingEmpire() = ALL_EMPIRES; std::map<int, SaveGameEmpireData> ignored_save_game_empire_data; SaveGamePreviewData ignored_save_preview_data; std::vector<PlayerSaveHeaderData> ignored_player_save_header_data; empire_manager.Clear(); universe.Clear(); try { // set up input archive / stream for loading const fs::path path = FilenameToPath(filename); fs::ifstream ifs(path, std::ios_base::binary); if (!ifs) throw std::runtime_error(UNABLE_TO_OPEN_FILE); try { // first attempt binary deserialziation freeorion_bin_iarchive ia(ifs); DebugLogger() << "Reading binary iarchive"; ia >> BOOST_SERIALIZATION_NVP(ignored_save_preview_data); ia >> BOOST_SERIALIZATION_NVP(galaxy_setup_data); ia >> BOOST_SERIALIZATION_NVP(server_save_game_data); ia >> BOOST_SERIALIZATION_NVP(ignored_player_save_header_data); ia >> BOOST_SERIALIZATION_NVP(ignored_save_game_empire_data); ia >> BOOST_SERIALIZATION_NVP(player_save_game_data); ia >> BOOST_SERIALIZATION_NVP(empire_manager); ia >> BOOST_SERIALIZATION_NVP(species_manager); ia >> BOOST_SERIALIZATION_NVP(combat_log_manager); Deserialize(ia, universe); DebugLogger() << "Done deserializing"; } catch (...) { // if binary deserialization failed, try more-portable XML deserialization // reset to start of stream (attempted binary serialization will have consumed some input...) boost::iostreams::seek(ifs, 0, std::ios_base::beg); // allocate buffers for serialized gamestate DebugLogger() << "Allocating buffers for XML deserialization..."; std::string serial_str, compressed_str; try { serial_str.reserve( std::pow(2.0, 29.0)); compressed_str.reserve(std::pow(2.0, 26.0)); } catch (...) { DebugLogger() << "Unable to preallocate full deserialization buffers. Attempting deserialization with dynamic buffer allocation."; } // create archive with (preallocated) buffer... freeorion_xml_iarchive xia(ifs); // read from save file: uncompressed header serialized data, with compressed main archive string at end... // deserialize uncompressed save header info xia >> BOOST_SERIALIZATION_NVP(ignored_save_preview_data); xia >> BOOST_SERIALIZATION_NVP(galaxy_setup_data); xia >> BOOST_SERIALIZATION_NVP(server_save_game_data); xia >> BOOST_SERIALIZATION_NVP(ignored_player_save_header_data); xia >> BOOST_SERIALIZATION_NVP(ignored_save_game_empire_data); // extract compressed gamestate info xia >> BOOST_SERIALIZATION_NVP(compressed_str); // wrap compressed string in iostream::stream to extract compressed data typedef boost::iostreams::basic_array_source<char> SourceDevice; SourceDevice compressed_source(compressed_str.data(), compressed_str.size()); boost::iostreams::stream<SourceDevice> c_source(compressed_source); // wrap uncompressed buffer string in iostream::stream to receive decompressed string typedef boost::iostreams::back_insert_device<std::string> InsertDevice; InsertDevice serial_inserter(serial_str); boost::iostreams::stream<InsertDevice> s_sink(serial_inserter); // set up filter to decompress data boost::iostreams::filtering_istreambuf i; i.push(boost::iostreams::zlib_decompressor()); i.push(c_source); boost::iostreams::copy(i, s_sink); // The following line has been commented out because it caused an assertion in boost iostreams to fail // s_sink.flush(); // wrap uncompressed buffer string in iostream::stream to extract decompressed string SourceDevice serial_source(serial_str.data(), serial_str.size()); boost::iostreams::stream<SourceDevice> s_source(serial_source); // create archive with (preallocated) buffer... freeorion_xml_iarchive xia2(s_source); // deserialize main gamestate info xia2 >> BOOST_SERIALIZATION_NVP(player_save_game_data); xia2 >> BOOST_SERIALIZATION_NVP(empire_manager); xia2 >> BOOST_SERIALIZATION_NVP(species_manager); xia2 >> BOOST_SERIALIZATION_NVP(combat_log_manager); Deserialize(xia2, universe); } } catch (const std::exception& err) { ErrorLogger() << "LoadGame(...) failed! Error: " << err.what(); return; } DebugLogger() << "LoadGame : Successfully loaded save file"; }
// ###################################################################### int main(const int argc, const char **argv) { MYLOGVERB = LOG_INFO; // suppress debug messages // instantiate a model manager: ModelManager manager("Test Optic Flow"); nub::ref<InputFrameSeries> ifs(new InputFrameSeries(manager)); manager.addSubComponent(ifs); nub::ref<OutputFrameSeries> ofs(new OutputFrameSeries(manager)); manager.addSubComponent(ofs); //nub::ref<PopulationHeadingMap> phm(new PopulationHeadingMap(manager)); rutz::shared_ptr<PopulationHeadingMap> phm(new PopulationHeadingMap(400.0)); manager.exportOptions(MC_RECURSE); if (manager.parseCommandLine((const int)argc, (const char**)argv, "", 0, 0) == false) return(1); // get some options // if(manager.numExtraArgs() > 0) // { // outFilename = manager.getExtraArg(0); // LINFO("save to: %s", outFilename.c_str()); // } // let's do it! manager.start(); Timer timer(1000000); timer.reset(); // reset the timer int frame = 0; bool keepGoing = true; const FrameState is = ifs->updateNext(); ifs->updateNext(); Image<PixRGB<byte> > img1 = ifs->readRGB(); ifs->updateNext(); Image<PixRGB<byte> > img2 = ifs->readRGB(); Image<PixRGB<byte> > image; Image<float> stim; if (is == FRAME_COMPLETE) keepGoing = false; float flen = 400; while (keepGoing) { if (ofs->becameVoid()) { LINFO("quitting because output stream was closed or became void"); break; } // get the frame const FrameState is = ifs->updateNext(); if (is == FRAME_COMPLETE) break; // done receiving frames image = ifs->readRGB(); // compute the Focus of Expansion phm->setFocalLength(flen); //flen += 5.0; phm->getFOE(Image<byte>(luminance(img1)),Image<byte>(luminance(img2))); //phm->getFOE(Image<byte>(luminance(image))); ofs->writeRGB(image, "Optic Flow"); const FrameState os = ofs->updateNext(); Raster::waitForKey(); //Raster::WriteRGB(currImage, sformat("image%d.ppm",frame)); if (os == FRAME_FINAL) break; frame++; } // stop all our ModelComponents manager.stop(); // all done! return 0; }
void gl_draw( void ) { int i, j; GLfloat len, lmax, r[8], g[8], b[8], a; glClear( GL_COLOR_BUFFER_BIT ); for( i = 0; i < 8; i++ ) { for( j = 0; j < 3; j++ ) { if( fps ) { if( ! ( rand() % (int) ( fps * 16.0f ) ) ) { dir[i][j] = (GLfloat) ( rand() % 3 ) - 1; } phi[i][j] += dir[i][j] / fps; } } } for( i = 0; i < 8; i++ ) { r[i] = ( (GLfloat) sin( phi[i][0] ) + 1.0f ) / 2.0f; g[i] = ( (GLfloat) sin( phi[i][1] ) + 1.0f ) / 2.0f; b[i] = ( (GLfloat) sin( phi[i][2] ) + 1.0f ) / 2.0f; } if( fps ) { rx += vx / fps; ry += vy / fps; } glMatrixMode( GL_MODELVIEW ); glLoadIdentity(); glTranslatef( 0.0f, 0.0f, -8.0f ); glRotatef( rx, 1.0f, 0.0f, 0.0f ); glRotatef( ry, 0.0f, 1.0f, 0.0f ); a = alpha; lmax = 1.4f + 0.12f * bmode; glBegin( GL_QUADS ); for( len = lmax; len > 0.0f; len -= 0.12f ) { glColor4f( r[0], g[0], b[0], a ); glVertex3f( -len, -len, -len ); glColor4f( r[1], g[1], b[1], a ); glVertex3f( -len, -len, len ); glColor4f( r[2], g[2], b[2], a ); glVertex3f( -len, len, len ); glColor4f( r[3], g[3], b[3], a ); glVertex3f( -len, len, -len ); glColor4f( r[4], g[4], b[4], a ); glVertex3f( len, -len, -len ); glColor4f( r[5], g[5], b[5], a ); glVertex3f( len, -len, len ); glColor4f( r[6], g[6], b[6], a ); glVertex3f( len, len, len ); glColor4f( r[7], g[7], b[7], a ); glVertex3f( len, len, -len ); glColor4f( r[0], g[0], b[0], a ); glVertex3f( -len, -len, -len ); glColor4f( r[1], g[1], b[1], a ); glVertex3f( -len, -len, len ); glColor4f( r[5], g[5], b[5], a ); glVertex3f( len, -len, len ); glColor4f( r[4], g[4], b[4], a ); glVertex3f( len, -len, -len ); glColor4f( r[3], g[3], b[3], a ); glVertex3f( -len, len, -len ); glColor4f( r[2], g[2], b[2], a ); glVertex3f( -len, len, len ); glColor4f( r[6], g[6], b[6], a ); glVertex3f( len, len, len ); glColor4f( r[7], g[7], b[7], a ); glVertex3f( len, len, -len ); glColor4f( r[0], g[0], b[0], a ); glVertex3f( -len, -len, -len ); glColor4f( r[3], g[3], b[3], a ); glVertex3f( -len, len, -len ); glColor4f( r[7], g[7], b[7], a ); glVertex3f( len, len, -len ); glColor4f( r[4], g[4], b[4], a ); glVertex3f( len, -len, -len ); glColor4f( r[1], g[1], b[1], a ); glVertex3f( -len, -len, len ); glColor4f( r[2], g[2], b[2], a ); glVertex3f( -len, len, len ); glColor4f( r[6], g[6], b[6], a ); glVertex3f( len, len, len ); glColor4f( r[5], g[5], b[5], a ); glVertex3f( len, -len, len ); } glEnd(); if( fps && info ) { gl_printf( 0.7f, 0.7f, 0.7f, 1.0f, width - 114, height - 40, font, "%5.1f fps", fps ); } glFinish(); frames++; if( timer( &tv, 0 ) >= 0.2f ) { fps = (GLfloat) frames / timer( &tv, 1 ); frames = 0; } }
/* * This is the entry point for offline bytecode generation. */ void emitAllHHBC(AnalysisResultPtr&& ar) { auto ues = ar->getHhasFiles(); decltype(ues) ues_to_print; auto const outputPath = ar->getOutputPath(); std::thread wp_thread; auto unexpectedException = [&] (const char* what) { if (wp_thread.joinable()) { Logger::Error("emitAllHHBC exited via an exception " "before wp_thread was joined: %s", what); } throw; }; try { { SCOPE_EXIT { genText(ues_to_print, outputPath); }; auto commitSome = [&] (decltype(ues)& emitters) { batchCommit(emitters); if (Option::GenerateTextHHBC || Option::GenerateHhasHHBC) { std::move(emitters.begin(), emitters.end(), std::back_inserter(ues_to_print)); } emitters.clear(); }; if (!RuntimeOption::EvalUseHHBBC && ues.size()) { commitSome(ues); } HHBBC::UnitEmitterQueue ueq; auto commitLoop = [&] { folly::Optional<Timer> commitTime; // kBatchSize needs to strike a balance between reducing // transaction commit overhead (bigger batches are better), and // limiting the cost incurred by failed commits due to identical // units that require rollback and retry (smaller batches have // less to lose). Empirical results indicate that a value in // the 2-10 range is reasonable. static const unsigned kBatchSize = 8; while (auto ue = ueq.pop()) { if (!commitTime) { commitTime.emplace(Timer::WallTime, "committing units to repo"); } ues.push_back(std::move(ue)); if (ues.size() == kBatchSize) { commitSome(ues); } } if (ues.size()) commitSome(ues); }; LitstrTable::get().setReading(); ar->finish(); ar.reset(); if (!RuntimeOption::EvalUseHHBBC) { if (Option::GenerateBinaryHHBC) { commitGlobalData(std::unique_ptr<ArrayTypeTable::Builder>{}); } return; } RuntimeOption::EvalJit = false; // For HHBBC to invoke builtins. std::unique_ptr<ArrayTypeTable::Builder> arrTable; wp_thread = std::thread([&] { Timer timer(Timer::WallTime, "running HHBBC"); hphp_thread_init(); hphp_session_init(Treadmill::SessionKind::CompilerEmit); SCOPE_EXIT { hphp_context_exit(); hphp_session_exit(); hphp_thread_exit(); }; HHBBC::whole_program( std::move(ues), ueq, arrTable, Option::ParserThreadCount > 0 ? Option::ParserThreadCount : 0); }); commitLoop(); LitstrTable::get().setReading(); commitGlobalData(std::move(arrTable)); } wp_thread.join(); } catch (std::exception& ex) {
//-----------------------------------WinMain----------------------------------------- // Entry point for our windows application //----------------------------------------------------------------------------------- int WINAPI WinMain(HINSTANCE hinstance, HINSTANCE hprevinstance, LPSTR lpcmdline, int ncmdshow) { WNDCLASSEX winclass; HWND hwnd; MSG msg; // first fill in the window class stucture winclass.cbSize = sizeof(WNDCLASSEX); winclass.style = CS_HREDRAW | CS_VREDRAW; winclass.lpfnWndProc = WindowProc; winclass.cbClsExtra = 0; winclass.cbWndExtra = 0; winclass.hInstance = hinstance; winclass.hIcon = LoadIcon(hinstance, MAKEINTRESOURCE(IDI_ICON1)); winclass.hCursor = LoadCursor(NULL, IDC_ARROW); winclass.hbrBackground = NULL; winclass.lpszMenuName = NULL; winclass.lpszClassName = szWindowClassName; winclass.hIconSm = LoadIcon(hinstance, MAKEINTRESOURCE(IDI_ICON1)); // register the window class if (!RegisterClassEx(&winclass)) { MessageBox(NULL, "Error Registering Class!", "Error", 0); return 0; } // create the window (one that cannot be resized) if (!(hwnd = CreateWindowEx(NULL, szWindowClassName, szApplicationName, WS_OVERLAPPED | WS_VISIBLE | WS_CAPTION | WS_SYSMENU, GetSystemMetrics(SM_CXSCREEN) / 2 - CParams::WindowWidth / 2, GetSystemMetrics(SM_CYSCREEN) / 2 - CParams::WindowHeight / 2, CParams::WindowWidth, CParams::WindowHeight, NULL, NULL, hinstance, NULL))) { MessageBox(NULL, "Error Creating Window!", "Error", 0); return 0; } //Show the window ShowWindow(hwnd, SW_SHOWDEFAULT); UpdateWindow(hwnd); //create a timer CTimer timer(CParams::iFramesPerSecond); //start the timer timer.Start(); globalTimer_p = &timer; // Enter the message loop bool bDone = FALSE; while (!bDone) { while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { if (msg.message == WM_QUIT) { //Stop loop if it's a quit message bDone = TRUE; } else { TranslateMessage(&msg); DispatchMessage(&msg); } } if (timer.ReadyForNextFrame() || g_pController->FastRender()) { if (!g_pController->Update()) { //we have a problem, end app bDone = TRUE; } //this will call WM_PAINT which will render our scene InvalidateRect(hwnd, NULL, TRUE); UpdateWindow(hwnd); } }//end while // Clean up everything and exit the app Cleanup(); UnregisterClass(szWindowClassName, winclass.hInstance); return 0; } // end WinMain
int CProblem::setModel() { //time_t start, end; IloEnv env; try { IloModel model(env); IloCplex cplex(env); /*Variables*/ IloNumVar lambda(env, "lambda"); IloNumVarArray c(env, n); // for (unsigned int u = 0; u < n; u++) { std::stringstream ss; ss << u; std::string str = "c" + ss.str(); c[u] = IloNumVar(env, str.c_str()); } IloArray<IloIntVarArray> z0(env,n); for (unsigned int i=0; i<n; i++) { std::stringstream ss; ss << i; std::string str = "z0_" + ss.str(); z0[i]= IloIntVarArray(env, n, 0, 1); } /* IloIntVarArray z0(env, Info.numAddVar); for (int i = 0; i < Info.numAddVar; i++) { std::stringstream ss; ss << i; std::string str = "z0_" + ss.str(); z0[i] = IloIntVar(env, 0, 1, str.c_str()); } */ /* Objective*/ model.add(IloMinimize(env, lambda)); /*Constrains*/ /* d=function of the distance */ IloArray<IloNumArray> Par_d(env, n); for (unsigned int u = 0; u < n; u++) { Par_d[u] = IloNumArray(env, n); for (unsigned int v = 0; v < n; v++) { Par_d[u][v] = d[u][v]; } } int M = (max_distance + 1) * n; /* for (int i = 0; i < Info.numAddVar; i++) { int u = Info.ConstrIndex[i * 2]; int v = Info.ConstrIndex[i * 2 + 1]; model.add(c[u] - c[v] + M * (z0[i]) >= Par_d[u][v]); model.add(c[v] - c[u] + M * (1 - z0[i]) >= Par_d[u][v]); } */ for (unsigned u=0; u<n; u++) { for (unsigned v=0; v<u; v++) { if (Par_d[u][v] <= max_distance) { model.add(c[v]-c[u]+M*z0[u][v] >=Par_d[u][v]); model.add(c[u]-c[v]+M*(1-z0[u][v]) >=Par_d[u][v]); //Info.numvar++; } } } // d(x) = 3 - x if (max_distance == 2) { // Sechsecke mit der Seitenlaenge 1 model.add(c[0]+c[2] +c[3] +c[5] +c[6] +c[9]>=16.6077); model.add(c[1]+c[3] +c[4] +c[6] +c[7] +c[10]>=16.6077); model.add(c[5]+c[8] +c[9] +c[12]+c[13]+c[16]>=16.6077); model.add(c[6]+c[9] +c[10]+c[13]+c[14]+c[17]>=16.6077); model.add(c[7]+c[10]+c[11]+c[14]+c[15]+c[18]>=16.6077); model.add(c[13]+c[16]+c[17]+c[19]+c[20]+c[22]>=16.6077); model.add(c[14]+c[17]+c[18]+c[20]+c[21]+c[23]>=16.6077); } //d(x) = 4 - x if (max_distance == 3) { // Sechsecke mit der Seitenlaenge 1 model.add(c[0]+c[2] +c[3] +c[5] +c[6] +c[9]>=31.6077); model.add(c[1]+c[3] +c[4] +c[6] +c[7] +c[10]>=31.6077); model.add(c[5]+c[8] +c[9] +c[12]+c[13]+c[16]>=31.6077); model.add(c[6]+c[9] +c[10]+c[13]+c[14]+c[17]>=31.6077); model.add(c[7]+c[10]+c[11]+c[14]+c[15]+c[18]>=31.6077); model.add(c[13]+c[16]+c[17]+c[19]+c[20]+c[22]>=31.6077); model.add(c[14]+c[17]+c[18]+c[20]+c[21]+c[23]>=31.6077); } for (unsigned int v = 0; v < n; v++) { model.add(c[v] <= lambda); model.add(c[v] >= 0); } std::cout << "Number of variables " << Info.numVar << "\n"; /* solve the Model*/ cplex.extract(model); cplex.exportModel("L-Labeling.lp"); cplex.setParam(IloCplex::ClockType,1); IloTimer timer(env); timer.start(); int solveError = cplex.solve(); timer.stop(); if (!solveError) { std::cout << "STATUS : " << cplex.getStatus() << "\n"; env.error() << "Failed to optimize LP \n"; exit(1); } //Info.time = (double)(end-start)/(double)CLOCKS_PER_SEC; Info.time = timer.getTime(); std::cout << "STATUS : " << cplex.getStatus() << "\n"; /* get the solution*/ env.out() << "Solution status = " << cplex.getStatus() << "\n"; Info.numConstr = cplex.getNrows(); env.out() << " Number of constraints = " << Info.numConstr << "\n"; lambda_G_d = cplex.getObjValue(); env.out() << "Solution value = " << lambda_G_d << "\n"; for (unsigned int u = 0; u < n; u++) { C.push_back(cplex.getValue(c[u])); std::cout << "c(" << u << ")=" << C[u] << " "; } } // end try catch (IloException& e) { std::cerr << "Concert exception caught: " << e << std::endl; } catch (...) { std::cerr << "Unknown exception caught" << std::endl; } env.end(); return 0; }
int main(int argc, char** argv) { /* variable declaration */ DB(DB_LVL, "declaration"); DT * memA_t0, *memA_t1, *memA_t2, *memA_t3; DT * memB_t0, *memB_t1, *memB_t2, *memB_t3; int reps, size; int samples; int tid; int i, p, r, bytes, elems; int bytes_min, bytes_max; int elems_min, elems_max; double func_overhead; double t_start, t_end; double t_min, c_min; double alpha = 0.5; DB(DB_LVL, SEPERATOR); /* initialization */ DB(DB_LVL, "intialization"); samples = 3; bytes_min = 1024, bytes_max = 1024*32; /* [1KB, 32KB] */ elems_min = bytes_min/sizeof(DT), elems_max = bytes_max/sizeof(DT); /* the number of elements */ reps = 40000; DB(DB_LVL, SEPERATOR); /* omp environment */ const int nthreads = argc > 1 ? atoi(argv[1]) : 4; fprintf(stderr , "nthreads= %d\n", nthreads); omp_set_num_threads(nthreads); /* iteration */ DB(DB_LVL, "measurement"); for(elems=elems_min, bytes=bytes_min; elems<=elems_max; elems=elems+elems_min, bytes=bytes+bytes_min) { memA_t0 = (DT *)_mm_malloc(bytes_max, 64); memA_t1 = (DT *)_mm_malloc(bytes_max, 64); memA_t2 = (DT *)_mm_malloc(bytes_max, 64); memA_t3 = (DT *)_mm_malloc(bytes_max, 64); memB_t0 = (DT *)_mm_malloc(bytes_max, 64); memB_t1 = (DT *)_mm_malloc(bytes_max, 64); memB_t2 = (DT *)_mm_malloc(bytes_max, 64); memB_t3 = (DT *)_mm_malloc(bytes_max, 64); /* initialization a local space */ fill(memA_t0, elems, 1.0); fill(memA_t1, elems, 2.0); fill(memA_t2, elems, 3.0); fill(memA_t3, elems, 4.0); fill(memB_t0, elems, 1.0); fill(memB_t1, elems, 2.0); fill(memB_t2, elems, 3.0); fill(memB_t3, elems, 4.0); /* measurement */ t_min = 0.0f; c_min = 0.0f; DT ret_t0 = 0.0; DT ret_t1 = 0.0; DT ret_t2 = 0.0; DT ret_t3 = 0.0; #ifdef SAXPY2 #define Z _y #else #define Z _y #endif for(p=0; p<samples; p++) { __m512d *_x, *_y, *_z; #pragma omp parallel private(_x,_y,_z) default(shared) { int tid; tid = omp_get_thread_num(); switch(tid) { case 0: _x = (__m512d*)memA_t0; _y = (__m512d*)memB_t0; break; case 1: _x = (__m512d*)memA_t1; _y = (__m512d*)memB_t1; break; case 2: _x = (__m512d*)memA_t2; _y = (__m512d*)memB_t2; break; case 3: _x = (__m512d*)memA_t3; _y = (__m512d*)memB_t3; break; default: assert(0); } #pragma omp barrier if(p==(samples-1)) t_start = timer(); int r; for(r=0; r<reps; r++) { asm("#t0-beg"); #if 0 double *memO_t0 = (double*)Z; const double *memA_t0 = (double*)_x; const double *memB_t0 = (double*)_y; #pragma vector aligned for(i=0; i<elems; i=i+1) { //ret_t0 += mem_t0[i]; memO_t0[i] = alpha * memA_t0[i] + memB_t0[i]; } memO_t0[0] = memO_t0[0] * 0.1; // to avoid overflow and optimizations #else const int cnts = elems >> 3; const __m512d _a = _mm512_set1_pd(alpha); int ib; for (ib = 0; ib < cnts; ib += 8*8) { Z[ib+0] = _mm512_add_pd(_y[ib+0], _mm512_mul_pd(_a,_x[ib+0])); Z[ib+1] = _mm512_add_pd(_y[ib+1], _mm512_mul_pd(_a,_x[ib+1])); Z[ib+2] = _mm512_add_pd(_y[ib+2], _mm512_mul_pd(_a,_x[ib+2])); Z[ib+3] = _mm512_add_pd(_y[ib+3], _mm512_mul_pd(_a,_x[ib+3])); Z[ib+4] = _mm512_add_pd(_y[ib+4], _mm512_mul_pd(_a,_x[ib+4])); Z[ib+5] = _mm512_add_pd(_y[ib+5], _mm512_mul_pd(_a,_x[ib+5])); Z[ib+6] = _mm512_add_pd(_y[ib+6], _mm512_mul_pd(_a,_x[ib+6])); Z[ib+7] = _mm512_add_pd(_y[ib+7], _mm512_mul_pd(_a,_x[ib+7])); Z[ib+8+0] = _mm512_add_pd(_y[ib+8+0], _mm512_mul_pd(_a,_x[ib+8+0])); Z[ib+8+1] = _mm512_add_pd(_y[ib+8+1], _mm512_mul_pd(_a,_x[ib+8+1])); Z[ib+8+2] = _mm512_add_pd(_y[ib+8+2], _mm512_mul_pd(_a,_x[ib+8+2])); Z[ib+8+3] = _mm512_add_pd(_y[ib+8+3], _mm512_mul_pd(_a,_x[ib+8+3])); Z[ib+8+4] = _mm512_add_pd(_y[ib+8+4], _mm512_mul_pd(_a,_x[ib+8+4])); Z[ib+8+5] = _mm512_add_pd(_y[ib+8+5], _mm512_mul_pd(_a,_x[ib+8+5])); Z[ib+8+6] = _mm512_add_pd(_y[ib+8+6], _mm512_mul_pd(_a,_x[ib+8+6])); Z[ib+8+7] = _mm512_add_pd(_y[ib+8+7], _mm512_mul_pd(_a,_x[ib+8+7])); Z[ib+16+0] = _mm512_add_pd(_y[ib+16+0], _mm512_mul_pd(_a,_x[ib+16+0])); Z[ib+16+1] = _mm512_add_pd(_y[ib+16+1], _mm512_mul_pd(_a,_x[ib+16+1])); Z[ib+16+2] = _mm512_add_pd(_y[ib+16+2], _mm512_mul_pd(_a,_x[ib+16+2])); Z[ib+16+3] = _mm512_add_pd(_y[ib+16+3], _mm512_mul_pd(_a,_x[ib+16+3])); Z[ib+16+4] = _mm512_add_pd(_y[ib+16+4], _mm512_mul_pd(_a,_x[ib+16+4])); Z[ib+16+5] = _mm512_add_pd(_y[ib+16+5], _mm512_mul_pd(_a,_x[ib+16+5])); Z[ib+16+6] = _mm512_add_pd(_y[ib+16+6], _mm512_mul_pd(_a,_x[ib+16+6])); Z[ib+16+7] = _mm512_add_pd(_y[ib+16+7], _mm512_mul_pd(_a,_x[ib+16+7])); Z[ib+24+0] = _mm512_add_pd(_y[ib+24+0], _mm512_mul_pd(_a,_x[ib+24+0])); Z[ib+24+1] = _mm512_add_pd(_y[ib+24+1], _mm512_mul_pd(_a,_x[ib+24+1])); Z[ib+24+2] = _mm512_add_pd(_y[ib+24+2], _mm512_mul_pd(_a,_x[ib+24+2])); Z[ib+24+3] = _mm512_add_pd(_y[ib+24+3], _mm512_mul_pd(_a,_x[ib+24+3])); Z[ib+24+4] = _mm512_add_pd(_y[ib+24+4], _mm512_mul_pd(_a,_x[ib+24+4])); Z[ib+24+5] = _mm512_add_pd(_y[ib+24+5], _mm512_mul_pd(_a,_x[ib+24+5])); Z[ib+24+6] = _mm512_add_pd(_y[ib+24+6], _mm512_mul_pd(_a,_x[ib+24+6])); Z[ib+24+7] = _mm512_add_pd(_y[ib+24+7], _mm512_mul_pd(_a,_x[ib+24+7])); Z[ib+32+0] = _mm512_add_pd(_y[ib+32+0], _mm512_mul_pd(_a,_x[ib+32+0])); Z[ib+32+1] = _mm512_add_pd(_y[ib+32+1], _mm512_mul_pd(_a,_x[ib+32+1])); Z[ib+32+2] = _mm512_add_pd(_y[ib+32+2], _mm512_mul_pd(_a,_x[ib+32+2])); Z[ib+32+3] = _mm512_add_pd(_y[ib+32+3], _mm512_mul_pd(_a,_x[ib+32+3])); Z[ib+32+4] = _mm512_add_pd(_y[ib+32+4], _mm512_mul_pd(_a,_x[ib+32+4])); Z[ib+32+5] = _mm512_add_pd(_y[ib+32+5], _mm512_mul_pd(_a,_x[ib+32+5])); Z[ib+32+6] = _mm512_add_pd(_y[ib+32+6], _mm512_mul_pd(_a,_x[ib+32+6])); Z[ib+32+7] = _mm512_add_pd(_y[ib+32+7], _mm512_mul_pd(_a,_x[ib+32+7])); Z[ib+40+0] = _mm512_add_pd(_y[ib+40+0], _mm512_mul_pd(_a,_x[ib+40+0])); Z[ib+40+1] = _mm512_add_pd(_y[ib+40+1], _mm512_mul_pd(_a,_x[ib+40+1])); Z[ib+40+2] = _mm512_add_pd(_y[ib+40+2], _mm512_mul_pd(_a,_x[ib+40+2])); Z[ib+40+3] = _mm512_add_pd(_y[ib+40+3], _mm512_mul_pd(_a,_x[ib+40+3])); Z[ib+40+4] = _mm512_add_pd(_y[ib+40+4], _mm512_mul_pd(_a,_x[ib+40+4])); Z[ib+40+5] = _mm512_add_pd(_y[ib+40+5], _mm512_mul_pd(_a,_x[ib+40+5])); Z[ib+40+6] = _mm512_add_pd(_y[ib+40+6], _mm512_mul_pd(_a,_x[ib+40+6])); Z[ib+40+7] = _mm512_add_pd(_y[ib+40+7], _mm512_mul_pd(_a,_x[ib+40+7])); Z[ib+48+0] = _mm512_add_pd(_y[ib+48+0], _mm512_mul_pd(_a,_x[ib+48+0])); Z[ib+48+1] = _mm512_add_pd(_y[ib+48+1], _mm512_mul_pd(_a,_x[ib+48+1])); Z[ib+48+2] = _mm512_add_pd(_y[ib+48+2], _mm512_mul_pd(_a,_x[ib+48+2])); Z[ib+48+3] = _mm512_add_pd(_y[ib+48+3], _mm512_mul_pd(_a,_x[ib+48+3])); Z[ib+48+4] = _mm512_add_pd(_y[ib+48+4], _mm512_mul_pd(_a,_x[ib+48+4])); Z[ib+48+5] = _mm512_add_pd(_y[ib+48+5], _mm512_mul_pd(_a,_x[ib+48+5])); Z[ib+48+6] = _mm512_add_pd(_y[ib+48+6], _mm512_mul_pd(_a,_x[ib+48+6])); Z[ib+48+7] = _mm512_add_pd(_y[ib+48+7], _mm512_mul_pd(_a,_x[ib+48+7])); Z[ib+56+0] = _mm512_add_pd(_y[ib+56+0], _mm512_mul_pd(_a,_x[ib+56+0])); Z[ib+56+1] = _mm512_add_pd(_y[ib+56+1], _mm512_mul_pd(_a,_x[ib+56+1])); Z[ib+56+2] = _mm512_add_pd(_y[ib+56+2], _mm512_mul_pd(_a,_x[ib+56+2])); Z[ib+56+3] = _mm512_add_pd(_y[ib+56+3], _mm512_mul_pd(_a,_x[ib+56+3])); Z[ib+56+4] = _mm512_add_pd(_y[ib+56+4], _mm512_mul_pd(_a,_x[ib+56+4])); Z[ib+56+5] = _mm512_add_pd(_y[ib+56+5], _mm512_mul_pd(_a,_x[ib+56+5])); Z[ib+56+6] = _mm512_add_pd(_y[ib+56+6], _mm512_mul_pd(_a,_x[ib+56+6])); Z[ib+56+7] = _mm512_add_pd(_y[ib+56+7], _mm512_mul_pd(_a,_x[ib+56+7])); } #endif asm("#t0-end"); } } if(p==(samples-1)) t_end = timer(); } t_min = (t_end - t_start)/reps; printf("%lf,%lf,%lf,%lf\n", ret_t0, ret_t1, ret_t2, ret_t3); SAVE_DATA("%lf\t", 3*nthreads*bytes/t_min); printf("cbw: %lf\t elems= %d mem_tot= %d\n", 3*nthreads*bytes/t_min, elems/8, 3*elems*sizeof(DT)*nthreads); if(memA_t0!=NULL) _mm_free(memA_t0); if(memA_t1!=NULL) _mm_free(memA_t1); if(memA_t2!=NULL) _mm_free(memA_t2); if(memA_t3!=NULL) _mm_free(memA_t3); if(memB_t0!=NULL) _mm_free(memB_t0); if(memB_t1!=NULL) _mm_free(memB_t1); if(memB_t2!=NULL) _mm_free(memB_t2); if(memB_t3!=NULL) _mm_free(memB_t3); } DB(DB_LVL, SEPERATOR); /* post-process */ DB(DB_LVL, "post-process"); DB(DB_LVL, SEPERATOR); }
int gpuOsSenseGadget::process(GadgetContainerMessage<ISMRMRD::ImageHeader> *m1, GadgetContainerMessage<GenericReconJob> *m2) { // Is this data for this gadget's set/slice? // GDEBUG("Starting gpuOsSenseGadget\n"); if( m1->getObjectPtr()->set != set_number_ || m1->getObjectPtr()->slice != slice_number_ ) { // No, pass it downstream... return this->next()->putq(m1); } //GDEBUG("gpuOsSenseGadget::process\n"); //GPUTimer timer("gpuOsSenseGadget::process"); if (!is_configured_) { GDEBUG("\nData received before configuration complete\n"); return GADGET_FAIL; } GenericReconJob* j = m2->getObjectPtr(); // Let's first check that this job has the required data... if (!j->csm_host_.get() || !j->dat_host_.get() || !j->tra_host_.get() || !j->dcw_host_.get()) { GDEBUG("Received an incomplete Sense job\n"); return GADGET_FAIL; } unsigned int samples = j->dat_host_->get_size(0); unsigned int channels = j->dat_host_->get_size(1); unsigned int rotations = samples / j->tra_host_->get_number_of_elements(); unsigned int frames = j->tra_host_->get_size(1)*rotations; if( samples%j->tra_host_->get_number_of_elements() ) { GDEBUG("Mismatch between number of samples (%d) and number of k-space coordinates (%d).\nThe first should be a multiplum of the latter.\n", samples, j->tra_host_->get_number_of_elements()); return GADGET_FAIL; } boost::shared_ptr< cuNDArray<floatd2> > traj(new cuNDArray<floatd2> (j->tra_host_.get())); boost::shared_ptr< cuNDArray<float> > dcw(new cuNDArray<float> (j->dcw_host_.get())); sqrt_inplace(dcw.get()); boost::shared_ptr< cuNDArray<float_complext> > csm(new cuNDArray<float_complext> (j->csm_host_.get())); boost::shared_ptr< cuNDArray<float_complext> > device_samples(new cuNDArray<float_complext> (j->dat_host_.get())); // Take the reconstruction matrix size from the regulariaztion image. // It could be oversampled from the sequence specified size... matrix_size_ = uint64d2( j->reg_host_->get_size(0), j->reg_host_->get_size(1) ); cudaDeviceProp deviceProp; if( cudaGetDeviceProperties( &deviceProp, device_number_ ) != cudaSuccess) { GDEBUG( "\nError: unable to query device properties.\n" ); return GADGET_FAIL; } unsigned int warp_size = deviceProp.warpSize; matrix_size_os_ = uint64d2(((static_cast<unsigned int>(std::ceil(matrix_size_[0]*oversampling_factor_))+warp_size-1)/warp_size)*warp_size, ((static_cast<unsigned int>(std::ceil(matrix_size_[1]*oversampling_factor_))+warp_size-1)/warp_size)*warp_size); GDEBUG("Matrix size : [%d,%d] \n", matrix_size_[0], matrix_size_[1]); GDEBUG("Matrix size OS : [%d,%d] \n", matrix_size_os_[0], matrix_size_os_[1]); std::vector<size_t> image_dims = to_std_vector(matrix_size_); image_dims.push_back(frames); E_->set_domain_dimensions(&image_dims); E_->set_codomain_dimensions(device_samples->get_dimensions().get()); E_->set_csm(csm); E_->setup( matrix_size_, matrix_size_os_, kernel_width_ ); E_->preprocess(traj.get()); { auto precon = boost::make_shared<cuNDArray<float_complext>>(image_dims); fill(precon.get(),float_complext(1.0f)); //solver_.set_preconditioning_image(precon); } reg_image_ = boost::shared_ptr< cuNDArray<float_complext> >(new cuNDArray<float_complext>(&image_dims)); // These operators need their domain/codomain set before being added to the solver // //E_->set_dcw(dcw); GDEBUG("Prepared\n"); // Expand the average image to the number of frames // { cuNDArray<float_complext> tmp(*j->reg_host_); *reg_image_ = expand( tmp, frames ); } PICS_->set_prior(reg_image_); // Define preconditioning weights // //Apply weights //*device_samples *= *dcw; // Invoke solver // boost::shared_ptr< cuNDArray<float_complext> > result; { GDEBUG("Running NLCG solver\n"); GPUTimer timer("Running NLCG solver"); // Optionally, allow exclusive (per device) access to the solver // This may not matter much in terms of speed, but it can in terms of memory consumption // if( exclusive_access_ ) _mutex[device_number_].lock(); result = solver_.solve(device_samples.get()); if( exclusive_access_ ) _mutex[device_number_].unlock(); } // Provide some info about the scaling between the regularization and reconstruction. // If it is not close to one, PICCS does not work optimally... // if( alpha_ > 0.0 ){ cuNDArray<float_complext> gpureg(j->reg_host_.get()); boost::shared_ptr< cuNDArray<float_complext> > gpurec = sum(result.get(),2); *gpurec /= float(result->get_size(2)); float scale = abs(dot(gpurec.get(), gpurec.get())/dot(gpurec.get(),&gpureg)); GDEBUG("Scaling factor between regularization and reconstruction is %f.\n", scale); } if (!result.get()) { GDEBUG("\nNon-linear conjugate gradient solver failed\n"); return GADGET_FAIL; } /* static int counter = 0; char filename[256]; sprintf((char*)filename, "recon_sb_%d.cplx", counter); write_nd_array<float_complext>( sbresult->to_host().get(), filename ); counter++; */ // If the recon matrix size exceeds the sequence matrix size then crop if( matrix_size_seq_ != matrix_size_ ) *result = crop<float_complext,2>( (matrix_size_-matrix_size_seq_)>>1, matrix_size_seq_, *result ); // Now pass on the reconstructed images // this->put_frames_on_que(frames,rotations,j,result.get(),channels); frame_counter_ += frames; m1->release(); return GADGET_OK; }
int HttpClient::impl(const char *url, const char *data, int size, StringBuffer &response, const HeaderMap *requestHeaders, std::vector<String> *responseHeaders) { SlowTimer timer(RuntimeOption::HttpSlowQueryThreshold, "curl", url); m_response = &response; char error_str[CURL_ERROR_SIZE + 1]; memset(error_str, 0, sizeof(error_str)); CURL *cp = curl_easy_init(); curl_easy_setopt(cp, CURLOPT_URL, url); curl_easy_setopt(cp, CURLOPT_WRITEFUNCTION, curl_write); curl_easy_setopt(cp, CURLOPT_WRITEDATA, (void*)this); curl_easy_setopt(cp, CURLOPT_ERRORBUFFER, error_str); curl_easy_setopt(cp, CURLOPT_NOPROGRESS, 1); curl_easy_setopt(cp, CURLOPT_VERBOSE, 0); curl_easy_setopt(cp, CURLOPT_NOSIGNAL, 1); curl_easy_setopt(cp, CURLOPT_DNS_USE_GLOBAL_CACHE, 0); // for thread-safe curl_easy_setopt(cp, CURLOPT_DNS_CACHE_TIMEOUT, 120); curl_easy_setopt(cp, CURLOPT_NOSIGNAL, 1); // for multithreading mode curl_easy_setopt(cp, CURLOPT_SSL_VERIFYPEER, 0); curl_easy_setopt(cp, CURLOPT_SSL_CTX_FUNCTION, curl_tls_workarounds_cb); curl_easy_setopt(cp, CURLOPT_TIMEOUT, m_timeout); if (m_maxRedirect > 1) { curl_easy_setopt(cp, CURLOPT_FOLLOWLOCATION, 1); curl_easy_setopt(cp, CURLOPT_MAXREDIRS, m_maxRedirect); } else { curl_easy_setopt(cp, CURLOPT_FOLLOWLOCATION, 0); } if (!m_use11) { curl_easy_setopt(cp, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); } if (m_decompress) { curl_easy_setopt(cp, CURLOPT_ENCODING, ""); } if (!m_username.empty()) { curl_easy_setopt(cp, CURLOPT_HTTPAUTH, m_basic ? CURLAUTH_BASIC : CURLAUTH_DIGEST); curl_easy_setopt(cp, CURLOPT_USERNAME, m_username.c_str()); curl_easy_setopt(cp, CURLOPT_PASSWORD, m_password.c_str()); } if (!m_proxyHost.empty() && m_proxyPort) { curl_easy_setopt(cp, CURLOPT_PROXY, m_proxyHost.c_str()); curl_easy_setopt(cp, CURLOPT_PROXYPORT, m_proxyPort); if (!m_proxyUsername.empty()) { curl_easy_setopt(cp, CURLOPT_PROXYAUTH, CURLAUTH_BASIC); curl_easy_setopt(cp, CURLOPT_PROXYUSERNAME, m_proxyUsername.c_str()); curl_easy_setopt(cp, CURLOPT_PROXYPASSWORD, m_proxyPassword.c_str()); } } std::vector<String> headers; // holding those temporary strings curl_slist *slist = nullptr; if (requestHeaders) { for (HeaderMap::const_iterator iter = requestHeaders->begin(); iter != requestHeaders->end(); ++iter) { for (unsigned int i = 0; i < iter->second.size(); i++) { String header = iter->first + ": " + iter->second[i]; headers.push_back(header); slist = curl_slist_append(slist, header.data()); } } if (slist) { curl_easy_setopt(cp, CURLOPT_HTTPHEADER, slist); } } if (data && size) { curl_easy_setopt(cp, CURLOPT_POST, 1); curl_easy_setopt(cp, CURLOPT_POSTFIELDS, data); curl_easy_setopt(cp, CURLOPT_POSTFIELDSIZE, size); } if (responseHeaders) { m_responseHeaders = responseHeaders; curl_easy_setopt(cp, CURLOPT_HEADERFUNCTION, curl_header); curl_easy_setopt(cp, CURLOPT_WRITEHEADER, (void*)this); } if (m_stream_context_options[s_ssl].isArray()) { const Array ssl = m_stream_context_options[s_ssl].toArray(); if (ssl[s_verify_peer].toBoolean()) { curl_easy_setopt(cp, CURLOPT_SSL_VERIFYPEER, 1); } if (ssl.exists(s_capath)) { curl_easy_setopt(cp, CURLOPT_CAPATH, ssl[s_capath].toString().data()); } if (ssl.exists(s_cafile)) { curl_easy_setopt(cp, CURLOPT_CAINFO, ssl[s_cafile].toString().data()); } if (ssl.exists(s_local_cert)) { curl_easy_setopt(cp, CURLOPT_SSLKEY, ssl[s_local_cert].toString().data()); curl_easy_setopt(cp, CURLOPT_SSLKEYTYPE, "PEM"); } if (ssl.exists(s_passphrase)) { curl_easy_setopt(cp, CURLOPT_KEYPASSWD, ssl[s_passphrase].toString().data()); } } long code = 0; { IOStatusHelper io("http", url); CURLcode error_no = curl_easy_perform(cp); if (error_no != CURLE_OK) { m_error = error_str; } else { curl_easy_getinfo(cp, CURLINFO_RESPONSE_CODE, &code); } } set_curl_statuses(cp, url); if (slist) { curl_slist_free_all(slist); } curl_easy_cleanup(cp); return code; }
StatusWith<bool> ReplSetDistLockManager::canOvertakeLock(OperationContext* txn, LocksType lockDoc, const milliseconds& lockExpiration) { const auto& processID = lockDoc.getProcess(); auto pingStatus = _catalog->getPing(txn, processID); Date_t pingValue; if (pingStatus.isOK()) { const auto& pingDoc = pingStatus.getValue(); Status pingDocValidationStatus = pingDoc.validate(); if (!pingDocValidationStatus.isOK()) { return {ErrorCodes::UnsupportedFormat, str::stream() << "invalid ping document for " << processID << ": " << pingDocValidationStatus.toString()}; } pingValue = pingDoc.getPing(); } else if (pingStatus.getStatus() != ErrorCodes::NoMatchingDocument) { return pingStatus.getStatus(); } // else use default pingValue if ping document does not exist. Timer timer(_serviceContext->getTickSource()); auto serverInfoStatus = _catalog->getServerInfo(txn); if (!serverInfoStatus.isOK()) { return serverInfoStatus.getStatus(); } // Be conservative when determining that lock expiration has elapsed by // taking into account the roundtrip delay of trying to get the local // time from the config server. milliseconds delay(timer.millis() / 2); // Assuming symmetrical delay. const auto& serverInfo = serverInfoStatus.getValue(); stdx::lock_guard<stdx::mutex> lk(_mutex); auto pingIter = _pingHistory.find(lockDoc.getName()); if (pingIter == _pingHistory.end()) { // We haven't seen this lock before so we don't have any point of reference // to compare and determine the elapsed time. Save the current ping info // for this lock. _pingHistory.emplace(std::piecewise_construct, std::forward_as_tuple(lockDoc.getName()), std::forward_as_tuple(processID, pingValue, serverInfo.serverTime, lockDoc.getLockID(), serverInfo.electionId)); return false; } auto configServerLocalTime = serverInfo.serverTime - delay; auto* pingInfo = &pingIter->second; LOG(1) << "checking last ping for lock '" << lockDoc.getName() << "' against last seen process " << pingInfo->processId << " and ping " << pingInfo->lastPing; if (pingInfo->lastPing != pingValue || // ping is active // Owner of this lock is now different from last time so we can't // use the ping data. pingInfo->lockSessionId != lockDoc.getLockID() || // Primary changed, we can't trust that clocks are synchronized so // treat as if this is a new entry. pingInfo->electionId != serverInfo.electionId) { pingInfo->lastPing = pingValue; pingInfo->electionId = serverInfo.electionId; pingInfo->configLocalTime = configServerLocalTime; pingInfo->lockSessionId = lockDoc.getLockID(); return false; } if (configServerLocalTime < pingInfo->configLocalTime) { warning() << "config server local time went backwards, from last seen: " << pingInfo->configLocalTime << " to " << configServerLocalTime; return false; } milliseconds elapsedSinceLastPing(configServerLocalTime - pingInfo->configLocalTime); if (elapsedSinceLastPing >= lockExpiration) { LOG(0) << "forcing lock '" << lockDoc.getName() << "' because elapsed time " << elapsedSinceLastPing << " >= takeover time " << lockExpiration; return true; } LOG(1) << "could not force lock '" << lockDoc.getName() << "' because elapsed time " << durationCount<Milliseconds>(elapsedSinceLastPing) << " < takeover time " << durationCount<Milliseconds>(lockExpiration) << " ms"; return false; }
/** * main function. Parses command-line arguments. */ int hisat2_build(int argc, const char **argv) { string outfile; try { // Reset all global state, including getopt state opterr = optind = 1; resetOptions(); string infile; EList<string> infiles(MISC_CAT); parseOptions(argc, argv); argv0 = argv[0]; if(showVersion) { cout << argv0 << " version " << string(HISAT2_VERSION).c_str() << endl; if(sizeof(void*) == 4) { cout << "32-bit" << endl; } else if(sizeof(void*) == 8) { cout << "64-bit" << endl; } else { cout << "Neither 32- nor 64-bit: sizeof(void*) = " << sizeof(void*) << endl; } cout << "Built on " << BUILD_HOST << endl; cout << BUILD_TIME << endl; cout << "Compiler: " << COMPILER_VERSION << endl; cout << "Options: " << COMPILER_OPTIONS << endl; cout << "Sizeof {int, long, long long, void*, size_t, off_t}: {" << sizeof(int) << ", " << sizeof(long) << ", " << sizeof(long long) << ", " << sizeof(void *) << ", " << sizeof(size_t) << ", " << sizeof(off_t) << "}" << endl; return 0; } // Get input filename if(optind >= argc) { cerr << "No input sequence or sequence file specified!" << endl; printUsage(cerr); return 1; } infile = argv[optind++]; // Get output filename if(optind >= argc) { cerr << "No output file specified!" << endl; printUsage(cerr); return 1; } outfile = argv[optind++]; tokenize(infile, ",", infiles); if(infiles.size() < 1) { cerr << "Tokenized input file list was empty!" << endl; printUsage(cerr); return 1; } if(!lineRate_provided) { if(snp_fname == "" && ss_fname == "" && exon_fname == "") { lineRate = GFM<TIndexOffU>::default_lineRate_fm; } else { lineRate = GFM<TIndexOffU>::default_lineRate_gfm; } } // Optionally summarize if(verbose) { cerr << "Settings:" << endl << " Output files: \"" << outfile.c_str() << ".*." << gfm_ext << "\"" << endl << " Line rate: " << lineRate << " (line is " << (1<<lineRate) << " bytes)" << endl << " Lines per side: " << linesPerSide << " (side is " << ((1<<lineRate)*linesPerSide) << " bytes)" << endl << " Offset rate: " << offRate << " (one in " << (1<<offRate) << ")" << endl << " FTable chars: " << ftabChars << endl << " Strings: " << (packed? "packed" : "unpacked") << endl << " Local offset rate: " << localOffRate << " (one in " << (1<<localOffRate) << ")" << endl << " Local fTable chars: " << localFtabChars << endl << " Local sequence length: " << local_index_size << endl << " Local sequence overlap between two consecutive indexes: " << local_index_overlap << endl; #if 0 if(bmax == OFF_MASK) { cerr << " Max bucket size: default" << endl; } else { cerr << " Max bucket size: " << bmax << endl; } if(bmaxMultSqrt == OFF_MASK) { cerr << " Max bucket size, sqrt multiplier: default" << endl; } else { cerr << " Max bucket size, sqrt multiplier: " << bmaxMultSqrt << endl; } if(bmaxDivN == 0xffffffff) { cerr << " Max bucket size, len divisor: default" << endl; } else { cerr << " Max bucket size, len divisor: " << bmaxDivN << endl; } cerr << " Difference-cover sample period: " << dcv << endl; #endif cerr << " Endianness: " << (bigEndian? "big":"little") << endl << " Actual local endianness: " << (currentlyBigEndian()? "big":"little") << endl << " Sanity checking: " << (sanityCheck? "enabled":"disabled") << endl; #ifdef NDEBUG cerr << " Assertions: disabled" << endl; #else cerr << " Assertions: enabled" << endl; #endif cerr << " Random seed: " << seed << endl; cerr << " Sizeofs: void*:" << sizeof(void*) << ", int:" << sizeof(int) << ", long:" << sizeof(long) << ", size_t:" << sizeof(size_t) << endl; cerr << "Input files DNA, " << file_format_names[format].c_str() << ":" << endl; for(size_t i = 0; i < infiles.size(); i++) { cerr << " " << infiles[i].c_str() << endl; } } // Seed random number generator srand(seed); { Timer timer(cerr, "Total time for call to driver() for forward index: ", verbose); try { driver<SString<char> >(infile, infiles, snp_fname, ht_fname, ss_fname, exon_fname, sv_fname, outfile, false, REF_READ_FORWARD); } catch(bad_alloc& e) { if(autoMem) { cerr << "Switching to a packed string representation." << endl; packed = true; } else { throw e; } } } return 0; } catch(std::exception& e) { cerr << "Error: Encountered exception: '" << e.what() << "'" << endl; cerr << "Command: "; for(int i = 0; i < argc; i++) cerr << argv[i] << " "; cerr << endl; deleteIdxFiles(outfile, writeRef || justRef, justRef); return 1; } catch(int e) { if(e != 0) { cerr << "Error: Encountered internal HISAT2 exception (#" << e << ")" << endl; cerr << "Command: "; for(int i = 0; i < argc; i++) cerr << argv[i] << " "; cerr << endl; } deleteIdxFiles(outfile, writeRef || justRef, justRef); return e; } }
StatusWith<DistLockManager::ScopedDistLock> ReplSetDistLockManager::lock( OperationContext* txn, StringData name, StringData whyMessage, milliseconds waitFor, milliseconds lockTryInterval) { Timer timer(_serviceContext->getTickSource()); Timer msgTimer(_serviceContext->getTickSource()); // Counts how many attempts have been made to grab the lock, which have failed with network // error. This value is reset for each lock acquisition attempt because these are // independent write operations. int networkErrorRetries = 0; // Distributed lock acquisition works by tring to update the state of the lock to 'taken'. If // the lock is currently taken, we will back off and try the acquisition again, repeating this // until the lockTryInterval has been reached. If a network error occurs at each lock // acquisition attempt, the lock acquisition will be retried immediately. while (waitFor <= milliseconds::zero() || milliseconds(timer.millis()) < waitFor) { const OID lockSessionID = OID::gen(); const string who = str::stream() << _processID << ":" << getThreadName(); auto lockExpiration = _lockExpiration; MONGO_FAIL_POINT_BLOCK(setDistLockTimeout, customTimeout) { const BSONObj& data = customTimeout.getData(); lockExpiration = stdx::chrono::milliseconds(data["timeoutMs"].numberInt()); } LOG(1) << "trying to acquire new distributed lock for " << name << " ( lock timeout : " << durationCount<Milliseconds>(lockExpiration) << " ms, ping interval : " << durationCount<Milliseconds>(_pingInterval) << " ms, process : " << _processID << " )" << " with lockSessionID: " << lockSessionID << ", why: " << whyMessage; auto lockResult = _catalog->grabLock( txn, name, lockSessionID, who, _processID, Date_t::now(), whyMessage); auto status = lockResult.getStatus(); if (status.isOK()) { // Lock is acquired since findAndModify was able to successfully modify // the lock document. log() << "distributed lock '" << name << "' acquired for '" << whyMessage << "', ts : " << lockSessionID; return ScopedDistLock(txn, lockSessionID, this); } // If a network error occurred, unlock the lock synchronously and try again if (ShardRegistry::kAllRetriableErrors.count(status.code()) && networkErrorRetries < kMaxNumLockAcquireRetries) { LOG(1) << "Failed to acquire distributed lock because of retriable error. Retrying " "acquisition by first unlocking the stale entry, which possibly exists now" << causedBy(status); networkErrorRetries++; status = _catalog->unlock(txn, lockSessionID); if (status.isOK()) { // We certainly do not own the lock, so we can retry continue; } // Fall-through to the error checking logic below invariant(status != ErrorCodes::LockStateChangeFailed); LOG(1) << "Failed to retry acqusition of distributed lock. No more attempts will be made" << causedBy(status); } if (status != ErrorCodes::LockStateChangeFailed) { // An error occurred but the write might have actually been applied on the // other side. Schedule an unlock to clean it up just in case. queueUnlock(lockSessionID); return status; } // Get info from current lock and check if we can overtake it. auto getLockStatusResult = _catalog->getLockByName(txn, name); const auto& getLockStatus = getLockStatusResult.getStatus(); if (!getLockStatusResult.isOK() && getLockStatus != ErrorCodes::LockNotFound) { return getLockStatus; } // Note: Only attempt to overtake locks that actually exists. If lock was not // found, use the normal grab lock path to acquire it. if (getLockStatusResult.isOK()) { auto currentLock = getLockStatusResult.getValue(); auto canOvertakeResult = canOvertakeLock(txn, currentLock, lockExpiration); if (!canOvertakeResult.isOK()) { return canOvertakeResult.getStatus(); } if (canOvertakeResult.getValue()) { auto overtakeResult = _catalog->overtakeLock(txn, name, lockSessionID, currentLock.getLockID(), who, _processID, Date_t::now(), whyMessage); const auto& overtakeStatus = overtakeResult.getStatus(); if (overtakeResult.isOK()) { // Lock is acquired since findAndModify was able to successfully modify // the lock document. LOG(0) << "lock '" << name << "' successfully forced"; LOG(0) << "distributed lock '" << name << "' acquired, ts : " << lockSessionID; return ScopedDistLock(txn, lockSessionID, this); } if (overtakeStatus != ErrorCodes::LockStateChangeFailed) { // An error occurred but the write might have actually been applied on the // other side. Schedule an unlock to clean it up just in case. queueUnlock(lockSessionID); return overtakeStatus; } } } LOG(1) << "distributed lock '" << name << "' was not acquired."; if (waitFor == milliseconds::zero()) { break; } // Periodically message for debugging reasons if (msgTimer.seconds() > 10) { LOG(0) << "waited " << timer.seconds() << "s for distributed lock " << name << " for " << whyMessage; msgTimer.reset(); } // A new lock acquisition attempt will begin now (because the previous found the lock to be // busy, so reset the retries counter) networkErrorRetries = 0; const milliseconds timeRemaining = std::max(milliseconds::zero(), waitFor - milliseconds(timer.millis())); sleepFor(std::min(lockTryInterval, timeRemaining)); } return {ErrorCodes::LockBusy, str::stream() << "timed out waiting for " << name}; }
void VoxelManipulator::addArea(const VoxelArea &area) { // Cancel if requested area has zero volume if (area.hasEmptyExtent()) return; // Cancel if m_area already contains the requested area if(m_area.contains(area)) return; TimeTaker timer("addArea", &addarea_time); // Calculate new area VoxelArea new_area; // New area is the requested area if m_area has zero volume if(m_area.hasEmptyExtent()) { new_area = area; } // Else add requested area to m_area else { new_area = m_area; new_area.addArea(area); } s32 new_size = new_area.getVolume(); /*dstream<<"adding area "; area.print(dstream); dstream<<", old area "; m_area.print(dstream); dstream<<", new area "; new_area.print(dstream); dstream<<", new_size="<<new_size; dstream<<std::endl;*/ // Allocate new data and clear flags MapNode *new_data = new MapNode[new_size]; assert(new_data); u8 *new_flags = new u8[new_size]; assert(new_flags); memset(new_flags, VOXELFLAG_NO_DATA, new_size); // Copy old data s32 old_x_width = m_area.MaxEdge.X - m_area.MinEdge.X + 1; for(s32 z=m_area.MinEdge.Z; z<=m_area.MaxEdge.Z; z++) for(s32 y=m_area.MinEdge.Y; y<=m_area.MaxEdge.Y; y++) { unsigned int old_index = m_area.index(m_area.MinEdge.X,y,z); unsigned int new_index = new_area.index(m_area.MinEdge.X,y,z); memcpy(&new_data[new_index], &m_data[old_index], old_x_width * sizeof(MapNode)); memcpy(&new_flags[new_index], &m_flags[old_index], old_x_width * sizeof(u8)); } // Replace area, data and flags m_area = new_area; MapNode *old_data = m_data; u8 *old_flags = m_flags; /*dstream<<"old_data="<<(int)old_data<<", new_data="<<(int)new_data <<", old_flags="<<(int)m_flags<<", new_flags="<<(int)new_flags<<std::endl;*/ m_data = new_data; m_flags = new_flags; delete[] old_data; delete[] old_flags; //dstream<<"addArea done"<<std::endl; }
DockWnd::DockWnd(QWidget *main) : QWidget(NULL) { #ifndef WIN32 wharfIcon = NULL; #endif connect(this, SIGNAL(toggleWin()), main, SLOT(toggleShow())); connect(this, SIGNAL(showPopup(QPoint)), main, SLOT(showPopup(QPoint))); connect(pClient, SIGNAL(event(ICQEvent*)), this, SLOT(processEvent(ICQEvent*))); connect(pClient, SIGNAL(messageRead(ICQMessage*)), this, SLOT(messageRead(ICQMessage*))); connect(pClient, SIGNAL(messageReceived(ICQMessage*)), this, SLOT(messageReceived(ICQMessage*))); connect(pMain, SIGNAL(iconChanged()), this, SLOT(reset())); m_state = 0; showIcon = State; QTimer *t = new QTimer(this); connect(t, SIGNAL(timeout()), this, SLOT(timer())); t->start(800); bool bWMDock = false; #ifndef WIN32 Atom r_type; int r_format; unsigned long count, bytes_remain; unsigned char *prop = NULL, *prop2 = NULL; Atom _XA_WIN_SUPPORTING_WM_CHECK = XInternAtom(qt_xdisplay(), XA_WIN_SUPPORTING_WM_CHECK, False); int p = XGetWindowProperty(qt_xdisplay(), qt_xrootwin(), _XA_WIN_SUPPORTING_WM_CHECK, 0, 1, False, XA_CARDINAL, &r_type, &r_format, &count, &bytes_remain, &prop); if (p == Success && prop && r_type == XA_CARDINAL && r_format == 32 && count == 1) { Window n = *(long *) prop; p = XGetWindowProperty(qt_xdisplay(), n, _XA_WIN_SUPPORTING_WM_CHECK, 0, 1, False, XA_CARDINAL, &r_type, &r_format, &count, &bytes_remain, &prop2); if (p == Success && prop2 && r_type == XA_CARDINAL && r_format == 32 && count == 1) bWMDock = true; } if (prop) XFree(prop); if (prop2) XFree(prop2); #endif #ifdef USE_KDE log(L_DEBUG, "WM props? %u", bWMDock); if (!bWMDock) KWin::setSystemTrayWindowFor( winId(), main->topLevelWidget()->winId()); #endif needToggle = false; #ifdef WIN32 QWidget::hide(); QWidget::setIcon(Pict(pClient->getStatusIcon())); gDock = this; oldDockProc = (WNDPROC)SetWindowLongW(winId(), GWL_WNDPROC, (LONG)DockWindowProc); if (oldDockProc == 0) oldDockProc = (WNDPROC)SetWindowLongA(winId(), GWL_WNDPROC, (LONG)DockWindowProc); NOTIFYICONDATAA notifyIconData; notifyIconData.cbSize = sizeof(notifyIconData); notifyIconData.hIcon = topData()->winIcon; notifyIconData.hWnd = winId(); notifyIconData.szTip[0] = 0; notifyIconData.uCallbackMessage = WM_DOCK; notifyIconData.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP; notifyIconData.uID = 0; Shell_NotifyIconA(NIM_ADD, ¬ifyIconData); #else if (!bWMDock){ setBackgroundMode(X11ParentRelative); setIcon(Pict(pClient->getStatusIcon())); #ifdef USE_KDE show(); #else hide(); #endif }else{ wharfIcon = new WharfIcon(this); Display *dsp = x11Display(); WId win = winId(); XWMHints *hints; XClassHint classhint; classhint.res_name = (char*)"sim"; classhint.res_class = (char*)"sim"; XSetClassHint(dsp, win, &classhint); hints = XGetWMHints(dsp, win); hints->initial_state = WithdrawnState; hints->icon_x = 0; hints->icon_y = 0; hints->icon_window = wharfIcon->winId(); hints->window_group = win; hints->flags = WindowGroupHint | IconWindowHint | IconPositionHint | StateHint; XSetWMHints(dsp, win, hints); XFree( hints ); XSetCommand(dsp, winId(), _argv, _argc); resize(64, 64); show(); } #endif loadUnread(); reset(); }
void StaticContentCache::load() { Timer timer(Timer::WallTime, "loading static content"); if (!RuntimeOption::FileCache.empty()) { TheFileCache = std::make_shared<FileCache>(); TheFileCache->loadMmap(RuntimeOption::FileCache.c_str()); Logger::Info("loaded file cache from %s", RuntimeOption::FileCache.c_str()); return; } int rootSize = RuntimeOption::SourceRoot.size(); if (rootSize == 0) return; // get a list of all files, one for each extension Logger::Info("searching all files under source root..."); int count = 0; std::map<std::string, std::vector<std::string> > ext2files; { const char *argv[] = {"", (char*)RuntimeOption::SourceRoot.c_str(), "-type", "f", nullptr}; std::string files; std::vector<std::string> out; Process::Exec("find", argv, nullptr, files); Util::split('\n', files.c_str(), out, true); for (unsigned int i = 0; i < out.size(); i++) { const std::string &name = out[i]; size_t pos = name.rfind('.'); if (pos != std::string::npos) { ext2files[name.substr(pos+1)].push_back(name); ++count; } } } Logger::Info("analyzing %d files under source root...", count); for (auto iter = RuntimeOption::StaticFileExtensions.begin(); iter != RuntimeOption::StaticFileExtensions.end(); ++iter) { if (ext2files.find(iter->first) == ext2files.end()) { continue; } const std::vector<std::string> &out = ext2files[iter->first]; int total = 0; for (unsigned int i = 0; i < out.size(); i++) { auto const f = std::make_shared<ResourceFile>(); auto const sb = std::make_shared<CstrBuffer>(out[i].c_str()); if (sb->valid() && sb->size() > 0) { std::string url = out[i].substr(rootSize + 1); f->file = sb; m_files[url] = f; // prepare gzipped content, skipping image and swf files if (iter->second.find("image/") != 0 && iter->first != "swf") { int len = sb->size(); char *data = gzencode(sb->data(), len, 9, CODING_GZIP); if (data) { if (unsigned(len) < sb->size()) { f->compressed = std::make_shared<CstrBuffer>(data, len); } else { free(data); } } } total += sb->size(); } } Logger::Info("..loaded %d bytes of %s files", total, iter->first.c_str()); m_totalSize += total; } Logger::Info("loaded %d bytes of static content in total", m_totalSize); }
void Detection::TestBs() { std::ofstream fout("text.txt", std::ofstream::ate|std::ofstream::app); fout << "\n**********************************************************************\n"; fout << "10. TestBS" << std::endl; std::string bss[3]; bss[0] = "ppvabs.pplive.com"; bss[1] = "ppvaindex.pplive.com"; bss[2] = "60.28.216.149"; for (int i = 0; i < 3; ++i) { boost::asio::io_service io_service; boost::asio::ip::udp::resolver resolver(io_service); boost::asio::ip::udp::resolver::query query(boost::asio::ip::udp::v4(), bss[i], ""); boost::asio::ip::udp::endpoint receiver_endpoint = *resolver.resolve(query); receiver_endpoint.port(6400); boost::asio::ip::udp::socket socket(io_service); socket.open(boost::asio::ip::udp::v4()); std::string send_buffer = ""; boost::uint32_t check_sum = 0x80301a7d; boost::uint8_t action = 0x14; boost::uint32_t transaction_id = 0x00000006; boost::uint8_t is_request = 1; boost::uint16_t peer_version = 0x0106; boost::uint16_t reserved = 0x0000; boost::uint32_t guid_1 = 0x36e985d8; boost::uint32_t guid_2 = 0x4e4e041d; boost::uint32_t guid_3 = 0x8a7db9b7; boost::uint32_t guid_4 = 0x911a6af6; send_buffer.append((const char *)&check_sum, 4); send_buffer.append((const char *)&action, 1); send_buffer.append((const char *)&transaction_id, 4); send_buffer.append((const char *)&is_request, 1); send_buffer.append((const char *)&peer_version, 2); send_buffer.append((const char *)&reserved, 2); send_buffer.append((const char *)&guid_1, 4); send_buffer.append((const char *)&guid_2, 4); send_buffer.append((const char *)&guid_3, 4); send_buffer.append((const char *)&guid_4, 4); socket.send_to(boost::asio::buffer(send_buffer), receiver_endpoint); boost::asio::ip::udp::endpoint sender_endpoint; boost::asio::deadline_timer timer(io_service); socket.async_receive_from( boost::asio::buffer(data_, 2000), sender_endpoint, boost::bind(&Detection::HandleReceiveFrom, this, 0, 0, boost::ref(timer), boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); timer.expires_from_now(boost::posix_time::seconds(5)); timer.async_wait(boost::bind(&Detection::TimeOutHandler, this, 0, boost::asio::placeholders::error, boost::ref(socket), 0)); io_service.run(); if (has_tracker_list) { m_progress_pos_ = 135; break; } } fout.close(); }
void BDPTIntegrator::Render(const Scene &scene) { ProfilePhase p(Prof::IntegratorRender); // Compute _lightDistr_ for sampling lights proportional to power std::unique_ptr<Distribution1D> lightDistr = ComputeLightPowerDistribution(scene); // Partition the image into tiles Film *film = camera->film; const Bounds2i sampleBounds = film->GetSampleBounds(); const Vector2i sampleExtent = sampleBounds.Diagonal(); const int tileSize = 16; const int nXTiles = (sampleExtent.x + tileSize - 1) / tileSize; const int nYTiles = (sampleExtent.y + tileSize - 1) / tileSize; ProgressReporter reporter(nXTiles * nYTiles, "Rendering"); // Allocate buffers for debug visualization const int bufferCount = (1 + maxDepth) * (6 + maxDepth) / 2; std::vector<std::unique_ptr<Film>> weightFilms(bufferCount); if (visualizeStrategies || visualizeWeights) { for (int depth = 0; depth <= maxDepth; ++depth) { for (int s = 0; s <= depth + 2; ++s) { int t = depth + 2 - s; if (t == 0 || (s == 1 && t == 1)) continue; char filename[32]; snprintf(filename, sizeof(filename), "bdpt_d%02i_s%02i_t%02i.exr", depth, s, t); weightFilms[BufferIndex(s, t)] = std::unique_ptr<Film>(new Film( film->fullResolution, Bounds2f(Point2f(0, 0), Point2f(1, 1)), std::unique_ptr<Filter>(CreateBoxFilter(ParamSet())), film->diagonal * 1000, filename, 1.f)); } } } // Render and write the output image to disk if (scene.lights.size() > 0) { StatTimer timer(&renderingTime); ParallelFor([&](const Point2i tile) { // Render a single tile using BDPT MemoryArena arena; int seed = tile.y * nXTiles + tile.x; std::unique_ptr<Sampler> tileSampler = sampler->Clone(seed); int x0 = sampleBounds.pMin.x + tile.x * tileSize; int x1 = std::min(x0 + tileSize, sampleBounds.pMax.x); int y0 = sampleBounds.pMin.y + tile.y * tileSize; int y1 = std::min(y0 + tileSize, sampleBounds.pMax.y); Bounds2i tileBounds(Point2i(x0, y0), Point2i(x1, y1)); std::unique_ptr<FilmTile> filmTile = camera->film->GetFilmTile(tileBounds); for (Point2i pPixel : tileBounds) { tileSampler->StartPixel(pPixel); do { // Generate a single sample using BDPT Point2f pFilm = (Point2f)pPixel + tileSampler->Get2D(); // Trace the camera and light subpaths Vertex *cameraVertices = arena.Alloc<Vertex>(maxDepth + 2); Vertex *lightVertices = arena.Alloc<Vertex>(maxDepth + 1); int nCamera = GenerateCameraSubpath( scene, *tileSampler, arena, maxDepth + 2, *camera, pFilm, cameraVertices); int nLight = GenerateLightSubpath( scene, *tileSampler, arena, maxDepth + 1, cameraVertices[0].time(), *lightDistr, lightVertices); // Execute all BDPT connection strategies Spectrum L(0.f); for (int t = 1; t <= nCamera; ++t) { for (int s = 0; s <= nLight; ++s) { int depth = t + s - 2; if ((s == 1 && t == 1) || depth < 0 || depth > maxDepth) continue; // Execute the $(s, t)$ connection strategy and // update _L_ Point2f pFilmNew = pFilm; Float misWeight = 0.f; Spectrum Lpath = ConnectBDPT( scene, lightVertices, cameraVertices, s, t, *lightDistr, *camera, *tileSampler, &pFilmNew, &misWeight); if (visualizeStrategies || visualizeWeights) { Spectrum value; if (visualizeStrategies) value = misWeight == 0 ? 0 : Lpath / misWeight; if (visualizeWeights) value = Lpath; weightFilms[BufferIndex(s, t)]->AddSplat( pFilmNew, value); } if (t != 1) L += Lpath; else film->AddSplat(pFilmNew, Lpath); } } filmTile->AddSample(pFilm, L); arena.Reset(); } while (tileSampler->StartNextSample()); } film->MergeFilmTile(std::move(filmTile)); reporter.Update(); }, Point2i(nXTiles, nYTiles)); reporter.Done(); } film->WriteImage(1.0f / sampler->samplesPerPixel); // Write buffers for debug visualization if (visualizeStrategies || visualizeWeights) { const Float invSampleCount = 1.0f / sampler->samplesPerPixel; for (size_t i = 0; i < weightFilms.size(); ++i) if (weightFilms[i]) weightFilms[i]->WriteImage(invSampleCount); } }
void Detection::TestTracker() { // std::ofstream fout("text.txt", std::ofstream::ate|std::ofstream::app); // fout << "\n**********************************************************************\n"; // fout << "11. TestTracker" << std::endl; // fout.close(); std::string send_buffer = ""; boost::uint32_t check_sum = 0x66e3d105; boost::uint8_t action = 0x31; boost::uint32_t transaction_id = 0x00054afb; boost::uint8_t is_request = 1; boost::uint16_t peer_version = 0x0106; boost::uint16_t reserved = 0x0000; boost::uint32_t rid_1 = 0x4c58186d; boost::uint32_t rid_2 = 0x45cab895; boost::uint32_t rid_3 = 0x47d10c08; boost::uint32_t rid_4 = 0xf4354547; boost::uint32_t guid_1 = 0xa111fe6e; boost::uint32_t guid_2 = 0x4e1472c3; boost::uint32_t guid_3 = 0x9298e98b; boost::uint32_t guid_4 = 0x825f3f99; boost::uint16_t peer_count = 0x0032; send_buffer.append((const char *)&check_sum, 4); send_buffer.append((const char *)&action, 1); send_buffer.append((const char *)&transaction_id, 4); send_buffer.append((const char *)&is_request, 1); send_buffer.append((const char *)&peer_version, 2); send_buffer.append((const char *)&reserved, 2); send_buffer.append((const char *)&rid_1, 4); send_buffer.append((const char *)&rid_2, 4); send_buffer.append((const char *)&rid_3, 4); send_buffer.append((const char *)&rid_4, 4); send_buffer.append((const char *)&guid_1, 4); send_buffer.append((const char *)&guid_2, 4); send_buffer.append((const char *)&guid_3, 4); send_buffer.append((const char *)&guid_4, 4); send_buffer.append((const char *)&peer_count, 2); for (int i = 0; i < m_tracker_infos.size(); ++i) { boost::asio::io_service io_service; boost::asio::ip::udp::resolver resolver(io_service); boost::asio::ip::udp::resolver::query query(boost::asio::ip::udp::v4(), m_tracker_infos[i].ip, ""); boost::asio::ip::udp::endpoint receiver_endpoint = *resolver.resolve(query); receiver_endpoint.port(m_tracker_infos[i].port); boost::asio::ip::udp::socket socket(io_service); socket.open(boost::asio::ip::udp::v4()); socket.send_to(boost::asio::buffer(send_buffer), receiver_endpoint); boost::asio::ip::udp::endpoint sender_endpoint; boost::asio::deadline_timer timer(io_service); socket.async_receive_from( boost::asio::buffer(data_, 2000), sender_endpoint, boost::bind(&Detection::HandleReceiveFrom, this, 1, i, boost::ref(timer), boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); timer.expires_from_now(boost::posix_time::seconds(5)); timer.async_wait(boost::bind(&Detection::TimeOutHandler, this, 1, boost::asio::placeholders::error, boost::ref(socket), i)); io_service.run(); } }
Aconfig::Aconfig(char *name, Aobject *father) : Aobject(name, father, (father->pos.w-400)>>1, (father->pos.h-400)>>1, 400, 400) { //zorder(zorderTOP); MYwindow *w=(MYwindow *)getWindow(); setTooltips("properties dialog"); close=new Abutton("close", this, pos.w-100, pos.h-30, 90, 20, "CLOSE"); close->setTooltips("close the properties dialog"); close->show(TRUE); /* regist=new Abutton("register", this, 10, pos.h-30, 90, 20, "regist"); regist->setTooltips("register information"); { MYwindow *w=(MYwindow *)father; Aregistry *reg=w->regpwd; char sname[256]=""; char spwd[256]=""; reg->read("name", sname, sizeof(sname)); reg->read("pwd", spwd, sizeof(spwd)); regist->show(!VerifyPassword(sname, spwd)); } */ resItems=new Aitem("resolutions", "resolutions", NULL, 0); { int i; for(i=0; i<Atable::reso_MAXIMUM; i++) new Aitem(Atable::infoReso[i].help, Atable::infoReso[i].help, resItems, i, this); } resList=new Alist("video resolution", this, 100, 40, pos.w-120, 20, resItems); resList->setCurrentByData(((MYwindow *)father)->currentReso); resList->setTooltips("video resolution selector"); resList->show(TRUE); rateItems=new Aitem("rate", "rate", NULL, 0); new Aitem("8 f/s", "8 frames per seconde", rateItems, rate8, this); new Aitem("12 f/s", "12 frames per seconde", rateItems, rate12, this); new Aitem("20 f/s", "20 frames per seconde", rateItems, rate20, this); new Aitem("24 f/s", "24 frames per seconde", rateItems, rate24, this); new Aitem("25 f/s", "25 frames per seconde", rateItems, rate25, this); new Aitem("30 f/s", "30 frames per seconde", rateItems, rate30, this); new Aitem("50 f/s", "50 frames per seconde", rateItems, rate50, this); new Aitem("60 f/s", "60 frames per seconde", rateItems, rate60, this); rateList=new Alist("video frame rate", this, 100, 70, pos.w-120, 20, rateItems); rateList->setCurrentByData(((MYwindow *)father)->currentRate); rateList->setTooltips("video frame rate selector"); rateList->show(TRUE); timeItems=new Aitem("time", "time", NULL, 0); new Aitem("4 s", "4 secondes", timeItems, 4, this); new Aitem("8 s", "8 secondes", timeItems, 8, this); new Aitem("12 s", "12 secondes", timeItems, 12, this); new Aitem("16 s", "16 secondes", timeItems, 16, this); new Aitem("20 s", "20 secondes", timeItems, 20, this); timeList=new Alist("timeList", this, 100, 100, pos.w-270, 20, timeItems); timeList->setCurrentByData(((MYwindow *)father)->table->vlooptime); timeList->setTooltips("video buffer time (eg: rnbox or loop107)"); timeList->show(TRUE); cmpItems=new Aitem("cmp", "cmp", NULL, 0); new Aitem("[none]", "no compression, raw format", cmpItems, compressNONE, this); new Aitem("JPEG 100%", "compression, jpeg - quality 100%", cmpItems, compressJPEG100, this); new Aitem("JPEG 80%", "compression, jpeg - quality 80%", cmpItems, compressJPEG80, this); new Aitem("JPEG 50%", "compression, jpeg - quality 50%", cmpItems, compressJPEG50, this); cmpList=new Alist("cmpList", this, pos.w-160, 100, 140, 20, cmpItems); if(((MYwindow *)father)->table->compressRamVidz) { if(((MYwindow *)father)->table->compressJpegQuality>0.8f) cmpList->setCurrentByData(compressJPEG100); else if(((MYwindow *)father)->table->compressJpegQuality>0.5f) cmpList->setCurrentByData(compressJPEG80); else cmpList->setCurrentByData(compressJPEG50); } else cmpList->setCurrentByData(compressNONE); cmpList->setTooltips("video loop compression in ram (eg: rnbox)"); cmpList->show(TRUE); /* render=new Abutton("render", this, 100, 100, Abutton::btCHECK); render->setTooltips("activate threaded rendering [multi-processor]"); render->setChecked(w->table->threading); render->show(TRUE); */ /* priority=new Abutton("priority", this, 100, 120, Abutton::btCHECK); priority->setTooltips("activate high priority level"); priority->show(TRUE); priority->setChecked(w->table->highPriority); */ /* splash=new Abutton("splash", this, 100, 320, Abutton::btCHECK); splash->show(TRUE); splash->setTooltips("activate splash screen"); { bool b; bool ok=w->reg->read("splash", &b); splash->setChecked((!ok)|b); } */ tips=new Abutton("tooltips", this, 100, 320, Abutton::btCHECK); tips->show(TRUE); tips->setTooltips("activate tooltips"); { bool b; bool ok=w->reg->read("tooltips", &b); tips->setChecked((!ok)|b); } midiInItems=new Aitem("midi in", "midi in devices", NULL, 0); { MIDIINCAPS mic; int n=midiInGetNumDevs(); int i; for(i=0; i<n; i++) { if(midiInGetDevCaps(i, &mic, sizeof(mic))==MMSYSERR_NOERROR) { Aitem *it=new Aitem(mic.szPname, mic.szPname, midiInItems, i, this); if(((MYwindow *)father)->table->midiInDeviceF&(1i64<<i)) it->state|=Aitem::stateSELECTED; } } } midiOutItems=new Aitem("midi out", "midi out devices", NULL, 0); new Aitem("[none]", "no midi out device selected", midiOutItems, -1, this); { MIDIOUTCAPS moc; int n=midiOutGetNumDevs(); int i; for(i=0; i<n; i++) { if(midiOutGetDevCaps(i, &moc, sizeof(moc))==MMSYSERR_NOERROR) new Aitem(moc.szPname, moc.szPname, midiOutItems, i, this); } } psetItems=new Aitem("pset", "presets channel", NULL, -1); new Aitem("[none]", "no preset / program change", psetItems, -1, this); { int i; for(i=0; i<16; i++) { char str[256]; char st2[256]; sprintf(str, "%d", i+1); sprintf(st2, "midi channel #%d", i+1); new Aitem(str, st2, psetItems, i, this); } } new Aitem("[all]", "all channels", psetItems, 16, this); midiIn=new Amlist("midi in devices", this, 100, 160, pos.w-120, 50, midiInItems); midiIn->setTooltips("midi in devices"); midiIn->show(TRUE); midiOut=new Alist("midi out devices", this, 100, 220, pos.w-120, 20, midiOutItems); midiOut->setCurrentByData(((MYwindow *)father)->table->midiOutDevice); midiOut->setTooltips("midi out devices"); midiOut->show(TRUE); pset=new Alist("pset", this, 100, 250, pos.w-120, 20, psetItems); pset->setCurrentByData(((MYwindow *)father)->table->midiProgChangeChannel); pset->setTooltips("presets - program change event midi channel"); pset->show(TRUE); sndsize=new Aselsize("sndsize", this, 100, 280, pos.w-120, 20); sndsize->set(((MYwindow *)father)->table->dsoundsize); { char str[256]; float v=(sndsize->get()*(float)(DSOUNDSIZE-DSOUNDSIZEMIN)+(float)DSOUNDSIZEMIN)/(44100.f*2.f); // 2x >> double event buffer sprintf(str, "%5.2f ms", v*1000.f); sndsize->set(str); } sndsize->setTooltips("direct sound buffer latency"); sndsize->show(true); timer(500); } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// Aconfig::~Aconfig() { ((MYwindow *)father)->config=NULL; delete(close); //delete(regist); delete(resList); delete(resItems); delete(rateList); delete(rateItems); delete(timeList); delete(timeItems); delete(cmpList); delete(cmpItems); //delete(render); //delete(priority); delete(midiIn); delete(midiInItems); delete(midiOut); delete(midiOutItems); delete(pset); delete(psetItems); //delete(splash); delete(tips); ((MYwindow *)father)->settings(); } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// bool Aconfig::mouse(int x, int y, int state, int event) { return FALSE; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// bool Aconfig::notify(Anode *o, int event, dword p) { MYwindow *w=(MYwindow *)father; switch(event) { case nyCLICK: if(o==close) { destroy(); return TRUE; } else if(o==regist) { Aobject *o=new Apass("register", (Aobject *)father); o->show(true); o->repaint(); } break; case nyCHANGE: if(o==tips) { bool b=tips->isChecked(); w->reg->write("tooltips", b); w->btips=b; } else if(o==resList) { Aitem *i=(Aitem *)p; w->currentReso=i->data; w->table->videoW=Atable::infoReso[w->currentReso].width; w->table->videoH=Atable::infoReso[w->currentReso].height; } else if(o==rateList) { Aitem *i=(Aitem *)p; w->currentRate=i->data; switch(i->data) { case rate8: w->table->frameRate=8; break; case rate12: w->table->frameRate=12; break; case rate20: w->table->frameRate=20; break; case rate24: w->table->frameRate=24; break; case rate25: w->table->frameRate=25; break; case rate30: w->table->frameRate=30; break; case rate50: w->table->frameRate=50; break; case rate60: w->table->frameRate=60; break; } } /* else if(o==render) { w->table->threading=render->isChecked(); } else if(o==priority) { w->table->highPriority=priority->isChecked(); } */ else if(o==timeList) { Aitem *i=(Aitem *)p; w->table->vlooptime=i->data; } else if(o==cmpList) { Aitem *i=(Aitem *)p; switch(i->data) { case compressNONE: w->table->compressRamVidz=false; w->table->compressJpegQuality=1.f; break; case compressJPEG100: w->table->compressRamVidz=true; w->table->compressJpegQuality=1.f; break; case compressJPEG80: w->table->compressRamVidz=true; w->table->compressJpegQuality=0.8f; break; case compressJPEG50: w->table->compressRamVidz=true; w->table->compressJpegQuality=0.5f; break; } } else if(o==midiIn) { Aitem *i=(Aitem *)p; if(i->state&Aitem::stateSELECTED) w->table->midiInDeviceF|=(1i64<<i->data); else w->table->midiInDeviceF&=~(1i64<<i->data); } else if(o==midiOut) { Aitem *i=(Aitem *)p; w->table->midiOutDevice=i->data; } else if(o==pset) { Aitem *i=(Aitem *)p; w->table->midiProgChangeChannel=i->data; } else if(o==sndsize) { char str[256]; float v=(sndsize->get()*(float)(DSOUNDSIZE-DSOUNDSIZEMIN)+(float)DSOUNDSIZEMIN)/(44100.f*2.f); // 2x >> double event buffer sprintf(str, "%5.2f ms", v*1000.f); sndsize->set(str); w->table->dsoundsize=sndsize->get(); } return true; } return Aobject::notify(o, event , p); }
lword NetworkSink::DoFlush(unsigned long maxTime, size_t targetSize) { NetworkSender &sender = AccessSender(); bool forever = maxTime == INFINITE_TIME; Timer timer(Timer::MILLISECONDS, forever); unsigned int totalFlushSize = 0; while (true) { if (m_buffer.CurrentSize() <= targetSize) break; if (m_needSendResult) { if (sender.MustWaitForResult() && !sender.Wait(SaturatingSubtract(maxTime, timer.ElapsedTime()), CallStack("NetworkSink::DoFlush() - wait send result", 0))) break; unsigned int sendResult = sender.GetSendResult(); #if CRYPTOPP_TRACE_NETWORK OutputDebugString((IntToString((unsigned int)this) + ": Sent " + IntToString(sendResult) + " bytes\n").c_str()); #endif m_buffer.Skip(sendResult); totalFlushSize += sendResult; m_needSendResult = false; if (!m_buffer.AnyRetrievable()) break; } unsigned long timeOut = maxTime ? SaturatingSubtract(maxTime, timer.ElapsedTime()) : 0; if (sender.MustWaitToSend() && !sender.Wait(timeOut, CallStack("NetworkSink::DoFlush() - wait send", 0))) break; size_t contiguousSize = 0; const byte *block = m_buffer.Spy(contiguousSize); #if CRYPTOPP_TRACE_NETWORK OutputDebugString((IntToString((unsigned int)this) + ": Sending " + IntToString(contiguousSize) + " bytes\n").c_str()); #endif sender.Send(block, contiguousSize); m_needSendResult = true; if (maxTime > 0 && timeOut == 0) break; // once time limit is reached, return even if there is more data waiting } m_byteCountSinceLastTimerReset += totalFlushSize; ComputeCurrentSpeed(); if (m_buffer.IsEmpty() && !m_needSendResult) { if (m_eofState == EOF_PENDING_SEND) { sender.SendEof(); m_eofState = sender.MustWaitForEof() ? EOF_PENDING_DELIVERY : EOF_DONE; } while (m_eofState == EOF_PENDING_DELIVERY) { unsigned long timeOut = maxTime ? SaturatingSubtract(maxTime, timer.ElapsedTime()) : 0; if (!sender.Wait(timeOut, CallStack("NetworkSink::DoFlush() - wait EOF", 0))) break; if (sender.EofSent()) m_eofState = EOF_DONE; } } return totalFlushSize; }