Esempio n. 1
0
        /// <summary>
        /// Compute inset from input polygon. If requested, will check for
        /// topological changes and try smaller insets, and if that fails,
        /// will just return input polygon.
        /// </summary>
        protected virtual List <GeneralPolygon2d> ComputeInitialInsetPolygon(
            bool bForcePreserveTopology)
        {
            double fInset = ToolWidth * InsetFromInputPolygonX;
            List <GeneralPolygon2d> insetPolys =
                ClipperUtil.MiterOffset(Polygon, -fInset);

            if (bForcePreserveTopology == false)
            {
                return(insetPolys);
            }

            if (check_large_topology_change(Polygon, insetPolys, fInset))
            {
                fInset    /= 2;
                insetPolys = ClipperUtil.MiterOffset(Polygon, -fInset);
                if (check_large_topology_change(Polygon, insetPolys, fInset))
                {
                    insetPolys = new List <GeneralPolygon2d>()
                    {
                        Polygon
                    }
                }
                ;
            }

            return(insetPolys);
        }
Esempio n. 2
0
        /*
         *  functions for subclasses to override to customize behavior
         */

        protected virtual GeneralPolygon2d[] process_input_polys_before_sort(GeneralPolygon2d[] polys)
        {
            if (Offsets.Count == 0)
            {
                return(polys);
            }
            List <GeneralPolygon2d> newPolys = new List <GeneralPolygon2d>();
            bool modified = false;

            foreach (var poly in polys)
            {
                double offset;
                if (Offsets.TryGetValue(poly, out offset) && Math.Abs(offset) > MathUtil.ZeroTolerancef)
                {
                    List <GeneralPolygon2d> offsetPolys = ClipperUtil.MiterOffset(poly, offset);
                    foreach (var newpoly in offsetPolys)
                    {
                        transfer_tags(poly, newpoly);
                        newPolys.Add(newpoly);
                    }
                    modified = true;
                }
                else
                {
                    newPolys.Add(poly);
                }
            }
            if (modified == false)
            {
                return(polys);
            }
            return(newPolys.ToArray());
        }
Esempio n. 3
0
        /// <summary>
        /// Shrink holes inside polys such that if we do offset/2, the hole and
        /// outer offsets will (probably) not collide. Two options:
        ///   1) contract and then dilate each hole. This doesn't handle long skinny holes?
        ///   2) shrink outer by offset and then intersect with holes
        /// Currently using (2). This is better, right?
        /// </summary>
        protected void FilterHoles(List <GeneralPolygon2d> polys, double offset)
        {
            foreach (var poly in polys)
            {
                if (poly.Holes.Count == 0)
                {
                    continue;
                }

                List <GeneralPolygon2d> outer_inset = ClipperUtil.MiterOffset(
                    new GeneralPolygon2d(poly.Outer), -offset);

                List <GeneralPolygon2d> hole_polys = new List <GeneralPolygon2d>();
                foreach (var hole in poly.Holes)
                {
                    hole.Reverse();
                    hole_polys.Add(new GeneralPolygon2d(hole));
                }

                //List<GeneralPolygon2d> contracted = ClipperUtil.MiterOffset(hole_polys, -offset, 0.01);
                //List<GeneralPolygon2d> dilated = ClipperUtil.MiterOffset(hole_polys, offset, 0.01);

                List <GeneralPolygon2d> dilated = ClipperUtil.Intersection(hole_polys, outer_inset, 0.01);

                poly.ClearHoles();

                List <Polygon2d> new_holes = new List <Polygon2d>();
                foreach (var dpoly in dilated)
                {
                    dpoly.Outer.Reverse();
                    poly.AddHole(dpoly.Outer, false, false);
                }
            }
        }
Esempio n. 4
0
        protected virtual GeneralPolygon2d[] process_input_polys_after_sort(GeneralPolygon2d[] solids)
        {
            // construct thickened solids
            Thickened = new Dictionary <GeneralPolygon2d, List <GeneralPolygon2d> >();
            for (int k = 0; k < solids.Length; ++k)
            {
                double clearance;
                if (Clearances.TryGetValue(solids[k], out clearance) && clearance > 0)
                {
                    Thickened.Add(solids[k], ClipperUtil.MiterOffset(solids[k], clearance));
                }
            }

            return(solids);
        }
