<commit_before>#include <osg/Vec3>
#include <osg/Vec4>
#include <osg/Quat>
#include <osg/Matrix>
#include <osg/ShapeDrawable>
#include <osg/Geometry>
#include <osg/Geode>
#include <osg/Texture2D>

#include <osgDB/FileUtils>
#include <osgDB/ReadFile>

#include <osgUtil/Optimizer>

#include <osgProducer/Viewer>

char vertexShaderSource[] =
    "uniform vec2  xCoeff; \n"
    "uniform vec2  yCoeff; \n"
    "\n"
    "void main(void) \n"
    "{ \n"
    "\n"
    "    gl_TexCoord[0] = gl_Vertex; \n"
    "    gl_Vertex.z = gl_Vertex.x*xCoeff[0] + gl_Vertex.x*gl_Vertex.x* xCoeff[1] + \n"
    "                  gl_Vertex.y*yCoeff[1] + gl_Vertex.y*gl_Vertex.y* yCoeff[1]; \n"
    "    gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;\n"
    "}\n";

char fragmentShaderSource[] =
    "uniform sampler2D baseTexture; \n"
    "\n"
    "void main(void) \n"
    "{ \n"
    "    gl_FragColor = texture2D( baseTexture, gl_TexCoord[0].xy); \n"
    "}\n";

class UniformVarying : public osg::Uniform::Callback
{
    virtual void operator () (osg::Uniform* uniform, osg::NodeVisitor* nv)
    {
        const osg::FrameStamp* fs = nv->getFrameStamp();
        float value = sinf(fs->getReferenceTime());
        uniform->set(osg::Vec2(value,-value));
    }
};

osg::Node* createModel()
{
    osg::Geode* geode = new osg::Geode;

    osg::Geometry* geom = new osg::Geometry;
    geode->addDrawable(geom);

    // dimensions for ~one million triangles :-)
    unsigned int num_x = 708;
    unsigned int num_y = 708;

    osg::Vec3Array* vertices = new osg::Vec3Array( num_x * num_y );

    float dx = 1.0f/(float)(num_x-1);
    float dy = 1.0f/(float)(num_y-1);
    osg::Vec3 row(0.0f,0.0f,0.0);

    unsigned int vert_no = 0;
    for(unsigned int iy=0; iy<num_y; ++iy)
    {
        osg::Vec3 column = row;
        for(unsigned int ix=0;ix<num_x;++ix)
        {
            (*vertices)[vert_no++] = column;
            column.x() += dx;
        }
        row.y() += dy;
    }

    geom->setVertexArray(vertices);

    for(unsigned int iy=0; iy<num_y-1; ++iy)
    {
        unsigned int element_no = 0;
        osg::DrawElementsUInt* elements = new osg::DrawElementsUInt(GL_TRIANGLE_STRIP, num_x*2);
        unsigned int index = iy * num_x;
        for(unsigned int ix = 0; ix<num_x; ++ix)
        {
            (*elements)[element_no++] = index + num_x;
            (*elements)[element_no++] = index++;
        }
        geom->addPrimitiveSet(elements);
    }

    geom->setUseVertexBufferObjects(true);

    osg::StateSet* stateset = geom->getOrCreateStateSet();

    osg::Program* program = new osg::Program;
    stateset->setAttribute(program);

    osg::Shader* vertex_shader = new osg::Shader(osg::Shader::VERTEX, vertexShaderSource);
    program->addShader(vertex_shader);

    osg::Shader* fragment_shader = new osg::Shader(osg::Shader::FRAGMENT, fragmentShaderSource);
    program->addShader(fragment_shader);

    osg::Uniform* xCoeff = new osg::Uniform("xCoeff",osg::Vec2(1.0,-1.0f));
    xCoeff->setUpdateCallback(new UniformVarying);
    stateset->addUniform(xCoeff);

    osg::Uniform* yCoeff = new osg::Uniform("yCoeff",osg::Vec2(-1.0f,1.0f));
    stateset->addUniform(yCoeff);

    stateset->setTextureAttributeAndModes(0,new osg::Texture2D(osgDB::readImageFile("lz.rgb")));

    osg::Uniform* baseTextureSampler = new osg::Uniform("baseTexture",0);
    stateset->addUniform(baseTextureSampler);

    return geode;

}

int main(int argc, char *argv[])
{
    // use an ArgumentParser object to manage the program arguments.
    osg::ArgumentParser arguments(&argc,argv);

    // set up the usage document, in case we need to print out how to use this program.
    arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the example which demonstrate support for ARB_vertex_program.");
    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ...");
    arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");

    // construct the viewer.
    osgProducer::Viewer viewer(arguments);

    // set up the value with sensible default event handlers.
    viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS);

    // get details on keyboard and mouse bindings used by the viewer.
    viewer.getUsage(*arguments.getApplicationUsage());

    // if user request help write it out to cout.
    if (arguments.read("-h") || arguments.read("--help"))
    {
        arguments.getApplicationUsage()->write(std::cout);
        return 1;
    }

    // any option left unread are converted into errors to write out later.
    arguments.reportRemainingOptionsAsUnrecognized();

    // report any errors if they have occured when parsing the program aguments.
    if (arguments.errors())
    {
        arguments.writeErrorMessages(std::cout);
        return 1;
    }

    // load the nodes from the commandline arguments.
    osg::Node* model = createModel();
    if (!model)
    {
        return 1;
    }

    // add a viewport to the viewer and attach the scene graph.
    viewer.setSceneData(model);

    // create the windows and run the threads.
    viewer.realize();

    while( !viewer.done() )
    {
        // wait for all cull and draw threads to complete.
        viewer.sync();

        // update the scene by traversing it with the the update visitor which will
        // call all node update callbacks and animations.
        viewer.update();

        // fire off the cull and draw traversals of the scene.
        viewer.frame();

    }

    // wait for all cull and draw threads to complete before exit.
    viewer.sync();

    return 0;
}
<commit_msg>Tweaked the vertex program.<commit_after>#include <osg/Vec3>
#include <osg/Vec4>
#include <osg/Quat>
#include <osg/Matrix>
#include <osg/ShapeDrawable>
#include <osg/Geometry>
#include <osg/Geode>
#include <osg/Texture2D>

#include <osgDB/FileUtils>
#include <osgDB/ReadFile>

#include <osgUtil/Optimizer>

#include <osgProducer/Viewer>

char vertexShaderSource[] =
    "uniform vec2  xCoeff; \n"
    "uniform vec2  yCoeff; \n"
    "//uniform sampler2D baseTexture; \n"
    "\n"
    "void main(void) \n"
    "{ \n"
    "\n"
    "    gl_TexCoord[0] = gl_Vertex; \n"
    "    gl_Vertex.z = gl_Vertex.x*xCoeff[0] + gl_Vertex.x*gl_Vertex.x* xCoeff[1] + \n"
    "                  gl_Vertex.y*yCoeff[1] + gl_Vertex.y*gl_Vertex.y* yCoeff[1]; \n"
    "    //gl_Vertex.z = texture2D( vertexTexture, gl_TexCoord[0].xy).r; \n"
    "    gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;\n"
    "}\n";

char fragmentShaderSource[] =
    "uniform sampler2D baseTexture; \n"
    "\n"
    "void main(void) \n"
    "{ \n"
    "    gl_FragColor = texture2D( baseTexture, gl_TexCoord[0].xy); \n"
    "}\n";

class UniformVarying : public osg::Uniform::Callback
{
    virtual void operator () (osg::Uniform* uniform, osg::NodeVisitor* nv)
    {
        const osg::FrameStamp* fs = nv->getFrameStamp();
        float value = sinf(fs->getReferenceTime());
        uniform->set(osg::Vec2(value,-value));
    }
};

osg::Node* createModel()
{
    osg::Geode* geode = new osg::Geode;

    osg::Geometry* geom = new osg::Geometry;
    geode->addDrawable(geom);

    // dimensions for ~one million triangles :-)
    unsigned int num_x = 708;
    unsigned int num_y = 708;

    osg::Vec3Array* vertices = new osg::Vec3Array( num_x * num_y );

    float dx = 1.0f/(float)(num_x-1);
    float dy = 1.0f/(float)(num_y-1);
    osg::Vec3 row(0.0f,0.0f,0.0);

    unsigned int vert_no = 0;
    for(unsigned int iy=0; iy<num_y; ++iy)
    {
        osg::Vec3 column = row;
        for(unsigned int ix=0;ix<num_x;++ix)
        {
            (*vertices)[vert_no++] = column;
            column.x() += dx;
        }
        row.y() += dy;
    }

    geom->setVertexArray(vertices);

    for(unsigned int iy=0; iy<num_y-1; ++iy)
    {
        unsigned int element_no = 0;
        osg::DrawElementsUInt* elements = new osg::DrawElementsUInt(GL_TRIANGLE_STRIP, num_x*2);
        unsigned int index = iy * num_x;
        for(unsigned int ix = 0; ix<num_x; ++ix)
        {
            (*elements)[element_no++] = index + num_x;
            (*elements)[element_no++] = index++;
        }
        geom->addPrimitiveSet(elements);
    }

    geom->setUseVertexBufferObjects(true);

    osg::StateSet* stateset = geom->getOrCreateStateSet();

    osg::Program* program = new osg::Program;
    stateset->setAttribute(program);

    osg::Shader* vertex_shader = new osg::Shader(osg::Shader::VERTEX, vertexShaderSource);
    program->addShader(vertex_shader);

    osg::Shader* fragment_shader = new osg::Shader(osg::Shader::FRAGMENT, fragmentShaderSource);
    program->addShader(fragment_shader);

    osg::Uniform* xCoeff = new osg::Uniform("xCoeff",osg::Vec2(1.0,-1.0f));
    xCoeff->setUpdateCallback(new UniformVarying);
    stateset->addUniform(xCoeff);

    osg::Uniform* yCoeff = new osg::Uniform("yCoeff",osg::Vec2(-1.0f,1.0f));
    stateset->addUniform(yCoeff);

    osg::Texture2D* texture = new osg::Texture2D(osgDB::readImageFile("lz.rgb"));
    texture->setFilter(osg::Texture::MIN_FILTER,osg::Texture::NEAREST);
    texture->setFilter(osg::Texture::MAG_FILTER,osg::Texture::NEAREST);
    stateset->setTextureAttributeAndModes(0,texture);

    osg::Uniform* baseTextureSampler = new osg::Uniform("baseTexture",0);
    stateset->addUniform(baseTextureSampler);

    return geode;

}

int main(int argc, char *argv[])
{
    // use an ArgumentParser object to manage the program arguments.
    osg::ArgumentParser arguments(&argc,argv);

    // set up the usage document, in case we need to print out how to use this program.
    arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the example which demonstrate support for ARB_vertex_program.");
    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ...");
    arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");

    // construct the viewer.
    osgProducer::Viewer viewer(arguments);

    // set up the value with sensible default event handlers.
    viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS);

    // get details on keyboard and mouse bindings used by the viewer.
    viewer.getUsage(*arguments.getApplicationUsage());

    // if user request help write it out to cout.
    if (arguments.read("-h") || arguments.read("--help"))
    {
        arguments.getApplicationUsage()->write(std::cout);
        return 1;
    }

    // any option left unread are converted into errors to write out later.
    arguments.reportRemainingOptionsAsUnrecognized();

    // report any errors if they have occured when parsing the program aguments.
    if (arguments.errors())
    {
        arguments.writeErrorMessages(std::cout);
        return 1;
    }

    // load the nodes from the commandline arguments.
    osg::Node* model = createModel();
    if (!model)
    {
        return 1;
    }

    // add a viewport to the viewer and attach the scene graph.
    viewer.setSceneData(model);

    // create the windows and run the threads.
    viewer.realize();

    while( !viewer.done() )
    {
        // wait for all cull and draw threads to complete.
        viewer.sync();

        // update the scene by traversing it with the the update visitor which will
        // call all node update callbacks and animations.
        viewer.update();

        // fire off the cull and draw traversals of the scene.
        viewer.frame();

    }

    // wait for all cull and draw threads to complete before exit.
    viewer.sync();

    return 0;
}
<|endoftext|>


