Esempio n. 1
0
        /// <summary>
        /// Check that all values in other are within epsilon of the values in this
        /// </summary>
        /// <param name="other"></param>
        /// <param name="epsilon"></param>
        /// <returns></returns>
        public bool EpsilonEquals(NurbsSurfaceKnotList other, double epsilon)
        {
            if (null == other)
            {
                throw new ArgumentNullException("other");
            }

            if (ReferenceEquals(this, other))
            {
                return(true);
            }

            if (m_direction != other.m_direction)
            {
                return(false);
            }

            if (Count != other.Count)
            {
                return(false);
            }

            // check for equality of spans
            for (int i = 1; i < Count; ++i)
            {
                double myDelta    = this[i] - this[i - 1];
                double theirDelta = other[i] - other[i - 1];
                if (!RhinoMath.EpsilonEquals(myDelta, theirDelta, epsilon))
                {
                    return(false);
                }
            }

            return(true);
        }
Esempio n. 2
0
    /// <summary>
    /// This procedure contains the user code. Input parameters are provided as regular arguments,
    /// Output parameters as ref arguments. You don't have to assign output parameters,
    /// they will have a default value.
    /// </summary>
    private void RunScript(Brep brep, object void0, int fate, int mode, double rot, object void1, int divX, int divY, double stepZ, int inX, int inY, ref object DucatiumPanigaleumAmamusDumSpiramus, ref object Elapsed, ref object baseBoxWire, ref object baseGrid, ref object baseColumns, ref object xStruts, ref object yStruts)
    {
        if (brep == null || !brep.IsValid)
        {
            return;
        }

        System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
        sw.Start();

        BrepFace baseFace = brep.Faces.Where(x => x.IsPlanar()).ToList()[0];
        Curve    bound    = baseFace.OuterLoop.To3dCurve();

        Plane  plane    = Plane.WorldXY;
        double rotPlane = RhinoMath.ToRadians(rot);

        plane.Rotate(rotPlane, plane.ZAxis);

        Box box = new Box(plane, bound);

        baseBoxWire = box.ToBrep().GetWireframe(-1);

        GetElements(box, divX, divY, baseFace, brep, stepZ, inX, inY);
        baseGrid    = grid;
        baseColumns = columns;
        xStruts     = xConn;
        yStruts     = yConn;

        sw.Stop();
        Elapsed = (string.Format("Elapsed: {0}ms", sw.Elapsed.TotalMilliseconds));
    }
        static double InHostUnits(double value, DB.ParameterType type, RhinoDoc rhinoDoc)
        {
            if (rhinoDoc is null)
            {
                return(double.NaN);
            }

            switch (type)
            {
            case DB.ParameterType.Length:
                return(value * RhinoMath.UnitScale(rhinoDoc.ModelUnitSystem, UnitSystem.Feet));

            //value *= Math.Pow(RhinoMath.UnitScale(rhinoDoc.ModelUnitSystem, UnitSystem.Millimeters), 1.0);
            //return DB.UnitUtils.ConvertToInternalUnits(value, DB.DisplayUnitType.DUT_MILLIMETERS);

            case DB.ParameterType.Area:
                return(value * Math.Pow(RhinoMath.UnitScale(rhinoDoc.ModelUnitSystem, UnitSystem.Feet), 1.0));

            //value *= Math.Pow(RhinoMath.UnitScale(rhinoDoc.ModelUnitSystem, UnitSystem.Millimeters), 2.0);
            //return DB.UnitUtils.ConvertToInternalUnits(value, DB.DisplayUnitType.DUT_SQUARE_MILLIMETERS);

            case DB.ParameterType.Volume:
                return(value * Math.Pow(RhinoMath.UnitScale(rhinoDoc.ModelUnitSystem, UnitSystem.Feet), 1.0));

            //value *= Math.Pow(RhinoMath.UnitScale(rhinoDoc.ModelUnitSystem, UnitSystem.Millimeters), 3.0);
            //return DB.UnitUtils.ConvertToInternalUnits(value, DB.DisplayUnitType.DUT_CUBIC_MILLIMETERS);

            default:
                Debug.WriteLine(false, $"{nameof(InHostUnits)} do not implement conversion for {type}");
                break;
            }

            return(value);
        }
