bool CLastFmManager::RequestRadioTracks() { unsigned int start = CTimeUtils::GetTimeMS(); CStdString url; CStdString html; url.Format("http://" + m_RadioBaseUrl + m_RadioBasePath + "/xspf.php?sk=%s&discovery=0&desktop=", m_RadioSession); { CFileCurl http; if (!http.Get(url, html)) { m_RadioSession.empty(); CLog::Log(LOGERROR, "LastFmManager: Connect to Last.fm to request tracks failed."); return false; } } //CLog::DebugLog("RequestRadioTracks: %s", html.c_str()); //parse playlist TiXmlDocument xmlDoc; xmlDoc.Parse(html); if (xmlDoc.Error()) { m_RadioSession.empty(); CLog::Log(LOGERROR, "LastFmManager: Unable to parse tracklist Error: %s", xmlDoc.ErrorDesc()); return false; } TiXmlElement* pRootElement = xmlDoc.RootElement(); if (!pRootElement ) { CLog::Log(LOGWARNING, "LastFmManager: No more tracks received"); m_RadioSession.empty(); return false; } TiXmlElement* pBodyElement = pRootElement->FirstChildElement("trackList"); if (!pBodyElement ) { CLog::Log(LOGWARNING, "LastFmManager: No more tracks received, no tracklist"); m_RadioSession.empty(); return false; } TiXmlElement* pTrackElement = pBodyElement->FirstChildElement("track"); if (!pTrackElement) { CLog::Log(LOGWARNING, "LastFmManager: No more tracks received, empty tracklist"); m_RadioSession.empty(); return false; } while (pTrackElement) { CFileItemPtr newItem(new CFileItem); TiXmlElement* pElement = pTrackElement->FirstChildElement("location"); if (pElement) { TiXmlNode* child = pElement->FirstChild(); if (child) { CStdString url = child->Value(); url.Replace("http:", "lastfm:"); newItem->m_strPath = url; } } pElement = pTrackElement->FirstChildElement("title"); if (pElement) { TiXmlNode* child = pElement->FirstChild(); if (child) { newItem->SetLabel(child->Value()); newItem->GetMusicInfoTag()->SetTitle(child->Value()); } } pElement = pTrackElement->FirstChildElement("creator"); if (pElement) { TiXmlNode* child = pElement->FirstChild(); if (child) { newItem->GetMusicInfoTag()->SetArtist(child->Value()); } } pElement = pTrackElement->FirstChildElement("album"); if (pElement) { TiXmlNode* child = pElement->FirstChild(); if (child) { newItem->GetMusicInfoTag()->SetAlbum(child->Value()); } } pElement = pTrackElement->FirstChildElement("duration"); if (pElement) { TiXmlNode* child = pElement->FirstChild(); if (child) { int iDuration = atoi(child->Value())/1000; newItem->GetMusicInfoTag()->SetDuration(iDuration); } } newItem->FillInDefaultIcon(); pElement = pTrackElement->FirstChildElement("image"); if (pElement) { TiXmlNode* child = pElement->FirstChild(); if (child) { CStdString coverUrl = child->Value(); if ((coverUrl != "") && (coverUrl.Find("noimage") == -1) && (coverUrl.Right(1) != "/")) { newItem->SetThumbnailImage(coverUrl); } } } //trackauth is needed for validating the track when scrobbling pElement = pTrackElement->FirstChildElement("lastfm:trackauth"); if (pElement) { TiXmlNode* child = pElement->FirstChild(); if (child) { CStdString trackAuth = child->Value(); //abuse comment field for the track authcode newItem->GetMusicInfoTag()->SetComment(trackAuth); } } { CSingleLock lock(m_lockCache); m_RadioTrackQueue->Add(newItem); } pTrackElement = pTrackElement->NextSiblingElement(); } //end parse CSingleLock lock(m_lockCache); int iNrCachedTracks = m_RadioTrackQueue->size(); CLog::Log(LOGDEBUG, "%s: Done (time: %i ms)", __FUNCTION__, (int)(CTimeUtils::GetTimeMS() - start)); return iNrCachedTracks > 0; }
bool UrdfParser::parseGeometry(UrdfGeometry& geom, TiXmlElement* g, ErrorLogger* logger) { btAssert(g); TiXmlElement *shape = g->FirstChildElement(); if (!shape) { logger->reportError("Geometry tag contains no child element."); return false; } const std::string type_name = shape->ValueTStr().c_str(); if (type_name == "sphere") { geom.m_type = URDF_GEOM_SPHERE; if (!shape->Attribute("radius")) { logger->reportError("Sphere shape must have a radius attribute"); return false; } else { geom.m_sphereRadius = urdfLexicalCast<double>(shape->Attribute("radius")); } } else if (type_name == "box") { geom.m_type = URDF_GEOM_BOX; if (m_parseSDF) { TiXmlElement* size = shape->FirstChildElement("size"); if (0==size) { logger->reportError("box requires a size child element"); return false; } parseVector3(geom.m_boxSize,size->GetText(),logger); } else { if (!shape->Attribute("size")) { logger->reportError("box requires a size attribute"); return false; } else { parseVector3(geom.m_boxSize,shape->Attribute("size"),logger); } } } else if (type_name == "cylinder") { geom.m_type = URDF_GEOM_CYLINDER; if (!shape->Attribute("length") || !shape->Attribute("radius")) { logger->reportError("Cylinder shape must have both length and radius attributes"); return false; } geom.m_cylinderRadius = urdfLexicalCast<double>(shape->Attribute("radius")); geom.m_cylinderLength = urdfLexicalCast<double>(shape->Attribute("length")); } else if (type_name == "mesh") { geom.m_type = URDF_GEOM_MESH; if (m_parseSDF) { TiXmlElement* scale = shape->FirstChildElement("scale"); if (0==scale) { geom.m_meshScale.setValue(1,1,1); } else { parseVector3(geom.m_meshScale,scale->GetText(),logger); } TiXmlElement* filename = shape->FirstChildElement("uri"); geom.m_meshFileName = filename->GetText(); } else { if (!shape->Attribute("filename")) { logger->reportError("Mesh must contain a filename attribute"); return false; } geom.m_meshFileName = shape->Attribute("filename"); geom.m_meshScale.setValue(1,1,1); if (shape->Attribute("scale")) { if (!parseVector3(geom.m_meshScale,shape->Attribute("scale"),logger)) { logger->reportWarning("scale should be a vector3, not single scalar. Workaround activated.\n"); std::string scalar_str = shape->Attribute("scale"); double scaleFactor = urdfLexicalCast<double>(scalar_str.c_str()); if (scaleFactor) { geom.m_meshScale.setValue(scaleFactor,scaleFactor,scaleFactor); } } } else { } } } else { if (this->m_parseSDF) { if (type_name == "plane") { geom.m_type = URDF_GEOM_PLANE; TiXmlElement *n = shape->FirstChildElement("normal"); TiXmlElement *s = shape->FirstChildElement("size"); if ((0==n)||(0==s)) { logger->reportError("Plane shape must have both normal and size attributes"); return false; } parseVector3(geom.m_planeNormal,n->GetText(),logger); } } else { logger->reportError("Unknown geometry type:"); logger->reportError(type_name.c_str()); return false; } } return true; }
bool UrdfParser::parseLink(UrdfModel& model, UrdfLink& link, TiXmlElement *config, ErrorLogger* logger) { const char* linkName = config->Attribute("name"); if (!linkName) { logger->reportError("Link with no name"); return false; } link.m_name = linkName; if (m_parseSDF) { TiXmlElement* pose = config->FirstChildElement("pose"); if (0==pose) { link.m_linkTransformInWorld.setIdentity(); } else { parseTransform(link.m_linkTransformInWorld, pose,logger,m_parseSDF); } } { //optional 'contact' parameters TiXmlElement* ci = config->FirstChildElement("contact"); if (ci) { TiXmlElement *friction_xml = ci->FirstChildElement("lateral_friction"); if (friction_xml) { if (m_parseSDF) { link.m_contactInfo.m_lateralFriction = urdfLexicalCast<double>(friction_xml->GetText()); } else { if (!friction_xml->Attribute("value")) { logger->reportError("Link/contact: lateral_friction element must have value attribute"); return false; } link.m_contactInfo.m_lateralFriction = urdfLexicalCast<double>(friction_xml->Attribute("value")); } } } } // Inertial (optional) TiXmlElement *i = config->FirstChildElement("inertial"); if (i) { if (!parseInertia(link.m_inertia, i,logger)) { logger->reportError("Could not parse inertial element for Link:"); logger->reportError(link.m_name.c_str()); return false; } } else { if ((strlen(linkName)==5) && (strncmp(linkName, "world", 5))==0) { link.m_inertia.m_mass = 0.f; link.m_inertia.m_linkLocalFrame.setIdentity(); link.m_inertia.m_ixx = 0.f; link.m_inertia.m_iyy = 0.f; link.m_inertia.m_izz= 0.f; } else { logger->reportWarning("No inertial data for link, using mass=1, localinertiadiagonal = 1,1,1, identity local inertial frame"); link.m_inertia.m_mass = 1.f; link.m_inertia.m_linkLocalFrame.setIdentity(); link.m_inertia.m_ixx = 1.f; link.m_inertia.m_iyy = 1.f; link.m_inertia.m_izz= 1.f; logger->reportWarning(link.m_name.c_str()); } } // Multiple Visuals (optional) for (TiXmlElement* vis_xml = config->FirstChildElement("visual"); vis_xml; vis_xml = vis_xml->NextSiblingElement("visual")) { UrdfVisual visual; if (parseVisual(model, visual, vis_xml,logger)) { link.m_visualArray.push_back(visual); } else { logger->reportError("Could not parse visual element for Link:"); logger->reportError(link.m_name.c_str()); return false; } } // Multiple Collisions (optional) for (TiXmlElement* col_xml = config->FirstChildElement("collision"); col_xml; col_xml = col_xml->NextSiblingElement("collision")) { UrdfCollision col; if (parseCollision(col, col_xml,logger)) { link.m_collisionArray.push_back(col); } else { logger->reportError("Could not parse collision element for Link:"); logger->reportError(link.m_name.c_str()); return false; } } return true; }
void MCVolume::initFromXML(const char *xml_filepath) throw (iom::exception) { #if VM_VERBOSE > 3 printf("\t\t\t\tin MCVolume::initFromXML(char *xml_filename = %s)\n", xml_filename); #endif TiXmlDocument xml; if(!xml.LoadFile(xml_filepath)) { char errMsg[2000]; sprintf(errMsg,"in MCVolume::initFromXML(xml_filepath = \"%s\") : unable to load xml", xml_filepath); throw iom::exception(errMsg); } //setting ROOT element (that is the first child, i.e. <TeraStitcher> node) TiXmlHandle hRoot(xml.FirstChildElement("TeraStitcher")); // 2014-09-10. Alessandro. @ADDED 'volume_format' attribute to <TeraStitcher> XML node const char *volformat = hRoot.ToElement()->Attribute("volume_format"); if(volformat && strcmp(volformat, id.c_str()) != 0) throw iom::exception(vm::strprintf("in MCVolume::initFromXML(): unsupported volume_format = \"%s\" (current format is \"%s\")", volformat, id.c_str()).c_str()); // 2017-04-27. Giulio. ADDED 'input_plugin' attribute to <TeraStitcher> XML node const char *inplugin = hRoot.ToElement()->Attribute("input_plugin"); if(inplugin) iom::IMIN_PLUGIN = inplugin; //reading fields TiXmlElement * pelem = hRoot.FirstChildElement("stacks_dir").Element(); // 2014-11-06. Giulio. @ADDED saved reference system into XML file if ( (pelem = hRoot.FirstChildElement("ref_sys").Element()) != 0 ) { // skip if not present (for compatibility with previous versions) pelem->QueryIntAttribute("ref1", (int *) &reference_system.first); pelem->QueryIntAttribute("ref2", (int *) &reference_system.second); pelem->QueryIntAttribute("ref3", (int *) &reference_system.third); } else { // 2014-11-06. Giulio. @MOVED in case XML is old // 2014-09-09. Alessandro. @FIXED. Added default reference system if volume is imported from xml. reference_system = vm::ref_sys(vm::vertical,vm::horizontal,vm::depth); } pelem = hRoot.FirstChildElement("voxel_dims").Element(); pelem->QueryFloatAttribute("V", &VXL_V); pelem->QueryFloatAttribute("H", &VXL_H); pelem->QueryFloatAttribute("D", &VXL_D); pelem = hRoot.FirstChildElement("origin").Element(); pelem->QueryFloatAttribute("V", &ORG_V); pelem->QueryFloatAttribute("H", &ORG_H); pelem->QueryFloatAttribute("D", &ORG_D); //// 2016-10-27. Giulio. New field in the xml import file to select a subimage (resolution, timepoint, series_no) //if ( (pelem = hRoot.FirstChildElement("subimage").Element()) != 0 ) { // skip if not present (for compatibility with previous versions) // int value; // std::stringstream str; // if ( pelem->QueryIntAttribute("resolution", &value) == TIXML_SUCCESS ) { // if ( value ) {// additional parameters are not needed if resolution is zero // additionalIOPluginParams = true; // str << value; // active_res = str.str(); // } // } // if ( pelem->QueryIntAttribute("timepoint", &value) == TIXML_SUCCESS ) { // if ( value ) { // additional parameters are not needed if resolution is zero // additionalIOPluginParams = true; // str.str(""); // str << value; // active_tp = str.str(); // } // } // const char *series_no_flag=pelem->Attribute("series_no"); // if ( series_no_flag ) { // if ( strcmp(series_no_flag,"true") == 0 ) // series_no = additionalIOPluginParams = true; // } //} pelem = hRoot.FirstChildElement("mechanical_displacements").Element(); pelem->QueryFloatAttribute("V", &MEC_V); pelem->QueryFloatAttribute("H", &MEC_H); pelem = hRoot.FirstChildElement("dimensions").Element(); int nrows, ncols, nslices; pelem->QueryIntAttribute("stack_rows", &nrows); pelem->QueryIntAttribute("stack_columns", &ncols); N_ROWS = nrows; N_COLS = ncols; pelem->QueryIntAttribute("stack_slices", &nslices); N_SLICES = nslices; pelem = hRoot.FirstChildElement("SUBVOLUMES").Element(); pelem->QueryIntAttribute("N_SUBVOLUMES", &N_SUBVOLS); pelem->QueryIntAttribute("ENABLED_SUBVOLUME", &enabledSV); const char *strvalue = pelem->Attribute("ALIGNED"); if ( strcmp(strvalue,"true") == 0 ) aligned = true; else aligned = false; subvolumes = new vm::VirtualVolume *[N_SUBVOLS]; sv_format = new string[N_SUBVOLS]; xml_file_names = new string[N_SUBVOLS]; //for each entry creates a VirtualVolume TiXmlElement * pelem2; pelem2 = pelem->FirstChildElement("Subvolume"); for( int i=0; i<N_SUBVOLS; i++ ) { xml_file_names[i] = pelem2->Attribute("xml_fname"); subvolumes[i] = volumemanager::VirtualVolumeFactory::createFromXML(xml_file_names[i].c_str(),false); sv_format[i] = subvolumes[i]->getVolumeFormat(xml_file_names[i].c_str()); pelem2 = pelem2->NextSiblingElement(); } }
void MainWindow::ReadDBFromFile() { //读入数据 QString filename = QFileDialog::getOpenFileName(this,"open database","","database (db.xml)"); string filenameStr = filename.toStdString(); if("" == filenameStr) return; cout<<"filename = "<<filenameStr<<endl; TiXmlDocument doc; if(!doc.LoadFile(filenameStr)) { ShowError("读取指定数据库失败。"); return; } //清空已有的数据 dataBase.clear(); Reset(); TiXmlElement* firstElem = doc.FirstChildElement()->FirstChildElement(); while (NULL!=firstElem) { TiXmlElement* pathElem = firstElem->FirstChildElement(); TiXmlElement* segPathElem = pathElem->NextSiblingElement(); TiXmlElement* phaseElem = segPathElem->NextSiblingElement(); TiXmlElement* qualityElem = phaseElem->NextSiblingElement(); TiXmlElement* tumorQualityElem = qualityElem->NextSiblingElement(); TiXmlElement* layerElem = tumorQualityElem->NextSiblingElement(); TiXmlElement* isSegErrorElem = layerElem->NextSiblingElement(); TiXmlElement* descriptionElem = isSegErrorElem->NextSiblingElement(); //cout<<"description = "<<(string)descriptionElem->Value()<<endl; dbAtom newAtom; newAtom.path = pathElem->GetText(); newAtom.segPath = segPathElem->GetText(); newAtom.phase = atoi(phaseElem->GetText()); newAtom.quality = atoi(qualityElem->GetText()); newAtom.tumorQuality = atoi(tumorQualityElem->GetText()); int currLayer = atoi(layerElem->GetText()); //newAtom.layer = (currLayer>100)+(currLayer>200)+(currLayer>400); newAtom.layer = currLayer; if(0 == strcmp("TRUE", isSegErrorElem->GetText())) { newAtom.isError = 0;//有错是0,没错是1 }else{ newAtom.isError = 1; } if(NULL != descriptionElem->FirstChild()) newAtom.description = descriptionElem->GetText(); else newAtom.description = "无描述"; //newAtom.PrintSelf(std::cout); this->dataBase.push_back(newAtom); firstElem = firstElem->NextSiblingElement(); } UpdateFilters(0); //SetupDB(); }
void CVar::deserialize(TiXmlNode* rootNode) { int oldFlags = m_flags; unlock(); if (rootNode == NULL) return; TiXmlElement* cvarNode = NULL; if (type() != Bind) cvarNode = rootNode->FirstChildElement("CVar"); else cvarNode = rootNode->FirstChildElement("Bind"); while (cvarNode != nullptr) { if (type() != Bind) { if (!std::string(cvarNode->Attribute("name")).compare(name())) break; cvarNode = cvarNode->NextSiblingElement("CVar"); } else { if (!std::string(cvarNode->Attribute("action")).compare(name())) break; cvarNode = cvarNode->NextSiblingElement("Bind"); } } if (!cvarNode) return; switch(type()) { case Bind: { std::string tmp; if (cvarNode->Attribute("key")) { tmp = cvarNode->Attribute("key"); Athena::utility::tolower(tmp); for (int k = 0; k < (int)Key::KEYCOUNT; k++) { std::string keyName = enumToStdString((Key)k); Athena::utility::tolower(keyName); if (!keyName.compare(tmp)) m_binding.KeyVal = (Key)k; } } if (cvarNode->Attribute("mouseButton")) { tmp = cvarNode->Attribute("mouseButton"); for (int m = 0; m < (int)MouseButton::COUNT; m++) { std::string name = enumToStdString((MouseButton)m); Athena::utility::tolower(name); if (!name.compare(tmp)) m_binding.MouseButtonVal = (MouseButton)m; } } for (int j = 0; j < IJoystickManager::MaxJoysticks; j++) { std::stringstream ss; ss << j; TiXmlElement* joyNode = cvarNode->FirstChildElement("Joy"); while (joyNode != NULL) { if (!std::string(joyNode->Attribute("id")).compare(ss.str())) break; joyNode = joyNode->NextSiblingElement("Joy"); } if (!joyNode) continue; bool set = false; if (joyNode->Attribute("button")) { int button; joyNode->Attribute("button", &button); m_binding.Joysticks[j].Button = button; set = true; } if (joyNode->Attribute("axis")) { int axis; joyNode->Attribute("axis", &axis); m_binding.Joysticks[j].Axis = axis; set = true; } if (joyNode->Attribute("isAxisNegative")) { tmp = joyNode->Attribute("isAxisNegative"); m_binding.Joysticks[j].NegativeAxis = Athena::utility::parseBool(tmp); set = true; } m_binding.Joysticks[j].valid = set; } } break; case Color: { int r, g, b, a; cvarNode->Attribute("r", &r); cvarNode->Attribute("g", &g); cvarNode->Attribute("b", &b); cvarNode->Attribute("a", &a); fromColorb(Colorb(r, g, b, a)); } break; default: m_value = cvarNode->FirstChild()->ToText()->ValueStr(); break; } lock(); m_flags = oldFlags; }
void CAdvancedSettings::ParseSettingsFile(const CStdString &file) { CXBMCTinyXML advancedXML; if (!CFile::Exists(file)) { CLog::Log(LOGNOTICE, "No settings file to load (%s)", file.c_str()); return; } if (!advancedXML.LoadFile(file)) { CLog::Log(LOGERROR, "Error loading %s, Line %d\n%s", file.c_str(), advancedXML.ErrorRow(), advancedXML.ErrorDesc()); return; } TiXmlElement *pRootElement = advancedXML.RootElement(); if (!pRootElement || strcmpi(pRootElement->Value(),"advancedsettings") != 0) { CLog::Log(LOGERROR, "Error loading %s, no <advancedsettings> node", file.c_str()); return; } // succeeded - tell the user it worked CLog::Log(LOGNOTICE, "Loaded settings file from %s", file.c_str()); // Dump contents of AS.xml to debug log TiXmlPrinter printer; printer.SetLineBreak("\n"); printer.SetIndent(" "); advancedXML.Accept(&printer); CLog::Log(LOGNOTICE, "Contents of %s are...\n%s", file.c_str(), printer.CStr()); TiXmlElement *pElement = pRootElement->FirstChildElement("audio"); if (pElement) { XMLUtils::GetFloat(pElement, "ac3downmixgain", m_ac3Gain, -96.0f, 96.0f); XMLUtils::GetInt(pElement, "headroom", m_audioHeadRoom, 0, 12); XMLUtils::GetString(pElement, "defaultplayer", m_audioDefaultPlayer); // 101 on purpose - can be used to never automark as watched XMLUtils::GetFloat(pElement, "playcountminimumpercent", m_audioPlayCountMinimumPercent, 0.0f, 101.0f); XMLUtils::GetBoolean(pElement, "usetimeseeking", m_musicUseTimeSeeking); XMLUtils::GetInt(pElement, "timeseekforward", m_musicTimeSeekForward, 0, 6000); XMLUtils::GetInt(pElement, "timeseekbackward", m_musicTimeSeekBackward, -6000, 0); XMLUtils::GetInt(pElement, "timeseekforwardbig", m_musicTimeSeekForwardBig, 0, 6000); XMLUtils::GetInt(pElement, "timeseekbackwardbig", m_musicTimeSeekBackwardBig, -6000, 0); XMLUtils::GetInt(pElement, "percentseekforward", m_musicPercentSeekForward, 0, 100); XMLUtils::GetInt(pElement, "percentseekbackward", m_musicPercentSeekBackward, -100, 0); XMLUtils::GetInt(pElement, "percentseekforwardbig", m_musicPercentSeekForwardBig, 0, 100); XMLUtils::GetInt(pElement, "percentseekbackwardbig", m_musicPercentSeekBackwardBig, -100, 0); XMLUtils::GetInt(pElement, "resample", m_audioResample, 0, 192000); XMLUtils::GetBoolean(pElement, "allowtranscode44100", m_allowTranscode44100); XMLUtils::GetBoolean(pElement, "forceDirectSound", m_audioForceDirectSound); XMLUtils::GetBoolean(pElement, "audiophile", m_audioAudiophile); XMLUtils::GetBoolean(pElement, "allchannelstereo", m_allChannelStereo); XMLUtils::GetBoolean(pElement, "streamsilence", m_streamSilence); XMLUtils::GetString(pElement, "transcodeto", m_audioTranscodeTo); XMLUtils::GetInt(pElement, "audiosinkbufferdurationmsec", m_audioSinkBufferDurationMsec); TiXmlElement* pAudioExcludes = pElement->FirstChildElement("excludefromlisting"); if (pAudioExcludes) GetCustomRegexps(pAudioExcludes, m_audioExcludeFromListingRegExps); pAudioExcludes = pElement->FirstChildElement("excludefromscan"); if (pAudioExcludes) GetCustomRegexps(pAudioExcludes, m_audioExcludeFromScanRegExps); XMLUtils::GetString(pElement, "audiohost", m_audioHost); XMLUtils::GetBoolean(pElement, "applydrc", m_audioApplyDrc); XMLUtils::GetBoolean(pElement, "dvdplayerignoredtsinwav", m_dvdplayerIgnoreDTSinWAV); XMLUtils::GetFloat(pElement, "limiterhold", m_limiterHold, 0.0f, 100.0f); XMLUtils::GetFloat(pElement, "limiterrelease", m_limiterRelease, 0.001f, 100.0f); } pElement = pRootElement->FirstChildElement("omx"); if (pElement) { XMLUtils::GetBoolean(pElement, "omxhwaudiodecode", m_omxHWAudioDecode); XMLUtils::GetBoolean(pElement, "omxdecodestartwithvalidframe", m_omxDecodeStartWithValidFrame); } pElement = pRootElement->FirstChildElement("karaoke"); if (pElement) { XMLUtils::GetFloat(pElement, "syncdelaycdg", m_karaokeSyncDelayCDG, -3.0f, 3.0f); // keep the old name for comp XMLUtils::GetFloat(pElement, "syncdelaylrc", m_karaokeSyncDelayLRC, -3.0f, 3.0f); XMLUtils::GetBoolean(pElement, "alwaysreplacegenre", m_karaokeChangeGenreForKaraokeSongs ); XMLUtils::GetBoolean(pElement, "storedelay", m_karaokeKeepDelay ); XMLUtils::GetInt(pElement, "autoassignstartfrom", m_karaokeStartIndex, 1, 2000000000); XMLUtils::GetBoolean(pElement, "nocdgbackground", m_karaokeAlwaysEmptyOnCdgs ); XMLUtils::GetBoolean(pElement, "lookupsongbackground", m_karaokeUseSongSpecificBackground ); TiXmlElement* pKaraokeBackground = pElement->FirstChildElement("defaultbackground"); if (pKaraokeBackground) { const char* attr = pKaraokeBackground->Attribute("type"); if ( attr ) m_karaokeDefaultBackgroundType = attr; attr = pKaraokeBackground->Attribute("path"); if ( attr ) m_karaokeDefaultBackgroundFilePath = attr; } } pElement = pRootElement->FirstChildElement("video"); if (pElement) { XMLUtils::GetFloat(pElement, "subsdelayrange", m_videoSubsDelayRange, 10, 600); XMLUtils::GetFloat(pElement, "audiodelayrange", m_videoAudioDelayRange, 10, 600); XMLUtils::GetInt(pElement, "blackbarcolour", m_videoBlackBarColour, 0, 255); XMLUtils::GetString(pElement, "defaultplayer", m_videoDefaultPlayer); XMLUtils::GetString(pElement, "defaultdvdplayer", m_videoDefaultDVDPlayer); XMLUtils::GetBoolean(pElement, "fullscreenonmoviestart", m_fullScreenOnMovieStart); // 101 on purpose - can be used to never automark as watched XMLUtils::GetFloat(pElement, "playcountminimumpercent", m_videoPlayCountMinimumPercent, 0.0f, 101.0f); XMLUtils::GetInt(pElement, "ignoresecondsatstart", m_videoIgnoreSecondsAtStart, 0, 900); XMLUtils::GetFloat(pElement, "ignorepercentatend", m_videoIgnorePercentAtEnd, 0, 100.0f); XMLUtils::GetInt(pElement, "smallstepbackseconds", m_videoSmallStepBackSeconds, 1, INT_MAX); XMLUtils::GetInt(pElement, "smallstepbacktries", m_videoSmallStepBackTries, 1, 10); XMLUtils::GetInt(pElement, "smallstepbackdelay", m_videoSmallStepBackDelay, 100, 5000); //MS XMLUtils::GetBoolean(pElement, "usetimeseeking", m_videoUseTimeSeeking); XMLUtils::GetInt(pElement, "timeseekforward", m_videoTimeSeekForward, 0, 6000); XMLUtils::GetInt(pElement, "timeseekbackward", m_videoTimeSeekBackward, -6000, 0); XMLUtils::GetInt(pElement, "timeseekforwardbig", m_videoTimeSeekForwardBig, 0, 6000); XMLUtils::GetInt(pElement, "timeseekbackwardbig", m_videoTimeSeekBackwardBig, -6000, 0); XMLUtils::GetInt(pElement, "percentseekforward", m_videoPercentSeekForward, 0, 100); XMLUtils::GetInt(pElement, "percentseekbackward", m_videoPercentSeekBackward, -100, 0); XMLUtils::GetInt(pElement, "percentseekforwardbig", m_videoPercentSeekForwardBig, 0, 100); XMLUtils::GetInt(pElement, "percentseekbackwardbig", m_videoPercentSeekBackwardBig, -100, 0); TiXmlElement* pVideoExcludes = pElement->FirstChildElement("excludefromlisting"); if (pVideoExcludes) GetCustomRegexps(pVideoExcludes, m_videoExcludeFromListingRegExps); pVideoExcludes = pElement->FirstChildElement("excludefromscan"); if (pVideoExcludes) GetCustomRegexps(pVideoExcludes, m_moviesExcludeFromScanRegExps); pVideoExcludes = pElement->FirstChildElement("excludetvshowsfromscan"); if (pVideoExcludes) GetCustomRegexps(pVideoExcludes, m_tvshowExcludeFromScanRegExps); pVideoExcludes = pElement->FirstChildElement("cleanstrings"); if (pVideoExcludes) GetCustomRegexps(pVideoExcludes, m_videoCleanStringRegExps); XMLUtils::GetString(pElement,"cleandatetime", m_videoCleanDateTimeRegExp); XMLUtils::GetString(pElement,"ppffmpegdeinterlacing",m_videoPPFFmpegDeint); XMLUtils::GetString(pElement,"ppffmpegpostprocessing",m_videoPPFFmpegPostProc); XMLUtils::GetInt(pElement,"vdpauscaling",m_videoVDPAUScaling); XMLUtils::GetFloat(pElement, "nonlinearstretchratio", m_videoNonLinStretchRatio, 0.01f, 1.0f); XMLUtils::GetBoolean(pElement,"enablehighqualityhwscalers", m_videoEnableHighQualityHwScalers); XMLUtils::GetFloat(pElement,"autoscalemaxfps",m_videoAutoScaleMaxFps, 0.0f, 1000.0f); XMLUtils::GetBoolean(pElement,"allowmpeg4vdpau",m_videoAllowMpeg4VDPAU); XMLUtils::GetBoolean(pElement,"allowmpeg4vaapi",m_videoAllowMpeg4VAAPI); XMLUtils::GetBoolean(pElement, "disablebackgrounddeinterlace", m_videoDisableBackgroundDeinterlace); XMLUtils::GetInt(pElement, "useocclusionquery", m_videoCaptureUseOcclusionQuery, -1, 1); XMLUtils::GetInt(pElement,"vdpauHDdeint",m_videoVDPAUdeintHD); XMLUtils::GetInt(pElement,"vdpauSDdeint",m_videoVDPAUdeintSD); XMLUtils::GetBoolean(pElement,"vdpauInvTelecine",m_videoVDPAUtelecine); XMLUtils::GetBoolean(pElement,"vdpauHDdeintSkipChroma",m_videoVDPAUdeintSkipChromaHD); TiXmlElement* pAdjustRefreshrate = pElement->FirstChildElement("adjustrefreshrate"); if (pAdjustRefreshrate) { TiXmlElement* pRefreshOverride = pAdjustRefreshrate->FirstChildElement("override"); while (pRefreshOverride) { RefreshOverride override = {0}; float fps; if (XMLUtils::GetFloat(pRefreshOverride, "fps", fps)) { override.fpsmin = fps - 0.01f; override.fpsmax = fps + 0.01f; } float fpsmin, fpsmax; if (XMLUtils::GetFloat(pRefreshOverride, "fpsmin", fpsmin) && XMLUtils::GetFloat(pRefreshOverride, "fpsmax", fpsmax)) { override.fpsmin = fpsmin; override.fpsmax = fpsmax; } float refresh; if (XMLUtils::GetFloat(pRefreshOverride, "refresh", refresh)) { override.refreshmin = refresh - 0.01f; override.refreshmax = refresh + 0.01f;
int CDBServiceConfig::LoadXmlByFileName(const string& sFileName) { SC_XLOG(XLOG_DEBUG, "CDBServiceConfig::%s,FileName=[%s]\n",__FUNCTION__,sFileName.c_str()); TiXmlDocument m_xmlDoc; TiXmlElement *pService; if(!m_xmlDoc.LoadFile(sFileName.c_str())) { SC_XLOG(XLOG_ERROR, "CDBServiceConfig::%s,Load File Error,FileName=[%s]\n",__FUNCTION__,sFileName.c_str()); return -1; } if((pService=m_xmlDoc.RootElement())==NULL) { SC_XLOG(XLOG_ERROR, "CDBServiceConfig::%s,No RootElement,FileName=[%s]\n",__FUNCTION__,sFileName.c_str()); return -1; } SServiceDesc serviceDesc; char szName[64] = {0}; int nRet = pService->QueryValueAttribute("name", &szName); if(nRet != TIXML_SUCCESS) { SC_XLOG(XLOG_ERROR, "CDBServiceConfig::%s,No Service Name,FileName=[%s]\n",__FUNCTION__,sFileName.c_str()); return -1; } serviceDesc.sServiceName = szName; boost::to_lower(serviceDesc.sServiceName); serviceDesc.bReadOnly = false; char szReadOnly[64]={0}; nRet = pService->QueryValueAttribute("queryonly", &szReadOnly); if(nRet == TIXML_SUCCESS) { if (strncmp(szReadOnly,"true",4)==0) { serviceDesc.bReadOnly = true; } } int nServiceId = 0; nRet = pService->QueryIntAttribute("id", (int *)&nServiceId); if(nRet != TIXML_SUCCESS) { SC_XLOG(XLOG_ERROR, "CDBServiceConfig::%s,Get ServiceId Error\n",__FUNCTION__); return -1; } serviceDesc.nServiceId = nServiceId; /* get types */ TiXmlElement * pConfigType = NULL; if((pConfigType=pService->FirstChildElement("type"))==NULL) { SC_XLOG(XLOG_ERROR, "CDBServiceConfig::%s,No Type,FileName=[%s]\n",__FUNCTION__,sFileName.c_str()); return -1; } else { SServiceType serviceType; if(LoadServiceTypes(pConfigType,serviceType)<0) { return -1; } serviceDesc.mapServiceType.insert(make_pair(serviceType.sTypeName,serviceType)); } while((pConfigType=pConfigType->NextSiblingElement("type"))!=NULL) { SServiceType serviceType; if(LoadServiceTypes(pConfigType,serviceType)<0) { return -1; } serviceDesc.mapServiceType.insert(make_pair(serviceType.sTypeName,serviceType)); } PostProcessServiceTypes(serviceDesc.mapServiceType); //get message attribute TiXmlElement * pMsgAttri = NULL; if((pMsgAttri=pService->FirstChildElement("message"))==NULL) { SC_XLOG(XLOG_ERROR, "CDBServiceConfig::%s,No Message,FileName=[%s]\n",__FUNCTION__,sFileName.c_str()); return -1; } else { SMsgAttri sMsgAttri; if(LoadServiceMessage(pMsgAttri,sMsgAttri)<0) { return -1; } SC_XLOG(XLOG_DEBUG, "CDBServiceConfig::%s,OperType=[%d]\n",__FUNCTION__,sMsgAttri.eOperType); serviceDesc.mapMsgAttri.insert(make_pair(sMsgAttri.nMsgId,sMsgAttri)); } while((pMsgAttri=pMsgAttri->NextSiblingElement("message"))!=NULL) { SMsgAttri sMsgAttri; if(LoadServiceMessage(pMsgAttri,sMsgAttri)<0) { return -1; } SC_XLOG(XLOG_DEBUG, "CDBServiceConfig::%s,OperType=[%d]\n",__FUNCTION__,sMsgAttri.eOperType); serviceDesc.mapMsgAttri.insert(make_pair(sMsgAttri.nMsgId,sMsgAttri)); } PostProcessMsgAttri(serviceDesc.mapMsgAttri,serviceDesc.mapServiceType); mapServiceConfig.insert(make_pair(serviceDesc.nServiceId,serviceDesc)); return 0; }
bool ResourceManager::parseResourceFile(const std::string &fileName, unsigned char *key) { // if we've already loaded the fonts: if (find(mParsedResourceFiles.begin(),mParsedResourceFiles.end(),fileName) != mParsedResourceFiles.end()) { // ignore this call: return true; } TiXmlDocument doc; if (key==NULL) { bool success = doc.LoadFile(fileName.c_str()); if (!success) { return false; } } else { // adjust the filename to point to the encrypted version: std::string encFileName = fileName; if (key!=NULL) { encFileName.append(".bin"); } // load and decrypt the resource file char *data; int dataSize; bool success = Boy::loadDecrypt(key, encFileName.c_str(), &data, &dataSize); if (!success) { return false; } // parse it: doc.Parse(data); mParsedResourceFiles.push_back(fileName); // deallocate the mem: delete[] data; data = NULL; } TiXmlElement *root = doc.RootElement(); for (TiXmlElement *e = root->FirstChildElement() ; e!=NULL ; e = e->NextSiblingElement()) { if (Boy::Environment::instance()->stricmp(e->Value(),"resources")==0) { parseResourceGroup(e); } else { assert(false); } } doc.Clear(); return true; }
int CDBServiceConfig::LoadXMLDBConnConfig(const string& sFileName) { SC_XLOG(XLOG_DEBUG, "CDBServiceConfig::%s,FileName=[%s]\n",__FUNCTION__,sFileName.c_str()); TiXmlDocument m_xmlDoc; TiXmlElement *pRoot; if(!m_xmlDoc.LoadFile(sFileName.c_str())) { SC_XLOG(XLOG_ERROR, "CDBServiceConfig::%s,Load File Error,FileName=[%s]\n",__FUNCTION__,sFileName.c_str()); return -1; } if((pRoot=m_xmlDoc.RootElement())==NULL) { SC_XLOG(XLOG_ERROR, "CDBServiceConfig::%s,Have No RootElement,FileName=[%s]\n",__FUNCTION__,sFileName.c_str()); return -1; } m_nBPEThreadNum=8; TiXmlElement* pBPEThreadNum; if((pBPEThreadNum=pRoot->FirstChildElement("ThreadNum"))!=NULL) { string sTmp = pBPEThreadNum->GetText(); m_nBPEThreadNum = atoi(sTmp.c_str()); } else { SC_XLOG(XLOG_WARNING, "CDBServiceConfig::%s,No BPEThreadNum Use Default[8]\n",__FUNCTION__); } if (m_nBPEThreadNum<=0) { m_nBPEThreadNum=8; } m_nDBThreadNum = 8; TiXmlElement* pDBThreadNum; if((pDBThreadNum=pRoot->FirstChildElement("dbthreadnum"))!=NULL) { string sTmp = pDBThreadNum->GetText(); m_nDBThreadNum = atoi(sTmp.c_str()); } else { SC_XLOG(XLOG_WARNING, "CDBServiceConfig::%s,No DBThreadNum Use Default[8]\n",__FUNCTION__); } m_nDBBigQueueNum = 500000; //50万 TiXmlElement* pDBBigQueueNum; if((pDBBigQueueNum=pRoot->FirstChildElement("dbbigqueuenum"))!=NULL) { string sTmp = pDBBigQueueNum->GetText(); m_nDBBigQueueNum = atoi(sTmp.c_str()); } else { SC_XLOG(XLOG_WARNING, "CDBServiceConfig::%s,No DBBigQueueNum Use Default[5000000]\n",__FUNCTION__); } m_nDBDelayQueueNum = 3000; //3000 TiXmlElement* pDBDelayQueueNum; if((pDBDelayQueueNum=pRoot->FirstChildElement("dbdelayqueuenum"))!=NULL) { string sTmp = pDBDelayQueueNum->GetText(); m_nDBDelayQueueNum = atoi(sTmp.c_str()); } else { SC_XLOG(XLOG_WARNING, "CDBServiceConfig::%s,No DBDelayQueueNum Use Default[3000]\n",__FUNCTION__); } TiXmlElement* pDBSosList; if((pDBSosList=pRoot->FirstChildElement("dbsoslist"))==NULL) { SC_XLOG(XLOG_DEBUG, "CDBServiceConfig::%s no dbsoslist\n",__FUNCTION__); return -1; } else { SConnDesc connDesc; if(LoadDBConnDesc(pDBSosList,connDesc)<0) { return -1; } vecDBConnConfig.push_back(connDesc); } while((pDBSosList=pDBSosList->NextSiblingElement("dbsoslist"))!=NULL) { SConnDesc connDesc; if(LoadDBConnDesc(pDBSosList,connDesc)<0) { return -1; } vecDBConnConfig.push_back(connDesc); } return 0; }
int CDBServiceConfig::SubLoadDBConnDesc(TiXmlElement* pDBDesc,SConnItem& connItem) { SC_XLOG(XLOG_DEBUG, "CDBServiceConfigX::%s\n",__FUNCTION__); try{ int nRet = 0; int nConnNum = 0; nRet = pDBDesc->QueryIntAttribute("conns", (int *)&nConnNum); if(nRet != TIXML_SUCCESS) { SC_XLOG(XLOG_ERROR, "CDBServiceConfig::%s,Get Master ConnNum Error\n",__FUNCTION__); } else { SC_XLOG(XLOG_DEBUG, "CDBServiceConfig::%s nConnNum[%d]\n",__FUNCTION__,nConnNum); } connItem.nConnNum = nConnNum; int nDBFactor = 1; nRet = pDBDesc->QueryIntAttribute("dbfactor", (int *)&nDBFactor); if(nRet == TIXML_SUCCESS) { connItem.nDBFactor = nDBFactor; SC_XLOG(XLOG_DEBUG, "CDBServiceConfig::%s nDBFactor[%d]\n",__FUNCTION__,nDBFactor); } int nTBFactor = 1; nRet = pDBDesc->QueryIntAttribute("tbfactor", (int *)&nTBFactor); if(nRet == TIXML_SUCCESS) { connItem.nTBFactor = nTBFactor; SC_XLOG(XLOG_DEBUG, "CDBServiceConfig::%s nTBFactor[%d]\n",__FUNCTION__,nTBFactor); } char szFactorType[64] = {0}; nRet = pDBDesc->QueryValueAttribute("factortype", &szFactorType); if(nRet == TIXML_SUCCESS) { connItem.sFactorType= szFactorType; SC_XLOG(XLOG_DEBUG, "CDBServiceConfig::%s szFactorType[%s]\n",__FUNCTION__,szFactorType); } TiXmlElement* pDivideConns; if((pDivideConns=pDBDesc->FirstChildElement("divideconns"))!=NULL) { TiXmlElement* pConnStr; if((pConnStr=pDivideConns->FirstChildElement("conn"))!=NULL) { string strConn = pConnStr->GetText(); string out1,out2; out1= strConn; if (DecodePassword(out1,out2)<0) { SC_XLOG(XLOG_ERROR, "divide connectstr[%s] config error\n",strConn.c_str()); return -1; } strConn = out2; //SC_XLOG(XLOG_DEBUG, ".............out2[%s]\n",out2.c_str()); connItem.vecDivideConn.push_back(strConn); } while((pConnStr=pConnStr->NextSiblingElement("conn"))!=NULL) { string strConn = pConnStr->GetText(); string out1,out2; out1= strConn; if (DecodePassword(out1,out2)<0) { SC_XLOG(XLOG_ERROR, "divide connectstr[%s] config error\n",strConn.c_str()); return -1; } strConn = out2; //SC_XLOG(XLOG_DEBUG, ".............out2[%s]\n",out2.c_str()); connItem.vecDivideConn.push_back(strConn); } } SC_XLOG(XLOG_DEBUG, "CDBServiceConfigY::%s\n",__FUNCTION__); TiXmlElement* pDefaultConn; if((pDefaultConn=pDBDesc->FirstChildElement("defaultconn"))!=NULL) { string strConn = pDefaultConn->GetText(); string out1,out2; out1= strConn; if (DecodePassword(out1,out2)<0) { SC_XLOG(XLOG_ERROR, "default contstr[%s] config error\n",strConn.c_str()); return -1; } strConn = out2; //SC_XLOG(XLOG_DEBUG, ".............out2[%s]\n",out2.c_str()); connItem.sDefaultConn = strConn; } }catch(std::exception const &e) { SC_XLOG(XLOG_ERROR, "Load SubConnect Exception e:%s\n",e.what()); SC_XLOG(XLOG_ERROR, "Load SubConnect FAILED !!!!!!!!!!!!!\n"); return -1; } return 0; }
int CDBServiceConfig::LoadServiceMessage(TiXmlElement* pMessage, SMsgAttri& sMsgAtrri) { SC_XLOG(XLOG_DEBUG, "CDBServiceConfig::%s Start\n",__FUNCTION__); char szName[64] = {0}; int nRet = pMessage->QueryValueAttribute("name", &szName); if(nRet != TIXML_SUCCESS) { SC_XLOG(XLOG_ERROR, "CDBServiceConfig::%s,Get Message Name Error\n",__FUNCTION__); return -1; } sMsgAtrri.sMsgName = szName; boost::to_lower(sMsgAtrri.sMsgName); // int nMsgId; nRet = pMessage->QueryIntAttribute("id", (int *)&nMsgId); if(nRet != TIXML_SUCCESS) { SC_XLOG(XLOG_ERROR, "CDBServiceConfig::%s,Get MessageID Error,MsgName=[%s] Error\n",__FUNCTION__,szName); return -1; } sMsgAtrri.nMsgId = nMsgId; char szMultiArray[64] = {0}; nRet = pMessage->QueryValueAttribute("multiarrayasone", &szMultiArray); if(nRet == TIXML_SUCCESS) { if (strcmp(szMultiArray,"true")==0) { sMsgAtrri.bMultArray = true; } } /* procedure */ TiXmlElement *pProcedure = NULL; if( (pProcedure= pMessage->FirstChildElement("procedure")) != NULL) { SProcedure proc; proc.sProcName = pProcedure->GetText(); sMsgAtrri.exeSPs.push_back(proc); SC_XLOG(XLOG_DEBUG, "CDBServiceConfig::%s,procedure=[%s]\n",__FUNCTION__,proc.sProcName.c_str()); while((pProcedure=pProcedure->NextSiblingElement("procedure"))!=NULL) { SProcedure proc; string strProcedure = pProcedure->GetText(); MakeSQLToLower(strProcedure); proc.sProcName = strProcedure; sMsgAtrri.exeSPs.push_back(proc); SC_XLOG(XLOG_DEBUG, "CDBServiceConfig::%s,procedure=[%s]\n",__FUNCTION__,proc.sProcName.c_str()); } sMsgAtrri.eOperType = DBO_WRITE; } /* simple sql and compose sql */ TiXmlElement *pExeSQLs = NULL; if((pExeSQLs=pMessage->FirstChildElement("sql")) != NULL) { LoadSQLs(pExeSQLs,sMsgAtrri); while((pExeSQLs=pExeSQLs->NextSiblingElement("sql"))!=NULL) { LoadSQLs(pExeSQLs,sMsgAtrri); } } /* request param */ TiXmlElement * pRequestParams = NULL; if((pRequestParams=pMessage->FirstChildElement("requestparameter"))!=NULL) { TiXmlElement * pField = NULL; if((pField=pRequestParams->FirstChildElement("field"))!=NULL) { SParam param; if(LoadRequestParam(pField,param)<0) { return -1; } sMsgAtrri.requestParams.push_back(param); while((pField=pField->NextSiblingElement("field"))!=NULL) { SParam param; if(LoadRequestParam(pField,param)<0) { return -1; } sMsgAtrri.requestParams.push_back(param); } } } /* respone */ TiXmlElement * pResponeParams = NULL; if((pResponeParams=pMessage->FirstChildElement("responseparameter"))!=NULL) { TiXmlElement * pField = NULL; if((pField=pResponeParams->FirstChildElement("field"))!=NULL) { SParam param; if(LoadResponeParam(pField,param)<0) { return -1; } sMsgAtrri.responeParams.push_back(param); while((pField=pField->NextSiblingElement("field"))!=NULL) { SParam param; if(LoadResponeParam(pField,param)<0) { return -1; } sMsgAtrri.responeParams.push_back(param); } } } SC_XLOG(XLOG_DEBUG, "CDBServiceConfig::%s End,MsgId=[%d],MsgName=[%s]\n\n", __FUNCTION__,sMsgAtrri.nMsgId,sMsgAtrri.sMsgName.c_str()); return 0; }
void AppBrushes::load(const std::string& filename) { XmlDocumentRef doc = app::open_xml(filename); TiXmlHandle handle(doc.get()); TiXmlElement* brushElem = handle .FirstChild("brushes") .FirstChild("brush").ToElement(); while (brushElem) { // flags int flags = 0; BrushRef brush; app::Color fgColor; app::Color bgColor; tools::InkType inkType = tools::InkType::DEFAULT; int inkOpacity = 255; Shade shade; bool pixelPerfect = false; // Brush const char* type = brushElem->Attribute("type"); const char* size = brushElem->Attribute("size"); const char* angle = brushElem->Attribute("angle"); if (type || size || angle) { if (type) flags |= int(BrushSlot::Flags::BrushType); if (size) flags |= int(BrushSlot::Flags::BrushSize); if (angle) flags |= int(BrushSlot::Flags::BrushAngle); brush.reset( new Brush( string_id_to_brush_type(type), (size ? base::convert_to<int>(std::string(size)): 1), (angle ? base::convert_to<int>(std::string(angle)): 0))); } // Brush image if (TiXmlElement* imageElem = brushElem->FirstChildElement("image")) { ImageRef image = load_xml_image(imageElem); if (image) { if (!brush) brush.reset(new Brush()); brush->setImage(image.get()); } } // Colors if (TiXmlElement* fgcolorElem = brushElem->FirstChildElement("fgcolor")) { if (auto value = fgcolorElem->Attribute("value")) { fgColor = app::Color::fromString(value); flags |= int(BrushSlot::Flags::FgColor); } } if (TiXmlElement* bgcolorElem = brushElem->FirstChildElement("bgcolor")) { if (auto value = bgcolorElem->Attribute("value")) { bgColor = app::Color::fromString(value); flags |= int(BrushSlot::Flags::BgColor); } } // Ink if (TiXmlElement* inkTypeElem = brushElem->FirstChildElement("inktype")) { if (auto value = inkTypeElem->Attribute("value")) { inkType = app::tools::string_id_to_ink_type(value); flags |= int(BrushSlot::Flags::InkType); } } if (TiXmlElement* inkOpacityElem = brushElem->FirstChildElement("inkopacity")) { if (auto value = inkOpacityElem->Attribute("value")) { inkOpacity = base::convert_to<int>(std::string(value)); flags |= int(BrushSlot::Flags::InkOpacity); } } // Shade if (TiXmlElement* shadeElem = brushElem->FirstChildElement("shade")) { if (auto value = shadeElem->Attribute("value")) { shade = shade_from_string(value); flags |= int(BrushSlot::Flags::Shade); } } // Pixel-perfect if (TiXmlElement* pixelPerfectElem = brushElem->FirstChildElement("pixelperfect")) { pixelPerfect = bool_attr_is_true(pixelPerfectElem, "value"); flags |= int(BrushSlot::Flags::PixelPerfect); } if (flags != 0) flags |= int(BrushSlot::Flags::Locked); BrushSlot brushSlot(BrushSlot::Flags(flags), brush, fgColor, bgColor, inkType, inkOpacity, shade, pixelPerfect); m_slots.push_back(brushSlot); brushElem = brushElem->NextSiblingElement(); } }
RenderContext* RenderContext::LoadXML(const char* xmlFileNamePtr, const char* indentifier) { TiXmlDocument doc((ContentManager::theContentPath + xmlFileNamePtr).c_str()); if(!doc.LoadFile()) { InternalOutput::GetReference().Error( "Failed to load %s, does the file exist?\n", xmlFileNamePtr); return 0; } TiXmlHandle hDoc(&doc); TiXmlElement* elementPtr; TiXmlHandle hRoot(0); elementPtr = hDoc.FirstChildElement().Element(); if( !elementPtr ) { InternalOutput::GetReference().Error( "Failed to load %s, is the file empty?\n", xmlFileNamePtr); return 0; } std::string rootName = elementPtr->Value(); if( strcmp(rootName.c_str(), "GDRenderContext") != 0 ) { InternalOutput::GetReference().Error( "Failed to load %s, missing a GDRenderContext element\n", xmlFileNamePtr); return 0; } TiXmlElement* pMaterialElement = elementPtr->FirstChildElement("Material"); std::string materialString; std::string shaderEffectString; std::string techniqueString; std::string vertexFormatString; std::string castShadowString; std::string renderStyleString; if( pMaterialElement != 0 ) { if(pMaterialElement->GetText() != 0) materialString = pMaterialElement->GetText(); } // Error check for old Effect based shader usage TiXmlElement* pEffectElement = elementPtr->FirstChildElement("Effect"); if(nullptr == pEffectElement ) { InternalOutput::GetReference().Error( "Failed to load %s, missing Effect element", xmlFileNamePtr); return 0; } shaderEffectString = pEffectElement->GetText(); TiXmlElement* pTechniqueElement = elementPtr->FirstChildElement("Technique"); if( pTechniqueElement != 0 ) { if( pTechniqueElement->GetText() != 0 ) techniqueString = pTechniqueElement->GetText(); } if( techniqueString.length() == 0 ) techniqueString = "Basic"; TiXmlElement* pVertexFormatElement = elementPtr->FirstChildElement("VertexFormat"); if( pVertexFormatElement == 0 ) { InternalOutput::GetReference().Error( "Failed to load %s, missing a VertexFormat element\n", xmlFileNamePtr); return 0; } vertexFormatString = pVertexFormatElement->GetText(); bool isDeferredPointLightContext = false; TiXmlElement* pPointLightTechnique = elementPtr->FirstChildElement("PointLightTechnique"); if( pPointLightTechnique != 0 ) { if( pPointLightTechnique->GetText() != 0 ) { std::string technique = pPointLightTechnique->GetText(); if( technique.length() != 0 ) isDeferredPointLightContext = true; } } bool isDeferredDirLightContext = false; TiXmlElement* pDirLightTechnique = elementPtr->FirstChildElement("DirLightTechnique"); if( pDirLightTechnique != 0 ) { if( pDirLightTechnique->GetText() != 0 ) { std::string technique = pDirLightTechnique->GetText(); if( technique.length() != 0 ) isDeferredDirLightContext = true; } } bool isDeferredSpotLightContext = false; TiXmlElement* pSpotLightTechnique = elementPtr->FirstChildElement("SpotLightTechnique"); if( pSpotLightTechnique != 0 ) { if( pSpotLightTechnique->GetText() != 0 ) { std::string technique = pSpotLightTechnique->GetText(); if( technique.length() != 0 ) isDeferredSpotLightContext = true; } } bool castShadows = false; TiXmlElement* pCastShadowsEle = elementPtr->FirstChildElement("CastShadows"); if( pCastShadowsEle != 0 ) { castShadows = true; if( pCastShadowsEle->GetText() != 0 ) { if( strlen( pCastShadowsEle->GetText() ) != 0 && (_stricmp( pCastShadowsEle->GetText(), "false") == 0 || strcmp( pCastShadowsEle->GetText(), "0" ) == 0 ) ) { castShadows = false; } } } TiXmlElement* pRenderStyleElement = elementPtr->FirstChildElement("RenderStyle"); renderStyleString = pRenderStyleElement->GetText(); RenderContext* pRenderContext = 0; if( materialString.length() != 0 ) { RenderContextWithTexture* pRcWithTex = new RenderContextWithTexture; pRenderContext = pRcWithTex; if( strcmp( vertexFormatString.c_str(), "VERTEX_POS" ) == 0 ) { pRcWithTex->RenderFunc = RenderContextWithTexture::ContextPositionRenderFunc; pRcWithTex->vertexFormat = eVERTEX_POS; } else if( strcmp( vertexFormatString.c_str(), "VERTEX_POSCOLOR" ) == 0 ) { pRcWithTex->RenderFunc = RenderContextWithTexture::ContextPositionRenderFunc; pRcWithTex->vertexFormat = eVERTEX_POSCOLOR; } else if( strcmp( vertexFormatString.c_str(), "VERTEX_POSTEX" ) == 0 ) { pRcWithTex->RenderFunc = RenderContextWithTexture::ContextPositionUVRenderFunc; pRcWithTex->vertexFormat = eVERTEX_POSTEX; } else if( strcmp( vertexFormatString.c_str(), "VERTEX_POSNORMTEX" ) == 0 ) { pRcWithTex->RenderFunc = RenderContextWithTexture::ContextPosNormalUVRenderFunc; pRcWithTex->vertexFormat = eVERTEX_POSNORMTEX; } else if( strcmp( vertexFormatString.c_str(), "VERTEX_POSNORMTANTEX" ) == 0 ) { pRcWithTex->RenderFunc = RenderContextWithTexture::ContextPosNormalTangentUVRenderFunc; pRcWithTex->vertexFormat = eVERTEX_POSNORMTANTEX; } else if( strcmp( vertexFormatString.c_str(), "VERTEX_POSBONEWEIGHTNORMTEX" ) == 0 ) { pRcWithTex->RenderFunc = RenderContextWithTexture::ContextPosBoneWeightNormalUVRenderFunc; pRcWithTex->vertexFormat = eVERTEX_POSBONEWEIGHTNORMTEX; } else if( strcmp( vertexFormatString.c_str(), "VERTEX_POSBONEWEIGHTNORMTANTEX" ) == 0 ) { pRcWithTex->RenderFunc = RenderContextWithTexture::ContextPosBoneWeightNormalTanUVRenderFunc; pRcWithTex->vertexFormat = eVERTEX_POSBONEWEIGHTNORMTANTEX; } } else { pRenderContext = new RenderContext; if( "TRANSPARENT" == renderStyleString ) { if( strcmp( vertexFormatString.c_str(), "VERTEX_POS" ) == 0 ) { pRenderContext->RenderFunc = ContextTransparentPositionRenderFunc; pRenderContext->vertexFormat = eVERTEX_POS; } else if( strcmp( vertexFormatString.c_str(), "VERTEX_POSCOLOR" ) == 0 ) { pRenderContext->RenderFunc = ContextTransparentPositionColorRenderFunc; pRenderContext->vertexFormat = eVERTEX_POSCOLOR; } else if( strcmp( vertexFormatString.c_str(), "VERTEX_POSTEX" ) == 0 ) { pRenderContext->RenderFunc = ContextTransparentPositionUVRenderFunc; pRenderContext->vertexFormat = eVERTEX_POSTEX; } else if( strcmp( vertexFormatString.c_str(), "VERTEX_POSNORMTEX" ) == 0 ) { pRenderContext->RenderFunc = ContextTransparentPosNormalUVRenderFunc; pRenderContext->vertexFormat = eVERTEX_POSNORMTEX; } else if( strcmp( vertexFormatString.c_str(), "VERTEX_POSNORMTANTEX" ) == 0 ) { pRenderContext->RenderFunc = ContextTransparentPosNormalTangentUVRenderFunc; pRenderContext->vertexFormat = eVERTEX_POSNORMTANTEX; } } else { if( strcmp( vertexFormatString.c_str(), "VERTEX_POS" ) == 0 ) { pRenderContext->RenderFunc = ContextPositionRenderFunc; pRenderContext->vertexFormat = eVERTEX_POS; } else if( strcmp( vertexFormatString.c_str(), "VERTEX_POSCOLOR" ) == 0 ) { pRenderContext->RenderFunc = ContextPositionColorRenderFunc; pRenderContext->vertexFormat = eVERTEX_POSCOLOR; } else if( strcmp( vertexFormatString.c_str(), "VERTEX_POSTEX" ) == 0 ) { pRenderContext->RenderFunc = ContextPositionUVRenderFunc; pRenderContext->vertexFormat = eVERTEX_POSTEX; } else if( strcmp( vertexFormatString.c_str(), "VERTEX_POSNORMTEX" ) == 0 ) { pRenderContext->RenderFunc = ContextPosNormalUVRenderFunc; pRenderContext->vertexFormat = eVERTEX_POSNORMTEX; } else if (strcmp(vertexFormatString.c_str(), "VERTEX_POSNORMTEXNOCULL") == 0) { pRenderContext->RenderFunc = ContextPosNormalUVNoCullRenderFunc; pRenderContext->vertexFormat = eVERTEX_POSNORMTEX; } else if( strcmp( vertexFormatString.c_str(), "VERTEX_POSNORMTANTEX" ) == 0 ) { pRenderContext->RenderFunc = ContextPosNormalTangentUVRenderFunc; pRenderContext->vertexFormat = eVERTEX_POSNORMTANTEX; } else if (strcmp(vertexFormatString.c_str(), "VERTEX_POSNORMTANTEXNOCULL") == 0) { pRenderContext->RenderFunc = ContextPosNormalTangentUVNoCullRenderFunc; pRenderContext->vertexFormat = eVERTEX_POSNORMTANTEX; } else if( strcmp( vertexFormatString.c_str(), "VERTEX_POSBONEWEIGHTNORMTEX" ) == 0 ) { pRenderContext->RenderFunc = ContextPosBoneWeightNormalUVRenderFunc; pRenderContext->vertexFormat = eVERTEX_POSBONEWEIGHTNORMTEX; } else if( strcmp( vertexFormatString.c_str(), "VERTEX_POSBONEWEIGHTNORMTANTEX" ) == 0 ) { pRenderContext->RenderFunc = ContextPosBoneWeightNormalTanUVRenderFunc; pRenderContext->vertexFormat = eVERTEX_POSBONEWEIGHTNORMTANTEX; } } } if( materialString.length() != 0 ) { //std::string materialFilePath = "Resources/GDAssets"; //materialFilePath += materialString; //ContentHandle<RenderMaterial> matHandle = ContentManager::LoadXML<RenderMaterial>(materialFilePath.c_str()); } pRenderContext->castShadows = castShadows; // Set up shaders if(!pRenderContext->CreateEffect((string("ShaderEffects/") + shaderEffectString).c_str())) { InternalOutput::GetReference().Error( "Failed to load %s, shader effect, %s, failed to load\n", xmlFileNamePtr, shaderEffectString.c_str()); } ShaderTechnique *techPtr = nullptr; pRenderContext->SetRenderStageTechnique(elementPtr, "GBufferTechnique", xmlFileNamePtr, RenderContext::RS_GBUFFER); pRenderContext->SetRenderStageTechnique(elementPtr, "DepthCameraTechnique", xmlFileNamePtr, RenderContext::RS_DEPTH_CAMERA); pRenderContext->SetRenderStageTechnique(elementPtr, "DepthSpotLightTechnique", xmlFileNamePtr, RenderContext::RS_DEPTH_SPT_LIGHT); TiXmlElement* pDepthPointLightTechnique = elementPtr->FirstChildElement("DepthPointLightTechnique"); if( pDepthPointLightTechnique != 0 ) { if( pDepthPointLightTechnique->GetText() != 0 ) { std::string technique = pDepthPointLightTechnique->GetText(); if( technique.length() != 0 ) { ShaderTechnique *techPtr = pRenderContext->effectPtr.GetContent()->GetTechniqueByName( technique.c_str()); if(!techPtr) { InternalOutput::GetReference().Error( "Context %s specifies %s, but the technique does not exist in the shader\n", xmlFileNamePtr, "DepthPointLightTechnique"); } pRenderContext->SetRenderStageTechnique( RenderStage(RenderContext::RS_DEPTH_PNT_LIGHT), techPtr); } } } pRenderContext->SetRenderStageTechnique(elementPtr, "DepthDirectionalLightTechnique", xmlFileNamePtr, RenderContext::RS_DEPTH_DIR_LIGHT); pRenderContext->SetRenderStageTechnique(elementPtr, "UnlitTechnique", xmlFileNamePtr, RenderContext::RS_UNLIT); pRenderContext->SetRenderStageTechnique(elementPtr, "TransparencyTechnique", xmlFileNamePtr, RenderContext::RS_TRANSPARENT); pRenderContext->SetRenderStageTechnique(elementPtr, "GUITechnique", xmlFileNamePtr, RenderContext::RS_GUI); if( isDeferredPointLightContext ) { std::string technique = pPointLightTechnique->GetText(); if( technique.length() != 0 ) pRenderContext->SetRenderStageTechnique( RenderContext::RS_PNT_LIGHT, pRenderContext->effectPtr.GetContent()->GetTechniqueByName(technique.c_str() )); } if( isDeferredDirLightContext ) { std::string technique = pDirLightTechnique->GetText(); if( technique.length() != 0 ) pRenderContext->SetRenderStageTechnique( RenderContext::RS_DIR_LIGHT, pRenderContext->effectPtr.GetContent()->GetTechniqueByName(technique.c_str() )); } if( isDeferredSpotLightContext ) { std::string technique = pSpotLightTechnique->GetText(); if( technique.length() != 0 ) pRenderContext->SetRenderStageTechnique( RenderContext::RS_SPT_LIGHT, pRenderContext->effectPtr.GetContent()->GetTechniqueByName(technique.c_str() )); } //////////////////////////////////////////////////////////////////////////////////// // Layout verification //LayoutVerification((string("ShaderEffects/") + shaderEffectString).c_str(), vertexFormatString); // End layout verification if( pRenderContext->GetRenderStageTechnique( RenderContext::RS_TRANSPARENT ) != 0 ) pRenderContext->CreateRenderSet( true, RenderSetSorted::ZSortSmaller ); else pRenderContext->CreateRenderSet(); return pRenderContext; }
/** * Parses a XML collision file. * Uses Tinyxml * @param pBList TODO describtion * @param pFile the filepath of the file */ bool CollisionParser::parseCollision(list <BOUNDING_COLLISION *> *pBList, const char *pFile) { TiXmlDocument *mXmlDoc = new TiXmlDocument(pFile); // Fatal error, cannot load if (!mXmlDoc->LoadFile()) return 0; // Document root TiXmlElement *mXBoundingAreas = 0; mXBoundingAreas = mXmlDoc->FirstChildElement("bounding_areas"); if (!mXBoundingAreas) { g_debug->header("Invalid name for document root, should be <bounding_areas>", 2); mXmlDoc->Clear(); delete mXmlDoc; return 0; } // ----- Triangle ----- TiXmlElement *mXTriangle = 0; mXTriangle = mXBoundingAreas->FirstChildElement("triangle"); while (mXTriangle) { if (mXTriangle->Attribute("id") && mXTriangle->Attribute("ax") && mXTriangle->Attribute("ay") && mXTriangle->Attribute("bx") && mXTriangle->Attribute("by") && mXTriangle->Attribute("cx") && mXTriangle->Attribute("cy")) { setBoundingTriangle(pBList, mXTriangle->Attribute("id"), atoi(mXTriangle->Attribute("ax")), atoi(mXTriangle->Attribute("ay")), atoi(mXTriangle->Attribute("bx")), atoi(mXTriangle->Attribute("by")), atoi(mXTriangle->Attribute("cx")), atoi(mXTriangle->Attribute("cy"))); } else { g_debug->header("The triangle doesn't have all the attributes", 2); mXmlDoc->Clear(); delete mXmlDoc; return 0; } // Move to the next element mXTriangle = mXTriangle->NextSiblingElement("triangle"); } // ----- Circle ----- TiXmlElement *mXCircle = 0; mXCircle = mXBoundingAreas->FirstChildElement("circle"); while (mXCircle) { if (mXCircle->Attribute("id") && mXCircle->Attribute("x") && mXCircle->Attribute("y") && mXCircle->Attribute("radius")) { setBoundingCircle(pBList, mXCircle->Attribute("id"), atoi(mXCircle->Attribute("x")), atoi(mXCircle->Attribute("y")), atoi(mXCircle->Attribute("radius"))); } else { g_debug->header("The circle doesn't have all the attributes", 2); mXmlDoc->Clear(); delete mXmlDoc; return 0; } // Move to the next element mXCircle = mXCircle->NextSiblingElement("circle"); } // ----- Rectangle ----- TiXmlElement *mXRectangle = 0; mXRectangle = mXBoundingAreas->FirstChildElement("rectangle"); while (mXRectangle) { if (mXRectangle->Attribute("id") && mXRectangle->Attribute("x") && mXRectangle->Attribute("y") && mXRectangle->Attribute("width") && mXRectangle->Attribute("height")) { setBoundingRectangle(pBList, mXRectangle->Attribute("id"), atoi(mXRectangle->Attribute("x")), atoi(mXRectangle->Attribute("y")), atoi(mXRectangle->Attribute("width")), atoi(mXRectangle->Attribute("height"))); } else { g_debug->header("The rectangle doesn't have all the attributes", 2); mXmlDoc->Clear(); delete mXmlDoc; return 0; } // Move to the next element mXRectangle = mXRectangle->NextSiblingElement("rectangle"); } // Delete our allocated document and return success ;) mXmlDoc->Clear(); delete mXmlDoc; return 1; }
void ResourceManager::loadStrings(const char *filename, const char *filenamebin, unsigned char *key) { TiXmlDocument doc; if( key == NULL ) { // load the clear text strings directly if (doc.LoadFile(filename)==false) { return; } } else { // load and decrypt the strings when we have an encryption key char *data; int dataSize; if (Boy::loadDecrypt(key, filenamebin, &data, &dataSize)==false) { return; } doc.Parse( data ); delete[] data; } TiXmlElement *root = doc.RootElement(); #ifdef _DEBUG int totalCount = 0; int missingCount = 0; #endif for (TiXmlElement *e = root->FirstChildElement() ; e!=NULL ; e = e->NextSiblingElement()) { assert(strcmp(e->Value(),"string")==0); const char *id = e->Attribute("id"); const char *text = e->Attribute("text"); assert(id!=NULL && text!=NULL); #ifdef _DEBUG // only do this for actual strings, skip the mom state machine stuff:S if (std::string(text).find("MOM_")!=0 && strlen(text)!=0) { totalCount += 4; if (e->Attribute("es")==NULL) { printf("%s missing SPANISH\n",id); missingCount++; } if (e->Attribute("fr")==NULL) { printf("%s missing FRENCH\n",id); missingCount++; } if (e->Attribute("it")==NULL) { printf("%s missing ITALIAN\n",id); missingCount++; } if (e->Attribute("de")==NULL) { printf("%s missing GERMAN\n",id); missingCount++; } } #endif // look for localized text: bool foundLocalized = false; for (TiXmlAttribute *a = e->FirstAttribute() ; a!=NULL ; a=a->Next()) { // skip the 'id' and 'text' attributes: const char *name = a->Name(); if (Boy::Environment::instance()->stricmp("id",name)==0 || Boy::Environment::instance()->stricmp("text",name)==0) { continue; } // if this attribute is the localized version for the first language: if (mLanguage1==a->Name()) { // remebmer the localized text: text = a->Value(); break; } else if (mLanguage2==a->Name()) { // remebmer the localized text: text = a->Value(); // (but keep searching for the first language) } } // store the text: mText[id] = text; } #ifdef _DEBUG float progress = (float)(totalCount - missingCount) / totalCount; printf("LOCALIZATION IS %0.0f%% COMPLETE\n",progress*100); #endif doc.Clear(); }
bool CXRandR::Query(bool force) { /* 歌方: 1、 卦指: 1、 傍苧: 1、 */ if (!force) if (m_bInit) return m_outputs.size() > 0; m_bInit = true; if (getenv("XBMC_BIN_HOME") == NULL) return false; m_outputs.clear(); m_current.clear(); CStdString cmd; cmd = getenv("XBMC_BIN_HOME"); cmd += "/xbmc-xrandr"; FILE* file = popen(cmd.c_str(),"r"); if (!file) { CLog::Log(LOGERROR, "CXRandR::Query - unable to execute xrandr tool"); return false; } TiXmlDocument xmlDoc; if (!xmlDoc.LoadFile(file, TIXML_DEFAULT_ENCODING)) { CLog::Log(LOGERROR, "CXRandR::Query - unable to open xrandr xml"); pclose(file); return false; } pclose(file); TiXmlElement *pRootElement = xmlDoc.RootElement(); if (strcasecmp(pRootElement->Value(), "screen") != 0) { // TODO ERROR return false; } for (TiXmlElement* output = pRootElement->FirstChildElement("output"); output; output = output->NextSiblingElement("output")) { XOutput xoutput; xoutput.name = output->Attribute("name"); xoutput.name.TrimLeft(" \n\r\t"); xoutput.name.TrimRight(" \n\r\t"); xoutput.isConnected = (strcasecmp(output->Attribute("connected"), "true") == 0); xoutput.w = (output->Attribute("w") != NULL ? atoi(output->Attribute("w")) : 0); xoutput.h = (output->Attribute("h") != NULL ? atoi(output->Attribute("h")) : 0); xoutput.x = (output->Attribute("x") != NULL ? atoi(output->Attribute("x")) : 0); xoutput.y = (output->Attribute("y") != NULL ? atoi(output->Attribute("y")) : 0); xoutput.wmm = (output->Attribute("wmm") != NULL ? atoi(output->Attribute("wmm")) : 0); xoutput.hmm = (output->Attribute("hmm") != NULL ? atoi(output->Attribute("hmm")) : 0); if (!xoutput.isConnected) continue; bool hascurrent = false; for (TiXmlElement* mode = output->FirstChildElement("mode"); mode; mode = mode->NextSiblingElement("mode")) { XMode xmode; xmode.id = mode->Attribute("id"); xmode.name = mode->Attribute("name"); xmode.hz = atof(mode->Attribute("hz")); xmode.w = atoi(mode->Attribute("w")); xmode.h = atoi(mode->Attribute("h")); xmode.isPreferred = (strcasecmp(mode->Attribute("preferred"), "true") == 0); xmode.isCurrent = (strcasecmp(mode->Attribute("current"), "true") == 0); xoutput.modes.push_back(xmode); if (xmode.isCurrent) { m_current.push_back(xoutput); hascurrent = true; } } if (hascurrent) m_outputs.push_back(xoutput); else CLog::Log(LOGWARNING, "CXRandR::Query - output %s has no current mode, assuming disconnected", xoutput.name.c_str()); } return m_outputs.size() > 0; }
bool CGUIWindow::Load(CXBMCTinyXML &xmlDoc) { TiXmlElement* pRootElement = xmlDoc.RootElement(); if (strcmpi(pRootElement->Value(), "window")) { CLog::Log(LOGERROR, "file : XML file doesnt contain <window>"); return false; } // set the scaling resolution so that any control creation or initialisation can // be done with respect to the correct aspect ratio g_graphicsContext.SetScalingResolution(m_coordsRes, m_needsScaling); // Resolve any includes that may be present g_SkinInfo->ResolveIncludes(pRootElement); // now load in the skin file SetDefaults(); CGUIControlFactory::GetInfoColor(pRootElement, "backgroundcolor", m_clearBackground, GetID()); CGUIControlFactory::GetActions(pRootElement, "onload", m_loadActions); CGUIControlFactory::GetActions(pRootElement, "onunload", m_unloadActions); CGUIControlFactory::GetHitRect(pRootElement, m_hitRect); TiXmlElement *pChild = pRootElement->FirstChildElement(); while (pChild) { CStdString strValue = pChild->Value(); if (strValue == "type" && pChild->FirstChild()) { // if we have are a window type (ie not a dialog), and we have <type>dialog</type> // then make this window act like a dialog if (!IsDialog() && strcmpi(pChild->FirstChild()->Value(), "dialog") == 0) m_isDialog = true; } else if (strValue == "previouswindow" && pChild->FirstChild()) { m_previousWindow = CButtonTranslator::TranslateWindow(pChild->FirstChild()->Value()); } else if (strValue == "defaultcontrol" && pChild->FirstChild()) { const char *always = pChild->Attribute("always"); if (always && strcmpi(always, "true") == 0) m_defaultAlways = true; m_defaultControl = atoi(pChild->FirstChild()->Value()); } else if (strValue == "visible" && pChild->FirstChild()) { CStdString condition; CGUIControlFactory::GetConditionalVisibility(pRootElement, condition); m_visibleCondition = g_infoManager.Register(condition, GetID()); } else if (strValue == "animation" && pChild->FirstChild()) { CRect rect(0, 0, (float)m_coordsRes.iWidth, (float)m_coordsRes.iHeight); CAnimation anim; anim.Create(pChild, rect, GetID()); m_animations.push_back(anim); } else if (strValue == "zorder" && pChild->FirstChild()) { m_renderOrder = atoi(pChild->FirstChild()->Value()); } else if (strValue == "coordinates") { XMLUtils::GetFloat(pChild, "posx", m_posX); XMLUtils::GetFloat(pChild, "posy", m_posY); TiXmlElement *originElement = pChild->FirstChildElement("origin"); while (originElement) { COrigin origin; originElement->QueryFloatAttribute("x", &origin.x); originElement->QueryFloatAttribute("y", &origin.y); if (originElement->FirstChild()) origin.condition = g_infoManager.Register(originElement->FirstChild()->Value(), GetID()); m_origins.push_back(origin); originElement = originElement->NextSiblingElement("origin"); } } else if (strValue == "camera") { // z is fixed pChild->QueryFloatAttribute("x", &m_camera.x); pChild->QueryFloatAttribute("y", &m_camera.y); m_hasCamera = true; } else if (strValue == "controls") { TiXmlElement *pControl = pChild->FirstChildElement(); while (pControl) { if (strcmpi(pControl->Value(), "control") == 0) { LoadControl(pControl, NULL); } pControl = pControl->NextSiblingElement(); } } else if (strValue == "allowoverlay") { bool overlay = false; if (XMLUtils::GetBoolean(pRootElement, "allowoverlay", overlay)) m_overlayState = overlay ? OVERLAY_STATE_SHOWN : OVERLAY_STATE_HIDDEN; } pChild = pChild->NextSiblingElement(); } LoadAdditionalTags(pRootElement); m_windowLoaded = true; OnWindowLoaded(); return true; }
// \brief Load the config file (sounds.xml) for nav sounds // Can be located in a folder "sounds" in the skin or from a // subfolder of the folder "sounds" in the root directory of // xbmc bool CGUIAudioManager::Load() { CSingleLock lock(m_cs); UnLoad(); if (CSettings::Get().GetString("lookandfeel.soundskin")=="OFF") return true; else Enable(true); CStdString soundSkin = CSettings::Get().GetString("lookandfeel.soundskin"); if (soundSkin == "SKINDEFAULT") { m_strMediaDir = URIUtils::AddFileToFolder(g_SkinInfo->Path(), "sounds"); } else { //check if sound skin is located in home, otherwise fallback to built-ins m_strMediaDir = URIUtils::AddFileToFolder("special://home/sounds", soundSkin); if (!XFILE::CDirectory::Exists(m_strMediaDir)) m_strMediaDir = URIUtils::AddFileToFolder("special://xbmc/sounds", soundSkin); } CStdString strSoundsXml = URIUtils::AddFileToFolder(m_strMediaDir, "sounds.xml"); // Load our xml file CXBMCTinyXML xmlDoc; CLog::Log(LOGINFO, "Loading %s", strSoundsXml.c_str()); // Load the config file if (!xmlDoc.LoadFile(strSoundsXml)) { CLog::Log(LOGNOTICE, "%s, Line %d\n%s", strSoundsXml.c_str(), xmlDoc.ErrorRow(), xmlDoc.ErrorDesc()); return false; } TiXmlElement* pRoot = xmlDoc.RootElement(); CStdString strValue = pRoot->Value(); if ( strValue != "sounds") { CLog::Log(LOGNOTICE, "%s Doesn't contain <sounds>", strSoundsXml.c_str()); return false; } // Load sounds for actions TiXmlElement* pActions = pRoot->FirstChildElement("actions"); if (pActions) { TiXmlNode* pAction = pActions->FirstChild("action"); while (pAction) { TiXmlNode* pIdNode = pAction->FirstChild("name"); int id = 0; // action identity if (pIdNode && pIdNode->FirstChild()) { CButtonTranslator::TranslateActionString(pIdNode->FirstChild()->Value(), id); } TiXmlNode* pFileNode = pAction->FirstChild("file"); CStdString strFile; if (pFileNode && pFileNode->FirstChild()) strFile += pFileNode->FirstChild()->Value(); if (id > 0 && !strFile.empty()) { CStdString filename = URIUtils::AddFileToFolder(m_strMediaDir, strFile); IAESound *sound = LoadSound(filename); if (sound) m_actionSoundMap.insert(pair<int, IAESound *>(id, sound)); } pAction = pAction->NextSibling(); } } // Load window specific sounds TiXmlElement* pWindows = pRoot->FirstChildElement("windows"); if (pWindows) { TiXmlNode* pWindow = pWindows->FirstChild("window"); while (pWindow) { int id = 0; TiXmlNode* pIdNode = pWindow->FirstChild("name"); if (pIdNode) { if (pIdNode->FirstChild()) id = CButtonTranslator::TranslateWindow(pIdNode->FirstChild()->Value()); } CWindowSounds sounds; sounds.initSound = LoadWindowSound(pWindow, "activate" ); sounds.deInitSound = LoadWindowSound(pWindow, "deactivate"); if (id > 0) m_windowSoundMap.insert(pair<int, CWindowSounds>(id, sounds)); pWindow = pWindow->NextSibling(); } } return true; }
void XMLLodDefinitionSerializer::importLodDefinition(const Ogre::DataStreamPtr& stream, LodDefinition& lodDef) const { TiXmlDocument xmlDoc; XMLHelper xmlHelper; if (!xmlHelper.Load(xmlDoc, stream)) { return; } // <lod>...</lod> TiXmlElement* rootElem = xmlDoc.RootElement(); if (rootElem) { // <automatic enabled="true|false" /> TiXmlElement* autElem = rootElem->FirstChildElement("automatic"); if (autElem) { const char* tmp = autElem->Attribute("enabled"); if (tmp) { lodDef.setUseAutomaticLod(Ogre::StringConverter::parseBool(tmp, true)); } } // <manual>...</manual> TiXmlElement* manElem = rootElem->FirstChildElement("manual"); if (manElem) { // <type>user|automatic</type> TiXmlElement* elem = manElem->FirstChildElement("type"); if (elem) { const char* tmp = elem->GetText(); if (tmp && strcmp(tmp, "automatic") == 0) { lodDef.setType(LodDefinition::LT_AUTOMATIC_VERTEX_REDUCTION); } else { lodDef.setType(LodDefinition::LT_USER_CREATED_MESH); } } // <strategy>distance|pixelcount</strategy> elem = manElem->FirstChildElement("strategy"); if (elem) { const char* tmp = elem->GetText(); if (tmp && strcmp(tmp, "distance") == 0) { lodDef.setStrategy(LodDefinition::LS_DISTANCE); } else { lodDef.setStrategy(LodDefinition::LS_PIXEL_COUNT); } } // <level>...</level> <level>...</level> <level>...</level> for (TiXmlElement* distElem = manElem->FirstChildElement("level"); distElem != 0; distElem = distElem->NextSiblingElement("level")) { LodDistance dist; if (lodDef.getType() == LodDefinition::LT_USER_CREATED_MESH) { // <meshName>.../test.mesh</meshName> elem = distElem->FirstChildElement("meshName"); if (elem) { const char* tmp = elem->GetText(); bool isValidMeshName = Ogre::ResourceGroupManager::getSingleton().resourceExistsInAnyGroup(tmp); if (tmp && isValidMeshName) { dist.setMeshName(tmp); } else { S_LOG_FAILURE( lodDef.getName() << " contains invalid mesh name for user created lod level. Skipping lod level for distance " << distElem->Attribute("distance")); continue; } } } else { // <method>constant|proportional</method> elem = distElem->FirstChildElement("method"); if (elem) { const char* tmp = elem->GetText(); if (tmp) { if (strcmp(tmp, "constant") == 0) { dist.setReductionMethod(Ogre::LodLevel::VRM_CONSTANT); } else if (strcmp(tmp, "proportional") == 0) { dist.setReductionMethod(Ogre::LodLevel::VRM_PROPORTIONAL); } else { dist.setReductionMethod(Ogre::LodLevel::VRM_COLLAPSE_COST); } } else { dist.setReductionMethod(Ogre::LodLevel::VRM_PROPORTIONAL); } } // <value>0.5</value> elem = distElem->FirstChildElement("value"); if (elem) { const char* tmp = elem->GetText(); if (tmp) { dist.setReductionValue(Ogre::StringConverter::parseReal(tmp)); } } } // <level distance="10">...</level> const char* distVal = distElem->Attribute("distance"); if (distVal) { lodDef.addLodDistance(Ogre::StringConverter::parseReal(distVal), dist); } } } } }
void Mapa::leerMapa(int numMapa){ _numLayers=0; //cargo la textura del fondo if(!fond.loadFromFile("resources/background.jpg")){ std::cerr << "Error cargando la imagen background.png"; exit(0); } fondo.setTexture(fond); //creo el objeto xml TiXmlDocument doc; if(numMapa==1)doc.LoadFile("resources/PP/nivel1PP.tmx"); if(numMapa==2)doc.LoadFile("resources/PSOE/nivel1PSOE.tmx"); if(numMapa==3)doc.LoadFile("resources/CIUDADANOS/nivel1CIUDADANOS.tmx"); if(numMapa==4)doc.LoadFile("resources/PSOE/nivel1PODEMOS.tmx"); TiXmlElement* map = doc.FirstChildElement("map"); //leo sus atributos map->QueryIntAttribute("width",&_width); map->QueryIntAttribute("height",&_height); map->QueryIntAttribute("tilewidth",&_tileWidth); map->QueryIntAttribute("tileheight",&_tileHeigth); //Leemos las diferentes imagenes que nos sirven para hacer el rect de las texturas TiXmlElement *img = map->FirstChildElement("tileset"); int numTil=0; while(img){ numTil++; img=img->NextSiblingElement("tileset"); } string filename; img = map->FirstChildElement("tileset"); //guardamos en filename el spritesheet while(img){ filename=(string)img->FirstChildElement("image")->Attribute("source"); img=img->NextSiblingElement("tileset"); } //leemos las diferentes capas _tilesetTexture.loadFromFile(filename); TiXmlElement *layer = map->FirstChildElement("layer"); while(layer){ _numLayers++; layer= layer->NextSiblingElement("layer"); } //Reserva de memoria para saber el numnero de capas y el tamaño _tilemap=new int**[_numLayers]; for(int i=0; i<_numLayers; i++){ _tilemap[i]=new int*[_height]; } for(int l=0; l<_numLayers; l++){ for(int y=0; y<_height; y++){ _tilemap[l][y]=new int[_width]; } } TiXmlElement *data; //leemos el atributo imagen layer = map->FirstChildElement("layer"); string *name=new string[_numLayers]; int j=0; int l=0; //leo los tiles del xml y avanzo a la siguiente posicion while(layer){ data= layer->FirstChildElement("data")->FirstChildElement("tile"); name[j]= (string)layer->Attribute("name"); while(data){ for(int y=0; y<_height; y++){ for(int x=0; x<_width;x++){ data->QueryIntAttribute("gid",&_tilemap[l][y][x]); data=data->NextSiblingElement("tile"); } } } l++; layer= layer->NextSiblingElement("layer"); j++; } //Reserva de memoria para los sprites _tilemapSprite=new sf::Sprite***[_numLayers]; for(int l=0; l<_numLayers; l++){ _tilemapSprite[l]=new sf::Sprite**[_height]; } for(int l=0; l<_numLayers; l++){ for(int y=0; y<_height; y++){ _tilemapSprite[l][y]= new sf::Sprite*[_width]; for(int x=0; x<_width; x++){ _tilemapSprite[l][y][x]=new sf::Sprite(); } } } sf::Texture aux; //falta el corte int columns = _tilesetTexture.getSize().x / _tileWidth; int rows = _tilesetTexture.getSize().y / _tileHeigth; // cout<<columns<<" "<<rows<<endl; _tilesetSprite =new sf::Sprite[columns*rows]; int t=0; for(int y=0; y<rows; y++){ for(int x=0; x<columns;x++){ _tilesetSprite[t].setTexture(_tilesetTexture); //_tilesetSprite[t].setTextureRect(sf::IntRect(left,top,width,height));//ojo si hay dos imagenes _tilesetSprite[t].setTextureRect(sf::IntRect(x*_tileWidth,y*_tileHeigth,_tileWidth,_tileHeigth)); t++; } } /** for(int y=0; y<t; y++) { cout<<_tilesetSprite[y].getTextureRect().left<<" "; cout<<_tilesetSprite[y].getTextureRect().top<<" "; cout<<_tilesetSprite[y].getTextureRect().width<<" "; cout<<_tilesetSprite[y].getTextureRect().height<<endl; }**/ //cout<<t<<endl; //asignacion sprite for(int l=0; l<_numLayers; l++){ for(int y=0; y<_height; y++){ for(int x=0; x<_width;x++){ int gid=_tilemap[l][y][x]-1; if(gid>=rows*columns){ // cout<<gid<<endl; // cout<<rows<<endl; // cout<<columns<<endl; // cout<<"Error aaaa"<<endl; } else if(gid>0){ _tilemapSprite[l][y][x]=new sf::Sprite(_tilesetTexture,_tilesetSprite[gid].getTextureRect()); _tilemapSprite[l][y][x]->setPosition(x*_tileWidth,y*_tileHeigth); } else{ _tilemapSprite[l][y][x]=NULL; } } } } /////////////////////Resumen // cout<<endl; // cout<<"Resumen:"<<endl; // cout<<"Heigth= "<<_height<<endl; // cout<<"Width= "<<_width<<endl; // cout<<"TileWidth= "<<_tileWidth<<endl; // cout<<"TileHeigth= "<<_tileHeigth<<endl; // cout<<"Numero de capas= "******"Nombre del tileset= "<<filename[0]<<endl; // cout<<"Nombre del tileset= "<<filename[1]<<endl; // cout<<endl; TiXmlElement *suelo = map->FirstChildElement("objectgroup"); string nombre; int filas=0; string xString, yString, widthString, heightString; int x, y, width, height; while(suelo){ nombre=(string) suelo->Attribute("name"); if(nombre=="Suelo"){ // cout<<"nombre: "<<nombre<<endl; TiXmlElement *object = suelo->FirstChildElement("object"); while(object){ xString = (string) object->Attribute("x"); yString = (string) object->Attribute("y"); widthString = (string) object->Attribute("width"); heightString = (string) object->Attribute("height"); x=atoi(xString.c_str()); y=atoi(yString.c_str()); width=atoi(widthString.c_str()); height=atoi(heightString.c_str()); /*Se crean los rectangulos que colisionan*/ sf::RectangleShape* colision = new sf::RectangleShape(sf::Vector2f(width, height)); colision->setPosition(x,y); arraySuelo.push_back(colision); /*cout<<"x: "<<x<<endl; // cout<<"y: "<<y<<endl; // cout<<"width: "<<width<<endl; // cout<<"heigth: "<<height<<endl; // cout<<"----"<<endl;*/ object = object->NextSiblingElement("object"); filas++; } } suelo = suelo->NextSiblingElement("objectgroup"); } TiXmlElement *paredes = map->FirstChildElement("objectgroup"); while(paredes){ nombre=(string) paredes->Attribute("name"); if(nombre=="Paredes"){ // cout<<"nombre: "<<nombre<<endl; TiXmlElement *object = paredes->FirstChildElement("object"); while(object){ xString = (string) object->Attribute("x"); yString = (string) object->Attribute("y"); widthString = (string) object->Attribute("width"); heightString = (string) object->Attribute("height"); x=atoi(xString.c_str()); y=atoi(yString.c_str()); width=atoi(widthString.c_str()); height=atoi(heightString.c_str()); sf::RectangleShape* colision = new sf::RectangleShape(sf::Vector2f(width, height)); colision->setPosition(x,y); arrayParedes.push_back(colision); /*cout<<"x: "<<x<<endl; // cout<<"y: "<<y<<endl; // cout<<"width: "<<width<<endl; // cout<<"heigth: "<<height<<endl; // cout<<"----"<<endl; */ object = object->NextSiblingElement("object"); filas++; } } paredes = paredes->NextSiblingElement("objectgroup"); } // cout<<"width "<<arrayColisiones[0]->getScale()<<endl; // cout<<"height "<<arrayColisiones[0]->height<<endl; TiXmlElement *plataformas = map->FirstChildElement("objectgroup"); while(plataformas){ nombre=(string) plataformas->Attribute("name"); if(nombre=="Plataforma"){ // cout<<"nombre: "<<nombre<<endl; TiXmlElement *object = plataformas->FirstChildElement("object"); while(object){ xString = (string) object->Attribute("x"); yString = (string) object->Attribute("y"); x=atoi(xString.c_str()); y=atoi(yString.c_str()); Plataforma *plataforma = new Plataforma(x, y, numMapa); arrayPlataformas.push_back(plataforma); /*cout<<"x: "<<x<<endl; // cout<<"y: "<<y<<endl; // cout<<"----"<<endl; */ object = object->NextSiblingElement("object"); filas++; } } plataformas = plataformas->NextSiblingElement("objectgroup"); } TiXmlElement *votos = map->FirstChildElement("objectgroup"); while(votos){ nombre=(string) votos->Attribute("name"); if(nombre=="Votos"){ // cout<<"nombre: "<<nombre<<endl; TiXmlElement *object = votos->FirstChildElement("object"); while(object){ xString = (string) object->Attribute("x"); yString = (string) object->Attribute("y"); x=atoi(xString.c_str()); y=atoi(yString.c_str()); if (!texVoto.loadFromFile("resources/voto.png")) { std::cerr << "Error cargando la imagen voto.png"; exit(0); } spriteVoto = new sf::Sprite(texVoto); spriteVoto->setPosition(x, y); //spriteVoto.setTexture(texVoto); //spriteVoto.setPosition(x, y); arrayVotos->push_back(spriteVoto); /*cout<<"x: "<<x<<endl; // cout<<"y: "<<y<<endl; // cout<<"----"<<endl; */ object = object->NextSiblingElement("object"); filas++; } } votos = votos->NextSiblingElement("objectgroup"); } int iC=0; TiXmlElement *enemigosC = map->FirstChildElement("objectgroup"); while(enemigosC){ nombre=(string) enemigosC->Attribute("name"); if(nombre=="Enemigos C"){ // cout<<"nombre: "<<nombre<<endl; TiXmlElement *object = enemigosC->FirstChildElement("object"); while(object){ xString = (string) object->Attribute("x"); yString = (string) object->Attribute("y"); x=atoi(xString.c_str()); y=atoi(yString.c_str()); matrizEnemigosC[iC][0]=x; matrizEnemigosC[iC][1]=y; // cout<<"-----Pos x enemC:-------- "<<matrizEnemigosC[iC][0]<<endl; // cout<<"-----Pos y enemC:-------- "<<matrizEnemigosC[iC][1]<<endl; iC++; // sf::RectangleShape* enemigosC = new sf::RectangleShape(sf::Vector2f(40, 110)); //enemigosC->setFillColor(sf::Color::Red); //enemigosC->setPosition(x,y); //arrayEnemigosC.push_back(enemigoC); /*cout<<"x: "<<x<<endl; // cout<<"y: "<<y<<endl; // cout<<"----"<<endl; */ object = object->NextSiblingElement("object"); filas++; } } enemigosC = enemigosC->NextSiblingElement("objectgroup"); } int iA=0; TiXmlElement *enemigosA = map->FirstChildElement("objectgroup"); while(enemigosA){ nombre=(string) enemigosA->Attribute("name"); if(nombre=="Enemigos A"){ // cout<<"nombre: "<<nombre<<endl; TiXmlElement *object = enemigosA->FirstChildElement("object"); while(object){ xString = (string) object->Attribute("x"); yString = (string) object->Attribute("y"); x=atoi(xString.c_str()); y=atoi(yString.c_str()); matrizEnemigosA[iA][0]=x; matrizEnemigosA[iA][1]=y; // cout<<"-----Pos x enemA:-------- "<<matrizEnemigosA[iA][0]<<endl; // cout<<"-----Pos y enemA:-------- "<<matrizEnemigosA[iA][1]<<endl; iA++; /*cout<<"x: "<<x<<endl; // cout<<"y: "<<y<<endl; // cout<<"----"<<endl; */ object = object->NextSiblingElement("object"); filas++; } } enemigosA = enemigosA->NextSiblingElement("objectgroup"); } TiXmlElement *boss = map->FirstChildElement("objectgroup"); while(boss){ nombre=(string) boss->Attribute("name"); if(nombre=="BOSS FINAL"){ // cout<<"nombre: "<<nombre<<endl; TiXmlElement *object = boss->FirstChildElement("object"); while(object){ xString = (string) object->Attribute("x"); yString = (string) object->Attribute("y"); x=atoi(xString.c_str()); y=atoi(yString.c_str()); /***************************CREACION DEL BOSS FINAL!!**********************************/ posxBoss=x; posyBoss=y; // cout<<"-----Pos x JEFE:-------- "<<posxBoss<<endl; // cout<<"-----Pos y JEFE:-------- "<<posyBoss<<endl; /*cout<<"x: "<<x<<endl; cout<<"y: "<<y<<endl; cout<<"----"<<endl; */ object = object->NextSiblingElement("object"); filas++; } } boss = boss->NextSiblingElement("objectgroup"); } // TiXmlElement *properties = colisiones->FirstChildElement("properties"); // string atributo; // while(properties){ // atributo = properties->FirstChildElement("property")->Attribute("name"); // cout<<"hola"<<endl; // } // cout<<"atributo: "<<atributo<<endl; //guardamos en filename el spritesheet // while(img){ // filename=(string)img->FirstChildElement("image")->Attribute("source"); // img=img->NextSiblingElement("tileset"); // } /*cout<<"Gid de las capas"<<endl; for(int l=0; l<_numLayers; l++) { cout<<name[l]<<endl; for(int y=0; y<_height; y++) { for(int x=0; x<_width;x++) { cout<<_tilemap[l][y][x]<<" "; if(x==_width-1) { cout<<endl; } } } }*/ //CREACION DEL FONDO if(Mundo::Instance()->nivel==1){ if (!tex.loadFromFile("resources/background.jpg")) { std::cerr << "Error cargando la imagen background.jpg"; exit(0); } } if(Mundo::Instance()->nivel==2){ if (!tex.loadFromFile("resources/backgroundPSOE.jpg")) { std::cerr << "Error cargando la imagen background.jpg"; exit(0); } } if(Mundo::Instance()->nivel==3){ if (!tex.loadFromFile("resources/backgroundCS.jpg")) { std::cerr << "Error cargando la imagen background.jpg"; exit(0); } } if(Mundo::Instance()->nivel==4){ if (!tex.loadFromFile("resources/backgroundPODEMOS.jpg")) { std::cerr << "Error cargando la imagen background.jpg"; exit(0); } } int cuantasVecesDeboPintarElFondo=(Mundo::Instance()->mapa->_tileWidth*Mundo::Instance()->mapa->_width)/Mundo::Instance()->mapa->fondo.getGlobalBounds().width; cuantasVecesDeboPintarElFondo=trunc(cuantasVecesDeboPintarElFondo)+1; for(int i=0; i<cuantasVecesDeboPintarElFondo; i++){ fondos.push_back(new sf::Sprite()); fondos[i]->setTexture(tex); fondos[i]->setPosition(Mundo::Instance()->mapa->fondo.getGlobalBounds().width*i, 0); } }
void MeshCompiler::CompileFace( TiXmlElement* Face ) { uint NumVertsInFace = 0; uint TempIndices[4]; Vector TempPositions[4]; for( TiXmlElement* Vert = Face->FirstChildElement( "vert" ); Vert; Vert = Vert->NextSiblingElement( "vert" ) ) { // Push back cached indices to handle 4-sided faces if( NumVertsInFace == 3 ) { m_Indices.PushBack( TempIndices[0] ); m_Indices.PushBack( TempIndices[2] ); } m_TempPos = Vector( 0.f, 0.f, 0.f ); m_TempUV = Vector2( 0.f, 0.f ); m_TempNorm = Vector( 0.f, 0.f, 0.f ); m_TempBoneIndex = SBoneData(); m_TempBoneWeight = SBoneWeights(); TiXmlElement* Pos = Vert->FirstChildElement( "pos" ); if( Pos ) { TiXmlAttribute* PosAttr = Pos->FirstAttribute(); m_TempPos.x = (float)PosAttr->DoubleValue(); PosAttr = PosAttr->Next(); m_TempPos.y = (float)PosAttr->DoubleValue(); PosAttr = PosAttr->Next(); m_TempPos.z = (float)PosAttr->DoubleValue(); } TempPositions[ NumVertsInFace ] = m_TempPos; TiXmlElement* UVEl = Vert->FirstChildElement( "uv" ); if( UVEl ) { m_Header.m_HasUVs = true; TiXmlAttribute* UVAttr = UVEl->FirstAttribute(); m_TempUV.x = (float)UVAttr->DoubleValue(); UVAttr = UVAttr->Next(); m_TempUV.y = (float)UVAttr->DoubleValue(); // Blender uses OpenGL-style (bottom-to-top) texture coordinates; // For now, at least, always convert to Direct3D-style. m_TempUV.y = 1.0f - m_TempUV.y; } TiXmlElement* Norm = Vert->FirstChildElement( "norm" ); if( Norm ) { m_Header.m_HasNormals = true; TiXmlAttribute* NormAttr = Norm->FirstAttribute(); m_TempNorm.x = (float)NormAttr->DoubleValue(); NormAttr = NormAttr->Next(); m_TempNorm.y = (float)NormAttr->DoubleValue(); NormAttr = NormAttr->Next(); m_TempNorm.z = (float)NormAttr->DoubleValue(); } int bIdx = 0; for( TiXmlElement* Bone = Vert->FirstChildElement( "bone" ); Bone; Bone = Bone->NextSiblingElement( "bone" ) ) { TiXmlAttribute* BoneAttr = Bone->FirstAttribute(); m_TempBoneIndex.m_Data[ bIdx ] = GetIndexForBone( HashedString( BoneAttr->Value() ) ); BoneAttr = BoneAttr->Next(); m_TempBoneWeight.m_Data[ bIdx ] = static_cast<float>( BoneAttr->DoubleValue() ); ++bIdx; } uint32 Index = GetIndexForTempVertex(); if( Index == 65536 && !m_Header.m_LongIndices ) { PRINTF( "Warning: Exceeded 65536 indices.\n" ); PRINTF( "\tUse -l to compile with long indices.\n" ); } m_Indices.PushBack( Index ); // Cache indices to handle 4-side faces TempIndices[ NumVertsInFace++ ] = Index; } if( NumVertsInFace == 4 ) { m_RawTris.PushBack( Triangle( TempPositions[0], TempPositions[1], TempPositions[2] ) ); m_RawTris.PushBack( Triangle( TempPositions[0], TempPositions[2], TempPositions[3] ) ); } else { m_RawTris.PushBack( Triangle( TempPositions[0], TempPositions[1], TempPositions[2] ) ); } }
//载入地图数据 void CGameMap::Load(hgeResourceManager *resMgr, TiXmlElement* xmlElement) { TiXmlElement* sonElement; //初始化场景图片 sonElement = xmlElement->FirstChildElement("SprBackground"); if(sonElement) { m_hSprMap = resMgr->GetSprite(sonElement->GetText()); m_nPixWidth = m_hSprMap->GetWidth(); m_nPixHeight = m_hSprMap->GetHeight(); } assert(m_hSprMap != NULL); //初始化地图数据文件 TCHAR* mapFile = new TCHAR[256]; sonElement = xmlElement->FirstChildElement("MapDataFile"); string str = sonElement->GetText(); if(sonElement) swprintf(mapFile,L"%S",sonElement->GetText()); __InitAMap(mapFile); //初始化场景坐标 sonElement = xmlElement->FirstChildElement("Coordinate"); TiXmlElement* grandson = sonElement->FirstChildElement("X"); m_CurrentXY.x = atoi(grandson->GetText()); grandson = sonElement->FirstChildElement("Y"); m_CurrentXY.y = atoi(grandson->GetText()); //初始化天空层数据 sonElement = xmlElement->FirstChildElement("SkyMap"); if(sonElement) { m_pSkyMap = new CSkyMap(resMgr, sonElement); } // assert(m_pSkyMap != NULL); m_CurRenderLayer = DEMO::TILE_LEVEL_GROUND; //初始化NPC方格 //sonElement = xmlElement->FirstChildElement("RectList"); m_pRectList = new CRectList(m_MapData->GetWidth() * DEMO::TILE_SIZE, m_MapData->GetHeight() * DEMO::TILE_SIZE); sonElement = xmlElement->FirstChildElement("EventTile"); if (sonElement) { TiXmlElement* eventElement = sonElement->FirstChildElement("Event"); if(eventElement) { int nEventId; int nEventType; for (; eventElement != NULL; eventElement = eventElement->NextSiblingElement()) { if(strcmp(eventElement->Value(),"Event") != 0) break; nEventId = atoi(eventElement->Attribute("Id")); nEventType = EventTypeStr2int(eventElement->Attribute("Type")); TiXmlElement* xyElement = eventElement->FirstChildElement("XY"); Point eventTile; for(; xyElement != NULL; xyElement = xyElement->NextSiblingElement()) { eventTile = Str2Point(std::string(xyElement->GetText())); m_MapData->SetTileAttr(eventTile.y, eventTile.x, DEMO::TILE_ATTR_ITRAP, nEventId); m_MapData->SetTileAttr(eventTile.y, eventTile.x, DEMO::TILE_ATTR_TTRAP, nEventType); } } } } }
int MeshCompiler::Compile( const char* InFilename, const char* OutFilename, bool LongIndices ) { m_StrippedFilename = FileUtil::StripExtensions( FileUtil::StripLeadingFolders( InFilename ) ); TiXmlDocument XMLDoc; XMLDoc.LoadFile( InFilename ); TiXmlElement* RootElement = XMLDoc.FirstChildElement(); // "mesh" // Sanity check if( _stricmp( RootElement->Value(), "mesh" ) ) { PRINTF( "Input file is not a valid XML mesh file.\n" ); return -1; } STATICHASH( BakeAOForDynamicMeshes ); STATICHASH( BakeAOForAnimatedMeshes ); STATICHASH( TraceTriangleBacks ); STATICHASH( DynamicAORadius ); STATICHASH( DynamicAOPushOut ); MAKEHASH( m_StrippedFilename ); ConfigManager::Load( FileStream( "tools.cfg", FileStream::EFM_Read ) ); m_BakeAOForDynamicMeshes = ConfigManager::GetArchetypeBool( sBakeAOForDynamicMeshes, ConfigManager::EmptyContext, false, sm_StrippedFilename ); m_BakeAOForAnimatedMeshes = ConfigManager::GetArchetypeBool( sBakeAOForAnimatedMeshes, ConfigManager::EmptyContext, false, sm_StrippedFilename ); m_TraceTriangleBacks = ConfigManager::GetArchetypeBool( sTraceTriangleBacks, ConfigManager::EmptyContext, false, sm_StrippedFilename ); m_AORadius = ConfigManager::GetArchetypeFloat( sDynamicAORadius, ConfigManager::EmptyContext, 0.1f, sm_StrippedFilename ); m_AOPushOut = ConfigManager::GetArchetypeFloat( sDynamicAOPushOut, ConfigManager::EmptyContext, 0.01f, sm_StrippedFilename ); m_Header.m_LongIndices = LongIndices; // Get armature first, which will make it easier to handle bone references in verts TiXmlElement* Arm = RootElement->FirstChildElement( "armature" ); CompileArmature( Arm ); int NumFaces = 0; for( TiXmlElement* Face = RootElement->FirstChildElement( "face" ); Face; Face = Face->NextSiblingElement( "face" ) ) { CompileFace( Face ); NumFaces++; } for( TiXmlElement* Mat = RootElement->FirstChildElement( "material" ); Mat; Mat = Mat->NextSiblingElement( "material" ) ) { CompileMaterial( Mat ); } m_Header.m_NumVertices = m_Positions.Size(); m_Header.m_NumIndices = m_Indices.Size(); NormalizeWeights(); CalculateAABB(); if( m_Header.m_HasUVs && m_Header.m_HasNormals ) { m_Header.m_HasTangents = true; } PRINTF( "Calculating tangents...\n" ); CalculateTangents(); CalculateAmbientOcclusion(); PRINTF( "Compile successful!\n" ); PRINTF( "Imported %d faces.\n", NumFaces ); Write( FileStream( OutFilename, FileStream::EFM_Write ) ); PRINTF( "Exported %d vertices.\n", m_Header.m_NumVertices ); PRINTF( "Exported %d indices (%d triangles).\n", m_Header.m_NumIndices, m_Header.m_NumIndices / 3 ); if( m_Header.m_HasSkeleton ) { PRINTF( "Exported %d bones.\n", m_Header.m_NumBones ); PRINTF( "Exported %d frames.\n", m_Header.m_NumFrames ); PRINTF( "Exported %d animations.\n", m_Header.m_NumAnims ); } return 0; }
int main() { // // We start with the 'demoStart' todo list. Process it. And // should hopefully end up with the todo list as illustrated. // const char* demoStart = "<?xml version=\"1.0\" standalone='no' >\n" "<!-- Our to do list data -->" "<ToDo>\n" "<!-- Do I need a secure PDA? -->\n" "<Item priority=\"1\" distance='close'> Go to the <bold>Toy store!</bold></Item>" "<Item priority=\"2\" distance='none'> Do bills </Item>" "<Item priority=\"2\" distance='far & back'> Look for Evil Dinosaurs! </Item>" "</ToDo>"; { #ifdef TIXML_USE_STL /* What the todo list should look like after processing. In stream (no formatting) representation. */ const char* demoEnd = "<?xml version=\"1.0\" standalone=\"no\" ?>" "<!-- Our to do list data -->" "<ToDo>" "<!-- Do I need a secure PDA? -->" "<Item priority=\"2\" distance=\"close\">Go to the" "<bold>Toy store!" "</bold>" "</Item>" "<Item priority=\"1\" distance=\"far\">Talk to:" "<Meeting where=\"School\">" "<Attendee name=\"Marple\" position=\"teacher\" />" "<Attendee name=\"Voel\" position=\"counselor\" />" "</Meeting>" "<Meeting where=\"Lunch\" />" "</Item>" "<Item priority=\"2\" distance=\"here\">Do bills" "</Item>" "</ToDo>"; #endif // The example parses from the character string (above): #if defined( WIN32 ) && defined( TUNE ) _CrtMemCheckpoint( &startMemState ); #endif { // Write to a file and read it back, to check file I/O. TiXmlDocument doc( "demotest.xml" ); doc.Parse( demoStart ); if ( doc.Error() ) { printf( "Error in %s: %s\n", doc.Value(), doc.ErrorDesc() ); exit( 1 ); } doc.SaveFile(); } TiXmlDocument doc( "demotest.xml" ); bool loadOkay = doc.LoadFile(); if ( !loadOkay ) { printf( "Could not load test file 'demotest.xml'. Error='%s'. Exiting.\n", doc.ErrorDesc() ); exit( 1 ); } printf( "** Demo doc read from disk: ** \n\n" ); printf( "** Printing via doc.Print **\n" ); doc.Print( stdout ); { printf( "** Printing via TiXmlPrinter **\n" ); TiXmlPrinter printer; doc.Accept( &printer ); fprintf( stdout, "%s", printer.CStr() ); } #ifdef TIXML_USE_STL { printf( "** Printing via operator<< **\n" ); std::cout << doc; } #endif TiXmlNode* node = 0; TiXmlElement* todoElement = 0; TiXmlElement* itemElement = 0; // -------------------------------------------------------- // An example of changing existing attributes, and removing // an element from the document. // -------------------------------------------------------- // Get the "ToDo" element. // It is a child of the document, and can be selected by name. node = doc.FirstChild( "ToDo" ); assert( node ); todoElement = node->ToElement(); assert( todoElement ); // Going to the toy store is now our second priority... // So set the "priority" attribute of the first item in the list. node = todoElement->FirstChildElement(); // This skips the "PDA" comment. assert( node ); itemElement = node->ToElement(); assert( itemElement ); itemElement->SetAttribute( "priority", 2 ); // Change the distance to "doing bills" from // "none" to "here". It's the next sibling element. itemElement = itemElement->NextSiblingElement(); assert( itemElement ); itemElement->SetAttribute( "distance", "here" ); // Remove the "Look for Evil Dinosaurs!" item. // It is 1 more sibling away. We ask the parent to remove // a particular child. itemElement = itemElement->NextSiblingElement(); todoElement->RemoveChild( itemElement ); itemElement = 0; // -------------------------------------------------------- // What follows is an example of created elements and text // nodes and adding them to the document. // -------------------------------------------------------- // Add some meetings. TiXmlElement item( "Item" ); item.SetAttribute( "priority", "1" ); item.SetAttribute( "distance", "far" ); TiXmlText text( "Talk to:" ); TiXmlElement meeting1( "Meeting" ); meeting1.SetAttribute( "where", "School" ); TiXmlElement meeting2( "Meeting" ); meeting2.SetAttribute( "where", "Lunch" ); TiXmlElement attendee1( "Attendee" ); attendee1.SetAttribute( "name", "Marple" ); attendee1.SetAttribute( "position", "teacher" ); TiXmlElement attendee2( "Attendee" ); attendee2.SetAttribute( "name", "Voel" ); attendee2.SetAttribute( "position", "counselor" ); // Assemble the nodes we've created: meeting1.InsertEndChild( attendee1 ); meeting1.InsertEndChild( attendee2 ); item.InsertEndChild( text ); item.InsertEndChild( meeting1 ); item.InsertEndChild( meeting2 ); // And add the node to the existing list after the first child. node = todoElement->FirstChild( "Item" ); assert( node ); itemElement = node->ToElement(); assert( itemElement ); todoElement->InsertAfterChild( itemElement, item ); printf( "\n** Demo doc processed: ** \n\n" ); doc.Print( stdout ); #ifdef TIXML_USE_STL printf( "** Demo doc processed to stream: ** \n\n" ); cout << doc << endl << endl; #endif // -------------------------------------------------------- // Different tests...do we have what we expect? // -------------------------------------------------------- int count = 0; TiXmlElement* element; ////////////////////////////////////////////////////// #ifdef TIXML_USE_STL cout << "** Basic structure. **\n"; ostringstream outputStream( ostringstream::out ); outputStream << doc; XmlTest( "Output stream correct.", string( demoEnd ).c_str(), outputStream.str().c_str(), true ); #endif node = doc.RootElement(); assert( node ); XmlTest( "Root element exists.", true, ( node != 0 && node->ToElement() ) ); XmlTest ( "Root element value is 'ToDo'.", "ToDo", node->Value()); node = node->FirstChild(); XmlTest( "First child exists & is a comment.", true, ( node != 0 && node->ToComment() ) ); node = node->NextSibling(); XmlTest( "Sibling element exists & is an element.", true, ( node != 0 && node->ToElement() ) ); XmlTest ( "Value is 'Item'.", "Item", node->Value() ); node = node->FirstChild(); XmlTest ( "First child exists.", true, ( node != 0 && node->ToText() ) ); XmlTest ( "Value is 'Go to the'.", "Go to the", node->Value() ); ////////////////////////////////////////////////////// printf ("\n** Iterators. **\n"); // Walk all the top level nodes of the document. count = 0; for( node = doc.FirstChild(); node; node = node->NextSibling() ) { count++; } XmlTest( "Top level nodes, using First / Next.", 3, count ); count = 0; for( node = doc.LastChild(); node; node = node->PreviousSibling() ) { count++; } XmlTest( "Top level nodes, using Last / Previous.", 3, count ); // Walk all the top level nodes of the document, // using a different syntax. count = 0; for( node = doc.IterateChildren( 0 ); node; node = doc.IterateChildren( node ) ) { count++; } XmlTest( "Top level nodes, using IterateChildren.", 3, count ); // Walk all the elements in a node. count = 0; for( element = todoElement->FirstChildElement(); element; element = element->NextSiblingElement() ) { count++; } XmlTest( "Children of the 'ToDo' element, using First / Next.", 3, count ); // Walk all the elements in a node by value. count = 0; for( node = todoElement->FirstChild( "Item" ); node; node = node->NextSibling( "Item" ) ) { count++; } XmlTest( "'Item' children of the 'ToDo' element, using First/Next.", 3, count ); count = 0; for( node = todoElement->LastChild( "Item" ); node; node = node->PreviousSibling( "Item" ) ) { count++; } XmlTest( "'Item' children of the 'ToDo' element, using Last/Previous.", 3, count ); #ifdef TIXML_USE_STL { cout << "\n** Parsing. **\n"; istringstream parse0( "<Element0 attribute0='foo0' attribute1= noquotes attribute2 = '>' />" ); TiXmlElement element0( "default" ); parse0 >> element0; XmlTest ( "Element parsed, value is 'Element0'.", "Element0", element0.Value() ); XmlTest ( "Reads attribute 'attribute0=\"foo0\"'.", "foo0", element0.Attribute( "attribute0" )); XmlTest ( "Reads incorrectly formatted 'attribute1=noquotes'.", "noquotes", element0.Attribute( "attribute1" ) ); XmlTest ( "Read attribute with entity value '>'.", ">", element0.Attribute( "attribute2" ) ); } #endif { const char* error = "<?xml version=\"1.0\" standalone=\"no\" ?>\n" "<passages count=\"006\" formatversion=\"20020620\">\n" " <wrong error>\n" "</passages>"; TiXmlDocument docTest; docTest.Parse( error ); XmlTest( "Error row", docTest.ErrorRow(), 3 ); XmlTest( "Error column", docTest.ErrorCol(), 17 ); //printf( "error=%d id='%s' row %d col%d\n", (int) doc.Error(), doc.ErrorDesc(), doc.ErrorRow()+1, doc.ErrorCol() + 1 ); } #ifdef TIXML_USE_STL { ////////////////////////////////////////////////////// cout << "\n** Streaming. **\n"; // Round trip check: stream in, then stream back out to verify. The stream // out has already been checked, above. We use the output istringstream inputStringStream( outputStream.str() ); TiXmlDocument document0; inputStringStream >> document0; ostringstream outputStream0( ostringstream::out ); outputStream0 << document0; XmlTest( "Stream round trip correct.", string( demoEnd ).c_str(), outputStream0.str().c_str(), true ); std::string str; str << document0; XmlTest( "String printing correct.", string( demoEnd ).c_str(), str.c_str(), true ); } #endif } { const char* str = "<doc attr0='1' attr1='2.0' attr2='foo' />"; TiXmlDocument doc; doc.Parse( str ); TiXmlElement* ele = doc.FirstChildElement(); int iVal, result; double dVal; result = ele->QueryDoubleAttribute( "attr0", &dVal ); XmlTest( "Query attribute: int as double", result, TIXML_SUCCESS ); XmlTest( "Query attribute: int as double", (int)dVal, 1 ); result = ele->QueryDoubleAttribute( "attr1", &dVal ); XmlTest( "Query attribute: double as double", (int)dVal, 2 ); result = ele->QueryIntAttribute( "attr1", &iVal ); XmlTest( "Query attribute: double as int", result, TIXML_SUCCESS ); XmlTest( "Query attribute: double as int", iVal, 2 ); result = ele->QueryIntAttribute( "attr2", &iVal ); XmlTest( "Query attribute: not a number", result, TIXML_WRONG_TYPE ); result = ele->QueryIntAttribute( "bar", &iVal ); XmlTest( "Query attribute: does not exist", result, TIXML_NO_ATTRIBUTE ); } { const char* str = "\t<?xml version=\"1.0\" standalone=\"no\" ?>\t<room doors='2'>\n" "</room>"; TiXmlDocument doc; doc.SetTabSize( 8 ); doc.Parse( str ); TiXmlHandle docHandle( &doc ); TiXmlHandle roomHandle = docHandle.FirstChildElement( "room" ); assert( docHandle.Node() ); assert( roomHandle.Element() ); TiXmlElement* room = roomHandle.Element(); assert( room ); TiXmlAttribute* doors = room->FirstAttribute(); assert( doors ); XmlTest( "Location tracking: Tab 8: room row", room->Row(), 1 ); XmlTest( "Location tracking: Tab 8: room col", room->Column(), 49 ); XmlTest( "Location tracking: Tab 8: doors row", doors->Row(), 1 ); XmlTest( "Location tracking: Tab 8: doors col", doors->Column(), 55 ); } { const char* str = "\t<?xml version=\"1.0\" standalone=\"no\" ?>\t<room doors='2'>\n" " <!-- Silly example -->\n" " <door wall='north'>A great door!</door>\n" "\t<door wall='east'/>" "</room>"; TiXmlDocument doc; doc.Parse( str ); TiXmlHandle docHandle( &doc ); TiXmlHandle roomHandle = docHandle.FirstChildElement( "room" ); TiXmlHandle commentHandle = docHandle.FirstChildElement( "room" ).FirstChild(); TiXmlHandle textHandle = docHandle.FirstChildElement( "room" ).ChildElement( "door", 0 ).FirstChild(); TiXmlHandle door0Handle = docHandle.FirstChildElement( "room" ).ChildElement( 0 ); TiXmlHandle door1Handle = docHandle.FirstChildElement( "room" ).ChildElement( 1 ); assert( docHandle.Node() ); assert( roomHandle.Element() ); assert( commentHandle.Node() ); assert( textHandle.Text() ); assert( door0Handle.Element() ); assert( door1Handle.Element() ); TiXmlDeclaration* declaration = doc.FirstChild()->ToDeclaration(); assert( declaration ); TiXmlElement* room = roomHandle.Element(); assert( room ); TiXmlAttribute* doors = room->FirstAttribute(); assert( doors ); TiXmlText* text = textHandle.Text(); TiXmlComment* comment = commentHandle.Node()->ToComment(); assert( comment ); TiXmlElement* door0 = door0Handle.Element(); TiXmlElement* door1 = door1Handle.Element(); XmlTest( "Location tracking: Declaration row", declaration->Row(), 1 ); XmlTest( "Location tracking: Declaration col", declaration->Column(), 5 ); XmlTest( "Location tracking: room row", room->Row(), 1 ); XmlTest( "Location tracking: room col", room->Column(), 45 ); XmlTest( "Location tracking: doors row", doors->Row(), 1 ); XmlTest( "Location tracking: doors col", doors->Column(), 51 ); XmlTest( "Location tracking: Comment row", comment->Row(), 2 ); XmlTest( "Location tracking: Comment col", comment->Column(), 3 ); XmlTest( "Location tracking: text row", text->Row(), 3 ); XmlTest( "Location tracking: text col", text->Column(), 24 ); XmlTest( "Location tracking: door0 row", door0->Row(), 3 ); XmlTest( "Location tracking: door0 col", door0->Column(), 5 ); XmlTest( "Location tracking: door1 row", door1->Row(), 4 ); XmlTest( "Location tracking: door1 col", door1->Column(), 5 ); } // -------------------------------------------------------- // UTF-8 testing. It is important to test: // 1. Making sure name, value, and text read correctly // 2. Row, Col functionality // 3. Correct output // -------------------------------------------------------- printf ("\n** UTF-8 **\n"); { TiXmlDocument doc( "utf8test.xml" ); doc.LoadFile(); if ( doc.Error() && doc.ErrorId() == TiXmlBase::TIXML_ERROR_OPENING_FILE ) { printf( "WARNING: File 'utf8test.xml' not found.\n" "(Are you running the test from the wrong directory?)\n" "Could not test UTF-8 functionality.\n" ); } else { TiXmlHandle docH( &doc ); // Get the attribute "value" from the "Russian" element and check it. TiXmlElement* element = docH.FirstChildElement( "document" ).FirstChildElement( "Russian" ).Element(); const unsigned char correctValue[] = { 0xd1U, 0x86U, 0xd0U, 0xb5U, 0xd0U, 0xbdU, 0xd0U, 0xbdU, 0xd0U, 0xbeU, 0xd1U, 0x81U, 0xd1U, 0x82U, 0xd1U, 0x8cU, 0 }; XmlTest( "UTF-8: Russian value.", (const char*)correctValue, element->Attribute( "value" ), true ); XmlTest( "UTF-8: Russian value row.", 4, element->Row() ); XmlTest( "UTF-8: Russian value column.", 5, element->Column() ); const unsigned char russianElementName[] = { 0xd0U, 0xa0U, 0xd1U, 0x83U, 0xd1U, 0x81U, 0xd1U, 0x81U, 0xd0U, 0xbaU, 0xd0U, 0xb8U, 0xd0U, 0xb9U, 0 }; const char russianText[] = "<\xD0\xB8\xD0\xBC\xD0\xB5\xD0\xB5\xD1\x82>"; TiXmlText* text = docH.FirstChildElement( "document" ).FirstChildElement( (const char*) russianElementName ).Child( 0 ).Text(); XmlTest( "UTF-8: Browsing russian element name.", russianText, text->Value(), true ); XmlTest( "UTF-8: Russian element name row.", 7, text->Row() ); XmlTest( "UTF-8: Russian element name column.", 47, text->Column() ); TiXmlDeclaration* dec = docH.Child( 0 ).Node()->ToDeclaration(); XmlTest( "UTF-8: Declaration column.", 1, dec->Column() ); XmlTest( "UTF-8: Document column.", 1, doc.Column() ); // Now try for a round trip. doc.SaveFile( "utf8testout.xml" ); // Check the round trip. char savedBuf[256]; char verifyBuf[256]; int okay = 1; FILE* saved = fopen( "utf8testout.xml", "r" ); FILE* verify = fopen( "utf8testverify.xml", "r" ); if ( saved && verify ) { while ( fgets( verifyBuf, 256, verify ) ) { fgets( savedBuf, 256, saved ); if ( strcmp( verifyBuf, savedBuf ) ) { okay = 0; break; } } fclose( saved ); fclose( verify ); } XmlTest( "UTF-8: Verified multi-language round trip.", 1, okay ); // On most Western machines, this is an element that contains // the word "resume" with the correct accents, in a latin encoding. // It will be something else completely on non-wester machines, // which is why TinyXml is switching to UTF-8. const char latin[] = "<element>r\x82sum\x82</element>"; TiXmlDocument latinDoc; latinDoc.Parse( latin, 0, TIXML_ENCODING_LEGACY ); text = latinDoc.FirstChildElement()->FirstChild()->ToText(); XmlTest( "Legacy encoding: Verify text element.", "r\x82sum\x82", text->Value() ); } } ////////////////////// // Copy and assignment ////////////////////// printf ("\n** Copy and Assignment **\n"); { TiXmlElement element( "foo" ); element.Parse( "<element name='value' />", 0, TIXML_ENCODING_UNKNOWN ); TiXmlElement elementCopy( element ); TiXmlElement elementAssign( "foo" ); elementAssign.Parse( "<incorrect foo='bar'/>", 0, TIXML_ENCODING_UNKNOWN ); elementAssign = element; XmlTest( "Copy/Assign: element copy #1.", "element", elementCopy.Value() ); XmlTest( "Copy/Assign: element copy #2.", "value", elementCopy.Attribute( "name" ) ); XmlTest( "Copy/Assign: element assign #1.", "element", elementAssign.Value() ); XmlTest( "Copy/Assign: element assign #2.", "value", elementAssign.Attribute( "name" ) ); XmlTest( "Copy/Assign: element assign #3.", true, ( 0 == elementAssign.Attribute( "foo" )) ); TiXmlComment comment; comment.Parse( "<!--comment-->", 0, TIXML_ENCODING_UNKNOWN ); TiXmlComment commentCopy( comment ); TiXmlComment commentAssign; commentAssign = commentCopy; XmlTest( "Copy/Assign: comment copy.", "comment", commentCopy.Value() ); XmlTest( "Copy/Assign: comment assign.", "comment", commentAssign.Value() ); TiXmlUnknown unknown; unknown.Parse( "<[unknown]>", 0, TIXML_ENCODING_UNKNOWN ); TiXmlUnknown unknownCopy( unknown ); TiXmlUnknown unknownAssign; unknownAssign.Parse( "incorrect", 0, TIXML_ENCODING_UNKNOWN ); unknownAssign = unknownCopy; XmlTest( "Copy/Assign: unknown copy.", "[unknown]", unknownCopy.Value() ); XmlTest( "Copy/Assign: unknown assign.", "[unknown]", unknownAssign.Value() ); TiXmlText text( "TextNode" ); TiXmlText textCopy( text ); TiXmlText textAssign( "incorrect" ); textAssign = text; XmlTest( "Copy/Assign: text copy.", "TextNode", textCopy.Value() ); XmlTest( "Copy/Assign: text assign.", "TextNode", textAssign.Value() ); TiXmlDeclaration dec; dec.Parse( "<?xml version='1.0' encoding='UTF-8'?>", 0, TIXML_ENCODING_UNKNOWN ); TiXmlDeclaration decCopy( dec ); TiXmlDeclaration decAssign; decAssign = dec; XmlTest( "Copy/Assign: declaration copy.", "UTF-8", decCopy.Encoding() ); XmlTest( "Copy/Assign: text assign.", "UTF-8", decAssign.Encoding() ); TiXmlDocument doc; elementCopy.InsertEndChild( textCopy ); doc.InsertEndChild( decAssign ); doc.InsertEndChild( elementCopy ); doc.InsertEndChild( unknownAssign ); TiXmlDocument docCopy( doc ); TiXmlDocument docAssign; docAssign = docCopy; #ifdef TIXML_USE_STL std::string original, copy, assign; original << doc; copy << docCopy; assign << docAssign; XmlTest( "Copy/Assign: document copy.", original.c_str(), copy.c_str(), true ); XmlTest( "Copy/Assign: document assign.", original.c_str(), assign.c_str(), true ); #endif } ////////////////////////////////////////////////////// #ifdef TIXML_USE_STL printf ("\n** Parsing, no Condense Whitespace **\n"); TiXmlBase::SetCondenseWhiteSpace( false ); { istringstream parse1( "<start>This is \ntext</start>" ); TiXmlElement text1( "text" ); parse1 >> text1; XmlTest ( "Condense white space OFF.", "This is \ntext", text1.FirstChild()->Value(), true ); } TiXmlBase::SetCondenseWhiteSpace( true ); #endif ////////////////////////////////////////////////////// // GetText(); { const char* str = "<foo>This is text</foo>"; TiXmlDocument doc; doc.Parse( str ); const TiXmlElement* element = doc.RootElement(); XmlTest( "GetText() normal use.", "This is text", element->GetText() ); str = "<foo><b>This is text</b></foo>"; doc.Clear(); doc.Parse( str ); element = doc.RootElement(); XmlTest( "GetText() contained element.", element->GetText() == 0, true ); str = "<foo>This is <b>text</b></foo>"; doc.Clear(); TiXmlBase::SetCondenseWhiteSpace( false ); doc.Parse( str ); TiXmlBase::SetCondenseWhiteSpace( true ); element = doc.RootElement(); XmlTest( "GetText() partial.", "This is ", element->GetText() ); } ////////////////////////////////////////////////////// // CDATA { const char* str = "<xmlElement>" "<![CDATA[" "I am > the rules!\n" "...since I make symbolic puns" "]]>" "</xmlElement>"; TiXmlDocument doc; doc.Parse( str ); doc.Print(); XmlTest( "CDATA parse.", doc.FirstChildElement()->FirstChild()->Value(), "I am > the rules!\n...since I make symbolic puns", true ); #ifdef TIXML_USE_STL //cout << doc << '\n'; doc.Clear(); istringstream parse0( str ); parse0 >> doc; //cout << doc << '\n'; XmlTest( "CDATA stream.", doc.FirstChildElement()->FirstChild()->Value(), "I am > the rules!\n...since I make symbolic puns", true ); #endif TiXmlDocument doc1 = doc; //doc.Print(); XmlTest( "CDATA copy.", doc1.FirstChildElement()->FirstChild()->Value(), "I am > the rules!\n...since I make symbolic puns", true ); } { // [ 1482728 ] Wrong wide char parsing char buf[256]; buf[255] = 0; for( int i=0; i<255; ++i ) { buf[i] = (char)((i>=32) ? i : 32); } TIXML_STRING str( "<xmlElement><![CDATA[" ); str += buf; str += "]]></xmlElement>"; TiXmlDocument doc; doc.Parse( str.c_str() ); TiXmlPrinter printer; printer.SetStreamPrinting(); doc.Accept( &printer ); XmlTest( "CDATA with all bytes #1.", str.c_str(), printer.CStr(), true ); #ifdef TIXML_USE_STL doc.Clear(); istringstream iss( printer.Str() ); iss >> doc; std::string out; out << doc; XmlTest( "CDATA with all bytes #2.", out.c_str(), printer.CStr(), true ); #endif } { // [ 1480107 ] Bug-fix for STL-streaming of CDATA that contains tags // CDATA streaming had a couple of bugs, that this tests for. const char* str = "<xmlElement>" "<![CDATA[" "<b>I am > the rules!</b>\n" "...since I make symbolic puns" "]]>" "</xmlElement>"; TiXmlDocument doc; doc.Parse( str ); doc.Print(); XmlTest( "CDATA parse. [ 1480107 ]", doc.FirstChildElement()->FirstChild()->Value(), "<b>I am > the rules!</b>\n...since I make symbolic puns", true ); #ifdef TIXML_USE_STL doc.Clear(); istringstream parse0( str ); parse0 >> doc; XmlTest( "CDATA stream. [ 1480107 ]", doc.FirstChildElement()->FirstChild()->Value(), "<b>I am > the rules!</b>\n...since I make symbolic puns", true ); #endif TiXmlDocument doc1 = doc; //doc.Print(); XmlTest( "CDATA copy. [ 1480107 ]", doc1.FirstChildElement()->FirstChild()->Value(), "<b>I am > the rules!</b>\n...since I make symbolic puns", true ); } ////////////////////////////////////////////////////// // Visit() ////////////////////////////////////////////////////// printf( "\n** Fuzzing... **\n" ); const int FUZZ_ITERATION = 300; // The only goal is not to crash on bad input. int len = (int) strlen( demoStart ); for( int i=0; i<FUZZ_ITERATION; ++i ) { char* demoCopy = new char[ len+1 ]; strcpy( demoCopy, demoStart ); demoCopy[ i%len ] = (char)((i+1)*3); demoCopy[ (i*7)%len ] = '>'; demoCopy[ (i*11)%len ] = '<'; TiXmlDocument xml; xml.Parse( demoCopy ); delete [] demoCopy; } printf( "** Fuzzing Complete. **\n" ); ////////////////////////////////////////////////////// printf ("\n** Bug regression tests **\n"); // InsertBeforeChild and InsertAfterChild causes crash. { TiXmlElement parent( "Parent" ); TiXmlElement childText0( "childText0" ); TiXmlElement childText1( "childText1" ); TiXmlNode* childNode0 = parent.InsertEndChild( childText0 ); TiXmlNode* childNode1 = parent.InsertBeforeChild( childNode0, childText1 ); XmlTest( "Test InsertBeforeChild on empty node.", ( childNode1 == parent.FirstChild() ), true ); } { // InsertBeforeChild and InsertAfterChild causes crash. TiXmlElement parent( "Parent" ); TiXmlElement childText0( "childText0" ); TiXmlElement childText1( "childText1" ); TiXmlNode* childNode0 = parent.InsertEndChild( childText0 ); TiXmlNode* childNode1 = parent.InsertAfterChild( childNode0, childText1 ); XmlTest( "Test InsertAfterChild on empty node. ", ( childNode1 == parent.LastChild() ), true ); } // Reports of missing constructors, irregular string problems. { // Missing constructor implementation. No test -- just compiles. TiXmlText text( "Missing" ); #ifdef TIXML_USE_STL // Missing implementation: TiXmlDocument doc; string name = "missing"; doc.LoadFile( name ); TiXmlText textSTL( name ); #else // verifying some basic string functions: TiXmlString a; TiXmlString b( "Hello" ); TiXmlString c( "ooga" ); c = " World!"; a = b; a += c; a = a; XmlTest( "Basic TiXmlString test. ", "Hello World!", a.c_str() ); #endif } // Long filenames crashing STL version { TiXmlDocument doc( "midsummerNightsDreamWithAVeryLongFilenameToConfuseTheStringHandlingRoutines.xml" ); bool loadOkay = doc.LoadFile(); loadOkay = true; // get rid of compiler warning. // Won't pass on non-dev systems. Just a "no crash" check. //XmlTest( "Long filename. ", true, loadOkay ); } { // Entities not being written correctly. // From Lynn Allen const char* passages = "<?xml version=\"1.0\" standalone=\"no\" ?>" "<passages count=\"006\" formatversion=\"20020620\">" "<psg context=\"Line 5 has "quotation marks" and 'apostrophe marks'." " It also has <, >, and &, as well as a fake copyright ©.\"> </psg>" "</passages>"; TiXmlDocument doc( "passages.xml" ); doc.Parse( passages ); TiXmlElement* psg = doc.RootElement()->FirstChildElement(); const char* context = psg->Attribute( "context" ); const char* expected = "Line 5 has \"quotation marks\" and 'apostrophe marks'. It also has <, >, and &, as well as a fake copyright \xC2\xA9."; XmlTest( "Entity transformation: read. ", expected, context, true ); FILE* textfile = fopen( "textfile.txt", "w" ); if ( textfile ) { psg->Print( textfile, 0 ); fclose( textfile ); } textfile = fopen( "textfile.txt", "r" ); assert( textfile ); if ( textfile ) { char buf[ 1024 ]; fgets( buf, 1024, textfile ); XmlTest( "Entity transformation: write. ", "<psg context=\'Line 5 has "quotation marks" and 'apostrophe marks'." " It also has <, >, and &, as well as a fake copyright \xC2\xA9.' />", buf, true ); } fclose( textfile ); } { FILE* textfile = fopen( "test5.xml", "w" ); if ( textfile ) { fputs("<?xml version='1.0'?><a.elem xmi.version='2.0'/>", textfile); fclose(textfile); TiXmlDocument doc; doc.LoadFile( "test5.xml" ); XmlTest( "dot in element attributes and names", doc.Error(), 0); } } { FILE* textfile = fopen( "test6.xml", "w" ); if ( textfile ) { fputs("<element><Name>1.1 Start easy ignore fin thickness
</Name></element>", textfile ); fclose(textfile); TiXmlDocument doc; bool result = doc.LoadFile( "test6.xml" ); XmlTest( "Entity with one digit.", result, true ); TiXmlText* text = doc.FirstChildElement()->FirstChildElement()->FirstChild()->ToText(); XmlTest( "Entity with one digit.", text->Value(), "1.1 Start easy ignore fin thickness\n" ); } } { // DOCTYPE not preserved (950171) // const char* doctype = "<?xml version=\"1.0\" ?>" "<!DOCTYPE PLAY SYSTEM 'play.dtd'>" "<!ELEMENT title (#PCDATA)>" "<!ELEMENT books (title,authors)>" "<element />"; TiXmlDocument doc; doc.Parse( doctype ); doc.SaveFile( "test7.xml" ); doc.Clear(); doc.LoadFile( "test7.xml" ); TiXmlHandle docH( &doc ); TiXmlUnknown* unknown = docH.Child( 1 ).Unknown(); XmlTest( "Correct value of unknown.", "!DOCTYPE PLAY SYSTEM 'play.dtd'", unknown->Value() ); #ifdef TIXML_USE_STL TiXmlNode* node = docH.Child( 2 ).Node(); std::string str; str << (*node); XmlTest( "Correct streaming of unknown.", "<!ELEMENT title (#PCDATA)>", str.c_str() ); #endif } { // [ 791411 ] Formatting bug // Comments do not stream out correctly. const char* doctype = "<!-- Somewhat<evil> -->"; TiXmlDocument doc; doc.Parse( doctype ); TiXmlHandle docH( &doc ); TiXmlComment* comment = docH.Child( 0 ).Node()->ToComment(); XmlTest( "Comment formatting.", " Somewhat<evil> ", comment->Value() ); #ifdef TIXML_USE_STL std::string str; str << (*comment); XmlTest( "Comment streaming.", "<!-- Somewhat<evil> -->", str.c_str() ); #endif } { // [ 870502 ] White space issues TiXmlDocument doc; TiXmlText* text; TiXmlHandle docH( &doc ); const char* doctype0 = "<element> This has leading and trailing space </element>"; const char* doctype1 = "<element>This has internal space</element>"; const char* doctype2 = "<element> This has leading, trailing, and internal space </element>"; TiXmlBase::SetCondenseWhiteSpace( false ); doc.Clear(); doc.Parse( doctype0 ); text = docH.FirstChildElement( "element" ).Child( 0 ).Text(); XmlTest( "White space kept.", " This has leading and trailing space ", text->Value() ); doc.Clear(); doc.Parse( doctype1 ); text = docH.FirstChildElement( "element" ).Child( 0 ).Text(); XmlTest( "White space kept.", "This has internal space", text->Value() ); doc.Clear(); doc.Parse( doctype2 ); text = docH.FirstChildElement( "element" ).Child( 0 ).Text(); XmlTest( "White space kept.", " This has leading, trailing, and internal space ", text->Value() ); TiXmlBase::SetCondenseWhiteSpace( true ); doc.Clear(); doc.Parse( doctype0 ); text = docH.FirstChildElement( "element" ).Child( 0 ).Text(); XmlTest( "White space condensed.", "This has leading and trailing space", text->Value() ); doc.Clear(); doc.Parse( doctype1 ); text = docH.FirstChildElement( "element" ).Child( 0 ).Text(); XmlTest( "White space condensed.", "This has internal space", text->Value() ); doc.Clear(); doc.Parse( doctype2 ); text = docH.FirstChildElement( "element" ).Child( 0 ).Text(); XmlTest( "White space condensed.", "This has leading, trailing, and internal space", text->Value() ); } { // Double attributes const char* doctype = "<element attr='red' attr='blue' />"; TiXmlDocument doc; doc.Parse( doctype ); XmlTest( "Parsing repeated attributes.", 0, (int)doc.Error() ); // not an error to tinyxml XmlTest( "Parsing repeated attributes.", "blue", doc.FirstChildElement( "element" )->Attribute( "attr" ) ); } { // Embedded null in stream. const char* doctype = "<element att\0r='red' attr='blue' />"; TiXmlDocument doc; doc.Parse( doctype ); XmlTest( "Embedded null throws error.", true, doc.Error() ); #ifdef TIXML_USE_STL istringstream strm( doctype ); doc.Clear(); doc.ClearError(); strm >> doc; XmlTest( "Embedded null throws error.", true, doc.Error() ); #endif } { // Legacy mode test. (This test may only pass on a western system) const char* str = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" "<ä>" "CöntäntßäöüÄÖÜ" "</ä>"; TiXmlDocument doc; doc.Parse( str ); TiXmlHandle docHandle( &doc ); TiXmlHandle aHandle = docHandle.FirstChildElement( "ä" ); TiXmlHandle tHandle = aHandle.Child( 0 ); assert( aHandle.Element() ); assert( tHandle.Text() ); XmlTest( "ISO-8859-1 Parsing.", "CöntäntßäöüÄÖÜ", tHandle.Text()->Value() ); } { // Empty documents should return TIXML_ERROR_PARSING_EMPTY, bug 1070717 const char* str = " "; TiXmlDocument doc; doc.Parse( str ); XmlTest( "Empty document error TIXML_ERROR_DOCUMENT_EMPTY", TiXmlBase::TIXML_ERROR_DOCUMENT_EMPTY, doc.ErrorId() ); } #ifndef TIXML_USE_STL { // String equality. [ 1006409 ] string operator==/!= no worky in all cases TiXmlString temp; XmlTest( "Empty tinyxml string compare equal", ( temp == "" ), true ); TiXmlString foo; TiXmlString bar( "" ); XmlTest( "Empty tinyxml string compare equal", ( foo == bar ), true ); } #endif { // Bug [ 1195696 ] from marlonism TiXmlBase::SetCondenseWhiteSpace(false); TiXmlDocument xml; xml.Parse("<text><break/>This hangs</text>"); XmlTest( "Test safe error return.", xml.Error(), false ); } { // Bug [ 1243992 ] - another infinite loop TiXmlDocument doc; doc.SetCondenseWhiteSpace(false); doc.Parse("<p><pb></pb>test</p>"); } { // Low entities TiXmlDocument xml; xml.Parse( "<test></test>" ); const char result[] = { 0x0e, 0 }; XmlTest( "Low entities.", xml.FirstChildElement()->GetText(), result ); xml.Print(); } { // Bug [ 1451649 ] Attribute values with trailing quotes not handled correctly TiXmlDocument xml; xml.Parse( "<foo attribute=bar\" />" ); XmlTest( "Throw error with bad end quotes.", xml.Error(), true ); } #ifdef TIXML_USE_STL { // Bug [ 1449463 ] Consider generic query TiXmlDocument xml; xml.Parse( "<foo bar='3' barStr='a string'/>" ); TiXmlElement* ele = xml.FirstChildElement(); double d; int i; float f; bool b; //std::string str; XmlTest( "QueryValueAttribute", ele->QueryValueAttribute( "bar", &d ), TIXML_SUCCESS ); XmlTest( "QueryValueAttribute", ele->QueryValueAttribute( "bar", &i ), TIXML_SUCCESS ); XmlTest( "QueryValueAttribute", ele->QueryValueAttribute( "bar", &f ), TIXML_SUCCESS ); XmlTest( "QueryValueAttribute", ele->QueryValueAttribute( "bar", &b ), TIXML_WRONG_TYPE ); XmlTest( "QueryValueAttribute", ele->QueryValueAttribute( "nobar", &b ), TIXML_NO_ATTRIBUTE ); //XmlTest( "QueryValueAttribute", ele->QueryValueAttribute( "barStr", &str ), TIXML_SUCCESS ); XmlTest( "QueryValueAttribute", (d==3.0), true ); XmlTest( "QueryValueAttribute", (i==3), true ); XmlTest( "QueryValueAttribute", (f==3.0f), true ); //XmlTest( "QueryValueAttribute", (str==std::string( "a string" )), true ); } #endif #ifdef TIXML_USE_STL { // [ 1505267 ] redundant malloc in TiXmlElement::Attribute TiXmlDocument xml; xml.Parse( "<foo bar='3' />" ); TiXmlElement* ele = xml.FirstChildElement(); double d; int i; std::string bar = "bar"; const std::string* atrrib = ele->Attribute( bar ); ele->Attribute( bar, &d ); ele->Attribute( bar, &i ); XmlTest( "Attribute", atrrib->empty(), false ); XmlTest( "Attribute", (d==3.0), true ); XmlTest( "Attribute", (i==3), true ); } #endif { // [ 1356059 ] Allow TiXMLDocument to only be at the top level TiXmlDocument xml, xml2; xml.InsertEndChild( xml2 ); XmlTest( "Document only at top level.", xml.Error(), true ); XmlTest( "Document only at top level.", xml.ErrorId(), TiXmlBase::TIXML_ERROR_DOCUMENT_TOP_ONLY ); } { // [ 1663758 ] Failure to report error on bad XML TiXmlDocument xml; xml.Parse("<x>"); XmlTest("Missing end tag at end of input", xml.Error(), true); xml.Parse("<x> "); XmlTest("Missing end tag with trailing whitespace", xml.Error(), true); } { // [ 1635701 ] fail to parse files with a tag separated into two lines // I'm not sure this is a bug. Marked 'pending' for feedback. TiXmlDocument xml; xml.Parse( "<title><p>text</p\n><title>" ); //xml.Print(); //XmlTest( "Tag split by newline", xml.Error(), false ); } #ifdef TIXML_USE_STL { // [ 1475201 ] TinyXML parses entities in comments TiXmlDocument xml; istringstream parse1( "<!-- declarations for <head> & <body> -->" "<!-- far & away -->" ); parse1 >> xml; TiXmlNode* e0 = xml.FirstChild(); TiXmlNode* e1 = e0->NextSibling(); TiXmlComment* c0 = e0->ToComment(); TiXmlComment* c1 = e1->ToComment(); XmlTest( "Comments ignore entities.", " declarations for <head> & <body> ", c0->Value(), true ); XmlTest( "Comments ignore entities.", " far & away ", c1->Value(), true ); } #endif { // [ 1475201 ] TinyXML parses entities in comments TiXmlDocument xml; xml.Parse("<!-- declarations for <head> & <body> -->" "<!-- far & away -->" ); TiXmlNode* e0 = xml.FirstChild(); TiXmlNode* e1 = e0->NextSibling(); TiXmlComment* c0 = e0->ToComment(); TiXmlComment* c1 = e1->ToComment(); XmlTest( "Comments ignore entities.", " declarations for <head> & <body> ", c0->Value(), true ); XmlTest( "Comments ignore entities.", " far & away ", c1->Value(), true ); } /* { TiXmlDocument xml; xml.Parse( "<tag>/</tag>" ); xml.Print(); xml.FirstChild()->Print( stdout, 0 ); xml.FirstChild()->Type(); } */ /* 1417717 experiment { TiXmlDocument xml; xml.Parse("<text>Dan & Tracie</text>"); xml.Print(stdout); } { TiXmlDocument xml; xml.Parse("<text>Dan &foo; Tracie</text>"); xml.Print(stdout); } */ #if defined( WIN32 ) && defined( TUNE ) _CrtMemCheckpoint( &endMemState ); //_CrtMemDumpStatistics( &endMemState ); _CrtMemState diffMemState; _CrtMemDifference( &diffMemState, &startMemState, &endMemState ); _CrtMemDumpStatistics( &diffMemState ); #endif printf ("\nPass %d, Fail %d\n", gPass, gFail); return gFail; }
int CourseMainInfoXml::UpdateScore(string CourseID, int Score, int flower ,bool isFirst) { if( pFirstBookElem != NULL && pRootElement != NULL) { TiXmlElement *FirstCourseItem = pFirstBookElem; while ( FirstCourseItem != NULL ) { TiXmlElement *FirstCourseIDItem = FirstCourseItem->FirstChildElement(); string IDElem = FirstCourseIDItem->FirstChild()->Value(); if( strcmp(IDElem.c_str() , CourseID.c_str()) ==0) { TiXmlElement *FirstCourseNameItem = FirstCourseIDItem->NextSiblingElement(); TiXmlElement *FirstCourseIntroItem = FirstCourseNameItem->NextSiblingElement(); TiXmlElement *FirstCourseScoreItem = FirstCourseIntroItem->NextSiblingElement(); TiXmlElement *FirstCourseRecentScoreItem = FirstCourseScoreItem->NextSiblingElement(); TiXmlElement *FirstCourseFlowerItem = FirstCourseRecentScoreItem->NextSiblingElement(); char cflower[2] = {0}; sprintf(cflower, "%d" ,flower); FirstCourseFlowerItem->FirstChild()->SetValue(cflower); char cscore[3] = {0}; sprintf(cscore, "%d" ,Score); if(isFirst) { if(FirstCourseScoreItem->FirstChild() != NULL) { FirstCourseScoreItem->FirstChild()->SetValue(cscore); } else { TiXmlText *pNewTextCoureScore = new TiXmlText(cscore); FirstCourseScoreItem->LinkEndChild(pNewTextCoureScore); } } //first score is also recent score if(FirstCourseRecentScoreItem->FirstChild() != NULL) { FirstCourseRecentScoreItem->FirstChild()->SetValue(cscore); } else { TiXmlText *pNewTextCoureScore = new TiXmlText(cscore); FirstCourseRecentScoreItem->LinkEndChild(pNewTextCoureScore); } myDocument->SaveFile(); return 0; } FirstCourseItem = FirstCourseItem->NextSiblingElement(); }//not found return -1; } }
bool UrdfParser::parseVisual(UrdfModel& model, UrdfVisual& visual, TiXmlElement* config, ErrorLogger* logger) { visual.m_linkLocalFrame.setIdentity(); // Origin TiXmlElement *o = config->FirstChildElement("origin"); if (o) { if (!parseTransform(visual.m_linkLocalFrame, o,logger)) return false; } // Geometry TiXmlElement *geom = config->FirstChildElement("geometry"); if (!parseGeometry(visual.m_geometry,geom,logger)) { return false; } const char *name_char = config->Attribute("name"); if (name_char) visual.m_name = name_char; visual.m_hasLocalMaterial = false; // Material TiXmlElement *mat = config->FirstChildElement("material"); //todo(erwincoumans) skip materials in SDF for now (due to complexity) if (mat) { if (m_parseSDF) { UrdfMaterial* matPtr = new UrdfMaterial; matPtr->m_name = "mat"; TiXmlElement *diffuse = mat->FirstChildElement("diffuse"); if (diffuse) { std::string diffuseText = diffuse->GetText(); btVector4 rgba(1,0,0,1); parseVector4(rgba,diffuseText); matPtr->m_rgbaColor = rgba; model.m_materials.insert(matPtr->m_name.c_str(),matPtr); visual.m_materialName = "mat"; visual.m_hasLocalMaterial = true; } } else { // get material name if (!mat->Attribute("name")) { logger->reportError("Visual material must contain a name attribute"); return false; } visual.m_materialName = mat->Attribute("name"); // try to parse material element in place TiXmlElement *t = mat->FirstChildElement("texture"); TiXmlElement *c = mat->FirstChildElement("color"); if (t||c) { if (parseMaterial(visual.m_localMaterial, mat,logger)) { UrdfMaterial* matPtr = new UrdfMaterial(visual.m_localMaterial); model.m_materials.insert(matPtr->m_name.c_str(),matPtr); visual.m_hasLocalMaterial = true; } } } } return true; }
int CourseMainInfoXml::LoadXml(const char *XmlFilePath) { if(XXml::LoadXml(XmlFilePath)<0) return -1; myDocument = new TiXmlDocument(XmlFilePath); myDocument ->LoadFile(); //begin read pRootElement = myDocument->RootElement();//CourseMainInfo if(pRootElement == NULL) return -1; strCourseMainInfoVersion = pRootElement->Attribute("version"); //TiXmlElement *NewCourseIDItem = pRootElement->FirstChildElement(); TiXmlElement *DelCourseIDItem = pRootElement->FirstChildElement(); // if(NewCourseIDItem->FirstChild() != NULL) // { // string strNewID = NewCourseIDItem->FirstChild()->Value(); // splitString( strNewID, "|", vNewID) ; // } if(DelCourseIDItem->FirstChild() != NULL) { string strDelID = DelCourseIDItem->FirstChild()->Value(); splitString( strDelID, ",", vDelID) ; } TiXmlElement *CourseListItem = DelCourseIDItem->NextSiblingElement(); TiXmlElement *FirstCourseItem = CourseListItem->FirstChildElement(); pFirstBookElem = FirstCourseItem; int index = 0; CourseMainInfo CMI; while ( FirstCourseItem != NULL ) { TiXmlElement *FirstCourseIDItem = FirstCourseItem->FirstChildElement(); CMI.CourseID = FirstCourseIDItem->FirstChild()->Value(); TiXmlElement *FirstCourseNameItem = FirstCourseIDItem->NextSiblingElement(); CMI.CourseName = FirstCourseNameItem->FirstChild()->Value(); TiXmlElement *FirstCourseIntroItem = FirstCourseNameItem->NextSiblingElement(); CMI.CourseIntro = FirstCourseIntroItem->FirstChild()->Value(); TiXmlElement *FirstCourseScoreItem = FirstCourseIntroItem->NextSiblingElement(); if(FirstCourseScoreItem->FirstChild() != NULL) { CMI.FirstScore = atoi(FirstCourseScoreItem->FirstChild()->Value()); } else { CMI.FirstScore = 0; } TiXmlElement *FirstCourseRecentScoreItem = FirstCourseScoreItem->NextSiblingElement(); if(FirstCourseRecentScoreItem->FirstChild() != NULL) { CMI.RecentScore = atoi(FirstCourseRecentScoreItem->FirstChild()->Value()); } else { CMI.RecentScore = 0; } TiXmlElement *FirstCourseFlowerItem = FirstCourseRecentScoreItem->NextSiblingElement(); if(FirstCourseFlowerItem->FirstChild() != NULL) { CMI.Flower = atoi(FirstCourseFlowerItem->FirstChild()->Value()); } else { CMI.Flower = 0; } TiXmlElement *FirstCourseHashItem = FirstCourseFlowerItem->NextSiblingElement(); CMI.Hash = FirstCourseHashItem->FirstChild()->Value(); TiXmlElement *FirstCourseIsNewItem = FirstCourseHashItem->NextSiblingElement(); CMI.IsNew = atoi(FirstCourseIsNewItem->FirstChild()->Value()); index = index + 1; VCourseMainInfo.push_back(CMI); FirstCourseItem = FirstCourseItem->NextSiblingElement(); } //end read cout <<"\nindex = "<< index << "#### Loop done ####" <<endl; return 1; }
virtual void OnbtnImportClick( wxCommandEvent& event ) { wxString strInputPath = m_textCtrlVSPrjPath->GetValue(); TiXmlDocument doc(strInputPath); wxFileName fn(strInputPath); int i; wxString strSavePath =wxString::Format("%s\\%s.import.vcproj", fn.GetPath(), fn.GetName()); // 获取多个Filter的信息 DoGetGridInfoString(); int num = m_GridInfoPtr.GetCount(); if (num<=0) { wxMessageBox("Not Import Path"); return; } m_strInfo.empty(); for (i=0; i<num; i++) { // 多个Filter m_iTreeLevel = 0; CGridInfo *pInfo = (CGridInfo*)m_GridInfoPtr[i]; pInfo->pElement = newFilter(pInfo->strFilterName); dirTrace(pInfo->strFilterPath, pInfo->pElement); } m_textCtrlInfo->AppendText(m_strInfo); if (!doc.LoadFile()) { wxMessageBox(wxT("Load Fail")); return; } // 删除重复的多个Filter TiXmlElement* root = doc.FirstChildElement("VisualStudioProject"); if (root) { TiXmlElement *files = root->FirstChildElement("Files"); if (files) { TiXmlElement* filter = files->FirstChildElement("Filter"); while(filter) { wxString str = filter->Attribute("Name"); for (i=0; i<num; i++) { CGridInfo *pInfo = (CGridInfo*)m_GridInfoPtr[i]; if (str == pInfo->strFilterName) { files->RemoveChild(filter); break; } } filter = filter->NextSiblingElement("Filter"); } for (i=0; i<num; i++) { CGridInfo *pInfo = (CGridInfo*)m_GridInfoPtr[i]; files->LinkEndChild(pInfo->pElement); } } } doc.SaveFile(strSavePath); m_textCtrlInfo->AppendText("\n ** Output Project Path: " + strSavePath); /* <Files> <Filter Name="源文件" Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx" UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}" > <File RelativePath=".\main.cpp" > </File> </Filter> <Filter Name="头文件" Filter="h;hpp;hxx;hm;inl;inc;xsd" UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}" > </Filter> <Filter Name="资源文件" Filter="rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav" UniqueIdentifier="{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}" > </Filter> </Files>*/ }
bool FiledScene::init(){ if (!Layer::init()) return false; _isGameOver = false; auto visibleSize = Director::getInstance()->getVisibleSize(); _screenWidth = visibleSize.width; _screenHeight = visibleSize.height; _tileMap = TMXTiledMap::create("field_map.tmx"); _tileMap->setAnchorPoint(Vec2::ANCHOR_MIDDLE); _tileMap->setPosition(Vec2(visibleSize.width / 2, visibleSize.height / 2)); // ②获取障碍层,并设置障碍层为不可见 _collidable = _tileMap->getLayer("collidable"); _collidable->setVisible(false); /********③初始化读取地图所有网格,并确定网格对象是否是障碍物,将信息保存到网格二维数组**************/ for (int i = 0; i < _tileMap->getMapSize().width; i++) { // 内部网格集合([x,0]-[x-20]),存储网格 Vector<Grid*> inner; for (int j = 0; j < _tileMap->getMapSize().height; j++) { // 设置网格对象的x轴和y轴以及是否可通过变量值 Grid *o = Grid::create(i, j); // 将网格加入到集合 inner.pushBack(o); } // 将内部集合加入到网格集合 _gridVector.push_back(inner); } // 循环保存根据每个网格的x轴和y轴查找对应的地图的GID,判断是否可通过 for (int i = 0; i < _gridVector.size(); i++) { Vector<Grid*> inner = _gridVector.at(i); // 循环内部网格集合 for (int j = 0; j < inner.size(); j++) { // 获取每一个网格对象 Grid *grid = inner.at(j); // 获取每一个网格对象对应的的坐标 Vec2 tileCoord = Vec2(grid->getX(), grid->getY()); // 使用TMXLayer类的tileGIDAt函数获取TileMap坐标系里的“全局唯一标识”GID int tileGid = _collidable->getTileGIDAt(tileCoord); if (tileGid) { // 使用GID来查找指定tile的属性,返回一个Value Value properties = _tileMap->getPropertiesForGID(tileGid); // 返回的Value实际是一个ValueMap ValueMap map = properties.asValueMap(); // 查找ValueMap,判断是否有”可碰撞的“物体,如果有,设置网格对象的isPass变量为false std::string value = map.at("collidable").asString(); if (value.compare("true") == 0) { grid->setPass(false); } } } } // 人物出场特效 auto effects_player_out = Sprite::create("effects/effects_player_out/effects_player_out_11.png"); effects_player_out->setPosition(Vec2(visibleSize.width*0.3,visibleSize.height*0.3)); this->addChild(effects_player_out, 1); auto player_out_animate = getAnimateByName("effects/effects_player_out/effects_player_out_", 0.1f, 11); auto delay1 = DelayTime::create(1.5f); auto fadeOut = FadeOut::create(0.2f); auto sequence = Sequence::create(delay1, player_out_animate, fadeOut, nullptr); effects_player_out->runAction(sequence); _player = SpriteBase::create("player/player_sword/player_sword_stand.png"); this->addChild(_player, 1); _player->setPosition(Vec2(visibleSize.width*0.3, visibleSize.height*0.3)); this->addChild(_tileMap,0); _player->setFlippedX(true); XmlTools::readPlayerData(_player); /// 传送门 ArmatureDataManager::getInstance()->addArmatureFileInfo("/buildings/gate/AnimationStart0.png", "/buildings/gate/AnimationStart0.plist", "/buildings/gate/AnimationStart.ExportJson"); Armature *armature = Armature::create("AnimationStart"); armature->getAnimation()->play("Start"); this->addChild(armature); armature->setScale(0.3); armature->setPosition(Vec2(visibleSize.width*0.9, visibleSize.height*0.7)); auto gate_effect = ParticleSystemQuad::create("effects/gate_effect.plist"); this->addChild(gate_effect); gate_effect->setScale(0.3); gate_effect->setPosition(Vec2(visibleSize.width*0.9, visibleSize.height*0.75)); gate_effect->setPositionType(kCCPositionTypeRelative); // 结束战斗按钮 auto end_fight_button = Button::create("ui/end_fight.png"); end_fight_button->setPosition(Vec2(visibleSize.width*0.95, visibleSize.height*0.97)); end_fight_button->setScale(0.5f); this->addChild(end_fight_button, 0); //结束战斗对话框 auto end_fight_dialog_bg = Sprite::create("ui/end_fight_dialog_bg.png"); end_fight_dialog_bg->setAnchorPoint(Vec2::ANCHOR_MIDDLE); end_fight_dialog_bg->setPosition(Vec2(visibleSize.width / 2, visibleSize.height / 2)); this->addChild(end_fight_dialog_bg, 3); // 确定结束战斗按钮 auto end_fight_sub_button = Button::create("ui/end_fight_sub_button.png"); end_fight_dialog_bg->addChild(end_fight_sub_button); end_fight_sub_button->setAnchorPoint(Vec2::ZERO); end_fight_sub_button->setPosition(Vec2(20, 30)); end_fight_sub_button->addTouchEventListener([=](Ref* pSender, Widget::TouchEventType type){ XmlTools::writePlayerData(_player); auto transition = TransitionSplitCols::create(2, Game::createScene()); Director::getInstance()->pushScene(transition); }); // 取消结束战斗按钮 auto end_fight_cancel_button = Button::create("ui/end_fight_cancel_button.png"); end_fight_dialog_bg->addChild(end_fight_cancel_button); end_fight_cancel_button->setAnchorPoint(Vec2::ZERO); end_fight_cancel_button->setPosition(Vec2(140, 30)); end_fight_cancel_button->addTouchEventListener([=](Ref* pSender, Widget::TouchEventType type){ end_fight_dialog_bg->setVisible(false); }); end_fight_dialog_bg->setVisible(false); end_fight_button->addTouchEventListener([=](Ref* pSender, Widget::TouchEventType type){ if (type == Widget::TouchEventType::ENDED){ end_fight_dialog_bg->setVisible(true); } }); // ⑤创建事件监听器 auto gameListener = EventListenerTouchOneByOne::create(); // 响应触摸事件函数 gameListener->onTouchBegan = [](Touch* touch, Event* event){return true; }; gameListener->onTouchEnded = [=](Touch *touch, Event *event){ // OpenGL坐标 Vec2 touchLocation = touch->getLocation(); // 将触摸点坐标转换成相对的Node坐标 Vec2 nodeLocation = this->convertToNodeSpace(touchLocation); // 玩家镜像反转 if (_player->getPosition().x > nodeLocation.x) { if (_player->isFlippedX() == true){ _player->setFlippedX(false); } } else{ if (_player->isFlippedX() == false) _player->setFlippedX(true); } // 用玩家位置作为起点,触摸点作为终点,转换为网格坐标,在地图上查找最佳到达路径 Vec2 from = tileCoordForPosition(_player->getPosition()); Vec2 to = tileCoordForPosition(nodeLocation); // 如果终点是不可通过(即有障碍物)的位置,则直接return int tileGid = _collidable->getTileGIDAt(to); if (tileGid) { // 使用GID来查找指定tile的属性,返回一个Value Value properties = _tileMap->getPropertiesForGID(tileGid); // 返回的Value实际是一个ValueMap ValueMap map = properties.asValueMap(); // 查找ValueMap,判断是否有”可碰撞的“物体,如果有,直接返回 std::string value = map.at("collidable").asString(); if (value.compare("true") == 0) { return; } } /**************玩家精灵移动到指定位置************************/ // 在玩家精灵移动过程中,如果用户在此触摸屏幕移动玩家时,如果精灵没有运行动作,直接执行移动动作 if (_player->getNumberOfRunningActions() == 0) { this->playerMover(nodeLocation); } else { //如果精灵正在运行动作,先停止精灵动作和层动作,再执行移动动作 _player->stopAllActions(); this->stopAllActions(); this->playerMover(nodeLocation); } // 接触传送门, 如果boss被杀死, 则传送回主场景. if (_player->getBoundingBox().intersectsRect(armature->getBoundingBox())){ if (monster_1->isVisible()==false){ _player->setExp(_player->getExp() + 200); _player->setGold(_player->getGold() + 1000); XmlTools::writePlayerData(_player); const string player_task = FileUtils::getInstance()->fullPathForFilename("data/kill_count.xml"); ssize_t player_taskFile_size; char* pPlayerTaskContent = (char*)FileUtils::getInstance()->getFileData(player_task, "r", &player_taskFile_size); TiXmlDocument* player_task_el = new TiXmlDocument(); player_task_el->Parse(pPlayerTaskContent, 0, TIXML_ENCODING_UTF8); TiXmlElement* rootElement = player_task_el->RootElement();//Root TiXmlElement* player_kill_count_1 = rootElement->FirstChildElement(); string accept = player_kill_count_1->GetText(); TiXmlElement* player_kill_count_2 = player_kill_count_1->NextSiblingElement(); stringstream ss; string kill_count = player_kill_count_2->GetText(); int kill_count_int; ss << kill_count; ss >> kill_count_int; if (accept=="true"){ kill_count_int += 1; player_kill_count_2->Clear(); string kill_count_str; stringstream ss; ss << kill_count_int; ss >> kill_count_str; TiXmlText* kill_count_text = new TiXmlText(kill_count_str.c_str()); player_kill_count_2->LinkEndChild(kill_count_text); player_task_el->SaveFile(player_task.c_str()); } auto transform_to = TransitionSplitCols::create(2.0f, Game::createScene()); Director::getInstance()->pushScene(transform_to); }