public void SetUpFixture() { RubyMSBuildEngineHelper.InitMSBuildEngine(); List <ProjectBindingDescriptor> bindings = new List <ProjectBindingDescriptor>(); using (TextReader reader = RubyBindingAddInFile.ReadAddInFile()) { AddIn addin = AddIn.Load(reader, String.Empty); bindings.Add(new ProjectBindingDescriptor(AddInHelper.GetCodon(addin, "/SharpDevelop/Workbench/ProjectBindings", "Ruby"))); } ProjectBindingService.SetBindings(bindings); convertProjectCommand = new DerivedConvertProjectToRubyProjectCommand(); parseInfo = new ParseInformation(new DefaultCompilationUnit(new DefaultProjectContent())); convertProjectCommand.ParseInfo = parseInfo; convertProjectCommand.FileServiceDefaultEncoding = Encoding.Unicode; sourceProject = new MockProject(); sourceProject.Directory = @"d:\projects\test"; source = new FileProjectItem(sourceProject, ItemType.Compile, @"src\Program.cs"); targetProject = (RubyProject)convertProjectCommand.CallCreateProject(@"d:\projects\test\converted", sourceProject); target = new FileProjectItem(targetProject, source.ItemType, source.Include); source.CopyMetadataTo(target); textFileSource = new FileProjectItem(sourceProject, ItemType.None, @"src\readme.txt"); textFileTarget = new FileProjectItem(targetProject, textFileSource.ItemType, textFileSource.Include); textFileSource.CopyMetadataTo(textFileTarget); convertProjectCommand.AddParseableFileContent(source.FileName, sourceCode); convertProjectCommand.CallConvertFile(source, target); convertProjectCommand.CallConvertFile(textFileSource, textFileTarget); }
//static void windowAdded(object sender, SubjectEventArgs<Window> e) { // if (e.Subject is Window) { // Window win = (Window)e.Subject; // if (win == null) // return; // Document doc = win.Document; // } //} static void ShowOptimizedPanel_Executing(object sender, EventArgs e) { isOptimizedPanelVisible = !isOptimizedPanelVisible; Command.GetCommand(optimizedPanelCommandName).IsVisible = isOptimizedPanelVisible; Command.GetCommand(twitterPanelCommandName).IsVisible = isOptimizedPanelVisible; AddInHelper.RefreshMainform(); }
private ConvertResult ConvertOoxToDaisy(string inputFile, string outputFile, Hashtable listMathMl, Hashtable table, string control, string output_Pipeline) { try { using (ConverterForm form = new ConverterForm(this.converter, inputFile, outputFile, this.resourceManager, true, listMathMl, table, control, output_Pipeline)) { if (DialogResult.OK != form.ShowDialog()) { return(ConvertResult.Cancel()); } if (!String.IsNullOrEmpty(form.ValidationError)) { OnValidationError(form.ValidationError, inputFile, outputFile); return(ConvertResult.ValidationError(form.ValidationError)); } if (form.HasLostElements) { OnLostElements(inputFile, outputFile, form.LostElements); if (!(AddInHelper.IsSingleDaisyTranslate(control) && this.ScriptToExecute == null) && IsContinueDTBookGenerationOnLostElements()) { ExecuteScript(outputFile); } } else if (AddInHelper.IsSingleDaisyTranslate(control) && this.ScriptToExecute == null) { OnSuccess(); } else { ExecuteScript(outputFile); } } } catch (IOException e) { // this is meant to catch "file already accessed by another process", though there's no .NET fine-grain exception for this. AddinLogger.Error(e); OnUnknownError("UnableToCreateOutputLabel", e.Message); return(ConvertResult.UnknownError(e.Message + Environment.NewLine + e.StackTrace)); } catch (Exception e) { AddinLogger.Error(e); OnUnknownError("DaisyUnexpectedError", e.GetType() + ": " + e.Message + " (" + e.StackTrace + ")"); if (File.Exists(outputFile)) { File.Delete(outputFile); } return(ConvertResult.UnknownError(e.Message + Environment.NewLine + e.StackTrace)); } return(ConvertResult.Success()); }
public void SetUpFixture() { PythonMSBuildEngineHelper.InitMSBuildEngine(); List <ProjectBindingDescriptor> bindings = new List <ProjectBindingDescriptor>(); using (TextReader reader = PythonBindingAddInFile.ReadAddInFile()) { AddIn addin = AddIn.Load(reader, String.Empty); bindings.Add(new ProjectBindingDescriptor(AddInHelper.GetCodon(addin, "/SharpDevelop/Workbench/ProjectBindings", "Python"))); } ProjectBindingService.SetBindings(bindings); // Set up IProjectContent so the ConvertProjectToPythonProjectCommand can // locate the startup object and determine it's filename. mockProjectContent = new ICSharpCode.Scripting.Tests.Utils.MockProjectContent(); MockClass mainClass = new MockClass(mockProjectContent, startupObject); mainClass.CompilationUnit.FileName = @"d:\projects\test\src\Main2.cs"; mockProjectContent.SetClassToReturnFromGetClass(startupObject, mainClass); convertProjectCommand = new DerivedConvertProjectToPythonProjectCommand(); convertProjectCommand.ProjectContent = mockProjectContent; convertProjectCommand.FileServiceDefaultEncoding = Encoding.Unicode; Solution solution = new Solution(new MockProjectChangeWatcher()); sourceProject = new MSBuildBasedProject( new ProjectCreateInformation() { Solution = solution, OutputProjectFileName = @"d:\projects\test\source.csproj", ProjectName = "source" }); sourceProject.Parent = solution; sourceProject.SetProperty(null, null, "StartupObject", startupObject, PropertyStorageLocations.Base, true); mainFile = new FileProjectItem(sourceProject, ItemType.Compile, @"src\Main.cs"); targetProject = (PythonProject)convertProjectCommand.CallCreateProject(@"d:\projects\test\converted", sourceProject); convertProjectCommand.CallCopyProperties(sourceProject, targetProject); targetMainFile = new FileProjectItem(targetProject, mainFile.ItemType, mainFile.Include); mainFile.CopyMetadataTo(targetMainFile); main2File = new FileProjectItem(sourceProject, ItemType.Compile, @"src\Main2.cs"); targetMain2File = new FileProjectItem(targetProject, main2File.ItemType, main2File.Include); main2File.CopyMetadataTo(targetMain2File); convertProjectCommand.AddParseableFileContent(mainFile.FileName, mainSource); convertProjectCommand.AddParseableFileContent(main2File.FileName, main2Source); convertProjectCommand.CallConvertFile(mainFile, targetMainFile); convertProjectCommand.CallConvertFile(main2File, targetMain2File); }
double[] ComputeAngles(Circle[] circles) { int count = circles.Length; var angles = new double[count]; for (int i = 0; i < count; i++) { int otherIndex = i == count - 1 ? 0 : i + 1; angles[i] = AddInHelper.AngleBetween(circles[i].Axis.Direction, circles[otherIndex].Axis.Direction) / 2; } angles[count - 1] = Math.PI / 2 - angles[count - 1]; return(angles); }
/// <summary> /// Function to translate all Bunch of documents selected by the user /// </summary> /// <param name="outputfilepath">Path of the output File</param> /// <param name="subList">List of All documents</param> /// <param name="category">whether master/sub doc or Bunch of Docs</param> /// <param name="table">Document Properties</param> public bool OoxToDaisySub(string outputfilepath, ArrayList subList, string category, Hashtable table, string control, Hashtable MultipleMathMl, string output_Pipeline) { flag = 0; validationErrorMsg = ""; using (Progress progress = new Progress(this.converter, this.resourceManager, outputfilepath, subList, category, table, control, MultipleMathMl, output_Pipeline)) { DialogResult progressDialogResult = progress.ShowDialog(); if (progressDialogResult == DialogResult.OK) { if (!string.IsNullOrEmpty(progress.ValidationError)) { validationErrorMsg = progress.ValidationError; OnMasterSubValidationError(progress.ValidationError); } else if (progress.HasLostElements) { OnLostElements(string.Empty, outputfilepath, progress.LostElements); flag = 1; if (!(AddInHelper.IsSingleDaisyFromMultipleButton(control) && ScriptToExecute == null)) { continueDTBookGeneration = IsContinueDTBookGenerationOnLostElements(); } } else { if (AddInHelper.IsSingleDaisyFromMultipleButton(control) && ScriptToExecute == null) { OnSuccess(); } flag = 1; } } else if (progressDialogResult == DialogResult.Cancel) { DeleteDTBookFilesIfExists(outputfilepath); } else if (!string.IsNullOrEmpty(progress.ValidationError)) { OnMasterSubValidationError(progress.ValidationError); } } DeleteTemporaryImages(); return((flag == 1) && continueDTBookGeneration); }
/* * LoopUnfold attempts to add as many FlatFaces to a FlatBody as it can. If interference checking is off, it will add all of the * faces of the body. (Actually, the shell, as we do not handle voids). We expect for the seed face of the FlatBody to already * be created, so we have some FlatFins from which to propogate. * * If interference checking is on, multiple flat bodies are required to avoid collisions. Therefore * we return the list of FlatFins on the completed FlatBody that need to start as the seeds for additional FlatBodies. By returning * the FlatFins on the base, rather than just the faces, we can easily transfrom the adjacent FlatFace to line up with that FlatFin * by making it the seed face for the next FlatBody. */ // TBD add tab code would go here, created extra flatfaces, but we need to consider the tabs as part of the collision detection??? private List <FlatFin> LoopUnfold(FlatBody flatBody) { Debug.Assert(flatBody.FlatFaces.Count > 0); // should only be one, but more is harmless if we optimize with seeds of several flatfaces List <FlatFin> remainingFins = new List <FlatFin>(); while (flatBody.OpenFins.Count > 0) { if (AddInHelper.IsEscDown) { break; } FlatFace testFace = null; List <FlatFin> interferingFins = new List <FlatFin>(); foreach (FlatFin baseFin in flatBody.OpenFins) // OpenFins sorts itself to present the most desirable edge (the longest) { testFace = new FlatFace(baseFin.FlatFace.SourceFace.GetAdjacentFace(baseFin.SourceFin.Edge), flatBody); baseFin.AdjacentFin = baseFin.OtherFlatFin(testFace); // make symmetric? Careful: FlatFace.Render() relies on the assumption it is not testFace.Transform = Matrix.CreateMapping(AddInHelper.CreateFrame(baseFin.Start, (baseFin.End - baseFin.Start).Direction, -Direction.DirZ)) * Matrix.CreateMapping(AddInHelper.CreateFrame(baseFin.AdjacentFin.SourceEnd, (baseFin.AdjacentFin.SourceStart - baseFin.AdjacentFin.SourceEnd).Direction, baseFin.AdjacentFin.FlatFace.SourcePlane.Frame.DirZ)).Inverse; if (isDetectingCollisions && flatBody.FaceInterferes(testFace)) // FaceInterferes only gets called if isDetectingCollisions == True { interferingFins.Add(baseFin); } else { flatBody.AddFace(testFace); baseFin.IsInternal = true; baseFin.AdjacentFin.IsInternal = true; break; } } foreach (FlatFin baseFin in interferingFins) { flatBody.OpenFins.Remove(baseFin); remainingFins.Add(baseFin); } } return(remainingFins); }
public static string GetNewValue(string fromAttName, XElement fromElement, string toAttName, string dataType, XElement toElement, bool needsUpdateList) { string sNewAttValue = string.Empty; //if the attribute doesn't exist in toElement, don't add it (don't add join fields to base docs) if (toElement.Attribute(toAttName) != null) { sNewAttValue = EditHelpers.XmlLinq.GetAttributeValue(fromElement, fromAttName); string sOldAttValue = EditHelpers.XmlLinq.GetAttributeValue(toElement, toAttName); if (string.IsNullOrEmpty(sNewAttValue) == false) { if (sNewAttValue.Equals(sOldAttValue) == false) { if (!needsUpdateList) { //don't allow formatting-only changes to numbers (schemas ignore anyway) sNewAttValue = AddInHelper.NoFormattingOnly( sNewAttValue, sOldAttValue, dataType); if (sNewAttValue != string.Empty) { EditHelpers.XmlLinq.SetAttributeValue(toElement, toAttName, sNewAttValue); } } else { sNewAttValue = AddInHelper.NoFormattingOnly( sNewAttValue, sOldAttValue, dataType); } } else { sNewAttValue = string.Empty; } } else { sNewAttValue = string.Empty; } } return(sNewAttValue); }
public void SetUpFixture() { MSBuildEngineHelper.InitMSBuildEngine(); List <LanguageBindingDescriptor> bindings = new List <LanguageBindingDescriptor>(); using (TextReader reader = PythonBindingAddInFile.ReadAddInFile()) { AddIn addin = AddIn.Load(reader, String.Empty); bindings.Add(new LanguageBindingDescriptor(AddInHelper.GetCodon(addin, "/SharpDevelop/Workbench/LanguageBindings", "Python"))); } LanguageBindingService.SetBindings(bindings); mockTextEditorProperties = new MockTextEditorProperties(); convertProjectCommand = new DerivedConvertProjectToPythonProjectCommand(mockTextEditorProperties); mockTextEditorProperties.Encoding = Encoding.Unicode; sourceProject = new MockProject(); sourceProject.Directory = @"d:\projects\test"; source = new FileProjectItem(sourceProject, ItemType.Compile, @"src\Program.cs"); targetProject = (PythonProject)convertProjectCommand.CallCreateProject(@"d:\projects\test\converted", sourceProject); target = new FileProjectItem(targetProject, source.ItemType, source.Include); source.CopyMetadataTo(target); textFileSource = new FileProjectItem(sourceProject, ItemType.None, @"src\readme.txt"); textFileTarget = new FileProjectItem(targetProject, textFileSource.ItemType, textFileSource.Include); textFileSource.CopyMetadataTo(textFileTarget); foreach (ProjectItem item in targetProject.Items) { ReferenceProjectItem reference = item as ReferenceProjectItem; if ((reference != null) && (reference.Name == "IronPython")) { ironPythonReference = reference; break; } } convertProjectCommand.AddParseableFileContent(source.FileName, sourceCode); convertProjectCommand.CallConvertFile(source, target); convertProjectCommand.CallConvertFile(textFileSource, textFileTarget); }
public static void UpdateNewValue(bool needsDbUpdate, string uriPattern, string attName, string attValue, string dataType, string stepNumber, XElement toElement, IDictionary <string, string> updates) { string sNewAttValue = string.Empty; //if the attribute doesn't exist in toElement, don't add it (don't add join fields to base docs) //this is safe because the toElement was generated from a db schema if (toElement.Attribute(attName) != null) { sNewAttValue = attValue; string sOldAttValue = EditHelpers.XmlLinq.GetAttributeValue(toElement, attName); if (string.IsNullOrEmpty(sNewAttValue) == false) { if (sNewAttValue.Equals(sOldAttValue) == false) { //don't allow formatting-only changes to numbers (schemas ignore anyway) sNewAttValue = AddInHelper.NoFormattingOnly( sNewAttValue, sOldAttValue, dataType); if (sNewAttValue != string.Empty) { EditHelpers.XmlLinq.SetAttributeValue(toElement, attName, sNewAttValue); } } else { sNewAttValue = string.Empty; } } else { sNewAttValue = string.Empty; } } if (needsDbUpdate) { AddInHelper.AddToDbList(uriPattern, attName, sNewAttValue, dataType, stepNumber, updates); } }
static void AddRound(DesignFace designFace, List <Round> roundSet, List <DesignFace> remainingFaces, Queue <DesignEdge> edgesToVisit) { remainingFaces.Remove(designFace); Round round = new Round(designFace); roundSet.Add(round); DesignFace otherFace = null; Round otherRound = null; foreach (DesignEdge newEdge in designFace.Edges) { edgesToVisit.Enqueue(newEdge); if (AddInHelper.TryGetAdjacentDesignFace(designFace, newEdge, out otherFace) && Round.TryGetRound(otherFace, out otherRound)) { round.AddAdjacentRound(otherRound); otherRound.AddAdjacentRound(round); } } }
public void Render() { renderedBody = CreateUnfoldedFaceBody(); DesignBody designBody = DesignBody.Create(flatBody.FlatPart, Resources.FlatFaceName, renderedBody); designBody.Layer = NoteHelper.CreateOrGetLayer(Window.ActiveWindow.Document, Resources.FlatFaceLayerName, System.Drawing.Color.Beige); foreach (FlatLoop flatLoop in Loops) { foreach (FlatFin flatFin in flatLoop.Fins.Where(f => !f.IsInternal)) { DesignCurve designCurve = DesignCurve.Create(flatBody.FlatPart, flatFin.SourceFin.Edge); designCurve.Transform(transform); designCurve.Layer = NoteHelper.CreateOrGetLayer(Window.ActiveWindow.Document, Resources.FlatCuttingLinesLayerName, System.Drawing.Color.Blue); } foreach (FlatFin flatFin in flatLoop.Fins.Where(f => f.AdjacentFin != null)) { if ( flatBody.FlatPattern.IsCreatingDashes && Accuracy.CompareAngles(AddInHelper.AngleBetween(flatFin.FlatFace.SourceFace.Geometry.Evaluate(PointUV.Origin).Normal, flatFin.AdjacentFin.FlatFace.SourceFace.Geometry.Evaluate(PointUV.Origin).Normal), flatBody.FlatPattern.BreakAngle) <= 0) { Layer breakLayer = NoteHelper.CreateOrGetLayer(Window.ActiveWindow.Document, Resources.BreakLinesLayerName, System.Drawing.Color.DarkBlue); if (flatBody.FlatPattern.DashSize == 0) { DesignCurve desCurve = DesignCurve.Create(FlatBody.FlatPart, flatFin.AsCurveSegment()); desCurve.Layer = breakLayer; } else { DashesButtonCapsule.CreateDashes(flatFin.AsCurveSegment(), FlatBody.FlatPart, flatBody.FlatPattern.DashSize, breakLayer); } } } } }
static void CylinderDiameter_Executing(object sender, EventArgs e) { SetCylinderDiameter(AddInHelper.ParseAffixedCommand(((Command)sender).Name, cylinderDiameterCommandName)); }
static void SetCylinderDiameter(double diameter) { cylinderDiameter = diameter; Command.GetCommand(cylinderDiameterCommandName).Text = string.Format("{0}{1:0.00e+0} mm", cylinderDiameterCommandText, cylinderDiameter * 1000); AddInHelper.RefreshMainform(); }
static void ForstnerizeDiameter_Executing(object sender, EventArgs e) { diameter = AddInHelper.ParseAffixedCommand(((Command)sender).Name, forstnerizeDiameterCommandName); Command.GetCommand(forstnerizeDiameterCommandName).Text = diameter.ToString(); diameter *= inchesToMeters; }
private static double AngleBetween(List <Component> chain, int i) { int numGears = chain.Count; return(AddInHelper.AngleBetween(chain[i].Placement.Translation - chain[(i + 1) % numGears].Placement.Translation, chain[i].Placement.Translation - chain[(i + numGears - 1) % numGears].Placement.Translation)); }
Codon GetCodon(string name, string extensionPath) { return(AddInHelper.GetCodon(addin, name, extensionPath)); }
public void Iterate() { Iteration++; var newVParameters = new CircularList <CircularList <double> >(iSteps * 2); var backupVParameters = new CircularList <CircularList <double> >(iSteps * 2); var newTabAngles = new CircularList <CircularList <double> >(iSteps * 2); for (int i = 0; i < iSteps * 2; i++) { newVParameters.Add(new CircularList <double>(jSteps)); backupVParameters.Add(new CircularList <double>(jSteps)); newTabAngles.Add(new CircularList <double>(jSteps)); for (int j = 0; j < jSteps; j++) { newVParameters[i].Add(vParameters[i][j]); backupVParameters[i].Add(vParameters[i][j]); newTabAngles[i].Add(tabAngles[i][j]); } } double cumulativeErrorTally = 0; MaxError = 0; for (int i = 0; i < iSteps * 2; i++) { for (int j = 0; j < jSteps; j++) { bool swap = j % 2 == 0; int iOtherDir = swap ? -1 : 1; int iOther = i + iOtherDir; Circle baseCircle = GetTabFromPoints(true, i, j, iOther); Circle circle0 = GetTabFromPoints(true, iOther, j - 1, i); Circle circle1 = GetTabFromPoints(true, iOther, j + 1, i); double distance0 = (baseCircle.Frame.Origin - circle0.Frame.Origin).Magnitude - baseCircle.Radius - circle0.Radius; double distance1 = (baseCircle.Frame.Origin - circle1.Frame.Origin).Magnitude - baseCircle.Radius - circle1.Radius; cumulativeErrorTally += distance0 * distance0 + distance1 * distance1; MaxError = Math.Max(Math.Abs(distance0), MaxError); MaxError = Math.Max(Math.Abs(distance1), MaxError); double angleAdjust = (distance0 + distance1) / 2 * AngleForce / GetSpanAt(i, j) / baseCircle.Radius; // / GetSpanAt(i, j) / baseCircle.Radius; // / baseCircle.Radius; newTabAngles[i][j] -= angleAdjust; newTabAngles[i][j - 1] -= angleAdjust / 2; newTabAngles[i][j + 1] -= angleAdjust / 2; double iAngle = AddInHelper.AngleBetween( circle0.Frame.Origin - baseCircle.Frame.Origin, circle1.Frame.Origin - baseCircle.Frame.Origin ); double vOffset = (distance1 - distance0) * VForce; //double uAngleOffset = -(Math.PI / 2 - Math.Abs(iAngle)) * UAngleForce; double uAngleOffset = -(Math.PI * 2 / 3 - Math.Abs(iAngle)) * UAngleForce; Circle circleV = GetTabFromPoints(true, iOther, j, i); double distanceV = (baseCircle.Frame.Origin - circleV.Frame.Origin).Magnitude - baseCircle.Radius - circleV.Radius; double uTouchOffset = -distanceV * UTouchForce; double averageOffset = 0; double averageAngle = 0; double count = 0; #if false for (int ii = i - 1; ii <= i + 1; ii++) { for (int jj = j - 2; jj <= j + 2; jj++) { if (i == ii && j == jj) { continue; } double weight = (double)1 / (Math.Pow(i - ii, 2) + Math.Pow(j - jj, 2)); averageOffset += GetSpanAt(ii, jj) * weight; averageAngle += GetTabFromPoints(true, i, j, j % 2 == 0 ? i - 1 : i + 1).Radius *weight; count += weight; } } averageOffset = averageOffset / count - GetSpanAt(i, j); averageOffset *= -AverageVForce / 2; averageAngle = averageAngle / count - baseCircle.Radius; newTabAngles[i][j] += averageAngle * AverageTabAngleForce; #elif true foreach (int ii in new int[] { i, iOther }) { foreach (int jj in new int[] { j - 1, j + 1 }) { averageAngle += GetTabFromPoints(true, ii, jj, ii == i ? iOther : i).Radius; count++; } } averageOffset += GetSpanAt(i - 1, j); averageOffset += GetSpanAt(i + 1, j); averageOffset += GetSpanAt(i, j - 1); averageOffset += GetSpanAt(i, j + 1); averageOffset /= 4; averageOffset = averageOffset / count - GetSpanAt(i, j); averageOffset *= -AverageVForce / 2; averageAngle = averageAngle / count - baseCircle.Radius; newTabAngles[i][j] -= averageAngle * AverageTabAngleForce; #else Point midpointV = GetFivePointNurbsAverage(new int[, ] { { i, j - 2 }, { i, j - 1 }, { i, j }, { i, j + 1 }, { i, j + 2 } }); Point midpointD0 = GetFivePointNurbsAverage(new int[, ] { { i - iOtherDir, j - 2 }, { i, j - 1 }, { i, j }, { i + iOtherDir, j + 1 }, { i + 2 * iOtherDir, j + 2 } }); Point midpointD1 = GetFivePointNurbsAverage(new int[, ] { { i - iOtherDir, j + 2 }, { i, j + 1 }, { i, j }, { i + iOtherDir, j - 1 }, { i + 2 * iOtherDir, j - 2 } }); Point midpointU = GetFivePointNurbsAverage(new int[, ] { { i - 2 * iOtherDir, j }, { i - iOtherDir, j }, { i, j }, { i + iOtherDir, j }, { i + 2 * iOtherDir, j } }); averageOffset = (midpointV.Y + midpointU.Y) / 2 - GetSpanAt(i, j); averageOffset *= -AverageVForce / 2; averageAngle = (midpointV.X + 2 * midpointD0.X + 2 * midpointD1.X) / 5 - tabAngles[i][j]; newTabAngles[i][j] += averageAngle * AverageTabAngleForce; #endif double size = 1; // (points[i][j + 1] - points[i][j]).Magnitude; double slip = (uAngleOffset + averageOffset + uTouchOffset) * size; newVParameters[i][j] += vOffset + slip; newVParameters[i][j + 1] += vOffset - slip; newVParameters[i][j - 1] += (vOffset + slip) / 2; newVParameters[i][j + 2] += (vOffset - slip) / 2; // double oldSpan = (points[i][j + 1] - points[i][j]).Magnitude; // double newSpan = (points[i][j + 1] - points[i][j]).Magnitude; Trace.WriteIf(Iteration % 400 == 0, tabAngles[i][j] + " "); // Trace.WriteIf(Iteration % 400 == 0, iAngle + " "); // Trace.WriteIf(Iteration % 400 == 0, GetSpanAt(i,j) + " "); } Trace.WriteLineIf(Iteration % 400 == 0, ""); } for (int i = 0; i < iSteps * 2; i++) { for (int j = 0; j < jSteps; j++) { newTabAngles[i][j] = Math.Max(Math.PI / 2, newTabAngles[i][j]); newTabAngles[i][j] = Math.Min(Math.PI * 3 / 4, newTabAngles[i][j]); double l1 = backupVParameters[i][j + 1] - backupVParameters[i][j]; double l2 = newVParameters[i][j + 1] - newVParameters[i][j]; double b1 = Math.PI - tabAngles[i][j]; double a = l1 / l2 / Math.Tan(b1 / 2) * (1 + 1 / Math.Cos(b1 / 2)); double phi = 2 * Math.Atan(1 / a); tabAngles[i][j] = Math.PI - 2 * phi; //double b2 = 2 * Math.Asin(l2 / l1 * Math.Sin(b1 / 2)); //tabAngles[i][j] = Math.PI - b2; } } for (int i = 0; i < iSteps * 2; i++) { // make intersecting tabs identical //double angle = ( // newTabAngles[i][0] + // newTabAngles[i + iSteps][0] + // newTabAngles[i + iSteps / 2][jSteps / 2] + // newTabAngles[i + 3 * iSteps / 2][jSteps / 2] //) / 4; //newTabAngles[i][0] = angle; //newTabAngles[i + iSteps][0] = angle; //newTabAngles[i + iSteps / 2][jSteps / 2] = angle; //newTabAngles[i + 3 * iSteps / 2][jSteps / 2] = angle; double span = ( (newVParameters[i][1] - newVParameters[i][0]) + (newVParameters[i + iSteps][1] - newVParameters[i + iSteps][0]) + (newVParameters[i + iSteps / 2][jSteps / 2 + 1] - newVParameters[i + iSteps / 2][jSteps / 2]) + (newVParameters[i + 3 * iSteps / 2][jSteps / 2 + 1] - newVParameters[i + 3 * iSteps / 2][jSteps / 2]) ) / 8; newVParameters[i][0] = -span; newVParameters[i][1] = span; newVParameters[i + iSteps][0] = -span; newVParameters[i + iSteps][1] = span; newVParameters[i + iSteps / 2][jSteps / 2] = Math.PI - span; newVParameters[i + iSteps / 2][jSteps / 2 + 1] = Math.PI + span; newVParameters[i + 3 * iSteps / 2][jSteps / 2] = Math.PI - span; newVParameters[i + 3 * iSteps / 2][jSteps / 2 + 1] = Math.PI + span; } // Average antipodal points // for l(i, j), // l(i, j) == l(-i, pi+j)* == l(i+2pi, -j) == l(-i-2pi, pi-j)* // Where * means x=x, y=-y, z=-z for (int i = 0; i < iSteps * 2; i++) { for (int j = 0; j < jSteps / 2; j++) { double average = ( newVParameters[i][j] + newVParameters[-i][j + jSteps / 2] - Math.PI + (j < 2 ? 0 : 2 * Math.PI) - newVParameters[i + iSteps][-j + 1] + Math.PI - newVParameters[-i - iSteps][-j + jSteps / 2 + 1] ) / 4; newVParameters[i][j] = average; newVParameters[-i][j + jSteps / 2] = average + Math.PI; newVParameters[i + iSteps][-j + 1] = (j < 2 ? 0 : 2 * Math.PI) - average; newVParameters[-i - iSteps][-j + jSteps / 2 + 1] = Math.PI - average; average = ( tabAngles[i][j] + tabAngles[-i][j + jSteps / 2 + 1] + tabAngles[i + iSteps][-j] + tabAngles[-i - iSteps][-j + jSteps / 2 + 1] ) / 4; tabAngles[i][j] = average; tabAngles[-i][j + jSteps / 2 + 1] = average; tabAngles[i + iSteps][-j] = average; tabAngles[-i - iSteps][-j + jSteps / 2 + 1] = average; } } CumulativeError = Math.Sqrt(cumulativeErrorTally / (iSteps * 2 * jSteps * 2)); // Trace.WriteLine(lastCumulativeError); // We're not calculating the points for the last iteration. Whatevs. vParameters = newVParameters; tabAngles = newTabAngles; for (int i = 0; i < iSteps * 2; i++) { double u = 2 * Math.PI * (double)i / iSteps; for (int j = 0; j < jSteps; j++) { points[i][j] = Lawson.Evaluate(PointUV.Create(vParameters[i][j], u), p, q, circleAngle, inverseOffset, true) * scale; // Trace.WriteLine(string.Format("{0} {1} {2}", i, j, tabAngles[i][j])); } } }
protected override void OnExecute(Command command, ExecutionContext context, System.Drawing.Rectangle buttonRect) { if (ScenePart == null) { return; } double stepSize = Values[Resources.TessellateLoftStepSize].Value / ActiveWindow.Units.Length.ConversionFactor; ITrimmedCurve[] curves = Window.ActiveWindow.GetAllSelectedITrimmedCurves().ToArray(); if (curves.Length != 2) { Debug.Fail("Need exactly two curves"); } ITrimmedCurve curve0 = curves[0], curve1 = curves[1]; //List<Point> points0 = curve0.Shape.GetPolyline() as List<Point>; //List<Point> points1 = curve1.Shape.GetPolyline() as List<Point>; //Debug.Assert (points0 != null && points1 != null); //if ((points1[0] - points0[0]).Magnitude > (points1[points1.Count - 1] - points0[0]).Magnitude) // points1.Reverse(); if ((curve1.StartPoint - curve0.StartPoint).Magnitude > (curve1.EndPoint - curve0.StartPoint).Magnitude) { curve1 = CurveSegment.Create(curve1.GetGeometry <Curve>(), Interval.Create(curve1.Bounds.End, curve1.Bounds.Start)); } List <Point> points0 = curve0.TessellateCurve(stepSize) as List <Point>; List <Point> points1 = curve1.TessellateCurve(stepSize) as List <Point>; if ((points1[0] - points0[0]).Magnitude > (points1[points1.Count - 1] - points0[0]).Magnitude) { points1.Reverse(); } //int steps = Math.Min(points0.Count, points1.Count); //for (int i = 0; i < steps; i++) { // AddInHelper.CreateLines(new List<Point> { points0[i], points1[i] }, part); int basePoint0 = points0.Count - 1; int basePoint1 = points1.Count - 1; List <Body> bodies = new List <Body>(); while (basePoint0 > 0 || basePoint1 > 0) { double base0Diagonal = double.MaxValue; double base1Diagonal = double.MaxValue; if (basePoint1 > 0) { base0Diagonal = (points1[basePoint1 - 1] - points0[basePoint0]).Magnitude; } if (basePoint0 > 0) { base1Diagonal = (points0[basePoint0 - 1] - points1[basePoint1]).Magnitude; } List <Point> facetPoints = new List <Point>(); facetPoints.Add(points0[basePoint0]); facetPoints.Add(points1[basePoint1]); if (base0Diagonal < base1Diagonal) { facetPoints.Add(points1[--basePoint1]); } else { facetPoints.Add(points0[--basePoint0]); } Plane plane = null; if (AddInHelper.TryCreatePlaneFromPoints(facetPoints, out plane)) { bodies.Add(ShapeHelper.CreatePolygon(facetPoints, plane, 0)); } } bodies = bodies.TryUnionBodies().ToList(); Debug.Assert(bodies.Count == 1); DesignBody.Create(ScenePart, Resources.TessellateLoftBodyName, bodies[0]); }
protected override void OnExecute(Command command, ExecutionContext context, System.Drawing.Rectangle buttonRect) { Part part = Window.ActiveWindow.Scene as Part; Debug.Assert(part != null); Double stepSize = 0.001; string tessellateLoftResolutionPropertyName = "Loft Tessellation Resolution"; if (!part.Document.CustomProperties.ContainsKey(tessellateLoftResolutionPropertyName)) { CustomProperty.Create(part.Document, tessellateLoftResolutionPropertyName, stepSize); } CustomProperty property; if (part.Document.CustomProperties.TryGetValue(tessellateLoftResolutionPropertyName, out property)) { stepSize = (double)property.Value; } List <ITrimmedCurve> curves = new List <ITrimmedCurve>(Window.ActiveWindow.GetAllSelectedITrimmedCurves()); if (curves.Count < 3) { return; } Point startPoint = curves[0].StartPoint; if (curves[1].StartPoint != startPoint) { if (curves[1].StartPoint != startPoint) { curves[0] = CurveSegment.Create(curves[0].GetGeometry <Curve>(), Interval.Create(curves[0].Bounds.End, curves[0].Bounds.Start)); // TBD Figure out why we can't call ReverseCurves and debug } else { curves[1] = CurveSegment.Create(curves[1].GetGeometry <Curve>(), Interval.Create(curves[1].Bounds.End, curves[1].Bounds.Start)); } } for (int i = 2; i < curves.Count; i++) { if (curves[i].StartPoint != startPoint) { curves[i] = CurveSegment.Create(curves[i].GetGeometry <Curve>(), Interval.Create(curves[i].Bounds.End, curves[i].Bounds.Start)); } if (curves[i].StartPoint != startPoint) { return; } } double endZ = double.NegativeInfinity; foreach (ITrimmedCurve curve in curves) { if (curve.EndPoint.Z > endZ) { endZ = curve.EndPoint.Z; } } Plane startPlane = Plane.Create(Frame.Create(startPoint, Direction.DirX, Direction.DirY)); double cuttingZ = startPoint.Z; List <List <Point> > curveSteps = new List <List <Point> >(); List <List <Point> > insetSteps = new List <List <Point> >(); while (true) { cuttingZ -= stepSize; if (cuttingZ < endZ) { break; } Plane cuttingPlane = Plane.Create(Frame.Create(Point.Create(startPoint.X, startPoint.Y, cuttingZ), Direction.DirX, Direction.DirY)); List <Point> curvePoints = new List <Point>(); List <Point> planarPoints = new List <Point>(); foreach (ITrimmedCurve curve in curves) { ICollection <IntPoint <SurfaceEvaluation, CurveEvaluation> > surfaceIntersections = cuttingPlane.IntersectCurve(curve.GetGeometry <Curve>()); foreach (IntPoint <SurfaceEvaluation, CurveEvaluation> surfaceIntersection in surfaceIntersections) { Point point = surfaceIntersection.Point; curvePoints.Add(point); Point projectedPoint = startPlane.ProjectPoint(point).Point; Direction direction = (projectedPoint - startPoint).Direction; double length = CurveSegment.Create(curve.GetGeometry <Curve>(), Interval.Create(curve.Bounds.Start, surfaceIntersection.EvaluationB.Param)).Length; planarPoints.Add(startPoint + direction * length); break; // assume one intersection } } List <Point> insetPoints = new List <Point>(); for (int i = 0; i < planarPoints.Count; i++) { int ii = i == planarPoints.Count - 1 ? 0 : i + 1; ICollection <Point> pointCandidates = AddInHelper.IntersectSpheres(new Sphere[] { Sphere.Create(Frame.Create(startPoint, Direction.DirX, Direction.DirY), ((startPoint - curvePoints[i]).Magnitude + (startPoint - curvePoints[ii]).Magnitude) / 2), Sphere.Create(Frame.Create(curvePoints[i], Direction.DirX, Direction.DirY), (startPoint - curvePoints[i]).Magnitude), Sphere.Create(Frame.Create(curvePoints[ii], Direction.DirX, Direction.DirY), (startPoint - curvePoints[ii]).Magnitude) }); Point planarMidPoint = Point.Origin + (planarPoints[i] + planarPoints[ii].Vector).Vector / 2; Point insetPoint; foreach (Point point in pointCandidates) { Point testPoint = startPlane.ProjectPoint(point).Point; if ((testPoint - planarMidPoint).Magnitude < (insetPoint - planarMidPoint).Magnitude) { insetPoint = point; } } insetPoints.Add(insetPoint); } curveSteps.Add(curvePoints); insetSteps.Add(insetPoints); } for (int i = 0; i < curveSteps.Count - 1; i++) { for (int j = 0; j < curveSteps[i].Count; j++) { int jj = j == curveSteps[i].Count - 1 ? 0 : j + 1; ShapeHelper.CreatePolygon(new Point[] { curveSteps[i][j], curveSteps[i + 1][j], insetSteps[i][j] }, 0, null); ShapeHelper.CreatePolygon(new Point[] { curveSteps[i + 1][j], insetSteps[i][j], insetSteps[i + 1][j] }, 0, null); ShapeHelper.CreatePolygon(new Point[] { insetSteps[i][j], insetSteps[i + 1][j], curveSteps[i][jj] }, 0, null); ShapeHelper.CreatePolygon(new Point[] { insetSteps[i + 1][j], curveSteps[i][jj], curveSteps[i + 1][jj] }, 0, null); } } return; }
static void Forstnerize_Executing(object sender, EventArgs e) { Window activeWindow = Window.ActiveWindow; IDesignBody forstnerBody = null; Box faceBoundingBox = Box.Empty; foreach (IDesignFace iDesignFace in activeWindow.ActiveContext.GetSelection <IDesignFace>()) { forstnerBody = iDesignFace.GetAncestor <IDesignBody>(); faceBoundingBox |= iDesignFace.Shape.GetBoundingBox(Matrix.Identity); } if (forstnerBody == null || faceBoundingBox == Box.Empty) { return; } Part part = Part.Create(activeWindow.Document, "Forstner Bottoms"); Component component = Component.Create(activeWindow.Scene as Part, part); Box bodyBoundingBox = forstnerBody.Shape.GetBoundingBox(Matrix.Identity); Plane topPlane = Plane.Create(Frame.Create(bodyBoundingBox.MaxCorner, Direction.DirX, Direction.DirY)); double xSpacing = diameter * Math.Sqrt(3) / 2; double ySpacing = diameter * 3 / 4; bool shortRow = false; for (double y = faceBoundingBox.MinCorner.Y; y < faceBoundingBox.MaxCorner.Y; y += ySpacing) { for (double x = shortRow ? faceBoundingBox.MinCorner.X + xSpacing / 2 : faceBoundingBox.MinCorner.X; x < faceBoundingBox.MaxCorner.X; x += xSpacing) { List <IDesignBody> referenceBodies = new List <IDesignBody>(); referenceBodies.Add(DesignBody.Create( Part.Create(activeWindow.Document, "Temp"), "Target Copy", forstnerBody.Master.Shape.Copy() )); Point lowerPoint = Point.Create(x, y, bodyBoundingBox.MinCorner.Z); Point upperPoint = Point.Create(x, y, bodyBoundingBox.MaxCorner.Z); IDesignBody drillBody = ShapeHelper.CreateCylinder(lowerPoint, upperPoint, diameter, activeWindow.Scene as Part); ICollection <IDesignBody> outputBodies = new List <IDesignBody>(); try { //XXX outputBodies = drillBody.Subtract(referenceBodies); } finally { //outputBodies = new List<IDesignBody>(); } // Find the top of the faces created by the intersection of the cylinder and the target. The top of the bounding box of all faces except the top face and the cylinder of the drill are perfect. Box bottomBox = Box.Empty; Cylinder drillCylinder = Cylinder.Create( Frame.Create(lowerPoint, Direction.DirX, Direction.DirY), diameter / 2 ); bool hasTop = false; foreach (IDesignBody iDesignBody in outputBodies) { foreach (IDesignFace iDesignFace in iDesignBody.Faces) { Plane plane = iDesignFace.Shape.Geometry as Plane; if (plane != null) { if (AddInHelper.isCooincident(plane, topPlane)) { hasTop = true; continue; } } Cylinder cylinder = iDesignFace.Shape.Geometry as Cylinder; if (cylinder != null) { if (AddInHelper.isCooincident(cylinder, drillCylinder)) { continue; } } bottomBox |= iDesignFace.Shape.GetBoundingBox(Matrix.Identity); } iDesignBody.Delete(); } if (!bottomBox.IsEmpty && hasTop) { Point bottomPoint = Point.Create(lowerPoint.X, lowerPoint.Y, bottomBox.MaxCorner.Z); DesignBody bottomBody = ShapeHelper.CreateCircle(Frame.Create(bottomPoint, Direction.DirX, Direction.DirY), diameter, part); //AddInHelper.CreateCircle(Frame.Create(bottomPoint, Direction.DirX, Direction.DirY), 0.001, part); foreach (DesignFace designFace in bottomBody.Faces) { NoteHelper.AnnotateFace(designFace.GetAncestor <Part>(), designFace, activeWindow.Units.Length.Format(-bottomPoint.Z), diameter / 5, Direction.DirZ); } } } shortRow = !shortRow; } }
/// <summary> /// Function to translate all sub documents in the Master Document /// </summary> /// <param name="outputfilepath">Path of the output File</param> /// <param name="subList">List of All documents</param> /// <param name="HTable">Document Properties</param> /// <param name="tempInputFile">Duplicate for the Input File</param> public void OoxToDaisySub(String outputfilepath, ArrayList subList, Hashtable HTable, String tempInputFile, string control, Hashtable listMathMl, string output_Pipeline, ArrayList notTranslatedDoc) { flag = 0; validationErrorMsg = ""; using (Progress progress = new Progress(this.converter, this.resourceManager, outputfilepath, subList, HTable, tempInputFile, control, listMathMl, output_Pipeline)) { DialogResult dr = progress.ShowDialog(); if (dr == DialogResult.OK) { validationErrorMsg = progress.ValidationError; String messageDocsSkip = DocumentSkipped(notTranslatedDoc); if (!string.IsNullOrEmpty(validationErrorMsg)) { validationErrorMsg = validationErrorMsg + messageDocsSkip; OnMasterSubValidationError(validationErrorMsg); } else if (progress.HasLostElements) { OnLostElements(string.Empty, outputfilepath + "\\1.xml", progress.LostElements); if (AddInHelper.PipelineIsInstalled() && AddInHelper.buttonIsSingleWordToXMLConversion(control) && ScriptToExecute != null && IsContinueDTBookGenerationOnLostElements()) { try { ExecuteScript(outputfilepath + "\\" + Path.GetFileNameWithoutExtension(tempInputFile) + ".xml"); } catch (Exception e) { AddinLogger.Error(e); OnUnknownError(e.Message); } } } else { if (!string.IsNullOrEmpty(messageDocsSkip)) { OnSuccessMasterSubValidation(ResManager.GetString("SucessLabel") + messageDocsSkip); } else { if (AddInHelper.IsSingleDaisyTranslate(control) && ScriptToExecute == null) { OnSuccess(); } else { ExecuteScript(outputfilepath + "\\" + Path.GetFileNameWithoutExtension(tempInputFile) + ".xml"); } } } } else if (dr == DialogResult.Cancel) { DeleteDTBookFilesIfExists(outputfilepath); } else { validationErrorMsg = progress.ValidationError; if (!string.IsNullOrEmpty(validationErrorMsg)) { OnMasterSubValidationError(validationErrorMsg); } } } DeleteTemporaryImages(); }
protected override void OnExecute(Command command, ExecutionContext context, System.Drawing.Rectangle buttonRect) { double lengthConversion = ActiveWindow.Units.Length.ConversionFactor; int numberOfTeethL = (int)Values[Resources.NumberOfTeethLText].Value; int numberOfTeethR = (int)Values[Resources.NumberOfTeethRText].Value; bool isInternalL = numberOfTeethL < 0; bool isInternalR = numberOfTeethR < 0; numberOfTeethL = Math.Abs(numberOfTeethL); numberOfTeethR = Math.Abs(numberOfTeethR); double pressureAngle = Values[Resources.PressureAngleText].Value * Math.PI / 180; double module = Values[Resources.ModuleText].Value / lengthConversion; double dedendumClearance = Values[Resources.DedendumClearanceText].Value; double depth = Values[Resources.DepthText].Value / lengthConversion; bool useTrochoidalInterferenceRemoval = Booleans[Resources.UseTrochoidalText].Value; bool addDedendumClearance = Booleans[Resources.AddDedendumClearance].Value; if (!addDedendumClearance) { dedendumClearance = 0; } bool isBevel = RibbonBooleanGroupCapsule.BooleanGroupCapsules[Resources.IsBevelText].IsEnabledCommandBoolean.Value; double bevelAngle = RibbonBooleanGroupCapsule.BooleanGroupCapsules[Resources.IsBevelText].Values[Resources.BevelAngleText].Value * Math.PI / 180; double bevelKneeRatio = RibbonBooleanGroupCapsule.BooleanGroupCapsules[Resources.IsBevelText].Values[Resources.BevelKneeRatioText].Value; bool isHelical = RibbonBooleanGroupCapsule.BooleanGroupCapsules[Resources.IsHelicalText].IsEnabledCommandBoolean.Value; double helicalAngle = RibbonBooleanGroupCapsule.BooleanGroupCapsules[Resources.IsHelicalText].Values[Resources.HelicalAngleText].Value * Math.PI / 180; if (!isHelical) { helicalAngle = 0; } bool isScrew = RibbonBooleanGroupCapsule.BooleanGroupCapsules[Resources.IsScrewText].IsEnabledCommandBoolean.Value; double screwAngle = RibbonBooleanGroupCapsule.BooleanGroupCapsules[Resources.IsScrewText].Values[Resources.ScrewAngleText].Value * Math.PI / 180; double screwAngleOffset = RibbonBooleanGroupCapsule.BooleanGroupCapsules[Resources.IsScrewText].Values[Resources.ScrewAngleBiasText].Value * Math.PI / 180; if (!isScrew) { screwAngle = 0; screwAngleOffset = 0; } double screwAngleAverage = screwAngle / 2; double screwAngleL = screwAngleAverage + screwAngleOffset; double screwAngleR = screwAngleAverage - screwAngleOffset; bool isHypoid = RibbonBooleanGroupCapsule.BooleanGroupCapsules[Resources.IsHypoidText].IsEnabledCommandBoolean.Value; double hypoidAngle = RibbonBooleanGroupCapsule.BooleanGroupCapsules[Resources.IsHypoidText].Values[Resources.HypoidAngleText].Value * Math.PI / 180; double hypoidOffset = RibbonBooleanGroupCapsule.BooleanGroupCapsules[Resources.IsHypoidText].Values[Resources.HypoidOffsetText].Value / lengthConversion; if (!isHypoid) { hypoidAngle = 0; hypoidOffset = 0; } Frame frame = Frame.World; //Circle circle = SelectedCircle(ActiveWindow); //if (circle != null) // frame = circle.Frame; List <ITrimmedCurve> selectedCurves = ActiveWindow.GetAllSelectedITrimmedCurves().ToList(); if (selectedCurves.Count == 2 && selectedCurves[0].Geometry is Circle && selectedCurves[0].Geometry is Circle) { Circle circle0 = (Circle)selectedCurves[0].Geometry; Circle circle1 = (Circle)selectedCurves[1].Geometry; Separation separation = circle0.Axis.GetClosestSeparation(circle1.Axis); if (Accuracy.LengthIsZero(separation.Distance)) { throw new NotImplementedException("Distance between axes is zero; only hypoid implemented."); } isHypoid = true; hypoidAngle = AddInHelper.AngleBetween(circle0.Axis.Direction, circle1.Axis.Direction); hypoidOffset = ((circle0.Frame.Origin - separation.PointA).Magnitude - depth / 2) / Math.Cos(hypoidAngle / 2); double radiusAApprox = separation.Distance * circle0.Radius / (circle0.Radius + circle1.Radius); double radiusBApprox = separation.Distance - radiusAApprox; numberOfTeethR = (int)Math.Round((double)numberOfTeethL / radiusAApprox * radiusBApprox); module = radiusAApprox * 2 / numberOfTeethL; Point midpoint = separation.PointA + (separation.PointA - separation.PointB) * numberOfTeethL / numberOfTeethR; Direction sideSide = (circle0.Frame.Origin - circle1.Frame.Origin).Direction; frame = Frame.Create(midpoint, Direction.Cross(sideSide, -(midpoint - circle0.GetClosestSeparation(circle1).PointA).Direction), sideSide); } double hypoidAngleL = Math.Atan(Math.Sin(hypoidAngle) / (Math.Cos(hypoidAngle) + (double)numberOfTeethR / numberOfTeethL)); double hypoidAngleR = Math.Atan(Math.Sin(hypoidAngle) / (Math.Cos(hypoidAngle) + (double)numberOfTeethL / numberOfTeethR)); Gear gearL = null; Gear gearR = null; var gearDataL = new GearData(numberOfTeethL, pressureAngle, module, dedendumClearance, isInternalL, screwAngleL); var gearDataR = new GearData(numberOfTeethR, pressureAngle, module, dedendumClearance, isInternalR, screwAngleR); ToothProfile toothProfileL = GetGearProfileFromOptions(gearDataL, gearDataR, useTrochoidalInterferenceRemoval, addDedendumClearance); ToothProfile toothProfileR = GetGearProfileFromOptions(gearDataR, gearDataL, useTrochoidalInterferenceRemoval, addDedendumClearance); if (isBevel) { gearL = BevelGear.Create(ActiveIPart, gearDataL, gearDataR, toothProfileL, helicalAngle, bevelAngle, bevelKneeRatio, depth); gearR = BevelGear.Create(ActiveIPart, gearDataR, gearDataL, toothProfileR, -helicalAngle, bevelAngle, bevelKneeRatio, depth); } else if (isHypoid) { gearL = HypoidGear.Create(ActiveIPart, gearDataL, gearDataR, toothProfileL, helicalAngle, hypoidAngleL, hypoidOffset, bevelKneeRatio, depth); gearR = HypoidGear.Create(ActiveIPart, gearDataR, gearDataL, toothProfileR, -helicalAngle, hypoidAngleR, hypoidOffset, bevelKneeRatio, depth); } else { gearL = StraightGear.Create(ActiveIPart, gearDataL, gearDataR, toothProfileL, helicalAngle, screwAngleL, depth); gearR = StraightGear.Create(ActiveIPart, gearDataR, gearDataL, toothProfileR, -helicalAngle, screwAngleR, depth); } Line zAxis = Line.Create(Point.Origin, Direction.DirZ); gearL.Component.Transform( Matrix.CreateMapping(frame) * Matrix.CreateRotation(zAxis, Math.PI) * gearL.TransformToTangent * Matrix.CreateRotation(zAxis, gearDataL.PitchAngle * ((double)1 / 2 + (gearDataL.NumberOfTeeth % 2 == 0 && !isHypoid ? -1 : 0))) ); gearR.Component.Transform( Matrix.CreateMapping(frame) * gearR.TransformToTangent * Matrix.CreateRotation(zAxis, gearDataR.PitchAngle * ((double)1 / 2 + (gearDataR.NumberOfTeeth % 2 == 0 && !isHypoid ? -1 : 0))) ); // if (gearDataR.NumberOfTeeth % 2 == 0) // gearR.Component.Transform(Matrix.CreateRotation(Line.Create(Point.Origin, Direction.DirZ), gearDataR.PitchAngle)); //gearR.Component.Transform(gearR.TransformToTangent); Part parent = ActiveIPart.Master; IDesignFace pitchCircleL = gearL.Component.Content.Bodies.Where(b => b.Master == gearL.PitchCircleDesBody).First().Faces.First(); IDesignFace pitchCircleR = gearR.Component.Content.Bodies.Where(b => b.Master == gearR.PitchCircleDesBody).First().Faces.First(); Part gearMountPart = Part.Create(parent.Document, String.Format(Resources.GearMountPartName, gearDataL.NumberOfTeeth, gearDataR.NumberOfTeeth)); Component gearMountComponent = Component.Create(parent, gearMountPart); DesignBody mountBodyL = DesignBody.Create(gearMountPart, string.Format(Resources.MountBodyName, gearDataL.NumberOfTeeth), pitchCircleL.Master.Shape.Body.CreateTransformedCopy(pitchCircleL.TransformToMaster.Inverse)); DesignBody mountBodyR = DesignBody.Create(gearMountPart, string.Format(Resources.MountBodyName, gearDataR.NumberOfTeeth), pitchCircleR.Master.Shape.Body.CreateTransformedCopy(pitchCircleR.TransformToMaster.Inverse)); IDesignFace mountCircleL = gearMountComponent.Content.Bodies.Where(b => b.Master == mountBodyL).First().Faces.First(); IDesignFace mountCircleR = gearMountComponent.Content.Bodies.Where(b => b.Master == mountBodyR).First().Faces.First(); Layer mountLayer = NoteHelper.CreateOrGetLayer(ActiveDocument, Resources.GearMountAlignmentCircleLayer, System.Drawing.Color.LightGray); mountLayer.SetVisible(null, false); mountBodyL.Layer = mountLayer; mountBodyR.Layer = mountLayer; MatingCondition matingCondition; matingCondition = AnchorCondition.Create(parent, gearMountComponent); matingCondition = AlignCondition.Create(parent, mountCircleL, pitchCircleL); matingCondition = AlignCondition.Create(parent, mountCircleR, pitchCircleR); // matingCondition = TangentCondition.Create(parent, pitchCircleL, pitchCircleR); GearCondition gearCondition = GearCondition.Create(parent, pitchCircleL, pitchCircleR); if (gearDataL.IsInternal ^ gearDataR.IsInternal) { gearCondition.IsBelt = true; } ActiveWindow.InteractionMode = InteractionMode.Solid; Settings.Default.NumberOfTeethL = numberOfTeethL; Settings.Default.NumberOfTeethR = numberOfTeethR; Settings.Default.PressureAngleDegrees = pressureAngle * 180 / Math.PI; Settings.Default.Module = module; Settings.Default.Depth = depth; Settings.Default.DedendumClearance = dedendumClearance; Settings.Default.UseTrochoidalInterferenceRemoval = useTrochoidalInterferenceRemoval; Settings.Default.AddDedendumClearace = addDedendumClearance; Settings.Default.IsBevel = isBevel; if (isBevel) { Settings.Default.BevelAngle = bevelAngle * 180 / Math.PI; Settings.Default.BevelKneeRatio = bevelKneeRatio; } Settings.Default.IsHelical = isHelical; Settings.Default.HelicalAngle = helicalAngle * 180 / Math.PI; Settings.Default.IsScrew = isScrew; Settings.Default.ScrewAngle = screwAngle * 180 / Math.PI; Settings.Default.ScrewAngleOffset = screwAngleOffset * 180 / Math.PI; Settings.Default.IsHypoid = isHypoid; Settings.Default.HypoidAngle = hypoidAngle * 180 / Math.PI; Settings.Default.HypoidOffset = hypoidOffset * lengthConversion; Settings.Default.Save(); }
public void Iterate() { Iteration++; //var newVParameters = new List<List<double>>(steps + 1); //var backupVParameters = new List<List<double>>(steps + 1); //var newTabAngles = new List<List<double>>(steps + 1); for (int i = 0; i < steps; i++) { //newVParameters.Add(new List<double>(steps + 1)); //backupVParameters.Add(new List<double>(steps + 1)); //newTabAngles.Add(new List<double>(steps + 1)); for (int j = 0; j <= steps; j++) { // newVParameters[i].Add(vParameters[i][j]); // backupVParameters[i].Add(vParameters[i][j]); //newTabAngles[i].Add(tabAngles[i][j]); } } double cumulativeErrorTally = 0; MaxError = 0; for (int i = 0; i <= steps; i++) { for (int j = 0; j <= steps; j++) { Vector grad = Gradient(points[i, j]); points[i, j] = points[i, j] + grad.Z * Direction.DirZ / 100; #if false bool swap = j % 2 == 0; int iOtherDir = swap ? -1 : 1; int iOther = i + iOtherDir; Circle baseCircle = GetTabFromPoints(true, i, j, iOther); Circle circle0 = GetTabFromPoints(true, iOther, j - 1, i); Circle circle1 = GetTabFromPoints(true, iOther, j + 1, i); double distance0 = (baseCircle.Frame.Origin - circle0.Frame.Origin).Magnitude - baseCircle.Radius - circle0.Radius; double distance1 = (baseCircle.Frame.Origin - circle1.Frame.Origin).Magnitude - baseCircle.Radius - circle1.Radius; cumulativeErrorTally += distance0 * distance0 + distance1 * distance1; MaxError = Math.Max(Math.Abs(distance0), MaxError); MaxError = Math.Max(Math.Abs(distance1), MaxError); double angleAdjust = (distance0 + distance1) / 2 * AngleForce / GetSpanAt(i, j) / baseCircle.Radius; // / GetSpanAt(i, j) / baseCircle.Radius; // / baseCircle.Radius; newTabAngles[i][j] -= angleAdjust; newTabAngles[i][j - 1] -= angleAdjust / 2; newTabAngles[i][j + 1] -= angleAdjust / 2; double iAngle = AddInHelper.AngleBetween( circle0.Frame.Origin - baseCircle.Frame.Origin, circle1.Frame.Origin - baseCircle.Frame.Origin ); double vOffset = (distance1 - distance0) * VForce; //double uAngleOffset = -(Math.PI / 2 - Math.Abs(iAngle)) * UAngleForce; double uAngleOffset = -(Math.PI * 2 / 3 - Math.Abs(iAngle)) * UAngleForce; Circle circleV = GetTabFromPoints(true, iOther, j, i); double distanceV = (baseCircle.Frame.Origin - circleV.Frame.Origin).Magnitude - baseCircle.Radius - circleV.Radius; double uTouchOffset = -distanceV * UTouchForce; double averageOffset = 0; double averageAngle = 0; double count = 0; foreach (int ii in new int[] { i, iOther }) { foreach (int jj in new int[] { j - 1, j + 1 }) { averageAngle += GetTabFromPoints(true, ii, jj, ii == i ? iOther : i).Radius; count++; } } averageOffset += GetSpanAt(i - 1, j); averageOffset += GetSpanAt(i + 1, j); averageOffset += GetSpanAt(i, j - 1); averageOffset += GetSpanAt(i, j + 1); averageOffset /= 4; averageOffset = averageOffset / count - GetSpanAt(i, j); averageOffset *= -AverageVForce / 2; averageAngle = averageAngle / count - baseCircle.Radius; newTabAngles[i][j] -= averageAngle * AverageTabAngleForce; double size = 1; // (points[i][j + 1] - points[i][j]).Magnitude; double slip = (uAngleOffset + averageOffset + uTouchOffset) * size; newVParameters[i][j] += vOffset + slip; newVParameters[i][j + 1] += vOffset - slip; newVParameters[i][j - 1] += (vOffset + slip) / 2; newVParameters[i][j + 2] += (vOffset - slip) / 2; // double oldSpan = (points[i][j + 1] - points[i][j]).Magnitude; // double newSpan = (points[i][j + 1] - points[i][j]).Magnitude; Trace.WriteIf(Iteration % 400 == 0, tabAngles[i][j] + " "); // Trace.WriteIf(Iteration % 400 == 0, iAngle + " "); // Trace.WriteIf(Iteration % 400 == 0, GetSpanAt(i,j) + " "); #endif } Trace.WriteLineIf(Iteration % 400 == 0, ""); } #if false // Average antipodal points // for l(i, j), // l(i, j) == l(-i, pi+j)* == l(i+2pi, -j) == l(-i-2pi, pi-j)* // Where * means x=x, y=-y, z=-z for (int i = 0; i < iSteps; i++) { for (int j = 0; j < jSteps / 2; j++) { double average = ( newVParameters[i][j] + newVParameters[-i][j + jSteps / 2] - Math.PI + (j < 2 ? 0 : 2 * Math.PI) - newVParameters[i + iSteps][-j + 1] + Math.PI - newVParameters[-i - iSteps][-j + jSteps / 2 + 1] ) / 4; newVParameters[i][j] = average; newVParameters[-i][j + jSteps / 2] = average + Math.PI; newVParameters[i + iSteps][-j + 1] = (j < 2 ? 0 : 2 * Math.PI) - average; newVParameters[-i - iSteps][-j + jSteps / 2 + 1] = Math.PI - average; average = ( tabAngles[i][j] + tabAngles[-i][j + jSteps / 2 + 1] + tabAngles[i + iSteps][-j] + tabAngles[-i - iSteps][-j + jSteps / 2 + 1] ) / 4; tabAngles[i][j] = average; tabAngles[-i][j + jSteps / 2 + 1] = average; tabAngles[i + iSteps][-j] = average; tabAngles[-i - iSteps][-j + jSteps / 2 + 1] = average; } } #endif CumulativeError = Math.Sqrt(cumulativeErrorTally / (steps * steps * 2)); // Trace.WriteLine(lastCumulativeError); // We're not calculating the points for the last iteration. Whatevs. // vParameters = newVParameters; //tabAngles = newTabAngles; #if false for (int i = 0; i < iSteps; i++) { double u = 2 * Math.PI * (double)i / iSteps; for (int j = 0; j < jSteps; j++) { points[i][j] = Gyroid.Evaluate(PointUV.Create(vParameters[i][j], u), p, q, circleAngle, inverseOffset, true) * scale; // Trace.WriteLine(string.Format("{0} {1} {2}", i, j, tabAngles[i][j])); } } #endif }
static void TumbleSpeed_Executing(object sender, EventArgs e) { activeTumbler.Speed = AddInHelper.ParseAffixedCommand(((Command)sender).Name, tumbleSpeedCommandName); }
static void growSelectionThreshold_Executing(object sender, EventArgs e) { threshold = AddInHelper.ParseAffixedCommand(((Command)sender).Name, growSelectionThresholdCommandName); Command.GetCommand(growSelectionThresholdCommandName).Text = growSelectionThresholdCommandText + threshold.ToString(); AddInHelper.RefreshMainform(); }
// hardwired to place on about inch-spaced points // Edge-only for now -- See EO comments static void MakeTabs_Executing(object sender, EventArgs e) { Window activeWindow = Window.ActiveWindow; Layer tabLayer = NoteHelper.CreateOrGetLayer(activeWindow.ActiveContext.Context.Document, "Tabs", System.Drawing.Color.Fuchsia); ICollection <ITrimmedCurve> trimmedCurves = AddInHelper.GetITrimmedCurvesOfSelectedTopology(activeWindow); // quantize with lines to points separated by approx targetDistance; TrimmedCurveChain curveChain = new TrimmedCurveChain(trimmedCurves); Point lastPoint = curveChain.Curves[0].StartPoint; double tolerance = 0.2 * inches; double targetDistance = 1 * inches; trimmedCurves = new List <ITrimmedCurve>(); Dictionary <ITrimmedCurve, Direction> OriginalNormals = new Dictionary <ITrimmedCurve, Direction>(); double extraLength = 0; foreach (OrientedTrimmedCurve curve in curveChain.Curves) { Point point = curve.EndPoint; if (Math.Abs((lastPoint - point).Magnitude - targetDistance) > tolerance) { extraLength += (lastPoint - point).Magnitude; continue; } CurveSegment curveSegment = null; // if (extraLength == 0) curveSegment = CurveSegment.Create(lastPoint, point); // else // curveSegment = CurveSegment.Create(point - (lastPoint - point).Direction * ((lastPoint - point).Magnitude + extraLength), point); trimmedCurves.Add(curveSegment); Edge edge = curve.TrimmedCurve as Edge; if (edge != null) { Face face = null; foreach (Face testFace in edge.Faces) { face = testFace; break; } SurfaceEvaluation surfEval = face.ProjectPoint(curve.StartPoint); OriginalNormals[curveSegment] = surfEval.Normal; } lastPoint = point; // extraLength = 0; } curveChain = new TrimmedCurveChain(trimmedCurves); if (AreTabsFlipped) { curveChain.Reverse(); } List <Window> curveWindows = new List <Window>(Document.Open(@"C:\Users\bcr.SPACECLAIM\Documents\Models\Pod Tent\TabCurve.scdoc", false)); bool adjustEnds = true; #if false List <Window> curveWindows = new List <Window>(Document.Open(@"C:\Users\bcr.SPACECLAIM\Documents\Models\Pod Tent\TabStrapEdgeCurve.scdoc", false)); bool adjustEnds = true; #endif NurbsCurve middle = GetFirstNurbsCurveFromPart(curveWindows[0].Scene as Part); Debug.Assert(middle != null); NurbsCurve endTab = null; NurbsCurve endSlot = null; foreach (Component component in (curveWindows[0].Scene as Part).Components) { if (component.Template.Name == "EndTab") { endTab = GetFirstNurbsCurveFromPart(component.Template); } if (component.Template.Name == "EndSlot") { endSlot = GetFirstNurbsCurveFromPart(component.Template); } } Debug.Assert(endTab != null); Debug.Assert(endSlot != null); Point startPoint = curveChain.Curves[0].StartPoint; Point endPoint = curveChain.Curves[0].EndPoint; Point startTail = startPoint + (endPoint - startPoint); bool mirror = false; if (IsTabStartSlot) { NurbsCurve tmp = endTab; endTab = endSlot; endSlot = tmp; mirror = !mirror; } for (int i = 0; i < curveChain.Curves.Count; i++) { Point endTail; if (i == curveChain.Curves.Count - 1) { endTail = curveChain.Curves[i].EndPoint + (curveChain.Curves[i].EndPoint - curveChain.Curves[i].StartPoint); } else { endTail = curveChain.Curves[i + 1].EndPoint; } Point mid = Point.Origin + (startPoint.Vector + endPoint.Vector) / 2; Direction startDirection = (startPoint - startTail).Direction; Direction lineDirection = (endPoint - startPoint).Direction; Direction endDirection = (endTail - endPoint).Direction; Direction upDirection = Direction.DirZ; //if (upDirection.IsParallelTo(lineDirection)) // upDirection = Direction.DirY; if (OriginalNormals.ContainsKey(curveChain.Curves[i].TrimmedCurve)) { upDirection = OriginalNormals[curveChain.Curves[i].TrimmedCurve]; } Direction normalDirection = Direction.Cross(lineDirection, upDirection); Line startMidLine; if (startDirection.UnitVector == lineDirection.UnitVector) { startMidLine = Line.Create(startPoint, Direction.Cross(lineDirection, upDirection)); } else { startMidLine = Line.Create(startPoint, (startDirection.UnitVector - lineDirection.UnitVector).Direction); } Line endMidLine; if (lineDirection.UnitVector == endDirection.UnitVector) { endMidLine = Line.Create(endPoint, Direction.Cross(lineDirection, upDirection)); } else { endMidLine = Line.Create(endPoint, (lineDirection.UnitVector - endDirection.UnitVector).Direction); } NurbsCurve template = middle; if (mirror) { lineDirection = -lineDirection; Line tmp = startMidLine; startMidLine = endMidLine; endMidLine = tmp; } if (i == 0) { template = endSlot; } if (i == curveChain.Curves.Count - 1) { if (mirror ^ IsTabStartSlot) { template = endSlot; } else { template = endTab; } } Frame frame = Frame.Create(mid, lineDirection, normalDirection); Matrix transform = Matrix.CreateMapping(frame); ControlPoint[] controlPoints = new ControlPoint[template.ControlPoints.Length]; int j = 0; foreach (ControlPoint controlPoint in template.ControlPoints) { controlPoints[j] = new ControlPoint(transform * controlPoint.Position, controlPoint.Weight); j++; } //CurveEvaluation curveEval = null; //curveEval = startMidLine.Evaluate(1); //DesignCurve.Create(activeWindow.SubjectMatter as Part, CurveSegment.Create(startPoint, curveEval.Point)); //curveEval = endMidLine.Evaluate(1); //DesignCurve.Create(activeWindow.SubjectMatter as Part, CurveSegment.Create(endPoint, curveEval.Point)); MakeNurbsEndTangent(endMidLine, controlPoints, 0, 1); if (adjustEnds) { MakeNurbsEndTangent(startMidLine, controlPoints, controlPoints.Length - 1, controlPoints.Length - 2); } Curve curve = NurbsCurve.Create(template.Data, controlPoints); CurveSegment curveSegment = CurveSegment.Create(curve, template.Parameterization.Range.Value); DesignCurve tab = DesignCurve.Create(activeWindow.ActiveContext.Context as Part, curveSegment); tab.Layer = tabLayer; startTail = startPoint; startPoint = endPoint; endPoint = endTail; mirror = !mirror; } foreach (Window window in curveWindows) { window.Close(); } }