public void boardCanvas_MouseDown(object sender, MouseButtonEventArgs e) { boardCanvas.CaptureMouse(); sP = e.GetPosition(boardCanvas); newAtr.Color = (Color)colorStroke.SelectedColor; newAtr.Height = newAtr.Width = slider.Value; boardCanvas.DefaultDrawingAttributes = newAtr; if (tempTool == pencilImage.Name || tempTool == eraserImage.Name || tempTool == circleImage.Name || tempTool == rectangleImage.Name) { if (tempTool == circleImage.Name) { ellipse = new Ellipse(); } else if (tempTool == rectangleImage.Name) { rect = new Rectangle(); } } else if (tempTool == lineImage.Name) { line_C = new Line(); } else if (tempTool == textBoxImage.Name) { tB = new TextBox(); } //eP = new Point(0, 0); }
/// <summary>Constructs a new event of the specified type, originating from the specified line. /// </summary> /// <remarks>Constructs a new event of the specified type, originating from the specified line. /// </remarks> /// <param name="line">the source of this event</param> /// <param name="type">the event type (<code>OPEN</code>, <code>CLOSE</code>, <code>START</code>, or <code>STOP</code>) /// </param> /// <param name="position"> /// the number of sample frames that the line had already processed when the event occurred, /// or /// <see cref="AudioSystem.NOT_SPECIFIED">AudioSystem.NOT_SPECIFIED</see> /// </param> /// <exception cref="System.ArgumentException"> /// if <code>line</code> is /// <code>null</code>. /// </exception> public LineEvent(Line line, LineEvent.Type type, long position) : base(line) { // INSTANCE VARIABLES this.type = type; this.position = position; }
public void CreateALine() { // Create a Line Line redLine = new Line(); redLine.X1 = 50; redLine.Y1 = 50; redLine.X2 = 200; redLine.Y2 = 200; // Create a red Brush SolidColorBrush redBrush = new SolidColorBrush(); redBrush.Color = Colors.Red; // Set Line's width and color redLine.StrokeThickness = 4; redLine.Stroke = redBrush; // Add line to the Grid. LayoutRoot.Children.Add(redLine); }
public void Setup() { m_OtherDirection = Constants.LineDirection.Reverse; m_OtherLine = new Line(2, 100.0, 100.0, 600.0, 600.0); m_From = new Line(0, 10.0, 10.0, 60.0, 60.0); m_FromDirection = Constants.LineDirection.Forward; m_To = new Line(1, -10.0, -10.0, -60.0, -60.0); m_ToDirection = Constants.LineDirection.Forward; m_Sut = new CostForLineSwitchCalculator(m_From, m_FromDirection, m_To, m_ToDirection); m_Sut.Calculate(); }
public MainWindow() { InitializeComponent(); //int highestPrice = 65; //List<int> vals = new List<int>() { 10, 20, 30, 40, 50 }; //int min = vals.Min(); //int max = vals.Max(); //max = highestPrice > max ? highestPrice : max; //double range = max - min; Color d = new Color() { ScA = 1, ScR = .5F, ScG = .5F, ScB = .5F }; var line = new Line() { X1 = 0, Y1 = 0, X2 = canvas.Width, Y2 = 0, Stroke = new SolidColorBrush(d), StrokeThickness = 2.0 }; line = new Line() { X1 = 0, Y1 = 0, X2 = canvas.Width, Y2 = 10, Stroke = new SolidColorBrush(d), StrokeThickness = 1.0 }; canvas.Children.Add(line); line = new Line() { X1 = canvas.Width, Y1 = 10, X2 = 0, Y2 = 20, Stroke = new SolidColorBrush(d), StrokeThickness = 1.0 }; canvas.Children.Add(line); //foreach (int val in vals) //{ // double percent = 1.0 - ((val - min) / range); // 0 is at the top, so invert it by doing 1.0 - xxx // double y = percent * canvas.Height; // // Draw line in a shade of blue/green // c = new Color() { ScA = 1, ScR = 0, ScG = 0.5f, ScB = (float)percent }; // line = new Line() { X1 = 0, Y1 = y, X2 = canvas.Width, Y2 = y, Stroke = new SolidColorBrush(c), StrokeThickness = 2.0 }; // canvas.Children.Add(line); //} }
/// <summary> /// Add line to Log /// </summary> /// <param name="text"></param> /// <param name="file"></param> /// <param name="member"></param> /// <param name="lineNumber"></param> public static void Log(string text, LogLineType type = LogLineType.Notification, [CallerFilePath] string filename = "", [CallerMemberName] string member = "", [CallerLineNumber] int lineNumber = 0) { try { string[] lines = text.Split(new string[] { "\r\n", "\n", Environment.NewLine }, StringSplitOptions.None); foreach (var line in lines) { var queueLine = new Line(); queueLine.Text = line; queueLine.Type = type; queueLine.Timestamp = DateTime.Now; var assembly = Assembly.GetCallingAssembly(); queueLine.Assembly = assembly.FullName; queueLine.Filename = filename; queueLine.Member = member; queueLine.LineNumber = lineNumber; logQueue.AddLineToQueue(queueLine); Console.WriteLine(line); } } catch (Exception ex) { } }
public static void CreateEdge(DrawingState state) { if (state.firstCircle == null || state.secondCircle == null) return; if (!state.controller.ContainsEdge(state.firstCircle, state.secondCircle) && state.firstCircle != state.secondCircle) { Line line = new Line() { X1 = state.firstCircle.Position.X, Y1 = state.firstCircle.Position.Y, X2 = state.secondCircle.Position.X, Y2 = state.secondCircle.Position.Y }; state.controller.AddEdge(line, state.firstCircle, state.secondCircle); line.Stroke = System.Windows.Media.Brushes.LightSteelBlue; line.StrokeThickness = 2; state.canvas.Children.Add(line); line.MouseDown += (object a, MouseButtonEventArgs b) => { if (state.currentTool == DrawingState.Tool.REMOVE_EDGE) { state.controller.RemoveEdge(a as Line, state.mainWindow); } }; } state.firstCircle = null; state.secondCircle = null; }
public void Setup() { m_StartPoint = new Point(-10.0, -10.0); m_EndPoint = new Point(10.0, 10.0); m_LineDirection = Constants.LineDirection.Forward; m_Line = new Line(m_StartPoint, m_EndPoint); m_WindowsStartPoint = new System.Windows.Point(100.0, 200.0); m_WindowsEndPoint = new System.Windows.Point(300.0, 400.0); m_GeometryPointToWindowsPointConverter = Substitute.For <IGeometryPointToWindowsPointConverter>(); m_GeometryPointToWindowsPointConverter.Point.Returns(m_WindowsStartPoint, m_WindowsEndPoint); m_Sut = new LineToWindowPointsConverter(m_GeometryPointToWindowsPointConverter) { Line = m_Line }; m_Sut.Line = m_Line; m_Sut.LineDirection = m_LineDirection; m_Sut.Convert(); }
public void OnJoin(Line line) { if (line.PrefixIsSelf()) Channels.Add(line.Target, new Channel(line.Target)); line.GetChannel().Users.Add(line.Prefix.Nickname, new User(line.Prefix)); }
public void OnPart(Line line) { line.GetChannel().Users.Remove(line.Prefix.Nickname); if (line.PrefixIsSelf()) Channels.Remove(line.Target); }
public override void OnTick() { if (!Manager.IsInGame) return; var greenCircle = new Circle(CIRCLE_RADIUS, Color.FromArgb(0x8f, 0, 0xff, 0), Color.FromArgb(0x8f, 0, 0xff, 0)); var redCircle = new Circle(CIRCLE_RADIUS, Color.FromArgb(0x8f, 0xff, 0, 0), Color.FromArgb(0x8f, 0xff, 0, 0)); var blueCircle = new Circle(CIRCLE_RADIUS, Color.Black, Color.FromArgb(0x8f, 0, 0, 0xff), isFilled: false); var units = Manager.Objects.Where(x => x.IsValid && (x.IsUnit || x.IsPlayer)).OfType<WoWUnit>(); foreach (var u in units) { if (u.IsNeutral || u.IsHostile) redCircle.Add(u.Location.ToVector3()); else greenCircle.Add(u.Location.ToVector3()); blueCircle.Add(u.Location.ToVector3()); var color = (u.InLoS ? Color.FromArgb(0x8f, 0, 0xff, 0) : Color.FromArgb(0x8f, 0xff, 0, 0)); var line = new Line(); line.Add(Manager.LocalPlayer.Location, color); line.Add(u.Location, color); Rendering.RegisterResource(line); } Rendering.RegisterResource(redCircle); Rendering.RegisterResource(greenCircle); Rendering.RegisterResource(blueCircle); }
internal static SqlCommand SqlCommandWithValues(SqlCommand sqlCommand, Line line) { var values = line.Values.ToArray(); for (var i = 0; i < values.Length; i++) { sqlCommand.Parameters[i].Value = values[i]; } return sqlCommand; }
public LineGlyph InsertNewLineGlyph(Line line) { var lineGlyph = new LineGlyph(line) {Config = ParentVectorRedactor.LineConfig, Parent = this, MainGlyph = MainGlyph}; InsertChild(lineGlyph); return lineGlyph; }
public void Setup() { m_FromStartPoint = new Point(10.0, 10.0); m_FromEndPoint = new Point(60.0, 60.0); m_ToStartPoint = new Point(-10.0, -10.0); m_ToEndPoint = new Point(-60.0, -60.0); m_From = new Line(0, m_FromStartPoint, m_FromEndPoint); m_FromDirection = Constants.LineDirection.Forward; m_To = new Line(1, m_ToStartPoint, m_ToEndPoint); m_ToDirection = Constants.LineDirection.Forward; m_Sut = new LinesToTransferPointsConverter(m_From, m_FromDirection, m_To, m_ToDirection); m_Sut.Convert(); }
public void TestInitialize() { try { StreamReader testFileReader = new StreamReader(filePath, System.Text.Encoding.Default); data = testFileReader.ReadToEnd(); testFileReader.Close(); } catch (Exception) { //TODO } deserializer = new JavaScriptSerializer(); response = deserializer.Deserialize<Response>(data); List<Monitor> monitors = response.Data.Monitors; Monitor firstMonitor = monitors.First(); List<Line> lines = firstMonitor.Lines; firstLine = lines.First(); Departures departures = firstLine.Departures; List<Departure> departure = departures.Departure; Departure firstDeparture = departure.First(); Departure secondDeparture = departure.ElementAt(1); departureTime1 = firstDeparture.DepartureTime; departureTime2 = secondDeparture.DepartureTime; }
//----------------------------------------------------- public void AddPoint(Vector2 newPoint) { if(!m_lineStarted) { m_tmpLine = new Line(); m_tmpLine.src = newPoint; m_lineStarted = true; } else { m_tmpLine.setDst(newPoint, s_lineDrawWidth); Vector2 pxSrc = ToPixelCoord(m_tmpLine.src); Vector2 pxDst = ToPixelCoord(m_tmpLine.dst); float pixelLen = (pxDst - pxSrc).magnitude; if(pixelLen > 3/*10*/) { m_lines.Add(m_tmpLine); m_tmpLine = new Line(); m_tmpLine.src = newPoint; m_lineStarted = true; } } }
public void ResetLines() { HLines = new Line[Display.GetPixelsHeight()-1]; VLines = new Line[Display.GetPixelsWidth()-1]; for (int i = 0; i < HLines.Length; i++) HLines[i] = new Line() { Stroke = GridBrush, StrokeThickness = 1 }; for (int i = 0; i < VLines.Length; i++) VLines[i] = new Line() { Stroke = GridBrush, StrokeThickness = 1 }; }
public List<Vector2> Intersects(Rectangle rect) { Line helperLine = new Line(p1, angle); List<Vector2> intersection1 = helperLine.Intersects(rect); List<Vector2> intersection = new List<Vector2>(); if (angle >= 0 && angle < Math.PI / 2 || angle >= Math.PI / 2 * 3) { foreach (Vector2 p in intersection1) { if (p.X + 0.1 >= p1.X) //note: 0.1 intersection.Add(p); } } else { foreach (Vector2 p in intersection1) { if (p.X - 0.1 <= p1.X) //note: 0.1 intersection.Add(p); } } return intersection; }
public Window(Vector2 pos, Vector2 size, int bor, IGUIManager manager) { position = pos; this.size = size; border = bor; guiManager = manager; Color[] data = new Color[1]; Color[] data4 = new Color[1]; data[0] = Color.FromNonPremultiplied(210, 210, 210, 220); tex1 = new Texture2D(guiManager.GetGraphics(), 1, 1); tex1.SetData(data); data4[0] = Color.FromNonPremultiplied(100, 100, 100, 255); tex4 = new Texture2D(guiManager.GetGraphics(), 1, 1); tex4.SetData(data4); lines = new Line[4]; lines[0] = new Line(tex4, position - new Vector2(border, border), new Vector2(size.X + border * 2, border)); lines[1] = new Line(tex4, position - new Vector2(border, border), new Vector2(border, size.Y + border * 2)); lines[2] = new Line(tex4, new Vector2(position.X + size.X, position.Y - border), new Vector2(border, size.Y + border * 2)); lines[3] = new Line(tex4, new Vector2(position.X - border, position.Y + size.Y), new Vector2(size.X + border, border)); manager.AddGui(this); }
public DialogueController(RootLine rootLine, GameObject[] speakerGOs, GameObject pcGO, string situation) { currentLine = rootLine; speakers = new DialogueAction[speakerGOs.Length]; speakerMemories = new ArrayList(); for (int i = 0; i < speakerGOs.Length; i++){ GameObject speakerGO = speakerGOs[i]; bool isPC = speakerGO == pcGO; if(!isPC) { speakerMemories.Add(speakerGOs[i].GetComponent("ImpressionMemory")); } GameObject otherSpeakerGO = speakerGOs[0]; if (otherSpeakerGO == speakerGO){ otherSpeakerGO = speakerGOs[1]; } DialogueAction speaker = new DialogueAction(speakerGO, otherSpeakerGO.name, isPC); speakers[i] = speaker; ((ActionRunner)speakerGO.GetComponent("ActionRunner")).ResetRoutine(speaker, false); if (isPC){ pc = speaker; goodbyeLine = GetGoodbyeLine(otherSpeakerGO); } } if(pc != null) { SendActionStarted(); } this.situation = situation; //InitLookingDirections(); currentSpeaker = null; started = false; firstLineSaid = false; }
static void Main(string[] args) { Drawing obj = new Line(); obj.Draw(); Console.ReadKey(); }
public Line ToWorldFrom(Transform t) { Line ret = new Line(); ret.from = t.TransformPoint(from); ret.to = ret.from + t.TransformDirection(to - from); return ret; }
internal static Vector Cross(Line line1, Line line2) { if (line2.K - line1.K == 0) return new Vector(0, line1.B); var x = (line1.B - line2.B) / (line2.K - line1.K); var y = line1.K * x + line1.B; return new Vector(x, y); }
internal static Line Normal(Line line, Vector point) { if (line.K == 0) return new Line(0, 0); var kn = Math.Round(-1f / line.K, 1); var bn = Math.Round(point.Y - kn * point.X, 1); return new Line(kn, bn); }
/// <summary> /// Draw a line between two joints in a canvas /// </summary> /// <param name="canvas">the canvas</param> /// <param name="jstart">the joint where to start the line</param> /// <param name="jend">the joint where to end the line</param> /// <param name="vskeleton">the visual skeleton</param> private static void DrawLineBetween(Canvas canvas, Joint jstart, Joint jend, VisualSkeleton vskeleton) { if (vskeleton.positionMap.ContainsKey(jstart) && vskeleton.positionMap.ContainsKey(jend)) { Line l = new Line(); l.X1 = vskeleton.positionMap[jstart].X; l.Y1 = vskeleton.positionMap[jstart].Y; l.X2 = vskeleton.positionMap[jend].X; l.Y2 = vskeleton.positionMap[jend].Y; if (jstart.TrackingState == JointTrackingState.Inferred && jend.TrackingState == JointTrackingState.Inferred) { l.Stroke = Brushes.Yellow; l.StrokeThickness = 3; } else if (jstart.TrackingState == JointTrackingState.Tracked && jend.TrackingState == JointTrackingState.Tracked) { l.Stroke = Brushes.Green; l.StrokeThickness = 3; } else if (jstart.TrackingState == JointTrackingState.NotTracked || jend.TrackingState == JointTrackingState.NotTracked) { l.Stroke = Brushes.Transparent; l.StrokeThickness = 0; } canvas.Children.Add(l); } }
public override void Move() { if (x + 2 < Console.WindowHeight && isGoingDown) { Console.SetCursorPosition(0, x); foreach (var dot in LineTypes.AllLines[x].Dots) { dot.Content = Dot.ContentToString(Strings.emptyString); } LineTypes.AllLines[x].Draw(); x++; this.ruler = LineTypes.AllLines[x]; } else { isGoingDown = false; } if (x > 0 && !isGoingDown) { Console.SetCursorPosition(0, x); foreach (var dot in LineTypes.AllLines[x].Dots) { dot.Content = Dot.ContentToString(Strings.emptyString); } LineTypes.AllLines[x].Draw(); x--; this.ruler = LineTypes.AllLines[x]; } else { isGoingDown = true; } }
public void Setup() { m_Line1 = new Line(0, 10.0, 10.0, 20.0, 10.0); m_Line2 = new Line(1, 10.0, 20.0, 20.0, 20.0); m_Lines1 = new[] {m_Line1, m_Line2}; m_Lines2 = new[] {m_Line2, m_Line1}; m_ForwardForwardPaths = CreateForwardForwardPaths(); m_ForwardReversePaths = CreateForwardReversePaths(); m_ReverseForwardPaths = CreateReverseForwardPaths(); m_ReverseReversePaths = CreateReverseReversePaths(); m_Racetracks = Substitute.For<IRacetracks>(); m_Racetracks.ForwardToForward.Returns(m_ForwardForwardPaths); m_Racetracks.ForwardToReverse.Returns(m_ForwardReversePaths); m_Racetracks.ReverseToForward.Returns(m_ReverseForwardPaths); m_Racetracks.ReverseToReverse.Returns(m_ReverseReversePaths); m_Converter = new LineToLinesConverter(new CostStartToStartCalculator(), new CostStartToEndCalculator(), new CostEndToStartCalculator(), new CostEndToEndCalculator()) { Racetracks = m_Racetracks, Line = m_Line1, Lines = m_Lines1 }; m_Converter.Convert(); }
public override GraphicsResult GetGraphics(IWpfTextView view, Geometry geometry) { Initialize(view); // We clip off a bit off the start of the line to prevent a half-square being // drawn. var clipRectangle = geometry.Bounds; clipRectangle.Offset(2, 0); var line = new Line { X1 = geometry.Bounds.Left, Y1 = geometry.Bounds.Bottom - _graphicsTagPen.Thickness, X2 = geometry.Bounds.Right, Y2 = geometry.Bounds.Bottom - _graphicsTagPen.Thickness, Clip = new RectangleGeometry { Rect = clipRectangle } }; // RenderOptions.SetEdgeMode(line, EdgeMode.Aliased); ApplyPen(line, _graphicsTagPen); // Shift the line over to offset the clipping we did. line.RenderTransform = new TranslateTransform(-_graphicsTagPen.Thickness, 0); return new GraphicsResult(line, null); }
async Task Exec(string cmd, double param) { var px = x; var py = y; switch(cmd) { case "forw": x += param * Math.Sin(Conv(angle)); y += param * Math.Cos(Conv(angle)); await Speak("Going forward"); break; case "back": x -= param * Math.Sin(Conv(angle)); y -= param * Math.Cos(Conv(angle)); await Speak("Going Back"); break; case "left": angle += param; await Speak("Turning left"); break; case "right": angle -= param; await Speak("Turning right"); break; } if (px!=x || py!=y) { var P = new Line(); P.X1 = px; P.Y1 = py; P.X2 = x; P.Y2 = y; P.Stroke = new SolidColorBrush(Colors.Black); P.StrokeThickness = 1; main.Children.Add(P); } SetTurtle(); }
// Static function to find the intersection of two planes // If they are parallel, returns false and outputs an invalid line struct // Otherwise, returns true and outputs the line of intersection public static bool Intersect(Plane a, Plane b, out Line result) { Vec3 cross = Vec3.Cross(a.normal, b.normal); double magsq = cross.ComputeMagnitudeSquared(); if (magsq == 0) { // failure! planes did not intersect, or planes were equal result = new Line { direction = Vec3.Zero, origin = Vec3.Zero }; // not a valid line! return false; } double invmag = 1.0 / Math.Sqrt(magsq); Vec3 line_direction = cross * invmag; // using plane a to find intersection (also could try b?) Vec3 in_a_toward_edge = Vec3.Normalize(Vec3.Cross(a.normal, line_direction)); Vec3 point_in_a = a.normal * a.offset; double dist = b.PointDistance(point_in_a); // seems this number could be either the positive or negative of what we want... double unsigned_r = dist * invmag; Vec3 positive = point_in_a + in_a_toward_edge * unsigned_r; Vec3 negative = point_in_a - in_a_toward_edge * unsigned_r; // figure out which one is actually at the intersection (or closest to it) double positive_check = new Vec2 { x = a.PointDistance(positive), y = b.PointDistance(positive) }.ComputeMagnitudeSquared(); double negative_check = new Vec2 { x = a.PointDistance(negative), y = b.PointDistance(negative) }.ComputeMagnitudeSquared(); // and use that one as a point on the line (for the out value) Vec3 point_on_line; if (positive_check < negative_check) point_on_line = positive; else point_on_line = negative; // success! planes intersectedx result = new Line { origin = point_on_line, direction = line_direction }; return true; }
void ToggleBreakpoint(int lineNo) { if (!ShowBreakpointsMargin) { return; } BreakpointsChangedEventArgs e; Line sline = Lines[lineNo]; const uint mask = (1 << BOOKMARK_MARKER); while (sline.Text.Length < 4 || sline.Text.Substring(0, 4) == " ") { lineNo++; sline = Lines[lineNo]; if (lineNo > Lines.Count) { return; } } string saddress = sline.Text.Substring(0, 4).Trim(); if (saddress.Length > 0) { try { LastBeakpointAddress = Convert.ToInt32(saddress, 16); } catch { return; } Breakpoints[LastBeakpointAddress] = !Breakpoints[LastBeakpointAddress]; if (!Breakpoints[LastBeakpointAddress]) { // Remove existing bookmark sline.MarkerDelete(BOOKMARK_MARKER); //if (Breakpoint != null) Breakpoint(address, false); Breakpoints[LastBeakpointAddress] = false; BreakpointsChanged?.Invoke(this, new BreakpointsChangedEventArgs(Breakpoints)); Refresh(); return; } else { // Add bookmark sline.MarkerAdd(BOOKMARK_MARKER); //if (Breakpoint != null) Breakpoint(address, true); Breakpoints[LastBeakpointAddress] = true; } e = new BreakpointsChangedEventArgs(Breakpoints); BreakpointsChanged?.Invoke(this, e); if (!e.SourceChanged) { return; } lineNo = 0; while (true) { sline = Lines[lineNo]; if (sline.Text.Length < 4 || sline.Text.Substring(0, 4) == " ") { lineNo++; continue; } if (sline.Text.Substring(0, 4).Trim() == saddress) { if ((sline.MarkerGet() & mask) > 0) { // Remove existing bookmark sline.MarkerDelete(BOOKMARK_MARKER); //if (Breakpoint != null) Breakpoint(address, false); Breakpoints[LastBeakpointAddress] = false; } else { // Add bookmark sline.MarkerAdd(BOOKMARK_MARKER); //if (Breakpoint != null) Breakpoint(address, true); Breakpoints[LastBeakpointAddress] = true; } BreakpointsChanged?.Invoke(this, new BreakpointsChangedEventArgs(Breakpoints)); break; } lineNo++; sline = Lines[lineNo]; if (lineNo > Lines.Count) { return; } } } }
/// <summary> /// Here is a part or our code to start a Revit command. /// The aim of the code is to set a wall type current in the Revit property window. /// We only start up the wall command with the API and let the user do the drawing of the wall. /// This solution can also be used to launch other Revit commands. /// </summary> public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication uiapp = commandData.Application; UIDocument uidoc = uiapp.ActiveUIDocument; Application app = uiapp.Application; Document doc = uidoc.Document; // name of target wall type that we want to use: string wallTypeName = "Generic - 203"; WallType wallType = GetFirstWallTypeNamed( doc, wallTypeName); Wall wall = GetFirstWallUsingType( doc, wallType); // select the wall in the UI uidoc.Selection.Elements.Add(wall); if (0 == uidoc.Selection.Elements.Size) { // no wall with the correct wall type found FilteredElementCollector collector = new FilteredElementCollector(doc); Level ll = collector .OfClass(typeof(Level)) .FirstElement() as Level; // place a new wall with the // correct wall type in the project //Line geomLine = app.Create.NewLineBound( XYZ.Zero, new XYZ( 2, 0, 0 ) ); // 2013 Line geomLine = Line.CreateBound(XYZ.Zero, new XYZ(2, 0, 0)); // 2014 Transaction t = new Transaction( doc, "Create dummy wall"); t.Start(); //Wall nw = doc.Create.NewWall( geomLine, // 2012 // wallType, ll, 1, 0, false, false ); Wall nw = Wall.Create(doc, geomLine, // 2013 wallType.Id, ll.Id, 1, 0, false, false); t.Commit(); // Select the new wall in the project uidoc.Selection.Elements.Add(nw); // Start command create similar. In the // property menu, our wall type is set current Press.Keys("CS"); // select the new wall in the project, // so we can delete it uidoc.Selection.Elements.Add(nw); // erase the selected wall (remark: // doc.delete(nw) may not be used, // this command will undo) Press.Keys("DE"); // start up wall command Press.Keys("WA"); } else { // the correct wall is already selected: Press.Keys("CS"); // start "create similar" } return(Result.Succeeded); }
public static List <Autodesk.Revit.DB.Wall> TrimOrExtendWall(this IEnumerable <Autodesk.Revit.DB.Wall> walls, double maxDistance, double tolerance = Core.Tolerance.Distance) { Dictionary <double, Dictionary <Autodesk.Revit.DB.Wall, Segment2D> > dictionary = new Dictionary <double, Dictionary <Autodesk.Revit.DB.Wall, Segment2D> >(); foreach (Autodesk.Revit.DB.Wall wall in walls) { Curve curve = (wall.Location as LocationCurve).Curve; Segment3D segment3D = Geometry.Revit.Convert.ToSAM_Segment3D(curve); double elevation = Math.Min(segment3D[0].Z, segment3D[1].Z); Dictionary <Autodesk.Revit.DB.Wall, Segment2D> dictionary_Wall = null; if (!dictionary.TryGetValue(elevation, out dictionary_Wall)) { dictionary_Wall = new Dictionary <Autodesk.Revit.DB.Wall, Segment2D>(); dictionary[elevation] = dictionary_Wall; } dictionary_Wall[wall] = Geometry.Spatial.Plane.WorldXY.Convert(segment3D); } List <Autodesk.Revit.DB.Wall> result = new List <Autodesk.Revit.DB.Wall>(); foreach (KeyValuePair <double, Dictionary <Autodesk.Revit.DB.Wall, Segment2D> > keyValuePair in dictionary) { List <Segment2D> segment2Ds = keyValuePair.Value.Values.ToList(); //Filtering Walls by Level List <Tuple <Autodesk.Revit.DB.Wall, Segment2D, List <int>, bool> > tupleList = new List <Tuple <Autodesk.Revit.DB.Wall, Segment2D, List <int>, bool> >(); foreach (KeyValuePair <Autodesk.Revit.DB.Wall, Segment2D> keyValuePair_Wall in keyValuePair.Value) { LocationCurve locationCurve = keyValuePair_Wall.Key.Location as LocationCurve; List <int> indexes = new List <int>(); ElementArray elementArray = null; elementArray = locationCurve.get_ElementsAtJoin(0); if (elementArray == null || elementArray.Size == 0) { indexes.Add(0); } elementArray = locationCurve.get_ElementsAtJoin(1); if (elementArray == null || elementArray.Size == 0) { indexes.Add(1); } //if (indexes.Count > 0) tupleList.Add(new Tuple <Autodesk.Revit.DB.Wall, Segment2D, List <int>, bool>(keyValuePair_Wall.Key, keyValuePair_Wall.Value, indexes, false)); } //Seeking for walls to be extended/trimmed bool updated = true; while (updated) { updated = false; List <Tuple <Autodesk.Revit.DB.Wall, Segment2D, List <int>, bool> > tupleList_Unconnected = tupleList.FindAll(x => x.Item3 != null && x.Item3.Count > 0); for (int i = 0; i < tupleList_Unconnected.Count; i++) { Tuple <Autodesk.Revit.DB.Wall, Segment2D, List <int>, bool> tuple = tupleList_Unconnected[i]; List <Tuple <Autodesk.Revit.DB.Wall, Segment2D, List <int>, bool> > tupleList_Temp = new List <Tuple <Autodesk.Revit.DB.Wall, Segment2D, List <int>, bool> >(tupleList); tupleList_Temp.Remove(tuple); Segment2D segment2D = tuple.Item2; List <Tuple <Point2D, Segment2D> > tupleList_Intersection = new List <Tuple <Point2D, Segment2D> >(); foreach (Segment2D segment2D_Temp in tupleList_Temp.ConvertAll(x => x.Item2)) { Point2D point2D_Intersection = segment2D_Temp.Intersection(segment2D, false, tolerance); if (point2D_Intersection == null) { //Checking Colinear Segment2Ds if can be extended Vector2D direction_Temp = segment2D_Temp.Direction; Vector2D direction = segment2D.Direction; if (!direction_Temp.AlmostEqual(direction, tolerance) && !direction_Temp.AlmostEqual(direction.GetNegated(), tolerance)) { continue; } Point2D point2D_Temp = null; Point2D point2D = null; if (!Geometry.Planar.Query.Closest(segment2D_Temp, segment2D, out point2D_Temp, out point2D, tolerance)) { continue; } if (point2D_Temp.AlmostEquals(point2D, tolerance)) { continue; } Vector2D direction_New = new Vector2D(point2D, point2D_Temp).Unit; if (!direction_Temp.AlmostEqual(direction_New, tolerance) && !direction_Temp.AlmostEqual(direction_New.GetNegated(), tolerance)) { continue; } point2D_Intersection = point2D; } double distance; distance = segment2D.Distance(point2D_Intersection); if (distance > maxDistance) { continue; } distance = segment2D_Temp.Distance(point2D_Intersection); if (distance > maxDistance) { continue; } tupleList_Intersection.Add(new Tuple <Point2D, Segment2D>(point2D_Intersection, segment2D_Temp)); } if (tupleList_Intersection.Count == 0) { continue; } foreach (int index in tuple.Item3) { Point2D point2D = segment2D[index]; tupleList_Intersection.Sort((x, y) => x.Item1.Distance(point2D).CompareTo(y.Item1.Distance(point2D))); Tuple <Point2D, Segment2D> tuple_Intersection = tupleList_Intersection.Find(x => x.Item1.Distance(point2D) < maxDistance); if (tuple_Intersection == null) { continue; } Segment2D segment2D_Intersection = tuple_Intersection.Item2; int j = tupleList.FindIndex(x => x.Item2 == segment2D_Intersection); if (j == -1) { continue; } int k = tupleList.FindIndex(x => x.Item2 == segment2D); if (k == -1) { continue; } //TODO: Double Check if works (added 2020.05.14) if ((index == 0 && segment2D[1].AlmostEquals(tuple_Intersection.Item1)) || (index == 1 && segment2D[0].AlmostEquals(tuple_Intersection.Item1))) { tupleList[k] = new Tuple <Autodesk.Revit.DB.Wall, Segment2D, List <int>, bool>(tuple.Item1, new Segment2D(tuple_Intersection.Item1, tuple_Intersection.Item1), tuple.Item3.FindAll(x => x != index), true); updated = true; break; } Segment2D segment2D_Temp; if (segment2D_Intersection[0].Distance(tuple_Intersection.Item1) < maxDistance || segment2D_Intersection[1].Distance(tuple_Intersection.Item1) < maxDistance) { segment2D_Temp = new Segment2D(segment2D_Intersection); segment2D_Temp.Adjust(tuple_Intersection.Item1); if (!segment2D_Temp.AlmostSimilar(segment2D_Intersection) && segment2D_Temp.GetLength() > segment2D_Intersection.GetLength()) { tupleList[j] = new Tuple <Autodesk.Revit.DB.Wall, Segment2D, List <int>, bool>(tupleList[j].Item1, segment2D_Temp, tupleList[j].Item3.FindAll(x => x != segment2D_Temp.GetEndIndex(tuple_Intersection.Item1)), true); } } segment2D_Temp = new Segment2D(segment2D); segment2D_Temp.Adjust(tuple_Intersection.Item1); if (segment2D_Temp.AlmostSimilar(segment2D)) { continue; } tupleList[k] = new Tuple <Autodesk.Revit.DB.Wall, Segment2D, List <int>, bool>(tuple.Item1, segment2D_Temp, tuple.Item3.FindAll(x => x != index), true); updated = true; break; } if (updated) { break; } } } tupleList.RemoveAll(x => !x.Item4); //Updating Revit Walls foreach (Tuple <Autodesk.Revit.DB.Wall, Segment2D, List <int>, bool> tuple in tupleList) { Autodesk.Revit.DB.Wall wall = tuple.Item1; if (!wall.IsValidObject) { continue; } Segment2D segment2D = tuple.Item2; if (segment2D.GetLength() < tolerance) { wall.Document.Delete(wall.Id); continue; } LocationCurve locationCurve = wall.Location as LocationCurve; JoinType[] joinTypes = new JoinType[] { locationCurve.get_JoinType(0), locationCurve.get_JoinType(1) }; WallUtils.DisallowWallJoinAtEnd(wall, 0); WallUtils.DisallowWallJoinAtEnd(wall, 1); Segment3D segment3D = new Segment3D(new Point3D(segment2D[0].X, segment2D[0].Y, keyValuePair.Key), new Point3D(segment2D[1].X, segment2D[1].Y, keyValuePair.Key)); Line line = Geometry.Revit.Convert.ToRevit(segment3D); locationCurve.Curve = line; WallUtils.AllowWallJoinAtEnd(wall, 0); locationCurve.set_JoinType(0, joinTypes[0]); WallUtils.AllowWallJoinAtEnd(wall, 1); locationCurve.set_JoinType(1, joinTypes[1]); result.Add(tuple.Item1); } } return(result); }
public override void WriteXml(ref IaXmlWriter xml) { xml.WriteStartElement("function"); xml.WriteAttribute("controlid", ControlId, true); xml.WriteStartElement("update_sotransaction"); if (!String.IsNullOrWhiteSpace(ExternalId)) { xml.WriteAttribute("key", ExternalId); xml.WriteAttribute("externalkey", true); } else { xml.WriteAttribute("key", TransactionId); } if (DisableValidation == true) { xml.WriteAttribute("disablevalidation", true); } if (TransactionDate.HasValue) { xml.WriteStartElement("datecreated"); xml.WriteDateSplitElements(TransactionDate.Value, true); xml.WriteEndElement(); //datecreated } if (GlPostingDate.HasValue) { xml.WriteStartElement("dateposted"); xml.WriteDateSplitElements(GlPostingDate.Value); xml.WriteEndElement(); //dateposted } xml.WriteElement("referenceno", ReferenceNumber); xml.WriteElement("termname", PaymentTerm); if (DueDate.HasValue) { xml.WriteStartElement("datedue"); xml.WriteDateSplitElements(DueDate.Value, true); xml.WriteEndElement(); //datedue } if (OriginalDocumentDate.HasValue) { xml.WriteStartElement("origdocdate"); xml.WriteDateSplitElements(OriginalDocumentDate.Value, true); xml.WriteEndElement(); //origdocdate } xml.WriteElement("message", Message); xml.WriteElement("shippingmethod", ShippingMethod); if (!String.IsNullOrWhiteSpace(ShipToContactName)) { xml.WriteStartElement("shipto"); xml.WriteElement("contactname", ShipToContactName, true); xml.WriteEndElement(); //shipto } if (!String.IsNullOrWhiteSpace(BillToContactName)) { xml.WriteStartElement("billto"); xml.WriteElement("contactname", BillToContactName, true); xml.WriteEndElement(); //billto } xml.WriteElement("supdocid", AttachmentsId); xml.WriteElement("basecurr", BaseCurrency); xml.WriteElement("currency", TransactionCurrency); if (ExchangeRateDate.HasValue) { xml.WriteStartElement("exchratedate"); xml.WriteDateSplitElements(ExchangeRateDate.Value); xml.WriteEndElement(); //exchratedate } if (!String.IsNullOrWhiteSpace(ExchangeRateType)) { xml.WriteElement("exchratetype", ExchangeRateType); } else if (ExchangeRateValue.HasValue) { xml.WriteElement("exchrate", ExchangeRateValue); } else if (!String.IsNullOrWhiteSpace(BaseCurrency) || !String.IsNullOrWhiteSpace(TransactionCurrency)) { xml.WriteElement("exchratetype", ExchangeRateType, true); } xml.WriteElement("vsoepricelist", VsoePriceList); xml.WriteCustomFieldsExplicit(CustomFields); xml.WriteElement("state", State); xml.WriteElement("projectid", ProjectId); if (Lines.Count > 0) { xml.WriteStartElement("updatesotransitems"); foreach (AbstractOrderEntryTransactionLine Line in Lines) { Line.WriteXml(ref xml); } xml.WriteEndElement(); //updatesotransitems } if (Subtotals.Count > 0) { xml.WriteStartElement("updatesubtotals"); foreach (AbstractTransactionSubtotal Subtotal in Subtotals) { Subtotal.WriteXml(ref xml); } xml.WriteEndElement(); //updatesubtotals } xml.WriteEndElement(); //update_sotransaction xml.WriteEndElement(); //function }
/// <summary> /// 这条线是否在点上 /// </summary> /// <param name="line"></param> /// <returns></returns> public bool ContainLine(Line line) { return(lineList.Contains(line)); }
/// <summary> /// 删除点上的边 /// </summary> /// <param name="line"></param> public void RemoveLine(Line line) { lineList.Remove(line); }
/// <summary> /// 在点上添加边 /// </summary> /// <param name="line"></param> public void AddLine(Line line) { lineList.Add(line); }
private void DrawArrowEdge(bool weighted) { double len1 = 10; double len2 = 5; double coef = 3; double X1 = _from.GetCenter().X; double Y1 = _from.GetCenter().Y; double X2 = _to.GetCenter().X; double Y2 = _to.GetCenter().Y; // Длина отрезка double d = Math.Sqrt(Math.Pow(X2 - X1, 2) + Math.Pow(Y2 - Y1, 2)); // Координаты вектора double X = X2 - X1; double Y = Y2 - Y1; // double X3 = (X1 + X2 * coef) / (1 + coef); double Y3 = (Y1 + Y2 * coef) / (1 + coef); // double X4 = X3 - (X / d) * len1; double Y4 = Y3 - (Y / d) * len1; // double Xp = Y2 - Y1; double Yp = X1 - X2; // double X5 = X4 + (Xp / d) * len2; double Y5 = Y4 + (Yp / d) * len2; double X6 = X4 - (Xp / d) * len2; double Y6 = Y4 - (Yp / d) * len2; // Line mainLine = new Line { X1 = X1, Y1 = Y1, X2 = X2, Y2 = Y2, Stroke = color, StrokeThickness = 3, }; Line leftLine = new Line { X1 = X5, Y1 = Y5, X2 = X3, Y2 = Y3, Stroke = color, StrokeThickness = 3, }; Line rightLine = new Line { X1 = X6, Y1 = Y6, X2 = X3, Y2 = Y3, Stroke = color, StrokeThickness = 3, }; Canvas.SetZIndex(mainLine, -3); Canvas.SetZIndex(rightLine, -3); Canvas.SetZIndex(leftLine, -3); if (weighted) { double xc = (X1 + divideEdge * X2) / (1.0 + divideEdge) - 15; double yc = (Y1 + divideEdge * Y2) / (1.0 + divideEdge) - 15; Ellipse el = new Ellipse { Height = 30, Width = 30, Fill = Brushes.White, Stroke = Brushes.Black, StrokeThickness = 2, HorizontalAlignment = HorizontalAlignment.Left, VerticalAlignment = VerticalAlignment.Top, Margin = new Thickness(left: xc, top: yc, right: 0, bottom: 0), }; TextBlock text = new TextBlock { FontSize = 15, Text = _weight.ToString(), Margin = new Thickness(left: xc - _weight.ToString().Length *10 / 2 + 18, top: yc + 5, right: 0, bottom: 0), }; Canvas.SetZIndex(el, -2); Canvas.SetZIndex(text, -2); _canvas.Children.Add(el); _canvas.Children.Add(text); } _canvas.Children.Add(mainLine); _canvas.Children.Add(leftLine); _canvas.Children.Add(rightLine); }
public MaterialsAMLPaletteRequest(UIApplication uiApp, String text) { RVTDocument doc = uiApp.ActiveUIDocument.Document; MaterialsAMLPalette materialsPalette = BARevitTools.Application.thisApp.newMainUi.materialsAMLPalette; //Get the versioned symbol family FamilySymbol familySymbol = null; string versionedFamily = RVTOperations.GetVersionedFamilyFilePath(uiApp, Properties.Settings.Default.RevitIDAccentMatTag); //Try loading the family symbol Transaction loadSymbolTransaction = new Transaction(doc, "LoadFamilySymbol"); loadSymbolTransaction.Start(); try { try { IFamilyLoadOptions loadOptions = new RVTFamilyLoadOptions(); doc.LoadFamilySymbol(versionedFamily, "Legend Tag (Fake)", loadOptions, out FamilySymbol symb); familySymbol = symb; } catch { MessageBox.Show(String.Format("Could not get the 'Legend Tag (Fake)' type from {0}", versionedFamily), "Family Symbol Load Error"); } loadSymbolTransaction.Commit(); } catch (Exception transactionException) { loadSymbolTransaction.RollBack(); MessageBox.Show(transactionException.ToString()); } //Get the line style to use, or create the default Element lineStyle = null; if (materialsPalette.paletteMaterialComboBox.Text == "Default") { try { lineStyle = doc.Settings.Categories.get_Item(BuiltInCategory.OST_Lines).SubCategories.get_Item("6 BA ID ACCENT").GetGraphicsStyle(GraphicsStyleType.Projection); } catch { try { Category linesCategory = doc.Settings.Categories.get_Item(BuiltInCategory.OST_Lines); Category newLineStyleCategory = doc.Settings.Categories.NewSubcategory(linesCategory, "6 BA ID ACCENT"); newLineStyleCategory.LineColor = new Color(0, 0, 0); newLineStyleCategory.SetLineWeight(6, GraphicsStyleType.Projection); newLineStyleCategory.SetLinePatternId(LinePatternElement.GetSolidPatternId(), GraphicsStyleType.Projection); doc.Regenerate(); lineStyle = newLineStyleCategory.GetGraphicsStyle(GraphicsStyleType.Projection); } catch (Exception e) { MessageBox.Show(e.ToString()); } } } else { lineStyle = doc.Settings.Categories.get_Item(BuiltInCategory.OST_Lines).SubCategories.get_Item("ID " + materialsPalette.paletteMaterialComboBox.Text).GetGraphicsStyle(GraphicsStyleType.Projection); } //Assure the view being used is a floor plan if (doc.ActiveView.ViewType != ViewType.FloorPlan) { MessageBox.Show("This tool should be used ina a Floor Plan or Area Plan view"); } else { //Create a loop for picking points. Change the palette background color based on the number of points picked List <XYZ> pickedPoints = new List <XYZ>(); bool breakLoop = false; int pickCount = 0; while (breakLoop == false) { try { //Have the user begin picking points. The number of clicks to start the UI color change is 1 because the first click is usually to activate the window. XYZ point = uiApp.ActiveUIDocument.Selection.PickPoint(Autodesk.Revit.UI.Selection.ObjectSnapTypes.Endpoints, "Click points for the line to follow. Then click once to the side where the lines should be drawn. Hit ESC to finish"); pickedPoints.Add(point); if (pickCount == 1) { materialsPalette.BackColor = System.Drawing.Color.Firebrick; } else if (pickCount == 2) { materialsPalette.BackColor = System.Drawing.Color.Orange; } else if (pickCount > 2) { //After three clicks in the window, the user has made the minimum point selection to generate the lines from the start, end, and positive side points. materialsPalette.BackColor = System.Drawing.Color.GreenYellow; } else { ; } pickCount++; } catch { materialsPalette.BackColor = MaterialsAMLPalette.DefaultBackColor; breakLoop = true; } } //Get rid of the first point from clicking into the Revit view. This point is not needed. pickedPoints.RemoveAt(0); if (pickedPoints.Count > 2) { Transaction createLinesTransaction = new Transaction(doc, "CreateAccentLines"); createLinesTransaction.Start(); try { //These points will be used in determining the start, end, and room points XYZ firstPoint = pickedPoints[0]; XYZ roomPoint = pickedPoints[pickedPoints.Count - 1]; XYZ lastPoint = pickedPoints[pickedPoints.Count - 2]; //Create a list of points for the polyline that excludes the room point List <XYZ> polyLinePoints = new List <XYZ>(); for (int i = 0; i < pickedPoints.Count - 1; i++) { polyLinePoints.Add(pickedPoints[i]); } //Create a polyline from the list of picked points and then get make lines from the points on the poly line PolyLine guidePolyLine = PolyLine.Create(polyLinePoints); IList <XYZ> polyPoints = guidePolyLine.GetCoordinates(); List <Line> guideLines = new List <Line>(); for (int i = 0; i < polyLinePoints.Count - 1; i++) { guideLines.Add(Line.CreateBound(polyLinePoints[i], polyLinePoints[i + 1])); } //Get the direction of the line offset by measuring the first offset for positive and negative values and comparing their distances with the room point bool positiveZ = false; List <Line> offsetLines = new List <Line>(); Line positiveOffsetLine = guideLines.Last().CreateOffset(0.6666666667d, XYZ.BasisZ) as Line; Line negativeOffsetLine = guideLines.Last().CreateOffset(-0.6666666667d, XYZ.BasisZ) as Line; XYZ positiveOffsetMidPoint = positiveOffsetLine.Evaluate(0.5d, true); XYZ negativeOffsetMidPoint = negativeOffsetLine.Evaluate(0.5d, true); Double positiveOffsetDistance = positiveOffsetMidPoint.DistanceTo(roomPoint); Double negativeOffsetDistance = negativeOffsetMidPoint.DistanceTo(roomPoint); //If the positive offset side resulted in a shorter distance to the point inside the room, then the offset should have a positive Z normal. if (positiveOffsetDistance < negativeOffsetDistance) { positiveZ = true; } //Knowing whether or not to use a positive or negative offset, begin creating offset lines for each guide line foreach (Line guideLine in guideLines) { if (positiveZ) { offsetLines.Add(guideLine.CreateOffset(0.6666666667d, XYZ.BasisZ) as Line); } else { offsetLines.Add(guideLine.CreateOffset(-0.6666666667d, XYZ.BasisZ) as Line); } } //Determine if the number of line segments is 1 or more Line firstLine = offsetLines.First(); Line lastLine = null; if (offsetLines.Count > 1) { lastLine = offsetLines.Last(); } //If there is only one line segment, both end operations must be performed on it if (lastLine == null) { double lineLength = firstLine.Length; double fractionOfLength = 0.6666666667d / lineLength; //Checking fractions to ensure they are not greater than 1 for the normalization if (fractionOfLength > 1) { fractionOfLength = 0.25d; } //Re-evaluating where to place the start and end point of the line XYZ shiftedStartPoint = firstLine.Evaluate(fractionOfLength, true); XYZ shiftedEndPoint = firstLine.Evaluate(1 - fractionOfLength, true); firstLine = Line.CreateBound(shiftedStartPoint, shiftedEndPoint); //Creating the angled corner lines Line firstCornerLine = Line.CreateBound(firstPoint, firstLine.GetEndPoint(0)); Line lastCornerLine = Line.CreateBound(lastPoint, firstLine.GetEndPoint(1)); //Create the detail lines from the lines DetailCurve newAccentLine1 = doc.Create.NewDetailCurve(doc.ActiveView, firstCornerLine); DetailCurve newAccentLine2 = doc.Create.NewDetailCurve(doc.ActiveView, firstLine); DetailCurve newAccentLine3 = doc.Create.NewDetailCurve(doc.ActiveView, lastCornerLine); //Assign a line style to the newly created detail lines newAccentLine1.LineStyle = lineStyle; newAccentLine2.LineStyle = lineStyle; newAccentLine3.LineStyle = lineStyle; XYZ tagPlacementPoint = firstLine.Evaluate(0.5d, true); XYZ direction = firstLine.Direction; Line axisLine = Line.CreateUnbound(tagPlacementPoint, XYZ.BasisZ); double rotationAngle = direction.AngleTo(XYZ.BasisX); //Get the midpoint of the line, its direction, and create the rotation and axis if (familySymbol != null) { //Create the tag instance FamilyInstance newTag = doc.Create.NewFamilyInstance(tagPlacementPoint, familySymbol, doc.ActiveView); //Rotate the new tag instance ElementTransformUtils.RotateElement(doc, newTag.Id, axisLine, rotationAngle); } createLinesTransaction.Commit(); } //If there is more than one line segment, an operation must be performed on the start and end of the start and end lines, respectively else { List <Line> linesToDraw = new List <Line>(); // Get the normalized value for 8" relative to the lengths of the start and end lines double firstLineLength = firstLine.Length; double fractionOfFirstLine = 0.6666666667 / firstLineLength; double lastLineLength = lastLine.Length; double fractionOfLastLine = 0.666666667 / lastLineLength; //Checking fractions to ensure they are not greater than 1 for the normalization if (fractionOfFirstLine > 1) { fractionOfFirstLine = 0.25d; } if (fractionOfLastLine > 1) { fractionOfLastLine = 0.25d; } //Shift the ends of the start and end lines by finding the point along the line relative to the normalized 8" value XYZ shiftedStartPoint = firstLine.Evaluate(fractionOfFirstLine, true); XYZ shiftedEndPoint = lastLine.Evaluate(1 - fractionOfLastLine, true); //Reset the start and end lines with the new shifted points firstLine = Line.CreateBound(shiftedStartPoint, firstLine.GetEndPoint(1)); lastLine = Line.CreateBound(lastLine.GetEndPoint(0), shiftedEndPoint); linesToDraw.Add(firstLine); //If there are only 3 offset lines, there will be just one middle segment if (offsetLines.Count == 3) { linesToDraw.Add(offsetLines[1]); } //If there are more than three offset lines, there will be more than one middle line segment else { List <Line> middleLines = offsetLines.GetRange(1, offsetLines.Count - 2); foreach (Line middleLine in middleLines) { linesToDraw.Add(middleLine); } } linesToDraw.Add(lastLine); //For the lines to draw, intersect them with the next line in the list and reset their start and end points to be the intersection for (int i = 0; i < linesToDraw.Count - 1; i++) { Line line1 = linesToDraw[i]; Line scaledLine1 = Line.CreateUnbound(line1.GetEndPoint(1), line1.Direction); Line line2 = linesToDraw[i + 1]; Line scaledLine2 = Line.CreateUnbound(line2.GetEndPoint(0), line2.Direction.Negate()); SetComparisonResult intersectionResult = scaledLine1.Intersect(scaledLine2, out IntersectionResultArray results); if (intersectionResult == SetComparisonResult.Overlap) { IntersectionResult result = results.get_Item(0); Line newLine1 = Line.CreateBound(line1.GetEndPoint(0), result.XYZPoint); Line newLine2 = Line.CreateBound(result.XYZPoint, line2.GetEndPoint(1)); linesToDraw[i] = newLine1; linesToDraw[i + 1] = newLine2; } } //Create the angled corner lines at the start and end of the line chain Line firstCornerLine = Line.CreateBound(firstPoint, firstLine.GetEndPoint(0)); Line lastCornerLine = Line.CreateBound(lastPoint, lastLine.GetEndPoint(1)); linesToDraw.Add(firstCornerLine); linesToDraw.Add(lastCornerLine); //Create each line as a detail line foreach (Line apiLine in linesToDraw) { DetailCurve newAccentLine = doc.Create.NewDetailCurve(doc.ActiveView, apiLine); newAccentLine.LineStyle = lineStyle; } //Declare some stuff for use in the symbol placement Line firstMiddleLine = linesToDraw[0]; Line lastMiddleLine = linesToDraw[linesToDraw.Count - 3]; XYZ firstTagPoint = firstMiddleLine.Evaluate(0.5d, true); XYZ lastTagPoint = lastMiddleLine.Evaluate(0.5d, true); XYZ firstDirection = firstMiddleLine.Direction; XYZ lastDirection = lastMiddleLine.Direction; Line firstAxisLine = Line.CreateUnbound(firstTagPoint, XYZ.BasisZ); Line lastAxisLine = Line.CreateUnbound(lastTagPoint, XYZ.BasisZ); double firstRotation = firstDirection.AngleTo(XYZ.BasisX); double lastRotation = lastDirection.AngleTo(XYZ.BasisX); if (familySymbol != null) { //Create tag at the beginning of the middle lines FamilyInstance firstTag = doc.Create.NewFamilyInstance(firstTagPoint, familySymbol, doc.ActiveView); ElementTransformUtils.RotateElement(doc, firstTag.Id, firstAxisLine, firstRotation); //Create a tag at the end of the middle lines if there are more than 2 middle lines if (linesToDraw.Count > 4) { FamilyInstance lastTag = doc.Create.NewFamilyInstance(lastTagPoint, familySymbol, doc.ActiveView); ElementTransformUtils.RotateElement(doc, lastTag.Id, lastAxisLine, lastRotation); } } createLinesTransaction.Commit(); } } catch (Exception e) { //Suppose the user closed the palette too soon. This will remind them to keep it open. if (BARevitTools.Application.thisApp.newMainUi.materialsAMLPalette == null) { MessageBox.Show("AML Picker was closed prematurely. Please keep the picker open until the lines are drawn."); } else { //Otherwise, if some other error occurred, show the exception MessageBox.Show(e.ToString()); } createLinesTransaction.RollBack(); } } else { ; } } }
private void selectLineToolStripMenuItem_Click(object sender, EventArgs e) { Line line = TextArea.Lines[TextArea.CurrentLine]; TextArea.SetSelection(line.Position + line.Length, line.Position); }
private static void DrawLineOn(Canvas canvas, Line line, ImmutableColor color) => DrawLineOn(canvas, line.A.X, line.A.Y, line.B.X, line.B.Y, color);
static void Parse(string line, int lineNumber) { MatchCollection matches = GCodeSplitter.Matches(line); List <Word> Words = new List <Word>(matches.Count); foreach (Match match in matches) { Words.Add(new Word() { Command = match.Groups[1].Value[0], Parameter = double.Parse(match.Groups[2].Value, Constants.DecimalParseFormat) }); } for (int i = 0; i < Words.Count; i++) { if (!ValidWords.Contains(Words[i].Command)) { throw new ParseException($"unknown word (letter): \"{Words[i].Command} {Words[i].Parameter}\"", lineNumber); } if (Words[i].Command != 'F') { continue; } State.Feed = Words[i].Parameter; if (State.Unit == ParseUnit.Imperial) { State.Feed *= 25.4; } Words.RemoveAt(i--); continue; } for (int i = 0; i < Words.Count; i++) { if (Words[i].Command == 'M') { int param = (int)Words[i].Parameter; if (param != Words[i].Parameter || param < 0) { throw new ParseException("MCode can only have integer parameters", lineNumber); } Commands.Add(new MCode() { Code = param }); Words.RemoveAt(i); i--; continue; } if (Words[i].Command == 'S') { double param = Words[i].Parameter; if (param < 0) { throw new ParseException("Spindle Speed must be positive", lineNumber); } Commands.Add(new Spindle() { Speed = param }); Words.RemoveAt(i); i--; continue; } if (Words[i].Command == 'G' && !MotionCommands.Contains(Words[i].Parameter)) { #region UnitPlaneDistanceMode double param = Words[i].Parameter; if (param == 90) { State.DistanceMode = ParseDistanceMode.Absolute; Words.RemoveAt(i); i--; continue; } if (param == 91) { State.DistanceMode = ParseDistanceMode.Incremental; Words.RemoveAt(i); i--; continue; } if (param == 90.1) { State.ArcDistanceMode = ParseDistanceMode.Absolute; Words.RemoveAt(i); continue; } if (param == 91.1) { State.ArcDistanceMode = ParseDistanceMode.Incremental; Words.RemoveAt(i); i--; continue; } if (param == 21) { State.Unit = ParseUnit.Metric; Words.RemoveAt(i); i--; continue; } if (param == 20) { State.Unit = ParseUnit.Imperial; Words.RemoveAt(i); i--; continue; } if (param == 17) { State.Plane = ArcPlane.XY; Words.RemoveAt(i); i--; continue; } if (param == 18) { State.Plane = ArcPlane.ZX; Words.RemoveAt(i); i--; continue; } if (param == 19) { State.Plane = ArcPlane.YZ; Words.RemoveAt(i); i--; continue; } if (param == 4) { if (Words.Count >= 2 && Words[i + 1].Command == 'P') { if (Words[i + 1].Parameter < 0) { throw new ParseException("Negative dwell time", lineNumber); } Commands.Add(new Dwell() { Seconds = Words[i + 1].Parameter }); Words.RemoveAt(i + 1); Words.RemoveAt(i); i--; continue; } } if (param == 54 || param == 94 || param == 40) { // discard Gxx words Words.RemoveAt(i); i--; continue; } throw new ParseException($"G{param} is not supported", lineNumber); #endregion } } if (Words.Count == 0) { return; } int MotionMode = State.LastMotionMode; if (Words.First().Command == 'G') { MotionMode = (int)Words.First().Parameter; State.LastMotionMode = MotionMode; Words.RemoveAt(0); } if (MotionMode < 0) { throw new ParseException("No Motion Mode active", lineNumber); } double UnitMultiplier = (State.Unit == ParseUnit.Metric) ? 1 : 25.4; Vector3 EndPos = State.Position; #region FindEndPos { int Incremental = (State.DistanceMode == ParseDistanceMode.Incremental) ? 1 : 0; for (int i = 0; i < Words.Count; i++) { if (Words[i].Command != 'X') { continue; } EndPos.X = Words[i].Parameter * UnitMultiplier + Incremental * EndPos.X; Words.RemoveAt(i); break; } for (int i = 0; i < Words.Count; i++) { if (Words[i].Command != 'Y') { continue; } EndPos.Y = Words[i].Parameter * UnitMultiplier + Incremental * EndPos.Y; Words.RemoveAt(i); break; } for (int i = 0; i < Words.Count; i++) { if (Words[i].Command != 'Z') { continue; } EndPos.Z = Words[i].Parameter * UnitMultiplier + Incremental * EndPos.Z; Words.RemoveAt(i); break; } } #endregion if (MotionMode != 0 && State.Feed <= 0) { throw new ParseException("Feed Rate Undefined", lineNumber); } if (MotionMode <= 1) { if (Words.Count > 0) { throw new ParseException("Motion Command must be last in line (unused Words in Block)", lineNumber); } Line motion = new Line(); motion.Start = State.Position; motion.End = EndPos; motion.Feed = State.Feed; motion.Rapid = MotionMode == 0; Commands.Add(motion); State.Position = EndPos; return; } double U, V; bool IJKused = false; switch (State.Plane) { default: U = State.Position.X; V = State.Position.Y; break; case ArcPlane.YZ: U = State.Position.Y; V = State.Position.Z; break; case ArcPlane.ZX: U = State.Position.Z; V = State.Position.X; break; } #region FindIJK { int ArcIncremental = (State.ArcDistanceMode == ParseDistanceMode.Incremental) ? 1 : 0; for (int i = 0; i < Words.Count; i++) { if (Words[i].Command != 'I') { continue; } switch (State.Plane) { case ArcPlane.XY: U = Words[i].Parameter * UnitMultiplier + ArcIncremental * State.Position.X; break; case ArcPlane.YZ: throw new ParseException("Current Plane is YZ, I word is invalid", lineNumber); case ArcPlane.ZX: V = Words[i].Parameter * UnitMultiplier + ArcIncremental * State.Position.X; break; } IJKused = true; Words.RemoveAt(i); break; } for (int i = 0; i < Words.Count; i++) { if (Words[i].Command != 'J') { continue; } switch (State.Plane) { case ArcPlane.XY: V = Words[i].Parameter * UnitMultiplier + ArcIncremental * State.Position.Y; break; case ArcPlane.YZ: U = Words[i].Parameter * UnitMultiplier + ArcIncremental * State.Position.Y; break; case ArcPlane.ZX: throw new ParseException("Current Plane is ZX, J word is invalid", lineNumber); } IJKused = true; Words.RemoveAt(i); break; } for (int i = 0; i < Words.Count; i++) { if (Words[i].Command != 'K') { continue; } switch (State.Plane) { case ArcPlane.XY: throw new ParseException("Current Plane is XY, K word is invalid", lineNumber); case ArcPlane.YZ: V = Words[i].Parameter * UnitMultiplier + ArcIncremental * State.Position.Z; break; case ArcPlane.ZX: U = Words[i].Parameter * UnitMultiplier + ArcIncremental * State.Position.Z; break; } IJKused = true; Words.RemoveAt(i); break; } } #endregion #region ResolveRadius for (int i = 0; i < Words.Count; i++) { if (Words[i].Command != 'R') { continue; } if (IJKused) { throw new ParseException("Both IJK and R notation used", lineNumber); } if (State.Position == EndPos) { throw new ParseException("arcs in R-notation must have non-coincident start and end points", lineNumber); } double Radius = Words[i].Parameter * UnitMultiplier; if (Radius == 0) { throw new ParseException("Radius can't be zero", lineNumber); } double A, B; switch (State.Plane) { default: A = EndPos.X; B = EndPos.Y; break; case ArcPlane.YZ: A = EndPos.Y; B = EndPos.Z; break; case ArcPlane.ZX: A = EndPos.Z; B = EndPos.X; break; } A -= U; //(AB) = vector from start to end of arc along the axes of the current plane B -= V; /* * double C = -B; //(UV) = vector perpendicular to (AB) * double D = A; * * { //normalize perpendicular vector * double perpLength = Math.Sqrt(C * C + D * D); * C /= perpLength; * D /= perpLength; * } * * double PerpSquare = (Radius * Radius) - ((A * A + B * B) / 4); * * if (PerpSquare < 0) * throw new ParseException("arc radius too small to reach both ends", lineNumber); * * double PerpLength = Math.Sqrt(PerpSquare); * * if (MotionMode == 3 ^ Radius < 0) * PerpLength = -PerpLength; * * U += (A / 2) + C * (PerpLength); * V += (B / 2) + (D * PerpLength); */ //see grbl/gcode.c double h_x2_div_d = 4.0 * (Radius * Radius) - (A * A + B * B); if (h_x2_div_d < 0) { throw new ParseException("arc radius too small to reach both ends", lineNumber); } h_x2_div_d = -Math.Sqrt(h_x2_div_d) / Math.Sqrt(A * A + B * B); if (MotionMode == 3 ^ Radius < 0) { h_x2_div_d = -h_x2_div_d; } U += 0.5 * (A - (B * h_x2_div_d)); V += 0.5 * (B + (A * h_x2_div_d)); Words.RemoveAt(i); break; } #endregion Arc arc = new Arc(); arc.Start = State.Position; arc.End = EndPos; arc.Feed = State.Feed; arc.Direction = (MotionMode == 2) ? ArcDirection.CW : ArcDirection.CCW; arc.U = U; arc.V = V; arc.Plane = State.Plane; Commands.Add(arc); State.Position = EndPos; return; }
public override void InsertLine(int index, Line line) { throw new NotImplementedException(); }
public bool Snap(IGeometry igeometry_0, IPoint ipoint_0, double double_0) { bool flag; double num = 0; int num1 = 0; int num2 = 0; bool flag1 = true; IPoint pointClass = new ESRI.ArcGIS.Geometry.Point(); bool flag2 = false; IPoint ipoint0 = ipoint_0; IPoint igeometry0 = null; if (igeometry_0 is IPoint) { igeometry0 = (IPoint)igeometry_0; } else if (igeometry_0 != null) { igeometry0 = ((IPointCollection)igeometry_0).Point[0]; } int num3 = 0; while (true) { if (num3 < this.ifeatureCache_0.Count) { IHitTest shape = (IHitTest)this.ifeatureCache_0.Feature[num3].Shape; if (shape.HitTest(ipoint0, double_0, esriGeometryHitPartType.esriGeometryPartBoundary, pointClass, ref num, ref num1, ref num2, ref flag1)) { ILine segment = ((ISegmentCollection)((IGeometryCollection)shape).Geometry[num1]).Segment[num2] as ILine; if (segment != null) { ILine lineClass = new Line(); lineClass.PutCoords(segment.FromPoint, igeometry0); double angle = lineClass.Angle; if (angle < 0) { angle = angle + 6.28318530717959; } double angle1 = segment.Angle; if (angle1 < 0) { angle1 = angle1 + 6.28318530717959; } double num4 = angle1 - angle; if (num4 < 0) { num4 = num4 + 6.28318530717959; } double num5 = Math.Cos(num4) * lineClass.Length; if (num5 <= segment.Length) { IPoint point = new Point() { X = segment.FromPoint.X + num5 * Math.Cos(segment.Angle), Y = segment.FromPoint.Y + num5 * Math.Sin(segment.Angle), Z = pointClass.Z }; ipoint_0.PutCoords(point.X, point.Y); flag = true; break; } } } num3++; } else { flag = flag2; break; } } return(flag); }
/// <summary> /// This method will trim a line from a start point to end point /// This method can trim only horizontal or vertical line /// </summary> /// <param name="lineToTrim"></param> /// <param name="trimStartPoint"></param> /// <param name="trimEndPoint"></param> public void trimLine(Line lineToTrim, Point3d trimStartPoint, Point3d trimEndPoint) { }
public static Vector3 Intersect(Plane plane, Line line) { double t = (plane.Position - line.V1).Dot(plane.Normal) / line.Direction.Dot(plane.Normal); return(line.At(t)); }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { string input = Interaction.InputBox("Enter the panel width in millimeters", "CLT Creator", "250", -1, -1); double inputnum = Convert.ToDouble(input); /* * var hi = new TaskDialog("Hi") * { * MainContent = inputnum, * MainIcon = TaskDialogIcon.TaskDialogIconInformation, * CommonButtons = TaskDialogCommonButtons.Ok * }; * hi.Show(); */ try { if (null == commandData) { throw new ArgumentNullException("commandData"); } UIApplication uiapp = commandData.Application; Application app = uiapp.Application; UIDocument uidoc = uiapp.ActiveUIDocument; Document doc = uidoc.Document; Reference r = null; try { r = uidoc.Selection.PickObject( ObjectType.Element, new WallSelectionFilter(), "Select a wall to split into panels"); } catch (Autodesk.Revit.Exceptions .OperationCanceledException) { return(Result.Cancelled); } Wall wall = (r == null || r.ElementId == ElementId.InvalidElementId) ? null : doc.GetElement(r.ElementId) as Wall; if (wall == null) { message = "Unable to retrieve wall."; return(Result.Failed); } LocationCurve location = wall.Location as LocationCurve; if (null == location) { message = "Unable to retrieve wall location curve."; return(Result.Failed); } Line line = location.Curve as Line; if (null == location) { message = "Unable to retrieve wall location line."; return(Result.Failed); } using (Transaction transaction = new Transaction(doc)) { transaction.Start("Building panels"); IList <ElementId> wallList = new List <ElementId>(1); wallList.Add(r.ElementId); if (PartUtils.AreElementsValidForCreateParts( doc, wallList)) { PartUtils.CreateParts(doc, wallList); doc.Regenerate(); ICollection <ElementId> parts = PartUtils.GetAssociatedParts( doc, wall.Id, false, false); if (PartUtils.ArePartsValidForDivide( doc, parts)) { double divisions = line.Length / (inputnum / 25.4 / 12); XYZ origin = line.Origin; XYZ delta = line.Direction.Multiply( inputnum / 25.4 / -12); Transform shiftDelta = Transform.CreateTranslation(delta); // Construct a 90 degree rotation in the // XY plane around the line start point Transform rotation = Transform.CreateRotationAtPoint( XYZ.BasisZ, 0.5 * Math.PI, origin); // A vector perpendicular to the wall with // length equal to twice the wall witdh XYZ wallWidthVector = rotation.OfVector( line.Direction.Multiply(2 * wall.Width)); Curve intersectionLine = Line.CreateBound( // Line.CreateBound location.Curve.GetEndPoint(1) + wallWidthVector, location.Curve.GetEndPoint(1) - wallWidthVector); IList <Curve> curveArray = new List <Curve>(); //Jeremy's Modelline Code //XYZ v = 2*wallWidthVector; //double dxy = Math.Abs(v.X) + Math.Abs(v.Y); //XYZ w = (dxy > 1.0e-9)? XYZ.BasisZ: XYZ.BasisY; //XYZ norm = v.CrossProduct(w).Normalize(); //Plane plane = Plane.CreateByNormalAndOrigin(norm, origin + wallWidthVector); //SketchPlane sketchPlane = SketchPlane.Create(doc, plane); //Jeremy's code end for (int i = 1; i < divisions; ++i) { intersectionLine = intersectionLine.CreateTransformed(shiftDelta); //ModelCurve curve = doc.IsFamilyDocument ? doc.FamilyCreate.NewModelCurve(intersectionLine, sketchPlane) : doc.Create.NewModelCurve(intersectionLine, sketchPlane); curveArray.Add(intersectionLine); } SketchPlane divisionSketchPlane = SketchPlane.Create(doc, Plane.CreateByNormalAndOrigin(XYZ.BasisZ, origin)); // An empty list of intersecting ElementIds IList <ElementId> intersectionElementIds = new List <ElementId>(); PartUtils.DivideParts(doc, parts, intersectionElementIds, curveArray, divisionSketchPlane.Id); } doc.ActiveView.PartsVisibility = PartsVisibility.ShowPartsOnly; } transaction.Commit(); } return(Result.Succeeded); } catch (Exception e) { message = e.Message; return(Result.Failed); } }
public void door() { // Get the current document and database Document acDoc = Application.DocumentManager.MdiActiveDocument; Database acCurDb = acDoc.Database; pointOptions = new PromptPointOptions(""); flaPoint = new Point3d(flagPoint); //Getting lower corner point Point3d gtPoint = GetPoint("Please select the outside corner point :"); if (gtPoint == flaPoint) { return; } Point3d cornerPointOut = gtPoint; //Getting upper corner point gtPoint = GetPoint("Please select the inside corner point :"); if (gtPoint == flaPoint) { return; } Point3d cornerPointIn = gtPoint; PromptStringOptions stringPrompt = new PromptStringOptions("\nEnter the start distance from outside corner :"); stringPrompt.AllowSpaces = false; //start distance PromptResult distanceString = ed.GetString(stringPrompt); if (distanceString.Status != PromptStatus.OK && decimal.TryParse(distanceString.StringResult, out _)) { return; } decimal startDistance; decimal.TryParse(distanceString.StringResult, out startDistance); //door width stringPrompt.Message = "\nEnter the door width :"; distanceString = ed.GetString(stringPrompt); if (distanceString.Status != PromptStatus.OK && decimal.TryParse(distanceString.StringResult, out _)) { return; } decimal doorWidth; decimal.TryParse(distanceString.StringResult, out doorWidth); //Getting direction gtPoint = GetPoint("Select the direction to place the door"); if (gtPoint == flaPoint) { return; } Point3d directionPoint = gtPoint; direction direction = GetDirection(cornerPointOut, directionPoint); //Wall offset calc double wallOffset = Math.Abs(cornerPointIn.Y - cornerPointOut.Y); ed.WriteMessage("\noffset distance :" + wallOffset); //Getting wall lines Line outsideLine = new Line(); Line insideLine = new Line(); using (Transaction tr = acCurDb.TransactionManager.StartTransaction()) { // Open the Block table for read BlockTable acBlkTbl; acBlkTbl = tr.GetObject(acCurDb.BlockTableId, OpenMode.ForRead) as BlockTable; // Open the Block table record Model space for write BlockTableRecord acBlkTblRec; acBlkTblRec = tr.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; // Request for objects to be selected in the drawing area PromptSelectionOptions promptSelectionOptions = new PromptSelectionOptions(); promptSelectionOptions.MessageForAdding = "\nSelect Outside && inside line and press enter"; PromptSelectionResult SSPrompt = acDoc.Editor.GetSelection(promptSelectionOptions); //Line outsideLine = new Line(); //Line insideLine = new Line(); if (SSPrompt.Status == PromptStatus.OK && SSPrompt.Value.Count == 2) { foreach (PickPointSelectedObject ent in SSPrompt.Value) { if (ent.ObjectId.ObjectClass.DxfName == "LINE") { //Test inside or outside line and then assign /* * Create two test point on two line * Calculate distance from cornerpoint to testpoints * Larger distance means outside line and vice versa */ Point3d testPoint1 = new Point3d(), testPoint2 = new Point3d(); if (direction == direction.top || direction == direction.bottom) { if (direction == direction.top) { testPoint1 = new Point3d(cornerPointOut.X, cornerPointOut.Y + wallOffset + 5, 0); } else { testPoint1 = new Point3d(cornerPointOut.X, cornerPointOut.Y - wallOffset - 5, 0); } testPoint2 = new Point3d(cornerPointIn.X, testPoint1.Y, 0); } else if (direction == direction.right || direction == direction.left) { if (direction == direction.right) { testPoint1 = new Point3d(cornerPointOut.X + wallOffset + 5, cornerPointOut.Y, 0); } else { testPoint1 = new Point3d(cornerPointOut.X - wallOffset - 5, cornerPointOut.Y, 0); } testPoint2 = new Point3d(testPoint1.X, cornerPointIn.Y, 0); } //Distance of cornerpoint lower to testpoint double dist1 = GetDistBetPoints(cornerPointOut, testPoint1); double dist2 = GetDistBetPoints(cornerPointIn, testPoint2); Line tempL = tr.GetObject(ent.ObjectId, OpenMode.ForWrite) as Line; if (dist1 > dist2) { if (IsPointOnPolyline(ConvertToPolyline(tempL), testPoint1)) { outsideLine = tr.GetObject(ent.ObjectId, OpenMode.ForWrite) as Line; } else if (IsPointOnPolyline(ConvertToPolyline(tempL), testPoint2)) { insideLine = tr.GetObject(ent.ObjectId, OpenMode.ForWrite) as Line; } } else { if (IsPointOnPolyline(ConvertToPolyline(tempL), testPoint1)) { insideLine = tr.GetObject(ent.ObjectId, OpenMode.ForWrite) as Line; } else if (IsPointOnPolyline(ConvertToPolyline(tempL), testPoint2)) { outsideLine = tr.GetObject(ent.ObjectId, OpenMode.ForWrite) as Line; } } } } } else { ed.WriteMessage("\nCancelled or selected more than two line"); return; } //Trim operation Point3d lineStartPoint = outsideLine.StartPoint; Point3d lineEndPoint = outsideLine.EndPoint; Polyline polyl = ConvertToPolyline(outsideLine); //Calculate trimming points Point3d outsideTrimStart = new Point3d(), outsideTrimEnd = new Point3d(), insideTrimStart = new Point3d(), insideTrimEnd = new Point3d(); switch (direction) { case direction.right: outsideTrimStart = new Point3d(cornerPointOut.X + Convert.ToDouble(startDistance), cornerPointOut.Y, 0); outsideTrimEnd = new Point3d(outsideTrimStart.X + Convert.ToDouble(doorWidth), cornerPointOut.Y, 0); insideTrimStart = new Point3d(outsideTrimStart.X, cornerPointIn.Y, 0); insideTrimEnd = new Point3d(outsideTrimEnd.X, cornerPointIn.Y, 0); break; case direction.left: outsideTrimStart = new Point3d(cornerPointOut.X - Convert.ToDouble(startDistance), cornerPointOut.Y, 0); outsideTrimEnd = new Point3d(outsideTrimStart.X - Convert.ToDouble(doorWidth), cornerPointOut.Y, 0); insideTrimStart = new Point3d(outsideTrimStart.X, cornerPointIn.Y, 0); insideTrimEnd = new Point3d(outsideTrimEnd.X, cornerPointIn.Y, 0); break; case direction.top: outsideTrimStart = new Point3d(cornerPointOut.X, cornerPointOut.Y + Convert.ToDouble(startDistance), 0); outsideTrimEnd = new Point3d(cornerPointOut.X, outsideTrimStart.Y + Convert.ToDouble(doorWidth), 0); insideTrimStart = new Point3d(cornerPointIn.X, outsideTrimStart.Y, 0); insideTrimEnd = new Point3d(cornerPointIn.X, outsideTrimEnd.Y, 0); break; case direction.bottom: outsideTrimStart = new Point3d(cornerPointOut.X, cornerPointOut.Y - Convert.ToDouble(startDistance), 0); outsideTrimEnd = new Point3d(cornerPointOut.X, outsideTrimStart.Y - Convert.ToDouble(doorWidth), 0); insideTrimStart = new Point3d(cornerPointIn.X, outsideTrimStart.Y, 0); insideTrimEnd = new Point3d(cornerPointIn.X, outsideTrimEnd.Y, 0); break; } Line tempLine = new Line(lineStartPoint, outsideTrimStart); if (IsPointOnPolyline(ConvertToPolyline(tempLine), outsideTrimEnd)) { Point3d tempPoint = lineStartPoint; lineStartPoint = lineEndPoint; lineEndPoint = tempPoint; } Line line1 = new Line(lineStartPoint, outsideTrimStart); Line line2 = new Line(outsideTrimEnd, lineEndPoint); line1.SetDatabaseDefaults(); line2.SetDatabaseDefaults(); polyl.SetDatabaseDefaults(); acBlkTblRec.AppendEntity(line1); acBlkTblRec.AppendEntity(line2); acBlkTblRec.AppendEntity(polyl); tr.AddNewlyCreatedDBObject(line1, true); tr.AddNewlyCreatedDBObject(line2, true); tr.AddNewlyCreatedDBObject(polyl, true); //Upperline trim lineStartPoint = insideLine.StartPoint; lineEndPoint = insideLine.EndPoint; Polyline polyl2 = ConvertToPolyline(insideLine); //Need to check trimStartPoint and trimEndPoint lies into the line or not if (!(IsPointOnPolyline(polyl2, insideTrimStart) && IsPointOnPolyline(polyl2, insideTrimEnd))) { ed.WriteMessage("\nTrim startpoint and endpoint are not on the line to trim"); return; } tempLine = new Line(lineStartPoint, insideTrimStart); if (IsPointOnPolyline(ConvertToPolyline(tempLine), insideTrimEnd)) { Point3d tempPoint = lineStartPoint; lineStartPoint = lineEndPoint; lineEndPoint = tempPoint; } Line line3 = new Line(lineStartPoint, insideTrimStart); Line line4 = new Line(insideTrimEnd, lineEndPoint); line3.SetDatabaseDefaults(); line4.SetDatabaseDefaults(); polyl.SetDatabaseDefaults(); polyl2.SetDatabaseDefaults(); acBlkTblRec.AppendEntity(line3); acBlkTblRec.AppendEntity(line4); acBlkTblRec.AppendEntity(polyl2); tr.AddNewlyCreatedDBObject(line3, true); tr.AddNewlyCreatedDBObject(line4, true); tr.AddNewlyCreatedDBObject(polyl2, true); //Delete the base line to complete trimming operation polyl.Erase(); polyl2.Erase(); outsideLine.Erase(); insideLine.Erase(); //Add two more line connecting four trimming points Line startTrimConnection = new Line(outsideTrimStart, insideTrimStart); Line endTrimConnection = new Line(outsideTrimEnd, insideTrimEnd); startTrimConnection.SetDatabaseDefaults(); endTrimConnection.SetDatabaseDefaults(); acBlkTblRec.AppendEntity(startTrimConnection); acBlkTblRec.AppendEntity(endTrimConnection); tr.AddNewlyCreatedDBObject(startTrimConnection, true); tr.AddNewlyCreatedDBObject(endTrimConnection, true); ed.Regen(); tr.Commit(); } Point3d insertionPoint = GetPoint("Select door block insertion point"); InsertBlock(insertionPoint, "door2", Convert.ToDouble(doorWidth)); }
protected override void OnMouseDown(MouseEventArgs e) { base.OnMouseDown(e); this.Focus(); if (e.Clicks == 2) { if (e.X < 2 + _gutterWidth + 1 + _addressWidth + 1) { return; } int y = e.Y / _lineHeight; int lineIndex = Math.Min(_firstVisibleLine + y, _totalLines); int currentLine = lineIndex; int lineSum; int index = this.IndexOfMethodAt(currentLine, out lineSum); if (index == -1) { return; } int lineOffset = currentLine - lineSum; if (currentLine <= _lastVisibleLine) { if (index < _codeCache.Methods.Count) { MethodBody body = _codeCache.Methods[index++]; List <Line> lines = (List <Line>)body.UserCache; if (lines == null) { lines = this.CacheMethod(body); } Line line = lines[lineOffset]; switch (line.Type) { case LineType.Label: Debug.WriteLine(line.Instruction.Label.ToString()); break; case LineType.Instruction: Debug.WriteLine(line.Instruction.ToString()); if (line.Instruction.Reference is CodeReference) { uint target = line.Instruction.Reference.Address; this.NavigateToAddress(target); } else if (line.Instruction.Reference is Noxa.Emulation.Psp.Player.Debugger.Model.Label) { uint target = line.Instruction.Reference.Address; this.NavigateToAddress(target); } else if (line.Instruction.Reference is MemoryReference) { uint target = line.Instruction.Reference.Address; _debugger.MemoryTool.NavigateToAddress(target); _debugger.MemoryTool.Activate(); } break; } } } } }
private int DrawMethod(Graphics g, MethodBody body, List <Line> lines, int x, int y, int lineOffset, int maxLines) { int addressx = x + _gutterWidth + 1; int codex = addressx + _addressWidth + 1 + 6; int opcodex = codex + _labelWidth / 3 + 6; int operandx = opcodex + _opcodeWidth; int refx = 300; Brush codeBrush = this.Enabled ? _instrFontBrush : _disabledFontBrush; Brush addressBrush = this.Enabled ? _addressFontBrush : _disabledFontBrush; // -- lines -- for (int n = lineOffset; n < lines.Count; n++) { Line line = lines[n]; Instruction instr = line.Instruction; if (body.UserTop + n == _highlightedLine) { g.FillRectangle(SystemBrushes.GradientInactiveCaption, codex, y, this.ClientRectangle.Width - codex - 5, _lineHeight + 2); } switch (line.Type) { case LineType.Header: { string fullName = string.Format("// {0}::{1}", body.Module.Name, body.Name); g.DrawString(fullName, _font, _commentFontBrush, codex, y); g.DrawLine(_commentLinePen, codex + (_charSize.Width * (fullName.Length + 1)), y + (_charSize.Height / 2.0f), this.ClientRectangle.Width - 10, y + (_charSize.Height / 2.0f)); } break; case LineType.Footer: { } break; case LineType.Label: { g.DrawString(instr.Label.Name + ":", _font, _labelFontBrush, codex, y, _stringFormat); } break; case LineType.Instruction: { // Gutter if (instr.Breakpoint != null) { Image icon = (instr.Breakpoint.Enabled == true) ? _breakpointOnIcon : _breakpointOffIcon; g.DrawImage(icon, x + 2, y, 15, 15); } if ((_debugger.State != DebuggerState.Running) && (_debugger.PC == instr.Address)) { g.DrawImage(_statementIcon, x + 3, y, 14, 15); } // Address g.DrawString(string.Format("{0:X8}", instr.Address), _font, addressBrush, addressx + 6, y, _stringFormat); // Instruction int realx = operandx; if (instr.Code == 0x0) { g.DrawString("nop", _font, _disabledFontBrush, opcodex, y, _stringFormat); } else { if (instr.Opcode == null) { g.DrawString("UNKNOWN", _font, codeBrush, opcodex, y, _stringFormat); } else { g.DrawString(instr.Opcode.ToString(), _font, codeBrush, opcodex, y, _stringFormat); // Operands for (int m = 0; m < instr.Operands.Length; m++) { Operand op = instr.Operands[m]; string resolved = instr.GetResolvedOperandString(op, this.UseHex); Brush fontBrush = codeBrush; switch (op.Type) { case OperandType.BranchTarget: fontBrush = _referenceFontBrush; break; case OperandType.JumpTarget: fontBrush = _referenceFontBrush; break; } g.DrawString(resolved, _font, fontBrush, realx, y, _stringFormat); realx += ( int )_charSize.Width * resolved.Length; bool last = (m == instr.Operands.Length - 1); if (last == false) { g.DrawString(", ", _font, codeBrush, realx - 2, y, _stringFormat); realx += ( int )_charSize.Width * 2 - 2; } } } } MemoryReference memRef = instr.Reference as MemoryReference; if (memRef != null) { Variable var = _debugger.DebugHost.Database.FindSymbol(memRef.Address) as Variable; string name; if ((var != null) && (var.Name != null)) { name = var.Name; } else { name = memRef.Address.ToString("X8"); } g.DrawString(name, _font, _referenceFontBrush, refx, y, _stringFormat); } // Annotations //if( instr.Annotation != null ) // g.DrawString( instr.Annotation, _font, _referenceFontBrush, realx + 10, y, _stringFormat ); // Comments // TODO _commentFontBrush } break; } y += _lineHeight; maxLines--; if (maxLines == 0) { break; } } return(y); }
private void lineContextMenuStrip_Opening(object sender, CancelEventArgs e) { this.renameToolStripMenuItem.Visible = false; this.valueToolStripTextBox.Visible = false; this.toolStripSeparator5.Visible = false; this.copyOperandToolStripMenuItem.Visible = false; this.goToTargetToolStripMenuItem.Visible = false; this.toolStripSeparator4.Visible = false; MethodBody method; Line line = this.GetContextLine(out method); if (line == null) { return; } switch (line.Type) { case LineType.Header: this.renameToolStripMenuItem.Visible = true; this.toolStripSeparator4.Visible = true; return; case LineType.Label: this.renameToolStripMenuItem.Visible = true; this.toolStripSeparator4.Visible = true; return; default: if (line.Instruction == null) { e.Cancel = true; return; } break; } Instruction instr = line.Instruction; bool hasOperand = (_contextOperand != null); bool referenceOperand = false; if (hasOperand == true) { // Only allow editing if it's a register bool readOnly = (_contextOperand.Register == null) || (_contextOperand.Register.ReadOnly == true); this.valueToolStripTextBox.ReadOnly = readOnly; // Only allow goto if a reference referenceOperand = (_contextOperand.Type == OperandType.BranchTarget) || (_contextOperand.Type == OperandType.JumpTarget) || (_contextOperand.Type == OperandType.MemoryAccess); if ((referenceOperand == true) && (_contextOperand.Type == OperandType.MemoryAccess)) { this.goToTargetToolStripMenuItem.Text = "&Go to Memory Address"; this.goToTargetToolStripMenuItem.Image = Properties.Resources.MemoryIcon; } else { this.goToTargetToolStripMenuItem.Text = "&Go to Code Address"; this.goToTargetToolStripMenuItem.Image = Properties.Resources.DisassemblyIcon; } //this.valueToolStripTextBox.Text = this.RequestOperandValue( instr, _contextOperand, false ); this.valueToolStripTextBox.Modified = false; } this.valueToolStripTextBox.Visible = hasOperand; this.toolStripSeparator5.Visible = hasOperand; this.copyOperandToolStripMenuItem.Visible = hasOperand; this.goToTargetToolStripMenuItem.Visible = hasOperand && referenceOperand; this.toolStripSeparator4.Visible = hasOperand; }
private void renameToolStripMenuItem_Click(object sender, System.EventArgs e) { MethodBody method; Line line = this.GetContextLine(out method); if (line == null) { return; } RenameTarget target = RenameTarget.Method; string value = ""; switch (line.Type) { case LineType.Header: target = RenameTarget.Method; value = method.Name; break; case LineType.Label: target = RenameTarget.Label; value = line.Instruction.Label.Name; break; default: return; } RenameDialog dialog = new RenameDialog(); dialog.Target = target; dialog.Value = value; if (dialog.ShowDialog(this.FindForm()) == DialogResult.OK) { switch (line.Type) { case LineType.Header: method.Name = dialog.Value; { bool found = false; foreach (TagInfo tag in _debugger.UserData.CodeTags.MethodNames) { if (tag.Address == method.Address) { found = true; tag.Value = dialog.Value; break; } } if (found == false) { TagInfo tag = new TagInfo(); tag.Address = method.Address; tag.Value = dialog.Value; _debugger.UserData.CodeTags.MethodNames.Add(tag); } _debugger.CodeCache.Version++; _debugger.UserData.Save(); } break; case LineType.Label: line.Instruction.Label.Name = dialog.Value; { bool found = false; foreach (TagInfo tag in _debugger.UserData.CodeTags.LabelNames) { if (tag.Address == line.Instruction.Address) { found = true; tag.Value = dialog.Value; break; } } if (found == false) { TagInfo tag = new TagInfo(); tag.Address = line.Instruction.Address; tag.Value = dialog.Value; _debugger.UserData.CodeTags.LabelNames.Add(tag); } _debugger.CodeCache.Version++; _debugger.UserData.Save(); } break; } this.Invalidate(); } this.ContextReturn(); }
public void GetLengthTest_Success() { Assert.AreEqual(4.0, Line.GetLength(0, 4, 0, 0)); }
internal virtual SamplingGrid GetSamplingGrid(FinderPattern finderPattern, AlignmentPattern alignmentPattern) { Point[][] center = alignmentPattern.getCenter(); int version = finderPattern.Version; int num = version / 7 + 2; center[0][0] = finderPattern.GetCenter(0); center[num - 1][0] = finderPattern.GetCenter(1); center[0][num - 1] = finderPattern.GetCenter(2); int sqrtNumArea = num - 1; SamplingGrid samplingGrid = new SamplingGrid(sqrtNumArea); Axis axis = new Axis(finderPattern.GetAngle(), finderPattern.GetModuleSize()); for (int ay = 0; ay < sqrtNumArea; ++ay) { for (int ax = 0; ax < sqrtNumArea; ++ax) { QRCodeImageReader.ModulePitch modulePitch = new QRCodeImageReader.ModulePitch(this); Line line1 = new Line(); Line line2 = new Line(); axis.ModulePitch = finderPattern.GetModuleSize(); Point[][] logicalCenter = AlignmentPattern.getLogicalCenter(finderPattern); Point point1 = center[ax][ay]; Point point2 = center[ax + 1][ay]; Point point3 = center[ax][ay + 1]; Point point4 = center[ax + 1][ay + 1]; Point point5 = logicalCenter[ax][ay]; Point point6 = logicalCenter[ax + 1][ay]; Point point7 = logicalCenter[ax][ay + 1]; Point point8 = logicalCenter[ax + 1][ay + 1]; if (ax == 0 && ay == 0) { if (sqrtNumArea == 1) { point1 = axis.translate(point1, -3, -3); point2 = axis.translate(point2, 3, -3); point3 = axis.translate(point3, -3, 3); point4 = axis.translate(point4, 6, 6); point5.Translate(-6, -6); point6.Translate(3, -3); point7.Translate(-3, 3); point8.Translate(6, 6); } else { point1 = axis.translate(point1, -3, -3); point2 = axis.translate(point2, 0, -6); point3 = axis.translate(point3, -6, 0); point5.Translate(-6, -6); point6.Translate(0, -6); point7.Translate(-6, 0); } } else if (ax == 0 && ay == sqrtNumArea - 1) { point1 = axis.translate(point1, -6, 0); point3 = axis.translate(point3, -3, 3); point4 = axis.translate(point4, 0, 6); point5.Translate(-6, 0); point7.Translate(-6, 6); point8.Translate(0, 6); } else if (ax == sqrtNumArea - 1 && ay == 0) { point1 = axis.translate(point1, 0, -6); point2 = axis.translate(point2, 3, -3); point4 = axis.translate(point4, 6, 0); point5.Translate(0, -6); point6.Translate(6, -6); point8.Translate(6, 0); } else if (ax == sqrtNumArea - 1 && ay == sqrtNumArea - 1) { point3 = axis.translate(point3, 0, 6); point2 = axis.translate(point2, 6, 0); point4 = axis.translate(point4, 6, 6); point7.Translate(0, 6); point6.Translate(6, 0); point8.Translate(6, 6); } else if (ax == 0) { point1 = axis.translate(point1, -6, 0); point3 = axis.translate(point3, -6, 0); point5.Translate(-6, 0); point7.Translate(-6, 0); } else if (ax == sqrtNumArea - 1) { point2 = axis.translate(point2, 6, 0); point4 = axis.translate(point4, 6, 0); point6.Translate(6, 0); point8.Translate(6, 0); } else if (ay == 0) { point1 = axis.translate(point1, 0, -6); point2 = axis.translate(point2, 0, -6); point5.Translate(0, -6); point6.Translate(0, -6); } else if (ay == sqrtNumArea - 1) { point3 = axis.translate(point3, 0, 6); point4 = axis.translate(point4, 0, 6); point7.Translate(0, 6); point8.Translate(0, 6); } if (ax == 0) { point6.Translate(1, 0); point8.Translate(1, 0); } else { point5.Translate(-1, 0); point7.Translate(-1, 0); } if (ay == 0) { point7.Translate(0, 1); point8.Translate(0, 1); } else { point5.Translate(0, -1); point6.Translate(0, -1); } int width = point6.X - point5.X; int height = point7.Y - point5.Y; if (version < 7) { width += 3; height += 3; } modulePitch.top = this.GetAreaModulePitch(point1, point2, width - 1); modulePitch.left = this.GetAreaModulePitch(point1, point3, height - 1); modulePitch.bottom = this.GetAreaModulePitch(point3, point4, width - 1); modulePitch.right = this.GetAreaModulePitch(point2, point4, height - 1); line1.SetP1(point1); line2.SetP1(point1); line1.SetP2(point3); line2.SetP2(point2); samplingGrid.InitGrid(ax, ay, width, height); for (int index = 0; index < width; ++index) { Line line3 = new Line(line1.GetP1(), line1.GetP2()); axis.Origin = line3.GetP1(); axis.ModulePitch = modulePitch.top; line3.SetP1(axis.translate(index, 0)); axis.Origin = line3.GetP2(); axis.ModulePitch = modulePitch.bottom; line3.SetP2(axis.translate(index, 0)); samplingGrid.SetXLine(ax, ay, index, line3); } for (int index = 0; index < height; ++index) { Line line3 = new Line(line2.GetP1(), line2.GetP2()); axis.Origin = line3.GetP1(); axis.ModulePitch = modulePitch.left; line3.SetP1(axis.translate(0, index)); axis.Origin = line3.GetP2(); axis.ModulePitch = modulePitch.right; line3.SetP2(axis.translate(0, index)); samplingGrid.SetYLine(ax, ay, index, line3); } } } return(samplingGrid); }
/// <summary> /// Given a list of tokens, turn it into a list of lines. /// The lines will satisfy the following properties: /// - No line will be longer than the maxLineWidth /// - No token will be split unless it is both /// - the first token on a line /// - too long to fit on the line /// - No line will contain any newline characters /// /// Note that width is not measured in character count, but in /// character width provided by the given delegate /// </summary> public static void Wrap(string source, List <Token> tokens, List <Line> lines, Func <char, float> widthFunc, float maxLineWidth) { if (tokens.Count == 0) { return; } int tokenIndex = 0; Token token = tokens[0]; while (true) { if (token.IsNewline(source)) { lines.Add(new Line() { start = token.start, length = 0, width = 0 }); goto LOOP_END; } NEW_LINE_CONTINUE_TOKEN: float firstTokenWidth = widthFunc(source[token.start]); //Line starts out equal to the first character of the first token Line line = new Line() { start = token.start, end = token.end, width = firstTokenWidth }; //Add as many of the rest of the characters of the token as we can for (int i = token.start + 1; i < token.end; i++) { float charWidth = widthFunc(source[i]); //If the line gets too big, we are forced to truncate! if (firstTokenWidth + charWidth > maxLineWidth) { line.end = i; line.width = firstTokenWidth; lines.Add(line); token.start = i; //Start a new line with the remainder of the current token goto NEW_LINE_CONTINUE_TOKEN; } firstTokenWidth += charWidth; } //Set line equal to the first token line.width = firstTokenWidth; line.length = token.length; //Move to the next token to begin adding them to the line tokenIndex++; if (tokenIndex >= tokens.Count) { //Line only contains first token, which cannot be whitespace, so we don't trim lines.Add(line); return; } token = tokens[tokenIndex]; //Fit the rest of the tokens on this line while (true) { //If the token is a newline, simply add the line and finish the main loop if (token.IsNewline(source)) { line.TrimEnd(source, widthFunc); lines.Add(line); break; } //If a non-whitespace token is too big, finish the line float tokenWidth = token.GetWidth(source, widthFunc); if (line.width + tokenWidth > maxLineWidth && !token.IsWhitespace(source)) { line.TrimEnd(source, widthFunc); lines.Add(line); //Go start a new line with the current token goto NEW_LINE_CONTINUE_TOKEN; } //Otherwise append to the line and keep trying tokens line.length += token.length; line.width += tokenWidth; tokenIndex++; if (tokenIndex >= tokens.Count) { lines.Add(line); return; } token = tokens[tokenIndex]; } LOOP_END: tokenIndex++; if (tokenIndex >= tokens.Count) { return; } token = tokens[tokenIndex]; } }
public void SameVertex_ThrowsException() { // Setup/Test Line l1 = new Line(1.0, 2.0, 1.0, 2.0); }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { var uiapp = commandData.Application; var uidoc = uiapp.ActiveUIDocument; var doc = uidoc.Document; var sel = uidoc.Selection; var acview = doc.ActiveView; while (true) { try { var wireref = sel.PickObject(ObjectType.Element, doc.GetSelectionFilter(m => m is Wire)); var wire = wireref.GetElement(doc) as Wire; //var connectors = (wire).ConnectorManager.Connectors.PhysicalConToList(); var locationcurve = wire.Location as LocationCurve; //var con1 = connectors.First(); //var con2 = connectors.Last(); //var origin1 = con1.Origin; //var origin2 = con2.Origin; //var dir1 = connectors.First().CoordinateSystem.BasisZ; //var dir2 = connectors.Last().CoordinateSystem.BasisZ; //var line1 = Line.CreateUnbound(origin1, dir1); //var line2 = Line.CreateUnbound(origin2, dir2); var intersection = default(XYZ); //if (!(locationcurve.Curve is Line)) //{ // MessageBox.Show("本功能不适应于曲线类型的导线"); //} var tempoint = sel.PickPoint(); var linefirst = Line.CreateBound(wire.GetVertex(0), wire.GetVertex(1)); var vertexcount = wire.NumberOfVertices; var linelast = Line.CreateBound(wire.GetVertex(vertexcount - 2), wire.GetVertex(vertexcount - 1)); var globalpoint = wireref.GlobalPoint; globalpoint = new XYZ(globalpoint.X, globalpoint.Y, linefirst.StartPoint().Z); if (!globalpoint.IsOnLine(linefirst) && !globalpoint.IsOnLine(linelast)) { MessageBox.Show("本功能不适应于曲线类型的导线 选择起始端或结束端导线" //+ Environment.NewLine + //globalpoint.IsOnLine(linefirst).ToString() + Environment.NewLine + //globalpoint.IsOnLine(linelast).ToString() + Environment.NewLine + //globalpoint.ToString() + Environment.NewLine + //linefirst.StartPoint().ToString() + Environment.NewLine + //linelast.StartPoint().ToString() ); continue; } Transaction ts1 = new Transaction(doc, "更改导线"); ts1.Start(); if (vertexcount > 2) { if (globalpoint.IsOnLine(linefirst)) { tempoint = tempoint.ProjectToXLine(linefirst); wire.SetVertex(0, tempoint); } else if (globalpoint.IsOnLine(linelast)) { tempoint = tempoint.ProjectToXLine(linelast); wire.SetVertex(vertexcount - 1, tempoint); } } else if (vertexcount == 2) { var startpo = wire.GetVertex(0); var endpo = wire.GetVertex(1); if (globalpoint.DistanceTo(startpo) < globalpoint.DistanceTo(endpo)) { tempoint = tempoint.ProjectToXLine(linefirst); wire.SetVertex(0, tempoint); } else { tempoint = tempoint.ProjectToXLine(linelast); wire.SetVertex(vertexcount - 1, tempoint); } } ts1.Commit(); } catch (Exception) { break; } } return(Result.Succeeded); }
public override int GetHashCode() { unchecked { return((string.IsNullOrEmpty(MachineAddr) ? 0 : MachineAddr.GetHashCode() * 397) ^ (string.IsNullOrEmpty(Line) ? 0 : Line.GetHashCode())); } }
public static bool Contains(Line containingLine, Segment containedSegment) { // Contenir un segment revient à contenir la droite sur laquelle se trouve le segment return LineWithLine.Contains(containingLine, containedSegment); }
/// <summary> /// Execute the command /// </summary> public override void ExecuteBuild() { // Get the source and target streams string Stream = ParseParamValue("Stream", P4Env.BuildRootP4); string Changes = ParseParamValue("Changes", null); string Lockdown = ParseParamValue("Lockdown", "Nick.Penwarden"); bool bPlatformSplit = !ParseParam("CombinePlatforms"); // Get changes which haven't been copied up from the current stream string AllDescriptions; string SourceStream; string VerbosityFlag = bPlatformSplit ? "" : "-l"; int LastCl; string[] Platforms = GetPlatformNames(); StringBuilder[] DescriptionBuilders = new StringBuilder[Platforms.Length]; for (int Index = 0; Index < Platforms.Length; Index++) { DescriptionBuilders[Index] = new StringBuilder(); } if (Changes == null) { IProcessResult Result = P4.P4(String.Format("interchanges {0} -S {1}", VerbosityFlag, Stream), AllowSpew: false); AllDescriptions = Result.Output; SourceStream = Stream; // Get the last submitted change in the source stream List <P4Connection.ChangeRecord> ChangeRecords; if (!P4.Changes(out ChangeRecords, String.Format("-m1 {0}/...", SourceStream), AllowSpew: false)) { throw new AutomationException("Couldn't get changes for this branch"); } LastCl = ChangeRecords[0].CL; } else { IProcessResult Result = P4.P4(String.Format("changes {0} {1}", VerbosityFlag, Changes), AllowSpew: false); AllDescriptions = Result.Output; SourceStream = Regex.Replace(Changes, @"(\/(?:\/[^\/]*){2}).*", "$1"); LastCl = Int32.Parse(Regex.Replace(Changes, ".*,", "")); } if (bPlatformSplit) { string[] Lines = AllDescriptions.Split("\n".ToCharArray()); foreach (string Line in Lines) { // @todo replace with regexes!! string[] Tokens = Line.Split(" ".ToCharArray()); if (Tokens.Length > 2 && Tokens[0] == "Change") { IProcessResult Result = P4.P4(String.Format("describe -s {0}", Tokens[1]), AllowSpew: false); // Affected files ... is the splitting point int AffectedFilesPos = Result.Output.IndexOf("Affected files ..."); string Description = Result.Output.Substring(0, AffectedFilesPos); string Files = Result.Output.Substring(AffectedFilesPos); // look for the NDA platforms in the list of files (skipping over the "no" and "multi" platforms int WhichPlatform = 0; for (int Index = 2; Index < Platforms.Length; Index++) { // we search by directory in the form of /Platform/ if (Files.Contains("/" + Platforms[Index] + "/")) { // if we contained multiple files, then we put into the Multi file, and someone will have to manually deal with it!! if (WhichPlatform == 0) { WhichPlatform = Index; } else { WhichPlatform = 1; } } } // add this description to the proper platform DescriptionBuilders[WhichPlatform].AppendLine(Description); } } } else { DescriptionBuilders[0].Append(AllDescriptions); } for (int PlatformIndex = 0; PlatformIndex < Platforms.Length; PlatformIndex++) { string Desc = DescriptionBuilders[PlatformIndex].ToString().Replace("\r\n", "\n"); // Clean any workspace names that may reveal internal information Desc = Regex.Replace(Desc, "(Change[^@]*)@.*", "$1", RegexOptions.Multiline); // Remove changes by the build machine Desc = Regex.Replace(Desc, "[^\n]*buildmachine\n(\n|\t[^\n]*\n)*", ""); // Remove all the tags we don't care about Desc = Regex.Replace(Desc, "^[ \t]*#(rb|fyi|codereview|lockdown)\\s.*$", "", RegexOptions.Multiline); // Empty out lines which just contain whitespace Desc = Regex.Replace(Desc, "^[ \t]+$", "", RegexOptions.Multiline); // Remove multiple consecutive blank lines Desc = Regex.Replace(Desc, "\n\n+", "\n\n"); // Only include one newline at the end of each description Desc = Regex.Replace(Desc, "\n+Change", "\n\nChange"); // Remove merge-only changelists Desc = Regex.Replace(Desc, "(?<=(^|\\n))Change .*\\s*Merging .* to .*\\s*\\n(?=(Change|$))", ""); if (string.IsNullOrEmpty(Desc)) { continue; } // Figure out the target stream IProcessResult StreamResult = P4.P4(String.Format("stream -o {0}", Stream), AllowSpew: false); if (StreamResult.ExitCode != 0) { throw new AutomationException("Couldn't get stream description for {0}", Stream); } string Target = P4Spec.FromString(StreamResult.Output).GetField("Parent"); if (Target == null) { throw new AutomationException("Couldn't get parent stream for {0}", Stream); } // Write the output file string OutputDirName = Path.Combine(CommandUtils.CmdEnv.LocalRoot, "Engine", "Intermediate"); CommandUtils.CreateDirectory(OutputDirName); string OutputFileName = Path.Combine(OutputDirName, string.Format("Changes{0}.txt", Platforms[PlatformIndex])); using (StreamWriter Writer = new StreamWriter(OutputFileName)) { if (PlatformIndex == 1) { Writer.WriteLine("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); Writer.WriteLine("CHANGES WITH MULTIPLE PLATFORMS!!! YOU MUST COPY THESE INTO THE OTHER ONES AS MAKES SENSE!!"); Writer.WriteLine("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); Writer.WriteLine(); Writer.WriteLine(); } else { Writer.WriteLine("Copying {0} to {1} (Source: {2} @ {3})", Stream, Target.Trim(), SourceStream, LastCl); Writer.WriteLine("#lockdown {0}", Lockdown); Writer.WriteLine(); Writer.WriteLine("====================================="); Writer.WriteLine("{0} MAJOR FEATURES + CHANGES", Platforms[PlatformIndex]); Writer.WriteLine("====================================="); Writer.WriteLine(); } foreach (string Line in Desc.Split('\n')) { Writer.WriteLine(Line); } Writer.WriteLine("DONE!"); } Log("Written {0}.", OutputFileName); // Open it with the default text editor Process.Start(OutputFileName); } }