<commit_before>// $Id: property.C,v 1.22 2000/10/19 20:03:26 oliver Exp $

#include <BALL/CONCEPT/property.h>
#include <BALL/CONCEPT/persistenceManager.h>
#include <BALL/CONCEPT/textPersistenceManager.h>

using namespace std;

namespace BALL
{

	NamedProperty::NamedProperty()
		: PersistentObject(),
			type_(NONE),
			name_("")
	{
	}

	NamedProperty::NamedProperty(const NamedProperty& property)
		: PersistentObject(property),
			type_(property.type_),
			name_(property.name_)
	{
		if (type_ != STRING)
		{
			data_ = property.data_;
		}
		else
		{
			data_.s = new string(*property.data_.s);
		}
	}

	void NamedProperty::persistentWrite(PersistenceManager& pm, const char* name) const
	{
		pm.writeObjectHeader(this, name);
			pm.writePrimitive((int)type_, "type_");
			pm.writePrimitive(String(name_), "name_");

			switch (type_)
			{
				case	INT:					pm.writePrimitive(data_.i, "data_.i");		break;
				case	FLOAT:				pm.writePrimitive(data_.f, "data_.f");		break;
				case	DOUBLE:				pm.writePrimitive(data_.d, "data_.d");		break;
				case	UNSIGNED_INT:	pm.writePrimitive(data_.ui, "data_.ui"); break;
				case	BOOL:					pm.writePrimitive(data_.b, "data_.b");		break;
				case	OBJECT:				pm.writeObjectPointer(data_.object, "data_.object"); break;
				case	NONE:					break;
				case	STRING:				pm.writePrimitive(String(*data_.s), "data_.s");	break;
				default:
					Log.error() << "cannot write unknown property type: " << (int)type_ << endl;
			}
		pm.writeObjectTrailer(name);
	}

	void NamedProperty::persistentRead(PersistenceManager& pm)
	{
		int type;
		pm.readPrimitive(type, "type_");
		type_ = (Type)type;
		String s;
		pm.readPrimitive(s, "name_");
		name_ = s;

		switch (type_)
		{
			case	INT:					pm.readPrimitive(data_.i, "data_.i");		break;
			case	FLOAT:				pm.readPrimitive(data_.f, "data_.f");		break;
			case	DOUBLE:				pm.readPrimitive(data_.d, "data_.d");		break;
			case	UNSIGNED_INT:	pm.readPrimitive(data_.ui, "data_.ui"); break;
			case	BOOL:					pm.readPrimitive(data_.b, "data_.b");		break;
			case	NONE:	break;

			case	STRING:
				// we have to create a new string
				pm.readPrimitive(s, "data_.s");
				data_.s = new string(s);
				break;

			case	OBJECT:
				// the persistence manager will take care of
				// reading the object and will set this pointer afterwards
				pm.readObjectPointer(data_.object, "data_.object");
				break;

			default:
				Log.error() << "Unknown type while reading NamedProperty: " << (int)type_ << endl;
		}
	}

	/// Output operator
	ostream& operator << (std::ostream& s, const NamedProperty& property)
  {
		s << property.type_;
		s << endl;
		s << property.name_;
		s << endl;
		switch (property.type_)
		{
			case NamedProperty::BOOL:					s << property.data_.b; break;
			case NamedProperty::INT:					s << property.data_.i; break;
			case NamedProperty::UNSIGNED_INT: s << property.data_.ui; break;
			case NamedProperty::FLOAT:				s << property.data_.f; break;
			case NamedProperty::DOUBLE:				s << property.data_.d; break;
			case NamedProperty::STRING:				s << *property.data_.s; break;
			case NamedProperty::OBJECT:
				{
					TextPersistenceManager pm;
					pm.setOstream(s);
					pm.writeObjectPointer(property.data_.object, "data_.object");
					break;
				}
			case NamedProperty::NONE : break;
			default:
				Log.error() << "Unknown type while writing NamedProperty: " << (int)property.type_ << endl;
		}
		return s;
	}

	/// Input operator
	istream& operator >> (std::istream& s, NamedProperty& property)
  {
		s >> (int)property.type_;
		s >> property.name_;
		switch (property.type_)
		{
			case NamedProperty::BOOL : 	s >> property.data_.b; break;
			case NamedProperty::INT : 	s >> property.data_.i; break;
			case NamedProperty::UNSIGNED_INT : 	s >> property.data_.ui; break;
			case NamedProperty::FLOAT : s >> property.data_.f; break;
			case NamedProperty::DOUBLE :s >> property.data_.d; break;
			case NamedProperty::OBJECT :
			{
				TextPersistenceManager pm;
				pm.setIstream(s);
				pm.readObjectPointer(property.data_.object, "data_.object");
				break;
			}
			case NamedProperty::NONE : break;
			case NamedProperty::STRING :
			{
				string str;
				s >> str;
				property.data_.s = new string(str);
				break;
			}
			default:
				Log.error() << "Unknown type while reading NamedProperty: " << (int)property.type_ << endl;
		}
		return s;
	}

  ostream& operator << (ostream& s, const PropertyManager& property_manager)
  {
    s << property_manager.bitvector_;

		s << endl;
		s << property_manager.named_properties_.size();
		s << endl;
		vector<NamedProperty>::const_iterator it = property_manager.named_properties_.begin();
		for (; it != property_manager.named_properties_.end(); ++it)
		{
			s << *it << endl;
		}
		return s;
	}

  istream& operator >> (istream& s, PropertyManager& property_manager)
  {
		int size;
    s >> property_manager.bitvector_;
		s >> size;
		NamedProperty np;
		for (int i = 0; i < size; i++)
		{
			s >> np;
			property_manager.setProperty(np);
		}

		return s;
	}

  void PropertyManager::write(PersistenceManager& pm) const
  {
		pm.writeStorableObject(bitvector_, "bitvector_");
		Size size = named_properties_.size();
		pm.writePrimitive(size, "size");
		for (Size i = 0; i < size; i++)
		{
			named_properties_[i].persistentWrite(pm, "");
		}
	}

  bool PropertyManager::read(PersistenceManager& pm)
  {
		if (!pm.readStorableObject(bitvector_, "bitvector_"))
		{
			return false;
		}

		NamedProperty property("");
		named_properties_.clear();
		Size size = 0;
		pm.readPrimitive(size, "size");
		for (Size i = 0; i < size; i++)
		{
			pm.checkObjectHeader(property, "");
				property.persistentRead(pm);
			pm.checkObjectTrailer("");
			named_properties_.push_back(property);
		}

		return true;
	}

	void PropertyManager::set(const PropertyManager& property_manager, bool /* deep */)
	{
		bitvector_ = property_manager.bitvector_;
		named_properties_ = property_manager.named_properties_;
	}

	void PropertyManager::setProperty(const NamedProperty& property)
	{
		// search whether the property already exists
		vector<NamedProperty>::iterator it = named_properties_.begin();
		for (; it != named_properties_.end(); ++it)
		{
			if (it->getName() == property.getName())
			{
				// yes, it exists. Erase the old content
				named_properties_.erase(it);
				break;
			}
		}

		// add the new content
		named_properties_.push_back(property);
	}

	void PropertyManager::setProperty(const string& name)
	{
		// search whether a property with the same name already exists
		vector<NamedProperty>::iterator it = named_properties_.begin();
		for (; it != named_properties_.end(); ++it)
		{
			if (it->getName() == name)
			{
				// yes, it exists. Erase the old content
				named_properties_.erase(it);
				break;
			}
		}

		// add the new content
		named_properties_.push_back(NamedProperty(name));
	}

	const NamedProperty& PropertyManager::getProperty(const string& name) const
	{
		for (Size i = 0; i < named_properties_.size(); ++i)
		{
			if (named_properties_[i].getName() == name)
			{
				return named_properties_[i];
			}
		}

		return RTTI::getDefault<NamedProperty>();
	}

	void PropertyManager::clearProperty(const string& name)
	{
    vector<NamedProperty>::iterator it = named_properties_.begin();
		for (; it != named_properties_.end(); ++it)
 		{
			if (it->getName() == name)
			{
				named_properties_.erase(it);
				break;
			}
		}
	}

	bool PropertyManager::hasProperty(const string& name) const
	{
		for (Size i = 0; i < named_properties_.size(); i++)
		{
			if (named_properties_[i].getName() == name)
			{
				return true;
			}
		}

		return false;
	}

	void PropertyManager::dump(ostream& s, Size depth) const
	{
		BALL_DUMP_STREAM_PREFIX(s);

		BALL_DUMP_DEPTH(s, depth);
		BALL_DUMP_CLASS_HEADER(s, PropertyManager, this);

		BALL_DUMP_DEPTH(s, depth);
		s << bitvector_ << endl;

		for (Size i = 0; i < named_properties_.size(); ++i)
		{
			BALL_DUMP_DEPTH(s, depth);
			s << "(" << named_properties_[i].getName();
			switch (named_properties_[i].getType())
			{
				case NamedProperty::NONE:
					s << "NONE: ";
					break;
				case NamedProperty::BOOL:
					s << "BOOL: " << named_properties_[i].getBool();
					break;
				case NamedProperty::INT:
					s << "INT: " << named_properties_[i].getInt();
					break;
				case NamedProperty::UNSIGNED_INT:
					s << "UNSIGNED_INT: " << named_properties_[i].getUnsignedInt();
					break;
				case NamedProperty::FLOAT:
					s << "FLOAT: " << named_properties_[i].getFloat();
					break;
				case NamedProperty::DOUBLE:
					s << "DOUBLE: " << named_properties_[i].getDouble();
					break;
				case NamedProperty::STRING:
					s << "STRING: " << (char)34 << named_properties_[i].getString().c_str() << (char)34;
					break;
				case NamedProperty::OBJECT:
					s << "OBJECT: " << named_properties_[i].getObject();
			}

			s << ")" << endl;
		}

		BALL_DUMP_STREAM_SUFFIX(s);
	}

#	ifdef BALL_NO_INLINE_FUNCTIONS
#		include <BALL/CONCEPT/property.iC>
#	endif

} // namespace BALL
<commit_msg>fixed: could not read type due to illegal cast (cast to temporary!)<commit_after>// $Id: property.C,v 1.23 2000/10/25 19:26:15 oliver Exp $

#include <BALL/CONCEPT/property.h>
#include <BALL/CONCEPT/persistenceManager.h>
#include <BALL/CONCEPT/textPersistenceManager.h>

using namespace std;

namespace BALL
{

	NamedProperty::NamedProperty()
		: PersistentObject(),
			type_(NONE),
			name_("")
	{
	}

	NamedProperty::NamedProperty(const NamedProperty& property)
		: PersistentObject(property),
			type_(property.type_),
			name_(property.name_)
	{
		if (type_ != STRING)
		{
			data_ = property.data_;
		}
		else
		{
			data_.s = new string(*property.data_.s);
		}
	}

	void NamedProperty::persistentWrite(PersistenceManager& pm, const char* name) const
	{
		pm.writeObjectHeader(this, name);
			pm.writePrimitive((int)type_, "type_");
			pm.writePrimitive(String(name_), "name_");

			switch (type_)
			{
				case	INT:					pm.writePrimitive(data_.i, "data_.i");		break;
				case	FLOAT:				pm.writePrimitive(data_.f, "data_.f");		break;
				case	DOUBLE:				pm.writePrimitive(data_.d, "data_.d");		break;
				case	UNSIGNED_INT:	pm.writePrimitive(data_.ui, "data_.ui"); break;
				case	BOOL:					pm.writePrimitive(data_.b, "data_.b");		break;
				case	OBJECT:				pm.writeObjectPointer(data_.object, "data_.object"); break;
				case	NONE:					break;
				case	STRING:				pm.writePrimitive(String(*data_.s), "data_.s");	break;
				default:
					Log.error() << "cannot write unknown property type: " << (int)type_ << endl;
			}
		pm.writeObjectTrailer(name);
	}