Esempio n. 5
0
        private LayerCache build_cache(PrintLayerData layerData)
        {
            LayerCache cache = new LayerCache();

            cache.SupportAreas      = ClipperUtil.MiterOffset(layerData.SupportAreas, layerData.Settings.Machine.NozzleDiamMM);
            cache.SupportAreaBounds = new AxisAlignedBox2d[cache.SupportAreas.Count];
            cache.AllSupportBounds  = AxisAlignedBox2d.Empty;
            for (int i = 0; i < cache.SupportAreas.Count; ++i)
            {
                cache.SupportAreaBounds[i] = cache.SupportAreas[i].Bounds;
                cache.AllSupportBounds.Contain(cache.SupportAreaBounds[i]);
            }

            return(cache);
        }
Esempio n. 6
0
        protected virtual List <GeneralPolygon2d> remove_cavity(List <GeneralPolygon2d> solids, GeneralPolygon2d cavity)
        {
            double offset = 0;

            if (Cavity_Clearances.ContainsKey(cavity))
            {
                offset = Cavity_Clearances[cavity];
            }
            if (Cavity_Offsets.ContainsKey(cavity))
            {
                offset += Cavity_Offsets[cavity];
            }
            if (Math.Abs(offset) > 0.0001)
            {
                var offset_cavities = ClipperUtil.MiterOffset(cavity, offset, MIN_AREA);
                return(ClipperUtil.Difference(solids, offset_cavities, MIN_AREA));
            }
            else
            {
                return(ClipperUtil.Difference(solids, cavity, MIN_AREA));
            }
        }
Esempio n. 7
0
        virtual public void PreRender()
        {
            if (in_shutdown())
            {
                return;
            }

            if (parameters_dirty)
            {
                // offset
                List <GeneralPolygon2d> offset = ClipperUtil.RoundOffset(combined_all, offset_distance);
                // aggressively simplify after round offset...
                foreach (var poly in offset)
                {
                    poly.Simplify(path_width);
                }

                // subtract initial and add tiny gap so these don't get merged by slicer
                if (SubtractSolids)
                {
                    offset = ClipperUtil.Difference(offset, combined_solid);
                    offset = ClipperUtil.MiterOffset(offset, -path_width * 0.1);
                }

                offset = CurveUtils2.FilterDegenerate(offset, 0.001);
                foreach (var poly in offset)
                {
                    poly.Simplify(path_width * 0.02);
                }

                DMesh3     mesh   = new DMesh3();
                MeshEditor editor = new MeshEditor(mesh);
                foreach (var poly in offset)
                {
                    TriangulatedPolygonGenerator polygen = new TriangulatedPolygonGenerator()
                    {
                        Polygon = poly
                    };
                    editor.AppendMesh(polygen.Generate().MakeDMesh());
                }
                MeshTransforms.ConvertZUpToYUp(mesh);

                if (mesh.TriangleCount > 0)
                {
                    MeshExtrudeMesh extrude = new MeshExtrudeMesh(mesh);
                    extrude.ExtrudedPositionF = (v, n, vid) => {
                        return(v + Layers * layer_height * Vector3d.AxisY);
                    };
                    extrude.Extrude();
                    MeshTransforms.Translate(mesh, -mesh.CachedBounds.Min.y * Vector3d.AxisY);
                }

                PreviewSO.ReplaceMesh(mesh, true);

                //Vector3d translate = scene_bounds.Point(1, -1, 1);
                //translate.x += spiral.Bounds.Width + PathWidth;
                //Frame3f sceneF = Frame3f.Identity.Translated((Vector3f)translate);
                //PreviewSO.SetLocalFrame(sceneF, CoordSpace.SceneCoords);

                parameters_dirty = false;
            }
        }
