<commit_before>/*************************************************************************
 *                                                                       *
 * Open Dynamics Engine, Copyright (C) 2001,2002 Russell L. Smith.       *
 * All rights reserved.  Email: russ@q12.org   Web: www.q12.org          *
 *                                                                       *
 * This library is free software; you can redistribute it and/or         *
 * modify it under the terms of EITHER:                                  *
 *   (1) The GNU Lesser General Public License as published by the Free  *
 *       Software Foundation; either version 2.1 of the License, or (at  *
 *       your option) any later version. The text of the GNU Lesser      *
 *       General Public License is included with this library in the     *
 *       file LICENSE.TXT.                                               *
 *   (2) The BSD-style license that is included with this library in     *
 *       the file LICENSE-BSD.TXT.                                       *
 *                                                                       *
 * This library is distributed in the hope that it will be useful,       *
 * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the files    *
 * LICENSE.TXT and LICENSE-BSD.TXT for more details.                     *
 *                                                                       *
 *************************************************************************/

// Basket ball demo.
// Serves as a test for the sphere vs trimesh collider
// By Bram Stolk.
// Press the spacebar to reset the position of the ball.

#include <ode/config.h>
#include <assert.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <ode/ode.h>
#include <drawstuff/drawstuff.h>

#include "basket_geom.h" // this is our world mesh

#ifdef _MSC_VER
#pragma warning(disable:4244 4305)  // for VC++, no precision loss complaints
#endif

// some constants

#define RADIUS 0.14

// dynamics and collision objects (chassis, 3 wheels, environment)

static dWorldID world;
static dSpaceID space;

static dBodyID sphbody;
static dGeomID sphgeom;

static dJointGroupID contactgroup;
static dGeomID world_mesh;

// this is called by dSpaceCollide when two objects in space are
// potentially colliding.

static void nearCallback (void *data, dGeomID o1, dGeomID o2)
{
  assert(o1);
  assert(o2);

  if (dGeomIsSpace(o1) || dGeomIsSpace(o2))
  {
    fprintf(stderr,"testing space %p %p\n", o1,o2);
    // colliding a space with something
    dSpaceCollide2(o1,o2,data,&nearCallback);
    // Note we do not want to test intersections within a space,
    // only between spaces.
    return;
  }

//  fprintf(stderr,"testing geoms %p %p\n", o1, o2);

  const int N = 32;
  dContact contact[N];
  int n = dCollide (o1,o2,N,&(contact[0].geom),sizeof(dContact));
  if (n > 0)
  {
    for (int i=0; i<n; i++)
    {
	  // Paranoia  <-- not working for some people, temporarily removed for 0.6
      //dIASSERT(dVALIDVEC3(contact[i].geom.pos));
      //dIASSERT(dVALIDVEC3(contact[i].geom.normal));
      //dIASSERT(!dIsNan(contact[i].geom.depth));
      contact[i].surface.slip1 = 0.7;
      contact[i].surface.slip2 = 0.7;
      contact[i].surface.mode = dContactSoftERP | dContactSoftCFM | dContactApprox1 | dContactSlip1 | dContactSlip2;
      contact[i].surface.mu = 50.0; // was: dInfinity
      contact[i].surface.soft_erp = 0.96;
      contact[i].surface.soft_cfm = 0.04;
      dJointID c = dJointCreateContact (world,contactgroup,&contact[i]);
      dJointAttach (c,
		    dGeomGetBody(contact[i].geom.g1),
		    dGeomGetBody(contact[i].geom.g2));
    }
  }
}

// start simulation - set viewpoint

static void start()
{
  static float xyz[3] = {-8,0,5};
  static float hpr[3] = {0.0f,-29.5000f,0.0000f};
  dsSetViewpoint (xyz,hpr);
}

static void reset_ball(void)
{
  float sx=0.0f, sy=3.40f, sz=6.80f;

#if defined(_MSC_VER) && defined(dDOUBLE)
  sy -= 0.01; // Cheat, to make it score under win32/double
#endif

  dQuaternion q;
  dQSetIdentity(q);
  dBodySetPosition (sphbody, sx, sy, sz);
  dBodySetQuaternion(sphbody, q);
  dBodySetLinearVel (sphbody, 0,0,0);
  dBodySetAngularVel (sphbody, 0,0,0);
}

// called when a key pressed

static void command (int cmd)
{
  switch (cmd)
  {
    case ' ':
	  reset_ball();
      break;
  }
}

// simulation loop

static void simLoop (int pause)
{
  double simstep = 0.001; // 1ms simulation steps
  double dt = dsElapsedTime();

  int nrofsteps = (int) ceilf(dt/simstep);
//  fprintf(stderr, "dt=%f, nr of steps = %d\n", dt, nrofsteps);

  for (int i=0; i<nrofsteps && !pause; i++)
  {
    dSpaceCollide (space,0,&nearCallback);
    dWorldQuickStep (world, simstep);
    dJointGroupEmpty (contactgroup);
  }

  dsSetColor (1,1,1);
  const dReal *SPos = dBodyGetPosition(sphbody);
  const dReal *SRot = dBodyGetRotation(sphbody);
  float spos[3] = {SPos[0], SPos[1], SPos[2]};
  float srot[12] = { SRot[0], SRot[1], SRot[2], SRot[3], SRot[4], SRot[5], SRot[6], SRot[7], SRot[8], SRot[9], SRot[10], SRot[11] };
  dsDrawSphere
  (
    spos,
    srot,
    RADIUS
  );

  // draw world trimesh
  dsSetColor(0.4,0.7,0.9);
  dsSetTexture (DS_NONE);

  const dReal* Pos = dGeomGetPosition(world_mesh);
  //dIASSERT(dVALIDVEC3(Pos));
  float pos[3] = { Pos[0], Pos[1], Pos[2] };

  const dReal* Rot = dGeomGetRotation(world_mesh);
  //dIASSERT(dVALIDMAT3(Rot));
  float rot[12] = { Rot[0], Rot[1], Rot[2], Rot[3], Rot[4], Rot[5], Rot[6], Rot[7], Rot[8], Rot[9], Rot[10], Rot[11] };

  int numi = sizeof(world_indices)  / sizeof(int);

  for (int i=0; i<numi/3; i++)
  {
    int i0 = world_indices[i*3+0];
    int i1 = world_indices[i*3+1];
    int i2 = world_indices[i*3+2];
    float *v0 = world_vertices+i0*3;
    float *v1 = world_vertices+i1*3;
    float *v2 = world_vertices+i2*3;
    dsDrawTriangle(pos, rot, v0,v1,v2, true); // single precision draw
  }
}

int main (int argc, char **argv)
{
  dMass m;
  dMatrix3 R;

  // setup pointers to drawstuff callback functions
  dsFunctions fn;
  fn.version = DS_VERSION;
  fn.start = &start;
  fn.step = &simLoop;
  fn.command = &command;
  fn.stop = 0;
  fn.path_to_textures = "../../drawstuff/textures";
  if(argc==2)
    fn.path_to_textures = argv[1];

  // create world
  dInitODE();
  world = dWorldCreate();
  space = dHashSpaceCreate (0);

  contactgroup = dJointGroupCreate (0);
  dWorldSetGravity (world,0,0,-9.8);
  dWorldSetQuickStepNumIterations (world, 64);

  // Create a static world using a triangle mesh that we can collide with.
  int numv = sizeof(world_vertices)/(3*sizeof(float));
  int numi = sizeof(world_indices)/ sizeof(int);
  printf("numv=%d, numi=%d\n", numv, numi);
  dTriMeshDataID Data = dGeomTriMeshDataCreate();

//  fprintf(stderr,"Building Single Precision Mesh\n");

  dGeomTriMeshDataBuildSingle
  (
    Data,
    world_vertices,
    3 * sizeof(float),
    numv,
    world_indices,
    numi,
    3 * sizeof(int)
  );

  world_mesh = dCreateTriMesh(space, Data, 0, 0, 0);
  dGeomTriMeshEnableTC(world_mesh, dSphereClass, false);
  dGeomTriMeshEnableTC(world_mesh, dBoxClass, false);
  dGeomSetPosition(world_mesh, 0, 0, 0.5);
  dRSetIdentity(R);
  //dIASSERT(dVALIDMAT3(R));

  dGeomSetRotation (world_mesh, R);

  float sx=0.0, sy=3.40, sz=6.80;
  sphbody = dBodyCreate (world);
  dMassSetSphere (&m,1,RADIUS);
  dBodySetMass (sphbody,&m);
  sphgeom = dCreateSphere(0, RADIUS);
  dGeomSetBody (sphgeom,sphbody);
  reset_ball();
  dSpaceAdd (space, sphgeom);

  // run simulation
  dsSimulationLoop (argc,argv,352,288,&fn);

  // Causes segm violation? Why?
  // (because dWorldDestroy() destroys body connected to geom; must call first!)
  dGeomDestroy(sphgeom);
  dGeomDestroy (world_mesh);

  dJointGroupEmpty (contactgroup);
  dJointGroupDestroy (contactgroup);
  dSpaceDestroy (space);
  dWorldDestroy (world);
  dCloseODE();
  return 0;
}

<commit_msg>Make it score on linux+opcode<commit_after>/*************************************************************************
 *                                                                       *
 * Open Dynamics Engine, Copyright (C) 2001,2002 Russell L. Smith.       *
 * All rights reserved.  Email: russ@q12.org   Web: www.q12.org          *
 *                                                                       *
 * This library is free software; you can redistribute it and/or         *
 * modify it under the terms of EITHER:                                  *
 *   (1) The GNU Lesser General Public License as published by the Free  *
 *       Software Foundation; either version 2.1 of the License, or (at  *
 *       your option) any later version. The text of the GNU Lesser      *
 *       General Public License is included with this library in the     *
 *       file LICENSE.TXT.                                               *
 *   (2) The BSD-style license that is included with this library in     *
 *       the file LICENSE-BSD.TXT.                                       *
 *                                                                       *
 * This library is distributed in the hope that it will be useful,       *
 * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the files    *
 * LICENSE.TXT and LICENSE-BSD.TXT for more details.                     *
 *                                                                       *
 *************************************************************************/

// Basket ball demo.
// Serves as a test for the sphere vs trimesh collider
// By Bram Stolk.
// Press the spacebar to reset the position of the ball.

#include <ode/config.h>
#include <assert.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <ode/ode.h>
#include <drawstuff/drawstuff.h>

#include "basket_geom.h" // this is our world mesh

#ifdef _MSC_VER
#pragma warning(disable:4244 4305)  // for VC++, no precision loss complaints
#endif

// some constants

#define RADIUS 0.14

// dynamics and collision objects (chassis, 3 wheels, environment)

static dWorldID world;
static dSpaceID space;

static dBodyID sphbody;
static dGeomID sphgeom;

static dJointGroupID contactgroup;
static dGeomID world_mesh;

// this is called by dSpaceCollide when two objects in space are
// potentially colliding.