	void NamedProperty::persistentRead(PersistenceManager& pm)
	{
		int type;
		pm.readPrimitive(type, "type_");
		type_ = (Type)type;
		String s;
		pm.readPrimitive(s, "name_");
		name_ = s;

		switch (type_)
		{
			case	INT:					pm.readPrimitive(data_.i, "data_.i");		break;
			case	FLOAT:				pm.readPrimitive(data_.f, "data_.f");		break;
			case	DOUBLE:				pm.readPrimitive(data_.d, "data_.d");		break;
			case	UNSIGNED_INT:	pm.readPrimitive(data_.ui, "data_.ui"); break;
			case	BOOL:					pm.readPrimitive(data_.b, "data_.b");		break;
			case	NONE:	break;

			case	STRING:
				// we have to create a new string
				pm.readPrimitive(s, "data_.s");
				data_.s = new string(s);
				break;

			case	OBJECT:
				// the persistence manager will take care of
				// reading the object and will set this pointer afterwards
				pm.readObjectPointer(data_.object, "data_.object");
				break;

			default:
				Log.error() << "Unknown type while reading NamedProperty: " << (int)type_ << endl;
		}
	}

	/// Output operator
	ostream& operator << (std::ostream& s, const NamedProperty& property)
  {
		s << property.type_;
		s << endl;
		s << property.name_;
		s << endl;
		switch (property.type_)
		{
			case NamedProperty::BOOL:					s << property.data_.b; break;
			case NamedProperty::INT:					s << property.data_.i; break;
			case NamedProperty::UNSIGNED_INT: s << property.data_.ui; break;
			case NamedProperty::FLOAT:				s << property.data_.f; break;
			case NamedProperty::DOUBLE:				s << property.data_.d; break;
			case NamedProperty::STRING:				s << *property.data_.s; break;
			case NamedProperty::OBJECT:
				{
					TextPersistenceManager pm;
					pm.setOstream(s);
					pm.writeObjectPointer(property.data_.object, "data_.object");
					break;
				}
			case NamedProperty::NONE : break;
			default:
				Log.error() << "Unknown type while writing NamedProperty: " << (int)property.type_ << endl;
		}
		return s;
	}

	/// Input operator
	istream& operator >> (std::istream& s, NamedProperty& property)
  {
		Index tmp;
		s >> tmp;
		property.type_ = (NamedProperty::Type)tmp;
		s >> property.name_;
		switch (property.type_)
		{
			case NamedProperty::BOOL : 	s >> property.data_.b; break;
			case NamedProperty::INT : 	s >> property.data_.i; break;
			case NamedProperty::UNSIGNED_INT : 	s >> property.data_.ui; break;
			case NamedProperty::FLOAT : s >> property.data_.f; break;
			case NamedProperty::DOUBLE :s >> property.data_.d; break;
			case NamedProperty::OBJECT :
			{
				TextPersistenceManager pm;
				pm.setIstream(s);
				pm.readObjectPointer(property.data_.object, "data_.object");
				break;
			}
			case NamedProperty::NONE : break;
			case NamedProperty::STRING :
			{
				string str;
				s >> str;
				property.data_.s = new string(str);
				break;
			}
			default:
				Log.error() << "Unknown type while reading NamedProperty: " << (int)property.type_ << endl;
		}
		return s;
	}

  ostream& operator << (ostream& s, const PropertyManager& property_manager)
  {
    s << property_manager.bitvector_;

		s << endl;
		s << property_manager.named_properties_.size();
		s << endl;
		vector<NamedProperty>::const_iterator it = property_manager.named_properties_.begin();
		for (; it != property_manager.named_properties_.end(); ++it)
		{
			s << *it << endl;
		}
		return s;
	}

  istream& operator >> (istream& s, PropertyManager& property_manager)
  {
		int size;
    s >> property_manager.bitvector_;
		s >> size;
		NamedProperty np;
		for (int i = 0; i < size; i++)
		{
			s >> np;
			property_manager.setProperty(np);
		}

		return s;
	}

  void PropertyManager::write(PersistenceManager& pm) const
  {
		pm.writeStorableObject(bitvector_, "bitvector_");
		Size size = named_properties_.size();
		pm.writePrimitive(size, "size");
		for (Size i = 0; i < size; i++)
		{
			named_properties_[i].persistentWrite(pm, "");
		}
	}

  bool PropertyManager::read(PersistenceManager& pm)
  {
		if (!pm.readStorableObject(bitvector_, "bitvector_"))
		{
			return false;
		}

		NamedProperty property("");
		named_properties_.clear();
		Size size = 0;
		pm.readPrimitive(size, "size");
		for (Size i = 0; i < size; i++)
		{
			pm.checkObjectHeader(property, "");
				property.persistentRead(pm);
			pm.checkObjectTrailer("");
			named_properties_.push_back(property);
		}

		return true;
	}

	void PropertyManager::set(const PropertyManager& property_manager, bool /* deep */)
	{
		bitvector_ = property_manager.bitvector_;
		named_properties_ = property_manager.named_properties_;
	}

	void PropertyManager::setProperty(const NamedProperty& property)
	{
		// search whether the property already exists
		vector<NamedProperty>::iterator it = named_properties_.begin();
		for (; it != named_properties_.end(); ++it)
		{
			if (it->getName() == property.getName())
			{
				// yes, it exists. Erase the old content
				named_properties_.erase(it);
				break;
			}
		}

		// add the new content
		named_properties_.push_back(property);
	}

	void PropertyManager::setProperty(const string& name)
	{
		// search whether a property with the same name already exists
		vector<NamedProperty>::iterator it = named_properties_.begin();
		for (; it != named_properties_.end(); ++it)
		{
			if (it->getName() == name)
			{
				// yes, it exists. Erase the old content
				named_properties_.erase(it);
				break;
			}
		}

		// add the new content
		named_properties_.push_back(NamedProperty(name));
	}

	const NamedProperty& PropertyManager::getProperty(const string& name) const
	{
		for (Size i = 0; i < named_properties_.size(); ++i)
		{
			if (named_properties_[i].getName() == name)
			{
				return named_properties_[i];
			}
		}

		return RTTI::getDefault<NamedProperty>();
	}

	void PropertyManager::clearProperty(const string& name)
	{
    vector<NamedProperty>::iterator it = named_properties_.begin();
		for (; it != named_properties_.end(); ++it)
 		{
			if (it->getName() == name)
			{
				named_properties_.erase(it);
				break;
			}
		}
	}

	bool PropertyManager::hasProperty(const string& name) const
	{
		for (Size i = 0; i < named_properties_.size(); i++)
		{
			if (named_properties_[i].getName() == name)
			{
				return true;
			}
		}

		return false;
	}

	void PropertyManager::dump(ostream& s, Size depth) const
	{
		BALL_DUMP_STREAM_PREFIX(s);

		BALL_DUMP_DEPTH(s, depth);
		BALL_DUMP_CLASS_HEADER(s, PropertyManager, this);

		BALL_DUMP_DEPTH(s, depth);
		s << bitvector_ << endl;

		for (Size i = 0; i < named_properties_.size(); ++i)
		{
			BALL_DUMP_DEPTH(s, depth);
			s << "(" << named_properties_[i].getName();
			switch (named_properties_[i].getType())
			{
				case NamedProperty::NONE:
					s << "NONE: ";
					break;
				case NamedProperty::BOOL:
					s << "BOOL: " << named_properties_[i].getBool();
					break;
				case NamedProperty::INT:
					s << "INT: " << named_properties_[i].getInt();
					break;
				case NamedProperty::UNSIGNED_INT:
					s << "UNSIGNED_INT: " << named_properties_[i].getUnsignedInt();
					break;
				case NamedProperty::FLOAT:
					s << "FLOAT: " << named_properties_[i].getFloat();
					break;
				case NamedProperty::DOUBLE:
					s << "DOUBLE: " << named_properties_[i].getDouble();
					break;
				case NamedProperty::STRING:
					s << "STRING: " << (char)34 << named_properties_[i].getString().c_str() << (char)34;
					break;
				case NamedProperty::OBJECT:
					s << "OBJECT: " << named_properties_[i].getObject();
			}

			s << ")" << endl;
		}

		BALL_DUMP_STREAM_SUFFIX(s);
	}

#	ifdef BALL_NO_INLINE_FUNCTIONS
#		include <BALL/CONCEPT/property.iC>
#	endif

} // namespace BALL
<|endoftext|>


<commit_before>#include "GameState.hpp"
#include "Planet.hpp"
#include "Ship.hpp"
#include "../Application.hpp"

#include <SFML/Window/Event.hpp>
#include <SFML/Graphics/RenderTarget.hpp>

#include <unordered_map>
#include <functional>
#include <string>

GameState::GameState() : mMouseDrag(false), mLoadState("Creating the universe")
{

}
GameState::~GameState()
{

}

bool GameState::load()
{
    static std::unordered_map<std::string, std::function<void()> > loadStates;
    if (loadStates.empty())
    {
        loadStates["Creating the universe"] = [&]() {
            static int stage = 0;
            switch (stage++)
            {
            case 0:
                mWorld.init();
                mWorld.setSize(sf::Vector2f(1600, 1000));
                break;

            case 1:
                break;

            default:
                mLoadState = "Placing planets";
            }
        };
        loadStates["Placing planets"] = [&]() {
            static int totalPlanets = 0;

            if (totalPlanets++ > 9)
                mLoadState = "Adding retards";
            else
            {
                Game::Planet p;

                mWorld.addPlanet(p);
            }
        };
        loadStates["Adding retards"] = [&]() {
            static int totalRetards = 0;

            if (totalRetards++ > 0)
                mLoadState = "Giving them guns";
            else
            {
                Game::Ship s;

                mWorld.addShip(s);
            }
        };
        loadStates["Giving them guns"] = [&]() {
            static int scripts = 0;

            if (scripts++ > 0)
                mLoadState = "Finalizing";
            else
            {
                ///\TODO Load weapons from scripts.
            }
        };
        loadStates["Finalizing"] = [&]() {
            static int finalizeWait = 0;

            if (finalizeWait++ > 0)
                mLoadState = "Reticulating splines";
        };
        loadStates["Reticulating splines"] = [&]() {
            static int noWait = 0;

            if (noWait++ > 0)
                mLoadState = "Done";
        };
    }

    if (loadStates.count(mLoadState) == 0)
        return true;

    loadStates[mLoadState]();
    return false;
}
void GameState::unload()
{

}

bool GameState::event(const sf::Event& ev)
{
    if (ev.type == sf::Event::MouseButtonPressed && ev.mouseButton.button == sf::Mouse::Left)
    {
        mMouseDrag = true;
        mLastMouse = getApplication().getMouse();
    }
    else if (ev.type == sf::Event::MouseButtonReleased && ev.mouseButton.button == sf::Mouse::Left)
        mMouseDrag = false;
    else if (ev.type == sf::Event::MouseWheelMoved)
    {
        static float zoomFactor = 5.f;
        int delta = -ev.mouseWheel.delta;

        sf::Vector2f curMouse = getApplication().getMouse();
        sf::View& gameView = getApplication().getGameView();

        sf::Vector2f diff = gameView.getCenter() - curMouse;
        if (delta < 0)
            diff = -diff;

        gameView.move(diff/zoomFactor);

        gameView.zoom(1 + delta / zoomFactor);
    }

    return false;
}
void GameState::update(float dt)
{
    if (mMouseDrag)
    {
        sf::Vector2f curMouse = getApplication().getMouse();

        sf::Vector2f diff = mLastMouse - curMouse;
        curMouse += diff;

        getApplication().getGameView().move(diff);
        mLastMouse = curMouse;
    }

    mWorld.update(dt);
}
void GameState::draw(sf::RenderTarget& target)
{
    mWorld.draw(target);
}
void GameState::drawUi(sf::RenderTarget& target)
{
    mWorld.drawUi(target);
}<commit_msg>Add 10 players instead of one<commit_after>#include "GameState.hpp"
#include "Planet.hpp"
#include "Ship.hpp"
#include "../Application.hpp"

