void CDemo::loadSceneData() { // load quake level video::IVideoDriver* driver = device->getVideoDriver(); scene::ISceneManager* sm = device->getSceneManager(); // Quake3 Shader controls Z-Writing sm->getParameters()->setAttribute(scene::ALLOW_ZWRITE_ON_TRANSPARENT, true); quakeLevelMesh = (scene::IQ3LevelMesh*) sm->getMesh("maps/20kdm2.bsp"); if (quakeLevelMesh) { u32 i; //move all quake level meshes (non-realtime) core::matrix4 m; m.setTranslation ( core::vector3df(-1300,-70,-1249) ); for ( i = 0; i!= scene::quake3::E_Q3_MESH_SIZE; ++i ) { sm->getMeshManipulator()->transformMesh ( quakeLevelMesh->getMesh(i), m ); } quakeLevelNode = sm->addOctreeSceneNode( quakeLevelMesh->getMesh( scene::quake3::E_Q3_MESH_GEOMETRY) ); if (quakeLevelNode) { //quakeLevelNode->setPosition(core::vector3df(-1300,-70,-1249)); quakeLevelNode->setVisible(true); // create map triangle selector mapSelector = sm->createOctreeTriangleSelector(quakeLevelMesh->getMesh(0), quakeLevelNode, 128); // if not using shader and no gamma it's better to use more lighting, because // quake3 level are usually dark quakeLevelNode->setMaterialType ( video::EMT_LIGHTMAP_M4 ); // set additive blending if wanted if (additive) quakeLevelNode->setMaterialType(video::EMT_LIGHTMAP_ADD); } // the additional mesh can be quite huge and is unoptimized scene::IMesh * additional_mesh = quakeLevelMesh->getMesh ( scene::quake3::E_Q3_MESH_ITEMS ); for ( i = 0; i!= additional_mesh->getMeshBufferCount (); ++i ) { scene::IMeshBuffer *meshBuffer = additional_mesh->getMeshBuffer ( i ); const video::SMaterial &material = meshBuffer->getMaterial(); //! The ShaderIndex is stored in the material parameter s32 shaderIndex = (s32) material.MaterialTypeParam2; // the meshbuffer can be rendered without additional support, or it has no shader const scene::quake3::IShader *shader = quakeLevelMesh->getShader ( shaderIndex ); if ( 0 == shader ) { continue; } // Now add the MeshBuffer(s) with the current Shader to the Manager sm->addQuake3SceneNode ( meshBuffer, shader ); } } // load sydney model and create 2 instances scene::IAnimatedMesh* mesh = 0; mesh = sm->getMesh("../../media/sydney.md2"); if (mesh) { model1 = sm->addAnimatedMeshSceneNode(mesh); if (model1) { model1->setMaterialTexture(0, driver->getTexture("../../media/spheremap.jpg")); model1->setPosition(core::vector3df(100,40,-80)); model1->setScale(core::vector3df(2,2,2)); model1->setMD2Animation(scene::EMAT_STAND); model1->setMaterialFlag(video::EMF_LIGHTING, false); model1->setMaterialType(video::EMT_SPHERE_MAP); model1->addShadowVolumeSceneNode(); model1->setAutomaticCulling ( scene::EAC_BOX ); } model2 = sm->addAnimatedMeshSceneNode(mesh); if (model2) { model2->setPosition(core::vector3df(180,15,-60)); model2->setScale(core::vector3df(2,2,2)); model2->setMD2Animation(scene::EMAT_RUN); model2->setMaterialTexture(0, device->getVideoDriver()->getTexture("../../media/sydney.bmp")); model2->setMaterialFlag(video::EMF_LIGHTING, true); model2->addShadowVolumeSceneNode(); model2->setAutomaticCulling ( scene::EAC_BOX ); } } scene::ISceneNodeAnimator* anim = 0; // create sky box driver->setTextureCreationFlag(video::ETCF_CREATE_MIP_MAPS, false); skyboxNode = sm->addSkyBoxSceneNode( driver->getTexture("../../media/irrlicht2_up.jpg"), driver->getTexture("../../media/irrlicht2_dn.jpg"), driver->getTexture("../../media/irrlicht2_lf.jpg"), driver->getTexture("../../media/irrlicht2_rt.jpg"), driver->getTexture("../../media/irrlicht2_ft.jpg"), driver->getTexture("../../media/irrlicht2_bk.jpg")); driver->setTextureCreationFlag(video::ETCF_CREATE_MIP_MAPS, true); //driver->setTextureCreationFlag(video::ETCF_CREATE_MIP_MAPS, true); // create walk-between-portals animation core::vector3df waypoint[2]; waypoint[0].set(-150,40,100); waypoint[1].set(350,40,100); if (model2) { anim = device->getSceneManager()->createFlyStraightAnimator(waypoint[0], waypoint[1], 2000, true); model2->addAnimator(anim); anim->drop(); } // create animation for portals; core::array<video::ITexture*> textures; for (s32 g=1; g<8; ++g) { core::stringc tmp("../../media/portal"); tmp += g; tmp += ".bmp"; video::ITexture* t = driver->getTexture( tmp ); textures.push_back(t); } anim = sm->createTextureAnimator(textures, 100); // create portals scene::IBillboardSceneNode* bill = 0; for (int r=0; r<2; ++r) { bill = sm->addBillboardSceneNode(0, core::dimension2d<f32>(100,100), waypoint[r]+ core::vector3df(0,20,0)); bill->setMaterialFlag(video::EMF_LIGHTING, false); bill->setMaterialTexture(0, driver->getTexture("../../media/portal1.bmp")); bill->setMaterialType(video::EMT_TRANSPARENT_ADD_COLOR); bill->addAnimator(anim); } anim->drop(); // create cirlce flying dynamic light with transparent billboard attached scene::ILightSceneNode* light = 0; light = sm->addLightSceneNode(0, core::vector3df(0,0,0), video::SColorf(1.0f, 1.0f, 1.f, 1.0f), 500.f); anim = sm->createFlyCircleAnimator( core::vector3df(100,150,80), 80.0f, 0.0005f); light->addAnimator(anim); anim->drop(); bill = device->getSceneManager()->addBillboardSceneNode( light, core::dimension2d<f32>(40,40)); bill->setMaterialFlag(video::EMF_LIGHTING, false); bill->setMaterialTexture(0, driver->getTexture("../../media/particlewhite.bmp")); bill->setMaterialType(video::EMT_TRANSPARENT_ADD_COLOR); // create meta triangle selector with all triangles selectors in it. metaSelector = sm->createMetaTriangleSelector(); metaSelector->addTriangleSelector(mapSelector); // create camp fire campFire = sm->addParticleSystemSceneNode(false); campFire->setPosition(core::vector3df(100,120,600)); campFire->setScale(core::vector3df(2,2,2)); scene::IParticleEmitter* em = campFire->createBoxEmitter( core::aabbox3d<f32>(-7,0,-7,7,1,7), core::vector3df(0.0f,0.06f,0.0f), 80,100, video::SColor(0,255,255,255),video::SColor(0,255,255,255), 800,2000); em->setMinStartSize(core::dimension2d<f32>(20.0f, 10.0f)); em->setMaxStartSize(core::dimension2d<f32>(20.0f, 10.0f)); campFire->setEmitter(em); em->drop(); scene::IParticleAffector* paf = campFire->createFadeOutParticleAffector(); campFire->addAffector(paf); paf->drop(); campFire->setMaterialFlag(video::EMF_LIGHTING, false); campFire->setMaterialFlag(video::EMF_ZWRITE_ENABLE, false); campFire->setMaterialTexture(0, driver->getTexture("../../media/fireball.bmp")); campFire->setMaterialType(video::EMT_TRANSPARENT_VERTEX_ALPHA); // load music #ifdef USE_IRRKLANG if (music) startIrrKlang(); #endif #ifdef USE_SDL_MIXER if (music) startSound(); #endif }
// Load new map bool j1Map::Load(const char* file_name) { bool ret = true; p2SString tmp("%s%s", folder.GetString(), file_name); char* buf; int size = App->fs->Load(tmp.GetString(), &buf); pugi::xml_parse_result result = map_file.load_buffer(buf, size); RELEASE(buf); if(result == NULL) { LOG("Could not load map xml file %s. pugi error: %s", file_name, result.description()); ret = false; } // Load general info ---------------------------------------------- if(ret == true) { ret = LoadMap(); } // Load all tilesets info ---------------------------------------------- pugi::xml_node tileset; for(tileset = map_file.child("map").child("tileset"); tileset && ret; tileset = tileset.next_sibling("tileset")) { TileSet* set = new TileSet(); if(ret == true) { ret = LoadTilesetDetails(tileset, set); } if(ret == true) { ret = LoadTilesetImage(tileset, set); } //STL CHANGE data.tilesets.push_back(set); } // Load layer info ---------------------------------------------- pugi::xml_node layer; for(layer = map_file.child("map").child("layer"); layer && ret; layer = layer.next_sibling("layer")) { MapLayer* lay = new MapLayer(); ret = LoadLayer(layer, lay); //STL CHANGE if(ret == true) data.layers.push_back(lay); } if(ret == true) { LOG("Successfully parsed map XML file: %s", file_name); LOG("width: %d height: %d", data.width, data.height); LOG("tile_width: %d tile_height: %d", data.tile_width, data.tile_height); //STL CHANGE list<TileSet*>::iterator item = data.tilesets.begin(); while(item != data.tilesets.end()) { TileSet* s = *item; LOG("Tileset ----"); LOG("name: %s firstgid: %d", s->name.GetString(), s->firstgid); LOG("tile width: %d tile height: %d", s->tile_width, s->tile_height); LOG("spacing: %d margin: %d", s->spacing, s->margin); item++; } //STL CHANGE list<MapLayer*>::iterator item_layer = data.layers.begin(); while(item_layer != data.layers.end()) { MapLayer* l = *item_layer; LOG("Layer ----"); LOG("name: %s", l->name.GetString()); LOG("tile width: %d tile height: %d", l->width, l->height); item_layer++; } } map_loaded = ret; return ret; }
void RegisterMMIO(MMIO::Mapping* mmio, u32 base) { struct { u32 addr; u16* ptr; bool readonly; bool writes_align_to_32_bytes; } directly_mapped_vars[] = { { FIFO_TOKEN_REGISTER, &m_tokenReg }, // Bounding box registers are read only. { FIFO_BOUNDING_BOX_LEFT, &m_bboxleft, true }, { FIFO_BOUNDING_BOX_RIGHT, &m_bboxright, true }, { FIFO_BOUNDING_BOX_TOP, &m_bboxtop, true }, { FIFO_BOUNDING_BOX_BOTTOM, &m_bboxbottom, true }, // Some FIFO addresses need to be aligned on 32 bytes on write - only // the high part can be written directly without a mask. { FIFO_BASE_LO, MMIO::Utils::LowPart(&fifo.CPBase), false, true }, { FIFO_BASE_HI, MMIO::Utils::HighPart(&fifo.CPBase) }, { FIFO_END_LO, MMIO::Utils::LowPart(&fifo.CPEnd), false, true }, { FIFO_END_HI, MMIO::Utils::HighPart(&fifo.CPEnd) }, { FIFO_HI_WATERMARK_LO, MMIO::Utils::LowPart(&fifo.CPHiWatermark) }, { FIFO_HI_WATERMARK_HI, MMIO::Utils::HighPart(&fifo.CPHiWatermark) }, { FIFO_LO_WATERMARK_LO, MMIO::Utils::LowPart(&fifo.CPLoWatermark) }, { FIFO_LO_WATERMARK_HI, MMIO::Utils::HighPart(&fifo.CPLoWatermark) }, // FIFO_RW_DISTANCE has some complex read code different for // single/dual core. { FIFO_WRITE_POINTER_LO, MMIO::Utils::LowPart(&fifo.CPWritePointer), false, true }, { FIFO_WRITE_POINTER_HI, MMIO::Utils::HighPart(&fifo.CPWritePointer) }, // FIFO_READ_POINTER has different code for single/dual core. }; for (auto& mapped_var : directly_mapped_vars) { u16 wmask = mapped_var.writes_align_to_32_bytes ? 0xFFE0 : 0xFFFF; mmio->Register(base | mapped_var.addr, MMIO::DirectRead<u16>(mapped_var.ptr), mapped_var.readonly ? MMIO::InvalidWrite<u16>() : MMIO::DirectWrite<u16>(mapped_var.ptr, wmask)); } mmio->Register( base | FIFO_BP_LO, MMIO::DirectRead<u16>(MMIO::Utils::LowPart(&fifo.CPBreakpoint)), MMIO::ComplexWrite<u16>([](u32, u16 val) { WriteLow(fifo.CPBreakpoint, val & 0xffe0); })); mmio->Register(base | FIFO_BP_HI, MMIO::DirectRead<u16>(MMIO::Utils::HighPart(&fifo.CPBreakpoint)), MMIO::ComplexWrite<u16>([](u32, u16 val) { WriteHigh(fifo.CPBreakpoint, val); })); // Timing and metrics MMIOs are stubbed with fixed values. struct { u32 addr; u16 value; } metrics_mmios[] = { { XF_RASBUSY_L, 0 }, { XF_RASBUSY_H, 0 }, { XF_CLKS_L, 0 }, { XF_CLKS_H, 0 }, { XF_WAIT_IN_L, 0 }, { XF_WAIT_IN_H, 0 }, { XF_WAIT_OUT_L, 0 }, { XF_WAIT_OUT_H, 0 }, { VCACHE_METRIC_CHECK_L, 0 }, { VCACHE_METRIC_CHECK_H, 0 }, { VCACHE_METRIC_MISS_L, 0 }, { VCACHE_METRIC_MISS_H, 0 }, { VCACHE_METRIC_STALL_L, 0 }, { VCACHE_METRIC_STALL_H, 0 }, { CLKS_PER_VTX_OUT, 4 }, }; for (auto& metrics_mmio : metrics_mmios) { mmio->Register(base | metrics_mmio.addr, MMIO::Constant<u16>(metrics_mmio.value), MMIO::InvalidWrite<u16>()); } mmio->Register(base | STATUS_REGISTER, MMIO::ComplexRead<u16>([](u32) { SetCpStatusRegister(); return m_CPStatusReg.Hex; }), MMIO::InvalidWrite<u16>()); mmio->Register(base | CTRL_REGISTER, MMIO::DirectRead<u16>(&m_CPCtrlReg.Hex), MMIO::ComplexWrite<u16>([](u32, u16 val) { UCPCtrlReg tmp(val); m_CPCtrlReg.Hex = tmp.Hex; SetCpControlRegister(); Fifo::RunGpu(); })); mmio->Register(base | CLEAR_REGISTER, MMIO::DirectRead<u16>(&m_CPClearReg.Hex), MMIO::ComplexWrite<u16>([](u32, u16 val) { UCPClearReg tmp(val); m_CPClearReg.Hex = tmp.Hex; SetCpClearRegister(); Fifo::RunGpu(); })); mmio->Register(base | PERF_SELECT, MMIO::InvalidRead<u16>(), MMIO::Nop<u16>()); // Some MMIOs have different handlers for single core vs. dual core mode. mmio->Register(base | FIFO_RW_DISTANCE_LO, IsOnThread() ? MMIO::ComplexRead<u16>([](u32) { if (fifo.CPWritePointer >= fifo.SafeCPReadPointer) return ReadLow(fifo.CPWritePointer - fifo.SafeCPReadPointer); else return ReadLow(fifo.CPEnd - fifo.SafeCPReadPointer + fifo.CPWritePointer - fifo.CPBase + 32); }) : MMIO::DirectRead<u16>(MMIO::Utils::LowPart(&fifo.CPReadWriteDistance)), MMIO::DirectWrite<u16>(MMIO::Utils::LowPart(&fifo.CPReadWriteDistance), 0xFFE0)); mmio->Register(base | FIFO_RW_DISTANCE_HI, IsOnThread() ? MMIO::ComplexRead<u16>([](u32) { if (fifo.CPWritePointer >= fifo.SafeCPReadPointer) return ReadHigh(fifo.CPWritePointer - fifo.SafeCPReadPointer); else return ReadHigh(fifo.CPEnd - fifo.SafeCPReadPointer + fifo.CPWritePointer - fifo.CPBase + 32); }) : MMIO::DirectRead<u16>(MMIO::Utils::HighPart(&fifo.CPReadWriteDistance)), MMIO::ComplexWrite<u16>([](u32, u16 val) { WriteHigh(fifo.CPReadWriteDistance, val); Fifo::SyncGPU(Fifo::SyncGPUReason::Other); if (fifo.CPReadWriteDistance == 0) { GPFifo::ResetGatherPipe(); Fifo::ResetVideoBuffer(); } else { Fifo::ResetVideoBuffer(); } Fifo::RunGpu(); })); mmio->Register(base | FIFO_READ_POINTER_LO, IsOnThread() ? MMIO::DirectRead<u16>(MMIO::Utils::LowPart(&fifo.SafeCPReadPointer)) : MMIO::DirectRead<u16>(MMIO::Utils::LowPart(&fifo.CPReadPointer)), MMIO::DirectWrite<u16>(MMIO::Utils::LowPart(&fifo.CPReadPointer), 0xFFE0)); mmio->Register(base | FIFO_READ_POINTER_HI, IsOnThread() ? MMIO::DirectRead<u16>(MMIO::Utils::HighPart(&fifo.SafeCPReadPointer)) : MMIO::DirectRead<u16>(MMIO::Utils::HighPart(&fifo.CPReadPointer)), IsOnThread() ? MMIO::ComplexWrite<u16>([](u32, u16 val) { WriteHigh(fifo.CPReadPointer, val); fifo.SafeCPReadPointer = fifo.CPReadPointer; }) : MMIO::DirectWrite<u16>(MMIO::Utils::HighPart(&fifo.CPReadPointer))); }
bool parse(const QString& arg, HValidityCheckLevel checkLevel) { HLOG(H_AT, H_FUN); QString tmp(arg.simplified()); HUdn udn; qint32 indx = tmp.indexOf("::"); if (indx == 41) // the length of "uuid:UUID" is 41 { udn = HUdn(tmp.left(41)); if (!udn.isValid(checkLevel)) { return false; } if (tmp.size() > 43) { tmp = tmp.mid(43); } else { m_udn = udn; m_type = HDiscoveryType::SpecificDevice; m_contents = udn.toString(); return true; } } QStringList parsed = tmp.split(':'); if (parsed.size() < 2) { HLOG_WARN(QString("Invalid resource identifier: %1").arg(arg)); return false; } if (!udn.isValid(checkLevel)) { if (parsed[0] == "ssdp" && parsed[1] == "all") { m_type = HDiscoveryType::All; m_contents = "ssdp:all"; return true; } } if (parsed[0] == "upnp" && parsed[1] == "rootdevice") { m_udn = udn; if (m_udn.isValid(checkLevel)) { m_type = HDiscoveryType::SpecificRootDevice; m_contents = QString("%1::upnp:rootdevice").arg(udn.toString()); } else { m_type = HDiscoveryType::RootDevices; m_contents = "upnp:rootdevice"; } return true; } else if (parsed[0] == "uuid") { udn = HUdn(parsed[1]); if (udn.isValid(checkLevel)) { m_udn = udn; m_type = HDiscoveryType::SpecificDevice; m_contents = udn.toString(); return true; } } HResourceType resourceType(tmp); if (parse(resourceType)) { m_udn = udn; if (m_udn.isValid(checkLevel)) { m_type = resourceType.isDeviceType() ? HDiscoveryType::SpecificDeviceWithType : HDiscoveryType::SpecificServiceWithType; m_contents = QString("%1::%2").arg( udn.toString(), resourceType.toString()); } else { m_type = resourceType.isDeviceType() ? HDiscoveryType::DeviceType : HDiscoveryType::ServiceType; m_contents = QString("%1").arg(resourceType.toString()); } return true; } HLOG_WARN(QString("Invalid resource identifier: %1").arg(arg)); return false; }
void testObj::test<8>(void) { PtrNN tmp(new int); tmp=nn_; ensure("invalid pointer value", tmp.get()==nn_.get() ); }
virtual void run() { fTraceInfo = 1; LocalPointer<NumberFormat> percentFormatter; UErrorCode status = U_ZERO_ERROR; #if 0 // debugging code, for (int i=0; i<4000; i++) { status = U_ZERO_ERROR; UDataMemory *data1 = udata_openChoice(0, "res", "en_US", isAcceptable, 0, &status); UDataMemory *data2 = udata_openChoice(0, "res", "fr", isAcceptable, 0, &status); udata_close(data1); udata_close(data2); if (U_FAILURE(status)) { error("udata_openChoice failed.\n"); break; } } return; #endif #if 0 // debugging code, int m; for (m=0; m<4000; m++) { status = U_ZERO_ERROR; UResourceBundle *res = NULL; const char *localeName = NULL; Locale loc = Locale::getEnglish(); localeName = loc.getName(); // localeName = "en"; // ResourceBundle bund = ResourceBundle(0, loc, status); //umtx_lock(&gDebugMutex); res = ures_open(NULL, localeName, &status); //umtx_unlock(&gDebugMutex); //umtx_lock(&gDebugMutex); ures_close(res); //umtx_unlock(&gDebugMutex); if (U_FAILURE(status)) { error("Resource bundle construction failed.\n"); break; } } return; #endif // Keep this data here to avoid static initialization. FormatThreadTestData kNumberFormatTestData[] = { FormatThreadTestData((double)5.0, UnicodeString("5", "")), FormatThreadTestData( 6.0, UnicodeString("6", "")), FormatThreadTestData( 20.0, UnicodeString("20", "")), FormatThreadTestData( 8.0, UnicodeString("8", "")), FormatThreadTestData( 8.3, UnicodeString("8.3", "")), FormatThreadTestData( 12345, UnicodeString("12,345", "")), FormatThreadTestData( 81890.23, UnicodeString("81,890.23", "")), }; int32_t kNumberFormatTestDataLength = UPRV_LENGTHOF(kNumberFormatTestData); // Keep this data here to avoid static initialization. FormatThreadTestData kPercentFormatTestData[] = { FormatThreadTestData((double)5.0, CharsToUnicodeString("500\\u00a0%")), FormatThreadTestData( 1.0, CharsToUnicodeString("100\\u00a0%")), FormatThreadTestData( 0.26, CharsToUnicodeString("26\\u00a0%")), FormatThreadTestData( 16384.99, CharsToUnicodeString("1\\u00a0638\\u00a0499\\u00a0%")), // U+00a0 = NBSP FormatThreadTestData( 81890.23, CharsToUnicodeString("8\\u00a0189\\u00a0023\\u00a0%")), }; int32_t kPercentFormatTestDataLength = UPRV_LENGTHOF(kPercentFormatTestData); int32_t iteration; status = U_ZERO_ERROR; LocalPointer<NumberFormat> formatter(NumberFormat::createInstance(Locale::getEnglish(),status)); if(U_FAILURE(status)) { IntlTest::gTest->dataerrln("%s:%d Error %s on NumberFormat::createInstance().", __FILE__, __LINE__, u_errorName(status)); goto cleanupAndReturn; } percentFormatter.adoptInstead(NumberFormat::createPercentInstance(Locale::getFrench(),status)); if(U_FAILURE(status)) { IntlTest::gTest->errln("%s:%d Error %s on NumberFormat::createPercentInstance().", __FILE__, __LINE__, u_errorName(status)); goto cleanupAndReturn; } for(iteration = 0;!IntlTest::gTest->getErrors() && iteration<kFormatThreadIterations;iteration++) { int32_t whichLine = (iteration + fOffset)%kNumberFormatTestDataLength; UnicodeString output; formatter->format(kNumberFormatTestData[whichLine].number, output); if(0 != output.compare(kNumberFormatTestData[whichLine].string)) { IntlTest::gTest->errln("format().. expected " + kNumberFormatTestData[whichLine].string + " got " + output); goto cleanupAndReturn; } // Now check percent. output.remove(); whichLine = (iteration + fOffset)%kPercentFormatTestDataLength; percentFormatter->format(kPercentFormatTestData[whichLine].number, output); if(0 != output.compare(kPercentFormatTestData[whichLine].string)) { IntlTest::gTest->errln("percent format().. \n" + showDifference(kPercentFormatTestData[whichLine].string,output)); goto cleanupAndReturn; } // Test message error const int kNumberOfMessageTests = 3; UErrorCode statusToCheck; UnicodeString patternToCheck; Locale messageLocale; Locale countryToCheck; double currencyToCheck; UnicodeString expected; // load the cases. switch((iteration+fOffset) % kNumberOfMessageTests) { default: case 0: statusToCheck= U_FILE_ACCESS_ERROR; patternToCheck= "0:Someone from {2} is receiving a #{0}" " error - {1}. Their telephone call is costing " "{3,number,currency}."; // number,currency messageLocale= Locale("en","US"); countryToCheck= Locale("","HR"); currencyToCheck= 8192.77; expected= "0:Someone from Croatia is receiving a #4 error - " "U_FILE_ACCESS_ERROR. Their telephone call is costing $8,192.77."; break; case 1: statusToCheck= U_INDEX_OUTOFBOUNDS_ERROR; patternToCheck= "1:A customer in {2} is receiving a #{0} error - {1}. " "Their telephone call is costing {3,number,currency}."; // number,currency messageLocale= Locale("de","DE@currency=DEM"); countryToCheck= Locale("","BF"); currencyToCheck= 2.32; expected= CharsToUnicodeString( "1:A customer in Burkina Faso is receiving a #8 error - U_INDEX_OUTOFBOUNDS_ERROR. " "Their telephone call is costing 2,32\\u00A0DM."); break; case 2: statusToCheck= U_MEMORY_ALLOCATION_ERROR; patternToCheck= "2:user in {2} is receiving a #{0} error - {1}. " "They insist they just spent {3,number,currency} " "on memory."; // number,currency messageLocale= Locale("de","AT@currency=ATS"); // Austrian German countryToCheck= Locale("","US"); // hmm currencyToCheck= 40193.12; expected= CharsToUnicodeString( "2:user in Vereinigte Staaten is receiving a #7 error" " - U_MEMORY_ALLOCATION_ERROR. They insist they just spent" " \\u00f6S\\u00A040\\u00A0193,12 on memory."); break; } UnicodeString result; UErrorCode status = U_ZERO_ERROR; formatErrorMessage(status,patternToCheck,messageLocale,statusToCheck, countryToCheck,currencyToCheck,result); if(U_FAILURE(status)) { UnicodeString tmp(u_errorName(status)); IntlTest::gTest->errln("Failure on message format, pattern=" + patternToCheck + ", error = " + tmp); goto cleanupAndReturn; } if(result != expected) { IntlTest::gTest->errln("PatternFormat: \n" + showDifference(expected,result)); goto cleanupAndReturn; } // test the Thread Safe Format UnicodeString appendErr; if(!fTSF->doStuff(fNum, appendErr, status)) { IntlTest::gTest->errln(appendErr); goto cleanupAndReturn; } } /* end of for loop */ cleanupAndReturn: fTraceInfo = 2; }
wxMenuBar* NewtonDemos::CreateMainMenu() { wxMenuBar* const mainMenu = new wxMenuBar(); // adding the file menu { wxMenu* const fileMenu = new wxMenu; fileMenu->Append(wxID_ABOUT, wxT("About")); fileMenu->AppendSeparator(); fileMenu->Append(wxID_PREFERENCES, wxT("Preferences")); fileMenu->AppendSeparator(); fileMenu->Append(wxID_NEW, wxT("&New"), wxT("Create a blank new scene")); fileMenu->AppendSeparator(); fileMenu->Append(wxID_OPEN, wxT("&Open"), wxT("Open visual scene in dScene newton format")); fileMenu->Append(wxID_SAVE, wxT("&Save"), wxT("Save visual scene in dScene newton format")); fileMenu->AppendSeparator(); fileMenu->Append(ID_SERIALIZE, wxT("&Serialize"), wxT("Serialize scene to binary file")); fileMenu->Append(ID_DESERIALIZE, wxT("&Deserialize"), wxT("Load previuoslly serialized scame")); // fileMenu->AppendSeparator(); // fileMenu->Append(m_idImportPhysics, wxT("&Open physics scene"), wxT("Open physics scene in collada format")); // fileMenu->Append(m_idExportPhysics, wxT("&Save physics scene"), wxT("Save physics in collada format")); fileMenu->AppendSeparator(); fileMenu->Append(wxID_EXIT, wxT("E&xit\tAlt-X"), wxT("Quit SDK sample") ); // add main menus to menu bar mainMenu->Append(fileMenu, wxT("&File")); } // engine all demo examples { wxMenu* const sdkDemos = new wxMenu; int demosCount = int (sizeof (m_demosSelection) / sizeof m_demosSelection[0]); for (int i = 0; i < demosCount; i ++) { sdkDemos->AppendRadioItem (NewtonDemos::ID_RUN_DEMO + i, m_demosSelection[i].m_name, m_demosSelection[i].m_description); } mainMenu->Append(sdkDemos, wxT("&Demos")); } // option menu { wxMenu* const optionsMenu = new wxMenu;; optionsMenu->AppendCheckItem(ID_AUTOSLEEP_MODE, wxT("Auto sleep mode"), wxT("toogle auto sleep bodies")); optionsMenu->Check (ID_AUTOSLEEP_MODE, m_autoSleepState); optionsMenu->AppendCheckItem(ID_SHOW_STATISTICS, wxT("Show Stats on screen"), wxT("toogle on screen frame rate and other stats")); optionsMenu->AppendCheckItem(ID_USE_PARALLEL_SOLVER, wxT("Parallel solver on")); optionsMenu->AppendSeparator(); optionsMenu->AppendRadioItem(ID_BROADPHSE_TYPE0, wxT("Default broaphase"), wxT("for scenes with more dynamics bodies than static")); optionsMenu->AppendRadioItem(ID_BROADPHSE_TYPE1, wxT("Persintent broaphase"), wxT("for scenes with lot more static bodies than dynamics")); optionsMenu->AppendSeparator(); optionsMenu->AppendRadioItem(ID_SOLVER_MODE + 0, wxT("Exact solver on")); optionsMenu->AppendRadioItem(ID_SOLVER_MODE + 1, wxT("Iterative solver one passes")); optionsMenu->AppendRadioItem(ID_SOLVER_MODE + 2, wxT("Iterative solver two passes")); optionsMenu->AppendRadioItem(ID_SOLVER_MODE + 3, wxT("Iterative solver four passes")); optionsMenu->AppendRadioItem(ID_SOLVER_MODE + 4, wxT("Iterative solver eight passes")); dAssert (m_solverModeIndex >= 0); dAssert (m_solverModeIndex < int (sizeof (m_solverModes)/sizeof (m_solverModes[0]))); optionsMenu->Check (ID_SOLVER_MODE + m_solverModeIndex, true); optionsMenu->AppendSeparator(); optionsMenu->AppendRadioItem(ID_SOLVER_QUALITY + 0, wxT("Iterative Solver Quality Low")); optionsMenu->AppendRadioItem(ID_SOLVER_QUALITY + 1, wxT("Iterative Solver Quality High")); optionsMenu->Check (ID_SOLVER_QUALITY + m_solverModeQuality, true); optionsMenu->AppendSeparator(); optionsMenu->AppendRadioItem(ID_SHOW_COLLISION_MESH, wxT("Hide collision Mesh")); optionsMenu->AppendRadioItem(ID_SHOW_COLLISION_MESH + 1, wxT("Show solid collision Mesh")); optionsMenu->AppendRadioItem(ID_SHOW_COLLISION_MESH + 2, wxT("Show wire frame collision Mesh")); optionsMenu->AppendSeparator(); optionsMenu->AppendCheckItem(ID_HIDE_VISUAL_MESHES, wxT("Hide visual meshes")); optionsMenu->AppendCheckItem(ID_SHOW_CONTACT_POINTS, wxT("Show contact points")); optionsMenu->AppendCheckItem(ID_SHOW_NORMAL_FORCES, wxT("Show normal forces")); optionsMenu->AppendCheckItem(ID_SHOW_AABB, wxT("Show aabb")); optionsMenu->AppendCheckItem(ID_SHOW_CENTER_OF_MASS, wxT("Show center of mass")); optionsMenu->AppendCheckItem(ID_SHOW_JOINTS, wxT("show Joint debug info")); optionsMenu->AppendSeparator(); int platformsCount = NewtonEnumerateDevices (m_scene->GetNewton()); for (int i = 0; i < platformsCount; i ++) { wxString label; char platform[256]; NewtonGetDeviceString (m_scene->GetNewton(), i, platform, sizeof (platform)); #ifdef _POSIX_VER wxChar wPlatform[256]; mbstowcs (wPlatform, platform, sizeof (platform)); wxString tmp (wPlatform); label.Printf (wxT(" hardware mode %s"), tmp.c_str()); #else label.Printf (wxT(" hardware mode %s"), wxString(platform)); #endif optionsMenu->AppendRadioItem(ID_PLATFORMS + i, label); } //optionsMenu->Check(ID_PLATFORMS, true); optionsMenu->AppendSeparator(); optionsMenu->AppendCheckItem(ID_CONCURRENT_PHYSICS_UPDATE, wxT("Concurrent physics update")); wxMenu* const microThreadedsSubMenu = new wxMenu; for (int i = 0 ; i < int (sizeof (m_threadsTracks)/ sizeof (m_threadsTracks[0])); i ++) { wxString msg; msg.Printf(wxT ("%d micro threads"), m_threadsTracks[i]); microThreadedsSubMenu->AppendRadioItem(ID_SELECT_MICROTHREADS + i, msg); } optionsMenu->AppendSubMenu (microThreadedsSubMenu, wxT("select microThread count")); mainMenu->Append(optionsMenu, wxT("&Options")); } // add help menu { wxMenu* const helpMenu = new wxMenu;; helpMenu->Append(wxID_HELP, wxT("About")); // helpMenu->Append(NewtonDemos::ID_ON_ABOUT, wxT("About")); mainMenu->Append(helpMenu, wxT("&Help")); } SetMenuBar(mainMenu); return mainMenu; }
int builtin_evaluate(Environment &env, std::vector<token> &&tokens, const fdmask &fds) { // evaluate expression // evaluate variable = expression // evaluate variable += expression // evaluate variable -= expression // flags -- -h -o -b -- print in hex, octal, or binary // convert the arguments to a stack. int output = 'd'; //io_helper io(fds); std::reverse(tokens.begin(), tokens.end()); // remove 'Evaluate' tokens.pop_back(); // check for -h -x -o if (tokens.size() >= 2 && tokens.back().type == '-') { const token &t = tokens[tokens.size() - 2]; if (t.type == token::text && t.string.length() == 1) { int flag = tolower(t.string[0]); switch(flag) { case 'o': case 'h': case 'b': output = flag; tokens.pop_back(); tokens.pop_back(); } } } if (tokens.size() >= 2 && tokens.back().type == token::text) { int type = tokens[tokens.size() -2].type; if (is_assignment(type)) { std::string name = tokens.back().string; tokens.pop_back(); tokens.pop_back(); int32_t i = evaluate_expression("Evaluate", std::move(tokens)); switch(type) { case '=': env.set(name, i); break; case '+=': case '-=': { value old; auto iter = env.find(name); if (iter != env.end()) old = (const std::string &)iter->second; switch(type) { case '+=': i = old.to_number() + i; break; case '-=': i = old.to_number() - i; break; } env.set(name, i); } break; } return 0; } } int32_t i = evaluate_expression("Evaluate", std::move(tokens)); if (output == 'h') { fdprintf(stdout, "0x%08x\n", i); return 0; } if (output == 'b') { std::string tmp("0b"); for (int j = 0; j < 32; ++j) { tmp.push_back(i & 0x80000000 ? '1' : '0'); i <<= 1; } tmp.push_back('\n'); fdputs(tmp.c_str(), stdout); return 0; } if (output == 'o') { // octal. fdprintf(stdout, "0%o\n", i); return 0; } fdprintf(stdout, "%d\n", i); return 0; }
inline time_duration parse_undelimited_time_duration(const std::string& s) { int precision = 0; { // msvc wouldn't compile 'time_duration::num_fractional_digits()' // (required template argument list) as a workaround, a temp // time_duration object was used time_duration tmp(0,0,0,1); precision = tmp.num_fractional_digits(); } // 'precision+1' is so we grab all digits, plus the decimal int offsets[] = {2,2,2, precision+1}; int pos = 0, sign = 0; int hours = 0; short min=0, sec=0; boost::int64_t fs=0; // increment one position if the string was "signed" if(s.at(sign) == '-') { ++sign; } // stlport choked when passing s.substr() to tokenizer // using a new string fixed the error std::string remain = s.substr(sign); /* We do not want the offset_separator to wrap the offsets, we * will never want to process more than: * 2 char, 2 char, 2 char, frac_sec length. * We *do* want the offset_separator to give us a partial for the * last characters if there were not enough provided in the input string. */ bool wrap_off = false; bool ret_part = true; boost::offset_separator osf(offsets, offsets+4, wrap_off, ret_part); typedef boost::tokenizer<boost::offset_separator, std::basic_string<char>::const_iterator, std::basic_string<char> > tokenizer; typedef boost::tokenizer<boost::offset_separator, std::basic_string<char>::const_iterator, std::basic_string<char> >::iterator tokenizer_iterator; tokenizer tok(remain, osf); for(tokenizer_iterator ti=tok.begin(); ti!=tok.end();++ti){ switch(pos) { case 0: { hours = boost::lexical_cast<int>(*ti); break; } case 1: { min = boost::lexical_cast<short>(*ti); break; } case 2: { sec = boost::lexical_cast<short>(*ti); break; } case 3: { std::string char_digits(ti->substr(1)); // digits w/no decimal int digits = static_cast<int>(char_digits.length()); //Works around a bug in MSVC 6 library that does not support //operator>> thus meaning lexical_cast will fail to compile. #if (defined(BOOST_MSVC) && (_MSC_VER <= 1200)) // 1200 == VC++ 6.0 // _atoi64 is an MS specific function if(digits >= precision) { // drop excess digits fs = _atoi64(char_digits.substr(0, precision).c_str()); } else if(digits == 0) { fs = 0; // just in case _atoi64 doesn't like an empty string } else { fs = _atoi64(char_digits.c_str()); } #else if(digits >= precision) { // drop excess digits fs = boost::lexical_cast<boost::int64_t>(char_digits.substr(0, precision)); } else if(digits == 0) { fs = 0; // lexical_cast doesn't like empty strings } else { fs = boost::lexical_cast<boost::int64_t>(char_digits); } #endif if(digits < precision){ // trailing zeros get dropped from the string, // "1:01:01.1" would yield .000001 instead of .100000 // the power() compensates for the missing decimal places fs *= power(10, precision - digits); } break; } }; pos++; } if(sign) { return -time_duration(hours, min, sec, fs); } else { return time_duration(hours, min, sec, fs); } }
/// \brief Postincrement: Skip to the next character of the source /// \return *this inline TextScanner operator ++(int) {TextScanner tmp(*this); skip(); return tmp;}
void Recorder::pre_draw_CB() { //set/get time, cam_pos, etc... CAM tmp("temp"); if ( !_cur_path ) return; if ( !_paused ) { if ( _sync && ( _path_pos > _target_frame ) ) replay(); double ttime = _swatch->elapsed_time(); if ( _play_on ) { //forward to closest path after current time if ( _path_pos >= (int)_cur_path->state_list.size() || _cur_path->state_list.empty() ) { cerr << "end of state list reached::camera stop" << endl; rec_stop() ; return; } if ( _render_on || _play_all_frames ) { CAMptr mine = (_cur_path->state_list[_path_pos]->cam()); _view->cam()->data()->set_from ( mine->data()->from() ); _view->cam()->data()->set_at ( mine->data()->at() ); _view->cam()->data()->set_up ( mine->data()->up() ); _view->cam()->data()->set_center ( mine->data()->center() ); _view->cam()->data()->set_focal ( mine->data()->focal() ); _view->cam()->data()->set_persp ( mine->data()->persp() ); _view->cam()->data()->set_iod ( mine->data()->iod() ); _view->set_frame_time( _cur_path->state_list[_path_pos]->t()); //update UI to reflect which frame is being shown _ui->set_frame_num ( _path_pos ); if ( _sync ) { if ( _path_pos == _target_frame ) { cerr << "at target frame: pausing:" << endl ; rec_pause(); } else if ( _path_pos > _target_frame ) { cerr << "ack, we need to set back"<< endl; replay(); } else _path_pos++; } else { if ( _path_pos >= (int)_cur_path->state_list.size() -1 ) rec_stop(); else if ( _path_pos >= _target_frame ) rec_pause(); else _path_pos++; } } else { while ( _cur_path->state_list[_path_pos]->t() < ttime ) { _path_pos++; if ( _path_pos >= (int)_cur_path->state_list.size()) { rec_stop(); return; } } CAMptr mine = (_cur_path->state_list[_path_pos]->cam()); _view->cam()->data()->set_from ( mine->data()->from() ); _view->cam()->data()->set_at ( mine->data()->at() ); _view->cam()->data()->set_up ( mine->data()->up() ); _view->cam()->data()->set_center ( mine->data()->center() ); _view->cam()->data()->set_focal ( mine->data()->focal() ); _view->cam()->data()->set_persp ( mine->data()->persp() ); _view->cam()->data()->set_iod ( mine->data()->iod() ); _view->set_frame_time( _cur_path->state_list[_path_pos]->t()); _ui->set_frame_num ( _path_pos ); } //set view camera to stored camera } else if ( _record_on ) { while ( ttime >= _next_time ) { _cur_path->add( _next_time, _view->cam()); //always adds to end of list _path_pos = _cur_path->state_list.size()-1; _next_time += 1.0/_fps; //set next time to get data } } } else if ( _paused && _play_on) { if ( _sync && ( _path_pos > _target_frame ) ) { replay(); _paused = true; } if ( _path_pos < 0 || _path_pos >= (int)_cur_path->state_list.size() || _cur_path->state_list.empty() ) { rec_stop(); return; } } _ui->update_checks(); }
Plus operator+(const Plus &a) { std::cout<<"Process... "<<name<<" + "<<a.name<<std::endl; Plus tmp("TMP"); tmp.value=value+a.value; return tmp; }
// Draws a cached pixmap with shadow void StyleHelper::drawIconWithShadow(const QIcon &icon, const QRect &rect, QPainter *p, QIcon::Mode iconMode, int radius, const QColor &color, const QPoint &offset) { QPixmap cache; QString pixmapName = QString::fromLatin1("icon %0 %1 %2").arg(icon.cacheKey()).arg(iconMode).arg(rect.height()); if (!QPixmapCache::find(pixmapName, cache)) { QPixmap px = icon.pixmap(rect.size()); cache = QPixmap(px.size() + QSize(radius * 2, radius * 2)); cache.fill(Qt::transparent); QPainter cachePainter(&cache); if (iconMode == QIcon::Disabled) { QImage im = px.toImage().convertToFormat(QImage::Format_ARGB32); for (int y=0; y<im.height(); ++y) { QRgb *scanLine = (QRgb*)im.scanLine(y); for (int x=0; x<im.width(); ++x) { QRgb pixel = *scanLine; char intensity = qGray(pixel); *scanLine = qRgba(intensity, intensity, intensity, qAlpha(pixel)); ++scanLine; } } px = QPixmap::fromImage(im); } // Draw shadow QImage tmp(px.size() + QSize(radius * 2, radius * 2 + 1), QImage::Format_ARGB32_Premultiplied); tmp.fill(Qt::transparent); QPainter tmpPainter(&tmp); tmpPainter.setCompositionMode(QPainter::CompositionMode_Source); tmpPainter.drawPixmap(QPoint(radius, radius), px); tmpPainter.end(); // blur the alpha channel QImage blurred(tmp.size(), QImage::Format_ARGB32_Premultiplied); blurred.fill(Qt::transparent); QPainter blurPainter(&blurred); qt_blurImage(&blurPainter, tmp, radius, false, true); blurPainter.end(); tmp = blurred; // blacken the image... tmpPainter.begin(&tmp); tmpPainter.setCompositionMode(QPainter::CompositionMode_SourceIn); tmpPainter.fillRect(tmp.rect(), color); tmpPainter.end(); tmpPainter.begin(&tmp); tmpPainter.setCompositionMode(QPainter::CompositionMode_SourceIn); tmpPainter.fillRect(tmp.rect(), color); tmpPainter.end(); // draw the blurred drop shadow... cachePainter.drawImage(QRect(0, 0, cache.rect().width(), cache.rect().height()), tmp); // Draw the actual pixmap... cachePainter.drawPixmap(QPoint(radius, radius) + offset, px); QPixmapCache::insert(pixmapName, cache); } QRect targetRect = cache.rect(); targetRect.moveCenter(rect.center()); p->drawPixmap(targetRect.topLeft() - offset, cache); }
//-------------------------------------------------- ofBuffer::Line ofBuffer::Line::operator++(int) { Line tmp(*this); operator++(); return tmp; }
symbol_exprt symbol_expr(const symbolt &symbol) { symbol_exprt tmp(symbol.type); tmp.set_identifier(symbol.name); return tmp; }
Vector3 Vector3::getNormalised() const { Vector3 tmp(*this); tmp.normalise(); return tmp; }
inline void op_mean::apply_noalias_unwrap(Cube<typename T1::elem_type>& out, const ProxyCube<T1>& P, const uword dim) { arma_extra_debug_sigprint(); typedef typename T1::elem_type eT; typedef typename get_pod_type<eT>::result T; typedef typename ProxyCube<T1>::stored_type P_stored_type; const unwrap_cube<P_stored_type> U(P.Q); const Cube<eT>& X = U.M; const uword X_n_rows = X.n_rows; const uword X_n_cols = X.n_cols; const uword X_n_slices = X.n_slices; if(dim == 0) { out.set_size((X_n_rows > 0) ? 1 : 0, X_n_cols, X_n_slices); if(X_n_rows == 0) { return; } for(uword slice=0; slice < X_n_slices; ++slice) { eT* out_mem = out.slice_memptr(slice); for(uword col=0; col < X_n_cols; ++col) { out_mem[col] = op_mean::direct_mean( X.slice_colptr(slice,col), X_n_rows ); } } } else if(dim == 1) { out.zeros(X_n_rows, (X_n_cols > 0) ? 1 : 0, X_n_slices); if(X_n_cols == 0) { return; } for(uword slice=0; slice < X_n_slices; ++slice) { eT* out_mem = out.slice_memptr(slice); for(uword col=0; col < X_n_cols; ++col) { const eT* col_mem = X.slice_colptr(slice,col); for(uword row=0; row < X_n_rows; ++row) { out_mem[row] += col_mem[row]; } } const Mat<eT> tmp('j', X.slice_memptr(slice), X_n_rows, X_n_cols); for(uword row=0; row < X_n_rows; ++row) { out_mem[row] /= T(X_n_cols); if(arma_isfinite(out_mem[row]) == false) { out_mem[row] = op_mean::direct_mean_robust( tmp, row ); } } } } else if(dim == 2) { out.zeros(X_n_rows, X_n_cols, (X_n_slices > 0) ? 1 : 0); if(X_n_slices == 0) { return; } eT* out_mem = out.memptr(); for(uword slice=0; slice < X_n_slices; ++slice) { arrayops::inplace_plus(out_mem, X.slice_memptr(slice), X.n_elem_slice ); } out /= T(X_n_slices); podarray<eT> tmp(X_n_slices); for(uword col=0; col < X_n_cols; ++col) for(uword row=0; row < X_n_rows; ++row) { if(arma_isfinite(out.at(row,col,0)) == false) { for(uword slice=0; slice < X_n_slices; ++slice) { tmp[slice] = X.at(row,col,slice); } out.at(row,col,0) = op_mean::direct_mean_robust(tmp.memptr(), X_n_slices); } } } }
SaturationModulus<EvalT, Traits>:: SaturationModulus(Teuchos::ParameterList& p) : satMod(p.get<std::string>("Saturation Modulus Name"), p.get<Teuchos::RCP<PHX::DataLayout>>("QP Scalar Data Layout")) { Teuchos::ParameterList* satmod_list = p.get<Teuchos::ParameterList*>("Parameter List"); Teuchos::RCP<PHX::DataLayout> vector_dl = p.get< Teuchos::RCP<PHX::DataLayout>>("QP Vector Data Layout"); std::vector<PHX::DataLayout::size_type> dims; vector_dl->dimensions(dims); numQPs = dims[1]; numDims = dims[2]; Teuchos::RCP<ParamLib> paramLib = p.get< Teuchos::RCP<ParamLib>>("Parameter Library", Teuchos::null); std::string type = satmod_list->get("Saturation Modulus Type", "Constant"); if (type == "Constant") { is_constant = true; constant_value = satmod_list->get("Value", 0.0); // Add Saturation Modulus as a Sacado-ized parameter this->registerSacadoParameter("Saturation Modulus", paramLib); } #ifdef ALBANY_STOKHOS else if (type == "Truncated KL Expansion") { is_constant = false; PHX::MDField<MeshScalarT,Cell,QuadPoint,Dim> fx(p.get<std::string>("QP Coordinate Vector Name"), vector_dl); coordVec = fx; this->addDependentField(coordVec); exp_rf_kl = Teuchos::rcp(new Stokhos::KL::ExponentialRandomField<RealType>(*satmod_list)); int num_KL = exp_rf_kl->stochasticDimension(); // Add KL random variables as Sacado-ized parameters rv.resize(num_KL); for (int i=0; i<num_KL; i++) { std::string ss = Albany::strint("Saturation Modulus KL Random Variable",i); this->registerSacadoParameter(ss, paramLib); rv[i] = satmod_list->get(ss, 0.0); } } #endif else { TEUCHOS_TEST_FOR_EXCEPTION(true, Teuchos::Exceptions::InvalidParameter, "Invalid saturation modulus type " << type); } // Optional dependence on Temperature // Switched ON by sending Temperature field in p if ( p.isType<std::string>("QP Temperature Name") ) { Teuchos::RCP<PHX::DataLayout> scalar_dl = p.get< Teuchos::RCP<PHX::DataLayout>>("QP Scalar Data Layout"); PHX::MDField<ScalarT,Cell,QuadPoint> tmp(p.get<std::string>("QP Temperature Name"), scalar_dl); Temperature = tmp; this->addDependentField(Temperature); isThermoElastic = true; dSdT_value = satmod_list->get("dSdT Value", 0.0); refTemp = p.get<RealType>("Reference Temperature", 0.0); this->registerSacadoParameter("dSdT Value", paramLib); } else { isThermoElastic=false; dSdT_value=0.0; } this->addEvaluatedField(satMod); this->setName("Saturation Modulus"+PHX::typeAsString<EvalT>()); }
std::pair<size_t, RedisParser::ParseResult> RedisParser::parseChunk(const char *ptr, size_t size) { size_t i = 0; for(; i < size; ++i) { char c = ptr[i]; switch(state) { case Start: buf.clear(); switch(c) { case stringReply: state = String; break; case errorReply: state = ErrorString; break; case integerReply: state = Integer; break; case bulkReply: state = BulkSize; bulkSize = 0; break; case arrayReply: state = ArraySize; break; default: state = Start; return std::make_pair(i + 1, Error); } break; case String: if( c == '\r' ) { state = StringLF; } else if( isChar(c) && !isControl(c) ) { buf.push_back(c); } else { state = Start; return std::make_pair(i + 1, Error); } break; case ErrorString: if( c == '\r' ) { state = ErrorLF; } else if( isChar(c) && !isControl(c) ) { buf.push_back(c); } else { state = Start; return std::make_pair(i + 1, Error); } break; case BulkSize: if( c == '\r' ) { if( buf.empty() ) { state = Start; return std::make_pair(i + 1, Error); } else { state = BulkSizeLF; } } else if( isdigit(c) || c == '-' ) { buf.push_back(c); } else { state = Start; return std::make_pair(i + 1, Error); } break; case StringLF: if( c == '\n') { state = Start; valueStack.push(buf); return std::make_pair(i + 1, Completed); } else { state = Start; return std::make_pair(i + 1, Error); } break; case ErrorLF: if( c == '\n') { state = Start; RedisValue::ErrorTag tag; valueStack.push(RedisValue(buf, tag)); return std::make_pair(i + 1, Completed); } else { state = Start; return std::make_pair(i + 1, Error); } break; case BulkSizeLF: if( c == '\n' ) { // TODO optimize me std::string tmp(buf.begin(), buf.end()); bulkSize = strtol(tmp.c_str(), 0, 10); buf.clear(); if( bulkSize == -1 ) { state = Start; valueStack.push(RedisValue()); // Nil return std::make_pair(i + 1, Completed); } else if( bulkSize == 0 ) { state = BulkCR; } else if( bulkSize < 0 ) { state = Start; return std::make_pair(i + 1, Error); } else { buf.reserve(bulkSize); long int available = size - i - 1; long int canRead = std::min(bulkSize, available); if( canRead > 0 ) { buf.assign(ptr + i + 1, ptr + i + canRead + 1); } i += canRead; if( bulkSize > available ) { bulkSize -= canRead; state = Bulk; return std::make_pair(i + 1, Incompleted); } else { state = BulkCR; } } } else { state = Start; return std::make_pair(i + 1, Error); } break; case Bulk: { assert( bulkSize > 0 ); long int available = size - i; long int canRead = std::min(available, bulkSize); buf.insert(buf.end(), ptr + i, ptr + canRead); bulkSize -= canRead; i += canRead - 1; if( bulkSize > 0 ) { return std::make_pair(i + 1, Incompleted); } else { state = BulkCR; if( size == i + 1 ) { return std::make_pair(i + 1, Incompleted); } } break; } case BulkCR: if( c == '\r') { state = BulkLF; } else { state = Start; return std::make_pair(i + 1, Error); } break; case BulkLF: if( c == '\n') { state = Start; valueStack.push(buf); return std::make_pair(i + 1, Completed); } else { state = Start; return std::make_pair(i + 1, Error); } break; case ArraySize: if( c == '\r' ) { if( buf.empty() ) { state = Start; return std::make_pair(i + 1, Error); } else { state = ArraySizeLF; } } else if( isdigit(c) || c == '-' ) { buf.push_back(c); } else { state = Start; return std::make_pair(i + 1, Error); } break; case ArraySizeLF: if( c == '\n' ) { // TODO optimize me std::string tmp(buf.begin(), buf.end()); long int arraySize = strtol(tmp.c_str(), 0, 10); buf.clear(); std::vector<RedisValue> array; if( arraySize == -1 || arraySize == 0) { state = Start; valueStack.push(array); // Empty array return std::make_pair(i + 1, Completed); } else if( arraySize < 0 ) { state = Start; return std::make_pair(i + 1, Error); } else { array.reserve(arraySize); arrayStack.push(arraySize); valueStack.push(array); state = Start; if( i + 1 != size ) { std::pair<size_t, ParseResult> parseResult = parseArray(ptr + i + 1, size - i - 1); parseResult.first += i + 1; return parseResult; } else { return std::make_pair(i + 1, Incompleted); } } } else { state = Start; return std::make_pair(i + 1, Error); } break; case Integer: if( c == '\r' ) { if( buf.empty() ) { state = Start; return std::make_pair(i + 1, Error); } else { state = IntegerLF; } } else if( isdigit(c) || c == '-' ) { buf.push_back(c); } else { state = Start; return std::make_pair(i + 1, Error); } break; case IntegerLF: if( c == '\n' ) { // TODO optimize me std::string tmp(buf.begin(), buf.end()); long int value = strtol(tmp.c_str(), 0, 10); buf.clear(); valueStack.push(value); state = Start; return std::make_pair(i + 1, Completed); } else { state = Start; return std::make_pair(i + 1, Error); } break; default: state = Start; return std::make_pair(i + 1, Error); } } return std::make_pair(i, Incompleted); }
QPolygonF minigis::shiftPolygonDifficult(const QPolygonF &origin, qreal delta, bool closed) { if (qFuzzyIsNull(delta)) return origin; QPolygonF path = origin; QPolygonF norm; // ----------------- Поиск нормалей к оригинальному полигону int N = path.size(); for (int i = 1; i < N; ++i) { QPointF vect = path.at(i) - path.at(i-1); double len = lengthR2(vect); if (qFuzzyIsNull(len)) { path.remove(i); --N; --i; continue; } vect /= len; norm.append(QPointF(vect.y() * delta, -vect.x() * delta)); } // ---- if (closed) { QPointF vect = path.first() - path.last(); double len = lengthR2(vect); if (qFuzzyIsNull(len)) path.remove(path.size() - 1); else { vect /= len; norm.append(QPointF(vect.y() * delta, -vect.x() * delta)); } } // ------------------ QVector<QLineF> lines; // -------------------------- Построение смещенных линий for (int i = 1; i < path.size(); ++i) lines.append(QLineF(path.at(i) + norm.at(i-1), path.at(i-1) + norm.at(i-1))); // ---- if (closed) lines.append(QLineF(path.first() + norm.last(), path.last() + norm.last())); // ------------------ QPolygonF shell; if (lines.isEmpty()) return shell; // -------------------------- Построение смещенного полигона N = lines.size(); for (int i = 1; i < N; ++i) { QPointF tmp; QLineF::IntersectType type = lines.at(i-1).intersect(lines.at(i), &tmp); qreal ang = lines.at(i-1).angleTo(lines.at(i)); if (type != QLineF::NoIntersection) shell.append(tmp); else { if (qFuzzyCompare(ang, qreal(180))) shell.append(lines.at(i).p2() - 2 * norm.at(i)); shell.append(lines.at(i).p2()); } } // ---- if (closed) { QPointF tmp; QLineF::IntersectType type = lines.last().intersect(lines.first(), &tmp); qreal ang = lines.last().angleTo(lines.first()); if (type != QLineF::NoIntersection) shell.append(tmp); else { if (qFuzzyCompare(ang, qreal(180))) shell.append(lines.first().p2() - 2 * norm.first()); shell.append(lines.first().p2()); } shell.append(shell.first()); } else { shell.prepend(lines.first().p2()); shell.append(lines.last().p1()); } // ------------------ // -------------------------- обрезание острых углов int k = 0; N = lines.size(); for (int i = 1; i < N; ++i) { double ang = lines.at(i-1).angleTo(lines.at(i)); bool first = (120 < ang && ang < 180 && delta < 0) || (180 < ang && ang < 240 && delta > 0); bool second = (120 < ang && ang < 180 && delta > 0) || (180 < ang && ang < 240 && delta < 0); if (first) { int num = closed ? 1 : 0; QPointF v = shell.at(i + k - num) - path.at(i); v /= lengthR2(v); QPointF start = path.at(i) + v * qAbs(delta); QLineF tmp(start, start + QPointF(-v.y(), v.x())); QPointF a; if (tmp.intersect(lines.at(i ), &a) != QLineF::NoIntersection) shell.replace(i + k - num, a); if (tmp.intersect(lines.at(i-1), &a) != QLineF::NoIntersection) shell.insert(i + k - num, a); ++k; } else if (second) { // TODO: cut corner } } // ---- if (closed) { double ang = lines.last().angleTo(lines.first()); int num = lines.size(); int shellNum = (num + k - 1) % shell.size(); bool first = (120 < ang && ang < 180 && delta < 0) || (180 < ang && ang < 240 && delta > 0); bool second = (180 < ang && ang < 240 && delta < 0) || (120 < ang && ang < 180 && delta > 0); if (first) { QPointF v = shell.at(shellNum) - path.at(num % path.size()); v /= lengthR2(v); QPointF start = path.at(num % path.size()) + v * qAbs(delta); QLineF tmp(start, start + QPointF(-v.y(), v.x())); QPointF a; if (tmp.intersect(lines.first(), &a) != QLineF::NoIntersection) shell.replace(shellNum, a); if (tmp.intersect(lines.last() , &a) != QLineF::NoIntersection) shell.insert(shellNum, a); } else if (second) { // TODO: cut corner } } // ------------------ return shell; }
void VideoFluids::trackVelocity(Matrix& Zn1,Matrix& Zn,Matrix& U,Matrix& V) { Matrix Zx(height,width),Zy(height,width),ZZx(height,width),ZZy(height,width),Zt(height,width),ZZt(height,width),ZZtx(height,width),ZZty(height,width); Matrix Au1(height,width),Au2(height,width),Av1(height,width),Av2(height,width); Matrix Z2x(height,width),Z2y(height,width),Z2(height,width); Matrix Cu(height,width),Cv(height,width); Matrix tmp(height,width),tmp1(height,width); Matrix U_old(height,width),V_old(height,width),Ux(height,width),Uy(height,width),Vx(height,width),Vy(height,width),Uax(height,width),Uay(height,width),Vax(height,width),Vay(height,width),Uxy(height,width),Vxy(height,width); Matrix Coe(height,width); Zt = Zn; Zt -= Zn1; DotMul(Zn,Zt,ZZt); Zn.output("Zn.txt"); Zn1.output("Zn1.txt"); Zt.output("Zt.txt"); Partial(ZZt,ZZtx,AXIS_X); Partial(ZZt,ZZty,AXIS_Y); Partial(Zn,Zx,AXIS_X); Partial(Zn,Zy,AXIS_Y); DotMul(Zn,Zx,ZZx); DotMul(Zn,Zy,ZZy); DotMul(Zx,Zx,Au1); Partial(ZZx,tmp,AXIS_X); Au1-=tmp; DotMul(Zn,Zn,tmp); Au1+=tmp; Au1+=2*alpha*alpha; DotMul(Zx,Zy,Au2); Partial(ZZy,tmp,AXIS_X); Au2-=tmp; DotMul(Zx,Zy,Av1); Partial(ZZx,tmp,AXIS_Y); Av1-=tmp; DotMul(Zy,Zy,Av2); Partial(ZZy,tmp,AXIS_Y); Av2-=tmp; DotMul(Zn,Zn,tmp); Av2+=tmp; Av2+=2*alpha*alpha; DotMul(Zn,Zn,Z2); Partial(Z2,Z2x,AXIS_X); Partial(Z2,Z2y,AXIS_Y); for (int i = 0;i<height;i++) for (int j = 0;j<width;j++) Coe[i][j] = 1.0/(Au1[i][j]*Av2[i][j]-Au2[i][j]*Av1[i][j]); U = 0.0; V = 0.0; for (int iter_time = 0;iter_time<iterationTime;iter_time++) { V_old = V; U_old = U; Partial(U,Ux,AXIS_X); Partial(U,Uy,AXIS_Y); Partial(V,Vx,AXIS_X); Partial(V,Vy,AXIS_Y); Partial(Vx,Vxy,AXIS_Y); Partial(Ux,Uxy,AXIS_Y); Average(U,Uax,AXIS_X); Average(U,Uay,AXIS_Y); Average(V,Vax,AXIS_X); Average(V,Vay,AXIS_Y); DotMul(Z2x,Ux,Cu); DotMul(ZZy,Vx,tmp); Cu += tmp; tmp = ZZx*-1; tmp+=Z2x; DotMul(tmp,Vy,tmp1); Cu+=tmp1; tmp = Z2; tmp+=alpha*alpha; DotMul(tmp,Uax,tmp1); Cu+=tmp1; tmp1=Uay; tmp1*=alpha*alpha; Cu+=tmp1; DotMul(Z2,Vxy,tmp1); Cu+=tmp1; DotMul(Zx,Zt,tmp); Cu-=tmp; Cu+=ZZtx; DotMul(Z2y,Vy,Cv); DotMul(ZZx,Uy,tmp); Cv += tmp; tmp = ZZy; tmp*=-1; tmp+=Z2y; DotMul(tmp,Ux,tmp1); Cv+=tmp1; tmp = Z2; tmp+=alpha*alpha; DotMul(tmp,Vay,tmp1); Cv+=tmp1; tmp1=Vax; tmp1*=alpha*alpha; Cv+=tmp1; DotMul(Z2,Uxy,tmp1); Cv+=tmp1; DotMul(Zy,Zt,tmp); Cv-=tmp; Cv+=ZZty; for (int i = 0;i<height;i++) for (int j = 0;j<width;j++) { U[i][j] = Coe[i][j]*(Av2[i][j]*Cu[i][j]-Au2[i][j]*Cv[i][j]); V[i][j] = Coe[i][j]*(-Av1[i][j]*Cu[i][j]+Au1[i][j]*Cv[i][j]); } for (int i = 0;i<height;i++) { U[i][0] = U[i][1]; U[i][width-1] = U[i][width-2]; V[i][0] = V[i][1]; V[i][width-1] =V[i][width-2]; } for (int i = 0;i<width;i++) { U[0][i] = U[1][i]; U[height-1][i] = U[height-2][i]; V[0][i] = V[1][i]; V[height-1][i] =V[height-2][i]; } FILE* fp; // Au1.output("Au1.txt"); // Au2.output("Au2.txt"); // Av1.output("Av1.txt"); // Av2.output("Av2.txt"); // Cu.output("Cu.txt"); // Cv.output("Cv.txt"); float d1 = Difference(U,U_old); float d2 = Difference(V,V_old); // U.output("U.txt"); // U_old.output("U_old.txt"); // V.output("V.txt"); cout<<d1<<' '<<d2<<endl; if (d1<iterationTorlerance && d2<iterationTorlerance) break; } U.output("U.txt"); cv::Mat showV(height,width,CV_8UC3); float lowv=10000000,lowu=10000000,highu=-10000000,highv=-1000000; for(int j=0;j<height;j++){ for(int k=0;k<width;k++){ if(U[j][k]>highu) highu=U[j][k]; if(U[j][k]<lowu) lowu=U[j][k]; if(V[j][k]>highv) highv=V[j][k]; if(V[j][k]<lowv) lowv=V[j][k]; } } for(int j=0;j<height;j++){ for(int k=0;k<width;k++){ //printf("%d %d\n",j,k); //if(sfs_list[i][j][k]<low) // showH.at<uchar>(j,k)=0; //else float u=(U[j][k]-lowu)/(highu-lowu); float v=(V[j][k]-lowv)/(highv-lowv); if(u>0.5) showV.at<cv::Vec3b>(j,k)[2]=255; else showV.at<cv::Vec3b>(j,k)[2]=255*u; if(v>0.5){ showV.at<cv::Vec3b>(j,k)[0]=255; showV.at<cv::Vec3b>(j,k)[1]=255*(1-v); } else{ showV.at<cv::Vec3b>(j,k)[1]=255; showV.at<cv::Vec3b>(j,k)[0]=255*v; } } } cv::imwrite("testV.bmp",showV); printf("show you"); }
QPolygonF minigis::shiftPolygon(const QPolygonF &origin, qreal delta, bool direction, QList<int> *doubleDots) { if (doubleDots) doubleDots->clear(); delta = qAbs(delta); QVector<QLineF> lines; for (int i = 1; i < origin.size(); ++i) { QLineF l(origin.at(i - 1), origin.at(i)); QLineF norm = l.normalVector(); qreal len = lengthR2(l.p2() - l.p1()); QPointF normVect = (norm.p2() - norm.p1()) / len; lines.append(l.translated(normVect * (direction ? -delta : delta))); } QPolygonF path; QVectorIterator<QLineF> it(lines); QLineF base = it.next(); int pointNumber = 0; path.append(base.p1()); while (it.hasNext()) { QLineF next = it.next(); ++pointNumber; double ang = base.angleTo(next); bool side = ang < 180 ? direction : !direction; if (ang > 180) ang = 360 - ang; if (qFuzzyIsNull(ang)) { // "I" + // линия-продолжение path.append(base.p2()); base.setP2(next.p2()); } else if (qFuzzyIsNull(ang - 180)) { // "IV" ? // коллинеарная линия в обраную строную // TODO: mb we don't need this path.append(base.p2()); path.append(next.p1()); base = next; if (doubleDots) doubleDots->append(pointNumber); } else if (ang < 120) { // "II" QPointF p; base.intersect(next, &p); if (side) { // "A" + // линия снаружи path.append(p); base = next; } else { // "B" - // линия внутри // TODO: correct algo path.append(p); base = next; } } else { // "III" if (side) { // "A" + // линия снаружи с острым углом QPointF p; base.intersect(next, &p); QPointF start = origin.at(pointNumber); QPointF vect = p - start; vect *= delta / lengthR2(vect); QPointF norm(vect.y(), -vect.x()); QLineF tmp(start + vect, start + vect + norm); base.intersect(tmp, &p); path.append(p); next.intersect(tmp, &p); path.append(p); base = next; if (doubleDots) doubleDots->append(pointNumber); } else { // "B" - // линия внутри с острым углом // TODO: correct algo QPointF p; base.intersect(next, &p); path.append(p); base = next; } } } path.append(base.p2()); return path; }
MixGaussProb::MixGaussProb( const MatrixXf& data, const MultiD& mu, const MultiD& Sigma, const MatrixXf& _mixmat ) { MatrixXf mixmat = _mixmat; /* if iscolumn(mu) d = length(mu); Q = 1; M = 1; elseif ismatrix(mu) [~, Q] = size(mu); M = 1; else [~, Q M] = size(mu); end*/ //we always have 3D mu size_t Q = mu(0,0).cols(); // not safe size_t M = mu.rows(); size_t T = data.cols(); //[d T] = size(data); if(mixmat.rows() == 0 && mixmat.cols() == 0) { // if nargin < 4, mixmat = ones(Q,1); end mixmat = MatrixXf::Ones(Q, 1); } //sigma always 4d, so implement % general case B2.resize(T,1); //B2 = zeros(Q,M,T); for(size_t i = 0; i < T; ++i) { B2(i, 0) = MatrixXf::Zero(Q, M); } #ifdef DEBUG_GAUSSIAN_PROB print4DMatrix(mu); #endif for(size_t j = 0; j < Q; ++j) { //for j=1:Q for(size_t k = 0; k < M; ++k) { //for k=1:M MatrixXf sig = Sigma(j, k); MatrixXf m = mu(k, 0).col(j); MatrixXf t = gaussianProb(data, m, sig); for(size_t index = 0; index < (size_t)t.rows(); ++index) { B2(index, 0)(j, k) = t(index, 0); //B2(j,k,:) = gaussian_prob(data, mu(:,j,k), Sigma(:,:,j,k)); } } } B = MatrixXf::Zero(Q,T);//B = zeros(Q,T); if(Q < T) { for(size_t q = 0; q < Q; ++q) { MatrixXf tmp(M, T); for(size_t i = 0; i < T; ++i) { MatrixXf B2i1 = B2(i,0); tmp.col(i) = B2(i,0).row(q); } //permute(B2(q,:,:), [2 3 1]) B.row(q) = mixmat.row(q) * tmp; // B(q,:) = mixmat(q,:) * permute(B2(q,:,:), [2 3 1]); % vector * matrix sums over m } } else { std::string unimplemented_code = "for t=1:T\nB(:,t) = sum(mixmat .* B2(:,:,t), 2); % sum over m\nend\n"; throw std::runtime_error(unimplemented_code); } #ifdef DEBUG_MIX_GAUSS_PROB std::cout << B << std::endl; print4DMatrix(B2); #endif }
case_converting_iterator operator ++(int) { case_converting_iterator tmp(*this); ++*this; return tmp; }
int main(int argc, char* argv[]) { if (argc < 5) { std::cout << "program " << argv[0] << " takes a *layered* mesh file and closed polylines from a geometry and " "computes the surface mesh nodes within the closed polyline" << std::endl; std::cout << "Usage: " << std::endl << argv[0] << "\n\t--mesh ogs_meshfile\n\t--geometry ogs_geometry_as_gli_file" << std::endl; return -1; } // *** read mesh std::string tmp(argv[1]); if (tmp.find("--mesh") == std::string::npos) { std::cout << "could not extract mesh file name" << std::endl; return -1; } tmp = argv[2]; std::string file_base_name(tmp); if (tmp.find(".msh") != std::string::npos) file_base_name = tmp.substr(0, tmp.size() - 4); std::vector<MeshLib::CFEMesh*> mesh_vec; FEMRead(file_base_name, mesh_vec); if (mesh_vec.empty()) { std::cerr << "could not read mesh from file " << std::endl; return -1; } MeshLib::CFEMesh* mesh(mesh_vec[mesh_vec.size() - 1]); mesh->ConstructGrid(); // extract path std::string path; BaseLib::extractPath(argv[2], path); // *** read geometry tmp = argv[3]; if (tmp.find("--geometry") == std::string::npos) { std::cout << "could not extract geometry file name" << std::endl; return -1; } GEOLIB::GEOObjects* geo(new GEOLIB::GEOObjects); tmp = argv[4]; std::string unique_name; std::vector<std::string> error_strings; FileIO::readGLIFileV4(tmp, geo, unique_name, error_strings); // { // const std::vector<GEOLIB::Point*>* pnts (geo->getPointVec (tmp)); // if (pnts) { // std::string fname ("MeshIDs.txt"); // std::ofstream out (fname.c_str()); // // std::string fname_gli ("MeshNodesAsPnts.gli"); // std::ofstream pnt_out (fname_gli.c_str()); // pnt_out << "#POINTS" << std::endl; // // MeshLib::ExtractMeshNodes extract_mesh_nodes (mesh); // // const size_t n_pnts (pnts->size()); // for (size_t k(0); k<n_pnts; k++) { // extract_mesh_nodes.writeNearestMeshNodeToPoint (out, pnt_out, *((*pnts)[k])); // } // pnt_out << "#STOP" << std::endl; // } // return 0; // } // *** get Polygon const std::vector<GEOLIB::Polyline*>* plys(geo->getPolylineVec(unique_name)); if (!plys) { std::cout << "could not get vector of polylines" << std::endl; delete mesh; delete geo; return -1; } std::vector<size_t> mesh_ids; // size_t ply_id (0); // size_t layer(1); // getMeshNodesFromLayerAlongPolyline(mesh, geo, unique_name, ply_id, layer, mesh_ids); // writeMeshNodes(mesh, mesh_ids, "MeshIDs.txt", "MeshNodesAsPoints.gli", true); //*** extract surface out of mesh MeshLib::ExtractMeshNodes extract_mesh_nodes(mesh); // // *** generate a polygon from polyline //// std::vector<GEOLIB::Polyline*> polylines; // const size_t n_plys (plys->size()); // for (size_t k(0); k < n_plys; k++) // { // bool closed ((*plys)[k]->isClosed()); // if (!closed) // { // std::cout << "converting polyline " << k << " to closed polyline" << std::endl; // GEOLIB::Polygon* polygon(NULL); // extract_mesh_nodes.getPolygonFromPolyline(*((*plys)[k]), geo, unique_name, polygon); //// polylines.push_back (polygon); //// geo->appendPolylineVec (polylines, unique_name); // std::string *polygon_name(new std::string); // geo->getPolylineVecObj(unique_name)->getNameOfElementByID(k, *polygon_name); // (*polygon_name) += "-Polygon"; // geo->getPolylineVecObj(unique_name)->push_back(polygon, polygon_name); //// polylines.clear(); // } // } // // FileIO::writeGLIFileV4 ("New.gli", unique_name, *geo); // *** search mesh nodes for direct assigning bc, st or ic const size_t n_plys(plys->size()); for (size_t k(0); k < n_plys; k++) { bool closed((*plys)[k]->isClosed()); if (!closed) { std::cout << "polyline " << k << " is not closed" << std::endl; } else { std::string fname(path + "MeshIDs.txt"); std::ofstream out(fname.c_str()); std::string fname_gli(path + "MeshNodesAsPnts.gli"); std::ofstream pnt_out(fname_gli.c_str()); pnt_out << "#POINTS" << std::endl; GEOLIB::Polygon polygon(*((*plys)[k])); // extract_mesh_nodes.writeMesh2DNodeIDAndArea (out, pnt_out, polygon); extract_mesh_nodes.writeTopSurfaceMeshNodeIDs(out, pnt_out, polygon); // write all nodes - not only the surface nodes // extract_mesh_nodes.writeMeshNodeIDs (out, pnt_out, polygon); pnt_out << "#STOP" << std::endl; out.close(); pnt_out.close(); } } // *** for Model Pipiripau // std::vector<GEOLIB::Polygon*> holes; // size_t bounding_polygon_id(0); // while (bounding_polygon_id < n_plys && ! (*plys)[bounding_polygon_id]->isClosed()) { // bounding_polygon_id++; // } // // for (size_t k(bounding_polygon_id+1); k<n_plys; k++) { // bool closed ((*plys)[k]->isClosed()); // if (!closed) { // std::cout << "polyline " << k << " is not closed" << std::endl; // } else { // holes.push_back (new GEOLIB::Polygon(*(((*plys)[k])))); // } // } // extract_mesh_nodes.writeMesh2DNodeIDAndArea (out, pnt_out, GEOLIB::Polygon((*((*plys)[bounding_polygon_id]))), // holes); // for (size_t k(0); k<holes.size(); k++) { // delete holes[k]; // } // out << "#STOP" << std::endl; // out.close(); // // pnt_out << "#STOP" << std::endl; // pnt_out.close (); delete mesh; delete geo; return 0; }
guardt &operator |= (guardt &g1, const guardt &g2) { if(g2.is_false() || g1.is_true()) return g1; if(g1.is_false() || g2.is_true()) { g1=g2; return g1; } if(g1.id()!=ID_and || g2.id()!=ID_and) { exprt tmp(g2); tmp.make_not(); if(tmp==g1) g1.make_true(); else g1=or_exprt(g1, g2); // TODO: make simplify more capable and apply here return g1; } // find common prefix sort_and_join(g1); guardt g2_sorted=g2; sort_and_join(g2_sorted); exprt::operandst &op1=g1.operands(); const exprt::operandst &op2=g2_sorted.operands(); exprt::operandst n_op1, n_op2; n_op1.reserve(op1.size()); n_op2.reserve(op2.size()); exprt::operandst::iterator it1=op1.begin(); for(exprt::operandst::const_iterator it2=op2.begin(); it2!=op2.end(); ++it2) { while(it1!=op1.end() && *it1<*it2) { n_op1.push_back(*it1); it1=op1.erase(it1); } if(it1!=op1.end() && *it1==*it2) ++it1; else n_op2.push_back(*it2); } while(it1!=op1.end()) { n_op1.push_back(*it1); it1=op1.erase(it1); } if(n_op2.empty()) return g1; // end of common prefix exprt and_expr1=conjunction(n_op1); exprt and_expr2=conjunction(n_op2); g1=conjunction(op1); exprt tmp(and_expr2); tmp.make_not(); if(tmp!=and_expr1) { if(and_expr1.is_true() || and_expr2.is_true()) { } else // TODO: make simplify more capable and apply here g1.add(or_exprt(and_expr1, and_expr2)); } return g1; }
C operator+ (const C& lhs, const C& rhs) { C tmp (lhs); tmp.insert (tmp.end (), rhs.begin (), rhs.end ()); return tmp; };
//------------------------------------------------------------------------------ void CTsmMatrixBuilder::BuildMatrix(CShadowClipper* clipper) { //这个函数优化空间很大,把矩阵下面手动算完,推导出公式最后放到程序中写成一个简单结果就行 //目前这种没有必要的矩阵乘法太多,有时间建议优化下 Ast(NULL != m_Camera); Ast(NULL != clipper); m_ViewMatrix = m_Camera->getViewMatrix(); // get the near and the far plane (points) in eye space. CVector3f frustumPnts[CFrustum::FrustumCornerNum]; CFrustum eyeFrustum(m_Camera->getProjectionMatrix()); for (index_t i = 0; i < 4; ++i) { frustumPnts[i] = *(CVector3f*)&(eyeFrustum.GetCorner((i<<1))); // far plane frustumPnts[i+4] = *(CVector3f*)&(eyeFrustum.GetCorner((i<<1) | 0x1)); // near plane } // we need to transform the eye into the light's post-projective space. // however, the sun is a directional light, so we first need to find an appropriate // rotate/translate matrix, before constructing an ortho projection. // this matrix is a variant of "light space" from LSPSMs, with the Y and Z axes permuted CVector3f leftVector, upVector, viewVector; const CVector3f eyeVector( 0.f, 0.f, -1.f ); // eye is always -Z in eye space // lightDir is defined in eye space, so xform it upVector = m_LightDir; upVector.MultiplyNormal(m_ViewMatrix); leftVector = upVector.Cross(eyeVector); leftVector.Normalize(); viewVector = upVector.Cross(leftVector); CMatrix lightSpaceBasis; lightSpaceBasis._11 = leftVector.x,lightSpaceBasis._12 = viewVector.x,lightSpaceBasis._13 = -upVector.x,lightSpaceBasis._14 = 0.f; lightSpaceBasis._21 = leftVector.y,lightSpaceBasis._22 = viewVector.y,lightSpaceBasis._23 = -upVector.y,lightSpaceBasis._24 = 0.f; lightSpaceBasis._31 = leftVector.z,lightSpaceBasis._32 = viewVector.z,lightSpaceBasis._33 = -upVector.z,lightSpaceBasis._34 = 0.f; lightSpaceBasis._41 = 0.f,lightSpaceBasis._42 = 0.f,lightSpaceBasis._43 = 0.f,lightSpaceBasis._44 = 1.f; // rotate the view frustum into light space for ( int i = 0; i< CFrustum::FrustumCornerNum; ++i ) frustumPnts[i] *= lightSpaceBasis; // build an off-center ortho projection that translates and scales the eye frustum's 3D AABB to the unit cube CAxisAlignedBox frustumBox; for (index_t i = 0; i < CFrustum::FrustumCornerNum; ++i) frustumBox.mergeBox(frustumPnts[i]); const CAxisAlignedBox& casterBox = clipper->GetCastersAABB(lightSpaceBasis); float min_z = min(frustumBox.getMinimum().z, casterBox.getMinimum().z); float max_z = max(frustumBox.getMaximum().z, casterBox.getMaximum().z); // virtually forward if ( min_z <= 0.f ) { CMatrix lightSpaceTranslate; lightSpaceTranslate.SetTranslate( 0.f, 0.f, -min_z + 1.f ); max_z = -min_z + max_z + 1.f; min_z = 1.f; lightSpaceBasis *= lightSpaceTranslate; for ( int i = 0; i< CFrustum::FrustumCornerNum; ++i ) frustumPnts[i] *= lightSpaceTranslate; frustumBox.setNull(); for (index_t i = 0; i < CFrustum::FrustumCornerNum; ++i) frustumBox.mergeBox(frustumPnts[i]); } // build orthogonal projection matrix CMatrix lightSpaceOrtho; lightSpaceOrtho.SetOrthoOffCenterLH(frustumBox.getMinimum().x, frustumBox.getMaximum().x, frustumBox.getMinimum().y, frustumBox.getMaximum().y, min_z, max_z ); // transform the view frustum by the new matrix for ( int i = 0; i< CFrustum::FrustumCornerNum; ++i ) frustumPnts[i] *= lightSpaceOrtho; CVector2f centerPts[2]; // near plane centerPts[0].x = 0.25f * (frustumPnts[4].x + frustumPnts[5].x + frustumPnts[6].x + frustumPnts[7].x); centerPts[0].y = 0.25f * (frustumPnts[4].y + frustumPnts[5].y + frustumPnts[6].y + frustumPnts[7].y); // far plane centerPts[1].x = 0.25f * (frustumPnts[0].x + frustumPnts[1].x + frustumPnts[2].x + frustumPnts[3].x); centerPts[1].y = 0.25f * (frustumPnts[0].y + frustumPnts[1].y + frustumPnts[2].y + frustumPnts[3].y); CVector2f centerOrig = (centerPts[0] + centerPts[1])*0.5f; CMatrix xlate_center(1.f, 0.f, 0.f, 0.f, 0.f, 1.f, 0.f, 0.f, 0.f, 0.f, 1.f, 0.f, -centerOrig.x, -centerOrig.y, 0.f, 1.f ); float half_center_len = CVector2f(centerPts[1] - centerOrig).Mag(); float x_len = centerPts[1].x - centerOrig.x; float y_len = centerPts[1].y - centerOrig.y; float cos_theta = x_len / half_center_len; float sin_theta = y_len / half_center_len; CMatrix rot_center( cos_theta, -sin_theta, 0.f, 0.f, sin_theta, cos_theta, 0.f, 0.f, 0.f, 0.f, 1.f, 0.f, 0.f, 0.f, 0.f, 1.f ); // this matrix transforms the center line to y=0. // since Top and Base are orthogonal to Center, we can skip computing the convex hull, and instead // just find the view frustum X-axis extrema. The most negative is Top, the most positive is Base // Point Q (trapezoid projection point) will be a point on the y=0 line. m_ProjMatrix = xlate_center * rot_center; for ( int i = 0; i< CFrustum::FrustumCornerNum; ++i ) frustumPnts[i] *= m_ProjMatrix; CAxisAlignedBox frustumAABB2D; for (index_t i = 0; i < CFrustum::FrustumCornerNum; ++i) frustumAABB2D.mergeBox(frustumPnts[i]); float x_scale = max( fabsf(frustumAABB2D.getMaximum().x), fabsf(frustumAABB2D.getMinimum().x) ); float y_scale = max( fabsf(frustumAABB2D.getMaximum().y), fabsf(frustumAABB2D.getMinimum().y) ); x_scale = 1.f/x_scale; y_scale = 1.f/y_scale; // maximize the area occupied by the bounding box CMatrix scale_center(x_scale, 0.f, 0.f, 0.f, 0.f, y_scale, 0.f, 0.f, 0.f, 0.f, 1.f, 0.f, 0.f, 0.f, 0.f, 1.f); m_ProjMatrix *= scale_center; // scale the frustum AABB up by these amounts (keep all values in the same space) frustumAABB2D.scaleBox( CVector3f( x_scale, y_scale, 1.0f ) ); // compute eta. float lambda = frustumAABB2D.getMaximum().x - frustumAABB2D.getMinimum().x; float delta_proj = m_FocusRegion * lambda; //focusPt.x - frustumAABB2D.minPt.x; const float xi = -0.6f; // 80% line float eta = (lambda*delta_proj*(1.f+xi)) / (lambda*(1.f-xi)-2.f*delta_proj); // compute the projection point a distance eta from the top line. this point is on the center line, y=0 CVector2f projectionPtQ( frustumAABB2D.getMaximum().x + eta, 0.f ); // find the maximum slope from the projection point to any point in the frustum. this will be the // projection field-of-view float max_slope = -1e32f; float min_slope = 1e32f; for ( index_t i = 0; i < CFrustum::FrustumCornerNum; ++i ) { CVector2f tmp( frustumPnts[i].x*x_scale, frustumPnts[i].y*y_scale ); float x_dist = tmp.x - projectionPtQ.x; if ( !(gIsZero(tmp.y) || gIsZero(x_dist))) { max_slope = max(max_slope, tmp.y/x_dist); min_slope = min(min_slope, tmp.y/x_dist); } } float xn = eta; float xf = lambda + eta; CMatrix ptQ_xlate(-1.f, 0.f, 0.f, 0.f, 0.f, 1.f, 0.f, 0.f, 0.f, 0.f, 1.f, 0.f, projectionPtQ.x, 0.f, 0.f, 1.f ); m_ProjMatrix *= ptQ_xlate; // this shear balances the "trapezoid" around the y=0 axis (no change to the projection pt position) // since we are redistributing the trapezoid, this affects the projection field of view (shear_amt) float shear_amt = (max_slope + fabsf(min_slope))*0.5f - max_slope; max_slope = max_slope + shear_amt; CMatrix trapezoid_shear( 1.f, shear_amt, 0.f, 0.f, 0.f, 1.f, 0.f, 0.f, 0.f, 0.f, 1.f, 0.f, 0.f, 0.f, 0.f, 1.f ); m_ProjMatrix *= trapezoid_shear; float z_aspect = (frustumBox.getMaximum().z-frustumBox.getMinimum().z) / (frustumAABB2D.getMaximum().y-frustumAABB2D.getMinimum().y); // perform a 2DH projection to 'unsqueeze' the top line. CMatrix trapezoid_projection( xf/(xf-xn), 0.f, 0.f, 1.f, 0.f, 1.f/max_slope, 0.f, 0.f, 0.f, 0.f, 1.f/(z_aspect*max_slope), 0.f, -xn*xf/(xf-xn),0.f, 0.f, 0.f ); m_ProjMatrix *= trapezoid_projection; // the x axis is compressed to [0..1] as a result of the projection, so expand it to [-1,1] CMatrix biasedScaleX( 2.f, 0.f, 0.f, 0.f, 0.f, 1.f, 0.f, 0.f, 0.f, 0.f, 1.f, 0.f, -1.f, 0.f, 0.f, 1.f ); m_ProjMatrix *= biasedScaleX; m_ProjMatrix = lightSpaceOrtho * m_ProjMatrix; m_ProjMatrix = lightSpaceBasis * m_ProjMatrix; // now, focus on shadow receivers. m_ShadowMatrix = m_ViewMatrix * m_ProjMatrix; CAxisAlignedBox rcvrBox = clipper->GetCastersAABBWithProj(m_ShadowMatrix); rcvrBox.m_vMaximum.x = min( 1.f, rcvrBox.m_vMaximum.x ); rcvrBox.m_vMinimum.x = max(-1.f, rcvrBox.m_vMinimum.x ); rcvrBox.m_vMaximum.y = min( 1.f, rcvrBox.m_vMaximum.y ); rcvrBox.m_vMinimum.y = max(-1.f, rcvrBox.m_vMinimum.y ); float boxWidth = rcvrBox.m_vMaximum.x - rcvrBox.m_vMinimum.x; float boxHeight = rcvrBox.m_vMaximum.y - rcvrBox.m_vMinimum.y; // the receiver box is degenerate, this will generate specials (and there shouldn't be any shadows, anyway). if ( !(gIsZero(boxWidth) || gIsZero(boxHeight)) ) { // the divide by two's cancel out in the translation, but included for clarity float boxX = (rcvrBox.m_vMaximum.x+rcvrBox.m_vMinimum.x) / 2.f; float boxY = (rcvrBox.m_vMaximum.y+rcvrBox.m_vMinimum.y) / 2.f; CMatrix trapezoidUnitCube( 2.f/boxWidth, 0.f, 0.f, 0.f, 0.f, 2.f/boxHeight, 0.f, 0.f, 0.f, 0.f, 1.f, 0.f, -2.f*boxX/boxWidth, -2.f*boxY/boxHeight, 0.f, 1.f ); m_ProjMatrix *= trapezoidUnitCube; } m_ShadowMatrix = m_ViewMatrix * m_ProjMatrix; //set special texture matrix for shadow mapping float fOffsetX = 0.5f + (0.5f / (float)m_ShadowMapSize); float fOffsetY = 0.5f + (0.5f / (float)m_ShadowMapSize); CMatrix texCoordMatrix( 0.5f, 0.0f, 0.0f, 0.0f, 0.0f, -0.5f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, fOffsetX, fOffsetY, 0.0f, 1.0f ); m_ShadowMatrix *= texCoordMatrix; }
// add something to this string bool wxStringImpl::ConcatSelf(size_t nSrcLen, const wxStringCharType *pszSrcData, size_t nMaxLen) { STATISTICS_ADD(SummandLength, nSrcLen); nSrcLen = nSrcLen < nMaxLen ? nSrcLen : nMaxLen; // concatenating an empty string is a NOP if ( nSrcLen > 0 ) { wxStringData *pData = GetStringData(); size_t nLen = pData->nDataLength; // take special care when appending part of this string to itself: the code // below reallocates our buffer and this invalidates pszSrcData pointer so // we have to copy it in another temporary string in this case (but avoid // doing this unnecessarily) if ( pszSrcData >= m_pchData && pszSrcData < m_pchData + nLen ) { wxStringImpl tmp(pszSrcData, nSrcLen); return ConcatSelf(nSrcLen, tmp.m_pchData, nSrcLen); } size_t nNewLen = nLen + nSrcLen; // alloc new buffer if current is too small if ( pData->IsShared() ) { STATISTICS_ADD(ConcatHit, 0); // we have to allocate another buffer wxStringData* pOldData = GetStringData(); if ( !AllocBuffer(nNewLen) ) { // allocation failure handled by caller return false; } memcpy(m_pchData, pOldData->data(), nLen*sizeof(wxStringCharType)); pOldData->Unlock(); } else if ( nNewLen > pData->nAllocLength ) { STATISTICS_ADD(ConcatHit, 0); reserve(nNewLen); // we have to grow the buffer if ( capacity() < nNewLen ) { // allocation failure handled by caller return false; } } else { STATISTICS_ADD(ConcatHit, 1); // the buffer is already big enough } // should be enough space wxASSERT( nNewLen <= GetStringData()->nAllocLength ); // fast concatenation - all is done in our buffer memcpy(m_pchData + nLen, pszSrcData, nSrcLen*sizeof(wxStringCharType)); m_pchData[nNewLen] = wxT('\0'); // put terminating '\0' GetStringData()->nDataLength = nNewLen; // and fix the length } //else: the string to append was empty return true; }
Gregorian Gregorian::operator--(int){ Gregorian tmp(*this); --offset; return tmp; }