static void nearCallback (void *data, dGeomID o1, dGeomID o2)
{
  assert(o1);
  assert(o2);

  if (dGeomIsSpace(o1) || dGeomIsSpace(o2))
  {
    fprintf(stderr,"testing space %p %p\n", o1,o2);
    // colliding a space with something
    dSpaceCollide2(o1,o2,data,&nearCallback);
    // Note we do not want to test intersections within a space,
    // only between spaces.
    return;
  }

//  fprintf(stderr,"testing geoms %p %p\n", o1, o2);

  const int N = 32;
  dContact contact[N];
  int n = dCollide (o1,o2,N,&(contact[0].geom),sizeof(dContact));
  if (n > 0)
  {
    for (int i=0; i<n; i++)
    {
	  // Paranoia  <-- not working for some people, temporarily removed for 0.6
      //dIASSERT(dVALIDVEC3(contact[i].geom.pos));
      //dIASSERT(dVALIDVEC3(contact[i].geom.normal));
      //dIASSERT(!dIsNan(contact[i].geom.depth));
      contact[i].surface.slip1 = 0.7;
      contact[i].surface.slip2 = 0.7;
      contact[i].surface.mode = dContactSoftERP | dContactSoftCFM | dContactApprox1 | dContactSlip1 | dContactSlip2;
      contact[i].surface.mu = 50.0; // was: dInfinity
      contact[i].surface.soft_erp = 0.96;
      contact[i].surface.soft_cfm = 0.04;
      dJointID c = dJointCreateContact (world,contactgroup,&contact[i]);
      dJointAttach (c,
		    dGeomGetBody(contact[i].geom.g1),
		    dGeomGetBody(contact[i].geom.g2));
    }
  }
}

// start simulation - set viewpoint

static void start()
{
  static float xyz[3] = {-8,0,5};
  static float hpr[3] = {0.0f,-29.5000f,0.0000f};
  dsSetViewpoint (xyz,hpr);
}

static void reset_ball(void)
{
  float sx=0.0f, sy=3.40f, sz=7.05;

#if defined(_MSC_VER) && defined(dDOUBLE)
  sy -= 0.01; // Cheat, to make it score under win32/double
#endif

  dQuaternion q;
  dQSetIdentity(q);
  dBodySetPosition (sphbody, sx, sy, sz);
  dBodySetQuaternion(sphbody, q);
  dBodySetLinearVel (sphbody, 0,0,0);
  dBodySetAngularVel (sphbody, 0,0,0);
}

// called when a key pressed

static void command (int cmd)
{
  switch (cmd)
  {
    case ' ':
	  reset_ball();
      break;
  }
}

// simulation loop

static void simLoop (int pause)
{
  double simstep = 0.001; // 1ms simulation steps
  double dt = dsElapsedTime();

  int nrofsteps = (int) ceilf(dt/simstep);
//  fprintf(stderr, "dt=%f, nr of steps = %d\n", dt, nrofsteps);

  for (int i=0; i<nrofsteps && !pause; i++)
  {
    dSpaceCollide (space,0,&nearCallback);
    dWorldQuickStep (world, simstep);
    dJointGroupEmpty (contactgroup);
  }

  dsSetColor (1,1,1);
  const dReal *SPos = dBodyGetPosition(sphbody);
  const dReal *SRot = dBodyGetRotation(sphbody);
  float spos[3] = {SPos[0], SPos[1], SPos[2]};
  float srot[12] = { SRot[0], SRot[1], SRot[2], SRot[3], SRot[4], SRot[5], SRot[6], SRot[7], SRot[8], SRot[9], SRot[10], SRot[11] };
  dsDrawSphere
  (
    spos,
    srot,
    RADIUS
  );

  // draw world trimesh
  dsSetColor(0.4,0.7,0.9);
  dsSetTexture (DS_NONE);

  const dReal* Pos = dGeomGetPosition(world_mesh);
  //dIASSERT(dVALIDVEC3(Pos));
  float pos[3] = { Pos[0], Pos[1], Pos[2] };

  const dReal* Rot = dGeomGetRotation(world_mesh);
  //dIASSERT(dVALIDMAT3(Rot));
  float rot[12] = { Rot[0], Rot[1], Rot[2], Rot[3], Rot[4], Rot[5], Rot[6], Rot[7], Rot[8], Rot[9], Rot[10], Rot[11] };

  int numi = sizeof(world_indices)  / sizeof(int);

  for (int i=0; i<numi/3; i++)
  {
    int i0 = world_indices[i*3+0];
    int i1 = world_indices[i*3+1];
    int i2 = world_indices[i*3+2];
    float *v0 = world_vertices+i0*3;
    float *v1 = world_vertices+i1*3;
    float *v2 = world_vertices+i2*3;
    dsDrawTriangle(pos, rot, v0,v1,v2, true); // single precision draw
  }
}

int main (int argc, char **argv)
{
  dMass m;
  dMatrix3 R;

  // setup pointers to drawstuff callback functions
  dsFunctions fn;
  fn.version = DS_VERSION;
  fn.start = &start;
  fn.step = &simLoop;
  fn.command = &command;
  fn.stop = 0;
  fn.path_to_textures = "../../drawstuff/textures";
  if(argc==2)
    fn.path_to_textures = argv[1];

  // create world
  dInitODE();
  world = dWorldCreate();
  space = dHashSpaceCreate (0);

  contactgroup = dJointGroupCreate (0);
  dWorldSetGravity (world,0,0,-9.8);
  dWorldSetQuickStepNumIterations (world, 64);

  // Create a static world using a triangle mesh that we can collide with.
  int numv = sizeof(world_vertices)/(3*sizeof(float));
  int numi = sizeof(world_indices)/ sizeof(int);
  printf("numv=%d, numi=%d\n", numv, numi);
  dTriMeshDataID Data = dGeomTriMeshDataCreate();

//  fprintf(stderr,"Building Single Precision Mesh\n");

  dGeomTriMeshDataBuildSingle
  (
    Data,
    world_vertices,
    3 * sizeof(float),
    numv,
    world_indices,
    numi,
    3 * sizeof(int)
  );

  world_mesh = dCreateTriMesh(space, Data, 0, 0, 0);
  dGeomTriMeshEnableTC(world_mesh, dSphereClass, false);
  dGeomTriMeshEnableTC(world_mesh, dBoxClass, false);
  dGeomSetPosition(world_mesh, 0, 0, 0.5);
  dRSetIdentity(R);
  //dIASSERT(dVALIDMAT3(R));

  dGeomSetRotation (world_mesh, R);

  float sx=0.0, sy=3.40, sz=6.80;
  sphbody = dBodyCreate (world);
  dMassSetSphere (&m,1,RADIUS);
  dBodySetMass (sphbody,&m);
  sphgeom = dCreateSphere(0, RADIUS);
  dGeomSetBody (sphgeom,sphbody);
  reset_ball();
  dSpaceAdd (space, sphgeom);

  // run simulation
  dsSimulationLoop (argc,argv,352,288,&fn);

  // Causes segm violation? Why?
  // (because dWorldDestroy() destroys body connected to geom; must call first!)
  dGeomDestroy(sphgeom);
  dGeomDestroy (world_mesh);

  dJointGroupEmpty (contactgroup);
  dJointGroupDestroy (contactgroup);
  dSpaceDestroy (space);
  dWorldDestroy (world);
  dCloseODE();
  return 0;
}

<|endoftext|>


<commit_before>#include "Resource.hpp"
#include "Asset.hpp"
#include "SDInputFile.hpp"

namespace MPACK
{
	namespace Core
	{
		const int PATH_BUFFER_SIZE=256;

		Resource::Resource(const char* pPath)
		{
			mPath = new char[strlen(pPath)+2];
			strcpy(mPath,pPath);
		}

		const char* Resource::GetPath()
		{
			return mPath;
		}

		Resource::~Resource()
		{
			delete[] mPath;
		}

		Resource* LoadResource(const char* pPath)
		{
	#ifdef ANDROID_PLATFORM
			if(pPath[0]=='@')
			{
				return (Resource*)(new Asset(pPath+1));
			}
			if(pPath[1]=='&')
			{
				return (Resource*)(new SDInputFile(pPath+1));
			}
	#elif	defined(WINDOWS_PLATFORM) || defined(LINUX_PLATFORM)
			char pathBuffer[PATH_BUFFER_SIZE];
			if(pPath[0]=='@')
			{
				strcpy(pathBuffer,"assets/");
				strcat(pathBuffer,pPath+1);
			}
			if(pPath[1]=='&')
			{
				strcpy(pathBuffer,pPath+1);
			}
			return (Resource*)(new SDInputFile(pathBuffer));
	#endif
			LOGE("LoadResource: invalid path %s",pPath);
			return NULL;
		}
	}
}
<commit_msg>Fixed resource loading bug<commit_after>#include "Resource.hpp"
#include "Asset.hpp"
#include "SDInputFile.hpp"

using namespace std;

namespace MPACK
{
	namespace Core
	{
		const int PATH_BUFFER_SIZE=256;

		Resource::Resource(const char* pPath)
		{
			mPath = new char[strlen(pPath)+2];
			strcpy(mPath,pPath);
		}

		const char* Resource::GetPath()
		{
			return mPath;
		}

		Resource::~Resource()
		{
			delete[] mPath;
		}

		Resource* LoadResource(const char* pPath)
		{
	#ifdef ANDROID_PLATFORM
			if(pPath[0]=='@')
			{
				return (Resource*)(new Asset(pPath+1));
			}
			if(pPath[0]=='&')
			{
				return (Resource*)(new SDInputFile(pPath+1));
			}
	#elif	defined(WINDOWS_PLATFORM) || defined(LINUX_PLATFORM)
			char pathBuffer[PATH_BUFFER_SIZE];
			if(pPath[0]=='@')
			{
				strcpy(pathBuffer,"assets/");
				strcat(pathBuffer,pPath+1);
			}
			if(pPath[0]=='&')
			{
				strcpy(pathBuffer,pPath+1);
			}
			return (Resource*)(new SDInputFile(pathBuffer));
	#endif
			LOGE("LoadResource: invalid path %s",pPath);
			return NULL;
		}
	}
}
<|endoftext|>


<commit_before>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 1999 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xalan" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */
/**
 *
 * @author David N. Bertoni (david_n_bertoni@lotus.com)
 * */

// Base class header file.
#include "ProblemListenerDefault.hpp"

#include <XalanDOM/XalanNode.hpp>

#include <PlatformSupport/DOMStringHelper.hpp>
#include <PlatformSupport/PrintWriter.hpp>

#include <XSLT/ElemTemplateElement.hpp>

static const char* const	errorHeader = "error: ";
static const char* const	warningHeader = "warning: ";

static const char* const	xslHeader = "XSLT ";
static const char* const	xmlHeader = "XML ";
static const char* const	xpathHeader = "XPath ";

static const char* const	styleTreeNodeHeader = ", style tree node: ";
static const char* const	sourceTreeNodeHeader = ", source tree node: ";
static const char* const	locationOpen = " (";
static const char* const	uriHeader = "";
static const char* const	lineNoHeader = ", line ";
static const char* const	charOffsetHeader = ", column ";
static const char* const	locationClose = ")";

ProblemListenerDefault::ProblemListenerDefault(PrintWriter*		pw) :
	ProblemListener(),
	m_pw(pw)
{
}

ProblemListenerDefault::~ProblemListenerDefault()
{
	m_pw = 0;
}

void
ProblemListenerDefault::setPrintWriter(PrintWriter*		pw)
{
	m_pw = pw;
}