#include <SFML/Window/Event.hpp>
#include <SFML/Graphics/RenderTarget.hpp>

#include <unordered_map>
#include <functional>
#include <string>

GameState::GameState() : mMouseDrag(false), mLoadState("Creating the universe")
{

}
GameState::~GameState()
{

}

bool GameState::load()
{
    static std::unordered_map<std::string, std::function<void()> > loadStates;
    if (loadStates.empty())
    {
        loadStates["Creating the universe"] = [&]() {
            static int stage = 0;
            switch (stage++)
            {
            case 0:
                mWorld.init();
                mWorld.setSize(sf::Vector2f(1600, 1000));
                break;

            case 1:
                break;

            default:
                mLoadState = "Placing planets";
            }
        };
        loadStates["Placing planets"] = [&]() {
            static int totalPlanets = 0;

            if (totalPlanets++ > 9)
                mLoadState = "Adding retards";
            else
            {
                Game::Planet p;

                mWorld.addPlanet(p);
            }
        };
        loadStates["Adding retards"] = [&]() {
            static int totalRetards = 0;

            if (totalRetards++ > 9)
                mLoadState = "Giving them guns";
            else
            {
                Game::Ship s;

                mWorld.addShip(s);
            }
        };
        loadStates["Giving them guns"] = [&]() {
            static int scripts = 0;

            if (scripts++ > 0)
                mLoadState = "Finalizing";
            else
            {
                ///\TODO Load weapons from scripts.
            }
        };
        loadStates["Finalizing"] = [&]() {
            static int finalizeWait = 0;

            if (finalizeWait++ > 0)
                mLoadState = "Reticulating splines";
        };
        loadStates["Reticulating splines"] = [&]() {
            static int noWait = 0;

            if (noWait++ > 0)
                mLoadState = "Done";
        };
    }

    if (loadStates.count(mLoadState) == 0)
        return true;

    loadStates[mLoadState]();
    return false;
}
void GameState::unload()
{

}

bool GameState::event(const sf::Event& ev)
{
    if (ev.type == sf::Event::MouseButtonPressed && ev.mouseButton.button == sf::Mouse::Left)
    {
        mMouseDrag = true;
        mLastMouse = getApplication().getMouse();
    }
    else if (ev.type == sf::Event::MouseButtonReleased && ev.mouseButton.button == sf::Mouse::Left)
        mMouseDrag = false;
    else if (ev.type == sf::Event::MouseWheelMoved)
    {
        static float zoomFactor = 5.f;
        int delta = -ev.mouseWheel.delta;

        sf::Vector2f curMouse = getApplication().getMouse();
        sf::View& gameView = getApplication().getGameView();

        sf::Vector2f diff = gameView.getCenter() - curMouse;
        if (delta < 0)
            diff = -diff;

        gameView.move(diff/zoomFactor);

        gameView.zoom(1 + delta / zoomFactor);
    }

    return false;
}
void GameState::update(float dt)
{
    if (mMouseDrag)
    {
        sf::Vector2f curMouse = getApplication().getMouse();

        sf::Vector2f diff = mLastMouse - curMouse;
        curMouse += diff;

        getApplication().getGameView().move(diff);
        mLastMouse = curMouse;
    }

    mWorld.update(dt);
}
void GameState::draw(sf::RenderTarget& target)
{
    mWorld.draw(target);
}
void GameState::drawUi(sf::RenderTarget& target)
{
    mWorld.drawUi(target);
}<|endoftext|>


<commit_before>// Copyright (c) 2017 Emilian Cioca
#pragma message("Precompiled Headers Started...")

#include "Jewel3D/Precompiled.h"

#pragma message("Precompiled Headers Completed.")
<commit_msg>Removed pragma messages from the Precompiled Header<commit_after>// Copyright (c) 2017 Emilian Cioca
#include "Jewel3D/Precompiled.h"
<|endoftext|>


<commit_before>#include "gaussian.h"

#include "Halide.h"
#include "halide_image_io.h"
#include "tiramisu/utils.h"
#include <cstdlib>
#include <iostream>

double median(std::vector<std::chrono::duration<double, std::milli>> scores)
{
    double median;
    size_t size = scores.size();

    std::sort(scores.begin(), scores.end());

    if (size % 2 == 0)
    {
        median = (scores[size / 2 - 1].count() + scores[size / 2].count()) / 2;
    }
    else
    {
        median = scores[size / 2].count();
    }

    return median;
}

int main(int, char**)
{
    std::vector<std::chrono::duration<double,std::milli>> duration_vector_1;
    std::vector<std::chrono::duration<double,std::milli>> duration_vector_2;

    Halide::Buffer<uint8_t> input = Halide::Tools::load_image("../rgb.png");
    Halide::Buffer<int32_t> SIZES_b(5);
    SIZES_b(0) = input.extent(0);
    SIZES_b(1) = input.extent(1);
    SIZES_b(2) = input.extent(2);

    Halide::Buffer<float> kernelX(5);
    Halide::Buffer<float> kernelY(5);

    SIZES_b(3) = kernelX.extent(0);
    SIZES_b(4) = kernelY.extent(0);

    kernelX(0) = 1.0f; kernelX(1) = 4.0f; kernelX(2) = 6.0f; kernelX(3) = 4.0f; kernelX(4) = 1.0f;
    kernelY(0) = 1.0f/256; kernelY(1) = 4.0f/256; kernelY(2) = 6.0f/256; kernelY(3) = 4.0f/256; kernelY(4) = 1.0f/256;

    Halide::Buffer<uint8_t> output1(input.width()-8, input.height()-8, input.channels());
    Halide::Buffer<uint8_t> temp(input.width(), input.height(), input.channels());
    Halide::Buffer<uint8_t> output2(input.width()-8, input.height()-8, input.channels());

    std::cout << "Dimensions : " << std::endl;
    std::cout << "input.extent(0): " << input.extent(0) << std::endl; // Rows
    std::cout << "input.extent(1): " << input.extent(1) << std::endl; // Cols
    std::cout << "input.extent(2): " << input.extent(2) << std::endl; // Colors

    //Warm up
    pencil_gaussian(input.extent(0), input.extent(1), 1, (uint8_t *) input.raw_buffer()->host,
		    kernelX.extent(0), (float *) kernelX.raw_buffer()->host,
		    kernelY.extent(0), (float *) kernelY.raw_buffer()->host,
		    (uint8_t *) output1.raw_buffer()->host,
		    (uint8_t *) temp.raw_buffer()->host);

    // Tiramisu
    for (int i=0; i<1; i++)
    {
        auto start1 = std::chrono::high_resolution_clock::now();
        pencil_gaussian(input.extent(0), input.extent(1), 1, (uint8_t *) input.raw_buffer()->host,
   		        kernelX.extent(0), (float *) kernelX.raw_buffer()->host,
		        kernelY.extent(0), (float *) kernelY.raw_buffer()->host,
		        (uint8_t *) output1.raw_buffer()->host,
			(uint8_t *) temp.raw_buffer()->host);

        auto end1 = std::chrono::high_resolution_clock::now();
        std::chrono::duration<double,std::milli> duration1 = end1 - start1;
        duration_vector_1.push_back(duration1);
    }

    std::cout << "time: " << median(duration_vector_1) << std::endl;

    return 0;
}
<commit_msg>update gaussian wrapper<commit_after>#include "gaussian.h"

#include "Halide.h"
#include "halide_image_io.h"
#include "tiramisu/utils.h"
#include <cstdlib>
#include <iostream>

double median(std::vector<std::chrono::duration<double, std::milli>> scores)
{
    double median;
    size_t size = scores.size();

    std::sort(scores.begin(), scores.end());

    if (size % 2 == 0)
    {
        median = (scores[size / 2 - 1].count() + scores[size / 2].count()) / 2;
    }
    else
    {
        median = scores[size / 2].count();
    }

    return median;
}

int main(int, char**)
{
    std::vector<std::chrono::duration<double,std::milli>> duration_vector_1;
    std::vector<std::chrono::duration<double,std::milli>> duration_vector_2;

    Halide::Buffer<uint8_t> input = Halide::Tools::load_image("../rgb.png");
    Halide::Buffer<int32_t> SIZES_b(5);
    SIZES_b(0) = input.extent(0);
    SIZES_b(1) = input.extent(1);
    SIZES_b(2) = input.extent(2);

    Halide::Buffer<float> kernelX(5);
    Halide::Buffer<float> kernelY(5);

    SIZES_b(3) = kernelX.extent(0);
    SIZES_b(4) = kernelY.extent(0);

    kernelX(0) = 1.0f; kernelX(1) = 4.0f; kernelX(2) = 6.0f; kernelX(3) = 4.0f; kernelX(4) = 1.0f;
    kernelY(0) = 1.0f/256; kernelY(1) = 4.0f/256; kernelY(2) = 6.0f/256; kernelY(3) = 4.0f/256; kernelY(4) = 1.0f/256;

    Halide::Buffer<uint8_t> output1(input.width()-8, input.height()-8, input.channels());
    Halide::Buffer<uint8_t> temp(input.width(), input.height(), input.channels());
    Halide::Buffer<uint8_t> output2(input.width()-8, input.height()-8, input.channels());

    std::cout << "Dimensions : " << std::endl;
    std::cout << "input.extent(0): " << input.extent(0) << std::endl; // Rows
    std::cout << "input.extent(1): " << input.extent(1) << std::endl; // Cols
    std::cout << "input.extent(2): " << input.extent(2) << std::endl; // Colors

    //Warm up
    pencil_gaussian(input.extent(0), input.extent(1), 1, (uint8_t *) input.raw_buffer()->host,
		    kernelX.extent(0), (float *) kernelX.raw_buffer()->host,
		    kernelY.extent(0), (float *) kernelY.raw_buffer()->host,
		    (uint8_t *) output1.raw_buffer()->host,
		    (uint8_t *) temp.raw_buffer()->host);

    // Tiramisu
    for (int i=0; i<10; i++)
    {
        auto start1 = std::chrono::high_resolution_clock::now();
        pencil_gaussian(input.extent(0), input.extent(1), 1, (uint8_t *) input.raw_buffer()->host,
   		        kernelX.extent(0), (float *) kernelX.raw_buffer()->host,
		        kernelY.extent(0), (float *) kernelY.raw_buffer()->host,
		        (uint8_t *) output1.raw_buffer()->host,
			(uint8_t *) temp.raw_buffer()->host);

        auto end1 = std::chrono::high_resolution_clock::now();
        std::chrono::duration<double,std::milli> duration1 = end1 - start1;
        duration_vector_1.push_back(duration1);
    }

    std::cout << "time: " << median(duration_vector_1) << std::endl;

    return 0;
}
<|endoftext|>


<commit_before>// Copyright (c) 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "net/third_party/quiche/src/common/test_tools/quiche_test_utils.h"

#include "net/third_party/quiche/src/common/platform/api/quiche_logging.h"
#include "net/third_party/quiche/src/common/platform/api/quiche_test.h"

#include <string>