Esempio n. 4
0
        /**
         * divideCrvsByDeltaTan : Curve[] * double -> LinkedList<Plane>
         * REQUIRES: theta > 0
         * ENSURES: divideCrvsByDeltaTan(crvs, theta) returns a linked list of planes
         *          along the curves s.t. there is a plane at every point along
         *          the curve where the change in the tangent vector between
         *          two points is greater than theta.
         **/
        private IEnumerable <Point3d> DivByAngle(Curve crv, double angle)
        {
            //initialize parameters
            double   theta    = angle;
            Interval dom      = crv.Domain;
            double   stepSize = Math.Abs(dom.Length) * Constants.AbsoluteTolerance * Constants.AbsoluteTolerance;

            //initialize list
            List <Point3d> pts = new List <Point3d>();

            Continuity c = Continuity.C1_continuous;
            //initialize data

            double rover = dom.Min; //steps along the curve by stepSize

            //Add plane at start point of curve to list
            Point3d pt = crv.PointAt(rover);

            pts.Add(pt);

            //Increment
            Vector3d prevTan  = crv.TangentAt(rover);
            double   oldRover = rover; //stores the previous rover for comparison

            rover += stepSize;

            while (rover < dom.Max)
            {
                Vector3d currTan = crv.TangentAt(rover);
                //If there is a discontinuity between the oldRover and rover
                //then place a point at the discontinuity and update prevTan.
                double discontinuity;
                bool   isDisc = crv.GetNextDiscontinuity(c, oldRover, rover,
                                                         out discontinuity);
                if (isDisc)
                {
                    pt = crv.PointAt(discontinuity);
                    pts.Add(pt);
                    prevTan = crv.TangentAt(discontinuity);
                }

                //If the change in tangent vector is greater than theta,
                //then drop a target at the rover and update prevTan.
                double delta = RhinoMath.ToDegrees(Math.Abs(Vector3d.VectorAngle(prevTan, currTan)));
                if (delta > theta)
                {
                    pt = crv.PointAt(rover);
                    pts.Add(pt);
                    prevTan = currTan;
                }
                //Increment
                oldRover = rover;
                rover   += stepSize;
            }

            //Add target at end point of curve
            pt = crv.PointAt(dom.Max);
            pts.Add(pt);
            return(pts);
        }
Esempio n. 5
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            int        id         = 0;
            RebarShape rebarShape = null;
            int        count      = 0;
            Curve      curve      = null;
            double     angle      = 0.0;

            DA.GetData(0, ref id);
            DA.GetData(1, ref rebarShape);
            DA.GetData(2, ref curve);
            DA.GetData(3, ref count);
            if (!DA.GetData(4, ref angle))
            {
                return;
            }
            if (_useDegrees)
            {
                angle = RhinoMath.ToRadians(angle);
            }

            RebarGroup rebarGroup = new RebarGroup(id, new RebarSpacing(rebarShape, count, curve, angle));

            DA.SetData(0, rebarGroup);
            DA.SetDataList(1, rebarGroup.RebarGroupMesh);
            DA.SetDataList(2, rebarGroup.RebarGroupCurves);
        }
Esempio n. 6
0
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        protected override void SolveInstance(IGH_DataAccess data)
        {
            var x = 0.0;

            if (!data.GetData(0, ref x))
            {
                return;
            }

            if (!RhinoMath.IsValidDouble(x))
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "X Value is invalid");
                return;
            }

            var y = 0.0;

            if (!data.GetData(1, ref y))
            {
                return;
            }

            if (!RhinoMath.IsValidDouble(y))
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Y Value is invalid");
                return;
            }

            var sum = MooseCommon.Utility.Sum(x, y);

            data.SetData(0, sum);
        }
 public bool EpsilonEquals(Quaternion other, double epsilon)
 {
     return(RhinoMath.EpsilonEquals(m_a, other.m_a, epsilon) &&
            RhinoMath.EpsilonEquals(m_b, other.m_b, epsilon) &&
            RhinoMath.EpsilonEquals(m_c, other.m_c, epsilon) &&
            RhinoMath.EpsilonEquals(m_d, other.m_d, epsilon));
 }
