elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Como proteger una cartera - billetera de Bitcoin


  Mostrar Mensajes
Páginas: 1 [2] 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 ... 238
11  Programación / Ingeniería Inversa / Re: InnoExtractor, novedosa aplicación para desempaquetar instaladores de Inno Setup en: 13 Diciembre 2018, 04:40 am
Es increíble que después de 5 años y medio aún sigas actualizando el tema. Wow.
12  Programación / .NET (C#, VB.NET, ASP) / Re: Librería de códigos C# (Compartan aquí sus códigos) en: 12 Diciembre 2018, 02:47 am
Rasterizar un triangulo cualquiera

Hoy estoy felis, ya que he conseguido rasterizar un triangulo. Y me diréis pues muy bien no? Vale, os explico.

Rasterizar es esto. Es decir, pintar por pantalla los pixeles que conforman un poligono cualquiera. Bueno sí... Pero lo que no os he dicho que un poligono cualquiera se puede triangular, es decir, como en el post anterior al igual que con Ramer-Douglas-Pecker puedes conseguir el minimo de puntos que definen un poligono cualquiera, con triangulación consigues algo parecido, ya que si lo pensamos, un triangulo es la minima expresión de poligono, es decir, el poligono con menos vertices y que de sumas de ellos podemos definir los demas.

Si queréis conseguir una buena triangulación os recomiendo LibTessDotNet. Funciona muy bien.

Esto es muy potente ya que puedes mostrar por pantalla (aunque para esto ya está DirectX y OpenGL, internamente, esto que comento es un trabajo que la GPU hace muy bien ya que se trata de repetir), hacer procesos más complejos (que es por lo que fundamental lo necesito yo) o bien hacer librerías de pago de rasterización para Unity :xD.

Así que aquí os dejo mi buena *****:

Código
  1. using System;
  2. using UnityEngine;
  3.  
  4. namespace UnityEngine.Utilities.Drawing
  5. {
  6.    // Uncomment this if you don't a an own implementation
  7.    /*public struct Point
  8.     {
  9.         public int x;
  10.         public int y;
  11.  
  12.         public Point(int x, int y)
  13.         {
  14.             this.x = 0;
  15.             this.y = 0;
  16.         }
  17.     }*/
  18.  
  19.    public static class TriangleUtils
  20.    {
  21.        public static void Rasterize(Point pt1, Point pt2, Point pt3, Action<int, int> action, bool debug = false)
  22.        {
  23.            /*
  24.                  // https://www.geeksforgeeks.org/check-whether-triangle-valid-not-sides-given/
  25.                  a + b > c
  26.                  a + c > b
  27.                  b + c > a
  28.              */
  29.  
  30.            if (!CheckIfValidTriangle(pt1, pt2, pt3, debug))
  31.                return;
  32.  
  33.            if (TriangleArea(pt1, pt2, pt3) <= 1)
  34.            {
  35.                Point center = GetTriangleCenter(pt1, pt2, pt3);
  36.                action?.Invoke(center.x, center.y);
  37.  
  38.                return;
  39.            }
  40.  
  41.            Point tmp;
  42.  
  43.            if (pt2.x < pt1.x)
  44.            {
  45.                tmp = pt1;
  46.                pt1 = pt2;
  47.                pt2 = tmp;
  48.            }
  49.  
  50.            if (pt3.x < pt2.x)
  51.            {
  52.                tmp = pt2;
  53.                pt2 = pt3;
  54.                pt3 = tmp;
  55.  
  56.                if (pt2.x < pt1.x)
  57.                {
  58.                    tmp = pt1;
  59.                    pt1 = pt2;
  60.                    pt2 = tmp;
  61.                }
  62.            }
  63.  
  64.            var baseFunc = CreateFunc(pt1, pt3);
  65.            var line1Func = pt1.x == pt2.x ? (x => pt2.y) : CreateFunc(pt1, pt2);
  66.  
  67.            for (var x = pt1.x; x < pt2.x; ++x)
  68.            {
  69.                int maxY;
  70.                int minY = GetRange(line1Func(x), baseFunc(x), out maxY);
  71.  
  72.                for (int y = minY; y <= maxY; ++y)
  73.                    action?.Invoke(x, y);
  74.            }
  75.  
  76.            var line2Func = pt2.x == pt3.x ? (x => pt2.y) : CreateFunc(pt2, pt3);
  77.  
  78.            for (var x = pt2.x; x <= pt3.x; ++x)
  79.            {
  80.                int maxY;
  81.                int minY = GetRange(line2Func(x), baseFunc(x), out maxY);
  82.  
  83.                for (int y = minY; y <= maxY; ++y)
  84.                    action?.Invoke(x, y);
  85.            }
  86.        }
  87.  
  88.        private static int GetRange(float y1, float y2, out int maxY)
  89.        {
  90.            if (y1 < y2)
  91.            {
  92.                maxY = Mathf.FloorToInt(y2);
  93.                return Mathf.CeilToInt(y1);
  94.            }
  95.  
  96.            maxY = Mathf.FloorToInt(y1);
  97.            return Mathf.CeilToInt(y2);
  98.        }
  99.  
  100.        private static Func<int, float> CreateFunc(Point pt1, Point pt2)
  101.        {
  102.            var y0 = pt1.y;
  103.  
  104.            if (y0 == pt2.y)
  105.                return x => y0;
  106.  
  107.            float m = (float)(pt2.y - y0) / (pt2.x - pt1.x);
  108.  
  109.            return x => m * (x - pt1.x) + y0;
  110.        }
  111.  
  112.        public static void RasterizeStandard(Point p1, Point p2, Point p3, Action<int, int> action, bool debug = false)
  113.        {
  114.            // Thanks to: https://www.davrous.com/2013/06/21/tutorial-part-4-learning-how-to-write-a-3d-software-engine-in-c-ts-or-js-rasterization-z-buffering/
  115.  
  116.            if (!CheckIfValidTriangle(p1, p2, p3, debug))
  117.                return;
  118.  
  119.            // Sorting the points in order to always have this order on screen p1, p2 & p3
  120.            // with p1 always up (thus having the y the lowest possible to be near the top screen)
  121.            // then p2 between p1 & p3
  122.            if (p1.y > p2.y)
  123.            {
  124.                var temp = p2;
  125.                p2 = p1;
  126.                p1 = temp;
  127.            }
  128.  
  129.            if (p2.y > p3.y)
  130.            {
  131.                var temp = p2;
  132.                p2 = p3;
  133.                p3 = temp;
  134.            }
  135.  
  136.            if (p1.y > p2.y)
  137.            {
  138.                var temp = p2;
  139.                p2 = p1;
  140.                p1 = temp;
  141.            }
  142.  
  143.            // inverse slopes
  144.            float dP1P2, dP1P3;
  145.  
  146.            // http://en.wikipedia.org/wiki/Slope
  147.            // Computing inverse slopes
  148.            if (p2.y - p1.y > 0)
  149.                dP1P2 = (p2.x - p1.x) / (p2.y - p1.y);
  150.            else
  151.                dP1P2 = 0;
  152.  
  153.            if (p3.y - p1.y > 0)
  154.                dP1P3 = (p3.x - p1.x) / (p3.y - p1.y);
  155.            else
  156.                dP1P3 = 0;
  157.  
  158.            // First case where triangles are like that:
  159.            // P1
  160.            // -
  161.            // --
  162.            // - -
  163.            // -  -
  164.            // -   - P2
  165.            // -  -
  166.            // - -
  167.            // -
  168.            // P3
  169.            if (dP1P2 > dP1P3)
  170.            {
  171.                for (var y = p1.y; y <= p3.y; y++)
  172.                {
  173.                    if (y < p2.y)
  174.                        ProcessScanLine(y, p1, p3, p1, p2, action);
  175.                    else
  176.                        ProcessScanLine(y, p1, p3, p2, p3, action);
  177.                }
  178.            }
  179.            // First case where triangles are like that:
  180.            //       P1
  181.            //        -
  182.            //       --
  183.            //      - -
  184.            //     -  -
  185.            // P2 -   -
  186.            //     -  -
  187.            //      - -
  188.            //        -
  189.            //       P3
  190.            else
  191.            {
  192.                for (var y = p1.y; y <= p3.y; y++)
  193.                {
  194.                    if (y < p2.y)
  195.                        ProcessScanLine(y, p1, p2, p1, p3, action);
  196.                    else
  197.                        ProcessScanLine(y, p2, p3, p1, p3, action);
  198.                }
  199.            }
  200.        }
  201.  
  202.        // drawing line between 2 points from left to right
  203.        // papb -> pcpd
  204.        // pa, pb, pc, pd must then be sorted before
  205.        private static void ProcessScanLine(int y, Point pa, Point pb, Point pc, Point pd, Action<int, int> action)
  206.        {
  207.            // Thanks to current y, we can compute the gradient to compute others values like
  208.            // the starting x (sx) and ending x (ex) to draw between
  209.            // if pa.y == pb.y or pc.y == pd.y, gradient is forced to 1
  210.            var gradient1 = pa.y != pb.y ? (y - pa.y) / (pb.y - pa.y) : 1;
  211.            var gradient2 = pc.y != pd.y ? (y - pc.y) / (pd.y - pc.y) : 1;
  212.  
  213.            int sx = (int)Mathf.Lerp(pa.x, pb.x, gradient1);
  214.            int ex = (int)Mathf.Lerp(pc.x, pd.x, gradient2);
  215.  
  216.            // drawing a line from left (sx) to right (ex)
  217.            for (var x = sx; x < ex; x++)
  218.                action?.Invoke(x, y);
  219.        }
  220.  
  221.        public static void RasterizeBarycentric(Point v1, Point v2, Point v3, Action<int, int> action, bool debug = false)
  222.        {
  223.            // Thanks to: http://www.sunshine2k.de/coding/java/TriangleRasterization/TriangleRasterization.html#algo3 && https://www.cs.unm.edu/~joel/cs491_VR/src/DrawUtilities.cs
  224.  
  225.            /* checks for a valid triangle */
  226.  
  227.            if (!CheckIfValidTriangle(v1, v2, v3, debug))
  228.                return;
  229.  
  230.            /* get the bounding box of the triangle */
  231.            int maxX = Mathf.Max(v1.x, Mathf.Max(v2.x, v3.x));
  232.            int minX = Mathf.Min(v1.x, Mathf.Min(v2.x, v3.x));
  233.            int maxY = Mathf.Max(v1.y, Mathf.Max(v2.y, v3.y));
  234.            int minY = Mathf.Min(v1.y, Mathf.Min(v2.y, v3.y));
  235.  
  236.            //if (debug)
  237.            //    Debug.Log($"({minX}, {minY}, {maxX}, {maxY})");
  238.  
  239.            /* spanning vectors of edge (v1,v2) and (v1,v3) */
  240.            Point vs1 = new Point(v2.x - v1.x, v2.y - v1.y);
  241.            Point vs2 = new Point(v3.x - v1.x, v3.y - v1.y);
  242.  
  243.            for (int x = minX; x <= maxX; x++)
  244.            {
  245.                for (int y = minY; y <= maxY; y++)
  246.                {
  247.                    Point q = new Point(x - v1.x, y - v1.y);
  248.  
  249.                    float s = Vector2.Dot(q, vs2) / Vector2.Dot(vs1, vs2);
  250.                    float t = Vector2.Dot(vs1, q) / Vector2.Dot(vs1, vs2);
  251.  
  252.                    if ((s >= 0) && (t >= 0) && (s + t <= 1))
  253.                    { /* inside triangle */
  254.                        action?.Invoke(x, y);
  255.                    }
  256.                }
  257.            }
  258.        }
  259.  
  260.        public static void RasterizeBresenham(Point vt1, Point vt2, Point vt3, Action<int, int> action, bool debugException = false)
  261.        {
  262.            // Thanks to: http://www.sunshine2k.de/coding/java/TriangleRasterization/TriangleRasterization.html#algo3 && https://www.cs.unm.edu/~joel/cs491_VR/src/DrawUtilities.cs
  263.  
  264.            /* checks for a valid triangle */
  265.  
  266.            if (!CheckIfValidTriangle(vt1, vt2, vt3, debugException))
  267.                return;
  268.  
  269.            string invalidTriangle = $"The given points must form a triangle. {{{vt1}, {vt2}, {vt3}}}";
  270.  
  271.            /* at first sort the three vertices by y-coordinate ascending so v1 is the topmost vertice */
  272.            sortVerticesAscendingByY(ref vt1, ref vt2, ref vt3);
  273.  
  274.            /* here we know that v1.y <= v2.y <= v3.y */
  275.            /* check for trivial case of bottom-flat triangle */
  276.            if (vt2.y == vt3.y)
  277.            {
  278.                if (!fillBottomFlatTriangle(vt1, vt2, vt3, action, debugException))
  279.                {
  280.                    if (debugException)
  281.                        Debug.LogWarning(invalidTriangle);
  282.  
  283.                    return;
  284.                }
  285.            }
  286.            /* check for trivial case of top-flat triangle */
  287.            else if (vt1.y == vt2.y)
  288.            {
  289.                if (!fillTopFlatTriangle(vt1, vt2, vt3, action, debugException))
  290.                {
  291.                    if (debugException)
  292.                        Debug.LogWarning(invalidTriangle);
  293.  
  294.                    return;
  295.                }
  296.            }
  297.            else
  298.            {
  299.                /* general case - split the triangle in a topflat and bottom-flat one */
  300.                Point v4 = new Point((int)(vt1.x + (vt2.y - vt1.y) / (float)(vt3.y - vt1.y) * (vt3.x - vt1.x)), vt2.y);
  301.  
  302.                if (!fillBottomFlatTriangle(vt1, vt2, v4, action, debugException) || !fillTopFlatTriangle(vt2, v4, vt3, action, debugException))
  303.                {
  304.                    if (debugException)
  305.                        Debug.LogWarning(invalidTriangle);
  306.  
  307.                    return;
  308.                }
  309.            }
  310.        }
  311.  
  312.        public static bool CheckIfValidTriangle(Point v1, Point v2, Point v3, bool debug = false)
  313.        {
  314.            /*
  315.                 // https://www.geeksforgeeks.org/check-whether-triangle-valid-not-sides-given/
  316.                 a + b > c
  317.                 a + c > b
  318.                 b + c > a
  319.             */
  320.  
  321.            float a = Vector2.Distance(new Vector2(v1.x, v1.y), new Vector2(v2.x, v2.y)),
  322.                  b = Vector2.Distance(new Vector2(v2.x, v2.y), new Vector2(v3.x, v3.y)),
  323.                  c = Vector2.Distance(new Vector2(v3.x, v3.y), new Vector2(v1.x, v1.y));
  324.  
  325.            if (a + b <= c || a + c <= b || b + c <= a)
  326.            {
  327.                if (debug)
  328.                    Debug.LogWarning($"The given points must form a triangle. {{{v1}, {v2}, {v3}}}");
  329.  
  330.                return false;
  331.            }
  332.  
  333.            return true;
  334.        }
  335.  
  336.        public static bool CheckIfValidTriangle(Point v1, Point v2, Point v3, out float a, out float b, out float c)
  337.        {
  338.            a = Vector2.Distance(new Vector2(v1.x, v1.y), new Vector2(v2.x, v2.y));
  339.            b = Vector2.Distance(new Vector2(v2.x, v2.y), new Vector2(v3.x, v3.y));
  340.            c = Vector2.Distance(new Vector2(v3.x, v3.y), new Vector2(v1.x, v1.y));
  341.  
  342.            if (a + b <= c || a + c <= b || b + c <= a)
  343.            {
  344.                // Debug.LogWarning($"The given points must form a triangle. {{{v1}, {v2}, {v3}}}");
  345.                return false;
  346.            }
  347.  
  348.            return true;
  349.        }
  350.  
  351.        private static bool fillBottomFlatTriangle(Point v1, Point v2, Point v3, Action<int, int> action, bool debugException = false)
  352.        {
  353.            try
  354.            {
  355.                float invslope1 = (v2.x - v1.x) / (v2.y - v1.y);
  356.                float invslope2 = (v3.x - v1.x) / (v3.y - v1.y);
  357.  
  358.                float curx1 = v1.x;
  359.                float curx2 = v1.x;
  360.  
  361.                for (int scanlineY = v1.y; scanlineY <= v2.y; scanlineY++)
  362.                {
  363.                    DrawLine((int)curx1, scanlineY, (int)curx2, scanlineY, action);
  364.  
  365.                    curx1 += invslope1;
  366.                    curx2 += invslope2;
  367.                }
  368.            }
  369.            catch (Exception ex)
  370.            {
  371.                if (debugException)
  372.                    Debug.LogException(ex);
  373.  
  374.                return false;
  375.            }
  376.  
  377.            return true;
  378.        }
  379.  
  380.        private static bool fillTopFlatTriangle(Point v1, Point v2, Point v3, Action<int, int> action, bool debugException = false)
  381.        {
  382.            try
  383.            {
  384.                float invslope1 = (v3.x - v1.x) / (v3.y - v1.y);
  385.                float invslope2 = (v3.x - v2.x) / (v3.y - v2.y);
  386.  
  387.                float curx1 = v3.x;
  388.                float curx2 = v3.x;
  389.  
  390.                for (int scanlineY = v3.y; scanlineY > v1.y; scanlineY--)
  391.                {
  392.                    DrawLine((int)curx1, scanlineY, (int)curx2, scanlineY, action);
  393.                    curx1 -= invslope1;
  394.                    curx2 -= invslope2;
  395.                }
  396.            }
  397.            catch (Exception ex)
  398.            {
  399.                if (debugException)
  400.                    Debug.LogException(ex);
  401.  
  402.                return false;
  403.            }
  404.  
  405.            return true;
  406.        }
  407.  
  408.        private static void sortVerticesAscendingByY(ref Point v0, ref Point v1, ref Point v2)
  409.        {
  410.            if (v2.y < v1.y)
  411.                Swap(ref v1, ref v2);
  412.  
  413.            if (v1.y < v0.y)
  414.                Swap(ref v0, ref v1);
  415.  
  416.            if (v2.y < v1.y)
  417.                Swap(ref v1, ref v2);
  418.        }
  419.  
  420.        private static void Swap<T>(ref T lhs, ref T rhs)
  421.        {
  422.            (lhs, rhs) = (rhs, lhs);
  423.  
  424.            // Impl for versions lower than C# 7
  425.  
  426.            //T temp;
  427.            //temp = lhs;
  428.            //lhs = rhs;
  429.            //rhs = temp;
  430.        }
  431.  
  432.        public static float TriangleArea(Point p1, Point p2, Point p3)
  433.        {
  434.            float a, b, c;
  435.  
  436.            if (!CheckIfValidTriangle(p1, p2, p3, out a, out b, out c))
  437.                return 0;
  438.  
  439.            return TriangleArea(a, b, c);
  440.        }
  441.  
  442.        public static float TriangleArea(float a, float b, float c)
  443.        {
  444.            // Thanks to: http://james-ramsden.com/area-of-a-triangle-in-3d-c-code/
  445.  
  446.            float s = (a + b + c) / 2.0f;
  447.            return Mathf.Sqrt(s * (s - a) * (s - b) * (s - c));
  448.        }
  449.  
  450.        // Bresenham impl: https://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm
  451.  
  452.        public static void DrawLine(Vector2 p1, Vector2 p2, Action<int, int> action)
  453.        {
  454.            DrawLine((int)p1.x, (int)p1.y, (int)p2.x, (int)p2.y, action);
  455.        }
  456.  
  457.        public static void DrawLine(int x0, int y0, int x1, int y1, Action<int, int> action)
  458.        {
  459.            int sx = 0,
  460.                sy = 0;
  461.  
  462.            int dx = Mathf.Abs(x1 - x0),
  463.                dy = Mathf.Abs(y1 - y0);
  464.  
  465.            if (x0 < x1) { sx = 1; } else { sx = -1; }
  466.            if (y0 < y1) { sy = 1; } else { sy = -1; }
  467.  
  468.            int err = dx - dy,
  469.                e2 = 0;
  470.  
  471.            while (true)
  472.            {
  473.                //colors[P(x0 % width, y0 % height, width, height)] = x0 / width >= 1 || y0 / height >= 1 ? UnityEngine.Color.yellow : c;
  474.                action?.Invoke(x0, y0);
  475.  
  476.                if ((x0 == x1) && (y0 == y1))
  477.                    break;
  478.  
  479.                e2 = 2 * err;
  480.  
  481.                if (e2 > -dy)
  482.                {
  483.                    err = err - dy;
  484.                    x0 = x0 + sx;
  485.                }
  486.                if (e2 < dx)
  487.                {
  488.                    err = err + dx;
  489.                    y0 = y0 + sy;
  490.                }
  491.            }
  492.        }
  493.  
  494.        public static Point GetTriangleCenter(Point p0, Point p1, Point p2)
  495.        {
  496.            // Thanks to: https://stackoverflow.com/questions/524755/finding-center-of-2d-triangle
  497.  
  498.            return new Point(p0.x + p1.x + p2.x / 3, p0.y + p1.y + p2.y / 3);
  499.        }
  500.    }
  501. }

Gist: https://gist.github.com/z3nth10n/7d60f22c7e906f645d53c9622507c23b (dadle una estrellica, no me seais gitanos :laugh: :laugh:)

Vídeo de ejemplo:



Un saludo.
13  Foros Generales / Foro Libre / Re: Marihuana en el espacio en: 8 Diciembre 2018, 23:56 pm
Las semillas vienen de la tierra que hay es donde germinan... :silbar:

Pues es gracioso que la historia se repita, no tenia ni idea. De hecho, la noticia no es tan novedosa, es de febrero de 2016, pero vaya... Que no me deja de impactar :laugh: :laugh:

14  Foros Generales / Foro Libre / Re: Marihuana en el espacio en: 8 Diciembre 2018, 20:29 pm
PD: He colocado la noticia porque sé que a algunos les gustan éstas cosas...  ;D

Ese guiño dice muchas cosas :rolleyes: :xD :xD :xD

Muy interesante la verdad.... Como dice Machacador a saber si no son pruebas contaminadas...

De no ser así, pues ya solo faltaría encontrar algunas otros compuestos como CBD y/o otras drogas... (Empezando por el alcohol)

Si encuentran el THC asilado sin CBD yo daría por presupuesto que no son pruebas contaminadas, pero a saber ;-)
15  Programación / Programación General / Re: Ayuda con nomenclatura para función geométrica en: 5 Diciembre 2018, 19:55 pm
Yo lo llamaría SquareSimilarityPercentage o algo así :P
16  Programación / Programación General / Re: Algun forero de buena fe que me lo pueda pasar a python3 en: 3 Diciembre 2018, 21:13 pm
No lo he probado, pero quizás te venga bien: https://pypi.org/project/java2python/
17  Programación / Desarrollo Web / Re: [Pregunta]: Options no se desplazan correctamente en: 30 Noviembre 2018, 14:28 pm
Te puedo ayudar, pero realmente, se me hace muy espeso el tema (ya que no tengo como probar por mi cuenta lo que realmente está ocurriendo)

Mejor, sube todo tu codigo aquí:

https://jsfiddle.net/

Intenta representar con la mayor fidelidad posible el problema.

Y a ver. :P
18  Foros Generales / Foro Libre / Re: Algo raro está ocurriendo... en: 30 Noviembre 2018, 14:25 pm
Pues yo es la primera vez que no lo veo oculto :xD
19  Foros Generales / Foro Libre / Algo raro está ocurriendo... en: 30 Noviembre 2018, 14:06 pm


Quizás no se den cuenta, pero el easteregg empieza por w y acaba por n. :silbar:

Me da curiosidad saber porque razón ya no está en oculto su conexión. :silbar: :silbar:
20  Programación / Desarrollo Web / Re: [Pregunta]: Options no se desplazan correctamente en: 29 Noviembre 2018, 21:56 pm
Pero muchacho, edita el trochimoche de arriba, y dile a algun mod que te edite dos doble posts. Si no, andamos en las mismas.

Así es imposible responderte bien.

Solo faltaría que llegase alguien y te citase la respuesta :xD (10 veces por lo menos)
Páginas: 1 [2] 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 ... 238
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines