public void TestRealWorldExpression2() { int inputLength = 12; var input = new string('\0', inputLength); var builder = new LineBuilder(input, null); List<string> lines; var block1 = new TextBlock("c"); var block2 = new TextBlock("mc"); var block3 = new TextBlock("ccc"); var block4 = new TextBlock("mm"); var starBlock1 = new ZeroOrMoreBlock(block1); var orGroupBlock = new OrGroupBlock(new RegexBlock[] { block3, block4 }); var starBlock2 = new ZeroOrMoreBlock(orGroupBlock); AndGroupBlock andGroupBlock = new AndGroupBlock(new RegexBlock [] { starBlock1, block2, starBlock2 }); var regex = new RegularExpression(andGroupBlock); lines = builder.GetLines(regex).ToList(); // Check against regular expression string regexPattern = "c*mc(ccc|mm)*"; CheckGeneratedLines(lines, regexPattern); }
public void GetLinesTestWithEmptyInput() { int inputLength = 3; var input = new string('\0', inputLength); var builder = new LineBuilder(input, null); List<string> lines; // a+b+ - should be abb, aab var aBlock = new TextBlock("a"); var bBlock = new TextBlock("b"); var plusBlock1 = new OneOrMoreBlock(aBlock); var plusBlock2 = new OneOrMoreBlock(bBlock); var groupBlock = new AndGroupBlock(new RegexBlock[] { plusBlock1, plusBlock2 }); var regex1 = new RegularExpression(groupBlock); lines = builder.GetLines(regex1).ToList(); string[] expectedLines = new string[] { "abb", "aab" }; CollectionAssert.AreEquivalent(expectedLines, lines); // a*b* - should be bbb, abb, aab, aaa var starBlock1 = new ZeroOrMoreBlock(aBlock); var starBlock2 = new ZeroOrMoreBlock(bBlock); groupBlock = new AndGroupBlock(new RegexBlock[] { starBlock1, starBlock2 }); var regex2 = new RegularExpression(groupBlock); lines = builder.GetLines(regex2).ToList(); expectedLines = new string[] { "bbb", "abb", "aab", "aaa" }; CollectionAssert.AreEquivalent(expectedLines, lines); }
public void GetLinesFromOneOrMoreBlockTest() { int patternLength = 4; var pattern = new string('\0', patternLength); LineBuilder builder = new LineBuilder(pattern, null); string text = "a"; var textBlock = new TextBlock(text); OneOrMoreBlock oneOrMoreBlock = new OneOrMoreBlock(textBlock); List<string> lines = builder.GetLinesFromOneOrMoreBlock(0, oneOrMoreBlock).ToList(); Assert.AreEqual(patternLength, lines.Count); StringBuilder sb = new StringBuilder(); for (int i = 0; i < patternLength; i++) { sb.Append(text); Assert.AreEqual(sb.ToString(), lines[i]); } TextBlock aBlock = new TextBlock("a"); TextBlock bBlock = new TextBlock("b"); OrGroupBlock orGroupBlock = new OrGroupBlock(new[] { aBlock, bBlock }); oneOrMoreBlock = new OneOrMoreBlock(orGroupBlock); lines = builder.GetLinesFromOneOrMoreBlock(0, oneOrMoreBlock).ToList(); Assert.AreEqual(30, lines.Count); }
public MainViewModel() { // titles this.Title = "Simple Demo (Workitem 10043)"; this.SubTitle = "Please switch to Viewport 2 and then back to Viewport 1"; // camera setup this.Camera = new PerspectiveCamera { Position = new Point3D(3, 3, 5), LookDirection = new Vector3D(-3, -3, -5), UpDirection = new Vector3D(0, 1, 0) }; if (this.RenderTechniquesManager != null) { // default render technique this.RenderTechnique = RenderTechniquesManager.RenderTechniques.Get(DefaultRenderTechniqueNames.Blinn); } // setup lighting this.AmbientLightColor = new Color4(0.1f, 0.1f, 0.1f, 1.0f); this.DirectionalLightColor = Color.White; this.DirectionalLightDirection = new Vector3(-2, -5, -2); // floor plane grid this.Grid = LineBuilder.GenerateGrid(); this.GridColor = SharpDX.Color.Black; this.GridTransform = new Media3D.TranslateTransform3D(-5, -1, -5); // scene model3d var b1 = new MeshBuilder(); b1.AddSphere(new Vector3(0, 0, 0), 0.5); b1.AddBox(new Vector3(0, 0, 0), 1, 0.5, 2, BoxFaces.All); var meshGeometry = b1.ToMeshGeometry3D(); meshGeometry.Colors = new Color4Collection(meshGeometry.TextureCoordinates.Select(x => x.ToColor4())); this.Model = meshGeometry; // lines model3d var e1 = new LineBuilder(); e1.AddBox(new Vector3(0, 0, 0), 1, 0.5, 2); this.Lines = e1.ToLineGeometry3D(); // model trafos this.Model1Transform = new Media3D.TranslateTransform3D(0, 0, 0); this.Model2Transform = new Media3D.TranslateTransform3D(-2, 0, 0); this.Model3Transform = new Media3D.TranslateTransform3D(+2, 0, 0); // model materials this.RedMaterial = PhongMaterials.Red; this.GreenMaterial = PhongMaterials.Green; this.BlueMaterial = PhongMaterials.Blue; //var diffColor = this.RedMaterial.DiffuseColor; //diffColor.Alpha = 0.5f; //this.RedMaterial.DiffuseColor = diffColor; }
public MainViewModel() { RenderTechniquesManager = new DefaultRenderTechniquesManager(); RenderTechnique = RenderTechniquesManager.RenderTechniques[DefaultRenderTechniqueNames.Blinn]; EffectsManager = new DefaultEffectsManager(RenderTechniquesManager); this.Title = "Line Shading Demo (HelixToolkitDX)"; this.SubTitle = null; // camera setup this.Camera = new PerspectiveCamera { Position = new Point3D(0, 5, 5), LookDirection = new Vector3D(-0, -5, -5), UpDirection = new Vector3D(0, 1, 0) }; // setup lighting this.AmbientLightColor = new Color4(0.1f, 0.1f, 0.1f, 1.0f); this.DirectionalLightColor = Color.White; this.DirectionalLightDirection = new Vector3(-2, -5, -2); // floor plane grid this.Grid = LineBuilder.GenerateGrid(); this.GridColor = SharpDX.Color.Black; this.GridTransform = new TranslateTransform3D(-5, -1, -5); // scene model3d var b1 = new MeshBuilder(); b1.AddSphere(new Vector3(0, 0, 0), 0.5); b1.AddBox(new Vector3(0, 0, 0), 1, 0.5, 2, BoxFaces.All); this.Model = b1.ToMeshGeometry3D(); // lines model3d var e1 = new LineBuilder(); e1.AddBox(new Vector3(0, 0, 0), 1, 0.5, 2); //e1.AddLine(new Vector3(-1, 0, 0), new Vector3(1, 0, 0)); this.Lines = e1.ToLineGeometry3D(); // lines params this.LineThickness = 2; this.LineSmoothness = 2.0; this.LinesEnabled = true; this.GridEnabled = true; // model trafos this.Model1Transform = new TranslateTransform3D(0, 0, 0); this.Model2Transform = new TranslateTransform3D(-2, 0, 0); this.Model3Transform = new TranslateTransform3D(+2, 0, 0); // model materials this.Material1 = PhongMaterials.PolishedGold; this.Material2 = PhongMaterials.Copper; this.Material3 = PhongMaterials.Glass; }
public void GetLinesFromOrGroupBlockTest() { int patternLength = 2; var pattern = new string('\0', patternLength); LineBuilder builder = new LineBuilder(pattern, null); TextBlock aBlock = new TextBlock("a"); TextBlock bBlock = new TextBlock("bb"); TextBlock cBlock = new TextBlock("ccc"); OrGroupBlock orGroupBlock = new OrGroupBlock(new[] { aBlock, bBlock, cBlock }); List<string> lines = builder.GetLinesFromOrGroupBlock(0, orGroupBlock).ToList(); string[] expectedLines = new string[] { "a", "bb"}; CollectionAssert.AreEquivalent(expectedLines, lines); }
public MainViewModel() { RenderTechniquesManager = new DefaultRenderTechniquesManager(); RenderTechnique = RenderTechniquesManager.RenderTechniques[DefaultRenderTechniqueNames.Blinn]; EffectsManager = new DefaultEffectsManager(RenderTechniquesManager); this.Title = "Manipulator Demo"; this.SubTitle = null; // camera setup this.Camera = new OrthographicCamera { Position = new Point3D(0, 0, 5), LookDirection = new Vector3D(0, 0, -5), UpDirection = new Vector3D(0, 1, 0) }; // setup lighting this.AmbientLightColor = new Color4(0.2f, 0.2f, 0.2f, 1.0f); this.DirectionalLightColor = Color.White; this.DirectionalLightDirection = new Vector3(-2, -5, -2); // floor plane grid this.Grid = LineBuilder.GenerateGrid(); this.GridColor = SharpDX.Color.Black; this.GridTransform = new TranslateTransform3D(-5, -1, -5); // scene model3d var b1 = new MeshBuilder(); b1.AddSphere(new Vector3(0, 0, 0), 0.5); b1.AddBox(new Vector3(0, 0, 0), 1, 0.5, 1.5, BoxFaces.All); this.Model = b1.ToMeshGeometry3D(); // lines model3d var e1 = new LineBuilder(); e1.AddBox(new Vector3(0, 0, 0), 1, 0.5, 1.5); this.Lines = e1.ToLineGeometry3D(); // model trafos this.Model1Transform = CreateAnimatedTransform(new Vector3D(0, 0, 0), new Vector3D(1, 1, 1), 20); this.Model2Transform = new TranslateTransform3D(-3, 0, 0); this.Model3Transform = new TranslateTransform3D(+3, 0, 0); // model materials this.Material1 = PhongMaterials.Orange; this.Material2 = PhongMaterials.Orange; this.Material3 = PhongMaterials.Red; var dr = Color.DarkRed; Console.WriteLine(dr); }
public void ParseAndGenerateExpressionTest3() { int inputLength = 4; var input = new string('\0', inputLength); var builder = new LineBuilder(input, null); List<string> lines; string regexPattern = "([^emc]|em)*"; RegexParser parser = new RegexParser(); RegularExpression regex = parser.Parse(regexPattern); lines = builder.GetLines(regex).Take(10).ToList(); Assert.IsTrue(lines.Count > 1); // Check against regular expression CheckGeneratedLines(lines, regexPattern); }
public void ParseAndGenerateExpressionTest4() { int inputLength = 7; var input = new string('\0', inputLength); var builder = new LineBuilder(input, null); List<string> lines; string regexPattern = ".*g.*v.*h.*"; RegexParser parser = new RegexParser(); RegularExpression regex = parser.Parse(regexPattern); lines = builder.GetLines(regex).Take(10).ToList(); Assert.AreNotEqual(0, lines.Count); // Check against regular expression CheckGeneratedLines(lines, regexPattern); }
public void GetLinesFromAndGroupBlockTest() { int patternLength = 4; var pattern = new string('\0', patternLength); LineBuilder builder = new LineBuilder(pattern, null); // (a|aa)(b|bb) TextBlock aBlock = new TextBlock("a"); TextBlock aaBlock = new TextBlock("aa"); TextBlock bBlock = new TextBlock("b"); TextBlock bbBlock = new TextBlock("bb"); OrGroupBlock orGroupBlock1 = new OrGroupBlock(new[] { aBlock, aaBlock }); OrGroupBlock orGroupBlock2 = new OrGroupBlock(new[] { bBlock, bbBlock }); AndGroupBlock andGroupBlock = new AndGroupBlock(new[] { orGroupBlock1, orGroupBlock2 }); List<string> lines = builder.GetLinesFromAndGroupBlock(0, andGroupBlock).ToList(); string[] expectedLines = new string[] { "ab", "abb", "aab", "aabb" }; CollectionAssert.AreEquivalent(expectedLines, lines); }
public static ParserAction Parse(ExpressionWalker ew, string code, LineBuilder output) { // multiline: // %foreach expr% // code #1 // % // singleline: // %foreach expr // code #1 ew.IsCurrentOrThrow(ExpressionToken.Foreach); ew.NextOrThrow(); //parse the arguments for the foreach var args = ArgumentsExpression.Parse(ew, token => token.Token == ExpressionToken.NewLine || token.Token == ExpressionToken.Mod, false, typeof(ForeachExpression)); //ew.Back(); //agrumentsExpression skips the closer token and we need it to identify if this is a singleline or multiline if (output == null) { output = new LineBuilder(code); } string content; var relatedLines = new List <Line>(); relatedLines.AddRange(output.GetLinesRelated(args.Matches())); if (ew.PeakBack.Token == ExpressionToken.Mod) { //the content is % to % block var leftBorder = ew.Current.Match; var nextMod = ForeachExpression.FindCloser(leftBorder.Index, code); //handle implicit end block (when % is not existing) if (nextMod == -1) { nextMod = code.Length - 1; } ew.SkipForwardWhile(token => token.Match.Index < nextMod); ew.Next(); //skip % itself var l1 = output.GetLineAt(leftBorder.Index) ?? output.Lines.First(); relatedLines.AddRange(new Range(l1.LineNumber, output.GetLineAt(nextMod).LineNumber).EnumerateIndexes().Select(output.GetLineByLineNumber)); content = null; } else { //the content is only next line var leftMod = ew.Current.Match; var nextMod = code.IndexOf('\n', leftMod.Index); relatedLines.Add(output.GetLineByLineNumber(relatedLines.Last().LineNumber + 1)); //next line. content = code.Substring(leftMod.Index, nextMod == -1 ? (code.Length - leftMod.Index) : nextMod - leftMod.Index); } relatedLines = relatedLines.Distinct().OrderBy(l => l.StartIndex).ToList(); if (relatedLines.Count(l => l.Content.Contains("%foreach")) <= relatedLines.Count(l => l.CleanContent() == "%") && relatedLines.Last().CleanContent() == "%") { relatedLines[relatedLines.Count - 1].MarkedForDeletion = true; relatedLines.RemoveAt(relatedLines.Count - 1); } //make sure to clean out % at the end if (content == null) { content = relatedLines.Select(l => l.Content).StringJoin(); } //all lines of the foreach are destined to deletion foreach (var line in relatedLines) { line.MarkedForDeletion = true; } return(new ParserAction(ParserToken.ForeachLoop, relatedLines, new ForeachExpression() { Content = content, Arguments = args })); }
public MainViewModel() { // titles Title = "Simple Demo"; SubTitle = "WPF & SharpDX"; // camera setup Camera = new PerspectiveCamera { Position = new Point3D(-6, 8, 23), LookDirection = new Vector3D(11, -4, -23), UpDirection = new Vector3D(0, 1, 0), FarPlaneDistance = 5000 }; EffectsManager = new CustomEffectsManager(); var builder = new MeshBuilder(true); Vector3[] points = new Vector3[Width * Height]; for (int i = 0; i < Width; ++i) { for (int j = 0; j < Height; ++j) { points[i * Width + j] = new Vector3(i / 10f, 0, j / 10f); } } builder.AddRectangularMesh(points, Width); Model = builder.ToMesh(); for (int i = 0; i < Model.Normals.Count; ++i) { Model.Normals[i] = new Vector3(0, Math.Abs(Model.Normals[i].Y), 0); } StartColor = Colors.Blue; MidColor = Colors.Green; EndColor = Colors.Red; var lineBuilder = new LineBuilder(); lineBuilder.AddLine(new Vector3(0, 0, 0), new Vector3(10, 0, 0)); lineBuilder.AddLine(new Vector3(0, 0, 0), new Vector3(0, 10, 0)); lineBuilder.AddLine(new Vector3(0, 0, 0), new Vector3(0, 0, 10)); AxisModel = lineBuilder.ToLineGeometry3D(); AxisModel.Colors = new Color4Collection(AxisModel.Positions.Count); AxisModel.Colors.Add(Colors.Red.ToColor4()); AxisModel.Colors.Add(Colors.Red.ToColor4()); AxisModel.Colors.Add(Colors.Green.ToColor4()); AxisModel.Colors.Add(Colors.Green.ToColor4()); AxisModel.Colors.Add(Colors.Blue.ToColor4()); AxisModel.Colors.Add(Colors.Blue.ToColor4()); AxisLabel = new BillboardText3D(); AxisLabel.TextInfo.Add(new TextInfo() { Origin = new Vector3(11, 0, 0), Text = "X", Foreground = Colors.Red.ToColor4() }); AxisLabel.TextInfo.Add(new TextInfo() { Origin = new Vector3(0, 11, 0), Text = "Y", Foreground = Colors.Green.ToColor4() }); AxisLabel.TextInfo.Add(new TextInfo() { Origin = new Vector3(0, 0, 11), Text = "Z", Foreground = Colors.Blue.ToColor4() }); builder = new MeshBuilder(true); builder.AddSphere(new Vector3(-15, 0, 0), 5); SphereModel = builder.ToMesh(); GenerateNoiseCommand = new RelayCommand((o) => { CreatePerlinNoise(); }); CreatePerlinNoise(); }
/// <summary> /// /// </summary> /// <param name="octant"></param> /// <param name="context"></param> /// <param name="model"></param> /// <param name="modelMatrix"></param> /// <param name="rayWS"></param> /// <param name="rayModel"></param> /// <param name="hits"></param> /// <param name="isIntersect"></param> /// <param name="hitThickness"></param> /// <returns></returns> protected override bool HitTestCurrentNodeExcludeChild(ref Octant octant, RenderContext context, object model, Matrix modelMatrix, ref Ray rayWS, ref Ray rayModel, ref List <HitTestResult> hits, ref bool isIntersect, float hitThickness) { isIntersect = false; if (!octant.IsBuilt) { return(false); } var isHit = false; var bound = octant.Bound; bound.Maximum += new Vector3(hitThickness); bound.Minimum -= new Vector3(hitThickness); var lastDist = double.MaxValue; //Hit test in local space. if (rayModel.Intersects(ref bound)) { isIntersect = true; if (octant.Count == 0) { return(false); } var result = new LineHitTestResult { IsValid = false, Distance = double.MaxValue }; result.Distance = double.MaxValue; for (int i = octant.Start; i < octant.End; ++i) { var idx = Objects[i].Key * 2; var idx1 = Indices[idx]; var idx2 = Indices[idx + 1]; var v0 = Positions[idx1]; var v1 = Positions[idx2]; var t0 = Vector3.TransformCoordinate(v0, modelMatrix); var t1 = Vector3.TransformCoordinate(v1, modelMatrix); Vector3 sp, tp; float sc, tc; var rayToLineDistance = LineBuilder.GetRayToLineDistance(rayWS, t0, t1, out sp, out tp, out sc, out tc); var svpm = context.ScreenViewProjectionMatrix; Vector4 sp4; Vector4 tp4; Vector3.Transform(ref sp, ref svpm, out sp4); Vector3.Transform(ref tp, ref svpm, out tp4); var sp3 = sp4.ToVector3(); var tp3 = tp4.ToVector3(); var tv2 = new Vector2(tp3.X - sp3.X, tp3.Y - sp3.Y); var dist = tv2.Length(); if (dist < lastDist && dist <= hitThickness) { lastDist = dist; result.PointHit = sp; result.NormalAtHit = sp - tp; // not normalized to get length result.Distance = (rayWS.Position - sp).Length(); result.RayToLineDistance = rayToLineDistance; result.ModelHit = model; result.IsValid = true; result.Tag = idx; // For compatibility result.LineIndex = idx; result.TriangleIndices = null; // Since triangles are shader-generated result.RayHitPointScalar = sc; result.LineHitPointScalar = tc; isHit = true; } } if (isHit) { isHit = false; if (hits.Count > 0) { if (hits[0].Distance > result.Distance) { hits[0] = result; isHit = true; } } else { hits.Add(result); isHit = true; } } } return(isHit); }
static GeometryNode() { _BuiltLines = new List<FullLine>(); _LineBuilder = new LineBuilder(); }
public MainViewModel() { // titles Title = "Simple Demo"; SubTitle = "WPF & SharpDX"; // camera setup Camera = new PerspectiveCamera { Position = new Point3D(3, 3, 5), LookDirection = new Vector3D(-3, -3, -5), UpDirection = new Vector3D(0, 1, 0), FarPlaneDistance = 5000000 }; // default render technique RenderTechniquesManager = new DefaultRenderTechniquesManager(); RenderTechnique = RenderTechniquesManager.RenderTechniques[DefaultRenderTechniqueNames.Blinn]; EffectsManager = new DefaultEffectsManager(RenderTechniquesManager); // setup lighting AmbientLightColor = new Color4(0.1f, 0.1f, 0.1f, 1.0f); DirectionalLightColor = Color.White; DirectionalLightDirection = new Vector3(-2, -5, -2); // floor plane grid Grid = LineBuilder.GenerateGrid(); GridColor = SharpDX.Color.Black; GridTransform = new Media3D.TranslateTransform3D(-5, -1, -5); // scene model3d var b1 = new MeshBuilder(); b1.AddSphere(new Vector3(0, 0, 0), 0.5); b1.AddBox(new Vector3(0, 0, 0), 1, 0.5, 2, BoxFaces.All); var meshGeometry = b1.ToMeshGeometry3D(); meshGeometry.Colors = new Color4Collection(meshGeometry.TextureCoordinates.Select(x => x.ToColor4())); Model = meshGeometry; // lines model3d var e1 = new LineBuilder(); e1.AddBox(new Vector3(0, 0, 0), 1, 0.5, 2); Lines = e1.ToLineGeometry3D(); // model trafos Model1Transform = new Media3D.TranslateTransform3D(0, 0, 0); Model2Transform = new Media3D.TranslateTransform3D(-2, 0, 0); Model3Transform = new Media3D.TranslateTransform3D(+2, 0, 0); // model materials RedMaterial = PhongMaterials.Red; GreenMaterial = PhongMaterials.Green; BlueMaterial = PhongMaterials.Blue; //var diffColor = this.RedMaterial.DiffuseColor; //diffColor.Alpha = 0.5f; //this.RedMaterial.DiffuseColor = diffColor; Points = new PointGeometry3D(); var ptPos = new Vector3Collection(); var ptIdx = new IntCollection(); for (int x = 0; x < 10; x++) { for (int y = 0; y < 10; y++) { for (int z = 0; z < 10; z++) { ptIdx.Add(ptPos.Count); ptPos.Add(new Vector3(x, y, z)); } } } Points.Positions = ptPos; Points.Indices = ptIdx; Text = new BillboardText3D(); for (var i = 0; i < 50; i++) { for (var j = 0; j < 50; j++) { Text.TextInfo.Add(new TextInfo("Hello World", new Vector3(i, j, 0))); } } }
public void BuildNewLineFromOddIndeciesOfOld_String_CorrectResult(string actual, string expected) { LineBuilder lineBuilder = new LineBuilder(); Assert.Equal(expected, lineBuilder.BuildNewLineFromOddIndeciesOfOld(actual)); }
public void ParseAndGenerateExpressionTest7() { //var input = "\0\0\0\0\0\0c\0o\0d\0"; var input = "\0\0\0\0\0\0c\0\0\0\0\0"; var builder = new LineBuilder(input, null); string regexPattern = "[^c]*mmm[^c]*"; var parser = new RegexParser(); RegularExpression regex = parser.Parse(regexPattern); Assert.IsFalse(builder.GetLines(regex).Any()); }
public MainViewModel() { // Lines Setup this.LineThickness = 1d; this.TriangulationThickness = .5; this.ShowTriangleLines = true; // Count Setup this.PointCount = 1000; // Lighting Setup this.AmbientLightColor = new Color4(1f, 1f, 1f, 1.0f); this.DirectionalLightColor = Color.White; this.DirectionalLightDirection = new Vector3(0, -1, 0); // Model Transformations this.ModelTransform = new TranslateTransform3D(0, 0, 0); this.ModelLineTransform = new TranslateTransform3D(0, 0.001, 0); // Model Materials and Colors this.Material = PhongMaterials.PolishedBronze; this.TriangulationColor = SharpDX.Color.Black; // Grid Setup this.Grid = LineBuilder.GenerateGrid(Vector3.UnitY, -5, 5, 0, 10); this.GridColor = SharpDX.Color.DarkGray; this.GridTransform = new TranslateTransform3D(0, -0.01, 0); //this.GroundGeometry = new Element3DCollection(); //this.PlayersGeometry = new Element3DCollection(); RenderTechniquesManager = new DefaultRenderTechniquesManager(); RenderTechnique = RenderTechniquesManager.RenderTechniques[DefaultRenderTechniqueNames.Blinn]; EffectsManager = new DefaultEffectsManager(RenderTechniquesManager); // setup lighting this.LightDirectionTransform = CreateAnimatedTransform(-DirectionalLightDirection.ToVector3D(), new Vector3D(0, 1, -1), 24); this.ShadowMapResolution = new Vector2(2048, 2048); // camera setup this.Camera = new PerspectiveCamera { Position = (Point3D)(-DirectionalLightDirection.ToVector3D()), LookDirection = DirectionalLightDirection.ToVector3D(), UpDirection = new Vector3D(0, 1, 0) }; // floor plane grid //Grid = LineBuilder.GenerateGrid(); //GridColor = SharpDX.Color.Black; //GridTransform = new Media3D.TranslateTransform3D(-5, -1, -5); // scene model3d //var b1 = new MeshBuilder(); //b1.AddSphere(new Vector3(0, 0, 0), 0.5); //b1.AddBox(new Vector3(0, 0, 0), 1, 0.25, 2, BoxFaces.All); //Model = b1.ToMeshGeometry3D(); ////Instances = new[] { Matrix.Translation(0, 0, -1.5f), Matrix.Translation(0, 0, 1.5f) }; //var b2 = new MeshBuilder(); //b2.AddBox(new Vector3(0, 0, 0), 10, 0, 10, BoxFaces.PositiveY); //Plane = b2.ToMeshGeometry3D(); //PlaneTransform = new Media3D.TranslateTransform3D(-0, -2, -0); //GrayMaterial = PhongMaterials.LightGray; ////GrayMaterial.TextureMap = new BitmapImage(new System.Uri(@"TextureCheckerboard2.jpg", System.UriKind.RelativeOrAbsolute)); //// lines model3d //Lines = LineBuilder.GenerateBoundingBox(Model); //// model trafos //Model1Transform = new Media3D.TranslateTransform3D(0, 0, 0); //Model2Transform = new Media3D.TranslateTransform3D(-2, 0, 0); //Model3Transform = new Media3D.TranslateTransform3D(+2, 0, 0); // model materials RedMaterial = PhongMaterials.Glass; GreenMaterial = PhongMaterials.Green; BlueMaterial = PhongMaterials.Blue; }
public void GetSpacesAbove2() { Assert.AreEqual(" ", LineBuilder.GetIntermediarySpacesForLine(5)); }
/// <summary> /// Method to draw the radials inside the range rings /// Must have at least 1 radial /// All radials are drawn from the center point to the farthest ring /// </summary> private void DrawRadials() { // must have at least 1 if (NumberOfRadials < 1) { return; } var nameConverter = new EnumToFriendlyNameConverter(); double azimuth = 0.0; double interval = 360.0 / NumberOfRadials; double radialLength = 0.0; if (!(RingType == RingTypes.Fixed)) { radialLength = maxDistance; } else { radialLength = Distance * NumberOfRings; } try { // for each radial, draw from center point for (int x = 0; x < NumberOfRadials; x++) { var polyline = QueuedTask.Run(() => { MapPoint movedMP = null; var mpList = new List <MapPoint>() { Point1 }; // get point 2 var results = GeometryEngine.Instance.GeodeticMove(mpList, MapView.Active.Map.SpatialReference, radialLength, GetLinearUnit(LineDistanceType), GetAzimuthAsRadians(azimuth), GetCurveType()); // update feedback //UpdateFeedback(); foreach (var mp in results) { movedMP = mp; } if (movedMP != null) { var movedMPproj = GeometryEngine.Instance.Project(movedMP, Point1.SpatialReference); var segment = LineBuilder.CreateLineSegment(Point1, (MapPoint)movedMPproj); return(PolylineBuilder.CreatePolyline(segment)); } else { return(null); } }).Result; Geometry newline = GeometryEngine.Instance.GeodeticDensifyByLength(polyline, 0, LinearUnit.Meters, GeodeticCurveType.Loxodrome); if (newline != null) { // Hold onto the attributes in case user saves graphics to file later var displayValue = nameConverter.Convert(LineDistanceType, typeof(string), new object(), CultureInfo.CurrentCulture); RangeAttributes rangeAttributes = new RangeAttributes() { mapPoint = Point1, numRings = NumberOfRings, distance = radialLength, centerx = Point1.X, centery = Point1.Y, distanceunit = displayValue.ToString(), ringorradial = "Radial" }; // AddGraphicToMap(newline, rangeAttributes); CreateRangeRingOrRadialFeature(newline, rangeAttributes); } azimuth += interval; } } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex); } }
public MainViewModel() { EffectsManager = new DefaultEffectsManager(); RenderTechnique = EffectsManager[DefaultRenderTechniqueNames.Blinn]; this.Title = "Line Shading Demo (HelixToolkitDX)"; this.SubTitle = null; // camera setup this.Camera = new PerspectiveCamera { Position = new Point3D(0, 5, 5), LookDirection = new Vector3D(-0, -5, -5), UpDirection = new Vector3D(0, 1, 0) }; // setup lighting this.AmbientLightColor = Colors.DimGray; this.DirectionalLightColor = Colors.White; this.DirectionalLightDirection = new Vector3D(-2, -5, -2); // floor plane grid this.Grid = LineBuilder.GenerateGrid(); this.GridColor = Media.Colors.Black; this.GridTransform = new TranslateTransform3D(-5, -1, -5); // scene model3d var b1 = new MeshBuilder(); b1.AddSphere(new Vector3(0, 0, 0), 0.5); b1.AddBox(new Vector3(0, 0, 0), 1, 0.5, 2, BoxFaces.All); this.Model = b1.ToMeshGeometry3D(); // lines model3d var e1 = new LineBuilder(); e1.AddBox(new Vector3(0, 0, 0), 1, 0.5, 2); //this.Lines = e1.ToLineGeometry3D().ToUnshared(); this.Lines = e1.ToLineGeometry3D(true); this.Lines.Colors = new Color4Collection(); var linesCount = this.Lines.Indices.Count; var rnd = new Random(); while (linesCount-- > 0) { this.Lines.Colors.Add(rnd.NextColor()); } // lines params this.LineThickness = 2; this.LineSmoothness = 2.0; this.LinesEnabled = true; this.GridEnabled = true; // model trafos this.Model1Transform = new TranslateTransform3D(0, 0, 0); this.Model2Transform = new TranslateTransform3D(-2, 0, 0); this.Model3Transform = new TranslateTransform3D(+2, 0, 0); // model materials this.Material1 = PhongMaterials.PolishedGold; this.Material2 = PhongMaterials.Copper; this.Material3 = PhongMaterials.Glass; }
/// <summary> /// /// </summary> /// <param name="plane"></param> /// <param name="radius"></param> /// <param name="segments"></param> /// <returns></returns> public static LineGeometry3D GenerateCircle(Vector3 plane, float radius, int segments) { if (segments < 3) { throw new ArgumentNullException("too few segments, at least 3"); } var circle = new LineBuilder(); float sectionAngle = (float)(2.0 * Math.PI / segments); if (plane == Vector3.UnitX) { Point3D start = new Point3D(0.0f, 0.0f, radius); Point3D current = new Point3D(0.0f, 0.0f, radius); Point3D next = new Point3D(0.0f, 0.0f, 0.0f); for (int i = 1; i < segments; i++) { next.Z = radius * (float)Math.Cos(i * sectionAngle); next.Y = radius * (float)Math.Sin(i * sectionAngle); circle.AddLine(current, next); current = next; } circle.AddLine(current, start); } else if (plane == Vector3.UnitY) { Point3D start = new Point3D(radius, 0.0f, 0.0f); Point3D current = new Point3D(radius, 0.0f, 0.0f); Point3D next = new Point3D(0.0f, 0.0f, 0.0f); for (int i = 1; i < segments; i++) { next.X = radius * (float)Math.Cos(i * sectionAngle); next.Z = radius * (float)Math.Sin(i * sectionAngle); circle.AddLine(current, next); current = next; } circle.AddLine(current, start); } else { Point3D start = new Point3D(0.0f, radius, 0.0f); Point3D current = new Point3D(0.0f, radius, 0.0f); Point3D next = new Point3D(0.0f, 0.0f, 0.0f); for (int i = 1; i < segments; i++) { next.Y = radius * (float)Math.Cos(i * sectionAngle); next.X = radius * (float)Math.Sin(i * sectionAngle); circle.AddLine(current, next); current = next; } circle.AddLine(current, start); } return(circle.ToLineGeometry3D()); }
/// <summary> /// The on children changed. /// </summary> protected virtual void OnChildrenChanged() { this.translateXL.Length = 0.5; this.translateYL.Length = 0.5; this.translateZL.Length = 0.5; this.translateXR.Length = 0.5; this.translateYR.Length = 0.5; this.translateZR.Length = 0.5; this.Children.Clear(); if (this.CanTranslateX) { this.Children.Add(this.translateXL); this.Children.Add(this.translateXR); } if (this.CanTranslateY) { this.Children.Add(this.translateYL); this.Children.Add(this.translateYR); } if (this.CanTranslateZ) { this.Children.Add(this.translateZL); this.Children.Add(this.translateZR); } { var g = new LineBuilder(); g.AddLine(new Vector3(0, 0, 0), new Vector3(1, 0, 0)); g.AddLine(new Vector3(1, 0, 0), new Vector3(1, 1, 0)); g.AddLine(new Vector3(1, 1, 0), new Vector3(0, 1, 0)); g.AddLine(new Vector3(0, 1, 0), new Vector3(0, 0, 0)); this.selectionBounds = new LineGeometryModel3D() { Thickness = 3, Smoothness = 2, Color = Color.Red, IsThrowingShadow = false, Geometry = g.ToLineGeometry3D(), }; this.Children.Add(this.selectionBounds); } }
void IGeometrySink.Begin() { _BuiltLines.Clear(); _LineBuilder = new LineBuilder(); }
void IGeometrySink.Close() { if(_LineBuilder.Point1 == null) { throw new InvalidOperationException(); } _LineBuilder.Point2 = _FigureStart; FullLine newLine; newLine.Point1 = _LineBuilder.Point1.Value; newLine.Point2 = _LineBuilder.Point2.Value; _BuiltLines.Add(newLine); _LineBuilder = new LineBuilder(); }
public MainViewModel() { RenderTechniquesManager = new DefaultRenderTechniquesManager(); RenderTechnique = RenderTechniquesManager.RenderTechniques[DefaultRenderTechniqueNames.Blinn]; EffectsManager = new DefaultEffectsManager(RenderTechniquesManager); // titles this.Title = "Mouse Drag Demo"; this.SubTitle = "WPF & SharpDX"; // camera setup this.Camera = new PerspectiveCamera { Position = new Point3D(0, 0, 9), LookDirection = new Vector3D(-0, -0, -9), UpDirection = new Vector3D(0, 1, 0) }; // default render technique this.RenderTechnique = RenderTechniquesManager.RenderTechniques[DefaultRenderTechniqueNames.Blinn]; // setup lighting this.AmbientLightColor = new Color4(0.1f, 0.1f, 0.1f, 1.0f); this.DirectionalLightColor = Color.White; this.DirectionalLightDirection = new Vector3(-2, -5, -2); // floor plane grid this.Grid = LineBuilder.GenerateGrid(Vector3.UnitZ, -5, 5); this.GridColor = SharpDX.Color.Black; this.GridTransform = new Media3D.TranslateTransform3D(-0, -0, -0); // scene model3d var b1 = new MeshBuilder(); b1.AddSphere(new Vector3(0, 0, 0), 0.65); b1.AddBox(new Vector3(0, 0, 0), 1, 1, 1); var meshGeometry = b1.ToMeshGeometry3D(); meshGeometry.Colors = new Color4Collection(meshGeometry.TextureCoordinates.Select(x => x.ToColor4())); this.MeshGeometry = meshGeometry; this.Model1Instances = new List<Matrix>(); for (int i = 0; i < 5; i++) { this.Model1Instances.Add(Matrix.Translation(0, i, 0)); } // lines model3d var e1 = new LineBuilder(); e1.AddBox(new Vector3(0, 0, 0), 1, 0.5, 2); this.Lines = e1.ToLineGeometry3D(); // model trafos this.Model1Transform = new Media3D.TranslateTransform3D(0, 0, 0.0); this.Model2Transform = new Media3D.TranslateTransform3D(-2, 0, 0); this.Model3Transform = new Media3D.TranslateTransform3D(+2, 0, 0); // model materials this.RedMaterial = PhongMaterials.Red; this.GreenMaterial = PhongMaterials.Green; this.BlueMaterial = PhongMaterials.Blue; // --- this.Shape3DCollection = new ObservableCollection<Shape3D> { new Shape3D() { Geometry = this.MeshGeometry, Material = this.BlueMaterial, Transform = this.Model3Transform, Instances = new List<Matrix>{Matrix.Identity}, DragZ = false, }, new Shape3D() { Geometry = this.MeshGeometry, Material = this.RedMaterial, Transform = this.Model1Transform, Instances = new List<Matrix>{Matrix.Identity}, DragZ = true, }, }; this.Element3DCollection = new ObservableCollection<Element3D>() { new DraggableGeometryModel3D() { Geometry = this.MeshGeometry, Material = this.BlueMaterial, Transform = this.Model3Transform, }, new DraggableGeometryModel3D() { Geometry = this.MeshGeometry, Material = this.RedMaterial, Transform = this.Model1Transform, }, }; this.AddCmd = new RelayCommand((o) => AddShape()); this.DelCmd = new RelayCommand((o) => DelShape()); }
public void GetIntermediarySpacesForDistance2() { Assert.AreEqual(" ", LineBuilder.GetIntermediarySpacesForLine(2)); }
public MainViewModel() { // titles Title = "Simple Demo"; SubTitle = "WPF & SharpDX"; // camera setup Camera = new PerspectiveCamera { Position = new Point3D(3, 3, 5), LookDirection = new Vector3D(-3, -3, -5), UpDirection = new Vector3D(0, 1, 0), FarPlaneDistance = 5000000 }; // Create a custom render techniques manager that // only supports Phong and Blinn RenderTechniquesManager = new CustomRenderTechniquesManager(); RenderTechnique = RenderTechniquesManager.RenderTechniques["RenderCustom"]; EffectsManager = new CustomEffectsManager(RenderTechniquesManager); // setup lighting AmbientLightColor = new Color4(0.1f, 0.1f, 0.1f, 1.0f); DirectionalLightColor = Color.White; DirectionalLightDirection = new Vector3(-2, -5, -2); // floor plane grid Grid = LineBuilder.GenerateGrid(); GridColor = Color.Black; GridTransform = new Media3D.TranslateTransform3D(-5, -1, -5); // scene model3d var b1 = new MeshBuilder(); b1.AddSphere(new Vector3(0, 0, 0), 0.5); b1.AddBox(new Vector3(0, 0, 0), 1, 0.5, 2, BoxFaces.All); var meshGeometry = b1.ToMeshGeometry3D(); meshGeometry.Colors = new Color4Collection(meshGeometry.TextureCoordinates.Select(x => x.ToColor4())); Model = meshGeometry; // lines model3d var e1 = new LineBuilder(); e1.AddBox(new Vector3(0, 0, 0), 1, 0.5, 2); Lines = e1.ToLineGeometry3D(); // model transform Model1Transform = new Media3D.TranslateTransform3D(0, 0, 0); Model2Transform = new Media3D.TranslateTransform3D(-2, 0, 0); Model3Transform = new Media3D.TranslateTransform3D(+2, 0, 0); // model materials RedMaterial = PhongMaterials.Red; GreenMaterial = PhongMaterials.Green; BlueMaterial = PhongMaterials.Blue; Points = new PointGeometry3D(); var ptPos = new Vector3Collection(); var ptIdx = new IntCollection(); Text = new BillboardText3D(); for (int x = -5; x <= 5; x++) { for (int y = -5; y <= 5; y++) { ptIdx.Add(ptPos.Count); ptPos.Add(new Vector3(x, -1, y)); Text.TextInfo.Add(new TextInfo(string.Format("{0}:{1}", x, y), new Vector3(x, -1, y))); } } Points.Positions = ptPos; Points.Indices = ptIdx; }
public void GetIntermediarySpacesInvalid() { Assert.ThrowsException <ArgumentOutOfRangeException>(() => LineBuilder.GetIntermediarySpacesForLine(0)); }
private void InitializeScene() { camera = new PerspectiveCameraCore() { LookDirection = new Vector3(0, 0, 50), Position = new Vector3(0, 0, -50), FarPlaneDistance = 1000, NearPlaneDistance = 0.1f, FieldOfView = 45, UpDirection = new Vector3(0, 1, 0) }; viewport.CameraCore = camera; viewport.Items.Add(new DirectionalLightNode() { Direction = new Vector3(0, -1, 1), Color = Color.White }); viewport.Items.Add(new PointLightNode() { Position = new Vector3(0, 0, -20), Color = Color.Yellow, Range = 20, Attenuation = Vector3.One }); var builder = new MeshBuilder(true, true, true); builder.AddSphere(Vector3.Zero, 1, 12, 12); sphere = builder.ToMesh(); builder = new MeshBuilder(true, true, true); builder.AddBox(Vector3.Zero, 1, 1, 1); box = builder.ToMesh(); points = new PointGeometry3D() { Positions = sphere.Positions }; var lineBuilder = new LineBuilder(); lineBuilder.AddBox(Vector3.Zero, 2, 2, 2); lines = lineBuilder.ToLineGeometry3D(); groupSphere = new GroupNode(); groupBox = new GroupNode(); groupLines = new GroupNode(); groupPoints = new GroupNode(); InitializeMaterials(); materialList = materials.Values.ToArray(); var materialCount = materialList.Length; for (int i = 0; i < NumItems; ++i) { var transform = Matrix.Translation(new Vector3(rnd.NextFloat(-20, 20), rnd.NextFloat(-20, 20), rnd.NextFloat(-20, 20))); groupSphere.AddChildNode(new MeshNode() { Geometry = sphere, Material = materialList[i % materialCount], ModelMatrix = transform, CullMode = SharpDX.Direct3D11.CullMode.Back }); } for (int i = 0; i < NumItems; ++i) { var transform = Matrix.Translation(new Vector3(rnd.NextFloat(-50, 50), rnd.NextFloat(-50, 50), rnd.NextFloat(-50, 50))); groupBox.AddChildNode(new MeshNode() { Geometry = box, Material = materialList[i % materialCount], ModelMatrix = transform, CullMode = SharpDX.Direct3D11.CullMode.Back }); } //for(int i=0; i< NumItems; ++i) //{ // var transform = Matrix.Translation(new Vector3(rnd.NextFloat(-50, 50), rnd.NextFloat(-50, 50), rnd.NextFloat(-50, 50))); // groupPoints.AddChildNode(new PointNode() { Geometry = points, ModelMatrix = transform, Material = new PointMaterialCore() { PointColor = Color.Red } }); //} //for (int i = 0; i < NumItems; ++i) //{ // var transform = Matrix.Translation(new Vector3(rnd.NextFloat(-50, 50), rnd.NextFloat(-50, 50), rnd.NextFloat(-50, 50))); // groupLines.AddChildNode(new LineNode() { Geometry = lines, ModelMatrix = transform, Material = new LineMaterialCore() { LineColor = Color.LightBlue } }); //} viewport.Items.Add(groupSphere); groupSphere.AddChildNode(groupBox); groupSphere.AddChildNode(groupPoints); groupSphere.AddChildNode(groupLines); var viewbox = new ViewBoxNode(); viewport.Items.Add(viewbox); var imGui = new ImGuiNode(); viewport.Items.Add(imGui); imGui.UpdatingImGuiUI += ImGui_UpdatingImGuiUI; io.KeyMap[GuiKey.Tab] = (int)Keys.Tab; io.KeyMap[GuiKey.LeftArrow] = (int)Keys.Left; io.KeyMap[GuiKey.RightArrow] = (int)Keys.Right; io.KeyMap[GuiKey.UpArrow] = (int)Keys.Up; io.KeyMap[GuiKey.DownArrow] = (int)Keys.Down; io.KeyMap[GuiKey.PageUp] = (int)Keys.PageUp; io.KeyMap[GuiKey.PageDown] = (int)Keys.PageDown; io.KeyMap[GuiKey.Home] = (int)Keys.Home; io.KeyMap[GuiKey.End] = (int)Keys.End; io.KeyMap[GuiKey.Delete] = (int)Keys.Delete; io.KeyMap[GuiKey.Backspace] = (int)Keys.Back; io.KeyMap[GuiKey.Enter] = (int)Keys.Enter; io.KeyMap[GuiKey.Escape] = (int)Keys.Escape; }
public void ParseAndGenerateExpressionTest6() { int inputLength = 12; var input = new string('\0', inputLength); var builder = new LineBuilder(input, null); string regexPattern = ".*"; var parser = new RegexParser(); RegularExpression regex = parser.Parse(regexPattern); var line = builder.GetLines(regex).First(); }
public MainViewModel() { // titles Title = "Simple Demo"; SubTitle = "WPF & SharpDX"; // camera setup Camera = new PerspectiveCamera { Position = new Point3D(3, 3, 5), LookDirection = new Vector3D(-3, -3, -5), UpDirection = new Vector3D(0, 1, 0), FarPlaneDistance = 5000000 }; // default render technique RenderTechniquesManager = new DefaultRenderTechniquesManager(); RenderTechnique = RenderTechniquesManager.RenderTechniques[DefaultRenderTechniqueNames.Blinn]; EffectsManager = new DefaultEffectsManager(RenderTechniquesManager); // setup lighting AmbientLightColor = new Color4(0.1f, 0.1f, 0.1f, 1.0f); DirectionalLightColor = Color.White; DirectionalLightDirection = new Vector3(-2, -5, -2); // floor plane grid Grid = LineBuilder.GenerateGrid(); GridColor = SharpDX.Color.Black; GridTransform = new Media3D.TranslateTransform3D(-5, -1, -5); // scene model3d var b1 = new MeshBuilder(); b1.AddSphere(new Vector3(0, 0, 0), 0.5); b1.AddBox(new Vector3(0, 0, 0), 1, 0.5, 2, BoxFaces.All); var meshGeometry = b1.ToMeshGeometry3D(); meshGeometry.Colors = new Color4Collection(meshGeometry.TextureCoordinates.Select(x => x.ToColor4())); Model = meshGeometry; // lines model3d var e1 = new LineBuilder(); e1.AddBox(new Vector3(0, 0, 0), 1, 0.5, 2); Lines = e1.ToLineGeometry3D(); // model trafos Model1Transform = new Media3D.TranslateTransform3D(0, 0, 0); Model2Transform = new Media3D.TranslateTransform3D(-2, 0, 0); Model3Transform = new Media3D.TranslateTransform3D(+2, 0, 0); // model materials RedMaterial = PhongMaterials.Red; GreenMaterial = PhongMaterials.Green; BlueMaterial = PhongMaterials.Blue; //var diffColor = this.RedMaterial.DiffuseColor; //diffColor.Alpha = 0.5f; //this.RedMaterial.DiffuseColor = diffColor; Points = new PointGeometry3D(); var ptPos = new Vector3Collection(); var ptIdx = new IntCollection(); for (int x = 0; x < 10; x++) { for (int y = 0; y < 10; y++) { for (int z = 0; z < 10; z++) { ptIdx.Add(ptPos.Count); ptPos.Add(new Vector3(x, y, z)); } } } Points.Positions = ptPos; Points.Indices = ptIdx; Text = new BillboardText3D(); for (var i = 0; i < 50; i++) { for (var j = 0; j < 50; j++) { Text.TextInfo.Add(new TextInfo("Hello World", new Vector3(i, j, 0))); } } Billboard1Model = new BillboardSingleText3D() { TextInfo = new TextInfo("Model 1", new Vector3(0, 1, 0)), FontColor = Color.Blue, FontSize = 12, BackgroundColor = Color.Plum, FontStyle = System.Windows.FontStyles.Italic, Padding = new System.Windows.Thickness(2) }; var background = Color.Blue; background.A = (byte)120; Billboard2Model = new BillboardSingleText3D() { TextInfo = new TextInfo("Model 1", new Vector3(2, 1, 0)), FontSize = 12, FontColor = Color.Green, BackgroundColor = background, FontWeight = System.Windows.FontWeights.Bold, Padding = new System.Windows.Thickness(2) }; background = Color.Purple; background.A = (byte)50; Billboard3Model = new BillboardSingleText3D(2, 0.8f) { TextInfo = new TextInfo("Model 1", new Vector3(-2, 1, 0)), FontSize = 12, FontColor = Color.Red, BackgroundColor = background, FontFamily = new System.Windows.Media.FontFamily("Times New Roman"), FontStyle = System.Windows.FontStyles.Italic, Padding = new System.Windows.Thickness(2) }; //BillboardImageModel = new BillboardSingleImage3D(CreateBitmapSample()) { MaskColor = Color.Black }; BillboardImageModel = new BillboardSingleImage3D(CreatePNGSample(), 1, 1); BillboardImageModel.Center = new Vector3(2, 2, 0); }
public MainPageViewModel() { EffectsManager = new DefaultEffectsManager(new Logger()); Camera = new PerspectiveCamera() { Position = new Vector3(0, 0, -15), LookDirection = new Vector3(0, 0, 15), UpDirection = new Vector3(0, 1, 0) }; var builder = new MeshBuilder(true, true, true); builder.AddBox(new SharpDX.Vector3(0, 0, 0), 2, 2, 2); builder.AddSphere(new Vector3(0, 2, 0), 1.5); Geometry = builder.ToMesh(); Material = new PhongMaterial() { AmbientColor = Color.Gray, DiffuseColor = new Color4(0.75f, 0.75f, 0.75f, 1.0f), SpecularColor = Color.White, SpecularShininess = 100f, }; Material.DiffuseMap = LoadTexture("TextureCheckerboard2.jpg"); Material.NormalMap = LoadTexture("TextureCheckerboard2_dot3.jpg"); var lineBuilder = new LineBuilder(); lineBuilder.AddLine(Vector3.Zero, new Vector3(5, 0, 0)); lineBuilder.AddLine(Vector3.Zero, new Vector3(0, 5, 0)); lineBuilder.AddLine(Vector3.Zero, new Vector3(0, 0, 5)); LineGeometry = lineBuilder.ToLineGeometry3D(); LineGeometry.Colors = new HelixToolkit.UWP.Core.Color4Collection() { Color.Red, Color.Red, Color.Green, Color.Green, Color.Blue, Color.Blue }; builder = new MeshBuilder(); builder.AddSphere(new Vector3(), 3); var mesh = builder.ToMesh(); PointGeometry = new PointGeometry3D() { Positions = mesh.Positions }; AxisLabelGeometry = new BillboardText3D(); AxisLabelGeometry.TextInfo.Add(new TextInfo("X", new Vector3(5.5f, 0, 0)) { Foreground = Color.Red }); AxisLabelGeometry.TextInfo.Add(new TextInfo("Y", new Vector3(0, 5.5f, 0)) { Foreground = Color.Green }); AxisLabelGeometry.TextInfo.Add(new TextInfo("Z", new Vector3(0, 0, 5.5f)) { Foreground = Color.Blue }); builder = new MeshBuilder(); builder.AddBox(new Vector3(0, -6, 0), 30, 0.5, 30); FloorModel = builder.ToMesh(); FloorMaterial = PhongMaterials.LightGray; timer = new DispatcherTimer(); timer.Tick += Timer_Tick; timer.Interval = new TimeSpan(0, 0, 0, 0, 16); timer.Start(); }
void IGeometrySink.LineTo(Point endPoint) { if(_LineBuilder.Point1 == null) { _LineBuilder.Point1 = endPoint; } else if(_LineBuilder.Point2 == null) { _LineBuilder.Point2 = endPoint; FullLine newLine; newLine.Point1 = _LineBuilder.Point1.Value; newLine.Point2 = _LineBuilder.Point2.Value; _BuiltLines.Add(newLine); _LineBuilder = new LineBuilder(); } }
// alternative way, 3.36 times faster, but wrong PointHit protected bool HitTest2D(IRenderMatrices context, Ray rayWS, ref List <HitTestResult> hits) { LineGeometry3D lineGeometry3D; if (this.Visibility == Visibility.Collapsed || this.IsHitTestVisible == false || context == null || (lineGeometry3D = this.Geometry as LineGeometry3D) == null) { return(false); } // revert unprojection; probably better: overloaded HitTest() for LineGeometryModel3D? var svpm = context.ScreenViewProjectionMatrix; var smvpm = this.modelMatrix * svpm; var clickPoint4 = new Vector4(rayWS.Position + rayWS.Direction, 1); Vector4.Transform(ref clickPoint4, ref svpm, out clickPoint4); var clickPoint = clickPoint4.ToVector3(); var result = new HitTestResult { IsValid = false, Distance = double.MaxValue }; var maxDist = this.HitTestThickness; var lastDist = double.MaxValue; var index = 0; foreach (var line in lineGeometry3D.Lines) { var p0 = Vector3.TransformCoordinate(line.P0, smvpm); var p1 = Vector3.TransformCoordinate(line.P1, smvpm); Vector3 hitPoint; float t; var dist = LineBuilder.GetPointToLineDistance2D(ref clickPoint, ref p0, ref p1, out hitPoint, out t); if (dist < lastDist && dist <= maxDist) { lastDist = dist; Vector4 res; var lp0 = line.P0; Vector3.Transform(ref lp0, ref this.modelMatrix, out res); lp0 = res.ToVector3(); var lp1 = line.P1; Vector3.Transform(ref lp1, ref this.modelMatrix, out res); lp1 = res.ToVector3(); var lv = lp1 - lp0; var hitPointWS = lp0 + lv * t; // wrong, because t refers to screen space result.Distance = (rayWS.Position - hitPointWS).Length(); result.PointHit = hitPointWS.ToPoint3D(); result.ModelHit = this; result.IsValid = true; result.Tag = index; // ToDo: LineHitTag with additional info } index++; } if (result.IsValid) { hits.Add(result); } return(result.IsValid); }
/// <summary> /// Runs a process (executed via shell) with the given arguments and waits for it to finish. /// </summary> /// <param name="ExePath">Path to exe or command to run</param> /// <param name="WorkingDirectory">Directory to execute command within.</param> /// <param name="Arguments">Arguments to pass to command.</param> /// <returns>Exit code returned by the process. If process fails to start -1 is returned.</returns> public static int RunAndWait(string ExePath, string WorkingDirectory, string Arguments, ScriptBuildOutputCallbackDelegate OutputCallback = null) { Logger.Log(LogLevel.Info, LogCategory.Script, "Running (and waiting for result) '{0}' in '{1}' with arguments '{2}'.", ExePath, WorkingDirectory, Arguments); try { ProcessStartInfo StartInfo = new ProcessStartInfo(); StartInfo.FileName = ExePath; StartInfo.WorkingDirectory = WorkingDirectory; StartInfo.Arguments = Arguments; StartInfo.RedirectStandardOutput = true; StartInfo.RedirectStandardError = true; StartInfo.UseShellExecute = false; StartInfo.CreateNoWindow = true; Process process = Process.Start(StartInfo); ChildProcessTracker.AddProcess(process); /*process.OutputDataReceived += delegate (object sender, DataReceivedEventArgs e) * { * OutputLineBuilder.Add(e.Data); * while (true) * { * string Line = OutputLineBuilder.Read(); * if (Line == null) * { * break; * } * Logger.Log(LogLevel.Info, LogCategory.Main, "{0}", Line); * } * * OutputCallback?.Invoke(e.Data); * }; * process.ErrorDataReceived += delegate (object sender, DataReceivedEventArgs e) * { * while (true) * { * string Line = ErrorLineBuilder.Read(); * if (Line == null) * { * break; * } * Logger.Log(LogLevel.Info, LogCategory.Main, "{0}", Line); * } * * OutputCallback?.Invoke(e.Data); * }; * * //process.BeginErrorReadLine(); * //process.BeginOutputReadLine(); */ Func <StreamReader, ConcurrentQueue <string>, bool> QueueBuilder = (StreamReader Reader, ConcurrentQueue <string> Queue) => { int Char = Reader.Read(); if (Char < 0) { return(true); } string Value = new string((char)Char, 1); Queue.Enqueue(Value); return(false); }; Func <ConcurrentQueue <string>, LineBuilder, bool> Parser = (ConcurrentQueue <string> Queue, LineBuilder Builder) => { while (Queue.Count > 0) { string Value = ""; if (Queue.TryDequeue(out Value)) { Builder.Add(Value); while (true) { string Line = Builder.Read(); if (Line == null) { break; } Logger.Log(LogLevel.Info, LogCategory.Main, "{0}", Line); } OutputCallback?.Invoke(Value); } } return(true); }; Func <LineBuilder, bool> DrainBuilder = (LineBuilder Builder) => { Builder.End(); while (true) { string Line = Builder.Read(); if (Line == null) { break; } Logger.Log(LogLevel.Info, LogCategory.Main, "{0}", Line); } return(true); }; LineBuilder OutputLineBuilder = new LineBuilder(); LineBuilder ErrorLineBuilder = new LineBuilder(); // This is retarded, the blocking api for all of this in C# is s***e. ConcurrentQueue <string> OutputData = new ConcurrentQueue <string>(); ConcurrentQueue <string> ErrorData = new ConcurrentQueue <string>(); Task OutputTask = Task.Run(() => { while (!QueueBuilder(process.StandardOutput, OutputData)) { ; } }); Task ErrorTask = Task.Run(() => { while (!QueueBuilder(process.StandardError, ErrorData)) { ; } }); // Wait for process to exit. while (!OutputTask.IsCompleted || !ErrorTask.IsCompleted || OutputData.Count > 0 || ErrorData.Count > 0) { Parser(OutputData, OutputLineBuilder); Parser(ErrorData, ErrorLineBuilder); Thread.Sleep(1); } process.WaitForExit(); // Drain any output. DrainBuilder(OutputLineBuilder); DrainBuilder(ErrorLineBuilder); Logger.Log(LogLevel.Info, LogCategory.Script, "Finished running with exit code {0}.", process.ExitCode); return(process.ExitCode); } catch (Exception Ex) { Logger.Log(LogLevel.Error, LogCategory.Script, "Failed to run program with error: {0}", Ex.Message.ToString()); return(-1); } }
private void Grbl_IsReset(object sender, EventArgs e) { localprocessed = new LineBuilder(); Processed = null; }
//public Camera Camera2 { private set; get; } public MainViewModel() { EffectsManager = new DefaultEffectsManager(); Title = "Shadow Map Demo"; SubTitle = "WPF & SharpDX"; // setup lighting this.AmbientLightColor = new Color4(0.1f, 0.1f, 0.1f, 1.0f); this.DirectionalLightColor = Media.Colors.White; //this.DirectionalLightDirection = new Vector3(-1, -1, -1); // this.LightDirectionTransform = CreateAnimatedTransform(-DirectionalLightDirection.ToVector3D(), new Vector3D(0, 1, -1), 24); this.ShadowMapResolution = new Size(2048, 2048); // camera setup this.Camera = new PerspectiveCamera { Position = new Point3D(0, 1, 1), LookDirection = new Vector3D(0, -1, -1), UpDirection = new Vector3D(0, 1, 0) }; Camera1 = new PerspectiveCamera { Position = new Point3D(0, 5, 0), LookDirection = new Vector3D(0, -1, 0), UpDirection = new Vector3D(1, 0, 0), FarPlaneDistance = 5000, NearPlaneDistance = 1, FieldOfView = 45 }; // scene model3d var b1 = new MeshBuilder(); b1.AddSphere(new Vector3(0, 0, 0), 0.5); b1.AddBox(new Vector3(0, 0, 0), 1, 0.25, 2, BoxFaces.All); Model = b1.ToMeshGeometry3D(); Instances = new[] { Matrix.Translation(0, 0, -1.5f), Matrix.Translation(0, 0, 1.5f) }; var b2 = new MeshBuilder(); b2.AddBox(new Vector3(0, 0, 0), 10, 0, 10, BoxFaces.PositiveY); Plane = b2.ToMeshGeometry3D(); PlaneTransform = new Media3D.TranslateTransform3D(-0, -2, -0); GrayMaterial = PhongMaterials.Indigo; // lines model3d Lines = LineBuilder.GenerateBoundingBox(Model); //this.PropertyChanged += MainViewModel_PropertyChanged; // model trafos Model1Transform = new Media3D.TranslateTransform3D(0, 0, 0); Model2Transform = new Media3D.TranslateTransform3D(-2, 0, 0); Model3Transform = new Media3D.TranslateTransform3D(+2, 0, 0); // model materials RedMaterial = PhongMaterials.Glass; GreenMaterial = PhongMaterials.Green; BlueMaterial = PhongMaterials.Blue; GrayMaterial.RenderShadowMap = RedMaterial.RenderShadowMap = GreenMaterial.RenderShadowMap = BlueMaterial.RenderShadowMap = true; //var b3 = new MeshBuilder(); //b3.AddBox(new Vector3(), 0.3f, 0.3f, 0.3f, BoxFaces.All); //b3.AddCone(new Vector3(0, 0.3f, 0), new Vector3(0, 0f, 0), 0.2f, true, 24); //LightCameraModel = b3.ToMesh(); //LightCameraTransform.Children.Add(new Media3D.RotateTransform3D(new Media3D.AxisAngleRotation3D(new Vector3D(1, 0, 0), -135))); //LightCameraTransform.Children.Add(new Media3D.TranslateTransform3D(0, 3, 3)); //UpdateCamera(); }
/// <summary> /// Writes the entry. /// </summary> /// <typeparam name="TEntity">The type of the t entity.</typeparam> /// <param name="writer">The writer.</param> /// <param name="lineNumber">The line number.</param> /// <param name="entity">The entity.</param> protected virtual void WriteEntry <TEntity>(TextWriter writer, int lineNumber, TEntity entity) { LineBuilder.BuildLine(entity, writer); writer.WriteLine(); }
public Line(string thisName, SubGeographicalRegion thisArea, string sourceBus, float baseKV) : base(thisName, thisArea) { this.lineBuilder = new LineBuilder(this); VoltageLevels = new List<TopologicalNode.VoltageLevel>(); lineBuilder.BuildModel(); type = "Line"; bus1 = sourceBus; Area = thisArea; BaseKV = baseKV; }
public MainViewModel() { EffectsManager = new DefaultEffectsManager(); // camera setup Camera = new PerspectiveCamera { Position = new Point3D(0, -2000, 400), LookDirection = new Vector3D(0, 2000, 0), UpDirection = UpDirection, FarPlaneDistance = 5000000, }; // setup lighting //SkyboxTexture = LoadFileToMemory("Cubemap_Grandcanyon.dds"); LightDirection = new Vector3D(0, -0.5, -1); LightDirection.Normalize(); SetHeadLight(); AmbientLightColor = Colors.White * 1000; DirectionalLightColor = Color.FromScRgb(1, 10, 10, 10); BackgroundColor = Color.FromRgb(40, 40, 40); // model transform ModelTransform = Transform3D.Identity; //var r = new System.Windows.Media.Media3D.AxisAngleRotation3D(new Vector3D(0, 0, 1), 90); //EnvironmentTransform = new System.Windows.Media.Media3D.RotateTransform3D(r); // model materials var material = new PBRMaterial(); material.AlbedoColor = new Color4(0.8f, 0.4f, 0.05f, 1f); material.MetallicFactor = 0.2; material.ReflectanceFactor = 0.8; material.RenderEnvironmentMap = false; material.AmbientOcclusionFactor = 1; // floor plane grid Grid = LineBuilder.GenerateGrid(new Vector3(0, 0, 1), -10, 10, -10, 10); GridColor = Color.FromRgb(100, 100, 100); GridTransform = new System.Windows.Media.Media3D.ScaleTransform3D(100, 100, 100); // commands UpZCommand = new RelayCommand(_ => { Log = "test switch"; }); // robot program var test = new TestProgram(); Program = test.Program; Log = Program.Errors.Count == 0 ? Program.RobotSystem.Name : string.Join(" ", Program.Errors); // make robot var cell = Program.RobotSystem as Robots.RobotCell; var group = cell.MechanicalGroups.First(); var meshes = group.Joints.Select(j => j.Mesh).Prepend(group.Robot.BaseMesh); _origins = group.Joints.Select(j => j.Plane).Prepend(group.Robot.BasePlane).ToArray(); foreach (var joint in meshes) { var model = new MeshGeometryModel3D(); model.Geometry = joint.ToWPF(); model.Material = material; model.Transform = Transform3D.Identity; model.IsThrowingShadow = true; RobotModels.Add(model); } // timer _timer = new Timer(Tick, null, Timeout.Infinite, 0); }
public static ParsedCode Parse(string code, Dictionary <string, object> variables = null, InterpreterOptions opts = null) { code = code.Replace("\r", ""); //todo this might cause throws in osx. StringSpan output_sb; var output = new LineBuilder(output_sb = StringSpan.Create(code)); variables = variables ?? new Dictionary <string, object>(); opts = opts ?? new InterpreterOptions(); // Define the context of our expression var ew = new ExpressionWalker(ExpressionLexer.Tokenize(code).Where(t => t.Token != ExpressionToken.UnixNewLine).ToList()); //if no tokens detected if (ew.Count == 0) { return(new ParsedCode() { OriginalCode = code, Output = output, Variables = variables, Options = opts, ParseActions = new OList <ParserAction>(0) }); } var parserTokens = new OList <ParserAction>(); do { var current = ew.Current; switch (ew.Current.Token) { case ExpressionToken.Mod: { //copypastes.Add(sb.Substring(from, ew.Current.Match.Index + ew.Current.Match.Length - 1)); current = ew.NextToken(); if (current == null) { break; } switch (current.Token) { case ExpressionToken.Template: { //this is import %import namespace.type as aliasnmae var template = TemplateExpression.Parse(ew); parserTokens += new ParserAction(ParserToken.Template, output.MarkDeleteLinesRelated(template.Matches()), template); break; } case ExpressionToken.Import: { //this is import %import namespace.type as aliasnmae var import = ImportExpression.Parse(ew); parserTokens += new ParserAction(ParserToken.Import, output.MarkDeleteLinesRelated(import.Matches()), import); break; } case ExpressionToken.Literal: { //this is variable declaration %varname = expr var peak = ew.PeakNext.Token; if (peak == ExpressionToken.Equal) { var expr = VariableDeclarationExpression.Parse(ew); parserTokens += new ParserAction(ParserToken.Declaration, output.MarkDeleteLinesRelated(expr.Matches()), expr); } else { break; } break; } case ExpressionToken.LeftParen: { //it is an expression block %(expr) ew.NextOrThrow(); var expr = Expression.ParseExpression(ew); parserTokens += new ParserAction(ParserToken.Expression, output.MarkDeleteLinesRelated(expr.Matches()), expr); ew.IsCurrentOrThrow(ExpressionToken.RightParen); ew.Next(); break; } case ExpressionToken.Foreach: { parserTokens += ForeachExpression.Parse(ew, code, output); break; } case ExpressionToken.CommentRow: //skip untill we hit newline ew.SkipForwardWhile(t => t.Token != ExpressionToken.NewLine); //todo test break; default: { var precentageLine = output.GetLineAt(ew.PeakBack.Match.Index); if (precentageLine.CleanContent() != "%") { throw new UnexpectedTokenException(current.Token, $"The given token was not expected at line {precentageLine.LineNumber}, offset: {current.Match.Index - precentageLine.StartIndex}"); } break; } } break; } default: break; } } while (ew.Next()); return(new ParsedCode() { OriginalCode = code, Output = output, Variables = variables, ETokens = (List <TokenMatch>)ew.Walking, ParseActions = parserTokens, Options = opts }); }
public void Export(ScriptBook book, string filePath) { using (var writer = new HtmlTextWriter(new StreamWriter(File.Create(filePath)))) { writer.RenderBeginTag(HtmlTextWriterTag.Style); var cssLines = File.ReadAllLines( Path.Combine( Path.GetDirectoryName( System.Reflection.Assembly.GetEntryAssembly().Location ), "style.css" ) ); writer.WriteLine(); foreach (var cssLine in cssLines) { writer.WriteLine(cssLine); } writer.RenderEndTag(); writer.WriteLine(); writer.RenderBeginTag(HtmlTextWriterTag.H1); writer.Write(book.Title); writer.RenderEndTag(); writer.WriteLine(); writer.AddAttribute(HtmlTextWriterAttribute.Class, "story-area"); writer.RenderBeginTag(HtmlTextWriterTag.Div); foreach (var chapter in book) { writer.RenderBeginTag(HtmlTextWriterTag.H3); writer.Write(chapter.Key.MainTitle); writer.RenderEndTag(); writer.WriteLine(); writer.RenderBeginTag(HtmlTextWriterTag.H2); writer.Write(chapter.Key.SubTitle); writer.RenderEndTag(); writer.WriteLine(); foreach (var section in chapter.Value) { writer.AddAttribute(HtmlTextWriterAttribute.Class, "story-section"); writer.RenderBeginTag(HtmlTextWriterTag.Div); foreach (var paragraph in section) { writer.AddAttribute(HtmlTextWriterAttribute.Class, "story-paragraph"); writer.RenderBeginTag(HtmlTextWriterTag.Div); var lineBuilder = new LineBuilder(); foreach (var line in paragraph) { lineBuilder.Append(line); //lineBuilder = concat(lineBuilder, line); } writer.Write(lineBuilder.ToString()); writer.RenderEndTag(); writer.WriteLine(); } writer.RenderEndTag(); writer.WriteLine(); writer.AddAttribute(HtmlTextWriterAttribute.Class, "story-separator"); writer.RenderBeginTag(HtmlTextWriterTag.Div); writer.Write("☆☆☆☆☆"); writer.RenderEndTag(); writer.AddAttribute(HtmlTextWriterAttribute.Class, "story-pagebreak"); writer.RenderBeginTag(HtmlTextWriterTag.Div); writer.RenderEndTag(); } } } }
public virtual bool HitTest(RenderContext context, Matrix modelMatrix, ref Ray rayWS, ref List <HitTestResult> hits, object originalSource, float hitTestThickness) { if (Positions == null || Positions.Count == 0 || Indices == null || Indices.Count == 0) { return(false); } if (Octree != null) { return(Octree.HitTest(context, originalSource, modelMatrix, rayWS, ref hits, hitTestThickness)); } else { var result = new LineHitTestResult { IsValid = false, Distance = double.MaxValue }; var lastDist = double.MaxValue; var lineIndex = 0; foreach (var line in Lines) { var t0 = Vector3.TransformCoordinate(line.P0, modelMatrix); var t1 = Vector3.TransformCoordinate(line.P1, modelMatrix); Vector3 sp, tp; float sc, tc; var rayToLineDistance = LineBuilder.GetRayToLineDistance(rayWS, t0, t1, out sp, out tp, out sc, out tc); var svpm = context.ScreenViewProjectionMatrix; Vector4 sp4; Vector4 tp4; Vector3.Transform(ref sp, ref svpm, out sp4); Vector3.Transform(ref tp, ref svpm, out tp4); var sp3 = sp4.ToVector3(); var tp3 = tp4.ToVector3(); var tv2 = new Vector2(tp3.X - sp3.X, tp3.Y - sp3.Y); var dist = tv2.Length(); if (dist < lastDist && dist <= hitTestThickness) { lastDist = dist; result.PointHit = sp; result.NormalAtHit = sp - tp; // not normalized to get length result.Distance = (rayWS.Position - sp).Length(); result.RayToLineDistance = rayToLineDistance; result.ModelHit = originalSource; result.IsValid = true; result.Tag = lineIndex; // For compatibility result.LineIndex = lineIndex; result.TriangleIndices = null; // Since triangles are shader-generated result.RayHitPointScalar = sc; result.LineHitPointScalar = tc; } lineIndex++; } if (result.IsValid) { hits.Add(result); } return(result.IsValid); } }
public MainViewModel() { EffectsManager = new DefaultEffectsManager(); // titles this.Title = "Mouse Drag Demo"; this.SubTitle = "WPF & SharpDX"; // camera setup this.Camera = new PerspectiveCamera { Position = new Point3D(0, 0, 9), LookDirection = new Vector3D(-0, -0, -9), UpDirection = new Vector3D(0, 1, 0) }; // setup lighting this.AmbientLightColor = Colors.DimGray; this.DirectionalLightColor = Colors.White; this.DirectionalLightDirection = new Vector3D(-2, -5, -2); // floor plane grid this.Grid = LineBuilder.GenerateGrid(Vector3.UnitZ, -5, 5); this.GridColor = Colors.Black; this.GridTransform = new Media3D.TranslateTransform3D(-0, -0, -0); // scene model3d var b1 = new MeshBuilder(); b1.AddSphere(new Vector3(0, 0, 0), 0.65); b1.AddBox(new Vector3(0, 0, 0), 1, 1, 1); var meshGeometry = b1.ToMeshGeometry3D(); meshGeometry.Colors = new Color4Collection(meshGeometry.TextureCoordinates.Select(x => x.ToColor4())); this.MeshGeometry = meshGeometry; this.Model1Instances = new List <Matrix>(); for (int i = 0; i < 5; i++) { this.Model1Instances.Add(Matrix.Translation(0, i, 0)); } // lines model3d var e1 = new LineBuilder(); e1.AddBox(new Vector3(0, 0, 0), 1, 0.5, 2); this.Lines = e1.ToLineGeometry3D(); // model trafos this.Model1Transform = new Media3D.TranslateTransform3D(0, 0, 0.0); this.Model2Transform = new Media3D.TranslateTransform3D(-2, 0, 0); this.Model3Transform = new Media3D.TranslateTransform3D(+2, 0, 0); // model materials this.RedMaterial = PhongMaterials.Red; this.GreenMaterial = PhongMaterials.Green; this.BlueMaterial = PhongMaterials.Blue; // --- this.Shape3DCollection = new ObservableCollection <Shape3D> { new Shape3D() { Geometry = this.MeshGeometry, Material = this.BlueMaterial, Transform = this.Model3Transform, Instances = new List <Matrix> { Matrix.Identity }, DragZ = false, }, new Shape3D() { Geometry = this.MeshGeometry, Material = this.RedMaterial, Transform = this.Model1Transform, Instances = new List <Matrix> { Matrix.Identity }, DragZ = true, }, }; this.Element3DCollection = new ObservableCollection <Element3D>() { new DraggableGeometryModel3D() { Geometry = this.MeshGeometry, Material = this.BlueMaterial, Transform = this.Model3Transform, }, new DraggableGeometryModel3D() { Geometry = this.MeshGeometry, Material = this.RedMaterial, Transform = this.Model1Transform, }, }; this.AddCmd = new RelayCommand((o) => AddShape()); this.DelCmd = new RelayCommand((o) => DelShape()); }
private void InitializeScene() { camera = new PerspectiveCameraCore() { LookDirection = new Vector3(0, 0, 50), Position = new Vector3(0, 0, -50), FarPlaneDistance = 1000, NearPlaneDistance = 0.1f, FieldOfView = 45, UpDirection = new Vector3(0, 1, 0) }; viewport.CameraCore = camera; viewport.Items.Add(new DirectionalLightNode() { Direction = new Vector3(0, -1, 1), Color = Color.White }); viewport.Items.Add(new PointLightNode() { Position = new Vector3(0, 0, -20), Color = Color.Yellow, Range = 20, Attenuation = Vector3.One }); var builder = new MeshBuilder(true, true, true); builder.AddSphere(Vector3.Zero, 1, 12, 12); sphere = builder.ToMesh(); builder = new MeshBuilder(true, true, true); builder.AddBox(Vector3.Zero, 1, 1, 1); box = builder.ToMesh(); points = new PointGeometry3D() { Positions = sphere.Positions }; var lineBuilder = new LineBuilder(); lineBuilder.AddBox(Vector3.Zero, 2, 2, 2); lines = lineBuilder.ToLineGeometry3D(); groupSphere = new GroupNode(); groupBox = new GroupNode(); groupLines = new GroupNode(); groupPoints = new GroupNode(); InitializeMaterials(); materialList = materials.Values.ToArray(); var materialCount = materialList.Length; for (int i = 0; i < NumItems; ++i) { var transform = Matrix.Translation(new Vector3(rnd.NextFloat(-20, 20), rnd.NextFloat(-20, 20), rnd.NextFloat(-20, 20))); groupSphere.AddChildNode(new MeshNode() { Geometry = sphere, Material = materialList[i % materialCount], ModelMatrix = transform, CullMode = SharpDX.Direct3D11.CullMode.Back }); } for (int i = 0; i < NumItems; ++i) { var transform = Matrix.Translation(new Vector3(rnd.NextFloat(-50, 50), rnd.NextFloat(-50, 50), rnd.NextFloat(-50, 50))); groupBox.AddChildNode(new MeshNode() { Geometry = box, Material = materialList[i % materialCount], ModelMatrix = transform, CullMode = SharpDX.Direct3D11.CullMode.Back }); } for (int i = 0; i < NumItems; ++i) { var transform = Matrix.Translation(new Vector3(rnd.NextFloat(-50, 50), rnd.NextFloat(-50, 50), rnd.NextFloat(-50, 50))); groupPoints.AddChildNode(new PointNode() { Geometry = points, ModelMatrix = transform, Color = Color.Red, Size = new Size2F(0.5f, 0.5f) }); } for (int i = 0; i < NumItems; ++i) { var transform = Matrix.Translation(new Vector3(rnd.NextFloat(-50, 50), rnd.NextFloat(-50, 50), rnd.NextFloat(-50, 50))); groupLines.AddChildNode(new LineNode() { Geometry = lines, ModelMatrix = transform, Color = Color.LightBlue, Thickness = 0.5f }); } viewport.Items.Add(groupSphere); groupSphere.AddChildNode(groupBox); groupSphere.AddChildNode(groupPoints); groupSphere.AddChildNode(groupLines); var viewbox = new ViewBoxNode(); viewport.Items.Add(viewbox); }
public MainViewModel() { EffectsManager = new DefaultEffectsManager(); // titles Title = "Simple Demo"; SubTitle = "WPF & SharpDX"; // camera setup Camera = new PerspectiveCamera { Position = new Point3D(3, 3, 5), LookDirection = new Vector3D(-3, -3, -5), UpDirection = new Vector3D(0, 1, 0), FarPlaneDistance = 5000000 }; // setup lighting AmbientLightColor = Colors.DimGray; DirectionalLightColor = Colors.White; DirectionalLightDirection = new Vector3D(-2, -5, -2); // floor plane grid Grid = LineBuilder.GenerateGrid(new Vector3(0, 1, 0), -5, 5, -5, 5); GridColor = Colors.Black; GridTransform = new Media3D.TranslateTransform3D(0, -3, 0); // scene model3d var b1 = new MeshBuilder(); b1.AddSphere(new Vector3(0, 0, 0), 0.5); b1.AddBox(new Vector3(0, 0, 0), 1, 0.5, 2, BoxFaces.All); var meshGeometry = b1.ToMeshGeometry3D(); meshGeometry.Colors = new Color4Collection(meshGeometry.TextureCoordinates.Select(x => x.ToColor4())); Model = meshGeometry; // lines model3d var e1 = new LineBuilder(); e1.AddBox(new Vector3(0, 0, 0), 1, 0.5, 2); Lines = e1.ToLineGeometry3D(); var textBuilder = new MeshBuilder(); textBuilder.ExtrudeText("HelixToolkit.SharpDX", "Arial", System.Windows.FontStyles.Normal, System.Windows.FontWeights.Bold, 14, new Vector3(1, 0, 0), new Vector3(0, 0, 0), new Vector3(0, 0, 1)); TextModel = textBuilder.ToMesh(); // model trafos Model1Transform = new Media3D.TranslateTransform3D(0, 0, 0); Model2Transform = new Media3D.TranslateTransform3D(-2, 0, 0); Model3Transform = new Media3D.TranslateTransform3D(+2, 0, 0); Model4Transform = new Media3D.TranslateTransform3D(-8, 0, -5); // model materials RedMaterial = PhongMaterials.Red; GreenMaterial = PhongMaterials.Green; BlueMaterial = PhongMaterials.Blue; //var diffColor = this.RedMaterial.DiffuseColor; //diffColor.Alpha = 0.5f; //this.RedMaterial.DiffuseColor = diffColor; Points = new PointGeometry3D(); var ptPos = new Vector3Collection(); var ptIdx = new IntCollection(); for (int x = 0; x < 10; x++) { for (int y = 0; y < 10; y++) { for (int z = 0; z < 10; z++) { ptIdx.Add(ptPos.Count); ptPos.Add(new Vector3(x, y, z)); } } } Points.Positions = ptPos; Points.Indices = ptIdx; Text = new BillboardText3D(); int numRows = 11; int numColumns = 11; string[] texts = new string[] { "HelixToolkit", "abcde", "random", "SharpDX", "DirectX" }; float angle = 0; for (var i = 0; i < numRows; i++) { for (var j = 0; j < numColumns; j++) { angle += (float)Math.PI / 10; Text.TextInfo.Add(new TextInfo(texts[(i + j) % texts.Length], new Vector3((i - numRows / 2), 0.0f, (j - numColumns / 2))) { Foreground = new Color4((float)i / numRows, 1 - (float)i / numRows, (float)(numColumns - j) / numColumns, 1f), Background = new Color4(1 - (float)i / numRows, (float)(numColumns - j) / numColumns, (float)i / numRows, 0.8f), Scale = Math.Max(0.01f, (float)i / numRows * 0.02f), Angle = angle }); } } Billboard1Model = new BillboardSingleText3D() { TextInfo = new TextInfo("Model 1", new Vector3(0, 1, 0)) { Angle = 0 }, FontColor = Colors.Blue.ToColor4(), FontSize = 12, BackgroundColor = Colors.Plum.ToColor4(), FontStyle = System.Windows.FontStyles.Italic, Padding = new System.Windows.Thickness(2), }; var background = Colors.Blue; background.A = (byte)120; Billboard2Model = new BillboardSingleText3D() { TextInfo = new TextInfo("Model 2", new Vector3(2, 1, 0)) { Angle = -(float)Math.PI / 3 }, FontSize = 12, FontColor = Colors.Green.ToColor4(), BackgroundColor = background.ToColor4(), FontWeight = System.Windows.FontWeights.Bold, Padding = new System.Windows.Thickness(2), }; background = Colors.Purple; background.A = (byte)50; Billboard3Model = new BillboardSingleText3D(2, 0.8f) { TextInfo = new TextInfo("Model 3", new Vector3(-2, 1, 0)) { Angle = -(float)Math.PI / 6 }, FontSize = 12, FontColor = Colors.Red.ToColor4(), BackgroundColor = background.ToColor4(), FontFamily = "Times New Roman", FontStyle = System.Windows.FontStyles.Italic, Padding = new System.Windows.Thickness(2), }; //BillboardImageModel = new BillboardSingleImage3D(CreateBitmapSample()) { MaskColor = Color.Black }; BillboardImageModel = new BillboardSingleImage3D(CreatePNGSample(), 1, 1) { Angle = -(float)Math.PI / 5 }; BillboardImageModel.Center = new Vector3(2, 2, 0); UpXCommand = new RelayCommand(x => { UpDirection = new Vector3D(1, 0, 0); }); UpYCommand = new RelayCommand(x => { UpDirection = new Vector3D(0, 1, 0); }); UpZCommand = new RelayCommand(x => { UpDirection = new Vector3D(0, 0, 1); }); BackgroundTexture = BitmapExtensions.CreateLinearGradientBitmapStream(EffectsManager, 128, 128, Direct2DImageFormat.Bmp, new Vector2(0, 0), new Vector2(0, 128), new SharpDX.Direct2D1.GradientStop[] { new SharpDX.Direct2D1.GradientStop() { Color = Colors.White.ToColor4(), Position = 0f }, new SharpDX.Direct2D1.GradientStop() { Color = Colors.DarkGray.ToColor4(), Position = 1f } }); }
private static List <Line> GetAllLines(string fullName, string[] tmpText) { var lines = new List <Line>(); var propertys = new List <string>(); string moduleName = GetImportName(fullName.Replace(Extension.BPModule, "")); bool func = false; int funcNum = 0; for (int i = 0; i < tmpText.Length; i++) { var tmpLine = new Line(LineBuilder.GetWords(tmpText[i]), tmpText[i]); tmpLine.Number = i + 1; //tmpLine.FileName = moduleName + Extension.BPModule; tmpLine.FileName = fullName; tmpLine.Type = LineBuilder.GetType(tmpLine); if (tmpLine.Type == LineType.INCLUDE) { Data.Errors.Add(new Errore(tmpLine.Number, moduleName + Extension.BPModule, 2005, "")); return(lines); } else if (tmpLine.Type == LineType.FOLDER) { Data.Errors.Add(new Errore(tmpLine.Number, moduleName + Extension.BPModule, 2006, "")); return(lines); } else if (tmpLine.Type == LineType.FUNCINIT) { if (func) { Data.Errors.Add(new Errore(tmpLine.Number, moduleName + Extension.BPModule, 1026, "")); return(lines); } else { func = true; funcNum = tmpLine.Number; } } else if (tmpLine.Type == LineType.ONEKEYWORD && tmpLine.Words[0].ToLower() == "endfunction") { if (!func) { Data.Errors.Add(new Errore(tmpLine.Number, moduleName + Extension.BPModule, 1027, "")); return(lines); } else { func = false; } } else if (tmpLine.Type == LineType.SUBINIT) { Data.Errors.Add(new Errore(tmpLine.Number, moduleName + Extension.BPModule, 2007, "")); return(lines); } else if (tmpLine.Type == LineType.NUMBERINIT || tmpLine.Type == LineType.NUMBERARRAYINIT || tmpLine.Type == LineType.STRINGINIT || tmpLine.Type == LineType.STRINGARRAYINIT) { tmpLine.Type = LineType.MODULEPROPERTY; /* * Console.Write("\n"); * Console.WriteLine("===> " + tmpLine.NewLine); * string str = ""; * foreach (var w in tmpLine.Words) * { * str += w.Token.ToString() + " "; * } * Console.WriteLine(str); * Console.Write("\n"); */ if (func) { Data.Errors.Add(new Errore(tmpLine.Number, moduleName + Extension.BPModule, 2015, "")); return(lines); } if (tmpLine.Count != 2) { // Ошибка Data.Errors.Add(new Errore(tmpLine.Number, moduleName + Extension.BPModule, 2011, "")); return(lines); } else if (tmpLine.Words[0].Token != Tokens.KEYWORD && tmpLine.Words[0].Token != Tokens.VARIABLE) { // Ошибка Data.Errors.Add(new Errore(tmpLine.Number, moduleName + Extension.BPModule, 2012, "")); return(lines); } else if (tmpLine.Words[0].ToLower() != "number" && tmpLine.Words[0].ToLower() != "number[]" && tmpLine.Words[0].ToLower() != "string" && tmpLine.Words[0].ToLower() != "string[]") { // Ошибка Data.Errors.Add(new Errore(tmpLine.Number, moduleName + Extension.BPModule, 2013, "")); return(lines); } else if (propertys.Contains(tmpLine.Words[1].ToLower())) { // Ошибка Data.Errors.Add(new Errore(tmpLine.Number, moduleName + Extension.BPModule, 2014, tmpLine.Words[1].OriginText)); return(lines); } else { propertys.Add(tmpLine.Words[1].ToLower()); } } else if (!func && tmpLine.Type != LineType.FUNCINIT) { if (tmpLine.Type != LineType.EMPTY && tmpLine.Type != LineType.IMPORT && tmpLine.NewLine.Trim().IndexOf("'") != 0 && tmpLine.Type != LineType.ONEKEYWORD) { Data.Errors.Add(new Errore(tmpLine.Number, moduleName + Extension.BPModule, 2008, "")); return(lines); } } // Парсим ошибки на количество скобок в строке BracketErrorParser.Start(tmpLine); if (Data.Errors.Count > 0) { return(lines); } lines.Add(tmpLine); } if (func) { Data.Errors.Add(new Errore(funcNum, moduleName + Extension.BPModule, 1028, "")); return(lines); } return(lines); }
public MainPageViewModel() { EffectsManager = new DefaultEffectsManager(new Logger()); Camera = new PerspectiveCamera() { Position = new Vector3(40, 10, 100), LookDirection = new Vector3(0, -10, -100), UpDirection = UpDirection, FarPlaneDistance = 500, NearPlaneDistance = 0.1 }; Camera1 = new OrthographicCamera() { Position = new Vector3(60, 10, 100), LookDirection = new Vector3(0, -10, -100), UpDirection = upDirection, Width = 30, FarPlaneDistance = 500, NearPlaneDistance = 20 }; var builder = new MeshBuilder(true, true, true); builder.AddBox(new SharpDX.Vector3(0, 0, 0), 2, 2, 2); builder.AddSphere(new Vector3(0, 2, 0), 1.5); Geometry = builder.ToMesh(); Geometry.UpdateOctree(); builder = new MeshBuilder(); builder.AddSphere(new Vector3(0, 2, 0), 2); Sphere = builder.ToMesh(); Sphere.UpdateOctree(); Material = new PhongMaterial() { AmbientColor = Color.Gray, DiffuseColor = new Color4(0.75f, 0.75f, 0.75f, 1.0f), SpecularColor = Color.White, SpecularShininess = 10f, ReflectiveColor = new Color4(0.2f, 0.2f, 0.2f, 0.5f) }; Material.DiffuseMap = LoadTexture("TextureCheckerboard2.jpg"); Material.NormalMap = LoadTexture("TextureCheckerboard2_dot3.jpg"); Material1 = Material.Clone(); Material1.ReflectiveColor = Color.Silver; Material1.RenderDiffuseMap = false; Material1.RenderNormalMap = false; var lineBuilder = new LineBuilder(); lineBuilder.AddLine(Vector3.Zero, new Vector3(5, 0, 0)); lineBuilder.AddLine(Vector3.Zero, new Vector3(0, 5, 0)); lineBuilder.AddLine(Vector3.Zero, new Vector3(0, 0, 5)); LineGeometry = lineBuilder.ToLineGeometry3D(); LineGeometry.Colors = new HelixToolkit.UWP.Core.Color4Collection() { Color.Red, Color.Red, Color.Green, Color.Green, Color.Blue, Color.Blue }; builder = new MeshBuilder(); builder.AddSphere(new Vector3(), 3); var mesh = builder.ToMesh(); mesh.UpdateOctree(); PointGeometry = new PointGeometry3D() { Positions = mesh.Positions }; AxisLabelGeometry = new BillboardText3D(); AxisLabelGeometry.TextInfo.Add(new TextInfo("X", new Vector3(5.5f, 0, 0)) { Foreground = Color.Red }); AxisLabelGeometry.TextInfo.Add(new TextInfo("Y", new Vector3(0, 5.5f, 0)) { Foreground = Color.Green }); AxisLabelGeometry.TextInfo.Add(new TextInfo("Z", new Vector3(0, 0, 5.5f)) { Foreground = Color.Blue }); builder = new MeshBuilder(); builder.AddBox(new Vector3(0, -6, 0), 30, 0.5, 30); FloorModel = builder.ToMesh(); FloorMaterial = PhongMaterials.Obsidian; FloorMaterial.ReflectiveColor = Color.Silver; EnvironmentMap = LoadTexture("Cubemap_Grandcanyon.dds"); UpDirXCommand = new RelayCommand(() => { UpDirection = Vector3.UnitX; }, () => { return(UpDirection != Vector3.UnitX); }); UpDirYCommand = new RelayCommand(() => { UpDirection = Vector3.UnitY; }, () => { return(UpDirection != Vector3.UnitY); }); UpDirZCommand = new RelayCommand(() => { UpDirection = Vector3.UnitZ; }, () => { return(UpDirection != Vector3.UnitZ); }); timer = new DispatcherTimer(); timer.Tick += Timer_Tick; timer.Interval = new TimeSpan(0, 0, 0, 0, 16); timer.Start(); }
public void GetLinesFromZeroOrOneBlockTest() { int patternLength = 3; var pattern = new string('\0', patternLength); LineBuilder builder = new LineBuilder(pattern, null); string text = "a"; var textBlock = new TextBlock(text); var zeroOrOneBlock = new ZeroOrOneBlock(textBlock); List<string> lines = builder.GetLinesFromZeroOrOneBlock(0, zeroOrOneBlock).ToList(); string[] expectedLines = new[] { "", "a" }; CollectionAssert.AreEquivalent(expectedLines, lines); }