예제 #1
0
int
cgi_FindAllClubs::FindAllClubs( ostream &os )
{
  cgidata 	     data;
  vector<Club*>      sv;
  HTMLTemplate       templ( "/web/kochut/public_html/FindAllClubs-Result.html" );
  Club 		    *c;
  char		    *subs[1][2];
  strstream	     clubs;
  int i;

  try {

    sv = ctrl_FindAllClubs::FindAllClubs();
    sort( sv.begin(), sv.end(), CompClubsPtr() );

    for( i = 0; i < sv.size(); i++ ) {

      c = (Club*) sv[ i ];
      clubs << "<li>" << *c << "</li>";

    }

    subs[0][0] = "%CLUBS%";
    if ( clubs.str() == NULL )
      subs[0][1] = "No clubs have been defined";
    else
      subs[0][1] = clubs.str();

    templ.Instantiate( os, subs, 1 );

  }
  catch( ClubsException ce ) {

    HTMLTemplate         templ( "/web/kochut/public_html/FindAllClubs-Error.html" );

    subs[0][0] = "%REASON%";
    subs[0][1] = ce.get_Msg();

    templ.Instantiate( os, subs, 1 );

    return 0;

  }
  catch( HTMLTemplateException te ) {

    HTMLTemplate         templ( "/web/kochut/public_html/FindAllClubs-Error.html" );

    subs[0][0] = "%REASON%";
    subs[0][1] = te.get_Msg();

    templ.Instantiate( os, subs, 1 );

    return 0;

  }

  return 0;

}
예제 #2
0
파일: cgen.cpp 프로젝트: dreamsxin/slorm
void CGen::process ()
{
    // Creating header and implementation files
    openFile(H, ctx().baseName() + ".h");
    openFile(C, ctx().baseName() + ".c");

    Templ h(templ()), c(templ());

    file(H) << h.str("h/header") << std::endl << std::endl;

    file(C) << c.str("c/header") << std::endl << std::endl <<
        c.str("c/str-api") << std::endl << std::endl;

    if (ctx().cacheLimit() > 0)
        file(C) << c.str("c/cache-api") << std::endl << std::endl;

    h.load("h/tab");
    c.load("c/tab-id");
    BOOST_FOREACH(const meta::Tab &tab, db().tabs())
    {
        setTab(tab.name());
        file(H) << h.str() << std::endl << std::endl;
        file(C) << c.str() << std::endl;

        Templ h2(h), c2(c);
        BOOST_FOREACH(const meta::Col &col, tab.cols())
        {
            setCol(col.name());
            file(H) << h2.str("h/col") << std::endl;
            file(C) << c2.str("c/col-id") << std::endl;

            if (col.nullable())
                file(H) << h2.str("h/col-null") << std::endl;

            switch (col.type())
            {
            case meta::TYPE_INT:
                file(H) << h2.str("h/col-int") << std::endl;
                break;
            case meta::TYPE_REAL:
                file(H) << h2.str("h/col-real") << std::endl;
                break;
            case meta::TYPE_TEXT:
                file(H) << h2.str("h/col-text") << std::endl;
                break;
            case meta::TYPE_BLOB:
                file(H) << h2.str("h/col-blob") << std::endl;
                break;
            }

            file(H) << std::endl;
            file(C) << std::endl;
        }
    }

    file(H) << h.str("h/footer") << std::endl;
}
void KAccountTemplateSelector::slotLoadCountry(void)
{
#ifndef KMM_DESIGNER

  KListViewItem* parent = new KListViewItem(m_groupList, d->it_m.key());
  parent->setSelectable(false);
  QStringList::iterator it;
  for(it = d->dirlist.begin(); it != d->dirlist.end(); ++it) {
    QStringList::iterator it_f;
    QDir dir(QString("%1%2").arg(*it).arg(*(d->it_m)));
    if(dir.exists()) {
      QStringList files = dir.entryList("*", QDir::Files);
      for(it_f = files.begin(); it_f != files.end(); ++it_f) {
        MyMoneyTemplate templ(QString("%1/%2").arg(dir.canonicalPath()).arg(*it_f));
        d->m_templates[QString("%1").arg(d->id)] = templ;
        new KListViewItem(parent, templ.title(), templ.shortDescription(), QString("%1").arg(d->id));
        ++d->id;
      }
    }
  }

  ++d->it_m;
  if(d->it_m != d->countries.end())
    QTimer::singleShot(0, this, SLOT(slotLoadCountry()));
  else {
    d->loadHierarchy();
  }
#endif

}
예제 #4
0
void SearchEditor::onLoad()
{
	EditorBase::onLoad();
	
	String path = utils::makeFilePath(utils::makeFolderPath(g_componentsPath, _S("search")), _S("search_editor.xsl"));

	shared_ptr<XMLStylesheet> stylesheet(OS_NEW XMLStylesheet());
	// Inizializza le funzioni del template
	getPage()->initStylesheet(stylesheet);
	// Carica l'xsl
	if(stylesheet->parseFile(path))
	{
		// URGENT devo per forza creare un documento?
		// Se il secondo parametro della XSLControl  nullptr non crea il controllo,
		// e non posso passare una "getDocument()" perch se  una nuova istanza  nullptr pure lui...
		shared_ptr<XMLDocument> document(OS_NEW XMLDocument());
		shared_ptr<XMLNode> root = document->create(OS_MODULES_SEARCH_ROOT);

		shared_ptr<HtmlXSLControl> templ(OS_NEW HtmlXSLControl(stylesheet, document));
		
		templ->addChildParam(m_globalParams);

		templ->addChildParam(m_showParams);
		templ->addChildParam(m_directRun);
		templ->addChildParam(m_allowRss);
		templ->addChildParam(m_rssDescription);
		templ->addChildParam(m_rssBody);

		getControls()->add(templ);
	}
}
예제 #5
0
void
Features::resize(unsigned int numVectors, unsigned int numFeatures) {

	std::vector<double> templ(numFeatures, 0.0);

	_features.resize(numVectors, templ);
}
예제 #6
0
GPU_PERF_TEST(MatchTemplate_32F, cv::gpu::DeviceInfo, cv::Size, TemplateSize, Channels, TemplateMethod)
{
    cv::gpu::DeviceInfo devInfo = GET_PARAM(0);
    cv::gpu::setDevice(devInfo.deviceID());

    cv::Size size = GET_PARAM(1);
    cv::Size templ_size = GET_PARAM(2);
    int cn = GET_PARAM(3);
    int method = GET_PARAM(4);

    cv::Mat image_host(size, CV_MAKE_TYPE(CV_32F, cn));
    fill(image_host, 0, 255);

    cv::Mat templ_host(templ_size, CV_MAKE_TYPE(CV_32F, cn));
    fill(templ_host, 0, 255);

    cv::gpu::GpuMat image(image_host);
    cv::gpu::GpuMat templ(templ_host);
    cv::gpu::GpuMat dst;

    cv::gpu::matchTemplate(image, templ, dst, method);

    TEST_CYCLE()
    {
        cv::gpu::matchTemplate(image, templ, dst, method);
    }
};
예제 #7
0
bool FUNCREFID::execute(void)
{
	bool result= false;
	VMPTR<TES3REFERENCE*> pref(machine);
	VMPTR<TES3REFERENCE> ref(machine);
	VMPTR<TES3TEMPLATE> templ(machine);
	VMPTR<TES3IDSTRING> id(machine);
	const char* idstring= "null";
	try
	{
		pref= (TES3REFERENCE**)reltolinear(SCRIPTTARGETREF_IMAGE);
		ref= *pref;
		templ= ref->templ;
		id= (VPIDSTRING)templ->objectid;
		idstring= strings.add((const char*)id->id);
		result= machine.push((VMREGTYPE)idstring);
	}
	catch(...)
	{
		result= false;
	}
	
		
	return result;
}
예제 #8
0
static bool copy_pro_file_template( const SEARCH_STACK& aSearchS, const wxString& aDestination )
{
    if( aDestination.IsEmpty() )
    {
        wxLogTrace( tracePathsAndFiles, "%s: destination is empty.", __func__ );
        return false;
    }

    wxString templateFile = wxT( "kicad." ) + ProjectFileExtension;

    wxString kicad_pro_template = aSearchS.FindValidPath( templateFile );

    if( !kicad_pro_template )
    {
        wxLogTrace( tracePathsAndFiles, "%s: template file '%s' not found using search paths.",
                    __func__, TO_UTF8( templateFile ) );

        wxFileName  templ( wxStandardPaths::Get().GetDocumentsDir(),
                            wxT( "kicad" ), ProjectFileExtension );

        if( !templ.IsFileReadable() )
        {
            wxString msg = wxString::Format( _(
                    "Unable to find \"%s\" template config file." ),
                    GetChars( templateFile ) );

            DisplayErrorMessage( nullptr, _( "Error copying project file template" ), msg );

            return false;
        }

        kicad_pro_template = templ.GetFullPath();
    }

    wxLogTrace( tracePathsAndFiles, "%s: using template file '%s' as project file.",
                __func__, TO_UTF8( kicad_pro_template ) );

    // Verify aDestination can be created. if this is not the case, wxCopyFile
    // will generate a crappy log error message, and we *do not want* this kind
    // of stupid message
    wxFileName fn( aDestination );
    bool success = true;

    if( fn.IsOk() && fn.IsDirWritable() )
        success = wxCopyFile( kicad_pro_template, aDestination );
    else
    {
        wxLogMessage( _( "Cannot create prj file \"%s\" (Directory not writable)" ),
                      GetChars( aDestination) );
        success = false;
    }

    return success;
}
예제 #9
0
void
SLAPrint::_infill_layer(size_t i, const Fill* _fill)
{
    Layer &layer = this->layers[i];
    
    const float shell_thickness = this->config.get_abs_value("perimeter_extrusion_width", this->config.layer_height.value);
    
    // In order to detect what regions of this layer need to be solid,
    // perform an intersection with layers within the requested shell thickness.
    Polygons internal = layer.slices;
    for (size_t j = 0; j < this->layers.size(); ++j) {
        const Layer &other = this->layers[j];
        if (abs(other.print_z - layer.print_z) > shell_thickness) continue;
    
        if (j == 0 || j == this->layers.size()-1) {
            internal.clear();
            break;
        } else if (i != j) {
            internal = intersection(internal, other.slices);
            if (internal.empty()) break;
        }
    }
    
    // If we have no internal infill, just print the whole layer as a solid slice.
    if (internal.empty()) return;
    layer.solid = false;
    
    const Polygons infill = offset(layer.slices, -scale_(shell_thickness));
    
    // Generate solid infill
    layer.solid_infill << diff_ex(infill, internal, true);
    
    // Generate internal infill
    {
        std::auto_ptr<Fill> fill(_fill->clone());
        fill->layer_id = i;
        fill->z        = layer.print_z;
        
        ExtrusionPath templ(erInternalInfill);
        templ.width = fill->spacing;
        const ExPolygons internal_ex = intersection_ex(infill, internal);
        for (ExPolygons::const_iterator it = internal_ex.begin(); it != internal_ex.end(); ++it) {
            Polylines polylines = fill->fill_surface(Surface(stInternal, *it));
            layer.infill.append(polylines, templ);
        }
    }
    
    // Generate perimeter(s).
    layer.perimeters << diff_ex(
        layer.slices,
        offset(layer.slices, -scale_(shell_thickness))
    );
}
예제 #10
0
bool REFERENCE::GetInventory(TES3MACHINE& machine, VPREFERENCE pref, VPLISTNODE& firststack)
{
	firststack= 0;
	
	VMPTR<TES3REFERENCE> ref(machine,pref);
	VMPTR<TES3TEMPLATE> templ(machine,ref->templ);

	if(isContainer(templ))
		firststack= templ->inventory.first;
	
	return true;
}
예제 #11
0
파일: factory.cpp 프로젝트: glftpd/ebftpd
util::Error Factory::Initialize()
{
  std::unique_ptr<Factory> factory(new Factory());
  
  auto textpath = fs::Path(cfg::Get().Datapath()) / "text";
  
  try
  {
    util::path::DirIterator it(textpath.ToString());
    util::path::DirIterator end;
   
    // let's get all error's in one go 
    int errors = 0;

    for (; it != end; ++it)
    {
      fs::Path p(*it);
      if (p.Extension() != "tmpl") continue;
      
      fs::Path file(textpath / p);
      std::string name = p.NoExtension(); 
      util::ToLower(name);

      try
      {
        TemplateParser templ(file.ToString());
        factory->templates.insert(std::make_pair(name, templ.Create()));
      }
      catch (const text::TemplateError& e)
      {
        logs::Error("Template Initialize error (%1%): %2%", *it, e.Message());
        ++errors;
      }
    }
    
    if (errors > 0)
    {
      std::ostringstream os;
      os << errors << " template errors. Please review errors above.";
      throw text::TemplateError(os.str());
    }
  }
  catch (const util::SystemError& e)
  {
    logs::Error("Unable to open template directory: %1%", e.Message());
    return util::Error::Failure(e.Message());
  }

  std::lock_guard<std::mutex> lock(mutex);
  instance = std::move(factory);
  return util::Error::Success();
}
예제 #12
0
	String Log::apply_template(ssh_wcs fn, ssh_wcs fl, int ln, int tp, ssh_wcs msg, ssh_wcs tpl) const
	{
		String tmp;
		String templ(tpl);
		static ssh_wcs m_types[] = {L"INFO", L"ASSERT", L"EXCEPTION", L"TRACE"};
		static ssh_wcs rpl[] = {L"$DT", L"$fn", L"$ln", L"$fl", L"$ms", L"$tm", L"$dt", L"$us", L"$cm", L"$nm", L"$tp", nullptr};
		tmp.fmt(L"%s\1%s\1%i\1%s\1%s\1%s\1%s\1%s\1%s\1%s\1%s\1\1",
				Time::current().fmt(L"$d.$m.$y"), fn, ln, fl, msg, Time::current().fmt(L"$h:$nm:$s"),
				Time::current().fmt(L"$d $MN)+ $Y ($dW)"), ssh_system_paths(SystemInfo::siUserName),
				ssh_system_paths(SystemInfo::siCompName), ssh_system_paths(SystemInfo::siNameProg), m_types[tp]);
		tmp.replace(L'\1', L'\0');
		return templ.replace(rpl, tmp);
	}
