Exemple #1
0
void CODEGeom::set_position(const Fvector& /*ref_point*/)
{
	dGeomUserDataResetLastPos(geom());
}
Exemple #2
0
void mean::entry()
{
  sc_signed i(24);  // Will hold input a
  sc_signed j(24);  // Will hold input b
  sc_signed k(24);  // Will hold input c
  sc_signed l(24);  // Will hold input d

  sc_signed arith(24);    // Arithmetic mean
  sc_signed geom(24);     // Geometric mean
  sc_signed harmonic(24); // Harmonic mean

  while (true) {
    // read all inputs
    do { wait(); } while (input_available != true);
    send_data.write(true);
    do { wait(); } while (input_available != false);
    i = in.read().to_int();
    send_data.write(false);

    do { wait(); } while (input_available != true);
    send_data.write(true);
    do { wait(); } while (input_available != false);
    j = in.read().to_int();
    send_data.write(false);

    do { wait(); } while (input_available != true);
    send_data.write(true);
    do { wait(); } while (input_available != false);
    k = in.read().to_int();
    send_data.write(false);

    do { wait(); } while (input_available != true);
    send_data.write(true);
    do { wait(); } while (input_available != false);
    l = in.read().to_int();
    send_data.write(false);
    wait();

    // Calculate arithmetic mean
    arith = (i + j + k + l) / 4;
    // Calculate geometric mean
    calculate_geometric_mean(i, j, k, l, geom);
    // Calculate harmonic mean
    calculate_harmonic_mean(i, j, k, l, harmonic);

    // write all outputs
    output_ready.write(true);
    do { wait(); } while (receiver_ready != true);
    output_ready.write(false);
    out.write(arith);
    do { wait(); } while (receiver_ready != false);

    output_ready.write(true);
    do { wait(); } while (receiver_ready != true);
    output_ready.write(false);
    out.write(geom);
    do { wait(); } while (receiver_ready != false);


    output_ready.write(true);
    do { wait(); } while (receiver_ready != true);
    output_ready.write(false);
    out.write(harmonic);
    do { wait(); } while (receiver_ready != false);
  }
} // end of entry function
Exemple #3
0
void CODEGeom::get_local_form_bt(Fmatrix& form)
{
	PHDynamicData::DMXPStoFMX(dGeomGetRotation(geom()),dGeomGetPosition(geom()),form);
}
void LineDomain::snap_to( Mesh::VertexHandle ,
                          Vector3D &coordinate) const
  { coordinate = geom().point(geom().closest( coordinate )); }
Exemple #5
0
void CircleDomain::snap_to( Mesh::VertexHandle ,
                            Vector3D &coordinate) const
  { coordinate = geom().closest( coordinate ); }
