int main(int argc, char* argv[]) { srand(time(NULL)); int fd = socket(AF_INET, SOCK_STREAM, 0); if (fd == -1) { printf("%s\n", strerror(errno)); } struct sockaddr_in servaddr; servaddr.sin_family = AF_INET; servaddr.sin_port = htons(11000); inet_pton(AF_INET, "127.0.0.1", &servaddr.sin_addr); int ret = connect(fd, (struct sockaddr *)&servaddr, sizeof(struct sockaddr)); if (ret == -1) { printf("%s", strerror(errno)); return 0; } int epfd = epoll_create(1024); if (epfd == -1) { printf("create failed"); return 0; } set_io_nonblock(fd, 1); struct epoll_event event; event.data.fd = fd; event.events = EPOLLIN | EPOLLET; ret = epoll_ctl(epfd, EPOLL_CTL_ADD, fd, &event); struct epoll_event *evs = (struct epoll_event *)malloc(sizeof(struct epoll_event) * 200); int done = 0; while (!done) { int i; recv_again: int n = epoll_wait(epfd, evs, 1024, 100); if (n == -1 && errno != EINTR) { printf("%s", strerror(errno)); return 0; } for (i = 0; i < n; ++i) { int fd = evs[i].data.fd; printf("fd=%u type=%u\n", fd, evs[i].events); if (evs[i].events && EPOLLIN) { char recvbuf[102400]; int ret = safe_tcp_recv_n(fd, recvbuf, 102400); if (ret == 0) { printf("fd closed"); return 0; } else if (ret > 0) { printf("recvbuf len=%d\n", ret); int len = ret; int readlen = 0; struct timeval end; struct timeval start; while (readlen < len) { gettimeofday(&end, NULL); char* ptr = recvbuf; proto_pkg_t *msg = (proto_pkg_t *)(ptr + readlen); start = seq_time_map[msg->seq]; printf("recv: %d,%d,%d,%d,%d,%s:%lu,%lu\n", msg->id, msg->cmd, msg->seq, msg->ret, msg->len, msg->data, msg->len - sizeof(proto_pkg_t), (end.tv_sec - start.tv_sec) * 1000000 + (end.tv_usec - start.tv_usec) ); readlen += msg->len; seq_time_map.erase(msg->seq); } } else { printf("recv error"); return 0; } } else if (evs[i].events && EPOLLOUT) { } } if (seq_time_map.size()) { goto recv_again; } sleep(1); //getchar(); char input[200] = {'\0'}; int num = rand() % 200+ 1; //int num = 30; gen_str(input, num); // scanf("%s", input); char buf[1024]; for (i = 0; i < 200; ++i) { proto_pkg_t *pkg = (proto_pkg_t *)buf; pkg->id = i; pkg->cmd = i + 1; pkg->ret = i + 2; pkg->seq = ++seq; struct timeval start; gettimeofday(&start, NULL); seq_time_map[pkg->seq] = start; pkg->len = sizeof(proto_pkg_t) + strlen(input) + 1; input[strlen(input)] = '\0'; memcpy(pkg->data, input, strlen(input) + 1); send(fd, buf, pkg->len, 0); printf("send: id=%u,cmd=%u,seq=%u,ret=%u,%s:%lu\n\n", pkg->id, pkg->cmd, pkg->seq, pkg->ret, input, strlen(input) + 1); // getchar(); } // sleep(1); //if (rand() % 2) { //} } free(evs); close(epfd); close(fd); return 0; }
Value *ForExprAST::Codegen() { // Output this as: // var = alloca double // ... // start = startexpr // store start -> var // goto loop // loop: // ... // bodyexpr // ... // loopend: // step = stepexpr // endcond = endexpr // // curvar = load var // nextvar = curvar + step // store nextvar -> var // br endcond, loop, endloop // outloop: Function *TheFunction = Builder.GetInsertBlock()->getParent(); // Create an alloca for the variable in the entry block. AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName); // Emit the start code first, without 'variable' in scope. Value *StartVal = Start->Codegen(); if (StartVal == 0) return 0; // Store the value into the alloca. Builder.CreateStore(StartVal, Alloca); // Make the new basic block for the loop header, inserting after current // block. BasicBlock *LoopBB = BasicBlock::Create(TheContext, "loop", TheFunction); // Insert an explicit fall through from the current block to the LoopBB. Builder.CreateBr(LoopBB); // Start insertion in LoopBB. Builder.SetInsertPoint(LoopBB); // Within the loop, the variable is defined equal to the PHI node. If it // shadows an existing variable, we have to restore it, so save it now. AllocaInst *OldVal = NamedValues[VarName]; NamedValues[VarName] = Alloca; // Emit the body of the loop. This, like any other expr, can change the // current BB. Note that we ignore the value computed by the body, but don't // allow an error. if (Body->Codegen() == 0) return 0; // Emit the step value. Value *StepVal; if (Step) { StepVal = Step->Codegen(); if (StepVal == 0) return 0; } else { // If not specified, use 1.0. StepVal = ConstantFP::get(TheContext, APFloat(1.0)); } // Compute the end condition. Value *EndCond = End->Codegen(); if (EndCond == 0) return EndCond; // Reload, increment, and restore the alloca. This handles the case where // the body of the loop mutates the variable. Value *CurVar = Builder.CreateLoad(Alloca, VarName.c_str()); Value *NextVar = Builder.CreateFAdd(CurVar, StepVal, "nextvar"); Builder.CreateStore(NextVar, Alloca); // Convert condition to a bool by comparing equal to 0.0. EndCond = Builder.CreateFCmpONE( EndCond, ConstantFP::get(TheContext, APFloat(0.0)), "loopcond"); // Create the "after loop" block and insert it. BasicBlock *AfterBB = BasicBlock::Create(TheContext, "afterloop", TheFunction); // Insert the conditional branch into the end of LoopEndBB. Builder.CreateCondBr(EndCond, LoopBB, AfterBB); // Any new code will be inserted in AfterBB. Builder.SetInsertPoint(AfterBB); // Restore the unshadowed variable. if (OldVal) NamedValues[VarName] = OldVal; else NamedValues.erase(VarName); // for expr always returns 0.0. return Constant::getNullValue(Type::getDoubleTy(TheContext)); }
void BannerCache::CacheBannerInternal( std::string sBannerPath ) { using std::min; using std::max; std::string sError; RageSurface *pImage = RageSurfaceUtils::LoadFile( sBannerPath, sError ); if( pImage == nullptr ) { LOG->UserLog( "Cache file", sBannerPath, "couldn't be loaded: %s", sError.c_str() ); return; } const int iSourceWidth = pImage->w, iSourceHeight = pImage->h; int iWidth = pImage->w / 2, iHeight = pImage->h / 2; // int iWidth = pImage->w, iHeight = pImage->h; /* Round to the nearest power of two. This simplifies the actual texture load. */ iWidth = closest( iWidth, power_of_two(iWidth), power_of_two(iWidth) / 2 ); iHeight = closest( iHeight, power_of_two(iHeight), power_of_two(iHeight) / 2 ); /* Don't resize the image to less than 32 pixels in either dimension or the next * power of two of the source (whichever is smaller); it's already very low res. */ iWidth = max( iWidth, min(32, power_of_two(iSourceWidth)) ); iHeight = max( iHeight, min(32, power_of_two(iSourceHeight)) ); //RageSurfaceUtils::ApplyHotPinkColorKey( pImage ); RageSurfaceUtils::Zoom( pImage, iWidth, iHeight ); /* * When paletted banner cache is enabled, cached banners are paletted. Cached * 32-bit banners take 1/16 as much memory, 16-bit banners take 1/8, and paletted * banners take 1/4. * * When paletted banner cache is disabled, cached banners are stored in 16-bit * RGBA. Cached 32-bit banners take 1/8 as much memory, cached 16-bit banners * take 1/4, and cached paletted banners take 1/2. * * Paletted cache is disabled by default because palettization takes time, causing * the initial cache run to take longer. Also, newer ATI hardware doesn't supported * paletted textures, which would slow down runtime, because we have to depalettize * on use. They'd still have the same memory benefits, though, since we only load * one cached banner into a texture at once, and the speed hit may not matter on * newer ATI cards. RGBA is safer, though. */ if( g_bPalettedBannerCache ) { if( pImage->fmt.BytesPerPixel != 1 ) RageSurfaceUtils::Palettize( pImage ); } else { /* Dither to the final format. We use A1RGB5, since that's usually supported * natively by both OpenGL and D3D. */ RageSurface *dst = CreateSurface( pImage->w, pImage->h, 16, 0x7C00, 0x03E0, 0x001F, 0x8000 ); /* OrderedDither is still faster than ErrorDiffusionDither, and * these images are very small and only displayed briefly. */ RageSurfaceUtils::OrderedDither( pImage, dst ); delete pImage; pImage = dst; } const std::string sCachePath = GetBannerCachePath(sBannerPath); RageSurfaceUtils::SaveSurface( pImage, sCachePath ); /* If an old image is loaded, free it. */ if( g_BannerPathToImage.find(sBannerPath) != g_BannerPathToImage.end() ) { RageSurface *oldimg = g_BannerPathToImage[sBannerPath]; delete oldimg; g_BannerPathToImage.erase(sBannerPath); } if( PREFSMAN->m_BannerCache == BNCACHE_LOW_RES_PRELOAD ) { /* Keep it; we're just going to load it anyway. */ g_BannerPathToImage[sBannerPath] = pImage; } else delete pImage; /* Remember the original size. */ BannerData.SetValue( sBannerPath, "Path", sCachePath ); BannerData.SetValue( sBannerPath, "Width", iSourceWidth ); BannerData.SetValue( sBannerPath, "Height", iSourceHeight ); BannerData.SetValue( sBannerPath, "FullHash", GetHashForFile( sBannerPath ) ); BannerData.WriteFile( BANNER_CACHE_INDEX ); }
bool Http2StreamHandler::handle(Http2Frame* frame, const int& precedingStreamId, std::map<uint16_t, uint32_t>& settings, Http2ReadWriteUtil* handler, std::map<int, bool>& frameAcks, void*& requestObj) { if(frame->header.type==1) { //Header Frame Http2HeadersFrame* headerf = static_cast<Http2HeadersFrame*>(frame); //Header frame can only be received in the Idle/Open states if(state==Idle || state==Open) { state = Open; //If this is the end of headers block then decode headers if(!isWebSocket && headerf->getHeader().isEndHeaders()) { request->setHttp2Headers(context->decode(headerf->headerBlockFragment)); void* temp = handleWebSocketRequest(context, frame, handler, settings); if(temp!=NULL) { requestObj = temp; return false; } } else if(headerf->getHeader().isEndHeaders()) { std::map<std::string, std::string> wshdrs = context->decode(headerf->headerBlockFragment); if(wshdrs.find(":opcode")!=wshdrs.end()) { try { wsrequest->dataType = CastUtil::lexical_cast<short>(wshdrs[":opcode"]); } catch(const std::exception& e) { //TODO specify proper error closeConnection(frame->header.streamIdentifier, handler); return true; } } else { //TODO specify proper error closeConnection(frame->header.streamIdentifier, handler); return true; } } else { //else continue appending to the headerBlockFragment headerBlockFragment += headerf->headerBlockFragment; } if(headerf->getHeader().isWsEndSegment()) { endofsegment = true; } if(headerf->getHeader().isEndOfStream()) { endofstream = true; if(isWebSocket && headerf->getHeader().isEndHeaders()) { //TODO handle websocket close } } //if end of stream is reached then change state and process request if(!isWebSocket && headerf->getHeader().isEndHeaders() && endofstream) { state = Half_Closed_R; sendPushPromiseFrames(context, frame, handler, settings); requestObj = getRequestAndReInit(); } } else { closeConnection(frame->header.streamIdentifier, handler); return true; } } else if(frame->header.type==9) { //Continuation Frame Http2ContinuationFrame* contf = static_cast<Http2ContinuationFrame*>(frame); //Continuation frame can only be received in the Open state given the preceding stream id is same //and last frame type was either a Header/Continuation/PushPromise frame if(state==Open && precedingStreamId==contf->getHeader().getStreamIdentifier() && (lastFrameType==1 || lastFrameType==5 || lastFrameType==9)) { if(!isWebSocket && contf->getHeader().isEndHeaders()) { headerBlockFragment += contf->headerBlockFragment; request->setHttp2Headers(context->decode(headerBlockFragment)); void* temp = handleWebSocketRequest(context, frame, handler, settings); if(temp!=NULL) { requestObj = temp; return false; } //if end of stream was set in the Header frame then change state and process request if(endofstream) { state = Half_Closed_R; sendPushPromiseFrames(context, frame, handler, settings); requestObj = getRequestAndReInit(); } } else if(contf->getHeader().isEndHeaders()) { std::map<std::string, std::string> wshdrs = context->decode(contf->headerBlockFragment); if(wshdrs.find(":opcode")!=wshdrs.end()) { try { wsrequest->dataType = CastUtil::lexical_cast<short>(wshdrs[":opcode"]); } catch(const std::exception& e) { //TODO specify proper error closeConnection(frame->header.streamIdentifier, handler); return true; } if(isWebSocket && endofstream && contf->getHeader().isEndHeaders()) { //TODO handle websocket close } } else { //TODO specify proper error closeConnection(frame->header.streamIdentifier, handler); return true; } } else { headerBlockFragment += contf->headerBlockFragment; } } else { closeConnection(frame->header.streamIdentifier, handler); return true; } } else if(frame->header.type==5) { closeConnection(frame->header.streamIdentifier, handler); return true; } else if(frame->header.type==4) { Http2SettingsFrame* settingsf = static_cast<Http2SettingsFrame*>(frame); //Settings Frame if(streamIdentifier==0) { settings.insert(settingsf->settings.begin(), settingsf->settings.end()); if(!settingsf->header.flags.test(0)) { Http2SettingsFrame sframe; sframe.header.flags.set(0); handler->writeData(&sframe); std::map<uint16_t, uint32_t>::iterator itt; for(itt=settings.begin();itt!=settings.end();++itt) { std::cout << "client_settings[" << itt->first << "] = " << itt->second << std::endl; } if(settings.find(Http2SettingsFrame::SETTINGS_MAX_FRAME_SIZE)!=settings.end()) { handler->updateMaxFrameSize(settings[Http2SettingsFrame::SETTINGS_MAX_FRAME_SIZE]); } } else if(frameAcks.find(frame->header.type)!=frameAcks.end() && frameAcks[frame->header.type]) { frameAcks.erase(frame->header.type); } else { //Invalid Ack received closeConnection(frame->header.streamIdentifier, handler); return true; } } else { closeConnection(frame->header.streamIdentifier, handler); return true; } } else if(frame->header.type==6) { Http2PingFrame* pingf = static_cast<Http2PingFrame*>(frame); //Settings Frame if(streamIdentifier==0) { if(!pingf->header.flags.test(0)) { Http2PingFrame pframe; pframe.opaqueData = pingf->opaqueData; pframe.header.flags.set(0); handler->writeData(&pframe); } else if(frameAcks.find(frame->header.type)!=frameAcks.end() && frameAcks[frame->header.type]) { frameAcks.erase(frame->header.type); } else { //Invalid Ack received closeConnection(frame->header.streamIdentifier, handler); return true; } } else { closeConnection(frame->header.streamIdentifier, handler); return true; } } else if(frame->header.type==7) { Http2GoAwayFrame* goawayf = static_cast<Http2GoAwayFrame*>(frame); //Go away Frame if(streamIdentifier==0) { std::cout << "Got go away frame for connection with last stream id " << goawayf->lastStreamId << " " << goawayf->errorCode << " " << goawayf->additionalDebugData << std::endl; } closeConnection(frame->header.streamIdentifier, handler); return true; } else if(frame->header.type==8) { Http2WindowUpdateFrame* windupdf = static_cast<Http2WindowUpdateFrame*>(frame); //Settings Frame if(streamIdentifier>=0) { if(streamIdentifier==0) { handler->updateSenderWindowSize(windupdf->windowSizeIncrement); std::cout << "Got window increment size " << windupdf->windowSizeIncrement << " for connection" << std::endl; } else { senderFlowControlWindow += windupdf->windowSizeIncrement; std::cout << "Got window increment size " << windupdf->windowSizeIncrement << " for stream " << streamIdentifier << std::endl; } if(pendingSendData.isDataPending()) { handler->writePendingDataFrame(pendingSendData); } } else { closeConnection(frame->header.streamIdentifier, handler); return true; } } else if(frame->header.type==10) { Http2AlternativeServicesFrame* alsvcf = static_cast<Http2AlternativeServicesFrame*>(frame); //Settings Frame if(streamIdentifier>=0) { std::cout << "Got alternative services frame for connection " << alsvcf->protocolId << std::endl; //TODO is it even valid for a server context? } else { closeConnection(frame->header.streamIdentifier, handler); return true; } } else if(state!=Idle) { if(frame->header.type==0) { //Send Window Update if current window size is not sufficient if(receiverFlowControlWindow<=frame->header.payloadLength) { Http2WindowUpdateFrame cwuframe; cwuframe.windowSizeIncrement = 65535 + frame->header.payloadLength; cwuframe.header.streamIdentifier = frame->header.streamIdentifier; handler->writeData(&cwuframe); } receiverFlowControlWindow -= frame->header.payloadLength; //Data Frame Http2DataFrame* dataf = static_cast<Http2DataFrame*>(frame); //Data frame can only be received in the Open/HalfClosedL state if(state==Open || state==Half_Closed_L) { //if end of stream is reached then change state and process request if(!isWebSocket && dataf->getHeader().isEndOfStream()) { request->content += dataf->data; state = Half_Closed_R; requestObj = getRequestAndReInit(); } else if(dataf->getHeader().isEndOfStream()) { wsrequest->data += dataf->data; //TODO handle websocket close } else if(isWebSocket && dataf->getHeader().isWsEndSegment()) { wsrequest->data += dataf->data; requestObj = getWsRequestAndReInit(); } else { //else continue appending the data if(!isWebSocket)request->content += dataf->data; else wsrequest->data += dataf->data; } } else { closeConnection(frame->header.streamIdentifier, handler); return true; } } else if(frame->header.type==3) { //Reset Frame if(lastFrameType!=9 && frame->header.streamIdentifier!=0) { state = Closed; } else { closeConnection(frame->header.streamIdentifier, handler); return true; } } } else { closeConnection(frame->header.streamIdentifier, handler); return true; } lastFrameType = frame->getHeader().type; delete frame; return false; }
BOOL CConcretion::Update(_bstr_t strGuid, _bstr_t strOldID,_bstr_t strTypeName, std::map<_bstr_t,_bstr_t> &mapFlds) { _bstr_t strSql, strNewID,strOldTypeName ; _bstr_t strSql1 = "",strSql2 = "", strSql3; _RecordsetPtr pRecordSet; vector<_bstr_t> vecStrSql; _variant_t var; adoDataTypeEnum adoFldType; string strTemp=""; strSql = "SELECT * FROM 类别信息 WHERE 类别名称 = '" + strTypeName + "'"; pRecordSet = theBllApp.m_pDB->ExcuteSqlRes(strSql, adCmdText); if(pRecordSet == NULL||pRecordSet->adoEOF) return FALSE; strNewID = pRecordSet->GetCollect("编号"); if(strNewID != strOldID) {//类别修改 if (CDatabaseFactory::m_enumDatabaseType==OracleType) strSql1 = "UPDATE 基本信息 SET 类别 = " + strNewID + " WHERE GUID= '"+ strGuid + "'"; else strSql1 = "UPDATE 基本信息 SET 类别 = " + strNewID + " WHERE [GUID]= '"+ strGuid + "'"; strSql = "SELECT * FROM 类别信息 WHERE 编号= " + strOldID; pRecordSet = theBllApp.m_pDB->ExcuteSqlRes(strSql, adCmdText); if(pRecordSet == NULL||pRecordSet->adoEOF) return FALSE; strOldTypeName = (_bstr_t)pRecordSet->GetCollect("类别名称"); //从旧具体类别表删除记录 if (CDatabaseFactory::m_enumDatabaseType==OracleType) strSql2 = "DELETE FROM " + strOldTypeName + " WHERE GUID = '" + strGuid + "'"; else strSql2 = "DELETE FROM " + strOldTypeName + " WHERE [GUID] = '" + strGuid + "'"; } //具体类别表存不存记录 if (CDatabaseFactory::m_enumDatabaseType==OracleType) strSql = "SELECT * FROM " + strTypeName + " WHERE GUID = '" + strGuid + "'"; else strSql = "SELECT * FROM " + strTypeName + " WHERE [GUID] = '" + strGuid + "'"; pRecordSet = theBllApp.m_pDB->ExcuteSqlRes(strSql, adCmdText); if(pRecordSet == NULL) return FALSE; else { if(pRecordSet->adoEOF) {//具体类别表不存在记录 map<_bstr_t,_bstr_t>::iterator itr1, itr2; _bstr_t strColumns,strValues; itr1 = mapFlds.begin(); itr2 = --mapFlds.end(); while(itr1 != itr2) { strTemp=(char *)(*itr1).first; if (strTemp=="ID") { itr1++; continue; } //字段 if (CDatabaseFactory::m_enumDatabaseType==OracleType) strColumns += (*itr1).first + ","; else strColumns +="[" +(*itr1).first + "],"; //值 var.bstrVal = (*itr1).first; adoFldType = pRecordSet->GetFields()->GetItem(var.bstrVal)->GetType(); if(adoFldType == ADODB::adDate || adoFldType == ADODB::adDBTimeStamp) { switch(CDatabaseFactory::m_enumDatabaseType) { case AccessType: strValues += "#" + (*itr1).second + "#,"; break; case SqlServerType: strValues += "'" + (*itr1).second + "',"; break; case OracleType: strValues += "to_date('" + (*itr1).second + "','yyyy-mm-dd'),"; break; } } else if( (adoFldType == ADODB::adInteger ) || (adoFldType == ADODB::adNumeric) || (adoFldType == ADODB::adDouble ) ) strValues+=(*itr1).second+","; else strValues+="'"+(*itr1).second+"',"; //循环 itr1++; } //最后一个字段 //字段 if (CDatabaseFactory::m_enumDatabaseType==OracleType) strColumns += (*itr1).first; else strColumns +="[" +(*itr1).first + "]"; //值 var.bstrVal = (*itr1).first; adoFldType = pRecordSet->GetFields()->GetItem(var.bstrVal)->GetType(); if(adoFldType == ADODB::adDate || adoFldType == ADODB::adDBTimeStamp) { switch(CDatabaseFactory::m_enumDatabaseType) { case AccessType: strValues += "#" + (*itr1).second + "#"; break; case SqlServerType: strValues += "'" + (*itr1).second + "'"; break; case OracleType: strValues += "to_date('" + (*itr1).second + "','yyyy-mm-dd')"; break; } } else if( (adoFldType == ADODB::adInteger ) || (adoFldType == ADODB::adNumeric) || (adoFldType == ADODB::adDouble ) ) strValues+=(*itr1).second; else strValues+="'"+(*itr1).second+"'"; strSql3 = "INSERT INTO " + strTypeName + " ( " + strColumns + " ) VALUES (" + strValues + ")"; } else {//具体类别表存在记录 map<_bstr_t,_bstr_t>::iterator itr1, itr2; _bstr_t strUpdateFormat=""; mapFlds.erase("GUID"); itr1 = mapFlds.begin(); itr2 = --mapFlds.end(); while(itr1 != itr2) { strTemp=(char *)(*itr1).first; if (strTemp=="ID") { itr1++; continue; } var.bstrVal = (*itr1).first; adoFldType = pRecordSet->GetFields()->GetItem(var.bstrVal)->GetType(); if(adoFldType == ADODB::adDate || adoFldType == ADODB::adDBTimeStamp) { switch(CDatabaseFactory::m_enumDatabaseType) { case AccessType: strUpdateFormat +="["+ (*itr1).first + "]=#" + (*itr1).second + "#,"; break; case SqlServerType: strUpdateFormat += "["+(*itr1).first + "]='" + (*itr1).second + "',"; break; case OracleType: strUpdateFormat += (*itr1).first +"=to_date('" + (*itr1).second + "','yyyy-mm-dd'),"; break; } } else if( (adoFldType == ADODB::adInteger ) || (adoFldType == ADODB::adNumeric) || (adoFldType == ADODB::adDouble ) ) { switch(CDatabaseFactory::m_enumDatabaseType) { case AccessType: case SqlServerType: strUpdateFormat += "["+(*itr1).first + "]=" + (*itr1).second+ ","; break; case OracleType: strUpdateFormat += (*itr1).first +"="+(*itr1).second+ ","; break; } } else { switch(CDatabaseFactory::m_enumDatabaseType) { case AccessType: case SqlServerType: strUpdateFormat += "["+(*itr1).first + "]='" + (*itr1).second + "',"; break; case OracleType: strUpdateFormat += (*itr1).first + "='" + (*itr1).second + "',"; break; } } //循环 itr1++; } //最后一个字段 var.bstrVal = (*itr1).first; adoFldType = pRecordSet->GetFields()->GetItem(var.bstrVal)->GetType(); if(adoFldType == ADODB::adDate || adoFldType == ADODB::adDBTimeStamp) { switch(CDatabaseFactory::m_enumDatabaseType) { case AccessType: strUpdateFormat +="["+ (*itr1).first + "]=#" + (*itr1).second + "#"; break; case SqlServerType: strUpdateFormat += "["+(*itr1).first + "]='" + (*itr1).second + "'"; break; case OracleType: strUpdateFormat += (*itr1).first +"=to_date('" + (*itr1).second + "','yyyy-mm-dd')"; break; } } else if( (adoFldType == ADODB::adInteger ) || (adoFldType == ADODB::adNumeric) || (adoFldType == ADODB::adDouble ) ) { switch(CDatabaseFactory::m_enumDatabaseType) { case AccessType: case SqlServerType: strUpdateFormat += "["+(*itr1).first + "]=" + (*itr1).second; break; case OracleType: strUpdateFormat += (*itr1).first +"="+(*itr1).second; break; } } else { switch(CDatabaseFactory::m_enumDatabaseType) { case AccessType: case SqlServerType: strUpdateFormat += "["+(*itr1).first + "]='" + (*itr1).second + "'"; break; case OracleType: strUpdateFormat += (*itr1).first + "='" + (*itr1).second + "'"; break; } } strSql3 = "UPDATE " + strTypeName + " SET " + strUpdateFormat + " WHERE GUID ='" + strGuid + "'"; } } if(strSql1.length() != 0) vecStrSql.push_back(strSql1); if(strSql2.length() != 0) vecStrSql.push_back(strSql2); vecStrSql.push_back(strSql3); return theBllApp.m_pDB->ExcuteTrans(vecStrSql, adCmdText); }
AlembicObjectEmitterNode::~AlembicObjectEmitterNode() { gEmitterNodes.erase(gEmitterNodes.find(mRefId)); }
void PlayHistoryTracker::Event(bz_EventData *eventData) { switch (eventData->eventType) { default: break; case bz_ePlayerDieEvent: { bz_PlayerDieEventData_V1 *deathRecord = (bz_PlayerDieEventData_V1*)eventData; // Create variables to store the callsigns std::string victimCallsign = "UNKNOWN"; std::string killerCallsign = "UNKNOWN"; // Get player records for victim and killer bz_BasePlayerRecord *victimData = bz_getPlayerByIndex(deathRecord->playerID); bz_BasePlayerRecord *killerData = bz_getPlayerByIndex(deathRecord->killerID); // If we have valid data, update the callsigns if (victimData) victimCallsign = victimData->callsign.c_str(); if (killerData) killerCallsign = killerData->callsign.c_str(); // Free the player records bz_freePlayerRecord(victimData); bz_freePlayerRecord(killerData); // Handle the victim if (spreeCount.find(deathRecord->playerID) != spreeCount.end()) { // Store a quick reference to their former spree count int spreeTotal = spreeCount[deathRecord->playerID]; std::string message; // Generate an appropriate message, if any if (spreeTotal >= 5 && spreeTotal < 10) message = victimCallsign + std::string("'s rampage was stopped by ") + killerCallsign; else if (spreeTotal >= 10 && spreeTotal < 20) message = victimCallsign + std::string("'s killing spree was halted by ") + killerCallsign; else if (spreeTotal >= 20) message = std::string("The unstoppable reign of ") + victimCallsign + std::string(" was ended by ") + killerCallsign; // If we have a message to send, then send it if (message.size()) bz_sendTextMessage(BZ_SERVER, BZ_ALLUSERS, message.c_str()); // Since they died, release their spree counter spreeCount[deathRecord->playerID] = 0; } // Handle the killer (if it wasn't also the victim) if (deathRecord->playerID != deathRecord->killerID && spreeCount.find(deathRecord->killerID) != spreeCount.end()) { // Store a quick reference to their newly incremented spree count int spreeTotal = ++spreeCount[deathRecord->playerID]; std::string message; // Generate an appropriate message, if any if (spreeTotal == 5) message = victimCallsign + std::string(" is on a Rampage!"); else if (spreeTotal == 10) message = victimCallsign + std::string(" is on a Killing Spree!"); else if (spreeTotal == 20) message = victimCallsign + std::string(" is Unstoppable!!"); else if (spreeTotal > 20 && spreeTotal%5 == 0) message = victimCallsign + std::string(" continues to rage on"); // If we have a message to send, then send it if (message.size()) bz_sendTextMessage(BZ_SERVER, BZ_ALLUSERS, message.c_str()); } } break; case bz_ePlayerJoinEvent: { // Initialize the spree counter for the player that just joined spreeCount[((bz_PlayerJoinPartEventData_V1*)eventData)->playerID] = 0; } break; case bz_ePlayerPartEvent: { // Erase the spree counter for the player that just left std::map<int, int >::iterator itr = spreeCount.find(((bz_PlayerJoinPartEventData_V1*)eventData)->playerID); if (itr != spreeCount.end()) spreeCount.erase(itr); } break; } }
void ChargesApp::update() { mFps = getAverageFps(); // Update device if ( mLeap && mLeap->isConnected() ) { mLeap->update(); } vector< int32_t > currentFingersIds; for ( const std::pair< int32_t, LeapSdk::Hand > hand : mHands ) { const LeapSdk::FingerMap &fingers = hand.second.getFingers(); for ( const auto &fkv : fingers ) { int32_t id = fkv.first; const LeapSdk::Finger &finger = fkv.second; currentFingersIds.push_back( id ); // new finger? if ( mActiveFingers.find( id ) == mActiveFingers.end() ) { mActiveFingers[ id ] = mTimestamp; mEffectCharge.addCursor( id, 0.f, 0.f, 1.f ); // init with (0, 0), will be updated below } // update finger const LeapSdk::ScreenMap &screens = mLeap->getScreens(); if ( screens.begin() != screens.end() ) { mActiveFingers[ id ] = mTimestamp; const LeapSdk::Screen &screen = screens.begin()->second; Vec3f normPos; screen.intersects( finger, normPos, true, 1.5f ); // normalized screen coordinates with 1.5 clamp ratio Vec2f fingertip = normPos.xy() * Vec2f( mFbo.getSize() ); Vec3f screenPos; screen.intersects( finger, screenPos, false, 1.5f ); // screen coordinates with 1.5 clamp ratio float d = screenPos.distance( finger.getPosition() ); const float dMin = 50.f; const float dMax = 500.f; const float sMin = 1.f; const float sMax = 100.f; d = math< float >::clamp( d, dMin, dMax ); float strength = lmap( d, dMin, dMax, sMax, sMin ); mEffectCharge.updateCursor( id, fingertip.x, fingertip.y, strength ); } } } // erase disappeared fingers int64_t disappearThr = mFingerDisapperanceThreshold * 1000000; for ( auto it = mActiveFingers.begin(); it != mActiveFingers.end(); ) { int32_t id = it->first; if ( find( currentFingersIds.begin(), currentFingersIds.end(), id ) == currentFingersIds.end() ) { // seen earlier than the threshold? if ( mTimestamp - it->second > disappearThr ) { mEffectCharge.removeCursor( id ); it = mActiveFingers.erase( it ); } else { it++; } } else { it++; } } }
// Output for-loop as: // ... // start = startexpr // goto loop // loop: // variable = phi [start, loopheader], [nextvariable, loopend] // ... // bodyexpr // ... // loopend: // step = stepexpr // nextvariable = variable + step // endcond = endexpr // br endcond, loop, endloop // outloop: Value *ForExprAST::codegen() { // Emit the start code first, without 'variable' in scope. Value *StartVal = Start->codegen(); if (!StartVal) return nullptr; // Make the new basic block for the loop header, inserting after current // block. Function *TheFunction = Builder.GetInsertBlock()->getParent(); BasicBlock *PreheaderBB = Builder.GetInsertBlock(); BasicBlock *LoopBB = BasicBlock::Create(getGlobalContext(), "loop", TheFunction); // Insert an explicit fall through from the current block to the LoopBB. Builder.CreateBr(LoopBB); // Start insertion in LoopBB. Builder.SetInsertPoint(LoopBB); // Start the PHI node with an entry for Start. PHINode *Variable = Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2, VarName.c_str()); Variable->addIncoming(StartVal, PreheaderBB); // Within the loop, the variable is defined equal to the PHI node. If it // shadows an existing variable, we have to restore it, so save it now. Value *OldVal = NamedValues[VarName]; NamedValues[VarName] = Variable; // Emit the body of the loop. This, like any other expr, can change the // current BB. Note that we ignore the value computed by the body, but don't // allow an error. if (!Body->codegen()) return nullptr; // Emit the step value. Value *StepVal = nullptr; if (Step) { StepVal = Step->codegen(); if (!StepVal) return nullptr; } else { // If not specified, use 1.0. StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0)); } Value *NextVar = Builder.CreateFAdd(Variable, StepVal, "nextvar"); // Compute the end condition. Value *EndCond = End->codegen(); if (!EndCond) return nullptr; // Convert condition to a bool by comparing equal to 0.0. EndCond = Builder.CreateFCmpONE( EndCond, ConstantFP::get(getGlobalContext(), APFloat(0.0)), "loopcond"); // Create the "after loop" block and insert it. BasicBlock *LoopEndBB = Builder.GetInsertBlock(); BasicBlock *AfterBB = BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction); // Insert the conditional branch into the end of LoopEndBB. Builder.CreateCondBr(EndCond, LoopBB, AfterBB); // Any new code will be inserted in AfterBB. Builder.SetInsertPoint(AfterBB); // Add a new entry to the PHI node for the backedge. Variable->addIncoming(NextVar, LoopEndBB); // Restore the unshadowed variable. if (OldVal) NamedValues[VarName] = OldVal; else NamedValues.erase(VarName); // for expr always returns 0.0. return Constant::getNullValue(Type::getDoubleTy(getGlobalContext())); }
void GetPostManageFunction() { // GET / POST requests code curlHandleCount = 0; CURLMcode code = CURLM_CALL_MULTI_PERFORM; while (code == CURLM_CALL_MULTI_PERFORM) { code = curl_multi_perform(curlMulti, &curlHandleCount); /////////////////////////DEV ONLY///////////////////////// //if (code !=0) //{ // //requestQueue.front()->Error[1023] = '\0'; // printf("Perform: %d %d!!!\n", code, curlHandleCount); // //printf("%s\n", requestQueue.front()->Error); //} //if (curlHandleCount !=0) //{ // requestQueue.front()->Error[1023] = '\0'; // printf("Perform: %d %d!!!\n", code, curlHandleCount); // printf("%s\n", requestQueue.front()->Error); //} /////////////////////////DEV ONLY///////////////////////// } if ( code != CURLM_OK && curlHandleCount != 0) { printf("Error: Something happend in perform GET/POST: %d!!!\n", code); //// what after error???????? } CURLMsg *msg; // for picking up messages with the transfer status int msgsLeft; // how many messages are left std::list<InfoResultStruct> handlesInfoResult; while ( (msg = curl_multi_info_read(curlMulti, &msgsLeft)) ) { if (msg->msg == CURLMSG_DONE) { std::map<CURL *, CRequest *>::iterator f = requestMap.find(msg->easy_handle); f->second->SetStatusWaitingForDone(); InfoResultStruct d = { msg->easy_handle, msg->data.result }; handlesInfoResult.push_back(d); } if (msgsLeft == 0) break; } { std::list<InfoResultStruct>::iterator e = handlesInfoResult.end(); std::list<InfoResultStruct>::iterator i = handlesInfoResult.begin(); for ( ; i != e; i++ ) { CURLcode result = i->result; CURL *handle = i->handle; std::map<CURL *, CRequest *>::iterator e = requestMap.end(); std::map<CURL *, CRequest *>::iterator f = requestMap.find(handle); if ( f == e ) { printf("REQUEST NOT FOUND FOR HANDLE %p\n", handle); continue; } CRequest *foundRequest = f->second; curl_multi_remove_handle(curlMulti, handle); DecrementRequestCount(foundRequest->GetMethodHttp()); if (foundRequest->GetIsPostPush()) { foundRequest->SetSuccessError(ErrorConnectionEndedByServer); foundRequest->SetStatusDone(); } else { if ( result != CURLE_OK ) { foundRequest->SetError(ErrorUndefineResultDone, result, curl_easy_strerror(result)); foundRequest->SetStatusDone(); } else { foundRequest->SetSuccess(); foundRequest->SetStatusDone(); } } requestMap.erase(f); requestQueue.remove(foundRequest); delete foundRequest; } } std::list<CRequest *>::iterator e = requestQueue.end(); std::list<CRequest *>::iterator i = requestQueue.begin(); // start requests which are ready GET / POST for ( ; i != e; i++ ) { // remove canceled request if ( i != e && (*i)->GetRequestStatus() == RSCancel ) { curl_multi_remove_handle(curlMulti, (*i)->GetCurl()); std::map<CURL *, CRequest *>::iterator f = requestMap.find((*i)->GetCurl()); if (f != requestMap.end()) { requestMap.erase(f); } CRequest *toRemove = (*i); DecrementRequestCount((*i)->GetMethodHttp()); i = requestQueue.erase(i); delete toRemove; if (i == e) break; } if ( i != e && (*i)->GetRequestStatus() == RSReady ) { bool shouldBeHandled = true; if ( (*i)->GetMethodHttp() == MethodGet && g_actualGetRequestsCount >= MAX_GET_REQUESTS) { shouldBeHandled = false; } if ( (*i)->GetMethodHttp() == MethodPost && g_actualPostRequestsCount >= MAX_POST_REQUESTS) { shouldBeHandled = false; } if (shouldBeHandled) { CURL *handle = (*i)->GetCurl(); CURLMcode codem; codem = curl_multi_add_handle(curlMulti, handle); if (codem != CURLM_OK) { printf("Error: Something wrong with adding handle\n"); (*i)->SendErrorByCallback(ErrorMultiAddHandleProblem, codem); continue; } requestMap[handle] = *i; (*i)->SetStatusWorking(); IncrementRequestCount((*i)->GetMethodHttp()); } } } }
void log_deregister_thread() { threadid_t id = get_current_thread_id(); log_threadnames.erase(id); }
int callback_eqemu(libwebsocket_context *context, libwebsocket *wsi, libwebsocket_callback_reasons reason, void *user, void *in, size_t len) { per_session_data_eqemu *session = (per_session_data_eqemu*)user; switch (reason) { case LWS_CALLBACK_ESTABLISHED: session->uuid = CreateUUID(); session->send_queue = new std::list<std::string>(); sessions[session->uuid] = session; break; case LWS_CALLBACK_RECEIVE: { //recv and parse commands here if(len < 1) break; rapidjson::Document document; if(document.Parse((const char*)in).HasParseError()) { WriteWebCallResponseString(session, document, "Malformed JSON data", true, true); break; } std::string method; if(document.HasMember("method") && !document["method"].Empty() && document["method"].IsString()) { method = document["method"].GetString(); } if(method.length() == 0) { //No function called, toss this message WriteWebCallResponseString(session, document, "No method specified", true); break; } int status = CheckTokenAuthorization(session); if (status == 0) { //check func call against functions that dont req auth if (unauthorized_methods.count(method) == 0) { WriteWebCallResponseString(session, document, "No suitable method found: " + method, true); break; } auto call_func = unauthorized_methods[method]; call_func(session, document, method); } else if(status > 0) { //check func call against functions that req auth if (authorized_methods.count(method) == 0) { WriteWebCallResponseString(session, document, "No suitable method found: " + method, true); break; } //check status level auto iter = authorized_methods.find(method); if(iter->second.first > status) { WriteWebCallResponseString(session, document, "Method " + method + " requires status " + std::to_string((long)iter->second.first), true); break; } auto call_func = iter->second.second; call_func(session, document, method); } break; } case LWS_CALLBACK_SERVER_WRITEABLE: { std::vector<char> out_message; for (auto iter = session->send_queue->begin(); iter != session->send_queue->end(); ++iter) { out_message.resize((*iter).size() + LWS_SEND_BUFFER_PRE_PADDING + LWS_SEND_BUFFER_POST_PADDING + 1); memset(&out_message[0], 0, (*iter).size() + LWS_SEND_BUFFER_PRE_PADDING + LWS_SEND_BUFFER_POST_PADDING + 1); memcpy(&out_message[LWS_SEND_BUFFER_PRE_PADDING], &(*iter)[0], (*iter).size()); int n = libwebsocket_write(wsi, (unsigned char*)&out_message[LWS_SEND_BUFFER_PRE_PADDING], (*iter).size(), LWS_WRITE_TEXT); if(n < (*iter).size()) { return -1; } } session->send_queue->clear(); break; } case LWS_CALLBACK_PROTOCOL_DESTROY: //clean up sessions here safe_delete(session->send_queue); break; case LWS_CALLBACK_CLOSED: //Session closed but perhaps not yet destroyed, we still don't want to track it though. sessions.erase(session->uuid); safe_delete(session->send_queue); session->uuid.clear(); break; default: break; }; return 0; }
// delete clusters with no members, merge clusters that are close bool Segment::merge(std::map<int, std::vector<int> > &clusterMembers, std::vector<int> &indices, int &clusters) { if (DEBUG) { printf("Merging clusters...\n"); } int origClusters = clusters; std::vector<int> mergeTo(indices.size()); std::vector<int> bestMerge(indices.size()); std::vector<float> bestScore(indices.size()); for(unsigned int i=0; i<indices.size(); ++i) { mergeTo[i] = i; bestMerge[i] = -1; bestScore[i] = 1; } std::map<int, std::vector<int> >::iterator i, j; for(i=clusterMembers.begin(); i!=clusterMembers.end(); ++i) { if (i->second.size() == 0) { continue; } int curMerge = i->first; float minDist = 1; for(j=clusterMembers.begin(); j!=clusterMembers.end(); ++j) { if (i==j || j->second.size() == 0) { continue; } float curDist = distance(visibilityVectors[indices[i->first]], visibilityVectors[indices[j->first]]); if (curDist < minDist) { minDist = curDist; curMerge = j->first; //i->second.insert(i->second.end(), j->second.begin(), j->second.end()); //j->second.clear(); } } bestMerge[i->first] = curMerge; bestScore[i->first] = minDist; } for(unsigned int k=0; k<bestMerge.size(); ++k) { // prevents merging into self if (mergeTo[bestMerge[k]] == k) { continue; } // 2 clusters that want to merge into each other if (bestMerge[k] == bestMerge[bestMerge[k]]) { if (k < bestMerge[k]) { continue; } clusterMembers[mergeTo[bestMerge[k]]].insert(clusterMembers[mergeTo[bestMerge[k]]].end(), clusterMembers[k].begin(), clusterMembers[k].end()); clusterMembers[k].clear(); mergeTo[k] = mergeTo[bestMerge[k]]; } else if (bestScore[k] < MERGE_THRESH) { clusterMembers[mergeTo[bestMerge[k]]].insert(clusterMembers[mergeTo[bestMerge[k]]].end(), clusterMembers[k].begin(), clusterMembers[k].end()); clusterMembers[k].clear(); mergeTo[k] = mergeTo[bestMerge[k]]; } } for(unsigned int k=0; k<indices.size(); ++k) { if (clusterMembers.count(k) > 0 && clusterMembers[k].size() == 0) { clusters -= clusterMembers.erase(k); indices[k] = -1; } } return origClusters != clusters; }
int fn_2D_by_2D_args_2D_count(MContext *mc, DNode *form, const char *prefix) { dale::Units *units = (dale::Units*) mc->units; Node *n = units->top()->dnc->toNode(form); if (!units->top()->ctx->er->assertArgNums("fn-by-args-count", n, 0, -1)) { return 0; } int error_count_begin = units->top()->ctx->er->getErrorTypeCount(ErrorType::Error); std::vector<Node *> *lst = n->list; std::vector<Node *>::iterator iter = lst->begin(); std::string map_key; std::vector<Type *> parameter_types; while (iter != lst->end()) { Type *parameter_type = FormTypeParse(units, (*iter), false, false); if (!parameter_type) { units->top()->ctx->er->popErrors(error_count_begin); return 0; } parameter_type->toString(&map_key); parameter_types.push_back(parameter_type); ++iter; } std::map<std::string, std::vector<std::string>*>::iterator b = fn_by_args.find(map_key), e = fn_by_args.end(); if (b != e) { std::vector<std::string>* fn_by_args_list = b->second; delete fn_by_args_list; fn_by_args.erase(b); } /* For each function that exists, see if it has an instance * for the provided parameter types. */ std::set<std::string> function_names; bool has_prefix = prefix; if (!prefix) { prefix = ""; } std::string ss_prefix(prefix); units->top()->ctx->getFunctionNames(&function_names, (has_prefix ? &ss_prefix : NULL)); std::vector<std::string> *fn_by_args_list = new std::vector<std::string>; for (std::set<std::string>::iterator b = function_names.begin(), e = function_names.end(); b != e; ++b) { Function *fn = units->top()->ctx->getFunction(b->c_str(), ¶meter_types, NULL, NULL, 0); if (fn && !fn->is_macro) { fn_by_args_list->push_back(*b); } } fn_by_args.insert( std::pair<std::string, std::vector<std::string>*>( map_key, fn_by_args_list ) ); return (int) fn_by_args_list->size(); }
AlembicObjectNode::~AlembicObjectNode() { gNodes.erase(gNodes.find(mRefId)); }
void OffloadDescriptor::scatter_copyin_data() { OFFLOAD_TIMER_START(c_offload_target_scatter_inputs); OFFLOAD_DEBUG_TRACE(2, "IN buffer @ %p size %lld\n", m_in.get_buffer_start(), m_in.get_buffer_size()); OFFLOAD_DEBUG_DUMP_BYTES(2, m_in.get_buffer_start(), m_in.get_buffer_size()); // receive data for (int i = 0; i < m_vars_total; i++) { bool src_is_for_mic = (m_vars[i].direction.out || m_vars[i].into == NULL); void** ptr_addr = src_is_for_mic ? static_cast<void**>(m_vars[i].ptr) : static_cast<void**>(m_vars[i].into); int type = src_is_for_mic ? m_vars[i].type.src : m_vars[i].type.dst; bool is_static = src_is_for_mic ? m_vars[i].flags.is_static : m_vars[i].flags.is_static_dstn; void *ptr = NULL; if (m_vars[i].flags.alloc_disp) { int64_t offset = 0; m_in.receive_data(&offset, sizeof(offset)); m_vars[i].offset = -offset; } if (VAR_TYPE_IS_DV_DATA_SLICE(type) || VAR_TYPE_IS_DV_DATA(type)) { ArrDesc *dvp = (type == c_dv_data_slice || type == c_dv_data)? reinterpret_cast<ArrDesc*>(ptr_addr) : *reinterpret_cast<ArrDesc**>(ptr_addr); ptr_addr = reinterpret_cast<void**>(&dvp->Base); } // Set pointer values switch (type) { case c_data_ptr_array: { int j = m_vars[i].ptr_arr_offset; int max_el = j + m_vars[i].count; char *dst_arr_ptr = (src_is_for_mic)? *(reinterpret_cast<char**>(m_vars[i].ptr)) : reinterpret_cast<char*>(m_vars[i].into); for (; j < max_el; j++) { if (src_is_for_mic) { m_vars[j].ptr = dst_arr_ptr + m_vars[j].ptr_arr_offset; } else { m_vars[j].into = dst_arr_ptr + m_vars[j].ptr_arr_offset; } } } break; case c_data: case c_void_ptr: case c_cean_var: case c_dv: break; case c_string_ptr: case c_data_ptr: case c_cean_var_ptr: case c_dv_ptr: if (m_vars[i].alloc_if) { void *buf; if (m_vars[i].flags.sink_addr) { m_in.receive_data(&buf, sizeof(buf)); } else { buf = m_buffers.front(); m_buffers.pop_front(); } if (buf) { if (!is_static) { if (!m_vars[i].flags.sink_addr) { // increment buffer reference OFFLOAD_TIMER_START(c_offload_target_add_buffer_refs); BufferAddRef(buf); OFFLOAD_TIMER_STOP(c_offload_target_add_buffer_refs); } add_ref_count(buf, 0 == m_vars[i].flags.sink_addr); } ptr = static_cast<char*>(buf) + m_vars[i].mic_offset + (m_vars[i].flags.is_stack_buf ? 0 : m_vars[i].offset); } *ptr_addr = ptr; } else if (m_vars[i].flags.sink_addr) { void *buf; m_in.receive_data(&buf, sizeof(buf)); void *ptr = static_cast<char*>(buf) + m_vars[i].mic_offset + (m_vars[i].flags.is_stack_buf ? 0 : m_vars[i].offset); *ptr_addr = ptr; } break; case c_func_ptr: break; case c_dv_data: case c_dv_ptr_data: case c_dv_data_slice: case c_dv_ptr_data_slice: if (m_vars[i].alloc_if) { void *buf; if (m_vars[i].flags.sink_addr) { m_in.receive_data(&buf, sizeof(buf)); } else { buf = m_buffers.front(); m_buffers.pop_front(); } if (buf) { if (!is_static) { if (!m_vars[i].flags.sink_addr) { // increment buffer reference OFFLOAD_TIMER_START(c_offload_target_add_buffer_refs); BufferAddRef(buf); OFFLOAD_TIMER_STOP(c_offload_target_add_buffer_refs); } add_ref_count(buf, 0 == m_vars[i].flags.sink_addr); } ptr = static_cast<char*>(buf) + m_vars[i].mic_offset + m_vars[i].offset; } *ptr_addr = ptr; } else if (m_vars[i].flags.sink_addr) { void *buf; m_in.receive_data(&buf, sizeof(buf)); ptr = static_cast<char*>(buf) + m_vars[i].mic_offset + m_vars[i].offset; *ptr_addr = ptr; } break; default: LIBOFFLOAD_ERROR(c_unknown_var_type, type); abort(); } // Release obsolete buffers for stack of persistent objects if (type = c_data_ptr && m_vars[i].flags.is_stack_buf && !m_vars[i].direction.bits && m_vars[i].alloc_if && m_vars[i].size != 0) { for (int j=0; j < m_vars[i].size; j++) { void *buf; m_in.receive_data(&buf, sizeof(buf)); BufferReleaseRef(buf); ref_data.erase(buf); } } // Do copyin switch (m_vars[i].type.dst) { case c_data_ptr_array: break; case c_data: case c_void_ptr: case c_cean_var: if (m_vars[i].direction.in && !m_vars[i].flags.is_static_dstn) { int64_t size; int64_t disp; char* ptr = m_vars[i].into ? static_cast<char*>(m_vars[i].into) : static_cast<char*>(m_vars[i].ptr); if (m_vars[i].type.dst == c_cean_var) { m_in.receive_data((&size), sizeof(int64_t)); m_in.receive_data((&disp), sizeof(int64_t)); } else { size = m_vars[i].size; disp = 0; } m_in.receive_data(ptr + disp, size); } break; case c_dv: if (m_vars[i].direction.bits || m_vars[i].alloc_if || m_vars[i].free_if) { char* ptr = m_vars[i].into ? static_cast<char*>(m_vars[i].into) : static_cast<char*>(m_vars[i].ptr); m_in.receive_data(ptr + sizeof(uint64_t), m_vars[i].size - sizeof(uint64_t)); } break; case c_string_ptr: case c_data_ptr: case c_cean_var_ptr: case c_dv_ptr: case c_dv_data: case c_dv_ptr_data: case c_dv_data_slice: case c_dv_ptr_data_slice: break; case c_func_ptr: if (m_vars[i].direction.in) { m_in.receive_func_ptr((const void**) m_vars[i].ptr); } break; default: LIBOFFLOAD_ERROR(c_unknown_var_type, m_vars[i].type.dst); abort(); } } OFFLOAD_TRACE(1, "Total copyin data received from host: [%lld] bytes\n", m_in.get_tfr_size()); OFFLOAD_TIMER_STOP(c_offload_target_scatter_inputs); OFFLOAD_TIMER_START(c_offload_target_compute); }
AlembicObjectDeformNode::~AlembicObjectDeformNode() { gDeformNodes.erase(gDeformNodes.find(mRefId)); }
LRESULT CALLBACK sdl_window::CustomWindowProc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam) { auto mapEntry = sHandleMap.find(sHandleMap[hwnd]->iNativeHandle); auto wndproc = mapEntry->second->iSDLWindowProc; LRESULT result; switch(msg) { case WM_SYSCHAR: result = CallWindowProc(wndproc, hwnd, msg, wparam, lparam); { std::string buffer; buffer.resize(5); if (WIN_ConvertUTF32toUTF8((UINT32)wparam, &buffer[0])) { std::string text = buffer.c_str(); if (!app::instance().keyboard().grabber().sys_text_input(text)) { mapEntry->second->event_handler().native_window_sys_text_input(text); } } } break; case WM_LBUTTONDOWN: case WM_RBUTTONDOWN: case WM_MBUTTONDOWN: case WM_XBUTTONDOWN: case WM_LBUTTONDBLCLK: case WM_RBUTTONDBLCLK: case WM_MBUTTONDBLCLK: case WM_XBUTTONDBLCLK: { key_modifiers_e modifiers = KeyModifier_NONE; if (wparam & MK_SHIFT) modifiers = static_cast<key_modifiers_e>(modifiers | KeyModifier_SHIFT); if (wparam & MK_CONTROL) modifiers = static_cast<key_modifiers_e>(modifiers | KeyModifier_CTRL); mapEntry->second->push_mouse_button_event_extra_info(modifiers); result = CallWindowProc(wndproc, hwnd, msg, wparam, lparam); } break; case WM_NCLBUTTONDOWN: case WM_NCRBUTTONDOWN: case WM_NCMBUTTONDOWN: mapEntry->second->event_handler().native_window_dismiss_children(); // call this before default wndproc (which enters its own NC drag message loop) result = CallWindowProc(wndproc, hwnd, msg, wparam, lparam); break; case WM_DESTROY: { mapEntry->second->destroying(); result = CallWindowProc(wndproc, hwnd, msg, wparam, lparam); } break; case WM_NCDESTROY: { mapEntry->second->destroyed(); sHandleMap.erase(mapEntry); result = CallWindowProc(wndproc, hwnd, msg, wparam, lparam); } break; case WM_MOUSEACTIVATE: if (GetWindowLongPtr(hwnd, GWL_EXSTYLE) & WS_EX_NOACTIVATE) result = MA_NOACTIVATE; else result = CallWindowProc(wndproc, hwnd, msg, wparam, lparam); break; default: result = CallWindowProc(wndproc, hwnd, msg, wparam, lparam); break; } return result; }
void closeInputTempFile(uint64_t id) { libmaus2::parallel::ScopeLock slock(lock); if ( instreams.find(id) != instreams.end() ) instreams.erase(instreams.find(id)); }
void NodeHelper::remove(Contactable& contactable) { NodeItem item = name_cache[&contactable]; name_cache.erase(&contactable); by_part_name.erase(item.nc.getNestedName()); by_category.erase(item.nc.getCategory()); }
/*------------------------------------------------------------------------------ FUNCTION: CheckServerRequest DESIGNER/PROGRAMMER: Jerry Jia, Martin Minkov, Scott Plummer, Dylan Blake REVISIONS: INTERFACE: void ServerTCP::CheckServerRequest(Player player, char * buffer) RETURNS: void NOTES: -------------------------------------------------------------------------------*/ void ServerTCP::CheckServerRequest(Player player, char * buffer) { std::string error; Json json = Json::parse(buffer, error).array_items()[0]; if (json["DataType"].int_value() != Networking) { this->ServerTCP::Broadcast(buffer); return; } switch(json["ID"].int_value()) { //Player joining team request case TeamChangeRequest: std::cout << "Team change: " << json[TeamID].int_value() << std::endl; _PlayerTable[player.id].team = json[TeamID].int_value(); this->ServerTCP::Broadcast(buffer); break; //Player joining class request case ClassChangeRequest: std::cout << "Class change: " << json[ClassID].int_value() << std::endl; _PlayerTable [player.id].playerClass = json[ClassID].int_value(); this->ServerTCP::Broadcast(buffer); break; //Player making a ready request case ReadyRequest: std::cout << "Ready change: " << (json[Ready].int_value() ? "ready" : "not ready") << std::endl; _PlayerTable[player.id].isReady = (json[Ready].int_value() ? true : false); this->ServerTCP::Broadcast(buffer); break; //New Player has joined lobby case PlayerJoinedLobby: std::cout << "New Player Change: " << json[UserName].string_value() << std::endl; strcpy(_PlayerTable[player.id].username, json[UserName].string_value().c_str()); //Send player a table of players sendToClient(player, constructPlayerTable().c_str()); //Create packet and send to everyone this->ServerTCP::Broadcast(UpdateID(_PlayerTable[player.id]).c_str()); break; case PlayerLeftLobby: std::cout << "Player: " << json[PlayerID].int_value() << " has left the lobby" << std::endl; _PlayerTable.erase(json[PlayerID].int_value()); this->ServerTCP::Broadcast(buffer); break; case GameStart: std::cout << "Player: " << json[PlayerID].int_value() << " has started the game" << std::endl; //All players in lobby are ready if (this->ServerTCP::AllPlayersReady()) { this->ServerTCP::Broadcast(buffer); this->ServerTCP::Broadcast(generateMapSeed().c_str()); } break; case GameEnd: //Currently allows any player to annouce the end of the game. std::cout << "Player: " << json[PlayerID].int_value() << " has ended the game" << std::endl; close(_UDPReceivingSocket); gameRunning = false; break; default: this->ServerTCP::Broadcast(buffer); break; } }
client::Vizualizer::~Vizualizer() { //TODO : find out how ot destroy vizualizer object while programm is running //now access exception occurs objs.erase(this->index); }
virtual void ResetMoveAnimation(std::string name) { std::map<std::string, std::string>::const_iterator it = m_AnimOverride.find(name); if (it != m_AnimOverride.end()) m_AnimOverride.erase(name); }
void UpdateAI(const uint32 diff) { if (!UpdateCombatState()) return; events.Update(diff); if (Phase == 1) { while (uint32 eventId = events.GetEvent()) { switch(eventId) { case EVENT_WASTE: DoSummon(NPC_WASTE, Pos[RAND(0,3,6,9)]); events.RepeatEvent(urand(2000,5000)); break; case EVENT_ABOMIN: if (nAbomination < 8) { DoSummon(NPC_ABOMINATION, Pos[RAND(1,4,7,10)]); nAbomination++; events.RepeatEvent(20000); } else events.PopEvent(); break; case EVENT_WEAVER: if (nWeaver < 8) { DoSummon(NPC_WEAVER, Pos[RAND(0,3,6,9)]); nWeaver++; events.RepeatEvent(25000); } else events.PopEvent(); break; case EVENT_TRIGGER: if (GameObject *pKTTrigger = me->GetMap()->GetGameObject(KTTriggerGUID)) pKTTrigger->SetPhaseMask(2, true); events.PopEvent(); break; case EVENT_PHASE: events.Reset(); DoScriptText(RAND(SAY_AGGRO_1,SAY_AGGRO_2,SAY_AGGRO_3), me); spawns.DespawnAll(); me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_DISABLE_MOVE | UNIT_FLAG_NOT_SELECTABLE); me->CastStop(); DoStartMovement(me->getVictim()); events.ScheduleEvent(EVENT_BOLT, urand(5000,10000)); events.ScheduleEvent(EVENT_NOVA, 15000); events.ScheduleEvent(EVENT_DETONATE, urand(30000,40000)); events.ScheduleEvent(EVENT_FISSURE, urand(10000,30000)); events.ScheduleEvent(EVENT_BLAST, urand(60000,120000)); if (getDifficulty() == RAID_DIFFICULTY_25MAN_NORMAL) events.ScheduleEvent(EVENT_CHAIN, urand(30000,60000)); Phase = 2; break; default: events.PopEvent(); break; } } } else { //start phase 3 when we are 45% health if (Phase != 3) { if (HealthBelowPct(45)) { Phase = 3 ; DoScriptText(SAY_REQUEST_AID, me); //here Lich King should respond to KelThuzad but I don't know which Creature to make talk //so for now just make Kelthuzad says it. DoScriptText(SAY_ANSWER_REQUEST, me); for (uint8 i = 0; i <= 3; ++i) { if (GameObject *pPortal = me->GetMap()->GetGameObject(PortalsGUID[i])) { if (pPortal->getLootState() == GO_READY) pPortal->UseDoorOrButton(); } } } } else if (nGuardiansOfIcecrownCount < RAID_MODE(2,4)) { if (uiGuardiansOfIcecrownTimer <= diff) { // TODO : Add missing text if (Creature* pGuardian = DoSummon(NPC_ICECROWN, Pos[RAND(2,5,8,11)])) pGuardian->SetFloatValue(UNIT_FIELD_COMBATREACH, 2); ++nGuardiansOfIcecrownCount; uiGuardiansOfIcecrownTimer = 5000; } else uiGuardiansOfIcecrownTimer -= diff; } if (me->hasUnitState(UNIT_STAT_CASTING)) return; if (uint32 eventId = events.GetEvent()) { switch(eventId) { case EVENT_BOLT: DoCastVictim(RAID_MODE(SPELL_FROST_BOLT,H_SPELL_FROST_BOLT)); events.RepeatEvent(urand(5000,10000)); break; case EVENT_NOVA: DoCastAOE(RAID_MODE(SPELL_FROST_BOLT_AOE,H_SPELL_FROST_BOLT_AOE)); events.RepeatEvent(urand(15000,30000)); break; case EVENT_CHAIN: { uint32 count = urand(1,3); for (uint8 i = 1; i <= count; i++) { Unit *pTarget = SelectTarget(SELECT_TARGET_RANDOM, 1, 200, true); if (pTarget && !pTarget->isCharmed() && (chained.find(pTarget->GetGUID()) == chained.end())) { DoCast(pTarget, SPELL_CHAINS_OF_KELTHUZAD); float scale = pTarget->GetFloatValue(OBJECT_FIELD_SCALE_X); chained.insert(std::make_pair(pTarget->GetGUID(), scale)); pTarget->SetFloatValue(OBJECT_FIELD_SCALE_X, scale * 2); events.ScheduleEvent(EVENT_CHAINED_SPELL, 2000); //core has 2000ms to set unit flag charm } } if (!chained.empty()) DoScriptText(RAND(SAY_CHAIN_1,SAY_CHAIN_2), me); events.RepeatEvent(urand(100000,180000)); break; } case EVENT_CHAINED_SPELL: { std::map<uint64, float>::iterator itr; for (itr = chained.begin(); itr != chained.end();) { if (Unit* player = Unit::GetPlayer((*itr).first)) { if (!player->isCharmed()) { player->SetFloatValue(OBJECT_FIELD_SCALE_X, (*itr).second); std::map<uint64, float>::iterator next = itr; ++next; chained.erase(itr); itr = next; continue; } if (Unit *pTarget = SelectTarget(SELECT_TARGET_TOPAGGRO, 0, NotCharmedTargetSelector())) { switch(player->getClass()) { case CLASS_DRUID: if (urand(0,1)) player->CastSpell(pTarget, SPELL_MOONFIRE, false); else player->CastSpell(me, SPELL_LIFEBLOOM, false); break; case CLASS_HUNTER: player->CastSpell(pTarget, RAND(SPELL_MULTI_SHOT, SPELL_VOLLEY), false); break; case CLASS_MAGE: player->CastSpell(pTarget, RAND(SPELL_FROST_FIREBOLT, SPELL_ARCANE_MISSILES), false); break; case CLASS_WARLOCK: player->CastSpell(pTarget, RAND(SPELL_CURSE_OF_AGONY, SPELL_SHADOW_BOLT), true); break; case CLASS_WARRIOR: player->CastSpell(pTarget, RAND(SPELL_BLADESTORM, SPELL_CLEAVE), false); break; case CLASS_PALADIN: if (urand(0,1)) player->CastSpell(pTarget, SPELL_HAMMER_OF_JUSTICE, false); else player->CastSpell(me, SPELL_HOLY_SHOCK, false); break; case CLASS_PRIEST: if (urand(0,1)) player->CastSpell(pTarget, SPELL_VAMPIRIC_TOUCH, false); else player->CastSpell(me, SPELL_RENEW, false); break; case CLASS_SHAMAN: if (urand(0,1)) player->CastSpell(pTarget, SPELL_EARTH_SHOCK, false); else player->CastSpell(me, SPELL_HEALING_WAVE, false); break; case CLASS_ROGUE: player->CastSpell(pTarget, RAND(SPELL_HEMORRHAGE, SPELL_MUTILATE), false); break; case CLASS_DEATH_KNIGHT: if (urand(0,1)) player->CastSpell(pTarget, SPELL_PLAGUE_STRIKE, true); else player->CastSpell(pTarget, SPELL_HOWLING_BLAST, true); break; } } } ++itr; } if (chained.empty()) events.PopEvent(); else events.RepeatEvent(5000); break; } case EVENT_DETONATE: { std::vector<Unit*> unitList; std::list<HostileReference*> *threatList = &me->getThreatManager().getThreatList(); for (std::list<HostileReference*>::const_iterator itr = threatList->begin(); itr != threatList->end(); ++itr) { if ((*itr)->getTarget()->GetTypeId() == TYPEID_PLAYER && (*itr)->getTarget()->getPowerType() == POWER_MANA && (*itr)->getTarget()->GetPower(POWER_MANA)) unitList.push_back((*itr)->getTarget()); } if (!unitList.empty()) { std::vector<Unit*>::const_iterator itr = unitList.begin(); advance(itr, rand()%unitList.size()); DoCast(*itr, SPELL_MANA_DETONATION); DoScriptText(RAND(SAY_SPECIAL_1,SAY_SPECIAL_2,SAY_SPECIAL_3), me); } events.RepeatEvent(urand(20000,50000)); break; } case EVENT_FISSURE: if (Unit *pTarget = SelectUnit(SELECT_TARGET_RANDOM,0)) DoCast(pTarget, SPELL_SHADOW_FISURE); events.RepeatEvent(urand(10000,45000)); break; case EVENT_BLAST: if (Unit *pTarget = SelectTarget(SELECT_TARGET_RANDOM, RAID_MODE(1,0), 0, true)) DoCast(pTarget, SPELL_FROST_BLAST); if (rand()%2) DoScriptText(SAY_FROST_BLAST, me); events.RepeatEvent(urand(30000,90000)); break; default: events.PopEvent(); break; } } DoMeleeAttackIfReady(); } }
int main(int argc, char** argv) { int option; while ((option = getopt(argc, argv, "zcsm:w:l:f:t:i:o:d:")) != -1) { switch(option) { case 'z': useZeroCopy = true; break; case 'c': isClient = true; break; case 's': isServer = true; break; case 'l': pcntLossOk = atof((const char*)optarg); break; case 't': if (strncasecmp(optarg, "tcp", 3) == 0) { type = PUB_TCP; } else if (strncasecmp(optarg, "mcast", 5) == 0) { type = PUB_MCAST; } else if (strncasecmp(optarg, "rtp", 3) == 0) { type = PUB_RTP; } break; case 'm': mtu = displayToBytes(optarg); break; case 'f': fixedBytesPerSecond = displayToBytes(optarg); break; case 'd': duration = atoi((const char*)optarg); break; case 'o': filePrefix = optarg; break; case 'w': waitForSubs = atoi((const char*)optarg); break; case 'i': reportInterval = atoi((const char*)optarg); break; default: printUsageAndExit(); break; } } if (!isClient && !isServer) printUsageAndExit(); if (fixedBytesPerSecond > 0) bytesPerSecond = fixedBytesPerSecond; DiscoveryConfigMDNS discConfig; // discConfig.setDomain("throughput"); disc = Discovery(&discConfig); Subscriber sub("reports"); ReportReceiver reportRecv; sub.setReceiver(&reportRecv); node.addSubscriber(sub); if (isServer) { runAsServer(); } else { runAsClient(); } if (filePrefix.size() > 0) { // wait for missing reports, then make sure no more reports are coming in Thread::sleepMs(20000); sub.setReceiver(NULL); // write files std::map<std::string, std::list<Report> >::iterator reportIter = allReports.begin(); std::map<std::string, std::ofstream*> fileHandles; // open a file per reporter and write header while(reportIter != allReports.end()) { std::string pubUUID = reportIter->first; std::string reportFileName = filePrefix + pubUUID.substr(0,8) + ".data"; fileHandles[pubUUID] = new std::ofstream(); fileHandles[pubUUID]->open(reportFileName.c_str(), std::fstream::out); Report::writeCSVHead(*fileHandles[pubUUID]); #ifdef UNIX // that's only useful if there is only a single reporter per host std::string linkFrom = filePrefix + pubUUID.substr(0,8) + ".data"; std::string linkTo = filePrefix + reportIter->second.back().hostId + ".host.data"; unlink(linkTo.c_str()); symlink(linkFrom.c_str(), linkTo.c_str()); #endif reportIter++; } // write reports std::fstream senderReport; std::string senderReportFileName = filePrefix + "sender.data"; senderReport.open(senderReportFileName.c_str(), std::fstream::out); senderReport << "\"Bytes Sent\", \"Packets sent\"" << std::endl; std::list<Report>::iterator senderRepIter = senderReports.begin(); while(senderRepIter!= senderReports.end()) { senderReport << senderRepIter->bytesRcvd << ", "; senderReport << senderRepIter->pktsRcvd << std::endl; senderRepIter++; reportIter = allReports.begin(); while(reportIter != allReports.end()) { if (reportIter->second.size() == 0) { // all data consumed - insert missing at end *fileHandles[reportIter->first] << "-" << std::endl; break; } if (reportIter->second.front().pertainingPacket > senderRepIter->pertainingPacket) { // no data for reporting period! *fileHandles[reportIter->first] << "-" << std::endl; } else { reportIter->second.front().writeCSVData(*fileHandles[reportIter->first]); reportIter->second.pop_front(); } #if 0 // discard multiple reports? while(reportIter->second.size() > 0 && reportIter->second.front().pertainingPacket < senderRepIter->pertainingPacket) { reportIter->second.pop_front(); } #endif reportIter++; } } std::map<std::string, std::ofstream*>::iterator fhIter = fileHandles.begin(); while(fhIter != fileHandles.end()) { fhIter->second->close(); delete(fhIter->second); fhIter++; } senderReport.close(); #if 0 while(true) { reportIter = allReports.begin(); size_t nextReportingEnd = 4294967295; // 2**32 - 1 std::string nextReporter; // break when we consumed all reports if (allReports.size() == 0) break; while(reportIter != allReports.end()) { // walk through the report iterators and find next report due size_t nextDueReport = reportIter->second.front().pertainingPacket; if (nextDueReport < nextReportingEnd) { nextReportingEnd = nextDueReport; nextReporter = reportIter->first; } reportIter++; } // ok, write earliest report into earlist's reports file Report& nextReport = allReports[nextReporter].front(); fileHandles[nextReporter] << nextReport.discoveryTime << ", "; fileHandles[nextReporter] << nextReport.bytesRcvd << ", "; fileHandles[nextReporter] << nextReport.pktsRcvd << ", "; fileHandles[nextReporter] << nextReport.pktsLate << ", "; fileHandles[nextReporter] << nextReport.roundTripTime << ", "; fileHandles[nextReporter] << nextReport.pcntLoss << ", "; fileHandles[nextReporter] << nextReport.pktsDropped << ", "; fileHandles[nextReporter] << nextReport.hostName << std::endl; allReports[nextReporter].pop_front(); if (allReports[nextReporter].size() == 0) { allReports.erase(nextReporter); } else { // fill with newlines if we skipped reports Report& upcomingReport = allReports[nextReporter].front(); for(int i = 1; nextReport.reportNr + i < upcomingReport.reportNr; i++) { fileHandles[nextReporter] << std::endl; } } } std::map<std::string, std::fstream>::iterator fhIter = fileHandles.begin(); while(fhIter != fileHandles.end()) { fhIter->second.close(); fhIter++; } // write sender reports std::fstream senderReport; std::string reportFileName = filePrefix + "sender.data"; senderReport.open(reportFileName.c_str(), std::fstream::out); std::list<Report>::iterator senderRepIter = senderReports.begin(); while(senderRepIter!= senderReports.end()) { senderReport << senderRepIter->bytesRcvd << ", "; senderReport << senderRepIter->pktsRcvd << std::endl; senderRepIter++; } senderReport.close(); #endif } }
CommonHttpResponseCallBack::~CommonHttpResponseCallBack() { _httpResponses.erase(m_sUrl); CC_SAFE_RELEASE_NULL(m_pTarget); }
/* * RemoveImport * Erases a item from the import table */ void CAbstractStreaming::RemoveImport(int index) { scoped_lock xlock(this->cs); imports.erase(index); }
AlembicObjectLocatorNode::~AlembicObjectLocatorNode() { gLocatorNodes.erase(gLocatorNodes.find(mRefId)); }
void MultilevelHexahedronSetTopologyContainer::connectionToNodeAdjacency(const Vec3i& connection, std::map<unsigned int, unsigned int>& nodeMap) const { for(unsigned int i=0; i<8; ++i) nodeMap[i] = i; if(connection[0] == 1) // cube is on the right from neighbor { nodeMap.erase(1); nodeMap.erase(2); nodeMap.erase(5); nodeMap.erase(6); } else if(connection[0] == -1) // cube is on the left from neighbor { nodeMap.erase(0); nodeMap.erase(3); nodeMap.erase(4); nodeMap.erase(7); } if(connection[1] == 1) // cube is on the top from neighbor { nodeMap.erase(3); nodeMap.erase(2); nodeMap.erase(7); nodeMap.erase(6); } else if(connection[1] == -1) // cube is on the bottom from neighbor { nodeMap.erase(0); nodeMap.erase(1); nodeMap.erase(4); nodeMap.erase(5); } if(connection[2] == 1) // cube is on the front from neighbor { nodeMap.erase(4); nodeMap.erase(5); nodeMap.erase(6); nodeMap.erase(7); } else if(connection[2] == -1) // cube is on the back from neighbor { nodeMap.erase(0); nodeMap.erase(1); nodeMap.erase(2); nodeMap.erase(3); } if(nodeMap.size() == 4) // face connection { if((connection - Vec3i(1,0,0)).norm2() == 0) // cube is on the right from neighbor { nodeMap[0] = 1; nodeMap[3] = 2; nodeMap[4] = 5; nodeMap[7] = 6; } else if((connection - Vec3i(-1,0,0)).norm2() == 0) // cube is on the left from neighbor { nodeMap[1] = 0; nodeMap[2] = 3; nodeMap[5] = 4; nodeMap[6] = 7; } else if((connection - Vec3i(0,1,0)).norm2() == 0) // cube is on the top from neighbor { nodeMap[0] = 3; nodeMap[1] = 2; nodeMap[4] = 7; nodeMap[5] = 6; } else if((connection - Vec3i(0,-1,0)).norm2() == 0) // cube is on the bottom from neighbor { nodeMap[3] = 0; nodeMap[2] = 1; nodeMap[7] = 4; nodeMap[6] = 5; } else if((connection - Vec3i(0,0,1)).norm2() == 0) // cube is on the front from neighbor { nodeMap[0] = 4; nodeMap[1] = 5; nodeMap[2] = 6; nodeMap[3] = 7; } else if((connection - Vec3i(0,0,-1)).norm2() == 0) // cube is on the back from neighbor { nodeMap[4] = 0; nodeMap[5] = 1; nodeMap[6] = 2; nodeMap[7] = 3; } } else if(nodeMap.size() == 2) // edge connection { switch(nodeMap.begin()->first) { case 0: switch(nodeMap.rbegin()->first) { case 1: nodeMap[0] = 7; nodeMap[1] = 6; break; case 3: nodeMap[0] = 5; nodeMap[3] = 6; break; case 4: nodeMap[0] = 2; nodeMap[4] = 6; break; } break; case 1: switch(nodeMap.rbegin()->first) { case 2: nodeMap[1] = 4; nodeMap[2] = 7; break; case 5: nodeMap[1] = 3; nodeMap[5] = 7; break; } break; case 2: switch(nodeMap.rbegin()->first) { case 3: nodeMap[2] = 5; nodeMap[3] = 4; break; case 6: nodeMap[2] = 0; nodeMap[6] = 4; break; } break; case 3: switch(nodeMap.rbegin()->first) { case 7: nodeMap[3] = 1; nodeMap[7] = 5; break; } break; case 4: switch(nodeMap.rbegin()->first) { case 5: nodeMap[4] = 3; nodeMap[5] = 2; break; case 7: nodeMap[4] = 1; nodeMap[7] = 2; break; } break; case 5: switch(nodeMap.rbegin()->first) { case 6: nodeMap[5] = 0; nodeMap[6] = 3; break; } break; case 6: switch(nodeMap.rbegin()->first) { case 7: nodeMap[6] = 1; nodeMap[7] = 0; break; } break; } } else if(nodeMap.size() == 1) // vertex connection { switch(nodeMap.begin()->first) { case 0: nodeMap[0] = 6; break; case 1: nodeMap[1] = 7; break; case 2: nodeMap[2] = 4; break; case 3: nodeMap[3] = 5; break; case 4: nodeMap[4] = 2; break; case 5: nodeMap[5] = 3; break; case 6: nodeMap[6] = 0; break; case 7: nodeMap[7] = 1; break; } } }
void SimpleReceiverApp::setup() { mReceiver.setListener( "/mousemove/1", [&]( const osc::Message &msg ){ mCurrentCirclePos.x = msg[0].int32(); mCurrentCirclePos.y = msg[1].int32(); }); mReceiver.setListener( "/mouseclick/1", [&]( const osc::Message &msg ){ mCurrentSquarePos = vec2( msg[0].flt(), msg[1].flt() ) * vec2( getWindowSize() ); }); try { // Bind the receiver to the endpoint. This function may throw. mReceiver.bind(); } catch( const osc::Exception &ex ) { CI_LOG_E( "Error binding: " << ex.what() << " val: " << ex.value() ); quit(); } #if USE_UDP // UDP opens the socket and "listens" accepting any message from any endpoint. The listen // function takes an error handler for the underlying socket. Any errors that would // call this function are because of problems with the socket or with the remote message. mReceiver.listen( []( asio::error_code error, protocol::endpoint endpoint ) -> bool { if( error ) { CI_LOG_E( "Error Listening: " << error.message() << " val: " << error.value() << " endpoint: " << endpoint ); return false; } else return true; }); #else mReceiver.setConnectionErrorFn( // Error Function for Accepted Socket Errors. Will be called anytime there's an // error reading from a connected socket (a socket that has been accepted below). [&]( asio::error_code error, uint64_t identifier ) { if ( error ) { auto foundIt = mConnections.find( identifier ); if( foundIt != mConnections.end() ) { // EOF or end of file error isn't specifically an error. It's just that the // other side closed the connection while you were expecting to still read. if( error == asio::error::eof ) { CI_LOG_W( "Other side closed the connection: " << error.message() << " val: " << error.value() << " endpoint: " << foundIt->second.address().to_string() << " port: " << foundIt->second.port() ); } else { CI_LOG_E( "Error Reading from Socket: " << error.message() << " val: " << error.value() << " endpoint: " << foundIt->second.address().to_string() << " port: " << foundIt->second.port() ); } mConnections.erase( foundIt ); } } }); auto expectedOriginator = protocol::endpoint( asio::ip::address::from_string( "127.0.0.1" ), 10000 ); mReceiver.accept( // Error Handler for the acceptor. You'll return true if you want to continue accepting // or fals otherwise. []( asio::error_code error, protocol::endpoint endpoint ) -> bool { if( error ) { CI_LOG_E( "Error Accepting: " << error.message() << " val: " << error.value() << " endpoint: " << endpoint.address().to_string() ); return false; } else return true; }, // Accept Handler. Return whether or not the acceptor should cache this connection // (true) or dismiss it (false). [&, expectedOriginator]( osc::TcpSocketRef socket, uint64_t identifier ) -> bool { // Here we return whether or not the remote endpoint is the expected endpoint mConnections.emplace( identifier, socket->remote_endpoint() ); return socket->remote_endpoint() == expectedOriginator; } ); #endif }