예제 #13
0
bool FUNCREFTYPE::execute(void)
{
	bool result= false;
	VMPTR<TES3REFERENCE*> pref(machine);
	VMPTR<TES3REFERENCE> ref(machine);
	VMPTR<TES3TEMPLATE> templ(machine);
	try
	{
		pref= (TES3REFERENCE**)reltolinear(SCRIPTTARGETREF_IMAGE);
		ref= *pref;
		templ= ref->templ;
		result= machine.push((VMREGTYPE)templ->type);
	}
	catch(...)
	{
		result= false;
	}
	
		
	return result;
}
예제 #14
0
int
cgi_JoinClub::ListAllPersonsClubs( ostream &os )
{
  vector<Person*>     svp;
  vector<Club*>       svc;
  HTMLTemplate         templ( "/web/kochut/public_html/JoinClub-PersonsClubs.html" );
  Person	      *p;
  Club		      *c;
  char		      *subs[2][2];
  strstream	       persons;
  strstream	       clubs;
  int i;

  try {

    // get persons
    //
    svp = ctrl_FindAllPersons::FindAllPersons();

    for( i = 0; i < svp.size(); i++ ) {

      p = (Person*) svp[ i ];

      persons << "<option value=\"" << p->get_SSN() << "\">"
	<< p->get_LastName() << ", "
	<< p->get_FirstName()
	<< "</option>\n";

    }

    subs[0][0] = "%PERSONS%";
    subs[0][1] = persons.str();

    // get clubs
    //
    svc = ctrl_FindAllClubs::FindAllClubs();

    for( i = 0; i < svc.size(); i++ ) {

      c = (Club*) svc[ i ];
      clubs << "<option>"
	<< c->get_Name() 
	<< "</option>\n";

    }

    subs[1][0] = "%CLUBS%";
    subs[1][1] = clubs.str();

    templ.Instantiate( cout, subs, 2 );

  }
  catch( ClubsException ce ) {

    HTMLTemplate         templ( "/web/kochut/public_html/JoinClub-Error.html" );

    subs[0][0] = "%REASON%";
    subs[0][1] = ce.get_Msg();

    templ.Instantiate( os, subs, 1 );

    return 0;

  }
  catch( HTMLTemplateException te ) {

    HTMLTemplate         templ( "/web/kochut/public_html/JoinClub-Error.html" );

    subs[0][0] = "%REASON%";
    subs[0][1] = te.get_Msg();

    templ.Instantiate( os, subs, 1 );

    return 0;

  }

  return 1;

}
예제 #15
0
int
cgi_JoinClub::JoinClub( ostream &os, char *ssn, char *club )
{
  HTMLTemplate    templ( "/web/kochut/public_html/JoinClub-Result.html" );
  char		 *subs[2][2];

  if ( ssn == NULL || club == NULL ) {

    HTMLTemplate         templ( "/web/kochut/public_html/JoinClub-Error.html" );

    subs[0][0] = "%REASON%";
    subs[0][1] = "Insufficient data was specified.";

    templ.Instantiate( os, subs, 1 );

    return 0;

  }
  
  try {

    // person with 'ssn' joins 'club'
    //
    ctrl_JoinClub::JoinClub( ssn, club );
      
    subs[0][0] = "%SSN%";
    subs[0][1] = ssn;
    subs[1][0] = "%CLUB%";
    subs[1][1] = club;

    templ.Instantiate( cout, subs, 2 );

  }
  catch( ClubsException ce ) {

    HTMLTemplate         templ( "/web/kochut/public_html/JoinClub-Error.html" );

    subs[0][0] = "%REASON%";
    subs[0][1] = ce.get_Msg();

    templ.Instantiate( os, subs, 1 );

    return 0;

  }
  catch( HTMLTemplateException te ) {

    HTMLTemplate         templ( "/web/kochut/public_html/JoinClub-Error.html" );

    subs[0][0] = "%REASON%";
    subs[0][1] = te.get_Msg();

    templ.Instantiate( os, subs, 1 );

    return 0;

  }

  return 1;

}
예제 #16
0
wxConfigBase* PROJECT::configCreate( const SEARCH_STACK& aSList, const wxString& aFileName,
            const wxString& aGroupName, bool aForceUseLocalConfig )
{
    wxConfigBase*   cfg = 0;

    wxFileName      fn = aFileName;
    fn.SetExt( ProjectFileExtension );

    wxString        cur_pro_fn = fn.GetFullPath();

    // is there an edge transition, a change in m_project_filename?
    if( m_project_name != cur_pro_fn )
    {
        m_sch_search.Clear();

        // to the empty lists, add project dir as first
        m_sch_search.AddPaths( fn.GetPath() );

        // append all paths from aSList
        add_search_paths( &m_sch_search, aSList, -1 );

        // addLibrarySearchPaths( SEARCH_STACK* aSP, wxConfigBase* aCfg )
        // This is undocumented, but somebody wanted to store !schematic!
        // library search paths in the .kicad_common file?
        add_search_paths( &m_sch_search, Pgm().CommonSettings(), -1 );

#if 1 && defined(DEBUG)
        m_sch_search.Show( __func__ );
#endif
    }

    // Init local config filename
    if( aForceUseLocalConfig || fn.FileExists() )
    {
        cfg = new wxFileConfig( wxEmptyString, wxEmptyString, cur_pro_fn, wxEmptyString );

        cfg->DontCreateOnDemand();

        if( aForceUseLocalConfig )
        {
            SetProjectFullName( cur_pro_fn );
            return cfg;
        }

        /* Check the application version against the version saved in the
         * project file.
         *
         * TODO: Push the version test up the stack so that when one of the
         *       KiCad application version changes, the other applications
         *       settings do not get updated.  Practically, this can go away.
         *       It isn't used anywhere as far as I know (WLS).
         */

        cfg->SetPath( aGroupName );

        int def_version = 0;
        int version = cfg->Read( wxT( "version" ), def_version );

        if( version > 0 )
        {
            cfg->SetPath( wxCONFIG_PATH_SEPARATOR );
            SetProjectFullName( cur_pro_fn );
            return cfg;
        }
        else    // Version incorrect
        {
            wxLogDebug( wxT( "Project file version is zero, not using this old project file, going with template." ) );
            delete cfg;
            cfg = 0;
        }
    }

    // No suitable pro file was found, either does not exist, or is too old.
    // Use the template kicad.pro file.  Find it by using caller's SEARCH_STACK.
    wxString templateFile = wxT( "kicad." ) + ProjectFileExtension;
    wxString kicad_pro_template = aSList.FindValidPath( templateFile );

    if( !kicad_pro_template )
    {
        wxLogDebug( wxT( "Template file <%s> not found using search paths." ),
                    GetChars( templateFile ) );

        wxFileName  templ( wxStandardPaths::Get().GetDocumentsDir(),
                            wxT( "kicad" ), ProjectFileExtension );

        if( !templ.IsFileReadable() )
        {
            wxString msg = wxString::Format( _( "Unable to find %s template config file." ),
                                             GetChars( templateFile ) );

            DisplayError( NULL, msg );

            return NULL;
        }

        kicad_pro_template = templ.GetFullPath();
    }

    // The project config file is not found (happens for new projects,
    // or if the schematic editor is run outside an existing project
    // In this case the default template (kicad.pro) is used
    cur_pro_fn = kicad_pro_template;
    wxLogDebug( wxT( "Use template file '%s' as project file." ), GetChars( cur_pro_fn ) );

    cfg = new wxFileConfig( wxEmptyString, wxEmptyString, cur_pro_fn, wxEmptyString );

    cfg->DontCreateOnDemand();

    SetProjectFullName( cur_pro_fn );
    return cfg;
}
예제 #17
0
bool SCgTranslateGWFToSc::translate(QIODevice &device, ScMemoryInterface *memory, const ScUri &set)
{
    mScMemory = memory;
    Q_ASSERT(mScMemory != 0);

    QScopedPointer<ScHelperInterface> helper(SCgPlugin::rootInterface()->scHelper(mScMemory));

    // read data from gwf
    GwfObjectInfoReader reader;
    if (!reader.read(&device))
    {
        qDebug() << "Error while translate to sc-code: " << reader.lastError();
        return false;
    }

    // iterate all objects and resolve them
    GwfObjectInfoReader::TypeToObjectsMap::const_iterator it;
    for (it = reader.objectsInfo().begin(); it != reader.objectsInfo().end(); ++it)
    {
        GwfObjectInfoReader::ObjectInfoList::const_iterator it_info;
        for (it_info = (*it).begin(); it_info != (*it).end(); ++it_info)
            resolveObject(*it_info);
    }

    // setup pair begin and end objects
    const GwfObjectInfoReader::ObjectInfoList &list = reader.objectsInfo()[SCgVisualObject::SCgPairType];
    GwfObjectInfoReader::ObjectInfoList::const_iterator it_info;
    for (it_info = list.begin(); it_info != list.end(); ++it_info)
    {
        SCgPairInfo *pairInfo = static_cast<SCgPairInfo*>(*it_info);
        ScUri pair_uri = mIdToScUri[pairInfo->id()];

        // get begin and end uri's
        ScUri b = mIdToScUri[pairInfo->beginObjectId()];
        ScUri e = mIdToScUri[pairInfo->endObjectId()];

        // setup begin and end
        mScMemory->set_beg(pair_uri, b);
        mScMemory->set_end(pair_uri, e);
    }

    // append objects into parent sets
    for (it = reader.objectsInfo().begin(); it != reader.objectsInfo().end(); ++it)
        for (it_info = (*it).begin(); it_info != (*it).end(); ++it_info)
        {
            SCgObjectInfo *info = *it_info;

            // check if object has a parent
            if (info->parentId() != "0" && !info->parentId().isEmpty())
            {
                ScUri uri = mIdToScUri[info->id()];
                ScUri parent = mIdToScUri[info->parentId()];

                // generate 5 elements construction to append new arc between parent and child into output set
                ScUriVector res;
                ScTemplate templ(parent,
                                 ScElementType(ScArcMain | ScConst | ScPos),
                                 uri,
                                 ScElementType(ScArcMain | ScConst | ScPos),
                                 set);

                if (!helper->genElStr(templ, res))
                    SuiExcept(SuiExceptionInternalError,
                              QString("Can't append '%1' into '%1'").arg(uri.value()).arg(parent.value()),
                              "bool SCgTranslateGWFToSc::translate(QIODevice &device, ScMemoryInterface *memory, const ScUri &set)");
            }
        }

    // append all translated objects into output set
    ScUriList::iterator it_list;
    ScUriVector res;
    for (it_list = mTranslatedObjects.begin(); it_list != mTranslatedObjects.end(); ++it_list)
        if (!helper->genElStr(ScTemplate() << set << ScElementType(ScArcMain | ScConst| ScPos) << *it_list, res))
            SuiExcept(SuiExceptionInternalError,
                      QString("Can't append '%1 into output set '%2").arg((*it_list).value()).arg(set.value()),
                      "bool SCgTranslateGWFToSc::translate(QIODevice &device, ScMemoryInterface *memory, const ScUri &set)");


    return true;
}
예제 #18
0
/// The LayerRegion at this point of time may contain
/// surfaces of various types (internal/bridge/top/bottom/solid).
/// The infills are generated on the groups of surfaces with a compatible type.
/// Fills an array of ExtrusionPathCollection objects containing the infills generated now
/// and the thin fills generated by generate_perimeters().
void
LayerRegion::make_fill()
{
    this->fills.clear();
    
    const double fill_density          = this->region()->config.fill_density;
    const Flow   infill_flow           = this->flow(frInfill);
    const Flow   solid_infill_flow     = this->flow(frSolidInfill);
    const Flow   top_solid_infill_flow = this->flow(frTopSolidInfill);
    const coord_t perimeter_spacing    = this->flow(frPerimeter).scaled_spacing();

    SurfaceCollection surfaces;
    
    // merge adjacent surfaces
    // in case of bridge surfaces, the ones with defined angle will be attached to the ones
    // without any angle (shouldn't this logic be moved to process_external_surfaces()?)
    {
        Polygons polygons_bridged;
        polygons_bridged.reserve(this->fill_surfaces.surfaces.size());
        for (Surfaces::const_iterator it = this->fill_surfaces.surfaces.begin(); it != this->fill_surfaces.surfaces.end(); ++it)
            if (it->is_bridge() && it->bridge_angle >= 0)
                append_to(polygons_bridged, (Polygons)*it);
        
        // group surfaces by distinct properties (equal surface_type, thickness, thickness_layers, bridge_angle)
        // group is of type SurfaceCollection
        // FIXME: Use some smart heuristics to merge similar surfaces to eliminate tiny regions.
        std::vector<SurfacesConstPtr> groups;
        this->fill_surfaces.group(&groups);
        
        // merge compatible solid groups (we can generate continuous infill for them)
        {
            // cache flow widths and patterns used for all solid groups
            // (we'll use them for comparing compatible groups)
            std::vector<SurfaceGroupAttrib> group_attrib(groups.size());
            for (size_t i = 0; i < groups.size(); ++i) {
                const Surface &surface = *groups[i].front();
                // we can only merge solid non-bridge surfaces, so discard
                // non-solid or bridge surfaces
                if (!surface.is_solid() || surface.is_bridge()) continue;
                
                group_attrib[i].is_solid = true;
                group_attrib[i].fw = (surface.is_top()) ? top_solid_infill_flow.width : solid_infill_flow.width;
                group_attrib[i].pattern = surface.is_top() ? this->region()->config.top_infill_pattern.value
                    : surface.is_bottom() ? this->region()->config.bottom_infill_pattern.value
                    : ipRectilinear;
            }
            // Loop through solid groups, find compatible groups and append them to this one.
            for (size_t i = 0; i < groups.size(); ++i) {
                if (!group_attrib[i].is_solid)
                    continue;
                for (size_t j = i + 1; j < groups.size();) {
                    if (group_attrib[i] == group_attrib[j]) {
                        // groups are compatible, merge them
                        append_to(groups[i], groups[j]);
                        groups.erase(groups.begin() + j);
                        group_attrib.erase(group_attrib.begin() + j);
                    } else {
                        ++j;
                    }
                }
            }
        }
        
        // Give priority to oriented bridges. Process the bridges in the first round, the rest of the surfaces in the 2nd round.
        for (size_t round = 0; round < 2; ++ round) {
            for (std::vector<SurfacesConstPtr>::const_iterator it_group = groups.begin(); it_group != groups.end(); ++ it_group) {
                const SurfacesConstPtr &group = *it_group;
                const bool is_oriented_bridge = group.front()->is_bridge() && group.front()->bridge_angle >= 0;
                if (is_oriented_bridge != (round == 0))
                    continue;
                
                // Make a union of polygons defining the infiill regions of a group, use a safety offset.
                Polygons union_p = union_(to_polygons(group), true);
                
                // Subtract surfaces having a defined bridge_angle from any other, use a safety offset.
                if (!is_oriented_bridge && !polygons_bridged.empty())
                    union_p = diff(union_p, polygons_bridged, true);
                
                // subtract any other surface already processed
                //FIXME Vojtech: Because the bridge surfaces came first, they are subtracted twice!
                surfaces.append(
                    diff_ex(union_p, to_polygons(surfaces), true),
                    *group.front()  // template
                );
            }
        }
    }
    
    // we need to detect any narrow surfaces that might collapse
    // when adding spacing below
    // such narrow surfaces are often generated in sloping walls
    // by bridge_over_infill() and combine_infill() as a result of the
    // subtraction of the combinable area from the layer infill area,
    // which leaves small areas near the perimeters
    // we are going to grow such regions by overlapping them with the void (if any)
    // TODO: detect and investigate whether there could be narrow regions without
    // any void neighbors
    {
        coord_t distance_between_surfaces = std::max(
            std::max(infill_flow.scaled_spacing(), solid_infill_flow.scaled_spacing()),
            top_solid_infill_flow.scaled_spacing()
        );
        
        Polygons surfaces_polygons = (Polygons)surfaces;
        Polygons collapsed = diff(
            surfaces_polygons,
            offset2(surfaces_polygons, -distance_between_surfaces/2, +distance_between_surfaces/2),
            true
        );
            
        Polygons to_subtract;
        surfaces.filter_by_type((stInternal | stVoid), &to_subtract);
                
        append_to(to_subtract, collapsed);
        surfaces.append(
            intersection_ex(
                offset(collapsed, distance_between_surfaces),
                to_subtract,
                true
            ),
            (stInternal | stSolid)
        );
    }

    if (false) {
//        require "Slic3r/SVG.pm";
//        Slic3r::SVG::output("fill_" . $layerm->print_z . ".svg",
//            expolygons      => [ map $_->expolygon, grep !$_->is_solid, @surfaces ],
//            red_expolygons  => [ map $_->expolygon, grep  $_->is_solid, @surfaces ],
//        );
    }

    for (Surfaces::const_iterator surface_it = surfaces.surfaces.begin();
        surface_it != surfaces.surfaces.end(); ++surface_it) {
        
        const Surface &surface = *surface_it;
        if (surface.surface_type == (stInternal | stVoid))
            continue;
        
        InfillPattern fill_pattern = this->region()->config.fill_pattern.value;
        double density = fill_density;
        FlowRole role = (surface.is_top()) ? frTopSolidInfill
            : surface.is_solid() ? frSolidInfill
            : frInfill;
        const bool is_bridge = this->layer()->id() > 0 && surface.is_bridge();
        
        if (surface.is_solid()) {
            density = 100.;
            fill_pattern = (surface.is_top()) ? this->region()->config.top_infill_pattern.value
                : (surface.is_bottom() && !is_bridge) ? this->region()->config.bottom_infill_pattern.value
                : ipRectilinear;
        } else if (density <= 0)
            continue;
        
        // get filler object
        #if SLIC3R_CPPVER >= 11
            std::unique_ptr<Fill> f = std::unique_ptr<Fill>(Fill::new_from_type(fill_pattern));
        #else
            std::auto_ptr<Fill> f = std::auto_ptr<Fill>(Fill::new_from_type(fill_pattern));
        #endif
        
        // switch to rectilinear if this pattern doesn't support solid infill
        if (density > 99 && !f->can_solid())
            #if SLIC3R_CPPVER >= 11
                f = std::unique_ptr<Fill>(Fill::new_from_type(ipRectilinear));
            #else
                f = std::auto_ptr<Fill>(Fill::new_from_type(ipRectilinear));
            #endif
        
        f->bounding_box = this->layer()->object()->bounding_box();
        
        // calculate the actual flow we'll be using for this infill
        coordf_t h = (surface.thickness == -1) ? this->layer()->height : surface.thickness;
        Flow flow = this->region()->flow(
            role,
            h,
            is_bridge || f->use_bridge_flow(),  // bridge flow?
            this->layer()->id() == 0,           // first layer?
            -1,                                 // auto width
            *this->layer()->object()
        );
        
        // calculate flow spacing for infill pattern generation
        bool using_internal_flow = false;
        if (!surface.is_solid() && !is_bridge) {
            // it's internal infill, so we can calculate a generic flow spacing
            // for all layers, for avoiding the ugly effect of
            // misaligned infill on first layer because of different extrusion width and
            // layer height
            Flow internal_flow = this->region()->flow(
                frInfill,
                h,  // use the calculated surface thickness here for internal infill instead of the layer height to account for infill_every_layers
                false,  // no bridge
                false,  // no first layer
                -1,     // auto width
                *this->layer()->object()
            );
            f->min_spacing = internal_flow.spacing();
            using_internal_flow = true;
        } else {
            f->min_spacing = flow.spacing();
        }
        
        f->endpoints_overlap = scale_(this->region()->config.get_abs_value("infill_overlap",
            (unscale(perimeter_spacing) + (f->min_spacing))/2));
        f->layer_id = this->layer()->id();
        f->z        = this->layer()->print_z;
        f->angle    = Geometry::deg2rad(this->region()->config.fill_angle.value);
        
        // Maximum length of the perimeter segment linking two infill lines.
        f->link_max_length = (!is_bridge && density > 80)
            ? scale_(3 * f->min_spacing)
            : 0;
        
        // Used by the concentric infill pattern to clip the loops to create extrusion paths.
        f->loop_clipping = scale_(flow.nozzle_diameter) * LOOP_CLIPPING_LENGTH_OVER_NOZZLE_DIAMETER;
        
        // apply half spacing using this flow's own spacing and generate infill
        f->density = density/100;
        f->dont_adjust = false;
        /*
        std::cout << surface.expolygon.dump_perl() << std::endl
            << " layer_id: " << f->layer_id << " z: " << f->z
            << " angle: " << f->angle << " min-spacing: " << f->min_spacing
            << " endpoints_overlap: " << f->endpoints_overlap << std::endl << std::endl;
        */
        Polylines polylines = f->fill_surface(surface);
        if (polylines.empty())
            continue;

        // calculate actual flow from spacing (which might have been adjusted by the infill
        // pattern generator)
        if (using_internal_flow) {
            // if we used the internal flow we're not doing a solid infill
            // so we can safely ignore the slight variation that might have
            // been applied to f->spacing()
        } else {
            flow = Flow::new_from_spacing(f->spacing(), flow.nozzle_diameter, h, is_bridge || f->use_bridge_flow());
        }

        // Save into layer.
        ExtrusionEntityCollection* coll = new ExtrusionEntityCollection();
        coll->no_sort = f->no_sort();
        this->fills.entities.push_back(coll);
        
        {
            ExtrusionRole role;
            if (is_bridge) {
                role = erBridgeInfill;
            } else if (surface.is_solid()) {
                role = (surface.is_top()) ? erTopSolidInfill : erSolidInfill;
            } else {
                role = erInternalInfill;
            }
            
            ExtrusionPath templ(role);
            templ.mm3_per_mm    = flow.mm3_per_mm();
            templ.width         = flow.width;
            templ.height        = flow.height;
            
            coll->append(STDMOVE(polylines), templ);
        }
    }

    // add thin fill regions
    // thin_fills are of C++ Slic3r::ExtrusionEntityCollection, perl type Slic3r::ExtrusionPath::Collection
    // Unpacks the collection, creates multiple collections per path so that they will
    // be individually included in the nearest neighbor search.
    // The path type could be ExtrusionPath, ExtrusionLoop or ExtrusionEntityCollection.
    for (ExtrusionEntitiesPtr::const_iterator thin_fill = this->thin_fills.entities.begin(); thin_fill != this->thin_fills.entities.end(); ++ thin_fill) {
        ExtrusionEntityCollection* coll = new ExtrusionEntityCollection();
        this->fills.entities.push_back(coll);
        coll->append(**thin_fill);
    }
}
예제 #19
0
bool Robot::adjustWorldCoordinate(IplImage* image, double coordAdjustRate)
{
    IplImage *img;
    IplImage* src1=cvCreateImage(cvGetSize(image),IPL_DEPTH_8U,1);
    if(image->nChannels==3)
    {
        IplImage *hsv_img = get_hsv(image);
        img=worldMap.getField(hsv_img);
        cvReleaseImage(&hsv_img);
        src1=img;
    }
    else
    {
        img=image;
        src1=img;
            //cvCvtColor(img, src1, CV_BGR2GRAY);
    }
		if( img != 0 )
		{
			IplImage* dst = cvCreateImage( cvGetSize(img), 8, 1 );
			IplImage* color_dst = cvCreateImage( cvGetSize(img), 8, 3 );
			CvMemStorage* storage = cvCreateMemStorage(0);
			CvSeq* ls = 0;
			int i;
			cvCanny( src1, dst, 50, 200, 3 );

			cvCvtColor( dst, color_dst, CV_GRAY2BGR );

			ls = cvHoughLines2( dst, storage, CV_HOUGH_PROBABILISTIC, 2, CV_PI/90, 20, 5, 30 );
			//ls = cvHoughLines2( dst, storage, CV_HOUGH_PROBABILISTIC, 5, CV_PI/30, 10, 20, 5 );
			vector<myLine> tmplines;
			for( i = 0; i < ls->total; i++ )
			{
				CvPoint* tmpl = (CvPoint*)cvGetSeqElem(ls,i);
				cvLine( color_dst, tmpl[0], tmpl[1], CV_RGB(255,0,0), 1, 8 );

                cv::Point2f tmpp[2];
                cv::Point2f scrPos(tmpl[0].x,tmpl[0].y);
                cv::Point2f roboPos=worldMap.coord_screen2robot(scrPos,true);
                cv::Point2f worldPos=worldMap.coord_robot2world(roboPos);
                tmpp[0]=worldPos;
                scrPos=cv::Point2f(tmpl[1].x,tmpl[1].y);
                roboPos=worldMap.coord_screen2robot(scrPos,true);
                worldPos=worldMap.coord_robot2world(roboPos);
                tmpp[1]=worldPos;
                myLine templ(tmpp[0],tmpp[1]);
                if(templ.l>LINE_LENGTH_LBOUND)
                    tmplines.push_back(templ);
//				//printf("length=%f angle=%f\n",sqrt(float((tmpl[1].y-tmpl[0].y)*(tmpl[1].y-tmpl[0].y));
				//	+float((tmpl[1].x-tmpl[0].x)*(tmpl[1].x-tmpl[0].x)))
				//	,atan2(float(tmpl[1].y-tmpl[0].y),float(tmpl[1].x-tmpl[0].x)));
			}
			//printf("\n");
			cvNamedWindow( "Source", 1 );
			cvShowImage( "Source", img );

			cvNamedWindow( "Hough", 1 );
			cvShowImage( "Hough", color_dst );

			cvWaitKey(10);
			cvReleaseImage(&dst);
			cvReleaseImage(&src1);
			cvReleaseImage(&color_dst);
			cvReleaseMemStorage(&storage);
			if(coordAdjustRate==0)
			{
                for(i=0;i<tmplines.size();++i)
                {
                    lines.push_back(tmplines[i]);
                }
			}
			else if(coordAdjustRate==2)
			{
                for(i=0;i<tmplines.size();++i)
                {
                    lines.push_back(tmplines[i]);
                }
                //vector<double> oris;
                vector<int> lineNums;
                vector<double> lineValues;
                int groupId=0;
			    for(i=0;i<lines.size();++i)
			    {
			        bool classified=false;
			        int j;
			        for(j=0;j<i;++j)
			        {
			            double angle=lines[i].theta-lines[j].theta+CV_PI/4.0;   //to make the process simple, add 45 degree
                                                                                //to turn the cared angles to the middle of a phase
			            if(angle<0)
                            angle+=CV_PI*2.0;
			            int phase=(int)(angle/(CV_PI/2.0));
			            double angle90=angle-CV_PI/2.0*(double)phase;
			            phase%=2;
			            if(abs(angle90-CV_PI/4.0)<CV_PI/60.0)//subtract the added 45 degree
			            {
			                lines[i].clsId=lines[j].clsId/2*2+phase;
			                ++lineNums[lines[i].clsId];
			                lineValues[lines[i].clsId]+=lines[i].l;
			                classified=true;
			                break;
			            }
			        }
			        if(classified==false)
			        {
			            lines[i].clsId=groupId;
                        lineNums.push_back(1);
                        lineNums.push_back(0);
                        lineValues.push_back(lines[i].l);
                        lineValues.push_back(0);
			            groupId+=2;
			        }
			    }
			    int maxValueGroup=0;
			    double maxValue=0;
			    for(i=0;i<lineNums.size();i+=2)
			    {
			        if(lineValues[i]+lineValues[i+1]>maxValue)
			        {
			            maxValue=lineValues[i]+lineValues[i+1];
			            maxValueGroup=i;
			        }
			    }
			    maxValueGroup/=2;
			    double sumAngle=0;
			    double sumL=0;
			    for(i=0;i<lines.size();++i)
			    {
			        if(lines[i].clsId/2==maxValueGroup)
			        {
			            double angle=lines[i].theta+CV_PI/4.0;//similar strategy, add 45 degree
			            if(angle<0)
                            angle+=CV_PI*2.0;
			            double angle90=angle-CV_PI/2.0*(double)((int)(angle/(CV_PI/2.0)));
			            sumAngle+=(angle90-CV_PI/4.0)*lines[i].l;//subtract 45 degree
			            sumL+=lines[i].l;
			        }
			    }
			    if(sumL==0)
			    {
                    //printf("false 2 sumL=0\n");
			        return false;
			    }
			    mainAngle=sumAngle/sumL;
			    mainGroupId=maxValueGroup;
			    //printf("mainAngle=%f mainGroupId=%d\n",mainAngle,mainGroupId);
			}
			else if(coordAdjustRate==1)
            {
                CvRect bBox=worldMap.getMap_bbox();
                    //printf("in func param=1\n");
                    //printf("tmplines.size=%d\n",tmplines.size());
                for(i=0;i<tmplines.size();++i)
                {
                    cv::Point2f imgPos=world2image(tmplines[i].p[0]);
                    if(!(imgPos.x>bBox.x-BBOX_DELTA && imgPos.x<bBox.x+bBox.width+BBOX_DELTA && imgPos.y>bBox.y-BBOX_DELTA && imgPos.y<bBox.y+bBox.height+BBOX_DELTA))
                        continue;
			        bool classified=false;
			        double minAngle=CV_PI;
			        int minAnglePhase=0;
			        int bestJ=-1;
			        int j;
			        for(j=0;j<lines.size();++j)
			        {
			            if(lines[j].clsId/2!=mainGroupId)
                            continue;
			            double angle=tmplines[i].theta-lines[j].theta+CV_PI/4.0;   //to make the process simple, add 45 degree
                                                                                //to turn the cared angles to the middle of a phase
			            if(angle<0)
                            angle+=CV_PI*2.0;
			            int phase=(int)(angle/(CV_PI/2.0));
			            double angle90=angle-CV_PI/2.0*(double)phase;
			            phase%=2;
			            if(abs(angle90-CV_PI/4.0)<minAngle)//subtract the added 45 degree
			            {
			                minAngle=abs(angle90-CV_PI/4.0);
			                bestJ=j;
                                minAnglePhase=phase;
			            }
			        }
			        if(bestJ>-1)
			        {
			            //if(minAngle<CV_PI/6.0)
                        tmplines[i].clsId=mainGroupId*2+minAnglePhase;
                        classified=true;
                        //printf("nearest main ori found. angle diff=%f\n",minAngle);
			        }
			    }
			    double sumAngle=0;
			    double sumL=0;
			    for(i=0;i<tmplines.size();++i)
			    {
			        if(tmplines[i].clsId/2==mainGroupId)
			        {
                    //printf("comparing with a main line..i=%d\n",i);
			            double angle=tmplines[i].theta+CV_PI/4.0;//similar strategy, add 45 degree
			            if(angle<0)
                            angle+=CV_PI*2.0;
			            double angle90=angle-CV_PI/2.0*double((int)(angle/(CV_PI/2.0)));
			            sumAngle+=angle90*tmplines[i].l;//use the 45 degree to balance the unwanted lines
			            sumL+=tmplines[i].l;
			        }
			    }
			    if(sumL<LINE_LENGTH_SUM_LBOUND)
			    {
                    //printf("false sumL=%f<%d\n",sumL,LINE_LENGTH_SUM_LBOUND);
			        return false;
			    }
			    double curAngle=sumAngle/sumL-CV_PI/4.0;//subtract 45 degree
			    ori+=curAngle-mainAngle;
                    //printf("true oriChange=%f\n",curAngle-mainAngle);
            }
		}

    return true;
}