コード例 #1
0
void SaveToConsole(const string name, const Paths &pp, double scale = 1.0)
{
  cout << '\n' << name << ":\n"
    << pp.size() << '\n';
  for (unsigned i = 0; i < pp.size(); ++i)
  {
    cout << pp[i].size() << '\n';
    for (unsigned j = 0; j < pp[i].size(); ++j)
      cout << pp[i][j].X /scale << ", " << pp[i][j].Y /scale << ",\n";
  }
  cout << "\n";
}
コード例 #2
0
ファイル: bfsDiGraphTest.cpp プロジェクト: dendibakh/Misc
		bool equalStacks(Paths<DiGraph>::VertexStack lhs, Paths<DiGraph>::VertexStack rhs)
		{
			if (lhs.size() != rhs.size())
				return false;
			while (!lhs.empty())
			{
				if (lhs.top() != rhs.top())
					return false;
				lhs.pop();
				rhs.pop();
			}
			return true;
		}
コード例 #3
0
vector<ofVec3f> ofApp::offsetCell(list<int> & crv, float amt) {
	float scaling = 10;
	ClipperOffset co;
	Path P;
	Paths offsetP;
	float offset = amt;

	for (auto index : crv) {
		ofVec3f v = linesMesh.getVertex(index);
		P.push_back(IntPoint(v.x*scaling, v.y*scaling));
	}
	co.AddPath(P, jtRound, etClosedPolygon);
	co.Execute(offsetP, -offset*scaling);

	vector<ofVec3f> offsetPts;
	if (offsetP.size() > 0) {
		//visual offset for etching
		CleanPolygons(offsetP);

		if (doEtchOffset) {
			co.Clear();
			co.AddPaths(offsetP, jtRound, etClosedPolygon);
			co.Execute(offsetP, -etchOffset*scaling);
		}

		Path & oP = offsetP[0];
		for (int i = 0; i < oP.size(); i++) {
			ofVec3f pt3D(oP[i].X / scaling, oP[i].Y / scaling);
			offsetPts.push_back(pt3D);
		}
	}
	return offsetPts;
}
コード例 #4
0
ファイル: TerraGenerator.cpp プロジェクト: Euphe/utymap
void TerraGenerator::populateMesh(Paths& paths, const RegionContext& regionContext)
{
    ClipperLib::SimplifyPolygons(paths);
    ClipperLib::CleanPolygons(paths);

    bool hasHeightOffset = std::abs(regionContext.options.heightOffset) > 1E-8;
    // calculate approximate size of overall points
    std::size_t size = 0;
    for (auto i = 0; i < paths.size(); ++i)
        size += static_cast<std::size_t>(paths[i].size() * 1.5);

    Polygon polygon(size);
    for (const Path& path : paths) {
        double area = ClipperLib::Area(path);
        bool isHole = area < 0;
        if (std::abs(area) < AreaTolerance)
            continue;

        backGroundClipper_.AddPath(path, ptClip, true);

        Points points = restorePoints(path);
        if (isHole)
            polygon.addHole(points);
        else
            polygon.addContour(points);

        if (hasHeightOffset)
            processHeightOffset(points, regionContext);
    }

    if (!polygon.points.empty())
        fillMesh(polygon, regionContext);
}
コード例 #5
0
ファイル: main.cpp プロジェクト: HondaDai/MinimumSpanningTree
	Paths* popPathFrom(string c) {
		Paths* ps = getPathFrom(c);
		for(int i=0;i<ps->size();i++) {
			this->remove(ps->at(i));
		}
		return ps;
	}
