Example #1
0
        public Action GetSaveCommand()
        {
            return () =>
            {
                var d = (AblGeometryData)_fileHandler.Read(_vProject.ProjectDir);
                var box = new Vertice[8];
                for (var i = 0; i < 8; i++) box[i] = new Vertice(0, 0, 0);
                box[1].X = _model.Width;
                box[2].X = _model.Width;
                box[5].X = _model.Width;
                box[6].X = _model.Width;

                box[2].Y = _model.Length;
                box[3].Y = _model.Length;
                box[6].Y = _model.Length;
                box[7].Y = _model.Length;

                box[4].Z = _model.Height;
                box[5].Z = _model.Height;
                box[6].Z = _model.Height;
                box[7].Z = _model.Height;

                d.BlockMesh.vertices.Clear();
                d.BlockMesh.vertices.AddRange(box);

                d.TopoSet.X2 = _model.Width + 0.1m;
                d.TopoSet.Y2 = _model.Length + 0.1m;
                d.TopoSet.Z2 = _model.Height + 0.1m;

                _fileHandler.Write(_vProject.ProjectDir, d);
                _model.AcceptChanges();
            };
        }
Example #2
0
 private static int CompareDinosByLength(Vertice x, Vertice y)
 {
     if (x == null) { if (y == null) { return 0; } else { return -1; } }
     else
     {
       if (y == null) { return 1; }
       else
       {
     if (x.Sequece > y.Sequece) return 1;
     if (x.Sequece == y.Sequece) return 0;
     if (x.Sequece < y.Sequece) return -1;
     else return 0;
       }
     }
 }
Example #3
0
    public List <Vertice> Perturbator(List <Vertice> vertices)
    {
        List <Vertice> Result = new List <Vertice>(vertices);
        float          alpha  = 0;

        for (int i = 0; i < vertices.Count; i++)
        {
            alpha = (1f / 9f) * (4f - 2f * Mathf.Cos((2f * Mathf.PI) / vertices[i].Neighbours.Count));

            Vector3 sum = new Vector3(0, 0, 0);
            for (int j = 0; j < vertices[i].Neighbours.Count; j++)
            {
                sum += vertices[i].Neighbours[j].Position;
            }
            Result[i] = new Vertice(vertices[i].Position * (1f - alpha) + (alpha / vertices[i].Neighbours.Count) * sum);
        }
        return(Result);
    }
    //TODO coger plano perpendicular a la direccion de impacto y coger un triangulo bien grandote y sabrosote
    private Triangle GetSuperTrianglev1(List <Vector3> points, Vector3 impact, Vector3 impactDir)
    {
        Triangle superTriangle = new Triangle();

        Vector3 firstVectorPlane  = Vector3.Cross(impactDir, Vector3.up);
        Vector3 secondVectorPlane = Vector3.Cross(impactDir, firstVectorPlane);



        Vertice firstVertice   = new Vertice(impact + firstVectorPlane * 100, 0);
        Vertice secondtVertice = new Vertice(impact - firstVectorPlane * 20 + secondVectorPlane * 80, 0);
        Vertice thirdVertice   = new Vertice(impact - firstVectorPlane * 20 - secondVectorPlane * 80, 0);

        superTriangle.first  = new Edge(secondtVertice, firstVertice);
        superTriangle.second = new Edge(firstVertice, thirdVertice);
        superTriangle.third  = new Edge(thirdVertice, secondtVertice);
        return(superTriangle);
    }
Example #5
0
    public Lado getLado(int vi, int vf)
    {
        Vertice v1 = nodos[vi];
        Vertice v2 = nodos[vf];
        Lado    l  = new Lado(v1, v2, 0f);

        for (int k = 0; k < lados.Count; k++)
        {
            if (lados[k].getInicial().getNum() == v1.getNum() && lados[k].getFinal().getNum() == v2.getNum())
            {
                l = lados[k];
                //Debug.Log("Lado: " + l.getInicial().getNum() + "-" + l.getFinal().getNum());
                break;
            }
        }

        return(l);
    }
Example #6
0
        public static int[] CalculaDjkstra(int VerticeOrigem, Grafo Grafo)
        {
            Queue <int> filaVisita = new Queue <int>();

            if (Grafo == null || Grafo.NumeroVertices == 0)
            {
                throw new Exception("Grafo nao foi definido");
            }
            int[] retorno = new int[Grafo.NumeroVertices];
            int[] peso    = new int[Grafo.NumeroVertices];
            int[] visitas = new int[Grafo.NumeroVertices];
            for (int i = 0; i < retorno.Length; i++)
            {
                retorno[i] = i;
                peso[i]    = int.MaxValue;
                visitas[i] = 0;
            }

            filaVisita.Enqueue(VerticeOrigem);
            retorno[VerticeOrigem] = VerticeOrigem; // o Vertice de origem é a propria origem
            visitas[VerticeOrigem] = 1;
            peso[VerticeOrigem]    = 0;

            while (filaVisita.Count > 0)
            {
                Vertice    verticeAtual = Grafo.GetVertice(filaVisita.Dequeue());
                List <int> adjacentes   = verticeAtual.Adjacentes;
                foreach (var item in adjacentes)
                {
                    Aresta arestaAt = Grafo.ObtenhaAresta(verticeAtual.Id, item);
                    if (visitas[item] != 1)
                    {
                        filaVisita.Enqueue(item);
                    }
                    visitas[item] = 1;//visitado
                    if ((peso[verticeAtual.Id] + arestaAt.Peso) < peso[item])
                    {
                        peso[item]    = peso[verticeAtual.Id] + arestaAt.Peso;
                        retorno[item] = verticeAtual.Id;
                    }
                }
            }
            return(retorno);
        }
Example #7
0
        private void btnDeleteVertice_Click(object sender, RoutedEventArgs e)
        {
            Vertice v1 = new Vertice();

            v1.Nome      = Convert.ToInt32(txtNomeVerticeDelete.Text);
            v1.Cor       = Convert.ToInt32(txtCorVerticeDelete.Text);
            v1.Descricao = txtDescricaoVerticeDelete.Text;
            v1.Peso      = Convert.ToDouble(txtPesoVerticeDelete.Text);

            //Vamos identificar qual client será utilizado
            int nClient = Uteis.GetServidor(v1.Nome.ToString());

            Retorno r = new Retorno();

            switch (nClient)
            {
            case 0:
                r = VariaveisGlobais.client_servidor1.deleteVertice(v1);
                break;

            case 1:
                r = VariaveisGlobais.client_servidor2.deleteVertice(v1);
                break;

            case 2:
                r = VariaveisGlobais.client_servidor3.deleteVertice(v1);
                break;
            }

            if (r != null && r.Sucesso)
            {
                txtNomeVerticeDelete.Text      = "";
                txtCorVerticeDelete.Text       = "";
                txtDescricaoVerticeDelete.Text = "";
                txtPesoVerticeDelete.Text      = "";
                txtNomeVerticeDelete.IsEnabled = true;
                MessageBox.Show(r.Mensagem + " Servidor Utilizado - ID " + (nClient + 1) + "!");
            }
            else
            {
                txtNomeVerticeDelete.IsEnabled = true;
                MessageBox.Show("Não foi possível excluir o vértice!" + r.Mensagem);
            }
        }