namespace {

std::string HexDumpWithMarks(const char* data,
                             int length,
                             const bool* marks,
                             int mark_length) {
  static const char kHexChars[] = "0123456789abcdef";
  static const int kColumns = 4;

  const int kSizeLimit = 1024;
  if (length > kSizeLimit || mark_length > kSizeLimit) {
    QUICHE_LOG(ERROR) << "Only dumping first " << kSizeLimit << " bytes.";
    length = std::min(length, kSizeLimit);
    mark_length = std::min(mark_length, kSizeLimit);
  }

  std::string hex;
  for (const char* row = data; length > 0;
       row += kColumns, length -= kColumns) {
    for (const char* p = row; p < row + 4; ++p) {
      if (p < row + length) {
        const bool mark =
            (marks && (p - data) < mark_length && marks[p - data]);
        hex += mark ? '*' : ' ';
        hex += kHexChars[(*p & 0xf0) >> 4];
        hex += kHexChars[*p & 0x0f];
        hex += mark ? '*' : ' ';
      } else {
        hex += "    ";
      }
    }
    hex = hex + "  ";

    for (const char* p = row; p < row + 4 && p < row + length; ++p) {
      hex += (*p >= 0x20 && *p <= 0x7f) ? (*p) : '.';
    }

    hex = hex + '\n';
  }
  return hex;
}

}  // namespace

namespace quiche {
namespace test {

void CompareCharArraysWithHexError(const std::string& description,
                                   const char* actual,
                                   const int actual_len,
                                   const char* expected,
                                   const int expected_len) {
  EXPECT_EQ(actual_len, expected_len);
  const int min_len = std::min(actual_len, expected_len);
  const int max_len = std::max(actual_len, expected_len);
  std::unique_ptr<bool[]> marks(new bool[max_len]);
  bool identical = (actual_len == expected_len);
  for (int i = 0; i < min_len; ++i) {
    if (actual[i] != expected[i]) {
      marks[i] = true;
      identical = false;
    } else {
      marks[i] = false;
    }
  }
  for (int i = min_len; i < max_len; ++i) {
    marks[i] = true;
  }
  if (identical)
    return;
  ADD_FAILURE() << "Description:\n"
                << description << "\n\nExpected:\n"
                << HexDumpWithMarks(expected, expected_len, marks.get(),
                                    max_len)
                << "\nActual:\n"
                << HexDumpWithMarks(actual, actual_len, marks.get(), max_len);
}

}  // namespace test
}  // namespace quiche
<commit_msg>gfe-relnote: n/a(test only) fix a GCC complier error in QUIC test utils. Not protected.<commit_after>// Copyright (c) 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "net/third_party/quiche/src/common/test_tools/quiche_test_utils.h"

#include "net/third_party/quiche/src/common/platform/api/quiche_logging.h"
#include "net/third_party/quiche/src/common/platform/api/quiche_test.h"

#include <string>

namespace {

std::string HexDumpWithMarks(const char* data,
                             int length,
                             const bool* marks,
                             int mark_length) {
  static const char kHexChars[] = "0123456789abcdef";
  static const int kColumns = 4;

  const int kSizeLimit = 1024;
  if (length > kSizeLimit || mark_length > kSizeLimit) {
    QUICHE_LOG(ERROR) << "Only dumping first " << kSizeLimit << " bytes.";
    length = std::min(length, kSizeLimit);
    mark_length = std::min(mark_length, kSizeLimit);
  }

  std::string hex;
  for (const char* row = data; length > 0;
       row += kColumns, length -= kColumns) {
    for (const char* p = row; p < row + 4; ++p) {
      if (p < row + length) {
        const bool mark =
            (marks && (p - data) < mark_length && marks[p - data]);
        hex += mark ? '*' : ' ';
        hex += kHexChars[(*p & 0xf0) >> 4];
        hex += kHexChars[*p & 0x0f];
        hex += mark ? '*' : ' ';
      } else {
        hex += "    ";
      }
    }
    hex = hex + "  ";

    for (const char* p = row; p < row + 4 && p < row + length; ++p) {
      hex += (*p >= 0x20 && *p < 0x7f) ? (*p) : '.';
    }

    hex = hex + '\n';
  }
  return hex;
}

}  // namespace

namespace quiche {
namespace test {

void CompareCharArraysWithHexError(const std::string& description,
                                   const char* actual,
                                   const int actual_len,
                                   const char* expected,
                                   const int expected_len) {
  EXPECT_EQ(actual_len, expected_len);
  const int min_len = std::min(actual_len, expected_len);
  const int max_len = std::max(actual_len, expected_len);
  std::unique_ptr<bool[]> marks(new bool[max_len]);
  bool identical = (actual_len == expected_len);
  for (int i = 0; i < min_len; ++i) {
    if (actual[i] != expected[i]) {
      marks[i] = true;
      identical = false;
    } else {
      marks[i] = false;
    }
  }
  for (int i = min_len; i < max_len; ++i) {
    marks[i] = true;
  }
  if (identical)
    return;
  ADD_FAILURE() << "Description:\n"
                << description << "\n\nExpected:\n"
                << HexDumpWithMarks(expected, expected_len, marks.get(),
                                    max_len)
                << "\nActual:\n"
                << HexDumpWithMarks(actual, actual_len, marks.get(), max_len);
}

}  // namespace test
}  // namespace quiche
<|endoftext|>


<commit_before>/*******************************************************************************
 * benchmarks/prefix_doubling/prefix_doubling.cpp
 *
 * Part of Project Thrill - http://project-thrill.org
 *
 * Copyright (C) 2016 Florian Kurpicz <florian.kurpicz@tu-dortmund.de>
 *
 * All rights reserved. Published under the BSD-2 license in the LICENSE file.
 ******************************************************************************/

#include <thrill/api/allgather.hpp>
#include <thrill/api/cache.hpp>
#include <thrill/api/dia.hpp>
#include <thrill/api/distribute.hpp>
#include <thrill/api/distribute_from.hpp>
#include <thrill/api/gather.hpp>
#include <thrill/api/generate.hpp>
#include <thrill/api/groupby.hpp>
#include <thrill/api/merge.hpp>
#include <thrill/api/prefixsum.hpp>
#include <thrill/api/read_binary.hpp>
#include <thrill/api/size.hpp>
#include <thrill/api/sort.hpp>
#include <thrill/api/sum.hpp>
#include <thrill/api/window.hpp>
#include <thrill/api/write_binary.hpp>
#include <thrill/api/zip.hpp>
#include <thrill/common/cmdline_parser.hpp>
#include <thrill/common/logger.hpp>
#include <thrill/core/multiway_merge.hpp>

#include <algorithm>
#include <limits>
#include <random>
#include <stdexcept>
#include <string>
#include <tuple>
#include <utility>
#include <vector>

bool debug_print = false;
bool debug = true;

using namespace thrill; // NOLINT
using thrill::common::RingBuffer;

//! A pair (index, t=T[index]).
template <typename AlphabetType>
struct IndexOneMer {
    size_t index;
    AlphabetType t;

    friend std::ostream& operator << (std::ostream& os, const IndexOneMer& iom) {
        return os << '[' << iom.index << ',' << iom.t << ']';
    }
} THRILL_ATTRIBUTE_PACKED;

//! A pair (rank, index)
struct RankIndex {
    size_t rank;
    size_t index;

    friend std::ostream& operator << (std::ostream& os, const RankIndex& ri) {
        return os << '(' << ri.index << '|' << ri.rank << ')';
    }
} THRILL_ATTRIBUTE_PACKED;

//! A triple (rank_1, rank_2, index)
struct RankRankIndex {
    size_t rank1;
    size_t rank2;
    size_t index;

    friend std::ostream& operator << (std::ostream& os, const RankRankIndex& rri) {
        return os << "( i: " << rri.index << "| r1: " << rri.rank1 << "| r2: " << rri.rank2 << ")";
    }
} THRILL_ATTRIBUTE_PACKED;

template <typename InputDIA>
DIA<size_t> PrefixDoubling(Context& ctx, const InputDIA& input_dia, size_t input_size) {

    using Char = typename InputDIA::ValueType;
    using IndexOneMer = ::IndexOneMer<Char>;

    auto one_mers_sorted =
        input_dia
        .template FlatWindow<IndexOneMer>(
            2,
            [input_size](size_t index, const RingBuffer<Char>& rb, auto emit) {
                emit(IndexOneMer {index, rb[0]});
                if(index == input_size - 2) emit(IndexOneMer {index + 1, rb[1]});
        })
        .Sort([](const IndexOneMer& a, const IndexOneMer& b) {
            return a.t < b.t;
        }).Keep();

    if(debug_print)
        one_mers_sorted.Print("one_mers_sorted");

    DIA<size_t> sa =
        one_mers_sorted
        .Map([](const IndexOneMer& iom) {
            return iom.index;
        }).Collapse();

    if (debug_print)
        sa.Print("sa");

    DIA<size_t> rebucket =
        one_mers_sorted
        .template FlatWindow<size_t>(
            2,
            [input_size](size_t index, const RingBuffer<IndexOneMer>& rb, auto emit) {
                if (index == 0) emit(0);
                if (rb[0].t == rb[1].t) emit(0);
                else emit(index + 1);
                if (index == input_size - 2) {
                    if (rb[0].t == rb[1].t) emit(0);
                    else emit(index + 2);
                }
        })
        .PrefixSum([](const size_t a, const size_t b) {
            return a > b ? a : b;
        });

    if (debug_print)
        rebucket.Print("rebucket");

    uint8_t shifted_exp = 1;

    while(true) {

        DIA<RankIndex> isa =
            sa
            .Zip(
                rebucket,
                [](size_t sa, size_t rb) {
                    return RankIndex {sa, rb};
            })
            .Sort([](const RankIndex& a, const RankIndex& b) {
                return a.rank < b.rank;
            });

        if (debug_print)
            isa.Print("isa");
        LOG << "Computed the ISA";

        size_t shift_by = 1 << shifted_exp++;
        LOG << "Shift the ISA by " << shift_by << " positions";

        DIA<RankRankIndex> triple_sorted =
            isa
            .template FlatWindow<RankRankIndex>(
                shift_by,
                [input_size, shift_by](size_t index, const RingBuffer<RankIndex>& rb, auto emit) {
                    emit(RankRankIndex {rb[0].index, rb[shift_by - 1].index, rb[0].rank});
                    if(index == input_size - shift_by)
                        for(size_t i = 1; i < input_size - index; ++i)
                            emit(RankRankIndex {rb[i].index, 0, rb[i].rank});
                }
            )
            .Sort([](const RankRankIndex& a, const RankRankIndex& b) {
                if (a.rank1 == b.rank1) {
                    if (a.rank2 == b.rank2) return a.index < b.index;
                    else return a.rank2 < b.rank2;
                } else return a.rank1 < b.rank1;
            });
        LOG << "Sorted the triples";

        size_t non_singletons =
            triple_sorted
            .template FlatWindow<uint8_t>(
                2,
                [](size_t /*index*/, const RingBuffer<RankRankIndex>& rb, auto emit) {
                    if (rb[0].rank1 == rb[1].rank1 and rb[0].rank2 == rb[1].rank2)
                        emit(0);
                }
            ).Size();

        LOG << "Computed the number of non singletons";

        sa =
            triple_sorted
            .Map([](const RankRankIndex& rri) { return rri.index;
        }).Collapse();

        if (debug_print)
            sa.Print("sa");
        // If each suffix is unique regarding their 2h-prefix, we have computed
        // the suffix array and can return it.
        if (non_singletons == 0)
            return sa;

        rebucket =
            triple_sorted
            .template FlatWindow<size_t>(
                2,
                [input_size](size_t index, const RingBuffer<RankRankIndex>& rb, auto emit) {
                    if (index == 0) emit(0);
                    if (rb[0].rank1 == rb[1].rank1 and rb[0].rank2 == rb[1].rank2)
                        emit(0);
                    else
                        emit(index + 1);
                    if (index == input_size - 2) {
                        if (rb[0].rank1 == rb[1].rank1 and rb[0].rank2 == rb[1].rank2)
                            emit(0);
                        else
                            emit(index + 2);
                    }
            })
            .PrefixSum([](const size_t a, const size_t b) {
                return a > b ? a : b;
            });

        if (debug_print)
            rebucket.Print("rebucket");
        LOG << "Rebucket the partial SA";
    }

}