コード例 #6
0
//FIXME: merge with basicly duplicate in slpaths.cpp
std::string GetSpringlobbyInfo()
{
	static const std::string nl = std::string("\n");
	std::string res;
	res = getSpringlobbyAgent() + nl;
	const bool configwriteable = wxFileName::IsFileWritable(TowxString(SlPaths::GetConfigPath()));
	res += stdprintf("SpringLobby config file: %s (%swritable)\n",
			 SlPaths::GetConfigPath().c_str(),
			 BtS(configwriteable, "", "not ").c_str());
	Paths paths;
	getWritePaths(paths);
	for (size_t i = 0; i < paths.size(); ++i) {
		std::string path = paths[i].m_path;
#if defined(__WIN32__) || defined(_MSC_VER)
		path = Utf8ToLocalEncoding(path.c_str());
#endif
		res += stdprintf("%s (%s)\n", paths[i].m_desc.c_str(), path.c_str());
		const bool wx = wxFileName::IsDirWritable(path);
		const bool posix = access(path.c_str(), WRITABLE) == 0;
		bool tried = false;
		try {
			std::ofstream of;
			wxString dummy_fn = paths[i].m_path;
			if (!wxEndsWithPathSeparator(dummy_fn)) {
				dummy_fn += wxFileName::GetPathSeparator();
			}
			dummy_fn += _T("dummy.txt");

			std::string dummyFileString = dummy_fn.ToStdString();
#if defined(__WIN32__) || defined(_MSC_VER)
			dummyFileString = Utf8ToLocalEncoding(dummyFileString.c_str());
#endif
			of.open(dummyFileString);

			if (of.is_open()) {
				of << "fhreuohgeiuhguie";
				of.flush();
				of.close();
				tried = wxRemoveFile(dummyFileString);
			}
		} catch (...) {
		}
		if (paths[i].m_requireswrite && (!wx || !posix || !tried)) {
			wxLogError("%s is not writeable!", path.c_str());
		}
		res += stdprintf(("\tWX: %s POSIX: %s TRY: %s\n"), BtS(wx).c_str(), BtS(posix).c_str(), BtS(tried).c_str());
	}

	res += stdprintf("Current unitsync: %s\n", SlPaths::GetUnitSync().c_str());
	res += stdprintf("Current spring executable: %s\n", SlPaths::GetSpringBinary().c_str());
	res += stdprintf("Portable mode: %s\n", BtS(SlPaths::IsPortableMode()).c_str());

	res += stdprintf(("Compiled with wxWidgets %d.%d.%d.%d"), wxMAJOR_VERSION, wxMINOR_VERSION, wxRELEASE_NUMBER, wxSUBRELEASE_NUMBER) + nl;
	res += "Started with: \n";
	for (int i = 0; i < wxTheApp->argc; ++i)
		res += STD_STRING(wxTheApp->argv[i]) + std::string(" ");
	return res;
}
コード例 #7
0
InfoDialog::InfoDialog(wxWindow* parent)
    : wxDialog(parent, wxID_ANY, _("Paths"), wxDefaultPosition, wxSize(620, 400), wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER | wxMAXIMIZE_BOX | wxCLOSE_BOX)
{
	m_main_sizer = new wxBoxSizer(wxVERTICAL);

	typedef std::vector<std::pair<std::string, wxString> > Paths;
	Paths paths;
	paths.push_back(std::make_pair(SlPaths::GetLobbyWriteDir(), _T("LobbyWriteDir")));
	paths.push_back(std::make_pair(SlPaths::GetCachePath(), _T("CachePath")));
	paths.push_back(std::make_pair(SlPaths::GetExecutableFolder(), _T("ExecutableFolder")));
	paths.push_back(std::make_pair(SlPaths::GetDownloadDir(), _T("DownloadDir")));
	paths.push_back(std::make_pair(SlPaths::GetDataDir(), _T("Current SpringData:")));

	wxTextCtrl* out = new wxTextCtrl(this, wxNewId(), wxEmptyString, wxDefaultPosition, wxDefaultSize,
					 wxTE_MULTILINE | wxTE_READONLY | wxTE_RICH | wxTE_AUTO_URL);

	*out << TowxString(getSpringlobbyAgent()) + _T("\n");
	*out << wxString::Format(_T("SpringLobby config file: %s (%s writable)\n"),
				 TowxString(SlPaths::GetConfigPath()).c_str(),
				 BtS(wxFileName::IsFileWritable(TowxString(SlPaths::GetConfigPath())), "", "not").c_str());

	for (size_t i = 0; i < paths.size(); ++i) {
		const wxString path = TowxString(paths[i].first);
		*out << wxString::Format(_T("%s (%s)\n"), paths[i].second.c_str(), path.c_str());
		const bool wx = wxFileName::IsDirWritable(path);
		const bool posix = access(STD_STRING(path).c_str(), WRITABLE) == 0;
		bool tried = false;
		try {
			std::ofstream of;
			const wxString dummy_fn = path + wxFileName::GetPathSeparator() + _T("dummy.txt");
			of.open(STD_STRING(dummy_fn).c_str());

			if (of.is_open()) {
				of << "fhreuohgeiuhguie";
				of.flush();
				of.close();
				tried = wxRemoveFile(dummy_fn);
			}
		} catch (...) {
		}
		*out << wxString::Format(_T("\tWX: %s POSIX: %s TRY: %s\n"), BtS(wx).c_str(), BtS(posix).c_str(), BtS(tried).c_str());
	}

	*out << wxString::Format(_T("Current unitsync: %s\n"), TowxString(SlPaths::GetUnitSync()).c_str());
	*out << wxString::Format(_T("Current spring executable: %s\n"), TowxString(SlPaths::GetSpringBinary()).c_str());
	*out << wxString::Format(_T("Current uikeys.txt: %s\n"), TowxString(SlPaths::GetUikeys()).c_str());

	*out << wxString::Format(_T("Portable mode: %s\n"), BtS(SlPaths::IsPortableMode()).c_str());

	*out << wxString::Format(_T("Compiled with wxWidgets %d.%d.%d.%d"), wxMAJOR_VERSION, wxMINOR_VERSION, wxRELEASE_NUMBER, wxSUBRELEASE_NUMBER) + _T("\n");
	*out << _T("Started with: \n");
	for (int i = 0; i < wxTheApp->argc; ++i)
		*out << wxTheApp->argv[i] << _T(" ");
	m_main_sizer->Add(out, 1, wxALL | wxEXPAND | wxALIGN_CENTER_HORIZONTAL | wxALIGN_CENTER_VERTICAL, 0);
	SetSizer(m_main_sizer);
	Layout();
}
コード例 #8
0
InfoDialog::InfoDialog(wxWindow* parent )
	:wxDialog(parent,wxID_ANY, _("path shit"), wxDefaultPosition, wxSize(620,400), wxDEFAULT_DIALOG_STYLE|wxRESIZE_BORDER|wxMAXIMIZE_BOX)
{
	wxBoxSizer* main_sizer = new wxBoxSizer( wxVERTICAL );

	typedef  std::vector< std::pair< wxString,wxString > >
		Paths;
	Paths paths;
	paths.push_back( std::make_pair( sett().GetLobbyWriteDir(), _T("LobbyWriteDir") ) );
	paths.push_back( std::make_pair( sett().GetTempStorage(), _T("TempStorage")) );
	paths.push_back( std::make_pair( sett().GetCachePath(), _T("CachePath")) );
	paths.push_back( std::make_pair( sett().GetCurrentUsedDataDir(), _T("CurrentUsedDataDir")) );
	paths.push_back( std::make_pair( GetExecutableFolder() , _T("ExecutableFolder")));
	wxTextCtrl* out = new wxTextCtrl( this, wxNewId(), _T( "" ), wxDefaultPosition, wxDefaultSize,
									 wxTE_MULTILINE | wxTE_READONLY | wxTE_RICH | wxTE_AUTO_URL );
	for ( size_t i =0; i < paths.size(); ++i )
	{
		*out << wxString::Format( _T("%s (%s)\n"), paths[i].second.c_str(), paths[i].first.c_str());
		wxString path = paths[i].first;
		wxString dummy_fn = path + wxFileName::GetPathSeparator() + _T("dummy.txt");
		const bool wx = wxFileName::IsDirWritable( path );
		const bool posix = access(STD_STRING(path).c_str(), WRITABLE) == 0;
		bool tried = false;
		try{
			std::ofstream of;
			of.open( STD_STRING(dummy_fn).c_str() );

			if ( of.is_open() )
			{
				of << "fhreuohgeiuhguie";
				of.flush();
				of.close();
				tried = wxRemoveFile(dummy_fn);
			}
		}
		catch (...){}
		*out << wxString::Format( _T("\tWX: %s POSIX: %s TRY: %s\n"), BtS(wx).c_str(), BtS(posix).c_str(), BtS(tried).c_str() );
	}
	*out << wxString::Format( _T("Global config: %s (%s %s )\n"),
							 sett().GlobalConfigPath().c_str(),
							 BtS(wxFileName::FileExists(sett().GlobalConfigPath()), "exists", "missing").c_str(),
							 BtS(wxFileName::IsFileWritable(sett().GlobalConfigPath()), "writable", "").c_str()  );
	*out << wxString::Format( _T("Local config: %s (%s writable)\n"),
							 sett().FinalConfigPath().c_str(),
							 BtS(wxFileName::IsFileWritable(sett().FinalConfigPath()), "", "not" ).c_str() );
	*out << wxString::Format( _T("Portable mode: %s\n"), BtS(sett().IsPortableMode()).c_str() );


	*out << _T( "Version " ) + GetSpringLobbyVersion()
			<< wxString( wxVERSION_STRING ) + _T(" on ") + wxPlatformInfo::Get().GetOperatingSystemIdName() + _T( "\ncl: " ) ;
	for ( int i = 0; i < wxTheApp->argc; ++i )
		*out << wxTheApp->argv[i] << _T(" ");
	main_sizer->Add( out, 1, wxALL|wxEXPAND|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 0);
	SetSizer( main_sizer );
	Layout();
}
コード例 #9
0
void SaveToFile(char *filename, Paths &pp, double scale = 1)
{
  FILE *f = fopen(filename, "w");
  if (!f) return;
  fprintf(f, "%d\n", pp.size());
  for (unsigned i = 0; i < pp.size(); ++i)
  {
    fprintf(f, "%d\n", pp[i].size());
    if (scale > 1.01 || scale < 0.99) {
      for (unsigned j = 0; j < pp[i].size(); ++j)
        fprintf(f, "%.6lf, %.6lf,\n",
          (double)pp[i][j].X /scale, (double)pp[i][j].Y /scale);
    }
    else
    {
      for (unsigned j = 0; j < pp[i].size(); ++j)
        fprintf(f, "%lld, %lld,\n", pp[i][j].X, pp[i][j].Y );
    }
  }
  fclose(f);
}
コード例 #10
0
ファイル: geometry.cpp プロジェクト: Paulloz/godot
Vector<Vector<Point2> > Geometry::_polypaths_do_operation(PolyBooleanOperation p_op, const Vector<Point2> &p_polypath_a, const Vector<Point2> &p_polypath_b, bool is_a_open) {

	using namespace ClipperLib;

	ClipType op = ctUnion;

	switch (p_op) {
		case OPERATION_UNION: op = ctUnion; break;
		case OPERATION_DIFFERENCE: op = ctDifference; break;
		case OPERATION_INTERSECTION: op = ctIntersection; break;
		case OPERATION_XOR: op = ctXor; break;
	}
	Path path_a, path_b;

	// Need to scale points (Clipper's requirement for robust computation)
	for (int i = 0; i != p_polypath_a.size(); ++i) {
		path_a << IntPoint(p_polypath_a[i].x * SCALE_FACTOR, p_polypath_a[i].y * SCALE_FACTOR);
	}
	for (int i = 0; i != p_polypath_b.size(); ++i) {
		path_b << IntPoint(p_polypath_b[i].x * SCALE_FACTOR, p_polypath_b[i].y * SCALE_FACTOR);
	}
	Clipper clp;
	clp.AddPath(path_a, ptSubject, !is_a_open); // forward compatible with Clipper 10.0.0
	clp.AddPath(path_b, ptClip, true); // polylines cannot be set as clip

	Paths paths;

	if (is_a_open) {
		PolyTree tree; // needed to populate polylines
		clp.Execute(op, tree);
		OpenPathsFromPolyTree(tree, paths);
	} else {
		clp.Execute(op, paths); // works on closed polygons only
	}
	// Have to scale points down now
	Vector<Vector<Point2> > polypaths;

	for (Paths::size_type i = 0; i < paths.size(); ++i) {
		Vector<Vector2> polypath;

		const Path &scaled_path = paths[i];

		for (Paths::size_type j = 0; j < scaled_path.size(); ++j) {
			polypath.push_back(Point2(
					static_cast<real_t>(scaled_path[j].X) / SCALE_FACTOR,
					static_cast<real_t>(scaled_path[j].Y) / SCALE_FACTOR));
		}
		polypaths.push_back(polypath);
	}
	return polypaths;
}
コード例 #11
0
ファイル: geometry.cpp プロジェクト: Paulloz/godot
Vector<Vector<Point2> > Geometry::_polypath_offset(const Vector<Point2> &p_polypath, real_t p_delta, PolyJoinType p_join_type, PolyEndType p_end_type) {

	using namespace ClipperLib;

	JoinType jt = jtSquare;

	switch (p_join_type) {
		case JOIN_SQUARE: jt = jtSquare; break;
		case JOIN_ROUND: jt = jtRound; break;
		case JOIN_MITER: jt = jtMiter; break;
	}

	EndType et = etClosedPolygon;

	switch (p_end_type) {
		case END_POLYGON: et = etClosedPolygon; break;
		case END_JOINED: et = etClosedLine; break;
		case END_BUTT: et = etOpenButt; break;
		case END_SQUARE: et = etOpenSquare; break;
		case END_ROUND: et = etOpenRound; break;
	}
	ClipperOffset co;
	Path path;

	// Need to scale points (Clipper's requirement for robust computation)
	for (int i = 0; i != p_polypath.size(); ++i) {
		path << IntPoint(p_polypath[i].x * SCALE_FACTOR, p_polypath[i].y * SCALE_FACTOR);
	}
	co.AddPath(path, jt, et);

	Paths paths;
	co.Execute(paths, p_delta * SCALE_FACTOR); // inflate/deflate

	// Have to scale points down now
	Vector<Vector<Point2> > polypaths;

	for (Paths::size_type i = 0; i < paths.size(); ++i) {
		Vector<Vector2> polypath;

		const Path &scaled_path = paths[i];

		for (Paths::size_type j = 0; j < scaled_path.size(); ++j) {
			polypath.push_back(Point2(
					static_cast<real_t>(scaled_path[j].X) / SCALE_FACTOR,
					static_cast<real_t>(scaled_path[j].Y) / SCALE_FACTOR));
		}
		polypaths.push_back(polypath);
	}
	return polypaths;
}
コード例 #12
0
ファイル: c_clipper.cpp プロジェクト: ramonelalto/gambas
static GB_ARRAY from_polygons(Paths &polygons, bool closed)
{
	GB_ARRAY a;
	CPOLYGON *p;
	uint i;

	GB.Array.New(&a, GB.FindClass("Polygon"), polygons.size());

	for (i = 0; i < polygons.size(); i++)
	{
		if (polygons[i].size() == 0)
			continue;
		
		set_polygon_closed(polygons[i], closed);

		p = (CPOLYGON *)GB.New(GB.FindClass("Polygon"), NULL, NULL);
		*(p->poly) = polygons[i];

		*(GB_ARRAY *)GB.Array.Get(a, i) = p;
		GB.Ref(p);
	}

	return a;
}
コード例 #13
0
ファイル: PathOverlap.cpp プロジェクト: bcgsc/abyss
/** Assemble overlapping paths. */
static void assembleOverlappingPaths(Graph& g,
		Paths& paths, vector<string>& pathIDs)
{
	if (paths.empty())
		return;

	// Find overlapping paths.
	Overlaps overlaps = findOverlaps(g, paths);
	addPathOverlapEdges(g, paths, pathIDs, overlaps);

	// Create a property map of path overlaps.
	OverlapMap overlapMap;
	for (Overlaps::const_iterator it = overlaps.begin();
			it != overlaps.end(); ++it)
		overlapMap.insert(OverlapMap::value_type(
				OverlapMap::key_type(
					it->source.descriptor(),
					it->target.descriptor()),
				it->overlap));

	// Assemble unambiguously overlapping paths.
	Paths merges;
	assemble_if(g, back_inserter(merges),
			IsPathOverlap(g, overlapMap, IsPositive<Graph>(g)));

	// Merge overlapping paths.
	g_contigNames.unlock();
	assert(!pathIDs.empty());
	setNextContigName(pathIDs.back());
	for (Paths::const_iterator it = merges.begin();
			it != merges.end(); ++it) {
		string name = createContigName();
		if (opt::verbose > 0)
			cerr << name << '\t' << *it << '\n';
		Vertex u(paths.size(), false);
		put(vertex_name, g, u.descriptor(), name);
		pathIDs.push_back(name);
		paths.push_back(mergePaths(paths, overlapMap, *it));

		// Remove the merged paths.
		for (ContigPath::const_iterator it2 = it->begin();
				it2 != it->end(); ++it2) {
			if (isPath(*it2))
				paths[it2->id() - Vertex::s_offset].clear();
		}
	}
	g_contigNames.lock();
}
コード例 #14
0
ファイル: path_util.cpp プロジェクト: paulmecklenburg/svg2nc
bool ComputeOffset(const Paths &paths, double amount, Paths *result) {
  // Previous operations can leave small artifacts (e.g. self-intersecting
  // polygons) which ClipperOffset cannot handle. CleanPolygons fixes at least
  // some of these cases.
  Paths cleaned(paths.size());  // CleanPolygons does not resize 'cleaned'.
  CleanPolygons(paths, cleaned);
  Paths tmp_paths;
  if (!CopyAndForceOrientation(cleaned, true, &tmp_paths))
    return false;

  ClipperOffset co;
  co.ArcTolerance = kQuantaPerInch / 1000;
  co.AddPaths(tmp_paths, jtRound, etClosedPolygon);
  co.Execute(*result, InchesToQuanta(amount));
  return true;
}
コード例 #15
0
ファイル: pcircle.cpp プロジェクト: nphuc/alg
int main() {
    n=8;
    create();
    //GP();
    Paths res;
    Path p;
    unsigned long c=0;
    for(int i=2; i<=2*n; ++i) {
        if(i%2==0) {
            res=all(1,i,p,1);
            c+=res.size();
            PSP(res);
        }
    }
    printf("%lu",c);

}
コード例 #16
0
ファイル: PathOverlap.cpp プロジェクト: bcgsc/abyss
/** Find the largest overlap for each contig and remove it. */
static void trimOverlaps(Paths& paths, const Overlaps& overlaps)
{
	vector<unsigned> removed[2];
	removed[0].resize(paths.size());
	removed[1].resize(paths.size());

	for (Overlaps::const_iterator it = overlaps.begin();
			it != overlaps.end(); ++it) {
		unsigned& a = removed[!it->source.sense][it->source.id];
		unsigned& b = removed[it->target.sense][it->target.id];
		a = max(a, it->overlap);
		b = max(b, it->overlap);
	}

	for (Paths::iterator it = paths.begin(); it != paths.end(); ++it)
		removeContigs(*it, removed[0][it - paths.begin()],
				it->size() - removed[1][it - paths.begin()]);
}
コード例 #17
0
ファイル: main.cpp プロジェクト: HondaDai/MinimumSpanningTree
int main(int argc, char** argv)  {

	int n, m;
	int val;
	string c, c1, c2;

	// initialize & input
	cin>>n>>m;
	Citys citys(n);
	Paths paths;
	SpanningPaths spanning_path;

	for(int i=0;i<n;i++) {
		cin >> c;
		citys.setName(i, c);
	}

	for(int i=0;i<m;i++) {
		cin>>c1>>c2>>val;
		paths.push(new Path(c1, c2, val));
	}

	// kruskal's algo
	paths.sortByCost();
	for (int i=0; i<paths.size(); i++) {
		Path* p = paths.at(i);
		if (!spanning_path.existRingIfAdd(p)) {
			spanning_path.push(p->clone());
		}
	}

	int total_cost = 0;
	for (int i=0; i<spanning_path.size(); i++) {
		Path* p = spanning_path.at(i);
		cout << "(" << p->c1 << " " << p->c2 << ") ";
		total_cost += p->cost;
	}
	cout << "\n" << total_cost << endl;

//	paths.list();
//	spanning_path.list();

	return 0;
}
コード例 #18
0
ファイル: main.cpp プロジェクト: HondaDai/MinimumSpanningTree
	bool existRingIfAdd(Path* p) {
		if (this->size() == 0) {
			return false;
		}

		Paths *tmp_path = this->clone();
		string t;

		// BFS
		vector<string> sv, ev;
		sv.push_back(p->c1);
		sv.push_back(p->c2);
		while ( !sv.empty() ) {
			t = sv.back();
			sv.pop_back();
			if ( std::find(ev.begin(), ev.end(), t) != ev.end() ) {
				delete tmp_path;
				return true;
			} else {
				ev.push_back(t);
				Paths* ps = tmp_path->popPathFrom(t);
				for (int i=0;i<ps->size();i++) {
					Path* p = ps->at(i);
					if (p->c1 == t) {
						sv.push_back(p->c2);
					} else {
						sv.push_back(p->c1);
					}
				}
				delete ps;
			}
		}
		delete tmp_path;

		return false;
	}
