blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
5
146
content_id
stringlengths
40
40
detected_licenses
listlengths
0
7
license_type
stringclasses
2 values
repo_name
stringlengths
6
79
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
4 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.07k
426M
star_events_count
int64
0
27
fork_events_count
int64
0
12
gha_license_id
stringclasses
3 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
6 values
src_encoding
stringclasses
26 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
1 class
length_bytes
int64
20
6.28M
extension
stringclasses
20 values
content
stringlengths
20
6.28M
authors
listlengths
1
16
author_lines
listlengths
1
16
242191e7fdb06250204e0288de43f1c313c986e2
478570cde911b8e8e39046de62d3b5966b850384
/apicompatanamdw/bcdrivers/mw/ipappprotocols/sip/sipclient/inc/t_csipclienttransaction.h
abeb563a38df5740e041d87c53023ef1bda04ed7
[]
no_license
SymbianSource/oss.FCL.sftools.ana.compatanamdw
a6a8abf9ef7ad71021d43b7f2b2076b504d4445e
1169475bbf82ebb763de36686d144336fcf9d93b
refs/heads/master
2020-12-24T12:29:44.646072
2010-11-11T14:03:20
2010-11-11T14:03:20
72,994,432
0
0
null
null
null
null
UTF-8
C++
false
false
1,778
h
/* * Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of "Eclipse Public License v1.0" * which accompanies this distribution, and is available * at the URL "http://www.eclipse.org/legal/epl-v10.html". * * Initial Contributors: * Nokia Corporation - initial contribution. * * Contributors: * * Description: * */ // This contains CT_DataSIPClientTransaction #ifndef __T_SIPCLIENTTRANSACTION__ #define __T_SIPCLIENTTRANSACTION__ // User includes #include "t_csiptransactionbase.h" #include <sipclienttransaction.h> class CT_DataSIPClientTransaction : public CT_DataSIPTransactionBase { public: static CT_DataSIPClientTransaction* NewL(); ~CT_DataSIPClientTransaction(); virtual TBool DoCommandL(const TTEFFunction& aCommand, const TTEFSectionName& aSection, const TInt aAsyncErrorIndex); virtual TAny* GetObject(); virtual void SetObjectL(TAny* aAny); virtual void DisownObjectL(); void SetIsOwner(TBool aIsOwner); protected: CT_DataSIPClientTransaction(); void ConstructL(); virtual CSIPTransactionBase* GetSIPTransactionBaseObject() const; private: void DoCmdCancelAllowed(const TTEFSectionName& aSection); void DoCmdCancelL(const TTEFSectionName& aSection); void DoCmdRefreshL(const TTEFSectionName& aSection); void DoCmdResponseElementsL(const TTEFSectionName& aSection); void DoCmdDestructor(const TTEFSectionName& aSection); void DestroyData(); private: CSIPClientTransaction* iSIPClientTransaction; TBool iIsOwner; }; #endif /* __T_SIPCLIENTTRANSACTION__ */
[ "none@none" ]
[ [ [ 1, 59 ] ] ]
00842746ac89fbfa21340ccd81454efe6b908dea
4d7f00745c1e8c04282cbde64066fe0684d1144e
/itsumo/src/interface/filehandler.cpp
bdab3fd277b775dd02214c3c9f45da7a96d9b470
[]
no_license
NiNjA-CodE/itsumo
45b5f7ce09c52300dee3a4a58a9e02c26ef46579
8bf7d590b520ec0be79f80a82370ee26314238da
refs/heads/master
2021-01-23T21:30:46.344786
2011-10-13T00:07:06
2011-10-13T00:07:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
51,221
cpp
#include "filehandler.h" #include <qstringlist.h> #include <qfile.h> #include <string> #include <qpoint.h> #include <qmessagebox.h> #include <qdir.h> #include "../tiny/tinyxml.h" #include <iostream> using namespace std; FileHandler::FileHandler() : QDomDocument() { loaded_ = false; if (confLoad()) { loaded_ = true; } } FileHandler::~FileHandler() { } ///Load the configuration file that defines templates for drivers. int FileHandler::confLoad() { //open the file QFile f( "src/interface/drivers.xml" ); //todo: outside it if ( !f.open( IO_ReadOnly ) ) return 0; if ( !setContent( &f ) ) { f.close(); return 0; } f.close(); QDomNode n = firstChild(); n = n.firstChild(); //DRIVERS if (!n.isNull()) { QDomNode p;//properties of drivers QDomElement de;//property element QString option = ""; while (!n.isNull()) { XmlDriver driver; XmlDriverOptions options; driver.name = n.namedItem("name").toElement().text(); driver.nick = n.namedItem("nick").toElement().text(); driver.description = n.namedItem("description").toElement().text(); p = n.firstChild(); while (!p.isNull()) { de = p.toElement(); if ( (de.tagName() == "option") ) { options.push_back(qMakePair(de.text(), option)); } p = p.nextSibling(); } driver.options = options; confDrvList_.push_back(driver); n = n.nextSibling(); } } return 1; } ///Save the configuration file that defines templates for drivers. int FileHandler::confSave() { QDomText t; QString aux = ""; setContent(aux); //general QDomElement root = createElement( "drivers" ); appendChild( root ); if (confDrvList_.isEmpty()) { t = createTextNode( "" ); root.appendChild( t ); } else //populate { QDomElement driver; QDomElement opn ; QDomElement on; XmlDriverList::iterator itD; for (itD = confDrvList_.begin(); itD != confDrvList_.end(); itD++) { driver = createElement( "driver" ); root.appendChild(driver); //name opn = createElement( "name" ); driver.appendChild(opn); t = createTextNode( itD->name ); opn.appendChild( t ); //nick opn = createElement( "nick" ); driver.appendChild(opn); t = createTextNode( itD->nick ); opn.appendChild( t ); //description opn = createElement( "description" ); driver.appendChild(opn); t = createTextNode( itD->description ); opn.appendChild( t ); //options XmlDriverOptions options = itD->options; if (options.isEmpty()) { t = createTextNode( "" ); driver.appendChild( t ); } else { QDomElement temp;//rever XmlDriverOptions::iterator itOp; for (itOp = options.begin(); itOp != options.end(); itOp++) { QString p = itOp->first; //option temp = createElement( "option" ); driver.appendChild(temp); t = createTextNode( itOp->first ); temp.appendChild( t ); } } } } QStringList xml(toString()); QFile f( "src/interface/drivers.xml" ); if ( f.open( IO_WriteOnly ) ) { QTextStream stream( &f ); for ( QStringList::Iterator it = xml.begin(); it != xml.end(); ++it ) stream << *it << "\n"; f.close(); } else return 0; return 1;; } ///Return names for available template drivers. ///\param list: vector os names. int FileHandler::confDrivers(XmlDrivers& list) { XmlDriverList::iterator it; for (it = confDrvList_.begin(); it != confDrvList_.end(); it++) { list.push_back(it->nick); } return 1; } ///Insert a template driver. ///\param name: name of template. int FileHandler::insertTemplateDriver(const QString& name) { XmlDriver driver; XmlDriverList::iterator it; driver.name = name; for (it = confDrvList_.begin(); it != confDrvList_.end(); it++) { QString object = it->nick; object.replace(" ", ""); if(object == name) return 0; } confDrvList_.push_back(driver); return 1; } ///Remove a template driver. ///\param name: name of template. int FileHandler::removeTemplateDriver(const QString& name) { XmlDriverList::iterator it; bool found = false; for (it = confDrvList_.begin(); it != confDrvList_.end(); it++) { if(it->nick == name) { found = true; break; } } if (found) confDrvList_.erase(it); return 1; } ///Return the template structure of driver. int FileHandler::getTemplateDriver(const QString& name, XmlDriver& driver) { XmlDriverList::iterator it; for (it = confDrvList_.begin(); it != confDrvList_.end(); it++) { if(it->nick == name) driver = *it; } return 1; } ///Add or remove an option from the list. ///\param driver: name of model. ///\param option: name of option. int FileHandler::editTemplateOption(const int& op, const QString& driver, const QPair<QString, QString>& option) { QString aux; XmlDriverList::iterator it; XmlDriverOptions::iterator itOp; XmlDriverOptions::iterator itFound=NULL; for (it = confDrvList_.begin(); it != confDrvList_.end(); it++) { QString object = it->nick; object.replace(" ", ""); if( (object == driver) || (driver == it->nick) ) { bool exists = false; if (option.first == "name") { it->name = option.second; } else if (option.first == "description") { it->description = option.second; } else { for (itOp=it->options.begin(); itOp!=it->options.end(); itOp++) { QString objectProp = itOp->first; object.replace(" ", ""); if(objectProp == option.first) { exists = true; itFound = itOp; break; } } if ((op == 1) && (exists))//remove { it->options.erase(itFound); } else if (op == 3)//edit { if (!exists) { QString empty = ""; it->options.push_back(qMakePair(option.second, empty)); } else itFound->second = option.second; } } } } return 1; } //********************************************************************* //********************************************************************* //********************************************************************* SimFileHandler::SimFileHandler() : FileHandler() { dList_ = static_cast<unsigned int>(NULL); sList_ = static_cast<unsigned int>(NULL); configFile_ = ""; } SimFileHandler::~SimFileHandler() { } ///Load the XML structure of the XML file. ///\param file: name of te file to be loaded. ///\return: status of operation. int SimFileHandler::load( const QString& file ) { //open the file QFile f( file ); if ( !f.open( IO_ReadOnly ) ) return 0; if ( !setContent( &f ) ) { f.close(); return 0; } f.close(); configFile_ = file; QDomNode dn; //drivers node QDomNode sn; //sensors node QDomNode n = firstChild(); dn = n.namedItem("drivers"); sn = n.namedItem("sensors"); QDomElement e; simConf.netFile = n.namedItem("file").toElement().text(); simConf.steps = n.namedItem("steps").toElement().text().toInt(); simConf.defDec = n.namedItem("default_deceleration").toElement().text().toDouble(); simConf.sensorInterval = n.namedItem("sensor_interval").toElement().text().toInt(); simConf.agentInterval = n.namedItem("agent_interval").toElement().text().toInt(); simConf.carMaxSpeed = n.namedItem("car_max_speed").toElement().text().toInt(); simConf.cellSize = n.namedItem("cell_size").toElement().text().toInt(); simConf.iterationLength = n.namedItem("iteration_length").toElement().text().toInt(); //DRIVERS if (!dn.isNull()) { dn = dn.firstChild(); while (!dn.isNull()) { XmlDriver driver; XmlDriverOptions options; QDomNode op;//option node QDomElement ope;//option element driver.name = dn.namedItem("name").toElement().text(); driver.nick = dn.namedItem("nick").toElement().text(); driver.number = dn.namedItem("number").toElement().text().toInt(); driver.state = dn.namedItem("state").toElement().text(); driver.debug = dn.namedItem("debug").toElement().text(); if (dn.namedItem("options").hasChildNodes()) { op = dn.namedItem("options").firstChild(); while (!op.isNull()) { ope = op.toElement(); options.push_back(qMakePair(ope.tagName(), ope.text())); op = op.nextSibling(); } } if (dn.namedItem("routes").hasChildNodes()) { op = dn.namedItem("routes").firstChild(); while (!op.isNull()) { Route r; r.laneset = op.namedItem("laneset").toElement().text().toInt(); driver.route.push_back(r); op = op.nextSibling(); } } driver.options = options; dList_.push_back(driver); dn = dn.nextSibling(); } } //SENSORS if (!sn.isNull()) { sn = sn.firstChild(); while (!sn.isNull()) { XmlSensor sensor; sensor.name = sn.namedItem("name").toElement().text(); sensor.file = sn.namedItem("file").toElement().text(); sensor.state = sn.namedItem("state").toElement().text(); sensor.timetag = sn.namedItem("time_tag").toElement().text(); sList_.push_back(sensor); sn = sn.nextSibling(); } } return 1; } ///Save the XML structure of the XML file. ///\param file: name of te file to be loaded. ///\return: status of operation. int SimFileHandler::save(const QString& file) { if ( (file == "") && (configFile_ == "") ) { return 0; } if ((file != "") && (file.right(4) != ".xml")) configFile_ = file + ".xml"; else configFile_ = file; QDomText t; QString aux = ""; setContent(aux); //general QDomElement root = createElement( "config" ); appendChild( root ); QDomElement fn = createElement( "file" ); root.appendChild( fn ); t = createTextNode( simConf.netFile ); fn.appendChild( t ); QDomElement stn = createElement( "steps" ); root.appendChild( stn ); t = createTextNode( aux.setNum(simConf.steps) ); stn.appendChild( t ); QDomElement ddn = createElement( "default_deceleration" ); root.appendChild( ddn ); t = createTextNode( aux.setNum(simConf.defDec) ); ddn.appendChild( t ); QDomElement sin = createElement( "sensor_interval" ); root.appendChild( sin ); t = createTextNode( aux.setNum(simConf.sensorInterval) ); sin.appendChild( t ); QDomElement ain = createElement( "agent_interval" ); root.appendChild( ain ); t = createTextNode( aux.setNum(simConf.agentInterval) ); ain.appendChild( t ); QDomElement cms = createElement( "car_max_speed" ); root.appendChild( cms ); t = createTextNode( aux.setNum(simConf.carMaxSpeed) ); cms.appendChild( t ); QDomElement cs = createElement( "cell_size" ); root.appendChild( cs ); t = createTextNode( aux.setNum(simConf.cellSize) ); cs.appendChild( t ); QDomElement itl = createElement( "iteration_length" ); root.appendChild( itl ); t = createTextNode( aux.setNum(simConf.iterationLength) ); itl.appendChild( t ); //drivers QDomElement dn = createElement( "drivers" ); root.appendChild( dn ); if (dList_.isEmpty()) { t = createTextNode( "" ); dn.appendChild( t ); } else //populate { QDomElement driver; QDomElement opn ; QDomElement on; QDomElement rn; XmlDriverList::iterator itD; for (itD = dList_.begin(); itD != dList_.end(); itD++) { driver = createElement( "driver" ); dn.appendChild(driver); //name opn = createElement( "name" ); driver.appendChild(opn); t = createTextNode( itD->name ); opn.appendChild( t ); //nick opn = createElement( "nick" ); driver.appendChild(opn); t = createTextNode( itD->nick ); opn.appendChild( t ); //number opn = createElement( "number" ); driver.appendChild(opn); t = createTextNode( aux.setNum(itD->number) ); opn.appendChild( t ); //state opn = createElement( "state" ); driver.appendChild(opn); t = createTextNode( itD->state ); opn.appendChild( t ); //debug opn = createElement( "debug" ); driver.appendChild(opn); t = createTextNode( itD->debug ); opn.appendChild( t ); //options on = createElement( "options" ); driver.appendChild(on); XmlDriverOptions options = itD->options; if (options.isEmpty()) { t = createTextNode( "" ); on.appendChild( t ); } else { QDomElement temp;//rever XmlDriverOptions::iterator itOp; for (itOp = options.begin(); itOp != options.end(); itOp++) { QString p = itOp->first; //option temp = createElement( itOp->first ); on.appendChild(temp); t = createTextNode( itOp->second ); //int legal = itOp->second.toInt(); temp.appendChild( t ); } } //routes rn = createElement( "routes" ); driver.appendChild(rn); RouteList rl = itD->route; if (rl.isEmpty()) { t = createTextNode( "" ); rn.appendChild( t ); } else { QDomElement temp;//rever QDomElement item; RouteList::iterator itRl; for (itRl = rl.begin(); itRl != rl.end(); itRl++) { temp = createElement("route"); rn.appendChild(temp); item = createElement( "laneset" ); t = createTextNode( aux.setNum(itRl->laneset) ); item.appendChild( t ); temp.appendChild(item); } } } } //sensors QDomElement sn = createElement( "sensors" ); root.appendChild( sn ); if (sList_.isEmpty()) { t = createTextNode( "" ); sn.appendChild( t ); } else //populate { QDomElement sensor; QDomElement opn ; XmlSensorList::iterator itS; for (itS = sList_.begin(); itS != sList_.end(); itS++) { sensor = createElement( "sensor" ); sn.appendChild(sensor); //name opn = createElement( "name" ); sensor.appendChild(opn); t = createTextNode( itS->name ); opn.appendChild( t ); //file opn = createElement( "file" ); sensor.appendChild(opn); t = createTextNode( itS->file ); opn.appendChild( t ); //state opn = createElement( "state" ); sensor.appendChild(opn); t = createTextNode( itS->state ); opn.appendChild( t ); //timetag opn = createElement( "time_tag" ); sensor.appendChild(opn); t = createTextNode( itS->timetag ); opn.appendChild( t ); } } QStringList xml(toString()); QFile f( configFile_ ); if ( f.open( IO_WriteOnly ) ) { QTextStream stream( &f ); for ( QStringList::Iterator it = xml.begin(); it != xml.end(); ++it ) stream << *it << "\n"; f.close(); } else return 0; return 1; } ///Get the names of the drivers on the file. ///\param list: list fo drivers names to be populated. ///\return: status of operation. int SimFileHandler::drivers(XmlDrivers& list) { XmlDriverList::iterator it; for (it = dList_.begin(); it != dList_.end(); it++) { list.push_back(it->nick); } return 1; } ///Get the names of the drivers on the file. ///\param list: list fo drivers names to be populated. ///\return: status of operation. int SimFileHandler::sensors(XmlSensors& list) { XmlSensorList::iterator it; for (it = sList_.begin(); it != sList_.end(); it++) { list.push_back(it->name); } return 1; } ///Get the driver properties. ///\param name: name of the driver. ///\param driver: structure os driver. ///\return: status of operation. int SimFileHandler::getDriver(const QString& name, XmlDriver& driver) { XmlDriverList::iterator it; for (it = dList_.begin(); it != dList_.end(); it++) { if(it->nick == name) driver = *it; } return 1; } ///Get the sensor properties. ///\param name: name of the sensor. ///\param sensor: structure os sensor. ///\return: status of operation. int SimFileHandler::getSensor(const QString& name, XmlSensor& sensor) { XmlSensorList::iterator it; for (it = sList_.begin(); it != sList_.end(); it++) { if(it->name == name) sensor = *it; } return 1; } ///Set the driver properties. ///\param name: name of the driver. ///\param driver: structure os driver. ///\return: status of operation. int SimFileHandler::setDriver(QString name, XmlDriver driver) { XmlDriverList::iterator it; bool found = false; bool removed = true; for (it = dList_.begin(); it != dList_.end(); it++) { if(it->nick == name) { found = true; break; } } if (found) { removed = removeDriver(name); } if (removed) { dList_.push_back(driver); } return 1; } ///Set the sensor properties. ///\param name: name of the sensor. ///\param sensor: structure os sensor. ///\return: status of operation. int SimFileHandler::setSensor(QString name, XmlSensor sensor) { XmlSensorList::iterator it; for (it = sList_.begin(); it != sList_.end(); it++) { QString object = it->name; object.replace(" ", ""); if(object == name) removeSensor(object); } sList_.push_back(sensor); return 1; } ///Clear the class. void SimFileHandler::localClear() { configFile_ = ""; XmlDriverList newDriverList; XmlSensorList newSensorList; XmlSimConf newConf; dList_ = newDriverList; sList_ = newSensorList; simConf = newConf; } ///Remove the driver from the list. ///\param driver: driver to be removed. int SimFileHandler::removeDriver(QString driver) { XmlDriverList::iterator it; bool found = false; for (it = dList_.begin(); it != dList_.end(); it++) { if(it->nick == driver) { found = true; dList_.erase(it); break; } } if (found) return 1; return 0; } ///Remove the sensor from the list. ///\param sensor: sensor to be removed. int SimFileHandler::removeSensor(QString sensor) { XmlSensorList::iterator it; bool found = false; for (it = sList_.begin(); it != sList_.end(); it++) { if(it->name == sensor) { found = true; sList_.erase(it); break; } } if (found) return 1; return 0; } ///Insert a driver. ///\param driver: driver to be inserted. int SimFileHandler::insertDriver(const QString& driver) { XmlDriverList::iterator it; QString aux; for (it = dList_.begin(); it != dList_.end(); it++) { if(it->name == driver) return 0; } XmlDriver newD; //todo: check if driver model exists getTemplateDriver(driver, newD); newD.nick = driver + "_" + aux.setNum(dList_.size()); newD.number = 1; newD.state = "ON"; newD.debug = "OFF"; dList_.push_back(newD); return 1; } ///Insert a sensor. ///\param sensor: sensor to be inserted. int SimFileHandler::insertSensor(const QString& sensor) { XmlSensorList::iterator it; for (it = sList_.begin(); it != sList_.end(); it++) { QString object = it->name; object.replace(" ", ""); if(object == sensor) return 0; } XmlSensor newS; QDir dir("output/"); newS.name = sensor; newS.file = dir.absPath() + "/" + sensor + ".txt"; newS.state = "ON"; newS.timetag = "NO"; sList_.push_back(newS); return 1; } ///Change some property of a driver. int SimFileHandler::changeDriverProperty(const QString& driver, QPair<QString, QString> prop) { QString aux; //cout << "ill change from " << driver.ascii() << endl; XmlDriverList::iterator it; XmlDriverOptions::iterator itOp; for (it = dList_.begin(); it != dList_.end(); it++) { QString object = it->nick; object.replace(" ", ""); if( (object == driver) || (driver == it->nick) ) { //cout << "i found " << it->nick.ascii() << endl; QString item = prop.first; if (item == "name") it->name = prop.second; else if(item == "nick") it->nick = prop.second.toInt(); else if(item == "number") it->number = prop.second.toInt(); else if(item == "state") it->state = prop.second; else if(item == "debug") it->debug = prop.second; else { for (itOp=it->options.begin(); itOp!=it->options.end(); itOp++) { QString objectProp = itOp->first; object.replace(" ", ""); if(objectProp == item) { itOp->second = prop.second; break; } } } } } return 1; } ///Change some property of a sensor. int SimFileHandler::changeSensorProperty(const QString& sensor, QPair<QString, QString> prop) { XmlSensorList::iterator it; for (it = sList_.begin(); it != sList_.end(); it++) { QString object = it->name; object.replace(" ", ""); if( (object == sensor) || (sensor == it->name) ) { QString item = prop.first; if (item == "name") it->name = prop.second; else if(item == "file") it->file = prop.second; else if(item == "state") it->state = prop.second; else if (item == "timetag") it->timetag = prop.second; } } return 1; } ///Check structures. //needs optimization int SimFileHandler::checkDriverTemplate() { XmlDriverList::iterator itT; XmlDriverList::iterator itO; XmlDriverOptions temp; XmlDriverOptions::iterator itOp; XmlDriverOptions::iterator itOp2; for (itO = dList_.begin(); itO != dList_.end(); itO++) { for (itT = confDrvList_.begin(); itT!=confDrvList_.end(); itT++) { QString object = itO->nick; object.replace(" ", ""); if( (object == itT->nick) || (itT->nick == itO->nick) )//driver == template { temp = itT->options; itOp = temp.begin(); for (itOp2 = itO->options.begin(); itOp2!=itO->options.end(); itOp2++) { if ((itOp != NULL) && (itOp!=temp.end()) && (itOp2 != NULL)) { if ( (itT->options.size() < itO->options.size())//option removed && (itOp->first != itOp2->first) ) itO->options.erase(itOp2); if (itOp2 != NULL) { itOp->second = itOp2->second; itOp++; } } } itO->options = temp; break; } } } return 1; } ///Change names of templatesXdrivers. ///\param old: old name. ///\param actual: new name. int SimFileHandler::changeDriversName(const QString& old, const QString& actual) { XmlDriverList::iterator it; for (it = dList_.begin(); it != dList_.end(); it++) { QString object = it->nick; object.replace(" ", ""); if( (object == old) || (old == it->name) ) { it->name = actual; } } return 1; } //********************************************************************* //********************************************************************* //********************************************************************* NetHandler::NetHandler() : QDomDocument() { loaded_ = false; } NetHandler::~NetHandler() { } ///Load the configuration file that defines templates for drivers. int NetHandler::load(const QString& file) { TiXmlElement* simulation; TiXmlDocument doc( file.ascii() ); bool loadOkay = doc.LoadFile(); if ( !loadOkay ) { printf( "Could not load file. Error='%s'.\nExiting.\n", doc.ErrorDesc()); return 0; } loaded_ = true; simulation = doc.FirstChildElement( "simulation" ); TiXmlElement* nodes; //node TiXmlElement* sources; //sources node TiXmlElement* sinks; //sinks node TiXmlElement* streets; //streets node TiXmlElement* traffic_lights; nodes = simulation->FirstChildElement( "nodes" ); sources = simulation->FirstChildElement( "sources" ); sinks = simulation->FirstChildElement( "sinks" ); streets = simulation->FirstChildElement( "streets" ); traffic_lights = simulation->FirstChildElement( "traffic_lights" ); netId_ = atoi(simulation->FirstChildElement( "network_id" )->FirstChild()->Value()); netName_ = simulation->FirstChildElement( "network_name" )->FirstChild()->Value(); lanesets_.clear(); nodes_.clear(); parseNodes_(nodes, sources, sinks); parseTls_(traffic_lights); parseStreets_(streets); return 1; } ///Parse the node structure setting sources and sinks. ///\param nodes: nodes structure. ///\param sources: sources structure. ///\param sinks: sinks structure. ///\return: status of operation. int NetHandler::parseNodes_(TiXmlElement* nodes, TiXmlElement* sources, TiXmlElement* sinks) { QValueList<int> sourcesIds; QValueList<int> sinksIds; //sources TiXmlElement* source; for(source = sources->FirstChildElement("source"); source; source = source->NextSiblingElement("source")) { sourcesIds.push_back(atoi(source->FirstChildElement("located_at_node")->FirstChild()->Value())); } //sinks TiXmlElement* sink; for(sink = sinks->FirstChildElement("sink"); sink; sink = sink->NextSiblingElement("sink")) { sinksIds.push_back(atoi(sink->FirstChildElement("located_at_node")->FirstChild()->Value())); } //nodes TiXmlElement* node; for(node = nodes->FirstChildElement("node"); node; node = node->NextSiblingElement("node")) { Node nd; nd.id = atoi(node->FirstChildElement("node_id")->FirstChild()->Value()); nd.hastl = false; nd.name = node->FirstChildElement("node_name")->FirstChild()->Value(); nd.x = atoi(node->FirstChildElement("x_coord")->FirstChild()->Value()); nd.y = atoi(node->FirstChildElement("y_coord")->FirstChild()->Value()); if (sourcesIds.contains(nd.id)) nd.type = SOURCE; else if (sinksIds.contains(nd.id)) nd.type = SINK; else nd.type = NODE; nodes_.push_back(nd); } return 1; } ///Parse the node structure setting sources and sinks. ///\param streets: streets structure. ///\return: status of operation. int NetHandler::parseStreets_(TiXmlElement* streets) { TiXmlElement* sections; TiXmlElement* lanesets; TiXmlElement* turnings; //streets TiXmlElement* street; for(street = streets->FirstChildElement("street"); street; street = street->NextSiblingElement("street")) { //sections sections = street->FirstChildElement("sections"); TiXmlElement* section; section = sections->FirstChildElement("section"); for(section = sections->FirstChildElement("section"); section; section = section->NextSiblingElement("section")) { //lanesets lanesets = section->FirstChildElement("lanesets"); TiXmlElement* laneset; for(laneset = lanesets->FirstChildElement("laneset"); laneset; laneset = laneset->NextSiblingElement("laneset")) { Laneset ls; ls.id = atoi(laneset->FirstChildElement("laneset_id")->FirstChild()->Value()); ls.begin = atoi(laneset->FirstChildElement("start_node")->FirstChild()->Value()); ls.end = atoi(laneset->FirstChildElement("end_node")->FirstChild()->Value()); ls.sectionId = atoi(section->FirstChildElement("section_id")->FirstChild()->Value()); ls.sectionName = atoi(section->FirstChildElement("section_name")->FirstChild()->Value()); turnings = laneset->FirstChildElement("turning_probabilities"); TiXmlElement* turning; for(turning = turnings->FirstChildElement("turning"); turning; turning = turning->NextSiblingElement("turning")) { Destination dir; dir.id = atoi(turning->FirstChildElement("destination_laneset")->FirstChild()->Value()); dir.prob = atoi(turning->FirstChildElement("probability")->FirstChild()->Value()); ls.destinations.push_back(dir); } lanesets_.push_back(ls); } } } return 1; } int NetHandler::parseTls_(TiXmlElement* tls) { //tls TiXmlElement* tl; for(tl = tls->FirstChildElement("traffic_light"); tl; tl = tl->NextSiblingElement("traffic_light")) { int tlid = atoi(tl->FirstChildElement("traffic_light_id")->FirstChild()->Value()); int nodeid = atoi(tl->FirstChildElement("located_at_node")->FirstChild()->Value()); NodeList::iterator it; for (it = nodes_.begin(); it != nodes_.end(); it++) { if (it->id == nodeid) { it->tlid = tlid; it->hastl = true; break; } } } return 1; } ///Returns a string with the structure of the net. //not complete QString NetHandler::toString() { QString ans; QString aux; LanesetList::iterator it; for (it = lanesets_.begin(); it != lanesets_.end(); it++) { ans += "Laneset: " + aux.setNum(it->id) + "\n"; } return ans; } TLList NetHandler::nodeToTls(TLList list) { TLList ans; NodeList::iterator it; TLList::iterator it2; for (it2 = list.begin(); it2 != list.end(); it2++) for (it = nodes_.begin(); it != nodes_.end(); it++) { if ( (it->id == *it2) && (it->hastl) ) { ans.push_back(it->tlid); } } return ans; } TLList NetHandler::tlToLaneset(TLList list) { TLList ans; LanesetList::iterator it; TLList::iterator it2; for (it2 = list.begin(); it2 != list.end(); it2++) for (it = lanesets_.begin(); it != lanesets_.end(); it++) { if ( (getNode(it->begin).tlid == *it2)) { ans.push_back(it->id); break; } } return ans; } Node NetHandler::getNode(int id) { Node ans; NodeList::iterator it; for (it = nodes_.begin(); it != nodes_.end(); it++) { if (it->id == id) { ans = *it; } } return ans; } QPoint NetHandler::nodeLocation(const int& nodeId) { NodeList::iterator it; QPoint ans; for (it=nodes_.begin(); it!=nodes_.end(); it++) { if (it->id == nodeId) { QPoint point(it->x, it->y); ans = point; } } return ans; } QPoint NetHandler::xRange() { NodeList::iterator it; int max = 0; int min = 100000; for (it=nodes_.begin(); it!=nodes_.end(); it++) { if (it->x > max) max = it->x; if (it->x < min) min = it->x; } QPoint range(min,max); return range; } QPoint NetHandler::yRange() { NodeList::iterator it; int max = 0; int min = 100000; for (it=nodes_.begin(); it!=nodes_.end(); it++) { if (it->y > max) max = it->y; if (it->y < min) min = it->y; } QPoint range(min,max); return range; } QPair<QString, QString> NetHandler::lanesetNodes(const int& id) { QPair<QString, QString> ans; LanesetList::iterator it; for (it = lanesets_.begin(); it != lanesets_.end(); it++) { if (it->id == id) ans = qMakePair(nodeName_(it->begin), nodeName_(it->end)); } return ans; } QString NetHandler::nodeName_(const int& id) { QString ans; NodeList::iterator it; for (it = nodes_.begin(); it != nodes_.end(); it++) { if (it->id == id) ans = it->name; } return ans; } int NetHandler::nodeId_(const QString& name) { int ans=-1; NodeList::iterator it; for (it = nodes_.begin(); it != nodes_.end(); it++) { if (it->name == name) ans = it->id; } return ans; } QValueVector<QString> NetHandler::nextNodes(const QString& from) { QValueVector<QString> ans; LanesetList::iterator it; for (it = lanesets_.begin(); it != lanesets_.end(); it++) { if (nodeName_(it->begin) == from) ans.push_back(nodeName_(it->end)); } return ans; } int NetHandler::definedLaneset(const QString& from, const QString& to) { int ans = -1; LanesetList::iterator it; for (it = lanesets_.begin(); it != lanesets_.end(); it++) { if ( (nodeName_(it->begin) == from) && (nodeName_(it->end) == to) ) ans = it->id; } return ans; } //********************************************************************* //********************************************************************* //********************************************************************* AgentHandler::AgentHandler() : QDomDocument() { loaded = false; } AgentHandler::~AgentHandler() { } #define VALUE(element) (element->FirstChild()->Value()) int AgentHandler::load(const QString& file) { TiXmlElement *agents; TiXmlDocument doc( file.ascii() ); bool loadOkay = doc.LoadFile(); if ( !loadOkay ) { printf( "Could not load file. Error='%s'.\nExiting.\n", doc.ErrorDesc()); exit(1); } agents = doc.FirstChildElement( "agents" ); TiXmlElement *agent; TiXmlElement *name; TiXmlElement *nickname; TiXmlElement *memsize; TiXmlElement *alpha; TiXmlElement *action; TiXmlElement *minphase; TiXmlElement *states; TiXmlElement *algorithm; TiXmlElement *coordneighbors; TiXmlElement *gamma; TiXmlElement *starttime; TiXmlElement *learningrate; TiXmlElement *discountrate; TiXmlElement *firstphase; TiXmlElement *secondphase; TiXmlElement *tau; //same for DCOP tau's TiXmlElement *log; TiXmlElement *tl; TiXmlElement *tls; for(agent = agents->FirstChildElement("agent");agent; agent = agent->NextSiblingElement("agent")) { XmlAgent la; name = agent->FirstChildElement("type"); string agentName = VALUE(name); la.name = agentName; nickname = agent->FirstChildElement("name"); string agentNickName = VALUE(nickname); la.nickname = agentNickName; //Greedy agents if (agentName == "Greedy") { memsize = agent->FirstChildElement("memsize"); string agentMemSize = VALUE(memsize); la.memsize = agentMemSize; alpha = agent->FirstChildElement("alpha"); string agentAlpha = VALUE(alpha); la.alpha = agentAlpha; minphase = agent->FirstChildElement("minphase"); string agentMinPhase = VALUE(minphase); la.minphase = agentMinPhase; action = agent->FirstChildElement("action"); string agentAction = VALUE(action); la.action = agentAction; } //Q-learning agents if (agentName == "Q-learning") { memsize = agent->FirstChildElement("memsize"); string agentMemSize = VALUE(memsize); la.memsize = agentMemSize; states = agent->FirstChildElement("states"); string agentStates = VALUE(states); la.states = agentStates; //start time starttime = agent->FirstChildElement("start_time"); string agentStartTime = VALUE(starttime); la.starttime = agentStartTime; //learning rate learningrate = agent->FirstChildElement("learning_rate"); string agentLearningRate = VALUE(learningrate); la.learningrate = agentLearningRate; //discount rate discountrate = agent->FirstChildElement("discount_rate"); string agentDiscountRate = VALUE(discountrate); la.discountrate = agentDiscountRate; } //DCOP agents if (agentName == "DCOP") { //algorithm algorithm = agent->FirstChildElement("algorithm"); string agentAlgorithm = VALUE(algorithm); la.algorithm = agentAlgorithm; //coordinated neighbors coordneighbors = agent->FirstChildElement("coordneighbors"); string agentCoordNeighbors = VALUE(coordneighbors); la.coordneighbors = agentCoordNeighbors; //alpha alpha = agent->FirstChildElement("alpha"); string agentAlpha = VALUE(alpha); la.alpha = agentAlpha; //gamma gamma = agent->FirstChildElement("gamma")->FirstChildElement("synchronized"); string agentGamma = VALUE(gamma); la.gammasync = agentGamma; gamma = agent->FirstChildElement("gamma")->FirstChildElement("unsynchronized"); agentGamma = VALUE(gamma); la.gammaunsync = agentGamma; //tau tau = agent->FirstChildElement("tau")->FirstChildElement("up_agree")->FirstChildElement("down_agree"); string agentTau = VALUE(tau); la.tau_agr_agr = agentTau; tau = agent->FirstChildElement("tau")->FirstChildElement("up_agree")->FirstChildElement("down_not_agree"); agentTau = VALUE(tau); la.tau_agr_not = agentTau; tau = agent->FirstChildElement("tau")->FirstChildElement("up_not_agree")->FirstChildElement("down_agree"); agentTau = VALUE(tau); la.tau_not_agr = agentTau; tau = agent->FirstChildElement("tau")->FirstChildElement("up_not_agree")->FirstChildElement("down_not_agree"); agentTau = VALUE(tau); la.tau_not_not = agentTau; // TiXmlElement *tau; } //supervised learning agents if (agentName == "supervised-learning") { //memory size memsize = agent->FirstChildElement("memsize"); string agentMemSize = VALUE(memsize); la.memsize = agentMemSize; //number of states states = agent->FirstChildElement("states"); string agentStates = VALUE(states); la.states = agentStates; //start time starttime = agent->FirstChildElement("start_time"); string agentStartTime = VALUE(starttime); la.starttime = agentStartTime; //learning rate learningrate = agent->FirstChildElement("learning_rate"); string agentLearningRate = VALUE(learningrate); la.learningrate = agentLearningRate; //discount rate discountrate = agent->FirstChildElement("discount_rate"); string agentDiscountRate = VALUE(discountrate); la.discountrate = agentDiscountRate; //first phase firstphase = agent->FirstChildElement("first_phase"); string agentFirstPhase = VALUE(firstphase); la.firstphase = agentFirstPhase; //second phase secondphase = agent->FirstChildElement("second_phase"); string agentSecondPhase = VALUE(secondphase); la.secondphase = agentSecondPhase; //tau tau = agent->FirstChildElement("tau"); string agentTau = VALUE(tau); la.tau = agentTau; } log = agent->FirstChildElement("log"); string agentLog; agentLog = static_cast<string> (VALUE(log)); la.log = agentLog; tls = agent->FirstChildElement("trafficlights"); TLList ids; if (tls != 0) { for(tl = tls->FirstChildElement("trafficlight"); tl; tl = tl->NextSiblingElement("trafficlight")) { int id = atoi(VALUE(tl)); ids.push_back(id); } } la.tls = ids; //insert agent into list al.push_back(la); } loaded = true; agentFile = file; return 1; } int AgentHandler::save(const QString& file) { if (file != "") agentFile = file; if ( (file == "") && (agentFile == "") ) return 0; if (agentFile.right(4) != ".xml") agentFile += ".xml"; QDomText t; QString aux = ""; setContent(aux); //general QDomElement root = createElement( "agents" ); appendChild( root ); if (al.isEmpty()) { t = createTextNode( "" ); root.appendChild( t ); } else //populate { QDomElement agent; QDomElement opn ; QDomElement on; QDomElement temp; XmlAgentList::iterator it; for (it = al.begin(); it != al.end(); it++) { agent = createElement( "agent" ); root.appendChild(agent); //name opn = createElement( "type" ); agent.appendChild(opn); t = createTextNode( it->name ); opn.appendChild( t ); //name opn = createElement( "name" ); agent.appendChild(opn); t = createTextNode( it->nickname ); opn.appendChild( t ); //Greedy Agents if (it->name == "Greedy") { //memsize opn = createElement( "memsize" ); agent.appendChild(opn); t = createTextNode( it->memsize ); opn.appendChild( t ); //alpha opn = createElement( "alpha" ); agent.appendChild(opn); t = createTextNode( it->alpha ); opn.appendChild( t ); //minphase opn = createElement( "minphase" ); agent.appendChild(opn); t = createTextNode( it->minphase ); opn.appendChild( t ); opn = createElement( "action" ); agent.appendChild(opn); t = createTextNode( it->action ); opn.appendChild( t ); } //Q-learning Agents if (it->name == "Q-learning") { //memsize opn = createElement( "memsize" ); agent.appendChild(opn); t = createTextNode( it->memsize ); opn.appendChild( t ); //states opn = createElement( "states" ); agent.appendChild(opn); t = createTextNode( it->states ); opn.appendChild( t ); //start time opn = createElement ( "start_time" ); agent.appendChild(opn); t = createTextNode( it->starttime ); opn.appendChild( t ); //learning rate opn = createElement ( "learning_rate" ); agent.appendChild(opn); t = createTextNode( it->learningrate ); opn.appendChild( t ); //discount rate opn = createElement ( "discount_rate" ); agent.appendChild(opn); t = createTextNode( it->discountrate ); opn.appendChild( t ); } //DCOP Agents if (it->name == "DCOP") { //algorithm opn = createElement( "algorithm" ); agent.appendChild(opn); t = createTextNode( it->algorithm ); opn.appendChild( t ); //coordneighbors opn = createElement( "coordneighbors" ); agent.appendChild(opn); t = createTextNode( it->coordneighbors ); opn.appendChild( t ); //alpha opn = createElement( "alpha" ); agent.appendChild(opn); t = createTextNode( it->alpha ); opn.appendChild( t ); //gamma on = createElement( "gamma" ); agent.appendChild(on); opn = createElement( "synchronized" ); on.appendChild(opn); t = createTextNode( it->gammasync ); opn.appendChild( t ); opn = createElement( "unsynchronized" ); on.appendChild(opn); t = createTextNode( it->gammaunsync ); opn.appendChild( t ); //tau temp = createElement( "tau" ); agent.appendChild(temp); on = createElement( "up_agree" ); temp.appendChild(on); opn = createElement( "down_agree" ); on.appendChild(opn); t = createTextNode( it->tau_agr_agr ); opn.appendChild( t ); opn = createElement( "down_not_agree" ); on.appendChild(opn); t = createTextNode( it->tau_agr_not ); opn.appendChild( t ); on = createElement( "up_not_agree" ); temp.appendChild(on); opn = createElement( "down_agree" ); on.appendChild(opn); t = createTextNode( it->tau_not_agr ); opn.appendChild( t ); opn = createElement( "down_not_agree" ); on.appendChild(opn); t = createTextNode( it->tau_not_not ); opn.appendChild( t ); } //supervised-learning agents if (it->name == "supervised-learning") { //memsize opn = createElement( "memsize" ); agent.appendChild(opn); t = createTextNode( it->memsize ); opn.appendChild( t ); //states opn = createElement( "states" ); agent.appendChild(opn); t = createTextNode( it->states ); opn.appendChild( t ); //start time opn = createElement ( "start_time" ); agent.appendChild(opn); t = createTextNode( it->starttime ); opn.appendChild( t ); //learning rate opn = createElement ( "learning_rate" ); agent.appendChild(opn); t = createTextNode( it->learningrate ); opn.appendChild( t ); //discount rate opn = createElement ( "discount_rate" ); agent.appendChild(opn); t = createTextNode( it->discountrate ); opn.appendChild( t ); //first phase opn = createElement ( "first_phase" ); agent.appendChild(opn); t = createTextNode( it->firstphase ); opn.appendChild( t ); //first phase opn = createElement ( "second_phase" ); agent.appendChild(opn); t = createTextNode( it->secondphase ); opn.appendChild( t ); //tau opn = createElement ( "tau" ); agent.appendChild(opn); t = createTextNode( it->tau ); opn.appendChild( t ); } //log opn = createElement( "log" ); agent.appendChild(opn); t = createTextNode( it->log ); opn.appendChild( t ); //tls on = createElement( "trafficlights" ); agent.appendChild(on); TLList tls = it->tls; if (tls.isEmpty()) { t = createTextNode( "" ); on.appendChild( t ); } else { QString aux; TLList::iterator it; for (it = tls.begin(); it != tls.end(); it++) { temp = createElement( "trafficlight" ); t = createTextNode( aux.setNum(*it) ); temp.appendChild( t ); on.appendChild( temp ); } } } } QStringList xml(toString()); QFile f( agentFile ); if ( f.open( IO_WriteOnly ) ) { QTextStream stream( &f ); for ( QStringList::Iterator it = xml.begin(); it != xml.end(); ++it ) stream << *it << "\n"; f.close(); } else return 0; return 1; } void AgentHandler::changeLogStat(QString name, QString stat) { XmlAgentList::iterator it; //bool found = false; for (it = al.begin(); it != al.end(); it++) { if(it->name == name) { it->log = stat; break; } } } int AgentHandler::setAgentTls(QString name, TLList list) { XmlAgentList::iterator it; //bool found = false; for (it = al.begin(); it != al.end(); it++) { if(it->nickname == name) { it->tls = list; break; } } return static_cast<unsigned int>(NULL); } TLList AgentHandler::agentTls(QString name) { XmlAgentList::iterator it; //bool found = false; for (it = al.begin(); it != al.end(); it++) { if(it->nickname == name) { return it->tls; } } return static_cast<unsigned int>(NULL); } int AgentHandler::addAgent(QString name, QString nickname) { XmlAgent agent; agent.name = name; agent.nickname = nickname; agent.log = "on"; //initial values for Greedy agents if (name == "Greedy") { agent.memsize = "300"; agent.alpha = "0.2"; agent.minphase = "15"; agent.action = "modify_plan"; } //initial values for Q-Learning agents if (name == "Q-learning") { agent.memsize = "300"; agent.starttime = "300"; agent.states = "1"; agent.learningrate = "0.5"; agent.discountrate = "0.9"; } //initial values for DCOP agents if (name == "DCOP") { agent.algorithm = "ADOPT"; agent.coordneighbors = "yes"; agent.alpha = "0.5"; agent.gammasync = "0.5"; agent.gammaunsync = "0.5"; agent.tau_agr_agr = "0.5"; agent.tau_agr_not = "0.5"; agent.tau_not_agr = "0.5"; agent.tau_not_not = "0.5"; } //initial values for Supervised Learning agents if (name == "supervised-learning") { agent.memsize = "60"; agent.states = "3"; agent.starttime = "360"; agent.learningrate = "1.0"; agent.discountrate = "0.0"; agent.firstphase = "6000"; agent.secondphase = "12000"; agent.tau = "0.1"; } al.push_back(agent); return 1; } ///Get the agent properties. ///\param name: name of the agent. ///\param driver: structure os agent. ///\return: status of operation. int AgentHandler::getAgent(const QString& name, XmlAgent& agent) { XmlAgentList::iterator it; for (it = al.begin(); it != al.end(); it++) { if(it->nickname == name) agent = *it; } return 1; } int AgentHandler::changeAgentProperty(QString agentName, QPair<QString, QString> prop) { XmlAgentList::iterator it; for (it = al.begin(); it != al.end(); it++) { if(it->nickname == agentName) { if (prop.first == "Agent Name") it->nickname = prop.second; if (prop.first == "Log") it->log = prop.second; if (prop.first == "Memory Size") it->memsize = prop.second; if (prop.first == "Alpha") it->alpha = prop.second; if (prop.first == "Action") it->action = prop.second; if (prop.first == "Minimum Phase Size") it->minphase = prop.second; if (prop.first == "Number of States") it->states = prop.second; if (prop.first == "Coordinated Neighbors") it->coordneighbors = prop.second; if (prop.first == "Algorithm") it->algorithm = prop.second; if (prop.first == "Gamma Sync") it->gammasync = prop.second; if (prop.first == "Gamma Unsync") it->gammaunsync = prop.second; if (prop.first == "Tau Agr Agr") it->tau_agr_agr = prop.second; if (prop.first == "Tau Not Agr") it->tau_not_agr = prop.second; if (prop.first == "Tau Agr Not") it->tau_agr_not = prop.second; if (prop.first == "Tau Not Not") it->tau_not_not = prop.second; if (prop.first == "Start Time") it->starttime = prop.second; if (prop.first == "Learning Rate") it->learningrate = prop.second; if (prop.first == "Discount Rate") it->discountrate = prop.second; if (prop.first == "First Phase") it->firstphase = prop.second; if (prop.first == "Second Phase") it->secondphase = prop.second; if (prop.first == "Tau") it->tau = prop.second; } } return 1; } //Remove the agent from the list. ///\param agent: agent to be removed. int AgentHandler::removeAgent(QString agent) { XmlAgentList::iterator it; bool found = false; for (it = al.begin(); it != al.end(); it++) { if(it->nickname == agent) { found = true; al.erase(it); break; } } if (found) return 1; return 0; }
[ [ [ 1, 2198 ] ] ]
fb97170f0d3b25c4e2cc0c89f911854d8c694f8b
6a2f859a41525c5512f9bf650db68bcd7d95748d
/TP2/ex2/R0/inc/Variable.hpp
6c25e839be6d81eed4cfff35925f1b8d7bbbd64b
[]
no_license
Bengrunt/mif12-2009
21df06941a6a1e844372eb01f4911b1ef232b306
d4f02f1aab82065c8184facf859fe80233bc46b5
refs/heads/master
2021-01-23T13:48:47.238211
2009-12-04T22:52:25
2009-12-04T22:52:25
32,153,296
0
0
null
null
null
null
UTF-8
C++
false
false
788
hpp
#ifndef VARIABLE_DEF #define VARIABLE_DEF #include "Symbole.hpp" #include "Type.hpp" /** * Classe de gestion d'un symbole d'un programme en Pascal. */ class Variable : public Symbole{ private: /** Type du symbole. */ Type* _type; public: /** * Constructeur. * * @param[in] type Type du symbole. */ Variable(Type* type); /** * Destructeur */ virtual ~Variable(); /** * Retourne nom de la catégorie de symbole (variable, temporaire, étiquette...) * * @return Nom de la catégorie. */ virtual char* getCategory() const; /** * Retourne chaîne de caractères représentant les attributs du symbole. * * @return Chaîne représentant les attributs du symbole. */ virtual char* getAttributes() const; }; #endif
[ [ [ 1, 3 ], [ 6, 41 ] ], [ [ 4, 5 ] ] ]
d169838f19b01f58f5c327940018f1e9e30945e7
27d5670a7739a866c3ad97a71c0fc9334f6875f2
/CPP/Targets/MapLib/Shared/include/CopyrightHolder.h
da0bb9493baf071d2bce251482005668b4b6fcd3
[ "BSD-3-Clause" ]
permissive
ravustaja/Wayfinder-S60-Navigator
ef506c418b8c2e6498ece6dcae67e583fb8a4a95
14d1b729b2cea52f726874687e78f17492949585
refs/heads/master
2021-01-16T20:53:37.630909
2010-06-28T09:51:10
2010-06-28T09:51:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,374
h
/* Copyright (c) 1999 - 2010, Vodafone Group Services Ltd All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Vodafone Group Services Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef COPYRIGHT_HOLDER #define COPYRIGHT_HOLDER #include "config.h" #include "BitBuffer.h" #include <vector> #include "MC2SimpleString.h" #include "MC2BoundingBox.h" /** * Copyright notice. * Describes one box containing copyright information. */ class CopyrightNotice { public: friend class CopyrightHolder; friend class CopyrightHandler; /// Load from buffer. bool load( BitBuffer& buf ); /// Save to buffer. bool save( BitBuffer& buf ) const; /// Get the copyright id. MAX_INT32 if overlap box. int getCopyrightID() const; /** * If the box is an overlap box, i.e. only a boundingbox * for its child boxes. Contains no logical copyright information. */ bool isOverlappingBox() const; /// Get the box for this notice. const MC2BoundingBox& getBox() const; /// Dump data to stdout. void dump() const; private: /// The box. MC2BoundingBox m_box; /// The copyright id. MAX_INT32 if overlap box. int m_copyrightID; }; /** * Copyright holder. * Contains all copyright information for the world. */ class CopyrightHolder { public: friend class CopyrightHandler; /// Hard code data. void initWithHardcodedData(); /// Load from buffer. bool load( BitBuffer& buf ); /// Save to buffer. bool save( BitBuffer& buf ) const; /// Pair type. typedef std::pair<int,int> pair_t; /// Dump info to stdout. void dump() const; private: /// Vector of pairs, kind of like a std:map typedef std::vector<pair_t> map_t; /// Iterator to map. typedef map_t::const_iterator mapIt_t; /// Range of iterators. typedef std::pair<mapIt_t,mapIt_t> range_t; /** * Table describing the parent / child relationship for the * CopyrightNotices. pair_t::first is the parent id, and * pair_t::second refers to the child id. The id:s are * the position in the m_boxes vector. * * Parent id MAX_INT32 means that there is no parent, * i.e. the box is at the top / root level. */ map_t m_boxesByParent; /** * The copyright boxes. The position in the vector refers to * their respective id. */ std::vector<CopyrightNotice> m_boxes; /** * The copyright strings. The copyright id in the CopyrightNotice * refers to the position in this vector for the copyright string. */ std::vector<MC2SimpleString> m_copyrightStrings; /// The copyright head, i.e. "(c) Wayfinder" MC2SimpleString m_copyrightHead; /// The minimum coverage in percent for a copyright ID to be included. int m_minCovPercent; }; // -- Inlined functions #endif // COPYRIGHT_HOLDER
[ [ [ 1, 132 ] ] ]
77a4af157f78c8cbb311d7e03e61ddf8bed55689
324524076ba7b05d9d8cf5b65f4cd84072c2f771
/Checkers/wndAbout.cpp
7adffe19c353695b3c17b73f7ea8fd8f6c23265a
[ "BSD-2-Clause" ]
permissive
joeyespo-archive/checkers-c
3bf9ff11f5f1dee4c17cd62fb8af9ba79246e1c3
477521eb0221b747e93245830698d01fafd2bd66
refs/heads/master
2021-01-01T05:32:45.964978
2011-03-13T04:53:08
2011-03-13T04:53:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,178
cpp
// frmAbout.cpp - Checkers // About Window Implementation File // By Joey Esposito #pragma once // Header File: #include "Main.h" // Local Macros // ------------- // Gradient colors #define BG_GB_COLOR_TL 0x8888E0 #define BG_GB_COLOR_BL 0x404040 #define BG_GB_COLOR_TR 0x80000018 #define BG_GB_COLOR_BR 0x5050A0 // Window IDs #define ID_BTN_OK 0x1001 // frmMain Window Procedure // ------------------------- LRESULT CALLBACK wndAboutProc (HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { LPABOUTWNDINFO lpAboutInfo; HDC hDC, hDC2; PAINTSTRUCT ps; HBITMAP hbmTemp; HFONT hftTemp; HWND hwndTemp; RECT rt; // Get Window Info // ---------------- lpAboutInfo = (LPABOUTWNDINFO)GetWindowLong(hWnd, GWL_USERDATA); // Event Switch // ------------- switch (uMsg) { case WM_CREATE: // Window Startup Position // ------------------------ // Get dimensions ((LPCREATESTRUCT)lParam)->cx = (NCWidth(hWnd) + 344); ((LPCREATESTRUCT)lParam)->cy = (NCHeight(hWnd) + 178); GetWindowRect(GetDesktopWindow(), &rt); Reposition(hWnd, (((rt.right-rt.left)-((LPCREATESTRUCT)lParam)->cx) / 2), (((rt.bottom-rt.top) - ((LPCREATESTRUCT)lParam)->cy) / 2), ((LPCREATESTRUCT)lParam)->cx, ((LPCREATESTRUCT)lParam)->cy); // Initialize Window // ------------------ // Create window info structure if ((lpAboutInfo = new ABOUTWNDINFO) == NULL) return -1; // Set window info lpAboutInfo->hicoLogo = (HICON)LoadImage(hInstance, MAKEINTRESOURCE(icoMain), IMAGE_ICON, 0, 0, (LR_CREATEDIBSECTION)); lpAboutInfo->hBackground = CreateGradientBitmap(ClientWidth(hWnd), ClientHeight(hWnd), BG_GB_COLOR_TL, BG_GB_COLOR_BL, BG_GB_COLOR_TR, BG_GB_COLOR_BR); SetWindowLong(hWnd, GWL_USERDATA, (LONG)lpAboutInfo); // Create Window // -------------- hwndTemp = CreateButton("OK", (WS_CHILD | WS_GROUP | WS_TABSTOP | WS_VISIBLE), 258, 8, 73, 25, hWnd, ID_BTN_OK, hInstance); SendMessage(hwndTemp, WM_SETFONT, (WPARAM)hFont_Main, 0); break; case WM_ACTIVATE: if ((LOWORD(wParam) != WA_INACTIVE) && (HIWORD(wParam) == FALSE)) { SetFocus(GetDlgItem(hWnd, ID_BTN_OK)); SendMessage(hWnd, DM_SETDEFID, ID_BTN_OK, NULL); return 0; } break; case DM_GETDEFID: return (MAKELONG(ID_BTN_OK, DC_HASDEFID)); case WM_PAINT: // Failsafe if (!lpAboutInfo) break; // Setup Painting // --------------- hDC = BeginPaint(hWnd, &ps); // Paint Background // ----------------- if (lpAboutInfo->hBackground) { // Paint background bitmap hDC2 = CreateCompatibleDC(NULL); hbmTemp = (HBITMAP)SelectObject(hDC2, lpAboutInfo->hBackground); BitBlt(hDC, ps.rcPaint.left, ps.rcPaint.top, (ps.rcPaint.right - ps.rcPaint.left), (ps.rcPaint.bottom - ps.rcPaint.top), hDC2, ps.rcPaint.left, ps.rcPaint.top, SRCCOPY); SelectObject(hDC2, hbmTemp); DeleteDC(hDC2); } else { FillRect(hDC, &ps.rcPaint, (HBRUSH)GetStockObject(LTGRAY_BRUSH)); } // Draw Window // ------------ // Draw icon rt.left = 8; rt.top = 8; rt.right = 44; rt.bottom = 44; DrawEdge(hDC, &rt, (BDR_SUNKENOUTER), (BF_RECT | BF_MONO)); DrawIcon(hDC, 10, 10, lpAboutInfo->hicoLogo); // Set up text drawing SetBkMode(hDC, TRANSPARENT); hftTemp = (HFONT)GetCurrentObject(hDC, OBJ_FONT); // Draw window text SelectObject(hDC, hFont_MainBold); rt.left = 52; rt.top = 10; rt.right = 232; rt.bottom = 50; DrawText(hDC, "Checkers", -1, &rt, 0); rt.left = 52; rt.top = 26; rt.right = 232; rt.bottom = 58; DrawText(hDC, "By Joe Esposito", -1, &rt, 0); // Clean up // --------- SelectObject(hDC, hftTemp); EndPaint(hWnd, &ps); return TRUE; case WM_SYSCOLORCHANGE: // Redraw background hDC = CreateCompatibleDC(NULL); hbmTemp = (HBITMAP)SelectObject(hDC, lpAboutInfo->hBackground); DrawGradientRect(hDC, 0, 0, ClientWidth(hWnd), ClientHeight(hWnd), BG_GB_COLOR_TL, BG_GB_COLOR_BL, BG_GB_COLOR_TR, BG_GB_COLOR_BR); SelectObject(hDC, hbmTemp); DeleteDC(hDC); break; case WM_COMMAND: if (lParam != NULL) { // Control Notification // --------------------- switch (LOWORD(wParam)) { case (ID_BTN_OK | BN_CLICKED): // OK button switch (HIWORD(wParam)) { case BN_CLICKED: SendMessage(hWnd, WM_CLOSE, 0, 0); return 0; } } } break; case WM_CLOSE: // End the dialog EndDialog(hWnd, 0); return 0; case WM_DESTROY: // Clean up // --------- // Clean up window info if (lpAboutInfo) { // Destroy windows objects DestroyIcon(lpAboutInfo->hicoLogo); // Destroy logo icon DeleteObject(lpAboutInfo->hBackground); // Destroy background bitmap // Delete window info delete lpAboutInfo; SetWindowLong(hWnd, GWL_USERDATA, (LONG)(lpAboutInfo = NULL)); } // Failsafe EndDialog(hWnd, 0); break; } return DefDlgProc(hWnd, uMsg, wParam, lParam); } // Public Functions // ----------------- void DoAbout (HWND hParent) { CreateDialogBox((WS_EX_CONTROLPARENT | WS_EX_DLGMODALFRAME | WS_EX_WINDOWEDGE), ID_ABOUTWND_CLASSNAME, "About Checkers", (WS_VISIBLE | WS_POPUPWINDOW | WS_DLGFRAME | WS_CAPTION | WS_SYSMENU | WS_CLIPSIBLINGS | DS_NOIDLEMSG | DS_SETFOREGROUND), CW_USEDEFAULT, CW_USEDEFAULT, 344, 178, hParent, NULL, 0, hInstance, NULL, NULL, true); }
[ [ [ 1, 212 ] ] ]
aacd9c79fbb680d2f17778afe1af1329f8a74e38
b73f27ba54ad98fa4314a79f2afbaee638cf13f0
/libproject/Setting/HotkeySetting.h
a8969fb77ade4dd453fe28b9078386f5277d7f16
[]
no_license
weimingtom/httpcontentparser
4d5ed678f2b38812e05328b01bc6b0c161690991
54554f163b16a7c56e8350a148b1bd29461300a0
refs/heads/master
2021-01-09T21:58:30.326476
2009-09-23T08:05:31
2009-09-23T08:05:31
48,733,304
3
0
null
null
null
null
WINDOWS-1252
C++
false
false
727
h
#ifndef _SETTING_HOTKEYSETTING_H__ #define _SETTING_HOTKEYSETTING_H__ #include <setting\configitem.h> #include <setting\settingitem.h> #include <string> #include <map> // ¶ÁÈ¡ÈȼüµÄÉèÖà class HotkeySetting : public ConfigItem, public SettingItem { public: HotkeySetting(); ~HotkeySetting(void); unsigned getHotkey(const std::string &name); void setHotkey(const std::string &name, const unsigned hotkey); protected: typedef std::map<std::string, unsigned> HOTKEY_MAP; HOTKEY_MAP hotkeys_; void defaultSetting(); public: virtual int parseConfig(TiXmlElement * item_root); virtual TiXmlElement * saveConfig(TiXmlElement * root); }; #endif // _SETTING_HOTKEYSETTING_H__
[ [ [ 1, 29 ] ] ]
6f7095270d8a80248637da786c548a0d6a7ed67e
a7990bf2f56d927ae884db0e727c17394bda39c4
/image-approx/Net.h
0bff589d5d81b019dd9a7cdf93846f8935e2b246
[]
no_license
XPaladin/image-approx
600862d8d76264e25f96ae10f3a9f5639a678b17
b0fbddef0e58ae1ba2b5e31f7eb87e2a48509dfb
refs/heads/master
2016-09-01T17:49:01.705563
2009-06-15T06:01:46
2009-06-15T06:01:46
33,272,564
0
0
null
null
null
null
UTF-8
C++
false
false
139
h
#ifndef NET_H #define NET_H class Net { protected: virtual bool invariante()const; public: Net(); }; #endif // NET_H
[ "pala.sepu@17da7754-4e6e-11de-84bb-6bba061bd1d3" ]
[ [ [ 1, 12 ] ] ]
d52ce258a28c57bdc0e2489577f91a5c2c25a544
5df145c06c45a6181d7402279aabf7ce9376e75e
/src/treeproxymodel.cpp
37f145622c2f7b5175b4ef1967344712b128853e
[]
no_license
plus7/openjohn
89318163f42347bbac24e8272081d794449ab861
1ffdcc1ea3f0af43b9033b68e8eca048a229305f
refs/heads/master
2021-03-12T22:55:57.315977
2009-05-15T11:30:00
2009-05-15T11:30:00
152,690
1
1
null
null
null
null
UTF-8
C++
false
false
2,463
cpp
/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Qt Software Information ([email protected]) ** ** This file is part of the demonstration applications of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial Usage ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain ** additional rights. These rights are described in the Nokia Qt LGPL ** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this ** package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at [email protected]. ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "treeproxymodel.h" TreeProxyModel::TreeProxyModel(QObject *parent) : QSortFilterProxyModel(parent) { //setSortRole(HistoryModel::DateTimeRole); setFilterCaseSensitivity(Qt::CaseInsensitive); } bool TreeProxyModel::filterAcceptsRow(int source_row, const QModelIndex &source_parent) const { if (!source_parent.isValid()) return true; return QSortFilterProxyModel::filterAcceptsRow(source_row, source_parent); }
[ [ [ 1, 55 ] ] ]
a7451b26c16a2fd836fb94f6b6ad4af71f36b4c8
6a925ad6f969afc636a340b1820feb8983fc049b
/librtsp/contrib/inc/jrtplib/rtpsession.h
0e611a0424595288e9d8a40afa8d74c386cd4249
[]
no_license
dulton/librtsp
c1ac298daecd8f8008f7ab1c2ffa915bdbb710ad
8ab300dc678dc05085f6926f016b32746c28aec3
refs/heads/master
2021-05-29T14:59:37.037583
2010-05-30T04:07:28
2010-05-30T04:07:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
25,321
h
/* This file is a part of JRTPLIB Copyright (c) 1999-2007 Jori Liesenborgs Contact: [email protected] This library was developed at the "Expertisecentrum Digitale Media" (http://www.edm.uhasselt.be), a research center of the Hasselt University (http://www.uhasselt.be). The library is based upon work done for my thesis at the School for Knowledge Technology (Belgium/The Netherlands). Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * \file rtpsession.h */ #ifndef RTPSESSION_H #define RTPSESSION_H #include "rtpconfig.h" #include "rtplibraryversion.h" #include "rtppacketbuilder.h" #include "rtpsessionsources.h" #include "rtptransmitter.h" #include "rtpcollisionlist.h" #include "rtcpscheduler.h" #include "rtcppacketbuilder.h" #include "rtptimeutilities.h" #include "rtcpcompoundpacketbuilder.h" #include "rtpmemoryobject.h" #include <list> #ifdef RTP_SUPPORT_THREAD #include <jmutex.h> #endif // RTP_SUPPORT_THREAD class RTPTransmitter; class RTPSessionParams; class RTPTransmissionParams; class RTPAddress; class RTPSourceData; class RTPPacket; class RTPPollThread; class RTPTransmissionInfo; class RTCPCompoundPacket; class RTCPPacket; class RTCPAPPPacket; /** High level class for using RTP. * For most RTP based applications, the RTPSession class will probably be the one to use. It handles * the RTCP part completely internally, so the user can focus on sending and receiving the actual data. * \note The RTPSession class is not meant to be thread safe. The user should use some kind of locking * mechanism to prevent different threads from using the same RTPSession instance. */ class RTPSession : public RTPMemoryObject { public: /** Constructs an RTPSession instance, optionally installing a memory manager. */ RTPSession(RTPMemoryManager *mgr = 0); virtual ~RTPSession(); /** Creates an RTP session. * This function creates an RTP session with parameters \c sessparams, which will use a transmitter * corresponding to \c proto. Parameters for this transmitter can be specified as well. If \c * proto is of type RTPTransmitter::UserDefinedProto, the NewUserDefinedTransmitter function must * be implemented. */ int Create(const RTPSessionParams &sessparams,const RTPTransmissionParams *transparams = 0, RTPTransmitter::TransmissionProtocol proto = RTPTransmitter::IPv4UDPProto); /** Creates an RTP session using \c transmitter as transmission component. * This function creates an RTP session with parameters \c sessparams, which will use the * transmission component \c transmitter. Initialization and destruction of the transmitter * will not be done by the RTPSession class if this Create function is used. This function * can be useful if you which to reuse the transmission component in another RTPSession * instance, once the original RTPSession isn't using the transmitter anymore. */ int Create(const RTPSessionParams &sessparams,RTPTransmitter *transmitter); /** Leaves the session without sending a BYE packet. */ void Destroy(); /** Sends a BYE packet and leaves the session. * Sends a BYE packet and leaves the session. At most a time \c maxwaittime will be waited to * send the BYE packet. If this time expires, the session will be left without sending a BYE packet. * The BYE packet will contain as reason for leaving \c reason with length \c reasonlength. */ void BYEDestroy(const RTPTime &maxwaittime,const void *reason,size_t reasonlength); /** Returns whether the session has been created or not. */ bool IsActive(); /** Returns our own SSRC. */ uint32_t GetLocalSSRC(); /** Adds \c addr to the list of destinations. */ int AddDestination(const RTPAddress &addr); /** Deletes \c addr from the list of destinations. */ int DeleteDestination(const RTPAddress &addr); /** Clears the list of destinations. */ void ClearDestinations(); /** Returns \c true if multicasting is supported. */ bool SupportsMulticasting(); /** Joins the multicast group specified by \c addr. */ int JoinMulticastGroup(const RTPAddress &addr); /** Leaves the multicast group specified by \c addr. */ int LeaveMulticastGroup(const RTPAddress &addr); /** Leaves all multicast groups. */ void LeaveAllMulticastGroups(); /** Sends the RTP packet with payload \c data which has length \c len. * Sends the RTP packet with payload \c data which has length \c len. * The used payload type, marker and timestamp increment will be those that have been set * using the \c SetDefault member functions. */ int SendPacket(const void *data,size_t len); /** Sends the RTP packet with payload \c data which has length \c len. * It will use payload type \c pt, marker \c mark and after the packet has been built, the * timestamp will be incremented by \c timestampinc. */ int SendPacket(const void *data,size_t len, uint8_t pt,bool mark,uint32_t timestampinc); /** Sends the RTP packet with payload \c data which has length \c len. * The packet will contain a header extension with identifier \c hdrextID and containing data * \c hdrextdata. The length of this data is given by \c numhdrextwords and is specified in a * number of 32-bit words. The used payload type, marker and timestamp increment will be those that * have been set using the \c SetDefault member functions. */ int SendPacketEx(const void *data,size_t len, uint16_t hdrextID,const void *hdrextdata,size_t numhdrextwords); /** Sends the RTP packet with payload \c data which has length \c len. * It will use payload type \c pt, marker \c mark and after the packet has been built, the * timestamp will be incremented by \c timestampinc. The packet will contain a header * extension with identifier \c hdrextID and containing data \c hdrextdata. The length * of this data is given by \c numhdrextwords and is specified in a number of 32-bit words. */ int SendPacketEx(const void *data,size_t len, uint8_t pt,bool mark,uint32_t timestampinc, uint16_t hdrextID,const void *hdrextdata,size_t numhdrextwords); #ifdef RTP_SUPPORT_SENDAPP /** If sending of RTCP APP packets was enabled at compile time, this function creates a compound packet * containing an RTCP APP packet and sends it immediately. * If sending of RTCP APP packets was enabled at compile time, this function creates a compound packet * containing an RTCP APP packet and sends it immediately. If successful, the function returns the number * of bytes in the RTCP compound packet. Note that this immediate sending is not compliant with the RTP * specification, so use with care. */ int SendRTCPAPPPacket(uint8_t subtype, const uint8_t name[4], const void *appdata, size_t appdatalen); #endif // RTP_SUPPORT_SENDAPP #ifdef RTP_SUPPORT_RTCPUNKNOWN /** Tries to send an Unknown packet immediately. * Tries to send an Unknown packet immediately. If successful, the function returns the number * of bytes in the RTCP compound packet. Note that this immediate sending is not compliant with the RTP * specification, so use with care. Can send message along with a receiver report or a sender report */ int SendUnknownPacket(bool sr, uint8_t payload_type, uint8_t subtype, const void *data, size_t len); #endif // RTP_SUPPORT_RTCPUNKNOWN /** Sets the default payload type for RTP packets to \c pt. */ int SetDefaultPayloadType(uint8_t pt); /** Sets the default marker for RTP packets to \c m. */ int SetDefaultMark(bool m); /** Sets the default value to increment the timestamp with to \c timestampinc. */ int SetDefaultTimestampIncrement(uint32_t timestampinc); /** This function increments the timestamp with the amount given by \c inc. * This function increments the timestamp with the amount given by \c inc. This can be useful * if, for example, a packet was not sent because it contained only silence. Then, this function * should be called to increment the timestamp with the appropriate amount so that the next packets * will still be played at the correct time at other hosts. */ int IncrementTimestamp(uint32_t inc); /** This function increments the timestamp with the amount given set by the SetDefaultTimestampIncrement * member function. * This function increments the timestamp with the amount given set by the SetDefaultTimestampIncrement * member function. This can be useful if, for example, a packet was not sent because it contained only silence. * Then, this function should be called to increment the timestamp with the appropriate amount so that the next * packets will still be played at the correct time at other hosts. */ int IncrementTimestampDefault(); /** This function allows you to inform the library about the delay between sampling the first * sample of a packet and sending the packet. * This function allows you to inform the library about the delay between sampling the first * sample of a packet and sending the packet. This delay is taken into account when calculating the * relation between RTP timestamp and wallclock time, used for inter-media synchronization. */ int SetPreTransmissionDelay(const RTPTime &delay); /** This function returns an instance of a subclass of RTPTransmissionInfo which will give some * additional information about the transmitter (a list of local IP addresses for example). * This function returns an instance of a subclass of RTPTransmissionInfo which will give some * additional information about the transmitter (a list of local IP addresses for example). The user * has to free the returned instance when it is no longer needed, preferably using the DeleteTransmissionInfo * function. */ RTPTransmissionInfo *GetTransmissionInfo(); /** Frees the memory used by the transmission information \c inf. */ void DeleteTransmissionInfo(RTPTransmissionInfo *inf); /** If you're not using the poll thread, this function must be called regularly to process incoming data * and to send RTCP data when necessary. */ int Poll(); /** Waits at most a time \c delay until incoming data has been detected. * Waits at most a time \c delay until incoming data has been detected. Only works when you're not * using the poll thread. If \c dataavailable is not \c NULL, it should be set to \c true if data * was actually read and to \c false otherwise. */ int WaitForIncomingData(const RTPTime &delay,bool *dataavailable = 0); /** If the previous function has been called, this one aborts the waiting (only works when you're not * using the poll thread). */ int AbortWait(); /** Returns the time interval after which an RTCP compound packet may have to be sent (only works when * you're not using the poll thread. */ RTPTime GetRTCPDelay(); /** The following member functions (till EndDataAccess}) need to be accessed between a call * to BeginDataAccess and EndDataAccess. * The BeginDataAccess function makes sure that the poll thread won't access the source table * at the same time that you're using it. When the EndDataAccess is called, the lock on the * source table is freed again. */ int BeginDataAccess(); /** Starts the iteration over the participants by going to the first member in the table. * Starts the iteration over the participants by going to the first member in the table. * If a member was found, the function returns \c true, otherwise it returns \c false. */ bool GotoFirstSource(); /** Sets the current source to be the next source in the table. * Sets the current source to be the next source in the table. If we're already at the last * source, the function returns \c false, otherwise it returns \c true. */ bool GotoNextSource(); /** Sets the current source to be the previous source in the table. * Sets the current source to be the previous source in the table. If we're at the first source, * the function returns \c false, otherwise it returns \c true. */ bool GotoPreviousSource(); /** Sets the current source to be the first source in the table which has RTPPacket instances * that we haven't extracted yet. * Sets the current source to be the first source in the table which has RTPPacket instances * that we haven't extracted yet. If no such member was found, the function returns \c false, * otherwise it returns \c true. */ bool GotoFirstSourceWithData(); /** Sets the current source to be the next source in the table which has RTPPacket instances * that we haven't extracted yet. * Sets the current source to be the next source in the table which has RTPPacket instances * that we haven't extracted yet. If no such member was found, the function returns \c false, * otherwise it returns \c true. */ bool GotoNextSourceWithData(); /** Sets the current source to be the previous source in the table which has RTPPacket * instances that we haven't extracted yet. * Sets the current source to be the previous source in the table which has RTPPacket * instances that we haven't extracted yet. If no such member was found, the function returns \c false, * otherwise it returns \c true. */ bool GotoPreviousSourceWithData(); /** Returns the \c RTPSourceData instance for the currently selected participant. */ RTPSourceData *GetCurrentSourceInfo(); /** Returns the \c RTPSourceData instance for the participant identified by \c ssrc, * or NULL if no such entry exists. */ RTPSourceData *GetSourceInfo(uint32_t ssrc); /** Extracts the next packet from the received packets queue of the current participant, * or NULL if no more packets are available. * Extracts the next packet from the received packets queue of the current participant, * or NULL if no more packets are available. When the packet is no longer needed, its * memory should be freed using the DeletePacket member function. */ RTPPacket *GetNextPacket(); /** Frees the memory used by \c p. */ void DeletePacket(RTPPacket *p); /** See BeginDataAccess. */ int EndDataAccess(); /** Sets the receive mode to \c m. * Sets the receive mode to \c m. Note that when the receive mode is changed, the list of * addresses to be ignored ot accepted will be cleared. */ int SetReceiveMode(RTPTransmitter::ReceiveMode m); /** Adds \c addr to the list of addresses to ignore. */ int AddToIgnoreList(const RTPAddress &addr); /** Deletes \c addr from the list of addresses to ignore. */ int DeleteFromIgnoreList(const RTPAddress &addr); /** Clears the list of addresses to ignore. */ void ClearIgnoreList(); /** Adds \c addr to the list of addresses to accept. */ int AddToAcceptList(const RTPAddress &addr); /** Deletes \c addr from the list of addresses to accept. */ int DeleteFromAcceptList(const RTPAddress &addr); /** Clears the list of addresses to accept. */ void ClearAcceptList(); /** Sets the maximum allowed packet size to \c s. */ int SetMaximumPacketSize(size_t s); /** Sets the session bandwidth to \c bw, which is specified in bytes per second. */ int SetSessionBandwidth(double bw); /** Sets the timestamp unit for our own data. * Sets the timestamp unit for our own data. The timestamp unit is defined as a time interval in * seconds divided by the corresponding timestamp interval. For example, for 8000 Hz audio, the * timestamp unit would typically be 1/8000. Since this value is initially set to an illegal value, * the user must set this to an allowed value to be able to create a session. */ int SetTimestampUnit(double u); /** Sets the RTCP interval for the SDES name item. * After all possible sources in the source table have been processed, the class will check if other * SDES items need to be sent. If \c count is zero or negative, nothing will happen. If \c count * is positive, an SDES name item will be added after the sources in the source table have been * processed \c count times. */ void SetNameInterval(int count); /** Sets the RTCP interval for the SDES e-mail item. * After all possible sources in the source table have been processed, the class will check if other * SDES items need to be sent. If \c count is zero or negative, nothing will happen. If \c count * is positive, an SDES e-mail item will be added after the sources in the source table have been * processed \c count times. */ void SetEMailInterval(int count); /** Sets the RTCP interval for the SDES location item. * After all possible sources in the source table have been processed, the class will check if other * SDES items need to be sent. If \c count is zero or negative, nothing will happen. If \c count * is positive, an SDES location item will be added after the sources in the source table have been * processed \c count times. */ void SetLocationInterval(int count); /** Sets the RTCP interval for the SDES phone item. * After all possible sources in the source table have been processed, the class will check if other * SDES items need to be sent. If \c count is zero or negative, nothing will happen. If \c count * is positive, an SDES phone item will be added after the sources in the source table have been * processed \c count times. */ void SetPhoneInterval(int count); /** Sets the RTCP interval for the SDES tool item. * After all possible sources in the source table have been processed, the class will check if other * SDES items need to be sent. If \c count is zero or negative, nothing will happen. If \c count * is positive, an SDES tool item will be added after the sources in the source table have been * processed \c count times. */ void SetToolInterval(int count); /** Sets the RTCP interval for the SDES note item. * After all possible sources in the source table have been processed, the class will check if other * SDES items need to be sent. If \c count is zero or negative, nothing will happen. If \c count * is positive, an SDES note item will be added after the sources in the source table have been * processed \c count times. */ void SetNoteInterval(int count); /** Sets the SDES name item for the local participant to the value \c s with length \c len. */ int SetLocalName(const void *s,size_t len); /** Sets the SDES e-mail item for the local participant to the value \c s with length \c len. */ int SetLocalEMail(const void *s,size_t len); /** Sets the SDES location item for the local participant to the value \c s with length \c len. */ int SetLocalLocation(const void *s,size_t len); /** Sets the SDES phone item for the local participant to the value \c s with length \c len. */ int SetLocalPhone(const void *s,size_t len); /** Sets the SDES tool item for the local participant to the value \c s with length \c len. */ int SetLocalTool(const void *s,size_t len); /** Sets the SDES note item for the local participant to the value \c s with length \c len. */ int SetLocalNote(const void *s,size_t len); /** Returns the current RTP timestamp. */ uint32_t GetTimestamp() const { return packetbuilder.GetTimestamp(); } /** Returns the current sequence number. */ uint16_t GetSequenceNumber() const { return packetbuilder.GetSequenceNumber(); } #ifdef RTPDEBUG void DumpSources(); void DumpTransmitter(); #endif // RTPDEBUG protected: /** Allocate a user defined transmitter. * In case you specified in the Create function that you want to use a * user defined transmitter, you should override this function. The RTPTransmitter * instance returned by this function will then be used to send and receive RTP and * RTCP packets. Note that when the session is destroyed, this RTPTransmitter * instance will be destroyed as well. */ virtual RTPTransmitter *NewUserDefinedTransmitter() { return 0; } /** Is called when an incoming RTCP packet is about to be processed. */ virtual void OnRTPPacket(RTPPacket *pack,const RTPTime &receivetime, const RTPAddress *senderaddress) { } /** Is called when an incoming RTCP packet is about to be processed. */ virtual void OnRTCPCompoundPacket(RTCPCompoundPacket *pack,const RTPTime &receivetime, const RTPAddress *senderaddress) { } /** Is called when an SSRC collision was detected. * Is called when an SSRC collision was detected. The instance \c srcdat is the one present in * the table, the address \c senderaddress is the one that collided with one of the addresses * and \c isrtp indicates against which address of \c srcdat the check failed. */ virtual void OnSSRCCollision(RTPSourceData *srcdat,const RTPAddress *senderaddress,bool isrtp) { } /** Is called when another CNAME was received than the one already present for source \c srcdat. */ virtual void OnCNAMECollision(RTPSourceData *srcdat,const RTPAddress *senderaddress, const uint8_t *cname,size_t cnamelength) { } /** Is called when a new entry \c srcdat is added to the source table. */ virtual void OnNewSource(RTPSourceData *srcdat) { } /** Is called when the entry \c srcdat is about to be deleted from the source table. */ virtual void OnRemoveSource(RTPSourceData *srcdat) { } /** Is called when participant \c srcdat is timed out. */ virtual void OnTimeout(RTPSourceData *srcdat) { } /** Is called when participant \c srcdat is timed after having sent a BYE packet. */ virtual void OnBYETimeout(RTPSourceData *srcdat) { } /** Is called when an RTCP APP packet \c apppacket has been received at time \c receivetime * from address \c senderaddress. */ virtual void OnAPPPacket(RTCPAPPPacket *apppacket,const RTPTime &receivetime, const RTPAddress *senderaddress) { } /** Is called when an unknown RTCP packet type was detected. */ virtual void OnUnknownPacketType(RTCPPacket *rtcppack,const RTPTime &receivetime, const RTPAddress *senderaddress) { } /** Is called when an unknown packet format for a known packet type was detected. */ virtual void OnUnknownPacketFormat(RTCPPacket *rtcppack,const RTPTime &receivetime, const RTPAddress *senderaddress) { } /** Is called when the SDES NOTE item for source \c srcdat has been timed out. */ virtual void OnNoteTimeout(RTPSourceData *srcdat) { } /** Is called when a BYE packet has been processed for source \c srcdat. */ virtual void OnBYEPacket(RTPSourceData *srcdat) { } /** Is called when an RTCP compound packet has just been sent (useful to inspect outgoing RTCP data). */ virtual void OnSendRTCPCompoundPacket(RTCPCompoundPacket *pack) { } #ifdef RTP_SUPPORT_THREAD /** Is called when error \c errcode was detected in the poll thread. */ virtual void OnPollThreadError(int errcode) { } /** Is called each time the poll thread loops. * Is called each time the poll thread loops. This happens when incoming data was * detected or when it's time to send an RTCP compound packet. */ virtual void OnPollThreadStep() { } #endif // RTP_SUPPORT_THREAD private: int InternalCreate(const RTPSessionParams &sessparams); int CreateCNAME(uint8_t *buffer,size_t *bufferlength,bool resolve); int ProcessPolledData(); int ProcessRTCPCompoundPacket(RTCPCompoundPacket &rtcpcomppack,RTPRawPacket *pack); RTPTransmitter *rtptrans; bool created; bool deletetransmitter; bool usingpollthread; bool acceptownpackets; bool useSR_BYEifpossible; size_t maxpacksize; double sessionbandwidth; double controlfragment; double sendermultiplier; double byemultiplier; double membermultiplier; double collisionmultiplier; double notemultiplier; bool sentpackets; RTPSessionSources sources; RTPPacketBuilder packetbuilder; RTCPScheduler rtcpsched; RTCPPacketBuilder rtcpbuilder; RTPCollisionList collisionlist; std::list<RTCPCompoundPacket *> byepackets; #ifdef RTP_SUPPORT_THREAD RTPPollThread *pollthread; JMutex sourcesmutex,buildermutex,schedmutex,packsentmutex; friend class RTPPollThread; #endif // RTP_SUPPORT_THREAD friend class RTPSessionSources; friend class RTCPSessionPacketBuilder; }; #endif // RTPSESSION_H
[ "TangWentaoHust@95ff1050-1aa1-11de-b6aa-3535bc3264a2" ]
[ [ [ 1, 562 ] ] ]
04c5fbf43d78c3a40a33e70d0998794d43bc2c5c
080941f107281f93618c30a7aa8bec9e8e2d8587
/src/libloader/conditionerBase.cpp
7f111961a11cd4bbf5ce295c4e9162201a0e8001
[ "MIT" ]
permissive
scoopr/COLLADA_Refinery
6d40ee1497b9f33818ec1e71677c3d0a0bf8ced4
3a5ad1a81e0359f9025953e38e425bc10b5bf6c5
refs/heads/master
2021-01-22T01:55:14.642769
2009-03-10T21:31:04
2009-03-10T21:31:04
194,828
2
0
null
null
null
null
UTF-8
C++
false
false
9,689
cpp
/* The MIT License Copyright 2006 Sony Computer Entertainment Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ //#include <windows.h> #include <dae.h> #include "conditionerBase.h" static std::string NULLString = ""; ConditionerBase::ConditionerBase() { _numInputs = 1; _numOutputs = 1; _inputs.resize( 1 ); _outputs.resize( 1 ); _variableInputs = false; _outputs[0]._linked = true; _outputs[0]._editable = false; } ConditionerBase::ConditionerBase(const ConditionerBase &toCopy) { printf("*** Copy constructor !!!"); } ConditionerBase::~ConditionerBase() { } bool ConditionerBase::setDAE( DAE *dae ) { _dae = dae; return true; } std::string ConditionerBase::getCategory() const { return ""; } void ConditionerBase::setName( const std::string &nm ) { _name = nm; } void ConditionerBase::setNumInputs( unsigned int num, bool variable ) { _numInputs = num; _inputs.resize( _numInputs ); _variableInputs = variable; } bool ConditionerBase::setInput( unsigned int num, const std::string &input ) { if ( num >= _numInputs ) return false; _inputs[num] = input; return true; } void ConditionerBase::setNumOutputs( unsigned int num ) { _numOutputs = num; _outputs.resize( _numOutputs ); } bool ConditionerBase::setOutput( unsigned int num, const std::string &output ) { if ( num >= _numOutputs ) return false; if ( _outputs[num]._linked ) return false; _outputs[num]._output = output; return true; } bool ConditionerBase::setOutputProperties( unsigned int num, bool linked, bool editable ) { if ( num >= _numOutputs ) return false; if ( linked && editable ) return false; if ( linked && num >= _numInputs ) return false; _outputs[num]._editable = editable; _outputs[num]._linked = linked; return true; } void ConditionerBase::addBoolOption( const std::string &option, const std::string &fullName, const std::string &description, bool def ) { BoolOption bo; bo.fullName = fullName; bo.description = description; bo.value = def; bo.flag = false; _boolOptions.insert( std::make_pair( option, bo ) ); } void ConditionerBase::addStringOption( const std::string &option, const std::string &fullName, const std::string &description, const std::string &def, bool fileMenu ) { StringOption so; so.fullName = fullName; so.description = description; so.value = def; so.flag = fileMenu; _stringOptions.insert( std::make_pair( option, so ) ); } void ConditionerBase::addFloatOption( const std::string &option, const std::string &fullName, const std::string &description, float def ) { FloatOption fo; fo.fullName = fullName; fo.description = description; fo.value = def; fo.flag = false; _floatOptions.insert( std::make_pair( option, fo ) ); } const std::string &ConditionerBase::getName() const { return _name; } int ConditionerBase::getNumInputs() const { return _numInputs; } const std::string &ConditionerBase::getInput( unsigned int num ) const { if ( num >= _numInputs ) return NULLString; return _inputs[num]; } bool ConditionerBase::hasVariableNumInputs() const { return _variableInputs; } int ConditionerBase::getNumOutputs() const { return _numOutputs; } const std::string &ConditionerBase::getOutput( unsigned int num ) const { if ( num >= _numOutputs ) return NULLString; if ( _outputs[num]._linked ) return _inputs[num]; return _outputs[num]._output; } bool ConditionerBase::isOutputLinked( unsigned int num ) const { if ( num >= _numOutputs ) { return false; } return _outputs[num]._linked; } bool ConditionerBase::isOutputEditable( unsigned int num ) const { if ( num >= _numOutputs ) { return false; } return _outputs[num]._editable; } bool ConditionerBase::getBoolOption( const std::string &option, bool &out ) const { BoolOptionMap::const_iterator iter = _boolOptions.find( option ); if ( iter == _boolOptions.end() ) return false; out = iter->second.value; return true; } bool ConditionerBase::getStringOption( const std::string &option, std::string &out ) const { StringOptionMap::const_iterator iter = _stringOptions.find( option ); if ( iter == _stringOptions.end() ) return false; out = iter->second.value; return true; } bool ConditionerBase::getFloatOption( const std::string &option, float &out ) const { FloatOptionMap::const_iterator iter = _floatOptions.find( option ); if ( iter == _floatOptions.end() ) return false; out = iter->second.value; return true; } bool ConditionerBase::setBoolOption( const std::string &option, bool val ) { BoolOptionMap::iterator iter = _boolOptions.find( option ); if ( iter == _boolOptions.end() ) return false; iter->second.value = val; return true; } bool ConditionerBase::setStringOption( const std::string &option, const std::string &val ) { StringOptionMap::iterator iter = _stringOptions.find( option ); if ( iter == _stringOptions.end() ) return false; iter->second.value = val; return true; } bool ConditionerBase::setFloatOption( const std::string &option, float val ) { FloatOptionMap::iterator iter = _floatOptions.find( option ); if ( iter == _floatOptions.end() ) return false; iter->second.value = val; return true; } const ConditionerBase::BoolOptionMap &ConditionerBase::getBoolOptionsMap() const { return _boolOptions; } const ConditionerBase::StringOptionMap &ConditionerBase::getStringOptionsMap() const { return _stringOptions; } const ConditionerBase::FloatOptionMap &ConditionerBase::getFloatOptionsMap() const { return _floatOptions; } void ConditionerBase::printDebugMessage( const std::string &message ) { #ifdef _DEBUG #ifdef REFINERY LibLoader::printDebugMessage( message ); #else printf( message.c_str() ); #endif #endif } void ConditionerBase::printExecutionMessage( const std::string &message ) { #ifdef REFINERY LibLoader::printExecutionMessage( message ); #else printf( message.c_str() ); #endif } void ConditionerBase::printErrorMessage( const std::string &message ) { #ifdef REFINERY LibLoader::printErrorMessage( message ); #else fprintf( stderr, message.c_str() ); #endif } Conditioner *ConditionerBase::create() const { //If you are going to use your derived Conditioner class as the creation //object you MUST overwrite this function to return an instance of your //derived class. //If you don't want an extra instance of your class to be used as the //creator then you can write a class that derives from ConditionerCreator //and have it's create() function returns an instance of your derived class. assert( 0 ); return NULL; } #if 0 jobject Conditioner::startNewChart(string name){ jstring nameJString = env->NewStringUTF(name.c_str()); jmethodID mid = env->GetMethodID(cls, "startNewChart", "(Ljava/lang/String;)Lrefinery/output/Chart;"); if (mid == 0) { printf("startNewChart not found !!\n"); return false; } jvalue args[2]; args[0].l = nameJString; return env->CallObjectMethodA(obj, mid, args); } void Conditioner::startProfile(jobject chart, string profileName){ jstring profileNameJString = env->NewStringUTF(profileName.c_str()); jmethodID mid = env->GetMethodID(cls, "startChartProfile", "(Lrefinery/output/Chart;Ljava/lang/String;)V"); if (mid == 0) { printf("startChartProfile not found !!\n"); return; } jvalue args[2]; args[0].l = chart; args[1].l = profileNameJString; env->CallVoidMethodA(obj, mid, args); } void Conditioner::startGroup(jobject chart, string groupName){ jstring groupNameJString = env->NewStringUTF(groupName.c_str()); jmethodID mid = env->GetMethodID(cls, "startChartGroup", "(Lrefinery/output/Chart;Ljava/lang/String;)V"); if (mid == 0) { printf("startChartGroup not found !!\n"); return; } jvalue args[2]; args[0].l = chart; args[1].l = groupNameJString; env->CallVoidMethodA(obj, mid, args); } void Conditioner::addDataToChart(jobject chart, string elementName, jint *array, int _size){ jsize size = _size; jintArray values = env->NewIntArray(size); env->SetIntArrayRegion(values, 0, size, array); jstring elementNameJString = env->NewStringUTF(elementName.c_str()); jmethodID mid = env->GetMethodID(cls, "addChartElement", "(Lrefinery/output/Chart;Ljava/lang/String;[I)V"); if (mid == 0) { printf("addChartElement not found !!\n"); return; } jvalue args[3]; args[0].l = chart; args[1].l = elementNameJString; args[2].l = values; env->CallVoidMethodA(obj, mid, args); } void Conditioner::displayChart(jobject chart){ jmethodID mid = env->GetMethodID(cls, "displayChart", "(Lrefinery/output/Chart;)V"); if (mid == 0) { printf("displayChart not found !!\n"); return; } jvalue args[1]; args[0].l = chart; env->CallVoidMethodA(obj, mid, args); } #endif
[ "alorino@7d79dae2-2c22-0410-a73c-a02ad39e49d4", "sceahklaw@7d79dae2-2c22-0410-a73c-a02ad39e49d4", "hnz@7d79dae2-2c22-0410-a73c-a02ad39e49d4" ]
[ [ [ 1, 1 ], [ 23, 24 ], [ 26, 402 ] ], [ [ 2, 22 ] ], [ [ 25, 25 ] ] ]
072857c36208b4f67e081c4102c12b4ceaedae6f
6e563096253fe45a51956dde69e96c73c5ed3c18
/dhnetsdk/Demo/User_AddGroup.cpp
3e92347d8091fdda93a7b1e7b017d56c30886abe
[]
no_license
15831944/phoebemail
0931b76a5c52324669f902176c8477e3bd69f9b1
e10140c36153aa00d0251f94bde576c16cab61bd
refs/heads/master
2023-03-16T00:47:40.484758
2010-10-11T02:31:02
2010-10-11T02:31:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,142
cpp
// User_AddGroup.cpp : implementation file // #include "stdafx.h" #include "netsdkdemo.h" #include "User_AddGroup.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CUser_AddGroup dialog CUser_AddGroup::CUser_AddGroup(CWnd* pParent /*=NULL*/) : CDialog(CUser_AddGroup::IDD, pParent) { m_user_info = 0; m_dev = 0; //{{AFX_DATA_INIT(CUser_AddGroup) // NOTE: the ClassWizard will add member initialization here //}}AFX_DATA_INIT } void CUser_AddGroup::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CUser_AddGroup) // NOTE: the ClassWizard will add DDX and DDV calls here //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CUser_AddGroup, CDialog) //{{AFX_MSG_MAP(CUser_AddGroup) ON_BN_CLICKED(IDC_BTN_OK, OnBtnOk) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CUser_AddGroup message handlers BOOL CUser_AddGroup::OnInitDialog() { CDialog::OnInitDialog(); g_SetWndStaticText(this); CRect rect; GetDlgItem(IDC_RLIST_FRAME)->GetClientRect(&rect); GetDlgItem(IDC_RLIST_FRAME)->ClientToScreen(&rect); ScreenToClient(&rect); BOOL bCreate = m_rightList.Create(WS_VISIBLE | WS_TABSTOP | WS_CHILD | WS_BORDER | TVS_HASBUTTONS | TVS_LINESATROOT | TVS_HASLINES | TVS_DISABLEDRAGDROP, rect, this, 0x1005); SetWindowLong(m_rightList.m_hWnd, GWL_STYLE, TVS_CHECKBOXES); m_rightList.ShowWindow(SW_SHOW); if (!m_user_info || !m_dev) { return TRUE; } CString strRight; for (int i = 0; i < m_user_info->dwRightNum; i++) { HTREEITEM hRoot; strRight.Format("%d: %s : %s", m_user_info->rightList[i].dwID, m_user_info->rightList[i].name, m_user_info->rightList[i].memo); hRoot = m_rightList.InsertItem(strRight, 0, 0, TVI_ROOT); m_rightList.SetItemData(hRoot, m_user_info->rightList[i].dwID); } return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE } void CUser_AddGroup::SetEnvrmt(USER_MANAGE_INFO *info, DeviceNode *dev) { m_user_info = info; m_dev = dev; } void CUser_AddGroup::OnBtnOk() { USER_GROUP_INFO ugInfo = {0}; ugInfo.dwID = m_user_info->dwGroupNum + 1; GetDlgItem(IDC_NAME_EDIT)->GetWindowText(ugInfo.name, USER_NAME_LENGTH); GetDlgItem(IDC_MEMO_EDIT)->GetWindowText(ugInfo.memo, MEMO_LENGTH); int count = m_rightList.GetCount(); HTREEITEM node = m_rightList.GetRootItem(); int rIndex = 0; for (int i=0; i<count && node; i++) { if (m_rightList.GetCheck(node)) { ugInfo.rights[rIndex] = m_rightList.GetItemData(node); rIndex++; } node = m_rightList.GetNextItem(node, TVGN_NEXT); } ugInfo.dwRightNum = rIndex; BOOL bRet = CLIENT_OperateUserInfo(m_dev->LoginID, 0/*type: add user group*/, &ugInfo, 0, 1000); if (!bRet) { MessageBox(ConvertString("Failed to operate user info")); } else { EndDialog(0); } }
[ "guoqiao@a83c37f4-16cc-5f24-7598-dca3a346d5dd" ]
[ [ [ 1, 121 ] ] ]
5c4115ce15ae18f92db3f570ffce14c925db824c
c1c3866586c56ec921cd8c9a690e88ac471adfc8
/WOW/BlpViewer/BlpViewer/BlpViewerDoc.h
5740aa1732039f7ea69dcea5a5d1991f6b2429c6
[]
no_license
rtmpnewbie/lai3d
0802dbb5ebe67be2b28d9e8a4d1cc83b4f36b14f
b44c9edfb81fde2b40e180a651793fec7d0e617d
refs/heads/master
2021-01-10T04:29:07.463289
2011-03-22T17:51:24
2011-03-22T17:51:24
36,842,700
1
0
null
null
null
null
GB18030
C++
false
false
592
h
// BlpViewerDoc.h : CBlpViewerDoc 类的接口 // #pragma once class CBlpViewerDoc : public CDocument { protected: // 仅从序列化创建 CBlpViewerDoc(); DECLARE_DYNCREATE(CBlpViewerDoc) // 属性 public: // 操作 public: // 重写 public: virtual BOOL OnNewDocument(); virtual void Serialize(CArchive& ar); // 实现 public: virtual ~CBlpViewerDoc(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif protected: // 生成的消息映射函数 protected: DECLARE_MESSAGE_MAP() };
[ "laiyanlin@27d9c402-1b7e-11de-9433-ad2e3fad96c5" ]
[ [ [ 1, 40 ] ] ]
befb1511b4c45e7a77e59826e11dd9482a557427
bfe8eca44c0fca696a0031a98037f19a9938dd26
/DDEPrint/StdAfx.cpp
0d9acde48f2354c4e2bca4408d39163f07d3f5e9
[]
no_license
luge/foolject
a190006bc0ed693f685f3a8287ea15b1fe631744
2f4f13a221a0fa2fecab2aaaf7e2af75c160d90c
refs/heads/master
2021-01-10T07:41:06.726526
2011-01-21T10:25:22
2011-01-21T10:25:22
36,303,977
0
0
null
null
null
null
UTF-8
C++
false
false
295
cpp
// stdafx.cpp : source file that includes just the standard includes // DDEPrint.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h" // TODO: reference any additional headers you need in STDAFX.H // and not in this file
[ "greatfoolbear@756bb6b0-a119-0410-8338-473b6f1ccd30" ]
[ [ [ 1, 8 ] ] ]
531e9896daf9a90b11f195eb755f9daad419b618
804e416433c8025d08829a08b5e79fe9443b9889
/src/config.h
6ac1e2100d358d99b47c3f993578cbca84fada89
[ "BSD-2-Clause" ]
permissive
cstrahan/argss
e77de08db335d809a482463c761fb8d614e11ba4
cc595bd9a1e4a2c079ea181ff26bdd58d9e65ace
refs/heads/master
2020-05-20T05:30:48.876372
2010-10-03T23:21:59
2010-10-03T23:21:59
1,682,890
1
0
null
null
null
null
UTF-8
C++
false
false
2,180
h
///////////////////////////////////////////////////////////////////////////// // ARGSS - Copyright (c) 2009 - 2010, Alejandro Marzini (vgvgf) // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY EXPRESS OR // IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. // IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT // NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF // THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ///////////////////////////////////////////////////////////////////////////// #ifndef _CONFIG_H_ #define _CONFIG_H_ /////////////////////////////////////////////////////////// // Headers /////////////////////////////////////////////////////////// #include <string> /////////////////////////////////////////////////////////// /// Config namespace. /////////////////////////////////////////////////////////// namespace Config { /////////////////////////////////////////////////////// /// Initialize System. /////////////////////////////////////////////////////// void Init(); extern std::string ScriptsPath; extern std::string Title; extern std::string RTPS[3]; extern int Width; extern int Height; }; #endif
[ "vgvgf@a70b67f4-0116-4799-9eb2-a6e6dfe7dbda" ]
[ [ [ 1, 51 ] ] ]
882f9282a559cd61fe22eae64c748575fdf10202
3d873b9abae5014a271615d94d7c445d0e15b52d
/UnitTestingCustomActions/Source/CustomActionTest/CustomActionTest.cpp
d7e0785830dc42f7df6923913c09dcb290dd611d
[]
no_license
hacker-chandan/codeproject
c26b6a906cd66714964e31c0b3c5775f72565220
c65cdd702701e2766feb3114b64455763fa4bbe0
refs/heads/master
2021-05-27T11:23:59.870263
2010-12-03T15:32:51
2010-12-03T15:32:51
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,168
cpp
#include "stdafx.h" int _tmain(int argc, _TCHAR* argv[]) { CoInitialize(NULL); MSIHANDLE hdb = NULL; // create the database LPCTSTR filename = L"Test.msi"; MsiOpenDatabase(filename, MSIDBOPEN_CREATEDIRECT, & hdb); // set summary information, this makes an MSI runnable MSIHANDLE hsummary = NULL; MsiGetSummaryInformation(hdb, NULL, 7, & hsummary); MsiSummaryInfoSetPropertyA(hsummary, PID_REVNUMBER, VT_LPSTR, 0, NULL, "{00000000-0000-0000-0000-000000000000}"); MsiSummaryInfoSetPropertyA(hsummary, PID_SUBJECT, VT_LPSTR, 0, NULL, "Test MSI"); MsiSummaryInfoSetPropertyA(hsummary, PID_TITLE, VT_LPSTR, 0, NULL, "Test MSI"); MsiSummaryInfoSetPropertyA(hsummary, PID_AUTHOR, VT_LPSTR, 0, NULL, "dB."); MsiSummaryInfoSetPropertyA(hsummary, PID_TEMPLATE, VT_LPSTR, 0, NULL, ";1033"); MsiSummaryInfoSetProperty(hsummary, PID_PAGECOUNT, VT_I4, 100, NULL, NULL); MsiSummaryInfoSetProperty(hsummary, PID_WORDCOUNT, VT_I4, 100, NULL, NULL); // persiste the summary in the stream MsiSummaryInfoPersist(hsummary); MsiCloseHandle(hsummary); // commit changes to disk MsiDatabaseCommit(hdb); // close the database // MsiCloseHandle(hdb); // reopen as an MSI package, this function accepts opened handles in form of #handle wchar_t handle[12] = { 0 }; _snwprintf(handle, ARRAYSIZE(handle), L"#%d", (UINT) hdb); MSIHANDLE hproduct = NULL; MsiOpenPackage(handle, & hproduct); // load CustomAction.dll HMODULE hca = LoadLibrary(L"CustomAction.dll"); // find the address of SetProperty1CustomAction typedef int (__stdcall * LPCUSTOMACTION) (MSIHANDLE h); LPCUSTOMACTION lpca = (LPCUSTOMACTION) GetProcAddress(hca, "SetProperty1CustomAction"); // call the custom action lpca(hproduct); wchar_t buffer[255] = { 0 }; DWORD size = ARRAYSIZE(buffer); MsiGetProperty(hproduct, L"Property1", buffer, & size); if (wcscmp(buffer, L"Value1") == 0) { wprintf(L"success!"); } FreeLibrary(hca); MsiCloseHandle(hproduct); CoUninitialize(); return 0; }
[ [ [ 1, 58 ] ] ]
13a63de86b320844a34885dec91e08b2bacbfb7a
cfcd2a448c91b249ea61d0d0d747129900e9e97f
/thirdparty/OpenCOLLADA/COLLADASaxFrameworkLoader/src/COLLADASaxFWLInputUnshared.cpp
676e9f01587dcaf80556d72fd281a833fe754723
[]
no_license
fire-archive/OgreCollada
b1686b1b84b512ffee65baddb290503fb1ebac9c
49114208f176eb695b525dca4f79fc0cfd40e9de
refs/heads/master
2020-04-10T10:04:15.187350
2009-05-31T15:33:15
2009-05-31T15:33:15
268,046
0
0
null
null
null
null
UTF-8
C++
false
false
6,358
cpp
/* Copyright (c) 2008 NetAllied Systems GmbH This file is part of COLLADASaxFrameworkLoader. Licensed under the MIT Open Source License, for details please see LICENSE file or the website http://www.opensource.org/licenses/mit-license.php */ #include "COLLADASaxFWLStableHeaders.h" #include "COLLADASaxFWLInputUnshared.h" using namespace COLLADAFW; namespace COLLADASaxFWL { //------------------------------ InputUnshared::InputUnshared( InputSemantic::Semantic semantic, const COLLADABU::URI& source ) : mSemantic ( semantic ) , mSource ( source ) { } //------------------------------ InputUnshared::InputUnshared( const String& semantic, const String& source ) : mSemantic ( getSemanticFromString(semantic) ) , mSource ( source ) { } // ---------------------------- const String& InputUnshared::getSemanticAsString ( const InputSemantic::Semantic semantic ) { switch ( semantic ) { case InputSemantic::BINORMAL: return Constants::SEMANTIC_BINORMAL; case InputSemantic::COLOR: return Constants::SEMANTIC_COLOR; case InputSemantic::CONTINUITY: return Constants::SEMANTIC_CONTINUITY; case InputSemantic::IMAGE: return Constants::SEMANTIC_IMAGE; case InputSemantic::INPUT: return Constants::SEMANTIC_INPUT; case InputSemantic::IN_TANGENT: return Constants::SEMANTIC_IN_TANGENT; case InputSemantic::INTERPOLATION: return Constants::SEMANTIC_INTERPOLATION; case InputSemantic::INV_BIND_MATRIX: return Constants::SEMANTIC_INV_BIND_MATRIX; case InputSemantic::JOINT: return Constants::SEMANTIC_JOINT; case InputSemantic::LINEAR_STEPS: return Constants::SEMANTIC_LINEAR_STEPS; case InputSemantic::MORPH_TARGET: return Constants::SEMANTIC_MORPH_TARGET; case InputSemantic::MORPH_WEIGHT: return Constants::SEMANTIC_MORPH_WEIGHT; case InputSemantic::NORMAL: return Constants::SEMANTIC_NORMAL; case InputSemantic::OUTPUT: return Constants::SEMANTIC_OUTPUT; case InputSemantic::OUT_TANGENT: return Constants::SEMANTIC_OUT_TANGENT; case InputSemantic::POSITION: return Constants::SEMANTIC_POSITION; case InputSemantic::TANGENT: return Constants::SEMANTIC_TANGENT; case InputSemantic::TEXBINORMAL: return Constants::SEMANTIC_TEXBINORMAL; case InputSemantic::TEXCOORD: return Constants::SEMANTIC_TEXCOORD; case InputSemantic::TEXTANGENT: return Constants::SEMANTIC_TEXTANGENT; case InputSemantic::UV: return Constants::SEMANTIC_UV; case InputSemantic::VERTEX: return Constants::SEMANTIC_VERTEX; case InputSemantic::WEIGHT: return Constants::SEMANTIC_WEIGHT; case InputSemantic::UNKNOWN: default: return Constants::EMPTY_STRING; } } // ---------------------------- const InputSemantic::Semantic InputUnshared::getSemanticFromString ( const String& semanticStr ) { if ( COLLADABU::Utils::equalsIgnoreCase ( semanticStr, Constants::SEMANTIC_BINORMAL ) ) return InputSemantic::BINORMAL; if ( COLLADABU::Utils::equalsIgnoreCase ( semanticStr, Constants::SEMANTIC_COLOR ) ) return InputSemantic::COLOR; if ( COLLADABU::Utils::equalsIgnoreCase ( semanticStr, Constants::SEMANTIC_CONTINUITY ) ) return InputSemantic::CONTINUITY; if ( COLLADABU::Utils::equalsIgnoreCase ( semanticStr, Constants::SEMANTIC_IMAGE ) ) return InputSemantic::IMAGE; if ( COLLADABU::Utils::equalsIgnoreCase ( semanticStr, Constants::SEMANTIC_INPUT ) ) return InputSemantic::INPUT; if ( COLLADABU::Utils::equalsIgnoreCase ( semanticStr, Constants::SEMANTIC_IN_TANGENT ) ) return InputSemantic::IN_TANGENT; if ( COLLADABU::Utils::equalsIgnoreCase ( semanticStr, Constants::SEMANTIC_INTERPOLATION ) ) return InputSemantic::INTERPOLATION; if ( COLLADABU::Utils::equalsIgnoreCase ( semanticStr, Constants::SEMANTIC_INV_BIND_MATRIX ) ) return InputSemantic::INV_BIND_MATRIX; if ( COLLADABU::Utils::equalsIgnoreCase ( semanticStr, Constants::SEMANTIC_JOINT ) ) return InputSemantic::JOINT; if ( COLLADABU::Utils::equalsIgnoreCase ( semanticStr, Constants::SEMANTIC_LINEAR_STEPS ) ) return InputSemantic::LINEAR_STEPS; if ( COLLADABU::Utils::equalsIgnoreCase ( semanticStr, Constants::SEMANTIC_MORPH_TARGET ) ) return InputSemantic::MORPH_TARGET; if ( COLLADABU::Utils::equalsIgnoreCase ( semanticStr, Constants::SEMANTIC_MORPH_WEIGHT ) ) return InputSemantic::MORPH_WEIGHT; if ( COLLADABU::Utils::equalsIgnoreCase ( semanticStr, Constants::SEMANTIC_NORMAL ) ) return InputSemantic::NORMAL; if ( COLLADABU::Utils::equalsIgnoreCase ( semanticStr, Constants::SEMANTIC_OUTPUT ) ) return InputSemantic::OUTPUT; if ( COLLADABU::Utils::equalsIgnoreCase ( semanticStr, Constants::SEMANTIC_OUT_TANGENT ) ) return InputSemantic::OUT_TANGENT; if ( COLLADABU::Utils::equalsIgnoreCase ( semanticStr, Constants::SEMANTIC_POSITION ) ) return InputSemantic::POSITION; if ( COLLADABU::Utils::equalsIgnoreCase ( semanticStr, Constants::SEMANTIC_TANGENT ) ) return InputSemantic::TANGENT; if ( COLLADABU::Utils::equalsIgnoreCase ( semanticStr, Constants::SEMANTIC_TEXBINORMAL ) ) return InputSemantic::TEXBINORMAL; if ( COLLADABU::Utils::equalsIgnoreCase ( semanticStr, Constants::SEMANTIC_TEXCOORD ) ) return InputSemantic::TEXCOORD; if ( COLLADABU::Utils::equalsIgnoreCase ( semanticStr, Constants::SEMANTIC_TEXTANGENT ) ) return InputSemantic::TEXTANGENT; if ( COLLADABU::Utils::equalsIgnoreCase ( semanticStr, Constants::SEMANTIC_UV ) ) return InputSemantic::UV; if ( COLLADABU::Utils::equalsIgnoreCase ( semanticStr, Constants::SEMANTIC_VERTEX ) ) return InputSemantic::VERTEX; if ( COLLADABU::Utils::equalsIgnoreCase ( semanticStr, Constants::SEMANTIC_WEIGHT ) ) return InputSemantic::WEIGHT; return InputSemantic::UNKNOWN; } }
[ [ [ 1, 121 ] ] ]
c241862945fc16ffc4f91a8893b86797ca14c3b2
5fb9b06a4bf002fc851502717a020362b7d9d042
/developertools/GumpEditor/entity/GumpSliderPropertyPage.h
3b772b0d22c3a19c4a44ce5bdb9db66067a08732
[]
no_license
bravesoftdz/iris-svn
8f30b28773cf55ecf8951b982370854536d78870
c03438fcf59d9c788f6cb66b6cb9cf7235fbcbd4
refs/heads/master
2021-12-05T18:32:54.525624
2006-08-21T13:10:54
2006-08-21T13:10:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
769
h
#pragma once #include "DiagramPropertyPage.h" #include "numspinctrl.h" class CGumpSliderPropertyPage :public CDiagramPropertyPage { DECLARE_DYNAMIC(CGumpSliderPropertyPage) public: CGumpSliderPropertyPage(); virtual ~CGumpSliderPropertyPage(); enum { IDD = IDD_SLIDER_DIALOG }; virtual void SetValues(); virtual void ApplyValues(); virtual void ResetValues(); protected: virtual void DoDataExchange(CDataExchange* pDX); DECLARE_MESSAGE_MAP() public: BOOL m_bVertical; int m_iMin; int m_iMax; int m_iPos; CString m_strTrackID; CString m_strThumbID; CNumSpinCtrl m_spinMin; CNumSpinCtrl m_spinMax; CNumSpinCtrl m_spinPos; CNumSpinCtrl m_spinTrack; CNumSpinCtrl m_spinThumb; virtual BOOL OnInitDialog(); };
[ "sience@a725d9c3-d2eb-0310-b856-fa980ef11a19" ]
[ [ [ 1, 36 ] ] ]
5a53200e3a0f85374775cb667c7bc505f68e42d0
be2e23022d2eadb59a3ac3932180a1d9c9dee9c2
/GameServer/MapGroupKernel/MapGroup.cpp
178b05fe39439655923192376153fa25d5d0fcf7
[]
no_license
cronoszeu/revresyksgpr
78fa60d375718ef789042c452cca1c77c8fa098e
5a8f637e78f7d9e3e52acdd7abee63404de27e78
refs/heads/master
2020-04-16T17:33:10.793895
2010-06-16T12:52:45
2010-06-16T12:52:45
35,539,807
0
2
null
null
null
null
GB18030
C++
false
false
23,770
cpp
#include "MessagePort.h" #pragma warning(disable:4786) #include "AllMsg.h" #include "MapGroup.h" #pragma warning(disable:4786) #include "protocol.h" #include "itemtype.h" #include "MapManager.h" #include "ActionDefine.h" #include "WantedList.h" #include "DeadLoop.h" #include "NPC.h" //#include "DropRuleMap.h" //add by zlong 2003-11-15 //MYHEAP_IMPLEMENTATION(CMapGroup,s_heap) // 全局对象 CMapGroup::MAPGROUP_SET CMapGroup::m_setMapGroup; CItemType* g_pItemType = NULL; CDropRuleMap* g_pDropRuleMap = NULL; //add by zlong 2003-11-15 IStaticMapSet* g_setStaticMap = NULL; ITaskSet* g_setTask = NULL; IActionSet* g_setAction = NULL; ILevupexpSet* g_setLevupexp = NULL; IMagicTypeSet* g_setMagicType = NULL; IMagicTrackSet* g_setMagicTrack = NULL; IMagicTypeSet* g_setAutoMagicType = NULL; IAddPointSet* g_setAddPoint = NULL; ITrapTypeSet* g_setTrapType = NULL; IMonsterTypeSet* g_setMonsterType = NULL; IRebirthSet* g_setRebirth = NULL; CItemAddition* g_pItemAddition = NULL; CMapGroup::CMapGroup() { m_idProcess = NULL; m_pSocket = NULL; m_pDb = NULL; m_pMsgPort = NULL; m_pRoleManager = NULL; m_pUserManager = NULL; m_pMapManager = NULL; m_pNpcManager = NULL; m_pSynManager = NULL; m_pLeaveWord = NULL; m_pGameAction = NULL; m_pMercenaryTask= NULL; m_pAnnounce = NULL; } bool CMapGroup::Create(PROCESS_ID idProcess, ISocket* pSocket, IDatabase* pDb, IMessagePort* pMsgPort) { m_idProcess = idProcess; m_pSocket = pSocket; m_pDb = pDb; m_pMsgPort = pMsgPort; // 初始化所有DATA类的表结构。(注:所有要写盘的DATA类都需要在此初始化,并同时在Destroy()中清除。) char szSQL[11][1024]; sprintf(szSQL[0], "SELECT * FROM %s WHERE id=0 LIMIT 1", _TBL_ITEM); sprintf(szSQL[1], "SELECT * FROM %s WHERE id=0 LIMIT 1", _TBL_USER); sprintf(szSQL[2], "SELECT * FROM %s WHERE id=0 LIMIT 1", _TBL_MAP); sprintf(szSQL[3], "SELECT * FROM %s WHERE id=0 LIMIT 1", _TBL_WEAPONSKILL); sprintf(szSQL[4], "SELECT * FROM %s WHERE id=0 LIMIT 1", _TBL_MAGIC); sprintf(szSQL[5], "SELECT * FROM %s WHERE id=0 LIMIT 1", _TBL_SYNDICATE); sprintf(szSQL[6], "SELECT * FROM %s WHERE id=0 LIMIT 1", _TBL_SYNATTR); sprintf(szSQL[7], "SELECT * FROM %s WHERE id=0 LIMIT 1", _TBL_PET); sprintf(szSQL[8], "SELECT * FROM %s WHERE id=0 LIMIT 1", _TBL_DYNANPC); sprintf(szSQL[9], "SELECT * FROM %s WHERE id=0 LIMIT 1", _TBL_DYNAMAP); sprintf(szSQL[10], "SELECT * FROM %s WHERE id=0 LIMIT 1", _TBL_EUDEMON); m_pGameItemDataDefault = ::MapGroup(PID)->GetDatabase()->CreateNewRecordset(szSQL[0], false); m_pUserDataDefault = ::MapGroup(PID)->GetDatabase()->CreateNewRecordset(szSQL[1], false); m_pGameMapDataDefault = ::MapGroup(PID)->GetDatabase()->CreateNewRecordset(szSQL[2], false); m_pUserWeaponSkillDefault = ::MapGroup(PID)->GetDatabase()->CreateNewRecordset(szSQL[3], false); m_pMagicDataDefault = ::MapGroup(PID)->GetDatabase()->CreateNewRecordset(szSQL[4], false); m_pSynDataDefault = ::MapGroup(PID)->GetDatabase()->CreateNewRecordset(szSQL[5], false); m_pSynAttrDataDefault = ::MapGroup(PID)->GetDatabase()->CreateNewRecordset(szSQL[6], false); m_pPetDataDefault = ::MapGroup(PID)->GetDatabase()->CreateNewRecordset(szSQL[7], false); m_pDynaNpcDataDefault = ::MapGroup(PID)->GetDatabase()->CreateNewRecordset(szSQL[8], false); m_pDynaMapDataDefault = ::MapGroup(PID)->GetDatabase()->CreateNewRecordset(szSQL[9], false); m_pEudemonDataDefault = ::MapGroup(PID)->GetDatabase()->CreateNewRecordset(szSQL[10], false); if ( !m_pGameItemDataDefault ) { return false; } if ( !m_pUserDataDefault ) { return false; } if ( !m_pGameMapDataDefault ) { return false; } if ( !m_pUserWeaponSkillDefault ) { return false; } if ( !m_pMagicDataDefault ) { return false; } if ( !m_pSynDataDefault ) { return false; } if ( !m_pSynAttrDataDefault ) { return false; } if ( !m_pPetDataDefault ) { return false; } if ( !m_pDynaNpcDataDefault ) { return false; } if ( !m_pDynaMapDataDefault ) { return false; } if ( !m_pEudemonDataDefault ) { return false; } // 创建全局常量对象 if(m_idProcess == MSGPORT_MAPGROUP_FIRST) { g_pItemType = CItemType::CreateNew(); IF_NOT(g_pItemType && g_pItemType->Create(pDb)) return false; //add by zlong 2003-11-15 g_pDropRuleMap = CDropRuleMap::CreateNew(); IF_NOT(g_pDropRuleMap && g_pDropRuleMap->Create(pDb)) return false; char szSQL[1024]; sprintf(szSQL, "SELECT * FROM %s", _TBL_MAP); g_setStaticMap = CStaticMapSet::CreateNew(true); IF_NOT_(g_setStaticMap && g_setStaticMap->Create(szSQL, pDb)) return false; sprintf(szSQL, "SELECT * FROM %s", _TBL_TASK); g_setTask = CTaskSet::CreateNew(true); IF_NOT_(g_setTask && g_setTask->Create(szSQL, Database())) return false; sprintf(szSQL, "SELECT * FROM %s", _TBL_ACTION); g_setAction = CActionSet::CreateNew(true); IF_NOT_(g_setAction && g_setAction->Create(szSQL, Database())) return false; sprintf(szSQL, "SELECT * FROM %s", _TBL_LEVEXP); g_setLevupexp = CLevupexpSet::CreateNew(true); IF_NOT_(g_setLevupexp && g_setLevupexp->Create(szSQL, Database())) return false; sprintf(szSQL, "SELECT * FROM %s", _TBL_POINTALLOT); g_setAddPoint = CAddPointSet::CreateNew(true); IF_NOT_(g_setAddPoint && g_setAddPoint->Create(szSQL, Database())) return false; sprintf(szSQL, "SELECT * FROM %s", _TBL_TRACK); g_setMagicTrack = CMagicTrackSet::CreateNew(true); IF_NOT (g_setMagicTrack && g_setMagicTrack->Create(szSQL, Database())) return false; sprintf(szSQL, "SELECT * FROM %s", _TBL_MAGICTYPE); g_setMagicType = CMagicTypeSet::CreateNew(true); IF_NOT_(g_setMagicType && g_setMagicType->Create(szSQL, Database())) return false; sprintf(szSQL, "SELECT * FROM %s WHERE auto_learn!=0", _TBL_MAGICTYPE); g_setAutoMagicType = CMagicTypeSet::CreateNew(true); IF_NOT_(g_setAutoMagicType && g_setAutoMagicType->Create(szSQL, Database())) return false; IF_NOT(CWantedList::s_WantedList.Create(Database())) return false; sprintf(szSQL, "SELECT * FROM %s", _TBL_TRAPTYPE); g_setTrapType = CTrapTypeSet::CreateNew(true); IF_NOT_(g_setTrapType && g_setTrapType->Create(szSQL, Database())) return false; sprintf(szSQL, "SELECT * FROM %s", _TBL_MONSTERTYPE); g_setMonsterType = CMonsterTypeSet::CreateNew(true); IF_NOT_(g_setMonsterType && g_setMonsterType->Create(szSQL, Database())) return false; sprintf(szSQL, "SELECT * FROM %s", _TBL_REBIRTH); g_setRebirth = CRebirthSet::CreateNew(true); IF_NOT_(g_setRebirth && g_setRebirth->Create(szSQL, Database())) return false; g_pItemAddition = CItemAddition::CreateNew(); IF_NOT(g_pItemAddition && g_pItemAddition->Create(pDb)) return false; /* sprintf(szSQL, "DELETE FROM %s WHERE state = 2", _TBL_AUCTION);//LW每次起动服务器时删除已拍买过的物品 Database()->ExecuteSQL(szSQL);*/ } CMapManager* pMapManager = new CMapManager(m_idProcess); if (!pMapManager || !pMapManager->Create()) { ASSERT(!"pMapManager->Create"); return false; } m_pMapManager = pMapManager->GetInterface(); CRoleManager* pRoleManager = new CRoleManager(m_idProcess); if (!pRoleManager || !pRoleManager->Create()) { ASSERT(!"pRoleManager->Create"); return false; } m_pRoleManager = pRoleManager->GetInterface(); CUserManager* pUserManager = new CUserManager(m_idProcess); if (!pUserManager || !pUserManager->Create()) { ASSERT(!"pUserManager->Create"); return false; } m_pUserManager = pUserManager->GetInterface(); m_pSynManager = new CSynManager(m_idProcess); if (!m_pSynManager || !m_pSynManager->Create()) { ASSERT(!"m_pSynManager->Create"); return false; } CNpcManager* pNpcManager = new CNpcManager(m_idProcess); if (!pNpcManager || !pNpcManager->Create()) { ASSERT(!"pNpcManager->Create"); return false; } m_pNpcManager = pNpcManager->GetInterface(); m_pLeaveWord = new CLeaveWord(); if (!m_pLeaveWord || !m_pLeaveWord->Create(m_idProcess)) { ASSERT(!"m_pLeaveWord->Create"); return false; } m_pGameAction = CGameAction::CreateNew(m_idProcess); if (!m_pGameAction) { ASSERT(!"m_pGameAction->Create"); return false; } m_pMercenaryTask = CMercenaryTask::CreateNew(); IF_NOT(m_pMercenaryTask && m_pMercenaryTask->Create(m_idProcess)) return false; m_pAnnounce = CAnnounce::CreateNew(); if(!m_pAnnounce) { ASSERT(!"CAnnounce::CreateNew()"); return false; } #define INTERVAL_EVENT 60 // seconds m_tmEvent.Startup(INTERVAL_EVENT); return true; } void CMapGroup::Destroy() { S_REL (m_pMercenaryTask); S_REL (m_pGameAction); S_REL (m_pLeaveWord); S_REL (m_pNpcManager); S_REL (m_pUserManager); S_REL (m_pRoleManager); S_REL (m_pSynManager); S_REL (m_pMapManager); S_REL (m_pAnnounce); // 清除全局常量对象 if(m_idProcess == MSGPORT_MAPGROUP_FIRST) //@ 可能有问题 { CWantedList::s_WantedList.Release(); S_REL (g_setRebirth); S_REL (g_setMonsterType); S_REL (g_setTrapType); S_REL (g_setMagicTrack); S_REL (g_setAutoMagicType); S_REL (g_setMagicType); S_REL (g_setAddPoint); S_REL (g_setLevupexp); S_REL(g_setAction); S_REL(g_setTask); S_REL (g_setStaticMap); S_REL (g_pItemType); // add by zlong 2003-11-15 S_REL (g_pDropRuleMap); S_REL (g_pItemAddition); } S_REL (m_pEudemonDataDefault); S_REL (m_pDynaMapDataDefault); S_REL (m_pDynaNpcDataDefault); S_REL (m_pPetDataDefault); S_REL (m_pSynAttrDataDefault); S_REL (m_pSynDataDefault); S_REL (m_pMagicDataDefault); S_REL (m_pUserWeaponSkillDefault); S_REL (m_pGameItemDataDefault); S_REL (m_pUserDataDefault); S_REL (m_pGameMapDataDefault); } void CMapGroup::OnTimer(time_t tCurr) { DEBUG_TRY DEADLOOP_CHECK(PID, "RoleManager()->OnTimer") RoleManager()->OnTimer(tCurr); DEBUG_CATCH("RoleManager()->OnTimer(tCurr);") DEBUG_TRY DEADLOOP_CHECK(PID, "MapManager()->OnTimer") MapManager()->OnTimer(tCurr); DEBUG_CATCH("MapManager()->OnTimer(tCurr);") DEBUG_TRY DEADLOOP_CHECK(PID, "UserManager()->OnTimer") UserManager()->OnTimer(tCurr); DEBUG_CATCH("UserManager()->OnTimer(tCurr);") DEBUG_TRY DEADLOOP_CHECK(PID, "LeaveWord()->OnTimer") LeaveWord()->OnTimer(tCurr); DEBUG_CATCH("LeaveWord()->OnTimer(tCurr);") DEBUG_TRY DEADLOOP_CHECK(PID, "ProcessEvent") clock_t tStart = clock(); if (m_tmEvent.ToNextTime()) this->ProcessEvent(); clock_t tUsed = clock()-tStart; if(tUsed > 1000) ASSERT(!"EVENT定时任务超时!"); DEBUG_CATCH("ProcessEvent();") DEBUG_TRY DEADLOOP_CHECK(PID, "MercenaryTask()->OnTimer") MercenaryTask()->OnTimer(tCurr); DEBUG_CATCH("MercenaryTask()->Ontimer(tCurr);") } BOOL CMapGroup::CheckTime(const DWORD dwType, const char* pszParam) { if (!pszParam) return false; time_t ltime; time( &ltime ); struct tm *pTime; pTime = localtime( &ltime ); /* Convert to local time. */ int nCurYear, nCurMonth, nCurDay, nCurWeekDay, nCurYearDay, nCurHour, nCurMinute; nCurYear =pTime->tm_year+1900; nCurMonth =pTime->tm_mon+1; nCurDay =pTime->tm_mday; nCurWeekDay =pTime->tm_wday; nCurYearDay =pTime->tm_yday; nCurHour =pTime->tm_hour; nCurMinute =pTime->tm_min; int nYear0=0, nMonth0=0, nDay0=0, nHour0=0, nMinute0=0; int nYear1=0, nMonth1=0, nDay1=0, nHour1=0, nMinute1=0; if (dwType == 0) //精确时间 { if (10 == sscanf(pszParam, "%d-%d-%d %d:%d %d-%d-%d %d:%d", &nYear0, &nMonth0, &nDay0, &nHour0, &nMinute0, &nYear1, &nMonth1, &nDay1, &nHour1, &nMinute1)) { struct tm time0, time1; memset(&time0, 0L, sizeof(tm)); memset(&time1, 0L, sizeof(tm)); time0.tm_year =nYear0-1900; time0.tm_mon =nMonth0-1; time0.tm_mday =nDay0; time0.tm_hour =nHour0; time0.tm_min =nMinute0; time0.tm_isdst =pTime->tm_isdst; time1.tm_year =nYear1-1900; time1.tm_mon =nMonth1-1; time1.tm_mday =nDay1; time1.tm_hour =nHour1; time1.tm_min =nMinute1; time1.tm_isdst =pTime->tm_isdst; time_t t0 =mktime(&time0); time_t t1 =mktime(&time1); if (ltime >= t0 && ltime<= t1) return true; } } else if (dwType == 1) //年时间 { if (8 == sscanf(pszParam, "%d-%d %d:%d %d-%d %d:%d", &nMonth0, &nDay0, &nHour0, &nMinute0, &nMonth1, &nDay1, &nHour1, &nMinute1)) { struct tm time0, time1; memset(&time0, 0L, sizeof(tm)); memset(&time1, 0L, sizeof(tm)); time0.tm_year =pTime->tm_year; time0.tm_mon =nMonth0-1; time0.tm_mday =nDay0; time0.tm_hour =nHour0; time0.tm_min =nMinute0; time0.tm_isdst =pTime->tm_isdst; time1.tm_year =pTime->tm_year; time1.tm_mon =nMonth1-1; time1.tm_mday =nDay1; time1.tm_hour =nHour1; time1.tm_min =nMinute1; time1.tm_isdst =pTime->tm_isdst; time_t t0 =mktime(&time0); time_t t1 =mktime(&time1); if (ltime >= t0 && ltime<= t1) return true; } } else if (dwType == 2) //月时间 { if (6 == sscanf(pszParam, "%d %d:%d %d %d:%d", &nDay0, &nHour0, &nMinute0, &nDay1, &nHour1, &nMinute1)) { struct tm time0, time1; memset(&time0, 0L, sizeof(tm)); memset(&time1, 0L, sizeof(tm)); time0.tm_year =pTime->tm_year; time0.tm_mon =pTime->tm_mon; time0.tm_mday =nDay0; time0.tm_hour =nHour0; time0.tm_min =nMinute0; time0.tm_isdst =pTime->tm_isdst; time1.tm_year =pTime->tm_year; time1.tm_mon =pTime->tm_mon; time1.tm_mday =nDay1; time1.tm_hour =nHour1; time1.tm_min =nMinute1; time1.tm_isdst =pTime->tm_isdst; time_t t0 =mktime(&time0); time_t t1 =mktime(&time1); if (ltime >= t0 && ltime<= t1) return true; } } else if (dwType == 3) //周时间 { if (6 == sscanf(pszParam, "%d %d:%d %d %d:%d", &nDay0, &nHour0, &nMinute0, &nDay1, &nHour1, &nMinute1)) { DWORD timeNow =nCurWeekDay*24*60+nCurHour*60+nCurMinute; if (timeNow >= nDay0*24*60+nHour0*60+nMinute0 && timeNow <= nDay1*24*60+nHour1*60+nMinute1) { return true; } } } else if (dwType == 4) //日时间 { if (4 == sscanf(pszParam, "%d:%d %d:%d", &nHour0, &nMinute0, &nHour1, &nMinute1)) { DWORD timeNow =nCurHour*60+nCurMinute; if (timeNow >= nHour0*60+nMinute0 && timeNow <= nHour1*60+nMinute1) { return true; } } } else if (dwType == 5) //小时时间 { if (2 == sscanf(pszParam, "%d %d", &nMinute0, &nMinute1)) { if (nCurMinute >= nMinute0 && nCurMinute <= nMinute1) { return true; } } } return false; } void CMapGroup::ProcessEvent(void) { CONST OBJID ID_EVENT_BEGIN = 2000000; CONST DWORD MAX_EVENT = 100; OBJID idBegin = ID_EVENT_BEGIN+m_idProcess*10000; for (OBJID id=idBegin; id<idBegin+MAX_EVENT; id++) { //this->ProcessAction(id); if (ActionSet()->GetObj(id)) GameAction()->ProcessAction(id); } } bool CMapGroup::SendClientMsg(SOCKET_ID idSocket, Msg* pMsg) { //pMsg->AppendInfo(m_idProcess, idSocket, ID_NONE); return m_pSocket->SendClientMsg(idSocket, pMsg); } bool CMapGroup::SendNpcMsg(OBJID idNpc, Msg* pMsg) { //pMsg->AppendInfo(m_idProcess, SOCKET_NONE, idNpc); return m_pSocket->SendNpcMsg(idNpc, pMsg); } bool CMapGroup::SendBroadcastMsg(Msg* pMsg) { for(int i = MSGPORT_MAPGROUP_FIRST; i < m_pMsgPort->GetSize(); i++) { if(i != m_idProcess) // 不回送 { MESSAGESTR buf; CLIENTMSG_PACKET0* pPacket = (CLIENTMSG_PACKET0*)buf; pPacket->Create(0,pMsg); m_pMsgPort->Send(i, MAPGROUP_BROADCASTMSG, STRUCT_TYPE(buf), pPacket); } } return true; } // 广播给其它地图组核心处理 bool CMapGroup::TransmitMsg(Msg* pMsg, SOCKET_ID idSocket, OBJID idNpc) { ASSERT(idSocket != SOCKET_NONE || idNpc != ID_NONE); MESSAGESTR buf; TRANSMSG_PACKET0* pPacket = (TRANSMSG_PACKET0*)buf; pPacket->Create(idSocket, idNpc, pMsg->GetTransData(), pMsg); for(int i = MSGPORT_MAPGROUP_FIRST; i < m_pMsgPort->GetSize(); i++) { if(i != m_idProcess) // 不回送 m_pMsgPort->Send(i, MAPGROUP_TRANSMITMSG, STRUCT_TYPE(buf), pPacket); } return true; } // 广播给其它地图组核心处理 void CMapGroup::RemoteCall(REMOTE_CALL0* pInfo,bool bSendToLocal) { for(int i = MSGPORT_MAPGROUP_FIRST; i < m_pMsgPort->GetSize(); i++) { if (i != m_idProcess || bSendToLocal) m_pMsgPort->Send(i, MAPGROUP_REMOTECALL, BUFFER_TYPE(pInfo->nSize), pInfo); } } // 广播给世界核心处理 bool CMapGroup::TransmitWorldMsg(Msg* pMsg) { MESSAGESTR buf; TRANSMSG_PACKET0* pPacket = (TRANSMSG_PACKET0*)buf; pPacket->Create( 0/*pMsg->GetSocketID()*/, 0/*pMsg->GetNpcID()*/,pMsg->GetTransData(),pMsg); m_pMsgPort->Send(MSGPORT_WORLD, WORLD_TRANSMITMSG, STRUCT_TYPE(buf), pPacket); return true; } // 通过世界核心转发给玩家 bool CMapGroup::TransmitWorldMsgByName(SOCKET_ID idSocket, Msg* pMsg, LPCTSTR szName) { MESSAGESTR buf; USERNAMEMSG_PACKET0* pPacket = (USERNAMEMSG_PACKET0*)buf; pPacket->Create(idSocket, szName, pMsg); m_pMsgPort->Send(MSGPORT_WORLD, WORLD_USERNAMEMSG, STRUCT_TYPE(buf), pPacket); return true; } // 通过世界核心转发给玩家 bool CMapGroup::TransmitWorldMsgByUserID(Msg* pMsg, OBJID idUser) { MESSAGESTR buf; USERIDMSG_PACKET0* pPacket = (USERIDMSG_PACKET0*)buf; pPacket->Create( 0/*pMsg->GetSocketID()*/, idUser, pMsg); m_pMsgPort->Send(MSGPORT_WORLD, WORLD_USERIDMSG, STRUCT_TYPE(buf), pPacket); return true; } bool CMapGroup::SendSocketUserInfo(PROCESS_ID idProcess, SOCKET_ID idSocket, UserInfoStruct* pInfo) { // 通知另一地图组 MESSAGESTR buf; ST_USERCHANGEMAPGORUP* pPacket = (ST_USERCHANGEMAPGORUP*)buf; pPacket->idSocket = idSocket; memcpy(&pPacket->info, pInfo, sizeof(UserInfoStruct)); return m_pMsgPort->Send(idProcess, MAPGROUP_SOCKETUSERINFO, STRUCT_TYPE(ST_USERCHANGEMAPGORUP), &buf); } bool CMapGroup::SendObjInfo(PROCESS_ID idProcess, OBJID idUser, INFO_ID nInfoID, void* pInfo, int nSize) { CHECKF(nInfoID > INFO_NONE && nInfoID < 20); // 20 最多20种INFO MESSAGESTR buf; CHANGEMAPGORUP_INFO0* pPacket = (CHANGEMAPGORUP_INFO0*)buf; pPacket->idUser = idUser; pPacket->nInfoType = nInfoID; memcpy(&pPacket->info, pInfo, nSize); return m_pMsgPort->Send(idProcess, MAPGROUP_SENDOBJINFO, STRUCT_TYPE(buf), pPacket); } bool CMapGroup::SetNpcProcessID(OBJID idNpc, bool bAddNew) { CHANGE_NPCPROCESSID buf; buf.idNpc = idNpc; if(bAddNew) buf.idProcess = m_idProcess; else buf.idProcess = PROCESS_NONE; return m_pMsgPort->Send(MSGPORT_SOCKET, SOCKET_SETNPCPROCESSID, STRUCT_TYPE(CHANGE_NPCPROCESSID), &buf); } bool CMapGroup::ChangeMapGroup(PROCESS_ID idProcess, OBJID idUser, OBJID idMap, int nPosX, int nPosY) { ST_CHANGEMAPGROUP st; st.idUser = idUser; st.idMap = idMap; st.nPosX = nPosX; st.nPosY = nPosY; return m_pMsgPort->Send(idProcess, MAPGROUP_CHANGEMAPGROUP, STRUCT_TYPE(ST_CHANGEMAPGROUP), &st); } bool CMapGroup::PrintText (LPCTSTR szText) { return m_pMsgPort->Send(MSGPORT_SHELL, SHELL_PRINTTEXT, STRING_TYPE(szText), szText); } bool CMapGroup::CloseMapGroup(SOCKET_ID idGmSocket) // 关闭所有socket(除GM),禁止登录 { // TODO: 请在此添加关闭客户端SOCKET的代码 return m_pMsgPort->Send(MSGPORT_SOCKET, SOCKET_BREAKALLCONNECT, VARTYPE_INT, &idGmSocket); RoleManager()->SaveAll(); } bool CMapGroup::ChangeTeam(int nAction, OBJID idTeam, OBJID idUser, int nData) // 组队相关 { ST_CHANGETEAM st; st.nAction = nAction; st.idTeam = idTeam; st.idUser = idUser; st.nData = nData; for(int i = MSGPORT_MAPGROUP_FIRST; i < m_pMsgPort->GetSize(); i++) { if(i != m_idProcess) // 不回送 m_pMsgPort->Send(i, MAPGROUP_CHANGETEAM, STRUCT_TYPE(st), &st); } return true; } void CMapGroup::ModifyNpc(OBJID idNpc, LPCTSTR szField, LPCTSTR szData) { char buf[1024]; char* ptr = buf; *(int*)ptr = idNpc; ptr += sizeof(int); strcpy(ptr, szField); ptr = ptr + strlen(szField) + 1; strcpy(ptr, szData); ptr = ptr + strlen(szData) + 1; for(int i = MSGPORT_MAPGROUP_FIRST; i < m_pMsgPort->GetSize(); i++) { if(i != m_idProcess) // 不回送 m_pMsgPort->Send(i, MAPGROUP_CHANGENPC, BUFFER_TYPE(ptr - buf), buf); } } void CMapGroup::DelTransNpc(OBJID idMasterNpc, bool bBroadcast) { for(IRoleSet::Iter i = RoleManager()->QuerySet()->Begin(); i != RoleManager()->QuerySet()->End(); i++) { IRole* pRole = RoleManager()->QuerySet()->GetObjByIter(i); if(pRole) { CNpc* pNpc; if(pRole->QueryObj(OBJ_NPC, IPP_OF(pNpc))) { if(pNpc->GetType() == _SYNTRANS_NPC && pNpc->GetInt(NPCDATA_LINKID) == idMasterNpc) ASSERT(pNpc->DelNpc()); } } } if(bBroadcast) { for(int i = MSGPORT_MAPGROUP_FIRST; i < m_pMsgPort->GetSize(); i++) { if(i != m_idProcess) // 不回送 m_pMsgPort->Send(i, MAPGROUP_DELTRANSNPC, VARTYPE_INT, &idMasterNpc); } } } void CMapGroup::ChangeCode (SOCKET_ID idSocket, DWORD dwData) { CHANGE_USERDATA st; st.idSocket = idSocket; st.nData = dwData; m_pMsgPort->Send(MSGPORT_SOCKET, SOCKET_CHANGECODE, STRUCT_TYPE(CHANGE_USERDATA), &st); } void CMapGroup::SendRpc(const CEventPack& pack) { for(int i = MSGPORT_MAPGROUP_FIRST; i < m_pMsgPort->GetSize(); i++) { if(i != m_idProcess) // 不回送 m_pMsgPort->Send(i, MAPGROUP_RPC, BUFFER_TYPE(pack.GetSize()), pack.GetBuf()); } } // syndicate bool CMapGroup::CreateSyndicate (const CreateSyndicateInfo* pInfo) { return m_pMsgPort->Send(MSGPORT_WORLD, KERNEL_CREATESYNDICATE, STRUCT_TYPE(CreateSyndicateInfo), pInfo); } bool CMapGroup::DestroySyndicate(OBJID idSyn, OBJID idTarget) { OBJID setID[2]; setID[0] = idSyn; setID[1] = idTarget; return m_pMsgPort->Send(MSGPORT_WORLD, KERNEL_DESTROYSYNDICATE, STRUCT_TYPE(setID), &setID); } bool CMapGroup::CombineSyndicate(OBJID idSyn, OBJID idTarget) { OBJID setID[2]; setID[0] = idSyn; setID[1] = idTarget; return m_pMsgPort->Send(MSGPORT_WORLD, KERNEL_COMBINESYNDICATE, STRUCT_TYPE(setID), &setID); } bool CMapGroup::ChangeSyndicate (const SynFuncInfo0* pFuncInfo) { return m_pMsgPort->Send(MSGPORT_WORLD, KERNEL_CHANGESYNDICATE, BUFFER_TYPE(pFuncInfo->nSize), pFuncInfo); } void CMapGroup::SetMapSynID(OBJID idMap, OBJID idSyn) { OBJID setID[2]; setID[0] = idMap; setID[1] = idSyn; for(int i = MSGPORT_MAPGROUP_FIRST; i < m_pMsgPort->GetSize(); i++) { if(i != m_idProcess) // 不回送 m_pMsgPort->Send(i, MAPGROUP_SETMAPSYNID, STRUCT_TYPE(setID), &setID); } } int CMapGroup::GetMapGroupAmount() { CHECKF(m_pMsgPort); return m_pMsgPort->GetSize() - MSGPORT_MAPGROUP_FIRST + 1; } void CMapGroup::LevelUp (OBJID idUser, int nLevel) { m_pMsgPort->Send(MSGPORT_WORLD, WORLD_LEVELUP, VARTYPE_INT, &idUser); } void CMapGroup::QueryFee (OBJID idAccount) { m_pMsgPort->Send(MSGPORT_WORLD, WORLD_QUERYFEE, VARTYPE_INT, &idAccount); } //bool CMapGroup::TransmitWorldMsg(SOCKET_ID idSocket,Msg *pMsg) //{ // MESSAGESTR buf; // TRANSMSG_PACKET0* pPacket = (TRANSMSG_PACKET0*)buf; // pPacket->idSocket = idSocket; // pPacket->idNpc = pMsg->GetNpcID(); // pPacket->idPacket = pMsg->GetType(); // memcpy(pPacket->buf, pMsg, pMsg->GetSize()); // pPacket->nSize = pMsg->GetSize(); // pPacket->nTrans = pMsg->GetTransData(); // // m_pMsgPort->Send(MSGPORT_WORLD, WORLD_TRANSMITMSG, STRUCT_TYPE(buf), pPacket); // // return true; //}
[ "rpgsky.com@cc92e6ba-efcf-11de-bf31-4dec8810c1c1" ]
[ [ [ 1, 822 ] ] ]
13d3cefb949eb3a2c0fce020c62dfc19dc1f7db8
7b4c786d4258ce4421b1e7bcca9011d4eeb50083
/C++Primer中文版(第4版)/第一次-代码集合-20090414/第十二章 类/20090215_习题12.3_提供返回名字和地址的操作.hpp
37142a19c9dbdb78617d192ae8123721bdc02f41
[]
no_license
lzq123218/guoyishi-works
dbfa42a3e2d3bd4a984a5681e4335814657551ef
4e78c8f2e902589c3f06387374024225f52e5a92
refs/heads/master
2021-12-04T11:11:32.639076
2011-05-30T14:12:43
2011-05-30T14:12:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
315
hpp
class Person { public: Person (const std::string &nm, const std::string &addr): name(nm), address(addr) { } std::string getName() const { return name; } std::string getAddress() const { return address; } private: std::string name; std::string address; };
[ "baicaibang@70501136-4834-11de-8855-c187e5f49513" ]
[ [ [ 1, 21 ] ] ]
3086197a6f2d0e4a2d1138517148ae170631998f
26867688a923573593770ef4c25de34e975ff7cb
/mmokit/cpp/common/inc/singleton.h
6550984b15e86d90782ded849d01260b57730ff4
[]
no_license
JeffM2501/mmokit
2c2b873202324bd37d0bb2c46911dc254501e32b
9212bf548dc6818b364cf421778f6a36f037395c
refs/heads/master
2016-09-06T10:02:07.796899
2010-07-25T22:12:15
2010-07-25T22:12:15
32,234,709
1
0
null
null
null
null
UTF-8
C++
false
false
3,142
h
/* bzflag * Copyright (c) 1993 - 2004 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named LICENSE that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ #ifndef __SINGLETON_H__ #define __SINGLETON_H__ /* system headers */ #ifdef HAVE_ATEXIT # ifdef HAVE_CSTDLIB #include <cstdlib> using std::atexit; # else #include <stdlib.h> # endif #endif /* Singleton template class * * This template class pattern provides a traditional Singleton pattern. * Allows you to designate a single-instance global class by inheriting * off of the template class. * * Example: * * class Whatever : public Singleton<Whatever> ... * * The class will need to provide either a public or a protected friend * constructor: * * friend class Singleton<Whatever>; * * The class will also need to initialize it's own instance in a single * compilation unit (a .cxx file): * * // statically initialize the instance to nothing * template <> * Whatever* Singleton<Whatever>::_instance = 0; * * The class can easily be extended to support different allocation * mechanisms or multithreading access. This implementation, however, * only uses new/delete and is not thread safe. * * The Singleton will automatically get destroyed when the application * terminates (via an atexit() hook) unless the inheriting class has an * accessible destructor. */ template < typename T > class Singleton { private: static T* _instance; protected: // protection from instantiating a non-singleton Singleton Singleton() { } Singleton(T* pInstance) { _instance = pInstance; } Singleton(const Singleton &) { } // do not use Singleton& operator=(const Singleton&) { return *this; } // do not use ~Singleton() { _instance = 0; } // do not delete static void destroy() { if ( _instance != 0 ) { delete(_instance); _instance = 0; } } public: /** returns a singleton */ inline static T& instance() { if ( _instance == 0 ) { _instance = new T; // destroy the singleton when the application terminates #ifdef HAVE_ATEXIT atexit(Singleton::destroy); #endif } return *Singleton::_instance; } /** returns a singleton pointer */ inline static T* pInstance() { if (_instance == 0) { _instance = new T; #ifdef _WIN32 atexit(Singleton::destroy); #else std::atexit(Singleton::destroy); #endif } return Singleton::_instance; } /** returns a const singleton reference */ inline static const T& constInstance() { return *instance(); } }; #endif /* __SINGLETON_H__ */ // Local Variables: *** // mode: C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8
[ "JeffM2501@b8188ba6-572f-0410-9fd0-1f3cfbbf368d" ]
[ [ [ 1, 122 ] ] ]
01e890c511068ae1dc1d5d34e77fa51a750d0a45
00c36cc82b03bbf1af30606706891373d01b8dca
/OpenGUI/OpenGUI_Imagery.h
fee508a80ad91616713fa2d7fced0457ca32621c
[ "BSD-3-Clause" ]
permissive
VB6Hobbyst7/opengui
8fb84206b419399153e03223e59625757180702f
640be732a25129a1709873bd528866787476fa1a
refs/heads/master
2021-12-24T01:29:10.296596
2007-01-22T08:00:22
2007-01-22T08:00:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,920
h
// OpenGUI (http://opengui.sourceforge.net) // This source code is released under the BSD License // See LICENSE.TXT for details #ifndef DA3C55D9_F331_4cd8_9AAA_9354011F56C0 #define DA3C55D9_F331_4cd8_9AAA_9354011F56C0 #include "OpenGUI_PreRequisites.h" #include "OpenGUI_Exports.h" #include "OpenGUI_String.h" #include "OpenGUI_Types.h" #include "OpenGUI_RefPtr.h" #include "OpenGUI_Texture.h" namespace OpenGUI { class Texture; //forward declaration //! Defines a sub area of an Imageset. class OPENGUI_API Imagery { friend class __RefObj<Imagery>; //required for RefPtr to have access to destroy these objects friend class Imageset; public: //! Returns the FRect that defines the Texture UVs for this Imagery within the Imageset const FRect& getTextureUVRect() const; //! Returns the IRect that was used to define the Imagery within the Imageset /*!If the Imagery was created by defining UV coordinates, rather than a pixel based rect, then a pixel rect will be calculated based on the UVs. (This is mostly accurate, but not 100% perfect, so some error may occur.) */ const IRect& getImagesetRect() const; //! Returns a pointer to the Texture object for this Imagery's parent Imageset. TexturePtr getTexture() const; //! Returns the name of this Imagery object const String& getName() const; //! Returns the fully qualified name of this Imagery object const String& getFQN() const; private: Imagery( const String ImagesetName, const String Name, FRect areaRect, IRect nativeRect, TexturePtr texture ); ~Imagery(); String mFQN; String mName; FRect mAreaRect; IRect mNativeRect; TexturePtr mTexture; }; //! Reference counted, auto deleting Imagery pointer typedef RefPtr<Imagery> ImageryPtr; //! list of ImageryPtrs typedef std::list<ImageryPtr> ImageryPtrList; } ;//namespace OpenGUI{ #endif
[ "zeroskill@2828181b-9a0d-0410-a8fe-e25cbdd05f59" ]
[ [ [ 1, 59 ] ] ]
7ae7bbb57ca85ae2e0a413f8c1f83b36ba2e6b55
9ad9345e116ead00be7b3bd147a0f43144a2e402
/Integration_WAH_&_Extraction/SMDataExtraction/Algorithm/AlgoUtils.h
3b5901f082017018681cd2e852108030349bf7eb
[]
no_license
asankaf/scalable-data-mining-framework
e46999670a2317ee8d7814a4bd21f62d8f9f5c8f
811fddd97f52a203fdacd14c5753c3923d3a6498
refs/heads/master
2020-04-02T08:14:39.589079
2010-07-18T16:44:56
2010-07-18T16:44:56
33,870,353
0
0
null
null
null
null
UTF-8
C++
false
false
7,870
h
#ifndef _ALGOUTILS_H #define _ALGOUTILS_H #include "boost\dynamic_bitset\dynamic_bitset.hpp" #include <vector> #include <map> #include "EncodedAttributeInfo.h" #include "EncodedMultiCatAttribute.h" #include "WrapDataSource.h" #include <iostream> #include <math.h> #include "aprioriitemset.h" #include "associaterule.h" #include "BitStreamHolder.h" #include "smalgorithmexceptions.h" using namespace std; /************************************************************************ * Class :AlgoUtils * Author :Amila De Silva * Subj : * This class is a utility class. Provides widely used common algorithms * for main data mining algorithms. This class can be split to create * domain specific algorithms in future * Version: 1 ************************************************************************/ class AlgoUtils { public: _declspec(dllexport) AlgoUtils(void); _declspec(dllexport) ~AlgoUtils(void); /* * * Function for obtaining bit patterns for distinct values. Distinct values are obtained as bitsets * */ _declspec(dllexport) static vector<dynamic_bitset<>> GenerateUniqueValues(vector<string> & _string_map,int _no_of_bits); /**Finds the pattern defined by the _pattern from the BitStreams provided as BitStreamHolders*/ _declspec(dllexport) static BitStreamHolder * FindPattern(dynamic_bitset<> & _pattern,vector<BitStreamHolder *> & _container) throw (algorithm_exception); /**Finds the pattern defined by the _pattern from the BitStreams provided as BitStreamInfo objects*/ _declspec(dllexport) static BitStreamInfo * FindPattern(dynamic_bitset<> & _pattern,vector<BitStreamInfo *> & _container) throw (algorithm_exception); /**Finds the pattern defined by the _pattern from the BitStreams provided as dynamic_bitset*/ _declspec(dllexport) static dynamic_bitset<> FindPattern(dynamic_bitset<> & _pattern,vector<dynamic_bitset<>> & _container) throw (algorithm_exception); /**Finds the corresponding bitmaps of distinct values and return as a vector*/ _declspec(dllexport) static vector<BitStreamInfo *> FindDistinctValues(EncodedMultiCatAttribute * _attribute) throw(null_parameter_exception); /**Performs the AND operation and return the count*/ _declspec(dllexport) static double ANDCount(BitStreamInfo * left_op, BitStreamInfo * right_op) throw (algorithm_exception); /**Creates a BitStreamHolder with the given parameters*/ _declspec(dllexport) static BitStreamHolder * WrapWithHolder(BitStreamInfo * _stream,int _attribute_id,int _bit_map_id); /**Computes the sum of a numeric _attribute*/ _declspec(dllexport) static double USum(EncodedAttributeInfo * _attribute)throw (null_parameter_exception,incompatible_operand_exception); /**Computes the sum of a numeric _attribute sampled by the _existence bitmap*/ _declspec(dllexport) static double USum(EncodedAttributeInfo * _attribute, BitStreamInfo * _existence)throw (null_parameter_exception,incompatible_operand_exception); /**Computes the sum square of a numeric _attribute*/ _declspec(dllexport) static double SumSquare(EncodedAttributeInfo * _attribute) throw (null_parameter_exception,incompatible_operand_exception); /**Computes the sum square of a numeric _attribute sampled by the _existence bitmap*/ _declspec(dllexport) static double SumSquare(EncodedAttributeInfo * _attribute,BitStreamInfo * _existence) throw (null_parameter_exception,incompatible_operand_exception); /**Returns the bitmap of results greater than the given value*/ _declspec(dllexport) static BitStreamInfo * UGreaterThan(EncodedAttributeInfo * _attribute, double value,int _rows) throw(algorithm_exception); /**Returns the bitmap of results greater than or equal to the given value*/ _declspec(dllexport) static BitStreamInfo * UGreaterThanOrEq(EncodedAttributeInfo * _attribute, unsigned long value,int _rows); /**Returns the bitmap of results less than or equal to the given value*/ _declspec(dllexport) static BitStreamInfo * ULessThanOrEq(EncodedAttributeInfo * _attribute, unsigned long value,int _rows); /**Returns the bitmap of results less than the given value*/ _declspec(dllexport) static BitStreamInfo * ULessThan(EncodedAttributeInfo * _attribute, double value,int _rows); /**Returns the bitmap of results equal to the given value*/ _declspec(dllexport) static BitStreamInfo * UEq(EncodedAttributeInfo * _attribute, double value, int _rows); /**Generates a BitstreamInfo as same the type of attribute */ _declspec(dllexport) static BitStreamInfo * BitStreamGenerator(EncodedAttributeInfo * _attribute,dynamic_bitset<> & _bit_stream) throw (algorithm_exception); /** Function for calculating the variance of an attribute*/ _declspec(dllexport) static double Variance(EncodedAttributeInfo * _attribute,BitStreamInfo * _existence) throw (division_by_zero_exception); _declspec(dllexport) static map<int,int> CreateIndexAttributeMap(map<int,vector<int>> & _index_att_map); _declspec(dllexport) static void GetUniqueBitmaps(WrapDataSource * _source,vector<BitStreamHolder *> & _bitmaps,map<int,vector<int>> & _index_bitmap_map,vector<unsigned long int> & _pattern_index_map); _declspec(dllexport) static void GetUniqueBitmaps(EncodedAttributeInfo * _attribute,vector<BitStreamHolder *> & _bitmaps,vector<dynamic_bitset<>> & _unique_patterns,map<int,vector<int>> & _index_bitmap_map,vector<unsigned long int> & _pattern_index_map); _declspec(dllexport) static void CopyFirstToSecond(vector<BitStreamHolder *> & _left,vector<BitStreamHolder *> & _right); _declspec(dllexport) void PrintAprioriItemSets(vector<AprioriItemset *> _items); _declspec(dllexport) void PrintAprioriItemSets(vector<AprioriItemset *> _items, WrapDataSource * ws); _declspec(dllexport) void PrintAprioriItemSets(vector<vector<AprioriItemset *>> & _items, WrapDataSource * ws); _declspec(dllexport) void PrintHashMapVector(vector<hash_map<int, int>> & _map_vector); _declspec(dllexport) static void CopyFirstToSecond(vector<AssociateRule *> & _left,vector<AssociateRule *> & _right); _declspec(dllexport) void PrintHashMap(hash_map<int, int> & _hash_map); _declspec(dllexport) static void PrintRules(vector<AssociateRule *> & _rules); _declspec(dllexport) static void PrintRule(AssociateRule * _rule); private : static double SumOfInt(EncodedAttributeInfo * _attribute, BitStreamInfo * _existence); static double SumOfInt(EncodedAttributeInfo * _attribute); /**Handles the sum square obtaining function for int values*/ static double SumSquareOfInt(EncodedAttributeInfo * _attribute); /** Handles the sum square obtaining function for int values. The sample of which the sum is to be taken is given by the bitstream _existence */ static double SumSquareOfInt(EncodedAttributeInfo * _attribute,BitStreamInfo * _existence); /**Finds value greater than the given value (the given value should be unsigned)*/ static BitStreamInfo * UGreaterThanInt(EncodedAttributeInfo * _attribute,unsigned long _input_value,int _no_of_rows); /**Finds value greater than the given value (the given value should be unsigned)*/ static BitStreamInfo * UGreaterThanInt(EncodedAttributeInfo * _attribute,unsigned long long _input_value,int _no_of_rows,unsigned long long _max_value); /**Finds value less than the given value (the given value should be unsigned) @param attribute Numeric Attribute @param input_value upper limit of the range @param noOfRows No of _rows in the attribute */ static BitStreamInfo * ULessThanInt(EncodedAttributeInfo * _attribute,unsigned long long _input_value,int _no_of_rows,unsigned long long _max_value) throw(null_parameter_exception); }; #endif
[ "jaadds@c7f6ba40-6498-11de-987a-95e5a5a5d5f1" ]
[ [ [ 1, 144 ] ] ]
65590dbe4c49e0b4246d26be881019bc124aba5e
15469da4f39e1632c21ac81c52f91fff572368fc
/OpenCL/src/oclGPUProcessor/inc/GPUTransferManager.h
9028d632f69be7010fed2ec28576348d1f3d6e3b
[]
no_license
mateuszpruchniak/gpuprocessor
b855d47fdeaa28f0a2b5270fe7cd4232f1f4fbf9
9bdaf28e307b375cee3677ea7d1210b9ead88553
refs/heads/master
2020-05-02T19:07:37.264631
2010-11-22T12:42:47
2010-11-22T12:42:47
709,566
2
0
null
null
null
null
UTF-8
C++
false
false
2,725
h
/*! * \file GPUTransferManager.h * \brief File contains class responsible for managing transfer to GPU. * * \author Mateusz Pruchniak * \date 2010-05-05 */ #pragma once #include "oclUtils.h" #include <iostream> #include <vector> #include <string> #include "cv.h" #include "cxmisc.h" #include "highgui.h" #include <algorithm> #include <stdio.h> #include <ctype.h> #include <time.h> using namespace std; /*! * \class GPUTransferManager * \brief Class responsible for managing transfer between GPU and CPU. * \author Mateusz Pruchniak * \date 2010-05-05 */ class GPUTransferManager { private: /*! * Mapped Pointer to pinned Host input and output buffer for host processing. */ cl_uint* GPUInputOutput; /*! * OpenCL host memory input output buffer object: pinned. */ cl_mem cmPinnedBuf; /*! * The size in bytes of the buffer memory object to be allocated. */ size_t szBuffBytes; /*! * Error code, only 0 is allowed. */ cl_int GPUError; /*! * Image return from buffer. */ IplImage* image; public: /*! * OpenCL command-queue, is an object where OpenCL commands are enqueued to be executed by the device. */ cl_command_queue GPUCommandQueue; /*! * Context defines the entire OpenCL environment, including OpenCL kernels, devices, memory management, command-queues, etc. Contexts in OpenCL are referenced by an cl_context object */ cl_context GPUContext; /*! * OpenCL device memory input/output buffer object. */ cl_mem cmDevBuf; /*! * Image width. */ unsigned int ImageWidth; /*! * Image height. */ unsigned int ImageHeight; /*! * Number of color channels. */ int nChannels; /*! * Destructor. Release buffers. */ ~GPUTransferManager(); /*! * Constructor. Allocate pinned and mapped memory for input and output host image buffers. */ GPUTransferManager( cl_context , cl_command_queue , unsigned int , unsigned int, int nChannels ); /*! * Default Constructor. */ GPUTransferManager(); /*! * Send image to GPU memory. */ void SendImage( IplImage* ); /*! * Get image from GPU memory. */ IplImage* ReceiveImage(); /*! * Release all buffors. */ void Cleanup(); /*! * Check error code. */ void CheckError(int ); };
[ "mateusz@ubuntu.(none)" ]
[ [ [ 1, 132 ] ] ]
953b8584673494c05273d75825766a4af41c9c85
3e69b159d352a57a48bc483cb8ca802b49679d65
/tags/release-2006-01-16/cvpcb/class_cvpcb.cpp
25a455a5062d2835b6ccd7fc56e99adb60bee033
[]
no_license
BackupTheBerlios/kicad-svn
4b79bc0af39d6e5cb0f07556eb781a83e8a464b9
4c97bbde4b1b12ec5616a57c17298c77a9790398
refs/heads/master
2021-01-01T19:38:40.000652
2006-06-19T20:01:24
2006-06-19T20:01:24
40,799,911
0
0
null
null
null
null
UTF-8
C++
false
false
1,133
cpp
/*******************/ /* class_cvpcb.cpp */ /*******************/ // For compilers that support precompilation, includes "wx.h". #include "wx/wxprec.h" #ifdef __BORLANDC__ #pragma hdrstop #endif // for all others, include the necessary headers (this file is usually all you // need because it includes almost all "standard" wxWindows headers #ifndef WX_PRECOMP #include <wx/wx.h> #endif #include "fctsys.h" #include "common.h" #include "cvpcb.h" STORECMP::STORECMP(void) { Pnext = Pback = NULL; m_Type = STRUCT_COMPONENT; m_Pins = NULL; m_Num = 0; m_Multi = 0; } STORECMP::~STORECMP(void) { STOREPIN * Pin, * NextPin; for( Pin = m_Pins; Pin != NULL; Pin = NextPin ) { NextPin = Pin->Pnext; delete Pin; } } STOREMOD::STOREMOD(void) { Pnext = Pback = NULL; m_Type = STRUCT_MODULE; m_Num = 0; } STOREPIN::STOREPIN(void) { m_Type = STRUCT_PIN; /* Type de la structure */ Pnext = NULL; /* Chainage avant */ m_Index = 0; /* variable utilisee selon types de netlistes */ m_PinType = 0; /* code type electrique ( Entree Sortie Passive..) */ }
[ "bokeoa@244deca0-f506-0410-ab94-f4f3571dea26" ]
[ [ [ 1, 59 ] ] ]
59f76ee4a940b3b272f89a0639f3f7cbd857e0c7
df5277b77ad258cc5d3da348b5986294b055a2be
/GameEngineV0.35/Source/Threading.cpp
6fbf9327cc3e27f547fe8d47b3f27d59ae2c4901
[]
no_license
beentaken/cs260-last2
147eaeb1ab15d03c57ad7fdc5db2d4e0824c0c22
61b2f84d565cc94a0283cc14c40fb52189ec1ba5
refs/heads/master
2021-03-20T16:27:10.552333
2010-04-26T00:47:13
2010-04-26T00:47:13
null
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
8,631
cpp
/**************************************************************************************************/ /*! @file Threading.hpp @author Robert Onulak @author Justin Keane @par email: robert.onulak@@digipen.edu @par email: justin.keane@@digipen.edu @par Course: CS260 @par Assignment #3 ---------------------------------------------------------------------------------------------------- @attention © Copyright 2010: DigiPen Institute of Technology (USA). All Rights Reserved. */ /**************************************************************************************************/ #include "Precompiled.h" #include "Threading.hpp" #include <iostream> //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////// // Mutex Public Methods /**************************************************************************************************/ /**************************************************************************************************/ Mutex::Mutex( void ) { InitializeCriticalSection( &criticalSection_ ); } /**************************************************************************************************/ /**************************************************************************************************/ Mutex::~Mutex( void ) throw() { DeleteCriticalSection( &criticalSection_ ); } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////// // Mutex Private Methods /**************************************************************************************************/ /**************************************************************************************************/ void Mutex::Acquire( void ) { EnterCriticalSection( &criticalSection_ ); } /**************************************************************************************************/ /**************************************************************************************************/ void Mutex::Release( void ) { LeaveCriticalSection( &criticalSection_ ); } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////// // Lock Methods /**************************************************************************************************/ /**************************************************************************************************/ Lock::Lock( Mutex &mutex ) : mutex_(mutex) { mutex_.Acquire(); } /**************************************************************************************************/ /**************************************************************************************************/ Lock::~Lock( void ) throw() { mutex_.Release(); } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////// // Event Methods /**************************************************************************************************/ /**************************************************************************************************/ Event::Event( void ) { // Create a event in a non-signaled state. (red state) handle_ = CreateEvent( NULL, FALSE, FALSE, NULL ); } /**************************************************************************************************/ /**************************************************************************************************/ Event::~Event( void ) throw() { CloseHandle( handle_ ); } /**************************************************************************************************/ /**************************************************************************************************/ void Event::Release( void ) { // Put this event into a signled state. SetEvent( handle_ ); } /**************************************************************************************************/ /**************************************************************************************************/ DWORD Event::Wait( DWORD milliseconds ) { // Wait until this event is in signaled (green) state. return WaitForSingleObject( handle_, milliseconds ); } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////// // Thread Methods /**************************************************************************************************/ /**************************************************************************************************/ Thread::Thread( Routine fn, void *arg ) : running(false) { attributes_.nLength = sizeof(SECURITY_ATTRIBUTES); attributes_.lpSecurityDescriptor = NULL; attributes_.bInheritHandle = FALSE; handle_ = CreateThread( &attributes_, 0, fn, arg, CREATE_SUSPENDED, &id_ ); } /**************************************************************************************************/ /**************************************************************************************************/ Thread::~Thread( void ) throw() { CloseHandle( handle_ ); } /**************************************************************************************************/ /**************************************************************************************************/ void Thread::Resume( void ) { running = true; ResumeThread( handle_ ); } /**************************************************************************************************/ /**************************************************************************************************/ void Thread::WaitForDeath( void ) { running = false; WaitForSingleObject( handle_, INFINITE ); } /**************************************************************************************************/ /**************************************************************************************************/ bool Thread::Terminate( void ) { return TerminateThread( handle_, -1 ) ? true : false; } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////// // RoutineObject Methods /**************************************************************************************************/ /**************************************************************************************************/ RoutineObject::RoutineObject( void ) : dying_(0), // Passing our RoutineObject to our thread before it is constructed. It is not a flaw because we // start our thread's suspended, therefore the thread will use this object at some point after this // object is created. #pragma warning( disable : 4355 ) // 'this' : used in base member initializer list thread_( RoutineObject::Routine, this ) #pragma warning( default : 4355 ) { } /**************************************************************************************************/ /**************************************************************************************************/ void RoutineObject::Kill( void ) { ++dying_; FlushThread(); thread_.WaitForDeath(); } /**************************************************************************************************/ /**************************************************************************************************/ DWORD WINAPI RoutineObject::Routine( void *arg ) { // Collect our Routine, then run the Routine until the object is finished. RoutineObject *object = reinterpret_cast<RoutineObject*>(arg); // Announce that we are starting a particular thread and the id of that thread. //std::cout << "Starting thread: " << object->thread_.id_ << std::endl; try { object->InitializeThread(); object->Run(); } catch ( const std::exception &e ) { std::cerr << "Exception caught: " << e.what() << std::endl; } catch ( ... ) { std::cerr << "Unknown error occured." << std::endl; } //std::cout << "Thread exiting: " << object->thread_.id_ << std::endl; object->ExitThread(); return 0; }
[ "ProstheticMind43@af704e40-745a-32bd-e5ce-d8b418a3b9ef", "westleyargentum@af704e40-745a-32bd-e5ce-d8b418a3b9ef" ]
[ [ [ 1, 182 ], [ 184, 210 ] ], [ [ 183, 183 ] ] ]
0e5c7896d1afa0cb38c714d68f30c1faf3df6afe
12732dc8a5dd518f35c8af3f2a805806f5e91e28
/trunk/LiteEditor/setters_getters_dlg.h
7da9d738c846688ac2a698cc2c23c8d12c5cb47f
[]
no_license
BackupTheBerlios/codelite-svn
5acd9ac51fdd0663742f69084fc91a213b24ae5c
c9efd7873960706a8ce23cde31a701520bad8861
refs/heads/master
2020-05-20T13:22:34.635394
2007-08-02T21:35:35
2007-08-02T21:35:35
40,669,327
0
0
null
null
null
null
UTF-8
C++
false
false
1,128
h
#ifndef __setters_getters_dlg__ #define __setters_getters_dlg__ /** @file Subclass of SettersGettersBaseDlg, which is generated by wxFormBuilder. @todo Add your event handlers directly to this file. */ #include "setters_getters_base_dlg.h" #include "manager.h" #include "ctags_manager.h" /** Implementing SettersGettersBaseDlg */ class SettersGettersDlg : public SettersGettersBaseDlg { std::vector<TagEntryPtr> m_members; wxFileName m_file; int m_lineno; std::map<wxString, TagEntryPtr> m_tagsMap; wxString m_code; protected: void OnCheckStartWithUpperCase(wxCommandEvent &event); wxString GenerateFunctions(); wxString GenerateSetter(TagEntryPtr tag); wxString GenerateGetter(TagEntryPtr tag); void FormatName(wxString &name); void UpdatePreview(); void GenerateGetters(wxString &code); void GenerateSetters(wxString &code); public: /** Constructor */ SettersGettersDlg(wxWindow* parent); const wxString &GetGenCode() const {return m_code;} void Init(const std::vector<TagEntryPtr> &tags, const wxFileName &file, int lineno); }; #endif // __setters_getters_dlg__
[ "eranif@b1f272c1-3a1e-0410-8d64-bdc0ffbdec4b" ]
[ [ [ 1, 40 ] ] ]
e63c46919f435c6b616ca36f1e4b6d4a3ee16ea0
5ac13fa1746046451f1989b5b8734f40d6445322
/minimangalore/Nebula2/code/contrib/nbsptool/src/nbsptool/libs/jpeg/jdcoefct.cc
88a5a74f961479726a6cc2822953f2a3e83cbed1
[]
no_license
moltenguy1/minimangalore
9f2edf7901e7392490cc22486a7cf13c1790008d
4d849672a6f25d8e441245d374b6bde4b59cbd48
refs/heads/master
2020-04-23T08:57:16.492734
2009-08-01T09:13:33
2009-08-01T09:13:33
35,933,330
0
0
null
null
null
null
UTF-8
C++
false
false
26,226
cc
/* * jdcoefct.c * * Copyright (C) 1994-1995, Thomas G. Lane. * This file is part of the Independent JPEG Group's software. * For conditions of distribution and use, see the accompanying README file. * * This file contains the coefficient buffer controller for decompression. * This controller is the top level of the JPEG decompressor proper. * The coefficient buffer lies between entropy decoding and inverse-DCT steps. * * In buffered-image mode, this controller is the interface between * input-oriented processing and output-oriented processing. * Also, the input side (only) is used when reading a file for transcoding. */ #define JPEG_INTERNALS #include "nbsptool/libs/jpeg/jinclude.h" #include "nbsptool/libs/jpeg/jpeglib.h" /* Block smoothing is only applicable for progressive JPEG, so: */ #ifndef D_PROGRESSIVE_SUPPORTED #undef BLOCK_SMOOTHING_SUPPORTED #endif /* Private buffer controller object */ typedef struct { struct jpeg_d_coef_controller pub; /* public fields */ /* These variables keep track of the current location of the input side. */ /* cinfo->input_iMCU_row is also used for this. */ JDIMENSION MCU_ctr; /* counts MCUs processed in current row */ int MCU_vert_offset; /* counts MCU rows within iMCU row */ int MCU_rows_per_iMCU_row; /* number of such rows needed */ /* The output side's location is represented by cinfo->output_iMCU_row. */ /* In single-pass modes, it's sufficient to buffer just one MCU. * We allocate a workspace of D_MAX_BLOCKS_IN_MCU coefficient blocks, * and let the entropy decoder write into that workspace each time. * (On 80x86, the workspace is FAR even though it's not really very big; * this is to keep the module interfaces unchanged when a large coefficient * buffer is necessary.) * In multi-pass modes, this array points to the current MCU's blocks * within the virtual arrays; it is used only by the input side. */ JBLOCKROW MCU_buffer[D_MAX_BLOCKS_IN_MCU]; #ifdef D_MULTISCAN_FILES_SUPPORTED /* In multi-pass modes, we need a virtual block array for each component. */ jvirt_barray_ptr whole_image[MAX_COMPONENTS]; #endif #ifdef BLOCK_SMOOTHING_SUPPORTED /* When doing block smoothing, we latch coefficient Al values here */ int * coef_bits_latch; #define SAVED_COEFS 6 /* we save coef_bits[0..5] */ #endif } my_coef_controller; typedef my_coef_controller * my_coef_ptr; /* Forward declarations */ METHODDEF int decompress_onepass JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf)); #ifdef D_MULTISCAN_FILES_SUPPORTED METHODDEF int decompress_data JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf)); #endif #ifdef BLOCK_SMOOTHING_SUPPORTED LOCAL boolean smoothing_ok JPP((j_decompress_ptr cinfo)); METHODDEF int decompress_smooth_data JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf)); #endif LOCAL void start_iMCU_row (j_decompress_ptr cinfo) /* Reset within-iMCU-row counters for a new row (input side) */ { my_coef_ptr coef = (my_coef_ptr) cinfo->coef; /* In an interleaved scan, an MCU row is the same as an iMCU row. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows. * But at the bottom of the image, process only what's left. */ if (cinfo->comps_in_scan > 1) { coef->MCU_rows_per_iMCU_row = 1; } else { if (cinfo->input_iMCU_row < (cinfo->total_iMCU_rows-1)) coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor; else coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height; } coef->MCU_ctr = 0; coef->MCU_vert_offset = 0; } /* * Initialize for an input processing pass. */ METHODDEF void start_input_pass (j_decompress_ptr cinfo) { cinfo->input_iMCU_row = 0; start_iMCU_row(cinfo); } /* * Initialize for an output processing pass. */ METHODDEF void start_output_pass (j_decompress_ptr cinfo) { #ifdef BLOCK_SMOOTHING_SUPPORTED my_coef_ptr coef = (my_coef_ptr) cinfo->coef; /* If multipass, check to see whether to use block smoothing on this pass */ if (coef->pub.coef_arrays != NULL) { if (cinfo->do_block_smoothing && smoothing_ok(cinfo)) coef->pub.decompress_data = decompress_smooth_data; else coef->pub.decompress_data = decompress_data; } #endif cinfo->output_iMCU_row = 0; } /* * Decompress and return some data in the single-pass case. * Always attempts to emit one fully interleaved MCU row ("iMCU" row). * Input and output must run in lockstep since we have only a one-MCU buffer. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED. * * NB: output_buf contains a plane for each component in image. * For single pass, this is the same as the components in the scan. */ METHODDEF int decompress_onepass (j_decompress_ptr cinfo, JSAMPIMAGE output_buf) { my_coef_ptr coef = (my_coef_ptr) cinfo->coef; JDIMENSION MCU_col_num; /* index of current MCU within row */ JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1; JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1; int blkn, ci, xindex, yindex, yoffset, useful_width; JSAMPARRAY output_ptr; JDIMENSION start_col, output_col; jpeg_component_info *compptr; inverse_DCT_method_ptr inverse_DCT; /* Loop to process as much as one whole iMCU row */ for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row; yoffset++) { for (MCU_col_num = coef->MCU_ctr; MCU_col_num <= last_MCU_col; MCU_col_num++) { /* Try to fetch an MCU. Entropy decoder expects buffer to be zeroed. */ jzero_far((void FAR *) coef->MCU_buffer[0], (size_t) (cinfo->blocks_in_MCU * SIZEOF(JBLOCK))); if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) { /* Suspension forced; update state counters and exit */ coef->MCU_vert_offset = yoffset; coef->MCU_ctr = MCU_col_num; return JPEG_SUSPENDED; } /* Determine where data should go in output_buf and do the IDCT thing. * We skip dummy blocks at the right and bottom edges (but blkn gets * incremented past them!). Note the inner loop relies on having * allocated the MCU_buffer[] blocks sequentially. */ blkn = 0; /* index of current DCT block within MCU */ for (ci = 0; ci < cinfo->comps_in_scan; ci++) { compptr = cinfo->cur_comp_info[ci]; /* Don't bother to IDCT an uninteresting component. */ if (! compptr->component_needed) { blkn += compptr->MCU_blocks; continue; } inverse_DCT = cinfo->idct->inverse_DCT[compptr->component_index]; useful_width = (MCU_col_num < last_MCU_col) ? compptr->MCU_width : compptr->last_col_width; output_ptr = output_buf[ci] + yoffset * compptr->DCT_scaled_size; start_col = MCU_col_num * compptr->MCU_sample_width; for (yindex = 0; yindex < compptr->MCU_height; yindex++) { if (cinfo->input_iMCU_row < last_iMCU_row || yoffset+yindex < compptr->last_row_height) { output_col = start_col; for (xindex = 0; xindex < useful_width; xindex++) { (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) coef->MCU_buffer[blkn+xindex], output_ptr, output_col); output_col += compptr->DCT_scaled_size; } } blkn += compptr->MCU_width; output_ptr += compptr->DCT_scaled_size; } } } /* Completed an MCU row, but perhaps not an iMCU row */ coef->MCU_ctr = 0; } /* Completed the iMCU row, advance counters for next one */ cinfo->output_iMCU_row++; if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) { start_iMCU_row(cinfo); return JPEG_ROW_COMPLETED; } /* Completed the scan */ (*cinfo->inputctl->finish_input_pass) (cinfo); return JPEG_SCAN_COMPLETED; } /* * Dummy consume-input routine for single-pass operation. */ METHODDEF int dummy_consume_data (j_decompress_ptr cinfo) { return JPEG_SUSPENDED; /* Always indicate nothing was done */ } #ifdef D_MULTISCAN_FILES_SUPPORTED /* * Consume input data and store it in the full-image coefficient buffer. * We read as much as one fully interleaved MCU row ("iMCU" row) per call, * ie, v_samp_factor block rows for each component in the scan. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED. */ METHODDEF int consume_data (j_decompress_ptr cinfo) { my_coef_ptr coef = (my_coef_ptr) cinfo->coef; JDIMENSION MCU_col_num; /* index of current MCU within row */ int blkn, ci, xindex, yindex, yoffset; JDIMENSION start_col; JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN]; JBLOCKROW buffer_ptr; jpeg_component_info *compptr; /* Align the virtual buffers for the components used in this scan. */ for (ci = 0; ci < cinfo->comps_in_scan; ci++) { compptr = cinfo->cur_comp_info[ci]; buffer[ci] = (*cinfo->mem->access_virt_barray) ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index], cinfo->input_iMCU_row * compptr->v_samp_factor, (JDIMENSION) compptr->v_samp_factor, TRUE); /* Note: entropy decoder expects buffer to be zeroed, * but this is handled automatically by the memory manager * because we requested a pre-zeroed array. */ } /* Loop to process one whole iMCU row */ for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row; yoffset++) { for (MCU_col_num = coef->MCU_ctr; MCU_col_num < cinfo->MCUs_per_row; MCU_col_num++) { /* Construct list of pointers to DCT blocks belonging to this MCU */ blkn = 0; /* index of current DCT block within MCU */ for (ci = 0; ci < cinfo->comps_in_scan; ci++) { compptr = cinfo->cur_comp_info[ci]; start_col = MCU_col_num * compptr->MCU_width; for (yindex = 0; yindex < compptr->MCU_height; yindex++) { buffer_ptr = buffer[ci][yindex+yoffset] + start_col; for (xindex = 0; xindex < compptr->MCU_width; xindex++) { coef->MCU_buffer[blkn++] = buffer_ptr++; } } } /* Try to fetch the MCU. */ if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) { /* Suspension forced; update state counters and exit */ coef->MCU_vert_offset = yoffset; coef->MCU_ctr = MCU_col_num; return JPEG_SUSPENDED; } } /* Completed an MCU row, but perhaps not an iMCU row */ coef->MCU_ctr = 0; } /* Completed the iMCU row, advance counters for next one */ if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) { start_iMCU_row(cinfo); return JPEG_ROW_COMPLETED; } /* Completed the scan */ (*cinfo->inputctl->finish_input_pass) (cinfo); return JPEG_SCAN_COMPLETED; } /* * Decompress and return some data in the multi-pass case. * Always attempts to emit one fully interleaved MCU row ("iMCU" row). * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED. * * NB: output_buf contains a plane for each component in image. */ METHODDEF int decompress_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf) { my_coef_ptr coef = (my_coef_ptr) cinfo->coef; JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1; JDIMENSION block_num; int ci, block_row, block_rows; JBLOCKARRAY buffer; JBLOCKROW buffer_ptr; JSAMPARRAY output_ptr; JDIMENSION output_col; jpeg_component_info *compptr; inverse_DCT_method_ptr inverse_DCT; /* Force some input to be done if we are getting ahead of the input. */ while (cinfo->input_scan_number < cinfo->output_scan_number || (cinfo->input_scan_number == cinfo->output_scan_number && cinfo->input_iMCU_row <= cinfo->output_iMCU_row)) { if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED) return JPEG_SUSPENDED; } /* OK, output from the virtual arrays. */ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; ci++, compptr++) { /* Don't bother to IDCT an uninteresting component. */ if (! compptr->component_needed) continue; /* Align the virtual buffer for this component. */ buffer = (*cinfo->mem->access_virt_barray) ((j_common_ptr) cinfo, coef->whole_image[ci], cinfo->output_iMCU_row * compptr->v_samp_factor, (JDIMENSION) compptr->v_samp_factor, FALSE); /* Count non-dummy DCT block rows in this iMCU row. */ if (cinfo->output_iMCU_row < last_iMCU_row) block_rows = compptr->v_samp_factor; else { /* NB: can't use last_row_height here; it is input-side-dependent! */ block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor); if (block_rows == 0) block_rows = compptr->v_samp_factor; } inverse_DCT = cinfo->idct->inverse_DCT[ci]; output_ptr = output_buf[ci]; /* Loop over all DCT blocks to be processed. */ for (block_row = 0; block_row < block_rows; block_row++) { buffer_ptr = buffer[block_row]; output_col = 0; for (block_num = 0; block_num < compptr->width_in_blocks; block_num++) { (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) buffer_ptr, output_ptr, output_col); buffer_ptr++; output_col += compptr->DCT_scaled_size; } output_ptr += compptr->DCT_scaled_size; } } if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows) return JPEG_ROW_COMPLETED; return JPEG_SCAN_COMPLETED; } #endif /* D_MULTISCAN_FILES_SUPPORTED */ #ifdef BLOCK_SMOOTHING_SUPPORTED /* * This code applies interblock smoothing as described by section K.8 * of the JPEG standard: the first 5 AC coefficients are estimated from * the DC values of a DCT block and its 8 neighboring blocks. * We apply smoothing only for progressive JPEG decoding, and only if * the coefficients it can estimate are not yet known to full precision. */ /* * Determine whether block smoothing is applicable and safe. * We also latch the current states of the coef_bits[] entries for the * AC coefficients; otherwise, if the input side of the decompressor * advances into a new scan, we might think the coefficients are known * more accurately than they really are. */ LOCAL boolean smoothing_ok (j_decompress_ptr cinfo) { my_coef_ptr coef = (my_coef_ptr) cinfo->coef; boolean smoothing_useful = FALSE; int ci, coefi; jpeg_component_info *compptr; JQUANT_TBL * qtable; int * coef_bits; int * coef_bits_latch; if (! cinfo->progressive_mode || cinfo->coef_bits == NULL) return FALSE; /* Allocate latch area if not already done */ if (coef->coef_bits_latch == NULL) coef->coef_bits_latch = (int *) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, cinfo->num_components * (SAVED_COEFS * SIZEOF(int))); coef_bits_latch = coef->coef_bits_latch; for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; ci++, compptr++) { /* All components' quantization values must already be latched. */ if ((qtable = compptr->quant_table) == NULL) return FALSE; /* Verify DC & first 5 AC quantizers are nonzero to avoid zero-divide. */ for (coefi = 0; coefi <= 5; coefi++) { if (qtable->quantval[coefi] == 0) return FALSE; } /* DC values must be at least partly known for all components. */ coef_bits = cinfo->coef_bits[ci]; if (coef_bits[0] < 0) return FALSE; /* Block smoothing is helpful if some AC coefficients remain inaccurate. */ for (coefi = 1; coefi <= 5; coefi++) { coef_bits_latch[coefi] = coef_bits[coefi]; if (coef_bits[coefi] != 0) smoothing_useful = TRUE; } coef_bits_latch += SAVED_COEFS; } return smoothing_useful; } /* * Variant of decompress_data for use when doing block smoothing. */ METHODDEF int decompress_smooth_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf) { my_coef_ptr coef = (my_coef_ptr) cinfo->coef; JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1; JDIMENSION block_num, last_block_column; int ci, block_row, block_rows, access_rows; JBLOCKARRAY buffer; JBLOCKROW buffer_ptr, prev_block_row, next_block_row; JSAMPARRAY output_ptr; JDIMENSION output_col; jpeg_component_info *compptr; inverse_DCT_method_ptr inverse_DCT; boolean first_row, last_row; JBLOCK workspace; int *coef_bits; JQUANT_TBL *quanttbl; INT32 Q00,Q01,Q02,Q10,Q11,Q20, num; int DC1,DC2,DC3,DC4,DC5,DC6,DC7,DC8,DC9; int Al, pred; /* Force some input to be done if we are getting ahead of the input. */ while (cinfo->input_scan_number <= cinfo->output_scan_number && ! cinfo->inputctl->eoi_reached) { if (cinfo->input_scan_number == cinfo->output_scan_number) { /* If input is working on current scan, we ordinarily want it to * have completed the current row. But if input scan is DC, * we want it to keep one row ahead so that next block row's DC * values are up to date. */ JDIMENSION delta = (cinfo->Ss == 0) ? 1 : 0; if (cinfo->input_iMCU_row > cinfo->output_iMCU_row+delta) break; } if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED) return JPEG_SUSPENDED; } /* OK, output from the virtual arrays. */ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; ci++, compptr++) { /* Don't bother to IDCT an uninteresting component. */ if (! compptr->component_needed) continue; /* Count non-dummy DCT block rows in this iMCU row. */ if (cinfo->output_iMCU_row < last_iMCU_row) { block_rows = compptr->v_samp_factor; access_rows = block_rows * 2; /* this and next iMCU row */ last_row = FALSE; } else { /* NB: can't use last_row_height here; it is input-side-dependent! */ block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor); if (block_rows == 0) block_rows = compptr->v_samp_factor; access_rows = block_rows; /* this iMCU row only */ last_row = TRUE; } /* Align the virtual buffer for this component. */ if (cinfo->output_iMCU_row > 0) { access_rows += compptr->v_samp_factor; /* prior iMCU row too */ buffer = (*cinfo->mem->access_virt_barray) ((j_common_ptr) cinfo, coef->whole_image[ci], (cinfo->output_iMCU_row - 1) * compptr->v_samp_factor, (JDIMENSION) access_rows, FALSE); buffer += compptr->v_samp_factor; /* point to current iMCU row */ first_row = FALSE; } else { buffer = (*cinfo->mem->access_virt_barray) ((j_common_ptr) cinfo, coef->whole_image[ci], (JDIMENSION) 0, (JDIMENSION) access_rows, FALSE); first_row = TRUE; } /* Fetch component-dependent info */ coef_bits = coef->coef_bits_latch + (ci * SAVED_COEFS); quanttbl = compptr->quant_table; Q00 = quanttbl->quantval[0]; Q01 = quanttbl->quantval[1]; Q10 = quanttbl->quantval[2]; Q20 = quanttbl->quantval[3]; Q11 = quanttbl->quantval[4]; Q02 = quanttbl->quantval[5]; inverse_DCT = cinfo->idct->inverse_DCT[ci]; output_ptr = output_buf[ci]; /* Loop over all DCT blocks to be processed. */ for (block_row = 0; block_row < block_rows; block_row++) { buffer_ptr = buffer[block_row]; if (first_row && block_row == 0) prev_block_row = buffer_ptr; else prev_block_row = buffer[block_row-1]; if (last_row && block_row == block_rows-1) next_block_row = buffer_ptr; else next_block_row = buffer[block_row+1]; /* We fetch the surrounding DC values using a sliding-register approach. * Initialize all nine here so as to do the right thing on narrow pics. */ DC1 = DC2 = DC3 = (int) prev_block_row[0][0]; DC4 = DC5 = DC6 = (int) buffer_ptr[0][0]; DC7 = DC8 = DC9 = (int) next_block_row[0][0]; output_col = 0; last_block_column = compptr->width_in_blocks - 1; for (block_num = 0; block_num <= last_block_column; block_num++) { /* Fetch current DCT block into workspace so we can modify it. */ jcopy_block_row(buffer_ptr, (JBLOCKROW) workspace, (JDIMENSION) 1); /* Update DC values */ if (block_num < last_block_column) { DC3 = (int) prev_block_row[1][0]; DC6 = (int) buffer_ptr[1][0]; DC9 = (int) next_block_row[1][0]; } /* Compute coefficient estimates per K.8. * An estimate is applied only if coefficient is still zero, * and is not known to be fully accurate. */ /* AC01 */ if ((Al=coef_bits[1]) != 0 && workspace[1] == 0) { num = 36 * Q00 * (DC4 - DC6); if (num >= 0) { pred = (int) (((Q01<<7) + num) / (Q01<<8)); if (Al > 0 && pred >= (1<<Al)) pred = (1<<Al)-1; } else { pred = (int) (((Q01<<7) - num) / (Q01<<8)); if (Al > 0 && pred >= (1<<Al)) pred = (1<<Al)-1; pred = -pred; } workspace[1] = (JCOEF) pred; } /* AC10 */ if ((Al=coef_bits[2]) != 0 && workspace[8] == 0) { num = 36 * Q00 * (DC2 - DC8); if (num >= 0) { pred = (int) (((Q10<<7) + num) / (Q10<<8)); if (Al > 0 && pred >= (1<<Al)) pred = (1<<Al)-1; } else { pred = (int) (((Q10<<7) - num) / (Q10<<8)); if (Al > 0 && pred >= (1<<Al)) pred = (1<<Al)-1; pred = -pred; } workspace[8] = (JCOEF) pred; } /* AC20 */ if ((Al=coef_bits[3]) != 0 && workspace[16] == 0) { num = 9 * Q00 * (DC2 + DC8 - 2*DC5); if (num >= 0) { pred = (int) (((Q20<<7) + num) / (Q20<<8)); if (Al > 0 && pred >= (1<<Al)) pred = (1<<Al)-1; } else { pred = (int) (((Q20<<7) - num) / (Q20<<8)); if (Al > 0 && pred >= (1<<Al)) pred = (1<<Al)-1; pred = -pred; } workspace[16] = (JCOEF) pred; } /* AC11 */ if ((Al=coef_bits[4]) != 0 && workspace[9] == 0) { num = 5 * Q00 * (DC1 - DC3 - DC7 + DC9); if (num >= 0) { pred = (int) (((Q11<<7) + num) / (Q11<<8)); if (Al > 0 && pred >= (1<<Al)) pred = (1<<Al)-1; } else { pred = (int) (((Q11<<7) - num) / (Q11<<8)); if (Al > 0 && pred >= (1<<Al)) pred = (1<<Al)-1; pred = -pred; } workspace[9] = (JCOEF) pred; } /* AC02 */ if ((Al=coef_bits[5]) != 0 && workspace[2] == 0) { num = 9 * Q00 * (DC4 + DC6 - 2*DC5); if (num >= 0) { pred = (int) (((Q02<<7) + num) / (Q02<<8)); if (Al > 0 && pred >= (1<<Al)) pred = (1<<Al)-1; } else { pred = (int) (((Q02<<7) - num) / (Q02<<8)); if (Al > 0 && pred >= (1<<Al)) pred = (1<<Al)-1; pred = -pred; } workspace[2] = (JCOEF) pred; } /* OK, do the IDCT */ (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) workspace, output_ptr, output_col); /* Advance for next column */ DC1 = DC2; DC2 = DC3; DC4 = DC5; DC5 = DC6; DC7 = DC8; DC8 = DC9; buffer_ptr++, prev_block_row++, next_block_row++; output_col += compptr->DCT_scaled_size; } output_ptr += compptr->DCT_scaled_size; } } if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows) return JPEG_ROW_COMPLETED; return JPEG_SCAN_COMPLETED; } #endif /* BLOCK_SMOOTHING_SUPPORTED */ /* * Initialize coefficient buffer controller. */ GLOBAL void jinit_d_coef_controller (j_decompress_ptr cinfo, boolean need_full_buffer) { my_coef_ptr coef; coef = (my_coef_ptr) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, SIZEOF(my_coef_controller)); cinfo->coef = (struct jpeg_d_coef_controller *) coef; coef->pub.start_input_pass = start_input_pass; coef->pub.start_output_pass = start_output_pass; #ifdef BLOCK_SMOOTHING_SUPPORTED coef->coef_bits_latch = NULL; #endif /* Create the coefficient buffer. */ if (need_full_buffer) { #ifdef D_MULTISCAN_FILES_SUPPORTED /* Allocate a full-image virtual array for each component, */ /* padded to a multiple of samp_factor DCT blocks in each direction. */ /* Note we ask for a pre-zeroed array. */ int ci, access_rows; jpeg_component_info *compptr; for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; ci++, compptr++) { access_rows = compptr->v_samp_factor; #ifdef BLOCK_SMOOTHING_SUPPORTED /* If block smoothing could be used, need a bigger window */ if (cinfo->progressive_mode) access_rows *= 3; #endif coef->whole_image[ci] = (*cinfo->mem->request_virt_barray) ((j_common_ptr) cinfo, JPOOL_IMAGE, TRUE, (JDIMENSION) jround_up((long) compptr->width_in_blocks, (long) compptr->h_samp_factor), (JDIMENSION) jround_up((long) compptr->height_in_blocks, (long) compptr->v_samp_factor), (JDIMENSION) access_rows); } coef->pub.consume_data = consume_data; coef->pub.decompress_data = decompress_data; coef->pub.coef_arrays = coef->whole_image; /* link to virtual arrays */ #else ERREXIT(cinfo, JERR_NOT_COMPILED); #endif } else { /* We only need a single-MCU buffer. */ JBLOCKROW buffer; int i; buffer = (JBLOCKROW) (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE, D_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK)); for (i = 0; i < D_MAX_BLOCKS_IN_MCU; i++) { coef->MCU_buffer[i] = buffer + i; } coef->pub.consume_data = dummy_consume_data; coef->pub.decompress_data = decompress_onepass; coef->pub.coef_arrays = NULL; /* flag for no virtual arrays */ } }
[ "BawooiT@d1c0eb94-fc07-11dd-a7be-4b3ef3b0700c" ]
[ [ [ 1, 725 ] ] ]
84e697d45edd0a12a6b70b6f239a6c2c579e7aa4
e2e49023f5a82922cb9b134e93ae926ed69675a1
/tools/aoslcpp/include/aosl/object_video.inl
b8552534f57663ebb33eb2c1712df2105b75b876
[]
no_license
invy/mjklaim-freewindows
c93c867e93f0e2fe1d33f207306c0b9538ac61d6
30de8e3dfcde4e81a57e9059dfaf54c98cc1135b
refs/heads/master
2021-01-10T10:21:51.579762
2011-12-12T18:56:43
2011-12-12T18:56:43
54,794,395
1
0
null
null
null
null
UTF-8
C++
false
false
2,059
inl
// Copyright (C) 2005-2010 Code Synthesis Tools CC // // This program was generated by CodeSynthesis XSD, an XML Schema // to C++ data binding compiler, in the Proprietary License mode. // You should have received a proprietary license from Code Synthesis // Tools CC prior to generating this code. See the license text for // conditions. // #ifndef AOSLCPP_AOSL__OBJECT_VIDEO_INL #define AOSLCPP_AOSL__OBJECT_VIDEO_INL // Begin prologue. // // // End prologue. #include "aosl/object.inl" #include "aosl/properties_graphic_object.hpp" #include "aosl/properties_graphic_object.inl" #include "aosl/properties_stream_object.hpp" #include "aosl/properties_stream_object.inl" namespace aosl { // Object_video // inline const Object_video::GraphicType& Object_video:: graphic () const { return this->graphic_.get (); } inline Object_video::GraphicType& Object_video:: graphic () { return this->graphic_.get (); } inline void Object_video:: graphic (const GraphicType& x) { this->graphic_.set (x); } inline void Object_video:: graphic (::std::auto_ptr< GraphicType > x) { this->graphic_.set (x); } inline ::std::auto_ptr< Object_video::GraphicType > Object_video:: detach_graphic () { return this->graphic_.detach (); } inline const Object_video::StreamType& Object_video:: stream () const { return this->stream_.get (); } inline Object_video::StreamType& Object_video:: stream () { return this->stream_.get (); } inline void Object_video:: stream (const StreamType& x) { this->stream_.set (x); } inline void Object_video:: stream (::std::auto_ptr< StreamType > x) { this->stream_.set (x); } inline ::std::auto_ptr< Object_video::StreamType > Object_video:: detach_stream () { return this->stream_.detach (); } } // Begin epilogue. // // // End epilogue. #endif // AOSLCPP_AOSL__OBJECT_VIDEO_INL
[ "klaim@localhost" ]
[ [ [ 1, 107 ] ] ]
53757e5a1cd064830f6efc12c99c11f84ebcecb9
138a353006eb1376668037fcdfbafc05450aa413
/source/NewtonSDK/customJoints/CustomPoweredBallAndSocket.h
d22572315632403eebee5d4df3c2f48bad84b8ff
[]
no_license
sonicma7/choreopower
107ed0a5f2eb5fa9e47378702469b77554e44746
1480a8f9512531665695b46dcfdde3f689888053
refs/heads/master
2020-05-16T20:53:11.590126
2009-11-18T03:10:12
2009-11-18T03:10:12
32,246,184
0
0
null
null
null
null
UTF-8
C++
false
false
1,449
h
//******************************************************************** // Newton Game dynamics // copyright 2000-2004 // By Julio Jerez // VC: 6.0 // simple demo list vector class with iterators //******************************************************************** // CustomPoweredBallAndSocket.h: interface for the CustomPoweredBallAndSocket class. // ////////////////////////////////////////////////////////////////////// #if !defined(AFX_CustomPoweredBallAndSocket_H__468B_4331_B7D7_F85ECF3E9ADE__INCLUDED_) #define AFX_CustomPoweredBallAndSocket_H__468B_4331_B7D7_F85ECF3E9ADE__INCLUDED_ #include "NewtonCustomJoint.h" // this joint is very similar to the ball and sucked plus it had the property that // the its three rotationals degree of freedoms can by controlled by the applycation // this joint could be used for controlling the limbs of organics articulated bodies // like creatures and humanoids class CustomPoweredBallAndSocket: public NewtonCustomJoint { public: CustomPoweredBallAndSocket(const dVector& pivot, NewtonBody* child, NewtonBody* parent = NULL); virtual ~CustomPoweredBallAndSocket(); void SetChildOrientation (const dMatrix& matrix); protected: virtual void SubmitConstrainst (); dMatrix m_localMatrix0; dMatrix m_localMatrix1; dMatrix m_targetMatrix; }; #endif // !defined(AFX_CustomPoweredBallAndSocket_H__B631F556_468B_4331_B7D7_F85ECF3E9ADE__INCLUDED_)
[ "Sonicma7@0822fb10-d3c0-11de-a505-35228575a32e" ]
[ [ [ 1, 40 ] ] ]
9353549a90dce69349261f716acfee5996b646a8
ea12fed4c32e9c7992956419eb3e2bace91f063a
/zombie/code/nebula2/src/microtcl/tclParse.cc
bde8af18d05d8ff5197ab0ad9ddccf0845e9ef17
[]
no_license
ugozapad/TheZombieEngine
832492930df28c28cd349673f79f3609b1fe7190
8e8c3e6225c2ed93e07287356def9fbdeacf3d6a
refs/heads/master
2020-04-30T11:35:36.258363
2011-02-24T14:18:43
2011-02-24T14:18:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
85,038
cc
/* * tclParse.c -- * * This file contains procedures that parse Tcl scripts. They * do so in a general-purpose fashion that can be used for many * different purposes, including compilation, direct execution, * code analysis, etc. This file also includes a few additional * procedures such as Tcl_EvalObjv, Tcl_Eval, and Tcl_EvalEx, which * allow scripts to be evaluated directly, without compiling. * * Copyright (c) 1997 Sun Microsystems, Inc. * Copyright (c) 1998-2000 Ajuba Solutions. * * See the file "license.terms" for information on usage and redistribution * of this file, and for a DISCLAIMER OF ALL WARRANTIES. * * RCS: @(#) $Id: tclParse.cc,v 1.2 2003/03/23 17:12:30 brucem Exp $ */ #include "microtcl/tclInt.h" #include "microtcl/tclPort.h" /* * The following table provides parsing information about each possible * 8-bit character. The table is designed to be referenced with either * signed or unsigned characters, so it has 384 entries. The first 128 * entries correspond to negative character values, the next 256 correspond * to positive character values. The last 128 entries are identical to the * first 128. The table is always indexed with a 128-byte offset (the 128th * entry corresponds to a character value of 0). * * The macro CHAR_TYPE is used to index into the table and return * information about its character argument. The following return * values are defined. * * TYPE_NORMAL - All characters that don't have special significance * to the Tcl parser. * TYPE_SPACE - The character is a whitespace character other * than newline. * TYPE_COMMAND_END - Character is newline or semicolon. * TYPE_SUBS - Character begins a substitution or has other * special meaning in ParseTokens: backslash, dollar * sign, open bracket, or null. * TYPE_QUOTE - Character is a double quote. * TYPE_CLOSE_PAREN - Character is a right parenthesis. * TYPE_CLOSE_BRACK - Character is a right square bracket. * TYPE_BRACE - Character is a curly brace (either left or right). */ #define TYPE_NORMAL 0 #define TYPE_SPACE 0x1 #define TYPE_COMMAND_END 0x2 #define TYPE_SUBS 0x4 #define TYPE_QUOTE 0x8 #define TYPE_CLOSE_PAREN 0x10 #define TYPE_CLOSE_BRACK 0x20 #define TYPE_BRACE 0x40 #define CHAR_TYPE(c) (typeTable+128)[(int)(c)] char typeTable[] = { /* * Negative character values, from -128 to -1: */ TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, /* * Positive character values, from 0-127: */ TYPE_SUBS, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_SPACE, TYPE_COMMAND_END, TYPE_SPACE, TYPE_SPACE, TYPE_SPACE, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_SPACE, TYPE_NORMAL, TYPE_QUOTE, TYPE_NORMAL, TYPE_SUBS, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_CLOSE_PAREN, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_COMMAND_END, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_SUBS, TYPE_SUBS, TYPE_CLOSE_BRACK, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_BRACE, TYPE_NORMAL, TYPE_BRACE, TYPE_NORMAL, TYPE_NORMAL, /* * Large unsigned character values, from 128-255: */ TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, TYPE_NORMAL, }; /* * Prototypes for local procedures defined in this file: */ static int CommandComplete _ANSI_ARGS_((char *script, int length)); static int ParseTokens _ANSI_ARGS_((char *src, int mask, Tcl_Parse *parsePtr)); static int EvalObjv _ANSI_ARGS_((Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[], char *command, int length, int flags)); /* *---------------------------------------------------------------------- * * Tcl_ParseCommand -- * * Given a string, this procedure parses the first Tcl command * in the string and returns information about the structure of * the command. * * Results: * The return value is TCL_OK if the command was parsed * successfully and TCL_ERROR otherwise. If an error occurs * and interp isn't NULL then an error message is left in * its result. On a successful return, parsePtr is filled in * with information about the command that was parsed. * * Side effects: * If there is insufficient space in parsePtr to hold all the * information about the command, then additional space is * malloc-ed. If the procedure returns TCL_OK then the caller must * eventually invoke Tcl_FreeParse to release any additional space * that was allocated. * *---------------------------------------------------------------------- */ int Tcl_ParseCommand(interp, string, numBytes, nested, parsePtr) Tcl_Interp *interp; /* Interpreter to use for error reporting; * if NULL, then no error message is * provided. */ char *string; /* First character of string containing * one or more Tcl commands. The string * must be in writable memory and must * have one additional byte of space at * string[length] where we can * temporarily store a 0 sentinel * character. */ int numBytes; /* Total number of bytes in string. If < 0, * the script consists of all bytes up to * the first null character. */ int nested; /* Non-zero means this is a nested command: * close bracket should be considered * a command terminator. If zero, then close * bracket has no special meaning. */ register Tcl_Parse *parsePtr; /* Structure to fill in with information * about the parsed command; any previous * information in the structure is * ignored. */ { register char *src; /* Points to current character * in the command. */ int type; /* Result returned by CHAR_TYPE(*src). */ Tcl_Token *tokenPtr; /* Pointer to token being filled in. */ int wordIndex; /* Index of word token for current word. */ char utfBytes[TCL_UTF_MAX]; /* Holds result of backslash substitution. */ int terminators; /* CHAR_TYPE bits that indicate the end * of a command. */ char *termPtr; /* Set by Tcl_ParseBraces/QuotedString to * point to char after terminating one. */ int length, savedChar; if (numBytes < 0) { numBytes = (string? strlen(string) : 0); } parsePtr->commentStart = NULL; parsePtr->commentSize = 0; parsePtr->commandStart = NULL; parsePtr->commandSize = 0; parsePtr->numWords = 0; parsePtr->tokenPtr = parsePtr->staticTokens; parsePtr->numTokens = 0; parsePtr->tokensAvailable = NUM_STATIC_TOKENS; parsePtr->string = string; parsePtr->end = string + numBytes; parsePtr->term = parsePtr->end; parsePtr->interp = interp; parsePtr->incomplete = 0; parsePtr->errorType = TCL_PARSE_SUCCESS; if (nested != 0) { terminators = TYPE_COMMAND_END | TYPE_CLOSE_BRACK; } else { terminators = TYPE_COMMAND_END; } /* * Temporarily overwrite the character just after the end of the * string with a 0 byte. This acts as a sentinel and reduces the * number of places where we have to check for the end of the * input string. The original value of the byte is restored at * the end of the parse. */ savedChar = string[numBytes]; if (savedChar != 0) { string[numBytes] = 0; } /* * Parse any leading space and comments before the first word of the * command. */ src = string; while (1) { while ((CHAR_TYPE(*src) == TYPE_SPACE) || (*src == '\n')) { src++; } if ((*src == '\\') && (src[1] == '\n')) { /* * Skip backslash-newline sequence: it should be treated * just like white space. */ if ((src + 2) == parsePtr->end) { parsePtr->incomplete = 1; } src += 2; continue; } if (*src != '#') { break; } if (parsePtr->commentStart == NULL) { parsePtr->commentStart = src; } while (1) { if (src == parsePtr->end) { if (nested) { parsePtr->incomplete = nested; } parsePtr->commentSize = src - parsePtr->commentStart; break; } else if (*src == '\\') { if ((src[1] == '\n') && ((src + 2) == parsePtr->end)) { parsePtr->incomplete = 1; } Tcl_UtfBackslash(src, &length, utfBytes); src += length; } else if (*src == '\n') { src++; parsePtr->commentSize = src - parsePtr->commentStart; break; } else { src++; } } } /* * The following loop parses the words of the command, one word * in each iteration through the loop. */ parsePtr->commandStart = src; while (1) { /* * Create the token for the word. */ if (parsePtr->numTokens == parsePtr->tokensAvailable) { TclExpandTokenArray(parsePtr); } wordIndex = parsePtr->numTokens; tokenPtr = &parsePtr->tokenPtr[wordIndex]; tokenPtr->type = TCL_TOKEN_WORD; /* * Skip white space before the word. Also skip a backslash-newline * sequence: it should be treated just like white space. */ while (1) { type = CHAR_TYPE(*src); if (type == TYPE_SPACE) { src++; continue; } else if ((*src == '\\') && (src[1] == '\n')) { if ((src + 2) == parsePtr->end) { parsePtr->incomplete = 1; } Tcl_UtfBackslash(src, &length, utfBytes); src += length; continue; } break; } if ((type & terminators) != 0) { parsePtr->term = src; src++; break; } if (src == parsePtr->end) { break; } tokenPtr->start = src; parsePtr->numTokens++; parsePtr->numWords++; /* * At this point the word can have one of three forms: something * enclosed in quotes, something enclosed in braces, or an * unquoted word (anything else). */ if (*src == '"') { if (Tcl_ParseQuotedString(interp, src, (parsePtr->end - src), parsePtr, 1, &termPtr) != TCL_OK) { goto error; } src = termPtr; } else if (*src == '{') { if (Tcl_ParseBraces(interp, src, (parsePtr->end - src), parsePtr, 1, &termPtr) != TCL_OK) { goto error; } src = termPtr; } else { /* * This is an unquoted word. Call ParseTokens and let it do * all of the work. */ if (ParseTokens(src, TYPE_SPACE|terminators, parsePtr) != TCL_OK) { goto error; } src = parsePtr->term; } /* * Finish filling in the token for the word and check for the * special case of a word consisting of a single range of * literal text. */ tokenPtr = &parsePtr->tokenPtr[wordIndex]; tokenPtr->size = src - tokenPtr->start; tokenPtr->numComponents = parsePtr->numTokens - (wordIndex + 1); if ((tokenPtr->numComponents == 1) && (tokenPtr[1].type == TCL_TOKEN_TEXT)) { tokenPtr->type = TCL_TOKEN_SIMPLE_WORD; } /* * Do two additional checks: (a) make sure we're really at the * end of a word (there might have been garbage left after a * quoted or braced word), and (b) check for the end of the * command. */ type = CHAR_TYPE(*src); if (type == TYPE_SPACE) { src++; continue; } else { /* * Backslash-newline (and any following white space) must be * treated as if it were a space character. */ if ((*src == '\\') && (src[1] == '\n')) { if ((src + 2) == parsePtr->end) { parsePtr->incomplete = 1; } Tcl_UtfBackslash(src, &length, utfBytes); src += length; continue; } } if ((type & terminators) != 0) { parsePtr->term = src; src++; break; } if (src == parsePtr->end) { break; } if (src[-1] == '"') { if (interp != NULL) { Tcl_SetResult(interp, "extra characters after close-quote", TCL_STATIC); } parsePtr->errorType = TCL_PARSE_QUOTE_EXTRA; } else { if (interp != NULL) { Tcl_SetResult(interp, "extra characters after close-brace", TCL_STATIC); } parsePtr->errorType = TCL_PARSE_BRACE_EXTRA; } parsePtr->term = src; goto error; } parsePtr->commandSize = src - parsePtr->commandStart; if (savedChar != 0) { string[numBytes] = (char) savedChar; } return TCL_OK; error: if (savedChar != 0) { string[numBytes] = (char) savedChar; } Tcl_FreeParse(parsePtr); if (parsePtr->commandStart == NULL) { parsePtr->commandStart = string; } parsePtr->commandSize = parsePtr->term - parsePtr->commandStart; return TCL_ERROR; } /* *---------------------------------------------------------------------- * * ParseTokens -- * * This procedure forms the heart of the Tcl parser. It parses one * or more tokens from a string, up to a termination point * specified by the caller. This procedure is used to parse * unquoted command words (those not in quotes or braces), words in * quotes, and array indices for variables. * * Results: * Tokens are added to parsePtr and parsePtr->term is filled in * with the address of the character that terminated the parse (the * first one whose CHAR_TYPE matched mask or the character at * parsePtr->end). The return value is TCL_OK if the parse * completed successfully and TCL_ERROR otherwise. If a parse * error occurs and parsePtr->interp isn't NULL, then an error * message is left in the interpreter's result. * * Side effects: * None. * *---------------------------------------------------------------------- */ static int ParseTokens(src, mask, parsePtr) register char *src; /* First character to parse. */ int mask; /* Specifies when to stop parsing. The * parse stops at the first unquoted * character whose CHAR_TYPE contains * any of the bits in mask. */ Tcl_Parse *parsePtr; /* Information about parse in progress. * Updated with additional tokens and * termination information. */ { int type, originalTokens, varToken; char utfBytes[TCL_UTF_MAX]; Tcl_Token *tokenPtr; Tcl_Parse nested; /* * Each iteration through the following loop adds one token of * type TCL_TOKEN_TEXT, TCL_TOKEN_BS, TCL_TOKEN_COMMAND, or * TCL_TOKEN_VARIABLE to parsePtr. For TCL_TOKEN_VARIABLE tokens, * additional tokens are added for the parsed variable name. */ originalTokens = parsePtr->numTokens; while (1) { if (parsePtr->numTokens == parsePtr->tokensAvailable) { TclExpandTokenArray(parsePtr); } tokenPtr = &parsePtr->tokenPtr[parsePtr->numTokens]; tokenPtr->start = src; tokenPtr->numComponents = 0; type = CHAR_TYPE(*src); if (type & mask) { break; } if ((type & TYPE_SUBS) == 0) { /* * This is a simple range of characters. Scan to find the end * of the range. */ while (1) { src++; if (CHAR_TYPE(*src) & (mask | TYPE_SUBS)) { break; } } tokenPtr->type = TCL_TOKEN_TEXT; tokenPtr->size = src - tokenPtr->start; parsePtr->numTokens++; } else if (*src == '$') { /* * This is a variable reference. Call Tcl_ParseVarName to do * all the dirty work of parsing the name. */ varToken = parsePtr->numTokens; if (Tcl_ParseVarName(parsePtr->interp, src, parsePtr->end - src, parsePtr, 1) != TCL_OK) { return TCL_ERROR; } src += parsePtr->tokenPtr[varToken].size; } else if (*src == '[') { /* * Command substitution. Call Tcl_ParseCommand recursively * (and repeatedly) to parse the nested command(s), then * throw away the parse information. */ src++; while (1) { if (Tcl_ParseCommand(parsePtr->interp, src, parsePtr->end - src, 1, &nested) != TCL_OK) { parsePtr->errorType = nested.errorType; parsePtr->term = nested.term; parsePtr->incomplete = nested.incomplete; return TCL_ERROR; } src = nested.commandStart + nested.commandSize; if (nested.tokenPtr != nested.staticTokens) { ckfree((char *) nested.tokenPtr); } if ((*nested.term == ']') && !nested.incomplete) { break; } if (src == parsePtr->end) { if (parsePtr->interp != NULL) { Tcl_SetResult(parsePtr->interp, "missing close-bracket", TCL_STATIC); } parsePtr->errorType = TCL_PARSE_MISSING_BRACKET; parsePtr->term = tokenPtr->start; parsePtr->incomplete = 1; return TCL_ERROR; } } tokenPtr->type = TCL_TOKEN_COMMAND; tokenPtr->size = src - tokenPtr->start; parsePtr->numTokens++; } else if (*src == '\\') { /* * Backslash substitution. */ if (src[1] == '\n') { if ((src + 2) == parsePtr->end) { parsePtr->incomplete = 1; } /* * Note: backslash-newline is special in that it is * treated the same as a space character would be. This * means that it could terminate the token. */ if (mask & TYPE_SPACE) { break; } } tokenPtr->type = TCL_TOKEN_BS; Tcl_UtfBackslash(src, &tokenPtr->size, utfBytes); parsePtr->numTokens++; src += tokenPtr->size; } else if (*src == 0) { /* * We encountered a null character. If it is the null * character at the end of the string, then return. * Otherwise generate a text token for the single * character. */ if (src == parsePtr->end) { break; } tokenPtr->type = TCL_TOKEN_TEXT; tokenPtr->size = 1; parsePtr->numTokens++; src++; } else { panic("ParseTokens encountered unknown character"); } } if (parsePtr->numTokens == originalTokens) { /* * There was nothing in this range of text. Add an empty token * for the empty range, so that there is always at least one * token added. */ tokenPtr->type = TCL_TOKEN_TEXT; tokenPtr->size = 0; parsePtr->numTokens++; } parsePtr->term = src; return TCL_OK; } /* *---------------------------------------------------------------------- * * Tcl_FreeParse -- * * This procedure is invoked to free any dynamic storage that may * have been allocated by a previous call to Tcl_ParseCommand. * * Results: * None. * * Side effects: * If there is any dynamically allocated memory in *parsePtr, * it is freed. * *---------------------------------------------------------------------- */ void Tcl_FreeParse(parsePtr) Tcl_Parse *parsePtr; /* Structure that was filled in by a * previous call to Tcl_ParseCommand. */ { if (parsePtr->tokenPtr != parsePtr->staticTokens) { ckfree((char *) parsePtr->tokenPtr); parsePtr->tokenPtr = parsePtr->staticTokens; } } /* *---------------------------------------------------------------------- * * TclExpandTokenArray -- * * This procedure is invoked when the current space for tokens in * a Tcl_Parse structure fills up; it allocates memory to grow the * token array * * Results: * None. * * Side effects: * Memory is allocated for a new larger token array; the memory * for the old array is freed, if it had been dynamically allocated. * *---------------------------------------------------------------------- */ void TclExpandTokenArray(parsePtr) Tcl_Parse *parsePtr; /* Parse structure whose token space * has overflowed. */ { int newCount; Tcl_Token *newPtr; newCount = parsePtr->tokensAvailable*2; newPtr = (Tcl_Token *) ckalloc((unsigned) (newCount * sizeof(Tcl_Token))); memcpy((VOID *) newPtr, (VOID *) parsePtr->tokenPtr, (size_t) (parsePtr->tokensAvailable * sizeof(Tcl_Token))); if (parsePtr->tokenPtr != parsePtr->staticTokens) { ckfree((char *) parsePtr->tokenPtr); } parsePtr->tokenPtr = newPtr; parsePtr->tokensAvailable = newCount; } /* *---------------------------------------------------------------------- * * EvalObjv -- * * This procedure evaluates a Tcl command that has already been * parsed into words, with one Tcl_Obj holding each word. * * Results: * The return value is a standard Tcl completion code such as * TCL_OK or TCL_ERROR. A result or error message is left in * interp's result. If an error occurs, this procedure does * NOT add any information to the errorInfo variable. * * Side effects: * Depends on the command. * *---------------------------------------------------------------------- */ static int EvalObjv(interp, objc, objv, command, length, flags) Tcl_Interp *interp; /* Interpreter in which to evaluate the * command. Also used for error * reporting. */ int objc; /* Number of words in command. */ Tcl_Obj *CONST objv[]; /* An array of pointers to objects that are * the words that make up the command. */ char *command; /* Points to the beginning of the string * representation of the command; this * is used for traces. If the string * representation of the command is * unknown, an empty string should be * supplied. */ int length; /* Number of bytes in command; if -1, all * characters up to the first null byte are * used. */ int flags; /* Collection of OR-ed bits that control * the evaluation of the script. Only * TCL_EVAL_GLOBAL is currently * supported. */ { Command *cmdPtr; Interp *iPtr = (Interp *) interp; Tcl_Obj **newObjv; int i, code; Trace *tracePtr, *nextPtr; char **argv, *commandCopy; CallFrame *savedVarFramePtr; /* Saves old copy of iPtr->varFramePtr * in case TCL_EVAL_GLOBAL was set. */ Tcl_ResetResult(interp); if (objc == 0) { return TCL_OK; } /* * If the interpreter was deleted, return an error. */ if (iPtr->flags & DELETED) { Tcl_AppendToObj(Tcl_GetObjResult(interp), "attempt to call eval in deleted interpreter", -1); Tcl_SetErrorCode(interp, "CORE", "IDELETE", "attempt to call eval in deleted interpreter", (char *) NULL); return TCL_ERROR; } /* * Check depth of nested calls to Tcl_Eval: if this gets too large, * it's probably because of an infinite loop somewhere. */ if (iPtr->numLevels >= iPtr->maxNestingDepth) { iPtr->result = "too many nested calls to Tcl_Eval (infinite loop?)"; return TCL_ERROR; } iPtr->numLevels++; /* * On the Mac, we will never reach the default recursion limit before * blowing the stack. So we need to do a check here. */ // FIXME FLOH /* if (TclpCheckStackSpace() == 0) { iPtr->numLevels--; iPtr->result = "too many nested calls to Tcl_Eval (infinite loop?)"; return TCL_ERROR; } */ /* * Find the procedure to execute this command. If there isn't one, * then see if there is a command "unknown". If so, create a new * word array with "unknown" as the first word and the original * command words as arguments. Then call ourselves recursively * to execute it. */ cmdPtr = (Command *) Tcl_GetCommandFromObj(interp, objv[0]); if (cmdPtr == NULL) { newObjv = (Tcl_Obj **) ckalloc((unsigned) ((objc + 1) * sizeof (Tcl_Obj *))); for (i = objc-1; i >= 0; i--) { newObjv[i+1] = objv[i]; } newObjv[0] = Tcl_NewStringObj("unknown", -1); Tcl_IncrRefCount(newObjv[0]); cmdPtr = (Command *) Tcl_GetCommandFromObj(interp, newObjv[0]); if (cmdPtr == NULL) { Tcl_AppendStringsToObj(Tcl_GetObjResult(interp), "invalid command name \"", Tcl_GetString(objv[0]), "\"", (char *) NULL); code = TCL_ERROR; } else { code = EvalObjv(interp, objc+1, newObjv, command, length, 0); } Tcl_DecrRefCount(newObjv[0]); ckfree((char *) newObjv); goto done; } /* * Call trace procedures if needed. */ argv = NULL; commandCopy = command; for (tracePtr = iPtr->tracePtr; tracePtr != NULL; tracePtr = nextPtr) { nextPtr = tracePtr->nextPtr; if (iPtr->numLevels > tracePtr->level) { continue; } /* * This is a bit messy because we have to emulate the old trace * interface, which uses strings for everything. */ if (argv == NULL) { argv = (char **) ckalloc((unsigned) (objc + 1) * sizeof(char *)); for (i = 0; i < objc; i++) { argv[i] = Tcl_GetString(objv[i]); } argv[objc] = 0; if (length < 0) { length = strlen(command); } else if ((size_t)length < strlen(command)) { commandCopy = (char *) ckalloc((unsigned) (length + 1)); strncpy(commandCopy, command, (size_t) length); commandCopy[length] = 0; } } (*tracePtr->proc)(tracePtr->clientData, interp, iPtr->numLevels, commandCopy, cmdPtr->proc, cmdPtr->clientData, objc, argv); } if (argv != NULL) { ckfree((char *) argv); } if (commandCopy != command) { ckfree((char *) commandCopy); } /* * Finally, invoke the command's Tcl_ObjCmdProc. */ iPtr->cmdCount++; savedVarFramePtr = iPtr->varFramePtr; if (flags & TCL_EVAL_GLOBAL) { iPtr->varFramePtr = NULL; } code = (*cmdPtr->objProc)(cmdPtr->objClientData, interp, objc, objv); iPtr->varFramePtr = savedVarFramePtr; // FIXME FLOH /* if (Tcl_AsyncReady()) { code = Tcl_AsyncInvoke(interp, code); } */ /* * If the interpreter has a non-empty string result, the result * object is either empty or stale because some procedure set * interp->result directly. If so, move the string result to the * result object, then reset the string result. */ if (*(iPtr->result) != 0) { (void) Tcl_GetObjResult(interp); } done: iPtr->numLevels--; return code; } /* *---------------------------------------------------------------------- * * Tcl_EvalObjv -- * * This procedure evaluates a Tcl command that has already been * parsed into words, with one Tcl_Obj holding each word. * * Results: * The return value is a standard Tcl completion code such as * TCL_OK or TCL_ERROR. A result or error message is left in * interp's result. * * Side effects: * Depends on the command. * *---------------------------------------------------------------------- */ int Tcl_EvalObjv(interp, objc, objv, flags) Tcl_Interp *interp; /* Interpreter in which to evaluate the * command. Also used for error * reporting. */ int objc; /* Number of words in command. */ Tcl_Obj *CONST objv[]; /* An array of pointers to objects that are * the words that make up the command. */ int flags; /* Collection of OR-ed bits that control * the evaluation of the script. Only * TCL_EVAL_GLOBAL is currently * supported. */ { Interp *iPtr = (Interp *)interp; Trace *tracePtr; Tcl_DString cmdBuf; char *cmdString = ""; int cmdLen = 0; int code = TCL_OK; for (tracePtr = iPtr->tracePtr; tracePtr; tracePtr = tracePtr->nextPtr) { /* * EvalObjv will increment numLevels so use "<" rather than "<=" */ if (iPtr->numLevels < tracePtr->level) { int i; /* * The command will be needed for an execution trace or stack trace * generate a command string. */ cmdtraced: Tcl_DStringInit(&cmdBuf); for (i = 0; i < objc; i++) { Tcl_DStringAppendElement(&cmdBuf, Tcl_GetString(objv[i])); } cmdString = Tcl_DStringValue(&cmdBuf); cmdLen = Tcl_DStringLength(&cmdBuf); break; } } /* * Execute the command if we have not done so already */ switch (code) { case TCL_OK: code = EvalObjv(interp, objc, objv, cmdString, cmdLen, flags); if (code == TCL_ERROR && cmdLen == 0) goto cmdtraced; break; case TCL_ERROR: Tcl_LogCommandInfo(interp, cmdString, cmdString, cmdLen); break; default: /*NOTREACHED*/ break; } if (cmdLen != 0) { Tcl_DStringFree(&cmdBuf); } return code; } /* *---------------------------------------------------------------------- * * Tcl_LogCommandInfo -- * * This procedure is invoked after an error occurs in an interpreter. * It adds information to the "errorInfo" variable to describe the * command that was being executed when the error occurred. * * Results: * None. * * Side effects: * Information about the command is added to errorInfo and the * line number stored internally in the interpreter is set. If this * is the first call to this procedure or Tcl_AddObjErrorInfo since * an error occurred, then old information in errorInfo is * deleted. * *---------------------------------------------------------------------- */ void Tcl_LogCommandInfo(interp, script, command, length) Tcl_Interp *interp; /* Interpreter in which to log information. */ char *script; /* First character in script containing * command (must be <= command). */ char *command; /* First character in command that * generated the error. */ int length; /* Number of bytes in command (-1 means * use all bytes up to first null byte). */ { char buffer[200]; register char *p; char *ellipsis = ""; Interp *iPtr = (Interp *) interp; if (iPtr->flags & ERR_ALREADY_LOGGED) { /* * Someone else has already logged error information for this * command; we shouldn't add anything more. */ return; } /* * Compute the line number where the error occurred. */ iPtr->errorLine = 1; for (p = script; p != command; p++) { if (*p == '\n') { iPtr->errorLine++; } } /* * Create an error message to add to errorInfo, including up to a * maximum number of characters of the command. */ if (length < 0) { length = strlen(command); } if (length > 150) { length = 150; ellipsis = "..."; } if (!(iPtr->flags & ERR_IN_PROGRESS)) { sprintf(buffer, "\n while executing\n\"%.*s%s\"", length, command, ellipsis); } else { sprintf(buffer, "\n invoked from within\n\"%.*s%s\"", length, command, ellipsis); } Tcl_AddObjErrorInfo(interp, buffer, -1); iPtr->flags &= ~ERR_ALREADY_LOGGED; } /* *---------------------------------------------------------------------- * * Tcl_EvalTokens -- * * Given an array of tokens parsed from a Tcl command (e.g., the * tokens that make up a word or the index for an array variable) * this procedure evaluates the tokens and concatenates their * values to form a single result value. * * Results: * The return value is a pointer to a newly allocated Tcl_Obj * containing the value of the array of tokens. The reference * count of the returned object has been incremented. If an error * occurs in evaluating the tokens then a NULL value is returned * and an error message is left in interp's result. * * Side effects: * A new object is allocated to hold the result. * *---------------------------------------------------------------------- */ Tcl_Obj * Tcl_EvalTokens(interp, tokenPtr, count) Tcl_Interp *interp; /* Interpreter in which to lookup * variables, execute nested commands, * and report errors. */ Tcl_Token *tokenPtr; /* Pointer to first in an array of tokens * to evaluate and concatenate. */ int count; /* Number of tokens to consider at tokenPtr. * Must be at least 1. */ { Tcl_Obj *resultPtr, *indexPtr, *valuePtr, *newPtr; char buffer[TCL_UTF_MAX]; #ifdef TCL_MEM_DEBUG # define MAX_VAR_CHARS 5 #else # define MAX_VAR_CHARS 30 #endif char nameBuffer[MAX_VAR_CHARS+1]; char *varName, *index; char *p = NULL; /* Initialized to avoid compiler warning. */ int length, code; /* * The only tricky thing about this procedure is that it attempts to * avoid object creation and string copying whenever possible. For * example, if the value is just a nested command, then use the * command's result object directly. */ resultPtr = NULL; for ( ; count > 0; count--, tokenPtr++) { valuePtr = NULL; /* * The switch statement below computes the next value to be * concat to the result, as either a range of text or an * object. */ switch (tokenPtr->type) { case TCL_TOKEN_TEXT: p = tokenPtr->start; length = tokenPtr->size; break; case TCL_TOKEN_BS: length = Tcl_UtfBackslash(tokenPtr->start, (int *) NULL, buffer); p = buffer; break; case TCL_TOKEN_COMMAND: code = Tcl_EvalEx(interp, tokenPtr->start+1, tokenPtr->size-2, 0); if (code != TCL_OK) { goto error; } valuePtr = Tcl_GetObjResult(interp); break; case TCL_TOKEN_VARIABLE: if (tokenPtr->numComponents == 1) { indexPtr = NULL; } else { indexPtr = Tcl_EvalTokens(interp, tokenPtr+2, tokenPtr->numComponents - 1); if (indexPtr == NULL) { goto error; } } /* * We have to make a copy of the variable name in order * to have a null-terminated string. We can't make a * temporary modification to the script to null-terminate * the name, because a trace callback might potentially * reuse the script and be affected by the null character. */ if (tokenPtr[1].size <= MAX_VAR_CHARS) { varName = nameBuffer; } else { varName = ckalloc((unsigned) (tokenPtr[1].size + 1)); } strncpy(varName, tokenPtr[1].start, (size_t) tokenPtr[1].size); varName[tokenPtr[1].size] = 0; if (indexPtr != NULL) { index = TclGetString(indexPtr); } else { index = NULL; } valuePtr = Tcl_GetVar2Ex(interp, varName, index, TCL_LEAVE_ERR_MSG); if (varName != nameBuffer) { ckfree(varName); } if (indexPtr != NULL) { Tcl_DecrRefCount(indexPtr); } if (valuePtr == NULL) { goto error; } count -= tokenPtr->numComponents; tokenPtr += tokenPtr->numComponents; break; default: panic("unexpected token type in Tcl_EvalTokens"); } /* * If valuePtr isn't NULL, the next piece of text comes from that * object; otherwise, take length bytes starting at p. */ if (resultPtr == NULL) { if (valuePtr != NULL) { resultPtr = valuePtr; } else { resultPtr = Tcl_NewStringObj(p, length); } Tcl_IncrRefCount(resultPtr); } else { if (Tcl_IsShared(resultPtr)) { newPtr = Tcl_DuplicateObj(resultPtr); Tcl_DecrRefCount(resultPtr); resultPtr = newPtr; Tcl_IncrRefCount(resultPtr); } if (valuePtr != NULL) { p = Tcl_GetStringFromObj(valuePtr, &length); } Tcl_AppendToObj(resultPtr, p, length); } } return resultPtr; error: if (resultPtr != NULL) { Tcl_DecrRefCount(resultPtr); } return NULL; } /* *---------------------------------------------------------------------- * * Tcl_EvalEx -- * * This procedure evaluates a Tcl script without using the compiler * or byte-code interpreter. It just parses the script, creates * values for each word of each command, then calls EvalObjv * to execute each command. * * Results: * The return value is a standard Tcl completion code such as * TCL_OK or TCL_ERROR. A result or error message is left in * interp's result. * * Side effects: * Depends on the script. * *---------------------------------------------------------------------- */ int Tcl_EvalEx(interp, script, numBytes, flags) Tcl_Interp *interp; /* Interpreter in which to evaluate the * script. Also used for error reporting. */ char *script; /* First character of script to evaluate. */ int numBytes; /* Number of bytes in script. If < 0, the * script consists of all bytes up to the * first null character. */ int flags; /* Collection of OR-ed bits that control * the evaluation of the script. Only * TCL_EVAL_GLOBAL is currently * supported. */ { Interp *iPtr = (Interp *) interp; char *p, *next; Tcl_Parse parse; #define NUM_STATIC_OBJS 20 Tcl_Obj *staticObjArray[NUM_STATIC_OBJS], **objv; Tcl_Token *tokenPtr; int i, code, commandLength, bytesLeft, nested; CallFrame *savedVarFramePtr; /* Saves old copy of iPtr->varFramePtr * in case TCL_EVAL_GLOBAL was set. */ /* * The variables below keep track of how much state has been * allocated while evaluating the script, so that it can be freed * properly if an error occurs. */ int gotParse = 0, objectsUsed = 0; if (numBytes < 0) { numBytes = strlen(script); } Tcl_ResetResult(interp); savedVarFramePtr = iPtr->varFramePtr; if (flags & TCL_EVAL_GLOBAL) { iPtr->varFramePtr = NULL; } /* * Each iteration through the following loop parses the next * command from the script and then executes it. */ objv = staticObjArray; p = script; bytesLeft = numBytes; if (iPtr->evalFlags & TCL_BRACKET_TERM) { nested = 1; } else { nested = 0; } iPtr->evalFlags = 0; do { if (Tcl_ParseCommand(interp, p, bytesLeft, nested, &parse) != TCL_OK) { code = TCL_ERROR; goto error; } gotParse = 1; if (parse.numWords > 0) { /* * Generate an array of objects for the words of the command. */ if (parse.numWords <= NUM_STATIC_OBJS) { objv = staticObjArray; } else { objv = (Tcl_Obj **) ckalloc((unsigned) (parse.numWords * sizeof (Tcl_Obj *))); } for (objectsUsed = 0, tokenPtr = parse.tokenPtr; objectsUsed < parse.numWords; objectsUsed++, tokenPtr += (tokenPtr->numComponents + 1)) { objv[objectsUsed] = Tcl_EvalTokens(interp, tokenPtr+1, tokenPtr->numComponents); if (objv[objectsUsed] == NULL) { code = TCL_ERROR; goto error; } } /* * Execute the command and free the objects for its words. */ code = EvalObjv(interp, objectsUsed, objv, p, bytesLeft, 0); if (code != TCL_OK) { goto error; } for (i = 0; i < objectsUsed; i++) { Tcl_DecrRefCount(objv[i]); } objectsUsed = 0; if (objv != staticObjArray) { ckfree((char *) objv); objv = staticObjArray; } } /* * Advance to the next command in the script. */ next = parse.commandStart + parse.commandSize; bytesLeft -= next - p; p = next; Tcl_FreeParse(&parse); gotParse = 0; if ((nested != 0) && (p > script) && (p[-1] == ']')) { /* * We get here in the special case where the TCL_BRACKET_TERM * flag was set in the interpreter and we reached a close * bracket in the script. Return immediately. */ iPtr->termOffset = (p - 1) - script; iPtr->varFramePtr = savedVarFramePtr; return TCL_OK; } } while (bytesLeft > 0); iPtr->termOffset = p - script; iPtr->varFramePtr = savedVarFramePtr; return TCL_OK; error: /* * Generate various pieces of error information, such as the line * number where the error occurred and information to add to the * errorInfo variable. Then free resources that had been allocated * to the command. */ if ((code == TCL_ERROR) && !(iPtr->flags & ERR_ALREADY_LOGGED)) { commandLength = parse.commandSize; if ((parse.commandStart + commandLength) != (script + numBytes)) { /* * The command where the error occurred didn't end at the end * of the script (i.e. it ended at a terminator character such * as ";". Reduce the length by one so that the error message * doesn't include the terminator character. */ commandLength -= 1; } Tcl_LogCommandInfo(interp, script, parse.commandStart, commandLength); } for (i = 0; i < objectsUsed; i++) { Tcl_DecrRefCount(objv[i]); } if (gotParse) { next = parse.commandStart + parse.commandSize; bytesLeft -= next - p; p = next; Tcl_FreeParse(&parse); if ((nested != 0) && (p > script)) { char *nextCmd = NULL; /* pointer to start of next command */ /* * We get here in the special case where the TCL_BRACKET_TERM * flag was set in the interpreter. * * At this point, we want to find the end of the script * (either end of script or the closing ']'). */ while ((p[-1] != ']') && bytesLeft) { if (Tcl_ParseCommand(NULL, p, bytesLeft, nested, &parse) != TCL_OK) { /* * We were looking for the ']' to close the script. * But if we find a syntax error, it is ok to quit * early since in that case we no longer need to know * where the ']' is (if there was one). We reset the * pointer to the start of the command that after the * one causing the return. -- hobbs */ p = (nextCmd == NULL) ? parse.commandStart : nextCmd; break; } if (nextCmd == NULL) { nextCmd = parse.commandStart; } /* * Advance to the next command in the script. */ next = parse.commandStart + parse.commandSize; bytesLeft -= next - p; p = next; Tcl_FreeParse(&parse); } iPtr->termOffset = (p - 1) - script; } else { iPtr->termOffset = p - script; } } if (objv != staticObjArray) { ckfree((char *) objv); } iPtr->varFramePtr = savedVarFramePtr; return code; } /* *---------------------------------------------------------------------- * * Tcl_Eval -- * * Execute a Tcl command in a string. This procedure executes the * script directly, rather than compiling it to bytecodes. Before * the arrival of the bytecode compiler in Tcl 8.0 Tcl_Eval was * the main procedure used for executing Tcl commands, but nowadays * it isn't used much. * * Results: * The return value is one of the return codes defined in tcl.h * (such as TCL_OK), and interp's result contains a value * to supplement the return code. The value of the result * will persist only until the next call to Tcl_Eval or Tcl_EvalObj: * you must copy it or lose it! * * Side effects: * Can be almost arbitrary, depending on the commands in the script. * *---------------------------------------------------------------------- */ int Tcl_Eval(interp, string) Tcl_Interp *interp; /* Token for command interpreter (returned * by previous call to Tcl_CreateInterp). */ char *string; /* Pointer to TCL command to execute. */ { int code; code = Tcl_EvalEx(interp, string, -1, 0); /* * For backwards compatibility with old C code that predates the * object system in Tcl 8.0, we have to mirror the object result * back into the string result (some callers may expect it there). */ Tcl_SetResult(interp, TclGetString(Tcl_GetObjResult(interp)), TCL_VOLATILE); return code; } /* *---------------------------------------------------------------------- * * Tcl_EvalObj, Tcl_GlobalEvalObj -- * * These functions are deprecated but we keep them around for backwards * compatibility reasons. * * Results: * See the functions they call. * * Side effects: * See the functions they call. * *---------------------------------------------------------------------- */ #undef Tcl_EvalObj int Tcl_EvalObj(interp, objPtr) Tcl_Interp * interp; Tcl_Obj * objPtr; { return Tcl_EvalObjEx(interp, objPtr, 0); } #undef Tcl_GlobalEvalObj int Tcl_GlobalEvalObj(interp, objPtr) Tcl_Interp * interp; Tcl_Obj * objPtr; { return Tcl_EvalObjEx(interp, objPtr, TCL_EVAL_GLOBAL); } /* *---------------------------------------------------------------------- * * Tcl_ParseVarName -- * * Given a string starting with a $ sign, parse off a variable * name and return information about the parse. * * Results: * The return value is TCL_OK if the command was parsed * successfully and TCL_ERROR otherwise. If an error occurs and * interp isn't NULL then an error message is left in its result. * On a successful return, tokenPtr and numTokens fields of * parsePtr are filled in with information about the variable name * that was parsed. The "size" field of the first new token gives * the total number of bytes in the variable name. Other fields in * parsePtr are undefined. * * Side effects: * If there is insufficient space in parsePtr to hold all the * information about the command, then additional space is * malloc-ed. If the procedure returns TCL_OK then the caller must * eventually invoke Tcl_FreeParse to release any additional space * that was allocated. * *---------------------------------------------------------------------- */ int Tcl_ParseVarName(interp, string, numBytes, parsePtr, append) Tcl_Interp *interp; /* Interpreter to use for error reporting; * if NULL, then no error message is * provided. */ char *string; /* String containing variable name. First * character must be "$". */ int numBytes; /* Total number of bytes in string. If < 0, * the string consists of all bytes up to the * first null character. */ Tcl_Parse *parsePtr; /* Structure to fill in with information * about the variable name. */ int append; /* Non-zero means append tokens to existing * information in parsePtr; zero means ignore * existing tokens in parsePtr and reinitialize * it. */ { Tcl_Token *tokenPtr; char *end, *src; unsigned char c; int varIndex, offset; Tcl_UniChar ch; unsigned array; if (numBytes >= 0) { end = string + numBytes; } else { end = string + strlen(string); } if (!append) { parsePtr->numWords = 0; parsePtr->tokenPtr = parsePtr->staticTokens; parsePtr->numTokens = 0; parsePtr->tokensAvailable = NUM_STATIC_TOKENS; parsePtr->string = string; parsePtr->end = end; parsePtr->interp = interp; parsePtr->errorType = TCL_PARSE_SUCCESS; parsePtr->incomplete = 0; } /* * Generate one token for the variable, an additional token for the * name, plus any number of additional tokens for the index, if * there is one. */ src = string; if ((parsePtr->numTokens + 2) > parsePtr->tokensAvailable) { TclExpandTokenArray(parsePtr); } tokenPtr = &parsePtr->tokenPtr[parsePtr->numTokens]; tokenPtr->type = TCL_TOKEN_VARIABLE; tokenPtr->start = src; varIndex = parsePtr->numTokens; parsePtr->numTokens++; tokenPtr++; src++; if (src >= end) { goto justADollarSign; } tokenPtr->type = TCL_TOKEN_TEXT; tokenPtr->start = src; tokenPtr->numComponents = 0; /* * The name of the variable can have three forms: * 1. The $ sign is followed by an open curly brace. Then * the variable name is everything up to the next close * curly brace, and the variable is a scalar variable. * 2. The $ sign is not followed by an open curly brace. Then * the variable name is everything up to the next * character that isn't a letter, digit, or underscore. * :: sequences are also considered part of the variable * name, in order to support namespaces. If the following * character is an open parenthesis, then the information * between parentheses is the array element name. * 3. The $ sign is followed by something that isn't a letter, * digit, or underscore: in this case, there is no variable * name and the token is just "$". */ if (*src == '{') { src++; tokenPtr->type = TCL_TOKEN_TEXT; tokenPtr->start = src; tokenPtr->numComponents = 0; while (1) { if (src == end) { if (interp != NULL) { Tcl_SetResult(interp, "missing close-brace for variable name", TCL_STATIC); } parsePtr->errorType = TCL_PARSE_MISSING_VAR_BRACE; parsePtr->term = tokenPtr->start-1; parsePtr->incomplete = 1; goto error; } if (*src == '}') { break; } src++; } tokenPtr->size = src - tokenPtr->start; tokenPtr[-1].size = src - tokenPtr[-1].start; parsePtr->numTokens++; src++; } else { tokenPtr->type = TCL_TOKEN_TEXT; tokenPtr->start = src; tokenPtr->numComponents = 0; while (src != end) { offset = Tcl_UtfToUniChar(src, &ch); c = UCHAR(ch); if (isalnum(c) || (c == '_')) { /* INTL: ISO only, UCHAR. */ src += offset; continue; } if ((c == ':') && (((src+1) != end) && (src[1] == ':'))) { src += 2; while ((src != end) && (*src == ':')) { src += 1; } continue; } break; } /* * Support for empty array names here. */ array = ((src != end) && (*src == '(')); tokenPtr->size = src - tokenPtr->start; if (tokenPtr->size == 0 && !array) { goto justADollarSign; } parsePtr->numTokens++; if (array) { /* * This is a reference to an array element. Call * ParseTokens recursively to parse the element name, * since it could contain any number of substitutions. */ if (ParseTokens(src+1, TYPE_CLOSE_PAREN, parsePtr) != TCL_OK) { goto error; } if ((parsePtr->term == end) || (*parsePtr->term != ')')) { if (parsePtr->interp != NULL) { Tcl_SetResult(parsePtr->interp, "missing )", TCL_STATIC); } parsePtr->errorType = TCL_PARSE_MISSING_PAREN; parsePtr->term = src; parsePtr->incomplete = 1; goto error; } src = parsePtr->term + 1; } } tokenPtr = &parsePtr->tokenPtr[varIndex]; tokenPtr->size = src - tokenPtr->start; tokenPtr->numComponents = parsePtr->numTokens - (varIndex + 1); return TCL_OK; /* * The dollar sign isn't followed by a variable name. * replace the TCL_TOKEN_VARIABLE token with a * TCL_TOKEN_TEXT token for the dollar sign. */ justADollarSign: tokenPtr = &parsePtr->tokenPtr[varIndex]; tokenPtr->type = TCL_TOKEN_TEXT; tokenPtr->size = 1; tokenPtr->numComponents = 0; return TCL_OK; error: Tcl_FreeParse(parsePtr); return TCL_ERROR; } /* *---------------------------------------------------------------------- * * Tcl_ParseVar -- * * Given a string starting with a $ sign, parse off a variable * name and return its value. * * Results: * The return value is the contents of the variable given by * the leading characters of string. If termPtr isn't NULL, * *termPtr gets filled in with the address of the character * just after the last one in the variable specifier. If the * variable doesn't exist, then the return value is NULL and * an error message will be left in interp's result. * * Side effects: * None. * *---------------------------------------------------------------------- */ char * Tcl_ParseVar(interp, string, termPtr) Tcl_Interp *interp; /* Context for looking up variable. */ register char *string; /* String containing variable name. * First character must be "$". */ char **termPtr; /* If non-NULL, points to word to fill * in with character just after last * one in the variable specifier. */ { Tcl_Parse parse; register Tcl_Obj *objPtr; if (Tcl_ParseVarName(interp, string, -1, &parse, 0) != TCL_OK) { return NULL; } if (termPtr != NULL) { *termPtr = string + parse.tokenPtr->size; } if (parse.numTokens == 1) { /* * There isn't a variable name after all: the $ is just a $. */ return "$"; } objPtr = Tcl_EvalTokens(interp, parse.tokenPtr, parse.numTokens); if (objPtr == NULL) { return NULL; } /* * At this point we should have an object containing the value of * a variable. Just return the string from that object. */ #ifdef TCL_COMPILE_DEBUG if (objPtr->refCount < 2) { panic("Tcl_ParseVar got temporary object from Tcl_EvalTokens"); } #endif /*TCL_COMPILE_DEBUG*/ TclDecrRefCount(objPtr); return TclGetString(objPtr); } /* *---------------------------------------------------------------------- * * Tcl_ParseBraces -- * * Given a string in braces such as a Tcl command argument or a string * value in a Tcl expression, this procedure parses the string and * returns information about the parse. * * Results: * The return value is TCL_OK if the string was parsed successfully and * TCL_ERROR otherwise. If an error occurs and interp isn't NULL then * an error message is left in its result. On a successful return, * tokenPtr and numTokens fields of parsePtr are filled in with * information about the string that was parsed. Other fields in * parsePtr are undefined. termPtr is set to point to the character * just after the last one in the braced string. * * Side effects: * If there is insufficient space in parsePtr to hold all the * information about the command, then additional space is * malloc-ed. If the procedure returns TCL_OK then the caller must * eventually invoke Tcl_FreeParse to release any additional space * that was allocated. * *---------------------------------------------------------------------- */ int Tcl_ParseBraces(interp, string, numBytes, parsePtr, append, termPtr) Tcl_Interp *interp; /* Interpreter to use for error reporting; * if NULL, then no error message is * provided. */ char *string; /* String containing the string in braces. * The first character must be '{'. */ int numBytes; /* Total number of bytes in string. If < 0, * the string consists of all bytes up to * the first null character. */ register Tcl_Parse *parsePtr; /* Structure to fill in with information * about the string. */ int append; /* Non-zero means append tokens to existing * information in parsePtr; zero means * ignore existing tokens in parsePtr and * reinitialize it. */ char **termPtr; /* If non-NULL, points to word in which to * store a pointer to the character just * after the terminating '}' if the parse * was successful. */ { char utfBytes[TCL_UTF_MAX]; /* For result of backslash substitution. */ Tcl_Token *tokenPtr; register char *src, *end; int startIndex, level, length; if ((numBytes >= 0) || (string == NULL)) { end = string + numBytes; } else { end = string + strlen(string); } if (!append) { parsePtr->numWords = 0; parsePtr->tokenPtr = parsePtr->staticTokens; parsePtr->numTokens = 0; parsePtr->tokensAvailable = NUM_STATIC_TOKENS; parsePtr->string = string; parsePtr->end = end; parsePtr->interp = interp; parsePtr->errorType = TCL_PARSE_SUCCESS; } src = string+1; startIndex = parsePtr->numTokens; if (parsePtr->numTokens == parsePtr->tokensAvailable) { TclExpandTokenArray(parsePtr); } tokenPtr = &parsePtr->tokenPtr[startIndex]; tokenPtr->type = TCL_TOKEN_TEXT; tokenPtr->start = src; tokenPtr->numComponents = 0; level = 1; while (1) { while (CHAR_TYPE(*src) == TYPE_NORMAL) { src++; } if (*src == '}') { level--; if (level == 0) { break; } src++; } else if (*src == '{') { level++; src++; } else if (*src == '\\') { Tcl_UtfBackslash(src, &length, utfBytes); if (src[1] == '\n') { /* * A backslash-newline sequence must be collapsed, even * inside braces, so we have to split the word into * multiple tokens so that the backslash-newline can be * represented explicitly. */ if ((src + 2) == end) { parsePtr->incomplete = 1; } tokenPtr->size = (src - tokenPtr->start); if (tokenPtr->size != 0) { parsePtr->numTokens++; } if ((parsePtr->numTokens+1) >= parsePtr->tokensAvailable) { TclExpandTokenArray(parsePtr); } tokenPtr = &parsePtr->tokenPtr[parsePtr->numTokens]; tokenPtr->type = TCL_TOKEN_BS; tokenPtr->start = src; tokenPtr->size = length; tokenPtr->numComponents = 0; parsePtr->numTokens++; src += length; tokenPtr++; tokenPtr->type = TCL_TOKEN_TEXT; tokenPtr->start = src; tokenPtr->numComponents = 0; } else { src += length; } } else if (src == end) { int openBrace; if (interp != NULL) { Tcl_SetResult(interp, "missing close-brace", TCL_STATIC); } /* * Search the source string for a possible open * brace within the context of a comment. Since we * aren't performing a full Tcl parse, just look for * an open brace preceeded by a '<whitspace>#' on * the same line. */ openBrace = 0; while (src > string ) { switch (*src) { case '{': openBrace = 1; break; case '\n': openBrace = 0; break; case '#': if ((openBrace == 1) && (isspace(UCHAR(src[-1])))) { if (interp != NULL) { Tcl_AppendResult(interp, ": possible unbalanced brace in comment", (char *) NULL); } openBrace = -1; break; } break; } if (openBrace == -1) { break; } src--; } parsePtr->errorType = TCL_PARSE_MISSING_BRACE; parsePtr->term = string; parsePtr->incomplete = 1; goto error; } else { src++; } } /* * Decide if we need to finish emitting a partially-finished token. * There are 3 cases: * {abc \newline xyz} or {xyz} - finish emitting "xyz" token * {abc \newline} - don't emit token after \newline * {} - finish emitting zero-sized token * The last case ensures that there is a token (even if empty) that * describes the braced string. */ if ((src != tokenPtr->start) || (parsePtr->numTokens == startIndex)) { tokenPtr->size = (src - tokenPtr->start); parsePtr->numTokens++; } if (termPtr != NULL) { *termPtr = src+1; } return TCL_OK; error: Tcl_FreeParse(parsePtr); return TCL_ERROR; } /* *---------------------------------------------------------------------- * * Tcl_ParseQuotedString -- * * Given a double-quoted string such as a quoted Tcl command argument * or a quoted value in a Tcl expression, this procedure parses the * string and returns information about the parse. * * Results: * The return value is TCL_OK if the string was parsed successfully and * TCL_ERROR otherwise. If an error occurs and interp isn't NULL then * an error message is left in its result. On a successful return, * tokenPtr and numTokens fields of parsePtr are filled in with * information about the string that was parsed. Other fields in * parsePtr are undefined. termPtr is set to point to the character * just after the quoted string's terminating close-quote. * * Side effects: * If there is insufficient space in parsePtr to hold all the * information about the command, then additional space is * malloc-ed. If the procedure returns TCL_OK then the caller must * eventually invoke Tcl_FreeParse to release any additional space * that was allocated. * *---------------------------------------------------------------------- */ int Tcl_ParseQuotedString(interp, string, numBytes, parsePtr, append, termPtr) Tcl_Interp *interp; /* Interpreter to use for error reporting; * if NULL, then no error message is * provided. */ char *string; /* String containing the quoted string. * The first character must be '"'. */ int numBytes; /* Total number of bytes in string. If < 0, * the string consists of all bytes up to * the first null character. */ register Tcl_Parse *parsePtr; /* Structure to fill in with information * about the string. */ int append; /* Non-zero means append tokens to existing * information in parsePtr; zero means * ignore existing tokens in parsePtr and * reinitialize it. */ char **termPtr; /* If non-NULL, points to word in which to * store a pointer to the character just * after the quoted string's terminating * close-quote if the parse succeeds. */ { char *end; if ((numBytes >= 0) || (string == NULL)) { end = string + numBytes; } else { end = string + strlen(string); } if (!append) { parsePtr->numWords = 0; parsePtr->tokenPtr = parsePtr->staticTokens; parsePtr->numTokens = 0; parsePtr->tokensAvailable = NUM_STATIC_TOKENS; parsePtr->string = string; parsePtr->end = end; parsePtr->interp = interp; parsePtr->errorType = TCL_PARSE_SUCCESS; } if (ParseTokens(string+1, TYPE_QUOTE, parsePtr) != TCL_OK) { goto error; } if (*parsePtr->term != '"') { if (interp != NULL) { Tcl_SetResult(parsePtr->interp, "missing \"", TCL_STATIC); } parsePtr->errorType = TCL_PARSE_MISSING_QUOTE; parsePtr->term = string; parsePtr->incomplete = 1; goto error; } if (termPtr != NULL) { *termPtr = (parsePtr->term + 1); } return TCL_OK; error: Tcl_FreeParse(parsePtr); return TCL_ERROR; } /* *---------------------------------------------------------------------- * * CommandComplete -- * * This procedure is shared by TclCommandComplete and * Tcl_ObjCommandcoComplete; it does all the real work of seeing * whether a script is complete * * Results: * 1 is returned if the script is complete, 0 if there are open * delimiters such as " or (. 1 is also returned if there is a * parse error in the script other than unmatched delimiters. * * Side effects: * None. * *---------------------------------------------------------------------- */ static int CommandComplete(script, length) char *script; /* Script to check. */ int length; /* Number of bytes in script. */ { Tcl_Parse parse; char *p, *end; int result; p = script; end = p + length; while (Tcl_ParseCommand((Tcl_Interp *) NULL, p, end - p, 0, &parse) == TCL_OK) { p = parse.commandStart + parse.commandSize; if (*p == 0) { break; } Tcl_FreeParse(&parse); } if (parse.incomplete) { result = 0; } else { result = 1; } Tcl_FreeParse(&parse); return result; } /* *---------------------------------------------------------------------- * * Tcl_CommandComplete -- * * Given a partial or complete Tcl script, this procedure * determines whether the script is complete in the sense * of having matched braces and quotes and brackets. * * Results: * 1 is returned if the script is complete, 0 otherwise. * 1 is also returned if there is a parse error in the script * other than unmatched delimiters. * * Side effects: * None. * *---------------------------------------------------------------------- */ int Tcl_CommandComplete(script) char *script; /* Script to check. */ { return CommandComplete(script, (int) strlen(script)); } /* *---------------------------------------------------------------------- * * TclObjCommandComplete -- * * Given a partial or complete Tcl command in a Tcl object, this * procedure determines whether the command is complete in the sense of * having matched braces and quotes and brackets. * * Results: * 1 is returned if the command is complete, 0 otherwise. * * Side effects: * None. * *---------------------------------------------------------------------- */ int TclObjCommandComplete(objPtr) Tcl_Obj *objPtr; /* Points to object holding script * to check. */ { char *script; int length; script = Tcl_GetStringFromObj(objPtr, &length); return CommandComplete(script, length); } /* *---------------------------------------------------------------------- * * TclIsLocalScalar -- * * Check to see if a given string is a legal scalar variable * name with no namespace qualifiers or substitutions. * * Results: * Returns 1 if the variable is a local scalar. * * Side effects: * None. * *---------------------------------------------------------------------- */ int TclIsLocalScalar(src, len) CONST char *src; int len; { CONST char *p; CONST char *lastChar = src + (len - 1); for (p = src; p <= lastChar; p++) { if ((CHAR_TYPE(*p) != TYPE_NORMAL) && (CHAR_TYPE(*p) != TYPE_COMMAND_END)) { /* * TCL_COMMAND_END is returned for the last character * of the string. By this point we know it isn't * an array or namespace reference. */ return 0; } if (*p == '(') { if (*lastChar == ')') { /* we have an array element */ return 0; } } else if (*p == ':') { if ((p != lastChar) && *(p+1) == ':') { /* qualified name */ return 0; } } } return 1; }
[ "magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91" ]
[ [ [ 1, 2334 ] ] ]
3e0c5f9f52fb9c1a1cd381fdaaa06b646f271ebb
f4da78dbfbe129336ab63b36c94fb23747aa9cf3
/giz_sdl/stdafx.cpp
41202504fdb5c8e4e1362d5f9261170e971eb188
[]
no_license
zincsamael/psx4m
caf4b29a7b6e89834cdb8f5d0c6d1f50876e7473
822b7e8ed8574c01fce1d5b6c07278004ffcee46
refs/heads/master
2020-04-10T03:51:52.403952
2010-08-01T22:11:17
2010-08-01T22:11:17
10,868,599
1
0
null
null
null
null
UTF-8
C++
false
false
294
cpp
// stdafx.cpp : source file that includes just the standard includes // psx4ppc.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h" // TODO: reference any additional headers you need in STDAFX.H // and not in this file
[ [ [ 1, 8 ] ] ]
9a9f8bfd13806599454a2e4c0b2527c90d5f473f
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/mpl/preprocessed/set/set40_c.cpp
4e530faf7496420cee9a7b1957e6299c8f3d1079
[ "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
willrebuild/flyffsf
e5911fb412221e00a20a6867fd00c55afca593c7
d38cc11790480d617b38bb5fc50729d676aef80d
refs/heads/master
2021-01-19T20:27:35.200154
2011-02-10T12:34:43
2011-02-10T12:34:43
32,710,780
3
0
null
null
null
null
UTF-8
C++
false
false
512
cpp
// Copyright Aleksey Gurtovoy 2003-2004 // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // See http://www.boost.org/libs/mpl for documentation. // $Source: /cvsroot/boost/boost/libs/mpl/preprocessed/set/set40_c.cpp,v $ // $Date: 2006/06/12 05:11:54 $ // $Revision: 1.2.6.1 $ #define BOOST_MPL_PREPROCESSING_MODE #include <boost/config.hpp> #include <boost/mpl/set/set40_c.hpp>
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 16 ] ] ]
4e7563ed0d390257cce9fdd844803d19e5103e2a
c7120eeec717341240624c7b8a731553494ef439
/src/cplusplus/freezone-samp/src/core/npcs_i.hpp
3e69468f8c8b5249296a9789f918c4ef8ef2982b
[]
no_license
neverm1ndo/gta-paradise-sa
d564c1ed661090336621af1dfd04879a9c7db62d
730a89eaa6e8e4afc3395744227527748048c46d
refs/heads/master
2020-04-27T22:00:22.221323
2010-09-04T19:02:28
2010-09-04T19:02:28
174,719,907
1
0
null
2019-03-09T16:44:43
2019-03-09T16:44:43
null
UTF-8
C++
false
false
444
hpp
#ifndef NPCS_I_HPP #define NPCS_I_HPP #include "npc_fwd.hpp" #include "core/samp/samp_events_t.hpp" namespace npcs_events { struct on_npc_connect_i { virtual void on_npc_connect(npc_ptr_t const& npc_ptr) = 0; }; struct on_npc_disconnect_i { virtual void on_npc_disconnect(npc_ptr_t const& npc_ptr, samp::player_disconnect_reason reason) = 0; }; } // namespace npcs_events { #endif // NPCS_I_HPP
[ "dimonml@19848965-7475-ded4-60a4-26152d85fbc5" ]
[ [ [ 1, 15 ] ] ]
01c9d0669e599e156d75eac0733ea6fd8e04fc77
c5ecda551cefa7aaa54b787850b55a2d8fd12387
/src/UILayer/ToolbarCtrls/TbcAdvance.cpp
0cdb362daf3e0f84a0ece80707dcf324034644c2
[]
no_license
firespeed79/easymule
b2520bfc44977c4e0643064bbc7211c0ce30cf66
3f890fa7ed2526c782cfcfabb5aac08c1e70e033
refs/heads/master
2021-05-28T20:52:15.983758
2007-12-05T09:41:56
2007-12-05T09:41:56
null
0
0
null
null
null
null
GB18030
C++
false
false
3,589
cpp
// TbcAdvance.cpp : 实现文件 // #include "stdafx.h" #include "TbcAdvance.h" #include ".\tbcadvance.h" #include "eMule.h" #include "MenuCmds.h" #include "UserMsgs.h" #include "WndMgr.h" #include "StrSafe.h" // CTbcAdvance IMPLEMENT_DYNAMIC(CTbcAdvance, CToolBarCtrlZ) CTbcAdvance::CTbcAdvance() { m_iConnectServerStatus = 0; } CTbcAdvance::~CTbcAdvance() { } BEGIN_MESSAGE_MAP(CTbcAdvance, CToolBarCtrlZ) ON_WM_CREATE() ON_WM_DESTROY() ON_MESSAGE(UM_TB_CHANGE_CONN_STATE, OnTbEnableButton) END_MESSAGE_MAP() void CTbcAdvance::Localize() { ToolBarCtrl_SetText(this, 0, GetConnectServerText()); ToolBarCtrl_SetText(this, 1, GetResString(IDS_WIZ1)); ToolBarCtrl_SetText(this, 2, GetResString(IDS_OPTIONS)); if (NULL != GetParent()) GetParent()->SendMessage(WM_SIZE); } void CTbcAdvance::InitImageList() { AddImageIcon(_T("PNG_CONNECT_SVR")); AddImageIcon(_T("PNG_WIZARD")); AddImageIcon(_T("PNG_OPTIONS")); AddImageIcon(_T("PNG_DISCONNECT_SVR")); AddDisableImageIcon(_T("PNG_CONNECT_SVR")); AddDisableImageIcon(_T("PNG_WIZARD")); AddDisableImageIcon(_T("PNG_OPTIONS")); AddDisableImageIcon(_T("PNG_DISCONNECT_SVR")); } CString CTbcAdvance::GetConnectServerText() { switch(m_iConnectServerStatus) { case 0: // Disconnected return GetResString(IDS_TB_CONNECT_SERVER); break; case 1: // Connecting return GetResString(IDS_TB_CANCEL_CONNECTING); break; case 2: // Connected return GetResString(IDS_TB_DISCONNECT_SERVER); break; default: return CString(_T("")); } } // CTbcAdvance 消息处理程序 int CTbcAdvance::OnCreate(LPCREATESTRUCT lpCreateStruct) { if (CToolBarCtrlZ::OnCreate(lpCreateStruct) == -1) return -1; // TODO: 在此添加您专用的创建代码 theWndMgr.SetWndHandle(CWndMgr::WI_ADVANCE_TOOLBAR, GetSafeHwnd()); InitImageList(); AddSingleString(GetResString(IDS_TB_CONNECT_SERVER)); AddSingleString(GetResString(IDS_WIZ1)); AddSingleString(GetResString(IDS_OPTIONS)); TBBUTTON tbb[BUTTON_COUNT]; CString str; tbb[0].idCommand = MP_CONNECT; tbb[1].idCommand = MP_HM_1STSWIZARD; tbb[2].idCommand = MP_HM_PREFS; int i = 0; for (i = 0; i < BUTTON_COUNT; i++) { tbb[i].iString = i; tbb[i].iBitmap = i; tbb[i].fsState = TBSTATE_ENABLED; tbb[i].fsStyle = TBSTYLE_BUTTON | BTNS_AUTOSIZE; } AddButtons(BUTTON_COUNT, tbb); Localize(); return 0; } void CTbcAdvance::OnDestroy() { CToolBarCtrlZ::OnDestroy(); // TODO: 在此处添加消息处理程序代码 theWndMgr.SetWndHandle(CWndMgr::WI_ADVANCE_TOOLBAR, NULL); } LRESULT CTbcAdvance::OnTbEnableButton(WPARAM wParam, LPARAM /*lParam*/) { if (m_iConnectServerStatus == (int) wParam) return 0; CString strText; TBBUTTONINFO tbbi; ZeroMemory(&tbbi, sizeof(tbbi)); tbbi.cbSize = sizeof(tbbi); tbbi.dwMask = TBIF_BYINDEX | TBIF_COMMAND | TBIF_IMAGE | TBIF_TEXT; switch (wParam) { case 0: // Disconnected tbbi.idCommand = MP_CONNECT; tbbi.iImage = 0; break; case 1: // Connecting tbbi.idCommand = MP_DISCONNECT; tbbi.iImage = BUTTON_COUNT; break; case 2: // Connected tbbi.idCommand = MP_DISCONNECT; tbbi.iImage = BUTTON_COUNT; break; default: return 0; } m_iConnectServerStatus = wParam; strText = GetConnectServerText(); tbbi.pszText = strText.LockBuffer(); tbbi.cchText = strText.GetLength(); SetButtonInfo(0, &tbbi); strText.UnlockBuffer(); if (NULL != GetParent()) GetParent()->SendMessage(WM_SIZE); return 0; }
[ "LanceFong@4a627187-453b-0410-a94d-992500ef832d" ]
[ [ [ 1, 160 ] ] ]
08d93884633159048d995f22e5559edc8269c20a
c5534a6df16a89e0ae8f53bcd49a6417e8d44409
/trunk/Samples/NPR/App.h
7638538854fb190425253c004b6af67872a2d992
[]
no_license
svn2github/ngene
b2cddacf7ec035aa681d5b8989feab3383dac012
61850134a354816161859fe86c2907c8e73dc113
refs/heads/master
2023-09-03T12:34:18.944872
2011-07-27T19:26:04
2011-07-27T19:26:04
78,163,390
2
0
null
null
null
null
UTF-8
C++
false
false
1,047
h
/* --------------------------------------------------------------------------- This source file is part of nGENE Tech. Copyright (c) 2006- Wojciech Toman This program is free software. File: App.h Version: 0.01 Info: This demo presents 2D non-photorealistic rendering. --------------------------------------------------------------------------- */ #pragma once #include "FrameworkWin32.h" #include "ScenePartitionerQuadTree.h" #include "MyWindow.h" #include "MyInputListener.h" using namespace nGENE::Application; using nGENE::ScenePartitionerQuadTree; /** Demo application presenting some basic techniques available through nGENE Tech. */ class App: public FrameworkWin32 { protected: ScenePartitionerQuadTree* m_pPartitioner; GUIFont* m_pFont; MyWindow m_Window; // Post process material SPriorityMaterial postWaterColor; SPriorityMaterial postPencil; MyInputListener* m_pInputListener; void cleanup(); public: App(); virtual ~App(); void createApplication(); };
[ "Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57" ]
[ [ [ 1, 53 ] ] ]
c2fad802a816e4e84b77a8f05a072e72b9c8b4c3
4b0f51aeecddecf3f57a29ffa7a184ae48f1dc61
/CleanProject/MyGUI/include/MyGUI_SubWidgetManager.h
debfa48b81e4026ca986755fc5ac782144deadd7
[]
no_license
bahao247/apeengine2
56560dbf6d262364fbc0f9f96ba4231e5e4ed301
f2617b2a42bdf2907c6d56e334c0d027fb62062d
refs/heads/master
2021-01-10T14:04:02.319337
2009-08-26T08:23:33
2009-08-26T08:23:33
45,979,392
0
1
null
null
null
null
UTF-8
C++
false
false
2,169
h
/*! @file @author Albert Semenov @date 11/2007 @module *//* This file is part of MyGUI. MyGUI is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. MyGUI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with MyGUI. If not, see <http://www.gnu.org/licenses/>. */ #ifndef __MYGUI_SUB_WIDGET_MANAGER_H__ #define __MYGUI_SUB_WIDGET_MANAGER_H__ #include "MyGUI_Prerequest.h" #include "MyGUI_Instance.h" #include "MyGUI_XmlDocument.h" #include "MyGUI_ICroppedRectangle.h" #include "MyGUI_ISubWidgetFactory.h" #include "MyGUI_SubSkin.h" #include "MyGUI_MainSkin.h" #include "MyGUI_SimpleText.h" #include "MyGUI_EditText.h" #include "MyGUI_RawRect.h" #include "MyGUI_TileRect.h" namespace MyGUI { class MYGUI_EXPORT SubWidgetManager { MYGUI_INSTANCE_HEADER(SubWidgetManager); public: void initialise(); void shutdown(); // создает сабвиджет используя фабрику ISubWidget * createSubWidget(const SubWidgetInfo &_info, ICroppedRectangle * _parent); void registerFactory(ISubWidgetFactory * _factory) { mFactoryList.push_back(_factory); } StateInfo * getStateData(const std::string & _factory, xml::ElementPtr _node, xml::ElementPtr _root, Version _version); protected: std::list<ISubWidgetFactory*> mFactoryList; SubWidgetFactory<SubSkin> * mFactorySubSkin; SubWidgetFactory<MainSkin> * mFactoryMainSkin; SubWidgetFactory<SimpleText> * mFactorySimpleText; SubWidgetFactory<EditText> * mFactoryEditText; SubWidgetFactory<RawRect> * mFactoryRawRect; SubWidgetFactory<TileRect> * mFactoryTileRect; }; } // namespace MyGUI #endif // __MYGUI_SUB_WIDGET_MANAGER_H__
[ "pablosn@06488772-1f9a-11de-8b5c-13accb87f508" ]
[ [ [ 1, 73 ] ] ]
8b8ebe3011b63023aa352bb2ea3d696df8f4c60c
2f77d5232a073a28266f5a5aa614160acba05ce6
/01.DevelopLibrary/SaveSmsTest/InfoCenterOfSmartPhone/UiEditControl.cpp
eb96872b59b1bc13d27f8483815cde4161b61092
[]
no_license
radtek/mobilelzz
87f2d0b53f7fd414e62c8b2d960e87ae359c81b4
402276f7c225dd0b0fae825013b29d0244114e7d
refs/heads/master
2020-12-24T21:21:30.860184
2011-03-26T02:19:47
2011-03-26T02:19:47
58,142,323
0
0
null
null
null
null
GB18030
C++
false
false
1,501
cpp
#include"stdafx.h" #include <mzfc_inc.h> #include"UiEditControl.h" #include"NewSmsWnd.h" #include"ContactorsWnd.h" void UiEditControl::OnFocused (UiWin *pWinPrev) { } CContactorsWnd clContactorsWnd; //zds 2010/03/21 19:39 int UiEditControl::OnLButtonUp ( UINT fwKeys, int xPos, int yPos ) { // MzCloseSip(); int i = MZ_ANIMTYPE_SCROLL_BOTTOM_TO_TOP_2; m_lFlag = 1; clContactorsWnd.SetParent(this); RECT rcWork = MzGetWorkArea(); clContactorsWnd.Create(rcWork.left,rcWork.top,RECT_WIDTH(rcWork),RECT_HEIGHT(rcWork), 0, 0, WS_POPUP); // 设置窗口切换动画(弹出时的动画) //clContactorsWnd.SetAnimateType_Show(i); // 设置窗口切换动画(结束时的动画) //clContactorsWnd.SetAnimateType_Hide(i+1); int nRet = clContactorsWnd.DoModal(); int b = 2; return 0; } //zds 2010/03/21 19:39 void UiEditControl::SetParent(void* pParent) { m_pParent = pParent; } void UiEditControl::UpdateData( long lFlag ) { if(lFlag == 0) { //m_lFlag = 0; } else { long lReciversCount = g_ReciversList.GetItemCount(); wchar_t wcsReciversName[512] = L""; wcscat(wcsReciversName, L"收件人:" ); for(int i = 0; i < lReciversCount; i++) { wcscat(wcsReciversName, g_ReciversList.GetItem(i)->StringTitle ); wcscat(wcsReciversName, L";" ); } SetText(wcsReciversName); //Update(); } ReleaseCapture(); //((CNewSmsWnd*)m_pParent)->UpdateData(pRecivers, lReciversCount); }
[ [ [ 1, 66 ] ] ]
a4c6611962aa982021a61d1dc23d9eeb4ea53a40
b14d5833a79518a40d302e5eb40ed5da193cf1b2
/cpp/extern/crypto++/5.2.1/tiger.cpp
cd4b1c79ced33d83d907b53ac98c25da4d6f536d
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-cryptopp" ]
permissive
andyburke/bitflood
dcb3fb62dad7fa5e20cf9f1d58aaa94be30e82bf
fca6c0b635d07da4e6c7fbfa032921c827a981d6
refs/heads/master
2016-09-10T02:14:35.564530
2011-11-17T09:51:49
2011-11-17T09:51:49
2,794,411
1
0
null
null
null
null
UTF-8
C++
false
false
2,193
cpp
// tiger.cpp - written and placed in the public domain by Wei Dai #include "pch.h" #include "tiger.h" #include "misc.h" #ifdef WORD64_AVAILABLE NAMESPACE_BEGIN(CryptoPP) void Tiger::InitState(HashWordType *state) { state[0] = W64LIT(0x0123456789ABCDEF); state[1] = W64LIT(0xFEDCBA9876543210); state[2] = W64LIT(0xF096A5B4C3B2E187); } void Tiger::TruncatedFinal(byte *hash, unsigned int size) { ThrowIfInvalidTruncatedSize(size); PadLastBlock(56, 0x01); CorrectEndianess(m_data, m_data, 56); m_data[7] = GetBitCountLo(); Transform(m_digest, m_data); CorrectEndianess(m_digest, m_digest, DigestSize()); memcpy(hash, m_digest, size); Restart(); // reinit for next use } #define t1 (table) #define t2 (table+256) #define t3 (table+256*2) #define t4 (table+256*3) #define round(a,b,c,x,mul) \ c ^= x; \ a -= t1[GETBYTE(c,0)] ^ t2[GETBYTE(c,2)] ^ t3[GETBYTE(c,4)] ^ t4[GETBYTE(c,6)]; \ b += t4[GETBYTE(c,1)] ^ t3[GETBYTE(c,3)] ^ t2[GETBYTE(c,5)] ^ t1[GETBYTE(c,7)]; \ b *= mul #define pass(a,b,c,mul,X) \ round(a,b,c,X[0],mul); \ round(b,c,a,X[1],mul); \ round(c,a,b,X[2],mul); \ round(a,b,c,X[3],mul); \ round(b,c,a,X[4],mul); \ round(c,a,b,X[5],mul); \ round(a,b,c,X[6],mul); \ round(b,c,a,X[7],mul) #define key_schedule(Y,X) \ Y[0] = X[0] - (X[7]^W64LIT(0xA5A5A5A5A5A5A5A5)); \ Y[1] = X[1] ^ Y[0]; \ Y[2] = X[2] + Y[1]; \ Y[3] = X[3] - (Y[2] ^ ((~Y[1])<<19)); \ Y[4] = X[4] ^ Y[3]; \ Y[5] = X[5] + Y[4]; \ Y[6] = X[6] - (Y[5] ^ ((~Y[4])>>23)); \ Y[7] = X[7] ^ Y[6]; \ Y[0] += Y[7]; \ Y[1] -= Y[0] ^ ((~Y[7])<<19); \ Y[2] ^= Y[1]; \ Y[3] += Y[2]; \ Y[4] -= Y[3] ^ ((~Y[2])>>23); \ Y[5] ^= Y[4]; \ Y[6] += Y[5]; \ Y[7] -= Y[6] ^ W64LIT(0x0123456789ABCDEF) void Tiger::Transform (word64 *digest, const word64 *X) { word64 a = digest[0]; word64 b = digest[1]; word64 c = digest[2]; word64 Y[8]; pass(a,b,c,5,X); key_schedule(Y,X); pass(c,a,b,7,Y); key_schedule(Y,Y); pass(b,c,a,9,Y); digest[0] = a ^ digest[0]; digest[1] = b - digest[1]; digest[2] = c + digest[2]; memset(Y, 0, sizeof(Y)); } NAMESPACE_END #endif // WORD64_AVAILABLE
[ [ [ 1, 95 ] ] ]
95f67c3eb7c652be76abbcc8d9683a95c757c004
62874cd4e97b2cfa74f4e507b798f6d5c7022d81
/src/Properties/GenericProperty.h
a1d841a7871955c7a478789007b3be129dcae26b
[]
no_license
rjaramih/midi-me
6a4047e5f390a5ec851cbdc1b7495b7fe80a4158
6dd6a1a0111645199871f9951f841e74de0fe438
refs/heads/master
2021-03-12T21:31:17.689628
2011-07-31T22:42:05
2011-07-31T22:42:05
36,944,802
0
0
null
null
null
null
UTF-8
C++
false
false
1,138
h
#ifndef MIDIME_GENERICPROPERTY_H #define MIDIME_GENERICPROPERTY_H // Includes #include "global.h" #include "Property.h" #include "FastDelegate.h" namespace MidiMe { // Forward declarations /** This class is a templated version of a generic property. It can be used to easily create a lot of property types. */ template<class GetType, class SetType = GetType> class PROPERTIES_API GenericProperty: public Property { public: // Typedefs typedef fastdelegate::FastDelegate0<GetType> GetFunctor; typedef fastdelegate::FastDelegate1<SetType> SetFunctor; protected: // Member variables GetFunctor m_getFunctor; SetFunctor m_setFunctor; public: // Constructors and destructor GenericProperty(const string &name, const GetFunctor &getter, const SetFunctor &setter) : Property(name), m_getFunctor(getter), m_setFunctor(setter) {} virtual ~GenericProperty() {} // Get/set GetType getValue() const { return m_getFunctor(); } void setValue(SetType value) { if(value != getValue()) { m_setFunctor(value); fireChanged(); } } }; } #endif // MIDIME_GENERICPROPERTY_H
[ "Jeroen.Dierckx@d8a2fbcc-2753-0410-82a0-8bc2cd85795f" ]
[ [ [ 1, 41 ] ] ]
43dd3f80c48178a8619da9f6705c8c342faaf5aa
ef356dbd697546b63c1c4c866db4f410ecf1c226
/typedefs.hpp
f99e41a6c1327b53a394b925e91eaa4a322d8758
[]
no_license
jondos/Mix
d5e7ab0f6ca4858b300341fb17e56af9106ffb65
8e0ebd9490542472197eca4b7c9974618df6f1de
refs/heads/master
2023-09-03T12:55:23.983398
2010-01-04T14:52:26
2010-01-04T14:52:26
425,933,032
0
0
null
null
null
null
UTF-8
C++
false
false
9,645
hpp
/* Copyright (c) 2000, The JAP-Team All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of the University of Technology Dresden, Germany nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE */ #ifndef __TYEDEFS__ #define __TYEDEFS__ enum NetworkType {UNKNOWN_NETWORKTYPE,RAW_TCP,RAW_UNIX,SSL_TCP,SSL_UNIX, HTTP_TCP}; typedef UINT32 HCHANNEL; #define MIX_PAYLOAD_HTTP 0 #define MIX_PAYLOAD_SOCKS 1 #define MIXPACKET_SIZE 998 #define CHANNEL_DATA 0x00 #define CHANNEL_OPEN 0x08 #define CHANNEL_TIMESTAMPS_UP 0x60 #define CHANNEL_TIMESTAMPS_DOWN 0x90 #define CHANNEL_CLOSE 0x01 #define CHANNEL_SUSPEND 0x02 #define CHANNEL_RESUME 0x04 #define CHANNEL_DUMMY 0x10 #ifdef LOG_CRIME #define CHANNEL_SIG_CRIME 0x20 #define CHANNEL_SIG_CRIME_ID_MASK 0x0000FF00 #define CHANNEL_ALLOWED_FLAGS (CHANNEL_OPEN|CHANNEL_CLOSE|CHANNEL_SUSPEND|CHANNEL_RESUME|CHANNEL_TIMESTAMPS_UP|CHANNEL_TIMESTAMPS_DOWN|CHANNEL_SIG_CRIME|CHANNEL_SIG_CRIME_ID_MASK) #else #define CHANNEL_SIG_CRIME 0x0 #define CHANNEL_SIG_CRIME_ID_MASK 0x0 #ifdef NEW_FLOW_CONTROL #define CHANNEL_ALLOWED_FLAGS (CHANNEL_OPEN|CHANNEL_CLOSE|CHANNEL_TIMESTAMPS_UP|CHANNEL_TIMESTAMPS_DOWN) #else #define CHANNEL_ALLOWED_FLAGS (CHANNEL_OPEN|CHANNEL_CLOSE|CHANNEL_SUSPEND|CHANNEL_RESUME|CHANNEL_TIMESTAMPS_UP|CHANNEL_TIMESTAMPS_DOWN) #endif #endif #define NEW_FLOW_CONTROL_FLAG 0x8000 #define CONNECTION_ERROR_FLAG 0x01 #define DATA_SIZE 992 #define PAYLOAD_SIZE 989 #define PAYLOAD_LEN_MASK 0x03FF; #if (defined(WIN32) ||defined(__sgi))&&!defined(__GNUC__) #define DO_PACKED #else #define DO_PACKED __attribute__ ((__packed__)) #endif #if (defined(WIN32) ||defined(__sgi))&&!defined(__GNUC__) #pragma pack( push, t_MixPacket ) #pragma pack(1) struct t_MixPacketPayload { UINT16 len; UINT8 type; UINT8 data[PAYLOAD_SIZE]; }; struct t_MixPacket { HCHANNEL channel; UINT16 flags; union { UINT8 data[DATA_SIZE]; struct t_MixPacketPayload payload; }; }; #pragma pack( pop, t_MixPacket ) #else struct t_MixPacketPayload { UINT16 len; UINT8 type; UINT8 data[PAYLOAD_SIZE]; } __attribute__ ((__packed__)); struct t_MixPacket { HCHANNEL channel; UINT16 flags; union { UINT8 data[DATA_SIZE]; struct t_MixPacketPayload payload; }; } __attribute__ ((__packed__)); // MUXPACKET __attribute__ ((__packed__)); #endif //WIN32 typedef t_MixPacket MIXPACKET; #ifdef DATA_RETENTION_LOG #if (defined(WIN32) ||defined(__sgi))&&!defined(__GNUC__) #pragma pack( push, t_DataRetentionLogEntry ) #pragma pack(1) #endif struct __t__data_retention_log_entry { UINT32 t_in; UINT32 t_out; union t_union_entity { struct t_first_mix_data_retention_log_entry { HCHANNEL channelid; UINT8 ip_in[4]; UINT16 port_in; } DO_PACKED first; struct t_last_mix_data_retention_log_entry { HCHANNEL channelid; UINT8 ip_out[4]; UINT16 port_out; } DO_PACKED last; } DO_PACKED entity; } #if (defined(WIN32) ||defined(__sgi))&&!defined(__GNUC__) ; #pragma pack( pop, t_DataRetentionLogEntry ) #else DO_PACKED ; #endif typedef struct __t__data_retention_log_entry t_dataretentionLogEntry; #endif //DATA_RETENION_LOG //For that we store in our packet queue... //normally this is just the packet struct t_queue_entry { MIXPACKET packet; #if defined(DATA_RETENTION_LOG) t_dataretentionLogEntry dataRetentionLogEntry; #endif #if defined (LOG_PACKET_TIMES) || defined (LOG_CHANNEL) UINT64 timestamp_proccessing_start; UINT64 timestamp_proccessing_start_OP; UINT64 timestamp_proccessing_end; #endif #if defined (LOG_PACKET_TIMES) //without send/receive or queueing times UINT64 timestamp_proccessing_end_OP; #ifdef USE_POOL UINT64 pool_timestamp_in; UINT64 pool_timestamp_out; #endif #endif }; typedef struct t_queue_entry tQueueEntry; //for that we store in our pool //normaly this is just the packet typedef tQueueEntry tPoolEntry; ///the Replaytimestamp type struct t_replay_timestamp { UINT interval; //the current interval number UINT offset; //seconds since start of this interval }; typedef struct t_replay_timestamp tReplayTimestamp; struct t_mix_parameters { //stores the mix id of the mix UINT8* m_strMixID; // stores the local time in seconds since epoch for interval '0' for this mix UINT32 m_u32ReplayOffset; UINT16 m_u32ReplayBase; }; typedef struct t_mix_parameters tMixParameters; /** * These flags are used to represent the state * of the payment */ /** new user, not yet authenticated */ #define AUTH_NEW 0x0 /** user has sent an account certificate */ #define AUTH_GOT_ACCOUNTCERT 0x1 /** format and signature of all received certificates was OK */ #define AUTH_ACCOUNT_OK 0x2 /** First CC from client has not been settled yet. */ #define AUTH_WAITING_FOR_FIRST_SETTLED_CC 0x4 /** we have sent one or two CC requests */ #define AUTH_SENT_CC_REQUEST 0x20 /** A database error occured (internal or in the BI) */ #define AUTH_DATABASE 0x40 /** Account has been blocked temporarly */ #define AUTH_BLOCKED 0x80 /** we have sent one request for an accountcertificate */ #define AUTH_SENT_ACCOUNT_REQUEST 0x100 #define AUTH_HARD_LIMIT_REACHED 0x200 /** the user tried to fake something */ #define AUTH_FAKE 0x400 /** we have sent a challenge and not yet received the response */ #define AUTH_CHALLENGE_SENT 0x800 /** the account is empty */ #define AUTH_ACCOUNT_EMPTY 0x1000 /** a fatal error occured earlier */ #define AUTH_FATAL_ERROR 0x2000 #define AUTH_OUTDATED_CC 0x4000 /** Account does not exist */ #define AUTH_INVALID_ACCOUNT 0x8000 // AI is waiting for a necessary message from JAP (e.g. response to challenge) #define AUTH_TIMEOUT_STARTED 0x10000 #define AUTH_MULTIPLE_LOGIN 0x20000 #define AUTH_UNKNOWN 0x40000 // we settled at least one CC for this account in this session #define AUTH_SETTLED_ONCE 0x80000 /* * The user corresponding to this entry has closed the connection. * Delete the entry as soon as possible. */ #define AUTH_DELETE_ENTRY 0x80000 #define AUTH_LOGIN_NOT_FINISHED 0x100000 #define AUTH_LOGIN_FAILED 0x200000 #define AUTH_LOGIN_SKIP_SETTLEMENT 0x400000 class CASignature; class CAAccountingControlChannel; class CAMutex; struct t_fmhashtableentry; /** * Structure that holds all per-user payment information * Included in CAFirstMixChannelList (struct fmHashTableEntry) */ struct t_accountinginfo { CAMutex* mutex; /** we store the challenge here to verify the response later */ UINT8 * pChallenge; /** the signature verifying instance for this user */ CASignature * pPublicKey; /** The number of packets transfered. */ UINT64 sessionPackets; /** the number of bytes that was transferred (as counted by the AI) Elmar: since last CC, or in total? */ UINT64 transferredBytes; /** the number of bytes that was confirmed by the account user */ UINT64 confirmedBytes; /** The bytes the user could confirm in the last CC sent to him. */ UINT64 bytesToConfirm; /** the user's account number */ UINT64 accountNumber; /** The same value as in fmHashTableEntry. */ UINT64 userID; struct t_fmhashtableentry *ownerRef; /** a pointer to the user-specific control channel object */ CAAccountingControlChannel* pControlChannel; /** Flags, see above AUTH_* */ UINT32 authFlags; /** timestamp when last HardLimit was reached */ SINT32 lastHardLimitSeconds; /** timestamp when last PayRequest was sent */ SINT32 challengeSentSeconds; /** ID of payment instance belonging to this account */ UINT8* pstrBIID; //time at which the timeout for waiting for the account certificate has been started SINT32 authTimeoutStartSeconds; // the number of references to this entry in the ai queue UINT32 nrInQueue; // new JonDo clients will send their version number as during challenge-response. UINT8* clientVersion; }; typedef struct t_accountinginfo tAiAccountingInfo; #endif
[ "rolf@f4013887-1060-43d1-a937-9d2a4c6f27f8" ]
[ [ [ 1, 335 ] ] ]
8a5ad6ca8a536012139f5bdc10a1cffccbdc639c
85d9531c984cd9ffc0c9fe8058eb1210855a2d01
/QxOrm/include/QxTraits/is_smart_ptr.h
df6745d7d7ec915fdc54554160dac1ddb8f4500f
[]
no_license
padenot/PlanningMaker
ac6ece1f60345f857eaee359a11ee6230bf62226
d8aaca0d8cdfb97266091a3ac78f104f8d13374b
refs/heads/master
2020-06-04T12:23:15.762584
2011-02-23T21:36:57
2011-02-23T21:36:57
1,125,341
0
1
null
null
null
null
UTF-8
C++
false
false
2,944
h
/**************************************************************************** ** ** http://www.qxorm.com/ ** http://sourceforge.net/projects/qxorm/ ** Original file by Lionel Marty ** ** This file is part of the QxOrm library ** ** This software is provided 'as-is', without any express or implied ** warranty. In no event will the authors be held liable for any ** damages arising from the use of this software. ** ** GNU Lesser General Public License Usage ** This file must be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file 'license.lgpl.txt' included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** If you have questions regarding the use of this file, please contact : ** [email protected] ** ****************************************************************************/ #ifndef _QX_IS_SMART_PTR_H_ #define _QX_IS_SMART_PTR_H_ #ifdef _MSC_VER #pragma once #endif #include <boost/mpl/if.hpp> #include <boost/mpl/or.hpp> #include <boost/mpl/logical.hpp> #include <QxTraits/is_boost_intrusive_ptr.h> #include <QxTraits/is_boost_scoped_ptr.h> #include <QxTraits/is_boost_shared_ptr.h> #include <QxTraits/is_boost_weak_ptr.h> #include <QxTraits/is_qt_shared_data_ptr.h> #include <QxTraits/is_qt_scoped_ptr.h> #include <QxTraits/is_qt_shared_ptr.h> #include <QxTraits/is_qt_weak_ptr.h> namespace qx { namespace trait { template <typename T> class is_smart_ptr { private: typedef typename boost::mpl::or_< qx::trait::is_boost_intrusive_ptr<T>, qx::trait::is_boost_scoped_ptr<T>, qx::trait::is_boost_shared_ptr<T>, qx::trait::is_boost_weak_ptr<T> >::type cond_is_boost_smart_ptr; typedef typename boost::mpl::or_< typename qx::trait::is_smart_ptr<T>::cond_is_boost_smart_ptr, qx::trait::is_qt_scoped_ptr<T>, qx::trait::is_qt_shared_ptr<T>, qx::trait::is_qt_weak_ptr<T>, qx::trait::is_qt_shared_data_ptr<T> >::type cond_is_smart_ptr; typedef typename boost::mpl::if_< typename qx::trait::is_smart_ptr<T>::cond_is_smart_ptr, boost::mpl::true_, boost::mpl::false_ >::type type_is_smart_ptr; public: enum { value = qx::trait::is_smart_ptr<T>::type_is_smart_ptr::value }; typedef typename qx::trait::is_smart_ptr<T>::type_is_smart_ptr type; }; } // namespace trait } // namespace qx #endif // _QX_IS_SMART_PTR_H_
[ [ [ 1, 81 ] ] ]
b34e791996e87fdc4f1fdd63a1d88d447838ee3c
4497c10f3b01b7ff259f3eb45d0c094c81337db6
/Retargeting/Shifmap/Version01/ShiftMapVisualizer.h
b158a6908a2090705c2718bc18912463e12f3714
[]
no_license
liuguoyou/retarget-toolkit
ebda70ad13ab03a003b52bddce0313f0feb4b0d6
d2d94653b66ea3d4fa4861e1bd8313b93cf4877a
refs/heads/master
2020-12-28T21:39:38.350998
2010-12-23T16:16:59
2010-12-23T16:16:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
349
h
#pragma once #include "cv.h" #include "Label.h" #include "highgui.h" // this class is to visualize the shiftmap result class ShiftMapVisualizer { public: ShiftMapVisualizer(void); ~ShiftMapVisualizer(void); void Visualize(CvMat* labelMap, IplImage* source, IplImage* map, CvSize shiftSize); int ComputeEnergy(CvMat* labelMap); };
[ "kidphys@aeedd7dc-6096-11de-8dc1-e798e446b60a" ]
[ [ [ 1, 14 ] ] ]
84dbd75077b35a7acd8ceb31927cfbecce7071e1
9566086d262936000a914c5dc31cb4e8aa8c461c
/EnigmaProtocol/Messages/SkillResponseMessage.hpp
1c9389fcbd44ed372e4abc6cff2c5da1dd56b2b1
[]
no_license
pazuzu156/Enigma
9a0aaf0cd426607bb981eb46f5baa7f05b66c21f
b8a4dfbd0df206e48072259dbbfcc85845caad76
refs/heads/master
2020-06-06T07:33:46.385396
2011-12-19T03:14:15
2011-12-19T03:14:15
3,023,618
1
0
null
null
null
null
WINDOWS-1252
C++
false
false
1,967
hpp
#ifndef SKILLRESPONSEMESSAGE_HPP_INCLUDED #define SKILLRESPONSEMESSAGE_HPP_INCLUDED /* Copyright © 2009 Christopher Joseph Dean Schaefer (disks86) This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "MessageContainer.hpp" #include "string.hpp" #include "TargetPreferenceTypes.hpp" namespace Enigma { class DllExport SkillResponseMessage : public MessageContainer { private: protected: public: SkillResponseMessage(Message& message) :MessageContainer(message){}; SkillResponseMessage(); ~SkillResponseMessage(); static const int GetMessageType(){return 43;} static const int GetMessageLength(){return 3;} Enigma::s32 GetSkillId(); void SetSkillId(Enigma::s32 value); void SetSkillId(std::string value); Enigma::s32 GetTargetId(); void SetTargetId(Enigma::s32 value); void SetTargetId(std::string value); Enigma::s32 GetSkillLevel(); void SetSkillLevel(Enigma::s32 value); void SetSkillLevel(std::string value); }; }; #endif // SKILLRESPONSEMESSAGE_HPP_INCLUDED
[ [ [ 1, 56 ] ] ]
d6878b20947cee61871d69e8bedfb8455229097b
12203ea9fe0801d613bbb2159d4f69cab3c84816
/Export/cpp/windows/obj/src/Std.cpp
7450f52d41e5bd64feea5e66bca9f358bc6e6e9d
[]
no_license
alecmce/haxe_game_of_life
91b5557132043c6e9526254d17fdd9bcea9c5086
35ceb1565e06d12c89481451a7bedbbce20fa871
refs/heads/master
2016-09-16T00:47:24.032302
2011-10-10T12:38:14
2011-10-10T12:38:14
2,547,793
0
0
null
null
null
null
UTF-8
C++
false
false
3,489
cpp
#include <hxcpp.h> #ifndef INCLUDED_Std #include <Std.h> #endif Void Std_obj::__construct() { return null(); } Std_obj::~Std_obj() { } Dynamic Std_obj::__CreateEmpty() { return new Std_obj; } hx::ObjectPtr< Std_obj > Std_obj::__new() { hx::ObjectPtr< Std_obj > result = new Std_obj(); result->__construct(); return result;} Dynamic Std_obj::__Create(hx::DynamicArray inArgs) { hx::ObjectPtr< Std_obj > result = new Std_obj(); result->__construct(); return result;} bool Std_obj::is( Dynamic v,Dynamic t){ HX_SOURCE_PUSH("Std_obj::is") HX_SOURCE_POS("C:\\Motion-Twin\\haxe/std/cpp/_std/Std.hx",27) return ::__instanceof(v,t); } STATIC_HX_DEFINE_DYNAMIC_FUNC2(Std_obj,is,return ) ::String Std_obj::string( Dynamic s){ HX_SOURCE_PUSH("Std_obj::string") HX_SOURCE_POS("C:\\Motion-Twin\\haxe/std/cpp/_std/Std.hx",31) return ( (((s == null()))) ? ::String(HX_CSTRING("null")) : ::String(s->toString()) ); } STATIC_HX_DEFINE_DYNAMIC_FUNC1(Std_obj,string,return ) int Std_obj::_int( double x){ HX_SOURCE_PUSH("Std_obj::int") HX_SOURCE_POS("C:\\Motion-Twin\\haxe/std/cpp/_std/Std.hx",35) return ::__int__(x); } STATIC_HX_DEFINE_DYNAMIC_FUNC1(Std_obj,_int,return ) Dynamic Std_obj::parseInt( ::String x){ HX_SOURCE_PUSH("Std_obj::parseInt") HX_SOURCE_POS("C:\\Motion-Twin\\haxe/std/cpp/_std/Std.hx",39) return ::__hxcpp_parse_int(x); } STATIC_HX_DEFINE_DYNAMIC_FUNC1(Std_obj,parseInt,return ) double Std_obj::parseFloat( ::String x){ HX_SOURCE_PUSH("Std_obj::parseFloat") HX_SOURCE_POS("C:\\Motion-Twin\\haxe/std/cpp/_std/Std.hx",43) return ::__hxcpp_parse_float(x); } STATIC_HX_DEFINE_DYNAMIC_FUNC1(Std_obj,parseFloat,return ) int Std_obj::random( int x){ HX_SOURCE_PUSH("Std_obj::random") HX_SOURCE_POS("C:\\Motion-Twin\\haxe/std/cpp/_std/Std.hx",47) return hx::Mod(::rand(),x); } STATIC_HX_DEFINE_DYNAMIC_FUNC1(Std_obj,random,return ) Std_obj::Std_obj() { } void Std_obj::__Mark(HX_MARK_PARAMS) { HX_MARK_BEGIN_CLASS(Std); HX_MARK_END_CLASS(); } Dynamic Std_obj::__Field(const ::String &inName) { switch(inName.length) { case 2: if (HX_FIELD_EQ(inName,"is") ) { return is_dyn(); } break; case 3: if (HX_FIELD_EQ(inName,"int") ) { return _int_dyn(); } break; case 6: if (HX_FIELD_EQ(inName,"string") ) { return string_dyn(); } if (HX_FIELD_EQ(inName,"random") ) { return random_dyn(); } break; case 8: if (HX_FIELD_EQ(inName,"parseInt") ) { return parseInt_dyn(); } break; case 10: if (HX_FIELD_EQ(inName,"parseFloat") ) { return parseFloat_dyn(); } } return super::__Field(inName); } Dynamic Std_obj::__SetField(const ::String &inName,const Dynamic &inValue) { return super::__SetField(inName,inValue); } void Std_obj::__GetFields(Array< ::String> &outFields) { super::__GetFields(outFields); }; static ::String sStaticFields[] = { HX_CSTRING("is"), HX_CSTRING("string"), HX_CSTRING("int"), HX_CSTRING("parseInt"), HX_CSTRING("parseFloat"), HX_CSTRING("random"), String(null()) }; static ::String sMemberFields[] = { String(null()) }; static void sMarkStatics(HX_MARK_PARAMS) { }; Class Std_obj::__mClass; void Std_obj::__register() { Static(__mClass) = hx::RegisterClass(HX_CSTRING("Std"), hx::TCanCast< Std_obj> ,sStaticFields,sMemberFields, &__CreateEmpty, &__Create, &super::__SGetClass(), 0, sMarkStatics); } void Std_obj::__boot() { }
[ [ [ 1, 149 ] ] ]
0ec44a61e0905968d7dc0334aa1265750da1c5f8
21da454a8f032d6ad63ca9460656c1e04440310e
/src/wcpp/io/wsiReader.h
e0a5605358b32bab844cc170218f41d6ecac9327
[]
no_license
merezhang/wcpp
d9879ffb103513a6b58560102ec565b9dc5855dd
e22eb48ea2dd9eda5cd437960dd95074774b70b0
refs/heads/master
2021-01-10T06:29:42.908096
2009-08-31T09:20:31
2009-08-31T09:20:31
46,339,619
0
0
null
null
null
null
UTF-8
C++
false
false
208
h
#ifndef __wsiReader_h__ #define __wsiReader_h__ #include <wcpp.lang/wsiObject.h> class wsiReader : public wsiObject { public: static const ws_iid sIID; }; #endif // __wsReader_h__
[ "xukun0217@98f29a9a-77f1-11de-91f8-ab615253d9e8" ]
[ [ [ 1, 18 ] ] ]
b3de4dccac1f9de787000ffbf0ed3179031e2406
0bab4267636e3b06cb0e73fe9d31b0edd76260c2
/freewar-alpha/src/init_server_connection.cpp
9b151ee11a00f460f191a1bef25e05fa06ac5caf
[]
no_license
BackupTheBerlios/freewar-svn
15fafedeed3ea1d374500d3430ff16b412b2f223
aa1a28f19610dbce12be463d5ccd98f712631bc3
refs/heads/master
2021-01-10T19:54:11.599797
2006-12-10T21:45:11
2006-12-10T21:45:11
40,725,388
0
0
null
null
null
null
UTF-8
C++
false
false
452
cpp
// // init_server_connection.cpp for freewar in /u/ept2/huot_j // // Made by jonathan huot // Login <[email protected]> // // Started on Fri May 7 12:16:06 2004 jonathan huot // Last update Fri May 7 13:52:55 2004 jonathan huot // #include "freewar.h" int init_server_connection(t_trame *req) { // a faire // se connecte sur l'ip / port, et envoi son nickname (informations // presentes dans la req) return (0); }
[ "doomsday@b2c3ed95-53e8-0310-b220-efb193137011" ]
[ [ [ 1, 20 ] ] ]
24f0b937e41b9c020c0c16f3292758d9e18296a0
2dbbca065b62a24f47aeb7ec5cd7a4fd82083dd4
/OUAN/OUAN/Src/GUI/GUIWindow.h
c65950115f1f92c81b1c3f0e1b5df9eafbce7f99
[]
no_license
juanjmostazo/once-upon-a-night
9651dc4dcebef80f0475e2e61865193ad61edaaa
f8d5d3a62952c45093a94c8b073cbb70f8146a53
refs/heads/master
2020-05-28T05:45:17.386664
2010-10-06T12:49:50
2010-10-06T12:49:50
38,101,059
1
1
null
null
null
null
UTF-8
C++
false
false
775
h
#ifndef GUIWINDOWH_H #define GUIWINDOWH_H #include "GUIDefs.h" #include "../OUAN.h" namespace OUAN { const std::string CEGUIWIN_ID_CREDITS="OUANExtras/TempCreditsBox"; const std::string STRING_KEY_CREDITS="EXTRAS_SCREEN_CREDITS"; class GUIWindow { protected: std::string mLayoutName; CEGUI::Window* mSheet; /// Parent state GameStatePtr mParentGameState; void setGUIStrings(std::string windowNames[],int windowNamesLen); public: GUIWindow(); virtual ~GUIWindow(); virtual void init(const std::string& layoutName,CEGUI::Window* sheet); virtual void initGUI(GameStatePtr parentGameState); virtual void destroy(); virtual void setStrings(); CEGUI::Window* getSheet() const; void show(); void hide(); }; } #endif
[ "ithiliel@1610d384-d83c-11de-a027-019ae363d039" ]
[ [ [ 1, 31 ] ] ]
c883a829f3e1065c0fe8409f67d9347ade58909c
faacd0003e0c749daea18398b064e16363ea8340
/lyxlib/filelist.h
32f37180e545ada0ccab4dab378f2457085cf29b
[]
no_license
yjfcool/lyxcar
355f7a4df7e4f19fea733d2cd4fee968ffdf65af
750be6c984de694d7c60b5a515c4eb02c3e8c723
refs/heads/master
2016-09-10T10:18:56.638922
2009-09-29T06:03:19
2009-09-29T06:03:19
42,575,701
0
0
null
null
null
null
UTF-8
C++
false
false
1,093
h
/* * Copyright (C) 2008-2009 Pavlov Denis * * Comments unavailable. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of the * License, or any later version. * */ #ifndef _FILELIST_H_ #define _FILELIST_H_ #include "lists.h" class ALyxFileListWidget : public ALyxListWidget { Q_OBJECT public: ALyxFileListWidget(QWidget *parent, ASkinner *skinner); QDir dir() { return m_rootdir; } void setRootDir(QDir dir) { m_rootdir = dir; refresh(); } void setRootDir(QString dir) { m_rootdir = QDir(dir); refresh(); } void setFilter(QStringList filter) { m_filter = filter; refresh(); } void refresh(); private: QDir m_rootdir; QStringList m_filter; void readRootDir(); void fileDoubleClicked(QString fileName); void directoryDoubleClicked(QString dirName); protected: void mouseDoubleClickEvent(QMouseEvent *e); signals: void fileActivated(QString fileName); }; #endif // _FILELIST_H_
[ "futurelink.vl@9e60f810-e830-11dd-9b7c-bbba4c9295f9" ]
[ [ [ 1, 44 ] ] ]
38929048fe0475e81584dff609f9b6508197a550
1e976ee65d326c2d9ed11c3235a9f4e2693557cf
/CommonSources/HTMLLite/PPMessageBoxClass.cpp
b923919ed442673efc530a346e0996d53b4c5086
[]
no_license
outcast1000/Jaangle
062c7d8d06e058186cb65bdade68a2ad8d5e7e65
18feb537068f1f3be6ecaa8a4b663b917c429e3d
refs/heads/master
2020-04-08T20:04:56.875651
2010-12-25T10:44:38
2010-12-25T10:44:38
19,334,292
3
0
null
null
null
null
UTF-8
C++
false
false
5,800
cpp
// PPMessageBoxMFC.cpp : implementation file // #include "stdafx.h" #include "PPMessageBoxClass.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif CPPMessageBox::CPPMessageBox() { } int CPPMessageBox::MessageBox(LPCTSTR lpszText, LPCTSTR lpszCaption /*= NULL*/, UINT nStyle /*= MB_OK | MB_ICONEXCLAMATION*/, const PPMSGBOXPARAMS * pMsgBox /*= NULL*/) { if (NULL != pMsgBox) return PPMessageBox(NULL, lpszText, lpszCaption, nStyle, pMsgBox); PackText(); return PPMessageBox(NULL, lpszText, lpszCaption, nStyle, &m_MsgParam); } int CPPMessageBox::MessageBoxIndirect(const PPMSGBOXPARAMS * pMsgBox /*= NULL*/) { if (NULL != pMsgBox) return PPMessageBoxIndirect(pMsgBox); PackText(); return PPMessageBoxIndirect(&m_MsgParam); } CPPMessageBox::~CPPMessageBox() { } void CPPMessageBox::SetTimeouts(int nAutoclick, int nDisable /*= 0*/, BOOL bGlobalDisable /*= FALSE*/) { m_MsgParam.bDisableAllCtrls = bGlobalDisable; m_MsgParam.nDisabledSeconds = nDisable; m_MsgParam.nTimeoutSeconds = nAutoclick; } void CPPMessageBox::SetCustomButtons(LPCTSTR lpszButtonNames /*= NULL*/) { m_sCustomButtonText = GetString(lpszButtonNames); } PPMSGBOXPARAMS * CPPMessageBox::GetMessageBoxParams() { PackText(); return &m_MsgParam; } //End of GetMessageBoxParams void CPPMessageBox::SetMessageBoxParams(const PPMSGBOXPARAMS * pMsgBoxParams) { m_MsgParam = *pMsgBoxParams; } //End of SetMessageBoxParams void CPPMessageBox::SetBackground(DWORD dwArea, PPMSGBOXAREA_BK * pAreaBk) { switch (dwArea) { case PPMSGBOX_HEADER_AREA: m_MsgParam.pHeaderBk = *pAreaBk; m_sHeaderSepText = GetString(pAreaBk->lpszSepText); break; case PPMSGBOX_MESSAGE_AREA: m_MsgParam.pMsgBoxBk = *pAreaBk; break; case PPMSGBOX_CONTROL_AREA: m_MsgParam.pControlBk = *pAreaBk; m_sControlSepText = GetString(pAreaBk->lpszSepText); break; case PPMSGBOX_MOREINFO_AREA: m_MsgParam.pMoreInfoBk = *pAreaBk; m_sMoreInfoSepText = GetString(pAreaBk->lpszSepText); break; } //switch } //End of SetBackground void CPPMessageBox::SetBackground(DWORD dwArea, int nEffectBk /*= -1*/, COLORREF crStartBk /*= -1*/, COLORREF crEndBk /*= -1*/, COLORREF crMidBk /*= -1*/) { if (crStartBk < 0) crStartBk = ::GetSysColor(COLOR_3DFACE); if (crEndBk < 0) crEndBk = crStartBk; if (crMidBk < 0) crMidBk = crStartBk; switch (dwArea) { case PPMSGBOX_HEADER_AREA: m_MsgParam.pHeaderBk.nEffectBk = nEffectBk; m_MsgParam.pHeaderBk.crStartBk = crStartBk; m_MsgParam.pHeaderBk.crEndBk = crEndBk; m_MsgParam.pHeaderBk.crMidBk = crMidBk; break; case PPMSGBOX_MESSAGE_AREA: m_MsgParam.pMsgBoxBk.nEffectBk = nEffectBk; m_MsgParam.pMsgBoxBk.crStartBk = crStartBk; m_MsgParam.pMsgBoxBk.crEndBk = crEndBk; m_MsgParam.pMsgBoxBk.crMidBk = crMidBk; break; case PPMSGBOX_CONTROL_AREA: m_MsgParam.pControlBk.crStartBk = crStartBk; m_MsgParam.pControlBk.crEndBk = crEndBk; m_MsgParam.pControlBk.crMidBk = crMidBk; break; case PPMSGBOX_MOREINFO_AREA: m_MsgParam.pMoreInfoBk.crStartBk = crStartBk; m_MsgParam.pMoreInfoBk.crEndBk = crEndBk; m_MsgParam.pMoreInfoBk.crMidBk = crMidBk; break; } //switch } //End of SetBackground void CPPMessageBox::SetSeparator(DWORD dwArea, int nSepType /*= PPMSGBOX_SEP_NONE*/, int nSepAlign /*= PPMSGBOX_ALIGN_LEFT*/, LPCTSTR lpszSepText /*= NULL*/) { switch (dwArea) { case PPMSGBOX_HEADER_AREA: m_MsgParam.pHeaderBk.nSepType = nSepType; m_MsgParam.pHeaderBk.nSepAlign = nSepAlign; m_sHeaderSepText = GetString(lpszSepText); break; case PPMSGBOX_CONTROL_AREA: m_MsgParam.pControlBk.nSepType = nSepType; m_MsgParam.pControlBk.nSepAlign = nSepAlign; m_sControlSepText = GetString(lpszSepText); break; case PPMSGBOX_MOREINFO_AREA: m_MsgParam.pMoreInfoBk.nSepType = nSepType; m_MsgParam.pMoreInfoBk.nSepAlign = nSepAlign; m_sMoreInfoSepText = GetString(lpszSepText); break; } //switch } //End of SetSeparator void CPPMessageBox::ClearAllButtonsText() { m_mapButtonText.clear(); } //End of ClearAllButtonsText void CPPMessageBox::SetButtonText(DWORD dwBtnID, LPCTSTR lpszText /*= NULL*/) { mapBtnText::iterator iter = m_mapButtonText.find(dwBtnID); CString sText = GetString(lpszText); if (iter == m_mapButtonText.end()) { if (!sText.IsEmpty()) m_mapButtonText.insert(std::make_pair(dwBtnID, sText)); } else { if (sText.IsEmpty()) m_mapButtonText.erase(iter); else iter->second = sText; } } //End of SetButtonText LPCTSTR CPPMessageBox::GetButtonText(DWORD dwBtnID) { mapBtnText::iterator iter = m_mapButtonText.find(dwBtnID); if (iter != m_mapButtonText.end()) return (LPCTSTR)iter->second; return NULL; } //End of GetButtonText CString CPPMessageBox::GetString(LPCTSTR lpszText) { if ((NULL == lpszText) || (0 == lpszText [0])) return _T(""); CString sText = _T(""); if (0 == HIWORD(lpszText)) sText.LoadString(LOWORD(lpszText)); else sText = (CString)lpszText; return sText; } //End of GetString void CPPMessageBox::PackText() { //Packing a localization of the button text m_pLocalBtnText.clear(); mapBtnText::iterator iter; for (iter = m_mapButtonText.begin(); iter != m_mapButtonText.end(); ++iter) m_pLocalBtnText.insert(std::make_pair(iter->first, (LPCTSTR)iter->second)); m_MsgParam.pLocalBtnText = &m_pLocalBtnText; //Packing a separator text m_MsgParam.pHeaderBk.lpszSepText = (LPCTSTR)m_sHeaderSepText; m_MsgParam.pControlBk.lpszSepText = (LPCTSTR)m_sControlSepText; m_MsgParam.pMoreInfoBk.lpszSepText = (LPCTSTR)m_sMoreInfoSepText; m_MsgParam.lpszCustomButtons = (LPCTSTR)m_sCustomButtonText; } //End of PackText
[ "outcast1000@dc1b949e-fa36-4f9e-8e5c-de004ec35678" ]
[ [ [ 1, 199 ] ] ]
5feacce2cd221214cdd587efb1c292baa02425b5
40b507c2dde13d14bb75ee1b3c16b4f3f82912d1
/extensions/mysql/mysql/MyDatabase.cpp
b9f797a095e4ef6e6474d2709681384c181101ec
[]
no_license
Nephyrin/-furry-octo-nemesis
5da2ef75883ebc4040e359a6679da64ad8848020
dd441c39bd74eda2b9857540dcac1d98706de1de
refs/heads/master
2016-09-06T01:12:49.611637
2008-09-14T08:42:28
2008-09-14T08:42:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,706
cpp
/** * vim: set ts=4 : * ============================================================================= * SourceMod MySQL Extension * Copyright (C) 2004-2007 AlliedModders LLC. All rights reserved. * ============================================================================= * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, version 3.0, as published by the * Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. * * As a special exception, AlliedModders LLC gives you permission to link the * code of this program (as well as its derivative works) to "Half-Life 2," the * "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software * by the Valve Corporation. You must obey the GNU General Public License in * all respects for all other code used. Additionally, AlliedModders LLC grants * this exception to all derivative works. AlliedModders LLC defines further * exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007), * or <http://www.sourcemod.net/license.php>. * * Version: $Id$ */ #include "MyDatabase.h" #include "smsdk_ext.h" #include "MyBasicResults.h" #include "MyStatement.h" DBType GetOurType(enum_field_types type) { switch (type) { case MYSQL_TYPE_DOUBLE: case MYSQL_TYPE_FLOAT: { return DBType_Float; } case MYSQL_TYPE_TINY: case MYSQL_TYPE_SHORT: case MYSQL_TYPE_LONG: case MYSQL_TYPE_INT24: case MYSQL_TYPE_YEAR: case MYSQL_TYPE_BIT: { return DBType_Integer; } case MYSQL_TYPE_LONGLONG: case MYSQL_TYPE_DATE: case MYSQL_TYPE_TIME: case MYSQL_TYPE_DATETIME: case MYSQL_TYPE_TIMESTAMP: case MYSQL_TYPE_NEWDATE: case MYSQL_TYPE_VAR_STRING: case MYSQL_TYPE_VARCHAR: case MYSQL_TYPE_STRING: case MYSQL_TYPE_NEWDECIMAL: case MYSQL_TYPE_DECIMAL: case MYSQL_TYPE_ENUM: case MYSQL_TYPE_SET: { return DBType_String; } case MYSQL_TYPE_TINY_BLOB: case MYSQL_TYPE_MEDIUM_BLOB: case MYSQL_TYPE_LONG_BLOB: case MYSQL_TYPE_BLOB: case MYSQL_TYPE_GEOMETRY: { return DBType_Blob; } default: { return DBType_String; } } return DBType_Unknown; } MyDatabase::MyDatabase(MYSQL *mysql, const DatabaseInfo *info, bool persistent) : m_mysql(mysql), m_refcount(1), m_pFullLock(NULL), m_bPersistent(persistent) { m_Host.assign(info->host); m_Database.assign(info->database); m_User.assign(info->user); m_Pass.assign(info->pass); m_Info.database = m_Database.c_str(); m_Info.host = m_Host.c_str(); m_Info.user = m_User.c_str(); m_Info.pass = m_Pass.c_str(); m_Info.driver = NULL; m_Info.maxTimeout = info->maxTimeout; m_Info.port = info->port; m_pRefLock = threader->MakeMutex(); } MyDatabase::~MyDatabase() { mysql_close(m_mysql); m_mysql = NULL; m_pRefLock->DestroyThis(); if (m_pFullLock) { m_pFullLock->DestroyThis(); } } void MyDatabase::IncReferenceCount() { m_pRefLock->Lock(); m_refcount++; m_pRefLock->Unlock(); } bool MyDatabase::Close() { m_pRefLock->Lock(); if (m_refcount > 1) { m_refcount--; m_pRefLock->Unlock(); return false; } m_pRefLock->Unlock(); /* Remove us from the search list */ if (m_bPersistent) { g_MyDriver.RemoveFromList(this, true); } /* Finally, free our resource(s) */ delete this; return true; } const DatabaseInfo &MyDatabase::GetInfo() { return m_Info; } unsigned int MyDatabase::GetInsertID() { return (unsigned int)mysql_insert_id(m_mysql); } unsigned int MyDatabase::GetAffectedRows() { return (unsigned int)mysql_affected_rows(m_mysql); } const char *MyDatabase::GetError(int *errCode) { if (errCode) { *errCode = mysql_errno(m_mysql); } return mysql_error(m_mysql); } bool MyDatabase::QuoteString(const char *str, char buffer[], size_t maxlength, size_t *newSize) { unsigned long size = static_cast<unsigned long>(strlen(str)); unsigned long needed = size * 2 + 1; if (maxlength < needed) { if (newSize) { *newSize = (size_t)needed; } return false; } needed = mysql_real_escape_string(m_mysql, buffer, str, size); if (newSize) { *newSize = (size_t)needed; } return true; } bool MyDatabase::DoSimpleQuery(const char *query) { IQuery *pQuery = DoQuery(query); if (!pQuery) { return false; } pQuery->Destroy(); return true; } IQuery *MyDatabase::DoQuery(const char *query) { if (mysql_real_query(m_mysql, query, strlen(query)) != 0) { return NULL; } MYSQL_RES *res = NULL; if (mysql_field_count(m_mysql)) { res = mysql_store_result(m_mysql); if (!res) { return NULL; } } return new MyQuery(this, res); } bool MyDatabase::DoSimpleQueryEx(const char *query, size_t len) { IQuery *pQuery = DoQueryEx(query, len); if (!pQuery) { return false; } pQuery->Destroy(); return true; } IQuery *MyDatabase::DoQueryEx(const char *query, size_t len) { if (mysql_real_query(m_mysql, query, len) != 0) { return NULL; } MYSQL_RES *res = NULL; if (mysql_field_count(m_mysql)) { res = mysql_store_result(m_mysql); if (!res) { return NULL; } } return new MyQuery(this, res); } IPreparedQuery *MyDatabase::PrepareQuery(const char *query, char *error, size_t maxlength, int *errCode) { MYSQL_STMT *stmt = mysql_stmt_init(m_mysql); if (!stmt) { if (error) { strncopy(error, GetError(errCode), maxlength); } else if (errCode) { *errCode = mysql_errno(m_mysql); } return NULL; } if (mysql_stmt_prepare(stmt, query, strlen(query)) != 0) { if (error) { strncopy(error, mysql_stmt_error(stmt), maxlength); } if (errCode) { *errCode = mysql_stmt_errno(stmt); } mysql_stmt_close(stmt); return NULL; } return new MyStatement(this, stmt); } bool MyDatabase::LockForFullAtomicOperation() { if (!m_pFullLock) { m_pFullLock = threader->MakeMutex(); if (!m_pFullLock) { return false; } } m_pFullLock->Lock(); return true; } void MyDatabase::UnlockFromFullAtomicOperation() { if (m_pFullLock) { m_pFullLock->Unlock(); } } IDBDriver *MyDatabase::GetDriver() { return &g_MyDriver; }
[ [ [ 1, 2 ], [ 4, 5 ], [ 7, 7 ], [ 11, 11 ], [ 16, 16 ], [ 19, 19 ], [ 28, 318 ] ], [ [ 3, 3 ], [ 6, 6 ], [ 8, 10 ], [ 12, 15 ], [ 17, 18 ], [ 20, 27 ] ] ]
ad8c5325b0473b6c2231cc6ae8334c9dbc444f34
e192bb584e8051905fc9822e152792e9f0620034
/tags/sources_0_1/base/test/test_liste.h
358ecfd43dce3530830452daede8e816c6bb68e0
[]
no_license
BackupTheBerlios/projet-univers-svn
708ffadce21f1b6c83e3b20eb68903439cf71d0f
c9488d7566db51505adca2bc858dab5604b3c866
refs/heads/master
2020-05-27T00:07:41.261961
2011-07-31T20:55:09
2011-07-31T20:55:09
40,817,685
0
0
null
null
null
null
MacCentralEurope
C++
false
false
3,222
h
/*************************************************************************** * Copyright (C) 2004 by Equipe Projet Univers * * [email protected] * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU Lesser General Public License as * * published by the Free Software Foundation; either version 2.1 of the * * License, or (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU Lesser General Public License for more details. * * * * You should have received a copy of the GNU General Lesser Public * * License along with this program; if not, write to the * * Free Software Foundation, Inc., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #ifndef _PU_BASE_TEST_LISTE_H_ #define _PU_BASE_TEST_LISTE_H_ // Includes #include <cppunit/extensions/HelperMacros.h> #include "liste_composition.h" #include "liste_association.h" namespace ProjetUnivers { namespace Base { namespace Test { class ElementTestListe ; /* CLASS TestListe Teste les liste en association et en composition. */ class TestListe : public CppUnit::TestFixture { protected: // **************************** // GROUP: Tests proprement dits // **************************** //////////////// // Teste l'ajout dans la liste. void TestAjouter() ; /////////////// // Teste que, mÍme une liste temporaire, peut Ítre // parcourue. void TestParcoursListeTemporaire() ; ////////////// // Teste la destruction de liste en composition. void TestDestruction() ; // ******************** // GROUP: Mise en place // ******************** CPPUNIT_TEST_SUITE(TestListe) ; CPPUNIT_TEST(TestAjouter) ; CPPUNIT_TEST(TestParcoursListeTemporaire) ; CPPUNIT_TEST(TestDestruction) ; CPPUNIT_TEST_SUITE_END() ; public: /////////////// // Initialisation du test void setUp() ; /////////////// // Desinitialisation du test void tearDown() ; private: ListeAssociation< ElementTestListe > f() ; // une liste ListeComposition< ElementTestListe > liste ; }; } } } #endif
[ "rogma@fb75c231-3be1-0310-9bb4-c95e2f850c73" ]
[ [ [ 1, 115 ] ] ]
6016ec9e72c8e5b7b88a52eadcc21b038fd54fa6
1c80a726376d6134744d82eec3129456b0ab0cbf
/Project/C++/C++/练习/Visual C++程序设计与应用教程/Li3_6/stdafx.cpp
000ab2332fe16e7fbc4ea18c8eb20970f7e4b333
[]
no_license
dabaopku/project_pku
338a8971586b6c4cdc52bf82cdd301d398ad909f
b97f3f15cdc3f85a9407e6bf35587116b5129334
refs/heads/master
2021-01-19T11:35:53.500533
2010-09-01T03:42:40
2010-09-01T03:42:40
null
0
0
null
null
null
null
GB18030
C++
false
false
166
cpp
// stdafx.cpp : 只包括标准包含文件的源文件 // Li3_6.pch 将作为预编译头 // stdafx.obj 将包含预编译类型信息 #include "stdafx.h"
[ "[email protected]@592586dc-1302-11df-8689-7786f20063ad" ]
[ [ [ 1, 7 ] ] ]
3afc03565f82c7519e3c84b74b9be16da70fc140
4ed04c4f418f2404db1fb94363b30552623e53da
/TibiaTekBot Injected DLL/Battlelist.cpp
30f385bc00bad65ce6c87097cbc7a34afae30487
[]
no_license
Cameri/tibiatekbot
5f8ff3629d0fd2153ee2657af193ba2bc7585411
f98695749224061ba13ab56e922efb8a971b6363
refs/heads/master
2020-05-25T12:05:39.437437
2009-05-29T23:46:21
2009-05-29T23:46:21
32,226,477
1
0
null
null
null
null
UTF-8
C++
false
false
2,020
cpp
#include "stdafx.h" #include <windows.h> #include <string> #include "Constants.h" #include "Battlelist.h" #include "Core.h" Battlelist::Battlelist() { Reset(); } bool Battlelist::NextEntity() { if (IndexPosition + 1 < Consts::BLMax) { IndexPosition++; Address += Consts::BLDist/sizeof(int); return true; } return false; } bool Battlelist::PrevEntity() { if (IndexPosition > 0) { IndexPosition--; Address -= Consts::BLDist/sizeof(int); return true; } return false; } std::string Battlelist::Name(){ std::string Result = (char*)(Address + Consts::BLNameOffset/sizeof(int)); return Result; } void Battlelist::Reset() { IndexPosition = 0; Address = (unsigned int*)Consts::ptrBattlelistBegin; } bool Battlelist::IsVisible() { LocationDefinition loc = GetLocation(); //char output[128]; //sprintf(output, "%d,%d,%d - %d,%d,%d",*Consts::ptrCharX,*Consts::ptrCharY,*Consts::ptrCharZ, loc.x, loc.y, loc.z); //MessageBoxA(0,output,"coords",0); return (abs(*Consts::ptrCharX - loc.x) < 8 && abs(*Consts::ptrCharY - loc.y) < 6 && *Consts::ptrCharZ == loc.z); } bool Battlelist::FindByName(Battlelist *BL, std::string EntityName){ do { if (BL->Name() == EntityName) return true; } while(BL->NextEntity()); return false; } bool Battlelist::IsOnScreen() { return (*(Address + Consts::BLOnScreenOffset/sizeof(int)) == 1); } unsigned int Battlelist::HPPercentage() { return *(Address + Consts::BLHPPercentOffset/sizeof(int)); } bool Battlelist::IsPlayer() { return (ID() < 0x40000000); } int Battlelist::GetIndexPosition() { return IndexPosition; } unsigned int Battlelist::ID() { return *(Address); } LocationDefinition Battlelist::GetLocation() { LocationDefinition ReturnValue = {0, 0, 0}; LocationDefinition *ld = (LocationDefinition*)(Address + Consts::BLLocationOffset/sizeof(int)); ReturnValue.x = ld->x; ReturnValue.y = ld->y; ReturnValue.z = ld->z; return ReturnValue; }
[ "oskari.virtanen@33ddfa00-593a-0410-b0c9-7b4335ea722e", "cameri2005@33ddfa00-593a-0410-b0c9-7b4335ea722e" ]
[ [ [ 1, 3 ], [ 5, 5 ], [ 7, 7 ], [ 39, 40 ], [ 59, 60 ], [ 88, 89 ], [ 94, 95 ] ], [ [ 4, 4 ], [ 6, 6 ], [ 8, 38 ], [ 41, 58 ], [ 61, 87 ], [ 90, 93 ], [ 96, 96 ] ] ]
be7d8a2de66d15259daf3c54702f513ce8dcfa82
b6146901a939cda09a0d399ade6a3c8ddaaef08d
/itkSiddonJacobsRayCastInterpolateImageFunction.h
e382545870cc53856b02b6320754dfcb00c10e57
[]
no_license
midas-journal/midas-journal-784
34f63b8f048c7f69cf8ce0047a49043a12917899
5f528b99231d38831df6be5bd51cdef5dc836b23
refs/heads/master
2016-09-05T18:31:16.082143
2011-08-22T13:48:29
2011-08-22T13:48:29
2,248,757
12
6
null
null
null
null
UTF-8
C++
false
false
7,600
h
/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkSiddonJacobsRayCastInterpolateImageFunction.h Language: C++ Date: 2010/12/20 Version: 1.0 Author: Jian Wu ([email protected]) Univerisity of Florida Virginia Commonwealth University Calculate DRR from a CT dataset using incremental ray-tracing algorithm The algorithm was initially proposed by Robert Siddon and improved by Filip Jacobs etc. ------------------------------------------------------------------------- References: R. L. Siddon, "Fast calculation of the exact radiological path for a threedimensional CT array," Medical Physics 12, 252-55 (1985). F. Jacobs, E. Sundermann, B. De Sutter, M. Christiaens, and I. Lemahieu, "A fast algorithm to calculate the exact radiological path through a pixel or voxel space," Journal of Computing and Information Technology ? CIT 6, 89-94 (1998). =========================================================================*/ #ifndef _itkSiddonJacobsRayCastInterpolateImageFunction_h #define _itkSiddonJacobsRayCastInterpolateImageFunction_h #include "itkInterpolateImageFunction.h" #include "itkTransform.h" #include "itkVector.h" namespace itk { /** \class SiddonJacobsRayCastInterpolateImageFunction * \brief Projective interpolation of an image at specified positions. * * SiddonJacobsRayCastInterpolateImageFunction casts rays through a 3-dimensional * image * \warning This interpolator works for 3-dimensional images only. * * \ingroup ImageFunctions */ template <class TInputImage, class TCoordRep = float> class ITK_EXPORT SiddonJacobsRayCastInterpolateImageFunction : public InterpolateImageFunction<TInputImage,TCoordRep> { public: /** Standard class typedefs. */ typedef SiddonJacobsRayCastInterpolateImageFunction Self; typedef InterpolateImageFunction<TInputImage,TCoordRep> Superclass; typedef SmartPointer<Self> Pointer; typedef SmartPointer<const Self> ConstPointer; /** Constants for the image dimensions */ itkStaticConstMacro(InputImageDimension, unsigned int, TInputImage::ImageDimension); typedef Euler3DTransform<TCoordRep> TransformType; typedef typename TransformType::Pointer TransformPointer; typedef typename TransformType::InputPointType InputPointType; typedef typename TransformType::OutputPointType OutputPointType; typedef typename TransformType::ParametersType TransformParametersType; typedef typename TransformType::JacobianType TransformJacobianType; typedef typename Superclass::InputPixelType PixelType; typedef typename TInputImage::SizeType SizeType; typedef Vector<TCoordRep, 3> DirectionType; /** Type of the Interpolator Base class */ typedef InterpolateImageFunction<TInputImage,TCoordRep> InterpolatorType; typedef typename InterpolatorType::Pointer InterpolatorPointer; /** Run-time type information (and related methods). */ itkTypeMacro(SiddonJacobsRayCastInterpolateImageFunction, InterpolateImageFunction); /** Method for creation through the object factory. */ itkNewMacro(Self); /** OutputType typedef support. */ typedef typename Superclass::OutputType OutputType; /** InputImageType typedef support. */ typedef typename Superclass::InputImageType InputImageType; /** InputImageConstPointer typedef support. */ typedef typename Superclass::InputImageConstPointer InputImageConstPointer; /** RealType typedef support. */ typedef typename Superclass::RealType RealType; /** Dimension underlying input image. */ itkStaticConstMacro(ImageDimension, unsigned int,Superclass::ImageDimension); /** Point typedef support. */ typedef typename Superclass::PointType PointType; /** Index typedef support. */ typedef typename Superclass::IndexType IndexType; /** ContinuousIndex typedef support. */ typedef typename Superclass::ContinuousIndexType ContinuousIndexType; /** \brief * Interpolate the image at a point position. * * Returns the interpolated image intensity at a * specified point position. No bounds checking is done. * The point is assume to lie within the image buffer. * * ImageFunction::IsInsideBuffer() can be used to check bounds before * calling the method. */ virtual OutputType Evaluate( const PointType& point ) const; /** Interpolate the image at a continuous index position * * Returns the interpolated image intensity at a * specified index position. No bounds checking is done. * The point is assume to lie within the image buffer. * * Subclasses must override this method. * * ImageFunction::IsInsideBuffer() can be used to check bounds before * calling the method. */ virtual OutputType EvaluateAtContinuousIndex( const ContinuousIndexType &index ) const; virtual void Initialize(void); /** Connect the Transform. */ itkSetObjectMacro( Transform, TransformType ); /** Get a pointer to the Transform. */ itkGetObjectMacro( Transform, TransformType ); /** Set and get the focal point to isocenter distance in mm */ itkSetMacro(scd, double); itkGetMacro(scd, double); /** Set and get the Lianc grantry rotation angle in radians */ itkSetMacro(ProjectionAngle, double); itkGetMacro(ProjectionAngle, double); /** Set and get the Threshold */ itkSetMacro(Threshold, double); itkGetMacro(Threshold, double); /** Check if a point is inside the image buffer. * \warning For efficiency, no validity checking of * the input image pointer is done. */ inline bool IsInsideBuffer( const PointType & ) const { return true; } bool IsInsideBuffer( const ContinuousIndexType & ) const { return true; } bool IsInsideBuffer( const IndexType & ) const { return true; } protected: /// Constructor SiddonJacobsRayCastInterpolateImageFunction(); /// Destructor ~SiddonJacobsRayCastInterpolateImageFunction(){}; /// Print the object void PrintSelf(std::ostream& os, Indent indent) const; /// Transformation used to calculate the new focal point position TransformPointer m_Transform; // Displacement of the volume // Overall inverse transform used to calculate the ray position in the input space TransformPointer m_InverseTransform; // The threshold above which voxels along the ray path are integrated double m_Threshold; double m_scd; // Focal point to isocenter distance double m_ProjectionAngle; // Linac gantry rotation angle in radians private: SiddonJacobsRayCastInterpolateImageFunction( const Self& ); //purposely not implemented void operator=( const Self& ); //purposely not implemented void ComputeInverseTransform( void ) const; TransformPointer m_GantryRotTransform; // Gantry rotation transform TransformPointer m_CamShiftTransform; // Camera shift transform camRotTransform TransformPointer m_CamRotTransform; // Camera rotation transform TransformPointer m_ComposedTransform; // Composed transform PointType m_sourcePoint; // Coordinate of the source in the standard Z projection geometry PointType m_sourceWorld; // Coordinate of the source in the world coordinate system }; } // namespace itk #ifndef ITK_MANUAL_INSTANTIATION #include "itkSiddonJacobsRayCastInterpolateImageFunction.txx" #endif #endif
[ [ [ 1, 214 ] ] ]
fa3538bb7ba4bcecdb53a04dabdc549103d6ee94
9c62af23e0a1faea5aaa8dd328ba1d82688823a5
/rl/tags/v0-1/engine/rules/src/CombatActions.cpp
f8712086ee36897bf3fb3f40e7923ec07699f9a4
[ "ClArtistic", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
jacmoe/dsa-hl-svn
55b05b6f28b0b8b216eac7b0f9eedf650d116f85
97798e1f54df9d5785fb206c7165cd011c611560
refs/heads/master
2021-04-22T12:07:43.389214
2009-11-27T22:01:03
2009-11-27T22:01:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,359
cpp
/* This source file is part of Rastullahs Lockenpracht. * Copyright (C) 2003-2005 Team Pantheon. http://www.team-pantheon.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the Clarified Artistic License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * Clarified Artistic License for more details. * * You should have received a copy of the Clarified Artistic License * along with this program; if not you can get it here * http://www.jpaulmorrison.com/fbp/artistic2.htm. */ #include "CombatActions.h" namespace rl { CombatAction::CombatAction() : mSource(NULL) { } CombatAction::CombatAction(rl::Creature* source) : mSource(source) { } CombatAction::~CombatAction() { } Creature* CombatAction::getSource() { return mSource; } void CombatAction::setSource(rl::Creature* source) { mSource = source; } CombatActionMove::CombatActionMove(Creature* source, MoveType moveType, Ogre::Vector3 moveTarget) : CombatAction(source), mType(moveType), mTarget(moveTarget) { } CombatActionMove::~CombatActionMove() { } Ogre::Vector3 CombatActionMove::getMoveTarget() { return mTarget; } MoveType CombatActionMove::getMoveType() { return mType; } CombatActionAttack::CombatActionAttack(Creature* source, Creature* target, const CeGuiString& kampftechnik) : CombatAction(source), mTarget(target), mKampftechnik(kampftechnik) { } Creature* CombatActionAttack::getTarget() { return mTarget; } const CeGuiString& CombatActionAttack::getKampftechnik() { return mKampftechnik; } CombatActionAttack::~CombatActionAttack() { } void CombatActionAttack::setKampftechnik(const CeGuiString& kampftechnik) { mKampftechnik = kampftechnik; } CombatActionParee::CombatActionParee(Creature* source, Creature* target, const CeGuiString& kampftechnik) : CombatActionAttack(source, target, kampftechnik) { } CombatActionParee::~CombatActionParee() { } CombatActionNop::CombatActionNop() : CombatAction(NULL) { } CombatActionNop::~CombatActionNop() { } }
[ "blakharaz@4c79e8ff-cfd4-0310-af45-a38c79f83013" ]
[ [ [ 1, 111 ] ] ]
1ee067c5d925caecbb206257043cf00228d44ce2
0c1f669f3dfdab47085bf537348b0354f836abea
/ qtremotedroid/QtRemoteDroidServer/src/netreturnaddress.cpp
39dfbe99351ec9464cd51bfe29ba8ccf2904539e
[]
no_license
harlentan/qtremotedroid
fc5fc96d4374c39561aea73470a88d1f0a68b637
d07dd045213711538b38c7ced2fd6d5a8edcf241
refs/heads/master
2021-01-10T11:37:59.331004
2010-12-12T09:55:39
2010-12-12T09:55:39
54,114,402
0
0
null
null
null
null
UTF-8
C++
false
false
77
cpp
#include "netreturnaddress.h" NetReturnAddress::NetReturnAddress() { }
[ [ [ 1, 5 ] ] ]
06ec02e002c4d6718ae333b3052cf047039bd342
37c757f24b674f67edd87b75b996d8d5015455cb
/Server/include/dataManager.h
8be8cd33a0cc660ce9a344d8d3081d950c394464
[]
no_license
SakuraSinojun/cotalking
1118602313f85d1c49d73e1603cf6642bc15f36d
37354d99db6b7033019fd0aaccec84e68aee2adf
refs/heads/master
2021-01-10T21:20:50.269547
2011-04-07T06:15:04
2011-04-07T06:15:04
32,323,167
0
0
null
null
null
null
UTF-8
C++
false
false
1,034
h
/*************************************************** Project: grouptalk author: TaXueWuHen data Manager; ***************************************************/ #ifndef __TALK_DATAPMANAGER_H__ #define __TALK_DATAPMANAGER_H__ #include <map> #include "../include/def.h" #include "../include/defGroupTalk.h" #include "../include/userManager.h" #define C_MAX_MAINDATA 1000 using namespace std; //data main struct; typedef struct TS_dmMain { int sock; int length; scData data; } sdmMain, *psdmMain; const int C_MAX_SENDDATA = 10; class TS_dataManager { public: TS_dataManager(); ~TS_dataManager(); private: sdmMain dataMain[C_MAX_MAINDATA]; int dataPos; //pointer on dataMain; TS_userManager m_userMng; byte dataSend[C_SCDATA_LENGTH * C_MAX_SENDDATA]; public: //append data; //if the data of received is wrong, then len = 0; bool appendData(int id, void* data, int len); bool appendError(int id, int errid); void *getSendData(int id, int &len); }; #endif
[ "SakuraSinojun@02eed91f-dd82-7cf9-bfd0-73567c4360d3" ]
[ [ [ 1, 49 ] ] ]
055375d1f47c3c8ef4942c6b44d1cd9579c95e7b
7b7a3f9e0cac33661b19bdfcb99283f64a455a13
/Engine/dll/Assimp/include/assimp.hpp
a68963383d92a9b058eee1e33cfa0451adb50803
[]
no_license
grimtraveller/fluxengine
62bc0169d90bfe656d70e68615186bd60ab561b0
8c967eca99c2ce92ca4186a9ca00c2a9b70033cd
refs/heads/master
2021-01-10T10:58:56.217357
2009-09-01T15:07:05
2009-09-01T15:07:05
55,775,414
0
0
null
null
null
null
UTF-8
C++
false
false
16,698
hpp
/* --------------------------------------------------------------------------- Open Asset Import Library (ASSIMP) --------------------------------------------------------------------------- Copyright (c) 2006-2008, ASSIMP Development Team All rights reserved. Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the ASSIMP team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of the ASSIMP Development Team. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --------------------------------------------------------------------------- */ /** @file Defines the C++-API to the Open Asset Import Library. */ #ifndef __AI_ASSIMP_HPP_INC__ #define __AI_ASSIMP_HPP_INC__ #ifndef __cplusplus # error This header requires C++ to be used. Use Assimp's C-API (assimp.h) \ to access the library from C code. #endif #include <map> #include <vector> // Public ASSIMP headers #include "aiTypes.h" #include "aiConfig.h" #include "aiAssert.h" namespace Assimp { // Public interface class Importer; class IOStream; class IOSystem; // Plugin development class BaseImporter; class BaseProcess; class SharedPostProcessInfo; class BatchLoader; } #define AI_PROPERTY_WAS_NOT_EXISTING 0xffffffff struct aiScene; struct aiFileIO; extern "C" ASSIMP_API const aiScene* aiImportFileEx( const char*, unsigned int, aiFileIO*); namespace Assimp { // --------------------------------------------------------------------------- /** The Importer class forms an C++ interface to the functionality of the * Asset Import library. * * Create an object of this class and call ReadFile() to import a file. * If the import succeeds, the function returns a pointer to the imported data. * The data remains property of the object, it is intended to be accessed * read-only. The imported data will be destroyed along with the Importer * object. If the import failes, ReadFile() returns a NULL pointer. In this * case you can retrieve a human-readable error description be calling * GetErrorString(). * * If you need the Importer to do custom file handling to access the files, * implement IOSystem and IOStream and supply an instance of your custom * IOSystem implementation by calling SetIOHandler() before calling ReadFile(). * If you do not assign a custion IO handler, a default handler using the * standard C++ IO logic will be used. * * @note One Importer instance is not thread-safe. If you use multiple * threads for loading each thread should manage its own Importer instance. */ class ASSIMP_API Importer { // used internally friend class BaseProcess; friend class BatchLoader; friend const aiScene* ::aiImportFileEx( const char*, unsigned int, aiFileIO*); public: typedef unsigned int KeyType; typedef std::map<KeyType, int> IntPropertyMap; typedef std::map<KeyType, float> FloatPropertyMap; typedef std::map<KeyType, std::string> StringPropertyMap; public: // ------------------------------------------------------------------- /** Constructor. Creates an empty importer object. * * Call ReadFile() to start the import process. */ Importer(); // ------------------------------------------------------------------- /** Destructor. The object kept ownership of the imported data, * which now will be destroyed along with the object. */ ~Importer(); // ------------------------------------------------------------------- /** Registers a new loader. * * @param pImp Importer to be added. The Importer instance takes * ownership of the pointer, so it will be automatically deleted * with the Importer instance. * @return AI_SUCCESS if the loader has been added. The registration * fails if there is already a loader for a specific file extension. */ aiReturn RegisterLoader(BaseImporter* pImp); // ------------------------------------------------------------------- /** Unregisters a loader. * * @param pImp Importer to be unregistered. * @return AI_SUCCESS if the loader has been removed. The function * fails if the loader is currently in use (this could happen * if the #Importer instance is used by more than one thread) or * if it has not yet been registered. */ aiReturn UnregisterLoader(BaseImporter* pImp); #if 0 // ------------------------------------------------------------------- /** Registers a new post-process step. * * @param pImp Post-process step to be added. The Importer instance * takes ownership of the pointer, so it will be automatically * deleted with the Importer instance. * @return AI_SUCCESS if the step has been added. */ aiReturn RegisterPPStep(BaseProcess* pImp); // ------------------------------------------------------------------- /** Unregisters a post-process step. * * @param pImp Step to be unregistered. * @return AI_SUCCESS if the step has been removed. The function * fails if the step is currently in use (this could happen * if the #Importer instance is used by more than one thread) or * if it has not yet been registered. */ aiReturn UnregisterPPStep(BaseProcess* pImp); #endif // ------------------------------------------------------------------- /** Set an integer configuration property. * @param szName Name of the property. All supported properties * are defined in the aiConfig.g header (all constants share the * prefix AI_CONFIG_XXX). * @param iValue New value of the property * @param bWasExisting Optional pointer to receive true if the * property was set before. The new value replaced the old value * in this case. * @note Property of different types (float, int, string ..) are kept * on different stacks, so calling SetPropertyInteger() for a * floating-point property has no effect - the loader will call * GetPropertyFloat() to read the property, but it won't be there. */ void SetPropertyInteger(const char* szName, int iValue, bool* bWasExisting = NULL); // ------------------------------------------------------------------- /** Set a floating-point configuration property. * @see SetPropertyInteger() */ void SetPropertyFloat(const char* szName, float fValue, bool* bWasExisting = NULL); // ------------------------------------------------------------------- /** Set a string configuration property. * @see SetPropertyInteger() */ void SetPropertyString(const char* szName, const std::string& sValue, bool* bWasExisting = NULL); // ------------------------------------------------------------------- /** Get a configuration property. * @param szName Name of the property. All supported properties * are defined in the aiConfig.g header (all constants share the * prefix AI_CONFIG_XXX). * @param iErrorReturn Value that is returned if the property * is not found. * @return Current value of the property * @note Property of different types (float, int, string ..) are kept * on different lists, so calling SetPropertyInteger() for a * floating-point property has no effect - the loader will call * GetPropertyFloat() to read the property, but it won't be there. */ int GetPropertyInteger(const char* szName, int iErrorReturn = 0xffffffff) const; // ------------------------------------------------------------------- /** Get a floating-point configuration property * @see GetPropertyInteger() */ float GetPropertyFloat(const char* szName, float fErrorReturn = 10e10f) const; // ------------------------------------------------------------------- /** Get a string configuration property * * The return value remains valid until the property is modified. * @see GetPropertyInteger() */ const std::string& GetPropertyString(const char* szName, const std::string& sErrorReturn = "") const; // ------------------------------------------------------------------- /** Supplies a custom IO handler to the importer to use to open and * access files. If you need the importer to use custion IO logic to * access the files, you need to provide a custom implementation of * IOSystem and IOFile to the importer. Then create an instance of * your custion IOSystem implementation and supply it by this function. * * The Importer takes ownership of the object and will destroy it * afterwards. The previously assigned handler will be deleted. * * @param pIOHandler The IO handler to be used in all file accesses * of the Importer. NULL resets it to the default handler. */ void SetIOHandler( IOSystem* pIOHandler); // ------------------------------------------------------------------- /** Retrieves the IO handler that is currently set. * You can use IsDefaultIOHandler() to check whether the returned * interface is the default IO handler provided by ASSIMP. The default * handler is active as long the application doesn't supply its own * custom IO handler via SetIOHandler(). * @return A valid IOSystem interface */ IOSystem* GetIOHandler(); // ------------------------------------------------------------------- /** Checks whether a default IO handler is active * A default handler is active as long the application doesn't * supply its own custom IO handler via SetIOHandler(). * @return true by default */ bool IsDefaultIOHandler(); // ------------------------------------------------------------------- /** Reads the given file and returns its contents if successful. * * If the call succeeds, the contents of the file are returned as a * pointer to an aiScene object. The returned data is intended to be * read-only, the importer object keeps ownership of the data and will * destroy it upon destruction. If the import failes, NULL is returned. * A human-readable error description can be retrieved by calling * GetErrorString(). The previous scene will be deleted during this call. * @param pFile Path and filename to the file to be imported. * @param pFlags Optional post processing steps to be executed after * a successful import. Provide a bitwise combination of the * #aiPostProcessSteps flags. * @return A pointer to the imported data, NULL if the import failed. * The pointer to the scene remains in possession of the Importer * instance. Use GetOrphanedScene() to take ownership of it. */ const aiScene* ReadFile( const std::string& pFile, unsigned int pFlags); // ------------------------------------------------------------------- /** Returns an error description of an error that occured in ReadFile(). * * Returns an empty string if no error occured. * @return A description of the last error, an empty string if no * error occured. */ inline const std::string& GetErrorString() const; // ------------------------------------------------------------------- /** Returns whether a given file extension is supported by ASSIMP. * * @param szExtension Extension to be checked. * Must include a trailing dot '.'. Example: ".3ds", ".md3". * Cases-insensitive. * @return true if the extension is supported, false otherwise */ bool IsExtensionSupported(const std::string& szExtension); // ------------------------------------------------------------------- /** Get a full list of all file extensions supported by ASSIMP. * * If a file extension is contained in the list this does, of course, not * mean that ASSIMP is able to load all files with this extension. * @param szOut String to receive the extension list. * Format of the list: "*.3ds;*.obj;*.dae". */ void GetExtensionList(std::string& szOut); // ------------------------------------------------------------------- /** Find the loader corresponding to a specific file extension. * * This is quite similar to IsExtensionSupported() except a * BaseImporter instance is returned. * @param szExtension Extension to be checke, cases insensitive, * must include a trailing dot. * @return NULL if there is no loader for the extension. */ BaseImporter* FindLoader (const std::string& szExtension); // ------------------------------------------------------------------- /** Returns the scene loaded by the last successful call to ReadFile() * * @return Current scene or NULL if there is currently no scene loaded */ inline const aiScene* GetScene(); // ------------------------------------------------------------------- /** Returns the scene loaded by the last successful call to ReadFile() * and releases the scene from the ownership of the Importer * instance. The application is now resposible for deleting the * scene. Any further calls to GetScene() or GetOrphanedScene() * will return NULL - until a new scene has been loaded via ReadFile(). * * @return Current scene or NULL if there is currently no scene loaded */ inline const aiScene* GetOrphanedScene(); // ------------------------------------------------------------------- /** Returns the storage allocated by ASSIMP to hold the asset data * in memory. * \param in Data structure to be filled. */ void GetMemoryRequirements(aiMemoryInfo& in) const; // ------------------------------------------------------------------- /** Enables the "extra verbose" mode. In this mode the data * structure is validated after each post-process step to make sure * all steps behave consequently in the same manner when modifying * data structures. */ inline void SetExtraVerbose(bool bDo); private: /** Empty copy constructor. */ Importer(const Importer &other); protected: /** IO handler to use for all file accesses. */ IOSystem* mIOHandler; bool mIsDefaultHandler; /** Format-specific importer worker objects - * one for each format we can read. */ std::vector<BaseImporter*> mImporter; /** Post processing steps we can apply at the imported data. */ std::vector<BaseProcess*> mPostProcessingSteps; /** The imported data, if ReadFile() was successful, * NULL otherwise. */ aiScene* mScene; /** The error description, if there was one. */ std::string mErrorString; /** List of integer properties */ IntPropertyMap mIntProperties; /** List of floating-point properties */ FloatPropertyMap mFloatProperties; /** List of string properties */ StringPropertyMap mStringProperties; /** Used for testing - extra verbose mode causes the validateDataStructure-Step to be executed before and after every single postprocess step */ bool bExtraVerbose; /** Used by post-process steps to share data */ SharedPostProcessInfo* mPPShared; }; // --------------------------------------------------------------------------- // inline methods for Importer inline const std::string& Importer::GetErrorString() const { return mErrorString; } inline void Importer::SetExtraVerbose(bool bDo) { bExtraVerbose = bDo; } inline const aiScene* Importer::GetOrphanedScene() { aiScene* scene = mScene; mScene = NULL; return scene; } inline const aiScene* Importer::GetScene() { return mScene; } } // End of namespace Assimp #endif // __AI_ASSIMP_HPP_INC
[ "marvin.kicha@e13029a8-578f-11de-8abc-d1c337b90d21" ]
[ [ [ 1, 451 ] ] ]
c3ac404952e866d46bb1fd39fd2970543cacb64e
f7b5d803225fa1fdbcc22b69d8cc083691c68f01
/util/windows_fast_timer.h
df0e329610d8a56c38914eff3fc53481fa47c916
[]
no_license
a40712344/cvaddon
1b3e4b8295eaea3b819598bb7982aa1ba786cb57
e7ebbef09b864b98cce14f0151cef643d2e6bf9d
refs/heads/master
2020-05-20T07:18:49.379088
2008-12-09T03:40:11
2008-12-09T03:40:11
35,675,249
0
0
null
null
null
null
UTF-8
C++
false
false
2,743
h
#ifndef _WINDOWS_FAST_TIMER_H #define _WINDOWS_FAST_TIMER_H //////////////////////////////////////////////////////////// // Windows Fast Timer Class //////////////////////////////////////////////////////////// // By Wai Ho Li //////////////////////////////////////////////////////////// // High accuracy Windows-only timer // Inspired by the class posted in: // http://groups.google.com.au/group/comp.lang.c++/browse_thread/thread/5b78dc1667fdc380/6a7a54dc26c2d425%236a7a54dc26c2d425 //////////////////////////////////////////////////////////// // Usage Notes // --- // Only use to time periods > 50us, as the // timing functions may take considerable // processing time // // Example // --- // while(1) // { // std::cerr << timer.getLoopTime() << std::endl; // <do_processing> // } // // float oldTime = timer.getTime(); // // <do_more_processing> // float timeDif = timer.getTime() - oldTime; // std::cerr << timeDif << std::endl; //////////////////////////////////////////////////////////// // For Query{foo} functions #include <winbase.h> // Highly accurate Windows-only timer // Only use to time periods > 50us, as the // timing functions may take considerable // processing time class FastTimer { public: FastTimer(); ~FastTimer(); // Restarts timer void restart(); // Returns time in ms from last call of restart (or timer creation) float getTime() const; // Returns time from last call of getLoopTime() float getLoopTime(); // Call this to update the counter frequency // May improve accuracy when used every 5-10 timer calls // if used on systems with variable CPU clock ratess void retuneFrequency(); private: LARGE_INTEGER frequency; LARGE_INTEGER startTime; LARGE_INTEGER lastLoopTime; }; inline FastTimer::FastTimer() { QueryPerformanceFrequency( &frequency ); QueryPerformanceCounter( &startTime ); QueryPerformanceCounter( &lastLoopTime ); } inline FastTimer::~FastTimer() {} inline float FastTimer::getTime() const { LARGE_INTEGER curTime; QueryPerformanceCounter( &curTime ); return float( double(curTime.QuadPart - startTime.QuadPart) / double(frequency.QuadPart) * 1e3); } inline void FastTimer::restart() { QueryPerformanceCounter( &startTime ); QueryPerformanceCounter( &lastLoopTime ); } inline float FastTimer::getLoopTime() { LARGE_INTEGER delta; QueryPerformanceCounter( &delta ); delta.QuadPart -= lastLoopTime.QuadPart; QueryPerformanceCounter( &lastLoopTime ); return float( double(delta.QuadPart) / double(frequency.QuadPart) * 1e3); } inline void FastTimer::retuneFrequency() { QueryPerformanceFrequency( &frequency ); } #endif
[ "waiho@66626562-0408-11df-adb7-1be7f7e3f636" ]
[ [ [ 1, 105 ] ] ]
90dcd9a5de3b8ae176984c300e683726b8c217ee
05869e5d7a32845b306353bdf45d2eab70d5eddc
/soft/application/NetworkSimulator/Simulator/ObjectSearch.h
e68f5bef3c7361140fc91d8409247492d525f443
[]
no_license
shenfahsu/sc-fix
beb9dc8034f2a8fd9feb384155fa01d52f3a4b6a
ccc96bfaa3c18f68c38036cf68d3cb34ca5b40cd
refs/heads/master
2020-07-14T16:13:47.424654
2011-07-22T16:46:45
2011-07-22T16:46:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,346
h
/***************************************************************************** * Copyright Statement: * -------------------- * This software is protected by Copyright and the information contained * herein is confidential. The software may not be copied and the information * contained herein may not be used or disclosed except with the written * permission of COOLSAND Inc. (C) 2005 * * BY OPENING THIS FILE, BUYER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES * THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("COOLSAND SOFTWARE") * RECEIVED FROM COOLSAND AND/OR ITS REPRESENTATIVES ARE PROVIDED TO BUYER ON * AN "AS-IS" BASIS ONLY. COOLSAND EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NONINFRINGEMENT. * NEITHER DOES COOLSAND PROVIDE ANY WARRANTY WHATSOEVER WITH RESPECT TO THE * SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, INCORPORATED IN, OR * SUPPLIED WITH THE COOLSAND SOFTWARE, AND BUYER AGREES TO LOOK ONLY TO SUCH * THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. COOLSAND SHALL ALSO * NOT BE RESPONSIBLE FOR ANY COOLSAND SOFTWARE RELEASES MADE TO BUYER'S * SPECIFICATION OR TO CONFORM TO A PARTICULAR STANDARD OR OPEN FORUM. * * BUYER'S SOLE AND EXCLUSIVE REMEDY AND COOLSAND'S ENTIRE AND CUMULATIVE * LIABILITY WITH RESPECT TO THE COOLSAND SOFTWARE RELEASED HEREUNDER WILL BE, * AT COOLSAND'S OPTION, TO REVISE OR REPLACE THE COOLSAND SOFTWARE AT ISSUE, * OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE CHARGE PAID BY BUYER TO * COOLSAND FOR SUCH COOLSAND SOFTWARE AT ISSUE. * * THE TRANSACTION CONTEMPLATED HEREUNDER SHALL BE CONSTRUED IN ACCORDANCE * WITH THE LAWS OF THE STATE OF CALIFORNIA, USA, EXCLUDING ITS CONFLICT OF * LAWS PRINCIPLES. ANY DISPUTES, CONTROVERSIES OR CLAIMS ARISING THEREOF AND * RELATED THERETO SHALL BE SETTLED BY ARBITRATION IN SAN FRANCISCO, CA, UNDER * THE RULES OF THE INTERNATIONAL CHAMBER OF COMMERCE (ICC). * *****************************************************************************/ /************************************************************** FILENAME : ObjectSearch.h PURPOSE : Template class header file. REMARKS : nil AUTHOR : Vikram DATE : Aug 5,03 **************************************************************/ #if !defined(AFX_OBJECTSEARCH_H__C41B5291_473E_4350_A09D_8A6C3318DA94__INCLUDED_) #define AFX_OBJECTSEARCH_H__C41B5291_473E_4350_A09D_8A6C3318DA94__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include "GlobalDEfines.h" template <class T> class CObjectSearch { public: CObjectSearch(); virtual ~CObjectSearch(); ERR GetObject(CPtrList*pList,CString cs, T** tObj); }; template <class T> CObjectSearch<T>::CObjectSearch() { } template <class T> CObjectSearch<T>::~CObjectSearch() { } template <class T> ERR CObjectSearch<T>::GetObject(CPtrList* pList,CString cs, T** tObj) { T* p; for( POSITION pos = pList->GetHeadPosition(); pos != NULL; ) { p = (T*)(pList->GetNext( pos )) ; if(cs==p->GetName()) { *tObj = p; return SUCCESS; } } return FAILURE; }; #endif // !defined(AFX_OBJECTSEARCH_H__C41B5291_473E_4350_A09D_8A6C3318DA94__INCLUDED_)
[ "windyin@2490691b-6763-96f4-2dba-14a298306784" ]
[ [ [ 1, 89 ] ] ]
2512f288b7fc72150c5ffffba68a78f044f9af71
3bfc30f7a07ce0f6eabcd526e39ba1030d84c1f3
/BlobbyWarriors/Source/BlobbyWarriors/Logic/Controller/PlayerController.cpp
72373a177867b719364fc6126455dbdb8d270bf3
[]
no_license
visusnet/Blobby-Warriors
b0b70a0b4769b60d96424b55ad7c47b256e60061
adec63056786e4e8dfcb1ed7f7fe8b09ce05399d
refs/heads/master
2021-01-19T14:09:32.522480
2011-11-29T21:53:25
2011-11-29T21:53:25
2,850,563
0
0
null
null
null
null
UTF-8
C++
false
false
2,801
cpp
#include "PlayerController.h" PlayerController::PlayerController() { GraphicsEngine::getInstance()->subscribe(this); KeyboardHandler::getInstance()->subscribe(this); MouseHandler::getInstance()->subscribe(this); } void PlayerController::update(Publisher *who, UpdateData *what) { if (this->blobby == 0) { return; } KeyEventArgs *keyEventArgs = dynamic_cast<KeyEventArgs*>(what); if (!this->handleKeyEvent(keyEventArgs)) { return; } MouseEventArgs *mouseEventArgs = dynamic_cast<MouseEventArgs*>(what); if (!this->handleMouseEvent(mouseEventArgs)) { return; } } bool PlayerController::handleKeyEvent(KeyEventArgs *keyEventArgs) { b2Body *body = this->blobby->getBody(0); if (keyEventArgs != 0) { if (keyEventArgs->key.code == 'w' && keyEventArgs->key.hasChanged) { this->blobby->jump(); } } if (KeyboardHandler::getInstance()->isKeyDown('a')) { this->blobby->walkLeft(); } else if (KeyboardHandler::getInstance()->isKeyDown('d')) { this->blobby->walkRight(); } else { this->blobby->stopWalk(); } if (KeyboardHandler::getInstance()->isKeyDown('s')) { this->blobby->duck(); } else { this->blobby->standUp(); } return true; } bool PlayerController::handleMouseEvent(MouseEventArgs *mouseEventArgs) { b2Vec2 mousePosition; bool fire = false; bool stopFire = false; if (mouseEventArgs != 0) { mousePosition = pixel2meter(Camera::convertScreenToWorld(mouseEventArgs->x, mouseEventArgs->y)); if (mouseEventArgs->type == MOUSE_BUTTON_STATE_CHANGED && mouseEventArgs->state == MOUSE_STATE_PRESSED && mouseEventArgs->button == MOUSE_BUTTON_LEFT) { fire = true; } else if (mouseEventArgs->type == MOUSE_BUTTON_STATE_CHANGED && mouseEventArgs->state == MOUSE_STATE_RELEASED && mouseEventArgs->button == MOUSE_BUTTON_LEFT) { stopFire = true; } } else { b2Vec2 absoluteMousePosition = MouseHandler::getInstance()->getPosition(); mousePosition = pixel2meter(Camera::convertScreenToWorld(int(absoluteMousePosition.x), int(absoluteMousePosition.y))); } if (this->blobby->getWeapon() != 0) { AbstractWeapon *weapon = this->blobby->getWeapon(); b2Vec2 weaponPosition = weapon->getBody(0)->GetPosition(); b2Vec2 a = mousePosition - weaponPosition; b2Vec2 b = b2Vec2(1, 0); a.Normalize(); b.Normalize(); float angle = acosf(a.x * b.x + a.y * b.y); if (weaponPosition.y > mousePosition.y) { angle = b2_pi - angle; } if (fire) { weapon->fire(a, false, true); } else if (MouseHandler::getInstance()->isButtonPressed(MOUSE_BUTTON_LEFT)) { weapon->fire(a, false, true); } else if (stopFire) { weapon->stopFire(); } weapon->getBody(0)->SetTransform(weapon->getBody(0)->GetPosition(), angle); } return true; }
[ [ [ 1, 94 ] ] ]
261d241eca99388e6e3690cbcffc905c037ff377
4d1ff12001a4f9e3bb54ac8ef6bb14d056f97133
/stdafx.h
39134ef54e7bae7a459fa61959ddaefd5c6ecb20
[]
no_license
semog/svndiff3
0a422f7520645e8cb9414b8e5e688b0d7339c400
db6bf942ff1e5091a740e0af203a73d562381981
refs/heads/master
2021-01-19T21:29:00.473003
2008-04-22T21:59:49
2008-04-22T21:59:49
32,508,301
0
0
null
null
null
null
UTF-8
C++
false
false
768
h
// stdafx.h : include file for standard system include files, // or project specific include files that are used frequently, but // are changed infrequently // #pragma once #include "targetver.h" #define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers // Windows Header Files: #include <windows.h> #include <stdio.h> #include <tchar.h> #include <stdlib.h> #include <io.h> #include <process.h> #include <fcntl.h> #include <sys/stat.h> #include <share.h> #include <vector> #include <string> using namespace std; #ifdef UNICODE #define tstring wstring #else #define tstring string #endif // Define some pseudo-keywords to be more explicit #define ref #define out #define NULCHAR TEXT('\0')
[ "e.semog@3c9b7e3f-6b4b-0410-9807-2539ebdfb00e" ]
[ [ [ 1, 38 ] ] ]
27468fa7e1e4a55737d62673664dc4cb349c156b
06ff805f168597297a87642c951867b453e401f7
/Algorithm/boost/boost/mpl/integral_c.hpp
ebc9b913bb890a9585c6b35d06c004b7e0c5ef81
[]
no_license
fredska/algorithms
58459720295f8cf36edc88f68e4b37962235e533
10538d9677894b450f359db9301108b459b604ca
refs/heads/master
2021-01-02T09:38:34.466733
2011-11-09T17:32:57
2011-11-09T17:32:57
2,652,603
1
0
null
null
null
null
UTF-8
C++
false
false
1,639
hpp
#ifndef BOOST_MPL_INTEGRAL_C_HPP_INCLUDED #define BOOST_MPL_INTEGRAL_C_HPP_INCLUDED // Copyright Aleksey Gurtovoy 2000-2006 // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // See http://www.boost.org/libs/mpl for documentation. // $Id: integral_c.hpp,v 1.1 2010-07-13 06:44:15 egraf Exp $ // $Date: 2010-07-13 06:44:15 $ // $Revision: 1.1 $ #include <boost/mpl/integral_c_fwd.hpp> #include <boost/mpl/aux_/config/ctps.hpp> #include <boost/mpl/aux_/config/static_constant.hpp> #include <boost/mpl/aux_/config/workaround.hpp> #if BOOST_WORKAROUND(__HP_aCC, <= 53800) // the type of non-type template arguments may not depend on template arguments # define AUX_WRAPPER_PARAMS(N) typename T, long N #else # define AUX_WRAPPER_PARAMS(N) typename T, T N #endif #define AUX_WRAPPER_NAME integral_c #define AUX_WRAPPER_VALUE_TYPE T #define AUX_WRAPPER_INST(value) AUX_WRAPPER_NAME< T, value > #include <boost/mpl/aux_/integral_wrapper.hpp> #if !defined(BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION) \ && !BOOST_WORKAROUND(__BORLANDC__, <= 0x551) BOOST_MPL_AUX_ADL_BARRIER_NAMESPACE_OPEN // 'bool' constant doesn't have 'next'/'prior' members template< bool C > struct integral_c<bool, C> { BOOST_STATIC_CONSTANT(bool, value = C); typedef integral_c_tag tag; typedef integral_c type; typedef bool value_type; operator bool() const { return this->value; } }; BOOST_MPL_AUX_ADL_BARRIER_NAMESPACE_CLOSE #endif #endif // BOOST_MPL_INTEGRAL_C_HPP_INCLUDED
[ [ [ 1, 51 ] ] ]
7b41fd01963112d8ca0cd772e0cbe664cadcb753
59166d9d1eea9b034ac331d9c5590362ab942a8f
/FrustumTerrainShader/TerrainShader/TerrainShaderPatchNode.h
19bf2492d0e2f886d77575431e36233c744c1479
[]
no_license
seafengl/osgtraining
5915f7b3a3c78334b9029ee58e6c1cb54de5c220
fbfb29e5ae8cab6fa13900e417b6cba3a8c559df
refs/heads/master
2020-04-09T07:32:31.981473
2010-09-03T15:10:30
2010-09-03T15:10:30
40,032,354
0
3
null
null
null
null
WINDOWS-1251
C++
false
false
1,443
h
#ifndef _TERRAIN_SHADER_PATCH_NODE_H_ #define _TERRAIN_SHADER_PATCH_NODE_H_ #include <osg/Group> #include <osg/Referenced> #include <osg/ref_ptr> #include <osg/Program> class TerrainShaderPatchNode : public osg::Referenced { public: TerrainShaderPatchNode(); virtual ~TerrainShaderPatchNode(); //вернуть узел содержащий части земли osg::ref_ptr< osg::Group > getRootNode() { return m_rootNode.get(); } private: //инициализировать корневой узел земли void InitTerrainNode(); //добавить текстуру с индексами void AddTextureIndex(); //добавить составную текстуру void AddTexturePatches(); ////////////////////////////////////////////////////////////////////////// //добавить текстуру для микроландшафта void AddMicroTexture( std::string _sFile , int _iMod ); //добавить шейдер в узел void AddShader(); //настроить uniform'ы void SetupUniforms( osg::StateSet* ss ); // load source from a file. void LoadShaderSource( osg::Shader* shader, const std::string& fileName ); //uniform для задания положения наблюдателя osg::ref_ptr< osg::Uniform > m_unfVisPos; //корневой узел osg::ref_ptr< osg::Group > m_rootNode; }; #endif //_TERRAIN_SHADER_PATCH_NODE_H_
[ "asmzx79@3290fc28-3049-11de-8daa-cfecb5f7ff5b" ]
[ [ [ 1, 48 ] ] ]
59f7e0ffd4c069bce10e3cda6ecc4480c066bd95
b14d5833a79518a40d302e5eb40ed5da193cf1b2
/cpp/extern/crypto++/5.2.1/md2.cpp
19657fb2da340dea2137b038f5fb0a6cdb4f8345
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-cryptopp" ]
permissive
andyburke/bitflood
dcb3fb62dad7fa5e20cf9f1d58aaa94be30e82bf
fca6c0b635d07da4e6c7fbfa032921c827a981d6
refs/heads/master
2016-09-10T02:14:35.564530
2011-11-17T09:51:49
2011-11-17T09:51:49
2,794,411
1
0
null
null
null
null
UTF-8
C++
false
false
3,038
cpp
// md2.cpp - modified by Wei Dai from Andrew M. Kuchling's md2.c // The original code and all modifications are in the public domain. // This is the original introductory comment: /* * md2.c : MD2 hash algorithm. * * Part of the Python Cryptography Toolkit, version 1.1 * * Distribute and use freely; there are no restrictions on further * dissemination and usage except those imposed by the laws of your * country of residence. * */ #include "pch.h" #include "md2.h" NAMESPACE_BEGIN(CryptoPP) MD2::MD2() : m_X(48), m_C(16), m_buf(16) { Init(); } void MD2::Init() { memset(m_X, 0, 48); memset(m_C, 0, 16); memset(m_buf, 0, 16); m_count = 0; } void MD2::Update(const byte *buf, unsigned int len) { static const byte S[256] = { 41, 46, 67, 201, 162, 216, 124, 1, 61, 54, 84, 161, 236, 240, 6, 19, 98, 167, 5, 243, 192, 199, 115, 140, 152, 147, 43, 217, 188, 76, 130, 202, 30, 155, 87, 60, 253, 212, 224, 22, 103, 66, 111, 24, 138, 23, 229, 18, 190, 78, 196, 214, 218, 158, 222, 73, 160, 251, 245, 142, 187, 47, 238, 122, 169, 104, 121, 145, 21, 178, 7, 63, 148, 194, 16, 137, 11, 34, 95, 33, 128, 127, 93, 154, 90, 144, 50, 39, 53, 62, 204, 231, 191, 247, 151, 3, 255, 25, 48, 179, 72, 165, 181, 209, 215, 94, 146, 42, 172, 86, 170, 198, 79, 184, 56, 210, 150, 164, 125, 182, 118, 252, 107, 226, 156, 116, 4, 241, 69, 157, 112, 89, 100, 113, 135, 32, 134, 91, 207, 101, 230, 45, 168, 2, 27, 96, 37, 173, 174, 176, 185, 246, 28, 70, 97, 105, 52, 64, 126, 15, 85, 71, 163, 35, 221, 81, 175, 58, 195, 92, 249, 206, 186, 197, 234, 38, 44, 83, 13, 110, 133, 40, 132, 9, 211, 223, 205, 244, 65, 129, 77, 82, 106, 220, 55, 200, 108, 193, 171, 250, 36, 225, 123, 8, 12, 189, 177, 74, 120, 136, 149, 139, 227, 99, 232, 109, 233, 203, 213, 254, 59, 0, 29, 57, 242, 239, 183, 14, 102, 88, 208, 228, 166, 119, 114, 248, 235, 117, 75, 10, 49, 68, 80, 180, 143, 237, 31, 26, 219, 153, 141, 51, 159, 17, 131, 20 }; while (len) { word32 L = (16-m_count) < len ? (16-m_count) : len; memcpy(m_buf+m_count, buf, L); m_count+=L; buf+=L; len-=L; if (m_count==16) { byte t; int i,j; m_count=0; memcpy(m_X+16, m_buf, 16); t=m_C[15]; for(i=0; i<16; i++) { m_X[32+i]=m_X[16+i]^m_X[i]; t=m_C[i]^=S[m_buf[i]^t]; } t=0; for(i=0; i<18; i++) { for(j=0; j<48; j+=8) { t=m_X[j+0]^=S[t]; t=m_X[j+1]^=S[t]; t=m_X[j+2]^=S[t]; t=m_X[j+3]^=S[t]; t=m_X[j+4]^=S[t]; t=m_X[j+5]^=S[t]; t=m_X[j+6]^=S[t]; t=m_X[j+7]^=S[t]; } t=(t+i) & 0xFF; } } } } void MD2::TruncatedFinal(byte *hash, unsigned int size) { ThrowIfInvalidTruncatedSize(size); byte padding[16]; word32 padlen; unsigned int i; padlen= 16-m_count; for(i=0; i<padlen; i++) padding[i]=(byte)padlen; Update(padding, padlen); Update(m_C, 16); memcpy(hash, m_X, size); Init(); } NAMESPACE_END
[ [ [ 1, 117 ] ] ]
dcaf5c551dae65e0e7723bad2cb08847726988db
54d6164d9f32e7de52b9d43bac815b55c96f2fdc
/src/GLRenderSHP.cpp
594c23a3ceeffc627aa0bc47143f787e14d8c200
[]
no_license
hpeikemo/WorldViz
93c09ed3ec7ae365594d322be76c5bdb2227a4ad
168f5007dc847d1459a81406c925beae0260895f
refs/heads/master
2016-09-10T11:14:28.561051
2010-08-23T07:35:20
2010-08-23T07:35:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,587
cpp
//Program to Parse ESRI Shapefile and render it in OpenGL //Author : Dhulipudi Durga Prasad //Contact: [email protected] //Libraries Used: Shapelib ,OpenGL #include <stdlib.h> #include "stdio.h" #include "shapelib/shapefil.h" #include <vector> using namespace std; typedef struct MyPoint2D { double dX; double dY; }MyPoint2D; //Holds Coordinates of Point Shapefile vector<MyPoint2D> vPoints; typedef struct MyLineString2D { vector<MyPoint2D> vPointList; }MyLineString2D; //Holds Coordinates of Line Shapefile vector<MyLineString2D> vLines; typedef struct MyPolygon2D { vector<MyPoint2D> vPointList; }MyPolygon2D; //Holds Coordinates of Polygon Shapefile vector<MyPolygon2D> vPolygons; typedef struct SBoundingBox { float fMaxX; float fMaxY; float fMinX; float fMinY; }SBoundingBox; //Bounding Box of Shapefile SBoundingBox sBoundingBox; //Function to Open Shapefile and parse the info void OpenShapeFile(char* fileName) { SHPHandle hSHP=SHPOpen(fileName, "rb" ); //Read Bounding Box of Shapefile sBoundingBox.fMaxX=hSHP->adBoundsMax[0]; sBoundingBox.fMaxY=hSHP->adBoundsMax[1]; sBoundingBox.fMinX=hSHP->adBoundsMin[0]; sBoundingBox.fMinY=hSHP->adBoundsMin[1]; if(hSHP == NULL) return; //Point Shapefile if(hSHP->nShapeType == SHPT_POINT) { SHPObject *psShape; for(int i=0;i<hSHP->nRecords;i++) { psShape = SHPReadObject(hSHP, i); double fX = psShape->padfX[0]; double fY = -psShape->padfY[0]; //Plot these points MyPoint2D pt; pt.dX=fX; pt.dY=-fY; vPoints.push_back(pt); } } //Line Shapefile else if(hSHP->nShapeType == SHPT_ARC) { SHPObject *psShape; for(int i=0;i<hSHP->nRecords;i++) { psShape = SHPReadObject(hSHP, i); vector<MyPoint2D> tempPointArray; for(int j=0;j<psShape->nVertices;j++) { double fX = psShape->padfX[j]; double fY = psShape->padfY[j]; MyPoint2D pt; pt.dX=fX; pt.dY=fY; tempPointArray.push_back(pt); } MyLineString2D linestring; linestring.vPointList=tempPointArray; vLines.push_back(linestring); } } //Polygon Shapefile if(hSHP->nShapeType == SHPT_POLYGON) { SHPObject *psShape; for(int i=0;i<hSHP->nRecords;i++) { psShape = SHPReadObject(hSHP, i); for (int p=0;p<psShape->nParts;p++) { vector<MyPoint2D> tempPointArray; int pstart = psShape->panPartStart[p]; int pend; if (p+1 < psShape->nParts) { pend = psShape->panPartStart[p+1]; } else { pend = psShape->nVertices; } for(int j=pstart;j<pend;j++) { double fX = psShape->padfX[j]; double fY = psShape->padfY[j]; MyPoint2D pt; pt.dX=fX; pt.dY=fY; tempPointArray.push_back(pt); } MyPolygon2D polygon; polygon.vPointList=tempPointArray; vPolygons.push_back(polygon); } } } }
[ [ [ 1, 156 ] ] ]
7394a45e70165108385847a46694897754e8372c
5fb9b06a4bf002fc851502717a020362b7d9d042
/developertools/GumpEditor/diagram/DialogEditorDemoDoc.cpp
688eeca7247941c6bf2cac89cda2a70fe979928f
[]
no_license
bravesoftdz/iris-svn
8f30b28773cf55ecf8951b982370854536d78870
c03438fcf59d9c788f6cb66b6cb9cf7235fbcbd4
refs/heads/master
2021-12-05T18:32:54.525624
2006-08-21T13:10:54
2006-08-21T13:10:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,219
cpp
// DialogEditorDemoDoc.cpp : implementation of the CDialogEditorDemoDoc class // #include "stdafx.h" #include "DialogEditorDemo.h" #include "DialogEditorDemoDoc.h" // --- DiagramEditor --- //#include "DiagramControlFactory.h" #include "TextFile.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #pragma warning( disable : 4706 ) ///////////////////////////////////////////////////////////////////////////// // CDialogEditorDemoDoc IMPLEMENT_DYNCREATE(CDialogEditorDemoDoc, CDocument) BEGIN_MESSAGE_MAP(CDialogEditorDemoDoc, CDocument) //{{AFX_MSG_MAP(CDialogEditorDemoDoc) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CDialogEditorDemoDoc construction/destruction CDialogEditorDemoDoc::CDialogEditorDemoDoc() { } CDialogEditorDemoDoc::~CDialogEditorDemoDoc() { } BOOL CDialogEditorDemoDoc::OnNewDocument() { if (!CDocument::OnNewDocument()) return FALSE; // --- DiagramEditor --- // Removing the current data m_objs.Clear(); return TRUE; } ///////////////////////////////////////////////////////////////////////////// // CDialogEditorDemoDoc serialization void CDialogEditorDemoDoc::Serialize(CArchive& ar) { #if 0 // --- DiagramEditor --- // Saving and loading to/from a text file if (ar.IsStoring()) { ar.WriteString( m_objs.GetString() + _T( "\r\n" ) ); int count = 0; CDiagramEntity* obj; while( ( obj = m_objs.GetAt( count++ ) ) ) ar.WriteString( obj->GetString() + _T( "\r\n" ) ); m_objs.SetModified( FALSE ); } else { m_objs.Clear(); CString str; while(ar.ReadString( str ) ) { if( !m_objs.FromString( str ) ) { CDiagramEntity* obj = CDiagramControlFactory::CreateFromString( str ); if( obj ) m_objs.Add( obj ); } } m_objs.SetModified( FALSE ); } #endif } ///////////////////////////////////////////////////////////////////////////// // CDialogEditorDemoDoc diagnostics #ifdef _DEBUG void CDialogEditorDemoDoc::AssertValid() const { CDocument::AssertValid(); } void CDialogEditorDemoDoc::Dump(CDumpContext& dc) const { CDocument::Dump(dc); } #endif //_DEBUG ///////////////////////////////////////////////////////////////////////////// // CDialogEditorDemoDoc commands // --- DiagramEditor --- CDiagramEntityContainer* CDialogEditorDemoDoc::GetData() { // Data accessor return &m_objs; } BOOL CDialogEditorDemoDoc::SaveModified() { // We override this to get the dirty- // handling right SetModifiedFlag( m_objs.IsModified() ); return CDocument::SaveModified(); } void CDialogEditorDemoDoc::Export() { // An example of exporting CString filename; CStringArray stra; // Header. I don't want this in the CDiagramEntityContainer class // where it would normally belong, as it should not be necessary // to derive a class from CDiagramEntityContainer. stra.Add( _T( "<html>" ) ); stra.Add( _T( "<head>" ) ); stra.Add( _T( "<style>" ) ); stra.Add( _T( "\t.controls { font-family:MS Sans Serif;font-size:12; }" ) ); stra.Add( _T( "\tbody { background-color:#c0c0c0; }" ) ); stra.Add( _T( "</style>" ) ); stra.Add( _T( "<script>" ) ); stra.Add( _T( "function buttonHandler( obj )" ) ); stra.Add( _T( "{" ) ); stra.Add( _T( "\talert( obj.name )" ) ); stra.Add( _T( "}" ) ); stra.Add( _T( "function checkboxHandler( obj )" ) ); stra.Add( _T( "{" ) ); stra.Add( _T( "\talert( obj.name )" ) ); stra.Add( _T( "}" ) ); stra.Add( _T( "function radiobuttonHandler( obj )" ) ); stra.Add( _T( "{" ) ); stra.Add( _T( "\talert( obj.name )" ) ); stra.Add( _T( "}" ) ); stra.Add( _T( "function listboxHandler( obj )" ) ); stra.Add( _T( "{" ) ); stra.Add( _T( "\talert( obj.name )" ) ); stra.Add( _T( "}" ) ); stra.Add( _T( "function comboboxHandler( obj )" ) ); stra.Add( _T( "{" ) ); stra.Add( _T( "\talert( obj.name )" ) ); stra.Add( _T( "}" ) ); stra.Add( _T( "</script>" ) ); stra.Add( _T( "</head>" ) ); stra.Add( _T( "<body topmargin=0 leftmargin=0>" ) ); CRect rect( 0, 0, m_objs.GetVirtualSize().cx + 1, m_objs.GetVirtualSize().cy + 1 ); CString input1( _T( "<div style='position:absolute;left:%i;top:%i;width:%i;height:%i;border:1 solid black;'>" ) ); CString input2( _T( "<div style='position:absolute;left:0;top:0;width:%i;height:%i;border-top:1 solid white;border-left:1 solid white;border-right:1 solid gray;border-bottom:1 solid gray;'>" ) ); CString str; str.Format( input1, rect.left, rect.top, rect.Width(), rect.Height() ); stra.Add( str ); rect.InflateRect( -1, -1 ); str.Format( input2, rect.Width(), rect.Height() ); stra.Add( str ); // The export itself m_objs.Export( stra ); // The footer stra.Add( _T( "</div>" ) ); stra.Add( _T( "</div>" ) ); stra.Add( _T( "</body>" ) ); stra.Add( _T( "</html>" ) ); // Writing it to a file CTextFile tf( _T( "html" ), _T( "\n" ) ); if( !tf.WriteTextFile( filename, stra ) ) if( filename.GetLength() ) AfxMessageBox( tf.GetErrorMessage() ); } #pragma warning( default : 4706 )
[ "sience@a725d9c3-d2eb-0310-b856-fa980ef11a19" ]
[ [ [ 1, 201 ] ] ]
d1a6be87c78f9e55a9756dae6aabcb8d8ac9a329
d7910157c6f2b58f159ec8dc2634e0acfe6d678e
/qtdemo/demotextitem.h
9285ca34585525018be492c2bf5bd92c88d96913
[]
no_license
TheProjecter/qtdemo-plugin
7699b19242aacea9c5b2c741e615e6b1e62c6c11
4db5ffe7e8607e01686117820ce1fcafb72eb311
refs/heads/master
2021-01-19T06:30:22.017229
2010-02-05T06:36:25
2010-02-05T06:36:25
43,904,026
0
0
null
null
null
null
UTF-8
C++
false
false
2,962
h
/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the demonstration applications of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial Usage ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef DEMO_TEXT_ITEM_H #define DEMO_TEXT_ITEM_H #include <QtGui> #include "demoitem.h" class DemoTextItem : public DemoItem { public: enum TYPE {STATIC_TEXT, DYNAMIC_TEXT}; DemoTextItem(const QString &text, const QFont &font, const QColor &textColor, float textWidth, QGraphicsScene *scene = 0, QGraphicsItem *parent = 0, TYPE type = STATIC_TEXT, const QColor &bgColor = QColor()); void setText(const QString &text); QRectF boundingRect() const; // overridden void animationStarted(int id = 0); void animationStopped(int id = 0); protected: virtual QImage *createImage(const QMatrix &matrix) const; // overridden virtual void paint(QPainter *painter, const QStyleOptionGraphicsItem *option = 0, QWidget *widget = 0); // overridden private: float textWidth; QString text; QFont font; QColor textColor; QColor bgColor; TYPE type; }; #endif // DEMO_TEXT_ITEM_H
[ "douyongwang@152bb772-114e-11df-9f54-17e475596acb" ]
[ [ [ 1, 74 ] ] ]
ffaf855603d5504cc7c1f28de422a7e15e913f76
bc4919e48aa47e9f8866dcfc368a14e8bbabbfe2
/Open GL Basic Engine/source/glutFramework/glutFramework/interpreter.cpp
b1b75a70ccb7d189af3bd960ba9363439a98acd9
[]
no_license
CorwinJV/rvbgame
0f2723ed3a4c1a368fc3bac69052091d2d87de77
a4fc13ed95bd3e5a03e3c6ecff633fe37718314b
refs/heads/master
2021-01-01T06:49:33.445550
2009-11-03T23:14:39
2009-11-03T23:14:39
32,131,378
0
0
null
null
null
null
UTF-8
C++
false
false
690
cpp
#include "interpreter.h" void interpreter::addInterp(std::string name, CFunctionPointer0R<bool> nTargetFunc, int numVars = 0) { interpObj* tempInterpObj; tempInterpObj = new interpObj(); tempInterpObj->setTargetFunc(nTargetFunc); tempInterpObj->setNumVars(numVars); tempInterpObj->setName(name); interpList.push_back(tempInterpObj); } void interpreter::interpret(std::string interpMe) { std::vector<interpObj*>::iterator iitr = interpList.begin(); // iterate through the vector looking for a pattern match for(;iitr < interpList.end(); iitr++) { // found the match if(interpMe == (*iitr)->getName()) { // do whatever should be done } } }
[ "corwin.j@5457d560-9b84-11de-b17c-2fd642447241" ]
[ [ [ 1, 26 ] ] ]
41d71dd20e3fbb400638a3b2a3439703c7303852
6253ab92ce2e85b4db9393aa630bde24655bd9b4
/Common/math/matrix.template.h
cff80b7135de0e1ff4ced7fe1a7a8eac99af24f6
[]
no_license
Aand1/cornell-urban-challenge
94fd4df18fd4b6cc6e12d30ed8eed280826d4aed
779daae8703fe68e7c6256932883de32a309a119
refs/heads/master
2021-01-18T11:57:48.267384
2008-10-01T06:43:18
2008-10-01T06:43:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
11,229
h
#ifndef _MATRIX_H #define _MATRIX_H #include <cassert> #include "acml.h" #include "../coords/dpvector3.h" #include "../coords/dpmatrix3.h" class matrix_exception { private: size_t len; char* msg; public: matrix_exception(); matrix_exception(const char* msg); matrix_exception(const matrix_exception&); virtual matrix_exception& operator = (const matrix_exception&); virtual ~matrix_exception(); virtual const char* what() const; }; template<int m, int n> class dpmatrix { protected: double d[n][m]; // store in column major order public: dpmatrix() {}; dpmatrix(const double* c) { for (int j = 0; j < n; j++) { // column index for (int i = 0; i < m; i++) { // row index d[j][i] = c[j * m + i]; } } } dpmatrix(const dpmatrix<m, n>& c) { for (int j = 0; j < n; j++) { for (int i = 0; i < m; i++) { d[j][i] = c.d[j][i]; } } } inline dpmatrix<m, n>& operator = (const dpmatrix<m, n>& c) { for (int j = 0; j < n; j++) for (int i = 0; i < m; i++) d[j][i] = c(i, j); return *this; } inline operator double * () { return (double*)d; } inline double operator () (const int i, const int j) const { assert(i >= 0 && i < m && j >= 0 && j < n); return d[j][i]; } inline double& operator() (const int i, const int j) { assert(i >= 0 && i < m && j >= 0 && j < n); return d[j][i]; } virtual dpmatrix<n, m> trans() const { dpmatrix<n, m> r; for (int j = 0; j < n; j++) { for (int i = 0; i < m; i++) { r(j, i) = d[j][i]; } } return r; } template<int k, int l> void set_submatrix(const int i_start, const int j_start, const dpmatrix<k, l>& mat) { assert(i_start >= 0 && i_start + k <= m && j_start >= 0 && j_start + l <= n); for (int j = j_start; j < j_start + l; j++) { for (int i = i_start; i < i_start + k; i++) { operator()(i, j) = mat(i - i_start, j - j_start); } } } template<int k, int l> void get_submatrix(const int i_start, const int j_start, dpmatrix<k, l>& dest) { assert(i_start >= 0 && i_start + k <= m && j_start >= 0 && j_start + l <= n); for (int j = j_start; j < j_start + l; j++) { for (int i = i_start; i < i_start + k; i++) { dest(i - i_start, j - j_start) = operator()(i, j); } } } template<int k, int l> dpmatrix<k, l> get_submatrix(const int i_start, const int j_start) const { dpmatrix<k, l> r; get_submatrix(i_start, j_start, r); return r; } inline int lda() const { return m; } }; template<int m, bool upper> class tri_dpmatrix : public dpmatrix<m, m> { public: tri_dpmatrix() {} tri_dpmatrix(const double* c) : dpmatrix<m, m>(c) {} tri_dpmatrix(const dpmatrix<m, m>& c) : dpmatrix<m, m>(c) {} tri_dpmatrix(const tri_dpmatrix<m, upper> &c) : dpmatrix<m, m>((double*)c.d) {} virtual dpmatrix<m, m> trans() const { return tri_dpmatrix<m, !upper>(dpmatrix<m, m>::trans()); } }; template<> class dpmatrix<3, 1> { private: dpvector3 d; public: inline dpmatrix() {} inline dpmatrix(const double* c) : d(c) {} inline dpmatrix(const dpmatrix<3, 1>& c) : d(c.d) {} inline dpmatrix(const dpvector3 &c) : d(c) {} inline dpmatrix<3, 1>& operator = (const dpmatrix<3, 1>& c) { d = c.d; return *this; } inline operator double* () { return (double*)&d; } inline double operator () (const int i, const int j) const { return d[i]; } inline double& operator() (const int i, const int j) { return d[i]; } virtual dpmatrix<1, 3> trans() const { return dpmatrix<1, 3>(d); } inline int lda() const { return 4; } }; template<> class dpmatrix<1, 3> { private: dpvector3 d; public: inline dpmatrix() {} inline dpmatrix(const double* c) : d(c) {} inline dpmatrix(const dpmatrix<1, 3> &c) : d(c.d) {} inline dpmatrix(const dpvector3 &c) : d(c) {} inline dpmatrix<1, 3>& operator = (const dpmatrix<1, 3>& c) { d = c.d; return *this; } inline operator double* () { return (double*)&d; } inline double operator () (const int i, const int j) const { return d[i]; } inline double& operator() (const int i, const int j) { return d[i]; } virtual dpmatrix<3, 1> trans() const { return dpmatrix<3, 1>(d); } inline int lda() const { return 4; } }; template<> class dpmatrix<3, 3> { private: dpmatrix3 d; public: inline dpmatrix() {} inline dpmatrix(const double* c) : d(c) {} inline dpmatrix(const dpmatrix<3, 3> &c) : d(c.d) {} inline dpmatrix(const dpmatrix3 &c) : d(c) {} inline dpmatrix<3, 3>& operator = (const dpmatrix<3, 3>& c) { d = c.d; return *this; } inline operator double* () { return (double*)&d; } inline double operator () (const int i, const int j) const { return d(i, j); } inline double& operator() (const int i, const int j) { return d(i, j); } virtual dpmatrix<3, 3> trans() const { return dpmatrix<3, 3>(d.transpose()); } inline int lda() const { return 4; } template<int m, int k, int n> friend dpmatrix<m, n> operator * (const dpmatrix<m, k>&, const dpmatrix<k, n>&); }; // utility operator for matrix multiplication // this doesn't allow most the flexibility that you get with the BLAS multiplication, but it's decent template <int m, int k, int n> inline dpmatrix<m, n> operator * (const dpmatrix<m, k> &A, const dpmatrix<k, n> &B) { dpmatrix<m, n> C; dgemm('N', 'N', m, n, k, 1.0, ((dpmatrix<m,k>&)A), A.lda(), (dpmatrix<m,k>&)B, B.lda(), 0.0, C, C.lda()); return C; } template<> inline dpmatrix<3, 3> operator * (const dpmatrix<3, 3> &A, const dpmatrix<3, 3> &B) { return dpmatrix<3, 3>(A.d * B.d); } template<int m, bool upper> inline tri_dpmatrix<m, upper> operator * (const tri_dpmatrix<m, upper> &A, const tri_dpmatrix<m, upper> &B) { tri_dpmatrix<m, upper> temp(B); dtrmm('L', upper ? 'U' : 'L', 'N', 'N', m, m, 1.0, (tri_dpmatrix<m, upper>&)A, A.lda(), temp, temp.lda()); return temp; } template<int m, bool upper> inline void mat_mult(const tri_dpmatrix<m, upper> &A, tri_dpmatrix<m, upper> &B, const double ab_coeff = 1.0) { dtrmm('L', upper ? 'U' : 'L', 'N', 'N', m, m, ab_coeff, (tri_dpmatrix<m, upper>&)A, A.lda(), B, B.lda()); } // TODO: could specialize multiplication for vector3, matrix3 template<int m, int k> inline dpmatrix<m, k> operator - (const dpmatrix<m, k>& A, const dpmatrix<m, k>& B) { dpmatrix<m, k> r; for (int j = 0; j < k; j++) for (int i = 0; i < m; i++) r(i, j) = A(i, j) - B(i, j); return r; } template<int m, int k> inline dpmatrix<m, k> operator + (const dpmatrix<m, k>& A, const dpmatrix<m, k>& B) { dpmatrix<m, k> r; for (int j = 0; j < k; j++) for (int i = 0; i < m; i++) r(i, j) = A(i, j) + B(i, j); return r; } template<int m, int k> inline dpmatrix<m, k>& operator -= (dpmatrix<m, k>& A, const dpmatrix<m, k>& B) { for (int j = 0; j < k; j++) for (int i = 0; i < m; i++) A(i, j) -= B(i, j); return A; } template<int m, int k> inline dpmatrix<m, k>& operator += (dpmatrix<m, k>& A, const dpmatrix<m, k>& B) { for (int j = 0; j < k; j++) for (int i = 0; i < m; i++) A(i, j) += B(i, j); return A; } template<int m, int k> inline dpmatrix<m, k> operator * (const dpmatrix<m, k>& A, const double d) { dpmatrix<m, k> r; for (int j = 0; j < k; j++) for (int i = 0; i < m; i++) r(i, j) = A(i, j) * d; return r; } template<int m, int k> inline dpmatrix<m, k> operator * (const double d, const dpmatrix<m, k>& A) { return A * d; } template<int m, int k> inline dpmatrix<m, k> operator / (const dpmatrix<m, k>& A, const double d) { dpmatrix<m, k> r; double recip = 1.0/d; for (int j = 0; j < k; j++) for (int i = 0; i < m; i++) r(i, j) = A(i, j) * recip; return r; } template<int m, int k> inline dpmatrix<m, k>& operator *= (dpmatrix<m, k>& A, const double d ) { for (int j = 0; j < k; j++) for (int i = 0; i < m; i++) A(i, j) *= d; return A; } template<int m, int k> inline dpmatrix<m, k>& operator /= (dpmatrix<m, k>& A, const double d) { double recip = 1.0 / d; for (int j = 0; j < k; j++) for (int i = 0; i < m; i++) A(i, j) *= recip; return A; } template <int m, int k, int n> inline void mat_mult(const dpmatrix<m, k> &A, const dpmatrix<k, n> &B, dpmatrix<m, n> &C, double ab_coeff = 1.0, double c_coeff = 0.0) { dgemm('N', 'N', m, n, k, ab_coeff, A, A.lda(), B, B.lda(), c_coeff, C, C.lda()); } template <int m, int k, int n> inline dpmatrix<m, n> mat_mult(const dpmatrix<m, k> &A, const dpmatrix<k, n> &B, double ab_coeff = 1.0) { dpmatrix<m, n> C; dgemm('N', 'N', m, n, k, ab_ceoff, A, A.lda(), B, B.lda(), 0.0, C, C.lda()); return C; } template <int m> inline dpmatrix<m, m> eye() { dpmatrix<m, m> r; for (int j = 0; j < m; j++) for (int i = 0; i < m; i++) { if (i == j) r(i, j) = 1.0; else r(i, j) = 0.0; } return r; } template<> inline dpmatrix<3, 3> eye() { return dpmatrix<3, 3>(dpmatrix3::identity()); } template <int m, int n> inline dpmatrix<m, n> zeros() { dpmatrix<m, n> r; for (int j = 0; j < n; j++) for (int i = 0; i < m; i++) r[i, j] = 0.0; return r; } template <> inline dpmatrix<3, 3> zeros() { return dpmatrix<3, 3>(dpmatrix3::zero()); } template<int m> inline void chol_ip(dpmatrix<m, m>& c) throw(...) { int info; dpotrf(upper ? 'U' : 'L', m, c.lda(), &info); if (info != 0) throw matrix_exception("Error computing cholesky factorization"); for (int j = 0; j < m - i; j++) { for (int i = j + 1; i < m; i++) { // fill in zeros, these aren't set in factorization routine c(i, j) = 0.0; } } } template<int m> inline tri_dpmatrix<m, true>chol(const dpmatrix<m, m>& c) throw(...) { tri_dpmatrix<m, true> temp(c); chol_ip(temp); return temp; } template<int m> inline void inv_lu(dpmatrix<m, m> &c) throw(...) { int info; int ipiv[m]; // see http://www.netlib.org/lapack/double/dgetrf.f for more information dgetrf(m, m, c, c.lda(), ipiv, &info); // check for success if (info != 0) throw matrix_exception("Error computing LU factorization in inv_lu"); // now compute the inverse // see http://www.netlib.org/lapack/double/dgetri.f for more information dgetri(m, c, c.lda(), ipiv, &info); if (info != 0) throw matrix_exception("Error computing inverse in inv_lu"); } template<int m> inline void inv_chol(dpmatrix<m, m> &c) throw(...) { int info; // use cholesky factorization and then find the inverse using that // this method should be about 2-4 times faster than LU decomposition // see http://www.netlib.org/lapack/double/dpotrf.f dpotrf('U', m, c, c.lda(), &info); if (info != 0) throw matrix_exception("Error computing cholesky factorization in inv_chol"); // calculate the inverse // see http://www.netlib.org/lapack/double/dpotri.f dpotri('U', m, c, c.lda(), &info); if (info != 0) throw matrix_exception("Error computing inverse in inv_chol"); } template<int m, bool upper> inline void inv_tri(tri_dpmatrix<m, upper> &c) throw (...) { int info; // see http://www.netlib.org/lapack/double/dtrtri.f dtrtri(upper ? 'U' : 'L', 'N', m, c, c.lda(), &info); if (info != 0) throw matrix_exception("Error computing inverse in inv_tri"); } #endif
[ "anathan@5031bdca-8e6f-11dd-8a4e-8714b3728bc5" ]
[ [ [ 1, 383 ] ] ]
97197b301f3ad33c07252d53cd62c7a04765b32d
d94c6cce730a771c18a6d84c7991464129ed3556
/safeFatPrinter/trunk/src/SimpleItem.cpp
88021f8adc5d9c67d8db73c14cdf4fa30fadc109
[]
no_license
S1aNT/cupsfilter
09afbcedb4f011744e670fae74d71fce4cebdd25
26ecc1e76eefecde2b00173dff9f91ebd92fb349
refs/heads/master
2021-01-02T09:26:27.015991
2011-03-15T06:43:47
2011-03-15T06:43:47
32,496,994
0
0
null
null
null
null
UTF-8
C++
false
false
5,269
cpp
#include "simpleitem.h" SimpleItem::SimpleItem(QGraphicsItem * parent) :QGraphicsItem(parent) { currentFont = QFont("Times", 10, QFont::Bold); //textList << QObject::trUtf8(" old Шаблон ") << QObject::trUtf8(" Шаблон 2 "); printFrame=false; currentColor =Qt::blue; changeFontAction = new QAction(QObject::trUtf8("Изменить шрифт"),0); changeFontAction->setStatusTip(QObject::trUtf8("Выбор нового шрифта для элемента шаблона")); connect(changeFontAction, SIGNAL(triggered()), this, SLOT(changeFont())); changeColorAction = new QAction(QObject::trUtf8("Изменить цвет"),0); changeColorAction->setStatusTip(QObject::trUtf8("Выбор нового цвета для элемента шаблона")); connect(changeColorAction, SIGNAL(triggered()), this, SLOT(changeColor())); rotateRightAction = new QAction (QObject::trUtf8("Вращать по часовой стрелке"),0); connect(rotateRightAction,SIGNAL(triggered()),this,SLOT(rotateRight())); rotateLeftAction = new QAction (QObject::trUtf8("Вращать против часовой стрелки"),0); connect(rotateLeftAction,SIGNAL(triggered()),this,SLOT(rotateLeft())); } QRectF SimpleItem::boundingRect() const { //QPointF ptPosition(pos().x()-nPenWidth,pos().y()-nPenWidth); QPointF ptPosition(0-nPenWidth,0-nPenWidth); QSize size_pt(nPenWidth*2,nPenWidth*2); //qDebug() <<size_pt ; size_pt+=calcSize(); //qDebug() <<size_pt <<"\n"; return QRectF(ptPosition,QSizeF(size_pt)); } void SimpleItem::contextMenuEvent(QGraphicsSceneContextMenuEvent *event) { QMenu menu; menu.addAction(changeFontAction); menu.addAction(changeColorAction); menu.addSeparator(); menu.addAction(rotateRightAction); menu.addAction(rotateLeftAction); //menu.addSeparator(); //QAction *printNoFrameAction = menu.addAction("Не печатать рамку"); menu.exec(event->screenPos()); } void SimpleItem::paint (QPainter *ppainter, const QStyleOptionGraphicsItem *, QWidget *) { ppainter->save(); ppainter->setPen(QPen(Qt::black,nPenWidth,Qt::DotLine)); //QPoint pt =pos().toPoint(); QSize size_pt=calcSize(); //qDebug() << Q_FUNC_INFO <<pt << size_pt <<"\n"; ppainter->drawRect(0,0,size_pt.width(),size_pt.height()); QFontMetrics fm(currentFont); int pixelsHigh=fm.height(); ppainter->setPen(QPen(currentColor,0)); ppainter->setFont(currentFont); for (int i = 0; i < textList.size(); ++i){ ppainter->drawText(0,0+((i+1)*pixelsHigh),textList.at(i).toLocal8Bit().constData()); } ppainter->restore(); } void SimpleItem::mousePressEvent(QGraphicsSceneMouseEvent *pe) { QApplication::setOverrideCursor(Qt::PointingHandCursor); QGraphicsItem::mousePressEvent(pe); } void SimpleItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *pe) { QApplication::restoreOverrideCursor(); QGraphicsItem::mouseReleaseEvent(pe); } void SimpleItem::setText(QStringList &pList) { textList.clear(); textList.append(pList); update(); } void SimpleItem::changeFont() { bool ok; QFont font = QFontDialog::getFont( &ok, QFont("Times", 10,QFont::Bold),0,QObject::trUtf8("Выберите шрифт для элемента ")); if (ok) {// пользователь нажимает OK, и шрифт устанавливается в выбранный currentFont =font; update(); } } void SimpleItem::changeColor() { QColor col = QColorDialog::getColor ( Qt::white,0,QObject::trUtf8("Выберите цвет текущего элемента ") ) ; if (col.isValid()) {// пользователь нажимает OK, и шрифт устанавливается в выбранный currentColor =col; update(); } } void SimpleItem::setPrintFrame(bool frm) { printFrame =frm; } void SimpleItem::rotateRight() { this->rotate(89.9); } void SimpleItem::rotateLeft() { this->rotate(-89.9); } QSize SimpleItem::calcSize() const { QFontMetrics fm(currentFont); int pHigh=0; int maxPixelsWide=0; // Максимальная ширина строки //qDebug() << Q_FUNC_INFO << fm.height() <<"\n"; for (int i = 0; i < textList.size(); ++i){ int pixelsWide = fm.width(textList.at(i).toLocal8Bit().constData()); if (pixelsWide >maxPixelsWide){ maxPixelsWide=pixelsWide; //qDebug() << Q_FUNC_INFO <<textList.at(i).toLocal8Bit().constData() << maxPixelsWide <<"\n"; } pHigh += fm.height(); } pHigh+= (fm.height()/2); //qDebug() << Q_FUNC_INFO <<QSize(maxPixelsWide+nPenWidth*2,pHigh+nPenWidth*2); //return QSize(maxPixelsWide+5+nPenWidth*2,pHigh+nPenWidth*2); return QSize(maxPixelsWide,pHigh); } QStringList SimpleItem::getText() { qDebug() << Q_FUNC_INFO << textList; return textList; } QFont SimpleItem::getFont() { qDebug() << Q_FUNC_INFO <<currentFont; return currentFont; } QColor SimpleItem::getColor() { qDebug() << Q_FUNC_INFO <<currentColor; return currentColor; }
[ [ [ 1, 163 ] ] ]
9c65ad1008e35e841516c566e7d1579a4629c074
f8b364974573f652d7916c3a830e1d8773751277
/emulator/allegrex/instructions/VF2IU.h
6ed21a7f5159a297573c5afb0336bbd53430376f
[]
no_license
lemmore22/pspe4all
7a234aece25340c99f49eac280780e08e4f8ef49
77ad0acf0fcb7eda137fdfcb1e93a36428badfd0
refs/heads/master
2021-01-10T08:39:45.222505
2009-08-02T11:58:07
2009-08-02T11:58:07
55,047,469
0
0
null
null
null
null
UTF-8
C++
false
false
1,042
h
template< > struct AllegrexInstructionTemplate< 0xd2400000, 0xffe00000 > : AllegrexInstructionUnknown { static AllegrexInstructionTemplate &self() { static AllegrexInstructionTemplate insn; return insn; } static AllegrexInstruction *get_instance() { return &AllegrexInstructionTemplate::self(); } virtual AllegrexInstruction *instruction(u32 opcode) { return this; } virtual char const *opcode_name() { return "VF2IU"; } virtual void interpret(Processor &processor, u32 opcode); virtual void disassemble(u32 address, u32 opcode, char *opcode_name, char *operands, char *comment); protected: AllegrexInstructionTemplate() {} }; typedef AllegrexInstructionTemplate< 0xd2400000, 0xffe00000 > AllegrexInstruction_VF2IU; namespace Allegrex { extern AllegrexInstruction_VF2IU &VF2IU; } #ifdef IMPLEMENT_INSTRUCTION AllegrexInstruction_VF2IU &Allegrex::VF2IU = AllegrexInstruction_VF2IU::self(); #endif
[ [ [ 1, 41 ] ] ]
5a442b1f5048a778714ae9c8716e3fccc97b43e9
3532ae25961855b20635decd1481ed7def20c728
/app/CamDriver/points.cpp
609052d4bffe2ee1e64ee8f5cb1d7d53a7b0a21f
[]
no_license
mcharmas/Bazinga
121645a0c7bc8bd6a91322c2a7ecc56a5d3f71b7
1d35317422c913f28710b3182ee0e03822284ba3
refs/heads/master
2020-05-18T05:48:32.213937
2010-03-22T17:13:09
2010-03-22T17:13:09
577,323
1
0
null
null
null
null
UTF-8
C++
false
false
3,874
cpp
#include "points.h" Points2::Points2(VideoInput *input) : FrameRetreiver(input), count(0), max_count(50), quality(0.01), min_distance(10), active(false) { currBuffsSize.width = 0; currBuffsSize.height = 0; // pt.x = 120; // // pt.y = 160; // add_remove_pt = 1; points[0] = (CvPoint2D32f*)cvAlloc(max_count*sizeof(points[0][0])); points[1] = (CvPoint2D32f*)cvAlloc(max_count*sizeof(points[0][0])); status = (char*)cvAlloc(max_count); } Points2::~Points2() { if( !currBuffsSize.width == 0 ) { cvReleaseImage(&tempImage); cvReleaseImage(&currGreyImage); cvReleaseImage(&prevGreyImage); cvReleaseImage(&currPyramid); cvReleaseImage(&prevPyramid); } } void Points2::addPoint( int x, int y ){ pt.x = x; pt.y = y; add_remove_pt = 1; } CvPoint Points2::pt = cvPoint(0,0); //Points2::pt.w = 0; //= cvSize(0,0); int Points2::add_remove_pt = 0; void Points2::checkSize(CvSize frameSize) { if(frameSize.width != currBuffsSize.width || frameSize.height != currBuffsSize.height) { if( !currBuffsSize.width == 0 ) { cvReleaseImage(&tempImage); cvReleaseImage(&currGreyImage); cvReleaseImage(&prevGreyImage); cvReleaseImage(&currPyramid); cvReleaseImage(&prevPyramid); } tempImage = cvCreateImage(frameSize, IPL_DEPTH_8U, 3); currGreyImage = cvCreateImage(frameSize, IPL_DEPTH_8U, 1); prevGreyImage = cvCreateImage(frameSize, IPL_DEPTH_8U, 1); currPyramid = cvCreateImage(frameSize, IPL_DEPTH_8U, 1); prevPyramid = cvCreateImage(frameSize, IPL_DEPTH_8U, 1); currBuffsSize = frameSize; flags = 0; } } void Points2::retreiveFrame(cv::Mat & frame) { bobs.clear(); double horizProp = (double) 640 / frame.cols; double vertProp = (double) 480 / frame.rows; CvSize frameSize; frameSize.width = frame.size().width; frameSize.height = frame.size().height; checkSize(frameSize); IplImage *dupa = new IplImage(frame); cvCopy(dupa,tempImage,0); cvCvtColor(tempImage, currGreyImage, CV_BGR2GRAY); int i, k; if( count > 0 ) { cvCalcOpticalFlowPyrLK( prevGreyImage, currGreyImage, prevPyramid, currPyramid, points[0], points[1], count, cvSize(20,20), 3, status, 0, cvTermCriteria(CV_TERMCRIT_ITER|CV_TERMCRIT_EPS,20,0.03), flags ); flags |= CV_LKFLOW_PYR_A_READY; for( i = k = 0; i < count; i++ ) { if( add_remove_pt ) { double dx = pt.x - points[1][i].x; double dy = pt.y - points[1][i].y; if( dx*dx + dy*dy <= 25 ) { add_remove_pt = 0; continue; } } if( !status[i] ) continue; points[1][k++] = points[1][i]; cv::circle( frame, cvPointFrom32f(points[1][i]), 3, CV_RGB(0,255,0), -1, 8,0); bobs.append(BOb((quint16) (horizProp * points[1][i].x), (quint16) (vertProp * points[1][i].y), 1,1)); } count = k; } if( add_remove_pt && count < max_count ) { points[1][count++] = cvPointTo32f(pt); cvFindCornerSubPix( currGreyImage, points[1] + count - 1, 1, cvSize(10,10), cvSize(-1,-1), cvTermCriteria(CV_TERMCRIT_ITER|CV_TERMCRIT_EPS,20,0.03)); add_remove_pt = 0; } CV_SWAP( prevGreyImage, currGreyImage, swapImage ); CV_SWAP( prevPyramid, currPyramid, swapImage ); CV_SWAP( points[0], points[1], swap_points ); delete dupa; if(!bobs.empty()) emit bobjects(&bobs); }
[ "rpycka@ffdda973-792b-4bce-9e62-2343ac01ffa1", "santamon@ffdda973-792b-4bce-9e62-2343ac01ffa1" ]
[ [ [ 1, 61 ], [ 66, 105 ], [ 109, 128 ], [ 132, 132 ] ], [ [ 62, 65 ], [ 106, 108 ], [ 129, 131 ] ] ]
dd1e3d8effaee6d62b9d7e0cb3548ba82b0f18ce
5ed707de9f3de6044543886ea91bde39879bfae6
/ASMember/ASManager/ASManager.cpp
573321072d34ed84601cd0f00dbb451a459408c7
[]
no_license
grtvd/asifantasysports
9e472632bedeec0f2d734aa798b7ff00148e7f19
76df32c77c76a76078152c77e582faa097f127a8
refs/heads/master
2020-03-19T02:25:23.901618
1999-12-31T16:00:00
2018-05-31T19:48:19
135,627,290
0
0
null
null
null
null
UTF-8
C++
false
false
2,270
cpp
/* ASManager.cpp */ /******************************************************************************/ /******************************************************************************/ #include "CBldVCL.h" #pragma hdrstop #include "NTService.h" #include "ASMemberAppOptions.h" using namespace asmember; /******************************************************************************/ USEUNIT("..\..\..\CBldComm\Source\CommType.cpp"); USEUNIT("..\..\..\CBldComm\Source\CommMisc.cpp"); USEUNIT("..\..\..\CBldComm\Source\CommErr.cpp"); USEUNIT("..\..\..\CBldComm\Source\CommStr.cpp"); USEUNIT("..\..\..\CBldComm\Source\CommFormat.cpp"); USEUNIT("..\..\..\CBldComm\Source\CommDB.cpp"); USEUNIT("..\..\..\CBldComm\Source\CommDir.cpp"); USEUNIT("..\..\..\CBldComm\Source\CommTick.cpp"); USEUNIT("..\..\..\CBldComm\Source\Streamable.cpp"); USEUNIT("..\..\..\CBldComm\Source\ObjectBuilder.cpp"); USEUNIT("..\..\..\CBldComm\Source\DataFiler.cpp"); USEUNIT("..\..\..\CBldComm\Source\TextFiler.cpp"); USEUNIT("..\..\..\CBldComm\Source\PipeTextFiler.cpp"); USEUNIT("..\..\..\CBldComm\Source\DataSetRecord.cpp"); USEUNIT("..\..\..\CBldComm\Source\PasswordEncode.cpp"); USEUNIT("..\..\..\CBldComm\Source\RegistryExt.cpp"); USEUNIT("..\..\..\CBldComm\Source\ErrorLog.cpp"); USEUNIT("..\..\..\CBldComm\Source\Mailer.cpp"); USEUNIT("..\..\..\CBldComm\Source\SMTPMailer.cpp"); USEUNIT("..\..\..\CBldComm\Source\SendMail.cpp"); USEUNIT("..\..\..\CBldComm\Source\CommCon.cpp"); USEUNIT("..\..\..\CBldComm\Source\NTService.cpp"); USEUNIT("..\Shared\Source\ASMemberAppOptions.cpp"); USEUNIT("..\Shared\Source\ASMemberType.cpp"); USEUNIT("..\Shared\Source\ASMemberObjectBuilder.cpp"); USEUNIT("Source\ASMemberManager.cpp"); //--------------------------------------------------------------------------- const char* tag::GetExeDllName() { return("ASManager.exe"); } /******************************************************************************/ #pragma argsused int main(int argc, char* argv[]) { return(TNTService::main(ASMemberHomeDir(),"ASManager",argc,argv)); } /******************************************************************************/ /******************************************************************************/
[ [ [ 1, 57 ] ] ]
ad356bb150b480fd71bf0f03235d39c64157aa6f
6c8c4728e608a4badd88de181910a294be56953a
/InWorldChatModule/InWorldChatModule.h
8b6ddbf1601719bc9a913b2d1da8c3bb89761486
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
caocao/naali
29c544e121703221fe9c90b5c20b3480442875ef
67c5aa85fa357f7aae9869215f840af4b0e58897
refs/heads/master
2021-01-21T00:25:27.447991
2010-03-22T15:04:19
2010-03-22T15:04:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,279
h
/** * For conditions of distribution and use, see copyright notice in license.txt * * @file InWorldChatModule.h * @brief Simple OpenSim world chat module. Listens for ChatFromSimulator packets and shows the chat on the UI. * Outgoing chat sent using ChatFromViewer packets. Manages EC_ChatBubbles * @note Depends on RexLogicModule so don't create dependency to this module. */ #ifndef incl_InWorldChatModule_InWorldChatModule_h #define incl_InWorldChatModule_InWorldChatModule_h #include "ModuleInterface.h" #include "ModuleLoggingFunctions.h" #include "ConsoleCommandServiceInterface.h" #include <QObject> class RexUUID; namespace ProtocolUtilities { class NetInMessage; } namespace Foundation { class EventDataInterface; } namespace ProtocolUtilities { class ProtocolModuleInterface; class WorldStream; typedef boost::weak_ptr<ProtocolModuleInterface> ProtocolWeakPtr; typedef boost::shared_ptr<WorldStream> WorldStreamPtr; } namespace UiServices { class UiModule; } QT_BEGIN_NAMESPACE class QColor; QT_END_NAMESPACE namespace Naali { class InWorldChatModule : public QObject, public Foundation::ModuleInterfaceImpl { Q_OBJECT public: /// Default constructor. InWorldChatModule(); /// Destructor ~InWorldChatModule(); /// ModuleInterfaceImpl overrides. void Load(); void PostInitialize(); void Update(f64 frametime); bool HandleEvent( event_category_id_t category_id, event_id_t event_id, Foundation::EventDataInterface* data); void SubscribeToNetworkEvents(ProtocolUtilities::ProtocolWeakPtr currentProtocolModule); MODULE_LOGGING_FUNCTIONS /// Returns name of this module. Needed for logging. static const std::string &NameStatic(); /// Name of this module. static const std::string moduleName; public slots: /// Sends chat message to server. /// @param msg Chat message to be sent. void SendChatFromViewer(const QString &msg); private: Q_DISABLE_COPY(InWorldChatModule); /// Console command for testing billboards. /// @param params Parameters. Console::CommandResult TestAddBillboard(const StringVector &params); /// Console command for sending chat message to server. /// @param params Parameters. Console::CommandResult ConsoleChat(const StringVector &params); /// Applies EC_ChatBubble to a scene entity with default parameters. /// @param entity Entity. /// @message Message to be shown at the chat bubble. void ApplyDefaultChatBubble(Scene::Entity &entity, const QString &message); /// Applies EC_ChatBubble to a scene entity. /// @param entity Entity. /// @param texture /// @param timeToShow void ApplyBillboard(Scene::Entity &entity, const std::string &texture, float timeToShow); /// Returns scene entity pointer with the wanter ID: /// @param id ID of the entity. /// @return Entity pointer matching the id or 0 if not found. Scene::Entity *GetEntityWithId(const RexUUID &id); /// Handles RexEmotionIcon generic message. /// @param params Parameters. void HandleRexEmotionIconMessage(StringVector &params); /// Handles ChatFromSimulator message. /// @param msg Network message. void HandleChatFromSimulatorMessage(ProtocolUtilities::NetInMessage &msg); /// NetworkState event category. event_category_id_t networkStateEventCategory_; /// NetworkIn event category. event_category_id_t networkInEventCategory_; /// Framework event category event_category_id_t frameworkEventCategory_; /// WorldStream pointer ProtocolUtilities::WorldStreamPtr currentWorldStream_ ; /// UiModule pointer. boost::weak_ptr<UiServices::UiModule> uiModule_; /// Do we want to show the in-world chat bubbles bool showChatBubbles_; }; } #endif
[ "Stinkfist0@5b2332b8-efa3-11de-8684-7d64432d61a3", "jujjyl@5b2332b8-efa3-11de-8684-7d64432d61a3" ]
[ [ [ 1, 14 ], [ 16, 89 ], [ 92, 105 ], [ 107, 110 ], [ 112, 140 ] ], [ [ 15, 15 ], [ 90, 91 ], [ 106, 106 ], [ 111, 111 ] ] ]
ca1b5d566a4cb05973d68c24efcb14d1ffe6fd1c
3dc524d7d842eb91d2c5c93e87688e473697197a
/Source/main.cpp
a40958da60acf6f8e92a5f4718562f9bc213c7fb
[]
no_license
SamOatesUniversity/Year-2---Animation-Simulation---PigCam
8aae5ddf90289f92275349ccafe096b07447c8c2
aa33e4dea6bd42cb2d1cf4159d8b2c4e67e63cae
refs/heads/master
2020-06-03T13:59:52.260548
2011-02-15T17:53:26
2011-02-15T17:53:26
41,170,127
0
0
null
null
null
null
UTF-8
C++
false
false
2,905
cpp
/** * Original Author: Tyrone Davison, Teesside University * Filename: main.cpp * Date: January 2011 * Description: application main for assignment task 2 * Notes: you shouldn't need to modify this file */ #include "twm/core/world.hpp" #include "twm/core/service.hpp" #include "twm/windows/window.hpp" #include "twm/graphics/components.hpp" #include "twm/graphics/basic_renderer.hpp" #include "prototype.hpp" #include "pigcam.hpp" #include <iostream> #include <crtdbg.h> //** you should not need to modify main for the assignment int main( int argc, char* argv[] ) { // debug check for memory leaks on exit _CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF ); std::cout << "Animation and Simulation Programming: ICA Task 2" << std::endl; std::cout << "Usage instructions:" << std::endl; std::cout << " '1' - Camera mode \"front\"" << std::endl; std::cout << " '2' - Camera mode \"rear\"" << std::endl; std::cout << " '3' - Camera mode \"driver\"" << std::endl; std::cout << " '4' - Toggle active WartPig" << std::endl; // create an instance of a virtual world twm::World* world = new twm::World(); // create a window and attach it to the world twm::Window* window = new twm::Window( "win1" ); world->AttachService( window ); // create and assign a renderer for the window twm::BasicRenderer* renderer = new twm::BasicRenderer(); window->SetRenderer( renderer ); // register component types for the renderer twm::RegisterGraphicsComponentTypes( world ); // create the testing service and attach it to the world PrototypeService* prototype = new PrototypeService(); world->AttachService( prototype ); // register component types for the testing service RegisterPrototypeComponentTypes( world ); // create our service to host the assignment code and attach it to the world PigCamService* pigcam = new PigCamService(); world->AttachService( pigcam ); // signal services to start world->Start(); // advance to the next frame at approximately 60fps const unsigned int ideal_frame_duration = 17; twm::Timer timer; unsigned int frame_time = timer.GetTime() + ideal_frame_duration; while ( window->IsOpen() ) { world->AdvanceFrame(); unsigned int current_time = timer.GetTime(); int delta_time = frame_time - current_time; if ( delta_time > 0 ) { timer.Sleep( delta_time ); frame_time += ideal_frame_duration; } else { // dropped time frame_time = current_time + ideal_frame_duration; } } // signal services to stop world->Stop(); // cleanup delete pigcam; delete prototype; delete window; delete renderer; delete world; // wait for a key press before exit (so you can see console output) system( "PAUSE" ); return 0; }
[ [ [ 1, 98 ] ] ]
cf51671cd6196c4723edb8f9bc4a08f066054436
cd0987589d3815de1dea8529a7705caac479e7e9
/webkit/WebKitTools/DumpRenderTree/TestNetscapePlugIn/PluginTest.h
0207628b99393644a380a3da0b56dc381d61bdee
[]
no_license
azrul2202/WebKit-Smartphone
0aab1ff641d74f15c0623f00c56806dbc9b59fc1
023d6fe819445369134dee793b69de36748e71d7
refs/heads/master
2021-01-15T09:24:31.288774
2011-07-11T11:12:44
2011-07-11T11:12:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,640
h
/* * Copyright (C) 2010 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef PluginTest_h #define PluginTest_h #include <WebKit/npfunctions.h> #include <assert.h> #include <map> #include <string> // Helper classes for implementing has_member typedef char (&no_tag)[1]; typedef char (&yes_tag)[2]; #define DEFINE_HAS_MEMBER_CHECK(member, returnType, argumentTypes) \ template<typename T, returnType (T::*member) argumentTypes> struct pmf_##member##_helper {}; \ template<typename T> no_tag has_member_##member##_helper(...); \ template<typename T> yes_tag has_member_##member##_helper(pmf_##member##_helper<T, &T::member >*); \ template<typename T> struct has_member_##member { \ static const bool value = sizeof(has_member_##member##_helper<T>(0)) == sizeof(yes_tag); \ }; DEFINE_HAS_MEMBER_CHECK(hasMethod, bool, (NPIdentifier methodName)); DEFINE_HAS_MEMBER_CHECK(invoke, bool, (NPIdentifier methodName, const NPVariant*, uint32_t, NPVariant* result)); DEFINE_HAS_MEMBER_CHECK(invokeDefault, bool, (const NPVariant*, uint32_t, NPVariant* result)); DEFINE_HAS_MEMBER_CHECK(hasProperty, bool, (NPIdentifier propertyName)); DEFINE_HAS_MEMBER_CHECK(getProperty, bool, (NPIdentifier propertyName, NPVariant* result)); class PluginTest { public: static PluginTest* create(NPP, const std::string& identifier); virtual ~PluginTest(); // NPP functions. virtual NPError NPP_DestroyStream(NPStream* stream, NPReason reason); virtual NPError NPP_GetValue(NPPVariable, void* value); // NPN functions. NPIdentifier NPN_GetStringIdentifier(const NPUTF8* name); NPIdentifier NPN_GetIntIdentifier(int32_t intid); NPObject* NPN_CreateObject(NPClass*); bool NPN_RemoveProperty(NPObject*, NPIdentifier propertyName); template<typename TestClassTy> class Register { public: Register(const std::string& identifier) { registerCreateTestFunction(identifier, Register::create); } private: static PluginTest* create(NPP npp, const std::string& identifier) { return new TestClassTy(npp, identifier); } }; protected: PluginTest(NPP npp, const std::string& identifier); // FIXME: A plug-in test shouldn't need to know about it's NPP. Make this private. NPP m_npp; const std::string& identifier() const { return m_identifier; } // NPObject helper template. template<typename T> struct Object : NPObject { public: static NPObject* create(PluginTest* pluginTest) { Object* object = static_cast<Object*>(pluginTest->NPN_CreateObject(npClass())); object->m_pluginTest = pluginTest; return object; } // These should never be called. bool hasMethod(NPIdentifier methodName) { assert(false); return false; } bool invoke(NPIdentifier methodName, const NPVariant*, uint32_t, NPVariant* result) { assert(false); return false; } bool invokeDefault(const NPVariant*, uint32_t, NPVariant* result) { assert(false); return false; } bool hasProperty(NPIdentifier propertyName) { assert(false); return false; } bool getProperty(NPIdentifier propertyName, NPVariant* result) { assert(false); return false; } protected: Object() : m_pluginTest(0) { } virtual ~Object() { } PluginTest* pluginTest() const { return m_pluginTest; } private: static NPObject* NP_Allocate(NPP npp, NPClass* aClass) { return new T; } static void NP_Deallocate(NPObject* npObject) { delete static_cast<T*>(npObject); } static bool NP_HasMethod(NPObject* npObject, NPIdentifier methodName) { return static_cast<T*>(npObject)->hasMethod(methodName); } static bool NP_Invoke(NPObject* npObject, NPIdentifier methodName, const NPVariant* arguments, uint32_t argumentCount, NPVariant* result) { return static_cast<T*>(npObject)->invoke(methodName, arguments, argumentCount, result); } static bool NP_InvokeDefault(NPObject* npObject, const NPVariant* arguments, uint32_t argumentCount, NPVariant* result) { return static_cast<T*>(npObject)->invokeDefault(arguments, argumentCount, result); } static bool NP_HasProperty(NPObject* npObject, NPIdentifier propertyName) { return static_cast<T*>(npObject)->hasProperty(propertyName); } static bool NP_GetProperty(NPObject* npObject, NPIdentifier propertyName, NPVariant* result) { return static_cast<T*>(npObject)->getProperty(propertyName, result); } static NPClass* npClass() { static NPClass npClass = { NP_CLASS_STRUCT_VERSION, NP_Allocate, NP_Deallocate, 0, // NPClass::invalidate has_member_hasMethod<T>::value ? NP_HasMethod : 0, has_member_invoke<T>::value ? NP_Invoke : 0, has_member_invokeDefault<T>::value ? NP_InvokeDefault : 0, has_member_hasProperty<T>::value ? NP_HasProperty : 0, has_member_getProperty<T>::value ? NP_GetProperty : 0, 0, // NPClass::setProperty 0, // NPClass::removeProperty 0, // NPClass::enumerate 0 // NPClass::construct }; return &npClass; }; PluginTest* m_pluginTest; }; private: typedef PluginTest* (*CreateTestFunction)(NPP, const std::string&); static void registerCreateTestFunction(const std::string&, CreateTestFunction); static std::map<std::string, CreateTestFunction>& createTestFunctions(); std::string m_identifier; }; #endif // PluginTest_h
[ [ [ 1, 212 ] ] ]
6f4e72bfe3645b2f61bcce2729204d1ad0ded6e9
037faae47a5b22d3e283555e6b5ac2a0197faf18
/pcsx2v2/x86/ix86-32/iR5900Jump.cpp
294790796c7f9bee8f787f8b013983b2ca939d09
[]
no_license
isabella232/pcsx2-sourceforge
6e5aac8d0b476601bfc8fa83ded66c1564b8c588
dbb2c3a010081b105a8cba0c588f1e8f4e4505c6
refs/heads/master
2023-03-18T22:23:15.102593
2008-11-17T20:10:17
2008-11-17T20:10:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,533
cpp
/* Pcsx2 - Pc Ps2 Emulator * Copyright (C) 2002-2008 Pcsx2 Team * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA */ // recompiler reworked to add dynamic linking zerofrog(@gmail.com) Jan06 #include <stdlib.h> #include <string.h> #include <assert.h> #include "Common.h" #include "InterTables.h" #include "ix86/ix86.h" #include "iR5900.h" #ifdef _WIN32 #pragma warning(disable:4244) #pragma warning(disable:4761) #endif /********************************************************* * Jump to target * * Format: OP target * *********************************************************/ #ifndef JUMP_RECOMPILE REC_SYS(J); REC_SYS(JAL); REC_SYS(JR); REC_SYS(JALR); #else //////////////////////////////////////////////////// void recJ( void ) { // SET_FPUSTATE; u32 newpc = (_Target_ << 2) + ( pc & 0xf0000000 ); recompileNextInstruction(1); SetBranchImm(newpc); } //////////////////////////////////////////////////// void recJAL( void ) { u32 newpc = (_Target_ << 2) + ( pc & 0xf0000000 ); _deleteEEreg(31, 0); GPR_SET_CONST(31); g_cpuConstRegs[31].UL[0] = pc + 4; g_cpuConstRegs[31].UL[1] = 0; recompileNextInstruction(1); SetBranchImm(newpc); } /********************************************************* * Register jump * * Format: OP rs, rd * *********************************************************/ //////////////////////////////////////////////////// void recJR( void ) { SetBranchReg( _Rs_); } //////////////////////////////////////////////////// void recJALR( void ) { _allocX86reg(ESI, X86TYPE_PCWRITEBACK, 0, MODE_WRITE); _eeMoveGPRtoR(ESI, _Rs_); // uncomment when there are NO instructions that need to call interpreter // int mmreg; // if( GPR_IS_CONST1(_Rs_) ) // MOV32ItoM( (u32)&cpuRegs.pc, g_cpuConstRegs[_Rs_].UL[0] ); // else { // int mmreg; // // if( (mmreg = _checkXMMreg(XMMTYPE_GPRREG, _Rs_, MODE_READ)) >= 0 ) { // SSE_MOVSS_XMM_to_M32((u32)&cpuRegs.pc, mmreg); // } // else if( (mmreg = _checkMMXreg(MMX_GPR+_Rs_, MODE_READ)) >= 0 ) { // MOVDMMXtoM((u32)&cpuRegs.pc, mmreg); // SetMMXstate(); // } // else { // MOV32MtoR(EAX, (int)&cpuRegs.GPR.r[ _Rs_ ].UL[ 0 ] ); // MOV32RtoM((u32)&cpuRegs.pc, EAX); // } // } if ( _Rd_ ) { _deleteEEreg(_Rd_, 0); GPR_SET_CONST(_Rd_); g_cpuConstRegs[_Rd_].UL[0] = pc + 4; g_cpuConstRegs[_Rd_].UL[1] = 0; } _clearNeededMMXregs(); _clearNeededXMMregs(); recompileNextInstruction(1); if( x86regs[ESI].inuse ) { assert( x86regs[ESI].type == X86TYPE_PCWRITEBACK ); MOV32RtoM((int)&cpuRegs.pc, ESI); x86regs[ESI].inuse = 0; } else { MOV32MtoR(EAX, (u32)&g_recWriteback); MOV32RtoM((int)&cpuRegs.pc, EAX); } SetBranchReg(0xffffffff); } #endif
[ "saqibakhtar@23c756db-88ba-2448-99d7-e6e4c676ec84" ]
[ [ [ 1, 130 ] ] ]
19d3b36d958a8972d49a42af329eea4e08e4b1af
4df96df7014bf0ffd912ab69142bd3ab8d897a1b
/dev/tests/cpp_interface/include/test_base.h
9f7a2929e8e5696ac811b4e080088b6892eb8317
[]
no_license
al-sabr/caspin
25e66369de26e9ac2467109ef20a692e0f508dc7
fd901f1dbec708864ab12e8ce5ed153e33b6e93f
refs/heads/master
2021-12-12T04:55:15.474635
2011-10-10T18:01:37
2011-10-10T18:01:37
null
0
0
null
null
null
null
UTF-8
C++
false
false
433
h
#ifndef __test_base_H__ #define __test_base_H__ class test_base { public: virtual const char* name() = 0; virtual void test_global_functions(csp::VmCore* core) = 0; virtual void test_static_class_functions(csp::VmCore* core) = 0; virtual avmplus::ScriptObject* test_class_construction(csp::VmCore* core) = 0; virtual void test_class_member_functions(csp::VmCore* core, avmplus::ScriptObject* obj) = 0; }; #endif
[ [ [ 1, 14 ] ] ]
063b8c76b5cabba0777365e0a575283339ccc2a4
f2385a5a332401269b27f91a9d259c2395c3016c
/glut0/main.cpp
b36c44994cff610613cd7ca753b9a2aac2c9da7f
[]
no_license
mohamedAAhassan/airhockey
33fe436131f6f693425ba3e83da2f53605388aac
35ce7c457f5c3ab2a2620deb5b8b844eca235071
refs/heads/master
2021-01-01T05:45:20.237879
2009-10-15T11:33:11
2009-10-15T11:33:11
56,930,383
0
0
null
null
null
null
WINDOWS-1250
C++
false
false
14,409
cpp
#include <GL/glut.h> #include <cmath> #include <iostream> #include "Point2.h" #include "Pak.h" #include "NeuralNetwork.h" #define SIRINA 1.2 #define DOLZINA 3 #define VISINA 0.1 NeuralNetwork* network=new NeuralNetwork(); vector<double> input; vector<double> output; Pak pakec=Pak(Point2(0.40,-2.1),Point2(0.01, -0.03), 0.1,0.999,true,""); Pak pakec2=Pak(Point2(0,-1),Point2(0, 0), 0.1,1, false,"Player 1"); Pak pakec3=Pak(Point2(0,1),Point2(0, 0), 0.1,1, false,"Player 2"); //Kij pakec2=Kij(Point2(0,-1),Point2(0, 0), 0.12,1, SIRINA, DOLZINA); GLfloat angle = 0.0; double gol=0.25; double not=pakec.getRad()*2; int resultpl1=0,resultpl2=0; char* statustxt=""; GLfloat WIN_X = 0; GLfloat WIN_Y = 0; GLfloat WIN_Z = 0; struct table_s { GLfloat width; GLfloat height; GLfloat depth; GLfloat goal; GLfloat border; }; void preveriTrk(Pak &prvi, Pak &drugi) { double x21,y21,vx21,vy21; x21 = prvi.getPos().getX() - drugi.getPos().getX(); y21 = prvi.getPos().getY()- drugi.getPos().getY(); vx21 = prvi.getDir().getX() - drugi.getDir().getX(); vy21 = prvi.getDir().getY() - drugi.getDir().getY(); if ((vx21 * x21 + vy21 * y21) >= 0) { return; } Point2 razdalja=prvi.getPos()-drugi.getPos(); if (razdalja.Lenght()<=(prvi.getRad()+drugi.getRad())) { if (prvi.getLastTrk()>10) { prvi.setLastTrk(); double deltaY = (prvi.getPos().getY() - drugi.getPos().getY()); double deltaX = (prvi.getPos().getX() - drugi.getPos().getX()); double Distance = deltaX * deltaX + deltaY * deltaY; double k1= (deltaX * prvi.getDir().getX() + deltaY * prvi.getDir().getY()) / Distance; double k2 = (deltaX * prvi.getDir().getY() - deltaY * prvi.getDir().getX()) / Distance; double k3 = (deltaX * drugi.getDir().getX() + deltaY * drugi.getDir().getY()) / Distance; double k4 = (deltaX * drugi.getDir().getY() - deltaY * drugi.getDir().getX()) / Distance; prvi.setDir(k3 * deltaX - k2 * deltaY,k3 * deltaY + k2 * deltaX); prvi.UpdatePos(); prvi.setPos(prvi.getPos().getX()+prvi.getRad()*prvi.getDir().getX(),prvi.getPos().getY()+prvi.getRad()*prvi.getDir().getY()); Point2 razdalja=prvi.getPos()-drugi.getPos(); if (razdalja.Lenght()<=(prvi.getRad()+drugi.getRad())) { //prvi.setPos(prvi.getPos().getX()+razdalja.Lenght()*prvi.getDir().getX()*10,prvi.getPos().getY()+razdalja.Lenght()*prvi.getDir().getY()*10); prvi.setPos(prvi.getPos().getX()+prvi.getRad()*prvi.getDir().getX(),prvi.getPos().getY()+prvi.getRad()*prvi.getDir().getY()); } } } } const float DEG2RAD = 3.14159/180; void drawCircle(float radius) { glBegin(GL_LINE_LOOP); for (int i=0; i < 360; i++) { float degInRad = i*DEG2RAD; glVertex2f(cos(degInRad)*radius,sin(degInRad)*radius); } glEnd(); } void fillCircle(float radius) { glBegin(GL_TRIANGLE_FAN); glVertex2f(0, 0); for (int i=0; i <= 360; i++) { float degInRad = i*DEG2RAD; glVertex2f(cos(degInRad)*radius,sin(degInRad)*radius); } glEnd(); } void napisi(double x, double y, double z, char *string) { int len, i; glRasterPos3f(x, y, z); len = (int) strlen(string); for (i = 0; i < len; i++) { glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18, string[i]); } } void izrisi(Pak prvi) { glPushMatrix(); glTranslatef(prvi.getPos().getX() ,prvi.getPos().getY(), 0.0); GLUquadricObj* cyl; cyl = gluNewQuadric(); gluQuadricDrawStyle(cyl, GLU_SMOOTH); gluCylinder(cyl, prvi.getRad(), prvi.getRad(), 0.05, 16, 2); glTranslatef(0,0,0.05); fillCircle(prvi.getRad()); glPopMatrix(); } void preveriTrkeInGol(Pak &prvi) { if (abs((prvi.getPos()+prvi.getDir()).getX())>=SIRINA-prvi.getRad()) { prvi.setDir(prvi.getDir().getX()*-1, prvi.getDir().getY()); } if (abs((prvi.getPos()+prvi.getDir()).getY())>=DOLZINA-prvi.getRad()) { if (abs(prvi.getPos().getX())<gol) { prvi.setDir(0,0); if (prvi.getPos().getY()<0) { resultpl2++; prvi.setPos(0,-1); } else { resultpl1++; prvi.setPos(0,1); } if ((resultpl1>6||resultpl2>6)) { statustxt="Konec igre!"; prvi.setPos(-10000,-10000); } } else { prvi.setDir(prvi.getDir().getX(), prvi.getDir().getY()*-1); } } } void Risi (void) { glRotatef(-100,1,0,0); glRotatef(sin(angle/100)*5,0,0,1); //glRotatef(sin(angle/100)*15,0,1,0); //glRotatef(sin(angle/10)*15,0,0,1); //glRotatef(angle/5,0,1,0); //glRotatef(angle/5,0,1,0); //glRotatef(-pakec.getPos().getX()*3,0,0,1); glBegin(GL_QUADS); //rezultat glColor3f(1, 1, 1); glVertex3f(-SIRINA,DOLZINA,0); glVertex3f(SIRINA,DOLZINA,0); glVertex3f(SIRINA,-DOLZINA,0); glVertex3f(-SIRINA,-DOLZINA,0); // Zagolje :D glVertex3f(-gol,-DOLZINA,0); glVertex3f(gol,-DOLZINA,0); glVertex3f(gol,-DOLZINA-not,0); glVertex3f(-gol,-DOLZINA-not,0); glVertex3f(-gol,DOLZINA,0); glVertex3f(gol,DOLZINA,0); glVertex3f(gol,DOLZINA+not,0); glVertex3f(-gol,DOLZINA+not,0); glColor4f(0.3,0.3,0.8, 0.5); //Stranice zagolja glVertex3f(gol,-DOLZINA,0); glVertex3f(gol,-DOLZINA-not,0); glVertex3f(gol,-DOLZINA-not,VISINA/3); glVertex3f(gol,-DOLZINA,VISINA); glVertex3f(gol,-DOLZINA-not,0); glVertex3f(gol,-DOLZINA-not,VISINA/3); glVertex3f(-gol,-DOLZINA-not,VISINA/3); glVertex3f(-gol,-DOLZINA-not,0); glVertex3f(-gol,-DOLZINA,0); glVertex3f(-gol,-DOLZINA-not,0); glVertex3f(-gol,-DOLZINA-not,VISINA/3); glVertex3f(-gol,-DOLZINA,VISINA); glVertex3f(gol,DOLZINA,0); glVertex3f(gol,DOLZINA+not,0); glVertex3f(gol,DOLZINA+not,VISINA/3); glVertex3f(gol,DOLZINA,VISINA); glVertex3f(gol,DOLZINA+not,0); glVertex3f(gol,DOLZINA+not,VISINA/3); glVertex3f(-gol,DOLZINA+not,VISINA/3); glVertex3f(-gol,DOLZINA+not,0); glVertex3f(-gol,DOLZINA,0); glVertex3f(-gol,DOLZINA+not,0); glVertex3f(-gol,DOLZINA+not,VISINA/3); glVertex3f(-gol,DOLZINA,VISINA); // Stranice //Zgornja glVertex3f(-SIRINA,DOLZINA,0); glVertex3f(-gol,DOLZINA,0); glVertex3f(-gol,DOLZINA,VISINA); glVertex3f(-SIRINA,DOLZINA,VISINA); glVertex3f(gol,DOLZINA,0); glVertex3f(SIRINA,DOLZINA,0); glVertex3f(SIRINA,DOLZINA,VISINA); glVertex3f(gol,DOLZINA,VISINA); //Stranska glVertex3f(SIRINA,DOLZINA,0); glVertex3f(SIRINA,-DOLZINA,0); glVertex3f(SIRINA,-DOLZINA,VISINA); glVertex3f(SIRINA,DOLZINA,VISINA); // Spodnja glNormal3f(-1, 0, 0); glVertex3f(SIRINA,-DOLZINA,0); glVertex3f(gol,-DOLZINA,0); glVertex3f(gol,-DOLZINA,VISINA); glVertex3f(SIRINA,-DOLZINA,VISINA); glNormal3f(-1, 0, 0); glVertex3f(-SIRINA,-DOLZINA,0); glVertex3f(-gol,-DOLZINA,0); glVertex3f(-gol,-DOLZINA,VISINA); glVertex3f(-SIRINA,-DOLZINA,VISINA); // stranska glVertex3f(-SIRINA,-DOLZINA,0); glVertex3f(-SIRINA,DOLZINA,0); glVertex3f(-SIRINA,DOLZINA,VISINA); glVertex3f(-SIRINA,-DOLZINA,VISINA); glEnd(); // Črte na igrišču glBegin(GL_QUADS); glColor3f(0.8,0.6,0.6); glVertex3f(-SIRINA,0.06,0.005); glVertex3f(SIRINA,0.06,0.005); glVertex3f(SIRINA,-0.06,0.005); glVertex3f(-SIRINA,-0.06,0.005); glColor3f(0.6,0.6,0.8); glVertex3f(-SIRINA,0.60,0.005); glVertex3f(SIRINA,0.60,0.005); glVertex3f(SIRINA,0.64,0.005); glVertex3f(-SIRINA,0.64,0.005); glColor3f(0.6,0.6,0.8); glVertex3f(-SIRINA,-0.60,0.005); glVertex3f(SIRINA,-0.60,0.005); glVertex3f(SIRINA,-0.64,0.005); glVertex3f(-SIRINA,-0.64,0.005); glEnd(); // Goli glColor3f(0.8,0.6,0.6); glBegin(GL_LINES); glVertex3f(gol+0.005, 3, 0.005); glVertex3f(gol+0.005, 2.5, 0.005); glVertex3f(-gol-0.005, 3, 0.005); glVertex3f(-gol-0.005, 2.5, 0.005); glVertex3f(gol+0.005, 2.5, 0.005); glVertex3f(-gol-0.005, 2.5, 0.005); glVertex3f(gol+0.005, -3, 0.005); glVertex3f(gol+0.005, -2.5, 0.005); glVertex3f(-gol-0.005, -3, 0.005); glVertex3f(-gol-0.005, -2.5, 0.005); glVertex3f(gol+0.005, -2.5, 0.005); glVertex3f(-gol-0.005, -2.5, 0.005); glColor3f(0.5,0.5,0.5); glVertex3f(-gol,-DOLZINA,0.005); glVertex3f(gol,-DOLZINA,0.005); glVertex3f(gol,-DOLZINA-0.003,0.005); glVertex3f(-gol,-DOLZINA-0.003,0.005); glVertex3f(-gol,DOLZINA,0.005); glVertex3f(gol,DOLZINA,0.005); glVertex3f(gol,DOLZINA+0.003,0.005); glVertex3f(-gol,DOLZINA+0.003,0.005); glColor3f(0.8,0.6,0.6); glEnd( ); glPushMatrix(); glTranslatef((float)SIRINA/2,(float)DOLZINA/2,0.005); drawCircle((float)SIRINA/4); drawCircle((float)SIRINA/50); glTranslatef((float)(-SIRINA),0,0); drawCircle((float)SIRINA/4); drawCircle((float)SIRINA/50); glTranslatef(0,(float)(-DOLZINA),0); drawCircle((float)SIRINA/4); drawCircle((float)SIRINA/50); glTranslatef((float)SIRINA,0,0); drawCircle((float)SIRINA/4); drawCircle((float)SIRINA/50); glPopMatrix(); // Pak // Preveri trk // pak pos x, pak pos y, pak dir x, pak dir y, njegov pos x, njegov posy input.clear(); input.push_back((pakec.getPos().getY()+DOLZINA)/(DOLZINA*2)); input.push_back((pakec.getPos().getX()+SIRINA)/(SIRINA*2)); input.push_back((pakec.getDir().getY())); //cout<<pakec.getDir().getX()<<endl;5 input.push_back((pakec.getDir().getX())); input.push_back((pakec3.getPos().getY()+DOLZINA)/(DOLZINA*2)); input.push_back((pakec3.getPos().getX()+SIRINA)/(SIRINA*2)); //printf("Input: %f, %f, %f, %f, %f, %f\n", input[0],input[1],input[2]input[3],input[4],input[5]); //cout<<"Input: "<<input[0]<<", "<<input[1]<<", "<<input[2]<<", "<<input[3]<<", "<<input[4]<<", "<<input[5]<<endl; output=network->calculate(input); //printf("%f, %f", output[1],output[0]); //cout<<"<>"<<input[0]<<", "<<input[1]<<", "<<input[2]<<", "<<input[3]<<", "<<input[4]<<", "<<input[5]<<endl; pakec3.setDir(output[1]*DOLZINA/3,output[0]*SIRINA/3); Point2 temp=pakec3.getPos()+pakec3.getDir()*0.05; //printf("%f - %f\n", temp.getX(), temp.getY()); if (abs(temp.getX())>=SIRINA-pakec3.getRad()) { if (pakec3.getDir().getX()<0) { pakec3.setPos(-SIRINA+pakec3.getRad()+0.001,pakec3.getPos().getY()); } if (pakec3.getDir().getX()>0) { pakec3.setPos(SIRINA-pakec3.getRad()-0.001,pakec3.getPos().getY()); } pakec3.setDir(0,0); } if (abs(temp.getY())>=DOLZINA-pakec3.getRad()) { pakec3.setPos(pakec3.getPos().getX(),DOLZINA-pakec3.getRad()-0.001); pakec3.setDir(0,0); } if (temp.getY()<= pakec3.getRad()) { pakec3.setPos(pakec3.getPos().getX(),pakec3.getRad()+0.001); pakec3.setDir(0,0); } //pakec3.setDir((pakec.getPos().getX()-pakec3.getPos().getX())/20+sin(angle/11)/50,sin(angle/11)/10); //pakec3.setDir(sin(angle/10)/10,0); //pakec3.setPos(pakec.getPos().getX(),2+sin(angle/100)); // | | // \_/ // ˇ| ooo |' // \ooooo/ // ooo ooo // ooo ooo BUG! // /oo oo\ // .| |. preveriTrk(pakec, pakec2); preveriTrk(pakec, pakec3); preveriTrkeInGol(pakec); pakec.UpdatePos(); pakec3.UpdatePos(); //pakec2.UpdatePos(); pakec2.setDir(0,0); glColor3f(0.1,0.1,0.1); izrisi(pakec); glColor3f(0.1,0.1,0.7); izrisi(pakec2); glColor3f(0.5,0.1,0.1); izrisi(pakec3); glColor3f(0.3, 0.3, 1); glRasterPos3f(-SIRINA/3,DOLZINA,VISINA+0.2); char buffer[2]; sprintf(buffer, "%i", resultpl1); glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18, buffer[0]); glColor3f(0, 0, 0); glRasterPos3f(0,DOLZINA,VISINA+0.2); glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18, '-'); glColor3f(1, 0.3, 0.3); glRasterPos3f(SIRINA/3,DOLZINA,VISINA+0.2); sprintf(buffer, "%i", resultpl2); glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18, buffer[0]); glColor3f(0.3, 0.3, 0.3); napisi(0,0,1, statustxt); angle++; //pakec2.setDir(pakec2.getDir().getX()*0.9,pakec2.getDir().getY()*0.9); } void MouseMotion(int x, int y) { WIN_X = x; WIN_Y = y; glutPostRedisplay(); GLint viewport[4]; GLdouble modelview[16]; GLdouble projection[16]; GLdouble posX, posY, posZ; glGetDoublev(GL_MODELVIEW_MATRIX, modelview); glGetDoublev(GL_PROJECTION_MATRIX, projection); glGetIntegerv(GL_VIEWPORT, viewport); WIN_Y = (float)viewport[3] - (float)WIN_Y; glReadPixels((int)WIN_X, (int)WIN_Y, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &WIN_Z); gluUnProject(WIN_X, WIN_Y, WIN_Z, modelview, projection, viewport, &posX, &posY, &posZ); if ((abs(posX)<=SIRINA-pakec.getRad())&&((posY<=0)&&(posY>-DOLZINA))){ pakec2.setDir((posX-pakec2.getPos().getX())/5,(posY-pakec2.getPos().getY())/5); pakec2.UpdatePos(); //printf("%i\n", posX); } } void init (void) { glEnable (GL_DEPTH_TEST); glEnable (GL_LIGHTING); glEnable (GL_LIGHT0); glEnable (GL_LIGHT1); glShadeModel (GL_SMOOTH); glEnable(GL_COLOR_MATERIAL); glEnable (GL_BLEND); glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); network->load("utezi.txt"); } void display (void) { glClearDepth(1); glClearColor (0.9,0.9,1,1.0); glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glLoadIdentity(); GLfloat DiffuseLight[] = {1, 1,1}; //set DiffuseLight[] to the specified values GLfloat AmbientLight[] = {1, 1, 1}; //set AmbientLight[] to the specified values GLfloat LightPosition[] = {0, 0, 1, 0}; //set the LightPosition to the specified values glLightfv (GL_LIGHT0, GL_DIFFUSE, DiffuseLight); //change the light accordingly glLightfv (GL_LIGHT1, GL_AMBIENT, AmbientLight); //change the light accordingly glLightfv (GL_LIGHT0, GL_POSITION, LightPosition); //change the light accordingly gluLookAt (0.0, 2.5, 5.5, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0); Risi(); glutSwapBuffers(); } void reshape (int w, int h) { glViewport (0, 0, (GLsizei)w, (GLsizei)h); glMatrixMode (GL_PROJECTION); glLoadIdentity (); gluPerspective (30, (GLfloat)w / (GLfloat)h, 1.0, 100.0); glMatrixMode (GL_MODELVIEW); } int main (int argc, char **argv) { glutInit (&argc, argv); glutInitDisplayMode (GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH); glutInitWindowSize (1024, 768); glutInitWindowPosition (100, 100); glutCreateWindow ("A basic OpenGL Window"); glutPassiveMotionFunc(MouseMotion); init (); glutDisplayFunc (display); glutIdleFunc (display); glutReshapeFunc (reshape); glutMainLoop (); return 0; }
[ "matjaz.lenic@07432978-1335-11de-a4db-e31d5fa7c4f0" ]
[ [ [ 1, 506 ] ] ]
07166190e1286dc4df1e2bb27d13526562dbabf9
205069c97095da8f15e45cede1525f384ba6efd2
/Casino/Code/Server/GameModule/P_Slot_Star97/GameProject/TableFrameSink.cpp
84d546b2283cef89f1dceb83d0c53285eed0be78
[]
no_license
m0o0m/01technology
1a3a5a48a88bec57f6a2d2b5a54a3ce2508de5ea
5e04cbfa79b7e3cf6d07121273b3272f441c2a99
refs/heads/master
2021-01-17T22:12:26.467196
2010-01-05T06:39:11
2010-01-05T06:39:11
null
0
0
null
null
null
null
GB18030
C++
false
false
1,494
cpp
#include "StdAfx.h" #include ".\tableframesink.h" CTableFrameSink::CTableFrameSink(void) { } CTableFrameSink::~CTableFrameSink(void) { } //管理接口 //初始化 bool __cdecl CTableFrameSink::InitTableFrameSink(IUnknownEx * pIUnknownEx) { if(!__super::InitTableFrameSink(pIUnknownEx)) return false; return true; } //复位桌子 void __cdecl CTableFrameSink::RepositTableFrameSink() { __super::RepositTableFrameSink(); return; } //游戏事件 //游戏开始 bool __cdecl CTableFrameSink::OnEventGameStart() { return true; } //游戏结束 bool __cdecl CTableFrameSink::OnEventGameEnd(WORD wChairID, IServerUserItem * pIServerUserItem, BYTE cbReason) { return true; } //发送场景 bool __cdecl CTableFrameSink::SendGameScene(WORD wChiarID, IServerUserItem * pIServerUserItem, BYTE bGameStatus, bool bSendSecret) { return true; } //人工智能游戏动作 bool __cdecl CTableFrameSink::OnPerformAIGameAction() { return true; } //事件接口 //定时器事件 bool __cdecl CTableFrameSink::OnTimerMessage(WORD wTimerID, WPARAM wBindParam) { return false; } //游戏消息处理 bool __cdecl CTableFrameSink::OnGameMessage(WORD wSubCmdID, const void * pDataBuffer, WORD wDataSize, IServerUserItem * pIServerUserItem) { return false; } //框架消息处理 bool __cdecl CTableFrameSink::OnFrameMessage(WORD wSubCmdID, const void * pDataBuffer, WORD wDataSize, IServerUserItem * pIServerUserItem) { return false; }
[ [ [ 1, 62 ] ] ]
56a9c073642096d0225f91961cb883b5d48b6c2f
b002ebd2938f8d79c6b09fc652064001a2d92887
/source/FileIo.cpp
6021f1bf8c08d2eff3bfbf2ada545c3f6196a275
[]
no_license
benbaker76/DetectiveDS
104a175738970dfd12ea8557685a63245b2a3fbe
ca487610b8088a07fc7fe62e345557ccb9663b20
refs/heads/master
2022-11-25T17:22:07.218401
2011-07-30T13:13:23
2011-07-30T13:13:23
241,390,011
1
0
null
null
null
null
UTF-8
C++
false
false
2,666
cpp
#include <nds.h> #include <stdio.h> #include <malloc.h> #include <fat.h> #include <unistd.h> //#include "zlib.h" #include "efs_lib.h" // include EFS lib char *pFileBuffer = NULL; int readFile(const char *fileName) { FILE *pFile; struct stat fileStat; size_t result; if(pFileBuffer != NULL) free(pFileBuffer); pFile = fopen(fileName, "rb"); if(pFile == NULL) return 0; if(stat(fileName, &fileStat) != 0) { fclose(pFile); return 0; } pFileBuffer = (char *) malloc(fileStat.st_size); if(pFileBuffer == NULL) { fclose(pFile); return 0; } result = fread(pFileBuffer, 1, fileStat.st_size, pFile); if(result != (uint) fileStat.st_size) { fclose(pFile); return 0; } fclose(pFile); return result; } int readFileBuffer(const char *fileName, char *pBuffer) { FILE *pFile; struct stat fileStat; size_t result; pFile = fopen(fileName, "rb"); if(pFile == NULL) return 0; if(stat(fileName, &fileStat) != 0) { fclose(pFile); return 0; } result = fread(pBuffer, 1, fileStat.st_size, pFile); if(result != (uint) fileStat.st_size) { fclose(pFile); return 0; } fclose(pFile); return result; } int writeFileBuffer(const char *fileName, char *pBuffer) { FILE *pFile; struct stat fileStat; size_t result; pFile = fopen(fileName, "wb+"); if(pFile == NULL) return 0; if(stat(fileName, &fileStat) != 0) { fclose(pFile); return 0; } result = fwrite(pBuffer, 1, fileStat.st_size, pFile); if(result != (uint) fileStat.st_size) { fclose(pFile); return 0; } fclose(pFile); return result; } /* int decompressFileBuffer(const char *fileName, char *pBuffer, int bufferLen) { FILE *pFile; struct stat fileStat; size_t result; pFile = fopen(fileName, "rb"); if(pFile == NULL) return 0; if(stat(fileName, &fileStat) != 0) { fclose(pFile); return 0; } void *pZLibBuffer = malloc(fileStat.st_size); if(pZLibBuffer == NULL) { fclose(pFile); return 0; } result = fread(pZLibBuffer, 1, fileStat.st_size, pFile); if(result != (uint) fileStat.st_size) { free(pZLibBuffer); fclose(pFile); return 0; } uLongf unCompSize = bufferLen; uncompress((Bytef*)pBuffer, &unCompSize, (const Bytef*) pZLibBuffer, fileStat.st_size); free(pZLibBuffer); fclose(pFile); return result; } */ int readFileSize(const char *fileName) { struct stat fileStat; size_t result; result = stat(fileName, &fileStat); if(result != 0) return 0; return fileStat.st_size; }
[ [ [ 1, 168 ] ] ]
d38ae24b9966777f0f619ffd99eca3602abac61a
4275e8a25c389833c304317bdee5355ed85c7500
/KylTek/GUIEvents.cpp
8adaa885d19bdc882495e50adac982a07f700975
[]
no_license
kumorikarasu/KylTek
482692298ef8ff501fd0846b5f41e9e411afe686
be6a09d20159d0a320abc4d947d4329f82d379b9
refs/heads/master
2021-01-10T07:57:40.134888
2010-07-26T12:10:09
2010-07-26T12:10:09
55,943,006
0
0
null
null
null
null
MacCentralEurope
C++
false
false
3,913
cpp
#include "winsock2.h" #include "Main.h" #include "GUI.h" #include "CConsole.h" #include "CLevel.h" #include "CGlobal.h" #include "CollisionManager.h" SOCKET Client; sockaddr_in CLIENT; string hostIP; WSADATA w; // used to store information about WinSock version void OnGUIEvent(UINT Event, CGUIBase* Src, void* Dest){ UINT GUIType=Src->GetType(); switch(GUIType){ case GUITYPE_WINDOW: break; case GUITYPE_INPUTBOX: switch(Event){ case EVENT_TOGGLEFULLSCREEN: case EVENT_NEWGAME: case EVENT_SAVEGAME: case EVENT_EXITGAME: break; case EVENT_CONSOLE: ((CConsole*)Dest)->Command(((CGUIInputBox*)Src)->GetText()); ((CGUIInputBox*)Src)->SetText(""); break; case EVENT_SETGLOBAL: break; } break; case GUITYPE_RADIO: switch(Event){ case EVENT_SETGLOBAL: break; } break; case GUITYPE_CHECKBOX: switch(Event){ case EVENT_TOGGLEFULLSCREEN: //fullscreen=((CGUICheckBox*)Src)->GetChecked(); break; case EVENT_SETGLOBAL: break; } break; case GUITYPE_BUTTON: switch(Event){ case EVENT_TOGGLEFULLSCREEN: case EVENT_NEWGAME: Src->GetParent()->OnFocusOut(); Src->GetParent()->SetEnabled(false); Src->GetParent()->SetVisible(false); ((CLevel*)Dest)->DumpLevel(); ((CLevel*)Dest)->LoadLevel("../Resources/Levels/level1.mel"); Global->inGame=true; break; /*case EVENT_LOADGAME: ((CLevel*)Dest)->DumpLevel(); ((CLevel*)Dest)->LoadLevel("../Resources/Levels/level1.mel"); Global->inGame=true; break; */ case EVENT_NETWORK: //Open Netplay Window //DEBUG //INI WINSOCK WSAStartup (0x0202, &w); // Fill in w //CONNECT TO MASTER SERVER hostIP = "99.236.225.103"; Client = socket (AF_INET, SOCK_DGRAM, 0);; // Create socket CLIENT.sin_family = AF_INET; // address family Internet CLIENT.sin_port = htons (7500); // set serverís port number CLIENT.sin_addr.s_addr = inet_addr (hostIP.c_str()); // set serverís IP /*if (connect(Client, (struct sockaddr *) &CLIENT, sizeof(CLIENT)) == SOCKET_ERROR) { // an error connecting has occurred! cout << "Error!\n"; if (WSAGetLastError() == 10060) cout << "Connection Timed out"; else cout << WSAGetLastError(); WSACleanup (); } */ //END DEBUG break; case EVENT_SAVEGAME: break; case EVENT_EXITGAME: Global->Exit=true; break; case EVENT_OPENWINDOW: ((CGUIWindow*)Dest)->SetEnabled(true); ((CGUIWindow*)Dest)->RequestFocus(); break; case EVENT_CLOSEWINDOW: ((CGUIWindow*)Dest)->OnFocusOut(); ((CGUIWindow*)Dest)->SetEnabled(false); ((CGUIWindow*)Dest)->SetVisible(false); break; case EVENT_SWITCHTABS: ((CGUITabGroup*)Dest)->ActivateTab(((CGUIButton*)Src)->GetText()); break; case EVENT_SCROLLLEFT: { CGUIHorizontalScrollBar* dest; dest=((CGUIHorizontalScrollBar*)Dest); dest->Scroll(-(dest->GetMaxValue()/(dest->GetMaxBarWidth()-dest->GetBarWidth()))); } break; case EVENT_SCROLLRIGHT: { CGUIHorizontalScrollBar* dest; dest=((CGUIHorizontalScrollBar*)Dest); dest->Scroll(dest->GetMaxValue()/(dest->GetMaxBarWidth()-dest->GetBarWidth())); } break; case EVENT_SCROLLUP: { CGUIVerticalScrollBar* dest; dest=((CGUIVerticalScrollBar*)Dest); dest->Scroll(-(dest->GetMaxValue()/(dest->GetMaxBarHeight()-dest->GetBarHeight()))); } break; case EVENT_SCROLLDOWN: { CGUIVerticalScrollBar* dest; dest=((CGUIVerticalScrollBar*)Dest); dest->Scroll(dest->GetMaxValue()/(dest->GetMaxBarHeight()-dest->GetBarHeight())); } break; } break; case GUITYPE_TABGROUP: break; } }
[ "Sean Stacey@localhost" ]
[ [ [ 1, 150 ] ] ]
5d11f91c2b168fea66d627b179f223350014ad6f
891e876aafde31b093ff8a67907c4b36a1e632b2
/common/LibHeaders/IND_Animation.h
a72b5f6e927f422ddb6b68a5cf50ec579173a9ce
[]
no_license
aramande/Nirena
fc51d8768e9a9fb7e44dd6fadf726ed3fc1d51c8
1e7299ee4915ab073dc7c64569789a07769e71be
refs/heads/master
2021-01-18T20:17:52.943977
2010-12-04T00:05:10
2010-12-04T00:05:10
1,217,641
0
0
null
null
null
null
ISO-8859-2
C++
false
false
7,292
h
/***************************************************************************************** /* File: IND_Animation.h /* Desc: Animation object /*****************************************************************************************/ /* IndieLib 2d library Copyright (C) 2005 Javier López López ([email protected]) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef _IND_ANIMATION_ #define _IND_ANIMATION_ // ----- Includes ----- #include "IND_Frame.h" #include "IND_Sequence.h" // -------------------------------------------------------------------------------- // IND_Animation // -------------------------------------------------------------------------------- /*! \defgroup IND_Animation IND_Animation \ingroup Objects Class for storing sequences of frames (animations). Click in ::IND_Animation to see all the methods of this class. */ /*@{*/ /*! IND_Animation objects are loaded trough the methods of IND_AnimationManager. In order to load an animation it is necessary to create an animation script in xml format. The structure of the script is quite easy to understand. In each animation script you define first the frames (each of the sprites) that you will use for the sequences that you want to create. Later, you create sequences, using references to these frames, and specifying the time delay between frames. So, you can set different sequences using the same frames. The schema of one animation would be as follows: \code Animation { Frames {Frame_1, Frame_2, Frame_3... Frame_n} Sequences { Sequence_1 (list of n frames) Sequence_2 (list of n frames) Sequence_3 (list of n frames) ... Sequence_n } } \endcode The \b tokens or <b>keywords</b> of a \b IndieLib animation file are: <b><< Relative to frames >></b> \arg <b><frames></b> Frame section \arg <b><name></b> Name assigned to the frames (later it will be used in the sequences). \arg <b><file></b> Path to the image file. \arg <b><offset_x></b> X offset of the frame. (Optional, 0 by default). \arg <b><offset_y></b> Y offset of the frame. (Optional, 0 by default). <b><< Relative to sequences >></b> \arg <b><sequences></b> Indicates that the sequences are going to be defined in the section between brackets. \arg <b><name></b> Name assigned to the sequence. \arg <b><frame name></b> Name of the frame that we are refering to. Here we have to use one of the names we assigned to the loaded frames. \arg <b><time></b> Time, in milliseconds, that the frame will be displayed. (Optional, 150 by default). \b Note: "//" can be used before a phrase for writing comments. \image html surfa1.jpg Animations example in IndieLib. */ class DLL_EXP IND_Animation { public: // ----- Public gets ------ // ----- Relative to lobal animation ------ //! This function returns the animation script file name in a string of characters. char *GetName () { return mAnimation.mName; } //! This function returns the total number of animation sequences. int GetNumSequences () { return mAnimation.mNumSequences; } //! This function returns the total number of animation frames. int GetNumTotalFrames () { return mVectorFrames->size(); } //! This function returns the pointer to the object ::IND_Image that contains the frame received or NULL in case that the object has not been loaded. IND_Image *GetImage (int pFrame); //! This function returns the pointer to the object ::IND_Surface that contains the frame received or NULL in case that the object has not been loaded. IND_Surface *GetSurface (int pFrame); // ----- Relative to a concrete sequence ------ //! This function returns the maximum width of the sequence. It means, the width of the widest frame of the sequence. int GetHighWidth (int pSequence); //! This function returns the maximum height of the sequence. It means, the height of the highest frame of the sequence. int GetHighHeight (int pSequence); //! This function returns the number of frames which are referenced by the sequeence received as a parameter. int GetNumFrames (int pSequence); //! This function returns the name, in a string of characters, of the sequence received as a paramater. char *GetName (int pSequence); // NOT DOCUMENTED int GetActualFramePos (int pSequence); int GetActualFrameTime (int pSequence); int GetActualOffsetX (int pSequence); int GetActualOffsetY (int pSequence); IND_Surface *GetActualSurface (int pSequence); void SetActualFramePos (int pSequence, int pPos); IND_Timer *GetSequenceTimer (int pSequence); bool GetIsActive (int pSequence); void SetIsActive (int pSequence, bool pAct); // ----- Public sets ------ //! This function establish a IND_Image object in a frame. It can be useful for modifying some frames of animations.Note: It is convenient to eliminate any IND_Image object that would be there before setting the actual one. void SetImage (int pFrame, IND_Image *pNewImage); //! This function establish a IND_Surface object in a frame. It can be useful for modifying some frames of animations.Note: It is convenient to eliminate any IND_Surface object that would be there before setting the actual one. void SetSurface (int pFrame, IND_Surface *pNewSurface); private: // ----- Structures ------ vector <IND_Frame*> *mVectorFrames; // Vector of frames // Animation (list of sequences) struct structAnimation { char *mName; // Animation name int mNumSequences; // Number os sequences vector <IND_Sequence*> *mListSequences; // Sequence list structAnimation () { mName = 0; mNumSequences = 0; } }; typedef struct structAnimation ANIMATION; ANIMATION mAnimation; // ----- Private sets ------ void SetName (char *pName) { mAnimation.mName = pName; } void SetNumSequences (int pNum) { mAnimation.mNumSequences = pNum; } // ----- Private gets ------ vector <IND_Sequence*> *GetListSequences () { return mAnimation.mListSequences; } vector <IND_Frame*> *GetVectorFrames () { return mVectorFrames; } // ----- Friends ----- friend class IND_AnimationManager; friend class IND_Render; friend class IND_Entity2dManager; }; /*@}*/ #endif // _IND_ANIMATION_
[ [ [ 1, 181 ] ] ]
4289cb0b8ff04511710ef7c62c7acdc073aac7a0
0f8559dad8e89d112362f9770a4551149d4e738f
/Wall_Destruction/Havok/Source/ContentTools/Common/Filters/Common/FilterManager/hctFilterManagerInterface.h
ac99156cf1d27766ed971bed9a916503424fab3c
[]
no_license
TheProjecter/olafurabertaymsc
9360ad4c988d921e55b8cef9b8dcf1959e92d814
456d4d87699342c5459534a7992f04669e75d2e1
refs/heads/master
2021-01-10T15:15:49.289873
2010-09-20T12:58:48
2010-09-20T12:58:48
45,933,002
0
0
null
null
null
null
UTF-8
C++
false
false
9,095
h
/* * * Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's * prior written consent. This software contains code, techniques and know-how which is confidential and proprietary to Havok. * Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2009 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement. * */ #ifndef HAVOK_FILTER_MANAGER_INTERFACE__H #define HAVOK_FILTER_MANAGER_INTERFACE__H #include <Common/Base/Fwd/hkwindows.h> class hkPackfileData; /// The interface to the filter manager. /// Use the function createFilterManager() exposed in hctFilterManagerDll to do that. /// We make this pure virtual so that the actual implementation can be havok memory managed etc.. /// and this interface is still clean. It also avoids static linkage with the implementation. /// Some methods are used by applications calling the filter manager (exporters for example), while other /// will mostly be used by filters during processing. class hctFilterManagerInterface { public: /// Virtual destructor virtual ~hctFilterManagerInterface() {} /// Returns a version associated with the filter manager. /// This version is used to check compatibility between configurations. virtual unsigned int getFilterManagerVersion() const = 0; /* * Configuration options : Called by application (exporter) */ /// Get the current configuration set, including all the filters for each configuration. /// This data is usually saved with the original asset, or saved explicitly by the user to file. /// Pass in a NULL to retrieve the required size of the buffer. virtual int getConfigurationSet(void* optionData) const = 0; /// Initialize a configuration set. virtual void setConfigurationSet(const void* optionData, int optionDataSize) = 0; /* * Interaction and processing, called by the application (exporter) */ /// Bring up a dialog box to allow the user to organize which filters to use. /// The selected filters and configuration are remembered between runs. /// It returns whether the configuration should be executed and whether it should be saved. virtual void openFilterManager ( HWND owner, const class hkRootLevelContainer& data, hkBool& shouldSaveConfigOut ) = 0; /// Process a scene in batch mode. All configurations will be executed. /// It will alter a copy of the data (one per config) in place as much as possible and all allocations into the hkRootLevelContainer /// will be through the memory tracker. As such the contents of the scene post process will be /// valid until you delete the memory tracker (will deallocate all tracked mem) or you shut down /// this manager instance (it will unload all the filter DLLs and hence all the hkClasses from /// those DLLs will be unloaded too and the pointers in any registry etc ). virtual void processBatch ( HWND owner, const class hkRootLevelContainer& data, int configToRun = -1, bool allowModlessFilters = false ) = 0; /// Process a scene in batch mode. Only specific configuration will be executed. /// It will alter a copy of the data in place as much as possible and all allocations into the hkRootLevelContainer /// will be through the memory tracker. As such the contents of the scene post process will be /// valid until you delete the memory tracker (will deallocate all tracked mem) or you shut down /// this manager instance (it will unload all the filter DLLs and hence all the hkClasses from /// those DLLs will be unloaded too and the pointers in any registry etc ). /// It will only return the modified (copied) data if you provide a sceneCopyStorage array to hold the original deep copy virtual hkRootLevelContainer* processBatchReturnData( HWND owner, const class hkRootLevelContainer& data, int configToRun, bool allowModelessFilters, hkPackfileData*& sceneCopyData ) = 0; /* ** Methods useful for filters */ /// Some filters may want to access the contents that is going to be processed in order to show their options /// (for example in order to present picking dialogs). Notice that this is not necessarily the contents that /// will reach the filter (as it may be modified by any filter preceding this one) virtual const class hkRootLevelContainer* getOriginalContents() const = 0; /// Get the filter manager's error handler. /// Allows for merging with other error handlers (from the exporters for example). virtual class hctSceneExportError* getErrorHandler() = 0; /// Some complicated filter setups require some knowledge on what /// data they will get upon process(), so this will process up /// to the given filter, in the current filter configuration. /// It's up to the filter to manage the memory of this contents, hence the storageTempMem parameter. virtual bool getInputContentsToCurrentFilter ( hkRootLevelContainer** outputData, hkPackfileData*& sceneCopyData ) const = 0; /// Returns the HWND of the filter manager main window (or HK_NULL if no UI is shown). virtual HWND getMainWindowHandle () const = 0; /// Returns the HWND of the application (owner) that called the filter manager virtual HWND getOwnerWindowHandle () const = 0; enum ProcessMode { PROCESS_NONE = 0, // not in process of any type PROCESS_INTERACTIVE, // full interactive run PROCESS_BATCH, // batch (so no ui) and do full writes etc PROCESS_BATCH_UI, // batch (but with ui / modeless filters) and do full writes etc OPTIONS_BATCH // batch mode for options to current dialog etc, write any scene mutating data, but do not alter external files }; virtual ProcessMode getProcessMode() const = 0; /* * Thread utils */ /// Register a thread callback. DLLs creating objects with virtual methods need to register themselves /// so their threadback data is updated when a new thread is created. The filter manager automatically /// registers filter DLLS, but if you have another module taking part (a non-filter DLL, like hkpreview) /// you can register a callback to ensure thread information is registered in that module. The scene exporters /// register themselves using this mechanism. virtual void registerThreadCallback (const class hctFilterThreadCallback* cb)= 0; /// If you create a thread that will use code from a another filter (by means /// of vtable calls for instance) you must propagate your thread data (esp thread mem) /// It will set the thread data for all filters, but also whatever callback /// is registered too (just one) virtual void setThreadData (hkMemoryRouter* memRouter) const = 0; /* * Utility dialogs, called by filters */ /// Bring up a modal dialog to select a given node, mesh, whatever from the scene. /// A tree view manager may be implemented to limit the selection to a specific root node /// and/or specific class types. If the user successfully selected an object, the /// function returns true and the selected object is returned as the variant. virtual bool selectObjectFromTree( HWND owner, const char* title, class hctTreeViewManager* tvManager, struct hkVariant& selected ) const = 0; /// Bring up a modal dialog to select one item from a list of items. /// Returns the index of the selected item, or -1 if the user hit cancel or escape. virtual int selectItemFromList( HWND owner, const char* title, const hkArray<const char*>& items ) const = 0; /// Bring up a modal dialog to show a list of item names. /// Only action available to the user is to close the dialog. virtual void showItems( HWND owner, const char* title, const hkArray<const char*>& items ) const = 0; }; /// Thread callback : Registered through hctFilterManagerInterface::registerThreadCallback, these objects will /// be called each time a new thread is created by any filter. class hctFilterThreadCallback { public: /// This method will be called each time a new thread is created by any filter. virtual void newThreadCreated (hkMemoryRouter* memRouter) const = 0; }; #endif // HAVOK_FILTER_MANAGER_INTERFACE__H /* * Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20091222) * * Confidential Information of Havok. (C) Copyright 1999-2009 * Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok * Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership * rights, and intellectual property rights in the Havok software remain in * Havok and/or its suppliers. * * Use of this software for evaluation purposes is subject to and indicates * acceptance of the End User licence Agreement for this product. A copy of * the license is included with this software and is also available at www.havok.com/tryhavok. * */
[ [ [ 1, 171 ] ] ]
bcb8d00fee3e653153a07f2ab03a1a54527f9ada
5d36f6102c8cadcf1a124b366ae189d6a2609c59
/src/symbian/glue/minimal.cpp
6aec75f42d4c1dac48094a8d3c25e865b8837c28
[]
no_license
Devil084/psx4all
336f2861246367c8d397ef5acfc0b7972085c21b
04c02bf8840007792d23d15ca42a572035a1d703
refs/heads/master
2020-02-26T15:18:04.554046
2010-08-11T13:49:24
2010-08-11T13:49:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
32,167
cpp
#include "minimal.h" #include "profiler.h" #ifdef PROFILER_PSX4ALL #include "timeval.h" #endif extern int psx4all_emulating; #ifdef __WIN32__ int __errno; #endif int gp2x_sdlwrapper_bpp=8; void *gp2x_sdlwrapper_screen_pixels=NULL; SDL_Surface *gp2x_sdlwrapper_screen=NULL; SDL_Surface *hw_screen=NULL; double gp2x_sdlwrapper_ticksdivisor=1.0; unsigned long gp2x_ticks_per_second = 1000; extern int soundcard; extern int closing_sound; extern void init_sound(unsigned rate, int stereo, int bits); extern void quit_sound(void); int gp2x_double_buffer=0; #ifdef DEBUG FILE* fdbg; #endif /* The font is generated from Xorg 6x10-L1.bdf */ static unsigned char gp2x_fontf[256][10] = { { 0x00>>2, 0xA8>>2, 0x00>>2, 0x88>>2, 0x00>>2, 0x88>>2, 0x00>>2, 0xA8>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x00>>2, 0x20>>2, 0x70>>2, 0xF8>>2, 0x70>>2, 0x20>>2, 0x00>>2, 0x00>>2, 0x00>>2, }, { 0xA8>>2, 0x54>>2, 0xA8>>2, 0x54>>2, 0xA8>>2, 0x54>>2, 0xA8>>2, 0x54>>2, 0xA8>>2, 0x54>>2, }, { 0x00>>2, 0x90>>2, 0x90>>2, 0xF0>>2, 0x90>>2, 0x90>>2, 0x78>>2, 0x10>>2, 0x10>>2, 0x10>>2, }, { 0x00>>2, 0xE0>>2, 0x80>>2, 0xC0>>2, 0x80>>2, 0xB8>>2, 0x20>>2, 0x30>>2, 0x20>>2, 0x20>>2, }, { 0x00>>2, 0x70>>2, 0x80>>2, 0x80>>2, 0x70>>2, 0x70>>2, 0x48>>2, 0x70>>2, 0x48>>2, 0x48>>2, }, { 0x00>>2, 0x80>>2, 0x80>>2, 0x80>>2, 0xF0>>2, 0x78>>2, 0x40>>2, 0x70>>2, 0x40>>2, 0x40>>2, }, { 0x00>>2, 0x20>>2, 0x50>>2, 0x20>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x00>>2, 0x20>>2, 0x20>>2, 0xF8>>2, 0x20>>2, 0x20>>2, 0xF8>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x90>>2, 0xD0>>2, 0xD0>>2, 0xB0>>2, 0x90>>2, 0x40>>2, 0x40>>2, 0x40>>2, 0x78>>2, }, { 0x00>>2, 0x90>>2, 0x90>>2, 0x60>>2, 0x40>>2, 0x78>>2, 0x10>>2, 0x10>>2, 0x10>>2, 0x10>>2, }, { 0x20>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0xE0>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0xE0>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x20>>2, }, { 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x3C>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x20>>2, }, { 0x20>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x3C>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, }, { 0x20>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0xFC>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x20>>2, }, { 0xFC>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x00>>2, 0xFC>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0xFF>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0xFC>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0xFC>>2, }, { 0x20>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x3C>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x20>>2, }, { 0x20>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0xE0>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x20>>2, }, { 0x20>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0xFC>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0xFC>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x20>>2, }, { 0x20>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x20>>2, }, { 0x00>>2, 0x18>>2, 0x60>>2, 0x80>>2, 0x60>>2, 0x18>>2, 0x00>>2, 0xF8>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0xC0>>2, 0x30>>2, 0x08>>2, 0x30>>2, 0xC0>>2, 0x00>>2, 0xF8>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x00>>2, 0x00>>2, 0xF8>>2, 0x50>>2, 0x50>>2, 0x50>>2, 0x50>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x08>>2, 0x10>>2, 0xF8>>2, 0x20>>2, 0xF8>>2, 0x40>>2, 0x80>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x30>>2, 0x48>>2, 0x40>>2, 0xE0>>2, 0x40>>2, 0x48>>2, 0xB0>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x20>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x00>>2, 0x20>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x50>>2, 0x50>>2, 0x50>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x50>>2, 0x50>>2, 0xF8>>2, 0x50>>2, 0xF8>>2, 0x50>>2, 0x50>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x20>>2, 0x70>>2, 0xA0>>2, 0x70>>2, 0x28>>2, 0x70>>2, 0x20>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x48>>2, 0xA8>>2, 0x50>>2, 0x20>>2, 0x50>>2, 0xA8>>2, 0x90>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x40>>2, 0xA0>>2, 0xA0>>2, 0x40>>2, 0xA8>>2, 0x90>>2, 0x68>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x10>>2, 0x20>>2, 0x40>>2, 0x40>>2, 0x40>>2, 0x20>>2, 0x10>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x40>>2, 0x20>>2, 0x10>>2, 0x10>>2, 0x10>>2, 0x20>>2, 0x40>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x00>>2, 0x88>>2, 0x50>>2, 0xF8>>2, 0x50>>2, 0x88>>2, 0x00>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x00>>2, 0x20>>2, 0x20>>2, 0xF8>>2, 0x20>>2, 0x20>>2, 0x00>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x30>>2, 0x20>>2, 0x40>>2, 0x00>>2, }, { 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0xF8>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x20>>2, 0x70>>2, 0x20>>2, 0x00>>2, }, { 0x00>>2, 0x08>>2, 0x08>>2, 0x10>>2, 0x20>>2, 0x40>>2, 0x80>>2, 0x80>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x20>>2, 0x50>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0x50>>2, 0x20>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x20>>2, 0x60>>2, 0xA0>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0xF8>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x70>>2, 0x88>>2, 0x08>>2, 0x30>>2, 0x40>>2, 0x80>>2, 0xF8>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0xF8>>2, 0x08>>2, 0x10>>2, 0x30>>2, 0x08>>2, 0x88>>2, 0x70>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x10>>2, 0x30>>2, 0x50>>2, 0x90>>2, 0xF8>>2, 0x10>>2, 0x10>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0xF8>>2, 0x80>>2, 0xB0>>2, 0xC8>>2, 0x08>>2, 0x88>>2, 0x70>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x30>>2, 0x40>>2, 0x80>>2, 0xB0>>2, 0xC8>>2, 0x88>>2, 0x70>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0xF8>>2, 0x08>>2, 0x10>>2, 0x10>>2, 0x20>>2, 0x40>>2, 0x40>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x70>>2, 0x88>>2, 0x88>>2, 0x70>>2, 0x88>>2, 0x88>>2, 0x70>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x70>>2, 0x88>>2, 0x98>>2, 0x68>>2, 0x08>>2, 0x10>>2, 0x60>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x00>>2, 0x20>>2, 0x70>>2, 0x20>>2, 0x00>>2, 0x20>>2, 0x70>>2, 0x20>>2, 0x00>>2, }, { 0x00>>2, 0x00>>2, 0x20>>2, 0x70>>2, 0x20>>2, 0x00>>2, 0x30>>2, 0x20>>2, 0x40>>2, 0x00>>2, }, { 0x00>>2, 0x08>>2, 0x10>>2, 0x20>>2, 0x40>>2, 0x20>>2, 0x10>>2, 0x08>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x00>>2, 0x00>>2, 0xF8>>2, 0x00>>2, 0xF8>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x40>>2, 0x20>>2, 0x10>>2, 0x08>>2, 0x10>>2, 0x20>>2, 0x40>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x70>>2, 0x88>>2, 0x10>>2, 0x20>>2, 0x20>>2, 0x00>>2, 0x20>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x70>>2, 0x88>>2, 0x98>>2, 0xA8>>2, 0xB0>>2, 0x80>>2, 0x70>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x20>>2, 0x50>>2, 0x88>>2, 0x88>>2, 0xF8>>2, 0x88>>2, 0x88>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0xF0>>2, 0x48>>2, 0x48>>2, 0x70>>2, 0x48>>2, 0x48>>2, 0xF0>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x70>>2, 0x88>>2, 0x80>>2, 0x80>>2, 0x80>>2, 0x88>>2, 0x70>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0xF0>>2, 0x48>>2, 0x48>>2, 0x48>>2, 0x48>>2, 0x48>>2, 0xF0>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0xF8>>2, 0x80>>2, 0x80>>2, 0xF0>>2, 0x80>>2, 0x80>>2, 0xF8>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0xF8>>2, 0x80>>2, 0x80>>2, 0xF0>>2, 0x80>>2, 0x80>>2, 0x80>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x70>>2, 0x88>>2, 0x80>>2, 0x80>>2, 0x98>>2, 0x88>>2, 0x70>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0xF8>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x70>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x70>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x38>>2, 0x10>>2, 0x10>>2, 0x10>>2, 0x10>>2, 0x90>>2, 0x60>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x88>>2, 0x90>>2, 0xA0>>2, 0xC0>>2, 0xA0>>2, 0x90>>2, 0x88>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x80>>2, 0x80>>2, 0x80>>2, 0x80>>2, 0x80>>2, 0x80>>2, 0xF8>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x88>>2, 0x88>>2, 0xD8>>2, 0xA8>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x88>>2, 0x88>>2, 0xC8>>2, 0xA8>>2, 0x98>>2, 0x88>>2, 0x88>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x70>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0x70>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0xF0>>2, 0x88>>2, 0x88>>2, 0xF0>>2, 0x80>>2, 0x80>>2, 0x80>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x70>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0xA8>>2, 0x70>>2, 0x08>>2, 0x00>>2, }, { 0x00>>2, 0xF0>>2, 0x88>>2, 0x88>>2, 0xF0>>2, 0xA0>>2, 0x90>>2, 0x88>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x70>>2, 0x88>>2, 0x80>>2, 0x70>>2, 0x08>>2, 0x88>>2, 0x70>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0xF8>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0x70>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0x50>>2, 0x50>>2, 0x50>>2, 0x20>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0xA8>>2, 0xA8>>2, 0xD8>>2, 0x88>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x88>>2, 0x88>>2, 0x50>>2, 0x20>>2, 0x50>>2, 0x88>>2, 0x88>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x88>>2, 0x88>>2, 0x50>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0xF8>>2, 0x08>>2, 0x10>>2, 0x20>>2, 0x40>>2, 0x80>>2, 0xF8>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x70>>2, 0x40>>2, 0x40>>2, 0x40>>2, 0x40>>2, 0x40>>2, 0x70>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x80>>2, 0x80>>2, 0x40>>2, 0x20>>2, 0x10>>2, 0x08>>2, 0x08>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x70>>2, 0x10>>2, 0x10>>2, 0x10>>2, 0x10>>2, 0x10>>2, 0x70>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x20>>2, 0x50>>2, 0x88>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0xF8>>2, 0x00>>2, }, { 0x20>>2, 0x10>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x00>>2, 0x00>>2, 0x70>>2, 0x08>>2, 0x78>>2, 0x88>>2, 0x78>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x80>>2, 0x80>>2, 0xB0>>2, 0xC8>>2, 0x88>>2, 0xC8>>2, 0xB0>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x00>>2, 0x00>>2, 0x70>>2, 0x88>>2, 0x80>>2, 0x88>>2, 0x70>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x08>>2, 0x08>>2, 0x68>>2, 0x98>>2, 0x88>>2, 0x98>>2, 0x68>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x00>>2, 0x00>>2, 0x70>>2, 0x88>>2, 0xF8>>2, 0x80>>2, 0x70>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x30>>2, 0x48>>2, 0x40>>2, 0xF0>>2, 0x40>>2, 0x40>>2, 0x40>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x00>>2, 0x00>>2, 0x78>>2, 0x88>>2, 0x88>>2, 0x78>>2, 0x08>>2, 0x88>>2, 0x70>>2, }, { 0x00>>2, 0x80>>2, 0x80>>2, 0xB0>>2, 0xC8>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x20>>2, 0x00>>2, 0x60>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x70>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x08>>2, 0x00>>2, 0x18>>2, 0x08>>2, 0x08>>2, 0x08>>2, 0x48>>2, 0x48>>2, 0x30>>2, }, { 0x00>>2, 0x80>>2, 0x80>>2, 0x88>>2, 0x90>>2, 0xE0>>2, 0x90>>2, 0x88>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x60>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x70>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x00>>2, 0x00>>2, 0xD0>>2, 0xA8>>2, 0xA8>>2, 0xA8>>2, 0x88>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x00>>2, 0x00>>2, 0xB0>>2, 0xC8>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x00>>2, 0x00>>2, 0x70>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0x70>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x00>>2, 0x00>>2, 0xB0>>2, 0xC8>>2, 0x88>>2, 0xC8>>2, 0xB0>>2, 0x80>>2, 0x80>>2, }, { 0x00>>2, 0x00>>2, 0x00>>2, 0x68>>2, 0x98>>2, 0x88>>2, 0x98>>2, 0x68>>2, 0x08>>2, 0x08>>2, }, { 0x00>>2, 0x00>>2, 0x00>>2, 0xB0>>2, 0xC8>>2, 0x80>>2, 0x80>>2, 0x80>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x00>>2, 0x00>>2, 0x70>>2, 0x80>>2, 0x70>>2, 0x08>>2, 0xF0>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x40>>2, 0x40>>2, 0xF0>>2, 0x40>>2, 0x40>>2, 0x48>>2, 0x30>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x00>>2, 0x00>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0x98>>2, 0x68>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x00>>2, 0x00>>2, 0x88>>2, 0x88>>2, 0x50>>2, 0x50>>2, 0x20>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x00>>2, 0x00>>2, 0x88>>2, 0x88>>2, 0xA8>>2, 0xA8>>2, 0x50>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x00>>2, 0x00>>2, 0x88>>2, 0x50>>2, 0x20>>2, 0x50>>2, 0x88>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x00>>2, 0x00>>2, 0x88>>2, 0x88>>2, 0x98>>2, 0x68>>2, 0x08>>2, 0x88>>2, 0x70>>2, }, { 0x00>>2, 0x00>>2, 0x00>>2, 0xF8>>2, 0x10>>2, 0x20>>2, 0x40>>2, 0xF8>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x18>>2, 0x20>>2, 0x10>>2, 0x60>>2, 0x10>>2, 0x20>>2, 0x18>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x60>>2, 0x10>>2, 0x20>>2, 0x18>>2, 0x20>>2, 0x10>>2, 0x60>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x48>>2, 0xA8>>2, 0x90>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x20>>2, 0x00>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x00>>2, 0x20>>2, 0x78>>2, 0xA0>>2, 0xA0>>2, 0xA0>>2, 0x78>>2, 0x20>>2, 0x00>>2, }, { 0x00>>2, 0x30>>2, 0x48>>2, 0x40>>2, 0xE0>>2, 0x40>>2, 0x48>>2, 0xB0>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x00>>2, 0x00>>2, 0x88>>2, 0x70>>2, 0x50>>2, 0x70>>2, 0x88>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x88>>2, 0x88>>2, 0x50>>2, 0x20>>2, 0xF8>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x00>>2, }, { 0x00>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x00>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x70>>2, 0x80>>2, 0xE0>>2, 0x90>>2, 0x48>>2, 0x38>>2, 0x08>>2, 0x70>>2, 0x00>>2, }, { 0x50>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x70>>2, 0x88>>2, 0xA8>>2, 0xC8>>2, 0xA8>>2, 0x88>>2, 0x70>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x38>>2, 0x48>>2, 0x58>>2, 0x28>>2, 0x00>>2, 0x78>>2, 0x00>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x00>>2, 0x00>>2, 0x24>>2, 0x48>>2, 0x90>>2, 0x48>>2, 0x24>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x78>>2, 0x08>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x78>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x70>>2, 0x88>>2, 0xE8>>2, 0xC8>>2, 0xC8>>2, 0x88>>2, 0x70>>2, 0x00>>2, 0x00>>2, }, { 0xF8>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x20>>2, 0x50>>2, 0x20>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x00>>2, 0x20>>2, 0x20>>2, 0xF8>>2, 0x20>>2, 0x20>>2, 0xF8>>2, 0x00>>2, 0x00>>2, }, { 0x30>>2, 0x48>>2, 0x10>>2, 0x20>>2, 0x78>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, }, { 0x70>>2, 0x08>>2, 0x30>>2, 0x08>>2, 0x70>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, }, { 0x10>>2, 0x20>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x00>>2, 0x00>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0xC8>>2, 0xB0>>2, 0x80>>2, 0x00>>2, }, { 0x00>>2, 0x78>>2, 0xE8>>2, 0xE8>>2, 0x68>>2, 0x28>>2, 0x28>>2, 0x28>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x20>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x10>>2, 0x20>>2, }, { 0x20>>2, 0x60>>2, 0x20>>2, 0x20>>2, 0x70>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x30>>2, 0x48>>2, 0x48>>2, 0x30>>2, 0x00>>2, 0x78>>2, 0x00>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x00>>2, 0x00>>2, 0x90>>2, 0x48>>2, 0x24>>2, 0x48>>2, 0x90>>2, 0x00>>2, 0x00>>2, }, { 0x40>>2, 0xC0>>2, 0x40>>2, 0x40>>2, 0xE4>>2, 0x0C>>2, 0x14>>2, 0x3C>>2, 0x04>>2, 0x00>>2, }, { 0x40>>2, 0xC0>>2, 0x40>>2, 0x40>>2, 0xE8>>2, 0x14>>2, 0x04>>2, 0x08>>2, 0x1C>>2, 0x00>>2, }, { 0xC0>>2, 0x20>>2, 0x40>>2, 0x20>>2, 0xC8>>2, 0x18>>2, 0x28>>2, 0x78>>2, 0x08>>2, 0x00>>2, }, { 0x00>>2, 0x20>>2, 0x00>>2, 0x20>>2, 0x20>>2, 0x40>>2, 0x88>>2, 0x70>>2, 0x00>>2, 0x00>>2, }, { 0x40>>2, 0x20>>2, 0x70>>2, 0x88>>2, 0x88>>2, 0xF8>>2, 0x88>>2, 0x88>>2, 0x00>>2, 0x00>>2, }, { 0x10>>2, 0x20>>2, 0x70>>2, 0x88>>2, 0x88>>2, 0xF8>>2, 0x88>>2, 0x88>>2, 0x00>>2, 0x00>>2, }, { 0x20>>2, 0x50>>2, 0x70>>2, 0x88>>2, 0x88>>2, 0xF8>>2, 0x88>>2, 0x88>>2, 0x00>>2, 0x00>>2, }, { 0x48>>2, 0xB0>>2, 0x70>>2, 0x88>>2, 0x88>>2, 0xF8>>2, 0x88>>2, 0x88>>2, 0x00>>2, 0x00>>2, }, { 0x50>>2, 0x00>>2, 0x70>>2, 0x88>>2, 0x88>>2, 0xF8>>2, 0x88>>2, 0x88>>2, 0x00>>2, 0x00>>2, }, { 0x20>>2, 0x50>>2, 0x70>>2, 0x88>>2, 0x88>>2, 0xF8>>2, 0x88>>2, 0x88>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x3C>>2, 0x50>>2, 0x90>>2, 0x9C>>2, 0xF0>>2, 0x90>>2, 0x9C>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x70>>2, 0x88>>2, 0x80>>2, 0x80>>2, 0x80>>2, 0x88>>2, 0x70>>2, 0x20>>2, 0x40>>2, }, { 0x40>>2, 0xF8>>2, 0x80>>2, 0x80>>2, 0xF0>>2, 0x80>>2, 0x80>>2, 0xF8>>2, 0x00>>2, 0x00>>2, }, { 0x10>>2, 0xF8>>2, 0x80>>2, 0x80>>2, 0xF0>>2, 0x80>>2, 0x80>>2, 0xF8>>2, 0x00>>2, 0x00>>2, }, { 0x20>>2, 0xF8>>2, 0x80>>2, 0x80>>2, 0xF0>>2, 0x80>>2, 0x80>>2, 0xF8>>2, 0x00>>2, 0x00>>2, }, { 0x50>>2, 0xF8>>2, 0x80>>2, 0x80>>2, 0xF0>>2, 0x80>>2, 0x80>>2, 0xF8>>2, 0x00>>2, 0x00>>2, }, { 0x40>>2, 0x20>>2, 0x70>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x70>>2, 0x00>>2, 0x00>>2, }, { 0x10>>2, 0x20>>2, 0x70>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x70>>2, 0x00>>2, 0x00>>2, }, { 0x20>>2, 0x50>>2, 0x70>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x70>>2, 0x00>>2, 0x00>>2, }, { 0x50>>2, 0x00>>2, 0x70>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x70>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0xF0>>2, 0x48>>2, 0x48>>2, 0xE8>>2, 0x48>>2, 0x48>>2, 0xF0>>2, 0x00>>2, 0x00>>2, }, { 0x28>>2, 0x50>>2, 0x88>>2, 0xC8>>2, 0xA8>>2, 0x98>>2, 0x88>>2, 0x88>>2, 0x00>>2, 0x00>>2, }, { 0x40>>2, 0x20>>2, 0x70>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0x70>>2, 0x00>>2, 0x00>>2, }, { 0x10>>2, 0x20>>2, 0x70>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0x70>>2, 0x00>>2, 0x00>>2, }, { 0x20>>2, 0x50>>2, 0x70>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0x70>>2, 0x00>>2, 0x00>>2, }, { 0x28>>2, 0x50>>2, 0x70>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0x70>>2, 0x00>>2, 0x00>>2, }, { 0x50>>2, 0x00>>2, 0x70>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0x70>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x00>>2, 0x00>>2, 0x88>>2, 0x50>>2, 0x20>>2, 0x50>>2, 0x88>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x70>>2, 0x98>>2, 0x98>>2, 0xA8>>2, 0xC8>>2, 0xC8>>2, 0x70>>2, 0x00>>2, 0x00>>2, }, { 0x40>>2, 0x20>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0x70>>2, 0x00>>2, 0x00>>2, }, { 0x10>>2, 0x20>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0x70>>2, 0x00>>2, 0x00>>2, }, { 0x20>>2, 0x50>>2, 0x00>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0x70>>2, 0x00>>2, 0x00>>2, }, { 0x50>>2, 0x00>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0x70>>2, 0x00>>2, 0x00>>2, }, { 0x10>>2, 0x20>>2, 0x88>>2, 0x88>>2, 0x50>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x80>>2, 0xF0>>2, 0x88>>2, 0xF0>>2, 0x80>>2, 0x80>>2, 0x80>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x70>>2, 0x88>>2, 0x90>>2, 0xA0>>2, 0x90>>2, 0x88>>2, 0xB0>>2, 0x00>>2, 0x00>>2, }, { 0x40>>2, 0x20>>2, 0x00>>2, 0x70>>2, 0x08>>2, 0x78>>2, 0x88>>2, 0x78>>2, 0x00>>2, 0x00>>2, }, { 0x10>>2, 0x20>>2, 0x00>>2, 0x70>>2, 0x08>>2, 0x78>>2, 0x88>>2, 0x78>>2, 0x00>>2, 0x00>>2, }, { 0x20>>2, 0x50>>2, 0x00>>2, 0x70>>2, 0x08>>2, 0x78>>2, 0x88>>2, 0x78>>2, 0x00>>2, 0x00>>2, }, { 0x28>>2, 0x50>>2, 0x00>>2, 0x70>>2, 0x08>>2, 0x78>>2, 0x88>>2, 0x78>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x50>>2, 0x00>>2, 0x70>>2, 0x08>>2, 0x78>>2, 0x88>>2, 0x78>>2, 0x00>>2, 0x00>>2, }, { 0x20>>2, 0x50>>2, 0x20>>2, 0x70>>2, 0x08>>2, 0x78>>2, 0x88>>2, 0x78>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x00>>2, 0x00>>2, 0x78>>2, 0x14>>2, 0x7C>>2, 0x90>>2, 0x7C>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x00>>2, 0x00>>2, 0x70>>2, 0x88>>2, 0x80>>2, 0x88>>2, 0x70>>2, 0x20>>2, 0x40>>2, }, { 0x40>>2, 0x20>>2, 0x00>>2, 0x70>>2, 0x88>>2, 0xF8>>2, 0x80>>2, 0x70>>2, 0x00>>2, 0x00>>2, }, { 0x10>>2, 0x20>>2, 0x00>>2, 0x70>>2, 0x88>>2, 0xF8>>2, 0x80>>2, 0x70>>2, 0x00>>2, 0x00>>2, }, { 0x20>>2, 0x50>>2, 0x00>>2, 0x70>>2, 0x88>>2, 0xF8>>2, 0x80>>2, 0x70>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x50>>2, 0x00>>2, 0x70>>2, 0x88>>2, 0xF8>>2, 0x80>>2, 0x70>>2, 0x00>>2, 0x00>>2, }, { 0x40>>2, 0x20>>2, 0x00>>2, 0x60>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x70>>2, 0x00>>2, 0x00>>2, }, { 0x20>>2, 0x40>>2, 0x00>>2, 0x60>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x70>>2, 0x00>>2, 0x00>>2, }, { 0x20>>2, 0x50>>2, 0x00>>2, 0x60>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x70>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x50>>2, 0x00>>2, 0x60>>2, 0x20>>2, 0x20>>2, 0x20>>2, 0x70>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0xC0>>2, 0x30>>2, 0x70>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0x70>>2, 0x00>>2, 0x00>>2, }, { 0x28>>2, 0x50>>2, 0x00>>2, 0xB0>>2, 0xC8>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0x00>>2, 0x00>>2, }, { 0x40>>2, 0x20>>2, 0x00>>2, 0x70>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0x70>>2, 0x00>>2, 0x00>>2, }, { 0x10>>2, 0x20>>2, 0x00>>2, 0x70>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0x70>>2, 0x00>>2, 0x00>>2, }, { 0x20>>2, 0x50>>2, 0x00>>2, 0x70>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0x70>>2, 0x00>>2, 0x00>>2, }, { 0x28>>2, 0x50>>2, 0x00>>2, 0x70>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0x70>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x50>>2, 0x00>>2, 0x70>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0x70>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x00>>2, 0x20>>2, 0x00>>2, 0xF8>>2, 0x00>>2, 0x20>>2, 0x00>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x00>>2, 0x00>>2, 0x78>>2, 0x98>>2, 0xA8>>2, 0xC8>>2, 0xF0>>2, 0x00>>2, 0x00>>2, }, { 0x40>>2, 0x20>>2, 0x00>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0x98>>2, 0x68>>2, 0x00>>2, 0x00>>2, }, { 0x10>>2, 0x20>>2, 0x00>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0x98>>2, 0x68>>2, 0x00>>2, 0x00>>2, }, { 0x20>>2, 0x50>>2, 0x00>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0x98>>2, 0x68>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x50>>2, 0x00>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0x98>>2, 0x68>>2, 0x00>>2, 0x00>>2, }, { 0x00>>2, 0x10>>2, 0x20>>2, 0x88>>2, 0x88>>2, 0x98>>2, 0x68>>2, 0x08>>2, 0x88>>2, 0x70>>2, }, { 0x00>>2, 0x00>>2, 0x80>>2, 0xF0>>2, 0x88>>2, 0x88>>2, 0x88>>2, 0xF0>>2, 0x80>>2, 0x80>>2, }, { 0x00>>2, 0x50>>2, 0x00>>2, 0x88>>2, 0x88>>2, 0x98>>2, 0x68>>2, 0x08>>2, 0x88>>2, 0x70>>2, }, }; static gp2x_font gp2x_default_font; void (*gp2x_printfchar)(gp2x_font *f, unsigned char c); void gp2x_printfchar15(gp2x_font *f, unsigned char c) { unsigned short *dst=&((unsigned short*)sdlscreen->pixels)[f->x+f->y*(sdlscreen->pitch>>1)],w,h=f->h; //unsigned char *src=f->data[ (c%16)*f->w + (c/16)*f->h ]; unsigned char *src=&f->data[c*10]; if(f->solid) while(h--) { w=f->wmask; while(w) { if( *src & w ) *dst++=f->fg; else *dst++=f->bg; w>>=1; } src++; dst+=(sdlscreen->pitch>>1)-(f->w); } else while(h--) { w=f->wmask; while(w) { if( *src & w ) *dst=f->fg; dst++; w>>=1; } src++; dst+=(sdlscreen->pitch>>1)-(f->w); } } void gp2x_printf(gp2x_font *f, int x, int y, const char *format, ...) { char buffer[4096]; int c; gp2x_font *g=&gp2x_default_font; va_list args; va_start(args, format); vsprintf(buffer, format, args); if(f!=NULL) g=f; if(x<0) x=g->x; else g->x=x; if(y<0) y=g->y; else g->y=y; for(c=0;buffer[c];c++) { switch(buffer[c]) { case '\b': g->x=x;g->y=y; break; case '\n': g->y+=g->h; case '\r': g->x=x; break; default: gp2x_printfchar(g, (unsigned char)buffer[c]); g->x+=g->w; break; } } //gp2x_video_flip_single(); } void gp2x_printf_init(gp2x_font *f, int w, int h, void *data, int fg, int bg, int solid) { gp2x_printfchar=gp2x_printfchar15; f->x=f->y=0; f->wmask=1<<(w-1); f->w=w; f->h=h; f->data=(unsigned char *)data; f->fg=fg; f->bg=bg; f->solid=solid; } SDL_Surface* screen_real; void gp2x_init(int ticks_per_second, int bpp, int rate, int bits, int stereo, int hz, int solid_font) { SDL_Event e; #ifdef DEBUG fdbg = fopen("debug.txt", "a+"); fprintf(fdbg, "\n\n"); #endif SDL_Init(SDL_INIT_VIDEO | SDL_INIT_JOYSTICK | SDL_INIT_AUDIO | SDL_INIT_NOPARACHUTE); #ifdef RENDER_DOUBLE screen_real = SDL_SetVideoMode(640, 480, 16, SDL_DOUBLEBUF); gp2x_sdlwrapper_screen = SDL_CreateRGBSurface(0, 320, 240, 16, screen_real->format->Rmask, screen_real->format->Gmask, screen_real->format->Bmask, screen_real->format->Amask); if(SDL_MUSTLOCK(screen_real)) SDL_LockSurface(screen_real); #else gp2x_sdlwrapper_screen = SDL_SetVideoMode(320, 240, 16, SDL_DOUBLEBUF); #endif if(SDL_MUSTLOCK(sdlscreen)) SDL_LockSurface(sdlscreen); SDL_WM_SetCaption("psx4all - SDL Version", "psx4all"); if(gp2x_sdlwrapper_screen == NULL) { exit(0); return; } gp2x_sdlwrapper_bpp=bpp; gp2x_sdlwrapper_screen_pixels=gp2x_sdlwrapper_screen->pixels; /*SDL_EventState(SDL_ACTIVEEVENT,SDL_IGNORE); SDL_EventState(SDL_MOUSEMOTION,SDL_IGNORE); SDL_EventState(SDL_MOUSEBUTTONDOWN,SDL_IGNORE); SDL_EventState(SDL_MOUSEBUTTONUP,SDL_IGNORE); SDL_EventState(SDL_SYSWMEVENT,SDL_IGNORE); SDL_EventState(SDL_VIDEORESIZE,SDL_IGNORE); SDL_EventState(SDL_USEREVENT,SDL_IGNORE); SDL_ShowCursor(SDL_DISABLE);*/ //init font gp2x_printf_init(&gp2x_default_font,6,10,gp2x_fontf,0xFFFF,0x0000,solid_font); atexit(gp2x_deinit); } void gp2x_change_res(int w, int h) { gp2x_sdlwrapper_screen = SDL_SetVideoMode(w, h, 16, SDL_HWSURFACE); /*SDL_EventState(SDL_ACTIVEEVENT,SDL_IGNORE); SDL_EventState(SDL_MOUSEMOTION,SDL_IGNORE); SDL_EventState(SDL_MOUSEBUTTONDOWN,SDL_IGNORE); SDL_EventState(SDL_MOUSEBUTTONUP,SDL_IGNORE); SDL_EventState(SDL_SYSWMEVENT,SDL_IGNORE); SDL_EventState(SDL_VIDEORESIZE,SDL_IGNORE); SDL_EventState(SDL_USEREVENT,SDL_IGNORE); SDL_ShowCursor(SDL_DISABLE);*/ } void gp2x_deinit(void) { SDL_Quit(); #ifdef DEBUG fclose(fdbg); #endif } unsigned long keystate = 0; unsigned long gp2x_joystick_read(void) { //events SDL_Event event; unsigned long ret = keystate; while(SDL_PollEvent(&event)) { switch(event.type) { case SDL_QUIT: gp2x_deinit(); exit(0); break; case SDL_KEYDOWN: switch(event.key.keysym.sym) { case SDLK_ESCAPE: gp2x_deinit(); exit(0); break; case SDLK_UP: ret |= GP2X_UP; break; case SDLK_DOWN: ret |= GP2X_DOWN; break; case SDLK_LEFT: ret |= GP2X_LEFT; break; case SDLK_RIGHT: ret |= GP2X_RIGHT; break; case SDLK_a: ret |= GP2X_A; break; case SDLK_x: ret |= GP2X_B; break; case SDLK_s: ret |= GP2X_Y; break; case SDLK_z: ret |= GP2X_X; break; case SDLK_w: ret |= GP2X_L; break; case SDLK_q: ret |= GP2X_VOL_DOWN; break; case SDLK_e: ret |= GP2X_R; break; case SDLK_r: ret |= GP2X_VOL_UP; break; case SDLK_RETURN: ret |= GP2X_START; break; case SDLK_BACKSPACE: ret |= GP2X_SELECT; break; default: break; } break; case SDL_KEYUP: switch(event.key.keysym.sym) { case SDLK_UP: ret &= ~GP2X_UP; break; case SDLK_DOWN: ret &= ~GP2X_DOWN; break; case SDLK_LEFT: ret &= ~GP2X_LEFT; break; case SDLK_RIGHT: ret &= ~GP2X_RIGHT; break; case SDLK_a: ret &= ~GP2X_A; break; case SDLK_x: ret &= ~GP2X_B; break; case SDLK_s: ret &= ~GP2X_Y; break; case SDLK_z: ret &= ~GP2X_X; break; case SDLK_w: ret &= ~GP2X_L; break; case SDLK_q: ret &= ~GP2X_VOL_DOWN; break; case SDLK_e: ret &= ~GP2X_R; break; case SDLK_r: ret &= ~GP2X_VOL_UP; break; case SDLK_RETURN: ret |= GP2X_START; break; case SDLK_BACKSPACE: ret |= GP2X_SELECT; break; default: break; } break; default: break; } } keystate = ret; return ret; } void gp2x_video_RGB_clearscreen16(void) { memset(sdlscreen->pixels, 0, sdlscreen->pitch*sdlscreen->h); } void gp2x_timer_delay(unsigned long ticks) { SDL_Delay(ticks); } void gp2x_timer_delay_raw(unsigned long raws) { // } unsigned long gp2x_timer_read(void) { // } unsigned long gp2x_timer_raw(void) { // } void gp2x_video_flip() { #ifdef RENDER_DOUBLE int i, j; for(i=0; i<240; i++) { for(j=0; j<320; j++) { ((Uint16*)screen_real->pixels)[640*i*2 + 2*j] = ((Uint16*)screen_real->pixels)[640*i*2 + 2*j + 1] = ((Uint16*)screen_real->pixels)[640*(i*2+1) + 2*j] = ((Uint16*)screen_real->pixels)[640*(i*2+1) + 2*j + 1] = ((Uint16*)sdlscreen->pixels)[320*i + j]; } } if(SDL_MUSTLOCK(sdlscreen)) SDL_UnlockSurface(sdlscreen); if(SDL_MUSTLOCK(screen_real)) SDL_UnlockSurface(screen_real); SDL_Flip(screen_real); if(SDL_MUSTLOCK(screen_real)) SDL_LockSurface(screen_real); #else if(SDL_MUSTLOCK(sdlscreen)) SDL_UnlockSurface(sdlscreen); SDL_Flip(sdlscreen); #endif if(SDL_MUSTLOCK(sdlscreen)) SDL_LockSurface(sdlscreen); }
[ [ [ 1, 586 ] ] ]
9e86acebd1d13e8cc6955505fee22f9b39537cb4
fd3f2268460656e395652b11ae1a5b358bfe0a59
/srchybrid/MediaInfo.cpp
3ee72a534b66eab20d5a4d1d0835e2e9af5c146f
[]
no_license
mikezhoubill/emule-gifc
e1cc6ff8b1bb63197bcfc7e67c57cfce0538ff60
46979cf32a313ad6d58603b275ec0b2150562166
refs/heads/master
2021-01-10T20:37:07.581465
2011-08-13T13:58:37
2011-08-13T13:58:37
32,465,033
4
2
null
null
null
null
UTF-8
C++
false
false
115,517
cpp
//this file is part of eMule //Copyright (C)2002-2008 Merkur ( strEmail.Format("%s@%s", "devteam", "emule-project.net") / http://www.emule-project.net ) // //This program is free software; you can redistribute it and/or //modify it under the terms of the GNU General Public License //as published by the Free Software Foundation; either //version 2 of the License, or (at your option) any later version. // //This program is distributed in the hope that it will be useful, //but WITHOUT ANY WARRANTY; without even the implied warranty of //MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //GNU General Public License for more details. // //You should have received a copy of the GNU General Public License //along with this program; if not, write to the Free Software //Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. #include "stdafx.h" #include "resource.h" #include "OtherFunctions.h" #include "MediaInfo.h" #include "SafeFile.h" #include <io.h> #include <fcntl.h> #ifdef HAVE_WMSDK_H #include <wmsdk.h> #if !defined(HAVE_VISTA_SDK) static const WCHAR g_wszWMPeakBitrate[] = L"WM/PeakBitrate"; static const WCHAR g_wszWMStreamTypeInfo[] = L"WM/StreamTypeInfo"; typedef struct { GUID guidMajorType; DWORD cbFormat; } WM_STREAM_TYPE_INFO; #endif #endif//HAVE_WMSDK_H #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif CStringStream& CStringStream::operator<<(LPCTSTR psz) { str += psz; return *this; } CStringStream& CStringStream::operator<<(char* psz) { str += psz; return *this; } CStringStream& CStringStream::operator<<(UINT uVal) { CString strVal; strVal.Format(_T("%u"), uVal); str += strVal; return *this; } CStringStream& CStringStream::operator<<(int iVal) { CString strVal; strVal.Format(_T("%d"), iVal); str += strVal; return *this; } CStringStream& CStringStream::operator<<(double fVal) { CString strVal; strVal.Format(_T("%.3f"), fVal); str += strVal; return *this; } const static struct { UINT uFmtTag; LPCTSTR pszDefine; LPCTSTR pszComment; } s_WavFmtTag[] = { // START: Codecs from Windows SDK "mmreg.h" file { 0x0000, _T(""), _T("Unknown") }, { 0x0001, _T("PCM"), _T("Uncompressed") }, { 0x0002, _T("ADPCM"), _T("") }, { 0x0003, _T("IEEE_FLOAT"), _T("") }, { 0x0004, _T("VSELP"), _T("Compaq Computer Corp.") }, { 0x0005, _T("IBM_CVSD"), _T("") }, { 0x0006, _T("ALAW"), _T("") }, { 0x0007, _T("MULAW"), _T("") }, { 0x0008, _T("DTS"), _T("Digital Theater Systems") }, { 0x0009, _T("DRM"), _T("") }, { 0x000A, _T("WMAVOICE9"), _T("") }, { 0x000B, _T("WMAVOICE10"), _T("") }, { 0x0010, _T("OKI_ADPCM"), _T("") }, { 0x0011, _T("DVI_ADPCM"), _T("Intel Corporation") }, { 0x0012, _T("MEDIASPACE_ADPCM"), _T("Videologic") }, { 0x0013, _T("SIERRA_ADPCM"), _T("") }, { 0x0014, _T("G723_ADPCM"), _T("Antex Electronics Corporation") }, { 0x0015, _T("DIGISTD"), _T("DSP Solutions, Inc.") }, { 0x0016, _T("DIGIFIX"), _T("DSP Solutions, Inc.") }, { 0x0017, _T("DIALOGIC_OKI_ADPCM"), _T("") }, { 0x0018, _T("MEDIAVISION_ADPCM"), _T("") }, { 0x0019, _T("CU_CODEC"), _T("Hewlett-Packard Company") }, { 0x0020, _T("YAMAHA_ADPCM"), _T("") }, { 0x0021, _T("SONARC"), _T("Speech Compression") }, { 0x0022, _T("DSPGROUP_TRUESPEECH"), _T("") }, { 0x0023, _T("ECHOSC1"), _T("Echo Speech Corporation") }, { 0x0024, _T("AUDIOFILE_AF36"), _T("Virtual Music, Inc.") }, { 0x0025, _T("APTX"), _T("Audio Processing Technology") }, { 0x0026, _T("AUDIOFILE_AF10"), _T("Virtual Music, Inc.") }, { 0x0027, _T("PROSODY_1612"), _T("Aculab plc") }, { 0x0028, _T("LRC"), _T("Merging Technologies S.A.") }, { 0x0030, _T("DOLBY_AC2"), _T("") }, { 0x0031, _T("GSM610"), _T("") }, { 0x0032, _T("MSNAUDIO"), _T("") }, { 0x0033, _T("ANTEX_ADPCME"), _T("") }, { 0x0034, _T("CONTROL_RES_VQLPC"), _T("") }, { 0x0035, _T("DIGIREAL"), _T("DSP Solutions, Inc.") }, { 0x0036, _T("DIGIADPCM"), _T("DSP Solutions, Inc.") }, { 0x0037, _T("CONTROL_RES_CR10"), _T("") }, { 0x0038, _T("NMS_VBXADPCM"), _T("Natural MicroSystems") }, { 0x0039, _T("CS_IMAADPCM"), _T("Crystal Semiconductor IMA ADPCM") }, { 0x003A, _T("ECHOSC3"), _T("Echo Speech Corporation") }, { 0x003B, _T("ROCKWELL_ADPCM"), _T("") }, { 0x003C, _T("ROCKWELL_DIGITALK"), _T("") }, { 0x003D, _T("XEBEC"), _T("") }, { 0x0040, _T("G721_ADPCM"), _T("Antex Electronics Corporation") }, { 0x0041, _T("G728_CELP"), _T("Antex Electronics Corporation") }, { 0x0042, _T("MSG723"), _T("") }, { 0x0050, _T("MP1"), _T("MPEG-1, Layer 1") }, { 0x0051, _T("MP2"), _T("MPEG-1, Layer 2") }, { 0x0052, _T("RT24"), _T("InSoft, Inc.") }, { 0x0053, _T("PAC"), _T("InSoft, Inc.") }, { 0x0055, _T("MP3"), _T("MPEG-1, Layer 3") }, { 0x0059, _T("LUCENT_G723"), _T("") }, { 0x0060, _T("CIRRUS"), _T("") }, { 0x0061, _T("ESPCM"), _T("ESS Technology") }, { 0x0062, _T("VOXWARE"), _T("") }, { 0x0063, _T("CANOPUS_ATRAC"), _T("") }, { 0x0064, _T("G726_ADPCM"), _T("APICOM") }, { 0x0065, _T("G722_ADPCM"), _T("APICOM") }, { 0x0067, _T("DSAT_DISPLAY"), _T("") }, { 0x0069, _T("VOXWARE_BYTE_ALIGNED"), _T("") }, { 0x0070, _T("VOXWARE_AC8"), _T("") }, { 0x0071, _T("VOXWARE_AC10"), _T("") }, { 0x0072, _T("VOXWARE_AC16"), _T("") }, { 0x0073, _T("VOXWARE_AC20"), _T("") }, { 0x0074, _T("VOXWARE_RT24"), _T("") }, { 0x0075, _T("VOXWARE_RT29"), _T("") }, { 0x0076, _T("VOXWARE_RT29HW"), _T("") }, { 0x0077, _T("VOXWARE_VR12"), _T("") }, { 0x0078, _T("VOXWARE_VR18"), _T("") }, { 0x0079, _T("VOXWARE_TQ40"), _T("") }, { 0x0080, _T("SOFTSOUND"), _T("") }, { 0x0081, _T("VOXWARE_TQ60"), _T("") }, { 0x0082, _T("MSRT24"), _T("") }, { 0x0083, _T("G729A"), _T("AT&T Labs, Inc.") }, { 0x0084, _T("MVI_MVI2"), _T("Motion Pixels") }, { 0x0085, _T("DF_G726"), _T("DataFusion Systems (Pty) (Ltd)") }, { 0x0086, _T("DF_GSM610"), _T("DataFusion Systems (Pty) (Ltd)") }, { 0x0088, _T("ISIAUDIO"), _T("Iterated Systems, Inc.") }, { 0x0089, _T("ONLIVE"), _T("") }, { 0x0091, _T("SBC24"), _T("Siemens Business Communications Sys") }, { 0x0092, _T("DOLBY_AC3_SPDIF"), _T("Sonic Foundry") }, { 0x0093, _T("MEDIASONIC_G723"), _T("") }, { 0x0094, _T("PROSODY_8KBPS"), _T("Aculab plc") }, { 0x0097, _T("ZYXEL_ADPCM"), _T("") }, { 0x0098, _T("PHILIPS_LPCBB"), _T("") }, { 0x0099, _T("PACKED"), _T("Studer Professional Audio AG") }, { 0x00A0, _T("MALDEN_PHONYTALK"), _T("") }, { 0x0100, _T("RHETOREX_ADPCM"), _T("") }, { 0x0101, _T("IRAT"), _T("BeCubed Software Inc.") }, { 0x0111, _T("VIVO_G723"), _T("") }, { 0x0112, _T("VIVO_SIREN"), _T("") }, { 0x0123, _T("DIGITAL_G723"), _T("Digital Equipment Corporation") }, { 0x0125, _T("SANYO_LD_ADPCM"), _T("") }, { 0x0130, _T("SIPROLAB_ACEPLNET"), _T("") }, { 0x0130, _T("SIPR"), _T("Real Audio 4 (Sipro)") }, { 0x0131, _T("SIPROLAB_ACELP4800"), _T("") }, { 0x0132, _T("SIPROLAB_ACELP8V3"), _T("") }, { 0x0133, _T("SIPROLAB_G729"), _T("") }, { 0x0134, _T("SIPROLAB_G729A"), _T("") }, { 0x0135, _T("SIPROLAB_KELVIN"), _T("") }, { 0x0140, _T("G726ADPCM"), _T("Dictaphone Corporation") }, { 0x0150, _T("QUALCOMM_PUREVOICE"), _T("") }, { 0x0151, _T("QUALCOMM_HALFRATE"), _T("") }, { 0x0155, _T("TUBGSM"), _T("Ring Zero Systems, Inc.") }, { 0x0160, _T("MSAUDIO1"), _T("Microsoft Audio") }, { 0x0161, _T("WMAUDIO2"), _T("Windows Media Audio") }, { 0x0162, _T("WMAUDIO3"), _T("Windows Media Audio 9 Pro") }, { 0x0163, _T("WMAUDIO_LOSSLESS"), _T("Windows Media Audio 9 Lossless") }, { 0x0164, _T("WMASPDIF"), _T("Windows Media Audio Pro-over-S/PDIF") }, { 0x0170, _T("UNISYS_NAP_ADPCM"), _T("") }, { 0x0171, _T("UNISYS_NAP_ULAW"), _T("") }, { 0x0172, _T("UNISYS_NAP_ALAW"), _T("") }, { 0x0173, _T("UNISYS_NAP_16K"), _T("") }, { 0x0200, _T("CREATIVE_ADPCM"), _T("") }, { 0x0202, _T("CREATIVE_FASTSPEECH8"), _T("") }, { 0x0203, _T("CREATIVE_FASTSPEECH10"), _T("") }, { 0x0210, _T("UHER_ADPCM"), _T("") }, { 0x0220, _T("QUARTERDECK"), _T("") }, { 0x0230, _T("ILINK_VC"), _T("I-link Worldwide") }, { 0x0240, _T("RAW_SPORT"), _T("Aureal Semiconductor") }, { 0x0241, _T("ESST_AC3"), _T("ESS Technology, Inc.") }, { 0x0250, _T("IPI_HSX"), _T("Interactive Products, Inc.") }, { 0x0251, _T("IPI_RPELP"), _T("Interactive Products, Inc.") }, { 0x0260, _T("CS2"), _T("Consistent Software") }, { 0x0270, _T("SONY_SCX"), _T("") }, { 0x0300, _T("FM_TOWNS_SND"), _T("Fujitsu Corp.") }, { 0x0400, _T("BTV_DIGITAL"), _T("Brooktree Corporation") }, { 0x0401, _T("IMC"), _T("Intel Music Coder for MSACM") }, { 0x0450, _T("QDESIGN_MUSIC"), _T("") }, { 0x0680, _T("VME_VMPCM"), _T("AT&T Labs, Inc.") }, { 0x0681, _T("TPC"), _T("AT&T Labs, Inc.") }, { 0x1000, _T("OLIGSM"), _T("Olivetti") }, { 0x1001, _T("OLIADPCM"), _T("Olivetti") }, { 0x1002, _T("OLICELP"), _T("Olivetti") }, { 0x1003, _T("OLISBC"), _T("Olivetti") }, { 0x1004, _T("OLIOPR"), _T("Olivetti") }, { 0x1100, _T("LH_CODEC"), _T("Lernout & Hauspie") }, { 0x1400, _T("NORRIS"), _T("") }, { 0x1500, _T("SOUNDSPACE_MUSICOMPRESS"),_T("AT&T Labs, Inc.") }, { 0x1600, _T("MPEG_ADTS_AAC"), _T("") }, { 0x1601, _T("MPEG_RAW_AAC"), _T("") }, { 0x1608, _T("NOKIA_MPEG_ADTS_AAC"), _T("") }, { 0x1609, _T("NOKIA_MPEG_RAW_AAC"), _T("") }, { 0x160A, _T("VODAFONE_MPEG_ADTS_AAC"), _T("") }, { 0x160B, _T("VODAFONE_MPEG_RAW_AAC"), _T("") }, { 0x2000, _T("AC3"), _T("Dolby AC3") }, // END: Codecs from Windows SDK "mmreg.h" file { 0x2001, _T("DTS"), _T("Digital Theater Systems") }, // Real Audio (Baked) codecs { 0x2002, _T("RA14"), _T("RealAudio 1/2 14.4") }, { 0x2003, _T("RA28"), _T("RealAudio 1/2 28.8") }, { 0x2004, _T("COOK"), _T("RealAudio G2/8 Cook (Low Bitrate)") }, { 0x2005, _T("DNET"), _T("RealAudio 3/4/5 Music (DNET)") }, { 0x2006, _T("RAAC"), _T("RealAudio 10 AAC (RAAC)") }, { 0x2007, _T("RACP"), _T("RealAudio 10 AAC+ (RACP)") } }; CString GetAudioFormatName(WORD wFormatTag, CString& rstrComment) { for (int i = 0; i < _countof(s_WavFmtTag); i++) { if (s_WavFmtTag[i].uFmtTag == wFormatTag){ rstrComment = s_WavFmtTag[i].pszComment; return CString(s_WavFmtTag[i].pszDefine); } } CString strCompression; strCompression.Format(_T("0x%04x (Unknown)"), wFormatTag); return strCompression; } CString GetAudioFormatName(WORD wFormatTag) { CString strComment; CString strFormat = GetAudioFormatName(wFormatTag, strComment); if (!strComment.IsEmpty()) strFormat += _T(" (") + strComment + _T(")"); return strFormat; } CString GetAudioFormatCodecId(WORD wFormatTag) { for (int i = 0; i < _countof(s_WavFmtTag); i++) { if (s_WavFmtTag[i].uFmtTag == wFormatTag) return s_WavFmtTag[i].pszDefine; } return _T(""); } CString GetAudioFormatDisplayName(const CString &strCodecId) { for (int i = 0; i < _countof(s_WavFmtTag); i++) { if (_tcsicmp(s_WavFmtTag[i].pszDefine, strCodecId) == 0) { if (s_WavFmtTag[i].uFmtTag == 0) break; if (s_WavFmtTag[i].pszDefine[0] == _T('\0') || s_WavFmtTag[i].pszComment[0] == _T('\0')) break; return CString(s_WavFmtTag[i].pszDefine) + _T(" (") + CString(s_WavFmtTag[i].pszComment) + _T(")"); } } return _T(""); } BOOL IsEqualFOURCC(FOURCC fccA, FOURCC fccB) { for (int i = 0; i < 4; i++) { if (tolower((unsigned char)fccA) != tolower((unsigned char)fccB)) return FALSE; fccA >>= 8; fccB >>= 8; } return TRUE; } CString GetVideoFormatDisplayName(DWORD biCompression) { CString strFormat; if (biCompression == BI_RGB) strFormat = _T("RGB (Uncompressed)"); else if (biCompression == BI_RLE8) strFormat = _T("RLE8 (Run Length Encoded 8-bit)"); else if (biCompression == BI_RLE4) strFormat = _T("RLE4 (Run Length Encoded 4-bit)"); else if (biCompression == BI_BITFIELDS) strFormat = _T("Bitfields"); else if (biCompression == BI_JPEG) strFormat = _T("JPEG"); else if (biCompression == BI_PNG) strFormat = _T("PNG"); else if (IsEqualFOURCC(biCompression, MAKEFOURCC('D','I','V','3'))) strFormat = CStringA((LPCSTR)&biCompression, 4) + " (DivX ;-) MPEG-4 v3 Low)"; else if (IsEqualFOURCC(biCompression, MAKEFOURCC('D','I','V','4'))) strFormat = CStringA((LPCSTR)&biCompression, 4) + " (DivX ;-) MPEG-4 v3 Fast)"; else if (IsEqualFOURCC(biCompression, MAKEFOURCC('D','I','V','X'))) strFormat = CStringA((LPCSTR)&biCompression, 4) + " (DivX 4)"; else if (IsEqualFOURCC(biCompression, MAKEFOURCC('D','X','5','0'))) strFormat = CStringA((LPCSTR)&biCompression, 4) + " (DivX 5)"; else if (IsEqualFOURCC(biCompression, MAKEFOURCC('M','P','G','4'))) strFormat = CStringA((LPCSTR)&biCompression, 4) + " (Microsoft MPEG-4 v1)"; else if (IsEqualFOURCC(biCompression, MAKEFOURCC('M','P','4','2'))) strFormat = CStringA((LPCSTR)&biCompression, 4) + " (Microsoft MPEG-4 v2)"; else if (IsEqualFOURCC(biCompression, MAKEFOURCC('M','P','4','3'))) strFormat = CStringA((LPCSTR)&biCompression, 4) + " (Microsoft MPEG-4 v3)"; else if (IsEqualFOURCC(biCompression, MAKEFOURCC('D','X','S','B'))) strFormat = CStringA((LPCSTR)&biCompression, 4) + " (Subtitle)"; else if (IsEqualFOURCC(biCompression, MAKEFOURCC('W','M','V','1'))) strFormat = CStringA((LPCSTR)&biCompression, 4) + " (Windows Media Video 7)"; else if (IsEqualFOURCC(biCompression, MAKEFOURCC('W','M','V','2'))) strFormat = CStringA((LPCSTR)&biCompression, 4) + " (Windows Media Video 8)"; else if (IsEqualFOURCC(biCompression, MAKEFOURCC('W','M','V','3'))) strFormat = CStringA((LPCSTR)&biCompression, 4) + " (Windows Media Video 9)"; else if (IsEqualFOURCC(biCompression, MAKEFOURCC('W','M','V','A'))) strFormat = CStringA((LPCSTR)&biCompression, 4) + " (Windows Media Video 9 Advanced Profile)"; else if (IsEqualFOURCC(biCompression, MAKEFOURCC('R','V','1','0'))) strFormat = CStringA((LPCSTR)&biCompression, 4) + " (Real Video 5)"; else if (IsEqualFOURCC(biCompression, MAKEFOURCC('R','V','1','3'))) strFormat = CStringA((LPCSTR)&biCompression, 4) + " (Real Video 5)"; else if (IsEqualFOURCC(biCompression, MAKEFOURCC('R','V','2','0'))) strFormat = CStringA((LPCSTR)&biCompression, 4) + " (Real Video G2)"; else if (IsEqualFOURCC(biCompression, MAKEFOURCC('R','V','3','0'))) strFormat = CStringA((LPCSTR)&biCompression, 4) + " (Real Video 8)"; else if (IsEqualFOURCC(biCompression, MAKEFOURCC('R','V','4','0'))) strFormat = CStringA((LPCSTR)&biCompression, 4) + " (Real Video 9)"; else if (IsEqualFOURCC(biCompression, MAKEFOURCC('H','2','6','4'))) strFormat = CStringA((LPCSTR)&biCompression, 4) + " (MPEG-4 AVC)"; else if (IsEqualFOURCC(biCompression, MAKEFOURCC('X','2','6','4'))) strFormat = CStringA((LPCSTR)&biCompression, 4) + " (x264 MPEG-4 AVC)"; else if (IsEqualFOURCC(biCompression, MAKEFOURCC('X','V','I','D'))) strFormat = CStringA((LPCSTR)&biCompression, 4) + " (Xvid MPEG-4)"; else if (IsEqualFOURCC(biCompression, MAKEFOURCC('T','S','C','C'))) strFormat = CStringA((LPCSTR)&biCompression, 4) + " (TechSmith Screen Capture)"; else if (IsEqualFOURCC(biCompression, MAKEFOURCC('M','J','P','G'))) strFormat = CStringA((LPCSTR)&biCompression, 4) + " (M-JPEG)"; else if (IsEqualFOURCC(biCompression, MAKEFOURCC('I','V','3','2'))) strFormat = CStringA((LPCSTR)&biCompression, 4) + " (Intel Indeo Video 3.2)"; else if (IsEqualFOURCC(biCompression, MAKEFOURCC('I','V','4','0'))) strFormat = CStringA((LPCSTR)&biCompression, 4) + " (Intel Indeo Video 4.0)"; else if (IsEqualFOURCC(biCompression, MAKEFOURCC('I','V','5','0'))) strFormat = CStringA((LPCSTR)&biCompression, 4) + " (Intel Indeo Video 5.0)"; else if (IsEqualFOURCC(biCompression, MAKEFOURCC('F','M','P','4'))) strFormat = CStringA((LPCSTR)&biCompression, 4) + " (MPEG-4)"; else if (IsEqualFOURCC(biCompression, MAKEFOURCC('C','V','I','D'))) strFormat = CStringA((LPCSTR)&biCompression, 4) + " (Cinepack)"; else if (IsEqualFOURCC(biCompression, MAKEFOURCC('C','R','A','M'))) strFormat = CStringA((LPCSTR)&biCompression, 4) + " (Microsoft Video 1)"; // X-Ray :: MoreFourCCCodes :: Start - added by zz_fly else if (IsEqualFOURCC(biCompression, MAKEFOURCC('A','V','C','1')) || IsEqualFOURCC(biCompression, MAKEFOURCC('D','A','V','C')) || IsEqualFOURCC(biCompression, MAKEFOURCC('V','S','S','H')) || IsEqualFOURCC(biCompression, MAKEFOURCC('V','S','S','W'))) strFormat = CStringA((LPCSTR)&biCompression, 4) + " (H.264/MPEG-4 AVC)"; else if (IsEqualFOURCC(biCompression, MAKEFOURCC('3','I','V','0')) || IsEqualFOURCC(biCompression, MAKEFOURCC('3','I','V','1')) || IsEqualFOURCC(biCompression, MAKEFOURCC('3','I','V','2')) || IsEqualFOURCC(biCompression, MAKEFOURCC('3','I','V','D')) || IsEqualFOURCC(biCompression, MAKEFOURCC('3','I','V','X')) || IsEqualFOURCC(biCompression, MAKEFOURCC('3','V','I','D'))) strFormat = CStringA((LPCSTR)&biCompression, 4) + " (3ivX)"; // X-Ray :: MoreFourCCCodes :: End return strFormat; } CString GetVideoFormatName(DWORD biCompression) { CString strFormat(GetVideoFormatDisplayName(biCompression)); if (strFormat.IsEmpty()) { char szFourcc[5]; *(LPDWORD)szFourcc = biCompression; szFourcc[4] = '\0'; strFormat = szFourcc; strFormat.MakeUpper(); } return strFormat; } CString GetKnownAspectRatioDisplayString(float fAspectRatio) { CString strAspectRatio; if (fAspectRatio >= 1.00F && fAspectRatio < 1.50F) strAspectRatio = _T("4/3"); else if (fAspectRatio >= 1.50F && fAspectRatio < 2.00F) strAspectRatio = _T("16/9"); else if (fAspectRatio >= 2.00F && fAspectRatio < 2.22F) strAspectRatio = _T("2.2"); else if (fAspectRatio >= 2.22F && fAspectRatio < 2.30F) strAspectRatio = _T("2.25"); else if (fAspectRatio >= 2.30F && fAspectRatio < 2.50F) strAspectRatio = _T("2.35"); return strAspectRatio; } CString GetCodecDisplayName(const CString &strCodecId) { static CMapStringToString s_mapCodecDisplayName; CString strCodecDisplayName; if (s_mapCodecDisplayName.Lookup(strCodecId, strCodecDisplayName)) return strCodecDisplayName; if (strCodecId.GetLength() == 3 || strCodecId.GetLength() == 4) { bool bHaveFourCC = true; FOURCC fcc; if (strCodecId == L"rgb") fcc = BI_RGB; else if (strCodecId == L"rle8") fcc = BI_RLE8; else if (strCodecId == L"rle4") fcc = BI_RLE4; else if (strCodecId == L"jpeg") fcc = BI_JPEG; else if (strCodecId == L"png") fcc = BI_PNG; else { fcc = MAKEFOURCC(' ',' ',' ',' '); LPSTR pcFourCC = (LPSTR)&fcc; for (int i = 0; i < strCodecId.GetLength(); i++) { WCHAR wch = strCodecId[i]; if (wch >= 0x100 || (!__iscsym((unsigned char)wch) && wch != L'.' && wch != L' ')) { bHaveFourCC = false; break; } pcFourCC[i] = (CHAR)toupper((unsigned char)wch); } } if (bHaveFourCC) strCodecDisplayName = GetVideoFormatDisplayName(fcc); } if (strCodecDisplayName.IsEmpty()) strCodecDisplayName = GetAudioFormatDisplayName(strCodecId); if (strCodecDisplayName.IsEmpty()) { strCodecDisplayName = strCodecId; strCodecDisplayName.MakeUpper(); } s_mapCodecDisplayName.SetAt(strCodecId, strCodecDisplayName); return strCodecDisplayName; } typedef struct { SHORT left; SHORT top; SHORT right; SHORT bottom; } RECT16; typedef struct { FOURCC fccType; FOURCC fccHandler; DWORD dwFlags; WORD wPriority; WORD wLanguage; DWORD dwInitialFrames; DWORD dwScale; DWORD dwRate; DWORD dwStart; DWORD dwLength; DWORD dwSuggestedBufferSize; DWORD dwQuality; DWORD dwSampleSize; RECT16 rcFrame; } AVIStreamHeader_fixed; #ifndef AVIFILEINFO_NOPADDING #define AVIFILEINFO_NOPADDING 0x0400 // from the SDK tool "RIFFWALK.EXE" #endif #ifndef AVIFILEINFO_TRUSTCKTYPE #define AVIFILEINFO_TRUSTCKTYPE 0x0800 // from DirectX SDK "Types of DV AVI Files" #endif typedef struct { AVIStreamHeader_fixed hdr; DWORD dwFormatLen; union { BITMAPINFOHEADER* bmi; PCMWAVEFORMAT* wav; LPBYTE dat; } fmt; char* nam; } STREAMHEADER; static BOOL ReadChunkHeader(int fd, FOURCC *pfccType, DWORD *pdwLength) { if (_read(fd, pfccType, sizeof(*pfccType)) != sizeof(*pfccType)) return FALSE; if (_read(fd, pdwLength, sizeof(*pdwLength)) != sizeof(*pdwLength)) return FALSE; return TRUE; } static BOOL ParseStreamHeader(int hAviFile, DWORD dwLengthLeft, STREAMHEADER* pStrmHdr) { FOURCC fccType; DWORD dwLength; while (dwLengthLeft >= sizeof(DWORD)*2) { if (!ReadChunkHeader(hAviFile, &fccType, &dwLength)) return FALSE; dwLengthLeft -= sizeof(DWORD)*2; if (dwLength > dwLengthLeft) { errno = 0; return FALSE; } dwLengthLeft -= dwLength + (dwLength & 1); switch (fccType) { case ckidSTREAMHEADER: if (dwLength < sizeof(pStrmHdr->hdr)) { memset(&pStrmHdr->hdr, 0x00, sizeof(pStrmHdr->hdr)); if (_read(hAviFile, &pStrmHdr->hdr, dwLength) != (int)dwLength) return FALSE; if (dwLength & 1) { if (_lseek(hAviFile, 1, SEEK_CUR) == -1) return FALSE; } } else { if (_read(hAviFile, &pStrmHdr->hdr, sizeof(pStrmHdr->hdr)) != sizeof(pStrmHdr->hdr)) return FALSE; if (_lseek(hAviFile, dwLength + (dwLength & 1) - sizeof(pStrmHdr->hdr), SEEK_CUR) == -1) return FALSE; } dwLength = 0; break; case ckidSTREAMFORMAT: if (dwLength > 4096) // expect corrupt data return FALSE; if ((pStrmHdr->fmt.dat = new BYTE[pStrmHdr->dwFormatLen = dwLength]) == NULL) { errno = ENOMEM; return FALSE; } if (_read(hAviFile, pStrmHdr->fmt.dat, dwLength) != (int)dwLength) return FALSE; if (dwLength & 1) { if (_lseek(hAviFile, 1, SEEK_CUR) == -1) return FALSE; } dwLength = 0; break; case ckidSTREAMNAME: if (dwLength > 512) // expect corrupt data return FALSE; if ((pStrmHdr->nam = new char[dwLength + 1]) == NULL) { errno = ENOMEM; return FALSE; } if (_read(hAviFile, pStrmHdr->nam, dwLength) != (int)dwLength) return FALSE; pStrmHdr->nam[dwLength] = '\0'; if (dwLength & 1) { if (_lseek(hAviFile, 1, SEEK_CUR) == -1) return FALSE; } dwLength = 0; break; } if (dwLength) { if (_lseek(hAviFile, dwLength + (dwLength & 1), SEEK_CUR) == -1) return FALSE; } } if (dwLengthLeft) { if (_lseek(hAviFile, dwLengthLeft, SEEK_CUR) == -1) return FALSE; } return TRUE; } BOOL GetRIFFHeaders(LPCTSTR pszFileName, SMediaInfo* mi, bool& rbIsAVI, bool bFullInfo) { ASSERT( !bFullInfo || mi->strInfo.m_hWnd != NULL ); BOOL bResult = FALSE; // Open AVI file int hAviFile = _topen(pszFileName, O_RDONLY | O_BINARY); if (hAviFile == -1) return FALSE; DWORD dwLengthLeft; FOURCC fccType; DWORD dwLength; BOOL bSizeInvalid = FALSE; int iStream = 0; DWORD dwMovieChunkSize = 0; DWORD uVideoFrames = 0; int iNonAVStreams = 0; DWORD dwAllNonVideoAvgBytesPerSec = 0; // // Read 'RIFF' header // if (!ReadChunkHeader(hAviFile, &fccType, &dwLength)) goto cleanup; if (fccType != FOURCC_RIFF) goto cleanup; if (dwLength < sizeof(DWORD)) { dwLength = 0xFFFFFFF0; bSizeInvalid = TRUE; } dwLengthLeft = dwLength -= sizeof(DWORD); // // Read 'AVI ' or 'WAVE' header // FOURCC fccMain; if (_read(hAviFile, &fccMain, sizeof(fccMain)) != sizeof(fccMain)) goto cleanup; if (fccMain == formtypeAVI) rbIsAVI = true; if (fccMain != formtypeAVI && fccMain != mmioFOURCC('W', 'A', 'V', 'E')) goto cleanup; // We need to read almost all streams (regardless of 'bFullInfo' mode) because we need to get the 'dwMovieChunkSize' BOOL bHaveReadAllStreams; bHaveReadAllStreams = FALSE; while (!bHaveReadAllStreams && dwLengthLeft >= sizeof(DWORD)*2) { if (!ReadChunkHeader(hAviFile, &fccType, &dwLength)) goto inv_format_errno; if (fccType == 0 && dwLength == 0) { // We jumped right into a gap which is (still) filled with 0-bytes. If we // continue reading this until EOF we throw an error although we may have // already read valid data. if (mi->iVideoStreams > 0 || mi->iAudioStreams > 0) break; // already have valid data goto cleanup; } BOOL bInvalidLength = FALSE; if (!bSizeInvalid) { dwLengthLeft -= sizeof(DWORD)*2; if (dwLength > dwLengthLeft) { if (fccType == FOURCC_LIST) bInvalidLength = TRUE; else goto cleanup; } dwLengthLeft -= (dwLength + (dwLength & 1)); if (dwLengthLeft == (DWORD)-1) dwLengthLeft = 0; } switch (fccType) { case FOURCC_LIST: if (_read(hAviFile, &fccType, sizeof(fccType)) != sizeof(fccType)) goto inv_format_errno; if (fccType != listtypeAVIHEADER && bInvalidLength) goto inv_format; // Some Premiere plugin is writing AVI files with an invalid size field in the LIST/hdrl chunk. if (dwLength < sizeof(DWORD) && fccType != listtypeAVIHEADER && (fccType != listtypeAVIMOVIE || !bSizeInvalid)) goto inv_format; dwLength -= sizeof(DWORD); switch (fccType) { case listtypeAVIHEADER: dwLengthLeft += (dwLength + (dwLength&1)) + 4; dwLength = 0; // silently enter the header block break; case listtypeSTREAMHEADER: { BOOL bStreamRes; STREAMHEADER strmhdr = {0}; if ((bStreamRes = ParseStreamHeader(hAviFile, dwLength, &strmhdr)) != FALSE) { double fSamplesSec = (strmhdr.hdr.dwScale != 0) ? (double)strmhdr.hdr.dwRate / (double)strmhdr.hdr.dwScale : 0.0F; double fLength = (fSamplesSec != 0.0) ? (double)strmhdr.hdr.dwLength / fSamplesSec : 0.0; if (strmhdr.hdr.fccType == streamtypeAUDIO) { mi->iAudioStreams++; if (mi->iAudioStreams == 1) { mi->fAudioLengthSec = fLength; if (strmhdr.dwFormatLen >= sizeof(*strmhdr.fmt.wav) && strmhdr.fmt.wav) { *(PCMWAVEFORMAT*)&mi->audio = *strmhdr.fmt.wav; mi->strAudioFormat = GetAudioFormatName(strmhdr.fmt.wav->wf.wFormatTag); } } else { // this works only for CBR // // TODO: Determine VBR audio... if (strmhdr.dwFormatLen >= sizeof(*strmhdr.fmt.wav) && strmhdr.fmt.wav) dwAllNonVideoAvgBytesPerSec += strmhdr.fmt.wav->wf.nAvgBytesPerSec; if (bFullInfo && mi->strInfo.m_hWnd) { if (!mi->strInfo.IsEmpty()) mi->strInfo << _T("\n"); mi->OutputFileName(); mi->strInfo.SetSelectionCharFormat(mi->strInfo.m_cfBold); mi->strInfo << GetResString(IDS_AUDIO) << _T(" #") << mi->iAudioStreams; if (strmhdr.nam && strmhdr.nam[0] != '\0') mi->strInfo << _T(": \"") << strmhdr.nam << _T("\""); mi->strInfo << _T("\n"); if (strmhdr.dwFormatLen >= sizeof(*strmhdr.fmt.wav) && strmhdr.fmt.wav) { mi->strInfo << _T(" ") << GetResString(IDS_CODEC) << _T(":\t") << GetAudioFormatName(strmhdr.fmt.wav->wf.wFormatTag) << _T("\n"); if (strmhdr.fmt.wav->wf.nAvgBytesPerSec) { CString strBitrate; if (strmhdr.fmt.wav->wf.nAvgBytesPerSec == (DWORD)-1) strBitrate = _T("Variable"); else strBitrate.Format(_T("%u %s"), (UINT)(((strmhdr.fmt.wav->wf.nAvgBytesPerSec * 8.0) + 500.0) / 1000.0), GetResString(IDS_KBITSSEC)); mi->strInfo << _T(" ") << GetResString(IDS_BITRATE) << _T(":\t") << strBitrate << _T("\n"); } if (strmhdr.fmt.wav->wf.nChannels) { mi->strInfo << _T(" ") << GetResString(IDS_CHANNELS) << _T(":\t"); if (strmhdr.fmt.wav->wf.nChannels == 1) mi->strInfo << _T("1 (Mono)"); else if (strmhdr.fmt.wav->wf.nChannels == 2) mi->strInfo << _T("2 (Stereo)"); else if (strmhdr.fmt.wav->wf.nChannels == 5) mi->strInfo << _T("5.1 (Surround)"); else mi->strInfo << strmhdr.fmt.wav->wf.nChannels; mi->strInfo << _T("\n"); } if (strmhdr.fmt.wav->wf.nSamplesPerSec) mi->strInfo << _T(" ") << GetResString(IDS_SAMPLERATE) << _T(":\t") << strmhdr.fmt.wav->wf.nSamplesPerSec / 1000.0 << _T(" kHz\n"); if (strmhdr.fmt.wav->wBitsPerSample) mi->strInfo << _T(" Bit/sample:\t") << strmhdr.fmt.wav->wBitsPerSample << _T(" Bit\n"); } if (fLength) { CString strLength; SecToTimeLength((ULONG)fLength, strLength); mi->strInfo << _T(" ") << GetResString(IDS_LENGTH) << _T(":\t") << strLength << _T("\n"); } } } } else if (strmhdr.hdr.fccType == streamtypeVIDEO) { mi->iVideoStreams++; if (mi->iVideoStreams == 1) { uVideoFrames = strmhdr.hdr.dwLength; mi->fVideoLengthSec = fLength; mi->fVideoFrameRate = fSamplesSec; if (strmhdr.dwFormatLen >= sizeof(*strmhdr.fmt.bmi) && strmhdr.fmt.bmi) { mi->video.bmiHeader = *strmhdr.fmt.bmi; mi->strVideoFormat = GetVideoFormatName(strmhdr.fmt.bmi->biCompression); if (strmhdr.fmt.bmi->biWidth && strmhdr.fmt.bmi->biHeight) mi->fVideoAspectRatio = (float)abs(strmhdr.fmt.bmi->biWidth) / (float)abs(strmhdr.fmt.bmi->biHeight); } } else { if (bFullInfo && mi->strInfo.m_hWnd) { if (!mi->strInfo.IsEmpty()) mi->strInfo << _T("\n"); mi->OutputFileName(); mi->strInfo.SetSelectionCharFormat(mi->strInfo.m_cfBold); mi->strInfo << GetResString(IDS_VIDEO) << _T(" #") << mi->iVideoStreams; if (strmhdr.nam && strmhdr.nam[0] != '\0') mi->strInfo << _T(": \"") << strmhdr.nam << _T("\""); mi->strInfo << _T("\n"); if (strmhdr.dwFormatLen >= sizeof(*strmhdr.fmt.bmi) && strmhdr.fmt.bmi) { mi->strInfo << _T(" ") << GetResString(IDS_CODEC) << _T(":\t") << GetVideoFormatName(strmhdr.fmt.bmi->biCompression) << _T("\n"); if (strmhdr.fmt.bmi->biWidth && strmhdr.fmt.bmi->biHeight) { mi->strInfo << _T(" ") << GetResString(IDS_WIDTH) << _T(" x ") << GetResString(IDS_HEIGHT) << _T(":\t") << abs(strmhdr.fmt.bmi->biWidth) << _T(" x ") << abs(strmhdr.fmt.bmi->biHeight) << _T("\n"); float fAspectRatio = (float)abs(strmhdr.fmt.bmi->biWidth) / (float)abs(strmhdr.fmt.bmi->biHeight); mi->strInfo << _T(" ") << GetResString(IDS_ASPECTRATIO) << _T(":\t") << fAspectRatio << _T(" (") << GetKnownAspectRatioDisplayString(fAspectRatio) << _T(")\n"); } } if (fLength) { CString strLength; SecToTimeLength((ULONG)fLength, strLength); mi->strInfo << _T(" ") << GetResString(IDS_LENGTH) << _T(":\t") << strLength << _T("\n"); } } } } else { iNonAVStreams++; if (bFullInfo && mi->strInfo.m_hWnd) { if (!mi->strInfo.IsEmpty()) mi->strInfo << _T("\n"); mi->OutputFileName(); mi->strInfo.SetSelectionCharFormat(mi->strInfo.m_cfBold); mi->strInfo << _T("Unknown Stream #") << iStream; if (strmhdr.nam && strmhdr.nam[0] != '\0') mi->strInfo << _T(": \"") << strmhdr.nam << _T("\""); mi->strInfo << _T("\n"); if (fLength) { CString strLength; SecToTimeLength((ULONG)fLength, strLength); mi->strInfo << _T(" ") << GetResString(IDS_LENGTH) << _T(":\t") << strLength << _T("\n"); } } } } delete[] strmhdr.fmt.dat; delete[] strmhdr.nam; if (!bStreamRes) goto inv_format_errno; iStream++; dwLength = 0; break; } case listtypeAVIMOVIE: dwMovieChunkSize = dwLength; if (!bFullInfo) bHaveReadAllStreams = TRUE; break; case mmioFOURCC('I', 'N', 'F', 'O'): { if (dwLength < 0x10000) { bool bError = false; BYTE* pChunk = new BYTE[dwLength]; if ((UINT)_read(hAviFile, pChunk, dwLength) == dwLength) { CSafeMemFile ck(pChunk, dwLength); try { if (bFullInfo && mi->strInfo.m_hWnd) { if (!mi->strInfo.IsEmpty()) mi->strInfo << _T("\n"); mi->OutputFileName(); mi->strInfo.SetSelectionCharFormat(mi->strInfo.m_cfBold); mi->strInfo << GetResString(IDS_FD_GENERAL) << _T("\n"); } while (ck.GetPosition() < ck.GetLength()) { FOURCC ckId = ck.ReadUInt32(); DWORD ckLen = ck.ReadUInt32(); CString strValue; if (ckLen < 512) { CStringA strValueA; ck.Read(strValueA.GetBuffer(ckLen), ckLen); strValueA.ReleaseBuffer(ckLen); strValue = strValueA; strValue.Trim(); } else { ck.Seek(ckLen, CFile::current); strValue.Empty(); } strValue.Replace(_T("\r"), _T(" ")); strValue.Replace(_T("\n"), _T(" ")); switch (ckId) { case mmioFOURCC('I', 'N', 'A', 'M'): if (bFullInfo && mi->strInfo.m_hWnd && !strValue.IsEmpty()) mi->strInfo << _T(" ") << GetResString(IDS_TITLE) << _T(":\t") << strValue << _T("\n"); mi->strTitle = strValue; break; case mmioFOURCC('I', 'S', 'B', 'J'): if (bFullInfo && mi->strInfo.m_hWnd && !strValue.IsEmpty()) mi->strInfo << _T(" ") << _T("Subject") << _T(":\t") << strValue << _T("\n"); break; case mmioFOURCC('I', 'A', 'R', 'T'): if (bFullInfo && mi->strInfo.m_hWnd && !strValue.IsEmpty()) mi->strInfo << _T(" ") << GetResString(IDS_AUTHOR) << _T(":\t") << strValue << _T("\n"); mi->strAuthor = strValue; break; case mmioFOURCC('I', 'C', 'O', 'P'): if (bFullInfo && mi->strInfo.m_hWnd && !strValue.IsEmpty()) mi->strInfo << _T(" ") << _T("Copyright") << _T(":\t") << strValue << _T("\n"); break; case mmioFOURCC('I', 'C', 'M', 'T'): if (bFullInfo && mi->strInfo.m_hWnd && !strValue.IsEmpty()) mi->strInfo << _T(" ") << GetResString(IDS_COMMENT) << _T(":\t") << strValue << _T("\n"); break; case mmioFOURCC('I', 'C', 'R', 'D'): if (bFullInfo && mi->strInfo.m_hWnd && !strValue.IsEmpty()) mi->strInfo << _T(" ") << GetResString(IDS_DATE) << _T(":\t") << strValue << _T("\n"); break; case mmioFOURCC('I', 'S', 'F', 'T'): if (bFullInfo && mi->strInfo.m_hWnd && !strValue.IsEmpty()) mi->strInfo << _T(" ") << _T("Software") << _T(":\t") << strValue << _T("\n"); break; } if (ckLen & 1) ck.Seek(1, CFile::current); } } catch(CException* ex) { ex->Delete(); bError = true; } } else { bError = true; } delete[] pChunk; if (bError) { bHaveReadAllStreams = TRUE; } else { if (dwLength & 1) { if (_lseek(hAviFile, 1, SEEK_CUR) == -1) bHaveReadAllStreams = TRUE; } dwLength = 0; } } break; } } break; case ckidAVIMAINHDR: if (dwLength == sizeof(MainAVIHeader)) { MainAVIHeader avihdr; if (_read(hAviFile, &avihdr, sizeof(avihdr)) != sizeof(avihdr)) goto inv_format_errno; if (dwLength & 1) { if (_lseek(hAviFile, 1, SEEK_CUR) == -1) goto inv_format_errno; } dwLength = 0; } break; case ckidAVINEWINDEX: // idx1 if (!bFullInfo) bHaveReadAllStreams = TRUE; break; case mmioFOURCC('f', 'm', 't', ' '): if (fccMain == mmioFOURCC('W', 'A', 'V', 'E')) { STREAMHEADER strmhdr = {0}; if (dwLength > 4096) // expect corrupt data goto inv_format; if ((strmhdr.fmt.dat = new BYTE[strmhdr.dwFormatLen = dwLength]) == NULL) { errno = ENOMEM; goto inv_format_errno; } if (_read(hAviFile, strmhdr.fmt.dat, dwLength) != (int)dwLength) goto inv_format_errno; if (dwLength & 1) { if (_lseek(hAviFile, 1, SEEK_CUR) == -1) goto inv_format_errno; } dwLength = 0; strmhdr.hdr.fccType = streamtypeAUDIO; if (strmhdr.dwFormatLen) { mi->iAudioStreams++; if (mi->iAudioStreams == 1) { if (strmhdr.dwFormatLen >= sizeof(*strmhdr.fmt.wav) && strmhdr.fmt.wav) { *(PCMWAVEFORMAT*)&mi->audio = *strmhdr.fmt.wav; mi->strAudioFormat = GetAudioFormatName(strmhdr.fmt.wav->wf.wFormatTag); } } } delete[] strmhdr.fmt.dat; delete[] strmhdr.nam; iStream++; } break; case mmioFOURCC('d', 'a', 't', 'a'): if (fccMain == mmioFOURCC('W', 'A', 'V', 'E')) { if (mi->iAudioStreams == 1 && mi->iVideoStreams == 0 && mi->audio.nAvgBytesPerSec != 0 && mi->audio.nAvgBytesPerSec != (DWORD)-1) { mi->fAudioLengthSec = (double)dwLength / mi->audio.nAvgBytesPerSec; if (mi->fAudioLengthSec < 1.0) mi->fAudioLengthSec = 1.0; // compensate for very small files } } break; } if (bHaveReadAllStreams) break; if (dwLength) { if (_lseek(hAviFile, dwLength + (dwLength & 1), SEEK_CUR) == -1) goto inv_format_errno; } } if (fccMain == formtypeAVI) { mi->strFileFormat = _T("AVI"); // NOTE: This video bitrate is published to ed2k servers and Kad, so, do everything to determine it right! if (mi->iVideoStreams == 1 /*&& mi->iAudioStreams <= 1*/ && iNonAVStreams == 0 && mi->fVideoLengthSec) { DWORD dwVideoFramesOverhead = uVideoFrames * (sizeof(WORD) + sizeof(WORD) + sizeof(DWORD)); mi->video.dwBitRate = (DWORD)(((dwMovieChunkSize - dwVideoFramesOverhead) / mi->fVideoLengthSec - dwAllNonVideoAvgBytesPerSec/*mi->audio.nAvgBytesPerSec*/) * 8); } } else if (fccMain == mmioFOURCC('W', 'A', 'V', 'E')) mi->strFileFormat = _T("WAV (RIFF)"); else mi->strFileFormat = _T("RIFF"); mi->InitFileLength(); bResult = TRUE; cleanup: _close(hAviFile); return bResult; inv_format: goto cleanup; inv_format_errno: goto cleanup; } #pragma pack(push,1) typedef struct { DWORD id; DWORD size; } SRmChunkHdr; typedef struct { DWORD file_version; DWORD num_headers; } SRmRMF; typedef struct { DWORD max_bit_rate; DWORD avg_bit_rate; DWORD max_packet_size; DWORD avg_packet_size; DWORD num_packets; DWORD duration; DWORD preroll; DWORD index_offset; DWORD data_offset; WORD num_streams; WORD flags; } SRmPROP; typedef struct { WORD stream_number; DWORD max_bit_rate; DWORD avg_bit_rate; DWORD max_packet_size; DWORD avg_packet_size; DWORD start_time; DWORD preroll; DWORD duration; //BYTE stream_name_size; //BYTE[stream_name_size] stream_name; //BYTE mime_type_size; //BYTE[mime_type_size] mime_type; //DWORD type_specific_len; //BYTE[type_specific_len] type_specific_data; } SRmMDPR; #pragma pack(pop) struct SRmFileProp { SRmFileProp() {} SRmFileProp(const CStringA& rstrName, const CStringA& rstrValue) : strName(rstrName), strValue(rstrValue) {} SRmFileProp& operator=(const SRmFileProp& r) { strName = r.strName; strValue = r.strValue; return *this; } CStringA strName; CStringA strValue; }; CStringA GetFOURCCString(DWORD fcc) { char szFourcc[5]; szFourcc[0] = ((LPCSTR)&fcc)[0]; szFourcc[1] = ((LPCSTR)&fcc)[1]; szFourcc[2] = ((LPCSTR)&fcc)[2]; szFourcc[3] = ((LPCSTR)&fcc)[3]; szFourcc[4] = '\0'; // Strip trailing spaces int i = 3; while (i >= 0) { if (szFourcc[i] == ' ') szFourcc[i] = '\0'; else if (szFourcc[i] != '\0') break; i--; } // Convert to lower case /*if (bToLower) { while (i >= 0) { szFourcc[i] = (char)tolower((unsigned char)szFourcc[i]); i--; } }*/ return szFourcc; } struct SRmCodec { LPCSTR pszID; LPCTSTR pszDesc; } g_aRealMediaCodecs[] = { { "14.4", _T("Real Audio 1 (14.4)") }, { "14_4", _T("Real Audio 1 (14.4)") }, { "28.8", _T("Real Audio 2 (28.8)") }, { "28_8", _T("Real Audio 2 (28.8)") }, { "RV10", _T("Real Video 5") }, { "RV13", _T("Real Video 5") }, { "RV20", _T("Real Video G2") }, { "RV30", _T("Real Video 8") }, { "RV40", _T("Real Video 9") }, { "atrc", _T("Real & Sony Atrac3 Codec") }, { "cook", _T("Real Audio G2/7 Cook (Low Bitrate)") }, { "dnet", _T("Real Audio 3/4/5 Music (DNET)") }, { "lpcJ", _T("Real Audio 1 (14.4)") }, { "raac", _T("Real Audio 10 AAC (RAAC)") }, { "racp", _T("Real Audio 10 AAC+ (RACP)") }, { "ralf", _T("Real Audio Lossless Format") }, { "rtrc", _T("Real Audio 8 (RTRC)") }, { "rv10", _T("Real Video 5") }, { "rv20", _T("Real Video G2") }, { "rv30", _T("Real Video 8") }, { "rv40", _T("Real Video 9") }, { "sipr", _T("Real Audio 4 (Sipro)") }, }; static int __cdecl CmpRealMediaCodec(const void *p1, const void *p2) { const SRmCodec *pCodec1 = (const SRmCodec *)p1; const SRmCodec *pCodec2 = (const SRmCodec *)p2; return strncmp(pCodec1->pszID, pCodec2->pszID, 4); } CString GetRealMediaCodecInfo(LPCSTR pszCodecID) { CString strInfo(GetFOURCCString(*(DWORD *)pszCodecID)); SRmCodec CodecSearch; CodecSearch.pszID = pszCodecID; SRmCodec *pCodecFound = (SRmCodec *)bsearch(&CodecSearch, g_aRealMediaCodecs, _countof(g_aRealMediaCodecs), sizeof(g_aRealMediaCodecs[0]), CmpRealMediaCodec); if (pCodecFound) { strInfo += _T(" ("); strInfo += pCodecFound->pszDesc; strInfo += _T(")"); } return strInfo; } BOOL GetRMHeaders(LPCTSTR pszFileName, SMediaInfo* mi, bool& rbIsRM, bool bFullInfo) { ASSERT( !bFullInfo || mi->strInfo.m_hWnd != NULL ); bool bResult = false; CSafeBufferedFile file; if (!file.Open(pszFileName, CFile::modeRead | CFile::osSequentialScan | CFile::typeBinary)) return false; setvbuf(file.m_pStream, NULL, _IOFBF, 16384); bool bReadPROP = false; bool bReadMDPR_Video = false; bool bReadMDPR_Audio = false; bool bReadMDPR_File = false; bool bReadCONT = false; UINT nFileBitrate = 0; CString strCopyright; CString strComment; CArray<SRmFileProp> aFileProps; try { ULONGLONG ullCurFilePos = 0; ULONGLONG ullChunkStartFilePos = ullCurFilePos; ULONGLONG ullChunkEndFilePos; SRmChunkHdr rmChunkHdr; file.Read(&rmChunkHdr, sizeof(rmChunkHdr)); DWORD dwID = _byteswap_ulong(rmChunkHdr.id); if (dwID != '.RMF') return false; DWORD dwSize = _byteswap_ulong(rmChunkHdr.size); if (dwSize < sizeof(rmChunkHdr)) return false; ullChunkEndFilePos = ullChunkStartFilePos + dwSize; dwSize -= sizeof(rmChunkHdr); if (dwSize == 0) return false; WORD wVersion; file.Read(&wVersion, sizeof(wVersion)); wVersion = _byteswap_ushort(wVersion); if (wVersion >= 2) return false; SRmRMF rmRMF; file.Read(&rmRMF, sizeof(rmRMF)); rbIsRM = true; mi->strFileFormat = _T("Real Media"); bool bBrokenFile = false; while (!bBrokenFile && (!bReadCONT || !bReadPROP || !bReadMDPR_Video || !bReadMDPR_Audio || (bFullInfo && !bReadMDPR_File))) { ullCurFilePos = file.GetPosition(); if (ullCurFilePos > ullChunkEndFilePos) break; // expect broken DATA-chunk headers created by 'mplayer' if (ullCurFilePos < ullChunkEndFilePos) ullCurFilePos = file.Seek(ullChunkEndFilePos - ullCurFilePos, CFile::current); ullChunkStartFilePos = ullCurFilePos; file.Read(&rmChunkHdr, sizeof(rmChunkHdr)); dwID = _byteswap_ulong(rmChunkHdr.id); dwSize = _byteswap_ulong(rmChunkHdr.size); TRACE("%08x: id=%.4s size=%u\n", (DWORD)ullCurFilePos, &rmChunkHdr.id, dwSize); if (dwSize < sizeof(rmChunkHdr)) break; // expect broken DATA-chunk headers created by 'mplayer' ullChunkEndFilePos = ullChunkStartFilePos + dwSize; dwSize -= sizeof(rmChunkHdr); if (dwSize > 0) { switch (dwID) { case 'PROP': { // Properties Header WORD wVersion; file.Read(&wVersion, sizeof(wVersion)); wVersion = _byteswap_ushort(wVersion); if (wVersion == 0) { SRmPROP rmPROP; file.Read(&rmPROP, sizeof(rmPROP)); nFileBitrate = _byteswap_ulong(rmPROP.avg_bit_rate); mi->fFileLengthSec = (_byteswap_ulong(rmPROP.duration) + 500.0) / 1000.0; bReadPROP = true; } break; } case 'MDPR': { // Media Properties Header WORD wVersion; file.Read(&wVersion, sizeof(wVersion)); wVersion = _byteswap_ushort(wVersion); if (wVersion == 0) { SRmMDPR rmMDPR; file.Read(&rmMDPR, sizeof(rmMDPR)); // Read 'Stream Name' BYTE ucLen; CStringA strStreamName; file.Read(&ucLen, sizeof(ucLen)); file.Read(strStreamName.GetBuffer(ucLen), ucLen); strStreamName.ReleaseBuffer(ucLen); // Read 'MIME Type' CStringA strMimeType; file.Read(&ucLen, sizeof(ucLen)); file.Read(strMimeType.GetBuffer(ucLen), ucLen); strMimeType.ReleaseBuffer(ucLen); DWORD dwTypeDataLen; file.Read(&dwTypeDataLen, sizeof(dwTypeDataLen)); dwTypeDataLen = _byteswap_ulong(dwTypeDataLen); if (strMimeType == "video/x-pn-realvideo") { mi->iVideoStreams++; if (mi->iVideoStreams == 1) { mi->video.dwBitRate = _byteswap_ulong(rmMDPR.avg_bit_rate); mi->fVideoLengthSec = _byteswap_ulong(rmMDPR.duration) / 1000.0; if (dwTypeDataLen >= 22+2 && dwTypeDataLen < 8192) { BYTE *pucTypeData = new BYTE[dwTypeDataLen]; try { file.Read(pucTypeData, dwTypeDataLen); if (_byteswap_ulong(*(DWORD *)(pucTypeData + 4)) == 'VIDO') { mi->strVideoFormat = GetRealMediaCodecInfo((LPCSTR)(pucTypeData + 8)); mi->video.bmiHeader.biCompression = *(DWORD *)(pucTypeData + 8); mi->video.bmiHeader.biWidth = _byteswap_ushort(*(WORD *)(pucTypeData + 12)); mi->video.bmiHeader.biHeight = _byteswap_ushort(*(WORD *)(pucTypeData + 14)); mi->fVideoAspectRatio = (float)abs(mi->video.bmiHeader.biWidth) / (float)abs(mi->video.bmiHeader.biHeight); mi->fVideoFrameRate = _byteswap_ushort(*(WORD *)(pucTypeData + 22)); bReadMDPR_Video = true; } } catch (CException* ex) { ex->Delete(); delete[] pucTypeData; break; } delete[] pucTypeData; } } } else if (strMimeType == "audio/x-pn-realaudio") { mi->iAudioStreams++; if (mi->iAudioStreams == 1) { mi->audio.nAvgBytesPerSec = _byteswap_ulong(rmMDPR.avg_bit_rate) / 8; mi->fAudioLengthSec = _byteswap_ulong(rmMDPR.duration) / 1000.0; if (dwTypeDataLen >= 4+2 && dwTypeDataLen < 8192) { BYTE *pucTypeData = new BYTE[dwTypeDataLen]; try { file.Read(pucTypeData, dwTypeDataLen); DWORD dwFourCC = _byteswap_ulong(*(DWORD *)(pucTypeData + 0)); WORD wVer = _byteswap_ushort(*(WORD *)(pucTypeData + 4)); if (dwFourCC == '.ra\xFD') { if (wVer == 3) { if (dwTypeDataLen >= 8+2) { mi->audio.nSamplesPerSec = 8000; mi->audio.nChannels = _byteswap_ushort(*(WORD *)(pucTypeData + 8)); mi->strAudioFormat = _T(".ra3"); bReadMDPR_Audio = true; } } else if (wVer == 4) // RealAudio G2, RealAudio 8 { if (dwTypeDataLen >= 62+4) { mi->audio.nSamplesPerSec = _byteswap_ushort(*(WORD *)(pucTypeData + 48)); mi->audio.nChannels = _byteswap_ushort(*(WORD *)(pucTypeData + 54)); if (strncmp((LPCSTR)(pucTypeData + 62), "sipr", 4) == 0) mi->audio.wFormatTag = WAVE_FORMAT_SIPROLAB_ACEPLNET; else if (strncmp((LPCSTR)(pucTypeData + 62), "cook", 4) == 0) mi->audio.wFormatTag = 0x2004; mi->strAudioFormat = GetRealMediaCodecInfo((LPCSTR)(pucTypeData + 62)); bReadMDPR_Audio = true; } } else if (wVer == 5) { if (dwTypeDataLen >= 66+4) { mi->audio.nSamplesPerSec = _byteswap_ulong(*(DWORD *)(pucTypeData + 48)); mi->audio.nChannels = _byteswap_ushort(*(WORD *)(pucTypeData + 60)); if (strncmp((LPCSTR)(pucTypeData + 62), "sipr", 4) == 0) mi->audio.wFormatTag = WAVE_FORMAT_SIPROLAB_ACEPLNET; else if (strncmp((LPCSTR)(pucTypeData + 62), "cook", 4) == 0) mi->audio.wFormatTag = 0x2004; mi->strAudioFormat = GetRealMediaCodecInfo((LPCSTR)(pucTypeData + 66)); bReadMDPR_Audio = true; } } } } catch (CException* ex) { ex->Delete(); delete[] pucTypeData; break; } delete[] pucTypeData; } } } else if (bFullInfo && strcmp(strMimeType, "logical-fileinfo") == 0) { DWORD dwLogStreamLen; file.Read(&dwLogStreamLen, sizeof(dwLogStreamLen)); dwLogStreamLen = _byteswap_ulong(dwLogStreamLen); WORD wVersion; file.Read(&wVersion, sizeof(wVersion)); wVersion = _byteswap_ushort(wVersion); if (wVersion == 0) { WORD wStreams; file.Read(&wStreams, sizeof(wStreams)); wStreams = _byteswap_ushort(wStreams); // Skip 'Physical Stream Numbers' file.Seek(wStreams * sizeof(WORD), CFile::current); // Skip 'Data Offsets' file.Seek(wStreams * sizeof(DWORD), CFile::current); WORD wRules; file.Read(&wRules, sizeof(wRules)); wRules = _byteswap_ushort(wRules); // Skip 'Rule to Physical Stream Number Map' file.Seek(wRules * sizeof(WORD), CFile::current); WORD wProperties; file.Read(&wProperties, sizeof(wProperties)); wProperties = _byteswap_ushort(wProperties); while (wProperties) { DWORD dwPropSize; file.Read(&dwPropSize, sizeof(dwPropSize)); dwPropSize = _byteswap_ulong(dwPropSize); WORD wPropVersion; file.Read(&wPropVersion, sizeof(wPropVersion)); wPropVersion = _byteswap_ushort(wPropVersion); if (wPropVersion == 0) { BYTE ucLen; CStringA strPropNameA; file.Read(&ucLen, sizeof(ucLen)); file.Read(strPropNameA.GetBuffer(ucLen), ucLen); strPropNameA.ReleaseBuffer(ucLen); DWORD dwPropType; file.Read(&dwPropType, sizeof(dwPropType)); dwPropType = _byteswap_ulong(dwPropType); WORD wPropValueLen; file.Read(&wPropValueLen, sizeof(wPropValueLen)); wPropValueLen = _byteswap_ushort(wPropValueLen); CStringA strPropValueA; if (dwPropType == 0 && wPropValueLen == sizeof(DWORD)) { DWORD dwPropValue; file.Read(&dwPropValue, sizeof(dwPropValue)); dwPropValue = _byteswap_ulong(dwPropValue); strPropValueA.Format("%u", dwPropValue); } else if (dwPropType == 2) { LPSTR pszA = strPropValueA.GetBuffer(wPropValueLen); file.Read(pszA, wPropValueLen); if (wPropValueLen > 0 && pszA[wPropValueLen - 1] == '\0') wPropValueLen--; strPropValueA.ReleaseBuffer(wPropValueLen); } else { file.Seek(wPropValueLen, CFile::current); strPropValueA.Format("<%u bytes>", wPropValueLen); } aFileProps.Add(SRmFileProp(strPropNameA, strPropValueA)); TRACE("Prop: %s, typ=%u, size=%u, value=%s\n", strPropNameA, dwPropType, wPropValueLen, (LPCSTR)strPropValueA); } else file.Seek(dwPropSize - sizeof(DWORD) - sizeof(WORD), CFile::current); wProperties--; } bReadMDPR_File = true; } } } break; } case 'CONT': { // Content Description Header WORD wVersion; file.Read(&wVersion, sizeof(wVersion)); wVersion = _byteswap_ushort(wVersion); if (wVersion == 0) { WORD wLen; CStringA strA; file.Read(&wLen, sizeof(wLen)); wLen = _byteswap_ushort(wLen); file.Read(strA.GetBuffer(wLen), wLen); strA.ReleaseBuffer(wLen); mi->strTitle = strA; file.Read(&wLen, sizeof(wLen)); wLen = _byteswap_ushort(wLen); file.Read(strA.GetBuffer(wLen), wLen); strA.ReleaseBuffer(wLen); mi->strAuthor = strA; file.Read(&wLen, sizeof(wLen)); wLen = _byteswap_ushort(wLen); file.Read(strA.GetBuffer(wLen), wLen); strA.ReleaseBuffer(wLen); strCopyright = strA; file.Read(&wLen, sizeof(wLen)); wLen = _byteswap_ushort(wLen); file.Read(strA.GetBuffer(wLen), wLen); strA.ReleaseBuffer(wLen); strComment = strA; bReadCONT = true; } break; } case 'DATA': case 'INDX': case 'RMMD': case 'RMJE': // Expect broken DATA-chunk headers created by 'mplayer'. Thus catch // all valid tags just to have chance to detect the broken ones. break; default: // Expect broken DATA-chunk headers created by 'mplayer'. Stop reading // the file on first broken chunk header. bBrokenFile = true; break; } } } } catch(CException *ex) { ex->Delete(); } // Expect broken DATA-chunk headers created by 'mplayer'. A broken DATA-chunk header // may not be a fatal error. We may have already successfully read the media properties // headers. Therefore we indicate 'success' if we read at least some valid headers. bResult = bReadCONT || bReadPROP || bReadMDPR_Video || bReadMDPR_Audio; if (bResult) { mi->InitFileLength(); if ( bFullInfo && mi->strInfo.m_hWnd && ( nFileBitrate || !mi->strTitle.IsEmpty() || !mi->strAuthor.IsEmpty() || !strCopyright.IsEmpty() || !strComment.IsEmpty() || aFileProps.GetSize())) { if (!mi->strInfo.IsEmpty()) mi->strInfo << _T("\n"); mi->OutputFileName(); mi->strInfo.SetSelectionCharFormat(mi->strInfo.m_cfBold); mi->strInfo << GetResString(IDS_FD_GENERAL) << _T("\n"); if (nFileBitrate) { CString strBitrate; strBitrate.Format(_T("%u %s"), (UINT)((nFileBitrate + 500.0) / 1000.0), GetResString(IDS_KBITSSEC)); mi->strInfo << _T(" ") << GetResString(IDS_BITRATE) << _T(":\t") << strBitrate << _T("\n"); } if (!mi->strTitle.IsEmpty()) mi->strInfo << _T(" ") << GetResString(IDS_TITLE) << _T(":\t") << mi->strTitle << _T("\n"); if (!mi->strAuthor.IsEmpty()) mi->strInfo << _T(" ") << GetResString(IDS_AUTHOR) << _T(":\t") << mi->strAuthor << _T("\n"); if (!strCopyright.IsEmpty()) mi->strInfo << _T(" ") << _T("Copyright") << _T(":\t") << strCopyright << _T("\n"); if (!strComment.IsEmpty()) mi->strInfo << _T(" ") << GetResString(IDS_COMMENT) << _T(":\t") << strComment << _T("\n"); for (int i = 0; i < aFileProps.GetSize(); i++) { if (!aFileProps[i].strValue.IsEmpty()) mi->strInfo << _T(" ") << CString(aFileProps[i].strName) << _T(":\t") << CString(aFileProps[i].strValue) << _T("\n"); } } } return bResult; } #ifdef HAVE_WMSDK_H template<class T, WMT_ATTR_DATATYPE attrTypeT> bool GetAttributeT(IWMHeaderInfo *pIWMHeaderInfo, WORD wStream, LPCWSTR pwszName, T &nValue) { WMT_ATTR_DATATYPE attrType; WORD wValueSize = sizeof(nValue); HRESULT hr = pIWMHeaderInfo->GetAttributeByName(&wStream, pwszName, &attrType, (BYTE *)&nValue, &wValueSize); if (hr == ASF_E_NOTFOUND) return false; else if (hr != S_OK || attrType != attrTypeT) { ASSERT(0); return false; } return true; } template<class T> bool GetAttribute(IWMHeaderInfo *pIWMHeaderInfo, WORD wStream, LPCWSTR pwszName, T &nData); bool GetAttribute<>(IWMHeaderInfo *pIWMHeaderInfo, WORD wStream, LPCWSTR pwszName, BOOL &nData) { return GetAttributeT<BOOL, WMT_TYPE_BOOL>(pIWMHeaderInfo, wStream, pwszName, nData); } bool GetAttribute<>(IWMHeaderInfo *pIWMHeaderInfo, WORD wStream, LPCWSTR pwszName, DWORD &nData) { return GetAttributeT<DWORD, WMT_TYPE_DWORD>(pIWMHeaderInfo, wStream, pwszName, nData); } bool GetAttribute<>(IWMHeaderInfo *pIWMHeaderInfo, WORD wStream, LPCWSTR pwszName, QWORD &nData) { return GetAttributeT<QWORD, WMT_TYPE_QWORD>(pIWMHeaderInfo, wStream, pwszName, nData); } bool GetAttribute(IWMHeaderInfo *pIWMHeaderInfo, WORD wStream, LPCWSTR pwszName, CString &strValue) { WMT_ATTR_DATATYPE attrType; WORD wValueSize; HRESULT hr = pIWMHeaderInfo->GetAttributeByName(&wStream, pwszName, &attrType, NULL, &wValueSize); if (hr == ASF_E_NOTFOUND) return false; else if (hr != S_OK || attrType != WMT_TYPE_STRING || wValueSize < sizeof(WCHAR) || (wValueSize % sizeof(WCHAR)) != 0) { ASSERT(0); return false; } // empty string ? if (wValueSize == sizeof(WCHAR)) return false; hr = pIWMHeaderInfo->GetAttributeByName(&wStream, pwszName, &attrType, (BYTE *)strValue.GetBuffer(wValueSize / sizeof(WCHAR)), &wValueSize); strValue.ReleaseBuffer(); if (hr != S_OK || attrType != WMT_TYPE_STRING) { ASSERT(0); return false; } if (strValue.IsEmpty()) return false; // SDK states that MP3 files could contain a BOM - never seen if ( *(const WORD *)(LPCWSTR)strValue == (WORD)0xFFFE || *(const WORD *)(LPCWSTR)strValue == (WORD)0xFEFF) { ASSERT(0); strValue = strValue.Mid(1); } return true; } bool GetAttributeIndices(IWMHeaderInfo3 *pIWMHeaderInfo, WORD wStream, LPCWSTR pwszName, CTempBuffer<WORD> &aIndices, WORD &wLangIndex) { WORD wIndexCount; HRESULT hr = pIWMHeaderInfo->GetAttributeIndices(wStream, pwszName, &wLangIndex, NULL, &wIndexCount); if (hr == ASF_E_NOTFOUND) return false; else if (hr != S_OK) { ASSERT(0); return false; } if (wIndexCount == 0) return false; hr = pIWMHeaderInfo->GetAttributeIndices(wStream, pwszName, &wLangIndex, aIndices.Allocate(wIndexCount), &wIndexCount); if (hr != S_OK || wIndexCount == 0) { ASSERT(0); return false; } return true; } template<class T, WMT_ATTR_DATATYPE attrTypeT> bool GetAttributeExT(IWMHeaderInfo3 *pIWMHeaderInfo, WORD wStream, LPCWSTR pwszName, T &nData) { // Certain attributes (e.g. WM/StreamTypeInfo, WM/PeakBitrate) can not get read with "IWMHeaderInfo::GetAttributeByName", // those attributes are only returned with "IWMHeaderInfo3::GetAttributeByIndexEx". CTempBuffer<WORD> aIndices; WORD wLangIndex = 0; if (!GetAttributeIndices(pIWMHeaderInfo, wStream, pwszName, aIndices, wLangIndex)) return false; WORD wIndex = aIndices[0]; WORD wNameSize; DWORD dwDataSize; WMT_ATTR_DATATYPE attrType; HRESULT hr = pIWMHeaderInfo->GetAttributeByIndexEx(wStream, wIndex, NULL, &wNameSize, &attrType, &wLangIndex, NULL, &dwDataSize); if (hr != S_OK || attrType != attrTypeT || dwDataSize != sizeof(nData)) { ASSERT(0); return false; } WCHAR wszName[1024]; if (wNameSize > _countof(wszName)) { ASSERT(0); return false; } hr = pIWMHeaderInfo->GetAttributeByIndexEx(wStream, wIndex, wszName, &wNameSize, &attrType, &wLangIndex, (BYTE *)&nData, &dwDataSize); if (hr != S_OK || attrType != attrTypeT || dwDataSize != sizeof(nData)) { ASSERT(0); return false; } return true; } template<class T> bool GetAttributeEx(IWMHeaderInfo3 *pIWMHeaderInfo, WORD wStream, LPCWSTR pwszName, T &nData); bool GetAttributeEx<>(IWMHeaderInfo3 *pIWMHeaderInfo, WORD wStream, LPCWSTR pwszName, BOOL &nData) { return GetAttributeExT<BOOL, WMT_TYPE_BOOL>(pIWMHeaderInfo, wStream, pwszName, nData); } bool GetAttributeEx<>(IWMHeaderInfo3 *pIWMHeaderInfo, WORD wStream, LPCWSTR pwszName, DWORD &nData) { return GetAttributeExT<DWORD, WMT_TYPE_DWORD>(pIWMHeaderInfo, wStream, pwszName, nData); } bool GetAttributeEx<>(IWMHeaderInfo3 *pIWMHeaderInfo, WORD wStream, LPCWSTR pwszName, QWORD &nData) { return GetAttributeExT<QWORD, WMT_TYPE_QWORD>(pIWMHeaderInfo, wStream, pwszName, nData); } bool GetAttributeEx(IWMHeaderInfo3 *pIWMHeaderInfo, WORD wStream, LPCWSTR pwszName, CTempBuffer<BYTE> &aData, DWORD &dwDataSize) { // Certain attributes (e.g. WM/StreamTypeInfo, WM/PeakBitrate) can not get read with "IWMHeaderInfo::GetAttributeByName", // those attributes are only returned with "IWMHeaderInfo3::GetAttributeByIndexEx". CTempBuffer<WORD> aIndices; WORD wLangIndex = 0; if (!GetAttributeIndices(pIWMHeaderInfo, wStream, pwszName, aIndices, wLangIndex)) return false; WORD wIndex = aIndices[0]; WORD wNameSize; WMT_ATTR_DATATYPE attrType; HRESULT hr = pIWMHeaderInfo->GetAttributeByIndexEx(wStream, wIndex, NULL, &wNameSize, &attrType, &wLangIndex, NULL, &dwDataSize); if (hr != S_OK || attrType != WMT_TYPE_BINARY) { ASSERT(0); return false; } WCHAR wszName[1024]; if (wNameSize > _countof(wszName)) { ASSERT(0); return false; } if (dwDataSize == 0) return false; hr = pIWMHeaderInfo->GetAttributeByIndexEx(wStream, wIndex, wszName, &wNameSize, &attrType, &wLangIndex, aData.Allocate(dwDataSize), &dwDataSize); if (hr != S_OK || attrType != WMT_TYPE_BINARY) { ASSERT(0); return false; } return true; } bool GetAttributeEx(IWMHeaderInfo3 *pIWMHeaderInfo, WORD wStream, LPCWSTR pwszName, CString &strValue) { CTempBuffer<WORD> aIndices; WORD wLangIndex = 0; if (!GetAttributeIndices(pIWMHeaderInfo, wStream, pwszName, aIndices, wLangIndex)) return false; WORD wIndex = aIndices[0]; WORD wNameSize; WMT_ATTR_DATATYPE attrType; DWORD dwValueSize; HRESULT hr = pIWMHeaderInfo->GetAttributeByIndexEx(wStream, wIndex, NULL, &wNameSize, &attrType, &wLangIndex, NULL, &dwValueSize); if (hr != S_OK || attrType != WMT_TYPE_STRING || dwValueSize < sizeof(WCHAR) || (dwValueSize % sizeof(WCHAR)) != 0) { ASSERT(0); return false; } WCHAR wszName[1024]; if (wNameSize > _countof(wszName)) { ASSERT(0); return false; } // empty string ? if (dwValueSize == sizeof(WCHAR)) return false; hr = pIWMHeaderInfo->GetAttributeByIndexEx(wStream, wIndex, wszName, &wNameSize, &attrType, &wLangIndex, (BYTE *)strValue.GetBuffer(dwValueSize / sizeof(WCHAR)), &dwValueSize); strValue.ReleaseBuffer(); if (hr != S_OK || attrType != WMT_TYPE_STRING) { ASSERT(0); return false; } if (strValue.IsEmpty()) return false; // SDK states that MP3 files could contain a BOM - never seen if ( *(const WORD *)(LPCWSTR)strValue == (WORD)0xFFFE || *(const WORD *)(LPCWSTR)strValue == (WORD)0xFEFF) { ASSERT(0); strValue = strValue.Mid(1); } return true; } ////////////////////////////////////////////////////////////////////////////// // CFileStream - Implements IStream interface on a file class CFileStream : public IStream { public: static HRESULT OpenFile(LPCTSTR pszFileName, IStream **ppStream, DWORD dwDesiredAccess = GENERIC_READ, DWORD dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE, DWORD dwCreationDisposition = OPEN_EXISTING, DWORD grfMode = STGM_READ | STGM_SHARE_DENY_NONE) { HANDLE hFile = CreateFile(pszFileName, dwDesiredAccess, dwShareMode, NULL, dwCreationDisposition, FILE_ATTRIBUTE_NORMAL, NULL); if (hFile == INVALID_HANDLE_VALUE) return HRESULT_FROM_WIN32(GetLastError()); CFileStream *pFileStream = new CFileStream(hFile, grfMode); return pFileStream->QueryInterface(__uuidof(*ppStream), (void **)ppStream); } /////////////////////////////////////////////////////////////////////////// // IUnknown STDMETHODIMP QueryInterface(REFIID iid, void **ppvObject) { if (iid == __uuidof(IUnknown) || iid == __uuidof(IStream) || iid == __uuidof(ISequentialStream)) { *ppvObject = static_cast<IStream *>(this); AddRef(); return S_OK; } return E_NOINTERFACE; } STDMETHODIMP_(ULONG) AddRef() { return (ULONG)InterlockedIncrement(&m_lRefCount); } STDMETHODIMP_(ULONG) Release() { ULONG ulRefCount = (ULONG)InterlockedDecrement(&m_lRefCount); if (ulRefCount == 0) delete this; return ulRefCount; } /////////////////////////////////////////////////////////////////////////// // ISequentialStream STDMETHODIMP Read(void *pv, ULONG cb, ULONG *pcbRead) { // If the stream was opened for 'write-only', no read access is allowed. if ((m_grfMode & 3) == STGM_WRITE) { ASSERT(0); return E_FAIL; } if (!ReadFile(m_hFile, pv, cb, pcbRead, NULL)) return HRESULT_FROM_WIN32(GetLastError()); // The specification of the 'IStream' interface allows to indicate an // end-of-stream condition by returning: // // HRESULT *pcbRead // ------------------------ // S_OK <less-than> 'cb' // S_FALSE <not used> // E_xxx <not used> // // If that object is used by the 'WMSyncReader', it seems to be better to // return an error code instead of 'S_OK'. // if (cb != 0 && *pcbRead == 0) return HRESULT_FROM_WIN32(ERROR_HANDLE_EOF); return S_OK; } STDMETHODIMP Write(void const *pv, ULONG cb, ULONG *pcbWritten) { // If the stream was opened for 'read-only', no write access is allowed. if ((m_grfMode & 3) == STGM_READ) { ASSERT(0); return E_FAIL; } ULONG cbWritten; if (!WriteFile(m_hFile, pv, cb, &cbWritten, NULL)) return HRESULT_FROM_WIN32(GetLastError()); if (pcbWritten != NULL) *pcbWritten = cbWritten; return S_OK; } /////////////////////////////////////////////////////////////////////////// // IStream STDMETHODIMP Seek(LARGE_INTEGER dlibMove, DWORD dwOrigin, ULARGE_INTEGER *plibNewPosition) { // 'dwOrigin' can get mapped to 'dwMoveMethod' ASSERT( STREAM_SEEK_SET == FILE_BEGIN ); ASSERT( STREAM_SEEK_CUR == FILE_CURRENT ); ASSERT( STREAM_SEEK_END == FILE_END ); LONG lNewFilePointerHi = dlibMove.HighPart; DWORD dwNewFilePointerLo = SetFilePointer(m_hFile, dlibMove.LowPart, &lNewFilePointerHi, dwOrigin); if (dwNewFilePointerLo == INVALID_SET_FILE_POINTER && GetLastError() != NO_ERROR) return HRESULT_FROM_WIN32(GetLastError()); if (plibNewPosition != NULL) { plibNewPosition->HighPart = lNewFilePointerHi; plibNewPosition->LowPart = dwNewFilePointerLo; } return S_OK; } STDMETHODIMP SetSize(ULARGE_INTEGER libNewSize) { ASSERT(0); UNREFERENCED_PARAMETER(libNewSize); return E_NOTIMPL; } STDMETHODIMP CopyTo(IStream *pstm, ULARGE_INTEGER cb, ULARGE_INTEGER *pcbRead, ULARGE_INTEGER *pcbWritten) { ASSERT(0); UNREFERENCED_PARAMETER(pstm); UNREFERENCED_PARAMETER(cb); UNREFERENCED_PARAMETER(pcbRead); UNREFERENCED_PARAMETER(pcbWritten); return E_NOTIMPL; } STDMETHODIMP Commit(DWORD grfCommitFlags) { ASSERT(0); UNREFERENCED_PARAMETER(grfCommitFlags); return E_NOTIMPL; } STDMETHODIMP Revert() { ASSERT(0); return E_NOTIMPL; } STDMETHODIMP LockRegion(ULARGE_INTEGER libOffset, ULARGE_INTEGER cb, DWORD dwLockType) { ASSERT(0); UNREFERENCED_PARAMETER(libOffset); UNREFERENCED_PARAMETER(cb); UNREFERENCED_PARAMETER(dwLockType); return E_NOTIMPL; } STDMETHODIMP UnlockRegion(ULARGE_INTEGER libOffset, ULARGE_INTEGER cb, DWORD dwLockType) { ASSERT(0); UNREFERENCED_PARAMETER(libOffset); UNREFERENCED_PARAMETER(cb); UNREFERENCED_PARAMETER(dwLockType); return E_NOTIMPL; } STDMETHODIMP Stat(STATSTG *pstatstg, DWORD grfStatFlag) { UNREFERENCED_PARAMETER(grfStatFlag); ASSERT( grfStatFlag == STATFLAG_NONAME ); memset(pstatstg, 0, sizeof(*pstatstg)); BY_HANDLE_FILE_INFORMATION fileInfo; if (!GetFileInformationByHandle(m_hFile, &fileInfo)) return HRESULT_FROM_WIN32(GetLastError()); pstatstg->type = STGTY_STREAM; pstatstg->cbSize.HighPart = fileInfo.nFileSizeHigh; pstatstg->cbSize.LowPart = fileInfo.nFileSizeLow; pstatstg->mtime = fileInfo.ftLastWriteTime; pstatstg->ctime = fileInfo.ftCreationTime; pstatstg->atime = fileInfo.ftLastAccessTime; pstatstg->grfMode = m_grfMode; return S_OK; } STDMETHODIMP Clone(IStream **ppstm) { ASSERT(0); UNREFERENCED_PARAMETER(ppstm); return E_NOTIMPL; } private: CFileStream(HANDLE hFile, DWORD grfMode) { m_lRefCount = 0; m_hFile = hFile; m_grfMode = grfMode; } ~CFileStream() { if (m_hFile != INVALID_HANDLE_VALUE) CloseHandle(m_hFile); } HANDLE m_hFile; DWORD m_grfMode; LONG m_lRefCount; }; class CWmvCoreDLL { public: CWmvCoreDLL() { m_bInitialized = false; m_hLib = NULL; m_pfnWMCreateEditor = NULL; m_pfnWMCreateSyncReader = NULL; } ~CWmvCoreDLL() { if (m_hLib) FreeLibrary(m_hLib); } bool Initialize() { if (!m_bInitialized) { m_bInitialized = true; // Support for WMVCORE.DLL depends on Windows version and WMP version. // // If WMP64 is installed, WMVCORE.DLL is not available. // If WMP9+ is installed, WMVCORE.DLL is available. // m_hLib = LoadLibrary(_T("wmvcore.dll")); if (m_hLib != NULL) { (FARPROC &)m_pfnWMCreateEditor = GetProcAddress(m_hLib, "WMCreateEditor"); (FARPROC &)m_pfnWMCreateSyncReader = GetProcAddress(m_hLib, "WMCreateSyncReader"); } } return m_pfnWMCreateEditor != NULL; } bool m_bInitialized; HMODULE m_hLib; HRESULT (STDMETHODCALLTYPE *m_pfnWMCreateEditor)(IWMMetadataEditor **ppEditor); HRESULT (STDMETHODCALLTYPE *m_pfnWMCreateSyncReader)(IUnknown *pUnkCert, DWORD dwRights, IWMSyncReader **ppSyncReader); }; static CWmvCoreDLL theWmvCoreDLL; BOOL GetWMHeaders(LPCTSTR pszFileName, SMediaInfo* mi, bool& rbIsWM, bool bFullInfo) { ASSERT( !bFullInfo || mi->strInfo.m_hWnd != NULL ); if (!theWmvCoreDLL.Initialize()) return FALSE; CComPtr<IUnknown> pIUnkReader; try { HRESULT hr = E_FAIL; // 1st, try to read the file with the 'WMEditor'. This object tends to give more (stream) information than the 'WMSyncReader'. // Though the 'WMEditor' is not capable of reading files which are currently opened for 'writing'. if (pIUnkReader == NULL) { CComPtr<IWMMetadataEditor> pIWMMetadataEditor; if (theWmvCoreDLL.m_pfnWMCreateEditor != NULL && (hr = (*theWmvCoreDLL.m_pfnWMCreateEditor)(&pIWMMetadataEditor)) == S_OK) { CComQIPtr<IWMMetadataEditor2> pIWMMetadataEditor2 = pIWMMetadataEditor; if (pIWMMetadataEditor2 && (hr = pIWMMetadataEditor2->OpenEx(pszFileName, GENERIC_READ, FILE_SHARE_READ)) == S_OK) pIUnkReader = pIWMMetadataEditor2; else if ((hr = pIWMMetadataEditor->Open(pszFileName)) == S_OK) pIUnkReader = pIWMMetadataEditor; } } // 2nd, try to read the file with 'WMSyncReader'. This may give less (stream) information than using the 'WMEditor', // but it has at least the advantage that one can provide the file data via an 'IStream' - which is needed for // reading files which are currently opened for 'writing'. // // However, the 'WMSyncReader' may take a noticeable amount of time to parse a few bytes of a stream. E.g. reading // the short MP3 test files from ID3Lib takes suspicious long time. So, invoke that 'WMSyncReader' only if we know // that the file could not get opened due to that it is currently opened for 'writing'. // // Note also: If the file is DRM protected, 'IWMSyncReader' may return an 'NS_E_PROTECTED_CONTENT' error. This makes // sense, because 'IWMSyncReader' does not know that we want to open the file for reading the meta data only. // This error code could get used to indicate 'protected' files. // if (pIUnkReader == NULL && hr == NS_E_FILE_OPEN_FAILED) { CComPtr<IWMSyncReader> pIWMSyncReader; if (theWmvCoreDLL.m_pfnWMCreateSyncReader != NULL && (hr = (*theWmvCoreDLL.m_pfnWMCreateSyncReader)(NULL, 0, &pIWMSyncReader)) == S_OK) { CComPtr<IStream> pIStream; if (CFileStream::OpenFile(pszFileName, &pIStream) == S_OK) { if ((hr = pIWMSyncReader->OpenStream(pIStream)) == S_OK) pIUnkReader = pIWMSyncReader; } } } else ASSERT( hr == S_OK || hr == NS_E_UNRECOGNIZED_STREAM_TYPE // general: unknown file type || hr == NS_E_INVALID_INPUT_FORMAT // general: unknown file type || hr == NS_E_INVALID_DATA // general: unknown file type || hr == NS_E_FILE_INIT_FAILED // got for an SWF file ? || hr == NS_E_FILE_READ // obviously if the file is too short ); if (pIUnkReader) { CComQIPtr<IWMHeaderInfo> pIWMHeaderInfo = pIUnkReader; if (pIWMHeaderInfo) { // Although it is not following any logic, using "IWMHeaderInfo3" instead of "IWMHeaderInfo" // gives a few more (important) stream properties !? // // NOTE: The existance of 'IWMHeaderInfo3' does not automatically mean that one will also // get 'WM/StreamTypeInfo'. // // Windows Vista SP1; WMP 11.0.6001.7000 // ------------------------------------- // WMASF.DLL 11.0.6001.7000 // WMVCORE.DLL 11.0.6001.7000 // --- // IWMHeaderInfo3: Yes // WM/StreamTypeInfo: Yes // Codec Info: Yes // // // Windows XP SP2; WMP 9.00.00.3354 // ------------------------------------- // WMASF.DLL 9.0.0.3267 // WMVCORE.DLL 9.0.0.3267 // --- // IWMHeaderInfo3: Yes // WM/StreamTypeInfo: No! // Codec Info: Yes // // // Windows 98 SE; WMP 9.00.00.3349 // ------------------------------------- // WMASF.DLL 9.00.00.2980 // WMVCORE.DLL 9.00.00.2980 // --- // IWMHeaderInfo3: Yes // WM/StreamTypeInfo: No! // Codec Info: Yes // CComQIPtr<IWMHeaderInfo3> pIWMHeaderInfo3 = pIUnkReader; WORD wStream = 0; // 0 = file level, 0xFFFF = all attributes from file and all streams DWORD dwContainer = (DWORD)-1; if (GetAttribute(pIWMHeaderInfo, wStream, g_wszWMContainerFormat, dwContainer)) { if (dwContainer == WMT_Storage_Format_MP3) { // The file is either a real MP3 file or a WAV file with an embedded MP3 stream. // // NOTE: The detection for MP3 is *NOT* safe. There are some MKV test files which // are reported as MP3 files although they contain more than just a MP3 stream. // This is no surprise, MP3 can not get detected safely in couple of cases. // // If that function is invoked for getting meta data which is to get published, // special care has to be taken for publishing the audio/video codec info. // We do not want to announce non-MP3 files as MP3 files by accident. // if (!bFullInfo) { LPCTSTR pszExt = PathFindExtension(pszFileName); if (pszExt && (_tcsicmp(pszExt, _T(".mp3")) != 0 && _tcsicmp(pszExt, _T(".mpa")) != 0 && _tcsicmp(pszExt, _T(".wav")) != 0)) throw new CNotSupportedException; } mi->strFileFormat = _T("MP3"); } else if (dwContainer == WMT_Storage_Format_V1) { mi->strFileFormat = _T("Windows Media"); rbIsWM = true; } else ASSERT(0); } else ASSERT(0); // WMFSDK 7.0 does not support the "WM/ContainerFormat" attribute at all. Though, // v7.0 has no importance any longer - it was originally shipped with WinME. // // If that function is invoked for getting meta data which is to get published, // special care has to be taken for publishing the audio/video codec info. // e.g. We do not want to announce non-MP3 files as MP3 files by accident. // if (!bFullInfo && dwContainer == (DWORD)-1) { ASSERT(0); throw new CNotSupportedException; } QWORD qwDuration = 0; if (GetAttribute(pIWMHeaderInfo, wStream, g_wszWMDuration, qwDuration)) { mi->fFileLengthSec = (double)(qwDuration / 10000000ui64); if (mi->fFileLengthSec < 1.0) mi->fFileLengthSec = 1.0; } else ASSERT(0); CString strValue; if (GetAttribute(pIWMHeaderInfo, wStream, g_wszWMTitle, strValue) && !strValue.IsEmpty()) mi->strTitle = strValue; if (GetAttribute(pIWMHeaderInfo, wStream, g_wszWMAuthor, strValue) && !strValue.IsEmpty()) mi->strAuthor = strValue; if (GetAttribute(pIWMHeaderInfo, wStream, g_wszWMAlbumTitle, strValue) && !strValue.IsEmpty()) mi->strAlbum = strValue; if (bFullInfo && mi->strInfo.m_hWnd) { WORD wAttributes; if (pIWMHeaderInfo->GetAttributeCount(wStream, &wAttributes) == S_OK && wAttributes != 0) { bool bOutputHeader = true; for (WORD wAttr = 0; wAttr < wAttributes; wAttr++) { WCHAR wszName[1024]; WORD wNameSize = _countof(wszName); WORD wDataSize; WMT_ATTR_DATATYPE attrType; if (pIWMHeaderInfo->GetAttributeByIndex(wAttr, &wStream, wszName, &wNameSize, &attrType, NULL, &wDataSize) == S_OK) { if (attrType == WMT_TYPE_STRING) { CString strValue; if (GetAttribute(pIWMHeaderInfo, wStream, wszName, strValue)) { strValue.Trim(); if (!strValue.IsEmpty()) { if (bOutputHeader) { bOutputHeader = false; if (!mi->strInfo.IsEmpty()) mi->strInfo << _T("\n"); mi->OutputFileName(); mi->strInfo.SetSelectionCharFormat(mi->strInfo.m_cfBold); mi->strInfo << GetResString(IDS_FD_GENERAL) << _T("\n"); } CString strName(wszName); if (wcsncmp(strName, L"WM/", 3) == 0) strName = strName.Mid(3); mi->strInfo << _T(" ") << strName << _T(":\t") << strValue << _T("\n"); } } } else if (attrType == WMT_TYPE_BOOL) { BOOL bValue; if (GetAttribute(pIWMHeaderInfo, wStream, wszName, bValue) && bValue) { if (bOutputHeader) { bOutputHeader = false; if (!mi->strInfo.IsEmpty()) mi->strInfo << _T("\n"); mi->OutputFileName(); mi->strInfo.SetSelectionCharFormat(mi->strInfo.m_cfBold); mi->strInfo << GetResString(IDS_FD_GENERAL) << _T("\n"); } CString strName(wszName); if (wcsncmp(strName, L"WM/", 3) == 0) strName = strName.Mid(3); bool bWarnInRed = wcscmp(wszName, g_wszWMProtected) == 0; if (bWarnInRed) mi->strInfo.SetSelectionCharFormat(mi->strInfo.m_cfRed); mi->strInfo << _T(" ") << strName << _T(":\t") << GetResString(IDS_YES) << _T("\n"); if (bWarnInRed) mi->strInfo.SetSelectionCharFormat(mi->strInfo.m_cfDef); } } } } } } while (wStream < 0x7F) { // Check if we reached the end of streams WORD wAttributes; if (pIWMHeaderInfo3) { if (pIWMHeaderInfo3->GetAttributeCountEx(wStream, &wAttributes) != S_OK) break; } else { if (pIWMHeaderInfo->GetAttributeCount(wStream, &wAttributes) != S_OK) break; } if (bFullInfo && mi->strAudioLanguage.IsEmpty()) { CString strLanguage; if (GetAttribute(pIWMHeaderInfo, wStream, g_wszWMLanguage, strLanguage)) mi->strAudioLanguage = strLanguage; } bool bHaveStreamInfo = false; if (pIWMHeaderInfo3) { // 'WM/StreamTypeInfo' is supported only since v10. This means that, WinXP/WMP9 does not have that support. CTempBuffer<BYTE> aStreamInfo; DWORD dwStreamInfoSize; if (GetAttributeEx(pIWMHeaderInfo3, wStream, g_wszWMStreamTypeInfo, aStreamInfo, dwStreamInfoSize) && dwStreamInfoSize >= sizeof(WM_STREAM_TYPE_INFO)) { const WM_STREAM_TYPE_INFO *pStreamTypeInfo = (WM_STREAM_TYPE_INFO *)(BYTE *)aStreamInfo; if (pStreamTypeInfo->guidMajorType == WMMEDIATYPE_Video) { bHaveStreamInfo = true; mi->iVideoStreams++; if ( dwStreamInfoSize >= sizeof(WM_STREAM_TYPE_INFO) + sizeof(WMVIDEOINFOHEADER) && pStreamTypeInfo->cbFormat >= sizeof(WMVIDEOINFOHEADER)) { const WMVIDEOINFOHEADER *pVideoInfo = (WMVIDEOINFOHEADER *)(pStreamTypeInfo + 1); ASSERT( sizeof(VIDEOINFOHEADER) == sizeof(WMVIDEOINFOHEADER) ); if (pVideoInfo->bmiHeader.biSize >= sizeof(pVideoInfo->bmiHeader)) { if (mi->iVideoStreams == 1) { mi->video = *(const VIDEOINFOHEADER *)pVideoInfo; if (mi->video.bmiHeader.biWidth && mi->video.bmiHeader.biHeight) mi->fVideoAspectRatio = (float)abs(mi->video.bmiHeader.biWidth) / (float)abs(mi->video.bmiHeader.biHeight); mi->strVideoFormat = GetVideoFormatName(pVideoInfo->bmiHeader.biCompression); if ( pVideoInfo->bmiHeader.biCompression == MAKEFOURCC('D','V','R',' ') && pVideoInfo->bmiHeader.biSize >= sizeof(pVideoInfo->bmiHeader) + sizeof(WMMPEG2VIDEOINFO) && dwStreamInfoSize >= sizeof(WM_STREAM_TYPE_INFO) + sizeof(WMVIDEOINFOHEADER) + sizeof(WMMPEG2VIDEOINFO) && pStreamTypeInfo->cbFormat >= sizeof(WMVIDEOINFOHEADER) + sizeof(WMMPEG2VIDEOINFO)) { const WMMPEG2VIDEOINFO *pMPEG2VideoInfo = (WMMPEG2VIDEOINFO *)(pVideoInfo + 1); if ( pMPEG2VideoInfo->hdr.bmiHeader.biSize >= sizeof(pMPEG2VideoInfo->hdr.bmiHeader) && pMPEG2VideoInfo->hdr.bmiHeader.biCompression != 0 && pMPEG2VideoInfo->hdr.bmiHeader.biWidth == pVideoInfo->bmiHeader.biWidth && pMPEG2VideoInfo->hdr.bmiHeader.biHeight == pVideoInfo->bmiHeader.biHeight) { if (!IsRectEmpty(&pMPEG2VideoInfo->hdr.rcSource)) mi->video.rcSource = pMPEG2VideoInfo->hdr.rcSource; if (!IsRectEmpty(&pMPEG2VideoInfo->hdr.rcTarget)) mi->video.rcTarget = pMPEG2VideoInfo->hdr.rcTarget; if (pMPEG2VideoInfo->hdr.dwBitRate) mi->video.dwBitRate = pMPEG2VideoInfo->hdr.dwBitRate; if (pMPEG2VideoInfo->hdr.dwBitErrorRate) mi->video.dwBitErrorRate = pMPEG2VideoInfo->hdr.dwBitErrorRate; if (pMPEG2VideoInfo->hdr.AvgTimePerFrame) mi->video.AvgTimePerFrame = pMPEG2VideoInfo->hdr.AvgTimePerFrame; mi->video.bmiHeader = pMPEG2VideoInfo->hdr.bmiHeader; mi->strVideoFormat = GetVideoFormatName(mi->video.bmiHeader.biCompression); if (pMPEG2VideoInfo->hdr.dwPictAspectRatioX != 0 && pMPEG2VideoInfo->hdr.dwPictAspectRatioY != 0) mi->fVideoAspectRatio = (float)pMPEG2VideoInfo->hdr.dwPictAspectRatioX / (float)pMPEG2VideoInfo->hdr.dwPictAspectRatioY; else if (mi->video.bmiHeader.biWidth && mi->video.bmiHeader.biHeight) mi->fVideoAspectRatio = (float)abs(mi->video.bmiHeader.biWidth) / (float)abs(mi->video.bmiHeader.biHeight); } } if (mi->fVideoFrameRate == 0.0 && mi->video.AvgTimePerFrame) mi->fVideoFrameRate = 1.0 / (mi->video.AvgTimePerFrame / 10000000.0); } else if (bFullInfo && mi->strInfo.m_hWnd) { mi->OutputFileName(); if (!mi->strInfo.IsEmpty()) mi->strInfo << _T("\n"); mi->strInfo.SetSelectionCharFormat(mi->strInfo.m_cfBold); mi->strInfo << GetResString(IDS_VIDEO) << _T(" #") << mi->iVideoStreams << _T("\n"); mi->strInfo << _T(" ") << GetResString(IDS_CODEC) << _T(":\t") << GetVideoFormatName(pVideoInfo->bmiHeader.biCompression) << _T("\n"); if (pVideoInfo->dwBitRate) mi->strInfo << _T(" ") << GetResString(IDS_BITRATE) << _T(":\t") << (UINT)((pVideoInfo->dwBitRate + 500) / 1000) << _T(" kBit/s\n"); mi->strInfo << _T(" ") << GetResString(IDS_WIDTH) << _T(" x ") << GetResString(IDS_HEIGHT) << _T(":\t") << abs(pVideoInfo->bmiHeader.biWidth) << _T(" x ") << abs(pVideoInfo->bmiHeader.biHeight) << _T("\n"); float fAspectRatio = (float)abs(pVideoInfo->bmiHeader.biWidth) / (float)abs(pVideoInfo->bmiHeader.biHeight); mi->strInfo << _T(" ") << GetResString(IDS_ASPECTRATIO) << _T(":\t") << fAspectRatio << _T(" (") << GetKnownAspectRatioDisplayString(fAspectRatio) << _T(")\n"); if (pVideoInfo->AvgTimePerFrame) { float fFrameRate = 1.0f / (pVideoInfo->AvgTimePerFrame / 10000000.0f); mi->strInfo << _T(" ") << GetResString(IDS_FPS) << _T(":\t") << fFrameRate << ("\n"); } } } } if (mi->iVideoStreams == 1) { if (mi->video.dwBitRate == 0) { DWORD dwValue; if (GetAttributeEx(pIWMHeaderInfo3, wStream, g_wszWMPeakBitrate, dwValue)) mi->video.dwBitRate = dwValue; } } } else if (pStreamTypeInfo->guidMajorType == WMMEDIATYPE_Audio) { bHaveStreamInfo = true; mi->iAudioStreams++; if ( dwStreamInfoSize >= sizeof(WM_STREAM_TYPE_INFO) + sizeof(WAVEFORMATEX) && pStreamTypeInfo->cbFormat >= sizeof(WAVEFORMATEX)) { const WAVEFORMATEX *pWaveFormatEx = (WAVEFORMATEX *)(pStreamTypeInfo + 1); ASSERT( sizeof(WAVEFORMAT) == sizeof(WAVEFORMATEX) - sizeof(WORD)*2 ); if (mi->iAudioStreams == 1) { mi->audio = *(const WAVEFORMAT *)pWaveFormatEx; mi->strAudioFormat = GetAudioFormatName(pWaveFormatEx->wFormatTag); } else if (bFullInfo && mi->strInfo.m_hWnd) { if (!mi->strInfo.IsEmpty()) mi->strInfo << _T("\n"); mi->OutputFileName(); mi->strInfo.SetSelectionCharFormat(mi->strInfo.m_cfBold); mi->strInfo << GetResString(IDS_AUDIO) << _T(" #") << mi->iAudioStreams << _T("\n"); mi->strInfo << _T(" ") << GetResString(IDS_CODEC) << _T(":\t") << GetAudioFormatName(pWaveFormatEx->wFormatTag) << _T("\n"); if (pWaveFormatEx->nAvgBytesPerSec) { CString strBitrate; if (pWaveFormatEx->nAvgBytesPerSec == (DWORD)-1) strBitrate = _T("Variable"); else strBitrate.Format(_T("%u %s"), (UINT)(((pWaveFormatEx->nAvgBytesPerSec * 8.0) + 500.0) / 1000.0), GetResString(IDS_KBITSSEC)); mi->strInfo << _T(" ") << GetResString(IDS_BITRATE) << _T(":\t") << strBitrate << _T("\n"); } if (pWaveFormatEx->nChannels) { mi->strInfo << _T(" ") << GetResString(IDS_CHANNELS) << _T(":\t"); if (pWaveFormatEx->nChannels == 1) mi->strInfo << _T("1 (Mono)"); else if (pWaveFormatEx->nChannels == 2) mi->strInfo << _T("2 (Stereo)"); else if (pWaveFormatEx->nChannels == 5) mi->strInfo << _T("5.1 (Surround)"); else mi->strInfo << pWaveFormatEx->nChannels; mi->strInfo << _T("\n"); } if (pWaveFormatEx->nSamplesPerSec) mi->strInfo << _T(" ") << GetResString(IDS_SAMPLERATE) << _T(":\t") << pWaveFormatEx->nSamplesPerSec / 1000.0 << _T(" kHz\n"); if (pWaveFormatEx->wBitsPerSample) mi->strInfo << _T(" Bit/sample:\t") << pWaveFormatEx->wBitsPerSample << _T(" Bit\n"); } } if (mi->iAudioStreams == 1) { if (mi->audio.nAvgBytesPerSec == 0) { DWORD dwValue; if (GetAttributeEx(pIWMHeaderInfo3, wStream, g_wszWMPeakBitrate, dwValue)) mi->audio.nAvgBytesPerSec = dwValue / 8; } } } else if (bFullInfo && mi->strInfo.m_hWnd) { bHaveStreamInfo = true; mi->OutputFileName(); if (!mi->strInfo.IsEmpty()) mi->strInfo << _T("\n"); mi->strInfo.SetSelectionCharFormat(mi->strInfo.m_cfBold); if (pStreamTypeInfo->guidMajorType == WMMEDIATYPE_Script) { mi->strInfo << _T("Script Stream #") << (UINT)wStream << _T("\n"); } else if (pStreamTypeInfo->guidMajorType == WMMEDIATYPE_Image) { mi->strInfo << _T("Image Stream #") << (UINT)wStream << _T("\n"); } else if (pStreamTypeInfo->guidMajorType == WMMEDIATYPE_FileTransfer) { mi->strInfo << _T("File Transfer Stream #") << (UINT)wStream << _T("\n"); } else if (pStreamTypeInfo->guidMajorType == WMMEDIATYPE_Text) { mi->strInfo << _T("Text Stream #") << (UINT)wStream << _T("\n"); } else { mi->strInfo << _T("Unknown Stream #") << (UINT)wStream << _T("\n"); } DWORD dwValue; if (GetAttributeEx(pIWMHeaderInfo3, wStream, g_wszWMPeakBitrate, dwValue) && dwValue != 0) mi->strInfo << _T(" ") << GetResString(IDS_BITRATE) << _T(":\t") << (UINT)((dwValue + 500) / 1000) << _T(" kBit/s\n"); } } } if (wStream > 0 && !bHaveStreamInfo) { WMT_CODEC_INFO_TYPE streamCodecType = WMT_CODECINFO_UNKNOWN; CString strStreamType; CString strStreamInfo; CString strDevTempl; if (GetAttribute(pIWMHeaderInfo, wStream, g_wszDeviceConformanceTemplate, strDevTempl)) { strStreamInfo = strDevTempl + L": "; if (strDevTempl == L"L") { streamCodecType = WMT_CODECINFO_AUDIO; strStreamType = GetResString(IDS_AUDIO); strStreamInfo += L"All bit rates"; } else if (strDevTempl == L"L1") { streamCodecType = WMT_CODECINFO_AUDIO; strStreamType = GetResString(IDS_AUDIO); strStreamInfo += L"64 - 160 kBit/s"; } else if (strDevTempl == L"L2") { streamCodecType = WMT_CODECINFO_AUDIO; strStreamType = GetResString(IDS_AUDIO); strStreamInfo += L"<= 160 kBit/s"; } else if (strDevTempl == L"L3") { streamCodecType = WMT_CODECINFO_AUDIO; strStreamType = GetResString(IDS_AUDIO); strStreamInfo += L"<= 384 kBit/s"; } else if (strDevTempl == L"S1") { streamCodecType = WMT_CODECINFO_AUDIO; strStreamType = GetResString(IDS_AUDIO); strStreamInfo += L"<= 20 kBit/s"; } else if (strDevTempl == L"S2") { streamCodecType = WMT_CODECINFO_AUDIO; strStreamType = GetResString(IDS_AUDIO); strStreamInfo += L"<= 20 kBit/s"; } else if (strDevTempl == L"M") { streamCodecType = WMT_CODECINFO_AUDIO; strStreamType = GetResString(IDS_AUDIO); strStreamInfo += L"All bit rates"; } else if (strDevTempl == L"M1") { streamCodecType = WMT_CODECINFO_AUDIO; strStreamType = GetResString(IDS_AUDIO); strStreamInfo += L"<= 384 kBit/s, <= 48 kHz"; } else if (strDevTempl == L"M2") { streamCodecType = WMT_CODECINFO_AUDIO; strStreamType = GetResString(IDS_AUDIO); strStreamInfo += L"<= 768 kBit/s, <= 96 kHz"; } else if (strDevTempl == L"M3") { streamCodecType = WMT_CODECINFO_AUDIO; strStreamType = GetResString(IDS_AUDIO); strStreamInfo += L"<= 1500 kBit/s, <= 96 kHz"; } else if (strDevTempl == L"SP@LL") { streamCodecType = WMT_CODECINFO_VIDEO; strStreamType = GetResString(IDS_VIDEO); strStreamInfo += L"Simple Profile, Low Level, <= 176 x 144, <= 96 kBit/s"; } else if (strDevTempl == L"SP@ML") { streamCodecType = WMT_CODECINFO_VIDEO; strStreamType = GetResString(IDS_VIDEO); strStreamInfo += L"Simple Profile, Medium Level, <= 352 x 288, <= 384 kBit/s"; } else if (strDevTempl == L"MP@LL") { streamCodecType = WMT_CODECINFO_VIDEO; strStreamType = GetResString(IDS_VIDEO); strStreamInfo += L"Main Profile, Low Level, <= 352 x 288, 2 MBit/s"; } else if (strDevTempl == L"MP@ML") { streamCodecType = WMT_CODECINFO_VIDEO; strStreamType = GetResString(IDS_VIDEO); strStreamInfo += L"Main Profile, Medium Level, <= 720 x 576, 10 MBit/s"; } else if (strDevTempl == L"MP@HL") { streamCodecType = WMT_CODECINFO_VIDEO; strStreamType = GetResString(IDS_VIDEO); strStreamInfo += L"Main Profile, High Level, <= 1920 x 1080, 20 MBit/s"; } else if (strDevTempl == L"CP") { streamCodecType = WMT_CODECINFO_VIDEO; strStreamType = GetResString(IDS_VIDEO); strStreamInfo += L"Complex Profile"; } else if (strDevTempl == L"I1") { streamCodecType = WMT_CODECINFO_VIDEO; strStreamType = GetResString(IDS_VIDEO); strStreamInfo += L"Video Image Level 1, <= 352 x 288, 192 kBit/s"; } else if (strDevTempl == L"I2") { streamCodecType = WMT_CODECINFO_VIDEO; strStreamType = GetResString(IDS_VIDEO); strStreamInfo += L"Video Image Level 2, <= 1024 x 768, 384 kBit/s"; } else if (strDevTempl == L"I") { streamCodecType = WMT_CODECINFO_VIDEO; strStreamType = GetResString(IDS_VIDEO); strStreamInfo += L"Generic Video Image"; } } DWORD dwCodecId = (DWORD)-1; CString strCodecName; CString strCodecDesc; if (streamCodecType != WMT_CODECINFO_UNKNOWN) { CComQIPtr<IWMHeaderInfo2> pIWMHeaderInfo2 = pIUnkReader; if (pIWMHeaderInfo2) { DWORD dwCodecInfos; if ((hr = pIWMHeaderInfo2->GetCodecInfoCount(&dwCodecInfos)) == S_OK) { for (DWORD dwCodec = 0; dwCodec < dwCodecInfos; dwCodec++) { WORD wNameSize; WORD wDescSize; WORD wCodecInfoSize; WMT_CODEC_INFO_TYPE codecType; hr = pIWMHeaderInfo2->GetCodecInfo(dwCodec, &wNameSize, NULL, &wDescSize, NULL, &codecType, &wCodecInfoSize, NULL); if (hr == S_OK && codecType == streamCodecType) { CString strName; CString strDesc; CTempBuffer<BYTE> aCodecInfo; hr = pIWMHeaderInfo2->GetCodecInfo(dwCodec, &wNameSize, bFullInfo ? strName.GetBuffer(wNameSize) : NULL, &wDescSize, bFullInfo ? strDesc.GetBuffer(wDescSize) : NULL, &codecType, &wCodecInfoSize, aCodecInfo.Allocate(wCodecInfoSize)); strName.ReleaseBuffer(); strName.Trim(); strDesc.ReleaseBuffer(); strDesc.Trim(); if (hr == S_OK) { strCodecName = strName; strCodecDesc = strDesc; if (codecType == WMT_CODECINFO_AUDIO) { if (wCodecInfoSize == sizeof(WORD)) { dwCodecId = *(WORD *)(BYTE *)aCodecInfo; } else ASSERT(0); } else if (codecType == WMT_CODECINFO_VIDEO) { if (wCodecInfoSize == sizeof(DWORD)) { dwCodecId = *(DWORD *)(BYTE *)aCodecInfo; } else ASSERT(0); } else ASSERT(0); } else ASSERT(0); break; } } } } } // Depending on the installed WMFSDK version and depending on the WMFSDK which // was used to create the WM file, we still may be missing the stream type info. // So, don't bother with printing 'Unknown' info. if (!strStreamType.IsEmpty()) { DWORD dwBitrate = 0; GetAttributeEx(pIWMHeaderInfo3, wStream, g_wszWMPeakBitrate, dwBitrate); if (streamCodecType == WMT_CODECINFO_VIDEO) { mi->iVideoStreams++; if (mi->iVideoStreams == 1) { mi->video.bmiHeader.biCompression = dwCodecId; mi->strVideoFormat = GetVideoFormatName(dwCodecId); mi->video.dwBitRate = dwBitrate; if (bFullInfo && mi->strInfo.m_hWnd) { mi->OutputFileName(); if (!mi->strInfo.IsEmpty()) mi->strInfo << _T("\n"); mi->strInfo.SetSelectionCharFormat(mi->strInfo.m_cfBold); mi->strInfo << GetResString(IDS_VIDEO) << _T(" #") << mi->iVideoStreams << _T("\n"); if (!strCodecName.IsEmpty()) mi->strInfo << _T(" ") << GetResString(IDS_SW_NAME) << _T(":\t") << strCodecName << _T("\n"); if (!strCodecDesc.IsEmpty()) mi->strInfo << _T(" ") << GetResString(IDS_DESCRIPTION) << _T(":\t") << strCodecDesc << _T("\n"); if (!strStreamInfo.IsEmpty()) mi->strInfo << _T(" ") << L"Device Conformance:\t" << strStreamInfo << _T("\n"); } } else if (bFullInfo && mi->strInfo.m_hWnd) { mi->OutputFileName(); if (!mi->strInfo.IsEmpty()) mi->strInfo << _T("\n"); mi->strInfo.SetSelectionCharFormat(mi->strInfo.m_cfBold); mi->strInfo << GetResString(IDS_VIDEO) << _T(" #") << mi->iVideoStreams << _T("\n"); mi->strInfo << _T(" ") << GetResString(IDS_CODEC) << _T(":\t") << GetVideoFormatName(dwCodecId) << _T("\n"); if (!strCodecName.IsEmpty()) mi->strInfo << _T(" ") << GetResString(IDS_SW_NAME) << _T(":\t") << strCodecName << _T("\n"); if (!strCodecDesc.IsEmpty()) mi->strInfo << _T(" ") << GetResString(IDS_DESCRIPTION) << _T(":\t") << strCodecDesc << _T("\n"); if (!strStreamInfo.IsEmpty()) mi->strInfo << _T(" ") << L"Device Conformance:\t" << strStreamInfo << _T("\n"); if (dwBitrate) mi->strInfo << _T(" ") << GetResString(IDS_BITRATE) << _T(":\t") << (UINT)((dwBitrate + 500) / 1000) << _T(" kBit/s\n"); } } else if (streamCodecType == WMT_CODECINFO_AUDIO) { mi->iAudioStreams++; if (mi->iAudioStreams == 1) { mi->audio.wFormatTag = (WORD)dwCodecId; mi->strAudioFormat = GetAudioFormatName((WORD)dwCodecId); mi->audio.nAvgBytesPerSec = dwBitrate / 8; if (bFullInfo && mi->strInfo.m_hWnd) { if (!mi->strInfo.IsEmpty()) mi->strInfo << _T("\n"); mi->OutputFileName(); mi->strInfo.SetSelectionCharFormat(mi->strInfo.m_cfBold); mi->strInfo << GetResString(IDS_AUDIO) << _T(" #") << mi->iAudioStreams << _T("\n"); if (!strCodecName.IsEmpty()) mi->strInfo << _T(" ") << GetResString(IDS_SW_NAME) << _T(":\t") << strCodecName << _T("\n"); if (!strCodecDesc.IsEmpty()) mi->strInfo << _T(" ") << GetResString(IDS_DESCRIPTION) << _T(":\t") << strCodecDesc << _T("\n"); if (!strStreamInfo.IsEmpty()) mi->strInfo << _T(" ") << L"Device Conformance:\t" << strStreamInfo << _T("\n"); } } else if (bFullInfo && mi->strInfo.m_hWnd) { if (!mi->strInfo.IsEmpty()) mi->strInfo << _T("\n"); mi->OutputFileName(); mi->strInfo.SetSelectionCharFormat(mi->strInfo.m_cfBold); mi->strInfo << GetResString(IDS_AUDIO) << _T(" #") << mi->iAudioStreams << _T("\n"); mi->strInfo << _T(" ") << GetResString(IDS_CODEC) << _T(":\t") << GetAudioFormatName((WORD)dwCodecId) << _T("\n"); if (!strCodecName.IsEmpty()) mi->strInfo << _T(" ") << GetResString(IDS_SW_NAME) << _T(":\t") << strCodecName << _T("\n"); if (!strCodecDesc.IsEmpty()) mi->strInfo << _T(" ") << GetResString(IDS_DESCRIPTION) << _T(":\t") << strCodecDesc << _T("\n"); if (!strStreamInfo.IsEmpty()) mi->strInfo << _T(" ") << L"Device Conformance:\t" << strStreamInfo << _T("\n"); if (dwBitrate) mi->strInfo << _T(" ") << GetResString(IDS_BITRATE) << _T(":\t") << (UINT)((dwBitrate + 500) / 1000) << _T(" kBit/s\n"); } } else if (bFullInfo && mi->strInfo.m_hWnd) { mi->OutputFileName(); if (!mi->strInfo.IsEmpty()) mi->strInfo << _T("\n"); mi->strInfo.SetSelectionCharFormat(mi->strInfo.m_cfBold); mi->strInfo << L"Stream #" << (UINT)wStream << L": " << strStreamType << _T("\n"); if (!strStreamInfo.IsEmpty()) mi->strInfo << _T(" ") << L"Device Conformance:\t" << strStreamInfo << _T("\n"); if (dwBitrate) mi->strInfo << _T(" ") << GetResString(IDS_BITRATE) << _T(":\t") << (UINT)((dwBitrate + 500) / 1000) << _T(" kBit/s\n"); } } } wStream++; } // 'IWMHeaderInfo3' may not have returned any 'WM/StreamTypeInfo' attributes. If the WM file // indicates the existance of Audio/Video streams, try to query for the codec info. // if (mi->iAudioStreams == 0 && mi->iVideoStreams == 0) { BOOL bHasAudio = FALSE; GetAttribute(pIWMHeaderInfo, 0, g_wszWMHasAudio, bHasAudio); BOOL bHasVideo = FALSE; GetAttribute(pIWMHeaderInfo, 0, g_wszWMHasVideo, bHasVideo); if (bHasAudio || bHasVideo) { CComQIPtr<IWMHeaderInfo2> pIWMHeaderInfo2 = pIUnkReader; if (pIWMHeaderInfo2) { DWORD dwCodecInfos; HRESULT hr; if ((hr = pIWMHeaderInfo2->GetCodecInfoCount(&dwCodecInfos)) == S_OK) { bool bAddedBakedAudioStream = false; bool bAddedBakedVideoStream = false; for (DWORD dwCodec = 0; dwCodec < dwCodecInfos; dwCodec++) { WORD wNameSize; WORD wDescSize; WORD wCodecInfoSize; WMT_CODEC_INFO_TYPE codecType; hr = pIWMHeaderInfo2->GetCodecInfo(dwCodec, &wNameSize, NULL, &wDescSize, NULL, &codecType, &wCodecInfoSize, NULL); if (hr == S_OK) { CString strName; CString strDesc; CTempBuffer<BYTE> aCodecInfo; hr = pIWMHeaderInfo2->GetCodecInfo(dwCodec, &wNameSize, bFullInfo ? strName.GetBuffer(wNameSize) : NULL, &wDescSize, bFullInfo ? strDesc.GetBuffer(wDescSize) : NULL, &codecType, &wCodecInfoSize, aCodecInfo.Allocate(wCodecInfoSize)); strName.ReleaseBuffer(); strName.Trim(); strDesc.ReleaseBuffer(); strDesc.Trim(); if (hr == S_OK) { if (bHasAudio && codecType == WMT_CODECINFO_AUDIO) { if (wCodecInfoSize == sizeof(WORD)) { if (!bAddedBakedAudioStream) { bAddedBakedAudioStream = true; mi->iAudioStreams++; mi->audio.wFormatTag = *(WORD *)(BYTE *)aCodecInfo; mi->strAudioFormat = GetAudioFormatName(mi->audio.wFormatTag); if (bFullInfo && mi->strInfo.m_hWnd && (!strName.IsEmpty() || !strDesc.IsEmpty())) { mi->OutputFileName(); if (!mi->strInfo.IsEmpty()) mi->strInfo << _T("\n"); mi->strInfo.SetSelectionCharFormat(mi->strInfo.m_cfBold); mi->strInfo << GetResString(IDS_AUDIO) << _T("\n"); if (!strName.IsEmpty()) mi->strInfo << _T(" ") << GetResString(IDS_SW_NAME) << _T(":\t") << strName << _T("\n"); if (!strDesc.IsEmpty()) mi->strInfo << _T(" ") << GetResString(IDS_DESCRIPTION) << _T(":\t") << strDesc << _T("\n"); } } else ASSERT(0); } else if (wCodecInfoSize == 0 && dwContainer == WMT_Storage_Format_MP3) { // MP3 files: no codec info returned if (!bAddedBakedAudioStream) { bAddedBakedAudioStream = true; mi->iAudioStreams++; mi->audio.wFormatTag = WAVE_FORMAT_MPEGLAYER3; mi->strAudioFormat = GetAudioFormatName(mi->audio.wFormatTag); if (bFullInfo && mi->strInfo.m_hWnd && (!strName.IsEmpty() || !strDesc.IsEmpty())) { mi->OutputFileName(); if (!mi->strInfo.IsEmpty()) mi->strInfo << _T("\n"); mi->strInfo.SetSelectionCharFormat(mi->strInfo.m_cfBold); mi->strInfo << GetResString(IDS_AUDIO) << _T("\n"); if (!strName.IsEmpty()) mi->strInfo << _T(" ") << GetResString(IDS_SW_NAME) << _T(":\t") << strName << _T("\n"); if (!strDesc.IsEmpty()) mi->strInfo << _T(" ") << GetResString(IDS_DESCRIPTION) << _T(":\t") << strDesc << _T("\n"); } } else ASSERT(0); } else ASSERT(0); } else if (bHasVideo && codecType == WMT_CODECINFO_VIDEO) { if (wCodecInfoSize == sizeof(DWORD)) { if (!bAddedBakedVideoStream) { bAddedBakedVideoStream = true; mi->iVideoStreams++; mi->video.bmiHeader.biCompression = *(DWORD *)(BYTE *)aCodecInfo; mi->strVideoFormat = GetVideoFormatName(mi->video.bmiHeader.biCompression); if (bFullInfo && mi->strInfo.m_hWnd && (!strName.IsEmpty() || !strDesc.IsEmpty())) { mi->OutputFileName(); if (!mi->strInfo.IsEmpty()) mi->strInfo << _T("\n"); mi->strInfo.SetSelectionCharFormat(mi->strInfo.m_cfBold); mi->strInfo << GetResString(IDS_VIDEO) << _T("\n"); if (!strName.IsEmpty()) mi->strInfo << _T(" ") << GetResString(IDS_SW_NAME) << _T(":\t") << strName << _T("\n"); if (!strDesc.IsEmpty()) mi->strInfo << _T(" ") << GetResString(IDS_DESCRIPTION) << _T(":\t") << strDesc << _T("\n"); } } else ASSERT(0); } else ASSERT(0); } else ASSERT(0); } } } } } } } if (dwContainer == WMT_Storage_Format_V1) { if (mi->iAudioStreams == 1 && mi->iVideoStreams == 0 && (mi->audio.nAvgBytesPerSec == 0 || mi->audio.nAvgBytesPerSec == (UINT)-1)) { DWORD dwCurrentBitrate; if (GetAttribute(pIWMHeaderInfo, 0, g_wszWMCurrentBitrate, dwCurrentBitrate) && dwCurrentBitrate) mi->audio.nAvgBytesPerSec = dwCurrentBitrate / 8; } else if (mi->iAudioStreams == 0 && mi->iVideoStreams == 1 && (mi->video.dwBitRate == 0 || mi->video.dwBitRate == (DWORD)-1)) { DWORD dwCurrentBitrate; if (GetAttribute(pIWMHeaderInfo, 0, g_wszWMCurrentBitrate, dwCurrentBitrate) && dwCurrentBitrate) mi->video.dwBitRate = dwCurrentBitrate; } } else if (dwContainer == WMT_Storage_Format_MP3) { if (mi->iAudioStreams == 1 && mi->iVideoStreams == 0 && (mi->audio.nAvgBytesPerSec == 0 || mi->audio.nAvgBytesPerSec == (UINT)-1)) { // CBR MP3 stream: The average bitrate is equal to the nominal bitrate // // VBR MP3 stream: The average bitrate is usually not equal to the nominal // bitrate (sometimes even quite way off). However, the average bitrate is // always a reasonable value, thus it is the preferred value for the bitrate. // // MP3 streams which are enveloped in a WAV file: some WM-bitrates are simply 0 ! // // Conclusio: For MP3 files always prefer the average bitrate, if available. // DWORD dwCurrentBitrate; if (GetAttribute(pIWMHeaderInfo, 0, g_wszWMCurrentBitrate, dwCurrentBitrate) && dwCurrentBitrate) mi->audio.nAvgBytesPerSec = dwCurrentBitrate / 8; } } } } } catch(CException *ex) { ASSERT( ex->IsKindOf(RUNTIME_CLASS(CNotSupportedException)) ); ex->Delete(); } if (pIUnkReader) { CComQIPtr<IWMMetadataEditor> pIWMMetadataEditor(pIUnkReader); if (pIWMMetadataEditor) VERIFY( pIWMMetadataEditor->Close() == S_OK ); } if (pIUnkReader) { CComQIPtr<IWMSyncReader> pIWMSyncReader(pIUnkReader); if (pIWMSyncReader) VERIFY( pIWMSyncReader->Close() == S_OK ); } return mi->iAudioStreams > 0 || mi->iVideoStreams > 0 || mi->fFileLengthSec > 0 || !mi->strAlbum.IsEmpty() || !mi->strAuthor.IsEmpty() || !mi->strTitle.IsEmpty(); } #endif//HAVE_WMSDK_H bool GetMimeType(LPCTSTR pszFilePath, CString& rstrMimeType) { int fd = _topen(pszFilePath, O_RDONLY | O_BINARY); if (fd != -1) { BYTE aucBuff[8192]; int iRead = _read(fd, aucBuff, sizeof aucBuff); _close(fd); fd = -1; if (iRead > 0) { // Supports only 26 hardcoded types - and some more (undocumented) // --------------------------------------------------------------- // x text/richtext .rtf // x text/html .html // x text/xml .xml // . audio/x-aiff // . audio/basic // x audio/wav .wav // x audio/mid .mid // x image/gif .gif // . image/jpeg ( never seen, all .jpg files are "image/pjpeg" ) // x image/pjpeg // . image/tiff ( never seen, all .tif files failed ??? ) // x image/x-png .png // . image/x-xbitmap // x image/bmp .bmp // . image/x-jg // x image/x-emf .emf // x image/x-wmf .wmf // x video/avi .avi // x video/mpeg .mpg // x application/postscript .ps // x application/base64 .b64 // x application/macbinhex40 .hqx // x application/pdf .pdf // . application/x-compressed // x application/x-zip-compressed .zip // x application/x-gzip-compressed .gz // x application/java .class // x application/x-msdownload .exe .dll // #define FMFD_DEFAULT 0x00000000 // No flags specified. Use default behavior for the function. #define FMFD_URLASFILENAME 0x00000001 // Treat the specified pwzUrl as a file name. #ifndef FMFD_ENABLEMIMESNIFFING #define FMFD_ENABLEMIMESNIFFING 0x00000002 // XP SP2 - Use MIME-type detection even if FEATURE_MIME_SNIFFING is detected. Usually, this feature control key would disable MIME-type detection. #define FMFD_IGNOREMIMETEXTPLAIN 0x00000004 // XP SP2 - Perform MIME-type detection if "text/plain" is proposed, even if data sniffing is otherwise disabled. #endif // Don't pass the file name to 'FindMimeFromData'. In case 'FindMimeFromData' can not determine the MIME type // from sniffing the header data it will parse the passed file name's extension to guess the MIME type. // That's basically OK for browser mode, but we can't use that here. LPWSTR pwszMime = NULL; HRESULT hr = FindMimeFromData(NULL, NULL/*pszFilePath*/, aucBuff, iRead, NULL, FMFD_ENABLEMIMESNIFFING | FMFD_IGNOREMIMETEXTPLAIN, &pwszMime, 0); // "application/octet-stream" ... means general "binary" file // "text/plain" ... means general "text" file if (SUCCEEDED(hr) && pwszMime != NULL && wcscmp(pwszMime, L"application/octet-stream") != 0) { rstrMimeType = pwszMime; return true; } // RAR file type if (iRead >= 7 && aucBuff[0] == 0x52) { if ( (aucBuff[1] == 0x45 && aucBuff[2] == 0x7e && aucBuff[3] == 0x5e) || (aucBuff[1] == 0x61 && aucBuff[2] == 0x72 && aucBuff[3] == 0x21 && aucBuff[4] == 0x1a && aucBuff[5] == 0x07 && aucBuff[6] == 0x00)) { rstrMimeType = _T("application/x-rar-compressed"); return true; } } // bzip (BZ2) file type if (aucBuff[0] == 'B' && aucBuff[1] == 'Z' && aucBuff[2] == 'h' && (aucBuff[3] >= '1' && aucBuff[3] <= '9')) { rstrMimeType = _T("application/x-bzip-compressed"); return true; } // ACE file type static const char _cACEheader[] = "**ACE**"; if (iRead >= 7 + _countof(_cACEheader)-1 && memcmp(&aucBuff[7], _cACEheader, _countof(_cACEheader)-1) == 0) { rstrMimeType = _T("application/x-ace-compressed"); return true; } // LHA/LZH file type static const char _cLZHheader[] = "-lh5-"; if (iRead >= 2 + _countof(_cLZHheader)-1 && memcmp(&aucBuff[2], _cLZHheader, _countof(_cLZHheader)-1) == 0) { rstrMimeType = _T("application/x-lha-compressed"); return true; } } } return false; }
[ "Mike.Ken.S@dd569cc8-ff36-11de-bbca-1111db1fd05b" ]
[ [ [ 1, 3092 ] ] ]
e06677bf1cfa0e1d244972855f31d3a7ea05194a
a04058c189ce651b85f363c51f6c718eeb254229
/Src/Forms/StringSelectForm.hpp
6d11f03c94654a330afe6b40483ad97685bd637f
[]
no_license
kjk/moriarty-palm
090f42f61497ecf9cc232491c7f5351412fba1f3
a83570063700f26c3553d5f331968af7dd8ff869
refs/heads/master
2016-09-05T19:04:53.233536
2006-04-04T06:51:31
2006-04-04T06:51:31
18,799
4
1
null
null
null
null
UTF-8
C++
false
false
1,432
hpp
#ifndef MORIARTY_STRING_SELECT_FORM_HPP__ #define MORIARTY_STRING_SELECT_FORM_HPP__ #include <FormObject.hpp> #include <HmStyleList.hpp> #include <Text.hpp> #include "MoriartyForm.hpp" class StringSelectForm: public MoriartyForm { protected: void attachControls(); void resize(const ArsRectangle& screenBounds); bool handleEvent(EventType& event); bool handleOpen(); public: void setSubtitle(const ArsLexis::char_t* subtitle) {subtitle_ = StringCopy2(subtitle);} struct StringSelectNotifyData { int selection; StringSelectNotifyData(int aSelection): selection(aSelection) {} }; StringSelectForm(uint_t notifyEvent, const ArsLexis::char_t* title); ~StringSelectForm(); enum RendererOwnershipOption { rendererOwnerNot, rendererOwner }; static int extractSelection(const EventType& event); void setItemRenderer(ExtendedList::ItemRenderer* itemRenderer, RendererOwnershipOption owner = rendererOwnerNot); private: Field subtitleField_; HmStyleList choicesList_; Control okButton_; Control cancelButton_; ExtendedList::ItemRenderer* itemRenderer_; RendererOwnershipOption itemRendererOwner_; ArsLexis::char_t* subtitle_; ArsLexis::char_t* title_; uint_t notifyEvent_; }; #endif
[ "andrzejc@a75a507b-23da-0310-9e0c-b29376b93a3c" ]
[ [ [ 1, 62 ] ] ]
4ead8cc98245ecbb60b1f175723caa99e6ce2e8f
c70941413b8f7bf90173533115c148411c868bad
/core/include/vtxGlyphResource.h
1f7bb706d979b52f4573e20fc1cc7d77a1367bc1
[]
no_license
cnsuhao/vektrix
ac6e028dca066aad4f942b8d9eb73665853fbbbe
9b8c5fa7119ff7f3dc80fb05b7cdba335cf02c1a
refs/heads/master
2021-06-23T11:28:34.907098
2011-03-27T17:39:37
2011-03-27T17:39:37
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,150
h
/* ----------------------------------------------------------------------------- This source file is part of "vektrix" (the rich media and vector graphics rendering library) For the latest info, see http://www.fuse-software.com/ Copyright (c) 2009-2010 Fuse-Software (tm) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------------- */ #ifndef __vtxGlyphResource_H__ #define __vtxGlyphResource_H__ #include "vtxPrerequisites.h" #include "vtxBoundingBox.h" #include "vtxShapeElement.h" namespace vtx { //----------------------------------------------------------------------- /** A Resource which contains information about a single glyph contained within a FontResource */ class vtxExport GlyphResource { public: GlyphResource(FontResource* parent); virtual ~GlyphResource(); /** Set the index for this glyph */ void setIndex(const uint& index); /** Get the index of this glyph */ const uint& getIndex() const; /** Set the unicode for this glyph */ void setCode(const ushort& code); /** Get the unicode of this glyph */ const ushort& getCode() const; /** Set the vertical advance value for this glyph */ const float& getAdvance() const; /** Get the vertical advance value of this glyph */ void setAdvance(const float& advance); /** Add a ShapeElement to the outline of this glyph */ void addShapeElement(ShapeElement element, const bool& auto_extend_bb = true); /** Get a list of all contained shape elements */ const ShapeElementList& getElementList() const; /** Set the BoundingBox for this glyph */ void setBoundingBox(const BoundingBox& bb); /** Get the BoundingBox of this glyph */ const BoundingBox& getBoundingBox() const; /** Get the FontResource that this glyph belongs to */ FontResource* getParentFont() const; protected: uint mIndex; ushort mCode; float mAdvance; BoundingBox mBoundingBox; FontResource* mParent; ShapeElementList mShapeElements; }; //----------------------------------------------------------------------- } #endif
[ "stonecold_@9773a11d-1121-4470-82d2-da89bd4a628a", "fixxxeruk@9773a11d-1121-4470-82d2-da89bd4a628a" ]
[ [ [ 1, 31 ], [ 33, 85 ] ], [ [ 32, 32 ] ] ]
6d9338fe0542b20c4d4fef14c043ea8a6de0225c
ef25bd96604141839b178a2db2c008c7da20c535
/src/src/Engine/Objects/Object.cpp
bd54b14e6b35c3055331fd2758aca5aabfad3915
[]
no_license
OtterOrder/crock-rising
fddd471971477c397e783dc6dd1a81efb5dc852c
543dc542bb313e1f5e34866bd58985775acf375a
refs/heads/master
2020-12-24T14:57:06.743092
2009-07-15T17:15:24
2009-07-15T17:15:24
32,115,272
0
0
null
null
null
null
ISO-8859-1
C++
false
false
3,189
cpp
#include "Object.h" #include "Game/Game.h" using namespace std; //****************************************************************** list< Object* > Object::RefList; //****************************************************************** /*********************************************************** * Initialisation commune à tous les constructeurs. **********************************************************/ void Object::CommonInit( void ) { D3DXMatrixIdentity( &m_WorldMatrix ); Object::RefList.push_front( this ); // enregistrement dans la liste } Object::Object( void ) { CommonInit(); m_vAngleX = m_vAngleY = m_vAngleZ = 0; } Object::Object( float initPosX, float initPosY, float initPosZ ) { CommonInit(); m_vAngleX = m_vAngleY = m_vAngleZ = 0; } Object::Object( D3DXVECTOR3 pos ) { CommonInit(); m_vAngleX = m_vAngleY = m_vAngleZ = 0; } Object::~Object( void ) { Object::RefList.remove( this ); // suppression dans la liste } /*********************************************************** * Méthode appelée chaque tour moteur. **********************************************************/ void Object::Update() { } void Object::SetTranslation( float x, float y, float z ) { D3DXMATRIX translation; D3DXMatrixTranslation( &translation, x, y, z); SetTransform(&translation); } void Object::SetRotation( float angleX, float angleY, float angleZ ) { m_vAngleX += angleX; m_vAngleY += angleY; m_vAngleZ += angleZ; if(m_vAngleX > 360.f) m_vAngleX = 0.f; if(m_vAngleY > 360.f) m_vAngleY = 0.f; if(m_vAngleZ > 360.f) m_vAngleZ = 0.f; D3DXMATRIX rotX, rotY, rotZ; D3DXMatrixRotationX(&rotX, D3DXToRadian(angleX)); D3DXMatrixRotationY(&rotY, D3DXToRadian(angleZ)); D3DXMatrixRotationZ(&rotZ, D3DXToRadian(angleY)); D3DXMATRIX result=rotX*rotY*rotZ; ApplyTransform(&result); } void Object::SetOrientation( float angleX, float angleY, float angleZ ) { m_vAngleX = angleX; m_vAngleY = angleY; m_vAngleZ = angleZ; if(m_vAngleX > 360.f) m_vAngleX = 0.f; if(m_vAngleY > 360.f) m_vAngleY = 0.f; if(m_vAngleZ > 360.f) m_vAngleZ = 0.f; D3DXMATRIX rotX, rotY, rotZ; D3DXMatrixRotationX(&rotX, D3DXToRadian(angleX)); D3DXMatrixRotationY(&rotY, D3DXToRadian(angleZ)); D3DXMatrixRotationZ(&rotZ, D3DXToRadian(angleY)); D3DXMATRIX result=rotX*rotY*rotZ; ApplyTransform(&result); } Vector3f Object::GetPosition() { float x=m_WorldMatrix._41; float y=m_WorldMatrix._42; float z=m_WorldMatrix._43; return Vector3f(x, y, z); } void Object::SetPosition(float x, float y, float z) { m_WorldMatrix._41 = x, m_WorldMatrix._42 = y, m_WorldMatrix._43 = z; } /*********************************************************** * Update toute la 3D : appelle l'Update de tous les * objets, etc. **********************************************************/ void Object::FullUpdate() { Object *pObj; std::list<Object*>::iterator it = RefList.begin(); bool isGamePaused = Game::GetInstance()->IsPaused(); while( it != RefList.end() ) { pObj = *it; if( !isGamePaused ) pObj->Update(); ++it; } }
[ "mathieu.chabanon@7c6770cc-a6a4-11dd-91bf-632da8b6e10b", "germain.mazac@7c6770cc-a6a4-11dd-91bf-632da8b6e10b", "berenger.mantoue@7c6770cc-a6a4-11dd-91bf-632da8b6e10b" ]
[ [ [ 1, 25 ], [ 27, 32 ], [ 34, 39 ], [ 41, 58 ], [ 62, 63 ], [ 65, 65 ], [ 104, 106 ], [ 114, 133 ] ], [ [ 26, 26 ], [ 33, 33 ], [ 40, 40 ], [ 59, 61 ], [ 64, 64 ], [ 89, 103 ] ], [ [ 66, 88 ], [ 107, 113 ] ] ]
2a4de5edfdca622947bb67a2cbd118700bcdcc08
dd007771e947dbed60fe6a80d4f325c4ed006f8c
/WarItemManager.h
5f276a5446532b9d125e9b6302692eba8fc5fc9a
[]
no_license
chenzhi/CameraGame
fccea24426ea5dacbe140b11adc949e043e84ef7
914e1a2b8bb45b729e8d55b4baebc9ba18989b55
refs/heads/master
2016-09-05T20:06:11.694787
2011-09-09T09:09:39
2011-09-09T09:09:39
2,005,632
0
0
null
null
null
null
GB18030
C++
false
false
2,453
h
/************************************************************** 道具管理器,用来负责道具的创建和销毁 ****************************************************************/ #pragma once #include "WarItem.h" class WarItemManager :public Ogre::Singleton<WarItemManager> { public: typedef WarItem* (WarItemManager::*createFun)(const Ogre::String&MeshName,const Ogre::String&textureName); typedef std::vector<std::pair<WarItemType ,createFun> > CreateFunCollect; ///道具种类的 struct ItemInformat { WarItemType m_ItemType;//类型id Ogre::String m_MeshName;//模型名字 Ogre::String m_Texture;//贴图名 float m_Power;///攻击力 }; public: WarItemManager(); ~WarItemManager(); /**创建一个道具 *@param itemtype 道具类型 *@p */ WarItem* createWarItem(WarItemType itemtype); /**创建道具 *@param typeName 类型名 *@param MeshName 道具模型文件名. *@param textureName 贴图名 */ WarItem* createWarItem(const Ogre::String& typeName); /**每帧更新*/ void update(float time); /**销毁道具*/ void destroy(WarItem* pItem); protected: /**销毁所有的道具*/ void destroyWarItem(); /**添加一个创建类型*/ bool addItemType(WarItemType itemtype,createFun); /**移除一个创建类型*/ bool removeItemtype(WarItemType itemtype); /**查打一个创建函数*/ createFun findCrateFun(WarItemType itemtype); protected: /**创建鸡蛋道具函数*/ //WarItem* createEggItem(const Ogre::String&MeshName,const Ogre::String&textureName); /**内部函数,把类型转了字符串 */ Ogre::String itemTypeToString(WarItemType itemType); /**内部函数把字符串转成类型 */ WarItemType stringToItemtype(const Ogre::String& itemtype); /**初始化道具类型信息*/ void initItemTypeInformation(); /**根据类型查找到相应的模型名*/ bool getItemTypeMeshAndTexture(WarItemType itemType,ItemInformat& itemTypeInfor); protected: WarItemCollect m_WarItemCollect;///所有道具的列表。 WarItemCollect m_RemoveItemCollect; CreateFunCollect m_CreateFunCollect;///创建函数列表 typedef std::vector<ItemInformat> ItemInformationCollect; ItemInformationCollect m_ItemInformation; };
[ "chenzhi@aee8fb6d-90e1-2f42-9ce8-abdac5710353" ]
[ [ [ 1, 117 ] ] ]
c4c0fa2cca667c5ff7f2207cc77dfaa98a63fe4d
7a310d01d1a4361fd06b40a74a2afc8ddc23b4d3
/src/DonutClipboardBar.cpp
fb629036cae24c77f8379ef9bcd9876301e9a8ac
[]
no_license
plus7/DonutG
b6fec6111d25b60f9a9ae5798e0ab21bb2fa28f6
2d204c36f366d6162eaf02f4b2e1b8bc7b403f6b
refs/heads/master
2020-06-01T15:30:31.747022
2010-08-21T18:51:01
2010-08-21T18:51:01
767,753
1
2
null
null
null
null
SHIFT_JIS
C++
false
false
7,310
cpp
/** * @file DonutClipbordBar.cpp * @brief クリップボード・バー */ #include "stdafx.h" #include "DonutClipboardBar.h" #include "Donut.h" #include "DonutPFunc.h" #include "option/MainOption.h" // Ctor CDonutClipboardBar::CDonutClipboardBar() : m_dwExStyle(0) #if 1 //+++ , m_strExts() , m_nOn(0) , m_nDirect(0) , m_nFlush(0) , m_edit() #endif , m_box(this, 1) { } // Methods CString CDonutClipboardBar::GetExtsList() { return MtlGetWindowText(m_edit); } void CDonutClipboardBar::OpenClipboardUrl() { CString strText = MtlGetClipboardText(); if ( strText.IsEmpty() ) return; CSimpleArray<CString> arrExt; MtlBuildExtArray( arrExt, GetExtsList() ); CSimpleArray<CString> arrUrl; MtlBuildUrlArray(arrUrl, arrExt, strText); for (int i = 0; i < arrUrl.GetSize(); ++i) { DonutOpenFile(m_hWnd, arrUrl[i], 0); } } // Overrides void CDonutClipboardBar::OnUpdateClipboard() { if (CMainOption::s_bIgnoreUpdateClipboard) return; clbTRACE( _T("OnUpdateClipboard\n") ); CString strText = MtlGetClipboardText(); if ( strText.IsEmpty() ) return; CGeckoBrowser browser = DonutGetNsIWebBrowser( GetTopLevelParent() ); if ( !browser.IsBrowserNull() ) { CString strUrl = browser.GetLocationURL(); if (strUrl == strText) return; } if ( _check_flag(CLPV_EX_FLUSH, m_dwExStyle) ) m_box.ResetContent(); CSimpleArray<CString> arrExt; MtlBuildExtArray( arrExt, MtlGetWindowText(m_edit) ); CSimpleArray<CString> arrUrl; MtlBuildUrlArray(arrUrl, arrExt, strText); if (arrUrl.GetSize() == 0) { return; } else { if ( _check_flag(CLPV_EX_FLUSH, m_dwExStyle) ) m_box.ResetContent(); } for (int i = 0; i < arrUrl.GetSize(); ++i) { if (m_box.GetCount() == 0) m_box.AddString(arrUrl[i]); else m_box.InsertString(0, arrUrl[i]); } if ( _check_flag(CLPV_EX_DIRECT, m_dwExStyle) ) { for (int i = 0; i < arrUrl.GetSize(); ++i) { DonutOpenFile(m_hWnd, arrUrl[i], 0); } } } // Methods BYTE CDonutClipboardBar::PreTranslateMessage(MSG *pMsg) { UINT msg = pMsg->message; //x int vKey = pMsg->wParam; HWND hWnd = pMsg->hwnd; if (m_hWnd == NULL) return _MTL_TRANSLATE_PASS; #if 1 //+++ 起動直後で、無項で、クリップボードバーを表示しているとき、 // F4押してもオプションメニューが起動できない件の暫定対処. // よくわからずなんとなくの修正なんで、問題があるかも... // ※ 何かWeb頁表示してたり、一旦、お気に入りバー等を表示したあとだとokになる状態で、 // 駄目なときは、下のIsDialogMessage(pMsg)が真を返していた。 // ここでなく他の箇所でのバグな気もするし、そもそも現状のundonutで、 // ここでIsDialogMessage()をする必要があるのかもわかってないけれど。 if (WM_KEYFIRST <= pMsg->message && pMsg->message <= WM_KEYLAST) { if (hWnd != m_edit.m_hWnd) return _MTL_TRANSLATE_PASS; } #else if (msg == WM_KEYDOWN) { if (hWnd != m_edit.m_hWnd && ::GetKeyState(VK_CONTROL) < 0) // may be accelerator return _MTL_TRANSLATE_PASS; } else if (msg == WM_SYSKEYDOWN) { return _MTL_TRANSLATE_PASS; } #endif if ( IsDialogMessage(pMsg) ) // is very smart. return _MTL_TRANSLATE_HANDLE; return _MTL_TRANSLATE_PASS; } LRESULT CDonutClipboardBar::OnInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL & /*bHandled*/) { DlgResize_Init(false, true, WS_CLIPCHILDREN); m_edit.Attach( GetDlgItem(IDC_EDIT_CB_EXT) ); m_box.SubclassWindow( GetDlgItem(IDC_LIST_CB_CONT) ); _GetProfile(); _SetData(); DoDataExchange(FALSE); return TRUE; } LRESULT CDonutClipboardBar::OnDestroy(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL & /*bHandled*/) { DoDataExchange(TRUE); _GetData(); _WriteProfile(); return 0; } LRESULT CDonutClipboardBar::OnCheckCommand(WORD wNotifyCode, WORD wID, HWND /*hWndCtl*/, BOOL & /*bHandled*/) { if (wNotifyCode == BN_CLICKED) { DoDataExchange(TRUE); _GetData(); } return 0; } LRESULT CDonutClipboardBar::OnButtonDelete(WORD wNotifyCode, WORD wID, HWND /*hWndCtl*/, BOOL & /*bHandled*/) { _MtlForEachListBoxSelectedItem( m_box.m_hWnd, _Function_DeleteString() ); return 0; } LRESULT CDonutClipboardBar::OnButtonOpen(WORD wNotifyCode, WORD wID, HWND /*hWndCtl*/, BOOL & /*bHandled*/) { _MtlForEachListBoxSelectedItem( m_box.m_hWnd, _Function_Open() ); return 0; } LRESULT CDonutClipboardBar::OnButtonPaste(WORD wNotifyCode, WORD wID, HWND /*hWndCtl*/, BOOL & /*bHandled*/) { OnUpdateClipboard(); return 0; } LRESULT CDonutClipboardBar::OnButtonPasteDonut(WORD wNotifyCode, WORD wID, HWND /*hWndCtl*/, BOOL & /*bHandled*/) { OpenClipboardUrl(); return 0; } LRESULT CDonutClipboardBar::OnButtonDeleteAll(WORD wNotifyCode, WORD wID, HWND /*hWndCtl*/, BOOL & /*bHandled*/) { m_box.ResetContent(); return 0; } LRESULT CDonutClipboardBar::OnIdOk(WORD wNotifyCode, WORD wID, HWND /*hWndCtl*/, BOOL & /*bHandled*/) { if (::GetFocus() == m_box.m_hWnd) _MtlForEachListBoxSelectedItem( m_box.m_hWnd, _Function_Open() ); return 0; } LRESULT CDonutClipboardBar::OnLBLButtonDblClk(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM lParam, BOOL & /*bHandled*/) { CPoint pt( LOWORD(lParam), HIWORD(lParam) ); BOOL bOutside; UINT nIndex = m_box.ItemFromPoint(pt, bOutside); if (!bOutside) _OnItemOpen(nIndex); return 0; } // Implementation void CDonutClipboardBar::_GetData() { // update style m_dwExStyle = 0; if (m_nOn /*== 1*/) m_dwExStyle |= CLPV_EX_ON; if (m_nDirect /*== 1*/) m_dwExStyle |= CLPV_EX_DIRECT; if (m_nFlush /*== 1*/) m_dwExStyle |= CLPV_EX_FLUSH; if ( _check_flag(CLPV_EX_ON, m_dwExStyle) ) InstallClipboardViewer(); else UninstallClipboardViewer(); } void CDonutClipboardBar::_SetData() { m_nOn = _check_flag(CLPV_EX_ON , m_dwExStyle); //+++ ? 1 : 0; m_nDirect = _check_flag(CLPV_EX_DIRECT, m_dwExStyle); //+++ ? 1 : 0; m_nFlush = _check_flag(CLPV_EX_FLUSH , m_dwExStyle); //+++ ? 1 : 0; } void CDonutClipboardBar::_GetProfile() { CIniFileI pr( MtlGetChangedExtFromModuleName( _T(".ini") ), _T("ClipboardBar") ); pr.QueryValue( m_dwExStyle, _T("Extended_Style") ); m_strExts = pr.GetString( _T("Ext_List"), _T("/;html;htm;shtml;cgi;asp;com;net;jp;lnk;url;") ); //+++ "Ext_List"があればその中身を、なければ第2引数を値とする. if ( _check_flag(CLPV_EX_ON, m_dwExStyle) ) InstallClipboardViewer(); } void CDonutClipboardBar::_WriteProfile() { CIniFileO pr( MtlGetChangedExtFromModuleName( _T(".ini") ), _T("ClipboardBar") ); pr.SetValue ( m_dwExStyle, _T("Extended_Style") ); pr.SetString( m_strExts , _T("Ext_List") ); pr.Close(); UninstallClipboardViewer(); } void CDonutClipboardBar::_OnItemOpen(int nIndex) { clbTRACE( _T("_OnItemOpen\n") ); CString str; MtlListBoxGetText(m_box.m_hWnd, nIndex, str); if ( str.IsEmpty() ) return; DonutOpenFile(m_hWnd, str, 0); }
[ [ [ 1, 323 ] ] ]
3002e79737a5ac8359405d6009d4b0deeda3b3e8
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/xpressive/test/test11.hpp
6aa9bac6404275168e38a20a0116a1e695749381
[ "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
willrebuild/flyffsf
e5911fb412221e00a20a6867fd00c55afca593c7
d38cc11790480d617b38bb5fc50729d676aef80d
refs/heads/master
2021-01-19T20:27:35.200154
2011-02-10T12:34:43
2011-02-10T12:34:43
32,710,780
3
0
null
null
null
null
UTF-8
C++
false
false
2,336
hpp
/////////////////////////////////////////////////////////////////////////////// // test11.hpp // // Copyright 2004 Eric Niebler. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include "./test.hpp" /////////////////////////////////////////////////////////////////////////////// // get_test_cases // template<typename BidiIterT> boost::iterator_range<test_case<BidiIterT> const *> get_test_cases() { typedef typename boost::iterator_value<BidiIterT>::type char_type; typedef test_case<BidiIterT> test_case; typedef basic_regex<BidiIterT> regex_type; static char_type const *nilbr = 0; static test_case const test_cases[] = { test_case ( "test166" , L("G") , regex_type(L('f') | icase(L('g'))) , backrefs(L("G"), nilbr) ) , test_case ( "test167" , L("aBBa") , regex_type(icase(+lower)) , backrefs(L("aBBa"), nilbr) ) , test_case ( "test168" , L("aA") , regex_type(icase(+as_xpr(L('\x61')))) , backrefs(L("aA"), nilbr) ) , test_case ( "test169" , L("aA") , regex_type(icase(+set[L('\x61')])) , backrefs(L("aA"), nilbr) ) , test_case ( "test170" , L("aA") , regex_type(icase(+as_xpr(L('\x0061')))) , backrefs(L("aA"), nilbr) ) , test_case ( "test171" , L("aA") , regex_type(icase(+set[L('\x0061')])) , backrefs(L("aA"), nilbr) ) , test_case ( "test172" , L("abcd") , regex_type(L('a') >> +(s1= L('b') | (s2= *(s3= L('c')))) >> L('d')) , backrefs(L("abcd"), L(""), L(""), L(""), nilbr) ) , test_case ( "test173" , L("abcd") , regex_type(L('a') >> +(s1= L('b') | (s2= !(s3= L('c')))) >> L('d')) , backrefs(L("abcd"), L(""), L(""), L(""), nilbr) ) }; return boost::make_iterator_range(test_cases); }
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 83 ] ] ]
0182bfe5148b61eabca456ac3e53682bef71f9c4
3d9e738c19a8796aad3195fd229cdacf00c80f90
/src/console/Console_logger_buffer.cpp
96fc1629a8b82425b3d29cb18ebb117ec8f95669
[]
no_license
mrG7/mesecina
0cd16eb5340c72b3e8db5feda362b6353b5cefda
d34135836d686a60b6f59fa0849015fb99164ab4
refs/heads/master
2021-01-17T10:02:04.124541
2011-03-05T17:29:40
2011-03-05T17:29:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,925
cpp
/* This source file is part of Mesecina, a software for visualization and studying of * the medial axis and related computational geometry structures. * More info: http://www.agg.ethz.ch/~miklosb/mesecina * Copyright Balint Miklos, Applied Geometry Group, ETH Zurich * * Portions of this source file are based on the code of Dietmar Kuehl from * http://www.inf.uni-konstanz.de/~kuehl/iostream/ * * $Id: Logger_buffer.cpp 383 2008-11-03 20:12:36Z miklosb $ */ #include "Console_logger_buffer.h" #include "Console_logger.h" Console_logger_buffer::Console_logger_buffer(Console_logger* l, int bsize) : std::streambuf(), logger(l) { if (bsize) { char *ptr = new char[bsize]; setp(ptr, ptr + bsize); } else setp(0, 0); setg(0, 0, 0); } Console_logger_buffer::~Console_logger_buffer() { sync(); delete[] pbase(); } int Console_logger_buffer::overflow(int c) { // mutex.lock(); put_buffer(); if (c != EOF) if (pbase() == epptr()) put_char(c); else sputc(c); return 0; } int Console_logger_buffer::sync() { put_buffer(); // mutex.unlock(); return 0; } void Console_logger_buffer::put_char(int chr) { char app[2]; app[0] = chr; app[1] = 0; if (app[0]==10) { logger->set_next_line(); } else logger->print_to_log(app); // originally // XmTextInsert(text, XmTextGetLastPosition(text), app); } void Console_logger_buffer::put_buffer() { // mutex.lock(); if (pbase() != pptr() && logger != 0) { int len = (pptr() - pbase()); char *buffer = new char[len + 1]; strncpy(buffer, pbase(), len); buffer[len] = 0; if (buffer[0]==10) { logger->set_next_line(); // logger->print_to_log(buffer+1); // mutex.unlock(); } else logger->print_to_log(buffer); // originally // XmTextInsert(text, XmTextGetLastPosition(text), buffer); setp(pbase(), epptr()); delete [] buffer; } }
[ "balint.miklos@localhost" ]
[ [ [ 1, 83 ] ] ]
c32fe2e5a5a38aa895be2c58a3451b1212a7bee2
17083b919f058848c3eb038eae37effd1a5b0759
/SimpleGL/sgl/Math/Containers.hpp
88e9aeddb3483565e65be425a4fbad785b830c27
[]
no_license
BackupTheBerlios/sgl
e1ce68dfc2daa011bdcf018ddce744698cc7bc5f
2ab6e770dfaf5268c1afa41a77c04ad7774a70ed
refs/heads/master
2021-01-21T12:39:59.048415
2011-10-28T16:14:29
2011-10-28T16:14:29
39,894,148
0
0
null
null
null
null
UTF-8
C++
false
false
4,235
hpp
/** * \author DikobrAz * \date 08.09.09 * File contains aligned arrays to store sse optimized vectors. * Actually used STL containers with aligned allocator if the * SSE optimization is enabled and without it otherwise. For the * MSVS there is own vector implementation because of compilation * bug using vector of aligned elements. */ #ifndef SIMPLE_GL_MATH_CONTAINERS_HPP #define SIMPLE_GL_MATH_CONTAINERS_HPP #include "../Utility/Aligned.h" #include "Matrix.hpp" #include "Quaternion.hpp" #include <algorithm> #include <vector> SGL_BEGIN_MATH_NAMESPACE #ifdef SIMPLE_GL_USE_SSE #ifdef __GNUC__ /// Aligned(0x10) std::vector of Vector4f typedef std::vector< Vector4f, sgl::aligned_allocator<Vector4f> > vector_of_vector4f; /// Aligned(0x10) std::vector of Matrix4f typedef std::vector< Matrix4f, sgl::aligned_allocator<Matrix4f> > vector_of_matrix4f; /// Aligned(0x10) std::vector of Quaternionf typedef sgl::vector< Quaternionf, sgl::aligned_allocator<Quaternionf> > vector_of_quaternionf; #else // MSVS /// Aligned(0x10) std::vector of Vector4f typedef sgl::vector< Vector4f, sgl::aligned_allocator<Vector4f> > vector_of_vector4f; /// Aligned(0x10) std::vector of Matrix4f typedef sgl::vector< Matrix4f, sgl::aligned_allocator<Matrix4f> > vector_of_matrix4f; /// Aligned(0x10) std::vector of Quaternionf typedef sgl::vector< Quaternionf, sgl::aligned_allocator<Quaternionf> > vector_of_quaternionf; #endif // MSVS #else // SIMPLE_GL_USE_SSE /// std::vector of Vector4f typedef std::vector<Vector4f> vector_of_vector4f; /// std::vector of Matrix4f typedef std::vector<Matrix4f> vector_of_matrix4f; /// std::vector of Quaternionf typedef std::vector<Quaternionf> vector_of_quaternionf; #endif // SIMPLE_GL_USE_SSE /// std::vector of Vector3f typedef std::vector<Vector3f> vector_of_vector3f; /// std::vector of Vector2f typedef std::vector<Vector2f> vector_of_vector2f; /// std::vector of Vector4d typedef std::vector<Vector4d> vector_of_vector4d; /// std::vector of Vector3d typedef std::vector<Vector3d> vector_of_vector3d; /// std::vector of Vector2d typedef std::vector<Vector2d> vector_of_vector2d; /// std::vector of Vector4i typedef std::vector<Vector4i> vector_of_vector4i; /// std::vector of Vector3i typedef std::vector<Vector3i> vector_of_vector3i; /// std::vector of Vector2i typedef std::vector<Vector2i> vector_of_vector2i; /// std::vector of Vector4ui typedef std::vector<Vector4ui> vector_of_vector4ui; /// std::vector of Vector3ui typedef std::vector<Vector3ui> vector_of_vector3ui; /// std::vector of Vector2ui typedef std::vector<Vector2ui> vector_of_vector2ui; /// std::vector of Vector4b typedef std::vector<Vector4b> vector_of_vector4b; /// std::vector of Vector3b typedef std::vector<Vector3b> vector_of_vector3b; /// std::vector of Vector2b typedef std::vector<Vector2b> vector_of_vector2b; /// std::vector of Matrix3f typedef std::vector<Matrix3f> vector_of_matrix3f; /// std::vector of Matrix2f typedef std::vector<Matrix2f> vector_of_matrix2f; /// std::vector of Matrix4d typedef std::vector<Matrix4d> vector_of_matrix4d; /// std::vector of Matrix3d typedef std::vector<Matrix3d> vector_of_matrix3d; /// std::vector of Matrix2d typedef std::vector<Matrix2d> vector_of_matrix2d; /// std::vector of Matrix4i typedef std::vector<Matrix4i> vector_of_matrix4i; /// std::vector of Matrix3i typedef std::vector<Matrix3i> vector_of_matrix3i; /// std::vector of Matrix2i typedef std::vector<Matrix2i> vector_of_matrix2i; /// std::vector of Matrix4ui typedef std::vector<Matrix4ui> vector_of_matrix4ui; /// std::vector of Matrix3ui typedef std::vector<Matrix3ui> vector_of_matrix3ui; /// std::vector of Matrix2ui typedef std::vector<Matrix2ui> vector_of_matrix2ui; /// std::vector of Matrix4b typedef std::vector<Matrix4b> vector_of_matrix4b; /// std::vector of Matrix3b typedef std::vector<Matrix3b> vector_of_matrix3b; /// std::vector of Matrix2b typedef std::vector<Matrix2b> vector_of_matrix2b; SGL_END_MATH_NAMESPACE #endif // SIMPLE_GL_MATH_CONTAINERS_HPP
[ "devnull@localhost" ]
[ [ [ 1, 123 ] ] ]
42fb6749f32afb38247c293627b97eedc6044326
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/boost/thread/once.hpp
64977bcba900232b4b18eaf6c075fe48a8882779
[ "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
willrebuild/flyffsf
e5911fb412221e00a20a6867fd00c55afca593c7
d38cc11790480d617b38bb5fc50729d676aef80d
refs/heads/master
2021-01-19T20:27:35.200154
2011-02-10T12:34:43
2011-02-10T12:34:43
32,710,780
3
0
null
null
null
null
UTF-8
C++
false
false
856
hpp
// Copyright (C) 2001-2003 // William E. Kempf // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_ONCE_WEK080101_HPP #define BOOST_ONCE_WEK080101_HPP #include <boost/thread/detail/config.hpp> #if defined(BOOST_HAS_PTHREADS) # include <pthread.h> #endif namespace boost { #if defined(BOOST_HAS_PTHREADS) typedef pthread_once_t once_flag; #define BOOST_ONCE_INIT PTHREAD_ONCE_INIT #elif (defined(BOOST_HAS_WINTHREADS) || defined(BOOST_HAS_MPTASKS)) typedef long once_flag; #define BOOST_ONCE_INIT 0 #endif void BOOST_THREAD_DECL call_once(void (*func)(), once_flag& flag); } // namespace boost // Change Log: // 1 Aug 01 WEKEMPF Initial version. #endif // BOOST_ONCE_WEK080101_HPP
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 37 ] ] ]
3ac5f6231103698ca835b7dd6f3a22118410cfba
5ac13fa1746046451f1989b5b8734f40d6445322
/minimangalore/Nebula2/code/nebula2/src/util/nbuffer.cc
a7c5c64bcdc531893afbb1d0cd165ad68be5920d
[]
no_license
moltenguy1/minimangalore
9f2edf7901e7392490cc22486a7cf13c1790008d
4d849672a6f25d8e441245d374b6bde4b59cbd48
refs/heads/master
2020-04-23T08:57:16.492734
2009-08-01T09:13:33
2009-08-01T09:13:33
35,933,330
0
0
null
null
null
null
UTF-8
C++
false
false
3,788
cc
//------------------------------------------------------------------------------ /** nbuffer.cc */ #include <memory.h> #include "kernel/ntypes.h" #include "util/nbuffer.h" // Initial buffer size. const int nBuffer::InitialCapacity = 4096; //------------------------------------------------------------------------------ /** */ nBuffer::nBuffer() : capacity(InitialCapacity), count(0) { this->data = this->MakeArea(InitialCapacity); } //------------------------------------------------------------------------------ /** */ nBuffer::nBuffer(const nBuffer& other) : capacity(other.capacity), count(other.count) { this->data = this->MakeArea(capacity); this->Copy(this->data, other.data, other.count); } //------------------------------------------------------------------------------ /** */ nBuffer::~nBuffer() { delete [] this->data; } //------------------------------------------------------------------------------ /** */ void nBuffer::Reset() { delete [] this->data; this->data = this->MakeArea(InitialCapacity); this->capacity = InitialCapacity; this->count = 0; } //------------------------------------------------------------------------------ /** Do not lose any previously entered items. */ void nBuffer::Resize(int newSize) { n_assert(newSize >= 0); if (newSize > this->capacity) { char* newData = this->MakeArea(newSize); if (this->count > 0) { this->Copy(newData, this->data, this->count); } delete[] this->data; this->data = newData; this->capacity = newSize; } } //------------------------------------------------------------------------------ /** */ void nBuffer::Write(const char* data, int startIndex, int endIndex) { n_assert(data != 0); n_assert(this->ValidRange(startIndex, endIndex)); char* p = this->data; p += startIndex; this->Copy(p, data, endIndex - startIndex + 1); if (this->count <= endIndex) { this->count = endIndex + 1; } } //------------------------------------------------------------------------------ /** */ void nBuffer::Read(char* data, int startIndex, int endIndex) { n_assert(data != 0); n_assert(this->ValidRange(startIndex, endIndex)); char* p = this->data; p += startIndex; this->Copy(data, p, endIndex - startIndex + 1); } //------------------------------------------------------------------------------ /** */ bool nBuffer::ValidIndex(int v) const { return 0 <= v && v <= this->Capacity() - 1; } //------------------------------------------------------------------------------ /** */ bool nBuffer::ValidRange(int startIndex, int endIndex) const { return this->ValidIndex(startIndex) && this->ValidIndex(endIndex) && endIndex >= startIndex; } //------------------------------------------------------------------------------ /** */ nBuffer& nBuffer::operator = (const nBuffer& other) { if (&other == this) { return *this; } this->Resize(other.capacity); this->Copy(this->data, other.data, other.count); count = other.count; return *this; } //------------------------------------------------------------------------------ /** */ void nBuffer::Copy(char* a, const char* b, int size) const { n_assert(a != 0); n_assert(b != 0); n_assert(size > 0); memcpy(a, b, size); } //------------------------------------------------------------------------------ /** */ char* nBuffer::MakeArea(int cap) const { n_assert(cap > 0); char* result = new char[cap]; n_assert(result != 0); return result; }
[ "BawooiT@d1c0eb94-fc07-11dd-a7be-4b3ef3b0700c" ]
[ [ [ 1, 167 ] ] ]
ef6bc20c055787e5ea807657a305c6dd23047b75
d9c5525fd5db3095382684c06757a1b384bae0d3
/Vision/trunk/ObjectDetection/src/objdetection.h
0498251703e260a709ecfa1f34e794d7818b23a3
[]
no_license
juokaz/SDP12
ae5e1a9ee13684f91de9ec260ca2f505fbbe89fc
ade1ec74edd9769f7dc1c7ba3da0f0c955dd2416
refs/heads/master
2021-01-01T19:56:30.571963
2011-04-21T15:03:06
2011-04-21T15:03:06
1,532,269
0
2
null
null
null
null
UTF-8
C++
false
false
11,672
h
#ifndef OBJECTDETECTION_H_ #define OBJECTDETECTION_H_ #include <cvaux.h> #include <highgui.h> #include <cxcore.h> #include <stdio.h> #include <iostream> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include <cmath> #include <float.h> #include <limits.h> #include <time.h> #include <ctype.h> #include <iostream> #include <ml.h> #include <time.h> #include <fstream> //#define MEASURE_TIME #ifdef MEASURE_TIME #include <boost/date_time/posix_time/posix_time_types.hpp> #endif /* \struct image_base * \brief this struct contains data for dealing image files. */ struct image_base { int image_start; /**< start number for loading images*/ int step; /**< step for iterating through images.*/ int image_end; /**< end number for iterating through images.*/ char* basefile; /**< base directory/address for images*/ int current; /**< current number in image dataset.*/ }; /* \struct Region of Interest * \brief this struct contains data for croping images. */ struct ROI { int X; /**< x value relative to top left of image*/ int Y; /**< y value relative to top left of image*/ int Width; /**< width to crop*/ int Height; /**< height to crop*/ }; /* * \struct circular buffer * \brief this struct contains data for a circular buffer. */ typedef struct circular_buffer { void *buffer; /**< pointer to buffer */ void *buffer_end; /**< end of data buffer */ size_t capacity; /**< maximum number of items in the buffer */ size_t count; /**< number of items in the buffer */ size_t sz; /**< size of each item in the buffer*/ void *head; /**< pointer to head*/ void *tail; /**< pointer to tail*/ }circular_buffer; /* \struct config * \brief this struct contains main configuration parameters. */ struct config { bool good; /**< indicates if program state is good*/ bool image_file; /**< indicates if images are loaded from file*/ CvMemStorage* storage; /**< storage for keeping contours durring run*/ image_base i_base; /**< struct that holds values for file based images*/ bool camera; /**< indicates if images are loaded from camera*/ bool rankedArea; /**< indicates if rankedArea method should be used for finding best match*/ bool closeObjects; /**< indicates if closeObjects method should be used to find best match and orientation*/ bool show; /**< indicates if results should be displayed*/ bool outputToText; /**< indicates if output should be saved in a file*/ char* outputfile; /**< address of file which results have to be saved*/ CvCapture* capture; /**< pointer to instance of CvCapture to get images from camera */ bool back; /**< indicates if background is loaded*/ circular_buffer TY_Buffer; /**< circular buffer for Yellow Plate */ circular_buffer TB_Buffer; /**< circular buffer for Blue Plate */ IplImage* current_frame; /**< pointer to current image */ IplImage* background; /**< pointer to backgound image */ IplImage* background_transformed; /**< pointer to processed backgound image */ int64 totalTime; /**< total time consumed for proccessing images */ int Opcount; /**< total number of cycles program has been working*/ CvRect rect_B; /**< position of position of Ball*/ CvBox2D sel_TB; /**< position and orientation of Blue Plate*/ CvBox2D sel_TY; /**< position and orientation of Yelow Plate*/ bool outputToConsole; /**< indicates if results should be sent to standard error*/ bool train_minor; /**< indicates if program should train using both larg obects and also second order objects(plate-dot)*/ bool predict_minor; /**< indicates if program should predict using both larg obects and also second order objects(plate-dot), if models don't exist one of deterministc methods is used*/ bool train_major; /**< indicates if program should train using larg obects*/ bool predict_major; /**< indicates if program should predict using larg obects ,if models don't exist one of deterministc methods is used*/ ROI windowOfInterest; /**<struct that holds values for Region of Interest*/ CvScalar hsv_min_B; /**<min values for thresholding Ball*/ CvScalar hsv_max_B; /**<max values for thresholding Ball*/ CvScalar hsv_min_TB; /**<min values for thresholding Blue plate*/ CvScalar hsv_max_TB; /**<max values for thresholding Blue plate*/ CvScalar hsv_min_TY; /**<min values for thresholding Yellow plate*/ CvScalar hsv_max_TY; /**<max values for thresholding Yellow plate*/ CvScalar hsv_min_D; /**<min values for thresholding Black Dot/Green Plate plate*/ CvScalar hsv_max_D; /**<max values for thresholding Black Dot/Green Plate plate*/ }; //! main namespace includes functions for calculating contours/orienation/matching contours and all sub namespaces namespace objDetection { #define TEST_FILES_START 1 #define TEST_FILES_END 43 #define PI 3.14159265 #define TEXT_OUTPUT "Outputlocs.txt" //Normalization macro #define NORMALIZE(X) if (X>PI*2) X=X-PI*2; else if(X<0) X=X+PI*2; //! \brief extracts contours in a image. /*! \param img pointer to an instance of IplImage* single channel image to extract contours from. \param storage pointer to an instance of ScMemStorage to store found contours */ std::vector<CvContour*> getContours( IplImage* img,CvMemStorage* storage); //! \brief Finds the biggest contour in an image //! use this function in conjunction with thresholding methods to find the object in an image /*! \param frame pointer to an instance of IplImage* single channel image to extract contours from. \param storage pointer to an instance of ScMemStorage to store found contours */ CvContour* rankedArea(IplImage* frame,CvMemStorage* storage); //! \brief Calculates position and orientation of an object using rankedArea method and orientation3 method //! use this function in conjunction with thresholding methods to find the object in an image /*! \param obj_frame pointer to an instance of IplImage* single channel image to extract contours from. \param dot_frame pointer to an instance of IplImage* single channel image to extract contours of second order objects. \param storage pointer to an instance of ScMemStorage to store found contours \param conf configuration instance. \return instance CvBox2D that include position and orientation of object. */ CvBox2D DotCloseObjectDetection(IplImage* obj_frame,IplImage* dot_frame,CvMemStorage* storage,config conf); //! \brief Calculates orientation and position of a contour using minimum bounding rectangle /*! \param cntr pointer to a contour to calculate its position and orientation. \return instance CvBox2D that include position and orientation of object. */ CvBox2D orientation_minRect(CvContour* cntr); //! \brief Calculates orientation and position of a contour using minimum bounding rectangle and enclosing circle. /*! \param cntr pointer to a contour to calculate its position and orientation. \return instance CvBox2D that include position and orientation of object. */ CvBox2D orientation_minRect_Circle(CvContour* cntr); //! \brief Calculates orientation and position of a contour using center of mass provided as input and furthest point in the contour from center of mass. /*! \param cntr pointer to a contour to calculate its position and orientation. \param cenX X value of center of Mass of the contour \param cenY Y value of center of Mass of the contour \return instance CvBox2D that include position and orientation of object. */ CvBox2D orientation_contourPoints(CvContour* cntr,float cenX,float cenY); //! \brief Calculates orientation and position of a contour using center of mass of the contour and enclosing center.. /*! \param cntr pointer to a contour to calculate its position and orientation. \return instance CvBox2D that include position and orientation of object. */ CvBox2D orientation_contourPoints(CvContour* cntr,float cenX,float cenY); CvBox2D orientation_centerMoment(CvContour* cntr); //! \brief Calculates orientation and position of a contour using center of mass of the contour and seconf order of centeral moments. //! uses orientation_minRect_Circle as a helper function to disambiguate orientation /*! \param cntr pointer to a contour to calculate its position and orientation. \return instance CvBox2D that include position and orientation of object. */ CvBox2D orientation_secondOrderMoment(CvContour* cntr); //! \brief Calculates orientation and position of a contour using a set of contours asscoiate to the plate(darkspot/plate) //! This method uses minbounding rectangle for both objects /*! \param cntr pointer to a contour to calculate its position and orientation. \param plate_vector list of contours associated to the plate(darkspot/plate) \return instance CvBox2D that include position and orientation of object. */ CvBox2D orientation_plate2(CvContour* cntr, std::vector<CvContour*> plate_vector); //! \brief Calculates orientation and position of a contour using a set of contours asscoiate to the plate(darkspot/plate) //! This method uses minbounding rectangle and bounding circle for both objects. /*! \param cntr pointer to a contour to calculate its position and orientation. \param plate_vector list of contours associated to the plate(darkspot/plate) \return instance CvBox2D that include position and orientation of object. */ CvBox2D orientation_plate1(CvContour* cntr, std::vector<CvContour*> plate_vector); //! \brief Preprocess an image //! This method uses: canny Edge detector,applies thresholds, smooths result /*! \param img_src source image. \param hsv_min minimum vector for thresholding. \param hsv_max maximum vector for thresholding. \return a new single channel image of applied thresholds and procedures. */ IplImage* preprocess_to_single_channel(IplImage* img_src,CvScalar hsv_min,CvScalar hsv_max); //! \brief Preprocess an image //! This method uses: canny Edge detector,applies thresholds, smooths result,subtracts background image. /*! \param frame source image. \param frame_back background image. \param hsv_min minimum vector for thresholding. \param hsv_max maximum vector for thresholding. \param back if set background will be subtracted from new frame. \param bgr if set color space is set to be RGB. \return a new single channel image of applied thresholds and procedures. */ IplImage* preprocess_to_single_channel(IplImage* frame,IplImage* frame_back,CvScalar hsv_min,CvScalar hsv_max,bool back=true,bool bgr=false); //! \brief draws orientation of input CvBox2D on input frame. /*! \param img image that position and orientation is drawn on. \param box input location and orientation to draw \param color color vector to use for drawing */ void drawOrientation(IplImage* img, CvBox2D box,CvScalar color=cvScalarAll(0)); //! \brief find closes contour in a list of contours. /*! \param cntr the contour to find closes contours to it. \param dot_contours list of contours to find closest contour from. \return closest contour to cntr. */ CvContour* findClosest(CvContour* cntr,std::vector<CvContour*> dot_contours); //! \brief calculates distance of two input contours //! this method uses center of contours calcuated by minimum bounding box. /*! \param cntr1 first contour. \param cntr2 second contour. \return distance between two contours. */ float distance(CvContour* cntr1,CvContour* cntr2); } #endif
[ [ [ 1, 236 ] ] ]
54ad1e03e2a94d03dfdb9742cbb69ced0c2b65b1
cbb40e1d71bc4585ad3a58d32024090901487b76
/trunk/tokamaksrc/src/collision.cpp
58aff8a54328ad90acaa9746aa2298dcdba33499
[]
no_license
huangleon/tokamak
c0dee7b8182ced6b514b37cf9c526934839c6c2e
0218e4d17dcf93b7ab476e3e8bd4026f390f82ca
refs/heads/master
2021-01-10T10:11:42.617076
2011-08-22T02:32:16
2011-08-22T02:32:16
50,816,154
0
0
null
null
null
null
UTF-8
C++
false
false
50,114
cpp
/************************************************************************* * * * Tokamak Physics Engine, Copyright (C) 2002-2007 David Lam. * * All rights reserved. Email: [email protected] * * Web: www.tokamakphysics.com * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of EITHER: * * (1) The GNU Lesser General Public License as published by the Free * * Software Foundation; either version 2.1 of the License, or (at * * your option) any later version. The text of the GNU Lesser * * General Public License is included with this library in the * * file LICENSE.TXT. * * (2) The BSD-style license that is included with this library in * * the file LICENSE-BSD.TXT. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the files * * LICENSE.TXT and LICENSE-BSD.TXT for more details. * * * *************************************************************************/ #include "stdio.h" /* #ifdef _WIN32 #include <windows.h> #endif */ #include "tokamak.h" #include "containers.h" #include "scenery.h" #include "collision.h" #include "collision2.h" #include "constraint.h" #include "rigidbody.h" #include "scenery.h" #include "stack.h" #include "simulator.h" #include "message.h" #include "dcd.h" namespace Tokamak { s32 currentMicroStep = 0; extern f32 CONSTRAINT_THESHOLD_JOINT; extern f32 CONSTRAINT_THESHOLD_CONTACT; extern f32 CONSTRAINT_THESHOLD_LIMIT; extern f32 CONSTRAINT_CONVERGE_FACTOR_JOINT; extern f32 CONSTRAINT_CONVERGE_FACTOR_CONTACT; extern f32 CONSTRAINT_CONVERGE_FACTOR_LIMIT; s32 magicN; //extern void DrawLine(const neV3 & colour, neV3 * startpoint, s32 count); //#pragma inline_recursion( on ) //#pragma inline_depth( 50 ) neBool neCollisionResult::CheckIdle() { f32 theshold = 1.0f; if (relativeSpeed > theshold) return false; neRigidBody_* ba = bodyA->AsRigidBody(); neRigidBody_* bb = NULL; if (bodyB) { bb = bodyB->AsRigidBody(); } if (ba && ba->status == neRigidBody_::NE_RBSTATUS_IDLE) { if (bb) { if (bb->status == neRigidBody_::NE_RBSTATUS_IDLE) { return true; } else { bodyA = NULL; return false; } } else { return true; } } else if (bb && bb->status == neRigidBody_::NE_RBSTATUS_IDLE) { if (ba) { bodyB = NULL; return false; } } return false; } void neCollisionResult::StartStage2() { if (impulseType != IMPULSE_CONTACT) return; //f32 timeStep; neV3 relVel; if (bodyA) { relVel = bodyA->VelocityAtPoint(contactA) * 1.0f; //timeStep = bodyA->sim->currentTimeStep; if (bodyA->AsRigidBody()) bodyA->AsRigidBody()->needRecalc = true; } if (bodyB) { relVel -= bodyB->VelocityAtPoint(contactB); //timeStep = bodyB->sim->currentTimeStep; if (bodyB->AsRigidBody()) bodyB->AsRigidBody()->needRecalc = true; } contactBWorld = w2c * relVel; contactBWorld[2] = 0.0f; //contactBWorld.RemoveComponent(collisionFrame[2]); //contactBWorld.SetZero(); } void neCollisionResult::UpdateConstraintRelativeSpeed() { ASSERT(impulseType == IMPULSE_CONTACT); neV3 relVel; relVel.SetZero(); s32 solverStage; if (bodyA) { relVel = bodyA->VelocityAtPoint(contactA) * -1.0f; solverStage = bodyA->sim->solverStage; } if (bodyB) { relVel += bodyB->VelocityAtPoint(contactB); solverStage = bodyB->sim->solverStage; } if (solverStage != 2) { ASSERT(FALSE); return; } relativeSpeed = relVel.Dot(collisionFrame[2]); if (relativeSpeed < 0.0f) { relativeSpeed = 0.0f; } } void neCollisionResult::CalcCollisionMatrix(neRigidBody_* ba, neRigidBody_ * bb, neBool isWorld) { neM3 zero; zero.SetZero(); neM3 * IinvAW; f32 oneOnMassA; if (!ba) { oneOnMassA = 0.0f; IinvAW = &zero;//.SetZero(); } else { IinvAW = &ba->Derive().Iinv; oneOnMassA = ba->oneOnMass; } neM3 * IinvBW; f32 oneOnMassB; if (!bb) { oneOnMassB = 0.0f; IinvBW = &zero;//.SetZero(); } else { IinvBW = &bb->Derive().Iinv; oneOnMassB = bb->oneOnMass; } k.SetIdentity(); //k *= (oneOnMassA + oneOnMassB); f32 oom = oneOnMassA + oneOnMassB; k[0][0] = oom; k[1][1] = oom; k[2][2] = oom; if (isWorld) { neM3 tmp = contactA ^ (*IinvAW) ^ contactA; k = k - tmp; tmp = contactB ^ (*IinvBW) ^ contactB; k = k - tmp; } else { //neM3 w2c; //w2c.SetTranspose(collisionFrame); neV3 pointA; pointA = w2c * contactA; neV3 pointB; pointB = w2c * contactB; neM3 IinvAC; IinvAC = w2c * (*IinvAW) * collisionFrame; neM3 IinvBC; IinvBC = w2c * (*IinvBW) * collisionFrame; neM3 tmp = pointA ^ IinvAC ^ pointA; k = k - tmp; tmp = pointB ^ IinvBC ^ pointB; k = k - tmp; } kInv.SetInvert(k); ASSERT(kInv.IsFinite()); } void neCollisionResult::CalcCollisionMatrix2(neRigidBody_* ba, neRigidBody_ * bb) { k.SetZero(); if (ba) k = ba->Derive().Iinv; if (bb) k += bb->Derive().Iinv; kInv.SetInvert(k); } void neCollisionResult::CalcCollisionMatrix3(neRigidBody_* ba, neRigidBody_ * bb) { neM3 kk; kk.SetZero(); neM3 ii; ii = bb->GetB2W().rot * k; neM3 kTrans; kTrans.SetTranspose(ii); if (ba) kk = ii * ba->Derive().Iinv * kTrans; if (bb) kk += bb->Derive().Iinv; kInv.SetInvert(kk); } void neCollisionResult::PrepareForSolver(neBool aIdle, neBool bIdle) { neRigidBody_ * ba = NULL; neRigidBody_ * bb = NULL; if (bodyA && bodyA->AsRigidBody() && !aIdle) { ba = bodyA->AsRigidBody(); } if (bodyB && bodyB->AsRigidBody() && !bIdle) { bb = bodyB->AsRigidBody(); } switch (impulseType) { case IMPULSE_NORMAL: case IMPULSE_CONTACT: { ChooseAxis(collisionFrame[0], collisionFrame[1], collisionFrame[2]); ASSERT(collisionFrame.IsFinite()); w2c.SetTranspose(collisionFrame); CalcCollisionMatrix(ba, bb, false); } break; case IMPULSE_CONSTRAINT: case IMPULSE_SLIDER: case IMPULSE_SLIDER_LIMIT_PRIMARY: { CalcCollisionMatrix(ba, bb, true); } break; case IMPULSE_ANGULAR_LIMIT_PRIMARY: case IMPULSE_ANGULAR_MOTOR_PRIMARY: { CalcCollisionMatrix2(ba, bb); } break; case IMPULSE_ANGULAR_LIMIT_SECONDARY: { CalcCollisionMatrix3(ba, bb); } break; case IMPULSE_RELATIVE_LINEAR_VELOCITY: { f32 oneOnMassA, oneOnMassB; if (!ba) { oneOnMassA = 0.0f; } else { oneOnMassA = ba->oneOnMass; } if (!bb) { oneOnMassB = 0.0f; } else { oneOnMassB = bb->oneOnMass; } kInv[0][0] = 1.0f / (oneOnMassA + oneOnMassB); } break; } } void neCollision::CalcBB() { s32 i; boundingRadius = 0.0f; if (convexCount == 0) return; TConvexItem * gi = (TConvexItem *) convex; while (gi) { TConvex * g = (TConvex *)gi; gi = gi->next; f32 r = g->GetBoundRadius(); if (r > boundingRadius) boundingRadius = r; } if (convexCount == 1 && (convex->type == TConvex::BOX)) { obb = *convex; //obb.as.box.boxSize *= 1.5f; } else { neV3 maxExt, minExt; maxExt.Set(-1.0e6f, -1.0e6f, -1.0e6f); minExt.Set(1.0e6f, 1.0e6f, 1.0e6f); neV3 _maxExt, _minExt; gi = (TConvexItem *) convex; while (gi) { TConvex * g = (TConvex *)gi; gi = gi->next; g->GetExtend(_minExt, _maxExt); for (s32 j = 0; j < 3; j++) { maxExt[j] = neMax(maxExt[j], _maxExt[j]); minExt[j] = neMin(minExt[j], _minExt[j]); } } obb.c2p.rot.SetIdentity(); for (i = 0; i < 3; i++) { obb.as.box.boxSize[i] = ( maxExt[i] - minExt[i] ) * 0.5f; obb.c2p.pos[i] = minExt[i] + obb.as.box.boxSize[i]; } } } void TConvex::GetExtend(neV3 & minExt, neV3 & maxExt) { s32 i; switch (GetType()) { case TConvex::BOX: for (i = 0; i < 3; i++) { maxExt[i] = neAbs(c2p.rot[0][i]) * as.box.boxSize[0] + neAbs(c2p.rot[1][i]) * as.box.boxSize[1] + neAbs(c2p.rot[2][i]) * as.box.boxSize[2] + c2p.pos[i]; minExt[i] = -neAbs(c2p.rot[0][i]) * as.box.boxSize[0] + -neAbs(c2p.rot[1][i]) * as.box.boxSize[1] + -neAbs(c2p.rot[2][i]) * as.box.boxSize[2] + c2p.pos[i]; } break; case TConvex::SPHERE: { neV3 rad; rad.Set(Radius()); maxExt = c2p.pos + rad; minExt = c2p.pos - rad; } break; case TConvex::CYLINDER: for (i = 0; i < 3; i++) { maxExt[i] = neAbs(c2p.rot[0][i]) * CylinderRadius() + neAbs(c2p.rot[1][i]) * (CylinderHalfHeight() + CylinderRadius()) + neAbs(c2p.rot[2][i]) * CylinderRadius() + c2p.pos[i]; minExt[i] = -neAbs(c2p.rot[0][i]) * CylinderRadius() + -neAbs(c2p.rot[1][i]) * (CylinderHalfHeight() + CylinderRadius()) + -neAbs(c2p.rot[2][i]) * CylinderRadius() + c2p.pos[i]; } break; #ifdef USE_OPCODE case TConvex::OPCODE_MESH: { IceMaths::Point minex, maxex; minex.Set(1.0e6f); maxex.Set(-1.0e6f); for (u32 kk = 0; kk < as.opcodeMesh.vertCount; kk++) { minex = minex.Min(as.opcodeMesh.vertices[kk]); maxex = maxex.Max(as.opcodeMesh.vertices[kk]); } minExt = minex; maxExt = maxex; } break; #endif //USE_OPCODE case TConvex::CONVEXITY: { neV3 minex; minex.Set(1.0e6f); neV3 maxex; maxex.Set(-1.0e6f); for (s32 kk = 0; kk < as.convexMesh.vertexCount; kk++) { minex.SetMin(minex, as.convexMesh.vertices[kk]); maxex.SetMax(maxex, as.convexMesh.vertices[kk]); } minExt = minex * (2.0f + envelope); maxExt = maxex * (2.0f + envelope); } break; case TConvex::CONVEXDCD: { neV3 minex; minex.Set(1.0e6f); neV3 maxex; maxex.Set(-1.0e6f); for (s32 kk = 0; kk < as.convexDCD.numVerts; kk++) { minex.SetMin(minex, as.convexDCD.vertices[kk]); maxex.SetMax(maxex, as.convexDCD.vertices[kk]); } minExt = minex * (2.0f); maxExt = maxex * (2.0f); } break; default: ASSERT(0); } } f32 TConvex::GetBoundRadius() { f32 extend = 0.0f; switch (GetType()) { case TConvex::BOX: { neV3 v3; v3.Set(as.box.boxSize[0], as.box.boxSize[1], as.box.boxSize[2]); extend = v3.Length(); extend += c2p.pos.Length(); } break; case TConvex::SPHERE: extend = c2p.pos.Length() + as.sphere.radius; break; case TConvex::CYLINDER: //extend = c2p.pos.Length() + sqrtf(CylinderRadiusSq() + CylinderHalfHeight() * CylinderHalfHeight()); { f32 r = CylinderRadiusSq() + CylinderHalfHeight(); extend = c2p.pos.Length() + r; } break; case TConvex::CONVEXITY: { for (s32 i = 0; i < as.convexMesh.vertexCount; i++) { f32 l = as.convexMesh.vertices[i].Length(); if (l > extend) { extend = l; } } extend *= (1.0f + envelope); } break; case TConvex::CONVEXDCD: { for (s32 i = 0; i < as.convexMesh.vertexCount; i++) { f32 l = as.convexMesh.vertices[i].Length(); if (l > extend) { extend = l; } } } break; #ifdef USE_OPCODE case TConvex::OPCODE_MESH: { for (u32 kk = 0; kk < as.opcodeMesh.vertCount; kk++) { f32 tmp = as.opcodeMesh.vertices[kk].Magnitude(); if (tmp > extend) extend = tmp; } } break; #endif //USE_OPCODE default: //fprintf(stderr, "TConvex::GetExtend - error: unrecongised primitive type\n"); ASSERT(0); break; } return extend; } void TConvex::SetBoxSize(f32 width, f32 height, f32 depth) { type = TConvex::BOX; as.box.boxSize[0] = width / 2.0f; as.box.boxSize[1] = height / 2.0f; as.box.boxSize[2] = depth / 2.0f; boundingRadius = as.box.boxSize.Length(); envelope = 0.0f; } void TConvex::SetSphere(f32 radius) { type = TConvex::SPHERE; as.sphere.radius = radius; as.sphere.radiusSq = radius * radius; boundingRadius = radius; envelope = 0.0f; } void TConvex::SetConvexMesh(neByte * convexData) { type = TConvex::CONVEXDCD; as.convexDCD.convexData = convexData; s32 numFace = *((s32*)convexData); as.convexDCD.numVerts = *((s32*)convexData + 1); as.convexDCD.vertices = (neV3 *)(convexData + numFace * sizeof(f32) * 4); } void TConvex::SetTriangle(s32 a, s32 b, s32 c, neV3 * _vertices) { type = TConvex::TRIANGLE; as.tri.indices[0] = a; as.tri.indices[1] = b; as.tri.indices[2] = c; vertices = _vertices; } void TConvex::SetTerrain(neSimpleArray<s32> & triangleIndex, neArray<neTriangle_> & triangles, neV3 * _vertices) { type = TConvex::TERRAIN; as.terrain.triangles = &triangles; as.terrain.triIndex = &triangleIndex; vertices = _vertices; } #ifdef USE_OPCODE void TConvex::SetOpcodeMesh(IndexedTriangle * triIndex, u32 triCount, IceMaths::Point * vertArray, u32 vertCount) { type = TConvex::OPCODE_MESH; as.opcodeMesh.triIndices = triIndex; as.opcodeMesh.triCount = triCount; as.opcodeMesh.vertices = vertArray; as.opcodeMesh.vertCount = vertCount; } #endif //USE_OPCODE void TConvex::SetMaterialId(s32 index) { matIndex = index; } /* void TConvex::SetId(s32 _id) { id = _id; } s32 TConvex::GetId() { return id; } */ s32 TConvex::GetMaterialId() { return matIndex; } u32 TConvex::GetType() { return type; } void TConvex::SetTransform(neT3 & t3) { c2p = t3; } neT3 TConvex::GetTransform() { switch (GetType()) { case TConvex::BOX: case TConvex::CYLINDER: case TConvex::SPHERE: #ifdef USE_OPCODE case TConvex::OPCODE_MESH: #endif //USE_OPCODE return c2p; break; default: ASSERT(1); } neT3 ret; ret.SetIdentity(); return ret; } void TConvex::Initialise() { SetBoxSize(1.0f, 1.0f, 1.0f); neT3 t; t.SetIdentity(); SetTransform(t); matIndex = 0; //id = 0; userData = 0; breakInfo.mass = 1.0f; breakInfo.inertiaTensor = neBoxInertiaTensor(1.0f, 1.0f, 1.0f, 1.0f); breakInfo.breakMagnitude = 0.0f; breakInfo.breakAbsorb = 0.5f; breakInfo.neighbourRadius = 0.0f; breakInfo.flag = neGeometry::NE_BREAK_DISABLE; //break all, breakInfo.breakPlane.SetZero(); } /**************************************************************************** * * TConvex::CalcInertiaTensor * ****************************************************************************/ void TranslateCOM(neM3 & I, neV3 &translate, f32 mass, f32 factor) { s32 i,j,k; f32 change; for(i=0;i<3;i++) { for(j=i;j<3;j++) { if(i==j) { change = 0.0f; for(k=0;k<3;k++) { if(k!=i) { change += (translate[k] * translate[k]); } } } else { change += (translate[i] * translate[j]); } change *= mass; change *= factor; I[j][i] += change; if (i != j) I[i][j] += change; } } return; } neM3 TConvex::CalcInertiaTensor(f32 density, f32 & mass) { neM3 ret; ret.SetZero(); switch (GetType()) { case TConvex::BOX: { f32 xsq = as.box.boxSize[0]; f32 ysq = as.box.boxSize[1]; f32 zsq = as.box.boxSize[2]; xsq *= xsq; ysq *= ysq; zsq *= zsq; mass = as.box.boxSize[0] * as.box.boxSize[1] * as.box.boxSize[2] * 8.0f * density; ret[0][0] = (ysq + zsq) * mass / 3.0f; ret[1][1] = (xsq + zsq) * mass / 3.0f; ret[2][2] = (xsq + ysq) * mass / 3.0f; break; } default: ASSERT(1); } neM3 invrotation; //invrotation.SetInvert(c2p.rot); invrotation.SetTranspose(c2p.rot); ret = ret * invrotation; ret = c2p.rot * ret; TranslateCOM(ret, c2p.pos, mass, 1.0f); return ret; } /**************************************************************************** * * CollisionModelTest * ****************************************************************************/ void CollisionTest(neCollisionResult & result, neCollision & colA, neT3 & transA, neCollision & colB, neT3 & transB, const neV3 & backupVector) { result.penetrate = false; if (colA.convexCount == 0 || colB.convexCount == 0) { return; } neCollisionResult candidate[2]; s32 cur = 0; s32 res = 1; s32 tmp; candidate[res].depth = 0.0f; neT3 convex2WorldA; neT3 convex2WorldB; if (colA.convexCount == 1 && colB.convexCount == 1) { convex2WorldA = transA * colA.convex->c2p; if (colB.convex->type != TConvex::TERRAIN) convex2WorldB = transB * colB.convex->c2p; ConvexCollisionTest(candidate[res], *colA.convex, convex2WorldA, *colB.convex, convex2WorldB, backupVector); if (candidate[res].penetrate) { candidate[res].convexA = colA.convex; candidate[res].convexB = colB.convex; goto CollisionTest_Exit; } else { return; } } convex2WorldA = transA * colA.obb.c2p; if (colB.obb.type != TConvex::TERRAIN) convex2WorldB = transB * colB.obb.c2p; ConvexCollisionTest(candidate[res], colA.obb, convex2WorldA, colB.obb, convex2WorldB, backupVector); if (candidate[res].penetrate == false) { return; //no more to do } candidate[res].depth = 0.0f; candidate[res].penetrate = false; if (colA.convexCount == 1 && colB.convexCount > 1) { TConvexItem * gi = (TConvexItem *)colB.convex; while (gi) { TConvex * g = (TConvex *) gi; gi = gi->next; convex2WorldB = transB * g->c2p; ConvexCollisionTest(candidate[cur], *colA.convex, convex2WorldA, *g, convex2WorldB, backupVector); if (candidate[cur].penetrate && (candidate[cur].depth > candidate[res].depth)) { candidate[cur].convexA = colA.convex; candidate[cur].convexB = g; tmp = res; res = cur; cur = tmp; } } } else if (colA.convexCount > 1 && colB.convexCount == 1) { TConvexItem * gi = (TConvexItem *)colA.convex; while (gi) { TConvex * g = (TConvex *) gi; gi = gi->next; convex2WorldA = transA * g->c2p; ConvexCollisionTest(candidate[cur], *g, convex2WorldA, *colB.convex, convex2WorldB, backupVector); if (candidate[cur].penetrate && (candidate[cur].depth > candidate[res].depth)) { candidate[cur].convexA = g; candidate[cur].convexB = colB.convex; tmp = res; res = cur; cur = tmp; } } } else //colA.convexCount > 1 && colB.convexCount > 1 { const s32 totalPotentials = 100; static TConvex * potentialsA[totalPotentials]; static TConvex * potentialsB[totalPotentials]; s32 potentialsACount = 0; s32 potentialsBCount = 0; TConvexItem * giA = (TConvexItem *)colA.convex; convex2WorldB = transB * colB.obb.c2p; while (giA) { TConvex * gA = (TConvex *) giA; giA = giA->next; convex2WorldA = transA * gA->c2p; ConvexCollisionTest(candidate[0], *gA, convex2WorldA, colB.obb, convex2WorldB, backupVector); if (!candidate[0].penetrate) continue; potentialsA[potentialsACount++] = gA; } TConvexItem * giB = (TConvexItem *)colB.convex; convex2WorldA = transA * colA.obb.c2p; while (giB) { TConvex * gB = (TConvex *) giB; giB = giB->next; convex2WorldB = transB * gB->c2p; ConvexCollisionTest(candidate[0], colA.obb, convex2WorldA, *gB, convex2WorldB, backupVector); if (!candidate[0].penetrate) continue; potentialsB[potentialsBCount++] = gB; } cur = 0; res = 1; candidate[res].depth = 0.0f; candidate[res].penetrate = false; for (s32 i = 0; i < potentialsACount; i++) { convex2WorldA = transA * potentialsA[i]->c2p; for (s32 j = 0; j < potentialsBCount; j++) { convex2WorldB = transB * potentialsB[j]->c2p; ConvexCollisionTest(candidate[cur], *potentialsA[i], convex2WorldA, *potentialsB[j], convex2WorldB, backupVector); if (candidate[cur].penetrate && (candidate[cur].depth > candidate[res].depth)) { candidate[cur].convexA = potentialsA[i]; candidate[cur].convexB = potentialsB[j]; tmp = res; res = cur; cur = tmp; } } } } if (!candidate[res].penetrate) return; CollisionTest_Exit: result = candidate[res]; result.contactAWorld = result.contactA; result.contactBWorld = result.contactB; result.contactA = result.contactA - transA.pos; result.contactB = result.contactB - transB.pos; result.contactABody = transA.rot.TransposeMulV3(result.contactA); result.contactBBody = transB.rot.TransposeMulV3(result.contactB); result.materialIdA = result.convexA->GetMaterialId(); if (colB.obb.GetType() != TConvex::TERRAIN && colB.obb.GetType() != TConvex::TRIANGLE) { result.materialIdB = result.convexB->GetMaterialId(); } } /**************************************************************************** * * ConvexCollisionTest * ****************************************************************************/ void ConvexCollisionTest(neCollisionResult & result, TConvex & convexA, neT3 & transA, TConvex & convexB, neT3 & transB, const neV3 & backupVector) { switch (convexA.type) { case TConvex::BOX: switch (convexB.type) { case TConvex::BOX: Box2BoxTest(result, convexA, transA, convexB, transB, backupVector); break; case TConvex::SPHERE: Box2SphereTest(result, convexA, transA, convexB, transB); break; case TConvex::CYLINDER: Box2CylinderTest(result, convexA, transA, convexB, transB); break; case TConvex::TRIANGLE: Box2TriangleTest(result, convexA, transA, convexB, transB); break; case TConvex::TERRAIN: Box2TerrainTest(result, convexA, transA, convexB); break; case TConvex::CONVEXDCD: Box2ConvexTest(result, convexA, transA, convexB, transB, backupVector); break; #ifdef USE_OPCODE case TConvex::OPCODE_MESH: Box2OpcodeTest(result, convexA, transA, convexB, transB); break; #endif //USE_OPCODE default: ASSERT(0); break; } break; case TConvex::SPHERE: switch (convexB.type) { case TConvex::BOX: Box2SphereTest(result, convexB, transB, convexA, transA); result.Swap(); break; case TConvex::SPHERE: Sphere2SphereTest(result, convexA, transA, convexB, transB); break; case TConvex::CYLINDER: Cylinder2SphereTest(result, convexB, transB, convexA, transA); result.Swap(); break; case TConvex::TRIANGLE: //Sphere2TriangleTest(result, convexA, transA, convexB, transB); break; case TConvex::TERRAIN: Sphere2TerrainTest(result, convexA, transA, convexB); break; #ifdef USE_OPCODE case TConvex::OPCODE_MESH: Sphere2OpcodeTest(result, convexA, transA, convexB, transB); break; #endif //USE_OPCODE default: ASSERT(0); break; } break; case TConvex::CYLINDER: switch (convexB.type) { case TConvex::BOX: Box2CylinderTest(result, convexB, transB, convexA, transA); result.Swap(); break; case TConvex::CYLINDER: Cylinder2CylinderTest(result, convexA, transA, convexB, transB); break; case TConvex::SPHERE: Cylinder2SphereTest(result, convexA, transA, convexB, transB); break; case TConvex::TRIANGLE: //Sphere2TriangleTest(result, convexA, transA, convexB, transB); break; case TConvex::TERRAIN: Cylinder2TerrainTest(result, convexA, transA, convexB); break; #ifdef USE_OPCODE case TConvex::OPCODE_MESH: Cylinder2OpcodeTest(result, convexA, transA, convexB, transB); break; #endif //USE_OPCODE default: ASSERT(0); break; } break; #ifdef USE_OPCODE case TConvex::OPCODE_MESH: switch(convexB.type) { case TConvex::BOX: Box2OpcodeTest(result, convexB, transB, convexA, transA); result.Swap(); break; case TConvex::SPHERE: Sphere2OpcodeTest(result, convexB, transB, convexA, transA); result.Swap(); break; case TConvex::CYLINDER: Cylinder2OpcodeTest(result, convexB, transB, convexA, transA); result.Swap(); break; case TConvex::TERRAIN: Opcode2TerrainTest(result, convexA, transA, convexB); break; case TConvex::OPCODE_MESH: Opcode2OpcodeTest(result, convexA, transA, convexB, transB); break; default: ASSERT(0); break; }; break; #endif //USE_OPCODE case TConvex::CONVEXDCD: { switch (convexB.type) { case TConvex::CONVEXDCD: Convex2ConvexTest(result, convexA, transA, convexB, transB, backupVector); break; case TConvex::BOX: Box2ConvexTest(result, convexB, transB, convexA, transA, -backupVector); result.Swap(); break; case TConvex::TERRAIN: Convex2TerrainTest(result, convexA, transA, convexB); break; } break; } default: ASSERT(0); break; } } /**************************************************************************** * * Box2BoxTest * ****************************************************************************/ #if 1 void Box2BoxTest(neCollisionResult & result, TConvex & convexA, neT3 & transA, TConvex & convexB, neT3 & transB, const neV3 & backupVector) { /* neCollisionResult dcdresult; TestDCD(dcdresult, convexA, transA, convexB, transB, backupVector); if (dcdresult.penetrate) { result.penetrate = true; result.depth = dcdresult.depth; result.collisionFrame[2] = dcdresult.collisionFrame[2]; result.contactA = dcdresult.contactA; result.contactB = dcdresult.contactB; } else { result.penetrate = false; } return; */ ConvexTestResult res; BoxTestParam boxParamA; BoxTestParam boxParamB; boxParamA.convex = &convexA; boxParamA.trans = &transA; boxParamA.radii[0] = transA.rot[0] * convexA.as.box.boxSize[0]; boxParamA.radii[1] = transA.rot[1] * convexA.as.box.boxSize[1]; boxParamA.radii[2] = transA.rot[2] * convexA.as.box.boxSize[2]; boxParamB.convex = &convexB; boxParamB.trans = &transB; boxParamB.radii[0] = transB.rot[0] * convexB.as.box.boxSize[0]; boxParamB.radii[1] = transB.rot[1] * convexB.as.box.boxSize[1]; boxParamB.radii[2] = transB.rot[2] * convexB.as.box.boxSize[2]; if (boxParamA.BoxTest(res, boxParamB)) { //return; result.penetrate = true; result.depth = res.depth; // result.collisionFrame[0] = res.contactX; // result.collisionFrame[1] = res.contactY; result.collisionFrame[2] = res.contactNormal; // if (res.isEdgeEdge) { result.contactA = res.contactA; result.contactB = res.contactB; } // else // { // result.contactA = res.contactA; // // result.contactB = res.contactB; // } } else { result.penetrate = false; } // ASSERT(result.penetrate == dcdresult.penetrate); } #else void Box2BoxTest(neCollisionResult & result, TConvex & convexA, neT3 & transA, TConvex & convexB, neT3 & transB, neV3 & backupVector) { Simplex simplex; GJKObj gjkObjA, gjkObjB; simplex.cache_valid = false; simplex.epsilon = 1.0e-6f; gjkObjA.half_box.Set(convexA.as.box.boxSize); gjkObjB.half_box.Set(convexB.as.box.boxSize); gjkObjA.scaleFactor = 1.0f; gjkObjB.scaleFactor = 1.0f; gjkObjA.type = GJK_BOX; gjkObjB.type = GJK_BOX; gjkObjA.lw = &transA; gjkObjB.lw = &transB; gjkObjA.lwrot = &transA.rot; gjkObjB.lwrot = &transB.rot; f32 envelopeA = convexA.envelope = 0.1f; f32 envelopeB = convexB.envelope = 0.1f; f32 envelope = envelopeA + envelopeB; f32 dist = calc_dist(&simplex, &gjkObjA, &gjkObjB, 1); if (dist > 0) { dist = sqrtf(dist); ASSERT(dist > 0.0f); if (dist < envelope) { neV3 pa, pb; pa = transA * simplex.closest_pointA; pb = transB * simplex.closest_pointB; neV3 diff = pa - pb; diff.Normalize(); result.collisionFrame[2] = diff; result.depth = envelope - dist; result.contactA = pa - diff * envelopeA; result.contactB = pb + diff * envelopeB; result.penetrate = true; } else result.penetrate = false; } else { neV3 posA, posB; posA = transA.pos; posB = transB.pos; f32 dist = 0.0f; //simplex.cache_valid = false; neV3 bv = backupVector * 10.0f; transA.pos += bv; dist = calc_dist(&simplex, &gjkObjA, &gjkObjB, 1); if (dist > 0.0f) { neV3 pa, pb; pa = transA * simplex.closest_pointA; pb = transB * simplex.closest_pointB; neV3 diff = pa - pb; f32 d = diff.Length(); result.collisionFrame[2] = diff * (1.0f / d); transA.pos = posA; pa = transA * simplex.closest_pointA; diff = pb - pa; d = diff.Length(); result.depth = d + envelope; result.penetrate = true; result.contactA = pa; result.contactB = pb; } else { //result.penetrate = false; //return; f32 shrink = 0.8f; transA.pos = posA; simplex.cache_valid = false; for (s32 i = 0; i < 5; i++) { simplex.cache_valid = false; gjkObjA.scaleFactor = shrink; gjkObjB.scaleFactor = shrink; dist = calc_dist(&simplex, &gjkObjA, &gjkObjB, 1); if (dist > 0.0f) break; shrink *= 0.8f; } if (dist == 0.0f) { result.penetrate = false; return; } if (!simplex.closest_pointA.IsFinite() || !simplex.closest_pointB.IsFinite() ) { result.penetrate = false; return; } neV3 pa, pb; pa = transA * simplex.closest_pointA; pb = transB * simplex.closest_pointB; neV3 diff = pa - pb; diff.Normalize(); f32 factor; if (convexA.boundingRadius > convexB.boundingRadius) factor = convexA.boundingRadius; else factor = convexB.boundingRadius; transA.pos += (diff * factor); simplex.cache_valid = false; ASSERT(transA.pos.IsFinite()); gjkObjA.scaleFactor = 1.0f; gjkObjB.scaleFactor = 1.0f; dist = calc_dist(&simplex, &gjkObjA, &gjkObjB, 1); ASSERT(dist > 0.0f); transA.pos = posA; result.contactA = transA * simplex.closest_pointA; result.contactB = transB * simplex.closest_pointB; result.penetrate = true; result.collisionFrame[2] = result.contactB - result.contactA; result.depth = result.collisionFrame[2].Length(); result.collisionFrame[2] *= (1.0f / result.depth); result.depth += envelope; } } } #endif /* void Convex2ConvexTest(neCollisionResult & result, TConvex & convexA, neT3 & transA, TConvex & convexB, neT3 & transB, neV3 & backupVector) { Simplex simplex; GJKObj gjkObjA, gjkObjB; simplex.cache_valid = false; simplex.epsilon = 1.0e-6f; //gjkObjA.half_box.Set(convexA.as.box.boxSize); //gjkObjB.half_box.Set(convexB.as.box.boxSize); gjkObjA.vp = convexA.as.convexMesh.vertices; gjkObjA.neighbors = convexA.as.convexMesh.neighbours; gjkObjB.vp = convexB.as.convexMesh.vertices; gjkObjB.neighbors = convexB.as.convexMesh.neighbours; gjkObjA.scaleFactor = 1.0f; gjkObjB.scaleFactor = 1.0f; gjkObjA.type = GJK_MESH; gjkObjB.type = GJK_MESH; simplex.hintA = 0; simplex.hintB = 0; gjkObjA.lw = &transA; gjkObjB.lw = &transB; gjkObjA.lwrot = &transA.rot; gjkObjB.lwrot = &transB.rot; f32 envelopeA = convexA.envelope; f32 envelopeB = convexB.envelope; f32 envelope = envelopeA + envelopeB; f32 dist = calc_dist(&simplex, &gjkObjA, &gjkObjB, 1); if (dist > 0) { dist = sqrtf(dist); ASSERT(dist > 0.0f); if (dist < envelope) { neV3 pa, pb; pa = transA * simplex.closest_pointA; pb = transB * simplex.closest_pointB; neV3 diff = pa - pb; diff.Normalize(); result.collisionFrame[2] = diff; result.depth = envelope - dist; result.contactA = pa - diff * envelopeA; result.contactB = pb + diff * envelopeB; result.penetrate = true; } else result.penetrate = false; } else { neV3 posA, posB; posA = transA.pos; posB = transB.pos; f32 dist = 0.0f; simplex.cache_valid = false; //neV3 bv = posA - posB; neV3 bv = backupVector; bv.Normalize(); bv *= (convexA.boundingRadius * 100.0f); transA.pos += bv; dist = calc_dist(&simplex, &gjkObjA, &gjkObjB, 1); if (0)//dist > 0.0f) { neV3 pa, pb; pa = transA * simplex.closest_pointA; pb = transB * simplex.closest_pointB; neV3 diff = pa - pb; f32 d = diff.Length(); result.collisionFrame[2] = diff * (1.0f / d); transA.pos = posA; pa = transA * simplex.closest_pointA; diff = pb - pa; d = diff.Length(); result.depth = d + envelope; result.penetrate = true; result.contactA = pa; result.contactB = pb; } else { //result.penetrate = false; //return; f32 shrink = 0.8f; transA.pos = posA; simplex.cache_valid = false; for (s32 i = 0; i < 5; i++) { simplex.cache_valid = false; gjkObjA.scaleFactor = shrink; gjkObjB.scaleFactor = shrink; dist = calc_dist(&simplex, &gjkObjA, &gjkObjB, 1); if (dist > 0.0f) break; shrink *= 0.8f; } if (dist == 0.0f) { result.penetrate = false; return; } if (!simplex.closest_pointA.IsFinite() || !simplex.closest_pointB.IsFinite() ) { result.penetrate = false; return; } neV3 pa, pb; pa = transA * simplex.closest_pointA; pb = transB * simplex.closest_pointB; neV3 diff = pa - pb; diff.Normalize(); f32 factor; if (convexA.boundingRadius > convexB.boundingRadius) factor = convexA.boundingRadius; else factor = convexB.boundingRadius; transA.pos = posA + (diff * factor * 10.0f); simplex.cache_valid = false; ASSERT(transA.pos.IsFinite()); gjkObjA.scaleFactor = 1.0f; gjkObjB.scaleFactor = 1.0f; dist = calc_dist(&simplex, &gjkObjA, &gjkObjB, 1); ASSERT(dist > 0.0f); pa = transA * simplex.closest_pointA; pb = transB * simplex.closest_pointB; diff = pa - pb; diff.Normalize(); result.collisionFrame[2] = diff; transA.pos = posA; result.contactA = transA * simplex.closest_pointA; result.contactB = pb;//transB * simplex.closest_pointB; result.penetrate = true; diff = result.contactB - result.contactA; result.depth = diff.Length(); result.depth += envelope; } } } */ void Convex2ConvexTest(neCollisionResult & result, TConvex & convexA, neT3 & transA, TConvex & convexB, neT3 & transB, const neV3 & backupVector) { neCollisionResult dcdresult; TestDCD(dcdresult, convexA, transA, convexB, transB, backupVector); if (dcdresult.penetrate) { result.penetrate = true; result.depth = dcdresult.depth; result.collisionFrame[2] = dcdresult.collisionFrame[2]; result.contactA = dcdresult.contactA; result.contactB = dcdresult.contactB; } else { result.penetrate = false; } return; } void Box2ConvexTest(neCollisionResult & result, TConvex & convexA, neT3 & transA, TConvex & convexB, neT3 & transB, const neV3 & backupVector) { neCollisionResult dcdresult; TestDCD(dcdresult, convexA, transA, convexB, transB, backupVector); if (dcdresult.penetrate) { result.penetrate = true; result.depth = dcdresult.depth; result.collisionFrame[2] = dcdresult.collisionFrame[2]; result.contactA = dcdresult.contactA; result.contactB = dcdresult.contactB; } else { result.penetrate = false; } return; } /* void Box2ConvexTest(neCollisionResult & result, TConvex & convexA, neT3 & transA, TConvex & convexB, neT3 & transB, neV3 & backupVector) { Simplex simplex; GJKObj gjkObjA, gjkObjB; simplex.cache_valid = false; simplex.epsilon = 1.0e-6f; gjkObjA.half_box.Set(convexA.as.box.boxSize); //gjkObjB.half_box.Set(convexB.as.box.boxSize); gjkObjB.vp = convexB.as.convexMesh.vertices; gjkObjB.neighbors = convexB.as.convexMesh.neighbours; gjkObjA.scaleFactor = 1.0f; gjkObjB.scaleFactor = 1.0f; gjkObjA.type = GJK_BOX; gjkObjB.type = GJK_MESH; simplex.hintB = 0; gjkObjA.lw = &transA; gjkObjB.lw = &transB; gjkObjA.lwrot = &transA.rot; gjkObjB.lwrot = &transB.rot; f32 envelopeA = 0.0f;//convexA.envelope = 0.05f; f32 envelopeB = convexB.envelope; f32 envelope = envelopeA + envelopeB; f32 dist = calc_dist(&simplex, &gjkObjA, &gjkObjB, 1); if (dist > 0) { dist = sqrtf(dist); ASSERT(dist > 0.0f); if (dist < envelope) { neV3 pa, pb; pa = transA * simplex.closest_pointA; pb = transB * simplex.closest_pointB; neV3 diff = pa - pb; diff.Normalize(); result.collisionFrame[2] = diff; result.depth = envelope - dist; result.contactA = pa - diff * envelopeA; result.contactB = pb + diff * envelopeB; result.penetrate = true; } else result.penetrate = false; } else { neV3 posA, posB; posA = transA.pos; posB = transB.pos; f32 dist = 0.0f; //simplex.cache_valid = false; neV3 bv = backupVector * 10.0f; transA.pos += bv; dist = calc_dist(&simplex, &gjkObjA, &gjkObjB, 1); if (dist > 0.0f) { neV3 pa, pb; pa = transA * simplex.closest_pointA; pb = transB * simplex.closest_pointB; neV3 diff = pa - pb; f32 d = diff.Length(); result.collisionFrame[2] = diff * (1.0f / d); transA.pos = posA; pa = transA * simplex.closest_pointA; diff = pb - pa; d = diff.Length(); result.depth = d + envelope; result.penetrate = true; result.contactA = pa; result.contactB = pb; } else { //result.penetrate = false; //return; f32 shrink = 0.8f; //transA.pos = posA; simplex.cache_valid = false; for (s32 i = 0; i < 5; i++) { simplex.cache_valid = false; gjkObjA.scaleFactor = shrink; gjkObjB.scaleFactor = shrink; dist = calc_dist(&simplex, &gjkObjA, &gjkObjB, 1); if (dist > 0.0f) break; shrink *= 0.8f; } if (dist == 0.0f) { result.penetrate = false; return; } if (!simplex.closest_pointA.IsFinite() || !simplex.closest_pointB.IsFinite() ) { result.penetrate = false; return; } neV3 pa, pb; pa = transA * simplex.closest_pointA; pb = transB * simplex.closest_pointB; neV3 diff = pa - pb; diff.Normalize(); f32 factor; if (convexA.boundingRadius > convexB.boundingRadius) factor = convexA.boundingRadius; else factor = convexB.boundingRadius; transA.pos += (diff * factor); simplex.cache_valid = false; ASSERT(transA.pos.IsFinite()); gjkObjA.scaleFactor = 1.0f; gjkObjB.scaleFactor = 1.0f; dist = calc_dist(&simplex, &gjkObjA, &gjkObjB, 1); ASSERT(dist > 0.0f); transA.pos = posA; result.contactA = transA * simplex.closest_pointA; result.contactB = transB * simplex.closest_pointB; result.penetrate = true; result.collisionFrame[2] = result.contactB - result.contactA; result.depth = result.collisionFrame[2].Length(); result.collisionFrame[2] *= (1.0f / result.depth); result.depth += envelope; } } } */ void BoxTestParam::CalcVertInWorld() { isVertCalc = true; verts[0] = trans->pos + radii[0] + radii[1] + radii[2]; verts[1] = trans->pos + radii[0] + radii[1] - radii[2]; verts[2] = trans->pos + radii[0] - radii[1] + radii[2]; verts[3] = trans->pos + radii[0] - radii[1] - radii[2]; verts[4] = trans->pos - radii[0] + radii[1] + radii[2]; verts[5] = trans->pos - radii[0] + radii[1] - radii[2]; verts[6] = trans->pos - radii[0] - radii[1] + radii[2]; verts[7] = trans->pos - radii[0] - radii[1] - radii[2]; } bool BoxTestParam::BoxTest(ConvexTestResult & result, BoxTestParam & otherBox) { result.depth = 1.e5f; result.isEdgeEdge = false; result.valid = false; if (MeasureVertexFacePeneration(result, otherBox, 0) && //vertex of B with face of A MeasureVertexFacePeneration(result, otherBox, 1) && MeasureVertexFacePeneration(result, otherBox, 2)) { result.contactNormal *= -1.0f; // normal points toward A (this) neV3 tmp = result.contactA; result.contactA = result.contactB; result.contactB = tmp; } else { return false; } if (otherBox.MeasureVertexFacePeneration(result, *this, 0) && //vertex of A with face of B otherBox.MeasureVertexFacePeneration(result, *this, 1) && otherBox.MeasureVertexFacePeneration(result, *this, 2)) { } else { return false; } ConvexTestResult result2; result2.valid = false; result2.depth = result.depth; bool edgeCollided = false; if (MeasureEdgePeneration(result2, otherBox, 0, 0) && MeasureEdgePeneration(result2, otherBox, 0, 1) && MeasureEdgePeneration(result2, otherBox, 0, 2) && MeasureEdgePeneration(result2, otherBox, 1, 0) && MeasureEdgePeneration(result2, otherBox, 1, 1) && MeasureEdgePeneration(result2, otherBox, 1, 2) && MeasureEdgePeneration(result2, otherBox, 2, 0) && MeasureEdgePeneration(result2, otherBox, 2, 1) && MeasureEdgePeneration(result2, otherBox, 2, 2) ) { if (result2.valid) edgeCollided = true; } else { return false; } if (edgeCollided) { result2.ComputerEdgeContactPoint(result); result.isEdgeEdge = true; result.contactNormal = result2.contactNormal * -1.0f; } else { return result.valid; } return result.valid; } bool BoxTestParam::MeasureVertexFacePeneration(ConvexTestResult & result, BoxTestParam & otherBox, s32 whichFace) { neV3 me2otherBox; me2otherBox = otherBox.trans->pos - trans->pos; neV3 direction; direction = trans->rot[whichFace]; neV3 contactPoint; contactPoint = otherBox.trans->pos; f32 penetrated; bool reverse = false; if ((penetrated = me2otherBox.Dot(direction)) < 0.0f) { direction = direction * -1.0f; reverse = true; } else { penetrated = penetrated * -1.0f; } penetrated += convex->as.box.boxSize[whichFace]; neV3 progression; progression = direction * otherBox.radii; neV3 sign; sign[0] = progression[0] > 0.0f ? 1.0f: -1.0f; sign[1] = progression[1] > 0.0f ? 1.0f: -1.0f; sign[2] = progression[2] > 0.0f ? 1.0f: -1.0f; penetrated += (progression[0] * sign[0]); penetrated += (progression[1] * sign[1]); penetrated += (progression[2] * sign[2]); contactPoint -= (otherBox.radii[0] * sign[0]); contactPoint -= (otherBox.radii[1] * sign[1]); contactPoint -= (otherBox.radii[2] * sign[2]); if (penetrated <= 0.0f) return false; if ((penetrated + 0.0001f) < result.depth) { result.depth = penetrated; result.contactA = contactPoint; // contactPoint is vertex of otherBox result.contactB = contactPoint + direction * penetrated; result.valid = true; result.contactNormal = direction; } else if (neIsConsiderZero(penetrated - result.depth)) { s32 otherAxis1 = neNextDim1[whichFace]; s32 otherAxis2 = neNextDim2[whichFace]; //check to see if this one fall into the faces neV3 sub = contactPoint - trans->pos; f32 dot = neAbs(sub.Dot(trans->rot[otherAxis1])); if (dot > (convex->as.box.boxSize[otherAxis1] * 1.001f)) return true;// not false ???? no it is true!!! dot = neAbs(sub.Dot(trans->rot[otherAxis2])); if (dot > (convex->as.box.boxSize[otherAxis2] * 1.001f)) return true;// not false ???? no it is true!!! result.depth = penetrated; result.contactA = contactPoint; result.contactB = contactPoint + direction * penetrated; result.valid = true; result.contactNormal = direction; } return true; } neBool BoxTestParam::MeasureEdgePeneration(ConvexTestResult & result, BoxTestParam & otherBox, s32 dim1, s32 dim2) { neV3 contactA = trans->pos; neV3 contactB = otherBox.trans->pos; neV3 contactNormal = trans->rot[dim1].Cross(otherBox.trans->rot[dim2]); f32 len = contactNormal.Length(); if (neIsConsiderZero(len)) return true; contactNormal *= (1.0f / len); neV3 me2OtherBox = otherBox.trans->pos - trans->pos; f32 penetrated = me2OtherBox.Dot(contactNormal); bool reverse = false; if (penetrated < 0.0f) { contactNormal = contactNormal * -1.0f; reverse = true; } else penetrated = penetrated * -1.0f; f32 progression[4]; s32 otherAxisA1 = (dim1 + 1) % 3; s32 otherAxisA2 = (dim1 + 2) % 3; s32 otherAxisB1 = (dim2 + 1) % 3; s32 otherAxisB2 = (dim2 + 2) % 3; progression[0] = radii[otherAxisA1].Dot(contactNormal); progression[1] = radii[otherAxisA2].Dot(contactNormal); progression[2] = otherBox.radii[otherAxisB1].Dot(contactNormal); progression[3] = otherBox.radii[otherAxisB2].Dot(contactNormal); f32 sign[4]; sign[0] = progression[0] > 0.0f ? 1.0f: -1.0f; sign[1] = progression[1] > 0.0f ? 1.0f: -1.0f; sign[2] = progression[2] > 0.0f ? 1.0f: -1.0f; sign[3] = progression[3] > 0.0f ? 1.0f: -1.0f; penetrated += (progression[0] * sign[0]); penetrated += (progression[1] * sign[1]); penetrated += (progression[2] * sign[2]); penetrated += (progression[3] * sign[3]); contactA += (radii[otherAxisA1] * sign[0]); contactA += (radii[otherAxisA2] * sign[1]); contactB -= (otherBox.radii[otherAxisB1] * sign[2]); contactB -= (otherBox.radii[otherAxisB2] * sign[3]); if(penetrated <= 0.0f) return false; if (penetrated < result.depth) { result.depth = penetrated; result.valid = true; result.edgeA[0] = contactA + (radii[dim1]); result.edgeA[1] = contactA - (radii[dim1]); result.edgeB[0] = contactB + (otherBox.radii[dim2]); result.edgeB[1] = contactB - (otherBox.radii[dim2]); result.contactA = contactA; result.contactB = contactB; /* if (reverse) result.contactX = trans->rot[dim1]; else result.contactX = trans->rot[dim1]; result.contactY = contactNormal.Cross(result.contactX); */ result.contactNormal = contactNormal; } return true; } neBool ConvexTestResult::ComputerEdgeContactPoint(ConvexTestResult & res) { f32 d1343, d4321, d1321, d4343, d2121; f32 numer, denom, au, bu; neV3 p13; neV3 p43; neV3 p21; // neV3 diff; p13 = (edgeA[0]) - (edgeB[0]); p43 = (edgeB[1]) - (edgeB[0]); if ( p43.IsConsiderZero() ) { goto ComputerEdgeContactPoint_Exit; } p21 = (edgeA[1]) - (edgeA[0]); if ( p21.IsConsiderZero() ) { goto ComputerEdgeContactPoint_Exit; } d1343 = p13.Dot(p43); d4321 = p43.Dot(p21); d1321 = p13.Dot(p21); d4343 = p43.Dot(p43); d2121 = p21.Dot(p21); denom = d2121 * d4343 - d4321 * d4321; if (neAbs(denom) < NE_ZERO) goto ComputerEdgeContactPoint_Exit; numer = d1343 * d4321 - d1321 * d4343; au = numer / denom; bu = (d1343 + d4321 * (au)) / d4343; if (au < 0.0f || au >= 1.0f) goto ComputerEdgeContactPoint_Exit; if (bu < 0.0f || bu >= 1.0f) goto ComputerEdgeContactPoint_Exit; { neV3 tmpv; tmpv = p21 * au; res.contactA = (edgeA[0]) + tmpv; tmpv = p43 * bu; res.contactB = (edgeB[0]) + tmpv; } // diff = (res.contactA) - (res.contactB); res.depth = depth;//sqrtf(diff.Dot(diff)); return true; ComputerEdgeContactPoint_Exit: //res.contactA = contactA; //res.contactB = contactB; //diff = (res.contactA) - (res.contactB); res.depth = depth;//sqrtf(diff.Dot(diff)); return false; } neBool ConvexTestResult::ComputerEdgeContactPoint2(f32 & au, f32 & bu) { f32 d1343, d4321, d1321, d4343, d2121; f32 numer, denom; neV3 p13; neV3 p43; neV3 p21; neV3 diff; p13 = (edgeA[0]) - (edgeB[0]); p43 = (edgeB[1]) - (edgeB[0]); if ( p43.IsConsiderZero() ) { valid = false; goto ComputerEdgeContactPoint2_Exit; } p21 = (edgeA[1]) - (edgeA[0]); if ( p21.IsConsiderZero() ) { valid = false; goto ComputerEdgeContactPoint2_Exit; } d1343 = p13.Dot(p43); d4321 = p43.Dot(p21); d1321 = p13.Dot(p21); d4343 = p43.Dot(p43); d2121 = p21.Dot(p21); denom = d2121 * d4343 - d4321 * d4321; if (neAbs(denom) < NE_ZERO) { valid = false; goto ComputerEdgeContactPoint2_Exit; } numer = d1343 * d4321 - d1321 * d4343; au = numer / denom; bu = (d1343 + d4321 * (au)) / d4343; if (au < 0.0f || au >= 1.0f) { valid = false; } else if (bu < 0.0f || bu >= 1.0f) { valid = false; } else { valid = true; } { neV3 tmpv; tmpv = p21 * au; contactA = (edgeA[0]) + tmpv; tmpv = p43 * bu; contactB = (edgeB[0]) + tmpv; } diff = contactA - contactB; depth = sqrtf(diff.Dot(diff)); return true; ComputerEdgeContactPoint2_Exit: return false; } neBool BoxTestParam::LineTest(ConvexTestResult & res, neV3 & point1, neV3 & point2) { return false; } }
[ [ [ 1, 2507 ] ] ]
c151e4452c8862125bd7349cc1ced5f50af95649
668dc83d4bc041d522e35b0c783c3e073fcc0bd2
/fbide-wx/sdk/include/sdk/PluginManager.h
4a3801608c0a5bf2b2a9bcf91e54ec4018054658
[]
no_license
albeva/fbide-old-svn
4add934982ce1ce95960c9b3859aeaf22477f10b
bde1e72e7e182fabc89452738f7655e3307296f4
refs/heads/master
2021-01-13T10:22:25.921182
2009-11-19T16:50:48
2009-11-19T16:50:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,551
h
/* * This file is part of FBIde project * * FBIde is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * FBIde is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with FBIde. If not, see <http://www.gnu.org/licenses/>. * * Author: Albert Varaksin <[email protected]> * Copyright (C) The FBIde development team */ #ifndef PLUGINMANAGER_H_INCLUDED #define PLUGINMANAGER_H_INCLUDED namespace fb { // fwd ref class CPluginProviderBase; class CPluginManager; /** * To ease differentation between plugins... */ enum PluginType { PLUGINTYPE_ARTPROVIDER, PLUGINTYPE_EDITOR, PLUGINTYPE_TOOL, PLUGINTYPE_WIZARD }; /** * Base class for plugins */ class DLLIMPORT CPluginBase { // allow PluginManager to access private bits friend class CPluginManager; // Get provider CPluginProviderBase * GetProvider (); // Set provider void SetProvider (CPluginProviderBase *); // Set this plugin to be "attached" void SetAttached (bool attached); public : // Create new plugin instance (should be a template?) CPluginBase (); // destroy virtual ~CPluginBase() {} // Get type PluginType GetType (); // Get plugin name wxString GetName (); // Is attached bool IsAttached (); // Unload this plugin (should be used with care) void Unload (); // Call on attach virtual bool Attach () = 0; // notify unload virtual void NotifyExit () {} // And when detached virtual bool Detach (bool force) { return true; }; private : CPluginProviderBase * m_provider; bool m_isAttached; }; /** * Base class for plugin registrants */ class DLLIMPORT CPluginProviderBase { public : // Get plugin instance (if loaded) CPluginBase * GetPlugin () { return m_plugin; } // get plugin type PluginType GetType () { return m_type; } // get sdk version virtual int GetSDKVersion() = 0; // Get plugin name (registration name) wxString GetName () { return m_name; } // Is loaded ? bool IsLoaded () { return m_plugin != NULL; }; protected : // Allow plugin manager to access private bits friend class CPluginManager; PluginType m_type; wxString m_name; CPluginBase * m_plugin; wxDynamicLibrary * m_dll; // Create plugin registrant object CPluginProviderBase (PluginType type, const wxString & name) : m_type(type), m_name(name), m_plugin(NULL), m_dll(NULL) {} // clean up... virtual ~CPluginProviderBase () {} // Get plugin instance (if loaded) virtual CPluginBase * Create () = 0; // Destroy plugin void Release () { if (m_plugin == NULL) return; delete m_plugin; m_plugin = NULL; } // Set the DLL handle void SetDll (wxDynamicLibrary * dll) { m_dll = dll; } // Get Dll wxDynamicLibrary * GetDll () { return m_dll; } }; /** * This class manages the plugins * * Can be accessed via CManager */ class DLLIMPORT CPluginManager { public : // Register new plugin provider void AddProvider (const wxString & name, CPluginProviderBase * registrant); // Load plugin by ID. (fbide/ide/plugins is default folder) CPluginBase * LoadPlugin (const wxString & name); // Will only load dll but not instantiate the plugin bool LoadPluginFile (const wxString & file); // Get plugin instance (if loaded) CPluginBase * GetPlugin (const wxString & name); // Unload the plugin. bool Unload (CPluginBase * plugin, bool force); bool Unload (const wxString & name, bool force); // Unload all plugins void UnloadAll (); // send unload notification void NotifyUnload (); private : friend class CManager; CPluginManager (); ~CPluginManager (); struct CData ; std::auto_ptr<CData> m_data; }; /** * Template used for registaring ny plugins easily and hasslefree. * namespace * { * CPluginProvider<PluginClass, PLUGINTYPE> plugin(_T("PluginName")); * } */ template<class T, PluginType type> class CPluginProvider : public CPluginProviderBase { public: CPluginProvider(const wxString& name) : CPluginProviderBase(type, name) { CManager::Get()->GetPluginManager()->AddProvider(name, this); } /** * Destroy */ virtual ~CPluginProvider() {} /** * Get plugin instance */ virtual CPluginBase * Create () { if (m_plugin == NULL) m_plugin = new T (); return m_plugin; } /** * Get version */ virtual int GetSDKVersion() { return (SDK_VERSION_MAJOR * 1000) + (SDK_VERSION_MINOR * 100) + SDK_VERSION_RELEASE; } }; } #endif // PLUGINMANAGER_H_INCLUDED
[ "vongodric@957c6b5c-1c3a-0410-895f-c76cfc11fbc7" ]
[ [ [ 1, 252 ] ] ]