/*!
 * Class to encapsulate all
 */
class StartPrefixDoubling
{
public:
    StartPrefixDoubling(
        Context& ctx,
        const std::string& input_path, const std::string& output_path,
        bool text_output_flag,
        bool check_flag,
        bool input_verbatim)
        : ctx_(ctx),
          input_path_(input_path), output_path_(output_path),
          text_output_flag_(text_output_flag),
          check_flag_(check_flag),
          input_verbatim_(input_verbatim) { }

    void Run() {
        if (input_verbatim_) {
            // take path as verbatim text
            std::vector<uint8_t> input_vec(input_path_.begin(), input_path_.end());
            auto input_dia = Distribute<uint8_t>(ctx_, input_vec);
            if (debug_print) input_dia.Print("input");

            StartPrefixDoublingInput(input_dia, input_vec.size());
        }
        else {
            auto input_dia = ReadBinary<uint8_t>(ctx_, input_path_);
            size_t input_size = input_dia.Size();
            StartPrefixDoublingInput(input_dia, input_size);
        }
    }

    template <typename InputDIA>
    void StartPrefixDoublingInput(const InputDIA& input_dia, uint64_t input_size) {

        auto suffix_array = PrefixDoubling(ctx_, input_dia, input_size);
        if (output_path_.size()) {
            suffix_array.WriteBinary(output_path_);
        }

        if (check_flag_) {
            LOG1 << "checking suffix array...";

            //if (!CheckSA(input_dia, suffix_array)) {
            //    throw std::runtime_error("Suffix array is invalid!");
            //}
            //else {
            //    LOG1 << "okay.";
            //}
        }
    }

protected:
    Context& ctx_;

    std::string input_path_;
    std::string output_path_;

    bool text_output_flag_;
    bool check_flag_;
    bool input_verbatim_;

};

int main(int argc, char* argv[]) {
    common::CmdlineParser cp;

    cp.SetDescription("A prefix doubling suffix array construction algorithm.");
    cp.SetAuthor("Florian Kurpicz <florian.kurpicz@tu-dortmund.de>");

    std::string input_path, output_path;
    bool text_output_flag = false;
    bool check_flag = false;
    bool input_verbatim = false;

    cp.AddParamString("input", input_path,
                      "Path to input file (or verbatim text).\n"
                      "  The special inputs 'random' and 'unary' generate "
                      "such text on-the-fly.");
    cp.AddFlag('c', "check", check_flag,
               "Check suffix array for correctness.");
    cp.AddFlag('t', "text", text_output_flag,
               "Print out suffix array in readable text.");
    cp.AddString('o', "output", output_path,
                 "Output suffix array to given path.");
    cp.AddFlag('v', "verbatim", input_verbatim,
               "Consider \"input\" as verbatim text to construct "
               "suffix array on.");
    cp.AddFlag('d', "debug", debug_print,
               "Print debug info.");

    // process command line
    if (!cp.Process(argc, argv))
        return -1;

    return Run(
        [&](Context& ctx) {
            return StartPrefixDoubling(ctx,
                            input_path, output_path,
                            text_output_flag,
                            check_flag,
                            input_verbatim).Run();
        });
}
/******************************************************************************/
<commit_msg>Renamed RankIndex and RankRankIndex to match DC3 implementation<commit_after>/*******************************************************************************
 * benchmarks/prefix_doubling/prefix_doubling.cpp
 *
 * Part of Project Thrill - http://project-thrill.org
 *
 * Copyright (C) 2016 Florian Kurpicz <florian.kurpicz@tu-dortmund.de>
 *
 * All rights reserved. Published under the BSD-2 license in the LICENSE file.
 ******************************************************************************/

#include <thrill/api/allgather.hpp>
#include <thrill/api/cache.hpp>
#include <thrill/api/dia.hpp>
#include <thrill/api/distribute.hpp>
#include <thrill/api/distribute_from.hpp>
#include <thrill/api/gather.hpp>
#include <thrill/api/generate.hpp>
#include <thrill/api/groupby.hpp>
#include <thrill/api/merge.hpp>
#include <thrill/api/prefixsum.hpp>
#include <thrill/api/read_binary.hpp>
#include <thrill/api/size.hpp>
#include <thrill/api/sort.hpp>
#include <thrill/api/sum.hpp>
#include <thrill/api/window.hpp>
#include <thrill/api/write_binary.hpp>
#include <thrill/api/zip.hpp>
#include <thrill/common/cmdline_parser.hpp>
#include <thrill/common/logger.hpp>
#include <thrill/core/multiway_merge.hpp>

#include <algorithm>
#include <limits>
#include <random>
#include <stdexcept>
#include <string>
#include <tuple>
#include <utility>
#include <vector>

bool debug_print = false;
bool debug = true;

using namespace thrill; // NOLINT
using thrill::common::RingBuffer;

//! A pair (index, t=T[index]).
template <typename AlphabetType>
struct IndexOneMer {
    size_t index;
    AlphabetType t;

    friend std::ostream& operator << (std::ostream& os, const IndexOneMer& iom) {
        return os << '[' << iom.index << ',' << iom.t << ']';
    }
} THRILL_ATTRIBUTE_PACKED;

//! A pair (rank, index)
struct IndexRank {
    size_t index;
    size_t rank;

    friend std::ostream& operator << (std::ostream& os, const IndexRank& ri) {
        return os << '(' << ri.index << '|' << ri.rank << ')';
    }
} THRILL_ATTRIBUTE_PACKED;

//! A triple (rank_1, rank_2, index)
struct IndexRankRank {
    size_t index;
    size_t rank1;
    size_t rank2;

    friend std::ostream& operator << (std::ostream& os, const IndexRankRank& rri) {
        return os << "( i: " << rri.index << "| r1: " << rri.rank1 << "| r2: " << rri.rank2 << ")";
    }
} THRILL_ATTRIBUTE_PACKED;

template <typename InputDIA>
DIA<size_t> PrefixDoubling(Context& ctx, const InputDIA& input_dia, size_t input_size) {

    using Char = typename InputDIA::ValueType;
    using IndexOneMer = ::IndexOneMer<Char>;

    auto one_mers_sorted =
        input_dia
        .template FlatWindow<IndexOneMer>(
            2,
            [input_size](size_t index, const RingBuffer<Char>& rb, auto emit) {
                emit(IndexOneMer {index, rb[0]});
                if(index == input_size - 2) emit(IndexOneMer {index + 1, rb[1]});
        })
        .Sort([](const IndexOneMer& a, const IndexOneMer& b) {
            return a.t < b.t;
        }).Keep();

    if(debug_print)
        one_mers_sorted.Print("one_mers_sorted");

    DIA<size_t> sa =
        one_mers_sorted
        .Map([](const IndexOneMer& iom) {
            return iom.index;
        }).Collapse();

    if (debug_print)
        sa.Print("sa");

    DIA<size_t> rebucket =
        one_mers_sorted
        .template FlatWindow<size_t>(
            2,
            [input_size](size_t index, const RingBuffer<IndexOneMer>& rb, auto emit) {
                if (index == 0) emit(0);
                if (rb[0].t == rb[1].t) emit(0);
                else emit(index + 1);
                if (index == input_size - 2) {
                    if (rb[0].t == rb[1].t) emit(0);
                    else emit(index + 2);
                }
        })
        .PrefixSum([](const size_t a, const size_t b) {
            return a > b ? a : b;
        });

    if (debug_print)
        rebucket.Print("rebucket");

    uint8_t shifted_exp = 1;

    while(true) {

        DIA<IndexRank> isa =
            sa
            .Zip(
                rebucket,
                [](size_t sa, size_t rb) {
                    return IndexRank {rb, sa};
            })
            .Sort([](const IndexRank& a, const IndexRank& b) {
                return a.rank < b.rank;
            });

        if (debug_print)
            isa.Print("isa");
        LOG << "Computed the ISA";

        size_t shift_by = 1 << shifted_exp++;
        LOG << "Shift the ISA by " << shift_by << " positions";

        DIA<IndexRankRank> triple_sorted =
            isa
            .template FlatWindow<IndexRankRank>(
                shift_by,
                [input_size, shift_by](size_t index, const RingBuffer<IndexRank>& rb, auto emit) {
                    emit(IndexRankRank {rb[0].rank, rb[shift_by - 1].index, rb[0].index});
                    if(index == input_size - shift_by)
                        for(size_t i = 1; i < input_size - index; ++i)
                            emit(IndexRankRank {rb[i].rank, 0, rb[i].index});
                }
            )
            .Sort([](const IndexRankRank& a, const IndexRankRank& b) {
                if (a.rank1 == b.rank1) {
                    if (a.rank2 == b.rank2) return a.index < b.index;
                    else return a.rank2 < b.rank2;
                } else return a.rank1 < b.rank1;
            });
        LOG << "Sorted the triples";

        size_t non_singletons =
            triple_sorted
            .template FlatWindow<uint8_t>(
                2,
                [](size_t /*index*/, const RingBuffer<IndexRankRank>& rb, auto emit) {
                    if (rb[0].rank1 == rb[1].rank1 and rb[0].rank2 == rb[1].rank2)
                        emit(0);
                }
            ).Size();

        LOG << "Computed the number of non singletons";

        sa =
            triple_sorted
            .Map([](const IndexRankRank& rri) {
                return rri.index;
        }).Collapse();

        if (debug_print)
            sa.Print("sa");
        // If each suffix is unique regarding their 2h-prefix, we have computed
        // the suffix array and can return it.
        if (non_singletons == 0)
            return sa;

        rebucket =
            triple_sorted
            .template FlatWindow<size_t>(
                2,
                [input_size](size_t index, const RingBuffer<IndexRankRank>& rb, auto emit) {
                    if (index == 0) emit(0);
                    if (rb[0].rank1 == rb[1].rank1 and rb[0].rank2 == rb[1].rank2)
                        emit(0);
                    else
                        emit(index + 1);
                    if (index == input_size - 2) {
                        if (rb[0].rank1 == rb[1].rank1 and rb[0].rank2 == rb[1].rank2)
                            emit(0);
                        else
                            emit(index + 2);
                    }
            })
            .PrefixSum([](const size_t a, const size_t b) {
                return a > b ? a : b;
            });

        if (debug_print)
            rebucket.Print("rebucket");
        LOG << "Rebucket the partial SA";
    }
}

/*!
 * Class to encapsulate all
 */
class StartPrefixDoubling
{
public:
    StartPrefixDoubling(
        Context& ctx,
        const std::string& input_path, const std::string& output_path,
        bool text_output_flag,
        bool check_flag,
        bool input_verbatim)
        : ctx_(ctx),
          input_path_(input_path), output_path_(output_path),
          text_output_flag_(text_output_flag),
          check_flag_(check_flag),
          input_verbatim_(input_verbatim) { }

    void Run() {
        if (input_verbatim_) {
            // take path as verbatim text
            std::vector<uint8_t> input_vec(input_path_.begin(), input_path_.end());
            auto input_dia = Distribute<uint8_t>(ctx_, input_vec);
            if (debug_print) input_dia.Print("input");

            StartPrefixDoublingInput(input_dia, input_vec.size());
        }
        else {
            auto input_dia = ReadBinary<uint8_t>(ctx_, input_path_);
            size_t input_size = input_dia.Size();
            StartPrefixDoublingInput(input_dia, input_size);
        }
    }