Esempio n. 8
0
    public static Result GetAngle(RhinoDoc doc)
    {
        var gp = new GetPoint();

        gp.SetCommandPrompt("Base point");
        gp.Get();
        if (gp.CommandResult() != Result.Success)
        {
            return(gp.CommandResult());
        }
        var base_point = gp.Point();

        gp.SetCommandPrompt("First reference point");
        gp.DrawLineFromPoint(base_point, true);
        gp.Get();
        if (gp.CommandResult() != Result.Success)
        {
            return(gp.CommandResult());
        }
        var first_point = gp.Point();

        double angle_radians;
        var    rc = RhinoGet.GetAngle("Second reference point", base_point, first_point, 0, out angle_radians);

        if (rc == Result.Success)
        {
            RhinoApp.WriteLine("Angle = {0} degrees", RhinoMath.ToDegrees(angle_radians));
        }

        return(rc);
    }
Esempio n. 9
0
        private static void closeIntersect(Curve innerBounderyCrv, PointCloud startPTsLeft, List <Parkingspace> finalParkingLinesLeft, Point3d crvEnd, out Curve lineOne, out CurveIntersections intersectionsOne)
        {
            int indexOne = startPTsLeft.ClosestPoint(crvEnd);

            lineOne = finalParkingLinesLeft[indexOne].Curves;

            Vector3d vectorone = lineOne.TangentAtEnd;

            vectorone.Rotate(RhinoMath.ToRadians(90), new Vector3d(0, 0, 1));
            Point3d movedPTone = lineOne.PointAtStart + vectorone;

            vectorone.Rotate(RhinoMath.ToRadians(180), new Vector3d(0, 0, 1));
            Point3d    movedPTTwo  = lineOne.PointAtStart + vectorone;
            PointCloud directionPT = new PointCloud();

            directionPT.Add(movedPTone);
            directionPT.Add(movedPTTwo);

            int indexdir = directionPT.ClosestPoint(crvEnd);

            if (indexdir == 0)
            {
                vectorone.Rotate(RhinoMath.ToRadians(180), new Vector3d(0, 0, 1));
            }
            vectorone        = Vector3d.Multiply(vectorone, 10);
            intersectionsOne = Intersection.CurveCurve(innerBounderyCrv, new Line(lineOne.PointAtEnd, vectorone).ToNurbsCurve(), 0.01, 0.01);
        }
Esempio n. 10
0
        public override void Draw()
        {
            // you need the up vector to determine the rotation axis
            //Vector3d up_vector = new Vector3d(0.0,0.0,1.0);
            // this is the same as Vector3d.ZAxis, which always returns new Vector(0.0,0.0,1.0)

            // rotate the earth sphere (radians,rotation_axis,rotation_origin)
            double base_speed = 0.1;

            earth.Rotate(RhinoMath.ToRadians(base_speed), Vector3d.ZAxis, origin);

            // add earth to document
            doc.Objects.AddSphere(earth);

            //moon speed ratio (orbit time = earth : 365.4 days, moon : 27.32days)
            double moon_speed = 365.4 / 27.32;

            // you can access to the spheres center by getting the .Center property.
            // rotation the moon sphere

            moon.Rotate(RhinoMath.ToRadians(base_speed * moon_speed), Vector3d.ZAxis, earth.Center);

            // add moon to document
            doc.Objects.AddSphere(moon);
        }