コード例 #19
0
ファイル: poly_boolmex.cpp プロジェクト: QiTai/gdsii-toolbox
void 
mexFunction(int nlhs, mxArray *plhs[],
	    int nrhs, const mxArray *prhs[])
{
   mxArray *par;         // ptr to mxArray structure 
   double *pda;          // ptr to polynomial data
   double *pud;          // pointer to unit conversion factor
   mxLogical *ph;        // pointer to hole flags
   double ud, iud;
   unsigned int Na, Nb, vnu;
   unsigned int k, m;
   ClipType pop;
   char ostr[STR_LEN];   //string with polygon operation


   //////////////////
   // check arguments
   //

   // argument number
   if (nrhs != 4) {
      mexErrMsgTxt("polyboolmex :  expected 4 input arguments.");
   }
   
   // argument pa
   if ( !mxIsCell(prhs[0]) ) {
      mexErrMsgTxt("polyboolmex :  argument pa must be a cell array.");
   }
   Na = mxGetM(prhs[0])*mxGetN(prhs[0]);
   if (!Na) {
      mexErrMsgTxt("polyboolmex :  no input polygons pa.");
   }
   
   // argument pb
   if ( !mxIsCell(prhs[1]) ) {
      mexErrMsgTxt("polyboolmex :  argument pb must be a cell array.");
   }
   Nb = mxGetM(prhs[1])*mxGetN(prhs[1]);
   if (!Nb) {
      mexErrMsgTxt("polyboolmex :  no input polygons pb.");
   }

   // get operation argument
   mxGetString(prhs[2], ostr, STR_LEN);
   if ( !strncmp(ostr, "or", 2) )
      pop = ctUnion; 
   else if ( !strncmp(ostr, "and", 3) )
      pop = ctIntersection; 
   else if ( !strncmp(ostr, "notb", 4) )
      pop = ctDifference; 
   else if ( !strncmp(ostr, "diff", 4) )
      pop = ctDifference; 
   else if ( !strncmp(ostr, "xor", 3) )
      pop = ctXor; 
   else {
      mexErrMsgTxt("polyboolmex :  unknown boolean set algebra operation.");
   }

   // conversion factor argument
   pud = (double*)mxGetData(prhs[3]);  
   ud = *pud;
   iud = 1.0/ud;


   ////////////////////////
   // copy and prepare data
   //

   // pa
   pa.resize(Na);
   for (k=0; k<Na; k++) {

      // get the next polygon from the cell array 
      par = mxGetCell(prhs[0], k);   // ptr to mxArray
      if ( mxIsEmpty(par) ) {
	 mexErrMsgTxt("poly_boolmex :  empty polygon in pa.");
      }
      pda = (double*)mxGetData(par); // ptr to a data     
      vnu = mxGetM(par);             // rows = vertex number

      // copy polygon and transpose, scale
      pa[k].resize(vnu);
      for (m=0; m<vnu; m++) {
	 pa[k][m].X = (cInt)(ud * pda[m]     + 0.5);
	 pa[k][m].Y = (cInt)(ud * pda[m+vnu] + 0.5);
      }

      // make sure polygons have positive orientation
      if ( !Orientation(pa[k]) )
	  ReversePath(pa[k]);
   }

   // pb
   pb.resize(Nb);
   for (k=0; k<Nb; k++) {

      // get the next polygon 
      par = mxGetCell(prhs[1], k);   // ptr to mxArray
      if ( mxIsEmpty(par) ) {
	 mexErrMsgTxt("poly_boolmex :  empty polygon in pb.");
      }
      pda = (double*)mxGetData(par); // ptr to a data     
      vnu = mxGetM(par);             // rows = vertex number

      // copy polygon and transpose, scale
      pb[k].resize(vnu);
      for (m=0; m<vnu; m++) {
	 pb[k][m].X = (cInt)(ud * pda[m]     + 0.5);
	 pb[k][m].Y = (cInt)(ud * pda[m+vnu] + 0.5);
      }

      // make sure polygons have positive orientation
      if ( !Orientation(pb[k]) )
	  ReversePath(pb[k]);
   }


   ////////////////////
   // clip the polygons
   //
   C.AddPaths(pa, ptSubject, true);
   C.AddPaths(pb, ptClip, true);

   if ( !C.Execute(pop, pc, pftEvenOdd, pftEvenOdd) )
       mexErrMsgTxt("polyboolmex :  Clipper library error.");


   //////////////////////////////////////////
   // create a cell array for output argument
   //
   plhs[0] = mxCreateCellMatrix(1, pc.size());

   //////////////////////////
   // return clipping results
   //
   for (k=0; k<pc.size(); k++) {
      
      // allocate matrix for boundary
      vnu = pc[k].size();
      par = mxCreateDoubleMatrix(vnu, 2, mxREAL);
      pda = (double*)mxGetData(par);
    
      // copy vertex array, transpose, and scale back to user units
      for (m=0; m<vnu; m++) {
         pda[m]     = iud * pc[k][m].X;
         pda[vnu+m] = iud * pc[k][m].Y;
      }

      // store in cell array
      mxSetCell(plhs[0], k, par);
   }

   ///////////////////
   // return hole flags
   //
   plhs[1] = mxCreateLogicalMatrix(1, pc.size());
   ph = (mxLogical*)mxGetData(plhs[1]);
   for (k=0; k<pc.size(); k++) 
      ph[k] = !Orientation(pc[k]); // same as input == no hole

   ///////////////////
   // clean up
   //
   C.Clear();
   pa.resize(0);
   pb.resize(0);
   pc.resize(0);
}
コード例 #20
0
vector<ofVec3f> ofApp::offsetCell(list<int> & crv, AnisoPoint2f & pt) {
	float scaling = 1000;
	ClipperOffset co;
	co.ArcTolerance = 1;
	Path P;
	Paths offsetP;
	float offset = ofClamp(offsetPercent / sqrt(pt.jacobian->determinant()), minThick*0.5, maxThick*0.5);

	if (doSmooth) {
		
		for (auto index : crv) {
			ofVec3f v = linesMesh.getVertex(index);
			IntPoint iPt(v.x * scaling, v.y * scaling);
			P.push_back(iPt);
		}
		co.AddPath(P, jtRound, etClosedPolygon);
		co.Execute(offsetP, -offset*scaling);
		if(offsetP.size() == 0) return vector<ofVec3f>();
		P.clear();
		ofVec2f center;
		for (auto & v : offsetP[0]) {
			//ofVec3f v = linesMesh.getVertex(index);
			Vector2f p(v.X, v.Y);
			p = (*pt.jacobian)*p;
			IntPoint iPt(p.coeff(0), p.coeff(1));
			P.push_back(iPt);
			center += ofVec2f(iPt.X, iPt.Y);
		}
		center /= crv.size();
		CleanPolygon(P);
		
		co.Clear();
		co.AddPath(P, jtRound, etClosedPolygon);
		float radius = 9e20;

		//get exact radius from straight skeleton
		Polygon_2 poly;
		for (auto & pt : P) {
			poly.push_back(Point_2(pt.X, pt.Y));
		}
		boost::shared_ptr<Ss> iss = CGAL::create_interior_straight_skeleton_2(poly.vertices_begin(), poly.vertices_end());
		radius = 0;
		for (Ss::Vertex_handle vh = iss->vertices_begin(); vh != iss->vertices_end(); vh++) {
			if (!vh->has_infinite_time()) {
				radius = max(radius, (float)vh->time());
			}
		}

		//estimate radius
		//for (auto & iPt : P) {
		//	radius = min(radius, (iPt.X - center.x)*(iPt.X - center.x) + (iPt.Y - center.y)*(iPt.Y - center.y));
		//}
		//radius = sqrt(radius);
		//co.Execute(offsetP, -radius);
		//int tries = 0;
		//while (offsetP.size() == 0 && tries < 50) {
		//	radius *= .95;
		//	co.Execute(offsetP, -radius);
		//	tries++;
		//}
		//cout << tries << endl;
		radius *= filletPercent;
		co.Execute(offsetP, -radius);
		//radius = min(radius,(radius - offset*scaling)*filletPercent + offset*scaling);
		
		//co.Execute(offsetP, -offset*scaling);
		vector<ofVec3f> offsetPts;
		if (offsetP.size() > 0) {
			//visual offset for etching
			co.Clear();
			CleanPolygons(offsetP);
			co.AddPaths(offsetP, jtRound, etClosedPolygon);
			co.Execute(offsetP, radius);
			CleanPolygons(offsetP);
			Path longestP;
			int pLen = 0;
			for (auto & oP : offsetP) {
				if (oP.size() > pLen) {
					pLen = oP.size();
					longestP = oP;
				}
			}
			Matrix2f inverse = pt.jacobian->inverse();
			if (doEtchOffset) {
				co.Clear();
				for (auto & lPt : longestP) {
					Vector2f anisoPt(lPt.X, lPt.Y);
					anisoPt = inverse*anisoPt;
					lPt.X = anisoPt[0];
					lPt.Y = anisoPt[1];
				}
				co.AddPath(longestP, jtRound, etClosedPolygon);
				co.Execute(offsetP, etchOffset*scaling);
				longestP = offsetP[0];
			}
			for (int i = 0; i < longestP.size(); i++) {
				//ofVec3f pt3D(oP[i].X / scaling, oP[i].Y/ scaling);
				Vector2f anisoPt(longestP[i].X / scaling, longestP[i].Y / scaling);
				if(!doEtchOffset)anisoPt = inverse*anisoPt;
				offsetPts.push_back(ofVec3f(anisoPt.coeff(0), anisoPt.coeff(1)));
			}
		}
		return offsetPts;
	}
	else {
		for (auto index : crv) {
			ofVec3f v = linesMesh.getVertex(index);
			IntPoint iPt(v.x * scaling, v.y * scaling);
			P.push_back(iPt);
		}
		CleanPolygon(P);
		//Paths simplerP;
		//SimplifyPolygon(P, simplerP);
		//CleanPolygons(simplerP);
		//P = simplerP[0];
		//CleanPolygon(P);
		//Polygon_2 poly;
		//for (auto & pt : P) {
		//	poly.push_back(Point_2(pt.X, pt.Y));
		//}
		//boost::shared_ptr<Ss> iss = CGAL::create_interior_straight_skeleton_2(poly.vertices_begin(), poly.vertices_end());
		//float radius = 0;
		//for (Ss::Vertex_handle vh = iss->vertices_begin(); vh != iss->vertices_end(); vh++) {
		//	if (!vh->has_infinite_time()) {
		//		radius = max(radius, (float)vh->time());
		//	}
		//}
		
		//Paths simplerP;
		//SimplifyPolygon(P, simplerP);
		//co.AddPaths(simplerP, jtRound, etClosedPolygon);
		//radius = ofClamp(radius*offsetPercent, minThick*0.5*scaling, maxThick*0.5*scaling);
		co.AddPath(P, jtRound, etClosedPolygon);
		co.Execute(offsetP, -offset*scaling);
		vector<ofVec3f> offsetPts;
		if (offsetP.size() > 0) {
			CleanPolygons(offsetP);
			if (doEtchOffset) {
				co.Clear();
				co.AddPaths(offsetP, jtRound, etClosedPolygon);
				co.Execute(offsetP, etchOffset*scaling);
			}
			else {
				co.Clear();
				co.AddPaths(offsetP, jtRound, etClosedPolygon);
				co.Execute(offsetP, 1);
			}
			Path longestP;
			int pLen = 0;
			for (auto & oP : offsetP) {
				if (oP.size() > pLen) {
					pLen = oP.size();
					longestP = oP;
				}
			}
			Path & oP = longestP;
			for (int i = 0; i < oP.size(); i++) {
				ofVec3f pt3D(oP[i].X / scaling, oP[i].Y/ scaling);
				offsetPts.push_back(pt3D);
			}
		}
		return offsetPts;
	}

}
コード例 #21
0
LatexGenerator::LatexGenerator(const Paths &paths,
                               const Cordinate maxValues,
                               const vector<char> &pieces,
                               const vector<Cordinate> &obstacles,
                               const string &outputFilename)
{
   ofstream out(outputFilename.c_str());
   out << "\\documentclass[12pt]{article}" << endl;
   out << "\\usepackage{chessboard}" << endl;
   out << "\\usepackage{chessfss}" << endl;
   out << "\\begin{document}" << endl;

	out << "\\chessboard[setpieces={";
   int numPieces(0);
   for (size_t i = 0; i < pieces.size(); i++)
   {
      if (pieces.at(i) == ' ' || pieces.at(i) == 'X') 
         continue;
      if (numPieces != 0) out << ',';
      out << pieces.at(i);
      out << _Alphabets.at(i%maxValues.first);
      out << (i/maxValues.first + 1);
      numPieces++;
   }
   out << "}";
   if (!obstacles.empty())
   {
      out << ",pgfstyle={text},text=X,markfields={";
      for (size_t i = 0; i < obstacles.size(); i++)
      {
         if (i!=0) out << ',';
         out << _Alphabets.at(obstacles.at(i).first-1) << obstacles.at(i).second;
      }
      out << "}";
   }
   if (!paths.empty())
   {
      system("mkdir -p lg_temp");
      int offset(0);
      cout << "Generating temp files" << endl;
      for (Paths::const_iterator itr = paths.begin(); itr != paths.end(); ++itr)
      {
         stringstream ss;
         ss << "./lg_temp/" << offset;
         ofstream out(ss.str().c_str());

         const string &currentPath(*itr);
         for (size_t j = 0; j < currentPath.size(); j++)
         {
            if (isdigit(currentPath.at(j)))
               out << currentPath.at(j);
            else if (currentPath.at(j) == ',')
               out << ' ';
            else if (currentPath.at(j) == ')')
               out << endl;
         }
         out.close();
         offset++;
      }
      cout << "DONE Generating temp files" << endl;

      out << ",pgfstyle={straightmove},";
      out << "markmoves={";
      cout << "Generating moves" << endl;
      bool isFirst(true);
      for (size_t i = 0; i < paths.size(); i++)
      {
         cout << "Generating move " << i << endl;
         stringstream ss;
         ss << "./lg_temp/" << i;
         ifstream in(ss.str().c_str());
         int a1(0), a2(0);
         int b1(0), b2(0);
         bool isNewFile(true);
         while (!in.eof())
         {
            if (isNewFile)
            {
               in >> a1;
               in >> a2;
            }
            in >> b1;
            in >> b2;
            if (in.eof()) break;
            if(!isFirst)
            {
               out << ',';
            }
            out << _Alphabets.at(a1-1) << a2 << "-" << _Alphabets.at(b1-1) << b2;
            a1 = b1;
            a2 = b2;
            isFirst = false;
            isNewFile = false;
         }
         cout << "DONE Generating move " << i << endl;
      }
      cout << "DONE Generating moves" << endl;
      out << "}, arrow=to, linewidth=0.1em" << endl;
   }
コード例 #22
0
 void AddPaths(Paths& poly)
 {
   if (poly.size() == 0) return;
   polyInfos.push_back(PolyInfo(poly, style));
 }
コード例 #23
0
ファイル: tilesetter.cpp プロジェクト: CruzR/wc3lib
int main(int argc, char *argv[])
{
	// Set the current locale.
	setlocale(LC_ALL, "");
	// Set the text message domain.
	bindtextdomain("tilesetter", LOCALE_DIR);
	textdomain("tilesetter");

	static const char* version = "0.1";
	std::cout << boost::format(_("Tilesetter version %1%")) % version << std::endl;
	std::cout << _(
	"Copyright (C) 2009 by Tamino Dauth\n"
	"[email protected]\n"
	"\n"
	"This program is free software; you can redistribute it and/or modify\n"
	"it under the terms of the GNU General Public License as published by\n"
	"the Free Software Foundation; either version 2 of the License, or\n"
	"(at your option) any later version.\n"
	"\n"
	"This program is distributed in the hope that it will be useful,\n"
	"but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
	"MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n"
	"GNU General Public License for more details.\n"
	"\n"
	"You should have received a copy of the GNU General Public License\n"
	"along with this program; if not, write to the\n"
	"Free Software Foundation, Inc.,\n"
	"59 Temple Place - Suite 330, Boston, MA  02111-1307, USA."
	) << std::endl;

	typedef std::vector<boost::filesystem::path> Paths;
	typedef std::vector<std::string> Strings;
	// TODO throws exception when using escaped white spaces! - string work around
	Strings environmentStrings;
	Paths environments;

	const boost::program_options::command_line_style::style_t pstyle = boost::program_options::command_line_style::style_t(
	boost::program_options::command_line_style::unix_style
	);

	boost::program_options::options_description desc("Allowed options");
	desc.add_options()
	("version,V", _("Shows current version of tilesetter."))
	("help,h",_("Shows this text."))
	// options

	// operations
	("reassign,r", _("Reads ground and cliff types from the first environment file and assigns them to all following."))

	// input
	("files,f", boost::program_options::value<Strings>(&environmentStrings), _("Expected environment files."))
	;

	boost::program_options::positional_options_description p;
	p.add("files", -1);

	boost::program_options::variables_map vm;

	try
	{
		boost::program_options::store(boost::program_options::command_line_parser(argc, argv).style(pstyle).options(desc).positional(p).run(), vm);
	}
	catch (std::exception &exception)
	{
		std::cerr << boost::format(_("Error while parsing program options: \"%1%\"")) % exception.what() << std::endl;

		return EXIT_FAILURE;
	}

	boost::program_options::notify(vm);

	// WORKAROUND
	environments.resize(environmentStrings.size());
	environments.assign(environmentStrings.begin(), environmentStrings.end());

	if (vm.count("version"))
	{
		std::cout << boost::format(_(
		"tilesetter %1%.\n"
		"Copyright © 2009 Tamino Dauth\n"
		"License GPLv2+: GNU GPL version 2 or later <http://gnu.org/licenses/gpl.html>\n"
		"This is free software: you are free to change and redistribute it.\n"
		"There is NO WARRANTY, to the extent permitted by law."
		)) % version << std::endl;

		return EXIT_SUCCESS;
	}

	if (vm.count("help"))
	{
		std::cout << desc << std::endl;
		std::cout << _("\nReport bugs to [email protected] or on https://wc3lib.org") << std::endl;

		return EXIT_SUCCESS;
	}

	if (environments.empty())
	{
		std::cerr << _("Missing environments arguments.") << std::endl;

		return EXIT_FAILURE;
	}

	if (vm.count("reassign"))
	{
		boost::ptr_vector<map::Environment> envs;
		envs.reserve(environments.size());

		BOOST_FOREACH(Paths::const_reference path, environments)
		{
			if (!boost::filesystem::is_regular_file(path))
			{
				std::cerr << boost::format(_("File %1% does not seem to be a regular file.")) % path << std::endl;

				return EXIT_FAILURE;
			}

			boost::filesystem::ifstream ifstream;
			ifstream.exceptions(boost::filesystem::ifstream::badbit | boost::filesystem::ifstream::failbit | boost::filesystem::ifstream::eofbit);

			try
			{
				ifstream.open(path, std::ios::in | std::ios::binary);
				std::auto_ptr<map::Environment> env(new map::Environment());
				env->read(ifstream);
				envs.push_back(env);
			}
			catch (std::exception &exception)
			{
				std::cerr << boost::format(_("Error occured while opening file %1%:\n\"%2%\"")) % path % exception.what() << std::endl;

				return EXIT_FAILURE;
			}
		}

		if (envs.size() < 2)
		{
			std::cerr << _("We need at least 2 environments.") << std::endl;

			return EXIT_FAILURE;
		}

		for (std::size_t i = 1; i < envs.size(); ++i)
		{
			envs[i].cliffTilesetsIds().assign(envs[0].cliffTilesetsIds().begin(), envs[0].cliffTilesetsIds().end());
			envs[i].groundTilesetsIds().assign(envs[0].groundTilesetsIds().begin(), envs[0].groundTilesetsIds().end());

			boost::filesystem::ofstream ofstream;
			ofstream.exceptions(boost::filesystem::ofstream::badbit | boost::filesystem::ofstream::failbit | boost::filesystem::ofstream::eofbit);

			try
			{
				ofstream.open(environments[i], std::ios::out | std::ios::binary);
				envs[i].write(ofstream);
			}
			catch (std::exception &exception)
			{
				std::cerr << boost::format(_("Error occured while saving file %1%:\n\"%2%\"")) % environments[i] % exception.what() << std::endl;

				return EXIT_FAILURE;
			}
		}
	}
コード例 #24
0
ファイル: plot.cpp プロジェクト: jmundack/linguistic_geometry
Plot::Plot(const Paths &paths,
           const Cordinate maxValues,
           const Cordinate start,
           const Cordinate end,
           const std::vector<Cordinate> &obstacles,
           const string &outputFilename)
{
   cout << "Plotting start : " << start.first << "," << start.second << " to end : " << end.first << "," << end.second << endl;
    system("mkdir -p temp");
   int offset(0);
   for (Paths::const_iterator itr = paths.begin(); itr != paths.end(); ++itr)
   {
       stringstream ss;
       ss << "./temp/" << offset;
      ofstream out(ss.str().c_str());

      const string &currentPath(*itr);
      for (size_t j = 0; j < currentPath.size(); j++)
      {
         if (isdigit(currentPath.at(j)))
            out << currentPath.at(j);
         else if (currentPath.at(j) == ',')
            out << ' ';
         else if (currentPath.at(j) == ')')
            out << endl;
      }
      out.close();
      offset++;
   }
   ofstream profile("profile.gnu");
   profile << "set term jpeg" << endl;
   profile << "set out \'" << outputFilename << "'" << endl;
   profile << "set xrange[0.5:" << float(maxValues.first) +0.5 << "]" << endl;
   profile << "set yrange[0.5:" << float(maxValues.second) +0.5 << "]" << endl;
   profile << "set grid" << endl;
//   profile << "set object circle at " << start.first << "," << start.second << " size 0.2 fillcolor rgbcolor \'red\' fill solid" << endl;
//   profile << "set object circle at " << end.first << "," << end.second << " size 0.2 fillcolor rgbcolor \'red\' fill solid" << endl;
   for (size_t i = 0; i < obstacles.size(); i++)
   {
       const pair<int,int> &ob(obstacles.at(i));
       profile << "set object rect from "  << ob.first-0.5 << "," << ob.second - 0.5 << " to "
                  << ob.first+0.5 << "," << ob.second + 0.5 << " fc rgbcolor \'gray\'" << endl;
   }

   profile << "set xtics (";
   for (int i = 0; i < maxValues.first; i++)
   {
       if (i!=0)
           profile << ',';
       profile << "'" << i+1 << "'" << (float(i)+0.5);
   }
   profile << ")" << endl;
   profile << "set ytics (";
   for (int i = 0; i < maxValues.second; i++)
   {
       if (i!=0)
           profile << ',';
       profile << "'" << i+1 << "'" << (float(i)+0.5);
   }
   profile << ")" << endl;
   profile << "plot ";
   for (size_t i = 0; i < paths.size(); i++)
   {
       if (i !=0)
           profile << ",";
       profile << "'" << "temp/" << i << "\' w linespoints lc \'red\' title \'\' ";
   }
   profile.close();
   system("gnuplot < profile.gnu");
   string openJpeg = "gnome-open " + outputFilename;
   system(openJpeg.c_str());
}
コード例 #25
0
ファイル: mp3d.cpp プロジェクト: JoeBargo/enh
int main(int argc, char* argv[]) {
  // Parse any command-line options.
  namespace po = boost::program_options;
  po::options_description desc("Allowed options");
  desc.add_options()
    ("help", "show help")
    ("debug-httpd", po::value<bool>(&mp3d_debug_httpd), "show httpd debug output")
    ("root", po::value<std::string>(&mp3d_music_root), "root of file system mp3 tree")
    ("port", po::value<int>(&mp3d_port), "httpd port number")
  ;
  po::variables_map args;
  po::store(po::parse_command_line(argc, argv, desc), args);
  po::notify(args);
  if (args.count("help")) {
    std::cout << desc << std::endl;
    return 1;
  }

  // Index all the mp3s.
  Paths paths;
  find_mp3_files(mp3d_music_root, paths);
  std::cerr << ".mp3 files found: " << paths.size() << std::endl;

  int old_percentage = -1;
  size_t id = 0;
  for (Paths::const_iterator it = paths.begin(); it != paths.end(); ++it) {
    Mp3Info mp3;
    mp3.filename = (*it).string();

    const ID3_Tag tag(mp3.filename.c_str());

    ID3_Tag::ConstIterator* it = tag.CreateIterator();
    for (size_t i = 0; i < tag.NumFrames(); ++i) {
      const ID3_Frame* frame = it->GetNext();
      if (frame != 0) {
        std::string* dst;
        switch (frame->GetID()) {
        case ID3FID_ALBUM: dst = &mp3.album; break;
        case ID3FID_LEADARTIST: dst = &mp3.artist; break;
        case ID3FID_TITLE: dst = &mp3.title; break;
        default: continue;
        }
        char* text = ID3_GetString(frame, ID3FN_TEXT);
        dst->assign(text);
        ID3_FreeString(text);
      }
    }
    
    // FIXME: maybe a hash, to enable bookmarks?
    mp3.id = id++;
    
    all_mp3s.push_back(mp3);
    
    // Show progress. Not really useful when we're not debugging.
    // FIXME: start the web server straight away, and say "Indexing..." there.
    const int new_percentage = (100*all_mp3s.size())/paths.size();
    if (new_percentage != old_percentage) {
      std::cout << "\rScanned: " << new_percentage << "%" << std::flush;
      old_percentage = new_percentage;
    }
  }
  std::cout << "\r.mp3 files scanned: " << all_mp3s.size() << std::endl;

  // Set up the static files we need to serve.
  read_static_file("/static/add.png",
                   "/usr/share/icons/gnome/16x16/actions/gtk-add.png");
  read_static_file("/static/play.png",
                   "/usr/share/icons/gnome/16x16/actions/gtk-media-play-ltr.png");
  read_static_file("/static/remove.png",
                   "/usr/share/icons/gnome/16x16/actions/gtk-remove.png");
  static_file_map["/static/site.css"] = make_css();
  
  // Start the mp3 player thread.
  boost::thread mp3_player_thread(mp3_play_loop);
  
  // Start the HTTP server.
  std::cerr << "Starting HTTP server on port " << mp3d_port << "..." << std::endl;
  const int mhd_flags = MHD_USE_SELECT_INTERNALLY;
  MHD_Daemon* daemon = MHD_start_daemon(mhd_flags, mp3d_port, 0, 0, &handle_request, 0, MHD_OPTION_END);
  if (daemon == 0) {
    fail("MHD_start_daemon failed!");
  }
  
  getchar(); // Wait for the user to hit enter.
  
  MHD_stop_daemon(daemon);
  //mp3_player_thread.join();
  return 0;
}
コード例 #26
0
ファイル: toolpath.cpp プロジェクト: malichao/GerberCAM
bool toolpath::cToolpathIntersects(QList<netPath> nPList,QList<collisionToolpath> &cTList)
{
    for(int i=0;i<nPList.size();i++)
    {
        netPath tNetPath=nPList.at(i);
        Path tPath=tNetPath.toolpath.at(0);
        collisionToolpath tcTList;
        tcTList.list.append(i);
        for(int j=i+1;j<nPList.size();j++)
        {
            netPath tNetPath1=nPList.at(j);
            Path tPath1=tNetPath1.toolpath.at(0);
            Paths tPaths;
            Clipper c;
            c.AddPath(tPath,ptSubject , true);
            c.AddPath(tPath1,ptClip , true);
            c.Execute(ctIntersection,tPaths,pftNonZero,pftNonZero);

            if(tPaths.size()>0)//collided
            {
                tcTList.list.append(j);
                collisionPair p;
                p.p1=i;
                p.p2=j;
                tcTList.pair.append(p);
            }


        }
        if(tcTList.list.size()>1)
        {
            bool collisionFlag=false;
            int toolpathNum=0;
            for(int l=0;l<cTList.size();l++)
            {
                collisionToolpath tcTList1=cTList.at(l);
                for(int k=0;k<tcTList.list.size();k++)
                {
                    int toopathIndex=tcTList.list.at(k);
                    for(int m=0;m<tcTList1.list.size();m++)
                    {
                        int toopathIndex1=tcTList1.list.at(m);
                        if(toopathIndex==toopathIndex1)
                        {
                            collisionFlag=true;
                            break;
                        }
                    }
                    if(collisionFlag==true)
                    {
                        toolpathNum=l;
                        break;
                    }
                }

                if(collisionFlag==true)//collided with existed toolpath,merge
                {
                    //merge two list
                    collisionToolpath tcTList1=cTList.at(toolpathNum);
                    for(int n=0;n<tcTList1.list.size();n++)
                    {
                        bool sameFlag=false;
                        int num=0;
                        for(int o=0;o<tcTList.list.size();o++)
                        {
                            if(tcTList.list.at(o)==tcTList1.list.at(n))
                            {
                                sameFlag=true;
                                num=o;
                                break;
                            }
                        }
                        if(sameFlag==true)
                            continue;
                        tcTList1.list.append(tcTList.list.at(num));
                    }
                    //and save
                    cTList.replace(l,tcTList1);
                    break;
                }
            }
            if(collisionFlag==false)
            {
                cTList.append(tcTList);
            }
        }
    }

}