    template <typename InputDIA>
    void StartPrefixDoublingInput(const InputDIA& input_dia, uint64_t input_size) {

        auto suffix_array = PrefixDoubling(ctx_, input_dia, input_size);
        if (output_path_.size()) {
            suffix_array.WriteBinary(output_path_);
        }

        if (check_flag_) {
            LOG1 << "checking suffix array...";

            //if (!CheckSA(input_dia, suffix_array)) {
            //    throw std::runtime_error("Suffix array is invalid!");
            //}
            //else {
            //    LOG1 << "okay.";
            //}
        }
    }

protected:
    Context& ctx_;

    std::string input_path_;
    std::string output_path_;

    bool text_output_flag_;
    bool check_flag_;
    bool input_verbatim_;

};

int main(int argc, char* argv[]) {
    common::CmdlineParser cp;

    cp.SetDescription("A prefix doubling suffix array construction algorithm.");
    cp.SetAuthor("Florian Kurpicz <florian.kurpicz@tu-dortmund.de>");

    std::string input_path, output_path;
    bool text_output_flag = false;
    bool check_flag = false;
    bool input_verbatim = false;

    cp.AddParamString("input", input_path,
                      "Path to input file (or verbatim text).\n"
                      "  The special inputs 'random' and 'unary' generate "
                      "such text on-the-fly.");
    cp.AddFlag('c', "check", check_flag,
               "Check suffix array for correctness.");
    cp.AddFlag('t', "text", text_output_flag,
               "Print out suffix array in readable text.");
    cp.AddString('o', "output", output_path,
                 "Output suffix array to given path.");
    cp.AddFlag('v', "verbatim", input_verbatim,
               "Consider \"input\" as verbatim text to construct "
               "suffix array on.");
    cp.AddFlag('d', "debug", debug_print,
               "Print debug info.");

    // process command line
    if (!cp.Process(argc, argv))
        return -1;

    return Run(
        [&](Context& ctx) {
            return StartPrefixDoubling(ctx,
                            input_path, output_path,
                            text_output_flag,
                            check_flag,
                            input_verbatim).Run();
        });
}
/******************************************************************************/
<|endoftext|>


<commit_before>/*****************************************************************************
 * libVLC backend for the Phonon library                                     *
 *                                                                           *
 * Copyright (C) 2007-2008 Tanguy Krotoff <tkrotoff@gmail.com>               *
 * Copyright (C) 2008 Lukas Durfina <lukas.durfina@gmail.com>                *
 * Copyright (C) 2009 Fathi Boudra <fabo@kde.org>                            *
 * Copyright (C) 2009-2010 vlc-phonon AUTHORS                                *
 *                                                                           *
 * 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 Lesser General Public          *
 * License along with this package; if not, write to the Free Software       *
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA *
 *****************************************************************************/

#include "devicemanager.h"

#ifdef PHONON_PULSESUPPORT
#  include <phonon/pulsesupport.h>
#endif

#include <vlc/vlc.h>

#include "backend.h"
#include "debug.h"
#include "libvlc.h"

QT_BEGIN_NAMESPACE

namespace Phonon
{
namespace VLC
{

DeviceInfo::DeviceInfo( const QByteArray& name, const QString& description, bool isAdvanced)
{
    // Get an id
    static int counter = 0;
    id = counter++;

    // Get name and description for the device
    this->name = name;
    this->description = description;
    this->isAdvanced = isAdvanced;
    capabilities = None;
}

DeviceManager::DeviceManager(Backend *parent)
    : QObject(parent)
    , m_backend(parent)
{
    Q_ASSERT(parent);
    m_deviceLists << &m_audioOutputDeviceList
                  << &m_audioCaptureDeviceList
                  << &m_videoCaptureDeviceList;
    updateDeviceList();
}

DeviceManager::~DeviceManager()
{
    foreach (const QList<DeviceInfo> *list, m_deviceLists) {
        const_cast<QList<DeviceInfo> *>(list)->clear();
    }
}

bool DeviceManager::canOpenDevice() const
{
    return true;
}

int DeviceManager::deviceId(const QByteArray &name) const
{
    foreach (const QList<DeviceInfo> *list, m_deviceLists) {
        foreach (const DeviceInfo &device, *list) {
            if (device.name == name)
                return device.id;
        }
    }

    return -1;
}

QString DeviceManager::deviceDescription(int id) const
{
    foreach (const QList<DeviceInfo> *list, m_deviceLists) {
        foreach (const DeviceInfo &device, *list) {
            if (device.id == id)
                return QString(device.name);
        }
    }

    return QString();
}

void DeviceManager::updateDeviceSublist(const QList<DeviceInfo> &newDevices, QList<DeviceInfo> &deviceList)
{
    // New and old device counts
    int newDeviceCount = newDevices.count();
    int oldDeviceCount = deviceList.count();

    for (int i = 0; i < newDeviceCount; ++i) {
        int id = deviceId(newDevices[i].name);
        if (id == -1) {
            // This is a new device, add it
            deviceList.append(newDevices[i]);
            id = deviceId(newDevices[i].name);
            emit deviceAdded(id);

            debug() << "Added backend device" << newDevices[i].name.data() << "with id" << id;
        }
    }

    if (newDeviceCount < oldDeviceCount) {
        // A device was removed
        for (int i = oldDeviceCount - 1; i >= 0 ; --i) {
            QByteArray currId = deviceList[i].name;
            bool b_found = false;
            for (int k = newDeviceCount - 1; k >= 0 ; --k) {
                if (currId == newDevices[k].name) {
                    b_found = true;
                    break;
                }
            }
            if (!b_found) {
                emit deviceRemoved(deviceId(currId));
                deviceList.removeAt(i);
            }
        }
    }
}

void DeviceManager::updateDeviceList()
{
    // Lists for capture devices
    QList<DeviceInfo> devices, videoCaptureDeviceList, audioCaptureDeviceList;
    int i;

    // Setup a list of available capture devices
    DeviceInfo screenDevice("Screen", "Virtual device for screen capture", false);
    screenDevice.capabilities = DeviceInfo::VideoCapture;
    screenDevice.accessList.append(QPair<QByteArray, QString>("screen", ""));
    videoCaptureDeviceList.append(screenDevice);

    // See the device capabilities and sort them accordingly
    for (i = 0; i < devices.count(); ++ i) {
        if (devices[i].capabilities & DeviceInfo::VideoCapture)
            videoCaptureDeviceList << devices[i];
        if (devices[i].capabilities & DeviceInfo::AudioCapture)
            audioCaptureDeviceList << devices[i];
    }

    devices.clear();

    // Update the capture device lists
    updateDeviceSublist(videoCaptureDeviceList, m_videoCaptureDeviceList);
    updateDeviceSublist(audioCaptureDeviceList, m_audioCaptureDeviceList);

    // Lists for audio output devices
    QList<DeviceInfo> audioOutputDeviceList;
    audioOutputDeviceList.append(DeviceInfo("default"));
    audioOutputDeviceList.last().capabilities = DeviceInfo::AudioOutput;

    if (!LibVLC::self)
        return;

    // Get the list of available audio outputs
    libvlc_audio_output_t *p_ao_list = libvlc_audio_output_list_get(libvlc);
    if (!p_ao_list) {
        error() << "libVLC:" << LibVLC::errorMessage();
    }
    libvlc_audio_output_t *p_start = p_ao_list;

    bool checkpulse = false;
#ifdef PHONON_PULSESUPPORT
    PulseSupport *pulse = PulseSupport::getInstance();
    checkpulse = pulse->isActive();
#endif
    bool haspulse = false;
    while (p_ao_list) {
        if (checkpulse && strcmp(p_ao_list->psz_name, "pulse") == 0) {
            audioOutputDeviceList.last().isAdvanced = false;
            audioOutputDeviceList.last().accessList.append(DeviceAccess("pulse", "default"));
            haspulse = true;
            break;
        }

        audioOutputDeviceList.append(DeviceInfo(p_ao_list->psz_name, p_ao_list->psz_description, true));
        audioOutputDeviceList.last().accessList.append(DeviceAccess(p_ao_list->psz_name, QString()));
        audioOutputDeviceList.last().capabilities = DeviceInfo::AudioOutput;

        p_ao_list = p_ao_list->p_next;
    }
    libvlc_audio_output_list_release(p_start);

#ifdef PHONON_PULSESUPPORT
    if (haspulse) {
        return;
    }
    pulse->enable(false);
#endif

    updateDeviceSublist(audioOutputDeviceList, m_audioOutputDeviceList);
}

const QList<DeviceInfo> DeviceManager::audioCaptureDevices() const
{
    return m_audioCaptureDeviceList;
}

const QList<DeviceInfo> DeviceManager::videoCaptureDevices() const
{
    return m_videoCaptureDeviceList;
}

const QList<DeviceInfo> DeviceManager::audioOutputDevices() const
{
    return m_audioOutputDeviceList;
}

}
}

QT_END_NAMESPACE
<commit_msg>formatting++<commit_after>/*****************************************************************************
 * libVLC backend for the Phonon library                                     *
 *                                                                           *
 * Copyright (C) 2007-2008 Tanguy Krotoff <tkrotoff@gmail.com>               *
 * Copyright (C) 2008 Lukas Durfina <lukas.durfina@gmail.com>                *
 * Copyright (C) 2009 Fathi Boudra <fabo@kde.org>                            *
 * Copyright (C) 2009-2010 vlc-phonon AUTHORS                                *
 *                                                                           *
 * 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 Lesser General Public          *
 * License along with this package; if not, write to the Free Software       *
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA *
 *****************************************************************************/

#include "devicemanager.h"

#ifdef PHONON_PULSESUPPORT
#  include <phonon/pulsesupport.h>
#endif

#include <vlc/vlc.h>

#include "backend.h"
#include "debug.h"
#include "libvlc.h"

QT_BEGIN_NAMESPACE