Esempio n. 11
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            string      name     = String.Empty;
            Profile     profile  = null;
            List <Line> lines    = new List <Line>();
            double      angle    = 0.0;
            Material    material = null;
            int         type     = 0;

            DA.GetData(0, ref name);
            DA.GetData(1, ref profile);
            if (!DA.GetData(2, ref angle))
            {
                return;
            }
            if (_useDegrees)
            {
                angle = RhinoMath.ToRadians(angle);
            }
            DA.GetData(3, ref material);
            DA.GetData(4, ref type);
            DA.GetDataList(5, lines);

            ProfileToElements profileToElements = new ProfileToElements(name, profile, lines, angle, material, type);

            DA.SetData(0, profileToElements);
            DA.SetDataList(1, profileToElements.Breps);
        }
Esempio n. 12
0
        /// <summary>
        /// Returns a mapping tag that is used to detect when a mesh's colors need to be set.
        /// </summary>
        private MappingTag GetMappingTag()
        {
            var mt = new MappingTag();

            // Since the false colors that are shown will change if
            // the mesh is transformed, we have to initialize the
            // transformation.
            mt.MeshTransform = Transform.Identity;

            // This is the analysis mode id passed to the
            // CRhinoVisualAnalysisMode constructor. Use the
            // m_am_id member and it this code will alwasy
            // work correctly.
            mt.Id = Id;

            // This is a 32 bit CRC or the information used to
            // set the false colors.

            // For this example, the m_z_range and m_hue_range
            // intervals control the colors, so we calculate
            // their crc.
            uint crc = 0;

            crc           = RhinoMath.CRC32(crc, m_z_range.T0);
            crc           = RhinoMath.CRC32(crc, m_z_range.T1);
            crc           = RhinoMath.CRC32(crc, m_hue_range.T0);
            crc           = RhinoMath.CRC32(crc, m_hue_range.T1);
            mt.MappingCRC = crc;

            return(mt);
        }
Esempio n. 13
0
        /// <summary>
        /// Try to fit a circle to two curves using tangent relationships.
        /// </summary>
        /// <param name="c1">First curve to touch.</param>
        /// <param name="c2">Second curve to touch.</param>
        /// <param name="t1">Parameter on first curve close to desired solution.</param>
        /// <param name="t2">Parameter on second curve closet to desired solution.</param>
        /// <returns>Valid circle on success, Circle.Unset on failure.</returns>
        /// <since>5.0</since>
        public static Circle TryFitCircleTT(Curve c1, Curve c2, double t1, double t2)
        {
            if (c1 == null)
            {
                throw new ArgumentNullException("c1");
            }
            if (c2 == null)
            {
                throw new ArgumentNullException("c2");
            }
            if (!RhinoMath.IsValidDouble(t1))
            {
                throw new ArgumentNullException("t1");
            }
            if (!RhinoMath.IsValidDouble(t2))
            {
                throw new ArgumentNullException("t2");
            }

            Circle rc = Circle.Unset;

            if (!UnsafeNativeMethods.ON_Circle_TryFitTT(c1.ConstPointer(), c2.ConstPointer(), t1, t2, ref rc))
            {
                rc = Circle.Unset;
            }

            Runtime.CommonObject.GcProtect(c1, c2);
            return(rc);
        }
Esempio n. 14
0
        public static Dictionary <OSMTag, List <PolylineCurve> > WayPolylinesFromCoords(RequestHandler result)
        {
            var   geometryResult  = new Dictionary <OSMTag, List <PolylineCurve> >();
            var   unitScale       = RhinoMath.UnitScale(UnitSystem.Meters, RhinoDoc.ActiveDoc.ModelUnitSystem); // OSM conversion assumes meters
            Coord lengthPerDegree = GetDegreesPerAxis(result.MinBounds, result.MaxBounds, unitScale);

            foreach (var entry in result.FoundData)
            {
                geometryResult[entry.Key] = new List <PolylineCurve>();
                foreach (FoundItem item in entry.Value)
                {
                    var linePoints = new List <Point3d>();
                    foreach (var coord in item.Coords)
                    {
                        var pt = GetPointFromLatLong(coord, lengthPerDegree, result.MinBounds);
                        linePoints.Add(pt);
                    }

                    var polyLine = new PolylineCurve(linePoints); // Creating a polylinecurve from scratch makes invalid geometry
                    geometryResult[entry.Key].Add(polyLine);
                }
            }

            return(geometryResult);
        }