QByteArray KstViewObjectImageDrag::encodedData(const char *mimeType) const {
  if (!_mimeTypes.contains(QString::fromLatin1(mimeType))) {
    return QByteArray();
  }

  QRect geom(0, 0, 0, 0);
  for (KstViewObjectList::ConstIterator i = _objects.begin(); i != _objects.end(); ++i) {
    geom = geom.unite((*i)->geometry());
  }

  QPixmap pm;
  pm.resize(geom.size());
  pm.fill();

  int prog = 0;
  bool cancelled = false;
  KstPainter p(KstPainter::P_EXPORT);
  p.begin(&pm);
  p.setClipping(true);
  KProgressDialog *dlg = new KProgressDialog(0, 0, QString::null, i18n("Generating and storing images of objects..."), true);
  dlg->setAllowCancel(true);
  dlg->progressBar()->setTotalSteps(_objects.count());
  dlg->progressBar()->setValue(prog);
  dlg->show();

  for (KstViewObjectList::Iterator i = _objects.begin(); i != _objects.end(); ++i) {
    p.setClipRect((*i)->geometry());
    p.setViewport((*i)->geometry());
    (*i)->paint(p, QRegion());
    if (dlg->wasCancelled()) {
      cancelled = true;
      break;
    }
    dlg->progressBar()->setValue(++prog);
    kapp->eventLoop()->processEvents(QEventLoop::ExcludeSocketNotifiers);
  }
  p.end();

  delete dlg;

  if (cancelled) {
    return QByteArray();
  }

  QByteArray rc;
#if QT_VERSION < 0x030200
  KTempFile tf;
  pm.save(tf.name(), KImageIO::typeForMime(mimeType).latin1());
  tf.close();
  QFile f(tf.name());
  if (f.open(IO_ReadOnly)) {
    rc = f.readAll();
    f.close();
  }
  QFile::remove(tf.name());
#else
  QDataStream ds(rc, IO_WriteOnly);
  pm.save(ds.device(), KImageIO::typeForMime(mimeType).latin1());
#endif

  return rc;
}
Exemple #7
0
HelpWindow::HelpWindow(QWidget *parent) :
    QMainWindow(parent),
    mActionGoMainPage(new QAction(tr("Home"), this)),
    mActionBackward(new QAction(tr("Backward"), this)),
    mActionForward(new QAction(tr("Forward"), this)),
    mHelpEngine(new QHelpEngine(settingsObj.getPath(MSUSettings::PATH_SHARE_HELP) + "msuproj-qt.qhc", this)),
    mPageWidget(new HelpBrowser(mHelpEngine, this))
{
    QByteArray geom(settingsObj.getGeometry(MSUSettings::HELPWINDOW));
    if (geom.size() > 0)
    {
        this->restoreGeometry(geom);
        this->restoreState(settingsObj.getState(MSUSettings::HELPWINDOW));
    }
    else
        this->resize(900, 600);
    this->setContentsMargins(5, 0, 5, 5);
    this->setCentralWidget(mPageWidget);

    bool errorLoadingHelp = true;
    if (mHelpEngine->setupData())
    {
        locale = settingsObj.getLocale();
        if (!mHelpEngine->filterAttributes().contains(locale) ||
            !QFile(mHelpEngine->documentationFileName("amigos.msuproj-qt." + locale)).exists())
            locale = "en";

        if(QFile(mHelpEngine->documentationFileName("amigos.msuproj-qt." + locale)).exists())
        {
            errorLoadingHelp = false;
            mHelpEngine->setCurrentFilter(locale);

            QToolBar *navigationBar = new QToolBar(tr("Navigation"), this);
            navigationBar->setObjectName("HelpWindowNavBar");
            navigationBar->addActions({mActionGoMainPage, mActionBackward, mActionForward});
            this->addToolBar(navigationBar);

            QDockWidget *contentsDockWidget = new QDockWidget(tr("Contents"), this);
            contentsDockWidget->setObjectName("HelpWindowContentsDock");
            contentsDockWidget->setFeatures(QDockWidget::NoDockWidgetFeatures);
            this->addDockWidget(Qt::LeftDockWidgetArea, contentsDockWidget);

            QHelpContentWidget *contentWidget = mHelpEngine->contentWidget();
            contentsDockWidget->setWidget(contentWidget);

            connect(contentWidget, &QHelpContentWidget::clicked, this, &HelpWindow::setPage);
            connect(this, &HelpWindow::contentChange, mPageWidget, &HelpBrowser::setSource);

            connect(mPageWidget, &HelpBrowser::backwardAvailable, mActionBackward, &QAction::setEnabled);
            connect(mActionBackward, &QAction::triggered, mPageWidget, &HelpBrowser::backward);

            connect(mPageWidget, &HelpBrowser::forwardAvailable, mActionForward, &QAction::setEnabled);
            connect(mActionForward, &QAction::triggered, mPageWidget, &HelpBrowser::forward);

            connect(mActionGoMainPage, &QAction::triggered, this, &HelpWindow::goMainPage);

            connect(mPageWidget, &HelpBrowser::anchorClicked, this, &HelpWindow::setCurrentContentIndex);
            connect(mActionBackward, &QAction::triggered, this, &HelpWindow::setCurrentContentIndex);
            connect(mActionForward, &QAction::triggered, this, &HelpWindow::setCurrentContentIndex);

            this->goMainPage();
        }
    }

    if (errorLoadingHelp)
        mPageWidget->setHtml(QString("<html><head/><body><p align=\"center\"><span style=\" font-size:16pt; font-weight:600;\">%1</span></p>"
                                     "<p align=\"center\">%2</p></body></html>")
                             .arg(tr("Error loading help files."),
                                  tr("Could not load help files. Have You installed the MSUProj-Qt Help package?")));
}
void QgsGeometryCheckerResultTab::highlightErrors( bool current )
{
  qDeleteAll( mCurrentRubberBands );
  mCurrentRubberBands.clear();

  QList<QTableWidgetItem *> items;
  QVector<QgsPointXY> errorPositions;
  QgsRectangle totextent;

  if ( current )
  {
    items.append( ui.tableWidgetErrors->currentItem() );
  }
  else
  {
    items.append( ui.tableWidgetErrors->selectedItems() );
  }
  for ( QTableWidgetItem *item : items )
  {
    QgsGeometryCheckError *error = ui.tableWidgetErrors->item( item->row(), 0 )->data( Qt::UserRole ).value<QgsGeometryCheckError *>();

    const QgsAbstractGeometry *geometry = error->geometry();
    if ( ui.checkBoxHighlight->isChecked() && geometry )
    {
      QgsRubberBand *featureRubberBand = new QgsRubberBand( mIface->mapCanvas() );
      QgsGeometry geom( geometry->clone() );
      featureRubberBand->addGeometry( geom, nullptr );
      featureRubberBand->setWidth( 5 );
      featureRubberBand->setColor( Qt::yellow );
      mCurrentRubberBands.append( featureRubberBand );
    }

    if ( ui.radioButtonError->isChecked() || current || error->status() == QgsGeometryCheckError::StatusFixed )
    {
      QgsRubberBand *pointRubberBand = new QgsRubberBand( mIface->mapCanvas(), QgsWkbTypes::PointGeometry );
      pointRubberBand->addPoint( error->location() );
      pointRubberBand->setWidth( 20 );
      pointRubberBand->setColor( Qt::red );
      mCurrentRubberBands.append( pointRubberBand );
      errorPositions.append( error->location() );
    }
    else if ( ui.radioButtonFeature->isChecked() )
    {
      QgsRectangle geomextent = error->affectedAreaBBox();
      if ( totextent.isEmpty() )
      {
        totextent = geomextent;
      }
      else
      {
        totextent.combineExtentWith( geomextent );
      }
    }
  }

  // If error positions positions are marked, pan to the center of all positions,
  // and zoom out if necessary to make all points fit.
  if ( !errorPositions.isEmpty() )
  {
    double cx = 0., cy = 0.;
    QgsRectangle pointExtent( errorPositions.first(), errorPositions.first() );
    Q_FOREACH ( const QgsPointXY &p, errorPositions )
    {
      cx += p.x();
      cy += p.y();
      pointExtent.include( p );
    }
Exemple #9
0
int main(int argc, char* argv[]) {
  gflags::SetUsageMessage("[options] full_path_to_urdf_or_sdf_file");
  gflags::ParseCommandLineFlags(&argc, &argv, true);
  if (argc < 2) {
    gflags::ShowUsageWithFlags(argv[0]);
    return 1;
  }
  logging::HandleSpdlogGflags();

  // todo: consider moving this logic into the RigidBodySystem class so it can
  // be reused
  FloatingBaseType floating_base_type = kQuaternion;
  if (FLAGS_base == "kFixed") {
    floating_base_type = kFixed;
  } else if (FLAGS_base == "RPY") {
    floating_base_type = kRollPitchYaw;
  } else if (FLAGS_base == "QUAT") {
    floating_base_type = kQuaternion;
  } else {
    throw std::runtime_error(string("Unknown base type") + FLAGS_base +
                             "; must be kFixed, RPY, or QUAT");
  }

  auto rigid_body_sys = make_shared<RigidBodySystem>();
  rigid_body_sys->AddModelInstanceFromFile(argv[argc - 1], floating_base_type);
  auto const& tree = rigid_body_sys->getRigidBodyTree();

  if (FLAGS_add_flat_terrain) {
    SPDLOG_TRACE(drake::log(), "adding flat terrain");
    double box_width = 1000;
    double box_depth = 10;
    DrakeShapes::Box geom(Vector3d(box_width, box_width, box_depth));
    Isometry3d T_element_to_link = Isometry3d::Identity();
    T_element_to_link.translation() << 0, 0,
        -box_depth / 2;  // top of the box is at z=0
    RigidBody& world = tree->world();
    Vector4d color;
    color << 0.9297, 0.7930, 0.6758,
        1;  // was hex2dec({'ee','cb','ad'})'/256 in matlab
    world.AddVisualElement(
        DrakeShapes::VisualElement(geom, T_element_to_link, color));
    tree->addCollisionElement(
        DrakeCollision::Element(geom, T_element_to_link, &world), world,
        "terrain");
    tree->updateStaticCollisionElements();
  }

  shared_ptr<lcm::LCM> lcm = make_shared<lcm::LCM>();
  auto visualizer =
      make_shared<BotVisualizer<RigidBodySystem::StateVector>>(lcm, tree);
  auto sys = cascade(rigid_body_sys, visualizer);

  SimulationOptions options;
  options.realtime_factor = 1.0;
  options.timeout_seconds = std::numeric_limits<double>::infinity();
  options.initial_step_size = 5e-3;

  runLCM(sys, lcm, 0, std::numeric_limits<double>::infinity(),
         getInitialState(*sys), options);
  //  simulate(*sys, 0, std::numeric_limits<double>::max(),
  //  getInitialState(*sys), options);

  return 0;
}
Exemple #10
0
void Gizmo::renderTranslateGizmo(Pipeline& pipeline)
{
	if (!m_shader->isReady()) return;

	Matrix scale_mtx = Matrix::IDENTITY;
	scale_mtx.m11 = scale_mtx.m22 = scale_mtx.m33 = m_scale;
	Matrix gizmo_mtx;
	getMatrix(gizmo_mtx);
	Matrix mtx = gizmo_mtx * scale_mtx;

	Vertex vertices[9];
	uint16 indices[9];
	vertices[0].position = Vec3(0, 0, 0);
	vertices[0].color = m_transform_axis == Axis::X ? SELECTED_COLOR : X_COLOR;
	indices[0] = 0;
	vertices[1].position = Vec3(1, 0, 0);
	vertices[1].color = m_transform_axis == Axis::X ? SELECTED_COLOR : X_COLOR;
	indices[1] = 1;
	vertices[2].position = Vec3(0, 0, 0);
	vertices[2].color = m_transform_axis == Axis::Y ? SELECTED_COLOR : Y_COLOR;
	indices[2] = 2;
	vertices[3].position = Vec3(0, 1, 0);
	vertices[3].color = m_transform_axis == Axis::Y ? SELECTED_COLOR : Y_COLOR;
	indices[3] = 3;
	vertices[4].position = Vec3(0, 0, 0);
	vertices[4].color = m_transform_axis == Axis::Z ? SELECTED_COLOR : Z_COLOR;
	indices[4] = 4;
	vertices[5].position = Vec3(0, 0, 1);
	vertices[5].color = m_transform_axis == Axis::Z ? SELECTED_COLOR : Z_COLOR;
	indices[5] = 5;

	auto& renderer = static_cast<Lumix::Renderer&>(m_scene->getPlugin());
	Lumix::TransientGeometry geom(vertices, 6, renderer.getBasicVertexDecl(), indices, 6);
	pipeline.render(geom,
		mtx,
		0,
		6,
		BGFX_STATE_PT_LINES | BGFX_STATE_DEPTH_TEST_LEQUAL,
		m_shader->getInstance(0).m_program_handles[pipeline.getPassIdx()]);

	if (dotProduct(gizmo_mtx.getXVector(), m_camera_dir) < 0) mtx.setXVector(-mtx.getXVector());
	if (dotProduct(gizmo_mtx.getYVector(), m_camera_dir) < 0) mtx.setYVector(-mtx.getYVector());
	if (dotProduct(gizmo_mtx.getZVector(), m_camera_dir) < 0) mtx.setZVector(-mtx.getZVector());

	vertices[0].position = Vec3(0, 0, 0);
	vertices[0].color = m_transform_axis == Axis::XY ? SELECTED_COLOR : Z_COLOR;
	indices[0] = 0;
	vertices[1].position = Vec3(0.5f, 0, 0);
	vertices[1].color = m_transform_axis == Axis::XY ? SELECTED_COLOR : Z_COLOR;
	indices[1] = 1;
	vertices[2].position = Vec3(0, 0.5f, 0);
	vertices[2].color = m_transform_axis == Axis::XY ? SELECTED_COLOR : Z_COLOR;
	indices[2] = 2;

	vertices[3].position = Vec3(0, 0, 0);
	vertices[3].color = m_transform_axis == Axis::YZ ? SELECTED_COLOR : X_COLOR;
	indices[3] = 3;
	vertices[4].position = Vec3(0, 0.5f, 0);
	vertices[4].color = m_transform_axis == Axis::YZ ? SELECTED_COLOR : X_COLOR;
	indices[4] = 4;
	vertices[5].position = Vec3(0, 0, 0.5f);
	vertices[5].color = m_transform_axis == Axis::YZ ? SELECTED_COLOR : X_COLOR;
	indices[5] = 5;

	vertices[6].position = Vec3(0, 0, 0);
	vertices[6].color = m_transform_axis == Axis::XZ ? SELECTED_COLOR : Y_COLOR;
	indices[6] = 6;
	vertices[7].position = Vec3(0.5f, 0, 0);
	vertices[7].color = m_transform_axis == Axis::XZ ? SELECTED_COLOR : Y_COLOR;
	indices[7] = 7;
	vertices[8].position = Vec3(0, 0, 0.5f);
	vertices[8].color = m_transform_axis == Axis::XZ ? SELECTED_COLOR : Y_COLOR;
	indices[8] = 8;

	Lumix::TransientGeometry geom2(vertices, 9, renderer.getBasicVertexDecl(), indices, 9);
	auto program_handle = m_shader->getInstance(0).m_program_handles[pipeline.getPassIdx()];
	pipeline.render(geom2, mtx, 0, 9, BGFX_STATE_DEPTH_TEST_LEQUAL, program_handle);
}
void	SMDImporter::CreateGeometry()
{

	if ( !m_pTriangles.GetUsed() )
		return;

	long t;

	XSI::MATH::CTransformation xfo;
	xfo.SetRotationFromXYZAnglesValues ( -1.570796, 0.0, 0.0 );

	for (t=0;t<m_pTriangles.GetUsed();t++)
	{
		for (int v=0;v<3;v++)
		{
			XSI::MATH::CVector3 vec = XSI::MATH::MapObjectPositionToWorldSpace ( xfo, m_pTriangles[t]->m_pVertex[v].m_vPosition );
			
			long outindex;
			compress.AddVertex ( vec.GetX(), 
									vec.GetY(), 
									vec.GetZ(), 
									m_pTriangles[t]->m_pVertex[v].m_vUV.GetX(), 
									m_pTriangles[t]->m_pVertex[v].m_vUV.GetY(),
									&m_pTriangles[t]->m_pVertex[v],
									&outindex);

			m_lVertexMap.Extend(1);
			m_lVertexMap[m_lVertexMap.GetUsed()-1] = outindex;
		}
	}

	XSI::MATH::CVector3Array verts(compress.GetCount());
	long vindex = 0;
	long cnt  = compress.GetCount ();
	for (t=0;t<compress.GetCount ();t++)
	{
		uvvec vec;
		compress.GetVertex (t, &vec);
		verts[t] = XSI::MATH::CVector3 ( vec.x, vec.y, vec.z );
	}
	
	
	XSI::CLongArray indices((m_pTriangles.GetUsed() * 3) + m_pTriangles.GetUsed());

	long iindex = 0;
	

	char *l_szGlobalTexture = m_pTriangles[0]->m_szTexture;
	CSIBCArray<TriCluster>	ClusterList;
	
	for (t=0;t<m_pTriangles.GetUsed();t++)
	{
		
		XSI::MATH::CVector3 vec1 = XSI::MATH::MapObjectPositionToWorldSpace ( xfo, m_pTriangles[t]->m_pVertex[0].m_vPosition );
		XSI::MATH::CVector3 vec2 = XSI::MATH::MapObjectPositionToWorldSpace ( xfo, m_pTriangles[t]->m_pVertex[1].m_vPosition );
		XSI::MATH::CVector3 vec3 = XSI::MATH::MapObjectPositionToWorldSpace ( xfo, m_pTriangles[t]->m_pVertex[2].m_vPosition );

		long i1 = compress.GetIndex ( vec1.GetX(), vec1.GetY(), vec1.GetZ(), m_pTriangles[t]->m_pVertex[0].m_vUV.GetX(), m_pTriangles[t]->m_pVertex[0].m_vUV.GetY());
		long i2 = compress.GetIndex ( vec2.GetX(), vec2.GetY(), vec2.GetZ(), m_pTriangles[t]->m_pVertex[1].m_vUV.GetX(), m_pTriangles[t]->m_pVertex[1].m_vUV.GetY());
		long i3 = compress.GetIndex ( vec3.GetX(), vec3.GetY(), vec3.GetZ(), m_pTriangles[t]->m_pVertex[2].m_vUV.GetX(), m_pTriangles[t]->m_pVertex[2].m_vUV.GetY());

		indices[iindex] = 3;
		indices[iindex+1] = i1;
		indices[iindex+2] = i2;
		indices[iindex+3] = i3;
		iindex += 4;

		if ( strcmp ( l_szGlobalTexture, m_pTriangles[t]->m_szTexture ))
		{
			//
			// found a local material
			//

			TriCluster* cls = NULL;

			for (int c=0;c<ClusterList.GetUsed();c++)
			{
				if ( !strcmp ( ClusterList[c].m_szName, m_pTriangles[t]->m_szTexture))
				{
					cls = &ClusterList[c];
					break;
				}

			}

			if ( cls == NULL )
			{
				ClusterList.Extend(1);
				strcpy ( ClusterList[ClusterList.GetUsed()-1].m_szName, m_pTriangles[t]->m_szTexture );
				cls = &ClusterList[ClusterList.GetUsed()-1];
			}

			cls->m_indices.Add ( t );

		}

	}

	char mname[1024];
	sprintf (mname, "mesh" );
	if ( m_pMeshNode )
	{
		sprintf (mname, FixName(m_pMeshNode->m_szName));
	}

	LPWSTR l_wszModelName;
	DSA2W(&l_wszModelName,mname);

	m_pModel.AddPolygonMesh ( verts, indices, l_wszModelName, m_pMesh );


	XSI::Application	app;
	XSI::CValueArray	args(4);
	XSI::CValue			outArg;
	XSI::CStatus		st;

	args[0] = XSI::CValue( XSI::CString(L"") );
	args[1] = XSI::CValue(false);
	args[0] = XSI::CValue(m_pMesh.GetRef());
	args[1] = XSI::CValue((long)XSI::siTxtUV);
	args[2] = XSI::CValue((long)XSI::siTxtDefaultSpherical);
	args[3] = XSI::CValue(XSI::CString(L"Texture_Support"));

	app.ExecuteCommand( L"CreateTextureSupport", args, outArg );

	XSI::CValueArray	moreargs(1);
	XSI::CValueArray	moreoutargs(3);
	moreargs[0] = m_pMesh.GetRef();
	app.ExecuteCommand(L"FreezeObj",moreargs, outArg);

	XSI::Material		l_matMaterial;
	st = m_pMesh.AddMaterial(L"Phong", true, L"CubeMat", l_matMaterial);
		
	XSI::OGLTexture		l_oglTexture(l_matMaterial.GetOGLTexture());

	XSI::CString		l_szFullNameDefaultOut	= l_oglTexture.GetFullName();
	int			l_nHeightDefaultOut		= l_oglTexture.GetHeight();
	int			l_nWidthDefaultOut		= l_oglTexture.GetWidth();

	

	// Now actually add a texture, so we can test it.
	args[0] = XSI::CValue( XSI::CString(L"Image") );
	args[1] = XSI::CValue(m_pMesh.GetRef());
	args[2] = XSI::CValue((short)1);
	args[3] = XSI::CValue(false);
	st = app.ExecuteCommand( L"BlendInPresets", args, outArg );

	
	//
	// create the texture and connect
	//
	
	XSI::CValueArray	clipargs(3);
	XSI::ImageClip2 l_pClip;
	
	char l_szTextureFullname[1024];
	sprintf ( l_szTextureFullname, "%s%s", m_szDirectory, m_pTriangles[0]->m_szTexture);
	char clipname[1024];
	_splitpath ( m_pTriangles[0]->m_szTexture, NULL, NULL, clipname, NULL );

	LPWSTR l_wszClipName;
	DSA2W(&l_wszClipName,l_szTextureFullname);

	LPWSTR l_wszClipName2;
	DSA2W(&l_wszClipName2,clipname);

	
	
	clipargs[0] = XSI::CValue( XSI::CString(l_wszClipName) );
	clipargs[1] = XSI::CValue( XSI::CString(l_wszClipName2) );
	clipargs[2] = XSI::CValue(l_pClip.GetRef());
	app.ExecuteCommand( L"SICreateImageClip", clipargs, outArg );
	
	XSI::CString		l_szMaterialName	= l_matMaterial.GetFullName(); 
	XSI::CString		l_szImageNode = l_szMaterialName + L".CubeMat.ambient_blend.Image.tex";
	XSI::CString		l_szFullclipname = L"Clips." +  XSI::CString(l_wszClipName2);
	
	XSI::CValueArray	clipargs2(2);
	clipargs2[0] = XSI::CValue( XSI::CString(l_szFullclipname) );
	clipargs2[1] = XSI::CValue( XSI::CString(l_szImageNode) );
	
	app.ExecuteCommand( L"SIConnectShaderToCnxPoint", clipargs2, outArg );

	//
	// Create all clusters
	//

	XSI::Geometry geom( m_pMesh.GetActivePrimitive().GetGeometry() );
	
	for (int b=0;b<ClusterList.GetUsed();b++)
	{
		TriCluster* cls = &ClusterList[b];
		
		
		sprintf ( l_szTextureFullname, "%s%s", m_szDirectory, cls->m_szName);
		_splitpath ( cls->m_szName, NULL, NULL, clipname, NULL );
		
		DSA2W(&l_wszClipName,l_szTextureFullname);
		DSA2W(&l_wszClipName2,clipname);
		
		XSI::CLongArray array;
		XSI::Cluster polyCluster ;
		geom.AddCluster( XSI::siPolygonCluster, l_wszClipName2, cls->m_indices, polyCluster ) ;
		
		st = polyCluster.AddMaterial(L"Phong", true, L"CubeMat", l_matMaterial);
		
		XSI::OGLTexture		l_oglTexture(l_matMaterial.GetOGLTexture());
	
		// Now actually add a texture, so we can test it.
		args[0] = XSI::CValue( XSI::CString(L"Image") );
		args[1] = XSI::CValue(polyCluster.GetRef());
		args[2] = XSI::CValue((short)1);
		args[3] = XSI::CValue(false);
		st = app.ExecuteCommand( L"BlendInPresets", args, outArg );
			

		
		
		
		clipargs[0] = XSI::CValue( XSI::CString(l_wszClipName) );
		clipargs[1] = XSI::CValue( XSI::CString(l_wszClipName2) );
		clipargs[2] = XSI::CValue(l_pClip.GetRef());
		app.ExecuteCommand( L"SICreateImageClip", clipargs, outArg );
		
		l_szMaterialName	= l_matMaterial.GetFullName(); 
		l_szImageNode = l_szMaterialName + L".CubeMat.ambient_blend.Image.tex";
		l_szFullclipname = L"Clips." +  XSI::CString(l_wszClipName2);
		
		clipargs2[0] = XSI::CValue( XSI::CString(l_szFullclipname) );
		clipargs2[1] = XSI::CValue( XSI::CString(l_szImageNode) );
		
		app.ExecuteCommand( L"SIConnectShaderToCnxPoint", clipargs2, outArg );
		
	}

	
	if ( m_pMesh.IsValid () )
	{
		XSI::Geometry geom( m_pMesh.GetActivePrimitive().GetGeometry() );
		XSI::PolygonMesh mesh(m_pMesh.GetActivePrimitive().GetGeometry());

		XSI::CPointRefArray Geompoints = geom.GetPoints();
		
				
		XSI::CTriangleRefArray triangles(geom.GetTriangles());
		XSI::ClusterProperty UVWProp(m_pMesh.GetMaterial().GetCurrentUV());
		
		if ( UVWProp.IsValid() )
		{

		XSI::CClusterPropertyElementArray clusterPropertyElements = UVWProp.GetElements();
		XSI::CDoubleArray elementArray = clusterPropertyElements.GetArray();
		
		long totalUvCount = elementArray.GetCount ();
		int cc=0;
		int uvc = 0;
		for (int c=0;c<m_pTriangles.GetUsed();c++)
		{
			long l_iNumVertex = indices[cc];
			
			cc++;
			for (int i=0;i<l_iNumVertex;i++)
			{
				long l_iID = indices[cc];
				cc++;
				
				uvvec vec;
				compress.GetVertex (l_iID, &vec);

				elementArray[ uvc * 3 ] = vec.u;
				
				elementArray[ (uvc * 3) + 1] = vec.v;
				elementArray[ (uvc * 3) + 2] = 0.0f;
				
				uvc++;
			}
			
			
			
		}


			clusterPropertyElements.PutArray(elementArray);
		}
	}

}
Exemple #12
0
int main(int argc, char *argv[ ])
{
    char *directory = NULL;
    char *overlay_image = NULL;
    char *resolution = NULL;
    char *productid1 = NULL;
    char *productid2 = NULL;
    char *timing = NULL;
    char *format = NULL;

    char *pname = strdup(argv[0]);

    float geometry = 1.0;
    bool normalize = false;
    bool do_overlay = false;

    while (1) {
        int option_index = 0;
        int c;

        static struct option long_options[] = {
            {"directory", 1, 0, 'd'},
            {"resolution", 1, 0, 'r'},
            {"productid1", 1, 0, 's'},
            {"productid2", 1, 0, 'c'},
            {"outformat", 1, 0, 'f'},
            {"outscale", 1, 0, 'g'},
            {"overlay", 1, 0, 'o'},
            {"time", 1, 0, 't'},
            {"normalize", 0, 0, 'n'},
            {"version", 0, 0, 'V'},
            {"help", 0, 0, 'h'},
            {0, 0, 0, 0}
        };

        c = getopt_long (argc, argv, "d:r:s:c:f:g:o:t:nVh?",
                         long_options, &option_index);
        if (c == -1)
            break;

        switch (c)
        {
        case 'd':
            directory = strdup(optarg);
            break;
        case 'r':
            resolution = strdup(optarg);
            break;
        case 's':
            productid1 = strdup(optarg);
            break;
        case 'c':
            productid2 = strdup(optarg);
            break;
        case 'f':
            format = strdup(optarg);
            break;
        case 'g':
            geometry = strtod(optarg, (char **)NULL);
            break;
        case 'o':
            do_overlay = true;
            overlay_image = strdup(optarg);
            break;
        case 't':
            timing = strdup(optarg);
            break;
        case 'n':
            normalize = true;
            break;
        case 'V':
            std::cout << pname << " " << PACKAGE_STRING << std::endl;
            return 0;
        case '?':
        case 'h':
            usage(pname);
            return(0);
            break;
        default:
            std::cerr << "?? getopt returned character code"
                      << std::oct << c << "??" << std::endl;
            usage(pname);
            return(1);
        }
    }

    if (resolution == NULL || productid1 == NULL ||
            productid2 == NULL || timing == NULL)
    {
        usage(pname);
        return(1);
    }

    std::string filename;
    if (directory) filename = directory;
    else filename = ".";

    filename = filename + PATH_SEPARATOR + resolution;
    filename = filename + "-\?\?\?-\?\?\?\?\?\?-";
    filename = filename + underscoreit(productid1, 12) + "-";
    filename = filename + underscoreit(productid2, 9) + "-";
    filename = filename + "0\?\?\?\?\?___" + "-";
    filename = filename + timing + "-" + "\?_";

    glob_t globbuf;
    globbuf.gl_offs = 1;

    if ((glob(filename.c_str( ), GLOB_DOOFFS, NULL, &globbuf)) != 0)
    {
        std::cerr << "No such file(s)." << std::endl;
        return 1;
    }

    int nsegments = globbuf.gl_pathc;

    MSG_header *header;
    MSG_data *msgdat;

    header = new MSG_header[nsegments];
    msgdat = new MSG_data[nsegments];

    for (int i = 0; i < nsegments; i ++)
    {
        std::ifstream hrit(globbuf.gl_pathv[i+1],
                           (std::ios::binary | std::ios::in));
        if (hrit.fail())
        {
            std::cerr << "Cannot open input hrit file "
                      << globbuf.gl_pathv[i+1] << std::endl;
            return 1;
        }
        header[i].read_from(hrit);
        msgdat[i].read_from(hrit, header[i]);
        hrit.close( );
        std::cout << header[i];
    }

    globfree(&globbuf);

    if (header[0].segment_id->data_field_format == MSG_NO_FORMAT)
    {
        std::cout << "Product dumped in binary format." << std::endl;
        return 0;
    }

    int totalsegs = header[0].segment_id->planned_end_segment_sequence_number;
    int *segsindexes = new int[totalsegs];

    for (int i = 0; i < totalsegs; i ++)
        segsindexes[i] = -1;

    for (int i = 0; i < nsegments; i ++)
        segsindexes[header[i].segment_id->sequence_number-1] = i;

    filename = resolution;
    filename = filename + "-" + productid1 + "-" + productid2 + "-" +
               timing;
    if (format)
        filename = filename + "." + format;
    else
        filename = filename + ".jpg";

    int npix = header[0].image_structure->number_of_columns;
    int nlin = header[0].image_structure->number_of_lines;
    size_t npixperseg = npix*nlin;

    size_t total_size = totalsegs*npixperseg;
    MSG_SAMPLE *pixels = new MSG_SAMPLE[total_size];
    memset(pixels, 0, total_size*sizeof(MSG_SAMPLE));
    size_t pos = 0;
    for (int i = 0; i < totalsegs; i ++)
    {
        if (segsindexes[i] >= 0)
            memcpy(pixels+pos, msgdat[segsindexes[i]].image->data,
                   npixperseg*sizeof(MSG_SAMPLE));
        pos += npixperseg;
    }

    Magick::Image *image = new Magick::Image(npix, nlin*totalsegs,
            "I", Magick::ShortPixel, pixels);
    if (normalize) image->normalize( );
    image->rotate(180.0);
    if (header[0].segment_id->spectral_channel_id < 12)
    {
        if (do_overlay)
        {
            Magick::Image overlay;
            overlay.read(overlay_image);
            image->composite(overlay, 0, 0, Magick::PlusCompositeOp);
        }
    }

    if (geometry < 1.0)
    {
        Magick::Geometry geom((int) ((float) npix*geometry),
                              (int) ((float) nlin*totalsegs*geometry));
        image->scale(geom);
    }

    image->write(filename);

    delete image;

    delete [ ] pixels;
    delete [ ] header;
    delete [ ] msgdat;
    delete [ ] segsindexes;
    return 0;
}
Exemple #13
0
void Client::updateSize(xcb_connection_t* conn, xcb_get_geometry_cookie_t cookie)
{
    AutoPointer<xcb_get_geometry_reply_t> geom(xcb_get_geometry_reply(conn, cookie, 0));
    mRect = Rect(geom->x, geom->y, geom->width, geom->height);
}
Exemple #14
0
int
main (int   argc,
      char* argv[])
{
    BoxLib::Initialize(argc,argv);

    std::cout << std::setprecision(10);

    if (argc < 2)
    {
      std::cerr << "usage:  " << argv[0] << " inputsfile [options]" << '\n';
      exit(-1);
    }

    ParmParse pp;
    
    int n;

    BoxArray bs;
    
#if BL_SPACEDIM == 2
    Box domain(IntVect(0,0),IntVect(11,11));
    std::string boxfile("gr.2_small_a") ;
#elif BL_SPACEDIM == 3
    Box domain(IntVect(0,0,0),IntVect(11,11,11));
    std::string boxfile("grids/gr.3_2x3x4") ;
#endif
    pp.query("boxes", boxfile);

    std::ifstream ifs(boxfile.c_str(), std::ios::in);

    if (!ifs)
    {
        std::string msg = "problem opening grids file: ";
        msg += boxfile.c_str();
        BoxLib::Abort(msg.c_str());
    }

    ifs >> domain;

    if (ParallelDescriptor::IOProcessor())
	std::cout << "domain: " << domain << std::endl;

    bs.readFrom(ifs);

    if (ParallelDescriptor::IOProcessor())
	std::cout << "grids:\n" << bs << std::endl;

    Geometry geom(domain);
    const Real* H = geom.CellSize();
    int ratio=2; pp.query("ratio", ratio);

    // allocate/init soln and rhs
    int Ncomp=BL_SPACEDIM;
    int Nghost=0;
    int Ngrids=bs.size();
    MultiFab soln(bs, Ncomp, Nghost, Fab_allocate); soln.setVal(0.0);
    MultiFab out(bs, Ncomp, Nghost, Fab_allocate); 
    MultiFab rhs(bs, Ncomp, Nghost, Fab_allocate); rhs.setVal(0.0);
    for(MFIter rhsmfi(rhs); rhsmfi.isValid(); ++rhsmfi)
    {
	FORT_FILLRHS(rhs[rhsmfi].dataPtr(),
		     ARLIM(rhs[rhsmfi].loVect()),ARLIM(rhs[rhsmfi].hiVect()),
		     H,&Ncomp);
    }
    
    // Create the boundary object
    MCViscBndry vbd(bs,geom);

    BCRec phys_bc;
    Array<int> lo_bc(BL_SPACEDIM), hi_bc(BL_SPACEDIM);
    pp.getarr("lo_bc",lo_bc,0,BL_SPACEDIM);
    pp.getarr("hi_bc",hi_bc,0,BL_SPACEDIM);
    for (int i = 0; i < BL_SPACEDIM; i++)
    {
        phys_bc.setLo(i,lo_bc[i]);
        phys_bc.setHi(i,hi_bc[i]);
    }

    
    // Create the BCRec's interpreted by ViscBndry objects
#if BL_SPACEDIM==2
    Array<BCRec> pbcarray(4);
    pbcarray[0] = BCRec(D_DECL(REFLECT_ODD,REFLECT_EVEN,EXT_DIR),
			D_DECL(EXT_DIR,EXT_DIR,EXT_DIR));
    pbcarray[1] = BCRec(D_DECL(REFLECT_EVEN,REFLECT_ODD,EXT_DIR),
			D_DECL(EXT_DIR,EXT_DIR,EXT_DIR));
    pbcarray[2] = BCRec(D_DECL(EXT_DIR,EXT_DIR,EXT_DIR),
			D_DECL(EXT_DIR,EXT_DIR,EXT_DIR));
    pbcarray[3] = BCRec(D_DECL(EXT_DIR,EXT_DIR,EXT_DIR),
			D_DECL(EXT_DIR,EXT_DIR,EXT_DIR));
#elif BL_SPACEDIM==3
    Array<BCRec> pbcarray(12);

#if 1
    pbcarray[0] = BCRec(EXT_DIR,EXT_DIR,EXT_DIR,EXT_DIR,EXT_DIR,EXT_DIR);
    pbcarray[1] = BCRec(EXT_DIR,EXT_DIR,EXT_DIR,EXT_DIR,EXT_DIR,EXT_DIR);
    pbcarray[2] = BCRec(EXT_DIR,EXT_DIR,EXT_DIR,EXT_DIR,EXT_DIR,EXT_DIR);
    pbcarray[3] = BCRec(D_DECL(EXT_DIR,EXT_DIR,EXT_DIR),
			D_DECL(EXT_DIR,EXT_DIR,EXT_DIR));
    pbcarray[4] = BCRec(D_DECL(EXT_DIR,EXT_DIR,EXT_DIR),
			D_DECL(EXT_DIR,EXT_DIR,EXT_DIR));
    pbcarray[5] = BCRec(D_DECL(EXT_DIR,EXT_DIR,EXT_DIR),
			D_DECL(EXT_DIR,EXT_DIR,EXT_DIR));
    pbcarray[6] = BCRec(D_DECL(EXT_DIR,EXT_DIR,EXT_DIR),
			D_DECL(EXT_DIR,EXT_DIR,EXT_DIR));
    pbcarray[7] = BCRec(D_DECL(EXT_DIR,EXT_DIR,EXT_DIR),
			D_DECL(EXT_DIR,EXT_DIR,EXT_DIR));
    pbcarray[8] = BCRec(D_DECL(EXT_DIR,EXT_DIR,EXT_DIR),
			D_DECL(EXT_DIR,EXT_DIR,EXT_DIR));
    pbcarray[9] = BCRec(D_DECL(EXT_DIR,EXT_DIR,EXT_DIR),
			D_DECL(EXT_DIR,EXT_DIR,EXT_DIR));
    pbcarray[10] = BCRec(D_DECL(EXT_DIR,EXT_DIR,EXT_DIR),
			 D_DECL(EXT_DIR,EXT_DIR,EXT_DIR));
    pbcarray[11] = BCRec(D_DECL(EXT_DIR,EXT_DIR,EXT_DIR),
			 D_DECL(EXT_DIR,EXT_DIR,EXT_DIR));
#else
    for (int i = 0; i < 12; i++)
        pbcarray[i] = phys_bc;
#endif
#endif
    
    Nghost = 1; // need space for bc info
    MultiFab fine(bs,Ncomp,Nghost,Fab_allocate);
    for(MFIter finemfi(fine); finemfi.isValid(); ++finemfi)
    {
	FORT_FILLFINE(fine[finemfi].dataPtr(),
		      ARLIM(fine[finemfi].loVect()),ARLIM(fine[finemfi].hiVect()),
		      H,&Ncomp);
    }

    // Create "background coarse data"
    Box crse_bx = Box(domain).coarsen(ratio).grow(1);
    BoxArray cba(crse_bx);
    cba.maxSize(32);
    Real h_crse[BL_SPACEDIM];
    for (n=0; n<BL_SPACEDIM; n++) h_crse[n] = H[n]*ratio;

    MultiFab crse_mf(cba, Ncomp, 0);
//    FArrayBox crse_fab(crse_bx,Ncomp);

    for (MFIter mfi(crse_mf); mfi.isValid(); ++mfi)
    {
        FORT_FILLCRSE(crse_mf[mfi].dataPtr(),
                      ARLIM(crse_mf[mfi].loVect()),ARLIM(crse_mf[mfi].hiVect()),
                      h_crse,&Ncomp);
    }


    
    // Create coarse boundary register, fill w/data from coarse FAB
    int bndry_InRad=0;
    int bndry_OutRad=1;
    int bndry_Extent=1;
    BoxArray cbs = BoxArray(bs).coarsen(ratio);
    BndryRegister cbr(cbs,bndry_InRad,bndry_OutRad,bndry_Extent,Ncomp);
    for (OrientationIter face; face; ++face)
    {
	Orientation f = face();
	FabSet& bnd_fs(cbr[f]);
	bnd_fs.copyFrom(crse_mf, 0, 0, 0, Ncomp);
    }
  
    // Interpolate crse data to fine boundary, where applicable
    int cbr_Nstart=0;
    int fine_Nstart=0;
    int bndry_Nstart=0;
    vbd.setBndryValues(cbr,cbr_Nstart,fine,fine_Nstart,
		       bndry_Nstart,Ncomp,ratio,pbcarray);
  
    Nghost = 1; // other variables don't need extra space
    
    DivVis lp(vbd,H);
    
    Real a = 0.0;
    Real b[BL_SPACEDIM];
    b[0] = 1.0;
    b[1] = 1.0;
#if BL_SPACEDIM>2
    b[2] = 1.0;
#endif
    MultiFab  acoefs;
    int NcompA = (BL_SPACEDIM == 2  ?  2  :  1);
    acoefs.define(bs, NcompA, Nghost, Fab_allocate);
    acoefs.setVal(a);
    MultiFab bcoefs[BL_SPACEDIM];
    for (n=0; n<BL_SPACEDIM; ++n)
    {
	BoxArray bsC(bs);
	bcoefs[n].define(bsC.surroundingNodes(n), 1,
			 Nghost, Fab_allocate);
#if 1
	for(MFIter bmfi(bcoefs[n]); bmfi.isValid(); ++bmfi)
	{
	    FORT_MAKEMU(bcoefs[n][bmfi].dataPtr(),
			ARLIM(bcoefs[n][bmfi].loVect()),ARLIM(bcoefs[n][bmfi].hiVect()),H,n);
	}
#else
	bcoefs[n].setVal(b[n]);
#endif
    } // -->> over dimension
    lp.setCoefficients(acoefs, bcoefs);
#if 1
    lp.maxOrder(4);
#endif
    
    Nghost = 1;
    MultiFab tsoln(bs, Ncomp, Nghost, Fab_allocate); 
    tsoln.setVal(0.0);
#if 1
    tsoln.copy(fine);
#endif
#if 0
    // testing apply
    lp.apply(out,tsoln);
    Box subbox = out[0].box();
    Real n1 = out[0].norm(subbox,1,0,BL_SPACEDIM)*pow(H[0],BL_SPACEDIM);
    ParallelDescriptor::ReduceRealSum(n1);
    if (ParallelDescriptor::IOProcessor())
    {
	cout << "n1 output is "<<n1<<std::endl;
    }
    out.minus(rhs,0,BL_SPACEDIM,0);
    // special to single grid prob
    Real n2 = out[0].norm(subbox,1,0,BL_SPACEDIM)*pow(H[0],BL_SPACEDIM);
    ParallelDescriptor::ReduceRealSum(n2);
    if (ParallelDescriptor::IOProcessor())
    {
	cout << "n2 difference is "<<n2<<std::endl;
    }
#if 0
    subbox.grow(-1);
    Real n3 = out[0].norm(subbox,0,0,BL_SPACEDIM)*pow(H[0],BL_SPACEDIM);
    ParallelDescriptor::ReduceRealMax(n3);
    if (ParallelDescriptor::IOProcessor())
    {
	cout << "n3 difference is "<<n3<<std::endl;
    }
#endif
    
#endif
    
    const IntVect refRatio(D_DECL(2,2,2));
    const Real bgVal = 1.0;
    
#if 1
#ifndef NDEBUG
    // testing flux computation
    BoxArray xfluxbox(bs);
    xfluxbox.surroundingNodes(0);
    MultiFab xflux(xfluxbox,Ncomp,Nghost,Fab_allocate);
    xflux.setVal(1.e30);
    BoxArray yfluxbox(bs);
    yfluxbox.surroundingNodes(1);
    MultiFab yflux(yfluxbox,Ncomp,Nghost,Fab_allocate);
    yflux.setVal(1.e30);
#if BL_SPACEDIM>2
    BoxArray zfluxbox(bs);
    zfluxbox.surroundingNodes(2);
    MultiFab zflux(zfluxbox,Ncomp,Nghost,Fab_allocate);
    zflux.setVal(1.e30);
#endif
    lp.compFlux(xflux,
		yflux,
#if BL_SPACEDIM>2
		zflux,
#endif
		tsoln);
    
    // Write fluxes
    //writeMF(&xflux,"xflux.mfab");
    //writeMF(&yflux,"yflux.mfab");
#if BL_SPACEDIM>2
    //writeMF(&zflux,"zflux.mfab");
#endif
    
#endif
#endif
    
    Real tolerance = 1.0e-10; pp.query("tol", tolerance);
    Real tolerance_abs = 1.0e-10; pp.query("tol_abs", tolerance_abs);

#if 0
    cout << "Bndry Data object:" << std::endl;
    cout << lp.bndryData() << std::endl;
#endif
    
#if 0
    bool use_mg_pre = false;
    MCCGSolver cg(lp,use_mg_pre);
    cg.solve(soln,rhs,tolerance,tolerance_abs);
#else
    MCMultiGrid mg(lp);
    mg.solve(soln,rhs,tolerance,tolerance_abs);
#endif

#if 0
    cout << "MCLinOp object:" << std::endl;
    cout << lp << std::endl;
#endif
    
    VisMF::Write(soln,"soln");
    
#if 0
    // apply operator to soln to see if really satisfies eqn
    tsoln.copy(soln);
    lp.apply(out,tsoln);
    soln.copy(out);
    // Output "apply" results on soln
    VisMF::Write(soln,"apply");

    // Compute truncation
    for (MFIter smfi(soln); smfi.isValid(); ++smfi)
    {
	soln[smfi] -= fine[smfi];
    }
    for( int icomp=0; icomp < BL_SPACEDIM ; icomp++ )
    {
	Real solnMin = soln.min(icomp);
	Real solnMax = soln.max(icomp);
	ParallelDescriptor::ReduceRealMin(solnMin);
	ParallelDescriptor::ReduceRealMax(solnMax);
	if (ParallelDescriptor::IOProcessor())
	{
	    cout << icomp << "  "<<solnMin << " " << solnMax <<std::endl;
	}
    }
    // Output truncation
    VisMF::Write(soln,"trunc");
#endif

    int dumpLp=0; pp.query("dumpLp",dumpLp);
    bool write_lp = (dumpLp == 1 ? true : false);
    if (write_lp)
	std::cout << lp << std::endl;

    // Output trunc
    ParallelDescriptor::EndParallel();
}
Exemple #15
0
	void object::test<5>()
	{         
            GeomPtr geom(wktreader.read("LineString (-117 33 2, -116 34 4)"));
            ensure_equals( wktwriter.write(geom.get()), 
                           std::string("LINESTRING Z (-117 33 2, -116 34 4)") );
    }
void ModelTestScene::Initialize(const GameContext& gameContext)
{
	UNREFERENCED_PARAMETER(gameContext);

	//GROUND PLANE
	//************
	auto physX = PhysxManager::GetInstance()->GetPhysics();

	auto bouncyMaterial = physX->createMaterial(0, 0, 1);
	auto ground = new GameObject();
	ground->AddComponent(new RigidBodyComponent(true));

	std::shared_ptr<PxGeometry> geom(new PxPlaneGeometry());
	ground->AddComponent(new ColliderComponent(geom, *bouncyMaterial, PxTransform(PxQuat(XM_PIDIV2, PxVec3(0, 0, 1)))));
	AddChild(ground);

	//CHAIR OBJECT
	//************
	m_pChair = new GameObject();

	//1. Attach a modelcomponent (chair.ovm)
	auto chairModelComponent = new ModelComponent(L"./Resources/Meshes/chair.ovm");
	m_pChair->AddComponent(chairModelComponent);

	//2. Create a ColorMaterial and add it to the material manager
	auto chairColorMaterial = new ColorMaterial();
	gameContext.pMaterialManager->AddMaterial(chairColorMaterial, 102);

	//3. Assign the material to the previous created modelcomponent
	m_pChair->GetComponent<ModelComponent>()->SetMaterial(102);
	// Build and Run

	//4. Create a DiffuseMaterial (using PosNormTex3D.fx)
	//		Make sure you are able to set a texture (DiffuseMaterial::SetDiffuseTexture(const wstring& assetFile))
	//		Load the correct shadervariable and set it during the material variable update
	auto chairDiffuseMaterial = new DiffuseMaterial();
	chairDiffuseMaterial->SetDiffuseTexture(L"./Resources/Textures/Chair_Dark.dds");
	gameContext.pMaterialManager->AddMaterial(chairDiffuseMaterial, 104);

	//5. Assign the material to the modelcomponent
	m_pChair->GetComponent<ModelComponent>()->SetMaterial(104);
	// Build and Run

	//6. Attach a rigidbody component (pure-dynamic)
	auto chairRigidbody = new RigidBodyComponent();
	m_pChair->AddComponent(chairRigidbody);

	//7. Attach a collider component (Use a PxConvexMeshGeometry [chair.ovpc])

	auto defaultMaterial = physX->createMaterial(0.5f, 0.5f, 0.1f);
	auto chairMesh = ContentManager::Load<PxConvexMesh>(L"./Resources/Meshes/chair.ovpc");
	shared_ptr<PxGeometry> chairGeo(new PxConvexMeshGeometry(chairMesh));
	auto chairCollider = new ColliderComponent(chairGeo, *defaultMaterial);

	m_pChair->AddComponent(chairCollider);

	AddChild(m_pChair);

	chairRigidbody->SetDensity(300);

	m_pChair->GetTransform()->Translate(0, 10, 0);

	// Build and Run
}
Exemple #17
0
int
main (int argc, char* argv[])
{
  BoxLib::Initialize(argc,argv);

  // What time is it now?  We'll use this to compute total run time.
  Real strt_time = ParallelDescriptor::second();

  std::cout << std::setprecision(15);

  // ParmParse is way of reading inputs from the inputs file
  ParmParse pp;

  // We need to get n_cell from the inputs file - this is the number of cells on each side of 
  //   a square (or cubic) domain.
  int n_cell;
  pp.get("n_cell",n_cell);

  // Default nsteps to 0, allow us to set it to something else in the inputs file
  int max_grid_size;
  pp.get("max_grid_size",max_grid_size);

  // Default plot_int to 1, allow us to set it to something else in the inputs file
  //  If plot_int < 0 then no plot files will be written
  int plot_int = 1;
  pp.query("plot_int",plot_int);

  // Default nsteps to 0, allow us to set it to something else in the inputs file
  int nsteps   = 0;
  pp.query("nsteps",nsteps);

  // Define a single box covering the domain
#if (BL_SPACEDIM == 2)
  IntVect dom_lo(0,0);
  IntVect dom_hi(n_cell-1,n_cell-1);
#else
  IntVect dom_lo(0,0,0);
  IntVect dom_hi(n_cell-1,n_cell-1,n_cell-1);
#endif
  Box domain(dom_lo,dom_hi);

  // Initialize the boxarray "bs" from the single box "bx"
  BoxArray bs(domain);

  // Break up boxarray "bs" into chunks no larger than "max_grid_size" along a direction
  bs.maxSize(max_grid_size);

  // This defines the physical size of the box.  Right now the box is [-1,1] in each direction.
  RealBox real_box;
  for (int n = 0; n < BL_SPACEDIM; n++)
  {
     real_box.setLo(n,-1.0);
     real_box.setHi(n, 1.0);
  }

  // This says we are using Cartesian coordinates
  int coord = 0;

  // This sets the boundary conditions to be doubly or triply periodic
  int is_per[BL_SPACEDIM];
  for (int i = 0; i < BL_SPACEDIM; i++) is_per[i] = 1; 

  // This defines a Geometry object which is useful for writing the plotfiles  
  Geometry geom(domain,&real_box,coord,is_per);

  // This defines the mesh spacing
  Real dx[BL_SPACEDIM];
  for ( int n=0; n<BL_SPACEDIM; n++ )
      dx[n] = ( geom.ProbHi(n) - geom.ProbLo(n) )/domain.length(n);

  // Nghost = number of ghost cells for each array 
  int Nghost = 1;

  // Ncomp = number of components for each array
  int Ncomp  = 1;

  // Make sure we can fill the ghost cells from the adjacent grid
  if (Nghost > max_grid_size)
    std::cout <<  "NGHOST < MAX_GRID_SIZE --  grids are too small! " << std::endl;

  // Allocate space for the old_phi and new_phi -- we define old_phi and new_phi as
  //   pointers to the MultiFabs
  MultiFab* old_phi = new MultiFab(bs, Ncomp, Nghost);
  MultiFab* new_phi = new MultiFab(bs, Ncomp, Nghost);

  // Initialize both to zero (just because)
  old_phi->setVal(0.0);
  new_phi->setVal(0.0);

  // Initialize the old_phi by calling a Fortran routine.
  // MFIter = MultiFab Iterator
  for ( MFIter mfi(*new_phi); mfi.isValid(); ++mfi )
  {
    const Box& bx = mfi.validbox();

    FORT_INIT_PHI((*new_phi)[mfi].dataPtr(),
                     bx.loVect(),bx.hiVect(), &Nghost,
                     dx,geom.ProbLo(),geom.ProbHi());
  }

  // Call the compute_dt routine to return a time step which we will pass to advance
  Real dt = compute_dt(dx[0]);

  // Write a plotfile of the initial data if plot_int > 0 (plot_int was defined in the inputs file)
  if (plot_int > 0)
  {
     int n = 0;
     const std::string& pltfile = BoxLib::Concatenate("plt",n,5);
     writePlotFile(pltfile, *new_phi, geom);
  }

  // build the flux multifabs
  MultiFab* flux = new MultiFab[BL_SPACEDIM];
  for (int dir = 0; dir < BL_SPACEDIM; dir++)
    {
      BoxArray edge_grids(bs);
      // flux(dir) has one component, zero ghost cells, and is nodal in direction dir
      edge_grids.surroundingNodes(dir);
      flux[dir].define(edge_grids,1,0,Fab_allocate);
    }

  for (int n = 1; n <= nsteps; n++)
  {
     // Swap the pointers so we don't have to allocate and de-allocate data
     std::swap(old_phi, new_phi);

     // new_phi = old_phi + dt * (something)
     advance(old_phi, new_phi, flux, dx, dt, geom); 

     // Tell the I/O Processor to write out which step we're doing
     if (ParallelDescriptor::IOProcessor())
        std::cout << "Advanced step " << n << std::endl;

     // Write a plotfile of the current data (plot_int was defined in the inputs file)
     if (plot_int > 0 && n%plot_int == 0)
     {
        const std::string& pltfile = BoxLib::Concatenate("plt",n,5);
        writePlotFile(pltfile, *new_phi, geom);
     }
  }

  // Call the timer again and compute the maximum difference between the start time and stop time
  //   over all processors
  Real stop_time = ParallelDescriptor::second() - strt_time;
  const int IOProc = ParallelDescriptor::IOProcessorNumber();
  ParallelDescriptor::ReduceRealMax(stop_time,IOProc);

  // Tell the I/O Processor to write out the "run time"
  if (ParallelDescriptor::IOProcessor())
     std::cout << "Run time = " << stop_time << std::endl;
  
  // Say goodbye to MPI, etc...
  BoxLib::Finalize();

}
QRect LDesktopPluginSpace::findOpenSpot(int gridwidth, int gridheight, int startRow, int startCol, bool reversed, QString plugID){
  //Note about the return QPoint: x() is the column number, y() is the row number
  QPoint pt(0,0);
  //qDebug() << "FIND OPEN SPOT:" << gridwidth << gridheight << startRow << startCol << reversed;
  int row = startRow; int col = startCol;
  if(row<0){ row = 0; } //just in case - since this can be recursively called
  if(col<0){ col = 0; } //just in case - since this can be recursively called
  bool found = false;
  int rowCount, colCount;
  rowCount = RoundUp(this->height()/GRIDSIZE);
  colCount = RoundUp(this->width()/GRIDSIZE);
  if( (row+gridheight)>rowCount){ row = rowCount-gridheight; startRow = row; }
  if( (col+gridwidth)>colCount){ col = colCount-gridwidth; startCol = col; }
  QRect geom(0, 0, gridwidth*GRIDSIZE, gridheight*GRIDSIZE); //origin point will be adjusted in a moment
  if(DEBUG){ qDebug() << "Search for plugin space:" << rowCount << colCount << gridheight << gridwidth << this->size(); }
  if(TopToBottom && reversed && (startRow>0 || startCol>0) ){
    //Arrange Top->Bottom (work backwards)
    //qDebug() << "Search backwards for space:" << rowCount << colCount << startRow << startCol << gridheight << gridwidth;
    while(col>=0 && !found){
      while(row>=0 && !found){
        bool ok = true;
        geom.moveTo(col*GRIDSIZE, row*GRIDSIZE);
	//qDebug() << " - Check Geom:" << geom << col << row;
        //Check all the existing items to ensure no overlap
        for(int i=0; i<ITEMS.length() && ok; i++){
	  if(ITEMS[i]->whatsThis()==plugID){ continue; } //same plugin - this is not a conflict
          if(geom.intersects(ITEMS[i]->geometry())){
            //Collision - move the next searchable row/column index
	    ok = false;
	    //qDebug() << "Collision:" << col << row;
	    row = ((ITEMS[i]->geometry().y()-GRIDSIZE/2)/GRIDSIZE) -gridheight; //use top edge for next search (minus item height)
	    //qDebug() << " - new row:" << row;
	  }
        }
        if(ok){ pt = QPoint(col,row); found = true; } //found an open spot
      }
      if(!found){ col--; row=rowCount-gridheight; } //go to the previous column
    }
  }else if(TopToBottom){
    //Arrange Top->Bottom
    while(col<(colCount-gridwidth) && !found){
      while(row<(rowCount-gridheight) && !found){
        bool ok = true;
        geom.moveTo(col*GRIDSIZE, row*GRIDSIZE);
	//qDebug() << " - Check Geom:" << geom << col << row;
        //Check all the existing items to ensure no overlap
        for(int i=0; i<ITEMS.length() && ok; i++){
	  if(ITEMS[i]->whatsThis()==plugID){ continue; } //same plugin - this is not a conflict
          if(geom.intersects(ITEMS[i]->geometry())){
            //Collision - move the next searchable row/column index
	    ok = false;
	    row = posToGrid(ITEMS[i]->geometry().bottomLeft()).y(); //use bottom edge for next search
	  }
        }
        if(ok){ pt = QPoint(col,row); found = true; } //found an open spot
        //else{ row++; }
      }
      if(!found){ col++; row=0; } //go to the next column
    }	    
  }else if(reversed && (startRow>0 || startCol>0) ){
    //Arrange Left->Right (work backwards)
    while(row>=0 && !found){
      while(col>=0 && !found){
        bool ok = true;
        geom.moveTo(col*GRIDSIZE, row*GRIDSIZE);
        //Check all the existing items to ensure no overlap
        for(int i=0; i<ITEMS.length() && ok; i++){
	  if(ITEMS[i]->whatsThis()==plugID){ continue; } //same plugin - this is not a conflict
          if(geom.intersects(ITEMS[i]->geometry())){
            //Collision - move the next searchable row/column index
	    ok = false;
	    col = (ITEMS[i]->geometry().x()-GRIDSIZE/2)/GRIDSIZE - gridwidth; // Fill according to row/column
	  }
        }
        if(ok){ pt = QPoint(col,row); found = true; } //found an open spot
        //else{ col++; }
      }
      if(!found){ row--; col=colCount-gridwidth;} //go to the previous row
    }	  
  }else{
    //Arrange Left->Right
    while(row<(rowCount-gridheight) && !found){
      while(col<(colCount-gridwidth) && !found){
        bool ok = true;
        geom.moveTo(col*GRIDSIZE, row*GRIDSIZE);
        //Check all the existing items to ensure no overlap
        for(int i=0; i<ITEMS.length() && ok; i++){
	  if(ITEMS[i]->whatsThis()==plugID){ continue; } //same plugin - this is not a conflict
          if(geom.intersects(ITEMS[i]->geometry())){
            //Collision - move the next searchable row/column index
	    ok = false;
	    col = posToGrid(ITEMS[i]->geometry().topRight()).x(); // Fill according to row/column
	  }
        }
        if(ok){ pt = QPoint(col,row); found = true; } //found an open spot
        //else{ col++; }
      }
      if(!found){ row++; col=0;} //go to the next row
    }
  }
  if(!found){
    //qDebug() << "Could not find a spot:" << startRow << startCol << gridheight << gridwidth;
    if( (startRow!=0 || startCol!=0) && !reversed){
      //Did not check the entire screen yet - gradually work it's way back to the top/left corner
      //qDebug() << " - Start backwards search";
      return findOpenSpot(gridwidth, gridheight,startRow,startCol, true); //reverse the scan
    }else if(gridwidth>1 && gridheight>1){
      //Decrease the size of the item by 1x1 grid points and try again
      //qDebug() << " - Out of space: Decrease item size and try again...";
      return findOpenSpot(gridwidth-1, gridheight-1, 0, 0);
    }else{
      //qDebug() << " - Could not find an open spot for a desktop plugin:" << gridwidth << gridheight << startRow << startCol;
      return QRect(-1,-1,-1,-1);
    }
  }else{
    return QRect(pt,QSize(gridwidth,gridheight));
  }
}
Exemple #19
0
int
main (int argc, char* argv[])
{
    BoxLib::Initialize(argc,argv);

    // What time is it now?  We'll use this to compute total run time.
    Real strt_time = ParallelDescriptor::second();

    std::cout << std::setprecision(15);

    // ParmParse is way of reading inputs from the inputs file
    ParmParse pp;
    
    int verbose = 0;
    pp.query("verbose", verbose);
    
    // We need to get n_cell from the inputs file - this is the number of cells on each side of 
    //   a square (or cubic) domain.
    int n_cell;
    pp.get("n_cell",n_cell);

    int max_grid_size;
    pp.get("max_grid_size",max_grid_size);

    // Default plot_int to 1, allow us to set it to something else in the inputs file
    //  If plot_int < 0 then no plot files will be written
    int plot_int = 1;
    pp.query("plot_int",plot_int);

    // Default nsteps to 0, allow us to set it to something else in the inputs file
    int nsteps   = 0;
    pp.query("nsteps",nsteps);

    pp.query("do_tiling", do_tiling);

    // Define a single box covering the domain
    IntVect dom_lo(0,0,0);
    IntVect dom_hi(n_cell-1,n_cell-1,n_cell-1);
    Box domain(dom_lo,dom_hi);

    // Initialize the boxarray "bs" from the single box "bx"
    BoxArray bs(domain);

    // Break up boxarray "bs" into chunks no larger than "max_grid_size" along a direction
    bs.maxSize(max_grid_size);

    // This defines the physical size of the box.  Right now the box is [-1,1] in each direction.
    RealBox real_box;
    for (int n = 0; n < BL_SPACEDIM; n++) {
	real_box.setLo(n,-1.0);
	real_box.setHi(n, 1.0);
    }

    // This says we are using Cartesian coordinates
    int coord = 0;
    
    // This sets the boundary conditions to be doubly or triply periodic
    int is_per[BL_SPACEDIM];
    for (int i = 0; i < BL_SPACEDIM; i++) is_per[i] = 1; 
    
    // This defines a Geometry object which is useful for writing the plotfiles  
    Geometry geom(domain,&real_box,coord,is_per);

    // This defines the mesh spacing
    Real dx[BL_SPACEDIM];
    for ( int n=0; n<BL_SPACEDIM; n++ )
	dx[n] = ( geom.ProbHi(n) - geom.ProbLo(n) )/domain.length(n);

    // Nghost = number of ghost cells for each array 
    int Nghost = 1;

    // Ncomp = number of components for each array
    int Ncomp  = 1;
    pp.query("ncomp", Ncomp);

    // Allocate space for the old_phi and new_phi -- we define old_phi and new_phi as
    PArray < MultiFab > phis(2, PArrayManage);
    phis.set(0, new MultiFab(bs, Ncomp, Nghost));
    phis.set(1, new MultiFab(bs, Ncomp, Nghost));
    MultiFab* old_phi = &phis[0];
    MultiFab* new_phi = &phis[1];

    // Initialize both to zero (just because)
    old_phi->setVal(0.0);
    new_phi->setVal(0.0);

    // Initialize phi by calling a Fortran routine.
    // MFIter = MultiFab Iterator
#ifdef _OPENMP
#pragma omp parallel
#endif
    for ( MFIter mfi(*new_phi,true); mfi.isValid(); ++mfi )
    {
	const Box& bx = mfi.tilebox();

	init_phi(bx.loVect(),bx.hiVect(), 
		 BL_TO_FORTRAN((*new_phi)[mfi]),Ncomp,
		 dx,geom.ProbLo(),geom.ProbHi());
    }

    // Call the compute_dt routine to return a time step which we will pass to advance
    Real dt = compute_dt(dx[0]);

    // Write a plotfile of the initial data if plot_int > 0 (plot_int was defined in the inputs file)
    if (plot_int > 0) {
	int n = 0;
	const std::string& pltfile = BoxLib::Concatenate("plt",n,5);
	writePlotFile(pltfile, *new_phi, geom);
    }

    Real adv_start_time = ParallelDescriptor::second();

    for (int n = 1; n <= nsteps; n++)
    {
	// Swap the pointers so we don't have to allocate and de-allocate data
	std::swap(old_phi, new_phi);

	// new_phi = old_phi + dt * (something)
	advance(old_phi, new_phi, dx, dt, geom); 

	// Tell the I/O Processor to write out which step we're doing
	if (verbose && ParallelDescriptor::IOProcessor())
	    std::cout << "Advanced step " << n << std::endl;

	// Write a plotfile of the current data (plot_int was defined in the inputs file)
	if (plot_int > 0 && n%plot_int == 0) {
	    const std::string& pltfile = BoxLib::Concatenate("plt",n,5);
	    writePlotFile(pltfile, *new_phi, geom);
	}
    }

    // Call the timer again and compute the maximum difference between the start time and stop time
    //   over all processors
    Real advance_time = ParallelDescriptor::second() - adv_start_time;
    Real stop_time = ParallelDescriptor::second() - strt_time;
    const int IOProc = ParallelDescriptor::IOProcessorNumber();
    ParallelDescriptor::ReduceRealMax(stop_time,IOProc);
    ParallelDescriptor::ReduceRealMax(advance_time,IOProc);
    ParallelDescriptor::ReduceRealMax(kernel_time,IOProc);
    ParallelDescriptor::ReduceRealMax(FB_time,IOProc);
    
    // Tell the I/O Processor to write out the "run time"
    if (ParallelDescriptor::IOProcessor()) {
	std::cout << "Kernel    time = " << kernel_time << std::endl;
	std::cout << "FB        time = " << FB_time << std::endl;
	std::cout << "Advance   time = " << advance_time << std::endl;
	std::cout << "Total run time = " << stop_time << std::endl;
    }
    
    // Say goodbye to MPI, etc...
    BoxLib::Finalize();
}
Exemple #20
0
static void
option(int argc, char *argv[], void (*badusage)(void))
{
	char *cp;

	ARGBEGIN {
	default:
		badusage();
	case 'g':		/* Window geometry */
		if (geom(EARGF(badusage())) == 0)
			badusage();
		break;
	case 'b':		/* jit array bounds checking (obsolete, now on by default) */
		break;
	case 'B':		/* suppress jit array bounds checks */
		bflag = 0;
		break;
	case 'c':		/* Compile on the fly */
		cp = EARGF(badusage());
		if (!isnum(cp))
			badusage();
		cflag = atoi(cp);
		if(cflag < 0|| cflag > 9)
			usage();
		break;
	case 'I':	/* (temporary option) run without cons */
		dflag++;
		break;
	case 'd':		/* run as a daemon */
		dflag++;
		imod = EARGF(badusage());
		break;
	case 's':		/* No trap handling */
		sflag++;
		break;
	case 'm':		/* gc mark and sweep */
		cp = EARGF(badusage());
		if (!isnum(cp))
			badusage();
		mflag = atoi(cp);
		if(mflag < 0|| mflag > 9)
			usage();
		break;
	case 'p':		/* pool option */
		poolopt(EARGF(badusage()));
		break;
	case 'f':		/* Set font path */
		tkfont = EARGF(badusage());
		break;
	case 'r':		/* Set inferno root */
		strecpy(rootdir, rootdir+sizeof(rootdir), EARGF(badusage()));
		break;
	case '7':		/* use 7 bit colormap in X */
		xtblbit = 1;
		break;
	case 'G':		/* allow global access to file system (obsolete) */
		break;
	case	'C':		/* channel specification for display */
		cp = EARGF(badusage());
		displaychan = strtochan(cp);
		if(displaychan == 0){
			fprint(2, "emu: invalid channel specifier (-C): %q\n", cp);
			exits("usage");
		}
		break;
	case 'S':
		tkstylus = 1;
		break;
	case 'v':
		vflag = 1;	/* print startup messages */
		break;
	} ARGEND
}
bool QgsGeometryCheckerResultTab::exportErrorsDo( const QString &file )
{
  QList< QPair<QString, QString> > attributes;
  attributes.append( qMakePair( QStringLiteral( "Layer" ), QStringLiteral( "String;30;" ) ) );
  attributes.append( qMakePair( QStringLiteral( "FeatureID" ), QStringLiteral( "String;10;" ) ) );
  attributes.append( qMakePair( QStringLiteral( "ErrorDesc" ), QStringLiteral( "String;80;" ) ) );

  QFileInfo fi( file );
  QString ext = fi.suffix();
  QString driver = QgsVectorFileWriter::driverForExtension( ext );

  QLibrary ogrLib( QgsProviderRegistry::instance()->library( QStringLiteral( "ogr" ) ) );
  if ( !ogrLib.load() )
  {
    return false;
  }
  typedef bool ( *createEmptyDataSourceProc )( const QString &, const QString &, const QString &, QgsWkbTypes::Type, const QList< QPair<QString, QString> > &, const QgsCoordinateReferenceSystem &, QString & );
  createEmptyDataSourceProc createEmptyDataSource = ( createEmptyDataSourceProc ) cast_to_fptr( ogrLib.resolve( "createEmptyDataSource" ) );
  if ( !createEmptyDataSource )
  {
    return false;
  }
  QString createError;
  if ( !createEmptyDataSource( file, driver, "UTF-8", QgsWkbTypes::Point, attributes, QgsProject::instance()->crs(), createError ) )
  {
    return false;
  }

  const QgsVectorLayer::LayerOptions options { QgsProject::instance()->transformContext() };
  QgsVectorLayer *layer = new QgsVectorLayer( file, QFileInfo( file ).baseName(), QStringLiteral( "ogr" ), options );
  if ( !layer->isValid() )
  {
    delete layer;
    return false;
  }

  int fieldLayer = layer->fields().lookupField( QStringLiteral( "Layer" ) );
  int fieldFeatureId = layer->fields().lookupField( QStringLiteral( "FeatureID" ) );
  int fieldErrDesc = layer->fields().lookupField( QStringLiteral( "ErrorDesc" ) );
  for ( int row = 0, nRows = ui.tableWidgetErrors->rowCount(); row < nRows; ++row )
  {
    QgsGeometryCheckError *error = ui.tableWidgetErrors->item( row, 0 )->data( Qt::UserRole ).value<QgsGeometryCheckError *>();
    QgsVectorLayer *srcLayer = mChecker->featurePools()[error->layerId()]->layer();
    QgsFeature f( layer->fields() );
    f.setAttribute( fieldLayer, srcLayer->name() );
    f.setAttribute( fieldFeatureId, error->featureId() );
    f.setAttribute( fieldErrDesc, error->description() );
    QgsGeometry geom( new QgsPoint( error->location() ) );
    f.setGeometry( geom );
    layer->dataProvider()->addFeatures( QgsFeatureList() << f );
  }

  // Remove existing layer with same uri
  QStringList toRemove;
  for ( QgsMapLayer *maplayer : QgsProject::instance()->mapLayers() )
  {
    if ( qobject_cast<QgsVectorLayer *>( maplayer ) &&
         static_cast<QgsVectorLayer *>( maplayer )->dataProvider()->dataSourceUri() == layer->dataProvider()->dataSourceUri() )
    {
      toRemove.append( maplayer->id() );
    }
  }
  if ( !toRemove.isEmpty() )
  {
    QgsProject::instance()->removeMapLayers( toRemove );
  }

  QgsProject::instance()->addMapLayers( QList<QgsMapLayer *>() << layer );
  return true;
}
Exemple #22
0
	std::shared_ptr<ILoadableObject> ObjLoader::load(AssetManager *assetMgr, AssetInfo &asset)
	{
		shared_ptr<Node> node(new Node());

		std::string currentDir = std::string(asset.getFilePath());
		std::string nodeFileName = currentDir.substr(currentDir.find_last_of("\\/")+1);
		nodeFileName = nodeFileName.substr(0, nodeFileName.find_first_of(".")); // trim extension

		node->setName(nodeFileName);

		std::string line;
		while (std::getline(*asset.getStream(), line))
		{
			vector<string> tokens = split(line, ' ');
			tokens = removeEmptyStrings(tokens);

			if (tokens.size() == 0 || strcmp(tokens[0].c_str(), "#") == 0)
			{
			}
			else if (strcmp(tokens[0].c_str(), "v") == 0)
			{
				float x = parse<float>(tokens[1]);
				float y = parse<float>(tokens[2]);
				float z = parse<float>(tokens[3]);
				Vector3f vec(x, y, z);
				positions.push_back(vec);
			}
			else if (strcmp(tokens[0].c_str(), "vn") == 0)
			{
				float x = parse<float>(tokens[1]);
				float y = parse<float>(tokens[2]);
				float z = parse<float>(tokens[3]);
				Vector3f vec(x, y, z);
				normals.push_back(vec);
			}
			else if (strcmp(tokens[0].c_str(), "vt") == 0)
			{
				float x = parse<float>(tokens[1]);
				float y = parse<float>(tokens[2]);
				Vector2f vec(x, y);
				texCoords.push_back(vec);
			}
			else if (strcmp(tokens[0].c_str(), "f") == 0)
			{
				vector<ObjIndex> *c_idx = currentList();
				for (int i = 0; i < tokens.size() - 3; i++)
				{
					c_idx->push_back(parseObjIndex(tokens[1]));
					c_idx->push_back(parseObjIndex(tokens[2 + i]));
					c_idx->push_back(parseObjIndex(tokens[3 + i]));
				}
			}
			else if (strcmp(tokens[0].c_str(), "mtllib") == 0)
			{
				string libLoc = tokens[1];

				std::string currentDir = std::string(asset.getFilePath());
				currentDir = currentDir.substr(0, currentDir.find_last_of("\\/"));

				if (!contains(currentDir, "/") && !contains(currentDir, "\\"))	// the file path is just current file name,															   
				{																// so just make the string empty
					currentDir = "";
				}

				currentDir += "/" + libLoc;

				std::shared_ptr<MaterialList> mtlList = assetMgr->loadAs<MaterialList>(currentDir.c_str());
				this->mtlList = *mtlList.get();
			}
			else if (strcmp(tokens[0].c_str(), "usemtl") == 0)
			{
				string matname = tokens[1];
				newMesh(matname);
			}
		}

		for (int i = 0; i < objIndices.size(); i++)
		{
			vector<ObjIndex> *c_idx = objIndices[i];
			vector<Vertex> vertices;

			for (int j = 0; j < c_idx->size(); j++)
			{
				Vertex vert(positions[(*c_idx)[j].vertex_idx],
						   (hasTexCoords ? texCoords[(*c_idx)[j].texcoord_idx] : Vector2f()),
						   (hasNormals ? normals[(*c_idx)[j].normal_idx] : Vector3f()));

				vertices.push_back(vert);
			}

			shared_ptr<Mesh> mesh(new Mesh());
			mesh->setVertices(vertices);

			if (hasNormals)
				mesh->getAttributes().setAttribute(VertexAttributes::NORMALS);
			if (hasTexCoords)
				mesh->getAttributes().setAttribute(VertexAttributes::TEXCOORDS0);

			shared_ptr<Geometry> geom(new Geometry());
			geom->setName(names[i]);
			geom->setMesh(mesh);
			geom->setMaterial(materialWithName(namesMtl[i]));
			node->add(geom);

			delete c_idx;
		}

		return std::static_pointer_cast<ILoadableObject>(node);
	}
Exemple #23
0
void LineDomain::element_normal_at( Mesh::ElementHandle ,
                                    Vector3D &coordinate) const
    // no normal, return tangent instead.
  { coordinate = geom().direction(); }
Exemple #24
0
int main(int argc, char* argv[])
{
  BoxLib::Initialize(argc,argv);

  BL_PROFILE_VAR("main()", pmain);

  std::cout << std::setprecision(15);

  ParmParse ppmg("mg");  
  ppmg.query("v", verbose);
  ppmg.query("maxorder", maxorder);
  
  ParmParse pp;

  {
    std::string solver_type_s;
    pp.get("solver_type",solver_type_s);
    if (solver_type_s == "BoxLib_C") {
      solver_type = BoxLib_C;
    }
    else if (solver_type_s == "BoxLib_C4") {
      solver_type = BoxLib_C4;
    }
    else if (solver_type_s == "BoxLib_F") {
#ifdef USE_F90_SOLVERS
      solver_type = BoxLib_F;      
#else
      BoxLib::Error("Set USE_FORTRAN=TRUE in GNUmakefile");
#endif
    }
    else if (solver_type_s == "Hypre") {
#ifdef USEHYPRE
      solver_type = Hypre;
#else
      BoxLib::Error("Set USE_HYPRE=TRUE in GNUmakefile");
#endif
    }
    else if (solver_type_s == "All") {
      solver_type = All;
    }  
    else {
      if (ParallelDescriptor::IOProcessor()) {
	std::cout << "Don't know this solver type: " << solver_type << std::endl;
      }
      BoxLib::Error("");
    }
  }

  {
    std::string bc_type_s;
    pp.get("bc_type",bc_type_s);
    if (bc_type_s == "Dirichlet") {
      bc_type = Dirichlet;
#ifdef USEHPGMG
      domain_boundary_condition = BC_DIRICHLET;
#endif
    }
    else if (bc_type_s == "Neumann") {
      bc_type = Neumann;
#ifdef USEHPGMG
      BoxLib::Error("HPGMG does not support Neumann boundary conditions");
#endif
    }
    else if (bc_type_s == "Periodic") {
      bc_type = Periodic;
#ifdef USEHPGMG
      domain_boundary_condition = BC_PERIODIC;
#endif
    }
    else {
      if (ParallelDescriptor::IOProcessor()) {
	std::cout << "Don't know this boundary type: " << bc_type << std::endl;
      }
      BoxLib::Error("");
    }
  }

  pp.query("tol_rel", tolerance_rel);
  pp.query("tol_abs", tolerance_abs);
  pp.query("maxiter", maxiter);
  pp.query("plot_rhs" , plot_rhs);
  pp.query("plot_beta", plot_beta);
  pp.query("plot_soln", plot_soln);
  pp.query("plot_asol", plot_asol);
  pp.query("plot_err", plot_err);
  pp.query("comp_norm", comp_norm);

  Real a, b;
  pp.get("a",  a);
  pp.get("b",  b);

  pp.get("n_cell",n_cell);
  pp.get("max_grid_size",max_grid_size);

  // Define a single box covering the domain
  IntVect dom_lo(D_DECL(0,0,0));
  IntVect dom_hi(D_DECL(n_cell-1,n_cell-1,n_cell-1));
  Box domain(dom_lo,dom_hi);

  // Initialize the boxarray "bs" from the single box "bx"
  BoxArray bs(domain);

  // Break up boxarray "bs" into chunks no larger than "max_grid_size" along a direction
  bs.maxSize(max_grid_size);

  // This defines the physical size of the box.  Right now the box is [0,1] in each direction.
  RealBox real_box;
  for (int n = 0; n < BL_SPACEDIM; n++) {
    real_box.setLo(n, 0.0);
    real_box.setHi(n, 1.0);
  }
 
  // This says we are using Cartesian coordinates
  int coord = 0;
  
  // This sets the boundary conditions to be periodic or not
  Array<int> is_per(BL_SPACEDIM,1);
  
  if (bc_type == Dirichlet || bc_type == Neumann) {
    if (ParallelDescriptor::IOProcessor()) {
      std::cout << "Using Dirichlet or Neumann boundary conditions." << std::endl;
    }
    for (int n = 0; n < BL_SPACEDIM; n++) is_per[n] = 0;
  } 
  else {
    if (ParallelDescriptor::IOProcessor()) {
      std::cout << "Using periodic boundary conditions." << std::endl;
    }
    for (int n = 0; n < BL_SPACEDIM; n++) is_per[n] = 1;
  }
 
  // This defines a Geometry object which is useful for writing the plotfiles
  Geometry geom(domain,&real_box,coord,is_per.dataPtr());

  for ( int n=0; n<BL_SPACEDIM; n++ ) {
    dx[n] = ( geom.ProbHi(n) - geom.ProbLo(n) )/domain.length(n);
  }

  if (ParallelDescriptor::IOProcessor()) {
    std::cout << "Grid resolution : " << n_cell << " (cells)" << std::endl;
    std::cout << "Domain size     : " << real_box.hi(0) - real_box.lo(0) << " (length unit) " << std::endl;
    std::cout << "Max_grid_size   : " << max_grid_size << " (cells)" << std::endl;
    std::cout << "Number of grids : " << bs.size() << std::endl;
  }

  // Allocate and define the right hand side.
  bool do_4th = (solver_type==BoxLib_C4 || solver_type==All);
  int ngr = (do_4th ? 1 : 0);
  MultiFab rhs(bs, Ncomp, ngr); 
  setup_rhs(rhs, geom);

  // Set up the Helmholtz operator coefficients.
  MultiFab alpha(bs, Ncomp, 0);
  PArray<MultiFab> beta(BL_SPACEDIM, PArrayManage);
  for ( int n=0; n<BL_SPACEDIM; ++n ) {
    BoxArray bx(bs);
    beta.set(n, new MultiFab(bx.surroundingNodes(n), Ncomp, 0, Fab_allocate));
  }

  // The way HPGMG stores face-centered data is completely different than the
  // way BoxLib does it, and translating between the two directly via indexing
  // magic is a nightmare. Happily, the way this tutorial calculates
  // face-centered values is by first calculating cell-centered values and then
  // interpolating to the cell faces. HPGMG can do the same thing, so rather
  // than converting directly from BoxLib's face-centered data to HPGMG's, just
  // give HPGMG the cell-centered data and let it interpolate itself.

  MultiFab beta_cc(bs,Ncomp,1); // cell-centered beta
  setup_coeffs(bs, alpha, beta, geom, beta_cc);

  MultiFab alpha4, beta4;
  if (do_4th) {
    alpha4.define(bs, Ncomp, 4, Fab_allocate);
    beta4.define(bs, Ncomp, 3, Fab_allocate);
    setup_coeffs4(bs, alpha4, beta4, geom);
  }

  MultiFab anaSoln;
  if (comp_norm || plot_err || plot_asol) {
    anaSoln.define(bs, Ncomp, 0, Fab_allocate);
    compute_analyticSolution(anaSoln,Array<Real>(BL_SPACEDIM,0.5));
    
    if (plot_asol) {
      writePlotFile("ASOL", anaSoln, geom);
    }
  }

  // Allocate the solution array 
  // Set the number of ghost cells in the solution array.
  MultiFab soln(bs, Ncomp, 1);
  MultiFab soln4;
  if (do_4th) {
    soln4.define(bs, Ncomp, 3, Fab_allocate);
  }
  MultiFab gphi(bs, BL_SPACEDIM, 0);

#ifdef USEHYPRE
  if (solver_type == Hypre || solver_type == All) {
    if (ParallelDescriptor::IOProcessor()) {
      std::cout << "----------------------------------------" << std::endl;
      std::cout << "Solving with Hypre " << std::endl;
    }

    solve(soln, anaSoln, gphi, a, b, alpha, beta, beta_cc, rhs, bs, geom, Hypre);
  }
#endif

  if (solver_type == BoxLib_C || solver_type == All) {
    if (ParallelDescriptor::IOProcessor()) {
      std::cout << "----------------------------------------" << std::endl;
      std::cout << "Solving with BoxLib C++ solver " << std::endl;
    }
    solve(soln, anaSoln, gphi, a, b, alpha, beta, beta_cc, rhs, bs, geom, BoxLib_C);
  }

  if (solver_type == BoxLib_C4 || solver_type == All) {
    if (ParallelDescriptor::IOProcessor()) {
      std::cout << "----------------------------------------" << std::endl;
      std::cout << "Solving with BoxLib C++ 4th order solver " << std::endl;
    }

    solve4(soln4, anaSoln, a, b, alpha4, beta4, rhs, bs, geom);
  }

#ifdef USE_F90_SOLVERS
  if (solver_type == BoxLib_F || solver_type == All) {
    if (ParallelDescriptor::IOProcessor()) {
      std::cout << "----------------------------------------" << std::endl;
      std::cout << "Solving with BoxLib F90 solver " << std::endl;
    }

    solve(soln, anaSoln, gphi, a, b, alpha, beta, beta_cc, rhs, bs, geom, BoxLib_F);
  }
#endif

#ifdef USEHPGMG
  if (solver_type == HPGMG || solver_type == All) {
    if (ParallelDescriptor::IOProcessor()) {
      std::cout << "----------------------------------------" << std::endl;
      std::cout << "Solving with HPGMG solver " << std::endl;
    }

    solve(soln, anaSoln, gphi, a, b, alpha, beta, beta_cc, rhs, bs, geom, HPGMG);
  }
#endif

  if (ParallelDescriptor::IOProcessor()) {
    std::cout << "----------------------------------------" << std::endl;
  }
  
  BL_PROFILE_VAR_STOP(pmain);

  BoxLib::Finalize();
}
Exemple #25
0
void PointDomain::snap_to( Mesh::VertexHandle,
                           Vector3D &coordinate) const
  { coordinate = geom(); }
Exemple #26
0
std::auto_ptr<scene::SceneGeometry>
Utilities::getSceneGeometry(const DerivedData* derived)
{
    const double centerTime = getCenterTime(*derived);

    // compute arpPos and arpVel
    six::Vector3 arpPos = derived->measurement->arpPoly(centerTime);
    six::Vector3 arpVel =
            derived->measurement->arpPoly.derivative()(centerTime);
    six::Vector3 refPt = derived->measurement->projection->referencePoint.ecef;

    six::Vector3 rowVec;
    six::Vector3 colVec;

    if (derived->measurement->projection->projectionType
            == six::ProjectionType::POLYNOMIAL)
    {
        const six::sidd::PolynomialProjection* projection =
            reinterpret_cast<const six::sidd::PolynomialProjection*>(
                derived->measurement->projection.get());

        double cR = projection->referencePoint.rowCol.row;
        double cC = projection->referencePoint.rowCol.col;

        scene::LatLonAlt centerLLA;
        centerLLA.setLat(projection->rowColToLat(cR, cC));
        centerLLA.setLon(projection->rowColToLon(cR, cC));
        six::Vector3 centerEcef = scene::Utilities::latLonToECEF(centerLLA);

        scene::LatLonAlt downLLA;
        downLLA.setLat(projection->rowColToLat(cR + 1, cC));
        downLLA.setLon(projection->rowColToLon(cR + 1, cC));
        six::Vector3 downEcef = scene::Utilities::latLonToECEF(downLLA);

        scene::LatLonAlt rightLLA;
        rightLLA.setLat(projection->rowColToLat(cR, cC + 1));
        rightLLA.setLon(projection->rowColToLon(cR, cC + 1));
        six::Vector3 rightEcef = scene::Utilities::latLonToECEF(rightLLA);

        rowVec = downEcef - centerEcef;
        rowVec.normalize();
        colVec = rightEcef - centerEcef;
        colVec.normalize();
    }
    else if (derived->measurement->projection->projectionType
            == six::ProjectionType::PLANE)
    {
        const six::sidd::PlaneProjection* projection =
                reinterpret_cast<const six::sidd::PlaneProjection*>(
                    derived->measurement->projection.get());

        rowVec = projection->productPlane.rowUnitVector;
        colVec = projection->productPlane.colUnitVector;
    }
    else if (derived->measurement->projection->projectionType
            == six::ProjectionType::GEOGRAPHIC)
    {
        // In this case there are no image plane row/col vectors, so we want
        // to use a different constructor
        std::auto_ptr<scene::SceneGeometry> geom(new scene::SceneGeometry(
                    arpVel, arpPos, refPt));
        return geom;
    }
    else
    {
        throw except::Exception(Ctxt(
                "Cylindrical projection not yet supported"));
    }

    std::auto_ptr<scene::SceneGeometry> geom(new scene::SceneGeometry(
            arpVel, arpPos, refPt, rowVec, colVec));
    return geom;
}