void
ProblemListenerDefault::problem(
			eProblemSource			where,
			eClassification			classification,
			const XalanNode*		sourceNode,
			const XalanNode*		styleNode,
			const XalanDOMString&	msg,
			const XalanDOMChar*		uri,
			int						lineNo,
			int						charOffset)
{
	if (m_pw != 0)
	{
		if (eXMLPARSER == where)
		{
			m_pw->print(xmlHeader);
		}
		else if (eXPATH == where)
		{
			m_pw->print(xpathHeader);
		}
		else
		{
			m_pw->print(xslHeader);
		}

		if (eERROR == classification)
		{
			m_pw->print(errorHeader);
		}
		else
		{
			m_pw->print(warningHeader);
		}

		m_pw->print(msg);

		if (0 != styleNode)
		{
			m_pw->print(styleTreeNodeHeader);
			m_pw->print(styleNode->getNodeName());
		}

		if (0 != sourceNode)
		{
			m_pw->print(sourceTreeNodeHeader);
			m_pw->print(sourceNode->getNodeName());
		}

		m_pw->print(locationOpen);

		if (0 != uri)
		{
			m_pw->print(uriHeader);
			m_pw->print(uri);
		}

		if (0 != lineNo)
		{
			m_pw->print(lineNoHeader);
			m_pw->print(lineNo);
		}

		if (0 != charOffset)
		{
			m_pw->print(charOffsetHeader);
			m_pw->print(charOffset);
		}

		m_pw->print(locationClose);

		m_pw->println();
	}
}
<commit_msg>Removed bogus destructor code.<commit_after>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 1999 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xalan" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */
/**
 *
 * @author David N. Bertoni (david_n_bertoni@lotus.com)
 * */

// Base class header file.
#include "ProblemListenerDefault.hpp"

#include <XalanDOM/XalanNode.hpp>

#include <PlatformSupport/DOMStringHelper.hpp>
#include <PlatformSupport/PrintWriter.hpp>

#include <XSLT/ElemTemplateElement.hpp>

static const char* const	errorHeader = "error: ";
static const char* const	warningHeader = "warning: ";

static const char* const	xslHeader = "XSLT ";
static const char* const	xmlHeader = "XML ";
static const char* const	xpathHeader = "XPath ";

static const char* const	styleTreeNodeHeader = ", style tree node: ";
static const char* const	sourceTreeNodeHeader = ", source tree node: ";
static const char* const	locationOpen = " (";
static const char* const	uriHeader = "";
static const char* const	lineNoHeader = ", line ";
static const char* const	charOffsetHeader = ", column ";
static const char* const	locationClose = ")";

ProblemListenerDefault::ProblemListenerDefault(PrintWriter*		pw) :
	ProblemListener(),
	m_pw(pw)
{
}

ProblemListenerDefault::~ProblemListenerDefault()
{
}

void
ProblemListenerDefault::setPrintWriter(PrintWriter*		pw)
{
	m_pw = pw;
}

void
ProblemListenerDefault::problem(
			eProblemSource			where,
			eClassification			classification,
			const XalanNode*		sourceNode,
			const XalanNode*		styleNode,
			const XalanDOMString&	msg,
			const XalanDOMChar*		uri,
			int						lineNo,
			int						charOffset)
{
	if (m_pw != 0)
	{
		if (eXMLPARSER == where)
		{
			m_pw->print(xmlHeader);
		}
		else if (eXPATH == where)
		{
			m_pw->print(xpathHeader);
		}
		else
		{
			m_pw->print(xslHeader);
		}

		if (eERROR == classification)
		{
			m_pw->print(errorHeader);
		}
		else
		{
			m_pw->print(warningHeader);
		}

		m_pw->print(msg);

		if (0 != styleNode)
		{
			m_pw->print(styleTreeNodeHeader);
			m_pw->print(styleNode->getNodeName());
		}

		if (0 != sourceNode)
		{
			m_pw->print(sourceTreeNodeHeader);
			m_pw->print(sourceNode->getNodeName());
		}

		m_pw->print(locationOpen);

		if (0 != uri)
		{
			m_pw->print(uriHeader);
			m_pw->print(uri);
		}

		if (0 != lineNo)
		{
			m_pw->print(lineNoHeader);
			m_pw->print(lineNo);
		}

		if (0 != charOffset)
		{
			m_pw->print(charOffsetHeader);
			m_pw->print(charOffset);
		}

		m_pw->print(locationClose);

		m_pw->println();
	}
}
<|endoftext|>


<commit_before>#include "KinectStreamer.hpp"
#include <libfreenect2/libfreenect2.hpp>
#include <libfreenect2/frame_listener_impl.h>
#include <libfreenect2/registration.h>
#include "FAST/Data/Image.hpp"
#include "FAST/Data/Mesh.hpp"

namespace fast {

bool KinectStreamer::mInitialized = false;
std::stack<std::string> KinectStreamer::mAvailableDevices;

KinectStreamer::KinectStreamer() {
    createOutputPort<Image>(0); // RGB
    createOutputPort<Image>(1); // Depth image
    createOutputPort<Mesh>(2); // Point cloud
    mNrOfFrames = 0;
    mHasReachedEnd = false;
    mFirstFrameIsInserted = false;
    mStreamIsStarted = false;
    mIsModified = true;
    mPointCloudFilterEnabled = false;
    registration = NULL;
}

void KinectStreamer::setPointCloudFiltering(bool enabled) {
    mPointCloudFilterEnabled = enabled;
}

void KinectStreamer::execute() {
    if(!mStreamIsStarted) {
        // Check that first frame exists before starting streamer

        mStreamIsStarted = true;
        mStop = false;
        mThread = new std::thread(std::bind(&KinectStreamer::producerStream, this));
    }

    // Wait here for first frame
    std::unique_lock<std::mutex> lock(mFirstFrameMutex);
    while(!mFirstFrameIsInserted) {
        mFirstFrameCondition.wait(lock);
    }
}

MeshVertex KinectStreamer::getPoint(int x, int y) {
    float x2, y2, z2, rgb;
    Color color;
    if(registration != NULL) {
        registration->getPointXYZRGB(mUndistorted, mRegistered, y, x, x2, y2, z2, rgb);
        const uint8_t *p = reinterpret_cast<uint8_t*>(&rgb);
        uint8_t red = p[0];
        uint8_t green = p[1];
        uint8_t blue = p[2];
        color = Color(red/255.0f, green/255.0f, blue/255.0f);
    } else {
        throw Exception();
    }

    MeshVertex vertex(Vector3f(x2*1000, y2*1000, z2*1000));
    vertex.setColor(color);
    return vertex;
}

void KinectStreamer::producerStream() {
    reportInfo() << "Trying to set up kinect stream..." << reportEnd();
    libfreenect2::Freenect2 freenect2;
    libfreenect2::Freenect2Device *dev = 0;
    libfreenect2::PacketPipeline *pipeline = 0;
    std::string serial = "";

    int nrOfDevices = freenect2.enumerateDevices();
    if(nrOfDevices == 0) {
        throw Exception("Unable to find any Kinect devices");
    }
    if(!mInitialized) {
        for(int i = 0; i < nrOfDevices; ++i) {
            mAvailableDevices.push(freenect2.getDeviceSerialNumber(i));
        }
        mInitialized = true;
    }
    if(mAvailableDevices.empty()) {
        throw Exception("No more available kinect devices for KinectStreamer");
    } else {
        // Select first
        serial = mAvailableDevices.top();
        mAvailableDevices.pop();
    }

    reportInfo() << "Using kinect device with serial: " << serial << reportEnd();
    pipeline = new libfreenect2::OpenGLPacketPipeline();
    dev = freenect2.openDevice(serial, pipeline);

    int types = libfreenect2::Frame::Color | libfreenect2::Frame::Ir | libfreenect2::Frame::Depth;
    libfreenect2::SyncMultiFrameListener listener(types);
    libfreenect2::FrameMap frames;
    dev->setColorFrameListener(&listener);
    dev->setIrAndDepthFrameListener(&listener);

    if(!dev->start())
        throw Exception("Failed to start Kinect device streaming");

    reportInfo() << "Kinect device serial: " << dev->getSerialNumber() << reportEnd();
    reportInfo() << "Kinect device firmware: " << dev->getFirmwareVersion() << reportEnd();

    registration = new libfreenect2::Registration(dev->getIrCameraParams(),
                                                                              dev->getColorCameraParams());
    libfreenect2::Frame undistorted(512, 424, 4), registered(512, 424, 4);

    while(true) {
        {
            // Check if stop signal is sent
            std::unique_lock<std::mutex> lock(mStopMutex);
            if(mStop) {
                mStreamIsStarted = false;
                mFirstFrameIsInserted = false;
                mHasReachedEnd = false;
                break;
            }
        }
        if(!listener.waitForNewFrame(frames, 10 * 1000)) { // 10 seconds
            throw Exception("Kinect streaming timeout");
        }
        libfreenect2::Frame *rgb = frames[libfreenect2::Frame::Color];
        libfreenect2::Frame *ir = frames[libfreenect2::Frame::Ir];
        libfreenect2::Frame *depth = frames[libfreenect2::Frame::Depth];

        registration->apply(rgb, depth, &undistorted, &registered);
        mUndistorted = &undistorted;
        mRegistered = &registered;

        auto * depth_data = (float*)undistorted.data;
        auto * rgb_data = (unsigned char*)registered.data;

        Image::pointer depthImage = Image::New();
        depthImage->create(512, 424, TYPE_FLOAT, 1, depth_data);

        if(rgb->format == libfreenect2::Frame::Format::BGRX) {
            // Have to swap B and R channel
            for(int i = 0; i < 512*424; ++i) {
                uchar blue = rgb_data[i*4];
                rgb_data[i*4] = rgb_data[i*4+2];
                rgb_data[i*4+2] = blue;
            }
        }

        auto rgbImage = Image::New();
        rgbImage->create(512, 424, TYPE_UINT8, 4, rgb_data);
        auto imageAccess = rgbImage->getImageAccess(ACCESS_READ_WRITE);
        uchar* rgb_data2 = (uchar*)imageAccess->get();
        auto depthAccess = depthImage->getImageAccess(ACCESS_READ_WRITE);
        float* depth_data2 = (float*)depthAccess->get();

        // Create point cloud
        std::vector<MeshVertex> points;
        for(int r=0; r<424; ++r) { // y
            for(int c = 0; c < 512; ++c) { // x
                // Flip image horizontally
                if(c < 512/2) {
                    for(uchar i = 0; i < 3; i++) {
                        std::swap(rgb_data2[(c + r * 512) * 4 + i], rgb_data2[(512 - c - 1 + r * 512) * 4 + i]);
                    }
                    std::swap(depth_data2[(c + r * 512)], depth_data2[(512 - c - 1 + r * 512)]);
                }
                float x, y, z, color;
                registration->getPointXYZRGB(&undistorted, &registered, r, c, x, y, z, color);
                if(z < mMinRange || z > mMaxRange) {
                    continue;
                }
                if(!std::isnan(x)) {
                    // for each valid neigbhor; is the depth similar
                    if(mPointCloudFilterEnabled) {
                        int invalidNeighbors = 0;
                        const int size = 1;
                        for(int a = -size; a <= size; ++a) {
                            for(int b = -size; b <= size; ++b) {
                                if(r + a < 0 || r + a >= 424 || c + b < 0 || c + b >= 512)
                                    continue;
                                float x2, y2, z2, color2;
                                registration->getPointXYZRGB(&undistorted, &registered, r + a, c + b, x2, y2, z2,
                                                             color2);
                                if(std::isnan(x2))
                                    invalidNeighbors++;
                                if(fabs(z - z2) * 1000 > 10)
                                    invalidNeighbors++;

                            }
                        }
                        if (invalidNeighbors > 0)
                            continue;
                    }

                    // Decode color channels
                    const uint8_t *p = reinterpret_cast<uint8_t*>(&color);
                    uint8_t red = p[0];
                    uint8_t green = p[1];
                    uint8_t blue = p[2];
                    MeshVertex point(Vector3f(-x*1000, y*1000, z*1000)); // Flip x
                    point.setColor(Color(red/255.0f, green/255.0f, blue/255.0f));
                    points.push_back(point);
                }
            }
        }
        auto cloud = Mesh::New();
        cloud->create(points);
        imageAccess->release();
        depthAccess->release();

        addOutputData(0, rgbImage);
        addOutputData(1, depthImage);
        addOutputData(2, cloud);
        if(!mFirstFrameIsInserted) {
            {
                std::lock_guard<std::mutex> lock(mFirstFrameMutex);
                mFirstFrameIsInserted = true;
            }
            mFirstFrameCondition.notify_one();
        }
        mNrOfFrames++;
        listener.release(frames);
    }

    dev->stop();
    dev->close();
    delete dev;
    reportInfo() << "Kinect streamer stopped" << Reporter::end();
    mAvailableDevices.push(serial); // Adding streamer back to queue
}

bool KinectStreamer::hasReachedEnd() {
    return mHasReachedEnd;
}

uint KinectStreamer::getNrOfFrames() const {
    return mNrOfFrames;
}

KinectStreamer::~KinectStreamer() {
    if(mStreamIsStarted) {
        stop();
        mThread->join();
    }
}

void KinectStreamer::stop() {
    std::unique_lock<std::mutex> lock(mStopMutex);
    reportInfo() << "Stopping kinect streamer" << Reporter::end();
    mStop = true;
}

void KinectStreamer::setMaxRange(float range) {
    if(range < 0)
        throw Exception("Range has to be >= 0");
    mMaxRange = range;
}

void KinectStreamer::setMinRange(float range) {
    if(range < 0)
        throw Exception("Range has to be >= 0");
    mMinRange = range;
}

}<commit_msg>fixed KinectStreamer::getPoint due to flipping<commit_after>#include "KinectStreamer.hpp"
#include <libfreenect2/libfreenect2.hpp>
#include <libfreenect2/frame_listener_impl.h>
#include <libfreenect2/registration.h>
#include "FAST/Data/Image.hpp"
#include "FAST/Data/Mesh.hpp"