Esempio n. 15
0
        /// <summary>
        /// Check that all values in other are within epsilon of the values in this
        /// </summary>
        /// <param name="other"></param>
        /// <param name="epsilon"></param>
        /// <returns></returns>
        public bool EpsilonEquals(NurbsCurvePointList other, double epsilon)
        {
            if (null == other)
            {
                throw new ArgumentNullException("other");
            }

            if (ReferenceEquals(this, other))
            {
                return(true);
            }

            if (Count != other.Count)
            {
                return(false);
            }

            if (!RhinoMath.EpsilonEquals(ControlPolygonLength, other.ControlPolygonLength, epsilon))
            {
                return(false);
            }

            for (int i = 0; i < Count; ++i)
            {
                ControlPoint mine   = this[i];
                ControlPoint theirs = other[i];
                if (!mine.EpsilonEquals(theirs, epsilon))
                {
                    return(false);
                }
            }

            return(true);
        }
Esempio n. 16
0
        private bool CalculatePlaneAngle(Point3d point)
        {
            if (System.Math.Abs(m_plane.ValueAt(point)) > 0.000001)
            {
                return(false);
            }

            if (m_base_point.DistanceTo(point) <= RhinoMath.ZeroTolerance)
            {
                return(false);
            }

            Vector3d v = point - m_base_point;

            v.Unitize();

            Vector3d zerov = m_ref_point - m_base_point;
            double   r     = zerov.Length;

            zerov.Unitize();

            double dot = zerov * v;

            if (!RhinoMath.IsValidDouble(dot))
            {
                dot = 1.0;
            }
            else if (dot > 1.0)
            {
                dot = 1.0;
            }
            else if (dot < -1.0)
            {
                dot = -1.0;
            }

            double   test_angle = Math.Acos(dot);
            Vector3d zaxis      = Vector3d.CrossProduct(m_plane.XAxis, m_plane.YAxis);

            zaxis.Unitize();

            v = Vector3d.CrossProduct(zaxis, zerov);
            v.Unitize();

            Plane yplane = new Plane(m_base_point, v);

            if (yplane.ValueAt(point) < 0.0)
            {
                test_angle = 2.0 * Math.PI - test_angle;
            }

            m_angle = test_angle;

            Plane arc_plane = new Plane(m_plane.Origin, zerov, v);

            m_arc = new Arc(arc_plane, r, m_angle);

            return(m_arc.IsValid);
        }
        //Surfaceを回転させ積み上げていく
        public void MoveSrf(int num)//pile of brick
        {
            double ang = RhinoMath.ToRadians((angle / (num - 1)) * id);

            bool flag2 = srf.Rotate(ang, NormalVector(), Center());

            bool flag3 = srf.Rotate(ang, new Vector3d(0, 1, 0), Center());
        }
Esempio n. 18
0
        public Hour(double newClockTime, double newAltitudeAngle, double newAzumithAngle)
        {
            clockTime     = newClockTime;
            altitudeAngle = RhinoMath.ToRadians(newAltitudeAngle);
            azumithAngle  = RhinoMath.ToRadians(newAzumithAngle);

            sunVector = CreateSunVector();
        }
 public int FindParticleIndex(Point3d Pos, double tol, bool ByCurrent)
 {
     if (ByCurrent)
     {
         return(this.m_particles.FindIndex(x => RhinoMath.OrthoClose(x.Position, Pos, tol)));
     }
     return(this.m_particles.FindIndex(x => RhinoMath.OrthoClose(x.StartPosition, Pos, tol)));
 }