namespace Phonon
{
namespace VLC
{

DeviceInfo::DeviceInfo(const QByteArray &name,
                       const QString &description,
                       bool isAdvanced)
{
    // Get an id
    static int counter = 0;
    id = counter++;

    // Get name and description for the device
    this->name = name;
    this->description = description;
    this->isAdvanced = isAdvanced;
    capabilities = None;
}

DeviceManager::DeviceManager(Backend *parent)
    : QObject(parent)
    , m_backend(parent)
{
    Q_ASSERT(parent);
    m_deviceLists << &m_audioOutputDeviceList
                  << &m_audioCaptureDeviceList
                  << &m_videoCaptureDeviceList;
    updateDeviceList();
}

DeviceManager::~DeviceManager()
{
    foreach (const QList<DeviceInfo> *list, m_deviceLists) {
        const_cast<QList<DeviceInfo> *>(list)->clear();
    }
}

bool DeviceManager::canOpenDevice() const
{
    return true;
}

int DeviceManager::deviceId(const QByteArray &name) const
{
    foreach (const QList<DeviceInfo> *list, m_deviceLists) {
        foreach (const DeviceInfo &device, *list) {
            if (device.name == name)
                return device.id;
        }
    }

    return -1;
}

QString DeviceManager::deviceDescription(int id) const
{
    foreach (const QList<DeviceInfo> *list, m_deviceLists) {
        foreach (const DeviceInfo &device, *list) {
            if (device.id == id)
                return QString(device.name);
        }
    }

    return QString();
}

void DeviceManager::updateDeviceSublist(const QList<DeviceInfo> &newDevices, QList<DeviceInfo> &deviceList)
{
    // New and old device counts
    int newDeviceCount = newDevices.count();
    int oldDeviceCount = deviceList.count();

    for (int i = 0; i < newDeviceCount; ++i) {
        int id = deviceId(newDevices[i].name);
        if (id == -1) {
            // This is a new device, add it
            deviceList.append(newDevices[i]);
            id = deviceId(newDevices[i].name);
            emit deviceAdded(id);

            debug() << "Added backend device" << newDevices[i].name.data() << "with id" << id;
        }
    }

    if (newDeviceCount < oldDeviceCount) {
        // A device was removed
        for (int i = oldDeviceCount - 1; i >= 0; --i) {
            QByteArray currId = deviceList[i].name;
            bool b_found = false;
            for (int k = newDeviceCount - 1; k >= 0; --k) {
                if (currId == newDevices[k].name) {
                    b_found = true;
                    break;
                }
            }
            if (!b_found) {
                emit deviceRemoved(deviceId(currId));
                deviceList.removeAt(i);
            }
        }
    }
}

void DeviceManager::updateDeviceList()
{
    // Lists for capture devices
    QList<DeviceInfo> devices, videoCaptureDeviceList, audioCaptureDeviceList;
    int i;

    // Setup a list of available capture devices
    DeviceInfo screenDevice("Screen", "Virtual device for screen capture", false);
    screenDevice.capabilities = DeviceInfo::VideoCapture;
    screenDevice.accessList.append(QPair<QByteArray, QString>("screen", ""));
    videoCaptureDeviceList.append(screenDevice);

    // See the device capabilities and sort them accordingly
    for (i = 0; i < devices.count(); ++ i) {
        if (devices[i].capabilities & DeviceInfo::VideoCapture)
            videoCaptureDeviceList << devices[i];
        if (devices[i].capabilities & DeviceInfo::AudioCapture)
            audioCaptureDeviceList << devices[i];
    }

    devices.clear();

    // Update the capture device lists
    updateDeviceSublist(videoCaptureDeviceList, m_videoCaptureDeviceList);
    updateDeviceSublist(audioCaptureDeviceList, m_audioCaptureDeviceList);

    // Lists for audio output devices
    QList<DeviceInfo> audioOutputDeviceList;
    audioOutputDeviceList.append(DeviceInfo("default"));
    audioOutputDeviceList.last().capabilities = DeviceInfo::AudioOutput;

    if (!LibVLC::self)
        return;

    // Get the list of available audio outputs
    libvlc_audio_output_t *p_ao_list = libvlc_audio_output_list_get(libvlc);
    if (!p_ao_list) {
        error() << "libVLC:" << LibVLC::errorMessage();
    }
    libvlc_audio_output_t *p_start = p_ao_list;

    bool checkpulse = false;
#ifdef PHONON_PULSESUPPORT
    PulseSupport *pulse = PulseSupport::getInstance();
    checkpulse = pulse->isActive();
#endif
    bool haspulse = false;
    while (p_ao_list) {
        if (checkpulse && strcmp(p_ao_list->psz_name, "pulse") == 0) {
            audioOutputDeviceList.last().isAdvanced = false;
            audioOutputDeviceList.last().accessList.append(DeviceAccess("pulse", "default"));
            haspulse = true;
            break;
        }

        audioOutputDeviceList.append(DeviceInfo(p_ao_list->psz_name, p_ao_list->psz_description, true));
        audioOutputDeviceList.last().accessList.append(DeviceAccess(p_ao_list->psz_name, QString()));
        audioOutputDeviceList.last().capabilities = DeviceInfo::AudioOutput;

        p_ao_list = p_ao_list->p_next;
    }
    libvlc_audio_output_list_release(p_start);

#ifdef PHONON_PULSESUPPORT
    if (haspulse) {
        return;
    }
    pulse->enable(false);
#endif

    updateDeviceSublist(audioOutputDeviceList, m_audioOutputDeviceList);
}

const QList<DeviceInfo> DeviceManager::audioCaptureDevices() const
{
    return m_audioCaptureDeviceList;
}

const QList<DeviceInfo> DeviceManager::videoCaptureDevices() const
{
    return m_videoCaptureDeviceList;
}

const QList<DeviceInfo> DeviceManager::audioOutputDevices() const
{
    return m_audioOutputDeviceList;
}

}
}

QT_END_NAMESPACE
<|endoftext|>


<commit_before>#include "dialognewdirectory.h"
#include "ui_dialognewdirectory.h"
#include <QPushButton>

DialogNewDirectory::DialogNewDirectory(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::DialogNewDirectory)
{
    ui->setupUi(this);

    // Remove [?] Button from window
    this->setWindowFlags(this->windowFlags() & ~Qt::WindowContextHelpButtonHint);

    // Enable or disable OK butotn
    enableOkButton(validDirectory(ui->txtDirectoryName->text()));
}

DialogNewDirectory::~DialogNewDirectory()
{
    delete ui;
}

bool DialogNewDirectory::validDirectory(QString directoryName){
    //Todo: add regexp to check directory name
    QRegExp re("^(?!\\s)[^<>\\\\/:|\"\*\?\.]+$");
    return re.exactMatch(directoryName);
}

void  DialogNewDirectory::enableOkButton(bool enable){
    // Check if valid dirictory and set OK enable/disable OK burron
    QPushButton *button = ui->buttonBoxNewDir->button(QDialogButtonBox::Ok);
    button->setEnabled(enable);
    if(enable) dirName = ui->txtDirectoryName->text();
}

void DialogNewDirectory::on_txtDirectoryName_textChanged(const QString &dirName)
{
    // Check if input is valid and enable/diable the OK button
    enableOkButton(validDirectory(dirName));
}
<commit_msg>#43 can't end with space<commit_after>#include "dialognewdirectory.h"
#include "ui_dialognewdirectory.h"
#include <QPushButton>

DialogNewDirectory::DialogNewDirectory(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::DialogNewDirectory)
{
    ui->setupUi(this);

    // Remove [?] Button from window
    this->setWindowFlags(this->windowFlags() & ~Qt::WindowContextHelpButtonHint);

    // Enable or disable OK butotn
    enableOkButton(validDirectory(ui->txtDirectoryName->text()));
}

DialogNewDirectory::~DialogNewDirectory()
{
    delete ui;
}

bool DialogNewDirectory::validDirectory(QString directoryName){
    //Todo: add regexp to check directory name
    QRegExp re("^(?!\\s)[^<>\\\\/:|\"\*\?\.]*\\S(?!\\s)$");
    return re.exactMatch(directoryName);
}

void  DialogNewDirectory::enableOkButton(bool enable){
    // Check if valid dirictory and set OK enable/disable OK burron
    QPushButton *button = ui->buttonBoxNewDir->button(QDialogButtonBox::Ok);
    button->setEnabled(enable);
    if(enable) dirName = ui->txtDirectoryName->text();
}

void DialogNewDirectory::on_txtDirectoryName_textChanged(const QString &dirName)
{
    // Check if input is valid and enable/diable the OK button
    enableOkButton(validDirectory(dirName));
}
<|endoftext|>


<commit_before>#pragma once

#include "pugixml.hpp"

#include "solver.hpp"
#include "source.hpp"
#include "core_mesh.hpp"
#include "transport_sweeper.hpp"
#include "h5file.hpp"

namespace mocc{
    /**
    * This Solver (FSS) attempts to solve the fixed source problem. For now, the
    * fixed source must be provided by some solver above the FSS, in the form of
    * a Source object, however in the future it might be useful to be able to
    * supply a user-defined Source for non-eigenvalue problems.
    *
    * Right now, the FSS is used by the EigenSolver to converge the flux
    * solution for intermediate "fixed" sources for each eigenvalue step.
    */
    class FixedSourceSolver: public Solver {
    public:
        /**
        * Initialize a FSS using an XML node and CoreMesh. The expects the
        * passed XML node to be a valid \<solver\> tag containing a relevant
        * \<sweeper\> tag, which is needed by the TransportSweeperFactory() to
        * generate a TransportSweeper.
        */
        FixedSourceSolver( const pugi::xml_node &input, const CoreMesh &mesh );

        ~FixedSourceSolver() {
        }

        /**
        * For now, there is no actual implementation of this method, since there
        * is no functionality for specifying a user-defined Source. In practice,
        * the FSS is driven via the step() routine by the EigenSolver.
        *
        * Ideally, this would solve a fixed source problem subject to the
        * configuration in the XML input. This can either be to some sort of
        * tolerance, or for a fixed number of group sweeps.
        */
        void solve();

        /**
        * Instructs the sweeper to store the old value of the flux, then
        * performs a group sweep.
        */
        void step();

        /**
        * Initialize the state of the FSS to start a new problem. For now this
        * just calls the same routine on the TransportSweeper, which in turn
        * initializes the scalar flux, boundary conditions, etc. to some sort of
        * halfway-reasonable starting values.
        */
        void initialize() {
            sweeper_->initialize();
        }

        /// Set the group-independent fission source. The group-dependent fission
        /// source is calculated internally by the Source object.
        void set_fission_source( const ArrayX* fs) {
            fs_ = fs;
        }

        /// Return the number of flat source regions.
        unsigned int n_reg() {
            return sweeper_->n_reg();
        }

        /// Return a constant reference to the transport sweeper.
        const TransportSweeper* sweeper() const {
            return sweeper_.get();
        }

        void output( H5File& file ) const {
            sweeper_->output( file );
            return;
        }

    private:
        UP_Sweeper_t sweeper_;
        UP_Source_t source_;
        // Pointer to the group-independent fission source. Usually comes from
        // an eigenvalue solver, if present
        const ArrayX* fs_;
        unsigned int ng_;
    };
}
<commit_msg>Add accessor for ng_ to FSS<commit_after>#pragma once

#include "pugixml.hpp"

#include "solver.hpp"
#include "source.hpp"
#include "core_mesh.hpp"
#include "transport_sweeper.hpp"
#include "h5file.hpp"

namespace mocc{
    /**
    * This Solver (FSS) attempts to solve the fixed source problem. For now, the
    * fixed source must be provided by some solver above the FSS, in the form of
    * a Source object, however in the future it might be useful to be able to
    * supply a user-defined Source for non-eigenvalue problems.
    *
    * Right now, the FSS is used by the EigenSolver to converge the flux
    * solution for intermediate "fixed" sources for each eigenvalue step.
    */
    class FixedSourceSolver: public Solver {
    public:
        /**
        * Initialize a FSS using an XML node and CoreMesh. The expects the
        * passed XML node to be a valid \<solver\> tag containing a relevant
        * \<sweeper\> tag, which is needed by the TransportSweeperFactory() to
        * generate a TransportSweeper.
        */
        FixedSourceSolver( const pugi::xml_node &input, const CoreMesh &mesh );

        ~FixedSourceSolver() {
        }

        /**
        * For now, there is no actual implementation of this method, since there
        * is no functionality for specifying a user-defined Source. In practice,
        * the FSS is driven via the step() routine by the EigenSolver.
        *
        * Ideally, this would solve a fixed source problem subject to the
        * configuration in the XML input. This can either be to some sort of
        * tolerance, or for a fixed number of group sweeps.
        */
        void solve();

        /**
        * Instructs the sweeper to store the old value of the flux, then
        * performs a group sweep.
        */
        void step();

        /**
        * Initialize the state of the FSS to start a new problem. For now this
        * just calls the same routine on the TransportSweeper, which in turn
        * initializes the scalar flux, boundary conditions, etc. to some sort of
        * halfway-reasonable starting values.
        */
        void initialize() {
            sweeper_->initialize();
        }

        /// Set the group-independent fission source. The group-dependent fission
        /// source is calculated internally by the Source object.
        void set_fission_source( const ArrayX* fs) {
            fs_ = fs;
        }

        /// Return the number of flat source regions.
        unsigned int n_reg() {
            return sweeper_->n_reg();
        }

        /// Return the number of energy groups
        unsigned int n_group() {
            return ng_;
        }

        /// Return a constant reference to the transport sweeper.
        const TransportSweeper* sweeper() const {
            return sweeper_.get();
        }

        void output( H5File& file ) const {
            sweeper_->output( file );
            return;
        }

    private:
        UP_Sweeper_t sweeper_;
        UP_Source_t source_;
        // Pointer to the group-independent fission source. Usually comes from
        // an eigenvalue solver, if present
        const ArrayX* fs_;
        unsigned int ng_;
    };
}
<|endoftext|>