namespace fast {

bool KinectStreamer::mInitialized = false;
std::stack<std::string> KinectStreamer::mAvailableDevices;

KinectStreamer::KinectStreamer() {
    createOutputPort<Image>(0); // RGB
    createOutputPort<Image>(1); // Depth image
    createOutputPort<Mesh>(2); // Point cloud
    mNrOfFrames = 0;
    mHasReachedEnd = false;
    mFirstFrameIsInserted = false;
    mStreamIsStarted = false;
    mIsModified = true;
    mPointCloudFilterEnabled = false;
    registration = NULL;
}

void KinectStreamer::setPointCloudFiltering(bool enabled) {
    mPointCloudFilterEnabled = enabled;
}

void KinectStreamer::execute() {
    if(!mStreamIsStarted) {
        // Check that first frame exists before starting streamer

        mStreamIsStarted = true;
        mStop = false;
        mThread = new std::thread(std::bind(&KinectStreamer::producerStream, this));
    }

    // Wait here for first frame
    std::unique_lock<std::mutex> lock(mFirstFrameMutex);
    while(!mFirstFrameIsInserted) {
        mFirstFrameCondition.wait(lock);
    }
}

MeshVertex KinectStreamer::getPoint(int x, int y) {
    float x2, y2, z2, rgb;
    Color color;
    if(registration != NULL) {
        registration->getPointXYZRGB(mUndistorted, mRegistered, y, 512-x-1, x2, y2, z2, rgb);
        const uint8_t *p = reinterpret_cast<uint8_t*>(&rgb);
        uint8_t red = p[0];
        uint8_t green = p[1];
        uint8_t blue = p[2];
        color = Color(red/255.0f, green/255.0f, blue/255.0f);
    } else {
        throw Exception();
    }

    MeshVertex vertex(Vector3f(-x2*1000, y2*1000, z2*1000));
    vertex.setColor(color);
    return vertex;
}

void KinectStreamer::producerStream() {
    reportInfo() << "Trying to set up kinect stream..." << reportEnd();
    libfreenect2::Freenect2 freenect2;
    libfreenect2::Freenect2Device *dev = 0;
    libfreenect2::PacketPipeline *pipeline = 0;
    std::string serial = "";

    int nrOfDevices = freenect2.enumerateDevices();
    if(nrOfDevices == 0) {
        throw Exception("Unable to find any Kinect devices");
    }
    if(!mInitialized) {
        for(int i = 0; i < nrOfDevices; ++i) {
            mAvailableDevices.push(freenect2.getDeviceSerialNumber(i));
        }
        mInitialized = true;
    }
    if(mAvailableDevices.empty()) {
        throw Exception("No more available kinect devices for KinectStreamer");
    } else {
        // Select first
        serial = mAvailableDevices.top();
        mAvailableDevices.pop();
    }

    reportInfo() << "Using kinect device with serial: " << serial << reportEnd();
    pipeline = new libfreenect2::OpenGLPacketPipeline();
    dev = freenect2.openDevice(serial, pipeline);

    int types = libfreenect2::Frame::Color | libfreenect2::Frame::Ir | libfreenect2::Frame::Depth;
    libfreenect2::SyncMultiFrameListener listener(types);
    libfreenect2::FrameMap frames;
    dev->setColorFrameListener(&listener);
    dev->setIrAndDepthFrameListener(&listener);

    if(!dev->start())
        throw Exception("Failed to start Kinect device streaming");

    reportInfo() << "Kinect device serial: " << dev->getSerialNumber() << reportEnd();
    reportInfo() << "Kinect device firmware: " << dev->getFirmwareVersion() << reportEnd();

    registration = new libfreenect2::Registration(dev->getIrCameraParams(),
                                                                              dev->getColorCameraParams());
    libfreenect2::Frame undistorted(512, 424, 4), registered(512, 424, 4);

    while(true) {
        {
            // Check if stop signal is sent
            std::unique_lock<std::mutex> lock(mStopMutex);
            if(mStop) {
                mStreamIsStarted = false;
                mFirstFrameIsInserted = false;
                mHasReachedEnd = false;
                break;
            }
        }
        if(!listener.waitForNewFrame(frames, 10 * 1000)) { // 10 seconds
            throw Exception("Kinect streaming timeout");
        }
        libfreenect2::Frame *rgb = frames[libfreenect2::Frame::Color];
        libfreenect2::Frame *ir = frames[libfreenect2::Frame::Ir];
        libfreenect2::Frame *depth = frames[libfreenect2::Frame::Depth];

        registration->apply(rgb, depth, &undistorted, &registered);
        mUndistorted = &undistorted;
        mRegistered = &registered;

        auto * depth_data = (float*)undistorted.data;
        auto * rgb_data = (unsigned char*)registered.data;

        Image::pointer depthImage = Image::New();
        depthImage->create(512, 424, TYPE_FLOAT, 1, depth_data);

        if(rgb->format == libfreenect2::Frame::Format::BGRX) {
            // Have to swap B and R channel
            for(int i = 0; i < 512*424; ++i) {
                uchar blue = rgb_data[i*4];
                rgb_data[i*4] = rgb_data[i*4+2];
                rgb_data[i*4+2] = blue;
            }
        }

        auto rgbImage = Image::New();
        rgbImage->create(512, 424, TYPE_UINT8, 4, rgb_data);
        auto imageAccess = rgbImage->getImageAccess(ACCESS_READ_WRITE);
        uchar* rgb_data2 = (uchar*)imageAccess->get();
        auto depthAccess = depthImage->getImageAccess(ACCESS_READ_WRITE);
        float* depth_data2 = (float*)depthAccess->get();

        // Create point cloud
        std::vector<MeshVertex> points;
        for(int r=0; r<424; ++r) { // y
            for(int c = 0; c < 512; ++c) { // x
                // Flip image horizontally
                if(c < 512/2) {
                    for(uchar i = 0; i < 3; i++) {
                        std::swap(rgb_data2[(c + r * 512) * 4 + i], rgb_data2[(512 - c - 1 + r * 512) * 4 + i]);
                    }
                    std::swap(depth_data2[(c + r * 512)], depth_data2[(512 - c - 1 + r * 512)]);
                }
                float x, y, z, color;
                registration->getPointXYZRGB(&undistorted, &registered, r, c, x, y, z, color);
                if(z < mMinRange || z > mMaxRange) {
                    continue;
                }
                if(!std::isnan(x)) {
                    // for each valid neigbhor; is the depth similar
                    if(mPointCloudFilterEnabled) {
                        int invalidNeighbors = 0;
                        const int size = 1;
                        for(int a = -size; a <= size; ++a) {
                            for(int b = -size; b <= size; ++b) {
                                if(r + a < 0 || r + a >= 424 || c + b < 0 || c + b >= 512)
                                    continue;
                                float x2, y2, z2, color2;
                                registration->getPointXYZRGB(&undistorted, &registered, r + a, c + b, x2, y2, z2,
                                                             color2);
                                if(std::isnan(x2))
                                    invalidNeighbors++;
                                if(fabs(z - z2) * 1000 > 10)
                                    invalidNeighbors++;

                            }
                        }
                        if (invalidNeighbors > 0)
                            continue;
                    }

                    // Decode color channels
                    const uint8_t *p = reinterpret_cast<uint8_t*>(&color);
                    uint8_t red = p[0];
                    uint8_t green = p[1];
                    uint8_t blue = p[2];
                    MeshVertex point(Vector3f(-x*1000, y*1000, z*1000)); // Flip x
                    point.setColor(Color(red/255.0f, green/255.0f, blue/255.0f));
                    points.push_back(point);
                }
            }
        }
        auto cloud = Mesh::New();
        cloud->create(points);
        imageAccess->release();
        depthAccess->release();

        addOutputData(0, rgbImage);
        addOutputData(1, depthImage);
        addOutputData(2, cloud);
        if(!mFirstFrameIsInserted) {
            {
                std::lock_guard<std::mutex> lock(mFirstFrameMutex);
                mFirstFrameIsInserted = true;
            }
            mFirstFrameCondition.notify_one();
        }
        mNrOfFrames++;
        listener.release(frames);
    }

    dev->stop();
    dev->close();
    delete dev;
    reportInfo() << "Kinect streamer stopped" << Reporter::end();
    mAvailableDevices.push(serial); // Adding streamer back to queue
}

bool KinectStreamer::hasReachedEnd() {
    return mHasReachedEnd;
}

uint KinectStreamer::getNrOfFrames() const {
    return mNrOfFrames;
}

KinectStreamer::~KinectStreamer() {
    if(mStreamIsStarted) {
        stop();
        mThread->join();
    }
}

void KinectStreamer::stop() {
    std::unique_lock<std::mutex> lock(mStopMutex);
    reportInfo() << "Stopping kinect streamer" << Reporter::end();
    mStop = true;
}

void KinectStreamer::setMaxRange(float range) {
    if(range < 0)
        throw Exception("Range has to be >= 0");
    mMaxRange = range;
}

void KinectStreamer::setMinRange(float range) {
    if(range < 0)
        throw Exception("Range has to be >= 0");
    mMinRange = range;
}

}<|endoftext|>


<commit_before>#include "compiler/build_tables/build_parse_table.h"
#include <string>
#include <utility>
#include <map>
#include <set>
#include <unordered_map>
#include "compiler/prepared_grammar.h"
#include "compiler/rules/built_in_symbols.h"
#include "compiler/rules/symbol.h"
#include "compiler/build_tables/parse_conflict_manager.h"
#include "compiler/build_tables/parse_item.h"
#include "compiler/build_tables/item_set_closure.h"
#include "compiler/build_tables/item_set_transitions.h"

namespace tree_sitter {
    using std::pair;
    using std::string;
    using std::vector;
    using std::set;
    using std::unordered_map;
    using std::make_shared;
    using rules::Symbol;