Esempio n. 20
0
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            Guid    guid    = new Guid();
            Point3d loc     = new Point3d();
            Point3d tar     = new Point3d();
            double  ins     = 100;
            double  angle   = 90;
            double  hot     = 0.5;
            Color   diffuse = Color.Aqua;
            Color   spec    = Color.Aqua;

            DA.GetData("Guid", ref guid);
            DA.GetData("Location", ref loc);
            DA.GetData("Target", ref tar);
            DA.GetData("Intensity", ref ins);
            DA.GetData("Radius", ref angle);
            DA.GetData("HotSpot", ref hot);
            DA.GetData("DiffuseColor", ref diffuse);

            Rhino.DocObjects.LightObject spotObj = null;
            foreach (Rhino.DocObjects.LightObject obj in Rhino.RhinoDoc.ActiveDoc.Lights)
            {
                if (obj.Id == guid)
                {
                    spotObj = obj;
                    break;
                }
            }

            if (((Param_Number)Params.Input[4]).UseDegrees)
            {
                angle = RhinoMath.ToRadians(angle);
            }

            if (angle <= 0 || angle >= Math.PI / 2)
            {
                angle = Math.PI / 4;
                this.AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Radius must be in 0-Pi/2.");
            }

            if (hot <= 0 || hot >= 1)
            {
                hot = 0.5;
                this.AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "HotSpot must be in 0-1.");
            }

            spotObj.LightGeometry.LightStyle       = LightStyle.WorldSpot;
            spotObj.LightGeometry.Location         = loc;
            spotObj.LightGeometry.Direction        = tar - loc;
            spotObj.LightGeometry.Intensity        = ins;
            spotObj.LightGeometry.SpotAngleRadians = angle;
            spotObj.LightGeometry.HotSpot          = hot;
            spotObj.LightGeometry.Diffuse          = diffuse;
            spotObj.LightGeometry.Specular         = spec;


            Rhino.RhinoDoc.ActiveDoc.Lights.Modify(guid, spotObj.LightGeometry);
        }
Esempio n. 21
0
 static ToUnitSystemStatic()
 {
     foreach (var unit in DB.UnitUtils.GetValidDisplayUnits(DB.UnitType.UT_Length))
     {
         var revit = DB.UnitUtils.Convert(1.0, DB.DisplayUnitType.DUT_METERS, unit);
         var rhino = RhinoMath.UnitScale(UnitSystem.Meters, unit.ToUnitSystem());
         //Debug.Assert(Rhino.RhinoMath.EpsilonEquals(revit, rhino, Rhino.RhinoMath.ZeroTolerance), $"ToRhinoLengthUnits({unit}) fails!!");
     }
 }
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            List <Line>     lines   = new List <Line>();
            List <Vector3d> vectors = new List <Vector3d>();
            double          angle   = 0;

            if (!DA.GetDataList(0, lines))
            {
                return;
            }
            if (!DA.GetDataList(1, vectors))
            {
                return;
            }
            if (!DA.GetData(2, ref angle))
            {
                return;
            }
            if (p.UseDegrees)
            {
                angle = RhinoMath.ToRadians(angle);
            }
            List <Line> goodline  = new List <Line>();
            List <Line> badline   = new List <Line>();
            List <int>  indexgood = new List <int>();
            List <int>  indexbad  = new List <int>();

            for (int i = 0; i < lines.Count; i++)
            {
                Line li = lines[i];
                for (int q = 0; q < vectors.Count; q++)
                {
                    double degree = Vector3d.VectorAngle(li.Direction, vectors[q]);
                    if (degree > Math.PI * 0.5)
                    {
                        degree = Math.PI - degree;
                    }
                    if (degree <= angle + 0.000000001)
                    {
                        goodline.Add(li);
                        indexgood.Add(i);
                        lines[i] = Line.Unset;
                        break;
                    }
                }
                if (lines[i] != Line.Unset)
                {
                    badline.Add(lines[i]);
                    indexbad.Add(i);
                }
            }
            DA.SetDataList(0, badline);
            DA.SetDataList(1, goodline);
            DA.SetDataList(2, indexbad);
            DA.SetDataList(3, indexgood);
        }