Esempio n. 8
0
        protected virtual void fill_bridge_region_decompose(GeneralPolygon2d poly, IFillPathScheduler2d scheduler, PrintLayerData layer_data)
        {
            poly.Simplify(0.1, 0.01, true);
            TriangulatedPolygonGenerator generator = new TriangulatedPolygonGenerator()
            {
                Polygon = poly, Subdivisions = 16
            };
            DMesh3 mesh = generator.Generate().MakeDMesh();
            //Util.WriteDebugMesh(mesh, "/Users/rms/scratch/bridgemesh.obj");


            //List<Polygon2d> polys = decompose_mesh_recursive(mesh);
            List <Polygon2d> polys = decompose_cluster_up(mesh);

            Util.WriteDebugMesh(mesh, "/Users/rms/scratch/bridgemesh_reduce.obj");

            double spacing = Settings.BridgeFillPathSpacingMM();

            foreach (Polygon2d polypart in polys)
            {
                Box2d    box   = polypart.MinimalBoundingBox(0.00001);
                Vector2d axis  = (box.Extent.x > box.Extent.y) ? box.AxisY : box.AxisX;
                double   angle = Math.Atan2(axis.y, axis.x) * MathUtil.Rad2Deg;

                GeneralPolygon2d gp = new GeneralPolygon2d(polypart);

                ShellsFillPolygon shells_fill = new ShellsFillPolygon(gp);
                shells_fill.PathSpacing            = Settings.SolidFillPathSpacingMM();
                shells_fill.ToolWidth              = Settings.Machine.NozzleDiamMM;
                shells_fill.Layers                 = 1;
                shells_fill.InsetFromInputPolygonX = 0.25;
                shells_fill.ShellType              = ShellsFillPolygon.ShellTypes.BridgeShell;
                shells_fill.FilterSelfOverlaps     = false;
                shells_fill.Compute();
                scheduler.AppendCurveSets(shells_fill.GetFillCurves());
                var fillPolys = shells_fill.InnerPolygons;

                double offset = Settings.Machine.NozzleDiamMM * Settings.SolidFillBorderOverlapX;
                fillPolys = ClipperUtil.MiterOffset(fillPolys, offset);

                foreach (var fp in fillPolys)
                {
                    BridgeLinesFillPolygon fill_gen = new BridgeLinesFillPolygon(fp)
                    {
                        InsetFromInputPolygon = false,
                        PathSpacing           = spacing,
                        ToolWidth             = Settings.Machine.NozzleDiamMM,
                        AngleDeg = angle,
                    };
                    fill_gen.Compute();
                    scheduler.AppendCurveSets(fill_gen.GetFillCurves());
                }
            }

            // fit bbox to try to find fill angle that has shortest spans
            //Box2d box = poly.Outer.MinimalBoundingBox(0.00001);
            //Vector2d axis = (box.Extent.x > box.Extent.y) ? box.AxisY : box.AxisX;
            //double angle = Math.Atan2(axis.y, axis.x) * MathUtil.Rad2Deg;

            // [RMS] should we do something like this?
            //if (Settings.SolidFillBorderOverlapX > 0) {
            //	double offset = Settings.Machine.NozzleDiamMM * Settings.SolidFillBorderOverlapX;
            //	fillPolys = ClipperUtil.MiterOffset(fillPolys, offset);
            //}
        }