Example #8
0
        /// <summary>
        /// Lê o arquivo com as informações das aulas, gera o grafo e exibe ele na tela
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnGerarGrafo_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFile = new OpenFileDialog();

            if (openFile.ShowDialog() == DialogResult.OK)
            {
                FileInfo info = new FileInfo(openFile.FileName);
                txtFilePath.Text = info.FullName;

                try
                {
                    List <string> arquivo = LeitorArquivo.Ler(info.FullName);
                    this.LimparValoresTela();

                    List <Aula> aulas = this.aulaService.CriarListaDeAulas(arquivo);
                    this.lblTotalAulasArquivo.Text = "Total Aulas arquivo: " + this.CalcularTotalAulasArquivo(aulas);
                    List <IDado> dadosAula = new List <IDado>();

                    dadosAula.AddRange(aulas);
                    List <string> grafo = this.grafoService.GerarHorariosFormatados(Vertice.ConverterParaVertice(dadosAula), out this.aulasSemHorario);
                    this.groupFiltro.Enabled = true;
                    this.InserirResultadosNaTabela(grafo);
                    this.InserirListasNoComboBox();
                    this.PreencherValoresLabel(grafo.Count);
                }
                catch (Exception error)
                {
                    MessageBox.Show("Houve um problema na leitura do arquivo. Erro retornado: " + error.Message,
                                    "Falha leitura arquivo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

                if (this.aulasSemHorario.Count > 0)
                {
                    DialogResult resultado = MessageBox.Show("Existem aulas que não foram encaixadas em um horário. Deseja ve-las agora ?",
                                                             "Aulas", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                    if (resultado == DialogResult.Yes)
                    {
                        this.btnMateriasSemHorario.Visible = true;
                        this.formMateriasSemAula           = new FormMateriasSemAula(this.aulasSemHorario);
                        this.formMateriasSemAula.ShowDialog();
                    }
                }
            }
        }
Example #9
0
        public Boolean colisionK5(Vertice velimina, Vertice nuevo)
        {
            if (!Colorario2(false) || !Colorario1(false))
            {
                if (velimina.GS_relacionDirecta.Count != 0 || velimina.GS_relacionIndirecta.Count != 0) // si tiene aunque sea alguna arista
                {
                    borrarNodo(buscaIndice(velimina.GS_coordenadas));

                    return(true);
                }
            }

            else
            {
                MessageBox.Show("el grafo ya es plano");
                return(true);
            }
            return(false);
        }
Example #10
0
        private async void Add_Point_Clicked(object sender, EventArgs e)
        {
            Vertice vertice = await LogIn.getCurrentLocation();

            if (count >= 3)
            {
                Done.IsVisible = true;
            }

            if (vertice != null)
            {
                count++;
                listOfVertices.Add(vertice);
            }
            else
            {
                await DisplayAlert("OOPS", "Unable to get area.\nMake Sure location is turned on.", "OK");
            }
        }
Example #11
0
    public List <string> BuscaProfundidadeLimitada(Vertice cidadeOrigem, Vertice cidadeDestino)
    {
        sw.Start();
        caminho.Clear();
        nosGerados    = 0;
        nosExpandidos = 0;
        int limite = 1;

        while (true)
        {
            bool resultado = BPLRecursivo(CriarNo(cidadeOrigem, null), cidadeDestino, limite);
            if (resultado)
            {
                sw.Stop();
                return(MontarCaminho());
            }
            limite++;
        }
    }
Example #12
0
        /// <summary>
        /// Checks Rem-combobox and confirms the operation
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void Confirm_rem_item(object sender, RoutedEventArgs e)
        {
            try
            {
                if (selected_item_name == "Grafo")
                {
                    Graph       = null;
                    Graph_exist = false;
                    graphStats.SetGrafo(Graph);
                    v1_box.Items.Clear();
                    v2_box.Items.Clear();
                    GraphCreate.Visibility = Visibility.Visible;
                    Drawer.ClearCanvas();
                }
                else if (selected_item_name == "Vértice")
                {
                    Vertice vertice_aux = Graph.BuscaVertice(lbl_rem_box.Text);

                    Graph.RemoveVertice(vertice_aux);

                    v1_box.Items.Remove(vertice_aux.Label);
                    v2_box.Items.Remove(vertice_aux.Label);
                }
                else if (selected_item_name == "Aresta")
                {
                    Aresta aresta_aux = Graph.BuscaAresta($"{Graph.BuscaVertice(v1_rem_box.SelectedItem.ToString())._id} {Graph.BuscaVertice(v2_rem_box.SelectedItem.ToString())._id}");
                    Graph.RemoveAresta(aresta_aux);
                }
            }
            catch (Exception ex)
            {
                msgdi = new MessageDialog($"Erro {ex.Message}");
                await msgdi.ShowAsync();
            }

            if (selected_item_name != "")
            {
                myConsole.AddStringToConsole($"\n{selected_item_name} foi removido.");
            }

            myConsole.Update();
            graphStats.Update();
        }
Example #13
0
    Grafo ObtenerTriangulos()
    {
        Grafo newGrafo = new Grafo(transform.childCount * 2);

        // Numero que llevara asociado el vertice
        int i = 0;

        foreach (Transform child in transform)
        {
            Mesh      meshChild = child.GetComponent <MeshFilter>().mesh;
            Vector3[] vertices  = meshChild.vertices;

            List <Vector3> lista = new List <Vector3>();

            for (int k = 0; k < vertices.Length; k++)
            {
                if (vertices[k].y >= 0.5f)
                {
                    if (!lista.Contains(vertices[k]))
                    {
                        lista.Add(vertices[k]);
                    }
                }
            }

            for (int j = 0; j < lista.Count - 2; j++)
            {
                Vector3[] puntos = new Vector3[3];
                puntos[0] = child.transform.position + lista[j];
                puntos[1] = child.transform.position + lista[j + 1];
                puntos[2] = child.transform.position + lista[j + 2];

                Vector3 center = (puntos[0] + puntos[1] + puntos[2]) / 3;

                Vertice newV = new Vertice(i, center, puntos);
                newGrafo.nodos[i] = newV;

                i++;
            }
        }

        return(newGrafo);
    }
    public void Start()
    {
        currentTriangulation = new List <Triangle>();
        currentVertices      = new List <Vertice>();
        plane = new Plane(new Vector3(0, 0, 1), new Vector3(1, 0, 0));
        // SUPER TRIANGLE
        Triangle superTriangle = GetSuperTriangle(plane);

        currentVertices.Add(superTriangle.first.origin);
        currentVertices.Add(superTriangle.second.origin);
        currentVertices.Add(superTriangle.third.origin);

        //CREATE VERTICES, PROJECT THEM INTO A PLANE AND ADD TO ARRAYS
        pointsToTriangulate = new List <Vector3>();

        for (int i = 0; i < 10; i++)
        {
            pointsToTriangulate.Add(new Vector3(Mathf.Cos(i * Mathf.PI * 2 / 10) + Random.Range(0, 0.01f), 0, Mathf.Sin(i * Mathf.PI * 2 / 10) + Random.Range(0, 0.01f)));
        }
        for (int i = 0; i < 5; i++)
        {
            pointsToTriangulate.Add(new Vector3(Mathf.Cos(i * Mathf.PI * 2 / 5) * 0.5f + Random.Range(0, 0.01f), 0, Mathf.Sin(i * Mathf.PI * 2 / 5) * 0.5f + Random.Range(0, 0.01f)));
        }
        for (int i = 0; i < 1; i++)
        {
            pointsToTriangulate.Add(new Vector3(Random.Range(0, 0.01f), 0, Random.Range(0, 0.01f)));
        }

        int            indexVertices            = 0;
        List <Vertice> verticesProjectedInPlane = new List <Vertice>();

        pointsToTriangulate.ForEach(pointToTriangulate => {
            //Vertice newVerticeProjected = new Vertice(PointProjectedStereographic(pointToTriangulate, centerSphere, radiusSphere), indexVertices);
            Vertice newVerticeMesh = new Vertice(pointToTriangulate, indexVertices++);
            //Instantiate(_verticePrefab, point * transform.localScale.x + transform.position, Quaternion.identity);
            //Debug.Log(pointToTriangulate.ToString("#.00000"));
            //verticesProjectedInPlane.Add(newVerticeProjected);
            currentVertices.Add(newVerticeMesh);
        });

        isTriangulationFinished = false;
        StartCoroutine(BowyerWatson(currentVertices, plane, superTriangle));
    }
Example #15
0
        /// <summary>
        /// COLOCA UM VERTICE NA FILA
        /// </summary>
        /// <param name="vertice"></param>
        public void ColocarFila(Vertice vertice)
        {
            Elemento novo = new Elemento
            {
                Vertice = vertice,
                Proximo = null
            };

            if (Fim != null)
            {
                Fim.Proximo = novo;
            }
            else
            {
                Inicio = novo;
            }

            Fim = novo;
        }
Example #16
0
        public bool isAtingivel(Vertice vOrigem, Vertice vDestino, List <Vertice> vertices)
        {
            foreach (var aresta in vOrigem.Arestas)
            {
                if (aresta.VerticeD == vDestino.Aeroporto)
                {
                    return(true);
                }
            }

            var vertex = BuscaLargura(vOrigem, vDestino, vertices);

            if (vertex != null)
            {
                return(true);
            }

            return(false);
        }
Example #17
0
        public Retorno listarArestasVertice(Vertice v)
        {
            Retorno retorno = new Retorno(true);

            Monitor.Enter(locker);

            atualizarGrafo();

            Monitor.Exit(locker);

            List <Aresta> _Arestas = new List <Aresta>();

            _Arestas = this.Arestas.Where(p => p.VerticeInicio == v.Nome || p.VerticeFim == v.Nome).ToList();

            //Serializado como uma lista de arestas
            retorno.Retorno_ = JsonConvert.SerializeObject(_Arestas);

            return(retorno);
        }
Example #18
0
        public static async Task<Vertice> getCurrentLocation() {
            try
            {
                var hasPermission = await Utils.CheckPermissions(Permission.Location);
                if (!hasPermission) {
                    return null;
                }

                var locator = CrossGeolocator.Current;

                var position = await locator.GetLastKnownLocationAsync();

                if (position == null)
                {
                    Application.Current.Properties["Location_ERR"] = "Couldn't get the location";
                    return null;
                }
                else
                {

                    double latitude = position.Latitude;
                    Application.Current.Properties["latitude"] = latitude;
                    double longitude = position.Longitude;
                    Application.Current.Properties["longitude"] = longitude;
                   /* double cosLatValue = Math.Cos(latitude);
                    double sinLongValue = Math.Sin(longitude);
                    double cosLongValue = Math.Sin(longitude);
                    double sinLatValue = Math.Sin(latitude);
                    double x = 6371 * 1000 * cosLatValue * cosLongValue;
                    double y = 6371 * 1000 * cosLatValue * sinLongValue;*/
                    Vertice v = new Vertice();
                    v.x = longitude;
                    v.y = latitude;
                    return v;
                }
            }
            catch (Exception ex)
            {
                Application.Current.Properties["Location_ERR"] = "Something went wrong, but don't worry we captured for analysis! Thanks";
                return null;
            }
        }    
Example #19
0
 public ShapeVertice(Vertice v)
 {
     //definindo o grid
     IsPositioned = false;
     MyGrid       = new Grid();
     MyVertice    = v;
     MyGrid.Children.Add(new Ellipse
     {
         Fill   = new SolidColorBrush(Colors.DarkBlue),
         Height = 30,
         Width  = 30
     });
     Size = 30;
     MyGrid.Children.Add(new TextBlock
     {
         Text     = "   " + v.Label,
         FontSize = 10,
         Name     = "A"
     });
 }
        static void Main(string[] args)
        {
            Vertice v0 = new Vertice("V0");
            Vertice v1 = new Vertice("V1");
            Vertice v2 = new Vertice("V2");
            Vertice v3 = new Vertice("V3");
            Vertice v4 = new Vertice("V4");
            Vertice v5 = new Vertice("V5");

            v0.AddIntercessoes(new Intercessao(v0, 0), new Intercessao(v1, 10), new Intercessao(v2, 5));
            v1.AddIntercessoes(new Intercessao(v0, 10), new Intercessao(v2, 3), new Intercessao(v3, 1));
            v2.AddIntercessoes(new Intercessao(v0, 5), new Intercessao(v1, 3), new Intercessao(v3, 8), new Intercessao(v4, 2));
            v3.AddIntercessoes(new Intercessao(v1, 1), new Intercessao(v2, 8), new Intercessao(v4, 4), new Intercessao(v5, 4));
            v4.AddIntercessoes(new Intercessao(v2, 2), new Intercessao(v3, 4), new Intercessao(v5, 6));
            v5.AddIntercessoes(new Intercessao(v3, 4), new Intercessao(v4, 6));

            Dijsktra dijsktra = new Dijsktra(v0, v1, v2, v3, v4, v5);

            dijsktra.Processar();
        }
Example #21
0
 public void AgregarVertice(Vertice a)
 {
     if (GrafoCount < ListaVertices.Count)
     {
         for (int i = 0; i < ListaVertices.Count; i++)
         {
             if (ListaVertices[i] == null)
             {
                 ListaVertices[i] = new Vertice(a.Nombre, a.LimInferior, a.LimSuperior, a.Valor);
                 GrafoCount++;
                 break;
             }
         }
     }
     else
     {
         ListaVertices.Add(new Vertice(a.Nombre, a.LimInferior, a.LimSuperior, a.Valor));
         GrafoCount++;
     }
 }
    public void AddUnDirectedEdge(int vertice1, int vertice2, int weight = 0)
    {
        Vertice sourceVertice      = GetVertice(vertice1);
        Vertice destinationVertice = GetVertice(vertice2);

        if (sourceVertice == null || destinationVertice == null)
        {
            throw new ArgumentException("Given source value or destination value doesn't exist in graph.");
        }

        if (!sourceVertice.ContainsEdge(destinationVertice))
        {
            sourceVertice.AddEdge(destinationVertice, weight);
        }

        if (!destinationVertice.ContainsEdge(sourceVertice))
        {
            destinationVertice.AddEdge(sourceVertice, weight);
        }
    }
Example #23
0
        public static Vertice GetPointFromTriangleArea(double area, Vertice pStart, Vertice pEnd, double d, double d2)
        {
            Vertice midPoint = new Vertice(-1, -1);
            double  distance = DistanceHelpers.DistanceBetween(pStart, pEnd);
            double  height   = (2 * area) / distance;
            double  z        = Pythagoras.GetCathetus(height, d);

            double  proportion    = z / distance;
            Vertice resultVertice = PointHelpers.GetPointInProportion(proportion, pStart, pEnd);

            PointHelpers.SetPointXY(midPoint, resultVertice.x, resultVertice.y);

            (double, double)line = Line.GetStraightLine(pStart, pEnd);
            (double, double)perpendicularLine = Line.GetPerpendicularThroughPoint(line, midPoint);
            if (line.Item1 == 0)
            {
                return(new Vertice(midPoint.x, midPoint.y - (int)height));
            }
            return(PointHelpers.GetPointFromLineDistanceAndPoint(perpendicularLine, height, midPoint).Item2);
        }
Example #24
0
 private void RemoverVertice(Vertice vertice, List <Vertice> vertices)
 {
     foreach (var vertex in vertices)
     {
         var arestasRemover = new List <Aresta>();
         foreach (var aresta in vertex.Arestas)
         {
             if (aresta.VerticeD == vertex.Aeroporto)
             {
                 arestasRemover.Add(aresta);
             }
         }
         foreach (var aresta in arestasRemover)
         {
             vertex.Arestas.Remove(aresta);
         }
     }
     vertices.Remove(vertice);
     vertices.RemoveAll(x => x == null);
 }
        private void btGravar_Click(object sender, EventArgs e)
        {
            Label lb_Selec = null;

            Vertice vd = Manager.GetVerticeNaGrade(new Disciplina(cbDisciplina.SelectedItem.ToString(), 0, 0));
            Vertice vh = null;

            for (int i = 0; i < lb_Horarios.Count; i++)
            {
                if (lb_Horarios[i].BackColor != Color.White)
                {
                    lb_Selec = lb_Horarios[i];
                    vh       = v_Horarios[i]; //a lista de labels está na mesma ordem da lista de vertices de horarios
                    break;
                }
            }

            if (Manager.TentarAlocar(vh, vd)) //ja realiza a alocação no grafo e grava no banco
            {
                //MessageBox.Show("Alocação gravada!", "Sucesso", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);

                lb_Selec.Text = cbDisciplina.SelectedItem.ToString();

                foreach (Label lb in lb_Horarios)
                {
                    lb.BackColor = Color.White;
                }

                lbHorarioEscolhido.Text = null;

                cbDisciplina.SelectedIndex = -1;
                cbDisciplina.Enabled       = false;
                lbExibeProfessor.Text      = "";
                btGravar.Enabled           = false;
            }
            else
            {
                MessageBox.Show("Não foi possível gravar a alocação! Este professor já ministra uma disciplina neste mesmo horário, em outro período.",
                                "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
            }
        }
Example #26
0
        public Retorno insertVertice(Vertice v)
        {
            Retorno retorno = new Retorno(true);

            Monitor.Enter(locker);

            this.atualizarGrafo();

            Vertice aux = null;

            if (this.Vertices.Count > 0)
            {
                aux = this.Vertices.Where(p => p.Nome == v.Nome).FirstOrDefault();
            }

            if (aux != null)
            {
                //Implica que já existe outro vertice com o mesmo nome
                Console.WriteLine("O nome destinado ao vértice já foi utilizado!");
                retorno.Sucesso  = false;
                retorno.Mensagem = "O nome destinado ao vértice já foi utilizado!";
                return(retorno);
            }

            this.Vertices.Add(v);

            if (!Util.escreverGrafoArquivo(this, Util.caminho))
            {
                Console.WriteLine("Não foi possível gravar o vértice no arquivo!");
                retorno.Sucesso  = false;
                retorno.Mensagem = "Não foi possível gravar o vértice no arquivo!";
                return(retorno);
            }

            Monitor.Exit(locker);

            Console.WriteLine("Vértice cadastrado com sucesso!");
            retorno.Mensagem = "Vértice cadastrado com sucesso!";

            return(retorno);
        }
Example #27
0
        public void Rotate(Vertice vertice)
        {
            var position = vertice.Position;

            if (position == 2 || position == 4)
            {
                vertice.Position++;
            }
            else if (position == 0 || position == 3)
            {
                vertice.Position += 4;
            }
            else if (position == 1 || position == 7)
            {
                vertice.Position--;
            }
            else if (position == 5 || position == 6)
            {
                vertice.Position -= 4;
            }
        }
Example #28
0
        public Vertice GetOpposite(Edge o)
        {
            var o0 = o.vertices[0];
            var o1 = o.vertices[1];

            for (int i = 0; i < 3; i++)
            { // Will never reach 3 because there will be an unequal vertice before the third edge
                Edge    e  = edges[i];
                Vertice e0 = e.vertices[0];
                if (e0 != o0 && e0 != o1)
                {
                    return(e0);
                }
                Vertice e1 = e.vertices[1];
                if (e1 != o0 && e1 != o1)
                {
                    return(e1);
                }
            }
            throw new Exception("A face seems to have three edges that all share a vertice with a given edge.");
        }
Example #29
0
        public IHttpContext GetMenorCaminhoBellmanFord(IHttpContext context)
        {
            Dictionary <string, string> loArgs = APIUtil.GetDictionaryFromContext(context);

            APIUtil.UpdateClientes(context);
            Cliente loCliente = APIUtil.ValidarCliente(context);

            int liID = Convert.ToInt32(loArgs["id"]);

            Vertice loVertice = APIUtil.FindVerticeByID(liID, loCliente.Grafo);
            int     aiIterationsCount;
            MultiKeyDictionary <Vertice, Vertice, int> loMenorCaminho = APIUtil.BellmanFord(loCliente.Grafo, loVertice, out aiIterationsCount);

            string lsHtml = APIUtil.GetMatrizHTML(loMenorCaminho);

            context.Response.ContentType     = ContentType.HTML;
            context.Response.ContentEncoding = Encoding.UTF8;
            context.Response.SendResponse(lsHtml);

            return(context);
        }
Example #30
0
        private Vertice BuscaLargura(Vertice vOrigem, Vertice vDestino, List <Vertice> listaVertice)
        {
            LimpaStatus();
            var visitados = new List <Vertice>();

            visitados.Add(vOrigem);

            bool TodosVisitados = false;

            while (!TodosVisitados) // quase n^3
            {
                foreach (var vertex in visitados)
                {
                    foreach (var aresta in vertex.Arestas)
                    {
                        if (aresta.VerticeD == vDestino.Aeroporto)
                        {
                            return(vDestino);
                        }
                    }
                }

                int count = visitados.Count;

                for (int i = 0; i < count; i++)
                {
                    foreach (var aresta in visitados[i].Arestas)
                    {
                        if (EncontraVerticePorNome(aresta.VerticeD, visitados) == null)
                        {
                            visitados.Add(EncontraVerticePorNome(aresta.VerticeD, listaVertice));
                            visitados.RemoveAll(x => x == null);
                        }
                    }
                    visitados[i].Status = Status.FINALIZADO;
                }
                TodosVisitados = (from vertice in visitados where vertice.Status == Status.FINALIZADO select vertice).Count() == visitados.Count ? true : false;
            }
            return(null);
        }
Example #31
0
        /// <summary>When collapsing an edge a->c, the linear space must
        /// be respected, and all faces, not connected with a->c,
        /// must not flip.
        /// </summary>
        public bool CanFollow(Edge transportEdge, out Vertice opposite)
        {
            if (IsStatic)
            {
                opposite = default(Vertice); return(false);
            }
            if (linearPosition != null && !transportEdge.IsParallel(linearPosition))
            {
                opposite = default(Vertice); return(false);
            }

            var localTris = new HashSet <Face>();

            foreach (Edge e in edges)
            {
                foreach (Face f in e.faces)
                {
                    localTris.Add(f);
                }
            }

            localTris.ExceptWith(transportEdge.faces);

            opposite = transportEdge.GetOpposite(this);
            var targetPos = opposite.position;
            var lTriEnum  = localTris.GetEnumerator();

            try
            {
                while (lTriEnum.MoveNext())
                {
                    if (lTriEnum.Current.MoveWouldFlip(this, targetPos))
                    {
                        return(false);
                    }
                }
            }
            finally { lTriEnum.Dispose(); }
            return(true);
        }
Example #32
0
        public Retorno insertAresta(Aresta a)
        {
            Retorno retorno = new Retorno(true);

            Monitor.Enter(locker);

            atualizarGrafo();

            Vertice v1 = null;
            Vertice v2 = null;

            v1 = this.Vertices.Where(p => p.Nome == a.VerticeInicio).FirstOrDefault();
            v2 = this.Vertices.Where(p => p.Nome == a.VerticeFim).FirstOrDefault();

            if (v1 == null || v2 == null)
            {
                //Implica que algum vértice informado não existe
                Console.WriteLine("Algum dos vértices informados não existe!");
                retorno.Sucesso  = false;
                retorno.Mensagem = "Algum dos vértices informados não existe!";
                return(retorno);
            }

            this.Arestas.Add(a);

            if (!Util.escreverGrafoArquivo(this, Util.caminho))
            {
                Console.WriteLine("Não foi possível gravar a aresta no arquivo!");
                retorno.Sucesso  = false;
                retorno.Mensagem = "Não foi possível gravar a aresta no arquivo!";
                return(retorno);
            }

            Monitor.Exit(locker);

            Console.WriteLine("Aresta cadastrado com sucesso!");
            retorno.Mensagem = "Aresta cadastrado com sucesso!";

            return(retorno);
        }
Example #33
0
		public void RecalcularNormalSRC(Vertice[] Vertices)
		{
			mNormalSRC = Cara.VectorNormalSRC(this, Vertices);
			if (Modificado != null) {
				Modificado(this);
			}
		}
Example #34
0
        static void Main(string[] args)
        {
            Grafo<string> grafo = new Grafo<string>();

            Vertice<string> v1 = new Vertice<string>("Index.htm");
            Vertice<string> v2 = new Vertice<string>("Home.htm");
            Vertice<string> v3 = new Vertice<string>("Contact.htm");
            Vertice<string> v4 = new Vertice<string>("About.htm");
            //InserirVertice()
            grafo.InserirVertice(v1);
            grafo.InserirVertice(v2);
            grafo.InserirVertice(v3);
            grafo.InserirVertice(v4);

            var lista = grafo.Vertices().ToList();
            foreach (Node<string> vertice in lista)
            {
                Console.WriteLine(vertice.Value.ToString());
            }
            Console.WriteLine();

            //InserirVerticeDirecionado()
            Aresta<string> aresta1 = grafo.InserirAresta(v1, v2, 1);
            Aresta<string> aresta2 = grafo.InserirAresta(v2, v3, 2);
            Aresta<string> aresta3 = grafo.InserirAresta(v1, v3, 3);
            Aresta<string> aresta4 = grafo.InserirAresta(v1, v4, 4);
            //Vertice<string> verticeSubst = new Vertice<string>("Gallery.htm");
            //grafo.substituirVertice(v1, verticeSubst);
            //bool verticeRemovido = grafo.RemoverVertice(v2);
            Console.WriteLine("Lista de arestas: ");
            List<Aresta<string>> listaArestas = grafo.Arestas();
            foreach (Aresta<string> arestaItem in listaArestas)
            {
                Console.WriteLine(grafo.GetAresta(arestaItem));
                if(!grafo.eDirecionado(arestaItem))
                    Console.WriteLine(arestaItem.to.Value.ToString()+" - "+ arestaItem.from.Value.ToString());
            }

            //eAdjacente()
            if (grafo.eAdjacente(v1, v2)) Console.WriteLine(v1.Value.ToString() + " é adjacente de " + v2.Value.ToString());
            else Console.WriteLine(v1.Value.ToString() + " não é adjacente de " + v2.Value.ToString());

            /*
            //removerVertice
            //
            //oposto
            Console.WriteLine(grafo.oposto(v1, aresta1).Value.ToString());
            //finalVertice
            Vertice<string>[] verticesFinais = grafo.finalVertices(aresta1);
            Console.WriteLine(verticesFinais[0].Value.ToString()+ " - " +verticesFinais[1].Value.ToString());
            //Subistuir Vertice
            Console.WriteLine("\nNova Lista de Vertices: ");
            Vertice<string> verticeSubst =new Vertice<string>("Galery.htm");
            grafo.substituirVertice(v1, verticeSubst);
            var listaSubstituidos = grafo.Vertices().ToList();
            foreach (Vertice<string> vertice in lista)
            {
                Console.WriteLine(vertice.Value.ToString());
            }
            Aresta<string> arestaSubst = new Aresta<string>(v3, v4);
            grafo.substituirAresta(aresta1, arestaSubst);
            Console.WriteLine("\nNova Lista de Arestas");
            List<Aresta<string>> listaSubst = grafo.Arestas();
            foreach (Aresta<string> arestaItem in listaSubst)
            {
                Console.WriteLine(Aresta<string>.GetAresta(arestaItem));
                if (!grafo.eDirecionado(arestaItem))
                    Console.WriteLine(arestaItem.to.Value.ToString() + " - " + arestaItem.from.Value.ToString());
            }*/
            //Aresta<string> arestaSubst = new Aresta<string>(v3, v4);
            //grafo.substituirAresta(aresta1, arestaSubst);

            Console.WriteLine("\nMatriz de Custo");
            grafo.MostrarMatrizdeCusto();
            Console.WriteLine("\nMatriz de Adjacencia");
            grafo.MostrarMatrizdeAdjacencia();
            grafo.eEuleriano();
            //grafo.Dijkstra(v1, v2);
            Console.Read();
        }
Example #35
0
		public void RecalcularBaricentroSRC(Vertice[] Vertices)
		{
			mBaricentroSRC = Cara.BaricentroCaraSRC(this, Vertices);
			if (Modificado != null) {
				Modificado(this);
			}
		}
Example #36
0
		public void RecalcularDatosSRC(Vertice[] Vertices)
		{
			mNormalSRC = Cara.VectorNormalSRC(this, Vertices);
			mBaricentroSRC = Cara.BaricentroCaraSRC(this, Vertices);
			if (Modificado != null) {
				Modificado(this);
			}
		}
        private void generateFace(Vector3 position1, Vector3 position2, Vector3 position3, Vector3 position4, int mapping, Vector3 normal, bool isBorder)
        {
            int Index1 = numberToID(position1);
            int Index2 = numberToID(position2);
            int Index3 = numberToID(position3);
            int Index4 = numberToID(position4);

            int textureIndex1 = 0;
            int textureIndex2 = 0;
            int textureIndex3 = 0;
            int textureIndex4 = 0;

            if (mapping == 0)
            {
                textureIndex1 = numberToID(new Vector3(position1.X, position1.Z, 0));
                textureIndex2 = numberToID(new Vector3(position2.X, position2.Z, 0));
                textureIndex3 = numberToID(new Vector3(position3.X, position3.Z, 0));
                textureIndex4 = numberToID(new Vector3(position4.X, position4.Z, 0));
            }
            else if (mapping == 1)
            {
                textureIndex1 = numberToID(new Vector3(position1.Z, position1.Y, 0));
                textureIndex2 = numberToID(new Vector3(position2.Z, position2.Y, 0));
                textureIndex3 = numberToID(new Vector3(position3.Z, position3.Y, 0));
                textureIndex4 = numberToID(new Vector3(position4.Z, position4.Y, 0));
            }
            else if (mapping == 2)
            {
                textureIndex1 = numberToID(new Vector3(position1.X, position1.Y, 0));
                textureIndex2 = numberToID(new Vector3(position2.X, position2.Y, 0));
                textureIndex3 = numberToID(new Vector3(position3.X, position3.Y, 0));
                textureIndex4 = numberToID(new Vector3(position4.X, position4.Y, 0));
            }

            normals[Index1] += normal;
            normals[Index2] += normal;
            normals[Index3] += normal;
            normals[Index4] += normal;

            Vertice vert1 = new Vertice(Index1, textureIndex1, Index1);
            Vertice vert2 = new Vertice(Index2, textureIndex2, Index2);
            Vertice vert3 = new Vertice(Index3, textureIndex3, Index3);
            Vertice vert4 = new Vertice(Index4, textureIndex4, Index4);

            Face newFace = new Face(vert1, vert2, vert3, vert4);
            newFace.isTemp = isBorder;

            Faces.Add(newFace);

            //Faces.Add(new Face(vert3, vert2, vert1));
            //Faces.Add(new Face(vert2, vert3, vert4));
        }
Example #38
0
		public static Punto3D BaricentroCaraSRC(Cara Cara, Vertice[] Vertices)
		{
			return Punto3D.Baricentro(Cara.PuntosSRC[Vertices]);
		}
Example #39
0
		public static Vertice AplicarTransformacion(Vertice Vertice, Traslacion Traslacion)
		{
			return new Vertice(new Punto3D(Vertice.CoodenadasSUR.X + Traslacion.Traslacion.X, Vertice.CoodenadasSUR.Y + Traslacion.Traslacion.Y, Vertice.CoodenadasSUR.Z + Traslacion.Traslacion.Z));
		}
Example #40
0
		public static Vertice AplicarTransformacion(Vertice Vertice, Escalado Escalado)
		{
			return new Vertice(new Punto3D(Vertice.CoodenadasSUR.X * Escalado.Escalado.X, Vertice.CoodenadasSUR.Y * Escalado.Escalado.Y, Vertice.CoodenadasSUR.Z * Escalado.Escalado.Z));
		}
Example #41
0
		public static Poliedro Malla(int Dimensiones, int NumeroCeldas)
		{
			Vertice[] Vertices = null;
			Cara[] Caras = null;

			double p = -(Dimensiones / 2);
			double d = (Dimensiones / NumeroCeldas);
			int indice = 0;

			Vertices = new Vertice[(Math.Pow((NumeroCeldas + 1), 2))];
			Caras = new Cara[(Math.Pow(NumeroCeldas, 2))];

			for (int i = 0; i <= NumeroCeldas; i++) {
				for (int j = 0; j <= NumeroCeldas; j++) {
					Vertices[(i * (NumeroCeldas + 1)) + j] = new Vertice(new Punto3D(p + (d * (j)), 0, p + (d * (i))));
				}
			}

			for (int i = 0; i <= NumeroCeldas - 1; i++) {
				for (int j = 0; j <= NumeroCeldas - 1; j++) {
					indice = (i * (NumeroCeldas)) + j;
					Caras[indice] = new Cara(indice, indice + 1, indice + NumeroCeldas + 2, indice + NumeroCeldas + 1);
				}
			}

			return new Poliedro(Vertices, Caras);
		}
Example #42
0
		public static Poliedro Cubo()
		{
			Vertice[] Vertices = new Vertice[8];
			Cara[] Caras = new Cara[6];

			Vertices[0] = new Vertice(new Punto3D(-1, -1, -1));
			Vertices[1] = new Vertice(new Punto3D(1, -1, -1));
			Vertices[2] = new Vertice(new Punto3D(1, 1, -1));
			Vertices[3] = new Vertice(new Punto3D(-1, 1, -1));
			Vertices[4] = new Vertice(new Punto3D(-1, -1, 1));
			Vertices[5] = new Vertice(new Punto3D(1, -1, 1));
			Vertices[6] = new Vertice(new Punto3D(1, 1, 1));
			Vertices[7] = new Vertice(new Punto3D(-1, 1, 1));

			Caras[0] = new Cara(3, 2, 1, 0);
			Caras[1] = new Cara(4, 5, 6, 7);
			Caras[2] = new Cara(7, 6, 2, 3);
			Caras[3] = new Cara(4, 7, 3, 0);
			Caras[4] = new Cara(5, 4, 0, 1);
			Caras[5] = new Cara(6, 5, 1, 2);

			//For i As Integer = 0 To 5
			//    Caras(i).RevertirVertices()
			//Next

			return new Poliedro(Vertices, Caras);
		}
		public static Vertice AplicarTransformacion(Vertice Vertice, Transformacion3D Transformacion)
		{
			return new Vertice(new Punto3D(Transformacion.Matriz * Vertice.CoodenadasSUR.Matriz));
		}
Example #44
0
		public static Vector3D VectorNormalSRC(Cara Cara, Vertice[] Vertices)
		{
			return (new Vector3D(Vertices[Cara.Vertices[0]].CoodenadasSRC, Vertices[Cara.Vertices[1]].CoodenadasSRC) + new Vector3D(Vertices[Cara.Vertices[0]].CoodenadasSRC, Vertices[Cara.Vertices[2]].CoodenadasSRC)).VectorUnitario;
		}
Example #45
0
		public static Plano3D PlanoSRC(Cara Cara, Vertice[] Vertices)
		{
			return new Plano3D(Vertices[Cara.Vertices[0]].CoodenadasSRC, Vertices[Cara.Vertices[1]].CoodenadasSRC, Vertices[Cara.Vertices[2]].CoodenadasSRC);
		}
Example #46
0
        /// <summary>
        /// 导出Point3Ds数据到vPDic和vPIndex(未完成,需要一个三角网构成算法,在这儿调用。同时替代以前构成mesh时候用的临时算法)
        /// </summary>
        /// <param name="ps"></param>
        /// <param name="vPDic"></param>
        /// <param name="vPIndex"></param>
        public static void ExportVPList(this Point3Ds ps, ref Dictionary<int, Vertice> vPDic, ref List<Index> vPIndex)
        {
            foreach (Point3D p3d in ps)
            {
                Vertice vp = new Vertice(p3d.X, p3d.Y, p3d.Z);
                if (!vPDic.ContainsKey(vp.HashCode))
                {
                    vPDic.Add(vp.HashCode, vp);
                }

            }

            #region 调用一个三角网构建算法

            #endregion
        }
Example #47
0
		public bool EsVisible(Camara3D Camara, Vertice[] Vertices)
		{
			if (mNormalSRC.Z <= 0.01 && Camara.Frustum.Pertenece(mBaricentroSRC)) {
				for (int i = 0; i <= mVertices.GetUpperBound(0); i++) {
					if (Camara.Pantalla.Pertenece(Vertices[mVertices[i]].Representacion)) {
						return true;
					}
				}

				return false;
			} else {
				return false;
			}
		}
Example #48
0
		public Poliedro(Vertice[] Vertices, Cara[] Caras)
		{
			if (Vertices.GetUpperBound(0) >= 3) {
				if (Caras.GetUpperBound(0) >= 3) {
					mCaras = Caras;

					for (int i = 0; i <= mCaras.GetUpperBound(0); i++) {
						mCaras[i].Color = Color.White;
					}

					mVertices = Vertices;
					mAutoRecalcularCajas = false;
					AutoReclcNorms = true;
					RecalcularCentro();
					CalcularCarasVertices();
					RecalcularDatosCaras();
					RecalcularNormalesVertices();
					mConstantesShading = new PhongShader();
					mVertical = new Vector3D(0, 1, 0);
				} else {
					throw new ExcepcionPrimitiva3D("POLIEDRO (NEW): Un poliedro debe tener al menos 4 caras" + Constants.vbNewLine + "Numero de caras=" + Vertices.GetUpperBound(0) + 1);
				}
			} else {
				throw new ExcepcionPrimitiva3D("POLIEDRO (NEW): Un poliedro debe tener al menos 4 vertices" + Constants.vbNewLine + "Numero de vertices=" + Vertices.GetUpperBound(0) + 1);
			}
		}
Example #49
0
        /// <summary>
        /// 提取结构化的数据
        /// </summary>
        /// <param name="geoModel"></param>
        /// <param name="Tolerance"></param>
        /// <param name="vPDic"></param>
        /// <param name="vPIndex"></param>
        public static void structureData(this GeoModel geoModel,int Tolerance, out Dictionary<int, Vertice> vPDic, out  List<Index> vPIndex)
        {
            vPDic = new Dictionary<int, Vertice>();
            vPIndex = new List<Index>();

            #region 提取数据并结构化
            foreach (Mesh m in geoModel.Meshes)
            {
                //插入一组mesh并索引三角面
                int inLen = m.Indexes.Length;
                for (int i = 0; i < inLen; i += 3)
                {
                    #region 结构化被索引的三个点对象,并依据hash插入dictionary
                    //相同坐标的点具有相同的hash
                    Normal nor = new Normal();
                    nor.X = m.Normals[3 * (m.Indexes[i])]; nor.Y = m.Normals[3 * (m.Indexes[i]) + 1]; nor.Z = m.Normals[3 * (m.Indexes[i]) + 2];
                    Vertice vP1 = new Vertice(Convert.ToInt32(m.Vertices[3 * (m.Indexes[i])] * Math.Pow(10, Tolerance)) / Convert.ToDouble((Math.Pow(10, Tolerance))),
                                                Convert.ToInt32(m.Vertices[3 * (m.Indexes[i]) + 1] * Math.Pow(10, Tolerance)) / (Math.Pow(10, Tolerance)),
                                                Convert.ToInt32(m.Vertices[3 * (m.Indexes[i]) + 2] * Math.Pow(10, Tolerance)) / (Math.Pow(10, Tolerance)))
                    {
                        Normal = nor
                    };
                    nor.X = m.Normals[3 * (m.Indexes[i + 1])]; nor.Y = m.Normals[3 * (m.Indexes[i + 1]) + 1]; nor.Z = m.Normals[3 * (m.Indexes[i + 1]) + 2];
                    Vertice vP2 = new Vertice(Convert.ToInt32(m.Vertices[3 * (m.Indexes[i + 1])] * Math.Pow(10, Tolerance)) / (Math.Pow(10, Tolerance)),
                                                Convert.ToInt32(m.Vertices[3 * (m.Indexes[i + 1]) + 1] * Math.Pow(10, Tolerance)) / (Math.Pow(10, Tolerance)),
                                                Convert.ToInt32(m.Vertices[3 * (m.Indexes[i + 1]) + 2] * Math.Pow(10, Tolerance)) / (Math.Pow(10, Tolerance)))
                    {
                        Normal = nor
                    };
                    nor.X = m.Normals[3 * (m.Indexes[i + 2])]; nor.Y = m.Normals[3 * (m.Indexes[i + 2]) + 1]; nor.Z = m.Normals[3 * (m.Indexes[i + 2]) + 2];
                    Vertice vP3 = new Vertice(Convert.ToInt32(m.Vertices[3 * (m.Indexes[i + 2])] * Math.Pow(10, Tolerance)) / (Math.Pow(10, Tolerance)),
                                                Convert.ToInt32(m.Vertices[3 * (m.Indexes[i + 2]) + 1] * Math.Pow(10, Tolerance)) / (Math.Pow(10, Tolerance)),
                                                Convert.ToInt32(m.Vertices[3 * (m.Indexes[i + 2]) + 2] * Math.Pow(10, Tolerance)) / (Math.Pow(10, Tolerance)))
                    {
                        Normal = nor
                    };

                    //插入点并计算该点法向量,如果已存在点则累加法向量
                    if (!vPDic.ContainsKey(vP1.HashCode)) vPDic.Add(vP1.HashCode, vP1);
                    vPDic[vP1.HashCode].Normal.X += vP1.Normal.X;
                    vPDic[vP1.HashCode].Normal.Y += vP1.Normal.Y;
                    vPDic[vP1.HashCode].Normal.Z += vP1.Normal.Z;

                    if (!vPDic.ContainsKey(vP2.HashCode)) vPDic.Add(vP2.HashCode, vP2);
                    vPDic[vP2.HashCode].Normal.X += vP2.Normal.X;
                    vPDic[vP2.HashCode].Normal.Y += vP2.Normal.Y;
                    vPDic[vP2.HashCode].Normal.Z += vP2.Normal.Z;

                    if (!vPDic.ContainsKey(vP3.HashCode)) vPDic.Add(vP3.HashCode, vP3);
                    vPDic[vP3.HashCode].Normal.X += vP3.Normal.X;
                    vPDic[vP3.HashCode].Normal.Y += vP3.Normal.Y;
                    vPDic[vP3.HashCode].Normal.Z += vP3.Normal.Z;

                    #endregion

                    Index Index = new Index()
                    {
                        P1 = vP1.HashCode,
                        P2 = vP2.HashCode,
                        P3 = vP3.HashCode
                    };

                    vPIndex.Add(Index);
                }
            }
            #endregion
        }
Example #50
0
		public static Poliedro Esfera(int Pasos)
		{
			Vertice[] Vertices = new Vertice[(Math.Pow(Pasos, 2)) - Pasos + 2];
			Cara[] Caras = new Cara[(Math.Pow(Pasos, 2))];
			int cont = 0;
			int contc = 0;
			double Radio = 1;


			for (int i = 0; i <= Pasos - 1; i++) {
				Caras[i] = new Cara(3);
			}
			for (int i = Pasos; i <= (Math.Pow(Pasos, 2)) - Pasos - 1; i++) {
				Caras[i] = new Cara(4);
			}
			for (int i = (Math.Pow(Pasos, 2)) - Pasos; i <= (Math.Pow(Pasos, 2)) - 1; i++) {
				Caras[i] = new Cara(3);
			}

			cont = 1;
			contc = 0;

			Vertices[0] = new Vertice(new Punto3D(0, 0, 1));
			Vertices[Vertices.GetUpperBound(0)] = new Vertice(new Punto3D(0, 0, -1));

			for (double a = 0; a <= Math.PI; a += Math.PI / (Pasos / 1)) {
				if (a == 0 | a == Math.PI)
					continue;
				Radio = Math.Sin(a);
				for (double b = 0; b <= 2 * Math.PI; b += Math.PI / (Pasos / 2)) {
					if (b == 2 * Math.PI)
						continue;
					Vertices[cont] = new Vertice(new Punto3D(Radio * Math.Cos(b), Radio * Math.Sin(b), Math.Cos(a)));

					if (cont == Vertices.GetUpperBound(0))
						break; // TODO: might not be correct. Was : Exit For
					cont += 1;
				}
				if (cont == (Math.Pow(Pasos, 2)) - 1)
					break; // TODO: might not be correct. Was : Exit For
			}

			cont = 1;
			for (int i = 0; i <= Pasos - 1; i++) {
				Caras[i].Vertices[0] = 0;
				Caras[i].Vertices[1] = (cont + 1 <= Pasos - 0 ? cont + 1 : 1);
				Caras[i].Vertices[2] = cont;
				if (cont == Pasos)
					break; // TODO: might not be correct. Was : Exit For
				cont += 1;
			}

			cont = Vertices.GetUpperBound(0) - Pasos - 1;
			for (int i = Caras.GetUpperBound(0) - Pasos; i <= Caras.GetUpperBound(0); i++) {
				Caras[i].Vertices[0] = cont;
				Caras[i].Vertices[1] = (cont + 1 < Vertices.GetUpperBound(0) - 1 ? cont + 1 : Vertices.GetUpperBound(0) - Pasos - 1);
				Caras[i].Vertices[2] = Vertices.GetUpperBound(0);
				if (cont == Vertices.GetUpperBound(0) - 1)
					break; // TODO: might not be correct. Was : Exit For
				cont += 1;
			}

			for (int i = 1; i <= Pasos - 2; i++) {
				for (int j = 0; j <= Pasos - 1; j++) {
					Caras[(i * Pasos) + j].Vertices[0] = ((i - 1) * Pasos) + j + 1;
					Caras[(i * Pasos) + j].Vertices[1] = (j + 1 <= Pasos - 1 ? ((i - 1) * Pasos) + j + 2 : ((i - 1) * Pasos) + 1);
					Caras[(i * Pasos) + j].Vertices[2] = (j + 1 <= Pasos - 1 ? ((i) * Pasos) + j + 2 : ((i) * Pasos) + 1);
					Caras[(i * Pasos) + j].Vertices[3] = ((i) * Pasos) + j + 1;
				}
			}

			return new Poliedro(Vertices, Caras);
		}
Example #51
0
            public Vertice Intersect(Vertice p1, Vertice p2)
            {
                Vertice p = new Vertice(0, 0, 0);
                double vp1, vp2, vp3, n1, n2, n3, v1, v2, v3, m1, m2, m3, t, vpt;
                vp1 = this.A; vp2 = this.B; vp3 = this.C;
                n1 = 0; n2 = 0; n3 = -1 * D / C;
                v1 = p2.X - p1.X; v2 = p2.Y - p1.Y; v3 = p2.Z - p1.Z;
                m1 = p1.X; m2 = p1.Y; m3 = p1.Z;
                vpt = v1 * vp1 + v2 * vp2 + v3 * vp3;
                //首先判断直线是否与平面平行
                if (vpt == 0)
                {
                    p = null;
                }
                else
                {
                    t = ((n1 - m1) * vp1 + (n2 - m2) * vp2 + (n3 - m3) * vp3) / vpt;
                    p.X = m1 + v1 * t;
                    p.Y = m2 + v2 * t;
                    p.Z = m3 + v3 * t;

                    Console.WriteLine("==交点==");
                    Console.WriteLine(string.Format("{0},{1},{2}  ---  {3},{4},{5}", p1.X, p1.Y, p1.Z, p2.X, p2.Y, p2.Z));
                    Console.WriteLine(string.Format("{0},{1},{2}",p.X,p.Y,p.Z));
                    Console.WriteLine("========");
                }

                return p;
            }
Example #52
0
 public bool isBelowMe(Vertice vP)
 {
     if (A * vP.X + B * vP.Y + C * vP.Z + D <= 0)
         return true;
     else
         return false;
 }
Example #53
0
    // Update is called once per frame
    void FixedUpdate()
    {
        if (segments < 2)
        {
            segments = 2;
        }
        inc = angle / (segments - 1);
        float rot_euler_z = transform.rotation.eulerAngles.z;
        Vertex.Clear();
        Vertice pivot_vertice = new Vertice();
        pivot_vertice.angle = 0;
        pivot_vertice.pos = Vector3.zero;
        Vertex.Add(pivot_vertice);
        int layer_mask = ~LayerMask.GetMask("LumColl");
        for (float i = 0; i <= angle; i += inc)
        {

            Vertice new_vertice = new Vertice();
            float pos_x = distance * Mathf.Cos(Mathf.Deg2Rad * (i + rot_euler_z));
            float pos_y = distance * Mathf.Sin(Mathf.Deg2Rad * (i + rot_euler_z));
            Vector3 point = new Vector3(pos_x, pos_y, 0);
            RaycastHit2D hit = Physics2D.Raycast(transform.position, point - transform.position, distance, layer_mask);
            if (hit)
            {
                if (hit.collider.GetType() == typeof(BoxCollider2D))
                {
                    new_vertice.pos = hit.point;
                    Vector2[] points = GetBoxCollider2DPoints((BoxCollider2D)hit.collider);
                    //Vertice new_sub_vertice = new Vertice();
                    List<Vertice> Vert = new List<Vertice>();
                    for (int j = 0; j < points.Length; j++)
                    {
                        RaycastHit2D sub_hit = Physics2D.Raycast(transform.position, points[j] - (Vector2)transform.position);
                        if (sub_hit.collider && approxHit(points[j], sub_hit.point))
                        {
                            Vertice new_sub_vertice = new Vertice();
                            new_sub_vertice.pos = sub_hit.point;
                            new_sub_vertice.angle = Mathf.Atan2(sub_hit.point.y, sub_hit.point.x);
                            Debug.DrawLine(transform.position, new_sub_vertice.pos, Color.green);
                            new_sub_vertice.pos = transform.InverseTransformPoint(new_sub_vertice.pos);
                            Vert.Add(new_sub_vertice);
                        }
                    }
                    SortVertex(Vert);
                    float last_angle = Vert[Vert.Count - 1].angle * Mathf.Rad2Deg;
                    float sub_pos_x = (distance) * Mathf.Cos(Vert[0].angle);
                    float sub_pos_y = (distance) * Mathf.Sin(Vert[0].angle);
                    Vector3 sub_point = new Vector3(sub_pos_x, sub_pos_y, 0);
                    Debug.DrawLine(Vert[0].pos, sub_point, Color.yellow);
                    sub_pos_x = (distance) * Mathf.Cos(Vert[Vert.Count - 1].angle);
                    sub_pos_y = (distance) * Mathf.Sin(Vert[Vert.Count - 1].angle);
                    sub_point = new Vector3(sub_pos_x, sub_pos_y, 0);
                    Debug.DrawLine(Vert[Vert.Count - 1].pos, sub_point, Color.red);
                    Vertex.AddRange(Vert);
                    print(last_angle);
                    while (i <= angle && i < last_angle)
                    {
                        i += inc;
                    }
                }
                else if (hit.collider.GetType() == typeof(PolygonCollider2D))
                {
                    new_vertice.pos = point;
                    Vector2[] points = GetPolygonCollider2DPoints((PolygonCollider2D)hit.collider);
                    List<Vertice> Vert = new List<Vertice>();
                    for (int j = 0; j < points.Length; j++)
                    {
                        RaycastHit2D sub_hit = Physics2D.Raycast(transform.position, points[j] - (Vector2)transform.position);
                        if (sub_hit.collider && approxHit(points[j], sub_hit.point))
                        {
                            Vertice new_sub_vertice = new Vertice();
                            new_sub_vertice.pos = sub_hit.point;
                            new_sub_vertice.angle = Mathf.Atan2(sub_hit.point.y, sub_hit.point.x);
                            Debug.DrawLine(transform.position, new_sub_vertice.pos, Color.green);
                            new_sub_vertice.pos = transform.InverseTransformPoint(new_sub_vertice.pos);
                            Vert.Add(new_sub_vertice);
                        }
                    }
                    SortVertex(Vert);
                    float last_angle = Vert[Vert.Count - 1].angle * Mathf.Rad2Deg;
                    float sub_pos_x = (distance) * Mathf.Cos(Vert[0].angle);
                    float sub_pos_y = (distance) * Mathf.Sin(Vert[0].angle);
                    Vector3 sub_point = new Vector3(sub_pos_x, sub_pos_y, 0);
                    Debug.DrawLine(Vert[0].pos, sub_point, Color.yellow);
                    sub_pos_x = (distance) * Mathf.Cos(Vert[Vert.Count - 1].angle);
                    sub_pos_y = (distance) * Mathf.Sin(Vert[Vert.Count - 1].angle);
                    sub_point = new Vector3(sub_pos_x, sub_pos_y, 0);
                    Debug.DrawLine(Vert[Vert.Count - 1].pos, sub_point, Color.red);
                    Vertex.AddRange(Vert);
                    print(last_angle);
                    while (i <= angle && i < last_angle)
                    {
                        i += inc;
                    }
                }
            }
            else {
                new_vertice.pos = transform.TransformPoint(point);
                Debug.DrawLine(transform.position, new_vertice.pos, Color.blue);
                new_vertice.pos = transform.InverseTransformPoint(new_vertice.pos);
                Vertex.Add(new_vertice);
            }
        }
        total_points = Vertex.Count;
        //SortVertex(Vertex);
        print(Vertex.Count);
        CreateMesh(ListToArray());
    }