Esempio n. 23
0
        //methods
        public void Rotate(RhinoDoc _doc)
        {
            // unit angle in one draw execution(frame). respectively for one year
            double delta_angle = RhinoMath.ToRadians(365.4 / rotation_days);

            // rotate the sphere
            obj.Rotate(delta_angle, Vector3d.ZAxis, rotation_origin);

            // add it to the document
            _doc.Objects.AddSphere(obj);
        }
Esempio n. 24
0
            public double ScaleToFitDocument(double input)
            {
                //The input is coming in from 0-300
                //This correlates with roughly 20 feet
                double scaledToFeet = input / 8;

                UnitSystem currentDocUnits  = RhinoDoc.ActiveDoc.ModelUnitSystem;
                double     unitSystemScaler = RhinoMath.UnitScale(UnitSystem.Feet, currentDocUnits);

                return(scaledToFeet * unitSystemScaler);
            }
Esempio n. 25
0
        /// <summary>
        /// Calculate false color.
        /// </summary>
        private Color FalseColor(double z)
        {
            // Simple example of one way to change a number
            // into a color.
            var s = m_z_range.NormalizedParameterAt(z);

            s = RhinoMath.Clamp(s, 0.0, 1.0);
            var hue = m_hue_range.ParameterAt(s);

            return(ColorFromHsv(hue, 1.0, 1.0));
        }
Esempio n. 26
0
        //private void ExportSampler()
        //{
        //    _mitsubaXml.CreateSamplerXml();
        //}

        /// <summary>
        /// This method exports the Mitsuba emitters: lights and environment.
        ///
        /// NOTE: if you try to get the environment with RhinoDoc.ActiveDoc.RenderEnvironments[0]
        /// Rhino crashes with a "pure virtual function called" error...
        /// </summary>
        private void ExportEmitters()
        {
            if (RhinoDoc.ActiveDoc.RenderEnvironments.Count > 0)
            {
                //HDR environment
                var environment = RenderEnvironment.CurrentEnvironment;
                var texture     = environment.FindChild("texture");

                if (texture != null)
                {
                    var env_file = texture.Fields.GetField("filename").ValueAsObject();
                    _mitsubaXml.CreateEnvironmentEmitterXml(env_file.ToString());
                }
            }

            //Lights
            foreach (var obj in RhinoDoc.ActiveDoc.Objects.GetObjectList(ObjectType.Light))
            {
                if (!obj.Visible)
                {
                    continue;
                }

                var objRef = new ObjRef(obj);
                var light  = objRef.Light();

                MitsubaEmitter emitter = null;

                if (light.IsPointLight)
                {
                    //var location = light.Location;
                    //var spectrum = light.Diffuse;
                    //var sampleWeight = light.Intensity;
                    emitter = new PointLightSource(light.Location, (float)light.Intensity * 100);
                }
                else if (light.IsSpotLight)
                {
                    var origin      = light.Location;
                    var target      = light.Direction;
                    var cutoffAngle = (float)RhinoMath.ToDegrees(light.SpotAngleRadians);
                    var intensity   = (float)light.Intensity * 50000;                   //TODO Multiplicador SpotLight ???
                    emitter = new SpotLightSource(origin, target, intensity, cutoffAngle);
                }
                else if (light.IsSunLight)
                {
                    //TODO SunLight
                }

                if (emitter != null)
                {
                    _mitsubaXml.CreateEmitterXml(emitter);
                }
            }
        }
Esempio n. 27
0
        public static double[] AreaOf(List <Curve> curves)
        {
            UnitSystem currentDocUnits  = RhinoDoc.ActiveDoc.ModelUnitSystem;
            double     unitSystemScaler = RhinoMath.UnitScale(currentDocUnits, UnitSystem.Feet);

            double[] areas = new double[curves.Count()];
            for (int i = 0; i < curves.Count(); i++)
            {
                areas[i] = Math.Round(AreaMassProperties.Compute(curves[i]).Area *unitSystemScaler *unitSystemScaler, 2);
            }
            return(areas);
        }
