/// <summary> /// This method is used to place an adaptive family which helps in debugging /// </summary> /// <param name="typeName"></param> /// <param name="p1"></param> /// <param name="p2"></param> /// <returns></returns> public static FamilyInstance PlaceAdaptiveFamilyInstance(string famAndTypeName, XYZ p1, XYZ p2) { //Get the symbol ElementParameterFilter filter = Filter.ParameterValueFilter(famAndTypeName, BuiltInParameter.SYMBOL_FAMILY_AND_TYPE_NAMES_PARAM); //Hardcoded until implements FamilySymbol markerSymbol = new FilteredElementCollector(PCFImport.doc).WherePasses(filter) .Cast <FamilySymbol>() .FirstOrDefault(); // Create a new instance of an adaptive component family FamilyInstance instance = AdaptiveComponentInstanceUtils.CreateAdaptiveComponentInstance(PCFImport.doc, markerSymbol); // Get the placement points of this instance IList <ElementId> placePointIds = new List <ElementId>(); placePointIds = AdaptiveComponentInstanceUtils.GetInstancePlacementPointElementRefIds(instance); // Set the position of each placement point ReferencePoint point1 = PCFImport.doc.GetElement(placePointIds[0]) as ReferencePoint; point1.Position = p1; ReferencePoint point2 = PCFImport.doc.GetElement(placePointIds[1]) as ReferencePoint; point2.Position = p2; return(instance); }
/// <summary> /// Sets the model that this object was instanced from /// </summary> public ModelInstance( Model source ) { m_Source = source; // Set up the animation layers if ( source.Animations == null ) { return; } m_Layers = new AnimationLayer[ ( int )ModelPart.NumParts ]; for ( int layerIndex = 0; layerIndex < ( int )ModelPart.NumParts; ++layerIndex ) { m_ReferencePoints[ layerIndex ] = new ReferencePoint( ( ModelPart )layerIndex ); ModelMesh partMesh = source.GetPartMesh( ( ModelPart )layerIndex ); if ( partMesh == null ) { continue; } if ( source.Animations != null ) { // TODO: This assigns the entire animation set to each layer, which isn't correct (although it'll work OK) m_Layers[ layerIndex ] = new AnimationLayer( source.Animations, ( ModelPart )layerIndex ); } } }
private bool IsPointOnCurve(PolyLine polyline, ReferencePoint point) { var coords = polyline.GetCoordinates(); for (int i = 0; i < coords.Count - 1; i++) { var start = coords[i]; var end = coords[i + 1]; var dir = end - start; var test = point.Position - start; var area = test.CrossProduct(dir); if (!area.IsZeroLength()) { continue; } var delta = Math.Abs(dir.GetLength() - test.GetLength() - (point.Position - end).GetLength()); if (delta > 1e-5) { continue; } return(true); } return(false); }
public void Process(DataTreeBranch bIn, DataTreeBranch currentBranch) { foreach (object o in bIn.Leaves) { ReferencePoint rp = o as ReferencePoint; if (rp != null) { //get the location of the point XYZ pos = rp.Position; FamilySymbol fs = InPortData[1].Object as FamilySymbol; FamilyInstance fi = dynElementSettings.SharedInstance.Doc.Document.FamilyCreate.NewFamilyInstance(pos, fs, Autodesk.Revit.DB.Structure.StructuralType.NonStructural); Elements.Append(fi); currentBranch.Leaves.Add(fi); } } foreach (DataTreeBranch b1 in bIn.Branches) { DataTreeBranch newBranch = new DataTreeBranch(); this.Tree.Trunk.Branches.Add(newBranch); Process(b1, newBranch); } }
/// <summary> /// Implement this method as an external command for Revit. /// </summary> /// <param name="commandData">An object that is passed to the external application /// which contains data related to the command, /// such as the application object and active view.</param> /// <param name="message">A message that can be set by the external application /// which will be displayed if a failure or cancellation is returned by /// the external command.</param> /// <param name="elements">A set of elements to which the external application /// can add elements that are to be highlighted in case of failure or cancellation.</param> /// <returns>Return the status of the external command. /// A result of Succeeded means that the API external method functioned as expected. /// Cancelled can be used to signify that the user cancelled the external operation /// at some point. Failure should be returned if the application is unable to proceed with /// the operation.</returns> public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { ExternalCommandData cdata = commandData; Autodesk.Revit.ApplicationServices.Application app = commandData.Application.Application; Document doc = commandData.Application.ActiveUIDocument.Document; XYZ xyz = new XYZ(); ReferenceArrayArray refArAr = new ReferenceArrayArray(); int x = 0; double z = 0; while (x < 800) { ReferencePointArray rpAr = new ReferencePointArray(); int y = 0; while (y < 800) { z = 50 * (Math.Cos((Math.PI / 180) * x) + Math.Cos((Math.PI / 180) * y)); xyz = app.Create.NewXYZ(x, y, z); ReferencePoint rp = doc.FamilyCreate.NewReferencePoint(xyz); rpAr.Append(rp); y = y + 40; } CurveByPoints curve = doc.FamilyCreate.NewCurveByPoints(rpAr); ReferenceArray refAr = new ReferenceArray(); refAr.Append(curve.GeometryCurve.Reference); refArAr.Append(refAr); x = x + 40; } Form form = doc.FamilyCreate.NewLoftForm(true, refArAr); return(Result.Succeeded); }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { Autodesk.Revit.ApplicationServices.Application app = commandData.Application.Application; Document doc = commandData.Application.ActiveUIDocument.Document; double yctr = 0; XYZ xyz = null; ReferencePoint rp = null; double power = 1.2; while (power < 1.5) { double xctr = 0; double zctr = 0; while (zctr < 100) { zctr = Math.Pow(xctr, power); xyz = app.Create.NewXYZ(xctr, yctr, zctr); rp = doc.FamilyCreate.NewReferencePoint(xyz); if (xctr > 0) { xyz = app.Create.NewXYZ(-xctr, yctr, zctr); rp = doc.FamilyCreate.NewReferencePoint(xyz); } xctr++; } power = power + 0.1; yctr = yctr + 50; zctr = 0; } return(Result.Succeeded); }
public void ByReferencePoints_Mutation() { ElementBinder.IsEnabled = false; var p1 = ReferencePoint.ByCoordinates(0, 0, 0); var p2 = ReferencePoint.ByCoordinates(1, 1, 1); var p3 = ReferencePoint.ByCoordinates(2, 2, 2); Assert.NotNull(p1); Assert.NotNull(p2); Assert.NotNull(p3); ElementBinder.IsEnabled = true; var curveByPoints = CurveByPoints.ByReferencePoints(new List <ReferencePoint> { p1, p2, p3 }.ToArray()); Assert.NotNull(curveByPoints); var curveRef = curveByPoints.ElementCurveReference; Assert.NotNull(curveRef); var p4 = ReferencePoint.ByCoordinates(3, 3, 3); curveByPoints = CurveByPoints.ByReferencePoints(new List <ReferencePoint> { p1, p2, p4 }.ToArray()); Assert.NotNull(curveByPoints); }
/// <summary> /// Implement this method as an external command for Revit. /// </summary> /// <param name="commandData">An object that is passed to the external application /// which contains data related to the command, /// such as the application object and active view.</param> /// <param name="message">A message that can be set by the external application /// which will be displayed if a failure or cancellation is returned by /// the external command.</param> /// <param name="elements">A set of elements to which the external application /// can add elements that are to be highlighted in case of failure or cancellation.</param> /// <returns>Return the status of the external command. /// A result of Succeeded means that the API external method functioned as expected. /// Cancelled can be used to signify that the user cancelled the external operation /// at some point. Failure should be returned if the application is unable to proceed with /// the operation.</returns> public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { Autodesk.Revit.ApplicationServices.Application app = commandData.Application.Application; Document doc = commandData.Application.ActiveUIDocument.Document; Transaction transaction = new Transaction(doc, "PointsParabola"); transaction.Start(); string filename = "sphere.csv"; string filepath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location); if (File.Exists(filepath + "\\" + filename)) { StreamReader readFile = new StreamReader(filepath + "\\" + filename); string line; while ((line = readFile.ReadLine()) != null) { string[] data = line.Split(','); XYZ xyz = new XYZ(Convert.ToDouble(data[0]), Convert.ToDouble(data[1]), Convert.ToDouble(data[2])); ReferencePoint rp = doc.FamilyCreate.NewReferencePoint(xyz); } } transaction.Commit(); return(Result.Succeeded); }
void CreateChainWithOneFixedEnd(ReferencePoint pt1, int numX, double springDampening, double springRestLength, double springConstant, double mass) { Particle p; XYZ partXYZ1 = pt1.Position; Particle fixedPart1 = particleSystem.makeParticleFromElementID(pt1.Id, mass, pt1.Position, true); // true means 'make fixed' XYZ partXYZ2 = partXYZ1 + new XYZ(10, 0, 0); //Line tempLine = this.UIDocument.Application.Application.Create.NewLineBound(partXYZ1, partXYZ2); XYZ vector = partXYZ2 - partXYZ1; XYZ step = vector.Divide(numX); for (int j = 0; j < numX; j++)//step along curve and evaluate at each step, making sure to thread in the existing fixed parts { //double curveParam = 0; XYZ pointOnLine; pointOnLine = partXYZ1 + step.Multiply(j); if (j == 0) // starting point { //curveParam = (double)j / numX; //pointOnLine = tempLine.Evaluate(curveParam, true); p = particleSystem.makeParticle(mass, pointOnLine, true); // make first particle fixed } else // middle points { //curveParam = (double)j / numX; //pointOnLine = tempLine.Evaluate(curveParam, true); p = particleSystem.makeParticle(mass, pointOnLine, false); // make a new particle along curve at j-th point on line particleSystem.makeSpring(particleSystem.getParticle((j - 1)), p, springRestLength, springConstant, springDampening); //make a new spring and connect it to the last-made point } } }
/// <summary> /// Implement this method as an external command for Revit. /// </summary> /// <param name="commandData">An object that is passed to the external application /// which contains data related to the command, /// such as the application object and active view.</param> /// <param name="message">A message that can be set by the external application /// which will be displayed if a failure or cancellation is returned by /// the external command.</param> /// <param name="elements">A set of elements to which the external application /// can add elements that are to be highlighted in case of failure or cancellation.</param> /// <returns>Return the status of the external command. /// A result of Succeeded means that the API external method functioned as expected. /// Cancelled can be used to signify that the user cancelled the external operation /// at some point. Failure should be returned if the application is unable to proceed with /// the operation.</returns> public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { Autodesk.Revit.ApplicationServices.Application app = commandData.Application.Application; Document doc = commandData.Application.ActiveUIDocument.Document; Transaction transaction = new Transaction(doc, "PointsFromExcel"); transaction.Start(); string excelFile = "helix.xlsx"; string filepath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location); Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application(); Workbook workbook = excelApp.Workbooks.Open(filepath + "\\" + excelFile, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); Worksheet sheet = (Worksheet)workbook.Sheets[1]; Range excelRange = sheet.UsedRange; object[,] valueArray = (object[, ])excelRange.get_Value(XlRangeValueDataType.xlRangeValueDefault); for (int i = 1; i <= excelRange.Rows.Count; i++) { XYZ xyz = new XYZ(Convert.ToDouble(valueArray[i, 1]), Convert.ToDouble(valueArray[i, 2]), Convert.ToDouble(valueArray[i, 3])); ReferencePoint rp = doc.FamilyCreate.NewReferencePoint(xyz); } workbook.Close(false, excelFile, null); transaction.Commit(); return(Result.Succeeded); }
/***************************************************/ /**** Constructors ****/ /***************************************************/ public LinearLayout(int numberOfPoints, Vector direction, double offset, ReferencePoint referencePoint) { NumberOfPoints = numberOfPoints; Direction = direction; Offset = offset; ReferencePoint = referencePoint; }
void CreateChainWithTwoFixedEnds(ReferencePoint pt1, ReferencePoint pt2, int numX, double springDampening, double springRestLength, double springConstant, double mass) { Particle p; Particle p2; XYZ partXYZ1 = pt1.Position; XYZ partXYZ2 = pt2.Position; XYZ lineVec = partXYZ2 - partXYZ1; double stepSize = lineVec.GetLength() / numX; for (int j = 0; j < numX; j++)//step along curve and evaluate at each step, making sure to thread in the existing fixed parts { //double curveParam = 0; XYZ pointOnLine; if (j == 0) // starting point { p = particleSystem.makeParticle(mass, partXYZ1, true); // make first particle fixed } else if (j > 0 && j < numX - 1) // middle points { pointOnLine = partXYZ1 + lineVec.Normalize() * (j * stepSize); p = particleSystem.makeParticle(mass, pointOnLine, false); // make a new particle along curve at j-th point on line p2 = particleSystem.getParticle(j - 1); particleSystem.makeSpring(p, p2, springRestLength, springConstant, springDampening); //make a new spring and connect it to the last-made point } else //last point - fixed { p = particleSystem.getParticle(j - 1); p2 = particleSystem.makeParticle(mass, partXYZ2, true); // make last particle fixed particleSystem.makeSpring(p, p2, springRestLength, springConstant, springDampening); //make a new spring and connect the j-th point to the fixed point } } }
public void CreateInRevitSelectInDynamoUndoInRevit() { //Create a reference point in Revit ElementId rpID; using (var trans = new Transaction(DocumentManager.Instance.CurrentUIDocument.Document, "CreateInRevit")) { trans.Start(); ReferencePoint rp = DocumentManager.Instance.CurrentUIDocument.Document.FamilyCreate.NewReferencePoint(new XYZ()); rpID = rp.Id; trans.Commit(); } //Select the reference point in Dynamo string dynFilePath = Path.Combine(_testPath, @".\ElementBinding\SelectInDynamo.dyn"); string testPath = Path.GetFullPath(dynFilePath); ViewModel.OpenCommand.Execute(testPath); var model = ViewModel.Model; var selNodes = model.AllNodes.Where(x => x is DSElementSelection); var selNode = selNodes.First() as DSElementSelection; selNode.SelectedElement = rpID; Assert.DoesNotThrow(() => ViewModel.Model.RunExpression()); //Undo the creation of a reference point in Revit Assert.Inconclusive("TO DO"); }
public static void CreateAdaptiveComponentFamily(XYZ[] pts, string fName) { FilteredElementCollector temc = new FilteredElementCollector(_doc); List <Element> guanPian = temc.OfClass(typeof(FamilySymbol)).ToElements() as List <Element>; FamilySymbol symbol = null; foreach (Element element in guanPian) { if (element.Name == fName) { symbol = element as FamilySymbol; } } //创建自适应族 using (Transaction tr = new Transaction(_doc)) { tr.Start("自适应族"); FamilyInstance instance = AdaptiveComponentInstanceUtils.CreateAdaptiveComponentInstance(_doc, symbol); //获取实例的放置点 IList <ElementId> placePointIds = new List <ElementId>(); placePointIds = AdaptiveComponentInstanceUtils.GetInstancePlacementPointElementRefIds(instance); //设置每个放置点的位置 for (int i = 0; i < placePointIds.Count; i++) { ReferencePoint point = _doc.GetElement(placePointIds[i]) as ReferencePoint; point.Position = pts[i]; } tr.Commit(); } }
public static ReferencePoint RequestReferencePointSelection(string message) { var doc = dynRevitSettings.Doc; ReferencePoint rp = null; Autodesk.Revit.UI.Selection.Selection choices = doc.Selection; choices.Elements.Clear(); dynSettings.Controller.DynamoViewModel.Log(message); //create some geometry options so that we computer references var opts = new Options { ComputeReferences = true, DetailLevel = ViewDetailLevel.Medium, IncludeNonVisibleObjects = false }; Reference pointRef = doc.Selection.PickObject(ObjectType.Element); if (pointRef != null) { rp = dynRevitSettings.Doc.Document.GetElement(pointRef) as ReferencePoint; } return(rp); }
protected override void Arrange() { _documentData = new DocumentData(); _graphicsMock = new Mock <IGraphics>(MockBehavior.Strict); _graphicsMock.Setup(x => x.MeasureString(It.IsAny <string>(), It.IsAny <XFont>(), It.IsAny <XStringFormat>())).Returns(new XSize { Height = 1000, Width = 1000 }); _renderDataMock = new Mock <IRenderData>(MockBehavior.Strict); _referencePoint = new ReferencePoint(); _referencePoint.ElementList.Add(new TextBox { Value = "Some text!" }); _renderDataMock = new Mock <IRenderData>(MockBehavior.Strict); _renderDataMock.Setup(x => x.ParentBounds).Returns(It.IsAny <XRect>()); _renderDataMock.Setup(x => x.Graphics).Returns(_graphicsMock.Object); _renderDataMock.Setup(x => x.Section).Returns(new Section()); _renderDataMock.Setup(x => x.DocumentData).Returns(_documentData); _renderDataMock.Setup(x => x.PageNumberInfo).Returns(new PageNumberInfo(1, 2)); _renderDataMock.Setup(x => x.DebugData).Returns((IDebugData)null); _renderDataMock.Setup(x => x.IncludeBackground).Returns(false); _renderDataMock.Setup(x => x.ElementBounds).Returns(It.IsAny <XRect>()); _renderDataMock.SetupSet(x => x.ElementBounds = It.IsAny <XRect>()); _renderDataMock.SetupGet(x => x.DocumentProperties).Returns(Mock.Of <DocumentProperties>()); }
/// <summary> /// Implement this method as an external command for Revit. /// </summary> /// <param name="commandData">An object that is passed to the external application /// which contains data related to the command, /// such as the application object and active view.</param> /// <param name="message">A message that can be set by the external application /// which will be displayed if a failure or cancellation is returned by /// the external command.</param> /// <param name="elements">A set of elements to which the external application /// can add elements that are to be highlighted in case of failure or cancellation.</param> /// <returns>Return the status of the external command. /// A result of Succeeded means that the API external method functioned as expected. /// Cancelled can be used to signify that the user cancelled the external operation /// at some point. Failure should be returned if the application is unable to proceed with /// the operation.</returns> public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { Autodesk.Revit.ApplicationServices.Application app = commandData.Application.Application; Document doc = commandData.Application.ActiveUIDocument.Document; Transaction transaction = new Transaction(doc, "CatenaryCurve"); transaction.Start(); for (double scalingFactor = 1; scalingFactor <= 2; scalingFactor = scalingFactor + 0.5) { ReferencePointArray rpArray = new ReferencePointArray(); for (double x = -5; x <= 5; x = x + 0.5) { double y = scalingFactor * Math.Cosh(x / scalingFactor); if (y < 50) { ReferencePoint rp = doc.FamilyCreate.NewReferencePoint(new XYZ(x, y, 0)); rpArray.Append(rp); } } CurveByPoints cbp = doc.FamilyCreate.NewCurveByPoints(rpArray); } transaction.Commit(); return(Result.Succeeded); }
public void CreateOrMoveAdaptiveComponent(Autodesk.Revit.DB.Document document, XYZ placementPoint, Autodesk.Revit.DB.FamilySymbol symbol = null, ElementId elementToMove = null) { Autodesk.Revit.DB.FamilyInstance instance = null; if (elementToMove == null) { // Create a new instance of an adaptive component family instance = AdaptiveComponentInstanceUtils.CreateAdaptiveComponentInstance(document, symbol); } else { instance = document.GetElement(elementToMove) as Autodesk.Revit.DB.FamilyInstance; } // Get the placement points of this instance IList <Autodesk.Revit.DB.ElementId> placePointIds = new List <Autodesk.Revit.DB.ElementId>(); placePointIds = AdaptiveComponentInstanceUtils.GetInstancePlacementPointElementRefIds(instance); // Set the position of each placement point foreach (Autodesk.Revit.DB.ElementId id in placePointIds) { ReferencePoint point = document.GetElement(id) as ReferencePoint; point.Position = placementPoint; } }
/// <summary> /// Implement this method as an external command for Revit. /// </summary> /// <param name="commandData">An object that is passed to the external application /// which contains data related to the command, /// such as the application object and active view.</param> /// <param name="message">A message that can be set by the external application /// which will be displayed if a failure or cancellation is returned by /// the external command.</param> /// <param name="elements">A set of elements to which the external application /// can add elements that are to be highlighted in case of failure or cancellation.</param> /// <returns>Return the status of the external command. /// A result of Succeeded means that the API external method functioned as expected. /// Cancelled can be used to signify that the user cancelled the external operation /// at some point. Failure should be returned if the application is unable to proceed with /// the operation.</returns> public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { Autodesk.Revit.ApplicationServices.Application app = commandData.Application.Application; Document doc = commandData.Application.ActiveUIDocument.Document; Transaction transaction = new Transaction(doc, "PointsParabola"); transaction.Start(); int pnt_ctr = 0; double xctr = 0; XYZ xyz = new XYZ(); ReferencePointArray rparray = new ReferencePointArray(); while (pnt_ctr < 500) { xyz = new XYZ(xctr, 0, (Math.Cos(xctr)) * 10); ReferencePoint rp = doc.FamilyCreate.NewReferencePoint(xyz); rparray.Append(rp); xctr = xctr + 0.1; pnt_ctr++; } CurveByPoints curve = doc.FamilyCreate.NewCurveByPoints(rparray); transaction.Commit(); return(Result.Succeeded); }
//点的内插 private XYZ Interpolation(FamilyInstance chordInstance, XYZ hangerRodDownPoint, ExternalCommandData commandData) { Document revitDoc = commandData.Application.ActiveUIDocument.Document; //取得文档 Application revitApp = commandData.Application.Application; //取得应用程序 UIDocument uiDoc = commandData.Application.ActiveUIDocument; //取得当前活动文档 IList <ElementId> chordPointIDs = AdaptiveComponentInstanceUtils.GetInstancePlacementPointElementRefIds(chordInstance); List <XYZ> chordPoints = new List <XYZ>(); foreach (ElementId elementId in chordPointIDs) { Element e = uiDoc.Document.GetElement(elementId); ReferencePoint referencePoint = e as ReferencePoint; chordPoints.Add(referencePoint.Position); } XYZ p1 = new XYZ(chordPoints[0].X, chordPoints[0].Y, 0); XYZ p2 = new XYZ(chordPoints[1].X, chordPoints[1].Y, 0); XYZ p3 = new XYZ(hangerRodDownPoint.X, hangerRodDownPoint.Y, 0); Line line = Line.CreateBound(chordPoints[0], chordPoints[1]); //三维线 Line line1 = Line.CreateBound(p1, p2); //投影线 double L = Line.CreateBound(p1, p3).Length; //到起点的距离 double ratio = L / line1.Length; XYZ UPPoint = line.Evaluate(ratio, true); return(UPPoint); }
/***************************************************/ /**** Public methods ****/ /***************************************************/ public static FamilyInstance AdaptiveComponent(Document document, FamilySymbol familySymbol, List <XYZ> points, RevitSettings settings = null) { if (document == null || familySymbol == null || points == null) { return(null); } settings = settings.DefaultIfNull(); FamilyInstance adaptiveComponent = AdaptiveComponentInstanceUtils.CreateAdaptiveComponentInstance(document, familySymbol); IList <ElementId> pointIds = AdaptiveComponentInstanceUtils.GetInstancePointElementRefIds(adaptiveComponent); if (pointIds.Count != points.Count) { pointIds = AdaptiveComponentInstanceUtils.GetInstancePlacementPointElementRefIds(adaptiveComponent); } if (pointIds.Count != points.Count) { BH.Engine.Reflection.Compute.RecordError($"An adaptive component could not be created based on the given ModelInstance because its definition requires different number of points than provided."); document.Delete(adaptiveComponent.Id); return(null); } for (int i = 0; i < pointIds.Count; i++) { ReferencePoint rp = (ReferencePoint)document.GetElement(pointIds[i]); Transform t = Transform.CreateTranslation(points[i]); rp.SetCoordinateSystem(t); } return(adaptiveComponent); }
public void CreateInDynamoModifyInRevitReRun() { //Create a reference point at (0.0, 0.0, 0.0); string dynFilePath = Path.Combine(workingDirectory, @".\ElementBinding\CreateOneReferencePoint.dyn"); string testPath = Path.GetFullPath(dynFilePath); ViewModel.OpenCommand.Execute(testPath); RunCurrentModel(); //Change the position of the reference point var points = GetAllReferencePointElements(true); Assert.AreEqual(1, points.Count); ReferencePoint pnt = points[0] as ReferencePoint; Assert.IsNotNull(pnt); using (var trans = new Transaction(DocumentManager.Instance.CurrentUIDocument.Document, "ModifyInRevit")) { trans.Start(); pnt.Position = new XYZ(10.0, 0.0, 0.0); trans.Commit(); } //Run the graph once again RunCurrentModel(); points = GetAllReferencePointElements(true); Assert.AreEqual(1, points.Count); pnt = points[0] as ReferencePoint; Assert.IsTrue(pnt.Position.IsAlmostEqualTo(new XYZ(0.0, 0.0, 0.0))); }
public override int GetHashCode() { unchecked { return((ReferencePoint.GetHashCode() * 397) ^ AngleInDegrees.GetHashCode()); } }
public void Process(DataTreeBranch bIn, DataTreeBranch currentBranch) { DataTree dt = InPortData[1].Object as DataTree; ReferencePoint attractor = dt.Trunk.Leaves[0] as ReferencePoint; //use each XYZ leaf on the input //to define a new origin foreach (object o in bIn.Leaves) { ReferencePoint rp = o as ReferencePoint; if (rp != null) { //get the distance betweent the points double dist = rp.Position.DistanceTo(attractor.Position); currentBranch.Leaves.Add(dist); } } foreach (DataTreeBranch b1 in bIn.Branches) { DataTreeBranch newBranch = new DataTreeBranch(); currentBranch.Branches.Add(newBranch); Process(b1, newBranch); } }
public async Task <IActionResult> Edit(int id, ReferencePointViewModel referencePointViewModel, string backlink) { ViewBag.BackLink = backlink; if (id != referencePointViewModel.Id) { return(NotFound()); } if (_context.ReferencePoint.Where(r => r.IndicatorId == referencePointViewModel.IndicatorId && r.Id != referencePointViewModel.Id).Count() > 0) { ModelState.AddModelError("IndicatorId", _sharedLocalizer["ErrorDublicateValue"]); } if (ModelState.IsValid) { try { ReferencePoint referencePoint = new ReferencePoint() { Id = referencePointViewModel.Id, IndicatorId = referencePointViewModel.IndicatorId, Min = referencePointViewModel.Min, Max = referencePointViewModel.Max }; ReferencePoint referencePoint_old = _context.ReferencePoint.AsNoTracking().FirstOrDefault(r => r.Id == referencePoint.Id); _context.Log.Add(new Log() { DateTime = DateTime.Now, Email = User.Identity.Name, Operation = "Редактирование Референтной точки", New = $"{referencePoint.Min}; {referencePoint.Max}", Old = $"{referencePoint_old.Min}; {referencePoint_old.Max}" }); _context.Update(referencePoint); await _context.SaveChangesAsync(); new IndicatorsController(_context, _sharedLocalizer).CalculateIndicatorsValues((int)referencePointViewModel.IndicatorId); } catch (DbUpdateConcurrencyException) { if (!ReferencePointExists(referencePointViewModel.Id)) { return(NotFound()); } else { throw; } } if (backlink.ToLower().Contains("referencepoint")) { return(Redirect(backlink)); } return(RedirectToAction("Index")); } ViewData["IndicatorId"] = new SelectList(_context.Indicator.OrderBy(g => g.NameCode), "Id", "NameCode", referencePointViewModel.IndicatorId); referencePointViewModel.Indicator = _context.Indicator.FirstOrDefault(i => i.Id == referencePointViewModel.IndicatorId); ViewData["BlocId"] = new SelectList(_context.Bloc.OrderBy(b => b.NameCode), "Id", "NameCode", referencePointViewModel.BlocId); ViewData["GroupId"] = new SelectList(_context.Group.OrderBy(g => g.NameCode).Where(g => g.BlocId == referencePointViewModel.BlocId), "Id", "NameCode", referencePointViewModel.GroupId); ViewData["IndicatorId"] = new SelectList(_context.Indicator.OrderBy(i => i.NameCode).Where(i => i.GroupId == referencePointViewModel.GroupId), "Id", "NameCode", referencePointViewModel.IndicatorId); return(View(referencePointViewModel)); }
ARReferencePoint CreateArReferencePoint(ReferencePoint referencePointData) { // Create a new GameObject for this point var parentTransform = m_SessionOrigin.trackablesParent; GameObject go; if (referencePointPrefab != null) { go = Instantiate(referencePointPrefab, parentTransform); } else { go = new GameObject(); go.transform.SetParent(parentTransform, false); go.layer = gameObject.layer; } go.name = string.Format("ReferencePoint {0}", referencePointData.Id); // Make sure it has an ARReferencePoint component. var referencePoint = go.GetComponent <ARReferencePoint>(); if (referencePoint == null) { referencePoint = go.AddComponent <ARReferencePoint>(); } m_ReferencePoints.Add(referencePointData.Id, referencePoint); referencePoint.sessionRelativeData = referencePointData; return(referencePoint); }
public static ReferencePoint RequestReferencePointSelection(string message) { UIDocument doc = DocumentManager.Instance.CurrentUIDocument; ReferencePoint rp = null; Autodesk.Revit.UI.Selection.Selection choices = doc.Selection; choices.Elements.Clear(); dynSettings.DynamoLogger.Log(message); //create some geometry options so that we computer references //var opts = new Options //{ // ComputeReferences = true, // DetailLevel = ViewDetailLevel.Medium, // IncludeNonVisibleObjects = false //}; Reference pointRef = doc.Selection.PickObject(ObjectType.Element); if (pointRef != null) { rp = DocumentManager.Instance.CurrentUIDocument.Document.GetElement(pointRef) as ReferencePoint; } return(rp); }
/// <summary> /// Implement this method as an external command for Revit. /// </summary> /// <param name="commandData">An object that is passed to the external application /// which contains data related to the command, /// such as the application object and active view.</param> /// <param name="message">A message that can be set by the external application /// which will be displayed if a failure or cancellation is returned by /// the external command.</param> /// <param name="elements">A set of elements to which the external application /// can add elements that are to be highlighted in case of failure or cancellation.</param> /// <returns>Return the status of the external command. /// A result of Succeeded means that the API external method functioned as expected. /// Cancelled can be used to signify that the user cancelled the external operation /// at some point. Failure should be returned if the application is unable to proceed with /// the operation.</returns> public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { Autodesk.Revit.ApplicationServices.Application app = commandData.Application.Application; Document doc = commandData.Application.ActiveUIDocument.Document; Transaction transaction = new Transaction(doc, "PointsOnCurve"); transaction.Start(); XYZ start = new XYZ(0, 0, 0); XYZ end = new XYZ(50, 50, 0); Autodesk.Revit.DB.Line line = Autodesk.Revit.DB.Line.CreateBound(start, end); Plane geometryPlane = Plane.CreateByNormalAndOrigin(XYZ.BasisZ, start); SketchPlane skplane = SketchPlane.Create(doc, geometryPlane); ModelCurve modelcurve = doc.FamilyCreate.NewModelCurve(line, skplane); for (double i = 0.1; i <= 1; i = i + 0.1) { PointLocationOnCurve locationOnCurve = new PointLocationOnCurve(PointOnCurveMeasurementType.NormalizedCurveParameter, i, PointOnCurveMeasureFrom.Beginning); PointOnEdge poe = app.Create.NewPointOnEdge(modelcurve.GeometryCurve.Reference, locationOnCurve); ReferencePoint rp2 = doc.FamilyCreate.NewReferencePoint(poe); } transaction.Commit(); return(Result.Succeeded); }
public override Value Evaluate(FSharpList <Value> args) { FSharpList <Value> pts = ((Value.List)args[0]).Item; FamilySymbol fs = (FamilySymbol)((Value.Container)args[1]).Item; FamilyInstance ac = null; //if the adapative component already exists, then move the points if (Elements.Any()) { //mutate Element e; //...we attempt to fetch it from the document... if (dynUtils.TryGetElement(this.Elements[0], typeof(FamilyInstance), out e)) { ac = e as FamilyInstance; ac.Symbol = fs; } else { //create ac = AdaptiveComponentInstanceUtils.CreateAdaptiveComponentInstance(dynRevitSettings.Doc.Document, fs); Elements[0] = ac.Id; } } else { //create ac = AdaptiveComponentInstanceUtils.CreateAdaptiveComponentInstance(dynRevitSettings.Doc.Document, fs); Elements.Add(ac.Id); } if (ac == null) { throw new Exception("An adaptive component could not be found or created."); } IList <ElementId> placePointIds = new List <ElementId>(); placePointIds = AdaptiveComponentInstanceUtils.GetInstancePlacementPointElementRefIds(ac); if (placePointIds.Count() != pts.Count()) { throw new Exception("The input list of points does not have the same number of values required by the adaptive component."); } // Set the position of each placement point int i = 0; foreach (ElementId id in placePointIds) { ReferencePoint point = dynRevitSettings.Doc.Document.GetElement(id) as ReferencePoint; XYZ pt = (XYZ)((Value.Container)pts.ElementAt(i)).Item; point.Position = pt; i++; } return(Value.NewContainer(ac)); }
/***************************************************/ /**** Constructors ****/ /***************************************************/ public MultiLinearLayout(int numberOfPoints, double parallelMinimumSpacing, double perpendicularMinimumSpacing, Vector direction, double offset, ReferencePoint referencePoint) { NumberOfPoints = numberOfPoints; ParallelMinimumSpacing = parallelMinimumSpacing; PerpendicularMinimumSpacing = perpendicularMinimumSpacing; Direction = direction; Offset = offset; ReferencePoint = referencePoint; }
public static bool ReferencePointsAreSame(ReferencePoint pnt1, ReferencePoint pnt2) { if (pnt1.Position.IsAlmostEqualTo(pnt2.Position, Tolerance)) { return(true); } return(false); }
/// <summary> /// Create reference points in a circular formation around the central body. Each point is linked to /// its neighbors and to the center /// </summary> void CreateRigidBodiesCircle(Bounds spriteBounds) { int numPoints = m_RadiusPoints; float width = spriteBounds.size.x * m_SpriteScale.x; float radius = width * 0.5f; m_CentralPoint = AddReferencePoint(Vector2.zero, width * m_SphereRadius, m_LockRotation); // Add nodes in a circle around the centre for(int loop = 0; loop < numPoints; loop++) { // Work out the correct offset to place the node float angle = ((Mathf.PI * 2)/numPoints) * loop; Vector2 offset = new Vector2(Mathf.Cos(angle), Mathf.Sin(angle)); offset *= radius; offset.x *= m_SoftBodyScale.x; offset.y *= m_SoftBodyScale.y; ReferencePoint referencePoint = AddReferencePoint(offset * (1.0f - (2 * m_SphereRadius)), width * m_SphereRadius, true); AttachPoint(referencePoint, m_CentralPoint); } if(m_AttachNeighbors) { for(int loop = 2; loop < m_ReferencePoints.Count; loop++) { AttachPoint(m_ReferencePoints[loop], m_ReferencePoints[loop - 1]); } AttachPoint(m_ReferencePoints[m_ReferencePoints.Count - 1], m_ReferencePoints[1]); } }
/// <summary> /// Creates the rigid bodies in a free configuration based around a central point /// </summary> /// <param name="">.</param> void CreateRigidBodiesFree(Bounds spriteBounds) { m_CentralPoint = AddReferencePoint(m_FreeModeBodyPositions[0], m_FreeModeBodyRadii[0], m_LockRotation); m_CentralPoint.SetKinematic(m_FreeModeBodyKinematic[0]); for(int loop = 1; loop < m_FreeModeBodyPositions.Count; loop++) { ReferencePoint referencePoint = AddReferencePoint(m_FreeModeBodyPositions[loop], m_FreeModeBodyRadii[loop], true); AttachPoint(referencePoint, m_CentralPoint); referencePoint.SetKinematic(m_FreeModeBodyKinematic[loop]); } if(m_AttachNeighbors) { for(int loop = 2; loop < m_ReferencePoints.Count; loop++) { AttachPoint(m_ReferencePoints[loop], m_ReferencePoints[loop - 1]); } AttachPoint(m_ReferencePoints[m_ReferencePoints.Count - 1], m_ReferencePoints[1]); } }
/// <summary> /// Create reference points in a cube formation with each point connected to the central /// point and to its neighbors /// </summary> void CreateRigidBodiesCube(Bounds meshBounds) { float width = meshBounds.size.x * m_SoftBodyScale.x * m_MeshScale.x; float height = meshBounds.size.y * m_SoftBodyScale.y * m_MeshScale.y; float depth = meshBounds.size.z * m_SoftBodyScale.z * m_MeshScale.z; float radius = meshBounds.size.y * m_SphereRadius * m_MeshScale.y; float offsetFactor = 0.5f - m_SphereRadius; m_CentralPoint = AddReferencePoint(m_SoftBodyPivotOffset, radius, false); ReferencePoint bottomLeftFarPoint = AddReferencePoint(new Vector3(-width * offsetFactor, -height * offsetFactor, -depth * offsetFactor) + m_SoftBodyOffset, radius, true); AttachPoint(bottomLeftFarPoint, m_CentralPoint); ReferencePoint bottomRightFarPoint = AddReferencePoint(new Vector3(width * offsetFactor, -height * offsetFactor, -depth * offsetFactor) + m_SoftBodyOffset, radius, true); AttachPoint(bottomRightFarPoint, m_CentralPoint); ReferencePoint topRightFarPoint = AddReferencePoint(new Vector3(width * offsetFactor, height * offsetFactor, -depth * offsetFactor) + m_SoftBodyOffset, radius, true); AttachPoint(topRightFarPoint, m_CentralPoint); ReferencePoint topLeftFarPoint = AddReferencePoint(new Vector3(-width * offsetFactor, height * offsetFactor, -depth * offsetFactor) + m_SoftBodyOffset, radius, true); AttachPoint(topLeftFarPoint, m_CentralPoint); ReferencePoint bottomLeftNearPoint = AddReferencePoint(new Vector3(-width * offsetFactor, -height * offsetFactor, depth * offsetFactor) + m_SoftBodyOffset, radius, true); AttachPoint(bottomLeftNearPoint, m_CentralPoint); ReferencePoint bottomRightNearPoint = AddReferencePoint(new Vector3(width * offsetFactor, -height * offsetFactor, depth * offsetFactor) + m_SoftBodyOffset, radius, true); AttachPoint(bottomRightNearPoint, m_CentralPoint); ReferencePoint topRightNearPoint = AddReferencePoint(new Vector3(width * offsetFactor, height * offsetFactor, depth * offsetFactor) + m_SoftBodyOffset, radius, true); AttachPoint(topRightNearPoint, m_CentralPoint); ReferencePoint topLeftNearPoint = AddReferencePoint(new Vector3(-width * offsetFactor, height * offsetFactor, depth * offsetFactor) + m_SoftBodyOffset, radius, true); AttachPoint(topLeftNearPoint, m_CentralPoint); if(m_AttachNeighbors) { AttachPoint(m_ReferencePoints[1], m_ReferencePoints[2]); AttachPoint(m_ReferencePoints[2], m_ReferencePoints[3]); AttachPoint(m_ReferencePoints[3], m_ReferencePoints[4]); AttachPoint(m_ReferencePoints[4], m_ReferencePoints[1]); AttachPoint(m_ReferencePoints[5], m_ReferencePoints[6]); AttachPoint(m_ReferencePoints[6], m_ReferencePoints[7]); AttachPoint(m_ReferencePoints[7], m_ReferencePoints[8]); AttachPoint(m_ReferencePoints[8], m_ReferencePoints[5]); AttachPoint(m_ReferencePoints[1], m_ReferencePoints[5]); AttachPoint(m_ReferencePoints[2], m_ReferencePoints[6]); AttachPoint(m_ReferencePoints[3], m_ReferencePoints[7]); AttachPoint(m_ReferencePoints[4], m_ReferencePoints[8]); } }
/// <summary> /// Add a reference point - essentially just a rigid body + circle collider - at the given /// position and with the given properties /// </summary> ReferencePoint AddReferencePoint(Vector3 position, float radius, bool addCollider) { position = Quaternion.Euler(m_SoftBodyRotation) * position; GameObject referencePointObject = new GameObject(); referencePointObject.name = this.name + " Ref Point " + m_ReferencePoints.Count.ToString(); referencePointObject.transform.parent = m_ReferencePointParent.transform; referencePointObject.transform.position = m_Transform.TransformPoint(position); referencePointObject.layer = gameObject.layer; referencePointObject.tag = gameObject.tag; JellyMeshReferencePoint refPointBehaviour = referencePointObject.AddComponent<JellyMeshReferencePoint>(); refPointBehaviour.ParentJellyMesh = this.gameObject; refPointBehaviour.Index = m_ReferencePoints.Count; ReferencePoint referencePoint = null; if(m_2DMode) { if(addCollider) { CircleCollider2D circleCollider = referencePointObject.AddComponent<CircleCollider2D>(); circleCollider.radius = radius; circleCollider.sharedMaterial = m_PhysicsMaterial2D; } Rigidbody2D newRigidBody = referencePointObject.AddComponent<Rigidbody2D>(); newRigidBody.fixedAngle = true; referencePoint = new ReferencePoint(newRigidBody); } else { if(addCollider) { SphereCollider circleCollider = referencePointObject.AddComponent<SphereCollider>(); circleCollider.radius = radius; circleCollider.sharedMaterial = m_PhysicsMaterial; } Rigidbody newRigidBody = referencePointObject.AddComponent<Rigidbody>(); // Fix the body to the 2D plane RigidbodyConstraints constraints = newRigidBody.constraints; constraints |= RigidbodyConstraints.FreezeRotationX; constraints |= RigidbodyConstraints.FreezeRotationY; constraints |= RigidbodyConstraints.FreezeRotationZ; newRigidBody.constraints = constraints; referencePoint = new ReferencePoint(newRigidBody); } m_ReferencePoints.Add(referencePoint); return referencePoint; }
/// <summary> /// Create reference points in a triangle formation. Each point is connected to the central point /// and to its neighbors /// </summary> void CreateRigidBodiesTriangle(Bounds meshBounds) { float width = meshBounds.size.x * m_SoftBodyScale.x * m_MeshScale.x; float height = meshBounds.size.y * m_SoftBodyScale.y * m_MeshScale.y; float radius = meshBounds.size.y * m_SphereRadius * m_MeshScale.y; float offsetFactor = 0.5f - m_SphereRadius; m_CentralPoint = AddReferencePoint(m_SoftBodyPivotOffset, radius, false); ReferencePoint bottomLeftPoint = AddReferencePoint(new Vector3(-width * offsetFactor, -height * offsetFactor) + m_SoftBodyOffset, radius, true); AttachPoint(bottomLeftPoint, m_CentralPoint); ReferencePoint bottomRightPoint = AddReferencePoint(new Vector3(width * offsetFactor, -height * offsetFactor) + m_SoftBodyOffset, radius, true); AttachPoint(bottomRightPoint, m_CentralPoint); ReferencePoint topCentrePoint = AddReferencePoint(new Vector3(0.0f, height * offsetFactor) + m_SoftBodyOffset, radius, true); AttachPoint(topCentrePoint, m_CentralPoint); if(m_AttachNeighbors) { AttachPoint(m_ReferencePoints[1], m_ReferencePoints[2]); AttachPoint(m_ReferencePoints[2], m_ReferencePoints[3]); AttachPoint(m_ReferencePoints[3], m_ReferencePoints[1]); } }
/// <summary> /// Create reference points in a sphere formation. Each point is connected to the central point /// and to its neighbors /// </summary> void CreateRigidBodiesSphere(Bounds meshBounds) { float width = meshBounds.size.x * m_MeshScale.x; float radius = width * 0.5f; m_CentralPoint = AddReferencePoint(m_SoftBodyPivotOffset, width * m_SphereRadius, false); int latitudes = m_RadiusPoints; int longitudes = m_RadiusPoints; float latitudeIncrement = 360.0f / latitudes; float longitudeIncrement = 180.0f / longitudes; int lattitudeIndex = 0; int maxLongitudes = 0; for (float u = 0; u <= 360.0f; u += latitudeIncrement) { ReferencePoint previousPoint = null; int longitudeIndex = 0; for (float t = 0; t <= 180.0f; t += longitudeIncrement) { float rad = radius; float x = (float) (rad * Mathf.Sin(Mathf.Deg2Rad * t) * Mathf.Sin(Mathf.Deg2Rad * u)) * m_SoftBodyScale.x; float y = (float) (rad * Mathf.Cos(Mathf.Deg2Rad * t)) * m_SoftBodyScale.y; float z = (float) (rad * Mathf.Sin(Mathf.Deg2Rad * t) * Mathf.Cos(Mathf.Deg2Rad * u)) * m_SoftBodyScale.z; Vector3 bodyPosition = new Vector3(x, y, z) * (1.0f - (2 * m_SphereRadius)); bodyPosition += m_SoftBodyOffset; ReferencePoint referencePoint = AddReferencePoint(bodyPosition, width * m_SphereRadius, true); AttachPoint(referencePoint, m_CentralPoint); if(m_AttachNeighbors) { // Attach points horizontally if(previousPoint != null) { AttachPoint(previousPoint, referencePoint); } if(lattitudeIndex > 0) { ReferencePoint prevVerticalPoint = m_ReferencePoints[m_ReferencePoints.Count - maxLongitudes - 1]; AttachPoint(prevVerticalPoint, referencePoint); } } previousPoint = referencePoint; longitudeIndex++; maxLongitudes = Mathf.Max(longitudeIndex, maxLongitudes); } lattitudeIndex++; } }
void CreateChainWithOneFixedEnd(ReferencePoint pt1, int numX, double springDampening, double springRestLength, double springConstant, double mass) { XYZ partXYZ1 = pt1.Position; Particle fixedPart1 = ParticleSystem.makeParticleFromElementID(pt1.Id, mass, pt1.Position, true); // true means 'make fixed' XYZ partXYZ2 = partXYZ1 + new XYZ(10, 0, 0); //Line tempLine = this.UIDocument.Application.Application.Create.NewLineBound(partXYZ1, partXYZ2); XYZ vector = partXYZ2 - partXYZ1; XYZ step = vector.Divide(numX); for (int j = 0; j < numX; j++)//step along curve and evaluate at each step, making sure to thread in the existing fixed parts { //double curveParam = 0; XYZ pointOnLine = partXYZ1 + step.Multiply(j); Particle p; if (j == 0) // starting point { //curveParam = (double)j / numX; //pointOnLine = tempLine.Evaluate(curveParam, true); p = ParticleSystem.makeParticle(mass, pointOnLine, true); // make first particle fixed } else // middle points { //curveParam = (double)j / numX; //pointOnLine = tempLine.Evaluate(curveParam, true); p = ParticleSystem.makeParticle(mass, pointOnLine, false); // make a new particle along curve at j-th point on line ParticleSystem.makeSpring(ParticleSystem.getParticle((j - 1)), p, springRestLength, springConstant, springDampening);//make a new spring and connect it to the last-made point } } }
void CreateChainWithTwoFixedEnds(ReferencePoint pt1, ReferencePoint pt2, int numX, double springDampening, double springRestLength, double springConstant, double mass) { XYZ partXYZ1 = pt1.Position; XYZ partXYZ2 = pt2.Position; XYZ lineVec = partXYZ2 - partXYZ1; double stepSize = lineVec.GetLength() / numX; for (int j = 0; j < numX; j++)//step along curve and evaluate at each step, making sure to thread in the existing fixed parts { //double curveParam = 0; Particle p; if (j == 0) // starting point { p = ParticleSystem.makeParticle(mass, partXYZ1, true); // make first particle fixed } else { Particle p2; if(j > 0 && j < numX-1) // middle points { XYZ pointOnLine = partXYZ1 + lineVec.Normalize() * (j * stepSize); p = ParticleSystem.makeParticle(mass, pointOnLine, false); // make a new particle along curve at j-th point on line p2 = ParticleSystem.getParticle(j - 1); ParticleSystem.makeSpring(p, p2, springRestLength, springConstant, springDampening);//make a new spring and connect it to the last-made point } else //last point - fixed { p = ParticleSystem.getParticle(j - 1); p2 = ParticleSystem.makeParticle(mass, partXYZ2, true); // make last particle fixed ParticleSystem.makeSpring(p, p2, springRestLength, springConstant, springDampening);//make a new spring and connect the j-th point to the fixed point } } } }
public override void Draw() { if (rightHandPt == null) { //create a reference point to track the right hand rightHandPt = dynElementSettings.SharedInstance.Doc.Document.FamilyCreate.NewReferencePoint(rightHandLoc); System.Windows.Point relativePoint = rightHandEllipse.TransformToAncestor(dynElementSettings.SharedInstance.Bench.workBench) .Transform(new System.Windows.Point(0, 0)); Canvas.SetLeft(rightHandEllipse, relativePoint.X); Canvas.SetTop(rightHandEllipse, relativePoint.Y); //add the right hand point at the base of the tree this.Tree.Trunk.Leaves.Add(rightHandPt); } if (CheckInputs()) { double xScale = Convert.ToDouble(InPortData[1].Object); double yScale = Convert.ToDouble(InPortData[2].Object); double zScale = Convert.ToDouble(InPortData[3].Object); //update the image image1.Source = nui.DepthStream.GetNextFrame(0).ToBitmapSource(); //get skeletonData SkeletonFrame allSkeletons = nui.SkeletonEngine.GetNextFrame(0); if (allSkeletons != null) { //get the first tracked skeleton SkeletonData skeleton = (from s in allSkeletons.Skeletons where s.TrackingState == SkeletonTrackingState.Tracked select s).FirstOrDefault(); if (skeleton != null) { Joint HandRight = skeleton.Joints[JointID.HandRight]; rightHandLoc = new XYZ(HandRight.Position.X * xScale, HandRight.Position.Z*zScale, HandRight.Position.Y*yScale); SetEllipsePosition(rightHandEllipse, HandRight); XYZ vec = rightHandLoc - rightHandPt.Position; Debug.WriteLine(vec.ToString()); //move the reference point dynElementSettings.SharedInstance.Doc.Document.Move(rightHandPt, vec); dynElementSettings.SharedInstance.Doc.RefreshActiveView(); } } } }
/// <summary> /// Create reference points in a diamond grid formation around the central body. Each point is linked to /// its neighbors /// </summary> void CreateRigidBodiesGrid(Bounds spriteBounds) { float radius = spriteBounds.size.x * m_SphereRadius * m_SpriteScale.x; float width = (spriteBounds.size.x * m_SoftBodyScale.x * m_SpriteScale.x) - (m_SphereRadius * 4); float height = (spriteBounds.size.y * m_SoftBodyScale.y * m_SpriteScale.y) - (m_SphereRadius * 4); int columns = m_GridColumns; int rows = m_GridRows; columns = Mathf.Max(1, columns); rows = Mathf.Max(1, rows); for(int y = 0; y < rows; y++) { for(int x = 0; x < columns; x++) { if(y % 2 != 0 && x == columns - 1) { Rigidbody2D dummyBody = null; ReferencePoint dummyPoint = new ReferencePoint(dummyBody); m_ReferencePoints.Add(dummyPoint); } else { Vector2 position; position.x = (-width * 0.5f) + ((width/(float)(columns - 1)) * x); if(y % 2 != 0) { position.x += ((width/(float)(columns - 1)) * 0.5f); } position.y = (-height * 0.5f) + ((height/(float)(rows - 1)) * y); ReferencePoint refPoint = AddReferencePoint(position, radius, true); if(x == columns/2 && y == rows/2) { m_CentralPoint = refPoint; } } } } for(int y = 0; y < rows - 1; y++) { for(int x = 0; x < columns; x++) { int thisPoint = (y * columns) + x; int nextPoint = ((y + 1) * columns) + x; if(!m_ReferencePoints[thisPoint].IsDummy && !m_ReferencePoints[nextPoint].IsDummy) { AttachPoint(m_ReferencePoints[thisPoint], m_ReferencePoints[nextPoint]); } } } for(int y = 0; y < rows - 1; y++) { for(int x = 1; x < columns - 1; x++) { if(y % 2 == 0) { int thisPoint = (y * columns) + x; int nextPoint = ((y + 1) * columns) + (x - 1); if(!m_ReferencePoints[thisPoint].IsDummy && !m_ReferencePoints[nextPoint].IsDummy) { AttachPoint(m_ReferencePoints[thisPoint], m_ReferencePoints[nextPoint]); } } } } for(int y = 0; y < rows - 1; y++) { for(int x = 0; x < columns - 1; x++) { if(y % 2 != 0) { int thisPoint = (y * columns) + x; int nextPoint = ((y + 1) * columns) + (x + 1); if(!m_ReferencePoints[thisPoint].IsDummy && !m_ReferencePoints[nextPoint].IsDummy) { AttachPoint(m_ReferencePoints[thisPoint], m_ReferencePoints[nextPoint]); } } } } for(int y = 0; y < rows - 1; y++) { if(y % 2 == 0) { int x = columns - 1; int thisPoint = (y * columns) + x; int nextPoint = ((y + 1) * columns) + (x - 1); if(!m_ReferencePoints[thisPoint].IsDummy && !m_ReferencePoints[nextPoint].IsDummy) { AttachPoint(m_ReferencePoints[thisPoint], m_ReferencePoints[nextPoint]); } } } }
/// <summary> /// Add a reference point - essentially just a rigid body + circle collider - at the given /// position and with the given properties /// </summary> ReferencePoint AddReferencePoint(Vector3 position, float radius, bool lockRotation) { GameObject referencePointObject = new GameObject(); referencePointObject.name = this.name + " Ref Point " + m_ReferencePoints.Count.ToString(); referencePointObject.transform.parent = m_ReferencePointParent.transform; referencePointObject.transform.position = this.transform.TransformPoint(position); referencePointObject.layer = gameObject.layer; JellySpriteReferencePoint refPointBehaviour = referencePointObject.AddComponent<JellySpriteReferencePoint>(); refPointBehaviour.ParentJellySprite = this.gameObject; refPointBehaviour.Index = m_ReferencePoints.Count; ReferencePoint referencePoint = null; if(m_2DMode) { CircleCollider2D circleCollider = referencePointObject.AddComponent<CircleCollider2D>(); circleCollider.radius = radius; circleCollider.sharedMaterial = m_PhysicsMaterial2D; Rigidbody2D newRigidBody = referencePointObject.AddComponent<Rigidbody2D>(); newRigidBody.fixedAngle = lockRotation; referencePoint = new ReferencePoint(newRigidBody); } else { SphereCollider circleCollider = referencePointObject.AddComponent<SphereCollider>(); circleCollider.radius = radius; circleCollider.sharedMaterial = m_PhysicsMaterial; Rigidbody newRigidBody = referencePointObject.AddComponent<Rigidbody>(); // Fix the body to the 2D plane RigidbodyConstraints constraints = newRigidBody.constraints; constraints |= RigidbodyConstraints.FreezePositionZ; constraints |= RigidbodyConstraints.FreezeRotationX; constraints |= RigidbodyConstraints.FreezeRotationY; // Prevent rotation unless desired constraints |= RigidbodyConstraints.FreezeRotationX; constraints |= RigidbodyConstraints.FreezeRotationY; if(lockRotation) { constraints |= RigidbodyConstraints.FreezeRotationZ; } newRigidBody.constraints = constraints; referencePoint = new ReferencePoint(newRigidBody); } m_ReferencePoints.Add(referencePoint); return referencePoint; }
// Use this for initialization void Start() { poiObjects = new ArrayList(); dataSE = referenceSE.GetComponent<ReferencePoint>(); dataNW = referenceNW.GetComponent<ReferencePoint>(); dataSW = referenceSW.GetComponent<ReferencePoint>(); DetermineXScale(); DetermineYScale(); lastUpdate = Time.timeSinceLevelLoad; StartCoroutine(DownloadFeed()); }
private void Stream( ArrayList data, ReferencePoint refPoint ) { data.Add( new Snoop.Data.ClassSeparator( typeof( ReferencePoint ) ) ); data.Add( new Snoop.Data.Object( "Coord plane ref XY", refPoint.GetCoordinatePlaneReferenceXY() ) ); data.Add( new Snoop.Data.Object( "Coord plane ref XZ", refPoint.GetCoordinatePlaneReferenceXZ() ) ); data.Add( new Snoop.Data.Object( "Coord plane ref YZ", refPoint.GetCoordinatePlaneReferenceYZ() ) ); data.Add( new Snoop.Data.String( "Coord plane visibility", refPoint.CoordinatePlaneVisibility.ToString() ) ); data.Add( new Snoop.Data.Object( "Coord system", refPoint.GetCoordinateSystem() ) ); data.Add( new Snoop.Data.Enumerable( "Interpolating curves", refPoint.GetInterpolatingCurves() ) ); data.Add( new Snoop.Data.Xyz( "Position", refPoint.Position ) ); data.Add( new Snoop.Data.Object( "Reference", refPoint.GetPointElementReference() ) ); //data.Add(new Snoop.Data.Double("Size", refPoint.Size)); data.Add( new Snoop.Data.Bool( "Visible", refPoint.Visible ) ); }
/// <summary> /// Create reference points in a triangle formation. Each point is connected to the central point /// and to its neighbors /// </summary> void CreateRigidBodiesTriangle(Bounds spriteBounds) { float width = spriteBounds.size.x * m_SoftBodyScale.x * m_SpriteScale.x; float height = spriteBounds.size.y * m_SoftBodyScale.y * m_SpriteScale.y; float radius = spriteBounds.size.y * m_SphereRadius * m_SpriteScale.y; float offsetFactor = 0.5f - m_SphereRadius; m_CentralPoint = AddReferencePoint(Vector2.zero, radius, m_LockRotation); ReferencePoint bottomLeftPoint = AddReferencePoint(new Vector2(-width * offsetFactor, -height * offsetFactor), radius, true); AttachPoint(bottomLeftPoint, m_CentralPoint); ReferencePoint bottomRightPoint = AddReferencePoint(new Vector2(width * offsetFactor, -height * offsetFactor), radius, true); AttachPoint(bottomRightPoint, m_CentralPoint); ReferencePoint topCentrePoint = AddReferencePoint(new Vector2(0.0f, height * offsetFactor), radius, true); AttachPoint(topCentrePoint, m_CentralPoint); if(m_AttachNeighbors) { AttachPoint(m_ReferencePoints[1], m_ReferencePoints[2]); AttachPoint(m_ReferencePoints[2], m_ReferencePoints[3]); AttachPoint(m_ReferencePoints[3], m_ReferencePoints[1]); } }
// geometric test, fairly expensive. public ReferencePoint FindRefPointWithCoincidentXYZ(ReferencePoint rp) { Element el; ReferencePoint rp2; foreach (ElementId id in this.Elements) // compare to inputed points { dynUtils.TryGetElement(id, out el); rp2 = el as ReferencePoint; if (rp != null && rp2 != null && rp.Position.IsAlmostEqualTo(rp2.Position))// note this is not gauranteed to be unique. there may be mulitple coincident refpoints and this utill will only return the first found { return rp2; // found a match } } return null; }
/// <summary> /// Attach two reference points together using a spring joint /// </summary> void AttachPoint(ReferencePoint point1, ReferencePoint point2) { if(m_2DMode) { SpringJoint2D joint = point1.Body2D.gameObject.AddComponent<SpringJoint2D>(); joint.connectedBody = point2.Body2D; joint.connectedAnchor = point1.Body2D.transform.localPosition - point2.Body2D.transform.localPosition; joint.distance = 0.0f; joint.collideConnected = m_CollideConnected; joint.frequency = m_Stiffness; joint.dampingRatio = m_DampingRatio; } else { SpringJoint joint = point1.Body3D.gameObject.AddComponent<SpringJoint>(); joint.connectedBody = point2.Body3D; joint.connectedAnchor = point1.Body3D.transform.localPosition - point2.Body3D.transform.localPosition; joint.minDistance = 0.0f; joint.maxDistance = 0.0f; joint.spring = m_Stiffness; joint.damper = m_DampingRatio; } }
void CreateChainWithTwoFixedEnds(ReferencePoint pt1, ReferencePoint pt2, int numX, double springDampening, double springRestLength, double springConstant, double mass) { Particle p; Particle p2; XYZ partXYZ1 = pt1.Position; Particle fixedPart1 = particleSystem.makeParticleFromElementID(pt1.Id, mass, pt1.Position, true); // true means 'make fixed' XYZ partXYZ2 = pt2.Position; Line tempLine = this.UIDocument.Application.Application.Create.NewLineBound(partXYZ1, partXYZ2); for (int j = 0; j < numX; j++)//step along curve and evaluate at each step, making sure to thread in the existing fixed parts { double curveParam = 0; XYZ pointOnLine; if (j == 0) // starting point { curveParam = (double)j / numX; pointOnLine = tempLine.Evaluate(curveParam, true); p = particleSystem.makeParticle(mass, pointOnLine, true); // make first particle fixed } else // middle points { curveParam = (double)j / numX; pointOnLine = tempLine.Evaluate(curveParam, true); p = particleSystem.makeParticle(mass, pointOnLine, false); // make a new particle along curve at j-th point on line particleSystem.makeSpring(particleSystem.getParticle((j - 1)), p, springRestLength, springConstant, springDampening);//make a new spring and connect it to the last-made point } if (j == numX - 1) //last free point, connect with fixed end point { curveParam = (double)(j + 1) / numX; // last point pointOnLine = tempLine.Evaluate(curveParam, true); p2 = particleSystem.makeParticle(mass, pointOnLine, true); // make last particle fixed particleSystem.makeSpring(p, p2, springRestLength, springConstant, springDampening);//make a new spring and connect the j-th point to the fixed point } } }