    namespace build_tables {
        class ParseTableBuilder {
            const PreparedGrammar grammar;
            ParseConflictManager conflict_manager;
            unordered_map<const ParseItemSet, ParseStateId> parse_state_ids;
            SymTransitions sym_transitions;
            ParseTable parse_table;

            ParseStateId add_parse_state(const ParseItemSet &item_set) {
                auto pair = parse_state_ids.find(item_set);
                if (pair == parse_state_ids.end()) {
                    ParseStateId state_id = parse_table.add_state();
                    parse_state_ids[item_set] = state_id;
                    add_shift_actions(item_set, state_id);
                    add_reduce_actions(item_set, state_id);
                    return state_id;
                } else {
                    return pair->second;
                }
            }

            void add_shift_actions(const ParseItemSet &item_set, ParseStateId state_id) {
                for (const auto &transition : sym_transitions(item_set, grammar)) {
                    const Symbol &symbol = transition.first;
                    const ParseItemSet &item_set = transition.second;
                    auto &actions = parse_table.states[state_id].actions;
                    auto current_action = actions.find(symbol);

                    set<int> precedence_values = precedence_values_for_item_set(item_set);
                    if (current_action == actions.end() ||
                        conflict_manager.resolve_parse_action(symbol, current_action->second, ParseAction::Shift(0, precedence_values))) {
                        ParseStateId new_state_id = add_parse_state(item_set);
                        parse_table.add_action(state_id, symbol, ParseAction::Shift(new_state_id, precedence_values));
                    }
                }

                for (const Symbol &symbol : grammar.options.ubiquitous_tokens) {
                    auto &actions = parse_table.states[state_id].actions;
                    if (actions.find(symbol) == actions.end())
                        parse_table.add_action(state_id, symbol, ParseAction::Shift(state_id, { 0 }));
                }
            }

            void add_reduce_actions(const ParseItemSet &item_set, ParseStateId state_id) {
                for (const ParseItem &item : item_set) {
                    if (item.is_done()) {
                        ParseAction action = (item.lhs == rules::START()) ?
                            ParseAction::Accept() :
                            ParseAction::Reduce(item.lhs, item.consumed_symbol_count, item.precedence());
                        auto current_actions = parse_table.states[state_id].actions;
                        auto current_action = current_actions.find(item.lookahead_sym);

                        if (current_action == current_actions.end() ||
                            conflict_manager.resolve_parse_action(item.lookahead_sym, current_action->second, action)) {
                            parse_table.add_action(state_id, item.lookahead_sym, action);
                        }
                    }
                }
            }

            set<int> precedence_values_for_item_set(const ParseItemSet &item_set) {
                set<int> result;
                for (const auto &item : item_set)
                    if (item.consumed_symbol_count > 0)
                        result.insert(item.precedence());
                return result;
            }

        public:
            ParseTableBuilder(const PreparedGrammar &grammar, const PreparedGrammar &lex_grammar) :
                grammar(grammar),
                conflict_manager(ParseConflictManager(grammar, lex_grammar)) {}

            pair<ParseTable, vector<Conflict>> build() {
                ParseItem start_item(rules::START(), make_shared<Symbol>(0), 0, rules::END_OF_INPUT());
                add_parse_state(item_set_closure(start_item, grammar));
                return { parse_table, conflict_manager.conflicts() };
            }
        };

        pair<ParseTable, vector<Conflict>>
        build_parse_table(const PreparedGrammar &grammar, const PreparedGrammar &lex_grammar) {
            return ParseTableBuilder(grammar, lex_grammar).build();
        }
    }
}
<commit_msg>Cleanup - extract method in parse table builder<commit_after>#include "compiler/build_tables/build_parse_table.h"
#include <string>
#include <utility>
#include <map>
#include <set>
#include <unordered_map>
#include "compiler/prepared_grammar.h"
#include "compiler/rules/built_in_symbols.h"
#include "compiler/rules/symbol.h"
#include "compiler/build_tables/parse_conflict_manager.h"
#include "compiler/build_tables/parse_item.h"
#include "compiler/build_tables/item_set_closure.h"
#include "compiler/build_tables/item_set_transitions.h"

namespace tree_sitter {
    using std::pair;
    using std::string;
    using std::vector;
    using std::set;
    using std::unordered_map;
    using std::make_shared;
    using rules::Symbol;

    namespace build_tables {
        class ParseTableBuilder {
            const PreparedGrammar grammar;
            ParseConflictManager conflict_manager;
            unordered_map<const ParseItemSet, ParseStateId> parse_state_ids;
            SymTransitions sym_transitions;
            ParseTable parse_table;

            ParseStateId add_parse_state(const ParseItemSet &item_set) {
                auto pair = parse_state_ids.find(item_set);
                if (pair == parse_state_ids.end()) {
                    ParseStateId state_id = parse_table.add_state();
                    parse_state_ids[item_set] = state_id;
                    add_shift_actions(item_set, state_id);
                    add_ubiquitous_token_actions(item_set, state_id);
                    add_reduce_actions(item_set, state_id);
                    return state_id;
                } else {
                    return pair->second;
                }
            }

            void add_shift_actions(const ParseItemSet &item_set, ParseStateId state_id) {
                for (const auto &transition : sym_transitions(item_set, grammar)) {
                    const Symbol &symbol = transition.first;
                    const ParseItemSet &item_set = transition.second;
                    auto &actions = parse_table.states[state_id].actions;
                    auto current_action = actions.find(symbol);

                    set<int> precedence_values = precedence_values_for_item_set(item_set);
                    if (current_action == actions.end() ||
                        conflict_manager.resolve_parse_action(symbol, current_action->second, ParseAction::Shift(0, precedence_values))) {
                        ParseStateId new_state_id = add_parse_state(item_set);
                        parse_table.add_action(state_id, symbol, ParseAction::Shift(new_state_id, precedence_values));
                    }
                }
            }

            void add_ubiquitous_token_actions(const ParseItemSet &item_set, ParseStateId state_id) {
                for (const Symbol &symbol : grammar.options.ubiquitous_tokens) {
                    auto &actions = parse_table.states[state_id].actions;
                    if (actions.find(symbol) == actions.end())
                        parse_table.add_action(state_id, symbol, ParseAction::Shift(state_id, { 0 }));
                }
            }

            void add_reduce_actions(const ParseItemSet &item_set, ParseStateId state_id) {
                for (const ParseItem &item : item_set) {
                    if (item.is_done()) {
                        ParseAction action = (item.lhs == rules::START()) ?
                            ParseAction::Accept() :
                            ParseAction::Reduce(item.lhs, item.consumed_symbol_count, item.precedence());
                        auto current_actions = parse_table.states[state_id].actions;
                        auto current_action = current_actions.find(item.lookahead_sym);

                        if (current_action == current_actions.end() ||
                            conflict_manager.resolve_parse_action(item.lookahead_sym, current_action->second, action)) {
                            parse_table.add_action(state_id, item.lookahead_sym, action);
                        }
                    }
                }
            }

            set<int> precedence_values_for_item_set(const ParseItemSet &item_set) {
                set<int> result;
                for (const auto &item : item_set)
                    if (item.consumed_symbol_count > 0)
                        result.insert(item.precedence());
                return result;
            }

        public:
            ParseTableBuilder(const PreparedGrammar &grammar, const PreparedGrammar &lex_grammar) :
                grammar(grammar),
                conflict_manager(ParseConflictManager(grammar, lex_grammar)) {}

            pair<ParseTable, vector<Conflict>> build() {
                ParseItem start_item(rules::START(), make_shared<Symbol>(0), 0, rules::END_OF_INPUT());
                add_parse_state(item_set_closure(start_item, grammar));
                return { parse_table, conflict_manager.conflicts() };
            }
        };

        pair<ParseTable, vector<Conflict>>
        build_parse_table(const PreparedGrammar &grammar, const PreparedGrammar &lex_grammar) {
            return ParseTableBuilder(grammar, lex_grammar).build();
        }
    }
}
<|endoftext|>


<commit_before>#include "autocomplete_api.h"
#include "type/pb_converter.h"
#include <boost/foreach.hpp>

namespace navitia { namespace autocomplete {
/**
 * se charge de remplir l'objet protocolbuffer autocomplete passé en paramètre
 *
 */
void create_pb(const std::vector<Autocomplete<nt::idx_t>::fl_quality>& result,
               const nt::Type_e type, uint32_t depth, const nt::Data& data,
               pbnavitia::Autocomplete& pb_fl){
    for(auto result_item : result){
        pbnavitia::AutocompleteItem* item = pb_fl.add_items();
        pbnavitia::PlaceMark* place_mark = item->mutable_object();
        switch(type){
        case nt::Type_e::StopArea:
            place_mark->set_type(pbnavitia::STOP_AREA);
            fill_pb_object(result_item.idx, data, place_mark->mutable_stop_area(), depth);
            item->set_name(data.pt_data.stop_areas[result_item.idx].name);
            item->set_uri(data.pt_data.stop_areas[result_item.idx].uri);
            item->set_quality(result_item.quality);
            break;
        case nt::Type_e::City:
            place_mark->set_type(pbnavitia::CITY);
            fill_pb_object(result_item.idx, data, place_mark->mutable_city(), depth);
            item->set_name(data.pt_data.cities[result_item.idx].name);
            item->set_uri(data.pt_data.cities[result_item.idx].uri);
            item->set_quality(result_item.quality);
            break;
        case nt::Type_e::StopPoint:
            place_mark->set_type(pbnavitia::STOP_POINT);
            fill_pb_object(result_item.idx, data, place_mark->mutable_stop_point(), depth);
            item->set_name(data.pt_data.stop_points[result_item.idx].name);
            item->set_uri(data.pt_data.stop_points[result_item.idx].uri);
            item->set_quality(result_item.quality);
            break;
        case nt::Type_e::Address:
            place_mark->set_type(pbnavitia::ADDRESS);
            //fill_pb_object(result_item.idx, data, place_mark->mutable_way(), 2);
            fill_pb_object(result_item.idx, data, place_mark->mutable_address(), result_item.house_number,result_item.coord, depth);
            item->set_name(data.geo_ref.ways[result_item.idx].name);
            item->set_uri(data.geo_ref.ways[result_item.idx].uri+":"+boost::lexical_cast<std::string>(result_item.house_number));
            item->set_quality(result_item.quality);
            break;
        case nt::Type_e::POI:
            place_mark->set_type(pbnavitia::POI);
            fill_pb_object(result_item.idx, data, place_mark->mutable_poi(), 2);
            item->set_name(data.geo_ref.pois[result_item.idx].name);
            item->set_uri(data.geo_ref.pois[result_item.idx].uri);
            item->set_quality(result_item.quality);
            break;
        default:
            break;
        }
    }
}

int penalty_by_type(navitia::type::Type_e ntype, bool Is_address_type) {
    // Ordre de tri :
    // Add, SA, POI, SP, City : si présence de addressType dans le recherche
    // City, SA, POI, Add, SP : si non
    int result = 0;
    switch(ntype){
    case navitia::type::Type_e::City:
        result = Is_address_type ? 8 : 0;
        break;
    case navitia::type::Type_e::StopArea:
        result = 2;
        break;
    case navitia::type::Type_e::POI:
        result = 4;
        break;
    case navitia::type::Type_e::Address:
        result = Is_address_type ? 0 : 6;
        break;
    case navitia::type::Type_e::StopPoint:
        result = 8;
        result = Is_address_type ? 6 : 8;
        break;
    default:
        break;
    }
    return result;
}

void Update_quality(std::vector<Autocomplete<nt::idx_t>::fl_quality>& ac_result, navitia::type::Type_e ntype, bool Is_address_type){
    //Mettre à jour la qualité sur la pénalité par type
    int penalty = penalty_by_type(ntype, Is_address_type);
    for(auto &item : ac_result){
        item.quality -= penalty;
    }
}

pbnavitia::Response autocomplete(const std::string &name,
                                 const std::vector<nt::Type_e> &filter,
                                 uint32_t depth,
                                 uint32_t nbmax,
                                 const navitia::type::Data &d){

    pbnavitia::Response pb_response;
    pb_response.set_requested_api(pbnavitia::AUTOCOMPLETE);

    bool addType = d.pt_data.stop_area_autocomplete.is_address_type(name, d.geo_ref.alias, d.geo_ref.synonymes);
    std::vector<Autocomplete<nt::idx_t>::fl_quality> result;
    pbnavitia::Autocomplete* pb = pb_response.mutable_autocomplete();
    BOOST_FOREACH(nt::Type_e type, filter){
        switch(type){
        case nt::Type_e::StopArea:
            result = d.pt_data.stop_area_autocomplete.find_complete(name, d.geo_ref.alias, d.geo_ref.synonymes, d.geo_ref.word_weight);
            break;
        case nt::Type_e::StopPoint:
            result = d.pt_data.stop_point_autocomplete.find_complete(name, d.geo_ref.alias, d.geo_ref.synonymes, d.geo_ref.word_weight);
            break;
        case nt::Type_e::City:
            result = d.pt_data.city_autocomplete.find_complete(name, d.geo_ref.alias, d.geo_ref.synonymes, d.geo_ref.word_weight);
            break;
        case nt::Type_e::Address:
            //result = d.geo_ref.fl.find_complete(name);
            result = d.geo_ref.find_ways(name);
            break;
        case nt::Type_e::POI:
            result = d.geo_ref.fl_poi.find_complete(name, d.geo_ref.alias, d.geo_ref.synonymes, d.geo_ref.word_weight);
        default: break;
        }

        if (result.size() > nbmax){result.resize(nbmax);}
        Update_quality(result, type, addType);

        create_pb(result, type, depth, d, *pb);
    }
    return pb_response;
}

}} //namespace navitia::autocomplete
<commit_msg>Autocompletion : retrier la liste de réponse limiter sa taille.<commit_after>#include "autocomplete_api.h"
#include "type/pb_converter.h"
#include <boost/foreach.hpp>