Esempio n. 28
0
        public static Result Import3DMFile(string filePath, Document doc, BuiltInCategory builtInCategory)
        {
            using (var model = File3dm.Read(filePath))
            {
                var scaleFactor = RhinoMath.UnitScale(model.Settings.ModelUnitSystem, Revit.ModelUnitSystem);

                using (var trans = new Transaction(doc, "Import 3D Model"))
                {
                    if (trans.Start() == TransactionStatus.Started)
                    {
                        var categoryId = new ElementId(builtInCategory);

                        var ds = DirectShape.CreateElement(doc, categoryId);
                        ds.Name = Path.GetFileName(filePath);

                        foreach (var obj in model.Objects)
                        {
                            if (!obj.Attributes.Visible)
                            {
                                continue;
                            }

                            var layer = model.AllLayers.FindIndex(obj.Attributes.LayerIndex);
                            if (layer?.IsVisible != true)
                            {
                                continue;
                            }

                            var geometryList = ImportObject(obj.Geometry, obj.Attributes, scaleFactor);
                            if (geometryList == null)
                            {
                                continue;
                            }

                            try { ds.AppendShape(geometryList); }
                            catch (Autodesk.Revit.Exceptions.ArgumentException) { }
                        }

                        if (trans.Commit() == TransactionStatus.Committed)
                        {
                            var elements = new ElementId[] { ds.Id };
                            Revit.ActiveUIDocument.Selection.SetElementIds(elements);
                            Revit.ActiveUIDocument.ShowElements(elements);

                            return(Result.Succeeded);
                        }
                    }
                }
            }

            return(Result.Failed);
        }
Esempio n. 29
0
        protected override void SolveInstance(IGH_DataAccess access)
        {
            Curve  curve = null;
            string edge  = null;
            string fill  = null;

            if (!access.GetData(0, ref curve))
            {
                return;
            }
            access.GetData(1, ref edge);
            access.GetData(2, ref fill);

            if (string.IsNullOrWhiteSpace(edge) && string.IsNullOrWhiteSpace(fill))
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Either an edge or a fill is required.");
                return;
            }

            Polyline polyline;

            if (!curve.TryGetPolyline(out polyline))
            {
                curve = curve.ToPolyline(0.1, RhinoMath.ToRadians(0.2), 0.01, 100);
                curve.TryGetPolyline(out polyline);
            }
            if (polyline == null)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Curve could not be converted to polyline.");
                return;
            }

            List <string> edges = new List <string>();
            List <string> fills = new List <string>();

            if (!string.IsNullOrWhiteSpace(edge))
            {
                edges.Add(edge);
            }
            if (!string.IsNullOrWhiteSpace(fill))
            {
                fills.Add(fill);
            }

            GdiShapeGoo goo = new GdiShapeGoo(polyline, edges, fills)
            {
                DrawFillsBeforeEdges = true
            };

            access.SetData(0, goo);
        }
Esempio n. 30
0
        protected override void SolveInstance(IGH_DataAccess access)
        {
            string  text       = null;
            string  font       = null;
            Color   colour     = Color.Black;
            Point3d location   = Point3d.Origin;
            double  horizontal = 0.0;
            double  vertical   = 0.0;
            double  rotation   = 0.0;

            if (!access.GetData(0, ref text))
            {
                return;
            }
            if (!access.GetData(1, ref font))
            {
                return;
            }
            if (!access.GetData(2, ref location))
            {
                return;
            }
            if (!access.GetData(3, ref colour))
            {
                return;
            }
            if (!access.GetData(4, ref horizontal))
            {
                return;
            }
            if (!access.GetData(5, ref vertical))
            {
                return;
            }
            if (!access.GetData(6, ref rotation))
            {
                return;
            }

            Param_Number param = (Param_Number)Params.Input[6];

            if (!param.UseDegrees)
            {
                rotation = RhinoMath.ToDegrees(rotation);
            }

            GdiTextGoo goo = new GdiTextGoo(text, font, colour, location, horizontal, vertical, rotation);

            access.SetData(0, goo);
        }