/// <summary> /// Instantiates an empty point cloud, ready for us to dump some data /// </summary> public vtkICP() { //instantiate empty lists and point clouds pointClouds = new List<PointCloud>(); txpointClouds = new List<PointCloud>(); pcd = new PointCloud(); //instantiate vtk lists vtkICPAlgo = new vtkIterativeClosestPointTransform(); sourceData = new vtkPoints(); sourcePoints = new vtkCellArray(); }
// Use this for initialization void Start () { this.pointCloud = this.pointCloudShadow.GetComponent<PointCloud>(); this.cipcLS = this.CIPCforLS.GetComponent<CIPCReceiverLaserScaner>(); this.CP = new CalculatePosition(); }
/// <summary> /// Instantiates an empty point cloud, ready for us to dump some data /// </summary> public BoundingBox() { //instantiate empty lists and point clouds pointClouds = new List<PointCloud>(); txpointClouds = new List<PointCloud>(); pcd = new PointCloud(); }
public void LoadFile(string f) { //http://answers.unity3d.com/questions/9960/how-do-i-let-the-user-select-a-local-file-for-my-a.html //dbgString = "should load "+f; GameObject go = new GameObject("PointCloud"); pc = go.AddComponent<PointCloud>(); pc.particleSystem.renderer.material = pointsMaterial; //GameObject p = new GameObject("pointcloud"); //PointCloud pc = Instantiate(pointCloudPrefab) as PointCloud; //p.AddComponent<ParticleSystem>(); //PointCloud pc = ps.GetComponent<PointCloud>(); pc.LoadPointsFromPts(f); cameraRotater.position = pc.transform.position; //Debug.Log("loaded file, now reseting particles"); //pc.ResetParticles();//why not???? CancelInvoke("RestartParticlesLater"); Invoke("ResetParticlesLater", 6f);//why????? what a hack! clouds.Add(pc); dbgString+="\nloaded file "+num; num++; }
/// <summary> /// Instantiates an empty point cloud, ready for us to dump some data /// </summary> public AffineICP() { //instantiate empty lists and point clouds pointClouds = new List<PointCloud>(); txpointClouds = new List<PointCloud>(); pcd = new PointCloud(); }
/// <summary> /// Nothing flashy here. Just saves the point cloud into memory /// </summary> /// <param name="pcd">A point cloud</param> /// <param name="xSep">Number of x separations</param> /// <param name="ySep">Number of y separations</param> /// <param name="zSep">Number of z separations</param> VoxelGrid(PointCloud pcd, int xSep, int ySep, int zSep) { this.pcd = pcd; this.xSep = xSep; this.ySep = ySep; this.zSep = zSep; }
public CloudSystem(ParticleSystem ps, PointCloud pc, float scaleFactor, Vector3 negaXYZ) { this.particleSystem = ps; this.scaleFactor = scaleFactor; this.transFactor = transFactor; this.particleCloud = new ParticleSystem.Particle[pc.PointList.Length]; SetPoints(pc); }
// Use this for initialization void Start() { this.pointcloud = pointCloudShadow.GetComponent<PointCloud>(); this.FpsAd = new FPSAdjuster.FPSAdjuster(); this.FpsAd.Fps = 30; this.FpsAd.Start(); }
public void LoadMesh(Mesh m) { GameObject go = new GameObject("PointCloudMesh"); pc = go.AddComponent<PointCloud>(); pc.particleSystem.renderer.material = pointsMaterial; pc.LoadPointsFromMesh(m); pc.ResetParticles(); cameraRotater.position = pc.transform.position; clouds.Add(pc); }
public override void add(PointCloud pc) { //stick into the pointcloud list this.pointClouds.Add(pc); //if the point cloud list isn't empty, register against previous scan if (this.pointClouds.Count != 0) { //register against previous scan //dump the points from the cloud into the points } }
// Replace single particle in particleCloud with single cloud point at the inputted index within the inputted PointCloud public void SetPoint(PointCloud pc, int index) { // Set position of particles to match those of the 3-D points. Vector3 newPos = new Vector3(pc.PointList[index].location[0], pc.PointList[index].location[1], pc.PointList[index].location[2]); newPos -= negaXYZ; newPos /= scaleFactor; particleCloud[index].position = newPos; // Color points according to Color[] array. particleCloud[index].color = pc.PointList[index].color; // Static size. particleCloud[index].size = particleSize; updatePoints(); }
void Start() { this.robotLight = this.robot.transform.FindChild("RobotLight").gameObject; this.cipcKinect = this.CIPCforKinect.GetComponent<CIPCReceiver>(); this.cipcLS = this.CIPCforLaserScaner.GetComponent<CIPCReceiverLaserScaner>(); this.pointCloud = this.depth.GetComponent<PointCloud>(); this.List_Human = new List<Human>(); this.list_humanpos = new List<Vector3>(); this.cp = new CalculatePosition(0); this.centerPos = Vector3.zero; this.preCenterPos = new Vector3(); this.pretime = 0; Debug.Log("Light Robot"); }
// Set particle positions according to point coordinates using single PointCloud parameter. public void SetPoints(PointCloud pc) { for (int i = 0; i < pc.PointList.Length; ++i) { // Set position of particles to match those of the 3-D points. Vector3 newPos = new Vector3(pc.PointList[i].location[0], pc.PointList[i].location[1], pc.PointList[i].location[2]); newPos -= transFactor; newPos /= scaleFactor; particleCloud[i].position = newPos; // Color points according to Color[] array. particleCloud[i].color = pc.PointList[i].color; // Static size. particleCloud[i].size = particleSize; //print("{ x: " + cloud[i].position.x + " // y: " + cloud[i].position.y + " // z: " + cloud[i].position.z + " }"); } updatePoints(); }
public static AbstractMeshCreator CreateMesh(PointCloud pointCloud, Type type, bool cleanMesh) { switch (type) { case Type.Convex: { var creator = new ShapeMeshCreator(pointCloud, cleanMesh); creator.CreateMeshCutoff(false); return(creator); } case Type.ConvexWithAttachments: { var creator = new ShapeMeshCreator(pointCloud, cleanMesh); creator.CreateMeshCutoff(true); return(creator); } case Type.SplitLayout: { var creator = new ShapeMeshCreator(pointCloud, cleanMesh); creator.CreateMeshWithPermutations(); return(creator); } case Type.Layout: { var creator = new ShapeMeshCreator(pointCloud, cleanMesh); creator.CreateLayoutMesh(); return(creator); } case Type.TriangulatePoints: { var creator = new PointMeshCreator(pointCloud, cleanMesh); creator.CreateMesh(); return(creator); } default: throw new System.NotImplementedException(); } }
public void WikipediaBuildTests() { // Should generate the following tree: // 7,2 // | // +------+-----+ // 5,4 9,6 // | | // +---+---+ +--+ // 2,3 4,7 8,1 Vector3[] points = new Vector3[] { new Vector3(7, 2, 0), new Vector3(5, 4, 0), new Vector3(2, 3, 0), new Vector3(4, 7, 0), new Vector3(9, 6, 0), new Vector3(8, 1, 0) }; List <Vector3> listV = new List <Vector3>(points); pointCloudTarget = PointCloud.FromListVector3(listV); pointCloudSource = pointCloudTarget.Clone(); pointCloudSource.ShuffleVectors(); //------------------- GlobalVariables.ResetTime(); this.pointCloudResult = tree.BuildAndFindClosestPoints(pointCloudSource, pointCloudTarget, false); // this.pointCloudResult = tree.BuildAndFindClosestPoints_NotParallel(pointCloudSource, pointCloudTarget, false); GlobalVariables.ShowLastTimeSpan("Search "); Assert.IsTrue(tree.MeanDistance == 0); for (int i = 0; i < pointCloudTarget.Vectors.Length; i++) { //Assert.That(pointCloudResult.Vectors[i], Is.EqualTo(pointCloudTarget.Vectors[i])); Assert.IsTrue(pointCloudSource.Vectors[i].Equals(pointCloudResult.Vectors[i])); } }
public static void CallBack(ROSBridgeMsg msg) //after receiving the ros message { PointCloud2Msg cloudm = (PointCloud2Msg)msg; //point cloud message PointCloud <PointXYZRGB> points = cloudm.GetCloud(); // get data, the data has point location and point color information PointXYZRGB point; //variable to access information of single point in the list of points //voxel mesh with triangles numPoints = points.Size; //number of points received mpoints = new Vector3[numPoints]; colors = new Color[numPoints]; //store points and colors of the point cloud separately in arrays for (int i = 0; i < numPoints; i++) { point = points.At(i); //point at index i in the list mpoints[i] = new Vector3(point.X, point.Z, point.Y); colors[i] = new Color(point.R / 255.0f, point.G / 255.0f, point.B / 255.0f); } // generate child meshes total_meshes = Mathf.CeilToInt(numPoints * 1.0f / Points_limit * 1.0f); //calculate the number of child meshes required main_mesh = GameObject.Find(Mesh_name); //find the mesh in unity environment if (main_mesh == null) { main_mesh = new GameObject(Mesh_name); //if no mesh found, create one } else { //do nothing } //initialize the mesh for (int i = 0; i < total_meshes - 1; i++) { Mesh_initialization(i, Points_limit); } Mesh_initialization(total_meshes - 1, numPoints - (total_meshes - 1) * Points_limit); }
// Update is called once per frame void Update() { // Skip if ARCore is not tracking if (Frame.TrackingState != FrameTrackingState.Tracking) { return; } // Get the Point cloud from the Frame PointCloud pointCloud = Frame.PointCloud; // Make Vertices / Indices array of Point Cloud size int pCount = pointCloud.PointCount; Vector3 [] vertices = new Vector3[pCount]; int [] indices = new int[pCount]; // If the Point Cloud was not empty and the observed timestamp was new if (pCount > 0 && pointCloud.Timestamp > lastTimeStamp) { for (int i = 0; i < pCount; i++) { //Set the vertices as each Point Cloud point vertices [i] = pointCloud.GetPoint(i); // Update the mesh indices array indices [i] = i; } // Update the mesh with vertices and indices mesh.Clear(); mesh.vertices = vertices; mesh.SetIndices(indices, MeshTopology.Points, 0); lastTimeStamp = pointCloud.Timestamp; } }
/// <summary> /// Updates the OpenGL buffer contents to the provided point. Repeated calls with the same /// point cloud will be ignored. /// </summary> public void Update(PointCloud cloud) { if (mLastPointCloud == cloud) { return; } GLES20.GlBindBuffer(GLES20.GlArrayBuffer, mVbo); mLastPointCloud = cloud; // If the VBO is not large enough to fit the new point cloud, resize it. mNumPoints = mLastPointCloud.Points.Remaining() / FLOATS_PER_POINT; if (mNumPoints * BYTES_PER_POINT > mVboSize) { while (mNumPoints * BYTES_PER_POINT > mVboSize) { mVboSize *= 2; } GLES20.GlBufferData(GLES20.GlArrayBuffer, mVboSize, null, GLES20.GlDynamicDraw); } GLES20.GlBufferSubData(GLES20.GlArrayBuffer, 0, mNumPoints * BYTES_PER_POINT, mLastPointCloud.Points); GLES20.GlBindBuffer(GLES20.GlArrayBuffer, 0); }
/// <summary> /// calculates the delaunay volume of a given point cloud /// </summary> /// <param name="pointCloud">the point cloud</param> /// <returns>the volume of the point cloud</returns> public static float calculateDelaunayVolume(PointCloud pointCloud) { if (pointCloud.count < 5) { return(0); } //updates the status Log.LogManager.updateAlgorithmStatus("Delaunay Volume"); //vars float returnValue = 0; try { //create delaunay List <Tetrahedron> tetrahedrons = createDelaunayTetrahedrons(pointCloud); //calculate volume of tetrahedons //http://en.wikipedia.org/wiki/Tetrahedron#Volume foreach (Tetrahedron c in tetrahedrons) { returnValue += ((float)Math.Abs( determinant3x3(substract(c.Vertices[0], c.Vertices[1]), substract(c.Vertices[1], c.Vertices[2]), substract(c.Vertices[2], c.Vertices[3])) ) / 6); } } catch (Exception) { return(0); } //updates the status Log.LogManager.updateAlgorithmStatus("Done"); return(returnValue); }
public void ProgressCallbackWorks() { var CHUNKSIZE = 10000; var CHUNKCOUNT = 10; var countProgressCallbacks = 0L; var config = ImportConfig.Default .WithStorage(PointCloud.CreateInMemoryStore()) .WithKey("test") .WithProgressCallback(x => Interlocked.Increment(ref countProgressCallbacks)); ; var pointcloud = PointCloud.Chunks(GenerateChunks(CHUNKSIZE).Take(CHUNKCOUNT), config); Assert.IsTrue(pointcloud.PointCount == CHUNKSIZE * CHUNKCOUNT); Assert.IsTrue(countProgressCallbacks > 10); IEnumerable <Chunk> GenerateChunks(int numberOfPointsPerChunk) { var r = new Random(); while (true) { var _ps = new V3d[numberOfPointsPerChunk]; for (var i = 0; i < numberOfPointsPerChunk; i++) { _ps[i] = new V3d(r.NextDouble(), r.NextDouble(), r.NextDouble()); } yield return(new Chunk(_ps)); } } }
public static NXOpen.Point[] ToPoints(this PointCloud value, double factor) { var array = new NXOpen.Point[value.Count]; int index = 0; if (factor == 1.0) { foreach (var point in value) { var location = point.Location; array[index++] = WorkPart.Points.CreatePoint(new NXOpen.Point3d(location.X, location.Y, location.Z)); } } else { foreach (var point in value) { var location = point.Location; array[index++] = WorkPart.Points.CreatePoint(new NXOpen.Point3d(location.X * factor, location.Y * factor, location.Z * factor)); } } return(array); }
public void CanImport_Empty() { var config = ImportConfig.Default .WithStorage(PointCloud.CreateInMemoryStore()) .WithKey("test") .WithOctreeSplitLimit(10) .WithCreateOctreeLod(false) .WithDeduplicateChunks(false) .WithMinDist(0.0) .WithReproject(null) .WithEstimateNormals(null) ; var pointcloud = PointCloud.Chunks(new Chunk[] { }, config); Assert.IsTrue(pointcloud.Id == "test"); Assert.IsTrue(pointcloud.PointCount == 0); var reloaded = config.Storage.GetPointSet("test", CancellationToken.None); Assert.IsTrue(reloaded.Id == "test"); Assert.IsTrue(reloaded.PointCount == 0); }
public void CanImportChunk_MinDist() { int n = 100; var r = new Random(); var ps = new V3d[n]; for (var i = 0; i < n; i++) { ps[i] = new V3d(r.NextDouble(), r.NextDouble(), r.NextDouble()); } var chunk = new Chunk(ps); Assert.IsTrue(chunk.Count == 100); var config = ImportConfig.Default .WithStorage(PointCloud.CreateInMemoryStore()) .WithKey("test") .WithOctreeSplitLimit(10) .WithMinDist(0.5) ; var pointcloud = PointCloud.Chunks(chunk, config); Assert.IsTrue(pointcloud.PointCount < 100); }
/// <summary> /// This is the method that actually does the work. /// </summary> /// <param name="DA">The DA object can be used to retrieve data from input parameters and /// to store data in output parameters.</param> protected override void SolveInstance(IGH_DataAccess DA) { PointCloud pc = null; if (!DA.GetData(0, ref pc)) { return; } ///Write ErrorMessage eles add box to Box List. if (!pc.UserDictionary.ContainsKey("ColorGradient")) { this.AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Cloud doesn't contain ColorGradient Information."); return; } List <Color> Colors = Color_Utils.Get_Colors(pc); List <double> Values = Color_Utils.Get_ColorValues(pc); DA.SetDataList(0, Colors); DA.SetDataList(1, Values); }
public void ShowAxes_Rotated() { CreateRectangle(); pointCloudTarget = null; PointCloud.RotateDegrees(pointCloudSource, 0, 0, -45); pca.PCA_OfPointCloud(pointCloudSource); //-----------Show in Window if (UIMode) { ShowResultsInWindow_Cube(true); } System.Diagnostics.Debug.Write(pointCloudSource.PCAAxes.PrintVectors()); //----------------check Result expectedResultCloud.AddVector(new Vector3(-0.707106781186548f, -0.707106781186548f, 0)); expectedResultCloud.AddVector(new Vector3(-0.353553390593274f, 0.353553390593274f, 0)); expectedResultCloud.AddVector(new Vector3(0, 0, 0)); float meanDistance = PointCloud.MeanDistance(expectedResultCloud, pointCloudSource.PCAAxes); Assert.IsTrue(this.threshold > meanDistance); }
public void Face_15000_Centered() { string fileNameLong = pathUnitTests + "\\KinectFace_1_15000.obj"; pointCloudTarget = PointCloud.FromObjFile(fileNameLong); pointCloudTarget = PointCloud.ShiftByCenterOfMass(pointCloudTarget); pointCloudSource = pointCloudTarget.Clone(); //pointCloudSource.Translate(2, 0, 0); GlobalVariables.ResetTime(); //------------------- this.pointCloudResult = tree.BuildAndFindClosestPoints(pointCloudSource, pointCloudTarget, false); GlobalVariables.ShowLastTimeSpan("Search "); float meanDistance = PointCloud.MeanDistance(pointCloudSource, pointCloudResult); float meanDistance1 = PointCloud.MeanDistance(pointCloudSource, pointCloudTarget); float meanDistance2 = PointCloud.MeanDistance(pointCloudTarget, pointCloudResult); //ShowPointCloudsInWindow_PCAVectors(true); Assert.IsTrue(meanDistance == 0); }
private static PointSet CreateClusteredPointsInUnitCube(int n, int splitLimit) { var r = new Random(); V3d randomPos() => new V3d(r.NextDouble(), r.NextDouble(), r.NextDouble()); var ps = new V3d[n]; for (var i = 0; i < n / 2; i++) { ps[i] = randomPos(); } for (var i = n / 2 + 1; i < n; i++) { ps[i] = randomPos(); } var config = ImportConfig.Default .WithStorage(PointCloud.CreateInMemoryStore()) .WithKey("test") .WithOctreeSplitLimit(splitLimit) ; return(PointCloud.Chunks(new Chunk(ps, null), config)); }
public PointCloud2Msg(JSONNode msg) { _header = new HeaderMsg(msg ["header"]); _height = uint.Parse(msg ["height"]); _width = uint.Parse(msg ["width"]); _is_bigendian = msg["is_bigendian"].AsBool; _is_dense = msg["is_dense"].AsBool; _point_step = uint.Parse(msg ["point_step"]); _row_step = uint.Parse(msg ["row_step"]); _fields = new PointFieldMsg[msg["fields"].Count]; for (int i = 0; i < _fields.Length; i++) { _fields[i] = new PointFieldMsg(msg["fields"][i]); } if (msg["data"] == null) { _cloud = new PointCloud <PointXYZIntensity>(); } else { _data = System.Convert.FromBase64String(msg["data"]); _cloud = ReadData(_data); } }
/// <summary> /// /// </summary> /// <param name="filename">File to read from</param> /// <param name="offset">Offset to start reading from</param> /// <returns>Pointcloud of type T</returns> public PointCloud <T> Read(String filename, int offset) { PCDHeader header = ReadHeader(filename); List <T> pointList; // Start reading data using (StreamReader sr = new StreamReader(filename)) { String line = sr.ReadLine(); while (!line.Contains("DATA")) { line = sr.ReadLine(); } if (line.Contains("ascii")) { pointList = readData(sr); } //else if (line.Contains("binary")) //{ //} else { throw new PCDReaderException("Data in file in unrecognized format."); } } PointCloud <T> cloud = new PointCloud <T>(pointList); cloud.Height = header.Height; cloud.Width = header.Width; return(cloud); }
public void SetPointCloud(PointCloud <PointXYZIntensity> newCloud) { if (particles.Length < newCloud.Size) { int oldSize = particles.Length; particles = new ParticleSystem.Particle[newCloud.Size]; cloud.GetParticles(particles); for (int i = oldSize; i < particles.Length; i++) { particles[i] = new ParticleSystem.Particle(); } } int ind = 0; foreach (PointXYZIntensity point in newCloud.Points) { particles[ind].position = (flipYZ) ? new Vector3(point.X, point.Z, point.Y) : new Vector3(point.X, point.Y, point.Z); particles[ind].startSize = 0.1f; ind += 1; } particle_count = newCloud.Size; cloud.SetParticles(particles, particle_count); OnParticlesUpdated(); }
void SetTypeClosest(IEnumerable <GeometryBase> attractors, double maxDistance) { var points = attractors.Where(a => a is Point).Select(p => (p as Point).Location); var curves = attractors.Where(a => a is Curve).Select(c => (c as Curve)); var pointCloud = new PointCloud(points); foreach (var voxel in GetVoxels().Where(v => v.IsActive)) { Point3d p = voxel.Location.Origin; var closestIndex = pointCloud.ClosestPoint(p); var closestPoint = pointCloud[closestIndex].Location; double minDistance = p.DistanceToSquared(closestPoint); foreach (var curve in curves) { if (curve.ClosestPoint(p, out double t, minDistance)) { minDistance = curve.PointAt(t).DistanceToSquared(p); } } var distance = Sqrt(minDistance); var param = distance / maxDistance; param = Rhino.RhinoMath.Clamp(param, 0.0, 1.0); var typeCount = _typesCount.Max(); var type = (int)(param * typeCount); if (type == typeCount) { type--; } voxel.AttractorDistance = param; voxel.Type = type; } }
public static DB.Point[] ToPoints(this PointCloud value, double factor) { var array = new DB.Point[value.Count]; int index = 0; if (factor == 1.0) { foreach (var point in value) { var location = point.Location; array[index++] = DB.Point.Create(new DB::XYZ(location.X, location.Y, location.Z)); } } else { foreach (var point in value) { var location = point.Location; array[index++] = DB.Point.Create(new DB::XYZ(location.X * factor, location.Y * factor, location.Z * factor)); } } return(array); }
/// <summary> /// Merge PointCloud Pieces to NewCloud with UserDictionaries. /// </summary> /// <param name="NewCloud"> PointCloud to Merge (add) to. </param> /// <param name="CloudPieces">PointCloud Pieces to Merge. </param> public static void MergeClouds(ref PointCloud NewCloud, PointCloud[] CloudPieces) { foreach (PointCloud pc in CloudPieces) { //Add PointCloud Pieces to NewCloud. if (pc != null) { NewCloud.Merge(pc); } //Add UserDictionary from PointCloud Pieces to NewCloud. if (pc.HasUserData) { foreach (string key in pc.UserDictionary.Keys) { double[] newDict = null; //Add to Dictionary if NewCloud already has a Dictionary with Key //Else Create Dictionary with Key. if (NewCloud.UserDictionary.ContainsKey(key)) { double[] Dict = (double[])NewCloud.UserDictionary[key]; double[] MyDict = (double[])pc.UserDictionary[key]; List <Double> listNewDict = new List <double>(Dict); listNewDict.AddRange(MyDict); newDict = listNewDict.ToArray(); } else { newDict = (double[])pc.UserDictionary[key]; } NewCloud.UserDictionary.Set(key, newDict); newDict = null; } } } }
public void Persons_V_4() { this.pointCloudTarget = new PointCloud(pathUnitTests + "\\2.obj"); this.pointCloudSource = new PointCloud(pathUnitTests + "\\1.obj"); this.pointCloudResult = pca.AlignPointClouds_OneVector(this.pointCloudSource, this.pointCloudTarget, 0, 0); this.pointCloudSource = PointCloud.CloneAll(pointCloudResult); this.pointCloudResult = pca.AlignPointClouds_OneVector(this.pointCloudSource, this.pointCloudTarget, 1, 1); this.pointCloudSource = PointCloud.CloneAll(pointCloudResult); this.pointCloudResult = pca.AlignPointClouds_OneVector(this.pointCloudSource, this.pointCloudTarget, 2, 2); this.pointCloudSource = PointCloud.CloneAll(pointCloudResult); this.pointCloudResult = pca.AlignPointClouds_OneVector(this.pointCloudSource, this.pointCloudTarget, 1, 1); this.pointCloudSource = PointCloud.CloneAll(pointCloudResult); this.pointCloudResult = pca.AlignPointClouds_SVD(this.pointCloudSource, this.pointCloudTarget); ShowPointCloudsInWindow_PCAVectors(true); Assert.IsTrue(this.threshold > pca.MeanDistance); }
public static float Test7_Face_KnownTransformation_PCA_15000(ref PointCloud mypointCloudTarget, ref PointCloud mypointCloudSource, ref PointCloud mypointCloudResult) { string path = AppDomain.CurrentDomain.BaseDirectory + "PointClouds\\UnitTests"; mypointCloudTarget = new PointCloud(path + "\\KinectFace_1_15000.obj"); mypointCloudSource = PointCloud.CloneAll(mypointCloudTarget); PointCloud.ScaleByFactor(mypointCloudSource, 0.9f); Matrix3 R = new Matrix3(); R = R.RotationXYZDegrees(60, 60, 60); PointCloud.Rotate(mypointCloudSource, R); PointCloud.Translate(mypointCloudSource, 0.3f, 0.5f, -0.4f); PCA pca = new PCA(); mypointCloudResult = pca.AlignPointClouds_SVD(mypointCloudSource, mypointCloudTarget); mypointCloudSource = mypointCloudResult; mypointCloudResult = IterativeClosestPointTransform.Instance.PerformICP(mypointCloudSource, mypointCloudTarget); return(IterativeClosestPointTransform.Instance.MeanDistance); }
/// <summary> /// This is the method that actually does the work. /// </summary> /// <param name="DA">The DA object can be used to retrieve data from input parameters and /// to store data in output parameters.</param> protected override void SolveInstance(IGH_DataAccess DA) { string strdc = null; PointCloud pc = null; if (!DA.GetData(0, ref pc)) { return; } if (!DA.GetData(1, ref strdc)) { return; } List <double> nl = new List <double>(); Dict_Utils.CastDictionary_ToArrayDouble(ref pc); nl.AddRange((double[])pc.UserDictionary[strdc]); DA.SetDataList(0, nl); }
private static PointSet CreateRegularPointsInUnitCube(int n, int splitLimit) { var ps = new List <V3d>(); var step = 1.0 / n; var start = step * 0.5; for (var x = start; x < 1.0; x += step) { for (var y = start; y < 1.0; y += step) { for (var z = start; z < 1.0; z += step) { ps.Add(new V3d(x, y, z)); } } } var config = ImportConfig.Default .WithStorage(PointCloud.CreateInMemoryStore()) .WithKey("test") .WithOctreeSplitLimit(splitLimit) ; return(PointCloud.Chunks(new Chunk(ps, null), config)); }
/// <summary> /// Constructs a new tree with an element for each pointcloud point. /// </summary> /// <param name="cloud">A pointcloud.</param> /// <returns>A new tree, or null on error.</returns> public static RTree CreatePointCloudTree(PointCloud cloud) { RTree rc = new RTree(); IntPtr pRtree = rc.NonConstPointer(); IntPtr pConstCloud = cloud.ConstPointer(); if (!UnsafeNativeMethods.ON_RTree_CreatePointCloudTree(pRtree, pConstCloud)) { rc.Dispose(); return null; } uint size = UnsafeNativeMethods.ON_RTree_SizeOf(pRtree); rc.m_memory_pressure = size; GC.AddMemoryPressure(rc.m_memory_pressure); return rc; }
public void cancelLearning() { this.curLearning = null; this.curLearningName = null; this.props = null; this.curLearningProp = null; }
public bool saveObject() { if (this.curLearning == null) { return false; } else { // Send updated identifier to through thrift if (client.update(this.curLearning.Identifier, this.curLearningName)) { this.unknownPointClouds.Remove(this.curLearning.Identifier); this.curLearning.Identifier = this.curLearningName; this.knownPointClouds[this.curLearningName] = this.curLearning; RecogObject obj = new RecogObject(this.curLearningName); obj.addProperties(props); this.addObject(obj); this.curLearning = null; this.curLearningName = null; return true; } else { return false; } } }
/// <summary> /// Add a point cloud into the list of point clouds /// </summary> /// <param name="pc">Input point cloud</param> public override void add(PointCloud pc) { this.pointClouds.Add(pc); }
/// <summary> /// Draws a point cloud. /// </summary> /// <param name="cloud">Point cloud to draw, if the cloud has a color array, it will be used, otherwise the points will be black.</param> /// <param name="size">Size of points.</param> public void DrawPointCloud(PointCloud cloud, int size) { DrawPointCloud(cloud, size, System.Drawing.Color.Black); }
private void CreateNewTargetSurface() { targetPoly = new RBFPolynomials.Paraboloid(null); switch (TargetBasis) { case BasisType.Cubic: targetBasis = new RBFBasis.PolyHarmonic3(null); break; case BasisType.Gaussian: targetBasis = new RBFBasis.Gaussian(null); break; case BasisType.Line: targetBasis = new RBFBasis.CustomBasis(null, 0, 0, 1, 0); break; case BasisType.Parabolic: targetBasis = new RBFBasis.ThinPlateSpline2(null); break; case BasisType.CubicParabolic: targetBasis = new RBFBasis.CustomBasis(null, 1, 1, -1, 0); break; } List<double[]> pnts = RandomizePoints(GridSize); target = new SurfaceRBF(null, "target", pnts, targetBasis, targetPoly, 0.0); Max[0] = Max[1] = Max[2] = -1e9; //start max low Min[0] = Min[1] = Min[2] = +1e9; //start min high pnts.ForEach((double[] v) => { for (int i = 0; i < v.Length; i++) //get fit points' bounding box { Max[i] = Math.Max(v[i], Max[i]); Min[i] = Math.Min(v[i], Min[i]); } }); List<KeyValuePair<double[], double>> pts = target.GetMeshPointsCvt(60, 60, Max, Min, null); CreateMesh(pts, 60, ref m_targetMesh); TargetMesh.RegenMode = devDept.Eyeshot.Standard.Entity.regenType.RegenAndCompile; TargetMesh.EntityData = "targetSurface"; AddEntity(TargetMesh, false); PointCloud fits = new PointCloud(doubleToPoint3d(pnts), 5.0f, Color.Red); fits.EntityData = "fitpoints"; AddEntity(fits, true); GC.Collect(); }
/// <summary> /// Stitch the point clouds using the "bounding box" algorithm /// </summary> public override void stitch() { //this algorithm requires four clouds, so we first check that there are four clouds available if (pointClouds.Count == 4) { //instantiate some initial variables double depth = 0; double width = 0; double rotationAngle = 0; double[] translationValue = new double[3]; double[] rotationCentre = new double[3]; //instantiate previous coord variables double[] prevMin = new double[3]; double[] prevMax = new double[3]; double prevWidth = 0; //iterate over every cloud int i = 0; foreach (PointCloud cloud in pointClouds) { //calculate the width of the cloud width = cloud.getxMax() - cloud.getxMin(); //perform the rotation depending on which point cloud we are looking at switch (i) { case 0: //this is nice, we don't need to do anything! rotationAngle = 0; //dont translate translationValue = new double[3] { 0, 0, 0 }; break; case 1: //set the rotation to a fixed value rotationAngle = 90; //calculate the centre of rotation rotationCentre = new double[3] { cloud.getxMin(), cloud.getyMin(), cloud.getzMin() }; //dont translate translationValue = new double[3] { 0, 0, width }; break; case 2: //set the rotation to a fixed value rotationAngle = 180; //calculate the centre of rotation (maxx',miny,maxz'+(maxx-minx)) rotationCentre = new double[3] { cloud.getxMin(), cloud.getyMin(), cloud.getzMin() }; /* * Translate by * x: -width * z: width' */ translationValue = new double[3] { width,0,prevWidth}; break; case 3: //set the rotation to a fixed value rotationAngle = 270; rotationCentre = new double[3] { cloud.getxMin(), cloud.getyMin(), cloud.getzMin() }; /* * Translate by * x: -(depth + width') * z: width */ translationValue = new double[3] { prevWidth,0,0 }; break; default: //this should not occur... throw an exception break; } //add the translated cloud into the grouped cloud (only tx/rt if not the first panel) if (i == 0) { this.pcd = cloud; } else { cloud.rotate(rotationCentre, rotationAngle); cloud.translate(translationValue); this.pcd.addPointCloud(cloud); } //store in a list of point clouds txpointClouds.Add(cloud); //store current values for the next iteration prevMin = new double[3]{cloud.getxMin(), cloud.getyMin(), cloud.getzMin()}; prevMax = new double[3]{cloud.getxMax(), cloud.getyMax(), cloud.getzMax()}; prevWidth = width; //calculate the depth depth = cloud.getzMax() - cloud.getzMin(); //increase iterator i++; } } else { //thow an exception } }
public virtual List<Entity> CreateEntities(bool bFitPoints, double TolAngle, out double[] sPos) { if (!AllFitPointsValid()) { sPos = null; return new List<Entity>(); } List<double> spos = new List<double>(); const int TEST = 8; int FitLength = FitPoints.Length; double[] stest = new double[(FitLength - 1) * TEST]; Vect3[] xtest = new Vect3[(FitLength - 1) * TEST]; Vect2 uv = new Vect2(); Vect3 xyz = new Vect3(); Vect3 dxp = new Vect3(), dxm = new Vect3(); //initial 8 subdivisions per segment int nFit, nTest = 0; for (nFit = 1; nFit < FitLength; nFit++) { for (int i = 0; i < TEST; i++, nTest++) { stest[nTest] = BLAS.interpolate(i, TEST, FitPoints[nFit].S, FitPoints[nFit - 1].S); xtest[nTest] = new Vect3(); xVal(stest[nTest], ref uv, ref xtest[nTest]); } } //test the midpoint of each subsegment to determine required # of points int[] nAdd = new int[stest.Length]; double cosA; double smid; int nTotal = FitLength; for (nTest = 1; nTest < stest.Length; nTest++) { //midpoint position smid = (stest[nTest] + stest[nTest - 1]) / 2.0; xVal(smid, ref uv, ref xyz); //forward and backward tangents dxp = xtest[nTest] - xyz; dxm = xtest[nTest - 1] - xyz; //change in angle between for and aft tans cosA = -(dxp.Dot(dxm)) / (dxp.Magnitude * dxm.Magnitude); Utilities.LimitRange(-1, ref cosA, 1); cosA = Math.Acos(cosA); //determine additional points and sum total nTotal += nAdd[nTest] = (int)(cosA / TolAngle + 1); } m_Length = 0; Vect3 xprev = new Vect3(); Vect3 dx = new Vect3(); List<Point3D> pnts = new List<Point3D>(); List<Vect3> tans = new List<Vect3>(); xVal(stest[0], ref uv, ref xprev); pnts.Add(new Point3D(xprev.ToArray())); spos.Add(stest[0]); for (nTest = 1; nTest < stest.Length; nTest++) { for (int i = 1; i <= nAdd[nTest]; i++) { smid = ((nAdd[nTest] - i) * stest[nTest - 1] + i * stest[nTest]) / nAdd[nTest]; xVec(smid, ref uv, ref xyz, ref dx); spos.Add(smid); pnts.Add(new Point3D(xyz.ToArray())); tans.Add(new Vect3(dx)); m_Length += xyz.Distance(xprev); xprev.Set(xyz); } } if (EXTENDENTITY) { //add for-cast/back-cast points for (int i = 0; i < 2; i++) { for (nTest = 0; nTest < 10; nTest++) { smid = BLAS.interpolant(nTest, 10) * 0.05;//scale down to .1 cast if (i == 0) smid = -smid; else smid += 1.0; xVal(smid, ref uv, ref xyz); if (i == 0) pnts.Insert(0, new Point3D(xyz.ToArray())); else pnts.Add(new Point3D(xyz.ToArray())); } } } LinearPath lp = new LinearPath(pnts); lp.EntityData = this; //lp.LineWeight = 3.0f; //lp.LineWeightMethod = colorMethodType.byEntity; List<Entity> tanpaths = new List<Entity>(); tanpaths.Add(lp); if (bFitPoints) { //LinearPath path; //int npnt = 0; //foreach (Vect3 pnt in tans) //{ // pnt.Magnitude = 2; // xyz = new Vect3(pnts[npnt].ToArray()); // xyz += pnt; // path = new LinearPath(pnts[npnt], new Point3D(xyz.ToArray())); // path.EntityData = this; // tanpaths.Add(path); // npnt++; // //xVal(pnt.UV, ref xyz); // //pnts.Add(new Point3D(xyz.ToArray())); //} pnts = new List<Point3D>(); foreach (IFitPoint pnt in FitPoints) { xVal(pnt.UV, ref xyz); pnts.Add(new Point3D(xyz.ToArray())); } PointCloud pc = new PointCloud(pnts, 8f); pc.EntityData = this; tanpaths.Add(pc); } sPos = spos.ToArray(); return tanpaths; }
void GAWorker_ProgressChanged(object sender, ProgressChangedEventArgs e) { if (GAWorker.CancellationPending == true) Algo.Stop(); m_progBar.Value = e.ProgressPercentage; if (e.UserState == null) return; List<int> bestChromo = (List<int>)e.UserState; if (bestChromo.Count > 0) { List<double[]> gaPnts = new List<double[]>(); double[] result = EvalChromosome(ref bestChromo, ref gaPnts); CustomBasis GeneticBasis = new CustomBasis(16.383 / 2.0 - result[0], 16.383 / 2.0 - result[1], 16.383 / 2.0 - result[2], 16.383 / 2.0 - result[3]); List<double[]> fitpoints = new List<double[]>(gaPnts); //for (int i = 0; i < fitpoints.Count; i++) //fitpoints[i][2] += 15; //offset SurfaceRBF tmpSurf = new SurfaceRBF(null, "best", fitpoints, GeneticBasis, targetPoly, 0.0); double[] max = new double[3]; double[] min = new double[3]; max[0] = max[1] = max[2] = -1e9; //start max low min[0] = min[1] = min[2] = +1e9; //start min high fitpoints.ForEach((double[] v) => { for (int i = 0; i < v.Length; i++) //get fit points' bounding box { max[i] = Math.Max(v[i], Max[i]); min[i] = Math.Min(v[i], Min[i]); } }); double[] pnt1 = new double[3]; double[] pnt2 = new double[3]; List<double[]> errorSurfPnts = new List<double[]>(); double gridCount = 10.0; List<devDept.Eyeshot.Labels.TextOnly> labels = new List<devDept.Eyeshot.Labels.TextOnly>(); for (double i = 0; i < gridCount; i += 1.0) { for (double j = 0; j < gridCount; j += 1.0) { pnt1 = new double[] { (i / (gridCount - 1)) * (Max[0] - Min[0]) + Min[0], (j / (gridCount - 1)) * (Max[1] - Min[1]) + Min[1], 0 }; pnt2 = new double[] { (i / (gridCount - 1)) * (Max[0] - Min[0]) + Min[0], (j / (gridCount - 1)) * (Max[1] - Min[1]) + Min[1], 0 }; target.Value(ref pnt1); found.Value(ref pnt2); errorSurfPnts.Add(new double[] { (i / (gridCount - 1)) * (Max[0] - Min[0]) + Min[0], (j / (gridCount - 1)) * (Max[1] - Min[1]) + Min[1], Math.Pow(pnt2[2] - pnt1[2], 2) }); labels.Add(new devDept.Eyeshot.Labels.TextOnly(new Point3D((i / (gridCount - 1)) * (Max[0] - Min[0]) + Min[0] + GridSize * 20, (j / (gridCount - 1)) * (Max[1] - Min[1]) + Min[1], Math.Pow(pnt1[2] - pnt2[2], 2)), Math.Pow(((pnt1[2] - pnt2[2]) / pnt1[2]), 1).ToString("#0.00"), new Font(FontFamily.GenericSansSerif, 12.0f), Color.White, ContentAlignment.BottomCenter)); } } SurfaceRBF tmpSurf2 = new SurfaceRBF(null, "error", errorSurfPnts, targetBasis, targetPoly, 0.0); List<KeyValuePair<double[], double>> errorpts = tmpSurf2.GetMeshPointsCvt(50, 50, max, min, null); MulticolorOnVerticesMesh errorMesh = new MulticolorOnVerticesMesh(0); CreateMesh(errorpts, 50, ref errorMesh); errorMesh.RegenMode = devDept.Eyeshot.Standard.Entity.regenType.RegenAndCompile; errorMesh.EntityData = "errorSurface"; errorMesh.Translate(GridSize * 20, 0, 0); AddEntity(errorMesh, false); List<KeyValuePair<double[], double>> pts = tmpSurf.GetMeshPointsCvt(60, 60, max, min, null); MulticolorOnVerticesMesh bestMesh = new MulticolorOnVerticesMesh(0); CreateMesh(pts, 60, ref bestMesh); bestMesh.RegenMode = devDept.Eyeshot.Standard.Entity.regenType.RegenAndCompile; bestMesh.EntityData = "bestSurface"; bestMesh.Translate(-2 * GridSize * 10, 0, 0); devDept.Eyeshot.Labels.TextOnly bestBasis = new devDept.Eyeshot.Labels.TextOnly(new Point3D(((gridCount / 2.0) / (gridCount - 1)) * (Max[0] - Min[0]) + Min[0] - (2 * GridSize * 10), ((gridCount / 2.0) / (gridCount - 1)) * (Max[1] - Min[1]) + Min[1], 20), GeneticBasis.ToString(), new Font(FontFamily.GenericSansSerif, 12.0f), Color.White, ContentAlignment.BottomCenter); viewportProfessional1.Labels.Clear(); labels.ForEach((label) => { viewportProfessional1.Labels.Add(label); }); viewportProfessional1.Labels.Add(bestBasis); AddEntity(bestMesh, false); //for (int i = 0; i < fitpoints.Count; i++) //fitpoints[i][2] -= 15; //offset PointCloud fits = new PointCloud(doubleToPoint3d(fitpoints), 7.5f, Color.Blue); fits.EntityData = "bestpoints"; AddEntity(fits, true); pts.Clear(); bestChromo.Clear(); //GC.Collect(); } }
public double PushOntoCloud(PointCloud other, int iterations, int matchLength, double threshold) { // we are going to update our transform to place us on the other cloud with the ICP double error = 0; #region Correspondence // make the list of matches // NOTE this cannot be a SortedList because that will complain if you give multiple pairs with the same dist List<PointMatch> matches = new List<PointMatch>(); // go over our list of features foreach (CloudPoint p in this.FeatureTree) { // find nearest in their list of features after our transform var pT = p.ApplyTransform(R, T); CloudPoint o = other.FeatureTree.FindNearestNeighbor(pT.ColorLocation()); PointMatch match = new PointMatch(pT, o); matches.Add(match); } // select the top ni matches based on how close they are var topMatches = matches.OrderBy(x => x.Distance).Take(matchLength); #endregion #region find normals for matchpoints var ourQueryPoints = topMatches.Select(x => x.A.UnApplyTransform(R, T)); this.CalculateNormals(ourQueryPoints); var theirQueryPoints = topMatches.Select(x => x.B); other.CalculateNormals(theirQueryPoints); #endregion // iterative part for (int i = 0; i < iterations; i++) { #region refine ICP estimate Matrix cov = new Matrix(6, 6); Vector b = new Vector(6); var r = Vector.Create(new double[] { R[2, 1], R[0, 2], R[1, 0] }); foreach (PointMatch pm in topMatches) { // moving A onto B var A = pm.A; var B = pm.B; Vector ni = B.normal; Vector ci = Vector.CrossProduct(A.location, ni); Vector CN = Vector.Create(ci.Concat(ni).ToArray()); cov = cov + (CN.ToColumnMatrix() * CN.ToRowMatrix()); var diffDot = (A.location - B.location) * ni; // this is a dot product b = b - (diffDot * Vector.Ones(6)).ArrayMultiply(CN); // also accumulate error for this RT since we're here already error = error + Math.Pow((diffDot + (T * ni) + (r * ci)), 2); } // done accumulating cov and B // we're done here if our thing put us close enough if (error < threshold) break; // solve cov * inc_transform = b // compute decomp var chol = cov.CholeskyDecomposition; // solve LL' * inc_transform = b var L = chol.TriangularFactor; Vector inc_transform = LLTSolve(L, b); R = Matrix.Create(new double[,]{{1, -inc_transform[2], inc_transform[1]}, {inc_transform[2], 1, -inc_transform[0]}, {-inc_transform[1], inc_transform[0], 1}}); // last three components are translation T = Vector.Create(inc_transform.Skip(3).ToArray()); #endregion } // apply transform to whole cloud ApplyTransform(); return error; }
protected override void FindBoundary() { bool output = false; //float acceptanceRatio = 0.9f; //float maxTimeDistance = 0.5f; // ~~~~~~~~~~~ Variable Initializations ~~~~~~~~~~~~~ \\ // Find out: Where do we want the boundary to be? // "One day": Take Okubo etc as predictor. int preferredBoundaryTime = SliceTimeMain + (24 * RedSea.Singleton.NumSubsteps) / _everyNthTimestep; float maxTimeDistance = 1.0f; float maxRadius = 12; float minRadius = 1; float radiusGrowth = StepSize * 3; float stepSizeStreamlines = StepSize; PointSet<Point> boundaryOW = OkuboBoundary(preferredBoundaryTime); // At which point did we find the Boundary? int[] boundaryIndices, boundaryIndicesLast; // At which point did we find the Boundary last time? Initalize 0. boundaryIndicesLast = new int[LineX]; for (int i = 0; i < boundaryIndicesLast.Length; i++) boundaryIndicesLast[i] = int.MaxValue; // Keep the chosen lines in here. LineSet chosenPathlines = new LineSet(new Line[LineX]); // These are lines that do not fullfill the criteria, but are the best ones we got so far. Line[] bestPathlines = new Line[LineX]; float[] bestTimeDistance = new float[LineX]; for (int i = 0; i < bestTimeDistance.Length; i++) bestTimeDistance[i] = float.MaxValue; // ~~~~~~~~~~~~ Inner Circle ~~~~~~~~~~~~~~~~~~~~~~~~ \\ //for (float offsetInnerCircle = 7; offsetInnerCircle < 10; offsetInnerCircle += 0.1f) float offsetInnerCircle = AlphaStable; { chosenPathlines = new LineSet(new Line[LineX]); Console.WriteLine("Current offset: {0}", offsetInnerCircle); // float offsetInnerCircle = AlphaStable; // Save where to transit steady -> unsteady integration. float[] offsetSeeds = new float[LineX]; for (int i = 0; i < offsetSeeds.Length; i++) offsetSeeds[i] = offsetInnerCircle; // Create small circle around selection. Point[] circle = new Point[LineX]; // Seeds for pathlines. PointSet<Point> seeds = boundaryOW; //new PointSet<Point>(circle); // ~~~~~~~~~~~~ Integrate Pathlines and Adapt ~~~~~~~~~~~~~~~~~~~~~~~~ \\ // Setup integrator. Integrator pathlineIntegrator = Integrator.CreateIntegrator(null, IntegrationType, _cores[_selectedCore], _repulsion); pathlineIntegrator.StepSize = StepSize; // Count out the runs for debugging. int run = 0; //while (seeds.Length > 0) //{ // if (output) Console.WriteLine("Starting run {0}, {1} seeds left.", run++, seeds.Length); // ~~~~~~~~~~~~ Integrate Pathlines ~~~~~~~~~~~~~~~~~~~~~~~~ \\ #region IntegratePathlines // Do we need to load a field first? if (_velocity.TimeOrigin > preferredBoundaryTime - 1 || _velocity.TimeOrigin + _velocity.Size.T < preferredBoundaryTime + 1) LoadField(Math.Max(preferredBoundaryTime - STEPS_IN_MEMORY / 2, 0), MemberMain, STEPS_IN_MEMORY); int startStep = (int)_velocity.TimeOrigin; // Integrate first few steps. pathlineIntegrator.Field = _velocity; pathlineIntegrator.Direction = Sign.POSITIVE; LineSet[] pathlines = pathlineIntegrator.Integrate(seeds, true); // Append integrated lines of next loaded vectorfield time slices. float timeLength = RedSea.Singleton.NumSubstepsTotal / _everyNthTimestep; //preferredBoundaryTime * 2; while (_currentEndStep + 1 < timeLength) { // Don't load more steps than we need to! int numSteps = (int)Math.Min(timeLength - _currentEndStep, STEPS_IN_MEMORY); pathlineIntegrator.Field = null; LoadField(_currentEndStep, MemberMain, numSteps); // Integrate further. pathlineIntegrator.Field = _velocity; pathlineIntegrator.IntegrateFurther(pathlines[0]); } // Now, integrate backwards. pathlineIntegrator.Direction = Sign.NEGATIVE; while (startStep > 0) { // Don't load more steps than we need to! int numSteps = (int)Math.Min(startStep + 1, STEPS_IN_MEMORY); pathlineIntegrator.Field = null; LoadField(startStep - numSteps + 1, MemberMain, numSteps); startStep = (int)_velocity.TimeOrigin; // Integrate further. pathlineIntegrator.Field = _velocity; pathlineIntegrator.IntegrateFurther(pathlines[1]); } pathlines[1].Reverse(); pathlines[1].Append(pathlines[0]); chosenPathlines = pathlines[1]; #endregion IntegratePathlines // // ~~~~~~~~~~~~ Get Boundary ~~~~~~~~~~~~~~~~~~~~~~~~ \\ // #region GetBoundary // // The two needes functions. // Line[] distances = FieldAnalysis.GetGraph(_cores[_selectedCore], _selection, pathlines[0], StepSize, _everyNthTimestep, true); // Line[] angles = FieldAnalysis.GetGraph(_cores[_selectedCore], _selection, pathlines[0], StepSize, _everyNthTimestep, false); // // Find the boundary based on angle and distance. // FieldAnalysis.FindBoundaryFromDistanceAngleDonut(distances, angles, out boundaryIndices); // #endregion GetBoundary // // ~~~~~~~~~~~~ Chose or Offset Pathlines ~~~~~~~~~~~~ \\ // int numNewSeeds = 0; // int numPathlines = 0; // float avgTimeDistance = 0; // // Recompute start points. // for (int idx = 0; idx < LineX; ++idx) // { // // We already have an optimal line here. Continue. // if (chosenPathlines[idx] != null) // continue; // // Should we save this line? // Vector3 pos; // // Save this point // if (boundaryIndices[numPathlines] >= 0) // { // pos = pathlines[numPathlines][boundaryIndices[numPathlines]]; // _allBoundaryPoints.Add(new Point(pos) { Color = new Vector3(0.1f, pos.Z * _everyNthTimestep / RedSea.Singleton.NumSubstepsTotal, 0.1f) }); // } // // Finally found it? // // TODOD: DEBUG!!!!!!!!!!!!!!!!111!!!!!!!!!!!!!!!!!!elf!!!!!!!!!!!!!!!! // float timeDistance = Math.Abs((boundaryIndices[numPathlines] * StepSize) - preferredBoundaryTime); // avgTimeDistance += timeDistance; // if (timeDistance < maxTimeDistance || run >= 100) // We reached the spot! Take this line! // { // chosenPathlines[idx] = pathlines[numPathlines]; // if (output) // Console.WriteLine("Line {0} was chosen because it is perfect!", idx); // } // else // { // // Add new seed to seed list. // float scale = boundaryIndices[numPathlines] / preferredBoundaryTime; // float newOffset = offsetSeeds[numPathlines] + ((scale > 1) ? radiusGrowth : -radiusGrowth); // newOffset = Math.Max(minRadius, newOffset); // newOffset = Math.Min(maxRadius, newOffset); // // We are stuck. Take best value we reached so far and go on. // if (newOffset == offsetSeeds[numPathlines] && bestPathlines[idx] != null) // { // chosenPathlines[idx] = bestPathlines[idx]; // continue; // } // if (timeDistance < bestTimeDistance[idx]) // { // bestPathlines[idx] = pathlines[numPathlines]; // bestTimeDistance[idx] = timeDistance; // } // offsetSeeds[numPathlines] = newOffset; // // Recompute position on circle. // float x = (float)(Math.Sin(angleDiff * idx + Math.PI / 2)); // float y = (float)(Math.Cos(angleDiff * idx + Math.PI / 2)); // // Take the selection as center. // seeds.Points[numNewSeeds] = new Point() { Position = new Vector3(_selection.X + x * offsetSeeds[numNewSeeds], _selection.Y + y * offsetSeeds[numNewSeeds], SliceTimeMain) }; // // Count up number of new seeds. // numNewSeeds++; // } // // We do not count up this value if there is a chosen pathline at this index already. // numPathlines++; // } // // We maybe need less seeds now? // if (numNewSeeds < seeds.Length) // Array.Resize(ref seeds.Points, numNewSeeds); // Console.WriteLine("Average time distance: {0}", avgTimeDistance / numPathlines); // } } // ~~~~~~~~~~~~ Get Boundary for Rendering~~~~~~~~~~~~~~~~~~~~~~~~ \\ // The two needes functions. _coreDistanceGraph = FieldAnalysis.GetGraph(_cores[_selectedCore], _selection, chosenPathlines, StepSize, _everyNthTimestep, true); _coreAngleGraph = FieldAnalysis.GetGraph(_cores[_selectedCore], _selection, chosenPathlines, StepSize, _everyNthTimestep, false); // Find the boundary based on angle and distance. _boundaryBallFunction = new LineBall(_linePlane, new LineSet(new Line[] { FieldAnalysis.FindBoundaryFromDistanceAngleDonut(_coreDistanceGraph, _coreAngleGraph, out boundaryIndices) })); // Find the boundary in space-time. int time = SliceTimeMain; _boundariesSpacetime[time] = new Line() { Positions = new Vector3[LineX + 1] }; for (int l = 0; l < LineX; ++l) { Vector3 pos = chosenPathlines[l][boundaryIndices[l]]; _allBoundaryPoints.Add(new Point(pos) { Color = Vector3.UnitY * pos.Z / RedSea.Singleton.NumSubstepsTotal * _everyNthTimestep }); _allBoundaryPoints.Add(boundaryOW.Points[l]); _boundariesSpacetime[time][l] = pos; } _boundariesSpacetime[time][LineX] = _boundariesSpacetime[time][0]; _boundaryBallSpacetime = new LineBall(_linePlane, _boundariesSpacetime, LineBall.RenderEffect.HEIGHT, Colormap); // Pathlines for rendering. _pathlinesTime = chosenPathlines; _pathlines = new LineBall(_linePlane, chosenPathlines, LineBall.RenderEffect.HEIGHT, ColorMapping.GetComplementary(Colormap), Flat); Console.WriteLine("Khalas. Boundary indices:"); float sumTime = 0; for (int i = 0; i < chosenPathlines.Length; i++) { float atTime = chosenPathlines[i][boundaryIndices[i]].Z; sumTime += atTime; Console.WriteLine("\tTime at {0}: {1}", i, atTime); } Console.WriteLine("Average time: {0}", sumTime / chosenPathlines.Length); _boundaryCloud = new PointCloud(_linePlane, new PointSet<Point>(_allBoundaryPoints.ToArray())); LineSet set = new LineSet(_coreAngleGraph); GeometryWriter.WriteHeightCSV(RedSea.Singleton.DonutFileName + "Angle.csv", set); GeometryWriter.WriteToFile(RedSea.Singleton.DonutFileName + ".angle", set); set = new LineSet(_coreDistanceGraph); GeometryWriter.WriteHeightCSV(RedSea.Singleton.DonutFileName + "Distance.csv", set); GeometryWriter.WriteToFile(RedSea.Singleton.DonutFileName + ".distance", set); }
internal static GeometryBase CreateGeometryHelper(IntPtr pGeometry, object parent, int subobject_index) { if (IntPtr.Zero == pGeometry) return null; int type = UnsafeNativeMethods.ON_Geometry_GetGeometryType(pGeometry); if (type < 0) return null; GeometryBase rc = null; switch (type) { case idxON_Curve: //1 rc = new Curve(pGeometry, parent, subobject_index); break; case idxON_NurbsCurve: //2 rc = new NurbsCurve(pGeometry, parent, subobject_index); break; case idxON_PolyCurve: // 3 rc = new PolyCurve(pGeometry, parent, subobject_index); break; case idxON_PolylineCurve: //4 rc = new PolylineCurve(pGeometry, parent, subobject_index); break; case idxON_ArcCurve: //5 rc = new ArcCurve(pGeometry, parent, subobject_index); break; case idxON_LineCurve: //6 rc = new LineCurve(pGeometry, parent, subobject_index); break; case idxON_Mesh: //7 rc = new Mesh(pGeometry, parent); break; case idxON_Point: //8 rc = new Point(pGeometry, parent); break; case idxON_TextDot: //9 rc = new TextDot(pGeometry, parent); break; case idxON_Surface: //10 rc = new Surface(pGeometry, parent); break; case idxON_Brep: //11 rc = new Brep(pGeometry, parent); break; case idxON_NurbsSurface: //12 rc = new NurbsSurface(pGeometry, parent); break; case idxON_RevSurface: //13 rc = new RevSurface(pGeometry, parent); break; case idxON_PlaneSurface: //14 rc = new PlaneSurface(pGeometry, parent); break; case idxON_ClippingPlaneSurface: //15 rc = new ClippingPlaneSurface(pGeometry, parent); break; case idxON_Annotation2: // 16 rc = new AnnotationBase(pGeometry, parent); break; case idxON_Hatch: // 17 rc = new Hatch(pGeometry, parent); break; case idxON_TextEntity2: //18 rc = new TextEntity(pGeometry, parent); break; case idxON_SumSurface: //19 rc = new SumSurface(pGeometry, parent); break; case idxON_BrepFace: //20 { int faceindex = -1; IntPtr pBrep = UnsafeNativeMethods.ON_BrepSubItem_Brep(pGeometry, ref faceindex); if (pBrep != IntPtr.Zero && faceindex >= 0) { Brep b = new Brep(pBrep, parent); rc = b.Faces[faceindex]; } } break; case idxON_BrepEdge: // 21 { int edgeindex = -1; IntPtr pBrep = UnsafeNativeMethods.ON_BrepSubItem_Brep(pGeometry, ref edgeindex); if (pBrep != IntPtr.Zero && edgeindex >= 0) { Brep b = new Brep(pBrep, parent); rc = b.Edges[edgeindex]; } } break; case idxON_InstanceDefinition: // 22 rc = new InstanceDefinitionGeometry(pGeometry, parent); break; case idxON_InstanceReference: // 23 rc = new InstanceReferenceGeometry(pGeometry, parent); break; #if USING_V5_SDK case idxON_Extrusion: //24 rc = new Extrusion(pGeometry, parent); break; #endif case idxON_LinearDimension2: //25 rc = new LinearDimension(pGeometry, parent); break; case idxON_PointCloud: // 26 rc = new PointCloud(pGeometry, parent); break; case idxON_DetailView: // 27 rc = new DetailView(pGeometry, parent); break; case idxON_AngularDimension2: // 28 rc = new AngularDimension(pGeometry, parent); break; case idxON_RadialDimension2: // 29 rc = new RadialDimension(pGeometry, parent); break; case idxON_Leader: // 30 rc = new Leader(pGeometry, parent); break; case idxON_OrdinateDimension2: // 31 rc = new OrdinateDimension(pGeometry, parent); break; case idxON_Light: //32 rc = new Light(pGeometry, parent); break; case idxON_PointGrid: //33 rc = new Point3dGrid(pGeometry, parent); break; case idxON_MorphControl: //34 rc = new MorphControl(pGeometry, parent); break; case idxON_BrepLoop: //35 { int loopindex = -1; IntPtr pBrep = UnsafeNativeMethods.ON_BrepSubItem_Brep(pGeometry, ref loopindex); if (pBrep != IntPtr.Zero && loopindex >= 0) { Brep b = new Brep(pBrep, parent); rc = b.Loops[loopindex]; } } break; case idxON_BrepTrim: // 36 { int trimindex = -1; IntPtr pBrep = UnsafeNativeMethods.ON_BrepSubItem_Brep(pGeometry, ref trimindex); if (pBrep != IntPtr.Zero && trimindex >= 0) { Brep b = new Brep(pBrep, parent); rc = b.Trims[trimindex]; } } break; default: rc = new UnknownGeometry(pGeometry, parent, subobject_index); break; } return rc; }
public abstract void EstimateRigidTransformation(PointCloud <PointSource> cloudSrc, PointCloud <PointTarget> cloudTgt);
/// <summary> /// Draws a point cloud. /// </summary> /// <param name="cloud">Point cloud to draw.</param> /// <param name="size">Size of points.</param> /// <param name="color">Color of points in the cloud, if the cloud has a color array this setting is ignored.</param> public void DrawPointCloud(PointCloud cloud, int size, System.Drawing.Color color) { IntPtr pCloud = cloud.ConstPointer(); UnsafeNativeMethods.CRhinoDisplayPipeline_DrawPointCloud(m_ptr, pCloud, size, color.ToArgb()); }
public ObjectPrimitive(RhinoObject o, PointCloud pc, Part p) : base(pc, p) { rhinoObject = o; }
public abstract void SetInputCloud(PointCloud <PointT> cloud);
public PointCloud learnObject() { if (this.unknownPointClouds.Count == 0) { return null; } else { this.curLearning = this.unknownPointClouds.FirstOrDefault().Value; this.props = new List<string>(); return this.curLearning; } }
public ObjectPrimitive(RhinoObject o, PointCloud pc) : base(pc) { rhinoObject = o; }
public void add_Sources(IEnumerable<Rhino.Geometry.Point3d> pts) { this.Enabled = true; Srcs = new PointCloud(pts); }
void AddPointCloudPreviews(PointCloud previewCloud) { int verticesCount = previewCloud.Count; if (verticesCount > VertexThreshold) { primitives = new Primitive[(verticesCount / VertexThreshold) + ((verticesCount % VertexThreshold) > 0 ? 1 : 0)]; for (int c = 0; c < verticesCount / VertexThreshold; ++c) { var part = new Primitive.Part(c * VertexThreshold, (c + 1) * VertexThreshold); primitives[c] = new ObjectPrimitive(rhinoObject, previewCloud, part); } if ((verticesCount % VertexThreshold) > 0) { var part = new Primitive.Part((primitives.Length - 1) * VertexThreshold, verticesCount); primitives[primitives.Length - 1] = new ObjectPrimitive(rhinoObject, previewCloud, part); } } else { primitives = new Primitive[] { new ObjectPrimitive(rhinoObject, previewCloud) } }; } void AddMeshPreviews(Mesh previewMesh) { int verticesCount = previewMesh.Vertices.Count; if (verticesCount > VertexThreshold || previewMesh.Faces.Count > VertexThreshold) { // If it's insane big show as point clouds if (previewMesh.Faces.Count > (VertexThreshold - 1) * 16) { primitives = new Primitive[(verticesCount / VertexThreshold) + ((verticesCount % VertexThreshold) > 0 ? 1 : 0)]; for (int c = 0; c < verticesCount / VertexThreshold; ++c) { var part = new Primitive.Part(c * VertexThreshold, (c + 1) * VertexThreshold); primitives[c] = new ObjectPrimitive(rhinoObject, previewMesh, part); } if ((verticesCount % VertexThreshold) > 0) { var part = new Primitive.Part((primitives.Length - 1) * VertexThreshold, verticesCount); primitives[primitives.Length - 1] = new ObjectPrimitive(rhinoObject, previewMesh, part); } // Mesh.Reduce is slow in this case //previewMesh = previewMesh.DuplicateMesh(); //previewMesh.Reduce((BigMeshThreshold - 1) * 16, true, 5, true); } // Split the mesh into partitions else if (previewMesh.CreatePartitions(VertexThreshold, int.MaxValue)) { int partitionCount = previewMesh.PartitionCount; primitives = new Primitive[partitionCount]; for (int p = 0; p < partitionCount; ++p) { primitives[p] = new ObjectPrimitive(rhinoObject, previewMesh, previewMesh.GetPartition(p)); } } } else { primitives = new Primitive[] { new ObjectPrimitive(rhinoObject, previewMesh) } }; }
///<exclude/> public bool Equals(PointCloud other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return other._Tm.Equals(_Tm) && other._Points.SequenceEqual(_Points); }
protected void CheckResult_Vectors() { Assert.IsTrue(1e-3f > PointCloud.MeanDistance(pointCloudTarget, pointCloudResult)); }
public void add_Receivers(IEnumerable<Rhino.Geometry.Point3d> pts) { this.Enabled = true; Recs = new PointCloud(pts); }