namespace navitia { namespace autocomplete {
/**
 * se charge de remplir l'objet protocolbuffer autocomplete passé en paramètre
 *
 */
void create_pb(const std::vector<Autocomplete<nt::idx_t>::fl_quality>& result,
               const nt::Type_e type, uint32_t depth, const nt::Data& data,
               pbnavitia::Autocomplete& pb_fl){
    for(auto result_item : result){
        pbnavitia::AutocompleteItem* item = pb_fl.add_items();
        pbnavitia::PlaceMark* place_mark = item->mutable_object();
        switch(type){
        case nt::Type_e::StopArea:
            place_mark->set_type(pbnavitia::STOP_AREA);
            fill_pb_object(result_item.idx, data, place_mark->mutable_stop_area(), depth);
            item->set_name(data.pt_data.stop_areas[result_item.idx].name);
            item->set_uri(data.pt_data.stop_areas[result_item.idx].uri);
            item->set_quality(result_item.quality);
            break;
        case nt::Type_e::City:
            place_mark->set_type(pbnavitia::CITY);
            fill_pb_object(result_item.idx, data, place_mark->mutable_city(), depth);
            item->set_name(data.pt_data.cities[result_item.idx].name);
            item->set_uri(data.pt_data.cities[result_item.idx].uri);
            item->set_quality(result_item.quality);
            break;
        case nt::Type_e::StopPoint:
            place_mark->set_type(pbnavitia::STOP_POINT);
            fill_pb_object(result_item.idx, data, place_mark->mutable_stop_point(), depth);
            item->set_name(data.pt_data.stop_points[result_item.idx].name);
            item->set_uri(data.pt_data.stop_points[result_item.idx].uri);
            item->set_quality(result_item.quality);
            break;
        case nt::Type_e::Address:
            place_mark->set_type(pbnavitia::ADDRESS);
            //fill_pb_object(result_item.idx, data, place_mark->mutable_way(), 2);
            fill_pb_object(result_item.idx, data, place_mark->mutable_address(), result_item.house_number,result_item.coord, depth);
            item->set_name(data.geo_ref.ways[result_item.idx].name);
            item->set_uri(data.geo_ref.ways[result_item.idx].uri+":"+boost::lexical_cast<std::string>(result_item.house_number));
            item->set_quality(result_item.quality);
            break;
        case nt::Type_e::POI:
            place_mark->set_type(pbnavitia::POI);
            fill_pb_object(result_item.idx, data, place_mark->mutable_poi(), 2);
            item->set_name(data.geo_ref.pois[result_item.idx].name);
            item->set_uri(data.geo_ref.pois[result_item.idx].uri);
            item->set_quality(result_item.quality);
            break;
        default:
            break;
        }
    }
}

int penalty_by_type(navitia::type::Type_e ntype, bool Is_address_type) {
    // Ordre de tri :
    // Add, SA, POI, SP, City : si présence de addressType dans le recherche
    // City, SA, POI, Add, SP : si non
    int result = 0;
    switch(ntype){
    case navitia::type::Type_e::City:
        result = Is_address_type ? 8 : 0;
        break;
    case navitia::type::Type_e::StopArea:
        result = 2;
        break;
    case navitia::type::Type_e::POI:
        result = 4;
        break;
    case navitia::type::Type_e::Address:
        result = Is_address_type ? 0 : 6;
        break;
    case navitia::type::Type_e::StopPoint:
        result = 8;
        result = Is_address_type ? 6 : 8;
        break;
    default:
        break;
    }
    return result;
}

void Update_quality(std::vector<Autocomplete<nt::idx_t>::fl_quality>& ac_result, navitia::type::Type_e ntype, bool Is_address_type){
    //Mettre à jour la qualité sur la pénalité par type
    int penalty = penalty_by_type(ntype, Is_address_type);
    for(auto &item : ac_result){
        item.quality -= penalty;
    }
}

pbnavitia::Response autocomplete(const std::string &name,
                                 const std::vector<nt::Type_e> &filter,
                                 uint32_t depth,
                                 uint32_t nbmax,
                                 const navitia::type::Data &d){

    pbnavitia::Response pb_response;
    pb_response.set_requested_api(pbnavitia::AUTOCOMPLETE);

    bool addType = d.pt_data.stop_area_autocomplete.is_address_type(name, d.geo_ref.alias, d.geo_ref.synonymes);
    std::vector<Autocomplete<nt::idx_t>::fl_quality> result;
    pbnavitia::Autocomplete* pb = pb_response.mutable_autocomplete();
    BOOST_FOREACH(nt::Type_e type, filter){
        switch(type){
        case nt::Type_e::StopArea:
            result = d.pt_data.stop_area_autocomplete.find_complete(name, d.geo_ref.alias, d.geo_ref.synonymes, d.geo_ref.word_weight);
            break;
        case nt::Type_e::StopPoint:
            result = d.pt_data.stop_point_autocomplete.find_complete(name, d.geo_ref.alias, d.geo_ref.synonymes, d.geo_ref.word_weight);
            break;
        case nt::Type_e::City:
            result = d.pt_data.city_autocomplete.find_complete(name, d.geo_ref.alias, d.geo_ref.synonymes, d.geo_ref.word_weight);
            break;
        case nt::Type_e::Address:
            //result = d.geo_ref.fl.find_complete(name);
            result = d.geo_ref.find_ways(name);
            break;
        case nt::Type_e::POI:
            result = d.geo_ref.fl_poi.find_complete(name, d.geo_ref.alias, d.geo_ref.synonymes, d.geo_ref.word_weight);
        default: break;
        }

        if (result.size() > nbmax){result.resize(nbmax);}
        Update_quality(result, type, addType);

        create_pb(result, type, depth, d, *pb);
    }

    auto compare = [](pbnavitia::AutocompleteItem a, pbnavitia::AutocompleteItem b){
            return a.quality() > b.quality();
    };

    std::sort(pb_response.mutable_autocomplete()->mutable_items()->begin(), pb_response.mutable_autocomplete()->mutable_items()->end(),compare);

    while (pb_response.mutable_autocomplete()->mutable_items()->size() > nbmax){
        pb_response.mutable_autocomplete()->mutable_items()->RemoveLast();
    }

    return pb_response;
}

}} //namespace navitia::autocomplete
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2007, 2008, 2009, 2010, Gostai S.A.S.
 *
 * This software is provided "as is" without warranty of any kind,
 * either expressed or implied, including but not limited to the
 * implied warranties of fitness for a particular purpose.
 *
 * See the LICENSE file for more information.
 */

/// \file urbi/uvalue.hh
#ifndef URBI_UVALUE_HH
# define URBI_UVALUE_HH

# include <libport/warning-push.hh>

# include <vector>

# include <libport/hash.hh>
# include <libport/traits.hh>
# include <libport/ufloat.h>

# include <urbi/fwd.hh>
# include <urbi/export.hh>
# include <urbi/ubinary.hh>

namespace urbi
{

  // UValue and other related types

  /// Possible value types a UValue can contain.
  enum UDataType
  {
    DATA_BINARY,
    DATA_DICTIONARY,
    DATA_DOUBLE,
    DATA_LIST,
    DATA_OBJECT,
    DATA_STRING,
    DATA_VOID
  };

  /*--------.
  | UList.  |
  `--------*/

  /// Class storing URBI List type
  class URBI_SDK_API UList
  {
  public:
    UList();
    UList(const UList &b);
    ~UList();

    UList& operator=(const UList &b);

    // Assign a container to the UList
    template<typename T>
    UList& operator=(const T& container);

    UList& operator=(UVar& v);

    // Transform the UList to a container.
    template<typename T>
    T as();

    // Append an element to the end.
    template<typename T>
    UList&
    push_back(const T& v);

    void pop_back();

    UValue& front();

    UValue& operator[](size_t i);
    const UValue& operator[](size_t i) const;

    size_t size() const;
    void setOffset(size_t n);

    std::ostream& print(std::ostream& o) const;

    // The actual contents.
    std::vector<UValue*> array;

  private:
    void clear();
    size_t offset;
  };

  URBI_SDK_API
  std::ostream& operator<< (std::ostream& o, const UList& t);

  /*--------------.
  | UDictionary.  |
  `--------------*/
  typedef boost::unordered_map<std::string, UValue> UDictionary;

  /*--------------.
  | UNamedValue.  |
  `--------------*/

  class URBI_SDK_API UNamedValue
  {
  public:
    UNamedValue(const std::string& n = "", UValue* v = 0);
    // Used on errors.
    static UNamedValue& error();
    std::string name;
    UValue* val;
  };

  /*----------------.
  | UObjectStruct.  |
  `----------------*/

  class URBI_SDK_API UObjectStruct
  {
  public:
    UObjectStruct();
    UObjectStruct(const UObjectStruct &b);
    UObjectStruct& operator=(const UObjectStruct &b);
    ~UObjectStruct();

    /// Return UValue::error() on errors.
    UValue& operator[](const std::string& s);

    /// Return UNamedValue::error() on errors.
    const UNamedValue& operator[](size_t i) const;
    UNamedValue& operator [](size_t i);

    size_t size() const;

    std::ostream& print(std::ostream& o) const;

    std::string refName;
    std::vector<UNamedValue> array;
  };

  URBI_SDK_API
  std::ostream& operator<< (std::ostream& o, const UObjectStruct& t);