Esempio n. 9
0
        /// <summary>
        /// Slice the meshes and return the slice stack.
        /// </summary>
        public Result Compute()
        {
            Result result = new Result();

            if (Meshes.Count == 0)
            {
                return(result);
            }

            // find Z interval we want to slice in
            Interval1d zrange = Interval1d.Empty;

            foreach (var meshinfo in Meshes)
            {
                zrange.Contain(meshinfo.bounds.Min.z);
                zrange.Contain(meshinfo.bounds.Max.z);
            }
            if (SetMinZValue != double.MinValue)
            {
                zrange.a = SetMinZValue;
            }

            result.TopZ  = Math.Round(zrange.b, PrecisionDigits);
            result.BaseZ = Math.Round(zrange.a, PrecisionDigits);

            // [TODO] might be able to make better decisions if we took flat regions
            // into account when constructing initial Z-heights? if we have large flat
            // region just below Zstep, might make sense to do two smaller Z-steps so we
            // can exactly hit it??

            // construct list of clearing Z-heights
            List <double> clearingZLayers = new List <double>();
            double        cur_layer_z     = zrange.b;
            int           layer_i         = 0;

            while (cur_layer_z > zrange.a)
            {
                double layer_height = get_layer_height(layer_i);
                cur_layer_z -= layer_height;
                double z = Math.Round(cur_layer_z, PrecisionDigits);
                clearingZLayers.Add(z);
                layer_i++;
            }
            if (clearingZLayers.Last() < result.BaseZ)
            {
                clearingZLayers[clearingZLayers.Count - 1] = result.BaseZ;
            }
            if (clearingZLayers.Last() == clearingZLayers[clearingZLayers.Count - 2])
            {
                clearingZLayers.RemoveAt(clearingZLayers.Count - 1);
            }

            // construct layer slices from Z-heights
            List <PlanarSlice> clearing_slice_list = new List <PlanarSlice>();

            layer_i = 0;
            for (int i = 0; i < clearingZLayers.Count; ++i)
            {
                double layer_height = (i == clearingZLayers.Count - 1) ?
                                      (result.TopZ - clearingZLayers[i]) : (clearingZLayers[i + 1] - clearingZLayers[i]);
                double     z     = clearingZLayers[i];
                Interval1d zspan = new Interval1d(z, z + layer_height);

                if (SliceLocation == SliceLocations.EpsilonBase)
                {
                    z += 0.001;
                }

                PlanarSlice slice = SliceFactoryF(zspan, z, layer_i);
                clearing_slice_list.Add(slice);
                layer_i++;
            }


            int NH = clearing_slice_list.Count;

            if (NH > MaxLayerCount)
            {
                throw new Exception("MeshPlanarSlicer.Compute: exceeded layer limit. Increase .MaxLayerCount.");
            }

            PlanarSlice[] clearing_slices = clearing_slice_list.ToArray();

            // assume Resolve() takes 2x as long as meshes...
            TotalCompute = (Meshes.Count * NH) + (2 * NH);
            Progress     = 0;

            // compute slices separately for each mesh
            for (int mi = 0; mi < Meshes.Count; ++mi)
            {
                if (Cancelled())
                {
                    break;
                }

                DMesh3           mesh         = Meshes[mi].mesh;
                PrintMeshOptions mesh_options = Meshes[mi].options;

                // [TODO] should we hang on to this spatial? or should it be part of assembly?
                DMeshAABBTree3   spatial = new DMeshAABBTree3(mesh, true);
                AxisAlignedBox3d bounds  = Meshes[mi].bounds;

                bool is_cavity   = mesh_options.IsCavity;
                bool is_crop     = mesh_options.IsCropRegion;
                bool is_support  = mesh_options.IsSupport;
                bool is_closed   = (mesh_options.IsOpen) ? false : mesh.IsClosed();
                var  useOpenMode = (mesh_options.OpenPathMode == PrintMeshOptions.OpenPathsModes.Default) ?
                                   DefaultOpenPathMode : mesh_options.OpenPathMode;

                if (is_crop || is_support)
                {
                    throw new Exception("Not supported!");
                }

                // each layer is independent so we can do in parallel
                gParallel.ForEach(Interval1i.Range(NH), (i) => {
                    if (Cancelled())
                    {
                        return;
                    }

                    double z = clearing_slices[i].Z;
                    if (z < bounds.Min.z || z > bounds.Max.z)
                    {
                        return;
                    }

                    // compute cut
                    Polygon2d[] polys; PolyLine2d[] paths;
                    ComputeSlicePlaneCurves(mesh, spatial, z, is_closed, out polys, out paths);

                    if (is_closed)
                    {
                        // construct planar complex and "solids"
                        // (ie outer polys and nested holes)
                        PlanarComplex complex = new PlanarComplex();
                        foreach (Polygon2d poly in polys)
                        {
                            complex.Add(poly);
                        }

                        PlanarComplex.FindSolidsOptions options
                            = PlanarComplex.FindSolidsOptions.Default;
                        options.WantCurveSolids            = false;
                        options.SimplifyDeviationTolerance = 0.001;
                        options.TrustOrientations          = true;
                        options.AllowOverlappingHoles      = true;

                        PlanarComplex.SolidRegionInfo solids   = complex.FindSolidRegions(options);
                        List <GeneralPolygon2d> solid_polygons = ApplyValidRegions(solids.Polygons);

                        if (is_cavity)
                        {
                            add_cavity_polygons(clearing_slices[i], solid_polygons, mesh_options);
                        }
                        else
                        {
                            if (ExpandStockAmount > 0)
                            {
                                solid_polygons = ClipperUtil.MiterOffset(solid_polygons, ExpandStockAmount);
                            }
                            add_solid_polygons(clearing_slices[i], solid_polygons, mesh_options);
                        }
                    }

                    Interlocked.Increment(ref Progress);
                });       // end of parallel.foreach
            }             // end mesh iter

            // resolve planar intersections, etc
            gParallel.ForEach(Interval1i.Range(NH), (i) => {
                if (Cancelled())
                {
                    return;
                }
                clearing_slices[i].Resolve();
                Interlocked.Add(ref Progress, 2);
            });
            // add to clearing stack
            result.Clearing = SliceStackFactoryF();
            for (int k = 0; k < clearing_slices.Length; ++k)
            {
                result.Clearing.Add(clearing_slices[k]);
            }



            /*
             * Horizontal planar regions finishing pass.
             * First we find all planar horizontal Z-regions big enough to mill.
             * Then we add slices at the Z's we haven't touched yet.
             *
             * Cannot just 'fill' planar regions because we will miss edges that might
             * be millable. So we grow region and then intersect with full-slice millable area.
             */

            // find set of horizontal flat regions
            Dictionary <double, List <PlanarRegion> > flat_regions = FindPlanarZRegions(ToolDiameter);

            if (flat_regions.Count == 0)
            {
                goto done_slicing;
            }

            // if we have already milled this exact Z-height in clearing pass, then we can skip it
            List <double> doneZ = new List <double>();

            foreach (double z in flat_regions.Keys)
            {
                if (clearingZLayers.Contains(z))
                {
                    doneZ.Add(z);
                }
            }
            foreach (var z in doneZ)
            {
                flat_regions.Remove(z);
            }

            // create slice for each layer
            PlanarSlice[] horz_slices = new PlanarSlice[flat_regions.Count];
            List <double> flatZ       = new List <double>(flat_regions.Keys);

            flatZ.Sort();
            for (int k = 0; k < horz_slices.Length; ++k)
            {
                double     z     = flatZ[k];
                Interval1d zspan = new Interval1d(z, z + LayerHeightMM);
                horz_slices[k] = SliceFactoryF(zspan, z, k);

                // compute full millable region slightly above this slice.
                PlanarSlice clip_slice = ComputeSolidSliceAtZ(z + 0.0001, false);
                clip_slice.Resolve();

                // extract planar polys
                List <Polygon2d> polys   = GetPlanarPolys(flat_regions[z]);
                PlanarComplex    complex = new PlanarComplex();
                foreach (Polygon2d poly in polys)
                {
                    complex.Add(poly);
                }

                // convert to planar solids
                PlanarComplex.FindSolidsOptions options
                    = PlanarComplex.FindSolidsOptions.SortPolygons;
                options.SimplifyDeviationTolerance = 0.001;
                options.TrustOrientations          = true;
                options.AllowOverlappingHoles      = true;
                PlanarComplex.SolidRegionInfo solids         = complex.FindSolidRegions(options);
                List <GeneralPolygon2d>       solid_polygons = ApplyValidRegions(solids.Polygons);

                // If planar solid has holes, then when we do inset later, we might lose
                // too-thin parts. Shrink the holes to avoid this case.
                //FilterHoles(solid_polygons, 0.55 * ToolDiameter);

                // ok now we need to expand region and intersect with full region.
                solid_polygons = ClipperUtil.MiterOffset(solid_polygons, ToolDiameter * 0.5, 0.0001);
                solid_polygons = ClipperUtil.Intersection(solid_polygons, clip_slice.Solids, 0.0001);

                // Same idea as above, but if we do after, we keep more of the hole and
                // hence do less extra clearing.
                // Also this could then be done at the slicer level instead of here...
                // (possibly this entire thing should be done at slicer level, except we need clip_slice!)
                FilterHoles(solid_polygons, 1.1 * ToolDiameter);

                add_solid_polygons(horz_slices[k], solid_polygons, PrintMeshOptions.Default());
            }

            // resolve planar intersections, etc
            int NF = horz_slices.Length;

            gParallel.ForEach(Interval1i.Range(NF), (i) => {
                if (Cancelled())
                {
                    return;
                }
                horz_slices[i].Resolve();
                Interlocked.Add(ref Progress, 2);
            });
            // add to clearing stack
            result.HorizontalFinish = SliceStackFactoryF();
            for (int k = 0; k < horz_slices.Length; ++k)
            {
                result.HorizontalFinish.Add(horz_slices[k]);
            }

done_slicing:
            return(result);
        }