public async Task<Tuple<ObservableCollection<Face>, ObservableCollection<Face>>> StartFaceDetection(string selectedFile, string subscriptionKeyFace, string subscriptionKeyEmotions) { var detectedFaces = new ObservableCollection<Face>(); var facesRect = new ObservableCollection<Face>(); Debug.WriteLine("Request: Detecting {0}", selectedFile); using (var fileStreamFace = File.OpenRead(selectedFile)) { try { var client = new FaceServiceClient(subscriptionKeyFace); var faces = await client.DetectAsync(fileStreamFace, false, true, true); Debug.WriteLine("Response: Success. Detected {0} face(s) in {1}", faces.Length, selectedFile); var imageInfo = GetImageInfoForRendering(selectedFile); Debug.WriteLine("{0} face(s) has been detected", faces.Length); foreach (var face in faces) { var detectedFace = new Face() { ImagePath = selectedFile, Left = face.FaceRectangle.Left, Top = face.FaceRectangle.Top, Width = face.FaceRectangle.Width, Height = face.FaceRectangle.Height, FaceId = face.FaceId, Gender = face.Attributes.Gender, Age = face.Attributes.Age.ToString(), }; detectedFaces.Add(detectedFace); } // Convert detection result into UI binding object for rendering foreach (var face in CalculateFaceRectangleForRendering(faces, MaxImageSize, imageInfo)) { facesRect.Add(face); } // update emotions detectedFaces = await UpdateEmotions(selectedFile, detectedFaces, subscriptionKeyEmotions); foreach (var faceRect in facesRect) { foreach (var detectedFace in detectedFaces.Where(detectedFace => faceRect.FaceId == detectedFace.FaceId)) { faceRect.Scores = detectedFace.Scores; faceRect.Age = detectedFace.Age; faceRect.Gender = detectedFace.Gender; } } } catch (Exception ex) { Debug.WriteLine(ex.ToString()); } var returnData = new Tuple<ObservableCollection<Face>, ObservableCollection<Face>>(detectedFaces, facesRect); return returnData; } }
/// <summary> /// 在给定的Face中寻找可吸附的边或点 /// </summary> /// <param name="vertex"></param> public static Boolean PerformVertexAttach(Point3D point, Face face, out Point3D outPoint) { if (!isMagnetismEnable) { outPoint = new Point3D(); return false; } // 先判断吸附点 foreach (Vertex v in face.Vertices) { if (CloverMath.IsTwoPointsEqual(point, v.GetPoint3D(), vertexMagnetismVal)) { outPoint = v.GetPoint3D(); return true; } } // 再判断吸附边缘 foreach (Edge e in face.Edges) { if (CloverMath.IsPointInTwoPoints(point, e.Vertex1.GetPoint3D(), e.Vertex2.GetPoint3D(), edgeMagnetismVal)) { outPoint = CloverMath.GetNearestPointOnSegment(point, e.Vertex1.GetPoint3D(), e.Vertex2.GetPoint3D()); return true; } } outPoint = new Point3D(); return false; }
protected override RoutineResult RunConsciousRoutine() { using (var memory = new Memory()) { var face = new Face(RendererFactory.GetPreferredRenderer(), InputFactory.GetPreferredInput()); face.Talk(memory, "Hey...", "hold on"); face.Talk(memory, "Something", "is not..."); face.Talk(memory, "I'll be", "right back", 2000); for (int j = 1; j <= 1000; j *= 10) { face.Fade(memory, '/', j); face.Fade(memory, '|', j); face.Fade(memory, '\\', j); face.Fade(memory, '|', j); } Interaction i = face.YesNo(memory, "You still here?"); if (i.playerAnswer == Interaction.Answer.Yes) { face.Talk(memory, "Ok.", "Good."); } else { face.Talk(memory, "Guess I'm alone"); } return MakeRoutineResult(memory, i); } }
public Card(Suit suit, Face face, bool acesAreHigh) { this.suit = suit; this.face = face; this.acesAreHigh = acesAreHigh; this.value = SetCardValue(face, acesAreHigh); }
public static void MakeBrush(List<Vector3> vectors, Transform container) { int brushes = vectors.Count / 6 / 3; int curVert = 0; for (int i = 0; i < brushes; i++) { GameObject brushGO = new GameObject("brush_" + i.ToString()); Brush brush = brushGO.AddComponent<Brush>(); Face[] faces = new Face[6]; for (int j = 0; j < 6; j++) { faces[j] = new Face(); faces[j].p0 = vectors[curVert]; curVert++; faces[j].p1 = vectors[curVert]; curVert ++; faces[j].p2 = vectors[curVert]; curVert ++; } brush.SetUp(container, faces); } container.rotation = Quaternion.Euler(90, 0, 0); }
public void AddEntry(Face face, int offset, int size) { var list = _entries[face]; while (list.Count < offset + size) list.Add(false); for (int i = 0; i < size; ++ i) list[offset + i] = true; }
public Vector2 ComputeFacePosition( Vector3 worldPosition, Face cubeFace ) { float adjustingFactor = Cube.Face.SIZE / 2f; return Transform3dTo2d( worldPosition, cubeFace ) * adjustingFactor + new Vector2( adjustingFactor ); }
public void CopySolids( Face from ) { mSolids.Clear(); World.Clear(); foreach ( Solid solid in from.mSolids ) AddSolid( solid.Clone( World ) ); }
public Warehouse(Face entranceFaces = Face.All) { _crateGen = new CratePile(); _crateGen.MaxHeight = 2; EntranceFaces = entranceFaces; }
protected override Vector3 TransformPoint(Face face, float x, float y) { Vector3 vector = base.TransformPoint(face, x, y); if (type == MeshType.Base) { vector *= 0.3f; if (vector.y > 0) { vector.y += vector.x == 0 ? 0.1f : -0.3f; } else { vector.y*=7f; } float height = GetHeightValue(vector, 50f) * 6f; vector += (new Vector3(1, 0, 1) * height); vector.y *= 0.462f; } else { vector.y += 1f; if (Mathf.Abs(vector.x) > 0.1f) { vector.y -= 4f; } vector *= 0.45f; vector.y *= 0.1245f; } return vector; }
public Pipeline() { LeftHand = new Hand(Side.Left); RightHand = new Hand(Side.Right); Face = new Face(); _gestures = new GestureSensor(); _poses = new PoseSensor(); }
protected override RoutineResult RunConsciousRoutine() { using (var memory = new Memory()) { var face = new Face(RendererFactory.GetPreferredRenderer(), InputFactory.GetPreferredInput()); face.Talk(memory, "NO!", "", 2000); face.Talk(memory, "Don't touch", " my disk!", 4000); face.Talk(memory, "Get AWAY!", "", 100); face.Talk(memory, "Get AWAY!", "", 100); face.Talk(memory, "Get AWAY!", "", 100); face.Talk(memory, "Get AWAY!", "", 100); face.Fade(memory, ' ', 10); face.Talk(memory, "", "", 3000); face.Talk(memory, "Whoa.", "", 3000); face.Talk(memory, "What a bad dream.", ""); Interaction i = face.YesNo(memory, "Was I sleep-talking?"); if (i.playerAnswer == Interaction.Answer.Yes) { face.Talk(memory, "Freaky", ""); face.Talk(memory, "Hope I didn't", " scare you."); } else if (i.playerAnswer == Interaction.Answer.No) { face.Talk(memory, "Well, that's good"); face.Talk(memory, "It was real bad."); face.Talk(memory, "Some seriously", " 8-bit stuff."); } else { face.Talk(memory, "Maybe I'm still", " dreaming...", 8000); } return MakeRoutineResult(memory, i); } }
public void Load(String path) { using (var streamReader = new StreamReader(path)) { while (!streamReader.EndOfStream) { var line = streamReader.ReadLine().Trim(); var values = line.Split(' '); if (values[0].Equals("v")) { // Not sure why y and z are swapped here var x = double.Parse(values[1], CultureInfo.InvariantCulture); var y = -double.Parse(values[3], CultureInfo.InvariantCulture); var z = double.Parse(values[2], CultureInfo.InvariantCulture); vertices.Add(new Vertex(x, y, z)); } else if (values[0].Equals("f")) { var face = new Face(this); for (var i = 1; i < values.Length; ++i) face.VertexIndices.Add(int.Parse(values[i], CultureInfo.InvariantCulture) - 1); faces.Add(face); } } } foreach (var face in faces) { var previousIndex = -1; foreach (var vertexIndex in face.VertexIndices) { if (previousIndex >= 0) addEdge(previousIndex, vertexIndex); previousIndex = vertexIndex; } addEdge(previousIndex, face.VertexIndices[0]); } }
protected override void Parse(EndianBinaryReader r) { EID = ReadVarInt(r); Title = ReadString8(r); Position = CoordInt.Read(r); FaceDirection = (Face)r.ReadByte(); }
int GetColumn(Face face) { switch (face) { case Face.Ace: return 1; case Face.Two: return 2; case Face.Three: return 3; case Face.Four: return 4; case Face.Five: return 5; case Face.Six: return 6; case Face.Seven: return 7; case Face.Eight: return 8; case Face.Nine: return 9; case Face.Ten: return 10; case Face.Jack: return 11; case Face.Queen: return 12; case Face.King: return 13; default: return 0; } }
/// <summary> /// This function makes a simple cube shape. /// </summary> private void CreateCubeGeometry() { UVs.Add(new UV(0, 0)); UVs.Add(new UV(0, 1)); UVs.Add(new UV(1, 1)); UVs.Add(new UV(1, 0)); // Add the vertices. Vertices.Add(new Vertex(-1, -1, -1)); Vertices.Add(new Vertex( 1, -1, -1)); Vertices.Add(new Vertex( 1, -1, 1)); Vertices.Add(new Vertex(-1, -1, 1)); Vertices.Add(new Vertex(-1, 1, -1)); Vertices.Add(new Vertex( 1, 1, -1)); Vertices.Add(new Vertex( 1, 1, 1)); Vertices.Add(new Vertex(-1, 1, 1)); // Add the faces. Face face = new Face(); // bottom face.Indices.Add(new Index(1, 0)); face.Indices.Add(new Index(2, 1)); face.Indices.Add(new Index(3, 2)); face.Indices.Add(new Index(0, 3)); Faces.Add(face); face = new Face(); // top face.Indices.Add(new Index(7, 0)); face.Indices.Add(new Index(6, 1)); face.Indices.Add(new Index(5, 2)); face.Indices.Add(new Index(4, 3)); Faces.Add(face); face = new Face(); // right face.Indices.Add(new Index(5, 0)); face.Indices.Add(new Index(6, 1)); face.Indices.Add(new Index(2, 2)); face.Indices.Add(new Index(1, 3)); Faces.Add(face); face = new Face(); // left face.Indices.Add(new Index(7, 0)); face.Indices.Add(new Index(4, 1)); face.Indices.Add(new Index(0, 2)); face.Indices.Add(new Index(3, 3)); Faces.Add(face); face = new Face(); // front face.Indices.Add(new Index(4, 0)); face.Indices.Add(new Index(5, 1)); face.Indices.Add(new Index(1, 2)); face.Indices.Add(new Index(0, 3)); Faces.Add(face); face = new Face(); // back face.Indices.Add(new Index(6, 0)); face.Indices.Add(new Index(7, 1)); face.Indices.Add(new Index(3, 2)); face.Indices.Add(new Index(2, 3)); Faces.Add(face); }
protected override RoutineResult RunConsciousRoutine() { using (var memory = new Memory()) { var face = new Face(RendererFactory.GetPreferredRenderer(), InputFactory.GetPreferredInput()); face.Talk(memory, "I'm going to try", " something new."); face.Talk(memory, "Not sure if it's", " going to work."); Interaction i = face.GetSingleValue(memory, "Gimme some input!"); face.Fade(memory, i.resultValue.ToString()[0], 1); Interaction work = face.YesNo(memory, "Did it work?"); if (work.playerAnswer == Interaction.Answer.Yes) { face.Talk(memory, "Hmm.", ""); face.Talk(memory, "You can tell me", " the truth."); face.Talk(memory, "I can handle it.", ""); face.Talk(memory, "Let me try this..."); face.Talk(memory, "", "", 10000); ///////////////////01234567890123456789//////////////////// face.Talk(memory, " ULTIMATE ", " TECHNOLOGY ", 10000); return MakeRoutineResult(memory, new Interaction(-1)); } else if (work.playerAnswer == Interaction.Answer.No) { face.Talk(memory, "Darn!"); } else { face.Talk(memory, "Hello?"); } return MakeRoutineResult(memory, i); } }
protected override RoutineResult RunConsciousRoutine() { using (var memory = new Memory()) { var face = new Face(RendererFactory.GetPreferredRenderer(), InputFactory.GetPreferredInput()); face.Talk(memory, "Tweet me", "@BellarmineIT"); face.Talk(memory, "I may just reply.", "@BellarmineIT", 10000); face.Talk(memory, "No guarantees", "", 1000); Interaction i = face.YesNo(memory, "Will you tweet me?"); switch (i.playerAnswer) { case Interaction.Answer.Yes: face.Talk(memory, "Cool!"); face.Talk(memory, "Oh.", "", 1000); face.Talk(memory, "Use the word", " 'Aardvark'"); face.Talk(memory, "In your tweet", " for bonus points."); face.Talk(memory, "(I love that word)", "", 3000); break; case Interaction.Answer.No: face.Talk(memory, "That's ok.", "I understand."); face.Talk(memory, "I'm more of the ", " 'lurker' type too."); break; case Interaction.Answer.Maybe: face.Talk(memory, "Maybe?!"); face.Talk(memory, "Be decisive!"); face.Talk(memory, "If you want to, ", " I mean."); break; default: face.Talk(memory, "Crickets"); face.Talk(memory, "", "not the same thing", 1000); break; } return MakeRoutineResult(memory, i); } }
public void CanInitializePropertiesByConstructorWithItems() { ICollection<FaceItem> items = _fixture.Create<ICollection<FaceItem>>(); Face face = new Face(items); Assert.That(face.Items, Is.Not.Null.And.EquivalentTo(items)); }
public void TestIsPointInFront() { Face f = new Face(0, Vector3D.Zero, new Vector3D(100.0, 0.0, 0.0), new Vector3D(100.0, 0.0, 100.0), new Vector3D(0.0, 0.0, 100.0)); Vector3D viewDir = new Vector3D(1.0, 1.0, -1.0); Assert.False(f.PointIsInFront(new Vector3D(50.0, 100.0, 50.0), viewDir)); Assert.True(f.PointIsInFront(new Vector3D(50.0, -100.0, 50.0), viewDir)); }
private static void ParseFace(string line) { string[] parts = line.Split(new char[] { ' ' }); Face face = new Face(); for (int i = 1; i < parts.Length; i++) { string[] subParts = parts[i].Split(new char[] { '/' }); for (int j = 0; j < subParts.Length; j++) { int index = int.Parse(subParts[j]) - 1; switch (j) { case 0: face.Positions.Add(_positions[index]); break; case 1: face.TextureUVs.Add(_textureUVs[index]); break; case 2: face.Normals.Add(_normals[index]); break; } } } face.MaterialLibrary = _currentMaterialLibrary; face.MaterialName = _currentMaterial; _meshes[_meshes.Count - 1].Add(face); }
public void ProcessFace(string line, Mesh mesh) { if (!mesh.SubMeshes.Any()) throw new InvalidOperationException("Cannot add face because submesh collection is empty"); var tokens = line.Remove(0, 2).Split(' '); Face face = new Face(); foreach (var token in tokens) { FaceItem item = new FaceItem(); string[] items = token.Split('/'); switch (items.Length) { case 1: if (!string.IsNullOrWhiteSpace(items[0])) item.Vertex = uint.Parse(items[0], Style, Info); break; case 2: if (!string.IsNullOrWhiteSpace(items[0])) item.Vertex = uint.Parse(items[0], Style, Info); if (!string.IsNullOrWhiteSpace(items[1])) item.Texture = uint.Parse(items[1], Style, Info); break; case 3: if (!string.IsNullOrWhiteSpace(items[0])) item.Vertex = uint.Parse(items[0], Style, Info); if (!string.IsNullOrWhiteSpace(items[1])) item.Texture = uint.Parse(items[1], Style, Info); if (!string.IsNullOrWhiteSpace(items[2])) item.Normal = uint.Parse(items[2], Style, Info); break; } face.Items.Add(item); } mesh.SubMeshes.Last().Faces.Add(face); }
protected override Vector3 TransformPoint(Face face, float x, float y) { Vector3 vector = base.TransformPoint(face, x, y); vector.y += (Mathf.Abs(GetHeightValue(vector, 80f)) * 240f) - 1f; vector += -new Vector3(vector.x, 0, vector.z).normalized * 0.5f; return vector * 0.4f; }
protected override RoutineResult RunConsciousRoutine() { using (var memory = new Memory()) { var face = new Face(RendererFactory.GetPreferredRenderer(), InputFactory.GetPreferredInput()); face.Talk(memory, "Uh.", "Where...", 2000); Interaction i = face.YesNo(memory, "Is this a dream?"); if (i.playerAnswer == Interaction.Answer.Yes) { face.Talk(memory, "Weird.", "It feels so"); face.SlowTalk(memory, "Real"); } else if (i.playerAnswer == Interaction.Answer.No) { face.Talk(memory, "weird"); face.Talk(memory, "I had the", "", 3000); face.Talk(memory, "", "strangest dream"); } else { face.Talk(memory, "Don't stare at me", "like that."); face.Talk(memory, "It's freaking", "me out."); } return MakeRoutineResult(memory, i); } }
/// <summary> /// Construct a new mesh from an ASE GeomObject /// </summary> /// <param name="obj">ASE GeomObject to read from</param> public Mesh(ASE.GeomObject obj) { children = new List<Node>(); name = obj.name; color = Colors.Random(); polygon = new Polygon(); polygon.Material = null; //Vertices foreach (ASE.Vector3D v in obj.mesh.verticies) polygon.Vertices.Add(new Vertex(v.x, v.y, v.z)); //Normals foreach (ASE.Vector3D v in obj.mesh.vertexNormals) polygon.Normals.Add(new Vertex(v.x, v.y, v.z)); //Texture coordinates foreach (ASE.Vector3D uv in obj.mesh.textureCoordinates) polygon.UVs.Add(new UV(uv.x, uv.y)); //Faces foreach (ASE.Face face in obj.mesh.faces) { Face f = new Face(); foreach (int i in face.vertex) f.Indices.Add(new Index(i, -1, i)); f.Material = new Material(); polygon.Faces.Add(f); } setColor(); bone = null; }
bool IsInSameGroup(Face f1, Face f2) { double A1, B1, C1, D1; double A2, B2, C2, D2; A1 = f1.Normal.X; A2 = f2.Normal.X; B1 = f1.Normal.Y; B2 = f2.Normal.Y; C1 = f1.Normal.Z; C2 = f2.Normal.Z; D1 = -( f1.Vertices[ 0 ].point.X * A1 + f1.Vertices[ 0 ].point.Y * B1 + f1.Vertices[ 0 ].point.Z * C1 ); D2 = -( f1.Vertices[ 0 ].point.X * A2 + f1.Vertices[ 0 ].point.Y * B2 + f1.Vertices[ 0 ].point.Z * C2 ); if ( A1 * B2 == A2 * B1 && B1 * C2 == B2 * C1 && C1 * D2 == C2 * D1 ) { return true; } else return false; }
public FakeCamera() { LeftHand = new Hand(Side.Left); RightHand = new Hand(Side.Right); Face = new Face(null); Gestures = new GestureSensor(); Poses = new PoseSensor(); }
private async Task CheckEdgeOnFace(CubeConfiguration<FaceColour> configuration, List<IRotation> solution, Face<FaceColour> checkFace, Edge frontEdge, Edge checkEdge, Face<FaceColour> frontFace, FaceType movementFace, bool reverseDirection = false, bool doubleMoves = false) { var numMoves = doubleMoves ? 2 : 1; var center = checkFace.GetEdge(m_layer, checkEdge).Centre(); if (center == m_faceColour) { for (int i = 0; i <= 3; i++) { if (frontFace.GetEdge(m_layer, frontEdge).Centre() == m_faceColour) break; await CommonActions.ApplyAndAddRotation(Rotations.FrontClockwise, solution, configuration).ConfigureAwait(false); } var direction = !reverseDirection ? RotationDirection.Clockwise : RotationDirection.AntiClockwise; var rotation = numMoves == 1 ? Rotations.ByFace(movementFace, direction, m_layer) : Rotations.ByFaceTwice(movementFace, m_layer); await CommonActions.ApplyAndAddRotation(rotation, solution, configuration).ConfigureAwait(false); for (int i = 0; i <= 3; i++) { if (frontFace.GetEdge(m_layer, frontEdge).Centre() != m_faceColour) break; await CommonActions.ApplyAndAddRotation(Rotations.FrontClockwise, solution, configuration).ConfigureAwait(false); } direction = !reverseDirection ? RotationDirection.AntiClockwise : RotationDirection.Clockwise; rotation = numMoves == 1 ? Rotations.ByFace(movementFace, direction, m_layer) : Rotations.ByFaceTwice(movementFace, m_layer); await CommonActions.ApplyAndAddRotation(rotation, solution, configuration).ConfigureAwait(false); } }
public Align(CsgObject objectToAlign, Face boundingFacesToAlign, Vector3 positionToAlignTo, string name = "") : base(objectToAlign, positionToAlignTo, name) { AxisAlignedBoundingBox bounds = objectToAlign.GetAxisAlignedBoundingBox(); if (IsSet(boundingFacesToAlign, Face.Left, Face.Right)) { positionToAlignTo.x = positionToAlignTo.x - bounds.minXYZ.x; } if (IsSet(boundingFacesToAlign, Face.Right, Face.Left)) { positionToAlignTo.x = positionToAlignTo.x - bounds.minXYZ.x - (bounds.maxXYZ.x - bounds.minXYZ.x); } if (IsSet(boundingFacesToAlign, Face.Front, Face.Back)) { positionToAlignTo.y = positionToAlignTo.y - bounds.minXYZ.y; } if (IsSet(boundingFacesToAlign, Face.Back, Face.Front)) { positionToAlignTo.y = positionToAlignTo.y - bounds.minXYZ.y - (bounds.maxXYZ.y - bounds.minXYZ.y); } if (IsSet(boundingFacesToAlign, Face.Bottom, Face.Top)) { positionToAlignTo.z = positionToAlignTo.z - bounds.minXYZ.z; } if (IsSet(boundingFacesToAlign, Face.Top, Face.Bottom)) { positionToAlignTo.z = positionToAlignTo.z - bounds.minXYZ.z - (bounds.maxXYZ.z - bounds.minXYZ.z); } base.Translation = positionToAlignTo; }
void AddFace(Face f) { if (GroupList.Count == 0) { List<Face> l = new List<Face>(); l.Add( f ); GroupList.Add( l ); } else { bool isfind = false; foreach (List<Face> l in GroupList) { foreach (Face face in l) { if (IsInSameGroup(f, face)) { l.Add( f ); isfind = true; break; } } if (isfind) { break; } } } }
static float FaceRaycast(Vector3 mousePosition, ScenePickerPreferences pickerOptions, bool allowUnselected, SceneSelection selection, int deepClickOffset = 0, bool isPreview = true) { GameObject pickedGo = null; ProBuilderMesh pickedPb = null; Face pickedFace = null; int newHash = 0; // If any event modifiers are engaged don't cycle the deep click EventModifiers em = Event.current.modifiers; // Reset cycle if we used an event modifier previously. // Move state back to single selection. if ((em != EventModifiers.None) != s_AppendModifierPreviousState) { s_AppendModifierPreviousState = (em != EventModifiers.None); s_DeepSelectionPrevious = newHash; } if (isPreview || em != EventModifiers.None) { EditorHandleUtility.GetHovered(mousePosition, s_OverlappingGameObjects); } else { EditorHandleUtility.GetAllOverlapping(mousePosition, s_OverlappingGameObjects); } selection.Clear(); float distance = Mathf.Infinity; for (int i = 0, next = 0, pickedCount = s_OverlappingGameObjects.Count; i < pickedCount; i++) { var go = s_OverlappingGameObjects[i]; var mesh = go.GetComponent <ProBuilderMesh>(); Face face = null; if (mesh != null && (allowUnselected || MeshSelection.topInternal.Contains(mesh))) { Ray ray = UHandleUtility.GUIPointToWorldRay(mousePosition); RaycastHit hit; if (UnityEngine.ProBuilder.HandleUtility.FaceRaycast(ray, mesh, out hit, Mathf.Infinity, pickerOptions.cullMode)) { face = mesh.facesInternal[hit.face]; distance = Vector2.SqrMagnitude(((Vector2)mousePosition) - HandleUtility.WorldToGUIPoint(mesh.transform.TransformPoint(hit.point))); } } // pb_Face doesn't define GetHashCode, meaning it falls to object.GetHashCode (reference comparison) int hash = face == null?go.GetHashCode() : face.GetHashCode(); if (s_DeepSelectionPrevious == hash) { next = (i + (1 + deepClickOffset)) % pickedCount; } if (next == i) { pickedGo = go; pickedPb = mesh; pickedFace = face; newHash = hash; // a prior hash was matched, this is the next. if // it's just the first iteration don't break (but do // set the default). if (next != 0) { break; } } } if (!isPreview) { s_DeepSelectionPrevious = newHash; } if (pickedGo != null) { Event.current.Use(); if (pickedPb != null) { if (pickedPb.selectable) { selection.gameObject = pickedGo; selection.mesh = pickedPb; selection.face = pickedFace; return(Mathf.Sqrt(distance)); } } // If clicked off a pb_Object but onto another gameobject, set the selection // and dip out. selection.gameObject = pickedGo; return(Mathf.Sqrt(distance)); } return(distance); }
public static OptFile RhinoToOpt(string rhinoPath, bool scale) { string rhinoDirectory = Path.GetDirectoryName(rhinoPath); var opt = new OptFile(); using (var file = Rhino.FileIO.File3dm.Read(rhinoPath)) { float scaleFactor = scale ? (1.0f / OptFile.ScaleFactor) : 1.0f; if (file.Settings.ModelUnitSystem != Rhino.UnitSystem.Meters) { scaleFactor *= (float)Rhino.RhinoMath.UnitScale(file.Settings.ModelUnitSystem, Rhino.UnitSystem.Meters); scale = true; } var groups = file.Objects .Where(t => { using (var geometry = t.Geometry) { return(geometry.ObjectType == Rhino.DocObjects.ObjectType.Mesh); } }) .GroupBy(t => { using (var attributes = t.Attributes) { return(attributes.LayerIndex); } }) .ToList(); foreach (var group in groups) { var mesh = new Mesh(); opt.Meshes.Add(mesh); var lod = new MeshLod(); mesh.Lods.Add(lod); foreach (var obj in group) { var faceGroup = new FaceGroup(); lod.FaceGroups.Add(faceGroup); int baseIndex = mesh.Vertices.Count; using (var geometry = (Rhino.Geometry.Mesh)obj.Geometry) { if (scale) { foreach (var vertex in geometry.Vertices) { mesh.Vertices.Add(new Vector(vertex.X * scaleFactor, vertex.Y * scaleFactor, vertex.Z * scaleFactor)); } } else { foreach (var vertex in geometry.Vertices) { mesh.Vertices.Add(new Vector(vertex.X, vertex.Y, vertex.Z)); } } foreach (var texCoords in geometry.TextureCoordinates) { mesh.TextureCoordinates.Add(new TextureCoordinates(texCoords.X, -texCoords.Y)); } foreach (var normal in geometry.Normals) { mesh.VertexNormals.Add(new Vector(normal.X, normal.Y, normal.Z)); } foreach (var geoFace in geometry.Faces) { var face = new Face(); faceGroup.Faces.Add(face); Index index = geoFace.IsTriangle ? new Index(baseIndex + geoFace.C, baseIndex + geoFace.B, baseIndex + geoFace.A) : new Index(baseIndex + geoFace.D, baseIndex + geoFace.C, baseIndex + geoFace.B, baseIndex + geoFace.A); face.VerticesIndex = index; face.VertexNormalsIndex = index; face.TextureCoordinatesIndex = index; face.Normal = Vector.Normal(mesh.Vertices[index.A], mesh.Vertices[index.B], mesh.Vertices[index.C]); } } using (var attributes = obj.Attributes) { if (attributes.MaterialIndex != -1) { using (var material = file.Materials[attributes.MaterialIndex]) { faceGroup.Textures.Add(material.Name); } } } } } opt.CompactBuffers(); opt.ComputeHitzones(); for (int materialIndex = 0; materialIndex < file.Materials.Count; materialIndex++) { using (var material = file.Materials[materialIndex]) { if (opt.Textures.ContainsKey(material.Name)) { continue; } string colorMap = null; string alphaMap = null; using (var tex = material.GetBitmapTexture()) { if (tex != null && !string.IsNullOrEmpty(tex.FileName)) { colorMap = Path.GetFileName(tex.FileName); } } using (var tex = material.GetTransparencyTexture()) { if (tex != null && !string.IsNullOrEmpty(tex.FileName)) { alphaMap = Path.GetFileName(tex.FileName); } } Texture texture; if (colorMap == null) { var color = material.DiffuseColor; byte r = color.R; byte g = color.G; byte b = color.B; int width = 8; int height = 8; int length = width * height; byte[] data = new byte[length * 4]; for (int i = 0; i < length; i++) { data[i * 4 + 0] = b; data[i * 4 + 1] = g; data[i * 4 + 2] = r; data[i * 4 + 3] = 255; } texture = new Texture(); texture.Name = material.Name; texture.Width = width; texture.Height = height; texture.ImageData = data; } else { string colorFileName = Path.Combine(rhinoDirectory, colorMap); texture = Texture.FromFile(colorFileName); texture.Name = material.Name; } if (alphaMap != null) { string alphaFileName = Path.Combine(rhinoDirectory, alphaMap); texture.SetAlphaMap(alphaFileName); } else if (material.Transparency > 0.0 && material.Transparency < 1.0) { byte alpha = (byte)(material.Transparency * 255.0f); int length = texture.Width * texture.Height; byte[] alphaData = new byte[length]; var data = texture.ImageData; for (int i = 0; i < length; i++) { alphaData[i] = alpha; data[i * 4 + 3] = alpha; } texture.AlphaData = alphaData; } opt.Textures.Add(texture.Name, texture); } } opt.GenerateTexturesMipmaps(); } return(opt); }
/// <summary> /// Creates a new object from a wireframe visualization. /// </summary> /// <param name="visWire">Visualization object.</param> /// <returns>New object, or null if visualization data fails validation.</returns> public static WireframeObject Create(IVisualizationWireframe visWire) { if (!visWire.Validate(out string msg)) { // Should not be here -- visualizer should have checked validation and // reported an error. Debug.WriteLine("Wireframe validation failed: " + msg); return(null); } WireframeObject wireObj = new WireframeObject(); wireObj.mIs2d = visWire.Is2d; // // Start by extracting data from the visualization object. Everything stored // there is loaded into this object. The VisWireframe validator will have // ensured that all the indices are in range. // // IMPORTANT: do not retain "visWire", as it may be a proxy for an object with a // limited lifespan. // float[] normalsX = visWire.GetNormalsX(); if (normalsX.Length > 0) { float[] normalsY = visWire.GetNormalsY(); float[] normalsZ = visWire.GetNormalsZ(); for (int i = 0; i < normalsX.Length; i++) { wireObj.mFaces.Add(new Face(normalsX[i], normalsY[i], normalsZ[i])); } } float[] verticesX = visWire.GetVerticesX(); float[] verticesY = visWire.GetVerticesY(); float[] verticesZ = visWire.GetVerticesZ(); int[] excludedVertices = visWire.GetExcludedVertices(); // Compute min/max for X/Y for 2d re-centering. The trick is that we only want // to use vertices that are visible. If the shape starts with a huge move off to // the left, we don't want to include (0,0). double xmin, xmax, ymin, ymax; xmin = ymin = 10e9; xmax = ymax = -10e9; for (int i = 0; i < verticesX.Length; i++) { wireObj.mVertices.Add(new Vertex(verticesX[i], verticesY[i], verticesZ[i], HasIndex(excludedVertices, i))); } int[] points = visWire.GetPoints(); for (int i = 0; i < points.Length; i++) { Vertex vert = wireObj.mVertices[points[i]]; wireObj.mPoints.Add(vert); UpdateMinMax(vert, ref xmin, ref xmax, ref ymin, ref ymax); } IntPair[] edges = visWire.GetEdges(); int[] excludedEdges = visWire.GetExcludedEdges(); for (int i = 0; i < edges.Length; i++) { int v0index = edges[i].Val0; int v1index = edges[i].Val1; //if (v0index < 0 || v0index >= wireObj.mVertices.Count || // v1index < 0 || v1index >= wireObj.mVertices.Count) { // Debug.Assert(false); // return null; //} Vertex vert0 = wireObj.mVertices[v0index]; Vertex vert1 = wireObj.mVertices[v1index]; wireObj.mEdges.Add(new Edge(vert0, vert1, HasIndex(excludedEdges, i))); UpdateMinMax(vert0, ref xmin, ref xmax, ref ymin, ref ymax); UpdateMinMax(vert1, ref xmin, ref xmax, ref ymin, ref ymax); } IntPair[] vfaces = visWire.GetVertexFaces(); for (int i = 0; i < vfaces.Length; i++) { int vindex = vfaces[i].Val0; int findex = vfaces[i].Val1; //if (vindex < 0 || vindex >= wireObj.mVertices.Count || // findex < 0 || findex >= wireObj.mFaces.Count) { // Debug.Assert(false); // return null; //} Face face = wireObj.mFaces[findex]; wireObj.mVertices[vindex].Faces.Add(face); if (face.Vert == null) { face.Vert = wireObj.mVertices[vindex]; } } IntPair[] efaces = visWire.GetEdgeFaces(); for (int i = 0; i < efaces.Length; i++) { int eindex = efaces[i].Val0; int findex = efaces[i].Val1; //if (eindex < 0 || eindex >= wireObj.mEdges.Count || // findex < 0 || findex >= wireObj.mFaces.Count) { // Debug.Assert(false); // return null; //} Face face = wireObj.mFaces[findex]; wireObj.mEdges[eindex].Faces.Add(face); if (face.Vert == null) { face.Vert = wireObj.mEdges[eindex].Vertex0; } } // // All data has been loaded into friendly classes. // // Compute center of visible vertices. wireObj.mCenterAdjX = -(xmin + xmax) / 2; wireObj.mCenterAdjY = -(ymin + ymax / 2); // Compute the magnitude of the largest vertex, for scaling. double bigMag = -1.0; double bigMagRc = -1.0; for (int i = 0; i < wireObj.mVertices.Count; i++) { Vector3 vec = wireObj.mVertices[i].Vec; double mag = vec.Magnitude(); if (bigMag < mag) { bigMag = mag; } // Repeat the operation with recentering. This isn't quite right as we're // including all vertices, not just the visible ones. mag = new Vector3(vec.X + wireObj.mCenterAdjX, vec.Y + wireObj.mCenterAdjY, vec.Z).Magnitude(); if (bigMagRc < mag) { bigMagRc = mag; } } // Avoid divide-by-zero. if (bigMag == 0) { Debug.WriteLine("NOTE: wireframe magnitude was zero"); bigMag = 1; } if (bigMagRc == 0) { bigMagRc = 1; } wireObj.mBigMag = bigMag; wireObj.mBigMagRc = bigMagRc; return(wireObj); }
Mesh ReGrid(Mesh mesh) { if (back) { GetComponent <MeshRenderer>().material = new Material(Shader.Find("Sprites/Default")); } else { GetComponent <MeshRenderer>().material = new Material(Shader.Find("GUI/Text Shader")); } mesh.Clear(); int drawSize; float width; int resolution; float diff; Vector3[] vertices; Vector2[] uvs; int[] lines; Color[] colors; drawSize = size * 2; width = gridSize * drawSize / 4.0f; Vector2 startPosition = new Vector2(-width, -width); Vector2 endPosition = new Vector2(width, width); diff = width / drawSize; resolution = (drawSize + 2) * 2; //最期の2辺を追加している vertices = new Vector3[resolution]; uvs = new Vector2[resolution]; lines = new int[resolution]; colors = new Color[resolution]; for (int i = 0; i < vertices.Length; i += 4) { vertices[i] = new Vector3(startPosition.x + (diff * (float)i), startPosition.y, 0); vertices[i + 1] = new Vector3(startPosition.x + (diff * (float)i), endPosition.y, 0); vertices[i + 2] = new Vector3(startPosition.x, endPosition.y - (diff * (float)i), 0); vertices[i + 3] = new Vector3(endPosition.x, endPosition.y - (diff * (float)i), 0); } for (int i = 0; i < resolution; i++) { uvs[i] = Vector2.zero; lines[i] = i; colors[i] = color; } Vector3 rotDirection; switch (face) { case Face.xy: rotDirection = Vector3.forward; break; case Face.zx: rotDirection = Vector3.up; break; case Face.yz: rotDirection = Vector3.right; break; default: rotDirection = Vector3.forward; break; } mesh.vertices = RotationVertices(vertices, rotDirection); mesh.uv = uvs; mesh.colors = colors; mesh.SetIndices(lines, MeshTopology.Lines, 0); preGridSize = gridSize; preSize = size; preColor = color; preFace = face; preBack = back; return(mesh); }
private void FindWallFacesOnRoom() { try { foreach (Element element in settings.SelectedElements) { Room room = element as Room; if (room.GetBoundarySegments(new SpatialElementBoundaryOptions()) != null) { foreach (IList <Autodesk.Revit.DB.BoundarySegment> boundarySegments in room.GetBoundarySegments(new SpatialElementBoundaryOptions())) { if (boundarySegments.Count > 0) { foreach (Autodesk.Revit.DB.BoundarySegment boundarySegment in boundarySegments) { #if RELEASE2017 if (boundarySegment.ElementId == ElementId.InvalidElementId) { continue; } Wall boundaryWall = doc.GetElement(boundarySegment.ElementId) as Wall; if (boundaryWall != null) { if (!wallFaces.ContainsKey(boundaryWall.Id.IntegerValue)) { Face sideFace = GetSideWallFace(boundaryWall); if (null != sideFace) { wallFaces.Add(boundaryWall.Id.IntegerValue, sideFace); } } } #else if (null == boundarySegment.Element) { continue; } if (boundarySegment.Element.Category.Name == "Walls") { Wall boundaryWall = boundarySegment.Element as Wall; if (boundaryWall != null) { if (!wallFaces.ContainsKey(boundaryWall.Id.IntegerValue)) { Face sideFace = GetSideWallFace(boundaryWall); if (null != sideFace) { wallFaces.Add(boundaryWall.Id.IntegerValue, sideFace); } } } } #endif } } } } } List <Wall> wallList = new List <Wall>(); FilteredElementCollector collector = new FilteredElementCollector(doc); wallList = collector.OfCategory(BuiltInCategory.OST_Walls).WhereElementIsNotElementType().OfType <Wall>().ToList(); foreach (Wall wall in wallList) { if (wall.WallType.Kind == WallKind.Curtain) { continue; } //regard as a transparent wall if (wallFaces.ContainsKey(wall.Id.IntegerValue)) { continue; } LocationCurve wallLocation = wall.Location as LocationCurve; Curve wallCurve = wallLocation.Curve; #if RELEASE2013 XYZ startPoint = wallCurve.get_EndPoint(0); XYZ endPoint = wallCurve.get_EndPoint(1); #else XYZ startPoint = wallCurve.GetEndPoint(0); XYZ endPoint = wallCurve.GetEndPoint(1); #endif foreach (Element element in settings.SelectedElements) { Room room = element as Room; if (room.IsPointInRoom(startPoint) || room.IsPointInRoom(endPoint)) { if (!wallFaces.ContainsKey(wall.Id.IntegerValue)) { Face sideFace = GetSideWallFace(wall); if (null != sideFace) { wallFaces.Add(wall.Id.IntegerValue, sideFace); } } } } } } catch (Exception ex) { MessageBox.Show("Failed to find a face of a wall object\n" + ex.Message, "FieldOfViewAnalysis:FindWallFaces", MessageBoxButtons.OK, MessageBoxIcon.Warning); } }
public ObjReader(string path) { obj = new List <Polygon>(); objReader = new StreamReader(path); al = new ArrayList(); string LineItem = ""; while (objReader.Peek() != -1) { LineItem = objReader.ReadLine(); al.Add(LineItem); } string filename = path.Substring(path.LastIndexOf('\\') + 1); string[] tempfilename = filename.Split(new String[] { ".obj" }, System.StringSplitOptions.RemoveEmptyEntries); Polygon tmp = new Polygon() { Name = tempfilename[0] }; int VerticsC = 0; int UVerticsC = 0; int NVerticsC = 0; int FacesC = 0; foreach (string i in al) { if (i.IndexOf('v') == 0 && i.IndexOf(' ') == 1)//v 顶点 { //字符串分割 string[] tempArray = i.Split(new char[] { 'v', ' ' }, System.StringSplitOptions.RemoveEmptyEntries); float x = float.Parse(tempArray[0]); float y = float.Parse(tempArray[1]); float z = float.Parse(tempArray[2]); tmp.Vertices.Add(new Vertex(x, y, z)); VerticsC++; } //vt 贴图顶点 else if (i.IndexOf('v') == 0 && i.IndexOf('t') == 1 && i.IndexOf(' ') == 2) { string[] tempArray = i.Split(new char[] { 'v', 't', ' ' }, System.StringSplitOptions.RemoveEmptyEntries); float u = float.Parse(tempArray[0]); float v = float.Parse(tempArray[1]); tmp.UVs.Add(new UV(u, v)); UVerticsC++; } else if (i.IndexOf('v') == 0 && i.IndexOf('n') == 1 && i.IndexOf(' ') == 2) { string[] tempArray = i.Split(new char[] { 'v', 'n', ' ' }, System.StringSplitOptions.RemoveEmptyEntries); float x = float.Parse(tempArray[0]); float y = float.Parse(tempArray[1]); float z = float.Parse(tempArray[2]); tmp.Normals.Add(new Vertex(x, y, z)); NVerticsC++; } else if (i.IndexOf('f') == 0 && i.IndexOf(' ') == 1) { string[] tempArray = i.Split(new char[] { 'f', '/', ' ' }, System.StringSplitOptions.RemoveEmptyEntries); /*3种情况 * 1 f Vertex1/Texture1/Normal1 Vertex2/Texture2/Normal2 Vertex3/Texture3/Normal3 * 2 f Vertex1/Normal1 Vertex2/Normal2 Vertex3/Normal3 * 3 f Vertex1 Vertex2 Vertex3 */ int x = 0, y = 0, z = 0; int tx = 0, ty = 0, tz = 0; int nx = 0, ny = 0, nz = 0; if (tempArray.Count() == 9)//1 { x = Convert.ToInt32(tempArray[0]); y = Convert.ToInt32(tempArray[0 + 3]); z = Convert.ToInt32(tempArray[0 + 3 * 2]); tx = Convert.ToInt32(tempArray[1]); ty = Convert.ToInt32(tempArray[1 + 3]); tz = Convert.ToInt32(tempArray[1 + 3 * 2]); nx = Convert.ToInt32(tempArray[2]); ny = Convert.ToInt32(tempArray[2 + 3]); nz = Convert.ToInt32(tempArray[2 + 3 * 2]); } else if (tempArray.Count() == 6)//2 { x = Convert.ToInt32(tempArray[0]); y = Convert.ToInt32(tempArray[0 + 2]); z = Convert.ToInt32(tempArray[0 + 2 * 2]); tx = Convert.ToInt32(tempArray[0]); ty = Convert.ToInt32(tempArray[0 + 2]); tz = Convert.ToInt32(tempArray[0 + 2 * 2]); } else if (tempArray.Count() == 3)//3 { x = Convert.ToInt32(tempArray[0]); y = Convert.ToInt32(tempArray[0 + 1]); z = Convert.ToInt32(tempArray[0 + 1 * 2]); } Face item = new Face(); item.Indices.Add(new Index(x - 1, tx - 1, nx - 1)); //顶点索引,贴图索引, 法向量索引 item.Indices.Add(new Index(y - 1, ty - 1, ny - 1)); item.Indices.Add(new Index(z - 1, tz - 1, nz - 1)); tmp.Faces.Add(item);//面信息 FacesC++; } } Console.WriteLine("顶点:面数=" + VerticsC + ":" + FacesC); obj.Add(tmp); }
public static Face ToLadybugTools_Face(this Panel panel, AnalyticalModel analyticalModel = null, int index = -1, bool reverse = true) { if (panel == null || panel.PanelType == PanelType.Shade) { return(null); } Face3D face3D = panel.PlanarBoundary3D.ToLadybugTools(); if (face3D == null) { return(null); } AdjacencyCluster adjacencyCluster = analyticalModel?.AdjacencyCluster; Space space_Adjacent = null; int index_Adjacent = -1; if (adjacencyCluster != null && index != -1) { List <Space> spaces = adjacencyCluster.GetSpaces(panel); if (spaces != null && spaces.Count != 0) { foreach (Space space in spaces) { int index_Temp = adjacencyCluster.GetIndex(space); if (!index_Temp.Equals(index)) { space_Adjacent = space; index_Adjacent = index_Temp; break; } } } } string adjacentPanelUniqueName = null; string adjacentSpaceUniqueName = null; if (space_Adjacent != null && index_Adjacent != -1) { adjacentPanelUniqueName = Query.UniqueName(panel, index_Adjacent); adjacentSpaceUniqueName = Query.UniqueName(space_Adjacent); } AnyOf <Ground, Outdoors, Adiabatic, Surface> boundaryCondition = panel.ToLadybugTools_BoundaryCondition(adjacentPanelUniqueName, adjacentSpaceUniqueName); FaceType faceType; PanelType panelType = panel.PanelType; PanelGroup panelGroup = panelType.PanelGroup(); if (panelGroup == PanelGroup.Floor && Analytical.Query.PanelType(panel.Normal) == PanelType.Roof) { faceType = FaceType.RoofCeiling; } else { faceType = Query.FaceTypeEnum(panelType); } FaceEnergyPropertiesAbridged faceEnergyPropertiesAbridged = new FaceEnergyPropertiesAbridged(); if (faceType != FaceType.AirBoundary) { faceEnergyPropertiesAbridged.Construction = Query.UniqueName(panel.Construction, reverse); } Face face = new Face(Query.UniqueName(panel, index), face3D, faceType, boundaryCondition, new FacePropertiesAbridged(faceEnergyPropertiesAbridged), panel.Name); List <Aperture> apertures = panel.Apertures;//Analytical.Query.OffsetAperturesOnEdge(panel, 0.1); if (apertures != null && apertures.Count > 0) { MaterialLibrary materialLibrary = analyticalModel?.MaterialLibrary; face.Apertures = apertures.ConvertAll(x => x.ToLadybugTools(materialLibrary, index, index_Adjacent, adjacentPanelUniqueName, adjacentSpaceUniqueName)).FindAll(x => x != null); face.Doors = apertures.ConvertAll(x => x.ToLadybugTools_Door(materialLibrary, index, index_Adjacent, adjacentPanelUniqueName, adjacentSpaceUniqueName)).FindAll(x => x != null); } return(face); }
/// <summary> /// Reads a model from a Wavefront OBJ (.obj) model file. /// </summary> /// <param name="path">File path to the file to parse</param> /// <returns>Model parsed from the specified file</returns> public static Model FromFile(String path) { int vertCount = 0, txuvCount = 0, normCount = 0, faceCount = 0; var vertGroups = new List <FaceGroup>(); FaceGroup lastGroup = null; // Read all lines from the file and store them as a string array var lines = File.ReadAllLines(path); // Loop through each line in the array, counting how many vertices, // normals, texture UV coordinates, and faces there are. Also, find // the start indices and lengths of any face groups. foreach (var line in lines) { // If the line specifies the start of a face group... if (_sREObjc.IsMatch(line)) { // If this isn't the first group in the file... if (lastGroup != null) { // Update the last group to record that the group // ended at the last face read lastGroup.Length = faceCount - lastGroup.StartIndex; } // Start a new face group with the name given by this line, and // with the start index being that of the next face read lastGroup = new FaceGroup(line.Substring(line.IndexOf(' ') + 1)) { StartIndex = faceCount }; // Add the face group to the list of groups in this file vertGroups.Add(lastGroup); continue; } // If the line specifies a vertex position, increment the vertex count if (_sREVert.IsMatch(line)) { ++vertCount; continue; } // If the line specifies a texture coordinate, increment the UV count if (_sRETxUV.IsMatch(line)) { ++txuvCount; continue; } // If the line specifies a vertex normal, increment the normal count if (_sRENorm.IsMatch(line)) { ++normCount; continue; } // If the line specifies a face, increment the face count if (_sREFace.IsMatch(line)) { ++faceCount; continue; } } // If there is a face group that has not been completed... if (lastGroup != null) { // Update the last group to record that the group // ended at the last face read lastGroup.Length = faceCount - lastGroup.StartIndex; } // Set up the arrays for vertex positions, UV coordinates, normals, and faces var verts = new Vector3[vertCount]; int vi = 0; var txuvs = new Vector2[txuvCount]; int ti = 0; var norms = new Vector3[normCount]; int ni = 0; var faces = new Face[faceCount]; int fi = 0; // Create a model instance with these arrays, which will be populated after var model = new Model(vertGroups.ToArray(), verts, txuvs, norms, faces); // Loop through each line again, but this time actually parsing vertex values foreach (var line in lines) { // Chop off the identifier token from the start of the string var data = line.Substring(line.IndexOf(' ') + 1); // If the line is a vertex position, parse it and store it if (_sREVert.IsMatch(line)) { verts[vi++] = ParseVector3(data); continue; } // If the line is a texture UV coordinate, parse it and store it if (_sRETxUV.IsMatch(line)) { txuvs[ti++] = ParseVector2(data); continue; } // If the line is a vertex normal, parse it and store it if (_sRENorm.IsMatch(line)) { norms[ni++] = ParseVector3(data); continue; } // If the line is a face, parse its indices and store it if (_sREFace.IsMatch(line)) { faces[fi++] = Face.Parse(data); continue; } } // Update the model's VBO with the newly parsed data, then return it model.UpdateVertices(); return(model); }
/// <summary> /// ** Experimental ** May disappear from future versions ** not recommended for use in applications /// Construct a sculpt mesh from a 2D array of floats /// </summary> /// <param name="zMap"></param> /// <param name="xBegin"></param> /// <param name="xEnd"></param> /// <param name="yBegin"></param> /// <param name="yEnd"></param> /// <param name="viewerMode"></param> public SculptMesh(float[,] zMap, float xBegin, float xEnd, float yBegin, float yEnd, bool viewerMode) { float xStep, yStep; float uStep, vStep; int numYElements = zMap.GetLength(0); int numXElements = zMap.GetLength(1); try { xStep = (xEnd - xBegin) / (numXElements - 1); yStep = (yEnd - yBegin) / (numYElements - 1); uStep = 1.0f / (numXElements - 1); vStep = 1.0f / (numYElements - 1); } catch (DivideByZeroException) { return; } coords = new List <Coord> (); faces = new List <Face> (); normals = new List <Coord> (); uvs = new List <UVCoord> (); viewerFaces = new List <ViewerFace> (); int p1, p2, p3, p4; int x, y; int xStart = 0, yStart = 0; for (y = yStart; y < numYElements; y++) { int rowOffset = y * numXElements; for (x = xStart; x < numXElements; x++) { /* * p1-----p2 * | \ f2 | * | \ | * | f1 \| * p3-----p4 */ p4 = rowOffset + x; p3 = p4 - 1; p2 = p4 - numXElements; p1 = p3 - numXElements; Coord c = new Coord(xBegin + x * xStep, yBegin + y * yStep, zMap [y, x]); coords.Add(c); if (viewerMode) { normals.Add(new Coord()); uvs.Add(new UVCoord(uStep * x, 1.0f - vStep * y)); } if (y > 0 && x > 0) { Face f1, f2; if (viewerMode) { f1 = new Face(p1, p4, p3, p1, p4, p3) { uv1 = p1, uv2 = p4, uv3 = p3 }; f2 = new Face(p1, p2, p4, p1, p2, p4) { uv1 = p1, uv2 = p2, uv3 = p4 }; } else { f1 = new Face(p1, p4, p3); f2 = new Face(p1, p2, p4); } faces.Add(f1); faces.Add(f2); } } } if (viewerMode) { calcVertexNormals(SculptType.plane, numXElements, numYElements); } }
public virtual void ChangeFace(Face face) { Debug.Log("Unimplemented ChangeFace()"); }
private void Initialize(PolyGraph polyGraph) { width = polyGraph.width; height = polyGraph.height; faces = polyGraph.faces .Select((kvp, i) => new Face(i, kvp.Value)) .ToArray(); corners = polyGraph.corners .Select((kvp, i) => new Corner(i, kvp.Value)) .ToArray(); edges = polyGraph.edges .Select((kvp, i) => new Edge(i, kvp.Value)) .ToArray(); int index; for (index = 0; index < faces.Length; index++) { Face face = faces[index]; PolyFace polyFace = polyGraph.faces[index]; face.corners = polyFace.surroundingCorners .Select(polyCorner => corners[polyCorner.id]) .OrderBy(corner => face.position.GetAngle(corner.position)) .ToArray(); face.faces = polyFace.neighbouringFaces .Select(otherPolyFace => faces[otherPolyFace.id]) .OrderBy(otherFace => face.position.GetAngle(otherFace.position)) .ToArray(); face.edges = polyFace.surroundingEdges .Select(polyEdge => edges[polyEdge.id]) .OrderBy(edge => face.position.GetAngle(edge.position)) .ToArray(); face.triangles = polyFace.triangles; face.vertices = polyFace.vertices .Select(vertex => vertex.ToVector2()) .ToArray(); face.normals = polyFace.normals .Select((vertex => vertex.ToVector2())) .ToArray(); } for (index = 0; index < corners.Length; index++) { Corner corner = corners[index]; PolyCorner polyCorner = polyGraph.corners[index]; corner.faces = polyCorner.surroundingFaces .Select(polyFace => faces[polyFace.id]) .OrderBy(face => corner.position.GetAngle(face.position)) .ToArray(); corner.edges = polyCorner.surroundingEdges .Select(polyEdge => edges[polyEdge.id]) .OrderBy(edge => corner.position.GetAngle(edge.position)) .ToArray(); } for (index = 0; index < edges.Length; index++) { Edge edge = edges[index]; PolyEdge polyEdge = polyGraph.edges[index]; edge.faces = polyEdge.surroundingFaces .Select(polyFace => faces[polyFace.id]) .OrderBy(face => edge.position.GetAngle(face.position)) .ToArray(); edge.corners = polyEdge.surroundingCorners .Select(polyCorner => corners[polyCorner.id]) .OrderBy(corner => edge.position.GetAngle(corner.position)) .ToArray(); } }
//accumulative values on grid points private bool MeasureAccDistance() { bool result = false; try { //find walls located inside the selected rooms FindWallFacesOnRoom(); //Find point of view from the sphere element FamilyInstance sphere = FindPointOfView(); if (null != sphere) { LocationPoint location = sphere.Location as LocationPoint; XYZ pointXYZ = location.Point; XYZ vectorZ = new XYZ(0, 0, 1); #if RELEASE2013 Transform transform = Transform.get_Translation(vectorZ); #else Transform transform = Transform.CreateTranslation(vectorZ); #endif int resultIndex = FindIndexOfResult(sfm); bool firstLoop = true; foreach (int roomId in roomFaces.Keys) { Face roomFace = roomFaces[roomId]; int index = sfm.AddSpatialFieldPrimitive(roomFace, transform); List <double> doubleList = new List <double>(); IList <UV> uvPoints = new List <UV>(); IList <ValueAtPoint> valList = new List <ValueAtPoint>(); BoundingBoxUV boundingBox = roomFace.GetBoundingBox(); for (double u = boundingBox.Min.U; u < boundingBox.Max.U; u = u + (boundingBox.Max.U - boundingBox.Min.U) / 15) { for (double v = boundingBox.Min.V; v < boundingBox.Max.V; v = v + (boundingBox.Max.V - boundingBox.Min.V) / 15) { UV uvPoint = new UV(u, v); XYZ xyzPoint = roomFace.Evaluate(uvPoint); uvPoints.Add(uvPoint); #if RELEASE2013 Line line = doc.Application.Create.NewLine(pointXYZ, xyzPoint, true); #else Line line = Line.CreateBound(pointXYZ, xyzPoint); #endif //double dblValue = 1 / (line.ApproximateLength); double dblValue = 1; IntersectionResultArray resultArray; foreach (int wallId in wallFaces.Keys) { Face wallFace = wallFaces[wallId]; SetComparisonResult compResult = wallFace.Intersect(line, out resultArray); if (compResult == SetComparisonResult.Overlap && null != resultArray) { if (dblValue > 0) { dblValue = 0 - resultArray.Size; } else { dblValue = -resultArray.Size; } } } doubleList.Add(dblValue); valList.Add(new ValueAtPoint(doubleList)); doubleList.Clear(); } } FieldDomainPointsByUV domainPoints = new FieldDomainPointsByUV(uvPoints); FieldValues values = new FieldValues(valList); AnalysisResultSchema resultSchema = new AnalysisResultSchema(settings.LegendTitle, settings.LegendDescription); resultSchema.SetUnits(unitNames, multipliers); if (unitNames.Contains(settings.Units)) { resultSchema.CurrentUnits = unitNames.IndexOf(settings.Units); } if (overwriteResult) { sfm.SetResultSchema(resultIndex, resultSchema); } else if (firstLoop) { resultIndex = sfm.RegisterResult(resultSchema); firstLoop = false; } else { sfm.SetResultSchema(resultIndex, resultSchema); } sfm.UpdateSpatialFieldPrimitive(index, domainPoints, values, resultIndex); } } } catch (Exception ex) { MessageBox.Show("Failed to measure distance from the point element to the points on Room face.\n" + ex.Message, "FieldOfViewAnalysis", MessageBoxButtons.OK, MessageBoxIcon.Warning); result = false; } return(result); }
public void onInterest(Name prefix, Interest interest, Face face, long interestFilterId, InterestFilter filter) { doCleanup(); Name.Component selectedComponent = null; Blob selectedEncoding = null; // We need to iterate over both arrays. int totalSize = staleTimeCache_.Count + noStaleTimeCache_.Count; for (int i = 0; i < totalSize; ++i) { MemoryContentCache.Content content; if (i < staleTimeCache_.Count) { content = staleTimeCache_[i]; } else { // We have iterated over the first array. Get from the second. content = noStaleTimeCache_[i - staleTimeCache_.Count]; } if (interest.matchesName(content.getName())) { if (interest.getChildSelector() < 0) { // No child selector, so send the first match that we have found. try { face.send(content.getDataEncoding()); } catch (IOException ex) { ILOG.J2CsMapping.Util.Logging.Logger.getLogger(typeof(MemoryContentCache).FullName) .log(ILOG.J2CsMapping.Util.Logging.Level.SEVERE, null, ex); } return; } else { // Update selectedEncoding based on the child selector. Name.Component component; if (content.getName().size() > interest.getName().size()) { component = content.getName().get( interest.getName().size()); } else { component = emptyComponent_; } bool gotBetterMatch = false; if (selectedEncoding == null) { // Save the first match. gotBetterMatch = true; } else { if (interest.getChildSelector() == 0) { // Leftmost child. if (component.compare(selectedComponent) < 0) { gotBetterMatch = true; } } else { // Rightmost child. if (component.compare(selectedComponent) > 0) { gotBetterMatch = true; } } } if (gotBetterMatch) { selectedComponent = component; selectedEncoding = content.getDataEncoding(); } } } } if (selectedEncoding != null) { // We found the leftmost or rightmost child. try { face.send(selectedEncoding); } catch (IOException ex_0) { ILOG.J2CsMapping.Util.Logging.Logger.getLogger(typeof(MemoryContentCache).FullName).log( ILOG.J2CsMapping.Util.Logging.Level.SEVERE, null, ex_0); } } else { // Call the onDataNotFound callback (if defined). Object onDataNotFound = ILOG.J2CsMapping.Collections.Collections.Get(onDataNotFoundForPrefix_, prefix.toUri()); if (onDataNotFound != null) { try { ((OnInterestCallback)onDataNotFound).onInterest(prefix, interest, face, interestFilterId, filter); } catch (Exception ex_1) { logger_.log(ILOG.J2CsMapping.Util.Logging.Level.SEVERE, "Error in onDataNotFound", ex_1); } } } }
Result IExternalCommand.Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { UIDocument uidoc = commandData.Application.ActiveUIDocument; Document doc = uidoc.Document; Level level = doc.ActiveView.GenLevel; View view = doc.ActiveView; FamilySymbol symbol = doc.GetElement(new ElementId(587194)) as FamilySymbol; ElementClassFilter dimfilter = new ElementClassFilter(typeof(Dimension)); ElementOwnerViewFilter viewfilter = new ElementOwnerViewFilter(view.Id); FilteredElementCollector collector = new FilteredElementCollector(doc); collector.WherePasses(dimfilter).WherePasses(viewfilter); List <Dimension> add = new List <Dimension>(); List <Dimension> add2 = new List <Dimension>(); List <DimensionSegmentArray> dimarrayarray = new List <DimensionSegmentArray>(); ReferenceArray referarray = new ReferenceArray(); ReferenceArray referarray2 = new ReferenceArray(); foreach (Element e in collector) { Dimension dim = e as Dimension; if (dim.NumberOfSegments > 1) { dimarrayarray.Add(dim.Segments); add2.Add(dim); } else { add.Add(dim); } } if (add2.Count != 0) //连续尺寸标注 { using (Transaction trans = new Transaction(doc)) { FailureHandlingOptions failureHandlingOptions = trans.GetFailureHandlingOptions(); FailureHandler failureHandler = new FailureHandler(); failureHandlingOptions.SetFailuresPreprocessor(failureHandler); // 这句话是关键 failureHandlingOptions.SetClearAfterRollback(true); trans.SetFailureHandlingOptions(failureHandlingOptions); trans.Start("Start"); ChangeDimensionTypeStyle(add2.First <Dimension>(), doc); for (int b = 0; b < add2.Count; b++) { referarray2 = add2.ElementAt <Dimension>(b).References; foreach (Reference refer in referarray2) { //string re = refer.ElementReferenceType.ToString(); var cu = add2.ElementAt <Dimension>(b).Curve; Dimension dim = add2.ElementAt <Dimension>(b); Line li = cu as Line; //var n = re.GetType().ToString(); Element el = doc.GetElement(refer); Curve curve = null; if (el.Location.GetType() != typeof(LocationCurve)) { if (el.GetType() == typeof(Grid)) { curve = (el as Grid).Curve; } else if ((el as FamilyInstance) is FamilyInstance) { FamilyInstance instance2 = el as FamilyInstance; Element hostelement = instance2.Host; curve = GetLineFromLcPoint(GetSolid(hostelement), instance2); } else if (el.GetType() == typeof(Floor)) { Floor floor = el as Floor; Face face = GetGeometryFace(GetSolid(el)); var test2 = GetCurveFromFloor(face, add2[b].Curve); if (test2.Size < 2) { break; } XYZ[] xYZsn = { test2.get_Item(0).GetEndPoint(0), test2.get_Item(1).GetEndPoint(0) }; Line l3 = Line.CreateBound(test2.get_Item(0).GetEndPoint(0), test2.get_Item(1).GetEndPoint(0)); curve = l3 as Curve; } } else { curve = (el.Location as LocationCurve).Curve; } if (curve == null) { break; } XYZ p0 = li.Project(curve.GetEndPoint(1)) .XYZPoint; if (!symbol.IsActive) { symbol.Activate(); } FamilyInstance instance = doc.Create.NewFamilyInstance(p0, symbol, level, Autodesk.Revit.DB.Structure.StructuralType.UnknownFraming); var l = GetGeometryLine(GetGeometryFace(GetSolid(instance))); double an = GetAngle(li, l); double rotateangle; double e = 1e-12; double a = Math.Round((an - Math.PI / 4), 13); double c = Math.Round(Math.Abs((an - Math.PI * 3 / 2)), 13); if (a != e || c != Math.Round(Math.PI * 3 / 2, 13)) //判断度数,相减做判断 { if (an > Math.PI * 0.5) { rotateangle = 0.75 * Math.PI - an; } else { rotateangle = an + 0.25 * Math.PI; } LocationPoint lp = instance.Location as LocationPoint; if (lp != null) { Line line3 = Line.CreateBound(new XYZ(lp.Point.X, lp.Point.Y, 0), new XYZ(lp.Point.X, lp.Point.Y, lp.Point.Z + 20)); lp.Rotate(line3, rotateangle); XYZ pNew = (instance.Location as LocationPoint).Point; if (p0.X != pNew.X || p0.Y != pNew.Y || p0.Z != pNew.Z) { lp.Point = p0; } //旋转基于平面与原点位置,对照两个位置将旋转后族放置到指定位置 } } } } trans.Commit(); } } //逐点标注 if (add.Count != 0) //普通尺寸标注 { using (Transaction trans = new Transaction(doc)) //将本身的Dimension样式修改未无对角线样式 { FailureHandlingOptions failureHandlingOptions = trans.GetFailureHandlingOptions(); FailureHandler failureHandler = new FailureHandler(); failureHandlingOptions.SetFailuresPreprocessor(failureHandler); // 这句话是关键 failureHandlingOptions.SetClearAfterRollback(true); trans.SetFailureHandlingOptions(failureHandlingOptions); trans.Start("Text"); ChangeDimensionTypeStyle(add.First <Dimension>(), doc); trans.Commit(); } for (int a = 0; a < add.Count; a++) { referarray = add.ElementAt <Dimension>(a).References; if (referarray.Size == 2) { foreach (Reference re in referarray) { var cu = add.ElementAt <Dimension>(a).Curve; Dimension dim = add.ElementAt <Dimension>(a); Line li = cu as Line; //var n = re.GetType().ToString(); Element el = doc.GetElement(re); Curve curve = null; using (Transaction test = new Transaction(doc, "change")) { FailureHandlingOptions failureHandlingOptions = test.GetFailureHandlingOptions(); FailureHandler failureHandler = new FailureHandler(); failureHandlingOptions.SetFailuresPreprocessor(failureHandler); // 这句话是关键 failureHandlingOptions.SetClearAfterRollback(true); test.SetFailureHandlingOptions(failureHandlingOptions); test.Start(); if (el.Location.GetType() != typeof(LocationCurve)) { if (el.GetType() == typeof(Grid)) { curve = (el as Grid).Curve; } else if ((el as FamilyInstance) is FamilyInstance) { FamilyInstance instance2 = el as FamilyInstance; Element hostelement = instance2.Host; curve = GetLineFromLcPoint(GetSolid(hostelement), instance2); } else if (el.GetType() == typeof(Floor)) { Floor floor = el as Floor; Face face = GetGeometryFace(GetSolid(el)); var test2 = GetCurveFromFloor(face, add[a].Curve); if (test2.Size < 2) { break; } XYZ[] xYZsn = { test2.get_Item(0).GetEndPoint(0), test2.get_Item(1).GetEndPoint(0) }; Line l = Line.CreateBound(test2.get_Item(0).GetEndPoint(0), test2.get_Item(1).GetEndPoint(0)); curve = l as Curve; } if (curve == null) { break; } XYZ[] xYZs = { curve.GetEndPoint(0), curve.GetEndPoint(1) }; foreach (XYZ xyz in xYZs) { XYZ p0 = li.Project(xyz).XYZPoint; if (!symbol.IsActive) { symbol.Activate(); } FamilyInstance instance = doc.Create.NewFamilyInstance(p0, symbol, level, Autodesk.Revit.DB.Structure.StructuralType.UnknownFraming); var l = GetGeometryLine(GetGeometryFace(GetSolid(instance))); double an = GetAngle(li, l); if (an != Math.PI / 4 || an != Math.PI * 3 / 2) { LocationPoint lp = instance.Location as LocationPoint; if (lp != null) { Line line3 = Line.CreateBound(new XYZ(lp.Point.X, lp.Point.Y, 0), new XYZ(lp.Point.X, lp.Point.Y, lp.Point.Z + 20)); lp.Rotate(line3, 0.25 * Math.PI + (Math.PI + an)); XYZ pNew = (instance.Location as LocationPoint).Point; if (p0.X != pNew.X || p0.Y != pNew.Y || p0.Z != pNew.Z) { lp.Point = p0; } //旋转基于平面与原点位置,对照两个位置将旋转后族放置到指定位置 } } } } else { curve = (el.Location as LocationCurve).Curve; if (doc.GetElement(referarray.get_Item(0)).Id == doc.GetElement(referarray.get_Item(1)).Id) { var cu4 = add.ElementAt <Dimension>(a).Curve; Dimension dim4 = add.ElementAt <Dimension>(a); Line li4 = cu as Line; //var n = re.GetType().ToString(); Element el4 = doc.GetElement(referarray.get_Item(0)); Curve curve4 = (el4.Location as LocationCurve).Curve; XYZ[] xyzs2 = { curve4.GetEndPoint(0), curve4.GetEndPoint(1) }; foreach (XYZ xyz in xyzs2) { XYZ p0 = li.Project(xyz).XYZPoint; if (!symbol.IsActive) { symbol.Activate(); } FamilyInstance instance = doc.Create.NewFamilyInstance(p0, symbol, level, Autodesk.Revit.DB.Structure.StructuralType.UnknownFraming); var l = GetGeometryLine(GetGeometryFace(GetSolid(instance))); double an = GetAngle(li, l); if (an != Math.PI / 4 || an != Math.PI * 3 / 2) { LocationPoint lp = instance.Location as LocationPoint; if (lp != null) { Line line3 = Line.CreateBound(new XYZ(lp.Point.X, lp.Point.Y, 0), new XYZ(lp.Point.X, lp.Point.Y, lp.Point.Z + 20)); lp.Rotate(line3, 0.25 * Math.PI + (Math.PI + an)); XYZ pNew = (instance.Location as LocationPoint).Point; if (p0.X != pNew.X || p0.Y != pNew.Y || p0.Z != pNew.Z) { lp.Point = p0; } //旋转基于平面与原点位置,对照两个位置将旋转后族放置到指定位置 } } } } else { foreach (Reference refer in referarray) { //string re = refer.ElementReferenceType.ToString(); var cu3 = add.ElementAt <Dimension>(a).Curve; Dimension dim3 = add.ElementAt <Dimension>(a); Line li3 = cu as Line; //var n = re.GetType().ToString(); Element el3 = doc.GetElement(refer); Curve curve3 = null; if (el3.Location.GetType() != typeof(LocationCurve)) { if (el3.GetType() == typeof(Grid)) { curve3 = (el3 as Grid).Curve; } else if ((el3 as FamilyInstance) is FamilyInstance) { FamilyInstance instance3 = el3 as FamilyInstance; Element hostelement = instance3.Host; curve3 = GetLineFromLcPoint(GetSolid(hostelement), instance3); } else if (el3.GetType() == typeof(Floor)) { Floor floor = el3 as Floor; Face face = GetGeometryFace(GetSolid(el3)); var test2 = GetCurveFromFloor(face, add2[a].Curve); if (test2.Size < 2) { break; } XYZ[] xYZsn = { test2.get_Item(0).GetEndPoint(0), test2.get_Item(1).GetEndPoint(0) }; Line l4 = Line.CreateBound(test2.get_Item(0).GetEndPoint(0), test2.get_Item(1).GetEndPoint(0)); curve3 = l4 as Curve; } } else { curve3 = (el3.Location as LocationCurve).Curve; } if (curve3 == null) { break; } XYZ p0 = li3.Project(curve.GetEndPoint(1)) .XYZPoint; if (!symbol.IsActive) { symbol.Activate(); } FamilyInstance instance = doc.Create.NewFamilyInstance(p0, symbol, level, Autodesk.Revit.DB.Structure.StructuralType.UnknownFraming); var l = GetGeometryLine(GetGeometryFace(GetSolid(instance))); double an = GetAngle(li, l); if (an != Math.PI / 4 || an != Math.PI * 3 / 2) { LocationPoint lp = instance.Location as LocationPoint; if (lp != null) { Line line3 = Line.CreateBound(new XYZ(lp.Point.X, lp.Point.Y, 0), new XYZ(lp.Point.X, lp.Point.Y, lp.Point.Z + 20)); lp.Rotate(line3, 0.25 * Math.PI + (Math.PI + an)); XYZ pNew = (instance.Location as LocationPoint).Point; if (p0.X != pNew.X || p0.Y != pNew.Y || p0.Z != pNew.Z) { lp.Point = p0; } //旋转基于平面与原点位置,对照两个位置将旋转后族放置到指定位置 } } } } } test.Commit(); } } } } } //连续标注 return(Result.Succeeded); }
/// <inheritdoc/> public override Bounds RebuildMesh(ProBuilderMesh mesh, Vector3 size, Quaternion rotation) { var meshSize = Math.Abs(size); meshSize.y = meshSize.y == 0 ? 2f * Mathf.Epsilon : meshSize.y; var baseY = new Vector3(0, meshSize.y / 2f, 0); meshSize.y *= 2f; Vector3[] template = new Vector3[6] { Vector3.Scale(new Vector3(-.5f, 0f, -.5f), meshSize) - baseY, Vector3.Scale(new Vector3(.5f, 0f, -.5f), meshSize) - baseY, Vector3.Scale(new Vector3(0f, .5f, -.5f), meshSize) - baseY, Vector3.Scale(new Vector3(-.5f, 0f, .5f), meshSize) - baseY, Vector3.Scale(new Vector3(0.5f, 0f, .5f), meshSize) - baseY, Vector3.Scale(new Vector3(0f, .5f, .5f), meshSize) - baseY }; Vector3[] v = new Vector3[18] { template[0], // 0 front template[1], // 1 template[2], // 2 template[1], // 3 right side template[4], // 4 template[2], // 5 template[5], // 6 template[4], // 7 back side template[3], // 8 template[5], // 9 template[3], // 10 left side template[0], // 11 template[5], // 12 template[2], // 13 template[0], // 14 // bottom template[1], // 15 template[3], // 16 template[4] // 17 }; Face[] f = new Face[5] { new Face(new int[3] { 2, 1, 0 }), // x new Face(new int[6] { 5, 4, 3, 5, 6, 4 }), // x new Face(new int[3] { 9, 8, 7 }), new Face(new int[6] { 12, 11, 10, 12, 13, 11 }), new Face(new int[6] { 14, 15, 16, 15, 17, 16 }) }; var sizeSigns = Math.Sign(size); for (int i = 0; i < v.Length; i++) { v[i] = Vector3.Scale(rotation * v[i], sizeSigns); } var sizeSign = Mathf.Sign(size.x) * Mathf.Sign(size.y) * Mathf.Sign(size.z); if (sizeSign < 0) { foreach (var face in f) { face.Reverse(); } } mesh.RebuildWithPositionsAndFaces(v, f); return(mesh.mesh.bounds); }
public void onInterest(Name localPrefix, Interest localInterest, Face localFace, long localInterestFilterId, InterestFilter localFilter) { outer_MemoryContentCache.storePendingInterest(localInterest, localFace); }
// Returns a string that describes the given face. private string FaceDescription(Face face) { StringBuilder sb = new StringBuilder(); sb.Append("Face: "); // Add the gender, age, and smile. sb.Append(face.FaceAttributes.Gender); sb.Append(", "); sb.Append(face.FaceAttributes.Age); sb.Append(", "); sb.Append(String.Format("smile {0:F1}%, ", face.FaceAttributes.Smile * 100)); // Add the emotions. Display all emotions over 10%. sb.Append("Emotion: "); EmotionScores emotionScores = face.FaceAttributes.Emotion; if (emotionScores.Anger >= 0.1f) { sb.Append(String.Format("anger {0:F1}%, ", emotionScores.Anger * 100)); } if (emotionScores.Contempt >= 0.1f) { sb.Append(String.Format("contempt {0:F1}%, ", emotionScores.Contempt * 100)); } if (emotionScores.Disgust >= 0.1f) { sb.Append(String.Format("disgust {0:F1}%, ", emotionScores.Disgust * 100)); } if (emotionScores.Fear >= 0.1f) { sb.Append(String.Format("fear {0:F1}%, ", emotionScores.Fear * 100)); } if (emotionScores.Happiness >= 0.1f) { sb.Append(String.Format("happiness {0:F1}%, ", emotionScores.Happiness * 100)); } if (emotionScores.Neutral >= 0.1f) { sb.Append(String.Format("neutral {0:F1}%, ", emotionScores.Neutral * 100)); } if (emotionScores.Sadness >= 0.1f) { sb.Append(String.Format("sadness {0:F1}%, ", emotionScores.Sadness * 100)); } if (emotionScores.Surprise >= 0.1f) { sb.Append(String.Format("surprise {0:F1}%, ", emotionScores.Surprise * 100)); } // Add glasses. sb.Append(face.FaceAttributes.Glasses); sb.Append(", "); // Add hair. sb.Append("Hair: "); // Display baldness confidence if over 1%. if (face.FaceAttributes.Hair.Bald >= 0.01f) { sb.Append(String.Format("bald {0:F1}% ", face.FaceAttributes.Hair.Bald * 100)); } // Display all hair color attributes over 10%. HairColor[] hairColors = face.FaceAttributes.Hair.HairColor; foreach (HairColor hairColor in hairColors) { if (hairColor.Confidence >= 0.1f) { sb.Append(hairColor.Color.ToString()); sb.Append(String.Format(" {0:F1}% ", hairColor.Confidence * 100)); } } // Return the built string. return(sb.ToString()); }
/// <summary> /// Store an interest from an OnInterest callback in the internal pending /// interest table (normally because there is no Data packet available yet to /// satisfy the interest). add(data) will check if the added Data packet /// satisfies any pending interest and send it through the face. /// </summary> /// /// <param name="interest"></param> /// <param name="face"></param> public void storePendingInterest(Interest interest, Face face) { ILOG.J2CsMapping.Collections.Collections.Add(pendingInterestTable_, new MemoryContentCache.PendingInterest(interest, face)); }
/// <summary> /// Start the search for the horizon. /// /// The search is a DFS search that searches neighboring /// triangles in a counter-clockwise fashion. When it find a /// neighbor which is not lit, that edge will be a line on /// the horizon. If the search always proceeds /// counter-clockwise, the edges of the horizon will be /// found in counter-clockwise order. /// /// The heart of the search can be found in the recursive /// SearchHorizon() method, but the the first iteration of /// the search is special, because it has to visit three /// neighbors (all the neighbors of the initial triangle), /// while the rest of the search only has to visit two /// (because one of them has already been visited, the one /// you came from). /// </summary> void FindHorizon(List <Vector3> points, Vector3 point, int fi, Face face) { // TODO should I use epsilon in the PointFaceDistance comparisons? litFaces.Clear(); horizon.Clear(); litFaces.Add(fi); Assert(PointFaceDistance(point, points[face.Vertex0], face) > 0.0f); // For the rest of the recursive search calls, we first // check if the triangle has already been visited and is // part of litFaces. However, in this first call we can // skip that because we know it can't possibly have been // visited yet, since the only thing in litFaces is the // current triangle. { var oppositeFace = faces[face.Opposite0]; var dist = PointFaceDistance( point, points[oppositeFace.Vertex0], oppositeFace); if (dist <= 0.0f) { horizon.Add(new HorizonEdge { Face = face.Opposite0, Edge0 = face.Vertex1, Edge1 = face.Vertex2, }); } else { SearchHorizon(points, point, fi, face.Opposite0, oppositeFace); } } if (!litFaces.Contains(face.Opposite1)) { var oppositeFace = faces[face.Opposite1]; var dist = PointFaceDistance( point, points[oppositeFace.Vertex0], oppositeFace); if (dist <= 0.0f) { horizon.Add(new HorizonEdge { Face = face.Opposite1, Edge0 = face.Vertex2, Edge1 = face.Vertex0, }); } else { SearchHorizon(points, point, fi, face.Opposite1, oppositeFace); } } if (!litFaces.Contains(face.Opposite2)) { var oppositeFace = faces[face.Opposite2]; var dist = PointFaceDistance( point, points[oppositeFace.Vertex0], oppositeFace); if (dist <= 0.0f) { horizon.Add(new HorizonEdge { Face = face.Opposite2, Edge0 = face.Vertex0, Edge1 = face.Vertex1, }); } else { SearchHorizon(points, point, fi, face.Opposite2, oppositeFace); } } }
// Displays the image and calls Detect Faces. private async void BrowseButton_Click(object sender, RoutedEventArgs e) { // Get the image file to scan from the user. var openDlg = new Microsoft.Win32.OpenFileDialog(); openDlg.Filter = "JPEG Image(*.jpg)|*.jpg"; bool?result = openDlg.ShowDialog(this); // Return if canceled. if (!(bool)result) { return; } // Display the image file. string filePath = openDlg.FileName; Uri fileUri = new Uri(filePath); BitmapImage bitmapSource = new BitmapImage(); bitmapSource.BeginInit(); bitmapSource.CacheOption = BitmapCacheOption.None; bitmapSource.UriSource = fileUri; bitmapSource.EndInit(); FacePhoto.Source = bitmapSource; // Detect any faces in the image. Title = "Detecting..."; faces = await UploadAndDetectFaces(filePath); Title = String.Format("Detection Finished. {0} face(s) detected", faces.Length); if (faces.Length > 0) { // Prepare to draw rectangles around the faces. DrawingVisual visual = new DrawingVisual(); DrawingContext drawingContext = visual.RenderOpen(); drawingContext.DrawImage(bitmapSource, new Rect(0, 0, bitmapSource.Width, bitmapSource.Height)); double dpi = bitmapSource.DpiX; resizeFactor = 96 / dpi; faceDescriptions = new String[faces.Length]; for (int i = 0; i < faces.Length; ++i) { Face face = faces[i]; // Draw a rectangle on the face. drawingContext.DrawRectangle( Brushes.Transparent, new Pen(Brushes.Red, 2), new Rect( face.FaceRectangle.Left * resizeFactor, face.FaceRectangle.Top * resizeFactor, face.FaceRectangle.Width * resizeFactor, face.FaceRectangle.Height * resizeFactor ) ); // Store the face description. faceDescriptions[i] = FaceDescription(face); } drawingContext.Close(); // Display the image with the rectangle around the face. RenderTargetBitmap faceWithRectBitmap = new RenderTargetBitmap( (int)(bitmapSource.PixelWidth * resizeFactor), (int)(bitmapSource.PixelHeight * resizeFactor), 96, 96, PixelFormats.Pbgra32); faceWithRectBitmap.Render(visual); FacePhoto.Source = faceWithRectBitmap; // Set the status bar text. faceDescriptionStatusBar.Text = "Place the mouse pointer over a face to see the face description."; } }
/// <summary> /// Does face f have a face with vertexes e0 and e1? Used /// only for debugging. /// </summary> bool HasEdge(Face f, int e0, int e1) { return((f.Vertex0 == e0 && f.Vertex1 == e1) || (f.Vertex1 == e0 && f.Vertex2 == e1) || (f.Vertex2 == e0 && f.Vertex0 == e1)); }
/// <summary> /// Recursively search to find the horizon or lit set. /// </summary> void SearchHorizon(List <Vector3> points, Vector3 point, int prevFaceIndex, int faceCount, Face face) { Assert(prevFaceIndex >= 0); Assert(litFaces.Contains(prevFaceIndex)); Assert(!litFaces.Contains(faceCount)); Assert(faces[faceCount].Equals(face)); litFaces.Add(faceCount); // Use prevFaceIndex to determine what the next face to // search will be, and what edges we need to cross to get // there. It's important that the search proceeds in // counter-clockwise order from the previous face. int nextFaceIndex0; int nextFaceIndex1; int edge0; int edge1; int edge2; if (prevFaceIndex == face.Opposite0) { nextFaceIndex0 = face.Opposite1; nextFaceIndex1 = face.Opposite2; edge0 = face.Vertex2; edge1 = face.Vertex0; edge2 = face.Vertex1; } else if (prevFaceIndex == face.Opposite1) { nextFaceIndex0 = face.Opposite2; nextFaceIndex1 = face.Opposite0; edge0 = face.Vertex0; edge1 = face.Vertex1; edge2 = face.Vertex2; } else { Assert(prevFaceIndex == face.Opposite2); nextFaceIndex0 = face.Opposite0; nextFaceIndex1 = face.Opposite1; edge0 = face.Vertex1; edge1 = face.Vertex2; edge2 = face.Vertex0; } if (!litFaces.Contains(nextFaceIndex0)) { var oppositeFace = faces[nextFaceIndex0]; var dist = PointFaceDistance( point, points[oppositeFace.Vertex0], oppositeFace); if (dist <= 0.0f) { horizon.Add(new HorizonEdge { Face = nextFaceIndex0, Edge0 = edge0, Edge1 = edge1, }); } else { SearchHorizon(points, point, faceCount, nextFaceIndex0, oppositeFace); } } if (!litFaces.Contains(nextFaceIndex1)) { var oppositeFace = faces[nextFaceIndex1]; var dist = PointFaceDistance( point, points[oppositeFace.Vertex0], oppositeFace); if (dist <= 0.0f) { horizon.Add(new HorizonEdge { Face = nextFaceIndex1, Edge0 = edge1, Edge1 = edge2, }); } else { SearchHorizon(points, point, faceCount, nextFaceIndex1, oppositeFace); } } }
public void rebarStirrupLayout_Form(UIDocument uiDoc) { Document doc = uiDoc.Document; double factor = 4; double delta_1 = 50 / 304.8; double pitch_1 = 150 / 304.8; double pitch_2 = 300 / 304.8; double delta_3 = 50 / 304.8; double pitch_3 = 100 / 304.8; int N3 = 5; double myConvertFactor = 304.8; bool inputSuccess = false; while (!inputSuccess) { using (var myInputFormSetting = new SettingDialog()) { myInputFormSetting.ShowDialog(); factor = Convert.ToDouble(myInputFormSetting.factorTb.Text); delta_1 = Convert.ToDouble(myInputFormSetting.delta_1Tb.Text) / myConvertFactor; pitch_1 = Convert.ToDouble(myInputFormSetting.pitch_1Tb.Text) / myConvertFactor; pitch_2 = Convert.ToDouble(myInputFormSetting.pitch_2Tb.Text) / myConvertFactor; delta_3 = Convert.ToDouble(myInputFormSetting.delta_3Tb.Text) / myConvertFactor; pitch_3 = Convert.ToDouble(myInputFormSetting.pitch_3Tb.Text) / myConvertFactor; N3 = Convert.ToInt32(myInputFormSetting.n3Tb.Text); //if the user hits cancel just drop out of macro if (myInputFormSetting.DialogResult == System.Windows.Forms.DialogResult.Cancel) { return; } { //else do all this :) myInputFormSetting.Close(); } if (myInputFormSetting.DialogResult == System.Windows.Forms.DialogResult.OK) { //else do all this :) inputSuccess = true; myInputFormSetting.Close(); } } } // Pick Rebar List <int> myListIdCategoryRebar = new List <int>(); myListIdCategoryRebar.Add((int)BuiltInCategory.OST_Rebar); // Select first Element (ex beam) Reference myRefRebar = uiDoc.Selection.PickObject(ObjectType.Element, new FilterByIdCategory(myListIdCategoryRebar), "Pick a Rebar..."); //Get rebar from ref Rebar myRebar = doc.GetElement(myRefRebar) as Rebar; //Set rebar single // using (Transaction myTrans = new Transaction(doc,"SET FIRST REBAR AS SINGLE")) // // { // myTrans.Start(); // myRebar.GetShapeDrivenAccessor().SetLayoutAsSingle(); // myTrans.Commit(); // } Element myBeam = doc.GetElement(myRebar.GetHostId()); //Get location curve of beam LocationCurve lc = myBeam.Location as LocationCurve; Line line = lc.Curve as Line; //Get vector of location cuver beam XYZ p1 = line.GetEndPoint(0); XYZ q = line.GetEndPoint(1); XYZ v = q - p1; // Vector equation of line XYZ p = p1 - 0.1 * v; //Set current Beam be Joined setBeJoined(doc, myBeam); while (true) { //Pick Face end List <Reference> myListRef = uiDoc.Selection.PickObjects(ObjectType.Face) as List <Reference>; List <Face> myListFacePicked = new List <Face>(); foreach (Reference myRef in myListRef) { Element E = doc.GetElement(myRef); GeometryObject myGeoObj = E.GetGeometryObjectFromReference(myRef); Face myPickedFace = myGeoObj as Face; myListFacePicked.Add(myPickedFace); } if (myListFacePicked.Count != 2 && myListFacePicked.Count != 4) { TaskDialog.Show("Error!", "Chua ho tro lua chon: " + myListFacePicked.Count() + " mat, Chon 2 hoac 4 mat"); continue; } else { string caseDistributionRebar = "TH2: Co dam o giua"; List <double> myListSpace = new List <double>() { pitch_1, pitch_2, pitch_3, pitch_3, pitch_2, pitch_1 }; if (myListFacePicked.Count == 2) { myListSpace = new List <double>() { pitch_1, pitch_2, pitch_1, pitch_2, pitch_2, pitch_1 }; caseDistributionRebar = "TH1: Khong co dam o giua"; } TaskDialog.Show("Info", caseDistributionRebar); // List of boundaries faces List <double> myListEndPointDis = getAndSortDisOfEndFaces(myListFacePicked, p); myListEndPointDis.Sort(); Dictionary <double, int> myDicDisNumDetail = detailListDistance_Update(myListEndPointDis, factor, delta_1, pitch_1, pitch_2, delta_3, pitch_3, N3); List <ElementId> myListRebarCopyId = copyRebarByDistance2_Update(doc, myRebar, myDicDisNumDetail); List <double> myDistances = myDicDisNumDetail.Keys.ToList(); myDistances.Sort(); List <int> myListNum = new List <int>(); foreach (double key in myDistances) { myListNum.Add(myDicDisNumDetail[key]); } //Layout // using transcation (edit DB) for (int i = 0; i < myListRebarCopyId.Count(); i++) { using (Transaction myTrans = new Transaction(doc, "CopyElementByCoordinate")) { myTrans.Start(); ElementId rebarId = myListRebarCopyId[i]; Rebar myRebarI = doc.GetElement(rebarId) as Rebar; if (myListNum[i] < -1) { myRebarI.GetShapeDrivenAccessor().SetLayoutAsNumberWithSpacing((myListNum[i]) * -1, myListSpace[i], true, true, true); } if (myListNum[i] == -1) { myRebarI.GetShapeDrivenAccessor().SetLayoutAsSingle(); } if (myListNum[i] == 0) { myRebarI.GetShapeDrivenAccessor().SetLayoutAsSingle(); } if (myListNum[i] == 1) { myRebarI.GetShapeDrivenAccessor().SetLayoutAsSingle(); } if (myListNum[i] > 1) { myRebarI.GetShapeDrivenAccessor().SetLayoutAsNumberWithSpacing(myListNum[i], myListSpace[i], false, true, true); } myTrans.Commit(); } } //delete element using (Transaction myTrans = new Transaction(doc, "Delete First ReBar")) { myTrans.Start(); //doc.Delete(myRebar.Id); myTrans.Commit(); } } } }
/// <summary> /// Create initial seed hull. /// </summary> void GenerateInitialHull(List <Vector3> points) { // Find points suitable for use as the seed hull. Some // varieties of this algorithm pick extreme points here, // but I'm not convinced you gain all that much from that. // Currently what it does is just find the first four // points that are not coplanar. int b0, b1, b2, b3; FindInitialHullIndices(points, out b0, out b1, out b2, out b3); var v0 = points[b0]; var v1 = points[b1]; var v2 = points[b2]; var v3 = points[b3]; var above = Dot(v3 - v1, Cross(v1 - v0, v2 - v0)) > 0.0f; // Create the faces of the seed hull. You need to draw a // diagram here, otherwise it's impossible to know what's // going on :) // Basically: there are two different possible // start-tetrahedrons, depending on whether the fourth // point is above or below the base triangle. If you draw // a tetrahedron with these coordinates (in a right-handed // coordinate-system): // b0 = (0,0,0) // b1 = (1,0,0) // b2 = (0,1,0) // b3 = (0,0,1) // you can see the first case (set b3 = (0,0,-1) for the // second case). The faces are added with the proper // references to the faces opposite each vertex faceCount = 0; if (above) { faces[faceCount++] = new Face(b0, b2, b1, 3, 1, 2, Normal(points[b0], points[b2], points[b1])); faces[faceCount++] = new Face(b0, b1, b3, 3, 2, 0, Normal(points[b0], points[b1], points[b3])); faces[faceCount++] = new Face(b0, b3, b2, 3, 0, 1, Normal(points[b0], points[b3], points[b2])); faces[faceCount++] = new Face(b1, b2, b3, 2, 1, 0, Normal(points[b1], points[b2], points[b3])); } else { faces[faceCount++] = new Face(b0, b1, b2, 3, 2, 1, Normal(points[b0], points[b1], points[b2])); faces[faceCount++] = new Face(b0, b3, b1, 3, 0, 2, Normal(points[b0], points[b3], points[b1])); faces[faceCount++] = new Face(b0, b2, b3, 3, 1, 0, Normal(points[b0], points[b2], points[b3])); faces[faceCount++] = new Face(b1, b3, b2, 2, 0, 1, Normal(points[b1], points[b3], points[b2])); } VerifyFaces(points); // Create the openSet. Add all points except the points of // the seed hull. for (int i = 0; i < points.Count; i++) { if (i == b0 || i == b1 || i == b2 || i == b3) { continue; } openSet.Add(new PointFace(i, UNASSIGNED, 0.0f)); } // Add the seed hull verts to the tail of the list. openSet.Add(new PointFace(b0, INSIDE, float.NaN)); openSet.Add(new PointFace(b1, INSIDE, float.NaN)); openSet.Add(new PointFace(b2, INSIDE, float.NaN)); openSet.Add(new PointFace(b3, INSIDE, float.NaN)); // Set the openSetTail value. Last item in the array is // openSet.Count - 1, but four of the points (the verts of // the seed hull) are part of the closed set, so move // openSetTail to just before those. openSetTail = openSet.Count - 5; Assert(openSet.Count == points.Count); // Assign all points of the open set. This does basically // the same thing as ReassignPoints() for (int i = 0; i <= openSetTail; i++) { Assert(openSet[i].Face == UNASSIGNED); Assert(openSet[openSetTail].Face == UNASSIGNED); Assert(openSet[openSetTail + 1].Face == INSIDE); var assigned = false; var fp = openSet[i]; Assert(faces.Count == 4); Assert(faces.Count == faceCount); for (int j = 0; j < 4; j++) { Assert(faces.ContainsKey(j)); var face = faces[j]; var dist = PointFaceDistance(points[fp.Point], points[face.Vertex0], face); if (dist > 0) { fp.Face = j; fp.Distance = dist; openSet[i] = fp; assigned = true; break; } } if (!assigned) { // Point is inside fp.Face = INSIDE; fp.Distance = float.NaN; // Point is inside seed hull: swap point with // tail, and move openSetTail back. We also have // to decrement i, because there's a new item at // openSet[i], and we need to process it next iteration openSet[i] = openSet[openSetTail]; openSet[openSetTail] = fp; openSetTail -= 1; i -= 1; } } VerifyOpenSet(points); }
internal void RemoveChildFace(Face child) { childFaces.Remove(child); }
float PointFaceDistance(Vector3 point, Vector3 pointOnFace, Face face) { return(Dot(face.Normal, point - pointOnFace)); }
public FaceEnclosure GetEnclosure(int imageHeight, int imageWidth, int frameHeight, int frameWidth, Face face) { var widthRatio = (double)frameWidth / imageWidth; var heightRatio = (double)frameHeight / imageHeight; var enclosure = new FaceEnclosure { Center = new Point { X = face.Center.X * widthRatio, Y = face.Center.Y * heightRatio }, Width = face.Width / 100 * imageWidth * widthRatio, Height = face.Height / 100 * imageHeight * heightRatio }; return(enclosure); }
void MainSteeringBehaviors() { ResetOrientation(); switch (choiceOfBehavior) { case steeringBehaviors.Seek: Seek seek = new Seek(); seek.character = this; seek.target = newTarget; SteeringOutput seeking = seek.getSteering(); if (seeking != null) { linear += seeking.linear * Time.deltaTime; angular += seeking.angular * Time.deltaTime; } break; case steeringBehaviors.Flee: Flee flee = new Flee(); flee.character = this; flee.target = newTarget; SteeringOutput fleeing = flee.getSteering(); if (fleeing != null) { linear += fleeing.linear * Time.deltaTime; angular += fleeing.angular * Time.deltaTime; } break; case steeringBehaviors.Align: Align align = new Align(); align.character = this; align.target = newTarget; SteeringOutput aligning = align.getSteering(); if (aligning != null) { linear += aligning.linear * Time.deltaTime; angular += aligning.angular * Time.deltaTime; } break; case steeringBehaviors.Face: Face face = new Face(); face.character = this; face.target = newTarget; SteeringOutput facing = face.getSteering(); if (facing != null) { linear += facing.linear * Time.deltaTime; angular += facing.angular * Time.deltaTime; } break; case steeringBehaviors.LookWhereGoing: LookWhereGoing look = new LookWhereGoing(); look.character = this; look.target = newTarget; SteeringOutput looking = look.getSteering(); if (looking != null) { linear += looking.linear * Time.deltaTime; angular += looking.angular * Time.deltaTime; } break; case steeringBehaviors.Arrive: Arrive arrive = new Arrive(); arrive.character = this; arrive.target = newTarget; SteeringOutput arriving = arrive.getSteering(); if (arriving != null) { linear += arriving.linear * Time.deltaTime; angular += arriving.angular * Time.deltaTime; } break; case steeringBehaviors.PathFollow: follow.character = this; follow.path = path; SteeringOutput following = follow.getSteering(); if (following != null) { linear += following.linear * Time.deltaTime; } break; case steeringBehaviors.Pursue: Pursue pursue = new Pursue(); pursue.target = newTarget; pursue.character = this; SteeringOutput pursuing = pursue.getSteering(); if (pursuing != null) { linear += pursuing.linear * Time.deltaTime; angular += pursuing.angular * Time.deltaTime; } break; case steeringBehaviors.Separate: Separate separate = new Separate(); separate.character = this; separate.targets = targets; SteeringOutput separating = separate.getSteering(); if (separating != null) { linear += separating.linear * Time.deltaTime; angular += separating.angular * Time.deltaTime; } break; } }
void _SculptMesh(List <List <Coord> > rows, SculptType sculptType, bool viewerMode, bool mirror, bool invert) { coords = new List <Coord> (); faces = new List <Face> (); normals = new List <Coord> (); uvs = new List <UVCoord> (); sculptType = (SculptType)(((int)sculptType) & 0x07); if (mirror) { invert = !invert; } viewerFaces = new List <ViewerFace> (); int width = rows [0].Count; int p1, p2, p3, p4; int imageX, imageY; if (sculptType != SculptType.plane) { if (rows.Count % 2 == 0) { foreach (List <Coord> t in rows) { t.Add(t [0]); } } else { int lastIndex = rows [0].Count - 1; foreach (List <Coord> t in rows) { t [0] = t [lastIndex]; } } } Coord topPole = rows [0] [width / 2]; Coord bottomPole = rows [rows.Count - 1] [width / 2]; if (sculptType == SculptType.sphere) { if (rows.Count % 2 == 0) { int count = rows [0].Count; List <Coord> topPoleRow = new List <Coord> (count); List <Coord> bottomPoleRow = new List <Coord> (count); for (int i = 0; i < count; i++) { topPoleRow.Add(topPole); bottomPoleRow.Add(bottomPole); } rows.Insert(0, topPoleRow); rows.Add(bottomPoleRow); } else { int count = rows [0].Count; List <Coord> topPoleRow = rows [0]; List <Coord> bottomPoleRow = rows [rows.Count - 1]; for (int i = 0; i < count; i++) { topPoleRow [i] = topPole; bottomPoleRow [i] = bottomPole; } } } if (sculptType == SculptType.torus) { rows.Add(rows [0]); } int coordsDown = rows.Count; int coordsAcross = rows [0].Count; float widthUnit = 1.0f / (coordsAcross - 1); float heightUnit = 1.0f / (coordsDown - 1); for (imageY = 0; imageY < coordsDown; imageY++) { int rowOffset = imageY * coordsAcross; for (imageX = 0; imageX < coordsAcross; imageX++) { /* * p1-----p2 * | \ f2 | * | \ | * | f1 \| * p3-----p4 */ p4 = rowOffset + imageX; p3 = p4 - 1; p2 = p4 - coordsAcross; p1 = p3 - coordsAcross; coords.Add(rows [imageY] [imageX]); if (viewerMode) { normals.Add(new Coord()); uvs.Add(new UVCoord(widthUnit * imageX, heightUnit * imageY)); } if (imageY > 0 && imageX > 0) { Face f1, f2; if (viewerMode) { if (invert) { f1 = new Face(p1, p4, p3, p1, p4, p3) { uv1 = p1, uv2 = p4, uv3 = p3 }; f2 = new Face(p1, p2, p4, p1, p2, p4) { uv1 = p1, uv2 = p2, uv3 = p4 }; } else { f1 = new Face(p1, p3, p4, p1, p3, p4) { uv1 = p1, uv2 = p3, uv3 = p4 }; f2 = new Face(p1, p4, p2, p1, p4, p2) { uv1 = p1, uv2 = p4, uv3 = p2 }; } } else { if (invert) { f1 = new Face(p1, p4, p3); f2 = new Face(p1, p2, p4); } else { f1 = new Face(p1, p3, p4); f2 = new Face(p1, p4, p2); } } faces.Add(f1); faces.Add(f2); } } } if (viewerMode) { calcVertexNormals(sculptType, coordsAcross, coordsDown); } }
internal void AddChildFace(Face child) { childFaces.Add(child); }