  /*---------.
  | UValue.  |
  `---------*/

  /** Container for a value that handles all types known to URBI.
   */
  class URBI_SDK_API UValue
  {
  public:
    UDataType       type;
    ufloat          val;  ///< value if of type DATA_DOUBLE
    union
    {
      std::string* stringValue; ///< value if of type DATA_STRING
      UBinary* binary;          ///< value if of type DATA_BINARY
      UList* list;              ///< value if of type DATA_LIST
      UDictionary* dictionary;  ///< value if of type DATA_DICTIONARY
      UObjectStruct* object;    ///< value if of type DATA_OBJ
      void* storage;            ///< internal
    };

    UValue();
    UValue(const UValue&);

    ~UValue();

    UValue& operator=(const UValue&);
    /// Setter. If copy is false, binary data if present is not copied.
    /// This is dangerous, as the user must ensure that the source UValue
    /// lives longer than this one.
    UValue& set(const UValue&, bool copy=true);
    /// Delete content and reset type to void.
    void clear();
    /// A specific UValue used when we want to return an error.
    /// For instance, out-of-bound access returns this object.
    static UValue& error();

    /// We use an operator , that behaves like an assignment.  The
    /// only difference is when the rhs is void, in which case it is
    /// the regular comma which is used.  This allows to write "uval,
    /// expr" to mean "compute expr and assign its result to uval,
    /// unless expr is void".
    UValue& operator, (const UValue &b);

    /// Return a legible definition of UDataType
    const char* format_string() const;

#define CTOR_AND_ASSIGN_AND_COMMA(Type)		\
    explicit UValue(Type, bool copy=true);	\
    UValue& operator=(Type);			\
    UValue& operator,(Type rhs)

    // UFloats.
    CTOR_AND_ASSIGN_AND_COMMA(ufloat);
    CTOR_AND_ASSIGN_AND_COMMA(int);
    CTOR_AND_ASSIGN_AND_COMMA(long);
    CTOR_AND_ASSIGN_AND_COMMA(unsigned int);
    CTOR_AND_ASSIGN_AND_COMMA(unsigned long);

    // Strings.
    CTOR_AND_ASSIGN_AND_COMMA(const char*);
    CTOR_AND_ASSIGN_AND_COMMA(const void*);
    CTOR_AND_ASSIGN_AND_COMMA(const std::string&);

    // Others.
    CTOR_AND_ASSIGN_AND_COMMA(const UBinary&);
    CTOR_AND_ASSIGN_AND_COMMA(const UList&);
    CTOR_AND_ASSIGN_AND_COMMA(const UDictionary&);
    CTOR_AND_ASSIGN_AND_COMMA(const UObjectStruct&);
    CTOR_AND_ASSIGN_AND_COMMA(const USound&);
    CTOR_AND_ASSIGN_AND_COMMA(const UImage&);

#undef CTOR_AND_ASSIGN_AND_COMMA

    operator ufloat() const;
    operator std::string() const;
    operator int() const;
    operator unsigned int() const;
    operator long() const;
    operator unsigned long() const;
    operator bool() const;

    /// Accessor. Gives us an implicit operator UBinary() const
    operator const UBinary&() const;

    /// Deep copy.
    operator UList() const;

    /// Deep copy.
    operator UDictionary() const;

    /// Shallow copy.
    operator UImage() const;

    /// Shallow copy.
    operator USound() const;

    /// This operator does nothing, but helps with the previous operator,.
    /// Indeed, when writing "uval, void_expr", the compiler complains
    /// about uval being evaluated for nothing.  Let's have it believe
    /// we're doing something...
    UValue& operator()();

    /// Parse an uvalue in current message+pos, returns pos of end of
    /// match -pos of error if error.
    int parse(const char* message,
	      int pos,
	      const std::list<BinaryData>& bins,
	      std::list<BinaryData>::const_iterator& binpos);

    /// Print itself on \c s, and return it.
    std::ostream& print(std::ostream& s) const;

    /// Print the dictionary on \c s and return it.
    std::ostream& dictionary_print(std::ostream& s) const;

    // Huge hack.
    static const bool copy = true;
  };

  inline
  std::ostream&
  operator<<(std::ostream& s, const UValue& v);

  inline
  std::ostream&
  operator<<(std::ostream& s, const UDictionary& d);

  /*----------.
  | Casters.  |
  `----------*/

  // For each Type, define an operator() that casts its UValue&
  // argument into Type.  We need partial specialization.
  template <typename Type>
  struct uvalue_caster
  {
  };

  // T -> UVar&  if T = UVar
  // T -> T      otherwise.
  template <typename T>
  struct uvar_ref_traits
  {
    typedef T type;
  };

  template <>
  struct uvar_ref_traits<UVar>
  {
    typedef UVar& type;
  };

  // Run the uvalue_caster<Type> on v.
  template <typename Type>
  typename uvar_ref_traits<typename libport::traits::remove_reference<Type>::type>::type
  uvalue_cast (UValue& v);

} // namespace urbi

# include <urbi/uvalue.hxx>

# include <libport/warning-pop.hh>

#endif // ! URBI_UVALUE_HH
<commit_msg>Remove leftover declaration of dictionary_print.<commit_after>/*
 * Copyright (C) 2007, 2008, 2009, 2010, Gostai S.A.S.
 *
 * This software is provided "as is" without warranty of any kind,
 * either expressed or implied, including but not limited to the
 * implied warranties of fitness for a particular purpose.
 *
 * See the LICENSE file for more information.
 */

/// \file urbi/uvalue.hh
#ifndef URBI_UVALUE_HH
# define URBI_UVALUE_HH

# include <libport/warning-push.hh>

# include <vector>

# include <libport/hash.hh>
# include <libport/traits.hh>
# include <libport/ufloat.h>

# include <urbi/fwd.hh>
# include <urbi/export.hh>
# include <urbi/ubinary.hh>

namespace urbi
{

  // UValue and other related types

  /// Possible value types a UValue can contain.
  enum UDataType
  {
    DATA_BINARY,
    DATA_DICTIONARY,
    DATA_DOUBLE,
    DATA_LIST,
    DATA_OBJECT,
    DATA_STRING,
    DATA_VOID
  };

  /*--------.
  | UList.  |
  `--------*/

  /// Class storing URBI List type
  class URBI_SDK_API UList
  {
  public:
    UList();
    UList(const UList &b);
    ~UList();

    UList& operator=(const UList &b);

    // Assign a container to the UList
    template<typename T>
    UList& operator=(const T& container);

    UList& operator=(UVar& v);

    // Transform the UList to a container.
    template<typename T>
    T as();

    // Append an element to the end.
    template<typename T>
    UList&
    push_back(const T& v);

    void pop_back();

    UValue& front();

    UValue& operator[](size_t i);
    const UValue& operator[](size_t i) const;

    size_t size() const;
    void setOffset(size_t n);

    std::ostream& print(std::ostream& o) const;

    // The actual contents.
    std::vector<UValue*> array;

  private:
    void clear();
    size_t offset;
  };

  URBI_SDK_API
  std::ostream& operator<< (std::ostream& o, const UList& t);

  /*--------------.
  | UDictionary.  |
  `--------------*/
  typedef boost::unordered_map<std::string, UValue> UDictionary;

  /*--------------.
  | UNamedValue.  |
  `--------------*/

  class URBI_SDK_API UNamedValue
  {
  public:
    UNamedValue(const std::string& n = "", UValue* v = 0);
    // Used on errors.
    static UNamedValue& error();
    std::string name;
    UValue* val;
  };

  /*----------------.
  | UObjectStruct.  |
  `----------------*/

  class URBI_SDK_API UObjectStruct
  {
  public:
    UObjectStruct();
    UObjectStruct(const UObjectStruct &b);
    UObjectStruct& operator=(const UObjectStruct &b);
    ~UObjectStruct();

    /// Return UValue::error() on errors.
    UValue& operator[](const std::string& s);

    /// Return UNamedValue::error() on errors.
    const UNamedValue& operator[](size_t i) const;
    UNamedValue& operator [](size_t i);

    size_t size() const;

    std::ostream& print(std::ostream& o) const;

    std::string refName;
    std::vector<UNamedValue> array;
  };

  URBI_SDK_API
  std::ostream& operator<< (std::ostream& o, const UObjectStruct& t);

  /*---------.
  | UValue.  |
  `---------*/

  /** Container for a value that handles all types known to URBI.
   */
  class URBI_SDK_API UValue
  {
  public:
    UDataType       type;
    ufloat          val;  ///< value if of type DATA_DOUBLE
    union
    {
      std::string* stringValue; ///< value if of type DATA_STRING
      UBinary* binary;          ///< value if of type DATA_BINARY
      UList* list;              ///< value if of type DATA_LIST
      UDictionary* dictionary;  ///< value if of type DATA_DICTIONARY
      UObjectStruct* object;    ///< value if of type DATA_OBJ
      void* storage;            ///< internal
    };

    UValue();
    UValue(const UValue&);

    ~UValue();

    UValue& operator=(const UValue&);
    /// Setter. If copy is false, binary data if present is not copied.
    /// This is dangerous, as the user must ensure that the source UValue
    /// lives longer than this one.
    UValue& set(const UValue&, bool copy=true);
    /// Delete content and reset type to void.
    void clear();
    /// A specific UValue used when we want to return an error.
    /// For instance, out-of-bound access returns this object.
    static UValue& error();

    /// We use an operator , that behaves like an assignment.  The
    /// only difference is when the rhs is void, in which case it is
    /// the regular comma which is used.  This allows to write "uval,
    /// expr" to mean "compute expr and assign its result to uval,
    /// unless expr is void".
    UValue& operator, (const UValue &b);

    /// Return a legible definition of UDataType
    const char* format_string() const;

#define CTOR_AND_ASSIGN_AND_COMMA(Type)		\
    explicit UValue(Type, bool copy=true);	\
    UValue& operator=(Type);			\
    UValue& operator,(Type rhs)

    // UFloats.
    CTOR_AND_ASSIGN_AND_COMMA(ufloat);
    CTOR_AND_ASSIGN_AND_COMMA(int);
    CTOR_AND_ASSIGN_AND_COMMA(long);
    CTOR_AND_ASSIGN_AND_COMMA(unsigned int);
    CTOR_AND_ASSIGN_AND_COMMA(unsigned long);

    // Strings.
    CTOR_AND_ASSIGN_AND_COMMA(const char*);
    CTOR_AND_ASSIGN_AND_COMMA(const void*);
    CTOR_AND_ASSIGN_AND_COMMA(const std::string&);

    // Others.
    CTOR_AND_ASSIGN_AND_COMMA(const UBinary&);
    CTOR_AND_ASSIGN_AND_COMMA(const UList&);
    CTOR_AND_ASSIGN_AND_COMMA(const UDictionary&);
    CTOR_AND_ASSIGN_AND_COMMA(const UObjectStruct&);
    CTOR_AND_ASSIGN_AND_COMMA(const USound&);
    CTOR_AND_ASSIGN_AND_COMMA(const UImage&);

#undef CTOR_AND_ASSIGN_AND_COMMA

    operator ufloat() const;
    operator std::string() const;
    operator int() const;
    operator unsigned int() const;
    operator long() const;
    operator unsigned long() const;
    operator bool() const;

    /// Accessor. Gives us an implicit operator UBinary() const
    operator const UBinary&() const;

    /// Deep copy.
    operator UList() const;

    /// Deep copy.
    operator UDictionary() const;

    /// Shallow copy.
    operator UImage() const;

    /// Shallow copy.
    operator USound() const;

    /// This operator does nothing, but helps with the previous operator,.
    /// Indeed, when writing "uval, void_expr", the compiler complains
    /// about uval being evaluated for nothing.  Let's have it believe
    /// we're doing something...
    UValue& operator()();

    /// Parse an uvalue in current message+pos, returns pos of end of
    /// match -pos of error if error.
    int parse(const char* message,
	      int pos,
	      const std::list<BinaryData>& bins,
	      std::list<BinaryData>::const_iterator& binpos);

    /// Print itself on \c s, and return it.
    std::ostream& print(std::ostream& s) const;

    // Huge hack.
    static const bool copy = true;
  };

  inline
  std::ostream&
  operator<<(std::ostream& s, const UValue& v);

  inline
  std::ostream&
  operator<<(std::ostream& s, const UDictionary& d);

  /*----------.
  | Casters.  |
  `----------*/

  // For each Type, define an operator() that casts its UValue&
  // argument into Type.  We need partial specialization.
  template <typename Type>
  struct uvalue_caster
  {
  };

  // T -> UVar&  if T = UVar
  // T -> T      otherwise.
  template <typename T>
  struct uvar_ref_traits
  {
    typedef T type;
  };

  template <>
  struct uvar_ref_traits<UVar>
  {
    typedef UVar& type;
  };

  // Run the uvalue_caster<Type> on v.
  template <typename Type>
  typename uvar_ref_traits<typename libport::traits::remove_reference<Type>::type>::type
  uvalue_cast (UValue& v);

} // namespace urbi

# include <urbi/uvalue.hxx>

# include <libport/warning-pop.hh>

#endif // ! URBI_UVALUE_HH
<|endoftext|>


<commit_before>/*
 * This file is part of the Yildiz-Engine project, licenced under the MIT License  (MIT)
 *
 * Copyright (c) 2019 Grégory Van den Borre
 *
 * More infos available: https://engine.yildiz-games.be
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
 * documentation files (the "Software"), to deal in the Software without restriction, including without
 * limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
 * of the Software, and to permit persons to whom the Software is furnished to do so,
 * subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all copies or substantial
 * portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
 * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
 * OR COPYRIGHT  HOLDERS BE LIABLE FOR ANY CLAIM,
 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE  SOFTWARE.
 */

#include "../includes/yz_ogre_vfs_Archive.hpp"

bool yz::ogre::vfs::Archive::exists(const Ogre::String& filename) const {
    LOG_FUNCTION
    return PhysFS::exists(mName + '/' + filename);
}

Ogre::DataStreamPtr yz::ogre::vfs::Archive::open(const Ogre::String& filename, bool append) const {
    LOG_FUNCTION
    Ogre::String fullName = mName + '/' + filename;
    return Ogre::DataStreamPtr(new DataStream(filename, fullName));
}

void yz::ogre::vfs::Archive::listInfoRecursive(const Ogre::String& base, bool recursive, bool dirs, Ogre::FileInfoListPtr fileInfoList) const {
    LOG_FUNCTION
    Ogre::String baseDir = mName + '/' + base;
    StringVector files = this->vfs->enumerateFiles(baseDir);

    Ogre::FileInfo fileInfo;
    fileInfo.archive = this;
    fileInfo.path = base;
    fileInfo.compressedSize = 0;

    // iterate over all files and directories in the given directory
    for (StringVector::iterator it = files.begin(); it != files.end(); ++it) {
         fileInfo.basename = *it;
         fileInfo.filename = base + *it;
         if (this->vfs->isDirectory(*it)) {
             if (dirs) {
                 fileInfo.uncompressedSize = 0;
                 fileInfoList->push_back(fileInfo);
             }
             if (recursive) {
                 listInfoRecursive(base + *it + '/', recursive, dirs, fileInfoList);
             }
         } else {
             if (!dirs) {
                 // get file size
                 yz::physfs::File* file = new yz::physfs::File(mName + '/' + fileInfo.filename);
                 fileInfo.uncompressedSize = (size_t) file->getSize();
                 file->close();

                 fileInfoList->push_back(fileInfo);
             }
         }
     }
 }

void yz::ogre::vfs::Archive::listRecursive(const Ogre::String& base, bool recursive, bool dirs, Ogre::StringVectorPtr fileList) const {
     LOG_FUNCTION

     Ogre::String baseDir = mName + '/' + base;
     StringVector files = this->vfs->enumerateFiles(baseDir);

     // iterate over all files and directories in the given directory
     for (StringVector::iterator it = files.begin(); it != files.end(); ++it) {
         if (this->vfs->isDirectory(*it)) {
             if (dirs) {
                 fileList->push_back(base + *it);
             }
             if (recursive) {
                 listRecursive(base + *it + '/', recursive, dirs, fileList);
             }
         } else {
             if (!dirs) {
                 fileList->push_back(base + *it);
             }
         }
     }
 }

Ogre::FileInfoListPtr yz::ogre::vfs::Archive::listFileInfo(bool recursive, bool dirs) const {
     LOG_FUNCTION
     Ogre::FileInfoListPtr fileInfoList(new Ogre::FileInfoList());
     listInfoRecursive("", recursive, dirs, fileInfoList);
     return fileInfoList;
 }

Ogre::StringVectorPtr yz::ogre::vfs::Archive::list(bool recursive, bool dirs) const {
     LOG_FUNCTION
     Ogre::StringVectorPtr fileList(new Ogre::StringVector());
     listRecursive("", recursive, dirs, fileList);
     return fileList;
 }

Ogre::StringVectorPtr yz::ogre::vfs::Archive::find(const Ogre::String& pattern, bool recursive, bool dirs) const {
     LOG_FUNCTION
     Ogre::StringVectorPtr fileList = list(recursive, dirs);
     Ogre::StringVectorPtr ret(new Ogre::StringVector());

     for (Ogre::StringVector::iterator it = fileList->begin(); it != fileList->end(); ++it) {
         if (Ogre::StringUtil::match(*it, pattern))
             ret->push_back(*it);
     }
     return ret;
 }

Ogre::FileInfoListPtr yz::ogre::vfs::Archive::findFileInfo(const Ogre::String& pattern, bool recursive, bool dirs) const {
     LOG_FUNCTION
     Ogre::FileInfoListPtr fileList = const_cast<yz::ogre::vfs::Archive*>(this)->listFileInfo(recursive, dirs);
     Ogre::FileInfoListPtr ret(new Ogre::FileInfoList());

     for (Ogre::FileInfoList::iterator it = fileList->begin(); it != fileList->end(); ++it) {
         if (Ogre::StringUtil::match(it->filename, pattern))
             ret->push_back(*it);
     }

     return ret;
 }
<commit_msg>Update yz_ogre_vfs_Archive.cpp<commit_after>/*
 * This file is part of the Yildiz-Engine project, licenced under the MIT License  (MIT)
 *
 * Copyright (c) 2019 Grégory Van den Borre
 *
 * More infos available: https://engine.yildiz-games.be
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
 * documentation files (the "Software"), to deal in the Software without restriction, including without
 * limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
 * of the Software, and to permit persons to whom the Software is furnished to do so,
 * subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all copies or substantial
 * portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
 * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
 * OR COPYRIGHT  HOLDERS BE LIABLE FOR ANY CLAIM,
 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE  SOFTWARE.
 */

#include "../includes/yz_ogre_vfs_Archive.hpp"

bool yz::ogre::vfs::Archive::exists(const Ogre::String& filename) const {
    LOG_FUNCTION
    return this->vfs->exists(mName + '/' + filename);
}

Ogre::DataStreamPtr yz::ogre::vfs::Archive::open(const Ogre::String& filename, bool append) const {
    LOG_FUNCTION
    Ogre::String fullName = mName + '/' + filename;
    return Ogre::DataStreamPtr(new DataStream(filename, fullName));
}

void yz::ogre::vfs::Archive::listInfoRecursive(const Ogre::String& base, bool recursive, bool dirs, Ogre::FileInfoListPtr fileInfoList) const {
    LOG_FUNCTION
    Ogre::String baseDir = mName + '/' + base;
    StringVector files = this->vfs->enumerateFiles(baseDir);

    Ogre::FileInfo fileInfo;
    fileInfo.archive = this;
    fileInfo.path = base;
    fileInfo.compressedSize = 0;

    // iterate over all files and directories in the given directory
    for (StringVector::iterator it = files.begin(); it != files.end(); ++it) {
         fileInfo.basename = *it;
         fileInfo.filename = base + *it;
         if (this->vfs->isDirectory(*it)) {
             if (dirs) {
                 fileInfo.uncompressedSize = 0;
                 fileInfoList->push_back(fileInfo);
             }
             if (recursive) {
                 listInfoRecursive(base + *it + '/', recursive, dirs, fileInfoList);
             }
         } else {
             if (!dirs) {
                 // get file size
                 yz::physfs::File* file = new yz::physfs::File(mName + '/' + fileInfo.filename);
                 fileInfo.uncompressedSize = (size_t) file->getSize();
                 file->close();

                 fileInfoList->push_back(fileInfo);
             }
         }
     }
 }

void yz::ogre::vfs::Archive::listRecursive(const Ogre::String& base, bool recursive, bool dirs, Ogre::StringVectorPtr fileList) const {
     LOG_FUNCTION

     Ogre::String baseDir = mName + '/' + base;
     StringVector files = this->vfs->enumerateFiles(baseDir);

     // iterate over all files and directories in the given directory
     for (StringVector::iterator it = files.begin(); it != files.end(); ++it) {
         if (this->vfs->isDirectory(*it)) {
             if (dirs) {
                 fileList->push_back(base + *it);
             }
             if (recursive) {
                 listRecursive(base + *it + '/', recursive, dirs, fileList);
             }
         } else {
             if (!dirs) {
                 fileList->push_back(base + *it);
             }
         }
     }
 }

Ogre::FileInfoListPtr yz::ogre::vfs::Archive::listFileInfo(bool recursive, bool dirs) const {
     LOG_FUNCTION
     Ogre::FileInfoListPtr fileInfoList(new Ogre::FileInfoList());
     listInfoRecursive("", recursive, dirs, fileInfoList);
     return fileInfoList;
 }

Ogre::StringVectorPtr yz::ogre::vfs::Archive::list(bool recursive, bool dirs) const {
     LOG_FUNCTION
     Ogre::StringVectorPtr fileList(new Ogre::StringVector());
     listRecursive("", recursive, dirs, fileList);
     return fileList;
 }

Ogre::StringVectorPtr yz::ogre::vfs::Archive::find(const Ogre::String& pattern, bool recursive, bool dirs) const {
     LOG_FUNCTION
     Ogre::StringVectorPtr fileList = list(recursive, dirs);
     Ogre::StringVectorPtr ret(new Ogre::StringVector());

     for (Ogre::StringVector::iterator it = fileList->begin(); it != fileList->end(); ++it) {
         if (Ogre::StringUtil::match(*it, pattern))
             ret->push_back(*it);
     }
     return ret;
 }

Ogre::FileInfoListPtr yz::ogre::vfs::Archive::findFileInfo(const Ogre::String& pattern, bool recursive, bool dirs) const {
     LOG_FUNCTION
     Ogre::FileInfoListPtr fileList = const_cast<yz::ogre::vfs::Archive*>(this)->listFileInfo(recursive, dirs);
     Ogre::FileInfoListPtr ret(new Ogre::FileInfoList());

     for (Ogre::FileInfoList::iterator it = fileList->begin(); it != fileList->end(); ++it) {
         if (Ogre::StringUtil::match(it->filename, pattern))
             ret->push_back(*it);
     }

     return ret;
 }
<|endoftext|>